int main(int argc, char** argv)
{
    int ch, width, height;
    thrd_t physics_thread = 0;
    GLFWwindow* window;
    GLFWmonitor* monitor = NULL;

    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        exit(EXIT_FAILURE);
    }

    while ((ch = getopt(argc, argv, "fh")) != -1)
    {
        switch (ch)
        {
            case 'f':
                monitor = glfwGetPrimaryMonitor();
                break;
            case 'h':
                usage();
                exit(EXIT_SUCCESS);
        }
    }

    if (monitor)
    {
        const GLFWvidmode* mode = glfwGetVideoMode(monitor);

        glfwWindowHint(GLFW_RED_BITS, mode->redBits);
        glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
        glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
        glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);

        width  = mode->width;
        height = mode->height;
    }
    else
    {
        width  = 640;
        height = 480;
    }

    window = glfwCreateWindow(width, height, "Particle Engine", monitor, NULL);
    if (!window)
    {
        fprintf(stderr, "Failed to create GLFW window\n");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    if (monitor)
        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    glfwSetFramebufferSizeCallback(window, resize_callback);
    glfwSetKeyCallback(window, key_callback);

    // Set initial aspect ratio
    glfwGetFramebufferSize(window, &width, &height);
    resize_callback(window, width, height);

    // Upload particle texture
    glGenTextures(1, &particle_tex_id);
    glBindTexture(GL_TEXTURE_2D, particle_tex_id);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, P_TEX_WIDTH, P_TEX_HEIGHT,
                 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, particle_texture);

    // Upload floor texture
    glGenTextures(1, &floor_tex_id);
    glBindTexture(GL_TEXTURE_2D, floor_tex_id);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, F_TEX_WIDTH, F_TEX_HEIGHT,
                 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, floor_texture);

    if (glfwExtensionSupported("GL_EXT_separate_specular_color"))
    {
        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT,
                      GL_SEPARATE_SPECULAR_COLOR_EXT);
    }

    // Set filled polygon mode as default (not wireframe)
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    wireframe = 0;

    // Set initial times
    thread_sync.t  = 0.0;
    thread_sync.dt = 0.001f;
    thread_sync.p_frame = 0;
    thread_sync.d_frame = 0;

    mtx_init(&thread_sync.particles_lock, mtx_timed);
    cnd_init(&thread_sync.p_done);
    cnd_init(&thread_sync.d_done);

    if (thrd_create(&physics_thread, physics_thread_main, window) != thrd_success)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetTime(0.0);

    while (!glfwWindowShouldClose(window))
    {
        draw_scene(window, glfwGetTime());

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    thrd_join(physics_thread, NULL);

    glfwDestroyWindow(window);
    glfwTerminate();

    exit(EXIT_SUCCESS);
}
Example #2
0
void OpenGL2Common::initializeGL()
{
    initGLProc();
#ifndef OPENGL_ES2
    if (!glActiveTexture) //Be sure that "glActiveTexture" has valid pointer (don't check "supportsShaders" here)!
    {
        showOpenGLMissingFeaturesMessage();
        isOK = false;
        return;
    }
#endif

    delete shaderProgramVideo;
    delete shaderProgramOSD;
    shaderProgramVideo = new QOpenGLShaderProgram;
    shaderProgramOSD = new QOpenGLShaderProgram;

    /* YCbCr shader */
    shaderProgramVideo->addShaderFromSourceCode(QOpenGLShader::Vertex, readShader(":/Video.vert"));
    QByteArray videoFrag;
    if (numPlanes == 1)
    {
        videoFrag = readShader(":/VideoRGB.frag");
        if (canUseHueSharpness)
        {
            //Use sharpness only when OpenGL/OpenGL|ES version >= 3.0, because it can be slow on old hardware and/or buggy drivers and may increase CPU usage!
            videoFrag.prepend("#define Sharpness\n");
        }
    }
    else
    {
        videoFrag = readShader(":/VideoYCbCr.frag");
        if (canUseHueSharpness)
        {
            //Use hue and sharpness only when OpenGL/OpenGL|ES version >= 3.0, because it can be slow on old hardware and/or buggy drivers and may increase CPU usage!
            videoFrag.prepend("#define HueAndSharpness\n");
        }
        if (numPlanes == 2)
            videoFrag.prepend("#define NV12\n");
    }
    if (target == GL_TEXTURE_RECTANGLE_ARB)
        videoFrag.prepend("#define TEXTURE_RECTANGLE\n");
    if (hqScaling)
    {
        constexpr const char *getTexelDefine = "#define getTexel texture\n";
        Q_ASSERT(videoFrag.contains(getTexelDefine));
        videoFrag.replace(getTexelDefine, readShader(":/Bicubic.frag", true));
    }
    shaderProgramVideo->addShaderFromSourceCode(QOpenGLShader::Fragment, videoFrag);
    if (shaderProgramVideo->bind())
    {
        texCoordYCbCrLoc = shaderProgramVideo->attributeLocation("aTexCoord");
        positionYCbCrLoc = shaderProgramVideo->attributeLocation("aPosition");
        shaderProgramVideo->setUniformValue((numPlanes == 1) ? "uRGB" : "uY" , 0);
        if (numPlanes == 2)
            shaderProgramVideo->setUniformValue("uCbCr", 1);
        else if (numPlanes == 3)
        {
            shaderProgramVideo->setUniformValue("uCb", 1);
            shaderProgramVideo->setUniformValue("uCr", 2);
        }
        shaderProgramVideo->release();
    }
    else
    {
        QMPlay2Core.logError(tr("Shader compile/link error"));
        isOK = false;
        return;
    }

    /* OSD shader */
    shaderProgramOSD->addShaderFromSourceCode(QOpenGLShader::Vertex, readShader(":/OSD.vert"));
    shaderProgramOSD->addShaderFromSourceCode(QOpenGLShader::Fragment, readShader(":/OSD.frag"));
    if (shaderProgramOSD->bind())
    {
        texCoordOSDLoc = shaderProgramOSD->attributeLocation("aTexCoord");
        positionOSDLoc = shaderProgramOSD->attributeLocation("aPosition");
        shaderProgramOSD->setUniformValue("uTex", 3);
        shaderProgramOSD->release();
    }
    else
    {
        QMPlay2Core.logError(tr("Shader compile/link error"));
        isOK = false;
        return;
    }

    /* Set OpenGL parameters */
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glDisable(GL_STENCIL_TEST);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_DITHER);

    /* Prepare textures */
    glGenTextures(numPlanes + 1, textures);
    for (int i = 0; i < numPlanes + 1; ++i)
    {
        const quint32 tmpTarget = (i == 0) ? GL_TEXTURE_2D : target;
        qint32 tmpParam  = (i == 0) ? GL_NEAREST : GL_LINEAR;
        glBindTexture(tmpTarget, textures[i]);
        glTexParameteri(tmpTarget, GL_TEXTURE_MIN_FILTER, tmpParam);
        glTexParameteri(tmpTarget, GL_TEXTURE_MAG_FILTER, tmpParam);
        glTexParameteri(tmpTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(tmpTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    }

    if (hasPbo)
    {
        glGenBuffers(1 + (hwAccellnterface ? 0 : numPlanes), pbo);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    }

    setVSync(vSync);

    doReset = true;
    resetSphereVbo();
}
		void display()
		{
			mMediaSource->idle();

			// Check whether the texture needs to be recreated.
			if(mMediaSource->textureValid())
			{
				if(
					(mAppTextureWidth != mMediaSource->getTextureWidth() ||	mAppTextureHeight != mMediaSource->getTextureHeight()) &&
					(mAppWindowWidth == mMediaSource->getWidth() && mAppWindowHeight == mMediaSource->getHeight())
				)
				{
					// Attempt to (re)create the texture
					createTexture();
				}
			}
						
			// clear screen
			glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

			glLoadIdentity();
			
			if(mAppTexture != 0)
			{
				// use the browser texture
				glBindTexture( GL_TEXTURE_2D, mAppTexture );

				// If dirty, update the texture.
				LLRect dirtyRect;
				if(!mMediaSource->textureValid())
				{
//					LL_DEBUGS("media_plugin_test") << "Resize in progress, skipping update..." << LL_ENDL;
				}
				else if(mAppWindowWidth != mMediaSource->getWidth() || mAppWindowHeight != mMediaSource->getHeight())
				{
					// A resize is in progress.  Just wait for it...
				}
				else if(mMediaSource->getDirty(&dirtyRect))
				{
					// grab the page
					const unsigned char* pixels = mMediaSource->getBitsData();
					if ( pixels )
					{
						// write them into the texture
						
						// Paranoia: intersect dirtyRect with (0, 0, mAppTextureWidth, mAppTextureHeight)?

						int x_offset = dirtyRect.mLeft;
						int y_offset = dirtyRect.mBottom;
						int width = dirtyRect.mRight - dirtyRect.mLeft;
						int height = dirtyRect.mTop - dirtyRect.mBottom;

						LL_DEBUGS("media_plugin_test") << "Updating, dirty rect is (" 
							<< dirtyRect.mLeft << ", " 
							<< dirtyRect.mTop << ", " 
							<< dirtyRect.mRight << ", " 
							<< dirtyRect.mBottom << "), update params are: (" 
							<< x_offset << ", " 
							<< y_offset << ", " 
							<< width << ", " 
							<< height << ")" 
							<< LL_ENDL; 
						
						// Offset the pixels pointer properly
						pixels += (y_offset * mMediaSource->getTextureDepth() * mMediaSource->getTextureWidth());
						pixels += (x_offset * mMediaSource->getTextureDepth());
						
						glPixelStorei(GL_UNPACK_ROW_LENGTH, mMediaSource->getTextureWidth());
						
						glTexSubImage2D( GL_TEXTURE_2D, 0, 
							x_offset, 
							y_offset,
							width, 
							height,
							mMediaSource->getTextureFormatPrimary(), 
							mMediaSource->getTextureFormatType(), 
							pixels );
						
						mMediaSource->resetDirty();
					}
				}
				
				// scale the texture so that it fits the screen
				GLdouble media_texture_x = mAppWindowWidth / (double)mAppTextureWidth;
				GLdouble media_texture_y = mAppWindowHeight / (double)mAppTextureHeight;

				// draw the single quad full screen (orthographic)

				glEnable( GL_TEXTURE_2D );
				glColor3f( 1.0f, 1.0f, 1.0f );
				glBegin( GL_TRIANGLE_STRIP );
				if(mAppTextureCoordsOpenGL)
				{
					// Render the texture as per opengl coords (where 0,0 is at the lower left)
					glTexCoord2d( 0, 0 );
					glVertex2d( 0, 0 );

					glTexCoord2d( 0 , media_texture_y );
					glVertex2d( 0, mAppWindowHeight);

					glTexCoord2d(media_texture_x, 0);
					glVertex2d(mAppWindowWidth, 0);

					glTexCoord2d( media_texture_x, media_texture_y );
					glVertex2d( mAppWindowWidth , mAppWindowHeight);
				}
				else
				{
					// Render the texture the "other way round" (where 0,0 is at the upper left)
					glTexCoord2d( 0, media_texture_y );
					glVertex2d( 0, 0 );

					glTexCoord2d( 0 , 0 );
					glVertex2d( 0, mAppWindowHeight);

					glTexCoord2d(media_texture_x, media_texture_y);
					glVertex2d(mAppWindowWidth, 0);

					glTexCoord2d( media_texture_x, 0 );
					glVertex2d( mAppWindowWidth , mAppWindowHeight);
				}
				glEnd();

			}
			
			glutSwapBuffers();
		};
Example #4
0
    std::vector<uint8_t> RenderTarget::getImagePixels( GLenum mode, dp::PixelFormat pixelFormat, dp::DataType pixelDataType )
    {
      // FIXME use C++ object for current/noncurrent for exception safety
      makeCurrent();

      size_t components = 0;
      size_t bytesPerComponent = 0;

      // set up alignments
      glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
      glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
      glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
      glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
      glPixelStorei(GL_PACK_ALIGNMENT, 1);
      glPixelStorei(GL_PACK_ROW_LENGTH, 0);
      glPixelStorei(GL_PACK_SKIP_ROWS, 0);
      glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

      // determine OpenGL format
      GLenum format = ~0;
      switch (pixelFormat)
      {
      case dp::PixelFormat::RGB:
        format = GL_RGB;
        components = 3;
        break;
      case dp::PixelFormat::RGBA:
        format = GL_RGBA;
        components = 4;
        break;
      case dp::PixelFormat::BGR:
        format = GL_BGR;
        components = 3;
        break;
      case dp::PixelFormat::BGRA:
        format = GL_BGRA;
        components = 4;
        break;
      case dp::PixelFormat::LUMINANCE:
        format = GL_LUMINANCE;
        components = 1;
        break;
      case dp::PixelFormat::ALPHA:
        format = GL_ALPHA;
        components = 1;
        break;
      case dp::PixelFormat::LUMINANCE_ALPHA:
        format = GL_LUMINANCE_ALPHA;
        components = 2;
        break;
      case dp::PixelFormat::DEPTH_COMPONENT:
        format = GL_DEPTH_COMPONENT;
        components = 1;
        break;
      case dp::PixelFormat::DEPTH_STENCIL:
        format = GL_DEPTH_STENCIL;
        components = 1;
        break;
      case dp::PixelFormat::STENCIL_INDEX:
        format = GL_STENCIL_INDEX;
        components = 1;
        break;
      default:
        DP_ASSERT(0 && "unsupported PixelFormat");
      };

      GLenum dataType = ~0;
      switch (pixelDataType)
      {
      case dp::DataType::INT_8:
        dataType = GL_BYTE;
        bytesPerComponent = 1;
        break;
      case dp::DataType::UNSIGNED_INT_8:
        dataType = GL_UNSIGNED_BYTE;
        bytesPerComponent = 1;
        break;
      case dp::DataType::INT_16:
        dataType = GL_SHORT;
        bytesPerComponent = 2;
        break;
      case dp::DataType::UNSIGNED_INT_16:
        dataType = GL_UNSIGNED_SHORT;
        bytesPerComponent = 2;
        break;
      case dp::DataType::INT_32:
        dataType = GL_INT;
        bytesPerComponent = 4;
        break;
      case dp::DataType::UNSIGNED_INT_32:
        dataType = GL_UNSIGNED_INT;
        bytesPerComponent = 4;
        break;
      case dp::DataType::FLOAT_32:
        dataType = GL_FLOAT;
        bytesPerComponent = 4;
        break;
      case dp::DataType::FLOAT_16:
        dataType = GL_HALF_FLOAT;
        bytesPerComponent = 2;
        break;
      default:
        DP_ASSERT(0 && "unsupported PixelDataType");
      }

      size_t imageSizeInBytes = m_width * m_height * components * bytesPerComponent;
      std::vector<uint8_t> output(imageSizeInBytes);

      if ( imageSizeInBytes )
      {
        // read the pixels
        glWindowPos2i(0,0);
        glReadBuffer( mode );

        glReadPixels(0, 0, m_width, m_height, format, dataType, &output[0]);
      }

      makeNoncurrent();

      return output;
    }
Example #5
0
// ----------------------------------------------------------------------------
void STKTexture::reload(bool no_upload, uint8_t* preload_data,
                        video::IImage* preload_img)
{
    if (ProfileWorld::isNoGraphics())
    {
        m_orig_size.Width = 2;
        m_orig_size.Height = 2;
        m_size = m_orig_size;
        m_texture_name = 1;
        if (preload_data)
            delete[] preload_data;
        if (preload_img)
            preload_img->drop();
        return;
    }
#ifndef SERVER_ONLY

    video::IImage* orig_img = NULL;
    uint8_t* data = preload_data;
    if (data == NULL)
    {
        orig_img = preload_img ? preload_img :
            irr_driver->getVideoDriver()->createImageFromFile(NamedPath);
        if (orig_img == NULL)
        {
            return;
        }

        if (orig_img->getDimension().Width  == 0 ||
            orig_img->getDimension().Height == 0)
        {
            orig_img->drop();
            return;
        }
        orig_img = resizeImage(orig_img, &m_orig_size, &m_size);
        applyMask(orig_img);
        data = orig_img ? (uint8_t*)orig_img->lock() : NULL;
    }

    const unsigned int w = m_size.Width;
    const unsigned int h = m_size.Height;
    unsigned int format = m_single_channel ? GL_RED : GL_BGRA;
    unsigned int internal_format = m_single_channel ? GL_R8 : isSrgb() ?
        GL_SRGB8_ALPHA8 : GL_RGBA8;

    // GLES 2.0 specs doesn't allow GL_RGBA8 internal format
#if defined(USE_GLES2)
    if (!CVS->isGLSL())
    {
        internal_format = GL_RGBA;
    }
#endif

    formatConversion(data, &format, w, h);

    if (!no_upload)
    {
        const bool reload = m_texture_name != 0;
        if (!reload)
            glGenTextures(1, &m_texture_name);

        glBindTexture(GL_TEXTURE_2D, m_texture_name);
        if (!reload)
        {
            if (m_single_channel)
            {
                glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_ONE);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_ONE);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_ONE);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_RED);
            }
            glTexImage2D(GL_TEXTURE_2D, 0, internal_format, w, h, 0, format,
                GL_UNSIGNED_BYTE, data);
        }
        else
        {
            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, format,
                GL_UNSIGNED_BYTE, data);
        }
        if (orig_img)
            orig_img->unlock();
        if (hasMipMaps())
            glGenerateMipmap(GL_TEXTURE_2D);
    }

    m_texture_size = w * h * (m_single_channel ? 1 : 4);
    if (no_upload)
        m_texture_image = orig_img;
    else if (orig_img)
        orig_img->drop();
    else
        delete[] data;

    if (!no_upload)
        glBindTexture(GL_TEXTURE_2D, 0);

