Scaling a vec3

How embarrassing. I should probably just to to sleep…

I would like to write:
vec3 a = vec3(2,2,2) * 0.5
… or something similar, and end up with a vector (1,1,1)

GLM doesn’t let me do this, and I can’t find a scale method either. What am I missing?

It seems like I can write a *= 0.5, and I guess it does scale (?), but this is not what I’m looking for.

This is quite the result of a C++ template limitation…

Try again with:
vec3 a = vec3(2,2,2) * 0.5f

And it will works.
vec3 is based on float, not double (use dvec3 for that).

In GLM both side of binary operator must match because otherwise how do you choose the returned type? Some rules can be defined but this requires to avoid using template and define each single operator…

With a *= 0.5, the returned type is defined, the type of a, so no issue here.

1 Like

This is quite the result of a C++ template limitation…

It should be possible to make it work, if you add a template type for the scalar:


template <typename T, typename S> 
	inline tvec3<T> operator*(tvec3<T> const & v, S const & s)
	{
		T s1 = T(s);
		return tvec3<T>(
		v.x * s1,
		v.y * s1,
		v.z * s1);
	}

If the given S type is not convertible to T, then that’s a compile-time error.

Thanks! After working mainly with Lua for a while I’ll have to get used again to this type of stuff.

I don’t mind using floats explicitly, so no need to mess with the templates.

Cheers

I thought about that indeed but what if:

vec3(1) * 1.0? => The result should be a double to avoid losing precisions.

vec3(1) * glm::half(1.0) => The result should be a float to avoid losing precisions.

Does it matter to lose this precision? Probably. It is better to have the operator defined or generating a build error?