Microsoft PowerPoint - GameProgramming15-MeshII

Similar documents
Microsoft PowerPoint - Week04_DirectX9 프로그래밍의 기초2.pptx

Microsoft PowerPoint - GameProgramming23-PixelShader.ppt

Microsoft PowerPoint - Class10_LOD와자료구조.pptx

Microsoft Word - game08-midterm.doc

Microsoft PowerPoint - Week03_DirectX9 프로그래밍의 기초.pptx

Microsoft PowerPoint - 10terrain.ppt

Microsoft PowerPoint - animation

(Microsoft PowerPoint - \301\24613\260\255 - oFusion \276\300 \261\270\274\272)

Microsoft PowerPoint - ch07 - 포인터 pm0415

슬라이드 1

11장 포인터

PowerPoint 프레젠테이션

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

Microsoft PowerPoint - lecture15-ch6.ppt

PowerPoint 프레젠테이션

12 강. 문자출력 Direct3D 에서는문자를출력하기위해서 LPD3DXFONT 객체를사용한다 LPD3DXFONT 객체생성과초기화 LPD3DXFONT 객체를생성하고초기화하는함수로 D3DXCreateFont() 가있다. HRESULT D3DXCreateFont

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi

04_오픈지엘API.key

<4D F736F F F696E74202D20C1A63034B0AD202D20C7C1B7B9C0D3B8AEBDBAB3CABFCD20B9ABB9F6C6DBC0D4B7C2>

11장 포인터

adfasdfasfdasfasfadf

chap 5: Trees

이번장에서학습할내용 동적메모리란? malloc() 와 calloc() 연결리스트 파일을이용하면보다많은데이터를유용하고지속적으로사용및관리할수있습니다. 2

K&R2 Reference Manual 번역본

슬라이드 1

Microsoft PowerPoint - lecture16-ch6

KNK_C_05_Pointers_Arrays_structures_summary_v02

<443A5C4C C4B48555C B3E25C32C7D0B1E25CBCB3B0E8C7C1B7CEC1A7C6AE425CBED0C3E0C7C1B7CEB1D7B7A55C D616E2E637070>

목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2

프로그램을 학교 등지에서 조금이라도 배운 사람들을 위한 프로그래밍 노트 입니다. 저 역시 그 사람들 중 하나 입니다. 중고등학교 시절 학교 도서관, 새로 생긴 시립 도서관 등을 다니며 책을 보 고 정리하며 어느정도 독학으르 공부하긴 했지만, 자주 안하다 보면 금방 잊어

제 11 장포인터 유준범 (JUNBEOM YOO) Ver 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다.

UI TASK & KEY EVENT

Let G = (V, E) be a connected, undirected graph with a real-valued weight function w defined on E. Let A be a set of E, possibly empty, that is includ

Microsoft PowerPoint - ch09 - 연결형리스트, Stack, Queue와 응용 pm0100

Chapter #01 Subject

Microsoft PowerPoint - chap13-입출력라이브러리.pptx

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

example code are examined in this stage The low pressure pressurizer reactor trip module of the Plant Protection System was programmed as subject for

Microsoft PowerPoint - 05geometry.ppt

Microsoft PowerPoint - chap-11.pptx

C# Programming Guide - Types

BMP 파일 처리

JAVA PROGRAMMING 실습 08.다형성

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx

PowerPoint Presentation

API 매뉴얼

슬라이드 1

No Slide Title

Microsoft PowerPoint - 제11장 포인터

설계란 무엇인가?

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

언리얼엔진4_내지_ indd

Microsoft PowerPoint - C++ 5 .pptx

Microsoft PowerPoint - NV40_Korea_KR_2.ppt

Microsoft PowerPoint - chap11-포인터의활용.pptx

JVM 메모리구조

Microsoft PowerPoint - Chapter_04.pptx

API 매뉴얼

A Hierarchical Approach to Interactive Motion Editing for Human-like Figures

<4D F736F F F696E74202D B30395FBAEDB7BBB5F95FBDBAC5D9BDC7B9F6C6DB5FB1D7B8B2C0DA2E >

금오공대 컴퓨터공학전공 강의자료

Microsoft PowerPoint - 04-Model Class.pptx

untitled

Microsoft PowerPoint - 제11장 포인터(강의)

