public GraphicsParameters(bool windowed, RectangleF rect, Format format, PresentParameters pparams, CreateFlags cflags,
     DeviceType dtype, Caps dcaps,float zNear,float zFar)
 {
     this.windowed = windowed;
     windowRect = rect;
     adapterFormat = format;
     presentParams = (PresentParameters)pparams.Clone();
     createFlags = cflags;
     deviceType = dtype;
     deviceCaps = dcaps;
     zNearPlane = zNear;
     zFar = zFarPlane;
 }
        internal static string CreateTableIfNotExists(string tableName, CreateFlags createFlags, IReadOnlyDictionary<string, ColumnMapping> columns)
        {
            bool fts3 = (createFlags & CreateFlags.FullTextSearch3) != 0;
            bool fts4 = (createFlags & CreateFlags.FullTextSearch4) != 0;
            bool fts = fts3 || fts4;

            var @virtual = fts ? "VIRTUAL " : string.Empty;
            var @using = fts3 ? "USING FTS3 " : fts4 ? "USING FTS4 " : string.Empty;

            // Build query.
            var query = "CREATE " + @virtual + "TABLE IF NOT EXISTS \"" + tableName + "\" " + @using + "(\n";
            var decls = columns.Select(c => SQLBuilder.SqlDecl(c.Key, c.Value));
            var decl = string.Join(",\n", decls.ToArray());
            query += decl;
            var fkconstraints = 
                string.Join(
                    ",\n", 
                    columns.Where(x => x.Value.ForeignKeyConstraint != null).Select(x =>
                        string.Format("FOREIGN KEY(\"{0}\") REFERENCES \"{1}\"(\"{2}\")",
                             x.Key, 
                             x.Value.ForeignKeyConstraint.TableName,
                             x.Value.ForeignKeyConstraint.ColumnName)));
            query += (fkconstraints.Length != 0) ? "," + fkconstraints : "";
            query += ")";

            return query;
        }
Beispiel #3
0
        private D3DDeviceService(IntPtr windowIntPtr)
        {
            isDeviceLost = false;
            m_pp = new PresentParameters
                                       {
                                           Windowed = true,
                                           SwapEffect = SwapEffect.Discard,
                                           PresentationInterval = PresentInterval.One,
                                           BackBufferFormat = Manager.Adapters.Default.CurrentDisplayMode.Format,
                                           BackBufferWidth = Manager.Adapters.Default.CurrentDisplayMode.Width,
                                           BackBufferHeight = Manager.Adapters.Default.CurrentDisplayMode.Height,
                                       };

            CreateFlags flags = new CreateFlags();
            Caps caps = Manager.GetDeviceCaps(0, DeviceType.Hardware);

            if(caps.DeviceCaps.SupportsHardwareTransformAndLight)
                flags |= CreateFlags.HardwareVertexProcessing;
            else
                flags |= CreateFlags.SoftwareVertexProcessing;

            if(caps.DeviceCaps.SupportsPureDevice)
                flags |= CreateFlags.PureDevice;

            D3DDevice = new Device(0, caps.DeviceType, windowIntPtr, flags, m_pp);
        }
        public Device CreateDevice(int adapter, DeviceType deviceType, IntPtr hFocusWindow, CreateFlags behaviorFlags,  PresentParameters presentParams)
        {
            IntPtr devicePtr = IntPtr.Zero;
            int res = Interop.Calli(comPointer, adapter, (int)deviceType, hFocusWindow, (int)behaviorFlags, (IntPtr)(void*)&presentParams,
                                       (IntPtr)(void*)&devicePtr,(*(IntPtr**)comPointer)[16]);

            if( res < 0 ) { throw new SharpDXException( res ); }
            return new Device( devicePtr );
        }
Beispiel #5
0
        ///////////////////////////////////////////////////////////////////////

        #region Internal Static Methods
        internal static ReturnCode UseStartupDefaults(
            InterpreterSettings interpreterSettings,
            CreateFlags createFlags,
            ref Result error
            )
        {
            if (interpreterSettings == null)
            {
                error = "invalid interpreter settings";
                return(ReturnCode.Error);
            }

            //
            // NOTE: Use the creation flags specified by the caller,
            //       ignoring the creation flags in the interpreter
            //       settings.  If there are existing policies and/or
            //       traces, make sure the creation flags are modified
            //       to skip adding the default policies and/or traces
            //       during interpreter creation.
            //
            if (interpreterSettings.Policies != null)
            {
                createFlags |= CreateFlags.NoCorePolicies;
            }

            if (interpreterSettings.Traces != null)
            {
                createFlags |= CreateFlags.NoCoreTraces;
            }

            interpreterSettings.CreateFlags = createFlags;

            //
            // NOTE: The interpreter host may be disposed now -OR- may
            //       end up being disposed later, so avoid copying it.
            //
            interpreterSettings.Host = null;

            //
            // NOTE: Nulling these out is not necessary when the creation
            //       flags are modified to skip adding default policies
            //       and traces (above).
            //
            // interpreterSettings.Policies = null;
            // interpreterSettings.Traces = null;

            //
            // NOTE: These startup settings are reset by this method to
            //       avoid having their values used when the command line
            //       arguments have been "locked" by the interpreter host.
            //
            interpreterSettings.Text        = null;
            interpreterSettings.LibraryPath = null;

            return(ReturnCode.Ok);
        }
Beispiel #6
0
        internal Dx11ImageSource()
        {
            var presentParams             = GetPresentParameters();
            const CreateFlags createFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve;

            _d3DContext = new Direct3DEx();
            _d3DDevice  = new DeviceEx(_d3DContext, 0, DeviceType.Hardware, IntPtr.Zero, createFlags, presentParams);

            StartD3D();
        }
        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
                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)));
                //Uncomment these lines to see the spite border areas
                //				donutTexture = TextureLoader.FromFile(device, MediaUtilities.FindFile("donuts.bmp"), 1024, 1024,
                //					1, 0,Format.A8R8G8B8, Pool.Managed, Filter.Point, Filter.Point, 0);

                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();

                hrt.Start();
            }
            catch (DirectXException) {
                // Catch any errors and return a failure
            }
        }
Beispiel #8
0
 public OutputSettings(int adapter, bool windowed, DeviceType devType, Format devFormat,
                       MultiSampleType antiAliasing, DepthFormat depthFormat, CreateFlags createFlags)
 {
     this.adapter      = adapter;
     this.windowed     = windowed;
     this.devType      = devType;
     this.devFormat    = devFormat;
     this.antiAliasing = antiAliasing;
     this.depthFormat  = depthFormat;
     this.createFlags  = createFlags;
 }
 public OutputSettings(int adapter, bool windowed, DeviceType devType, Format devFormat,
                       MultiSampleType antiAliasing, DepthFormat depthFormat, CreateFlags createFlags)
 {
     this.adapter = adapter;
     this.windowed = windowed;
     this.devType = devType;
     this.devFormat = devFormat;
     this.antiAliasing = antiAliasing;
     this.depthFormat = depthFormat;
     this.createFlags = createFlags;
 }
Beispiel #10
0
        public Task <CreateTablesResult> CreateTablesAsync <T, T2, T3>(CreateFlags createFlags = CreateFlags.None)

            where T : new()

            where T2 : new()

            where T3 : new()

        {
            return(CreateTablesAsync(createFlags, typeof(T), typeof(T2), typeof(T3)));
        }
 public GraphicsDeviceSettings(int adapter, bool windowed, DeviceType devType, Format devFormat,
                               MultiSampleType multisample, DepthFormat depthFormat, CreateFlags createFlags)
 {
     this.adapter = adapter;
     this.windowed = windowed;
     this.devType = devType;
     this.devFormat = devFormat;
     this.multisample = multisample;
     this.depthFormat = depthFormat;
     this.createFlags = createFlags;
 }
 public GraphicsDeviceSettings(int adapter, bool windowed, DeviceType devType, Format devFormat,
                               MultiSampleType multisample, DepthFormat depthFormat, CreateFlags createFlags)
 {
     this.adapter     = adapter;
     this.windowed    = windowed;
     this.devType     = devType;
     this.devFormat   = devFormat;
     this.multisample = multisample;
     this.depthFormat = depthFormat;
     this.createFlags = createFlags;
 }
        /*-------------------------------------------------------------------------
         * Deviceを作成する
         * 作成できなかったときの例外はスルーするので呼び出し側で対応すること
         * CreateType、DeviceTypeを指定する
         * ---------------------------------------------------------------------------*/
        public void Create(System.Windows.Forms.Form form, PresentParameters param, CreateType create_type, DeviceType device_type)
        {
            // 描画対象
            m_form = form;
            // デバイスタイプ
            m_device_type = device_type;
            // 作成方法
            m_create_type = create_type;

            // デフォルトのアダプタ番号
            m_adapter_index = Manager.Adapters.Default.Adapter;
            // デバイスの能力を取得する
            m_caps = Manager.GetDeviceCaps(m_adapter_index, device_type);

            // 作成パラメータ
            m_present_params = param;

            //
            m_create_flags = 0;
            switch (create_type)
            {
            case CreateType.BestPerformance:
                // 最適なものを選ぶ
                if (m_caps.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    // ハードウェアで頂点変換に対応している
                    m_create_flags |= CreateFlags.HardwareVertexProcessing;
                }
                else
                {
                    // ハードウェアで頂点変換に対応していない
                    m_create_flags |= CreateFlags.SoftwareVertexProcessing;
                }
                if ((m_caps.DeviceCaps.SupportsPureDevice) &&
                    (m_caps.DeviceCaps.SupportsHardwareTransformAndLight))
                {
                    // ピュアデバイスである
                    m_create_flags |= CreateFlags.PureDevice;
                }
                break;

            case CreateType.SoftwareVertexProcessing:
                // 頂点処理をCPUが行う
                m_create_flags |= CreateFlags.SoftwareVertexProcessing;
                break;

            default:
                throw new Exception("CreateTypeの指定が不正");
            }

            // デバイスを作成
            m_d3d_device = new Device(m_adapter_index, device_type, form,
                                      m_create_flags, m_present_params);
        }
Beispiel #14
0
        /// <summary>
        /// Executes a "create table if not exists" on the database. It also
        /// creates any specified indexes on the columns of the table. It uses
        /// a schema automatically generated from the specified type. You can
        /// later access this schema by calling GetMapping.
        /// </summary>
        /// <param name="ty">Type to reflect to a database table.</param>
        /// <param name="createFlags">Optional flags allowing implicit PK and indexes based on naming conventions.</param>
        /// <returns>
        /// The number of entries added to the database schema.
        /// </returns>
        public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None)
        {
            TableMapping map = null;

            if (_tables == null || !_tables.TryGetValue(ty.FullName, out map))
            {
                map = ToMapping(ty, createFlags);
            }

            return(InternalCreateTable(map));
        }
Beispiel #15
0
 static void CreateTable <T>(SQLiteConnection db, CreateFlags createFlags = CreateFlags.None)
 {
     try
     {
         db.CreateTable <T>(createFlags);
         Log.Info(TAG, $"Created db table {typeof(T).Name}.");
     }
     catch (Exception e)
     {
         Log.Error(TAG, $"Failed to create table {typeof(T).Name} with error {e}.");
     }
 }
