Xbox LIVE Indie Games
Sort Discussions: Previous Discussion Next Discussion
Page 1 of 1 (3 posts)

XNA Math types and constant buffers

Last post 6/8/2011 7:22 PM by JujiPL. 2 replies.
  • 6/7/2011 9:18 PM

    XNA Math types and constant buffers

    Hi!

    Could someone answer my questions, please?
    I am using XNA Math library in my application.

    The question is:
    Is it safe to use XNA Math types in a structure copied into the mapped resource of device's context?
    Imagine such model constant buffer, please:

    struct CConstantBuffer // Allocate with proper alignment 
      XMMATRIX    g_Proj;     // float4x4 
      XMFLOAT4X4  g_View;     // float4x4 
      XMFLOAT4X4A g_World;    // float4x4 
      XMFLOAT4A   g_LightCol; // float3 
      XMVECTOR    g_LightDir; // float4 
    }; 

    I have implemented aligned constant buffers with such types.
    It works, because these types are arrays of floats.
    I am not sure, that this is a safe solution.
    Is not it?

    The second question:
    Is it 'legal' to use XNA Math types without calling the constructors of these types?
    This is possible by casting memory buffers of other types.
    XNA types are non-virtual structures, and would be allocated by any method, I hope.
    After the allocation of variables, new values would be assinged using XMLoadFloat4, etc.

    Thank you very much
    Włodzimierz Kubera
  • 6/8/2011 6:38 PM In reply to

    Re: XNA Math types and constant buffers

    Answer
    Reply Quote
    Generally for memory data structures, it is best to use "XMFLOAT4X4" rather than "XMMATRIX" and "XMFLOAT4" rather than "XMVECTOR". Logically think of "XMMATRIX" and "XMVECTOR" as proxies for the SIMD registers, and not 'data structures'. That is the reason why there is a rich collection of data types in xboxmath/XNAMath.

    All XNAMath (the C++ SIMD library) types are "POD" (Plain Old Data). The constructors are just there for convienence.

    The challenge of using any data types with ConstantBuffers is of course the slightly funky alignment rules. I think it generally works out well if you stick with XMFLOAT4X4 and XMFLOAT4 since those types are natually 16-byte aligned lengths.

    If you can ensure that you only ever use struct CConstantBuffer in scenarios where you allocate them with the proper 16-byte alignment, then you can make use of XMMATRIX, XMVECTOR, FLOAT4X4A, and XMFLOAT4A. If, however, you ever get a pointer to some random memory and try to cast it, you may not actually have aligned memory and that can lead to faults. THis is why using non-aligned versions and avoiding XMMATRIX and XMVECTOR directly in data structures is a lot safer.
  • 6/8/2011 7:22 PM In reply to

    Re: XNA Math types and constant buffers

    I highly appreciate your help
    Włodzimierz Kubera
Page 1 of 1 (3 posts) Previous Discussion Next Discussion