码迷,mamicode.com
首页 > 其他好文 > 详细

outdated: 36.Radial Blur & Rendering To A Texture

时间:2016-09-24 13:28:00      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:

这种效果由ambient、position、diffuse和specular几种光在其背景贴图上实现。

在RenderToTexture()函数中ProcessHelix()函数为实现弹簧的光线效果,而在Draw()函数中的ProcessHelix()函数为实现弹簧实体。

RenderToTexture()函数中的glCopyTexImage2D()函数是从视觉窗口copy到一个二维贴图中,是对第一个ProcessHelix()函数效果的转换。

绘制弹簧实体代码如下,

技术分享
glBegin(GL_QUADS);
        for (phi = 0; phi <= 360; phi += 20.0f) {
            for (theta = 0; theta <= 360 * twists; theta += 20.0f) {
                // First
                v = phi / 180.0f * 3.1415f;                // rad
                u = theta / 180.0f * 3.1415f;              // rad

                x = float(cos(u) * (2.0f + cos(v))) * r;   // The coordniate of point 
                y = float(sin(u) * (2.0f + cos(v))) * r;
                z = float(((u - (2.0f * 3.1415f)) + sin(v)) * r);

                vertexes[0][0] = x;
                vertexes[0][1] = y;
                vertexes[0][2] = z;
                // Second
                v = phi / 180.0f * 3.1415f;
                u = (theta + 20) / 180.0f * 3.1415f;

                x = float(cos(u) * (2.0f + cos(v))) * r;   // The coordniate of point 
                y = float(sin(u) * (2.0f + cos(v))) * r;
                z = float(((u - (2.0f * 3.1415f)) + sin(v)) * r);

                vertexes[1][0] = x;
                vertexes[1][1] = y;
                vertexes[1][2] = z;
                // Third
                v = (phi + 20) / 180.0f * 3.1415f;
                u = (theta + 20) / 180.0f * 3.1415f;

                x = float(cos(u) * (2.0f + cos(v))) * r;   // The coordniate of point 
                y = float(sin(u) * (2.0f + cos(v))) * r;
                z = float(((u - (2.0f * 3.1415f)) + sin(v)) * r);

                vertexes[2][0] = x;
                vertexes[2][1] = y;
                vertexes[2][2] = z;
                // Fourth
                v = (phi + 20) / 180.0f * 3.1415f;
                u = theta / 180.0f * 3.1415f;

                x = float(cos(u) * (2.0f + cos(v))) * r;   // The coordniate of point 
                y = float(sin(u) * (2.0f + cos(v))) * r;
                z = float(((u - (2.0f * 3.1415f)) + sin(v)) * r);

                vertexes[3][0] = x;
                vertexes[3][1] = y;
                vertexes[3][2] = z;

                calcNormal(vertexes, normal);
                glNormal3f(normal[0], normal[1], normal[2]);// Set normal

                // Render
                glVertex3f(vertexes[0][0], vertexes[0][1], vertexes[0][2]);
                glVertex3f(vertexes[1][0], vertexes[1][1], vertexes[1][2]);
                glVertex3f(vertexes[2][0], vertexes[2][1], vertexes[2][2]);
                glVertex3f(vertexes[3][0], vertexes[3][1], vertexes[3][2]);
            }
        }
    glEnd();
弹簧

背景贴图,

技术分享
alphainc = alpha / times;                      // To render blur
    glBegin(GL_QUADS);
        for (int num = 0; num < times; ++num) {
            glColor4f(1.0f, 1.0f, 1.0f, alpha);
            glTexCoord2f(0 + spost, 1 - spost);
            glVertex2f(0, 0);

            glTexCoord2f(0 + spost, 0 + spost);
            glVertex2f(0, 480);

            glTexCoord2f(1 - spost, 0 + spost);
            glVertex2f(640, 480);

            glTexCoord2f(1 - spost, 1 - spost);
            glVertex2f(640, 0);

            spost += inc;                          // Zooming closer to texture center
            alpha -= alphainc;                     // Gradually fading image out
        }
    glEnd();
BlurTexture

技术分享

代码如下,

技术分享
#ifndef GL_FRAMEWORK_INCLUDED
#define GL_FRAMEWORK_INCLUDED

