void SurfaceSdlGraphicsManager::updateScreen() {
#ifdef USE_OPENGL
	if (_opengl) {
		if (_overlayVisible) {
			if (_overlayDirty) {
				// remove if already exist
				if (_overlayNumTex > 0) {
					glDeleteTextures(_overlayNumTex, _overlayTexIds);
					delete[] _overlayTexIds;
					_overlayNumTex = 0;
				}

				_overlayNumTex = ((_overlayWidth + (BITMAP_TEXTURE_SIZE - 1)) / BITMAP_TEXTURE_SIZE) *
								((_overlayHeight + (BITMAP_TEXTURE_SIZE - 1)) / BITMAP_TEXTURE_SIZE);
				_overlayTexIds = new GLuint[_overlayNumTex];
				glGenTextures(_overlayNumTex, _overlayTexIds);
				for (int i = 0; i < _overlayNumTex; i++) {
					glBindTexture(GL_TEXTURE_2D, _overlayTexIds[i]);
					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);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
					glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, BITMAP_TEXTURE_SIZE, BITMAP_TEXTURE_SIZE, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL);
				}

				glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
				glPixelStorei(GL_UNPACK_ROW_LENGTH, _overlayWidth);

				int curTexIdx = 0;
				for (int y = 0; y < _overlayHeight; y += BITMAP_TEXTURE_SIZE) {
					for (int x = 0; x < _overlayWidth; x += BITMAP_TEXTURE_SIZE) {
						int t_width = (x + BITMAP_TEXTURE_SIZE >= _overlayWidth) ? (_overlayWidth - x) : BITMAP_TEXTURE_SIZE;
						int t_height = (y + BITMAP_TEXTURE_SIZE >= _overlayHeight) ? (_overlayHeight - y) : BITMAP_TEXTURE_SIZE;
						glBindTexture(GL_TEXTURE_2D, _overlayTexIds[curTexIdx]);
						glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, t_width, t_height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, (byte *)_overlayscreen->pixels + (y * 2 * _overlayWidth) + (2 * x));
						curTexIdx++;
					}
				}
				glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
				glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
			}

			// Save current state
			glPushAttrib(GL_TRANSFORM_BIT | GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_SCISSOR_BIT);

			// prepare view
			glMatrixMode(GL_PROJECTION);
			glPushMatrix();
			glLoadIdentity();
			glOrtho(0, _overlayWidth, _overlayHeight, 0, 0, 1);

			glMatrixMode(GL_MODELVIEW);
			glPushMatrix();
			glLoadIdentity();

			glMatrixMode(GL_TEXTURE);
			glPushMatrix();
			glLoadIdentity();

			glDisable(GL_LIGHTING);
			glEnable(GL_TEXTURE_2D);
			glDisable(GL_DEPTH_TEST);
			glDepthMask(GL_FALSE);
			glEnable(GL_SCISSOR_TEST);

			glScissor(0, 0, _overlayWidth, _overlayHeight);

			int curTexIdx = 0;
			for (int y = 0; y < _overlayHeight; y += BITMAP_TEXTURE_SIZE) {
				for (int x = 0; x < _overlayWidth; x += BITMAP_TEXTURE_SIZE) {
					glBindTexture(GL_TEXTURE_2D, _overlayTexIds[curTexIdx]);
					glBegin(GL_QUADS);
					glTexCoord2f(0, 0);
					glVertex2i(x, y);
					glTexCoord2f(1.0f, 0.0f);
					glVertex2i(x + BITMAP_TEXTURE_SIZE, y);
					glTexCoord2f(1.0f, 1.0f);
					glVertex2i(x + BITMAP_TEXTURE_SIZE, y + BITMAP_TEXTURE_SIZE);
					glTexCoord2f(0.0f, 1.0f);
					glVertex2i(x, y + BITMAP_TEXTURE_SIZE);
					glEnd();
					curTexIdx++;
				}
			}

			// Restore previous state
			glMatrixMode(GL_PROJECTION);
			glPopMatrix();

			glMatrixMode(GL_MODELVIEW);
			glPopMatrix();

			glMatrixMode(GL_TEXTURE);
			glPopMatrix();

			glPopAttrib();
		}
		SDL_GL_SwapBuffers();
	} else
