File: quad.py

package info (click to toggle)
python-moderngl-window 2.4.6-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 69,220 kB
  • sloc: python: 11,387; makefile: 21
file content (85 lines) | stat: -rw-r--r-- 2,552 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import numpy

import moderngl
from moderngl_window.opengl.vao import VAO
from moderngl_window.geometry.attributes import AttributeNames


def quad_fs(attr_names=AttributeNames, normals=True, uvs=True, name=None) -> VAO:
    """
    Creates a screen aligned quad using two triangles with normals and texture coordinates.

    Keyword Args:
        attr_names (AttributeNames): Attrib name config
        normals (bool): Include normals in VAO
        uvs (bool): Include texture coordinates in VAO
        name (str): Optional name for the VAO
    Returns:
        A :py:class:`~moderngl_window.opengl.vao.VAO` instance.
    """
    return quad_2d(
        size=(2.0, 2.0), normals=normals, uvs=uvs, attr_names=attr_names, name=name,
    )


def quad_2d(
    size=(1.0, 1.0),
    pos=(0.0, 0.0),
    normals=True,
    uvs=True,
    attr_names=AttributeNames,
    name=None,
) -> VAO:
    """
    Creates a 2D quad VAO using 2 triangles with normals and texture coordinates.

    Keyword Args:
        size (tuple): width and height
        pos (float): Center position x and y
        normals (bool): Include normals in VAO
        uvs (bool): Include texture coordinates in VAO
        attr_names (AttributeNames): Attrib name config
        name (str): Optional name for the VAO
    Returns:
        A :py:class:`~moderngl_window.opengl.vao.VAO` instance.
    """
    width, height = size
    xpos, ypos = pos

    # fmt: off
    pos_data = numpy.array([
        xpos - width / 2.0, ypos + height / 2.0, 0.0,
        xpos - width / 2.0, ypos - height / 2.0, 0.0,
        xpos + width / 2.0, ypos - height / 2.0, 0.0,
        xpos - width / 2.0, ypos + height / 2.0, 0.0,
        xpos + width / 2.0, ypos - height / 2.0, 0.0,
        xpos + width / 2.0, ypos + height / 2.0, 0.0,
    ], dtype=numpy.float32)

    normal_data = numpy.array([
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
    ], dtype=numpy.float32)

    uv_data = numpy.array([
        0.0, 1.0,
        0.0, 0.0,
        1.0, 0.0,
        0.0, 1.0,
        1.0, 0.0,
        1.0, 1.0,
    ], dtype=numpy.float32)
    # fmt: on

    vao = VAO(name or "geometry:quad", mode=moderngl.TRIANGLES)
    vao.buffer(pos_data, "3f", [attr_names.POSITION])
    if normals:
        vao.buffer(normal_data, "3f", [attr_names.NORMAL])
    if uvs:
        vao.buffer(uv_data, "2f", [attr_names.TEXCOORD_0])

    return vao