r/javascript • u/ivanhoe90 • Oct 12 '18
A simple 3D engine in 47 lines of JS
Hi guys, I messed around a bit and made this little toy demo: https://jsfiddle.net/06L845jx/86/
It could be a little hint to help beginners understand, how 3D engines (like OpenGL or Direct X) work.
You can see, that drawing is just looping through triangles, processing each one with a Vertex Shader, and calling a Fragment Shader on it. The current "Fragment shader" just strokes the outline of a 2D triangle, but you could extend it, make a Z-buffer and loop through each pixel, for a proper fragment shading :) Or make the camera move with arrows on a keyboard (update transformation matrix).
The model is just a cube: 8 vertices for 12 triangles (two for each side). But it can render any triangle model you give it (e.g. generate a model with a code).
-------------------------------------------------------------
Thanks for upvotes! I made a second demo with 100 cubes (54 lines of JS) https://jsfiddle.net/06L845jx/127/
14
u/sinefine Oct 12 '18
This is really cool, but this isn't really how fragment shader works though. Fragment shader doesn't draw lines but interpolates pixel values between vertex positions. There are a lot of cool JS side projects like this one, but I hope no one sees this and attempts to extend to have z-buffer in pure JS. It really doesn't take much of an effort to draw something in 3D.
I put together the above example, and other than the perspective matrix and rotation matrix, drawing a static 3D is simple.
1
u/ivanhoe90 Oct 13 '18
It would not be that hard to extend my code with a Z-buffer (and drawing triangles pixel-by-pixel in JS).
Extending my code to that level would be useful, if we wanted to make a WebGL server in JS with the same interface (to run WebGL apps on devices without browser-side WebGL) . GLSL interpreter would probably be the hardest part.
1
u/BobbyThrowaway6969 Jan 18 '25
It might be educational for you to try but it's by no means practical to do graphics this way.
If you want a CPU rasteriser that runs at anything close to a useful framerate, do it in C/C++.
2
u/ivanhoe90 Jan 18 '25
I think modern Javascript compilers can compile Javascript to a similar machine code as your C++ compiler would compile your C++ code, so the possible achievable framerate should be similar.
4
u/nyclowkey Oct 12 '18
yep, adding interactions to the above in Canvas is where this will fall apart and require mental gymnastic skills of an Olympian.
It is amazing work though.
3
3
u/rybytud Oct 13 '18
Nice! A long time ago I used to play around with stuff like this. Brings back some good memories.
I messed around with your code and added back-face culling, and a duck model. Sadly the duck model was made with Y-axis pointing up, and I forget how to fix the math, so it's rotated wrong :(
2
u/ivanhoe90 Oct 13 '18
Cool! Some people like the Y to point forward (makers of a duck), while I like it to point up. It is enough to swap each second and third coordinate in your model, like this :) https://jsfiddle.net/y23jwr6k/1/
1
u/rybytud Oct 13 '18
Hah, wow I feel dumb now, I was thinking I'd have to modify the math. Thanks for fixing it :)
3
u/ivanhoe90 Oct 14 '18
Yeah, you could do the rotation with a linear transformation matrix, too. Sin / Cos of 90 degrees would be 1 / 0, so you would get Y = 0*Y + 1*Z, Z = 1*Y + 0*Z :)
2
u/ivanhoe90 Oct 13 '18 edited Oct 13 '18
@rybytud You made me do this :D https://jsfiddle.net/y23jwr6k/2/
1
u/rybytud Oct 13 '18
That's awesome! Did you make it?
1
u/ivanhoe90 Oct 13 '18
No, I found it on the internet :) http://lib.ivank.net/?p=demos&d=real3D . I disabled triangle filling of yours, because the FPS dropped a lot.
2
u/rybytud Oct 15 '18
Played with it a bit more and added flat (lambert?) shading as well as a random color palette, and some controls just for fun. The shading isn't very good and only looks half decent because the light vector is slowly spinning around with the model. Also, the code really needs bug fixing and refactoring too, but whatever, I had a lot of fun playing with it :) Thanks for posting your original code!
2
u/ivanhoe90 Oct 15 '18
Wow, maybe we should stop it, before we end up making Counter Strike :D
1
u/rybytud Oct 15 '18
Haha, right? :) Really though, I think it's getting really close to the maximum of what I'm capable of doing, so this is about as far as I care to take it. I might add polygon sorting and refactor a bit though.
2
u/ivanhoe90 Oct 15 '18
BTW. I think this looks more realistic: https://jsfiddle.net/o42mptx3/1/
I use just the "middle" color from your palette and mix it with black, according to "dotproduct".
1
u/Oikeus_niilo Jan 03 '19
Is it supposed to be slightly transparent? I can see the tail through the neck when the tail is supposed to be behind the rest of the duck...
Anyways, I know this is old thread, but all this is really cool. I always thought 3d drawing is way too much math for me because I suck at geometry. Recently i stumbled upon this tutorial https://www.khanacademy.org/computing/computer-programming/programming-games-visualizations/programming-3d-shapes/a/rotating-3d-shapes and it sparked an interest, I'm building on that code now except in Python ( i dont know JS). Your examples also inspire me
Right now I'm having problems on how to move the piece front and back. I can zoom it ok but once I bring another cube in the screen the zoom will just zoom both of them until they overlap. What I mean is that I can define the x,y position of the object, but not the z... because the tutorial I linked doesn't do it that way. Anyways, I will probably figure it out in couple days after some sleep.
1
u/ivanhoe90 Jan 03 '19 edited Jan 03 '19
We are aware of "triangle overlapping". The triangles of the model are three vertices in a 3D space: [A,B,C]. You could write them down in any order: [B,C,A], [A,C,B] ... and it would still define the same triangle.
The author of a duck did not make vertices of each triangle just in any random order. He (or she) ordered them in a way, such that A-B-C go clockwise when you look at the triangle from outside the duck. So we can say, that each triangle has an inner and an outer side.
The JS program loops through all triangles (in a fixed order) and draws them all. There is a little trick (on line 891): it skips the whole triangle, when it is facing the camera counter-clockwise. But when two triangles A,B are facing the camera clockwise (and B is after the A in a triangle list), B is drawn after A (on top of A), even when A is closer to the camera.
The solution would be to sort all triangles in a list (according to their distance to the camera) in each frame. But there still would be problems, if triangles intersect one another.
1
1
u/rybytud Oct 15 '18
Yeah, that looks much better. Looks like it adds more contrast so you can actually see the difference between the light and shadow color.
25
u/Emptyless Oct 12 '18
Wow this looks incredibly cool. I always like projects that make something hard, easy to understand. Great work :)
5
1
u/TheClarity Oct 16 '18 edited Oct 16 '18
https://jsfiddle.net/3m5L089d/46/ Added some color and z-sorting, move around with arrow keys but just can’t seem to figure out how to change the rotation from just pivoting around the center, need to brush up on my maths
2
u/ivanhoe90 Oct 16 '18
Nice! I fixed your keyboard controls a bit :) https://jsfiddle.net/3m5L089d/52/ That is how we do it in games :D
1
1
u/TheClarity Oct 18 '18
I know this is a little old but my brain is on fire, I can’t seem to get the camera to pivot around the current position not the center
1
u/ivanhoe90 Oct 18 '18
There are many ways to do it. You could draw it on a paper and solve it (it is actually a 2D problem). Or you could implement 4x4 matrix multiplication, and make the final matrix as a product of simpler matrices.
Note, that the "eye" is always at [0,0,0], looking forward in the direction of Z, and the matrix transforms the whole model. When the camera is at [X,Y,0] and has an angle A, the model has to be moved by -X,-Y, and rotated by -A. Now, you rotate before translating. You don't even track the X,Y of the camera.
1
u/Beneficial_Tea_1672 not my main Jan 28 '25
I know this is pretty old but I made a very modified version of the code (it's an abomination now) and can't figure out how to rotate the camera up and down. Is there a way to do that with the existing code or someway else? my (probably overcomplicated) code: https://jsfiddle.net/316t07hz/
1
u/ivanhoe90 Jan 29 '25
In my code https://jsfiddle.net/06L845jx/86/ you would have to change the viewing matrix (line 15).
To avoid complex matrices, create that matrix as a merging (multiplication) of several simpler matrices.
1
u/Beneficial_Tea_1672 not my main Jan 29 '25
Do you know which part of the matrix would have to change?
1
u/ivanhoe90 Jan 30 '25
Maybe try to write your own code from scratch, instead of trying to modify an existing code. You don't have to use matrices at all.
3
1
1
1
u/FKAred Nov 11 '18
maybe its just cause i'm retarded but man those variable names make this pretty much incomprehensible to me
1
u/BobbyThrowaway6969 Jan 18 '25
It's a nice introduction to matrix maths, but it's about as close to being a 3D engine as a taxi passenger is to a combustion engine.
1
-45
u/dominik9876 Oct 12 '18
And you call this "an engine"?
4
9
Oct 12 '18
I assume you've done something more impressive you'd like to show us?
-12
u/danketiquette Oct 12 '18
I mean he isn't wrong though. This is not a game engine lol.
11
2
u/spaghettu Oct 12 '18
Don't know why this guy is getting downvotes, he's right. It isn't an engine, it's some code that uses JS Canvas for some simple draws. I think calling it an engine is misleading, it's just a neat sample. Another misleading thing is the "fragmentShader" function, which draws the outline of the triangle, where in real fragment shaders this geometry would have already been created, and the function would run independently per-fragment on the GPU.
10
Oct 12 '18
Don't know why this guy is getting downvotes
Because his response serves no other purpose than to shit on OP. If he wanted to be constructive, he could have explained why it's not an engine or recommended some useful modifications or extended reading for the OP to continue on his path. Instead he offered a pointless remark for the sole purpose of being a dick. So he gets downvoted like a dick.
I think calling it an engine is misleading, it's just a neat sample. Another misleading thing is the "fragmentShader" function, which draws the outline of the triangle, where in real fragment shaders this geometry would have already been created, and the function would run independently per-fragment on the GPU.
Yeah, something like that would have been way more constructive to start with.
4
u/Arve Oct 12 '18 edited Oct 13 '18
So, explain why /u/spaghettu is being downvoted. While the original comment was short and dismissive, it was right. spaghettu offered direct examples into why "engine" is misleading, but still got downvoted.
Even outside the realm of "3d" the use of "engine" would've been misleading, as there isn't much in the way of something that abstracts or makes the task easier; it's merely an example of how to draw single-color unfilled 3d vectors on to a canvas, while glossing over things like FOV.
Had the code been adequately commented, and the maths behind the aspects, I think it would've served some good. As it stands now, it's hardly useful, and it's certainly not impressive. I mean, this was programmed by a couple of 15-year-olds on a machine running with all of 512kB ram and 7.14Mhz clock frequency, with no FPU.
1
u/parseHex Oct 13 '18
I think spaghettu is being downvoted because they say they don't know why the comment OP is being downvoted.
1
Oct 12 '18
I'd rather not, as I really don't care about upvotes/downvotes enough to continue this little spat. It's an internet web site. The votes mean nothing.
Explain why you care so much about it?
1
u/Arve Oct 12 '18
Explain why you care so much about it?
I don't, but I think the downvotes are undeserved, and just wanted to spend all of 30 seconds speaking up.
1
20
u/Arve Oct 12 '18
You should probably fix paint ordering. If you try to instead fill the triangles, the back face shows up at the front for every 2pi rotation. Example: