How can I cast an array of floats int the form float*
to glm::vec3
? I thought I had done it before but I lost my hdd. I tried a few C-style and static_cast
s but I can't seem to get it working.
From float*
to vec3
:
float data[] = { 1, 2, 3 };
glm::vec3 vec = glm::make_vec3(data);
From vec3
to float*
:
glm::vec3 vec(1, 2, 3);
float* data = glm::value_ptr(vec);
In both cases, do not forget to #include <glm/gtc/type_ptr.hpp>
.
The glm documentation tells you how to cast from vec3
to a float*
.
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
glm::vec3 aVector(3);
glm::mat4 someMatrix(1.0);
glUniform3fv(uniformLoc, 1, glm::value_ptr(aVector));
glUniformMatrix4fv(uniformMatrixLoc,
1, GL_FALSE, glm::value_ptr(someMatrix));
You use glm::value_ptr
.
The documentation doesn't say this explicitly, however it seems clear that glm intends these types to be 'layout compatible' with arrays, so that they can be used directly with OpenGL functions. If so then you can cast from an array to vec3 using the following cast:
float arr[] = { 1.f, 0.f, 0.f };
vec3<float> *v = reinterpret_cast<vec3<float>*>(arr);
You should probably wrap this up in your own utility function because you don't want to be scattering this sort of cast all over your codebase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With