コード例 #1
0
ファイル: render.cpp プロジェクト: jefferis/rgl
void NormalArray::beginUse() {
  glEnableClientState(GL_NORMAL_ARRAY);
  glNormalPointer(GL_FLOAT, 0, (const GLvoid*) arrayptr );
}
コード例 #2
0
ファイル: OpenGL.cpp プロジェクト: CastBart/AndroidTesting
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
    bool exit = false;
    bool sRgb = false;

    while (!exit)
    {
        // Request a 24-bits depth buffer when creating the window
        sf::ContextSettings contextSettings;
        contextSettings.depthBits = 24;
        contextSettings.sRgbCapable = sRgb;

        // Create the main window
        sf::RenderWindow window(sf::VideoMode(800, 600), "SFML graphics with OpenGL", sf::Style::Default, contextSettings);
        window.setVerticalSyncEnabled(true);

        // Create a sprite for the background
        sf::Texture backgroundTexture;
        backgroundTexture.setSrgb(sRgb);
        if (!backgroundTexture.loadFromFile("resources/background.jpg"))
            return EXIT_FAILURE;
        sf::Sprite background(backgroundTexture);

        // Create some text to draw on top of our OpenGL object
        sf::Font font;
        if (!font.loadFromFile("resources/sansation.ttf"))
            return EXIT_FAILURE;
        sf::Text text("SFML / OpenGL demo", font);
        sf::Text sRgbInstructions("Press space to toggle sRGB conversion", font);
        sf::Text mipmapInstructions("Press return to toggle mipmapping", font);
        text.setFillColor(sf::Color(255, 255, 255, 170));
        sRgbInstructions.setFillColor(sf::Color(255, 255, 255, 170));
        mipmapInstructions.setFillColor(sf::Color(255, 255, 255, 170));
        text.setPosition(250.f, 450.f);
        sRgbInstructions.setPosition(150.f, 500.f);
        mipmapInstructions.setPosition(180.f, 550.f);

        // Load a texture to apply to our 3D cube
        sf::Texture texture;
        if (!texture.loadFromFile("resources/texture.jpg"))
            return EXIT_FAILURE;

        // Attempt to generate a mipmap for our cube texture
        // We don't check the return value here since
        // mipmapping is purely optional in this example
        texture.generateMipmap();

        // Make the window the active window for OpenGL calls
        window.setActive(true);

        // Enable Z-buffer read and write
        glEnable(GL_DEPTH_TEST);
        glDepthMask(GL_TRUE);
        glClearDepth(1.f);

        // Disable lighting
        glDisable(GL_LIGHTING);

        // Configure the viewport (the same size as the window)
        glViewport(0, 0, window.getSize().x, window.getSize().y);

        // Setup a perspective projection
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        GLfloat ratio = static_cast<float>(window.getSize().x) / window.getSize().y;
        glFrustum(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);

        // Bind the texture
        glEnable(GL_TEXTURE_2D);
        sf::Texture::bind(&texture);

        // Define a 3D cube (6 faces made of 2 triangles composed by 3 vertices)
        static const GLfloat cube[] =
        {
            // positions    // texture coordinates
            -20, -20, -20,  0, 0,
            -20,  20, -20,  1, 0,
            -20, -20,  20,  0, 1,
            -20, -20,  20,  0, 1,
            -20,  20, -20,  1, 0,
            -20,  20,  20,  1, 1,

             20, -20, -20,  0, 0,
             20,  20, -20,  1, 0,
             20, -20,  20,  0, 1,
             20, -20,  20,  0, 1,
             20,  20, -20,  1, 0,
             20,  20,  20,  1, 1,

            -20, -20, -20,  0, 0,
             20, -20, -20,  1, 0,
            -20, -20,  20,  0, 1,
            -20, -20,  20,  0, 1,
             20, -20, -20,  1, 0,
             20, -20,  20,  1, 1,

            -20,  20, -20,  0, 0,
             20,  20, -20,  1, 0,
            -20,  20,  20,  0, 1,
            -20,  20,  20,  0, 1,
             20,  20, -20,  1, 0,
             20,  20,  20,  1, 1,

            -20, -20, -20,  0, 0,
             20, -20, -20,  1, 0,
            -20,  20, -20,  0, 1,
            -20,  20, -20,  0, 1,
             20, -20, -20,  1, 0,
             20,  20, -20,  1, 1,

            -20, -20,  20,  0, 0,
             20, -20,  20,  1, 0,
            -20,  20,  20,  0, 1,
            -20,  20,  20,  0, 1,
             20, -20,  20,  1, 0,
             20,  20,  20,  1, 1
        };

        // Enable position and texture coordinates vertex components
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glVertexPointer(3, GL_FLOAT, 5 * sizeof(GLfloat), cube);
        glTexCoordPointer(2, GL_FLOAT, 5 * sizeof(GLfloat), cube + 3);

        // Disable normal and color vertex components
        glDisableClientState(GL_NORMAL_ARRAY);
        glDisableClientState(GL_COLOR_ARRAY);

        // Make the window no longer the active window for OpenGL calls
        window.setActive(false);

        // Create a clock for measuring the time elapsed
        sf::Clock clock;

        // Flag to track whether mipmapping is currently enabled
        bool mipmapEnabled = true;

        // Start game loop
        while (window.isOpen())
        {
            // Process events
            sf::Event event;
            while (window.pollEvent(event))
            {
                // Close window: exit
                if (event.type == sf::Event::Closed)
                {
                    exit = true;
                    window.close();
                }

                // Escape key: exit
                if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
                {
                    exit = true;
                    window.close();
                }

                // Return key: toggle mipmapping
                if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Return))
                {
                    if (mipmapEnabled)
                    {
                        // We simply reload the texture to disable mipmapping
                        if (!texture.loadFromFile("resources/texture.jpg"))
                            return EXIT_FAILURE;

                        mipmapEnabled = false;
                    }
                    else
                    {
                        texture.generateMipmap();

                        mipmapEnabled = true;
                    }
                }

                // Space key: toggle sRGB conversion
                if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Space))
                {
                    sRgb = !sRgb;
                    window.close();
                }

                // Adjust the viewport when the window is resized
                if (event.type == sf::Event::Resized)
                {
                    // Make the window the active window for OpenGL calls
                    window.setActive(true);

                    glViewport(0, 0, event.size.width, event.size.height);

                    // Make the window no longer the active window for OpenGL calls
                    window.setActive(false);
                }
            }

            // Draw the background
            window.pushGLStates();
            window.draw(background);
            window.popGLStates();

            // Make the window the active window for OpenGL calls
            window.setActive(true);

            // Clear the depth buffer
            glClear(GL_DEPTH_BUFFER_BIT);

            // We get the position of the mouse cursor, so that we can move the box accordingly
            float x =  sf::Mouse::getPosition(window).x * 200.f / window.getSize().x - 100.f;
            float y = -sf::Mouse::getPosition(window).y * 200.f / window.getSize().y + 100.f;

            // Apply some transformations
            glMatrixMode(GL_MODELVIEW);
            glLoadIdentity();
            glTranslatef(x, y, -100.f);
            glRotatef(clock.getElapsedTime().asSeconds() * 50.f, 1.f, 0.f, 0.f);
            glRotatef(clock.getElapsedTime().asSeconds() * 30.f, 0.f, 1.f, 0.f);
            glRotatef(clock.getElapsedTime().asSeconds() * 90.f, 0.f, 0.f, 1.f);

            // Draw the cube
            glDrawArrays(GL_TRIANGLES, 0, 36);

            // Make the window no longer the active window for OpenGL calls
            window.setActive(false);

            // Draw some text on top of our OpenGL object
            window.pushGLStates();
            window.draw(text);
            window.draw(sRgbInstructions);
            window.draw(mipmapInstructions);
            window.popGLStates();

            // Finally, display the rendered frame on screen
            window.display();
        }
    }

    return EXIT_SUCCESS;
}
コード例 #3
0
static GLboolean test()
{
    GLboolean pass = GL_TRUE;

    /* Prepare the shaders */
    GLint prog       = setup_shaders();
    GLint uPixelSize = glGetUniformLocation(prog, "pixelSize");
    GLint uTexUnit   = glGetUniformLocation(prog, "texUnit");
    GLuint scratchTex;
    int i;

    /* Pixel sizes in texture coordinates for the horizontal and vertical passes */
    const float horizontal[2] = { 1.0 / WIDTH, 0 };
    const float vertical[2]   = { 0, 1.0 / HEIGHT };

    /* Texture and vertex coordinates */
    const float tc[] = { 0,1, 1,1, 0,0, 0,0, 1,1, 1,0 };
    const float vc[] = { -1,1, 1,1, -1,-1, -1,-1, 1,1, 1,-1 };

    /* Draw the rectangle that we're going to blur */
    piglit_draw_rect(-.5, -.5, 1, 1);

    /* Create a scratch texture */
    glGenTextures(1, &scratchTex);
    glBindTexture(GL_TEXTURE_2D, scratchTex);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, WIDTH, HEIGHT, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0);

    glUseProgram(prog);
    glUniform1i(uTexUnit, 0);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glTexCoordPointer(2, GL_FLOAT, 0, tc);
    glVertexPointer(2, GL_FLOAT, 0, vc);

    /* Horizontal pass */
    glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, WIDTH, HEIGHT);
    glUniform2fv(uPixelSize, 1, horizontal);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    /* Vertical pass */
    glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, WIDTH, HEIGHT);
    glUniform2fv(uPixelSize, 1, vertical);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    /* Clean up */
    glUseProgram(0);
    glBindTexture(GL_TEXTURE_2D, 0);
    glDeleteTextures(1, &scratchTex);
    glDeleteProgram(prog);

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);

    if (!piglit_check_gl_error(GL_NO_ERROR))
	     piglit_report_result(PIGLIT_FAIL);

    /* Test the sides */
    for (i = 0; i < 26; i++) {
        float color[3];
        color[0] = expected_edge[i] / 255.;
        color[1] = color[0];
        color[2] = color[0];
        pass = piglit_probe_pixel_rgb(50, 12 + i, color) && pass;
        pass = piglit_probe_pixel_rgb(50, HEIGHT - 13 - i, color) && pass;
        pass = piglit_probe_pixel_rgb(12 + i, 50, color) && pass;
        pass = piglit_probe_pixel_rgb(WIDTH - 13 - i, 50, color) && pass;
    }

    /* Test the corners */
    for (i = 0; i < 22; i++) {
        float color[3];
        color[0] = expected_corner[i] / 255.;
        color[1] = color[0];
        color[2] = color[0];
        pass = piglit_probe_pixel_rgb(16 + i, 16 + i, color) && pass;
        pass = piglit_probe_pixel_rgb(16 + i, HEIGHT - 17 - i, color) && pass;
        pass = piglit_probe_pixel_rgb(WIDTH - 17 - i, 16 + i, color) && pass;
        pass = piglit_probe_pixel_rgb(WIDTH - 17 - i, HEIGHT - 17 - i, color) && pass;
    }

    return pass;
}
コード例 #4
0
ファイル: glcommon.c プロジェクト: AeonGames/AeonGUI
void DrawCube ( float size )
{
#if 0
    glBegin ( GL_QUADS );
    glColor3f ( 0.0f, 0.0f, 1.0f );
    glVertex3f ( size, size, -size );
    glVertex3f ( -size, size, -size );
    glVertex3f ( -size, size, size );
    glVertex3f ( size, size, size );
    glColor3f ( 1.0f, 0.5f, 0.0f );
    glVertex3f ( size, -size, size );
    glVertex3f ( -size, -size, size );
    glVertex3f ( -size, -size, -size );
    glVertex3f ( size, -size, -size );
    glColor3f ( 1.0f, 0.0f, 0.0f );
    glVertex3f ( size, size, size );
    glVertex3f ( -size, size, size );
    glVertex3f ( -size, -size, size );
    glVertex3f ( size, -size, size );
    glColor3f ( 1.0f, 1.0f, 0.0f );
    glVertex3f ( size, -size, -size );
    glVertex3f ( -size, -size, -size );
    glVertex3f ( -size, size, -size );
    glVertex3f ( size, size, -size );
    glColor3f ( 0.0f, 1.0f, 0.0f );
    glVertex3f ( -size, size, size );
    glVertex3f ( -size, size, -size );
    glVertex3f ( -size, -size, -size );
    glVertex3f ( -size, -size, size );
    glColor3f ( 1.0f, 0.0f, 1.0f );
    glVertex3f ( size, size, -size );
    glVertex3f ( size, size, size );
    glVertex3f ( size, -size, size );
    glVertex3f ( size, -size, -size );
    glEnd();
#else
    float cube [] =
    {
        size, size, -size ,
        0.0f, 0.0f, 1.0f ,
        -size, size, -size ,
        0.0f, 0.0f, 1.0f ,
        -size, size, size ,
        0.0f, 0.0f, 1.0f ,
        size, size, size ,
        0.0f, 0.0f, 1.0f ,
        size, -size, size ,
        1.0f, 0.5f, 0.0f ,
        -size, -size, size ,
        1.0f, 0.5f, 0.0f ,
        -size, -size, -size ,
        1.0f, 0.5f, 0.0f ,
        size, -size, -size ,
        1.0f, 0.5f, 0.0f ,
        size, size, size ,
        1.0f, 0.0f, 0.0f ,
        -size, size, size ,
        1.0f, 0.0f, 0.0f ,
        -size, -size, size ,
        1.0f, 0.0f, 0.0f ,
        size, -size, size ,
        1.0f, 0.0f, 0.0f ,
        size, -size, -size ,
        1.0f, 1.0f, 0.0f ,
        -size, -size, -size ,
        1.0f, 1.0f, 0.0f ,
        -size, size, -size ,
        1.0f, 1.0f, 0.0f ,
        size, size, -size ,
        1.0f, 1.0f, 0.0f ,
        -size, size, size ,
        0.0f, 1.0f, 0.0f ,
        -size, size, -size ,
        0.0f, 1.0f, 0.0f ,
        -size, -size, -size ,
        0.0f, 1.0f, 0.0f ,
        -size, -size, size ,
        0.0f, 1.0f, 0.0f ,
        size, size, -size ,
        1.0f, 0.0f, 1.0f ,
        size, size, size ,
        1.0f, 0.0f, 1.0f ,
        size, -size, size ,
        1.0f, 0.0f, 1.0f ,
        size, -size, -size ,
        1.0f, 0.0f, 1.0f
    };
    glVertexPointer ( 3, GL_FLOAT, sizeof ( float ) * 6, cube );
    glColorPointer ( 3, GL_FLOAT, sizeof ( float ) * 6, cube + 3 );
    glPushClientAttrib ( GL_CLIENT_VERTEX_ARRAY_BIT );
    glEnableClientState ( GL_VERTEX_ARRAY );
    glEnableClientState ( GL_COLOR_ARRAY );
    glDrawArrays ( GL_QUADS, 0, 24 );
    glPopClientAttrib();
#endif
}
コード例 #5
0
void InfiniTAMApp::RenderGL(void)
{
	glClear(GL_COLOR_BUFFER_BIT);
	if (!IsInitialized()) return;

	if (mNewWindowSize.x > 0) {
		Vector2i depthImageSize = mMainEngine->GetImageSize();
		float ratio = (float)depthImageSize.x/(float)depthImageSize.y;

//		glViewport(0, 0, newWidth, newHeight);
		if (mNewWindowSize.x >= mNewWindowSize.y) {
			winPos[0] = Vector4f(0.0f, 0.0f, 1.0f/ratio, 1.0f);
			winPos[1] = Vector4f(1.0f/ratio, 0.5f, 1.0f, 1.0f);
			winPos[2] = Vector4f(1.0f/ratio, 0.0f, 1.0f, 0.5f);
		} else {
			winPos[0] = Vector4f(0.0f, 1.0f/3.0f, 1.0f, 1.0f);
			winPos[1] = Vector4f(0.0f, 0.0f, 0.5f, 1.0f/3.0f);
			winPos[2] = Vector4f(0.5f, 0.0f, 1.0f, 1.0f/3.0f);
		}

		mNewWindowSize.x = mNewWindowSize.y = -1;
	}

	int localNumWin = 1;//NUM_WIN
	for (int w = 0; w < localNumWin; w++) mMainEngine->GetImage(outImage[w], winImageType[w]);

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	{
		glLoadIdentity();
		glOrthof(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f);

		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		{
			glEnable(GL_TEXTURE_2D);
			glDisable(GL_BLEND);
			glEnableClientState(GL_VERTEX_ARRAY);
			glEnableClientState(GL_TEXTURE_COORD_ARRAY);
			for (int w = 0; w < localNumWin; w++) {
				glBindTexture(GL_TEXTURE_2D, textureId[w]);
				glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, outImage[w]->noDims.x, outImage[w]->noDims.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, outImage[w]->GetData(MEMORYDEVICE_CPU));
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

				float vertices[] = {
					winPos[w][0], winPos[w][3],
					winPos[w][2], winPos[w][3],
					winPos[w][0], winPos[w][1],
					winPos[w][2], winPos[w][1] };
				float texture[] = {
					0.0f, 0.0f,
					1.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 1.0f };

				glVertexPointer(2, GL_FLOAT, 0, vertices);
				glTexCoordPointer(2, GL_FLOAT, 0, texture);
				glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
			}
			glDisableClientState(GL_VERTEX_ARRAY);
			glDisableClientState(GL_TEXTURE_COORD_ARRAY);
			glDisable(GL_TEXTURE_2D);
		}
		glPopMatrix();
	}
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
}
コード例 #6
0
ファイル: opengl_window.cpp プロジェクト: basisbit/neogfx
	void opengl_window::render()
	{
		if (iRendering || processing_event())
			return;

		uint64_t now = app::instance().program_elapsed_ms();
		if (iFrameRate != boost::none && now - iLastFrameTime < 1000 / *iFrameRate)
			return;

		if (!iEventHandler.native_window_ready_to_render())
			return;

		rendering_check.trigger();

		if (iInvalidatedRects.empty())
			return;

		++iFrameCounter;

		iRendering = true;
		iLastFrameTime = now;

		rendering.trigger();

		rect invalidatedRect = *iInvalidatedRects.begin();
		for (const auto& ir : iInvalidatedRects)
		{
			invalidatedRect = invalidatedRect.combine(ir);
		}
		iInvalidatedRects.clear();
		invalidatedRect.cx = std::min(invalidatedRect.cx, surface_size().cx - invalidatedRect.x);
		invalidatedRect.cy = std::min(invalidatedRect.cy, surface_size().cy - invalidatedRect.y);

		static bool initialized = false;
		if (!initialized)
		{
			rendering_engine().initialize();
			initialized = true;
		}

		activate_context();

		glCheck(glViewport(0, 0, static_cast<GLsizei>(extents().cx), static_cast<GLsizei>(extents().cy)));
		glCheck(glMatrixMode(GL_PROJECTION));
		glCheck(glLoadIdentity());
		glCheck(glScalef(1.0, 1.0, 1.0));
		glCheck(glMatrixMode(GL_MODELVIEW));
		glCheck(glLoadIdentity());
		const auto& logicalCoordinates = logical_coordinates();
		glCheck(glOrtho(logicalCoordinates[0], logicalCoordinates[2], logicalCoordinates[1], logicalCoordinates[3], -1.0, 1.0));
		glCheck(glEnableClientState(GL_VERTEX_ARRAY));
		glCheck(glEnableClientState(GL_COLOR_ARRAY));
		glCheck(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
		glCheck(glEnable(GL_TEXTURE_2D));
		glCheck(glEnable(GL_MULTISAMPLE));
		glCheck(glEnable(GL_BLEND));
		if (iFrameBufferSize.cx < static_cast<double>(extents().cx) || iFrameBufferSize.cy < static_cast<double>(extents().cy))
		{
			if (iFrameBufferSize != size{})
			{
				glCheck(glDeleteRenderbuffers(1, &iDepthStencilBuffer));
				glCheck(glDeleteTextures(1, &iFrameBufferTexture));
				glCheck(glDeleteFramebuffers(1, &iFrameBuffer));
			}
			iFrameBufferSize = size(
				iFrameBufferSize.cx < extents().cx ? extents().cx * 1.5f : iFrameBufferSize.cx,
				iFrameBufferSize.cy < extents().cy ? extents().cy * 1.5f : iFrameBufferSize.cy);
			glCheck(glGenFramebuffers(1, &iFrameBuffer));
			glCheck(glBindFramebuffer(GL_FRAMEBUFFER, iFrameBuffer));
			glCheck(glGenTextures(1, &iFrameBufferTexture));
			glCheck(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, iFrameBufferTexture));
			glCheck(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_RGBA8, static_cast<GLsizei>(iFrameBufferSize.cx), static_cast<GLsizei>(iFrameBufferSize.cy), true));
			glCheck(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, iFrameBufferTexture, 0));
			glCheck(glGenRenderbuffers(1, &iDepthStencilBuffer));
			glCheck(glBindRenderbuffer(GL_RENDERBUFFER, iDepthStencilBuffer));
			glCheck(glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH24_STENCIL8, static_cast<GLsizei>(iFrameBufferSize.cx), static_cast<GLsizei>(iFrameBufferSize.cy)));
			glCheck(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, iDepthStencilBuffer));
			glCheck(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, iDepthStencilBuffer));
		}
		else
		{
			glCheck(glBindFramebuffer(GL_FRAMEBUFFER, iFrameBuffer));
			glCheck(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, iFrameBufferTexture));
			glCheck(glBindRenderbuffer(GL_RENDERBUFFER, iDepthStencilBuffer));
		}
		GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
		if (status != GL_NO_ERROR && status != GL_FRAMEBUFFER_COMPLETE)
			throw failed_to_create_framebuffer(status);
		glCheck(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, iFrameBuffer));
		GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0 };
		glCheck(glDrawBuffers(sizeof(drawBuffers) / sizeof(drawBuffers[0]), drawBuffers));

		glCheck(iEventHandler.native_window_render(invalidatedRect));

		glCheck(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0));
		glCheck(glBindFramebuffer(GL_READ_FRAMEBUFFER, iFrameBuffer));
		glCheck(glBlitFramebuffer(0, 0, static_cast<GLint>(extents().cx), static_cast<GLint>(extents().cy), 0, 0, static_cast<GLint>(extents().cx), static_cast<GLint>(extents().cy), GL_COLOR_BUFFER_BIT, GL_NEAREST));

		display();
		deactivate_context();

		iRendering = false;

		rendering_finished.trigger();
	}
