Inheritance: Interactive
        // using ctimer to simulate ramping of slider scene is Selected on UI
        public void SimulateLoadRamp(IRoom allRoomRef, int lightIndex, float rampTo)
        {
            LightDevice light       = _allLightDevices[lightIndex];
            float       light1Level = SimplSharpDeviceHelper.UshortToPercent(light.LoadLevel);

            ushort levelValue1;

            for (float i = light1Level; i < rampTo; i++)
            {
                levelValue1 = SimplSharpDeviceHelper.PercentToUshort(i);

                allRoomLights.DimmableLights[lightIndex].LightIsAtLevel((sig, component) => { sig.UShortValue = levelValue1; });

                light.LoadLevel = levelValue1;
            }

            for (float i = light1Level; i > rampTo; i--)
            {
                levelValue1 = SimplSharpDeviceHelper.PercentToUshort(i);

                allRoomLights.DimmableLights[lightIndex].LightIsAtLevel((sig, component) => { sig.UShortValue = levelValue1; });

                light.LoadLevel = levelValue1;
            }
        }
        // using ctimer to simulate ramping of slider when light is turn on/off
        public void SimulateOnOffLightRamp(object sender, string status)
        {
            LightDevice light = (LightDevice)((DimmableLight)sender).UserObject;

            float vOut = SimplSharpDeviceHelper.UshortToPercent(light.LoadLevel);

            ushort newLevelValue;

            if (status == "On")
            {
                for (float i = vOut; i < 100; i++)
                {
                    ushort levelValue = SimplSharpDeviceHelper.PercentToUshort(i);
                    ((DimmableLight)sender).LightIsAtLevel((sig, component) => { sig.UShortValue = levelValue; });
                }

                newLevelValue   = SimplSharpDeviceHelper.PercentToUshort(100);
                light.LoadLevel = newLevelValue;
            }
            else
            {
                for (float i = vOut; i > 0; i--)
                {
                    ushort levelValue = SimplSharpDeviceHelper.PercentToUshort(i);
                    ((DimmableLight)sender).LightIsAtLevel((sig, component) => { sig.UShortValue = levelValue; });
                }

                newLevelValue   = SimplSharpDeviceHelper.PercentToUshort(0);
                light.LoadLevel = newLevelValue;
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form();

            form.ClientSize = new Size(800, 600);

            using (var device = LightDevice.Create(form))
            {
                var target = new RenderTargetList(device.GetDefaultTarget(Color.White.WithAlpha(1)));
                target.Apply();

                var sprite  = new Sprite(device);
                var guiFont = new TextureFontCache(device, SystemFonts.DefaultFont);

                form.Show();
                device.RunMultithreadLoop(delegate()
                {
                    target.ClearAll();

                    sprite.Apply();
                    sprite.DrawString(guiFont, "Hello World!", 0, 0, 800);

                    device.Present(true);
                });
            }
        }
        // Event to set selected light level
        private void LightLevel(object sender, UIEventArgs e)
        {
            if (e.SigArgs.Sig.BoolValue)
            {
                LightDevice light = (LightDevice)((DimmableLight)sender).UserObject;

                ((DimmableLight)sender).LightIsAtLevel((sig, component) => { sig.UShortValue = e.SigArgs.Sig.UShortValue; });
            }
        }
Exemple #5
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form();

            form.ClientSize = new Size(800, 600);

            using (var device = LightDevice.Create(form))
            {
                var target = new RenderTargetList(device.GetDefaultTarget(), device.CreateDepthStencilTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Shader.fx", ShaderType.Vertex | ShaderType.Pixel));
                pipeline.Apply();

                var vertexConstant = pipeline.CreateConstantBuffer <Matrix4x4>();
                pipeline.SetConstant(ShaderType.Vertex, 0, vertexConstant);

                var input      = pipeline.CreateVertexDataProcessor <Vertex>();
                var bufferData = new Vertex[6 * 6];
                for (int i = 0; i < bufferData.Length; ++i)
                {
                    bufferData[i].Color = Color.FromArgb(250, i / 6 * 40, 250 - i / 6 * 30).WithAlpha(1);
                }
                SetupCubeFace(bufferData, 00, new Vector3(0.5f, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0));
                SetupCubeFace(bufferData, 06, new Vector3(-0.5f, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1));
                SetupCubeFace(bufferData, 12, new Vector3(0, 0.5f, 0), new Vector3(1, 0, 0), new Vector3(0, 0, 1));
                SetupCubeFace(bufferData, 18, new Vector3(0, -0.5f, 0), new Vector3(0, 0, 1), new Vector3(1, 0, 0));
                SetupCubeFace(bufferData, 24, new Vector3(0, 0, 0.5f), new Vector3(0, 1, 0), new Vector3(1, 0, 0));
                SetupCubeFace(bufferData, 30, new Vector3(0, 0, -0.5f), new Vector3(1, 0, 0), new Vector3(0, 1, 0));
                var buffer = input.CreateImmutableBuffer(bufferData);

                var camera = new Camera(new Vector3(10, 0, 0));
                camera.SetForm(form);
                var proj = device.CreatePerspectiveFieldOfView((float)Math.PI / 4).Transpose();

                vertexConstant.Value = proj * camera.GetViewMatrix();
                var pt = new Vector4(0, 0, 0, 0);
                var r  = Vector4.Transform(pt, vertexConstant.Value);

                form.Show();
                device.RunMultithreadLoop(delegate()
                {
                    target.ClearAll();

                    camera.Step();
                    vertexConstant.Value = proj * camera.GetViewMatrix();
                    vertexConstant.Update();

                    buffer.DrawAll();
                    device.Present(true);
                });
            }
        }
Exemple #6
0
        public void Run()
        {
            using (var form = new Form())
            {
                _form           = form;
                form.Text       = "ImGui.NET on LightDx";
                form.ClientSize = new Size(800, 600);
                form.KeyDown   += OnKeyDown;
                form.KeyUp     += OnKeyUp;

                using (var device = LightDevice.Create(form))
                {
                    _device = device;

                    var target = new RenderTarget(device.GetDefaultTarget());
                    target.Apply();

                    Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                               ShaderSource.FromResource("Shader.fx", ShaderType.Vertex | ShaderType.Pixel));;
                    _pipeline = pipeline;

                    pipeline.SetResource(0, CreateFontTexture());
                    pipeline.SetBlender(Blender.AlphaBlender);

                    pipeline.Apply();

                    var input = pipeline.CreateVertexDataProcessor <Vertex>();
                    _inputDataProcessor = input;

                    var constant = pipeline.CreateConstantBuffer <VSConstant>();
                    pipeline.SetConstant(ShaderType.Vertex, 0, constant);

                    void UpdateWindowSize()
                    {
                        constant.Value.Width  = device.ScreenWidth;
                        constant.Value.Height = device.ScreenHeight;
                        constant.Update();
                    }

                    device.ResolutionChanged += (sender, e) => UpdateWindowSize();
                    UpdateWindowSize();

                    form.Show();
                    device.RunLoop(delegate()
                    {
                        target.ClearAll();

                        RenderFrame();

                        device.Present(true);
                    });
                }
            }
        }
        // Event to turn off selected light
        private void LightOff(object sender, UIEventArgs e)
        {
            if (e.SigArgs.Sig.BoolValue)
            {
                LightDevice light = (LightDevice)((DimmableLight)sender).UserObject;

                // using ctimer for demo.  When using Light Devices please use Ramping object
                // _cTimer1 = new CTimer(o => SimulateOnOffLightRamp(sender, "Off"), 500);
                // using ctimer for demo.  When using Light Devices please use Ramping object
                _cTimers.Add(new CTimer(o => SimulateOnOffLightRamp(sender, "Off"), 300));
            }
        }
