Sign in to follow this  
Ubermeowmix

DirectX rendering procedure

Recommended Posts

I'm having trouble understanding how directX deals with the objects being called and when it renders each one.

 

In a nutshell is it like this?:

 

1. set render states

2. set vertex format

3. load vertex buffers

         3.1. create vertex buffer (lock buffer)

         3.2. fill the buffer with array data

         3.3. Copy array data and then unlock buffer.

4. Draw to scene

5. Present data

 

So do I create classes to load multiple models at step 3 before step 4?

Or does each model have to go through the process up to draw before present is called at step 5?

 

Help would be greatly appreciated!

 

 

Share this post


Link to post
Share on other sites

Not quite. You can think of DX11 application has having 3 distinct stages:

 

  • Load - in this stage you create all your state objects. Shaders, render states, resources, resource-views, vertex buffers, index buffers, constant buffers, etc.
    • This is stage where you load all you models and materials.
  • Rendering - the main rendering loop. this is the stage where you use the objects created in the load stage. In this stage you usually:
    • Set render states(depth state, rasterizer state, blend state).
    • Set viewport
    • Set and clear the render-target-view and depth-stencil-view.
    • Set shaders and shaders state
      • Samplers
      • Shader resource views
      • Constant buffer. In most cases, you map the CBs, fill them with data, unmap and bind them.
    • Set vertex and index buffer, input element layout, topology. Note that there's usually no reason to change the content of your VB/IB.
    • Draw.
  • Cleanup stage - release all the objects you created during load.

As you can see, the main rendering loop doesn't create anything, and besides the CBs doesn't use any dynamic buffers (there are exceptions, of course). This reduces API overhead and allows the driver to be more clever about optimizations it makes.

And unless I forgot something, this is DX11 in a nutshell.

Edited by satanir

Share this post


Link to post
Share on other sites

Is short, you setup rendering states: render targets, render states, textures, buffers, other things, and then draw. After that you need to change only what changed.

So lets say if you have 100 different models that use same textures/everything your loop would look like (pseudocode):

context->SetShader()
context->SetIndexBuffer() // assuming index buffer is identical
context->SetVertexFormat()
context->SetRenderTarget()
for(...) {
    context->SetVertexBuffer()
    context->Draw()
}

Share this post


Link to post
Share on other sites

Okay one more lol, getting lost in how to implement what I need using derived classes.

 

So I can lay it out like this then:

 

WinMain -> calls AssetsClass;

     during windows message check:

         calls AssetsClass->Update();

                 AssetsClass->Render();

 

DirectxBaseInitialization (class)

     virtual Render();

     virtual Update();

AssetsClass : public DirectxBaseInitialization

     virtual Update();

 

Then I can wrap all my code in the following classes Sprites, Font's & 3Dmodels. All 'public DirectxBaseInitialization'.

Then it all waterfalls back down the pipeline to the render call that is called by AssetsClass.

 

Or is that barking up the wrong tree?

Share this post


Link to post
Share on other sites

Okay I've gone away and RTFM a bit more,

 

I'm to the point where:

  • I've tied object creation down to the Vertex buffer & Index buffer in initialization
  • Declaration of the objects world Scale * rotation * translation in updating your scene
  • And drawing the object using the loaded textures, texture samplers & the vertex shader buffer in the DrawScene stage

I'm currently trying to encapsulate object creation (cubes) into a vector, problem is it's failing at runtime due to the CubesClass containing XMMATRIX variables.

 

How do I get round this? and why wont Vector allow a class containing them?

Share this post


Link to post
Share on other sites

problem is it's failing at runtime due to the CubesClass containing XMMATRIX variables.

No it’s not.

why wont Vector allow a class containing them?

It does.

How do I get round this?

Better show some code and provide more information.


L. Spiro

Share this post


Link to post
Share on other sites

#ifndef _C_MY_OBJECT_H_
#define _C_MY_OBJECT_H_

#include <xnamath.h>

class cMyObject
{
public:
    cMyObject() :    posX(0.0f),
                    posY(0.0f),
                    posZ(0.0f),
                    rot(0.0f),
                    scaleMod(0.3f),
                    scaleFull(false) {};
    ~cMyObject() {};

    //void DeclareMyObject(float rotPassed, float posXnew, float posYnew, float posZnew)
    void DeclareMyObject(    float newScale,
                            float rotIn,
                            float posXnew,
                            float posYnew,
                            float posZnew )
    {
        currCubeWorldMat = XMMatrixIdentity();                                            //Reset current cubes coords

        Scale = XMMatrixScaling( newScale, newScale, newScale );

        XMVECTOR rotaxis = XMVectorSet( 0.0f, 0.0f, 1.0f, 0.0f );                    //Define objects world space matrix
        Rotation = XMMatrixRotationAxis( rotaxis, rotIn );
        Translation = XMMatrixTranslation( posXnew, posYnew, posZnew );

        //SRT scale, rot, translation
        currCubeWorldMat = Scale * Rotation * Translation;                                //Set cube1's world space using the transformations
    }

    XMMATRIX ReturnWorldMatrix() { return currCubeWorldMat; }

