Пятница, 19 Апреля 2024, 01:22

Приветствую Вас Гость

[ Новые сообщения · Игроделы · Правила · Поиск ]
  • Страница 1 из 1
  • 1
Форум игроделов » Программирование » C/C++ » Не отображается юнит
Не отображается юнит
bond95Дата: Воскресенье, 20 Ноября 2011, 15:21 | Сообщение # 1
частый гость
Сейчас нет на сайте
Решил в целях обучения сделать простенькую стратегия но сразу же потерпел неудачу, юнит которого я хочу вывести почему-то не отображается хоть все вроде бы работает исправно, даже карту выводит. Вот исходник:
Code

#include <math.h>
#pragma warning( default : 4996 )
#include "main.h"
   
   
   
Player *pl;
//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------
LPDIRECT3D9             g_pD3D = NULL; // Used to create the D3DDevice
LPDIRECT3DDEVICE9       g_pd3dDevice = NULL; // Our rendering device
LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; // Buffer to hold vertices
LPDIRECT3DINDEXBUFFER9  vBi=NULL;
LPDIRECT3DTEXTURE9      texture[5];
int *map=NULL;
   
// A structure for our custom vertex type
VOID D3DUtil_InitMaterial( D3DMATERIAL9& mtrl, FLOAT r, FLOAT g, FLOAT b, FLOAT a );
   
   
   