Exemple #8
0
        public DeferredRenderer(LightDevice device, string shaderFile, Texture2D[] input, bool alphaBlend)
        {
            _device = device;

            //target
            var screenTarget = device.GetDefaultTarget();

            _target = new RenderTargetList(screenTarget);

            //pipeline
            _pipeline = device.CompilePipeline(InputTopology.Triangle,
                                               ShaderSource.FromResource(shaderFile, ShaderType.Vertex | ShaderType.Pixel));
            if (alphaBlend)
            {
                _pipeline.SetBlender(Blender.AlphaBlender);
            }

            _psConstants = _pipeline.CreateConstantBuffer <PSConstants>();
            _psConstants.Value.ClearColor = Color.AliceBlue.WithAlpha(1);
            _pipeline.SetConstant(ShaderType.Pixel, 0, _psConstants);

            for (int i = 0; i < input.Length; ++i)
            {
                _pipeline.SetResource(i, input[i]);
            }

            //vb
            var processor = _pipeline.CreateVertexDataProcessor <Vertex>();
            var data      = new Vertex[]
            {
                new Vertex {
                    Position = new Vector2(0, 0)
                },
                new Vertex {
                    Position = new Vector2(1, 0)
                },
                new Vertex {
                    Position = new Vector2(0, 1)
                },
                new Vertex {
                    Position = new Vector2(0, 1)
                },
                new Vertex {
                    Position = new Vector2(1, 0)
                },
                new Vertex {
                    Position = new Vector2(1, 1)
                },
            };

            _vertexBuffer = processor.CreateImmutableBuffer(data);
        }