    /*
    void DrawMyObject(    ID3D11DeviceContext* d3d11DevCon,
                            XMMATRIX& WVP,
                            cbPerObject& cbPerObjectBuffer,
                            cbPerObject& cbPerObj,
                            ID3D11ShaderResourceView* TextureRef,
                            ID3D11SamplerState* TexSamplerRef,
                            XMMATRIX& camView,
                            XMMATRIX& camProjection)
    {
        WVP = currCubeWorldMat * camView * camProjection;
        cbPerObj.WVP = XMMatrixTranspose(WVP);
        d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );
        d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );
        d3d11DevCon->PSSetShaderResources( 0, 1, &TextureRef );
        d3d11DevCon->PSSetSamplers( 0, 1, &TexSamplerRef );
    
        //Draw the cube
        d3d11DevCon->DrawIndexed( 36, 0, 0 );
    }
    */

private:
    XMMATRIX    currCubeWorldMat;

    XMMATRIX    Scale,
                Rotation,
                Translation;

    float        posX,
                posY,
                posZ,
                rot,
                scaleMod;

    bool        scaleFull;
};

#endif

 

//declarations at the top of main.cpp

std::vector<cMyObject> vCubes;

 

 

in the main update function

void UpdateScene()
{
    float newX = 0.0f;

    for(int i = 0; i < 3; i++)
    {
        vCubes.push_back( cMyObject( ) );
        vCubes[i].DeclareMyObject( newX, 0.0f, 0.0f );
        newX += 0.3f;
    }
}

 

in the drawscene function when I swap to this function i get the following error:

1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\vector(870): error C2719: '_Val': formal parameter with __declspec(align('16')) won't be aligned
1>          main.cpp(103) : see reference to class template instantiation 'std::vector<_Ty>' being compiled

 

for(int i = 0; i < 3; i++)
    {
        WVP = vCubes[i].ReturnWorldMatrix() * camView * camProjection;
        cbPerObj.WVP = XMMatrixTranspose(WVP);
        d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );
        d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );
        d3d11DevCon->PSSetShaderResources( 0, 1, &CubesTexture );
        d3d11DevCon->PSSetSamplers( 0, 1, &CubesTexSamplerState );

        //Draw the cube
        d3d11DevCon->DrawIndexed( 36, 0, 0 );
    }

 

 

The code works fine if I split up the variables into seperate calls eg:

//initial declarations
cMyObject object1;
cMyObject object2;
cMyObject object3;
 
//in the update scene
object1.DeclareMyObject( scaleMod, rot, -2.0f, 0.0f, 0.0f );
object2.DeclareMyObject( scaleMod, rot, 0.0f, 3.0f, 2.0f );
object3.DeclareMyObject( scaleMod, rot, 4.0f, 1.0f, 0.0f );
 
//in the draw call
WVP = object1.ReturnWorldMatrix() * camView * camProjection;
    cbPerObj.WVP = XMMatrixTranspose(WVP);
    d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );
    d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );
    d3d11DevCon->PSSetShaderResources( 0, 1, &CubesTexture2 );
    d3d11DevCon->PSSetSamplers( 0, 1, &CubesTexSamplerState2 );
   
    //Draw the cube
    d3d11DevCon->DrawIndexed( 36, 0, 0 );
//code repeated with 2/3 etc

Share this post


Link to post
Share on other sites

I was trying to implement:

 

object1.DrawMyObject( d3d11DevCon, WVP, cbPerObjectBuffer, cbPerObj, CubesTexture2, CubesTexSamplerState2, camView, camProjection );

 

But that does the same so I seperated it from the class to try identify where the error was.

Share this post


Link to post
Share on other sites

Right so a vector can hold XMMATRIX objects then, why is my code failing then?

 

main include code:

 

//////////////////////////////////////////////////////////////////////////HEADER INCLUDES
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dx11.lib")
#pragma comment(lib, "d3dx10.lib")

#pragma comment(lib, "dxerr.lib")

#include <windows.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>
#include <xnamath.h>

#include <string>
#include <sstream>
#include <vector>

#include <DxErr.h>

//#include "Fonts.h"
#include "cMyObject.h"

//////////////////////////////////////////////////////////////////////////GLOBALS

IDXGISwapChain* SwapChain;
ID3D11Device* d3d11Device;
ID3D11DeviceContext* d3d11DevCon;
ID3D11RenderTargetView* renderTargetView;

ID3D11Buffer* cube1IndexBuffer;
ID3D11Buffer* cube1VertBuffer;

ID3D11ShaderResourceView* CubesTexture;
ID3D11SamplerState* CubesTexSamplerState;

ID3D11ShaderResourceView* CubesTexture2;
ID3D11SamplerState* CubesTexSamplerState2;

ID3D11ShaderResourceView* FontTexture1;
ID3D11SamplerState* FontTexSamplerState;

ID3D11DepthStencilView* depthStencilView;
ID3D11Texture2D* depthStencilBuffer;

ID3D11VertexShader* VS;
ID3D11PixelShader* PS;
ID3D10Blob* VS_Buffer;
ID3D10Blob* PS_Buffer;
ID3D11InputLayout* vertLayout;

ID3D11Buffer* cbPerObjectBuffer;

ID3D11BlendState* Transparency;
ID3D11RasterizerState* CCWcullMode;
ID3D11RasterizerState* CWcullMode;

ID3D11RasterizerState* WireFrame;
ID3D11RasterizerState* NormalCamera;

ID3D11RasterizerState* noCull;

float red = 0.0f;
float green = 0.0f;
float blue = 0.0f;
int colormodr = 1;
int colormodg = 1;
int colormodb = 1;