#include <windows.h>

typedef struct {                                   // Structure for keyboard stuff
    BOOL keyDown[256];
} Keys;

typedef struct {                                   // Contains information vital to applications 
    HMODULE hInstance;                             // Application Instance
    const char* className;
} Application;

typedef struct {                                   // Window creation info
    Application* application;
    char* title;
    int width;
    int height;
    int bitsPerPixel;
    BOOL isFullScreen;
} GL_WindowInit;

typedef struct {                                   // Contains information vital to a window
    Keys* keys;
    HWND hWnd;                                     // Windows handle
    HDC hDC;                                       // Device context
    HGLRC hRC;                                     // Rendering context
    GL_WindowInit init;
    BOOL isVisible;                                // Window visiable?
    DWORD lastTickCount;                           // Tick counter
} GL_Window;

void TerminateApplication(GL_Window* window);      // Terminate the application

void ToggleFullscreen(GL_Window* window);          // Toggle fullscreen / Windowed mode

BOOL Initialize(GL_Window* window, Keys* keys);

void Deinitialize(void);

void Update(DWORD milliseconds);

void Draw(void);

#endif
Previous.h
技术分享
#include <Windows.h>
#include <GL\glew.h>
#include <GL\glut.h>
#include "Previous.h"

#define WM_TOGGLEFULLSCREEN (WM_USER+1)                   // Application define message for toggling 
// between fulscreen / windowed mode
static BOOL g_isProgramLooping;                           // Window creation loop, for fullscreen / windowed mode
static BOOL g_createFullScreen;                           // If true, then create window

void TerminateApplication(GL_Window* window)              // Terminate the application
{
    PostMessage(window->hWnd, WM_QUIT, 0, 0);             // Send a WM_QUIT message
    g_isProgramLooping = FALSE;                           // Stop looping of the program
}

void ToggleFullscreen(GL_Window* window)                  // Toggle fullscreen /windowed mode
{
    PostMessage(window->hWnd, WM_TOGGLEFULLSCREEN, 0, 0); // Send a WM_TOGGLEFULLSCREEN message
}