Beispiel #16
0
        /// <summary>
        /// Creates the rendering device
        /// </summary>
        private void CreateDevice()
        {
            // Get the adapter ordinal
            int adapterOrdinal = Manager.Adapters.Default.Adapter;

            // set up capabilities
            Caps caps = Manager.GetDeviceCaps(adapterOrdinal,
                                              DeviceType.Hardware);
            CreateFlags flags = CreateFlags.SoftwareVertexProcessing;

            if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
            {
                flags = CreateFlags.HardwareVertexProcessing;
            }
            if (caps.DeviceCaps.SupportsPureDevice)
            {
                flags |= CreateFlags.PureDevice;
            }

            // ste up presentation
            m_presentation            = new PresentParameters();
            m_presentation.Windowed   = true;
            m_presentation.SwapEffect = SwapEffect.Discard;
            //m_presentation.PresentFlag = PresentFlag.None;
            //m_presentation.MultiSample = MultiSampleType.None;
            //m_presentation.BackBufferWidth = Width;
            //m_presentation.BackBufferHeight = Height;
            m_presentation.EnableAutoDepthStencil = true;
            m_presentation.AutoDepthStencilFormat = DepthFormat.D16;

            // create the device and attach event handlers
            m_device              = new Device(adapterOrdinal, DeviceType.Hardware, Handle, flags, m_presentation);
            m_device.DeviceLost  += new EventHandler(m_device_DeviceLost);
            m_device.DeviceReset += new EventHandler(m_device_DeviceReset);

            m_camera = new Camera(Width, Height);
            m_axis   = new Axis(m_device);
            //m_meshScene = new SimpleMeshScene(m_device, 0x01002752);
            //m_meshScene = new SimpleMeshScene(m_device, 0x0100005E);
            //m_meshScene = new SimpleMeshScene(m_device, 0x0100002C);
            m_meshScene = new SimpleMeshScene(m_device, 0x0100058F);

            //m_meshScene = new SimpleMeshScene(m_device, 0x010025e3);

            //m_meshScene = new SimpleMeshScene(m_device, 0x010000D6);

            m_device_DeviceReset(null, null);

            MouseMove  += new MouseEventHandler(RenderForm_MouseMove);
            MouseUp    += new MouseEventHandler(RenderForm_MouseUp);
            MouseWheel += new MouseEventHandler(RenderForm_MouseWheel);
            KeyUp      += new KeyEventHandler(RenderForm_KeyUp);
        }
Beispiel #17
0
 public static extern bool CreateDelta(
     [MarshalAs(UnmanagedType.I8)] FileTypeSet fileTypeSet,
     [MarshalAs(UnmanagedType.I8)] CreateFlags setFlags,
     [MarshalAs(UnmanagedType.I8)] CreateFlags resetFlags,
     string sourceName,
     string targetName,
     string sourceOptionsName,
     string targetOptionsName,
     DeltaInput globalOptions,
     IntPtr targetFileTime,
     [MarshalAs(UnmanagedType.U4)] HashAlgId hashAlgId,
     string deltaName);
 public GraphicsDevice3DOutputDescription(int adapter, bool windowed, DeviceType type,
                                          Format format, MultiSampleType multiSample,
                                          DepthFormat depthFormat, CreateFlags createFlags)
 {
     this.adapter = adapter;
     this.windowed = windowed;
     this.type = type;
     this.format = format;
     this.multiSample = multiSample;
     this.depthFormat = depthFormat;
     this.createFlags = createFlags;
 }
Beispiel #19
0
 public GraphicsDevice3DOutputDescription(int adapter, bool windowed, DeviceType type,
                                          Format format, MultiSampleType multiSample,
                                          DepthFormat depthFormat, CreateFlags createFlags)
 {
     this.adapter     = adapter;
     this.windowed    = windowed;
     this.type        = type;
     this.format      = format;
     this.multiSample = multiSample;
     this.depthFormat = depthFormat;
     this.createFlags = createFlags;
 }
Beispiel #20
0
        public TableMapping(Type type, IEnumerable <PropertyInfo> properties, CreateFlags createFlags = CreateFlags.None, IColumnInformationProvider infoProvider = null)
        {
            if (infoProvider == null)
            {
                infoProvider = new DefaultColumnInformationProvider();
            }

            MappedType = type;

            var tableAttr = type.GetTypeInfo().GetCustomAttributes <TableAttribute>().FirstOrDefault();

            TableName = tableAttr != null ? tableAttr.Name : MappedType.Name;

            var props = properties;

            var cols = new List <Column>();

            foreach (var p in props)
            {
                var ignore = infoProvider.IsIgnored(p);

                if (p.CanWrite && !ignore)
                {
                    cols.Add(new Column(p, createFlags));
                }
            }
            Columns = cols.ToArray();
            foreach (var c in Columns)
            {
                if (c.IsAutoInc && c.IsPK)
                {
                    _autoPk = c;
                }
                if (c.IsPK)
                {
                    PKs.Add(c);
                }
            }

            HasAutoIncPK = _autoPk != null;

            if (PK != null)
            {
                GetByPrimaryKeySql  = string.Format("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
                PkWhereSql          = PKs.Aggregate(new StringBuilder(), (sb, pk) => sb.AppendFormat(" \"{0}\" = ? and", pk.Name), sb => sb.Remove(sb.Length - 3, 3).ToString());
                GetByPrimaryKeysSql = String.Format("select * from \"{0}\" where {1}", TableName, PkWhereSql);
            }
            else
            {
                // People should not be calling Get/Find without a PK
                GetByPrimaryKeysSql = GetByPrimaryKeySql = string.Format("select * from \"{0}\" limit 1", TableName);
            }
        }
Beispiel #21
0
        /// <summary>
        /// The create device.
        /// </summary>
        /// <param name="renderpanel">The renderpanel.</param>
        /// <remarks></remarks>
        public void CreateDevice(Control renderpanel)
        {
            PresentParameters presentParams = new PresentParameters();

            presentParams.Windowed = true; // We don't want to run fullscreen

            /*
             * presentParams.BackBufferCount = 1; //Number of backbuffers to create
             * presentParams.BackBufferFormat = Manager.Adapters.Default.CurrentDisplayMode.Format; //The current format of the display device
             * presentParams.BackBufferWidth = renderpanel.Width;
             * presentParams.BackBufferHeight = renderpanel.Height;
             */
            presentParams.SwapEffect             = SwapEffect.Discard; // Discard the frames
            presentParams.AutoDepthStencilFormat = DepthFormat.D16;    // 24 bits for the depth and 8 bits for the stencil
            presentParams.EnableAutoDepthStencil = true;               // Let direct3d handle the depth buffers for the application
            presentParams.PresentationInterval   = PresentInterval.One;

            IEnumerator i = Manager.Adapters.GetEnumerator();

            while (i.MoveNext())
            {
                AdapterInformation ai = i.Current as AdapterInformation;

                int adapterOrdinal = ai.Adapter;

                Caps hardware = Manager.GetDeviceCaps(adapterOrdinal, DeviceType.Hardware);

                CreateFlags flags = CreateFlags.SoftwareVertexProcessing;

                if (hardware.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    flags = CreateFlags.HardwareVertexProcessing;

                    // if (hardware.MaxActiveLights > 0)
                    // this.lighting = true;
                    // flags |= CreateFlags.PureDevice;
                    // if (hardware.DeviceCaps.m
                }

                device = new Device(adapterOrdinal, hardware.DeviceType, renderpanel, flags, presentParams);

                // Create a device
                if (device != null)
                {
                    break;
                }
            }

            device.DeviceReset += OnResetDevice;
            this.pause          = false;
            OnResetDevice(device, null);
        }
Beispiel #22
0
            public Column(PropertyInfo prop, CreateFlags createFlags = CreateFlags.None)
            {
                var colAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();

                _prop = prop;
                Name  = colAttr == null ? prop.Name : colAttr.Name;
                //If this type is Nullable<T> then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead
                ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                Collation  = Orm.Collation(prop);

                IsPK = Orm.IsPK(prop) ||
                       (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) &&
                        string.Compare(prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0);

                IsCK = Orm.IsCK(prop);

                IsFK = Orm.IsFK(prop);
                if (IsFK)
                {
                    ForeignKeyAttribute attr     = prop.GetCustomAttribute <ForeignKeyAttribute>(true);
                    TableMapping        refTable = new TableMapping(attr.ReferenceTable);
                    string refColumnName         = attr.ReferenceColumn ?? this.Name;
                    var    refColumns            = refTable.Columns.Select(c => c).Where(c => c.Name == refColumnName).ToArray();
                    if (refColumns.Length > 0)
                    {
                        FK = new ForeignKey(this, attr.ReferenceTable, refColumns[0]);
                    }
                    else
                    {
                        throw new Exception(string.Format("The referenced column \"{0}\" in {1} doesn't exist", refColumnName, this.Name));
                    }
                }

                var isAuto = Orm.IsAutoInc(prop) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK));

                IsAutoGuid = isAuto && ColumnType == typeof(Guid);
                IsAutoInc  = isAuto && !IsAutoGuid;

                Indices = Orm.GetIndices(prop);
                if (!Indices.Any() &&
                    !IsPK &&
                    ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex) &&
                    Name.EndsWith(Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase)
                    )
                {
                    Indices = new IndexedAttribute[] { new IndexedAttribute() };
                }
                IsNullable      = !(IsPK || Orm.IsMarkedNotNull(prop));
                MaxStringLength = Orm.MaxStringLength(prop);

                StoreAsText = prop.PropertyType.GetTypeInfo().GetCustomAttribute(typeof(StoreAsTextAttribute), false) != null;
            }
Beispiel #23
0
        public static IntPtr CreateDevice(IntPtr ptr, int adapter, DeviceType deviceType, IntPtr hFocusWindow,
                                          CreateFlags behaviorFlags, PresentParameters *presentParams)
        {
            IntPtr devicePtr = IntPtr.Zero;
            int    res       = Interop.Calli(ptr, adapter, (int)deviceType, hFocusWindow, (int)behaviorFlags, (IntPtr)presentParams,
                                             (IntPtr)(void *)&devicePtr, (*(IntPtr **)ptr)[16]);

            if (res < 0)
            {
                throw new SharpDXException(res);
            }
            return(devicePtr);
        }
Beispiel #24
0
 public TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None)
 {
     if (_mappings == null)
     {
         _mappings = new Dictionary <string, TableMapping>();
     }
     if (!_mappings.TryGetValue(type.FullName, out TableMapping value))
     {
         value = new TableMapping(type, createFlags);
         _mappings[type.FullName] = value;
     }
     return(value);
 }