float colorR = 0.0f;
float colorG = 0.0f;
float colorB = 0.0f;
int colorMr = 1;
int colorMg = 1;
int colorMb = 1;

float cameraPosY = 0.0f;

LPCTSTR WndClassName = L"firstwindow";
HWND hwnd = NULL;
HRESULT hr;

const int Width  = 1024;
const int Height = 768;

XMMATRIX WVP;
XMMATRIX World;
XMMATRIX camView;
XMMATRIX camProjection;

XMVECTOR camPosition;
XMVECTOR camTarget;
XMVECTOR camUp;

//instead of objects have a vector of XMMATRICES
std::vector<cMyObject> vCubes;
//XMMATRIX cube1World;
//XMMATRIX cube2World;
//XMMATRIX cube3World;
//cMyObject object1;
//cMyObject object2;
//cMyObject object3;

XMMATRIX Rotation;
XMMATRIX Scale;
XMMATRIX Translation;
float rot = 0.01f;
float scaleMod = 0.3f;
bool scaleFull = false;

D3D11_FILTER currentFilter = D3D11_FILTER_MIN_MAG_MIP_POINT;

float blendFactorMax = 0.0f;
float blendFactorMod = 0.5f;

static const int maxLetters = 600;

bool bSpinCubes = false;
bool bSpinCubesAlt = false;

//////////////////////////////////////////////////////////////////////////STRUCTURES

struct cbPerObject
{
    XMMATRIX  WVP;
};
cbPerObject cbPerObj;

struct Vertex    //Overloaded Vertex Structure
{
    Vertex() { }
    Vertex(float x, float y, float z,
    float u, float v)
        : pos(x,y,z), texCoord(u, v){}

    XMFLOAT3 pos;
    XMFLOAT2 texCoord;
};

D3D11_INPUT_ELEMENT_DESC layout[] =
{
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE(layout);

struct VertexSquare
{
    VertexSquare(){}
    VertexSquare(float x, float y, float z)
        : pos(x,y,z){}

    XMFLOAT3 pos;
};

D3D11_INPUT_ELEMENT_DESC layoutSquare[] =
{
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },  
};
UINT numElementsSquare = ARRAYSIZE(layoutSquare);

//////////////////////////////////////////////////////////////////////////DECLARE FUNCTION PROTOTYPES

bool InitializeDirect3d11App(HINSTANCE hInstance);
void ReleaseObjects();
bool InitScene();
void UpdateScene();
void DrawScene();
bool DrawString( const char* message, float startX, float startY );

bool InitializeWindow(
    HINSTANCE hInstance,
    int ShowWnd,
    int width, int height,
    bool windowed
);

int messageloop();

LRESULT CALLBACK WndProc(
    HWND hWnd,
    UINT msg,
    WPARAM wParam,
    LPARAM lParam
);

//////////////////////////////////////////////////////////////////////////MAIN CODE

int WINAPI WinMain(HINSTANCE hInstance,    //Main windows function
           HINSTANCE hPrevInstance,
           LPSTR lpCmdLine,
           int nShowCmd)
{
    if( !InitializeWindow( hInstance, nShowCmd, Width, Height, true ) )
    {
        MessageBox(0, L"Window Initialization - Failed",
                    L"Error", MB_OK);
        return 0;
    }

    if( !InitializeDirect3d11App( hInstance ) )    //Initialize Direct3D
    {
        MessageBox(0, L"Direct3D Initialization - Failed",
            L"Error", MB_OK);
        return 0;
    }

    if( !InitScene() )    //Initialize our scene
    {
        MessageBox(0, L"Scene Initialization - Failed",
            L"Error", MB_OK);
        return 0;
    }
    
    messageloop();

    ReleaseObjects();

    return 0;    //success no errors
}

bool InitializeWindow(    HINSTANCE hInstance,
                        int ShowWnd,
                        int width, int height,
                        bool windowed)
{
    typedef struct _WNDCLASS {
        UINT cbSize;
        UINT style;
        WNDPROC lpfnWndProc;
        int cbClsExtra;
        int cbWndExtra;
        HANDLE hInstance;
        HICON hIcon;
        HCURSOR hCursor;
        HBRUSH hbrBackground;
        LPCTSTR lpszMenuName;
        LPCTSTR lpszClassName;
    } WNDCLASS;

    WNDCLASSEX wc;

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = NULL;
    wc.cbWndExtra = NULL;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_EXCLAMATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 4);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = WndClassName;
    wc.hIconSm = LoadIcon(NULL, IDI_EXCLAMATION);

    if (!RegisterClassEx(&wc))
    {
        MessageBox(NULL, L"Error registering class",    
            L"Error", MB_OK | MB_ICONERROR);
        return 1;
    }

    hwnd = CreateWindowEx(    NULL,
                            WndClassName,
                            L"Window Title",
                            WS_OVERLAPPEDWINDOW,
                            CW_USEDEFAULT, CW_USEDEFAULT,
                            width, height,
                            NULL,
                            NULL,
                            hInstance,
                            NULL);

    if (!hwnd)
    {
        MessageBox(NULL, L"Error creating window",
            L"Error", MB_OK | MB_ICONERROR);
        return 1;
    }

    ShowWindow(hwnd, ShowWnd);
    UpdateWindow(hwnd);
    
    return true;
}