Exemple #9
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form();

            form.ClientSize = new Size(800, 600);

            using (var device = LightDevice.Create(form))
            {
                var target = new RenderTargetList(device.GetDefaultTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Shader.fx", ShaderType.Vertex | ShaderType.Pixel));
                pipeline.Apply();

                var input  = pipeline.CreateVertexDataProcessor <Vertex>();
                var buffer = input.CreateImmutableBuffer(new[] {
                    new Vertex {
                        Color = 0, Position = new Vector4(0.0f, 0.5f, 0.5f, 1.0f)
                    },
                    new Vertex {
                        Color = 1, Position = new Vector4(0.5f, -0.5f, 0.5f, 1.0f)
                    },
                    new Vertex {
                        Color = 2, Position = new Vector4(-0.5f, -0.5f, 0.5f, 1.0f)
                    },
                });

                var indexBuffer = pipeline.CreateImmutableIndexBuffer(new uint[] { 2, 0, 1 });

                var srBuffer = pipeline.CreateShaderResourceBuffer(new[]
                {
                    Color.Blue.WithAlpha(1),
                    Color.Red.WithAlpha(1),
                    Color.Green.WithAlpha(1),
                }, false);
                pipeline.SetResource(ShaderType.Vertex, 0, srBuffer);

                form.Show();
                device.RunMultithreadLoop(delegate()
                {
                    target.ClearAll();
                    indexBuffer.DrawAll(buffer);
                    device.Present(true);
                });
            }
        }
Exemple #10
0
    // Start is called before the first frame update
    public TurnLight(LightDevice device, GameObject lightComponent)
    {
        this.device       = device;
        this.actingObject = lightComponent;
        string state = this.device.state;

        if (state == "on")
        {
            this.command = "turn light off";
        }
        else
        {
            this.command = "turn light on";
        }
        this.description = "flipping light";
    }
Exemple #11
0
        private void InitializeRendering()
        {
            _renderWindow = new Form();
            _renderWindow.FormBorderStyle = FormBorderStyle.None;
            _renderWindow.TopLevel        = false;
            _renderWindow.Parent          = this;
            _renderWindow.Dock            = DockStyle.Fill;
            _renderWindow.Show();

            _device            = LightDevice.Create(_renderWindow);
            _device.AutoResize = false; //We don't use loop, so AutoResize is not checked.

            _spriteDebug = new Sprite(_device);
            _spriteFont  = new TextureFontCache(_device, SystemFonts.DefaultFont);

            _target = new RenderTargetList(_device.GetDefaultTarget(Color.AliceBlue.WithAlpha(1)), _device.CreateDepthStencilTarget());
            _target.Apply();

            _modelPipeline = _device.CompilePipeline(InputTopology.Point,
                                                     ShaderSource.FromResource("Model.fx", ShaderType.Vertex | ShaderType.Geometry | ShaderType.Pixel));
            _inputProcessor = _modelPipeline.CreateVertexDataProcessor <Voxel>();

            _vsConstant = _modelPipeline.CreateConstantBuffer <Matrix4x4>();
            _modelPipeline.SetConstant(ShaderType.Vertex, 0, _vsConstant);
            _gsConstant = _modelPipeline.CreateConstantBuffer <GSConstant>();
            _modelPipeline.SetConstant(ShaderType.Geometry, 0, _gsConstant);

            _camera = new Camera(_device, new Vector3(0, 0, 0));
            _camera.SetForm(_renderWindow);

            _renderWindowLastWidth  = _renderWindow.ClientSize.Width;
            _renderWindowLastHeight = _renderWindow.ClientSize.Height;
            ResizeBegin            += RenderWindow_ResizeBegin;
            ResizeEnd += RenderWindow_ResizeEnd;
            _renderWindow.ResizeBegin       += RenderWindow_ResizeBegin;
            _renderWindow.ResizeEnd         += RenderWindow_ResizeEnd;
            _renderWindow.ClientSizeChanged += RenderWindow_ClientSizeChanged;

            _renderWindow.DoubleClick += delegate(object obj, EventArgs e)
            {
                ResetCamera();
            };
        }
Exemple #12
0
        public void BasicCommandTest()
        {
            AutoHomeInvoker domotica = new AutoHomeInvoker();

            // Create Devices
            LightDevice   luz     = new LightDevice();
            NetflixDevice nerflis = new NetflixDevice();

            // Create Commands with concrete devices
            CommandLightsOn cmdLight   = new CommandLightsOn(luz);
            NetflixModeOn   cmdNetflix = new NetflixModeOn(nerflis);

            // Add commands to the invoker.
            domotica.AddCommand(cmdLight);
            domotica.AddCommand(cmdNetflix);

            // As client, invoke a command to activate one concrete device.
            domotica.ActivateDevice(1);
        } // end BasicCommandTest()