untitled

03_queue

Microsoft PowerPoint - GameProgramming16-Camera.ppt

슬라이드 1

쉽게 풀어쓴 C 프로그래밍

Microsoft PowerPoint - IP11.pptx

A Dynamic Grid Services Deployment Mechanism for On-Demand Resource Provisioning

3D MAX + WEEK 9 Hansung Univ. Interior Design

1. auto_ptr 다음프로그램의문제점은무엇인가? void func(void) int *p = new int; cout << " 양수입력 : "; cin >> *p; if (*p <= 0) cout << " 양수를입력해야합니다 " << endl; return; 동적할

PowerPoint Presentation

Microsoft PowerPoint - ch10 - 이진트리, AVL 트리, 트리 응용 pm0600

예제 1.1 ( 관계연산자 ) >> A=1:9, B=9-A A = B = >> tf = A>4 % 4 보다큰 A 의원소들을찾을경우 tf = >> tf = (A==B) % A

PowerPoint 프레젠테이션

Lab 3. 실습문제 (Single linked list)_해답.hwp

강의10

untitled

MPLAB C18 C

Microsoft PowerPoint - [2009] 02.pptx

JAVA PROGRAMMING 실습 02. 표준 입출력

<4D F736F F F696E74202D20C1A63037B0AD202D20B1A4BFF8B0FA20B1D7B8B2C0DA>

슬라이드 1

Microsoft PowerPoint - 알고리즘_5주차_1차시.pptx

Lab 4. 실습문제 (Circular singly linked list)_해답.hwp

K_R9000PRO_101.pdf

디지털영상처리3

Microsoft PowerPoint - 04-UDP Programming.ppt

untitled

서피스셰이더프로그램 셰이더개발을쉽게! Thursday, April 12, 12

Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

Chapter_02-3_NativeApp

쉽게 풀어쓴 C 프로그래밍

Dialog Box 실행파일을 Web에 포함시키는 방법

Chap 6: Graphs

10주차.key

PowerPoint 프레젠테이션

Transcription:

Mesh Part II Mesh Part II ID3DXBuffer XFiles 데이터를 ID3DXMesh 객체로읽어들이는방법 프로그레시브메쉬 (Progressive mesh) 를이용하여얻을수있는이점에대한이해와메쉬인터페이스 ID3DXPMesh 이용방법 305890 2007년봄학기 5/9/2007 박경신 경계볼륨 (Bounding volume) 의정의와용도에대한학습과 D3DX 함수를이용하여만드는방법 예제 ID3DXBuffer ID3DXBuffer ID3DXBuffer D3DX 가연속적인메모리블록에데이터를저장하기위해이용하는범용데이터구조체 LPVOID GetBufferPointer(VOID); // 데이터시작포인터반환 DWORD GetBufferSize(VOID); // 버퍼크기를 byte 단위로반환 데이터타입은프로그래머가관리해야함 DWORD* info = (DWORD*)adjacencyInfo->GetBufferPointer( ); D3DXMATERIAL *mtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer( ); ID3DXBuffer 생성하기 HRESULT D3DXCreateBuffer ( DWORD NumBytes, // 버퍼크기 (in bytes) LPD3DXBUFFER *ppbuffer); // ID3DXBuffer 예제 : // 4 개의정수를보관할수있는 buffer 의생성 ID3DXBuffer* buffer = 0; D3DXCreateBuffer( 4*sizeof(int), &buffer ); 메모리누출을막기위해, 반드시이용후에는객체를 release시킴 adjacencyinfo->release( ); mtrlbuffer->release( );