int messageloop(){
    MSG msg;
    ZeroMemory(&msg, sizeof(MSG));
    while(true)
    {
        BOOL PeekMessageL(
            LPMSG lpMsg,
            HWND hWnd,
            UINT wMsgFilterMin,
            UINT wMsgFilterMax,
            UINT wRemoveMsg
            );

        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            if (msg.message == WM_QUIT)
                break;
            TranslateMessage(&msg);    
            DispatchMessage(&msg);
        }
        else
        {
            // run game code
            UpdateScene();
            DrawScene();
        }
    }
    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd,
             UINT msg,
             WPARAM wParam,
             LPARAM lParam)
{
    switch( msg )
    {
        case WM_KEYDOWN:
            if( wParam == VK_ESCAPE )
            {
                if(MessageBox(0, L"Are you sure you want to exit?",
                        L"Really?", MB_YESNO | MB_ICONQUESTION) == IDYES)
                DestroyWindow(hwnd);
            }

            if( wParam == 0x41 ) //A key
                bSpinCubesAlt = true;

            if( wParam == 0x53 ) //S key
                bSpinCubes = true;
        return 0;

        case WM_KEYUP:
            if( wParam == 0x41 ) //A key
                bSpinCubesAlt = false;

            if( wParam == 0x53 ) //S key
                bSpinCubes = false;
        return 0;

        case WM_DESTROY:
            PostQuitMessage(0);
        return 0;
    }

    return DefWindowProc(    hwnd,
                            msg,
                            wParam,
                            lParam);
}

bool InitializeDirect3d11App(HINSTANCE hInstance)
{
    //Describe our Buffer
    DXGI_MODE_DESC bufferDesc;

    ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC));

    bufferDesc.Width = Width;
    bufferDesc.Height = Height;
    bufferDesc.RefreshRate.Numerator = 60;
    bufferDesc.RefreshRate.Denominator = 1;
    bufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
    
    //Describe our SwapChain
    DXGI_SWAP_CHAIN_DESC swapChainDesc;
        
    ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));

    swapChainDesc.BufferDesc = bufferDesc;
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.SampleDesc.Quality = 0;
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapChainDesc.BufferCount = 1;
    swapChainDesc.OutputWindow = hwnd;
    swapChainDesc.Windowed = TRUE;
    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

    //Create our SwapChain
    D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, NULL, NULL,
        D3D11_SDK_VERSION, &swapChainDesc, &SwapChain, &d3d11Device, NULL, &d3d11DevCon);

    //Create our BackBuffer
    ID3D11Texture2D* BackBuffer;
    SwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), (void**)&BackBuffer );

    //Describe our Depth/Stencil Buffer
    D3D11_TEXTURE2D_DESC depthStencilDesc;

    depthStencilDesc.Width     = Width;
    depthStencilDesc.Height    = Height;
    depthStencilDesc.MipLevels = 1;
    depthStencilDesc.ArraySize = 1;
    depthStencilDesc.Format    = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthStencilDesc.SampleDesc.Count   = 1;
    depthStencilDesc.SampleDesc.Quality = 0;
    depthStencilDesc.Usage          = D3D11_USAGE_DEFAULT;
    depthStencilDesc.BindFlags      = D3D11_BIND_DEPTH_STENCIL;
    depthStencilDesc.CPUAccessFlags = 0;
    depthStencilDesc.MiscFlags      = 0;

    d3d11Device->CreateTexture2D(&depthStencilDesc, NULL, &depthStencilBuffer);
    d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);

    //Create our Render Target
    d3d11Device->CreateRenderTargetView( BackBuffer, NULL, &renderTargetView );
    BackBuffer->Release();

    //Set our Render Target
    d3d11DevCon->OMSetRenderTargets( 1, &renderTargetView, depthStencilView  );

    return true;
}


void ReleaseObjects()
{
    //vCubes.clear();

    //Release the COM Objects we created
    SwapChain->Release();
    d3d11Device->Release();
    d3d11DevCon->Release();

    renderTargetView->Release();
    depthStencilView->Release();
    depthStencilBuffer->Release();

    cube1IndexBuffer->Release();
    cube1VertBuffer->Release();

    CubesTexture->Release();
    CubesTexSamplerState->Release();

    FontTexture1->Release();
    FontTexSamplerState->Release();

    VS->Release();
    PS->Release();
    //VS2->Release();
    //PS2->Release();
    VS_Buffer->Release();
    PS_Buffer->Release();
    //VS_Buffer2->Release();
    //PS_Buffer2->Release();
    vertLayout->Release();

    cbPerObjectBuffer->Release();

    //---------------RENDER STATES------------------
    Transparency->Release();
    CCWcullMode->Release();
    CWcullMode->Release();
    WireFrame->Release();
    NormalCamera->Release();
    noCull->Release();
}


