Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Cast float* to glm::vec3

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_casts but I can't seem to get it working.

like image 686
user1055947 Avatar asked Feb 18 '14 15:02

user1055947


2 Answers

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>.

like image 170
Wyrzutek Avatar answered Sep 21 '22 18:09

Wyrzutek


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.

like image 22
bames53 Avatar answered Sep 21 '22 18:09

bames53