Megjegyzés
Az oldalhoz való hozzáféréshez engedély szükséges. Megpróbálhat bejelentkezni vagy módosítani a címtárat.
Az oldalhoz való hozzáféréshez engedély szükséges. Megpróbálhatja módosítani a címtárat.
Megjegyzés:
Ez a témakör a Egyszerű Univerzális Windows Platform (UWP) játék készítése DirectX-szel című oktatóanyag-sorozat része. A hivatkozás témaköre beállítja a sorozat kontextusát.
A renderelési keretrendszerben,, bemutattuk, hogyan vesszük fel a jelenetinformációt, és mutatjuk be a képernyőre. Most egy lépéssel visszalépünk, és megtanuljuk, hogyan készítsük elő az adatokat a rendereléshez.
Megjegyzés:
Ha még nem töltötte le a minta legújabb játékkódját, lépjen tovább a Direct3D minta játék-ra. Ez a minta az UWP-szolgáltatásminták nagy gyűjteményének része. A minta letöltésére vonatkozó utasításokért lásd a Windows-fejlesztéshez készült mintaalkalmazásokat.
Célkitűzés
Rövid összefoglalás a célkitűzésről. Ez azt ismerteti, hogyan állíthat be alapszintű renderelési keretrendszert az UWP DirectX-játékok grafikus kimenetének megjelenítéséhez. Lazán csoportosíthatjuk őket ebbe a három lépésbe.
- Kapcsolat létrehozása a grafikus felülettel
- Előkészítés: Hozza létre azokat az erőforrásokat, amelyekre szükségünk van a grafikus elemek rajzolásához
- A kép megjelenítése: A keret renderelése
Rendering Framework I: Bevezetés a renderelésbe elmagyarázta a grafikus megjelenítés módját, amely az 1. és a 3. lépésre terjed ki.
Ez a cikk bemutatja, hogyan állíthatja be a keretrendszer egyéb részeit, és hogyan készítheti elő a szükséges adatokat a renderelés előtt, ami a folyamat 2. lépése.
A renderelő tervezése
A renderelő feladata a játékvizualizációk létrehozásához használt összes D3D11 és D2D objektum létrehozása és karbantartása. A GameRenderer osztály a mintajáték renderelője, és úgy lett kialakítva, hogy megfeleljen a játék renderelési igényeinek.
Ezek a fogalmak segíthetnek a játék renderelőjének megtervezésében:
- Mivel a Direct3D 11 API-k COM API-kként vannak definiálva, ComPtr hivatkoznia kell az ezen API-k által meghatározott objektumokra. A rendszer automatikusan felszabadítja ezeket az objektumokat, amikor az alkalmazás leállásakor az utolsó hivatkozás kiesik a hatókörből. További információ: ComPtr. Ilyen objektumok például: állandó pufferek, árnyékolóobjektumok – csúcspont-árnyékoló, képpontárnyékolóés árnyékoló erőforrásobjektumok.
- Ebben az osztályban állandó pufferek vannak definiálva a rendereléshez szükséges különböző adatok tárolásához.
- Több különböző frekvenciájú állandó puffer használata a GPU-nak keretenként küldendő adatok mennyiségének csökkentéséhez. Ez a minta az állandókat különböző pufferekre választja el attól függően, hogy milyen gyakorisággal kell frissíteni őket. Ez a Direct3D-programozás ajánlott eljárása.
- Ebben a mintajátékban 4 állandó puffer van definiálva.
- m_constantBufferNeverChanges tartalmazza a világítási paramétereket. Egyszer van beállítva a FinalizeCreateGameDeviceResources metódusban, és soha többé nem változik.
- m_constantBufferChangeOnResize tartalmazza a vetítési mátrixot. A vetítési mátrix az ablak méretétől és méretarányától függ. Először be van állítva a CreateWindowSizeDependentResources metódusban, majd az erőforrások betöltése után frissül a FinalizeCreateGameDeviceResources metódusban. Ha 3D renderelés történik, képkockánként kétszer módosul.
- m_constantBufferChangesEveryFrame tartalmazza a nézetmátrixot. Ez a mátrix a kamera helyzetétől és megjelenési irányától (a vetítés normál irányától) függ, és a Render metódusban képkockánként egyszer változik. Erről már korábban szó volt a Rendering framework I: Intro to renderingalatt, a GameRenderer::Render metódusrésznél.
- m_constantBufferChangesEveryPrim tartalmazza az egyes primitívek modellmátrixát és anyagtulajdonságait. A modellmátrix a helyi koordináták csúcsait világkoordinátákká alakítja át. Ezek az állandók minden primitívre vonatkoznak, és minden rajzhíváshoz frissülnek. Ez meg lett tárgyalva korábban a Rendering framework I: Intro to renderingalatt, a Primitív renderelésrészben.
- Ebben az osztályban definiáljuk a primitívek textúráit tartalmazó shader-erőforrásobjektumokat is.
- Bizonyos textúrák előre definiálva vannak (A DDS egy fájlformátum, amely tömörített és tömörítetlen textúrák tárolására használható. A DDS textúrákat a világ falaihoz és padlójához, valamint a lőszergömbökhöz használják.)
- Ebben a mintajátékban a shader erőforrásobjektumok a következők: m_sphereTexture, m_cylinderTexture, m_ceilingTexture, m_floorTexture, m_wallsTexture.
- A shader objektumok ebben az osztályban vannak definiálva a primitívek és a textúrák kiszámításához.
- Ebben a mintajátékban az árnyékoló objektumok m_vertexShader, m_vertexShaderFlatés m_pixelShader, m_pixelShaderFlat.
- A csúcsárnyékoló feldolgozza a primitíveket és az alapvető világítást, a képpontárnyékoló (más néven töredékárnyékoló) pedig feldolgozza a textúrákat és a képpontonkénti effektusokat.
- Ezeknek az árnyékolóknak két verziója van (normál és lapos) a különböző primitívek megjelenítéséhez. A különböző verziók azért vannak, mert a lapos verziók sokkal egyszerűbbek, és nem végeznek egyedi kiemeléseket vagy képpontonkénti megvilágítási effektusokat. Ezeket használják a falakhoz, és gyorsabban renderelnek alacsonyabb teljesítményű eszközökön.
GameRenderer.h
Most tekintsük meg a mintajáték renderelőosztály-objektumában található kódot.
// Class handling the rendering of the game
class GameRenderer : public std::enable_shared_from_this<GameRenderer>
{
public:
GameRenderer(std::shared_ptr<DX::DeviceResources> const& deviceResources);
void CreateDeviceDependentResources();
void CreateWindowSizeDependentResources();
void ReleaseDeviceDependentResources();
void Render();
// --- end of async related methods section
winrt::Windows::Foundation::IAsyncAction CreateGameDeviceResourcesAsync(_In_ std::shared_ptr<Simple3DGame> game);
void FinalizeCreateGameDeviceResources();
winrt::Windows::Foundation::IAsyncAction LoadLevelResourcesAsync();
void FinalizeLoadLevelResources();
Simple3DGameDX::IGameUIControl* GameUIControl() { return &m_gameInfoOverlay; };
DirectX::XMFLOAT2 GameInfoOverlayUpperLeft()
{
return DirectX::XMFLOAT2(m_gameInfoOverlayRect.left, m_gameInfoOverlayRect.top);
};
DirectX::XMFLOAT2 GameInfoOverlayLowerRight()
{
return DirectX::XMFLOAT2(m_gameInfoOverlayRect.right, m_gameInfoOverlayRect.bottom);
};
bool GameInfoOverlayVisible() { return m_gameInfoOverlay.Visible(); }
// --- end of rendering overlay section
...
private:
// Cached pointer to device resources.
std::shared_ptr<DX::DeviceResources> m_deviceResources;
...
// Shader resource objects
winrt::com_ptr<ID3D11ShaderResourceView> m_sphereTexture;
winrt::com_ptr<ID3D11ShaderResourceView> m_cylinderTexture;
winrt::com_ptr<ID3D11ShaderResourceView> m_ceilingTexture;
winrt::com_ptr<ID3D11ShaderResourceView> m_floorTexture;
winrt::com_ptr<ID3D11ShaderResourceView> m_wallsTexture;
// Constant buffers
winrt::com_ptr<ID3D11Buffer> m_constantBufferNeverChanges;
winrt::com_ptr<ID3D11Buffer> m_constantBufferChangeOnResize;
winrt::com_ptr<ID3D11Buffer> m_constantBufferChangesEveryFrame;
winrt::com_ptr<ID3D11Buffer> m_constantBufferChangesEveryPrim;
// Texture sampler
winrt::com_ptr<ID3D11SamplerState> m_samplerLinear;
// Shader objects: Vertex shaders and pixel shaders
winrt::com_ptr<ID3D11VertexShader> m_vertexShader;
winrt::com_ptr<ID3D11VertexShader> m_vertexShaderFlat;
winrt::com_ptr<ID3D11PixelShader> m_pixelShader;
winrt::com_ptr<ID3D11PixelShader> m_pixelShaderFlat;
winrt::com_ptr<ID3D11InputLayout> m_vertexLayout;
};
Konstruktor
Ezután vizsgáljuk meg a mintajáték GameRenderer konstruktorát, és hasonlítsuk össze a DirectX 11 alkalmazássablonban megadott Sample3DSceneRenderer konstruktorával.
// Constructor method of the main rendering class object
GameRenderer::GameRenderer(std::shared_ptr<DX::DeviceResources> const& deviceResources) : ...
m_gameInfoOverlay(deviceResources),
m_gameHud(deviceResources, L"Windows platform samples", L"DirectX first-person game sample")
{
// m_gameInfoOverlay is a GameHud object to render text in the top left corner of the screen.
// m_gameHud is Game info rendered as an overlay on the top-right corner of the screen,
// for example hits, shots, and time.
CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
}
DirectX-grafikus erőforrások létrehozása és betöltése
A mintajátékban (és a Visual Studio DirectX 11 alkalmazásában (univerzális Windows) sablonban a játékerőforrások létrehozása és betöltése a GameRenderer konstruktor által meghívott két módszerrel történik:
CreateDeviceDependentResources metódus
A DirectX 11 alkalmazássablonban ezt a módszert használják a csúcspontok és a képpontárnyékoló aszinkron betöltéséhez, az árnyékoló és az állandó puffer létrehozásához, valamint a pozíció- és színinformációkat tartalmazó csúcspontokból álló háló létrehozásához.
A mintajátékban a jelenetobjektumok műveletei ehelyett a CreateGameDeviceResourcesAsync és FinalizeCreateGameDeviceResources metódusok között vannak felosztva.
Ebben a mintajátékban mi kerül ebbe a módszerbe?
- Példányosított változók (m_gameResourcesLoaded = hamis és m_levelResourcesLoaded = hamis), amelyek azt jelzik, hogy az erőforrások betöltve lettek-e, mielőtt továbblépnénk a renderelésre, mivel aszinkron módon töltjük be őket.
- Mivel a HUD és az átfedéses renderelés külön osztályobjektumokban található, hívja GameHud::CreateDeviceDependentResources és GameInfoOverlay::CreateDeviceDependentResources metódusokat itt.
Íme a GameRenderer::CreateDeviceDependentResourceskódja.
// This method is called in GameRenderer constructor when it's created in GameMain constructor.
void GameRenderer::CreateDeviceDependentResources()
{
// instantiate variables that indicate whether resources were loaded.
m_gameResourcesLoaded = false;
m_levelResourcesLoaded = false;
// game HUD and overlay are design as separate class objects.
m_gameHud.CreateDeviceDependentResources();
m_gameInfoOverlay.CreateDeviceDependentResources();
}
Az alábbiakban felsoroljuk az erőforrások létrehozásához és betöltéséhez használt módszereket.
- Készítsen eszközfüggő erőforrásokat
- CreateGameDeviceResourcesAsync (Hozzáadva)
- FinalizeCreateGameDeviceResources (Hozzáadva)
- AblakmérettőlFüggőErőforrásokLétrehozása
Mielőtt megismerkednénk az erőforrások létrehozásához és betöltéséhez használt más módszerekkel, először hozzuk létre a renderelőt, és nézzük meg, hogyan illeszkedik a játék hurokjába.
A renderelő létrehozása
A GameRenderer a GameMainkonstruktorában jön létre. Emellett meghívja a két másik metódust is, CreateGameDeviceResourcesAsync és FinalizeCreateGameDeviceResources, amelyek az erőforrások létrehozásához és betöltéséhez vannak hozzáadva.
GameMain::GameMain(std::shared_ptr<DX::DeviceResources> const& deviceResources) : ...
{
m_deviceResources->RegisterDeviceNotify(this);
// Creation of GameRenderer
m_renderer = std::make_shared<GameRenderer>(m_deviceResources);
...
ConstructInBackground();
}
winrt::fire_and_forget GameMain::ConstructInBackground()
{
...
// Asynchronously initialize the game class and load the renderer device resources.
// By doing all this asynchronously, the game gets to its main loop more quickly
// and in parallel all the necessary resources are loaded on other threads.
m_game->Initialize(m_controller, m_renderer);
co_await m_renderer->CreateGameDeviceResourcesAsync(m_game);
// The finalize code needs to run in the same thread context
// as the m_renderer object was created because the D3D device context
// can ONLY be accessed on a single thread.
// co_await of an IAsyncAction resumes in the same thread context.
m_renderer->FinalizeCreateGameDeviceResources();
InitializeGameState();
...
}
CreateGameDeviceResourcesAsync függvény
CreateGameDeviceResourcesAsync a GameMain konstruktor metódusából hívjuk meg a create_task hurokban, mivel a játék erőforrásait aszinkron módon töltjük be.
CreateDeviceResourcesAsync egy olyan módszer, amely külön aszinkron feladatkészletként fut a játék erőforrásainak betöltéséhez. Mivel várhatóan külön szálon fog futni, csak a Direct3D 11 eszközmetódusokhoz (
FinalizeCreateGameDeviceResources metódus a fő szálon fut, és hozzáféréssel rendelkezik a Direct3D 11 eszközkörnyezeti metódusokhoz.
Általában:
- Csak ID3D11Device metódusokat használjon CreateGameDeviceResourcesAsync, mert ezek szabadszálasak, ami azt jelenti, hogy bármilyen szálon futtathatók. Az is várható, hogy nem ugyanazon a szálon futnak, amelyen a GameRenderer létrehozták.
- Ne használjon függvényeket a ID3D11DeviceContext-ben itt, mert egyazon szálon kell futniuk, ugyanazon a szálon, mint a GameRenderer.
- Ezzel a módszerrel állandó puffereket hozhat létre.
- Ezzel a módszerrel betölthet textúrákat (például .dds fájlokat) és árnyékolóadatokat (például a .cso fájlokat) a árnyékolókba.
Ez a módszer a következőre használható:
- Hozza létre a 4 állandó puffert: m_constantBufferNeverChanges, m_constantBufferChangeOnResize, m_constantBufferChangesEveryFrame, m_constantBufferChangesEveryPrim
- sampler-state objektum létrehozása, amely mintavételezési információkat foglal magában egy anyagmintához
- Hozzon létre egy feladatcsoportot, amely tartalmazza a metódus által létrehozott összes aszinkron feladatot. Megvárja az összes aszinkron feladat befejezését, majd meghívja FinalizeCreateGameDeviceResources.
- Készítsen rakodót a Alap betöltőhasználatával. Adja hozzá a betöltő aszinkron betöltési műveleteit tevékenységekként a korábban létrehozott feladatcsoporthoz.
- Az olyan metódusok, mint BasicLoader::LoadShaderAsync és BasicLoader::LoadTextureAsync a következők betöltésére használhatók:
- összeállított árnyékolóobjektumok (VertexShader.cso, VertexShaderFlat.cso, PixelShader.cso és PixelShaderFlat.cso). További információ: Különböző árnyékoló fájlformátumok.
- játékspecifikus textúrák (Assets\seafloor.dds, metal_texture.dds, cellceiling.dds, cellfloor.dds, cellwall.dds).
IAsyncAction GameRenderer::CreateGameDeviceResourcesAsync(_In_ std::shared_ptr<Simple3DGame> game)
{
auto lifetime = shared_from_this();
// Create the device dependent game resources.
// Only the d3dDevice is used in this method. It is expected
// to not run on the same thread as the GameRenderer was created.
// Create methods on the d3dDevice are free-threaded and are safe while any methods
// in the d3dContext should only be used on a single thread and handled
// in the FinalizeCreateGameDeviceResources method.
m_game = game;
auto d3dDevice = m_deviceResources->GetD3DDevice();
// Define D3D11_BUFFER_DESC. See
// https://learn.microsoft.com/windows/win32/api/d3d11/ns-d3d11-d3d11_buffer_desc
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
// Create the constant buffers.
bd.Usage = D3D11_USAGE_DEFAULT;
...
// Create the constant buffers: m_constantBufferNeverChanges, m_constantBufferChangeOnResize,
// m_constantBufferChangesEveryFrame, m_constantBufferChangesEveryPrim
// CreateBuffer is used to create one of these buffers: vertex buffer, index buffer, or
// shader-constant buffer. For CreateBuffer API ref info, see
// https://learn.microsoft.com/windows/win32/api/d3d11/nf-d3d11-id3d11device-createbuffer.
winrt::check_hresult(
d3dDevice->CreateBuffer(&bd, nullptr, m_constantBufferNeverChanges.put())
);
...
// Define D3D11_SAMPLER_DESC. For API ref, see
// https://learn.microsoft.com/windows/win32/api/d3d11/ns-d3d11-d3d11_sampler_desc.
D3D11_SAMPLER_DESC sampDesc;
// ZeroMemory fills a block of memory with zeros. For API ref, see
// https://learn.microsoft.com/previous-versions/windows/desktop/legacy/aa366920(v=vs.85).
ZeroMemory(&sampDesc, sizeof(sampDesc));
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
...
// Create a sampler-state object that encapsulates sampling information for a texture.
// The sampler-state interface holds a description for sampler state that you can bind to any
// shader stage of the pipeline for reference by texture sample operations.
winrt::check_hresult(
d3dDevice->CreateSamplerState(&sampDesc, m_samplerLinear.put())
);
// Start the async tasks to load the shaders and textures.
// Load compiled shader objects (VertextShader.cso, VertexShaderFlat.cso, PixelShader.cso, and PixelShaderFlat.cso).
// The BasicLoader class is used to convert and load common graphics resources, such as meshes, textures,
// and various shader objects into the constant buffers. For more info, see
// https://learn.microsoft.com/windows/uwp/gaming/complete-code-for-basicloader.
BasicLoader loader{ d3dDevice };
std::vector<IAsyncAction> tasks;
uint32_t numElements = ARRAYSIZE(PNTVertexLayout);
// Load shaders asynchronously with the shader and pixel data using the
// BasicLoader::LoadShaderAsync method. Push these method calls into a list of tasks.
tasks.push_back(loader.LoadShaderAsync(L"VertexShader.cso", PNTVertexLayout, numElements, m_vertexShader.put(), m_vertexLayout.put()));
tasks.push_back(loader.LoadShaderAsync(L"VertexShaderFlat.cso", nullptr, numElements, m_vertexShaderFlat.put(), nullptr));
tasks.push_back(loader.LoadShaderAsync(L"PixelShader.cso", m_pixelShader.put()));
tasks.push_back(loader.LoadShaderAsync(L"PixelShaderFlat.cso", m_pixelShaderFlat.put()));
// Make sure the previous versions if any of the textures are released.
m_sphereTexture = nullptr;
...
// Load Game specific textures (Assets\\seafloor.dds, metal_texture.dds, cellceiling.dds,
// cellfloor.dds, cellwall.dds).
// Push these method calls also into a list of tasks.
tasks.push_back(loader.LoadTextureAsync(L"Assets\\seafloor.dds", nullptr, m_sphereTexture.put()));
...
// Simulate loading additional resources by introducing a delay.
tasks.push_back([]() -> IAsyncAction { co_await winrt::resume_after(GameConstants::InitialLoadingDelay); }());
// Returns when all the async tasks for loading the shader and texture assets have completed.
for (auto&& task : tasks)
{
co_await task;
}
}
FinalizeCreateGameDeviceResources metódus
FinalizeCreateGameDeviceResources metódus a CreateGameDeviceResourcesAsync metódusban található összes terhelési erőforrás-tevékenység befejezése után lesz meghívva.
- A constantBufferNeverChanges inicializálása a fény pozícióival és színeivel. Betölti a kezdeti adatokat az állandó pufferekbe egy eszközkörnyezeti metódushívással ID3D11DeviceContext::UpdateSubresource.
- Mivel az aszinkron módon betöltött erőforrások betöltése befejeződött, ideje társítani őket a megfelelő játékobjektumokkal.
- Minden játékobjektumhoz hozza létre a hálót és az anyagot a betöltött textúrák használatával. Ezután társítsa a hálót és az anyagot a játékobjektumhoz.
- A cél játékobjektum textúrája, amely koncentrikus színes gyűrűkből áll, és amelynek a tetején egy numerikus érték található, nem töltődik be egy textúra fájlból. Ehelyett eljárásszerűen generálják a TargetTexture.cppkódjának segítségével. A TargetTexture osztály létrehozza a szükséges erőforrásokat, hogy inicializáláskor a textúra egy képernyőn kívüli erőforrásba legyen rajzolva. Az eredményként kapott textúra ezután a megfelelő céljáték-objektumokhoz lesz társítva.
FinalizeCreateGameDeviceResources és CreateWindowSizeDependentResources hasonló kódrészleteket osztanak meg ezekhez:
- A SetProjParams használatával győződjön meg arról, hogy a kamera rendelkezik a megfelelő vetítési mátrixokkal. További információ: Kamera és koordináta-tér.
- A képernyő forgatásának kezelése a térhatású forgatási mátrix és a kamera vetítési mátrixának szorzata után. Ezután frissítse a ConstantBufferChangeOnResize állandó puffert az eredményül kapott vetítési mátrixmal.
- Állítsa be a m_gameResourcesLoadedlogikai globális változót, amely jelzi, hogy az erőforrások most már betöltve vannak a pufferekben, és készen állnak a következő lépésre. Ne feledje, hogy ezt a változót először FALSE-ként inicializáltuk a GameRendererkonstruktor metódusában a GameRenderer::CreateDeviceDependentResources metóduson keresztül.
- Ha a m_gameResourcesLoadedigaz, a jelenetobjektumok renderelése is megtörténhet. Ez a Rendering framework I: Intro to rendering cikkben lett tárgyalva, a GameRenderer::Render metódus alatt.
// This method is called from the GameMain constructor.
// Make sure that 2D rendering is occurring on the same thread as the main rendering.
void GameRenderer::FinalizeCreateGameDeviceResources()
{
// All asynchronously loaded resources have completed loading.
// Now associate all the resources with the appropriate game objects.
// This method is expected to run in the same thread as the GameRenderer
// was created. All work will happen behind the "Loading ..." screen after the
// main loop has been entered.
// Initialize the Constant buffer with the light positions
// These are handled here to ensure that the d3dContext is only
// used in one thread.
auto d3dDevice = m_deviceResources->GetD3DDevice();
ConstantBufferNeverChanges constantBufferNeverChanges;
constantBufferNeverChanges.lightPosition[0] = XMFLOAT4(3.5f, 2.5f, 5.5f, 1.0f);
...
constantBufferNeverChanges.lightColor = XMFLOAT4(0.25f, 0.25f, 0.25f, 1.0f);
// CPU copies data from memory (constantBufferNeverChanges) to a subresource
// created in non-mappable memory (m_constantBufferNeverChanges) which was created in the earlier
// CreateGameDeviceResourcesAsync method. For UpdateSubresource API ref info,
// go to: https://msdn.microsoft.com/library/windows/desktop/ff476486.aspx
// To learn more about what a subresource is, go to:
// https://msdn.microsoft.com/library/windows/desktop/ff476901.aspx
m_deviceResources->GetD3DDeviceContext()->UpdateSubresource(
m_constantBufferNeverChanges.get(),
0,
nullptr,
&constantBufferNeverChanges,
0,
0
);
// For the objects that function as targets, they have two unique generated textures.
// One version is used to show that they have never been hit and the other is
// used to show that they have been hit.
// TargetTexture is a helper class to procedurally generate textures for game
// targets. The class creates the necessary resources to draw the texture into
// an off screen resource at initialization time.
TargetTexture textureGenerator(
d3dDevice,
m_deviceResources->GetD2DFactory(),
m_deviceResources->GetDWriteFactory(),
m_deviceResources->GetD2DDeviceContext()
);
// CylinderMesh is a class derived from MeshObject and creates a ID3D11Buffer of
// vertices and indices to represent a canonical cylinder (capped at
// both ends) that is positioned at the origin with a radius of 1.0,
// a height of 1.0 and with its axis in the +Z direction.
// In the game sample, there are various types of mesh types:
// CylinderMesh (vertical rods), SphereMesh (balls that the player shoots),
// FaceMesh (target objects), and WorldMesh (Floors and ceilings that define the enclosed area)
auto cylinderMesh = std::make_shared<CylinderMesh>(d3dDevice, (uint16_t)26);
...
// The Material class maintains the properties that represent how an object will
// look when it is rendered. This includes the color of the object, the
// texture used to render the object, and the vertex and pixel shader that
// should be used for rendering.
auto cylinderMaterial = std::make_shared<Material>(
XMFLOAT4(0.8f, 0.8f, 0.8f, .5f),
XMFLOAT4(0.8f, 0.8f, 0.8f, .5f),
XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f),
15.0f,
m_cylinderTexture.get(),
m_vertexShader.get(),
m_pixelShader.get()
);
...
// Attach the textures to the appropriate game objects.
// We'll loop through all the objects that need to be rendered.
for (auto&& object : m_game->RenderObjects())
{
if (object->TargetId() == GameConstants::WorldFloorId)
{
// Assign a normal material for the floor object.
// This normal material uses the floor texture (cellfloor.dds) that was loaded asynchronously from
// the Assets folder using BasicLoader::LoadTextureAsync method in the earlier
// CreateGameDeviceResourcesAsync loop
object->NormalMaterial(
std::make_shared<Material>(
XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
150.0f,
m_floorTexture.get(),
m_vertexShaderFlat.get(),
m_pixelShaderFlat.get()
)
);
// Creates a mesh object called WorldFloorMesh and assign it to the floor object.
object->Mesh(std::make_shared<WorldFloorMesh>(d3dDevice));
}
...
else if (auto cylinder = dynamic_cast<Cylinder*>(object.get()))
{
cylinder->Mesh(cylinderMesh);
cylinder->NormalMaterial(cylinderMaterial);
}
else if (auto target = dynamic_cast<Face*>(object.get()))
{
const int bufferLength = 16;
wchar_t str[bufferLength];
int len = swprintf_s(str, bufferLength, L"%d", target->TargetId());
auto string{ winrt::hstring(str, len) };
winrt::com_ptr<ID3D11ShaderResourceView> texture;
textureGenerator.CreateTextureResourceView(string, texture.put());
target->NormalMaterial(
std::make_shared<Material>(
XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
5.0f,
texture.get(),
m_vertexShader.get(),
m_pixelShader.get()
)
);
texture = nullptr;
textureGenerator.CreateHitTextureResourceView(string, texture.put());
target->HitMaterial(
std::make_shared<Material>(
XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
5.0f,
texture.get(),
m_vertexShader.get(),
m_pixelShader.get()
)
);
target->Mesh(targetMesh);
}
...
}
// The SetProjParams method calculates the projection matrix based on input params and
// ensures that the camera has been initialized with the right projection
// matrix.
// The camera is not created at the time the first window resize event occurs.
auto renderTargetSize = m_deviceResources->GetRenderTargetSize();
m_game->GameCamera().SetProjParams(
XM_PI / 2,
renderTargetSize.Width / renderTargetSize.Height,
0.01f,
100.0f
);
// Make sure that the correct projection matrix is set in the ConstantBufferChangeOnResize buffer.
// Get the 3D rotation transform matrix. We are handling screen rotations directly to eliminate an unaligned
// fullscreen copy. So it is necessary to post multiply the 3D rotation matrix to the camera's projection matrix
// to get the projection matrix that we need.
auto orientation = m_deviceResources->GetOrientationTransform3D();
ConstantBufferChangeOnResize changesOnResize;
// The matrices are transposed due to the shader code expecting the matrices in the opposite
// row/column order from the DirectX math library.
// XMStoreFloat4x4 takes a matrix and writes the components out to sixteen single-precision floating-point values at the given address.
// The most significant component of the first row vector is written to the first four bytes of the address,
// followed by the second most significant component of the first row, and so on. The second row is then written out in a
// like manner to memory beginning at byte 16, followed by the third row to memory beginning at byte 32, and finally
// the fourth row to memory beginning at byte 48. For more API ref info, go to:
// https://msdn.microsoft.com/library/windows/desktop/microsoft.directx_sdk.storing.xmstorefloat4x4.aspx
XMStoreFloat4x4(
&changesOnResize.projection,
XMMatrixMultiply(
XMMatrixTranspose(m_game->GameCamera().Projection()),
XMMatrixTranspose(XMLoadFloat4x4(&orientation))
)
);
// UpdateSubresource method instructs CPU to copy data from memory (changesOnResize) to a subresource
// created in non-mappable memory (m_constantBufferChangeOnResize ) which was created in the earlier
// CreateGameDeviceResourcesAsync method.
m_deviceResources->GetD3DDeviceContext()->UpdateSubresource(
m_constantBufferChangeOnResize.get(),
0,
nullptr,
&changesOnResize,
0,
0
);
// Finally we set the m_gameResourcesLoaded as TRUE, so we can start rendering.
m_gameResourcesLoaded = true;
}
CreateWindowSizeDependentResource metódus
A CreateWindowSizeDependentResources metódusokat minden alkalommal meghívjuk, amikor az ablak mérete, tájolása, sztereo-kompatibilis renderelése vagy felbontása megváltozik. A mintajátékban frissíti a vetítési mátrixot ConstantBufferChangeOnResize.
Az ablakméret erőforrásai a következő módon frissülnek:
- Az alkalmazás-keretrendszer lekéri a lehetséges események egyikét, amelyek az ablak állapotának változását jelzik.
- A fő játék hurok ezután értesül az eseményről, és meghívja CreateWindowSizeDependentResources a főosztály (GameMain) példányán, amely ezután meghívja a CreateWindowSizeDependentResources implementációját a játék rendererében (GameRenderer) osztályban.
- Ennek a módszernek az elsődleges feladata annak biztosítása, hogy a vizualizációk ne legyenek összezavarva vagy érvénytelenek az ablaktulajdonságok változása miatt.
Ebben a mintajátékban számos metódushívás megegyezik a FinalizeCreateGameDeviceResources metódussal. A kódbemutatót az előző szakaszban találja.
A játék HUD és átfedés ablakának méretbeállításait a Felhasználói felület hozzáadásatartalmazza.
// Initializes view parameters when the window size changes.
void GameRenderer::CreateWindowSizeDependentResources()
{
// Game HUD and overlay window size rendering adjustments are done here
// but they'll be covered in the UI section instead.
m_gameHud.CreateWindowSizeDependentResources();
...
auto d3dContext = m_deviceResources->GetD3DDeviceContext();
// In Sample3DSceneRenderer::CreateWindowSizeDependentResources, we had:
// Size outputSize = m_deviceResources->GetOutputSize();
auto renderTargetSize = m_deviceResources->GetRenderTargetSize();
...
m_gameInfoOverlay.CreateWindowSizeDependentResources(m_gameInfoOverlaySize);
if (m_game != nullptr)
{
// Similar operations as the last section of FinalizeCreateGameDeviceResources method
m_game->GameCamera().SetProjParams(
XM_PI / 2, renderTargetSize.Width / renderTargetSize.Height,
0.01f,
100.0f
);
XMFLOAT4X4 orientation = m_deviceResources->GetOrientationTransform3D();
ConstantBufferChangeOnResize changesOnResize;
XMStoreFloat4x4(
&changesOnResize.projection,
XMMatrixMultiply(
XMMatrixTranspose(m_game->GameCamera().Projection()),
XMMatrixTranspose(XMLoadFloat4x4(&orientation))
)
);
d3dContext->UpdateSubresource(
m_constantBufferChangeOnResize.get(),
0,
nullptr,
&changesOnResize,
0,
0
);
}
}
Következő lépések
Ez a játék grafikus renderelési keretrendszerének implementálásának alapfolyamata. Minél nagyobb a játék, annál több absztrakciót kellene létrehoznia az objektumtípusok és animációs viselkedések hierarchiáinak kezeléséhez. Összetettebb módszereket kell implementálnia az eszközök, például a hálók és a textúrák betöltéséhez és kezeléséhez. Ezután tanuljuk meg, hogyan lehet hozzáadni egy felhasználói felületet.