bool InitScene()
{
    //Compile Shaders from shader file
    hr = D3DX11CompileFromFile(L"Effects.fx", 0, 0, "VS", "vs_5_0", 0, 0, 0, &VS_Buffer, 0, 0);
    hr = D3DX11CompileFromFile(L"Effects.fx", 0, 0, "PS", "ps_5_0", 0, 0, 0, &PS_Buffer, 0, 0);

    //Create the Shader Objects
    hr = d3d11Device->CreateVertexShader(VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), NULL, &VS);
    if( FAILED(hr) ) { MessageBox(0, L"Vertex Shader FAILED - Go fix it!", L"BROKEN...", MB_OK); return 0; }
    hr = d3d11Device->CreatePixelShader(PS_Buffer->GetBufferPointer(), PS_Buffer->GetBufferSize(), NULL, &PS);
    if( FAILED(hr) ) { MessageBox(0, L"Pixel Shader FAILED - Go fix it!", L"BROKEN...", MB_OK); return 0; }

    //hr = D3DX11CompileFromFile(L"Effects2.fx", 0, 0, "VS", "vs_5_0", 0, 0, 0, &VS_Buffer2, 0, 0);
    //hr = D3DX11CompileFromFile(L"Effects2.fx", 0, 0, "PS", "ps_5_0", 0, 0, 0, &PS_Buffer2, 0, 0);

    //hr = d3d11Device->CreateVertexShader(VS_Buffer2->GetBufferPointer(), VS_Buffer2->GetBufferSize(), NULL, &VS2);
    //hr = d3d11Device->CreatePixelShader(PS_Buffer2->GetBufferPointer(), PS_Buffer2->GetBufferSize(), NULL, &PS2);

    //Set Vertex and Pixel Shaders
    d3d11DevCon->VSSetShader(VS, 0, 0);
    d3d11DevCon->PSSetShader(PS, 0, 0);

    //--------------------------------------Create the vertex buffers--------------------------------------
    
    Vertex v[] =
    {
        // Front Face
        Vertex(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f),
        Vertex(-1.0f,  1.0f, -1.0f, 0.0f, 0.0f),
        Vertex( 1.0f,  1.0f, -1.0f, 1.0f, 0.0f),
        Vertex( 1.0f, -1.0f, -1.0f, 1.0f, 1.0f),

        // Back Face
        Vertex(-1.0f, -1.0f, 1.0f, 1.0f, 1.0f),
        Vertex( 1.0f, -1.0f, 1.0f, 0.0f, 1.0f),
        Vertex( 1.0f,  1.0f, 1.0f, 0.0f, 0.0f),
        Vertex(-1.0f,  1.0f, 1.0f, 1.0f, 0.0f),

        // Top Face
        Vertex(-1.0f, 1.0f, -1.0f, 0.0f, 1.0f),
        Vertex(-1.0f, 1.0f,  1.0f, 0.0f, 0.0f),
        Vertex( 1.0f, 1.0f,  1.0f, 1.0f, 0.0f),
        Vertex( 1.0f, 1.0f, -1.0f, 1.0f, 1.0f),

        // Bottom Face
        Vertex(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f),
        Vertex( 1.0f, -1.0f, -1.0f, 0.0f, 1.0f),
        Vertex( 1.0f, -1.0f,  1.0f, 0.0f, 0.0f),
        Vertex(-1.0f, -1.0f,  1.0f, 1.0f, 0.0f),

        // Left Face
        Vertex(-1.0f, -1.0f,  1.0f, 0.0f, 1.0f),
        Vertex(-1.0f,  1.0f,  1.0f, 0.0f, 0.0f),
        Vertex(-1.0f,  1.0f, -1.0f, 1.0f, 0.0f),
        Vertex(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f),

        // Right Face
        Vertex( 1.0f, -1.0f, -1.0f, 0.0f, 1.0f),
        Vertex( 1.0f,  1.0f, -1.0f, 0.0f, 0.0f),
        Vertex( 1.0f,  1.0f,  1.0f, 1.0f, 0.0f),
        Vertex( 1.0f, -1.0f,  1.0f, 1.0f, 1.0f),
    };

    DWORD indices[] = {
        // Front Face
        0,  1,  2,
        0,  2,  3,

        // Back Face
        4,  5,  6,
        4,  6,  7,

        // Top Face
        8,  9, 10,
        8, 10, 11,

        // Bottom Face
        12, 13, 14,
        12, 14, 15,

        // Left Face
        16, 17, 18,
        16, 18, 19,

        // Right Face
        20, 21, 22,
        20, 22, 23
    };

    D3D11_BUFFER_DESC indexBufferDesc;
    ZeroMemory( &indexBufferDesc, sizeof(indexBufferDesc) );

    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(DWORD) * 12 * 3;
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;
    indexBufferDesc.MiscFlags = 0;

    D3D11_SUBRESOURCE_DATA iinitData;

    iinitData.pSysMem = indices;
    d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &cube1IndexBuffer);

    d3d11DevCon->IASetIndexBuffer( cube1IndexBuffer, DXGI_FORMAT_R32_UINT, 0);    

    //----------------------------------VERTEX BUFFER DESC--------------------------------------------

    D3D11_BUFFER_DESC vertexBufferDesc;
    ZeroMemory( &vertexBufferDesc, sizeof(vertexBufferDesc) );

    vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    vertexBufferDesc.ByteWidth = sizeof( Vertex ) * 24;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = 0;
    vertexBufferDesc.MiscFlags = 0;

    //-----------------------------------SET VERTEX BUFFER----------------------------------------------
    
    D3D11_SUBRESOURCE_DATA vertexBufferData;

    ZeroMemory( &vertexBufferData, sizeof(vertexBufferData) );
    vertexBufferData.pSysMem = v;
    hr = d3d11Device->CreateBuffer( &vertexBufferDesc, &vertexBufferData, &cube1VertBuffer);


    UINT stride = sizeof( Vertex );
    UINT offset = 0;
    d3d11DevCon->IASetVertexBuffers( 0, 2, &cube1VertBuffer, &stride, &offset );

    //Create the Input Layout
    hr = d3d11Device->CreateInputLayout( layout, numElements, VS_Buffer->GetBufferPointer(),
        VS_Buffer->GetBufferSize(), &vertLayout );

    //Set the Input Layout
    d3d11DevCon->IASetInputLayout( vertLayout );

    //Set Primitive Topology
    d3d11DevCon->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

    //-----------------------------------LOAD TEXTURE FILE----------------------------------------------

    hr = D3DX11CreateShaderResourceViewFromFile( d3d11Device, L"Cage.png", NULL, NULL, &CubesTexture, NULL );
    if( FAILED( hr ) ) { DXTRACE_MSG( L"Failed to load the texture 'Cage.png'!" ); return false; }

    // Describe the Sample State
    D3D11_SAMPLER_DESC sampDesc;
    ZeroMemory( &sampDesc, sizeof(sampDesc) );
    sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
    sampDesc.MinLOD = 0;
    sampDesc.MaxLOD = D3D11_FLOAT32_MAX;

    //Create the Sample State
    hr = d3d11Device->CreateSamplerState( &sampDesc, &CubesTexSamplerState );

    //----------TEXTURE 2---------------[

    hr = D3DX11CreateShaderResourceViewFromFile( d3d11Device, L"braynzar.jpg", NULL, NULL, &CubesTexture2, NULL );
    if( FAILED( hr ) ) { DXTRACE_MSG( L"Failed to load the texture 'braynzar.jpg'!" ); return false; }

    // Describe the Sample State
    D3D11_SAMPLER_DESC sampDesc2;
    ZeroMemory( &sampDesc2, sizeof(sampDesc2) );
    sampDesc2.Filter = D3D11_FILTER_COMPARISON_ANISOTROPIC; //global declared above
    //sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
    //sampDesc.Filter = D3D11_FILTER_COMPARISON_ANISOTROPIC;
    sampDesc2.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc2.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc2.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc2.ComparisonFunc = D3D11_COMPARISON_NEVER;
    /*
    sampDesc2.BorderColor[0] = 1.0f;
    sampDesc2.BorderColor[1] = 1.0f;
    sampDesc2.BorderColor[2] = 1.0f;
    sampDesc2.BorderColor[3] = 0.5f;
    */
    sampDesc2.MinLOD = 0;
    sampDesc2.MaxLOD = D3D11_FLOAT32_MAX;
    
    //Create the Sample State
    hr = d3d11Device->CreateSamplerState( &sampDesc2, &CubesTexSamplerState2 );

    //--------------TEXTURE 3-------------[

    hr = D3DX11CreateShaderResourceViewFromFile( d3d11Device, L"KKfont.dds", NULL, NULL, &FontTexture1, NULL );
    if( FAILED( hr ) ) { DXTRACE_MSG( L"Failed to load the texture 'KKfont.dds'!" ); return false; }

    D3D11_SAMPLER_DESC sampDesc3;
    ZeroMemory( &sampDesc3, sizeof(sampDesc) );
    sampDesc3.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    sampDesc3.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc3.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc3.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc3.ComparisonFunc = D3D11_COMPARISON_NEVER;
    sampDesc3.MinLOD = 0;
    sampDesc3.MaxLOD = D3D11_FLOAT32_MAX;

    //Create the Sample State
    hr = d3d11Device->CreateSamplerState( &sampDesc3, &FontTexSamplerState );

    //---------------------------------------Create the Viewport-----------------------------------------------

    D3D11_VIEWPORT viewport;
    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = Width;
    viewport.Height = Height;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;

    //Set the Viewport
    d3d11DevCon->RSSetViewports(1, &viewport);

    //-----------------------------------SET THE PROJECTION MATRIX----------------------------------------------
    D3D11_BUFFER_DESC cbbd;    
    ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));

    cbbd.Usage = D3D11_USAGE_DEFAULT;
    cbbd.ByteWidth = sizeof(cbPerObject);
    cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    cbbd.CPUAccessFlags = 0;
    cbbd.MiscFlags = 0;

    hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);

    //set up the camera
    camPosition = XMVectorSet( 0.0f, 3.0f, -8.0f, 0.0f );
    camTarget = XMVectorSet( 0.0f, 0.0f, 0.0f, 0.0f );
    camUp = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );

    //create the view space
    camView = XMMatrixLookAtLH( camPosition, camTarget, camUp );
    //create the projection matrix
    camProjection = XMMatrixPerspectiveFovLH( 0.4f*3.14f, (float)Width/Height, 1.0f, 1000.0f);
    
    //------------------------------------Rasterizer State-----------------------------------------------------

    D3D11_RASTERIZER_DESC wfdesc;
    ZeroMemory(&wfdesc, sizeof(D3D11_RASTERIZER_DESC));
    wfdesc.FillMode = D3D11_FILL_WIREFRAME;
    wfdesc.CullMode = D3D11_CULL_NONE;
    hr = d3d11Device->CreateRasterizerState(&wfdesc, &WireFrame);
    //d3d11DevCon->RSSetState(WireFrame);

    D3D11_RASTERIZER_DESC normDesc;
    ZeroMemory(&normDesc, sizeof(D3D11_RASTERIZER_DESC));
    normDesc.FillMode = D3D11_FILL_SOLID;
    normDesc.CullMode = D3D11_CULL_BACK;
    hr = d3d11Device->CreateRasterizerState(&normDesc, &NormalCamera);
    //d3d11DevCon->RSSetState(NormalCamera);
    
    
    //------------------------------------And the camera object-------------------------------------------------
    
    World = XMMatrixIdentity();
    WVP = World * camView * camProjection;

    cbPerObj.WVP = XMMatrixTranspose(WVP);
    d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );
    d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );

    return true;
}