void ReshapeGL(int width, int height)                     // Reshape the window  when it‘s moved or resized
{
    glViewport(0, 0, (GLsizei)(width), (GLsizei)(height)); // Reset the current viewport
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    // Calcutate the aspect ratio of the window
    gluPerspective(45.0f, (GLfloat)(width) / (GLfloat)(height), 1.0, 100.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

BOOL ChangeScreenResolution(int width, int height, int bitsPerPixel)     // Change the screen resolution
{
    DEVMODE dmScreenSettings;                              // Device mode
    ZeroMemory(&dmScreenSettings, sizeof(DEVMODE));        // Make sure memory is cleared
    dmScreenSettings.dmSize = sizeof(DEVMODE);             // Size of the devmode structure
    dmScreenSettings.dmPelsWidth = width;
    dmScreenSettings.dmPelsHeight = height;
    dmScreenSettings.dmBitsPerPel = bitsPerPixel;
    dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
    if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
        return FALSE;                                      // Display change failed
    }
    return TRUE;
}

BOOL CreateWindowGL(GL_Window* window)
{
    DWORD windowStyle = WS_OVERLAPPEDWINDOW;                // Define window style
    DWORD windowExtendedStyle = WS_EX_APPWINDOW;            // Define the window‘s extended style

    PIXELFORMATDESCRIPTOR pdf = {
        sizeof(PIXELFORMATDESCRIPTOR),                      // Size of this pixel format descriptor
        1,                                                  // Version Number
        PFD_DRAW_TO_WINDOW |                                // Format must support window
        PFD_SUPPORT_OPENGL |                                // Format must support openGL
        PFD_DOUBLEBUFFER,                                   // Must support double buffering
        PFD_TYPE_RGBA,                                      // Request an RGBA format
        window->init.bitsPerPixel,                          // Select color depth
        0, 0, 0, 0, 0, 0,                                   // Color bits ignored
        0,                                                  // No alpha buffer
        0,                                                  // Shift bit ignored
        0,                                                  // No accumulation buffer
        0, 0, 0, 0,                                         // Accumulation bits ignored
        16,                                                 // 16bits Z-buffer (depth buffer)
        0,                                                  // No stencil buffer
        0,                                                  // No auxiliary buffer
        PFD_MAIN_PLANE,                                     // Main drawing layer
        0,                                                  // Reserved
        0, 0, 0                                             // Layer masks ignored
    };
    RECT windowRect = { 0, 0, window->init.width, window->init.height };   // Window coordiantes

    GLuint PixelFormat;

    if (window->init.isFullScreen == TRUE) {
        if (ChangeScreenResolution(window->init.width, window->init.height, window->init.bitsPerPixel) == FALSE)
        {
            // Fullscreen mode failed, run in windowed mode instead
            MessageBox(HWND_DESKTOP, "Mode Switch Failed.\nRuning In Windowed Mode.",
                "Error", MB_OK | MB_ICONEXCLAMATION);
            window->init.isFullScreen = FALSE;
        }
        else {
            ShowCursor(FALSE);
            windowStyle = WS_POPUP;                         // Popup window
            windowExtendedStyle |= WS_EX_TOPMOST;
        }
    }
    else {
        // Adjust window, account for window borders
        AdjustWindowRectEx(&windowRect, windowStyle, 0, windowExtendedStyle);
    }
    // Create Opengl window
    window->hWnd = CreateWindowEx(windowExtendedStyle,      // Extended style
        window->init.application->className,                // Class name
        window->init.title,                                 // Window title
        windowStyle,                                        // Window style
        0, 0,                                               // Window X,Y position
        windowRect.right - windowRect.left,                 // Window width
        windowRect.bottom - windowRect.top,                 // Window height
        HWND_DESKTOP,                                       // Desktop is window‘s parent
        0,                                                  // No menu
        window->init.application->hInstance,                // Pass the window instance
        window);

    if (window->hWnd == 0) {                                // Was window creation a success?
        return FALSE;
    }
    window->hDC = GetDC(window->hWnd);
    if (window->hDC == 0) {
        DestroyWindow(window->hWnd);
        window->hWnd = 0;
        return FALSE;
    }
    PixelFormat = ChoosePixelFormat(window->hDC, &pdf);     // Find a compatible pixel format
    if (PixelFormat == 0) {
        ReleaseDC(window->hWnd, window->hDC);               // Release device context
        window->hDC = 0;
        DestroyWindow(window->hWnd);
        window->hWnd = 0;
        return FALSE;
    }
    if (SetPixelFormat(window->hDC, PixelFormat, &pdf) == FALSE) {   // Try to set the pixel format
        ReleaseDC(window->hWnd, window->hDC);
        window->hDC = 0;
        DestroyWindow(window->hWnd);
        window->hWnd = 0;
        return FALSE;
    }
    window->hRC = wglCreateContext(window->hDC);            // Try to get a rendering context
    if (window->hRC == 0) {
        ReleaseDC(window->hWnd, window->hDC);
        window->hDC = 0;
        DestroyWindow(window->hWnd);
        window->hWnd = 0;
        return FALSE;
    }
    // Make the rendering context our current rendering context
    if (wglMakeCurrent(window->hDC, window->hRC) == FALSE) {
        wglDeleteContext(window->hRC);                      //  Delete the rendering context
        window->hRC = 0;
        ReleaseDC(window->hWnd, window->hDC);
        window->hDC = 0;
        DestroyWindow(window->hWnd);
        window->hWnd = 0;
        return FALSE;
    }
    ShowWindow(window->hWnd, SW_NORMAL);                    // Make the window visiable
    window->isVisible = TRUE;
    ReshapeGL(window->init.width, window->init.height);     // Reshape our GL window
    ZeroMemory(window->keys, sizeof(Keys));                 // Clear all keys
    window->lastTickCount = GetTickCount();
    return TRUE;
}

BOOL DestoryWindowGL(GL_Window* window)
{
    if (window->hWnd != 0) {
        if (window->hDC != 0) {
            wglMakeCurrent(window->hDC, 0);                 // Setting current active rendering context to zero
            if (window->hRC != 0) {
                wglDeleteContext(window->hRC);
                window->hRC = 0;
            }
            ReleaseDC(window->hWnd, window->hDC);
            window->hDC = 0;
        }
        DestroyWindow(window->hWnd);
        window->hWnd = 0;
    }
    if (window->init.isFullScreen) {
        ChangeDisplaySettings(NULL, 0);                     // Switch back to desktop resolution
        ShowCursor(TRUE);
    }
    return TRUE;
}

// Process window message callback
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    // Get the window context
    GL_Window* window = (GL_Window*)(GetWindowLong(hWnd, GWL_USERDATA));
    switch (uMsg) {                                         // Evaluate window message
    case WM_SYSCOMMAND:                                     // Intercept system commands
    {
        switch (wParam) {                                   // Check system calls
        case SC_SCREENSAVE:                                 // Screensaver trying to start?
        case SC_MONITORPOWER:                               // Mointer trying to enter powersave?
            return 0;                                           // Prevent form happening
        }
        break;
    }
    return 0;
    case WM_CREATE:
    {
        CREATESTRUCT* creation = (CREATESTRUCT*)(lParam);   // Store window structure pointer
        window = (GL_Window*)(creation->lpCreateParams);
        SetWindowLong(hWnd, GWL_USERDATA, (LONG)(window));
    }
    return 0;

    case WM_CLOSE:
        TerminateApplication(window);
        return 0;

    case WM_SIZE:
        switch (wParam) {
        case SIZE_MINIMIZED:                                 // Was window minimized?
            window->isVisible = FALSE;
            return 0;
        case SIZE_MAXIMIZED:
            window->isVisible = TRUE;
            ReshapeGL(LOWORD(lParam), HIWORD(lParam));
            return 0;
        case SIZE_RESTORED:
            window->isVisible = TRUE;
            ReshapeGL(LOWORD(lParam), HIWORD(lParam));
            return 0;
        }
        break;

    case WM_KEYDOWN:
        if ((wParam >= 0) && (wParam <= 255)) {
            window->keys->keyDown[wParam] = TRUE;            // Set the selected key(wParam) to true
            return 0;
        }
        break;

    case WM_KEYUP:
        if ((wParam >= 0) && (wParam <= 255)) {
            window->keys->keyDown[wParam] = FALSE;
            return 0;
        }
        break;

    case WM_TOGGLEFULLSCREEN:
        g_createFullScreen = (g_createFullScreen == TRUE) ? FALSE : TRUE;
        PostMessage(hWnd, WM_QUIT, 0, 0);
        break;
    }
    return DefWindowProc(hWnd, uMsg, wParam, lParam);        // Pass unhandle message to DefWindowProc
}