//-----------------------------------------------------------------------------
// Name: InitD3D()
// Desc: Initializes Direct3D
//-----------------------------------------------------------------------------
HRESULT InitD3D( HWND hWnd )
{
     // Create the D3D object.
     if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
         return E_FAIL;
   
     // Set up the structure used to create the D3DDevice
     D3DPRESENT_PARAMETERS d3dpp;
     ZeroMemory( &d3dpp, sizeof( d3dpp ) );
     d3dpp.Windowed = TRUE;
     d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
     d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
         d3dpp.BackBufferHeight=480;
         d3dpp.BackBufferWidth=480;
   
     // Create the D3DDevice
     if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                    D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                    &d3dpp, &g_pd3dDevice ) ) )
     {
         return E_FAIL;
     }
   
     // Turn off culling, so we see the front and back of the triangle
             g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
   
     // Turn off D3D lighting, since we are providing our own vertex colors
     g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
         g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
   
     return S_OK;
}
   
   
   
   
//-----------------------------------------------------------------------------
// Name: InitGeometry()
// Desc: Creates the scene geometry
//-----------------------------------------------------------------------------
HRESULT InitGeometry()
{
     // Initialize three vertices for rendering a triangle
         unsigned short index[]={
                 0,1,2,2,1,3
         };
     // Create the vertex buffer.
     if( FAILED( g_pd3dDevice->CreateVertexBuffer( 4 * sizeof( CUSTOMVERTEX ),
                    0, D3DFVF_CUSTOMVERTEX,
                    D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )
     {
         return E_FAIL;
     }
     // Fill the vertex buffer.
     CUSTOMVERTEX* pVertices;
     if( FAILED( g_pVB->Lock( 0, sizeof( CUSTOMVERTEX)*4, ( void** )&pVertices, 0 ) ) )
         return E_FAIL;
         for(int i = 0; i < 4; i++)
       pVertices[i].color = 0xffffffff;
         pVertices[0].position   = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
         pVertices[0].tu                 = 0.0f;
         pVertices[0].tv                 = 1.0f;
   
   
         pVertices[1].position   = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
         pVertices[1].tu                 = 0.0f;
         pVertices[1].tv                 = 0.0f;
   
   
         pVertices[2].position   = D3DXVECTOR3( 1.0f, 0.0f, 0.0f );
         pVertices[2].tu                 = 1.0f;
         pVertices[2].tv                 = 1.0f;
   
   
         pVertices[3].position   = D3DXVECTOR3( 1.0f, 1.0f, 0.0f );
         pVertices[3].tu                 = 1.0f;
         pVertices[3].tv                 = 0.0f;
   
      
     g_pVB->Unlock();
         VOID* indeces;
     if( FAILED( g_pd3dDevice->CreateIndexBuffer(6 * sizeof(short ),
                    0, D3DFMT_INDEX16,
                    D3DPOOL_DEFAULT, &vBi, NULL ) ) )
     {
         return E_FAIL;
     }
     if( FAILED( vBi->Lock( 0, sizeof( index ), ( void** )&indeces, 0 ) ) )
         return E_FAIL;
     memcpy( indeces, index, sizeof( index ) );
     vBi->Unlock();
         map=new int[100];
         for(int i=0; i<50; i++)
                 map[i]=0;
         for(int i=50; i<60; i++)
                 map[i]=1;
         for(int i=60; i<100; i++)
                 map[i]=2;
         // Seed the randomized
         srand( timeGetTime() );
         for(int i = 0; i < 50; i++ ) {
                 // Place rock tile if random 0-10 = 5
                 if( rand()%10 == 5 )  
                         map[ i ] = 3;
         }
         // Seed the randomized
         srand( timeGetTime() );
         for(int i = 60; i < 100; i++ ) {
                 // Place rock tile if random 0-10 = 5
                 if( rand()%10 == 5 )  
                         map[ i ] = 4;
         }
         for(int i = 90; i < 100; i++ ) {
                 // Place rock tile if random 0-10 = 5
                         map[ i ] = 5;
         }
     if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, TEXT("grass00.bmp"),  
                   &texture[0] ) ) )
    {
       MessageBox( NULL, TEXT("Не удается загрузитьтекстуру"),  
                          TEXT("Текстура"),
          MB_OK );
       return E_FAIL;
    }
         if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, TEXT("grass_edging_bottom.bmp"),  
                   &texture[1] ) ) )
    {
       MessageBox( NULL, TEXT("Не удается загрузить BG.bmp"),  
          TEXT("Урок 4 - Наложение текстур, фильтрация"),
          MB_OK );
       return E_FAIL;
    }
         if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, TEXT("beach.bmp"),  
                   &texture[2] ) ) )
    {
       MessageBox( NULL, TEXT("Не удается загрузитьтекстуру"),  
                          TEXT("Текстура"),
          MB_OK );
       return E_FAIL;
    }
         if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, TEXT("grass_rocks.bmp"),  
                   &texture[3] ) ) )
    {
       MessageBox( NULL, TEXT("Не удается загрузитьтекстуру"),  
                          TEXT("Текстура"),
          MB_OK );
       return E_FAIL;
    }
         if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, TEXT("grass_splotch.bmp"),  
                   &texture[4] ) ) )
    {
       MessageBox( NULL, TEXT("Не удается загрузитьтекстуру"),  
                          TEXT("Текстура"),
          MB_OK );
       return E_FAIL;
    }
         if(FAILED(pl=new Player()))
                 return E_FAIL;
     return S_OK;
}
   
   
   
   
//-----------------------------------------------------------------------------
// Name: Cleanup()
// Desc: Releases all previously initialized objects
//-----------------------------------------------------------------------------
VOID Cleanup()
{
     if( g_pVB != NULL )
         g_pVB->Release();
         if( vBi != NULL )
         vBi->Release();
   
     if( g_pd3dDevice != NULL )
         g_pd3dDevice->Release();
   
     if( g_pD3D != NULL )
         g_pD3D->Release();
}
   
   
   
//-----------------------------------------------------------------------------
// Name: SetupMatrices()
// Desc: Sets up the world, view, and projection transform matrices.
//-----------------------------------------------------------------------------
VOID SetupMatrices()
{
         D3DXMATRIX      matproj,matview;
   
     // Set up the textures
     g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
     g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
     g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
     g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
     g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
   
     // Set miscellaneous render states
     g_pd3dDevice->SetRenderState( D3DRS_DITHERENABLE,   FALSE );
     g_pd3dDevice->SetRenderState( D3DRS_SPECULARENABLE, FALSE );
     g_pd3dDevice->SetRenderState( D3DRS_ZENABLE,        TRUE );
     g_pd3dDevice->SetRenderState( D3DRS_AMBIENT,        0x00888888 );
   
         // Setup the 3D View
         D3DXMatrixIdentity(&matview);
         g_pd3dDevice->SetTransform(D3DTS_VIEW, &matview);
   
         D3DXMatrixOrthoLH(&matproj, (float)480, (float)480, -1, 2);
         g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &matproj);
         g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
         g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
         g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
         g_pd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
   
     // Setup a material
     D3DMATERIAL9 mtrl;
     D3DUtil_InitMaterial( mtrl, 1.0f, 1.0f, 1.0f, 1.0f );
     g_pd3dDevice->SetMaterial( &mtrl );
}
   
   
   
