The famous cube! You might know it from voxel worlds like Minecraft or Roboblox. Cubes are like small 3d pixels (but instead of pixels they can represent small geometric elements in the 3d world). If they get small enough - and you have enough of them - you can create highly realistic world.
The famous 3D cube - think of a cube as 'virtual' lego blocks.
WARNING Cubes (or voxels) are great - but most rasterization engines are built around triangles. Voxels are popular due to their interlocking ability - like lego!
The example essentially builds a cube from positions and colors (no texturing, external libraries) - just a unit cube. The cube is rotated using some simple linear maths in the WGSL shader.
@vertex fn main(@location(0) position : vec4<f32>, @location(1) color : vec4<f32>) -> VertexOutput {
// bit of trig math to rotate around 'y' axis var p = position.xyz; var newP = vec4<f32>( p.x*cos(timer) - p.z*sin(timer), p.y, p.z*cos(timer) + p.x*sin(timer), 1.0);
// add a bit of 'perspective' - gets smaller further away newP = vec4<f32>(newP.xyz*0.5, 1.0/(newP.z + 2.0) );
You might notice this if you run the example - or if you look at the image very closly - but the back of the cube is slightly getting clipped when it rotates. This is because there isn't any camera or projection matrix set - it's drawing the unit cube in the unit space (i.e., anything outside the +/- 1 is clipped by the renderer - usually the camera and projection matrix would transform your geometry into this area).
Things to Try
The cube example is minimilstic but gets you started, some cool things to try - to help you develop your skills:
• Add transforms (e.g., gl-matrix) library and insert a model-view-projection matrix
• Try adding more cubes - draw multiple cubes around the screen (set a differnet local model matrix for each and you can draw it many times) - later we'll get to instancing (then you can draw thousands of cubes very easily)
• Build some shapes out of cubes and move the camera around - cube floor, stack of cubes, a cube cloud... just think of minecraft! Try and color the cubes differently (so they stand for different things - if you make a cube-tree - green for the cube leaves)