Exemple #1
0
        /// <summary>Initializes DirectX graphics</summary>
        /// <returns>true on success, false on failure</returns>
        private bool InitializeGraphics()
        {
            try
            {
                PresentParameters presentParams = new PresentParameters();
                presentParams.Windowed               = true;
                presentParams.SwapEffect             = SwapEffect.Discard;
                presentParams.BackBufferFormat       = Format.Unknown;
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                presentParams.EnableAutoDepthStencil = true;

                int         adapterOrdinal = D3D.Manager.Adapters.Default.Adapter;
                CreateFlags flags          = CreateFlags.SoftwareVertexProcessing;
                D3D.Caps    caps           = D3D.Manager.GetDeviceCaps(adapterOrdinal, D3D.DeviceType.Hardware);
                if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    flags = CreateFlags.HardwareVertexProcessing;
                }

                device                 = new Device(0, DeviceType.Hardware, this, flags, presentParams);
                device.DeviceLost     += new EventHandler(this.InvalidateDeviceObjects);
                device.DeviceReset    += new EventHandler(this.RestoreDeviceObjects);
                device.Disposing      += new EventHandler(this.DeleteDeviceObjects);
                device.DeviceResizing += new CancelEventHandler(this.EnvironmentResizeing);

                d3dsprite = new Sprite(device);
                return(true);
            }
            catch (DirectXException)
            {
                return(false);
            }
        }
Exemple #2
0
        private void Initialize()
        {
            try {
                //Common DirectX setup calls...
                PresentParameters presentParams = new PresentParameters();
                presentParams.Windowed               = true;
                presentParams.SwapEffect             = SwapEffect.Discard;
                presentParams.BackBufferFormat       = Format.Unknown;
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                presentParams.EnableAutoDepthStencil = true;

                // Store the default adapter
                int         adapterOrdinal = D3D.Manager.Adapters.Default.Adapter;
                CreateFlags flags          = CreateFlags.SoftwareVertexProcessing;

                // Check to see if we can use a pure hardware device
                D3D.Caps caps = D3D.Manager.GetDeviceCaps(adapterOrdinal, D3D.DeviceType.Hardware);

                // Do we support hardware vertex processing?
                if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    // Replace the software vertex processing
                    flags = CreateFlags.HardwareVertexProcessing;
                }

                device              = new D3D.Device(0, D3D.DeviceType.Hardware, this, flags, presentParams);
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);
                OnResetDevice(device, null);

                //Space Donuts setup
                donutTexture = TextureLoader.FromFile(device, MediaUtilities.FindFile(TileSetFileName), 1024, 1024,
                                                      1, 0, Format.A8R8G8B8, Pool.Managed, Filter.Point, Filter.Point, (unchecked ((int)0xff000000)));

                donutTileSet   = new TileSet(donutTexture, 0, 0, 6, 5, 32, 32);
                pyramidTileSet = new TileSet(donutTexture, 0, 384, 4, 10, 16, 16);
                sphereTileSet  = new TileSet(donutTexture, 0, 512, 2, 20, 8, 8);
                cubeTileSet    = new TileSet(donutTexture, 0, 544, 2, 20, 8, 8);
                shipTileSet    = new TileSet(donutTexture, 0, 576, 4, 10, 16, 16);
                nixiesTileSet  = new TileSet(donutTexture, 0, 832, 1, 14, 8, 8);
                bulletTileSet  = new TileSet(donutTexture, 304, 832, 1, 1, 8, 2);

                //set up DirectInput keyboard device...
                kbd = new DI.Device(SystemGuid.Keyboard);
                kbd.SetCooperativeLevel(this,
                                        DI.CooperativeLevelFlags.Background | DI.CooperativeLevelFlags.NonExclusive);
                kbd.Acquire();

                soundHandler = new SoundHandler(this);

                sm.OnCollisionDetected += new SpriteManager.HandleCollision(this.CollisionHandler);

                hrt.Start();
            }
            catch (DirectXException e) {
                Console.WriteLine("Exception is " + e.ErrorString);
                // Catch any errors and return a failure
            }
        }
        private void InitializeGraphics()
        {
            try {
                PresentParameters presentParams = new PresentParameters();
                presentParams.Windowed               = true;
                presentParams.SwapEffect             = SwapEffect.Discard;
                presentParams.BackBufferFormat       = Format.Unknown;
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                presentParams.EnableAutoDepthStencil = true;

                // Store the default adapter
                int         adapterOrdinal = D3D.Manager.Adapters.Default.Adapter;
                CreateFlags flags          = CreateFlags.SoftwareVertexProcessing;

                // Check to see if we can use a pure hardware device
                D3D.Caps caps = D3D.Manager.GetDeviceCaps(adapterOrdinal, D3D.DeviceType.Hardware);

                // Do we support hardware vertex processing?
                if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    // Replace the software vertex processing
                    flags = CreateFlags.HardwareVertexProcessing;
                }

                // Do we support a pure device?
                if (caps.DeviceCaps.SupportsPureDevice)
                {
                    flags |= CreateFlags.PureDevice;
                }

                device              = new D3D.Device(0, D3D.DeviceType.Hardware, this, flags, presentParams);
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);
                OnResetDevice(device, null);

                tileSheet = TextureLoader.FromFile(device, MediaUtilities.FindFile("donuts.bmp"), 1024, 1024,
                                                   1, 0, Format.A8R8G8B8, Pool.Managed, Filter.Point, Filter.Point, (unchecked ((int)0xff000000)));

                tileSet      = new TileSet(tileSheet, 0, 0, 6, 5, 32, 32);
                tilePosition = new Rectangle(tileSet.XOrigin, tileSet.YOrigin, tileSet.ExtentX * 2, tileSet.ExtentY * 2);

                //set up DirectInput keyboard device...
                kbd = new DI.Device(SystemGuid.Keyboard);
                kbd.SetCooperativeLevel(this,
                                        DI.CooperativeLevelFlags.Background | DI.CooperativeLevelFlags.NonExclusive);
                kbd.Acquire();

                //Set up DirectSound device and buffers
                snd = new DS.Device();
                snd.SetCooperativeLevel(this, DS.CooperativeLevel.Normal);
                bounce = new DS.SecondaryBuffer(MediaUtilities.FindFile("bounce.wav"), snd);

                hrt.Start();
            }
            catch (DirectXException) {
                // Catch any errors and return a failure
            }
        }