BOOL RegisterWindowClass(Application* application)
{
    WNDCLASSEX windowClass;
    ZeroMemory(&windowClass, sizeof(WNDCLASSEX));            // Make sure memory is cleared
    windowClass.cbSize = sizeof(WNDCLASSEX);                 // Size of the windowClass structure
    windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;  // Redraws the window for any movement / resizing
    windowClass.lpfnWndProc = (WNDPROC)(WindowProc);         // WindowProc handles message
    windowClass.hInstance = application->hInstance;          // Set the instance
    windowClass.hbrBackground = (HBRUSH)(COLOR_APPWORKSPACE);// Class background brush color
    windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);       // Load the arrow pointer
    windowClass.lpszClassName = application->className;      // Sets the application className
    if (RegisterClassEx(&windowClass) == 0) {
        MessageBox(HWND_DESKTOP, "RegisterClassEx Failed!", "Error", MB_OK | MB_ICONEXCLAMATION);
        return FALSE;
    }
    return TRUE;
}

int WINAPI WinMain(HINSTANCE hIstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    Application application;
    GL_Window window;
    Keys keys;
    BOOL isMessagePumpActive;
    MSG msg;
    DWORD tickCount;

    application.className = "OpenGL";
    application.hInstance = hIstance;

    ZeroMemory(&window, sizeof(GL_Window));
    window.keys = &keys;                                     // Window key structure
    window.init.application = &application;                  // Window application
    window.init.title = "GL Framework";                           // Window title
    window.init.width = 640;                                 // Window width
    window.init.height = 480;                                // Window height
    window.init.bitsPerPixel = 32;                           // Bits per pixel
    window.init.isFullScreen = TRUE;                         // Fullscreen? (set to TRUE)

    ZeroMemory(&keys, sizeof(Keys));
    if (MessageBox(HWND_DESKTOP, "Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",
        MB_YESNO | MB_ICONQUESTION) == IDNO)
    {
        window.init.isFullScreen = FALSE;
    }
    if (RegisterWindowClass(&application) == FALSE)
    {
        MessageBox(HWND_DESKTOP, "Error Registering Window Class!", "Error", MB_OK | MB_ICONEXCLAMATION);
        return -1;
    }
    g_isProgramLooping = TRUE;
    g_createFullScreen = window.init.isFullScreen;
    while (g_isProgramLooping) {                             // Loop until WM_QUIT is received
        window.init.isFullScreen = g_createFullScreen;       // Set init param of window creation to fullscreen?
        if (CreateWindowGL(&window) == TRUE) {               // Was window creation successful?
                                                             // At this point we should have a window that is setup to render OpenGL
            if (Initialize(&window, &keys) == FALSE) {
                TerminateApplication(&window);               // Close window, this will handle the shutdown
            }
            else {
                isMessagePumpActive = TRUE;
                while (isMessagePumpActive == TRUE) {
                    // Success creating window. Check for window messages
                    if (PeekMessage(&msg, window.hWnd, 0, 0, PM_REMOVE) != 0) {
                        if (msg.message != WM_QUIT) {
                            DispatchMessage(&msg);
                        }
                        else {
                            isMessagePumpActive = FALSE;     // Terminate the message pump
                        }
                    }
                    else {
                        if (window.isVisible == FALSE) {
                            WaitMessage();                   // Application is minimized wait for a message
                        }
                        else {
                            // Process application loop
                            tickCount = GetTickCount();      // Get the tick count
                            Update(tickCount - window.lastTickCount); // Update the counter
                            window.lastTickCount = tickCount;// Set last count to current count
                            Draw();                          // Draw screen
                            SwapBuffers(window.hDC);
                        }
                    }
                }
            }
            // Application is finished
            Deinitialize();
            DestoryWindowGL(&window);
        }
        else {
            MessageBox(HWND_DESKTOP, "Error Creating OpenGL Window", "Error", MB_OK | MB_ICONEXCLAMATION);
            g_isProgramLooping = FALSE;
        }
    }
    UnregisterClass(application.className, application.hInstance);    // UnRegister window class
    return 0;
}
Previous.cpp
技术分享
#include <Windows.h>
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/GLUAX.H>
#include <math.h>
#include "Previous.h"