//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Draws the scene
//-----------------------------------------------------------------------------
VOID Render()
{
     // Clear the backbuffer to a black color
     g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB( 0, 0, 255 ), 1.0f, 0 );
   
     // Begin the scene
     if( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
     {
                 SetupMatrices();
                 for(int iY = 0; iY <10; iY++ ) {
                         // Horizontal
                 for(int iX = 0; iX < 10; iX++ ) {
         // Setup the world, view, and projection matrices
                 D3DXMATRIX      matWorld;
                 D3DXMATRIX      matRotation;
                 D3DXMATRIX      matTranslation;
                 D3DXMATRIX      matScale;
                  
                 // Set default position,scale,rotation
                 D3DXMatrixIdentity( &matTranslation );
                 // Scale the tile
                 D3DXMatrixScaling( &matScale, 48.0f, 48.0f, 1.0f );
                 D3DXMatrixMultiply( &matTranslation, &matTranslation, &matScale );
                 // Rotate the tile
                 if(map[10*iY+iX]==5) {
                 g_pd3dDevice->SetTexture(0,texture[1]);
                 D3DXMatrixRotationZ( &matRotation, (3.14f));
                 }
                 else {
                         g_pd3dDevice->SetTexture(0,texture[map[10*iY+iX]]);
                         D3DXMatrixRotationZ( &matRotation, 0.0f );
                 }
                 D3DXMatrixMultiply( &matWorld, &matTranslation, &matRotation );
                 // Move the tile
                 matWorld._41 = -240.0f+(iX*48.0f)-0.5f; // X-Pos
                 matWorld._42 = 192.0f-(iY*48.0f)+0.5f;  // Y-Pos
                 if(map[10*iY+iX]==5) {
                         matWorld._42+=48.0f;
                     matWorld._41+=48.0f;
                 }
                 // Set matrix
                 g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
         // Render the vertex buffer contents
                 g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
         g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
                 g_pd3dDevice->SetIndices(vBi);
                 g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 4, 0, 2);
                 g_pd3dDevice->SetTexture( 0, NULL);
                 pl->ShowPlayer();
                 }
                 }
         // End the scene
         g_pd3dDevice->EndScene();
     }
   
     // Present the backbuffer contents to the display
     g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}
   
   
   
   
