Don't like ads? PRO users don't see any ads ;-)
Guest

game.cpp

By: a guest on Jul 20th, 2012  |  syntax: C++  |  size: 65.69 KB  |  hits: 45  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1.     #include <windows.h>
  2.     #include <d3d11.h>
  3.     #include <d3dx11.h>
  4.     #include <d3dcompiler.h>
  5.     #include <xnamath.h>
  6.     #include <vector>
  7.     #include <iostream>
  8.     #include <fstream>
  9.     #include <sstream>
  10.     #include <string>
  11.     #include <cstdint>
  12.     #include "resource.h"
  13.         #include <map>
  14.         #include <list>
  15.     #include "DXUT/Core/dxut.h"
  16.     #include "DXUTmisc.h"
  17.     #include "DXUTcamera.h"
  18.     #include "DXUTgui.h"
  19.     #include "DXUTsettingsDlg.h"
  20.     #include "SDKmisc.h"
  21.     #include <algorithm>
  22.     #include "Effects11/Inc/d3dx11effect.h"
  23.      
  24.     #include "ntx/NTX.h"
  25.      
  26.     #include "debug.h"
  27.         #include "SpriteRenderer.h"
  28.     #include "Mesh.h"
  29.     #include "T3d.h"
  30.     // Convenience macros for safe effect variable retrieval
  31.     #define SAFE_GET_PASS(Technique, name, var)   {assert(Technique!=NULL); var = Technique->GetPassByName( name );                                         assert(var->IsValid());}
  32.     #define SAFE_GET_TECHNIQUE(effect, name, var) {assert(effect!=NULL); var = effect->GetTechniqueByName( name );                                          assert(var->IsValid());}
  33.     #define SAFE_GET_SCALAR(effect, name, var)    {assert(effect!=NULL); var = effect->GetVariableByName( name )->AsScalar();                       assert(var->IsValid());}
  34.     #define SAFE_GET_VECTOR(effect, name, var)    {assert(effect!=NULL); var = effect->GetVariableByName( name )->AsVector();                       assert(var->IsValid());}
  35.     #define SAFE_GET_MATRIX(effect, name, var)    {assert(effect!=NULL); var = effect->GetVariableByName( name )->AsMatrix();                       assert(var->IsValid());}
  36.     #define SAFE_GET_SAMPLER(effect, name, var)   {assert(effect!=NULL); var = effect->GetVariableByName( name )->AsSampler();                      assert(var->IsValid());}
  37.     #define SAFE_GET_RESOURCE(effect, name, var)  {assert(effect!=NULL); var = effect->GetVariableByName( name )->AsShaderResource();       assert(var->IsValid());}
  38.      
  39.     // Help macros
  40.     #define DEG2RAD( a ) ( (a) * D3DX_PI / 180.f )
  41.      
  42.     using namespace std;
  43.      
  44.     //--------------------------------------------------------------------------------------
  45.     // Global variables
  46.     //--------------------------------------------------------------------------------------
  47.      
  48.     // Camera
  49.     struct CAMERAPARAMS {
  50.             float   m_Fovy;
  51.             float   m_Aspect;
  52.             float   m_NearPlane;
  53.             float   m_FarPlane;
  54.     }                                       g_CameraParams;
  55.     float                                   g_CameraMoveScaler = 1000.f;
  56.     float                                   g_CameraRotateScaler = 0.01f;
  57.     CFirstPersonCamera                      g_Camera;               // A first person camera
  58.      
  59.     // User Interface
  60.     CDXUTDialogResourceManager              g_DialogResourceManager; // manager for shared resources of dialogs
  61.     CD3DSettingsDlg                         g_SettingsDlg;          // Device settings dialog
  62.     CDXUTTextHelper*                        g_TxtHelper = NULL;
  63.     CDXUTDialog                             g_HUD;                  // dialog for standard controls
  64.     CDXUTDialog                             g_SampleUI;             // dialog for sample specific controls
  65.      
  66.     // A D3DX rendering effect
  67.     ID3DX11Effect*                          g_Effect = NULL; // The whole rendering effect
  68.     ID3DX11EffectTechnique*                 g_Technique = NULL; // One technique to render the effect
  69.     ID3DX11EffectPass*                      g_Pass0 = NULL; // One rendering pass of the technique
  70.     ID3DX11EffectMatrixVariable*            g_WorldEV = NULL; // World matrix effect variable
  71.     ID3DX11EffectMatrixVariable*            g_WorldViewProjectionEV = NULL; // WorldViewProjection matrix effect variable
  72.     ID3DX11EffectShaderResourceVariable*    g_DiffuseEV = NULL; // Effect variable for the diffuse color texture
  73.     ID3DX11EffectVectorVariable*            g_LightDirEV = NULL; // Light direction in object space
  74.     ID3DX11EffectShaderResourceVariable*    g_HeightEV = NULL;
  75.     ID3DX11EffectShaderResourceVariable*    g_NormalEV = NULL;
  76.     ID3DX11EffectScalarVariable*                    g_TerrainResEV = NULL;
  77.     ID3DX11EffectScalarVariable*                    g_TerrainQuadResEV = NULL;
  78.     ID3DX11EffectShaderResourceVariable*    g_SpecularEV = NULL;
  79.     ID3DX11EffectShaderResourceVariable*    g_GlowEV = NULL;
  80.     ID3DX11EffectMatrixVariable*                    g_WorldViewEV = NULL;
  81.     ID3DX11EffectMatrixVariable*                    g_WorldViewNormalsEV = NULL;
  82.     ID3DX11EffectVectorVariable*                    g_LightDirViewEV = NULL;
  83.     ID3DX11EffectPass*                                              g_Pass1_Mesh = NULL;
  84.      
  85.     // Background color
  86.     D3DXVECTOR4                             g_ClearColor;
  87.      
  88.     // Terrain meta information
  89.     struct PtfHeader {
  90.         int16_t magicNumber;        // Must be 0x00DA
  91.         int16_t version;            // Must be 1
  92.         int32_t heightSize;     // Height data size
  93.         int32_t colorSize;      // Color data size
  94.         int32_t normalSize;     // Normal data size
  95.     }                                           g_TerrainHeader;
  96.  
  97.         struct Spawn {
  98.                 float spawntime;
  99.                 float hMin;
  100.                 float hMax;
  101.                 float innerRadius;
  102.                 float outerRadius;
  103.                 float borderRadius;
  104.         };
  105.  
  106.         struct Object {
  107.                 string name;
  108.         float scale;
  109.                 float translationX;
  110.                 float translationY;
  111.                 float translationZ;
  112.                 float rotationX;
  113.                 float rotationY;
  114.                 float rotationZ;
  115.     };  
  116.  
  117.         struct Gun
  118.         {
  119.                 float projectileSpeed;
  120.                 float cooldown;
  121.                 float damage;
  122.                 float particleMass;
  123.                 int textureIndex;
  124.                 float radius;
  125.                 float spawnPoint;
  126.                 float cooldownLeft;
  127.                 bool firing;
  128.         };
  129.  
  130.         struct Projectile
  131.         {
  132.                 float lifetime;
  133.                 float Speed;
  134.                 D3DXVECTOR3 pos;
  135.                 D3DXVECTOR3 dir;
  136.         };
  137.  
  138.         struct ExplosionParticleSettings
  139.         {
  140.                 int texIndex;
  141.                 int maxNumber;
  142.                 int minNumber;
  143.                 float maxLifeTime;
  144.                 float minLifeTime;
  145.                 float maxSpeed;
  146.                 float minSpeed;
  147.                 float maxRadius;
  148.                 float minRadius;
  149.         };
  150.  
  151.         struct ExplosionParticle
  152.         {
  153.                 float timePassed;
  154.                 float lifetime;
  155.                 float speed;
  156.                 float radius;
  157.                 D3DXVECTOR3 pos;
  158.                 D3DXVECTOR3 dir;
  159.         };
  160.  
  161.         struct EnemyType{
  162.  
  163.                 int hitpoints;
  164.                 int boundingSize;
  165.                 int speed;
  166.                 string meshname;
  167.                 string name;
  168.         float scale;
  169.                 float translationX;
  170.                 float translationY;
  171.                 float translationZ;
  172.                 float rotationX;
  173.                 float rotationY;
  174.                 float rotationZ;
  175.  
  176.         };
  177.  
  178.         struct EnemyInstance {
  179.                 string typeName;
  180.                 int speed;
  181.                 int remainingHitpoints;
  182.                 D3DXVECTOR3 pos;
  183.                 D3DXVECTOR3 vel;
  184.         };
  185.  
  186.         struct explosionStandard{
  187.                 int number;
  188.                 int texIndex;
  189.                 float duration;
  190.         };
  191.  
  192.         struct Explosion {
  193.                 float timePassed;
  194.                 D3DXVECTOR3 pos;
  195.         };
  196.  
  197.     char                                    g_TerrainPath[MAX_PATH] = { '\0' };
  198.     int                                     g_TerrainResolution;
  199.     int                                     g_TerrainNumVertices = 3;
  200.     int                                     g_TerrainNumTriangles = 1;
  201.     float                                   g_TerrainWidth = 1000.0f;
  202.     float                                   g_TerrainDepth = 1000.0f;
  203.     float                                   g_TerrainHeight = 400.0f;
  204.     bool                                    g_TerrainSpinning = true;
  205.     float                                   g_TerrainSpinSpeed = 0.0f;
  206.     D3DXMATRIX                              g_TerrainWorld; // object- to world-space transformation
  207.  
  208.      
  209.     // Terrain rendering resources
  210.     ID3D11Buffer*                           g_TerrainHeightBuf = NULL;
  211.     ID3D11ShaderResourceView*               g_TerrainHeightSRV = NULL;
  212.     ID3D11Texture2D*                        g_TerrainNormalTex = NULL;
  213.     ID3D11ShaderResourceView*               g_TerrainNormalSRV = NULL;
  214.     ID3D11Texture2D*                        g_TerrainDiffuseTex = NULL; // The terrain's material color for diffuse lighting
  215.     ID3D11ShaderResourceView*               g_TerrainDiffuseSRV = NULL; // Describes the structure of the diffuse texture to the shader stages
  216.      
  217.     //Meshs/Objects
  218.     ID3D11InputLayout* g_MeshInputLayout = NULL;
  219.         map<string, Mesh*> g_Meshes;
  220.         map<string, EnemyType> g_EnemyTypes;
  221.         list <string> enemytypes;
  222.         vector<Object> CockpitObjects;
  223.         vector<Object> GroundObjects;
  224.     vector<unsigned short> terrainHeights;
  225.         list<EnemyInstance> g_Enemies;
  226.         Spawn spawn;
  227.         float g_SpawnTimer = 0.0f;
  228.  
  229.         //Sprites
  230.         SpriteRenderer* g_SpriteRenderer;
  231.         vector<Sprite> textureFilenames;
  232.         vector<Projectile> g_Projectiles_Gatling;
  233.         vector<Projectile> g_Projectiles_Plasma;
  234.         list<Explosion> g_Explosions;
  235.         explosionStandard g_explStandard;
  236.         ExplosionParticleSettings eps;
  237.         list<ExplosionParticle> g_explParticles;
  238.        
  239.         //Guns
  240.         Gun Gatling;
  241.         Gun Plasma;
  242.  
  243.     // Scene information
  244.     D3DXVECTOR4                             g_LightDir;
  245.      
  246.     // General meta data
  247.     char                                    g_DebugTexPath[MAX_PATH] = { '\0' };
  248.      
  249.     // General resources
  250.     ID3D11ShaderResourceView*               g_DebugSRV = NULL;
  251.      
  252.     //--------------------------------------------------------------------------------------
  253.     // UI control IDs
  254.     //--------------------------------------------------------------------------------------
  255.     #define IDC_TOGGLEFULLSCREEN    1
  256.     #define IDC_TOGGLEREF           2
  257.     #define IDC_CHANGEDEVICE        3
  258.     #define IDC_TOGGLESPIN          4
  259.     #define IDC_RELOAD_SHADERS              101
  260.      
  261.  
  262.     //--------------------------------------------------------------------------------------
  263.     // Forward declarations
  264.     //--------------------------------------------------------------------------------------
  265.     LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
  266.                               void* pUserContext );
  267.     void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
  268.     void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
  269.     void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
  270.     bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );
  271.      
  272.     bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
  273.                                            DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
  274.     HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
  275.                                          void* pUserContext );
  276.     HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
  277.                                              const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
  278.     void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext );
  279.     void CALLBACK OnD3D11DestroyDevice( void* pUserContext );
  280.     void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime,
  281.                                      float fElapsedTime, void* pUserContext );
  282.      
  283.     void InitApp();
  284.     void DeinitApp();
  285.     void RenderText();
  286.      
  287.     void ReleaseShader();
  288.     HRESULT ReloadShader(ID3D11Device* pd3dDevice);
  289.      
  290.     //--------------------------------------------------------------------------------------
  291.     // Entry point to the program. Initializes everything and goes into a message processing
  292.     // loop. Idle time is used to render the scene.
  293.     //--------------------------------------------------------------------------------------
  294.     int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
  295.     {
  296.         // Enable run-time memory check for debug builds.
  297.     #if defined(DEBUG) | defined(_DEBUG)
  298.         _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
  299.     #endif
  300.      
  301.         // Old Direct3D Documentation:
  302.         // Start > All Programs > Microsoft DirectX SDK (June 2010) > Windows DirectX Graphics Documentation
  303.      
  304.         // DXUT Documentaion:
  305.         // Start > All Programs > Microsoft DirectX SDK (June 2010) > DirectX Documentation for C++ : The DirectX Software Development Kit > Programming Guide > DXUT
  306.      
  307.      
  308.         // New Direct3D Documentaion (just for reference, use old documentation to find explanations):
  309.         // http://msdn.microsoft.com/en-us/library/windows/desktop/hh309466%28v=vs.85%29.aspx
  310.      
  311.      
  312.      
  313.         // Set DXUT callbacks
  314.         DXUTSetCallbackMsgProc( MsgProc );
  315.         DXUTSetCallbackKeyboard( OnKeyboard );
  316.         DXUTSetCallbackFrameMove( OnFrameMove );
  317.         DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
  318.      
  319.         DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable );
  320.         DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice );
  321.         DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain );
  322.         DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain );
  323.         DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice );
  324.         DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender );
  325.      
  326.         InitApp();
  327.         DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params
  328.         DXUTSetCursorSettings( true, true );
  329.         DXUTCreateWindow( L"TerrainViewer" ); // You may change the title
  330.      
  331.         DXUTCreateDevice( D3D_FEATURE_LEVEL_10_0, true, 1280, 720 );
  332.      
  333.         DXUTMainLoop(); // Enter into the DXUT render loop
  334.             DXUTShutdown();
  335.             DeinitApp();
  336.         return DXUTGetExitCode();
  337.     }
  338.      
  339.     //--------------------------------------------------------------------------------------
  340.     // Initialize the app
  341.     //--------------------------------------------------------------------------------------
  342.     void InitApp()
  343.     {
  344.                      
  345.                 char MeshName[MAX_PATH] = {'\0'};
  346.                 char T3dPath[MAX_PATH]={'\0'};
  347.                 char DiffusePath[MAX_PATH] = {'\0'};
  348.                 char SpecularPath[MAX_PATH] = {'\0'};
  349.                 char GlowPath[MAX_PATH] = {'\0'};
  350.                 string name;
  351.                 string meshname;
  352.                 float scale;
  353.                 float translationX, translationY, translationZ;
  354.                 float rotationX, rotationY, rotationZ;  
  355.                 HRESULT hr;
  356.         WCHAR path[MAX_PATH];
  357.         // Parse the config file
  358.         V(DXUTFindDXSDKMediaFileCch(path, MAX_PATH, L"game.cfg"));
  359.         ifstream stream(path);
  360.         if(!stream) {
  361.            MessageBoxA (NULL, "Fatal Error: game.cfg not found.",
  362.                             "Missing file", MB_ICONERROR | MB_OK);
  363.                     return;
  364.         }
  365.      
  366.             std::string var;
  367.             while(!stream.eof())
  368.             {
  369.                     stream >> var;
  370.      
  371.                     if ( var.compare("DebugTexPath")   ==0 ) stream >> g_DebugTexPath;
  372.                     if ( var.compare("Spinning")       ==0 ) stream >> g_TerrainSpinning;
  373.                     if ( var.compare("SpinSpeed")      ==0 ) stream >> g_TerrainSpinSpeed;
  374.                     if ( var.compare("BackgroundColor")==0 ) stream >> g_ClearColor.x >> g_ClearColor.y >> g_ClearColor.z >> g_ClearColor.w;
  375.      
  376.                     // BEGIN: Assignment 3.2.1
  377.      
  378.                     if( var.compare("TerrainPath") ==0) stream >> g_TerrainPath;
  379.                     if( var.compare("TerrainWidth") ==0) stream >> g_TerrainWidth;
  380.                     if( var.compare("TerrainDepth") ==0) stream >> g_TerrainDepth;
  381.                     if( var.compare("TerrainHeight") ==0) stream >> g_TerrainHeight;
  382.      
  383.                    
  384.                    
  385.                     if(var.compare("Mesh") == 0){
  386.                                                 stream >> MeshName >>T3dPath >> DiffusePath >> SpecularPath >> GlowPath;
  387.                                                 g_Meshes[MeshName] = new Mesh(T3dPath, DiffusePath, SpecularPath, GlowPath);
  388.                                         }
  389.                                        
  390.                                         if (var.compare("CockpitObject") == 0)
  391.                                         {
  392.                                                 stream>>name>>scale>>rotationX>>rotationY>>rotationZ>>translationX>>translationY>>translationZ;
  393.                                                 Object co;
  394.                                                 co.name = name;
  395.                                                 co.scale = scale;
  396.                                                 co.rotationX = rotationX;
  397.                                                 co.rotationY = rotationY;
  398.                                                 co.rotationZ = rotationZ;
  399.                                                 co.translationX = translationX;
  400.                                                 co.translationY = translationY;
  401.                                                 co.translationZ = translationZ;
  402.                                                 CockpitObjects.push_back(co);
  403.                                         }
  404.                                         if(var.compare("GroundObject") == 0)
  405.                                         {
  406.                                                 stream>>name>>scale>>rotationX>>rotationY>>rotationZ>>translationX>>translationY>>translationZ;
  407.                                                 Object go;
  408.                                                 go.name = name;
  409.                                                 go.scale = scale;
  410.                                                 go.rotationX = rotationX;
  411.                                                 go.rotationY = rotationY;
  412.                                                 go.rotationZ = rotationZ;
  413.                                                 go.translationX = translationX;
  414.                                                 go.translationY = translationY;
  415.                                                 go.translationZ = translationZ;
  416.                                                 GroundObjects.push_back(go);
  417.                                         }
  418.                                         if(var.compare("EnemyType") == 0)
  419.                                         {
  420.                                                 EnemyType et;
  421.                                                 stream>>et.name>>et.hitpoints>>et.boundingSize>>et.speed>>et.meshname>>et.scale>>et.rotationX>>et.rotationY>>et.rotationZ>>et.translationX>>et.translationY>>et.translationZ;
  422.                                                
  423.                                                 enemytypes.push_back(et.name);
  424.                                                 g_EnemyTypes[et.name] = et;
  425.                                         }
  426.                                         if (var.compare("Spawn") == 0)
  427.                                         {
  428.                                                 stream>>spawn.spawntime>>spawn.hMin>>spawn.hMax>>spawn.innerRadius>>spawn.outerRadius>>spawn.borderRadius;
  429.                                         }
  430.                                        
  431.                                         if(var.compare("Gatling") == 0) stream>>Gatling.projectileSpeed>>Gatling.cooldown>>Gatling.damage>>Gatling.particleMass>>Gatling.textureIndex>>Gatling.radius>>Gatling.spawnPoint;
  432.                                         if(var.compare("Plasma") == 0) stream>>Plasma.projectileSpeed>>Plasma.cooldown>>Plasma.damage>>Plasma.particleMass>>Plasma.textureIndex>>Plasma.radius>>Plasma.spawnPoint;
  433.                                         if(var.compare("Sprite") == 0)
  434.                                         {
  435.                                                 Sprite s;
  436.                                                 stream>>s.filenameP>>s.min>>s.max;
  437.                                                 textureFilenames.push_back(s);
  438.                                         }
  439.                                         if(var.compare("Explosion") == 0) stream>>g_explStandard.texIndex>>g_explStandard.duration>>g_explStandard.number;
  440.                                         if(var.compare("ExplosionParticleSettings") == 0)stream>>eps.maxNumber>>eps.minNumber>>eps.maxLifeTime>>eps.minLifeTime>>eps.maxSpeed>>eps.minSpeed>>eps.maxRadius>>eps.minRadius>>eps.texIndex;
  441.                                         Gatling.firing = false;
  442.                                         Gatling.cooldownLeft = 0.f;
  443.                                         Plasma.firing = false;
  444.                                         Plasma.cooldownLeft = 0.f;
  445.  
  446.                                         // TODO: Parse the additional information in the config file into the variables:
  447.             // g_TerrainPath, g_TerrainWidth, g_TerrainDepth and g_TerrainHeight
  448.                     // HINT: the operator '>>' converts the next word in 'stream' into the format of
  449.                     //       its right hand side and is really flexible
  450.      
  451.             // END: Assignment 3.2.1
  452.             }
  453.      
  454.         stream.close();
  455.      
  456.         // Intialize the user interface
  457.      
  458.         g_SettingsDlg.Init( &g_DialogResourceManager );
  459.         g_HUD.Init( &g_DialogResourceManager );
  460.         g_SampleUI.Init( &g_DialogResourceManager );
  461.      
  462.         g_HUD.SetCallback( OnGUIEvent );
  463.         int iY = 30;
  464.         int iYo = 26;
  465.         g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 0, iY, 170, 22 );
  466.         g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 0, iY += iYo, 170, 22, VK_F3 );
  467.         g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 0, iY += iYo, 170, 22, VK_F2 );
  468.      
  469.             g_HUD.AddButton (IDC_RELOAD_SHADERS, L"Reload shaders (F5)", 0, iY += 24, 170, 22, VK_F5);
  470.        
  471.         g_SampleUI.SetCallback( OnGUIEvent ); iY = 10;
  472.         iY += 24;
  473.         g_SampleUI.AddCheckBox( IDC_TOGGLESPIN, L"Toggle Spinning", 0, iY += 24, 125, 22, g_TerrainSpinning );  
  474.         g_SpriteRenderer = new SpriteRenderer(textureFilenames);
  475.     }
  476.      
  477.      
  478.      
  479.     void DeinitApp()
  480.     {
  481.             SAFE_DELETE(g_Meshes["Cockpit"]);
  482.                         SAFE_DELETE(g_Meshes["GatlingGunBase"]);
  483.                         SAFE_DELETE(g_Meshes["GatlingGunTop"]);
  484.                         SAFE_DELETE(g_Meshes["PlasmaGunBase"]);
  485.                         SAFE_DELETE(g_Meshes["PlasmaGunTop"]);
  486.                         SAFE_DELETE(g_Meshes["Barracks"]);
  487.                         SAFE_DELETE(g_Meshes["Tree"]);
  488.                         SAFE_DELETE(g_Meshes["Amy"]);
  489.                         SAFE_DELETE(g_Meshes["Lup"]);
  490.                         SAFE_DELETE(g_Meshes["Juf"]);
  491.                         SAFE_DELETE(g_SpriteRenderer);
  492.     }
  493.     //--------------------------------------------------------------------------------------
  494.     // Render the help and statistics text. This function uses the ID3DXFont interface for
  495.     // efficient text rendering.
  496.     //--------------------------------------------------------------------------------------
  497.     void RenderText()
  498.     {
  499.         g_TxtHelper->Begin();
  500.         g_TxtHelper->SetInsertionPos( 5, 5 );
  501.         g_TxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) );
  502.         g_TxtHelper->DrawTextLine( DXUTGetFrameStats(true)); //DXUTIsVsyncEnabled() ) );
  503.         g_TxtHelper->DrawTextLine( DXUTGetDeviceStats() );
  504.         g_TxtHelper->End();
  505.     }
  506.      
  507.  
  508.         float getHeightAtPoint(float x, float y) {
  509.         int k = min(g_TerrainResolution - 1, (0.5f + x / g_TerrainWidth) * g_TerrainResolution);
  510.         int t = min(g_TerrainResolution - 1, (0.5f - y / g_TerrainDepth) * g_TerrainResolution);
  511.         return g_TerrainHeight * terrainHeights[(int)(k + g_TerrainResolution * t)] / (float)UINT16_MAX;
  512.         }
  513.      
  514.     //--------------------------------------------------------------------------------------
  515.     // Reject any D3D11 devices that aren't acceptable by returning false
  516.     //--------------------------------------------------------------------------------------
  517.     bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
  518.             DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
  519.     {
  520.         return true;
  521.     }
  522.      
  523.      
  524.     //--------------------------------------------------------------------------------------
  525.     // Specify the initial device settings
  526.     //--------------------------------------------------------------------------------------
  527.     bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
  528.     {
  529.         // For the first device created if its a REF device, optionally display a warning dialog box
  530.         static bool s_bFirstTime = true;
  531.         if( s_bFirstTime )
  532.         {
  533.             s_bFirstTime = false;
  534.             if( ( DXUT_D3D9_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF ) ||
  535.                 ( DXUT_D3D11_DEVICE == pDeviceSettings->ver &&
  536.                 pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) )
  537.             {
  538.                 DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver );
  539.             }
  540.      
  541.         }
  542.         //// Enable anti aliasing
  543.         //pDeviceSettings->d3d11.sd.SampleDesc.Count = 4;
  544.         //pDeviceSettings->d3d11.sd.SampleDesc.Quality = 1;
  545.      
  546.         return true;
  547.     }
  548.      
  549.      
  550.     //--------------------------------------------------------------------------------------
  551.     // Create any D3D11 resources that aren't dependant on the back buffer
  552.     //--------------------------------------------------------------------------------------
  553.     HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice,
  554.             const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
  555.     {
  556.         HRESULT hr;
  557.      
  558.         ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext(); // http://msdn.microsoft.com/en-us/library/ff476891%28v=vs.85%29
  559.         V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) );
  560.         V_RETURN( g_SettingsDlg.OnD3D11CreateDevice( pd3dDevice ) );
  561.         g_TxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 );
  562.      
  563.         V_RETURN( ReloadShader(pd3dDevice) );
  564.        
  565.         errno_t error;
  566.         WCHAR path[MAX_PATH];
  567.         stringstream ss;
  568.         wstringstream wss;      
  569.        
  570.        
  571.      
  572.         // Load the debug texture and create a shader resource view
  573.         wss.str(L""); wss << g_DebugTexPath;
  574.         V(DXUTFindDXSDKMediaFileCch( path, MAX_PATH, wss.str().c_str()));
  575.             if (hr != S_OK) {
  576.             ss.str();
  577.             ss << "Could not find '" << g_DebugTexPath << "'";
  578.             MessageBoxA (NULL, ss.str().c_str(), "Missing file", MB_ICONERROR | MB_OK);
  579.                     return hr;
  580.             }
  581.         V(D3DX11CreateShaderResourceViewFromFile(pd3dDevice, path, NULL, NULL, &g_DebugSRV, &hr));
  582.             if (hr != S_OK) {
  583.             ss.str();
  584.             ss << "Could not load texture '" << g_DebugTexPath << "'";
  585.             MessageBoxA (NULL, ss.str().c_str(), "Invalid texture", MB_ICONERROR | MB_OK);
  586.                     return hr;
  587.             }
  588.            
  589.      
  590.         // Find the terrain file
  591.         wss.str(L""); wss << g_TerrainPath;
  592.         V(DXUTFindDXSDKMediaFileCch( path, MAX_PATH, wss.str().c_str()));
  593.             if (hr != S_OK) {
  594.             ss.str();
  595.             ss << "Could not find '" << g_TerrainPath << "'";
  596.             MessageBoxA (NULL, ss.str().c_str(), "Missing file", MB_ICONERROR | MB_OK);
  597.                     return hr;
  598.             }
  599.      
  600.         // Open the terrain file
  601.         FILE* file;
  602.         error = _wfopen_s(&file, path, L"rb");
  603.             if (file == nullptr) {
  604.             ss.str();
  605.             ss << "Could not open '" << g_TerrainPath << "'";
  606.             MessageBoxA (NULL, ss.str().c_str(), "File error", MB_ICONERROR | MB_OK);
  607.                     return E_FAIL;
  608.             }
  609.      
  610.         // Read the terrain header
  611.             {
  612.                     auto r = fread (&g_TerrainHeader, sizeof (g_TerrainHeader), 1, file);
  613.                     if (r != 1) {
  614.                             MessageBoxA (NULL, "Could not read the header.",
  615.                                     "Invalid terrain file", MB_ICONERROR | MB_OK);
  616.                             return E_FAIL;
  617.                     }
  618.             }
  619.      
  620.         // Check the magic number
  621.             if (g_TerrainHeader.magicNumber != 0x00DA) {
  622.                     MessageBoxA (NULL, "The magic number is incorrect.",
  623.                             "Invalid terrain file header", MB_ICONERROR | MB_OK);
  624.                     return E_FAIL;
  625.             }
  626.      
  627.         // Check the version
  628.             if (g_TerrainHeader.version != 1) {
  629.                     MessageBoxA (NULL, "The header version is incorrect.",
  630.                             "Invalid terrain file header", MB_ICONERROR | MB_OK);
  631.                     return E_FAIL;
  632.             }
  633.      
  634.         // Calculate the terrain resolution from the height size
  635.             g_TerrainResolution = (int)sqrt(g_TerrainHeader.heightSize / 2.0); // Assume a square terrain
  636.         g_TerrainNumVertices = g_TerrainResolution * g_TerrainResolution;
  637.         g_TerrainNumTriangles = 2 * (g_TerrainResolution - 1) * (g_TerrainResolution - 1) ;
  638.         assert((g_TerrainHeader.heightSize / 2) == g_TerrainNumVertices);
  639.      
  640.             // Read the terrain heights
  641.             //std::vector<unsigned short> terrainHeights;
  642.             terrainHeights.resize(g_TerrainNumVertices);
  643.             {
  644.                     if (g_TerrainHeader.heightSize != (int)::fread (&terrainHeights[0], sizeof(BYTE), g_TerrainHeader.heightSize, file)) {
  645.                             MessageBoxA(NULL, "Error while reading height data.",
  646.                                     "Invalid terrain file", MB_ICONERROR | MB_OK);
  647.                             return E_FAIL;
  648.                     }    
  649.             }
  650.      
  651.         // Read the terrain color texture for diffuse lighting
  652.         std::vector<unsigned char> terrainDiffuseNtx;
  653.         terrainDiffuseNtx.resize(g_TerrainHeader.colorSize);
  654.             {
  655.             const auto requestedSize = terrainDiffuseNtx.size();
  656.                     if (requestedSize != fread (&terrainDiffuseNtx[0], sizeof(unsigned char), requestedSize, file)) {
  657.                             MessageBoxA (NULL, "Error while reading color data.",
  658.                                     "Invalid terrain file", MB_ICONERROR | MB_OK);
  659.                             return E_FAIL;
  660.                     }    
  661.             }
  662.             // Read the terrain normal texture
  663.             std::vector<unsigned char> terrainNormalNtx;
  664.         terrainNormalNtx.resize(g_TerrainHeader.normalSize);
  665.             {
  666.             const auto requestedSize = terrainNormalNtx.size();
  667.                     if (requestedSize != fread (&terrainNormalNtx[0], sizeof(unsigned char), requestedSize, file)) {
  668.                             MessageBoxA (NULL, "Error while reading color data.",
  669.                                     "Invalid terrain file", MB_ICONERROR | MB_OK);
  670.                             return E_FAIL;
  671.                     }    
  672.             }
  673.      
  674.      
  675.      
  676.         fclose(file);
  677.      
  678.                 // Initialize the camera
  679.         D3DXVECTOR3 Eye( 0.0f, terrainHeights[g_TerrainResolution*g_TerrainResolution/2+g_TerrainResolution/2]/UINT16_MAX  * g_TerrainHeight + 200, 0 );
  680.         D3DXVECTOR3 At( 0.0f, 0.0f, 0.0f );
  681.         g_Camera.SetViewParams( &Eye, &At ); // http://msdn.microsoft.com/en-us/library/windows/desktop/bb206342%28v=vs.85%29.aspx
  682.         g_Camera.SetScalers( g_CameraRotateScaler, g_CameraMoveScaler );
  683.  
  684.  
  685.             /*int iVB = 0; // You can use this variable as index into the vertex buffer ( terrainVB[iVB++] = ... )
  686.         float snx = (g_TerrainHeight * (g_TerrainResolution - 1)) / (g_TerrainWidth * 2.0f);
  687.         float sny = (g_TerrainHeight * (g_TerrainResolution - 1)) / (g_TerrainDepth * 2.0f);
  688.         for(int v = 0; v < g_TerrainResolution; v++) {
  689.             for(int u = 0; u < g_TerrainResolution; u++) {
  690.                 // Retrieve the height
  691.                 float height = terrainHeights[u + v * g_TerrainResolution] / 65535.f; // [0, 1]
  692.      
  693.                 // Calculate the normal
  694.                 float heightL = terrainHeights[max(0, u - 1) + v * g_TerrainResolution] / 65535.f;
  695.                 float heightR = terrainHeights[min(g_TerrainResolution - 1, u + 1) + v * g_TerrainResolution] / 65535.f;
  696.                 float heightU = terrainHeights[u + max(0, v - 1) * g_TerrainResolution] / 65535.f;
  697.                 float heightD = terrainHeights[u + min(g_TerrainResolution - 1, v + 1) * g_TerrainResolution] / 65535.f;
  698.                 D3DXVECTOR3 n(snx * (heightL - heightR), sny * (heightU - heightD), 1.f);
  699.                 D3DXVec3Normalize(&n, &n);
  700.            
  701.                     }
  702.             }*/
  703.        
  704.         // BEGIN: Assignment 4.2.6
  705.             D3D11_SUBRESOURCE_DATA id;
  706.             id.pSysMem = &terrainHeights[0];
  707.             id.SysMemPitch = sizeof(unsigned short);
  708.             id.SysMemSlicePitch = 0;
  709.             D3D11_BUFFER_DESC bd;
  710.             bd.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  711.             bd.ByteWidth = g_TerrainNumVertices * id.SysMemPitch;
  712.             bd.CPUAccessFlags = 0;
  713.             bd.MiscFlags = 0;
  714.             bd.Usage = D3D11_USAGE_DEFAULT;
  715.             pd3dDevice->CreateBuffer(&bd, &id, &g_TerrainHeightBuf);
  716.             D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  717.             srvDesc.Format = DXGI_FORMAT_R16_UNORM;
  718.             srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
  719.             srvDesc.Buffer.FirstElement = 0;
  720.             srvDesc.Buffer.NumElements = g_TerrainResolution * g_TerrainResolution;
  721.             V_RETURN(pd3dDevice->CreateShaderResourceView(g_TerrainHeightBuf, &srvDesc, &g_TerrainHeightSRV));
  722.             // END: Assignment 4.2.6
  723.      
  724.         D3D11_TEXTURE2D_DESC tex2DDesc;
  725.         std::vector<std::vector<unsigned char>> textureData;
  726.         std::vector<D3D11_SUBRESOURCE_DATA> subresourceData;
  727.         bool sRgb;
  728.      
  729.             LoadNtx(terrainDiffuseNtx, &tex2DDesc, textureData, subresourceData, sRgb );
  730.             pd3dDevice->CreateTexture2D(&tex2DDesc, &subresourceData[0], &g_TerrainDiffuseTex);
  731.             pd3dDevice->CreateShaderResourceView(g_TerrainDiffuseTex, NULL, &g_TerrainDiffuseSRV);
  732.      
  733.      
  734.         LoadNtx(terrainNormalNtx, &tex2DDesc, textureData, subresourceData, sRgb);
  735.             pd3dDevice->CreateTexture2D(&tex2DDesc, &subresourceData[0], &g_TerrainNormalTex);
  736.             pd3dDevice->CreateShaderResourceView(g_TerrainNormalTex, NULL,&g_TerrainNormalSRV);
  737.      
  738.                        
  739.                         g_Meshes["Cockpit"]->CreateResources(pd3dDevice);
  740.                         g_Meshes["GatlingGunBase"]->CreateResources(pd3dDevice);
  741.                         g_Meshes["GatlingGunTop"]->CreateResources(pd3dDevice);
  742.                         g_Meshes["PlasmaGunBase"]->CreateResources(pd3dDevice);
  743.                         g_Meshes["PlasmaGunTop"]->CreateResources(pd3dDevice);
  744.                         g_Meshes["Barracks"]->CreateResources(pd3dDevice);
  745.                         g_Meshes["Tree"]->CreateResources(pd3dDevice);
  746.                         g_Meshes["Amy"]->CreateResources(pd3dDevice);
  747.                         g_Meshes["Lup"]->CreateResources(pd3dDevice);
  748.                         g_Meshes["Juf"]->CreateResources(pd3dDevice);
  749.                         g_SpriteRenderer->CreateResources(pd3dDevice);
  750.             T3d::CreateT3dInputLayout(pd3dDevice, g_Pass1_Mesh, &g_MeshInputLayout);
  751.      
  752.         return S_OK;
  753.             }
  754.      
  755.      
  756.     //--------------------------------------------------------------------------------------
  757.     // Release D3D11 resources created in OnD3D11CreateDevice
  758.     //--------------------------------------------------------------------------------------
  759.     void CALLBACK OnD3D11DestroyDevice( void* pUserContext )
  760.     {
  761.         g_DialogResourceManager.OnD3D11DestroyDevice();
  762.         g_SettingsDlg.OnD3D11DestroyDevice();
  763.         DXUTGetGlobalResourceCache().OnDestroyDevice();
  764.         SAFE_RELEASE( g_DebugSRV );
  765.      
  766.         // Assignment 3.2.4
  767.         // TODO: Release the index buffer
  768.      
  769.         // Assignment 3.2.5
  770.         // TODO: Release the terrain's shader resource view and texture
  771.             SAFE_RELEASE(g_TerrainDiffuseTex);
  772.             SAFE_RELEASE(g_TerrainDiffuseSRV);
  773.             SAFE_RELEASE(g_TerrainNormalTex);
  774.             SAFE_RELEASE(g_TerrainNormalSRV);
  775.             SAFE_RELEASE(g_TerrainHeightBuf);
  776.         SAFE_RELEASE(g_TerrainHeightSRV);
  777.             SAFE_RELEASE(g_MeshInputLayout);
  778.         SAFE_DELETE( g_TxtHelper );
  779.                 g_Meshes["Cockpit"]->ReleaseResources();
  780.                 g_Meshes["GatlingGunBase"]->ReleaseResources();
  781.                 g_Meshes["GatlingGunTop"]->ReleaseResources();
  782.                 g_Meshes["PlasmaGunBase"]->ReleaseResources();
  783.                 g_Meshes["PlasmaGunTop"]->ReleaseResources();
  784.                 g_Meshes["Barracks"]->ReleaseResources();
  785.                 g_Meshes["Tree"]->ReleaseResources();
  786.                 g_Meshes["Amy"]->ReleaseResources();
  787.                 g_Meshes["Lup"]->ReleaseResources();
  788.                 g_Meshes["Juf"]->ReleaseResources();
  789.                 g_SpriteRenderer->ReleaseResources();
  790.         ReleaseShader();
  791.     }
  792.      
  793.      
  794.     //--------------------------------------------------------------------------------------
  795.     // Create any D3D11 resources that depend on the back buffer
  796.     //--------------------------------------------------------------------------------------
  797.     HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
  798.             const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
  799.     {
  800.         HRESULT hr;
  801.        
  802.         // Intialize the user interface
  803.      
  804.         V_RETURN( g_DialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
  805.         V_RETURN( g_SettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
  806.      
  807.         g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 );
  808.         g_HUD.SetSize( 170, 170 );
  809.         g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 );
  810.         g_SampleUI.SetSize( 170, 300 );
  811.      
  812.         // Initialize the camera
  813.      
  814.         g_CameraParams.m_Aspect = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height;
  815.         g_CameraParams.m_Fovy = 0.785398;
  816.         g_CameraParams.m_NearPlane = 1.f;
  817.         g_CameraParams.m_FarPlane = 2000.f;
  818.      
  819.         g_Camera.SetProjParams(g_CameraParams.m_Fovy, g_CameraParams.m_Aspect, g_CameraParams.m_NearPlane, g_CameraParams.m_FarPlane);
  820.             g_Camera.SetEnablePositionMovement(false);
  821.             g_Camera.SetRotateButtons(true, false, false);
  822.             g_Camera.SetScalers( g_CameraRotateScaler, g_CameraMoveScaler );
  823.             g_Camera.SetDrag( true );
  824.      
  825.         return S_OK;
  826.     }
  827.      
  828.      
  829.     //--------------------------------------------------------------------------------------
  830.     // Release D3D11 resources created in OnD3D11ResizedSwapChain
  831.     //--------------------------------------------------------------------------------------
  832.     void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext )
  833.     {
  834.         g_DialogResourceManager.OnD3D11ReleasingSwapChain();
  835.     }
  836.      
  837.      
  838.     //--------------------------------------------------------------------------------------
  839.     // Loads the effect from file
  840.     // and retrieves all dependent variables
  841.     //--------------------------------------------------------------------------------------
  842.     HRESULT ReloadShader(ID3D11Device* pd3dDevice)
  843.     {
  844.         assert(pd3dDevice != NULL);
  845.      
  846.         HRESULT hr;
  847.      
  848.         ReleaseShader();
  849.            
  850.         WCHAR path[MAX_PATH];
  851.         stringstream ss;
  852.         wstringstream wss;
  853.        
  854.         // Find and load the rendering effect
  855.         V_RETURN(DXUTFindDXSDKMediaFileCch(path, MAX_PATH, L"game.fxo"));
  856.         ifstream is(path, ios_base::binary);
  857.         is.seekg(0, ios_base::end);
  858.         streampos pos = is.tellg();
  859.         is.seekg(0, ios_base::beg);
  860.         vector<char> effectBuffer((unsigned int)pos);
  861.         is.read(&effectBuffer[0], pos);
  862.         is.close();
  863.         V_RETURN(D3DX11CreateEffectFromMemory((const void*)&effectBuffer[0], effectBuffer.size(), 0, pd3dDevice, &g_Effect));    
  864.         assert(g_Effect->IsValid());
  865.      
  866.         // Obtain the effect technique
  867.         SAFE_GET_TECHNIQUE(g_Effect, "Render", g_Technique);
  868.      
  869.         // Obtain the effect pass
  870.         SAFE_GET_PASS(g_Technique, "P0", g_Pass0);
  871.             SAFE_GET_PASS(g_Technique, "P1_Mesh", g_Pass1_Mesh);
  872.      
  873.         // Obtain the effect variables
  874.         SAFE_GET_RESOURCE(g_Effect, "g_Diffuse", g_DiffuseEV);
  875.         SAFE_GET_MATRIX(g_Effect, "g_World", g_WorldEV);
  876.         SAFE_GET_MATRIX(g_Effect, "g_WorldViewProjection", g_WorldViewProjectionEV);  
  877.         SAFE_GET_VECTOR(g_Effect, "g_LightDir", g_LightDirEV);  
  878.         SAFE_GET_RESOURCE(g_Effect, "g_Height", g_HeightEV);
  879.         SAFE_GET_RESOURCE(g_Effect, "g_Normal", g_NormalEV);
  880.         SAFE_GET_SCALAR(g_Effect, "g_TerrainRes", g_TerrainResEV);
  881.         SAFE_GET_SCALAR(g_Effect, "g_TerrainQuadRes", g_TerrainQuadResEV);
  882.         SAFE_GET_RESOURCE(g_Effect, "g_Specular", g_SpecularEV);
  883.         SAFE_GET_RESOURCE(g_Effect, "g_Glow", g_GlowEV);
  884.         SAFE_GET_MATRIX(g_Effect, "g_WorldView", g_WorldViewEV);
  885.         SAFE_GET_MATRIX(g_Effect, "g_WorldViewNormals", g_WorldViewNormalsEV);
  886.         SAFE_GET_VECTOR(g_Effect, "g_LightDirView", g_LightDirViewEV);
  887.  
  888.                 g_SpriteRenderer->ReloadShader(pd3dDevice);
  889.  
  890.         return S_OK;
  891.     }
  892.      
  893.      
  894.     //--------------------------------------------------------------------------------------
  895.     // Release resources created in ReloadShader
  896.     //--------------------------------------------------------------------------------------
  897.     void ReleaseShader()
  898.     {
  899.         SAFE_RELEASE( g_Effect );
  900.                 g_SpriteRenderer->ReleaseShader();
  901.     }
  902.      
  903.     //--------------------------------------------------------------------------------------
  904.     // Handle messages to the application
  905.     //--------------------------------------------------------------------------------------
  906.     LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
  907.                               void* pUserContext )
  908.     {
  909.         // Pass messages to dialog resource manager calls so GUI state is updated correctly
  910.         *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam );
  911.         if( *pbNoFurtherProcessing )
  912.             return 0;
  913.      
  914.         // Pass messages to settings dialog if its active
  915.         if( g_SettingsDlg.IsActive() )
  916.         {
  917.             g_SettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
  918.             return 0;
  919.         }
  920.      
  921.         // Give the dialogs a chance to handle the message first
  922.         *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam );
  923.         if( *pbNoFurtherProcessing )
  924.             return 0;
  925.         *pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam );
  926.         if( *pbNoFurtherProcessing )
  927.             return 0;
  928.            
  929.         // Use the mouse weel to control the movement speed
  930.         if(uMsg == WM_MOUSEWHEEL) {
  931.             int zDelta = GET_WHEEL_DELTA_WPARAM(wParam);
  932.             g_CameraMoveScaler *= (1 + zDelta / 500.0f);
  933.             if (g_CameraMoveScaler < 0.1f)
  934.               g_CameraMoveScaler = 0.1f;
  935.             g_Camera.SetScalers(g_CameraRotateScaler, g_CameraMoveScaler);
  936.         }
  937.      
  938.         // Pass all remaining windows messages to camera so it can respond to user input
  939.         g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam );
  940.      
  941.         return 0;
  942.     }
  943.      
  944.      
  945.     //--------------------------------------------------------------------------------------
  946.     // Handle key presses
  947.     //--------------------------------------------------------------------------------------
  948.     void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext )
  949.     {
  950.                 if(nChar == 32)
  951.                 {
  952.                         if(bKeyDown) Gatling.firing = true;
  953.                 }
  954.                 if(nChar == 13)
  955.                 {
  956.                         if(bKeyDown) Plasma.firing = true;
  957.                 }
  958.     }
  959.  
  960.      
  961.      
  962.     //--------------------------------------------------------------------------------------
  963.     // Handles the GUI events
  964.     //--------------------------------------------------------------------------------------
  965.     void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
  966.     {
  967.         switch( nControlID )
  968.         {
  969.             case IDC_TOGGLEFULLSCREEN:
  970.                 DXUTToggleFullScreen(); break;
  971.             case IDC_TOGGLEREF:
  972.                 DXUTToggleREF(); break;
  973.             case IDC_CHANGEDEVICE:
  974.                 g_SettingsDlg.SetActive( !g_SettingsDlg.IsActive() ); break;
  975.             case IDC_TOGGLESPIN:
  976.                 g_TerrainSpinning = g_SampleUI.GetCheckBox( IDC_TOGGLESPIN )->GetChecked();
  977.                 break;
  978.                     case IDC_RELOAD_SHADERS:
  979.                             ReloadShader(DXUTGetD3D11Device ());
  980.                             break;
  981.         }
  982.     }
  983.      
  984.      
  985.     //--------------------------------------------------------------------------------------
  986.     // Handle updates to the scene.  This is called regardless of which D3D API is used
  987.     //--------------------------------------------------------------------------------------
  988.     void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
  989.     {
  990.         // Update the camera's position based on user input
  991.         g_Camera.FrameMove( fElapsedTime );
  992.        
  993.         D3DXMATRIX mTmp;
  994.  
  995.                 list<string>::iterator it;
  996.                 g_SpawnTimer -= fElapsedTime;
  997.                 if(g_SpawnTimer < 0)
  998.                 {
  999.                         g_SpawnTimer = spawn.spawntime;
  1000.  
  1001.                         EnemyInstance e;
  1002.                         D3DXVECTOR3 direction;
  1003.                        
  1004.                         int i = rand()%enemytypes.size();
  1005.                         it = enemytypes.begin();
  1006.                         std::advance(it, i);
  1007.                         e.typeName = *it;
  1008.  
  1009.                         e.remainingHitpoints = (g_EnemyTypes[e.typeName]).hitpoints;
  1010.  
  1011.                         e.speed = g_EnemyTypes[e.typeName].speed;
  1012.  
  1013.                        
  1014.                         float randVal = (float) rand() / (float) RAND_MAX;
  1015.                         float a = randVal * D3DX_PI*2;
  1016.                         e.pos.x = spawn.outerRadius * (sin(a), cos(a));
  1017.                         e.pos.z = spawn.outerRadius*(cos(a), sin(a));
  1018.                         e.pos.y = randVal*(spawn.hMax*g_TerrainHeight - spawn.hMin*g_TerrainHeight) + spawn.hMin*g_TerrainHeight;
  1019.  
  1020.                         randVal = (float) rand() / (float) RAND_MAX;
  1021.                         a = randVal * D3DX_PI*2;
  1022.                         direction.x = spawn.innerRadius * (sin(a), cos(a));
  1023.                         direction.z = spawn.innerRadius * (cos(a), sin(a));
  1024.                         direction.y = e.pos.y;
  1025.                         D3DXVECTOR3 helpvec = direction - e.pos;
  1026.                         D3DXVec3Normalize(&helpvec,&helpvec);
  1027.                         e.vel = (D3DXVECTOR3)(e.speed * helpvec);
  1028.  
  1029.                         g_Enemies.push_back(e);
  1030.                 }
  1031.                 Gatling.cooldownLeft -= fElapsedTime;
  1032.                 if(Gatling.firing)
  1033.                 {
  1034.                         if(Gatling.cooldownLeft <= 0.f)
  1035.                         {
  1036.                                 Projectile pro;
  1037.  
  1038.                                 pro.Speed = Gatling.projectileSpeed;
  1039.                                 pro.lifetime = 0.f;
  1040.                                 pro.dir = *g_Camera.GetWorldAhead();
  1041.  
  1042.                                 D3DXMATRIX world = *g_Camera.GetWorldMatrix();
  1043.                                 D3DXVECTOR3 Spawn;
  1044.                                 Spawn.x = Gatling.spawnPoint;
  1045.                                 Spawn.y = 0.5;
  1046.                                 Spawn.z = 7;
  1047.                                 D3DXVec3TransformCoord(&pro.pos,&Spawn,&world);
  1048.                                 g_Projectiles_Gatling.push_back(pro);
  1049.                                 Gatling.cooldownLeft = Gatling.cooldown;
  1050.                                 Gatling.firing = false;
  1051.                         }
  1052.                          
  1053.                 }
  1054.  
  1055.                 /*D3DXVECTOR4 lightDirView;
  1056.                                 D3DXVec4Transform(&lightDirView, &g_LightDir, &viewTransformation);
  1057.                                 D3DXVec3Normalize((D3DXVECTOR3*)&lightDirView, (D3DXVECTOR3*)&lightDirView);*/
  1058.                 Plasma.cooldownLeft -= fElapsedTime;
  1059.                 if(Plasma.firing)
  1060.                 {
  1061.                         if(Plasma.cooldownLeft <= 0.f)
  1062.                         {
  1063.                                 Projectile pro;
  1064.                                 pro.lifetime = 0.f;
  1065.                                 pro.Speed = Plasma.projectileSpeed;
  1066.  
  1067.                                 pro.dir = *g_Camera.GetWorldAhead();
  1068.  
  1069.                                 D3DXMATRIX world = *g_Camera.GetWorldMatrix();
  1070.                                 D3DXVECTOR3 Spawn;
  1071.                                 Spawn.x = Plasma.spawnPoint;
  1072.                                 Spawn.y = 0.5;
  1073.                                 Spawn.z = 7;
  1074.                                 D3DXVec3TransformCoord(&pro.pos,&Spawn,&world);
  1075.                                 g_Projectiles_Plasma.push_back(pro);
  1076.                                 Plasma.cooldownLeft = Plasma.cooldown;
  1077.                                 Plasma.firing = false;
  1078.  
  1079.                         }
  1080.                 }
  1081.  
  1082.                 for(int i = 0; i < g_Projectiles_Gatling.size(); i++)
  1083.                 {
  1084.                         if(g_Projectiles_Gatling[i].lifetime > 5.f)
  1085.                         {
  1086.                                 Projectile helper;
  1087.                                 helper = g_Projectiles_Gatling[g_Projectiles_Gatling.size()-1];
  1088.                                 g_Projectiles_Gatling[g_Projectiles_Gatling.size()-1] = g_Projectiles_Gatling[i];
  1089.                                 g_Projectiles_Gatling[i] = helper;
  1090.                                 g_Projectiles_Gatling.resize(g_Projectiles_Gatling.size()-1);
  1091.                                 i--;
  1092.                         }
  1093.                         else
  1094.                         {
  1095.                                 g_Projectiles_Gatling[i].lifetime += fElapsedTime;
  1096.                                 g_Projectiles_Gatling[i].dir.y = g_Projectiles_Gatling[i].dir.y - Gatling.particleMass * fElapsedTime;
  1097.                                 g_Projectiles_Gatling[i].pos.x = g_Projectiles_Gatling[i].pos.x + g_Projectiles_Gatling[i].dir.x * Gatling.projectileSpeed * fElapsedTime;
  1098.                                 g_Projectiles_Gatling[i].pos.z = g_Projectiles_Gatling[i].pos.z + g_Projectiles_Gatling[i].dir.z * Gatling.projectileSpeed * fElapsedTime;
  1099.                                 g_Projectiles_Gatling[i].pos.y = g_Projectiles_Gatling[i].pos.y + g_Projectiles_Gatling[i].dir.y * Gatling.projectileSpeed * fElapsedTime;
  1100.                         }
  1101.                 }
  1102.  
  1103.  
  1104.                 for(int i = 0; i < g_Projectiles_Plasma.size() ; i++)
  1105.                 {
  1106.                         if(g_Projectiles_Plasma[i].lifetime > 7.f)
  1107.                         {
  1108.                                 Projectile helper;
  1109.                                 helper = g_Projectiles_Plasma[g_Projectiles_Plasma.size()-1];
  1110.                                 g_Projectiles_Plasma[g_Projectiles_Plasma.size()-1] = g_Projectiles_Plasma[i];
  1111.                                 g_Projectiles_Plasma[i] = helper;
  1112.                                 g_Projectiles_Plasma.resize(g_Projectiles_Plasma.size()-1);
  1113.                                 i--;
  1114.                         }
  1115.                         else
  1116.                         {
  1117.                                 g_Projectiles_Plasma[i].lifetime += fElapsedTime;
  1118.                                 g_Projectiles_Plasma[i].pos.x = g_Projectiles_Plasma[i].pos.x + g_Projectiles_Plasma[i].dir.x * Plasma.projectileSpeed * fElapsedTime;
  1119.                                 g_Projectiles_Plasma[i].pos.z = g_Projectiles_Plasma[i].pos.z + g_Projectiles_Plasma[i].dir.z * Plasma.projectileSpeed * fElapsedTime;
  1120.                                 g_Projectiles_Plasma[i].pos.y = g_Projectiles_Plasma[i].pos.y + g_Projectiles_Plasma[i].dir.y * (Plasma.projectileSpeed - Plasma.particleMass * fElapsedTime) * fElapsedTime;
  1121.                         }
  1122.                 }
  1123.  
  1124.                 for(int i = 0; i < g_Projectiles_Plasma.size(); i++)
  1125.                 {
  1126.                         for(auto it = g_Enemies.begin(); it != g_Enemies.end(); )
  1127.                         {
  1128.                                 if(D3DXVec3Length(&((*it).pos - g_Projectiles_Plasma[i].pos)) < (g_EnemyTypes[(*it).typeName]).boundingSize + Plasma.radius)
  1129.                                 {
  1130.                                         Projectile helper;
  1131.                                         helper = g_Projectiles_Plasma[g_Projectiles_Plasma.size()-1];
  1132.                                         g_Projectiles_Plasma[g_Projectiles_Plasma.size()-1] = g_Projectiles_Plasma[i];
  1133.                                         g_Projectiles_Plasma[i] = helper;
  1134.                                         g_Projectiles_Plasma.resize(g_Projectiles_Plasma.size()-1);
  1135.                                         i--;
  1136.                                         (*it).remainingHitpoints -= Plasma.damage;
  1137.                                         if((*it).remainingHitpoints <= 0)
  1138.                                         {
  1139.                                                 Explosion et;
  1140.                                                 et.pos = (*it).pos + (*it).vel;
  1141.                                                 et.timePassed = 0;
  1142.                                                 g_Explosions.push_back(et);
  1143.                                                 int number;
  1144.                                                 number = eps.minNumber + (rand()%(eps.maxNumber-eps.minNumber));
  1145.                                                 for(int i = 0; i<number; i++)
  1146.                                                 {
  1147.                                                         ExplosionParticle ep;
  1148.                                                         ep.lifetime = eps.minLifeTime +(rand()%int(eps.maxLifeTime*100-eps.minLifeTime*100))/100.f;
  1149.                                                         ep.pos = et.pos;
  1150.                                                         ep.timePassed = 0;
  1151.                                                         ep.radius = eps.minRadius + (rand()%int(eps.maxRadius*100-eps.minRadius*100))/100.f;
  1152.                                                         ep.speed = eps.minSpeed + (rand()%int(eps.maxSpeed-eps.minSpeed));
  1153.                                                         D3DXVECTOR3 dir;
  1154.                                                         float alpha = rand()%180;
  1155.                                                         float beta = rand()%360;
  1156.                                                         dir.x = sin(alpha) * cos(beta);
  1157.                                                         dir.y = sin(alpha) * sin(beta);
  1158.                                                         dir.z = cos(alpha);
  1159.                                                         ep.dir = dir;
  1160.                                                         g_explParticles.push_back(ep);
  1161.                                                 }
  1162.                                                 auto it_remove = it;
  1163.                                                 it++;
  1164.                                                 g_Enemies.erase(it_remove);
  1165.                                         }
  1166.                                         break;
  1167.                                 }
  1168.                                 it++;
  1169.                         }
  1170.                 }
  1171.  
  1172.                 for(int i = 0; i <g_Projectiles_Gatling.size();i++)
  1173.                 {
  1174.                         for(auto it = g_Enemies.begin(); it != g_Enemies.end(); )
  1175.                         {
  1176.                                 if(D3DXVec3Length(&((*it).pos - g_Projectiles_Gatling[i].pos)) < (g_EnemyTypes[(*it).typeName]).boundingSize + Gatling.radius)
  1177.                                 {
  1178.                                         Projectile helper;
  1179.                                         helper = g_Projectiles_Gatling[g_Projectiles_Gatling.size()-1];
  1180.                                         g_Projectiles_Gatling[g_Projectiles_Gatling.size()-1] = g_Projectiles_Gatling[i];
  1181.                                         g_Projectiles_Gatling[i] = helper;
  1182.                                         g_Projectiles_Gatling.resize(g_Projectiles_Gatling.size()-1);
  1183.                                         i--;
  1184.                                         (*it).remainingHitpoints -= Gatling.damage;
  1185.                                         if((*it).remainingHitpoints <= 0)
  1186.                                         {
  1187.                                                 Explosion et;
  1188.                                                 et.pos = (*it).pos + (*it).vel;
  1189.                                                 et.timePassed = 0;
  1190.                                                 g_Explosions.push_back(et);
  1191.                                                 int number;
  1192.                                                 number = eps.minNumber + (rand()%(eps.maxNumber-eps.minNumber));
  1193.                                                 for(int i = 0; i<number; i++)
  1194.                                                 {
  1195.                                                         ExplosionParticle ep;
  1196.                                                         ep.lifetime = eps.minLifeTime +(rand()%int(eps.maxLifeTime*100-eps.minLifeTime*100))/100.f;
  1197.                                                         ep.pos = et.pos;
  1198.                                                         ep.timePassed = 0;
  1199.                                                         ep.radius = eps.minRadius + (rand()%int(eps.maxRadius*100-eps.minRadius*100))/100.f;
  1200.                                                         ep.speed = eps.minSpeed + (rand()%int(eps.maxSpeed-eps.minSpeed));
  1201.                                                         D3DXVECTOR3 dir;
  1202.                                                         float alpha = rand()%180;
  1203.                                                         float beta = rand()%360;
  1204.                                                         dir.x = sin(alpha) * cos(beta);
  1205.                                                         dir.y = sin(alpha) * sin(beta);
  1206.                                                         dir.z = cos(alpha);
  1207.                                                         ep.dir = dir;
  1208.                                                         g_explParticles.push_back(ep);
  1209.                                                 }
  1210.                                                 auto it_remove = it;
  1211.                                                 it++;
  1212.                                                 g_Enemies.erase(it_remove);
  1213.                                         }
  1214.                                         break;
  1215.                                 }
  1216.                                 it++;
  1217.                         }
  1218.                 }
  1219.  
  1220.                 for(auto it = g_explParticles.begin(); it != g_explParticles.end();)
  1221.                 {
  1222.                         (*it).timePassed += fElapsedTime/(*it).lifetime;
  1223.                         (*it).pos.x = (*it).pos.x + (*it).dir.x * (*it).speed * fElapsedTime;
  1224.                         (*it).pos.z = (*it).pos.z + (*it).dir.z * (*it).speed * fElapsedTime;
  1225.                         (*it).pos.y = (*it).pos.y + (*it).dir.y * (*it).speed * fElapsedTime;
  1226.                         if((*it).timePassed >= 1)
  1227.                         {
  1228.                                 auto it_remove = it;
  1229.                                 it++;
  1230.                                 g_explParticles.erase(it_remove);
  1231.                                 break;
  1232.                         }
  1233.                         it++;
  1234.                 }
  1235.  
  1236.                 for(auto it = g_Explosions.begin(); it != g_Explosions.end();)
  1237.                 {
  1238.                         (*it).timePassed += fElapsedTime/g_explStandard.duration;
  1239.                         if((*it).timePassed >= 1.f)
  1240.                         {
  1241.                                 auto it_remove = it;
  1242.                                 it++;
  1243.                                 g_Explosions.erase(it_remove);
  1244.                                 break;
  1245.                         }
  1246.                         it++;
  1247.                 }
  1248.                 for(auto it = g_Enemies.begin(); it != g_Enemies.end(); )
  1249.                 {
  1250.                         if (D3DXVec3Length(&(*it).pos)>spawn.borderRadius)
  1251.                         {
  1252.                                 auto it_remove = it;
  1253.                                 it++;
  1254.                                 g_Enemies.erase(it_remove);
  1255.                         }
  1256.                         else
  1257.                         {
  1258.                                 (*it).pos += fElapsedTime * (*it).vel;
  1259.                                 it++;
  1260.                         }
  1261.  
  1262.                 }
  1263.         // Initialize the terrain world matrix
  1264.         // http://msdn.microsoft.com/en-us/library/windows/desktop/bb206365%28v=vs.85%29.aspx
  1265.        
  1266.         // Set origin to (0.5, 0.5, 0)
  1267.         D3DXMatrixTranslation(&g_TerrainWorld, -0.5f, -0.5f, 0.f); // Assume: x, y and z are in [0,1]
  1268.        
  1269.         // Scale to terrain extents
  1270.         D3DXMatrixScaling(&mTmp, g_TerrainWidth, g_TerrainDepth, g_TerrainHeight);
  1271.         g_TerrainWorld = g_TerrainWorld * mTmp;
  1272.      
  1273.         // Since "up" is z-axis in object space, but y-axis in world space, we rotate around the x-axis
  1274.         D3DXMatrixRotationX( &mTmp, DEG2RAD( -90.0f ) );
  1275.         g_TerrainWorld *= mTmp;
  1276.        
  1277.         if( g_TerrainSpinning ) {
  1278.             D3DXMatrixRotationY( &mTmp, g_TerrainSpinSpeed * DEG2RAD((float)fTime) );
  1279.             g_TerrainWorld *= mTmp; // Rotate around world-space "up" axis
  1280.         }
  1281.      
  1282.         g_LightDir = D3DXVECTOR4(1, 1, -1, 0); // Direction to the directional light in world space    
  1283.      
  1284.         // Transform the light vector to terrain object space
  1285.         //D3DXMATRIX invWorld;
  1286.         //D3DXMatrixInverse(&invWorld, NULL, &g_TerrainWorld);
  1287.         //D3DXVec4Transform(&g_LightDir, &g_LightDir, &invWorld);
  1288.      
  1289.         //D3DXVec3Normalize((D3DXVECTOR3*)&g_LightDir, (D3DXVECTOR3*)&g_LightDir); // Normalize the light direction
  1290.     }
  1291.      
  1292.      
  1293.     //--------------------------------------------------------------------------------------
  1294.     // Render the scene using the D3D11 device
  1295.     //--------------------------------------------------------------------------------------
  1296.         bool compare(SpriteVertex i, SpriteVertex j)
  1297.         {
  1298.                 return (D3DXVec3Dot(&i.Position,g_Camera.GetWorldAhead())>D3DXVec3Dot(&j.Position, g_Camera.GetWorldAhead()));
  1299.         }
  1300.  
  1301.  
  1302.     void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime,
  1303.             float fElapsedTime, void* pUserContext )
  1304.     {
  1305.         HRESULT hr;
  1306.  
  1307.                
  1308.         D3DXMATRIX inverseTerrainWorldDir;
  1309.         D3DXVECTOR4 lightDirObj;
  1310.      
  1311.         D3DXMatrixTranspose(&inverseTerrainWorldDir,&g_TerrainWorld);
  1312.         D3DXVec4Transform(&lightDirObj, &g_LightDir, &inverseTerrainWorldDir);
  1313.         D3DXVec3Normalize((D3DXVECTOR3*)&lightDirObj, (D3DXVECTOR3*)&lightDirObj);
  1314.         // If the settings dialog is being shown, then render it instead of rendering the app's scene
  1315.         if( g_SettingsDlg.IsActive() )
  1316.         {
  1317.             g_SettingsDlg.OnRender( fElapsedTime );
  1318.             return;
  1319.         }    
  1320.      
  1321.         ID3D11RenderTargetView* pRTV = DXUTGetD3D11RenderTargetView();
  1322.         pd3dImmediateContext->ClearRenderTargetView( pRTV, g_ClearColor );
  1323.            
  1324.         if(g_Effect == NULL) {
  1325.             g_TxtHelper->Begin();
  1326.             g_TxtHelper->SetInsertionPos( 5, 5 );
  1327.             g_TxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) );
  1328.             g_TxtHelper->DrawTextLine( L"SHADER ERROR" );
  1329.             g_TxtHelper->End();
  1330.             return;
  1331.         }
  1332.      
  1333.  
  1334.  
  1335.                 vector<SpriteVertex> SpriteVector;
  1336.                 for(int i = 0; i < g_Projectiles_Gatling.size();i++)
  1337.                 {
  1338.                         SpriteVertex s;
  1339.                         s.Position = g_Projectiles_Gatling[i].pos;
  1340.                         s.Radius = Gatling.radius;
  1341.                         s.TextureIndex = Gatling.textureIndex;
  1342.                         SpriteVector.push_back(s);
  1343.                 }
  1344.                 for(int i = 0; i < g_Projectiles_Plasma.size();i++)
  1345.                 {
  1346.                         SpriteVertex s;
  1347.                         s.Position = g_Projectiles_Plasma[i].pos;
  1348.                         s.Radius = Plasma.radius;
  1349.                         s.TextureIndex = Plasma.textureIndex;
  1350.                         SpriteVector.push_back(s);
  1351.                 }
  1352.                 for(auto it = g_Explosions.begin(); it != g_Explosions.end(); it++)
  1353.                 {
  1354.                         SpriteVertex s;
  1355.                         s.Position = (*it).pos;
  1356.                         s.Radius = 85;
  1357.                         s.TextureIndex = g_explStandard.texIndex;
  1358.                         s.t = (*it).timePassed;
  1359.                         SpriteVector.push_back(s);
  1360.                 }
  1361.                 for(auto it = g_explParticles.begin(); it != g_explParticles.end(); it++)
  1362.                 {
  1363.                         SpriteVertex s;
  1364.                         s.Position = (*it).pos;
  1365.                         s.Radius = (*it).radius;
  1366.                         s.TextureIndex = eps.texIndex;
  1367.                         s.t = (*it).timePassed;
  1368.                         SpriteVector.push_back(s);
  1369.                 }
  1370.                 sort(SpriteVector.begin(),SpriteVector.end(),compare);
  1371.                
  1372.         // Clear the depth stencil
  1373.         ID3D11DepthStencilView* pDSV = DXUTGetD3D11DepthStencilView();
  1374.         pd3dImmediateContext->ClearDepthStencilView( pDSV, D3D11_CLEAR_DEPTH, 1.0, 0 );
  1375.        
  1376.         //
  1377.         // Update variables that change once per frame
  1378.         //
  1379.         D3DXMATRIX const * view = g_Camera.GetViewMatrix(); // http://msdn.microsoft.com/en-us/library/windows/desktop/bb206342%28v=vs.85%29.aspx
  1380.         D3DXMATRIX const * proj = g_Camera.GetProjMatrix(); // http://msdn.microsoft.com/en-us/library/windows/desktop/bb147302%28v=vs.85%29.aspx
  1381.         D3DXMATRIX worldViewProj = g_TerrainWorld * (*view) * (*proj);
  1382.         g_WorldEV->SetMatrix( ( float* )&g_TerrainWorld );
  1383.         g_WorldViewProjectionEV->SetMatrix( ( float* )&worldViewProj );
  1384.         g_LightDirEV->SetFloatVector( ( float* )lightDirObj );
  1385.      
  1386.         // Set input layout
  1387.         pd3dImmediateContext->IASetInputLayout( NULL );
  1388.      
  1389.         // Bind the terrain vertex buffer to the input assembler stage
  1390.         ID3D11Buffer* vbs[] = { NULL, };
  1391.         unsigned int strides[] = { 0, }, offsets[] = { 0, };
  1392.         pd3dImmediateContext->IASetVertexBuffers(0, 1, vbs, strides, offsets);
  1393.      
  1394.         // Tell the input assembler stage which primitive topology to use
  1395.         pd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  1396.      
  1397.         // Assignment 3.2.4
  1398.         // TODO: Bind the terrain index buffer to the input assembler stage
  1399.             //pd3dImmediateContext->IASetIndexBuffer(NULL,DXGI_FORMAT_R32_UINT, 0 );
  1400.         // Assignment 3.2.5
  1401.         // TODO: Bind the SRV of the terrain diffuse texture to the effect variable
  1402.         // (instead of the SRV of the debug texture)
  1403.                         V(g_DiffuseEV->SetResource( g_TerrainDiffuseSRV));
  1404.             V(g_NormalEV->SetResource(g_TerrainNormalSRV));
  1405.             V(g_HeightEV->SetResource(g_TerrainHeightSRV));
  1406.             g_TerrainResEV->SetInt(g_TerrainResolution);
  1407.             g_TerrainQuadResEV->SetInt(g_TerrainResolution-1);
  1408.      
  1409.         // Apply the rendering pass in order to submit the necessary render state changes to the device
  1410.                         g_Pass0->Apply(0, pd3dImmediateContext);
  1411.      
  1412.         // Draw
  1413.            
  1414.            
  1415.         // Assignment 3.2.6
  1416.         // TODO: Use DrawIndexed to draw the terrain geometry using as shared vertex list
  1417.         // (instead of drawing only the vertex buffer)
  1418.                         pd3dImmediateContext->Draw(g_TerrainNumTriangles*3, 0);
  1419.            
  1420.             pd3dImmediateContext->IASetInputLayout(g_MeshInputLayout);
  1421.             pd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  1422.             unsigned int stride[] = {sizeof(T3dVertex),};
  1423.                         D3DXMATRIX mTrans, mScale, mRotX, mRotY, mRotZ;
  1424.  
  1425.                        
  1426.  
  1427.                         for(int i = 0; i < CockpitObjects.size(); i++)
  1428.                         {
  1429.                                 V(g_DiffuseEV->SetResource(g_Meshes[CockpitObjects[i].name]->GetDiffuseSRV()));
  1430.                                 V(g_SpecularEV->SetResource(g_Meshes[CockpitObjects[i].name]->GetSpecularSRV()));
  1431.                                 V(g_GlowEV->SetResource(g_Meshes[CockpitObjects[i].name]->GetGlowSRV()));
  1432.      
  1433.                                 ID3D11Buffer* vBS[] ={g_Meshes[CockpitObjects[i].name]->GetVertexBuffer(),};
  1434.                                 pd3dImmediateContext->IASetVertexBuffers(0, 1, vBS,stride, offsets);
  1435.                                 pd3dImmediateContext->IASetIndexBuffer(g_Meshes[CockpitObjects[i].name]->GetIndexBuffer(), g_Meshes[CockpitObjects[i].name]->GetIndexFormat(),0);
  1436.                                 D3DXMatrixRotationX(&mRotX, CockpitObjects[i].rotationX*(D3DX_PI/180.0));
  1437.                                 D3DXMatrixRotationY(&mRotY,CockpitObjects[i].rotationY*(D3DX_PI/180.0));
  1438.                                 D3DXMatrixRotationZ(&mRotZ,CockpitObjects[i].rotationZ*(D3DX_PI/180.0));
  1439.                                 D3DXMatrixScaling(&mScale, CockpitObjects[i].scale, CockpitObjects[i].scale, CockpitObjects[i].scale);
  1440.                                 D3DXMatrixTranslation(&mTrans, CockpitObjects[i].translationX, CockpitObjects[i].translationY, CockpitObjects[i].translationZ);
  1441.                                 D3DXMATRIX worldView = mScale * mRotX * mRotY * mRotZ * mTrans;
  1442.                                 worldViewProj = worldView * (*g_Camera.GetProjMatrix());
  1443.                                 D3DXMATRIX worldViewNormals;
  1444.                                 D3DXMatrixInverse(&worldViewNormals,NULL,&worldViewProj);
  1445.                                 D3DXMatrixTranspose(&worldViewNormals,&worldViewNormals);
  1446.      
  1447.                                
  1448.  
  1449.                                 g_WorldViewEV ->SetMatrix(worldView);
  1450.                                 g_WorldViewNormalsEV ->SetMatrix(worldViewNormals);
  1451.                                 g_WorldViewProjectionEV ->SetMatrix(worldViewProj);
  1452.      
  1453.                                 D3DXMATRIX viewTransformation;
  1454.                                 D3DXMatrixInverse(&viewTransformation, NULL, view);
  1455.                                 D3DXMatrixTranspose(&viewTransformation,&viewTransformation);
  1456.  
  1457.                                 D3DXVECTOR4 lightDirView;
  1458.                                 D3DXVec4Transform(&lightDirView, &g_LightDir, &viewTransformation);
  1459.                                 D3DXVec3Normalize((D3DXVECTOR3*)&lightDirView, (D3DXVECTOR3*)&lightDirView);
  1460.                                 g_LightDirViewEV->SetFloatVector((float*)&lightDirView);
  1461.      
  1462.                                
  1463.      
  1464.                                 g_Pass1_Mesh ->Apply(0, pd3dImmediateContext);
  1465.                                 pd3dImmediateContext->DrawIndexed(g_Meshes[CockpitObjects[i].name]->GetIndexCount(), 0, 0);
  1466.                         }
  1467.  
  1468.                        
  1469.                         for(int i = 0; i < GroundObjects.size(); i++)
  1470.                         {
  1471.                                 V(g_DiffuseEV->SetResource(g_Meshes[GroundObjects[i].name]->GetDiffuseSRV()));
  1472.                                 V(g_SpecularEV->SetResource(g_Meshes[GroundObjects[i].name]->GetSpecularSRV()));
  1473.                                 V(g_GlowEV->SetResource(g_Meshes[GroundObjects[i].name]->GetGlowSRV()));
  1474.      
  1475.                                 ID3D11Buffer* vBS[] ={g_Meshes[GroundObjects[i].name]->GetVertexBuffer(),};
  1476.                                 pd3dImmediateContext->IASetVertexBuffers(0, 1, vBS,stride, offsets);
  1477.                                 pd3dImmediateContext->IASetIndexBuffer(g_Meshes[GroundObjects[i].name]->GetIndexBuffer(), g_Meshes[GroundObjects[i].name]->GetIndexFormat(),0);
  1478.                                 D3DXMatrixRotationX(&mRotX, GroundObjects[i].rotationX*(D3DX_PI/180.0));
  1479.                                 D3DXMatrixRotationY(&mRotY,GroundObjects[i].rotationY*(D3DX_PI/180.0));
  1480.                                 D3DXMatrixRotationZ(&mRotZ,GroundObjects[i].rotationZ*(D3DX_PI/180.0));
  1481.                                 D3DXMatrixScaling(&mScale, GroundObjects[i].scale, GroundObjects[i].scale, GroundObjects[i].scale);
  1482.                                 D3DXMatrixTranslation(&mTrans, GroundObjects[i].translationX, GroundObjects[i].translationY, getHeightAtPoint(GroundObjects[i].translationX,GroundObjects[i].translationY) + 10);
  1483.                                 D3DXMATRIX worldView = mScale * mRotX * mRotY * mRotZ * mTrans * (*g_Camera.GetViewMatrix());
  1484.                                 worldViewProj = worldView * (*g_Camera.GetProjMatrix());
  1485.  
  1486.                                 D3DXMATRIX worldViewNormals;
  1487.                                 D3DXMatrixInverse(&worldViewNormals,NULL,&worldViewProj);
  1488.                                 D3DXMatrixTranspose(&worldViewNormals,&worldViewNormals);
  1489.      
  1490.                                
  1491.  
  1492.                                 g_WorldViewEV ->SetMatrix(worldView);
  1493.                                 g_WorldViewNormalsEV ->SetMatrix(worldViewNormals);
  1494.                                 g_WorldViewProjectionEV ->SetMatrix(worldViewProj);
  1495.      
  1496.                                 D3DXMATRIX viewTransformation;
  1497.                                 D3DXMatrixInverse(&viewTransformation, NULL, view);
  1498.                                 D3DXMatrixTranspose(&viewTransformation,&viewTransformation);
  1499.  
  1500.                                 D3DXVECTOR4 lightDirView;
  1501.                                 D3DXVec4Transform(&lightDirView, &g_LightDir, &viewTransformation);
  1502.                                 D3DXVec3Normalize((D3DXVECTOR3*)&lightDirView, (D3DXVECTOR3*)&lightDirView);
  1503.                                 g_LightDirViewEV->SetFloatVector((float*)&lightDirView);
  1504.      
  1505.                                 g_Pass1_Mesh ->Apply(0, pd3dImmediateContext);
  1506.                                 pd3dImmediateContext->DrawIndexed(g_Meshes[GroundObjects[i].name]->GetIndexCount(), 0, 0);
  1507.                         }
  1508.  
  1509.                         for(auto it = g_Enemies.begin(); it != g_Enemies.end(); it++)
  1510.                         {
  1511.                                 V(g_DiffuseEV->SetResource(g_Meshes[g_EnemyTypes[(*it).typeName].meshname]->GetDiffuseSRV()));
  1512.                                 V(g_SpecularEV->SetResource(g_Meshes[g_EnemyTypes[(*it).typeName].meshname]->GetSpecularSRV()));
  1513.                                 V(g_GlowEV->SetResource(g_Meshes[g_EnemyTypes[(*it).typeName].meshname]->GetGlowSRV()));
  1514.      
  1515.                                 ID3D11Buffer* vBS[] ={g_Meshes[g_EnemyTypes[(*it).typeName].meshname]->GetVertexBuffer(),};
  1516.                                 pd3dImmediateContext->IASetVertexBuffers(0, 1, vBS,stride, offsets);
  1517.                                 pd3dImmediateContext->IASetIndexBuffer(g_Meshes[g_EnemyTypes[(*it).typeName].meshname]->GetIndexBuffer(), g_Meshes[g_EnemyTypes[(*it).typeName].meshname]->GetIndexFormat(),0);
  1518.                                 D3DXMatrixRotationX(&mRotX, g_EnemyTypes[(*it).typeName].rotationX*(D3DX_PI/180.0));
  1519.                                 D3DXMatrixRotationY(&mRotY,g_EnemyTypes[(*it).typeName].rotationY*(D3DX_PI/180.0));
  1520.                                 D3DXMatrixRotationZ(&mRotZ,g_EnemyTypes[(*it).typeName].rotationZ*(D3DX_PI/180.0));
  1521.                                 D3DXMatrixScaling(&mScale, g_EnemyTypes[(*it).typeName].scale, g_EnemyTypes[(*it).typeName].scale, g_EnemyTypes[(*it).typeName].scale);
  1522.                                 D3DXMatrixTranslation(&mTrans, g_EnemyTypes[(*it).typeName].translationX, g_EnemyTypes[(*it).typeName].translationY, getHeightAtPoint(g_EnemyTypes[(*it).typeName].translationX,g_EnemyTypes[(*it).typeName].translationY) + 10);
  1523.                                 D3DXVECTOR3 d = (*it).vel;
  1524.                                 D3DXVec3Normalize(&d,&d);      
  1525.                                 D3DXMATRIX mAnim;
  1526.                                 mAnim = D3DXMATRIX (d.x,d.y,d.z,0,
  1527.                                                 0,1,0,0,
  1528.                                                 -d.z,d.y,d.x,0,
  1529.                                                 (*it).pos.x,(*it).pos.y,(*it).pos.z,1);
  1530.                                 D3DXMATRIX worldView = mScale * mRotX * mRotY * mRotZ * mTrans * mAnim * (*g_Camera.GetViewMatrix()) ;
  1531.                                 worldViewProj = worldView * (*g_Camera.GetProjMatrix());
  1532.  
  1533.                                 D3DXMATRIX worldViewNormals;
  1534.                                 D3DXMatrixInverse(&worldViewNormals,NULL,&worldViewProj);
  1535.                                 D3DXMatrixTranspose(&worldViewNormals,&worldViewNormals);
  1536.      
  1537.                                
  1538.  
  1539.                                 g_WorldViewEV ->SetMatrix(worldView);
  1540.                                 g_WorldViewNormalsEV ->SetMatrix(worldViewNormals);
  1541.                                 g_WorldViewProjectionEV ->SetMatrix(worldViewProj);
  1542.      
  1543.                                 D3DXMATRIX viewTransformation;
  1544.                                 D3DXMatrixInverse(&viewTransformation, NULL, view);
  1545.                                 D3DXMatrixTranspose(&viewTransformation,&viewTransformation);
  1546.  
  1547.                                 D3DXVECTOR4 lightDirView;
  1548.                                 D3DXVec4Transform(&lightDirView, &g_LightDir, &viewTransformation);
  1549.                                 D3DXVec3Normalize((D3DXVECTOR3*)&lightDirView, (D3DXVECTOR3*)&lightDirView);
  1550.                                 g_LightDirViewEV->SetFloatVector((float*)&lightDirView);
  1551.      
  1552.                                 g_Pass1_Mesh ->Apply(0, pd3dImmediateContext);
  1553.                                 pd3dImmediateContext->DrawIndexed(g_Meshes[g_EnemyTypes[(*it).typeName].meshname]->GetIndexCount(), 0, 0);
  1554.            
  1555.            
  1556.                         }
  1557.  
  1558.  
  1559.                 g_SpriteRenderer->RenderSprites(pd3dDevice,SpriteVector,g_Camera);
  1560.                
  1561.      
  1562.         DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" );
  1563.         g_HUD.OnRender( fElapsedTime );
  1564.         g_SampleUI.OnRender( fElapsedTime );
  1565.         RenderText();
  1566.         DXUT_EndPerfEvent();
  1567.      
  1568.         static DWORD dwTimefirst = GetTickCount();
  1569.         if ( GetTickCount() - dwTimefirst > 5000 )
  1570.         {    
  1571.             OutputDebugString( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) );
  1572.             OutputDebugString( L"\n" );
  1573.             dwTimefirst = GetTickCount();
  1574.         }
  1575.     }