Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            RenderForm form = new RenderForm("Underground - POO version");
            form.Size = new Size(1280, 700);

            Direct3D direct3D = new Direct3D();
            PresentParameters parameters = new PresentParameters(form.ClientSize.Width, form.ClientSize.Height);
            Device device = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, parameters);
            ResManager.Initialize(ref device, ref form);
            IngameClass ingame = new IngameClass(ref device, ref form);

            Stopwatch clock = new Stopwatch();
            clock.Start();

            RenderLoop.Run(form, () =>
            {
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                device.BeginScene();

                ingame.Draw(ref device, ref form, ref clock);

                device.EndScene();
                device.Present();
            });

            ResManager.Dispose();
            device.Dispose();
            direct3D.Dispose();
        }
Ejemplo n.º 2
0
        public static void Initiate()
        {
            var form = new RenderForm("SharpDX - MiniCube Direct3D9 Sample");
            // Creates the Device
            var direct3D = new Direct3D();
            var device   = new SharpDX.Direct3D9.Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

            // Prepare matrices
            var view     = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            var proj     = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f);
            var viewProj = Matrix.Multiply(view, proj);

            // Use clock
            var clock = new Stopwatch();

            clock.Start();

            string Game = "WOT";

            switch (Game)
            {
            case "WOT":
                _list.Add(new DrawTextureAndCatchIt(SharpDX.Direct3D9.Texture.FromFile(device, "Resources/error_enter.png"), SharpDX.Direct3D9.Texture.FromFile(device, "Resources/error_6473.png"), new SharpDX.Mathematics.Interop.RawRectangle(1, 1, 100, 100), new SharpDX.Vector3(100, 100, 0)));
                _list.Add(new DrawTextureAndCatchIt(SharpDX.Direct3D9.Texture.FromFile(device, "Resources/edit-addenter.png"), SharpDX.Direct3D9.Texture.FromFile(device, "Resources/edit-add.png"), new SharpDX.Mathematics.Interop.RawRectangle(1, 1, 100, 100), new SharpDX.Vector3(100, 400, 0)));
                break;
            }
            //choose game


            RenderLoop.Run(form, () =>
            {
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                device.BeginScene();
                foreach (DrawTextureAndCatchIt dr in _list)
                {
                    dr.CheckCursorPosition();
                    dr.DrawTexture(device);
                }

                device.EndScene();
                device.Present();
            });

            device.Dispose();
            direct3D.Dispose();
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            var form = new RenderForm("Conway's Game of Life");

            var device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing,
                new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

            var vertices = new VertexBuffer(device, 3 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
            vertices.Lock(0, 0, LockFlags.None).WriteRange(new[] {
                new Vertex { Color = Color.Red, Position = new Vector4(400.0f, 100.0f, 0.5f, 1.0f)},
                new Vertex { Color = Color.Blue, Position = new Vector4(650.0f, 500.0f, 0.5f, 1.0f)},
                new Vertex { Color = Color.Green, Position = new Vector4(150.0f, 500.0f, 0.5f, 1.0f)},
            });

            vertices.Unlock();
            var vertexElements = new[]
            {
                new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0),
                new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                VertexElement.VertexDeclarationEnd,
            };

            var vertexDeclaration = new VertexDeclaration(device, vertexElements);

            RenderLoop.Run(form, () =>
                {
                    device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);

                    device.BeginScene();

                    device.SetStreamSource(0, vertices, 0, 20);
                    device.VertexDeclaration = vertexDeclaration;
                    device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);

                    device.EndScene();
                    device.Present();
                });
        }