コード例 #7
0
ファイル: imgui_impl_glfw.cpp プロジェクト: gyakoo/simutils
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
static void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data)
{
    // We are using the OpenGL fixed pipeline to make the example code simpler to read!
    // A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
    // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
    glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnable(GL_TEXTURE_2D);
    //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context

    // Setup orthographic projection matrix
    const float width = ImGui::GetIO().DisplaySize.x;
    const float height = ImGui::GetIO().DisplaySize.y;
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    // Render command lists
    #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front();
        const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front();
        glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, pos)));
        glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, uv)));
        glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, col)));

        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
        {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
                glScissor((int)pcmd->ClipRect.x, (int)(height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer);
            }
            idx_buffer += pcmd->ElemCount;
        }
    }
    #undef OFFSETOF

    // Restore modified state
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    glBindTexture(GL_TEXTURE_2D, 0);
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
}
コード例 #8
0
ファイル: output_5.cpp プロジェクト: Firobe/Pathfinder
void outPut::drawNormals(bool reinit)
{
    static VA normals;
    static GLuint buf_pos;
    unsigned int nbVertices = _dimensions.x*_dimensions.y*2;

    if(reinit)
    {
        glDeleteBuffers(1,&buf_pos);
        delete normals.verticesA;

        normals.verticesA = new float[nbVertices*P_SIZE];

#define NORM_SCALE 2.5
///Remplissage des tableaux de sommets et de couleurs
        for(unsigned int i = 0; i < _dimensions.x; i++)
        {
            for(unsigned int j = 0; j < _dimensions.y; j++)
            {
                coords3d<float> vertex(0,0,0), normal(0,0,0);

                vertex = getVertex<float>(i,j);
                normal = _scene3d.normalMap[i][j];
                normals.verticesA[(i*_dimensions.y+j)*P_SIZE*2] = vertex.x;
                normals.verticesA[(i*_dimensions.y+j)*P_SIZE*2+1] = vertex.y;
                normals.verticesA[(i*_dimensions.y+j)*P_SIZE*2+2] = vertex.z;

                normals.verticesA[(i*_dimensions.y+j)*P_SIZE*2+3] = vertex.x+normal.x*NORM_SCALE;
                normals.verticesA[(i*_dimensions.y+j)*P_SIZE*2+4] = vertex.y+normal.y*NORM_SCALE;
                normals.verticesA[(i*_dimensions.y+j)*P_SIZE*2+5] = vertex.z+normal.z*NORM_SCALE;
            }
        }
        /* creation de nos VBO+IBO */
        glGenBuffers(1, &buf_pos);

        /* construction du VBO de positions */
        glBindBuffer(GL_ARRAY_BUFFER, buf_pos);
        glBufferData(GL_ARRAY_BUFFER, (nbVertices*P_SIZE*sizeof *normals.verticesA),
                     NULL, GL_STREAM_DRAW);

        glBufferSubData(GL_ARRAY_BUFFER, 0, (nbVertices*P_SIZE*sizeof
                                             *normals.verticesA), normals.verticesA);

    //On debind le VBO
    glBindBuffer(GL_ARRAY_BUFFER, 0);

       // cout<<"\n(re)initialisation de l'affichage des normales reussie\n";
    }
    glUseProgram(_sNolight.getProgramID());
    /* specification du buffer des positions de sommets */
    glBindBuffer(GL_ARRAY_BUFFER, buf_pos);
    glVertexPointer(P_SIZE, GL_FLOAT, 0, BUFFER_OFFSET(0));

    glColor3ub(255,0,255);

    glEnableClientState(GL_VERTEX_ARRAY);

    glDrawArrays(GL_LINES, 0, nbVertices);

    glDisableClientState(GL_VERTEX_ARRAY);

    //On debind le VBO
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}
コード例 #9
0
ファイル: output_5.cpp プロジェクト: Firobe/Pathfinder
void outPut::drawTerrain(bool reinit)
{
    static bool lastwfStatus(!_reg.WIREFRAME);
    if(lastwfStatus != _reg.WIREFRAME)
    {
        if(_reg.WIREFRAME)
            {
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        glLineWidth(1);
    }
    else
    {
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    }}
    lastwfStatus = _reg.WIREFRAME;

    static bool init(true);
    static VA terrain;
    static GLuint buf_pos, buf_norm, buf_cost, buf_index;

    unsigned int nbVertices = _dimensions.x*_dimensions.y;
    unsigned int nbIndex = (_dimensions.x-1)*(_dimensions.y-1)*6;
    //nbIndex = nbVertices;
    /*Chaque vertex est associé à une maille qui 'coûte' 6 indices en mémoire :
         _
        |\| -> deux triangles, avec 3 indices par triangle. On enlève une ligne et une colonne parce que ceux sur les côtés n'entrainent pas une maille.
        +-
         */

    if(init || reinit)
    {
        gen_verticesMap();
        drawNormals(true);

        glDeleteBuffers(1,&buf_pos);
        glDeleteBuffers(1,&buf_norm);
        glDeleteBuffers(1,&buf_cost);
        glDeleteBuffers(1,&buf_index);


        delete terrain.verticesA;
        delete terrain.normalsA;
        delete terrain.costsA;
        delete terrain.indexA;

        terrain.verticesA = new float[nbVertices*P_SIZE];
        terrain.normalsA = new float[nbVertices*N_SIZE];
        terrain.costsA = new int[nbVertices*C_SIZE];
        terrain.indexA = new unsigned int[nbIndex];

///Remplissage des tableaux de sommets et de coûts
        for(unsigned int i = 0; i < _dimensions.x; i++)
        {
            for(unsigned int j = 0; j < _dimensions.y; j++)
            {
                coords3d<float> vertex(0,0,0), normal(0,0,0);

                vertex = getVertex<float>(i,j);
                normal = _scene3d.normalMap[i][j];

                int vertexPos = (i*_dimensions.y+j);

                terrain.verticesA[vertexPos*P_SIZE] = vertex.x;
                terrain.verticesA[vertexPos*P_SIZE+1] = vertex.y;
                terrain.verticesA[vertexPos*P_SIZE+2] = vertex.z;

                terrain.normalsA[vertexPos*P_SIZE] = normal.x;
                terrain.normalsA[vertexPos*P_SIZE+1] = normal.y;
                terrain.normalsA[vertexPos*P_SIZE+2] = normal.z;

                terrain.costsA[vertexPos*C_SIZE] = -1;
            }
        }
///Remplissage de l'index
        for(unsigned int i = 0; i < _dimensions.x-1; i++)
        {
            for(unsigned int j = 0; j < _dimensions.y-1; j++)
            {
                terrain.indexA[((i*(_dimensions.y-1))+j)*6] = i*_dimensions.y+j;
                terrain.indexA[((i*(_dimensions.y-1))+j)*6+2] = i*_dimensions.y+j+1;
                terrain.indexA[((i*(_dimensions.y-1))+j)*6+1] = (i+1)*_dimensions.y+j;
                terrain.indexA[((i*(_dimensions.y-1))+j)*6+3] = i*_dimensions.y+j+1;
                terrain.indexA[((i*(_dimensions.y-1))+j)*6+4] = (i+1)*_dimensions.y+j;
                terrain.indexA[((i*(_dimensions.y-1))+j)*6+5] = (i+1)*_dimensions.y+j+1;
                //cout << "\nindice max : " << ((i*(_dimensions.y-1))+j)*6+5 << " / " << nbIndex;

            }
        }

        /* creation de nos VBO+IBO */
        glGenBuffers(1, &buf_pos);
        glGenBuffers(1, &buf_cost);
        glGenBuffers(1, &buf_norm);
        glGenBuffers(1, &buf_index);

        /* construction du VBO de positions */
        glBindBuffer(GL_ARRAY_BUFFER, buf_pos);
        glBufferData(GL_ARRAY_BUFFER, (nbVertices*P_SIZE*sizeof *terrain.verticesA),
                     NULL, GL_STREAM_DRAW);

        glBufferSubData(GL_ARRAY_BUFFER, 0, (nbVertices*P_SIZE*sizeof
                                             *terrain.verticesA), terrain.verticesA);

        /* construction du VBO de normales */
        glBindBuffer(GL_ARRAY_BUFFER, buf_norm);
        glBufferData(GL_ARRAY_BUFFER, (nbVertices*N_SIZE*sizeof *terrain.normalsA),
                     NULL, GL_STREAM_DRAW);
        glBufferSubData(GL_ARRAY_BUFFER, 0, (nbVertices*N_SIZE*sizeof
                                             *terrain.normalsA), terrain.normalsA);

        /* construction du VBO de coûts */
        glBindBuffer(GL_ARRAY_BUFFER, buf_cost);
        glBufferData(GL_ARRAY_BUFFER, (nbVertices*C_SIZE*sizeof *terrain.costsA),
                     NULL, GL_STREAM_DRAW);
        glBufferSubData(GL_ARRAY_BUFFER, 0, (nbVertices*C_SIZE*sizeof
                                             *terrain.costsA), terrain.costsA);


        /* construction du IBO */
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buf_index);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, nbIndex * sizeof *terrain.indexA,
                     NULL, GL_STREAM_DRAW);
        glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, nbIndex * sizeof
                        *terrain.indexA, terrain.indexA);

    //On debind les VBO+IBO
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    _maxValue = 1;

