Python之OpenGL笔记(19):正弦波叠加为方波的GLSL实现

一、目的

1、正弦波叠加为方波的GLSL实现;

二、程序运行结果

三、正弦波合成方波的处理

1、傅里叶函数分解方波公式:
  f(y) = 4/PI * (sinx+ sin3x/3 + sin5x/5 + ...);
2、实际程序里面公式为:
  f(y) = sinx+ sin3x/3 + sin5x/5 + ...
3、键盘控制
  加入了正弦波合成方波的处理,使用箭头键移动正弦波,使用上下箭头进行振幅调整,使用+,-号来调整正弦波叠加的次数。

四、源代码

"""
glfw_sin02.py
Author: dalong10
Description: Draw a SquareWave, learning OPENGL 
"""
import glutils    #Common OpenGL utilities,see glutils.py
import sys, random, math
import OpenGL
from OpenGL.GL import *
from OpenGL.GL.shaders import *
import numpy 
import numpy as np
import glfw

strVS = """
#version 330 core
layout (location = 0) in float vertexSerial;  
uniform int g_sinCnt;
uniform float g_rangeL;   
uniform float g_rangeR;
uniform float g_amplitud;
const int sampleCnt=200; 

vec2 createSinPostion(float posIdex,float factor,float amplitude, float rangeL, float rangeR)
{   vec2 sinPos;
    float range = rangeR - rangeL;
    sinPos.x = (2.0 * posIdex - sampleCnt)/sampleCnt; 
    sinPos.y = amplitude * sin(factor * (rangeL + posIdex * range / sampleCnt)); 
    return sinPos;
}

vec2 createSquareWave(float posIdex,int sinCnt, float amplitude, float rangeL, float rangeR) 
{   vec2 SquareWarvePos, sinPos;
    int i = 0;
    for (i = 0;i<100 ; i++) 
    {   int f = 2 * i + 1; 
        sinPos =createSinPostion(posIdex, 1.0 * f, 1.0 / f, rangeL, rangeR); 
        SquareWarvePos.x = sinPos.x; 
        SquareWarvePos.y += (sinPos.y * amplitude); 
        if (i>=sinCnt) return SquareWarvePos;
    }
    return SquareWarvePos;
}
void main(){
    vec2 SquareWarvePos  = createSquareWave(vertexSerial,g_sinCnt,g_amplitud,g_rangeL,g_rangeR); 
    gl_Position = vec4(SquareWarvePos,0.0,1.0);
    }
"""

strFS = """
#version 330 core
out vec3 color;
void main(){
    color = vec3(1,1,0);
    }
"""


class FirstSinCurve:
    def __init__(self):
        global sinCntIdx
        global rangeLIdx
        global rangeRIdx
        global amplitudIdx
        global g_sinCnt
        global g_rangeL
        global g_rangeR
        global g_amplitud
        sampleCnt=200
        # load shaders
        self.program = glutils.loadShaders(strVS, strFS)
        glUseProgram(self.program)
        # attributes
        sinCntIdx = glGetUniformLocation(self.program, "g_sinCnt");
        rangeLIdx = glGetUniformLocation(self.program, "g_rangeL");
        rangeRIdx = glGetUniformLocation(self.program, "g_rangeR");
        amplitudIdx = glGetUniformLocation(self.program, "g_amplitud");                  
        # set up VBOs
        vertexSerial = np.zeros(200, np.float32)
        for i in range(sampleCnt):
            vertexSerial[i] = i       
        self.vertexBuffer = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
        glBufferData(GL_ARRAY_BUFFER, 4*len(vertexSerial), vertexSerial, GL_STATIC_DRAW)
        # Position attribute
        glVertexAttribPointer(0, 1, GL_FLOAT, GL_FALSE, 0,None)
        # enable arrays
        glEnableVertexAttribArray(0)
  

    def render(self):       
        global sinCntIdx
        global rangeLIdx
        global rangeRIdx
        global amplitudIdx
        global g_sinCnt
        global g_rangeL
        global g_rangeR
        global g_amplitud
       # use shader
        sampleCnt=200
        glUseProgram(self.program)
        glUniform1i(sinCntIdx,g_sinCnt)
        glUniform1f(rangeLIdx,g_rangeL)
        glUniform1f(rangeRIdx,g_rangeR)
        glUniform1f(amplitudIdx,g_amplitud)
        # set up VBOs
        vertexSerial = np.zeros(200, np.float32)
        for i in range(sampleCnt):
            vertexSerial[i] = i
        
        self.vertexBuffer = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
        glBufferData(GL_ARRAY_BUFFER, 4*len(vertexSerial), vertexSerial, GL_STATIC_DRAW)

        # Position attribute
        glVertexAttribPointer(0, 1, GL_FLOAT, GL_FALSE, 0,None)
        # enable arrays
        glEnableVertexAttribArray(0)
        # draw
        glDrawArrays(GL_LINE_STRIP, 0, 200)
        glFlush()


if __name__ == '__main__':
    import sys
    import glfw
    import OpenGL.GL as gl
    global g_sinCnt
    global g_rangeL
    global g_rangeR
    global g_amplitud
    PI = 3.14159265358979323846264
    g_sinCnt = 5
    g_rangeL = -3 * PI
    g_rangeR = 3 * PI
    g_amplitud = 1.0

    def on_key(window, key, scancode, action, mods):
        global g_sinCnt
        global g_rangeL
        global g_rangeR
        global g_amplitud
        if action == glfw.PRESS:
            if key == glfw.KEY_ESCAPE :
                glfw.set_window_should_close(window,1)
            elif  key == glfw.KEY_KP_ADD or key == glfw.KEY_A:  
                if  (g_sinCnt < 100):
                    g_sinCnt+=1
            elif  key == glfw.KEY_KP_SUBTRACT or key == glfw.KEY_D:  
                if  (g_sinCnt >=1):
                    g_sinCnt-=1
            elif  key == glfw.KEY_UP:
                if  (g_amplitud < 2):
                    g_amplitud += 0.1
            elif  key == glfw.KEY_DOWN:
                if  (g_amplitud > 0.3):
                    g_amplitud -= 0.1
            elif  key == glfw.KEY_LEFT:
                g_rangeL -= 0.1
                g_rangeR -= 0.1
            elif  key == glfw.KEY_RIGHT:
                g_rangeL += 0.1
                g_rangeR += 0.1                                           
        print('g_sinCnt=',g_sinCnt)

    # Initialize the library
    if not glfw.init():
        sys.exit()

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(300, 300, "draw SquareWave ", None, None)
    if not window:
        glfw.terminate()
        sys.exit()

    # Make the window's context current
    glfw.make_context_current(window)
    # Install a key handler
    glfw.set_key_callback(window, on_key)
    # Loop until the user closes the window
    firstSinCurve0 = FirstSinCurve()        
    while not glfw.window_should_close(window):
        # Render here
        width, height = glfw.get_framebuffer_size(window)
        ratio = width / float(height)
        gl.glViewport(0, 0, width, height)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        gl.glClearColor(0.0,0.0,4.0,0.0)
        firstSinCurve0.render()                 
        # Swap front and back buffers
        glfw.swap_buffers(window)     
        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()

五、参考文献

1、他山随悟博客https://blog.csdn.net/t3swing/article/details/78471135

你可能感兴趣的:(Python之OpenGL笔记(19):正弦波叠加为方波的GLSL实现)