Beispiel #25
0
			///<summary>Inverse of ToString(). String to DirectXDeviceFormat.</summary>
			public DirectXDeviceFormat(string directXFormat){
				if(directXFormat.IndexOf(';')<0){
					//Invalid format.
					return;
				}
				string[] settings=directXFormat.Split(new char[] {';'});
				adapter=Manager.Adapters[PIn.Int(settings[0])];
				deviceType=(DeviceType)Enum.Parse(typeof(DeviceType),settings[1]);
				createFlags=(CreateFlags)PIn.Int(settings[2]);
				depthStencilFormat=(DepthFormat)Enum.Parse(typeof(DepthFormat),settings[3]);
				backBufferFormat=(Format)Enum.Parse(typeof(Format),settings[4]);
				maxMultiSampleType=(MultiSampleType)Enum.Parse(typeof(MultiSampleType),settings[5]);
			}
Beispiel #26
0
        /// <summary>
        /// Override this method to modify how the device is created.
        /// </summary>
        /// <returns>The new device.</returns>
        protected virtual Device CreateDevice()
        {
            try {
                Device device;
                presentParams.Windowed   = true;               // We don't want to run fullscreen
                presentParams.SwapEffect = SwapEffect.Discard; // Discard the frames

                // Uncomment to enable depth buffer for 3D rendering.
                // Leave these lines commented out if you are rendering in 2D as
                // defining a depth buffer will incur a performance hit.
                //presentParams.EnableAutoDepthStencil = true; // Turn on a Depth stencil
                //presentParams.AutoDepthStencilFormat = DepthFormat.D16; // And the stencil format

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

                // Get the capabilities of the adapter
                Caps caps = Manager.GetDeviceCaps(adapterOrdinal, DeviceType.Hardware);

                // If the device supports our minimum required user clip planes we will try
                // to do hardware vertex processing.
                if (caps.MaxUserClipPlanes >= MIN_USER_CLIPPLANES)
                {
                    // Do we support hardware vertex processing?
                    if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                    {
                        flags = CreateFlags.HardwareVertexProcessing;
                    }

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

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

                return(device);
            }
            catch (DirectXException e) {
                // Catch any errors and return a failure
                Console.WriteLine("Unable to initialize Direct3D");
                Console.WriteLine(e);
                return(null);
            }
        }
 public async Task CreateDatabaseTables(List <Type> tables, CreateFlags tableCreateFlags)
 {
     foreach (Type item in tables)
     {
         try
         {
             await SqlCon.CreateTableAsync(item, tableCreateFlags).ConfigureAwait(false);
         }
         catch (Exception ex)
         {
             throw new Exception(ex.Message);
         }
     }
 }
Beispiel #28
0
		public TableMapping(Type type, IEnumerable<PropertyInfo> properties, CreateFlags createFlags = CreateFlags.None, IColumnInformationProvider infoProvider = null)
        {
			if (infoProvider == null)
			{
				infoProvider = new DefaultColumnInformationProvider ();
			}

            MappedType = type;

            var tableAttr = type.GetTypeInfo().GetCustomAttributes<TableAttribute>().FirstOrDefault();

            TableName = tableAttr != null ?  tableAttr.Name : MappedType.Name;

            var props = properties;

            var cols = new List<Column>();
            foreach (var p in props)
            {
				var ignore = infoProvider.IsIgnored (p);

                if (p.CanWrite && !ignore)
                {
                    cols.Add(new Column(p, createFlags));
                }
            }
            Columns = cols.ToArray();
            foreach (var c in Columns)
            {
                if (c.IsAutoInc && c.IsPK)
                {
                    _autoPk = c;
                }
                if (c.IsPK)
                {
                    PK = c;
                }
            }

            HasAutoIncPK = _autoPk != null;

            if (PK != null)
            {
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
            }
            else
            {
                // People should not be calling Get/Find without a PK
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" limit 1", TableName);
            }
        }
        public TableMapping(ISQLitePlatform platformImplementation, Type type,
            CreateFlags createFlags = CreateFlags.None)
        {
            _sqlitePlatform = platformImplementation;
            MappedType = type;

            var tableAttr = (TableAttribute) type.GetTypeInfo().GetCustomAttributes(typeof (TableAttribute), true).FirstOrDefault();

            TableName = tableAttr != null ? tableAttr.Name : MappedType.Name;

            IEnumerable<PropertyInfo> props = _sqlitePlatform.ReflectionService.GetPublicInstanceProperties(MappedType);

            var cols = new List<Column>();
            foreach (PropertyInfo p in props)
            {
                bool ignore = p.GetCustomAttributes(typeof (IgnoreAttribute), true).Any();

                if (p.CanWrite && !ignore)
                {
                    cols.Add(new Column(p, createFlags));
                }
            }
            Columns = cols.ToArray();
            foreach (Column c in Columns)
            {
                if (c.IsAutoInc && c.IsPK)
                {
                    _autoPk = c;
                }
                if (c.IsPK)
                {
                    PKs.Add(c);
                }
            }

            HasAutoIncPK = _autoPk != null;

            if (PK != null)
            {
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
                PkWhereSql = PKs.Aggregate(new StringBuilder(), (sb, pk) => sb.AppendFormat(" \"{0}\" = ? and", pk.Name), sb => sb.Remove(sb.Length - 3, 3).ToString());
                GetByPrimaryKeysSql = String.Format("select * from \"{0}\" where {1}", TableName, PkWhereSql);
            }
            else
            {
                // People should not be calling Get/Find without a PK
                GetByPrimaryKeysSql = GetByPrimaryKeySql = string.Format("select * from \"{0}\" limit 1", TableName);
            }
        }
Beispiel #30
0
 public bool Direct3DInit()
 {
     try
     {
         Direct3D           direct3D       = new Direct3D();
         AdapterInformation defaultAdapter = direct3D.Adapters.DefaultAdapter;
         CreateFlags        createFlags    = (direct3D.GetDeviceCaps(defaultAdapter.Adapter, SlimDX.Direct3D9.DeviceType.Hardware).DeviceCaps & DeviceCaps.HWTransformAndLight) != DeviceCaps.HWTransformAndLight ? CreateFlags.SoftwareVertexProcessing : CreateFlags.HardwareVertexProcessing;
         this.GlobalData.presentParams = new PresentParameters()
         {
             BackBufferWidth    = 640,
             BackBufferHeight   = 480,
             BackBufferFormat   = defaultAdapter.CurrentDisplayMode.Format,
             DeviceWindowHandle = this.Form_Main.Handle,
             Windowed           = !this.fullWindow,
             PresentFlags       = PresentFlags.DiscardDepthStencil,
             SwapEffect         = SwapEffect.Discard
         };
         if (this.presentInterval == 1)
         {
             this.GlobalData.presentParams.PresentationInterval = !this.verticalSync ? PresentInterval.Immediate : PresentInterval.Default;
         }
         else if (this.fullWindow && this.verticalSync)
         {
             if (this.presentInterval == 2)
             {
                 this.GlobalData.presentParams.PresentationInterval = PresentInterval.Two;
             }
             else if (this.presentInterval == 3)
             {
                 this.GlobalData.presentParams.PresentationInterval = PresentInterval.Three;
             }
         }
         else
         {
             this.GlobalData.presentParams.PresentationInterval = PresentInterval.Immediate;
         }
         this.DeviceMain = new SlimDX.Direct3D9.Device(direct3D, defaultAdapter.Adapter, SlimDX.Direct3D9.DeviceType.Hardware, this.Form_Main.Handle, createFlags, new PresentParameters[1]
         {
             this.GlobalData.presentParams
         });
         this.GlobalData.SpriteMain = new MySprite(this.DeviceMain);
         return(true);
     }
     catch
     {
         int num = (int)MessageBox.Show("DirectX初始化失败", "DirectX Initial Error");
         return(false);
     }
 }
Beispiel #31
0
        private static void StartD3D()
        {
            if (_activeClients != 0)
            {
                return;
            }

            var presentParams             = GetPresentParameters();
            const CreateFlags createFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded |
                                            CreateFlags.FpuPreserve;

            _d3DContext = new Direct3DEx();
            _d3DDevice  =
                new DeviceEx(_d3DContext, 0, DeviceType.Hardware, IntPtr.Zero, createFlags, presentParams);
        }
Beispiel #32
0
            public D3D9()
            {
                var presentparams = new PresentParameters
                {
                    Windowed             = true,
                    SwapEffect           = SwapEffect.Discard,
                    DeviceWindowHandle   = GetDesktopWindow(),
                    PresentationInterval = PresentInterval.Default
                };

                const CreateFlags deviceFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve;

                direct3d = new Direct3DEx();
                device   = new DeviceEx(direct3d, 0, DeviceType.Hardware, IntPtr.Zero, deviceFlags, presentparams);
            }
Beispiel #33
0
        /// <summary>
        /// Retrieves the mapping that is automatically generated for the given type.
        /// </summary>
        /// <param name="type">
        /// The type whose mapping to the database is returned.
        /// </param>
        /// <param name="createFlags">
        /// Optional flags allowing implicit PK and indexes based on naming conventions
        /// </param>
        /// <returns>
        /// The mapping represents the schema of the columns of the database and contains
        /// methods to set and get properties of objects.
        /// </returns>
        private TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None)
        {
            if (_mappings == null)
            {
                _mappings = new Dictionary <string, TableMapping>();
            }
            TableMapping map;

            if (!_mappings.TryGetValue(type.FullName, out map))
            {
                map = new TableMapping(type, createFlags);
                _mappings[type.FullName] = map;
            }
            return(map);
        }
Beispiel #34
0
        ///////////////////////////////////////////////////////////////////////

        public static bool HasFlags(
            CreateFlags flags,
            CreateFlags hasFlags,
            bool all
            )
        {
            if (all)
            {
                return((flags & hasFlags) == hasFlags);
            }
            else
            {
                return((flags & hasFlags) != CreateFlags.None);
            }
        }
Beispiel #35
0
 public Task <CreateTablesResult> CreateTablesAsync(CreateFlags createFlags = CreateFlags.None, params Type[] types)
 {
     return(Task.Factory.StartNew(() => {
         CreateTablesResult result = new CreateTablesResult();
         var conn = GetConnection();
         using (conn.Lock()) {
             foreach (Type type in types)
             {
                 int aResult = conn.CreateTable(type, createFlags);
                 result.Results[type] = aResult;
             }
         }
         return result;
     }));
 }
        public TableMapping(ISQLitePlatform platformImplementation, Type type,
                            CreateFlags createFlags = CreateFlags.None)
        {
            _sqlitePlatform = platformImplementation;
            MappedType      = type;

            var tableAttr = (TableAttribute)type.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault();

            TableName = tableAttr != null ? tableAttr.Name : MappedType.Name;

            IEnumerable <PropertyInfo> props = _sqlitePlatform.ReflectionService.GetPublicInstanceProperties(MappedType);

            var cols = new List <Column>();

            foreach (PropertyInfo p in props)
            {
                bool ignore = p.GetCustomAttributes(typeof(IgnoreAttribute), true).Length > 0;

                if (p.CanWrite && !ignore)
                {
                    cols.Add(new Column(p, createFlags));
                }
            }
            Columns = cols.ToArray();
            foreach (Column c in Columns)
            {
                if (c.IsAutoInc && c.IsPK)
                {
                    _autoPk = c;
                }
                if (c.IsPK)
                {
                    PK = c;
                }
            }

            HasAutoIncPK = _autoPk != null;

            if (PK != null)
            {
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
            }
            else
            {
                // People should not be calling Get/Find without a PK
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" limit 1", TableName);
            }
        }
