Using D3DXVec3Normalize as a parameter

Started by
1 comment, last by BattleMetalChris 13 years, 1 month ago
The MSDN entry for D3DXVec3Normalize says that it returns the vector produced as a result of the normalization, so it can be used as a parameter (so I don't actually want to permanantly normalize the vector, just pass a normalized copy into an expression).

Is there anything you can do about the 'D3DXVECTOR* pOut' parameter if you only want to use the return value? I tried using NULL, but got an 'error reading 0x00000000' error, so do you HAVE to declare a vector to put the result into before you call it, even if you don't want to store the result? This seems a bit silly to me. The best I came up with is normal = D3DXVec3Normalize(&D3DXVECTOR3(), &sourceVector))' which gets it all onto one line, but again it's constructing a vector which is unused and just discarded afterwards.

EDIT: Gah, ignore me. It returns a *pointer* to the normalized vector, so of course the vector being pointed at needs to be constructed somwhere if you're not altering the source vector.
Advertisement
You shouldn't take the address of a temporary like that.
Declare a temporary vector before calling the function. The result needs to be stored somewhere, so if you didn't have to declare it the function would just return a temporary instead.

D3DXVECTOR3 temp;
D3DXVECTOR3 result;
D3DXVec3Add(&result, D3DXVec3Normalize(&temp, &v0), &v1);


I agree it would be a bit cleaner to not do it like that.. I assume they did it this way for some optimization reason back when it was written..
With the later versions of the SDK you can switch to XNAMath instead. It has operators for vectors and returns the result instead, so you can do things like (v0 + XMVector3Normalize(v1)) / v2.

You shouldn't take the address of a temporary like that.


Surely it's ok to do in this special case though? Obviously storing a pointer to a temporary would be a bad thing, I wouldn't do

D3DXVECTOR3* pVec = D3DXVec3Normalize(&D3DXVECTOR(), &source))

as it'll dangle as soon as the temporary is destroyed but where the pointer is just used as a parameter then discarded it's ok?

This topic is closed to new replies.

Advertisement