#endif
	{
		if (_overlayVisible) {
			SDL_LockSurface(_screen);
			SDL_LockSurface(_overlayscreen);
			Graphics::PixelBuffer srcBuf(_overlayFormat, (byte *)_overlayscreen->pixels);
			Graphics::PixelBuffer dstBuf(_screenFormat, (byte *)_screen->pixels);
			int h = _overlayHeight;

			do {
				dstBuf.copyBuffer(0, _overlayWidth, srcBuf);

				srcBuf.shiftBy(_overlayWidth);
				dstBuf.shiftBy(_overlayWidth);
			} while (--h);
			SDL_UnlockSurface(_screen);
			SDL_UnlockSurface(_overlayscreen);
		}
		SDL_Flip(_screen);
	}
}
Esempio n. 2
0
int main()
{
    glfwInit();
    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);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "LearnOpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);



    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // Options
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, screenWidth, screenHeight);

    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);

    // Setup and compile our shaders
    Shader shader("./advanced.vs", "./advanced.frag");
    Shader skyboxShader("./skybox.vs", "./skybox.frag");

    #pragma region "object_initialization"
    // Set the object data (buffers, vertex attributes)
    GLfloat vertices[] = {
        -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
        0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
        0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
        0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,

        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
        0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
        0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
        0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
        -0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,

        -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,
        -0.5f,  0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
        -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
        -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
        -0.5f, -0.5f,  0.5f, -1.0f,  0.0f,  0.0f,
        -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,

        0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,
        0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
        0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
        0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
        0.5f, -0.5f,  0.5f,  1.0f,  0.0f,  0.0f,
        0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,

        -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,
        0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,
        0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
        0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,

        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,
        0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,
        0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
        0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
        -0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f
    };
    GLfloat skyboxVertices[] = {
        // Positions
        -1.0f,  1.0f, -1.0f,
        -1.0f, -1.0f, -1.0f,
        1.0f, -1.0f, -1.0f,
        1.0f, -1.0f, -1.0f,
        1.0f,  1.0f, -1.0f,
        -1.0f,  1.0f, -1.0f,

        -1.0f, -1.0f,  1.0f,
        -1.0f, -1.0f, -1.0f,
        -1.0f,  1.0f, -1.0f,
        -1.0f,  1.0f, -1.0f,
        -1.0f,  1.0f,  1.0f,
        -1.0f, -1.0f,  1.0f,

        1.0f, -1.0f, -1.0f,
        1.0f, -1.0f,  1.0f,
        1.0f,  1.0f,  1.0f,
        1.0f,  1.0f,  1.0f,
        1.0f,  1.0f, -1.0f,
        1.0f, -1.0f, -1.0f,

        -1.0f, -1.0f,  1.0f,
        -1.0f,  1.0f,  1.0f,
        1.0f,  1.0f,  1.0f,
        1.0f,  1.0f,  1.0f,
        1.0f, -1.0f,  1.0f,
        -1.0f, -1.0f,  1.0f,

        -1.0f,  1.0f, -1.0f,
        1.0f,  1.0f, -1.0f,
        1.0f,  1.0f,  1.0f,
        1.0f,  1.0f,  1.0f,
        -1.0f,  1.0f,  1.0f,
        -1.0f,  1.0f, -1.0f,

        -1.0f, -1.0f, -1.0f,
        -1.0f, -1.0f,  1.0f,
        1.0f, -1.0f, -1.0f,
        1.0f, -1.0f, -1.0f,
        -1.0f, -1.0f,  1.0f,
        1.0f, -1.0f,  1.0f
    };

    // Setup cube VAO
    GLuint cubeVAO, cubeVBO;
    glGenVertexArrays(1, &cubeVAO);
    glGenBuffers(1, &cubeVBO);
    glBindVertexArray(cubeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glBindVertexArray(0);
    // Setup skybox VAO
    GLuint skyboxVAO, skyboxVBO;
    glGenVertexArrays(1, &skyboxVAO);
    glGenBuffers(1, &skyboxVBO);
    glBindVertexArray(skyboxVAO);
    glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glBindVertexArray(0);

    // Load textures
    GLuint cubeTexture = loadTexture("./container.jpg");
    #pragma endregion

    // Cubemap (Skybox)
    vector<const GLchar*> faces;
    faces.push_back("skybox/right.jpg");
    faces.push_back("skybox/left.jpg");
    faces.push_back("skybox/top.jpg");
    faces.push_back("skybox/bottom.jpg");
    faces.push_back("skybox/back.jpg");
    faces.push_back("skybox/front.jpg");
    GLuint cubemapTexture = loadCubemap(faces);

    while (!glfwWindowShouldClose(window))
    {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // Check and call events
        glfwPollEvents();
        Do_Movement();

        // Clear buffers
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


        // Draw skybox first
        glDepthMask(GL_FALSE);// Remember to turn depth writing off
        skyboxShader.Use();
        glm::mat4 view = glm::mat4(glm::mat3(camera.GetViewMatrix()));	// Remove any translation component of the view matrix
        glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth/(float)screenHeight, 0.1f, 100.0f);
        glUniformMatrix4fv(glGetUniformLocation(skyboxShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(skyboxShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        // skybox cube
        glBindVertexArray(skyboxVAO);
        glActiveTexture(GL_TEXTURE0);
        glUniform1i(glGetUniformLocation(shader.Program, "skybox"), 0);
        glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
        glDrawArrays(GL_TRIANGLES, 0, 36);
        glBindVertexArray(0);
        glDepthMask(GL_TRUE);

        // Then draw scene as normal
        shader.Use();
        glm::mat4 model;
        view = camera.GetViewMatrix();

        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        // Cubes
        glBindVertexArray(cubeVAO);
        glActiveTexture(GL_TEXTURE0);
        glUniform1i(glGetUniformLocation(shader.Program, "skybox"), 0);
        glUniform3f(glGetUniformLocation(shader.Program, "cameraPos"), camera.Position.x, camera.Position.y, camera.Position.z);
        glBindTexture(GL_TEXTURE_2D, cubeTexture);
        glDrawArrays(GL_TRIANGLES, 0, 36);
        glBindVertexArray(0);


        // Swap the buffers
        glfwSwapBuffers(window);
    }

    return 0;
}
Esempio n. 3
0
void Camera::clearBackground(float depth)
{
    GLboolean oldDepthTest;
    GLint oldDepthFunc;
    GLboolean oldDepthMask;
    {
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
        glStencilMask(0);

        oldDepthTest = glIsEnabled(GL_DEPTH_TEST);
        glGetIntegerv(GL_DEPTH_FUNC, &oldDepthFunc);
        glGetBooleanv(GL_DEPTH_WRITEMASK, &oldDepthMask);

        glDepthMask(GL_TRUE);
        glEnable(GL_DEPTH_TEST);
        glDepthFunc(GL_ALWAYS);
    }

    //draw
    static V3F_C4B_T2F_Quad quad;
    quad.bl.vertices = Vec3(-1,-1,0);
    quad.br.vertices = Vec3(1,-1,0);
    quad.tl.vertices = Vec3(-1,1,0);
    quad.tr.vertices = Vec3(1,1,0);
    
    quad.bl.colors = quad.br.colors = quad.tl.colors = quad.tr.colors = Color4B(0,0,0,1);
    
    quad.bl.texCoords = Tex2F(0,0);
    quad.br.texCoords = Tex2F(1,0);
    quad.tl.texCoords = Tex2F(0,1);
    quad.tr.texCoords = Tex2F(1,1);
    
    auto shader = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_CAMERA_CLEAR);
    auto programState = GLProgramState::getOrCreateWithGLProgram(shader);
    programState->setUniformFloat("depth", 1.0);
    programState->apply(Mat4());
    GLshort indices[6] = {0, 1, 2, 3, 2, 1};
    
    {
        GL::bindVAO(0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        
        GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
        
        // vertices
        glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(V3F_C4B_T2F), &quad.tl.vertices);
        
        // colors
        glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V3F_C4B_T2F), &quad.tl.colors);
        
        // tex coords
        glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(V3F_C4B_T2F), &quad.tl.texCoords);
        
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices);
    }

    
    {
        if(GL_FALSE == oldDepthTest)
        {
            glDisable(GL_DEPTH_TEST);
        }
        glDepthFunc(oldDepthFunc);

        if(GL_FALSE == oldDepthMask)
        {
            glDepthMask(GL_FALSE);
        }

        /* IMPORTANT: We only need to update the states that are not restored.
         Since we don't know what was the previous value of the mask, we update the RenderState
         after setting it.
         The other values don't need to be updated since they were restored to their original values
         */
        glStencilMask(0xFFFFF);
//        RenderState::StateBlock::_defaultState->setStencilWrite(0xFFFFF);

        /* BUG: RenderState does not support glColorMask yet. */
        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    }
}
Esempio n. 4
0
void SampleGLView::gInit(void)
{
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);
}
Esempio n. 5
0
void SkyBox::draw(float x,float y,float z) {
  //Turn our world a bit, but first push the matrixes so others won't get into a strange position :P
  glPushMatrix();

  glPushAttrib(GL_ENABLE_BIT);
  //Disable the depth test so we can draw this in infinity
  glDepthMask(false);
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_LIGHTING);
  glDisable(GL_BLEND);

  glTranslatef(0.0f, y, 0.0f);

  //Draw some nice _large_ sky (the 100.0f scale might seem a bit large, but you have to prepare for odd camera settings too)
  glEnable(GL_TEXTURE_2D);

  glScalef(100.0f, 100.0f, 100.0f);
  glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

  const float cz = -0.0f;
  const float cx = 1.0f;
  const float r = 1.0f;

  // FRONT Side
  glBindTexture(GL_TEXTURE_2D,textures[0]);
  glBegin(GL_QUADS);
  glTexCoord2f(cx, cz); glVertex3f( -r,  r,  r);
  glTexCoord2f(cz, cz); glVertex3f(  r,  r,  r);
  glTexCoord2f(cz, cx); glVertex3f(  r, -r,  r); 
  glTexCoord2f(cx, cx); glVertex3f( -r, -r,  r);
  glEnd();

  // BACK side
  glBindTexture(GL_TEXTURE_2D,textures[2]);
  glBegin(GL_QUADS);
  glTexCoord2f(cx, cz);  glVertex3f(  r,  r, -r);
  glTexCoord2f(cz, cz);  glVertex3f( -r,  r, -r);
  glTexCoord2f(cz, cx);  glVertex3f( -r, -r, -r); 
  glTexCoord2f(cx, cx);  glVertex3f(  r, -r, -r);
  glEnd();

  // Left side
  glBindTexture(GL_TEXTURE_2D,textures[3]);
  glBegin(GL_QUADS);
  glTexCoord2f(cx,cz); glVertex3f( -r,  r, -r);
  glTexCoord2f(cz,cz); glVertex3f( -r,  r,  r); 
  glTexCoord2f(cz,cx); glVertex3f( -r, -r,  r);
  glTexCoord2f(cx,cx); glVertex3f( -r, -r, -r);
  glEnd();
 
  // Right side
  glBindTexture(GL_TEXTURE_2D,textures[1]);
  glBegin(GL_QUADS);
  glTexCoord2f(cx, cz); glVertex3f(  r,  r,  r);
  glTexCoord2f(cz, cz); glVertex3f(  r,  r, -r); 
  glTexCoord2f(cz, cx); glVertex3f(  r, -r, -r);
  glTexCoord2f(cx, cx); glVertex3f(  r, -r,  r);
  glEnd();

  // Up side
  glBindTexture(GL_TEXTURE_2D,textures[4]);
  glBegin(GL_QUADS);
  glTexCoord2f(cx, cz); glVertex3f( -r,  r, -r);
  glTexCoord2f(cz, cz); glVertex3f(  r,  r, -r); 
  glTexCoord2f(cz, cx); glVertex3f(  r,  r,  r);
  glTexCoord2f(cx, cx); glVertex3f( -r,  r,  r);
  glEnd();
 
  // Down side
  glBindTexture(GL_TEXTURE_2D,textures[5]);
  glBegin(GL_QUADS);
  glTexCoord2f(cx, cz); glVertex3f( -r, -r,  r);
  glTexCoord2f(cz, cz); glVertex3f(  r, -r,  r); 
  glTexCoord2f(cz, cx); glVertex3f(  r, -r, -r);
  glTexCoord2f(cx, cx); glVertex3f( -r, -r, -r);
  glEnd();

  //Back to where we were
  glDepthMask(true);
  glPopAttrib();
  glPopMatrix();
}
Esempio n. 6
0
static void draw_galaxy(int i, int j, int f, float a)
{
    struct galaxy *g = get_galaxy(i);
    float V[6][4];
    float p[4] = { 0.0, 0.0, 0.0, 1.0 };

    init_galaxy(i);

    glPushMatrix();
    {
        /* Apply the local coordinate system transformation. */

        transform_entity(j);
        get_viewfrust(V);
        get_viewpoint(p);

        /* Supply the view position as a vertex program parameter. */

        if (GL_has_vertex_program)
            glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 0,
                                       p[0], p[1], p[2], p[3]);

        glPushAttrib(GL_ENABLE_BIT       |
                     GL_TEXTURE_BIT      |
                     GL_DEPTH_BUFFER_BIT |
                     GL_COLOR_BUFFER_BIT);
        glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
        {
            /* Set up the GL state for star rendering. */

            draw_brush(g->brush, a * get_entity_alpha(j));

            glBindTexture(GL_TEXTURE_2D, g->texture);

            glDisable(GL_TEXTURE_2D);
            glDisable(GL_LIGHTING);
            glEnable(GL_COLOR_MATERIAL);

            glDepthMask(GL_FALSE);
            glBlendFunc(GL_ONE, GL_ONE);

            if (GL_has_vertex_program)
                glEnable(GL_VERTEX_PROGRAM_POINT_SIZE_ARB);

            if (GL_has_point_sprite)
            {
                glEnable(GL_POINT_SPRITE_ARB);
                glTexEnvi(GL_POINT_SPRITE_ARB,
                          GL_COORD_REPLACE_ARB, GL_TRUE);
            }

            draw_arrays(i);

            /* Render all stars. */

            node_draw(g->N, 0, 0, V);
        }
        glPopClientAttrib();
        glPopAttrib();

        /* Render all child entities in this coordinate system. */

        draw_entity_tree(j, f, a * get_entity_alpha(j));
    }
    glPopMatrix();
}
Esempio n. 7
0
// Draws the FBO texture for Oculus rift.
void ApplicationOverlay::displayOverlayTextureOculus(Camera& whichCamera) {
    if (_alpha == 0.0f) {
        return;
    }
    glEnable(GL_TEXTURE_2D);
    glActiveTexture(GL_TEXTURE0);
    _overlays.bindTexture();
    
    glEnable(GL_BLEND);
    glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_ONE);
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);
    glDisable(GL_LIGHTING);
    glEnable(GL_ALPHA_TEST);
    glAlphaFunc(GL_GREATER, 0.01f);
    
    
    //Update and draw the magnifiers
    MyAvatar* myAvatar = Application::getInstance()->getAvatar();
    const glm::quat& orientation = myAvatar->getOrientation();
    const glm::vec3& position = myAvatar->getDefaultEyePosition();
    const float scale = myAvatar->getScale() * _oculusUIRadius;
    
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix(); {
        glTranslatef(position.x, position.y, position.z);
        glm::mat4 rotation = glm::toMat4(orientation);
        glMultMatrixf(&rotation[0][0]);
        glScalef(scale, scale, scale);
        for (int i = 0; i < NUMBER_OF_RETICLES; i++) {
            
            if (_magActive[i]) {
                _magSizeMult[i] += MAG_SPEED;
                if (_magSizeMult[i] > 1.0f) {
                    _magSizeMult[i] = 1.0f;
                }
            } else {
                _magSizeMult[i] -= MAG_SPEED;
                if (_magSizeMult[i] < 0.0f) {
                    _magSizeMult[i] = 0.0f;
                }
            }
            
            if (_magSizeMult[i] > 0.0f) {
                //Render magnifier, but dont show border for mouse magnifier
                glm::vec2 projection = screenToOverlay(glm::vec2(_reticlePosition[MOUSE].x(),
                                                                 _reticlePosition[MOUSE].y()));
                
                renderMagnifier(projection, _magSizeMult[i], i != MOUSE);
            }
        }
        
        glDepthMask(GL_FALSE);
        glDisable(GL_ALPHA_TEST);
        
        glColor4f(1.0f, 1.0f, 1.0f, _alpha);
        
        static float textureFOV = 0.0f, textureAspectRatio = 1.0f;
        if (textureFOV != _textureFov ||
            textureAspectRatio != _textureAspectRatio) {
            textureFOV = _textureFov;
            textureAspectRatio = _textureAspectRatio;
            
            _overlays.buildVBO(_textureFov, _textureAspectRatio, 80, 80);
        }
        _overlays.render();
        renderPointersOculus(myAvatar->getDefaultEyePosition());
        
        glDepthMask(GL_TRUE);
        _overlays.releaseTexture();
        glDisable(GL_TEXTURE_2D);
        
        glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_ONE);
        glEnable(GL_LIGHTING);
    } glPopMatrix();
}
Esempio n. 8
0
void CShadowHandler::CreateShadows()
{
	fb.Bind();

	glDisable(GL_BLEND);
	glDisable(GL_LIGHTING);
	glDisable(GL_ALPHA_TEST);
	glDisable(GL_TEXTURE_2D);

	glShadeModel(GL_FLAT);
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
	glDepthMask(GL_TRUE);
	glEnable(GL_DEPTH_TEST);

	glViewport(0, 0, shadowMapSize, shadowMapSize);

	// glClearColor(0, 0, 0, 0);
	// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glClear(GL_DEPTH_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, 1, 0, 1, 0, -1);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();


	const ISkyLight* L = sky->GetLight();

	// sun direction is in world-space, invert it
	sunDirZ = -L->GetLightDir();
	sunDirX = (sunDirZ.cross(UpVector)).ANormalize();
	sunDirY = (sunDirX.cross(sunDirZ)).ANormalize();

	SetShadowMapSizeFactors();

	// NOTE:
	//     the xy-scaling factors from CalcMinMaxView do not change linearly
	//     or smoothly with camera movements, creating visible artefacts (eg.
	//     large jumps in shadow resolution)
	//
	//     therefore, EITHER use "fixed" scaling values such that the entire
	//     map barely fits into the sun's frustum (by pretending it is embedded
	//     in a sphere and taking its diameter), OR variable scaling such that
	//     everything that can be seen by the camera maximally fills the sun's
	//     frustum (choice of projection-style is left to the user and can be
	//     changed at run-time)
	//
	//     the first option means larger maps will have more blurred/aliased
	//     shadows if the depth buffer is kept at the same size, but no (map)
	//     geometry is ever omitted
	//
	//     the second option means shadows have higher average resolution, but
	//     become less sharp as the viewing volume increases (through eg.camera
	//     rotations) and geometry can be omitted in some cases
	//
	// NOTE:
	//     when DynamicSun is enabled, the orbit is always circular in the xz
	//     plane, instead of elliptical when the map has an aspect-ratio != 1
	//
	const float xyScale =
		(shadowProMode == SHADOWPROMODE_CAM_CENTER)? GetOrthoProjectedFrustumRadius(camera, centerPos):
		(shadowProMode == SHADOWPROMODE_MAP_CENTER)? GetOrthoProjectedMapRadius(-sunDirZ, centerPos):
		1.0f;
	const float xScale = xyScale;
	const float yScale = xyScale;
	const float zScale = globalRendering->viewRange;

	shadowMatrix[ 0] = sunDirX.x / xScale;
	shadowMatrix[ 1] = sunDirY.x / yScale;
	shadowMatrix[ 2] = sunDirZ.x / zScale;

	shadowMatrix[ 4] = sunDirX.y / xScale;
	shadowMatrix[ 5] = sunDirY.y / yScale;
	shadowMatrix[ 6] = sunDirZ.y / zScale;

	shadowMatrix[ 8] = sunDirX.z / xScale;
	shadowMatrix[ 9] = sunDirY.z / yScale;
	shadowMatrix[10] = sunDirZ.z / zScale;

	// rotate the target position into sun-space for the translation
	shadowMatrix[12] = (-sunDirX.dot(centerPos) / xScale);
	shadowMatrix[13] = (-sunDirY.dot(centerPos) / yScale);
	shadowMatrix[14] = (-sunDirZ.dot(centerPos) / zScale) + 0.5f;

	glLoadMatrixf(shadowMatrix.m);

	// set the shadow-parameter registers
	// NOTE: so long as any part of Spring rendering still uses
	// ARB programs at run-time, these lines can not be removed
	// (all ARB programs share the same environment)
	glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 16, shadowTexProjCenter.x, shadowTexProjCenter.y, 0.0f, 0.0f);
	glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 17, shadowTexProjCenter.z, shadowTexProjCenter.z, 0.0f, 0.0f);
	glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 18, shadowTexProjCenter.w, shadowTexProjCenter.w, 0.0f, 0.0f);

	if (globalRendering->haveGLSL) {
		for (int i = 0; i < SHADOWGEN_PROGRAM_LAST; i++) {
			shadowGenProgs[i]->Enable();
			shadowGenProgs[i]->SetUniform4fv(0, &shadowTexProjCenter.x);
			shadowGenProgs[i]->Disable();
		}
	}

	if (L->GetLightIntensity() > 0.0f) {
		// move view into sun-space
		const float3 oldup = camera->up;

		camera->right = sunDirX;
		camera->up = sunDirY;

		DrawShadowPasses();

		camera->up = oldup;
	}

	glShadeModel(GL_SMOOTH);
	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

	// we do this later to save render context switches (this is one of the slowest opengl operations!)
	// fb.Unbind();
	// glViewport(globalRendering->viewPosX,0,globalRendering->viewSizeX,globalRendering->viewSizeY);
}
Esempio n. 9
0
void DrawModels()
{
  GLint r, g, b;
  occlucedCount = 0;
  DrawOccluder();

  if (occlusionDetection)
  {
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_TEXTURE_GEN_S);
    glDisable(GL_TEXTURE_GEN_T);
    glDisable(GL_LIGHTING);
    glDisable(GL_COLOR_MATERIAL);
    glDepthMask(GL_FALSE);
    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    for (r = 0; r < 3; r++)
    {
      for (g = 0; g < 3; g++)
      {
        for (b = 0; b < 3; b++)
        {
          glPushMatrix();
          glTranslatef(100.0f * r - 100.0f,
            100.0f * g - 100.0f,
            100.0f * b - 100.0f);
          glBeginQuery(GL_SAMPLES_PASSED, queryIDs[(r*9)+(g*3)+b]);
          glutSolidCube(100.0f);
          glEndQuery(GL_SAMPLES_PASSED);
          glPopMatrix();
        }
      }
    }
     

    glDepthMask(GL_TRUE);
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    glEnable(GL_LIGHTING);
    glEnable(GL_COLOR_MATERIAL);
  }

  glEnable(GL_TEXTURE_2D);
  glEnable(GL_TEXTURE_GEN_S);;
  glEnable(GL_TEXTURE_GEN_T);

  for(r = 0; r < 3; r++)
  {
    for (g = 0; g < 3; g++)
    {
      for (b = 0; b < 3; b++)
      {
        glColor3f(r * 1.0f/3, g * 1.0f/3, b * 1.0f/3);

        glPushMatrix();
        glTranslatef(100.0f * r - 100.0f,
          100.0f * g - 100.0f,
          100.0f * b - 100.0f);
        DrawSphere((r*9)+(g*3)+b);
        glPopMatrix();
      }
    }
  }
  printf("occluced count is %d\n", occlucedCount);
  glDisable(GL_TEXTURE_2D);
  glDisable(GL_TEXTURE_GEN_T);
  glDisable(GL_TEXTURE_GEN_S);
}
Esempio n. 10
0
void CRender::enableDepthMask(void) {
	glDepthMask(GL_TRUE);
}
Esempio n. 11
0
void glPopAttrib() {
    ERROR_IN_BLOCK();
    glstack_t *cur = tack_pop(&state.stack.attrib);
    if (cur == NULL) {
        ERROR(GL_STACK_UNDERFLOW);
    }

    if (cur->mask & GL_COLOR_BUFFER_BIT) {
#ifndef USE_ES2
        enable_disable(GL_ALPHA_TEST, cur->alpha_test);
        glAlphaFunc(cur->alpha_test_func, cur->alpha_test_ref);
#endif

        enable_disable(GL_BLEND, cur->blend);
        glBlendFunc(cur->blend_src_func, cur->blend_dst_func);

        enable_disable(GL_DITHER, cur->dither);
#ifndef USE_ES2
        enable_disable(GL_COLOR_LOGIC_OP, cur->color_logic_op);
        glLogicOp(cur->logic_op);
#endif

        GLfloat *c;
        glClearColor(v4(cur->clear_color));
        glColorMask(v4(cur->color_mask));
    }

    if (cur->mask & GL_CURRENT_BIT) {
        glColor4f(v4(cur->color));
#ifndef USE_ES2
        glNormal3f(v3(cur->normal));
#endif
        for (int i = 0; i < MAX_TEX; i++) {
            glMultiTexCoord2f(GL_TEXTURE0 + i, v2(cur->tex[i]));
        }
    }

    if (cur->mask & GL_DEPTH_BUFFER_BIT) {
        enable_disable(GL_DEPTH_TEST, cur->depth_test);
        glDepthFunc(cur->depth_func);
        glClearDepth(cur->clear_depth);
        glDepthMask(cur->depth_mask);
    }

    if (cur->mask & GL_ENABLE_BIT) {
        int i;
        GLint max_clip_planes;
        glGetIntegerv(GL_MAX_CLIP_PLANES, &max_clip_planes);
        for (i = 0; i < max_clip_planes; i++) {
            enable_disable(GL_CLIP_PLANE0 + i, *(cur->clip_planes_enabled + i));
        }

        GLint max_lights;
        glGetIntegerv(GL_MAX_LIGHTS, &max_lights);
        for (i = 0; i < max_lights; i++) {
            enable_disable(GL_LIGHT0 + i, *(cur->lights_enabled + i));
        }

        enable_disable(GL_ALPHA_TEST, cur->alpha_test);
        enable_disable(GL_BLEND, cur->blend);
        enable_disable(GL_CULL_FACE, cur->cull_face);
        enable_disable(GL_DEPTH_TEST, cur->depth_test);
        enable_disable(GL_DITHER, cur->dither);
        enable_disable(GL_FOG, cur->fog);
        enable_disable(GL_LIGHTING, cur->lighting);
        enable_disable(GL_LINE_SMOOTH, cur->line_smooth);
        enable_disable(GL_LINE_STIPPLE, cur->line_stipple);
        enable_disable(GL_COLOR_LOGIC_OP, cur->color_logic_op);
        enable_disable(GL_MULTISAMPLE, cur->multisample);
        enable_disable(GL_NORMALIZE, cur->normalize);
        enable_disable(GL_POINT_SMOOTH, cur->point_smooth);
        enable_disable(GL_POLYGON_OFFSET_FILL, cur->polygon_offset_fill);
        enable_disable(GL_SAMPLE_ALPHA_TO_COVERAGE, cur->sample_alpha_to_coverage);
        enable_disable(GL_SAMPLE_ALPHA_TO_ONE, cur->sample_alpha_to_one);
        enable_disable(GL_SAMPLE_COVERAGE, cur->sample_coverage);
        enable_disable(GL_SCISSOR_TEST, cur->scissor_test);
        enable_disable(GL_STENCIL_TEST, cur->stencil_test);
        enable_disable(GL_TEXTURE_2D, cur->texture_2d);
    }

#ifndef USE_ES2
    if (cur->mask & GL_FOG_BIT) {
        enable_disable(GL_FOG, cur->fog);
        glFogfv(GL_FOG_COLOR, cur->fog_color);
        glFogf(GL_FOG_DENSITY, cur->fog_density);
        glFogf(GL_FOG_START, cur->fog_start);
        glFogf(GL_FOG_END, cur->fog_end);
        glFogf(GL_FOG_MODE, cur->fog_mode);
    }
#endif

    if (cur->mask & GL_HINT_BIT) {
        enable_disable(GL_PERSPECTIVE_CORRECTION_HINT, cur->perspective_hint);
        enable_disable(GL_POINT_SMOOTH_HINT, cur->point_smooth_hint);
        enable_disable(GL_LINE_SMOOTH_HINT, cur->line_smooth_hint);
        enable_disable(GL_FOG_HINT, cur->fog_hint);
        enable_disable(GL_GENERATE_MIPMAP_HINT, cur->mipmap_hint);
    }

    if (cur->mask & GL_LINE_BIT) {
        enable_disable(GL_LINE_SMOOTH, cur->line_smooth);
        // TODO: stipple stuff here
        glLineWidth(cur->line_width);
    }

    if (cur->mask & GL_MULTISAMPLE_BIT) {
        enable_disable(GL_MULTISAMPLE, cur->multisample);
        enable_disable(GL_SAMPLE_ALPHA_TO_COVERAGE, cur->sample_alpha_to_coverage);
        enable_disable(GL_SAMPLE_ALPHA_TO_ONE, cur->sample_alpha_to_one);
        enable_disable(GL_SAMPLE_COVERAGE, cur->sample_coverage);
    }

#ifndef USE_ES2
    if (cur->mask & GL_POINT_BIT) {
        enable_disable(GL_POINT_SMOOTH, cur->point_smooth);
        glPointSize(cur->point_size);
    }
#endif

    if (cur->mask & GL_SCISSOR_BIT) {
        enable_disable(GL_SCISSOR_TEST, cur->scissor_test);
        glScissor(v4(cur->scissor_box));
    }

    if (cur->mask & GL_TEXTURE_BIT) {
        glBindTexture(GL_TEXTURE_2D, cur->texture);
    }

    free(cur->clip_planes_enabled);
    free(cur->clip_planes);
    free(cur->lights_enabled);
    free(cur->lights);
    free(cur);
}
Esempio n. 12
0
void CRender::disableDepthMask(void) {
	glDepthMask(GL_FALSE);
}
Esempio n. 13
0
bool TextFont::PrepareForRender()
{
	if (!texture){
		std::cout<<"\nERROR: Texture not allocated in Font::RenderText";
		return false;
	}
	if (!whitened && false){ // Change so whitening process is executed only for those fonts which need it.
		MakeTextureWhite();
	}
	/// Bufferize texture as needed.
	if (texture->glid == -1)
	{
		texture->releaseOnBufferization = false;
		TexMan.BufferizeTexture(texture);
	}

	/// Prepare shader.
	if (shaderBased)
	{
		// Load shader.
		shader = ShadeMan.SetActiveShader("Font");
		if (!shader)
			return false;
		// Enable texture
		glEnable(GL_TEXTURE_2D);
		// Set matrices.
		shader->SetProjectionMatrix(graphicsState->projectionMatrixF);
		shader->SetViewMatrix(graphicsState->viewMatrixF);
		shader->SetModelMatrix(graphicsState->modelMatrixF);
		// Set text color
		glUniform4f(shader->uniformPrimaryColorVec4, color.x, color.y, color.z, color.w);
		
		// set hover state
		glUniform1i(shader->uniformHoveredOver, hoveredOver? 1 : 0);

		// Set some color.. hmm.
		// 		glColor4f(color[0], color[1], color[2], color[3]);
				glEnable(GL_BLEND);
		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		// Don't write depth to depth buffer.
		glDepthMask(GL_FALSE);
		glDisable(GL_DEPTH_TEST);

		// Set texture in shader? hm.
		glBindTexture(GL_TEXTURE_2D, texture->glid);

		// Fetch and bufferizes model.
		if (!model)
			model = ModelMan.GetModel("sprite.obj");
		model->BufferizeIfNeeded();
	}
	else 
	{
		// Enable textures if it wasn't already
		glEnable(GL_TEXTURE_2D);
		PrintGLError("Font.h: glEnable(GL_TEXTURE_2D) error");
		/// Set fill mode!
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

		ShadeMan.SetActiveShader(0);

		glEnable(GL_TEXTURE_2D);
	//	glEnable(GL_LIGHTING);
		glDisable(GL_COLOR_MATERIAL);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glLoadMatrixf(graphicsState->projectionMatrixF.getPointer());
		Matrix4f modelView = graphicsState->viewMatrixF * graphicsState->modelMatrixF;
		glMatrixMode(GL_MODELVIEW);
		glLoadMatrixf(modelView.getPointer());
		glColor4f(color[0], color[1], color[2], color[3]);
		glEnable(GL_BLEND);
		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		glDisable(GL_LIGHTING);

		// Disable depth test.. lol no?
	//	glDisable(GL_DEPTH_TEST);
		glDepthMask(GL_FALSE);

		glBindTexture(GL_TEXTURE_2D, texture->glid);

				// when texture area is small, bilinear filter the closest mipmap
		// when texture area is large, bilinear filter the original
		bool linear = false;
		if (linear){
			glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
			glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		}
		else {
			glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
			glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		}


	//	glUseProgram(shader->shaderProgram);
		/// Begin the QUADS!
		glBegin(GL_QUADS);
	}

	return true;
}
Esempio n. 14
0
/*
==============
RenderBumpFlat_f

==============
*/
void RenderBumpFlat_f( const idCmdArgs &args ) {
	int		width, height;
	idStr	source;
	int		i;
	idBounds	bounds;
	srfTriangles_t	*mesh;
	float	boundsScale;

	// update the screen as we print
	common->SetRefreshOnPrint( true );

	width = height = 256;
	boundsScale = 0;

	// check options
	for ( i = 1 ; i < args.Argc() - 1; i++ ) {
		const char *s;

		s = args.Argv( i );
		if ( s[0] == '-' ) {
			i++;
			s = args.Argv( i );
		}

		if ( !idStr::Icmp( s, "size" ) ) {
			if ( i + 2 >= args.Argc() ) {
				i = args.Argc();
				break;
			}
			width = atoi( args.Argv( i + 1 ) );
			height = atoi( args.Argv( i + 2 ) );
			i += 2;
		} else {
			common->Printf( "WARNING: Unknown option \"%s\"\n", s );
			break;
		}
	}

	if ( i != ( args.Argc() - 1 ) ) {
		common->Error( "usage: renderBumpFlat [-size width height] asefile" );
	}

	common->Printf( "Final image size: %i, %i\n", width, height );

	// load the source in "fastload" mode, because we don't
	// need tangent and shadow information
	source = args.Argv( i );

	idRenderModel *highPolyModel = renderModelManager->AllocModel();

	highPolyModel->PartialInitFromFile( source );

	if ( highPolyModel->IsDefaultModel() ) {
		common->Error( "failed to load %s", source.c_str() );
	}

	// combine the high poly model into a single polyset
	if ( highPolyModel->NumSurfaces() != 1 ) {
		highPolyModel = CombineModelSurfaces( highPolyModel );
	}

	// create normals if not present in file
	const modelSurface_t *surf = highPolyModel->Surface( 0 );
	mesh = surf->geometry;

	// bound the entire file
	R_BoundTriSurf( mesh );
	bounds = mesh->bounds;

	SaveWindow();
	ResizeWindow( width, height );

	// for small images, the viewport may be less than the minimum window
	glViewport( 0, 0, width, height );

	glEnable( GL_CULL_FACE );
	glCullFace( GL_FRONT );
	glDisable( GL_STENCIL_TEST );	
	glDisable( GL_SCISSOR_TEST );	
	glDisable( GL_ALPHA_TEST );	
	glDisable( GL_BLEND );	
	glEnable( GL_DEPTH_TEST );
	glDisable( GL_TEXTURE_2D );
	glDepthMask( GL_TRUE );
	glDepthFunc( GL_LEQUAL );

	glColor3f( 1, 1, 1 );

  GL_ProjectionMatrix.LoadIdentity();
  GL_ProjectionMatrix.Ortho(bounds[0][0], bounds[1][0], bounds[0][2],
  bounds[1][2], -(bounds[0][1] - 1), -(bounds[1][1] + 1));

  GL_ModelViewMatrix.LoadIdentity();

	// flat maps are automatically anti-aliased

	idStr	filename;
	int		j, k, c;
	byte	*buffer;
	int		*sumBuffer, *colorSumBuffer;
	bool	flat;
	int		sample;

	sumBuffer = (int *)Mem_Alloc( width * height * 4 * 4 );
	memset( sumBuffer, 0, width * height * 4 * 4 );
	buffer = (byte *)Mem_Alloc( width * height * 4 );

	colorSumBuffer = (int *)Mem_Alloc( width * height * 4 * 4 );
	memset( sumBuffer, 0, width * height * 4 * 4 );

	flat = false;
//flat = true;

	for ( sample = 0 ; sample < 16 ; sample++ ) {
		float	xOff, yOff;

		xOff = ( ( sample & 3 ) / 4.0 ) * ( bounds[1][0] - bounds[0][0] ) / width;
		yOff = ( ( sample / 4 ) / 4.0 ) * ( bounds[1][2] - bounds[0][2] ) / height;

		for ( int colorPass = 0 ; colorPass < 2 ; colorPass++ ) {
			glClearColor(0.5,0.5,0.5,0);
			glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

			glBegin( GL_TRIANGLES );
			for ( i = 0 ; i < highPolyModel->NumSurfaces() ; i++ ) {
				const modelSurface_t *surf = highPolyModel->Surface( i );

				mesh = surf->geometry;

				if ( colorPass ) {
					// just render the surface color for artist visualization
					for ( j = 0 ; j < mesh->numIndexes ; j+=3 ) {
						for ( k = 0 ; k < 3 ; k++ ) {
							int		v;
							float	*a;

							v = mesh->indexes[j+k];
							glColor3ubv( mesh->verts[v].color );
							a = mesh->verts[v].xyz.ToFloatPtr();
							glVertex3f( a[0] + xOff, a[2] + yOff, a[1] );
						}
					}
				} else {
					// render as normal map
					// we can either flat shade from the plane,
					// or smooth shade from the vertex normals
					for ( j = 0 ; j < mesh->numIndexes ; j+=3 ) {
						if ( flat ) {
							idPlane		plane;
							idVec3		*a, *b, *c;
							int			v1, v2, v3;

							v1 = mesh->indexes[j+0];
							v2 = mesh->indexes[j+1];
							v3 = mesh->indexes[j+2];

							a = &mesh->verts[ v1 ].xyz;
							b = &mesh->verts[ v2 ].xyz;
							c = &mesh->verts[ v3 ].xyz;

							plane.FromPoints( *a, *b, *c );

							// NULLNORMAL is used by the artists to force an area to reflect no
							// light at all
							if ( surf->shader->GetSurfaceFlags() & SURF_NULLNORMAL ) {
								glColor3f( 0.5, 0.5, 0.5 );
							} else {
								glColor3f( 0.5 + 0.5*plane[0], 0.5 - 0.5*plane[2], 0.5 - 0.5*plane[1] );
							}

							glVertex3f( (*a)[0] + xOff, (*a)[2] + yOff, (*a)[1] );
							glVertex3f( (*b)[0] + xOff, (*b)[2] + yOff, (*b)[1] );
							glVertex3f( (*c)[0] + xOff, (*c)[2] + yOff, (*c)[1] );
						} else {
							for ( k = 0 ; k < 3 ; k++ ) {
								int		v;
								float	*n;
								float	*a;

								v = mesh->indexes[j+k];
								n = mesh->verts[v].normal.ToFloatPtr();

								// NULLNORMAL is used by the artists to force an area to reflect no
								// light at all
								if ( surf->shader->GetSurfaceFlags() & SURF_NULLNORMAL ) {
									glColor3f( 0.5, 0.5, 0.5 );
								} else {
								// we are going to flip the normal Z direction
									glColor3f( 0.5 + 0.5*n[0], 0.5 - 0.5*n[2], 0.5 - 0.5*n[1] );
								}

								a = mesh->verts[v].xyz.ToFloatPtr();
								glVertex3f( a[0] + xOff, a[2] + yOff, a[1] );
							}
						}
					}
				}
			}

			glEnd();
			glFlush();
			GLimp_SwapBuffers();
			glReadPixels( 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer ); 

			if ( colorPass ) {
				// add to the sum buffer
				for ( i = 0 ; i < c ; i++ ) {
					colorSumBuffer[i*4+0] += buffer[i*4+0];
					colorSumBuffer[i*4+1] += buffer[i*4+1];
					colorSumBuffer[i*4+2] += buffer[i*4+2];
					colorSumBuffer[i*4+3] += buffer[i*4+3];
				}
			} else {
				// normalize
				c = width * height;
				for ( i = 0 ; i < c ; i++ ) {
					idVec3	v;

					v[0] = ( buffer[i*4+0] - 128 ) / 127.0;
					v[1] = ( buffer[i*4+1] - 128 ) / 127.0;
					v[2] = ( buffer[i*4+2] - 128 ) / 127.0;

					v.Normalize();

					buffer[i*4+0] = 128 + 127 * v[0];
					buffer[i*4+1] = 128 + 127 * v[1];
					buffer[i*4+2] = 128 + 127 * v[2];
				}

				// outline into non-drawn areas
				for ( i = 0 ; i < 8 ; i++ ) {
					OutlineNormalMap( buffer, width, height, 128, 128, 128 );
				}

				// add to the sum buffer
				for ( i = 0 ; i < c ; i++ ) {
					sumBuffer[i*4+0] += buffer[i*4+0];
					sumBuffer[i*4+1] += buffer[i*4+1];
					sumBuffer[i*4+2] += buffer[i*4+2];
					sumBuffer[i*4+3] += buffer[i*4+3];
				}
			}
		}
	}

	c = width * height;

	// save out the color map
	for ( i = 0 ; i < c ; i++ ) {
		buffer[i*4+0] = colorSumBuffer[i*4+0] / 16;
		buffer[i*4+1] = colorSumBuffer[i*4+1] / 16;
		buffer[i*4+2] = colorSumBuffer[i*4+2] / 16;
		buffer[i*4+3] = colorSumBuffer[i*4+3] / 16;
	}
	filename = source;
	filename.StripFileExtension();
	filename.Append( "_color.tga" );
	R_VerticalFlip( buffer, width, height );
	R_WriteTGA( filename, buffer, width, height );

	// save out the local map
	// scale the sum buffer back down to the sample buffer
	// we allow this to denormalize
	for ( i = 0 ; i < c ; i++ ) {
		buffer[i*4+0] = sumBuffer[i*4+0] / 16;
		buffer[i*4+1] = sumBuffer[i*4+1] / 16;
		buffer[i*4+2] = sumBuffer[i*4+2] / 16;
		buffer[i*4+3] = sumBuffer[i*4+3] / 16;
	}

	filename = source;
	filename.StripFileExtension();
	filename.Append( "_local.tga" );
	common->Printf( "writing %s (%i,%i)\n", filename.c_str(), width, height );
	R_VerticalFlip( buffer, width, height );
	R_WriteTGA( filename, buffer, width, height );


	// free the model
	renderModelManager->FreeModel( highPolyModel );

	// free our work buffer
	Mem_Free( buffer );
	Mem_Free( sumBuffer );
	Mem_Free( colorSumBuffer );

	RestoreWindow();

	// stop updating the screen as we print
	common->SetRefreshOnPrint( false );

	common->Error( "Completed." );
}
Esempio n. 15
0
static void draw_particles(GLFWwindow* window, double t, float dt)
{
    int i, particle_count;
    Vertex vertex_array[BATCH_PARTICLES * PARTICLE_VERTS];
    Vertex* vptr;
    float alpha;
    GLuint rgba;
    Vec3 quad_lower_left, quad_lower_right;
    GLfloat mat[16];
    PARTICLE* pptr;

    // Here comes the real trick with flat single primitive objects (s.c.
    // "billboards"): We must rotate the textured primitive so that it
    // always faces the viewer (is coplanar with the view-plane).
    // We:
    //   1) Create the primitive around origo (0,0,0)
    //   2) Rotate it so that it is coplanar with the view plane
    //   3) Translate it according to the particle position
    // Note that 1) and 2) is the same for all particles (done only once).

    // Get modelview matrix. We will only use the upper left 3x3 part of
    // the matrix, which represents the rotation.
    glGetFloatv(GL_MODELVIEW_MATRIX, mat);

    // 1) & 2) We do it in one swift step:
    // Although not obvious, the following six lines represent two matrix/
    // vector multiplications. The matrix is the inverse 3x3 rotation
    // matrix (i.e. the transpose of the same matrix), and the two vectors
    // represent the lower left corner of the quad, PARTICLE_SIZE/2 *
    // (-1,-1,0), and the lower right corner, PARTICLE_SIZE/2 * (1,-1,0).
    // The upper left/right corners of the quad is always the negative of
    // the opposite corners (regardless of rotation).
    quad_lower_left.x = (-PARTICLE_SIZE / 2) * (mat[0] + mat[1]);
    quad_lower_left.y = (-PARTICLE_SIZE / 2) * (mat[4] + mat[5]);
    quad_lower_left.z = (-PARTICLE_SIZE / 2) * (mat[8] + mat[9]);
    quad_lower_right.x = (PARTICLE_SIZE / 2) * (mat[0] - mat[1]);
    quad_lower_right.y = (PARTICLE_SIZE / 2) * (mat[4] - mat[5]);
    quad_lower_right.z = (PARTICLE_SIZE / 2) * (mat[8] - mat[9]);

    // Don't update z-buffer, since all particles are transparent!
    glDepthMask(GL_FALSE);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE);

    // Select particle texture
    if (!wireframe)
    {
        glEnable(GL_TEXTURE_2D);
        glBindTexture(GL_TEXTURE_2D, particle_tex_id);
    }

    // Set up vertex arrays. We use interleaved arrays, which is easier to
    // handle (in most situations) and it gives a linear memeory access
    // access pattern (which may give better performance in some
    // situations). GL_T2F_C4UB_V3F means: 2 floats for texture coords,
    // 4 ubytes for color and 3 floats for vertex coord (in that order).
    // Most OpenGL cards / drivers are optimized for this format.
    glInterleavedArrays(GL_T2F_C4UB_V3F, 0, vertex_array);

    // Wait for particle physics thread to be done
    mtx_lock(&thread_sync.particles_lock);
    while (!glfwWindowShouldClose(window) &&
            thread_sync.p_frame <= thread_sync.d_frame)
    {
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        ts.tv_nsec += 100000000;
        cnd_timedwait(&thread_sync.p_done, &thread_sync.particles_lock, &ts);
    }

    // Store the frame time and delta time for the physics thread
    thread_sync.t = t;
    thread_sync.dt = dt;

    // Update frame counter
    thread_sync.d_frame++;

    // Loop through all particles and build vertex arrays.
    particle_count = 0;
    vptr = vertex_array;
    pptr = particles;

    for (i = 0;  i < MAX_PARTICLES;  i++)
    {
        if (pptr->active)
        {
            // Calculate particle intensity (we set it to max during 75%
            // of its life, then it fades out)
            alpha =  4.f * pptr->life;
            if (alpha > 1.f)
                alpha = 1.f;

            // Convert color from float to 8-bit (store it in a 32-bit
            // integer using endian independent type casting)
            ((GLubyte*) &rgba)[0] = (GLubyte)(pptr->r * 255.f);
            ((GLubyte*) &rgba)[1] = (GLubyte)(pptr->g * 255.f);
            ((GLubyte*) &rgba)[2] = (GLubyte)(pptr->b * 255.f);
            ((GLubyte*) &rgba)[3] = (GLubyte)(alpha * 255.f);

            // 3) Translate the quad to the correct position in modelview
            // space and store its parameters in vertex arrays (we also
            // store texture coord and color information for each vertex).

            // Lower left corner
            vptr->s    = 0.f;
            vptr->t    = 0.f;
            vptr->rgba = rgba;
            vptr->x    = pptr->x + quad_lower_left.x;
            vptr->y    = pptr->y + quad_lower_left.y;
            vptr->z    = pptr->z + quad_lower_left.z;
            vptr ++;

            // Lower right corner
            vptr->s    = 1.f;
            vptr->t    = 0.f;
            vptr->rgba = rgba;
            vptr->x    = pptr->x + quad_lower_right.x;
            vptr->y    = pptr->y + quad_lower_right.y;
            vptr->z    = pptr->z + quad_lower_right.z;
            vptr ++;

            // Upper right corner
            vptr->s    = 1.f;
            vptr->t    = 1.f;
            vptr->rgba = rgba;
            vptr->x    = pptr->x - quad_lower_left.x;
            vptr->y    = pptr->y - quad_lower_left.y;
            vptr->z    = pptr->z - quad_lower_left.z;
            vptr ++;

            // Upper left corner
            vptr->s    = 0.f;
            vptr->t    = 1.f;
            vptr->rgba = rgba;
            vptr->x    = pptr->x - quad_lower_right.x;
            vptr->y    = pptr->y - quad_lower_right.y;
            vptr->z    = pptr->z - quad_lower_right.z;
            vptr ++;

            // Increase count of drawable particles
            particle_count ++;
        }

        // If we have filled up one batch of particles, draw it as a set
        // of quads using glDrawArrays.
        if (particle_count >= BATCH_PARTICLES)
        {
            // The first argument tells which primitive type we use (QUAD)
            // The second argument tells the index of the first vertex (0)
            // The last argument is the vertex count
            glDrawArrays(GL_QUADS, 0, PARTICLE_VERTS * particle_count);
            particle_count = 0;
            vptr = vertex_array;
        }

        // Next particle
        pptr++;
    }

    // We are done with the particle data
    mtx_unlock(&thread_sync.particles_lock);
    cnd_signal(&thread_sync.d_done);

    // Draw final batch of particles (if any)
    glDrawArrays(GL_QUADS, 0, PARTICLE_VERTS * particle_count);

    // Disable vertex arrays (Note: glInterleavedArrays implicitly called
    // glEnableClientState for vertex, texture coord and color arrays)
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);

    glDisable(GL_TEXTURE_2D);
    glDisable(GL_BLEND);

    glDepthMask(GL_TRUE);
}
Esempio n. 16
0
SideScroller::~SideScroller() {
	glDisable(GL_DEPTH_TEST);
	glDepthMask(GL_FALSE);

	SDL_Quit();
}
Esempio n. 17
0
static void draw_scene(GLFWwindow* window, double t)
{
    double xpos, ypos, zpos, angle_x, angle_y, angle_z;
    static double t_old = 0.0;
    float dt;

    // Calculate frame-to-frame delta time
    dt = (float) (t - t_old);
    t_old = t;

    glClearColor(0.1f, 0.1f, 0.1f, 1.f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(65.0, aspect_ratio, 1.0, 60.0);

    // Setup camera
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // Rotate camera
    angle_x = 90.0 - 10.0;
    angle_y = 10.0 * sin(0.3 * t);
    angle_z = 10.0 * t;
    glRotated(-angle_x, 1.0, 0.0, 0.0);
    glRotated(-angle_y, 0.0, 1.0, 0.0);
    glRotated(-angle_z, 0.0, 0.0, 1.0);

    // Translate camera
    xpos =  15.0 * sin((M_PI / 180.0) * angle_z) +
             2.0 * sin((M_PI / 180.0) * 3.1 * t);
    ypos = -15.0 * cos((M_PI / 180.0) * angle_z) +
             2.0 * cos((M_PI / 180.0) * 2.9 * t);
    zpos = 4.0 + 2.0 * cos((M_PI / 180.0) * 4.9 * t);
    glTranslated(-xpos, -ypos, -zpos);

    glFrontFace(GL_CCW);
    glCullFace(GL_BACK);
    glEnable(GL_CULL_FACE);

    setup_lights();
    glEnable(GL_LIGHTING);

    glEnable(GL_FOG);
    glFogi(GL_FOG_MODE, GL_EXP);
    glFogf(GL_FOG_DENSITY, 0.05f);
    glFogfv(GL_FOG_COLOR, fog_color);

    draw_floor();

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glDepthMask(GL_TRUE);

    draw_fountain();

    glDisable(GL_LIGHTING);
    glDisable(GL_FOG);

    // Particles must be drawn after all solid objects have been drawn
    draw_particles(window, t, dt);

    // Z-buffer not needed anymore
    glDisable(GL_DEPTH_TEST);
}
Esempio n. 18
0
	void SteamPass::Advance(double _dt)
	{
		for (auto node : m_nodeGroup.Nodes())
		{
			auto& terrainGeom = *node->terrainGeom;
			auto& particleGeom = *node->particleGeom;
			auto& material = *node->material;

			// Update
			{
				glBindProgramPipeline(GL_NONE);

				m_updateShader.BindPerPass();
			
				if (particleGeom.Switch())
				{
					GL_CHECK(glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, particleGeom.TransformFeedbackObjB()));
					GL_CHECK(glBindVertexArray(particleGeom.VertexArrayA()));
				}
				else
				{
					GL_CHECK(glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, particleGeom.TransformFeedbackObjA()));
					GL_CHECK(glBindVertexArray(particleGeom.VertexArrayB()));
				}

				GL_CHECK(glBeginTransformFeedback(GL_POINTS));
				GL_CHECK(glEnable(GL_RASTERIZER_DISCARD));

				auto& vs = m_updateShader.VertexShader();

				vs.SetTexture("s_heightData", terrainGeom.HeightData().GetRead());
				vs.SetTexture("s_smudgeData", terrainGeom.SmudgeData().GetRead());

				GL_CHECK(glDrawArrays(GL_POINTS, 0, particleGeom.NumParticles()));

				GL_CHECK(glDisable(GL_RASTERIZER_DISCARD));
				GL_CHECK(glEndTransformFeedback());
				glUseProgram(GL_NONE);

				particleGeom.Switch(!particleGeom.Switch());
			}

			// Draw
			{
				m_drawShader.BindPerPass();

				glEnable(GL_BLEND);
				glBlendEquation(GL_FUNC_ADD);
				glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				glDepthMask(GL_FALSE);
				glEnable(GL_DEPTH_TEST);
				glDepthFunc(GL_LESS);
				glPointSize(16.0f);

				RenderParams::SetModelMatrix(node->transform->matrix);

				GLuint vertexArray = particleGeom.Switch() ? particleGeom.VertexArrayA() : particleGeom.VertexArrayB();

				GL_CHECK(glBindVertexArray(vertexArray));

				m_drawShader.BindPerPass();
				auto& vs = m_drawShader.VertexShader();

				vs.SetUniform("u_mvpMatrix", RenderParams::ModelViewProjectionMatrix());

				vs.SetUniform("u_cameraPos", RenderParams::CameraPosition());
				vs.SetUniform("u_lightDir", -glm::euclidean(vec2(material.lightAltitude, material.lightAzimuth)));
				vs.SetUniform("u_moltenColor", material.moltenColor);

				vs.SetTexture("s_miscData", terrainGeom.MiscData().GetRead());

				m_drawShader.FragmentShader().SetTexture( "s_texture", material.smokeTexture );
				m_drawShader.FragmentShader().SetUniform("u_moltenColor", material.moltenColor);
				//vs.SetUniform("u_lightDir", -glm::euclidean(vec2(material.lightAltitude, material.lightAzimuth)));
				//vs.SetUniform("u_lightIntensity", material.directLightIntensity);
				//vs.SetUniform("u_ambientLightIntensity", material.ambientLightIntensity);

				glEnable(GL_PROGRAM_POINT_SIZE);
				GL_CHECK(glDrawArrays(GL_POINTS, 0, particleGeom.NumParticles()));
				glDisable(GL_PROGRAM_POINT_SIZE);

				glBindVertexArray(GL_NONE);
				//glDepthMask(GL_TRUE);
				//glEnable(GL_DEPTH_TEST);
				glDisable(GL_BLEND);
			}
		}
	}