Exemple #13
0
        public DeferredTarget(LightDevice device)
        {
            _device = device;

            //target & output
            var screenTarget = device.GetDefaultTarget();
            var colorTarget  = device.CreateTextureTarget();
            var normalTarget = device.CreateTextureTarget();
            var depthTarget  = device.CreateDepthStencilTarget();

            _normalTargetObj = normalTarget;

            _renderTarget1 = new RenderTargetList(colorTarget, normalTarget, depthTarget);
            _renderTarget2 = new RenderTargetList(screenTarget, normalTarget, depthTarget);

            colorTarget.ClearColor = Color.Black.WithAlpha(0);

            _colorData  = colorTarget.GetTexture2D();
            _depthData  = depthTarget.GetTexture2D();
            _normalData = normalTarget.GetTexture2D();
        }
        private static void datalog()
        {
            while (true)
            {
                fileLog = new FileLogger("file.log");

                // Crea ed utilizza un ADC. Il codice del ADC utilizzerà un gestore del bus SPI
                adc = new DigitalConverterMCP3208();

                lux      = new LightSensor(adc, 0, 3.3);
                temp     = new TemperatureSensor(adc, 1, 3.3);
                moisture = new SoilMoistureSensor(adc, 2, 3.3);
                co2      = new CO2Sensor(adc, 3, 4.9);
                rh       = new RelativeHumiditySensor(adc, 4, 5.0);

                shift = new OutShiftRegister(16, 25, 24, 23);

                lcd = new LCD1602Shift(shift, 12, 11, 10, 9, 13, 14);

                irrigator = new Device_OnOffShift(shift, 8);
                ////////irrigator.WriteLog += WriteFileLog;
                humidifier = new Device_OnOffShift(shift, 2);
                ////////humidifier.WriteLog += WriteFileLog;

                lightDevice = new LightDevice(shift, 3, 4, 5, 6, 7, 21, 20);

                lightDevice.PercentualeApertura(50);
                //irrigator.TimeOn(3000);

                //_timer = new DispatcherTimer();
                //_timer.Interval = TimeSpan.FromMilliseconds(1000);
                //_timer.Tick += Timer_Tick;
                //if (_pin != null)
                //{
                //    _timer.Start();
                //}
            }
        }
        public RenderToTexturePipeline(LightDevice device)
        {
            _device = device;

            //pipeline
            _pipeline1 = device.CompilePipeline(InputTopology.Triangle,
                                                ShaderSource.FromResource("RenderToTextureVS.fx", ShaderType.Vertex),
                                                ShaderSource.FromResource("RenderToTexturePS.fx", ShaderType.Pixel));
            _pipeline1.SetBlender(Blender.AlphaBlender);

            _pipeline2 = device.CompilePipeline(InputTopology.Triangle,
                                                ShaderSource.FromResource("RenderToTextureVS.fx", ShaderType.Vertex),
                                                ShaderSource.FromResource("ForwardRenderingPS.fx", ShaderType.Pixel));
            _pipeline2.SetBlender(Blender.AlphaBlender);

            //constant (VS)
            _constantBufferVS = _pipeline1.CreateConstantBuffer <VSConstants>();
            _pipeline1.SetConstant(ShaderType.Vertex, 0, _constantBufferVS);
            _constantBufferVS.Value.World = Matrix4x4.Identity;

            device.ResolutionChanged += (sender, e) => SetupProjMatrix();
            SetupProjMatrix();
        }
Exemple #16
0
 public CommandLightsOn(LightDevice l) => _light = l;