#endif   // !SERVER_ONLY
}   // reload
Example #6
0
/**
 * gdk_cairo_draw_from_gl:
 * @cr: a cairo context
 * @window: The window we're rendering for (not necessarily into)
 * @source: The GL ID of the source buffer
 * @source_type: The type of the @source
 * @buffer_scale: The scale-factor that the @source buffer is allocated for
 * @x: The source x position in @source to start copying from in GL coordinates
 * @y: The source y position in @source to start copying from in GL coordinates
 * @width: The width of the region to draw
 * @height: The height of the region to draw
 *
 * This is the main way to draw GL content in GTK+. It takes a render buffer ID
 * (@source_type == #GL_RENDERBUFFER) or a texture id (@source_type == #GL_TEXTURE)
 * and draws it onto @cr with an OVER operation, respecting the current clip.
 * The top left corner of the rectangle specified by @x, @y, @width and @height
 * will be drawn at the current (0,0) position of the cairo_t.
 *
 * This will work for *all* cairo_t, as long as @window is realized, but the
 * fallback implementation that reads back the pixels from the buffer may be
 * used in the general case. In the case of direct drawing to a window with
 * no special effects applied to @cr it will however use a more efficient
 * approach.
 *
 * For #GL_RENDERBUFFER the code will always fall back to software for buffers
 * with alpha components, so make sure you use #GL_TEXTURE if using alpha.
 *
 * Calling this may change the current GL context.
 *
 * Since: 3.16
 */
void
gdk_cairo_draw_from_gl (cairo_t              *cr,
                        GdkWindow            *window,
                        int                   source,
                        int                   source_type,
                        int                   buffer_scale,
                        int                   x,
                        int                   y,
                        int                   width,
                        int                   height)
{
    GdkGLContext *paint_context;
    cairo_surface_t *image;
    cairo_matrix_t matrix;
    int dx, dy, window_scale;
    gboolean trivial_transform;
    cairo_surface_t *group_target;
    GdkWindow *direct_window, *impl_window;
    guint framebuffer;
    int alpha_size = 0;
    cairo_region_t *clip_region;
    GdkGLContextPaintData *paint_data;

    impl_window = window->impl_window;

    window_scale = gdk_window_get_scale_factor (impl_window);

    paint_context = gdk_window_get_paint_gl_context (window, NULL);
    if (paint_context == NULL)
    {
        g_warning ("gdk_cairo_draw_gl_render_buffer failed - no paint context");
        return;
    }

    clip_region = gdk_cairo_region_from_clip (cr);

    gdk_gl_context_make_current (paint_context);
    paint_data = gdk_gl_context_get_paint_data (paint_context);

    if (paint_data->tmp_framebuffer == 0)
        glGenFramebuffersEXT (1, &paint_data->tmp_framebuffer);

    if (source_type == GL_RENDERBUFFER)
    {
        glBindRenderbuffer (GL_RENDERBUFFER, source);
        glGetRenderbufferParameteriv (GL_RENDERBUFFER, GL_RENDERBUFFER_ALPHA_SIZE,  &alpha_size);
    }
    else if (source_type == GL_TEXTURE)
    {
        glBindTexture (GL_TEXTURE_2D, source);

        glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_ALPHA_SIZE,  &alpha_size);
    }
    else
    {
        g_warning ("Unsupported gl source type %d\n", source_type);
        return;
    }

    group_target = cairo_get_group_target (cr);
    direct_window = cairo_surface_get_user_data (group_target, &direct_key);

    cairo_get_matrix (cr, &matrix);

    dx = matrix.x0;
    dy = matrix.y0;

    /* Trivial == integer-only translation */
    trivial_transform =
        (double)dx == matrix.x0 && (double)dy == matrix.y0 &&
        matrix.xx == 1.0 && matrix.xy == 0.0 &&
        matrix.yx == 0.0 && matrix.yy == 1.0;

    /* For direct paint of non-alpha renderbuffer, we can
       just do a bitblit */
    if ((_gdk_gl_flags & GDK_GL_SOFTWARE_DRAW_GL) == 0 &&
            source_type == GL_RENDERBUFFER &&
            alpha_size == 0 &&
            direct_window != NULL &&
            direct_window->current_paint.use_gl &&
            trivial_transform &&
            clip_region != NULL)
    {
        int unscaled_window_height;
        int i;

        /* Create a framebuffer with the source renderbuffer and
           make it the current target for reads */
        framebuffer = paint_data->tmp_framebuffer;
        glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, framebuffer);
        glFramebufferRenderbufferEXT (GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                                      GL_RENDERBUFFER_EXT, source);
        glBindFramebufferEXT (GL_DRAW_FRAMEBUFFER_EXT, 0);

        /* Translate to impl coords */
        cairo_region_translate (clip_region, dx, dy);

        glEnable (GL_SCISSOR_TEST);

        gdk_window_get_unscaled_size (impl_window, NULL, &unscaled_window_height);
        glDrawBuffer (GL_BACK);

#define FLIP_Y(_y) (unscaled_window_height - (_y))

        for (i = 0; i < cairo_region_num_rectangles (clip_region); i++)
        {
            cairo_rectangle_int_t clip_rect, dest;

            cairo_region_get_rectangle (clip_region, i, &clip_rect);
            clip_rect.x *= window_scale;
            clip_rect.y *= window_scale;
            clip_rect.width *= window_scale;
            clip_rect.height *= window_scale;

            glScissor (clip_rect.x, FLIP_Y (clip_rect.y + clip_rect.height),
                       clip_rect.width, clip_rect.height);

            dest.x = dx * window_scale;
            dest.y = dy * window_scale;
            dest.width = width * window_scale / buffer_scale;
            dest.height = height * window_scale / buffer_scale;

            if (gdk_rectangle_intersect (&clip_rect, &dest, &dest))
            {
                int clipped_src_x = x + (dest.x - dx * window_scale);
                int clipped_src_y = y + (height - dest.height - (dest.y - dy * window_scale));
                glBlitFramebufferEXT(clipped_src_x, clipped_src_y,
                                     (clipped_src_x + dest.width), (clipped_src_y + dest.height),
                                     dest.x, FLIP_Y(dest.y + dest.height),
                                     dest.x + dest.width, FLIP_Y(dest.y),
                                     GL_COLOR_BUFFER_BIT, GL_NEAREST);
                if (impl_window->current_paint.flushed_region)
                {
                    cairo_rectangle_int_t flushed_rect;

                    flushed_rect.x = dest.x / window_scale;
                    flushed_rect.y = dest.y / window_scale;
                    flushed_rect.width = (dest.x + dest.width + window_scale - 1) / window_scale - flushed_rect.x;
                    flushed_rect.height = (dest.y + dest.height + window_scale - 1) / window_scale - flushed_rect.y;

                    cairo_region_union_rectangle (impl_window->current_paint.flushed_region,
                                                  &flushed_rect);
                    cairo_region_subtract_rectangle (impl_window->current_paint.need_blend_region,
                                                     &flushed_rect);
                }
            }
        }

        glDisable (GL_SCISSOR_TEST);

        glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, 0);

#undef FLIP_Y

    }
    /* For direct paint of alpha or non-alpha textures we can use texturing */
    else if ((_gdk_gl_flags & GDK_GL_SOFTWARE_DRAW_GL) == 0 &&
             source_type == GL_TEXTURE &&
             direct_window != NULL &&
             direct_window->current_paint.use_gl &&
             trivial_transform &&
             clip_region != NULL)
    {
        int unscaled_window_height;
        GLint texture_width;
        GLint texture_height;
        int i, n_rects, n_quads;
        GdkTexturedQuad *quads;
        cairo_rectangle_int_t clip_rect;

        /* Translate to impl coords */
        cairo_region_translate (clip_region, dx, dy);

        if (alpha_size != 0)
        {
            cairo_region_t *opaque_region, *blend_region;

            opaque_region = cairo_region_copy (clip_region);
            cairo_region_subtract (opaque_region, impl_window->current_paint.flushed_region);
            cairo_region_subtract (opaque_region, impl_window->current_paint.need_blend_region);

            if (!cairo_region_is_empty (opaque_region))
                gdk_gl_texture_from_surface (impl_window->current_paint.surface,
                                             opaque_region);

            blend_region = cairo_region_copy (clip_region);
            cairo_region_intersect (blend_region, impl_window->current_paint.need_blend_region);

            glEnable (GL_BLEND);
            if (!cairo_region_is_empty (blend_region))
                gdk_gl_texture_from_surface (impl_window->current_paint.surface,
                                             blend_region);

            cairo_region_destroy (opaque_region);
            cairo_region_destroy (blend_region);
        }

        glBindTexture (GL_TEXTURE_2D, source);

        glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH,  &texture_width);
        glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT,  &texture_height);

        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        glEnable (GL_SCISSOR_TEST);

        gdk_window_get_unscaled_size (impl_window, NULL, &unscaled_window_height);

#define FLIP_Y(_y) (unscaled_window_height - (_y))

        cairo_region_get_extents (clip_region, &clip_rect);

        glScissor (clip_rect.x * window_scale, FLIP_Y ((clip_rect.y + clip_rect.height) * window_scale),
                   clip_rect.width * window_scale, clip_rect.height * window_scale);

        n_quads = 0;
        n_rects = cairo_region_num_rectangles (clip_region);
        quads = g_new (GdkTexturedQuad, n_rects);
        for (i = 0; i < n_rects; i++)
        {
            cairo_rectangle_int_t dest;

            cairo_region_get_rectangle (clip_region, i, &clip_rect);

            clip_rect.x *= window_scale;
            clip_rect.y *= window_scale;
            clip_rect.width *= window_scale;
            clip_rect.height *= window_scale;

            dest.x = dx * window_scale;
            dest.y = dy * window_scale;
            dest.width = width * window_scale / buffer_scale;
            dest.height = height * window_scale / buffer_scale;

            if (gdk_rectangle_intersect (&clip_rect, &dest, &dest))
            {
                int clipped_src_x = x + (dest.x - dx * window_scale);
                int clipped_src_y = y + (height - dest.height - (dest.y - dy * window_scale));
                GdkTexturedQuad quad = {
                    dest.x, FLIP_Y(dest.y),
                    dest.x + dest.width, FLIP_Y(dest.y + dest.height),
                    clipped_src_x / (float)texture_width, (clipped_src_y + dest.height) / (float)texture_height,
                    (clipped_src_x + dest.width) / (float)texture_width, clipped_src_y / (float)texture_height,
                };

                quads[n_quads++] = quad;

                if (impl_window->current_paint.flushed_region)
                {
                    cairo_rectangle_int_t flushed_rect;

                    flushed_rect.x = dest.x / window_scale;
                    flushed_rect.y = dest.y / window_scale;
                    flushed_rect.width = (dest.x + dest.width + window_scale - 1) / window_scale - flushed_rect.x;
                    flushed_rect.height = (dest.y + dest.height + window_scale - 1) / window_scale - flushed_rect.y;

                    cairo_region_union_rectangle (impl_window->current_paint.flushed_region,
                                                  &flushed_rect);
                    cairo_region_subtract_rectangle (impl_window->current_paint.need_blend_region,
                                                     &flushed_rect);
                }
            }
        }

        if (n_quads > 0)
            gdk_gl_texture_quads (paint_context, GL_TEXTURE_2D, n_quads, quads);

        g_free (quads);

        if (alpha_size != 0)
            glDisable (GL_BLEND);