Ejemplo n.º 4
0
        public static void Main()
        {
            var form = new RenderForm("SimpleD3D9 by C#")
            {
                ClientSize = new Size(1024, 768)
            };

            var device = new D3D9Device(
                new Direct3D(),
                CUDADevice.Default.ID,
                DeviceType.Hardware,
                form.Handle,
                CreateFlags.HardwareVertexProcessing,
                new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

            var vertices = new VertexBuffer(device, Utilities.SizeOf <Vector4>() * Total, Usage.WriteOnly,
                                            VertexFormat.None, Pool.Default);

            var vertexElems = new []
            {
                new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
                new VertexElement(0, 12, DeclarationType.Ubyte4, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                VertexElement.VertexDeclarationEnd
            };

            var vertexDecl = new VertexDeclaration(device, vertexElems);

            var worker  = Worker.CreateByFunc(() => Generate(device));
            var updater = new SimpleD3D9(GPUModuleTarget.Worker(worker));

            var view = Matrix.LookAtLH(
                new Vector3(0.0f, 3.0f, -2.0f), // the camera position
                new Vector3(0.0f, 0.0f, 0.0f),  // the look-at position
                new Vector3(0.0f, 1.0f, 0.0f)); // the up direction

            var proj = Matrix.PerspectiveFovLH(
                (float)(Math.PI / 4.0), // the horizontal field of view
                1.0f,
                1.0f,
                100.0f);

            device.SetTransform(TransformState.View, view);
            device.SetTransform(TransformState.Projection, proj);
            device.SetRenderState(RenderState.Lighting, false);

            var vbres = RegisterVerticesResource(vertices);
            var clock = System.Diagnostics.Stopwatch.StartNew();

            RenderLoop.Run(form, () =>
            {
                var time = (float)(clock.Elapsed.TotalMilliseconds) / 300.0f;
                updater.Update(vbres, time);

                // Now normal D3D9 rendering procedure.
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, new ColorBGRA(0, 40, 100, 0), 1.0f, 0);
                device.BeginScene();

                device.VertexDeclaration = vertexDecl;
                device.SetStreamSource(0, vertices, 0, Utilities.SizeOf <Vector4>());
                // we use PointList as the graphics primitives
                device.DrawPrimitives(SharpDX.Direct3D9.PrimitiveType.PointList, 0, Total);

                device.EndScene();
                device.Present();
            });

            UnregisterVerticesResource(vbres);

            updater.Dispose();
            worker.Dispose();
            vertexDecl.Dispose();
            vertices.Dispose();
            device.Dispose();
            form.Dispose();
        }
Ejemplo n.º 5
0
        private void Render()
        {
            elaspedTime += _timer.GetElaspedTime();
            if (elaspedTime < REFRESH)
            {
                Thread.Sleep(1);
                return;
            }

            lock (emote)
            {
                emote.Update((float)REFRESH * 1000);

                //_device.Clear(ClearFlags.Target, Color.Transparent, 1.0f, 0);
                //_device.Clear(ClearFlags.Target, new SharpDX.Mathematics.Interop.RawColorBGRA(0, 0, 0, 0), 1.0f, 0);
                //_device.Clear(ClearFlags.Target, new SharpDX.Mathematics.Interop.RawColorBGRA(0, 255, 0, 255), 1.0f, 0);
                _device.Clear(ClearFlags.Target, new SharpDX.Mathematics.Interop.RawColorBGRA(0, 0, 0, 255), 1.0f, 0);

                _device.BeginScene();
                //device.UpdateSurface(device.GetBackBuffer(0,0),new Surface(new IntPtr(e.D3DSurface)));
                emote.Draw();
                _device.EndScene();
                try
                {
                    _device.Present();
                }
                catch (SharpDXException exception)
                {
                    if (exception.ResultCode == SharpDX.Direct3D9.ResultCode.DeviceLost)
                    {
                        Console.WriteLine("Device Lost Detected");
                        emote.OnDeviceLost();
                        Result r;
                        while ((r = _device.TestCooperativeLevel()) == SharpDX.Direct3D9.ResultCode.DeviceLost)
                        {
                            Thread.Sleep(5);
                        }
                        r = _device.TestCooperativeLevel();
                        if (r == SharpDX.Direct3D9.ResultCode.DeviceNotReset)
                        {
                            emote.D3DReset();
                            emote.OnDeviceReset();
                            //e.D3DInitRenderState();
                        }
                        else
                        {
                            Console.WriteLine(r);
                        }
                        //r = _device.TestCooperativeLevel();
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            //if (EnableTransparentWindow)
            //{
            //    emote.D3DAfterPresentSetTransparentWindow();
            //}

            elaspedTime = 0;
        }
        static void Main()
        {
            var worldSize = new Size2(1024, 768);
            var renderSize = new Size2(1920, 1080);
            const bool windowed = true;

            const int numParticles = 1000000;
            const int numEmitters = 5;
            const int budget = numParticles / numEmitters;

            var form = new RenderForm("Mercury Particle Engine - SharpDX.Direct3D9 Sample")
            {
                Size = new System.Drawing.Size(renderSize.Width, renderSize.Height)
            };

            var direct3d = new Direct3D();
            var device = new Device(direct3d, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(renderSize.Width, renderSize.Height) { PresentationInterval = PresentInterval.Immediate, Windowed = windowed });

            var view = new Matrix(
                1.0f, 0.0f, 0.0f, 0.0f,
                0.0f, -1.0f, 0.0f, 0.0f,
                0.0f, 0.0f, -1.0f, 0.0f,
                0.0f, 0.0f, 0.0f, 1.0f);
            var proj = Matrix.OrthoOffCenterLH(worldSize.Width * -0.5f, worldSize.Width * 0.5f, worldSize.Height * 0.5f, worldSize.Height * -0.5f, 0f, 1f);
            var wvp = Matrix.Identity * view * proj;

            var emitters = new Emitter[numEmitters];

            for (int i = 0; i < numEmitters; i++)
            {
                emitters[i] = new Emitter(budget, TimeSpan.FromSeconds(600), Profile.BoxFill(worldSize.Width, worldSize.Height))
                {
                    Parameters = new ReleaseParameters
                    {
                        Colour = new Colour(220f, 0.7f, 0.1f),
                        Opacity = 1f,
                        Quantity = budget,
                        Speed = 0f,
                        Scale = 1f,
                        Rotation = 0f,
                        Mass = new RangeF(8f, 12f)
                    },
                    BlendMode = BlendMode.Add,
                    ReclaimInterval = 600f
                };

                emitters[i].Modifiers.Add(new DragModifier
                {
                    DragCoefficient = .47f,
                    Density         = .15f
                }, 15f);
                emitters[i].Modifiers.Add(new VortexModifier
                {
                    Position = Coordinate.Origin,
                    Mass = 200f,
                    MaxSpeed = 1000f
                }, 30f);
                emitters[i].Modifiers.Add(new VelocityHueModifier
                {
                    StationaryHue = 220f,
                    VelocityHue = 300f,
                    VelocityThreshold = 800f
                }, 15f);
                emitters[i].Modifiers.Add(new ContainerModifier
                        {
                            RestitutionCoefficient = 0.75f,
                            Position = Coordinate.Origin,
                            Width    = worldSize.Width,
                            Height   = worldSize.Height
                        }, 30f);
                emitters[i].Modifiers.Add(new MoveModifier(), 60f);
            };

            var renderer = new PointSpriteRenderer(device, budget)
            {
            //                EnableFastFade = true
            };

            var texture = Texture.FromFile(device, "Pixel.dds");

            var fontDescription = new FontDescription
            {
                Height         = 16,
                FaceName       = "Consolas",
                PitchAndFamily = FontPitchAndFamily.Mono,
                Quality        = FontQuality.Draft
            };

            var font = new Font(device, fontDescription);

            var totalTimer = Stopwatch.StartNew();
            var updateTimer = new Stopwatch();
            var renderTimer = new Stopwatch();

            var totalTime = 0f;

            foreach (var emitter in emitters)
            {
                emitter.Trigger(Coordinate.Origin);
            }

            float updateTime = 0f;

            RenderLoop.Run(form, () =>
                {
                    // ReSharper disable AccessToDisposedClosure
                    var frameTime = ((float)totalTimer.Elapsed.TotalSeconds) - totalTime;
                    totalTime = (float)totalTimer.Elapsed.TotalSeconds;

                    var mousePosition = form.PointToClient(RenderForm.MousePosition);

                    Task.WaitAll(
                        Task.Factory.StartNew(() =>
                        {
                            var mouseVector = new Vector3(mousePosition.X, mousePosition.Y, 0f);
                            var unprojected = Vector3.Unproject(mouseVector, 0, 0, renderSize.Width, renderSize.Height, 0f, 1f, wvp);

                            Parallel.ForEach(emitters, emitter => ((VortexModifier)emitter.Modifiers.ElementAt(1)).Position = new Coordinate(unprojected.X, unprojected.Y));

                            updateTimer.Restart();
                            Parallel.ForEach(emitters, emitter => emitter.Update(frameTime));
                            updateTimer.Stop();
                            updateTime = (float)updateTimer.Elapsed.TotalSeconds;
                            _updateTimes.Add(updateTime);
                        }),
                        Task.Factory.StartNew(() =>
                        {
                            device.Clear(ClearFlags.Target, Color.Black, 1f, 0);
                            device.BeginScene();

                            renderTimer.Restart();
                            for (int i = 0; i < numEmitters; i++)
                            {
                                renderer.Render(emitters[i], wvp, texture);
                            }
                            renderTimer.Stop();
                            var renderTime = (float)renderTimer.Elapsed.TotalSeconds;

                            var totalUpdateTime = 0f;
            //	                        foreach (var time in _updateTimes)
            //	                        {
            //		                        totalUpdateTime += time;
            //	                        }
            //	                        totalUpdateTime /= _updateTimes.Count;
            //
            //							if(_updateTimes.Count > 100)
            //								_updateTimes.RemoveAt(0);

                            font.DrawText(null, String.Format("Time:        {0}", totalTimer.Elapsed), 0, 0, Color.White);
                            font.DrawText(null, String.Format("Particles:   {0:n0}", emitters[0].ActiveParticles * numEmitters), 0, 16, Color.White);
                            font.DrawText(null, String.Format("Update:      {0:n4} ({1,8:P2})", updateTime, updateTime / 0.01666666f), 0, 32, Color.White);
                            font.DrawText(null, String.Format("Render:      {0:n4} ({1,8:P2})", renderTime, renderTime / 0.01666666f), 0, 48, Color.White);

                            device.EndScene();
                            device.Present();
                        })
                    );

                    if (Keyboard.IsKeyDown(Key.Escape))
                        Environment.Exit(0);
            // ReSharper restore AccessToDisposedClosure
                });

            form.Dispose();
            font.Dispose();
            device.Dispose();
            direct3d.Dispose();
        }
Ejemplo n.º 7
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniCube Direct3D9 Sample");

            // Creates the Device
            var direct3D = new Direct3D();
            var device = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

            // Creates the VertexBuffer
            var vertices = new VertexBuffer(device, Utilities.SizeOf<Vector4>() * 2 * 36, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
            vertices.Lock(0, 0, LockFlags.None).WriteRange(new[]
                                  {
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front
                                      new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top
                                      new Vector4(-1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),

                                      new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom
                                      new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left
                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),

                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                            });
            vertices.Unlock();

            // Compiles the effect
            var effect = Effect.FromFile(device, "MiniCube.fx", ShaderFlags.None);

            // Allocate Vertex Elements
            var vertexElems = new[] {
        		new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Position, 0),
        		new VertexElement(0, 16, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Color, 0),
				VertexElement.VertexDeclarationEnd
        	};

            // Creates and sets the Vertex Declaration
            var vertexDecl = new VertexDeclaration(device, vertexElems);
            device.SetStreamSource(0, vertices, 0, Utilities.SizeOf<Vector4>() * 2);
            device.VertexDeclaration = vertexDecl;

            // Get the technique
            var technique = effect.GetTechnique(0);
            var pass = effect.GetPass(technique, 0);

            // Prepare matrices
            var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f);
            var viewProj = Matrix.Multiply(view, proj);

            // Use clock
            var clock = new Stopwatch();
            clock.Start();

            RenderLoop.Run(form, () =>
            {
                var time = clock.ElapsedMilliseconds / 1000.0f;

                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                device.BeginScene();

                effect.Technique = technique;
                effect.Begin();
                effect.BeginPass(0);

                var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj;
                effect.SetValue("worldViewProj", worldViewProj);

                device.DrawPrimitives(PrimitiveType.TriangleList, 0, 12);

                effect.EndPass();
                effect.End();

                device.EndScene();
                device.Present();
            });

            effect.Dispose();
            vertices.Dispose();
            device.Dispose();
            direct3D.Dispose();
        }
Ejemplo n.º 8
0
        public static void Main()
        {
            var form = new RenderForm("SimpleD3D9 by C#") { ClientSize = new Size(1024, 768) };

            var device = new D3D9Device(
                new Direct3D(),
                CUDADevice.Default.ID,
                DeviceType.Hardware,
                form.Handle,
                CreateFlags.HardwareVertexProcessing,
                new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

            var vertices = new VertexBuffer(device, Utilities.SizeOf<Vector4>()*Total, Usage.WriteOnly,
                VertexFormat.None, Pool.Default);

            var vertexElems = new []
            {
                new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
                new VertexElement(0, 12, DeclarationType.Ubyte4, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                VertexElement.VertexDeclarationEnd
            };

            var vertexDecl = new VertexDeclaration(device, vertexElems);

            var worker = Worker.CreateByFunc(() => Generate(device));
            var updater = new SimpleD3D9(GPUModuleTarget.Worker(worker));

            var view = Matrix.LookAtLH(
                new Vector3(0.0f, 3.0f, -2.0f), // the camera position
                new Vector3(0.0f, 0.0f, 0.0f),  // the look-at position
                new Vector3(0.0f, 1.0f, 0.0f)); // the up direction

            var proj = Matrix.PerspectiveFovLH(
                (float) (Math.PI/4.0), // the horizontal field of view
                1.0f,
                1.0f,
                100.0f);

            device.SetTransform(TransformState.View, view);
            device.SetTransform(TransformState.Projection, proj);
            device.SetRenderState(RenderState.Lighting, false);

            var vbres = RegisterVerticesResource(vertices);
            var clock = System.Diagnostics.Stopwatch.StartNew();

            RenderLoop.Run(form, () =>
            {
                var time = (float) (clock.Elapsed.TotalMilliseconds)/300.0f;
                updater.Update(vbres, time);

                // Now normal D3D9 rendering procedure.
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, new ColorBGRA(0, 40, 100, 0), 1.0f, 0);
                device.BeginScene();

                device.VertexDeclaration = vertexDecl;
                device.SetStreamSource(0, vertices, 0, Utilities.SizeOf<Vector4>());
                // we use PointList as the graphics primitives
                device.DrawPrimitives(SharpDX.Direct3D9.PrimitiveType.PointList, 0, Total);

                device.EndScene();
                device.Present();
            });

            UnregisterVerticesResource(vbres);

            updater.Dispose();
            worker.Dispose();
            vertexDecl.Dispose();
            vertices.Dispose();
            device.Dispose();
            form.Dispose();
        }
Ejemplo n.º 9
0
        public void Sin()
        {
            for (int i = 0; i < NumChanel; i++)
            {
                vectormas[i] = new Vector2[NumVect];
            }

            form = new RenderForm("DirectX Rendered Window");
            //form.AllowUserResizing = false;
            form.UserResized += new EventHandler<EventArgs>(onResize);
            PresentParameters presentParams = new PresentParameters(form.ClientSize.Width, form.ClientSize.Height);
            device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, presentParams);

            //Line[] linemas = new Line[NumChanel];
            for (int i = 0; i < NumChanel; i++)
            {
                linemas[i] = new Line(device);
                linemas[i].Width = 1;
            }

            /*Line line = new Line(device);
            line.Width = 1;
            Line line2 = new Line(device);
            line2.Width = 3;*/

            //ColorBGRA[] colormas = new ColorBGRA[NumChanel];
            Random randColor = new Random();

            for (int i = 0; i < NumChanel; i++)
            {
                colormas[i].B = (byte)randColor.Next(0, 255);
                colormas[i].G = (byte)randColor.Next(0, 255);
                colormas[i].R = (byte)randColor.Next(0, 255);
                colormas[i].A = 255;
            }

            var timer = new System.Timers.Timer(1);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(onTick);
            timer.Enabled = true;

            /*double x = 0;
            for (int i = 0; i < NumVect; i++)
            {
                x+=0.1;
                double y = 100*Math.Sin(x * Math.PI / 15.0)+300;
                vector[i] = new Vector2((float)x,(float)y);
            }*/

            RenderLoop.Run(form, () =>
            {
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                //device.SoftwareVertexProcessing = true;
                device.BeginScene();

                //line.Antialias = true;
                //line2.Antialias = true;
                //line.GLLines = true;
                //line2.GLLines = true;
                //line.PatternScale = (float)5;
                //line.Pattern = 0xFFFFFF;

                //line.Draw(vector, color);
                //line2.Draw(vector2, color2);

                for (int i = 0; i < NumChanel; i++)
                {
                    linemas[i].Draw(vectormas[i], colormas[i]);
                    linemas[i].Antialias = true;
                }

                device.EndScene();
                device.Present();
            });
        }
Ejemplo n.º 10
0
        private static void TryCreateDeviceInternal(IntPtr windowHandle, DeviceType deviceType, MyRenderDeviceSettings settingsToTry, out Device device, out PresentParameters parameters)
        {
            device = null;
            parameters = CreatePresentParameters(settingsToTry, windowHandle);
            while (device == null)
            {
                try
                {
                    // These calls are here to ensure that none of these calls throw exceptions (even if their results are not used).
                    m_d3d.Dispose();
                    m_d3d = new Direct3D();

                    var d3dCaps = m_d3d.GetDeviceCaps(settingsToTry.AdapterOrdinal, DeviceType.Hardware);

                    device = new Device(m_d3d, settingsToTry.AdapterOrdinal, deviceType, Parameters.DeviceWindowHandle,
                        CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
                        Parameters);
                    device.Clear(ClearFlags.Target, new SharpDX.ColorBGRA(0, 0, 0, 1), 1.0f, 0);

                    var caps = Device.Capabilities;
                }
                catch (SharpDX.SharpDXException e)
                {
                    if (e.ResultCode == ResultCode.NotAvailable ||
                        (e.ResultCode == ResultCode.InvalidCall && GetForegroundWindow() != Parameters.DeviceWindowHandle))
                    {
                        // User has probably Alt+Tabbed or locked his computer before the game has started.
                        // To counter this, we try creating device again a bit later.
                        Thread.Sleep(2000);
                        MyLog.Default.WriteLine("Device creation failed with " + e.Message);
                    }
                    else
                    {
                        // Either settings or graphics card are not supported.
                        MyLog.Default.WriteLine(e);
                        throw;
                    }
                }

                try
                {
                    MyLog.Default.WriteLine("Loading adapters");
                    m_adaptersList = GetAdaptersList(m_d3d);
                    MyLog.Default.WriteLine("Found adapters");
                    foreach (var adapter in m_adaptersList)
                    {
                        adapter.LogInfo(MyLog.Default.WriteLine);
                    }
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e);
                    throw;
                }
            }
        }