Exemple #17
0
        static void Main()
        {
            const float BlockSize = 0.02f;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form();

            form.ClientSize = new Size(800, 600);

            var func          = MakeFunction(1 / BlockSize);
            var meshGenerator = new DCSolver(func, (int)(4 / BlockSize));
            var rawMesh       = meshGenerator.Solve();

            rawMesh = new MeshSimplifier(rawMesh, ClusterSizeHelper.GetSampleAverage(rawMesh, 3)).Run();
            var m = NormalMesh.MakeNormal(rawMesh);

            using (var device = LightDevice.Create(form))
            {
                var target = new RenderTargetList(device.GetDefaultTarget(Color.AliceBlue.WithAlpha(1)), device.CreateDepthStencilTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Viewer.Shader.fx", ShaderType.Vertex | ShaderType.Pixel));
                pipeline.Apply();

                var vertexConstant = pipeline.CreateConstantBuffer <Matrix4x4>();
                pipeline.SetConstant(ShaderType.Vertex, 0, vertexConstant);

                var input = pipeline.CreateVertexDataProcessor <Vertex>();
                var vb    = input.CreateImmutableBuffer(m.Vertices.Select(vv => new Vertex {
                    Position = new Vector4(m.Positions[vv.Position] * BlockSize, 1),
                    Normal   = new Vector4(vv.Normal, 0),
                }).ToArray());

                var ib = pipeline.CreateImmutableIndexBuffer(m.Triangles.SelectMany(tt => new[] { tt.Va, tt.Vb, tt.Vc }).ToArray());

                var camera = new Camera(new Vector3(10, 0, 0));
                camera.SetForm(form);
                var proj = device.CreatePerspectiveFieldOfView((float)Math.PI / 4).Transpose();

                vertexConstant.Value = proj * camera.GetViewMatrix();
                var pt = new Vector4(0, 0, 0, 0);
                var r  = Vector4.Transform(pt, vertexConstant.Value);

                form.Show();
                device.RunMultithreadLoop(delegate()
                {
                    target.ClearAll();

                    camera.Step();
                    var view             = camera.GetViewMatrix();
                    vertexConstant.Value = proj * view;
                    vertexConstant.Update();

                    ib.DrawAll(vb);
                    device.Present(true);
                });
            }
        }
Exemple #18
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string filename;

            using (var dialog = new OpenFileDialog {
                Filter = "*.pmx|*.pmx"
            })
            {
                if (dialog.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }
                filename = dialog.FileName;
            }

            var form = new Form
            {
                ClientSize = new Size(800, 600),
                Text       = "Pmx Viewer",
            };
            var device = LightDevice.Create(form);

            var renderToTexturePipeline = new RenderToTexturePipeline(device);
            var deferredTarget          = new DeferredTarget(device);
            var deferredRendering1      = new DeferredRenderer(device, "Deferred1.fx",
                                                               new[] { deferredTarget.ColorData, deferredTarget.NormalData, deferredTarget.DepthData }, false);
            var deferredRendering2 = new DeferredRenderer(device, "Deferred2.fx",
                                                          new[] { deferredTarget.NormalData, deferredTarget.DepthData }, true);

            deferredRendering2.ClearColor = Color.Black.WithAlpha(0);

            var model = new PmxModel(renderToTexturePipeline, filename);

            model.HideMaterial(29); //Hide the shadow of hair. We don't have diffuse color in shader.
            model.SetTransparent(26);
            var camera = new Camera(form);

            form.Show();
            form.Activate();
            var frameCounter = new FrameCounter();

            frameCounter.Start();

            device.RunMultithreadLoop(delegate()
            {
                var time = frameCounter.NextFrame() / 1000;

                camera.Update();

                renderToTexturePipeline.View = camera.GetViewMatrix().Transpose();
                renderToTexturePipeline.UpdateConstants();

                deferredTarget.ClearAll();
                deferredTarget.ApplyDeferred();
                renderToTexturePipeline.ApplyDeferred();
                model.DrawSolid();

                deferredRendering1.ClearAll();
                deferredRendering1.Render();

                deferredTarget.ClearDeferred();
                deferredTarget.ApplyForward();
                renderToTexturePipeline.ApplyForward();
                model.DrawTransparent();

                deferredRendering2.Render();

                device.Present(true);
            });
        }
Exemple #19
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form
            {
                ClientSize = new Size(800, 600),
                Text       = "Tutorial 4: Buffers, Shaders, and HLSL",
            };

            using (var device = LightDevice.Create(form))
            {
                //---------------------
                // Target & Pipeline
                //---------------------

                var target = new RenderTarget(device.GetDefaultTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Color_vs.fx", ShaderType.Vertex),
                                                           ShaderSource.FromResource("Color_ps.fx", ShaderType.Pixel));
                pipeline.Apply();

                //---------------------
                // Vertex buffer
                //---------------------

                var vertexDataProcessor = pipeline.CreateVertexDataProcessor <Vertex>();
                var vertexBuffer        = vertexDataProcessor.CreateImmutableBuffer(new[] {
                    new Vertex {
                        Position = new Vector4(-1, -1, 0, 1), Color = new Vector4(0, 1, 0, 1)
                    },
                    new Vertex {
                        Position = new Vector4(0, 1, 0, 1), Color = new Vector4(0, 1, 0, 1)
                    },
                    new Vertex {
                        Position = new Vector4(1, -1, 0, 1), Color = new Vector4(0, 1, 0, 1)
                    },
                });

                //---------------------
                // Index buffer
                //---------------------

                var indexBuffer = pipeline.CreateImmutableIndexBuffer(new uint[] { 0, 1, 2 });

                //---------------------
                // Constant buffer (VS)
                //---------------------

                var constantBuffer = pipeline.CreateConstantBuffer <Constants>();
                pipeline.SetConstant(ShaderType.Vertex, 0, constantBuffer);

                void SetupProjMatrix()
                {
                    constantBuffer.Value.Projection =
                        device.CreatePerspectiveFieldOfView((float)Math.PI / 4).Transpose();
                }

                device.ResolutionChanged += (sender, e) => SetupProjMatrix();

                constantBuffer.Value.World = Matrix4x4.Identity.Transpose();
                SetupProjMatrix();

                //---------------------
                // Camera
                //---------------------

                var camera = new Camera();

                //---------------------
                // Start main loop
                //---------------------

                form.Show();

                device.RunMultithreadLoop(delegate()
                {
                    // Update matrix

                    constantBuffer.Value.View = camera.GetViewMatrix().Transpose();
                    constantBuffer.Update();

                    // Clear and draw

                    target.ClearAll();
                    indexBuffer.DrawAll(vertexBuffer);

                    device.Present(true);
                });
            }
        }