#undef FLIP_Y

    }
    else
    {
        /* Software fallback */

        /* TODO: avoid reading back non-required data due to dest clip */
        image = cairo_surface_create_similar_image (cairo_get_target (cr),
                (alpha_size == 0) ? CAIRO_FORMAT_RGB24 : CAIRO_FORMAT_ARGB32,
                width, height);

        cairo_surface_set_device_scale (image, buffer_scale, buffer_scale);

        framebuffer = paint_data->tmp_framebuffer;
        glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, framebuffer);

        if (source_type == GL_RENDERBUFFER)
        {
            /* Create a framebuffer with the source renderbuffer and
               make it the current target for reads */
            glFramebufferRenderbufferEXT (GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                                          GL_RENDERBUFFER_EXT, source);
        }
        else
        {
            glFramebufferTexture2DEXT (GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                                       GL_TEXTURE_2D, source, 0);
        }

        glPixelStorei (GL_PACK_ALIGNMENT, 4);
        glPixelStorei (GL_PACK_ROW_LENGTH, cairo_image_surface_get_stride (image) / 4);

        glReadPixels (x, y, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV,
                      cairo_image_surface_get_data (image));

        glPixelStorei (GL_PACK_ROW_LENGTH, 0);

        glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, 0);

        cairo_surface_mark_dirty (image);

        /* Invert due to opengl having different origin */
        cairo_scale (cr, 1, -1);
        cairo_translate (cr, 0, -height / buffer_scale);

        cairo_set_source_surface (cr, image, 0, 0);
        cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
        cairo_paint (cr);

        cairo_surface_destroy (image);
    }

    if (clip_region)
        cairo_region_destroy (clip_region);

}
Example #7
0
int GetCacheMesTextureID( char *msg, int font_size, int font_style )
{
	//		キャッシュ済みのテクスチャIDを返す(OpenGLテクスチャIDを返す)
	//		(作成されていないメッセージテクスチャは自動的に作成する)
	//		(作成の必要がない場合は-1を返す)
	//
	GLuint id;
	int texid;
	int tsx,tsy;
	unsigned char *pImg;

	TEXINF *t;
	int mylen;
	short mycache;
	
	mycache = str2hash( msg, &mylen );			// キャッシュを取得
	if ( mylen <= 0 ) return -1;

	texid = getCache( msg, mycache, font_size, font_style );
	if ( texid >= 0 ) {
		return texid;							// キャッシュがあった
	}

	//		キャッシュが存在しないので作成
	pImg = (unsigned char *)j_callFontBitmap( msg, font_size, font_style, &tsx, &tsy );
	texid = MakeEmptyTex( tsx, tsy );
	if ( texid < 0 ) return -1;

	t = GetTex( texid );
	t->hash = mycache;
	t->font_size = font_size;
	t->font_style = font_style;

	if ( curmestex >= GetSysReq(SYSREQ_MESCACHE_MAX) ) {	// エントリ数がオーバーしているものは次のフレームで破棄
		t->life = 0;
		t->buf[0] = 0;
	} else {
		//		キャッシュの登録
		if ( mylen >= ( TEXMES_NAME_BUFFER - 1 ) ) {
			t->text = (char *)malloc( mylen+1 );		// テキストハッシュネーム用バッファを作成する
			strcpy( t->text, msg );
		} else {
			strcpy( t->buf, msg );						// 標準バッファにコピーする
		}
	}

	id = (GLuint)t->texid;

	glBindTexture( GL_TEXTURE_2D, id );
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
	glPixelStorei( GL_UNPACK_ALIGNMENT, 1);

	glTexSubImage2D(
		GL_TEXTURE_2D,
		0,
		(GLint)0,
		(GLint)0,
		(GLsizei)tsx,
		(GLsizei)tsy,
		GL_ALPHA,
		GL_UNSIGNED_BYTE,
		pImg
	);

	glBindTexture(GL_TEXTURE_2D, 0);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	free(pImg);

	return texid;
}
Example #8
0
void init(int argc, char *argv[]) {
    unsigned *image;
    int i, width, height, components;
    GLfloat pos[] = { 0.f, 1.f, 1.f, 0.f};

    glEnable(GL_TEXTURE_2D);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    for(i = 0; i < argc; i++) {
	image = read_texture(argv[i], &width, &height, &components);
	if (image == NULL) {
	    fprintf(stderr, "Error: Can't load image file \"%s\".\n",
		    argv[i]);
	    exit(EXIT_FAILURE);
	} else {
	    printf("%d x %d image loaded\n", width, height);
	}
	glBindTexture(GL_TEXTURE_2D, i+1);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexImage2D(GL_TEXTURE_2D, 0, components, width,
                 height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
	texture_count++;
    }

    glBindTexture(GL_TEXTURE_2D, 1+texture_count);
    image = read_texture("../data/smoke.bw", &width, &height, &components);
    if (image == NULL) {
	fprintf(stderr, "Error: Can't load image file \"%s\".\n", "smoke.la");
	exit(EXIT_FAILURE);
    }
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexImage2D(GL_TEXTURE_2D, 0, components, width,
	     height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
    smoke = new_smoke(0.f, 0.f, 0.f, .0f, 2.5f, 0.f, 25, .4f, 1+texture_count);

    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    glEnable(GL_TEXTURE_2D);
    glClearColor(.25f, .25f, .25f, .25f);

    glLightfv(GL_LIGHT0, GL_POSITION, pos);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50.,1.,.1,20.);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.,0.,-5.5);
    glClearColor(.25f, .25f, .75f, .25f);

    glAlphaFunc(GL_GREATER, 0.016f);
    glEnable(GL_ALPHA_TEST);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHT0);
    glEnable(GL_NORMALIZE);
}
Example #9
0
/*
	Функция	: nglInit

	Описание: Инициализация графического движка

	История	: 05.08.12	Создан

*/
N_API bool N_APIENTRY_EXPORT nglInit(void)
{
	wchar_t *tempt = 0, *_tempt = 0;

	if(ngl_isinit || !ngl_ea) return false;

	ngl_ea->nlPrint(F_NGLINIT); ngl_ea->nlAddTab(1);

	ngl_totalglerrors = 0;

	if(!nglInitWindow()) {
		ngl_ea->nlAddTab(-1); ngl_ea->nlPrint(LOG_FDEBUGFORMAT, F_NGLINIT, N_FALSE);
		return false;
	}

	//Далее вывод информации об OpenGL
	tempt = ngl_ea->nAllocMemory(sizeof(wchar_t)*(strlen((char*)glGetString(GL_RENDERER))+1));
	if(tempt) {
		mbstowcsl(tempt,(char*)glGetString(GL_RENDERER),strlen((char*)glGetString(GL_RENDERER))+1);
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,L"GL_RENDERER",tempt);
	}

	_tempt = ngl_ea->nReallocMemory(tempt,sizeof(wchar_t)*(strlen((char*)glGetString(GL_VENDOR))+1));
	if(_tempt) {
		tempt = _tempt;
		mbstowcsl(tempt,(char*)glGetString(GL_VENDOR),strlen((char*)glGetString(GL_VENDOR))+1);
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,L"GL_VENDOR",tempt);
	}

	_tempt = ngl_ea->nReallocMemory(tempt,sizeof(wchar_t)*(strlen((char*)glGetString(GL_VERSION))+1));
	if(_tempt) {
		tempt = _tempt;
		mbstowcsl(tempt,(char*)glGetString(GL_VERSION),strlen((char*)glGetString(GL_VERSION))+1);
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,L"GL_VERSION",tempt);
	}

	_tempt = ngl_ea->nReallocMemory(tempt,sizeof(wchar_t)*(strlen((char*)glGetString(GL_EXTENSIONS))+1));
	if(_tempt) {
		tempt = _tempt;
		mbstowcsl(tempt,(char*)glGetString(GL_EXTENSIONS),strlen((char*)glGetString(GL_EXTENSIONS))+1);
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,L"GL_EXTENSIONS",tempt);
	}
	if(tempt)
		ngl_ea->nFreeMemory(tempt);

	// Получение максимального размера стороны текстуры
	glGetIntegerv(GL_MAX_TEXTURE_SIZE,(int *)(&ngl_tex_maxsize));
	ngl_ea->nlPrint(LOG_FDEBUGFORMAT3,F_NGLINIT,NGL_MAXTEXSIZE,ngl_tex_maxsize);

	// Определение угла анизотропии
	if(strstr((char*)glGetString(GL_EXTENSIONS),"GL_EXT_texture_filter_anisotropic"))
		glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT,&ngl_tex_maxanis);
	else
		ngl_tex_maxanis = 0;
	ngl_ea->nlPrint(LOG_FDEBUGFORMAT3,F_NGLINIT,NGL_MAXANISOTROPY,ngl_tex_maxanis);
	if(ngl_tex_anis > ngl_tex_maxanis) ngl_tex_anis = ngl_tex_maxanis;
	ngl_ea->nlPrint(LOG_FDEBUGFORMAT3,F_NGLINIT,NGL_DEFAULTANISOTROPY,ngl_tex_anis);

	// Поддержка npot текстур
	if(strstr((char*)glGetString(GL_EXTENSIONS),"GL_ARB_texture_non_power_of_two" ))
		ngl_tex_s_npot = true;
	else
		ngl_tex_s_npot = false;
	ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,NGL_SUPPORTNPOT,ngl_tex_s_npot?N_YES:N_NO);

	// Поддержка BGRA текстур
	// TODO: найти инфу по экстеншену GL_EXT_texture_format_BGRA8888
	if(strstr((char*)glGetString(GL_EXTENSIONS),"GL_EXT_bgra"))
		ngl_tex_s_bgra_ext = true;
	else
		ngl_tex_s_bgra_ext = false;
	ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,NGL_SUPPORTBGRA,ngl_tex_s_bgra_ext?N_YES:N_NO);

	// Поддержка ABGR текстур
	if(strstr((char*)glGetString(GL_EXTENSIONS),"GL_EXT_abgr"))
		ngl_tex_s_abgr_ext = true;
	else
		ngl_tex_s_abgr_ext = false;
	if(strstr((char*)glGetString(GL_RENDERER),"DeltaChrome")) {
		ngl_tex_s_abgr_ext = false;
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,NGL_SUPPORTABGR,N_BROKEN);
	} else
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,NGL_SUPPORTABGR,ngl_tex_s_abgr_ext?N_YES:N_NO);

	// Поддержка CMYKA текстур
	if(strstr((char*)glGetString(GL_EXTENSIONS),"GL_EXT_cmyka"))
		ngl_tex_s_cmyka_ext = true;
	else
		ngl_tex_s_cmyka_ext = false;
	ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,NGL_SUPPORTCMYKA,ngl_tex_s_cmyka_ext?N_YES:N_NO);

	// Поддержка GL_EXT_packed_pixels
	if(strstr((char*)glGetString(GL_EXTENSIONS), "GL_EXT_packed_pixels"))
		ngl_tex_s_packed_pixels = true;
	else
		ngl_tex_s_packed_pixels = false;
	ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,NGL_SUPPORTPP,ngl_tex_s_packed_pixels?N_YES:N_NO);

	if(strstr((char*)glGetString(GL_EXTENSIONS), "GL_EXT_texture_edge_clamp") ||
		strstr((char*)glGetString(GL_EXTENSIONS), "GL_SGIS_texture_edge_clamp")) {
		ngl_win_texture_edge_clamp = true;
	} else {
		ngl_win_texture_edge_clamp = false;
	}
	ngl_ea->nlPrint(LOG_FDEBUGFORMAT2, F_NGLINIT, NGL_SUPPORTTEXTUREEDGECLAMP, ngl_win_texture_edge_clamp?N_YES:N_NO);

	if(strstr((char*)glGetString(GL_EXTENSIONS), "GL_ARB_vertex_program")) {
		ngl_win_vertexprogram_ext = true;
		glProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC)nglGetProcAddress("glProgramStringARB");
		glBindProgramARB = (PFNGLBINDPROGRAMARBPROC)nglGetProcAddress("glBindProgramARB");
		glDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC)nglGetProcAddress("glDeleteProgramsARB");
		glGenProgramsARB = (PFNGLGENPROGRAMSARBPROC)nglGetProcAddress("glGenProgramsARB");
		glGetProgramivARB = (PFNGLGETPROGRAMIVARBPROC)nglGetProcAddress("glGetProgramivARB");
		glProgramLocalParameter4fARB = (PFNGLPROGRAMLOCALPARAMETER4FARBPROC)nglGetProcAddress("glProgramLocalParameter4fARB");
		glGetIntegerv(GL_MAX_VERTEX_ATTRIBS_ARB,&ngl_win_maxvertexattribs);
		glGetProgramivARB(GL_VERTEX_PROGRAM_ARB,GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB,&ngl_win_maxprogramlocalparams);
		glGetProgramivARB(GL_VERTEX_PROGRAM_ARB,GL_MAX_PROGRAM_ENV_PARAMETERS_ARB,&ngl_win_maxprogramenvparams);
		glGetIntegerv(GL_MAX_PROGRAM_MATRICES_ARB,&ngl_win_maxprogrammatrices);
		glGetProgramivARB(GL_VERTEX_PROGRAM_ARB,GL_MAX_PROGRAM_TEMPORARIES_ARB,&ngl_win_maxprogramtemporaries);
		glGetProgramivARB(GL_VERTEX_PROGRAM_ARB,GL_MAX_PROGRAM_PARAMETERS_ARB,&ngl_win_maxprogramparams);
		glGetProgramivARB(GL_VERTEX_PROGRAM_ARB,GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB,&ngl_win_maxprogramaddressregs);
	} else
		ngl_win_vertexprogram_ext = false;
	ngl_ea->nlPrint(LOG_FDEBUGFORMAT2,F_NGLINIT,NGL_SUPPORTVERTEXPROGRAM,ngl_win_vertexprogram_ext?N_YES:N_NO);
	if(ngl_win_vertexprogram_ext) {
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT3,F_NGLINIT,NGL_MAXVERTEXATTRIBS,ngl_win_maxvertexattribs);
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT3,F_NGLINIT,NGL_MAXPROGRAMLOCALPARAMS,ngl_win_maxprogramlocalparams);
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT3,F_NGLINIT,NGL_MAXPROGRAMENVPARAMS,ngl_win_maxprogramenvparams);
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT3,F_NGLINIT,NGL_MAXPROGRAMMATRICES,ngl_win_maxprogrammatrices);
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT3,F_NGLINIT,NGL_MAXPROGRAMTEMPORARIES,ngl_win_maxprogramtemporaries);
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT3,F_NGLINIT,NGL_MAXPROGRAMPARAMS,ngl_win_maxprogramparams);
		ngl_ea->nlPrint(LOG_FDEBUGFORMAT3,F_NGLINIT,NGL_MAXPROGRAMADDRESSREGS,ngl_win_maxprogramaddressregs);
	}

	ngl_isinit = true;

	// Настройка OpenGL
	glViewport(0, 0, ngl_winx, ngl_winy);
	
	glDisable(GL_TEXTURE_2D);
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
	glShadeModel(GL_SMOOTH);
	glDepthFunc(GL_LEQUAL);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);
	ngl_glrowalignment = 4;
	glPixelStorei(GL_UNPACK_ALIGNMENT,ngl_glrowalignment);
	glPixelStorei(GL_PACK_ALIGNMENT,ngl_glrowalignment);
	glCullFace(GL_FRONT);
	glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);

	glClearDepth(1.0);
	glClearColor(ngl_winbcred, ngl_winbcgreen, ngl_winbcblue, 0.0f);

	if(!nglBatchInit()) {
		nglCloseWindow();
		ngl_isinit = false;
		ngl_ea->nlAddTab(-1); ngl_ea->nlPrint(LOG_FDEBUGFORMAT, F_NGLINIT, N_OK);
		return false;
	}

	nglUpdateClippingRegion();

	ngl_win_exitmsg = false;

	nglCatchOpenGLError(F_NGLINIT);

	ngl_ea->nlAddTab(-1); ngl_ea->nlPrint(LOG_FDEBUGFORMAT, F_NGLINIT, N_OK);

	return true;
}
Example #10
0
enum piglit_result
piglit_display(void)
{
	GLuint tex;
	static const float red[] = { 1, 0, 0, 1 };
	static const float green[] = { 0, 1, 0, 1 };
	static const float blue[] = { 0, 0, 1, 1 };
	static const float cyan[] = { 0, 1, 1, 1 };

	pass = GL_TRUE;

	extension_supported =
		piglit_is_extension_supported("GL_EXT_unpack_subimage");

	if (!piglit_automatic) {
		if (extension_supported)
			printf("GL_EXT_unpack_subimage is supported\n");
		else
			printf("GL_EXT_unpack_subimage is not supported\n");
	}

	piglit_reset_gl_error();
	if (!piglit_automatic)
		printf("Trying GL_UNPACK_ROW_LENGTH\n");
	glPixelStorei(GL_UNPACK_ROW_LENGTH, 2);
	check_error();

	piglit_reset_gl_error();
	if (!piglit_automatic)
		printf("Trying GL_UNPACK_SKIP_PIXELS\n");
	glPixelStorei(GL_UNPACK_SKIP_PIXELS, 1);
	check_error();

	piglit_reset_gl_error();
	if (!piglit_automatic)
		printf("Trying GL_UNPACK_SKIP_ROWS\n");
	glPixelStorei(GL_UNPACK_SKIP_ROWS, 4);
	check_error();

	glClear(GL_COLOR_BUFFER_BIT);

	/* Try creating a texture with the unpacking parameters we've set */
	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);
	glTexImage2D(GL_TEXTURE_2D,
		     0, /* level */
		     GL_RGBA, /* internalFormat */
		     1, /* width */
		     2, /* height */
		     0, /* border */
		     GL_RGBA, /* format */
		     GL_UNSIGNED_BYTE, /* type */
		     tex_data);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

	make_program(vertex_shader, fragment_shader);

	piglit_draw_rect_tex(-1, -1, 2, 2,
			     0, 0, 1, 1);

	if (extension_supported) {
		pass &= piglit_probe_pixel_rgba(piglit_width / 2,
						piglit_height / 4,
						blue);
		pass &= piglit_probe_pixel_rgba(piglit_width / 2,
						piglit_height * 3 / 4,
						cyan);
	} else {
		pass &= piglit_probe_pixel_rgba(piglit_width / 2,
						piglit_height / 4,
						red);
		pass &= piglit_probe_pixel_rgba(piglit_width / 2,
						piglit_height * 3 / 4,
						green);
	}

	return pass ? PIGLIT_PASS : PIGLIT_FAIL;
}
Example #11
0
void captureBlurScreen(const std::function<void(bool,  Dialog*&)>& afterCaptured, Dialog* layer)
{
    static bool startedCapture = false;
    
    if (startedCapture)
    {
        CCLOG("Screen capture is already working");
        if (afterCaptured)
        {
            afterCaptured(false, layer);
        }
        return;
    }
    else
    {
        startedCapture = true;
    }
    
    cocos2d::Size s = cocos2d::Director::getInstance()->getWinSize();
    auto glView = Director::getInstance()->getOpenGLView();
    auto frameSize = glView->getFrameSize();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
    frameSize = frameSize * glView->getFrameZoomFactor() * glView->getRetinaFactor();
#endif
    
    int width = static_cast<int>(frameSize.width);
    int height = static_cast<int>(frameSize.height);
    //    double ct1 ,ct2 ;
    //    ct1 = ct2 = AbsoluteTimeGetCurrent();
    bool succeed = false;
    int scale = 4;
    int dst_width = width / scale;
    int dst_height = height / scale;
    do
    {
        std::shared_ptr<GLubyte> buffer(new GLubyte[width * height * 4], [](GLubyte* p){ CC_SAFE_DELETE_ARRAY(p); });
        if (!buffer)
        {
            break;
        }
        
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer.get());
        //        CCLOG("First read %f", (ct2 = AbsoluteTimeGetCurrent()) - ct1); ct1 = ct2;
        std::shared_ptr<GLubyte> flippedBuffer(new GLubyte[(int)ceil(width / (float)scale) * (int)ceil(height/(float)scale) * 4 ], [](GLubyte* p) { CC_SAFE_DELETE_ARRAY(p); });
        if (!flippedBuffer)
        {
            break;
        }
        
        HaypiFrameworkCPP::HaypiData::Gossip_blur(buffer, flippedBuffer, width, height, 4, 2, scale, true);
//        SpriteBlur::Gossip_blur(buffer, flippedBuffer, width, height, 4, 2, scale, true);
        
        Image* image = new (std::nothrow) Image;
        if (image)
        {
            image->initWithRawData(flippedBuffer.get(), dst_width * dst_height * 4, dst_width, dst_height, 8);
            
            Texture2D* text = new Texture2D();
            text->initWithImage(image);
            startedCapture = false;
            
            auto blur = new Sprite();
            blur->initWithTexture(text, cocos2d::Rect(0,0,dst_width,dst_height));
            blur->setPosition(s/2);
            blur->setAnchorPoint(cocos2d::Vec2(0.5,0.5));
            
            blur->setScale(s.height / dst_height);
            layer->addChild(blur, -99999);
            auto layerBk = LayerColor::create(Color4B::WHITE);
            layer->addChild(layerBk, -100000);
            blur->autorelease();
            text->autorelease();
            delete image;
            
        }
        else
        {
            CCLOG("Malloc Image memory failed!");
            if (afterCaptured)
            {
                afterCaptured(succeed, layer);
            }
            startedCapture = false;
        }
    } while (0);
}
Example #12
0
// todo: lightmap support for PSP and ES
bool Texture::loadMipmap(std::string strFn)
{
	bool isJpgTexture = false;

	if(	strncmp((strFn.c_str()+strFn.length()-3), "JPG", 3)==0 ||
	   strncmp((strFn.c_str()+strFn.length()-3), "jpg", 3)==0)
		isJpgTexture = true;
	
	//if a jpg texture, need to set UNPACK_ALIGNMENT to 1
		
	if (img.Load((char *)strFn.c_str()))
	{
		generate();
		glEnable(GL_TEXTURE_2D);
		
#ifdef OPENGL_ES
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		
#else
		//Set Parameters
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
#endif

#ifndef ARCH_DC
		if(isJpgTexture)
			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
#endif

#ifdef OPENGL_ES
		//Create texture
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.width, img.height, 0, img.format, GL_UNSIGNED_BYTE, img.data);	
#else
		gluBuild2DMipmaps(	GL_TEXTURE_2D, GL_RGBA8, img.width, img.height,
						  img.format, GL_UNSIGNED_BYTE, img.data);
#endif
		
#ifndef ARCH_DC
		glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
#endif
		return true;
	}
	else
	{
		return false;
	}
	//	char c = toupper(strFn[strFn.length()-3]);
	//			
	//	if (c == 'T')
	//	{
	//		load(strFn,FORMAT_TGA);
	//	}
	//	else 
	//	if (c == 'P')
	//	{
	//		load(strFn,FORMAT_PNG);
	//	}
}
Example #13
0
bool Texture::load(std::string strFn)
{
	setId(strFn);
	//Create texture
	//		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.width, img.height, 0, img.format, GL_UNSIGNED_BYTE, img.data);	
#ifdef ARCH_PSP
	const char *filename = strFn.c_str();
	
	int filenameLength=strlen(filename);
   
	if(	strncmp((filename+filenameLength-3), "TGA", 3)==0 ||
	   strncmp((filename+filenameLength-3), "tga", 3)==0)
		{
   			Logger::log("[Texture:%s] Loading....",strFn.c_str());
   
   			if( !psp_texture.LoadTGA((char *)strFn.c_str()) )
   			{
   				Logger::log(LOG_ERROR,"failed!\n");
   				//sceKernelExitGame();
				return false;
   			}
   			else
   			{
   				Logger::log("ok.");
				return true;
   			}
   			psp_texture.Swizzle();
   			Logger::log("\n");
	}

#else
	bool isJpgTexture = false;
	
	if(	strncmp((strFn.c_str()+strFn.length()-3), "JPG", 3)==0 ||
	   strncmp((strFn.c_str()+strFn.length()-3), "jpg", 3)==0)
		isJpgTexture = true;

	bool imgLoaded = false;
		
#ifdef ARCH_DC

	const char *filename = strFn.c_str();
	
	int filenameLength=strlen(filename);
	
	if(	strncmp((filename+filenameLength-3), "PCX", 3)==0 ||
	   strncmp((filename+filenameLength-3), "pcx", 3)==0)
		{
			Logger::log("Loading PCX using dreamcast loader");
			generate();
			
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_FILTER, GL_FILTER_BILINEAR);
			loadtxr(filename, &glTexId);
			return true;
		}
	else if(	strncmp((filename+filenameLength-3), "PVR", 3)==0 ||
	   strncmp((filename+filenameLength-3), "pvr", 3)==0)
		{
			Logger::log("Loading PVR using dreamcast loader\n");
			generate();
			
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_FILTER, GL_FILTER_BILINEAR);
			loadpvr(filename, &glTexId);
			return true;
		}	
