示例#1
0
        public override void Execute(SharedObjects shared)
        {
            int argc = CountRemainingArgs(shared);

            // Handle the var args that might be passed in, or give defaults if fewer args:
            bool   wiping = (argc >= 9) ? Convert.ToBoolean(PopValueAssert(shared)) : true;
            bool   pointy = (argc >= 8) ? Convert.ToBoolean(PopValueAssert(shared)) : true;
            double width  = (argc >= 7) ? GetDouble(PopValueAssert(shared))         : 0.2;
            bool   show   = (argc >= 6) ? Convert.ToBoolean(PopValueAssert(shared)) : false;
            double scale  = (argc >= 5) ? GetDouble(PopValueAssert(shared))         : 1.0;
            string str    = (argc >= 4) ? PopValueAssert(shared).ToString()         : "";

            // Pop the arguments or use the default if omitted
            object argRgba  = (argc >= 3) ? PopValueAssert(shared) : GetDefaultColor();
            object argVec   = (argc >= 2) ? PopValueAssert(shared) : GetDefaultVector();
            object argStart = (argc >= 1) ? PopValueAssert(shared) : GetDefaultStart();

            // Assign the arguments of type delegate or null otherwise
            KOSDelegate colorUpdater = argRgba  as KOSDelegate;
            KOSDelegate vecUpdater   = argVec   as KOSDelegate;
            KOSDelegate startUpdater = argStart as KOSDelegate;

            // Get the values or use the default if its a delegate
            RgbaColor rgba  = (colorUpdater == null) ? GetRgba(argRgba)    : GetDefaultColor();
            Vector    vec   = (vecUpdater == null)   ? GetVector(argVec)   : GetDefaultVector();
            Vector    start = (startUpdater == null) ? GetVector(argStart) : GetDefaultStart();

            AssertArgBottomAndConsume(shared);
            DoExecuteWork(shared, start, vec, rgba, str, scale, show, width, pointy, wiping, colorUpdater, vecUpdater, startUpdater);
        }
示例#2
0
        public void RgbaColorImplementsEquals()
        {
            RgbaColor first  = RgbaColor.FromColor(Color.White);
            RgbaColor second = RgbaColor.FromColor(Color.White);

            first.Equals(second).Should().BeTrue("because the color structure should implement Equals()");
        }
示例#3
0
        public void DoExecuteWork(SharedObjects shared, Vector start, Vector vec, RgbaColor rgba, string str, double scale, bool show, double width, KOSDelegate colorUpdater, KOSDelegate vecUpdater, KOSDelegate startUpdater)
        {
            var vRend = new VectorRenderer(shared.UpdateHandler, shared)
            {
                Vector = vec,
                Start  = start,
                Color  = rgba,
                Scale  = scale,
                Width  = width
            };

            vRend.SetLabel(str);
            vRend.SetShow(show);

            if (colorUpdater != null)
            {
                vRend.SetSuffix("COLORUPDATER", colorUpdater);
            }

            if (vecUpdater != null)
            {
                vRend.SetSuffix("VECUPDATER", vecUpdater);
            }

            if (startUpdater != null)
            {
                vRend.SetSuffix("STARTUPDATER", startUpdater);
            }

            ReturnValue = vRend;
        }
示例#4
0
        public override void Execute(SharedObjects shared)
        {
            int argc = CountRemainingArgs(shared);

            // If I was called with arguments, then run the version of the constructor that takes args
            if (argc == 6)
            {
                bool      show  = Convert.ToBoolean(PopValueAssert(shared));
                double    scale = GetDouble(PopValueAssert(shared));
                string    str   = PopValueAssert(shared).ToString();
                RgbaColor rgba  = GetRgba(PopValueAssert(shared));
                Vector    vec   = GetVector(PopValueAssert(shared));
                Vector    start = GetVector(PopValueAssert(shared));
                AssertArgBottomAndConsume(shared);
                DoExecuteWork(shared, start, vec, rgba, str, scale, show);
            }
            else if (argc == 0)
            {
                AssertArgBottomAndConsume(shared); // no args
                DoExecuteWork(shared);             // default constructor:
            }
            else
            {
                throw new KOSArgumentMismatchException("Vecdraw() expected either 0 or 6 arguments passed, but got " + argc + " instead.");
            }
        }
        public void Add(string content, RgbaColor rgba, Action action)
        {
            if (Document.Blocks.Count <= 0)
            {
                Document.Blocks.Add(new Paragraph());
            }
            Run run = new Run(content);

            if (action == null)
            {
                if (rgba != null)
                {
                    run.Foreground = rgba.SolidColorBrush;
                }
                (Document.Blocks.LastBlock as Paragraph).Inlines.Add(run);
            }
            else
            {
                Hyperlink hl = new Hyperlink(run);
                if (rgba != null)
                {
                    hl.Foreground = rgba.SolidColorBrush;
                }
                hl.Click += delegate { action(); };
                hl.MouseLeftButtonDown += delegate { action(); };
                (Document.Blocks.LastBlock as Paragraph).Inlines.Add(hl);
            }
            ScrollToEnd();
        }