Esempio n. 19
0
//--------------------------------------------------------------
void ofApp::draw3d(){
    //ofEnableDepthTest();

    points.clear();
    sizes.clear();
    points2.clear();
    sizes2.clear();

    
    //カメラ設定
    int cx,cy;
    cameraCount++;
    cameraMoving = ofVec3f(0,objRoad.count*objRoad.speed,0);
    camera2.setPosition(camera.getPosition()+cameraMoving);
    camera2.lookAt(cameraMoving,ofVec3f(0,0,1));
    
    switch (cameraId) {
        case 1:
            camera.setPosition(0, -1000, 400);
            camera.lookAt(ofVec3f(0,0,0),ofVec3f(0,0,1));
            break;
        case 2:
            camera.setPosition(800, -800, 300);
            //camera.setPosition(1500, -3000, 800);
            camera.lookAt(ofVec3f(0,0,0),ofVec3f(0,0,1));
            break;
        case 3:
            camera.setPosition(0, 1500, 500);
            camera.lookAt(ofVec3f(0,0,0),ofVec3f(0,0,1));
            break;
        case 4:
            cx = 1200*cos( cameraCount/200.0 );
            cy = 1200*sin( cameraCount/200.0 );
            camera.setPosition(cx, cy, 400);
            camera.lookAt(ofVec3f(0,0,0),ofVec3f(0,0,1));
            break;
        case 5:
            cx = -1200*cos( cameraCount/100.0 )*(cos(cameraCount/100.0)+2)/3;
            cy = 1200*sin( cameraCount/100.0 )*(cos(cameraCount/100.0)+2)/3;
            camera.setPosition(cx, cy, 400*(cos(cameraCount/100.0)+2)/3);
            camera.lookAt(ofVec3f(0,0,0),ofVec3f(0,0,1));
            break;
        default:
            break;
    }
    
    glDepthMask(GL_FALSE);//デプスバッファに書き込むのを禁止する
    
    ofEnableBlendMode(OF_BLENDMODE_ADD);//加算描画 this makes everything look glowy
    ofEnablePointSprites();
    
    
    //道路表示
    //shader2.begin();
    camera2.begin();
    ofVec4f bufpos,bufpos_1f;
    for(int i=objRoad.getIdxStart();i<objRoad.getIdxEnd();i++){
        bufpos = objRoad.getLeftPos(i);
        int roadwidth = objRoad.getRoadWidth(i);
        if(i==objRoad.getIdxStart()){
            continue;
        }
        //ofSetColor(rainbow[(i/10)%7][0],rainbow[(i/10)%7][1],rainbow[(i/10)%7][2],bufpos.w);
        ofSetColor(0,200,0,bufpos.w);
        ofBoxPrimitive buf_box;
        buf_box = ofBoxPrimitive(roadwidth, objRoad.width, 1);
        buf_box.setPosition(bufpos_1f.x, bufpos_1f.y+objRoad.width/2, bufpos.z);
        buf_box.draw();
        if(i%20==0){
            ofSetColor(255,0,0,255);
            ofSpherePrimitive a;
            a = ofSpherePrimitive(10, 20);
            a.setPosition(bufpos_1f.x, bufpos_1f.y, 0);
            a.draw();
            ofBoxPrimitive b;
            b = ofBoxPrimitive(roadwidth, 3, 20);
            b.setPosition(bufpos_1f.x, bufpos_1f.y, bufpos.z);
            b.draw();
        }
        bufpos_1f = bufpos;
    }
    camera2.end();
    //shader2.end();
    
    ofDisablePointSprites();
    ofDisableBlendMode();
    
    glDepthMask(GL_TRUE);
    
    //観客描画
    //ofEnableBlendMode(OF_BLENDMODE_ADD);//加算描画 this makes everything look glowy
    if(bDraw3d){
        int buf_x,buf_y,buf_z,buf_speed;
        for (int i = 0; i < ObjHumans.size(); i++) {
            buf_x = ObjHumans[i].position.x;
            buf_x = ((buf_x - 512 - objFrameOffsetx)*scalex)>>5; //32等倍
            buf_y = ObjHumans[i].position.y;
            buf_y = ((buf_y - 512 - objFrameOffsety)*scaley)>>5; //32等倍
            buf_z = (ObjHumans[i].positionz * scalez) >>5;//32等倍
            buf_speed = (int)(ObjHumans[i].speed*humanscale/50+humansizeoffset);
            if(ObjHumans[i].humanStd <= ObjHumans[i].objMissThr){

                if(ObjHumans[i].humanStd>=0){
                    addPoint(buf_x, buf_y, buf_z,buf_speed*2);
                }
                addPoint(buf_x, buf_y, buf_z,buf_speed*2);
                boxScale.push_back(buf_speed);
            }else{
                addPoint2(buf_x, buf_y, buf_z,buf_speed*2);
                boxScale2.push_back(buf_speed);
            }
        }
    }
    glDepthMask(GL_FALSE);

    
    
    
    
    // this makes everything look glowy :)
    ofEnablePointSprites();
    //ofEnableBlendMode(OF_BLENDMODE_ADD);
    ofEnableAlphaBlending();
    
    shader.begin();
    camera.begin();
    
    glPointSize(20);
    
    //観客ノード
    texture.bind();
    //texture2.bind();
    //ofSetColor(255);
    ofSetColor(0, 100, 255);
    int total = (int)points.size();
    vbo.setVertexData(&points[0], total, GL_STATIC_DRAW);
    vbo.setNormalData(&sizes[0], total, GL_STATIC_DRAW);
    vbo.draw(GL_POINTS, 0, (int)points.size());
    
    ofSetColor(255, 100, 90);
    total = (int)points2.size();
    vbo.setVertexData(&points2[0], total, GL_STATIC_DRAW);
    vbo.setNormalData(&sizes2[0], total, GL_STATIC_DRAW);
    vbo.draw(GL_POINTS, 0,(int)points2.size());
    texture.unbind();
    //texture2.unbind();

    //ライブハウスグリッド描画
    objFrame.draw();

    
    
    camera.end();
    shader.end();
    
    ofDisablePointSprites();
    //ofDisableBlendMode();
    ofDisableAlphaBlending();
    
    //基準座標
    camera2.begin();
    ofSetLineWidth(1);
    
    /*ofSetColor(255,0,0);
    ofLine(ofVec3f(0,0,0), ofVec3f(300,0,0));
    ofSetColor(0,255,0);
    ofLine(ofVec3f(0,0,0), ofVec3f(0,300,0));
    ofSetColor(0,0,255);
    ofLine(ofVec3f(0,0,0), ofVec3f(0,0,300));*/
    
    //ここから松
    ofEnableAlphaBlending();
    // bind the shader so that wee can change the
    // size of the points via the vert shader
    billboardShader.begin();
    ofEnablePointSprites(); // not needed for GL3/4
    texture_.getTextureReference().bind();
    billboards.draw();
    texture_.getTextureReference().unbind();
    ofDisablePointSprites(); // not needed for GL3/4
    billboardShader.end();
    ofDisableAlphaBlending();
    //ここまで松
    
    camera2.end();
    
    /*float boxSize = 100;
    ofFill();
    ofSetColor(255);
    ofDrawBox(boxSize);
    ofNoFill();*/
    //ba.drawNormals(1000);
    //texture3.getTextureReference().unbind();
    ofEnableAlphaBlending();
    
    camera2.begin();
    objTorii.draw(texTorii);
    for(int i =0 ;i< objClouds.size();i++){
        if(objClouds[i].visible(cameraMoving.y)){
            objClouds[i].draw(texCloud);
        }
    }


    
    for(int i =0 ;i< objLibs.size();i++){
        if(objLibs[i].visible(cameraMoving.y)){
            objLibs[i].draw(texLibs[objLibs[i].texidi*TEXLIBNUM+objLibs[i].texidj]);
        }else{
            if(objLibs[i].killmyself(cameraMoving.y)){
                objLibs.erase(objLibs.begin()+i);
            }
        }
    }
    
    camera2.end();

    //ここから応援コメント
    camera.begin();
    ofSetColor(255,255,255);
    
    for (int i = 0; i < 3 ;i++){
        for(int j = 0;j < 2; j++){
            for(int k =0; k < 2; k++){
                if(commentdraw[i][j][k]){
                    objTexts[i*4+j*2+k].draw(texTexts[i*4+j*2+k]);
                }
            }
        }
    }
    camera.end();
    ofDisableAlphaBlending();

    
    glDepthMask(GL_TRUE);
}
Esempio n. 20
0
void GPU_select_begin(unsigned int *buffer, unsigned int bufsize, rctf *input, char mode, int oldhits)
{
	g_query_state.select_is_active = true;
	g_query_state.query_issued = false;
	g_query_state.active_query = 0;
	g_query_state.use_gpu_select = GPU_select_query_check_active();
	g_query_state.num_of_queries = 0;
	g_query_state.bufsize = bufsize;
	g_query_state.buffer = buffer;
	g_query_state.mode = mode;
	g_query_state.index = 0;
	g_query_state.oldhits = oldhits;

	if (!g_query_state.use_gpu_select) {
		glSelectBuffer(bufsize, (GLuint *)buffer);
		glRenderMode(GL_SELECT);
		glInitNames();
		glPushName(-1);
	}
	else {
		float viewport[4];

		g_query_state.num_of_queries = ALLOC_QUERIES;

		g_query_state.queries = MEM_mallocN(g_query_state.num_of_queries * sizeof(*g_query_state.queries), "gpu selection queries");
		g_query_state.id = MEM_mallocN(g_query_state.num_of_queries * sizeof(*g_query_state.id), "gpu selection ids");
		glGenQueries(g_query_state.num_of_queries, g_query_state.queries);

		glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_VIEWPORT_BIT);
		/* disable writing to the framebuffer */
		glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

		/* In order to save some fill rate we minimize the viewport using rect.
		 * We need to get the region of the scissor so that our geometry doesn't
		 * get rejected before the depth test. Should probably cull rect against
		 * scissor for viewport but this is a rare case I think */
		glGetFloatv(GL_SCISSOR_BOX, viewport);
		if (!input || input->xmin == input->xmax) {
			glViewport(viewport[0], viewport[1], 24, 24);
		}
		else {
			glViewport(viewport[0], viewport[1], (int)(input->xmax - input->xmin), (int)(input->ymax - input->ymin));
		}

		/* occlusion queries operates on fragments that pass tests and since we are interested on all
		 * objects in the view frustum independently of their order, we need to disable the depth test */
		if (mode == GPU_SELECT_ALL) {
			glDisable(GL_DEPTH_TEST);
			glDepthMask(GL_FALSE);
		}
		else if (mode == GPU_SELECT_NEAREST_FIRST_PASS) {
			glClear(GL_DEPTH_BUFFER_BIT);
			glEnable(GL_DEPTH_TEST);
			glDepthMask(GL_TRUE);
			glDepthFunc(GL_LEQUAL);
		}
		else if (mode == GPU_SELECT_NEAREST_SECOND_PASS) {
			glEnable(GL_DEPTH_TEST);
			glDepthMask(GL_FALSE);
			glDepthFunc(GL_EQUAL);
		}
	}
}
Esempio n. 21
0
// Draws the FBO texture for 3DTV.
void ApplicationOverlay::displayOverlayTexture3DTV(Camera& whichCamera, float aspectRatio, float fov) {
    if (_alpha == 0.0f) {
        return;
    }
    
    Application* application = Application::getInstance();
    
    MyAvatar* myAvatar = application->getAvatar();
    const glm::vec3& viewMatrixTranslation = application->getViewMatrixTranslation();
    
    glActiveTexture(GL_TEXTURE0);
    
    glEnable(GL_BLEND);
    glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_ONE);
    _overlays.bindTexture();
    glEnable(GL_DEPTH_TEST);
    glDisable(GL_LIGHTING);
    glEnable(GL_TEXTURE_2D);
    
    glMatrixMode(GL_MODELVIEW);
    
    glPushMatrix();
    glLoadIdentity();
    // Transform to world space
    glm::quat rotation = whichCamera.getRotation();
    glm::vec3 axis2 = glm::axis(rotation);
    glRotatef(-glm::degrees(glm::angle(rotation)), axis2.x, axis2.y, axis2.z);
    glTranslatef(viewMatrixTranslation.x, viewMatrixTranslation.y, viewMatrixTranslation.z);
    
    // Translate to the front of the camera
    glm::vec3 pos = whichCamera.getPosition();
    glm::quat rot = myAvatar->getOrientation();
    glm::vec3 axis = glm::axis(rot);
    
    glTranslatef(pos.x, pos.y, pos.z);
    glRotatef(glm::degrees(glm::angle(rot)), axis.x, axis.y, axis.z);
    
    glColor4f(1.0f, 1.0f, 1.0f, _alpha);
    
    //Render
    const GLfloat distance = 1.0f;
    
    const GLfloat halfQuadHeight = distance * tan(fov);
    const GLfloat halfQuadWidth = halfQuadHeight * aspectRatio;
    const GLfloat quadWidth = halfQuadWidth * 2.0f;
    const GLfloat quadHeight = halfQuadHeight * 2.0f;
    
    GLfloat x = -halfQuadWidth;
    GLfloat y = -halfQuadHeight;
    glDisable(GL_DEPTH_TEST);
    
    glBegin(GL_QUADS);
    
    glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + quadHeight, -distance);
    glTexCoord2f(1.0f, 1.0f); glVertex3f(x + quadWidth, y + quadHeight, -distance);
    glTexCoord2f(1.0f, 0.0f); glVertex3f(x + quadWidth, y, -distance);
    glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, -distance);
    
    glEnd();
    
    if (_crosshairTexture == 0) {
        _crosshairTexture = Application::getInstance()->getGLWidget()->bindTexture(QImage(Application::resourcesPath() + "images/sixense-reticle.png"));
    }
    
    //draw the mouse pointer
    glBindTexture(GL_TEXTURE_2D, _crosshairTexture);
    
    const float reticleSize = 40.0f / application->getGLWidget()->width() * quadWidth;
    x -= reticleSize / 2.0f;
    y += reticleSize / 2.0f;
    const float mouseX = (application->getMouseX() / (float)application->getGLWidget()->width()) * quadWidth;
    const float mouseY = (1.0 - (application->getMouseY() / (float)application->getGLWidget()->height())) * quadHeight;
    
    glBegin(GL_QUADS);
    
    glColor3f(RETICLE_COLOR[0], RETICLE_COLOR[1], RETICLE_COLOR[2]);
    
    glTexCoord2d(0.0f, 0.0f); glVertex3f(x + mouseX, y + mouseY, -distance);
    glTexCoord2d(1.0f, 0.0f); glVertex3f(x + mouseX + reticleSize, y + mouseY, -distance);
    glTexCoord2d(1.0f, 1.0f); glVertex3f(x + mouseX + reticleSize, y + mouseY - reticleSize, -distance);
    glTexCoord2d(0.0f, 1.0f); glVertex3f(x + mouseX, y + mouseY - reticleSize, -distance);
    
    glEnd();
    
    glEnable(GL_DEPTH_TEST);
    
    glPopMatrix();
    
    glDepthMask(GL_TRUE);
    glBindTexture(GL_TEXTURE_2D, 0);
    glDisable(GL_TEXTURE_2D);
    
    glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_ONE);
    glEnable(GL_LIGHTING);
    
    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