void UpdateScene()
{
    red = 0.5f;
    green = 0.5f;
    blue = 0.5f;

    //Keep the cubes rotating
    if(bSpinCubes) {
        rot += .0003f;
        if(rot > 6.28f)
            rot = 0.0f;
    }

    if(bSpinCubesAlt) {
        rot -= .0003f;
        if(rot > 6.28f)
            rot = 0.0f;
    }

    if(scaleFull) {
        scaleMod -= .00005f;
        if(scaleMod < 0.3f)
            scaleFull = false;
    } else {
        scaleMod += .00005f;
        if(scaleMod > 1.3f)
            scaleFull = true;
    }    

    float newX = 0.0f;
    //vCubes - fill the vector with objects
    for(int i = 0; i < 3; i++)
    {
        vCubes.push_back( cMyObject( ) );
        vCubes[i].DeclareMyObject( 0.5f, 0.005f, newX, 0.0f, 0.0f );
        newX += 0.3f;
    }
    //object1.DeclareMyObject( scaleMod, rot, -2.0f, 0.0f, 0.0f );
    //object2.DeclareMyObject( 0.0f, 3.0f, 2.0f );
    //object3.DeclareMyObject( 4.0f, 1.0f, 0.0f );
    
    /*
    //Reset cube1World
    cube1World = XMMatrixIdentity();

    //Define cube1's world space matrix
    XMVECTOR rotaxis = XMVectorSet( 1.0f, 1.0f, 0.0f, 0.0f );
    Rotation = XMMatrixRotationAxis( rotaxis, rot );
    Translation = XMMatrixTranslation( 0.0f, 0.0f, 4.3f );

    //Set cube1's world space using the transformations
    cube1World = Translation * Rotation;

    //-------------------Reset cube2World--------------------------
    cube2World = XMMatrixIdentity();
    //Define cube2's world space matrix
    Rotation = XMMatrixRotationAxis( rotaxis, -rot);

    if(scaleFull) {
        scaleMod -= .00005f;
        if(scaleMod < 0.3f)
            scaleFull = false;
    } else {
        scaleMod += .00005f;
        if(scaleMod > 1.3f)
            scaleFull = true;
    }    
    Scale = XMMatrixScaling( scaleMod, scaleMod, scaleMod );

    //Set cube2's world space matrix
    cube2World = Scale * Rotation;

    //-------------------Reset cube3World--------------------------
    cube3World = XMMatrixIdentity();
    //SRT - Normal
    Scale = XMMatrixScaling( 0.5f, 0.5f, 0.5f );
    XMVECTOR rotaxis2 = XMVectorSet( 0.0f, 1.0f, 1.0f, 0.0f );
    Rotation = XMMatrixRotationAxis( rotaxis2, rot );
    Translation = XMMatrixTranslation( 3.3f, 0.0f, 0.0f );

    cube3World = Scale * Translation * Rotation;
    */
}