示例#6
0
        public void RgbaColorShouldConvertToAndFromString(string expected)
        {
            Color     color     = ColorTranslator.FromHtml(expected);
            RgbaColor rgbaColor = RgbaColor.FromColor(color);
            string    result    = ColorTranslator.ToHtml(rgbaColor);

            result.Should().Be(expected);
        }
示例#7
0
 /// <summary>
 /// Sets a drop shadow on the label
 /// </summary>
 /// <param name="hasDropShadow">True to enable</param>
 /// <param name="alpha">Alpha of the shadow</param>
 /// <param name="offsetX">x offset of the shadow</param>
 /// <param name="offsetY">y offset of the shadow</param>
 /// <returns></returns>
 public TElementType SetDropShadow(bool hasDropShadow = true, float alpha = 0.7f, int offsetX = 2, int offsetY = 2)
 {
     _hasDropShadow       = hasDropShadow;
     _dropShadowOffsetX   = offsetX;
     _dropShadowOffsetY   = offsetY;
     _dropShadowRgbaColor = new RgbaColor(0, 0, 0, alpha);
     return(AsElementType());
 }
示例#8
0
        public void UpdatePixelView(Point pixelPosition)
        {
            this.UpdateMousePosition(pixelPosition);

            RgbaColor rgbaColor = this.imageController.GetRgbaPixel(pixelPosition);

            this.UpdatePixelColor(pixelPosition, rgbaColor);
        }
示例#9
0
        public override void Execute(SharedObjects shared)
        {
            var b = (float)GetDouble(PopValueAssert(shared));
            var g = (float)GetDouble(PopValueAssert(shared));
            var r = (float)GetDouble(PopValueAssert(shared));

            AssertArgBottomAndConsume(shared);
            ReturnValue = new RgbaColor(r, g, b);
        }
示例#10
0
 public HighlightStructure(UpdateHandler updateHandler, object toHighlight, RgbaColor color)
 {
     this.updateHandler = updateHandler;
     this.toHighlight   = toHighlight;
     this.color         = color;
     DetermineType();
     InitializeSuffixes();
     stale   = true;
     enabled = true;
     updateHandler.AddObserver(this);
 }
示例#11
0
 public HighlightStructure(UpdateHandler updateHandler, object toHighlight, RgbaColor color)
 {
     this.updateHandler = updateHandler;
     this.toHighlight   = toHighlight;
     this.color         = color;
     DetermineType();
     InitializeSuffixes();
     stale   = true;
     enabled = true;
     updateHandler.AddObserver(this);
     GameEvents.onStageSeparation.Add(OnHighlightStaleEvent);
     GameEvents.onVesselPartCountChanged.Add(OnHighlightStaleEvent);
 }
示例#12
0
 private void InitializeSuffixes()
 {
     AddSuffix("COLOR", new SetSuffix <RgbaColor>(() => color, value =>
     {
         color = value;
         stale = true;
     }));
     AddSuffix("ENABLED", new SetSuffix <BooleanValue>(() => enabled, value =>
     {
         enabled = value;
         stale   = true;
     }));
 }
示例#13
0
            public void then_should_return_rgba_version_of_system_drawing_color_given_red()
            {
                // Arrange
                var color = Color.Red;

                // Act
                RgbaColor rgbaColor = color;

                // Assert
                Assert.That(rgbaColor.R, Is.EqualTo(255));
                Assert.That(rgbaColor.G, Is.EqualTo(0));
                Assert.That(rgbaColor.B, Is.EqualTo(0));
                Assert.That(rgbaColor.A, Is.EqualTo(255));
            }
示例#14
0
            public void then_should_return_cmyk_version_of_rgba_color_given_red()
            {
                // Arrange
                var rgbaColor = RgbaColor.FromRgba(0xff, 0x0, 0x0);

                // Act
                var cmyk = (CmykColor)rgbaColor;

                // Assert
                Assert.That(cmyk.C, Is.EqualTo(0));
                Assert.That(cmyk.M, Is.EqualTo(100));
                Assert.That(cmyk.Y, Is.EqualTo(100));
                Assert.That(cmyk.K, Is.EqualTo(0));
            }
示例#15
0
            public void then_should_return_hsla_version_of_rgba_color_given_red()
            {
                // Arrange
                var rgbaColor = RgbaColor.FromRgba(0xff, 0x0, 0x0);

                // Act
                var hslaColor = (HslaColor)rgbaColor;

                // Assert
                Assert.That(hslaColor.H, Is.EqualTo(0));
                Assert.That(hslaColor.S, Is.EqualTo(1.0f));
                Assert.That(hslaColor.L, Is.EqualTo(.5f));
                Assert.That(hslaColor.A, Is.EqualTo(1.0f));
            }
示例#16
0
        public void DoExecuteWork(SharedObjects shared, Vector start, Vector vec, RgbaColor rgba, string str, double scale, bool show)
        {
            var vRend = new VectorRenderer(shared.UpdateHandler, shared)
            {
                Vector = vec,
                Start  = start,
                Color  = rgba,
                Scale  = scale
            };

            vRend.SetLabel(str);
            vRend.SetShow(show);

            ReturnValue = vRend;
        }
