SOL9 Sample: Direct3D11MultipleTexturedRectangleBuffer

SOL9 2.0 Samples

1 Screenshot


2 Source code

/*
 * Direct3D11MultipleTexturedRectangleBuffer.cpp 
 * Copyright (c) 2015 Antillia.com TOSHIYUKI ARAI. ALL RIGHTS RESERVED. 
 */


// 2016/01/23 
// 2017/01/18 Updated display to call setShaderMatrices.
// 2017/01/28 Updated to use ModuleFileName class and caught macro.

#pragma warning(disable : 4005) 
#pragma warning(disable : 4838) 

#define COMMONCONTROLS_V6

#include <sol/TickCounter.h>

#include <sol/direct3d11/DirectX3D11MainView.h>
#include <sol/direct3d11/DirectX3D11View.h>

#include <sol/direct3d11/Direct3D11RenderTargetView.h>
#include <sol/direct3d11/Direct3D11ShaderResourceView.h>
#include <sol/direct3d11/Direct3DX11TexturedRectangle.h>

#include <sol/direct3d11/Direct3D11RasterizerState.h>

#include <sol/direct3d11/Direct3D11VertexShader.h>
#include <sol/direct3d11/Direct3D11PixelShader.h>
#include <sol/direct3d11/Direct3D11SamplerState.h>

#include <sol/direct3d11/Direct3D11Texture2D.h>

#include <sol/direct3d11/D3D11Texture2DDesc.h>
#include <sol/direct3d11/Direct3D11Buffer.h>
#include <sol/direct3d11/Direct3D11Blob.h>

#include <sol/direct3d11/D3D11SimpleVertex.h>
#include <sol/direct3d11/D3D11ConstantBuffer.h>

#include <sol/direct3d11/Direct3D11InputLayout.h>
#include <sol/direct3d11/Direct3D11Resource.h>


#include "resource.h"

namespace SOL {
  
class MainView :public DirectX3D11MainView {
  
private:
  //////////////////////////////////////////////
  //Inner class starts
  class SimpleView : public DirectX3D11View {
  private: 
    SmartPtr<Direct3D11RenderTargetView>    renderTargetView;
    SmartPtr<Direct3D11ShaderResourceView>  shaderResourceView[2];
    SmartPtr<Direct3D11RasterizerState>     rasterizerState;
    SmartPtr<Direct3DX11TexturedRectangle>  texturedRectangle;
    SmartPtr<Direct3D11Blob>                vertexShaderBlob;
    SmartPtr<Direct3D11Blob>                pixelShaderBlob;
    SmartPtr<Direct3D11VertexShader>        vertexShader;
    SmartPtr<Direct3D11PixelShader>         pixelShader;
    SmartPtr<Direct3D11SamplerState>        samplerState;
    SmartPtr<Direct3D11Buffer>              constantBuffer;

    int                                     vertexCounter;

    SmartPtr<Direct3D11InputLayout>         inputLayout;

    XMMatrix                      world;
    XMMatrix                      view;
    XMMatrix                      projection;

    StringT<TCHAR>                directory;

    float                         angle;

  public:
    void deleteViews()
    {
      Direct3D11ImmediateContext* d3d11ImmediateContext = getD3D11ImmediateContext();
    
      d3d11ImmediateContext ->setOMRenderTargets(0, NULL, NULL);
 
      renderTargetView = NULL;
    }

    virtual void createViews()
    {
      int width  = 0;
      int height = 0;     
      validateClientSize(width, height);

      try {
        Direct3D11Device*   d3d11Device  = getD3D11Device();
        DirectXGISwapChain* swapChain = getSwapChain();
        Direct3D11ImmediateContext* d3d11ImmediateContext = getD3D11ImmediateContext();
        
        d3d11ImmediateContext ->setOMRenderTargets(0, NULL, NULL);

        //1 Create an instance of Direct3D11RenderTargetView
        Direct3D11Texture2D renderTargetViewTexture(*swapChain);

        renderTargetView = new Direct3D11RenderTargetView(*d3d11Device, renderTargetViewTexture, NULL);
        
        ID3D11RenderTargetView* targets[1];
        targets[0] = *renderTargetView; 

        //2 Set renderTargetView and depthStencilView to id3d11Device
        
        d3d11ImmediateContext ->setOMRenderTargets(1, targets, NULL);
        
      } catch (Exception& ex) {
        caught(ex);
      }
    }