Ejemplo n.º 11
0
        static void Main()
        {
            var form = new RenderForm("SharpDX - Direct3D9 Font Sample");
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;
            var device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(width, height) { PresentationInterval = PresentInterval.One });

            // Initialize the Font
            FontDescription fontDescription = new FontDescription()
            {
                Height = 72,
                Italic = false,
                CharacterSet = FontCharacterSet.Ansi,
                FaceName = "Arial",
                MipLevels = 0,
                OutputPrecision = FontPrecision.TrueType,
                PitchAndFamily = FontPitchAndFamily.Default,
                Quality = FontQuality.ClearType,
                Weight = FontWeight.Bold
            };



            var font = new Font(device, fontDescription);

            var displayText = "Direct3D9 Text!";

            // Measure the text to display
            var fontDimension = font.MeasureText(null, displayText, new Rectangle(0, 0, width, height), FontDrawFlags.Center | FontDrawFlags.VerticalCenter);

            int xDir = 1;
            int yDir = 1;

            RenderLoop.Run(form, () =>
            {
                device.Clear(ClearFlags.Target, Color.Black, 1.0f, 0);
                device.BeginScene();

                // Make the text boucing on the screen limits
                if ((fontDimension.Right + xDir) > width)
                    xDir = -1;
                else if ((fontDimension.Left + xDir) <= 0)
                    xDir = 1;

                if ((fontDimension.Bottom + yDir) > height)
                    yDir = -1;
                else if ((fontDimension.Top + yDir) <= 0)
                    yDir = 1;

                fontDimension.Left += (int)xDir;
                fontDimension.Top += (int)yDir;
                fontDimension.Bottom += (int)yDir;
                fontDimension.Right += (int)xDir;

                // Draw the text
                font.DrawText(null, displayText, fontDimension, FontDrawFlags.Center | FontDrawFlags.VerticalCenter, Color.White);

                device.EndScene();
                device.Present();
            });
        }