Esempio n. 22
0
void CSm3GroundDrawer::Draw(bool drawWaterReflection, bool drawUnitReflection)
{
	if (wireframe) {
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	}

	terrain::RenderContext* currc = rc;

	tr->SetShaderParams(sky->GetLight()->GetLightDir(), currc->cam->pos);

	if (shadowHandler->shadowsLoaded) {
		terrain::ShadowMapParams params;

		params.mid[0] = shadowHandler->GetShadowParams().x;
		params.mid[1] = shadowHandler->GetShadowParams().y;
		params.f_a    = shadowHandler->GetShadowParams().z;
		params.f_b    = shadowHandler->GetShadowParams().w;
		params.shadowMap = shadowHandler->shadowTexture;

		for (int a = 0; a < 16; a++)
			params.shadowMatrix[a] = shadowHandler->shadowMatrix[a];

		tr->SetShadowParams(&params);
	}

	tr->SetActiveContext(currc);

	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CW);

	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	glEnable(GL_LIGHTING);
	glLightfv(GL_LIGHT0, GL_POSITION, sky->GetLight()->GetLightDir());

	float d[4] = {0.0f, 0.0f, 0.0f, 1.0f};
	const float z[] = {0.0f, 0.0f, 0.0f, 1.0f};

	for (int a = 0; a < 3; a++)
		d[a] = mapInfo->light.groundSunColor[a];
	glLightfv(GL_LIGHT0, GL_DIFFUSE, d);

	for (int a = 0; a < 3; a++)
		d[a] = mapInfo->light.groundAmbientColor[a];
	glLightfv(GL_LIGHT0, GL_AMBIENT, d);

	for (int a = 0; a < 3; a++)
		d[a] = mapInfo->light.groundSpecularColor[a];
	glLightfv(GL_LIGHT0, GL_SPECULAR, d);

	for (int a = 0; a < 4; a++)
		d[a] = 0.0f;
	glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, d);

	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, z);
	glDisable(GL_LIGHT1);
	glEnable(GL_LIGHT0);
	glEnable(GL_RESCALE_NORMAL);