//        cout<<"\n(re)initialisation de l'affichage du terrain reussie\n";
        init = false;
        _valueChanges.clear();
    }
    drawAxis();

    glBindBuffer(GL_ARRAY_BUFFER, buf_cost);
    for(unsigned int i = 0; i < _valueChanges.size(); ++i)
    {
        int newCost = _valueChanges[i].value;
        //newCost = 2;
        //std::cout << newCost << "/" << _maxValue << std::endl;
        glBufferSubData(GL_ARRAY_BUFFER, (_valueChanges[i].x*_dimensions.y + _valueChanges[i].y)*(sizeof newCost)*C_SIZE, (sizeof
                                             newCost), &newCost);
        //terrain.costsA[_valueChanges[i].x*_dimensions.y + _valueChanges[i].y] = newCost;
    }
    /*
    glBufferSubData(GL_ARRAY_BUFFER, 0, (nbVertices*C_SIZE*sizeof
                                        *terrain.costsA), terrain.costsA);*/
    catchError("application de changements de couleur");
    _valueChanges.clear();

    glEnable(GL_DEPTH_TEST);
    if(_reg.DRAW_NORMALS)
        drawNormals();

    glUseProgram(_sLight.getProgramID());
    //Envoi des uniforms
    glUniform1i(uid_maxCost, _maxValue);
    catchError("Envoi de la valeur max");
    glUniform3f(uid_defaultColor, _reg.UNIFORM_COLOR[0],_reg.UNIFORM_COLOR[1],_reg.UNIFORM_COLOR[2]);
    /* specification du buffer des positions de sommets */
    glEnableVertexAttribArray(aID_position);
    glBindBuffer(GL_ARRAY_BUFFER, buf_pos);
    glVertexAttribPointer(aID_position, P_SIZE , GL_FLOAT, 0, 0, BUFFER_OFFSET(0) );
    /* specification du buffer des normales de sommets */
    glEnableVertexAttribArray(aID_normal);
    glBindBuffer(GL_ARRAY_BUFFER, buf_norm);
    glVertexAttribPointer(aID_normal, N_SIZE , GL_FLOAT, 0, 0, BUFFER_OFFSET(0) );
    /* specification du buffer des coûts de sommets */
    glEnableVertexAttribArray(aID_cost);
    glBindBuffer(GL_ARRAY_BUFFER, buf_cost);
    glVertexAttribIPointer(aID_cost, C_SIZE, GL_INT, 0, BUFFER_OFFSET(0));

    /*Spécification de l'index*/
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buf_index);

    glEnableClientState(GL_VERTEX_ARRAY);

    glDrawElements(GL_TRIANGLES, nbIndex, GL_UNSIGNED_INT, BUFFER_OFFSET(0));

    glDisableVertexAttribArray(aID_position);
    glDisableVertexAttribArray(aID_normal);
    glDisableVertexAttribArray(aID_cost);

    //On debind les VBO+IBO
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glDisableVertexAttribArray(aID_position);
    glDisableVertexAttribArray(aID_normal);
    glDisableVertexAttribArray(aID_cost);
    glUseProgram(0);
}
コード例 #10
0
ファイル: lwSprite.cpp プロジェクト: henyouqian/arrow
	void Sprite::draw(){
		ImageStaticData& d = g_imageStaticData;
		if ( d.vertexVec.empty() && d.batchInfoVec.empty() ){
			return;
		}
#ifdef USEVBO		
		if ( d.vbo == -1 ){
			glGenBuffers(1, &d.vbo);
		}
#endif

		glDisable(GL_LIGHTING);
		glDepthMask(GL_FALSE);

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		const App::Config conf = App::getConfig();
		float w = (float)conf.width;
		float h = (float)conf.height;
#ifdef __APPLE__
		float rotDegree = 0;
		const App::Orientation orient = App::getConfig().orientation;
		switch (orient) {
			case App::ORIENTATION_LEFT:
				rotDegree = 90;
				break;
			case App::ORIENTATION_RIGHT:
				rotDegree = -90;
				break;
			default:
				break;
		}
		glRotatef(rotDegree, 0, 0, 1);
#endif
#ifdef WIN32
		int dOrient = (App::getConfig().orientation-App::getConfig().orientation0);
		float rotDegree = -dOrient * 90.f;
		glRotatef(rotDegree, 0, 0, 1);
		//if ( abs(dOrient) == 1 ){
		//	float temp = h;
		//	h = w;
		//	w = temp;
		//}
#endif
		cml::Matrix44 m;
		cml::matrix_orthographic_RH(m, 0.f, w, -h, 0.f, Z_BEGIN, Z_END, cml::z_clip_neg_one);
		glMultMatrixf(m.data());

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		glEnable(GL_TEXTURE_2D);

		glEnableClientState(GL_VERTEX_ARRAY);
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);

		glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

#ifdef USEVBO
		glBindBuffer(GL_ARRAY_BUFFER, d.vbo);
		glBufferData(GL_ARRAY_BUFFER, (int)d.vertexVec.size()*sizeof(Vertex), &(d.vertexVec[0]), GL_DYNAMIC_DRAW);
		glVertexPointer(3, GL_FLOAT, sizeof(Vertex), (GLvoid*)0);
		glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (GLvoid*)(sizeof(float)*3));
#else
		if ( !d.vertexVec.empty() ){
			glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &(d.vertexVec[0]));
			char* p = (char*)&(d.vertexVec[0]);
			glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), p+(sizeof(float)*3));
		}
#endif
		
		bool blendEnabled = false;
		for ( size_t i = 0; i < d.batchInfoVec.size(); ++i ){
			BatchInfo& batchInfo = d.batchInfoVec[i];
			glColor4f(batchInfo.color.r/255.f, batchInfo.color.g/255.f, batchInfo.color.b/255.f, batchInfo.color.a/255.f);
			if ( !batchInfo.rsObjs.empty() ){
				std::vector<RanderStateObj*>::iterator it = batchInfo.rsObjs.begin();
				std::vector<RanderStateObj*>::iterator itEnd = batchInfo.rsObjs.end();
				for ( ; it != itEnd; ++it ){
					(*it)->set();
				}
			}
			if ( batchInfo.vertexOffset == -2 ){
				if ( !batchInfo.rsObjs.empty() ){
					std::vector<RanderStateObj*>::iterator it = batchInfo.rsObjs.begin();
					std::vector<RanderStateObj*>::iterator itEnd = batchInfo.rsObjs.end();
					for ( ; it != itEnd; ++it ){
						delete (*it);
					}
				}
				batchInfo.rsObjs.clear();
				continue;
			}
			//model
			if ( batchInfo.vertexOffset == -1 ){
				batchInfo.pModle->drawAsSprite(batchInfo.nodeIndex);
				if ( blendEnabled ){
					glEnable(GL_BLEND);
					//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				}else{
					glDisable(GL_BLEND);
				}
				if ( !d.vertexVec.empty() && i < d.batchInfoVec.size()-1 ){
					glEnable(GL_TEXTURE_2D);
					glEnableClientState(GL_VERTEX_ARRAY);
					glEnableClientState(GL_TEXTURE_COORD_ARRAY);
					glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &(d.vertexVec[0]));
					char* p = (char*)&(d.vertexVec[0]);
					glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), p+(sizeof(float)*3));
				}

				if ( !batchInfo.rsObjs.empty() ){
					std::vector<RanderStateObj*>::iterator it = batchInfo.rsObjs.begin();
					std::vector<RanderStateObj*>::iterator itEnd = batchInfo.rsObjs.end();
					for ( ; it != itEnd; ++it ){
						delete (*it);
					}
				}
				batchInfo.rsObjs.clear();
				continue;
			}

			bool shouldBlend = batchInfo.hasAlpha || batchInfo.color.a != 255;
			if ( shouldBlend != blendEnabled ){
				blendEnabled = shouldBlend;
				if ( blendEnabled ){
					glEnable(GL_BLEND);
					//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				}else{
					glDisable(GL_BLEND);
				}
			}
			
			glBindTexture(GL_TEXTURE_2D, batchInfo.textureId);
			lwassert(glGetError()==GL_NO_ERROR);
			//find next sprite batch
			int sz = 0;
			bool find = false;
			for ( size_t idx = i+1; idx < d.batchInfoVec.size(); ++idx ){
				if ( d.batchInfoVec[idx].vertexOffset != -1 ){
					sz = d.batchInfoVec[idx].vertexOffset - batchInfo.vertexOffset;
					find = true;
					break;
				}
			}
			if ( !find ){
				sz = (int)d.vertexVec.size()-batchInfo.vertexOffset;
			}
			//if ( i == d.batchInfoVec.size() - 1 ){
			//	sz = (int)d.vertexVec.size()-batchInfo.vertexOffset;
			//}else{
			//	sz = d.batchInfoVec[i+1].vertexOffset - batchInfo.vertexOffset;
			//}
			
			glDrawArrays(GL_TRIANGLES, batchInfo.vertexOffset, sz);

			if ( !batchInfo.rsObjs.empty() ){
				std::vector<RanderStateObj*>::iterator it = batchInfo.rsObjs.begin();
				std::vector<RanderStateObj*>::iterator itEnd = batchInfo.rsObjs.end();
				for ( ; it != itEnd; ++it ){
					delete (*it);
				}
				batchInfo.rsObjs.clear();
			}
		}

		glDepthMask(GL_TRUE);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glDisable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, 0);
		glDisableClientState(GL_VERTEX_ARRAY);
		glDisableClientState(GL_TEXTURE_COORD_ARRAY);
		if ( blendEnabled ){
			glDisable(GL_BLEND);
		}
		d.vertexVec.clear();
		d.batchInfoVec.clear();
		d.currTextureId = -1;
		//float z = g_currZ;
		g_currZ = Z_BEGIN+1.f;
	}