Exemple #4
0
        internal void Initialize(MDX1_DisplayWindow window)
        {
            if (mInitialized)
            {
                return;
            }

            if (window.RenderTarget.TopLevelControl == null)
            {
                throw new ArgumentException("The specified render target does not have a Form object yet.  " +
                                            "It's TopLevelControl property is null.  You may not create DisplayWindow objects before " +
                                            "the control to render to is added to the Form.");
            }

            mInitialized = true;

            // ok, create D3D device
            PresentParameters present = CreateWindowedPresentParameters(window, 0, 0);

            present.BackBufferWidth  = 1;
            present.BackBufferHeight = 1;

            DeviceType dtype = DeviceType.Hardware;

            int adapterOrdinal = Direct3D.Manager.Adapters.Default.Adapter;

            Direct3D.Caps        caps  = Direct3D.Manager.GetDeviceCaps(adapterOrdinal, Direct3D.DeviceType.Hardware);
            Direct3D.CreateFlags flags = Direct3D.CreateFlags.SoftwareVertexProcessing;

            // Is there support for hardware vertex processing? If so, replace
            // software vertex processing.
            if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
            {
                flags = Direct3D.CreateFlags.HardwareVertexProcessing;
            }

            // Does the device support a pure device?
            if (caps.DeviceCaps.SupportsPureDevice)
            {
                flags |= Direct3D.CreateFlags.PureDevice;
            }

            Device device = new Device
                                (0, dtype, window.RenderTarget.TopLevelControl.Handle,
                                flags, present);

            device.DeviceLost  += new EventHandler(mDevice_DeviceLost);
            device.DeviceReset += new EventHandler(mDevice_DeviceReset);

            mDevice = new D3DDevice(device);

            // create primitive objects
            mLine = new Direct3D.Line(device);

            //CreateSurfaceVB();
        }
Exemple #5
0
 public static D3D.CreateFlags GetDeviceCreateFlags(int adpNum, D3D.DeviceType type)
 {
     DebugOnly.ConsoleWrite("Getting device creation flags...");
     D3D.Caps        caps  = D3D.Manager.GetDeviceCaps(adpNum, type);
     D3D.CreateFlags flags = D3D.CreateFlags.SoftwareVertexProcessing;
     if (caps.DeviceCaps.SupportsHardwareRasterization && caps.DeviceCaps.SupportsHardwareTransformAndLight)
     {
         flags = D3D.CreateFlags.HardwareVertexProcessing;
         if (caps.DeviceCaps.SupportsPureDevice)
         {
             flags |= D3D.CreateFlags.PureDevice;
         }
     }
     DebugOnly.ConsoleWrite("Found flags: " + flags.ToString());
     return(flags);
 }
Exemple #6
0
        public bool IsDeviceAcceptable(Microsoft.DirectX.Direct3D.Caps caps, Microsoft.DirectX.Direct3D.Format adapterFormat, Microsoft.DirectX.Direct3D.Format backBufferFormat, bool isWindowed)
        {
            // No fallback, need at least PS1.1
            if (caps.PixelShaderVersion < new Version(1, 1))
            {
                return(false);
            }

            // Skip back buffer formats that don't support alpha blending
            if (!Manager.CheckDeviceFormat(caps.AdapterOrdinal, caps.DeviceType, adapterFormat,
                                           Usage.QueryPostPixelShaderBlending, ResourceType.Textures, backBufferFormat))
            {
                return(false);
            }

            return(true);
        }
