void MapOverlayBitmap::Draw(Canvas &canvas, const WindowProjection &projection) noexcept { if (!simple_bounds.Overlaps(projection.GetScreenBounds())) /* not visible, outside of screen area */ return; const RasterPoint vertices[] = { projection.GeoToScreen(bounds.top_left), projection.GeoToScreen(bounds.top_right), projection.GeoToScreen(bounds.bottom_left), projection.GeoToScreen(bounds.bottom_right), }; const ScopeVertexPointer vp(vertices); GLTexture &texture = *bitmap.GetNative(); texture.Bind(); const PixelSize allocated = texture.GetAllocatedSize(); const unsigned src_x = 0, src_y = 0; const unsigned src_width = texture.GetWidth(); const unsigned src_height = texture.GetHeight(); GLfloat x0 = (GLfloat)src_x / allocated.cx; GLfloat y0 = (GLfloat)src_y / allocated.cy; GLfloat x1 = (GLfloat)(src_x + src_width) / allocated.cx; GLfloat y1 = (GLfloat)(src_y + src_height) / allocated.cy; if (bitmap.IsFlipped()) { y0 = 1 - y0; y1 = 1 - y1; } const Point2D<GLfloat> coord[] = { {x0, y0}, {x1, y0}, {x0, y1}, {x1, y1}, }; const ScopeTextureConstantAlpha blend(alpha); #ifdef USE_GLSL OpenGL::texture_shader->Use(); glEnableVertexAttribArray(OpenGL::Attribute::TEXCOORD); glVertexAttribPointer(OpenGL::Attribute::TEXCOORD, 2, GL_FLOAT, GL_FALSE, 0, coord); #else const GLEnable<GL_TEXTURE_2D> scope; glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, coord); #endif glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); #ifdef USE_GLSL glDisableVertexAttribArray(OpenGL::Attribute::TEXCOORD); OpenGL::solid_shader->Use(); #else glDisableClientState(GL_TEXTURE_COORD_ARRAY); #endif }
static void mask_draw_curve_type(const bContext *C, MaskSpline *spline, float (*orig_points)[2], int tot_point, const bool is_feather, const bool is_smooth, const bool is_active, const unsigned char rgb_spline[4], const char draw_type) { const int draw_method = (spline->flag & MASK_SPLINE_CYCLIC) ? GL_LINE_LOOP : GL_LINE_STRIP; const unsigned char rgb_black[4] = {0x00, 0x00, 0x00, 0xff}; // const unsigned char rgb_white[4] = {0xff, 0xff, 0xff, 0xff}; unsigned char rgb_tmp[4]; SpaceClip *sc = CTX_wm_space_clip(C); float (*points)[2] = orig_points; if (sc) { int undistort = sc->clip && sc->user.render_flag & MCLIP_PROXY_RENDER_UNDISTORT; if (undistort) { int i; points = MEM_callocN(2 * tot_point * sizeof(float), "undistorthed mask curve"); for (i = 0; i < tot_point; i++) { mask_point_undistort_pos(sc, points[i], orig_points[i]); } } } glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, points); switch (draw_type) { case MASK_DT_OUTLINE: glLineWidth(3); mask_color_active_tint(rgb_tmp, rgb_black, is_active); glColor4ubv(rgb_tmp); glDrawArrays(draw_method, 0, tot_point); glLineWidth(1); mask_color_active_tint(rgb_tmp, rgb_spline, is_active); glColor4ubv(rgb_tmp); glDrawArrays(draw_method, 0, tot_point); break; case MASK_DT_DASH: default: glEnable(GL_LINE_STIPPLE); #ifdef USE_XOR glEnable(GL_COLOR_LOGIC_OP); glLogicOp(GL_OR); #endif mask_color_active_tint(rgb_tmp, rgb_spline, is_active); glColor4ubv(rgb_tmp); glLineStipple(3, 0xaaaa); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, points); glDrawArrays(draw_method, 0, tot_point); #ifdef USE_XOR glDisable(GL_COLOR_LOGIC_OP); #endif mask_color_active_tint(rgb_tmp, rgb_black, is_active); glColor4ubv(rgb_tmp); glLineStipple(3, 0x5555); glDrawArrays(draw_method, 0, tot_point); glDisable(GL_LINE_STIPPLE); break; case MASK_DT_BLACK: case MASK_DT_WHITE: if (draw_type == MASK_DT_BLACK) { rgb_tmp[0] = rgb_tmp[1] = rgb_tmp[2] = 0; } else { rgb_tmp[0] = rgb_tmp[1] = rgb_tmp[2] = 255; } /* alpha values seem too low but gl draws many points that compensate for it */ if (is_feather) { rgb_tmp[3] = 64; } else { rgb_tmp[3] = 128; } if (is_feather) { rgb_tmp[0] = (unsigned char)(((short)rgb_tmp[0] + (short)rgb_spline[0]) / 2); rgb_tmp[1] = (unsigned char)(((short)rgb_tmp[1] + (short)rgb_spline[1]) / 2); rgb_tmp[2] = (unsigned char)(((short)rgb_tmp[2] + (short)rgb_spline[2]) / 2); } if (is_smooth == FALSE && is_feather) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } mask_color_active_tint(rgb_tmp, rgb_tmp, is_active); glColor4ubv(rgb_tmp); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, points); glDrawArrays(draw_method, 0, tot_point); if (is_smooth == FALSE && is_feather) { glDisable(GL_BLEND); } break; } glDisableClientState(GL_VERTEX_ARRAY); if (points != orig_points) MEM_freeN(points); }
void VertexBuffer::DrawArrays(GLenum mode, GLint first, GLsizei count) { ProgramObject *p = rc->GetCurProgram(); if (p) p->updateMatrices(); glDrawArrays(mode, first, count); }
void ofGLRenderer::draw(ofPolyline & poly){ glVertexPointer(poly.is3D()?3:2, GL_FLOAT, sizeof(ofVec3f), &poly.getVertices()[0].x); glDrawArrays(poly.isClosed()?GL_LINE_LOOP:GL_LINE_STRIP, 0, poly.size());; }
void YuiSwapBuffers(void) { int buf_width, buf_height; int error; pthread_mutex_lock(&g_mtxGlLock); if( g_Display == EGL_NO_DISPLAY ) { pthread_mutex_unlock(&g_mtxGlLock); return; } if( eglMakeCurrent(g_Display,g_Surface,g_Surface,g_Context) == EGL_FALSE ) { printf( "eglMakeCurrent fail %04x",eglGetError()); pthread_mutex_unlock(&g_mtxGlLock); return; } glClearColor( 0.0f,0.0f,0.0f,1.0f); glClear(GL_COLOR_BUFFER_BIT); if( g_FrameBuffer == 0 ) { glEnable(GL_TEXTURE_2D); glGenTextures(1,&g_FrameBuffer); glBindTexture(GL_TEXTURE_2D, g_FrameBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); 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_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); error = glGetError(); if( error != GL_NO_ERROR ) { printf("gl error %d", error ); return; } }else{ glBindTexture(GL_TEXTURE_2D, g_FrameBuffer); } VIDCore->GetGlSize(&buf_width, &buf_height); glTexSubImage2D(GL_TEXTURE_2D, 0,0,0,buf_width,buf_height,GL_RGBA,GL_UNSIGNED_BYTE,dispbuffer); if( g_VertexBuffer == 0 ) { glGenBuffers(1, &g_VertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, g_VertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices),vertices,GL_STATIC_DRAW); error = glGetError(); if( error != GL_NO_ERROR ) { printf("gl error %d", error ); return; } }else{ glBindBuffer(GL_ARRAY_BUFFER, g_VertexBuffer); } if( buf_width != g_buf_width || buf_height != g_buf_height ) { vertices[6]=vertices[10]=(float)buf_width/1024.f; vertices[11]=vertices[15]=(float)buf_height/1024.f; glBufferData(GL_ARRAY_BUFFER, sizeof(vertices),vertices,GL_STATIC_DRAW); glVertexPointer(2, GL_FLOAT, sizeof(float)*4, 0); glTexCoordPointer(2, GL_FLOAT, sizeof(float)*4, (void*)(sizeof(float)*2)); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); g_buf_width = buf_width; g_buf_height = buf_height; } glDrawArrays(GL_TRIANGLE_FAN, 0, 4); eglSwapBuffers(g_Display,g_Surface); pthread_mutex_unlock(&g_mtxGlLock); }
int main() { // Initialize GLFW if (!glfwInit()) { std::cerr << "Failed to initialize GLFW!" << std::endl; return EXIT_FAILURE; } // Setup OpenGL context glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Try to create a window auto window = glfwCreateWindow( SIZE, SIZE, "OpenGL", NULL, NULL); if (window == NULL) { std::cerr << "Failed to open GLFW window, your graphics card is probably only capable of OpenGL 2.1" << std::endl; glfwTerminate(); return EXIT_FAILURE; } // Finalize window setup glfwMakeContextCurrent(window); // Initialize GLEW glewExperimental = GL_TRUE; glewInit(); if (!glewIsSupported("GL_VERSION_3_3")) { std::cerr << "Failed to initialize GLEW with OpenGL 3.3!" << std::endl; glfwTerminate(); return EXIT_FAILURE; } // Load shaders auto program_id = ShaderProgram("gl_projection.vert", "gl_projection.frag"); glUseProgram(program_id); InitializeGeometry(program_id); // Load and bind texture auto texture_id = LoadImage("lena.rgb", SIZE, SIZE); auto texture_attrib = glGetUniformLocation(program_id, "Texture"); glUniform1i(texture_attrib, 0); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, texture_id); InitializeProjection(program_id); // Time counter float time = 0; // Main execution loop while (!glfwWindowShouldClose(window)) { // Update model matrix (model rotation) UpdateModelMatrix(program_id, time++); // Set gray background glClearColor(.5f,.5f,.5f,0); // Clear depth and color buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw triangles using the program glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDrawArrays(GL_TRIANGLE_STRIP, 4, 4); // Display result glfwSwapBuffers(window); glfwPollEvents(); } // Clean up glfwTerminate(); return EXIT_SUCCESS; }
//-------------------------------------------------------------- // render the planet void Planet::render( int graphicsWidth, int graphicsHeight, double angle) { // if shader didn't compile, nothing we can do if (m_planetShader == 0) return; double atmos = 20.0; double radius = 1200.0; double eyeDist = m_eyePt.length()/radius; double a = 1.0; if (eyeDist < a) return; // below surface, nothing to do double b = sqrt(eyeDist*eyeDist - a*a); double h = (a*b)/eyeDist; double m = (a*a)/eyeDist; h += atmos/radius; // x axis from planet center towards eye mgPoint3 xaxis(m_eyePt); xaxis.normalize(); // build y axis mgPoint3 yaxis(xaxis); yaxis.cross(mgPoint3(0.0, 1.0, 0.0)); yaxis.normalize(); mgPoint3 zaxis(yaxis); zaxis.cross(xaxis); zaxis.normalize(); mgMatrix4 transform; transform._11 = xaxis.x; transform._12 = xaxis.y; transform._13 = xaxis.z; transform._21 = yaxis.x; transform._22 = yaxis.y; transform._23 = yaxis.z; transform._31 = zaxis.x; transform._32 = zaxis.y; transform._33 = zaxis.z; VertexPlanet tl, tr, bl, br; mgPoint3 pt; transform.mapPt(m, -h, h, pt.x, pt.y, pt.z); tl.setPoint(radius*pt.x, radius*pt.y, radius*pt.z); transform.mapPt(m, h, h, pt.x, pt.y, pt.z); tr.setPoint(radius*pt.x, radius*pt.y, radius*pt.z); transform.mapPt(m, -h, -h, pt.x, pt.y, pt.z); bl.setPoint(radius*pt.x, radius*pt.y, radius*pt.z); transform.mapPt(m, h, -h, pt.x, pt.y, pt.z); br.setPoint(radius*pt.x, radius*pt.y, radius*pt.z); // inverse of world transform mgMatrix4 model; model.rotateYDeg(-angle); mgPoint3 lightDir(1.0, 0.25, 0.0); lightDir.normalize(); mgPoint3 modelLightDir; model.mapPt(lightDir, modelLightDir); transform.multiply(model); mgPoint3 modelEye; transform.mapPt(eyeDist, 0.0, 0.0, modelEye.x, modelEye.y, modelEye.z); transform.mapPt(m, -h, h, pt.x, pt.y, pt.z); tl.setModelPoint(pt.x, pt.y, pt.z); transform.mapPt(m, h, h, pt.x, pt.y, pt.z); tr.setModelPoint(pt.x, pt.y, pt.z); transform.mapPt(m, -h, -h, pt.x, pt.y, pt.z); bl.setModelPoint(pt.x, pt.y, pt.z); transform.mapPt(m, h, -h, pt.x, pt.y, pt.z); br.setModelPoint(pt.x, pt.y, pt.z); mgMatrix4 viewMatrix; viewMatrix.translate(-m_eyePt.x, -m_eyePt.y, -m_eyePt.z); viewMatrix.multiply(m_eyeMatrix); mgMatrix4 worldProjection; createProjection(worldProjection, graphicsWidth, graphicsHeight); mgMatrix4 mvpMatrix(viewMatrix); mvpMatrix.multiply(worldProjection); setupShader(mvpMatrix, modelEye, modelLightDir); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, m_surfaceTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_CUBE_MAP, m_cloudsTexture); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPlanet), (const GLvoid*) offsetof(VertexPlanet, m_px)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPlanet), (const GLvoid*) offsetof(VertexPlanet, m_mx)); VertexPlanet data[6]; data[0] = tl; data[1] = tr; data[2] = bl; data[3] = bl; data[4] = tr; data[5] = br; int vertexSize = sizeof(VertexPlanet); int count = 6; glBufferData(GL_ARRAY_BUFFER, vertexSize * count, data, GL_DYNAMIC_DRAW); glDrawArrays(GL_TRIANGLES, 0, count); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glActiveTexture(GL_TEXTURE0); }
int main() { SetupOpenGL(); std::unique_ptr<btBroadphaseInterface> broadphase { new btDbvtBroadphase }; std::unique_ptr<btDefaultCollisionConfiguration> collisionConfiguration { new btDefaultCollisionConfiguration }; std::unique_ptr<btCollisionDispatcher> dispatcher { new btCollisionDispatcher { collisionConfiguration.get() } }; std::unique_ptr<btSequentialImpulseConstraintSolver> solver { new btSequentialImpulseConstraintSolver }; std::unique_ptr<btDiscreteDynamicsWorld> dynamicsWorld { new btDiscreteDynamicsWorld { dispatcher.get(), broadphase.get(), solver.get(), collisionConfiguration.get() } }; dynamicsWorld->setGravity(btVector3 { 0, -10, 0 }); std::unique_ptr<btCollisionShape> groundShape { new btStaticPlaneShape { btVector3 { 0, 1, 0 }, 1 } }; std::unique_ptr<btSphereShape> fallShape { new btSphereShape { 1 } }; std::unique_ptr<btDefaultMotionState> groundMotionState { new btDefaultMotionState { btTransform { btQuaternion { 0, 0, 0, 1 }, btVector3 { 0, -1, 0 } } } }; btRigidBody::btRigidBodyConstructionInfo groundRigidBodyConstructionInfo { 0, groundMotionState.get(), groundShape.get(), btVector3 { 0, 0, 0 } }; std::unique_ptr<btRigidBody> groundRigidBody { new btRigidBody { groundRigidBodyConstructionInfo } }; dynamicsWorld->addRigidBody(groundRigidBody.get()); std::unique_ptr<btDefaultMotionState> fallMotionState { new btDefaultMotionState { btTransform { btQuaternion { 0, 0, 0, 1 }, btVector3 { 0, 50, 0 } } } }; btScalar mass { 1 }; btVector3 fallInertia { 0, 0, 0 }; fallShape->calculateLocalInertia(mass, fallInertia); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyConstructionInfo { mass, fallMotionState.get(), fallShape.get(), fallInertia }; std::unique_ptr<btRigidBody> fallRigidBody { new btRigidBody { fallRigidBodyConstructionInfo } }; dynamicsWorld->addRigidBody(fallRigidBody.get()); glm::mat4 projectionMatrix = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f); glm::mat4 viewMatrix; glm::mat4 modelMatrix; glm::mat4 mvp; glm::vec3 lightPosition { 3, 3, 3 }; glm::vec3 lightColor { 1, 1, 1 }; float lightPower { 50.0f }; btTransform transformation; double currentTime, lastTime = glfwGetTime(); double fps { 0.0 }; size_t nFrames { 0l }; do { dynamicsWorld->stepSimulation(1 / 60.0f, 10); fallRigidBody->getMotionState()->getWorldTransform(transformation); ProcessInputs(); modelMatrix = glm::translate(glm::mat4 { 1.0f }, glm::vec3 { transformation.getOrigin().getX(), transformation.getOrigin().getY(), transformation.getOrigin().getZ() }); viewMatrix = glm::lookAt( s_position, s_position + s_direction, s_up ); mvp = projectionMatrix * viewMatrix * modelMatrix; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(s_programId); glUniformMatrix4fv(s_mvpMatrixId, 1, GL_FALSE, &mvp[0][0]); glUniformMatrix4fv(s_modelMatrixId, 1, GL_FALSE, &modelMatrix[0][0]); glUniformMatrix4fv(s_viewMatrixId, 1, GL_FALSE, &viewMatrix[0][0]); glUniform3f(s_lightPositionId, lightPosition.x, lightPosition.y, lightPosition.z); glUniform3f(s_lightColorId, lightColor.x, lightColor.y, lightColor.z); glUniform1f(s_lightPowerId, lightPower); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, s_textureId); glUniform1i(s_uniformTextureId, 0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, s_vertexBufferId); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, s_uvCoordBufferId); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, s_normalBufferId); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glDrawArrays(GL_TRIANGLES, 0, s_model.vertices().size()); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); currentTime = glfwGetTime(); ++nFrames; if (currentTime - lastTime > 1.0) { fps = 1000.0/nFrames; nFrames = 0; lastTime += 1.0; } ShowStatus(transformation.getOrigin().getY(), fps); glfwSwapBuffers(s_window); glfwPollEvents(); } while (glfwGetKey(s_window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwGetKey(s_window, GLFW_KEY_Q) != GLFW_PRESS && glfwWindowShouldClose(s_window) == 0); dynamicsWorld->removeRigidBody(fallRigidBody.get()); dynamicsWorld->removeRigidBody(groundRigidBody.get()); CleanupOpenGL(); return 0; }
void CCanvasContext::drawImageBatch(CImage *image, const vector<float> &coords) { //LOG("drawImageBatch: %d", coords.size()); int count = (int)(coords.size() / 8); if( !image || count <= 0 ) return; //glPushMatrix(); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, image->getTexture()); if( image->hasAlpha() ) { glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); } else { glDisable(GL_BLEND); } glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); int vertexCount = count * 6; static int maxVertex = 100; static GLfloat *vertices = NULL; static GLfloat *textureCoords = NULL; if( !vertices ) { vertices = (GLfloat *) malloc(maxVertex * 2 * sizeof(GLfloat)); } if( !textureCoords ) { textureCoords = (GLfloat *) malloc(maxVertex * 2 * sizeof(GLfloat)); } if( vertexCount > maxVertex ) { int newMaxVertex = maxVertex * 2; if( vertexCount > newMaxVertex ) { newMaxVertex = vertexCount; } GLfloat *newVertexBuf = (GLfloat *) malloc(newMaxVertex * 2 * sizeof(GLfloat)); GLfloat *newTextureCoordBuf = (GLfloat *) malloc(newMaxVertex * 2 * sizeof(GLfloat)); free(vertices); free(textureCoords); vertices = newVertexBuf; textureCoords = newTextureCoordBuf; maxVertex = newMaxVertex; } for( int i=0; i<count; i++ ) { float sx = coords[i*8]; float sy = coords[i*8+1]; float sw = coords[i*8+2]; float sh = coords[i*8+3]; float dx = coords[i*8+4]; float dy = coords[i*8+5]; float dw = coords[i*8+6]; float dh = coords[i*8+7]; // 6个点的订单坐标,其中2,3点和4,5点相同 vertices[i*12] = dx; vertices[i*12+1] = dy; vertices[i*12+2] = dx + dw; vertices[i*12+3] = dy; vertices[i*12+4] = dx; vertices[i*12+5] = dy + dh; vertices[i*12+6] = dx + dw; vertices[i*12+7] = dy; vertices[i*12+8] = dx; vertices[i*12+9] = dy + dh; vertices[i*12+10] = dx + dw; vertices[i*12+11] = dy + dh; // 6个点的纹理坐标,其中2,3点和4,5点相同 unsigned long POTWidth = image->POTWidth(); unsigned long POTHeight = image->POTHeight(); textureCoords[i*12] = sx / POTWidth; textureCoords[i*12+1] = sy / POTHeight; textureCoords[i*12+2] = (sx + sw) / POTWidth; textureCoords[i*12+3] = sy / POTHeight; textureCoords[i*12+4] = sx / POTWidth; textureCoords[i*12+5] = (sy + sh) / POTHeight; textureCoords[i*12+6] = (sx + sw) / POTWidth; textureCoords[i*12+7] = sy / POTHeight; textureCoords[i*12+8] = sx / POTWidth; textureCoords[i*12+9] = (sy + sh) / POTHeight; textureCoords[i*12+10] = (sx + sw) / POTWidth; textureCoords[i*12+11] = (sy + sh) / POTHeight; } glVertexPointer(2, GL_FLOAT, 0, vertices); glTexCoordPointer(2, GL_FLOAT, 0, textureCoords); glDrawArrays(GL_TRIANGLES, 0, vertexCount); //free(vertices); //free(textureCoords); glDisable(GL_VERTEX_ARRAY); glDisable(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); //glPopMatrix(); }
void CCanvasContext::stroke() { int pointCount = 0; int lineSegCount = 0; for( vector< vector<CGPoint> >::const_iterator it = m_lines.begin(); it != m_lines.end(); it++ ) { pointCount += it->size(); if( it->size() >= 2 ) { lineSegCount += (it->size() - 1); } } if( pointCount <= 0 ) { return; } cleanDrawImage(); glColor4f(m_strokeStyleColor.r, m_strokeStyleColor.g, m_strokeStyleColor.b, globalAlpha); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnableClientState(GL_VERTEX_ARRAY); bool bSqureCap = false; float originPointSize = 1; glGetFloatv(GL_POINT_SIZE, &originPointSize); int pointVertexCount = pointCount; int lineVertexCount = lineSegCount * 6 - 2; GLfloat * pointVertices = (GLfloat *)malloc(pointVertexCount * 2 * sizeof(GLfloat)); GLfloat * vertices = (GLfloat *)malloc( lineVertexCount * 2 * sizeof(GLfloat)); int pointCursor = 0; int lineCursor = 0; float x1,y1,x2,y2,distant,sina,cosa; float x11,y11,x12,y12,x21,y21,x22,y22; for( vector< vector<CGPoint> >::const_iterator it = m_lines.begin(); it != m_lines.end(); it++ ) { for( int i=0,max=it->size(); i<max; i++ ) { pointVertices[pointCursor++] = it->at(i).x; pointVertices[pointCursor++] = it->at(i).y; if( i == 0 ) { continue; } x1 = pointVertices[pointCursor-4]; y1 = pointVertices[pointCursor-3]; x2 = pointVertices[pointCursor-2]; y2 = pointVertices[pointCursor-1]; distant = sqrtf((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)); sina = (y2-y1)/distant; cosa = (x2-x1)/distant; // 计算2点直线所组成的矩形的四个顶点 x11 = x1-sina*lineWidth - (bSqureCap ? cosa*lineWidth : 0); y11 = y1+cosa*lineWidth - (bSqureCap ? sina*lineWidth : 0); x12 = x1+sina*lineWidth - (bSqureCap ? cosa*lineWidth : 0); y12 = y1-cosa*lineWidth - (bSqureCap ? sina*lineWidth : 0); x21 = x2-sina*lineWidth + (bSqureCap ? cosa*lineWidth : 0); y21 = y2+cosa*lineWidth + (bSqureCap ? sina*lineWidth : 0); x22 = x2+sina*lineWidth + (bSqureCap ? cosa*lineWidth : 0); y22 = y2-cosa*lineWidth + (bSqureCap ? sina*lineWidth : 0); if( lineCursor != 0 ) { // 增加首尾连接 ABCD DE EFGH vertices[lineCursor++] = vertices[lineCursor-2]; vertices[lineCursor++] = vertices[lineCursor-2]; vertices[lineCursor++] = x11; vertices[lineCursor++] = y11; } vertices[lineCursor++] = x11; vertices[lineCursor++] = y11; vertices[lineCursor++] = x12; vertices[lineCursor++] = y12; vertices[lineCursor++] = x21; vertices[lineCursor++] = y21; vertices[lineCursor++] = x22; vertices[lineCursor++] = y22; } } glVertexPointer(2, GL_FLOAT, 0, vertices); glDrawArrays(GL_TRIANGLE_STRIP, 0, lineVertexCount); glPointSize(lineWidth * 2); glEnable(GL_POINT_SMOOTH); glVertexPointer(2, GL_FLOAT, 0, pointVertices); glDrawArrays(GL_POINTS, 0, pointVertexCount); free(pointVertices); free(vertices); glPointSize(originPointSize); glColor4f(1.0, 1.0, 1.0, 1.0); glDisable(GL_BLEND); }
void AEVADrawRange(const AEVA* va, const AEVA* ia, GLuint start, GLuint count){ if(not va) return; if(count==0) count = (ia ? ia : va)->elementCount; char* offset=NULL; if(va->format.storageType) glBindBuffer(GL_ARRAY_BUFFER, va->data.vbo); else{ glBindBuffer(GL_ARRAY_BUFFER, 0); offset=va->data.pointer; } size_t stride=AEVAFormatByteSize(& va->format); for(int i=0;i<va->format.textureCoordsPerVertex;i++){ glClientActiveTexture(GL_TEXTURE0+i); glTexCoordPointer(2, GL_FLOAT, stride, offset); glEnableClientState(GL_TEXTURE_COORD_ARRAY); offset+=sizeof(float[2]); } glClientActiveTexture(GL_TEXTURE0); if(va->format.hasColors) { glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_UNSIGNED_BYTE, stride, offset); offset+=sizeof(GLubyte[4]); } if(va->format.hasNormals){ glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, stride, offset); offset+=sizeof(float[3]); } glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, stride, offset); if(ia) { char* indexOffset=NULL; size_t indexStride=0; //glEnableClientState(GL_INDEX_ARRAY); if(ia->format.storageType) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ia->data.vbo); else indexOffset=ia->data.pointer; indexStride=ia->format.indexType==AEVAFormatIndexType32Bit ? sizeof(GLuint) : sizeof(GLushort); GLuint indexType=GL_UNSIGNED_SHORT; #ifndef AEiOS if(ia->format.indexType==AEVAFormatIndexType32Bit) indexType=GL_UNSIGNED_INT; #endif glDrawElements(ia->format.isQuads ? GL_QUADS : GL_TRIANGLES, count, indexType, indexOffset+indexStride*start); //glDisableClientState(GL_INDEX_ARRAY); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } else glDrawArrays(va->format.isQuads ? GL_QUADS : GL_TRIANGLES, start, count); for(int i=0;i<va->format.textureCoordsPerVertex;i++){ glClientActiveTexture(GL_TEXTURE0+i); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } glClientActiveTexture(GL_TEXTURE0); if(va->format.hasColors) glDisableClientState(GL_COLOR_ARRAY); if(va->format.hasNormals) glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); }
void L_ParticleEffect::RenderPointSprites(SurfaceAnim *pSurf, int start, int count) { pSurf->Bind(); glBlendFunc( GL_SRC_ALPHA, GL_ONE); //this point sprite code was based on code from http://www.71squared.com/2009/05/iphone-game-programming-tutorial-8-particle-emitter/ which //was based on some cocos2d code I think -Seth glBindBuffer(GL_ARRAY_BUFFER, L_ParticleMem::pointSpriteBufferID); CHECK_GL_ERROR(); glBufferData(GL_ARRAY_BUFFER, sizeof(PointSprite)*count, &L_ParticleMem::pointSpriteArray[0], GL_DYNAMIC_DRAW); CHECK_GL_ERROR(); glEnable(GL_BLEND); // Enable and configure point sprites which we are going to use for our particles glEnable(GL_POINT_SPRITE_OES); CHECK_GL_ERROR(); glTexEnvi( GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE ); CHECK_GL_ERROR(); // Enable vertex arrays and bind to the vertices VBO which has been created glEnableClientState(GL_VERTEX_ARRAY); CHECK_GL_ERROR(); glBindBuffer(GL_ARRAY_BUFFER, L_ParticleMem::pointSpriteBufferID); CHECK_GL_ERROR(); // Configure the vertex pointer which will use the vertices VBO glVertexPointer(2, GL_FLOAT, sizeof(PointSprite), 0); CHECK_GL_ERROR(); // Enable the point size array glEnableClientState(GL_POINT_SIZE_ARRAY_OES); // Configure the point size pointer which will use the currently bound VBO. PointSprite contains // both the location of the point as well as its size, so the config below tells the point size // pointer where in the currently bound VBO it can find the size for each point glPointSizePointerOES(GL_FLOAT,sizeof(PointSprite),(GLvoid*) (sizeof(GL_FLOAT)*2)); // Enable the use of the color array glEnableClientState(GL_COLOR_ARRAY); // Configure the color pointer specifying how many values there are for each color and their type glColorPointer(4,GL_UNSIGNED_BYTE,sizeof(PointSprite),(GLvoid*) (sizeof(GL_FLOAT)*3)); // Now that all of the VBOs have been used to configure the vertices, pointer size and color // use glDrawArrays to draw the points //NOTE: It crashes here on the WebOS GLES windows emulator .. but runs on the device. driver bug I guess -Seth //Another note: It also can crash a Touchpad so.. not going to use this optimized point sprite stuff for webos :( glDrawArrays(GL_POINTS, start, count); CHECK_GL_ERROR(); // Unbind the current VBO glBindBuffer(GL_ARRAY_BUFFER, 0); CHECK_GL_ERROR(); // Disable the client states which have been used incase the next draw function does // not need or use them glDisableClientState(GL_POINT_SIZE_ARRAY_OES); glDisableClientState(GL_COLOR_ARRAY); CHECK_GL_ERROR(); glDisable(GL_POINT_SPRITE_OES); CHECK_GL_ERROR(); glDisableClientState(GL_POINT_SIZE_ARRAY_OES); glDisableClientState(GL_COLOR_ARRAY); CHECK_GL_ERROR(); glDisable(GL_POINT_SPRITE_OES); glDisable(GL_BLEND); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); CHECK_GL_ERROR(); }
void ccGenericMesh::drawMeOnly(CC_DRAW_CONTEXT& context) { ccGenericPointCloud* vertices = getAssociatedCloud(); if (!vertices) return; handleColorRamp(context); //3D pass if (MACRO_Draw3D(context)) { //any triangle? unsigned triNum = size(); if (triNum == 0) return; //L.O.D. bool lodEnabled = (triNum > context.minLODTriangleCount && context.decimateMeshOnMove && MACRO_LODActivated(context)); unsigned decimStep = (lodEnabled ? static_cast<unsigned>(ceil(static_cast<double>(triNum*3) / context.minLODTriangleCount)) : 1); unsigned displayedTriNum = triNum / decimStep; //display parameters glDrawParams glParams; getDrawingParameters(glParams); glParams.showNorms &= bool(MACRO_LightIsEnabled(context)); //vertices visibility const ccGenericPointCloud::VisibilityTableType* verticesVisibility = vertices->getTheVisibilityArray(); bool visFiltering = (verticesVisibility && verticesVisibility->isAllocated()); //wireframe ? (not compatible with LOD) bool showWired = isShownAsWire() && !lodEnabled; //per-triangle normals? bool showTriNormals = (hasTriNormals() && triNormsShown()); //fix 'showNorms' glParams.showNorms = showTriNormals || (vertices->hasNormals() && m_normalsDisplayed); //materials & textures bool applyMaterials = (hasMaterials() && materialsShown()); bool showTextures = (hasTextures() && materialsShown() && !lodEnabled); //GL name pushing bool pushName = MACRO_DrawEntityNames(context); //special case: triangle names pushing (for picking) bool pushTriangleNames = MACRO_DrawTriangleNames(context); pushName |= pushTriangleNames; if (pushName) { //not fast at all! if (MACRO_DrawFastNamesOnly(context)) return; glPushName(getUniqueIDForDisplay()); //minimal display for picking mode! glParams.showNorms = false; glParams.showColors = false; //glParams.showSF --> we keep it only if SF 'NaN' values are hidden showTriNormals = false; applyMaterials = false; showTextures = false; } //in the case we need to display scalar field colors ccScalarField* currentDisplayedScalarField = 0; bool greyForNanScalarValues = true; //unsigned colorRampSteps = 0; ccColorScale::Shared colorScale(0); if (glParams.showSF) { assert(vertices->isA(CC_TYPES::POINT_CLOUD)); ccPointCloud* cloud = static_cast<ccPointCloud*>(vertices); greyForNanScalarValues = (cloud->getCurrentDisplayedScalarField() && cloud->getCurrentDisplayedScalarField()->areNaNValuesShownInGrey()); if (greyForNanScalarValues && pushName) { //in picking mode, no need to take SF into account if we don't hide any points! glParams.showSF = false; } else { currentDisplayedScalarField = cloud->getCurrentDisplayedScalarField(); colorScale = currentDisplayedScalarField->getColorScale(); //colorRampSteps = currentDisplayedScalarField->getColorRampSteps(); assert(colorScale); //get default color ramp if cloud has no scale associated?! if (!colorScale) colorScale = ccColorScalesManager::GetUniqueInstance()->getDefaultScale(ccColorScalesManager::BGYR); } } //materials or color? bool colorMaterial = false; if (glParams.showSF || glParams.showColors) { applyMaterials = false; colorMaterial = true; glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); glEnable(GL_COLOR_MATERIAL); } //in the case we need to display vertex colors ColorsTableType* rgbColorsTable = 0; if (glParams.showColors) { if (isColorOverriden()) { ccGL::Color3v(m_tempColor.rgb); glParams.showColors = false; } else { assert(vertices->isA(CC_TYPES::POINT_CLOUD)); rgbColorsTable = static_cast<ccPointCloud*>(vertices)->rgbColors(); } } else { glColor3fv(context.defaultMat->getDiffuseFront().rgba); } if (glParams.showNorms) { //DGM: Strangely, when Qt::renderPixmap is called, the OpenGL version can fall to 1.0! glEnable((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_2 ? GL_RESCALE_NORMAL : GL_NORMALIZE)); glEnable(GL_LIGHTING); context.defaultMat->applyGL(true,colorMaterial); } //in the case we need normals (i.e. lighting) NormsIndexesTableType* normalsIndexesTable = 0; ccNormalVectors* compressedNormals = 0; if (glParams.showNorms) { assert(vertices->isA(CC_TYPES::POINT_CLOUD)); normalsIndexesTable = static_cast<ccPointCloud*>(vertices)->normals(); compressedNormals = ccNormalVectors::GetUniqueInstance(); } //stipple mask if (stipplingEnabled()) EnableGLStippleMask(true); if (!pushTriangleNames && !visFiltering && !(applyMaterials || showTextures) && (!glParams.showSF || greyForNanScalarValues)) { //the GL type depends on the PointCoordinateType 'size' (float or double) GLenum GL_COORD_TYPE = sizeof(PointCoordinateType) == 4 ? GL_FLOAT : GL_DOUBLE; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3,GL_COORD_TYPE,0,GetVertexBuffer()); if (glParams.showNorms) { glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_COORD_TYPE,0,GetNormalsBuffer()); } if (glParams.showSF || glParams.showColors) { glEnableClientState(GL_COLOR_ARRAY); glColorPointer(3,GL_UNSIGNED_BYTE,0,GetColorsBuffer()); } //we can scan and process each chunk separately in an optimized way //we mimic the way ccMesh beahves by using virtual chunks! unsigned chunks = static_cast<unsigned>(ceil(static_cast<double>(displayedTriNum)/MAX_NUMBER_OF_ELEMENTS_PER_CHUNK)); unsigned chunkStart = 0; const ColorCompType* col = 0; for (unsigned k=0; k<chunks; ++k, chunkStart += MAX_NUMBER_OF_ELEMENTS_PER_CHUNK) { //virtual chunk size const unsigned chunkSize = k+1 < chunks ? MAX_NUMBER_OF_ELEMENTS_PER_CHUNK : (displayedTriNum % MAX_NUMBER_OF_ELEMENTS_PER_CHUNK); //vertices PointCoordinateType* _vertices = GetVertexBuffer(); for (unsigned n=0; n<chunkSize; n+=decimStep) { const CCLib::VerticesIndexes* ti = getTriangleVertIndexes(chunkStart + n); memcpy(_vertices,vertices->getPoint(ti->i1)->u,sizeof(PointCoordinateType)*3); _vertices+=3; memcpy(_vertices,vertices->getPoint(ti->i2)->u,sizeof(PointCoordinateType)*3); _vertices+=3; memcpy(_vertices,vertices->getPoint(ti->i3)->u,sizeof(PointCoordinateType)*3); _vertices+=3; } //scalar field if (glParams.showSF) { ColorCompType* _rgbColors = GetColorsBuffer(); assert(colorScale); for (unsigned n=0; n<chunkSize; n+=decimStep) { const CCLib::VerticesIndexes* ti = getTriangleVertIndexes(chunkStart + n); col = currentDisplayedScalarField->getValueColor(ti->i1); memcpy(_rgbColors,col,sizeof(ColorCompType)*3); _rgbColors += 3; col = currentDisplayedScalarField->getValueColor(ti->i2); memcpy(_rgbColors,col,sizeof(ColorCompType)*3); _rgbColors += 3; col = currentDisplayedScalarField->getValueColor(ti->i3); memcpy(_rgbColors,col,sizeof(ColorCompType)*3); _rgbColors += 3; } } //colors else if (glParams.showColors) { ColorCompType* _rgbColors = GetColorsBuffer(); for (unsigned n=0; n<chunkSize; n+=decimStep) { const CCLib::VerticesIndexes* ti = getTriangleVertIndexes(chunkStart + n); memcpy(_rgbColors,rgbColorsTable->getValue(ti->i1),sizeof(ColorCompType)*3); _rgbColors += 3; memcpy(_rgbColors,rgbColorsTable->getValue(ti->i2),sizeof(ColorCompType)*3); _rgbColors += 3; memcpy(_rgbColors,rgbColorsTable->getValue(ti->i3),sizeof(ColorCompType)*3); _rgbColors += 3; } } //normals if (glParams.showNorms) { PointCoordinateType* _normals = GetNormalsBuffer(); if (showTriNormals) { for (unsigned n=0; n<chunkSize; n+=decimStep) { CCVector3 Na, Nb, Nc; getTriangleNormals(chunkStart + n, Na, Nb, Nc); memcpy(_normals,Na.u,sizeof(PointCoordinateType)*3); _normals+=3; memcpy(_normals,Nb.u,sizeof(PointCoordinateType)*3); _normals+=3; memcpy(_normals,Nc.u,sizeof(PointCoordinateType)*3); _normals+=3; } } else { for (unsigned n=0; n<chunkSize; n+=decimStep) { const CCLib::VerticesIndexes* ti = getTriangleVertIndexes(chunkStart + n); memcpy(_normals,vertices->getPointNormal(ti->i1).u,sizeof(PointCoordinateType)*3); _normals+=3; memcpy(_normals,vertices->getPointNormal(ti->i2).u,sizeof(PointCoordinateType)*3); _normals+=3; memcpy(_normals,vertices->getPointNormal(ti->i3).u,sizeof(PointCoordinateType)*3); _normals+=3; } } } if (!showWired) { glDrawArrays(lodEnabled ? GL_POINTS : GL_TRIANGLES,0,(chunkSize/decimStep)*3); } else { glDrawElements(GL_LINES,(chunkSize/decimStep)*6,GL_UNSIGNED_INT,GetWireVertexIndexes()); } } //disable arrays glDisableClientState(GL_VERTEX_ARRAY); if (glParams.showNorms) glDisableClientState(GL_NORMAL_ARRAY); if (glParams.showSF || glParams.showColors) glDisableClientState(GL_COLOR_ARRAY); } else { //current vertex color const ColorCompType *col1=0,*col2=0,*col3=0; //current vertex normal const PointCoordinateType *N1=0,*N2=0,*N3=0; //current vertex texture coordinates float *Tx1=0,*Tx2=0,*Tx3=0; //loop on all triangles int lasMtlIndex = -1; if (showTextures) { //#define TEST_TEXTURED_BUNDLER_IMPORT #ifdef TEST_TEXTURED_BUNDLER_IMPORT glPushAttrib(GL_COLOR_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(context.sourceBlend, context.destBlend); #endif glEnable(GL_TEXTURE_2D); } if (pushTriangleNames) glPushName(0); GLenum triangleDisplayType = lodEnabled ? GL_POINTS : showWired ? GL_LINE_LOOP : GL_TRIANGLES; glBegin(triangleDisplayType); //per-triangle normals const NormsIndexesTableType* triNormals = getTriNormsTable(); //materials const ccMaterialSet* materials = getMaterialSet(); for (unsigned n=0; n<triNum; ++n) { //current triangle vertices const CCLib::VerticesIndexes* tsi = getTriangleVertIndexes(n); //LOD: shall we display this triangle? if (n % decimStep) continue; if (visFiltering) { //we skip the triangle if at least one vertex is hidden if ((verticesVisibility->getValue(tsi->i1) != POINT_VISIBLE) || (verticesVisibility->getValue(tsi->i2) != POINT_VISIBLE) || (verticesVisibility->getValue(tsi->i3) != POINT_VISIBLE)) continue; } if (glParams.showSF) { assert(colorScale); col1 = currentDisplayedScalarField->getValueColor(tsi->i1); if (!col1) continue; col2 = currentDisplayedScalarField->getValueColor(tsi->i2); if (!col2) continue; col3 = currentDisplayedScalarField->getValueColor(tsi->i3); if (!col3) continue; } else if (glParams.showColors) { col1 = rgbColorsTable->getValue(tsi->i1); col2 = rgbColorsTable->getValue(tsi->i2); col3 = rgbColorsTable->getValue(tsi->i3); } if (glParams.showNorms) { if (showTriNormals) { assert(triNormals); int n1,n2,n3; getTriangleNormalIndexes(n,n1,n2,n3); N1 = (n1>=0 ? ccNormalVectors::GetNormal(triNormals->getValue(n1)).u : 0); N2 = (n1==n2 ? N1 : n1>=0 ? ccNormalVectors::GetNormal(triNormals->getValue(n2)).u : 0); N3 = (n1==n3 ? N1 : n3>=0 ? ccNormalVectors::GetNormal(triNormals->getValue(n3)).u : 0); } else { N1 = compressedNormals->getNormal(normalsIndexesTable->getValue(tsi->i1)).u; N2 = compressedNormals->getNormal(normalsIndexesTable->getValue(tsi->i2)).u; N3 = compressedNormals->getNormal(normalsIndexesTable->getValue(tsi->i3)).u; } } if (applyMaterials || showTextures) { assert(materials); int newMatlIndex = this->getTriangleMtlIndex(n); //do we need to change material? if (lasMtlIndex != newMatlIndex) { assert(newMatlIndex < static_cast<int>(materials->size())); glEnd(); if (showTextures) { GLuint texID = (newMatlIndex >= 0 ? context._win->getTextureID((*materials)[newMatlIndex]) : 0); assert(texID <= 0 || glIsTexture(texID)); glBindTexture(GL_TEXTURE_2D, texID); } //if we don't have any current material, we apply default one if (newMatlIndex >= 0) (*materials)[newMatlIndex]->applyGL(glParams.showNorms,false); else context.defaultMat->applyGL(glParams.showNorms,false); glBegin(triangleDisplayType); lasMtlIndex = newMatlIndex; } if (showTextures) { getTriangleTexCoordinates(n,Tx1,Tx2,Tx3); } } if (pushTriangleNames) { glEnd(); glLoadName(n); glBegin(triangleDisplayType); } else if (showWired) { glEnd(); glBegin(triangleDisplayType); } //vertex 1 if (N1) ccGL::Normal3v(N1); if (col1) glColor3ubv(col1); if (Tx1) glTexCoord2fv(Tx1); ccGL::Vertex3v(vertices->getPoint(tsi->i1)->u); //vertex 2 if (N2) ccGL::Normal3v(N2); if (col2) glColor3ubv(col2); if (Tx2) glTexCoord2fv(Tx2); ccGL::Vertex3v(vertices->getPoint(tsi->i2)->u); //vertex 3 if (N3) ccGL::Normal3v(N3); if (col3) glColor3ubv(col3); if (Tx3) glTexCoord2fv(Tx3); ccGL::Vertex3v(vertices->getPoint(tsi->i3)->u); } glEnd(); if (pushTriangleNames) glPopName(); if (showTextures) { #ifdef TEST_TEXTURED_BUNDLER_IMPORT glPopAttrib(); //GL_COLOR_BUFFER_BIT #endif glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); } } if (stipplingEnabled()) EnableGLStippleMask(false); if (colorMaterial) glDisable(GL_COLOR_MATERIAL); if (glParams.showNorms) { glDisable(GL_LIGHTING); glDisable((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_2 ? GL_RESCALE_NORMAL : GL_NORMALIZE)); } if (pushName) glPopName(); } }
static void text_draw(FT_Face face,wchar_t * str,RNG_Int width ,RNG_Int height,RNG_Color color,RNG_Vector offset) { static GLdouble quad[4][2]; static GLubyte expanded_data [128*128*4]; static GLfloat textureCoordinates[4][2]; glTranslated(offset.x,offset.y,0); for(int k=0; str[k]!='\0'; k++) { //对空格进行特殊处理 if(str[k]==32) { for(int i =0; i<128*128*4; i++) { expanded_data[i]=0; } } else { FT_Load_Glyph( face, FT_Get_Char_Index( face, str[k]), FT_LOAD_DEFAULT ); FT_Render_Glyph( face->glyph, FT_RENDER_MODE_NORMAL ); for(int j=0; j <face->glyph->bitmap.rows; j++) { for(int i=0; i < face->glyph->bitmap.width; i++) { if(face->glyph->bitmap.buffer[i + face->glyph->bitmap.width*j]) { expanded_data[4*(i+j*face->glyph->bitmap.width)] = 255; expanded_data[4*(i+j*face->glyph->bitmap.width)+1]=255; expanded_data[4*(i+j*face->glyph->bitmap.width)+2]=255; expanded_data[4*(i+j*face->glyph->bitmap.width)+3]=255; } else { expanded_data[4*(i+j*face->glyph->bitmap.width)] = 0; expanded_data[4*(i+j*face->glyph->bitmap.width)+1]=0; expanded_data[4*(i+j*face->glyph->bitmap.width)+2]=0; expanded_data[4*(i+j*face->glyph->bitmap.width)+3]=0; } } } } //左下 quad[0][0]=0; quad[0][1]=0; //右下 quad[1][0]=width; quad[1][1]=0; //左上 quad[2][0]=0; quad[2][1]=height; //右上 quad[3][0]=width; quad[3][1]=height; //左下 textureCoordinates[0][0]=0; textureCoordinates[0][1]=1; //右下 textureCoordinates[1][0]=1; textureCoordinates[1][1]=1; //左上 textureCoordinates[2][0]=0; textureCoordinates[2][1]=0; //右上 glColor4d(color.red,color.green,color.blue,color.alpha); textureCoordinates[3][0]=1; textureCoordinates[3][1]=0; glBindTexture(GL_TEXTURE_2D,texture); glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,face->glyph->bitmap.width,face->glyph->bitmap.rows,0,GL_RGBA,GL_UNSIGNED_BYTE,expanded_data); glTranslatef(width,0,0); glTexCoordPointer(2, GL_FLOAT, 0, textureCoordinates); glVertexPointer(2,GL_DOUBLE,0,quad); glDrawArrays(GL_TRIANGLE_STRIP,0,4); } }
///@todo Even though this function shares most of its code with client rendering, /// which appears to work fine, it is non-convergable. It appears that the projection /// matrices for each eye are too far apart? Could be modelview... void RiftAppSkeleton::display_stereo_undistorted() //const { ovrHmd hmd = m_Hmd; if (hmd == NULL) return; //ovrFrameTiming hmdFrameTiming = ovrHmd_BeginFrameTiming(hmd, 0); bindFBO(m_renderBuffer, m_fboScale); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++) { ovrEyeType eye = hmd->EyeRenderOrder[eyeIndex]; ovrPosef eyePose = ovrHmd_GetEyePose(hmd, eye); const ovrGLTexture& otex = l_EyeTexture[eye]; const ovrRecti& rvp = otex.OGL.Header.RenderViewport; const ovrRecti rsc = { static_cast<int>(m_fboScale * rvp.Pos.x), static_cast<int>(m_fboScale * rvp.Pos.y), static_cast<int>(m_fboScale * rvp.Size.w), static_cast<int>(m_fboScale * rvp.Size.h) }; glViewport(rsc.Pos.x, rsc.Pos.y, rsc.Size.w, rsc.Size.h); OVR::Quatf orientation = OVR::Quatf(eyePose.Orientation); OVR::Matrix4f proj = ovrMatrix4f_Projection( m_EyeRenderDesc[eye].Fov, 0.01f, 10000.0f, true); //m_EyeRenderDesc[eye].DistortedViewport; OVR::Vector3f EyePos = m_chassisPos; OVR::Matrix4f view = OVR::Matrix4f(orientation.Inverted()) * OVR::Matrix4f::RotationY(m_chassisYaw) * OVR::Matrix4f::Translation(-EyePos); OVR::Matrix4f eyeview = OVR::Matrix4f::Translation(m_EyeRenderDesc[eye].ViewAdjust) * view; _resetGLState(); _DrawScenes(&eyeview.Transposed().M[0][0], &proj.Transposed().M[0][0], rvp); } unbindFBO(); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); // Present FBO to screen const GLuint prog = m_presentFbo.prog(); glUseProgram(prog); m_presentFbo.bindVAO(); { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_renderBuffer.tex); glUniform1i(m_presentFbo.GetUniLoc("fboTex"), 0); // This is the only uniform that changes per-frame glUniform1f(m_presentFbo.GetUniLoc("fboScale"), m_fboScale); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } glBindVertexArray(0); glUseProgram(0); ovrHmd_EndFrameTiming(hmd); }
// The MAIN function, from here we start the application and run the game loop int main() { // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions glViewport(0, 0, WIDTH, HEIGHT); // Build and compile our shader program Shader ourShader("basic.vs", "basic.frag"); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Colors 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // Bottom Left 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // Top }; GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // Color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindVertexArray(0); // Unbind VAO // Game loop while (!glfwWindowShouldClose(window)) { // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Draw the triangle ourShader.Use(); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); // Swap the screen buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; }
void R_DrawParticles (void) { particle_t *p, *kill; float grav; int i; float time2, time3; float time1; float dvel; float frametime; #ifdef GLQUAKE vec3_t up, right; float scale; GL_Use (gl_coloredpolygon1textureprogram); glUniformMatrix4fv(gl_coloredpolygon1textureprogram_transform, 1, 0, gl_polygon_matrix); GL_Bind(particletexture); glEnable (GL_BLEND); VectorScale (vup, 1.5, up); VectorScale (vright, 1.5, right); #else D_StartParticles (); VectorScale (vright, xscaleshrink, r_pright); VectorScale (vup, yscaleshrink, r_pup); VectorCopy (vpn, r_ppn); #endif frametime = cl.time - cl.oldtime; time3 = frametime * 15; time2 = frametime * 10; // 15; time1 = frametime * 5; grav = frametime * sv_gravity.value * 0.05; dvel = 4*frametime; for ( ;; ) { kill = active_particles; if (kill && kill->die < cl.time) { active_particles = kill->next; kill->next = free_particles; free_particles = kill; continue; } break; } #ifdef GLQUAKE int mark = Hunk_LowMark(); int vertexcount = 0; for (p=active_particles ; p ; p=p->next) { vertexcount += 3; } if (vertexcount == 0) return; GLfloat* vertices = Hunk_AllocName (vertexcount * 9 * sizeof(GLfloat), "vertex_buffer"); int vertexpos = 0; #endif for (p=active_particles ; p ; p=p->next) { for ( ;; ) { kill = p->next; if (kill && kill->die < cl.time) { p->next = kill->next; kill->next = free_particles; free_particles = kill; continue; } break; } #ifdef GLQUAKE // hack a scale up to keep particles from disapearing scale = (p->org[0] - r_origin[0])*vpn[0] + (p->org[1] - r_origin[1])*vpn[1] + (p->org[2] - r_origin[2])*vpn[2]; if (scale < 20) scale = 1; else scale = 1 + scale * 0.004; unsigned c = d_8to24table[(int)p->color]; GLfloat r = (GLfloat)(c & 0xFF) / 255.0; GLfloat g = (GLfloat)((c >> 8) & 0xFF) / 255.0; GLfloat b = (GLfloat)((c >> 16) & 0xFF) / 255.0; GLfloat a = (GLfloat)((c >> 24) & 0xFF) / 255.0; vertices[vertexpos++] = p->org[0]; vertices[vertexpos++] = p->org[1]; vertices[vertexpos++] = p->org[2]; vertices[vertexpos++] = r; vertices[vertexpos++] = g; vertices[vertexpos++] = b; vertices[vertexpos++] = a; vertices[vertexpos++] = 0.0; vertices[vertexpos++] = 0.0; vertices[vertexpos++] = p->org[0] + up[0] * scale; vertices[vertexpos++] = p->org[1] + up[1] * scale; vertices[vertexpos++] = p->org[2] + up[2] * scale; vertices[vertexpos++] = r; vertices[vertexpos++] = g; vertices[vertexpos++] = b; vertices[vertexpos++] = a; vertices[vertexpos++] = 1.0; vertices[vertexpos++] = 0.0; vertices[vertexpos++] = p->org[0] + right[0] * scale; vertices[vertexpos++] = p->org[1] + right[1] * scale; vertices[vertexpos++] = p->org[2] + right[2] * scale; vertices[vertexpos++] = r; vertices[vertexpos++] = g; vertices[vertexpos++] = b; vertices[vertexpos++] = a; vertices[vertexpos++] = 0.0; vertices[vertexpos++] = 1.0; #else D_DrawParticle (p); #endif p->org[0] += p->vel[0]*frametime; p->org[1] += p->vel[1]*frametime; p->org[2] += p->vel[2]*frametime; switch (p->type) { case pt_static: break; case pt_fire: p->ramp += time1; if (p->ramp >= 6) p->die = -1; else p->color = ramp3[(int)p->ramp]; p->vel[2] += grav; break; case pt_explode: p->ramp += time2; if (p->ramp >=8) p->die = -1; else p->color = ramp1[(int)p->ramp]; for (i=0 ; i<3 ; i++) p->vel[i] += p->vel[i]*dvel; p->vel[2] -= grav; break; case pt_explode2: p->ramp += time3; if (p->ramp >=8) p->die = -1; else p->color = ramp2[(int)p->ramp]; for (i=0 ; i<3 ; i++) p->vel[i] -= p->vel[i]*frametime; p->vel[2] -= grav; break; case pt_blob: for (i=0 ; i<3 ; i++) p->vel[i] += p->vel[i]*dvel; p->vel[2] -= grav; break; case pt_blob2: for (i=0 ; i<2 ; i++) p->vel[i] -= p->vel[i]*dvel; p->vel[2] -= grav; break; case pt_grav: #ifdef QUAKE2 p->vel[2] -= grav * 20; break; #endif case pt_slowgrav: p->vel[2] -= grav; break; } } #ifdef GLQUAKE GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertexcount * 9 * sizeof(GLfloat), vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(gl_coloredpolygon1textureprogram_position); glVertexAttribPointer(gl_coloredpolygon1textureprogram_position, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(GLfloat), (const GLvoid *)0); glEnableVertexAttribArray(gl_coloredpolygon1textureprogram_color); glVertexAttribPointer(gl_coloredpolygon1textureprogram_color, 4, GL_FLOAT, GL_FALSE, 9 * sizeof(GLfloat), (const GLvoid *)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(gl_coloredpolygon1textureprogram_texcoords); glVertexAttribPointer(gl_coloredpolygon1textureprogram_texcoords, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(GLfloat), (const GLvoid *)(7 * sizeof(GLfloat))); glDrawArrays(GL_TRIANGLES, 0, vertexcount); glDisableVertexAttribArray(gl_coloredpolygon1textureprogram_texcoords); glDisableVertexAttribArray(gl_coloredpolygon1textureprogram_color); glDisableVertexAttribArray(gl_coloredpolygon1textureprogram_position); glBindBuffer(GL_ARRAY_BUFFER, 0); glDeleteBuffers(1, &vertexbuffer); Hunk_FreeToLowMark (mark); glDisable (GL_BLEND); #else D_EndParticles (); #endif }
Response Slider::Draw (AbstractWindow* context) { float x = 0.f; float y = 0.f; AbstractWindow::shaders()->widget_outer_program()->use(); glBindVertexArray(vao_); glUniform4fv(AbstractWindow::shaders()->location(Shaders::WIDGET_OUTER_COLOR), 1, AbstractWindow::theme()->regular().outline.data()); if (orientation() == Horizontal) { // ----- draw line glUniform2f(AbstractWindow::shaders()-> location(Shaders::WIDGET_OUTER_OFFSET), 0.f, size().height() / 2); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glUniform2f(AbstractWindow::shaders()-> location(Shaders::WIDGET_OUTER_OFFSET), 0.f, size().height() / 2 - 1.f); glUniform4f(AbstractWindow::shaders()-> location(Shaders::WIDGET_OUTER_COLOR), 1.f, 1.f, 1.f, 0.16f); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); x += get_slider_position(); y += size().height() / 2.f - slide_icon_.size().height() / 2.f; } else { // ----- draw line glUniform2f(AbstractWindow::shaders()-> location(Shaders::WIDGET_OUTER_OFFSET), size().width() / 2, 0.f); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glUniform2f(AbstractWindow::shaders()-> location(Shaders::WIDGET_OUTER_OFFSET), size().width() / 2 + 1.f, 0.f); glUniform4f(AbstractWindow::shaders()-> location(Shaders::WIDGET_OUTER_COLOR), 1.f, 1.f, 1.f, 0.16f); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); x += size().width() / 2.f - slide_icon_.size().width() / 2.f; y += get_slider_position(); } slide_icon_.Draw(x, y); return Finish; }
int main(int argc, char *argv[]) { ShaderProgram program = setup(); Matrix paddle_left_matrix; Matrix paddle_right_matrix; Matrix ball_matrix; Matrix view_matrix; Matrix projection_matrix; GLuint chartreuse_texture_ID = load_texture_rgb("chartreuse.png"); projection_matrix.setOrthoProjection(-3.55f, 3.55f, -2.0f, 2.0f, -1.0f, 1.0f); SDL_Event event; bool done = false; bool game_started = false; Paddle paddle_left(-3.5f, -3.4f, 0.5f, -0.5f); Paddle paddle_right(3.4f, 3.5f, 0.5f, -0.5f); Ball ball(0.0f, 0.0f, 0.05f, 0.0025f, (float)rand(), (float)rand()); while (!done) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //Controls for the game while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) done = true; if (event.type == SDL_KEYDOWN) { // left paddle if (event.key.keysym.scancode == SDL_SCANCODE_W) { if (paddle_left.top < 2.0f){ paddle_left.top += 0.3f; paddle_left.bottom += 0.3f; paddle_left_matrix.Translate(0.0f, 0.3f, 0.0f); } } if (event.key.keysym.scancode == SDL_SCANCODE_S) { if (paddle_left.bottom > -2.0f){ paddle_left.top -= 0.3f; paddle_left.bottom -= 0.3f; paddle_left_matrix.Translate(0.0f, -0.3f, 0.0f); } } // right paddle if (event.key.keysym.scancode == SDL_SCANCODE_UP) { if (paddle_right.top < 2.0f){ paddle_right.top += 0.3f; paddle_right.bottom += 0.3f; paddle_right_matrix.Translate(0.0f, 0.3f, 0.0f); } } if (event.key.keysym.scancode == SDL_SCANCODE_DOWN) { if (paddle_right.bottom > -2.0f){ paddle_right.top -= 0.3f; paddle_right.bottom -= 0.3f; paddle_right_matrix.Translate(0.0f, -0.3f, 0.0f); } } if (event.key.keysym.scancode == SDL_SCANCODE_SPACE || event.key.keysym.scancode == SDL_SCANCODE_RETURN) { if (!game_started) game_started = true; } } } glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); program.setModelMatrix(paddle_left_matrix); program.setViewMatrix(view_matrix); program.setProjectionMatrix(projection_matrix); glUseProgram(program.programID); float texture_coords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f }; // global texture coordinates // left paddle float paddle_left_coords[] = { -3.5f, -0.5f, -3.4f, -0.5f, -3.4f, 0.5f, -3.4f, 0.5f, -3.5f, 0.5f, -3.5f, -0.5f }; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, paddle_left_coords); glEnableVertexAttribArray(program.positionAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texture_coords); glEnableVertexAttribArray(program.texCoordAttribute); glBindTexture(GL_TEXTURE_2D, chartreuse_texture_ID); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); // right paddle program.setModelMatrix(paddle_right_matrix); float paddle_right_coords[] = { 3.4f, -0.5f, 3.5f, -0.5f, 3.5f, 0.5f, 3.5f, 0.5f, 3.4f, 0.5f, 3.4f, -0.5f }; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, paddle_right_coords); glEnableVertexAttribArray(program.positionAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texture_coords); glEnableVertexAttribArray(program.texCoordAttribute); glBindTexture(GL_TEXTURE_2D, chartreuse_texture_ID); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); // ball program.setModelMatrix(ball_matrix); float ball_coords[] = { -0.1f, -0.1f, 0.1f, -0.1f, 0.1f, 0.1f, 0.1f, 0.1f, -0.1f, 0.1f, -0.1f, -0.1f }; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, ball_coords); glEnableVertexAttribArray(program.positionAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texture_coords); glEnableVertexAttribArray(program.texCoordAttribute); glBindTexture(GL_TEXTURE_2D, chartreuse_texture_ID); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); if (game_started) { // right wins if (ball.position_x - 0.1f <= paddle_left.left) { game_started = false; ball_matrix.Translate(-ball.position_x, -ball.position_y, 0.0f); ball.position_x = 0.0f; // for some reason reset() doesn't work :-( ball.position_y = 0.0f; ball.direction_x = (float)rand() / (float)RAND_MAX; ball.direction_y = (float)rand() / (float)RAND_MAX; ball.speed = 0.05f; std::cout << "Right player wins!\n"; } // left wins else if (ball.position_x + 0.1f >= paddle_right.right) { game_started = false; ball_matrix.Translate(-ball.position_x, -ball.position_y, 0.0f); ball.position_x = 0.0f; ball.position_y = 0.0f; ball.direction_x = (float)rand() / (float)RAND_MAX; ball.direction_y = (float)rand() / (float)RAND_MAX; ball.speed = 0.05f; std::cout << "Left player wins!\n"; } // hits top or bottom of screen else if (ball.position_y + 0.1f >= 2.0f || ball.position_y - 0.1f <= -2.0f) { ball.direction_y *= -1; ball.speed += ball.acceleration; ball.move(); ball_matrix.Translate(ball.speed * ball.direction_x, ball.speed * ball.direction_y, 0.0f); } // hits a paddle else if ((ball.position_x - 0.1f <= paddle_left.right && ball.position_y - 0.1f <= paddle_left.top && ball.position_y + 0.1f >= paddle_left.bottom) || (ball.position_x + 0.1f >= paddle_right.left && ball.position_y - 0.1f <= paddle_right.top && ball.position_y + 0.1f >= paddle_right.bottom)) { ball.direction_x *= -1; ball.speed += ball.acceleration; ball.move(); ball_matrix.Translate((ball.speed * ball.direction_x), (ball.speed * ball.direction_y), 0.0f); } // general movement else { ball.move(); ball_matrix.Translate((ball.speed * ball.direction_x), (ball.speed * ball.direction_y), 0.0f); } } SDL_GL_SwapWindow(displayWindow); } SDL_Quit(); return 0; }
static void time_draw_cache(SpaceTime *stime, Object *ob) { PTCacheID *pid; ListBase pidlist; SpaceTimeCache *stc = stime->caches.first; float yoffs = 0.f; if (!(stime->cache_display & TIME_CACHE_DISPLAY) || (!ob)) return; BKE_ptcache_ids_from_object(&pidlist, ob, NULL, 0); /* iterate over pointcaches on the active object, * add spacetimecache and vertex array for each */ for (pid = pidlist.first; pid; pid = pid->next) { float col[4], *fp; int i, sta = pid->cache->startframe, end = pid->cache->endframe; int len = (end - sta + 1) * 4; switch (pid->type) { case PTCACHE_TYPE_SOFTBODY: if (!(stime->cache_display & TIME_CACHE_SOFTBODY)) continue; break; case PTCACHE_TYPE_PARTICLES: if (!(stime->cache_display & TIME_CACHE_PARTICLES)) continue; break; case PTCACHE_TYPE_CLOTH: if (!(stime->cache_display & TIME_CACHE_CLOTH)) continue; break; case PTCACHE_TYPE_SMOKE_DOMAIN: case PTCACHE_TYPE_SMOKE_HIGHRES: if (!(stime->cache_display & TIME_CACHE_SMOKE)) continue; break; case PTCACHE_TYPE_DYNAMICPAINT: if (!(stime->cache_display & TIME_CACHE_DYNAMICPAINT)) continue; break; } if (pid->cache->cached_frames == NULL) continue; /* make sure we have stc with correct array length */ if (stc == NULL || MEM_allocN_len(stc->array) != len * 2 * sizeof(float)) { if (stc) { MEM_freeN(stc->array); } else { stc = MEM_callocN(sizeof(SpaceTimeCache), "spacetimecache"); BLI_addtail(&stime->caches, stc); } stc->array = MEM_callocN(len * 2 * sizeof(float), "SpaceTimeCache array"); } /* fill the vertex array with a quad for each cached frame */ for (i = sta, fp = stc->array; i <= end; i++) { if (pid->cache->cached_frames[i - sta]) { fp[0] = (float)i - 0.5f; fp[1] = 0.0; fp += 2; fp[0] = (float)i - 0.5f; fp[1] = 1.0; fp += 2; fp[0] = (float)i + 0.5f; fp[1] = 1.0; fp += 2; fp[0] = (float)i + 0.5f; fp[1] = 0.0; fp += 2; } } glPushMatrix(); glTranslatef(0.0, (float)V2D_SCROLL_HEIGHT + yoffs, 0.0); glScalef(1.0, CACHE_DRAW_HEIGHT, 0.0); switch (pid->type) { case PTCACHE_TYPE_SOFTBODY: col[0] = 1.0; col[1] = 0.4; col[2] = 0.02; col[3] = 0.1; break; case PTCACHE_TYPE_PARTICLES: col[0] = 1.0; col[1] = 0.1; col[2] = 0.02; col[3] = 0.1; break; case PTCACHE_TYPE_CLOTH: col[0] = 0.1; col[1] = 0.1; col[2] = 0.75; col[3] = 0.1; break; case PTCACHE_TYPE_SMOKE_DOMAIN: case PTCACHE_TYPE_SMOKE_HIGHRES: col[0] = 0.2; col[1] = 0.2; col[2] = 0.2; col[3] = 0.1; break; case PTCACHE_TYPE_DYNAMICPAINT: col[0] = 1.0; col[1] = 0.1; col[2] = 0.75; col[3] = 0.1; break; default: BLI_assert(0); col[0] = 1.0; col[1] = 0.0; col[2] = 1.0; col[3] = 0.1; } glColor4fv(col); glEnable(GL_BLEND); glRectf((float)sta, 0.0, (float)end, 1.0); col[3] = 0.4f; if (pid->cache->flag & PTCACHE_BAKED) { col[0] -= 0.4f; col[1] -= 0.4f; col[2] -= 0.4f; } else if (pid->cache->flag & PTCACHE_OUTDATED) { col[0] += 0.4f; col[1] += 0.4f; col[2] += 0.4f; } glColor4fv(col); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, stc->array); glDrawArrays(GL_QUADS, 0, (fp - stc->array) / 2); glDisableClientState(GL_VERTEX_ARRAY); glDisable(GL_BLEND); glPopMatrix(); yoffs += CACHE_DRAW_HEIGHT; stc = stc->next; } BLI_freelistN(&pidlist); /* free excessive caches */ while (stc) { SpaceTimeCache *tmp = stc->next; BLI_remlink(&stime->caches, stc); MEM_freeN(stc->array); MEM_freeN(stc); stc = tmp; } }
int main() { int width = 640; int height = 480; sf::Window window(sf::VideoMode(width, height), "sfml", sf::Style::Default, sf::ContextSettings(0,0,0,3,3)); // using glew since sfml doesn create a core context if(glewInit()) { std::cerr << "failed to init GLEW" << std::endl; return 1; } // shader source code std::string vertex_source = "#version 330\n" "layout(location = 0) in vec4 vposition;\n" "layout(location = 1) in vec4 vcolor;\n" "out vec4 fcolor;\n" "void main() {\n" " fcolor = vcolor;\n" " gl_Position = vposition;\n" "}\n"; std::string fragment_source = "#version 330\n" "in vec4 fcolor;\n" "layout(location = 0) out vec4 FragColor;\n" "void main() {\n" " FragColor = fcolor;\n" "}\n"; // program and shader handles GLuint shader_program, vertex_shader, fragment_shader; // we need these to properly pass the strings const char *source; int length; // create and compiler vertex shader vertex_shader = glCreateShader(GL_VERTEX_SHADER); source = vertex_source.c_str(); length = vertex_source.size(); glShaderSource(vertex_shader, 1, &source, &length); glCompileShader(vertex_shader); if(!check_shader_compile_status(vertex_shader)) { return 1; } // create and compiler fragment shader fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); source = fragment_source.c_str(); length = fragment_source.size(); glShaderSource(fragment_shader, 1, &source, &length); glCompileShader(fragment_shader); if(!check_shader_compile_status(fragment_shader)) { return 1; } // create program shader_program = glCreateProgram(); // attach shaders glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); // link the program and check for errors glLinkProgram(shader_program); if(!check_program_link_status(shader_program)) { return 1; } // vao and vbo handle GLuint vao, vbo; // generate and bind the vao glGenVertexArrays(1, &vao); glBindVertexArray(vao); // generate and bind the buffer object glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); // data for a fullscreen quad GLfloat vertexData[] = { // X Y Z R G B 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, // vertex 0 -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // vertex 1 1.0f,-1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // vertex 2 1.0f,-1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // vertex 3 -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // vertex 4 -1.0f,-1.0f, 0.0f, 1.0f, 0.0f, 0.0f, // vertex 5 }; // 6 vertices with 6 components (floats) each // fill with data glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*6*6, vertexData, GL_STATIC_DRAW); // set up generic attrib pointers glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 3*sizeof(GLfloat)); bool closed = false; while(!closed) { sf::Event event; while(window.pollEvent(event)) { if(event.type == sf::Event::Closed) { closed = true; } } // clear first glClear(GL_COLOR_BUFFER_BIT); // use the shader program glUseProgram(shader_program); // bind the vao glBindVertexArray(vao); // draw glDrawArrays(GL_TRIANGLES, 0, 6); // check for errors GLenum error = glGetError(); if(error != GL_NO_ERROR) { std::cerr << error << std::endl; break; } // finally swap buffers window.display(); } // delete the created objects glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDetachShader(shader_program, vertex_shader); glDetachShader(shader_program, fragment_shader); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(shader_program); return 0; }
void glOutlineDrawArrays(GLenum mode, GLint first, GLsizei count) { if(mode == GL_POLYGON) mode = GL_LINE_LOOP; if(mode == GL_POINTS || mode == GL_LINE_STRIP || mode == GL_LINE_LOOP || mode == GL_LINES) glDrawArrays( mode, first, count ); else { glBegin(GL_LINES); if(mode == GL_TRIANGLE_STRIP) { U32 i; for(i = 0; i < count - 1; i++) { glArrayElement(first + i); glArrayElement(first + i + 1); if(i + 2 != count) { glArrayElement(first + i); glArrayElement(first + i + 2); } } } else if(mode == GL_TRIANGLE_FAN) { for(U32 i = 1; i < count; i ++) { glArrayElement(first); glArrayElement(first + i); if(i != count - 1) { glArrayElement(first + i); glArrayElement(first + i + 1); } } } else if(mode == GL_TRIANGLES) { for(U32 i = 3; i <= count; i += 3) { glArrayElement(first + i - 3); glArrayElement(first + i - 2); glArrayElement(first + i - 2); glArrayElement(first + i - 1); glArrayElement(first + i - 3); glArrayElement(first + i - 1); } } else if(mode == GL_QUADS) { for(U32 i = 4; i <= count; i += 4) { glArrayElement(first + i - 4); glArrayElement(first + i - 3); glArrayElement(first + i - 3); glArrayElement(first + i - 2); glArrayElement(first + i - 2); glArrayElement(first + i - 1); glArrayElement(first + i - 4); glArrayElement(first + i - 1); } } else if(mode == GL_QUAD_STRIP) { if(count < 4) return; glArrayElement(first + 0); glArrayElement(first + 1); for(U32 i = 4; i <= count; i += 2) { glArrayElement(first + i - 4); glArrayElement(first + i - 2); glArrayElement(first + i - 3); glArrayElement(first + i - 1); glArrayElement(first + i - 2); glArrayElement(first + i - 1); } } glEnd(); } }
bool render( const simd::matx4& mv, const simd::vect3 (& end)[2], const simd::vect4& color) { // sign-invert z in all rows, for GL screen space const GLfloat mvp[4][4] = { { mv[0][0], mv[0][1], -mv[0][2], 0.f }, { mv[1][0], mv[1][1], -mv[1][2], 0.f }, { mv[2][0], mv[2][1], -mv[2][2], 0.f }, { mv[3][0], mv[3][1], -mv[3][2], 1.f } }; const GLfloat point[][3] = { { end[0][0], end[0][1], end[0][2] }, { end[1][0], end[1][1], end[1][2] } }; const GLfloat shade[] = { color[0], color[1], color[2], color[3] }; // prepare and issue the drawcall glUseProgram(g_shader_prog[PROG_LINE]); DEBUG_GL_ERR() if (-1 != g_uni[PROG_LINE][UNI_MVP]) { glUniformMatrix4fv(g_uni[PROG_LINE][UNI_MVP], 1, GL_FALSE, mvp[0]); } DEBUG_GL_ERR() if (-1 != g_uni[PROG_LINE][UNI_COLOR]) { glUniform4fv(g_uni[PROG_LINE][UNI_COLOR], 1, shade); } DEBUG_GL_ERR() if (-1 != g_uni[PROG_LINE][UNI_END_POINTS]) { glUniform3fv(g_uni[PROG_LINE][UNI_END_POINTS], 2, point[0]); } DEBUG_GL_ERR() glBindVertexArray(g_vao[PROG_LINE]); DEBUG_GL_ERR() for (unsigned i = 0; i < g_active_attr_semantics[PROG_LINE].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_LINE].active_attr[i]); DEBUG_GL_ERR() glDrawArrays(GL_LINES, 0, 2); DEBUG_GL_ERR() for (unsigned i = 0; i < g_active_attr_semantics[PROG_LINE].num_active_attr; ++i) glDisableVertexAttribArray(g_active_attr_semantics[PROG_LINE].active_attr[i]); DEBUG_GL_ERR() return true; }
//---------------------------------------------------------------------- // Draw the cover //---------------------------------------------------------------------- void C_Cover::Draw() { if (0 == vOfs) return; glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,txd.wd,txd.ht,0,GL_RGBA,GL_UNSIGNED_BYTE,txd.rgba); glDrawArrays(GL_TRIANGLE_STRIP,vOfs,4); return; }
int main(int argc, char** argv) { if (!glfwInit()) // 初始化glfw库 { std::cout << "Error::GLFW could not initialize GLFW!" << std::endl; return -1; } // 开启OpenGL 3.3 core profile std::cout << "Start OpenGL core profile version 3.3" << std::endl; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_SAMPLES, 4); // 设置采样点个数 注意这里设置GLFW选项 不要写成了GL_SAMPLES // 创建窗口 GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo of anti-aliasing(press O on, F off)", NULL, NULL); if (!window) { std::cout << "Error::GLFW could not create winddow!" << std::endl; glfwTerminate(); std::system("pause"); return -1; } // 创建的窗口的context指定为当前context glfwMakeContextCurrent(window); // 注册窗口键盘事件回调函数 glfwSetKeyCallback(window, key_callback); // 注册鼠标事件回调函数 glfwSetCursorPosCallback(window, mouse_move_callback); // 注册鼠标滚轮事件回调函数 glfwSetScrollCallback(window, mouse_scroll_callback); // 鼠标捕获 停留在程序内 glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // 初始化GLEW 获取OpenGL函数 glewExperimental = GL_TRUE; // 让glew获取所有拓展函数 GLenum status = glewInit(); if (status != GLEW_OK) { std::cout << "Error::GLEW glew version:" << glewGetString(GLEW_VERSION) << " error string:" << glewGetErrorString(status) << std::endl; glfwTerminate(); std::system("pause"); return -1; } // 设置视口参数 glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); //Section1 顶点属性数据 // 指定立方体顶点属性数据 顶点位置 纹理 GLfloat cubeVertices[] = { -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // A 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // B 0.5f, 0.5f, 0.5f,1.0f, 1.0f, // C 0.5f, 0.5f, 0.5f,1.0f, 1.0f, // C -0.5f, 0.5f, 0.5f,0.0f, 1.0f, // D -0.5f, -0.5f, 0.5f,0.0f, 0.0f, // A -0.5f, -0.5f, -0.5f,0.0f, 0.0f, // E -0.5f, 0.5f, -0.5f,0.0, 1.0f, // H 0.5f, 0.5f, -0.5f,1.0f, 1.0f, // G 0.5f, 0.5f, -0.5f,1.0f, 1.0f, // G 0.5f, -0.5f, -0.5f,1.0f, 0.0f, // F -0.5f, -0.5f, -0.5f,0.0f, 0.0f, // E -0.5f, 0.5f, 0.5f,0.0f, 1.0f, // D -0.5f, 0.5f, -0.5f,1.0, 1.0f, // H -0.5f, -0.5f, -0.5f,1.0f, 0.0f, // E -0.5f, -0.5f, -0.5f,1.0f, 0.0f, // E -0.5f, -0.5f, 0.5f,0.0f, 0.0f, // A -0.5f, 0.5f, 0.5f,0.0f, 1.0f, // D 0.5f, -0.5f, -0.5f,1.0f, 0.0f, // F 0.5f, 0.5f, -0.5f,1.0f, 1.0f, // G 0.5f, 0.5f, 0.5f,0.0f, 1.0f, // C 0.5f, 0.5f, 0.5f,0.0f, 1.0f, // C 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // B 0.5f, -0.5f, -0.5f,1.0f, 0.0f, // F 0.5f, 0.5f, -0.5f,1.0f, 1.0f, // G -0.5f, 0.5f, -0.5f,0.0, 1.0f, // H -0.5f, 0.5f, 0.5f,0.0f, 0.0f, // D -0.5f, 0.5f, 0.5f,0.0f, 0.0f, // D 0.5f, 0.5f, 0.5f,1.0f, 0.0f, // C 0.5f, 0.5f, -0.5f,1.0f, 1.0f, // G -0.5f, -0.5f, 0.5f,0.0f, 0.0f, // A -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,// E 0.5f, -0.5f, -0.5f,1.0f, 1.0f, // F 0.5f, -0.5f, -0.5f,1.0f, 1.0f, // F 0.5f, -0.5f, 0.5f,1.0f, 0.0f, // B -0.5f, -0.5f, 0.5f,0.0f, 0.0f, // A }; // Section2 准备缓存对象 GLuint cubeVAOId, cubeVBOId; glGenVertexArrays(1, &cubeVAOId); glGenBuffers(1, &cubeVBOId); glBindVertexArray(cubeVAOId); glBindBuffer(GL_ARRAY_BUFFER, cubeVBOId); glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW); // 顶点位置数据 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GL_FLOAT), (GLvoid*)0); glEnableVertexAttribArray(0); // 顶点纹理数据 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GL_FLOAT), (GLvoid*)(3 * sizeof(GL_FLOAT))); glEnableVertexAttribArray(1); glBindVertexArray(0); // Section3 准备着色器程序 Shader shader("scene.vertex", "scene.frag"); glEnable(GL_MULTISAMPLE); // 开启multisample glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); // 开始游戏主循环 while (!glfwWindowShouldClose(window)) { GLfloat currentFrame = (GLfloat)glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); // 处理例如鼠标 键盘等事件 do_movement(); // 根据用户操作情况 更新相机属性 glClearColor(0.18f, 0.04f, 0.14f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shader.use(); glm::mat4 projection = glm::perspective(camera.mouse_zoom, (GLfloat)(WINDOW_WIDTH) / WINDOW_HEIGHT, 1.0f, 100.0f); // 投影矩阵 glm::mat4 view = camera.getViewMatrix(); // 视变换矩阵 glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"), 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 model; model = glm::mat4(); model = glm::rotate(model, glm::radians(45.0f), glm::vec3(0.0f, 1.0f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"), 1, GL_FALSE, glm::value_ptr(model)); // 这里填写场景绘制代码 glBindVertexArray(cubeVAOId); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glBindVertexArray(0); glUseProgram(0); glfwSwapBuffers(window); // 交换缓存 } // 释放资源 glDeleteVertexArrays(1, &cubeVAOId); glDeleteBuffers(1, &cubeVBOId); glfwTerminate(); return 0; }