示例#17
0
        public override void Execute(SharedObjects shared)
        {
            int argc = CountRemainingArgs(shared);

            // Handle the var args that might be passed in, or give defaults if fewer args:
            double    width = (argc >= 7) ? GetDouble(PopValueAssert(shared))         : 0.2;
            bool      show  = (argc >= 6) ? Convert.ToBoolean(PopValueAssert(shared)) : false;
            double    scale = (argc >= 5) ? GetDouble(PopValueAssert(shared))         : 1.0;
            string    str   = (argc >= 4) ? PopValueAssert(shared).ToString()         : "";
            RgbaColor rgba  = (argc >= 3) ? GetRgba(PopValueAssert(shared))           : new RgbaColor(1.0f, 1.0f, 1.0f);
            Vector    vec   = (argc >= 2) ? GetVector(PopValueAssert(shared))         : new Vector(1.0, 0.0, 0.0);
            Vector    start = (argc >= 1) ? GetVector(PopValueAssert(shared))         : new Vector(0.0, 0.0, 0.0);

            AssertArgBottomAndConsume(shared);
            DoExecuteWork(shared, start, vec, rgba, str, scale, show, width);
        }
示例#18
0
        /// <summary>
        /// Returns the inverted color.
        /// </summary>
        /// <param name="color">The input color.</param>
        /// <returns>An instance of <see cref="IColor"/> representing the output color.</returns>
        public static IColor Invert(this IColor color)
        {
            switch (color)
            {
            case IAlphaColor alpha:

                RgbaColor rgba = alpha as RgbaColor ?? alpha.ToRgba();

                return(new RgbaColor(~rgba.R, ~rgba.G, ~rgba.B, rgba.Alpha));

            default:

                RgbColor rgb = color as RgbColor ?? color.ToRgb();

                return(new RgbColor(~rgb.Red, ~rgb.Green, ~rgb.Blue));
            }
        }
示例#19
0
        private void UpdatePixelColor(Point pixelPosition, RgbaColor rgbaColor)
        {
            if (this.imageController.IsGrayscale)
            {
                this.rgbGrayColorToolStripStatusLabel.Text = FormattableString.Invariant($"Gray: {rgbaColor.R}");
                this.hsvColorToolStripStatusLabel.Text     = string.Empty;
            }
            else
            {
                this.rgbGrayColorToolStripStatusLabel.Text = rgbaColor.ToString();

                HslaColor hslaColor = rgbaColor;

                this.hsvColorToolStripStatusLabel.Text = hslaColor.ToString();
            }

            this.UpdateStatusStripSeparators();
        }
示例#20
0
        public RgbaColor GetRgbaPixel(Point pixelPosition)
        {
            RgbaColor rgbaColor;

            if (this.IsGrayscale)
            {
                byte gray = this.DisplayImageData[pixelPosition.Y, pixelPosition.X, 0];

                rgbaColor = RgbaColor.FromRgba(gray, gray, gray);
            }
            else
            {
                rgbaColor = RgbaColor.FromRgba(
                    this.DisplayImageData[pixelPosition.Y, pixelPosition.X, 0],
                    this.DisplayImageData[pixelPosition.Y, pixelPosition.X, 1],
                    this.DisplayImageData[pixelPosition.Y, pixelPosition.X, 2]);
            }

            return(rgbaColor);
        }
示例#21
0
        public override void Execute(SharedObjects shared)
        {
            bool      echo      = Convert.ToBoolean(PopValueAssert(shared));
            RgbaColor rgba      = GetRgba(PopValueAssert(shared));
            int       size      = Convert.ToInt32(PopValueAssert(shared));
            int       style     = Convert.ToInt32(PopValueAssert(shared));
            int       delay     = Convert.ToInt32(PopValueAssert(shared));
            string    textToHud = PopValueAssert(shared).ToString();

            AssertArgBottomAndConsume(shared);
            string htmlColour = rgba.ToHexNotation();

            switch (style)
            {
            case 1:
                ScreenMessages.PostScreenMessage("<color=" + htmlColour + "><size=" + size + ">" + textToHud + "</size></color>", delay, ScreenMessageStyle.UPPER_LEFT);
                break;

            case 2:
                ScreenMessages.PostScreenMessage("<color=" + htmlColour + "><size=" + size + ">" + textToHud + "</size></color>", delay, ScreenMessageStyle.UPPER_CENTER);
                break;

            case 3:
                ScreenMessages.PostScreenMessage("<color=" + htmlColour + "><size=" + size + ">" + textToHud + "</size></color>", delay, ScreenMessageStyle.UPPER_RIGHT);
                break;

            case 4:
                ScreenMessages.PostScreenMessage("<color=" + htmlColour + "><size=" + size + ">" + textToHud + "</size></color>", delay, ScreenMessageStyle.LOWER_CENTER);
                break;

            default:
                ScreenMessages.PostScreenMessage("*" + textToHud, 3f, ScreenMessageStyle.UPPER_CENTER);
                break;
            }
            if (echo)
            {
                shared.Screen.Print("HUD: " + textToHud);
            }
        }