Exemple #7
0
        //***************************************************************************
        // Static Methods
        //
        public static D3D.DeviceType GetDeviceType(int adpNum)
        {
            DebugOnly.ConsoleWrite("Determining device type...");
            D3D.DeviceType devType = D3D.DeviceType.Reference;
            D3D.Caps       devCaps = D3D.Manager.GetDeviceCaps(adpNum, D3D.DeviceType.Hardware);

            if (devCaps.DeviceCaps.SupportsHardwareRasterization)
            {
                devType = D3D.DeviceType.Hardware;
            }
            else if (devCaps.DeviceType == D3D.DeviceType.Software)
            {
                devType = D3D.DeviceType.Software;
            }

            DebugOnly.ConsoleWrite("Found DeviceType: " + devType.ToString());
            return(devType);
        }
        public static int ConvertEnum(TexCoordCalcMethod method, D3D.Caps caps)
        {
            switch (method)
            {
            case TexCoordCalcMethod.None:
                return((int)D3D.TextureCoordinateIndex.PassThru);

            case TexCoordCalcMethod.EnvironmentMapReflection:
                return((int)D3D.TextureCoordinateIndex.CameraSpaceReflectionVector);

            case TexCoordCalcMethod.EnvironmentMapPlanar:
                //return (int)D3D.TextureCoordinateIndex.CameraSpacePosition;
                if (caps.VertexProcessingCaps.SupportsTextureGenerationSphereMap)
                {
                    // use sphere map if available
                    return((int)D3D.TextureCoordinateIndex.SphereMap);
                }
                else
                {
                    // If not, fall back on camera space reflection vector which isn't as good
                    return((int)D3D.TextureCoordinateIndex.CameraSpaceReflectionVector);
                }

            case TexCoordCalcMethod.EnvironmentMapNormal:
                return((int)D3D.TextureCoordinateIndex.CameraSpaceNormal);

            case TexCoordCalcMethod.EnvironmentMap:
                if (caps.VertexProcessingCaps.SupportsTextureGenerationSphereMap)
                {
                    return((int)D3D.TextureCoordinateIndex.SphereMap);
                }
                else
                {
                    // fall back on camera space normal if sphere map isnt supported
                    return((int)D3D.TextureCoordinateIndex.CameraSpaceNormal);
                }

            case TexCoordCalcMethod.ProjectiveTexture:
                return((int)D3D.TextureCoordinateIndex.CameraSpacePosition);
            }             // switch

            return(0);
        }
Exemple #9
0
        public void ModifyDeviceSettings(DeviceSettings settings, Microsoft.DirectX.Direct3D.Caps caps)
        {
            // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
            // then switch to SWVP.
            if ((!caps.DeviceCaps.SupportsHardwareTransformAndLight) ||
                (caps.VertexShaderVersion < new Version(1, 1)))
            {
                settings.BehaviorFlags = CreateFlags.SoftwareVertexProcessing;
            }
            else
            {
                settings.BehaviorFlags = CreateFlags.HardwareVertexProcessing;
            }

            // This application is designed to work on a pure device by not using
            // any get methods, so create a pure device if supported and using HWVP.
            if ((caps.DeviceCaps.SupportsPureDevice) &&
                ((settings.BehaviorFlags & CreateFlags.HardwareVertexProcessing) != 0))
            {
                settings.BehaviorFlags |= CreateFlags.PureDevice;
            }

            // Debugging vertex shaders requires either REF or software vertex processing
            // and debugging pixel shaders requires REF.
#if (DEBUG_VS)
            if (settings.DeviceType != DeviceType.Reference)
            {
                settings.BehaviorFlags &= ~CreateFlags.HardwareVertexProcessing;
                settings.BehaviorFlags |= CreateFlags.SoftwareVertexProcessing;
            }
#endif
#if (DEBUG_PS)
            settings.DeviceType = DeviceType.Reference;
#endif

            // For the first device created if its a REF device, optionally display a warning dialog box
            if (settings.DeviceType == DeviceType.Reference)
            {
                Utility.DisplaySwitchingToRefWarning(sampleFramework, "ProgressiveMesh");
            }
        }