    void createVertexShader()
    {
      Direct3D11Device* d3d11Device = getD3D11Device();
      TCHAR fullpath[MAX_PATH];
      _stprintf_s(fullpath, CountOf(fullpath), _T("%s\\..\\fx\\%s"), 
                    (const TCHAR*)directory, 
                    _T("shader.fx"));
      try {
        vertexShaderBlob = new Direct3D11Blob(fullpath, "VS", "vs_4_0");
        if (vertexShaderBlob) {
          vertexShader = new Direct3D11VertexShader(*d3d11Device, *vertexShaderBlob);
        }
        
      } catch (Exception& ex) {
        caught(ex);
      }
    }
    
    void createPixelShader()
    {
      Direct3D11Device* d3d11Device = getD3D11Device();
      TCHAR fullpath[MAX_PATH];
      _stprintf_s(fullpath, CountOf(fullpath), _T("%s\\..\\fx\\%s"), 
                    (const TCHAR*)directory, 
                    _T("shader.fx"));

      try {
        pixelShaderBlob = new Direct3D11Blob(fullpath, "PS", "ps_4_0");
        if (pixelShaderBlob) {
          pixelShader = new Direct3D11PixelShader(*d3d11Device, *pixelShaderBlob);
       }
      } catch (Exception& ex) {
        caught(ex);
      }
    }
    
    void createInputLayout()
    {
      try {
        Direct3D11Device* d3d11Device = getD3D11Device();
        Direct3D11ImmediateContext* d3d11ImmediateContext = getD3D11ImmediateContext();
        
        size_t count = 0;
        static const D3D11_INPUT_ELEMENT_DESC* layout = D3D11InputElements::getPosTexCoordDesc(count); 
        
        inputLayout = new Direct3D11InputLayout(
              *d3d11Device, 
              layout, 
              count, 
              *vertexShaderBlob);

        d3d11ImmediateContext -> setIAInputLayout(*inputLayout);

      } catch (Exception& ex) {
        caught(ex);
      }
    }

    void createTexturedRectangleBuffer()
    {
      try {
        Direct3D11Device* d3d11Device = getD3D11Device();
        Direct3D11ImmediateContext* d3d11ImmediateContext = getD3D11ImmediateContext();
        
        texturedRectangle = new Direct3DX11TexturedRectangle(d3d11Device, d3d11ImmediateContext, 1.0f, 0.8f);
      } catch (Exception& ex) {
        caught(ex);
      }
    }

    void createConstantBuffer()
    {
      try {
        Direct3D11Device* d3d11Device = getD3D11Device();
        Direct3D11ImmediateContext* d3d11ImmediateContext = getD3D11ImmediateContext();

        D3D11_BUFFER_DESC constantBufferDesc;
        memset(&constantBufferDesc, 0, sizeof(constantBufferDesc));
        constantBufferDesc.Usage     = D3D11_USAGE_DEFAULT;
        constantBufferDesc.ByteWidth = sizeof(D3D11ConstantBuffer); 
        constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;

        // Create a constantBuffer from above parameters.
        constantBuffer = new Direct3D11Buffer(*d3d11Device, &constantBufferDesc, NULL);
        
      } catch (Exception& ex) {
        caught(ex);
      }
    }