示例#22
0
文件: Suffixed.cs 项目: jenden0/KOS
        public override void Execute(SharedObjects shared)
        {
            bool      show  = Convert.ToBoolean(shared.Cpu.PopValue());
            double    scale = GetDouble(shared.Cpu.PopValue());
            string    str   = shared.Cpu.PopValue().ToString();
            RgbaColor rgba  = GetRgba(shared.Cpu.PopValue());
            Vector    vec   = GetVector(shared.Cpu.PopValue());
            Vector    start = GetVector(shared.Cpu.PopValue());

            var vRend = new VectorRenderer(shared.UpdateHandler, shared)
            {
                Vector = vec,
                Start  = start,
                Color  = rgba,
                Scale  = scale
            };

            vRend.SetLabel(str);
            vRend.SetShow(show);

            shared.Cpu.PushStack(vRend);
        }
示例#23
0
 /// <summary>
 /// 将使用任意分隔符隔开的4个数字转换成<seealso cref="RgbColor"/>
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static RgbaColor ToRgbaColor(this string s)
 {
     s = RemoveComment(s);
     return(RgbaColor.Parse(s));
 }
示例#24
0
        private void InitializeSuffixes()
        {
            AddSuffix("MARGIN", new Suffix <WidgetStyleRectOffset>(() => new WidgetStyleRectOffset(Writable.margin)));
            AddSuffix("PADDING", new Suffix <WidgetStyleRectOffset>(() => new WidgetStyleRectOffset(Writable.padding)));
            AddSuffix("BORDER", new Suffix <WidgetStyleRectOffset>(() => new WidgetStyleRectOffset(Writable.border)));
            AddSuffix("OVERFLOW", new Suffix <WidgetStyleRectOffset>(() => new WidgetStyleRectOffset(Writable.overflow)));

            AddSuffix("WIDTH", new SetSuffix <ScalarValue>(() => ReadOnly.fixedWidth, value => Writable.fixedWidth    = value));
            AddSuffix("HEIGHT", new SetSuffix <ScalarValue>(() => ReadOnly.fixedHeight, value => Writable.fixedHeight = value));

            AddSuffix("HSTRETCH", new SetSuffix <BooleanValue>(() => ReadOnly.stretchWidth, value => Writable.stretchWidth   = value));
            AddSuffix("VSTRETCH", new SetSuffix <BooleanValue>(() => ReadOnly.stretchHeight, value => Writable.stretchHeight = value));

            AddSuffix("BG", new SetSuffix <StringValue>(() => "", value => Writable.normal.background = Widget.GetTexture(value)));
            AddSuffix("TEXTCOLOR", new SetSuffix <RgbaColor>(() => TextColor, value => TextColor      = value));

            AddSuffix("NORMAL", new Suffix <WidgetStyleState>(() => new WidgetStyleState(Writable.normal)));
            AddSuffix("FOCUSED", new Suffix <WidgetStyleState>(() => new WidgetStyleState(Writable.focused)));
            AddSuffix("ACTIVE", new Suffix <WidgetStyleState>(() => new WidgetStyleState(Writable.active)));
            AddSuffix("HOVER", new Suffix <WidgetStyleState>(() => new WidgetStyleState(Writable.hover)));
            AddSuffix(new[] { "ON", "NORMAL_ON" }, new Suffix <WidgetStyleState>(() => new WidgetStyleState(Writable.onNormal)));
            AddSuffix("FOCUSED_ON", new Suffix <WidgetStyleState>(() => new WidgetStyleState(Writable.onFocused)));
            AddSuffix("ACTIVE_ON", new Suffix <WidgetStyleState>(() => new WidgetStyleState(Writable.onActive)));
            AddSuffix("HOVER_ON", new Suffix <WidgetStyleState>(() => new WidgetStyleState(Writable.onHover)));

            AddSuffix("FONT", new SetSuffix <StringValue>(GetFont, SetFont));
            AddSuffix("FONTSIZE", new SetSuffix <ScalarIntValue>(() => ReadOnly.fontSize, value => Writable.fontSize = value));
            AddSuffix("RICHTEXT", new SetSuffix <BooleanValue>(() => ReadOnly.richText, value => Writable.richText   = value));
            AddSuffix("ALIGN", new SetSuffix <StringValue>(GetAlignment, SetAlignment));

            AddSuffix("WORDWRAP", new SetSuffix <BooleanValue>(() => ReadOnly.wordWrap, value => Writable.wordWrap = value));
        }