XFiles 3D 모델러를사용하여복잡한물체를생성 3DS Max (www.discreet.com) LightWave3D (www.newtek.com) Maya (www.aliaswavefront.com) Multigen Creator (www.multigen.com) Soft Image (www.softimage.com) 생성된메쉬데이터 ( 기하정보, 재질, 애니메이션등과같은데이터 ) 를 XFile 포맷으로변환가능 3D 모델 Exporter Okino Polytrans (www.okino.com) Converting 3DS MAX to X File Plug-in tool 을사용하는방법 DirectX Extensions for Discreet 3ds max Version7 MSDN Home -> MSDN Library -> Win32 and COM development -> Graphics and Multimedia -> DirectX -> DirectX 9.0 SDK Update (April 2005) C++ -> The DirectX Software Development Kit -> DirectX Tools -> DirectX Content Tools -> DirectX Extensions for DCC applications Version4.5 MSDN Home -> MSDN Library Archive -> Graphics and Multimedia -> DirectX -> Tools -> X File Exporter for Discreet s 3ds max 3D Max object 를.x 파일로 export 해주는 plug-in tool - Pandasoft http://www.andytather.co.uk/panda/directxmax_downloads.aspx Converting 3DS MAX to X File Converter 를사용하는방법 See conv3ds.exe http://msdn.microsoft.com/archive/default.asp?url=/archive/enus/directx9_c/directx/graphics/programmingguide/advancedtopi cs/xfiles/convertingexporting/conv3ds/specifyingoptionalargumen ts.asp Run conv3ds.exe Command prompt 상태에서 conv3ds File.3ds 하면.x file 생성 Version4.5 MSDN Home -> MSDN Library Archive -> DirectX Graphics -> Tools -> X File Exporter for Discreet s 3ds max Load Xfiles ID3DXMesh 객체를생성하고 XFile 의기하정보데이터를읽어들이는함수 : D3DXLoadMeshFromX HRESULT D3DXLoadMeshFromX ( LPCSTR pfilename, DWORD Options, LPDIRECT3DDEVICE9 pdevice, LPD3DXBUFFER* ppadjacency, LPD3DXBUFFER* ppmaterials, LPD3DXBUFFER* ppeffectinstances, PDWORD pnummaterials, LPD3DXMESH* ppmesh); pfilename 읽어들이고자하는 Xfile 의파일명 Options 생성플래그 (D3DXMESH 열거형 ) ppadjacency, ppmaterials, ppeffectinstaces, pnummaterials, ppmesh 리턴받을인자들

