Python之OpenGL笔记(18):正弦波的绘制

一、目的

1、正弦函数的基本画法;
2、GLSL方式实现练习。

二、程序运行结果

三、glDrawArrays 函数

  GLSL画这些基本的类型使用的函数主要是glDraw*系列的函数:

void  glDrawArrays (GLenum mode, GLint first, GLsizei count);

  mode有以下类型,画点GL_POINTS,画线 GL_LINES,顺连线段GL_LINE_STRIP,回环线段GL_LINE_LOOP,三角形GL_TRIANGLES,GL_TRIANGLE_STRIP,GL_TRIANGLE_FAN,四边形GL_QUADS,GL_QUAD_STRIP,多边形GL_POLYGON。
  first为0即可,
  count表示要绘制顶点的个数。

四、正弦波绘制

  正弦波公式是y = sin(x ) ,通过描点画出图形。需确定了以下几个参数来画正弦波:
  1. sampleCnt:采样点个数,openGL画东西都采用逼近的方式,采样点越多,正弦波就越精细。
  2. factor:用来控制正弦波的频率,如sin(2x ),sin(3x ) 等。
  3. amplitude:振幅,用来控制正弦波的振幅,如3sin(2x )。
  4. rangeL:我们要把正弦波映射到[-1.0,1.0]的范围内,否则画出来的正弦波都看不到。
  5. rangeR:如传的-pi~pi的范围,会把这个范围的正弦波映射到[-1.0,1.0]范围内。
  注意:shader里面y坐标统一乘了0.9,主要是避免图形顶到边框。

五、源代码

"""
glfw_sin01.py
Author: dalong10
Description: Draw a Sine curve, 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 vec2 position;
void main(){
	gl_Position = vec4(position.x,position.y*0.9,0.0,1.0);
	}
"""

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

def createSinArray(sampleCnt, factor, amplitude, rangeL,rangeR):
    i = 0
    range0 = rangeR-rangeL
    if ((sampleCnt<=4) or (rangeR <= rangeL)):
        print("param error sampleCnt:%d rangeR:%f rangeL:%f\n",sampleCnt,rangeL,rangeR)
        return 
    array0 =np.zeros(sampleCnt*2, np.float32)
    for i in range(sampleCnt):
        array0[i*2] = (2.0*i-sampleCnt)/sampleCnt  # x
        array0[i*2+1] = amplitude * math.sin(factor*(rangeL+i*range0/sampleCnt)) # y
    return array0


class FirstSinCurve:
    def __init__(self, side):
        self.side = side

        # load shaders
        self.program = glutils.loadShaders(strVS, strFS)
        glUseProgram(self.program)             
        # set up VBOs
        vertexData = createSinArray(200, 1.0,1.0,-3*PI,3 * PI)
        self.vertexBuffer = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
        glBufferData(GL_ARRAY_BUFFER, 4*len(vertexData), vertexData, GL_STATIC_DRAW)
        # set up vertex array object (VAO)
        self.vao = glGenVertexArrays(1)
        glBindVertexArray(self.vao)
        glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, None)
        glEnableVertexAttribArray(0)
        # unbind VAO
        glBindVertexArray(0)
        glBindBuffer(GL_ARRAY_BUFFER, 0)    

    def render(self):       
        # use shader
        glUseProgram(self.program)
        # bind VAO
        glBindVertexArray(self.vao)
        # draw
        glDrawArrays(GL_LINE_STRIP, 0, 200)
        # unbind VAO
        glBindVertexArray(0)

if __name__ == '__main__':
    import sys
    import glfw
    import OpenGL.GL as gl
    def on_key(window, key, scancode, action, mods):
        if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
            glfw.set_window_should_close(window,1)

    # 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 Sine Curve0 ", 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)
    PI = 3.14159265358979323846264
    # Loop until the user closes the window
    firstSinCurve0 = FirstSinCurve(1.0)        
    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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值