Mugichoko's blog

Mugichoko’s blog

プログラミングを中心としたメモ書き.

ModernGL奮闘記 (8) - αブレンディング -

今回はαブレンディングを実装する.単にQuadを半透明に表示する.

コード

以下のQuadを描画する回をベースとする.

mugichoko.hatenablog.com

  1. 上下キーでα値を設定し,シェーダプログラムに送る
  2. αブレンディングの設定を有効にしておく
    • self.window.ctx.blend_funcの部分参照
from pathlib import Path
import moderngl as mgl
import moderngl_window
from moderngl_window.conf import settings
from moderngl_window import resources
from moderngl_window.resources import programs
from moderngl_window.meta import ProgramDescription
from moderngl_window.scene.camera import Camera
import numpy as np


class Quad:
    def __init__(self, ctx: mgl.Context, prog: mgl.Program) -> None:
        self.prog = prog

        # Quad
        vertices = np.array([
            # x, y, u, v
            -0.5, -0.5, 0.0, 0.0,  # 0: Bottom left
            +0.5, -0.5, 1.0, 0.0,  # 1: Bottom right
            +0.5, +0.5, 1.0, 1.0,  # 2: Top right
            -0.5, +0.5, 0.0, 1.0,  # 3: Top left
        ], dtype="f4")
        indices = np.array([0, 1, 2, 3], dtype="i4")

        self.vbo = ctx.buffer(vertices)
        self.ibo = ctx.buffer(indices)

        vao_content = [(self.vbo, "2f 2f", "in_vert", "in_uv")]
        self.vao = ctx.vertex_array(self.prog, vao_content, self.ibo)

    def render(self, camera: Camera, alpha: float) -> None:
        self.prog["M"].write(np.identity(4, dtype="f4"))
        self.prog["V"].write(camera.matrix)
        self.prog["P"].write(camera.projection.matrix)
        self.prog["alpha"].write(np.array([alpha], dtype="f4"))
        self.vao.render(mgl.TRIANGLE_FAN)


class App:
    def __init__(self, width=512, height=512) -> None:
        # Window
        # create a gl window: https://moderngl-window.readthedocs.io/en/latest/reference/settings.conf.settings.html#moderngl_window.conf.Settings.WINDOW
        settings.WINDOW["class"] = "moderngl_window.context.glfw.Window"
        settings.WINDOW["gl_version"] = (4, 1)
        settings.WINDOW["size"] = (width, height)
        settings.WINDOW["aspect_ratio"] = width / height
        self.window = moderngl_window.create_window_from_settings()

        # Resources
        self.resource_dir = Path(__file__).parent.resolve() / "resources"
        resources.register_program_dir((self.resource_dir / "shaders").resolve())
        self.program = programs.load(
            ProgramDescription(
                vertex_shader="uv_alpha_vs.glsl", fragment_shader="uv_alpha_fs.glsl"
            )
        )

        # Camera
        self.camera = Camera(aspect_ratio=width / height, near=0.01, far=100.0)
        self.camera.set_position(0, 0.0, 1.5)
        self.camera.look_at(pos=(0, 0, 0))

        # Set key allback
        ## Ref: https://github.com/moderngl/moderngl-window/blob/master/examples/custom_config_class.py
        self.window.key_event_func = self.key_event

        # Quad mesh with a 2D texture array
        self.quad = Quad(self.window.ctx, self.program)
        self.alpha = 1.0  # initial alpha value

    def key_event(self, key, action, modifiers):
        keys = self.window.keys
        # Key pressed
        if action == keys.ACTION_PRESS:
            if key == keys.UP:
                self.alpha = min(self.alpha + 0.1, 1)
                print("UP: ", self.alpha)
            if key == keys.DOWN:
                self.alpha = max(self.alpha - 0.1, 0)
                print("Down: ", self.alpha)

    def run(self) -> None:
        while not self.window.is_closing:
            self.window.clear(0.5, 1.0, 0.25, 0.0)
            self.window.ctx.enable(mgl.DEPTH_TEST | mgl.CULL_FACE | mgl.BLEND)
            self.window.ctx.blend_func = (
                self.window.ctx.SRC_ALPHA,
                self.window.ctx.ONE_MINUS_SRC_ALPHA,
            )

            self.quad.render(self.camera, self.alpha)
            self.window.swap_buffers()


if __name__ == "__main__":
    app = App()
    app.run()

以下のシェーダは単にα値を受け取って,αチャンネルに書きだす,という内容.

// uv_alpha_vs.glsl
#version 330

uniform mat4 M; // model matrix
uniform mat4 V; // view matrix
uniform mat4 P; // projection matrix

in vec2 in_vert;
in vec2 in_uv;

out vec2 vs_uv;

void main()
{
    vs_uv = in_uv;
    gl_Position = P * V * M * vec4(in_vert, 0.0, 1.0);
}
// uv_alpha_fs.glsl
#version 330

in vec2 vs_uv;
out vec4 fs_color;

uniform float alpha;

void main()
{
    fs_color = vec4(vs_uv, 1.0, alpha);
}

結果

f:id:Mugichoko:20211120071354p:plain
左がα=1.0で右がα=0.6