549
Microsoft DirectX 8.1 Common Framework This source code is furnished to help you get up and running with DirectX more quickly. It is intended to illustrate how Direct3D works, and reduce the time it takes to build simple applications that allow you to experiment. It is used by the samples in the SDK. All of this source code lives in the Samples\Multimedia\Common\Src directory which can be installed during the SDK install. This code is not intended to be cut and paste into a production application. This is not because it is poorly written, but rather that it is not designed for production. No attempt has been made to optimize it for performance. Very little error checking has been added as it obscures the functionality. Use to code to experiment with Direct3D to understand how it works. Classes Names CD3DApplication CD3DArcBall CD3DCamera CD3DFrame CD3DFile CD3DFont CD3DMesh CD3DScreenSaver Functions Names D3DUtil_CreateTexture D3DUtil_CreateVertexShader D3DUtil_GetCubeMapVertex D3DUtil_GetRotationFromCursor D3DUtil_InitMaterial D3DUtil_InitLight D3DUtil_SetColorKey

Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1

CommonFramework

ThissourcecodeisfurnishedtohelpyougetupandrunningwithDirectXmorequickly.ItisintendedtoillustratehowDirect3Dworks,andreducethetimeittakestobuildsimpleapplicationsthatallowyoutoexperiment.ItisusedbythesamplesintheSDK.AllofthissourcecodelivesintheSamples\Multimedia\Common\SrcdirectorywhichcanbeinstalledduringtheSDKinstall.

Thiscodeisnotintendedtobecutandpasteintoaproductionapplication.Thisisnotbecauseitispoorlywritten,butratherthatitisnotdesignedforproduction.Noattempthasbeenmadetooptimizeitforperformance.Verylittleerrorcheckinghasbeenaddedasitobscuresthefunctionality.UsetocodetoexperimentwithDirect3Dtounderstandhowitworks.

Classes NamesCD3DApplicationCD3DArcBallCD3DCameraCD3DFrameCD3DFileCD3DFontCD3DMeshCD3DScreenSaver

Functions NamesD3DUtil_CreateTextureD3DUtil_CreateVertexShaderD3DUtil_GetCubeMapVertexD3DUtil_GetRotationFromCursorD3DUtil_InitMaterialD3DUtil_InitLightD3DUtil_SetColorKey

Page 2: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DUtil_SetDeviceCursor

Structures NamesD3DModeInfoD3DWindowedModeInfoD3DDeviceInfoD3DAdapterInfoMonitorInfoRenderUnit

Macros Names

ErrorCodes Names

Page 3: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 4: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Direct3DXShaderAssemblersReferenceThissectioncontainsreferenceinformationforthevertexandpixelshaderassemblersprovidedbytheDirect3DXutilitylibrary.

VertexShaderAssemblerReferencePixelShaderAssemblerReference

AlloftheexamplesyntaxusedinthisdocumentationisintendedtodemonstratehowtowriteshaderswhenusingtheDirect3DXvertexandpixelshaderassemblers.

Page 5: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 6: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IntroducingDirectX8.1Microsoft®DirectX®isasetoflow-levelapplicationprogramminginterfaces(APIs)forcreatinggamesandotherhigh-performancemultimediaapplications.Itincludessupportfortwo-dimensional(2-D)andthree-dimensional(3-D)graphics,soundeffects,music,inputdevices,andnetworkedapplicationssuchasmultiplayergames.

ThisdocumentprovidesintroductoryinformationaboutDirectX8.1.Informationisdividedintothefollowingsections.

What'sNewinDirectX8.1DirectX8.1ComponentsUsingtheDirectX8.1DocumentationDirectXToolsProgrammingDirectXwithC/C++FurtherInformation

Page 7: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 8: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

What'sNewinDirectX8.1Microsoft®DirectX®8.1isamajorreleaseprimarilyforgraphics.Itincludesseveralnewfeaturesforgraphics,andbugfixesforMicrosoftDirectInput®andMicrosoftDirectPlay®.

Page 9: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

NewToolsinDirectX

AppWizard.ThistoolprovidesanapplicationwizardforcreatingaDirectXapplicationwithanycombinationofDirectXcomponents.Thistoolisinstalledduringthesoftwaredevelopmentkit(SDK)installandcanbeaccessedwithinMicrosoftVisualStudio®whencreatinganewapplication.FormoreinformationseeAppWizard.ErrorLookupTool.Usethistooltotakethehexadecimalerrorcodesandlookupatext-basederrormessage.ThistoolisinstalledaspartoftheSDKinstallandcanbeaccessedfromStart,Programs,MicrosoftDirectX8.1SDK,DirectXUtilities,DirectXErrorLookup.

Page 10: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

NewFeaturesinDirectXGraphics

Expandedpixelshaderfunctionalitywithnewversion1.2,1.3,and1.4.ExpandedthefunctionalityoftheDirect3DX(D3DX)utilitylibraryformeshes,textures,bumpmapping,textures,andquaternions.MeshView.Thistoolprovidesaneasywaytoload,view,andmodifymeshes,andgenerallyexerciseD3DXfunctionalityonprogressivemeshes.Formoreinformationaboutthetool,seeMeshViewHelp.Anewscreensaversampleisincludedthatisbuiltonthescreensaversampleframework.Thenewframeworkincludessupportformultiplemonitors.Addednewsamples.Reorganizedthedocumentationintoreferenceandprogrammingguides.Expandedshadersandeffectssections.

FormoreinformationseeWhat'sNewinGraphics,orseeeachofthecomponents.

Page 11: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

NewFeaturesinDirectInput

Version8.1primarilyincludesperformanceimprovementsforDirectInput.

Formoreinformation,seeWhat'sNewinDirectInput.

Page 12: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

NewFeaturesinDirectPlay

Version8.1primarilyincludesperformanceimprovementsforDirectPlay.

Formoreinformation,seeWhat'sNewinDirectPlay.

Page 13: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

NewFeaturesinDirectX8.0

CompleteintegrationofDirectDrawandDirect3DMicrosoftDirectDraw®andMicrosoftDirect3D®aremergedintoasingleDirectXGraphicscomponent.Theapplicationprogramminginterface(API)hasbeenextensivelyupdatedtomakeiteveneasiertouseandtosupportthelatestgraphicshardware.

DirectMusicandDirectSoundmoreintegratedMicrosoftDirectMusic®andMicrosoftDirectSound®aremoretightlyintegratedthanwithDirectX7.0.WavefilesorresourcescannowbeloadedbytheDirectMusicloaderandplayedthroughtheDirectMusicperformance,synchronizedwithMIDInotes.

DirectPlayupdatedTheDirectPlaycomponenthasbeenextensivelyupdatedtoincreaseitscapabilitiesandimproveitsease-of-use.Inparticular,DirectPlaynowsupportsvoicecommunicationbetweenplayers.

DirectInputupdatedDirectInputintroducesonemajornewfeature:actionmapping.Actionmappingenablesyoutoestablishaconnectionbetweeninputactionsandinputdevices,whichdoesnotdependontheexistenceofparticulardeviceobjects.Itsimplifiestheinputloopandreducestheneedforcustomgamedrivers,customdeviceprofilers,andcustomconfigurationofuserinterfacesingames.

DirectShowincludedinDirectXMicrosoft®DirectShow®isnowpartofDirectXandhasbeenupdatedforthisrelease.

DebugbuildavailableYoucanusetheDirectXControlPanelApplicationtoswitchbetweenthedebugandretailbuildsofDirectInput,Direct3D,andDirectMusic.Toenablethisfeature,selectDebugwhenyouinstallthesoftwaredevelopmentkit(SDK).Thisoptioninstallsbothdebugandretaildynamic-linklibraries(DLLs)onyoursystem.TheRetailoptioninstallsonlytheretailDLLs.

Page 14: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 15: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DirectX8.1ComponentsMicrosoft®DirectX®8.1ismadeupofthefollowingcomponents.

DirectXGraphicscombinestheMicrosoftDirectDraw®andMicrosoftDirect3D®componentsofpreviousDirectXversionsintoasingleapplicationprogramminginterface(API)thatyoucanuseforallgraphicsprogramming.ThecomponentincludestheDirect3DXutilitylibrarythatsimplifiesmanygraphicsprogrammingtasks.DirectXAudiocombinestheMicrosoftDirectSound®andMicrosoftDirectMusic®componentsofpreviousDirectXversionsintoasingleAPIthatyoucanuseforallaudioprogramming.MicrosoftDirectInput®providessupportforavarietyofinputdevices,includingfullsupportforforce-feedbacktechnology.MicrosoftDirectPlay®providessupportformultiplayernetworkedgames.MicrosoftDirectShow®providesforhigh-qualitycaptureandplaybackofmultimediastreams.MicrosoftDirectSetupisasimpleAPIthatprovidesone-callinstallationoftheDirectXcomponents.

Page 16: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 17: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

UsingtheDirectX8.1Documentation

Thefollowingconventionsareusedinthesyntaxofmethods,functions,andotherAPIelements,aswellasinexplanatorymaterialandsamplecode.

Convention Meaning

Italictext

Denotesaplaceholderorvariable.Youmustprovidetheactualvalue.Forexample,thestatementSetCursorPos(X,Y)requiresyoutosubstitutevaluesfortheXandYparameters.

BoldtextDenotesafunction,procedure,structure,macro,interface,method,datatype,orotherkeywordintheprogramminginterfaceorlanguage.

[] Enclosesoptionalparameters.... Specifiesthattheprecedingitemmayberepeated.FULLBOLDCAPITALS Usedformosttypeandstructurenames.

FULLCAPITALS Usedforenumerationvalues,flags,andconstants.monospace Usedforcodeexamplesandsyntaxspacing..

.

.

Representsanomittedportionofasampleapplication.

Page 18: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 19: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

FurtherInformationYoucanfindfurtherexplanationsofthegraphicsandmultimediaconceptsandtermsdiscussedthroughouttheMicrosoft®DirectX®documentation,aswellasinformationonMicrosoft®Windows®programmingingeneral,inthefollowingsources:

Bargen,BradleyandPeterDonnelly,InsideDirectX,Microsoft®Press®,1998.Begault,DurandR.,3-DSoundforVirtualRealityandMultimedia,AcademicPress,1994.Blinn,James,JimBlinn'sCorner:ATripDowntheGraphicsPipeline,MorganKaufmann,1996.Dodge,CharlesandThomasA.Jerse,ComputerMusic:Synthesis,Composition,andPerformance,SchirmerBooks,1997(2ndedition).Foley,JamesD.,ComputerGraphics:PrinciplesandPractice,Addison-Wesley,1991(2ndedition).Hearn,DonaldandM.PaulineBaker,ComputerGraphics,Prentice-Hall,1986.Kientzle,Tim,AProgrammer'sGuidetoSound,Addison-WesleyDevelopersPress,1998.Kovach,PeterJ.,InsideDirect3D,MicrosoftPress,2000.Petzold,Charles,ProgrammingWindows98,MicrosoftPress,1998(5thedition).Thompson,Nigel,3DGraphicsProgrammingforWindows,MicrosoftPress,1996.Watt,AlanH.,andMarkWatt,AdvancedAnimationandRenderingTechniques,Addison-Wesley,1992.

AdditionalsourcesfortheconceptsandtermsassociatedwithCOMcanbefoundinthefollowingsources:

Brockschmidt,Kraig,InsideOLE2,MicrosoftPress,1995(2ndedition).Rogerson,DaleE.,InsideCOM,MicrosoftPress,1997.

Page 20: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 21: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MeshViewHelpMenuDescriptions

File

OpenMeshFile

Opensadialogtoselectafileinthe.xor.mfileformattobeloadedandviewed.

OpenPMeshFile

Opensadialogtoselectafileintheprogressivemeshformattobeloadedandviewed.

CreateShape

Opensasub-dialogtocreatesomebasicshapesthataredefinedprogrammatically(text,polygon,box,cylinder,torus,teapot,sphere,cone).

SaveMeshAs

Opensadialogtosavetheselectedmeshtoafile.Thefilecanbewrittenasatextorbinaryfile.

CloseSelected

Closesanddeletesthecurrentlyselectedmesh.

CloseNonSelected

Closesanddeletesthemeshesthatarenotcurrentlyselected.

View

Wireframe

Page 22: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Viewallcontentinwireframemode.

Edges

Viewallcontentinsolid-shadedmodewiththeedgesdrawninblack.

Creases

Highlightthecreasesonthevisiblemeshes.Acreaseisanedgewithavertexthathasadifferentpieceofdataonitformultiplefacesthatrefertoit,thatis,adifferentnormalforthevertexperface.

Strips

Showthestripsthataregeneratedbythismeshinblue.Thebluelinegoesfromthecenterofeachtriangletothenexttriangleinthetrianglestrip.

Adjacency

Showtheadjacencyofthepolygonsinameshbydrawingalinefromthecenterofapolygontothecenteroftheadjacentpolygon.

BoundingBox

Drawtheboundingboxesforthevisiblemeshes.

Normals

Drawthenormalsoftheverticesonthevisiblemeshesinyellow.

TextureCoords

Showthetexturecoordinatesfortheviewedgeometryasraysprojectingfromthevertices.BecauseavertexinMicrosoft®Direct3D®canhaveuptoeighttexturecoordinates,usersmustspecifywhichsetstheywouldliketoview.Thisviewingmodeisespeciallyusefulwhenthetexturecoordinatesarefilledwithtangentsforuseinpixelshadersforexample.

Textures

Displaythetexturesonthevisiblegeometry.

Page 23: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Lighting

Showthegeometryinthescenewithlightingcalculationsstillon.

Culling

Performbackfacecullingonthevisiblegeometrywhendisabledpolygonsfacingawayfromthecameraarenotdrawn.

Hierarchy

Displaytheframehierarchyofthemeshesthatarecurrentlyloaded.Thisisdisplayedinaseparatefloatingwindow.Tomakethewindowdisappear,ontheViewmenu,cleartheHierarchycommand.

PlayAnimation

Playthecurrentanimationforthecurrentlyloadedgeometryifoneexists.

PauseAnimation

Stoptheanimationatthecurrentframewhenplaying.

NormalSpeed

InterpretthetimevalueintheanimationfromanXfileas4800unitspersecond.Otherwise,theinterpretedvalueis30unitspersecond.

MeshOps

Optimize

Optimizesthecurrentlyselectedmeshwiththeselectedoptimizationmethod.SeetheMicrosoft®Direct3DXreferencepagestoseethedifferencesinmethods.

WeldVertices

Removesduplicateverticesandmakespolygonsthatusetheseverticesusethenondeletedvertex.

Page 24: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SplitMesh

Splitstheselectedmeshintomultiplemeshesthatarelessthanspecifiedsizeinverticesandfaces.

CollapseMeshes

Collapsesthecurrentlyselectedmeshesintoasinglemesh.

ResetMatrices

Resetsthematricesfortheframesthatareloadedtotheirinitialposition.

MeshProperties

Showstheselectedmesh'sFVFrenderstatesandwhetherornotitisa32bitmesh.

SkinningMethod

Allowstheusertoselecttheskinningmethodwhileanimatingaskinnedmesh.Thechoicesarenonindexed,indexed,andsoftwareskinning.

FaceSelection

Entersamodefortheusertoselectanindividualfaceonthecurrentmesh.

VertexSelection

Entersamodefortheusertoselectanindividualvertexonthecurrentmesh.

PMeshes

ConvertSelectedtoPM

Converttheselectedmeshtoaprogressivemesh.Theconversionusestheerrorparametersthatareenteredinadialogbox.FormoreinformationontheseparametersrefertotheDirect3DXdocumentationofprogressivemeshes.

Page 25: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SnapshottoMesh

Convertthecurrentprogressivemeshobjecttoastaticmeshobjectusingthecurrentsettingsoftheprogressivemesh.

SetnumberofFaces

Setthecurrentnumberoffacesintheprogressivemeshtoaspecificnumber.

SetnumberofVertices

Setthecurrentnumberofverticesintheprogressivemeshtoaspecificnumber.

Trim

Settheminimumandmaximumnumberoffacesforaprogressivemesh.Oncetheuserhassetthetrimvaluestothedesiredminimumandmaximum,theprogressivemeshcanbetrimmedtotheselectedvalues,therebyreducingthedynamicrangeoftheprogressivemesh.

N-Patches

N-PatchSelected

DrawthecurrentobjectasanN-Patchesobject.ThescrollbarinthismodeselectstheamountofN-Patchiterationsforthecurrentobject.

SnapShottomesh

ConverttheselectedobjecttoastaticmeshbasedonthecurrentN-Patchsettingstocreateahigh-resolutionstaticmesh.

Page 26: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IconsandUsage

Icons

SelectionModes

Thefirstthreeiconsareeasywaysfortheusertoselecttheselectionmode.TheyareMeshSelectionMode(Arrow),FaceSelectionMode(yellowoutlinedtriangle),andVertexSelectionMode(Redpointhighlightedtriangle).ThesearethesamemodesthatareavailablefromthemenusinMeshOps.

DisplayModes

Thenexticonsareeasywaystoselectthemostcommondisplaymodesforgeometry.TheyareShadedmode(nonoutlinedtri-colorcube),Wireframemode(wireframecube),andEdgemode(outlinedtri-colorcube).ThesearethesamemodesthatareavailablefromthemenusinView.

TopologyDisplaymodes

Thenexticonsdisplayspecifictopologicalinformationaboutthegeometrydisplayed.Theyareadjacency(A),Strips(S),Creases(C),andNormals(N).ThesearethesamemodesthatareavailablefromthemenusinView.

Info

Thenexticonistheinfobuttonthatwilldisplayinformationaboutthecurrentlyselectedelement.

AnimationControls

Thelasttwoiconsareanimationcontrolsforplayingandpausingtheanimationforthecurrentlyvisiblemesh.

StatusBar

ThestatusbarinMViewdisplaysthecurrentstatusofthevisiblegeometry.The

Page 27: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

orderfromlefttorightofthedisplayedinformationiscurrentlyselectedelement(faceorvertexonly),Meshmode(polygon,Pmesh,orpMesh),displayframespersecond,displaytrianglespersecond,numberofdisplayedtriangles,andnumberofdisplayedvertices.

ScrollBar

Thescrollbarwillappearintwoofthethreemeshmodes,pMeshandnPatchmode.InpMeshmode,thescrollbarindicatestherangeofdisplayedtrianglesfortheprogressivemesh.Youcanslidethescrollbarupordowntochangethenumberoftrianglesdisplayed.InnPatchmode,thescrollbarindicateshowmanynPatchlevelsarebeingused.Asthescrollbarismovedupordown,thenumberofnPatchinteractionsperformedareadjustedaccordingly.

Page 28: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MoreInformation

FormoreinformationonanyofthefunctionsusedbyMView,refertotheDirect3DXdocumentationincludedintheMicrosoft®DirectX®softwaredevelopmentkit(SDK).

Page 29: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 30: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MoireSample

Description

ThemoiresampleshowshowtousetheMicrosoft®DirectX®softwaredevelopmentkit(SDK)screensaverframeworktowriteascreensaverthatusesMicrosoft®Direct3D®.Thescreensaverframeworkissimilartothesampleapplicationframework,usingmanymethodsandvariableswiththesamenames.Afterwritingaprogramwiththescreensaverframework,youendupwithafully-functionalMicrosoft®Windows®screensaver,ratherthanwitharegularWindowsapplication.

Themoirescreensaverappearsasamesmerizingsequenceofspinninglinesandcolors.Itusestexturetransformationandalphablendingtocreateahighlyanimatedscene,eventhoughthepolygonsthatmakeupthescenedonotmoveatall.

Path

Source:(SDKroot)\Samples\Multimedia\Direct3D\ScreenSavers\Moire

Executable:(SDKroot)\Samples\Multimedia\Direct3D\Bin

User'sGuide

Moire.scrcanbestartedinfivemodes:configuration,preview,full,test,andpassword-change.Youcanchoosesomemodesbyclickingtherightmousebutton(right-click)onthemoire.scrfileandchoosingConfigureorPreview.Oryoucanstartmoire.scrfromthecommandlinewiththefollowingcommand-lineparameters:-c Configurationmode-t Testmode-p Previewmode-a Password-changemode-s Fullmode

Page 31: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Whenthescreensaverisrunninginfullmode,pressanykeyormovethemousetoexit.

ProgrammingNotes

ProgramsthatusethescreensaverframeworkareverysimilartoprogramsthatusetheDirect3Dsampleapplicationframework.Eachscreensaverneedstocreateaclassderivedfromthemainapplicationclass,CD3DScreensaver.Toprovidefunctionalityspecifictoeachscreensaver,thescreensaverimplementsitsownversionsofthevirtualfunctionsFrameMove,Render,InitDeviceObjects,andsoforth.

Screensaverscanbewrittentobemultimonitor-compatible,withoutmuchextraeffort.Ifyoudonotwantyourscreensavertorunonmultiplemonitors,youcanjustsetthem_bOneScreenOnlyvariabletoTRUE.ThisvalueissettoFALSEbydefault.ThefunctionSetDevicewillbecalledeachtimethedevicechanges.ThewaythatmoiredealswiththisistocreateastructurecalledDeviceObjects,whichcontainsalldevice-specificpointersandvalues.CMoireScreensaverholdsanarrayofDeviceObjectsstructures,calledm_DeviceObjectsArray.WhenSetDeviceiscalled,m_pDeviceObjectsischangedtopointtotheDeviceObjectsstructureforthespecifieddevice.Whenrendering,m_rcRenderTotalreferstotherenderingareathatspansallmonitors,andm_rcRenderCurDevicereferstotherenderingareaforthecurrentdevice'smonitor.ThefunctionSetProjectionMatrixshowsonewaytosetupaprojectionmatrixthatmakesproperuseofthesevariablestoeitherrenderascenethatspansallthemonitors,ordisplayacopyofthesceneoneachmonitor.Theprojectionmatrixuseddependsonthevalueofm_bAllScreensSame,whichyoucanenabletheusertocontrolintheconfigurationdialog.

TheReadSettingsfunctioniscalledbythescreensaverframeworkatprogramstartuptime,toreadvariousscreensaversettingsfromtheregistry.DoConfigiscalledwhentheuserwantstoconfigurethescreensaversettings.Theprogramshouldrespondtothisbycreatingadialogboxwithcontrolsforthevariousscreensaversettings.ThisdialogboxshouldalsohaveabuttoncalledDisplaySettingswhich,whenpressed,shouldcallDoScreenSettingsDialog.Thiscommondialogboxallowstheusertoconfigurewhatrendereranddisplaymodeshouldbeusedoneachmonitor.Youshouldsetthemembervariablem_strRegPathtoaregistrypaththatwillholdthescreensaver'ssettings.Youcanusethisvariableinyourregistryread/writefunctions.Thescreensaver

Page 32: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

frameworkwillalsousethisvariabletostoreinformationaboutthedefaultdisplaymodeinsomecases.

ThissampleusescommonDirectXcodethatconsistsofprogrammingelementssuchashelperfunctions.ThiscodeissharedwithothersamplesintheDirectXSDK.Youcanfindthecommonheadersandsourcecodein(SDKroot)\Samples\Multimedia\Common.

Page 33: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 34: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

What'sNewinDirectXGraphicsThissectiondescribesMicrosoft®DirectX®graphicsfeaturesthatarenewinDirectX8.x.

Toseewhat'snewinallofDirectX,seeWhat'snewinDirectX8.1.

Page 35: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

NewFeaturesinDirectX8.1

PixelShaders

Addedpixelshaderversions1.2,1.3,and1.4.Thesenewversionsexpandexistingfunctionalitythroughamorepowerfulsetofinstructions,registers,andmodifiersforprogrammingpixelshaders.

NewD3DXFunctionality

MeshAPI

AddedmeshfunctionalitytoimproveperformanceusingD3DXConvertMeshSubsetToStripsandD3DXConvertMeshSubsetToSingleStrip.UsetheOptimizedMeshsampletounderstandimprovingmeshperformance.ImprovedsupportforprogressivemesheswithOptimizeBaseLOD,TrimByVerticesandTrimByFaces.AddedD3DXSplitMeshtohelpsplitmeshesintosmallermeshes.

BumpMapping

AddedD3DXComputeTangenttocreateaper-vertexcoordinatesystembasedontexturecoordinategradients.D3DXComputeNormalMapconvertsaheightfieldtoanormalmap.

MeshViewTool

Thistoolprovidesaneasywaytoload,view,andmodifymeshes,andgenerallyexerciseDirect3DX(D3DX)functionalityonprogressivemeshes.Thistoolisinstalledaspartofthesoftwaredevelopmentkit(SDK)installandcanbeaccessedfromStart/Programs/MicrosoftDirectX8.1SDK/DirectXUtilities/DirectXMeshView.Formoreinformationaboutthetool,seeMeshViewHelp.

EffectFramework

Effects.Addedstringsupport,addedcomments,andremovedFourCC

Page 36: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

constraints.EffectframeworkAPI.Supportforstatesavingandrestoring,supportforhandlingOnLostandOnReset,supportSet*()afterBegin().AlloftheID3DXTechniquefunctionalityhasbeenmovedintotheID3DXEffectinterfacetosimplifytheeffectinterface.

TextureLibrary

ImplementedahigherqualityDXTnencodingalgorithm.UseD3DXGetImageInfoFromtogetimageinformationbeforeloadingit.Includessupportfordynamictextures.D3DXSaveSurfaceToFilesupports8-bitpaletted.bmpfilesand24-bitRGB.ddsfilesinallformats:mipmaps,cubemaps,volumes.D3DPOOL_SCRATCHallowscreationofresourcesthatarenotlimitedbydevicecapabilities.Theycanbecreatedanddestroyed,lockedandunlocked.Theseresourcescanbesettoadeviceandusedinrendering.UsewithD3DXtoconverttosomethinguseablesuchasloadingahigh-precisionheightfieldandconvertingtoanormalmap.Texturefillfunctions,D3DXFillTexture,D3DXFillCubeTexture,andD3DXFillVolumeTexture.

MathLibrary

Newmathfunctions:AdditionalsupportforsphericalquadraticquaternioninterpolationusingD3DXQuaternionSquadSetup.UseitwithD3DXQuaternionSquad.D3DXMatrixMultiplyTransposeformatricesinvertexshadersandD3DXFresnelTerm.Mathlibrary.AddedCPUspecificoptimizationsformostimportantfunctionsfor3DNow,SSE,andSSE2.Supportfor16-bytealignedmatricesusingD3DXMATRIXA16.

Samples

Severalnewsampleshavebeenincludedtodemonstrateculling,lighting,volumefog,andself-shadowingusingashadowvolume.Anewscreensaversampleisincludedthatisbuiltonthescreensaversampleframework.Thenewframeworkincludessupportformultiplemonitors.

DocumentationUpgrades

Page 37: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DXGraphicsSDKDocs.ThegraphicsSDKdocumentationhasbeenreorganizedintotwosections:aReferencesectionandaProgrammersGuide.Newsectionsforcreatingprogrammablevertexshaders,pixelshaders,andeffectshavebeenaddedtotheProgrammersGuide.TheglobalilluminationequationsandtheMathematicsofLightingsectionhavebeenrewrittenandexamplesincluded.

Page 38: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

NewFeaturesinDirectX8.0

ThisversionmaintainsbackwardcompatibilitybyexposingandsupportingobjectsandinterfacesofferedbypreviousreleasesofDirectX.However,manynewfeaturesandperformanceenhancementshavealsobeenaddedtotheMicrosoftDirect3D®APIinterfaces.

PixelandVertexShaders

ThetwoprogrammablesectionsoftheDirect3Darchitecturearevertexshadersandpixelshaders.Vertexshadersareinvokedpriortovertexassemblyandoperateonvertices.PixelshadersareinvokedafteranyDrawPrimitiveorDrawIndexedPrimitivecallsandgeneratethepixelsthatarewrittentotherendertarget.Theadditionofprogrammableshadersforvertexandpixeloperationsprovidestheframeworkforreal-timeprogrammableeffectsthatrivalmoviequality.Theinnovativefreedomthatthisprogrammabilitygivesbacktogamedevelopers—byallowingthemtoimplementwhatevereffecttheyseefitwiththeprogrammablepipeline—hasthepotentialtounlockanewroundofincrediblegames.PixelandvertexshaderscanbewrittenusingASCIIfiles,thustheshaderfilescanbeupdatedatruntimewithoutrecompilingthesourceapplication.

Effects

Allowsyoutochangehowanobjectisrendered,basedonthehardwarecapabilitiesofthemachineyourapplicationisrunningon.EffectsarewrittenusingASCIIfiles,thustheeffectfilecanbeupdatedatruntimewithoutrecompilingthesourceapplication.

CompleteIntegrationofDirectDrawandDirect3D

Simplifiesapplicationinitializationandimprovesdataallocationandmanagementperformance,whichreducesthememoryfootprint.Also,theintegrationofthegraphicsAPIsenableparallelvertexinputstreamsformoreflexiblerendering.

MultisamplingRenderingSupport

Page 39: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Enablesfull-sceneantialiasingandmultisamplingeffects,suchasmotionbluranddepth-of-field.

PointSprites

Enableshigh-performancerenderingofparticlesystemsforsparks,explosions,rain,snow,andsoon.

3-DVolumetricTextures

Enablesrange-attenuationinper-pixellightingandvolumetricatmosphericeffects,andcanbeappliedtomoreintricategeometry.

Higher-OrderPrimitiveSupport

Enhancestheappearanceofthree-dimensional(3-D)contentandfacilitatesthemappingofcontentfrommajor3-Dauthoringtools.

Higher-LevelTechnologies

Includes3-Dcontent-creationtoolplug-ins(forexporttoDirect3D)forskinnedmeshesthatuseavarietyofDirect3Dtechniques,multiresolutionlevel-of-detail(LOD)geometry,andhigher-ordersurfacedata.

IndexedVertexBlending

Extendsgeometryblendingsupporttoallowthematricesusedforvertexblendingtobereferredtousingamatrixindex.

ExpansionoftheDirect3DXUtilityLibrary

Containsawealthofnewfunctionality.TheDirect3DXutilitylibraryisahelperlayerthatsitsontopofDirect3Dtosimplifycommontasksencounteredby3-Dgraphicsdevelopers.Includesaskinninglibrary,supportforworkingwithmeshes,andfunctionstoassemblevertexandpixelshaders.About20newfunctionshavebeenaddedforDirectX8.1.NotethatthefunctionalitysuppliedbyD3D_OVERLOADS,firstintroducedwithDirectX5.0,hasbeenmovedtotheDirect3DXutilitylibrary.

Page 40: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 41: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

What'sNewinDirectInputNewFeaturesforDirectInput8.1

Microsoft®DirectX®8.1isamajorreleaseprimarilyforDirectXgraphics.TheimprovementsforMicrosoftDirectInput®areprimarilyperformanceenhancements.

TofindoutmoreaboutthenewfeaturesinDirectX,seeWhat'sNewinDirectX8.1.

Page 42: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

NewFeaturesforDirectInput8.0

ThefollowingaresomeofthenewfeaturesinDirectInput.

ActionmappingDirectInputforDirectX8.0introducesamajornewfeature:actionmapping.Actionmappingenablesyoutoestablishaconnectionbetweeninputactionsandinputdevicesthatdoesnotdependontheexistenceofparticulardeviceobjects(suchasspecificbuttonsoraxes).Actionmappingsimplifiestheinputloopandreducestheneedforcustomgamedrivers,customdeviceprofilers,andcustomconfigurationuserinterfacesingames.

Formoreinformation,seeActionMapping.

NewDirectInputobjectfeaturesTheDirectInputobjectisnowrepresentedbytheIDirectInput8interface.Anewhelperfunction,DirectInput8Create,createstheobjectandretrievesthisinterface.IDirectInput8hasanewCLSIDandcannotbeobtainedbycallingQueryInterfaceonaninterfacetoobjectsoftheclassCLSID_DirectInputusedinearlierDirectXversions.

NewkeyboardpropertiesTwokeyboardpropertieshavebeenadded:DIPROP_KEYNAME,whichretrievesalocalizedkeyname,andDIPROP_SCANCODE,whichretrievesthescancode.

JoysticksliderdatainrglSliderarrayJoysticksliderdatathatwasassignedtothez-axisofaDIJOYSTATEorDIJOYSTATE2structureunderearlierDirectXversionswillnowbefoundintherglSliderarrayofthosesamestructures.

Page 43: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 44: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Instructions

Pixelshaderscontainthefollowingtypesofinstructions.

AVersioninstructiondefinestheshaderversion.Thereisonlyoneversioninstructioninashaderanditisthefirstinstructioninashader.Constantinstructionsdefineconstants.Theseinstructionsmustbeaftertheversioninstructionandbeforeanyarithmeticortextureaddressinstructions.APhaseinstructionsplitsashaderintotwosections:phase1andphase2.Eachphasehasseparatearithmeticandtextureaddressinstructionlimits.Version1.4istheonlyversionthatsupportsthephaseinstruction.Arithmeticinstructionsincludecommonmathematicaloperationssuchasaddandsubtract,multiply,andtakingadotproduct.TextureAddressinstructionsmanipulatetexturecoordinatedatathatisassociatedwithtexturestages.

Theinstructionsarelistedbelow.

Versioninstructions Version1.0 1.1 1.2 1.3 1.4

ps x x x x x

Constantinstructions Version1.0 1.1 1.2 1.3 1.4

def x x x x x

Phaseinstructions Version1.0 1.1 1.2 1.3 1.4

phase x

Arithmeticinstructions Version1.0 1.1 1.2 1.3 1.4

add x x x x xbem xcmp x x xcnd x x x x xdp3 x x x x xdp4 x x x

Page 45: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

lrp x x x x xmad x x x x xmov x x x x xmul x x x x xnop x x x x xsub x x x x x

Textureaddressinstructions Version1.0 1.1 1.2 1.3 1.4

tex x x x xtexbem x x x xtexbeml x x x xtexcoord x x x xtexcrd xtexdepth xtexdp3 x xtexdp3tex x xtexkill x x x x xtexld xtexm3x2depth xtexm3x2pad x x x xtexm3x2tex x x x xtexm3x3 x xtexm3x3pad x x x xtexm3x3tex x x x xtexm3x3spec x x x xtexm3x3vspec x x x xtexreg2ar x x x xtexreg2gb x x x xtexreg2rgb x x

Page 46: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectx8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 47: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Registers

Registersholddataforusebythepixelshader.Registersarefullydescribedinthefollowingsections.

RegisterTypes.Describesthefourtypesofregistersavailableandtheirpurposes.ReadPortCount.Detailstherestrictionsonusingmultipleregistersinasingleinstruction.Read-only,Read/Write.Describeswhichregisterscanbeusedforreading,writing,orboth.Range.Detailstherangeofthecomponentdata.

RegisterTypes

RegisterstransferdatatotheshaderALUandstoretemporaryresults.Thetablebelowidentifiesthefourtypesofregistersandthenumberavailableineachshaderversion.

Registername Type Versions1.0 1.1 1.2 1.3 1.4

cn Constantregister 8 8 8 8 8rn Temporaryregister 2 2 2 2 6tn Textureregister 4 4 4 4 6vn Colorregister 2 2 2 2 2inphase2

Constantregisterscontainconstantdataorganizedinfourfixed-pointvalues.DatacanbeloadedintoaconstantregisterusingSetPixelShaderConstantoritcanbedefinedusingthedefshaderinstruction.Constantregistersarenotusablebytextureaddressinstructions.Theonlyexceptionisthetexm3x3specinstruction,whichusesaconstantregistertosupplyaneye-rayvector.

Temporaryregistersareusedtostoreintermediateresults,asfourfixed-pointvalues.r0additionallyservesasthepixelshaderoutput.Thevalueinr0attheendoftheshaderisthepixelcolorfortheshader.

Page 48: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Shaderpre-processingwillfailCreatePixelShaderonanyshaderthatattemptstoreadfromatemporaryregisterthathasnotbeenwrittenbyapreviousinstruction.D3DXAssembleShaderwillfailsimilarly,assumingvalidationisenabled(donotuseD3DXASM_SKIPVALIDATION).

TextureregistersPixelshaderversion1.1to1.3

Forpixelshaderversion1.1to1.3,textureregisterscontaintexturedata,organizedinfourfixed-pointvalues.Texturedataisloadedintoatextureregisterwhenatextureissampled.Texturesamplingusestexturecoordinatestolookup,orsample,acolorvalueatthespecified(u,v,w,q)coordinateswhiletakingintoaccountthetexturestagestateattributes.Thetexturecoordinatedataisinterpolatedfromthevertextexturecoordinatedataandisassociatedwithaspecifictexturestage.Thereisadefaultone-to-oneassociationbetweentexturestagenumberandtexturecoordinatedeclarationorder.Bydefault,thefirstsetoftexturecoordinatesdefinedinthevertexformatisassociatedwithtexturestage0.

Forthesepixelshaderversions,textureregistersbehavejustliketemporaryregisterswhenusedbyarithmeticinstructions.Forpixelshaderversion1.0,textureregistersareread-onlytoarithmeticinstructions.

Pixelshaderversion1.4

Forpixelshaderversion1.4,textureregisters(t#)containread-onlytexturecoordinatedata.Thismeansthatthetexturecoordinatesetandthetexturestagenumberareindependentfromeachother.Thetexturestagenumber(fromwhichtosampleatexture)isdeterminedbythedestinationregisternumber(r0tor5).Forthetexldinstruction,thetexturecoordinatesetisdeterminedbythesourceregister(t0tot5),sothetexturecoordinatesetcanbemappedtoanytexturestage.Inaddition,thesourceregister(specifyingtexturecoordinates)fortexldcanalsobeatemporaryregister(r#),inwhichcasethecontentsofthetemporaryregisterareusedastexturecoordinates.

Forthispixelshaderversion,textureregisterscontaintexture

Page 49: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

coordinatedataandarealsoavailabletotextureaddressinginstructionsassourceparameters.

Colorregisterscontainper-pixelcolorvalues.Thevaluesareobtainedbyper-pixeliterationofthediffuseandspecularcolorvaluesinthevertexdata.Colorregistersstoredatainfourfixed-pointvalues.Forpixelshaderversion1.4shaders,colorregistersareavailableonlyduringthesecondphase.

IftheshademodeissettoD3DSHADE_FLAT,theapplicationiterationofbothvertexcolors(diffuseandspecular)isdisabled.Regardlessoftheshademode,fogwillstillbeiteratedbythepipelineifpixelfogisenabled.Keepinmindthatfogisappliedlaterinthepipelinethanthepixelshader.

Itiscommontoloadthev0registerwiththevertexdiffusecolordata.Itisalsocommontoloadthev1registerwiththevertexspecularcolordata.

Inputcolordatavaluesareclamped(saturated)totherange0through1becausethisisthevalidinputrangeforcolorregistersinthepixelshader.

Pixelshadershavereadonlyaccesstocolorregisters.Thecontentsoftheseregistersareiteratedvalues,butiterationisperformedatmuchlowerprecisionthantexturecoordinates.

ReadPortLimit

Thereadportlimitspecifiesthenumberofdifferentregistersofeachregistertypethatcanbeusedasasourceregisterinasingleinstruction.

Registername Type Versions1.0 1.1 1.2 1.3 1.4

cn Constantregister 2 2 2 2 2rn Temporaryregister 2 2 2 2 3tn Textureregister 1 2 3 3 1vn Colorregister 1 2 2 2 2

Forexample,thecolorregistersforalmostallversionshaveareadportlimitof

Page 50: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

two.Thismeansthatasingleinstructioncanuseamaximumoftwodifferentcolorregisters(v0andv1forinstance)assourceregisters.Thisexampleshowstwocolorregistersbeingusedinthesameinstruction.Asshowninthetable,twocolorregisterscanbeusedineveryversionexcept1.0.

madr0,v0,v1,v1//Thisisvalidforversions1.1,1.2,1.3,1.4.

Anyvaliddestinationregistercanbeusedinthesameinstructionbecausereadportcountrestrictionsdonotaffectdestinationregisters.

Destinationregistersareindependentofthereadportcountrestrictions.

Forco-issuedinstructions,themaximumnumberofdifferentregisters(ofthesametype)thatcanbeusedacrosstwoco-issuedinstructionsisthree.Thisistrueforallshaderversions.

Read-only,Read/Write

Theregistertypesareidentifiedaccordingtoread-only(RO)capabilityorread/write(RW)capabilityinthefollowingtable.Read-onlyregisterscanbeusedonlyassourceregistersinaninstruction;theycanneverbeusedasadestinationregister.

Registername Type Versions1.0 1.1 1.2 1.3 1.4

cn Constantregister RO RO RO RO ROrn Temporaryregister RW RW RW RW RWtn Textureregister Seefollowingnote RW RW RW ROvn Colorregister RO RO RO RO RO

RegistersthatareRWcapablecanbeusedtostoreintermediateresults.Thisincludesthetemporaryregistersandtextureregistersforsomeoftheshaderversions.

Note

Forpixelshaderversion1.0,textureregistersareRWfortextureaddressing

Page 51: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

instructions,butROforarithmeticinstructions.Forpixelshaderversion1.4,textureregistersareROfortextureaddressinginstructions,andtextureregisterscanbeneitherreadfromnorwrittentobyarithmeticinstructions.Also,becausetextureregistershavebecometexturecoordinateregisters,havingROaccessisnotaregressionofpreviousfunctionality.

Range

Therangeisthemaximumandminimumregisterdatavalue.Therangesvarybasedonthetypeofregister.TherangesforsomeoftheregisterscanbequeriedfromthedevicecapsusingGetDeviceCaps.

Registername Type Range Versions

cnConstantregister -1to+1 All

versions

rnTemporaryregister

-MaxPixelShaderValueto+MaxPixelShaderValue

Allversions

tnTextureregister

-MaxPixelShaderValueto+MaxPixelShaderValue 1.0to1.3

-MaxTextureRepeatto+MaxTextureRepeat 1.4

vn Colorregister 0to+1 Allversions

Earlypixelshaderhardwarerepresentsdatainregistersusingafixed-pointnumber.Thislimitsprecisiontoamaximumofapproximatelyeightbitsforthefractionalpartofanumber.Keepthisinmindwhendesigningashader.

Forpixelshaderversion1.0to1.3,MaxTextureRepeatmustbeaminimumofone.For1.4,MaxTextureRepeatmustbeaminimumofeight.

Page 52: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 53: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Modifiers

Modifiersareusedtomodifyinstructions,sourceregisters,anddestinationregisters.

InstructionmodifiersSourceregistermodifiersSourceregisterselectorsDestinationregisterwritemasks

TextureRegisterModifiers

Pixelshaderversion1.4includestwonewinstructions,texldandtexcrd,whichcontaincustomregistermodifierfunctionality.Theseinstructionssupportdifferentregistermodifiers,registerselectors,andregisterwritemasks.Formoreinformation,seeTextureRegisterModifiers.

Page 54: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 55: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXConvertMeshSubsetToStripsConvertthespecifiedmeshsubsetintoaseriesofstrips.

HRESULTD3DXConvertMeshSubsetToStrips(

LPD3DXBASEMESHMeshIn,

DWORDAttribId,

DWORDIBOptions,

LPDIRECT3DINDEXBUFFER8*ppIndexBuffer,

DWORD*pNumIndices,

LPD3DXBUFFER*ppStripLengths,

DWORD*pNumStrips,

);

Parameters

MeshIn[in]PointertoaID3DXBaseMeshinterface,representingthemeshtoconverttostrips.

AttribId[in]AttirbuteIDofthemeshsubsettoconverttostrips.

IBOptions[in]AcombinationofoneormoreflagsfromtheD3DXMESHenumeration,specifyingoptionsforthecreateindexbuffer.

ppIndexBuffer[out]PointertoanID3DXBufferobject,representingtheindexbuffercontainingthestrips.

pNumIndices[out]NumberofindicesinthebufferreturnedintheppIndexBufferparameter.

ppStripLengths[out]BuffercontaininganarrayofoneDWORDperstrip,intheindexbufferthatspecifiesthelengthofthatstrip.

pNumStrips[out]Numberofindividualstripsintheindexbufferandcorrespondingstriplengtharray.

ReturnValues

Page 56: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Ifthefunctionsucceeds,thereturnvalueisD3D_OK.

Ifthefunctionfails,thereturnvaluecanbeoneofthefollowingvalues.

D3DERR_INVALIDCALLE_OUTOFMEMORY

Requirements

Header:DeclaredinD3dx8mesh.h.ImportLibrary:UseD3dx8.lib.

Page 57: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 58: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXConvertMeshSubsetToSingleStripConvertsthespecifiedmeshsubsetintoasingletrianglestrip.

HRESULTD3DXConvertMeshSubsetToSingleStrip(

LPD3DXBASEMESHMeshIn,

DWORDAttribId,

DWORDIBOptions,

LPDIRECT3DINDEXBUFFER8*ppIndexBuffer,

DWORD*pNumIndices

);

Parameters

MeshIn[in]PointertoaID3DXBaseMeshinterface,representingthemeshtoconverttoastrip.

AttribId[in]AttirbuteIDofthemeshsubsettoconverttostrips.

IBOptions[in]AcombinationofoneormoreflagsfromtheD3DXMESHenumeration,specifyingoptionsforthecreateindexbuffer.

ppIndexBuffer[out]PointertoanID3DXBufferobject,representingtheindexbuffercontainingthestrip.

pNumIndices[out]NumberofindicesinthebufferreturnedintheppIndexBufferparameter.

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisD3D_OK.

Ifthefunctionfails,thereturnvaluecanbeoneofthefollowingvalues.

D3DERR_INVALIDCALLE_OUTOFMEMORY

Page 59: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Requirements

Header:DeclaredinD3dx8mesh.h.ImportLibrary:UseD3dx8.lib.

Page 60: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 61: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

OptimizedMeshSample

Description

TheOptimizedMeshsampleillustrateshowtoloadandoptimizeafile-basedmeshusingtheMicrosoft®Direct3DXmeshutilityfunctions.

FormoreinformationonDirect3DX,refertotheMicrosoft®DirectX®SDKdocumentation.

Path

Source:(SDKroot)\Samples\Multimedia\Direct3D\OptimizedMesh

Executable:(SDKroot)\Samples\Multimedia\Direct3D\Bin

User'sGuide

Thefollowingtableliststhekeysthatareimplemented.Youcanusemenucommandsforthesamecontrols.

Key ActionENTER Startsandstopsthescene.SPACEBAR Advancesthescenebyasmallincrement.

F2 Promptstheusertoselectanewrenderingdeviceordisplaymode.

ALT+ENTER Togglesbetweenfull-screenandwindowedmodes.ESC Exitstheapplication.CTRL-O Opensmeshfile.CTRL-M Togglesoptimizedmesh.

ProgrammingNotes

ManyMicrosoftDirect3D®samplesintheDirectXSDKusefile-basedmeshes.However,theOptimizedMeshsampleisagoodexampleofthebasiccode

Page 62: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

necessaryforloadingamesh.TheD3DXmeshloadingfunctionalitycollapsestheframehierarchyofan.xfileintoonemesh.

Forothersamples,thebarebonesD3DXmeshfunctionalityiswrappedinacommonclassCD3DMesh.Ifyouwanttokeeptheframehierarchy,youcanusethecommonclassCD3DFile.

ThissampleusescommonDirectXcodethatconsistsprogrammingelementssuchashelperfunctions.ThiscodeissharedwithothersamplesintheDirectXSDK.Youcanfindthecommonheadersandsourcecodein(SDKroot)\Samples\Multimedia\Common.

Page 63: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 64: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXSplitMeshSplitsameshintomeshessmallerthanthespecifiedsize.

HRESULTD3DXSplitMesh(

CONSTLPD3DXMESHpMeshIn,

CONSTDWORD*pAdjacencyIn,

CONSTDWORDMaxSize,

CONSTDWORDOptions,

DWORD*pMeshesOut,

LPD3DXBUFFER*ppMeshArrayOut,

LPD3DXBUFFER*ppAdjacencyArrayOut,

LPD3DXBUFFER*ppFaceRemapArrayOut,

LPD3DXBUFFER*ppVertRemapArrayOut,

);

Parameters

pMeshIn[in]PointertoanID3DXMeshinterface,representingthesourcemesh.

pAdjacencyIn[in]PointertoanarrayofthreeDWORDsperfacethatspecifythethreeneighborsforeachfaceinthemeshtobesimplified.

MaxSize[in]Maximumnumberofverticesorfacesinthenewmesh.

Options[in]Optionflagsforthenewmeshes.

pMeshesOut[out,retval]Numberofmeshesreturned.

ppMeshArrayOut[out,retval]BuffercontaininganarrayofID3DXMeshinterfacesforthenewmeshes.

ppAdjacencyArrayOut[out,retval]Buffercontaininganarrayofadjacencyarraysforthenewmeshes.Thisparameterisoptional.SetittoNULLifitisunused.

ppFaceRemapArrayOut[out,retval]Buffercontaininganarrayoffaceremaparraysforthenewmeshes.Thisparameterisoptional.SetittoNULLifitisunused.

Page 65: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ppVertRemapArrayOut[out,retval]Buffercontaininganarrayofvertexremaparraysforthenewmeshes.Thisparameterisoptional.SetittoNULLifitisunused.

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisD3D_OK.

Ifthefunctionfails,thereturnvaluecanbeoneofthefollowingvalues.

D3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Requirements

Header:DeclaredinD3dx8mesh.h.ImportLibrary:UseD3dx8.lib.

Page 66: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 67: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXComputeTangentComputesapervertexcoordinatesystembasedontexturecoordinategradients.

HRESULTD3DXComputeTangent(

LPD3DXMESHInMesh,

DWORDTexStage,

LPD3DXMESHOutMesh,

DWORDTexStageUVec,

DWORDTexStageVVec,

DWORDWrap,

DWORD*pAdjacency

);

Parameters

InMesh[in]PointertoanID3DXMeshinterface,representingtheinputmesh.

TexStage[in]Texturecoordinatesetininputmeshtouseforgradients.

OutMesh[out]PointertoanID3DXMeshinterface,representingthereturnedmesh.

TexStageUVec[in]TexturecoordinatesetinoutputmeshtoreceiveUtangentvector.SetthisvaluetoD3DX_COMP_TANGENT_NONEifyoudonotwanttogenerateaUtangentvector.

TexStageVVec[in]TexturecoordinatesetinoutputmeshtoreceiveVtangentvector.SetthisvaluetoD3DX_COMP_TANGENT_NONEifyoudonotwanttogenerateaVtangentvector.

Wrap[in]Setthisvalueto0fornowrappingor1towrapintheUandVdirections.

pAdjacency[out]PointertoanarrayofthreeDWORDsperfacethatspecifythethreeneighborsforeachfaceinthecreatedmesh.

ReturnValues

Page 68: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Ifthefunctionsucceeds,thereturnvalueisD3D_OK.

Ifthefunctionfails,thereturnvaluecanbeoneofthefollowingvalues.

D3DERR_INVALIDCALLE_OUTOFMEMORY

Remarks

SettingbothTexStageVVecandTexStageWVectoD3DX_COMP_TANGENT_NONEwillcausethismethodtofail,sinceithasnothingtodo.

Requirements

Header:DeclaredinD3dx8mesh.h.ImportLibrary:UseD3dx8.lib.

Page 69: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 70: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXComputeNormalMapConvertsaheightmapintoanormalmap.The(x,y,z)componentsofeachnormalaremappedtothe(r,g,b)channelsoftheoutputtexture.

HRESULTD3DXComputeNormalMap(

LPDIRECT3DTEXTURE8pTexture,

LPDIRECT3DTEXTURE8pSrcTexture,

CONSTPALETTEENTRY*pSrcPalette,

DWORDFlags,

DWORDChannel,

FLOATAmplitude

);

Parameters

pTexture[out,retval]PointertoanIDirect3DTexture8interface,representingthedestinationtexture.

pSrcTexture[in,retval]PointertoanIDirect3DTexture8interface,representingthesourceheight-maptexture.

pSrcPalette[in]PointertoaPALETTEENTRYtypethatcontainsthesourcepaletteof256colorsorNULL.

Flags[in]OneormoreD3DX_NORMALMAPflagsthatcontrolgenerationofnormalmaps.

Channel[in,out]OneD3DX_CHANNELflagspecifyingthesourceofheightinformation.

Amplitude[in]Constantvaluebywhichtheheightinformationismultiplied.

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisD3D_OK.

Page 71: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Ifthefunctionfails,thereturnvaluecanbethefollowingvalue.

D3DERR_INVALIDCALL

Remarks

Thismethodcomputesthenormalbyusingthecentraldifferencewithakernelsizeof3×3.RGBchannelsinthedestinationcontainbiased(x,y,z)componentsofthenormal.

Requirements

Header:DeclaredinD3dx8tex.h.ImportLibrary:UseD3dx8.lib.

Page 72: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 73: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ID3DXEffectThemethodsfromtheID3DXTechniqueinterfacehavebeenmovedintotheID3DXEffectinterfaceforMicrosoft®DirectX®8.1.

TheID3DXEffectinterfaceisusedtosetandqueryeffects,andtochoosetechniques.Aneffectobjectcancontainmultipletechniquestorenderthesameeffect.

TheID3DXEffectinterfaceisobtainedbycallingD3DXCreateEffectorD3DXCreateEffectFromFile.ThemethodsoftheID3DXEffectinterfacecanbeorganizedintothefollowinggroups.

Copying CloneEffectGetCompiledEffect

EffectParameters

SetDwordSetFloatSetMatrixSetPixelShaderSetStringSetTextureSetVectorSetVertexShader

EffectParameterInformation

GetDwordGetFloatGetMatrixGetParameterDescGetPixelShaderGetStringGetTextureGetVectorGetVertexShaderGetDesc

Page 74: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Information GetDeviceGetPassDesc

Techniques

FindNextValidTechniqueGetTechniqueGetTechniqueDescSetTechniqueValidate

TechniqueApplicationBeginEndPass

Miscellaneous OnLostDeviceOnResetDevice

TheID3DXEffectinterface,likeallCOMinterfaces,inheritsfromtheIUnknownInterface.

TheLPD3DXEFFECTtypeisdefinedasapointertotheID3DXEffectinterface.

typedefstructID3DXEffect*LPD3DXEFFECT;

Requirements

Header:DeclaredinD3dx8effect.h.ImportLibrary:UseD3dx8.lib.

SeeAlso

D3DXCreateEffect,D3DXCreateEffectFromFile,D3DXCreateEffectFromResource

Page 75: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 76: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXSaveSurfaceToFileSavesasurfacetoafile.

HRESULTD3DXSaveSurfaceToFile(

LPCTSTRpDestFile,

D3DXIMAGE_FILEFORMATDestFormat,

LPDIRECT3DSURFACE8pSrcSurface,

CONSTPALETTEENTRY*pSrcPalette,

CONSTRECT*pSrcRect

);

Parameters

pDestFile[in]Filenametosavethesurfaceto.

DestFormat[in]D3DXIMAGE_FILEFORMATspecifyingfileformattousewhensaving.

pSrcSurface[in]PointertoIDirect3DSurface8interface,containingtheimagetobesaved.

pSrcPalette[in]PointertoaPALETTEENTRYstructurecontainingapaletteof256colors.ThisparametercanbeNULL.

pSrcRect[in]PointertoaRECTstructure.Specifiesthesourcerectangle.SetthisparametertoNULLtospecifytheentireimage.

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisD3D_OK.

Ifthefunctionfails,thereturnvaluecanbethefollowing.

D3DERR_INVALIDCALL

Page 77: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Remarks

Thisfunctionsupportsthefollowingfileformats:.bmpand.dds.

Thisfunctionhandlesconversiontoandfromcompressedtextureformats.

ThisfunctionsupportsbothUnicodeandANSIstrings.

Requirements

Header:DeclaredinD3dx8tex.h.ImportLibrary:UseD3dx8.lib.

SeeAlso

D3DXSaveTextureToFile,D3DXSaveVolumeToFile

Page 78: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 79: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXFillTextureUsesauser-providedfunctiontofilleachtexelofeachmiplevelofagiventexture.

HRESULTD3DXFillTexture(

LPDIRECT3DTEXTURE8pTexture,

LPD3DXFILL2DpFunction,

LPVOIDpData

);

Parameters

pTexture[out,retval]PointertoanIDirect3DTexture8interface,representingthefilledtexture.

pFunction[in]PointertoaLPD3DXFILL2Duser-providedevaluatorfunction,whichwillbeusedtocomputethevalueofeachtexel.

pData[in]Pointertoanarbitraryblockofuser-defineddata.ThispointerwillbepassedtothefunctionprovidedinpFunction.

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisD3D_OK.

Ifthefunctionfails,thereturnvaluecanbethefollowingvalues.

D3DERR_INVALIDCALL

Requirements

Header:DeclaredinD3dx8tex.h.ImportLibrary:UseD3dx8.lib.

Page 80: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 81: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXFillCubeTextureUsesauser-providedfunctiontofilleachtexelofeachmiplevelofagivencubetexture.

HRESULTD3DXFillCubeTexture(

LPDIRECT3DCUBETEXTURE8pTexture,

LPD3DXFILL3DpFunction,

LPVOIDpData

);

Parameters

pTexture[out,retval]PointertoanIDirect3DCubeTexture8interface,representingthefilledtexture.

pFunction[in]PointertoaLPD3DXFILL3Duser-providedevaluatorfunction,whichwillbeusedtocomputethevalueofeachtexel.

pData[in]Pointertoanarbitraryblockofuser-defineddata.ThispointerwillbepassedtothefunctionprovidedinpFunction.

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisD3D_OK.

Ifthefunctionfails,thereturnvaluecanbeoneofthefollowingvalues.

D3DERR_INVALIDCALL

Requirements

Header:DeclaredinD3dx8tex.h.ImportLibrary:UseD3dx8.lib.

Page 82: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 83: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXFillVolumeTextureUsesauser-providedfunctiontofilleachtexelofeachmiplevelofagiventexture.

HRESULTD3DXFillVolumeTexture(

LPDIRECT3DVOLUMETEXTURE8pVolumeTexture,

LPD3DXFILL3DpFunction,

LPVOIDpData

);

Parameters

pVolumeTexture[out,retval]PointertoanIDirect3DVolumeTexture8interface,representingthefilledtexture.

pFunction[in]PointertoanLPD3DXFILL3Duser-providedevaluatorfunction,whichwillbeusedtocomputethevalueofeachtexel.

pData[in]Pointertoanarbitraryblockofuser-defineddata.ThispointerwillbepassedtothefunctionprovidedinpFunction.

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisD3D_OK.

Ifthefunctionfails,thereturnvaluecanbethefollowingvalue.

D3DERR_INVALIDCALL

Remarks

Ifthevolumeisnondynamic(becauseofausageparametersetto0atthecreation)andlocatedinvideomemory(thememorypoolsettoD3DPOOL_DEFAULT),D3DXFillVolumeTexturewillfailbecauseDirect3DX

Page 84: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

cannotlocknondynamicvolumeslocatedinvideomemory.

Requirements

Header:DeclaredinD3dx8tex.h.ImportLibrary:UseD3dx8.lib.

Page 85: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 86: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXQuaternionSquadSetupSetupcontrolpointsforsphericalquadrangleinterpolation.

voidD3DXQuaternionSquadSetup(

D3DXQUATERNION*pAOut,

D3DXQUATERNION*pBOut,

D3DXQUATERNION*pCOut,

CONSTD3DXQUATERNION*pQ0,

CONSTD3DXQUATERNION*pQ1,

CONSTD3DXQUATERNION*pQ2,

CONSTD3DXQUATERNION*pQ3

);

Parameters

pAOut[out]PointertoAOut.

pBOut[out]PointertoBOut.

pCOut[out]PointertoCOut.

pQ0[in]Pointertotheinputcontrolpoint,Q0.

pQ1[in]Pointertotheinputcontrolpoint,Q1.

pQ2[in]Pointertotheinputcontrolpoint,Q2.

pQ3[in]Pointertotheinputcontrolpoint,Q3.

Remarks

Thisfunctionoperatesasshownbelow.Ittakesfourcontrolpoints(Q0,Q1,Q2,Q3),whicharesuppliedtotheinputspQ0,pQ1,pQ2,andpQ3.Thefunctionthenaltersthesevaluestofindacurvethatflowsalongtheshortestpath.Thevaluesofq0,q2,andq3arecalculatedasshownbelow.

Page 87: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

q0=|Q0+Q1|<|Q0-Q1|?-Q0:Q0

q2=|Q1+Q2|<|Q1-Q2|?-Q2:Q2

q3=|Q2+Q3|<|Q2-Q3|?-Q3:Q3

HavingcalculatedthenewQvalues,thevaluesforAOut,BOut,andCOutarecalculatedasshownbelow.

AOut=q1*e[-0.25*(Ln[Exp(q1)*q2]+Ln[Exp(q1)*q0])]

BOut=q2*e[-0.25*(Ln[Exp(q2)*q3]+Ln[Exp(q2)*q1])]

COut=q2

Note:

LnistheAPImethodD3DXQuaternionLn

ExpistheAPImethodD3DXQuaternionExp

Example

Thefollowingexampleshowshowtouseasetofquaternionkeys(Q0,Q1,Q2,Q3)tocomputetheinnerquadranglepoints(A,B,C).Thisensuresthatthetangentsarecontinuousacrossadjacentsegments.

AB

Q0Q1Q2Q3

ThisishowyoucaninterpolatebetweenQ1andQ2.

//rotationaboutthezaxis

D3DXQUATERNIONQ0=D3DXQUATERNION(0,0,0.707f,-.707f);

D3DXQUATERNIONQ1=D3DXQUATERNION(0,0,0.000f,1.000f);

D3DXQUATERNIONQ2=D3DXQUATERNION(0,0,0.707f,0.707f);

D3DXQUATERNIONQ3=D3DXQUATERNION(0,0,1.000f,0.000f);

D3DXQUATERNIONA,B,C,Qt;

FLOATtime=0.5f;

D3DXQuaternionSquadSetup(&A;,&B;,&C;,&Q0;,&Q1;,&Q2;,&Q3;);

D3DXQuaternionSquad(&Qt;,&Q1;,&A;,&B;,&C;,time);

Note:

Cis+/-Q2dependingontheresultofthefunction

Qtistheresultofthefunction

Theresultisarotationof45degreesaroundthezaxisfortime=0.5.

Requirements

Page 88: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Header:DeclaredinD3dx8math.h.ImportLibrary:UseD3dx8.lib.

SeeAlso

D3DXQuaternionSquad

Page 89: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 90: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXQuaternionSquadInterpolatesbetweenquaternions,usingsphericalquadrangleinterpolation.

D3DXQUATERNION*D3DXQuaternionSquad(

D3DXQUATERNION*pOut,

CONSTD3DXQUATERNION*pQ1,

CONSTD3DXQUATERNION*pA,

CONSTD3DXQUATERNION*pB,

CONSTD3DXQUATERNION*pC,

FLOATt

);

Parameters

pOut[in,out]PointertotheD3DXQUATERNIONstructurethatistheresultoftheoperation.

pQ1[in]PointertoasourceD3DXQUATERNIONstructure.

pA[in]PointertoasourceD3DXQUATERNIONstructure.

pB[in]PointertoasourceD3DXQUATERNIONstructure.

pC[in]PointertoasourceD3DXQUATERNIONstructure.

t[in]Parameterthatindicateshowfartointerpolatebetweenthequaternions.

ReturnValues

PointertoaD3DXQUATERNIONstructurethatistheresultofthesphericalquadrangleinterpolation.

Remarks

Thisfunctionusesthefollowingsequenceofsphericallinearinterpolation

Page 91: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

operations:Slerp(Slerp(pQ1,pC,t),Slerp(pA,pB,t),2t(1-t))

ThereturnvalueforthisfunctionisthesamevaluereturnedinthepOutparameter.Inthisway,theD3DXQuaternionSquadfunctioncanbeusedasaparameterforanotherfunction.

Requirements

Header:DeclaredinD3dx8math.h.ImportLibrary:UseD3dx8.lib.

SeeAlso

D3DXQuaternionExp,D3DXQuaternionLn,D3DXQuaternionSquadSetup

Page 92: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 93: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXMatrixMultiplyTransposeDeterminestheproductoftwomatrices,followedbyatranspose.

D3DXMATRIX*D3DXMatrixMultiplyTranspose(

D3DXMATRIX*pOut,

CONSTD3DXMATRIX*pM1,

CONSTD3DXMATRIX*pM2

);

Parameters

pOut[in,out]PointertotheD3DXMATRIXstructurethatistheresultoftheoperation.

pM1[in]PointertoasourceD3DXMATRIXstructure.

pM2[in]PointertoasourceD3DXMATRIXstructure.

ReturnValues

PointertoaD3DXMATRIXstructurethatistheproductoftwomatrices.

Remarks

TheresultrepresentsthetransformationM2,followedbythetransformationM1,tranposedbyT(Out=T(M1*M2)).

ThereturnvalueforthisfunctionisthesamevaluereturnedinthepOutparameter.Inthisway,theD3DXMatrixMultiplyTransposefunctioncanbeusedasaparameterforanotherfunction.

Thisfunctionisusefultosetmatricesasconstantsforvertexandpixelshaders.

Requirements

Page 94: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Header:DeclaredinD3dx8math.h.ImportLibrary:UseD3dx8.lib.

SeeAlso

D3DXMatrixMultiply,D3DXQuaternionMultiply

Page 95: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 96: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXFresnelTermCalculatetheFresnelterm.

FLOATD3DXFresnelTerm(

FLOATCosTheta,

FLOATRefractionIndex,

);

Parameters

CosTheta[in]Thevaluemustbebetween0and1.

RefractionIndex[in]therefractionindexofamaterial.Thevaluemustbegreaterthan1.

ReturnValues

ThisfunctionreturnstheFresneltermforunpolarizedlight.CosThetaisthecosineoftheincidentangle.

Requirements

Header:DeclaredinD3dx8math.h.ImportLibrary:UseD3dx8.lib.

Page 97: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 98: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SamplesDirectXGraphicsC/C++Samples

ThefollowingsamplesarebuiltonabaseclassthatincludesMicrosoft®Windows®andMicrosoft®Direct3D®functionality.ThisbaseclassprovidesmanyofthebasicfeaturesinaWindowsapplication,suchascreatingwindowsandhandlingmessages.ThesamplesincludeaderivedclassthatoverridesthemethodsnecessarytoaddDirect3Dfeatures,suchasbumpmaps,vertexblending,andvolumetextures.Formoreinformationaboutthesamplearchitecture,seeSampleFramework.

BillboardSampleBumpEarthSampleBumpLensSampleBumpUnderwaterSampleBumpWavesSampleBumpSelf-ShadowSampleClipMirrorSampleCubeMapSampleCullSampleDolphinVSSampleDotProduct3SampleDXTexToolEmbossSampleEnhancedMeshSampleFishEyeSampleLightingSampleMFCFogSampleMFCPixelShaderSampleMFCTexSampleMoireSampleOptimizedMeshSamplePickSamplePointSpritesSampleProgressiveMeshSample

Page 99: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

RTPatchSampleShadowVolumeSampleSkinnedMeshSampleSphereMapSampleStencilDepthSampleStencilMirrorSampleText3DSampleVertexBlendSampleVertexShaderSampleVolumeFogSampleVolumeTextureSampleWaterSample

TheApplicationWizardisavailabletohelpgenerateMicrosoft®DirectX®applications.

AlthoughDirectXsamplesincludeMicrosoft®VisualC++®projectworkspacefiles,youmightneedtoverifyothersettingsinyourdevelopmentenvironmenttoensurethatthesamplescompileproperly.Formoreinformation,seeCompilingDirectXSamplesandOtherDirectXApplications.

SeeAlso

DirectXGraphicsC/C++Tutorials

Page 100: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 101: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DirectXGraphicsThissectionprovidesinformationaboutusingtheMicrosoft®DirectX®Graphicsapplicationprogramminginterfaces(APIs).

AswithothercomponentsofDirectX,DirectXGraphicscanbeusedwithC,C++,andMicrosoft®VisualBasic®.

Page 102: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

RoadmapDiscoverthefeaturesofMicrosoft®DirectX8.1®inthreeways.

What'sNewinDirectXGraphics

ThissectionhighlightsnewfeaturesandfunctionalityofthiscomponentinDirectX8.1.IfyouhaveusedMicrosoft®Direct3D®orMicrosoft®DirectDraw®before,readthissectionfirstbecausemuchhaschangedsinceDirectX7.0.

ProgrammersGuide

Thissectioncontainsarchitecturedescriptions,functionalblockdiagrams,descriptionsofthebuildingblocksinthepipeline,codesnippets,andsampleapplications.

Reference

ThissectioncontainsthereferencepagesfortheDirect3Dapplicationprogramminginterface(API).ThisincludesthesyntaxfortheAPImethods,functions,instructions,anddatastructures.ItincludesanexplanationofhowtheAPImethodworks,andoftenincludescodesnippets.

Page 103: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 104: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ReferenceThissectioncontainsthereferencepagesfortheMicrosoft®Direct3D®applicationprogramminginterface(API).Informationiscontainedinthefollowingsections.

Direct3DC/C++Reference

Direct3DXC/C++Reference

VertexShaderReference

PixelShaderReference

EffectFileReferenceXFileC/C++Reference

Page 105: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 106: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ProgrammersGuideThisguidecontainsadescriptionofthegraphicspipelineimplementedbyMicrosoft®Direct3D®.Itisaguidefordeveloperswhoareimplementingthree-dimensional(3-D)graphicsfunctionalityintotheirapplications.Theguidecontainsarchitecturedescriptions,functionalblockdiagrams,anddescriptionsofthebuildingblocksinthepipeline,aswellascodesnippetsandsampleapplications.Theinformationisdividedintothefollowingsections:

GettingStartedwithDirect3D

Thissectioncontainsbothanoverviewofthepipelineandtutorialsthatcanhelpyougetasimplegraphicsapplicationrunninginafewminutes.

UsingDirect3D

Thissectionexplainshowtousethefixedfunctionpipeline.Includedherearethebasicfunctionalstepsinthegraphicspipeline:convertinggeometry,addinglighting,andrenderingoutput.

ProgrammablePipeline

Thissectioncoversthenewprogrammableextensionstothepipeline.Includedherearedetailsaboutusingvertexshadersformanipulatingobjectgeometry,pixelshadersforcontrollingpixelshading,andeffectsandeffectfilesforbuildingapplicationsthatcanrunonavarietyofhardwareplatforms.

AdvancedTopics

Thissectioncontainsexamplesofdifferenttypesofspecialeffectsyoucanimplement.Topicssuchasenvironmentandbumpmapping,antialiasing,vertexblending,andtweeningshowhowtoapplyleading-edgespecialeffectstoyourapplication.

Samples

Thissectioncontainssampleapplications.

Page 107: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Direct3DAppendix

Thissectioncontainsdetailsonadditionaltopics,suchasXFilesandgraphicsstate.

FormoreinformationaboutspecificAPImethods,seetheReferencepages.

Page 108: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(shaderversions1.0,1.1)

Page 109: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

VertexShaders

PrevioustoMicrosoft®DirectX®8.n,Microsoft®Direct3D®operatedafixedfunctionpipelineforconvertingthree-dimensional(3-D)geometrytorenderedscreenpixels.TheusersetsattributesofthepipelinethatcontrolhowDirect3Dtransforms,lights,andrenderspixels.Thefixedfunctionvertexformatisdeclaredatcompiletimeanddeterminestheinputvertexformat.Oncedefined,theuserhaslittlecontroloverpipelinechangesduringruntime.

Programmableshadersaddanewdimensiontothegraphicspipelinebyallowingthetransform,lighting,andrenderingfunctionalitytobemodifiedatruntime.Ashaderisdeclaredatruntimebut,oncedone,theuserisfreetochangewhichshaderisactiveaswellastocontroltheshaderdatadynamicallyusingstreamingdata.Thisgivestheuseranewlevelofdynamicflexibilityoverthewaythatpixelsarerendered.

Avertexshaderfilecontainsvertexshaderinstructions.Vertexshaderscancontrolvertexcolorandhowtexturesareappliedtovertices.Lightingcanbeaddedthroughtheuseofvertexshaderinstructions.TheshaderinstructionfilecontainsASCIItextsoitisreadableandinsomewayslookssimilartoassemblylanguage.AvertexshaderisinvokedafteranyDrawPrimitiveorDrawIndexedPrimitivecall.ShaderscanbedynamicallyswitchedusingSetVertexShadertospecifyanewshaderfile,orbychangingtheinstructionsintheASCIItextshaderfileusingthestreamingdatainputs.TheVertexShaderAssemblerReferencehasacompletelistingofshaderinstructions.

Foradditionalinformation,seethefollowingsections.

CreateaVertexShader

Thissectioncontainsacodesamplethatusesavertexshadertoapplyaconstantcolortoobjectvertices.Thisexamplecontainsadetailedexplanationofthemethodsused.

Shader2-Applyvertexcolors

Additionalexamplesshowsmorecodesamplesthataddtexturesandblendvertexcolorsandtextures.

Page 110: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Shader3-Applyatexturemap

Additionalexamplesshowsmorecodesamplesthataddtexturesandblendvertexcolorsandtextures.

Shader4-Applyatexturemapwithlighting

Additionalexamplesshowsmorecodesamplesthataddtexturesandblendvertexcolorsandtextures.

Debugging

Page 111: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 112: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

PixelShaders

BeforeMicrosoft®DirectX®8.x,Microsoft®Direct3D®usedafixedfunctionpipelineforconvertingthree-dimensional(3-D)geometrytorenderedscreenpixels.TheusersetsattributesofthepipelinethatcontrolhowDirect3Dtransforms,lights,andrenderspixels.Thefixedfunctionvertexformatisdeclaredatcompiletimeanddeterminestheinputvertexformat.Oncedefined,theuserhaslittlecontroloverpipelinechangesduringruntime.

Shadersaddanewdimensiontothegraphicspipelinebyallowingthevertextransform,lighting,andindividualpixelcoloringfunctionalitytobeprogrammed.Pixelshadersareshortprogramsthatexecuteforeachpixelwhentrianglesarerasterized.Thisgivestheuseranewlevelofdynamicflexibilityoverthewaythatpixelsarerendered.

ApixelshadercontainspixelshaderinstructionsmadeupofASCIItext.Arithmeticinstructionscanbeusedtoapplydiffuseand/orspecularcolor.Textureaddressinginstructionsprovideavarietyofoperationsforreadingandapplyingtexturedata.Functionalityisavailableformaskingandswappingcolorcomponents.TheshaderASCIItextlookssimilartoassemblylanguageandisassembledusingDirect3DXassemblerfunctionsfromeitheratextstringorafile.TheassembleroutputisaseriesofopcodesthatanapplicationmayprovidetoDirect3DbymeansofIDirect3DDevice8::CreatePixelShader.ThePixelShaderReferencehasacompletelistingofshaderinstructions.

Tounderstandmoreaboutpixelshaders,seethefollowingsections.

CreateaPixelShadercontainsacodesamplethatusesapixelshadertoapplyGouraudinterpolateddiffusecolorstoanobject.Thisexamplecontainsadetailedexplanationofthemethodsused.TextureConsiderationsdetailsthetexturestagestatesthatareignoredduringpixelshaders.ConfirmingPixelShaderSupportgivesamoredetailedexplanationofthestructuresforenumeratingpixelshadersupport.PixelShaderExamplesshowsmorecodesamplesthataddtexturesandblendvertexcolorsandtextures.ConvertingTextureOperationsgivesexamplesofconvertingtextureoperationstopixelshaderinstructions.

Page 113: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Debuggingprovidesdebugginginformation.

Page 114: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 115: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

EffectsMicrosoft®Direct3D®providesarichfeaturesetforcreatingcomplexandvisuallyrealisticthree-dimensional(3-D)scenes.Effectfileshelpyouwriteanapplicationthatusesalltherenderingcapabilitiesforthehardwareonwhichitruns.Effectsareacollectionofdifferentrenderingtechniquesthatcanfitontoavarietyofhardwaredevices.

Forexample,tocreatearealisticrippledpondofwaterthatreflectslightasshowninthefollowingimage,youbeginwiththefirsttechniquethatrendersthewater,addsspecularhighlights,addscaustictextures,andapplieslighttothewaterinasinglepass.Ifyourhardwarecannotrenderthistechniqueinasinglepass,asecondtechniquemightrenderthewater,addspecularhighlightsorcaustictextures,butnotapplylighttothewater.

Beforeyouuseatechnique,youcanvalidateitusingDirect3Dtoseeifitissupportedbythecurrenthardwareconfiguration.

Effectsaredefinedinaneffectfile.Aneffectfileconsistsofoneormoretechniques.Eachtechniqueconsistsofoneormorepasses.Thesefilesaretextbasedandcanbechangedwithoutrecompilingthesourceapplication.Thisenablesyoutoprogramgamesthatmakeoptimumuseofvideocardfunctionality.Effectfilesalsomakeiteasytoupgradeanexistinggametorunonnewervideocardsasadditionalfeaturesaredeveloped.

Thefollowingtopicsdiscusseffectsandhowyoucanusetheminyourapplication.

CreateanEffectMultipleTechniques

Page 116: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercises*

*FromtheDirectXMeltdown2001conference,ProgrammableShaderworkshop.

Exercise1-FixedFunctionDiffuseLightingandVertexShaderDiffuseLighting.Exercise2-VertexShaderDiffuseLighting.Lightthemodel,takingbothdiffusematerialandadiffuselightsourceintoconsideration.Exercise3-Transforms.Transformthevertexnormalintoworldspacetotakelightsourcemovementintoconsideration.Exercise4-Texturing.SetuptexturetopassontoFFPSModulatebetweenthetextureanddiffusecolorarguments.Exercise5-VertexShaderSpecularLighting.Exercise6-StandardTextureEffect.Exercise7-Multi-TexturingwithShaders.Exercise8-TexturingwithLights.Exercise9-Dot3BumpMapping,Dot3SpecularBumpMapping,andTableLookupSpecularBumpMapping.Exercise10-AnisotropicBumpMapping.Exercise11-AreaLighting,AreaandDiffuseLighting.

Formoreinformationabouteffectfiles,seeEffectFileFormat.

Page 117: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 118: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MathematicsofLighting

TheMicrosoft®Direct3D®LightModelcoversambient,diffuse,specular,andemissivelighting.Thisisenoughflexibilitytosolveawiderangeoflightingsituations.Yourefertothetotalamountoflightinasceneastheglobalilluminationandcomputeitusingthefollowingequation.

GlobalIllumination=AmbientLight+DiffuseLight+SpecularLight+EmissiveLight

Ambientlightingisconstantlighting.Itisconstantinalldirectionsanditcolorsallpixelsofanobjectthesame.Itisfasttocalculatebutleavesobjectslookingflatandunrealistic.ToseehowambientlightingiscalculatedbyDirect3D,seeAmbientLighting.

Diffuselightingdependsonboththelightdirectionandtheobjectsurfacenormal.Itvariesacrossthesurfaceofanobjectasaresultofthechanginglightdirectionandthechangingsurfacenumeralvector.Ittakeslongertocalculatediffuselightingbecauseitchangesforeachobjectvertex,howeverthebenefitofusingitisthatitshadesobjectsandgivesthemthree-dimensional(3-D)depth.ToseehowdiffuselightingiscalculatedinDirect3D,seeDiffuseLighting.

Specularlightingidentifiesthebrightspecularhighlightsthatoccurwhenlighthitsanobjectsurfaceandreflectsbacktowardthecamera.Itismoreintensethandiffuselightandfallsoffmorerapidlyacrosstheobjectsurface.Ittakeslongertocalculatespecularlightingthandiffuselighting,howeverthebenefitofusingitisthatitaddssignificantdetailtoasurface.ToseehowspecularlightingiscalculatedinDirect3D,seeSpecularLighting.

Emissivelightingislightthatisemittedbyanobject,forexample,aglow.ToseehowemissivelightingiscalculatedinDirect3D,seeEmissiveLighting.

Realisticlightingcanbeaccomplishedbyapplyingeachofthesetypesoflightingtoa3-Dscene.Toachieveamorerealisticlightingeffect,youaddmorelights;however,thescenetakeslongertorender.Toachievealltheeffectsadesignerwants,somegamesusemoreCPUpowerthaniscommonlyavailable.Inthiscase,itistypicaltoreducethenumberoflightingcalculationstoaminimumbyusinglightingmapsandenvironmentmapstoaddlightingtoascenewhileusingtexturemaps.

Page 119: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Alllightingcomputationsaremadeinmodelspacebytransformingthelightsource'spositionanddirection,alongwiththecameraposition,tomodelspaceusingtheinverseoftheworldmatrix.Asaresult,iftheworldorviewmatricesintroducenon-uniformscaling,theresultantlightingmightbeinaccurate.Toseehowlightingtransformationsarecalculated,seeCameraSpaceTransformations.

Diffuseandspecularlightvaluescanbeaffectedbyagivenlight'sattenuationandspotlightcharacteristics.Termsforbothoftheseareincludedinthediffuseandspecularequations.Formoreinformation,seeAttenuationandSpotlightTerms.

Page 120: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 121: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ActionMapping

Traditionally,applicationshavedonetheirownmappingofeventstoparticularbuttonsandaxes.Acar-racinggame,forexample,mightassumethatthex-axisontheuser'sjoystickormousewasthemostsuitablecontrolforsteeringthecar.Theonlywaytoaccommodateneworunusualdeviceswastoprovideconfigurationoptionssothattheusercouldspecifysomeotheraxis,suchasarotationalaxis,touseforsteering.Moreover,theapplicationhadnowayofknowingwhichinstalleddevicewasthebestfitforthegame,sotheusertypicallyhadtochooseadevicefromamenuormakesureonlythepreferreddevicewasattached.

Usingactionmapping,younolongerneedtomakeassumptionsaboutthebestuseofdevicesanddeviceobjects.Instead,yourapplicationbindsactionstovirtualcontrolswhereverpossible.Ratherthangettingdatafromthex-axisandsteeringthecartotheleftortherightaccordingly,theapplicationmightgetdatafromavirtualcontrolcalledDIAXIS_DRIVINGR_STEER.Microsoft®DirectInput®assignsthevirtualcontroltoaphysicalcontrol—thatis,adeviceobject.Itdoessobytakingintoaccounttheapplicationgenre,userpreferences,informationfromthedevicemanufacturer,andtheuser'sconfigurationofthedevice.

Actionmappingalsosimplifiestheinputloopbyreturningdataforalldevicesinaformindependentoftheparticulardevice.Asingleactioncanbemappedtomorethanonedevice,andtheinputloopcanrespondtotheactionthesamewayregardlessofwhichdeviceisbeingread.

Thefollowingtopicscontainmoreinformationonthestepsrequiredtoimplementactionmapping.

PreparingtheActionMapFindingMatchingDevicesConfiguringtheActionMapUserConfigurationoftheDeviceRetrievingActionDataMaintainingFilesDuringDevelopment

Page 122: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 123: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8ApplicationsusethemethodsoftheIDirectInput8interfacetoenumerate,create,andretrievethestatusofMicrosoft®DirectInput®devices,initializetheDirectInputobject,andinvokeaninstanceoftheMicrosoftWindows®ControlPanel.

IDirectInput8supersedestheIDirectInput,IDirectInput2,andIDirectInput7interfacesusedinearlierversionsofMicrosoftDirectX®.

IDirectInput8isaninterfacetoanewclassofobject,representedbytheclassidentifierCLSID_DirectInput8,andcannotbeobtainedbycallingQueryInterfaceonaninterfacetoobjectsofclassCLSID_DirectInput.Instead,obtaintheIDirectInput8interfacebyusingtheDirectInput8Createfunction.

ThemethodsoftheIDirectInput8interfacecanbeorganizedintothefollowinggroups.

DeviceManagement ConfigureDevices CreateDevice EnumDevices EnumDevicesBySemantics FindDevice GetDeviceStatusMiscellaneous Initialize RunControlPanel

TheIDirectInputinterface,likeallCOMinterfaces,inheritstheIUnknowninterfacemethods.TheIUnknowninterfacesupportsthefollowingthreemethods:

IUnknown AddRef QueryInterface Release

Page 124: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

TheLPDIRECTINPUT8typeisdefinedasapointertotheIDirectInput8interface:

typedefstructIDirectInput8*LPDIRECTINPUT8;

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

Page 125: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 126: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DirectInput8CreateCreatesaDirectInput®objectandreturnsanIDirectInput8orlaterinterface.

HRESULTWINAPIDirectInput8Create(

HINSTANCEhinst,

DWORDdwVersion,

REFIIDriidltf,

LPVOID*ppvOut,

LPUNKNOWNpunkOuter

);

Parameters

hinstInstancehandletotheapplicationorDLLthatiscreatingtheDirectInputobject.DirectInputusesthisvaluetodeterminewhethertheapplicationorDLLhasbeencertifiedandtoestablishanyspecialbehaviorsthatmightbenecessaryforbackwardcompatibility.

ItisanerrorforaDLLtopassthehandletotheparentapplication.Forexample,anActiveX®controlembeddedinaWebpagethatusesDirectInputmustpassitsowninstancehandle,andnotthehandletotheWebbrowser.ThisensuresthatDirectInputrecognizesthecontrolandcanenableanyspecialbehaviorsthatmightbenecessary.

dwVersionVersionnumberofDirectInputforwhichtheapplicationisdesigned.ThisvalueisnormallyDIRECTINPUT_VERSION.IftheapplicationdefinesDIRECTINPUT_VERSIONbeforeincludingDinput.h,thevaluemustbegreaterthan0x0700.Forearlierversions,useDirectInputCreateEx,whichisinDinput.lib.

riidltfUniqueidentifierofthedesiredinterface.ForDirectX8.0,thisvalueisIID_IDirectInput8AorIID_IDirectInput8W.PassingtheIID_IDirectInput8defineselectstheANSIorUnicodeversionoftheinterface,dependingonwhetherUNICODEisdefinedduringcompilation.

ppvOut

Page 127: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Addressofapointertoavariabletoreceivetheinterfacepointerifthecallsucceeds.

punkOuterPointertotheaddressofthecontrollingobject'sIUnknowninterfaceforCOMaggregation,orNULLiftheinterfaceisnotaggregated.MostcallerspassNULL.Ifaggregationisrequested,theobjectreturnedin*ppvOutisapointertoIUnknown,asrequiredbyCOMaggregation.

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisDI_OK.

Ifthefunctionfails,thereturnvaluecanbeoneofthefollowingerrorvalues:

DIERR_BETADIRECTINPUTVERSIONDIERR_INVALIDPARAMDIERR_OLDDIRECTINPUTVERSIONDIERR_OUTOFMEMORY

Remarks

TheDirectInputobjectcreatedbythisfunctionisimplementedinDinput8d.dll.VersionsofinterfacesearlierthanDirectX8.0cannotbeobtainedinthisimplementation.Touseearlierversions,createtheDirectInputobjectbyusingDirectInputCreateorDirectInputCreateEx,whichareinDinput.lib.

CallingthefunctionwithpunkOuter=NULLisequivalenttocreatingtheobjectthroughCoCreateInstance(&CLSID_DirectInput8,punkOuter,CLSCTX_INPROC_SERVER,&IID_IDirectInput8W,lplpDirectInput),theninitializingitwithIDirectInput8::Initialize.

CallingthefunctionwithpunkOuter!=NULLisequivalenttocreatingtheobjectthroughCoCreateInstance(&CLSID_DirectInput8,punkOuter,CLSCTX_INPROC_SERVER,&IID_IUnknown,lplpDirectInput).Theaggregatedobjectmustbeinitializedmanually.

Requirements

Page 128: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:Declaredindinput.h.ImportLibrary:Usedinput8.lib.

Page 129: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 130: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DIJOYSTATEDescribesthestateofajoystickdevice.ThisstructureisusedwiththeIDirectInputDevice8::GetDeviceStatemethod.

typedefstructDIJOYSTATE{

LONGlX;

LONGlY;

LONGlZ;

LONGlRx;

LONGlRy;

LONGlRz;

LONGrglSlider[2];

DWORDrgdwPOV[4];

BYTErgbButtons[32];

}DIJOYSTATE,*LPDIJOYSTATE;

Members

lXX-axis,usuallytheleft-rightmovementofastick.

lYY-axis,usuallytheforward-backwardmovementofastick.

lZZ-axis,oftenthethrottlecontrol.Ifthejoystickdoesnothavethisaxis,thevalueis0.

lRxX-axisrotation.Ifthejoystickdoesnothavethisaxis,thevalueis0.

lRyY-axisrotation.Ifthejoystickdoesnothavethisaxis,thevalueis0.

lRzZ-axisrotation(oftencalledtherudder).Ifthejoystickdoesnothavethisaxis,thevalueis0.

rglSlider[2]Twoadditionalaxes,formerlycalledtheu-axisandv-axis,whosesemanticsdependonthejoystick.UsetheIDirectInputDevice8::GetObjectInfomethodtoobtainsemanticinformationaboutthesevalues.

rgdwPOV[4]

Page 131: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Directioncontrollers,suchaspoint-of-viewhats.Thepositionisindicatedinhundredthsofadegreeclockwisefromnorth(awayfromtheuser).Thecenterpositionisnormallyreportedas–1;butseeRemarks.Forindicatorsthathaveonlyfivepositions,thevalueforacontrolleris–1,0,9,000,18,000,or27,000.

rgbButtons[32]Arrayofbuttons.Thehigh-orderbitofthebyteissetifthecorrespondingbuttonisdown,andclearifthebuttonisupordoesnotexist.

Remarks

Youmustpreparethedeviceforjoystick-styleaccessbycallingtheIDirectInputDevice8::SetDataFormatmethod,passingthec_dfDIJoystickglobaldataformatvariable.

Ifanaxisisinrelativemode,theappropriatemembercontainsthechangeinposition.Ifitisinabsolutemode,themembercontainstheabsoluteaxisposition.

SomedriversreportthecenteredpositionofthePOVindicatoras65,535.Determinewhethertheindicatoriscenteredasfollows:

BOOLPOVCentered=(LOWORD(dwPOV)==0xFFFF);

NoteUnderMicrosoft®DirectX®7,slidersonsomejoystickscouldbeassignedtotheZaxis,withsubsequentcoderetrievingdatafromthatmember.UsingDirectX8,thosesamesliderswillbeassignedtotherglSliderarray.ThisshouldbetakenintoaccountwhenportingapplicationstoDirectX8.MakeanynecessaryalterationstoensurethatsliderdataisretrievedfromtherglSliderarray.

Requirements

WindowsNT/2000/XP:RequiresWindows2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

SeeAlso

Page 132: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DIJOYSTATE2

Page 133: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 134: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DIJOYSTATE2Describesthestateofajoystickdevicewithextendedcapabilities.ThisstructureisusedwiththeIDirectInputDevice8::GetDeviceStatemethod.

typedefstructDIJOYSTATE2{

LONGlX;

LONGlY;

LONGlZ;

LONGlRx;

LONGlRy;

LONGlRz;

LONGrglSlider[2];

DWORDrgdwPOV[4];

BYTErgbButtons[128];

LONGlVX;

LONGlVY;

LONGlVZ;

LONGlVRx;

LONGlVRy;

LONGlVRz;

LONGrglVSlider[2];

LONGlAX;

LONGlAY;

LONGlAZ;

LONGlARx;

LONGlARy;

LONGlARz;

LONGrglASlider[2];

LONGlFX;

LONGlFY;

LONGlFZ;

LONGlFRx;

LONGlFRy;

LONGlFRz;

LONGrglFSlider[2];

}DIJOYSTATE2,*LPDIJOYSTATE2;

Members

lXX-axis,usuallytheleft-rightmovementofastick.

lY

Page 135: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Y-axis,usuallytheforward-backwardmovementofastick.lZ

Z-axis,oftenthethrottlecontrol.Ifthejoystickdoesnothavethisaxis,thevalueis0.

lRxX-axisrotation.Ifthejoystickdoesnothavethisaxis,thevalueis0.

lRyY-axisrotation.Ifthejoystickdoesnothavethisaxis,thevalueis0.

lRzZ-axisrotation(oftencalledtherudder).Ifthejoystickdoesnothavethisaxis,thevalueis0.

rglSlider[2]Twoadditionalaxisvalues(formerlycalledtheu-axisandv-axis)whosesemanticsdependonthejoystick.UsetheIDirectInputDevice8::GetObjectInfomethodtoobtainsemanticinformationaboutthesevalues.

rgdwPOV[4]Directioncontrollers,suchaspoint-of-viewhats.Thepositionisindicatedinhundredthsofadegreeclockwisefromnorth(awayfromtheuser).Thecenterpositionisnormallyreportedas–1;butseeRemarks.Forindicatorsthathaveonlyfivepositions,thevalueforacontrolleris–1,0,9,000,18,000,or27,000.

rgbButtons[128]Arrayofbuttons.Thehigh-orderbitofthebyteissetifthecorrespondingbuttonisdown,andclearifthebuttonisupordoesnotexist.

lVXX-axisvelocity.

lVYY-axisvelocity.

lVZZ-axisvelocity.

lVRxX-axisangularvelocity.

lVRyY-axisangularvelocity.

lVRzZ-axisangularvelocity.

rglVSlider[2]Extraaxisvelocities.

Page 136: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

lAXX-axisacceleration.

lAYY-axisacceleration.

lAZZ-axisacceleration.

lARxX-axisangularacceleration.

lARyY-axisangularacceleration.

lARzZ-axisangularacceleration.

rglASlider[2]Extraaxisaccelerations.

lFXX-axisforce.

lFYY-axisforce.

lFZZ-axisforce.

lFRxX-axistorque.

lFRyY-axistorque.

lFRzZ-axistorque.

rglFSlider[2]Extraaxisforces.

Remarks

YoumustpreparethedeviceforaccesstoajoystickwithextendedcapabilitiesbycallingtheIDirectInputDevice8::SetDataFormatmethod,passingthec_dfDIJoystick2globaldataformatvariable.

Ifanaxisisinrelativemode,theappropriatemembercontainsthechangeinposition.Ifitisinabsolutemode,themembercontainstheabsoluteaxisposition.

Page 137: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SomedriversreportthecenteredpositionofthePOVindicatoras65,535.Determinewhethertheindicatoriscenteredasfollows:

BOOLPOVCentered=(LOWORD(dwPOV)==0xFFFF);

NoteUnderMicrosoft®DirectX®7,slidersonsomejoystickscouldbeassignedtotheZaxis,withsubsequentcoderetrievingdatafromthatmember.UsingDirectX8,thosesamesliderswillbeassignedtotherglSliderarray.ThisshouldbetakenintoaccountwhenportingapplicationstoDirectX8.MakeanynecessaryalterationstoensurethatsliderdataisretrievedfromtherglSliderarray.

Requirements

WindowsNT/2000/XP:RequiresWindows2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

SeeAlso

DIJOYSTATE

Page 138: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 139: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ps

Providesthemethodtospecifytheversionoftheshadercode.

ps.mainVer.subVer

Registers

Argument Description ValuesmainVer mainversionnumber 1subVer subversionnumber 0,1,2,3,4

Remarks

Thisinstructionmustbethefirstinstructioninashader.

Example

//Thisexampledeclaresaversion1.0shader.

ps.1.0

//Thisexampledeclaresaversion1.4shader.

ps.1.4

Page 140: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 141: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

defProvidesamethodtodefineconstantstobeusedwithinthepixelshader.

defdest,fVal0,fVal1,fVal2,fVal3

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregister x 1.0,1.1,1.2,1.3,1.4

fVal0,fVal1,fVal2,fVal3

Sourcefloatingpointvalue N/A N/A N/A N/A 1.0,1.1,1.2,

1.3,1.4

N/ANotapplicable.Thefloatvaluesdonotuseregisters.

EachofthefloatvaluesinfVal0,fVal1,fVal2,fVal3isbetween-1.0and1.0.ThisisnotnecessarilythenumberspecifiedinMAXPIXELSHADERVALUE.

Tolearnmoreaboutregisters,seeRegisters.

Remarks

definstructionsmustbeplacedaftertheversioninstructionandbeforeanyarithmeticortextureaddressinstructions.

ThedefinstructionisanalternativetosettingpixelshaderconstantsbycallingSetPixelShaderConstant.WhenSetPixelShaderiscalled,thedefinstructioniseffectivelytranslatedintoaSetPixelShaderConstantcall.ConstantregistersthatareinitializedbythedefinstructionduringSetPixelShadercanbeoverwrittenbycallingSetPixelShaderConstantmanually.

Thisinstructiondoesnotcountagainsttheinstructionlimit.Itisstrippedfromtheinstructionstreampriortobeingsenttothedriver.

Page 142: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

FormoreinformationaboutMAXPIXELSHADERVALUE,seeD3DCAPS8.

Example

//Thisexampleoutputsaconstantcolor.

//Theshaderisshownbelow.

ps.1.0//versioninstruction

defc0,1.0f,0.0f,0.0f,1.0f//setc0register

movr0,c0//outputconstantcolor

Page 143: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversion1.4)

Page 144: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

phase

Thephaseinstructionmarksthetransitionbetweenphase1andphase2.Ifnophaseinstructionispresent,theentireshaderifexecutedasifitisaphase2shader.

phase

Remarks

Thisinstructionappliestoversion1.4only.

Shaderinstructionsthatoccurbeforethephaseinstructionarephase1instructions.Allotherinstructionsarephase2instructions.Byhavingtwophasesforinstructions,themaximumnumberofinstructionspershaderisincreased.

Theunfortunateside-effectofthephasetransitionisthatthealphacomponentoftemporaryregistersareunsetoruninitializedduringthetransition.

Example

Thisexampleshowshowtogroupinstructionsasphase1orphase2instructionswithinashader.

Thephaseinstructionisalsocommonlycalledthephasemarkerbecauseitmarksthetransitionbetweenphase1and2instructions.Inaversion1.4pixelshader,ifthephasemarkerisnotpresent,theshaderisexecutedasifitisrunninginphase2.Thisisimportantbecausetherearedifferencesbetweenphase1and2instructionsandregisteravailability.Thedifferencesarenotedthroughoutthereferencesection.

ps.1.4

//Addphase1instructionshere.

phase

//Addphase2instructionshere.

Page 145: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 146: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

addPerformsacomponent-wiseaddoftworegisters.

adddest,src0,src1

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregisterx 1.0

x x 1.1,1.2,1.3x 1.4

src0,src1 Sourceregisterx x x x 1.0,1.1,1.2,1.3

x x 1.4phase1x x x 1.4phase2

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionperformsacomponent-wiseadditionoftworegistersasshownbelow.

dest.r=src0.r+src1.r

dest.g=src0.g+src1.g

dest.b=src0.b+src1.b

dest.a=src0.a+src1.a

Example

Thisexampleisforillustrationonly.TheCcodeaccompanyingtheshaderhasnotbeenoptimizedforperformance.ItcanusehelperfunctionsfromtheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

Page 147: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Thisexampleaddsthevertexcolortothetexturecolor.

//Theshaderisshownbelow.

ps.1.0//Versioninstruction.

text0//Declaretexture.ThisexamplerequirestheDXLogotexture

//tobesetonstage0.

addr0,t0,t0//r0=t0+t0.Thisdoubleseachcolorcomponent.

//Theeffectistoincreaseimagebrightness.

//Theinputtextureisshownontheleft.Therenderedoutputfromthe

//pixelshaderisshownontheright.Inthisexample,itisbrighter

//becausethetexturecolorvalueshavebeendoubled.

//Additionalcodeloadsthetextureintexturestage0.

LPDIRECT3DDEVICE8m_pd3dDevice;//Initthisdevicepointerintheapplication.

LPDIRECT3DTEXTURE8m_pTexture0;//Usethisvariabletoholdapointertothetexture.

TCHARstrPath[512]="textureFile.jpg";

//UseahelperfunctionfromtheSDKtoloadthetexture.

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

m_pd3dDevice->SetTexture(0,m_pTexture0);

Page 148: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversion1.4)

Page 149: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

bemApplyafakebumpenvironment-maptransform.

bemdest.rg,src0,src1

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.4phase1src0

Sourceregisterx x 1.4phase1

src1 x 1.4phase1

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionperformsthefollowingcalculation.

(Givenn==destregister#)

dest.r=src0.r+D3DTSS_BUMPENVMAT00(stagen)*src1.r

+D3DTSS_BUMPENVMAT10(stagen)*src1.g

dest.g=src0.g+D3DTSS_BUMPENVMAT01(stagen)*src1.r

+D3DTSS_BUMPENVMAT11(stagen)*src1.g

Rulesforusingbem:

1. bemmustappearinthefirstphaseofashader(thatis,beforeaphasemarker).

2. bemconsumestwoarithmeticinstructionslots.3. Onlyoneuseofthisinstructionisallowedpershader.4. Destinationwritemaskmustbe.rg/.xy.5. Thisinstructioncannotbeco-issued.

Page 150: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

6. Asidefromtherestrictionthatdestinationwritemaskbe.rg,modifiersonsourcesrc0,src1,andinstructionmodifiersareunconstrained.

Page 151: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.2,1.3,1.4)

Page 152: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

cmpConditionallychoosesbetweensrc1andsrc2,basedonthecomparisonsrc0>=0.

cmpdest,src0,src1,src2

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregisterx x 1.2,1.3x 1.4

src0,src1,src2 Sourceregisterx x x x 1.2,1.3

x x 1.4phase1x x x 1.4phase2

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thecomparisonisdoneperchannel.

Forpixelshaderversion1.2and1.3,cmpcountsastwoarithmeticinstructions.Unfortunately,thiswasdiscoveredtoolateinthedevelopmentcycle,andthereforeisnotvalidatedproperlywhencallingCreatePixelShader.Itisincorrectlybeingcountedasconsumingonlyonearithmeticinstruction.Besuretomanuallycountthisinstructionastwoarithmeticinstructionstowardthemaximuminstructioncount.Formoreinformationaboutinstructioncounts,seeCountingInstructions.

Inaddition,forpixelshaderversion1.2and1.3,thedestinationregisterforcmpcannotbethesameasanyofthesourceregisters.Validationdoesnotcatchthis,sobesuretokeepthisinmind.

Page 153: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Example

Thisexampledoesafour-channelcomparison.

//Comparesallfourcomponents.

ps.1.4

defc0,-0.6,0.6,0,0.6

defc10,0,0,0

defc21,1,1,1

cmpr0,c0,c1,c2//r0isassigned1,0,0,0basedonthefollowing:

//r0.x=c2.xbecausec0.x<0

//r0.y=c1.ybecausec0.y>=0

//r0.z=c1.zbecausec0.z>=0

//r0.w=c1.wbecausec0.w>=0

Page 154: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 155: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

cndConditionallychoosesbetweensrc1andsrc2,basedonthecomparisonsrc0>0.5.

cnddest,src0,src1,src2

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregisterx 1.0

x x 1.1,1.2,1.3x 1.4

src0

Sourceregister

r0.a 1.0,1.1,1.2,1.3src1,src2 x x x x 1.0,1.1,1.2,1.3

src0,src1,src2x x 1.4phase1

x x x 1.4phase2

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Forversions1.0to1.3,src0mustber0.a.Version1.4hasnosuchrestriction.

//Version1.1to1.3

if(r0.a>0.5)

dest=src1

else

dest=src2

//Version1.4compareseachchannelseparately.

foreachcomponentinsrc0

{

if(src0.component>0.5)

dest.component=src1.component

else

Page 156: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

dest.component=src2.component

}

Example

Theseexamplesshowafour-channelcomparisondoneinaversion1.4shader,aswellasasingle-channelcomparisonpossibleinaversion1.1shader.

//Version1.4comparesallfourcomponents.

ps.1.4

defc0,-0.5,0.5,0,0.6

defc10,0,0,0

defc21,1,1,1

cndr1,c0,c1,c2//r0contains1,1,1,0because,

//r1.x=c2.xbecausec0.x≤0.5

//r1.y=c2.ybecausec0.y≤0.5

//r1.z=c2.zbecausec0.z≤0.5

//r1.w=c1.wbecausec0.w>0.5

//Version1.1to1.3comparesagainstthereplicatedalphachannel

//ofr0only.

ps.1.1

defc0,-0.5,0.5,0,0.6

defc10,0,0,0

defc21,1,1,1

movr0,c0

cndr1,r0.a,c1,c2//r1getsassigned0,0,0,0because

//r0.a>0.5,thereforer1.xyzw=c1.xyzw

//Thisexamplecomparestwovalues,AandB,toeachother.

//ThisexampleassumesAisloadedintov0andBisloadedintov1.

//BothAandBmustbeintherangeof-1to+1,andsincethe

//colorregisters(vn)aredefinedtobebetween0and1,

//therestrictionhappenstobesatisfiedinthisexample.

//Theshaderisshownbelow.

ps.1.0//versioninstruction

subr0,v0,v1_bias//r0=A-(B-0.5)

cndr0,r0.a,c0,c1//r0=(A>B?c0:c1)

//Theresultinr0isc0ifA>B.Otherwise,theresultinr0isc1.

Page 157: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 158: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

dp3Calculatesathree-componentdotproduct.Thescalarresultisreplicatedtoallfourchannels.

dp3dest,src0,src1

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregisterx 1.0

x x 1.1,1.2,1.3x 1.4

src0,src1 Sourceregisterx x x x 1.0,1.1,1.2,1.3

x x 1.4phase1x x x 1.4phase2

dp3doesnotautomaticallyclamptheoutputresultbetweenzeroandone.Ifclampingisnecessary,usethesaturatemodifiers.

dp3canbeco-issuedaslongasdp3iswritingthecolorchannelsandtheotherinstructioniswritingthealphachannel.

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionexecutesinthevectorpipeline,alwayswritingouttothecolorchannels.Forversion1.4,thisinstructionstillusesthevectorpipelinebutmaywritetoanychannel.

dp3r0.rgb,t0,v0//CopyscalarresulttoRGBcomponents.

AninstructionwithadestinationregisterRGBwritemaskmaybeco-issued

Page 159: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

withdp3asshownbelow.

dp3r0.rgb,t0,v0//Copyscalarresulttocolorcomponents.

+movr2.a,t0//Copyalphacomponentfromt0inparallel.

Thedp3instructioncanbemodifiedusingtheSignedScalinginputargumentmodifier(_bx2)appliedtoitsinputargumentsiftheyarenotalreadyexpandedtosigneddynamicrange.Foralightingshader,thesaturateinstructionmodifier(_sat)isoftenusedtoclampthenegativevaluestoblack,asshowninthefollowingexample.

dp3_satr0,t0_bx2,v0_bx2//Heret0isabumpmap,v0containsthelightdirection.

Example

Thisexampleisforillustrationonly.TheCcodeaccompanyingtheshaderhasnotbeenoptimizedforperformance.ItcanusehelperfunctionsfromtheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

Thisexampleusesadotproducttosquarethevertexdiffusecolorcomponents.

//Theshaderisshownbelow.

ps.1.0//Versioninstruction.

text0//Declaretexture.

dp3r0,v0,v0//Dotproductsquaresthevertexcolorvalues,

//color(v0)*color(v0).

//Brightcolorsmaxoutatwhite.

//Dimmercolorsyieldgray.

Theresultsofthisexampleareshownbelow.Theinputvertexcolorsareshownontheleft.Therenderedoutputfromthepixelshaderisshownontheright.Theleft,bottom,andrightedgesarewhitebecausetheinputcolorcomponentsreachthemaximumcolorvaluewhensquared.Thecentercolorisgraybecausethesquaredcolorvaluesarelowerwheretheinputcolorsblendtogether.

Additionalcodeloadsatextureintexturestage0

LPDIRECT3DDEVICE8m_pd3dDevice;//Initializethepointerbeforeusing.

LPDIRECT3DTEXTURE8m_pTexture0;//Usethisvariabletoholdapointertothetexture.

TCHARstrPath[512]="textureFile.jpg";

Page 160: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

m_pd3dDevice->SetTexture(0,m_pTexture0);

Page 161: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.2,1.3,1.4)

Page 162: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

dp4Calculatesafour-componentdotproduct.Thescalarresultisreplicatedtoallchannels.

dp4dest,src0,src1

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregisterx 1.2,1.3x 1.4

src0,src1 Sourceregisterx x x x 1.2,1.3

x x 1.4phase1x x x 1.4phase2

Thisinstructioncannotbeco-issued.

Thisinstructiondoesnotautomaticallyclamptheoutputresultbetweenzeroandone.Ifclampingisnecessary,usethesaturatemodifier.

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionexecutesinboththevectorandalphapipeline.

dp4r0,t0,v0//CopyscalarresulttoRGBAcomponents.

Forpixelshaderversion1.2and1.3,dp4countsastwoarithmeticinstructions.Unfortunately,thiswasdiscoveredtoolateinthedevelopmentcycleandthereforeisnotvalidatedproperlywhencallingCreatePixelShader.Itisbeingincorrectlycountedasconsumingonlyonearithmeticinstruction.Besuretomanuallycountthisinstructionastwoarithmeticinstructionstowardthe

Page 163: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

maximuminstructioncount.Formoreinformationaboutinstructioncounts,seeCountingInstructions.

Inaddition,forpixelshaderversion1.2and1.3,thedestinationregisterfordp4cannotbethesameasanyofthesourceregisters.Validationdoesnotcatchthis,sobesuretokeepthisinmind.

Page 164: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 165: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

lrpInterpolateslinearlybetweenthesecondandthirdsourceregistersbyaproportionspecifiedinthefirstsourceregister.

lrpdest,src0,src1,src2

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregisterx 1.0

x x 1.1,1.2,1.3x 1.4

src0,src1,src2 Sourceregisterx x x x 1.0,1.1,1.2,1.3

x x 1.4phase1x x x 1.4phase2

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionperformsthelinearinterpolationbasedonthefollowingformula.

dest=src0*src1+(1-src0)*src2

//whichisthesameas

dest=src2+src0*(src1-src2)

Example

Thisexampleisforillustrationonly.TheCcodeaccompanyingtheshaderhasnotbeenoptimizedforperformance.ItcanusehelperfunctionsfromtheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

Page 166: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Thisexamplecombinesatexturecolorwithadiffusecolorvalue.

//Theshaderisshownbelow.

ps.1.0//Versioninstruction.

text0//Declaretexture.

lrpr0,t0,v0,t0//Blendfromv0tot0byt0amount.

//Theinputcolorsandtheoutputcolorsareshownbelow.Thefirstimage

//(src0)determinestheamountofthesecondimage(src1)andthethirdimage

//(src2)thatareblendedtomakethefinalimage(dest).Wherethefirstimage

//iswhite,thesecondimageappearsintheoutput.Wherethefirstimageis

//black,thethirdimagesappearsintheoutput.Wherethefirstisgray,the

//finalimagecontainscolorvaluesfromthesecondandthirdimage.

//Additionalcodeloadsthetextureintexturestage0.

LPDIRECT3DDEVICE8m_pd3dDevice;//initializethepointer

LPDIRECT3DTEXTURE8m_pTexture0;//apointertothetexture.

TCHARstrPath[512]="textureFile.jpg";

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

m_pd3dDevice->SetTexture(0,m_pTexture0);

Page 167: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 168: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

madMultiplyandaddinstruction.Setsthedestinationregisterto(src0*src1)+src2.

maddest,src0,src1,src2

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregisterx 1.0

x x 1.1,1.2,1.3x 1.4

src0,src1,src2 Sourceregisterx x x x 1.0,1.1,1.2,1.3

x x 1.4phase1x x x 1.4phase2

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionperformsamultiplyaccumulateoperationbasedonthefollowingformula.

dest=src0*src1+src2

Example

Thisexampleisforillustrationonly.TheCcodeaccompanyingtheshaderhasnotbeenoptimizedforperformance.ItcanusehelperfunctionsfromtheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

//Thisexampleblendsadiffusecolor,atexturecolorandaconstantcolor.

Page 169: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Theshaderisshownbelow.

ps.1.0//Versioninstruction.

text0//Declaretexture.

madr0,v0,t0,v0//Mixdiffusecolorandtexturecolor.

//Thefollowingfourimagesshowthecontentsofthethreesourceregisters

//andtheresultingoutputregister.Theoutputregistershowstheresultof

//thegradientinthecenterofthedestinationimage,wherethemidtones

//appear.Thisisaresultofaddingthepixelsfromthecenterofsrc2with

//thepixelcolorcreatedfromthecenteroftheproductofsrc0*src1.

//Additionalcodeloadsatextureintexturestage0.

LPDIRECT3DDEVICE8m_pd3dDevice;//initializethispointer

LPDIRECT3DTEXTURE8m_pTexture0;//apointertothetexture.

TCHARstrPath[512]="textureFile.jpg";

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

m_pd3dDevice->SetTexture(0,m_pTexture0);

Page 170: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 171: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

movCopiesthecontentsofthesourcetothedestination.

movdest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregisterx 1.0

x x 1.1,1.2,1.3x 1.4

src Sourceregisterx x x x 1.0,1.1,1.2,1.3

x x 1.4phase1x x x 1.4phase2

Tolearnmoreaboutregisters,seeRegisters.

Example

Thisexampleisforillustrationonly.TheCcodeaccompanyingtheshaderhasnotbeenoptimizedforperformance.ItcanusehelperfunctionsfromtheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

//Thisexamplecopiesthetexturecolortotheoutput.

//Theshaderisshownbelow.

ps.1.0//Versioninstruction

text0//Declaretexture.

movr0,t0//Movetexturetooutput.

//Thefollowingimagesshowthecontentsofthesourceregisterand

//theresultingdestinationregister.Theimagesareidenticalbecause

//themovinstructionwasused.

Page 172: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Additionalcodeloadsthetextureintexturestage0.

LPDIRECT3DDEVICE8m_pd3dDevice;//Initthisdevicepointerintheapplication.

LPDIRECT3DTEXTURE8m_pTexture0;//Usethisvariabletoholdapointertothetexture.

TCHARstrPath[512]="textureFile.jpg";

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

m_pd3dDevice->SetTexture(0,m_pTexture0);

Page 173: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 174: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

mulMultipliesthecomponentsoftwosourceregisters.Theresultisdest=src0*src1.

muldest,src0,src1

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregisterx 1.0

x x 1.1,1.2,1.3x 1.4

src0,src1 Sourceregisterx x x x 1.0,1.1,1.2,1.3

x x 1.4phase1x x x 1.4phase2

Tolearnmoreaboutregisters,seeRegisters.

Example

Thisexampleisforillustrationonly.TheCcodeaccompanyingtheshaderhasnotbeenoptimizedforperformance.ItcanusehelperfunctionsfromtheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

//Thisexamplecombinesthetexturecolorandthediffusecolor.

//Theshaderisshownbelow.

ps.1.0//Versioninstruction

text0//Declaretexture.

mulr0,v0,t0//Multiplydiffusecolorwithgradienttexture.

//Thefollowingimagesshowthecontentsofthesourceregistersthe

//resultingoutputregister.

Page 175: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Wheresrc1iswhite,thedestinationpixelcoloristhesameasthe

//sourcepixelcolorsincedest=src*1.0.

//Wheresrc1isblack,thedestinationisalsoblack.

//Thepixelcolorsinthemiddleofthedestinationimageareablend

//ofsrc0andsrc1.

//Additionalcodeloadsatextureintexturestage0.

LPDIRECT3DDEVICE8m_pd3dDevice;//Initthisdevicepointerintheapplication.

LPDIRECT3DTEXTURE8m_pTexture0;//Usethisvariabletoholdapointertothetexture.

TCHARstrPath[512]="textureFile.jpg";

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

m_pd3dDevice->SetTexture(0,m_pTexture0);

Page 176: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 177: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

nopNooperationisperformed.

nop

Registers

None

Remarks

Thisinstructionperformsano-op,ornooperation.Thesyntaxforcallingitisasfollows:

nop

Page 178: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 179: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

subPerformssubtraction.Subtractsthesecondsourceregisterfromthefirstsourceregister.

subdest,src0,src1

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

dest Destinationregisterx 1.0

x x 1.1,1.2,1.3x 1.4

src0,src1 Sourceregisterx x x x 1.0,1.1,1.2,1.3

x x 1.4phase1x x x 1.4phase2

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionperformsthesubtractionbasedonthefollowingformula.

dest=src0-src1

Example

Thisexampleisforillustrationonly.TheCcodeaccompanyingtheshaderhasnotbeenoptimizedforperformance.ItcanusehelperfunctionsfromtheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

//Thisexamplesubtractstexturecolorfromthediffusecolor.

Page 180: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Theshaderisshownbelow.

ps.1.0//Versioninstruction

text0//Declaretexture.

subr0,v0,t0//Subtracttexturecolorfromdiffusecolor.

//Thefollowingimagesshowthecontentsofthesourceregistersand

//theresultingdestinationregister.Thecolorsinthesecondimage(src1)

//aresubtractedfromthecolorinthefirstimage(src0)tomakethe

//resultingimage(dest).

//Additionalcodeloadsthetextureintexturestage0.

LPDIRECT3DDEVICE8m_pd3dDevice;//Initthisdevicepointerintheapplication.

LPDIRECT3DTEXTURE8m_pTexture0;//Usethisvariabletoholdapointertothetexture.

TCHAR strPath[512]="textureFile.jpg";

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

m_pd3dDevice->SetTexture(0,m_pTexture0);

Page 181: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 182: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texLoadsthedestinationregisterwithcolordata(RGBA)sampledfromatexture.

Thetexturemustbeboundtoaparticulartexturestage(n)usingSetTexture.Texturesamplingiscontrolledbythetexturestagestateattributes,setwithSetTextureStageState.

texdest

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thedestinationregisternumberspecifiesthetexturestagenumber.

Texturesamplingusestexturecoordinatestolookup,orsample,acolorvalueatthespecified(u,v,w,q)coordinateswhiletakingintoaccountthetexturestagestateattributes.

Thetexturecoordinatedataisinterpolatedfromthevertextexturecoordinatedataandisassociatedwithaspecifictexturestage.Thedefaultassociationisaone-to-onemappingbetweentexturestagenumberandtexturecoordinatedeclarationorder.Thismeansthatthefirstsetoftexturecoordinatesdefinedinthevertexformatarebydefaultassociatedwithtexturestage0.

Texturecoordinatesmaybeassociatedwithanystageusingtwotechniques.Whenusingafixedfunctionvertexshaderorthefixedfunctionpipeline,thetexturestagestateflagTSS_TEXCOORDINDEXcanbeusedinSetTextureStageStatetoassociatecoordinatestoastage.Otherwise,thetexture

Page 183: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

coordinatesareoutputbythevertexshaderoTnregisterswhenusingaprogrammablevertexshader.

Example

Thisexampleisforillustrationonly.TheCcodeaccompanyingtheshaderhasnotbeenoptimizedforperformance.ItcanusehelperfunctionsfromtheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

//Thisexampleappliesatexturetoaquad.

//Theshaderisshownbelow.

ps.1.0//versioninstruction

text0//samplesthetextureatstage0usingtexturecoordinatesfromstage0

movr0,t0//copiesthecolorint0tooutputregisterr0

//Therenderedoutputfromthepixelshaderisshownbelow.Itis

//simplyatexturemapappliedtoaquadobject.

//Additionalcodeisrequiredtousethisshaderandanexample

//scenarioisshownbelow.

//Loadthetextureintexturestage0.

LPDIRECT3DDEVICE8m_pd3dDevice; //Initializethepointerbeforeusing

LPDIRECT3DTEXTURE8m_pTexture0; //apointerforthetexture

TCHARstrPath[512]="DX5_Logo.bmp";

//HelperfunctionfromtheSDK

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

m_pd3dDevice->SetTexture(0,m_pTexture0);

//Thiscodecreatestheshaderfromafile.Thecontentsoftheshader

//filecanalsobesuppliedasatextstring.

TCHARstrPShaderPath[512];

LPD3DXBUFFERpCode;

//HelperfunctionfromtheSDK

DXUtil_FindMediaFile(strPShaderPath,_T("shaderFile.txt"));

//Assemblethevertexshaderfromthefile.

D3DXAssembleShaderFromFile(strPShaderPath,0,NULL,&pCode;,NULL);

m_pd3dDevice->CreatePixelShader((DWORD*)pCode->GetBufferPointer(),

&m;_hPixelShader);

pCode->Release();

Page 184: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Definetheobjectvertexdata.

structCUSTOMVERTEX

{

FLOATx,y,z;

FLOATtu1,tv1;

};

#defineD3DFVF_CUSTOMVERTEX(D3DFVF_XYZ|D3DFVF_TEX1|TEXCOORD2(0))

staticCUSTOMVERTEXg_Vertices[]=

{

//xyzu1v1

{-1.0f,-1.0f,0.0f,0.0f,1.0f,},

{+1.0f,-1.0f,0.0f,1.0f,1.0f,},

{+1.0f,+1.0f,0.0f,1.0f,0.0f,},

{-1.0f,+1.0f,0.0f,0.0f,0.0f,},

//v1isflippedtomeetthetopdownconventioninWindows

//theupperlefttexturecoordinateis(0,0)

//thelowerrighttexturecoordinateis(1,1).

};

//Createandfillthequadvertexbuffer.

m_pd3dDevice->CreateVertexBuffer(4*sizeof(CUSTOMVERTEX),

D3DUSAGE_WRITEONLY,D3DFVF_CUSTOMVERTEX,

D3DPOOL_MANAGED,&m;_pQuadVB);

CUSTOMVERTEX*pVertices=NULL;

m_pQuadVB->Lock(0,4*sizeof(CUSTOMVERTEX),(BYTE**)&pVertices;,0);

for(DWORDi=0;i<4;i++)

pVertices[i]=g_Vertices[i];

m_pQuadVB->Unlock();

//Checktoseeifthehardwaresupportspixelshaders.

if(D3DSHADER_VERSION_MAJOR(pCaps->PixelShaderVersion)<1)

returnE_FAIL;

//Setupthetransforms.

D3DXVECTOR3from(0,0,-5.0f);

D3DXVECTOR3at(0.0f,0.0f,0.0f);

D3DXVECTOR3up(0.0f,1.0f,0.0f);

D3DXMATRIXmatWorld;

D3DXMatrixIdentity(&matWorld;);

m_pd3dDevice->SetTransform(D3DTS_WORLD,&matWorld;);

D3DXMATRIXmatView;

D3DXMatrixLookAtLH(&matView;,&from;,&at;,&up;);

m_pd3dDevice->SetTransform(D3DTS_VIEW,&matView;);

Page 185: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXMATRIXmatProj;

D3DXMatrixPerspectiveFovLH(&matProj;,D3DX_PI/4,1.0f,0.5f,1000.0f);

m_pd3dDevice->SetTransform(D3DTS_PROJECTION,&matProj;);

//Rendertheoutput.

//Clearthebackbuffertoblack.

m_pd3dDevice->Clear(0L,NULL,D3DCLEAR_TARGET,0x00000000,1.0f,0L);

//Setdevicestate.

m_pd3dDevice->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);

m_pd3dDevice->SetRenderState(D3DRS_CLIPPING,FALSE);

m_pd3dDevice->SetRenderState(D3DRS_LIGHTING,FALSE);

m_pd3dDevice->SetRenderState(D3DRS_ZENABLE,FALSE);

m_pd3dDevice->SetTexture(0,m_pTexture0);

m_pd3dDevice->SetStreamSource(0,m_pQuadVB,sizeof(CUSTOMVERTEX));

m_pd3dDevice->SetVertexShader(D3DFVF_CUSTOMVERTEX);

m_pd3dDevice->SetPixelShader(m_hPixelShader);

m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,0,2);

m_pd3dDevice->SetTexture(0,NULL);

Page 186: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 187: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texbemApplyafakebumpenvironment-maptransform.Thisisaccomplishedbymodifyingthetextureaddressdataofthedestinationregister,usingaddressperturbationdata(du,dv),andatwo-dimensional(2-D)bumpenvironmentmatrix.

texbemdest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3src Sourceregister x 1.0,1.1,1.2,1.3

Theredandgreencolordatainthesrcregisterisinterpretedastheperturbationdata(du,dv).

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructiontransformsredandgreencomponentsinthesourceregisterusingthe2-Dbumpenvironment-mappingmatrix.Theresultisaddedtothetexturecoordinatesetcorrespondingtothedestinationregisternumber,andisusedtosamplethecurrenttexturestage.

Thisoperationalwaysinterpretsduanddvassignedquantities.Forversions1.0and1.1,theSignedScalinginputmodifier(_bx2)isnotpermittedontheinputargument.

Thisinstructionproducesdefinedresultswheninputtexturescontainsignedformatdata.Mixedformatdataworksonlyifthefirsttwochannelscontainsigneddata.Formoreinformationaboutsurfaceformats,seeD3DFORMAT.

Page 188: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Thiscanbeusedforavarietyoftechniquesbasedonaddressperturbation,includingfakeper-pixelenvironmentmappinganddiffuselighting(bumpmapping).

//Whenusingthisinstruction,textureregistersmustfollowthefollowingsequence.

//Thetextureassignedtostaget(n)containsthe(du,dv)data.

//Thetextureassignedtostaget(m)issampled.

text(n)

texbemt(m),t(n)wherem>n

//Thecalculationsdonewithintheinstructionareshownbelow.

//1.Newvaluesfortextureaddresses(u',v')arecalculated.

//2.Samplethetextureusing(u',v')

u'=TextureCoordinates(stagem)u+D3DTSS_BUMPENVMAT00(stagem)*t(n)

D3DTSS_BUMPENVMAT10(stagem)*t(n)G

v'=TextureCoordinates(stagem)v+D3DTSS_BUMPENVMAT01(stagem)*t(n)

D3DTSS_BUMPENVMAT11(stagem)*t(n)G

t(m)RGBA=TextureSample(stagem)using(u',v')ascoordinates.

NoteWhenusingtexbemortexbeml,donotre-readthesourceregisterlaterintheshaderbecausethedatawithintheregistermightbecorrupted.Theshadervalidationallowsthiseventhoughtheresultwillbeundefined.

Example

//Hereisanexampleshaderwiththetexturemapsidentifiedand

//thetexturestagesidentified.

ps.1.0

text0;definet0togeta2-tupleDuDv

texbemt1,t0;compute(u',v')

;samplet1using(u',v')

movr0,t1;outputresult

//texbemrequiresthefollowingtexturesinthefollowingtexturestages.

//

//Stage0isassignedabumpmapwith(du,dv)perturbationdata.

//

//Stage1usesatexturemapwithcolordata.

//

//Thisinstructionsetsthematrixdataonthetexturestagethatissampled.

Page 189: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Thisisdifferentfromthefunctionalityofthefixedfunctionpipelinewhere

//theperturbationdataandthematricesoccupythesametexturestage.

Page 190: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 191: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texbemlApplyafakebumpenvironment-maptransformwithluminancecorrection.Thisisaccomplishedbymodifyingthetextureaddressdataofthedestinationregister,usingaddressperturbationdata(du,dv),atwo-dimensional(2-D)bumpenvironmentmatrix,andluminance.

texbemldest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3src Sourceregister x 1.0,1.1,1.2,1.3

Theredandgreencolordatainthesrcregisterisinterpretedastheperturbationdata(du,dv).

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructiontransformstheredandgreencomponentsinthesourceregisterusingthe2-Dbumpenvironmentmappingmatrix.Theresultisaddedtothetexturecoordinatesetcorrespondingtothedestinationregisternumber.Aluminancecorrectionisappliedusingtheluminancevalueandthebiastexturestagevalues.Theresultisusedtosamplethecurrenttexturestage.

Thiscanbeusedforavarietyoftechniquesbasedonaddressperturbationsuchasfakeper-pixelenvironmentmapping.

Thisoperationalwaysinterpretsduanddvassignedquantities.Forversions1.0and1.1,theSignedScalinginputmodifier(_bx2)isnotpermittedontheinputargument.

Page 192: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Thisinstructionproducesdefinedresultswheninputtexturescontainmixedformatdata.Formoreinformationaboutsurfaceformats,seeD3DFORMAT.

//Whenusingthisinstruction,textureregistersmustfollowthefollowingsequence.

//Thetextureassignedtostagetncontainsthe(du,dv)data.

//Thetextureassignedtostaget(m)issampled.

text(n)

texbemlt(m),t(n)wherem>n

//Thisexampleshowsthecalculationsdonewithintheinstruction.

//1.Newvaluesfortextureaddresses(u',v')arecalculated.

//2.Samplethetextureusing(u',v')

//3.Luminancecorrectionisapplied.

u'=TextureCoordinates(stagem)u+D3DTSS_BUMPENVMAT00(stagem)*t(n)

D3DTSS_BUMPENVMAT10(stagem)*t(n)G

v'=TextureCoordinates(stagem)v+D3DTSS_BUMPENVMAT01(stagem)*t(n)

D3DTSS_BUMPENVMAT11(stagem)*t(n)G

t(m)RGBA=TextureSample(stagem)using(u',v')ascoordinates.

t(m)RGBA=t(m)RGBA*[t(n)B*(D3DTSS_BUMPENVLSCALE(stagem)+D3DTSS_BUMPENVLOFFSET(stagem))]

NoteWhenusingtexbemortexbeml,donotre-readthesourceregisterlaterintheshaderbecausethedatawithintheregistermightbecorrupted.Theshadervalidationallowsthiseventhoughtheresultwillbeundefined.

Example

//Hereisanexampleshaderwiththetexturemapsidentifiedand

//thetexturestagesidentified.

ps.1.0

text0;definet0togeta2-tupleDuDv

texbemlt1,t0;compute(u',v')

;applyluminancecorrection

;samplet1using(u',v')

movr0,t1;outputresult

//Thisexamplerequiresthefollowingtexturesinthefollowingtexturestages.

//

//Stage0isassignedabumpmapwith(du,dv)perturbationdata.

Page 193: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//

//Stage1isassignedatexturemapwithcolordata.

//

//texbemlsetsthematrixdataonthetexturestagethatissampled.

//Thisisdifferentfromthefunctionalityofthefixedfunctionpipelinewhere

//theperturbationdataandthematricesoccupythesametexturestage.

Page 194: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 195: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texcoordInterpretstexturecoordinatedata(UVW1)ascolordata(RGBA).

texcoorddest

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructioninterpretsthetexturecoordinateset(UVW1)correspondingtothedestinationregisternumberascolordata(RGBA).Ifthetexturecoordinatesetcontainsfewerthanthreecomponents,themissingcomponentsaresetto0.Thefourthcomponentisalwayssetto1.Allvaluesareclampedbetween0and1.

Theadvantageoftexcoordisthatitprovidesawaytopassvertexdatainterpolatedathighprecisiondirectlyintothepixelshader.However,oncethedataiswrittenintothedestinationregister,someprecisionwillbelost,dependingonthenumberofbitsusedbythehardwareforregisters.

Notextureissampledbythisinstruction.Onlytexturecoordinatessetonthistexturestagearerelevant.

Anytexturedata(suchasposition,normal,andlightsourcedirection)canbemappedbyavertexshaderintoatexturecoordinate.ThisisdonebyassociatingatexturewithatextureregisterusingSetTextureandbyspecifyinghowthetexturesamplingisdoneusingSetTextureStageState.Ifthefixedfunctionpipelineisused,besuretosupplytheTSS_TEXCOORDINDEXflag.

Page 196: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Thisinstructionisusedasfollows:

texcoordtn

//Atextureregister(tn)containsfourcolorvalues(RGBA).Thedatacanalsobe

//thoughtofasvectordata(xyzw).Texcoordwillretrieve3ofthesevalues(xyz)from

//texturecoordinatesetx,andthefourthcomponent(w)issetto1.

//Thetextureaddressiscopiedfromthetexturecoordinatesetn.

//Theresultisclampedbetween0and1.

Example

Thisexampleisforillustrationonly.TheCcodeaccompanyingtheshaderhasnotbeenoptimizedforperformance.ItcanusehelperfunctionsfromtheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

//Hereisanexampleshaderusingtexcoord.

ps.1.0;versioninstruction

texcoordt0;declaret0holdtexturecoordinates,

;whichrepresentrgbavaluesinthisexample

movr0,t0;movethecolorint0tooutputregisterr0

Therenderedoutputfromthepixelshaderisshownbelow.The(u,v,w,1)coordinatevaluesmaptothe(rgb)channels.Thealphachannelissetto1.Atthecornersoftheimage,coordinate(0,0,0,1)isinterpretedasblack,(1,0,0,1)isred,(0,1,0,1)isgreen,and(1,1,0,1)containsgreenandred,producingyellow.

//Additionalcodeisrequiredtousethisshaderandanexample

//scenarioisshownbelow.

//Thiscodecreatestheshaderfromafile.Thecontentsoftheshader

//filecanalsobesuppliedasatextstring.

TCHARstrPShaderPath[512];

LPD3DXBUFFERpCode;

DXUtil_FindMediaFile(strPShaderPath,_T("shaderFile.txt"));

//Assemblethevertexshaderfromthefile.

D3DXAssembleShaderFromFile(strPShaderPath,0,NULL,&pCode;,NULL);

m_pd3dDevice->CreatePixelShader((DWORD*)pCode->GetBufferPointer(),

&m;_hPixelShader);

Page 197: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

pCode->Release();

//Thiscodedefinestheobjectvertexdata.

structCUSTOMVERTEX

{

FLOATx,y,z;

FLOATtu1,tv1;

};

#defineD3DFVF_CUSTOMVERTEX(D3DFVF_XYZ|D3DFVF_TEX1|TEXCOORD2(0))

staticCUSTOMVERTEXg_Vertices[]=

{

//xyzu1v1

{-1.0f,-1.0f,0.0f,0.0f,0.0f,},

{+1.0f,-1.0f,0.0f,1.0f,0.0f,},

{+1.0f,+1.0f,0.0f,1.0f,1.0f,},

{-1.0f,+1.0f,0.0f,0.0f,1.0f,},

};

Page 198: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversion1.4)

Page 199: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texcrdCopiestexturecoordinatedatafromthesourcetexturecoordinateiteratorregisterascolordatainthedestinationregister.

texcrddest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.4

src Sourceregisterx 1.4phase1x 1.4phase2

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructioninterpretscoordinatedataascolordata(RGBA).

Notextureissampledbythisinstruction.Onlytexturecoordinatessetonthistexturestagearerelevant.

Whenusingtexcrd,keepinmindthefollowingdetailabouthowdataiscopiedfromthesourceregistertothedestinationregister.Thesourcetexturecoordinateregister(t#)holdsdataintherange[-D3DCAPS8.MaxTextureRepeat,D3DCAPS8.MaxTextureRepeat],whilethedestinationregister(r#)canholddataonlyinthe(likelysmaller)range[-D3DCAPS8.MaxPixelShaderValue,D3DCAPS8.MaxPixelShaderValue].Notethatforpixelshaderversion1.4,D3DCAPS8.MaxPixelShaderValuemustbeaminimumofeight.Thetexcrdinstruction,intheprocessofclampingsourcedatathatisoutofrangeofthedestinationregister,islikelytobehavedifferentlyondifferenthardware.Thefirstpixelshaderversion1.4hardwareonthemarketwillperformaspecialclampforvaluesoutsideofrange.Thisclampisdesignedtoproduceanumber

Page 200: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

thatcanfitintothedestinationregister,butalsotopreservetextureaddressingbehaviorforout-of-rangedata(seeD3DTEXTUREADDRESS)ifthedataweretobesubsequentlyusedfortexturesampling.However,newhardwarefromdifferentmanufacturersmightnotexhibitthisbehaviorandmightsimplychopdatatofitthedestinationregisterrange.Therefore,thesafestcourseofactionwhenusingpixelshaderversion1.4texcrdistosupplytexturecoordinatedataonlyintothepixelshaderthatisalreadywithintherange[-8,8]sothatyoudonotrelyonthewayhardwareclamps.

Unliketexcoord,texcrddoesnotclampvaluesbetween0and1.

Rulesforusingtexcrd:

1. Thesame.xyzor.xywmodifiermustbeappliedtoeveryreadofanindividualt(n)registerwithinatexcrdortexldinstruction.

2. Thefourthchannelresultoftexcrdisunset/undefinedinallcases.3. Thethirdchannelisunset/undefinedforthexyw_dwcase.

Example

Thecompletesetofallowedsyntaxfortexcrd,takingintoaccountallvalidsourcemodifier/selectoranddestinationwritemaskcombinations,isshownbelow.Notethatthe.rgbaand.xyzwnotationcanbeusedinterchangeably.

texcrdr(m).rgb,t(n).xyz

//Copiesfirstthreechannelsoftexturecoordinateiteratorregister,

//t(n),intor(m).Thefourthchannelof

//r(m)isuninitialized.

texcrdr(m).rgb,t(n)

//Producesthesameresultasthepreviousinstruction.

texcrdr(m).rgb,t(n).xyw

//Putsfirst,second,andfourthcomponentsoft(n)intofirstthreechannels

//ofr(m).Thefourthchannelofr(m)isuninitialized.

//Hereisaprojectivedivideexampleusingthe_dwmodifier.

texcrdr(m).rg,t(n)_dw.xyw

//Thisexamplecopiesx/wandy/wfromt(n)intothe

//firsttwochannelsofr(m).Thethirdandfourth

//channelsofr(m)areuninitialized.Anydatapreviously

//writtentothethirdchannelofr(m)willbelost.Data

Page 201: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//inthefourthchannelofr(m)islostduetothephase

//marker.Forversion1.4,theD3DTTFF_PROJECTEDflagisignored.

Page 202: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversion1.4)

Page 203: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texdepthCalculatedepthvaluestobeusedinthedepthbuffercomparisontestforthispixel.

texdepthdest

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister r5 1.4phase2only

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionusesr5.r/r5.ginthedepthbuffercomparisontestforthispixel.Thedataintheblueandalphachannelsisignored.Ifr5.g=0,theresultofr5.r/r5.g=1.0.

Temporaryregisterr5istheonlyregisterthatthisinstructioncanuse.

Afterexecutingthisinstruction,temporaryregisterr5isunavailableforadditionaluseintheshader.

Whenmultisampling,usingthisinstructioneliminatesmostofthebenefitofthehigherresolutiondepthbuffer.Becausethepixelshaderexecutesonceperpixel,thesingledepthvalueoutputbytexm3x2depthortexdepthwillbeusedforeachofthesub-pixeldepthcomparisontests.

Example

Hereisanexampleusingtexdepth.

ps.1.4

Page 204: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texldr0,t0//Sampletexturefromtexturestage0(dest

//registernumber)intor0.

//Usetexturecoordinatedatafromt0.

texcrdr1.rgb,t1//Loadasecondsetoftexturecoordinatedataintor1.

addr5.rg,r0,r1//Addthetwosetsoftexturecoordinatedata.

phase//Phasemarker,requiredwhenusingtexdepthinstruction.

texdepthr5//Calculatepixeldepthasr5.r/r5.g.

//Doothercolorcalculationswithshaderoutputr0.

Page 205: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.2and1.3)

Page 206: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texdp3Performsathree-componentdotproductbetweendatainthetextureregisternumberandthetexturecoordinatesetcorrespondingtothedestinationregisternumber.

texdp3dest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.2,1.3src Sourceregister x 1.2,1.3

Remarks

Textureregistersmustusethefollowingsequence.

text(n)//Definetnasastandard3-vector(tnmustbe

//definedinsomewaybeforetexdp3usesit).

texdp3t(m),t(n)//wherem>n

//Performathree-componentdotproductbetweentnand

//thetexturecoordinatesetm.Thescalarresultis

//replicatedtoallcomponentsoft(m).

Hereismoredetailabouthowthedotproductisaccomplished.

//Thetexdp3instructionperformsathree-componentdotproductand

//replicatesittoallfourcolorchannels.

t(m)RGBA=TextureCoordinates(stagem)UVW•t(n)RGB

Page 207: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.2and1.3)

Page 208: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texdp3texPerformsathree-componentdotproductandusestheresulttodoa1-Dtexturelookup.

texdp3texdest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.2,1.3src Sourceregister x 1.2,1.3

Remarks

Textureregistersmustusethefollowingsequence.

text(n)//Definetnasastandard3-vector(tnmustbe

//definedinsomewaybeforetexdp3texusesit).

texdp3text(m),t(n)//wherem>n.

//Performathree-componentdotproductbetweent(n)and

//thetexturecoordinatesetm.Usethescalarresultto

//doa1-Dtexturelookupattexturestagemandplace

//theresultint(m).

Hereismoredetailabouthowthedotproductandtexturelookuparedone.

//Thetexdp3texinstructionperformsathree-componentdotproduct.

u'=TextureCoordinates(stagem)UVW•t(n)RGB

//Theresultisusedtosamplethetextureattexturestagembyperforming

//a1-Dlookup.

t(m)RGBA=TextureSample(stagem)RGBAusing(u',0,0)ascoordinates.

Page 209: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 210: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texkilltexkillsrc

Cancelsrenderingofthecurrentpixelifanyofthefirstthreecomponents(UVW)ofthetexturecoordinatesislessthanzero.

Registers

Argument DescriptionRegisters

Versionvn cn tn rn

src Sourceregisterx 1.0,1.1,1.2,1.3x x 1.4phase2only

Tolearnmoreaboutregisters,seeRegisters.

Remarks

texkilldoesnotsampleanytexture.Itoperatesonthefirstthreecomponentsofthetexturecoordinatesgivenbythesourceregisternumber.Forps1.4,texkilloperatesonthedatainthefirstthreecomponentsofthesourceregister.

Youcanusethisinstructiontoimplementarbitraryclipplanesintherasterizer.

Whenusingvertexshaders,theapplicationisresponsibleforapplyingtheperspectivetransform.Thiscancauseproblemsforthearbitraryclippingplanesbecauseifitcontainsanisomorphicscalefactors,theclipplanesneedtobetransformedaswell.Therefore,itisbesttoprovideanunprojectedvertexpositiontouseinthearbitraryclipper,whichisthetexturecoordinatesetidentifiedbythetexkilloperator.

//Thisinstructionisusedasfollows:

texkilltn

//Thepixelmaskingisaccomplishedasfollows:

if(anyofthefirst3componentsofTextureCoordinates(stagen)UVWQ

cancelpixelrender

Page 211: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Forps1.0,1.1,1.2,and1.3,texkilloperatesonthetexturecoordinatesetgivenbythesourceregisternumber.Inversion1.4,however,texkilloperatesonthedatacontainedinthetexturecoordinateiteratorregister(tn)orinthetemporaryregister(rn)thathasbeenspecifiedasthesource.

Whenmultisamplingisenabled,anyantialiasingeffectachievedonpolygonedgesduetomultisamplingwillnotbeachievedalonganyedgethathasbeengeneratedbytexkill.Thepixelshaderrunsonceperpixel.

Example

Thisexampleisforillustrationonly.

//Thisexamplemasksoutpixelsthathavenegativetexturecoordinates.Thepixel

//colorsareinterpolatedfromvertexcolorsprovidedinthevertexdata.

//Theshaderisshownbelow.

ps.1.0//versioninstruction

texkillt0//Maskoutpixelusingtexturecoordinatesfromstage0.

movr0,v0//Movethediffusecolorinv0tor0.

//Therenderedoutputfromthepixelshaderisshownbelow.Itshows

//vertexcolordataappliedtoaplane.Thetexturecoordinatedata

//isdeclaredinthevertexdatadeclarationinthisexample.

structCUSTOMVERTEX

{

FLOATx,y,z;

DWORDcolor;

FLOATtu1,tv1;

};

#defineD3DFVF_CUSTOMVERTEX(D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1|D3DTEXCOORD2(0))

staticCUSTOMVERTEXg_Vertices[]=

{

//xyzcoloru1,v1

{-1.0f,-1.0f,0.0f,0xffff0000,-0.5f,1.0f,},

{1.0f,-1.0f,0.0f,0xff00ff00,0.5f,1.0f,},

{1.0f,1.0f,0.0f,0xff0000ff,0.5f,0.0f,},

{-1.0f,1.0f,0.0f,0xffffffff,-0.5f,0.0f,},

};

//Thetexturecoordinatesrangefrom-0.5to0.5inu,and0.0to1.0inv.

//Thisinstructioncausesthenegativeuvaluesgetmaskedout.

//Thefirstimageshowsthevertexcoloredappliedtothequadwithoutthe

Page 212: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//texkillinstructionapplied.

//Thesecondimageshowstheresultofthetexkillinstruction.Thepixelcolors

//fromthetexturecoordinatesbelow0(wherexgoesfrom-0.5to0.0)aremasked

//out.Thebackgroundcolor(white)isusedwherethepixelcolorismasked.

Page 213: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectx8.1(pixelshaderversion1.4)

Page 214: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texldLoadsthedestinationregisterwithcolordata(RGBA)sampledusingthecontentsofthesourceregisterastexturecoordinates.Thesampledtextureisthetextureassociatedwiththedestinationregisternumber.

texlddest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.4

src Sourceregisterx 1.4phase1x x 1.4phase2

Whenusingr(n)asasourceregister,thefirstthreecomponents(XYZ)musthavebeeninitializedinthepreviousphaseoftheshader.

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionsamplesthetextureinthetexturestageassociatedwiththedestinationregisternumber.Thetextureissampledusingtexturecoordinatedatafromthesourceregister.

ThesyntaxforthetexldandtexcrdinstructionsexposesupportforaprojectivedividewithaTextureRegisterModifier.Forpixelshaderversion1.4,theD3DTTFF_PROJECTEDtexturetransformflagsisalwaysignored.

Rulesforusingtexld:

1. Thesame.xyzor.xywmodifiermustbeappliedtoeveryreadofanindividualt(n)registerwithinbothtexcrdortexldinstructions.If.xywis

Page 215: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

beingusedont(n)registerread(s),thiscanbemixedwithotherread(s)ofthesamet(n)registerusing.xyw_dw.

2. The_dzsourcemodifierisonlyvalidontexldwithr(n)sourceregister(thusphase2only).

3. The_dzsourcemodifiermaybeusednomorethantwotimespershader.

Examples

Thetexldinstructionofferssomecontroloverwhichcomponentsofthesourcetexturecoordinatedataareused.Thecompletesetofallowedsyntaxfortexldfollows,andincludesallvalidsourceregistermodifiers,selectors,andwritemaskcombinations.

texldr(m),t(n).xyz

//Usesxyzfromt(n)tosample1-D,2-D,or3-Dtexture.

texldr(m),t(n)

//Sameasprevious.

texldr(m),t(n).xyw

//Usesxyw(skippingz)fromt(n)tosample1-D,2-Dor3-Dtexture.

texldr(m),t(n)_dw.xyw

//Samples1-Dor2-Dtextureatx/w,y/wfromt(n).Theresult

//isundefinedforacube-maplookup.

texldr(m),r(n).xyz

//Samples1-D,2-D,or3-Dtextureatxyzfromr(m).

//Thisispossibleinthesecondphaseoftheshader.

texldr(m),r(n)

//Sameasprevious.

texldr(m),r(n)_dz.xyz

//Samples1-Dor2-Dtextureatx/z,y/zfromr(m).

//Possibleonlyinsecondphase.

//Theresultisundefinedforacube-maplookup.

texldr(n),r(n)_dz

//Sameasprevious.

Page 216: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversion1.3)

Page 217: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texm3x2depthCalculatethedepthvaluetobeusedindepthtestingforthispixel.

texm3x2depthdest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.3src Sourceregister x 1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionmustbeusedwiththetexm3x2padinstruction.

Whenusingthesetwoinstructions,textureregistersmustusethefollowingsequence.

text(n)//Definetnasastandard3-vector.(tnmustbe

//definedinsomewaybeforeitisused.

texm3x2padt(m),t(n)//Wherem>n

//Calculatezvalue.

texm3x2deptht(m+1),t(n)//Calculatewvalue;usebothzandwto

//finddepth.

Thedepthcalculationisdoneafterusingadotproductoperationtofindzandw.Hereismoredetailabouthowthedepthcalculationisaccomplished.

//Thetexm3x2padinstructioncalculatesz.

z=TextureCoordinates(stagem)UVW•t(n)RGB

//Thetexm3x2depthinstructioncalculatesw.

w=TextureCoordinates(stagem+1)UVW•t(n)RGB

Page 218: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Calculatedepthandstoretheresultint(m+1).

if(w==0)

t(m+1)=1.0

else

t(m+1)=z/w

Thecalculateddepthistaggedtobeusedinthedepthtestforthepixel,replacingtheexistingdepthtestvalueforthepixel.

Besuretoclampz/wtobeintherangeof(0-1).Ifz/wisoutsidethisrange,theresultstoredinthedepthbufferwillbeundefined.

Afterexecutingtex3x2depth,registert(m+1)isnolongeravailableforuseintheshader.

Whenmultisampling,usingthisinstructioneliminatesmostofthebenefitofthehigherresolutiondepthbuffer.Becausethepixelshaderexecutesonceperpixel,thesingledepthvalueoutputbytexm3x2depth/texdepthwillbeusedforeachofthesub-pixeldepthcomparisontests.

Page 219: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 220: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texm3x2padPerformsthefirstrowmultiplicationofatwo-rowmatrixmultiply.Thisinstructionmustbecombinedwitheithertexm3x2texortexm3x2depth.Refertoeitheroftheseinstructionsfordetailsonusingtexm3x2pad.

texm3x2paddest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3src Sourceregister x 1.0,1.1,1.2,1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructioncannotbeusedbyitself.

Page 221: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 222: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texm3x2texPerformsthefinalrowofa3×2matrixmultiplyandusestheresulttodoatexturelookup.texm3x2texmustbeusedinconjunctionwiththetexm3x2padinstruction.

texm3x2texdest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3src Sourceregister x 1.0,1.1,1.2,1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Theinstructionisusedasoneoftwoinstructionsrepresentinga3×2matrixmultiplyoperation.Thisinstructionmustbeusedwiththetexm3x2pad.

Whenusingthesetwoinstructions,textureregistersmustusethefollowingsequence.

text(n)//Definetnasastandard3-vector(tnmust

//bedefinedinsomewaybeforeitisused).

texm3x2padt(m),t(n)//wherem>n

//Performfirstrowofmatrixmultiply.

texm3x2text(m+1),t(n)//Performsecondrowofmatrixmultiply

//toget(u,v)tosampletexture

//associatedwithstagem+1.

Hereismoredetailabouthowthe3×2multiplyisaccomplished.

//Thetexm3x2padinstructionperformsthefirstrowofthemultiplytofindu

u'=t(n)RGB•TextureCoordinates(stagem)UVW

Page 223: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Thetexm3x2texinstructionperformsthesecondrowofthemultiplytofindv

v'=t(n)RGB•TextureCoordinates(stagem+1)UVW

//Thetexm3x2texinstructionsamplesthetextureonstage(m+1)with(u

//storestheresultint(m+1).

t(m+1)RGB=TextureSample(stagem+1)RGBusing(u',v')ascoordinates.

Example

//Hereisanexampleshaderwiththetexturemapsand

//thetexturestagesidentified.

ps.1.0

text0//Bindtextureinstage0toregistert0.

texm3x2padt1,t0//Firstrowofmatrixmultiply.

texm3x2text2,t0//Secondrowofmatrixmultiplytoget(u,v)

//withwhichtosampletextureinstage2.

movr0,t2//Outputresult.

//Thisexamplerequiresthefollowingtexturesinthefollowingtexturestages.

//

//Stage0takesamapwith(x,y,z)perturbationdata.

//

//Stage1holdstexturecoordinates.Notextureisrequiredinthetexturestage.

//

//Stage2holdsbothtexturecoordinatesaswellasa2-Dtexturesetat

//thattexturestage.

Page 224: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.2and1.3)

Page 225: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texm3x3Performsa3×3matrixmultiplywhenusedinconjunctionwithtwotexm3x3padinstructions.

texm3x3dest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.2,1.3src Sourceregister x 1.2,1.3

Remarks

Thisinstructionisthesameasthetexm3x3texinstruction,withoutthetexturelookup.

Thisinstructionisusedasthefinalofthreeinstructionsrepresentinga3×3matrixmultiplyoperation.The3×3matrixiscomprisedofthetexturecoordinatesofthethirdtexturestage,andbythetwoprecedingtexturestages.Anytextureassignedtoanyofthethreetexturestagesisignored.

Thisinstructionmustbeusedwithtwotexm3x3padinstructions.Textureregistersmustfollowthefollowingsequence.

text(n)//Definetnasastandard3-vector(tnmust

//bedefinedinsomewaybeforeitisused).

texm3x3padt(m),t(n)//wherem>n

//Performfirstrowofmatrixmultiply.

texm3x3padt(m+1),t(n)//Performsecondrowofmatrixmultiply.

texm3x3t(m+2),t(n)//Performthirdrowofmatrixmultiplytogeta

//3-vectorresult.

Hereismoredetailabouthowthe3×3multiplyisaccomplished.

Page 226: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Thefirsttexm3x3padinstructionperformsthefirstrowofthemultiply

//tofindu'.

u'=TextureCoordinates(stagem)UVW•t(n)RGB

//Thesecondtexm3x3padinstructionperformsthesecondrowofthemultiply

//tofindv'.

v'=TextureCoordinates(stagem+1)UVW•t(n)RGB

//Thetexm3x3texinstructionperformsthethirdrowofthemultiply

//tofindw'.

w'=TextureCoordinates(stagem+2)UVW•t(n)RGB

//Placetheresultofthematrixmultiplyinthedestinationregister.

t(m+2)RGBA=(u',v',w',1)

Page 227: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 228: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texm3x3padPerformsthefirstorsecondrowmultiplyofathree-rowmatrixmultiply.Thisinstructionmustbeusedincombinationwithtexm3x3,texm3x3spec,texm3x3vspec,ortexm3x3tex.

texm3x3paddest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3src Sourceregister x 1.0,1.1,1.2,1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructioncannotbeusedbyitself.

Page 229: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 230: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texm3x3texPerformsa3×3matrixmultiplyandusestheresulttodoatexturelookup.texm3x3texmustbeusedwithtwotexm3x3padinstructions.

texm3x3texdest,src

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3src Sourceregister x 1.0,1.1,1.2,1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionisusedasthefinalofthreeinstructionsrepresentinga3×3matrixmultiplyoperation,followedbyatexturelookup.The3×3matrixiscomprisedofthetexturecoordinatesofthethirdtexturestageandthetwoprecedingtexturestages.Theresultingthree-componentvector(u,v,w)isusedtosamplethetextureinstage3.Anytextureassignedtotheprecedingtwotexturestagesisignored.The3×3matrixmultiplyistypicallyusefulfororientinganormalvectortothecorrecttangentspaceforthesurfacebeingrendered.

Thisinstructionmustbeusedwithtwotexm3x3padinstructions.Textureregistersmustusethefollowingsequence.

text(n)//Definetnasastandard3-vector(tnmust

//bedefinedinsomewaybeforeitisused).

texm3x3padt(m),t(n)//wherem>n

//Performfirstrowofmatrixmultiply.

texm3x3padt(m+1),t(n)//Performsecondrowofmatrixmultiply.

texm3x3text(m+2),t(n)//Performthirdrowofmatrixmultiplytogeta

//3-vectorwithwhichtosampletexture

//associatedwithtexturestagem+2.

Hereismoredetailabouthowthe3×3multiplyisaccomplished.

Page 231: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Thefirsttexm3x3padinstructionperformsthefirstrowofthemultiply

//tofindu'.

u'=TextureCoordinates(stagem)UVW•t(n)RGB

//Thesecondtexm3x3padinstructionperformsthesecondrowofthemultiply

//tofindv'.

v'=TextureCoordinates(stagem+1)UVW•t(n)RGB

//Thetexm3x3specinstructionperformsthethirdrowofthemultiply

//tofindw'.

w'=TextureCoordinates(stagem+2)UVW•t(n)RGB

//Lastly,thetexm3x3texinstructionsamplest(m+2)with(u',v',w')

//andstorestheresultint(m+2).

t(m+2)RGBA=TextureSample(stagem+2)RGBAusing(u',v',w')ascoordinates.

Example

//Hereisanexampleshaderwiththetexturemapsidentifiedand

//thetexturestagesidentified.

ps.1.0

text0//Bindtextureinstage0toregistert0.

texm3x3padt1,t0//Firstrowofmatrixmultiply.

texm3x3padt2,t0//Secondrowofmatrixmultiply.

texm3x3text3,t0//Thirdrowofmatrixmultiplytogeta

//3-vectorwithwhichtosampletextureatstage3

movr0,t3//outputresult.

//Thisexamplerequiresthefollowingtexturestagesetup.

//

//Stage0isassignedatexturemapwithnormaldata.Thisisoften

//referredtoasabumpmap.Thedatais(XYZ)normalsfor

//eachtexel.Texturecoordinateset0defineshowtosamplethis

//normalmap.

//

//Texturecoordinateset1isassignedtorow1ofthe3×3matrix.

//Anytextureassignedtostage1isignored.

//

//Texturecoordinateset2isassignedtorow2ofthe3×3matrix.

//Anytextureassignedtostage2isignored.

//

//Texturecoordinateset3isassignedtorow3ofthe3×3matrix.

//Avolumeorcubetextureshouldbesettostage3forlookupbythe

//transformed3-Dvector.

//

Page 232: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 233: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texm3x3specPerformsa3×3matrixmultiplyandusestheresulttoperformatexturelookup.Thiscanbeusedforspecularreflectionandenvironmentmapping.texm3x3specmustbeusedinconjunctionwithtwotexm3x3padinstructions.

texm3x3specdest,src0,src1,src2

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3src0,src1

Sourceregisterx 1.0,1.1,1.2,1.3

src2 x 1.0,1.1,1.2,1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionperformsthefinalrowofa3×3matrixmultiply,usestheresultingvectorasanormalvectortoreflectaneye-rayvector,andthenusesthereflectedvectortoperformatexturelookup.Theshaderreadstheeye-rayvectorfromaconstantregister.The3×3matrixmultiplyistypicallyusefulfororientinganormalvectortothecorrecttangentspaceforthesurfacebeingrendered.

The3×3matrixiscomprisedofthetexturecoordinatesofthethirdtexturestageandthetwoprecedingtexturestages.Theresultingpostreflectionvector(u,v,w)isusedtosamplethetextureonthefinaltexturestage.Anytextureassignedtotheprecedingtwotexturestagesisignored.

Thisinstructionmustbeusedwithtwotexm3x3padinstructions.Textureregistersmustusethefollowingsequence.

text(n)//Definetnasastandard3-vector(tnmust

//bedefinedinsomewaybeforeitisused).

Page 234: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texm3x3padt(m),t(n)//wherem>n

//Performfirstrowofmatrixmultiply.

texm3x3padt(m+1),t(n)//Performsecondrowofmatrixmultiply.

texm3x3spect(m+2),t(n),c0//Performthirdrowofmatrixmultiply.

//Thendoatexturelookuponthetexture

//associatedwithtexturestagem+2.

//Thefirsttexm3x3padinstructionperformsthefirstrowofthemultiply

//tofindu'.

u'=TextureCoordinates(stagem)UVW•t(n)RGB

//Thesecondtexm3x3padinstructionperformsthesecondrowofthemultiply

//tofindv'.

v'=TextureCoordinates(stagem+1)UVW•t(n)RGB

//Thetexm3x3specinstructionperformsthethirdrowofthemultiply

//tofindw'.

w'=TextureCoordinates(stagem+2)UVW•t(n)RGB

//Thetexm3x3specinstructionthendoesareflectioncalculation.

(u'',v'',w'')=2*[(N•E)/(N•N)]*N-E

//wherethenormalNisgivenby

//N=(u',v',w')

//andtheeye-rayvectorEisgivenbytheconstantregister

//E=c#(Anyconstantregister--c0,c1,c2,etc.--canbeused.)

//Lastly,thetexm3x3specinstructionsamplest(m+2)with(u'',v'',w

//andstorestheresultint(m+2).

t(m+2)RGBA=TextureSample(stagem+2)RGBAusing(u'',v'',w'')ascoordinates.

Example

//Hereisanexampleshaderwiththetexturemapsand

//thetexturestagesidentified.

ps.1.0

text0//Bindtextureinstage0toregistert0(tnmust

//bedefinedinsomewaybeforeitisused).

texm3x3padt1,t0//Firstrowofmatrixmultiply.

texm3x3padt2,t0//Secondrowofmatrixmultiply.

texm3x3spect3,t0,c#//Thirdrowofmatrixmultiplytogeta3-vector.

//Reflect3-vectorbytheeye-rayvectorinc#.

//Usereflectedvectortolookuptexturein

//stage3

movr0,t3//outputresult

//Thisexamplerequiresthefollowingtexturestagesetup.

Page 235: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//

//Stage0isassignedatexturemapwithnormaldata.Thisisoften

//referredtoasabumpmap.Thedatais(XYZ)normalsfor

//eachtexel.Texturecoordinatesatstagendefineswheretosamplethis

//normalmap.

//

//Texturecoordinatesetmisassignedtorow1ofthe3×3matrix.

//Anytextureassignedtostagemisignored.

//

//Texturecoordinatesetm+1isassignedtorow2ofthe3×3matrix.

//Anytextureassignedtostagem+1isignored.

//

//Texturecoordinatesetm+2isassignedtorow3ofthe3×3matrix.

//Stagem+2isassignedavolumeorcubetexturemap.Thetextureprovides

//colordata(RGBA).

//

//Theeye-rayvectorEisgivenbya

//constantregisterE=c#.

Page 236: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 237: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texm3x3vspecPerformsa3×3matrixmultiplyandusestheresulttoperformatexturelookup.Thiscanbeusedforspecularreflectionandenvironmentmappingwheretheeye-rayvectorisnotconstant.texm3x3vspecmustbeusedinconjunctionwithtwotexm3x3padinstructions.

Iftheeye-rayvectorisconstant,thetexm3x3specinstructionwillperformthesamematrixmultiplyandtexturelookup.

texm3x3vspecdest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3src Sourceregister x 1.0,1.1,1.2,1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionperformsthefinalrowofa3×3matrixmultiplyoperation,interpretstheresultingvectorasanormalvectortoreflectaneye-rayvector,andthenusesthereflectedvectorasatextureaddressforatexturelookup.Itworksjustliketexm3x3spec,exceptthattheeye-rayvectoristakenfromthefourthcomponentofthetexturecoordinates.The3×3matrixmultiplyistypicallyusefulfororientinganormalvectortothecorrecttangentspaceforthesurfacebeingrendered.

The3×3matrixiscomprisedofthetexturecoordinatesofthethirdtexturestageandthetwoprecedingtexturestages.Theresultingpost-reflectionvector(UVW)isusedtosamplethetextureinstage3.Anytextureassignedtotheprecedingtwotexturestagesisignored.

Page 238: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Thisinstructionmustbeusedwiththetexm3x3padinstruction.Textureregistersmustusethefollowingsequence.

text(n)//Definetnasastandard3-vector(tnmust

//bedefinedinsomewaybeforeitisused).

texm3x3padt(m),t(n)//wherem>n

//Performfirstrowofmatrixmultiply.

texm3x3padt(m+1),t(n)//Performsecondrowofmatrixmultiply.

texm3x3vspect(m+2),t(n)//Performthirdrowofmatrixmultiply.

//Thendoatexturelookuponthetexture

//associatedwithtexturestagem+2.

//Thefirsttexm3x3padinstructionperformsthefirstrowofthemultiply

//tofindu'.

u'=TextureCoordinates(stagem)UVW•t(n)RGB

//Thesecondtexm3x3padinstructionperformsthesecondrowofthemultiply

//tofindv'.

v'=TextureCoordinates(stagem+1)UVW•t(n)RGB

//Thetexm3x3specinstructionperformsthethirdrowofthemultiply

//tofindw'.

w'=TextureCoordinates(stagem+2)UVW•t(n)RGB

//Thetexm3x3vspecinstructionalsodoesareflectioncalculation.

(u'',v'',w'')=2*[(N•E)/(N•N)]*N-E

//wherethenormalNisgivenby

//N=(u',v',w')

//andtheeye-rayvectorEisgivenby

//E=(TextureCoordinates(stagem)Q,TextureCoordinates(stagem+1)Q,TextureCoordinates(stagem+2)

//Lastly,thetexm3x3vspecinstructionsamplest(m+2)with(u'',v'',w

//andstorestheresultint(m+2).

t(m+2)RGBA=TextureSample(stagem+2)RGBAusing(u'',v'',w'')ascoordinates.

Example

//Hereisanexampleshaderwiththetexturemapsidentifiedand

//thetexturestagesidentified.

ps.1.0

text0//Bindtextureinstage0toregistert0.

texm3x3padt1,t0//Firstrowofmatrixmultiply.

texm3x3padt2,t0//Secondrowofmatrixmultiply.

texm3x3vspect3,t0//Thirdrowofmatrixmultiplytogeta3-vector.

//Reflect3-vectorbytheeye-rayvector.

Page 239: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Usereflectedvectortodoatexturelookup

//atstage3.

movr0,t3//Outputresult.

//Thisexamplerequiresthefollowingtexturestagesetup.

//

//Stage0isassignedatexturemapwithnormaldata.Thisisoften

//referredtoasabumpmap.Thedatais(XYZ)normalsfor

//eachtexel.Texturecoordinatesatstagendefineshowtosamplethis

//normalmap.

//

//Texturecoordinatesetmisassignedtorow1ofthe3×3matrix.

//Anytextureassignedtostagemisignored.

//

//Texturecoordinatesetm+1isassignedtorow2ofthe3×3matrix.

//Anytextureassignedtostagem+1isignored.

//

//Texturecoordinatesetm+2isassignedtorow3ofthe3×3matrix.

//Stagem+2isassignedavolumeorcubetexturemap.Thetextureprovides

//colordata(RGBA).

//

//Theeye-rayvectorEispassedintotheinstructioninthefourth

//component(q)ofthetexturecoordinatedataatstagesm,m+1,andm+2.

Page 240: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 241: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texreg2arInterpretsthealphaandredcolorcomponentsofthesourceregisterastextureaddressdata(u,v)tosamplethetextureatthestagecorrespondingtothedestinationregisternumber.Theresultisstoredinthedestinationregister.

texreg2ardest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3src Sourceregister x 1.0,1.1,1.2,1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionisusefulforcolor-spaceremappingoperations.

//Hereisanexampleofthesequencetheinstructionfollows.

text(n)

texreg2art(m),t(n)wherem>n

//Hereismoredetailabouthowtheremappingisaccomplished.

//Thefirstinstructionloadsthetexturecolor(RGBA)intoregistertn.

textn

//Thesecondinstructionremapsthecolor.

t(m)RGBA=TextureSample(stagem)RGBAusingt(n)ARascoordinates.

Forthisinstruction,thesourceregistermustuseunsigneddata.Useofsignedormixeddatainthesourceregisterwillproduceundefinedresults.Formoreinformation,seeD3DFORMAT.

Page 242: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3)

Page 243: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texreg2gbInterpretsthegreenandbluecolorcomponentsofthesourceregisterastextureaddressdatatosamplethetextureatthestagecorrespondingtothedestinationregisternumber.

texreg2gbdest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.0,1.1,1.2,1.3src Sourceregister x 1.0,1.1,1.2,1.3

Tolearnmoreaboutregisters,seeRegisters.

Remarks

Thisinstructionisusefulforcolor-spaceremappingoperations.

//Hereisanexampleofthesequencetheinstructionfollows.

text(n)

texreg2gbt(m),t(n)wherem>n

//Hereismoredetailabouthowtheremappingisaccomplished.

//Thefirstinstructionloadsthetexturecolor(RGBA)intoregistertn.

textn

//Thesecondinstructionremapsthecolor.

t(m)RGBA=TextureSample(stagem)RGBAusingt(n)GBascoordinates.

Forthisinstruction,thesourceregistermustuseunsigneddata.Useofsignedormixeddatainthesourceregisterwillproduceundefinedresults.Formoreinformation,seeD3DFORMAT.

Page 244: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.2and1.3)

Page 245: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texreg2rgbInterpretsthered,green,andblue(RGB)colorcomponentsofthesourceregisterastextureaddressdatainordertosamplethetextureatthestagecorrespondingtothedestinationregisternumber.Theresultisstoredinthedestinationregister.

texreg2rgbdest,src

Registers

Argument DescriptionRegisters

Versionvn cn tn rndest Destinationregister x 1.2,1.3src Sourceregister x 1.2,1.3

Remarks

Thisinstructionisusefulforcolor-spaceremappingoperations.Itsupportstwo-dimensional(2-D)andthree-dimensional(3-D)coordinates.Itcanbeusedjustlikethetexreg2arortexreg2gbtoremap2-Ddata.However,thisinstructionalsosupports3-Ddatasoitcanbeusedwithcubemapsand3-Dvolumetextures.

//Hereisanexampleofthesequencetheinstructionfollows.

text(n)

texreg2rgbt(m),t(n)wherem>n

Hereismoredetailabouthowtheremappingisaccomplished.

//Thefirstinstructionloadsthetexturecolor(RGBA)intoregistertn.

textn

//Thesecondinstructionremapsthecolor.

t(m)RGB=TextureSample(stagem)RGBusingt(n)RGBascoordinates.

Page 246: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 247: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirect3DDevice8::SetPixelShaderConstantSetsthevaluesinthepixelconstantarray.

HRESULTSetPixelShaderConstant(

DWORDRegister,

CONSTvoid*pConstantData,

DWORDConstantCount

);

Parameters

Register[in]Registeraddressatwhichtostartloadingdataintothepixelconstantarray.

pConstantData[in]Pointertothedatablockholdingthevaluestoloadintothepixelconstantarray.Thesizeofthedatablockis(ConstantCount*4*sizeof(float)).

ConstantCount[in]Numberofconstantstoloadintothepixelconstantarray.Eachconstantiscomprisedoffourfloating-pointvalues.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisD3D_OK.

Ifthemethodfails,thereturnvaluecanbeD3DERR_INVALIDCALL.

Remarks

Thisisthemethodusedtoloadtheconstantregistersofthepixelshaderassembler.

Requirements

Page 248: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Header:DeclaredinD3d8.h.ImportLibrary:UseD3d8.lib.

SeeAlso

IDirect3DDevice8::GetPixelShaderConstant

Page 249: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 250: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirect3DDevice8::CreatePixelShaderCreatesapixelshader.

HRESULTCreatePixelShader(

CONSTDWORD*pFunction,

DWORD*pHandle

);

Parameters

pFunction[in]Pointertothepixelshaderfunctiontokenarray,specifyingtheblendingoperations.ThisvaluecannotbeNULL.

pHandle[out,retval]Pointertothereturnedpixelshaderhandle.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisD3D_OK.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowingvalues.

D3DERR_INVALIDCALLD3DERR_OUTOFVIDEOMEMORYE_OUTOFMEMORY

Requirements

Header:DeclaredinD3d8.h.ImportLibrary:UseD3d8.lib.

SeeAlso

IDirect3DDevice8::DeletePixelShader,D3DXAssembleShader,D3DXAssembleShaderFromFile

Page 251: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 252: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXAssembleShaderAssemblesanASCIIdescriptionofashaderintobinaryform,wheretheshadersourceisinmemory.

HRESULTD3DXAssembleShader(

LPCVOIDpSrcData,

UINTSrcDataLen,

DWORDFlags,

LPD3DXBUFFER*ppConstants,

LPD3DXBUFFER*ppCompiledShader,

LPD3DXBUFFER*ppCompilationErrors

);

Parameters

pSrcData[in]Pointertothesourcecode.

SrcDataLen[in]Sizeofthesourcecode,inbytes.

Flags[in]AcombinationoftheD3DXASMflags,specifyingassemblyoptions.

ppConstants[out]ReturnsapointertoanID3DXBufferinterface,representingthereturnedconstantdeclarations.Theseconstantsarereturnedasavertexshaderdeclarationfragment.Itisuptotheapplicationtoinsertthecontentsofthisbufferintotheirdeclaration.Forpixelshadersthisparameterismeaninglessbecauseconstantdeclarationsareincludedintheassembledshader.ThisparameterisignoredifitisNULL.

ppCompiledShader[out]ReturnsapointertoanID3DXBufferinterface,representingthereturnedcompiledobjectcode.ThisparameterisignoredifitisNULL.

ppCompilationErrors[out]ReturnsapointertoanID3DXBufferinterface,representingthereturnedASCIIerrormessages.ThisparameterisignoredifitisNULL.

ReturnValues

Page 253: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Ifthefunctionsucceeds,thereturnvalueisD3D_OK.

Ifthefunctionfails,thereturnvaluecanbeoneofthefollowingvalues.

D3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Requirements

Header:DeclaredinD3dx8core.h.ImportLibrary:UseD3dx8.lib.

Page 254: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 255: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DCAPS8RepresentsthecapabilitiesofthehardwareexposedthroughtheMicrosoft®Direct3D®object.

typedefstruct_D3DCAPS8{

D3DDEVTYPEDeviceType;

UINTAdapterOrdinal;

DWORDCaps;

DWORDCaps2;

DWORDCaps3;

DWORDPresentationIntervals;

DWORDCursorCaps;

DWORDDevCaps;

DWORDPrimitiveMiscCaps;

DWORDRasterCaps;

DWORDZCmpCaps;

DWORDSrcBlendCaps;

DWORDDestBlendCaps;

DWORDAlphaCmpCaps;

DWORDShadeCaps;

DWORDTextureCaps;

DWORDTextureFilterCaps;

DWORDCubeTextureFilterCaps;

DWORDVolumeTextureFilterCaps;

DWORDTextureAddressCaps;

DWORDVolumeTextureAddressCaps;

DWORDLineCaps;

DWORDMaxTextureWidth,MaxTextureHeight;

DWORDMaxVolumeExtent;

DWORDMaxTextureRepeat;

DWORDMaxTextureAspectRatio;

DWORDMaxAnisotropy;

floatMaxVertexW;

floatGuardBandLeft;

floatGuardBandTop;

floatGuardBandRight;

Page 256: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

floatGuardBandBottom;

floatExtentsAdjust;

DWORDStencilCaps;

DWORDFVFCaps;

DWORDTextureOpCaps;

DWORDMaxTextureBlendStages;

DWORDMaxSimultaneousTextures;

DWORDVertexProcessingCaps;

DWORDMaxActiveLights;

DWORDMaxUserClipPlanes;

DWORDMaxVertexBlendMatrices;

DWORDMaxVertexBlendMatrixIndex;

floatMaxPointSize;

DWORDMaxPrimitiveCount;

DWORDMaxVertexIndex;

DWORDMaxStreams;

DWORDMaxStreamStride;

DWORDVertexShaderVersion;

DWORDMaxVertexShaderConst;

DWORDPixelShaderVersion;

floatMaxPixelShaderValue;

}D3DCAPS8;

Members

DeviceTypeMemberoftheD3DDEVTYPEenumeratedtype,whichidentifieswhattypeofresourcesareusedforprocessingvertices.

AdapterOrdinalAdapteronwhichthisDirect3DDeviceobjectwascreated.ThisordinalisvalidonlytopasstomethodsoftheIDirect3D8interfacethatcreatedthisDirect3DDeviceobject.TheIDirect3D8interfacecanalwaysberetrievedbycallingIDirect3DDevice8::GetDirect3D.

CapsThefollowingdriver-specificcapability.D3DCAPS_READ_SCANLINE

Displayhardwareiscapableofreturningthecurrentscanline.Caps2

Page 257: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Thefollowingdriver-specificcapabilities.D3DCAPS2_CANCALIBRATEGAMMA

Thesystemhasacalibratorinstalledthatcanautomaticallyadjustthegammarampsothattheresultisidenticalonallsystemsthathaveacalibrator.Toinvokethecalibratorwhensettingnewgammalevels,usetheD3DSGR_CALIBRATEflagwhencallingtheIDirect3DDevice8::SetGammaRampmethod.Calibratinggammarampsincurssomeprocessingoverheadandshouldnotbeusedfrequently.

D3DCAPS2_CANRENDERWINDOWEDThedriveriscapableofrenderinginwindowedmode.

D3DCAPS2_CANMANAGERESOURCEThedriveriscapableofmanagingresources.Onsuchdrivers,D3DPOOL_MANAGEDresourceswillbemanagedbythedriver.TohaveDirect3DoverridethedriversothatDirect3Dmanagesresources,usetheD3DCREATE_DISABLE_DRIVER_MANAGEMENTflagwhencallingIDirect3D8::CreateDevice

D3DCAPS2_DYNAMICTEXTURESThedriversupportsdynamictextures.

D3DCAPS2_FULLSCREENGAMMAThedriversupportsdynamicgammarampadjustmentinfull-screenmode.

D3DCAPS2_NO2DDURING3DSCENEWhentheD3DCAPS2_NO2DDURING3DSCENEcapabilityissetbythedriver,itmeansthat2-DoperationscannotbeperformedbetweencallstoIDirect3DDevice8::BeginSceneandIDirect3DDevice8::EndScene.

Typically,thiscapabilityissetbyhardwarethatpartitionsthesceneandthenrenderseachpartitioninsequence.Thepartitioningisperformedinthedriver,andthehardwarecontainsasmallcoloranddepthbufferthatcorrespondstothesizeoftheimagepartition.Typically,onthistypeofrenderinghardware,onceeachpartoftheimageisrendered,thedatainthecolorbuffersarewrittentovideomemoryandthecontentsofthedepthbufferarediscarded.Also,notethat3-DrenderingdoesnotstartuntilEndSceneisencountered.Next,thesceneisprocessedinregions.Therefore,theprocessingordercannotbeguaranteed.Forexample,thefirstregionthatisprocessed,typicallytheupperleftcornerofthewindow,mightincludethelast

Page 258: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

triangleintheframe.Thisdiffersfrommoretraditionalgraphicssystemsinwhicheachcommandisprocessedsequentiallyintheorderthatitwassent.The2-Doperationsareimpliedtooccuratsomefixedpointintheprocessing.InthesystemsthatsetD3DCAPS2_NO2DDURING3DSCENE,theprocessingorderisnotguaranteed.Therefore,thedisplayadaptermightdiscard2-Doperationsthatareencounteredduring3-Drendering.

Ingeneral,itisrecommendedthat2-DoperationsbeperformedoutsideofaBeginSceneandEndScenepair.If2-DoperationsaretobeperformedbetweenaBeginSceneandEndScenepair,thenitisnecessarytochecktheD3DCAPS2_NO2DDURING3DSCENEcapability.Ifitisset,theapplicationmustexpectthatany2-DoperationthatoccursbetweenBeginSceneandEndScenewillbediscarded.FormoreinformationonwritingapplicationsforsystemsthatsetD3DCAPS2_NO2DDURING3DSCENE,seeRemarks.

D3DCAPS2_RESERVEDReserved;notused.

Caps3Thefollowingdriver-specificcapabilities.D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD

ThedevicewillworkasexpectedwiththeD3DRS_ALPHABLENDENABLErenderstatewhenafull-screenapplicationusesD3DSWAPEFFECT_FLIPorD3DRS_SWAPEFFECT_DISCARD.D3DRS_ALPHABLENDENABLEworksasexpectedwhenusingD3DSWAPEFFECT_COPYandD3DSWAPEFFECT_COPYSYNC.

D3DCAPS3_RESERVEDReserved;notused.

PresentationIntervalsBitmaskofvaluesrepresentingwhatpresentationswapintervalsareavailable.D3DPRESENT_INTERVAL_IMMEDIATE

Thedriversupportsanimmediatepresentationswapinterval.D3DPRESENT_INTERVAL_ONE

Thedriversupportsapresentationswapintervalofeveryscreenrefresh.

D3DPRESENT_INTERVAL_TWO

Page 259: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Thedriversupportsapresentationswapintervalofeverysecondscreenrefresh.

D3DPRESENT_INTERVAL_THREEThedriversupportsapresentationswapintervalofeverythirdscreenrefresh.

D3DPRESENT_INTERVAL_FOURThedriversupportsapresentationswapintervalofeveryfourthscreenrefresh.

CursorCapsBitmaskindicatingwhathardwaresupportisavailableforcursors.D3DCURSORCAPS_COLOR

Afull-colorcursorissupportedinhardware.Specifically,thisflagindicatesthatthedriversupportsatleastahardwarecolorcursorinhigh-resolutionmodes(withscanlinesgreaterthanorequalto400).

D3DCURSORCAPS_LOWRESAfull-colorcursorissupportedinhardware.Specifically,thisflagindicatesthatthedriversupportsahardwarecolorcursorinbothhigh-resolutionandlow-resolutionmodes(withscanlineslessthan400).

Direct3Ddoesnotdefinealpha-blendingcursorcapabilities.

DevCapsFlagsidentifyingthecapabilitiesofthedevice.D3DDEVCAPS_CANBLTSYSTONONLOCAL

Devicesupportsblitsfromsystem-memorytexturestononlocalvideo-memorytextures.

D3DDEVCAPS_CANRENDERAFTERFLIPDevicecanqueuerenderingcommandsafterapageflip.Applicationsdonotchangetheirbehaviorifthisflagisset;thiscapabilitysimplymeansthatthedeviceisrelativelyfast.

D3DDEVCAPS_DRAWPRIMTLVERTEXDeviceexportsaDrawPrimitive-awarehardwareabstractionlayer(HAL).

D3DDEVCAPS_EXECUTESYSTEMMEMORYDevicecanuseexecutebuffersfromsystemmemory.

D3DDEVCAPS_EXECUTEVIDEOMEMORYDevicecanuseexecutebuffersfromvideomemory.

D3DDEVCAPS_HWRASTERIZATIONDevicehashardwareaccelerationforscenerasterization.

Page 260: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DDEVCAPS_HWTRANSFORMANDLIGHTDevicecansupporttransformationandlightinginhardware.

D3DDEVCAPS_NPATCHESDevicesupportsN-patches.

D3DDEVCAPS_PUREDEVICEDevicecansupportrasterization,transform,lighting,andshadinginhardware.

D3DDEVCAPS_QUINTICRTPATCHESDevicesupportsquinticBéziercurvesandB-splines.

D3DDEVCAPS_RTPATCHESDevicesupportsrectangularandtriangularpatches.

D3DDEVCAPS_RTPATCHHANDLEZEROWhenthisdevicecapabilityisset,thehardwarearchitecturedoesnotrequirecachingofanyinformation,anduncachedpatches(handlezero)willbedrawnasefficientlyascachedones.NotethatsettingD3DDEVCAPS_RTPATCHHANDLEZEROdoesnotmeanthatapatchwithhandlezerocanbedrawn.Ahandle-zeropatchcanalwaysbedrawnwhetherthiscapissetornot.

D3DDEVCAPS_SEPARATETEXTUREMEMORIESDeviceistexturingfromseparatememorypools.

D3DDEVCAPS_TEXTURENONLOCALVIDMEMDevicecanretrievetexturesfromnon-localvideomemory.

D3DDEVCAPS_TEXTURESYSTEMMEMORYDevicecanretrievetexturesfromsystemmemory.

D3DDEVCAPS_TEXTUREVIDEOMEMORYDevicecanretrievetexturesfromdevicememory.

D3DDEVCAPS_TLVERTEXSYSTEMMEMORYDevicecanusebuffersfromsystemmemoryfortransformedandlitvertices.

D3DDEVCAPS_TLVERTEXVIDEOMEMORYDevicecanusebuffersfromvideomemoryfortransformedandlitvertices.

PrimitiveMiscCapsGeneralcapabilitiesforthisprimitive.Thismembercanbeoneormoreofthefollowingflags.D3DPMISCCAPS_BLENDOP

Devicesupportsthealpha-blendingoperationsdefinedintheD3DBLENDOPenumeratedtype.

D3DPMISCCAPS_CLIPPLANESCALEDPOINTS

Page 261: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Devicecorrectlyclipsscaledpointsofsizegreaterthan1.0touser-definedclippingplanes.

D3DPMISCCAPS_CLIPTLVERTSDeviceclipspost-transformedvertexprimitives.

D3DPMISCCAPS_COLORWRITEENABLEDevicesupportsper-channelwritesfortherendertargetcolorbufferthroughtheD3DRS_COLORWRITEENABLEstate.

D3DPMISCCAPS_CULLCCWThedriversupportscounterclockwisecullingthroughtheD3DRS_CULLMODEstate.(Thisappliesonlytotriangleprimitives.)ThisflagcorrespondstotheD3DCULL_CCWmemberoftheD3DCULLenumeratedtype.

D3DPMISCCAPS_CULLCWThedriversupportsclockwisetrianglecullingthroughtheD3DRS_CULLMODEstate.(Thisappliesonlytotriangleprimitives.)ThisflagcorrespondstotheD3DCULL_CWmemberoftheD3DCULLenumeratedtype.

D3DPMISCCAPS_CULLNONEThedriverdoesnotperformtriangleculling.ThiscorrespondstotheD3DCULL_NONEmemberoftheD3DCULLenumeratedtype.

D3DPMISCCAPS_LINEPATTERNREPThedrivercanhandlevaluesotherthan1inthewRepeatFactormemberoftheD3DLINEPATTERNstructure.(Thisappliesonlytoline-drawingprimitives.)

D3DPMISCCAPS_MASKZDevicecanenableanddisablemodificationofthedepthbufferonpixeloperations.

D3DPMISCCAPS_TSSARGTEMPDevicesupportsD3DTA_TEMPfortemporaryregister.

RasterCapsInformationonraster-drawingcapabilities.Thismembercanbeoneormoreofthefollowingflags.D3DPRASTERCAPS_ANISOTROPY

Devicesupportsanisotropicfiltering.D3DPRASTERCAPS_ANTIALIASEDGES

Devicecanantialiaslinesformingtheconvexoutlineofobjects.Formoreinformation,seeD3DRS_EDGEANTIALIAS.

D3DPRASTERCAPS_COLORPERSPECTIVEDeviceiteratescolorsperspectivecorrect.

Page 262: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DPRASTERCAPS_DITHERDevicecandithertoimprovecolorresolution.

D3DPRASTERCAPS_FOGRANGEDevicesupportsrange-basedfog.Inrange-basedfog,thedistanceofanobjectfromtheviewerisusedtocomputefogeffects,notthedepthoftheobject(thatis,thez-coordinate)inthescene.

D3DPRASTERCAPS_FOGTABLEDevicecalculatesthefogvaluebyreferringtoalookuptablecontainingfogvaluesthatareindexedtothedepthofagivenpixel.

D3DPRASTERCAPS_FOGVERTEXDevicecalculatesthefogvalueduringthelightingoperation,andinterpolatesthefogvalueduringrasterization.

D3DPRASTERCAPS_MIPMAPLODBIASDevicesupportslevel-of-detail(LOD)biasadjustments.Thesebiasadjustmentsenableanapplicationtomakeamipmapappearcrisperorlesssharpthanitnormallywould.FormoreinformationaboutLODbiasinmipmaps,seeD3DTSS_MIPMAPLODBIAS.

D3DPRASTERCAPS_PATThedrivercanperformpatterneddrawinglinesorfillswithD3DRS_LINEPATTERNfortheprimitivebeingqueried.

D3DPRASTERCAPS_STRETCHBLTMULTISAMPLEDeviceprovideslimitedmultisamplesupportthroughastretch-bltimplementation.Whenthiscapabilityisset,D3DRS_MULTISAMPLEANTIALIAScannotbeturnedonandoffinthemiddleofascene.Multisamplemaskingcannotbeperformedifthisflagisset.

D3DPRASTERCAPS_WBUFFERDevicesupportsdepthbufferingusingw.

D3DPRASTERCAPS_WFOGDevicesupportsw-basedfog.W-basedfogisusedwhenaperspectiveprojectionmatrixisspecified,butaffineprojectionsstillusez-basedfog.Thesystemconsidersaprojectionmatrixthatcontainsanonzerovalueinthe[3][4]elementtobeaperspectiveprojectionmatrix.

D3DPRASTERCAPS_ZBIASDevicesupportsz-biasvalues.Theseareintegervaluesassignedtopolygonsthatallowphysicallycoplanarpolygonstoappearseparate.Formoreinformation,seeD3DRS_ZBIAS.

D3DPRASTERCAPS_ZBUFFERLESSHSRDevicecanperformhidden-surfaceremoval(HSR)withoutrequiring

Page 263: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

theapplicationtosortpolygonsandwithoutrequiringtheallocationofadepthbuffer.Thisleavesmorevideomemoryfortextures.ThemethodusedtoperformHSRishardware-dependentandistransparenttotheapplication.

Z-bufferlessHSRisperformedifnodepth-buffersurfaceisassociatedwiththerendering-targetsurfaceandthedepth-buffercomparisontestisenabled(thatis,whenthestatevalueassociatedwiththeD3DRS_ZENABLEenumerationconstantissettoTRUE).

D3DPRASTERCAPS_ZFOGDevicesupportsz-basedfog.

D3DPRASTERCAPS_ZTESTDevicecanperformz-testoperations.Thiseffectivelyrendersaprimitiveandindicateswhetheranyzpixelshavebeenrendered.

ZCmpCapsZ-buffercomparisoncapabilities.Thismembercanbeoneormoreofthefollowingflags.D3DPCMPCAPS_ALWAYS

Alwayspasstheztest.D3DPCMPCAPS_EQUAL

Passtheztestifthenewzequalsthecurrentz.D3DPCMPCAPS_GREATER

Passtheztestifthenewzisgreaterthanthecurrentz.D3DPCMPCAPS_GREATEREQUAL

Passtheztestifthenewzisgreaterthanorequaltothecurrentz.D3DPCMPCAPS_LESS

Passtheztestifthenewzislessthanthecurrentz.D3DPCMPCAPS_LESSEQUAL

Passtheztestifthenewzislessthanorequaltothecurrentz.D3DPCMPCAPS_NEVER

Alwaysfailtheztest.D3DPCMPCAPS_NOTEQUAL

Passtheztestifthenewzdoesnotequalthecurrentz.SrcBlendCaps

Source-blendingcapabilities.Thismembercanbeoneormoreofthefollowingflags.(TheRGBAvaluesofthesourceanddestinationareindicatedbythesubscriptssandd.)D3DPBLENDCAPS_BOTHINVSRCALPHA

Page 264: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Sourceblendfactoris(1–As,1–As,1–As,1–As),anddestinationblendfactoris(As,As,As,As);thedestinationblendselectionisoverridden.

D3DPBLENDCAPS_BOTHSRCALPHAThedriversupportstheD3DBLEND_BOTHSRCALPHAblendmode.(Thisblendmodeisobsolete.Formoreinformation,seeD3DBLEND.)

D3DPBLENDCAPS_DESTALPHABlendfactoris(Ad,Ad,Ad,Ad).

D3DPBLENDCAPS_DESTCOLORBlendfactoris(Rd,Gd,Bd,Ad).

D3DPBLENDCAPS_INVDESTALPHABlendfactoris(1–Ad,1–Ad,1–Ad,1–Ad).

D3DPBLENDCAPS_INVDESTCOLORBlendfactoris(1–Rd,1–Gd,1–Bd,1–Ad).

D3DPBLENDCAPS_INVSRCALPHABlendfactoris(1–As,1–As,1–As,1–As).

D3DPBLENDCAPS_INVSRCCOLORBlendfactoris(1–Rd,1–Gd,1–Bd,1–Ad).

D3DPBLENDCAPS_ONEBlendfactoris(1,1,1,1).

D3DPBLENDCAPS_SRCALPHABlendfactoris(As,As,As,As).

D3DPBLENDCAPS_SRCALPHASATBlendfactoris(f,f,f,1);f=min(As,1-Ad).

D3DPBLENDCAPS_SRCCOLORBlendfactoris(Rs,Gs,Bs,As).

D3DPBLENDCAPS_ZEROBlendfactoris(0,0,0,0).

DestBlendCapsDestination-blendingcapabilities.ThismembercanbethesamecapabilitiesthataredefinedfortheSrcBlendCapsmember.

AlphaCmpCapsAlpha-testcomparisoncapabilities.ThismembercanincludethesamecapabilityflagsdefinedfortheZCmpCapsmember.IfthismembercontainsonlytheD3DPCMPCAPS_ALWAYScapabilityoronlytheD3DPCMPCAPS_NEVERcapability,thedriverdoesnotsupportalphatests.Otherwise,theflagsidentifytheindividualcomparisonsthatare

Page 265: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

supportedforalphatesting.ShadeCaps

Shadingoperationscapabilities.Itisassumed,ingeneral,thatifadevicesupportsagivencommandatall,itsupportstheD3DSHADE_FLATmode(asspecifiedintheD3DSHADEMODEenumeratedtype).ThisflagspecifieswhetherthedrivercanalsosupportGouraudshadingandwhetheralphacolorcomponentsaresupported.Whenalphacomponentsarenotsupported,thealphavalueofcolorsgeneratedisimplicitly255.Thisisthemaximumpossiblealpha(thatis,thealphacomponentisatfullintensity).

Thecolor,specularhighlights,fog,andalphainterpolantsofatriangleeachhavecapabilityflagsthatanapplicationcanusetofindouthowtheyareimplementedbythedevicedriver.

Thismembercanbeoneormoreofthefollowingflags.

D3DPSHADECAPS_ALPHAGOURAUDBLENDDevicecansupportanalphacomponentforGouraud-blendedtransparency(theD3DSHADE_GOURAUDstatefortheD3DSHADEMODEenumeratedtype).Inthismode,thealphacolorcomponentofaprimitiveisprovidedatverticesandinterpolatedacrossaface,alongwiththeothercolorcomponents.

D3DPSHADECAPS_COLORGOURAUDRGBDevicesupportsGouraudshading.Inthismode,thered,green,andbluecomponentsforaprimitiveareprovidedatverticesandinterpolatedacrossaface.

D3DPSHADECAPS_FOGGOURAUDDevicesupportsGouraudshadingoffog.

D3DPSHADECAPS_SPECULARGOURAUDRGBDevicesupportsGouraudshadingofspecularhighlights.

TextureCapsMiscellaneoustexture-mappingcapabilities.Thismembercanbeoneormoreofthefollowingflags.D3DPTEXTURECAPS_ALPHA

Alphaintexturepixelsissupported.D3DPTEXTURECAPS_ALPHAPALETTE

Devicecandrawalphafromtexturepalettes.D3DPTEXTURECAPS_CUBEMAP

Page 266: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SupportscubetexturesD3DPTEXTURECAPS_CUBEMAP_POW2

Devicerequiresthatcubetexturemapshavedimensionsspecifiedaspowersof2.

D3DPTEXTURECAPS_MIPCUBEMAPDevicesupportsmipmappedcubetextures.

D3DPTEXTURECAPS_MIPMAPDevicesupportsmipmappedtextures.

D3DPTEXTURECAPS_MIPVOLUMEMAPDevicesupportsmipmappedvolumetextures.

D3DPTEXTURECAPS_NONPOW2CONDITIONALConditionallysupportstheuseoftextureswithdimensionsthatarenotpowersof2.Adevicethatexposesthiscapabilitycanusesuchatextureifallofthefollowingrequirementsaremet.ThetextureaddressingmodeforthetexturestageissettoD3DTADDRESS_CLAMP.Texturewrappingforthetexturestageisdisabled(D3DRS_WRAPnsetto0).Mipmappingisnotinuse(usemagnificationfilteronly).TextureformatsmustnotbeDXT1-5

Atexturethatisnotapoweroftwocannotbesetatastagethatwillbereadbasedonashadercomputation(suchasthebem,beml,ortexm3x3instructionsinpixelshadersversions1.0to1.3).Forexample,thesetexturescanbeusedtostorebumpsthatwillbefedintotexturereads,butnottheenvironmentmapsthatareusedintexbem,texbeml,ortexm3x3spec.Thismeansthatatexturewithdimensionsthatarenotpowersoftwocannotbeaddressedorsampledusingtexturecoordinatescomputedwithintheshader.Thistypeofoperationisknownasadependentreadandcannotbeperformedonthesekindsoftextures.

D3DPTEXTURECAPS_PERSPECTIVEPerspectivecorrectiontexturingissupported.

D3DPTEXTURECAPS_POW2Alltexturesmusthavewidthsandheightsspecifiedaspowersof2.Thisrequirementdoesnotapplytoeithercubetexturesorvolumetextures.

D3DPTEXTURECAPS_PROJECTEDSupportstheD3DTTFF_PROJECTEDtexturetransformationflag.

Page 267: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Whenapplied,thedevicedividestransformedtexturecoordinatesbythelasttexturecoordinate.Ifthiscapabilityispresent,thentheprojectivedivideoccursperpixel.Ifthiscapabilityisnotpresent,buttheprojectivedivideneedstooccuranyway,thenitisperformedonaper-vertexbasisbytheDirect3Druntime.

D3DPTEXTURECAPS_SQUAREONLYAlltexturesmustbesquare.

D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZETextureindicesarenotscaledbythetexturesizepriortointerpolation.

D3DPTEXTURECAPS_VOLUMEMAPDevicesupportsvolumetextures.

D3DPTEXTURECAPS_VOLUMEMAP_POW2Devicerequiresthatvolumetexturemapshavedimensionsspecifiedaspowersof2.

TextureFilterCapsTexture-filteringcapabilitiesforaDirect3DTextureobject.Per-stagefilteringcapabilitiesreflectwhichfilteringmodesaresupportedfortexturestageswhenperformingmultiple-textureblendingwiththeIDirect3DDevice8interface.Thismembercanbeanycombinationofthefollowingper-stagetexture-filteringflags.D3DPTFILTERCAPS_MAGFAFLATCUBIC

Devicesupportsper-stageflatcubicfilteringformagnifyingtextures.TheflatcubicmagnificationfilterisrepresentedbytheD3DTEXF_FLATCUBICmemberoftheD3DTEXTUREFILTERTYPEenumeratedtype.

D3DPTFILTERCAPS_MAGFANISOTROPICDevicesupportsper-stageanisotropicfilteringformagnifyingtextures.TheanisotropicmagnificationfilterisrepresentedbytheD3DTEXF_ANISOTROPICmemberoftheD3DTEXTUREFILTERTYPEenumeratedtype.

D3DPTFILTERCAPS_MAGFGAUSSIANCUBICDevicesupportstheper-stageGaussiancubicfilteringformagnifyingtextures.TheGaussiancubicmagnificationfilterisrepresentedbytheD3DTEXF_GAUSSIANCUBICmemberoftheD3DTEXTUREFILTERTYPEenumeratedtype.

D3DPTFILTERCAPS_MAGFLINEARDevicesupportsper-stagebilinearinterpolationfilteringformagnifyingtextures.ThebilinearinterpolationmagnificationfilterisrepresentedbytheD3DTEXF_LINEARmemberofthe

Page 268: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DTEXTUREFILTERTYPEenumeratedtype.D3DPTFILTERCAPS_MAGFPOINT

Devicesupportsper-stagepoint-samplefilteringformagnifyingtextures.Thepoint-samplemagnificationfilterisrepresentedbytheD3DTEXF_POINTmemberoftheD3DTEXTUREFILTERTYPEenumeratedtype.

D3DPTFILTERCAPS_MINFANISOTROPICDevicesupportsper-stageanisotropicfilteringforminifyingtextures.TheanisotropicminificationfilterisrepresentedbytheD3DTEXF_ANISOTROPICmemberoftheD3DTEXTUREFILTERTYPEenumeratedtype.

D3DPTFILTERCAPS_MINFLINEARDevicesupportsper-stagebilinearinterpolationfilteringforminifyingtextures.ThebilinearminificationfilterisrepresentedbytheD3DTEXF_LINEARmemberoftheD3DTEXTUREFILTERTYPEenumeratedtype.

D3DPTFILTERCAPS_MINFPOINTDevicesupportsper-stagepoint-samplefilteringforminifyingtextures.Thepoint-sampleminificationfilterisrepresentedbytheD3DTEXF_POINTmemberoftheD3DTEXTUREFILTERTYPEenumeratedtype.

D3DPTFILTERCAPS_MIPFLINEARDevicesupportsper-stagetrilinearinterpolationfilteringformipmaps.ThetrilinearinterpolationmipmappingfilterisrepresentedbytheD3DTEXF_LINEARmemberoftheD3DTEXTUREFILTERTYPEenumeratedtype.

D3DPTFILTERCAPS_MIPFPOINTDevicesupportsper-stagepoint-samplefilteringformipmaps.Thepoint-samplemipmappingfilterisrepresentedbytheD3DTEXF_POINTmemberoftheD3DTEXTUREFILTERTYPEenumeratedtype.

CubeTextureFilterCapsTexture-filteringcapabilitiesforaDirect3DCubeTextureobject.Per-stagefilteringcapabilitiesreflectwhichfilteringmodesaresupportedfortexturestageswhenperformingmultiple-textureblendingwiththeIDirect3DDevice8interface.Thismembercanbeanycombinationoftheper-stagetexture-filteringflagsdefinedfortheTextureFilterCapsmember.

VolumeTextureFilterCapsTexture-filteringcapabilitiesforaDirect3DVolumeTextureobject.Per-stage

Page 269: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

filteringcapabilitiesreflectwhichfilteringmodesaresupportedfortexturestageswhenperformingmultiple-textureblendingwiththeIDirect3DDevice8interface.Thismembercanbeanycombinationoftheper-stagetexture-filteringflagsdefinedfortheTextureFilterCapsmember.

TextureAddressCapsTexture-addressingcapabilitiesforDirect3DTextureobjects.Thismembercanbeoneormoreofthefollowingflags.D3DPTADDRESSCAPS_BORDER

Devicesupportssettingcoordinatesoutsidetherange[0.0,1.0]tothebordercolor,asspecifiedbytheD3DTSS_BORDERCOLORtexture-stagestate.

D3DPTADDRESSCAPS_CLAMPDevicecanclamptexturestoaddresses.

D3DPTADDRESSCAPS_INDEPENDENTUVDevicecanseparatethetexture-addressingmodesoftheuandvcoordinatesofthetexture.ThisabilitycorrespondstotheD3DTSS_ADDRESSUandD3DTSS_ADDRESSVrender-statevalues.

D3DPTADDRESSCAPS_MIRRORDevicecanmirrortexturestoaddresses.

D3DPTADDRESSCAPS_MIRRORONCEDevicecantaketheabsolutevalueofthetexturecoordinate(thus,mirroringaround0),andthenclamptothemaximumvalue.

D3DPTADDRESSCAPS_WRAPDevicecanwraptexturestoaddresses.

VolumeTextureAddressCapsTexture-addressingcapabilitiesforDirect3DVolumeTextureobjects.ThismembercanbeoneormoreoftheflagsdefinedfortheTextureAddressCapsmember.

LineCapsDefinesthecapabilitiesforline-drawingprimitives.D3DLINECAPS_ALPHACMP

Supportsalpha-testcomparisons.D3DLINECAPS_BLEND

Supportssource-blending.D3DLINECAPS_FOG

Supportsfog.D3DLINECAPS_TEXTURE

Supportstexture-mapping.

Page 270: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DLINECAPS_ZTESTSupportsz-buffercomparisons.

MaxTextureWidthandMaxTextureHeightMaximumtexturewidthandheightforthisdevice.

MaxVolumeExtentMaximumvolumeextent.

MaxTextureRepeatThisnumberrepresentsthemaximumrangeoftheintegerbitsofthepost-normalizedtexturecoordinates.Atexturecoordinateisstoredasa32-bitsignedintegerusing27bitstostoretheintegerpartand5bitsforthefloatingpointfraction.Themaximumintegerindex,227,isusedtodeterminethemaximumtexturecoordinate,dependingonhowthehardwaredoestexture-coordinatescaling.

SomehardwarereportsthecapD3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE.Forthiscase,thedevicedefersscalingtexturecoordinatesbythetexturesizeuntilafterinterpolationandapplicationofthetextureaddressmode,sothenumberoftimesatexturecanbewrappedisgivenbytheintegervalueinMaxTextureRepeat.

Lessdesirably,onsomehardwareD3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZEisnotsetandthedevicescalesthetexturecoordinatesbythetexturesize(usingthehighestlevelofdetail)priortointerpolation.ThislimitsthenumberoftimesatexturecanbewrappedtoMaxTextureRepeat/textureSize.

Example:

GivenMaxTextureRepeat=32kandtexturesize=4KB:

ifthehardwaresetsD3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE

#oftimesatexturecanbewrapped=MaxTextureRepeat

//whichis32kinthisexample

else

#oftimesatexturecanbewrapped=MaxTextureRepeat/textureSize

//whichis227/4k

MaxTextureAspectRatioMaximumtextureaspectratiosupportedbythehardware,typicallyapowerof2.

MaxAnisotropyMaximumvalidvaluefortheD3DTSS_MAXANISOTROPYtexture-stagestate.

Page 271: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MaxVertexWMaximumW-baseddepthvaluethatthedevicesupports.

GuardBandLeft,GuardBandTop,GuardBandRight,andGuardBandBottom

Screenspacecoordinatesoftheguard-bandclippingregion.Coordinatesinsidethisrectanglebutoutsidetheviewportrectangleareautomaticallyclipped.

ExtentsAdjustNumberofpixelstoadjusttheextentsrectangleoutwardtoaccommodateantialiasingkernels.

StencilCapsFlagsspecifyingsupportedstencil-bufferoperations.Stenciloperationsareassumedtobevalidforallthreestencil-bufferoperationrenderstates(D3DRS_STENCILFAIL,D3DRS_STENCILPASS,andD3DRS_STENCILFAILZFAIL).D3DSTENCILCAPS_DECR

TheD3DSTENCILOP_DECRoperationissupported.D3DSTENCILCAPS_DECRSAT

TheD3DSTENCILOP_DECRSAToperationissupported.D3DSTENCILCAPS_INCR

TheD3DSTENCILOP_INCRoperationissupported.D3DSTENCILCAPS_INCRSAT

TheD3DSTENCILOP_INCRSAToperationissupported.D3DSTENCILCAPS_INVERT

TheD3DSTENCILOP_INVERToperationissupported.D3DSTENCILCAPS_KEEP

TheD3DSTENCILOP_KEEPoperationissupported.D3DSTENCILCAPS_REPLACE

TheD3DSTENCILOP_REPLACEoperationissupported.D3DSTENCILCAPS_ZERO

TheD3DSTENCILOP_ZEROoperationissupported.

Formoreinformation,seetheD3DSTENCILOPenumeratedtype.

FVFCapsFlexiblevertexformatcapabilities.D3DFVFCAPS_DONOTSTRIPELEMENTS

Itispreferablethatvertexelementsnotbestripped.Thatis,ifthevertexformatcontainselementsthatarenotusedwiththecurrent

Page 272: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

renderstates,thereisnoneedtoregeneratethevertices.Ifthiscapabilityflagisnotpresent,strippingextraneouselementsfromthevertexformatprovidesbetterperformance.

D3DFVFCAPS_PSIZEPointsizeisdeterminedbyeithertherenderstateorthevertexdata.

IfD3DFVFCAPS_PSIZEisset,pointsizecancomefromD3DFVF_PSIZEdataintheFVFvertexdeclaration.Otherwise,pointsizeisdeterminedbytherenderstateD3DRS_POINTSIZE.

Iftheapplicationprovidespointsizeinboth(therenderstateandtheFVFdata),thevertexdataoverridestherender-statedata.

D3DFVFCAPS_TEXCOORDCOUNTMASKMasksthelowWORDofFVFCaps.Thesebits,casttotheWORDdatatype,describethetotalnumberoftexturecoordinatesetsthatthedevicecansimultaneouslyuseformultipletextureblending.(Youcanuseuptoeighttexturecoordinatesetsforanyvertex,butthedevicecanblendusingonlythespecifiednumberoftexturecoordinatesets.)

TextureOpCapsCombinationofflagsdescribingthetextureoperationssupportedbythisdevice.Thefollowingflagsaredefined.D3DTEXOPCAPS_ADD

TheD3DTOP_ADDtexture-blendingoperationissupported.D3DTEXOPCAPS_ADDSIGNED

TheD3DTOP_ADDSIGNEDtexture-blendingoperationissupported.

D3DTEXOPCAPS_ADDSIGNED2XTheD3DTOP_ADDSIGNED2Xtexture-blendingoperationissupported.

D3DTEXOPCAPS_ADDSMOOTHTheD3DTOP_ADDSMOOTHtexture-blendingoperationissupported.

D3DTEXOPCAPS_BLENDCURRENTALPHATheD3DTOP_BLENDCURRENTALPHAtexture-blendingoperationissupported.

D3DTEXOPCAPS_BLENDDIFFUSEALPHATheD3DTOP_BLENDDIFFUSEALPHAtexture-blendingoperationissupported.

Page 273: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DTEXOPCAPS_BLENDFACTORALPHATheD3DTOP_BLENDFACTORALPHAtexture-blendingoperationissupported.

D3DTEXOPCAPS_BLENDTEXTUREALPHATheD3DTOP_BLENDTEXTUREALPHAtexture-blendingoperationissupported.

D3DTEXOPCAPS_BLENDTEXTUREALPHAPMTheD3DTOP_BLENDTEXTUREALPHAPMtexture-blendingoperationissupported.

D3DTEXOPCAPS_BUMPENVMAPTheD3DTOP_BUMPENVMAPtexture-blendingoperationissupported.

D3DTEXOPCAPS_BUMPENVMAPLUMINANCETheD3DTOP_BUMPENVMAPLUMINANCEtexture-blendingoperationissupported.

D3DTEXOPCAPS_DISABLETheD3DTOP_DISABLEtexture-blendingoperationissupported.

D3DTEXOPCAPS_DOTPRODUCT3TheD3DTOP_DOTPRODUCT3texture-blendingoperationissupported.

D3DTEXOPCAPS_LERPTheD3DTOP_LERPtexture-blendingoperationissupported.

D3DTEXOPCAPS_MODULATETheD3DTOP_MODULATEtexture-blendingoperationissupported.

D3DTEXOPCAPS_MODULATE2XTheD3DTOP_MODULATE2Xtexture-blendingoperationissupported.

D3DTEXOPCAPS_MODULATE4XTheD3DTOP_MODULATE4Xtexture-blendingoperationissupported.

D3DTEXOPCAPS_MODULATEALPHA_ADDCOLORTheD3DTOP_MODULATEALPHA_ADDCOLORtexture-blendingoperationissupported.

D3DTEXOPCAPS_MODULATECOLOR_ADDALPHATheD3DTOP_MODULATECOLOR_ADDALPHAtexture-blendingoperationissupported.

D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLORTheD3DTOP_MODULATEINVALPHA_ADDCOLORtexture-blendingoperationissupported.

Page 274: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHATheD3DTOP_MODULATEINVCOLOR_ADDALPHAtexture-blendingoperationissupported.

D3DTEXOPCAPS_MULTIPLYADDTheD3DTOP_MULTIPLYADDtexture-blendingoperationissupported.

D3DTEXOPCAPS_PREMODULATETheD3DTOP_PREMODULATEtexture-blendingoperationissupported.

D3DTEXOPCAPS_SELECTARG1TheD3DTOP_SELECTARG1texture-blendingoperationissupported.

D3DTEXOPCAPS_SELECTARG2TheD3DTOP_SELECTARG2texture-blendingoperationissupported.

D3DTEXOPCAPS_SUBTRACTTheD3DTOP_SUBTRACTtexture-blendingoperationissupported.

MaxTextureBlendStagesMaximumnumberoftexture-blendingstagessupported.Thisvalueisthenumberofblendersavailable.IntheDirectX8.xprogrammablepipeline,thiscorrespondstothenumberofinstructionssupportedbypixelshadersonthisparticularimplementation.

MaxSimultaneousTexturesMaximumnumberoftexturesthatcanbesimultaneouslyboundtothetextureblendingstages.Thisvalueisthenumberoftexturesthatcanbeusedinasinglepass.Ifthesametextureisusedintwoblendingstages,itcountsastwowhencomparedagainsttheMaxSimultaneousTexturesvalue.Intheprogrammablepipeline,thisindicatesthenumberoftextureregisterssupportedbypixelshadersonthisparticularpieceofhardware,andthenumberoftexturedeclarationinstructionsthatcanbepresent.

VertexProcessingCapsVertexprocessingcapabilities.Foragivenphysicaldevice,thiscapabilitymightvaryacrossDirect3DDeviceobjectsdependingontheparameterssuppliedtoIDirect3D8::CreateDevice.D3DVTXPCAPS_DIRECTIONALLIGHTS

Devicesupportsdirectionallights.D3DVTXPCAPS_LOCALVIEWER

Devicesupportslocalviewer.D3DVTXPCAPS_MATERIALSOURCE7

Page 275: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Devicesupportsselectablevertexcolorsources.D3DVTXPCAPS_POSITIONALLIGHTS

Devicesupportspositionallights(includingpointlightsandspotlights).

D3DVTXPCAPS_TEXGENDevicecangeneratetexturecoordinates.

D3DVTXPCAPS_TWEENINGDevicesupportsvertextweening.

D3DVTXPCAPS_NO_VSDT_UBYTE4DevicedoesnotsupporttheD3DVSDT_UBYTE4vertexdeclarationtype.

MaxActiveLightsMaximumnumberoflightsthatcanbeactivesimultaneously.Foragivenphysicaldevice,thiscapabilitymightvaryacrossDirect3DDeviceobjectsdependingontheparameterssuppliedtoIDirect3D8::CreateDevice.

MaxUserClipPlanesMaximumnumberofuser-definedclippingplanessupported.Thismembercanrangefrom0throughD3DMAXUSERCLIPPLANES.Foragivenphysicaldevice,thiscapabilitymayvaryacrossDirect3DDeviceobjectsdependingontheparameterssuppliedtoIDirect3D8::CreateDevice.

MaxVertexBlendMatricesMaximumnumberofmatricesthatthisdevicecanapplywhenperformingmultimatrixvertexblending.Foragivenphysicaldevice,thiscapabilitymayvaryacrossDirect3DDeviceobjectsdependingontheparameterssuppliedtoIDirect3D8::CreateDevice.

MaxVertexBlendMatrixIndexDWORDvaluethatspecifiesthemaximummatrixindexthatcanbeindexedintousingtheper-vertexindices.ThenumberofmatricesisMaxVertexBlendMatrixIndex+1,whichisthesizeofthematrixpalette.Ifnormalsarepresentinthevertexdatathatneedstobeblendedforlighting,thenthenumberofmatricesishalfthenumberspecifiedbythiscapabilityflag.IfMaxVertexBlendMatrixIndexissettozero,thedriverdoesnotsupportindexedvertexblending.IfthisvalueisnotzerothenthevalidrangeofindicesiszerothroughMaxVertexBlendMatrixIndex.

AzerovalueforMaxVertexBlendMatrixIndexindicatesthatthedriverdoesnotsupportindexedmatrices.

Whensoftwarevertexprocessingisused,256matricescouldbeusedfor

Page 276: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

indexedvertexblending,withorwithoutnormalblending.

Foragivenphysicaldevice,thiscapabilitymayvaryacrossDirect3DDeviceobjectsdependingontheparameterssuppliedtoIDirect3D8::CreateDevice.

MaxPointSizeMaximumsizeofapointprimitive.Ifsetto1.0fthendevicedoesnotsupportpointsizecontrol.Therangeisgreaterthanorequalto1.0f.

MaxPrimitiveCountMaximumnumberofprimitives,orverticesforeachDrawPrimitivecall.NotethatwhenDirect3DisworkingwithaDirectX6.0orDirectX7.0driver,thisfieldissetto0xFFFF.Thismeansthatnotonlythenumberofprimitivesbutalsothenumberofverticesislimitedbythisvalue.

MaxVertexIndexMaximumsizeofindicessupportedforhardwarevertexprocessing.Itispossibletocreate32-bitindexbuffersbyspecifyingD3DFMT_INDEX32;however,youwillnotbeabletorenderwiththeindexbufferunlessthisvalueisgreaterthan0x0000FFFF.

MaxStreamsMaximumnumberofconcurrentdatastreamsforIDirect3DDevice8::SetStreamSource.Thevalidrangeis1–16.Notethatifthisvalueis0,thedriverisnotaDirectX8driver.

MaxStreamStrideMaximumstrideforIDirect3DDevice8::SetStreamSource.

VertexShaderVersionVertexshaderversion,indicatingthelevelofvertexshadersupportedbythedevice.OnlyvertexshaderswithversionnumbersequaltoorlessthanthiswillsucceedincallstoIDirect3DDevice8::CreateVertexShader.ThelevelofshaderisspecifiedtoCreateVertexShaderasthefirsttokeninthevertexshadertokenstream.

DirectX7.0functionalityis0DirectX8.xfunctionalityis01

Themainversionnumberisencodedinthesecondbyte.Thelowbytecontainsasub-versionnumber.

MaxVertexShaderConstThenumberofvertexshaderinputregistersthatarereservedforconstants.

Page 277: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

PixelShaderVersionTwonumbersthatrepresentthepixelshadermainandsubversions.FormoreinformationabouttheversionssupportedinDirectX8.x,seethepixelshaderversioninstruction.

MaxPixelShaderValueMaximumvalueofpixelshaderarithmeticcomponent.Thisvalueindicatestheinternalrangeofvaluessupportedforpixelcolorblendingoperations.Withintherangethattheyreportto,implementationsmustallowdatatopassthroughpixelprocessingunmodified(unclamped).Normally,thevalueofthismemberisanabsolutevalue.Forexample,a1.0indicatesthattherangeis–1.0to1,andan8.0indicatesthattherangeis–8.0to8.0.Thevaluemustbe>=1.0foranyhardwarethatsupportspixelshaders.

Remarks

TheMaxTextureBlendStagesandMaxSimultaneousTexturesmembersmightseemverysimilar,buttheycontaindifferentinformation.TheMaxTextureBlendStagesmembercontainsthetotalnumberoftexture-blendingstagessupportedbythecurrentdevice,andtheMaxSimultaneousTexturesmemberdescribeshowmanyofthosestagescanhavetexturesboundtothembyusingtheIDirect3DDevice8::SetTexturemethod.

Whenthedriverfillsthisstructure,itcansetvaluesforexecute-buffercapabilities,evenwhentheinterfacebeingusedtoretrievethecapabilities(suchasIDirect3DDevice8)doesnotsupportexecutebuffers.

ForsystemsthatsettheD3DCAPS2_NO2DDURING3DSCENEcapabilityflag,performanceproblemsmayoccurifyouuseatextureandthenmodifyitduringascene.Thisistrueonallhardware,butitismoresevereonhardwarethatexposestheD3DCAPS2_NO2DDURING3DSCENEcapability.IfD3DCAPS2_NO2DDURING3DSCENEispresentonthehardware,application-basedtexturemanagementshouldensurethatnotextureusedinthecurrentBeginSceneandEndSceneblockisevictedunlessabsolutelynecessary.Inthecaseofextremelyhightextureusagewithinascene,theresultsareundefined.Thisoccurswhenyoumodifyatexturethatyouhaveusedinthesceneandthereisnosparetexturememoryavailable.Forsuchsystems,thecontentsofthezbufferbecomeinvalidatEndScene.ApplicationsshouldnotcallIDirect3DDevice8::CopyRectstoorfromthebackbufferonthistypeofhardwareinsideaBeginSceneandEndScenepair.Inaddition,applications

Page 278: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

shouldnottrytoaccessthezbufferiftheD3DPRASTERCAPS_ZBUFFERLESSHSRcapabilityflagisset.Finally,applicationsshouldnotlockthebackbufferorthezbufferinsideaBeginSceneandEndScenepair.

ThefollowingflagsconcerningmipmappedtexturesarenotsupportedinDirectX8.x.

D3DPTFILTERCAPS_NEARESTD3DPTFILTERCAPS_LINEARD3DPTFILTERCAPS_MIPNEARESTD3DPTFILTERCAPS_MIPLINEARD3DPTFILTERCAPS_LINEARMIPNEARESTD3DPTFILTERCAPS_LINEARMIPLINEAR

Requirements

Header:DeclaredinD3d8caps.h.

SeeAlso

IDirect3D8::GetDeviceCaps,IDirect3DDevice8::GetDeviceCaps

Page 279: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 280: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirect3DDevice8::GetDeviceCapsRetrievesthecapabilitiesoftherenderingdevice.

HRESULTGetDeviceCaps(

D3DCAPS8*pCaps

);

Parameters

pCaps[out]PointertoaD3DCAPS8structure,describingthereturneddevice.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisD3D_OK.

Ifthemethodfails,thereturnvaluecanbeD3DERR_INVALIDCALL.

Remarks

GetDeviceCapsretrievesthesoftwarevertexpipelinecapabilitieswhenthedeviceisbeingusedinsoftwarevertexprocessingmode.SoftwarevertexprocessingmodeisselectedwhenadevicehasbeencreatedwithD3DCREATE_SOFTWAREVERTEXPROCESSING,orwhenadevicehasbeencreatedwithD3DCREATE_MIXEDVERTEXPROCESSINGandD3DRS_SOFTWAREVERTEXPROCESSINGissettoTRUE.

Requirements

Header:DeclaredinD3d8.h.ImportLibrary:UseD3d8.lib.

Page 281: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 282: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

InstructionModifiers

Useinstructionmodifierstochangetheoutputofaninstruction.Forinstance,usethemtomultiplyordividetheresultbyafactoroftwo,ortoclamptheresultbetweenzeroandone.Instructionmodifiersareappliedaftertheinstructionexecutesbutbeforewritingtheresulttothedestinationregister.

Alistofthemodifiersisshownbelow.

Modifier Description Syntax Version1.0 1.1 1.2 1.3 1.4

_x2 Multiplyby2 register_x2 X X X X X_x4 Multiplyby4 register_x4 X X X X X_x8 Multiplyby8 register_x8 X_d2 Divideby2 register_d2 X X X X X_d4 Divideby4 register_d4 X_d8 Divideby8 register_d8 X_sat Saturate(clampfrom0and1) register_sat X X X X X

Themultiplymodifiermultipliestheregisterdatabyapoweroftwoafteritisread.Thisisthesameasashiftleft.Thedividemodifierdividestheregisterdatabyapoweroftwoafteritisread.Thisisthesameasashiftright.Thesaturatemodifierclampstherangeofregistervaluesfromzerotoone.

Instructionmodifierscanbeusedonarithmeticinstructions.Theymaynotbeusedontextureaddressinstructions.

Examples

Multiplymodifier

Thisexampleloadsthedestinationregister(dest)withthesumofthetwocolorsinthesourceoperands(src0andsrc1)andmultipliestheresultbytwo.

add_x2dest,src0,src1

Page 283: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Thisexamplecombinestwoinstructionmodifiers.First,twocolorsinthesourceoperands(src0andsrc1)areadded.Theresultisthenmultipliedbytwo,andclampedbetween0.0to1.0foreachcomponent.Theresultissavedinthedestinationregister.

add_x2_satdest,src0,src1

Dividemodifier

Thisexampleloadsthedestinationregister(dest)withthesumofthetwocolorsinthesourceoperands(src0andsrc1)anddividestheresultbytwo.

add_d2dest,src0,src1

Saturatemodifier

Forarithmeticinstructions,thesaturationmodifierclampstheresultofthisinstructionintotherange0.0to1.0foreachcomponent.Thefollowingexampleshowshowtousethisinstructionmodifier.

dp3_satr0,t0_bx2,v0_bx2;t0isbump,v0islightdirection

Thisoperationoccursafteranymultiplyordivideinstructionmodifier._satismostoftenusedtoclampdotproductresults.However,italsoenablesconsistentemulationofmultipassmethodswheretheframebufferisalwaysintherange0to1,andofMicrosoft®DirectX®6.0and7.0multitexturesyntax,inwhichsaturationisdefinedtooccurateverystage.

Thisexampleloadsthedestinationregister(dest)withthesumofthetwocolorsinthesourceoperands(src0andsrc1),andclampstheresultintotherange0.0to1.0foreachcomponent.

add_satdest,src0,src1

Thisexamplecombinestwoinstructionmodifiers.First,twocolorsinthesourceoperands(src0andsrc1)areadded.Theresultismultipliedbytwoandclampedbetween0.0to1.0foreachcomponent.Theresultissavedinthedestinationregister.

add_x2_satdest,src0,src1

Page 284: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectx8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 285: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SourceRegisterModifiersUsesourceregistermodifierstochangethevaluereadfromaregisterbeforeaninstructionexecutes.Thecontentsofasourceregisterareleftunchanged.Modifiersareusefulforadjustingtherangeofregisterdatainpreparationfortheinstruction.Asetofmodifierscalledselectorscopiesorreplicatesthedatafromasinglechannel(r,g,b,a)intotheotherchannels.

Version1.4shadershavemodifierfunctionalityspecifictoshaderinstructionstexldandtexcrd.Thesemodifiersaffectversion1.4textureregistersandaredetailedinTextureRegisterModifiers.

Sourceregistermodifiers Syntax Version1.0 1.1 1.2 1.3 1.4

Bias register_bias X X X X XInvert 1-register X X X X XNegate -register X X X X XScale×2 register_x2 XSignedScaling register_bx2 X X X X X

Sourceregistermodifierscanbeusedonlyonarithmeticinstructions.Theycannotbeusedontextureaddressinstructions.Theexceptiontothisisthesignedscalemodifier(_bx2).Forversion1.0and1.1,signedscalecanbeusedonthesourceargumentofanytexm*instruction.Forversion1.2or1.3,signedscalecanbeusedonthesourceargumentofanytextureaddressinstruction.

Somemodifierspecificrestrictions:

Negatecanbecombinedwitheitherthebias,signedscaling,orscale×2modifier.Whencombined,negateisexecutedlast.Invertcannotbecombinedwithanyothermodifier.Invert,negate,bias,signedscaling,andscale×2canbecombinedwithanyoftheselectors.Sourceregistermodifiersshouldnotbeusedonconstantregistersbecausetheywillcauseundefinedresults.Forversion1.4,modifiersonconstantsarenotallowedandwillfailvalidation.

Page 286: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.1,1.2,1.3,1.4)

Page 287: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SourceRegisterSelectorsThismodifierreplicatesasinglechannelofasource-registerargumenttoallchannels.

sourceregister.channel

Sourceregisterselectors Syntax Version1.0 1.1 1.2 1.3 1.4

Redreplicate sourceregister.r XGreenreplicate sourceregister.g XBluereplicate sourceregister.b X X X XAlphareplicate sourceregister.a X X X X X

Redreplicate.Replicatestheredchanneltoallchannels.Greenreplicate.Replicatesthegreenchanneltoallchannels.Bluereplicate.Replicatesthebluechanneltoallchannels.Alphareplicate.Replicatesthealphachanneltotoallchannels.

Register

Sourceregister.Formoreaboutregistertypes,seeRegisters.

Inversion1.1,1.2,and1.3,bluereplicateisavailableonlyonthesourceregisterofarithmeticinstruction,whichusesanalphadestinationregisterwritemask.

Remarks

Sourceregisterselectorsareappliedbeforeanysourceregistermodifiersandbeforetheinstructionexecutes.

Copyingthecontentsofachannelintooneormoreotherchannelsiscommonlyreferredtoas"swizzling."

Theseselectorsarevalidonsourceregistersforarithmeticinstructions.Thefourselectorsoperateondifferentchannels.

Page 288: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Analternatesyntaxforther,g,b,achannelsisx,y,z,w.

Sourceselectorsandsourcemodifiersmaybecombinedfreely.Inthisexample,registerr0usestheinvert,bias,andsignedscalingmodifier,aswellasthegreenselector.Thecontentsofthesourceregisterareunaffected;themodifiermodifiesonlythedataread.

-r0_bx2.g

Tounderstandtheorderoftheexecutionofthesemodifiersandselectors,seeOrderofOperations.

ThisoperatorcanbeusedinconjunctionwiththeInvertorNegateoperators.

AlphareplicatefunctionalityisanalogoustotheD3DTA_ALPHAREPLICATEflagintheMicrosoft®DirectX®6.0and7.0multitexturesyntax.

Example

Theexamplesbelowillustrateeachofthefourselectors.

//Replicatetheredcolorchanneltotheallchannelsbefore

//doingthemultiply.

mulr0,r0,r1.r//theresultisr1.rgba=r1.r

//Replicatethegreencolorchanneltotheallchannelsbefore

//doingthemultiply.

mulr0,r0,r1.g//theresultisr1.rgba=r1.g

//Replicatethebluecolorchanneltotheallchannelsbefore

//doingthemultiply.

mulr0,r0,r1.b//theresultisr1.rgba=r1.b

//Forps1.1,1.2,1.3,thebluereplicateexample

//wouldrequireadestinationwritemask.

mulr0.a,r0,r1.b

//alphareplicate

mulr0,r0,r1.a;Replicatethealphacolorchanneltoallchannels.

Page 289: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(pixelshaderversions1.0,1.1,1.2,1.3,1.4)

Page 290: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DestinationRegisterWriteMasksdestinationregister.writemask

Writemaskscontrolwhichchannels(red,green,blue,alpha)areupdatedinthedestinationregister.

Register

Destinationregister.Formoreaboutregistertypes,seeRegisters.

Remarks

Thefollowingdestinationwritemasksareavailable.

WriteMask Syntax Version1.0 1.1 1.2 1.3 1.4

red,green,blue,alpha destinationregister.rgba X X X X Xnone destinationregister X X X X Xcolor(red,green,blue) destinationregister.rgb X X X X Xalpha destinationregister.a X X X X Xred destinationregister.r Xgreen destinationregister.g Xblue destinationregister.b Xarbitrary destinationregister.rgba Seenotebelow.

NoteThearbitrarymaskallowsanysetofchannelstobecombinedtoproduceamask.Thechannelsmustbelistedintheorderr,g,b,a—forexample,register.rba,whichupdatesthered,blue,andalphachannelsofthedestination.Thearbitrarymaskisavailableonlyinversion1.4.

Ifnodestinationwritemaskisspecified,thedestinationwritemaskdefaultstothergbacase.Inotherwords,allchannelsinthedestinationregisterareupdated.

Analternatesyntaxforther,g,b,achannelsisx,y,z,w.

Page 291: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Forversions1.0to1.3,thedp3arithmeticinstructioncanuseonlythe.rgbor.rgbaoutputwritemasks.

Destinationregisterwritemasksaresupportedforarithmeticoperationsonly.Theycannotbeusedontextureaddressinginstructions,withtheexceptionoftheversion1.4instructions,texcrdandtexld.

Page 292: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Examples

default

Thedefaultistowriteallfourcolorchannels.

//Allfourcolorchannelscanbewrittenbyexplicitlylistingthem.

mulr0.rgba,t0,v0

//Or,thedefaultmaskcanbeusedtowriteallfourchannels.

mulr0,t0,v0

alphawritemask

Thealphawritemaskisusedtocontrolwritingtothealphachannel.

//Thealphawritemaskisalsoreferredtoasthescalarwritemask,

//becauseitusesthescalarpipeline.

addr0.a,t1,v1

Sothisinstructioneffectivelyputsthesumofthealphacomponentoft1andthealphacomponentofv1intor0.a.

colorwritemask

Thecolorwritemaskisusedtocontrolwritingtothecolorchannels.

//Thecolorwritemaskisalsoreferredtoasthevectorwritemask,

//becauseitusesthevectorpipeline.

mulr0.rgb,t0,v0

arbitrarywritemask

Forversion1.4,destinationwritemaskscanbeusedinanycombinationaslongasthemasksareorderedr,g,b,a.

//Thisexampleupdatesthered,blue,andalphachannels.

movr0.rba,r1

co-issuedinstructions

Page 293: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Aco-issuedinstructionallowstwopotentiallydifferentinstructionstobeissuedsimultaneously.ThisisaccomplishedbyexecutingtheinstructionsinthealphapipelineandtheRGBpipeline.

//Forexample,thedefaultexampleshownabove:

mulr0,t0,v0

//isalsoequivalenttothefollowingco-issuedinstruction

mulr0.rgb,t0,v0

+mulr0.a,t0,v0

Theadvantageofpairinginstructionsthiswayisthatitallowsdifferentoperationstobeperformedinthevectorandscalarpipelineinparallel.

Page 294: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectx8.1(pixelshaderversion1.4)

Page 295: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

TextureRegisterModifiersfortexldandtexcrd

Twopixelshaderversion1.4textureaddressinstructions,texldandtexcrd,havecustomsyntax.Theseinstructionssupporttheirownsetofsourceregistermodifiers,sourceregisterselectors,anddestination-registerwritemasks,asshownbelow.

SourceRegisterModifiersfortexldandtexcrd

Thesemodifiersprovideprojectivedividefunctionalitybydividingthexandyvaluesbyeitherthezorwvalues.

Sourceregistermodifiers Description Syntax Version

_dzDividex,ycomponentsbyz

sourceregister_dz 1.4

_db sourceregister_db 1.4

_dwDividex,ycomponentsbyw

sourceregister_dw 1.4

_da sourceregister_da 1.4

Register

Sourceregister.Formoreaboutregistertypes,seeRegisters.

Remarks

The_dzor_dbmodifierdoesthefollowing:

x'=x/z(x'=1.0ifz==0)

y'=y/z(y'=1.0ifz==0)

z'isundefined

w'isundefined

Page 296: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

The_dwor_damodifierdoesthefollowing:

x'=x/w(x'=1.0ifw==0)

y'=y/w(y'=1.0ifw==0)

z'isundefined

w'isundefined

NoteForpixelshaderversion1.4,theD3DTTFF_PROJECTEDflagunderD3DTSS_TEXTURETRANSFORMFLAGSisignoredbecauseaprojectivedivideisaccomplishedbythesourceregistermodifierslistedpreviously.

SourceRegisterSelectorsfortexldandtexcrd

Selectorsreplicatethecontentsofonechannelintootherchannels.Replicatingthecontentsofachanneltooneormoreotherchannelsiscommonlyreferredtoas"swizzling."

Sourceregisterselectors Description Syntax Version

xyzMapsx,y,zdatatochannelsx,y,z,z

sourceregister.xyz 1.4

rgb sourceregister.rgb 1.4

xywMapsx,y,wdatatochannelsx,y,w,w

sourceregister.xyw 1.4

rga sourceregister.rga 1.4

Register

Sourceregister.Formoreaboutregistertypes,seeRegisters.

Remarks

Thetexldandtexcrdinstructionsneverreadmorethanthefirstthreecomponents.So,theseselectorsprovidetheoptionoftakingthethirdcomponentfromeitherthethirdorthefourthcomponentofthesourceregister.

Page 297: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DestinationRegisterWriteMasksfortexldandtexcrd

Writemaskscontrolwhichchannels(red,green,blue,alpha)areupdatedinthedestinationregister.

Destinationregisterwritemasks Description Syntax Used

by Version

xyzw

Updatesthex,y,z,wchannels

destinationregister.xyzw

texldonly 1.4

rgba destinationregister.rgba

texldonly 1.4

none destinationregister

texldonly 1.4

xyzUpdatesthex,y,zchannels

destinationregister.xyz

texcrdonly 1.4

rgb destinationregister.rgb

texcrdonly 1.4

xyUpdatesthex,ychannels

destinationregister.xy

texcrdonly 1.4

rg destinationregister.rg

texcrdonly 1.4

Register

Destinationregister.Formoreaboutregistertypes,seeRegisters.

Page 298: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 299: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXMESHFlagsusedtospecifycreationoptionsforamesh.

enum_D3DXMESH{

D3DXMESH_32BIT=0x001,

D3DXMESH_DONOTCLIP=0x002,

D3DXMESH_POINTS=0x004,

D3DXMESH_RTPATCHES=0x008,

D3DXMESH_NPATCHES=0x4000,

D3DXMESH_VB_SYSTEMMEM=0x010,

D3DXMESH_VB_MANAGED=0x020,

D3DXMESH_VB_WRITEONLY=0x040,

D3DXMESH_VB_DYNAMIC=0x080,

D3DXMESH_VB_SOFTWAREPROCESSING=0x8000,

D3DXMESH_IB_SYSTEMMEM=0x100,

D3DXMESH_IB_MANAGED=0x200,

D3DXMESH_IB_WRITEONLY=0x400,

D3DXMESH_IB_DYNAMIC=0x800,

D3DXMESH_IB_SOFTWAREPROCESSING=0x10000,

D3DXMESH_VB_SHARE=0x1000,

D3DXMESH_USEHWONLY=0x2000,

D3DXMESH_SYSTEMMEM=0x110,

D3DXMESH_MANAGED=0x220,

D3DXMESH_WRITEONLY=0x440,

D3DXMESH_DYNAMIC=0x880,

D3DXMESH_SOFTWAREPROCESSING=0x18000

};

Constants

D3DXMESH_32BITThemeshhas32-bitindicesinsteadof16-bitindices.A32-bitmeshcansupportupto(2^32)-1facesandvertices.

D3DXMESH_DONOTCLIPUsetheD3DUSAGE_DONOTCLIPusageflagforvertexandindexbuffers.

D3DXMESH_POINTSUsetheD3DUSAGE_POINTSusageflagforvertexandindexbuffers.

D3DXMESH_RTPATCHES

Page 300: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

UsetheD3DUSAGE_RTPATCHESusageflagforvertexandindexbuffers.D3DXMESH_NPATCHES

SpecifyingthisflagcausesthevertexandindexbufferofthemeshtobecreatedwithD3DUSAGE_NPATCHESflag.ThisisrequiredifthemeshobjectistoberenderedusingN-patchenhancementusingMicrosoft®Direct3D®.

D3DXMESH_VB_SYSTEMMEMUsetheD3DPOOL_SYSTEMMEMmemoryclassforvertexbuffers.

D3DXMESH_VB_MANAGEDUsetheD3DPOOL_MANAGEDmemoryclassforvertexbuffers.

D3DXMESH_VB_WRITEONLYUsetheD3DUSAGE_WRITEONLYusageflagforvertexbuffers.

D3DXMESH_VB_DYNAMICUsetheD3DUSAGE_DYNAMICusageflagforvertexbuffers.

D3DXMESH_VB_SOFTWAREPROCESSINGUsetheD3DUSAGE_SOFTWAREPROCESSINGforflagforvertexbuffers.

D3DXMESH_IB_SYSTEMMEMUsetheD3DPOOL_SYSTEMMEMmemoryclassforindexbuffers.

D3DXMESH_IB_MANAGEDUsetheD3DPOOL_MANAGEDmemoryclassforindexbuffers.

D3DXMESH_IB_WRITEONLYUsetheD3DUSAGE_WRITEONLYusageflagforindexbuffers.

D3DXMESH_IB_DYNAMICUsetheD3DUSAGE_DYNAMICusageflagforindexbuffers.

D3DXMESH_IB_SOFTWAREPROCESSINGUsetheD3DUSAGE_SOFTWAREPROCESSINGusageflagforindexbuffers.

D3DXMESH_VB_SHAREForcestheclonedmeshestosharevertexbuffers.

D3DXMESH_USEHWONLYUsehardwareprocessingonly.Thisflagshouldbespecifiedonlyforahardwareprocessingdevice.Onamixed-modedevice,thisflagwillcausethesystemtoeitherusehardwareonly,orifthehardwareisnotcapable,itwillapproximateusingthesoftwarecapabilities.

D3DXMESH_SYSTEMMEMEquivalenttospecifyingbothD3DXMESH_VB_SYSTEMMEMandD3DXMESH_IB_SYSTEMMEM.

D3DXMESH_MANAGED

Page 301: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

EquivalenttospecifyingbothD3DXMESH_VB_MANAGEDandD3DXMESH_IB_MANAGED.

D3DXMESH_WRITEONLYEquivalenttospecifyingbothD3DXMESH_VB_WRITEONLYandD3DXMESH_IB_WRITEONLY.

D3DXMESH_DYNAMICEquivalenttospecifyingbothD3DXMESH_VB_DYNAMICandD3DXMESH_IB_DYNAMIC.

D3DXMESH_SOFTWAREPROCESSINGEquivalenttospecifyingbothD3DXMESH_VB_SOFTWAREPROCESSINGandD3DXMESH_IB_SOFTWAREPROCESSING

Requirements

Header:DeclaredinD3dx8mesh.h.

Page 302: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 303: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ID3DXMeshApplicationsusethemethodsoftheID3DXMeshinterfacetomanipulatemeshobjects.

ToobtaintheID3DXMeshinterface,calleithertheD3DXCreateMeshorD3DXCreateMeshFVFfunction.ThemethodsoftheID3DXMeshinterfacecanbeorganizedintothefollowinggroups.

Locking LockAttributeBufferUnlockAttributeBuffer

Optimization OptimizeOptimizeInplace

Remarks

ThisinterfaceinheritsadditionalfunctionalityfromtheID3DXBaseMeshinterface.

Thisinterface,likeallCOMinterfaces,inheritsadditionalfunctionalityfromtheIUnknownInterface.

TheLPD3DXMESHtypeisdefinedasapointertotheID3DXMeshinterface,asshownbelow.

typedefstructID3DXMesh*LPD3DXMESH;

Requirements

Header:DeclaredinD3dx8mesh.h.ImportLibrary:UseD3dx8.lib.

SeeAlso

MeshFunctions

Page 304: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 305: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

PALETTEENTRYSpecifiesthecolorandusageofanentryinalogicalpalette.

typedefstructtagPALETTEENTRY{

BYTEpeRed;

BYTEpeGreen;

BYTEpeBlue;

BYTEpeFlags;

}PALETTEENTRY;

Members

peRedTheredintensityvalueforthepaletteentry.

peGreenThegreenintensityvalueforthepaletteentry.

peBlueTheblueintensityvalueforthepaletteentry.

peFlagsThealphaintensityvalueforthepaletteentry.NotethatasofMicrosoft®DirectX®8.0,thismemberistreateddifferentlythandocumentedintheMicrosoft®PlatformSoftwareDevelopmentKit(SDK).

Requirements

Header:DeclaredinWingdi.h;includeWindows.h.

Page 306: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 307: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DX_NORMALMAPFlagsControlthegenerationofnormalmaps.

#defineD3DX_NORMALMAP_MIRROR_U(1<<16)

#defineD3DX_NORMALMAP_MIRROR_V(2<<16)

#defineD3DX_NORMALMAP_MIRROR(3<<16)

#defineD3DX_NORMALMAP_INVERTSIGN(8<<16)

#defineD3DX_NORMALMAP_COMPUTE_OCCLUSION(16<<16)

Constants

D3DX_NORMALMAP_MIRROR_UIndicatesthatpixelsofftheedgeofthetextureontheU-axisshouldbemirrored,notwrapped.

D3DX_NORMALMAP_MIRROR_VIndicatesthatpixelsofftheedgeofthetextureontheV-axisshouldbemirrored,notwrapped.

D3DX_NORMALMAP_MIRRORSameasspecifyingD3DX_NORMALMAP_MIRROR_U|D3DX_NORMALMAP_MIRROR_V.

D3DX_NORMALMAP_INVERTSIGNInvertsthedirectionofeachnormal.

D3DX_NORMALMAP_COMPUTE_OCCLUSIONComputestheper-pixelocclusiontermandencodesitintothealpha.Analphaof1meansthatthepixelisnotobscuredinanyway,andanalphaof0meansthatthepixeliscompletelyobscured.

Requirements

Header:DeclaredinD3d8tex.h.

SeeAlso

D3DXComputeNormalMap

Page 308: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 309: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DX_CHANNELFlagsThefollowingflagsareusedtospecifywhichchannelsinatexturetooperateon.

#defineD3DX_CHANNEL_RED1

#defineD3DX_CHANNEL_BLUE2

#defineD3DX_CHANNEL_GREEN4

#defineD3DX_CHANNEL_ALPHA8

#defineD3DX_CHANNEL_LUMINANCE16

Constants

D3DX_CHANNEL_REDIndicatestheredchannelshouldbeused.

D3DX_CHANNEL_BLUEIndicatesthebluechannelshouldbeused.

D3DX_CHANNEL_GREENIndicatesthegreenchannelshouldbeused.

D3DX_CHANNEL_ALPHAIndicatesthealphachannelshouldbeused.

D3DX_CHANNEL_LUMINANCEIndicatestheluminancesofthered,green,andbluechannelsshouldbeused.

Requirements

Header:DeclaredinD3d8tex.h.

Page 310: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

IUnknownInterface

AllCOMobjectssupportaninterfacecalledIUnknown.ThisinterfaceprovidesMicrosoft®DirectX®withcontroloftheobject'slifetimeandtheabilitytoretrieveotherinterfacesimplementedbytheobject.IUnknownhasthreemethods.

AddRefincrementstheobject'sreferencecountby1whenaninterfaceoranotherapplicationbindsitselftotheobject.QueryInterfacequeriestheobjectaboutthefeaturesthatitsupportsbyrequestingpointerstoaspecificinterface.Releasedecrementstheobject'sreferencecountby1.Whenthecountreaches0,theobjectisdeallocated.

TheAddRefandReleasemethodsmaintainanobject'sreferencecount.Forexample,ifyoucreateaMicrosoftDirect3D®object,theobject'sreferencecountissetto1.Everytimeafunctionreturnsapointertoaninterfaceforthatobject,thefunctionmustcallAddRefthroughthatpointertoincrementthereferencecount.MatcheachAddRefcallwithacalltoRelease.Beforethepointercanbedestroyed,youmustcallReleasethroughthatpointer.Afteranobject'sreferencecountreaches0,theobjectisdestroyed,andallinterfacestoitbecomeinvalid.

TheQueryInterfacemethoddetermineswhetheranobjectsupportsaspecificinterface.Ifanobjectsupportsaninterface,QueryInterfacereturnsapointertothatinterface.Youthencanusethemethodsofthatinterfacetocommunicatewiththeobject.IfQueryInterfacesuccessfullyreturnsapointertoaninterface,itimplicitlycallsAddReftoincrementthereferencecount,soyourapplicationmustcallReleasetodecrementthereferencecountbeforedestroyingthepointertotheinterface.

Requirements

WindowsNT/2000/XP:RequiresWindowsNT3.1orlater.Windows98/Me:RequiresWindows98orlater.

Page 311: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Header:DeclaredinUnknwn.h.

Page 312: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 313: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXIMAGE_FILEFORMATDescribesthesupportedimagefileformats.

typedefenum_D3DXIMAGE_FILEFORMAT

{

D3DXIFF_BMP=0,

D3DXIFF_JPG=1,

D3DXIFF_TGA=2,

D3DXIFF_PNG=3,

D3DXIFF_DDS=4,

D3DXIFF_PPM=5,

D3DXIFF_DIB=6,

D3DXIFF_FORCE_DWORD=0x7fffffff

}D3DXIMAGE_FILEFORMAT;

Constants

D3DXIFF_BMPMicrosoft®Windows®bitmapfileformat.

D3DXIFF_JPGJointPhotographicExpertsGroupcompressedfile.

D3DXIFF_TGATruevisionTargaimagefile.

D3DXIFF_PNGPortableNetworkGraphicsfileformat.

D3DXIFF_DDSMicrosoftDirectDraw®surfacefileformat.

D3DXIFF_PPMPortablepixmapfileformat.

D3DXIFF_DIBWindowsbitmapfileformat.

D3DXIFF_FORCE_DWORDForcesthisenumerationtocompileto32bitsinsize.Thisvalueisnotused.

Requirements

Page 314: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Header:DeclaredinD3dx8tex.h.

Page 315: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 316: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

LPD3DXFILL2DFunctiontypeusedbythetexturefillfunctions.

VOID(*LPD3DXFILL2D)(

D3DXVECTOR4*pOut,

D3DXVECTOR2*pTexCoord,

D3DXVECTOR2*pTexelSize,

LPVOIDpData

);

Parameters

pOut[out]Pointertoavector,whichthefunctionusestoreturnitsresult.X,Y,Z,andWwillbemappedtoR,G,B,andArespectively.

pTexCoord[in]Pointertoavectorcontainingthecoordinatesofthetexelcurrentlybeingevaluated.Texturecoordinatecomponentsfortextureandvolumetexturesrangefrom0to1.Texturecoordinatecomponentsforcubetexturesrangefrom-1to1.

pTexelSize[in]Pointertoavectorcontainingthedimensionsofthecurrenttexel.

pData[in]Pointertouserdata.

Requirements

Header:DeclaredinD3dx8tex.h.

SeeAlso

D3DXFillTexture

Page 317: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 318: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

LPD3DXFILL3DFunctiontypeusedbythetexturefillfunctions.

VOID(*LPD3DXFILL3D)(

D3DXVECTOR4*pOut,

D3DXVECTOR3*pTexCoord,

D3DXVECTOR3*pTexelSize,

LPVOIDpData

);

Parameters

pOut[out]Pointertoavector,whichthefunctionusestoreturnitsresult.X,Y,Z,andWwillbemappedtoR,G,B,andArespectively.

pTexCoord[in]Pointertoavectorcontainingthecoordinatesofthetexelcurrentlybeingevaluated.Texturecoordinatecomponentsfortextureandvolumetexturesrangefrom0to1.Texturecoordinatecomponentsforcubetexturesrangefrom-1to1.

pTexelSize[in]Pointertoavectorcontainingthedimensionsofthecurrenttexel.

pData[in]Pointertouserdata.

Requirements

Header:DeclaredinD3dx8tex.h.

SeeAlso

D3DXFillCubeTexture,D3DXFillVolumeTexture

Page 319: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 320: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SampleFramework

TheMicrosoft®DirectX®8.1andMicrosoft®Direct3D®SoftwareDevelopmentKit(SDK)graphicssampleframeworkisanevolutionfromtheDirectX7.0graphicssampleframework.TheSDKsamplesareinstalledbydefaultin\Dxsdk\Samples\Multimedia.ThefoldersofinterestareCommonandDirect3D.ThesampleframeworkiscontainedintheCommonfolderandtheDirect3DsamplesbasedonthegraphicsframeworkarecontainedintheDirect3Dfolder.

Thegraphicsframeworkconsistsoffivesourcemodules.

d3dapp.cppexposestheapplicationinterfaceusedforsamples.OfparticularinterestisclassCD3DApplication.d3dfile.cppfurnishes.xfilesupport,toenablesamplestoload.xfiles.OfparticularinterestareclassesCD3DmeshandCD3DFrame.d3dfont.cppfurnishesbasicfontoutputsupport,toenablethingslikestatisticsviews.OfparticularinterestisclassCD3DFont.d3dutil.cppprovidesgenerallyuseful3dimensionalfunctions,suchasmaterial,light,andtexturehelperfunctions.dxutil.cppprovidesgenerallyusefulDirectXfunctions,suchasmedia,registry,andtimerhelperfunctions.

CorrespondingheaderfilesarelocatedintheCommon\Includefolder.

EachsampleimplementsasubclassofCD3DApplication,whichistypicallynamedCMyD3DApplication,andsetofoverridablesthatareshownbelow.

//Overridablefunctionsforthe3dimensionalscenecreatedbytheapplication

virtualHRESULTConfirmDevice(D3DCAPS8*,DWORD,D3DFORMAT){returnS_OK;}

virtualHRESULTOneTimeSceneInit(){returnS_OK;}

virtualHRESULTInitDeviceObjects(){returnS_OK;}

virtualHRESULTRestoreDeviceObjects(){returnS_OK;}

virtualHRESULTFrameMove(){returnS_OK;}

virtualHRESULTRender(){returnS_OK;}

virtualHRESULTInvalidateDeviceObjects(){returnS_OK;}

virtualHRESULTDeleteDeviceObjects(){returnS_OK;}

virtualHRESULTFinalCleanup(){returnS_OK;}

Theprototypesforthesemethodsarecontainedind3dapp.hinthe

CD3Dapplicationclass.ThesamplescreateanewDirect3Dapplicationandoverride

Page 321: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

thosemethodsthatareneededbytheapplication.

DerivedClassExample

Thisexampleusesasubsetoftheoverrideablemethods.TheclassCMyD3DApplicationcontainsthefollowingmethods.Eachofthesemethodsisexplainedbelow.

classCMyD3DApplication:publicCD3DApplication

{

public:

CMyD3DApplication();

protected:

HRESULTConfirmDevice(D3DCAPS8*,DWORD,D3DFORMAT);

HRESULTDeleteRestoreDeviceObjects();

HRESULTRestoreDeviceObjects();

HRESULTFrameMove();

HRESULTRender();

private:

LPDIRECT3DVERTEXBUFFER8m_pVB; //Vertexbuffertoholdvertices

};

Constructor

Theconstructorinitializesthewindowtitle,enablesdepthbufferingandinitializesthevertexbuffer.

CMyD3DApplication::CMyD3DApplication()

{

m_strWindowTitle=_T("D3DExample");//titlebarstring

m_bUseDepthBuffer=TRUE;//enabledepthbuffer

m_pVB=NULL;//initialize

}

Thewindowtitleisawidecharacterstringthatisvisibleinthetitlebarorthewindowclasswhentheapplicationisinvoked.Itisoptional.

Thebaseclasscontainsamembervariableforenablingdepthbuffering.ThedefaultvalueforthisbooleanvariableisFALSE,whichdisablesdepthbuffering.

Thewindowtitleisawidecharacterstringthatisvisibleinthetitlebarorthewindowclasswhentheapplicationisinvoked.Itisoptional.

Page 322: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ConfirmDeviceObjects

DeleteDeviceObjects

DeleteDeviceObjectsiscalledwhentheapplicationisexiting,orifthedeviceisbeingchanged.Youusethismethodtodeletedevicedependentobjects,suchasthevertexbuffer.

HRESULTCVShader1::DeleteDeviceObjects()

{

m_pQuadVB->Release();

m_pQuadVB=NULL;

returnS_OK;

}

RestoreDeviceObjects

Thismethodiscalledwhentheapplicationneedstorestoredevicememoryobjectsanddevicestates.ThisisrequiredafteraDirectXdeviceiscreatedorresized.Thismethoddoesmostoftheworkofcreatingobjectsandinitializingrenderstates.

HRESULTCMyD3DApplication::RestoreDeviceObjects()

{

//Createthevertexbuffer.Allocateenoughmemory(fromthedefaultpool)

//toholdthecustomvertices.Specifytheflexiblevertexformat(FVF),sothevertexbufferknowswhat

// dataitcontains.

if(FAILED(m_pd3dDevice->CreateVertexBuffer(NUM_VERTS*sizeof(CUSTOMVERTEX),

0,D3DFVF_CUSTOMVERTEX,D3DPOOL_DEFAULT,&m;_pVB)))

{

returnE_FAIL;

}

//Fillthevertexbuffer.First,lockthevertexbuffertogetaccesstothe

//vertices.Thismechanismisrequiredbecausevertexbuffersmaybeindevice

//memory.Thenusememcpytodoafastdatacopy.

VOID*pVertices;

if(FAILED(m_pVB->Lock(0,sizeof(g_Vertices),

(BYTE**)&pVertices;,0)))

returnE_FAIL;

memcpy(pVertices,g_Vertices,sizeof(g_Vertices));

m_pVB->Unlock();

//Settheprojectionmatrix.Thesizeofthebackbuffercomesfromthebase

//class

Page 323: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DXMATRIXmatProj;

FLOATfAspect=m_d3dsdBackBuffer.Width/

(FLOAT)m_d3dsdBackBuffer.Height;

D3DXMatrixPerspectiveFovLH(&matProj;,D3DX_PI/4,fAspect,

1.0f,100.0f);

m_pd3dDevice->SetTransform(D3DTS_PROJECTION,&matProj;);

//Setuptheviewmatrix.Aviewmatrixcanbedefinedfromaneye

//point,alookatpointandanupdirectionvector.Inthisexample,

//theeyepositionis(0,1,-4)thelookatpointis(0,0,0)andthe

//upvectoris(0,1,0.

D3DXMATRIXmatView;

D3DXMatrixLookAtLH(&matView;,&D3DXVECTOR3;(0.0f,1.0f,-4.0f),

&D3DXVECTOR3;(0.0f,0.0f,0.0f),

&D3DXVECTOR3;(0.0f,1.0f,0.0f));

m_pd3dDevice->SetTransform(D3DTS_VIEW,&matView;);

//Setupdefaulttexturestates

//Setuprenderstates(thisisonlyoneexamplerenderstate)

m_pd3dDevice->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);

returnS_OK;

}

Thismethodcreatesthevertexbufferandcopiesthevertexdataintoit.Itcreatestheviewandprojectionmatrices,whichdefinethecameraorientationtotheobjectinthevertexbuffer.Texturestagestatescanbesetinthismethodalthoughnonearepresentinthisexample.Renderstatesthatarenotlikelytochangeareset.Thesedeterminehowthescenerenders.

FrameMove

Thismethodcontainsactionsthathappeneveryframesuchasanimation.Inthisexample,itaddsayaxisrotationtotheworldtransform.

HRESULTCMyD3DApplication::FrameMove()

{

//Forourworldmatrix,justrotatetheobjectaboutthey-axis.

D3DXMATRIXmatWorld;

D3DXMatrixRotationY(&matWorld;,::TimeGetTime()/150.0f);

m_pd3dDevice->SetTransform(D3DTS_WORLD,&matWorld;);

returnS_OK;

}

Page 324: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

TheWindowsmethod::TimeGetTime()isusedtoreturnthecurrenttime.Onceitisdividedby150,thisgeneratesaincrementalangletorotatetheobject.

Render

Thismethodiscalledwhenitistimetorendertheoutput.Thisfunctionclearstheviewportandrenderthescene.Italsorendersstatechanges.

HRESULTCMyD3DApplication::Render()

{

//Cleartheviewport

m_pd3dDevice->Clear(0L,NULL,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,

D3DCOLOR_XRGB(0,0,0),1.0f,0L);

//Beginthescene

if(SUCCEEDED(m_pd3dDevice->BeginScene()))

{

m_pd3dDevice->SetStreamSource(0,m_pVB,sizeof(CUSTOMVERTEX));

m_pd3dDevice->SetVertexShader(D3DFVF_CUSTOMVERTEX);

m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,0,NUM_TRIS);

m_pd3dDevice->EndScene();

}

returnS_OK;

}

TheRendermethodfirstclearstheviewportusingClear.Then,withintheBeginScne/EndScenepairitusesSetStreamSourcetoinformtheruntimethatitusesvertexbufferm_pVBwithastrideofthesizeofthecustomvertextype.Then,itinformstheruntimethatitusesaflexiblevertexformat(FVF)shader,thesimplesttype.FinallyitinvokesDrawPrimitivetorenderthequad.

Otherfunctions

DeleteDeviceObjectsiscalledwhentheapplicationexits,orifthedevicechanges.Youusethismethodtodeletedevicedependentobjects.

ConfirmDevicechecksthedeviceforsomeminimumsetofcapabilities.Itiscalledduringthedeviceinitialization.

InvalidateDeviceObjectsiscalledwhenthedevicedependentobjectsmightbe

Page 325: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

removed.Devicedependentobjectssuchasvertexbuffersareusuallyaddedtothismethod.

OneTimeSceneInitisprovidedforcodethatneedstorunduringtheinitialapplicationstartup.

DirectXDevforgraphics,networking,andinputathttp://DISCUSS.MICROSOFT.COM/archives/DIRECTXDEV.html.

Page 326: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 327: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ApplicationWizardTheMicrosoft®DirectX®AppWizardcreatesasmallC++templateapplicationthatcanintegratethecommonDirectXcomponents—MicrosoftDirect3D®,MicrosoftDirectInput®,MicrosoftDirectMusic®,MicrosoftDirectSound®,andMicrosoftDirectPlay®.Itprovidesbasic,easy-to-build-uponfunctionallyanddemonstratestheuseofeachcomponent.

Alongwiththetemplate,AppWizardincludesthesameC++classesfoundintheDirectXsoftwaredevelopmentkit(SDK)commondirectory.TheseC++classesperformminimalwrappingofDirectXtogetyouupandrunningquickly.AlltheDirectXSDKsamplesmakeuseoftheseclasses.Forexample,theDirect3DsamplesuseD3dapp.*,theDirectMusicsamplesuseDmutil.*,theDirectSoundsamplesuseDsutil.*,andtheDirectPlaysamplesuseNetconnect.*.

TheAppWizardtargetaudienceisamateurC++gamedevelopers,3-Dhobbyists,andaudiohobbyists(whodonotneed3-D).

Page 328: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

RunningAppWizard

AppWizardislaunchedfromMicrosoftVisualStudio®6.0whenyoucreateanewproject.ItisoneoftheprojecttypesavailablewhenyouchooseFile,New,thentheProjectstab,asshowninthefollowingexample.

WhenyouenteraprojectnameandclickOK,thewizardpresentsaseriesofdialogboxestoallowyoutoconfiguretheDirectXservicesthattheapplicationwillneed.ThenumberofdialogboxesgeneratedbythewizarddependonwhichDirectXtechnologiesyouselect(Direct3D,DirectInput,andDirectPlayeachgeneratetheirowndialogboxes).ThefilesincludedintheprojectdependontheDirectXtechnologiesselected,aswellastheMicrosoftWindows®technologiesselected—MicrosoftWin32®,MicrosoftFoundationClasses(MFC),andGraphicsDeviceInterface(GDI).Youselectthesetechnologiesonthefirstpageofthewizard,whichisshowninthefollowingexample.

Thewizardhasthreesteps:Step1istheopeningpage,step2istheDirect3Dpage,andstep3istheDirectInputpage.TheDirectMusicandDirectSoundoptionsdonotgenerateadditionalpagesbuttheDirectPlayPeer-to-Peeroptionwillgenerateanadditionalpage.

Thewizardusesoneoffourbasetemplates,basedontheoptionsyouselect.

1. ForanapplicationthatisnotMFC-basedandusesDirect3D,chooseSingledocumentwindowandDirect3D.Thisisthestandardcaseandissimilartotheapplicationusedinthedolphinsample.

2. ForanapplicationthatisMFC-basedandusesDirect3D,chooseMFCdialogbasedandDirect3D.TheapplicationwillbesimilartotheMFCfogsample.

3. ForaWindowsapplicationthatusesGDIbutnotMFC,chooseSingledocumentwindow.ThisapplicationcanuseCreateWindowandbasicGameLoopduringidletime.

Page 329: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

4. ForanapplicationthatusesGDIandisMFC-based,chooseMFCdialogbased.TheapplicationwillbesimilartotheMFCAppWizarddialogtemplate.

TheDirect3D,DirectInput,andDirectPlaycheckboxeseachaddanotherpagetothewizard.Thesepagesaredescribedinthefollowingsections.

Direct3DPage

ThefollowingDirect3DpageisshownimmediatelyafterthefirstpageifyouselectedtheDirect3Dcheckboxinstep1.

TheDirect3Dpageisstep2becausestep1wasthefirstpageofthewizard.

TheDirect3Dexclusiveoptionsare:

1. Blank.NoDirect3Dobjectiscreated.2. Triangle.Createsasimpleobjectwithtwoback-to-backtriangles.3. Teapot.CreatesacomplexobjectusingD3DXCreateTeapot.

IfDirect3Dfontsischecked,theprojectincludesD3dfont.cppandD3dfont.h.Otherwise,theprojectusesD3DXFonttodisplay3-Dfonts.

If3Dmeshesischecked,theprojectincludesD3dfile.cppandD3dfile.h.

DirectInputPage

ThefollowingDirectInputpageisshownimmediatelyaftertheDirect3DpageifyouselectedtheDirectInputcheckboxinstep1.

TheDirectInputpageisstep3.Theoptionsonthispageare:

DirectInputactionmapping.UsesActionMappingtogatherinputdata.DirectInputkeyboarddevice.Usesasimplekeyboarddevicetogatherinputdata.

Page 330: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IfyoucheckedDirectInputinstep1,theprojectwillincludeDiutil.cppandDiutil.cppfiles.TheDirectXSDKsample,Root\Samples\bin\Donut3D.exe,usestheseclassfiles.

TheapplicationwilluseeitherActionMapperorakeyboarddeviceobjecttorecordkeystate.Ifneitherischecked,DirectInputwilluseWM_KEYDOWNmessagestorecordkeystate.

DirectMusicandDirectSoundCheckBoxes

Thesecheckboxesappearonpage1ofthewizard.Theydonoaddpagestothewizard.

IfDirectMusicischecked,theprojectwillincludeDmutil.cppandDmutil.h.TheDirectMusicsamplesusethesefiles.

IfDirectSoundischecked,theprojectwillincludeDsutil.cppandDsutil.h.TheDirectSoundsamplesusethesefilestoloadandplaysounds.

IfbothDirectMusicandDirectSoundarechecked,DirectMusicisusedtoloadandplaythesounds,butDsutil.*isstillincludedintheproject.

IfeitherDirectMusicorDirectSoundischecked,Bounce.wavisincludedintheproject.PressingtheAkeywillplaythesound.

IfneitherDirectMusicnorDirectSoundischecked,bounce.wavisnotincludedandtheAkeyisnotrecorded,noristheHelpstringdisplayed.

DirectPlayPage

ThefollowingDirectPlaypageisshownimmediatelyaftertheDirectInputpageifyouselectedtheDirectPlayPeer-to-Peercheckboxinstep1.

TheDirectPlaypageisstep4,assumingthatstep1wasthefirstpageofthewizard,step2wastheDirect3Dpage,andstep3wastheDirectInputpage.

IfDirectVoiceischecked,theprojectwillincludeNetvoice.cppandNetvoice.h.TheDirectPlayVoicesamplesusethesefiles.

Page 331: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

TheprojectwillintegratetheNetConnectDirectPlayconnectiondialogboxesintotheapplication.WhentheNetConnectdialogboxesfinish,anactiveDirectPlayconnectionorfailureresults.Ifsuccessful,thearrowkeystateispassedbetweenallplayersusingDirectPlay.

IfDirectInputActionMapperisused,DirectPlaysendstheaxisdataacrossthenetwork;otherwiseitsendsthestateofthefourarrowkeys.

Page 332: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 333: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DirectXGraphicsC/C++TutorialsThetutorialsinthissectionshowhowtouseMicrosoft®Direct3D®andDirect3DXinaC/C++applicationforcommontasks.Thetasksaredividedintorequiredsteps.Insomecases,stepsareorganizedintosubstepsforclarity.

Thefollowingtutorialsareprovided.

Tutorial1:CreatingaDeviceTutorial2:RenderingVerticesTutorial3:UsingMatricesTutorial4:CreatingandUsingLightsTutorial5:UsingTextureMapsTutorial6:UsingMeshes

NoteThesamplecodeinthesetutorialsisfromsourceprojectswhoselocationisprovidedineachtutorial.

ThesamplefilesinthesetutorialsarewritteninC++.IfyouareusingaCcompiler,youmustmaketheappropriatechangestothefilesforthemtosuccessfullycompile.Attheveryleast,youneedtoaddthevtableandthispointerstotheinterfacemethods.

SomecommentsintheincludedsamplecodemightdifferfromthesourcefilesintheMicrosoftPlatformSoftwareDevelopmentKit(SDK).Changesaremadeforbrevityonlyandarelimitedtocommentstoavoidchangingthebehaviorofthesamplecode.

SeeAlso

DirectXGraphicsC/C++Samples

Page 334: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 335: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Direct3DC/C++ReferenceThissectioncontainsreferenceinformationfortheAPIelementsprovidedbyMicrosoft®Direct3D®.Referencematerialisdividedintothefollowingcategories.

InterfacesFunctionsMacrosVertexShaderDeclaratorMacrosStructuresEnumeratedTypesOtherTypesTextureArgumentFlagsFlexibleVertexFormatFlagsReturnValues

Page 336: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 337: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Direct3DXC/C++ReferenceThissectioncontainsreferenceinformationfortheAPIelementsprovidedbytheDirect3DXutilitylibrary.Referencematerialisdividedintothefollowingcategories.

InterfacesFunctionsMacrosStructuresEnumeratedTypesandFlagsC++SpecificFeaturesReturnValues

Page 338: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 339: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

XFileC/C++ReferenceThissectioncontainsreferenceinformationfortheapplicationprogramminginterface(API)elementsyouusetoworkwithMicrosoft®DirectX®.xfiles.

InterfacesFunctionsStructuresReturnValuesXFileFormatReference

Page 340: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 341: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

GettingStartedwithDirect3DThissectionprovidesabriefintroductiontothethree-dimensional(3-D)graphicsfunctionalityintheMicrosoft®Direct3D®applicationprogrammerinterface(API).HereyouwillfindanoverviewofthegraphicspipelineandtutorialstohelpyougetbasicDirect3Dfunctionalityupandrunningquickly.

Direct3DArchitectureDirectXGraphicsC/C++Tutorials

Page 342: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 343: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

UsingDirect3DThissectionexplainstheoperationoftheMicrosoft®Direct3D®fixedfunctionpipeline.Thepipelineconsistsofseveralbuildingblocks.Theseblocksaredetailedinthefollowingsections.

VertexData

Transforms

ViewportsandClipping

LightsandMaterials

Textures

Rendering

AboutDevices

Page 344: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 345: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ProgrammablePipelineUsingshadersandeffects,developerscannowprogramthepipeline.Thesetopicsarecoveredinthefollowingsections.

VertexShadersPixelShadersEffects

Page 346: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 347: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

AdvancedTopics

Microsoft®Direct3D®providesapowerfulsetoftoolsthatyoucanusetoincreasetherealisticappearanceofa3-Dscene.ThissectionpresentsinformationoncommonspecialeffectsthatcanbeproducedwithDirect3D,buttherangeofpossibleeffectsisnotlimitedtothosepresentedhere.Thediscussioninthissectionisorganizedintothefollowingtopics.

AntialiasingBumpMappingEnvironmentMappingGeometryBlendingIndexedVertexBlendingMatrixStacksStencilBufferTechniquesVertexTweeningObjectGeometry

Page 348: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 349: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Direct3DAppendixThissectioncontainsadditionalmaterialthatcoverstopicssuchasfileformatsandtipsforperformanceimprovements.

DDSFileFormat

ThissectionexplainstheDDSfileformatindetail.

DeviceStates

Thissectionexplainsdevicestates,whichareusedtosetrenderingandtexturingattributes.

ProgrammingTips

Thesetipsarederivedfromlessonslearnedfromprogrammingtopicssuchastroubleshootingaprogram,implementingmultithreading,oroptimizingcodeforperformance.

XFiles

ThissectionexplainsXfilesindepth,includingtheirarchitecture,thefileformat,andsomesamplesoffileloadingandsaving.

MeshViewHelp

Thissectionoutlinesthefunctionalitythatisavailableinthemeshviewexecutable.Thishandyexecutablecanbeusedtoexperimentwithmeshesbyapplyingdifferentmeshutilityoperations.ThisapplicationispartoftheSDKinstall.

Page 350: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(version1.0,1.1)

Page 351: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

CreateaVertexShader

Thisexamplecreatesavertexshaderthatappliesaconstantcolortoanobject.TheexamplewillshowthecontentsoftheshaderfileaswellasthecoderequiredintheapplicationtosetuptheMicrosoft®Direct3D®pipelinefortheshaderdata.

Tocreateavertexshader

Step1:DeclarethevertexdataStep2:DesigntheshaderfunctionalityStep3:CheckforvertexshadersupportStep4:DeclaretheshaderregistersStep5:CreatetheshaderStep6:Rendertheoutputpixels

IfyoualreadyknowhowtobuildandrunDirect3Dsamples,youcancutandpastecodefromthisexampleintoyourexistingapplication.

Step1:Declarethevertexdata

Thisexampleusesaquadrilateralthatismadeupoftwotriangles.Thevertexdatawillcontain(x,y,z)positionandadiffusecolor.TheD3DFVF_CUSTOMVERTEXmacroisdefinedtomatchthevertexdata.Thevertexdataisdeclaredinaglobalarrayofvertices(g_Vertices).Thefourverticesarecenteredabouttheorigin,andeachvertexisgivenadifferentdiffusecolor.

//Declarevertexdatastructure.

structCUSTOMVERTEX

{

FLOATx,y,z;

DWORDdiffuseColor;

};

//DeclarecustomFVFmacro.

#defineD3DFVF_CUSTOMVERTEX(D3DFVF_XYZ|D3DFVF_DIFFUSE)

//Declarethevertexpositionanddiffusecolordata.

CUSTOMVERTEXg_Vertices[]=

{

Page 352: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//xyzdiffusecolor

{-1.0f,-1.0f,0.0f,0xffff0000},//red-bottomright

{+1.0f,-1.0f,0.0f,0xff00ff00},//green-bottomleft

{+1.0f,+1.0f,0.0f,0xff0000ff},//blue-topleft

{-1.0f,+1.0f,0.0f,0xffffff00},//redandgreen=yellow-topright

};

Step2:Designtheshaderfunctionality

Thisshaderappliesaconstantcolortoeachvertex.TheshaderfileVertexShader.vshfollows:

vs.1.0//versioninstruction

m4x4oPos,v0,c0//transformverticesbyview/projectionmatrix

movoD0,c4//loadconstantcolor

Thisfilecontainsthreeinstructions.

Thefirstinstructioninashaderfilemustbetheshaderversiondeclaration.Thisinstruction(vs)declaresthevertexshaderversion,whichis1.0inthiscase.

Thesecondinstruction(m4x4)transformstheobjectverticesusingtheview/projectionmatrix.Thematrixisloadedintofourconstantregistersc0,c1,c2,c3(asshownbelow).

Thethirdinstruction(mov)copiestheconstantcolorinregisterc4totheoutputdiffusecolorregisteroD0.Thisresultsincoloringtheoutputvertices.

Step3:Checkforvertexshadersupport

Thedevicecapabilitycanbequeriedforvertexshadersupportbeforeusingavertexshader.

D3DCAPS8caps;

m_pd3dDevice->GetDeviceCaps(∩);//initializem_pd3dDevicebeforeusingif(D3DSHADER_VERSION_MAJOR(caps.VertexShaderVersion)<1)

returnE_FAIL;

ThecapsstructurereturnsthefunctionalcapabilitiesofthehardwareafterGetDeviceCapsiscalled.UsetheD3DSHADER_VERSION_MAJORmacrototestthesupportedversionnumber.Iftheversionnumberislessthan1.0,thiscallwillfail.Theresultofthismethodshouldbeusedtocontrolwhetherornot

Page 353: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

vertexshadersareinvokedbyanapplication.

Step4:Declaretheshaderregisters

Theshaderiscreatedbydeclaringtheshaderregistersandcompilingtheshaderfile.Oncecreated,Direct3Dreturnsashaderhandle,whichisanintegernumberthatisusedtoidentifytheshader.

//Createtheshaderdeclaration.

DWORDdwDecl[]=

{

D3DVSD_STREAM(0),

D3DVSD_REG(D3DVSDE_POSITION,D3DVSDT_FLOAT3),

D3DVSD_REG(D3DVSDE_DIFFUSE,D3DVSDT_D3DCOLOR),

D3DVSD_END()

};

Thevertexdeclarationdeclaresthemappingbetweeninputdatastreamsandvertexbuffers.Multiplestreamscanbedeclaredintheshaderdeclaration,uptothenumberspecifiedintheMaxStreamscap.VertexbuffersareassociatedwithinputstreamsusingSetStreamSourceasillustratedinstep5.

Step5:Createtheshader

Theshaderisassembledandcreatednext.

//Createthevertexshader.

TCHARstrPath[512];//locationoftheshaderfile

LPD3DXBUFFERpCode;//assembledshadercode

DXUtil_FindMediaFile(strPath,_T("VertexShader.vsh"));

D3DXAssembleShaderFromFile(strPath,0,NULL,&pCode;,NULL);//assembleshadercode

m_pd3dDevice->CreateVertexShader(dwDecl,(DWORD*)pCode->GetBufferPointer(),&m;_hVertexShader,0)))

pCode->Release();

Oncetheshaderfileislocated,D3DXAssembleShaderFromFilereadsandvalidatestheshaderinstructions.CreateVertexShadertakestheshaderdeclarationandtheassembledinstructionsandcreatestheshader.Itreturnstheshaderhandle,whichisusedtorendertheoutput.

CreateVertexShadercanbeusedtocreateprogrammableorfixedfunctionshaders.Programmableshadersaregeneratedifapointertoashaderdeclarationispassedasthesecondparameter.Otherwise,afixedfunctionvertexshaderis

Page 354: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

generatedifNULLispassedasthesecondparameter.

Step6:Rendertheoutputpixels

Hereisanexampleofthecodethatcouldbeusedintherenderlooptorendertheobject,usingthevertexshader.Therenderloopupdatesthevertexshaderconstantsasaresultofchangesinthe3-DsceneanddrawstheoutputverticeswithacalltoDrawPrimitive.

//Turnlightingoff.Thisisincludedforclaritybutisnotrequired.

m_pd3dDevice->SetRenderState(D3DRS_LIGHTING,FALSE);

//Updatevertexshaderconstantsfromviewprojectionmatrixdata.

D3DXMATRIXmat,matView,matProj;

D3DXMatrixMultiply(&mat;,&matView;,&matProj;);

D3DXMatrixTranspose(&mat;,&mat;);

m_pd3dDevice->SetVertexShaderConstant(0,&mat;,4);

//Declareanddefinetheconstantvertexcolor.

floatcolor[4]={0,1,0,0};

m_pd3dDevice->SetVertexShaderConstant(4,&color;,1);

//Rendertheoutput.

m_pd3dDevice->SetStreamSource(0,m_pQuadVB,sizeof(CUSTOMVERTEX));

m_pd3dDevice->SetVertexShader(m_hVertexShader);

m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,0,2);

Lightingisturnedoffjusttomakeitclearthatthevertexcolorisfromtheshaderonly.Thisstatementisoptionalinthisexample.

Theviewandprojectionmatrixescontaincamerapositionandorientationdata.Gettingupdateddataandupdatingtheshaderconstantregistersisincludedintherenderloopbecausethescenemightchangebetweenrenderedframes.

Asusual,DrawPrimitiverenderstheoutputdatausingthevertexdataprovidedfromSetStreamSource.SetVertexShaderiscalledtotellDirect3Dtousethevertexshader.Theresultofthevertexshaderisshowninthefollowingimage.Itshowstheconstantcolorontheplaneobject.

Page 355: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(shaderversions1.0,1.1)

Page 356: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Shader2-Applyvertexcolors

Thisexampleappliesthevertexcolorfromthevertexdatatotheobject.Thevertexdatacontainspositiondataaswellasdiffusecolordata.Thisisreflectedinthevertexdeclarationandthefixedvertexfunctionmacro.Theseareshownbelow.

structCUSTOMVERTEX_POS_COLOR

{

floatx,y,z;

DWORDdiffuseColor;

};

#defineD3DFVF_CUSTOMVERTEX_POS_COLOR(D3DFVF_XYZ|D3DFVF_DIFFUSE)

//Createvertexdatawithpositionandtexturecoordinates.

CUSTOMVERTEX_POS_COLORg_Vertices[]=

{

//xyzdiffuse

{-1.0f,0.25f,0.0f,0xffff0000,}, //-bottomright-red

{0.0f,0.25f,0.0f,0xff00ff00,}, //-bottomleft-green

{0.0f,1.25f,0.0f,0xff0000ff,}, //-topleft-blue

{-1.0f,1.25f,0.0f,0xffffffff,}, //-topright-white

};

Thevertexshaderdeclarationneedstoreflectthepositionandcolordataalso.

DWORDdwDecl2[]=

{

D3DVSD_STREAM(0),

D3DVSD_REG(0,D3DVSDT_FLOAT3),//Register0willcontainthepositiondata.

D3DVSD_REG(1,D3DVSDT_D3DCOLOR),//Register1willcontainthecolordata.

D3DVSD_END()

};

Onewayfortheshadertogetthetransformationmatrixisfromaconstantregister.ThisisdonebycallingSetVertexShaderConstant.

D3DXMATRIXmat;

D3DXMatrixMultiply(&mat;,&m;_matView,&m;_matProj);

D3DXMatrixTranspose(&mat;,&mat;);

hr=m_pd3dDevice->SetVertexShaderConstant(1,&mat;,4);

if(FAILED(hr))returnhr;

Thisdeclarationdeclaresonestreamofdata,whichcontainsthepositionandthe

Page 357: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

colordata.Thecolordataisassignedtovertexregister7.

Lastly,hereistheshaderfile.

vs.1.0;versioninstruction

m4x4oPos,v0,c0;transformverticesbyview/projectionmatrix

movoD0,v1;loadcolorfromregister7todiffusecolor

Itcontainsthreeinstructions.Thefirstisalwaystheversioninstruction.Thesecondinstructiontransformsthevertices.Thethirdinstructionmovesthecolorinthevertexregistertotheoutputdiffusecolorregister.Theresultisoutputverticesusingthevertexcolordata.

Theresultingoutputlookslikethefollowing:

//Hereisanexampleoftheclassusedtoproducethisvertexshader.

//Thisexampleisforillustrationonly.Ithasnotbeenoptimizedforperformance.

//CVShader.h

//Usevertexcolortocolortheobject.

CUSTOMVERTEX_POS_COLORg_VerticesVS[]=

{

//xyzdiffuse

{-1.0f,0.25f,0.0f,0xffff0000,}, //-bottomright-red

{0.0f,0.25f,0.0f,0xff00ff00,}, //-bottomleft-green

{0.0f,1.25f,0.0f,0xff0000ff,}, //-topleft-blue

{-1.0f,1.25f,0.0f,0xffffffff,}, //-topright-red

};

classCVShader

{

public:

CVShader();

HRESULTConfirmDevice(D3DCAPS8*pCaps,DWORDdwBehavior,D3DFORMATFormat);

HRESULTDeleteDeviceObjects();

HRESULTRender();

HRESULTRestoreDeviceObjects(LPDIRECT3DDEVICE8l_pd3dDevice);

HRESULTInitMatrices();

HRESULTUpdateVertexShaderConstants();

private:

Page 358: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

LPDIRECT3DVERTEXBUFFER8 m_pQuadVB;

LPDIRECT3DDEVICE8 m_pd3dDevice;

DWORD m_hVertexShader;

D3DXMATRIX m_matView;

D3DXMATRIX m_matProj;

};

CVShader::CVShader()

{

m_pQuadVB =NULL;

m_pd3dDevice =NULL;

m_hVertexShader =0;

}

HRESULTCVShader::ConfirmDevice(D3DCAPS8*pCaps,DWORDdwBehavior,

D3DFORMATFormat)

{

if(D3DSHADER_VERSION_MAJOR(pCaps->VertexShaderVersion)<1)

returnE_FAIL;

returnS_OK;

}

HRESULTCVShader::DeleteDeviceObjects()

{

SAFE_RELEASE(m_pQuadVB);

HRESULThr;

if(m_hVertexShader>0)

{

hr=m_pd3dDevice->DeleteVertexShader(m_hVertexShader);

if(FAILED(hr))

{

::MessageBox(NULL,"","DeleteVertexShaderfailed",MB_OK);

returnE_FAIL;

}

m_hVertexShader=0;

}

//localtothisclass

m_pd3dDevice=NULL;

returnS_OK;

}

HRESULTCVShader::InitMatrices()

Page 359: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

{

HRESULThr;

D3DXVECTOR3from(0.0f,0.0f,3.0f);

D3DXVECTOR3at(0.0f,0.0f,0.0f);

D3DXVECTOR3up(0.0f,1.0f,0.0f);

D3DXMATRIXmatWorld;

D3DXMatrixIdentity(&matWorld;);

hr=m_pd3dDevice->SetTransform(D3DTS_WORLD,&matWorld;);

D3DXMatrixIdentity(&m;_matView);

D3DXMatrixLookAtLH(&m;_matView,&from;,&at;,&up;);

m_pd3dDevice->SetTransform(D3DTS_VIEW,&m;_matView);

D3DXMatrixIdentity(&m;_matProj);

D3DXMatrixPerspectiveFovLH(&m;_matProj,D3DX_PI/4,1.0f,0.5f,1000.0f);

m_pd3dDevice->SetTransform(D3DTS_PROJECTION,&m;_matProj);

returnS_OK;

}

HRESULTCVShader::Render()

{

if(m_pQuadVB)

{

HRESULThr;

hr=m_pd3dDevice->SetRenderState(D3DRS_LIGHTING,FALSE);

UpdateVertexShaderConstants();

hr=m_pd3dDevice->SetStreamSource(0,m_pQuadVB,

sizeof(CUSTOMVERTEX_POS_COLOR));

hr=m_pd3dDevice->SetVertexShader(m_hVertexShader);

hr=m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,0,2);

}

returnS_OK;

}

HRESULTCVShader::RestoreDeviceObjects(LPDIRECT3DDEVICE8l_pd3dDevice)

{

HRESULThr;

if(l_pd3dDevice==NULL)

{

::MessageBox(NULL,"","InvalidD3D8Deviceptr",MB_OK);

returnE_FAIL;

Page 360: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

}

else

m_pd3dDevice=l_pd3dDevice;

InitMatrices();

//CreatequadVertexBuffer.

hr=m_pd3dDevice->CreateVertexBuffer(4*sizeof(CUSTOMVERTEX_POS_COLOR),

D3DUSAGE_WRITEONLY,

D3DFVF_CUSTOMVERTEX_POS_COLOR,

D3DPOOL_DEFAULT,

&m;_pQuadVB);

if(FAILED(hr))returnhr;

//FillthequadVB.

CUSTOMVERTEX_POS_COLOR1*pVertices=NULL;

hr=m_pQuadVB->Lock(0,4*sizeof(CUSTOMVERTEX_POS_COLOR),(BYTE**)&pVertices;,0);

if(FAILED(hr))returnhr;

for(DWORDi=0;i<4;i++)

pVertices[i]=g_VerticesVS2[i];

m_pQuadVB->Unlock();

//Createthevertexshader.

TCHARstrVertexShaderPath[512];

LPD3DXBUFFERpCode;

DWORDdwDecl2[]=

{

D3DVSD_STREAM(0),

D3DVSD_REG(0,D3DVSDT_FLOAT3),

D3DVSD_REG(1,D3DVSDT_D3DCOLOR),

D3DVSD_END()

};

//Findthevertexshaderfile.

DXUtil_FindMediaFile(strVertexShaderPath,_T("VShader.vsh"));

//Assemblethevertexshaderfromthefile.

if(FAILED(hr=D3DXAssembleShaderFromFile(strVertexShaderPath,

0,NULL,&pCode;,NULL)))

returnhr;

//Createthevertexshader.

if(SUCCEEDED(hr=m_pd3dDevice->CreateVertexShader(dwDecl2,

(DWORD*)pCode->GetBufferPointer(),&m;_hVertexShader,0)))

pCode->Release();

Page 361: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

returnhr;

}

HRESULTCVShader::UpdateVertexShaderConstants()

{

HRESULThr;

D3DXMATRIXmat;

D3DXMatrixMultiply(&mat;,&m;_matView,&m;_matProj);

D3DXMatrixTranspose(&mat;,&mat;);

hr=m_pd3dDevice->SetVertexShaderConstant(1,&mat;,4);

returnhr;

}

Page 362: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(version1.0,1.1)

Page 363: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Shader3-Applyatexturemap

Thisexampleappliesatexturemaptotheobject.

Thevertexdatacontainsobjectpositiondataaswellastexturepositionoruvdata.Thiscauseschangestothevertexdeclarationstructureandthefixedvertexfunctionmacro.Thevertexdataisalsoshownbelow.

structCUSTOMVERTEX_POS_TEX1

{

floatx,y,z; //objectpositiondata

floattu1,tv1; //texturepositiondata

};

#defineD3DFVF_CUSTOMVERTEX_POS_TEX1(D3DFVF_XYZ|D3DFVF_TEX1)

CUSTOMVERTEX_POS_TEX1g_Vertices[]=

{

//xyzu1v1

{-0.75f,-0.5f,0.0f,0.0f,0.0f}, //-bottomright

{0.25f,-0.5f,0.0f,1.0f,0.0f}, //-bottomleft

{0.25f,0.5f,0.0f,1.0f,-1.0f}, //-topleft

{-0.75f,0.5f,0.0f,0.0f,-1.0f}, //-topright

};

D3DUtil_CreateTexture(m_pd3dDevice,_T("earth.bmp"),&m;_pTexture0,D3DFMT_R5G6B5);

Thetextureimagemustbeloaded.Inthiscase,thefile"earth.bmp"containsa2-Dtexturemapoftheearthandwillbeusedtocolortheobject.

Thevertexshaderdeclarationneedstoreflecttheobjectpositionandtexturepositiondata.

DWORDdwDecl2[]=

{

D3DVSD_STREAM(0),

D3DVSD_REG(D3DVSDE_POSITION,D3DVSDT_FLOAT3),

D3DVSD_REG(8,D3DVSDT_FLOAT2),

D3DVSD_END()

};

Thisdeclarationdeclaresonestreamofdatathatcontainstheobjectpositionandthetexturepositiondata.Thetexturepositiondataisassignedtovertexregister8.

Page 364: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

TherenderingcodetellsMicrosoft®Direct3D®wheretofindthedatastreamandtheshader,andsetsuptexturestagesbecauseatexturemapisbeingapplied.

m_pd3dDevice->SetStreamSource(0,m_pQuadVB,sizeof(CUSTOMVERTEX_POS_TEX1));

m_pd3dDevice->SetVertexShader(m_hVertexShader);

m_pd3dDevice->SetTextureStageState(0,D3DTSS_COLOROP,D3DTOP_MODULATE);

m_pd3dDevice->SetTextureStageState(0,D3DTSS_COLORARG1,D3DTA_TEXTURE);

m_pd3dDevice->SetTextureStageState(0,D3DTSS_COLORARG2,D3DTA_DIFFUSE);

m_pd3dDevice->SetTexture(0,m_pTexture0);

m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,0,2);

m_pd3dDevice->SetTexture(0,NULL);

Becausethereisasingletexture,thetexturestagestatesneedtobesetfortexturestate0.ThesemethodstellDirect3Dthatthetexelvalueswillbeusedtoprovidediffusecolorfortheobjectvertices.Inotherwords,a2-Dtexturemapwillbeappliedlikeadecal.

Hereistheshaderfile.

vs.1.0 ;versioninstruction

m4x4oPos,v0,c0 ;transformverticesbyview/projectionmatrix

movoT0,v8 ;movetexturecolortooutputtextureregister

Theshaderfilecontainsthreeinstructions.Thefirstisalwaystheversioninstruction.Thesecondinstructiontransformsthevertices.Thethirdinstructionmovesthetexturecolorsfromregisterv8totheoutputdiffusecolorregister.Thatresultsinatexturemappedobject,whichisshownbelow.

Page 365: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(version1.0,1.1)

Page 366: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Shader4-Applyatexturemapwithlighting

Thisexampleusesavertexshadertoapplyatexturemapandaddlightingtothescene.Theobjectusedisasphere.Thesamplecodeappliesatexturemapoftheearthtothesphereandappliesdiffuselightingtosimulatenightandday.

ThecodesampleaddstotheShader3examplebyaddinglightingtoatexturemappedobject.RefertoShader3forinformationaboutloadingthetexturemapandsettingupthetexturestagestates.

ThereisadetailedexplanationofthesamplecodeframeworkatSampleFramework.Youcancutandpastethesamplecodeintothesampleframeworktoquicklygetaworkingsample.

CreateVertexShader

ThevertexdatahasbeenmodifiedfromtheShader3sampletoincludevertexnormals.Forlightingtoappear,theobjectmusthavevertexnormals.Thedatastructureforthevertexdataandtheflexiblevertexformat(FVF)macrousedtodeclarethedatatypeareshownbelow.

structCUSTOMVERTEX_POS_NORM_COLOR1_TEX1

{

floatx,y,z;//position

floatnx,ny,nz;//normal

DWORDcolor1;//diffusecolor

floattu1,tv1;//texturecoordinates

};

#defineD3DFVF_CUSTOMVERTEX_POS_NORM_COLOR1_TEX1(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_DIFFUSE|D3DFVF_TEX1)

Ashaderdeclarationdefinestheinputvertexregistersandthedataassociatedwiththem.ThismatchestheFVFmacrousedtocreatethevertexbufferdatalater.

DWORDdwDecl[]=

{

D3DVSD_STREAM(0),

D3DVSD_REG(0,D3DVSDT_FLOAT3),//position

D3DVSD_REG(4,D3DVSDT_FLOAT3),//normal

D3DVSD_REG(7,D3DVSDT_D3DCOLOR),//diffusecolor

Page 367: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DVSD_REG(8,D3DVSDT_FLOAT2),//texturecoordinate

D3DVSD_END()

};

Thisdeclaresonestreamofdata,whichcontainsthevertexposition,normal,diffusecolor,andtexturecoordinates.Theintegerineachlineistheregisternumberthatwillcontainthedata.So,thetexturecoordinatedatawillbeinregisterv8,forinstance.

Next,createtheshaderfile.YoucancreateashaderfromanASCIItextstringorloaditfromashaderfilethatcontainsthesameinstructions.Thisexampleusesashaderfile.

//Shaderfile

//v7vertexdiffusecolorusedforthelightcolor

//v8texture

//c4viewprojectionmatrix

//c12lightdirection

vs.1.0//versioninstruction

m4x4oPos,v0,c4//transformverticesusingviewprojectiontransform

dp3r0,v4,c12//performlightingNdotLcalculationinworldspace

muloD0,r0.x,v7//calculatefinalpixelcolorfromlightintensityand

//interpolateddiffusevertexcolor

movoT0.xy,v8//copytexturecoordinatestooutput

Youalwaysentertheversioninstructionfirst.ThelastinstructionmovesthetexturedatatotheoutputregisteroT0.Afteryouwritetheshaderinstructions,youcanusethemtocreatetheshader.

//Nowthatthefileexists,useittocreateashader.

TCHARstrVertexShaderPath[512];

LPD3DXBUFFERpCode;

DXUtil_FindMediaFile(strVertexShaderPath,_T("VShader3.vsh"));

D3DXAssembleShaderFromFile(strVertexShaderPath,0,NULL,&pCode,NULL);

m_pd3dDevice->CreateVertexShader(dwDecl,(DWORD*)pCode->GetBufferPointer(),&m_hVertexShader,0);

pCode->Release();

Afterthefileislocated,Direct3Dcreatesthevertexshaderandreturnsashaderhandleandtheassembledshadercode.Thissampleusesashaderfile,whichisonemethodforcreatingashader.TheothermethodistocreateanASCIItextstringwiththeshaderinstructionsinit.Foranexample,seeProgrammableShadersforDirectX8.0.

VertexShaderConstants

Page 368: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Youcandefinevertexshaderconstantsoutsideoftheshaderfileasshowninthefollowingexample.Here,youuseconstantstoprovidetheshaderwithaview/projectionmatrix,adiffuselightcolor,RGBA,andthelightdirectionvector.

floatconstants[4]={0,0.5f,1.0f,2.0f};

m_pd3dDevice->SetVertexShaderConstant(0,&constants;,1);

D3DXMATRIXmat;

D3DXMatrixMultiply(&mat;,&m;_matView,&m;_matProj);

D3DXMatrixTranspose(&mat;,&mat;);

m_pd3dDevice->SetVertexShaderConstant(4,&mat;,4);

floatcolor[4]={1,1,1,1};

m_pd3dDevice->SetVertexShaderConstant(8,&color;,1);

floatlightDir[4]={-1,0,1,0};//fatterslice

m_pd3dDevice->SetVertexShaderConstant(12,&lightDir;,1);

Youcanalsodefineconstantsinsideashaderusingthedefinstruction

Render

Afteryouwritetheshaderinstructions,connectthevertexdatatothecorrectvertexregistersandinitializetheconstants,youshouldrendertheoutput.RenderingcodetellsDirect3DwheretofindthevertexbufferdatastreamandprovidesDirect3Dwiththeshaderhandle.Becauseyouuseatexture,youmustsettexturestagestotellDirect3Dhowtousethetexturedata.

//Identifythevertexbufferdatasource.

m_pd3dDevice->SetStreamSource(0,m_pVB,sizeof(CUSTOMVERTEX_POS_NORM_COLOR1_TEX1));

//Identifytheshader.

m_pd3dDevice->SetVertexShader(m_hVertexShader);

//Definethetexturestage(s)andsetthetexture(s)used

m_pd3dDevice->SetTextureStageState(0,D3DTSS_COLOROP,D3DTOP_MODULATE);

m_pd3dDevice->SetTextureStageState(0,D3DTSS_COLORARG1,D3DTA_TEXTURE);

m_pd3dDevice->SetTextureStageState(0,D3DTSS_COLORARG2,D3DTA_DIFFUSE);

m_pd3dDevice->SetTexture(0,m_pTexture0);

//Drawtheobject.

DWORDdwNumSphereVerts=2*m_dwNumSphereRings*(m_dwNumSphereSegments+1);

m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,dwNumSphereVerts-2);

//SetthetexturestagetoNULLaftertherendercommands.Leavingthis

Page 369: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//outwillcauseamemoryleak.

m_pd3dDevice->SetTexture(0,NULL);

Theoutputimagefollows:

Withthetexturemapapplied,thespherelooksliketheplanetEarth.Thelightingcreatesabrighttodarkgradientonthefaceoftheglobe.

AdditionalCode

Thereisadditionalcoderequiredtosupportthisexample.Shownbelowareafewoftheothermethodsforcreatingthesphereobject,loadingthetexture,andcheckingforthecorrectversionofpixelshadersupport.

//Confirmthatthehardwaresupportsversion1shaderinstructions.

if(D3DSHADER_VERSION_MAJOR(pCaps->VertexShaderVersion)<1)

returnE_FAIL;

//Loadtexturemapforthesphereobject.

LPDIRECT3DTEXTURE8m_pTexture0;

D3DUtil_CreateTexture(m_pd3dDevice,_T("earth.bmp"),&m;_pTexture0,D3DFMT_R5G6B5);

//Createthesphereobject.

DWORDdwNumSphereVerts=2*m_dwNumSphereRings*(m_dwNumSphereSegments+1);

//onceforthetop,onceforthebottomvertices

//GettheWorld-View(WV)matrixset.

D3DXMATRIXmatWorld,matView,matWorldView;

m_pd3dDevice->GetTransform(D3DTS_WORLD,&matWorld;);

m_pd3dDevice->GetTransform(D3DTS_VIEW,&matView;);

D3DXMatrixMultiply(&matWorldView;,&matWorld;,&matView;);

m_pd3dDevice->CreateVertexBuffer(

dwNumSphereVerts*sizeof(CUSTOMVERTEX_POS_NORM_COLOR1_TEX1),

D3DUSAGE_WRITEONLY,

D3DFVF_CUSTOMVERTEX_POS_NORM_COLOR1_TEX1,

D3DPOOL_DEFAULT,

&m;_pVB) );

CUSTOMVERTEX_POS_NORM_COLOR1_TEX1*pVertices;

HRESULThr;

hr=m_pVB->Lock(0,dwNumSphereVerts*sizeof(pVertices),

(BYTE**)&pVertices;,0);

if(SUCCEEDED(hr))

Page 370: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

{

FLOATfDeltaRingAngle=(D3DX_PI/m_dwNumSphereRings);

FLOATfDeltaSegAngle=(2.0f*D3DX_PI/m_dwNumSphereSegments);

//Generatethegroupofringsforthesphere.

for(DWORDring=0;ring<m_dwNumSphereRings;ring++)

{

FLOATr0=sinf((ring+0)*fDeltaRingAngle);

FLOATr1=sinf((ring+1)*fDeltaRingAngle);

FLOATy0=cosf((ring+0)*fDeltaRingAngle);

FLOATy1=cosf((ring+1)*fDeltaRingAngle);

//Generatethegroupofsegmentsforthecurrentring.

for(DWORDseg=0;seg<(m_dwNumSphereSegments+1);seg++)

{

FLOATx0=r0*sinf(seg*fDeltaSegAngle);

FLOATz0=r0*cosf(seg*fDeltaSegAngle);

FLOATx1=r1*sinf(seg*fDeltaSegAngle);

FLOATz1=r1*cosf(seg*fDeltaSegAngle);

//Addtwoverticestothestrip,whichmakesupthesphere

//(usingthetransformednormaltogeneratetexturecoords).

pVertices->x=x0;

pVertices->y=y0;

pVertices->z=z0;

pVertices->nx=x0;

pVertices->ny=y0;

pVertices->nz=z0;

pVertices->color=HIGH_WHITE_COLOR;

pVertices->tu=-((FLOAT)seg)/m_dwNumSphereSegments;

pVertices->tv=(ring+0)/(FLOAT)m_dwNumSphereRings;

pVertices++;

pVertices->x=x1;

pVertices->y=y1;

pVertices->z=z1;

pVertices->nx=x1;

pVertices->ny=y1;

pVertices->nz=z1;

pVertices->color=HIGH_WHITE_COLOR;

pVertices->tu=-((FLOAT)seg)/m_dwNumSphereSegments;

pVertices->tv=(ring+1)/(FLOAT)m_dwNumSphereRings;

pVertices++;

}

hr=m_pVB->Unlock();

}

}

Page 371: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 372: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

CreateaPixelShader

ThisexampleusesapixelshadertoapplyaGouraudinterpolateddiffusecolortoageometricplane.TheexamplewillshowthecontentsoftheshaderfileaswellasthecoderequiredintheapplicationtosetuptheMicrosoft®Direct3D®pipelinefortheshaderdata.

Tocreateapixelshader

1. Checkforpixelshadersupport.2. Declarethevertexdata.3. Designthepixelshader.4. Createthepixelshader.5. Rendertheoutputpixels.

IfyoualreadyknowhowtobuildandrunDirect3Dsamples,youshouldbeabletocutandpastecodefromthisexampleintoyourexistingapplication.

Step1:Checkforpixelshadersupport

Tocheckforpixelshadersupport,usethefollowingcode.Thisexamplechecksforpixelshaderversion1.1.

D3DCAPS8caps;

m_pd3dDevice->GetDeviceCaps(∩);//initm_pd3dDevicebeforeusingif(D3DPS_VERSION(1,1)!=caps.PixelShaderVersion)

returnE_FAIL;

Thecapsstructurereturnsthefunctionalcapabilitiesofthepipeline.UsetheD3DPS_VERSIONmacrototestforthesupportedshaderversionnumber.Iftheversionnumberislessthan1.1,thiscallwillfail.Ifthehardwaredoesnotsupporttheshaderversionthatistested,theapplicationwillhavetofallbacktoanotherrenderingapproach(perhapsalowershaderversionisavailable).

Step2:Declarethevertexdata

Thisexampleusesaplane,whichismadeupoftwotriangles.Thedatastructureforeachvertexwillcontainpositionanddiffusecolordata.The

Page 373: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

D3DFVF_CUSTOMVERTEXmacrodefinesadatastructuretomatchthevertexdata.Theactualvertexdataisdeclaredinaglobalarrayofverticescalledg_Vertices[].Thefourverticesarecenteredabouttheorigin,andeachvertexisgivenadifferentdiffusecolor.

//Declarevertexdatastructure.

structCUSTOMVERTEX

{

FLOATx,y,z;

DWORDdiffuseColor;

};

//DeclarecustomFVFmacro.

#defineD3DFVF_CUSTOMVERTEX(D3DFVF_XYZ|D3DFVF_DIFFUSE)

//Declarethevertexpositionanddiffusecolordata.

CUSTOMVERTEXg_Vertices[]=

{

//xyzdiffusecolor

{-1.0f,-1.0f,0.0f,0xffff0000},//red-bottomleft

{+1.0f,-1.0f,0.0f,0xff00ff00},//green-bottomright

{+1.0f,+1.0f,0.0f,0xff0000ff},//blue-topright

{-1.0f,+1.0f,0.0f,0xffffffff},//white-topleft

};

Step3:Designthepixelshader

ThisshadermovestheGouraudinterpolateddiffusecolordatatotheoutputpixels.TheshaderfilePixelShader.txtfollows:

ps.1.0//versioninstruction

movr0,v0//Movethediffusevertexcolortotheoutputregister.

Thefirstinstructioninapixelshaderfiledeclaresthepixelshaderversion,whichis1.0.

Thesecondinstructionmovesthecontentsofthecolorregister(v0)intotheoutputregister(r0).Thecolorregistercontainsthevertexdiffusecolorbecausethevertexdataisdeclaredtocontaintheinterpolateddiffusecolorinstep1.Theoutputregisterdeterminesthepixelcolorusedbytherendertarget(becausethereisnoadditionalprocessing,suchasfog,inthiscase).

Step4:Createthepixelshader

Page 374: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Thepixelshaderiscreatedfromthepixelshaderinstructions.Inthisexample,theinstructionsarecontainedinaseparatefile.Theinstructionscouldalsobeusedinatextstring.

TCHARstrPath[512];//usedtolocatetheshaderfile

LPD3DXBUFFERpCode;//pointstotheassembledshadercode

DXUtil_FindMediaFile(strPath,_T("PixelShader.txt"));

ThisfunctionisahelperfunctionusedbytheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

D3DXAssembleShaderFromFile(strPath,0,NULL,&pCode;,NULL);//assembleshadercode

m_pd3dDevice->CreatePixelShader((DWORD*)pCode->GetBufferPointer(),&m;_hPixelShader);

Oncetheshaderiscreated,thehandlem_hPixelShaderisusedtorefertoit.

Step5:Rendertheoutputpixels

Renderingtheoutputpixelsisverysimilartousingthefixedfunctionpipelinesequenceofcallsexceptthatthepixelshaderhandleisnowusedtosettheshader.

//Turnlightingoffforthisexample.Itwillnotcontributetothefinalpixelcolor.

//Thepixelcolorwillbedeterminedsolelybyinterpolatingthevertexcolors.

m_pd3dDevice->SetRenderState(D3DRS_LIGHTING,FALSE);

m_pd3dDevice->SetStreamSource(0,m_pQuadVB,sizeof(CUSTOMVERTEX));

m_pd3dDevice->SetVertexShader(D3DFVF_CUSTOMVERTEX);

m_pd3dDevice->SetPixelShader(m_hPixelShader);

m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,0,2);

ThesourceofthevertexdataissetwithSetStreamSource.Inthisexample,SetVertexShaderusesthesameFlexibleVertexFormat(FVF)macrousedduringvertexdatadeclarationtotellDirect3Dtodofixedfunctionvertexprocessing.Vertexshadersandpixelshadersmaybeusedtogetherorseparately.Thefixedfunctionpipelinecanalsobeusedinsteadofeitherpixelorvertexshaders.SetPixelShadertellsDirect3Dwhichpixelshadertouse,DrawPrimitivetellsDirect3Dhowtodrawtheplane.

Thegouraudshadedpixelsareshowninthefollowingimage.

Page 375: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

PixelShaderExamplescontainsexamplesthatshowhowtoapplytexturemapsandblendbetweentexturesandvertexcolors.

Page 376: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 377: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

TextureConsiderationsThepixelshadercompletelyreplacesthepixel-blendingfunctionalityspecifiedbytheMicrosoft®DirectX®6.0and7.0multi-texturingapplicationprogramminginterfaces(APIs),specificallythoseoperationsdefinedbytheD3DTSS_COLOROP,D3DTSS_COLORARG1,D3DTSS_COLORARG2,D3DTSS_ALPHAOP,D3DTSS_ALPHAARG1,andD3DTSS_ALPHAARG2texturestagestates,andassociatedargumentsandmodifiers.Whenaproceduralpixelshaderisset,thesestatesareignored.

Page 378: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

PixelShadersandTextureStageStates

Whenpixelshadersareinoperation,thefollowingtexturestagestatesarestillobserved.

D3DTSS_ADDRESSUD3DTSS_ADDRESSVD3DTSS_ADDRESSWD3DTSS_BUMPENVMAT00D3DTSS_BUMPENVMAT01D3DTSS_BUMPENVMAT10D3DTSS_BUMPENVMAT11D3DTSS_BORDERCOLORD3DTSS_MAGFILTERD3DTSS_MINFILTERD3DTSS_MIPFILTERD3DTSS_MIPMAPLODBIASD3DTSS_MAXMIPLEVELD3DTSS_MAXANISOTROPYD3DTSS_BUMPENVLSCALED3DTSS_BUMPENVLOFFSETD3DTSS_TEXCOORDINDEXD3DTSS_TEXTURETRANSFORMFLAGS

Becausethesetexturestagestatesarenotpartofthepixelshader,theyarenotavailableatshadercompiletimesothedrivercanmakenoassumptionsaboutthem.Forexample,thedrivercannotdifferentiatebetweenbilinearandtrilinearfilteringatthattime.Theapplicationisfreetochangethesestateswithoutrequiringtheregenerationofthecurrentlyboundshader.

Page 379: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

PixelShadersandTextureSampling

Texturesamplingandfilteringoperationsarecontrolledbythestandardtexturestagestatesforminification,magnification,mipfiltering,andthewrapaddressingmodes.Formoreinformation,seeTextureStageStates.Thisinformationisnotavailabletothedriveratshadercompiletime,soshadersmustbeabletocontinueoperationwhenthisstatechanges.Theapplicationisresponsibleforsettingtexturesofthecorrecttype(imagemap,cubemap,volumemap,etc.)neededbythepixelshader.Settingatextureoftheincorrecttypewillproduceunexpectedresults.

Page 380: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Post-ShaderPixelProcessing

Otherpixeloperations—suchasfogblending,stenciloperations,andrendertargetblending—occurafterexecutionoftheshader.Rendertargetblendingsyntaxisupdatedtosupportnewfeaturesasdescribedinthistopic.

PixelShaderInputs

Diffuseandspecularcolorsaresaturated(clamped)totherange0through1beforeusebytheshaderbecausethisistherangeofvalidinputstotheshader.

Colorvaluesinputtothepixelshaderareassumedtobeperspectivecorrect,butthisisnotguaranteedinallhardware.Colorsgeneratedfromtexturecoordinatesbytheaddressshaderarealwaysiteratedinaperspectivecorrectmanner.However,theyarealsoclampedtotherange0to1duringiteration.

PixelShaderOutputs

Theresultemittedbythepixelshaderisthecontentsofregisterr0.Whateveritcontainswhentheshadercompletesprocessingissenttothefogstageandrendertargetblender.

Page 381: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 382: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ConfirmingPixelShaderSupportYoucanquerymembersofD3DCAPS8todeterminethelevelofsupportforoperationsinvolvingpixelshaders.ThefollowingtableliststhedevicecapabilitiesrelatedtoprogrammablepixelprocessinginMicrosoft®DirectX®8.1.

Devicecapability Description

MaxPixelShaderValue

Rangeofvaluesthatmaybestoredinregistersis[-MaxPixelShaderValue,MaxPixelShaderValue].

MaxSimultaneousTextures Numberoftexturestagesthatcanbeusedintheprogrammablepixelshader.

PixelShaderVersion Levelofsupportforpixelshaders.

ThePixelShaderVersioncapabilityindicatesthelevelofpixelshadersupported.Onlypixelshaderswithversionnumbersequaltoorlessthanthisvaluewillbesuccessfullycreated.ThemajorversionnumberisencodedinthesecondbyteofPixelShaderVersion.Thelowbytecontainsaminorversionnumber.Thepixelshaderversionisindicatedbythefirsttokenineachshader.

EachimplementationsetsthePixelShaderVersionmembertoindicatethemaximumpixelshaderversionthatitcanfullysupport.ThisimpliesthatimplementationsshouldneverfailthecreationofavalidshaderoftheversionlessthanorequaltotheversionreportedbyPixelShaderVersion.

Page 383: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SettingPixelShaderTextureInputs

Thetexturecoordinatedataisinterpolatedfromthevertextexturecoordinatedataandisassociatedwithaspecifictexturestage.Thedefaultassociationisaone-to-onemappingbetweentexturestagenumberandtexturecoordinatedeclarationorder.Thismeansthatthefirstsetoftexturecoordinatesdefinedinthevertexformatare,bydefault,associatedwithtexturestage0.

Texturecoordinatescanbeassociatedwithanystage,usingeitherofthefollowingtwotechniques.Whenusingafixedfunctionvertexshader,thetexturestagestateflagTSS_TEXCOORDINDEXcanbeusedinIDirect3DDevice8::SetTextureStageStatetoassociatecoordinateswithastage.Otherwise,thetexturecoordinatesareoutputbythevertexshaderoTnregisterswhenusingaprogrammablevertexshader.

Page 384: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SettingthePixelShaderConstantRegisters

Youcanusethefollowingmethodstosetandretrievethevaluesinthepixelshaderconstantregisters.

IDirect3DDevice8::GetPixelShaderConstantIDirect3DDevice8::SetPixelShaderConstant

Inaddition,youcanusethedefinstructiontosettheconstantregistersofapixelshader,insideapixelshader.Thisinstructionmustcomebeforeallotherinstructionsexcepttheversioninstruction.

Page 385: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

CompilingandCreatingaPixelShader

TheDirect3DXutilitylibraryprovidesasetoffunctionstocompilepixelshaders.Thefollowingfunctionsareprovided.

D3DXAssembleShaderD3DXAssembleShaderFromFile

TheIDirect3DDevice8::CreatePixelShadercreateapixelshaderinDirectX8.1fromacompiledshaderdeclaration.ThecompiledshaderdeclarationisobtainedfromD3DXAssembleShader.

AgivenshadermightfailcreationbecauseoftherestraintsoftheDirectX8.1hardwaremodel.

Page 386: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 387: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

PixelShaderExamplesThetopicCreateaPixelShaderprovidesanexampleofhowtouseapixelshadertoapplyasinglediffusecolor.Thefollowingareexamplesofotherpixelshaderfunctions.Eachexamplebuildsonthepreviousexamplebyaddingapieceofadditionalpixelshaderfunctionality.

ApplyaTextureMapBlendaDiffuseVertexColorwithaTextureBlendTwoTexturesUsingaConstantColor

Page 388: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ApplyaTextureMap

Thisexampleappliesatexturemaptoaplane.Thedifferencesbetweenthisexampleandthepreviousexampleareasfollows:

ThevertexdatastructureandtheFlexibleVertexFormat(FVF)macroincludetexturecoordinates.Thevertexdataincludesu,vdata.Thevertexdatanolongerneedsdiffusecolorbecausethepixelcolorswillcomefromthetexturemap.Thetextureislinkedtotexturestage0withSetTexture.Becausethepreviousexampledidnotuseatexture,therewasnoSetTexturemethodused.Theshaderusesthet0textureregisterinsteadofthev0diffusecolorregister.

Thesamplecodefollows:

//Definevertexdatastructure.

structCUSTOMVERTEX

{

FLOATx,y,z;

FLOATu1,v1;

};

//DefinecorrespondingFVFmacro.

#defineD3DFVF_CUSTOMVERTEX(D3DFVF_XYZ|D3DFVF_TEX|D3DFVF_TEXCOORDSIZE2(0))

//Createvertexdatawithpositionandtexturecoordinates.

staticCUSTOMVERTEXg_Vertices[]=

{

//xyzu1v1

{-1.0f,-1.0f,0.0f,0,1,},

{1.0f,-1.0f,0.0f,1,1,},

{1.0f,1.0f,0.0f,1,0,},

{-1.0f,1.0f,0.0f,0,0,},

//v1isflippedtomeetthetopdownconventioninWindows

//theupperlefttexturecoordinateis(0,0)

//thelowerrighttexturecoordinateis(1,1).

};

Page 389: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Createatexture.ThisfileisintheDirectX8.1mediafromtheSDKdownload.

TCHARstrPath[512];

DXUtil_FindMediaFile(strPath,_T("DX5_Logo.bmp"));

LPDIRECT3DTEXTURE8m_pTexture0;

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

//Createthepixelshader.

DXUtil_FindMediaFile(strPShaderPath,_T("PixelShader2.txt"));

ThisfunctionisahelperfunctionusedbytheSampleFramework.Thesampleframeworkisthefoundationonwhichmanyofthesamplesarebuilt.

D3DXAssembleShaderFromFile(strPShaderPath,0,NULL,&pCode;,NULL);

m_pd3dDevice->CreatePixelShader((DWORD*)pCode->GetBufferPointer(),&m;_hPixelShader);

//Loadthetextureandrendertheoutputpixels.

m_pd3dDevice->SetTexture(0,m_pTexture0); //loadTSS0fromthetexture

m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,0,2);

Contentsofthefile"PixelShader2.txt"

//Appliesatexturemaptoobjectvertices.

ps.1.0//Versioninstructionmustbefirstinthefile.

text0//Declaretextureregistert0,whichwillbeloadedfromTextureStage0.

movr0,t0//Movethecontentsofthetextureregister(t0)totheoutputregister(r0).

Theresultingimageisshowninthefollowingexample.

Page 390: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

BlendaDiffuseVertexColorwithaTexture

Thisexampleblendsormodulatesthecolorsinatexturemapwiththevertexcolors.Thedifferencesbetweenthisexampleandthepreviousexampleareasfollows:

Thevertexdatastructure,theFVFmacro,andthevertexdataincludediffusecolor.Theshaderfileusesthemultiplyinstruction(mul)toblendormodulatethetexturecolorswiththevertexdiffusecolor.

Thetexturecreateandloadcodeisthesame.Itisincludedhereforcompleteness.

structCUSTOMVERTEX

{

FLOATx,y,z;

DWORDcolor1;

FLOATtu1,tv1;

};

#defineD3DFVF_CUSTOMVERTEX(D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1|D3DFVF_TEXCOORDSIZE2(0))

staticCUSTOMVERTEXg_Vertices[]=

{

//xyzdiffuseu1v1

{-1.0f,-1.0f,0.0f,0xffff0000,0,1,},//red

{1.0f,-1.0f,0.0f,0xff00ff00,1,1,},//green

{1.0f,1.0f,0.0f,0xff0000ff,1,0,},//blue

{-1.0f,1.0f,0.0f,0xffffffff,0,0,},//white

//v1isflippedtomeetthetopdownconventioninWindows

//theupperlefttexturecoordinateis(0,0)

//thelowerrighttexturecoordinateis(1,1).

};

//Createatexture.ThisfileisintheDirectX8.1mediafromtheSDKdownload.

TCHARstrPath[512];

DXUtil_FindMediaFile(strPath,_T("DX5_Logo.bmp"));

LPDIRECT3DTEXTURE8m_pTexture0;

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

//Createthepixelshader.

DXUtil_FindMediaFile(strPShaderPath,_T("PixelShader3.txt"));

D3DXAssembleShaderFromFile(strPShaderPath,0,NULL,&pCode;,NULL);

Page 391: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

m_pd3dDevice->CreatePixelShader((DWORD*)pCode->GetBufferPointer(),&m;_hPixelShader);

//Loadthetextureandrendertheoutputpixels.

m_pd3dDevice->SetTexture(0,m_pTexture0); //loadTSS0fromthetexture

m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,0,2);

Contentsofthefile"PixelShader3.txt"

ps.1.0//versioninstruction

text0//declaretextureregistert0whichwillbeloadedfromTextureStage0

mulr0,v0,t0//v0*t0,thenmovetor0

Theinputstotheshaderareshowninthefollowingexample.Thefirstimageshowsthevertexcolors.Thesecondimageshowsthetexturemap.

Theresultingimageisshowninthefollowingexample.Itshowstheoutput,whichisablendofthevertexcolorandthetextureimage.

Page 392: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

BlendTwoTexturesUsingaConstantColor

Thisexampleblendstwotexturemaps,usingthevertexcolor,todeterminehowmuchofeachtexturemapcolortouse.Thedifferencesbetweenthisexampleandthepreviousexampleareasfollows:

Thevertexdatastructure,theFVFmacro,andthevertexdataincludeasecondsetoftexturecoordinatesbecausethereisasecondtexture.SetTextureisalsocalledtwice,usingtwotexturestagestates.Theshaderfiledeclarestwotextureregistersandusesthelinearinterpolate(lrp)instructiontoblendthetwotextures.Thevaluesofthediffusecolorsdeterminetheratiooftexture0totexture1intheoutputcolor.

Hereisthesamplecode.

structCUSTOMVERTEX

{

FLOATx,y,z;

DWORDcolor;

FLOATtu1,tv1;

FLOATtu2,tv2;//asecondsetoftexturecoordinates

};

#defineD3DFVF_CUSTOMVERTEX(D3DFVF_XYZ|D3D_FVF_DIFFUSE|D3DFVF_TEX2|D3DFVF_TEXCOORDSIZE4(0))

staticCUSTOMVERTEXg_Vertices[]=

{

//xyzcoloru1v1u2v2

{-1.0f,-1.0f,0.0f,0xff0000ff,1.0f,1.0f,1.0f,1.0f},

{+1.0f,-1.0f,0.0f,0xffff0000,0.0f,1.0f,0.0f,1.0f},

{+1.0f,+1.0f,0.0f,0xffffff00,0.0f,0.0f,0.0f,0.0f},

{-1.0f,+1.0f,0.0f,0xffffffff,1.0f,0.0f,1.0f,0.0f},

};

//Createatexture.ThisfileisintheDirectX8.1mediafromtheSDKdownload.

TCHARstrPath[512];

LPDIRECT3DTEXTURE8m_pTexture0,m_pTexture1;

DXUtil_FindMediaFile(strPath,_T("DX5_Logo.bmp"));

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture0,D3DFMT_R5G6B5);

DXUtil_FindMediaFile(strPath,_T("snow2.jpg"));

D3DUtil_CreateTexture(m_pd3dDevice,strPath,&m;_pTexture1,D3DFMT_R5G6B5);

//Loadthetexturesstages.

m_pd3dDevice->SetTexture(0,m_pTexture0);

Page 393: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

m_pd3dDevice->SetTexture(1,m_pTexture1);//Useasecondtexturestage.

m_pd3dDevice->SetStreamSource(0,m_pQuadVB,sizeof(CUSTOMVERTEX));

m_pd3dDevice->SetVertexShader(D3DFVF_CUSTOMVERTEX);

m_pd3dDevice->SetPixelShader(m_hPixelShader);

m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,0,2);

Contentsofthefile"PixelShader5.txt"

ps.1.0//pixelshaderversion

text0//textureregistert0isloadedfromtexturestage0

text1//textureregistert1isloadedfromtexturestage1

movr1,t1//movetextureregister1intooutputregisterr1

lrpr0,v0,t0,r1//linearlyinterpolatebetweent0andr1byaproportion

//specifiedinv0

Theresultingoutputisasfollows:

Page 394: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 395: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ConvertingTextureOperations

Pixelshadersextendandgeneralizethemulti-texturecapabilitiesofMicrosoft®DirectX®6.0and7.0inthefollowingways.

Asetofgeneralread/writeregistersisaddedtoenablemoreflexibleexpression.TheserialcascadeusingD3DTA_CURRENTrequiresthespecificationofaseparateresultregisterargumentforeachstage.TheD3DTOP_MODULATE2XandD3DTOP_MODULATE4Xtextureoperationsarebrokenintoseparatemodifiersapplicabletoanyinstructionorthogonally.ThiseliminatestheneedforseparateD3DTOP_MODULATEandD3DTOP_MODULATE2Xoperations.Thebiasandunbiastextureoperationmodifiersareorthogonal.Thiseliminatestheneedforseparateaddandaddbiasoperations.Anoptionalthirdargumentisaddedtomodulateadd,sotheproceduralpixelshadercandoarg1×arg2+arg0.ThiseliminatestheD3DTOP_MODULATEALPHA_ADDCOLORandD3DTOP_MODULATECOLOR_ADDALPHAtextureoperations.Anoptionalthirdargumentisaddedtotheblendoperation,sotheproceduralpixelshadercanusearg0astheblendproportionbetweenarg1andarg2.ThiseliminatestheD3DTOP_BLENDDIFFUSEALPHA,D3DTOP_BLENDTEXTUREALPHA,D3DTOP_BLENDFACTORALPHA,D3DTOP_BLENDTEXTUREALPHAPM,andD3DTOP_BLENDCURRENTALPHAtextureoperations.Textureaddressmodifyingoperations,suchasD3DTOP_BUMPENVMAP,arebrokenoutfromthecolorandalphaoperationsanddefinedasathirdoperationtype,specificallyforoperatingontextureaddresses.

Tosupportthisincreasedflexibilityefficiently,theapplicationprogramminginterface(API)syntaxischangedfromDWORDpairstoanASCIIassemblecodesyntax.Thisexposesthefunctionalityofferedbyproceduralpixelshaders.

NoteWhenyouusepixelshaders,specularaddisnotspecificallycontrolledbyarenderstate,anditisuptothepixelshadertoimplementifneeded.However,fogblendingisstillappliedbythefixedfunctionpipeline.

Page 396: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 397: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Debugging

MFCPixelShaderSampleApplication

YoucanusetheMFCPixelShaderSampleapplicationtolearnpixelshaderinstructionsinteractively.Programmedintothisapplicationarediffusevertexcolorsandtwotextureimages.TheapplicationhasfiveworkingpixelshadersthatyoucanselectbypushingthebuttonsintheShadersbox.Itincludesaviewwindowonthelefttoshowtherenderedresult,aninstructionwindowontherighttoallowuserstoenterinstructionsforvalidation,andathirdwindowtoviewdebugoutput.

Asanexample,runtheapplicationandtypethefollowinginstructionsintheinstructionwindow.

ps.1.0

text0

movr0,t0

ThisresultsintheMicrosoft®DirectX®5logoimageintherenderedviewwindow.

Thisshaderappliesatexturemap.NoticethatthecompilationresulttextwindowsaysSuccess,whichindicatesthatalltheinstructionsarevalid.

Next,removethesecondinstruction,whichisthetexturedeclaration.Oncethisisdeleted,thecompilationresultsays:

(Statement2)(ValidationError)Readofuninitializedcomponents(*)int0:*R/X/0*G/Y/1*B/Z/2*A/W/3

Thiserroridentifiesthestatementthatfails,Statement2,andwhyitfailsUninitializedcomponentint0.YoucanfixthisproblembyaddingStatement2again.Whenyoudothis,theshaderworksagain.

Thisisasimpleexamplebutitillustratestheusefulnessofthetool.Bytryingdifferentinstructions,registers,andinstructionsequences,youcanbetter

Page 398: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

understandpixelshadersandvertexshaders.ThesampleapplicationalsohasanOpenbutton,whichsupportsloadingofashaderfilesothatyoucanloadanyshaderfilesyouhavealreadycreated.

ShaderDebuggers

SomegraphicschipcompaniesprovideashaderdebuggingtoolontheirWebsites.FindthesetoolsbysearchingtheWeborbyreadingthearticlelistedbelow.Youcanattachadebuggertoaprogramwhileitisrunningandusethedebuggertostepthroughashader.Bysettingbreakpoints,youcanstepthroughtheshadercodeonelineatatimeandwatchregisterstatechanges.Formoreinformationaboutvertexshadersanddebuggingtips,seeUsingVertexShaders:Part1.

TextureBlendingDebugging

Anothersampleapplicationthatispartofthesoftwaredevelopmentkit(SDK)installationisMFCTex.ThisMicrosoftFoundationClasses(MFC)applicationisagoodwaytolearnhowtoperformmulti-textureblendingoperationsinthefixedfunctionpipeline.

DiagnosticSupport

AnotheroptionforhelpwithdebuggingDirectXproblemsistousetheDirectXDiagnosticViewer(DXDiag.exe)tocreateadumpofyourmachine.ThisisdonebyrunningDxDiag.exeafteryourmachinehascrashedandsendingthedumptoMicrosoft,usingeithertheReportbuttonontheMoreHelptaborbysendingittodirectx@microsoft.com.Thedumpcanbeusedtotrackdownandreproducetheproblem.

Additionaldebuginformationcanbefoundathttp://msdn.microsoft.com/directx

Page 399: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 400: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

CreateanEffectThisexampleusesaneffectfiletoapplyatexturemaptoanobject.Theexampleshowsthecontentsoftheeffectfile,aswellasthecoderequiredintheapplicationtoloadandrunthefile.

Tocreateaneffect:

Step1:CreatetheEffectFileStep2:LoadtheEffectFileStep3:RendertheEffect

Step1:Createtheeffectfile

/*

*Step1:Createtheeffectfile

*Thiseffectfilemapsa3-Dtexturemapontotheobject.

*ThiscodeneedstobeinafilenamedEffects.fx

*/

TextureDiffuseTexture;

TechniqueT0

{

PassP0

{

Texture[0]=NULL;

PixelShader=NULL;

VertexShader=XYZ|Normal|Diffuse|Tex1;

Lighting=False;

CullMode=None;

Texture[0]=<DiffuseTexture>;

ColorOp[0]=SelectArg1;

ColorArg1[0]=Texture;

ColorOp[1]=Disable;

}

}

Step2:LoadtheEffectFile

Page 401: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

{

HRESULThr;

D3DXTECHNIQUE_DESCtechnique;

ID3DXEffectm_pEffect;

//Assumesthatm_pd3dDevicehasbeeninitialized

if(FAILED(hr=D3DXCreateEffectFromFile(m_pd3dDevice,"effect.fx",&m;_pEffect,NULL)))

returnhr;

if(FAILED(hr=FindNextValidTechnique(NULL,&technique;)))

returnhr;

m_pEffect->SetTechnique(technique.Index);

m_pEffect->SetTexture("DiffuseTexture",m_pTexture0);

}

Oncetheeffectfileiscreated,ID3DXEffect::FindNextValidTechniquereturnsatechniquethathasbeenvalidatedonthehardware.

Step3:RendertheEffect

{

HRESULThr;

UINTuPasses;

if(FAILED(hr=m_pd3dDevice->SetStreamSource(0,m_pVB,

sizeof(CUSTOMVERTEX_POS_NORM_COLOR1_TEX1))))

returnhr;

m_pEffect->Begin(&uPasses;,0);

//The0specifiesthatID3DXEffect::BeginandID3DXEffect::Endwill

//saveandrestoreallstatemodifiedbytheeffect.

for(UINTuPass=0;uPass<uPasses;uPass++)

{

//Setthestateforaparticularpassinatechnique

m_pEffect->Pass(uPass);

m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,dwNumSphereVerts-2);

}

m_pEffect->End();

}

Page 402: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 403: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MultipleTechniquesAneffectfiledefinesthetechniquesused.Thebasiclayoutofaneffectfilestartswithoneormoredeclarationsandthendefineseachtechniqueforthateffect.Thissampleshowsabasiceffectfilethatcontainstwotexturesandtwotechniques.Thiseffectfileallowsadevicethatdoesn'tsupportsingle-passrenderingfortwotexturestousemultiplepassestorenderthetextures.

//Declaretwotextures.

texturetex0;//Firsttexture

texturetex1;//Secondtexture

//Technique't0'willrenderthesceneinonepass.Thecolor

//foreachpixeliscalculatedtobetex0+tex1.Becauseituses

//twotexturesatonce,itwillworkonlyoncardsthatsupport

//multitexture.

techniquet0

{

passp0

{

Texture[0]=<tex0>;

ColorOp[0]=SelectArg1;

ColorArg1[0]=Texture;

Texture[1]=<tex1>;

ColorOp[1]=Add;

ColorArg1[1]=Texture;

ColorArg2[1]=Current;

ColorOp[2]=Disable;

}

}

//Technique't1'rendersthesceneintwopasses.Thefirstpasssets

//eachpixeltothecoloroftex0.Thesecondpassaddsinthecolor

//oftex1.Theresultshouldlookidenticaltothefirst

//technique.However,thistechniquecanbeusedoncardsthatdonot

//supportmultitexture.

techniquet1

{

passp0

{

Page 404: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

AlphaBlendEnable=False;

Texture[0]=<tex0>;

ColorOp[0]=SelectArg1;

ColorArg1[0]=Texture;

ColorOp[1]=Disable;

}

passp1

{

AlphaBlendEnable=True;

SrcBlend=One;

DestBlend=One;

Texture[0]=<tex1>;

ColorOp[0]=SelectArg1;

ColorArg[0]=Texture;

ColorOp[1]=Disable;

}

}

Thisexampleshowsthebasicsyntaxandlayoutofatypicaleffectfile.

//

//SampleEffect

//Thiseffectaddstwotextures,usingsinglepassormultipasstechnique.

//

texturetex0;

texturetex1;

//Singlepass

techniquet0

{

passp0

{

Texture[0]=<tex0>;

Texture[1]=<tex1>;

ColorOp[0]=SelectArg1;

ColorArg1[0]=Texture;

ColorOp[1]=Add;

Page 405: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ColorArg1[1]=Texture;

ColorArg2[1]=Current;

ColorOp[2]=Disable;

}

}

//Multipass

techniquet1

{

passp0

{

Texture[0]=<tex0>;

ColorOp[0]=SelectArg1;

ColorArg1[0]=Texture;

ColorOp[1]=Disable;

}

passp1

{

AlphaBlendEnable=True;

SrcBlend=One;

DestBlend=One;

Texture[0]=<tex1>;

ColorOp[0]=SelectArg1;

ColorArg1[0]=Texture;

ColorOp[1]=Disable;

}

}

Page 406: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 407: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise1:DiffuseLighting//

//EffectFileWorkshopSolutionforExercise1

//Copyright(c)2001MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR; //Directionoflight

vectormatD; //Objectdiffusematerialcolor

matrixmWld; //World

matrixmTot; //Total

//Loadmodel

stringXFile="sphere.x";

//Backgroundcolor

DWORDBCLR=0xff333333;

//Nopixelshader

pixelshaderpNIL;

//Techniquenamesfordisplayinviewerwindow

stringtec0="Exercise1a:FixedFunctionDiffuseLighting";

stringtec1="Exercise1b:VertexShaderDiffuseLighting";

/////////////////////////////////////////////////////////////////////////////

///////Exercise1a:FixedFunctionDiffuseLighting//////////

///////Changediffusematerialcolortocolorfrommodel,//////////

///////ratherthanthecurrentwhitematerialconstant.//////////

/////////////////////////////////////////////////////////////////////////////

//Given:Theapphasalreadysetthematricesbeforecallingthistechnique.

techniquetec0

{

passP0

{

//Diffuse,specular,andambientmaterialcolorsofobject

MaterialDiffuse=;//Diffusefromobjectmaterialdiffuse

MaterialDiffuse=(0.0f,0.0f,1.0f,1.0f);//Diffusefromconstantcolor

MaterialSpecular=(0.0f,0.0f,0.0f,0.0f);

MaterialAmbient=(0.0f,0.0f,0.0f,0.0f);

//LightProperties.lhtR,thelightdirection,isinputfromtheshaderapp

Page 408: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

LightType[0]=DIRECTIONAL;

LightDiffuse[0]=(1.0f,1.0f,1.0f,1.0f);

LightSpecular[0]=(0.0f,0.0f,0.0f,0.0f);

LightAmbient[0]=(0.0f,0.0f,0.0f,0.0f);

LightDirection[0]=;

LightRange[0]=100000.0f;

//Turnlightingonanduselightzero

LightEnable[0]=TRUE;

Lighting=TRUE;

//Assigndiffusecolortobeused

ColorOp[0]=SelectArg1;

ColorArg1[0]=Diffuse;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

//Onlyonecolorbeingused

ColorOp[1]=Disable;

AlphaOp[1]=Disable;

//Z-bufferingtobeused

ZEnable=true;

ZWriteEnable=true;

}

}

/////////////////////////////////////////////////////////////////////////////

///////Exercise1b:VertexShaderDiffuseLighting//////////

///////Changediffusematerialcolortocolorfrommodel,//////////

///////ratherthanthecurrentwhitematerialconstant.//////////

/////////////////////////////////////////////////////////////////////////////

techniquetec1

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=;//WorldMatrix

VertexShaderConstant[4]=;//World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=(1.0f,1.0f,1.0f,1.0f);//Diffusefromconstantcolor

VertexShaderConstant[9]=;//Diffusefromobjectmaterialdiffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specularfromconstantcolor

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambientfromconstantcolor

//LightProperties.lhtR,thelightdirection,isinputfromtheshaderapp

VertexShaderConstant[13]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

Page 409: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=;//Lightdirection

//Assigndiffusecolortobeused

ColorOp[0]=SelectArg1;

ColorArg1[0]=Diffuse;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

//Onlyonecolorbeingused

ColorOp[1]=Disable;

AlphaOp[1]=Disable;

//Definitionofthevertexshader,declarationsthenassembly

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//TextureCoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace.

m3x3r0,v3,c0//TransformnormaltoworldSpace,putresultintor0.

dp3r0,r0,-c16//Dotproductagainstlight,r0nowhaslighting

//constantinx,y,andzcomponents(r,g,b).

mulr0,r0,c13//Modulateagainstdiffuselightcolor.

movoD0,r0//Putintodiffusecoloroutput.

};

}

}

Page 410: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 411: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise2:VertexShaderDiffuseLighting//

//EffectFileWorkshopSolutionforExercise2

//Copyright(c)2001MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR; //Lightdirectionfromapp

vectormatD; //Objectdiffusematerialcolor

matrixmWld; //World

matrixmTot; //Total

//Loadmodel

stringXFile="f40.x";

//Backgroundcolor

DWORDBCLR=0xff000000;

//Nopixelshader

pixelshaderpNIL;

//Techniquenamesfordisplayinviewerwindow

stringtec0="Solution2:VertexShaderDiffuseLighting";

/////////////////////////////////////////////////////////////////////////////

///////Exercise2:VertexShaderDiffuseLighting//////////

///////Lightthemodeltakingbothdiffusematerialand//////////

///////diffuselightsourceintoconsideration.//////////

/////////////////////////////////////////////////////////////////////////////

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=; //WorldMatrix

VertexShaderConstant[4]=; //World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=;//Diffusefromobjectmaterialdiffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specularfromconstantcolor

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambientfromconstantcolor

Page 412: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//LightProperties.lhtRisinputfromtheshaderapp

VertexShaderConstant[13]=(1.0f,0.9f,0.9f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=; //Lightdirection

//Assigndiffusecolortobeused

ColorOp[0]=SelectArg1;

ColorArg1[0]=Diffuse;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

//Onlyonecolorbeingused

ColorOp[1]=Disable;

AlphaOp[1]=Disable;

//Definitionofthevertexshader,declarationsthenassembly

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//TextureCoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace

dp3r0,v3,-c16//Dotproductagainstuntransformedlight

mulr0,r0,c13//Modulateagainstdiffuselightcolor

mulr0,r0,c9//Modulateagainstdiffusematerial

movoD0,r0//PutintoDiffuseColoroutput

};

}

}

Page 413: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 414: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise3:Transforms//

//EffectFileWorkshopSolutionforExercise3

//Copyright(c)2001MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR; //Lightdirectionfromapp

vectormatD; //Objectdiffusematerialcolor

matrixmWld; //World

matrixmTot; //Total

//Loadmodel

stringXFile="f40.x";

//BackgroundColor

DWORDBCLR=0xff000000;

//Nopixelshader

pixelshaderpNIL;

//Techniquenamesfordisplayinviewerwindow

stringtec0="Solution3:Transforms";

/////////////////////////////////////////////////////////////////////////////

///////Exercise3:Transforms//////////

///////Transformthevertexnormalintoworldspacetotake//////////

///////lightsourcemovementintoconsideration.//////////

/////////////////////////////////////////////////////////////////////////////

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=;//WorldMatrix

VertexShaderConstant[4]=;//World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=;//Diffusefromobjectmaterialdiffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specularfromconstantcolor

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambientfromconstantcolor

//LightProperties.lhtRisinputfromtheshaderapp

VertexShaderConstant[13]=(1.0f,0.9f,0.9f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

Page 415: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=; //Lightdirection

//Assigndiffusecolortobeused

ColorOp[0]=SelectArg1;

ColorArg1[0]=Diffuse;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

//Onlyonecolorbeingused

ColorOp[1]=Disable;

AlphaOp[1]=Disable;

//Definitionofthevertexshader,declarationsthenassembly

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//Texturecoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace.

movr0,v3//Copyuntransformednormalintor0.

m3x3r0,v3,c0//Transformnormaltoworldspace,putresult

//intor0soprecedingmovnotnecessary.

dp3r0,r0,-c16//Dotproductagainstlight,r0nowhaslightingconstant

//inx,yandzcomponents(r,g,b).

mulr0,r0,c13//Modulateagainstdiffuselightcolor.

mulr0,r0,c9//Modulateagainstdiffusematerial.

movoD0,r0//Putintodiffusecoloroutput.

};

}

}

Page 416: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 417: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise4:Texturing//

//EffectFileWorkshopSolutionforExercise4

//Copyright(c)2001MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR;//Lightdirectionfromapp

vectormatD;//Objectdiffusematerialcolor

matrixmWld;//World

matrixmTot;//Total

texturetDif;//Diffusetextureofobject

//Loadmodel

stringXFile="bust.x";

//Backgroundcolor

DWORDBCLR=0xff000000;

//Nopixelshader

pixelshaderpNIL;

//Techniquenamesfordisplayinviewerwindow

stringtec0="Exercise4:Texturing";

/////////////////////////////////////////////////////////////////////////////

///////Exercise4:Texturing//////////

///////SetuptexturetopassontoFFPS//////////

///////Modulatebetweenthetextureanddiffusecolorargs.//////////

/////////////////////////////////////////////////////////////////////////////

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=;//WorldMatrix

VertexShaderConstant[4]=;//World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=;//Diffusefromobjectmaterialdiffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specularfromconstantcolor

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambientfromconstantcolor

//LightProperties.lhtRisinputfromtheshaderapp

Page 418: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

VertexShaderConstant[13]=(0.8f,0.8f,0.8f,0.8f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.3f,0.3f,0.3f,1.0f);//Ambient

VertexShaderConstant[16]=; //LightDirection

//Usefulconstant(s)

VertexShaderConstant[20]=(-1.0f,-1.0f,0.5f,1.0f);

//Assigndiffusetexture

Texture[0]=;

//Setuptexturewrappingmode

wrap0=U|V;

AddressU[0]=Wrap;

AddressV[0]=Wrap;

//Assigntexturecolortobeused

ColorArg1[0]=Texture;

ColorOp[0]=Modulate;//Modulatebetweenargs

ColorArg2[0]=Diffuse;//Adddiffusecomponentasarg

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

//Ensureremainingstagesaredisabled

ColorOp[1]=Disable;

AlphaOp[1]=Disable;

//Definitionofthevertexshader,declarationsthenassembly

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//TextureCoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace

m3x3r0,v3,c0//TransformNormaltoWorldSpace,putresultintor0

dp3r0,r0,-c16//Dotproductagainstlight,r0nowhaslighting

//constantinx,yandzcomponents(r,g,b)

mulr0,r0,c13//Modulateagainstdiffuselightcolor

mulr0,r0,c9//Modulateagainstdiffusematerial

Page 419: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

movoD0,r0//Outputdiffusecolor

//movoT0,v7//outputtexturecoordinates

//OR

movoT0.xy,v7.xy//outputonlythexandychannelsforbetterefficiency

};

}

}

Page 420: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 421: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise5:VertexShaderSpecularLighting//

//EffectFileWorkshopExercise5

//Copyright(c)2000MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR;//Lightdirection

matrixmWld;//World

matrixmTot;//Total

vectormatD;//Materialdiffuse

vectormatS;//Materialspecular

vectorvCPS;//Cameraposition

//Backgroundcolor

DWORDBCLR=0xFF000000;

pixelshaderpNIL;

stringXFile="f40.x";

//Techniquenamesfordisplayinviewerwindow

stringtec0="Exercise5:VertexShaderSpecularLighting";

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=;//WorldMatrix

VertexShaderConstant[4]=;//World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=;//Diffuse

VertexShaderConstant[10]=;//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,0.0f,0.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

Page 422: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=;//Lightdirection

//BlendingConstants

VertexShaderConstant[20]=(0.7f,0.7f,0.7f,0.7f);

VertexShaderConstant[21]=(0.3f,0.3f,0.3f,0.3f);

//CameraInformation.

VertexShaderConstant[24]=;

ColorOp[0]=SelectArg1;

ColorArg1[0]=Diffuse;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

ColorOp[1]=Disable;

AlphaOp[1]=Disable;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//Texturecoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace

m4x4r0,v0,c0//Transformpointtoworldspace

addr0,-r0,c24//Getavectortowardthecameraposition

//Thisisthenegativeofthecameradirection

//Normalize

dp3r11.x,r0.xyz,r0.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr0.xyz,r0.xyz,r11.xyz//Multiply,r0=-(cameravector)

addr2.xyz,r0.xyz,-c16//Gethalfangle

//Normalize

dp3r11.x,r2.xyz,r2.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr2.xyz,r2.xyz,r11.xyz//Multiply,r2=HalfAngle

m3x3r1,v3,c0//Transformnormaltoworldspace,putinr1

//r2=halfangle,r1=normal,r3(output)=intensity

Page 423: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

dp3r3.xyzw,r1,r2

//Nowraiseitseveraltimes

mulr3,r3,r3//2nd

mulr3,r3,r3//4th

mulr3,r3,r3//8th

mulr3,r3,r3//16th

//Computediffuseterm

dp3r4,r1,-c16

//Blenditin

mulr3,c20,r3//Kd

mulr4,r4,c21//Ks

mulr4,r4,c10//Specular

madr4,r3,c9,r4//Diffuse

movoD0,r4//PutintoDiffuseColor

};

}

}

Page 424: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise5B//

//EffectFileWorkshopExercise5B

//Copyright(c)2000MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR; //LightDirection

matrixmWld; //World

matrixmTot; //Total

vectorvCPS;//Cameraposition

texturetEnv;//Environmenttexture

texturetDif;

vectormatD;//ObjectDiffuseMaterialColor

vectormatS;//ObjectSpecularMaterialColor

//Backgroundcolor

DWORDBCLR=0xFF000000;

pixelshaderpNIL;

//stringXFile="f40.x";

stringXFile="viper.x";

stringBIMG="lobbyzneg.bmp";

//Techniquenamesfordisplayinviewerwindow

stringtec0="Exercise5b:VertexShaderSpecularEnvmap";

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=; //WorldMatrix

VertexShaderConstant[4]=; //World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=;//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

Page 425: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,0.0f,0.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=; //LightDirection

//Blendingconstants

VertexShaderConstant[20]=(-2.0f,-2.0f,-2.0f,-2.0f);

VertexShaderConstant[21]=(0.25f,0.25f,0.25f,0.05f);

VertexShaderConstant[22]=(0.75f,0.75f,0.75f,0.95f);

VertexShaderConstant[23]=(1.00f,1.00f,1.00f,1.00f);

//Camerainformation

VertexShaderConstant[24]=;

ColorOp[0]=Modulate;

ColorArg2[0]=Diffuse;

ColorArg1[0]=Texture;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

ColorOp[1]=Disable;

AlphaOp[1]=Disable;

Texture[0]=;

PixelShader=;

AlphaBlendEnable=True;

SrcBlend=One;

DestBlend=InvSrcAlpha;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//Texturecoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace

m4x4r0,v0,c0//Transformpointtoworldspace

addr0,r0,-c24//Getavectortowardthecameraposition

//Thisisthecameradirection

Page 426: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Normalize

dp3r11.x,r0.xyz,r0.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr0.xyz,r0.xyz,r11.xyz//Multiply,r0=(cameravector)

m3x3r1,v3,c0//Transformnormaltoworldspace,putinr1

dp3r3,r0,r1//DotproductCam*Normal

mulr2,c20,r3

madoT0.xyz,r2,r1,r0//Computereflectionvector

//(1-cos)^4=approxfresnel

addr0,c23,r3 //Complementcolor

mulr1,r0,r0//Square

mulr0,r1,r1//4th

mulr0,r0,c22

//movr1,c9

//mulr1,r1,c21//Blendinscaleddiffusematerialcolor

addoD0,r0,r1 //PutintoDiffuseColor

};

}

}

techniquetec1

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=; //WorldMatrix

VertexShaderConstant[4]=; //World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=;//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,0.0f,0.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=; //Lightdirection

//BlendingConstants

VertexShaderConstant[20]=(-2.0f,-2.0f,-2.0f,-2.0f);

VertexShaderConstant[21]=(0.25f,0.25f,0.25f,0.05f);

VertexShaderConstant[22]=(0.75f,0.75f,0.75f,0.95f);

VertexShaderConstant[23]=(1.00f,1.00f,1.00f,1.00f);

Page 427: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

VertexShaderConstant[24]=(1.0f,1.0f,1.0f,1.0f);

//CameraInformation

VertexShaderConstant[25]=;

ColorOp[0]=Modulate;

ColorArg1[0]=Texture;

ColorArg2[0]=Diffuse;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

ColorOp[1]=Add;

ColorArg1[1]=Current;

ColorArg2[1]=Specular;

ColorOp[2]=Disable;

AlphaOp[2]=Disable;

Texture[0]=;

PixelShader=;

//AlphaBlendEnable=True;

//SrcBlend=One;//SrcAlpha;

//DestBlend=InvSrcAlpha;

//CullMode=None;

SpecularEnable=True;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//Texturecoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace

m4x4r0,v0,c0//TransformpointtoWorldSpace

addr0,r0,-c25//Getavectortowardthecameraposition,

//thisisthecameradirection

//Normalize

dp3r11.x,r0.xyz,r0.xyz//Loadthesquareintor1

Page 428: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr0.xyz,r0.xyz,r11.xyz//Multiply,r0=(cameravector)

m3x3r1,v3,c0//Transformnormaltoworldspace,putinr1

dp3r3,r0,r1//DotproductCam*Normal

mulr2,c20,r3

madoT0.xyz,r2,r1,r0//Computereflectionvector

//(1-cos)^4=approxfresnel

addr0,c23,r3//Complementcolor

mulr1,r0,r0//Square

addoD0,r1,c21

movr1,c9

muloD1,r1,c21//Blendinscaleddiffusematerialcolor

};

}

}

techniquetec2

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=; //WorldMatrix

VertexShaderConstant[4]=; //World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=;//Diffuse

VertexShaderConstant[10]=;//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,0.0f,0.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=; //Lightdirection

//Blendingconstants

VertexShaderConstant[20]=(-2.0f,-2.0f,-2.0f,-2.0f);

VertexShaderConstant[21]=(0.25f,0.25f,0.25f,0.05f);

VertexShaderConstant[22]=(0.75f,0.75f,0.75f,0.95f);

VertexShaderConstant[23]=(1.00f,1.00f,1.00f,1.00f);

VertexShaderConstant[24]=(1.0f,1.0f,1.0f,1.0f);

//Camerainformation

VertexShaderConstant[25]=;

Page 429: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ColorOp[0]=Modulate;

ColorArg1[0]=Texture;

ColorArg2[0]=Diffuse;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

ColorOp[1]=Add;

ColorArg1[1]=Current;

ColorArg2[1]=Specular;

ColorOp[2]=Disable;

AlphaOp[2]=Disable;

Texture[0]=;

PixelShader=;

//FillMode=Wireframe;

SpecularEnable=True;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//Texturecoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace

m4x4r0,v0,c0//TransformpointtoworldSpace

addr0,r0,-c25//Getavectortowardthecameraposition,

//thisisthecameradirection

//Normalize

dp3r11.x,r0.xyz,r0.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr0.xyz,r0.xyz,r11.xyz//Multiply,r0=(cameravector)

m3x3r1,v3,c0//Transformnormaltoworldspace,putinr1

dp3r3,r0,r1//DotproductCam*Normal

mulr2,c20,r3

madoT0.xyz,r2,r1,r0//Computereflectionvector

Page 430: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//(1-cos)^4=approxfresnel

addr0,c23,r3 //Complementcolor

mulr1,r0,r0 //Square

//addr1,r1,c21

//muloD0,r1,c10

madoD0,r1,c10,c10

movr1,c9

muloD1,r1,c21//blendinscaleddiffusematcolor

};

}

}

techniquetec4

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=; //WorldMatrix

VertexShaderConstant[4]=; //World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=;//Diffuse

VertexShaderConstant[10]=;//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,0.0f,0.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=; //Lightdirection

//BlendingConstants

VertexShaderConstant[20]=(-2.0f,-2.0f,-2.0f,-2.0f);

VertexShaderConstant[21]=(1.0f,1.0f,1.0f,1.0f);

VertexShaderConstant[22]=(0.75f,0.75f,0.75f,0.95f);

VertexShaderConstant[23]=(1.00f,1.00f,1.00f,1.00f);

//CameraInformation

VertexShaderConstant[24]=;

//FillMode=Wireframe;

ColorOp[0]=Modulate;

ColorArg2[0]=Diffuse;

Page 431: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ColorArg1[0]=Texture;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

ColorOp[1]=Disable;

AlphaOp[1]=Disable;

Texture[0]=;

PixelShader=;

AlphaBlendEnable=True;

SrcBlend=One;

DestBlend=InvSrcAlpha;

//CullMode=None;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//Texturecoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace

m4x4r0,v0,c0//TransformpointtoWorldSpace

addr0,r0,-c24//Getavectortowardthecameraposition,

//thisisthecameradirection

//Normalize

dp3r11.x,r0.xyz,r0.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr0.xyz,r0.xyz,r11.xyz//Multiply,r0=(cameravector)

m3x3r1,v3,c0//Transformnormaltoworldspace,putinr1

dp3r3,r0,r1//DotproductCam*Normal

mulr2,c20,r3

madoT0.xyz,r2,r1,r0//Computereflectionvector

//(1-cos)^4=approxfresnel

addr0,c23,r3 //Complementcolor

mulr1,r0,r0 //Square

Page 432: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

mulr0,r1,r1 //4th

mulr0,r0,c22

movr1,c9

//addr0,r0,c10//Addinspecular

addoD0,r0,r1//PutintoDiffuseColor

};

}

}

Page 433: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise5C

//

//EffectFileWorkshopExercise5C

//Copyright(c)2000MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR; //Lightdirection

matrixmWld; //World

matrixmTot; //Total

vectorvCPS; //Cameraposition

texturetEnv;//Environmenttexture

texturetDif;

vectormatD; //Objectdiffusematerialcolor

//Backgroundcolor

DWORDBCLR=0xFF000000;

pixelshaderpNIL;

//stringXFile="sphere.x";

//stringXFile="f40.x";

stringXFile="viper.x";

stringBIMG="lobbyzneg.bmp";

//Techniquenamesfordisplayinviewerwindow

stringtec0="Exercise5b:VertexShaderSpecularEnvmap";

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=; //WorldMatrix

VertexShaderConstant[4]=; //World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=;//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

Page 434: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,0.0f,0.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=; //Lightdirection

//BlendingConstants

VertexShaderConstant[20]=(-2.0f,-2.0f,-2.0f,-2.0f);

VertexShaderConstant[25]=(1.0f,1.0f,1.0f,1.0f);

VertexShaderConstant[21]=(0.25f,0.25f,0.25f,0.05f);

VertexShaderConstant[22]=(0.75f,0.75f,0.75f,0.95f);

VertexShaderConstant[23]=(1.00f,1.00f,1.00f,1.00f);

//Camerainformation

VertexShaderConstant[24]=;

ColorOp[0]=Modulate;

ColorArg1[0]=Texture;

ColorArg2[0]=Diffuse;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

ColorOp[1]=Add;

ColorArg1[1]=Current;

ColorArg2[1]=Specular;

AlphaOp[1]=Disable;

Texture[0]=;

PixelShader=;

//AlphaBlendEnable=True;

//SrcBlend=One;//SrcAlpha;

//DestBlend=InvSrcAlpha;

//CullMode=None;

SpecularEnable=True;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//Texturecoord1

floatv8[3];//Texturecoord2

Page 435: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace

m4x4r0,v0,c0//TransformpointtoWorldSpace

addr0,r0,-c24//Getavectortowardthecameraposition,

//thisisthecameradirection

//Normalize

dp3r11.x,r0.xyz,r0.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr0.xyz,r0.xyz,r11.xyz//Multiply,r0=(cameravector)

m3x3r1,v3,c0//Transformnormaltoworldspace,putinr1

dp3r3,r0,r1//DotproductCam*Normal

mulr2,c20,r3

madoT0.xyz,r2,r1,r0//Computereflectionvector

//(1-cos)^4=approxfresnel

addr0,c23,r3 //Complementcolor

mulr1,r0,r0 //Square

//mulr0,r1,r1 //4th

//mulr0,r1,r1

addoD0,r1,c21

mulr0,r0,c22

movr1,c9

muloD1,r1,c25//Blendinscaleddiffusematcolor

//addoD0,r0,r1//PutintoDiffuseColor

//addoD0,r0,r1//PutintoDiffuseColor

};

}

}

Page 436: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 437: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise6:StandardTextureEffect//

//StandardTextureEffect

//Copyright(c)2000MicrosoftCorporation.Allrightsreserved.

//

vectormatD;//Materialdiffuse

vectormatS;//Materialspecular

vectormatA;//Materialambient

DWORDlhtT;//Lighttype

vectorlhtD;//Lightdiffuse

vectorlhtS;//Lightspecular

vectorlhtA;//Lightambient

vectorlhtR;//Lightdirection

vectorlhtP;//Lightposition

vectorvOff;//Embossoffset

vectorvVwD;//Viewdirection

vectorvCPS;//Cameraposition

matrixmEnv;//Environmentmaptransform

matrixmWld;//World

matrixmTot;//Total

matrixmWl0;//Blendingmatrices

matrixmWl1;

matrixmWl2;

matrixmWl3;

matrixmWl4;

matrixmWl5;

matrixmWl6;

matrixmWl7;

matrixmIdt=

[

1.0,0.0,0.0,0.0,

0.0,1.0,0.0,0.0,

0.0,0.0,1.0,0.0,

0.0,0.0,0.0,1.0

];

DWORDBCLR=0x0000000;

Page 438: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

texturetDif;//Diffusetexture

texturetEnv;//Environmenttexture

texturetEvC;//Circularyintegratexcubetexture

texturetEvL;

texturetDf2;//Secondtexture

texturetDf3;

texturetDf4;

texturetSt1;//Proceduralsatintexture

texturetSt2;//Proceduralstaintexture2

texturetMt1;//Brushedmetaltexture

texturetFrn;//FresnelShader

texturetGlw;//GlowShader

texturetL10;//Lightlookuptextureforspec

texturetL80;

texturetL64;

texturetL32;

texturetL16;

texturetfg1;

texturetfg2;

texturetNSE;

texturetNSN;

pixelshaderpNIL;

stringXFile="tiny.x";

stringSkinned="true";

//Skinnedversion,lotsoftransformshavetohappenhere

vertexshadersDif=

decl

{

stream0;

floatv0[3];//Blendweights

floatv1[3];//Indices

ubytev2[4];

//OR

//d3dcolorv2[1];//ifhardwaredoesn'tsupportubyte,used3dcolorinstead

floatv3[3];

floatv7[3];

floatv8[3];

}

asm

{

vs.1.1

//Theindicesareputintoancolor

//Ifubyteissupported,thistherightwaytodoit

Page 439: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

mulr1,v2.xyzw,c41.zzzz

//OR

//Ifubyteisnotsupported,decodefroma32bitd3dcolorvalue

//mulr1,v2.zyxw,c41.wwww

//Firstcomputethelastblendingweight

movr0.xyz,v1.xyz;

dp3r0.w,v1.xyz,c40.xxx;

addr0.w,-r0.w,c40.x

//Nowdoabunchofmatrixmultiples,

//r5=Position

//r6=Normal

mova0.x,r1.x

movr5,v0

m4x3r5,v0,c[a0.x];//Worldmatricesstartat0

m3x3r6,v3,c[a0.x];

//Blendthem

mulr5,r5,r0.xxxx

mulr6,r6,r0.xxxx

//Set2

mova0.x,r1.y

m4x3r2,v0,c[a0.x];

m3x3r3,v3,c[a0.x];

//Addthemin

madr5,r2,r0.yyyy,r5;

madr6,r3,r0.yyyy,r6;

//Set3

mova0.x,r1.z

m4x3r2,v0,c[a0.x];

m3x3r3,v3,c[a0.x];

//Addthemin

madr5,r2,r0.zzzz,r5;

madr6,r3,r0.zzzz,r6;

//Set4

mova0.x,r1.w

m4x3r2,v0,c[a0.x];

m3x3r3,v3,c[a0.x];

//Addthemin

madr5,r2,r0.wwww,r5;

Page 440: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

madr6,r3,r0.wwww,r6;

//Computeposition

movr5.w,c40.x

m4x4oPos,r5,c50;

dp3r11.x,r6.xyz,r6.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr6.xyz,r6.xyz,r11.xyz//Multiply

dp3r4.xyz,r6,-c48

movoD0.xyz,r4.xyz

movoT0.xy,v7.xy

};

//SkinnedDiffuse1

stringtec0="Exercise6:SkinnedDiffuse";

techniquetec0

{

passP0

{

ColorOp[0]=Modulate;

ColorArg1[0]=Texture;

ColorArg2[0]=Diffuse;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Current;

ColorOp[1]=Disable;

AlphaOp[1]=Disable;

MinFilter[0]=Linear;

MagFilter[0]=Linear;

MipFilter[0]=Linear;

VertexShaderConstant[0]=<mWl0>;

VertexShaderConstant[4]=<mWl1>;

VertexShaderConstant[8]=<mWl2>;

VertexShaderConstant[12]=<mWl3>;

VertexShaderConstant[16]=<mWl4>;

VertexShaderConstant[20]=<mWl5>;

VertexShaderConstant[24]=<mWl6>;

VertexShaderConstant[28]=<mWl7>;

VertexShaderConstant[32]=<mIdt>;

VertexShaderConstant[50]=<mTot>;//mTotisjustview*proj

VertexShaderConstant[48]=<lhtR>;

VertexShaderConstant[40]=(1.0f,-1.0f,0.0f,.0f);

Page 441: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

VertexShaderConstant[41]=(0.00390625f,256.0f,4.0f,1020.01f);

VertexShaderConstant[43]=(0.0,0.0,1.0,0.0f);

VertexShaderConstant[44]=(0.0,0.0,0.0,0.0);

VertexShaderConstant[60]=(0.5,0.5,0.5,0.5);

VertexShaderConstant[60]=(1.0f,1.0f,1.0f,1.0f);

VertexShaderConstant[61]=(.50f,0.43f,0.38f,1.0f);//Skycolor

VertexShaderConstant[62]=(0.18f,.10f,0.15f,1.0f);//Groundcolor

VertexShaderConstant[63]=<matD>;//Objectcolor

VerteXShaderConstant[64]=(0.0f,1.0f,0.0f,1.0f);//Skydirection

Texture[0]=<tDif>;

vertexshader=<sDif>;

wrap0=U|V;

wrap1=U|V;

AddressU[0]=Wrap;

AddressV[0]=Wrap;

AlphaBlendEnable=False;

}

}

Page 442: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 443: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise7:Multi-TexturingwithShaders//

//EffectFileWorkshopExercise7

//Copyright(c)2000MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR;//Lightdirection

matrixmWld;//World

matrixmTot;//Total

texturetDif;//Diffusetextureofobject

texturetNSE;//Noisetexture

//Backgroundcolor

DWORDBCLR=0xFF0000FF;

pixelshaderpNIL;

stringXFile="sphere.x";

//Techniquenamesfordisplayinviewerwindow

stringtec0="Exercise7:Multi-Texturingwithshaders";

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=<mWld>;//WorldMatrix

VertexShaderConstant[4]=<mTot>;//World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,0.0f,0.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=<lhtR>;//Lightdirection

Page 444: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Usefulconstant(s)

VertexShaderConstant[20]=(-1.0f,-1.0f,-1.0f,-1.0f);

Texture[0]=<tDif>;

Texture[1]=<tNSE>;

wrap0=U|V;

wrap1=U|V;

AddressU[0]=wrap;

AddressV[0]=wrap;

AddressU[1]=wrap;

AddressV[1]=wrap;

MinFilter[0]=Linear;

MagFilter[0]=Linear;

MinFilter[1]=Linear;

MagFilter[1]=Linear;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//Texturecoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace

m3x3r0,v3,c0//Transformnormaltoworldspace,put

//resultintor0

dp3r0,r0,-c16//Dotproductagainstlight,r0

//nowhaslightingconstantinx,yandz

//components(r,g,b)

movr0.xy,v7.xy//Copytexturecoordinatestor0

//mulr0.y,r0.y,c20//Inverttexturecoordinates

movoT0.xy,r0.xy//CopytexturecoordinatestooT0

movoT1.xy,r0.xy//CopytexturecoordinatestooT1

movoD0,r0//Copydiffusetooutput

};

PixelShader=

asm

{

Page 445: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ps.1.1

text0//Gettexturesamplefromstage0

text1//Gettexturesamplefromstage1

mul_x2r0,t1,t0;//Blendthemtogetherinaninterestingway

};

}

}

Page 446: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 447: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise8:TexturingwithLights//

//EffectFileWorkshopExercise8

//Copyright(c)2000MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR;//Lightdirection

matrixmWld;//World

matrixmTot;//Total

texturetDif;//Diffusetextureofobject

texturetNSE;//NoiseTexture

vectorvCPS;//Cameraposition

//Backgroundcolor

DWORDBCLR=0xFF0000FF;

pixelshaderpNIL;

stringXFile="sphere.x";

//Techniquenamesfordisplayinviewerwindow

stringtec0="Exercise8:Texturingwithlights";

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=<mWld>;//WorldMatrix

VertexShaderConstant[4]=<mTot>;//World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=<lhtR>;//LightDirection

Page 448: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Usefulconstants

VertexShaderConstant[20]=(1.0f,1.0f,1.0f,1.0f);

VertexShaderConstant[21]=(1.0f,1.0f,1.0f,0.0f);

//CameraInformation

VertexShaderConstant[24]=<vCPS>;

Texture[0]=<tDif>;

Texture[1]=<tNSE>;

wrap0=U|V;

wrap1=U|V;

AddressU[0]=wrap;

AddressV[0]=wrap;

AddressU[1]=wrap;

AddressV[1]=wrap;

MinFilter[0]=Linear;

MagFilter[0]=Linear;

MinFilter[1]=Linear;

MagFilter[1]=Linear;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//Texturecoord1

floatv8[3];//Texturecoord2

}

asm

{

vs.1.1//Versionnumber

m4x4oPos,v0,c4//Transformpointtoprojectionspace

m4x4r0,v0,c0//Transformpointtoworldspace

addr0,-r0,c24//Getavectortowardthecameraposition,

//thisisthenegativeofthecameradirection

//Normalize

dp3r11.x,r0.xyz,r0.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr0.xyz,r0.xyz,r11.xyz//Multiply,r0=-(cameravector)

addr2.xyz,r0.xyz,-c16//Gethalfangle

//Normalize

dp3r11.x,r2.xyz,r2.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr2.xyz,r2.xyz,r11.xyz//Multiply,r2=HalfAngle

Page 449: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

m3x3r1,v3,c0//Transformnormaltoworldspace,putinr1

//r2=halfangle,r1=normal,r3(output)=intensity

dp3r3.xyzw,r2,r1

//Nowraiseitseveraltimes

mulr3,r3,r3//2nd

mulr3,r3,r3//4th

mulr3,r3,r3//8th

mulr3,r3,r3//16th

mulr3,r3,c20

//Computediffuseterm

dp3r4,r1,-c16

mulr4,r4,c21

movoD0,r4

movoD1,r3

movoT0.xy,v7.xy//CopytexturecoordinatestooT0

movoT1.xy,v7.xy//CopytexturecoordinatestooT1

};

PixelShader=

asm

{

ps.1.1

text0//Sampletexture0

text1//Sampletexture1

mul_x2r1,t1,t0;//Blendthemtogether

movr0,r1

mulr0,r1,v0;//Modulatediffuse

mulr1,r1,v1;//Modulatespecular

addr0,r0,v1;//Blendthemtogether

};

}

}

Page 450: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 451: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise9:BumpMapping//

//EffectFileWorkshopExercise9

//Copyright(c)2000MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR;//Lightdirection

matrixmWld;//World

matrixmTot;//Total

texturetDif;//Diffusetextureofobject

texturetDf3;//Normalmapforearth

texturetL10;//Lightlookuptextureforspec

texturetL80;

texturetL64;

texturetL32;

texturetL16;

vectorvCPS;//CameraPosition

//Backgroundcolor

DWORDBCLR=0xFF0000FF;

pixelshaderpNIL;

stringXFile="sphere.x";

//Techniquenamesfordisplayinviewerwindow

stringtec0="Exercise9a:Dot3BumpMapping";

stringtec1="Exercise9b:Dot3SpecularBumpMapping";

stringtec2="Exercise9c:TableLookupSpecularBumpMapping";

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=; //WorldMatrix

VertexShaderConstant[4]=; //World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=(0.8f,0.8f,0.8f,0.8f);//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

Page 452: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(0.7f,0.7f,0.7f,0.7f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=; //LightDirection

vertexShaderConstant[20]=(.5f,.5f,.5f,.5f);

//Camerainformation

VertexShaderConstant[24]=;

Texture[0]=;

Texture[1]=;

wrap0=U|V;

wrap1=U|V;

AddressU[0]=wrap;

AddressV[0]=wrap;

AddressU[1]=wrap;

AddressV[1]=wrap;

MinFilter[0]=Linear;

MagFilter[0]=Linear;

MinFilter[1]=Linear;

MagFilter[1]=Linear;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//TextureCoord1

floatv8[3];//Tangent

}

asm

{

vs.1.1

//Transformposition

m4x4oPos,v0,c4

//Transformnormalandtangent

m3x3r7,v8,c0

m3x3r8,v3,c0

//Crossproduct

mulr0,-r7.zxyw,r8.yzxw;

madr5,-r7.yzxw,r8.zxyw,-r0;

Page 453: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Transformthelightvector

dp3r6.x,r7,-c16

dp3r6.y,r5,-c16

dp3r6.z,r8,-c16

//Multiplybyahalftobias,thenaddhalf

madr6.xyz,r6.xyz,c20,c20

movoT0.xy,v7.xy

movoT1.xy,v7.xy

movoD0.xyz,r6.xyz

};

PixelShader=

asm

{

ps.1.1

text0 //Sampletexture

text1 //Samplenormal

movr0,t1

dp3r0,t1_bx2,v0_bx2;//Dot(light,normal)

mulr0,t0,r0//Modulateagainstbasecolor

};

}

}

techniquetec1

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=; //Worldmatrix

VertexShaderConstant[4]=; //World*View*Projmatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=;//Lightdirection

VertexShaderConstant[20]=(.5f,.5f,.5f,.5f);

Page 454: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Camerainformation

VertexShaderConstant[24]=;

Texture[0]=;

Texture[1]=;

wrap0=U|V;

wrap1=U|V;

AddressU[0]=wrap;

AddressV[0]=wrap;

AddressU[1]=wrap;

AddressV[1]=wrap;

MinFilter[0]=Linear;

MagFilter[0]=Linear;

MinFilter[1]=Linear;

MagFilter[1]=Linear;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//TextureCoord1

floatv8[3];//Tangent

}

asm

{

vs.1.1

//Transformposition

m4x4oPos,v0,c4

//Transformnormalandtangent

m3x3r7,v8,c0

m3x3r8,v3,c0

//Crossproduct

mulr0,-r7.zxyw,r8.yzxw;

madr5,-r7.yzxw,r8.zxyw,-r0;

//Transformposition

m4x4r2,v0,c0

//Getavectortowardthecamera

addr2,-r2,c24

dp3r11.x,r2.xyz,r2.xyz//Loadthesquareintor11

Page 455: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr2.xyz,r2.xyz,r11.xyz//Multiply,r0=-(cameravector)

addr2.xyz,r2.xyz,-c16//Gethalfangle

//Normalize

dp3r11.x,r2.xyz,r2.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr2.xyz,r2.xyz,r11.xyz//Multiply,r2=HalfAngle

//Transformthehalfanglevector

dp3r6.x,r7,r2

dp3r6.y,r5,r2

dp3r6.z,r8,r2

//Multiplybyahalftobias,thenaddhalf

madr6.xyz,r6.xyz,c20,c20

movoT0.xy,v7.xy

movoT1.xy,v7.xy

movoD0.xyz,r6.xyz

};

PixelShader=

asm

{

ps.1.1

text0//Samplebasemap

text1//Samplenormal

dp3r0,t1_bx2,v0_bx2;//Dot(normal,half)

mulr1,r0,r0;//Raiseitto32ndpower

mulr0,r1,r1;

mulr1,r0,r0;

mulr0,r1,r1;

mulr0,t0,r0

};

}

}

techniquetec2

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=; //WorldMatrix

VertexShaderConstant[4]=; //World*View*ProjMatrix

Page 456: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Materialpropertiesofobject

VertexShaderConstant[9]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=;//LightDirection

vertexShaderConstant[20]=(.5f,.5f,.5f,.5f);

//CameraInformation

VertexShaderConstant[24]=;

Texture[0]=;

Texture[2]=;

Texture[3]=;

wrap0=U|V;

wrap1=0;

wrap2=0;

wrap3=U|V;

AddressU[0]=wrap;

AddressV[0]=wrap;

AddressU[1]=clamp;

AddressV[1]=clamp;

AddressU[2]=clamp;

AddressV[2]=clamp;

MinFilter[0]=Linear;

MagFilter[0]=Linear;

MinFilter[1]=Linear;

MagFilter[1]=Linear;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//TextureCoord1

floatv8[3];//Tangent

}

asm

{

vs.1.1

Page 457: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Transformposition

m4x4oPos,v0,c4

//Transformnormalandtangent

m3x3r7,v8,c0

m3x3r8,v3,c0

//Crossproduct

mulr0,-r7.zxyw,r8.yzxw;

madr5,-r7.yzxw,r8.zxyw,-r0;

//Transformposition

m4x4r2,v0,c0

//Getavectortowardthecamera

addr2,-r2,c24

dp3r11.x,r2.xyz,r2.xyz//Loadthesquareintor11

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr2.xyz,r2.xyz,r11.xyz//Multiply,r0=-(cameravector)

addr2.xyz,r2.xyz,-c16//Gethalfangle

//Normalize

dp3r11.x,r2.xyz,r2.xyz//Loadthesquareintor1

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr2.xyz,r2.xyz,r11.xyz//Multiply,r2=HalfAngle

//Transformthehalfanglevector

dp3r6.x,r7,r2

dp3r6.y,r5,r2

dp3r6.z,r8,r2

movoT0.xy,v7.xy//Coordinatetosampnormalfrom

movoT1.xyz,r6//Notatexcoordinate,buthalf

movoT2.xyz,r6//Angle

movoT3.xy,v7.xy

};

PixelShader=

asm

{

ps.1.1

text0 //Samplenormal

texm3x2padt1,t0_bx2//Lookitupinatable

texm3x2text2,t0_bx2

text3//Samplebasecolor

movr0,t2

Page 458: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

mulr0,r0,t3//Blendterms

};

}

}

Page 459: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 460: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise10:AnisotropicBumpMapping//

//EffectFileWorkshopExercise10

//Copyright(c)2000MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR;//Lightdirection

matrixmWld;//World

matrixmTot;//Total

texturetDif;//Diffusetextureofobject

texturetDf4;//Normalmapforearth

texturetSt2;//Anisotropiclightingtable

vectorvCPS;//Cameraposition

//Backgroundcolor

DWORDBCLR=0xFF0000FF;

pixelshaderpNIL;

stringXFile="bust.x";

//Techniquenamesfordisplayinviewerwindow

stringtec0="Exercise10:AnisotropicBumpMapping";

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=<mWld>;//WorldMatrix

VertexShaderConstant[4]=<mTot>;//World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

Page 461: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=;//Lightdirection

vertexShaderConstant[20]=(.5f,.5f,.5f,.5f);

vertexShaderConstant[40]=(1.0f,1.0f,1.0f,1.0f);

//Camerainformation

VertexShaderConstant[24]=<vCPS>;

PixelShaderConstant[0]=(0.5f,0.2f,0.2f,0.2f);

Texture[0]=<tDf4>;

Texture[3]=<tSt2>;

wrap0=U|V;

wrap1=0;

wrap2=0;

wrap3=0;

AddressU[0]=wrap;

AddressV[0]=wrap;

AddressU[1]=wrap;

AddressV[1]=wrap;

AddressU[3]=wrap;

AddressV[3]=wrap;

MinFilter[0]=Linear;

MagFilter[0]=Linear;

MinFilter[1]=Linear;

MagFilter[1]=Linear;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//TextureCoord1

floatv8[3];//Tangent

}

asm

{

vs.1.1

//Transformposition

m4x4oPos,v0,c4

//Transformnormalandtangent

m3x3r7,v8,c0

m3x3r8,v3,c0

Page 462: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

//Crossproduct

mulr0,-r7.zxyw,r8.yzxw;

madr5,-r7.yzxw,r8.zxyw,-r0;

//Transformposition

m4x4r2,v0,c0

//Getavectortowardthecamera

addr2,-r2,c24

dp3r11.x,r2.xyz,r2.xyz//Loadthesquareintor11

rsqr11.xyz,r11.x//Gettheinverseofthesquare

mulr2.xyz,r2.xyz,r11.xyz//Multiply,r0=-(cameravector)

//Transformtheviewanglevector

dp3r6.x,r7,r2

dp3r6.y,r5,r2

dp3r6.z,r8,r2

//Transformthelightvector

dp3r2.x,r7,-c16

dp3r2.y,r5,-c16

dp3r2.z,r8,-c16

movoT0.xy,v7.xy//Coordinatestosampnormalfrom

movoT1.xyz,r2//Light

movoT2.xyz,r6//Viewangle

movoT3.xyz,c40//Garbageinthisregister

};

PixelShader=

asm

{

ps.1.1

text0

texm3x3padt1,t0_bx2//3x3transform

texm3x3padt2,t0_bx2//Thesegenerateatexcoordwhichis

texm3x3text3,t0_bx2//u=dot(light,normal)

//v=dot(view,normal)

//w=somepositivenumber

movr0,t3;

madr0,c0,t3.a,r0;//Alphahasthediffuse,soaddit

//tospecularforfinalresult

};

}

}

Page 463: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 464: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Exercise11:AreaLighting//

//EffectFileWorkshopExercise11

//Copyright(c)2000MicrosoftCorporation.Allrightsreserved.

//

vectorlhtR;//LightDirection

vectormatD;//MaterialDiffuse

matrixmWld;//World

matrixmTot;//Total

texturetDif;//Diffusetextureofobject

//Backgroundcolor

DWORDBCLR=0xFF000000;

pixelshaderpNIL;

stringXFile="skullhiv.x";

//Techniquenamesfordisplayinviewerwindow

stringtec0="Exercise11a:AreaLighting";

stringtec1="Exercise11b:AreaandDiffuseLighting";

techniquetec0

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=<mWld>;//WorldMatrix

VertexShaderConstant[4]=<mTot>;//World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=<matD>;//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//Propertiesoflight

VertexShaderConstant[13]=(1.0f,1.0f,1.0f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=<lhtR>;//Lightdirection

Page 465: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

VertexShaderConstant[20]=(.5f,.5f,.5f,.5f);

VertexShaderConstant[40]=(1.0f,1.0f,1.0f,1.0f);

VertexShaderConstant[41]=(1.00f,0.86f,0.75f,1.0f);//skycolor

VertexShaderConstant[42]=(0.25f,.25f,0.15f,1.0f);//groundcolor

VertexShaderConstant[43]=<matD>;//objectcolor

VerteXShaderConstant[44]=(0.0f,-1.0f,0.0f,1.0f);//skydirection

Texture[0]=<tDif>;

wrap0=U|V;

wrap1=0;

wrap2=0;

AddressU[0]=wrap;

AddressV[0]=wrap;

MinFilter[0]=Linear;

MagFilter[0]=Linear;

MinFilter[1]=Linear;

MagFilter[1]=Linear;

ColorOp[0]=Modulate;

ColorArg1[0]=Diffuse;

ColorArg2[0]=Texture;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//TextureCoord1

floatv8[3];//Tangent

}

asm

{

vs.1.1

m4x4oPos,v0,c4//Transformposition

m3x3r0,v3,c0//Transformnormaltoworldspace

dp3r0,r0,-c44//Dotproductagainstskyvector

//Thedotproductwasbetween-1to1.Wewant

//tore-rangethisto0to1

madr0,r0,c20,c20

//Nowlerpbetweenthetwoskycolors.

movr1,c42

Page 466: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

subr1,c41,r1//Tosaveaclock,thisdeltashouldbe

//savedinaregister

madr0,r1,r0,c42//Nowlerp

subr1,c40,v7.zzz//Thismodulatesagainstadarkeningterm

//orocclusionterm,embeddedintheztex

//coordinate,wewant1-zthough

mulr0,r0,r1//Darkenskyterm

muloD0,r0,c9//Nowmodulateagainstobject'scolor

movoT0.xy,v7.xy

};

}

}

techniquetec1

{

passp0

{

//Loadmatrices

VertexShaderConstant[0]=<mWld>;//WorldMatrix

VertexShaderConstant[4]=<mTot>;//World*View*ProjMatrix

//Materialpropertiesofobject

VertexShaderConstant[9]=<matD>;//Diffuse

VertexShaderConstant[10]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[11]=(0.0f,0.0f,0.0f,0.0f);//Ambient

//propertiesoflight

VertexShaderConstant[13]=(.6f,.6f,.6f,1.0f);//Diffuse

VertexShaderConstant[14]=(0.0f,0.0f,0.0f,0.0f);//Specular

VertexShaderConstant[15]=(0.0f,0.0f,0.0f,0.0f);//Ambient

VertexShaderConstant[16]=<lhtR>;//Lightdirection

VertexShaderConstant[20]=(.5f,.5f,.5f,.5f);

VertexShaderConstant[40]=(1.0f,1.0f,1.0f,1.0f);

VertexShaderConstant[41]=(.80f,0.76f,0.65f,1.0f);//Skycolor

VertexShaderConstant[42]=(0.25f,.25f,0.15f,1.0f);//Groundcolor

VertexShaderConstant[43]=<matD>;//Objectcolor

VerteXShaderConstant[44]=(0.0f,-1.0f,0.0f,1.0f);//Skydirection

FillMode=Wireframe;

Texture[0]=<tDif>;

wrap0=U|V;

wrap1=0;

wrap2=0;

Page 467: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

AddressU[0]=wrap;

AddressV[0]=wrap;

MinFilter[0]=Linear;

MagFilter[0]=Linear;

MinFilter[1]=Linear;

MagFilter[1]=Linear;

ColorOp[0]=Modulate;

ColorArg1[0]=Diffuse;

ColorArg2[0]=Texture;

AlphaOp[0]=SelectArg1;

AlphaArg1[0]=Diffuse;

VertexShader=

decl

{

stream0;

floatv0[3];//Position

floatv3[3];//Normal

floatv7[3];//TextureCoord1

floatv8[3];//Tangent

}

asm

{

vs.1.1

m4x4oPos,v0,c4//Transformposition

m3x3r9,v3,c0//Transformnormaltoworldspace

dp3r0,r9,-c44//Dotproductagainstskyvector

//Thedotproductwasbetween-1to1.Wewant

//tore-rangethisto0to1

madr0,r0,c20,c20

//nowlerpbetweenthetwoskycolors

movr1,c42

subr1,c41,r1//Tosaveaclock,thisdeltashould

//besavedinaregister

madr0,r1,r0,c42//Nowlerp

subr1,c40,v7.zzz//Thismodulatesagainstadarkeningterm

//orocclusionterm,embeddedintheztex

//coordinate,wewant1-zthough

mulr2,r0,r1//Darkenskyterm

dp3r1,r9,-c16//Dotagainstlightvector

maxr1,c15,r1

//Complement,square,complement

Page 468: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

subr1,c40,r1

mulr1,r1,r1

mulr1,r1,r1

subr1,c40,r1

madr0,r1,c13,r2//Combinewithlightdiffuse

muloD0,r0,c9//Nowmodulateagainstobject'scolor

movoT0.xy,v7.xy

};

}

}

Page 469: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 470: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

AmbientLighting

Ambientlightingprovidesconstantlightingforascene.Itlightsallobjectverticesthesamebecauseitisnotdependentonanyotherlightingfactorssuchasvertexnormals,lightdirection,lightposition,range,orattenuation.Itisthefastesttypeoflightingbutitproducestheleastrealisticresults.Microsoft®Direct3D®containsasingleglobalambientlightpropertythatyoucanusewithoutcreatinganylight.Alternatively,youcansetanylightobjecttoprovideambientlighting.Theambientlightingforasceneisdescribedbythefollowingequation.

AmbientLighting=Mc*[Ga+sum(Lai)]

Theparametersaredefinedinthefollowingtable.

Parameter Defaultvalue Type DescriptionMc (0,0,0,0) D3DCOLORVALUE Materialambientcolor.Ga (0,0,0,0) D3DCOLORVALUE Globalambientcolor.

Lai (0,0,0,0) D3DVECTOR Lightambientcolor,oftheithlight.

sum N/A N/ASummationoftheambientlightfromthelightobjects.

ThevalueforMcisoneofthreevalues:oneofthetwopossiblevertexcolorsinavertexdeclaration,orthematerialambientcolor.Thevalueis:

vertexcolor1,ifAMBIENTMATERIALSOURCE=D3DMCS_COLOR1,andthefirstvertexcolorissuppliedinthevertexdeclaration.vertexcolor2,ifAMBIENTMATERIALSOURCE=D3DMCS_COLOR2,andthesecondvertexcolorissuppliedinvertexdeclaration.materialambientcolor

NoteIfeitherAMBIENTMATERIALSOURCEoptionisused,andthevertexcolorisnotprovided,thenthematerialambientcolorisused.

Tousethematerialambientcolor,useSetMaterialasshownintheexamplecode

Page 471: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

below.

Gaistheglobalambientcolor.ItissetusingSetRenderState(D3DRENDERSTATE_AMBIENT).ThereisoneglobalambientcolorinaDirect3Dscene.ThisparameterisnotassociatedwithaDirect3Dlightobject.

Laiistheambientcoloroftheithlightinthescene.EachDirect3Dlighthasasetofproperties,oneofwhichistheambientcolor.Theterm,sum(Lai)isasumofalltheambientcolorsinthescene.

Example

Inthisexample,theobjectiscoloredusingthesceneambientlightandamaterialambientcolor.Thecodeisshownbelow.

#defineGRAY_COLOR 0x00bfbfbf

//creatematerial

D3DMATERIAL8mtrl;

ZeroMemory(&mtrl;,sizeof(D3DMATERIAL8));

mtrl.Ambient.r=0.75f;

mtrl.Ambient.g=0.0f;

mtrl.Ambient.b=0.0f;

mtrl.Ambient.a=0.0f;

m_pd3dDevice->SetMaterial(&mtrl;);

m_pd3dDevice->SetRenderState(D3DRS_AMBIENT,GRAY_COLOR);

Accordingtotheequation,theresultingcolorfortheobjectverticesisacombinationofthematerialcolorandthelightcolor.

Thesetwoimagesshowthematerialcolor,whichisgray,andthelightcolor,whichisbrightred.

Theresultingsceneisshownbelow.Theonlyobjectinthesceneisasphere.Ambientlightlightsallobjectverticeswiththesamecolor.Itisnotdependentonthevertexnormalorthelightdirection.Asaresult,thespherelookslikea2-Dcirclebecausethereisnodifferenceinshadingaroundthesurfaceoftheobject.

Page 472: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Togiveobjectsamorerealisticlook,applydiffuseorspecularlightinginadditiontoambientlighting.

Page 473: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 474: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DiffuseLighting

Afteradjustingthelightintensityforanyattenuationeffects,Microsoft®Direct3D®computeshowmuchoftheremaininglightreflectsfromavertex,giventheangleofthevertexnormalandthedirectionoftheincidentlight.Direct3Dskipstothisstepfordirectionallightsbecausetheydonotattenuateoverdistance.Thesystemconsiderstworeflectiontypes,diffuseandspecular,andusesadifferentformulatodeterminehowmuchlightisreflectedforeach.Aftercalculatingtheamountsoflightreflected,Direct3Dappliesthesenewvaluestothediffuseandspecularreflectancepropertiesofthecurrentmaterial.TheresultingcolorvaluesarethediffuseandspecularcomponentsthattherasterizerusestoproduceGouraudshadingandspecularhighlighting.

Diffuselightingisdescribedbythefollowingequation.

DiffuseLighting=sum[Vd*Ld*(N.Ldir)*Atten*Spot]

Theparametersaredefinedinthefollowingtable.Parameter Defaultvalue Type Description

sum N/A N/ASummationofeachlight'sdiffusecomponent.

Vd (0,0,0,0) D3DCOLORVALUE Vertexdiffusecolor.Ld (0,0,0,0) D3DCOLORVALUE Lightdiffusecolor.N N/A D3DVECTOR Vertexnormal.

Ldir (0,0,0,0) D3DCOLORVALUE Directionvectorfromobjectvertextothelight.

Atten (0,0,0,0) D3DCOLORVALUE Lightattenuation.

Spot (0,0,0,0) D3DVECTOR Characteristicsofthespotlightcone.

ThevalueforVdisoneofthreevalues:oneofthetwopossiblevertexcolorsinavertexdeclaration,orthematerialdiffusecolor.Thevalueis:

vertexcolor1,ifDIFFUSEMATERIALSOURCE=D3DMCS_COLOR1,andthefirstvertexcolorissuppliedinthevertexdeclaration.

Page 475: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

vertexcolor2,ifDIFFUSEMATERIALSOURCE=D3DMCS_COLOR2,andthesecondvertexcolorissuppliedinthevertexdeclaration.materialdiffusecolor

Note:IfeitherDIFFUSEMATERIALSOURCEoptionisused,andthevertexcolorisnotprovided,thematerialdiffusecolorisused.

Tocalculatetheattenuation(Atten)orthespotlightcharacteristics(Spot),seeAttenuationandSpotlightTerms

Diffusecomponentsareclampedtobefrom0to255,afteralllightsareprocessedandinterpolatedseparately.Theresultingdiffuselightingvalueisacombinationoftheambient,diffuseandemissivelightvalues.

Example

Inthisexample,theobjectiscoloredusingthelightdiffusecolorandamaterialdiffusecolor.Thecodeisshownbelow.

D3DMATERIAL8mtrl;

ZeroMemory(&mtrl;,sizeof(D3DMATERIAL8));

D3DLIGHT8light;

ZeroMemory(&light;,sizeof(D3DLIGHT8));

light.Type=D3DLIGHT_DIRECTIONAL;

D3DXVECTOR3vecDir;

vecDir=D3DXVECTOR3(0.5f,0.0f,-0.5f);

D3DXVec3Normalize((D3DXVECTOR3*)&light.Direction;,&vecDir;);

//setdirectionallightdiffusecolor

light.Diffuse.r=1.0f;

light.Diffuse.g=1.0f;

light.Diffuse.b=1.0f;

light.Diffuse.a=1.0f;

m_pd3dDevice->SetLight(0,&light;);

m_pd3dDevice->LightEnable(0,TRUE);

//ifamaterialisused,SetRenderStatemustbeused

//vertexcolor=lightdiffusecolor*materialdiffusecolor

mtrl.Diffuse.r=0.75f;

mtrl.Diffuse.g=0.0f;

mtrl.Diffuse.b=0.0f;

mtrl.Diffuse.a=0.0f;

Page 476: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

m_pd3dDevice->SetMaterial(&mtrl;);

m_pd3dDevice->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE,D3DMCS_MATERIAL);

Accordingtotheequation,theresultingcolorfortheobjectverticesisacombinationofthematerialcolorandthelightcolor.

Thesetwoimagesshowthematerialcolor,whichisgray,andthelightcolor,whichisbrightred.

Theresultingsceneisshownbelow.Theonlyobjectinthesceneisasphere.Thediffuselightingcalculationtakesthematerialandlightdiffusecolorandmodifiesitbytheanglebetweenthelightdirectionandthevertexnormalusingthedotproduct.Asaresult,thebacksideofthespheregetsdarkerasthesurfaceofthespherecurvesawayfromthelight.

Combiningthediffuselightingwiththeambientlightingfromthepreviousexampleshadestheentiresurfaceoftheobject.Theambientlightshadestheentiresurfaceandthediffuselighthelpsrevealtheobject'sthree-dimensional(3-D)shape.

Diffuselightingismoreintensivetocalculatethanambientlighting.Becauseitdependsonthevertexnormalsandlightdirection,youcanseetheobjectsgeometryin3-Dspace,whichproducesamorerealisticlightingthanambientlighting.Youcanusespecularhighlightstoachieveamorerealisticlook.

Page 477: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 478: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

SpecularLighting

Modelingspecularreflectionrequiresthatthesystemnotonlyknowthedirectionthatlightistraveling,butalsothedirectiontotheviewer'seye.ThesystemusesasimplifiedversionofthePhongspecular-reflectionmodel,whichemploysahalfwayvectortoapproximatetheintensityofspecularreflection.

Thedefaultlightingstatedoesnotcalculatespecularhighlights.Toenablespecularlighting,besuretosettheD3DRS_SPECULARENABLEtoTRUE.

SpecularLightingisdescribedbythefollowingequation.

SpecularLighting=Vs*sum[Ls*(N.H)P*Atten*Spot]

Theparametersaredefinedinthefollowingtable.

Parameter Defaultvalue Type Description

Vs (0,0,0,0) D3DCOLORVALUEVertexspecularcolor.

sum N/A N/A

Summationofeachlight'sspecularcomponent.

ThevalueforVcisoneofthreevalues:oneofthetwopossiblevertexcolorsinavertexdeclaration,orthematerialspecularcolor.Thevalueis:

vertexcolor1,ifSPECULARMATERIALSOURCE=D3DMCS_COLOR1,andthefirstvertexcolorissuppliedinthevertexdeclaration.vertexcolor2,ifSPECULARMATERIALSOURCE=D3DMCS_COLOR2,andthesecondvertexcolorissuppliedinthevertexdeclaration.materialspecularcolor

Note:IfeitherSPECULARMATERIALSOURCEoptionisused,andthevertexcolorisnotprovided,thenthematerialspecularcolorisused.

Page 479: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Tocalculatetheattenuation(Atten)orthespotlightcharacteristics(Spot),seeAttenuationandSpotlightTerms

Thehalfwayvector(H)existsmidwaybetweenthevectorfromanobjectvertextothelightsourceandthevectorfromanobjectvertexandthecameraposition.Microsoft®Direct3D®providestwowaystocomputethehalfwayvector.WhenD3DRS_LOCALVIEWERissettoTRUE,thesystemcalculatesthehalfwayvectorusingthepositionofthecameraandthepositionofthevertex,alongwiththelight'sdirectionvector.Thefollowingformulaillustratesthis.

H=norm(norm(Cp-Vp)+Ldir)wheretheparametersaredefinedinthefollowingtable:

Parameter Defaultvalue Type Description

Cp (0,0,0,0) D3DVECTOR Cameraposition.

Vp (0,0,0,0) D3DVECTORVertexposition.

WhenD3DRS_LOCALVIEWERissettoTRUE,Direct3Ddeterminesthehalfwayvectorbythefollowingformula.

H=norm(norm(-Vp)+Ldir)

Determiningthehalfwayvectorinthismannercanbecomputationallyintensive.Asanalternative,settingD3DRS_LOCALVIEWERtoFALSEinstructsthesystemtoactasthoughtheviewpointisinfinitelydistantonthez-axis.Thissettingislesscomputationallyintensive,butmuchlessaccurate,soitisbestusedbyapplicationsthatuseorthogonalprojection.

Specularcomponentsareclampedtobefrom0to255,afteralllightsareprocessedandinterpolatedseparately.

Page 480: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Example

Inthisexample,theobjectiscoloredusingthescenespecularlightcolorandamaterialspecularcolor.Thecodeisshownbelow.

D3DMATERIAL8mtrl;

ZeroMemory(&mtrl;,sizeof(D3DMATERIAL8));

D3DLIGHT8light;

ZeroMemory(&light;,sizeof(D3DLIGHT8));

light.Type=D3DLIGHT_DIRECTIONAL;

D3DXVECTOR3vecDir;

vecDir=D3DXVECTOR3(0.5f,0.0f,-0.5f);

D3DXVec3Normalize((D3DXVECTOR3*)&light.Direction;,&vecDir;);

light.Specular.r=1.0f;

light.Specular.g=1.0f;

light.Specular.b=1.0f;

light.Specular.a=1.0f;

light.Range=1000;

light.Falloff=0;

light.Attenuation0=1;

light.Attenuation1=0;

light.Attenuation2=0;

m_pd3dDevice->SetLight(0,&light;);

m_pd3dDevice->LightEnable(0,TRUE);

m_pd3dDevice->SetRenderState(D3DRS_SPECULARENABLE,TRUE);

mtrl.Specular.r=1.0f;

mtrl.Specular.g=1.0f;

mtrl.Specular.b=1.0f;

mtrl.Specular.a=1.0f;

mtrl.Power=20;

m_pd3dDevice->SetMaterial(&mtrl;);

m_pd3dDevice->SetRenderState(D3DRS_SPECULARMATERIALSOURCE,D3DMCS_MATERIAL);

Accordingtotheequation,theresultingcolorfortheobjectverticesisacombinationofthematerialcolorandthelightcolor.

Thesetwoimagesshowthematerialcolor,whichisgray,andthelightcolor,whichiswhite.

Page 481: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Theresultingspecularhighlightisshownbelow.

Combiningthespecularhighlightwiththeambientanddiffuselightingproducesthefollowingimage.Withallthreetypesoflightingapplied,thismoreclearlyresemblesarealisticobject.

Specularlightingismoreintensivetocalculatethandiffuselighting.Itistypicallyusedtoprovidevisualcluesaboutthesurfacematerial.Thespecularhighlightvariesinsizeandcolorwiththematerialofthesurface.

Page 482: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 483: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

EmissiveLighting

Emissivelightingisdescribedbyasingleterm.

EmissiveLighting=Me

Theparameterisdefinedinthefollowingtable.

Parameter Defaultvalue Type Description

Me (0,0,0,0) D3DCOLORVALUE Materialemissivecolor.

ThevalueforMeisoneofthreevalues:oneofthetwopossiblevertexcolorsinavertexdeclaration,orthematerialemissivecolor.Thevalueis:

vertexcolor1,ifEMISSIVEMATERIALSOURCE=D3DMCS_COLOR1,andthefirstvertexcolorissuppliedinthevertexdeclaration.vertexcolor2,ifEMISSIVEMATERIALSOURCE=D3DMCS_COLOR2,andthesecondvertexcolorissuppliedinthevertexdeclaration.materialemissivecolor

NoteIfeitherEMISSIVEMATERIALSOURCEoptionisused,andthevertexcolorisnotprovided,thematerialemissivecolorisused.

Example

Inthisexample,theobjectiscoloredusingthesceneambientlightandamaterialambientcolor.Thecodeisshownbelow.

//creatematerial

D3DMATERIAL8mtrl;

ZeroMemory(&mtrl;,sizeof(D3DMATERIAL8));

mtrl.Emissive.r=0.0f;

mtrl.Emissive.g=0.75f;

mtrl.Emissive.b=0.0f;

mtrl.Emissive.a=0.0f;

m_pd3dDevice->SetMaterial(&mtrl;);

m_pd3dDevice->SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE,D3DMCS_MATERIAL);

Page 484: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Accordingtotheequation,theresultingcolorfortheobjectverticesisthematerialcolor.

Theimagebelowshowsthematerialcolor,whichisgreen.Emissivelightlightsallobjectverticeswiththesamecolor.Itisnotdependentonthevertexnormalorthelightdirection.Asaresult,thespherelookslikea2-Dcirclebecausethereisnodifferenceinshadingaroundthesurfaceoftheobject.

Thisimageshowshowtheemissivelightblendswiththeotherthreetypesoflights,fromthepreviousexamples.Ontherightsideofthesphere,thereisablendofthegreenemissiveandtheredambientlight.Ontheleftsideofthesphere,thegreenemissivelightblendswithredambientanddiffuselightproducingaredgradient.Thespecularhighlightiswhiteinthecenterandcreatesayellowringasthespecularlightvaluefallsoffsharplyleavingtheambient,diffuseandemissivelightvalueswhichblendtogethertomakeyellow.

Page 485: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

CameraSpaceTransformations

Verticesinthecameraspacearecomputedbytransformingtheobjectverticeswiththeworldviewmatrix.

V=V*wvMatrix

Vertexnormals,incameraspace,arecomputedbytransformingtheobjectnormalswiththeinversetransposeoftheworldviewmatrix.Theworldviewmatrixmayormaynotbesymmetrical.

N=N*(wvMatrix-1)T

Thematrixinversionandmatrixtransposeoperateona4×4matrix.Themultiplycombinesthenormalwiththe3×3portionoftheresulting4×4matrix.

Iftherenderstate,D3DRENDERSTATE_NORMALIZENORMALSissettoTRUE,vertexnormalvectorsarenormalizedaftertransformationtocameraspaceasfollows:

N=norm(N)

Lightpositionincameraspaceiscomputedbytransformingthelightsourcepositionwiththeviewmatrix.

Lp=Lp*vMatrix

Thedirectiontothelightincameraspaceforadirectionallightiscomputedbymultiplyingthelightsourcedirectionbytheviewmatrix,normalizing,andnegatingtheresult.

Page 486: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Ldir=-norm(Ldir*vMatrix)

FortheD3DLIGHT_POINTandD3DLIGHT_SPOTthedirectiontolightiscomputedasfollows:

Ldir=norm(Ldir),wheretheparametersaredefinedinthefollowingtable.

Parameter Defaultvalue Type Description

Ldir (0,0,0,0) D3DCOLORVALUE Directionvectorfromobjectvertextothelight

V (0,0,0,0) D3DVECTOR Vertexposition

wvMatrix Identity D3DMATRIXCompositematrixcontainingtheworldandviewtransforms

N (0,0,0,0) D3DVECTOR VertexnormalLp (0,0,0,0) D3DVECTOR Lightposition

vMatrix Identity D3DMATRIX Matrixcontainingtheviewtransform

Page 487: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

AttenuationandSpotlightTerms

Thediffuseandspecularlightingcomponentsoftheglobalilluminationequationcontaintermsthatdescribelightattenuationandthespotlightcone.Thesetermsaredescribedbelow.

AttenuationTerm

Theattenuationofalightdependsonthetypeoflightandthedistancebetweenthelightandthevertexposition.Tocalculateattenuation,useoneofthefollowingthreeequations.

Atten=1,ifthelightisadirectionallight.Atten=0,ifthedistancebetweenthelightandthevertexexceedsthelight'srange.Atten=1/(att0i+att1i*d+att2i*di2).

Parameter Defaultvalue Type Descriptionatt0i (0,0,0,0) FLOAT Linearattenuationfactoratt1i (0,0,0,0) FLOAT Squaredattenuationfactoratt2i (0,0,0,0) FLOAT Exponentialattenuationfactor

di (0,0,0,0) FLOAT Distancefromvertexpositiontolightposition

Theatt0,att1,att2valuesarespecifiedbytheAttenuation0,Attenuation1,andAttenuation2membersoftheD3DLIGHT8structure.

Thedistancebetweenthelightandthevertexpositionisalwayspositive.

di=||Ldir||

where:

Parameter Defaultvalue Type Description

Ldir 0.0 D3DVECTORDirectionvectorfromvertexpositiontothe

Page 488: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

lightposition

Ifdiisgreaterthanthelight'srange,thatis,theRangememberofaD3DLIGHT8structure,Direct3Dmakesnofurtherattenuationcalculationsandappliesnoeffectsfromthelighttothevertex.ThedvAttenuation0,dvAttenuation1,anddvAttenuation2valuesarethelight'sattenuationconstantsasspecifiedbythemembersofalightobject'sD3DLIGHT8structure.ThecorrespondingstructuremembersareAttenuation0,Attenuation1,andAttenuation2.

Theattenuationconstantsactascoefficientsintheformula—youcanproduceavarietyofattenuationcurvesbymakingsimpleadjustmentstothem.YoucansetAttenuation0to1.0tocreatealightthatdoesn'tattenuatebutisstilllimitedbyrange,oryoucanexperimentwithdifferentvaluestoachievevariousattenuationeffects.

Theattenuationatthemaximumrangeofthelightisnot0.0.Topreventlightsfromsuddenlyappearingwhentheyareatthelightrange,anapplicationcanincreasethelightrange.Or,theapplicationcansetupattenuationconstantssothattheattenuationfactoriscloseto0.0atthelightrange.Theattenuationvalueismultipliedbythered,green,andbluecomponentsofthelight'scolortoscalethelight'sintensityasafactorofthedistancelighttravelstoavertex.

SpotlightTerm

Parameter Defaultvalue Type Descriptionrho 0.0 N/A Angle

phi 0.0 FLOATPenumbraangleofspotlightinradians.Range:[thetaI,p)

theta 0.0 FLOAT Umbraangleofspotlightinradians.Range:[0,p)

falloff 0.0 FLOATFallofffactor.Range:(-infinity,+infinity)

Page 489: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

where:

rho=norm(Ldcs).norm(Ldir)

Parameter Defaultvalue Type Description

Ldcs 0.0 D3DVECTORDirectionvectorfromorigintothelightpositionincameraspace

Ldir 0.0 D3DVECTORDirectionvectorfromvertexpositiontothelightposition

Aftercomputingthelightattenuation,Direct3Dalsoconsiders:spotlighteffectsifapplicable,theanglethatthelightreflectsfromasurface,andthereflectanceofthecurrentmaterialtocalculatethediffuseandspecularcomponentsforthatvertex.Formoreinformation,seeSpotlightModel.

Page 490: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

PreparingtheActionMap

TheactionmapisaDIACTIONFORMATstructurecontaininginformationaboutapplicationactionsandtheirmappingtovirtualcontrolsordeviceobjects.ThestructureispassedbackandforthbetweentheapplicationandMicrosoft®DirectInput®toestablishthefinalmapping.Thissectionexplainshowtoinitializethemap.

1.DefineApplicationActions

ThefirststepinimplementingDirectInputactionmappingistodeterminewhatinput-drivenactionsinyourapplicationneedtobemappedtodeviceobjects.Foractionsthatcanbeperformedeitherbyanaxisorbyabutton,youmustdefineseparateactionsforbothinputtypes.Itisrecommendedthatyoudefinebuttonactionsforallimportantfunctions,incasethedevicedoesnothavetheappropriateaxes.

Thefollowingsampleenumerationofactionvaluesmightbedefinedbyacar-racinggame.Axisactionsbeginwith"eA"andbuttonactionswith"eB".

enumeGameActions

{

eA_STEER,//Steering

eB_STEER_LEFT,//Steerleft

eB_STEER_RIGHT,//Steerright

eA_ACCELERATE,//Changespeed

eB_ACCELERATE,//Speedup

eB_DECELERATE,//Slowdown

eA_BRAKE,//Brake

eB_BRAKE,//Brake

eB_UPSHIFT,//Shifttohighergear

eB_DOWNSHIFT,//Shifttolowergear

eB_CYCLEVIEW,//Cycletonextview

eB_COURSEVIEW,//Togglecourseview

eB_DRIVERVIEW,//Viewfromdriver'sseat

eB_BRAKEBIAS,//Brakebias

eA_VOLUME,//Soundvolume

eB_MUTE//Togglesound

};

Page 491: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

#defineNUM_MY_ACTIONS16

Intheexample,actionsaredefinedasenumeratedvalues.However,theycouldbeother32-bitdatatypes,suchaspointerstofunctions.Whenyouretrievedevicedata,yougetwhateveractionvalueyouhavedefined,andyoucanhandleitinanywayyoulike.

2.DefinetheGenre

Thenextstepistodecidewhatgenreyourapplicationbelongsto.Agenredefinesasetofvirtualcontrols.Byselectingthepropergenre,youcanobtainthebestpossiblefitofvirtualcontrolstoapplicationactions.ManufacturerswhochoosetosupplydefaultmappingsfortheirdevicesmustsupportoneormoreofthegenresdefinedbyDirectInput.SeeActionMappingConstantsforalistofthesegenres.

Forthegameintheexample,theobviouschoiceistheDIVIRTUAL_DRIVING_RACEgenre,whichcontainsthefollowingvirtualcontrols.

Priority1Controls

DIAXIS_DRIVINGR_STEERDIAXIS_DRIVINGR_ACCELERATEDIAXIS_DRIVINGR_BRAKEDIBUTTON_DRIVINGR_SHIFTUPDIBUTTON_DRIVINGR_SHIFTDOWNDIBUTTON_DRIVINGR_VIEWDIBUTTON_DRIVINGR_MENU

Priority2Controls

DIAXIS_DRIVINGR_ACCEL_AND_BRAKEDIHATSWITCH_DRIVINGR_GLANCEDIBUTTON_DRIVINGR_ACCELERATE_LINKDIBUTTON_DRIVINGR_AIDSDIBUTTON_DRIVINGR_BOOSTDIBUTTON_DRIVINGR_BRAKEDIBUTTON_DRIVINGR_DASHBOARD

Page 492: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DIBUTTON_DRIVINGR_DEVICEDIBUTTON_DRIVINGR_GLANCE_LEFT_LINKDIBUTTON_DRIVINGR_GLANCE_RIGHT_LINKDIBUTTON_DRIVINGR_MAPDIBUTTON_DRIVINGR_PAUSEDIBUTTON_DRIVINGR_PITDIBUTTON_DRIVINGR_STEER_LEFT_LINKDIBUTTON_DRIVINGR_STEER_RIGHT_LINK

ThereisnodifferenceinfunctionalitybetweenPriority1andPriority2controls.Priority1controlsarethosemostlikelytobesupportedbydevicemanufacturersintheirdefaultmappings.However,thereisnoguaranteethatanyvirtualcontrolwillbesupportedbyadevice.

3.AssignActionstoControlsorDeviceObjects

Thenextstepincreatingtheactionmapistoassociateeachapplicationactionwithoneormoreofthevirtualcontrolsdefinedforthegenre.YoudothisbydeclaringandinitializinganarrayofDIACTIONstructures.Eachstructureinthearrayspecifiestheactionvalue,thevirtualcontroltoassociatewithit,andafriendlynamethatdescribestheaction.Leaveothermembersaszero;theywillbefilledinlaterbyDirectInput.

YoucanalsouseelementsoftheDIACTIONarraytomapactionstoparticularkeysorbuttonsonthekeyboardormouseortochannelsonaMicrosoftDirectPlay®voicedevice.Bydoingso,youcantakeadvantageofthesimplifiedinputloopforallinput,notjustthatfromvirtualcontrols.Forexample,supposeyoumaptheapplication-definedactioneB_UPSHIFTtoboththeDIBUTTON_DRIVINGR_SHIFTUPvirtualcontrolandtothePageUpkey.Whenretrievingdata,yougetbackeB_UPSHIFTwhethertheinputcamefromajoystickbuttonorthekeyboard.

Thefollowingexampledeclaresanactionmapforthecar-racinggame.

DIACTIONrgActions[]=

{

//Genre-definedvirtualaxes

{eA_STEER,DIAXIS_DRIVINGR_STEER,0,"Steer",},

{eA_ACCELERATE,DIAXIS_DRIVINGR_ACCELERATE,0,"Accelerate",},

Page 493: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

{eA_BRAKE,DIAXIS_DRIVINGR_BRAKE,0,"Brake",},

//Genre-definedvirtualbuttons

{eB_UPSHIFT,DIBUTTON_DRIVINGR_SHIFTUP,0,"Upshift",},

{eB_DOWNSHIFT,DIBUTTON_DRIVINGR_SHIFTDOWN,0,"DownShift",},

{eB_CYCLEVIEW,DIBUTTON_DRIVINGR_VIEW,0,"ChangeView",},

//Actionsnotdefinedinthegenrethatcanbeassignedtoany

//buttonoraxis

{eA_VOLUME,DIAXIS_ANY_1,0,"Volume",},

{eB_MUTE,DIBUTTON_ANY(0),0,"ToggleSound",},

//Actionsnotdefinedinthegenrethatmustbeassignedto

//particularkeys

{eB_DRIVERVIEW,DIKEYBOARD_1,0,"DriverView",},

{eB_COURSEVIEW,DIKEYBOARD_C,0,"CourseView",},

{eB_BRAKEBIAS,DIKEYBOARD_B,0,"BrakeBias",},

//Actionsmappedtokeysaswellastovirtualcontrols

{eB_UPSHIFT,DIKEYBOARD_PRIOR,0,"Upshift",},

{eB_DOWNSHIFT,DIKEYBOARD_NEXT,0,"Downshift",},

{eB_STEER_LEFT,DIKEYBOARD_LEFT,0,"SteerLeft",},

{eB_STEER_RIGHT,DIKEYBOARD_RIGHT,0,"SteerRight",},

{eB_ACCELERATE,DIKEYBOARD_UP,0,"Accelerate",},

{eB_DECELERATE,DIKEYBOARD_DOWN,0,"Decelerate",},

{eB_BRAKE,DIKEYBOARD_END,0,"Brake",},

//Actionsmappedtobuttonsaswellastovirtualcontrolsandkeys

{eB_UPSHIFT,DIMOUSE_BUTTON0,0,"Upshift",},

{eB_DOWNSHIFT,DIMOUSE_BUTTON1,0,"Downshift",},

};

Intheexample,someactionsaremappedtoactualkeysbyusingKeyboardMappingConstants.SimilarmappingstothemousebuttonsandaxescanbemadebyusingMouseMappingConstants.

TheDIACTIONarrayiscontainedwithinaDIACTIONFORMATstructurethatalsocontainsinformationaboutthegenre,theapplication,andthedesiredscalingofaxisdata.Usethesameinstanceofthisstructurethroughouttheactionmappingprocess.Somememberswillnotbeusedimmediately,butyoucanfillintheentirestructurebeforethenextstep,FindingMatchingDevices.

Page 494: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

FindingMatchingDevices

Afteryoudefinetheapplicationactionsandthevirtualcontrolsordeviceobjectstowhichtheseactionsaretobemapped,thenextstepistoenumeratedevicesonthesystemtofindthosethatbestsupportthedesiredvirtualcontrols.

Todoso,passtheDIACTIONFORMATstructuretoIDirectInput8::EnumDevicesBySemantics.ThismethodworksinmuchthesamewayasIDirectInput8::EnumDevicesandtakesasimilarcallbackfunction.

Devicesthathavebeenconfiguredbytheusertomatchcertaincontrolsarealwaysenumeratedfirst.Forexample,ifauserhasconfiguredawheelastheprimarysteeringdevicefordrivinggames,thenthewheelisenumeratedfirstwheneverdevicesthatsupportDIAXIS_DRIVINGR_STEERarerequested,takingprecedenceoverothercapabledevicessuchasjoysticksthathavenotbeenconfiguredbytheuser.Otherwise,theorderinwhichavailabledevicesareenumeratedisdeterminedbythedegreetowhichtheymatchtherequestedcontrols.However,theorderinwhichdevicesareenumeratedbyMicrosoft®DirectInput®isnotguaranteed.

Intheenumerationcallback,youcanretrievethedefaultactionmappingforeachdevice,changeanymappingsyoudon'tlike,givetheuseranopportunitytoreconfigurethedevice,andapplytheactionmap.ThesestepsarecoveredinConfiguringtheActionMap.FlagsreturnedintheDIEnumDevicesBySemanticsCallbackwillprovideinformationaboutwhyaparticulardevicewasenumerated.Theseflagswillindicatewhetheradevicehasbeenusedrecently,isnewlyinstalled,orwillacceptmappingsofpriority1orpriority2controls.

Page 495: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

ConfiguringtheActionMap

Aseachdeviceisenumerated,youcanobtainapointertoit,retrievethedefaultactionmap,makechangesinthedefaultmap,andapplythefinalmappings.

1.ObtainingtheDevice

ObtaintheIDirectInputDevice8interfacepointerforeachenumerateddevicefromthelpdidparameteroftheenumerationcallback.SeeDIEnumDevicesBySemanticsCallback.Ifyouwanttosavethedeviceinterfaceforuseinyourapplication,callAddRefonthepointerandassignittoaglobalvariable.

2.ObtainingtheDefaultActionMap

Toobtainthedefaultactionmapforthedevice,callIDirectInputDevice8::BuildActionMap.Microsoft®DirectInput®takesthelistofvirtualcontrolsspecifiedinyourDIACTIONFORMATstructureandattemptstomapthesetophysicaldeviceobjects,returningtheresultsinthesamestructure.YoushouldexaminethedwHowmemberofeachDIACTIONelementtodeterminewhetherthecontrolwassuccessfullymapped.Ifitwas,youcanalsoascertainwhatcriterionwasusedinchoosingtheobject—forexample,configurationbytheuserorbythedevicemanufacturer.

3.MakingChangestotheActionMap

Younowhavetheoptionofchangingthedefaultmappings,althoughitisnotrecommendedthatyoudoso.AfterexaminingthedwSemanticmemberoftheDIACTIONstructuretodeterminewhichdeviceobjectwasmappedtoanaction,youcanchangethatvalue.Forexample,ifanactionismappedtoDIJOFS_BUTTON9,butyouwantthatactiontobemappedtothetriggerbuttoninstead,changethevaluetoDIJOFS_BUTTON0beforeapplyingtheactionmap.

Page 496: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

4.ApplyingtheActionMap

WhenyouaresatisfiedthattheDIACTIONFORMATstructurecontainssuitablemappingsforthedevice,callIDirectInputDevice8::SetActionMap.ThevalueyouassignedtotheuAppDatamemberofeachDIACTIONstructurenowbecomesboundtothecontrolspecifiedinthedwSemanticmember,whichinturnisboundtoaparticulardeviceobject.

5.MappingMorethanOneDevice

Repeatsteps1though4foreachdeviceyouwanttouseinyourapplication.Supposeyouwanttomapactionstobothajoystickandthekeyboard.Intheracing-gameexample,theactiondefinedinthegameaseB_DRIVERVIEWwasmappedtoakeyboardkeyinthefollowingelementoftheDIACTIONarray.

{eB_DRIVERVIEW,DIKEYBOARD_1,"DriverView",},

Inthatexample,whenBuildActionMapiscalledonanydevicethatisnotakeyboard,thelHowmemberoftheDIACTIONstructureforthatelementissettoDIAH_UNMAPPED.ContinueexaminingthelHowmemberaseachdeviceinturnisenumerated,untilavalueotherthanDIAH_UNMAPPEDisreturned.Thisindicatesthatthedevicebeingcurrentlymappedisakeyboardandtheactionhasbeensuccessfullymappedtotherequestedkey.

Evenactionsthathavebeensuccessfullymappedcanbemappedtoanotherdevice.Intheexample,eB_UPSHIFTisgiventwoDIACTIONstructures,asfollows:

{eB_UPSHIFT,DIBUTTON_DRIVINGR_SHIFTUP,0,"Upshift",},

...

{eB_UPSHIFT,DIKEYBOARD_PRIOR,0,"Upshift",},

Asdevicesaresuccessivelyenumerated,theeB_UPSHIFTactionismappedtoasuitablebuttonononeormorejoysticksorothergamecontrollers,andthenagaintothekeyboard.

6.DisplayingtheConfiguration

Toshowtheuserhowactionshavebeenmappedtodevices,passthe

Page 497: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DICD_DEFAULTflagtoIDirectInput8::ConfigureDevices.Thepropertysheetforthedevice,containingagraphicalrepresentationofmappings,isdisplayedinview-onlymodeasinthefollowingdiagram.Formoreinformationonthemechanicsofdisplayingtheimage,refertotheUsingActionMappingtutorial.

Ifthedevicemanufacturerhasnotprovidedadeviceimage,themappingwillbepresentedintextmodeasinthefollowingdiagram.

NoteEvenifthecooperativelevelfortheapplicationisdisablingtheMicrosoft®Windows®logokeypassivelythroughanexclusivecooperativeleveloractivelythroughuseoftheDISCL_NOWINKEYflag,thatkeywillbeactivewhilethedefaultactionmappingUIisdisplayed.

Formoreinformationaboutthispropertysheet,seeUserConfigurationoftheDevice.

Page 498: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

UserConfigurationoftheDevice

Microsoft®DirectInput®providesapropertysheetthatcanbecalledfromanapplication,enablingtheusertoconfiguredevicesfortheapplicationandviewthecurrentconfiguration.Thispropertysheetcandisplayvariousviewsofthedeviceasprovidedbythemanufacturer.

Toenableuserconfiguration,passaDICONFIGUREDEVICESPARAMSstructurecontainingapointertotheDIACTIONFORMATstructuredescribingthedesiredmapping,alongwiththeDICD_EDITflag,totheIDirectInput8::ConfigureDevicesmethod.NormallyyouwoulddothisaftercallingIDirectInputDevice8::BuildActionMaponalldevicesthatwillbeusedintheapplication.

Thefollowingillustrationshowsatypicalpropertysheetineditmode.

Ifthedevicemanufacturerhasnotprovidedadeviceimage,themappingwillbepresentedintextmodeasinthefollowingdiagram.

NoteEvenifthecooperativelevelfortheapplicationisdisablingtheMicrosoft®Windows®logokeypassivelythroughanexclusivecooperativeleveloractivelythroughuseoftheDISCL_NOWINKEYflag,thatkeywillbeactivewhilethedefaultactionmappingUIisdisplayed.

ThepropertypageforadeviceliststhefriendlynamesthatwereprovidedbyyouinthelptszActionNamememberofeachDIACTIONstructure.IfyouhavealreadycalledBuildActionMapforadevice,thepagealsoshowsthesenamesascalloutsontheimageofthedevice,withlinespointingtothedeviceobjectstowhichtheactionshavebeenmapped.

Theusernowhastheopportunitytoreassigngameactionsbyfirstchoosingacontrolthenchoosinganactionfromthemenu.Whentheuserclosesthe

Page 499: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

propertysheet,themethodreturnsandthemodificationsarestoredintheDIACTIONFORMATstructurethatyoupassedin.YoucannowpassthesamestructuretoIDirectInputDevice8::SetActionMapinordertoimplementthenewmappingscheme.

Page 500: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

RetrievingActionData

Youretrievebuffereddatafromaction-mappeddevicesjustasyouwouldfromunmappeddevices:bycallingIDirectInputDevice8::GetDeviceData.However,insteadofidentifyingdeviceobjectsbyexaminingthedwOfsmemberoftheDIDEVICEOBJECTDATAstructure,youobtaintheactionassociatedwiththeobjectfromtheuAppDatamember.ThisisthesamevalueyoupassedtothedeviceintheDIACTIONstructure.Itcanbeasimpleidentifierorapointertoafunctiondesignedtohandletheaction.

Rememberthatanactioncanbeassociatedwithmorethanonedevice.Youstillhavetoobtaindatafrombothdevicesindependently,butyoucanusethesameroutinetohandlethedataregardlessofwhereitcomesfrom.

Thefollowingsamplecode,whichmightbepartofthegameloopinadrivingsimulation,retrievesdatafromalldevicesintheg_lpIdiDevicesarray.Thisarraycontainsg_nDeviceselements.

for(intiDevice=0x0;iDevice<g_nDevices;iDevice++)

{

DIDEVICEOBJECTDATAdidod;

DWORDdwObjCount=1;

//Pollthedevicefordata.

g_lpDiDevices[iDevice]->Poll();

//Retrievethedata.

g_lpDiDevices[iDevice]->GetDeviceData(sizeof(didod),

&didod,

&dwObjCount,0);

//Handletheactionsregardlessofwhatdevicereturnedthem.

switch(didod.uAppData)

{

caseeA_STEER:

SteerCar(didod.dwData);

break;

caseeB_UPSHIFT

if(didod.dwData&0x80)ShiftGears(UPSHIFT);

break;

Page 501: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

.

.

.

default:

break;

}

}

NoteAxisconstantsforspecificgenres,suchasDIAXIS_DRIVINGR_STEERorDIAXIS_SPACESIM_LATERAL,areusedforabsolutejoystickdata.Theactionmapperattemptstomapthisvirtualcontroltoadeviceobjectthatreturnsabsolutedata.Thedatareturnedfromthatdeviceshouldbeprocessedaccordinglyintheapplication.DeviceconstantssuchasDIMOUSE_XAXIS,however,areexpectedtoreturnrelativedata.

Whenretrievingdata,eachpotentialsourceofdatashouldbeprocessedseparatelytokeeponedeviceobjectfrompossiblyoverwritingthedatafromanother.Forinstance,thefollowingDIACTIONstructuresareusedinanactionmaptocontroldirection.

{INPUT_LEFTRIGHT_ABS_AXIS,DIAXIS_SPACESIM_LATERAL,0,_T("Turn"),},

{INPUT_LEFTRIGHT_REL_AXIS,DIMOUSE_XAXIS,0,_T("Turn"),},

{INPUT_TURNLEFT,DIKEYBOARD_LEFT,0,_T("Turnleft"),},

{INPUT_TURNRIGHT,DIKEYBOARD_RIGHT,0,_T("Turnright"),},

Theapplication'sinputloopprocessesdatafromtheseactionsinthefollowingcasestatement.

switch(adod[j].uAppData)

{

caseINPUT_LEFTRIGHT_ABS_AXIS:

g_dwAbsLR=adod[j].dwData

break;

caseINPUT_LEFTRIGHT_REL_AXIS:

g_dwRelLR=adod[j].dwData;

break;

caseINPUT_TURNLEFT:

g_bLeft=(adod[j].dwData!=0);

break;

caseINPUT_TURNRIGHT:

g_bRight=(adod[j].dwData!=0)

break;

}

Page 502: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Notethateachdatasourceisassignedtoaseparatevariableratherthanalldatasourcesbeingassignedageneric"turn"variable.Iftheyweretoshareagenericvariable,holdingdowntheLEFTARROWkeyandthenmovingthejoystickwouldcausethekeyboardinformationtobelost.Thisisbecausethejoystickdatawouldoverwritethevariable.

Inadditiontoindividualvariables,therearemanywaystoprocessthedata.Whatevermethodisused,careshouldbetakenintheprocessingofdatatoavoidunexpectedlylostinformation.

Page 503: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

MaintainingFilesDuringDevelopment

Duringadevelopmentcycle,unusedandoutofdate.inifilesmayaccumulateduetofrequentactionmapchanges,Microsoft®DirectX®reinstallations,multipleusers,andothernormaldevelopmentsituations.Thesefilescouldpossiblycauseunexpectedmappingsorreportsof"recent"(DIEDBS_RECENTDEVICE)fordevicesthatwouldnotbeexpectedtoreturnthatvalue.Forthisreason,itisgoodpracticetooccasionallydeleteanyunused.inifiles.ThesefilescanbefoundinC:\ProgramFiles\CommonFiles\DirectX\DirectInput\UserMaps.

NoteTheproceduresuggestedaboveismeanttobeperformedonlymanuallyduringadevelopmentcycletoensurethatthedevelopmentenvironmentisinacleanerstate.Ashippingapplicationshouldneverdeleteusermapsasthiscouldresultinthelossofauser'spreferredsettings.

Page 504: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 505: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8::ConfigureDevicesDisplayspropertypagesforconnectedinputdevicesandenablestheusertomapactionstodevicecontrols.

HRESULTIDirectInput8::ConfigureDevices(

LPDICONFIGUREDEVICESCALLBACKlpdiCallback,

LPDICONFIGUREDEVICESPARAMSlpdiCDParams,

DWORDdwFlags,

LPVOIDpvRefData

);

Parameters

lpdiCallbackAddressofacallbackfunctiontobecalledeachtimethecontentsofthesurfacechange.SeeDIConfigureDevicesCallback.PassNULLiftheapplicationdoesnothandlethedisplayofthepropertysheet.Inthiscase,Microsoft®DirectInput®displaysthepropertysheetandreturnscontroltotheapplicationwhentheuserclosesthepropertysheet.Ifyousupplyacallbackpointer,youmustalsosupplyavalidsurfacepointerinthelpUnkDDSTargetmemberoftheDICONFIGUREDEVICESPARAMSstructure.

lpdiCDParamsAddressofaDICONFIGUREDEVICESPARAMSstructurethatcontainsinformationaboutusersandgenresforthegame,aswellasinformationabouthowtheuserinterfaceisdisplayed.

dwFlagsDWORDvaluethatspecifiesthemodeinwhichthecontrolpanelshouldbeinvoked.DwFlagsmustbeoneofthefollowingvalues.DICD_DEFAULT

Openthepropertysheetinview-onlymode.DICD_EDIT

Openthepropertysheetineditmode.Thismodeenablestheusertochangeaction-to-controlmappings.Afterthecallreturns,theapplicationshouldassumecurrentdevicesarenolongervalid,releasealldeviceinterfaces,andreinitializethembycalling

Page 506: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8::EnumDevicesBySemantics.pvRefData

Application-definedvaluetopasstothecallbackfunction.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisDI_OK.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowing.

DIERR_INVALIDPARAMDIERR_OUTOFMEMORY

Remarks

Hardwarevendorsprovidebitmapsandotherdisplayinformationfortheirdevice.

Beforecallingthemethod,anapplicationcanmodifythetextlabelsassociatedwitheachactionbychangingthevalueinthelptszActionNamememberoftheDIACTIONstructure.

Configurationisstoredforeachuserofeachdeviceforeachgame.TheinformationcanberetrievedbytheIDirectInputDevice8::BuildActionMapmethod.

Bydefault,accelerationissupportedforthesepixelformats:

A1R5G5B516-bitpixelformatwith5bitsreservedforeachcolorand1bitreservedforalpha(transparenttexel).

A8R8G8B832-bitARGBpixelformatwithalpha.

R9G8B824-bitRGBpixelformat.

X1R5G5B516-bitpixelformatwith5bitsreservedforeachcolor.

X8R8G8B8

Page 507: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

32-bitRGBpixelformatwith8bitsreservedforeachcolor.

Otherformatswillresultincolorconversionanddramaticallyslowtheframerate.

NoteEvenifthecooperativelevelfortheapplicationisdisablingtheMicrosoftWindows®logokeypassivelythroughanexclusivecooperativeleveloractivelythroughuseoftheDISCL_NOWINKEYflag,thatkeywillbeactivewhilethedefaultactionmappingUIisdisplayed.

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

Page 508: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 509: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8::CreateDeviceCreatesandinitializesaninstanceofadevicebasedonagivenGUID,andobtainsanIDirectInputDevice8interface.

HRESULTCreateDevice(

REFGUIDrguid,

LPDIRECTINPUTDEVICE*lplpDirectInputDevice,

LPUNKNOWNpUnkOuter

);

Parameters

rguidReferenceto(C++)oraddressof(C)theinstanceGUIDforthedesiredinputdevice(seeRemarks).TheGUIDisretrievedthroughtheIDirectInput8::EnumDevicesmethod,oritcanbeoneofthefollowingpredefinedGUIDs:GUID_SysKeyboard

Thedefaultsystemkeyboard.GUID_SysMouse

Thedefaultsystemmouse.

FortheprecedingGUIDvaluestobevalid,yourapplicationmustdefineINITGUIDbeforeallotherpreprocessordirectivesatthebeginningofthesourcefile,orlinktoDxguid.lib.

lplpDirectInputDeviceAddressofavariabletoreceivetheIDirectInputDevice8interfacepointerifsuccessful.

pUnkOuterAddressofthecontrollingobject'sIUnknowninterfaceforCOMaggregation,orNULLiftheinterfaceisnotaggregated.MostcallerspassNULL.

ReturnValues

Page 510: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Ifthemethodsucceeds,thereturnvalueisDI_OK.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowing:

DIERR_DEVICENOTREGDIERR_INVALIDPARAMDIERR_NOINTERFACEDIERR_NOTINITIALIZEDDIERR_OUTOFMEMORY

Remarks

CallingthismethodwithpUnkOuter=NULLisequivalenttocreatingtheobjectbyCoCreateInstance(&CLSID_DirectInputDevice,NULL,CLSCTX_INPROC_SERVER,riid,lplpDirectInputDevice)andtheninitializingitwithInitialize.

CallingthismethodwithpUnkOuter!=NULLisequivalenttocreatingtheobjectbyCoCreateInstance(&CLSID_DirectInputDevice,punkOuter,CLSCTX_INPROC_SERVER,&IID_IUnknown,lplpDirectInputDevice).Theaggregatedobjectmustbeinitializedmanually.

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

Page 511: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 512: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8::EnumDevicesEnumeratesavailabledevices.

HRESULTEnumDevices(

DWORDdwDevType,

LPDIENUMDEVICESCALLBACKlpCallback,

LPVOIDpvRef,

DWORDdwFlags

);

Parameters

dwDevTypeDevicetypefilter.

Torestricttheenumerationtoaparticulartypeofdevice,setthisparametertoaDI8DEVTYPE_*value.SeeDIDEVICEINSTANCE.

Toenumerateaclassofdevices,useoneofthefollowingvalues.

DI8DEVCLASS_ALLAlldevices.

DI8DEVCLASS_DEVICEAlldevicesthatdonotfallintoanotherclass.

DI8DEVCLASS_GAMECTRLAllgamecontrollers.

DI8DEVCLASS_KEYBOARDAllkeyboards.EquivalenttoDI8DEVTYPE_KEYBOARD.

DI8DEVCLASS_POINTERAlldevicesoftypeDI8DEVTYPE_MOUSEandDI8DEVTYPE_SCREENPOINTER.

lpCallbackAddressofacallbackfunctiontobecalledonceforeachdeviceenumerated.SeeDIEnumDevicesCallback.

pvRefApplication-defined32-bitvaluetobepassedtotheenumerationcallback

Page 513: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

eachtimeitiscalled.dwFlags

Flagvaluethatspecifiesthescopeoftheenumeration.Thisparametercanbeoneormoreofthefollowingvalues:DIEDFL_ALLDEVICES

Allinstalleddevicesareenumerated.Thisisthedefaultbehavior.DIEDFL_ATTACHEDONLY

Onlyattachedandinstalleddevices.DIEDFL_FORCEFEEDBACK

Onlydevicesthatsupportforcefeedback.DIEDFL_INCLUDEALIASES

Includedevicesthatarealiasesforotherdevices.DIEDFL_INCLUDEHIDDEN

Includehiddendevices.Formoreinformationabouthiddendevices,seeDIDEVCAPS.

DIEDFL_INCLUDEPHANTOMSIncludephantom(placeholder)devices.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisDI_OK.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowingerrorvalues:

DIERR_INVALIDPARAMDIERR_NOTINITIALIZED

Remarks

Allinstalleddevicescanbeenumerated,eveniftheyarenotpresent.Forexample,aflightstickmightbeinstalledonthesystembutnotcurrentlypluggedintothecomputer.SetthedwFlagsparametertoindicatewhetheronlyattachedorallinstalleddevicesshouldbeenumerated.IftheDIEDFL_ATTACHEDONLYflagisnotpresent,allinstalleddevicesareenumerated.

ApreferreddevicetypecanbepassedasadwDevTypefiltersothatonlythedevicesofthattypeareenumerated.

Page 514: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

NoteTheorderinwhichdevicesareenumeratedbyDirectInputisnotguaranteed.

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

SeeAlso

IDirectInput8::EnumDevicesBySemantics

Page 515: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 516: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8::EnumDevicesBySemanticsEnumeratesdevicesthatmostcloselymatchtheapplication-specifiedactionmap.

HRESULTEnumDevicesBySemantics(

LPCTSTRptszUserName,

LPDIACTIONFORMATlpdiActionFormat,

LPDIENUMDEVICESBYSEMANTICSCBlpCallback,

LPVOIDpvRef,

DWORDdwFlags

);

Parameters

ptszUserNameStringidentifyingthecurrentuser,orNULLtospecifytheuserloggedontothesystem.Theusernameistakenintoaccountwhenenumeratingdevices.Adevicewithusermappingsispreferredtoadevicewithoutanyusermappings.Bydefault,devicesinusebyotherusersarenotenumeratedforthisuser.

lpdiActionFormatAddressofaDIACTIONFORMATstructurethatspecifiestheactionmapforwhichsuitabledevicesareenumerated.

lpCallbackAddressofacallbackfunctiontobecalledonceforeachdeviceenumerated.SeeDIEnumDevicesBySemanticsCallback.

pvRefApplication-defined32-bitvaluetopasstotheenumerationcallbackeachtimeitiscalled.

dwFlagsFlagvaluethatspecifiesthescopeoftheenumeration.Thisparametercanbeoneormoreofthefollowingvalues.DIEDBSFL_ATTACHEDONLY

Onlyattachedandinstalleddevicesareenumerated.DIEDBSFL_AVAILABLEDEVICES

Onlyunowned,installeddevicesareenumerated.DIEDBSFL_FORCEFEEDBACK

Page 517: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Onlydevicesthatsupportforcefeedbackareenumerated.DIEDBSFL_MULTIMICEKEYBOARDS

Onlysecondary(non-system)keyboardandmousedevices.DIEDBSFL_NONGAMINGDEVICES

OnlyHID-compliantdeviceswhoseprimarypurposeisnotasagamingdevice.DevicessuchasUSBspeakersandmultimediabuttonsonsomekeyboardswouldfallwithinthisvalue.

DIEDBSFL_THISUSERAllinstalleddevicesfortheuseridentifiedbyptszUserName,andallunowneddevices,areenumerated.

DIEDBSFL_VALIDisalsodefinedinDinput.h,butisnotusedbyapplications.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisDI_OK.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowingerrorvalues.

DIERR_INVALIDPARAMDIERR_NOTINITIALIZED

Remarks

Thekeyboardandmouseareenumeratedlast.

NoteTheorderinwhichdevicesareenumeratedbyDirectInputisnotguaranteed.

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

SeeAlso

Page 518: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8::EnumDevices,ActionMapping.

Page 519: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 520: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8::FindDeviceRetrievestheinstanceGUIDofadevicethathasbeennewlyattachedtothesystem.ItiscalledinresponsetoaMicrosoft®Win32®devicemanagementnotification.

HRESULTFindDevice(

REFGUIDrguidClass,

LPCTSTRptszName,

LPGUIDpguidInstance

);

Parameters

rguidClassUniqueidentifierofthedeviceclassforthedevicethattheapplicationistolocate.TheapplicationobtainstheclassGUIDfromthedevicearrivalnotification.Formoreinformation,seethedocumentationontheDBT_DEVICEARRIVALeventintheMicrosoftPlatformSoftwareDevelopmentKit(SDK).

ptszNameNameofthedevice.Theapplicationobtainsthenamefromthedevicearrivalnotification.

pguidInstanceAddressofavariabletoreceivetheinstanceGUIDforthedevice,ifthedeviceisfound.ThisvaluecanbepassedtoIDirectInput8::CreateDevice.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisDI_OK.

Ifthemethodfails,thereturnvaluecanbeDIERR_DEVICENOTREG.FailureresultsiftheGUIDandnamedonotcorrespondtoadeviceclassthatisregisteredwithMicrosoft®DirectInput®.Forexample,theymightrefertoastoragedevice,ratherthananinputdevice.

Requirements

Page 521: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

Page 522: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 523: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8::GetDeviceStatusRetrievesthestatusofaspecifieddevice.

HRESULTGetDeviceStatus(

REFGUIDrguidInstance

);

Parameters

rguidInstanceReferenceto(C++)oraddressof(C)theGUIDidentifyingtheinstanceofthedevicewhosestatusisbeingchecked.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisDI_OKifthedeviceisattachedtothesystem,orDI_NOTATTACHEDotherwise.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowingerrorvalues:

DIERR_GENERICDIERR_INVALIDPARAMDIERR_NOTINITIALIZED

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

Page 524: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 525: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8::InitializeInitializesaMicrosoft®DirectInput®object.Applicationsnormallydonotneedtocallthismethod.TheDirectInput8CreatefunctionautomaticallyinitializestheDirectInputobjectaftercreatingit.

HRESULTInitialize(

HINSTANCEhinst,

DWORDdwVersion

);

Parameters

hinstInstancehandletotheapplicationordynamic-linklibrary(DLL)thatiscreatingtheDirectInputobject.DirectInputusesthisvaluetodeterminewhethertheapplicationorDLLhasbeencertifiedandtoestablishanyspecialbehaviorsthatmightbenecessaryforbackwardscompatibility.

ItisanerrorforaDLLtopassthehandleoftheparentapplication.Forexample,aMicrosoftActiveX®controlembeddedinaWebpagethatusesDirectInputmustpassitsowninstancehandle,andnotthehandleoftheWebbrowser.ThisensuresthatDirectInputrecognizesthecontrolandcanenableanyspecialbehaviorsthatmightbenecessary.

dwVersionVersionnumberofDirectInputforwhichtheapplicationisdesigned.ThisvalueisnormallyDIRECTINPUT_VERSION.PassingtheversionnumberofapreviousversioncausesDirectInputtoemulatethatversion.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisDI_OK.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowingerrorvalues:

DIERR_BETADIRECTINPUTVERSION

Page 526: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DIERR_OLDDIRECTINPUTVERSION

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

Page 527: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 528: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInput8::RunControlPanelRunsControlPaneltoenabletheusertoinstallanewinputdeviceormodifyconfigurations.

HRESULTRunControlPanel(

HWNDhwndOwner,

DWORDdwFlags

);

Parameters

hwndOwnerHandleofthewindowtobeusedastheparentwindowforthesubsequentuserinterface.IfthisparameterisNULL,noparentwindowisused.

dwFlagsCurrentlynotusedandmustbesetto0.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisDI_OK.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowingerrorvalues:

DIERR_INVALIDPARAMDIERR_NOTINITIALIZED

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

SeeAlso

Page 529: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInputDevice8::RunControlPanel

Page 530: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 531: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IUnknown::AddRefIncreasesthereferencecountoftheobjectby1.

ULONGAddRef();

Parameters

Therearenoparameters.

ReturnValues

Returnsthenewreferencecount.Thisvalueisfordiagnosticandtestingpurposesonly.

Remarks

Whentheobjectiscreated,itsreferencecountissetto1.EverytimeanapplicationobtainsaninterfacetotheobjectorcallstheAddRefmethod,theobject'sreferencecountisincreasedby1.UsetheReleasemethodtodecreasetheobject'sreferencecountby1.

Requirements

WindowsNT/2000/XP:RequiresWindowsNT3.1orlater.Windows98/Me:RequiresWindows98orlater.Header:DeclaredinUnknwn.h.

Page 532: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 533: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IUnknown::QueryInterfaceDetermineswhethertheobjectsupportsaparticularCOMinterface.Ifitdoes,thesystemincreasestheobject'sreferencecount,andtheapplicationcanusethatinterfaceimmediately.

HRESULTQueryInterface(

REFIIDriid,

LPVOID*ppvObj

);

Parameters

riidReferenceidentifieroftheinterfacebeingrequested.

ppvObjAddressofapointertofillwiththeinterfacepointerifthequerysucceeds.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisS_OK.

Ifthemethodfails,thereturnvaluemaybeE_NOINTERFACEorE_POINTER.Somecomponentsalsohavetheirowndefinitionsoftheseerrorvaluesintheirheaderfiles.InMicrosoft®DirectInput®,forexample,DIERR_NOINTERFACEisequivalenttoE_NOINTERFACE.

Remarks

Iftheapplicationdoesnotneedtousetheinterfaceretrievedbyacalltothismethod,itmustcalltheReleasemethodforthatinterfacetofreeit.TheQueryInterfacemethodenablesMicrosoftandthirdpartiestoextendobjectswithoutinterferingwithexistingorevolvingfunctionality.

Requirements

Page 534: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

WindowsNT/2000/XP:RequiresWindowsNT3.1orlater.Windows98/Me:RequiresWindows98orlater.Header:DeclaredinUnknwn.h.

Page 535: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 536: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IUnknown::ReleaseDecreasesthereferencecountoftheobjectby1.

ULONGRelease();

Parameters

Therearenoparameters.

ReturnValues

Returnsthenewreferencecount.Thisvalueisfordiagnosticandtestingpurposesonly.

Remarks

Theobjectdeallocatesitselfwhenitsreferencecountreaches0.UsetheAddRefmethodtoincreasetheobject'sreferencecountby1.

ApplicationsmustcallthismethodtoreleaseonlyinterfacesthatthemethodexplicitlycreatedinapreviouscalltoIUnknown::AddRef,IUnknown::QueryInterface,oracreationfunctionsuchasDirect3DCreate8.

Requirements

WindowsNT/2000/XP:RequiresWindowsNT3.1orlater.Windows98/Me:RequiresWindows98orlater.Header:DeclaredinUnknwn.h.

Page 537: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

ReturnValues

ThelistbelowcontainstheHRESULTvaluesthatcanbereturnedbyMicrosoft®DirectInput®methodsandfunctions.Errorsarerepresentedbynegativevaluesandcannotbecombined.

Foralistoftheerrorvalueseachmethodorfunctioncanreturn,seetheindividualdescriptions.Listsoferrorcodesinthedocumentationarenecessarilyincomplete.Forexample,anyDirectInputmethodcanreturnDIERR_OUTOFMEMORYeventhoughtheerrorcodeisnotexplicitlylistedasapossiblereturnvalueinthedocumentationforthatmethod.

DI_BUFFEROVERFLOWThedevicebufferoverflowedandsomeinputwaslost.ThisvalueisequaltotheS_FALSEstandardCOMreturnvalue.

DI_DOWNLOADSKIPPEDTheparametersoftheeffectweresuccessfullyupdated,buttheeffectcouldnotbedownloadedbecausetheassociateddevicewasnotacquiredinexclusivemode.

DI_EFFECTRESTARTEDTheeffectwasstopped,theparameterswereupdated,andtheeffectwasrestarted.

DI_NOEFFECTTheoperationhadnoeffect.ThisvalueisequaltotheS_FALSEstandardCOMreturnvalue.

DI_NOTATTACHEDThedeviceexistsbutisnotcurrentlyattached.ThisvalueisequaltotheS_FALSEstandardCOMreturnvalue.

DI_OKTheoperationcompletedsuccessfully.ThisvalueisequaltotheS_OKstandardCOMreturnvalue.

DI_POLLEDDEVICEThedeviceisapolleddevice.Asaresult,devicebufferingdoesnotcollectanydataandeventnotificationsisnotsignaleduntiltheIDirectInputDevice8::Pollmethodiscalled.

Page 538: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DI_PROPNOEFFECTThechangeindevicepropertieshadnoeffect.ThisvalueisequaltotheS_FALSEstandardCOMreturnvalue.

DI_SETTINGSNOTSAVEDTheactionmapwasappliedtothedevice,butthesettingscouldnotbesaved.

DI_TRUNCATEDTheparametersoftheeffectweresuccessfullyupdated,butsomeofthemwerebeyondthecapabilitiesofthedeviceandweretruncatedtothenearestsupportedvalue.

DI_TRUNCATEDANDRESTARTEDEqualtoDI_EFFECTRESTARTED|DI_TRUNCATED.

DI_WRITEPROTECTASUCCESScodeindicatingthatsettingscannotbemodified.

DIERR_ACQUIREDTheoperationcannotbeperformedwhilethedeviceisacquired.

DIERR_ALREADYINITIALIZEDThisobjectisalreadyinitialized

DIERR_BADDRIVERVERTheobjectcouldnotbecreatedduetoanincompatibledriverversionormismatchedorincompletedrivercomponents.

DIERR_BETADIRECTINPUTVERSIONTheapplicationwaswrittenforanunsupportedprereleaseversionofDirectInput.

DIERR_DEVICEFULLThedeviceisfull.

DIERR_DEVICENOTREGThedeviceordeviceinstanceisnotregisteredwithDirectInput.ThisvalueisequaltotheREGDB_E_CLASSNOTREGstandardCOMreturnvalue.

DIERR_EFFECTPLAYINGTheparameterswereupdatedinmemorybutwerenotdownloadedtothedevicebecausethedevicedoesnotsupportupdatinganeffectwhileitisstillplaying.

DIERR_GENERICAnundeterminederroroccurredinsidetheDirectInputsubsystem.ThisvalueisequaltotheE_FAILstandardCOMreturnvalue.

DIERR_HANDLEEXISTSThedevicealreadyhasaneventnotificationassociatedwithit.ThisvalueisequaltotheE_ACCESSDENIEDstandardCOMreturnvalue.

Page 539: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DIERR_HASEFFECTSThedevicecannotbereinitializedbecauseeffectsareattachedtoit.

DIERR_INCOMPLETEEFFECTTheeffectcouldnotbedownloadedbecauseessentialinformationismissing.Forexample,noaxeshavebeenassociatedwiththeeffect,ornotype-specificinformationhasbeensupplied.

DIERR_INPUTLOSTAccesstotheinputdevicehasbeenlost.Itmustbereacquired.

DIERR_INVALIDPARAMAninvalidparameterwaspassedtothereturningfunction,ortheobjectwasnotinastatethatpermittedthefunctiontobecalled.ThisvalueisequaltotheE_INVALIDARGstandardCOMreturnvalue.

DIERR_MAPFILEFAILAnerrorhasoccurredeitherreadingthevendor-suppliedaction-mappingfileforthedeviceorreadingorwritingtheuserconfigurationmappingfileforthedevice.

DIERR_MOREDATANotalltherequestedinformationfitintothebuffer.

DIERR_NOAGGREGATIONThisobjectdoesnotsupportaggregation.

DIERR_NOINTERFACETheobjectdoesnotsupportthespecifiedinterface.ThisvalueisequaltotheE_NOINTERFACEstandardCOMreturnvalue.

DIERR_NOTACQUIREDTheoperationcannotbeperformedunlessthedeviceisacquired.

DIERR_NOTBUFFEREDThedeviceisnotbuffered.SettheDIPROP_BUFFERSIZEpropertytoenablebuffering.

DIERR_NOTDOWNLOADEDTheeffectisnotdownloaded.

DIERR_NOTEXCLUSIVEACQUIREDTheoperationcannotbeperformedunlessthedeviceisacquiredinDISCL_EXCLUSIVEmode.

DIERR_NOTFOUNDTherequestedobjectdoesnotexist.

DIERR_NOTINITIALIZEDThisobjecthasnotbeeninitialized.

DIERR_OBJECTNOTFOUNDTherequestedobjectdoesnotexist.

Page 540: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

DIERR_OLDDIRECTINPUTVERSIONTheapplicationrequiresanewerversionofDirectInput.

DIERR_OTHERAPPHASPRIOAnotherapplicationhasahigherprioritylevel,preventingthiscallfromsucceeding.ThisvalueisequaltotheE_ACCESSDENIEDstandardCOMreturnvalue.Thiserrorcanbereturnedwhenanapplicationhasonlyforegroundaccesstoadevicebutisattemptingtoacquirethedevicewhileinthebackground.

DIERR_OUTOFMEMORYTheDirectInputsubsystemcouldnotallocatesufficientmemorytocompletethecall.ThisvalueisequaltotheE_OUTOFMEMORYstandardCOMreturnvalue.

DIERR_READONLYThespecifiedpropertycannotbechanged.ThisvalueisequaltotheE_ACCESSDENIEDstandardCOMreturnvalue.

DIERR_REPORTFULLMoreinformationwasrequestedtobesentthancanbesenttothedevice.

DIERR_UNPLUGGEDTheoperationcouldnotbecompletedbecausethedeviceisnotpluggedin.

DIERR_UNSUPPORTEDThefunctioncalledisnotsupportedatthistime.ThisvalueisequaltotheE_NOTIMPLstandardCOMreturnvalue.

E_HANDLETheHWNDparameterisnotavalidtop-levelwindowthatbelongstotheprocess.

E_PENDINGDataisnotyetavailable.

E_POINTERAninvalidpointer,usuallyNULL,waspassedasaparameter.

Page 541: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 542: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInputDevice8::GetDeviceStateRetrievesimmediatedatafromthedevice.

HRESULTGetDeviceState(

DWORDcbData,

LPVOIDlpvData

);

Parameters

cbDataSizeofthebufferinthelpvDataparameter,inbytes.

lpvDataAddressofastructurethatreceivesthecurrentstateofthedevice.TheformatofthedataisestablishedbyapriorcalltotheIDirectInputDevice8::SetDataFormatmethod.

ReturnValues

Ifthemethodsucceeds,thereturnvalueisDI_OK.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowingerrorvalues:

DIERR_INPUTLOSTDIERR_INVALIDPARAMDIERR_NOTACQUIREDDIERR_NOTINITIALIZEDE_PENDING

Remarks

Beforedevicedatacanbeobtained,setthecooperativelevelbyusingtheIDirectInputDevice8::SetCooperativeLevelmethod,thensetthedataformatbyusingIDirectInputDevice8::SetDataFormat,andacquirethedevicebyusingtheIDirectInputDevice8::Acquiremethod.

Page 543: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Thefivepredefineddataformatsrequirecorrespondingdevicestatestructuresaccordingtothefollowingtable:

Dataformat Statestructurec_dfDIMouse DIMOUSESTATEc_dfDIMouse2 DIMOUSESTATE2c_dfDIKeyboard arrayof256bytesc_dfDIJoystick DIJOYSTATEc_dfDIJoystick2 DIJOYSTATE2

Forexample,ifyoupassedthec_dfDIMouseformattotheIDirectInputDevice8::SetDataFormatmethod,youmustpassaDIMOUSESTATEstructuretotheIDirectInputDevice8::GetDeviceStatemethod.

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

SeeAlso

IDirectInputDevice8::Poll,PollingandEventNotification,BufferedandImmediateData

Page 544: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 545: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInputDevice8::GetObjectInfoRetrievesinformationaboutadeviceobject,suchasabuttonoraxis.

HRESULTGetObjectInfo(

LPDIDEVICEOBJECTINSTANCEpdidoi,

DWORDdwObj,

DWORDdwHow

);

Parameters

pdidoiAddressofaDIDEVICEOBJECTINSTANCEstructuretobefilledwithinformationabouttheobject.Thestructure'sdwSizemembermustbeinitializedbeforethismethodiscalled.

dwObjValuethatidentifiestheobjectwhoseinformationistoberetrieved.ThevaluesetforthisparameterdependsonthevaluespecifiedinthedwHowparameter.

dwHowValuethatspecifieshowthedwObjparametershouldbeinterpreted.Thisvaluecanbeoneofthefollowing:Value Meaning

DIPH_BYOFFSETThedwObjparameteristheoffsetintothecurrentdataformatoftheobjectwhoseinformationisbeingaccessed.

DIPH_BYID

ThedwObjparameteristheobjecttype/instanceidentifier.ThisidentifierisreturnedinthedwTypememberoftheDIDEVICEOBJECTINSTANCEstructurereturnedfromapreviouscalltotheIDirectInputDevice8::EnumObjectsmethod.

DIPH_BYUSAGEThedwObjparametercontainstheHIDUsagePageandUsagevaluesoftheobject,combinedbytheDIMAKEUSAGEDWORDmacro.

Page 546: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

ReturnValues

Ifthemethodsucceeds,thereturnvalueisDI_OK.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowingerrorvalues:

DIERR_INVALIDPARAMDIERR_NOTINITIALIZEDDIERR_OBJECTNOTFOUNDE_POINTER

Remarks

ForcompatibilitywithMicrosoft®DirectX®3,itisalsovalidtopassaDIDEVICEOBJECTINSTANCE_DX3structurewiththedwSizememberinitializedtosizeof(DIDEVICEOBJECTINSTANCE_DX3).

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

Page 547: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

MicrosoftDirectX8.1(C++)

Page 548: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

IDirectInputDevice8::SetDataFormatSetsthedataformatfortheMicrosoft®DirectInput®device.

HRESULTSetDataFormat(

LPCDIDATAFORMATlpdf

);

Parameters

lpdfAddressofastructurethatdescribestheformatofthedatathattheDirectInputDeviceshouldreturn.AnapplicationcandefineitsownDIDATAFORMATstructureoruseoneofthefollowingpredefinedglobalvariables:

c_dfDIKeyboardc_dfDIMousec_dfDIMouse2c_dfDIJoystickc_dfDIJoystick2

ReturnValues

Ifthemethodsucceeds,thereturnvalueisDI_OK.

Ifthemethodfails,thereturnvaluecanbeoneofthefollowingerrorvalues:

DIERR_ACQUIREDDIERR_INVALIDPARAMDIERR_NOTINITIALIZED

Remarks

ThedataformatmustbesetbeforethedevicecanbeacquiredbyusingtheIDirectInputDevice8::Acquiremethod.Itisnecessarytosetthedataformatonlyonce.Thedataformatcannotbechangedwhilethedeviceisacquired.

Page 549: Microsoft DirectX 8.1 Common Framework samples in the SDK ... · You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft®

Iftheapplicationisusingactionmapping,thedataformatissetinsteadbythecalltoIDirectInputDevice8::SetActionMap.

Requirements

WindowsNT/2000/XP:RequiresWindows®2000.Windows98/Me:RequiresWindows98orlater.AvailableasaredistributableforWindows98.Header:DeclaredinDinput.h.

SeeAlso

IDirectInputDevice8::GetDeviceState