header

Let's start with something super basic : we'll draw a single triangle.

First of all we define a surface where we are going to draw.

In the javascript code, we'll get a reference to this surface, and instead of calling webgl2 stuff directly, we will call whatever we need through lg.

let canvas = document.getElementById('canvas-id') let lg = new LG(canvas)

Now we write down a list of point coordinates, here in 2d.

let point_list = [ -1,-1, // lower left +1,-1, // lower right 0,+1 // upper mid ] let point_list_dim = 2 // we are in 2d let point_list_count = point_list.length/point_list_dim // how many points there are in our point_list

Now we send the data to the GPU. It looks silly with small amount of data, but this is required.

let point_list_gpu = lg.buffer().set(point_list)

Now we write a GPU program that will decide where to put each point we previously listed on the screen.
vs stands for "Vertex Shader". it will be executed for each 2d point of point_list_gpu (that we will put in vec2 position later when we call the program).

const vs = ` in vec2 position; void main() { gl_Position = vec4(position,0,1); }`

Now we write a GPU program that will decide what color to draw on screen.
fs stands for "Fragment Shader". it will be executed for each pixel coverd by whatever we are drawing. If we are drawing a Triangle, it will be called for every pixels that triangle covers on screen, if it is a Point, then it will fill a square box, etc...
In game engines, this is the place you would expect sophisticated lighing stuff to be rendered. But for this basic example we will simply make it red.

const fs = ` out vec4 rgba; void main() { rgba = vec4(1,0,0,1); // red }`

Now we compile the GPU program using our vs and fs.

let program = lg.compileProgram(vs,fs)

And at last, we can render our triangle ! We will tell our program to interpret our list of points as a strip of triangles (drawTriStrip).
We ask to render point_list_count points (this could be automated later)
We tell it that we want to have all points of our list, which is point_list_count points.

program.drawTriStrip(point_list_count)({ "position": point_list_gpu, })

If you want to animate, you can make a loop like this.

But DON'T USE while loop : you will freeze your browser and render way too many frames.

The loop function uses window.requestAnimationFrame to only make a new render when necessary.

loop((time,dt) => { lg.clear() lg.viewport() program.drawTriStrip(point_list_count)({ "position": point_list_gpu, }) })

And now the full thing.

Let's animate this and add some texture