    void setShaderMatrices()
    {
      int width = 0;
      int height = 0;
      getClientSize(width, height);

      try {
          //world = XMMatrixIdentity();
        
          XMVECTOR  eye = XMVectorSet(  0.0f,  0.0f, -2.0f,  0.0f );
          XMVECTOR  at  = XMVectorSet(  0.0f,  0.0f,  0.0f,  0.0f );
          XMVECTOR  up  = XMVectorSet(  0.0f,  1.0f,  0.0f,  0.0f );
          view = XMMatrix::lookAtLH(eye, at, up);

           projection = XMMatrix::perspectiveFovLH( XM_PIDIV2*0.5f, width / (FLOAT)height, 0.01f, 100.0f );
       
      } catch (Exception& ex) {
        caught(ex);
      }
    }
    void createShaderResourceView()
    {
      try {
        Direct3D11Device* d3d11Device = getD3D11Device();
        TCHAR fullpath[MAX_PATH];
        const TCHAR* files[] = {
          _T("SnowFlakes.png"),
          _T("TokyoSkyTree.png")
        };

        const char* textures[] = {
          "Texture1",
          "Texture2"
        };

        for (int i = 0; i<CountOf(files); i++) {
          _stprintf_s(fullpath, CountOf(fullpath), _T("%s\\..\\image\\%s"), 
                    (const TCHAR*)directory,  files[i]);
     
          shaderResourceView[i] = new Direct3D11ShaderResourceView(
            *d3d11Device,
            fullpath,
            NULL,   //D3D10_SHADER_RESOURCE_VIEW_DESC *desc
            NULL);  //D3DX10_IMAGE_LOAD_INFO* loadInfo
         
        }
      } catch(Exception& ex) {
        caught(ex); 
      }
    }
    
    void createRasterizerState()
    {
      try {
        Direct3D11Device* d3d11Device = getD3D11Device();
        Direct3D11ImmediateContext* d3d11ImmediateContext = getD3D11ImmediateContext();

        D3D11_RASTERIZER_DESC desc;
        memset(&desc, 0, sizeof(desc));
        desc.CullMode               = D3D11_CULL_NONE;
        desc.FillMode               = D3D11_FILL_SOLID;
        desc.FrontCounterClockwise  = true;
        desc.DepthBias              = false;
        //desc.DepthBiasClamp         = 0;
        //desc.SlopeScaledDepthBias   = 0;
        desc.DepthClipEnable        = true;
        desc.ScissorEnable          = false;
        desc.MultisampleEnable      = false;
        desc.AntialiasedLineEnable  = true;

        rasterizerState = new Direct3D11RasterizerState (*d3d11Device, &desc);

        d3d11ImmediateContext->setRSState(*rasterizerState);

      } catch (Exception& ex) {
        caught(ex);
      }
    }
    
    void createSamplerState()
    {
      try {
        Direct3D11Device* d3d11Device = getD3D11Device();

        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;
        samplerState = new Direct3D11SamplerState(*d3d11Device, &sampDesc);
      } catch (Exception& ex) {
        caught(ex);
      }
    }


    virtual void initialize()
    {
      try {
        createVertexShader();

        createPixelShader();

        createInputLayout();
        
        createTexturedRectangleBuffer();

        createConstantBuffer();

        setShaderMatrices();

        createShaderResourceView();

        createRasterizerState();  

        createSamplerState();

        createViews();

      } catch (Exception& ex) {
        caught(ex);
      }
    }

    virtual void display()
    {
      try {
        Direct3D11Device*  d3d11Device = getD3D11Device();
        DirectXGISwapChain* swapChain = getSwapChain();
        Direct3D11ImmediateContext*  d3d11ImmediateContext = getD3D11ImmediateContext();
        
        if (renderTargetView != nullptr) {
          renderTargetView -> clear(XMColor(0.0, 0.0, 0.0, 0.0));
          //2017/01/18
          setShaderMatrices();
          
          world = XMMatrixRotationY( angle );

          D3D11ConstantBuffer cb;

          //2016/03/10        
          cb.world      = world.transpose();
          cb.view       = view.transpose();
          cb.projection = projection.transpose();

          d3d11ImmediateContext -> updateSubresource(*constantBuffer, 0, NULL, &cb, 0, 0 );

          d3d11ImmediateContext -> setVSShader( *vertexShader, NULL, 0 );
          
          ID3D11Buffer* cbuffer =  *constantBuffer;
            d3d11ImmediateContext -> setVSConstantBuffers( 0, 1, &cbuffer );
            d3d11ImmediateContext -> setPSShader( *pixelShader, NULL, 0 );
            
          ID3D11ShaderResourceView* resourceView[2];
          resourceView[0]= *shaderResourceView[0];
          resourceView[1]= *shaderResourceView[1];
          
          d3d11ImmediateContext -> setPSShaderResources( 0, 2, resourceView );
          ID3D11SamplerState* state = *samplerState;
          d3d11ImmediateContext -> setPSSamplers( 0, 1, &state);

          texturedRectangle -> drawIndexed();
        }
        swapChain -> present();

      } catch (Exception& ex) {
        caught(ex);
      }
    }
    