Exemple #20
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form();

            form.ClientSize = new Size(800, 600);

            using (var device = LightDevice.Create(form))
            {
                var target = new RenderTargetList(device.GetDefaultTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Shader.fx", ShaderType.Vertex | ShaderType.Pixel));
                pipeline.Apply();

                var inputGroup = pipeline.CreateVertexDataProcessors(new[] {
                    typeof(VertexP),
                    typeof(VertexC),
                });
                var input1 = inputGroup.GetVertexDataProcessor <VertexP>();
                var input2 = inputGroup.GetVertexDataProcessor <VertexC>();

                var buffer1       = input1.CreateDynamicBuffer(3);
                var vertexPosData = new[] {
                    new VertexP {
                        Position = new Vector4(0, 0, 0.5f, 1)
                    },
                    new VertexP {
                        Position = new Vector4(0, 0, 0.5f, 1)
                    },
                    new VertexP {
                        Position = new Vector4(0, 0, 0.5f, 1)
                    },
                };
                var buffer2 = input2.CreateImmutableBuffer(new[] {
                    new VertexC {
                        Color = Color.Green.WithAlpha(1)
                    },
                    new VertexC {
                        Color = Color.Red.WithAlpha(1)
                    },
                    new VertexC {
                        Color = Color.Blue.WithAlpha(1)
                    },
                });
                var bufferGroup = new[] { buffer1, buffer2 };

                var indexBuffer = pipeline.CreateImmutableIndexBuffer(new uint[] { 0, 1, 2 });

                var constantBuffer = pipeline.CreateConstantBuffer <ConstantBuffer>();
                pipeline.SetConstant(ShaderType.Vertex, 0, constantBuffer);
                pipeline.SetConstant(ShaderType.Pixel, 0, constantBuffer);

                constantBuffer.Value.GlobalAlpha = new Vector4(1, 1, 1, 1);

                form.Show();

                var i    = 0;
                var rand = new Random();

                var clock = Stopwatch.StartNew();
                device.RunMultithreadLoop(delegate()
                {
                    var angle    = -clock.Elapsed.TotalSeconds * Math.PI / 3;
                    var distance = Math.PI * 2 / 3;

                    SetCoordinate(device, ref vertexPosData[0].Position, angle);
                    SetCoordinate(device, ref vertexPosData[1].Position, angle - distance);
                    SetCoordinate(device, ref vertexPosData[2].Position, angle + distance);
                    buffer1.Update(vertexPosData);

                    constantBuffer.Value.Time = ((float)clock.Elapsed.TotalSeconds % 2) / 2;

                    if (++i == 60)
                    {
                        i = 0;
                        constantBuffer.Value.GlobalAlpha.X = (float)rand.NextDouble() * 0.5f + 0.5f;
                        constantBuffer.Value.GlobalAlpha.Y = (float)rand.NextDouble() * 0.5f + 0.5f;
                        constantBuffer.Value.GlobalAlpha.Z = (float)rand.NextDouble() * 0.5f + 0.5f;
                    }
                    constantBuffer.Update();

                    target.ClearAll();
                    indexBuffer.DrawAll(inputGroup, bufferGroup);

                    device.Present(true);
                });
            }
        }
Exemple #21
0
 static void SetCoordinate(LightDevice device, ref Vector4 position, double angle)
 {
     position.X = 0.5f * (float)Math.Cos(angle) * 600 / device.ScreenWidth;
     position.Y = 0.5f * (float)Math.Sin(angle) * 600 / device.ScreenHeight;
 }