Exemple #10
0
    /// <summary>
    /// Initialize the device objects
    /// </summary>
    /// <param name="dev">The grpahics device used to initialize</param>
    public void InitializeDeviceObjects(Device dev)
    {
        if (dev != null)
        {
            // Set up our events
            dev.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects);
        }

        // Keep a local copy of the device
        device        = dev;
        textureState0 = device.TextureState[0];
        textureState1 = device.TextureState[1];
        samplerState0 = device.SamplerState[0];
        renderState   = device.RenderState;

        // Establish the font and texture size
        textureScale = 1.0f; // Draw fonts into texture without scaling

        // Large fonts need larger textures
        if (ourFontHeight > 60)
        {
            textureWidth = textureHeight = 2048;
        }
        else if (ourFontHeight > 30)
        {
            textureWidth = textureHeight = 1024;
        }
        else if (ourFontHeight > 15)
        {
            textureWidth = textureHeight = 512;
        }
        else
        {
            textureWidth = textureHeight = 256;
        }

        // If requested texture is too big, use a smaller texture and smaller font,
        // and scale up when rendering.
        Direct3D.Caps d3dCaps = device.DeviceCaps;

        if (textureWidth > d3dCaps.MaxTextureWidth)
        {
            textureScale = (float)d3dCaps.MaxTextureWidth / (float)textureWidth;
            textureWidth = textureHeight = d3dCaps.MaxTextureWidth;
        }

        Bitmap   bmp = new Bitmap(textureWidth, textureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        Graphics g   = Graphics.FromImage(bmp);

        g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        g.TextContrast      = 0;

        string str;
        float  x    = 0;
        float  y    = 0;
        Point  p    = new Point(0, 0);
        Size   size = new Size(0, 0);

        // Calculate the spacing between characters based on line height
        size = g.MeasureString(" ", systemFont).ToSize();
        x    = spacingPerChar = (int)Math.Ceiling(size.Height * 0.3);

        for (char c = (char)32; c < (char)127; c++)
        {
            str = c.ToString();
            // We need to do some things here to get the right sizes.  The default implemententation of MeasureString
            // will return a resolution independant size.  For our height, this is what we want.  However, for our width, we
            // want a resolution dependant size.
            Size resSize = g.MeasureString(str, systemFont).ToSize();
            size.Height = resSize.Height + 1;

            // Now the Resolution independent width
            if (c != ' ') // We need the special case here because a space has a 0 width in GenericTypoGraphic stringformats
            {
                resSize    = g.MeasureString(str, systemFont, p, StringFormat.GenericTypographic).ToSize();
                size.Width = resSize.Width;
            }
            else
            {
                size.Width = resSize.Width;
            }

            if ((x + size.Width + spacingPerChar) > textureWidth)
            {
                x  = spacingPerChar;
                y += size.Height;
            }

            if (c != ' ') // We need the special case here because a space has a 0 width in GenericTypoGraphic stringformats
            {
                g.DrawString(str, systemFont, Brushes.White, new Point((int)x, (int)y), StringFormat.GenericTypographic);
            }
            else
            {
                g.DrawString(str, systemFont, Brushes.White, new Point((int)x, (int)y));
            }
            textureCoords[c - 32, 0] = ((float)(x + 0 - spacingPerChar)) / textureWidth;
            textureCoords[c - 32, 1] = ((float)(y + 0 + 0)) / textureHeight;
            textureCoords[c - 32, 2] = ((float)(x + size.Width + spacingPerChar)) / textureWidth;
            textureCoords[c - 32, 3] = ((float)(y + size.Height + 0)) / textureHeight;

            x += size.Width + (2 * spacingPerChar);
        }

        // Create a new texture for the font from the bitmap we just created
        fontTexture = Texture.FromBitmap(device, bmp, 0, Pool.Managed);
        RestoreDeviceObjects(null, null);
    }
        private D3D.Device InitDevice(bool isFullscreen, bool depthBuffer, int width, int height, int colorDepth, Control target)
        {
            if(device != null) {
                return device;
            }

            // we don't care about event handlers
            Device.IsUsingEventHandlers = false;

            D3D.Device newDevice;

            PresentParameters presentParams = CreatePresentationParams(isFullscreen, depthBuffer, width, height, colorDepth);

            // create the D3D Device, trying for the best vertex support first, and settling for less if necessary
            try {
                // hardware vertex processing
                int adapterNum = 0;
                DeviceType type = DeviceType.Hardware;
            #if DEBUG
                for ( int i = 0; i < Manager.Adapters.Count; i++ ) {
                    if (Manager.Adapters[i].Information.Description == "NVIDIA NVPerfHUD")
                    {
                        adapterNum = i;
                        type = DeviceType.Reference;
                    }
                }
            #endif
                // use this with NVPerfHUD
                newDevice = new D3D.Device(adapterNum, type, target, CreateFlags.HardwareVertexProcessing, presentParams);
                // newDevice = new D3D.Device(0, DeviceType.Hardware, target, CreateFlags.HardwareVertexProcessing, presentParams);
            }
            catch(Exception) {
                try {
                    // doh, how bout mixed vertex processing
                    newDevice = new D3D.Device(0, DeviceType.Hardware, target, CreateFlags.MixedVertexProcessing, presentParams);
                }
                catch(Exception) {
                    // what the...ok, how bout software vertex procssing.  if this fails, then I don't even know how they are seeing
                    // anything at all since they obviously don't have a video card installed
                    newDevice = new D3D.Device(0, DeviceType.Hardware, target, CreateFlags.SoftwareVertexProcessing, presentParams);
                }
            }

            // CMH - end

            // save the device capabilites
            d3dCaps = newDevice.DeviceCaps;

            // by creating our texture manager, singleton TextureManager will hold our implementation
            textureMgr = new D3DTextureManager(newDevice);

            // by creating our Gpu program manager, singleton GpuProgramManager will hold our implementation
            gpuProgramMgr = new D3DGpuProgramManager(newDevice);

            // intializes the HardwareBufferManager singleton
            hardwareBufferManager = new D3DHardwareBufferManager(newDevice);

            return newDevice;
        }
        /// <summary>
        ///		Helper method to go through and interrogate hardware capabilities.
        /// </summary>
        private void InitCapabilities()
        {
            // get caps
            d3dCaps = device.DeviceCaps;

            // max active lights
            caps.MaxLights = d3dCaps.MaxActiveLights;

            D3D.Surface surface = device.DepthStencilSurface;
            D3D.SurfaceDescription surfaceDesc = surface.Description;
            surface.Dispose();

            if (surfaceDesc.Format == D3D.Format.D24S8 || surfaceDesc.Format == D3D.Format.D24X8) {
                caps.SetCap(Capabilities.StencilBuffer);
                // Actually, it's always 8-bit
                caps.StencilBufferBits = 8;
            }

            // Set number of texture units
            caps.TextureUnitCount = d3dCaps.MaxSimultaneousTextures;

            // some cards, oddly enough, do not support this
            if(d3dCaps.DeclTypes.SupportsUByte4) {
                caps.SetCap(Capabilities.VertexFormatUByte4);
            }

            // Anisotropy?
            if(d3dCaps.MaxAnisotropy > 1) {
                caps.SetCap(Capabilities.AnisotropicFiltering);
            }

            // Hardware mipmapping?
            if(d3dCaps.DriverCaps.CanAutoGenerateMipMap) {
                caps.SetCap(Capabilities.HardwareMipMaps);
            }

            // blending between stages is definately supported
            caps.SetCap(Capabilities.TextureBlending);
            caps.SetCap(Capabilities.MultiTexturing);

            // Dot3 bump mapping?
            if(d3dCaps.TextureOperationCaps.SupportsDotProduct3) {
                caps.SetCap(Capabilities.Dot3);
            }

            // Cube mapping?
            if(d3dCaps.TextureCaps.SupportsCubeMap) {
                caps.SetCap(Capabilities.CubeMapping);
            }

            // Texture Compression
            // We always support compression, D3DX will decompress if device does not support
            caps.SetCap(Capabilities.TextureCompression);
            caps.SetCap(Capabilities.TextureCompressionDXT);

            // D3D uses vertex buffers for everything
            caps.SetCap(Capabilities.VertexBuffer);

            // Scissor test
            if(d3dCaps.RasterCaps.SupportsScissorTest) {
                caps.SetCap(Capabilities.ScissorTest);
            }

            // 2 sided stencil
            if(d3dCaps.StencilCaps.SupportsTwoSided) {
                caps.SetCap(Capabilities.TwoSidedStencil);
            }

            // stencil wrap
            if(d3dCaps.StencilCaps.SupportsIncrement && d3dCaps.StencilCaps.SupportsDecrement) {
                caps.SetCap(Capabilities.StencilWrap);
            }

            // Hardware Occlusion
            try {
                D3D.Query test = new D3D.Query(device, QueryType.Occlusion);

                // if we made it this far, it is supported
                caps.SetCap(Capabilities.HardwareOcculusion);

                test.Dispose();
            }
            catch {
                // eat it, this is not supported
                // TODO: Isn't there a better way to check for D3D occlusion query support?
            }

            if(d3dCaps.MaxUserClipPlanes > 0) {
                caps.SetCap(Capabilities.UserClipPlanes);
            }

            CheckVertexProgramCaps();

            CheckFragmentProgramCaps();

            Driver driver = D3DHelper.GetDriverInfo();

            AdapterDetails details = D3D.Manager.Adapters[driver.AdapterNumber].Information;

            caps.DeviceName = details.Description;
            caps.DriverVersion = details.DriverVersion.ToString();

            try {
                //
                // use the dxdiag interface to get the actual size of video memory
                //
                Container container = new Container(false);
                container = container.GetContainer("DxDiag_DisplayDevices").Container;
                container = container.GetContainer(0).Container;

                Microsoft.DirectX.Diagnostics.PropertyData prop = container.GetProperty("szDisplayMemoryEnglish");
                string s = prop.Data as string;

                int numStartOffset = -1;
                for (int i = 0; i < s.Length; i++) {
                    char c = s[i];
                    if (char.IsDigit(s[i])) {
                        numStartOffset = i;
                        break;
                    }
                }

                if (numStartOffset >= 0) {
                    int numEndOffset;
                    for (numEndOffset = numStartOffset; numEndOffset < s.Length; numEndOffset++) {
                        if (!char.IsDigit(s[numEndOffset])) {
                            break;
                        }
                    }

                    string numString = s.Substring(numStartOffset, numEndOffset - numStartOffset);
                    //LogManager.Instance.Write("DXDiag memory size string returned: {0}", s);
                    //LogManager.Instance.Write("parsing memory size string: {0}", numString);

                    caps.VideoMemorySize = int.Parse(numString);
                    //LogManager.Instance.Write("Parsed memory size value is: {0}", caps.VideoMemorySize);

                } else {
                    // couldn't determine size
                    caps.VideoMemorySize = 0;
                }
            } catch (Exception) {
            #if FALSE_WARNING_IS_FIXED
                log.Warn("DXDiag unable to determine memory size.");
            #endif
                // couldn't determine size
                caps.VideoMemorySize = 0;
            }

            // Infinite projection?
            // We have no capability for this, so we have to base this on our
            // experience and reports from users
            // Non-vertex program capable hardware does not appear to support it
            if(caps.CheckCap(Capabilities.VertexPrograms)) {
                // GeForce4 Ti (and presumably GeForce3) does not
                // render infinite projection properly, even though it does in GL
                // So exclude all cards prior to the FX range from doing infinite

                // not nVidia or GeForceFX and above
                if(details.VendorId != 0x10DE || details.DeviceId >= 0x0301) {
                    caps.SetCap(Capabilities.InfiniteFarPlane);
                }
            }

            // TODO: Add the rest of the caps.
            caps.NumMultiRenderTargets = d3dCaps.NumberSimultaneousRts;

            // write hardware capabilities to registered log listeners
            caps.Log();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="type"></param>
        /// <param name="options"></param>
        /// <param name="caps"></param>
        /// <param name="texType"></param>
        /// <returns></returns>
        public static D3D.TextureFilter ConvertEnum(FilterType type, FilterOptions options, D3D.Caps devCaps, D3DTexType texType)
        {
            // setting a default val here to keep compiler from complaining about using unassigned value types
            D3D.FilterCaps filterCaps = devCaps.TextureFilterCaps;

            switch (texType)
            {
            case D3DTexType.Normal:
                filterCaps = devCaps.TextureFilterCaps;
                break;

            case D3DTexType.Cube:
                filterCaps = devCaps.CubeTextureFilterCaps;
                break;

            case D3DTexType.Volume:
                filterCaps = devCaps.VolumeTextureFilterCaps;
                break;
            }

            switch (type)
            {
            case FilterType.Min: {
                switch (options)
                {
                case FilterOptions.Anisotropic:
                    if (filterCaps.SupportsMinifyAnisotropic)
                    {
                        return(D3D.TextureFilter.Anisotropic);
                    }
                    else
                    {
                        return(D3D.TextureFilter.Linear);
                    }

                case FilterOptions.Linear:
                    if (filterCaps.SupportsMinifyLinear)
                    {
                        return(D3D.TextureFilter.Linear);
                    }
                    else
                    {
                        return(D3D.TextureFilter.Point);
                    }

                case FilterOptions.Point:
                case FilterOptions.None:
                    return(D3D.TextureFilter.Point);
                }
                break;
            }

            case FilterType.Mag: {
                switch (options)
                {
                case FilterOptions.Anisotropic:
                    if (filterCaps.SupportsMagnifyAnisotropic)
                    {
                        return(D3D.TextureFilter.Anisotropic);
                    }
                    else
                    {
                        return(D3D.TextureFilter.Linear);
                    }

                case FilterOptions.Linear:
                    if (filterCaps.SupportsMagnifyLinear)
                    {
                        return(D3D.TextureFilter.Linear);
                    }
                    else
                    {
                        return(D3D.TextureFilter.Point);
                    }

                case FilterOptions.Point:
                case FilterOptions.None:
                    return(D3D.TextureFilter.Point);
                }
                break;
            }

            case FilterType.Mip: {
                switch (options)
                {
                case FilterOptions.Anisotropic:
                case FilterOptions.Linear:
                    if (filterCaps.SupportsMipMapLinear)
                    {
                        return(D3D.TextureFilter.Linear);
                    }
                    else
                    {
                        return(D3D.TextureFilter.Point);
                    }

                case FilterOptions.Point:
                    if (filterCaps.SupportsMipMapPoint)
                    {
                        return(D3D.TextureFilter.Point);
                    }
                    else
                    {
                        return(D3D.TextureFilter.None);
                    }

                case FilterOptions.None:
                    return(D3D.TextureFilter.None);
                }
                break;
            }
            }

            // should never get here
            return(0);
        }
        /// <summary>
        ///		Static method for converting LayerBlendOperationEx enum values to the Direct3D
        ///		TextureOperation enum.
        /// </summary>
        /// <param name="blendop"></param>
        /// <returns></returns>
        public static D3D.TextureOperation ConvertEnum(LayerBlendOperationEx blendop, D3D.Caps devCaps)
        {
            D3D.TextureOperation d3dTexOp = 0;

            // figure out what is what
            switch (blendop)
            {
            case LayerBlendOperationEx.Source1:
                d3dTexOp = D3D.TextureOperation.SelectArg1;
                break;

            case LayerBlendOperationEx.Source2:
                d3dTexOp = D3D.TextureOperation.SelectArg2;
                break;

            case LayerBlendOperationEx.Modulate:
                d3dTexOp = D3D.TextureOperation.Modulate;
                break;

            case LayerBlendOperationEx.ModulateX2:
                d3dTexOp = D3D.TextureOperation.Modulate2X;
                break;

            case LayerBlendOperationEx.ModulateX4:
                d3dTexOp = D3D.TextureOperation.Modulate4X;
                break;

            case LayerBlendOperationEx.Add:
                d3dTexOp = D3D.TextureOperation.Add;
                break;

            case LayerBlendOperationEx.AddSigned:
                d3dTexOp = D3D.TextureOperation.AddSigned;
                break;

            case LayerBlendOperationEx.AddSmooth:
                d3dTexOp = D3D.TextureOperation.AddSmooth;
                break;

            case LayerBlendOperationEx.Subtract:
                d3dTexOp = D3D.TextureOperation.Subtract;
                break;

            case LayerBlendOperationEx.BlendDiffuseAlpha:
                d3dTexOp = D3D.TextureOperation.BlendDiffuseAlpha;
                break;

            case LayerBlendOperationEx.BlendTextureAlpha:
                d3dTexOp = D3D.TextureOperation.BlendTextureAlpha;
                break;

            case LayerBlendOperationEx.BlendCurrentAlpha:
                d3dTexOp = D3D.TextureOperation.BlendCurrentAlpha;
                break;

            case LayerBlendOperationEx.BlendManual:
                d3dTexOp = D3D.TextureOperation.BlendFactorAlpha;
                break;

            case LayerBlendOperationEx.DotProduct:
                if (Root.Instance.RenderSystem.Caps.CheckCap(Capabilities.Dot3))
                {
                    d3dTexOp = D3D.TextureOperation.DotProduct3;
                }
                else
                {
                    d3dTexOp = D3D.TextureOperation.Modulate;
                }
                break;

            case LayerBlendOperationEx.BlendDiffuseColor:
                if (devCaps.TextureOperationCaps.SupportsLerp)
                {
                    d3dTexOp = D3D.TextureOperation.Lerp;
                }
                else
                {
                    d3dTexOp = D3D.TextureOperation.Modulate;
                }
                break;
            } // end switch

            return(d3dTexOp);
        }
        protected void InitDevice()
        {
            Debug.Assert(device != null);
            // get device caps
            devCaps = device.DeviceCaps;

            // get our device creation parameters
            devParms = device.CreationParameters;

            // get our back buffer pixel format
            using (D3D.Surface back = device.GetBackBuffer(0, 0, D3D.BackBufferType.Mono)) {
                bbPixelFormat = back.Description.Format;
            }
        }
Exemple #16
0
    /// <summary>
    /// Initialize the device objects
    /// </summary>
    /// <param name="dev">The grpahics device used to initialize</param>
    public void InitializeDeviceObjects(Device dev)
    {
        if (dev != null)
        {
            // Set up our events
            dev.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects);
        }

        // Keep a local copy of the device
        device        = dev;
        textureState0 = device.TextureState[0];
        textureState1 = device.TextureState[1];
        samplerState0 = device.SamplerState[0];
        renderState   = device.RenderState;

        // Create a bitmap on which to measure the alphabet
        Bitmap   bmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        Graphics g   = Graphics.FromImage(bmp);

        g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        g.TextContrast      = 0;

        // Establish the font and texture size
        textureScale = 1.0f;  // Draw fonts into texture without scaling

        // Calculate the dimensions for the smallest power-of-two texture which
        // can hold all the printable characters
        textureWidth = textureHeight = 128;
        for (;;)
        {
            try
            {
                // Measure the alphabet
                PaintAlphabet(g, true);
            }
            catch (System.InvalidOperationException)
            {
                // Scale up the texture size and try again
                textureWidth  *= 2;
                textureHeight *= 2;
                continue;
            }

            break;
        }

        // If requested texture is too big, use a smaller texture and smaller font,
        // and scale up when rendering.
        Direct3D.Caps d3dCaps = device.DeviceCaps;

        // If the needed texture is too large for the video card...
        if (textureWidth > d3dCaps.MaxTextureWidth)
        {
            // Scale the font size down to fit on the largest possible texture
            textureScale = (float)d3dCaps.MaxTextureWidth / (float)textureWidth;
            textureWidth = textureHeight = d3dCaps.MaxTextureWidth;

            for (;;)
            {
                // Create a new, smaller font
                ourFontHeight = (int)Math.Floor(ourFontHeight * textureScale);
                systemFont    = new System.Drawing.Font(systemFont.Name, ourFontHeight, systemFont.Style);

                try
                {
                    // Measure the alphabet
                    PaintAlphabet(g, true);
                }
                catch (System.InvalidOperationException)
                {
                    // If that still doesn't fit, scale down again and continue
                    textureScale *= 0.9F;
                    continue;
                }

                break;
            }
        }

        // Release the bitmap used for measuring and create one for drawing
        bmp.Dispose();
        bmp                 = new Bitmap(textureWidth, textureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        g                   = Graphics.FromImage(bmp);
        g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        g.TextContrast      = 0;

        // Draw the alphabet
        PaintAlphabet(g, false);

        // Create a new texture for the font from the bitmap we just created
        fontTexture = Texture.FromBitmap(device, bmp, 0, Pool.Managed);
        RestoreDeviceObjects(null, null);
    }
Exemple #17
0
        public ScreenAccess()
        {
            try
            {
                Direct3D.PresentParameters presentParams = new Direct3D.PresentParameters();
                presentParams.Windowed               = true;
                presentParams.SwapEffect             = Direct3D.SwapEffect.Discard;
                presentParams.EnableAutoDepthStencil = true;
                presentParams.AutoDepthStencilFormat = Direct3D.DepthFormat.D16;

                Direct3D.Caps        hardware = Direct3D.Manager.GetDeviceCaps(0, Direct3D.DeviceType.Hardware);
                Direct3D.CreateFlags flags    = Direct3D.CreateFlags.SoftwareVertexProcessing;

                // Search for the highest possible shader support and define the device.
                if (hardware.VertexShaderVersion >= new Version(2, 0))
                {
                    if (hardware.DeviceCaps.SupportsHardwareTransformAndLight)
                    {
                        flags = Direct3D.CreateFlags.HardwareVertexProcessing;
                    }

                    if (hardware.DeviceCaps.SupportsPureDevice)
                    {
                        flags |= Direct3D.CreateFlags.PureDevice;
                    }

                    if (hardware.PixelShaderVersion >= new Version(3, 0))
                    {
                        CardShader = GameEngine.ShaderLevel.Pixel_3_0;
                    }
                    else if (hardware.PixelShaderVersion >= new Version(2, 2))
                    {
                        CardShader = GameEngine.ShaderLevel.Pixel_2_b;
                    }
                    else if (hardware.PixelShaderVersion >= new Version(2, 0))
                    {
                        CardShader = GameEngine.ShaderLevel.Pixel_2_0;
                    }
                    else if (hardware.PixelShaderVersion >= new Version(1, 4))
                    {
                        CardShader = GameEngine.ShaderLevel.Pixel_1_4;
                    }
                    else
                    {
                        CardShader = GameEngine.ShaderLevel.NoShaders;
                    }

                    device = new Direct3D.Device(0, Direct3D.DeviceType.Hardware, this, flags, presentParams);
                }
                else if (hardware.VertexShaderVersion >= new Version(1, 1))
                {
                    if (hardware.DeviceCaps.SupportsHardwareTransformAndLight)
                    {
                        flags = Direct3D.CreateFlags.HardwareVertexProcessing;
                    }

                    if (hardware.DeviceCaps.SupportsPureDevice)
                    {
                        flags |= Direct3D.CreateFlags.PureDevice;
                    }

                    if (hardware.PixelShaderVersion >= new Version(1, 4))
                    {
                        CardShader = GameEngine.ShaderLevel.Pixel_1_4;
                    }
                    else
                    {
                        CardShader = GameEngine.ShaderLevel.NoShaders;
                    }

                    device = new Direct3D.Device(0, Direct3D.DeviceType.Hardware, this, flags, presentParams);
                }
                //TODO: test this on shit cards and fake cards to see if they can use DeviceType.Hardware
                else
                {
                    CardShader = GameEngine.ShaderLevel.NoShaders;
                    device     = new Direct3D.Device(0, Direct3D.DeviceType.Hardware, this,
                                                     Direct3D.CreateFlags.SoftwareVertexProcessing, presentParams);
                }

                //Setup Alpha Blending
                this.device.RenderState.AlphaBlendOperation = Direct3D.BlendOperation.Add;
                this.device.RenderState.AlphaTestEnable     = true;
                this.device.RenderState.ReferenceAlpha      = 0x08;
                this.device.RenderState.AlphaFunction       = Direct3D.Compare.GreaterEqual;

                this.device.SetTextureStageState(0, Direct3D.TextureStageStates.AlphaOperation, true);

                //Get the best texture filtering available from the card
                if (this.device.DeviceCaps.TextureFilterCaps.SupportsMinifyAnisotropic == true &&
                    this.device.DeviceCaps.TextureFilterCaps.SupportsMagnifyAnisotropic == true)
                {
                    this.PreferedTextureFilter = Direct3D.TextureFilter.Anisotropic;
                }
                else if (this.device.DeviceCaps.TextureFilterCaps.SupportsMinifyLinear == true &&
                         this.device.DeviceCaps.TextureFilterCaps.SupportsMagnifyLinear == true)
                {
                    this.PreferedTextureFilter = Direct3D.TextureFilter.Linear;
                }
                else
                {
                    this.PreferedTextureFilter = Direct3D.TextureFilter.None;
                }

                //Add window events to hardware screen device
                this.DeligateEventsToDevices();
            }
            catch (Exception err)
            {
                throw new Exception(err.StackTrace);
            }
        }