Beispiel #37
0
        private void InitializeReference()
        {
            PresentParameters presentParameters = new PresentParameters();

            presentParameters.Windowed               = true;
            presentParameters.SwapEffect             = SwapEffect.Discard;
            presentParameters.AutoDepthStencilFormat = DepthFormat.D16;
            presentParameters.EnableAutoDepthStencil = true;

            m_ReferenceForm         = new System.Windows.Forms.Control("Reference", 0, 0, 1, 1);
            m_ReferenceForm.Visible = false;

            int adapterOrdinal = 0;

            try
            {
                // Store the default adapter
                adapterOrdinal = Manager.Adapters.Default.Adapter;
            }
            catch
            {
                // User probably needs to upgrade DirectX or install a 3D capable graphics adapter
                throw new NotAvailableException();
            }

            //		DeviceType dType = DeviceType.Reference;

            CreateFlags flags = CreateFlags.SoftwareVertexProcessing;

            flags |= CreateFlags.MultiThreaded | CreateFlags.FpuPreserve;

/*
 *                      try
 *                      {
 *                              // Create our m_Device3d
 *                              m_Device3dReference = new Device(adapterOrdinal, dType, m_ReferenceForm, flags, presentParameters);
 *                      }
 *                      catch( Microsoft.DirectX.DirectXException	)
 *                      {
 *                              throw new NotSupportedException("Unable to create the Direct3D m_Device3d.");
 *                      }
 *
 *                      // Hook the m_Device3d reset event
 *                      m_Device3dReference.DeviceReset += new EventHandler(OnDeviceReset);
 *              //	m_Device3dReference.DeviceResizing += new CancelEventHandler(m_Device3d_DeviceResizing);
 *                      OnDeviceReset(m_Device3dReference, null);
 */
        }
        /// <summary>
        ///     Creates an instance of Discord to initialize the SDK. This is the overlord of all things Discord. We like to call
        ///     her Nelly.
        /// </summary>
        /// <exception cref="InitializedException"></exception>
        public Discord(long clientId, CreateFlags flags)
        {
            if (IsInitialized)
            {
                throw new InitializedException("The Discord game SDK is already initialized!");
            }

            this.clientId = clientId;
            createFlags   = flags;

            selfHandle = GCHandle.Alloc(this);

            applicationEvents    = new ApplicationManager.FFIEvents();
            applicationEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(applicationEvents));

            userEvents    = new UserManager.FFIEvents();
            userEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(userEvents));

            imageEvents    = new ImageManager.FFIEvents();
            imageEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(imageEvents));

            activityEvents    = new ActivityManager.FFIEvents();
            activityEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(activityEvents));

            relationshipEvents    = new RelationshipManager.FFIEvents();
            relationshipEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(relationshipEvents));

            lobbyEvents    = new LobbyManager.FFIEvents();
            lobbyEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(lobbyEvents));

            networkEvents    = new NetworkManager.FFIEvents();
            networkEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(networkEvents));

            overlayEvents    = new OverlayManager.FFIEvents();
            overlayEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(overlayEvents));

            storageEvents    = new StorageManager.FFIEvents();
            storageEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(storageEvents));

            storeEvents    = new StoreManager.FFIEvents();
            storeEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(storeEvents));

            voiceEvents    = new VoiceManager.FFIEvents();
            voiceEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(voiceEvents));

            achievementEvents    = new AchievementManager.FFIEvents();
            achievementEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(achievementEvents));
        }
Beispiel #39
0
        /// <summary>
        /// Retrieves the mapping that is automatically generated for the given type.
        /// </summary>
        /// <returns>
        /// The mapping represents the schema of the columns of the database and contains
        /// methods to set and get properties of objects.
        /// </returns>
        public static TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None)
        {
            TableMapping map;

            if (!_mappings.TryGetValue(type, out map))
            {
                map = new TableMapping(type, createFlags);
                if (!_mappings.TryAdd(type, map))
                {
                    // concurrent add attempt this add, retreive a fresh copy
                    _mappings.TryGetValue(type, out map);
                }
            }

            return(map);
        }
Beispiel #40
0
        /// <summary>
        /// 创建表实体映射
        /// </summary>
        /// <param name="ty"></param>
        /// <returns></returns>
        public TableMapping ToMapping(Type ty, CreateFlags createFlags = CreateFlags.None)
        {
            if (_tables == null)
            {
                _tables = new Dictionary <string, TableMapping>();
            }

            TableMapping map;

            if (!_tables.TryGetValue(ty.FullName, out map))
            {
                map = GetMapping(ty, createFlags);
                _tables.Add(ty.FullName, map);
            }
            return(map);
        }
Beispiel #41
0
        public TableMapping(ISQLitePlatform platformImplementation, Type type,
                            CreateFlags createFlags = CreateFlags.None)
        {
            _sqlitePlatform = platformImplementation;
            MappedType = type;

            var tableAttr = type.GetTypeInfo().CustomAttributes.FirstOrDefault(data => data.AttributeType == typeof(TableAttribute));

            TableName = tableAttr != null ? (string)tableAttr.ConstructorArguments.FirstOrDefault().Value : MappedType.Name;

            IEnumerable<PropertyInfo> props = _sqlitePlatform.ReflectionService.GetPublicInstanceProperties(MappedType);

            var cols = new List<Column>();
            foreach (PropertyInfo p in props)
            {
                bool ignore = p.GetCustomAttributes<IgnoreAttribute>(true).Any();

                if (p.CanWrite && !ignore)
                {
                    cols.Add(new Column(p, createFlags));
                }
            }
            Columns = cols.ToArray();
            foreach (Column c in Columns)
            {
                if (c.IsAutoInc && c.IsPK)
                {
                    _autoPk = c;
                }
                if (c.IsPK)
                {
                    PK = c;
                }
            }

            HasAutoIncPK = _autoPk != null;

            if (PK != null)
            {
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
            }
            else
            {
                // People should not be calling Get/Find without a PK
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" limit 1", TableName);
            }
        }
        public TableMapping(Type type, IEnumerable<PropertyInfo> properties, CreateFlags createFlags = CreateFlags.None)
        {
            MappedType = type;

            var tableAttr = type.GetTypeInfo().CustomAttributes.FirstOrDefault(data => data.AttributeType == typeof (TableAttribute));

            TableName = tableAttr != null ? (string) tableAttr.ConstructorArguments.FirstOrDefault().Value : MappedType.Name;

            var props = properties;

            var cols = new List<Column>();
            foreach (var p in props)
            {
                var ignore = p.IsDefined(typeof (IgnoreAttribute), true);

                if (p.CanWrite && !ignore)
                {
                    cols.Add(new Column(p, createFlags));
                }
            }
            Columns = cols.ToArray();
            foreach (var c in Columns)
            {
                if (c.IsAutoInc && c.IsPK)
                {
                    _autoPk = c;
                }
                if (c.IsPK)
                {
                    PK = c;
                }
            }

            HasAutoIncPK = _autoPk != null;

            if (PK != null)
            {
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
            }
            else
            {
                // People should not be calling Get/Find without a PK
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" limit 1", TableName);
            }
        }
Beispiel #43
0
 public void InitializeDevice(DeviceType devType, CreateFlags devFlags)
 {
     this._devType = devType;
     this._devFlags = devFlags;
     this._device = new Device(this._adpNum, devType, this._ctrl, devFlags, this._presentParams);
     this._device.DeviceReset += new EventHandler(this.device_onDeviceReset);
 }
