Skip to content

Commit

Permalink
setting up mesh for triangle, trying to get transformations
Browse files Browse the repository at this point in the history
  • Loading branch information
JediWattson committed Jun 24, 2023
1 parent 7a0ac23 commit a01a833
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 37 deletions.
39 changes: 39 additions & 0 deletions components/canvas/buffer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
export const makeBuffer = (device: GPUDevice) => {
// each row contains 3 position values, 3 color values, 3 full points here
const vertices = new Float32Array([
0.0, 0.5, 1.0, 0.0, 0.0,
-0.5, -0.5, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.0, 1.0
]);

const descriptor: GPUBufferDescriptor = {
size: vertices.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true
};

const buffer = device.createBuffer(descriptor);
new Float32Array(buffer.getMappedRange()).set(vertices);
buffer.unmap();

const bufferLayout: GPUVertexBufferLayout = {
arrayStride: 20,
attributes: [
{
shaderLocation: 0,
format: "float32x2",
offset: 0
},
{
shaderLocation: 1,
format: "float32x3",
offset: 8
}
]
}

return {
buffer,
bufferLayout
}
};
28 changes: 28 additions & 0 deletions components/canvas/fragment.wgsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
struct Transform {
model: mat4x4<f32>,
view: mat4x4<f32>,
projection: mat4x4<f32>
}
@binding(0) @group(0) var<uniform> transformUBO: Transform;

struct Fragment {
@builtin(position) Position : vec4<f32>,
@location(0) Color : vec4<f32>
}

@vertex
fn vs_main(
@location(0) vertexPos: vec2<f32>,
@location(1) vertexCol: vec3<f32>) -> Fragment {

var output: Fragment;
output.Position = vec4<f32>(vertexPos, 0.0, 1.0);
output.Color = vec4<f32>(vertexCol, 1.0);

return output;
}

@fragment
fn fs_main(@location(0) Color: vec4<f32>) -> @location(0) vec4<f32> {
return Color;
}
104 changes: 83 additions & 21 deletions components/canvas/lib.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,31 @@
import { useEffect, useRef } from "react";

import triangleShader from './triangle-vert.wgsl';
import redFragShader from './red-frag.wgsl';
import fragmentShader from './fragment.wgsl'
import { makeBuffer } from "./buffer";
import { mat4 } from "wgpu-matrix";

export type CanvasRefType = HTMLCanvasElement | null;

function startPipeline(device: GPUDevice, context: GPUCanvasContext, pipeline: GPURenderPipeline): () => void {
function startPipeline(
device: GPUDevice,
context: GPUCanvasContext,
pipeline: GPURenderPipeline,
bindGroup: GPUBindGroup,
triangleTexture: GPUBuffer,
uniBuffer: GPUBuffer
): () => void {
let frameId: number;
function frame() {
let t: number = 0.0
function frame() {

const projection = mat4.perspective(Math.PI / 4, 7/6, 0.1, 10);
const view = mat4.lookAt([-2, 0, 2], [0, 0, 0], [0, 0, 1]);
const model = mat4.rotate(mat4.create(), [0, 0, 1], t);

device.queue.writeBuffer(uniBuffer, 0, <ArrayBuffer>model);
device.queue.writeBuffer(uniBuffer, 64, <ArrayBuffer>view);
device.queue.writeBuffer(uniBuffer, 128, <ArrayBuffer>projection);

const commandEncoder = device.createCommandEncoder();
const textureView = context.getCurrentTexture().createView();

Expand All @@ -24,14 +42,16 @@ function startPipeline(device: GPUDevice, context: GPUCanvasContext, pipeline: G

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(pipeline);
passEncoder.setVertexBuffer(0, triangleTexture);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.draw(3, 1, 0, 0);
passEncoder.end();

device.queue.submit([commandEncoder.finish()]);
frameId = requestAnimationFrame(frame);
}
frameId = requestAnimationFrame(frame);
return () => {
return () => {
if (!Number.isInteger(frameId)) return;
cancelAnimationFrame(frameId);
};
Expand All @@ -40,43 +60,85 @@ function startPipeline(device: GPUDevice, context: GPUCanvasContext, pipeline: G
function useInit(canvasRef: { current: CanvasRefType }) {

const cleanup = useRef(() => {});
const uniBuffer = useRef<GPUBuffer>();
const init = async () => {
if (!canvasRef.current) return;
const canvas = canvasRef.current;
const adapter = await navigator.gpu?.requestAdapter();
if (!adapter) return;
const context = canvas.getContext('webgpu') as GPUCanvasContext;
const device = await adapter.requestDevice();

// const devicePixelRatio = window.devicePixelRatio || 1;
// canvas.width = canvas.clientWidth * devicePixelRatio;
// canvas.height = canvas.clientHeight * devicePixelRatio;
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
const format = navigator.gpu.getPreferredCanvasFormat();

context.configure({
device,
format: presentationFormat,
format,
alphaMode: 'opaque',
});

const triangleTexture = makeBuffer(device);

uniBuffer.current = device.createBuffer({
size: 64 * 3,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
})

const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: {}
}
]
})

const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: uniBuffer.current
}
}
]
})

const pipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout]
})

const pipeline = device.createRenderPipeline({
layout: 'auto',
layout: pipelineLayout,
vertex: {
entryPoint: "main",
entryPoint: "vs_main",
module: device.createShaderModule({
code: triangleShader
})
code: fragmentShader
}),
buffers: [triangleTexture.bufferLayout]
},
fragment: {
entryPoint: "main",
entryPoint: "fs_main",
module: device.createShaderModule({
code: redFragShader
code: fragmentShader
}),
targets: [{
format: presentationFormat
}]
targets: [{ format }]
},

primitive: {
topology: "triangle-list"
}
})
cleanup.current = startPipeline(device, context, pipeline);
cleanup.current = startPipeline(
device,
context,
pipeline,
bindGroup,
triangleTexture.buffer,
uniBuffer.current,

);
}

useEffect(() => {
Expand Down
4 changes: 0 additions & 4 deletions components/canvas/red-frag.wgsl

This file was deleted.

12 changes: 0 additions & 12 deletions components/canvas/triangle-vert.wgsl

This file was deleted.

6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit a01a833

Please sign in to comment.