# CS 453, lecture 25: the same triangle, with a colour at each corner.
#
# Differs from triangle.py in three places only: each corner in the
# buffer carries a colour too (part 1), the SHADER hands that colour on
# (part 2), and corner_layout describes the longer corner (part 3).
# The GPU blends the three colours across the triangle (by lecture 24's
# weights) before fs_main sees them.
#
# Run it:          python triangle_colours.py
# No GPU found?    WGPU_BACKEND_TYPE=OpenGL python triangle_colours.py
# (Tested with wgpu 0.32.0 and rendercanvas 2.7.2.)

import numpy as np                                   # arrays of numbers
import wgpu                                          # Python's door to the GPU
from rendercanvas.auto import RenderCanvas, loop     # a window to draw in


# ============================================================================
# 1. THE TRIANGLE (made in Python, copied to the GPU in part 3)
#
#    Three corners, (x, y, red, green, blue) each. Screen positions run
#    from -1 to 1: (-1, -1) is the bottom-left corner of the window.
# ============================================================================
corners = np.array([
    [-0.5, -0.5,   1.0, 0.0, 0.0],     # corner 0: bottom left, red
    [ 0.5, -0.5,   0.0, 1.0, 0.0],     # corner 1: bottom right, green
    [ 0.0,  0.5,   0.0, 0.0, 1.0],     # corner 2: top, blue
], dtype=np.float32)                   # each number: a 4-byte decimal


# ============================================================================
# 2. THE SHADER (WGSL, runs on the GPU)
#
#    vs_main runs once for each corner: it says WHERE that corner goes, and
#    hands on that corner's COLOUR.
#    fs_main runs once for each pixel inside the triangle. It receives a
#    colour already blended from the three corners, and uses it.
# ============================================================================
SHADER = """
// What vs_main hands on for each corner: its position and its colour.
struct Corner {
    @builtin(position) pos: vec4f,
    @location(0) colour: vec3f,
};

@vertex
fn vs_main(@location(0) xy: vec2f,
           @location(1) colour: vec3f) -> Corner {
    var out: Corner;
    out.pos = vec4f(xy.x, xy.y, 0.0, 1.0);
    out.colour = colour;
    return out;
}

@fragment
fn fs_main(@location(0) colour: vec3f)
        -> @location(0) vec4f {
    // colour arrives blended from the three corners.
    return vec4f(colour.r, colour.g, colour.b, 1.0);
}
"""


# ============================================================================
# 3. SETUP (runs once, before the first picture)
# ============================================================================

# Pick a GPU. A laptop may have two; we ask for the fast one.
adapter = wgpu.gpu.request_adapter_sync(
    power_preference="high-performance")
print("Using:", adapter.summary)       # e.g. which chip, and through what

# Open our own connection to that GPU. Everything we make below,
# we make through the device.
device = adapter.request_device_sync()

# Open the window, and connect it to the device so the GPU can draw in it.
canvas = RenderCanvas(size=(640, 480), title="Lecture 25")
context = canvas.get_wgpu_context()                     # the window's GPU side
pixel_format = context.get_preferred_format(adapter)    # how one pixel is stored
context.configure(device=device, format=pixel_format)

# Copy the corners into GPU memory: a vertex buffer of 3 x 5 x 4 = 60 bytes.
vertex_buffer = device.create_buffer_with_data(
    data=corners, usage=wgpu.BufferUsage.VERTEX)

# How the GPU should read those bytes: each corner is 20 bytes (five 4-byte
# decimals). The first two go to vs_main's @location(0), the last three
# to @location(1).
corner_layout = {
    "array_stride": 20,                              # bytes from one corner to the next
    "attributes": [
        {"shader_location": 0, "offset": 0, "format": "float32x2"},   # x, y
        {"shader_location": 1, "offset": 8, "format": "float32x3"},   # r, g, b
    ],
}

# Hand the WGSL text to the GPU, which compiles it.
shader = device.create_shader_module(code=SHADER)

# The pipeline holds every drawing setting, fixed once and checked once.
pipeline = device.create_render_pipeline(
    layout="auto",                                   # no extra inputs today
    vertex={"module": shader, "entry_point": "vs_main",     # the corner function
            "buffers": [corner_layout]},                    # and how to read its input
    primitive={"topology": "triangle-list",                 # 3 corners = 1 triangle
               "front_face": "ccw", "cull_mode": "none"},   # draw both sides
    depth_stencil=None,                              # no depth test (one triangle)
    multisample={"count": 1},                        # one colour sample per pixel
    fragment={"module": shader, "entry_point": "fs_main",   # the pixel function
              "targets": [{"format": pixel_format}]},       # write the window's format
)


# ============================================================================
# 4. EVERY FRAME (the window calls draw_frame when it needs a new picture)
# ============================================================================
def draw_frame():
    # An empty list of commands; nothing is sent to the GPU yet.
    encoder = device.create_command_encoder()

    # The picture we draw on this time: a page that the window lends us.
    page = context.get_current_texture().create_view()

    # A render pass: draw on that page, and fill it with black first.
    render_pass = encoder.begin_render_pass(color_attachments=[{
        "view": page,                           # draw on this page
        "clear_value": (0.0, 0.0, 0.0, 1.0),    # the colour to fill it with
        "load_op": "clear",                     # fill it before drawing
        "store_op": "store",                    # keep the result
    }])
    render_pass.set_pipeline(pipeline)          # use our settings
    render_pass.set_vertex_buffer(0, vertex_buffer)   # read corners from here
    render_pass.draw(3)                         # 3 corners: vs_main runs 3 times
    render_pass.end()

    # Close the list and send it to the GPU, which now draws.
    device.queue.submit([encoder.finish()])


# Tell the window which function makes its pictures, then keep it open.
canvas.request_draw(draw_frame)

if __name__ == "__main__":        # (false when images/make_images.py runs this)
    loop.run()