Beispiel #44
0
 /// <summary>
 /// Creates a device to represent the display adapter.
 /// </summary>
 /// <param name="direct3D">an instance of <see cref="SharpDX.Direct3D9.Direct3D"/></param>
 /// <param name="adapter">Ordinal number that denotes the display adapter. {{D3DADAPTER_DEFAULT}} is always the primary display adapter.</param>
 /// <param name="deviceType">Member of the <see cref="SharpDX.Direct3D9.DeviceType"/> enumerated type that denotes the desired device type. If the desired device type is not available, the method will fail.</param>
 /// <param name="controlHandle">The focus window alerts Direct3D when an application switches from foreground mode to background mode. See Remarks. 	   For full-screen mode, the window specified must be a top-level window. For windowed mode, this parameter may be NULL only if the hDeviceWindow member of pPresentationParameters is set to a valid, non-NULL value.</param>
 /// <param name="createFlags">Combination of one or more options that control device creation. For more information, see {{D3DCREATE}}.</param>
 /// <param name="presentParameters">Pointer to a <see cref="SharpDX.Direct3D9.PresentParameters"/> structure, describing the presentation parameters for the device to be created. If BehaviorFlags specifies {{D3DCREATE_ADAPTERGROUP_DEVICE}}, pPresentationParameters is an array. Regardless of the number of heads that exist, only one depth/stencil surface is automatically created. For Windows 2000 and Windows XP, the full-screen device display refresh rate is set in the following order:   User-specified nonzero ForcedRefreshRate registry key, if supported by the device. Application-specified nonzero refresh rate value in the presentation parameter. Refresh rate of the latest desktop mode, if supported by the device. 75 hertz if supported by the device. 60 hertz if supported by the device. Device default.  An unsupported refresh rate will default to the closest supported refresh rate below it.  For example, if the application specifies 63 hertz, 60 hertz will be used. There are no supported refresh rates below 57 hertz. pPresentationParameters is both an input and an output parameter. Calling this method may change several members including:  If BackBufferCount, BackBufferWidth, and BackBufferHeight  are 0 before the method is called, they will be changed when the method returns. If BackBufferFormat equals <see cref="SharpDX.Direct3D9.Format.Unknown"/> before the method is called, it will be changed when the method returns.</param>
 /// <remarks>
 /// This method returns a fully working device interface, set to the required display mode (or windowed), and allocated with the appropriate back buffers. To begin rendering, the application needs only to create and set a depth buffer (assuming EnableAutoDepthStencil is FALSE in <see cref="SharpDX.Direct3D9.PresentParameters"/>). When you create a Direct3D device, you supply two different window parameters: a focus window (hFocusWindow) and a device window (the hDeviceWindow in <see cref="SharpDX.Direct3D9.PresentParameters"/>). The purpose of each window is:  The focus window alerts Direct3D when an application switches from foreground mode to background mode (via Alt-Tab, a mouse click, or some other method). A single focus window is shared by each device created by an application. The device window determines the location and size of the back buffer on screen. This is used by Direct3D when the back buffer contents are copied to the front buffer during {{Present}}.  This method should not be run during the handling of WM_CREATE. An application should never pass a window handle to Direct3D while handling WM_CREATE.  Any call to create, release, or reset the device must be done using the same thread as the window procedure of the focus window. Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and at least one of these vertex processing flags must be specified when calling this method. Back buffers created as part of the device are only lockable if D3DPRESENTFLAG_LOCKABLE_BACKBUFFER is specified in the presentation parameters. (Multisampled back buffers and depth surfaces are never lockable.) The methods {{Reset}}, <see cref="SharpDX.ComObject"/>, and {{TestCooperativeLevel}} must be called from the same thread that used this method to create a device. D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling CreateDevice, {{Reset}}, and {{CreateAdditionalSwapChain}}. This means the application does not have to query the current desktop format before calling CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified. If you attempt to create a device on a 0x0 sized window, CreateDevice will fail.
 /// </remarks>
 /// <unmanaged>HRESULT CreateDevice([None] UINT Adapter,[None] D3DDEVTYPE DeviceType,[None] HWND hFocusWindow,[None] int BehaviorFlags,[None] D3DPRESENT_PARAMETERS* pPresentationParameters,[None] IDirect3DDevice9** ppReturnedDeviceInterface)</unmanaged>
 public DeviceEx(Direct3DEx direct3D, int adapter, DeviceType deviceType, IntPtr controlHandle, CreateFlags createFlags, PresentParameters presentParameters)
     : base(IntPtr.Zero)
 {
     direct3D.CreateDeviceEx(adapter, deviceType, controlHandle, (int)createFlags, new[] { presentParameters }, null, this);
 }
 internal static void CreateTableIfNotExists(this IDatabaseConnection conn, string tableName, CreateFlags createFlags, IReadOnlyDictionary<string, ColumnMapping> columns)
 {
     var query = SQLBuilder.CreateTableIfNotExists(tableName, createFlags, columns);
     conn.Execute(query);
 }
        /// <summary>
        /// Create a not transaction create request packet for client to create new or open share on server.
        /// </summary>
        /// <param name = "treeId">the valid tree connect id, must be response by server of the tree connect. </param>
        /// <param name = "fileName">A string that represents the name of the file to open or create. </param>
        /// <param name = "desiredAccess">
        /// Access wanted. This value MUST be specified in the ACCESS_MASK format, as specified in [CIFS] section 3.7. 
        /// </param>
        /// <param name = "extFileAttributes">Extended attributes and flags for this file or directory. </param>
        /// <param name = "shareAccess">Type of shared access requested for this file or directory. </param>
        /// <param name = "createDisposition">The action to take if a file does or does not exist. </param>
        /// <param name = "createOptions">The options to use if creating the file or directory. </param>
        /// <param name = "impersonationLevel">
        /// This field specifies the information given to the server about the client and how the server MUST   
        /// represent, or impersonate, the client. 
        /// </param>
        /// <param name = "createFlags">
        /// A 32-bit field containing a set of options that specify the security tracking mode. 
        /// </param>
        /// <param name="securityDescriptor">The security descriptor to use when requesting access to the file</param>
        /// <param name="extendedAttributes">
        /// The list of extended attributes that SHOULD be applied to the new file.
        /// </param>
        /// <returns>a nt transaction create request packet</returns>
        public virtual SmbNtTransactCreateRequestPacket CreateNtTransCreateRequest(
            ushort treeId,
            string fileName,
            NtTransactDesiredAccess desiredAccess,
            SMB_EXT_FILE_ATTR extFileAttributes,
            NtTransactShareAccess shareAccess,
            NtTransactCreateDisposition createDisposition,
            NtTransactCreateOptions createOptions,
            NtTransactImpersonationLevel impersonationLevel,
            CreateFlags createFlags,
            RawSecurityDescriptor securityDescriptor,
            FILE_FULL_EA_INFORMATION[] extendedAttributes)
        {
            Cifs.SmbNtTransactCreateRequestPacket request = this.cifsClient.CreateNtTransactCreateRequest(
                this.MessageId, this.GetSessionIdByTreeId(treeId), treeId,
                (SmbFlags)this.capability.Flag, (SmbFlags2)this.capability.Flags2,
                this.capability.MaxSetupCount, this.capability.MaxParameterCount, this.capability.MaxDataCount,
                (NtTransactFlags)createFlags,
                0, // No root directory
                desiredAccess,
                0, // AllocationSize should be 0
                extFileAttributes, shareAccess, createDisposition, (Cifs.NtTransactCreateOptions)createOptions,
                impersonationLevel,
                (NtTransactSecurityFlags)0x00,
                fileName,
                securityDescriptor, // No security descriptor
                extendedAttributes // No extended attributes
                );

            return new SmbNtTransactCreateRequestPacket(request);
        }
        /// <summary>
        /// Initializes the Direct3D objects and sets the Available flag
        /// </summary>
        private void InitializeDirect3D()
        {
            DirectXStatus = DirectXStatus.Unavailable_Unknown;

            ReleaseDevice();
            ReleaseDirect3D();

            // assume that we can't run at all under terminal services
            //if (GetSystemMetrics(SM_REMOTESESSION) != 0)
            //{
            //    DirectXStatus = DirectXStatus.Unavailable_RemoteSession;
            //    return;
            //}

            //int renderingTier = (RenderCapability.Tier >> 16);
            //if (renderingTier < 2)
            //{
                //DirectXStatus = DirectXStatus.Unavailable_LowTier;
                //return;
            //}

#if USE_XP_MODE
         _direct3D = new Direct3D();
         UseDeviceEx = false;
#else
            try
            {
                direct3DEx = new Direct3DEx();
                UseDeviceEx = true;
            }
            catch
            {
                try
                {
                    direct3D = new Direct3D();
                    UseDeviceEx = false;
                }
                catch (Direct3DX9NotFoundException)
                {
                    DirectXStatus = DirectXStatus.Unavailable_MissingDirectX;
                    return;
                }
                catch
                {
                    DirectXStatus = DirectXStatus.Unavailable_Unknown;
                    return;
                }
            }
#endif

            bool ok;
            Result result;

            ok = Direct3D.CheckDeviceType(0, DeviceType.Hardware, adapterFormat, backbufferFormat, true, out result);
            if (!ok)
            {
                //const int D3DERR_NOTAVAILABLE = -2005530518;
                //if (result.Code == D3DERR_NOTAVAILABLE)
                //{
                //   ReleaseDirect3D();
                //   Available = Status.Unavailable_NotReady;
                //   return;
                //}
                ReleaseDirect3D();
                return;
            }

            ok = Direct3D.CheckDepthStencilMatch(0, DeviceType.Hardware, adapterFormat, backbufferFormat, depthStencilFormat, out result);
            if (!ok)
            {
                ReleaseDirect3D();
                return;
            }

            Capabilities deviceCaps = Direct3D.GetDeviceCaps(0, DeviceType.Hardware);
            if ((deviceCaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
                createFlags |= CreateFlags.HardwareVertexProcessing;
            else
                createFlags |= CreateFlags.SoftwareVertexProcessing;

            DirectXStatus = DirectXStatus.Available;

            return;
        }
Beispiel #48
0
        public string Save(string title,
                           string section,
                           string text,
                           string summary,
                           MinorFlags minor,
                           CreateFlags create,
                           WatchFlags watch,
                           SaveFlags mode,
                           bool bot,
                           string basetimestamp,
                           string starttimestamp,
                           string token)
        {
            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException("Title shouldn't be empty.", "title");
            }
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentException("Token shouldn't be empty.", "token");
            }

            ParameterCollection parameters = new ParameterCollection
            {
                { "title", title },
                { "token", token }
            };
            if (mode == SaveFlags.Replace && !string.IsNullOrEmpty(section))
            {
                parameters.Add("section", section);
            }
            if (minor != MinorFlags.None)
            {
                parameters.Add(minor.ToString().ToLower());
            }
            if (create != CreateFlags.None)
            {
                parameters.Add(create.ToString().ToLower());
            }
            if (watch != WatchFlags.None)
            {
                parameters.Add("watchlist", watch.ToString().ToLower());
            }
            if (mode == SaveFlags.Append)
            {
                parameters.Add("appendtext", text);
            }
            else if (mode == SaveFlags.Prepend)
            {
                parameters.Add("prependtext", text);
            }
            else
            {
                parameters.Add("text", text);
            }
            if (bot)
            {
                parameters.Add("bot");
            }
            if (!string.IsNullOrEmpty(basetimestamp))
            {
                parameters.Add("basetimestamp", basetimestamp);
            }
            if (!string.IsNullOrEmpty(starttimestamp))
            {
                parameters.Add("starttimestamp", starttimestamp);
            }
            if (!string.IsNullOrEmpty(summary))
            {
                parameters.Add("summary", summary);
            }

            try
            {
                XmlDocument xml = MakeRequest(Action.Edit, parameters);
                XmlNode result = xml.SelectSingleNode("//edit[@newrevid]");
                if (result != null)
                {
                    return result.Attributes["newrevid"].Value;
                }
            }
            catch (WebException e)
            {
                throw new WikiException("Saving failed", e);
            }
            return null;
        }
Beispiel #49
0
 public string Save(string title,
                    string section,
                    string text,
                    string summary,
                    MinorFlags minor,
                    CreateFlags create,
                    WatchFlags watch,
                    SaveFlags mode,
                    bool bot)
 {
     ParameterCollection parameters = new ParameterCollection
     {
         { "prop", "info" },
         { "intoken", "edit" }
     };
     XmlDocument doc = Query(QueryBy.Titles, parameters, title);
     XmlNode pageNode = doc.SelectSingleNode("//page");
     string token = pageNode != null ? pageNode.Attributes["edittoken"].Value : "";
     return Save(title,
                 section,
                 text,
                 summary,
                 minor,
                 create,
                 watch,
                 mode,
                 bot,
                 "",
                 "",
                 token);
 }
Beispiel #50
0
 public Context(CreateFlags flags) {
     ctx = nvgCreateContext((int)flags);
 }