Exemple #22
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form();

            form.ClientSize = new Size(800, 600);

            using (var device = LightDevice.Create(form))
            {
                var target = new RenderTargetList(device.GetDefaultTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Shader.fx", ShaderType.Vertex | ShaderType.Pixel));

                Texture2D texture;
                using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("TextureTriangle.Hiyori.png"))
                {
                    using (var bitmap = new Bitmap(stream))
                    {
                        texture = device.CreateTexture2D(bitmap);
                        pipeline.SetResource(0, texture);
                    }
                }

                pipeline.Apply();

                var input  = pipeline.CreateVertexDataProcessor <Vertex>();
                var buffer = input.CreateImmutableBuffer(new[] {
                    new Vertex {
                        TexCoord = new Vector4(0, 0, 0, 0), Position = new Vector4(-0.5f, 0.5f, 0.5f, 1.0f)
                    },
                    new Vertex {
                        TexCoord = new Vector4(1, 0, 0, 0), Position = new Vector4(0.5f, 0.5f, 0.5f, 1.0f)
                    },
                    new Vertex {
                        TexCoord = new Vector4(0, 1, 0, 0), Position = new Vector4(-0.5f, -0.5f, 0.5f, 1.0f)
                    },

                    new Vertex {
                        TexCoord = new Vector4(0, 1, 0, 0), Position = new Vector4(-0.5f, -0.5f, 0.5f, 1.0f)
                    },
                    new Vertex {
                        TexCoord = new Vector4(1, 0, 0, 0), Position = new Vector4(0.5f, 0.5f, 0.5f, 1.0f)
                    },
                    new Vertex {
                        TexCoord = new Vector4(1, 1, 0, 0), Position = new Vector4(0.5f, -0.5f, 0.5f, 1.0f)
                    },
                });

                form.Show();
                device.RunMultithreadLoop(delegate()
                {
                    target.ClearAll();
                    buffer.DrawAll();
                    device.Present(true);
                });
            }
        }
Exemple #23
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form
            {
                ClientSize = new Size(800, 600),
                Text       = "Tutorial 21: Specular Mapping",
            };

            using (var device = LightDevice.Create(form))
            {
                //---------------------
                // Target & Pipeline
                //---------------------

                var target = new RenderTarget(device.GetDefaultTarget(),
                                              device.CreateDefaultDepthStencilTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("SpecMap_vs.fx", ShaderType.Vertex),
                                                           ShaderSource.FromResource("SpecMap_ps.fx", ShaderType.Pixel));
                pipeline.Apply();

                //---------------------
                // Vertex buffer
                //---------------------

                var          vertexDataProcessor = pipeline.CreateVertexDataProcessor <ModelVertex>();
                VertexBuffer vertexBuffer;
                using (var stream = Assembly.GetEntryAssembly().GetManifestResourceStream("Tutorial21.cube.txt"))
                {
                    vertexBuffer = vertexDataProcessor.CreateImmutableBuffer(Model.ReadModelFile(stream));
                }

                //---------------------
                // Constant buffer (Matrix, VS)
                //---------------------

                var matrixBuffer = pipeline.CreateConstantBuffer <MatrixBuffer>();
                pipeline.SetConstant(ShaderType.Vertex, 0, matrixBuffer);

                void SetupProjMatrix()
                {
                    matrixBuffer.Value.Projection =
                        device.CreatePerspectiveFieldOfView((float)Math.PI / 4).Transpose();
                }

                device.ResolutionChanged += (sender, e) => SetupProjMatrix();

                matrixBuffer.Value.World = Matrix4x4.Identity.Transpose();
                SetupProjMatrix();

                //---------------------
                // Constant buffer (Camera, VS)
                //---------------------

                var cameraBuffer = pipeline.CreateConstantBuffer <CameraBuffer>();
                pipeline.SetConstant(ShaderType.Vertex, 1, cameraBuffer);

                //---------------------
                // Constant buffer (Light, PS)
                //---------------------

                var lightBuffer = pipeline.CreateConstantBuffer <LightBuffer>();
                pipeline.SetConstant(ShaderType.Pixel, 0, lightBuffer);

                lightBuffer.Value.DiffuseColor   = Color.White.WithAlpha(1);
                lightBuffer.Value.LightDirection = Vector3.Normalize(new Vector3(0, 0, 1));
                lightBuffer.Value.SpecularColor  = Color.White.WithAlpha(1);
                lightBuffer.Value.SpecularPower  = 16;
                lightBuffer.Update();

                //---------------------
                // Texture
                //---------------------

                Texture2D CreateTextureFromResource(string name)
                {
                    using (var stream = Assembly.GetEntryAssembly().GetManifestResourceStream($"Tutorial21.{name}.dds"))
                    {
                        return(device.CreateTexture2D(stream));
                    }
                }

                var tex1 = CreateTextureFromResource("stone02");
                var tex2 = CreateTextureFromResource("bump02");
                var tex3 = CreateTextureFromResource("spec02");
                pipeline.SetResource(0, tex1);
                pipeline.SetResource(1, tex2);
                pipeline.SetResource(2, tex3);

                //---------------------
                // Camera
                //---------------------

                var camera = new Camera();

                //---------------------
                // Start main loop
                //---------------------

                form.Show();

                var frameCounter = new FrameCounter();
                frameCounter.Start();

                device.RunMultithreadLoop(delegate()
                {
                    // Update matrix buffer

                    var time         = frameCounter.NextFrame() / 1000;
                    Matrix4x4 rotate = Matrix4x4.CreateRotationX(time * 3) *
                                       Matrix4x4.CreateRotationY(time * 6) *
                                       Matrix4x4.CreateRotationZ(time * 4);

                    matrixBuffer.Value.World *= rotate;
                    matrixBuffer.Value.View   = camera.GetViewMatrix().Transpose();
                    matrixBuffer.Update();

                    // Update camera buffer

                    cameraBuffer.Value.CameraPosition = camera.Position;
                    cameraBuffer.Update();

                    // Clear and draw

                    target.ClearAll();
                    vertexBuffer.DrawAll();

                    device.Present(true);
                });
            }
        }