#ifndef CDS_FULLSCREEN
#define CDS_FULLSCREEN 4
#endif

GL_Window* g_window;
Keys* g_keys;

float angle;                    // Used to rotate the helix
float vertexes[4][3];
float normal[3];
GLuint BlurTexture;             // Stored the texture number

GLuint EmptyTexture()           // Create a empty texture
{
    GLuint textureID;
    unsigned int* data;
    
    data = (unsigned int*)malloc(128 * 128 * 4 * sizeof(unsigned int));
    ZeroMemory(data, (128 * 128 * 4 * sizeof(unsigned int)));

    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_2D, textureID);
    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, 4, 128, 128, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

    free(data);
    return textureID;
}

void ReduceToUnit(float vector[3])            // Reduce a normal vector
{
    float length;
    length = (float)sqrt((vector[0] * vector[0]) * (vector[1] * vector[1]) * (vector[2] * vector[2]));
    
    if (length == 0.0f)
        length = 1.0f;
    vector[0] /= length;
    vector[1] /= length;
    vector[2] /= length;
}

void calcNormal(float v[3][3], float out[3])        //Calculates normal for a quad using 3 points
{
    float v1[3], v2[3];
    static const int x = 0;                         // Coordinate
    static const int y = 0;
    static const int z = 0;

    // Finds the vector bewteen 2 points
    v1[x] = v[0][x] - v[1][x];
    v1[y] = v[0][y] - v[1][y];
    v1[z] = v[0][z] - v[1][z];

    v2[x] = v[1][x] - v[2][x];
    v2[y] = v[1][y] - v[2][y];
    v2[z] = v[1][z] - v[2][z];

    out[x] = v1[y] * v2[z] - v1[z] * v2[y];          // Cross product for Y - Z
    out[y] = v1[z] * v2[x] - v1[x] * v2[z];          // Cross product for X - Z
    out[z] = v1[x] * v2[y] - v1[y] * v2[x];          // Cross product for X - Y

    ReduceToUnit(out);
}