Load XFiles 예제 : HRESULT hr = 0; ID3DXBuffer* adjbuffer = 0; ID3DXBuffer* mtrlbuffer = 0; DWORD nummtrls = 0; hr = D3DXLoadMeshFromX( "bigship1.x", D3DXMESH_MANAGED, Device, &adjbuffer, &mtrlbuffer, 0, &nummtrls, // # of D3DXMATERIAL structures // in mtrlbuffer &Mesh ); // loaded ID3DXMesh XFile Materials Xfile 에저장된재질정보의구조는 D3DXMATERIAL typedef struct D3DXMATERIAL { D3DMATERIAL9 MatD3D; LPSTR ptexturefilename; D3DXMATERIAL, *LPD3DXMATERIAL; XFile 은텍스처데이터를직접포함하지않음. 파일명만보관함. 리턴된 D3DMATERIAL 배열의 i번째항목은 i번째서브셋과대응되도록 XFile 정보를읽어들임. Example: XFile ID3DXMesh* Mesh = 0; std::vector<d3dxmaterial> Mtrls(0); std::vector<idirect3dtexture9*> Textures(0); bool Setup() { // Load XFile data ID3DXBuffer* adjbuffer = 0; ID3DXBuffer* mtrlbuffer = 0; DWORD nummtrls = 0; HRESULT hr = D3DXLoadMeshFromX( bigship1.x, D3DXMESH_MANAGED, Device, &adjbuffer, &mtrlbuffer, 0, &nummtrls, &Mesh); if (FAILE(hr)) { ::MessageBox(0, D3DXLoadMeshFromX() FAILED, 0, 0); return false; if (mtrlbuffer! = 0 && nummtrls!= 0) { // extract materials, and load textures D3DXMATERIAL* mtrls = (D3DXMATERIAL*) mtrlbuffer->getbufferpointer(); for (DWORD i = 0; I < nummtrls; i++) { // loading 시 MatD3d 에 ambient 값을가지지않으므로지금지정해줌 mtrls[i].matd3d.ambient = mtrls[i].matd3d.diffuse; Mtrls.push_back(mtrls[i].MatD3D); if ( mtrls[i].ptexturefilename!= 0) { // if it has an associative texture IDirect3DTexture9* tex = 0; D3DXCreateTextureFromFile(Device, mtrls[i].ptexturefilename, &tex); Textures.push_back( tex ); else { Textures.push_back(0); // if it has no texture d3d::release<id3dxbuffer*> (mtrlbuffer); Example: XFile // optimize the mesh to generate an attribute table hr = Mesh->OptimizeInplace(D3DXMESHOPT_ATTRSORT D3DXMESHOPT_COMPACT D3DXMESHOPT_VERTEXCACHE, (DWORD*) adjbuffer->getbufferpointer(), 0, 0, 0); d3d::release<id3dxbuffer*>(adjbuffer); if (FAILED(hr)) { ::MessageBox(0, OptimizeInplace() FAILED, 0, 0); return false; // textures // lights // camera // projection matrix void Cleanup() { d3d::release<id3dmesh*>(mesh); for (i=0; i<(int)textures.size(); i++) d3d::release<idirect3dtexture9*>(textures[i]);

Example: XFile Example: XFile bool Display(float timedelta) { if (Device) { D3DXMATRIX xrot, yrot, World; static float y = 0.0f; D3DXMatrixRotationX(&xRot, D3DX_PI * 0.2f); D3DXMatrixRotationY(&yRot, y); y += timedelta; if (y >= 6.28f) y = 0.0f; World = xrot * yrot; Device->SetTransform(D3DTS_WORLD, &World); Device->Clear(0, 0, D3DCLEAR_TARGET D3DCLEAR_ZBUFFER, 0x00000000, 1.0, 0); Device->BeginScene(); for (int i=0; i < (int) Mtrls.size(); i++) { Device->SetMaterial( &Mtrls[i] ); Device->SetTexture(0, Textures[i]); Mesh->DrawSubset(i); Device->EndScene(); Device->Present(0, 0, 0, 0); Creating Vertex Normals ID3DXBaseMesh 의버텍스법선계산함수 XFile 에버텍스법선데이터가없다면, 조명을위해직접 vertex normal 을계산해야한다. 계산원리 이웃하는면법선벡터의평균을이용 인접정보 중복된버텍스는무시하기위해사용 HRESULT D3DXComputeNormals ( LPD3DXBASEMESH pmesh, CONST DWORD *padjacency); pmesh - 버텍스포맷은반드시 D3DFVF_NORMAL 플래그를포함해야한다. D3DXComputeNormals 함수이용전에버텍스포맷지정 padjacency 각면마다3개의 DWORD를가지는배열. 안쓰면 NULL로지정한다. Creating Vertex Normals D3DXComputeNormals 사용법 XFile 이 vertex normal 를가지고있지않다면해당하는 ID3DXMesh 객체의 FVF 도 D3DFVF_NORMAL flag 가없음. if(!(pmesh->getfvf() & D3DFVF_NORMAL) ) { ID3DXMesh* ptempmesh = 0; pmesh->clonemeshfvf ( D3DXMESH_MANAGED, pmesh->getfvf() D3DFVF_NORMAL, Device, &ptempmesh ); D3DXComputeNormals( ptempmesh, 0 ); pmesh->release(); pmesh = ptempmesh;

Progressive Mesh ID3DXPMesh 인터페이스에의해표현 경계상실변환 (ECT: edge collapse transformation) sequence 를적용하여메쉬를단순화할수있도록해준다 한 ECT 는한 vertex 와 1~2 개의 face 를제거함 각 ECT 는 (vertex split 를통해 ) reversible 함 Progressive Mesh ECT vs. 버텍스분할 (vertex split) v l v u v r ecollapse(v u,v t,v s ) v l v r v t vsplit(vs,v v s l,v r,v u,v t ) ECT 를이용한단순화과정을되돌려원래상태의메쉬로돌아갈수있음 높은해상도중간해상도낮은해상도 Progressive Mesh 이용방법 : 카메라와의거리에따라메쉬의 LOD (Level- Of-Details) 를조정할수있음 작고먼메쉬는크고가까운메쉬만큼많은삼각형이필요치않음 카메라와의거리가감소하면메쉬의세부 (detail) 를높이고거리가증가하면세부를감소시킴 참조논문 Progressive Meshes (Hugues Hoppe, SIGGRAPH 96) http://research.microsoft.com/~hoppe/ Creating Progressive Mesh ID3DXPMesh 객체생성함수 D3DXGeneratePMesh HRESULT D3DXGeneratePMesh ( LPD3DXMESH pmesh, CONST DWORD *padjacency, CONST LPD3DXATTRIBUTEWEIGHTS pvertexattributeweights, CONST FLOAT *pvertexweights, DWORD MinValues, DWORD Options, LPD3DXPMESH *pppmesh); pvertexattributeweights D3DXATTRIBUTEWEIGHTS 배열 (pmesh->getnumvertices() 크기 ) 로의포인터 pvertexweights pmesh->getnumvertices() 크기를갖는 float array MinValue 단순화결과로얻어질최소한의버텍스나면개수 Options D3DXMESHSIMP_VERTEX, D3DXMESHSIMP_FACE, MinValue가 vertrex/face에적용됨을지정함

Vertex Attribute Weights 버텍스속성영향력구조체 typedef struct _D3DXATTRIBUTEWEIGHTS { FLOAT Position; FLOAT Boundary;// blend weight FLOAT Normal; // normal FLOAT Diffuse; // diffuse light value FLOAT Specular; // specular light value FLOAT Texcoord[8]; // texture coordinates FLOAT Tangent; FLOAT Binormal; D3DXATTRIBUTEWEIGHTS; 각요소의영향력을지정할수있도록함 값이높을수록버텍스의영향력이높아져단순화과정에서제거될가능성이낮아짐 ( 최소값 = 0.0) default 영향력값을이용하는것이좋음 Vertex Attribute Weights Default vertex attribute weights: D3DXATTRIBUTEWEIGHTS AttributeWeights; AttributeWeights.Position = 1.0; AttributeWeights.Boundary = 1.0; AttributeWeights.Normal = 1.0; AttributeWeights.Diffuse = 0.0; AttributeWeights.Specular = 0.0; AttributeWeights.Texcoord[8] = { 0, 0, 0, 0, 0, 0, 0, 0 ; ID3DXPMesh Methods ID3DXPMesh 인터페이스는 ID3DXBaseMesh 인터페이스를상속받음 ID3DXMesh 의모든기능을가짐 ID3DXBaseMesh ID3DXPMesh ID3DXPMesh Methods ID3DXBaseMesh 로부터상속받은것외에추가된 method DWORD ID3DXPMesh::GetMaxFaces(VOID); 최대 face 수 DWORD ID3DXPMesh::GetMaxVertices(VOID); 최대 vertex 수 DWORD ID3DXPMesh::GetMinFaces(VOID); 최소 face 수 DWORD ID3DXPMesh::GetMinVertices(VOID); 최소 vertex 수 HRESULT ID3DXPMesh::SetNumFaces(DWORD Faces); LOD 지정함수. 호출후의 face의수는지정한faces값보다 1 작을수있음. 항상최대 / 최소범위내에있도록함 HRESULT ID3DXPMesh::SetNumVertices(DWORD Vertices); LOD 지정함수. 호출후의 vertex의수는지정한vertices값보다 1 작을수있음. 항상최대 / 최소범위내에있도록함

ID3DXPMesh Methods ID3DXBaseMesh 로부터상속받은것외에추가된 method HRESULT ID3DXPMesh::TrimByFaces(DWORD NewFacesMin, DWORD NewFacesMax, DWORD *rgifaceremap, DWORD *rgivertremap) 새로운최소 / 최대 face 수를지정함. 새로운최소 / 최대범위는현재의최소 / 최대범위즉, GetMinFaces() 와 GetMaxFaces() 내에있어야함. rgifaceremap 과 rgivertremap 은각 face/vertex 당한 DWORD 로 face/vertex 의 remap 정보를가짐 즉, i 번째 face/vertex 가어디로이동했는지 HRESULT ID3DXPMesh::TrimByVertices(DWORD NewVerticesMin, DWORD NewVerticesMax, DWORD *rgifaceremap, DWORD *rgivertremap) 새로운최소 / 최대 vertex 수를지정함. 새로운최소 / 최대범위는현재의최소 / 최대범위즉, GetMinVertices() 와 GetMaxVertices() 내에있어야함. Example: Progressive Mesh ID3DXMesh* SourceMesh = 0; ID3DXPMesh* PMesh = 0; // progressive mesh bool Setup() { // Load XFile data ID3DXBuffer* adjbuffer = 0; ID3DXBuffer* mtrlbuffer = 0; DWORD nummtrls = 0; HRESULT hr = D3DXLoadMeshFromX( bigship1.x, D3DXMESH_MANAGED, Device, &adjbuffer, &mtrlbuffer, 0, &nummtrls, &SourceMesh); if (FAILE(hr)) { ::MessageBox(0, D3DXLoadMeshFromX() FAILED, 0, 0); return false; if (mtrlbuffer! = 0 && nummtrls!= 0) { // extract materials, and load textures D3DXMATERIAL* mtrls = (D3DXMATERIAL*) mtrlbuffer->getbufferpointer(); for (DWORD i = 0; I < nummtrls; i++) { // loading시 MatD3d에 ambient값을가지지않으므로지금지정해줌 mtrls[i].matd3d.ambient = mtrls[i].matd3d.diffuse; Mtrls.push_back(mtrls[i].MatD3D); if ( mtrls[i].ptexturefilename!= 0) { // if it has an associative texture IDirect3DTexture9* tex = 0; D3DXCreateTextureFromFile(Device, mtrls[i].ptexturefilename, &tex); Textures.push_back( tex ); else { Textures.push_back(0); // if it has no texture d3d::release<id3dxbuffer*> (mtrlbuffer); Example: Progressive Mesh Example: Progressive Mesh // optimize the mesh to generate an attribute table hr = SourceMesh->OptimizeInplace(D3DXMESHOPT_ATTRSORT D3DXMESHOPT_COMPACT D3DXMESHOPT_VERTEXCACHE, (DWORD*) adjbuffer->getbufferpointer(), (DWORD*) adjbuffer->getbufferpointer(), // new adjacency information 0, 0); if (FAILED(hr)) { ::MessageBox(0, OptimizeInplace() FAILED, 0, 0); d3d::release<id3dxbuffer*>(adjbuffer); return false; // generate the progressive mesh hr = D3DXGeneratePMesh(SourceMesh, (DWORD*) adjbuffer-> GetBufferPointer(), 0, 0, 1, D3DXMESHSIMP_FACE, &PMesh); d3d::release<id3dxmesh*>(sourcemesh); d3d::release<id3dxbuffer*>(adjbuffer); if (FAILED(hr)) { ::MessageBox(0, D3DXGeneratePMesh() FAILED, 0, 0); return false; // set to original detail 이렇게하지않으면가장낮은해상도로렌더링함. DWORD maxfaces = Pmesh->GetMaxFaces(); PMesh->SetNumFaces(maxFaces); // textures // lights // camera // projection matrix

Example: Progressive Mesh Example: Progressive Mesh bool Display(float timedelta) { if (Device) { //update mesh resolution int numfaces = PMesh->GetNumFaces(); // current number of faces if (::GetAsyncKeyState( A ) & 0x8000f) { // add a face PMesh->SetNumFaces(numFaces + 1); if (PMesh->GetNumFaces() == numfaces) PMesh->SetNumFaces(numFaces + 2); // ECT 역변환이가능하도록함 if (::GetAsyncKeyState( S ) & 0x8000f) { // remove a face PMesh->SetNumFaces(numFaces - 1); Device->Clear(0, 0, D3DCLEAR_TARGET D3DCLEAR_ZBUFFER, 0x00000000, 1.0, 0); Device->BeginScene(); for (int i=0; i < (int) Mtrls.size(); i++) { // draw pmesh using draw subset Device->SetMaterial( &Mtrls[i] ); // draw wireframe outline Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); PMesh->DrawSubset(i); Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); Device->EndScene(); Device->Present(0, 0, 0, 0); Bounding Volumes 가장자주이용되는경계볼륨 구 (sphere), 상자 (box) Bounding Sphere: 중심점, 반지름으로정의됨 Bounding Box: 최소점, 최대점으로정의됨 그외 원기둥 (cylinder), 타원체 (ellipsoid), 마름모꼴 (lozenge: 방석모양 ), 캡슐 (capsule) 용도 가시성테스트 (visibility test) 와충돌테스트의가속 max Bounding Volumes D3DX 라이브러리가제공하는경계구체와경계상자를계산하는함수 HRESULT D3DXComputeBoundingSphere ( LPD3DXVECTOR3 pfirstposition, // 첫번째 vertex DWORD NumVertices, DWORD dwstride, // 바이트단위의버텍스크기 D3DXVECTOR3* pcenter, // center of bounding sphere FLOAT* pradius); // radius of bounding sphere center radius min HRESULT D3DXComputeBoundingBox ( LPD3DXVECTOR3 pfirstposition, DWORD NumVertices, DWORD dwstride, // 바이트단위의버텍스크기 D3DXVECTOR3* pmin, // lower-left corner of bounding box D3DXVECTOR3* pmax); // upper-right corner of bounding box

Bounding Volumes d3dutility 새로운특수상수의추가 const float INFINITY = FLT_MAX; //float 에저장할수있는최대수 const float EPSILON = 0.001f; // 0 의의미로사용하는매우작은수 BoundingSphere/Box 타입추가 struct BoundingBox { BoundingBox(); bool ispointinside(d3dxvector3& p); D3DXVECTOR3 _min; D3DXVECTOR3 _max; ; struct BoundingSphere { BoundingSphere(); D3DXVECTOR3 _center; float _radius; ; Bounding Volumes d3dutility BoundingSphere/Box 타입추가 d3d::boundingbox::boundingbox() { _min.x = _min.y = _min.z = d3d::infinity; _max.x = _max.y = _max.z = -d3d::infinity; ; d3d::boundingbox::ispointinside(d3dxvector3& p) { if (p.x >= _min.x && p.y >= _min.y && p.z > = _min.z && p.x <= _max.x && p.y <= _max.y && p.z <= _max.z) ; d3d::boundingsphere::boundingsphere() { _radius = 0.0f; ; Example: Bounding Volumes ID3DXMesh* Mesh = 0; ID3DXMesh* SphereMesh = 0; // bounding sphere ID3DXMesh* BoxMesh = 0; // bounding box bool RenderBoundingSphere = true; bool ComputeBoundingSphere(ID3DXMesh* mesh, d3d::boundingsphere *sphere); bool ComputeBoundingBox(ID3DXMesh* mesh, d3d::boundingbox *box); bool Setup() { // load XFile data // extract the materials, load textures // optimize the mesh // compute bounding sphere and bounding box d3d::boundingsphere boundingsphere; d3d::boundingbox boundingbox; ComputeBoundingSphere(Mesh, &boundingsphere); ComputeBoundingBox(Mesh, &boundingbox); D3DXCreateSphere(Device, boundingsphere._radius, 20, 20, &SphereMesh, 0); D3DXCreateBox(Device, boundingbox._max.x boundingbox._min.x, boundingbox._max.y boundingbox._min.y, boundingbox._max.z boundingbox._min.z, &BoxMesh, 0); // textures, light, camera, projection matrix Example: Bounding Volumes bool Display(float timedelta) { if (Device) { //update mesh resolution // render // clear, BeginScene, draw mesh // draw bounding volume in blue, and at 10% opacity D3DXMATERIAL9 blue = d3d::blue_mtrl; blue.diffuse.a = 0.10f; Device->SetMaterial(&blue); Device->SetTexture(0, 0); // disable texture Device->SetRenderState(D3DRS_ALPHABLENDENABLE, true); Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); if (RenderBoundingSphere) SphereMesh->DrawSubset(0); else BoxMesh->DrawSubset(0); // EndScene, Present

Example: Bounding Volumes Example: Bounding Volumes bool ComputeBoundingSphere(ID3DXMesh* mesh, d3d::boundingsphere *sphere) { HRESULT hr = 0; BYTE* v = 0; mesh->lockvertexbuffer(0, (void**) &v); hr = D3DXComputeBoundingSphere((D3DXVECTOR3*) v, mesh->getnumvertices(), D3DXGetFVFVertexSize(mesh->GetFVF()), &sphere->_center, &sphere->_radius); mesh->unlockvertexbuffer(); if (FAILED(hr)) return false; bool ComputeBoundingBox(ID3DXMesh* mesh, d3d::boundingbox *box) { HRESULT hr = 0; BYTE* v = 0; mesh->lockvertexbuffer(0, (void**) &v); hr = D3DXComputeBoundingBox((D3DXVECTOR3*) v, mesh->getnumvertices(), D3DXGetFVFVertexSize(mesh->GetFVF()), &box->_min, &box->_max); mesh->unlockvertexbuffer(); if (FAILED(hr)) return false;