#endif
	
	imgLoaded = img.Load((char *)strFn.c_str());
	
	if (imgLoaded)
	{
		generate();
		glEnable(GL_TEXTURE_2D);

#ifdef OPENGL_ES
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
#endif
#ifdef ARCH_DC
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
#endif
		
#if !defined(ARCH_DC) && !defined(OPENGL_ES) && !defined(ARCH_PSP)
		glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
#endif

#ifndef ARCH_DC
		if(isJpgTexture)
			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
#endif

		format = img.format;
		alpha = (format==GL_RGBA)?true:false;
		
		glTexImage2D(GL_TEXTURE_2D, 0, img.format, img.width, img.height, 0, img.format, GL_UNSIGNED_BYTE, img.data);	

#ifndef ARCH_DC
		if(isJpgTexture)
			glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
#endif


		return true;
	}
	else
	{
		return false;
	}
#endif
//	char c = toupper(strFn[strFn.length()-3]);
//			
//	if (c == 'T')
//	{
//		load(strFn,FORMAT_TGA);
//	}
//	else 
//	if (c == 'P')
//	{
//		load(strFn,FORMAT_PNG);
//	}
}
Example #14
0
void
piglit_init(int argc, char **argv)
{
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
Example #15
0
bool CGLCG::LoadShader(const TCHAR *shaderFile)
{
	CCGShader cgShader;
	TCHAR shaderPath[MAX_PATH];
	TCHAR tempPath[MAX_PATH];
	CGprofile vertexProfile, fragmentProfile;
	GLenum error;

	if(!fboFunctionsLoaded) {
		MessageBox(NULL, TEXT("Your OpenGL graphics driver does not support framebuffer objects.\nYou will not be able to use CG shaders in OpenGL mode."), TEXT("CG Error"),
			MB_OK|MB_ICONEXCLAMATION);
        return false;
    }

	vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
	fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);

	cgGLDisableProfile(vertexProfile);
	cgGLDisableProfile(fragmentProfile);

	ClearPasses();

	if(prevTex) {
		glDeleteTextures(1,&prevTex);
		prevTex=0;
	}

	if (shaderFile == NULL || *shaderFile==TEXT('\0'))
		return true;

	lstrcpy(shaderPath,shaderFile);
	for(int i=lstrlen(shaderPath); i>=0; i--){
		if(IS_SLASH(shaderPath[i])){
			shaderPath[i]=TEXT('\0');
			break;
		}
	}

	SetCurrentDirectory(shaderPath);
	if(!cgShader.LoadShader(_tToChar(shaderFile)))
		return false;

	cgGLSetOptimalOptions(vertexProfile);
	cgGLSetOptimalOptions(fragmentProfile);

	/* insert dummy pass that will contain the original texture
	*/
	shaderPasses.push_back(shaderPass());

	for(CCGShader::passVector::iterator it=cgShader.shaderPasses.begin();
			it!=cgShader.shaderPasses.end();it++) {
		shaderPass pass;

		pass.scaleParams = it->scaleParams;
		/* if this is the last pass (the only one that can have CG_SCALE_NONE)
		   and no filter has been set use the GUI setting
		*/
		if(pass.scaleParams.scaleTypeX==CG_SCALE_NONE && !it->filterSet) {
			pass.linearFilter = GUI.BilinearFilter;
		} else {
			pass.linearFilter = it->linearFilter;
		}

		// paths in the meta file can be relative
		_tfullpath(tempPath,_tFromChar(it->cgShaderFile),MAX_PATH);
		char *fileContents = ReadShaderFileContents(tempPath);
		if(!fileContents)
			return false;

		pass.cgVertexProgram = cgCreateProgram( cgContext, CG_SOURCE, fileContents,
						vertexProfile, "main_vertex", NULL);

		checkForCgError("Compiling vertex program");

		pass.cgFragmentProgram = cgCreateProgram( cgContext, CG_SOURCE, fileContents,
							fragmentProfile, "main_fragment", NULL);

		checkForCgError("Compiling fragment program");

		delete [] fileContents;
		if(!pass.cgVertexProgram || !pass.cgFragmentProgram) {
			return false;
		}
		cgGLLoadProgram(pass.cgVertexProgram);
		cgGLLoadProgram(pass.cgFragmentProgram);

		/* generate framebuffer and texture for this pass and apply
		   default texture settings
		*/
		glGenFramebuffers(1,&pass.fbo);
		glGenTextures(1,&pass.tex);
		glBindTexture(GL_TEXTURE_2D,pass.tex);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

		shaderPasses.push_back(pass);
	}

	for(std::vector<CCGShader::lookupTexture>::iterator it=cgShader.lookupTextures.begin();it!=cgShader.lookupTextures.end();it++) {		
		lookupTexture tex;
		strcpy(tex.id,it->id);

		/* generate texture for the lut and apply specified filter setting
		*/
		glGenTextures(1,&tex.tex);
		glBindTexture(GL_TEXTURE_2D,tex.tex);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, it->linearfilter?GL_LINEAR:GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, it->linearfilter?GL_LINEAR:GL_NEAREST);

		_tfullpath(tempPath,_tFromChar(it->texturePath),MAX_PATH);

		// simple file extension png/tga decision
		int strLen = strlen(it->texturePath);
		if(strLen>4) {
			if(!strcasecmp(&it->texturePath[strLen-4],".png")) {
				int width, height;
				bool hasAlpha;
				GLubyte *texData;
				if(loadPngImage(tempPath,width,height,hasAlpha,&texData)) {
					glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
					glTexImage2D(GL_TEXTURE_2D, 0, hasAlpha ? 4 : 3, width,
						height, 0, hasAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, texData);
					free(texData);
				}
			} else if(!strcasecmp(&it->texturePath[strLen-4],".tga")) {
				STGA stga;
				if(loadTGA(tempPath,stga)) {
					glPixelStorei(GL_UNPACK_ROW_LENGTH, stga.width);
					glTexImage2D(GL_TEXTURE_2D, 0, 4, stga.width,
						stga.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, stga.data);
				}
			}
		}
		lookupTextures.push_back(tex);
	}

	/* enable texture unit 1 for the lookup textures
	*/
	glClientActiveTexture(GL_TEXTURE1);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glTexCoordPointer(2,GL_FLOAT,0,lut_coords);
	glClientActiveTexture(GL_TEXTURE0);

	/* generate a texture that we can swap with the original texture
	   and pass back to the main opengl code
	*/
	glGenTextures(1,&prevTex);
	glBindTexture(GL_TEXTURE_2D,prevTex);
	glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,512,512,0,GL_RGB,GL_UNSIGNED_SHORT_5_6_5,NULL);
	glBindTexture(GL_TEXTURE_2D,0);
	prevTexSize.x = prevTexSize.y = prevTexImageSize.x = prevTexImageSize.y = 0;
	memset(prevTexCoords,0,sizeof(prevTexCoords));

	shaderLoaded = true;
	
	return true;
}
Example #16
0
int make_texture(struct Picture * picturedata,int enable_mipmaping)
{

	if ( picturedata == 0 ) { fprintf(stderr,"Error making texture from picture , accomodation structure is not allocated\n");
	                          return 0; }

    unsigned long this_texture = picturedata->width * picturedata->height * /*RGBA ->*/ 4 /* <- RGBA*/ ;
    if ( !GPU_Memory_can_accomodate(this_texture) ) {
                                                      fprintf(stderr,"Abort making texture , GPU cant accomodate it ( %u KB ) \n",(unsigned int) this_texture/1024);
                                                      SignalGPUFull=1;
                                                      return 0;
                                                    }



    glEnable(GL_TEXTURE_2D);

     PrintDirectoryListItem(picturedata->directory_list_index);

     GLuint new_tex_id=0;
     if (PrintOpenGLDebugMsg()) fprintf(stderr,"OpenGL Generating new Texture \n");
     glGenTextures(1,&new_tex_id);
     if ( complain_about_errors() ) { return 0; }

     if (PrintOpenGLDebugMsg()) fprintf(stderr,"OpenGL Binding new Texture \n");
     glBindTexture(GL_TEXTURE_2D,new_tex_id);
     if ( complain_about_errors() ) { return 0; }
     glFlush();

    picturedata->gpu.gl_rgb_texture=new_tex_id;


    unsigned int depth_flag=GL_RGB;
    char * rgba_data = picturedata->system.rgb_data;

/* RGBA Software conversion for debugging :p   HAS ANOTHER PART (line 150+ ) THAT DOES THE FREE CALL
    rgba_data = (char*) malloc(picturedata->width*picturedata->height*4*sizeof(unsigned char));
    if (rgba_data==0)
      {
       rgba_data = picturedata->rgb_data;
      } else
      {
       depth_flag=GL_RGBA;
       software_add_alpha_channel(picturedata->rgb_data,rgba_data,picturedata->width,picturedata->height);
       fprintf(stderr,"Using Alpha texture conversion\n");
      }
*/
  unsigned int error_num=0;

  if ( ( enable_mipmaping == 1 ) || ( frame.force_mipmap_generation ==1 ) )
   {
      /* LOADING TEXTURE --WITH-- MIPMAPING */
      glPixelStorei(GL_UNPACK_ALIGNMENT,1);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
      glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);                      // GL_RGB
      glTexImage2D(GL_TEXTURE_2D, 0, depth_flag, picturedata->width , picturedata->height, 0, depth_flag, GL_UNSIGNED_BYTE, (const GLvoid *) rgba_data);
      error_num=glGetError();
      if  ( error_num!=0 ) { printoutOGLErr(error_num); fprintf(stderr,"Creating texture %ux%u:%u ( initial %ux%u )\n",picturedata->width,picturedata->height,depth_flag,picturedata->initial_width,picturedata->initial_height); return 0; }
   } else
   {
      /* LOADING TEXTURE --WITHOUT-- MIPMAPING - IT IS LOADED RAW*/
      glPixelStorei(GL_UNPACK_ALIGNMENT,1);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
      glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);                       //GL_RGB
      glTexImage2D(GL_TEXTURE_2D, 0, depth_flag, picturedata->width , picturedata->height, 0, depth_flag, GL_UNSIGNED_BYTE,(const GLvoid *) rgba_data);
      error_num=glGetError();
      if  ( error_num!=0 ) { printoutOGLErr(error_num); fprintf(stderr,"Creating texture %ux%u:%u ( initial %ux%u )\n",picturedata->width,picturedata->height,depth_flag,picturedata->initial_width,picturedata->initial_height); return 0; }
   }