Ejemplo n.º 12
0
        public void display(VideoFrame videoFrame, Color backColor, RenderMode mode)
        {
            lock (renderLock)
            {
                if (device == null)
                {
                    return;
                }

                SharpDX.Result deviceStatus = device.TestCooperativeLevel();

                if (deviceStatus.Success == true)
                {
                    try
                    {
                        SharpDX.ColorBGRA backColorDX = new SharpDX.ColorBGRA(backColor.R,
                                                                              backColor.G, backColor.B, backColor.A);

                        device.Clear(D3D.ClearFlags.Target, backColorDX, 1.0f, 0);

                        if (mode == RenderMode.CLEAR_SCREEN)
                        {
                            device.Present();
                            return;
                        }

                        device.BeginScene();

                        SharpDX.Rectangle videoSourceRect = new SharpDX.Rectangle();

                        if (mode == RenderMode.NORMAL)
                        {
                            videoSourceRect = new SharpDX.Rectangle(0, 0, videoFrame.Width, videoFrame.Height);

                            SharpDX.DataRectangle stream = offscreen.LockRectangle(LockFlags.None);

                            videoFrame.copyFrameDataToSurface(stream.DataPointer, stream.Pitch);

                            offscreen.UnlockRectangle();
                        }
                        else if (mode == RenderMode.PAUSED)
                        {
                            videoSourceRect = new SharpDX.Rectangle(0, 0, offscreen.Description.Width, offscreen.Description.Height);
                        }

                        videoDestRect = getVideoDestRect(backBuffer);

                        device.StretchRectangle(offscreen, videoSourceRect,
                                                backBuffer, videoDestRect, D3D.TextureFilter.Linear);

                        drawText();

                        device.EndScene();
                        device.Present();

                        RenderMode = mode;
                    }
                    catch (SharpDX.SharpDXException)
                    {
                        //log.Info("lost direct3d device", e);
                        deviceStatus = device.TestCooperativeLevel();
                    }
                }

                if (deviceStatus.Code == D3D.ResultCode.DeviceLost.Result)
                {
                    //Can't Reset yet, wait for a bit
                }
                else if (deviceStatus.Code == D3D.ResultCode.DeviceNotReset.Result)
                {
                    resetDevice();
                }
            }
        }