//	glLightfv (GL_LIGHT0, GL_SPOT_DIRECTION,dir.getf());
//	glLightf (GL_LIGHT0, GL_SPOT_CUTOFF, 90.0f);
/*	const float ambient[] = { 0.4f, 0.4f, 0.4f, 1.0f };
	const float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
	glLightfv (GL_LIGHT0, GL_DIFFUSE, diffuse);
	glLightfv (GL_LIGHT0, GL_AMBIENT, ambient);

	glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);

	const float md[] = { 1.0f, 1.0f, 1.0f, 1.0f };
	glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, md);
	glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR, md);
	glMaterialf (GL_FRONT_AND_BACK, GL_SHININESS, 10.0f);*/
	/////////////////////

	tr->Draw();
	glDisable(GL_LIGHT0);
	glDisable(GL_LIGHTING);

	if (wireframe) {
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	}

	if (drawMode != drawNormal) {
		glEnable(GL_BLEND);
		glDepthMask(GL_FALSE);

		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glEnable(GL_POLYGON_OFFSET_FILL);
		glPolygonOffset(0.0f, -10.0f);
		glColor4f(1.0f, 1.0f, 1.0f, 0.5f);
		tr->DrawOverlayTexture(infoTex);
		glDisable(GL_POLYGON_OFFSET_FILL);

		glDepthMask(GL_TRUE);
		glDisable(GL_BLEND);
	}

	glFrontFace(GL_CCW);
	glDisable(GL_CULL_FACE);

	glColor3ub(255, 255, 255);

	DrawObjects(drawWaterReflection, drawUnitReflection);

	glActiveTextureARB(GL_TEXTURE0_ARB);
	glDisable(GL_TEXTURE_2D);
}
Esempio n. 23
0
static void DrawFire(ModeInfo * mi)
{
    int j;
    firestruct *fs = &fire[MI_SCREEN(mi)];
    Bool wire = MI_IS_WIREFRAME(mi);

    mi->polygon_count = 0;

    if (do_wander && !fs->button_down_p)
    {
	GLfloat x, y, z;

#       define SINOID(SCALE,SIZE) \
        ((((1 + sin((fs->frame * (SCALE)) / 2 * M_PI)) / 2.0) * (SIZE)) - (SIZE)/2)

        x = SINOID(0.031, 0.85);
        y = SINOID(0.017, 0.25);
        z = SINOID(0.023, 0.85);
        fs->frame++;
        fs->obs[0] = x + DEF_OBS[0];
        fs->obs[1] = y + DEF_OBS[1];
        fs->obs[2] = z + DEF_OBS[2];
        fs->dir[1] = y;
        fs->dir[2] = z;
    }

    glEnable(GL_DEPTH_TEST);

    if (fs->fog)
	glEnable(GL_FOG);
    else
	glDisable(GL_FOG);

    glDepthMask(GL_TRUE);
    glClearColor(0.5, 0.5, 0.8, 1.0);	/* sky in the distance */
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glPushMatrix();

    calcposobs(fs);

    gltrackball_rotate (fs->trackball);

    gluLookAt(fs->obs[0], fs->obs[1], fs->obs[2],
              fs->obs[0] + fs->dir[0], 
              fs->obs[1] + fs->dir[1],
              fs->obs[2] + fs->dir[2],
              0.0, 1.0, 0.0);

    glEnable(GL_TEXTURE_2D);

    /* draw ground using the computed texture */
    if (do_texture) {
	glColor4f(1.0,1.0,1.0,1.0);	/* white to get texture in it's true color */
#ifdef HAVE_GLBINDTEXTURE
	glBindTexture(GL_TEXTURE_2D, fs->groundid);
#endif /* HAVE_GLBINDTEXTURE */
    }
    else
        glColor4f(0.54, 0.27, 0.07, 1.0);	/* untextured ground color */
    glBegin(GL_QUADS);
    glTexCoord2fv(qt[0]);
    glVertex3fv(q[0]);
    glTexCoord2fv(qt[1]);
    glVertex3fv(q[1]);
    glTexCoord2fv(qt[2]);
    glVertex3fv(q[2]);
    glTexCoord2fv(qt[3]);
    glVertex3fv(q[3]);
    mi->polygon_count++;
    glEnd();

    glAlphaFunc(GL_GEQUAL, 0.9);
    if (fs->num_trees)
    {
	/* here do_texture IS True - and color used is white */
	glEnable(GL_ALPHA_TEST);
#ifdef HAVE_GLBINDTEXTURE
	glBindTexture(GL_TEXTURE_2D,fs->treeid);
#endif /* HAVE_GLBINDTEXTURE */
	for(j=0;j<fs->num_trees;j++)
      mi->polygon_count += drawtree(fs->treepos[j].x ,fs->treepos[j].y ,fs->treepos[j].z );
    	glDisable(GL_ALPHA_TEST);
    }
    glDisable(GL_TEXTURE_2D);
    glDepthMask(GL_FALSE);

    if (fs->shadows) {
	/* draw shadows with black color */
	glBegin(wire ? GL_LINE_STRIP : GL_TRIANGLES);
	for (j = 0; j < fs->np; j++) {
	    glColor4f(black[0], black[1], black[2], fs->p[j].c[0][3]);
	    glVertex3f(fs->p[j].p[0][0], 0.1, fs->p[j].p[0][2]);

	    glColor4f(black[0], black[1], black[2], fs->p[j].c[1][3]);
	    glVertex3f(fs->p[j].p[1][0], 0.1, fs->p[j].p[1][2]);

	    glColor4f(black[0], black[1], black[2], fs->p[j].c[2][3]);
	    glVertex3f(fs->p[j].p[2][0], 0.1, fs->p[j].p[2][2]);
        mi->polygon_count++;
	}
	glEnd();
    }

    glBegin(wire ? GL_LINE_STRIP : GL_TRIANGLES);
    for (j = 0; j < fs->np; j++) {
	/* draw particles: colors are computed in setpart */
	glColor4fv(fs->p[j].c[0]);
	glVertex3fv(fs->p[j].p[0]);

	glColor4fv(fs->p[j].c[1]);
	glVertex3fv(fs->p[j].p[1]);

	glColor4fv(fs->p[j].c[2]);
	glVertex3fv(fs->p[j].p[2]);
    mi->polygon_count++;

	setpart(fs, &fs->p[j]);
    }
    glEnd();

    /* draw rain particles if no fire particles */
    if (!fs->np)
    {
        float timeused = gettimerain();
        glDisable(GL_TEXTURE_2D);
	glShadeModel(GL_SMOOTH);
	glBegin(GL_LINES);
	for (j = 0; j < NUMPART; j++) {
	    glColor4f(0.7f,0.95f,1.0f,0.0f);
	    glVertex3fv(fs->r[j].oldpos);
	    glColor4f(0.3f,0.7f,1.0f,1.0f);
	    glVertex3fv(fs->r[j].pos);
	    setpartrain(fs, &fs->r[j],timeused);
        mi->polygon_count++;
	}
	glEnd();
	glShadeModel(GL_FLAT);
    }

    glDisable(GL_TEXTURE_2D);
    glDisable(GL_ALPHA_TEST);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_FOG);

    /* manage framerate display */
    if (MI_IS_FPS(mi)) do_fps (mi);
    glPopMatrix();
}
Esempio n. 24
0
void display()
{   glClearColor(0.6, 0.75, 0.85, 1); // sky color is light blue
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	/* Clear The Screen And The Depth Buffer */
	if(view==0)
	{   
		display1();
	}

  else if (view==1)
	{
	display2();
   }
   else if(view==2)
   {
   //  Erase the window and the depth buffer
   
   glClearColor(0.6, 0.75, 0.85, 1); // sky color is light blue
   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    //  Enable Z-buffering in OpenGL
   glEnable(GL_DEPTH_TEST);
   glCullFace(GL_BACK);
  
   glLoadIdentity();
    
   // Set the look at position for perspective projection
      		gluLookAt(
			Ex,      Ey,      Ez,
			Ex + lx, Ey, Ez+lz,
			0.0,    1,    0.0);
   
    
  glShadeModel(GL_SMOOTH);
  glDisable(GL_DEPTH_TEST);
  glDepthMask(GL_FALSE);
  glPushMatrix();
  glTranslatef(	Ex + lx, 0, Ez+lz-4);
  Sky(1000); 
  glPopMatrix();
  glDepthMask(GL_TRUE);
  glEnable(GL_DEPTH_TEST);
  
    //  Light switch
   if (light)
   {
        //  Translate intensity to color vectors
        float Ambient[]   = {0.01*ambient ,0.01*ambient ,0.01*ambient ,1.0};
        float Diffuse[]   = {0.01*diffuse ,0.01*diffuse ,0.01*diffuse ,1.0};
        float Specular[]  = {0.01*specular,0.01*specular,0.01*specular,1.0};
        //  Light position
      float Position[]={0,1000,5000};
        //  Draw light position as ball (still no lighting here)
        glColor3f(1,1,1);
         ball(Position[0],Position[1],Position[2] , 0.2);
        //  OpenGL should normalize normal vectors
        glEnable(GL_NORMALIZE);
        //  Enable lighting
        glEnable(GL_LIGHTING);
        //  glColor sets ambient and diffuse color materials
        glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
        glEnable(GL_COLOR_MATERIAL);
        //  Enable light 0
        glEnable(GL_LIGHT0);
        //  Set ambient, diffuse, specular components and position of light 0
        glLightfv(GL_LIGHT0,GL_AMBIENT ,Ambient);
        glLightfv(GL_LIGHT0,GL_DIFFUSE ,Diffuse);
        glLightfv(GL_LIGHT0,GL_SPECULAR,Specular);
        glLightfv(GL_LIGHT0,GL_POSITION,Position);
        
   }
   else
     glDisable(GL_LIGHTING);
   
	if(opt==1)
	{
		 glPushMatrix();
         glTranslatef(	Ex + lx,0, Ez+lz-4);
         glRotatef(90, 1, 0, 0);
         glRotatef(180, 0, 1, 0);
         glColor3f(1,1,1);
		 glCallList(car1);
		 glPopMatrix();
		  int E=Ez+lz-4;
		 if(E<=40)
		 {
		 	Ex=0;
		 	Ez=1000;
		 	lx=0;
		 	lz=-1;
		 }
		
	}
	else if(opt==2)
	{
		 glPushMatrix();
         glTranslatef(	Ex + lx, 0, Ez+lz-4);
         glRotatef(90, 1, 0, 0);
         glRotatef(180, 0, 1, 0);
         glColor3f(1,1,1);
		 glCallList(car2);
		 glPopMatrix();
		   int E=Ez+lz-4;
		 if(E<=40)
		 {
		 	Ex=0;
		 	Ez=1000;
		 	lx=0;
		 	lz=-1;
		 }
	}
	cylinder();
    Road();
    
     
	for(i=0; i<=1000; i+=40)
	{
	glPushMatrix();
    glTranslated(-50,10,i);
    glScaled(50,50,50);
    Tree();
    glPopMatrix();
  }
    for(i=0; i<=1000; i+=40)
	{
	glPushMatrix();
    glTranslated(170,10,i);
    glScaled(50,50,50);
    Tree();
    glPopMatrix();
  }
    for(i=0; i<=1000; i+=60)
	{
	glPushMatrix();
    glTranslated(-70,-10,i);
    glScaled(2,10,10);
    Lamp();
    glPopMatrix();
  }
  for(i=0; i<=1000; i+=60)
	{
	glPushMatrix();
    glTranslated(70,-10,i);
    glRotated(90,0,1,0);
    glScaled(2,10,10);
    Lamp();
    glPopMatrix();
  }
  for(i=-60; i<=1000; i+=60)
	{
	glPushMatrix();
    glTranslated(-38,86.5,i+43);
    glScaled(5,5,5);
    lights();
    glPopMatrix();
  }
   for(i=-60; i<=1000; i+=60)
	{
	glPushMatrix();
    glTranslated(55,87,i+30);
    glScaled(5,5,5);
    lights();
    glPopMatrix();
  }
   for(i=0; i<=1000; i+=400)
	{
	glPushMatrix();
    glTranslated(-50,-10,i);
    glScaled(10,10,10);
    trafficsignal();
    glPopMatrix();
    }
     for(i=0; i<=1000; i+=400)
	{
	glPushMatrix();
    glTranslated(0,0,i+40);
    zebracrossing();
    glPopMatrix();
    }
     for(i=-60; i<=1000; i+=100)
	{
	glPushMatrix();
    glTranslated(200,-15,i+30);
    glScaled(10,15,10);
    buildings();
    glPopMatrix();
  }
   for(i=-60; i<=1000; i+=100)
	{
	glPushMatrix();
    glTranslated(-250,-15,i+30);
    glScaled(10,15,10);
    buildings();
    glPopMatrix();
  }
   for(i=-60; i<=1000; i+=100)
	{
	glPushMatrix();
    glTranslated(350,-15,i+30);
    glScaled(10,30,10);
    buildings();
    glPopMatrix();
  }
   for(i=-60; i<=1000; i+=100)
	{
	glPushMatrix();
    glTranslated(-400,-15,i+30);
    glScaled(10,30,10);
    buildings();
    glPopMatrix();
  }
     
   for(e=0; e<=1000; e+=155)
	{
	  if(e%2==0)
	{
		glPushMatrix();
		glTranslated(-16,-10,e);
		glScaled(6,6,6);
        roadpylon();
        glPopMatrix();
    }
    else
	{
		glPushMatrix();
		glTranslated(16,-10,e);
        glScaled(6,6,6);
        roadpylon();
        glPopMatrix();
    }
    } 
    for(i=0; i<=1000; i+=400)
	{
	glPushMatrix();
    glTranslated(65,0,i);
    glScaled(10,10,10);
    roadsign();
    glPopMatrix();
    }
  
  xpos = xpos + xvel;

if(xpos >= 30)
{
xvel = -xvel;
}
if( xpos <2)
{
xvel = -xvel;
}
  glPushMatrix();
  glTranslated(0,xpos,900);
  glRotated(-90,0,0,1);
  glRotated(-90,0,1,0);
  glScaled(2,2,2);
  glColor3f(1,1,1);
  glCallList(dragon);
  glPopMatrix();
   glWindowPos2i(5,5);
   glColor3f(1,1,1);
  Print("Speed=%f",1,jump);
 
}
   //  Render the scene and make it visible
   ErrCheck("display");
   glFlush();
   glutSwapBuffers();
}
Esempio n. 25
0
void OpenGLState::Apply() const {
    // Culling
    if (cull.enabled != cur_state.cull.enabled) {
        if (cull.enabled) {
            glEnable(GL_CULL_FACE);
        } else {
            glDisable(GL_CULL_FACE);
        }
    }

    if (cull.mode != cur_state.cull.mode) {
        glCullFace(cull.mode);
    }

    if (cull.front_face != cur_state.cull.front_face) {
        glFrontFace(cull.front_face);
    }

    // Depth test
    if (depth.test_enabled != cur_state.depth.test_enabled) {
        if (depth.test_enabled) {
            glEnable(GL_DEPTH_TEST);
        } else {
            glDisable(GL_DEPTH_TEST);
        }
    }

    if (depth.test_func != cur_state.depth.test_func) {
        glDepthFunc(depth.test_func);
    }

    // Depth mask
    if (depth.write_mask != cur_state.depth.write_mask) {
        glDepthMask(depth.write_mask);
    }

    // Color mask
    if (color_mask.red_enabled != cur_state.color_mask.red_enabled ||
            color_mask.green_enabled != cur_state.color_mask.green_enabled ||
            color_mask.blue_enabled != cur_state.color_mask.blue_enabled ||
            color_mask.alpha_enabled != cur_state.color_mask.alpha_enabled) {
        glColorMask(color_mask.red_enabled, color_mask.green_enabled,
                    color_mask.blue_enabled, color_mask.alpha_enabled);
    }

    // Stencil test
    if (stencil.test_enabled != cur_state.stencil.test_enabled) {
        if (stencil.test_enabled) {
            glEnable(GL_STENCIL_TEST);
        } else {
            glDisable(GL_STENCIL_TEST);
        }
    }

    if (stencil.test_func != cur_state.stencil.test_func ||
            stencil.test_ref != cur_state.stencil.test_ref ||
            stencil.test_mask != cur_state.stencil.test_mask) {
        glStencilFunc(stencil.test_func, stencil.test_ref, stencil.test_mask);
    }

    if (stencil.action_depth_fail != cur_state.stencil.action_depth_fail ||
            stencil.action_depth_pass != cur_state.stencil.action_depth_pass ||
            stencil.action_stencil_fail != cur_state.stencil.action_stencil_fail) {
        glStencilOp(stencil.action_stencil_fail, stencil.action_depth_fail, stencil.action_depth_pass);
    }

    // Stencil mask
    if (stencil.write_mask != cur_state.stencil.write_mask) {
        glStencilMask(stencil.write_mask);
    }

    // Blending
    if (blend.enabled != cur_state.blend.enabled) {
        if (blend.enabled) {
            glEnable(GL_BLEND);

            cur_state.logic_op = GL_COPY;
            glLogicOp(cur_state.logic_op);
            glDisable(GL_COLOR_LOGIC_OP);
        } else {
            glDisable(GL_BLEND);
            glEnable(GL_COLOR_LOGIC_OP);
        }
    }

    if (blend.color.red != cur_state.blend.color.red ||
            blend.color.green != cur_state.blend.color.green ||
            blend.color.blue != cur_state.blend.color.blue ||
            blend.color.alpha != cur_state.blend.color.alpha) {
        glBlendColor(blend.color.red, blend.color.green,
                     blend.color.blue, blend.color.alpha);
    }

    if (blend.src_rgb_func != cur_state.blend.src_rgb_func ||
            blend.dst_rgb_func != cur_state.blend.dst_rgb_func ||
            blend.src_a_func != cur_state.blend.src_a_func ||
            blend.dst_a_func != cur_state.blend.dst_a_func) {
        glBlendFuncSeparate(blend.src_rgb_func, blend.dst_rgb_func,
                            blend.src_a_func, blend.dst_a_func);
    }

    if (blend.rgb_equation != cur_state.blend.rgb_equation ||
            blend.a_equation != cur_state.blend.a_equation) {
        glBlendEquationSeparate(blend.rgb_equation, blend.a_equation);
    }

    if (logic_op != cur_state.logic_op) {
        glLogicOp(logic_op);
    }

    // Textures
    for (unsigned i = 0; i < ARRAY_SIZE(texture_units); ++i) {
        if (texture_units[i].texture_2d != cur_state.texture_units[i].texture_2d) {
            glActiveTexture(GL_TEXTURE0 + i);
            glBindTexture(GL_TEXTURE_2D, texture_units[i].texture_2d);
        }
        if (texture_units[i].sampler != cur_state.texture_units[i].sampler) {
            glBindSampler(i, texture_units[i].sampler);
        }
    }

    // Lighting LUTs
    for (unsigned i = 0; i < ARRAY_SIZE(lighting_luts); ++i) {
        if (lighting_luts[i].texture_1d != cur_state.lighting_luts[i].texture_1d) {
            glActiveTexture(GL_TEXTURE3 + i);
            glBindTexture(GL_TEXTURE_1D, lighting_luts[i].texture_1d);
        }
    }

    // Fog LUT
    if (fog_lut.texture_1d != cur_state.fog_lut.texture_1d) {
        glActiveTexture(GL_TEXTURE9);
        glBindTexture(GL_TEXTURE_1D, fog_lut.texture_1d);
    }

    // Framebuffer
    if (draw.read_framebuffer != cur_state.draw.read_framebuffer) {
        glBindFramebuffer(GL_READ_FRAMEBUFFER, draw.read_framebuffer);
    }
    if (draw.draw_framebuffer != cur_state.draw.draw_framebuffer) {
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, draw.draw_framebuffer);
    }

    // Vertex array
    if (draw.vertex_array != cur_state.draw.vertex_array) {
        glBindVertexArray(draw.vertex_array);
    }

    // Vertex buffer
    if (draw.vertex_buffer != cur_state.draw.vertex_buffer) {
        glBindBuffer(GL_ARRAY_BUFFER, draw.vertex_buffer);
    }

    // Uniform buffer
    if (draw.uniform_buffer != cur_state.draw.uniform_buffer) {
        glBindBuffer(GL_UNIFORM_BUFFER, draw.uniform_buffer);
    }

    // Shader program
    if (draw.shader_program != cur_state.draw.shader_program) {
        glUseProgram(draw.shader_program);
    }

    cur_state = *this;
}
void ofxSpriteRenderer::Render()
{
	//printf("--------------RENDER--------------\n");
	for(ofxBaseCommands::iterator it = m_Commands.begin();it != m_Commands.end();it++)
	{
		ofxBaseCommand* item = *it;
		delete item;
	}
	m_Commands.clear();
	
	//unsigned long long time_start_build = ofGetSystemTime();
	sort(m_Sprites.begin(), m_Sprites.end(), QuadCompare);
	for(int i=0;i<m_Sprites.size();i++)
	{
		m_Sprites[i]->SetID(i);
	}
	//unsigned long long time_finish_sort = ofGetSystemTime();
	//printf("sort time =  %llu\n", time_finish_sort - time_start_build);
	bool is_custom_command = false;
	for(ofxBaseSprites::iterator it = m_Sprites.begin();it != m_Sprites.end();it++)
	{
		ofxBaseSprite* sprite = *it;
		if(!(sprite->GetOcclusion() == SPRITE_OCCLUSION_IN_SCREEN || sprite->GetOcclusion() == SPRITE_OCCLUSION_UNKNOWN) ||
			!sprite->IsVisible())
		{
			continue;
		}
		if(sprite->IsCustomRendered())
		{
			ofxBaseCommand* command = (ofxBaseCommand*)sprite;
			m_Commands.push_back(command);
			is_custom_command = true;
			continue;
		}
		ofxSpriteCommand* command;
		if(m_Commands.size() == 0 || is_custom_command)
		{
			command = new ofxSpriteCommand();
			command->SetShader(sprite->GetShader());
			command->SetTexture(sprite->GetTexture());
			bool push_success = command->PushSprite(sprite);
			assert(push_success);
			m_Commands.push_back(command);
			is_custom_command = false;
		}
		else
		{
			command = (ofxSpriteCommand*)m_Commands.back();
			bool push_success = command->PushSprite(sprite);
			if(command->GetShader() != sprite->GetShader() 
				|| command->GetTexture() != sprite->GetTexture() 
				|| !push_success)
			{
				command = new ofxSpriteCommand();
				command->SetShader(sprite->GetShader());
				command->SetTexture(sprite->GetTexture());
				push_success = command->PushSprite(sprite);
				m_Commands.push_back(command);
				assert(push_success);
			}
		}
	}
	//unsigned long long time_finish_build = ofGetSystemTime();
	//printf("build time =  %llu\n", time_finish_build - time_start_build);
#ifdef _DEBUG
	m_DrawnBatches = 0;
	m_DrawnVertices = 0;
	unsigned long long time_start_render = ofGetSystemTime();
#endif
	m_TransformMatrix = ofGetCurrentMatrix(OF_MATRIX_MODELVIEW)*ofGetCurrentMatrix(OF_MATRIX_PROJECTION);
	//m_Camera->begin();
	{
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glEnable(GL_BLEND);
		//glDisable(GL_DEPTH_TEST);// transparent isn't work well with depth test
		glDepthMask(GL_FALSE);
		for(ofxBaseCommands::iterator it = m_Commands.begin();it != m_Commands.end();it++)
		{
			ofxBaseCommand* cmd = *it;
			cmd->Render();
#ifdef _DEBUG
			m_DrawnBatches++;
			m_DrawnVertices += cmd->GetRenderedVertices();
#endif
		}
		//glEnable(GL_DEPTH_TEST);
		glDepthMask(GL_TRUE);
		glDisable(GL_BLEND);
	}
	//m_Camera->end();
#ifdef _DEBUG
	unsigned long long time_finish_render = ofGetSystemTime();
	m_RenderTimeMilisecond = time_finish_render - time_start_render;
#endif
}
Esempio n. 27
0
/*-----------------------------------------------------------------------------
    Name        : RenderNAVLights
    Description : TODO: render sorted by projected depth value so alpha sorts correctly
    Inputs      : ship - the ship whose navlights we are to render
    Outputs     :
    Return      :
----------------------------------------------------------------------------*/
void RenderNAVLights(Ship *ship)
{
   sdword i;
   NAVLight *navLight;
   NAVLightInfo *navLightInfo;
   ShipStaticInfo *shipStaticInfo;
   NAVLightStatic *navLightStatic;
   vector origin = {0.0f, 0.0f, 0.0f};
   NAVLightStaticInfo *navLightStaticInfo;
   real32 fade;
   bool lightOn;
   extern bool bFade;
   extern real32 meshFadeAlpha;

   fade = bFade ? meshFadeAlpha : 1.0f;

   shipStaticInfo = (ShipStaticInfo *)ship->staticinfo;

    navLightInfo = ship->navLightInfo;
   if(shipStaticInfo->navlightStaticInfo && navLightInfo != NULL)
   {
      glDepthMask(GL_FALSE);
      rndAdditiveBlends(TRUE);
      lightOn = rndLightingEnable(FALSE);

      navLightStaticInfo = shipStaticInfo->navlightStaticInfo;
      navLightStatic = navLightStaticInfo->navlightstatics;
      navLight = navLightInfo->navLights;

      for( i=0 ; i<navLightStaticInfo->numNAVLights ; i++, navLight ++, navLightStatic ++)
      {
			// Account for the startdelay.
			if(navLight->lastTimeFlashed == navLightStatic->startdelay)
			{
				navLight->lastTimeFlashed = universe.totaltimeelapsed + navLightStatic->startdelay;
			}
			
			if(universe.totaltimeelapsed > navLight->lastTimeFlashed)
			{
				if(navLight->lightstate == 1)
				{
					navLight->lastTimeFlashed = universe.totaltimeelapsed + navLightStatic->flashrateoff;
				}
				else
				{
					navLight->lastTimeFlashed = universe.totaltimeelapsed + navLightStatic->flashrateon;
				}
				
				navLight->lightstate = 1 - navLight->lightstate;
			}

			if(navLight->lightstate)
			{
				if (ship->currentLOD <= (sdword)navLightStatic->minLOD)
				{
					navLightBillboardEnable(ship, navLightStatic);

					if(navLightStatic->texturehandle == TR_InvalidHandle)
					{
						primCircleSolid3Fade(&origin, navLightStatic->size, 10, navLightStatic->color, fade);
					}
					else
					{
						primSolidTexture3Fade(&origin, navLightStatic->size, navLightStatic->color, navLightStatic->texturehandle, fade);
					}

					navLightBillboardDisable();
				}
				else
				{
					color tempColor;

                    tempColor = colRGB(colRed(navLightStatic->color) * 2 / 3,
					                   colGreen(navLightStatic->color) * 2 / 3,
									   colBlue(navLightStatic->color) * 2 / 3);

                    rndTextureEnable(FALSE);
                    if (RGL)
                    {
                        if (glCapFastFeature(GL_BLEND))
                        {
                            rndAdditiveBlends(TRUE);
                            primPointSize3(&navLightStatic->position, 2.0f, tempColor);
                        }
                        else
                        {
                            primPointSize3(&navLightStatic->position, 1.0f, tempColor);
                        }
                    }
                    else
                    {
                        rndAdditiveBlends(TRUE);
                        glEnable(GL_POINT_SMOOTH);
                        primPointSize3Fade(&navLightStatic->position, 2.0f, tempColor, fade);
                        glDisable(GL_POINT_SMOOTH);
                    }
				}
			}
      }

      rndLightingEnable(lightOn);
      rndAdditiveBlends(FALSE);
      glDepthMask(GL_TRUE);
    }
}
void WebGraphicsContext3DDefaultImpl::reshape(int width, int height)
{
    m_cachedWidth = width;
    m_cachedHeight = height;
    makeContextCurrent();

    GLenum target = GL_TEXTURE_2D;

    if (!m_texture) {
        // Generate the texture object
        m_texture = createTextureObject(target);
        // Generate the framebuffer object
        glGenFramebuffersEXT(1, &m_fbo);
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
        m_boundFBO = m_fbo;
        if (m_attributes.depth || m_attributes.stencil)
            glGenRenderbuffersEXT(1, &m_depthStencilBuffer);
        // Generate the multisample framebuffer object
        if (m_attributes.antialias) {
            glGenFramebuffersEXT(1, &m_multisampleFBO);
            glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO);
            m_boundFBO = m_multisampleFBO;
            glGenRenderbuffersEXT(1, &m_multisampleColorBuffer);
            if (m_attributes.depth || m_attributes.stencil)
                glGenRenderbuffersEXT(1, &m_multisampleDepthStencilBuffer);
        }
    }

    GLint internalColorFormat, colorFormat, internalDepthStencilFormat = 0;
    if (m_attributes.alpha) {
        internalColorFormat = GL_RGBA8;
        colorFormat = GL_RGBA;
    } else {
        internalColorFormat = GL_RGB8;
        colorFormat = GL_RGB;
    }
    if (m_attributes.stencil || m_attributes.depth) {
        // We don't allow the logic where stencil is required and depth is not.
        // See GraphicsContext3DInternal constructor.
        if (m_attributes.stencil && m_attributes.depth)
            internalDepthStencilFormat = GL_DEPTH24_STENCIL8_EXT;
        else
            internalDepthStencilFormat = GL_DEPTH_COMPONENT;
    }

    bool mustRestoreFBO = false;

    // Resize multisampling FBO
    if (m_attributes.antialias) {
        GLint maxSampleCount;
        glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSampleCount);
        GLint sampleCount = std::min(8, maxSampleCount);
        if (m_boundFBO != m_multisampleFBO) {
            mustRestoreFBO = true;
            glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO);
        }
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_multisampleColorBuffer);
        glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, sampleCount, internalColorFormat, width, height);
        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, m_multisampleColorBuffer);
        if (m_attributes.stencil || m_attributes.depth) {
            glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_multisampleDepthStencilBuffer);
            glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, sampleCount, internalDepthStencilFormat, width, height);
            if (m_attributes.stencil)
                glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_multisampleDepthStencilBuffer);
            if (m_attributes.depth)
                glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_multisampleDepthStencilBuffer);
        }
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
        GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
        if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
            printf("GraphicsContext3D: multisampling framebuffer was incomplete\n");

            // FIXME: cleanup.
            notImplemented();
        }
    }

    // Resize regular FBO
    if (m_boundFBO != m_fbo) {
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
        mustRestoreFBO = true;
    }
    glBindTexture(target, m_texture);
    glTexImage2D(target, 0, internalColorFormat, width, height, 0, colorFormat, GL_UNSIGNED_BYTE, 0);
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target, m_texture, 0);
    glBindTexture(target, 0);
    if (!m_attributes.antialias && (m_attributes.stencil || m_attributes.depth)) {
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthStencilBuffer);
        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, internalDepthStencilFormat, width, height);
        if (m_attributes.stencil)
            glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthStencilBuffer);
        if (m_attributes.depth)
            glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthStencilBuffer);
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
    }
    GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
    if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
        printf("WebGraphicsContext3DDefaultImpl: framebuffer was incomplete\n");

        // FIXME: cleanup.
        notImplemented();
    }

    if (m_attributes.antialias) {
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO);
        if (m_boundFBO == m_multisampleFBO)
            mustRestoreFBO = false;
    }

    // Initialize renderbuffers to 0.
    GLboolean colorMask[] = {GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE}, depthMask = GL_TRUE, stencilMask = GL_TRUE;
    GLboolean isScissorEnabled = GL_FALSE;
    GLboolean isDitherEnabled = GL_FALSE;
    GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
    glGetBooleanv(GL_COLOR_WRITEMASK, colorMask);
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    if (m_attributes.depth) {
        glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask);
        glDepthMask(GL_TRUE);
        clearMask |= GL_DEPTH_BUFFER_BIT;
    }
    if (m_attributes.stencil) {
        glGetBooleanv(GL_STENCIL_WRITEMASK, &stencilMask);
        glStencilMask(GL_TRUE);
        clearMask |= GL_STENCIL_BUFFER_BIT;
    }
    isScissorEnabled = glIsEnabled(GL_SCISSOR_TEST);
    glDisable(GL_SCISSOR_TEST);
    isDitherEnabled = glIsEnabled(GL_DITHER);
    glDisable(GL_DITHER);

    glClear(clearMask);

    glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
    if (m_attributes.depth)
        glDepthMask(depthMask);
    if (m_attributes.stencil)
        glStencilMask(stencilMask);
    if (isScissorEnabled)
        glEnable(GL_SCISSOR_TEST);
    else
        glDisable(GL_SCISSOR_TEST);
    if (isDitherEnabled)
        glEnable(GL_DITHER);
    else
        glDisable(GL_DITHER);

    if (mustRestoreFBO)
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_boundFBO);

