Rotation Library – 2D, 3D, Quaternion
This is a shader include file that contains a ton of functions for rotation. It also has a quaternion multiplication function, since it’s needed for axis-angle rotation.
It is recommended that you put this code into a gdshaderinc file (Such as “rotate.gdshaderinc”). You can then include it at the top of any shader with “#include ‘”res://path_to_shader.gdshaderinc”.
Shader code
vec3 rotate_x(vec3 vert, float angle) {
float s = sin(angle);
float c = cos(angle);
// [cos - sin, sin + cos]
return vec3(vert.x, vert.y * c - vert.z * s, vert.y * s + vert.z * c );
}
vec3 rotate_y(vec3 vert, float angle) {
float s = sin(angle);
float c = cos(angle);
// [cos - sin, sin + cos]
return vec3(vert.x * c - vert.z * s, vert.y, vert.x * s + vert.z * c );
}
vec3 rotate_z(vec3 vert, float angle) {
float s = sin(angle);
float c = cos(angle);
// [cos - sin, sin + cos]
return vec3(vert.x * c - vert.y * s, vert.x * s + vert.y * c, vert.z);
}
vec4 quat_multiply(vec4 q, vec4 p) {
float a = q.w, b = q.x, c = q.y, d = q.z;
float w = p.w, x = p.x, y = p.y, z = p.z;
return vec4(
a * x + b * w + c * z - d * y, // i
a * y - b * z + c * w + d * x, // j
a * z + b * y - c * x + d * w, // k
a * w - b * x - c * y - d * z // w
);
}
vec3 rotate(vec3 vert, vec3 axis, float angle) {
vec4 q;
q.x = axis.x * sin(angle/2.0);
q.y = axis.y * sin(angle/2.0);
q.z = axis.z * sin(angle/2.0);
q.w = cos(angle / 2.0);
vec4 p = vec4(vert, 0.0);
vec4 q_conj = vec4(-q.xyz, q.w);
//q /= sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w);
return quat_multiply(quat_multiply(q, p), q_conj).xyz;
}
vec2 rotate(vec2 vector, float angle) {
if (angle == 0.0) {
return vector;
}
float sine = sin(angle);
float cosine = cos(angle);
return vec2(vector.x * cosine - vector.y * sine, vector.x * sine + vector.y * cosine);
}
