DirectX11 颜色立方体示例Demo

2023-11-09 14:30

本文主要是介绍DirectX11 颜色立方体示例Demo,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

颜色立方体示例Demo

1. 核心代码

我们已经讲解了足够多的内容,现在我们可以开始编写一个简单的颜色立方体演示程序了。这个例子基本上包含了我们前面讲到的所有内容。读者应该对照前面的几节,仔细研究这些代码,直到把每一行代码都弄懂为止。
核心代码(建议下载Demo在VS看会更方便,DX11龙书官网有项目源代码下载,请读者自行下载):

//***************************************************************************************
// BoxDemo.cpp by Frank Luna (C) 2011 All Rights Reserved.
//
// Demonstrates rendering a colored box.
//
// Controls:
//      Hold the left mouse button down and move the mouse to rotate.
//      Hold the right mouse button down to zoom in and out.
//
//***************************************************************************************#include "d3dApp.h"
#include "d3dx11Effect.h"
#include "MathHelper.h"struct Vertex
{XMFLOAT3 Pos;XMFLOAT4 Color;
};class BoxApp : public D3DApp
{
public:BoxApp(HINSTANCE hInstance);~BoxApp();bool Init();void OnResize();void UpdateScene(float dt);void DrawScene();void OnMouseDown(WPARAM btnState, int x, int y);void OnMouseUp(WPARAM btnState, int x, int y);void OnMouseMove(WPARAM btnState, int x, int y);private:void BuildGeometryBuffers();void BuildFX();void BuildVertexLayout();private:ID3D11Buffer* mBoxVB;ID3D11Buffer* mBoxIB;ID3DX11Effect* mFX;ID3DX11EffectTechnique* mTech;ID3DX11EffectMatrixVariable* mfxWorldViewProj;ID3D11InputLayout* mInputLayout;XMFLOAT4X4 mWorld;XMFLOAT4X4 mView;XMFLOAT4X4 mProj;float mTheta;float mPhi;float mRadius;POINT mLastMousePos;
};int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,PSTR cmdLine, int showCmd)
{// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endifBoxApp theApp(hInstance);if( !theApp.Init() )return 0;return theApp.Run();
}BoxApp::BoxApp(HINSTANCE hInstance)
: D3DApp(hInstance), mBoxVB(0), mBoxIB(0), mFX(0), mTech(0),mfxWorldViewProj(0), mInputLayout(0),mTheta(1.5f*MathHelper::Pi), mPhi(0.25f*MathHelper::Pi), mRadius(5.0f)
{mMainWndCaption = L"Box Demo";mLastMousePos.x = 0;mLastMousePos.y = 0;XMMATRIX I = XMMatrixIdentity();XMStoreFloat4x4(&mWorld, I);XMStoreFloat4x4(&mView, I);XMStoreFloat4x4(&mProj, I);
}BoxApp::~BoxApp()
{ReleaseCOM(mBoxVB);ReleaseCOM(mBoxIB);ReleaseCOM(mFX);ReleaseCOM(mInputLayout);
}bool BoxApp::Init()
{if(!D3DApp::Init())return false;BuildGeometryBuffers();BuildFX();BuildVertexLayout();return true;
}void BoxApp::OnResize()
{D3DApp::OnResize();// 当窗口大小改变时,需要更新横纵比,并重新计算投影矩阵XMMATRIX P = XMMatrixPerspectiveFovLH(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);XMStoreFloat4x4(&mProj, P);
}void BoxApp::UpdateScene(float dt)
{// Convert Spherical to Cartesian coordinates.float x = mRadius*sinf(mPhi)*cosf(mTheta);float z = mRadius*sinf(mPhi)*sinf(mTheta);float y = mRadius*cosf(mPhi);// 创建视矩阵XMVECTOR pos    = XMVectorSet(x, y, z, 1.0f);XMVECTOR target = XMVectorZero();XMVECTOR up     = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);XMMATRIX V = XMMatrixLookAtLH(pos, target, up);XMStoreFloat4x4(&mView, V);
}void BoxApp::DrawScene()
{md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::LightSteelBlue));md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0);md3dImmediateContext->IASetInputLayout(mInputLayout);md3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);UINT stride = sizeof(Vertex);UINT offset = 0;md3dImmediateContext->IASetVertexBuffers(0, 1, &mBoxVB, &stride, &offset);md3dImmediateContext->IASetIndexBuffer(mBoxIB, DXGI_FORMAT_R32_UINT, 0);// Set constantsXMMATRIX world = XMLoadFloat4x4(&mWorld);XMMATRIX view  = XMLoadFloat4x4(&mView);XMMATRIX proj  = XMLoadFloat4x4(&mProj);XMMATRIX worldViewProj = world*view*proj;mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&worldViewProj));D3DX11_TECHNIQUE_DESC techDesc;mTech->GetDesc( &techDesc );for(UINT p = 0; p < techDesc.Passes; ++p){mTech->GetPassByIndex(p)->Apply(0, md3dImmediateContext);// 立方体有36个索引md3dImmediateContext->DrawIndexed(36, 0, 0);}HR(mSwapChain->Present(0, 0));
}void BoxApp::OnMouseDown(WPARAM btnState, int x, int y)
{mLastMousePos.x = x;mLastMousePos.y = y;SetCapture(mhMainWnd);
}void BoxApp::OnMouseUp(WPARAM btnState, int x, int y)
{ReleaseCapture();
}void BoxApp::OnMouseMove(WPARAM btnState, int x, int y)
{if( (btnState & MK_LBUTTON) != 0 ){// Make each pixel correspond to a quarter of a degree.float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));// Update angles based on input to orbit camera around box.mTheta += dx;mPhi   += dy;// Restrict the angle mPhi.mPhi = MathHelper::Clamp(mPhi, 0.1f, MathHelper::Pi-0.1f);}else if( (btnState & MK_RBUTTON) != 0 ){// Make each pixel correspond to 0.005 unit in the scene.float dx = 0.005f*static_cast<float>(x - mLastMousePos.x);float dy = 0.005f*static_cast<float>(y - mLastMousePos.y);// Update the camera radius based on input.mRadius += dx - dy;// Restrict the radius.mRadius = MathHelper::Clamp(mRadius, 3.0f, 15.0f);}mLastMousePos.x = x;mLastMousePos.y = y;
}void BoxApp::BuildGeometryBuffers()
{// 创建顶点缓冲Vertex vertices[] ={{ XMFLOAT3(-1.0f, -1.0f, -1.0f), (const float*)&Colors::White   },{ XMFLOAT3(-1.0f, +1.0f, -1.0f), (const float*)&Colors::Black   },{ XMFLOAT3(+1.0f, +1.0f, -1.0f), (const float*)&Colors::Red     },{ XMFLOAT3(+1.0f, -1.0f, -1.0f), (const float*)&Colors::Green   },{ XMFLOAT3(-1.0f, -1.0f, +1.0f), (const float*)&Colors::Blue    },{ XMFLOAT3(-1.0f, +1.0f, +1.0f), (const float*)&Colors::Yellow  },{ XMFLOAT3(+1.0f, +1.0f, +1.0f), (const float*)&Colors::Cyan    },{ XMFLOAT3(+1.0f, -1.0f, +1.0f), (const float*)&Colors::Magenta }};D3D11_BUFFER_DESC vbd;vbd.Usage = D3D11_USAGE_IMMUTABLE;vbd.ByteWidth = sizeof(Vertex) * 8;vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;vbd.CPUAccessFlags = 0;vbd.MiscFlags = 0;vbd.StructureByteStride = 0;D3D11_SUBRESOURCE_DATA vinitData;vinitData.pSysMem = vertices;HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mBoxVB));// 创建索引缓冲UINT indices[] = {// 前表面0, 1, 2,0, 2, 3,// 后表面4, 6, 5,4, 7, 6,// 左表面4, 5, 1,4, 1, 0,// 右表面3, 2, 6,3, 6, 7,// 上表面1, 5, 6,1, 6, 2,// 下表面4, 0, 3,4, 3, 7};D3D11_BUFFER_DESC ibd;ibd.Usage = D3D11_USAGE_IMMUTABLE;ibd.ByteWidth = sizeof(UINT) * 36;ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;ibd.CPUAccessFlags = 0;ibd.MiscFlags = 0;ibd.StructureByteStride = 0;D3D11_SUBRESOURCE_DATA iinitData;iinitData.pSysMem = indices;HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mBoxIB));
}void BoxApp::BuildFX()
{DWORD shaderFlags = 0;#if defined( DEBUG ) || defined( _DEBUG )shaderFlags |= D3D10_SHADER_DEBUG;shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;#endifID3D10Blob* compiledShader = 0;ID3D10Blob* compilationMsgs = 0;HRESULT hr = D3DX11CompileFromFile(L"FX/color.fx", 0, 0, 0, "fx_5_0", shaderFlags,0, 0, &compiledShader, &compilationMsgs, 0);// compilationMsgs中包含错误或警告信息if( compilationMsgs != 0 ){MessageBoxA(0, (char*)compilationMsgs->GetBufferPointer(), 0, 0);ReleaseCOM(compilationMsgs);}// 就算没有compilationMsgs,也需要确保没有其他错误if(FAILED(hr)){DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX11CompileFromFile", true);}HR(D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(),0, md3dDevice, &mFX));// 编译完成释放资源ReleaseCOM(compiledShader);mTech    = mFX->GetTechniqueByName("ColorTech");mfxWorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix();
}void BoxApp::BuildVertexLayout()
{// 顶点输入布局描述D3D11_INPUT_ELEMENT_DESC vertexDesc[] ={{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},{"COLOR",    0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}};// 创建顶点输入布局D3DX11_PASS_DESC passDesc;mTech->GetPassByIndex(0)->GetDesc(&passDesc);HR(md3dDevice->CreateInputLayout(vertexDesc, 2, passDesc.pIAInputSignature,passDesc.IAInputSignatureSize, &mInputLayout));
}

这里写图片描述

这里写图片描述

这篇关于DirectX11 颜色立方体示例Demo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/376673

相关文章

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

用js控制视频播放进度基本示例代码

《用js控制视频播放进度基本示例代码》写前端的时候,很多的时候是需要支持要网页视频播放的功能,下面这篇文章主要给大家介绍了关于用js控制视频播放进度的相关资料,文中通过代码介绍的非常详细,需要的朋友可... 目录前言html部分:JavaScript部分:注意:总结前言在javascript中控制视频播放

Java中StopWatch的使用示例详解

《Java中StopWatch的使用示例详解》stopWatch是org.springframework.util包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比,这篇文章主要介绍... 目录stopWatch 是org.springframework.util 包下的一个工具类,使用它

Springboot处理跨域的实现方式(附Demo)

《Springboot处理跨域的实现方式(附Demo)》:本文主要介绍Springboot处理跨域的实现方式(附Demo),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录Springboot处理跨域的方式1. 基本知识2. @CrossOrigin3. 全局跨域设置4.

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

springboot security快速使用示例详解

《springbootsecurity快速使用示例详解》:本文主要介绍springbootsecurity快速使用示例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录创www.chinasem.cn建spring boot项目生成脚手架配置依赖接口示例代码项目结构启用s

golang 日志log与logrus示例详解

《golang日志log与logrus示例详解》log是Go语言标准库中一个简单的日志库,本文给大家介绍golang日志log与logrus示例详解,感兴趣的朋友一起看看吧... 目录一、Go 标准库 log 详解1. 功能特点2. 常用函数3. 示例代码4. 优势和局限二、第三方库 logrus 详解1.

SpringBoot实现MD5加盐算法的示例代码

《SpringBoot实现MD5加盐算法的示例代码》加盐算法是一种用于增强密码安全性的技术,本文主要介绍了SpringBoot实现MD5加盐算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习... 目录一、什么是加盐算法二、如何实现加盐算法2.1 加盐算法代码实现2.2 注册页面中进行密码加盐2.

python+opencv处理颜色之将目标颜色转换实例代码

《python+opencv处理颜色之将目标颜色转换实例代码》OpenCV是一个的跨平台计算机视觉库,可以运行在Linux、Windows和MacOS操作系统上,:本文主要介绍python+ope... 目录下面是代码+ 效果 + 解释转HSV: 关于颜色总是要转HSV的掩膜再标注总结 目标:将红色的部分滤

Redis 中的热点键和数据倾斜示例详解

《Redis中的热点键和数据倾斜示例详解》热点键是指在Redis中被频繁访问的特定键,这些键由于其高访问频率,可能导致Redis服务器的性能问题,尤其是在高并发场景下,本文给大家介绍Redis中的热... 目录Redis 中的热点键和数据倾斜热点键(Hot Key)定义特点应对策略示例数据倾斜(Data S