#ifdef FLIP_FRAMEBUFFER_VERTICALLY
    if (m_scanline) {
        delete[] m_scanline;
        m_scanline = 0;
    }
    m_scanline = new unsigned char[width * 4];
#endif // FLIP_FRAMEBUFFER_VERTICALLY
}
/*!****************************************************************************
 @Function		DoStencilTest
 @Description	Performs the Stencil test
******************************************************************************/
void OGLES2ShadowVolumes::DoStencilTest()
{
	/*
		For a detailed explanation on how to use the Stencil Buffer see the training course
		Stencil Buffer.
	*/
	// Use the shader program that is used for the shadow volumes
	glUseProgram(m_ShadowVolShader.uiId);

	// Set the VolumeScale variable in the shader to say how much to extrude the volume by
	glUniform1f(m_ShadowVolShader.auiLoc[eVolumeScale], 1000.0f);

	const float afColor[] = { 0.4f, 1.0f, 0.0f, 0.2f };
	glUniform4fv(m_ShadowVolShader.auiLoc[eColor], 1, afColor);


	//If we want to display the shadow volumes don't disable the colour mask and enable blending
	if(m_bDisplayVolumes)
	{
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}
	else // Disable the colour mask so we don't draw to the colour buffer
		glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

	// Disable writing to the depth buffer
	glDepthMask(GL_FALSE);

	// disable culling as we will want the front and back faces
	glDisable(GL_CULL_FACE);

	// Setup the stencil function
	glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);

	/*
		Setup the stencil operations for front facing triangles and for the back facing triangles

		Note:

		We are using INCR_WRAP and DECR_WRAP since we are submitting the front and back faces
		together so we won't be rendering all the INCR faces first. This way it stops the
		stencil value getting clamped at 0 or the maximum possible value.
	*/
	glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_INCR_WRAP);
	glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_DECR_WRAP);

	DrawShadowVolumes(&m_vLightPosWorld);

	// Enable Culling as we would like it back
	glEnable(GL_CULL_FACE);

	// Set the stencil function so we only draw where the stencil buffer isn't 0
	glStencilFunc(GL_NOTEQUAL, 0, 0xFFFFFFFF);
	glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

	// Enable writing to the depth buffer
	glDepthMask(GL_TRUE);

	// If we're displaying the volumes disable blending else enable the colour buffer
	if(m_bDisplayVolumes)
		glDisable(GL_BLEND);
	else
