Getting only the model matrix in a shader

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

As the title says, there is a model view matrix in the godot shader, but there is no model matrix and view matrix.

For example, in gdScript, if you want to get the right vector of an object, you can use get_transform().basis.x.
In the same way, I want to get the orientation vector in the shader.

To be more specific
MODEL_MATRIX * vec4(1.0, 0.0, 0.0, 1.0);

Or is there another way to do this?

:bust_in_silhouette: Reply From: Zylann

Which type of shader is it?
And which function do you need this into? (fragment or vertex?)

In a spatial shader’s vertex() function you can access the model matrix as WORLD_MATRIX, which is the global transform of the model. It is also available in the fragment() function.

In a canvas_item shader, there is also WORLD_MATRIX available in vertex() (only), however it is the view space matrix, unfortunately. I think what you’d need here is missing, but maybe there is a trick to get it which I’m not aware of. Maybe un-composing with a camera matrix?

If all else fails another option is to declare a uniform mat4 my_matrix; and pass what you need from GDScript to the ShaderMaterial using set_shader_param (make sure it is unique if you want different values for different objects).

If you need the local transform, that’s also not available in shaders, you’d have to pass that in.

You can use either type of shader. You can also use either vertex or fragment.

Since the model to which this shader is assigned will be treated as a GridMap mesh, it is not possible to make each one unique.
Therefore, I can’t pass them individually as uniform…

But I got the idea from you and was able to make it happen! Thank you very much.

It was quite simple, but I’ll write it down just in case…

vec4 origin = WORLD_MATRIX * vec4(0.0, 0.0, 0.0, 1.0);
vec4 right = WORLD_MATRIX * vec4(1.0, 0.0, 0.0, 1.0);

vec4 resultVelocity = right - origin;

huny | 2022-01-29 04:16

Yeah if you use GridMap then you have a spatial shader, so WORLD_MATRIX is what you need. You’d only use uniform parameters as last resort.

Zylann | 2022-01-29 16:07