Exemple #24
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form
            {
                ClientSize = new Size(800, 600),
                Text       = "Tutorial 7: 3D Model Rendering",
            };

            using (var device = LightDevice.Create(form))
            {
                //---------------------
                // Target & Pipeline
                //---------------------

                var target = new RenderTarget(device.GetDefaultTarget(),
                                              device.CreateDefaultDepthStencilTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Light_vs.fx", ShaderType.Vertex),
                                                           ShaderSource.FromResource("Light_ps.fx", ShaderType.Pixel));
                pipeline.Apply();

                //---------------------
                // Vertex buffer
                //---------------------

                var          vertexDataProcessor = pipeline.CreateVertexDataProcessor <ModelVertex>();
                VertexBuffer vertexBuffer;
                using (var stream = Assembly.GetEntryAssembly().GetManifestResourceStream("Tutorial07.Cube.txt"))
                {
                    vertexBuffer = vertexDataProcessor.CreateImmutableBuffer(Model.ReadModelFile(stream));
                }

                //---------------------
                // Constant buffer (VS)
                //---------------------

                var constantBufferVS = pipeline.CreateConstantBuffer <VSConstants>();
                pipeline.SetConstant(ShaderType.Vertex, 0, constantBufferVS);

                void SetupProjMatrix()
                {
                    constantBufferVS.Value.Projection =
                        device.CreatePerspectiveFieldOfView((float)Math.PI / 4).Transpose();
                }

                device.ResolutionChanged += (sender, e) => SetupProjMatrix();

                constantBufferVS.Value.World = Matrix4x4.Identity.Transpose();
                SetupProjMatrix();

                //---------------------
                // Constant buffer (PS)
                //---------------------

                var constantBufferPS = pipeline.CreateConstantBuffer <PSConstants>();
                pipeline.SetConstant(ShaderType.Pixel, 0, constantBufferPS);

                constantBufferPS.Value.Diffuse  = Color.White.WithAlpha(1);
                constantBufferPS.Value.LightDir = Vector3.Normalize(new Vector3(-3f, -4f, 6f));
                constantBufferPS.Update();

                //---------------------
                // Texture
                //---------------------

                Texture2D tex;
                using (var stream = Assembly.GetEntryAssembly().GetManifestResourceStream("Tutorial07.seafloor.dds"))
                {
                    tex = device.CreateTexture2D(stream);
                }
                pipeline.SetResource(0, tex);

                //---------------------
                // Camera
                //---------------------

                var camera = new Camera();

                //---------------------
                // Start main loop
                //---------------------

                form.Show();

                var frameCounter = new FrameCounter();
                frameCounter.Start();

                device.RunMultithreadLoop(delegate()
                {
                    // Update matrix

                    var time         = frameCounter.NextFrame() / 1000;
                    Matrix4x4 rotate = Matrix4x4.CreateRotationX(time * 3) *
                                       Matrix4x4.CreateRotationY(time * 6) *
                                       Matrix4x4.CreateRotationZ(time * 4);

                    constantBufferVS.Value.World *= rotate;
                    constantBufferVS.Value.View   = camera.GetViewMatrix().Transpose();
                    constantBufferVS.Update();

                    // Clear and draw
                    target.ClearAll();
                    vertexBuffer.DrawAll();

                    device.Present(true);
                });
            }
        }