void DrawScene()
{
    //Clear our backbuffer to the updated color
    D3DXCOLOR bgColor( red, green, blue, 1.0f );
    d3d11DevCon->ClearRenderTargetView(renderTargetView, bgColor);
    //Refresh the Depth/Stencil view
    d3d11DevCon->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0);

    //DrawMyObjects();

    //-----------------------------------------1st cube--------------------------------------------------------

    //object1.DrawMyObject( d3d11DevCon, WVP, cbPerObjectBuffer, cbPerObj, CubesTexture2,      //CubesTexSamplerState2, camView, camProjection );

    for(int i = 0; i < 3; i++)
    {
        WVP = vCubes[i].ReturnWorldMatrix() * camView * camProjection;
        cbPerObj.WVP = XMMatrixTranspose(WVP);
        d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );
        d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );
        d3d11DevCon->PSSetShaderResources( 0, 1, &CubesTexture );
        d3d11DevCon->PSSetSamplers( 0, 1, &CubesTexSamplerState );

        //Draw the cube
        d3d11DevCon->DrawIndexed( 36, 0, 0 );
    }

    /*
// THIS CODE WORKS
    WVP = object1.ReturnWorldMatrix() * camView * camProjection;
    cbPerObj.WVP = XMMatrixTranspose(WVP);
    d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );
    d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );
    d3d11DevCon->PSSetShaderResources( 0, 1, &CubesTexture2 );
    d3d11DevCon->PSSetSamplers( 0, 1, &CubesTexSamplerState2 );
    
    //Draw the cube
    d3d11DevCon->DrawIndexed( 36, 0, 0 );
    */

    //--------------------------------Present the backbuffer to the screen------------------------------------------
    SwapChain->Present(0, 0);
}

Share this post


Link to post
Share on other sites

Narrowed it down again, It's the fact i'm passing the struct wrongly to the class.

 