/* RGBA Software conversion for debugging :p HAS A PREVIOUS PART
   if ( (rgba_data != 0)&&(depth_flag=GL_RGBA) )  { free(rgba_data); }
*/


   if (enable_mipmaping)
    {
     if (PrintDevMsg()) fprintf(stderr,"Using mipmaps there is a lot more memory consumption , needs work..\n");
    }





    /* PICTURE IS LOADED IN GPU SO WE CAN UNLOAD IT FROM MAIN RAM MEMORY */
      if ( picturedata->system.rgb_data != 0 )
        {
          frame.system.usedRAM-=picturedata->system.rgb_data_size;
          free(picturedata->system.rgb_data);
          picturedata->system.rgb_data=0;
          picturedata->system.rgb_data_size=0;
        }

    frame.gpu.lastTexture=this_texture;
    frame.gpu.usedRAM+=frame.gpu.lastTexture;

    picturedata->gpu.texture_data_size=this_texture;
    picturedata->gpu.marked_for_texture_loading=0;
    picturedata->gpu.texture_loaded=1;

    if ( complain_about_errors() ) { return 0; }

    if (PrintOpenGLDebugMsg()) fprintf(stderr,"OpenGL Texture of size ( %u %u ) id is %u\n", picturedata->width , picturedata->height,picturedata->gpu.gl_rgb_texture);

    glFlush();

         SoundLibrary_PlaySound(LOADED_PICTURE);
    return 1;
}
Example #17
0
void CGLCG::Render(GLuint &origTex, xySize textureSize, xySize inputSize, xySize viewportSize, xySize windowSize)
{
	GLenum error;
	frameCnt++;
	CGprofile vertexProfile, fragmentProfile;

	if(!shaderLoaded)
		return;

	vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
	fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);

	cgGLEnableProfile(vertexProfile);
	cgGLEnableProfile(fragmentProfile);	

	/* set up our dummy pass for easier loop code
	*/
	shaderPasses[0].tex = origTex;
	shaderPasses[0].outputSize = inputSize;
	shaderPasses[0].textureSize = textureSize;

	/* loop through all real passes
	*/
	for(int i=1;i<shaderPasses.size();i++) {
		switch(shaderPasses[i].scaleParams.scaleTypeX) {
			case CG_SCALE_ABSOLUTE:
				shaderPasses[i].outputSize.x = (double)shaderPasses[i].scaleParams.absX;
				break;
			case CG_SCALE_SOURCE:
				shaderPasses[i].outputSize.x = shaderPasses[i-1].outputSize.x * shaderPasses[i].scaleParams.scaleX;
				break;
			case CG_SCALE_VIEWPORT:
				shaderPasses[i].outputSize.x = viewportSize.x * shaderPasses[i].scaleParams.scaleX;
				break;
			default:
				shaderPasses[i].outputSize.x = viewportSize.x;
		}
		switch(shaderPasses[i].scaleParams.scaleTypeY) {
			case CG_SCALE_ABSOLUTE:
				shaderPasses[i].outputSize.y = (double)shaderPasses[i].scaleParams.absX;
				break;
			case CG_SCALE_SOURCE:
				shaderPasses[i].outputSize.y = shaderPasses[i-1].outputSize.y * shaderPasses[i].scaleParams.scaleY;
				break;
			case CG_SCALE_VIEWPORT:
				shaderPasses[i].outputSize.y = viewportSize.y * shaderPasses[i].scaleParams.scaleY;
				break;
			default:
				shaderPasses[i].outputSize.y = viewportSize.y;
		}
		/* use next power of two in both directions
		*/
		float texSize = npot(max(shaderPasses[i].outputSize.x,shaderPasses[i].outputSize.y));
		shaderPasses[i].textureSize.x = shaderPasses[i].textureSize.y = texSize;

		/* set size of output texture
		*/
		glBindTexture(GL_TEXTURE_2D,shaderPasses[i].tex);
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,(unsigned int)shaderPasses[i].textureSize.x,
			(unsigned int)shaderPasses[i].textureSize.y,0,GL_RGBA,GL_UNSIGNED_INT_8_8_8_8,NULL);

		/* viewport determines the area we render into the output texture
		*/
		glViewport(0,0,shaderPasses[i].outputSize.x,shaderPasses[i].outputSize.y);

		/* set up framebuffer and attach output texture
		*/
		glBindFramebuffer(GL_FRAMEBUFFER,shaderPasses[i].fbo);
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, shaderPasses[i].tex, 0);

		/* set up input texture (output of previous pass) and apply filter settings
		*/
		glBindTexture(GL_TEXTURE_2D,shaderPasses[i-1].tex);
		glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)shaderPasses[i-1].textureSize.x);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
			shaderPasses[i].linearFilter?GL_LINEAR:GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
			shaderPasses[i].linearFilter?GL_LINEAR:GL_NEAREST);

		/* calculate tex coords first since we pass them to the shader
		*/
		setTexCoords(i,shaderPasses[i-1].outputSize,shaderPasses[i-1].textureSize);

		setShaderVars(i);

		cgGLBindProgram(shaderPasses[i].cgVertexProgram);
		cgGLBindProgram(shaderPasses[i].cgFragmentProgram);

		glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
		glClear(GL_COLOR_BUFFER_BIT);
		glDrawArrays (GL_QUADS, 0, 4);

	}

	/* disable framebuffer
	*/
	glBindFramebuffer(GL_FRAMEBUFFER,0);

	/* switch original and prev texture and make sure the
	   new original texture has the same size as the old one
	*/
	origTex = prevTex;
	prevTex = shaderPasses[0].tex;
	prevTexSize.x = textureSize.x;
	prevTexSize.y = textureSize.y;
	prevTexImageSize.x = inputSize.x;
	prevTexImageSize.y = inputSize.y;
	memcpy(prevTexCoords,shaderPasses[1].texcoords,sizeof(prevTexCoords));
	glBindTexture(GL_TEXTURE_2D,origTex);
	glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,textureSize.x,textureSize.y,0,GL_RGB,GL_UNSIGNED_SHORT_5_6_5,NULL);

	/* bind output of last pass to be rendered on the backbuffer
	*/
	glBindTexture(GL_TEXTURE_2D,shaderPasses.back().tex);
	glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)shaderPasses.back().textureSize.x);

	/* calculate and apply viewport and texture coordinates to
	   that will be used in the main ogl code
	*/
	RECT displayRect=CalculateDisplayRect(shaderPasses.back().outputSize.x,shaderPasses.back().outputSize.y,windowSize.x,windowSize.y);
	glViewport(displayRect.left,windowSize.y-displayRect.bottom,displayRect.right-displayRect.left,displayRect.bottom-displayRect.top);	
	setTexCoords(shaderPasses.size()-1,shaderPasses.back().outputSize,shaderPasses.back().textureSize,true);

	/* render to backbuffer without shaders
	*/
	cgGLDisableProfile(vertexProfile);
	cgGLDisableProfile(fragmentProfile);
}
Example #18
0
gfx::gfxFont::FontSprite gfx::gfxFont::LoadChar(int ch, int pixel)
{
	auto& glyph_group_it = glyph_map.find(pixel);
	if (glyph_group_it == glyph_map.end())
	{
		glyph_map[pixel] = Glyph_Group();
		glyph_group_it = glyph_map.find(pixel);
	}

	auto& glyph_group = glyph_group_it->second;

	auto& sprite_it = glyph_group.spritemap.find(ch);
	bool need_new_texture_cursor = false;
	if (sprite_it == glyph_group.spritemap.end())
	{
		FT_Set_Pixel_Sizes(face, 0, pixel);
		FT_Load_Char(face, ch, FT_LOAD_RENDER);
		if (ch == 56)
			printf("");
		if (glyph_group.textures.empty())
		{
			need_new_texture_cursor = true;
		}
		else
		{
			auto& texture_cursor = glyph_group.textures.back();
			if (texture_cursor.current_position_x + face->glyph->bitmap.width > maxTextureSize)
			{
				texture_cursor.current_position_x = 0;
				texture_cursor.current_position_y += texture_cursor.current_height + 1;
				texture_cursor.current_height = 0;
			}
			if (texture_cursor.current_position_y + face->glyph->bitmap.rows > maxTextureSize)
			{
				need_new_texture_cursor = true;
			}
		}

		if (need_new_texture_cursor)
		{
			glyph_group.textures.push_back(TextureCursor());
			auto& texture_cursor = glyph_group.textures.back();
			glm::u8* buffer = new glm::u8[maxTextureSize * maxTextureSize];
			memset(buffer, 0, maxTextureSize * maxTextureSize);

			glGenTextures(1, &texture_cursor.texture_id);
			glBindTexture(GL_TEXTURE_2D, texture_cursor.texture_id);
			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

			glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, maxTextureSize, maxTextureSize, 0, GL_RED, GL_UNSIGNED_BYTE, buffer);

			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
			glGenerateMipmap(GL_TEXTURE_2D);
			delete[] buffer;
		}

		auto& texture_cursor = glyph_group.textures.back();
		auto glyph = face->glyph;
		glBindTexture(GL_TEXTURE_2D, texture_cursor.texture_id);
		glTexSubImage2D(GL_TEXTURE_2D, 0, texture_cursor.current_position_x, texture_cursor.current_position_y, glyph->bitmap.width, glyph->bitmap.rows, GL_RED, GL_UNSIGNED_BYTE, glyph->bitmap.buffer);
		std::shared_ptr<Sprite> sprite(new Sprite);
		sprite->delete_itself = false;
		sprite->size = glm::vec2(glyph->bitmap.width,glyph->bitmap.rows);

		float uv_left = texture_cursor.current_position_x, uv_right = glyph->bitmap.width;
		uv_left /= maxTextureSize;
		uv_right /= maxTextureSize;
		float uv_up = texture_cursor.current_position_y, uv_down = glyph->bitmap.rows;
		uv_up /= maxTextureSize;
		uv_down /= maxTextureSize;

		sprite->texture_rect = glm::vec4(uv_left, uv_up, uv_right, uv_down);
		sprite->texture_id = texture_cursor.texture_id;
		texture_cursor.current_position_x += glyph->bitmap.width + 1;
		texture_cursor.current_height = texture_cursor.current_height > glyph->bitmap.rows ? texture_cursor.current_height : glyph->bitmap.rows;
		FontSprite font_sprite;
		font_sprite.sprite = sprite;
		font_sprite.left = glyph->bitmap_left;
		font_sprite.top = glyph->bitmap_top;
		font_sprite.advance = glyph->advance.x / 64.0f;

		glyph_group.spritemap[ch] = font_sprite;
	}
	sprite_it = glyph_group.spritemap.find(ch);
	return sprite_it->second;
}
TextureHandle RenderInterfaceDefaultGLCore::createTexture(int widthPixels, int heightPixels,
                                                          int colorChannels, const void * pixels)
{
    NTB_ASSERT(widthPixels   >  0);
    NTB_ASSERT(heightPixels  >  0);
    NTB_ASSERT(colorChannels >  0);
    NTB_ASSERT(colorChannels <= 4); // Up to GL_RGBA
    NTB_ASSERT(pixels != nullptr);

    GLTextureRecord * newTex = implAllocT<GLTextureRecord>();
    newTex->width  = widthPixels;
    newTex->height = heightPixels;
    newTex->texId  = 0;
    newTex->prev   = nullptr;
    newTex->next   = nullptr;

    GLint oldTexture = 0;
    GLint oldUnpackAlign = 0;

    if (saveGLStates)
    {
        glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldTexture);
        glGetIntegerv(GL_UNPACK_ALIGNMENT, &oldUnpackAlign);
    }

    glGenTextures(1, &newTex->texId);
    glBindTexture(GL_TEXTURE_2D, newTex->texId);

    // Set the row alignment to the highest value that
    // the size of a row divides evenly. Options are: 8,4,2,1.
    const GLuint rowSizeBytes = widthPixels * colorChannels;
    if ((rowSizeBytes % 8) == 0)
    {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
    }
    else if ((rowSizeBytes % 4) == 0)
    {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
    }
    else if ((rowSizeBytes % 2) == 0)
    {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
    }
    else
    {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    }

    const GLenum format = ((colorChannels == 1) ? GL_RED : (colorChannels == 3) ? GL_RGB : GL_RGBA);
    glTexImage2D(GL_TEXTURE_2D, 0, format, widthPixels, heightPixels, 0, format, GL_UNSIGNED_BYTE, pixels);

    // Alpha texture (used by font bitmaps):
    if (colorChannels == 1)
    {
        // RED only texture. Tell GL to fill RED, GREEN and BLUE with 1
        // and place the first component (RED) in the alpha channel.
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_ONE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_ONE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_ONE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_RED);
    }

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    // Restore the texture and alignment we had before or just set to 0 if not saving states.
    if (saveGLStates)
    {
        glBindTexture(GL_TEXTURE_2D, oldTexture);
        glPixelStorei(GL_UNPACK_ALIGNMENT, oldUnpackAlign);
    }
    else
    {
        glBindTexture(GL_TEXTURE_2D, 0);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    }

    if (checkGLErrors)
    {
        checkGLError(__FILE__, __LINE__);
    }

    textures.pushBack(newTex);
    return reinterpret_cast<TextureHandle>(newTex);
}
Example #20
0
// The MAIN function, from here we start our application and run the Game loop
int main_init()
{
	// Init GLFW
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); // Windowed
	glfwMakeContextCurrent(window);

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

	// Define the viewport dimensions
	glViewport(0, 0, WIDTH, HEIGHT);

	// Set OpenGL options
	glEnable(GL_CULL_FACE);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// Compile and setup the shader
	Shader shader("shaders/text.vs", "shaders/text.frag");
	glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(WIDTH), 0.0f, static_cast<GLfloat>(HEIGHT));
	shader.Use();
	glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));

	// FreeType
	FT_Library ft;
	// All functions return a value different than 0 whenever an error occurred
	if (FT_Init_FreeType(&ft))
		std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl;

	// Load font as face
	FT_Face face;
	if (FT_New_Face(ft, "fonts/arial.ttf", 0, &face))
		std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl;

	// Set size to load glyphs as
	FT_Set_Pixel_Sizes(face, 0, 48);

	// Disable byte-alignment restriction
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	// Load first 128 characters of ASCII set
	for (GLubyte c = 0; c < 128; c++)
	{
		// Load character glyph 
		if (FT_Load_Char(face, c, FT_LOAD_RENDER))
		{
			std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl;
			continue;
		}
		// Generate texture
		GLuint texture;
		glGenTextures(1, &texture);
		glBindTexture(GL_TEXTURE_2D, texture);
		glTexImage2D(
			GL_TEXTURE_2D,
			0,
			GL_RED,
			face->glyph->bitmap.width,
			face->glyph->bitmap.rows,
			0,
			GL_RED,
			GL_UNSIGNED_BYTE,
			face->glyph->bitmap.buffer
		);
		// Set texture options
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		// Now store character for later use
		Character character = {
			texture,
			glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
			glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
			face->glyph->advance.x
		};
		Characters.insert(std::pair<GLchar, Character>(c, character));
	}
	glBindTexture(GL_TEXTURE_2D, 0);
	// Destroy FreeType once we're finished
	FT_Done_Face(face);
	FT_Done_FreeType(ft);


	// Configure VAO/VBO for texture quads
	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);
	glBindVertexArray(VAO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindVertexArray(0);

	// Game loop
	while (!glfwWindowShouldClose(window))
	{
		// Check and call events
		glfwPollEvents();

		// Clear the colorbuffer
		glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		RenderText(shader, "This is sample text", 25.0f, 25.0f, 1.0f, glm::vec3(0.5, 0.8f, 0.2f));
		RenderText(shader, "(C) LearnOpenGL.com", 540.0f, 570.0f, 0.5f, glm::vec3(0.3, 0.7f, 0.9f));

		// Swap the buffers
		glfwSwapBuffers(window);
	}

	glfwTerminate();
	return 0;
}
Example #21
0
    bool RenderTarget::copyToBuffer( GLenum mode, dp::sg::core::Image::PixelFormat pixelFormat, dp::sg::core::Image::PixelDataType pixelDataType, const dp::sg::core::BufferSharedPtr & buffer )
    {
      // FIXME use C++ object for current/noncurrent for exception safety
      makeCurrent();

      size_t components = 0;
      size_t bytesPerComponent = 0;

      // set up alignments
      glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
      glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
      glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
      glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
      glPixelStorei(GL_PACK_ALIGNMENT, 1);
      glPixelStorei(GL_PACK_ROW_LENGTH, 0);
      glPixelStorei(GL_PACK_SKIP_ROWS, 0);
      glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

      // determine OpenGL format
      GLenum format = ~0;
      switch (pixelFormat)
      {
      case dp::PixelFormat::RGB:
        format = GL_RGB;
        components = 3;
      break;
      case dp::PixelFormat::RGBA:
        format = GL_RGBA;
        components = 4;
      break;
      case dp::PixelFormat::BGR:
        format = GL_BGR;
        components = 3;
      break;
      case dp::PixelFormat::BGRA:
        format = GL_BGRA;
        components = 4;
      break;
      case dp::PixelFormat::LUMINANCE:
        format = GL_LUMINANCE;
        components = 1;
      break;
      case dp::PixelFormat::ALPHA:
        format = GL_ALPHA;
        components = 1;
      break;
      case dp::PixelFormat::LUMINANCE_ALPHA:
        format = GL_LUMINANCE_ALPHA;
        components = 2;
      break;
      case dp::PixelFormat::DEPTH_COMPONENT:
        format = GL_DEPTH_COMPONENT;
        components = 1;
      break;
      case dp::PixelFormat::DEPTH_STENCIL:
        format = GL_DEPTH24_STENCIL8;
        components = 1;
      break;
      default:
        DP_ASSERT(0 && "unsupported PixelFormat");
      };

      GLenum dataType = ~0;
      switch (pixelDataType)
      {
      case dp::PixelFormat::PF_BYTE:
        dataType = GL_BYTE;
        bytesPerComponent = 1;
      break;
      case dp::PixelFormat::PF_UNSIGNED_BYTE:
        dataType = GL_UNSIGNED_BYTE;
        bytesPerComponent = 1;
      break;
      case dp::PixelFormat::PF_SHORT:
        dataType = GL_SHORT;
        bytesPerComponent = 2;
      break;
      case dp::PixelFormat::PF_UNSIGNED_SHORT:
        dataType = GL_UNSIGNED_SHORT;
        bytesPerComponent = 2;
      break;
      case dp::PixelFormat::PF_INT:
        dataType = GL_INT;
        bytesPerComponent = 4;
      break;
      case dp::PixelFormat::PF_UNSIGNED_INT:
        dataType = GL_UNSIGNED_INT;
        bytesPerComponent = 4;
      break;
      case dp::PixelFormat::PF_FLOAT32:
        dataType = GL_FLOAT;
        bytesPerComponent = 4;
      break;
      case dp::PixelFormat::PF_FLOAT16:
        dataType = GL_HALF_FLOAT;
        bytesPerComponent = 2;
      break;
      default:
        DP_ASSERT(0 && "unsupported PixelDataType");
      }

      BufferLock(buffer)->setSize(m_width * m_height * components * bytesPerComponent);

      // read the pixels
      glWindowPos2i(0,0);
      glReadBuffer( mode );

      bool isBufferGL = std::dynamic_pointer_cast<BufferGL>(buffer);
      if ( isBufferGL )
      {
        GLint oldPBO;
        glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &oldPBO);
        // FIXME it's necessary to check wheter the buffer object shared data with the current context...
        BufferGLLock bufferGL( sharedPtr_cast<BufferGL>( buffer ) );
        bufferGL->bind( GL_PIXEL_PACK_BUFFER );
        glReadPixels(0, 0, m_width, m_height, format, dataType, 0);
        glBindBuffer(GL_PIXEL_PACK_BUFFER, (GLuint)oldPBO);
      }
      else
      {
        Buffer::DataWriteLock bufferLock(buffer, Buffer::MAP_WRITE);
        glReadPixels(0, 0, m_width, m_height, format, dataType, bufferLock.getPtr());
      }

      makeNoncurrent();

      return true;
    }