コード例 #11
0
ファイル: NTextInput.cpp プロジェクト: Tamschi/Astrostruct
void NTextInput::Draw(NCamera* View)
{
    GenerateBuffers();
    if (Texture == NULL || GetColor().w == 0)
    {
        return;
    }
    if (Shader == NULL)
    {
        glEnableClientState(GL_VERTEX_ARRAY);
        glBindBuffer(GL_ARRAY_BUFFER,Buffers[0]);
        glVertexPointer(2,GL_FLOAT,0,NULL);

        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glBindBuffer(GL_ARRAY_BUFFER,Buffers[1]);
        glTexCoordPointer(2,GL_FLOAT,0,NULL);

        glEnable(GL_TEXTURE_2D);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        if (Texture != NULL)
        {
            glBindTexture(GL_TEXTURE_2D,Texture->GetID());
        }

        glMatrixMode(GL_PROJECTION);
        glLoadMatrixf(&View->GetOrthoMatrix()[0][0]);
        glMatrixMode(GL_MODELVIEW);
        glm::mat4 MVP = View->GetViewMatrix()*GetModelMatrix();
        glLoadMatrixf(&MVP[0][0]);

        glColor4fv(&(GetColor()[0]));
        glDrawArrays(GL_QUADS,0,Verts.size());
        glDisable(GL_TEXTURE_2D);
        glDisable(GL_BLEND);

        glDisableClientState(GL_VERTEX_ARRAY);
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        return;
    }
    glUseProgram(Shader->GetID());
    glActiveTexture(GL_TEXTURE0);
    if (Texture != NULL)
    {
        glBindTexture(GL_TEXTURE_2D,Texture->GetID());
    }
    glUniform1i(TextureLoc,0);
    glm::mat4 MVP = View->GetOrthoMatrix()*View->GetViewMatrix()*GetModelMatrix();
    glUniformMatrix4fv(MatrixLoc,1,GL_FALSE,&MVP[0][0]);
    glUniform4fv(ColorLoc,1,&(GetColor()[0]));
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER,Buffers[0]);
    glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,0,NULL);
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER,Buffers[1]);
    glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,0,NULL);
    
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_TEXTURE_2D);
    glDrawArrays(GL_QUADS,0,Verts.size());
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_BLEND);

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glUseProgram(0);
}
コード例 #12
0
		void OpenGLES1RenderManager::DrawModelObj(ModelObj *model,Math::Vector3 position,Math::Vector3 scale,Math::Vector3 rotation)
		{
            glColor4ub(255, 255, 255, 255);
            
			glPushMatrix();
            
			glRotatef(rotation.x,1.0f,0.0f,0.0f);
			glRotatef(rotation.y,0.0f,1.0f,0.0f);
			glRotatef(rotation.z,0.0f,0.0f,1.0f);
			glTranslatef(position.x,position.y,position.z);
			glScalef(scale.x,scale.y,scale.z);
            
			for (unsigned int i = 0; i < model->mMeshes.size();i++)
			{
				ObjMesh *mesh = model->mMeshes[i];
                
				glBindTexture(GL_TEXTURE_2D, model->mMaterials[mesh->mMaterial]->texturID);
				glEnable(GL_TEXTURE_2D);
                
				glEnableClientState(GL_VERTEX_ARRAY);
				glEnableClientState(GL_TEXTURE_COORD_ARRAY);
                
				glTexCoordPointer(2, GL_FLOAT, GLsizei(sizeof(TexturesPSPVertex)), &mesh->meshVertices[0].u);
				glVertexPointer(3, GL_FLOAT, GLsizei(sizeof(TexturesPSPVertex)), &mesh->meshVertices[0].x);
                
				glDrawElements(GL_TRIANGLES, GLsizei(mesh->indicesCount), GL_UNSIGNED_SHORT, &mesh->indices[0]);
                
				glDisableClientState(GL_VERTEX_ARRAY);
				glDisableClientState(GL_TEXTURE_COORD_ARRAY);
                
				glDisable(GL_TEXTURE_2D);
                
				/*glEnableClientState(GL_VERTEX_ARRAY);
                 glVertexPointer(3, GL_FLOAT, GLsizei(sizeof(TexturesPSPVertex)), &mesh->meshVertices[0].x);
                 
                 if(mesh->mMaterial != -1)
                 {
                 //texture
                 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
                 //glActiveTexture(GL_TEXTURE0);
                 //glClientActiveTexture(GL_TEXTURE0);
                 
                 bindTexture(model->mMaterials[mesh->mMaterial]->texturID);
                 glEnable(GL_TEXTURE_2D);			
                 
                 glTexCoordPointer(2, GL_FLOAT, GLsizei(sizeof(TexturesPSPVertex)), &mesh->meshVertices[0].u);
                 }
                 
                 
                 if (mesh->mMaterial != -1 && model->mMaterials[mesh->mMaterial]->lightmapping)
                 {
                 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
                 glActiveTexture(GL_TEXTURE1);
                 glClientActiveTexture(GL_TEXTURE1);
                 
                 glEnable(GL_TEXTURE_2D);
                 glBindTexture(GL_TEXTURE_2D, model->mMaterials[mesh->mMaterial]->lightMapID);
                 glTexCoordPointer(2, GL_FLOAT, GLsizei(sizeof(TexturesPSPVertex)), &mesh->meshVertices[0].u);
                 
                 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
                 }
                 
                 //glDrawElements(GL_TRIANGLE_STRIP, GLsizei(mesh->indicesCount), GL_UNSIGNED_INT, &mesh->indices[0]);
                 glDrawElements(GL_TRIANGLES, GLsizei(mesh->indicesCount), GL_UNSIGNED_INT, &mesh->indices[0]);
                 
                 glDisable(GL_TEXTURE_2D);
                 glDisableClientState(GL_VERTEX_ARRAY);
                 glDisableClientState(GL_TEXTURE_COORD_ARRAY);*/
			}
            
			glPopMatrix();
		}
コード例 #13
0
		void OpenGLES1RenderManager::drawText(TrueTypeFont* font,float x, float y, const char *text, int align, unsigned int col)
		{
            if (!font->g_ftex) return;
			if (!text) return;
            
			y = _height - y;
            
			if (align == Graphics::ALIGN_CENTER)
				x -= font->getTextLength(font->g_cdata, text)/2;
			else if (align == Graphics::ALIGN_RIGHT)
				x -= font->getTextLength(font->g_cdata, text);
            
			glColor4ub(col&0xff, (col>>8)&0xff, (col>>16)&0xff, (col>>24)&0xff);
			glEnable(GL_BLEND);
			glEnable(GL_TEXTURE_2D);
            
			// assume orthographic projection with units = screen pixels, origin at top left
			glBindTexture(GL_TEXTURE_2D, font->g_ftex);
			_currentTexture = font->g_ftex;
			const float ox = x;
            
			TexturedVertex *vertices = new TexturedVertex[strlen(text)*6];
			int ver = 0;
            
			while (*text)
			{
				int c = (unsigned char)*text;
				if (c == '\t')
				{
					for (int i = 0; i < 4; ++i)
					{
						if (x < g_tabStops2[i]+ox)
						{
							x = g_tabStops2[i]+ox;
							break;
						}
					}
				}
				else if (c >= 32 && c < 128)
				{                       
					stbtt_aligned_quad2 q;
					font->getBakedQuad(font->g_cdata, 256,256, c-32, &x,&y,&q);
                    
					vertices[ver].u = q.s0;vertices[ver].v = q.t0;vertices[ver].x = q.x0;vertices[ver].y = q.y0;vertices[ver].z = 0.0f;ver++;
					vertices[ver].u = q.s1;vertices[ver].v = q.t1;vertices[ver].x = q.x1;vertices[ver].y = q.y1;vertices[ver].z = 0.0f;ver++;
					vertices[ver].u = q.s1;vertices[ver].v = q.t0;vertices[ver].x = q.x1;vertices[ver].y = q.y0;vertices[ver].z = 0.0f;ver++;
                    
					vertices[ver].u = q.s0;vertices[ver].v = q.t0;vertices[ver].x = q.x0;vertices[ver].y = q.y0;vertices[ver].z = 0.0f;ver++;
					vertices[ver].u = q.s0;vertices[ver].v = q.t1;vertices[ver].x = q.x0;vertices[ver].y = q.y1;vertices[ver].z = 0.0f;ver++;
					vertices[ver].u = q.s1;vertices[ver].v = q.t1;vertices[ver].x = q.x1;vertices[ver].y = q.y1;vertices[ver].z = 0.0f;ver++;
				}
				++text;
			}
            
			glEnableClientState(GL_VERTEX_ARRAY);
			glEnableClientState(GL_TEXTURE_COORD_ARRAY);
            
			glVertexPointer(3, GL_FLOAT, GLsizei(sizeof(TexturedVertex)), &vertices[0].x);
			glTexCoordPointer(2, GL_FLOAT, GLsizei(sizeof(TexturedVertex)), &vertices[0].u);
            
			glDrawArrays(GL_TRIANGLES,0,ver);
            
			glDisableClientState(GL_VERTEX_ARRAY);
			glDisableClientState(GL_TEXTURE_COORD_ARRAY);
            
			glDisable(GL_TEXTURE_2D);
			glDisable(GL_BLEND);
            
			delete [] vertices;
		}
コード例 #14
0
ファイル: tube.c プロジェクト: davehorner/XScreenSaverWin
static int
unit_tube (int faces, int smooth, int caps_p, int wire_p)
{
  int i;
  int polys = 0;
  GLfloat step = M_PI * 2 / faces;
  GLfloat s2 = step/2;
  GLfloat th;
  GLfloat x, y, x0=0, y0=0;
  int z = 0;

  int arraysize, out;
  struct { XYZ p; XYZ n; GLfloat s, t; } *array;

  arraysize = (faces+1) * 6;
  array = (void *) calloc (arraysize, sizeof(*array));
  if (! array) abort();
  out = 0;


  /* #### texture coords are currently not being computed */


  /* side walls
   */
  th = 0;
  x = 1;
  y = 0;

  if (!smooth)
    {
      x0 = cos (s2);
      y0 = sin (s2);
    }

  if (smooth) faces++;

  for (i = 0; i < faces; i++)
    {
      array[out].p.x = x;			/* bottom point A */
      array[out].p.y = 0;
      array[out].p.z = y;

      if (smooth)
        array[out].n = array[out].p;		/* its own normal */
      else
        {
          array[out].n.x = x0;			/* mid-plane normal */
          array[out].n.y = 0;
          array[out].n.z = y0;
        }
      out++;


      array[out].p.x = x;			/* top point A */
      array[out].p.y = 1;
      array[out].p.z = y;
      array[out].n = array[out-1].n;		/* same normal */
      out++;


      th += step;
      x  = cos (th);
      y  = sin (th);

      if (!smooth)
        {
          x0 = cos (th + s2);
          y0 = sin (th + s2);

          array[out].p.x = x;			/* top point B */
          array[out].p.y = 1;
          array[out].p.z = y;
          array[out].n = array[out-1].n;	/* same normal */
          out++;


          array[out] = array[out-3];		/* bottom point A */
          out++;

          array[out] = array[out-2];		/* top point B */
          out++;

          array[out].p.x = x;			/* bottom point B */
          array[out].p.y = 0;
          array[out].p.z = y;
          array[out].n = array[out-1].n;	/* same normal */
          out++;

          polys++;
        }

      polys++;
      if (out >= arraysize) abort();
    }

  glEnableClientState (GL_VERTEX_ARRAY);
  glEnableClientState (GL_NORMAL_ARRAY);
  glEnableClientState (GL_TEXTURE_COORD_ARRAY);

  glVertexPointer   (3, GL_FLOAT, sizeof(*array), &array[0].p);
  glNormalPointer   (   GL_FLOAT, sizeof(*array), &array[0].n);
  glTexCoordPointer (2, GL_FLOAT, sizeof(*array), &array[0].s);

  glFrontFace(GL_CCW);
  glDrawArrays ((wire_p ? GL_LINES :
                 (smooth ? GL_TRIANGLE_STRIP : GL_TRIANGLES)),
                0, out);


  /* End caps
   */
  if (caps_p)
    for (z = 0; z <= 1; z++)
      {
        out = 0;
        if (! wire_p)
          {
            array[out].p.x = 0;
            array[out].p.y = z;
            array[out].p.z = 0;

            array[out].n.x = 0;
            array[out].n.y = (z == 0 ? -1 : 1);
            array[out].n.z = 0;
            out++;
          }

        th = 0;
        for (i = (z == 0 ? 0 : faces);
             (z == 0 ? i <= faces : i >= 0);
             i += (z == 0 ? 1 : -1)) {
            GLfloat x = cos (th);
            GLfloat y = sin (th);

            array[out] = array[0];  /* same normal and texture */
            array[out].p.x = x;
            array[out].p.y = z;
            array[out].p.z = y;
            out++;

            th += (z == 0 ? step : -step);

            polys++;
            if (out >= arraysize) abort();
          }

        glVertexPointer   (3, GL_FLOAT, sizeof(*array), &array[0].p);
        glNormalPointer   (   GL_FLOAT, sizeof(*array), &array[0].n);
        glTexCoordPointer (2, GL_FLOAT, sizeof(*array), &array[0].s);

        glFrontFace(GL_CCW);
        glDrawArrays ((wire_p ? GL_LINE_LOOP : GL_TRIANGLE_FAN), 0, out);
      }

  free(array);

  return polys;
}
コード例 #15
0
ファイル: mesh_renderer.cpp プロジェクト: Sergejus/nestk
void MeshRenderer :: renderToImage(cv::Mat4b& image, int flags)
{
    ntk_assert(m_vertex_buffer_object.initialized,
               "Renderer not initialized! Call setPose and setMesh.");

    ntk::TimeCount tc_gl_current("make_current", 2);
    m_pbuffer->makeCurrent();
    tc_gl_current.stop();

    ntk::TimeCount tc_gl_render("gl_render", 2);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if (flags & WIREFRAME)
        glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

    VertexBufferObject& vbo = m_vertex_buffer_object;
    glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbo.vertex_id);

    if (vbo.has_texcoords)
    {
        glEnable(GL_TEXTURE_2D);
        glBindTexture(GL_TEXTURE_2D, vbo.texture_id);
    }
    else
    {
        glDisable(GL_TEXTURE_2D);
    }

    if (vbo.has_texcoords)
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    if (vbo.has_color)
        glEnableClientState(GL_COLOR_ARRAY);
    else
        glColor3f(1.0f,0.f,0.f);

    glEnableClientState(GL_VERTEX_ARRAY);

    glVertexPointer(3, GL_FLOAT, 0, 0);
    if (vbo.has_color)
        glColorPointer(3, GL_UNSIGNED_BYTE, 0, ((char*) NULL) + vbo.color_offset);

    if (vbo.has_texcoords)
        glTexCoordPointer(2, GL_FLOAT, 0, ((char*) NULL) + vbo.texture_offset);

    if (vbo.has_faces)
    {
        glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, vbo.faces_id);
        glNormal3f(0, 0, 1);
        glDrawElements(GL_TRIANGLES, vbo.nb_faces*3, GL_UNSIGNED_INT, 0);
    }
    else
    {
        glDrawArrays(GL_POINTS,
                     0,
                     vbo.nb_vertices);
    }

    glDisableClientState(GL_VERTEX_ARRAY);

    if (vbo.has_color)
        glDisableClientState(GL_COLOR_ARRAY);

    if (vbo.has_texcoords)
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);

    // bind with 0, so, switch back to normal pointer operation
    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

    if (vbo.has_faces)
    {
        glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
    }

    glFinish();
    tc_gl_render.stop();

    ntk::TimeCount tc_image("to_image", 2);
    QImage qimage = m_pbuffer->toImage();
    tc_image.stop();

    ntk::TimeCount tc_depth_buffer("compute_depth_buffer", 2);
    computeDepthBuffer();
    tc_depth_buffer.stop();

    ntk::TimeCount tc_convert("convert_to_cv", 2);
    for (int r = 0; r < qimage.height(); ++r)
        for (int c = 0; c < qimage.width(); ++c)
        {
            QRgb pixel = qimage.pixel(c,r);
            Vec4b color (qBlue(pixel), qGreen(pixel), qRed(pixel), qAlpha(pixel));
            m_color_buffer(r,c) = color;
            float a = qAlpha(pixel)/255.f;
            if (a > 0)
            {
                Vec4b old_color = image(r,c);
                image(r,c) = Vec4b(old_color[0]*(1-a) + color[0]*a,
                                   old_color[1]*(1-a) + color[1]*a,
                                   old_color[2]*(1-a) + color[2]*a,
                                   255);
            }
        }
    tc_convert.stop();
}
コード例 #16
0
ファイル: droid_vout.c プロジェクト: golgol7777/gpac
void drawGLScene(AndroidContext *rc)
{
#ifdef DROID_EXTREME_LOGS
        LOG( ANDROID_LOG_VERBOSE, TAG, "drawGLScene : start");
#endif /* DROID_EXTREME_LOGS */
	GLfloat vertices[4][3];
	GLfloat texcoord[4][2];
//	int i, j;

	float rgba[4];

#ifdef GLES_FRAMEBUFFER_TEST
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
#endif

	// Reset states
	rgba[0] = rgba[1] = rgba[2] = 0.f;
	rgba[0] = 1.f;
	glColor4f(1.f, 1.f, 1.f, 1.f);
	glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, rgba);
	glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, rgba);
	glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, rgba);
	glDisable(GL_CULL_FACE | GL_NORMALIZE | GL_LIGHTING | GL_BLEND | GL_FOG | GL_COLOR_MATERIAL | GL_TEXTURE_2D);

    /* Clear The Screen And The Depth Buffer */
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //glEnable(GL_BLEND);
    //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glEnable(GL_TEXTURE_2D);
    glBindTexture( GL_TEXTURE_2D, rc->texID);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