void DrawMyObject(    ID3D11DeviceContext* d3d11DevCon,
                                    XMMATRIX&  WVP,
                                    ID3D11Buffer* cbPerObjectBuffer,
                                    struct cbPerObject& cbPerObj,                                                                                //passing a struct must have the struct declaration before it
                                    ID3D11ShaderResourceView* TextureRef,
                                    ID3D11SamplerState* TexSamplerRef,
                                    XMMATRIX& camView,
                                    XMMATRIX& camProjection)
    {
        WVP = currCubeWorldMat * camView * camProjection;
        cbPerObj.WVP = XMMatrixTranspose(WVP);
        d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );
        d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );
        d3d11DevCon->PSSetShaderResources( 0, 1, &TextureRef );
        d3d11DevCon->PSSetSamplers( 0, 1, &TexSamplerRef );
 
        d3d11DevCon->DrawIndexed( 36, 0, 0 );
    }

 

But now it won't compile due to the cbPerObj, it's giving the following error:

1>------ Build started: Project: Barynzarsoft_tutorials, Configuration: Debug Win32 ------
1>  main.cpp
1>c:\users\paulus\desktop\c++ code\barynzarsoft_tutorials\barynzarsoft_tutorials\cMyObject.h(48): error C2027: use of undefined type 'cbPerObject'
1>          c:\users\paulus\desktop\c++ code\barynzarsoft_tutorials\barynzarsoft_tutorials\cMyObject.h(41) : see declaration of 'cbPerObject'
1>c:\users\paulus\desktop\c++ code\barynzarsoft_tutorials\barynzarsoft_tutorials\cMyObject.h(48): error C2228: left of '.WVP' must have class/struct/union
1>main.cpp(93): error C2371: 'WVP' : redefinition; different basic types
1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\vector(870): error C2719: '_Val': formal parameter with __declspec(align('16')) won't be aligned
1>          main.cpp(103) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=cMyObject
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

 

Why is it not taking the Struct reference?

Share this post


Link to post
Share on other sites

I didn't think you needed to include the "struct" keyword in the function? It's not like you add the "class" keywords in other usage.

Am I missing something?

 

PS: Merry Christmas =)

Edited by CoreLactose

Share this post


Link to post
Share on other sites

You have several errors.

 

error C2027: use of undefined type 'cbPerObject'

You have not included a header where this structure is defined inside of cMyObject.h.

 

error C2228: left of '.WVP' must have class/struct/union

It will be fixed when the above error is fixed.

 

error C2371: 'WVP' : redefinition; different basic types

You have a huge mess of globals.This is related to WVP is somewhere outside of the code you are posting; you have it has a global and then somewhere else as another type.

This is why you should use a naming convention, such that globals are always prefixed with g_ (of course, better yet, never use globals).

 

error C2719: '_Val': formal parameter with __declspec(align('16')) won't be aligned

I said before that std::vector can hold an XMMATRIX, but that is basically in principle.

An XMMATRIX structure needs to be aligned on a 16-byte address, and the default allocator for std::vector does not guarantee to this.

You have to create a custom allocator for the std::vector that guarantees 16-byte-aligned addresses are returned, but I don’t know that the compiler will recognize this and make the warning go away.

 

 

L. Spiro

Share this post


Link to post
Share on other sites

Can a struct be redefined safely in a class? as it needs to be delcared in both main and myObject.

 

You have several errors.

 

error C2027: use of undefined type 'cbPerObject'

You have not included a header where this structure is defined inside of cMyObject.h.

 

error C2228: left of '.WVP' must have class/struct/union

It will be fixed when the above error is fixed.

 

 

So regarding this comment below, do you mean always pass by reference/pointer and avoid the possibility of forgetting what has access to which etc!

 


error C2371: 'WVP' : redefinition; different basic types

You have a huge mess of globals.This is related to WVP is somewhere outside of the code you are posting; you have it has a global and then somewhere else as another type.

This is why you should use a naming convention, such that globals are always prefixed with g_ (of course, better yet, never use globals).

 

 

This next part seems that I am going about this the wrong way, is it unrealistic to implement this function into a class. Am I missing the point with this bit. The problem is I have not seen examples of how commercial games generate objects on the fly so I'm taking what i've learned and attempting to make it simpler.

 


error C2719: '_Val': formal parameter with __declspec(align('16')) won't be aligned

I said before that std::vector can hold an XMMATRIX, but that is basically in principle.

An XMMATRIX structure needs to be aligned on a 16-byte address, and the default allocator for std::vector does not guarantee to this.

You have to create a custom allocator for the std::vector that guarantees 16-byte-aligned addresses are returned, but I don’t know that the compiler will recognize this and make the warning go away.

Share this post


Link to post
Share on other sites

Can a struct be redefined safely in a class? as it needs to be delcared in both main and myObject.

Define it once in a header and #include it where needed. Predeclaring is typically preferred to avoid redeclaration issues.
Use it in main() and use it as a member of your other class. There is no “redefining” taking place.


So regarding this comment below, do you mean always pass by reference/pointer and avoid the possibility of forgetting what has access to which etc!

I don’t see how this is related to pointers and references, especially in regards to the WVP error I explained below. I don’t know what you are trying to ask.

This next part seems that I am going about this the wrong way, is it unrealistic to implement this function into a class.

In the part to which you are referring I mention alignment issues, custom allocators, and that globals are bad.
What do you mean?
And “implement this function into a class”?

Again I have absolutely no idea what you are trying to ask.


L. Spiro

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this