void ProcessHelix()               // Draw a helix
{
    GLfloat x, y, z;              // Coordniate
    GLfloat phi;                  // Angle
    GLfloat theta;                // Angle
    GLfloat v, u;                 // Angles
    GLfloat r = 1.5;              // Radius of twist
    int twists = 5;               // Numbers

    GLfloat glfMaterialColor[] = { 0.4f, 0.2f, 0.8f, 1.0f };        // The material color
    GLfloat specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };                // Specular lighting

    glLoadIdentity();
    gluLookAt(0, 5, 50, 0, 0, 0, 0, 1, 0);
    glPushMatrix();
    
    glTranslatef(0, 0, -50);
    glRotatef(angle / 2.0f, 1, 0, 0);
    glRotatef(angle / 3.0f, 0, 1, 0);

    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, glfMaterialColor);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular);

    glBegin(GL_QUADS);
        for (phi = 0; phi <= 360; phi += 20.0f) {
            for (theta = 0; theta <= 360 * twists; theta += 20.0f) {
                // First
                v = phi / 180.0f * 3.1415f;                // rad
                u = theta / 180.0f * 3.1415f;              // rad

                x = float(cos(u) * (2.0f + cos(v))) * r;   // The coordniate of point 
                y = float(sin(u) * (2.0f + cos(v))) * r;
                z = float(((u - (2.0f * 3.1415f)) + sin(v)) * r);

                vertexes[0][0] = x;
                vertexes[0][1] = y;
                vertexes[0][2] = z;
                // Second
                v = phi / 180.0f * 3.1415f;
                u = (theta + 20) / 180.0f * 3.1415f;

                x = float(cos(u) * (2.0f + cos(v))) * r;   // The coordniate of point 
                y = float(sin(u) * (2.0f + cos(v))) * r;
                z = float(((u - (2.0f * 3.1415f)) + sin(v)) * r);

                vertexes[1][0] = x;
                vertexes[1][1] = y;
                vertexes[1][2] = z;
                // Third
                v = (phi + 20) / 180.0f * 3.1415f;
                u = (theta + 20) / 180.0f * 3.1415f;

                x = float(cos(u) * (2.0f + cos(v))) * r;   // The coordniate of point 
                y = float(sin(u) * (2.0f + cos(v))) * r;
                z = float(((u - (2.0f * 3.1415f)) + sin(v)) * r);

                vertexes[2][0] = x;
                vertexes[2][1] = y;
                vertexes[2][2] = z;
                // Fourth
                v = (phi + 20) / 180.0f * 3.1415f;
                u = theta / 180.0f * 3.1415f;

                x = float(cos(u) * (2.0f + cos(v))) * r;   // The coordniate of point 
                y = float(sin(u) * (2.0f + cos(v))) * r;
                z = float(((u - (2.0f * 3.1415f)) + sin(v)) * r);

                vertexes[3][0] = x;
                vertexes[3][1] = y;
                vertexes[3][2] = z;

                calcNormal(vertexes, normal);
                glNormal3f(normal[0], normal[1], normal[2]);// Set normal

                // Render
                glVertex3f(vertexes[0][0], vertexes[0][1], vertexes[0][2]);
                glVertex3f(vertexes[1][0], vertexes[1][1], vertexes[1][2]);
                glVertex3f(vertexes[2][0], vertexes[2][1], vertexes[2][2]);
                glVertex3f(vertexes[3][0], vertexes[3][1], vertexes[3][2]);
            }
        }
    glEnd();
    glPopMatrix();
}

void ViewOrtho()                  // Set up an ortho view
{
    glMatrixMode(GL_PROJECTION);  // Select projection
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0, 640, 480, 0, -1, 1);   // Select ortho mode
    glMatrixMode(GL_MODELVIEW);       // Select modelview matrix
    glPushMatrix();
    glLoadIdentity();
}