//    for ( i = 0; i < rc->height/2; i++ )
//    	for ( j = 0; j < rc->width; j++ )
//    		rc->texData[ i*rc->width*NBPP + j*NBPP + 3] = 200;

//    memset(rc->texData, 255, 4 * rc->width * rc->height );
#ifndef GLES_FRAMEBUFFER_TEST
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, rc->tex_width, rc->tex_height, 0,
		GL_RGBA, GL_UNSIGNED_BYTE, rc->texData );
#endif

	if ( rc->draw_texture )
	{
		int cropRect[4] = {0,rc->height,rc->width,-rc->height};
		glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, cropRect);

		glDrawTexsOES(0, 0, 0, rc->width, rc->height);
	}
	else
	{
		/* Enable VERTEX array */
		glEnableClientState(GL_VERTEX_ARRAY);
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);

		/* Setup pointer to  VERTEX array */
		glVertexPointer(3, GL_FLOAT, 0, vertices);
		glTexCoordPointer(2, GL_FLOAT, 0, texcoord);

		/* Move Left 1.5 Units And Into The Screen 6.0 */
		glLoadIdentity();
		//glTranslatef(0.0f, 0.0f, -3.3f);
		//glTranslatef(0.0f, 0.0f, -2.3f);

		/* Top Right Of The Quad    */
		vertices[0][0]=rc->tex_width;  vertices[0][1]=rc->tex_height;  vertices[0][2]=0.0f;
		texcoord[0][0]=1.f;   texcoord[0][1]=0.f;
		/* Top Left Of The Quad     */
		vertices[1][0]=0.f; vertices[1][1]=rc->tex_height;  vertices[1][2]=0.0f;
		texcoord[1][0]=0.f;   texcoord[1][1]=0.f;
		/* Bottom Left Of The Quad  */
		vertices[2][0]=rc->tex_width;  vertices[2][1]=0.f; vertices[2][2]=0.0f;
		texcoord[2][0]=1.f;   texcoord[2][1]=1.f;
		/* Bottom Right Of The Quad */
		vertices[3][0]=0.f; vertices[3][1]=0.f; vertices[3][2]=0.0f;
		texcoord[3][0]=0.f;   texcoord[3][1]=1.f;

		/* Drawing using triangle strips, draw triangles using 4 vertices */
		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

		/* Disable vertex array */
		glDisableClientState(GL_VERTEX_ARRAY);
		glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	}

    glDisable(GL_TEXTURE_2D);

    /* Flush all drawings */
    glFinish();
#ifdef GLES_FRAMEBUFFER_TEST
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, rc->framebuff);
#endif
#ifdef DROID_EXTREME_LOGS
    LOG( ANDROID_LOG_VERBOSE, TAG, "drawGLScene : end");
#endif /* DROID_EXTREME_LOGS */
}
コード例 #17
0
ファイル: fireworks.c プロジェクト: OoNEKERAFAoO/SDL_PSL1GHT
int
main(int argc, char *argv[])
{
    SDL_Window *window;         /* main window */
    Uint32 startFrame;          /* time frame began to process */
    Uint32 endFrame;            /* time frame ended processing */
    Uint32 delay;               /* time to pause waiting to draw next frame */
    int done;                   /* should we clean up and exit? */

    /* initialize SDL */
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        fatalError("Could not initialize SDL");
    }
    /* seed the random number generator */
    srand(time(NULL));
    /*      
       request some OpenGL parameters
       that may speed drawing
     */
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
    SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 0);
    SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);

    /* create main window and renderer */
    window = SDL_CreateWindow(NULL, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT,
                                SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |
                                SDL_WINDOW_BORDERLESS);
    SDL_CreateRenderer(window, 0, 0);

    /* load the particle texture */
    initializeTexture();

    /*      check if GL_POINT_SIZE_ARRAY_OES is supported
       this is used to give each particle its own size
     */
    pointSizeExtensionSupported =
        SDL_GL_ExtensionSupported("GL_OES_point_size_array");

    /* set up some OpenGL state */
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);

    glEnable(GL_POINT_SPRITE_OES);
    glTexEnvi(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, 1);

    if (pointSizeExtensionSupported) {
        /* we use this to set the sizes of all the particles */
        glEnableClientState(GL_POINT_SIZE_ARRAY_OES);
    } else {
        /* if extension not available then all particles have size 10 */
        glPointSize(10);
    }

    done = 0;
    /* enter main loop */
    while (!done) {
        startFrame = SDL_GetTicks();
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                done = 1;
            }
            if (event.type == SDL_MOUSEBUTTONDOWN) {
                int x, y;
                SDL_GetMouseState(&x, &y);
                spawnEmitterParticle(x, y);
            }
        }
        stepParticles();
        drawParticles();
        endFrame = SDL_GetTicks();

        /* figure out how much time we have left, and then sleep */
        delay = MILLESECONDS_PER_FRAME - (endFrame - startFrame);
        if (delay > MILLESECONDS_PER_FRAME) {
            delay = MILLESECONDS_PER_FRAME;
        }
        if (delay > 0) {
            SDL_Delay(delay);
        }
    }

    /* delete textures */
    glDeleteTextures(1, &particleTextureID);
    /* shutdown SDL */
    SDL_Quit();

    return 0;
}
コード例 #18
0
bool ShellRenderInterfaceOpenGL::AttachToNative(void *nativeWindow)
{
	this->render_context = NULL;
	this->window_handle = (HWND)nativeWindow;
	this->device_context = GetDC(this->window_handle);
	if (this->device_context == NULL)
	{
		Shell::DisplayError("Could not get device context.");
		return false;
	}

	PIXELFORMATDESCRIPTOR pixel_format_descriptor;
	memset(&pixel_format_descriptor, 0, sizeof(pixel_format_descriptor));
	pixel_format_descriptor.nSize = sizeof(PIXELFORMATDESCRIPTOR);
	pixel_format_descriptor.nVersion = 1;
	pixel_format_descriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
	pixel_format_descriptor.iPixelType = PFD_TYPE_RGBA;
	pixel_format_descriptor.cColorBits = 32;
	pixel_format_descriptor.cRedBits = 8;
	pixel_format_descriptor.cGreenBits = 8;
	pixel_format_descriptor.cBlueBits = 8;
	pixel_format_descriptor.cAlphaBits = 8;
	pixel_format_descriptor.cDepthBits = 24;
	pixel_format_descriptor.cStencilBits = 8;

	int pixel_format = ChoosePixelFormat(this->device_context, &pixel_format_descriptor);
	if (pixel_format == 0)
	{
		Shell::DisplayError("Could not choose 32-bit pixel format.");
		return false;
	}

	if (SetPixelFormat(this->device_context, pixel_format, &pixel_format_descriptor) == FALSE)
	{
		Shell::DisplayError("Could not set pixel format.");
		return false;
	}

	this->render_context = wglCreateContext(this->device_context);
	if (this->render_context == NULL)
	{ 
		Shell::DisplayError("Could not create OpenGL rendering context.");
		return false;
	}

	// Activate the rendering context.
	if (wglMakeCurrent(this->device_context, this->render_context) == FALSE)
	{
		Shell::DisplayError("Unable to make rendering context current.");
		return false;
	}

	// Set up the GL state.
	glClearColor(0, 0, 0, 1);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_COLOR_ARRAY);

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

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

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	return true;
}
コード例 #19
0
void GLBackend::do_glEnableClientState(Batch& batch, uint32 paramOffset) {
    glEnableClientState(batch._params[paramOffset]._uint);
    (void) CHECK_GL_ERROR();
}
コード例 #20
0
ファイル: ofVbo.cpp プロジェクト: imohame/openFrameworks
//--------------------------------------------------------------
void ofVbo::bind() const{
	bool programmable = ofIsGLProgrammableRenderer();
	if(programmable && (vaoSupported || !vaoChecked)){
		if(vaoID==0){
			#ifdef TARGET_OPENGLES
			if(glGenVertexArrays==0 && !vaoChecked){
				glGenVertexArrays = (glGenVertexArraysType)dlsym(RTLD_DEFAULT, "glGenVertexArrays");
				glDeleteVertexArrays = (glDeleteVertexArraysType)dlsym(RTLD_DEFAULT, "glDeleteVertexArrays");
				glBindVertexArray = (glBindVertexArrayType)dlsym(RTLD_DEFAULT, "glBindVertexArray");
				vaoChecked = true;
				vaoSupported = glGenVertexArrays;
			}
			#else
			vaoChecked = true;
			vaoSupported = true;
			#endif
			if(vaoSupported) glGenVertexArrays(1, &const_cast<ofVbo*>(this)->vaoID);
			if(vaoID!=0){
				retainVAO(vaoID);
				vaoChanged = true;
			}
		}
		if(vaoSupported) glBindVertexArray(vaoID);
	}else{
		vaoSupported = false;
	}

	if(vaoChanged || !vaoSupported){
		if(bUsingVerts){
			if(!programmable){
				positionAttribute.bind();
				#ifndef TARGET_PROGRAMMABLE_GL
				glEnableClientState(GL_VERTEX_ARRAY);
				glVertexPointer(positionAttribute.numCoords, GL_FLOAT,
								positionAttribute.stride,
								(void*)positionAttribute.offset);
				#endif
			}else{
				positionAttribute.enable();
			}
		}else if(programmable){
			positionAttribute.disable();
		}

		if(bUsingColors) {
			if(!programmable){
				colorAttribute.bind();
				#ifndef TARGET_PROGRAMMABLE_GL
				glEnableClientState(GL_COLOR_ARRAY);
				glColorPointer(colorAttribute.numCoords, GL_FLOAT,
						colorAttribute.stride,
							   (void*)colorAttribute.offset);
				#endif
			}else{
				colorAttribute.enable();
			}
		}else if(programmable){
			colorAttribute.disable();
		}

		if(bUsingNormals) {
			if(!programmable){
				normalAttribute.bind();
				#ifndef TARGET_PROGRAMMABLE_GL
				glEnableClientState(GL_NORMAL_ARRAY);
				glNormalPointer(GL_FLOAT, normalAttribute.stride,
								(void*)normalAttribute.offset);
				#endif
			}else{
				normalAttribute.enable();
			}
		}else if(programmable){
			normalAttribute.disable();
		}

		if(bUsingTexCoords) {
			if(!programmable){
				texCoordAttribute.bind();
				#ifndef TARGET_PROGRAMMABLE_GL
				glEnableClientState(GL_TEXTURE_COORD_ARRAY);
				glTexCoordPointer(texCoordAttribute.numCoords,
								  GL_FLOAT, texCoordAttribute.stride,
								  (void*)texCoordAttribute.offset);
				#endif
			}else{
				texCoordAttribute.enable();
			}
		}else if(programmable){
			texCoordAttribute.disable();
		}
        
        if (bUsingIndices) {
            indexAttribute.bind();
        }

		map<int,VertexAttribute>::const_iterator it;
		for(it = customAttributes.begin();it!=customAttributes.end();it++){
			it->second.enable();
		}

		vaoChanged=false;
	}
}
コード例 #21
0
ファイル: Render.cpp プロジェクト: andrepura/Multitouch
/**
 * main render function
 */