Beispiel #51
0
		private static bool TryCreateDevice(Direct3D d3D, DeviceSettings deviceSettings, DeviceType deviceType,
											CreateFlags vertexProcessingFlag, out Device device)
		{
			Format adapterformat = d3D.Adapters[0].CurrentDisplayMode.Format;
			//для теней обязательно нужен stencil buffer. Ищем формат
			PresentParameters presentParameters = deviceSettings.PresentParameters;
			foreach(Format stencilformat in new[] {Format.D24S8, Format.D24SingleS8, Format.D24X4S4, Format.D15S1})
			{
				if(d3D.CheckDeviceFormat(0, deviceType, adapterformat,
										Usage.DepthStencil, ResourceType.Surface, stencilformat) &&
					d3D.CheckDepthStencilMatch(0, deviceType,
												adapterformat, adapterformat, stencilformat))
				{
					presentParameters.EnableAutoDepthStencil = true;
					presentParameters.AutoDepthStencilFormat = stencilformat;
					break;
				}
			}
			//Выбираем тип multisampling
			var multiSamplingTypesToCheck = new Dictionary<MultisampleType, int>();
			if(deviceSettings.AutoDetermineMultisampleType)
				multiSamplingTypesToCheck = new[] {MultisampleType.FourSamples, MultisampleType.TwoSamples, MultisampleType.None}.ToDictionary(x => x, x => (int)x);
			else
			{
				MultisampleType multType = deviceSettings.MultisampleType;
				multiSamplingTypesToCheck.Add(multType, (int)multType);
			}
			foreach(var i in multiSamplingTypesToCheck)
			{
				presentParameters.Multisample = i.Key;
				presentParameters.MultisampleQuality = i.Value;
				try
				{
					device = new Device(d3D, 0, deviceType, presentParameters.DeviceWindowHandle,
										CreateFlags.Multithreaded | vertexProcessingFlag, presentParameters);
					return true;
				}
				catch(Direct3D9Exception)
				{
				}
			}
			device = null;
			return false;
		}
 /// <summary>
 /// Create a create request packet for client to create new or open share on server. 
 /// </summary>
 /// <param name = "messageId">the id of message, used to identity the request and the server response. </param>
 /// <param name = "sessionUid">the valid session id, must be response by server of the session setup request. </param>
 /// <param name = "treeId">the valid tree connect id, must be response by server of the tree connect. </param>
 /// <param name = "flags">
 /// The Flags field contains individual flags, as specified in [CIFS] sections 2.4.2 and 3.1.1. 
 /// </param>
 /// <param name = "flags2">
 /// The Flags2 field contains individual bit flags that, depending on the negotiated SMB dialect, indicate   
 /// various client and server capabilities. 
 /// </param>
 /// <param name = "fileName">A string that represents the name of the file to open or create. </param>
 /// <param name = "desiredAccess">
 /// Access wanted. This value MUST be specified in the ACCESS_MASK format, as specified in [CIFS] section 3.7. 
 /// </param>
 /// <param name = "extFileAttributes">Extended attributes and flags for this file or directory. </param>
 /// <param name = "shareAccess">Type of shared access requested for this file or directory. </param>
 /// <param name = "createDisposition">The action to take if a file does or does not exist. </param>
 /// <param name = "createOptions">The options to use if creating the file or directory. </param>
 /// <param name = "impersonationLevel">
 /// This field specifies the information given to the server about the client and how the server MUST   
 /// represent, or impersonate, the client. 
 /// </param>
 /// <param name = "createFlags">
 /// A 32-bit field containing a set of options that specify the security tracking mode. 
 /// </param>
 /// <returns>a create packet </returns>
 private SmbNtCreateAndxRequestPacket CreateCreateRequest(
     ushort messageId,
     ushort sessionUid,
     ushort treeId,
     SmbHeader_Flags_Values flags,
     SmbHeader_Flags2_Values flags2,
     string fileName,
     NtTransactDesiredAccess desiredAccess,
     SMB_EXT_FILE_ATTR extFileAttributes,
     NtTransactShareAccess shareAccess,
     NtTransactCreateDisposition createDisposition,
     NtTransactCreateOptions createOptions,
     NtTransactImpersonationLevel impersonationLevel,
     CreateFlags createFlags)
 {
     return new SmbNtCreateAndxRequestPacket(
         this.cifsClient.CreateNtCreateAndxRequest(
         messageId, sessionUid, treeId, (SmbFlags)flags, (SmbFlags2)flags2, (NtTransactFlags)createFlags,
         0, desiredAccess, 0, extFileAttributes, shareAccess, createDisposition,
         (Cifs.NtTransactCreateOptions)createOptions, impersonationLevel, (NtTransactSecurityFlags)0x00,
         fileName, null));
 }
 /// <summary>
 /// Create a create request packet for client to create new or open share on server. 
 /// </summary>
 /// <param name = "treeId">the valid tree connect id, must be response by server of the tree connect. </param>
 /// <param name = "fileName">A string that represents the name of the file to open or create. </param>
 /// <param name = "desiredAccess">
 /// Access wanted. This value MUST be specified in the ACCESS_MASK format, as specified in [CIFS] section 3.7. 
 /// </param>
 /// <param name = "extFileAttributes">Extended attributes and flags for this file or directory. </param>
 /// <param name = "shareAccess">Type of shared access requested for this file or directory. </param>
 /// <param name = "createDisposition">The action to take if a file does or does not exist. </param>
 /// <param name = "createOptions">The options to use if creating the file or directory. </param>
 /// <param name = "impersonationLevel">
 /// This field specifies the information given to the server about the client and how the server MUST   
 /// represent, or impersonate, the client. 
 /// </param>
 /// <param name = "createFlags">
 /// A 32-bit field containing a set of options that specify the security tracking mode. 
 /// </param>
 /// <returns>a create packet </returns>
 public SmbNtCreateAndxRequestPacket CreateCreateRequest(
     ushort treeId,
     string fileName,
     NtTransactDesiredAccess desiredAccess,
     SMB_EXT_FILE_ATTR extFileAttributes,
     NtTransactShareAccess shareAccess,
     NtTransactCreateDisposition createDisposition,
     NtTransactCreateOptions createOptions,
     NtTransactImpersonationLevel impersonationLevel,
     CreateFlags createFlags
     )
 {
     return CreateCreateRequest(this.MessageId,
         this.GetSessionIdByTreeId(treeId), treeId,
        this.capability.Flag, this.capability.Flags2, fileName,
         desiredAccess, extFileAttributes, shareAccess, createDisposition, createOptions,
         impersonationLevel, createFlags);
 }
Beispiel #54
0
 /// <summary>
 /// Creates a device to represent the display adapter.
 /// </summary>
 /// <param name="direct3D">an instance of <see cref="SharpDX.Direct3D9.Direct3D"/></param>
 /// <param name="adapter">Ordinal number that denotes the display adapter. {{D3DADAPTER_DEFAULT}} is always the primary display adapter.</param>
 /// <param name="deviceType">Member of the <see cref="SharpDX.Direct3D9.DeviceType"/> enumerated type that denotes the desired device type. If the desired device type is not available, the method will fail.</param>
 /// <param name="controlHandle">The focus window alerts Direct3D when an application switches from foreground mode to background mode. See Remarks. 	   For full-screen mode, the window specified must be a top-level window. For windowed mode, this parameter may be NULL only if the hDeviceWindow member of pPresentationParameters is set to a valid, non-NULL value.</param>
 /// <param name="createFlags">Combination of one or more options that control device creation. For more information, see {{D3DCREATE}}.</param>
 /// <param name="presentParameters">Pointer to a <see cref="SharpDX.Direct3D9.PresentParameters"/> structure, describing the presentation parameters for the device to be created. If BehaviorFlags specifies {{D3DCREATE_ADAPTERGROUP_DEVICE}}, pPresentationParameters is an array. Regardless of the number of heads that exist, only one depth/stencil surface is automatically created. For Windows 2000 and Windows XP, the full-screen device display refresh rate is set in the following order:   User-specified nonzero ForcedRefreshRate registry key, if supported by the device. Application-specified nonzero refresh rate value in the presentation parameter. Refresh rate of the latest desktop mode, if supported by the device. 75 hertz if supported by the device. 60 hertz if supported by the device. Device default.  An unsupported refresh rate will default to the closest supported refresh rate below it.  For example, if the application specifies 63 hertz, 60 hertz will be used. There are no supported refresh rates below 57 hertz. pPresentationParameters is both an input and an output parameter. Calling this method may change several members including:  If BackBufferCount, BackBufferWidth, and BackBufferHeight  are 0 before the method is called, they will be changed when the method returns. If BackBufferFormat equals <see cref="SharpDX.Direct3D9.Format.Unknown"/> before the method is called, it will be changed when the method returns.</param>
 /// <param name="fullScreenDisplayMode">The full screen display mode.</param>
 /// <remarks>
 /// This method returns a fully working device interface, set to the required display mode (or windowed), and allocated with the appropriate back buffers. To begin rendering, the application needs only to create and set a depth buffer (assuming EnableAutoDepthStencil is FALSE in <see cref="SharpDX.Direct3D9.PresentParameters"/>). When you create a Direct3D device, you supply two different window parameters: a focus window (hFocusWindow) and a device window (the hDeviceWindow in <see cref="SharpDX.Direct3D9.PresentParameters"/>). The purpose of each window is:  The focus window alerts Direct3D when an application switches from foreground mode to background mode (via Alt-Tab, a mouse click, or some other method). A single focus window is shared by each device created by an application. The device window determines the location and size of the back buffer on screen. This is used by Direct3D when the back buffer contents are copied to the front buffer during {{Present}}.  This method should not be run during the handling of WM_CREATE. An application should never pass a window handle to Direct3D while handling WM_CREATE.  Any call to create, release, or reset the device must be done using the same thread as the window procedure of the focus window. Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and at least one of these vertex processing flags must be specified when calling this method. Back buffers created as part of the device are only lockable if D3DPRESENTFLAG_LOCKABLE_BACKBUFFER is specified in the presentation parameters. (Multisampled back buffers and depth surfaces are never lockable.) The methods {{Reset}}, <see cref="SharpDX.ComObject"/>, and {{TestCooperativeLevel}} must be called from the same thread that used this method to create a device. D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling CreateDevice, {{Reset}}, and {{CreateAdditionalSwapChain}}. This means the application does not have to query the current desktop format before calling CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified. If you attempt to create a device on a 0x0 sized window, CreateDevice will fail.
 /// </remarks>
 /// <unmanaged>HRESULT CreateDevice([None] UINT Adapter,[None] D3DDEVTYPE DeviceType,[None] HWND hFocusWindow,[None] int BehaviorFlags,[None] D3DPRESENT_PARAMETERS* pPresentationParameters,[None] IDirect3DDevice9** ppReturnedDeviceInterface)</unmanaged>
 public DeviceEx(Direct3DEx direct3D, int adapter, DeviceType deviceType, IntPtr controlHandle, CreateFlags createFlags, PresentParameters[] presentParameters, DisplayModeEx[] fullScreenDisplayMode)
     : base(IntPtr.Zero)
 {
     direct3D.CreateDeviceEx(adapter, deviceType, controlHandle, (int)createFlags, presentParameters, fullScreenDisplayMode, this);
 }