//-----------------------------------------------------------------------------
// Name: MsgProc()
// Desc: The window's message handler
//-----------------------------------------------------------------------------
LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
     switch( msg )
     {
         case WM_DESTROY:
             Cleanup();
             PostQuitMessage( 0 );
             return 0;
                 case WM_CHAR:
                         Cleanup();
                 PostQuitMessage (0);
                 return 0;
     }
   
     return DefWindowProc( hWnd, msg, wParam, lParam );
}
   
   
   
   
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
INT WINAPI wWinMain( HINSTANCE hInst, HINSTANCE, LPWSTR, INT )
{
     UNREFERENCED_PARAMETER( hInst );
   
     // Register the window class
     WNDCLASSEX wc =
     {
         sizeof( WNDCLASSEX ), CS_CLASSDC, MsgProc, 0L, 0L,
         GetModuleHandle( NULL ), NULL, NULL, NULL, NULL,
         L"D3D Tutorial", NULL
     };
     RegisterClassEx( &wc );
   
     // Create the application's window
     HWND hWnd = CreateWindow( L"D3D Tutorial", L"D3D Tutorial 03: Matrices",
                 WS_OVERLAPPEDWINDOW, 100, 100, 480, 480,
                    NULL, NULL, wc.hInstance, NULL );
   
     // Initialize Direct3D
     if( SUCCEEDED( InitD3D( hWnd ) ) )
     {
         // Create the scene geometry
         if( SUCCEEDED( InitGeometry() ) )
         {
             // Show the window
             ShowWindow( hWnd, SW_SHOWDEFAULT );
             UpdateWindow( hWnd );
   
             // Enter the message loop
             MSG msg;
             ZeroMemory( &msg, sizeof( msg ) );
             while( msg.message != WM_QUIT )
             {
                 if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
                 {
                     TranslateMessage( &msg );
                     DispatchMessage( &msg );
                 }
                 else
                     Render();
             }
         }
     }
   
     UnregisterClass( L"D3D Tutorial", wc.hInstance );
     return 0;
}
   
   
VOID D3DUtil_InitMaterial( D3DMATERIAL9& mtrl, FLOAT r, FLOAT g, FLOAT b, FLOAT a )
{
      ZeroMemory( &mtrl, sizeof(D3DMATERIAL9) );
      mtrl.Diffuse.r = mtrl.Ambient.r = r;
      mtrl.Diffuse.g = mtrl.Ambient.g = g;
      mtrl.Diffuse.b = mtrl.Ambient.b = b;
      mtrl.Diffuse.a = mtrl.Ambient.a = a;
}
Player::Player()  
{
         if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, TEXT("warior.bmp"),  
                    &ptexture ) ) )
            {
                   MessageBox( NULL, TEXT("Не удается загрузитьтекстуру"),  
                          TEXT("Текстура"),
                          MB_OK );
            }
         px=endx=300.0f;
         py=endy=300.0f;
          
}
void Player::ShowPlayer() {
         D3DXMATRIX matWorld;
         D3DXMATRIX matScale;
         D3DXMATRIX matTranslation;
         D3DXMATRIX      matRotation;
   
         D3DXMatrixIdentity(&matTranslation);
         D3DXMatrixTranslation( &matTranslation, px-0.5f, py-0.5f, 0.0f );
         // Set default position,scale,rotation
         // Rotate the tile
         D3DXMatrixScaling(&matWorld,48.0f,24.0f,1.0f);
         D3DXMatrixMultiply(&matTranslation,&matTranslation,&matScale);
         D3DXMatrixRotationZ( &matRotation, 0);
         D3DXMatrixMultiply( &matWorld, &matTranslation, &matRotation );
         g_pd3dDevice->SetTexture(0,ptexture);
         g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
     // Render the vertex buffer contents
         g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
     g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
         g_pd3dDevice->SetIndices(vBi);
         g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 4, 0, 2);
         g_pd3dDevice->SetTexture( 0, NULL);
}

Добавлено (20.11.2011, 15:21)
---------------------------------------------
main.h

Code

#include <d3dx9.h>
struct CUSTOMVERTEX
{
     D3DXVECTOR3 position;     // The untransformed, 3D position for the vertex
     DWORD color;        // The vertex color
         FLOAT tu,tv;
   
};
   
// Our custom FVF, which describes our custom vertex structure
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
   
class Player {
private:
         LPDIRECT3DTEXTURE9 ptexture[2];
         LPDIRECT3DVERTEXBUFFER9 points;
         LPDIRECT3DINDEXBUFFER9 pindex;
         float px;
         float py;
         float endx;
         float endy;
         CUSTOMVERTEX pvertex[4];
public:
         Player();
         void ShowPlayer();
         void SetPosition(int tx, int ty)
         {
         }
};


PesetsДата: Воскресенье, 20 Ноября 2011, 22:35 | Сообщение # 2
постоянный участник
Сейчас нет на сайте


Это ж сколько надо "раскуривать" этот код, чтобы понять, что тут вообще делается? По-моему, самому же приятнее, когда все разбито на классы, каждый максимум на 300 строчек кода. И баги находить легче.

В общем, "tl; dr") Советую нормально оформить код, чтоли...





Сообщение отредактировал Pesets - Воскресенье, 20 Ноября 2011, 22:35
ТехникДата: Понедельник, 21 Ноября 2011, 17:18 | Сообщение # 3
Глава X-ray Games
Сейчас нет на сайте
Согласен с мнением Pesets. Ибо если уж и писать игру на голом api, то лучше оформить все это в некое подобие движка. А здесь набор всего и вся.
Форум игроделов » Программирование » C/C++ » Не отображается юнит
  • Страница 1 из 1
  • 1
Поиск:

Все права сохранены. GcUp.ru © 2008-2024 Рейтинг