void render() {
	counter++;
	if(counter >= 36000){
		counter = 0;
	}
	//Typical render pass
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// update dimensions
	enable_2d();

	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);

	glPushMatrix();

		// if in portrait mode
		if (oriention_side_up > 0)
		{
			glVertexPointer(2, GL_FLOAT, 0, verticesH);
			glTexCoordPointer(2, GL_FLOAT, 0, tex_coordH);
		}
		// if in landscape mode
		else
		{
			glVertexPointer(2, GL_FLOAT, 0, vertices);
			glTexCoordPointer(2, GL_FLOAT, 0, tex_coord);
		}

		//portrait or landscape?
		glBindTexture(GL_TEXTURE_2D, oriention_side_up>0?backgroundH:background);
		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

	glPopMatrix();

	pp = points.begin();

	while (pp != points.end()) {

		if (pp->visible) {
			// draw touchpoint
			glPushMatrix();
				glTranslatef(pp->getX(), (oriention_side_up>0?1024:600) - pp->getY(), 0);
				glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				glVertexPointer(2, GL_FLOAT, 0, verticesTouchpoint);
				glTexCoordPointer(2, GL_FLOAT, 0, tex_coord_touchpoint);
				glBindTexture(GL_TEXTURE_2D, touchpoint);
				glPushMatrix();
					glRotatef((float) ((float)(pp->startRotation) + (float) counter / 0.25f), 0, 0, 1);
					glPushMatrix();
						glTranslatef(-60, -60, 0);
						glColor4f(pp->r,pp->g,pp->b,1);
						glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
					glPopMatrix();
				glPopMatrix();
			glPopMatrix();

			// draw touchpoint number
			glPushMatrix();
				glColor4f(0.3f,0.3f,0.3f,1.0f);
				char buffer [33];
				itoa (pp->id+1,buffer,10);
				glTranslatef(pp->getX()+50,(oriention_side_up>0?1024:600)-pp->getY()+50,0);
				glPushMatrix();
					bbutil_render_text(font,buffer,0,0);
				glPopMatrix();
			glPopMatrix();

		}
		pp++;
	}

	glColor4f(1.0f,1.0f,1.0f,1.0f);

	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	glDisableClientState(GL_VERTEX_ARRAY);

	//Use utility code to update the screen
	bbutil_swap();
}
コード例 #22
0
static void renderFrame()
{
	glClearColor(0 / 255.0f, 0x2b / 255.0f, 0x36 / 255.0f, 1.0f);
	glClearDepth(1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// ---- UI

	imguiBeginFrame(mouseX, height - 1 - mouseY, mouseButtons, 0);

	static const int paramSize = 120;
	static int paramScroll = 0;
	imguiBeginScrollArea("Params", 0, height - paramSize, width, paramSize, &paramScroll);

	static float depth = 8.0f;
	imguiSlider("Depth", &depth, 0.0f, 12.0f, 1.0f);

	static float draw_ratio = 1.0f;
	imguiSlider("Draw ratio", &draw_ratio, 0.0f, 1.0f, 0.001f);

	static bool showWire = false;
	showWire ^= imguiCheck("Wireframe", showWire);

	static bool showPoints = false;
	showPoints ^= imguiCheck("Points", showPoints);

	static bool showPath = true;
	showPath ^= imguiCheck("Path", showPath);

	static bool showPathPoints = true;
	showPathPoints ^= imguiCheck("Path points", showPathPoints);

	imguiEndScrollArea();
	imguiEndFrame();

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

	glEnable(GL_LINE_SMOOTH);
	glLineWidth(1.2f);

	// prepare to render octahedron
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(60.0f, 1.333f, 0.01f, 10.0f);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(0.5f, 0.5f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);

	// model rot
	unsigned int loop_len = 30 * 1000;
	float phase = 1.0f * (timeGetTime() % loop_len) / loop_len;
	glRotatef(phase * 360.0f, 0.0f, 1.0f, 0.0f);

	// gen mesh
	Mesh octa;
	genSubdOctahedron(octa, (int) depth);
	spherize(octa.verts);

	// draw mesh as wireframe
	glEnable(GL_CULL_FACE);

	if (showWire) {
		glColor4ub(0xfd, 0xf6, 0xe3, 255);
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		octa.draw();
	}

	// draw vertices
	if (showPoints) {
		glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);

		glEnable(GL_POINT_SMOOTH);
		glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);

		for (int pass=0; pass < 2; ++pass) {
			if (!pass) {
				glColor3ub(0x00, 0x2b, 0x36);
				glPointSize(4.0f);
			} else {
				glColor3ub(0xcb, 0x4b, 0x16);
				glPointSize(2.0f);
			}
			octa.draw();
		}
		glColor4ub(255, 0, 0, 255);
		glPointSize(2.0f);
		octa.draw();
		glDisable(GL_POINT_SMOOTH);
	}

	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	// draw path
	if (showPath || showPathPoints) {
		std::vector<Vec3f> verts;
		sphereTraverseOcta(verts, (int) depth);

		//triTraverse(verts, Vec3f(1.0f, -1.0f, 0.0f), Vec3f(-1.0f, 1.0f, 0.0f), Vec3f(-1.0f, -1.0f, 0.0f), (int) depth, false);
		//triTraverse(verts, Vec3f(-1.0f, 1.0f, 0.0f), Vec3f(1.0f, -1.0f, 0.0f), Vec3f( 1.0f,  1.0f, 0.0f), (int) depth, false);

		glEnable(GL_POINT_SMOOTH);
		glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);

		static const float bgcol[4] = { 0.0f, 0x2b / 255.0f, 0x36 / 255.0f, 1.0f };

		glEnableClientState(GL_VERTEX_ARRAY);
		glVertexPointer(3, GL_FLOAT, 0, &verts[0]);

		glEnable(GL_FOG);
		glFogi(GL_FOG_MODE, GL_EXP2);
		glFogfv(GL_FOG_COLOR, bgcol);
		glFogf(GL_FOG_DENSITY, 0.4f);

		if (showPath) {
			glLineWidth(1.8f);
			glColor3ub(255, 127, 0);
			glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) (draw_ratio * verts.size()));
		}

		if (showPathPoints) {
			glPointSize(4.0f);
			glColor3ub(255, 0, 0);
			glDrawArrays(GL_POINTS, 0, (GLsizei) (draw_ratio * verts.size()));
		}

		glDisableClientState(GL_VERTEX_ARRAY);
		glDisable(GL_FOG);
		glDisable(GL_POINT_SMOOTH);
	}

	// back to GUI
	glDisable(GL_DEPTH_TEST);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, width, 0, height, -1.0f, 1.0f);

	imguiRenderGLDraw();

	glDisable(GL_BLEND);

	SwapBuffers(hDC);
}
コード例 #23
0
ファイル: bindlessindirect.cpp プロジェクト: jdm3/apitest
// --------------------------------------------------------------------------------------------------------------------
void UntexturedObjectsGLBindlessIndirect::Render(const std::vector<Matrix>& _transforms)
{
    const auto xformCount = _transforms.size();
    const auto objCount = m_commands.size();
    assert(xformCount == objCount);

    // Program
    Vec3 dir = { -0.5f, -1, 1 };
    Vec3 at = { 0, 0, 0 };
    Vec3 up = { 0, 0, 1 };
    dir = normalize(dir);
    Vec3 eye = at - 250 * dir;
    Matrix view = matrix_look_at(eye, at, up);
    Matrix view_proj = mProj * view;

    glUseProgram(m_prog);
    glUniformMatrix4fv(0, 1, GL_TRUE, &view_proj.x.x);

    // Input Layout
    glEnableClientState(GL_ELEMENT_ARRAY_UNIFIED_NV);
    glEnableClientState(GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glVertexAttribFormatNV(0, 3, GL_FLOAT, GL_FALSE, sizeof(UntexturedObjectsProblem::Vertex));
    glVertexAttribFormatNV(1, 3, GL_FLOAT, GL_FALSE, sizeof(UntexturedObjectsProblem::Vertex));

    // Rasterizer State
    glEnable(GL_CULL_FACE);
    glCullFace(GL_FRONT);
    glDisable(GL_SCISSOR_TEST);

    // Blend State
    glDisable(GL_BLEND);
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

    // Depth Stencil State
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);

    size_t i = 0;
    for (auto it = m_commands.begin(); it != m_commands.end(); ++it) {
        Command *cmd = &*it;

        cmd->Draw.count = mIndexCount;
        cmd->Draw.instanceCount = 1;
        cmd->Draw.firstIndex = 0;
        cmd->Draw.baseVertex = 0;
        cmd->Draw.baseInstance = 0;
        cmd->reserved = 0;
        cmd->indexBuffer.index = 0;
        cmd->indexBuffer.reserved = 0;
        cmd->indexBuffer.address = m_ib_addrs[i];
        cmd->indexBuffer.length = m_ib_sizes[i];
        cmd->vertexBuffers[0].index = 0;
        cmd->vertexBuffers[0].reserved = 0;
        cmd->vertexBuffers[0].address = m_vbo_addrs[i] + offsetof(UntexturedObjectsProblem::Vertex, pos);
        cmd->vertexBuffers[0].length = m_vbo_sizes[i] - offsetof(UntexturedObjectsProblem::Vertex, pos);
        cmd->vertexBuffers[1].index = 1;
        cmd->vertexBuffers[1].reserved = 0;
        cmd->vertexBuffers[1].address = m_vbo_addrs[i] + offsetof(UntexturedObjectsProblem::Vertex, color);
        cmd->vertexBuffers[1].length = m_vbo_sizes[i] - offsetof(UntexturedObjectsProblem::Vertex, color);

        ++i;
    }

    memcpy(m_transform_ptr, &*_transforms.begin(), sizeof(Matrix) * xformCount);

    memcpy(m_cmd_ptr, &*m_commands.begin(), sizeof(Command) * objCount);

    glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);

    // resolveQueries();

    // glBeginQuery(GL_TIME_ELAPSED, m_queries[m_currentQueryIssue]);
    glMultiDrawElementsIndirectBindlessNV(GL_TRIANGLES, GL_UNSIGNED_SHORT, nullptr, objCount, 0, 2);
    // glEndQuery(GL_TIME_ELAPSED);

    // m_currentQueryIssue = (m_currentQueryIssue + 1) % kQueryCount;
}
コード例 #24
0
JNIEXPORT void JNICALL
Java_name_nailgun_irrlichtvuforia_Renderer_renderFrame(JNIEnv *, jobject)
{
    QCAR::State state = QCAR::Renderer::getInstance().begin();
    QCAR::Renderer::getInstance().drawVideoBackground();
       
#ifndef DONT_SAVE_STATE
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glEnable(GL_TEXTURE_2D);
    glDisable(GL_LIGHTING);

    glEnable(GL_DEPTH_TEST);
    //glEnable(GL_CULL_FACE);
#endif

    // Did we find any trackables this frame?
    for(int tIdx = 0; tIdx < state.getNumActiveTrackables(); tIdx++)
    {
        // Get the trackable:
        const QCAR::Trackable* trackable = state.getActiveTrackable(tIdx);
        QCAR::Matrix44F modelViewMatrix =
            QCAR::Tool::convertPose2GLMatrix(trackable->getPose());        

        // Choose the texture based on the target name:
        int textureIndex;
        if (strcmp(trackable->getName(), "chips") == 0)
        {
            textureIndex = 0;
        }
        else if (strcmp(trackable->getName(), "stones") == 0)
        {
            textureIndex = 1;
        }
        else
        {
            textureIndex = 2;
        }

        if (!mDevice->run()) {
            // TODO: error
        }

        irr::core::matrix4& cameraMatrix = mTransformationNode->getRelativeTransformationMatrix();
        cameraMatrix.setM(modelViewMatrix.data);

        mDriver->beginScene(false, true);
        mSceneManager->drawAll();
        mDriver->endScene();
    }

#ifndef DONT_SAVE_STATE        
    glDisable(GL_DEPTH_TEST);

    glDisable(GL_TEXTURE_2D);
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
#endif

    QCAR::Renderer::getInstance().end();
}
コード例 #25
0
ファイル: ModelManager.c プロジェクト: devmario/IbizaEngine
bool ModelManagerDisplay(ModelManager* manager, Model* model, bool line) {
#else
bool ModelManagerDisplay(ModelManager* manager, Model* model) {
#endif
    if(model->isVisible)
	{
        
	if(model->ani) {
		if(model->ani->aniIsPlay) {
			if(model->ani->aniCurFrame < model->ani->aniTotalFrame - 1) {
				model->ani->aniCurFrame++;
				model->ani->aniIsUpdateFrame = true;
			} else {
				if(model->ani->aniIsLoop) {
					model->ani->aniCurFrame = 0;
					model->ani->aniIsUpdateFrame = true;
				}
			}
		}
		
		if(model->ani->aniIsUpdateFrame) {
			//모든 에니메이션 모델 삭제
			int i;
			for(i = 0; i < model->child->length; i++) {
				Model* child = ArrayObjectAtIndex(model->child, i);
				if(child->ani) {
					if(child->ani->instanceID) {
						ModelRemoveAt(model, i);
						i--;
					}
				}
			}
			
			//현제 프레임의 하위모델 셋팅후 매트릭스,칼라 셋팅
			if(model->ani->aniChildLength) {
				for(i = 0; i < model->ani->aniChildLength[model->ani->aniCurFrame]; i++) {
					ModelAddAt(model, model->ani->aniChild[model->ani->aniCurFrame][i], 0);
					ModelSetMatrix(model->ani->aniChild[model->ani->aniCurFrame][i], model->ani->aniMat[model->ani->aniCurFrame][i]);
					ModelSetColor(model->ani->aniChild[model->ani->aniCurFrame][i], model->ani->aniColor[model->ani->aniCurFrame][i]);
				}
			}
			
			model->ani->aniIsUpdateFrame = false;
		}
	}
	
	glPushMatrix();
	
	ModelUpdateMatrix(model);
	
	
	glMultMatrixf((float*)model->matrix);
	

	

	

		//glGetFloatv(GL_MODELVIEW_MATRIX, (float*)model->matrixGlobal);
		
		//model->globalPosition = Matrix3DMultiplyVector3D(*model->matrixGlobal, Vector3DInit(0.0, 0.0, 0.0));
		
		model->isRender = true;
		/*
		if(model->vertex) {
			Vector3D scale = Matrix3DGetScale(*model->matrixGlobal);
			Vector3D vec = Vector3DInit(model->maxLengthVertex.x * scale.x,
										model->maxLengthVertex.y * scale.y,
										model->maxLengthVertex.z * scale.z);
			model->globalRadius = Vector3DLength(vec);
			for(int i = 0; i < 6; i++ ) {
				if( manager->g_frustumPlanes[i][0] * model->globalPosition.x +
				   manager->g_frustumPlanes[i][1] * model->globalPosition.y +
				   manager->g_frustumPlanes[i][2] * model->globalPosition.z +
				   manager->g_frustumPlanes[i][3] <= -model->globalRadius ) {
					model->isRender = false;
				}
			}
		}
		*/
		//if(model->isRender) {
			
#ifdef ___MACSIMULATOR___
			if(model->mask) {
				ModelManagerDisplay(manager, model->mask, line);
			}
#else
			if(model->mask) {
				ModelManagerDisplay(manager, model->mask);
			}
#endif
			
			//if(model->renderEvent.event) {
			//	model->renderEvent.event(model->renderEvent.userReference, model->renderEvent.argument);
			//}
			/*
			if(model->touchEvent.event) {
				tt++;
				for(int i = 0; i < manager->touchArguments->length; i++) {
					ModelEventTouchArgument* touchArgumentCurrent = manager->touchArguments->data[i];
					bool hit = ModelGetIsVertexHitLineDirection(model, 
																touchArgumentCurrent->origin, touchArgumentCurrent->direction, 
																model->touchVector, model->touchVectorGlobal);
					
					model->touchEvent.argument.hitVector = model->touchVector;
					model->touchEvent.argument.hitVectorGlobal = model->touchVectorGlobal;
					model->touchEvent.argument.isHit = hit;
					model->touchEvent.argument.model = model;
					model->touchEvent.argument.touchID = touchArgumentCurrent->touchID;
					model->touchEvent.argument.touchTabCount = touchArgumentCurrent->touchTabCount;
					model->touchEvent.argument.touchType = touchArgumentCurrent->touchType;
					model->touchEvent.event(model->touchEvent.userReference, model->touchEvent.argument);
					touchArgumentCurrent->isChecked = true;
				}
			}
             */
			
			Model* _parent = ModelGetParent(model);
			for(int i = 0; i < model->mixColorLength; i++) {
				if(_parent) {
					model->mixColor[i].r = (unsigned char)(((float)_parent->mixColor[0].r / (float)0xFF) * (float)model->color[i].r);
					model->mixColor[i].g = (unsigned char)(((float)_parent->mixColor[0].g / (float)0xFF) * (float)model->color[i].g);
					model->mixColor[i].b = (unsigned char)(((float)_parent->mixColor[0].b / (float)0xFF) * (float)model->color[i].b);
					model->mixColor[i].a = (unsigned char)(((float)_parent->mixColor[0].a / (float)0xFF) * (float)model->color[i].a);
				} else {
					model->mixColor[i] = model->color[0];
				}
			}
			
			if(model->vertex)
			{

				
				//if(manager->lastBindVertex != model->vertex) {
				glVertexPointer(3, GL_FLOAT, 0, model->vertex);
				//	manager->lastBindVertex = model->vertex;
				//}
				
				if(model->texcoord) {
					glEnable(GL_TEXTURE_2D);
					glEnableClientState(GL_TEXTURE_COORD_ARRAY);
					if(manager->lastBindTexcoord != model->texcoord) {
					glTexCoordPointer(2, GL_FLOAT, 0, model->texcoord);
					manager->lastBindTexcoord = model->texcoord;
					}
					if(manager->lastBindTexture != model->textureID) {
						glBindTexture(GL_TEXTURE_2D, model->textureID);
						manager->lastBindTexture = model->textureID;
					}
					if(model->blendMode == ModelBlendModeNormal) {
						//	glDepthFunc(GL_LESS);
						glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
						
						
					} else if(model->blendMode == ModelBlendModeAdd) {
						//	glDepthFunc(GL_LESS);
						glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
						//	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
					} else if(model->blendMode == ModelBlendModeNoAlpha) {
						//	glDepthFunc(GL_LESS);
						glBlendFunc(GL_ONE, GL_ZERO);
					} else if(model->blendMode == ModelBlendModeSubatract) {
						glBlendFunc(GL_SRC_ALPHA, GL_ONE);
					} else if(model->blendMode == ModelBlendModeDot) {
						glBlendFunc(GL_ZERO, GL_SRC_COLOR);
					} else if(model->blendMode == ModelBlendModePower) {
						glBlendFunc(GL_ZERO, GL_DST_COLOR);
					} else if(model->blendMode == ModelBlendModeInverse) {
						glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO);
					}
				} else {
					glDisable(GL_TEXTURE_2D);
					glDisableClientState(GL_TEXTURE_COORD_ARRAY);
				}
                
				/*
				if(model->isMask) {
					glColorMask(0, 0, 0, 0);
					//if(model->maskDepth == 0) {
					//glDisable(GL_DEPTH_TEST);
					glEnable(GL_STENCIL_TEST);
					glClear(GL_STENCIL_BUFFER_BIT);
					//}
					glStencilFunc(GL_ALWAYS, model->maskDepth, model->maskDepth);
					glStencilOp(GL_INCR, GL_INCR, GL_INCR);
				} else if(model->hasMask) {
					glColorMask(1, 1, 1, 1);
					glStencilFunc(GL_LEQUAL, model->maskDepth, model->maskDepth);
					glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
				} else {
					glColorMask(1, 1, 1, 1);
					glDisable(GL_STENCIL_TEST);
					//if(model->isDepthTest) {
					//glEnable(GL_DEPTH_TEST);
					//} else {
					//	glDisable(GL_DEPTH_TEST);
					//}
				}
				*/
                
				/*
				 if(model->isLighting) {
				 glEnable(GL_LIGHTING);
				 } else {
				 glDisable(GL_LIGHTING);
				 }
				 */
				
				//if(model->colorMode == ModelColorModeNone) {
				//	glDisable(GL_COLOR_MATERIAL);
				//	glDisableClientState(GL_COLOR_ARRAY);
				//} else if(model->colorMode == ModelColorModeOneColor) {
				//glEnable(GL_COLOR_MATERIAL);
				//glDisableClientState(GL_COLOR_ARRAY);
				glColor4ub(model->mixColor->r, model->mixColor->g, model->mixColor->b, model->mixColor->a);
				//} else if(model->colorMode == ModelColorModeVertexColor) {
				//	glEnable(GL_COLOR_MATERIAL);
				//	glEnableClientState(GL_COLOR_ARRAY);
				//	glColorPointer(4, GL_UNSIGNED_BYTE, 0, model->mixColor);
				//}
				
				
				manager->drawModelCount++;
				//if(model->polygon) {
				//	glDrawElements(GL_TRIANGLES, model->polygonLength, GL_UNSIGNED_SHORT, model->polygon);
				//} else {
				if(model->isTriangleFanMode) {
#ifdef ___MACSIMULATOR___
					if(line){
						glDisable(GL_TEXTURE_2D);
						glLineWidth(1.0f);
						glColor4ub(lineR, lineG, lineB, 0xFF);
						glDrawArrays(GL_LINE_STRIP, 1, model->vertexLength - 2);
					}else
#endif
						glDrawArrays(GL_TRIANGLE_FAN, 0, model->vertexLength);
				}else{
#ifdef ___MACSIMULATOR___
					if(line)
					{
						glDisable(GL_TEXTURE_2D);
						glLineWidth(1.0);
						glColor4ub(lineR, lineG, lineB, 0xFF);
						glDrawArrays(GL_LINE_STRIP, 0, model->vertexLength);
						Vector3D vec[4];
						vec[0] = model->vertex[1];
						vec[1] = model->vertex[3];
						vec[2] = model->vertex[0];
						vec[3] = model->vertex[2];
						glVertexPointer(3, GL_FLOAT, 0, vec);
						glDrawArrays(GL_LINES, 0, 4);
					}
					else
#endif

						glDrawArrays(GL_TRIANGLE_STRIP, 0, model->vertexLength);
				}
				//}
				

				
				
			}
		//}
#ifdef ___MACSIMULATOR___
		for(int i = 0; i < model->child->length; i++)
			ModelManagerDisplay(manager, model->child->data[i], line);
#else

		for(int i = 0; i < model->child->length; i++)
			ModelManagerDisplay(manager, model->child->data[i]);
#endif
	
	
	glPopMatrix();
	}
	return true;
}

