微软出品简洁色块型PPT.ppt
Building a High Performance 3D Games for Windows PhoneAdam SchaefferMicrosoft CorporationSESSION CODE:WPH308Consistent sets of hardware capabilities defined by MicrosoftWindows Phone 7 HardwareResolutionTouch InputCPU/GPURAMHardware keyboard is The CPUThe Evolution Of ProgrammingLow level controlStraight to the metalRaw performance tuningHigh level abstractionRely on compiler and runtimeDeveloper productivityWhy C#r0 x0rzPowerful and expressiveType safety reduces hard-to-track-down bugsReflectionInitializer syntaxGreat tooling(IntelliSense)Similar enough to C that learning and porting are easyBlazingly fast compilesC#.NET on WindowsUsually within a few percent of native performanceAwesome generational garbage collectionPerformance shootout:Raymond Chen vs.Rico Marianihttp:/ on Xbox 360360Significant delta between managed and native.NET Compact FrameworkSimplistic mark-and-sweep garbage collectionXbox is not a general purpose computerUnforgiving in-order CPU architectureRequires custom VMX instructions for optimal math perfSecurity architecture poses challenges for jitted code.NET on Windows Phone 7In between Windows and Xbox 360.NET Compact FrameworkKeep an eye on garbage collection!ARMv7 CPUMore forgiving toward jitted codeARM jitter is more mature than PPCWays To Call CodeInstance methodInterfaceDelegate/eventReflectionVirtual methodChoose Your Own AddressC+allows independent choice of.NET types dictate their allocation and usage semanticsData typeThe memory in which a type lives(placement new)How a type instance is referenced(T,T*,T&,const T&)Value typesint,bool,struct,Vector3Reference typesclass,array,string,delegate,boxed value typesA Popular MythOft-repeated wisdomValue types live on the stackReference types live on the heapValue types live wherever they are declaredReference types have two piecesMemory allocated from the heapA pointer to this heap memoryThat is subtly incorrectBy default,prefer class over structureUse struct for things that areclass vs.structSmall(=16 bytes)Short livedPass large structures by referenceMatrix a,b,c;c=Matrix.Multiply(a,b);/copies 192 bytes!Matrix.Multiply(ref a,ref b,out c);Memory ManagementC+.NETAllocateInitially fast,becoming slower as fragmentation increasesVery fast,apart from periodic garbage collectionsFreeFastInstantaneousFragmentationIncreases over timeNoneCache coherencyRequires custom allocatorsThings allocated close in time are also close in physical locationGarbage collection is not optionalCant have type safety without automatic memory managementMark and SweepTriggered per megabyte of allocation1Starts with root references(stack variables,statics)2Recursively follows all references to see what other objects can be reached3Anything we didnt reach must be garbage4Compacts the heap,sliding live objects down to fill holes5Frameworks designed for performanceFrameworks designed for performanceTwo Ways To Keep GC HappyMake it run Less OftenIf you never allocate,GC will never runMake it Finish QuicklyCollection time is proportional to how many object references must be traversedUse object poolsSimple heap=fast collectionUse value types and integer handlesGC.CollectExplicitly forces a garbage collectionUse wisely to give yourself more headroomAfter loadingDuring pauses in gameplayDont call every frame!Avoiding AllocationBeware of boxingstring vs.StringBuilderUse WeakReference to track GC frequencyhttp:/ CLR Profiler on WindowsSee MIX10 talk:“Development and Debugging Tools for Windows Phone 7 Series”Use.NET Reflector to peek behind the curtainhttp:/www.red- GPUPlus hardware accelerated 2D sprite drawingFive Configurable EffectsBasicEffectSkinnedEffectEnvironmentMapEffectAlphaTestEffectDualTextureEffectBasicEffect0-3 directional lightsBlinn-Phong shadingOptional textureOptional fogOptional vertex colorBasicEffectVertex CostPixel CostNo lighting51One vertex light401Three vertex lights601Three pixel lights1850+Texture+1+2+Fog+4+2DualTextureEffectDualTextureEffectFor lightmaps,detail textures,decalsBlends two texturesSeparate texture coordinatesModulate 2X combine mode(A*B*2)Good visuals at low pixel costVertex CostPixel CostTwo Textures76+Fog+4+2AlphaTestEffectFor billboards and impostersAdds alpha test operations(pixel kill)Standard blending is free with all effectsOnly need alpha test if you want to disable depth/stencil writesAlphaTestEffectVertex CostPixel Cost,=,66=,!=610+Fog+4+2SkinnedEffectSkinnedEffectFor animated models and instancingGame code animates bones on CPUVertex skinning performed by GPUUp to 72 bonesOne,two,or four weights per vertexVertex CostPixel CostOne vertex light554Three vertex lights754Three pixel lights3351+Two bones+7+0+Four bones+13+0+Fog+0+2EnvironmentMapEffectEnvironmentMapEffectOooh,shiny!Diffuse texture+cube environment mapCheap way to fake many complex lightsFresnel term simulates behavior when light reaches a surface and some reflects,some penetratesVertex CostPixel CostOne light326Three lights366+Fresnel+7+0+Specular+0+2+Fog+0+2A Balancing ActFramerateNumberof PixelsPixel CostBalancing FramerateFramerate30 hz refresh rateNo point updating faster than the display!Game.TargetElapsedTime=TimeSpan.FromSeconds(1f/30);A Balancing ActPixel CostPrefer cheaper effectsMinimize overdrawMany known algorithms:Distance,frustum,BSP,sort front to backImplement“overdraw x-ray mode”Draw untextured with additive blendingBrighter areas indicate overdrawA Balancing ActNumberof Pixels800 x480 is 25%more pixels than Xbox 1Great for textToo many pixels for intensive games800 x480=384,000 pixels600 x360=216,000 pixels(56%)Dedicated hardware scalerDoes not consume any GPUHigher quality than bilinear upsamplingScaler DemoXNA Framework API Cheat SheetAvoidPreferRenderTargetUsage.PreserveContentsRenderTargetUsage.DiscardContentsdevice.BlendState=new BlendState.;/At startupstatic BlendState myState=new BlendState.;/Per frameDevice.BlendState=myState;VertexBuffer.SetData(.)device.DrawUserPrimitives(.);/orDynamicVertexBuffer.SetData(.,SetDataOptions.NoOverwrite);SummaryGreat performance comes from great knowledgeUnderstandActionsValue types vs.reference typesGarbage collectionC#compiler magic(foreach,iterator methods,closures)Cost of the different graphical effect optionsUse CLR Profiler and.NET ReflectorRender smaller than display resolution,rely on scaler 2010 Microsoft Corporation.All rights reserved.Microsoft,Windows,Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S.and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation.Because Microsoft must respond to changing market conditions,it should not be interpreted to be a commitment on the part of Microsoft,and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation.MICROSOFT MAKES NO WARRANTIES,EXPRESS,IMPLIED OR STATUTORY,AS TO THE INFORMATION IN THIS PRESENTATION.JUNE 7-10,2010|NEW ORLEANS,LARequired Slide