Example #22
0
/* Readfile uses imageio to read in an image, and binds it to an OpenGL
 * texture name.  Requires OpenGL 2.0 or better.
 *
 * filename: name of file to load
 *
 * texName: A pointer to where the OpenGL texture name should be stored.
 * (Remember that the "texture name" is really just some unsigned int).
 *
 * returns: aspect ratio of the image in the file.
 */
float readfile(char *filename, GLuint *texName, GLuint *numTiles)
{
	static int verbose=1;  // change this to 0 to print out less info

	/* Try to load the image. */
	imageio_info iioinfo;
	iioinfo.filename = filename;
	iioinfo.type = CharPixel;
	iioinfo.map = "RGBA";
	iioinfo.colorspace = sRGBColorspace;
	char *image = (char*) imagein(&iioinfo);

	if(image == NULL)
	{
		fprintf(stderr, "\n%s: Unable to read image.\n", filename);
		return -1;
	}

	/* "image" is a 1D array of characters (unsigned bytes) with four
	 * bytes for each pixel (red, green, blue, alpha). The data in "image"
	 * is in row major order. The first 4 bytes are the color information
	 * for the lowest left pixel in the texture. */
	int width  = (int)iioinfo.width;
	int height = (int)iioinfo.height;
	float original_aspectRatio = (float)width/height;
	if(verbose)
		printf("%s: Finished reading, dimensions are %dx%d\n", filename, width, height);

	/* OpenGL only supports textures if they are small enough. If
	 * the texture is too large, we need to split it into smaller
	 * textures and render each texture on its own
	 * quad. Typically, the limit is 4096 pixels in each
	 * dimension. This code will always split the image vertically
	 * in half...and then decide how many tiles are necessary
	 * horizontally. This allows for long horizontal panoramas but
	 * not long vertical panoramas. */
	
	/* Since we display image as being two tiles tall, make sure
	 * image isn't too tall. */
	if(height > 4096*2)
	{
		printf("Source image must <= 8192 pixels tall.");
		exit(1);
	}

	int subimgH = height/2; // height of a the tiles
	int workingWidth = width;
	*numTiles = 1; // number of tiles in horizontal direction
	/* Calculate number of tiles horizontally we need. */
	while(workingWidth > 4096)
	{
		/* If image is too wide, split the width of the tile
		 * in half---doubling the number of tiles in the
		 * horizontal direction */
		*numTiles = *numTiles * 2;
		workingWidth = workingWidth / 2;
	}
	int subimgW = workingWidth;

	if(*numTiles > MAX_TILES/2.0)
	{
		printf("Too many tiles");
		exit(1);
	}

	glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA8, subimgW, subimgH,
	             0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
	int tmp;
	glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &tmp);

	if(tmp == 0)
	{
		fprintf(stderr, "%s: File is too large (%d x %d). I can't load it!\n", filename, subimgW, subimgH);
		free(image);
		exit(1);
	}


	/* Generate all of the textures that we need. */
	glGenTextures(*numTiles*2, texName);

	for(GLuint curTile=0; curTile < *numTiles*2; curTile = curTile+2)
	{
		/* Prepare to copy the data from the array into the
		 * texture, tell OpenGL to skip pixels appropriately
		 * so that each tile gets the right part of the
		 * image. */
		glPixelStorei(GL_UNPACK_ROW_LENGTH,  width);
		glPixelStorei(GL_UNPACK_SKIP_PIXELS, curTile/2.0*subimgW);
		glPixelStorei(GL_UNPACK_SKIP_ROWS,   0);

		glBindTexture(GL_TEXTURE_2D, texName[curTile]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, subimgW, subimgH,
		             0, GL_RGBA, GL_UNSIGNED_BYTE, image);

		glPixelStorei( GL_UNPACK_SKIP_PIXELS, curTile/2.0*subimgW );
		glPixelStorei( GL_UNPACK_SKIP_ROWS, subimgH);

		glBindTexture(GL_TEXTURE_2D, texName[curTile+1]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, subimgW, subimgH,
		             0, GL_RGBA, GL_UNSIGNED_BYTE, image);
	}

	free(image);
	return original_aspectRatio;
}
CDicom3DTexture::CDicom3DTexture(QString &fileName)
{
    iFrames = NULL;
    GLenum err = glGetErr();//To throw away the last Open GL Error
    iFileName = new QString();
    iFileName->append(fileName);

    iFrames= new CDicomFrames(fileName.toAscii().data());
    glGenTextures(1,&iTextureID);            // Allocate space for texture

    glBindTexture(GL_TEXTURE_3D,iTextureID); // Set our Tex handle as current

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);          // zpusob ulozeni bytu v texture
    //generate texture
    switch (iFrames->GetColorCount())
    {
    case 1:
    {
        int maxsize[3] ;
        glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE,&maxsize[0] );

        //	int j=sizeof(GLushort );
        /*
        on't use GL_PROXY_TEXTURE_3D as its isn't very reliable as you have
        already seen, it might not be well implemented in the driver. A better
        thing is to actually use glTexImage3D(GL_TEXTURE_3D...) and check for
        GL errror (using glGetErr ). Repeat this with different texture sizes
        until you succeed (no GL error) with the call
        glTexImage3D(GL_TEXTURE_3D...).
        */
        //test for succesfull texture load
        /*glTexImage3D(GL_PROXY_TEXTURE_3D,0,GL_RGB32F_ARB    ,8200, 8200 ,8248,0,
        	GL_LUMINANCE ,GL_UNSIGNED_SHORT  ,frames.GetImageData());

        GLint format;
        glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, 0,
        	GL_TEXTURE_INTERNAL_FORMAT, &format);
        	*/

        //GL_RGB32F_ARB - for color resolution
        GLenum err = glGetErr();
        if(err!=GL_NO_ERROR )
        {
            int errt=1;
            d3dLog.write("glGetErr()(CDicom3DTexture::CDicom3DTexture genTextures,PixelStorei) not succesful");
            throw TextureNotCreatedException();
        }

        glTexImage3DEXT=(PFNGLTEXIMAGE3DEXTPROC)wglGetProcAddress("glTexImage3DEXT");
        glTexSubImage3DEXT=(PFNGLTEXSUBIMAGE3DEXTPROC)wglGetProcAddress("glTexSubImage3DEXT");

        glTexImage3D(GL_TEXTURE_3D,0,GL_LUMINANCE16  ,iFrames->GetWidth(), iFrames->GetHeight() ,iFrames->GetFramesCount(),0,
                     GL_LUMINANCE ,GL_UNSIGNED_SHORT  ,iFrames->GetImageData());  //tento prikaz neprobehne spravne

        err = glGetErr();

        if(err!=GL_NO_ERROR )
        {
            int errt=1;
            d3dLog.write("glGetErr()(CDicom3DTexture::CDicom3DTexture glTexImage3D) not succesful");
            throw TextureNotCreatedException();
        }


    }
    break;
    default:
        assert(1==0); //TODO other color depths
    }

    iWidth = iFrames->GetWidth();
    iHeight = iFrames->GetHeight();
    iDepth = iFrames->GetFramesCount ();
    iColorsCount = iFrames->GetColorCount ();
    iBitsPerPixel = iFrames->GetBitsPerSampleCount ()*iFrames->GetColorCount ();
    iWindowDefaults = iFrames->GetWindowDefaults();
    iMaxColorValue= iFrames->GetMinColorValue();
    iMinColorValue=iFrames->GetMaxColorValue();

    //glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    // Specify filtering and edge actions
    //glTexParameteri(GL_TEXTURE_3D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    //glTexParameteri(GL_TEXTURE_3D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_3D,GL_TEXTURE_MAG_FILTER,GL_NEAREST );
    glTexParameteri(GL_TEXTURE_3D,GL_TEXTURE_MIN_FILTER,GL_NEAREST );
    //nasledujici parametry znehodnoti texturu - nevim proc
    glTexParameteri(GL_TEXTURE_3D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_3D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
    // same as above for R axis
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    // this is a 3d texture, level 0 (max detail), GL should store it in RGB8 format, its WIDTHxHEIGHTxDEPTH in size,
    // it doesnt have a border, we're giving it to GL in RGB format as a series of unsigned bytes, and texels is where the texel data is.
    err = glGetErr();
    if(err!=GL_NO_ERROR )
    {
        int errt=1;
        throw TextureNotCreatedException();
    }
    iFrames->FreeData();

}
Example #24
0
// display results using OpenGL (called by GLUT)
void display()
{
    sdkStartTimer(&timer);

    // map PBO to get CUDA device pointer
    uchar4 *d_output;
    checkCudaErrors(cudaGraphicsMapResources(1, &cuda_pbo_resource, 0));
    size_t num_bytes;
    checkCudaErrors(cudaGraphicsResourceGetMappedPointer((void **)&d_output, &num_bytes,
                                                         cuda_pbo_resource));
    render(imageWidth, imageHeight, tx, ty, scale, cx, cy,
           blockSize, gridSize, g_FilterMode, d_output);

    checkCudaErrors(cudaGraphicsUnmapResources(1, &cuda_pbo_resource, 0));

    // Common diplay path
    {
        // display results
        glClear(GL_COLOR_BUFFER_BIT);

#if USE_BUFFER_TEX
        // display using buffer texture
        glBindTexture(GL_TEXTURE_BUFFER_EXT, bufferTex);
        glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, fprog);
        glEnable(GL_FRAGMENT_PROGRAM_ARB);
        glProgramLocalParameterI4iNV(GL_FRAGMENT_PROGRAM_ARB, 0, width, 0, 0, 0);
#else
        // download image from PBO to OpenGL texture
        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
        glBindTexture(GL_TEXTURE_TYPE, displayTex);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
        glTexSubImage2D(GL_TEXTURE_TYPE,
                        0, 0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, 0);
        glEnable(GL_TEXTURE_TYPE);
#endif

        // draw textured quad
        glDisable(GL_DEPTH_TEST);
        glBegin(GL_QUADS);
        glTexCoord2f(0.0f          , (GLfloat)height);
        glVertex2f(0.0f, 0.0f);
        glTexCoord2f((GLfloat)width, (GLfloat)height);
        glVertex2f(1.0f, 0.0f);
        glTexCoord2f((GLfloat)width, 0.0f);
        glVertex2f(1.0f, 1.0f);
        glTexCoord2f(0.0f          , 0.0f);
        glVertex2f(0.0f, 1.0f);
        glEnd();
        glDisable(GL_TEXTURE_TYPE);
        glDisable(GL_FRAGMENT_PROGRAM_ARB);

        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

        if (drawCurves)
        {
            // draw spline curves
            glPushMatrix();
            glScalef(0.25, 0.25, 1.0);

            glTranslatef(0.0, 2.0, 0.0);
            glColor3f(1.0, 0.0, 0.0);
            plotCurve(bspline_w3);

            glTranslatef(1.0, 0.0, 0.0);
            glColor3f(0.0, 1.0, 0.0);
            plotCurve(bspline_w2);

            glTranslatef(1.0, 0.0, 0.0);
            glColor3f(0.0, 0.0, 1.0);
            plotCurve(bspline_w1);

            glTranslatef(1.0, 0.0, 0.0);
            glColor3f(1.0, 0.0, 1.0);
            plotCurve(bspline_w0);

            glPopMatrix();
            glColor3f(1.0, 1.0, 1.0);
        }
    }

    glutSwapBuffers();
    glutReportErrors();

    sdkStopTimer(&timer);

    computeFPS();
}
void GenerateTextures()
{
	// zmienne użyte przy obsłudze plików TARGA
	GLsizei width, height;
	GLenum format, type;
	GLvoid *pixels;

	// tryb upakowania bajtów danych tekstury
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	// wskazówki do kompresji tesktur
	glHint(GL_TEXTURE_COMPRESSION_HINT, texture_compression_hint);

	// wczytanie tekstury white_skin_guy_black_hairs.tga
	GLboolean error = load_targa("white_skin_guy_black_hairs.tga", width, height, format, type, pixels);

	// błąd odczytu pliku
	if (error == GL_FALSE)
	{
		printf("Niepoprawny odczyt pliku white_skin_guy_black_hairs.tga");
		exit(0);
	}

	// utworzenie identyfikatora tekstury
	glGenTextures(1, &LENA);

	// dowiązanie stanu tekstury
	glBindTexture(GL_TEXTURE_2D, LENA);

	// definiowanie tekstury z kompresją
	glTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB, width, height, 0, format, type, pixels);

	// utworzenie identyfikatora tekstury
	glGenTextures(1, &LENA_UNC);

	// dowiązanie stanu tekstury
	glBindTexture(GL_TEXTURE_2D, LENA_UNC);

	// definiowanie tekstury bez kompresji
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, format, type, pixels);

	// porządki
	delete[](unsigned char*)pixels;

	// wczytanie tekstury white_skin_guy_black_hairs_gray.tga
	error = load_targa("white_skin_guy_black_hairs_gray.tga", width, height, format, type, pixels);

	// błąd odczytu pliku
	if (error == GL_FALSE)
	{
		printf("Niepoprawny odczyt pliku white_skin_guy_black_hairs_gray.tga");
		exit(0);
	}

	// utworzenie identyfikatora tekstury
	glGenTextures(1, &LENA_GRAY);

	// dowiązanie stanu tekstury
	glBindTexture(GL_TEXTURE_2D, LENA_GRAY);

	// definiowanie tekstury z kompresją
	glTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_LUMINANCE, width, height, 0, format, type, pixels);

	// utworzenie identyfikatora tekstury
	glGenTextures(1, &LENA_GRAY_UNC);

	// dowiązanie stanu tekstury
	glBindTexture(GL_TEXTURE_2D, LENA_GRAY_UNC);

	// definiowanie tekstury bez kompresji
	glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0, format, type, pixels);

	// porządki
	delete[](unsigned char*)pixels;

	// wybór bieżącej tekstury
	texture = LENA;
}
Example #26
0
GLuint graph_init_freetype(const char *fontname)
{
    /* Initialize OpenGL */
    GLuint text_program = graph_compile_shader(text_vs, text_fs);
    glBindAttribLocation(text_program, textattr_coord, "coord");
    glBindAttribLocation(text_program, textattr_texcoord, "textcolor");
    glBindAttribLocation(text_program, textattr_tex, "tex");
    glBindAttribLocation(text_program, textattr_color, "color");
    textattr_tex = glGetUniformLocation(text_program, "tex");
    textattr_color = glGetUniformLocation(text_program, "textcolor");
    glUniform1i(textattr_tex, 0);

    /* Init Freetype and generate texture atlas */
    if (FT_Init_FreeType(&library)) {
        pprintf(PRI_ERR, "Could not init freetype library.\n");
        exit(1);
    }
    if (FT_New_Face(library, fontname, 0, &face)) {
        pprintf(PRI_ERR, "Freetype could not open font.\n");
        exit(1);
    }
    FT_Set_Pixel_Sizes(face, 0, option->fontsize);
    g = face->glyph;

    /* Load glyphs and get maximum height and width */
    for (int i = 32; i < 128; i++) {
        if(FT_Load_Char(face, i, FT_LOAD_RENDER)) {
            fprintf(stderr, "Loading character %c failed!\n", i);
            continue;
        }
        atlas_w += g->bitmap.width + 1;
        if (g->bitmap.rows > atlas_h)
            atlas_h = g->bitmap.rows;
    }

    /* Create a seperate texture to hold altas, fill it with NULL */
    glActiveTexture(GL_TEXTURE0);
    glGenTextures(1, &font_tex);
    glBindTexture(GL_TEXTURE_2D, font_tex);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, atlas_w, atlas_h, 0,
                GL_ALPHA, GL_UNSIGNED_BYTE, NULL);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    /* Fill texture and save locations(offsets) for every char */
    GLint x = 0;
    for (short i = 32; i < 128; i++) {
        if (FT_Load_Char(face, i, FT_LOAD_RENDER))
            continue;
        glTexSubImage2D(GL_TEXTURE_2D, 0, x, 0, g->bitmap.width, g->bitmap.rows,
                        GL_ALPHA, GL_UNSIGNED_BYTE, g->bitmap.buffer);
        ft_chr[i].ax = g->advance.x >> 6;
        ft_chr[i].ay = g->advance.y >> 6;
        ft_chr[i].bw = g->bitmap.width;
        ft_chr[i].bh = g->bitmap.rows;
        ft_chr[i].bl = g->bitmap_left;
        ft_chr[i].bt = g->bitmap_top;
        ft_chr[i].tx = (GLfloat)x/atlas_w;
        x += g->bitmap.width;
    }

    pprintf(PRI_SPAM, "[FT] Created a %i by %i atlas (%3.3lf KiB)\n",
        atlas_w, atlas_h, atlas_w*atlas_h/1024.0);

    return text_program;
}
Example #27
0
static void
load_textures (ModeInfo *mi, Bool flip_p)
{
  matrix_configuration *mp = &mps[MI_SCREEN(mi)];
  XImage *xi;
  int x, y;
  int cw, ch;
  int orig_w, orig_h;

  /* The Matrix XPM is 512x598 -- but GL texture sizes must be powers of 2.
     So we waste some padding rows to round up.
   */
  xi = xpm_to_ximage (matrix3_xpm);
  orig_w = xi->width;
  orig_h = xi->height;
  mp->real_char_rows = CHAR_ROWS;
  spank_image (mp, xi);

  if (xi->height != 512 && xi->height != 1024)
    {
      xi->height = (xi->height < 512 ? 512 : 1024);
      xi->data = realloc (xi->data, xi->height * xi->bytes_per_line);
      if (!xi->data)
        {
          fprintf(stderr, "%s: out of memory\n", progname);
          exit(1);
        }
    }

  if (xi->width != 512) abort();
  if (xi->height != 512 && xi->height != 1024) abort();

  /* char size in pixels */
  cw = orig_w / CHAR_COLS;
  ch = orig_h / CHAR_ROWS;

  /* char size in ratio of final (padded) texture size */
  mp->tex_char_width  = (GLfloat) cw / xi->width;
  mp->tex_char_height = (GLfloat) ch / xi->height;

  /* Flip each character's bits horizontally -- we could also just do this
     by reversing the texture coordinates on the quads, but on some systems
     that slows things down a lot.
   */
  if (flip_p)
    {
      int xx, col;
      unsigned long buf[100];
      for (y = 0; y < xi->height; y++)
        for (col = 0, xx = 0; col < CHAR_COLS; col++, xx += cw)
          {
            for (x = 0; x < cw; x++)
              buf[x] = XGetPixel (xi, xx+x, y);
            for (x = 0; x < cw; x++)
              XPutPixel (xi, xx+x, y, buf[cw-x-1]);
          }
    }

  /* The pixmap is a color image with no transparency.  Set the texture's
     alpha to be the green channel, and set the green channel to be 100%.
   */
  {
    int rpos, gpos, bpos, apos;  /* bitfield positions */
#if 0
    /* #### Cherub says that the little-endian case must be taken on MacOSX,
            or else the colors/alpha are the wrong way around.  How can
            that be the case?
     */
    if (bigendian())
      rpos = 24, gpos = 16, bpos =  8, apos =  0;
    else
#endif
      rpos =  0, gpos =  8, bpos = 16, apos = 24;

    for (y = 0; y < xi->height; y++)
      for (x = 0; x < xi->width; x++)
        {
          unsigned long p = XGetPixel (xi, x, y);
          unsigned char r = (p >> rpos) & 0xFF;
          unsigned char g = (p >> gpos) & 0xFF;
          unsigned char b = (p >> bpos) & 0xFF;
          unsigned char a = g;
          g = 0xFF;
          p = (r << rpos) | (g << gpos) | (b << bpos) | (a << apos);
          XPutPixel (xi, x, y, p);
        }
  }

  /* Now load the texture into GL.
   */
  clear_gl_error();
  glGenTextures (1, &mp->texture);

  glPixelStorei (GL_UNPACK_ALIGNMENT, 4);
  glPixelStorei (GL_UNPACK_ROW_LENGTH, xi->width);
  glBindTexture (GL_TEXTURE_2D, mp->texture);
  check_gl_error ("texture init");
  glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, xi->width, xi->height, 0, GL_RGBA,
                GL_UNSIGNED_INT_8_8_8_8_REV, xi->data);
  {
    char buf[255];
    sprintf (buf, "creating %dx%d texture:", xi->width, xi->height);
    check_gl_error (buf);
  }

  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

  /* I'd expect CLAMP to be the thing to do here, but oddly, we get a
     faint solid green border around the texture if it is *not* REPEAT!
  */
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

  glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
  check_gl_error ("texture param");

  XDestroyImage (xi);
}
Example #28
0
GLint gltGrabScreenTGA(const char *szFileName)
	{
    FILE *pFile;                // File pointer
    TGAHEADER tgaHeader;		// TGA file header
    unsigned long lImageSize;   // Size in bytes of image
    GLbyte	*pBits = NULL;      // Pointer to bits
    GLint iViewport[4];         // Viewport in pixels
    GLenum lastBuffer;          // Storage for the current read buffer setting
    
	// Get the viewport dimensions
	glGetIntegerv(GL_VIEWPORT, iViewport);
	
    // How big is the image going to be (targas are tightly packed)
	lImageSize = iViewport[2] * 3 * iViewport[3];	
	
    // Allocate block. If this doesn't work, go home
    pBits = (GLbyte *)malloc(lImageSize);
    if(pBits == NULL)
        return 0;
	
    // Read bits from color buffer
    glPixelStorei(GL_PACK_ALIGNMENT, 1);
	glPixelStorei(GL_PACK_ROW_LENGTH, 0);
	glPixelStorei(GL_PACK_SKIP_ROWS, 0);
	glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
    
    // Get the current read buffer setting and save it. Switch to
    // the front buffer and do the read operation. Finally, restore
    // the read buffer state
    glGetIntegerv(GL_READ_BUFFER, (GLint *)&lastBuffer);
    glReadBuffer(GL_FRONT);
    glReadPixels(0, 0, iViewport[2], iViewport[3], GL_BGR_EXT, GL_UNSIGNED_BYTE, pBits);
    glReadBuffer(lastBuffer);
    
    // Initialize the Targa header
    tgaHeader.identsize = 0;
    tgaHeader.colorMapType = 0;
    tgaHeader.imageType = 2;
    tgaHeader.colorMapStart = 0;
    tgaHeader.colorMapLength = 0;
    tgaHeader.colorMapBits = 0;
    tgaHeader.xstart = 0;
    tgaHeader.ystart = 0;
    tgaHeader.width = iViewport[2];
    tgaHeader.height = iViewport[3];
    tgaHeader.bits = 24;
    tgaHeader.descriptor = 0;
    
    // Do byte swap for big vs little endian
#ifdef __APPLE__
    LITTLE_ENDIAN_WORD(&tgaHeader.colorMapStart);
    LITTLE_ENDIAN_WORD(&tgaHeader.colorMapLength);
    LITTLE_ENDIAN_WORD(&tgaHeader.xstart);
    LITTLE_ENDIAN_WORD(&tgaHeader.ystart);
    LITTLE_ENDIAN_WORD(&tgaHeader.width);
    LITTLE_ENDIAN_WORD(&tgaHeader.height);
#endif
    
    // Attempt to open the file
    pFile = fopen(szFileName, "wb");
    if(pFile == NULL)
		{
        free(pBits);    // Free buffer and return error
        return 0;
		}
	
    // Write the header
    fwrite(&tgaHeader, sizeof(TGAHEADER), 1, pFile);
    
    // Write the image data
    fwrite(pBits, lImageSize, 1, pFile);
	
    // Free temporary buffer and close the file
    free(pBits);    
    fclose(pFile);
    
    // Success!
    return 1;
	}