bool ModelManagerDisplayEnd(ModelManager* manager) {
	//printf("a %i\n", manager->touchArguments->length);
	while(manager->touchArguments->length) {
		ModelEventTouchArgument* touchArgument = ArrayObjectAtIndex(manager->touchArguments, 0);
		ArrayPopObjectAtIndex(manager->touchArguments, 0);
		free(touchArgument);
	}
	return true;
}

#pragma mark -
#pragma mark ModelManager 관리자 드바이스 이벤트 받는 함수

bool ModelManagerTouch(ModelManager* manager,
					   Vector2D touch, 
					   void* touchID, 
					   TouchType touchType, 
					   unsigned char tabCount) {
	ModelEventTouchArgument* touchArgument = (ModelEventTouchArgument*)calloc(1, sizeof(ModelEventTouchArgument));
	touchArgument->touchVector = touch;
	touchArgument->touchID = touchID;
	touchArgument->touchType = touchType;
	touchArgument->touchTabCount = tabCount;
	ArrayPushObject(manager->touchArguments, touchArgument);
	return true;
}
コード例 #26
0
/**
* Clear the screen, then render the mesh using the given camera.
* @param camera The logical camera to use.
* @see math/camera.hpp
*/
void OpenglProject::render(const Camera* camera)
{
   // TODO render code
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);




   //Quaternion to calcuate the angle and axis for rotation
   Quaternion rotation = scene.mesh_position.orientation;
   Quaternion rotationHeight = scene.heightmap_position.orientation;


   //Container mesh rotation conversion
   Vector3 rot_axis;
   double angle;
   rotation.to_axis_angle(&rot_axis, &angle);
   angle = angle *(180 / PI);


   //Heightmap mesh rotation conversion
   Vector3 rot_axisHeight;
   double angleHeight;
   rotationHeight.to_axis_angle(&rot_axisHeight, &angleHeight);
   angleHeight = angleHeight * (180 / PI);






   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();



   //Camera set up
   gluLookAt(camera->position.x, camera->position.y, camera->position.z,
             camera->position.x + camera->get_direction().x, 
             camera->position.y + camera->get_direction().y, 
             camera->position.z + camera->get_direction().z,
             camera->get_up().x, camera->get_up().y, camera->get_up().z);
		
		



   //Transformation for the heightmap mesh data
   glPushMatrix();

		
   GLfloat waterColor[] = { 0.0, 0.65, 1.0, 1.0 };
   GLfloat mat_specular[] = { 0.0, 0.65, 1.0, 1.0 };
   GLfloat low_shininess[] = { 6.0 };

   glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, waterColor);
   glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
   glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, low_shininess);
		

   glTranslated(
     scene.heightmap_position.position.x, 
     scene.heightmap_position.position.y,
     scene.heightmap_position.position.z);
   glRotated( angleHeight, 
              rot_axisHeight.x, rot_axisHeight.y, rot_axisHeight.z);
   glScaled(scene.heightmap_position.scale.x, 
            scene.heightmap_position.scale.y,
            scene.heightmap_position.scale.z);

   glEnableClientState(GL_VERTEX_ARRAY);
   glEnableClientState(GL_NORMAL_ARRAY);
   glColor3f(0.0, 1.0, 1.0);
   glVertexPointer(3, GL_DOUBLE, 0, masterHeightMap);
   glNormalPointer(GL_DOUBLE, 0, masterHeightNorm);
   glDrawElements(GL_TRIANGLES, 6 * (NUMVERTS - 1)*(NUMVERTS - 1), 
                  GL_UNSIGNED_INT, masterHIndex);
		
   glPopMatrix();

   //Transformation for the triangle mesh data
   glTranslated(scene.mesh_position.position.x, 
                scene.mesh_position.position.y, 
                scene.mesh_position.position.z);
   glRotated(angle, rot_axis.x, rot_axis.y, rot_axis.z);
   glScaled(scene.mesh_position.scale.x, 
            scene.mesh_position.scale.y, 
            scene.mesh_position.scale.z);
   display_callback();



   glFlush();

}
コード例 #27
0
ファイル: Init.cpp プロジェクト: PhilColbert/LK8000
void
OpenGL::SetupContext()
{
#if defined(HAVE_DYNAMIC_EGL)
  egl = EGLInit();
#endif

  texture_non_power_of_two = SupportsNonPowerOfTwoTextures();

#ifdef HAVE_OES_DRAW_TEXTURE
  oes_draw_texture = CheckOESDrawTexture();
#endif

#ifdef ANDROID
  native_view->SetTexturePowerOfTwo(texture_non_power_of_two);

  vertex_buffer_object = EnableVBO();
#endif

#ifdef HAVE_OES_MAPBUFFER
  mapbuffer = IsExtensionSupported("GL_OES_mapbuffer");
#endif

#ifdef HAVE_DYNAMIC_MAPBUFFER
  if (mapbuffer) {
    GLExt::map_buffer = (PFNGLMAPBUFFEROESPROC)
      eglGetProcAddress("glMapBufferOES");
    GLExt::unmap_buffer = (PFNGLUNMAPBUFFEROESPROC)
      eglGetProcAddress("glUnmapBufferOES");
    if (GLExt::map_buffer == nullptr || GLExt::unmap_buffer == nullptr)
      mapbuffer = false;
  }
#endif

#ifdef HAVE_DYNAMIC_MULTI_DRAW_ARRAYS
  if (IsExtensionSupported("GL_EXT_multi_draw_arrays")) {
    GLExt::multi_draw_arrays = (PFNGLMULTIDRAWARRAYSEXTPROC)
      dlsym(RTLD_DEFAULT, "glMultiDrawArraysEXT");
    GLExt::multi_draw_elements = (PFNGLMULTIDRAWELEMENTSEXTPROC)
      dlsym(RTLD_DEFAULT, "glMultiDrawElementsEXT");
  } else {
    GLExt::multi_draw_arrays = nullptr;
    GLExt::multi_draw_elements = nullptr;
  }
#endif

  frame_buffer_object = CheckFBO() && FBO::Initialise();
  if (frame_buffer_object) {
    render_buffer_depth_stencil = CheckDepthStencil();

    render_buffer_stencil = CheckStencil();
    if (!render_buffer_stencil)
      /* fall back to a packed depth+stencil format */
      render_buffer_stencil = render_buffer_depth_stencil;
  }

  glDisable(GL_DEPTH_TEST);
  glDisable(GL_DITHER);
#ifndef HAVE_GLES2
  glDisable(GL_LIGHTING);
#endif

#ifndef USE_GLSL
  glEnableClientState(GL_VERTEX_ARRAY);
#endif

  InitShapes();

#ifdef USE_GLSL
  InitShaders();
#endif

#ifndef HAVE_GLES
  ::glGetIntegerv(GL_MAX_ATTRIB_STACK_DEPTH, &max_attrib_stack_depth);
#endif
}
コード例 #28
0
ファイル: copyteximage.c プロジェクト: blaztinn/piglit
enum piglit_result
piglit_display(void)
{
	GLfloat buf_fcolor[IMAGE_SIZE][IMAGE_SIZE][4];
	GLuint tex;
	GLboolean pass = GL_TRUE;
	GLenum format;
	const GLfloat *expected;
	int i, j;

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	/* Image data setup */
	for (i = 0; i < IMAGE_SIZE; i++) {
		for (j = 0; j < IMAGE_SIZE; j++) {
			buf_fcolor[i][j][0] = 0.5;
			buf_fcolor[i][j][1] = 0.2;
			buf_fcolor[i][j][2] = 0.8;
			buf_fcolor[i][j][3] = 0.4;
		}
	}

	/* Do glCopyPixels and draw a textured rectangle for each format
	 * and each texture target
	 */
	for (j = 0; j < ARRAY_SIZE(target); j++) {

		/* Draw a pixel rectangle with float color data. As per OpenGL 3.0
		 * specification integer formats are not allowed in glDrawPixels
		 */
		glDrawPixels(IMAGE_SIZE, IMAGE_SIZE, GL_RGBA,
			     GL_FLOAT, buf_fcolor);

		/* Texture setup */
		glGenTextures(1, &tex);
		glBindTexture(target[j], tex);
		glTexParameteri(target[j],
				GL_TEXTURE_MIN_FILTER,
				GL_NEAREST);
		glTexParameteri(target[j],
				GL_TEXTURE_MAG_FILTER,
				GL_NEAREST);
		glTexParameteri(target[j],
				GL_GENERATE_MIPMAP,
				GL_FALSE);

		glEnableClientState(GL_TEXTURE_COORD_ARRAY);

		for (i = 0; i < ARRAY_SIZE(test_vectors); i++) {
			GLint x = IMAGE_SIZE * (i + 1);
			GLint y = 0;
			GLfloat vertices_1d[2][2] = { {x, y},
						      {x + IMAGE_SIZE, y} };

			format = test_vectors[i].format;
			expected = (const float*)test_vectors[i].expected;

			if(!piglit_automatic)
				printf("Texture target = %s, Internal"
				       " format = %s\n",
				       piglit_get_gl_enum_name(target[j]),
				       piglit_get_gl_enum_name(format));

			if (!supported_format(format) ||
			    !supported_target_format(target[j], format)) {
				if (!piglit_automatic)
					printf("Internal format = %s skipped\n",
					       piglit_get_gl_enum_name(format));
				continue;
			}

			/* To avoid failures not related to this test case,
			 * loosen up the tolerence for compressed texture
			 * formats
			 */
			if (is_compressed_format(format))
				piglit_set_tolerance_for_bits(7, 7, 7, 7);
			else
				piglit_set_tolerance_for_bits(8, 8, 8, 8);

			switch(target[j]) {

			case GL_TEXTURE_1D:
				glCopyTexImage1D(GL_TEXTURE_1D, 0,
						 format,
						 0, 0, IMAGE_SIZE, 0);
				pass = piglit_check_gl_error(GL_NO_ERROR)
				       && pass;

				glEnable(target[j]);
				glEnableClientState(GL_VERTEX_ARRAY);
				glTexCoordPointer(1, GL_FLOAT, 0, texCoords_1d);
				glVertexPointer(2, GL_FLOAT, 0, vertices_1d);

				glDrawArrays(GL_LINES, 0, 2);
				pass = piglit_probe_pixel_rgba(x, 0, expected)
				       && pass;
				pass = piglit_probe_pixel_rgba(x + IMAGE_SIZE - 1,
							       0, expected)
				       && pass;
				break;

			case GL_TEXTURE_2D:
				glCopyTexImage2D(GL_TEXTURE_2D, 0, format, 0, 0,
						 IMAGE_SIZE, IMAGE_SIZE, 0);
				pass = piglit_check_gl_error(GL_NO_ERROR) && pass;

				glEnable(target[j]);
				glTexCoordPointer(2, GL_FLOAT, 0, texCoords_2d);

				piglit_draw_rect(x, y, IMAGE_SIZE, IMAGE_SIZE);
				pass = piglit_probe_rect_rgba(x, y, IMAGE_SIZE,
							      IMAGE_SIZE,
							      expected)
				       && pass;
				break;

			case GL_TEXTURE_CUBE_MAP:
				glCopyTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X,
						 0, format, 0, 0,
						 IMAGE_SIZE, IMAGE_SIZE, 0);
				glCopyTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
						 0, format, 0, 0,
						 IMAGE_SIZE, IMAGE_SIZE, 0);
				glCopyTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
						 0, format, 0, 0,
						 IMAGE_SIZE, IMAGE_SIZE, 0);
				glCopyTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
						 0, format, 0, 0,
						 IMAGE_SIZE, IMAGE_SIZE, 0);
				glCopyTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
						 0, format, 0, 0,
						 IMAGE_SIZE, IMAGE_SIZE, 0);
				glCopyTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
						 0, format, 0, 0,
						 IMAGE_SIZE, IMAGE_SIZE, 0);
				pass = piglit_check_gl_error(GL_NO_ERROR) && pass;

				glEnable(target[j]);

				/* Draw a rect with +X cubemap face as texture */
				glTexCoordPointer(3, GL_FLOAT, 0,
						  cube_face_texcoords[0]);
				piglit_draw_rect(x, y, IMAGE_SIZE, IMAGE_SIZE);
				pass = piglit_probe_rect_rgba(x, y,
				       IMAGE_SIZE, IMAGE_SIZE, expected)
				       && pass;

				/* Draw a rect with +Z cubemap face as texture */
				glTexCoordPointer(3, GL_FLOAT, 0,
						  cube_face_texcoords[2]);
				piglit_draw_rect(x, y, IMAGE_SIZE, IMAGE_SIZE);
				pass = piglit_probe_rect_rgba(x, y,
				       IMAGE_SIZE, IMAGE_SIZE, expected)
				       && pass;
				break;
			}
			glDisable(target[j]);
		}
		glDisableClientState(GL_TEXTURE_COORD_ARRAY);
		glDeleteTextures(1, &tex);
	}
	if (!piglit_automatic)
		piglit_present_results();
	return (pass ? PIGLIT_PASS : PIGLIT_FAIL);
}
コード例 #29
0
int main(int argc, char **argv)
#endif
{
    GLuint  ui32Vbo = 0; // Vertex buffer object handle
    GLuint  ui32IndexVbo;
    GLuint  ui32Texture;

    int nframes = 100;
    bool immidateMode     = false;
    bool useIndices       = true;
    bool useTexture       = false;
    bool useCompTexture   = false;
    bool useConvertedType = true;
    bool useFixed         = false;
    bool usePoints        = false;
    bool useCopy          = false;
    bool useSubCopy       = false;

    int c;
    extern char *optarg;

    #ifdef _WIN32
        HWND   windowId = NULL;
    #elif __linux__
        Window windowId = NULL;
    #elif __APPLE__
        void* windowId = NULL;
    #endif

        //      // Inialize SDL window
        //
        if (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_VIDEO)) {
            fprintf(stderr,"SDL init failed: %s\n", SDL_GetError());
            return -1;
        }

        SDL_Surface *surface = SDL_SetVideoMode(WINDOW_WIDTH,WINDOW_HEIGHT, 32, SDL_HWSURFACE);
        if (surface == NULL) {
            fprintf(stderr,"Failed to set video mode: %s\n", SDL_GetError());
            return -1;
        }

        SDL_SysWMinfo  wminfo;
        memset(&wminfo, 0, sizeof(wminfo));
        SDL_GetWMInfo(&wminfo);
    #ifdef _WIN32
        windowId = wminfo.window;
    #elif __linux__
        windowId = wminfo.info.x11.window;
    #elif __APPLE__
        windowId = createGLView(wminfo.nsWindowPtr,0,0,WINDOW_WIDTH,WINDOW_HEIGHT);

    #endif

        int major,minor,num_config;
        EGLConfig configs[150];
        EGLSurface egl_surface;
        EGLContext ctx;
        EGLDisplay d = eglGetDisplay(EGL_DEFAULT_DISPLAY);
        eglInitialize(d,&major,&minor);
        printf("DISPLAY == %p major =%d minor = %d\n",d,major,minor);
        eglChooseConfig(d, attribute_list, configs, 150, &num_config);
        printf("config returned %d\n",num_config);
        egl_surface = eglCreateWindowSurface(d,configs[0],windowId,NULL);
        printf("before creating context..\n");
        ctx = eglCreateContext(d,configs[0],EGL_NO_CONTEXT,NULL);
        printf("SURFACE == %p CONTEXT == %p\n",egl_surface,ctx);
        if(eglMakeCurrent(d,egl_surface,egl_surface,ctx)!= EGL_TRUE){
            printf("make current failed\n");
            return false;
        }
        printf("after make current\n");

        GLenum err = glGetError();
        if(err != GL_NO_ERROR) {
        printf("error before drawing ->>> %d  \n",err);
        } else {
        printf("no error before drawing\n");
        }

    if (useTexture) {

        glEnable(GL_TEXTURE_2D);
        ui32Texture = 1;
        glBindTexture(GL_TEXTURE_2D, ui32Texture);
                GLenum err = glGetError();

        unsigned char *pixels = NULL;
                if(useCompTexture) {
                        pixels = genPalette4_rgb8(TEX_WIDTH,TEX_HEIGHT,3);
                        glCompressedTexImage2D(GL_TEXTURE_2D,0,GL_PALETTE4_RGB8_OES,TEX_WIDTH,TEX_HEIGHT,0,3*16+TEX_WIDTH*TEX_HEIGHT/2,pixels);

                } else {
                        pixels = genTexture(TEX_WIDTH, TEX_HEIGHT, 4);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEX_WIDTH, TEX_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
                }

        delete pixels;

                err = glGetError();
                if(err != GL_NO_ERROR)
            printf("error %d after image \n",err);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
                err = glGetError();
                if(err != GL_NO_ERROR)
            printf("error after min filter \n");
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
                err = glGetError();
                if(err != GL_NO_ERROR)
            printf("error after mag filter \n");
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
                err = glGetError();
                if(err != GL_NO_ERROR)
            printf("error after env mode \n");

                if(useCompTexture) {
                    pixels = genPalette4_rgb8(TEX_WIDTH,TEX_HEIGHT,1);
                    glCompressedTexSubImage2D(GL_TEXTURE_2D,0,TEX_WIDTH/4,TEX_HEIGHT/4,TEX_WIDTH/8,TEX_HEIGHT/8,GL_PALETTE4_RGB8_OES,3*16+(TEX_WIDTH*TEX_HEIGHT/128),pixels);
                } else {
            pixels = genRedTexture(TEX_WIDTH/8, TEX_HEIGHT/8, 4);
                    glTexSubImage2D(GL_TEXTURE_2D,0,TEX_WIDTH/4,TEX_HEIGHT/4,TEX_WIDTH/8,TEX_HEIGHT/8,GL_RGBA,GL_UNSIGNED_BYTE,pixels);
                }
                 err = glGetError();
                if(err != GL_NO_ERROR)
            printf("error %d after subimage \n",err);
        delete pixels;

    }

    glClearColor(0.6f, 0.8f, 1.0f, 1.0f); // clear blue

    float afVertices[] = {  -0.4f,-0.4f,0.0f, // Position
                 1.0f,0.0f,0.0f,1.0f, // Color
                 0.0f, 0.0f, // texture
                 12.f, //point size

                 0.4f,-0.4f,0.0f,
                 0.0f,1.0f,0.0f,1.0f,
                 1.0f, 0.0f,
                 47.0f,

                 0.0f,0.4f,0.0f,
                 0.0f,0.0f,1.0f,1.0f,
                 0.5f, 1.0f,
                 14.0f
    };

