1 / 32

GPU Programming Seminar 3 Direct3D

. . Outline. Direct3D 9 and its components.DXUT sample framework.D3DX utility library.Shaders using Effect files.Some other stuff.. . . Introduction. If you know Cg, you already know HLSL.DirectX is not as ugly and verbose as you may think.No more Hungarian notation in the core library.Tons a

raleigh
Download Presentation

GPU Programming Seminar 3 Direct3D

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    1. GPU Programming Seminar 3 Direct3D Jaakko Konttinen

    2. Outline Direct3D 9 and its components. DXUT sample framework. D3DX utility library. Shaders using Effect files. Some other stuff.

    3. Introduction If you know Cg, you already know HLSL. DirectX is not as ugly and verbose as you may think. No more Hungarian notation in the core library. Tons and tons of utility functions. Targeted for game developers. A good collection of tools for content creation. Mesh import/export. Texture viewer. A wealth of samples.

    4. Objects, COM, Error Checking Direct3D 9 uses the Component Object Model (COM). Everything is an object and is accessed through some interface represented by a C++ class. Objects are reference counted: ob->AddRef(), ob->Release() Must be done manually Error checking: All calls return an HRESULT Test for error with FAILED(hr) V(ob->DoSomething()) helper “assertion” macro.

    5. Direct3D9 Interface and the Device Direct3D 9 device is the central object. Like GL context? Represented by an IDirect3DDevice9 interface. Provides methods for creating and using resources. All resources (textures, geometry, etc.) are other objects. Lock/Unlock mechanism for sending data.

    6. How (Not) To Create a Device Get access to the “master” interface: IDirect3D9* d3d = Direct3DCreate9(D3D_SDK_VERSION); Create the device: D3DPRESENT_PARAMETERS params; ZeroMemory(¶ms, sizeof(params)); params.Windowed = TRUE; IDirect3DDevice9* device = NULL; d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, myWindow, D3DCREATE_HARDWARE_VERTEXPROCESSING, &device);

    7. Geometry in Direct3D 9 Stored in buffers Created by the device: IDirect3DVertexBuffer9* vertexBuf; device->CreateVertexBuffer( numBytes, ..., &vertexBuf); To fill it with data, lock the buffer to acquire a C-pointer. To draw contents: device->SetStreamSource(0, vertexBuf); device->SetIndices(indexBuf); device->DrawIndexedPrimitive(...);

    8. Vertex Format Vertex buffers are just memory until you describe their format. Two ways to describe: Flexible Vertex Format (easy but rigid) Vertex declarations (verbose but flexible) FVF is just a bit-mask: DWORD fvf = D3DFVF_XYZ|D3DFVF_NORMAL; device->SetFVF(fvf); device->Draw... FVFs map to shader semantics directly. D3DFVF_XYZ ? POSITION0 D3DFVF_NORMAL ? NORMAL0 D3DFVF_TEXCOORD2(0) ? TEXCOORD0 (float2)

    9. Vertex Format struct D3DVERTEXELEMENT9 { WORD Stream; WORD Offset; BYTE Type; BYTE Method; BYTE Usage; BYTE UsageIndex; };

    10. Textures in Direct3D 9 Textures are IDirect3DTexture9 objects. Create using device: IDirect3DTexture9* texture; device->CreateTexture(width, height, ..., usage, ..., &texture); Usage flags allow you to do things like render-to-texture. For regular textures, just put 0.

    11. Render State in Direct3D 9 Things like backface culling, Z-compare mode, ambient light, etc. Two main functions: device->SetRenderState(state, value); device->SetSamplerState(unit, state, value); Not really used with effects.

    12. Memory Pools For almost every resource you create, you must tell where in memory, or which memory pool, to place it in. Passed as parameter to creation functions. Some resources you have no choice. D3DPOOL_DEFAULT = let driver decide. (usually fixed in video or AGP memory; it is the only option for D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC). D3DPOOL_MANAGED = let DirectX manage. Choose this if you can. Backed up in system memory. Swapped out dynamically (expensive though).

    13. “Lost” Devices Devices can become “lost”, preventing any rendering. Circumstances undefined by design. ALT+TAB-ing in full-screen usually does it. Lost devices can be fixed by calling: device->Reset Caveat: Reset will only succeed if all resources created with D3DPOOL_DEFAULT are first destroyed. Sample framework will make this easier.

    14. DXUT Sample Framework Much like GLUT Event-driven. C-style callbacks. Light-weight and modular You can only use it for initialization. Also provides things like camera models and resource caching. Unfortunately has Hungarian notation. A good base for creating a new application. Install EmptyProject or SimpleSample.

    15. Main Functions in DXUT Apps The four initialization/termination functions: OnCreateDevice Called when device is created (only once). Create D3DPOOL_MANAGED here. OnDestroyDevice Called when quit message is received (only once). Release D3DPOOL_MANAGED here. OnResetDevice Called when device is reset (e.g. window resize). Create D3DPOOL_DEFAULT here. OnLostDevice Called when device is lost. Release D3DPOOL_DEFAULT here.

    16. Main Functions in DXUT Apps Two per-frame functions: OnFrameMove Run your simulation/physics/etc. here. OnFrameRender Render your scene here. Separate functions because they can be optionally called at different frequencies. You can rename them if you want.

    17. D3DX Utility Library Full math library. Matrices, vectors, quaternions. Syntax is a little ugly. Image loading/saving functions. BMP, JPEG, PNG, HDR, DDS Dump/load an entire 3D texture or render target (with mipmap chain) to file with one call. Easy filtering and support for procedural filling independent of pixel format.

    18. D3DX Utility Library ID3DXMesh class and its support functions. Combines a VB/IB pair and associated vertex format in one class. Rendering is easy: mesh->DrawSubset(subset); One-call conversion to a new vertex format. One-call mesh optimization functions (stripification, cache optimization, etc.). One-call normal/tangent computation. Import/export available for 3D Studio and Maya. (.X files). Can also create them dynamically instead of from file.

    19. EXAMPLE: White teapot.

    20. Shaders Using D3DX Effect Files An effect file (.fx) stores one or more techniques. A technique describes a way to render something. Contains one or more passes that are supposed to be run in sequence for the same geometry. A pass contains: A vertex shader A pixel shader Any render state data (cull mode, stencil ops, etc.) Effects also contain global variables used by shaders.

    21. Shaders Using D3DX Effect Files Shaders are written in HLSL It looks just like Cg A shader is represented as a function. Shaders can be reused by many passes/techniques by “calling” them with different parameters. A shader is compiled to a shader profile. pass p0 { ZEnable = false; VertexShader = compile vs_2_0 MyVShader(); PixelShader = compile ps_1_4 MyPShader(); }

    22. Interfacing with Effects Compiling an effect: ID3DXEffect* effect; D3DXCreateEffectFromFile(device, “myeffect.fx”, ..., &effect); Setting constant (global) variables: effect->SetFloat(“someGlobal”, 4.0f); effect->SetMatrix(“worldViewProj”, &wvp);

    23. Textures with Effects Textures are represented as variables in effects: texture myTexture; sampler2D mySampler = sampler_state { Texture = <myTexture>; MinFilter = linear; MagFilter = linear; } ... float4 sample = tex2D(mySampler, uv); To activate textures: effect->SetTexture(“myTexture”, myTex); Multiple sampler objects can reference same texture.

    24. Rendering with Effects First choose a technique: effect->SetTechnique(“CoolTech”); Then begin it (also backs up current render state): UINT num_passes; effect->Begin(&num_passes, 0); Render geometry for every pass: for(UINT i = 0; i < num_passes; ++i) { effect->BeginPass(i); /* ... draw meshes using this pass ... */ effect->EndPass(); } End the technique to restore state: effect->End();

    25. Rendering with Effects Of course you do not have to iterate through every pass if you don’t want to. Important: You can not change shader constant variables inside a BeginPass/EndPass block. If you do, call effect->CommitChanges() to make the changes stick. Inside Begin/End is fine.

    26. Other Cool Things about Effects Compilation errors piped to Visual Studio output window. No need for separate compiler to check for errors (although it exists). Effects can store resource information. String data types are supported. Texture file names, etc. There are GetX complements to all SetX functions as well as full enumeration functions. FX Composer implements a scripting language inside Effect files. Effects have preshaders: Shader code that uses only constant data is automatically removed into a mini-program that runs after Begin Can be turned off as a compilation flag.

    27. EXAMPLE: Let’s Write an Effect

    28. GUI, Shader Debugging, PIX DXUT has a full GUI library that is easy to use. SimpleSample already uses it for some basic buttons. DirectX with Visual Studio Extensions allows shader-level debugging. Add a debug flag to your effect compile function (only runs in software mode). Set a breakpoint in your shader and select Debug>With Direct3D from the debug menu. Also allows viewing of all bound textures and breakpoints at specific pixels. DXUT-supported advanced profiling tool (PIX) Haven’t really used it.

    29. Shader Debugging

    30. Render-to-texture in Direct3D9 First create a texture with usage D3DUSAGE_RENDERTARGET. Then store back buffer pointer: IDirect3DSurface9* bb; device->GetRenderTarget(0, &bb); Replace with your texture: IDirect3DSurface9* surface; texture->GetSurfaceLevel(0, &surface); device->SetRenderTarget(0, surface); Render as normal. Replace back buffer similarly when done.

    31. Where to Go For More The help file doesn’t suck. Use as reference only The tutorials are terrible Sample browser A whole bunch of samples ranging from simple to very advanced topics. nVidia/ATI developer resources “Back door” access in DirectX to newer features (e.g. efficient shadow mapping on nVidia cards). Weird quirks (no antialiasing on FP surfaces?) Optimization tips (e.g. GPU Programming Guide).

    32. Conclusion (Hopefully) not as ugly as you thought. Learning curve shouldn’t be too high if you know Cg. Effect files have some features “vanilla” Cg doesn’t have. Unrivalled number of utility functions and samples.

More Related