示例#25
0
        public static void AddLine(this FlowDocument Document, string content = null, RgbaColor rgba = null, Action action = null)
        {
            Run run = new Run(content);

            if (action == null)
            {
                if (rgba != null)
                {
                    run.Foreground = rgba.SolidColorBrush;
                }
                Document.Blocks.Add(new Paragraph(run));
            }
            else
            {
                Hyperlink hl = new Hyperlink(run);
                if (rgba != null)
                {
                    hl.Foreground = rgba.SolidColorBrush;
                }
                hl.Click += delegate { action(); };
                hl.MouseLeftButtonDown += delegate { action(); };
                Document.Blocks.Add(new Paragraph(hl));
            }
        }
        internal unsafe void Launch()
        {
            Console.WriteLine("Tessellation...");
            Console.WriteLine("    Left click to add a point.");
            Console.WriteLine("    'c' to close the current polyline and start a new one.");
            Console.WriteLine("    's' stroke the polyline.");
            Console.WriteLine("    't' to tessellate the polygon.");
            Console.WriteLine("    'r' reset the polygon.");

            using var windowServer     = new WindowServer();
            using var renderingContext = new RenderingContext { Settings = new RenderingSettings { Samples = 8 } };

            using var window               = windowServer.CreateWindow(renderingContext);
            window.Title                   = "Tessellation";
            window.BorderStyle             = WindowBorderStyle.Sizable;
            window.Size                    = (800, 800);
            renderingContext.CurrentWindow = window;

            var viewportSize = window.ViewportSize;
            var windowSize   = window.Size;

            var backend = new DrawingBackend(new EntryPointLoader(renderingContext))
            {
                PixelScaling = viewportSize.height / windowSize.height
            };

            var dataLock = new object();
            var vertices = new List <(double x, double y)>();
            List <List <(double x, double y)> >?polygon = new List <List <(double x, double y)> >();
            var contour = default(List <(double x, double y)>);
            var colors  = new RgbaColor[]
            {
                new RgbaColor(255, 255, 255, 255),
                new RgbaColor(110, 100, 70, 200),
                new RgbaColor(130, 30, 50, 200),
                new RgbaColor(150, 90, 80, 200),
                new RgbaColor(170, 40, 40, 200),
                new RgbaColor(190, 80, 90, 200),
                new RgbaColor(210, 50, 30, 200),
                new RgbaColor(230, 70, 100, 200),
            };

            var buffer            = new PointCoordinates[6];
            var vertexBuffer      = backend.CreateVertexBuffer(VertexType.PointCoordinates, 6);
            var colorBufferHandle = backend.CreateUniformBuffer(UniformType.RgbaColor, colors.Length);

            var transformBufferHandle = backend.CreateUniformBuffer(UniformType.AffineTransform, 1);

            var commandBufferInit = backend.CreateCommandBuffer();

            backend.BeginRecordCommands(commandBufferInit);
            backend.AddClearCommand(commandBufferInit, new RgbaColor(55, 55, 55, 255));
            backend.AddUseShaderCommand(commandBufferInit, ShaderKind.PlainColor);
            backend.AddBindUniformCommand(commandBufferInit, Uniform.Color, colorBufferHandle, 0);
            backend.AddBindUniformCommand(commandBufferInit, Uniform.Transform, transformBufferHandle, 0);
            backend.AddBindVertexBufferCommand(commandBufferInit, vertexBuffer);
            backend.EndRecordCommands(commandBufferInit);

            var bindColorCommandBuffers = new CommandBufferHandle[colors.Length];

            for (int i = 1; i < colors.Length; i++)
            {
                bindColorCommandBuffers[i - 1] = backend.CreateCommandBuffer();
                backend.BeginRecordCommands(bindColorCommandBuffers[i - 1]);
                backend.AddBindUniformCommand(bindColorCommandBuffers[i - 1], Uniform.Color, colorBufferHandle, i);
                backend.EndRecordCommands(bindColorCommandBuffers[i - 1]);
            }

            var commandBufferDrawTriangle = backend.CreateCommandBuffer();

            backend.BeginRecordCommands(commandBufferDrawTriangle);
            backend.AddDrawCommand(commandBufferDrawTriangle, DrawingPrimitive.Triangles, 0, 3);
            backend.EndRecordCommands(commandBufferDrawTriangle);

            var commandBufferDrawTriangles = backend.CreateCommandBuffer();

            backend.BeginRecordCommands(commandBufferDrawTriangles);
            backend.AddDrawCommand(commandBufferDrawTriangles, DrawingPrimitive.Triangles, 0, 6);
            backend.EndRecordCommands(commandBufferDrawTriangles);

            var drawLineStripArgsBufferHandle = backend.CreateVertexRangeBuffer(1);
            var drawLineStripCommandBuffer    = backend.CreateCommandBuffer();

            backend.BeginRecordCommands(drawLineStripCommandBuffer);
            backend.AddDrawIndirectCommand(drawLineStripCommandBuffer, DrawingPrimitive.LineStrip, drawLineStripArgsBufferHandle, 0);
            backend.EndRecordCommands(drawLineStripCommandBuffer);


            var vertexRanges         = new VertexRange[1];
            var commandBufferHandles = new CommandBufferHandle[2];
            var transforms           = new AffineTransform[1];

            transforms[0] = new AffineTransform(m11: 1, m22: 1);

            var drawLock           = new object();
            var interruptRendering = false;
            var requireRendering   = true;

            void draw()
            {
                while (!interruptRendering)
                {
                    if (requireRendering)
                    {
                        requireRendering = false;
                        renderingContext.CurrentWindow = window;
                        backend.PixelScaling           = viewportSize.height / windowSize.height;
                        backend.WindowSize             = windowSize;
                        backend.UpdateUniformBuffer(colorBufferHandle, colors, 0, colors.Length);

                        backend.BeginRenderFrame();
                        backend.UpdateUniformBuffer(transformBufferHandle, transforms, 0, 1);
                        commandBufferHandles[0] = commandBufferInit;
                        backend.SubmitCommands(commandBufferHandles, 0, 1);

                        lock (dataLock)
                        {
                            if (polygon != null)
                            {
                                for (int j = 0; j < polygon.Count; j++)
                                {
                                    var c = polygon[j];
                                    if (c.Count == 1)
                                    {
                                        commandBufferHandles[0] = commandBufferDrawTriangles;

                                        var(x, y) = c[0];
                                        var x0 = x - 2;
                                        var y0 = y - 2;
                                        var x1 = x + 2;
                                        var y1 = y - 2;
                                        var x2 = x + 2;
                                        var y2 = y + 2;
                                        var x3 = x - 2;
                                        var y3 = y + 2;

                                        buffer[0] = new PointCoordinates(x0, y0);
                                        buffer[1] = new PointCoordinates(x1, y1);
                                        buffer[2] = new PointCoordinates(x2, y2);
                                        buffer[3] = new PointCoordinates(x2, y2);
                                        buffer[4] = new PointCoordinates(x3, y3);
                                        buffer[5] = new PointCoordinates(x0, y0);

                                        backend.UpdateVertexBuffer(vertexBuffer, buffer, 0, 6);
                                        backend.SubmitCommands(commandBufferHandles, 0, 1);
                                    }
                                    else
                                    {
                                        commandBufferHandles[0] = drawLineStripCommandBuffer;
                                        vertexRanges[0]         = new VertexRange(0, 6);
                                        backend.UpdateVertexRangeBuffer(drawLineStripArgsBufferHandle, vertexRanges, 0, 1);
                                        var n = 0;
                                        for (int i = 0; i < c.Count; i++)
                                        {
                                            var(x, y) = c[i];
                                            buffer[n] = new PointCoordinates(x, y);

                                            if (++n == 6)
                                            {
                                                backend.UpdateVertexBuffer(vertexBuffer, buffer, 0, 6);
                                                backend.SubmitCommands(commandBufferHandles, 0, 1);
                                                buffer[0] = new PointCoordinates(x, y);
                                                n         = 1;
                                            }
                                        }
                                        if (j < polygon.Count - 1 || contour == null)
                                        {
                                            var(x, y) = c[0];
                                            buffer[n] = new PointCoordinates(x, y);
                                            ++n;
                                        }
                                        if (n > 1)
                                        {
                                            backend.UpdateVertexBuffer(vertexBuffer, buffer, 0, n);
                                            vertexRanges[0] = new VertexRange(0, n);
                                            backend.UpdateVertexRangeBuffer(drawLineStripArgsBufferHandle, vertexRanges, 0, 1);
                                            backend.SubmitCommands(commandBufferHandles, 0, 1);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                commandBufferHandles[1] = commandBufferDrawTriangle;
                                for (int i = 0; i < vertices.Count - 2; i += 3)
                                {
                                    commandBufferHandles[0] = bindColorCommandBuffers[((i / 3) % (colors.Length - 1))];
                                    var(x, y) = vertices[i];
                                    buffer[0] = new PointCoordinates(x, y);
                                    (x, y)    = vertices[i + 1];
                                    buffer[1] = new PointCoordinates(x, y);
                                    (x, y)    = vertices[i + 2];
                                    buffer[2] = new PointCoordinates(x, y);

                                    backend.UpdateVertexBuffer(vertexBuffer, buffer, 0, 3);
                                    backend.SubmitCommands(commandBufferHandles, 0, 2);
                                }
                            }
                        }

                        backend.EndRenderFrame();
                        renderingContext.SwapBuffers(window);
                        renderingContext.CurrentWindow = null;
                    }

                    lock (drawLock)
                    {
                        Monitor.Wait(drawLock, 50);
                    }
                }
            }

            window.TextInput += (sender, e) =>
            {
                switch (e.CodePoint)
                {
                case 'c':
                    lock (dataLock)
                    {
                        if (contour != null && contour.Count > 2)
                        {
                            contour.Add(contour[0]);
                        }
                        contour = null;
                    }
                    requireRendering = true;
                    break;

                case 'r':
                    lock (dataLock)
                    {
                        polygon = new List <List <(double x, double y)> >();
                        contour = null;
                        vertices.Clear();
                    }
                    requireRendering = true;
                    break;

                case 's':
                {
                    var p = new List <List <(double x, double y)> >();
                    var polylineStroker = new PolylineStroker(new StrokeHandler(p))
                    {
                        StrokeWidth    = 20,
                        StrokeLinecap  = StrokeLinecap.Round,
                        StrokeLineJoin = StrokeLineJoin.Round
                    };
                    foreach (var c in polygon)
                    {
                        polylineStroker.Stroke(c);
                    }
                    contour = null;
                    polygon = p;
                }
                    requireRendering = true;
                    break;

                case 't':
                    if (vertices.Count == 0)
                    {
                        lock (dataLock)
                        {
                            var tessellator = new Tessellator2D <int, int>(new TessellateHandler(vertices))
                            {
                                OutputKind  = OutputKind.TrianglesOnly,
                                WindingRule = WindingRule.NonZero
                            };

                            tessellator.BeginPolygon(0);
                            foreach (var c in polygon)
                            {
                                tessellator.BeginContour();
                                foreach (var(x, y) in c)
                                {
                                    tessellator.AddVertex(x, y, 0);
                                }
                                tessellator.EndContour();
                            }
                            tessellator.EndPolygon();
                            vertices.Clear();

                            tessellator.OutputKind = OutputKind.TriangleEnumerator;

                            tessellator.BeginPolygon(0);
                            foreach (var c in polygon)
                            {
                                tessellator.BeginContour();
                                foreach (var(x, y) in c)
                                {
                                    tessellator.AddVertex(x, y, 0);
                                }
                                tessellator.EndContour();
                            }
                            var sw = new System.Diagnostics.Stopwatch();
                            var f  = System.Diagnostics.Stopwatch.Frequency;
                            sw.Start();
                            tessellator.EndPolygon();

                            while (tessellator.Move())
                            {
                                var(x, y, _) = tessellator.Vertex;
                                vertices.Add((x, y));
                            }

                            sw.Stop();
                            Console.WriteLine("Tessellated " + (vertices.Count / 3) + " triangles in " +
                                              (sw.ElapsedTicks * 1e3 / f).ToString("0.000") + "ms");
                            polygon = null;
                        }
                    }
                    requireRendering = true;
                    break;
                }
            };

            window.MouseDown += (sender, e) =>
            {
                lock (dataLock)
                {
                    if (e.ChangedButton == MouseButton.Left && polygon != null)
                    {
                        if (contour == null)
                        {
                            contour = new List <(double x, double y)>();
                            polygon.Add(contour);
                        }
                        else if (window.CursorPosition.x == contour[contour.Count - 1].x &&
                                 window.CursorPosition.y == contour[contour.Count - 1].y)
                        {
                            return;
                        }
                        contour.Add(window.CursorPosition);
                        requireRendering = true;
                    }
                }
            };

            void resize()
            {
                viewportSize     = window.ViewportSize;
                windowSize       = window.Size;
                requireRendering = true;
                lock (drawLock)
                {
                    Monitor.Pulse(drawLock);
                }
            }

            var runLoop = MainRunLoop.Create(windowServer);

            var drawThread = new Thread(draw);

            window.Closed += (sender, e) =>
            {
                interruptRendering = true;
                drawThread.Join();
                runLoop.Interrupt();
                backend.Dispose();
            };
            window.Resize            += (sender, e) => resize();
            window.FramebufferResize += (sender, e) => resize();

            renderingContext.CurrentWindow = null;
            drawThread.Start();
            window.Visible = true;
            runLoop.Run();

            Console.WriteLine("Tessellation done.");
        }
示例#27
0
 public void Add(string content, RgbaColor rgba)
 {
     Add(content, rgba, null);
 }
 internal MonospaceStyleKey(FontSubfamily fontSubfamily, RgbaColor foreground, RgbaColor background)
 {
     this.fontSubfamily = fontSubfamily;
     this.foreground    = foreground;
     this.background    = background;
 }
示例#29
0
        internal unsafe void Launch()
        {
            Console.WriteLine("Glyph...");
            Console.WriteLine("    type any key to display the corresponding glyph.");
            Console.WriteLine("The top glyph is rasterized before being rendered as an image.");
            Console.WriteLine("The bottom glyph is tessellated and rendered as a set of triangles.");

            using var windowServer     = new WindowServer();
            using var renderingContext = new RenderingContext { Settings = new RenderingSettings { Samples = 8 } };
            using var window           = windowServer.CreateWindow(renderingContext);

            window.BorderStyle             = WindowBorderStyle.Sizable;
            window.Size                    = (500, 700);
            renderingContext.CurrentWindow = window;

            var viewportSize = window.ViewportSize;
            var windowSize   = window.Size;
            var vertices     = new List <(double x, double y)>();

            using var backend = new DrawingBackend(new EntryPointLoader(renderingContext))
                  {
                      PixelScaling = viewportSize.height / windowSize.height
                  };

            var colors = new RgbaColor[]
            {
                new RgbaColor(255, 255, 255, 255),
                new RgbaColor(110, 100, 70, 200),
                new RgbaColor(130, 30, 50, 200),
                new RgbaColor(150, 90, 80, 200),
                new RgbaColor(170, 40, 40, 200),
                new RgbaColor(190, 80, 90, 200),
                new RgbaColor(210, 50, 30, 200),
                new RgbaColor(230, 70, 100, 200),
            };

            var bufferTexture       = new PointAndImageCoordinates[6];
            var vertexBufferTexture = backend.CreateVertexBuffer(VertexType.PointAndImageCoordinates, 6);
            var buffer            = new PointCoordinates[3];
            var vertexBuffer      = backend.CreateVertexBuffer(VertexType.PointCoordinates, 3);
            var colorBufferHandle = backend.CreateUniformBuffer(UniformType.RgbaColor, colors.Length);

            backend.UpdateUniformBuffer(colorBufferHandle, colors, 0, colors.Length);

            const int GlyphSize = 300;

            var transformBufferHandle = backend.CreateUniformBuffer(UniformType.AffineTransform, 1);
            var imageHandle           = backend.CreateImage(GlyphSize, GlyphSize, ImageFormat.GreyscaleAlpha, ImageComponentType.UnsignedByte);

            var commandBufferInit = backend.CreateCommandBuffer();

            backend.BeginRecordCommands(commandBufferInit);
            backend.AddClearCommand(commandBufferInit, new RgbaColor(55, 55, 55, 255));
            backend.EndRecordCommands(commandBufferInit);

            var displayImageCommandBuffer = backend.CreateCommandBuffer();

            backend.BeginRecordCommands(displayImageCommandBuffer);
            backend.AddBindImageCommand(displayImageCommandBuffer, imageHandle);
            backend.AddUseShaderCommand(displayImageCommandBuffer, ShaderKind.GreyscaleImage);
            backend.AddBindUniformCommand(displayImageCommandBuffer, Uniform.Transform, transformBufferHandle, 0);
            backend.AddBindUniformCommand(displayImageCommandBuffer, Uniform.Color, colorBufferHandle, 0);
            backend.AddBindVertexBufferCommand(displayImageCommandBuffer, vertexBufferTexture);
            backend.AddDrawCommand(displayImageCommandBuffer, DrawingPrimitive.Triangles, 0, 6);
            backend.EndRecordCommands(displayImageCommandBuffer);

            var commandBufferInitDrawTriangle = backend.CreateCommandBuffer();

            backend.BeginRecordCommands(commandBufferInitDrawTriangle);
            backend.AddUseShaderCommand(commandBufferInitDrawTriangle, ShaderKind.PlainColor);
            backend.AddBindUniformCommand(commandBufferInitDrawTriangle, Uniform.Transform, transformBufferHandle, 0);
            backend.EndRecordCommands(commandBufferInitDrawTriangle);

            var bindColorCommandBuffers = new CommandBufferHandle[colors.Length];

            for (int i = 1; i < colors.Length; i++)
            {
                bindColorCommandBuffers[i - 1] = backend.CreateCommandBuffer();
                backend.BeginRecordCommands(bindColorCommandBuffers[i - 1]);
                backend.AddBindUniformCommand(bindColorCommandBuffers[i - 1], Uniform.Color, colorBufferHandle, i);
                backend.EndRecordCommands(bindColorCommandBuffers[i - 1]);
            }

            var commandBufferDrawTriangle = backend.CreateCommandBuffer();

            backend.BeginRecordCommands(commandBufferDrawTriangle);
            backend.AddBindVertexBufferCommand(commandBufferDrawTriangle, vertexBuffer);
            backend.AddDrawCommand(commandBufferDrawTriangle, DrawingPrimitive.Triangles, 0, 3);
            backend.EndRecordCommands(commandBufferDrawTriangle);

            var commandBufferHandles = new CommandBufferHandle[2];
            var transforms           = new AffineTransform[1];

            transforms[0] = new AffineTransform(m11: 1, m22: 1);

            var  bitmap         = new byte[GlyphSize * (GlyphSize + 5)];
            bool glyphAvailable = false;

            void draw()
            {
                renderingContext.CurrentWindow = window;

                backend.BeginRenderFrame();
                backend.UpdateUniformBuffer(transformBufferHandle, transforms, 0, 1);
                commandBufferHandles[0] = commandBufferInit;
                backend.SubmitCommands(commandBufferHandles, 0, 1);

                if (glyphAvailable)
                {
                    commandBufferHandles[0] = displayImageCommandBuffer;
                    backend.UpdateImage(imageHandle, bitmap, 0, 0, GlyphSize, GlyphSize);
                    bufferTexture[0] = new PointAndImageCoordinates(0, 0, 0, 0);
                    bufferTexture[1] = new PointAndImageCoordinates(0, 300, 0, 1);
                    bufferTexture[2] = new PointAndImageCoordinates(300, 300, 1, 1);
                    bufferTexture[3] = new PointAndImageCoordinates(0, 0, 0, 0);
                    bufferTexture[4] = new PointAndImageCoordinates(300, 300, 1, 1);
                    bufferTexture[5] = new PointAndImageCoordinates(300, 0, 1, 0);
                    backend.UpdateVertexBuffer(vertexBufferTexture, bufferTexture, 0, 6);
                    backend.SubmitCommands(commandBufferHandles, 0, 1);

                    commandBufferHandles[0] = commandBufferInitDrawTriangle;
                    backend.SubmitCommands(commandBufferHandles, 0, 1);

                    commandBufferHandles[1] = commandBufferDrawTriangle;
                    for (int i = 0; i < vertices.Count - 2; i += 3)
                    {
                        commandBufferHandles[0] = bindColorCommandBuffers[((i / 3) % (colors.Length - 1))];
                        var(x, y) = vertices[i];
                        buffer[0] = new PointCoordinates(x, y);
                        (x, y)    = vertices[i + 1];
                        buffer[1] = new PointCoordinates(x, y);
                        (x, y)    = vertices[i + 2];
                        buffer[2] = new PointCoordinates(x, y);

                        backend.UpdateVertexBuffer(vertexBuffer, buffer, 0, 3);
                        backend.SubmitCommands(commandBufferHandles, 0, 2);
                    }
                }

                backend.EndRenderFrame();

                renderingContext.SwapBuffers(window);
            }

            OpenType openType;
            var      namePrefix = typeof(GlyphLauncher).Namespace + ".Resources.";

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(namePrefix + "ebrima.ttf"))
            {
                openType = OpenType.Load(stream ?? throw new InvalidOperationException())[0];
示例#30
0
 internal void SetColor(GraphicsLibrary gl, RgbaColor color) =>
 program.Uniform4f(gl, ColorLocation, color.Red / 255f, color.Green / 255f, color.Blue / 255f, color.Alpha / 255f);