#define MAX_T 1
#define MID_T 0
#define MIN_T 0

    GLbyte byteVertices[] = { -1,-1,0, // Position
                             255,0,0,255, // Color
                             MIN_T, MIN_T, // texture
                             12, //point size

                             1,-1,0,
                             0,255,0,255,
                             MAX_T,MIN_T,
                             47,

                            0,1,0,
                            0,0,255,255,
                            MID_T, MAX_T,
                            14
    };

    GLfixed fixedVertices[] = { F_to_X(-0.4f),F_to_X(-0.4f),F_to_X(0.0f), // Position
                    F_to_X(1.0f),F_to_X(0.0f),F_to_X(0.0f),F_to_X(1.0f), // Color
                    F_to_X(0.0f),F_to_X(0.0f), // texture
                    F_to_X(12.0f),//points size

                    F_to_X(0.4f),F_to_X(-0.4f),F_to_X(0.0f),
                    F_to_X(0.0f),F_to_X(1.0f),F_to_X(0.0f),F_to_X(1.0f),
                    F_to_X(1.0f),F_to_X( 0.0f),
                    F_to_X(30.0f),

                    F_to_X(0.0f),F_to_X(0.4f),F_to_X(0.0f),
                    F_to_X(0.0f),F_to_X(0.0f),F_to_X(1.0f),F_to_X(1.0f),
                    F_to_X(0.5f), F_to_X(1.0f),
                    F_to_X(30.0)
    };

    unsigned short indices[] = { 2, 1, 0 };

    if (!immidateMode) {
        glGenBuffers(1, &ui32Vbo);
        ui32Vbo = 1;
         printf("ui32Vbo = %d\n", ui32Vbo);

        glBindBuffer(GL_ARRAY_BUFFER, ui32Vbo);
        void* data = (void*)afVertices;
        unsigned int uiSize = 3*(sizeof(float)*10);
        if(useConvertedType){
           if(useFixed){
               data = (void*)fixedVertices;
           } else {
               data   = (void*)byteVertices;
               uiSize = 3*(sizeof(GLbyte)*10);
           }
        }
        glBufferData(GL_ARRAY_BUFFER, uiSize,data, GL_STATIC_DRAW);

        ui32IndexVbo = 2;
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ui32IndexVbo);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
    }

    // Draws a triangle for 800 frames
    float angle = 0.0;
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    GLvoid* arr = NULL;
    GLenum  type;
    GLenum  drawType;
    GLenum  colorType;
    int     size_of;

    if(useConvertedType){
        if(useFixed)
        {
            arr = fixedVertices;
            colorType = type = GL_FIXED;
            size_of = sizeof(GLfixed);
        } else {
            arr = byteVertices;
            colorType = GL_UNSIGNED_BYTE;
            type = GL_BYTE;
            size_of = sizeof(GLbyte);
        }
    }else {
        arr = afVertices;
        colorType = type = GL_FLOAT;
        size_of = sizeof(float);
    }

    if(usePoints)
    {
        drawType = GL_POINTS;
    }
    else
        drawType = GL_TRIANGLES;

    GLvoid* data = NULL;
    for (int i = 0; i < 100; i++) {

        glClear(GL_COLOR_BUFFER_BIT);
        glPushMatrix();
        glRotatef(angle, 0.0, 0.0, 1.0);
        angle += 360.0 / nframes;
        // Enable vertex arrays
        glEnableClientState(GL_VERTEX_ARRAY);
        if (immidateMode) {
            glVertexPointer(3,type, size_of * 10, arr);
        } else {
            glVertexPointer(3,type, size_of * 10, 0);
        }

        // Set color data in the same way
        glEnableClientState(GL_COLOR_ARRAY);
        if (immidateMode) {
            SWITCH_SOURCE(3)
            glColorPointer(4, colorType, size_of * 10, data);
        } else {
            glColorPointer(4,colorType,size_of * 10, (GLvoid*) (size_of * 3) );
        }
        if (useTexture) {
            glEnableClientState(GL_TEXTURE_COORD_ARRAY);
            if (immidateMode) {
                SWITCH_SOURCE(7)
                glTexCoordPointer(2, type, size_of * 10,data);
            } else {
                glTexCoordPointer(2, type, size_of * 10, (GLvoid*)(size_of * 7));
            }
        }
        if(usePoints)
        {
            glEnableClientState(GL_POINT_SIZE_ARRAY_OES);
            if (immidateMode) {
                SWITCH_SOURCE(9)
                glPointSizePointerOES(type,size_of * 10,data);
                        } else {
                glPointSizePointerOES(type,size_of * 10,(GLvoid*)(size_of * 9));
                        }
        }

        if (useIndices) {
            if (immidateMode) {
                glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
                glDrawElements(drawType, 3, GL_UNSIGNED_SHORT, indices);
            } else {
                glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ui32IndexVbo);
                glDrawElements(drawType, 3, GL_UNSIGNED_SHORT, 0);
            }
        } else {
            glDrawArrays(drawType, 0, 3);
        }

                GLenum err = glGetError();
                if(err != GL_NO_ERROR)
            printf(" error %d has occured while drawing\n",err);


        glPopMatrix();
                eglSwapBuffers(d,egl_surface);

                if(useTexture && useCopy)
                    glCopyTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,0,0,256,256,0);
                else if(useTexture && useSubCopy)
                    glCopyTexSubImage2D(GL_TEXTURE_2D,0,100,100,WINDOW_WIDTH/2,WINDOW_HEIGHT/2,50,50);
    }
                err = glGetError();
                if(err != GL_NO_ERROR)
            printf("error ->>> %d  \n",err);
        eglDestroySurface(d,egl_surface);
        eglDestroyContext(d,ctx);

// Just wait until the window is closed
        SDL_Event ev;
        while( SDL_WaitEvent(&ev) ) {
            if (ev.type == SDL_QUIT) {
                break;
            }
        }
    return 0;
}
コード例 #30
0
ファイル: render.cpp プロジェクト: jefferis/rgl
void VertexArray::beginUse() {
  glEnableClientState(GL_VERTEX_ARRAY);
  glVertexPointer(3, GL_FLOAT, 0, (const GLvoid*) arrayptr );
}