  public:
    void render()
    {
      angle += 0.02f;
      display();
    }

  public:
    // Constructor
    SimpleView(DirectX3D11MainView* parent, const TCHAR* name, Args& args)
   :DirectX3D11View(parent, name,
                 args.set(XmNstyle, (ulong)WS_CLIPCHILDREN) ),
    vertexCounter(0),
    directory(_T("")),
    angle(0.0f)
    {
      directory = (const TCHAR*)args.get(XmNapplicationDirectory);
    }

    ~SimpleView()
    {    
    }
    
  private:
    void resize(int width, int height)
    {
      Direct3D11Device*   device = getD3D11Device();
      DirectXGISwapChain* swapChain = getSwapChain();
      if (device           == NULL && 
          swapChain        == NULL && 
          renderTargetView == NULL) {
        return ;
      }
    
      try {
        // 1 Delete existing rendarTargetView and depthStencilView.
        deleteViews();

        // 2 ResizeBuffers swapChain(IDXGISwapChain)
        swapChain -> resizeBuffers(width, height); 
     
        // 3 Recreate rendarTargetView and depthStencilView.
        createViews();
      
        // 4 SetViewPort
        setViewPort(width, height);

      } catch (Exception& ex) {
        caught(ex);
      }
    }  
  };
  //////////////////////////////////////////////
  // Inner class ends.
  
private:
  SmartPtr<SimpleView> view;
  TickCounter tickCounter;

public:
  // Constructor
  MainView(Application& applet, const TCHAR* name, Args& args)
  :DirectX3D11MainView(applet, name,
                 args.set(XmNstyle, (ulong)WS_CLIPCHILDREN|WS_CLIPSIBLINGS) )
  {
    DWORD interval = (DWORD)args.get(XmNrenderingInterval);
    tickCounter.setInterval(interval);

    const TCHAR* directory = (const TCHAR*)args.get(XmNapplicationDirectory);
    // 1 Create a view of SimpleView.
    Args ar;
    int width  = 0;
    int height = 0;
    getClientSize(width, height);

    ar.set(XmNwidth, width);
    ar.set(XmNheight,height);
    ar.set(XmNapplicationDirectory, directory);
    ar.set(XmNstyle, WS_BORDER|WS_CHILD|WS_VISIBLE);
    view = new SimpleView(this, _T(""), ar);

    // 2 Post a resize request to this MainView.
    postResizeRequest();
  }
  
public:
  ~MainView()
  {
  }
  
  virtual void render()
  {
    if (view != nullptr) {
      if (tickCounter.timeout()) {
        view -> render();
      }
    }
  }

private:
  void resize(int width, int height)
  {
    if (view) {
      view -> reshape(0, 0, width, height);
      view -> postResizeRequest(width, height);
    }
  }
};
  
}

//////////////////////////////////////////////
//
void  Main(int argc, TCHAR** argv)
{
  ModuleFileName module(argv[0]);
  const TCHAR* directory = module.getDirectory();
  const TCHAR* appClass =  module.getAppName(); 
    
  try {
    Application applet(appClass, argc, argv);

    Args args;
    args.set(XmNapplicationDirectory, directory);
    args.set(XmNwidth,  640);
    args.set(XmNheight, 480);
    args.set(XmNrenderingInterval, 10);  //10 millisec
    MainView mainv(applet, appClass, args);
    
    mainv.realize();

    applet.run();

  } catch (Exception& ex) {
    caught(ex);
  }
}


Last modified: 1 Feb 2017

Copyright (c) 2017 Antillia.com ALL RIGHTS RESERVED.