Beispiel #55
0
		/// <summary>
		/// Initialize the graphics environment
		/// </summary>
		void InitializeEnvironment(bool fullScreen)
		{
			// Save normal form settings (or initial settings when starting up minimized/maximized)
			if (!mFullScreen)
			{
				// Save form setting only when window state is normal
				if (ParentForm.WindowState == FormWindowState.Normal
							|| mFormRectangle.Size == new Size())
				{
					mFormBorderStyle = ParentForm.FormBorderStyle;
					mFormRectangle.Location = ParentForm.Location;
					mFormRectangle.Size = ParentForm.Size;
					mFormMainMenu = ParentForm.Menu;
					mFormVisible = ParentForm.Visible;
				}
				// Always save control settings before entering full screen mode
				mControlRectangle.Location = this.Location;
				mControlRectangle.Size = this.Size;
				mControlVisible = this.Visible;
			}
			// Delete old Dx object
			DeleteDirectxDevice();

			// If switching from full screen mode to windowed mode, restore control and form scale
			if (mFullScreen && !fullScreen)
			{
				// We need to force a redraw so the form is the correct size,
				// and is not hidden by the task bar.  Display a black form
				// while doing this, so there is not as much annoying flicker.
				Form blackForm = new Form();
				blackForm.WindowState = FormWindowState.Maximized;
				blackForm.ControlBox = false;
				blackForm.MinimizeBox = false;
				blackForm.MinimizeBox = false;
				blackForm.ShowInTaskbar = false;
				blackForm.BackColor = Color.Black;
				blackForm.Show();
				ParentForm.Visible = false;

				// Restore form parameters
				ParentForm.FormBorderStyle = mFormBorderStyle;
				ParentForm.Location = mFormRectangle.Location;
				ParentForm.Size = mFormRectangle.Size;
				if (mFormMainMenu != null)
					ParentForm.Menu = mFormMainMenu;
				
				// Restore control parameters
				Location = mControlRectangle.Location;
				Size = mControlRectangle.Size;
				Visible = mControlVisible;

				// Restore owned forms
				if (mFormOwnedForms != null)
					for (int i = 0; i < mFormOwnedForms.Length; i++)
					{
						mFormOwnedForms[i].Owner = ParentForm;
						mFormOwnedForms[i].BringToFront();
					}
				mFormOwnedForms = null;
				
				// Display this form, and close the black form
				ParentForm.Visible = mFormVisible;
				ParentForm.BringToFront();
				blackForm.Close();				
			}

			GraphicsAdapterInfo adapterInfo = mGraphicsSettings.AdapterInfo;
			GraphicsDeviceInfo deviceInfo = mGraphicsSettings.DeviceInfo;

			// Set new full screen mode
			//bool oldFullScreenMode = mFullScreen;
			mFullScreen = fullScreen;
			mGraphicsSettings.IsWindowed = !fullScreen;

			// Set up presentation parameters from current settings
			PresentParameters presentParams = new PresentParameters();
			presentParams.Windowed = mGraphicsSettings.IsWindowed;
			presentParams.MultiSample = mGraphicsSettings.MultisampleType;
			presentParams.MultiSampleQuality = mGraphicsSettings.MultisampleQuality;
			presentParams.SwapEffect = SwapEffect.Discard;
			presentParams.EnableAutoDepthStencil = mEnumerationSettings.AppUsesDepthBuffer;
			presentParams.AutoDepthStencilFormat = mGraphicsSettings.DepthStencilBufferFormat;

			// If doing 2D graphics, allow a lockable back buffer.
			if (this.DxRender2d == null)
				presentParams.PresentFlag = PresentFlag.None;
			else
				presentParams.PresentFlag = PresentFlag.LockableBackBuffer;

			if (!mFullScreen)
			{
				// Windowed mode parameters
				presentParams.BackBufferCount = 1; // One back buffer OK
				presentParams.BackBufferWidth = ClientRectangle.Right - ClientRectangle.Left;
				presentParams.BackBufferHeight = ClientRectangle.Bottom - ClientRectangle.Top;
				presentParams.BackBufferFormat = mGraphicsSettings.DeviceCombo.BackBufferFormat;
				presentParams.FullScreenRefreshRateInHz = 0;
				presentParams.PresentationInterval = PresentInterval.Immediate;
				presentParams.DeviceWindow = this;
			}
			else
			{
				// Full screen mode parameters
				presentParams.BackBufferCount = 2; // Two back buffers needed for full screen
				presentParams.BackBufferWidth = mGraphicsSettings.DisplayMode.Width;
				presentParams.BackBufferHeight = mGraphicsSettings.DisplayMode.Height;
				presentParams.BackBufferFormat = mGraphicsSettings.DeviceCombo.BackBufferFormat;
				presentParams.FullScreenRefreshRateInHz = mGraphicsSettings.DisplayMode.RefreshRate;
				presentParams.PresentationInterval = mGraphicsSettings.PresentInterval;
				presentParams.DeviceWindow = this.Parent;
			}

			if (mFullScreen)
			{
				// Save owned forms, and get rid of them so they can't overlap the full screen
				mFormOwnedForms = ParentForm.OwnedForms;
				for (int i = 0; i < mFormOwnedForms.Length; i++)
					mFormOwnedForms[i].Owner = null;

				// Setup form to be full screen mode
				if (ParentForm.WindowState == FormWindowState.Minimized)
					ParentForm.WindowState = FormWindowState.Normal;
				ParentForm.FormBorderStyle = FormBorderStyle.None;
				ParentForm.Menu = null;
				ParentForm.Visible = true;
				Location = new Point(0, 0);
				Size = new Size(presentParams.BackBufferWidth, presentParams.BackBufferHeight);
				Visible = true;
				ParentForm.BringToFront();  // This form must be on top
				BringToFront(); // This control must be on top
			}



			if (deviceInfo.Caps.PrimitiveMiscCaps.IsNullReference)
			{
				// Warn user about null ref device that can't render anything
			}

			CreateFlags createFlags = new CreateFlags();
			if (mGraphicsSettings.VertexProcessingType == VertexProcessingType.Software)
				createFlags = CreateFlags.SoftwareVertexProcessing;
			else if (mGraphicsSettings.VertexProcessingType == VertexProcessingType.Mixed)
				createFlags = CreateFlags.MixedVertexProcessing;
			else if (mGraphicsSettings.VertexProcessingType == VertexProcessingType.Hardware)
				createFlags = CreateFlags.HardwareVertexProcessing;
			else if (mGraphicsSettings.VertexProcessingType == VertexProcessingType.PureHardware)
			{
				createFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.PureDevice;
			}
			else
				throw new ApplicationException();

			// This application can be multithreaded
			createFlags |= CreateFlags.MultiThreaded;
			

			try
			{
				// Create the device
				mDx = new Device(mGraphicsSettings.AdapterOrdinal,
								mGraphicsSettings.DevType, this,
													createFlags, presentParams);
			}
			catch
			{
				// If that failed, fall back to the reference rasterizer
				if (deviceInfo.DevType == DeviceType.Hardware
					&& FindBestWindowedMode(false, true))
				{
					InitializeEnvironment(false);
					return;
				}
				throw;
			}


			// Set up the cursor (doesn't work)
			//mDx.SetCursor(this.Cursor, true);
			//mDx.ShowCursor(mShowCursor);

			// Setup the event handlers
			mDx.DeviceReset += new System.EventHandler(this.DxRestoreInternal);
			mDx.DeviceLost += new System.EventHandler(this.DxLostInternal);
			mDx.DeviceResizing += new System.ComponentModel.CancelEventHandler(this.DxResizeInternal);

			// Initialize device-dependent objects
			DxResizeInternal(null, null);
			if (!mLoaded && DxLoaded != null)
				DxLoaded(this, mDx);
			mLoaded = true;
			DxRestoreInternal(null, null);
		}
Beispiel #56
0
            /// <summary>
            /// Updates the string which describes the device
            /// </summary>
            private void UpdateDeviceStats(DeviceType deviceType, CreateFlags behaviorFlags, AdapterDetails info)
            {
            if (State.AreStatsHidden)
                return; // Do nothing if stats are hidden

            // Get the behavior flags
            BehaviorFlags flags = new BehaviorFlags(behaviorFlags);
            // Store device information
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            // Append device type
            builder.Append(deviceType.ToString());
            // Append other types based on flags
            if (flags.HardwareVertexProcessing && flags.PureDevice)
            {
                if (deviceType == DeviceType.Hardware)
                    builder.Append(" (pure hw vp)");
                else
                    builder.Append(" (simulated pure hw vp)");
            }
            else if (flags.HardwareVertexProcessing)
            {
                if (deviceType == DeviceType.Hardware)
                    builder.Append(" (hw vp)");
                else
                    builder.Append(" (simulated hw vp)");
            }
            else if (flags.MixedVertexProcessing)
            {
                if (deviceType == DeviceType.Hardware)
                    builder.Append(" (mixed vp)");
                else
                    builder.Append(" (simulated mixed vp)");
            }
            else if (flags.SoftwareVertexProcessing)
            {
                builder.Append(" (sw vp)");
            }

            // now add the description
            builder.Append(": ");
            builder.Append(info.Description);

            // Store the device stats string
            State.DeviceStats = builder.ToString();
            }
Beispiel #57
0
    /// <summary>
    /// Initialization of the D3D Device
    /// </summary>
    protected void InitializeDevice()
    {
      Log.Debug("D3D: InitializeDevice()");
      
      // get capabilities of hardware device for current adapter
      Caps capabilities = GetCapabilities();

      if (!successfulInit)
      {
        if (AdapterInfo != null)
        {
          Log.Info("D3D: GPU '{0}' is using driver version '{1}'", AdapterInfo.AdapterDetails.Description.Trim(), AdapterInfo.AdapterDetails.DriverVersion);
        }
        Log.Info("D3D: Vertex shader version: {0}", capabilities.VertexShaderVersion);
        Log.Info("D3D: Pixel shader version: {0}", capabilities.PixelShaderVersion);

        // default to reference rasterizer and software vertex processing for initialization purposes
        _deviceType = DeviceType.Reference;
        _createFlags = CreateFlags.SoftwareVertexProcessing;

        // check if GPU supports rasterization in hardware
        if (capabilities.DeviceCaps.SupportsHardwareRasterization)
        {
          Log.Info("D3D: GPU supports rasterization in hardware");
          _deviceType = DeviceType.Hardware;
        }

        //  check if GPU supports shader model 2.0
        if (capabilities.VertexShaderVersion >= new Version(2, 0) && capabilities.PixelShaderVersion >= new Version(2, 0))
        {
          // check if GPU supports rasterization, transformation, lighting in hardware
          if (capabilities.DeviceCaps.SupportsHardwareTransformAndLight)
          {
            Log.Info("D3D: GPU supports rasterization, transformation, lighting in hardware");
            _createFlags = CreateFlags.HardwareVertexProcessing;
          }
          // check if GPU supports rasterization, transformations, lighting, and shading in hardware
          if (capabilities.DeviceCaps.SupportsPureDevice)
          {
            Log.Info("D3D: GPU supports rasterization, transformations, lighting, and shading in hardware");
            if (OSInfo.OSInfo.VistaOrLater())
            {
              _createFlags |= CreateFlags.PureDevice;
            }
          }
        }

        // Log some interesting capabilities
        if (!capabilities.TextureCaps.SupportsPower2 && !capabilities.TextureCaps.SupportsNonPower2Conditional)
        {
          Log.Info("D3D: GPU unconditionally supports textures with dimensions that are not powers of two");
        }
        else if (capabilities.TextureCaps.SupportsPower2 && capabilities.TextureCaps.SupportsNonPower2Conditional)
        {
          Log.Info("D3D: GPU conditionally supports textures with dimensions that are not powers of two");
        }
        else if (capabilities.TextureCaps.SupportsPower2 && !capabilities.TextureCaps.SupportsNonPower2Conditional)
        {
          Log.Info("D3D: GPU does not support textures with dimensions that are not powers of two");
        }

        // TODO: check for any capabilities that would not allow MP to run

        // read skin information
        GUIControlFactory.LoadReferences(GUIGraphicsContext.GetThemedSkinFile(@"\references.xml"));

        // Set up the presentation parameters
        BuildPresentParams(Windowed);

        // backup _presentParams for later use (standby)
        _presentParamsBackup = _presentParams;
        Log.Debug("D3D: Backup PresentParams with buffer size set to: {0}x{1}", _presentParamsBackup.BackBufferWidth, _presentParamsBackup.BackBufferHeight);

        // Create the device
        if (GUIGraphicsContext.IsDirectX9ExUsed())
        {
          // Vista or later, use DirectX9Ex device
          Log.Info("D3D: Creating DirectX9Ex device");
          CreateDirectX9ExDevice();
        }
        else
        {
          Log.Info("D3D: Creating DirectX9 device");
          GUIGraphicsContext.DX9Device = new Device(AdapterInfo.AdapterOrdinal,
                                                    _deviceType,
                                                    _renderTarget,
                                                    _createFlags | CreateFlags.MultiThreaded | CreateFlags.FpuPreserve,
                                                    _presentParams);
        }

        // update some magic number use for animations
        GUIGraphicsContext.MaxFPS = Manager.Adapters[AdapterInfo.AdapterOrdinal].CurrentDisplayMode.RefreshRate;

        // set always on top parameter
        TopMost = _alwaysOnTop;

        // Set up the fullscreen cursor
        if (_showCursorWhenFullscreen && !Windowed)
        {
          var ourCursor = Cursor;
          GUIGraphicsContext.DX9Device.SetCursor(ourCursor, true);
          GUIGraphicsContext.DX9Device.ShowCursor(true);
        }

        // Setup the event handlers for our device
        if (GUIGraphicsContext.DX9Device != null)
        {
          GUIGraphicsContext.DX9Device.DeviceLost += OnDeviceLost;
        }

        // Initialize the app's device-dependent objects
        try
        {
          InitializeDeviceObjects();
          AppActive = true;
          successfulInit = true;
        }
        catch (Exception ex)
        {
          Log.Error("D3D: InitializeDeviceObjects - Exception: {0}", ex.ToString());
          if (GUIGraphicsContext.DX9Device != null)
          {
            GUIGraphicsContext.DX9Device.Dispose();
          }
          GUIGraphicsContext.DX9Device = null;
        }
      }
    }