void ViewPerspective()                // Set up a perspective view
{
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
}


void RenderToTexture()                // Render to a texture
{
    glViewport(0, 0, 128, 128);       // Set viewport (match texture size)
    ProcessHelix();                   // Render the helix
    glBindTexture(GL_TEXTURE_2D, BlurTexture);
    //Copy  viewport to the blur texture (from 0, 0 to 128, 128...No border)
    glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 0, 0, 128, 128, 0);
    glClearColor(0.0f, 0.0f, 0.4f, 0.5f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glViewport(0, 0, 640, 480);
}

void DrawBlur(int times, float inc)     // Draw the blurred image
{
    float spost = 0.0f;                 // Starting texture coordinate offset
    float alphainc = 0.0f / times;      // Fade speed for alpha blending
    float alpha = 0.2f;                 // Starting alpha value

    // Disable autoTexture cordinates
    glDisable(GL_TEXTURE_GEN_S);
    glDisable(GL_TEXTURE_GEN_T);

    glEnable(GL_TEXTURE_2D);
    glDisable(GL_DEPTH_TEST);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE);
    glEnable(GL_BLEND);
    glBindTexture(GL_TEXTURE_2D, BlurTexture);

    ViewOrtho();

    alphainc = alpha / times;                      // To render blur
    glBegin(GL_QUADS);
        for (int num = 0; num < times; ++num) {
            glColor4f(1.0f, 1.0f, 1.0f, alpha);
            glTexCoord2f(0 + spost, 1 - spost);
            glVertex2f(0, 0);

            glTexCoord2f(0 + spost, 0 + spost);
            glVertex2f(0, 480);

            glTexCoord2f(1 - spost, 0 + spost);
            glVertex2f(640, 480);

            glTexCoord2f(1 - spost, 1 - spost);
            glVertex2f(640, 0);

            spost += inc;                          // Zooming closer to texture center
            alpha -= alphainc;                     // Gradually fading image out
        }
    glEnd();
    
    ViewPerspective();

    glEnable(GL_DEPTH_TEST);
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_BLEND);
    glBindTexture(GL_TEXTURE_2D, 0);
}

BOOL Initialize(GL_Window* window, Keys* keys)             // Any GL init code & User initialiazation goes here
{
    g_window = window;
    g_keys = keys;

    angle = 0.0f;
    BlurTexture = EmptyTexture();
    glViewport(0, 0, window->init.width, window->init.height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50, (float)window->init.width / (float)window->init.height, 5, 2000);  // Set perspective
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glEnable(GL_DEPTH_TEST);

    GLfloat global_ambient[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
    GLfloat light0pos[4] = { 0.0f, 5.0f, 10.0f, 1.0f };
    GLfloat light0ambient[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
    GLfloat light0diffuse[4] = { 0.3f, 0.3f, 0.3f, 1.0f };
    GLfloat light0specular[4] = { 0.8f, 0.8f, 0.8f, 1.0f };

    GLfloat lmodel_ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);    // Set the model

    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient);
    glLightfv(GL_LIGHT0, GL_POSITION, light0pos);
    glLightfv(GL_LIGHT0, GL_AMBIENT, light0ambient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light0diffuse);
    glLightfv(GL_LIGHT0, GL_SPECULAR, light0specular);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glShadeModel(GL_SMOOTH);
    glMateriali(GL_FRONT, GL_SHININESS, 128);
    glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
    return TRUE;
}

void Deinitialize(void)
{
    glDeleteTextures(1, &BlurTexture);
}

void Update(DWORD milliseconds)                 // Perform motion updates here
{
    if (g_keys->keyDown[VK_ESCAPE] == TRUE) {
        TerminateApplication(g_window);
    }
    if (g_keys->keyDown[VK_F1] == TRUE) {
        ToggleFullscreen(g_window);
    }
    angle += (float)(milliseconds) / 5.0f;
}

void Draw(void)
{
    glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    RenderToTexture();
    ProcessHelix();
    DrawBlur(25, 0.02f);
    glFlush();
}
Main.cpp

 

outdated: 36.Radial Blur & Rendering To A Texture

标签:

原文地址:http://www.cnblogs.com/clairvoyant/p/5902931.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!