void APIENTRY 
glutBitmapCharacter(GLUTbitmapFont font, int c)
{
  const BitmapCharRec *ch;
  BitmapFontPtr fontinfo;
  GLint swapbytes, lsbfirst, rowlength;
  GLint skiprows, skippixels, alignment;

#if defined(WIN32)
  fontinfo = (BitmapFontPtr) __glutFont(font);
#else
  fontinfo = (BitmapFontPtr) font;
#endif

  if (c < fontinfo->first ||
    c >= fontinfo->first + fontinfo->num_chars)
    return;
  ch = fontinfo->ch[c - fontinfo->first];
  if (ch) {
    /* Save current modes. */
    glGetIntegerv(GL_UNPACK_SWAP_BYTES, &swapbytes);
    glGetIntegerv(GL_UNPACK_LSB_FIRST, &lsbfirst);
    glGetIntegerv(GL_UNPACK_ROW_LENGTH, &rowlength);
    glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skiprows);
    glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skippixels);
    glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);
    /* Little endian machines (DEC Alpha for example) could
       benefit from setting GL_UNPACK_LSB_FIRST to GL_TRUE
       instead of GL_FALSE, but this would require changing the
       generated bitmaps too. */
    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
    glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glBitmap(ch->width, ch->height, ch->xorig, ch->yorig,
      ch->advance, 0, ch->bitmap);
    /* Restore saved modes. */
    glPixelStorei(GL_UNPACK_SWAP_BYTES, swapbytes);
    glPixelStorei(GL_UNPACK_LSB_FIRST, lsbfirst);
    glPixelStorei(GL_UNPACK_ROW_LENGTH, rowlength);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, skiprows);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, skippixels);
    glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
  }
}
void Inicjuj( sf::RenderWindow &app )
{
    font.loadFromFile( "fonts/comicbd.ttf" );

    std::string str( "Ladowanie textur..." );
    CStopWatch timer;

    pisz( app, str );

    const char *chTextures[ LiczbaTextur ] = {  "textures/background.tga",
                                                "textures/cross.tga",
                                                "textures/life.tga",
                                                "textures/blood.tga",
                                                "textures/enemy.tga",
                                                "textures/comet.tga",
                                                "textures/bullet.tga",
                                                "textures/award.tga" };

    GLsizei width, height;
    GLenum format, type;
    GLvoid *pixels;

    glPixelStorei(GL_UNPACK_ALIGNMENT,1);

    for ( int i = 0; i < LiczbaTextur; ++i ){

        if ( !load_targa( chTextures[i], width, height, format, type, pixels) ){
            str = "Brak pliku ";
            str += chTextures[i];
            pisz( app, str );
            while ( timer.GetElapsedSeconds() < 1.0f ){
                continue;
            }
        }

        glGenTextures(1,&t_textures[ i ]);
        glBindTexture(GL_TEXTURE_2D, t_textures[ i ]);
        gluBuild2DMipmaps(GL_TEXTURE_2D,GL_RGBA,width,height,format,type,pixels);

        delete [] (unsigned char *)pixels;
    }

    str = "Ladowanie modeli...";
    pisz( app, str );

    load_obj( "models/award/WoodenBox02.obj", model_award );
    load_obj( "models/comet/Rock.obj", model_rock );
    load_obj( "models/bullet/bullet.obj", model_bullet );
    load_obj( "models/SpaceShip/fighter.obj", model_space_ship );

    str = "Ladowanie dzwiekow...";
    pisz( app, str );

    const char *chMusic[ LiczbaDzwiekow ] = {   "sounds/MenuBackground#1.ogg",
                                                "sounds/MenuBackground#2.ogg",
                                                "sounds/Background.ogg",
                                                "sounds/fire.ogg",
                                                "sounds/Award.ogg",
                                                "sounds/ColShipComet.ogg",
                                                "sounds/ColShipShip.ogg",
                                                "sounds/CometExplo.ogg",
                                                "sounds/lifeLost.ogg",
                                                "sounds/ShipExplo.ogg",
                                                "sounds/hit.ogg" };

    for ( int i = 0; i < LiczbaDzwiekow; ++i ){
        if ( !sounds[i].openFromFile( chMusic[i] ) ){
            str = "Brak pliku ";
            str += chMusic[i];
            pisz( app, str );
            while ( timer.GetElapsedSeconds() < 1.0f ){
                continue;
            }
        }
    }

    sounds[0].setRelativeToListener( true );
    sounds[1].setRelativeToListener( true );
    sounds[2].setRelativeToListener( true );
    sounds[3].setRelativeToListener( true );
    sounds[4].setRelativeToListener( true );
    sounds[8].setRelativeToListener( true );
    sounds[10].setRelativeToListener( true );

    sounds[2].setLoop( true );
    sounds[2].setVolume( 20 );

    sounds[9].setMinDistance( 7.0f );
    sounds[9].setAttenuation( 15.0f );
    sounds[7].setMinDistance( 7.0f );
    sounds[7].setAttenuation( 15.0f );

    sf::Listener::setGlobalVolume( 100.f );
    sf::Listener::setDirection( 0.0f, 0.0f, -1.0f );

    str = "Inicjowaie list wyswietlania...";
    pisz( app, str );

    ///Lista tla!
    list_SkyBox = glGenLists( 1 );
    glNewList( list_SkyBox, GL_COMPILE );

        glEnable( GL_TEXTURE_2D );
        glBindTexture( GL_TEXTURE_2D, t_textures[0] );

        glBegin( GL_QUADS );
            ///Tyl
            glNormal3f( 0.0f, 0.0f, 1.0f );

            glTexCoord2f(0, 1); glVertex3f(-1, -1, 1);
            glTexCoord2f(1, 1); glVertex3f(1, -1, 1);
            glTexCoord2f(1, 0); glVertex3f(1, 1, 1);
            glTexCoord2f(0, 0); glVertex3f(-1, 1, 1);

        glEnd();

        glDisable( GL_TEXTURE_2D );

    glEndList();

    ///Lista celownika
    list_cross = glGenLists( 1 );
    glNewList( list_cross, GL_COMPILE );

        glColor3fv( White );

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

        glEnable( GL_TEXTURE_2D );
        glBindTexture( GL_TEXTURE_2D, t_textures[1] );

        glBegin( GL_QUADS );

            glNormal3f( 0.0f, 0.0f, 1.0f );

            glTexCoord2f(0, 1); glVertex3f(-1, -1, 1);
            glTexCoord2f(1, 1); glVertex3f(1, -1, 1);
            glTexCoord2f(1, 0); glVertex3f(1, 1, 1);
            glTexCoord2f(0, 0); glVertex3f(-1, 1, 1);

        glEnd();

        glDisable( GL_TEXTURE_2D );

        glDisable( GL_BLEND );

    glEndList();

    ///lista zycia
    list_life = glGenLists( 1 );
    glNewList( list_life, GL_COMPILE );

        glColor3fv( White );

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

        glEnable( GL_TEXTURE_2D );
        glBindTexture( GL_TEXTURE_2D, t_textures[2] );

        glBegin( GL_QUADS );

            glNormal3f( 0.0f, 0.0f, 1.0f );

            glTexCoord2f(0, 1); glVertex3f(-1, -1, 1);
            glTexCoord2f(1, 1); glVertex3f(1, -1, 1);
            glTexCoord2f(1, 0); glVertex3f(1, 1, 1);
            glTexCoord2f(0, 0); glVertex3f(-1, 1, 1);

        glEnd();

        glDisable( GL_TEXTURE_2D );

        glDisable( GL_BLEND );

    glEndList();

    ///lista krwi
    list_blood = glGenLists( 1 );
    glNewList( list_blood, GL_COMPILE );

        glColor3fv( White );

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

        glEnable( GL_TEXTURE_2D );
        glBindTexture( GL_TEXTURE_2D, t_textures[3] );

        glBegin( GL_QUADS );

            glNormal3f( 0.0f, 0.0f, 1.0f );

            glTexCoord2f(0, 1); glVertex3f(-1, -1, 1);
            glTexCoord2f(1, 1); glVertex3f(1, -1, 1);
            glTexCoord2f(1, 0); glVertex3f(1, 1, 1);
            glTexCoord2f(0, 0); glVertex3f(-1, 1, 1);

        glEnd();

        glDisable( GL_TEXTURE_2D );

        glDisable( GL_BLEND );

    glEndList();

    list_dron = glGenLists( 1 );
    glNewList( list_dron, GL_COMPILE );

        glEnable( GL_LIGHTING );
        glEnable( GL_LIGHT0 );

        glEnable( GL_COLOR_MATERIAL );
        glColorMaterial( GL_FRONT, GL_AMBIENT );

        glEnable( GL_TEXTURE_2D );
        glBindTexture( GL_TEXTURE_2D, t_textures[4] );

        glRotatef( -90.0f, 1.0f, 0.0f, 0.0f );
        glScalef( 0.22f, 0.22f, 0.22f );

        glCallList( model_space_ship );

        glDisable( GL_TEXTURE_2D );


        glDisable( GL_COLOR_MATERIAL );
        glDisable( GL_LIGHTING );

    glEndList();

    list_award = glGenLists( 1 );
    glNewList( list_award, GL_COMPILE );

    glEnable( GL_TEXTURE_2D );
    glBindTexture( GL_TEXTURE_2D, t_textures[7] );

    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );

    glEnable( GL_COLOR_MATERIAL );
    glColorMaterial( GL_FRONT, GL_AMBIENT );

    glCallList( model_award );

    glDisable( GL_COLOR_MATERIAL );
    glDisable( GL_LIGHTING );

    glDisable( GL_TEXTURE_2D );

    glEndList();

    list_rock = glGenLists( 1 );
    glNewList( list_rock, GL_COMPILE );

        glEnable( GL_LIGHTING );
        glEnable( GL_LIGHT0 );

        glEnable( GL_COLOR_MATERIAL );
        glColorMaterial( GL_FRONT, GL_AMBIENT );

        glEnable( GL_TEXTURE_2D );
        glBindTexture( GL_TEXTURE_2D, t_textures[5] );

        glCallList( model_rock );

        glDisable( GL_TEXTURE_2D );

        glDisable( GL_COLOR_MATERIAL );
        glDisable( GL_LIGHTING );

    glEndList();

    list_bullet = glGenLists( 1 );
    glNewList( list_bullet, GL_COMPILE );

        glEnable( GL_TEXTURE_2D );
        glBindTexture( GL_TEXTURE_2D, t_textures[6] );

        glScaled(0.7,0.7,0.7);
        glCallList( model_bullet );

        glDisable( GL_TEXTURE_2D );

    glEndList();

    str = "Pobieranie rankingu...";
    pisz( app, str );

    if ( DownloadFile() ) {
        str = "Pobieranie zakonczone...";
    } else {
        str = "Nie udalo sie pobrac rankingu!";
    }

    pisz( app, str );

    while ( timer.GetElapsedSeconds() < 1.0f ){
        continue;
    }

    str = "Tworzenie rankingu...";
    pisz( app, str );

    std::ifstream fin( "ranking.txt" );

        if ( fin.good() ) {
            for ( int i = 0; i < 10; ++i ) {
                fin >> Top10[i].punkty;
                fin >> Top10[i].zycia;
                fin >> Top10[i].statki;
                fin >> Top10[i].nagrody_zdobyte;
                fin >> Top10[i].rozwalone_nagrody;
                fin >> Top10[i].rozbite_asteroidy;
                char ch;
                fin.get( ch );
                ch = 'p';
                while ( ch != '\n' && ch != '\r' ) {
                    fin.get( ch );
                    Top10[i].name += ch;
                }
            }
        } else {