get 3d position in spacial shader ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Teln0

I made a little project that generates 3d planets with mountains following this tutorial for unity and translating c# to GDScript tutorial link. Now if I want to color the planet based on the height of the mountain I have to know the position of the pixel in 3d and it’s distance to the center, so I can create a color based on that. (Related time code in the tutorial 9:24). How can I do that in Godot ?

:bust_in_silhouette: Reply From: wombatstampede

I didn’t work through that tutorial. But about your question:

You will easily get the position of the pixel in 3D inside the vertex() part of the shader via VERTEX. Those coordinates are local, so they are mesh-relative. If the center of the mesh equals the center of the planet (which I’d recommend) then the distance from planet center should equal the length of VERTEX ( length(VERTEX) ). If you need a height above a certain planet diameter then you could pass that via a uniform and substract from the calculated distance from center.

Here a link to the spatial shader info:

You can now either calculate the color (with whatever formula/texture lookup you want) inside the vertex shader or later inside the fragment shader. Usually it is best to do as much calculations as possible inside the vertex shader as it is only called for each vertex whereas the fragment shader is executed for each “pixel”.

Anyway you want to pass your resulting color (or length) to the fragment shader. This can be done via a “Varyings”. Look that up here:

Basically, varyings will interpolate the values for a fragment variable inside a mesh tri using the three values set by the vertex shaders on the tri corners. So you could also pass the VERTEX itself via a Varying to the fragment shader but this would mean a few more calculations inside the fragment shader (for getting the color) which is usually more “costly”.

Thanks, It’s exactly what I need ! I tried to use VERTEX in the fragment part, that’s why it wasn’t working…

Teln0 | 2020-01-05 14:22