Beispiel #58
0
 /// <summary>
 /// Creates a device to represent the display adapter.
 /// </summary>
 /// <param name="direct3D">an instance of <see cref="SharpDX.Direct3D9.Direct3D"/></param>
 /// <param name="adapter">Ordinal number that denotes the display adapter. {{D3DADAPTER_DEFAULT}} is always the primary display adapter.</param>
 /// <param name="deviceType">Member of the <see cref="SharpDX.Direct3D9.DeviceType"/> enumerated type that denotes the desired device type. If the desired device type is not available, the method will fail.</param>
 /// <param name="controlHandle">The focus window alerts Direct3D when an application switches from foreground mode to background mode. See Remarks. 	   For full-screen mode, the window specified must be a top-level window. For windowed mode, this parameter may be NULL only if the hDeviceWindow member of pPresentationParameters is set to a valid, non-NULL value.</param>
 /// <param name="createFlags">Combination of one or more options that control device creation. For more information, see {{D3DCREATE}}.</param>
 /// <param name="presentParameters">Pointer to a <see cref="SharpDX.Direct3D9.PresentParameters"/> structure, describing the presentation parameters for the device to be created. If BehaviorFlags specifies {{D3DCREATE_ADAPTERGROUP_DEVICE}}, pPresentationParameters is an array. Regardless of the number of heads that exist, only one depth/stencil surface is automatically created. For Windows 2000 and Windows XP, the full-screen device display refresh rate is set in the following order:   User-specified nonzero ForcedRefreshRate registry key, if supported by the device. Application-specified nonzero refresh rate value in the presentation parameter. Refresh rate of the latest desktop mode, if supported by the device. 75 hertz if supported by the device. 60 hertz if supported by the device. Device default.  An unsupported refresh rate will default to the closest supported refresh rate below it.  For example, if the application specifies 63 hertz, 60 hertz will be used. There are no supported refresh rates below 57 hertz. pPresentationParameters is both an input and an output parameter. Calling this method may change several members including:  If BackBufferCount, BackBufferWidth, and BackBufferHeight  are 0 before the method is called, they will be changed when the method returns. If BackBufferFormat equals <see cref="SharpDX.Direct3D9.Format.Unknown"/> before the method is called, it will be changed when the method returns.</param>
 /// <param name="fullScreenDisplayMode">The full screen display mode.</param>
 /// <remarks>
 /// This method returns a fully working device interface, set to the required display mode (or windowed), and allocated with the appropriate back buffers. To begin rendering, the application needs only to create and set a depth buffer (assuming EnableAutoDepthStencil is FALSE in <see cref="SharpDX.Direct3D9.PresentParameters"/>). When you create a Direct3D device, you supply two different window parameters: a focus window (hFocusWindow) and a device window (the hDeviceWindow in <see cref="SharpDX.Direct3D9.PresentParameters"/>). The purpose of each window is:  The focus window alerts Direct3D when an application switches from foreground mode to background mode (via Alt-Tab, a mouse click, or some other method). A single focus window is shared by each device created by an application. The device window determines the location and size of the back buffer on screen. This is used by Direct3D when the back buffer contents are copied to the front buffer during {{Present}}.  This method should not be run during the handling of WM_CREATE. An application should never pass a window handle to Direct3D while handling WM_CREATE.  Any call to create, release, or reset the device must be done using the same thread as the window procedure of the focus window. Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and at least one of these vertex processing flags must be specified when calling this method. Back buffers created as part of the device are only lockable if D3DPRESENTFLAG_LOCKABLE_BACKBUFFER is specified in the presentation parameters. (Multisampled back buffers and depth surfaces are never lockable.) The methods {{Reset}}, <see cref="SharpDX.ComObject"/>, and {{TestCooperativeLevel}} must be called from the same thread that used this method to create a device. D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling CreateDevice, {{Reset}}, and {{CreateAdditionalSwapChain}}. This means the application does not have to query the current desktop format before calling CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified. If you attempt to create a device on a 0x0 sized window, CreateDevice will fail.
 /// </remarks>
 /// <unmanaged>HRESULT CreateDevice([None] UINT Adapter,[None] D3DDEVTYPE DeviceType,[None] HWND hFocusWindow,[None] int BehaviorFlags,[None] D3DPRESENT_PARAMETERS* pPresentationParameters,[None] IDirect3DDevice9** ppReturnedDeviceInterface)</unmanaged>
 public DeviceEx(Direct3DEx direct3D, int adapter, DeviceType deviceType, IntPtr controlHandle, CreateFlags createFlags, PresentParameters presentParameters, DisplayModeEx fullScreenDisplayMode)
     : base(IntPtr.Zero)
 {
     direct3D.CreateDeviceEx(adapter, deviceType, controlHandle, (int)createFlags, new[] {presentParameters}, fullScreenDisplayMode == null ? null : new[] {fullScreenDisplayMode}, this);
 }
Beispiel #59
0
            public Column(PropertyInfo prop, CreateFlags createFlags = CreateFlags.None)
            {
                var colAttr =
                    prop.GetCustomAttributes<ColumnAttribute>(true).FirstOrDefault();

                _prop = prop;
                Name = colAttr == null ? prop.Name : colAttr.Name;
                //If this type is Nullable<T> then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead
                ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                Collation = Orm.Collation(prop);

                IsPK = Orm.IsPK(prop) ||
                       (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) &&
                        string.Compare(prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0);

                var isAuto = Orm.IsAutoInc(prop) ||
                             (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK));
                IsAutoGuid = isAuto && ColumnType == typeof (Guid);
                IsAutoInc = isAuto && !IsAutoGuid;

                DefaultValue = Orm.GetDefaultValue(prop);

                Indices = Orm.GetIndices(prop);
                if (!Indices.Any()
                    && !IsPK
                    && ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex)
                    && Name.EndsWith(Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase))
                {
                    Indices = new[] {new IndexedAttribute()};
                }
                IsNullable = !(IsPK || Orm.IsMarkedNotNull(prop));
                MaxStringLength = Orm.MaxStringLength(prop);
            }
Beispiel #60
0
        public override void Hook()
        {
            this.DebugMessage("Hook: Begin");
            // First we need to determine the function address for IDirect3DDevice9
            Device device;
            List<IntPtr> id3dDeviceFunctionAddresses = new List<IntPtr>();
            this.DebugMessage("Hook: Before device creation");
            using (Direct3D d3d = new Direct3D())
            {
                this.DebugMessage("Hook: Device created");

                //*
                if (_VertexMode == 0)
                {
                    _VertexProcessing = CreateFlags.HardwareVertexProcessing;
                    this.DebugMessage("Flag: HardwareVertexProcessing");
                }
                else if (_VertexMode == 1)
                {
                    _VertexProcessing = CreateFlags.SoftwareVertexProcessing;
                    this.DebugMessage("Flag: SoftwareVertexProcessing");
                }
                else if (_VertexMode == 2)
                {
                    _VertexProcessing = CreateFlags.PureDevice;
                    this.DebugMessage("Flag: PureDevice");
                }

                using (device = new Device(d3d, 0, DeviceType.Hardware, IntPtr.Zero, _VertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 }))
                // */

                // using (device = new Device(d3d, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.MixedVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 }))
                {
                    id3dDeviceFunctionAddresses.AddRange(GetVTblAddresses(device.ComPointer, D3D9_DEVICE_METHOD_COUNT));
                }
            }

            // We want to hook each method of the IDirect3DDevice9 interface that we are interested in

            // 42 - EndScene (we will retrieve the back buffer here)
            Direct3DDevice_EndSceneHook = LocalHook.Create(
                id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.EndScene],
                // On Windows 7 64-bit w/ 32-bit app and d3d9 dll version 6.1.7600.16385, the address is equiv to:
                // (IntPtr)(GetModuleHandle("d3d9").ToInt32() + 0x1ce09),
                // A 64-bit app would use 0xff18
                // Note: GetD3D9DeviceFunctionAddress will output these addresses to a log file
                new Direct3D9Device_EndSceneDelegate(EndSceneHook),
                this);

            // 16 - Reset (called on resolution change or windowed/fullscreen change - we will reset some things as well)
            Direct3DDevice_ResetHook = LocalHook.Create(
                id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Reset],
                // On Windows 7 64-bit w/ 32-bit app and d3d9 dll version 6.1.7600.16385, the address is equiv to:
                //(IntPtr)(GetModuleHandle("d3d9").ToInt32() + 0x58dda),
                // A 64-bit app would use 0x3b3a0
                // Note: GetD3D9DeviceFunctionAddress will output these addresses to a log file
                new Direct3D9Device_ResetDelegate(ResetHook),
                this);

            /*
             * Don't forget that all hooks will start deactivated...
             * The following ensures that all threads are intercepted:
             * Note: you must do this for each hook.
             */
            Direct3DDevice_EndSceneHook.ThreadACL.SetExclusiveACL(new Int32[1]);

            Direct3DDevice_ResetHook.ThreadACL.SetExclusiveACL(new Int32[1]);

            this.DebugMessage("Hook: End");
        }