#if defined(__PALMPDK__)
		glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); // The alpha part is false as we don't want to blend with the video layer on the Palm Pre
#else
		glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
#endif
}
Esempio n. 30
0
static void
redraw(void)
{
    int i;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glPushMatrix();
    glRotatef(15.0, 1.0, 0.0, 0.0);
    glRotatef(angle, 0.0, 1.0, 0.0);

    glDepthMask(GL_FALSE);

    /* Draw the floor. */
    /*  glEnable(GL_TEXTURE_2D);*/
    glColor3f(0.1, 0.5, 1.0);
    glBegin(GL_QUADS);
    glTexCoord2f(0.0, 0.0);
    glVertex3f(-EDGE, -0.05, -EDGE);
    glTexCoord2f(20.0, 0.0);
    glVertex3f(EDGE, -0.05, -EDGE);
    glTexCoord2f(20.0, 20.0);
    glVertex3f(EDGE, -0.05, EDGE);
    glTexCoord2f(0.0, 20.0);
    glVertex3f(-EDGE, -0.05, EDGE);
    glEnd();

    /* Allow particles to blend with each other. */
    glDepthMask(GL_TRUE);

    if (blend)
        glEnable(GL_BLEND);

    if (sprite) {
        glEnable(GL_TEXTURE_2D);
#ifdef GL_ARB_point_sprite
        glEnable(GL_POINT_SPRITE_ARB);
#endif
    }

    glColor3f(1,1,1);
    glBegin(GL_POINTS);
    for (i=0; i<numPoints; i++) {
        /* Draw alive particles. */
        if (colorList[i] != DEAD) {
            if (!sprite) glColor4fv(colorSet[colorList[i]]);
            glVertex3fv(pointList[i]);
        }
    }
    glEnd();

    glDisable(GL_TEXTURE_2D);
#ifdef GL_ARB_point_sprite
    glDisable(GL_POINT_SPRITE_ARB);
#endif
    glDisable(GL_BLEND);

    glPopMatrix();

    glutSwapBuffers();
}