Exemple #1
0
        public ArtworkPopup()
            : base(Gtk.WindowType.Popup)
        {
            VBox vbox = new VBox();
            Add(vbox);

            Decorated = false;
            BorderWidth = 6;

            SetPosition(WindowPosition.CenterAlways);

            image = new Gtk.Image();
            label = new Label(String.Empty);
            label.CanFocus = false;
            label.Wrap = true;

            var bg_color = new RGBA ();
            bg_color.Red = bg_color.Green = bg_color.Blue = 0;
            var fg_color = new RGBA ();
            fg_color.Red = bg_color.Green = bg_color.Blue =  160.0 / 255;
            label.OverrideBackgroundColor (StateFlags.Normal, bg_color);
            label.OverrideColor (StateFlags.Normal, fg_color);
            OverrideBackgroundColor (StateFlags.Normal, bg_color);
            OverrideColor (StateFlags.Normal, fg_color);

            vbox.PackStart(image, true, true, 0);
            vbox.PackStart(label, false, false, 0);

            vbox.Spacing = 6;
            vbox.ShowAll();
        }
Exemple #2
0
 public void Text(RGBA color, Utilities.Point topleft, string text, float fontsize = 16, string fontname = "Arial")
 {
     Graphics.DrawString(text, GetCachedFont(fontname, fontsize), GetCachedSolidBrush(color), topleft.X, topleft.Y);
 }
Exemple #3
0
 private void Update(EvaluationContext context)
 {
     Output.Value = RGBA.GetValue(context);
 }
Exemple #4
0
 private void WriteRGBA(BinaryWriter Writer, RGBA Color)
 {
     Writer.Write(Color.ToVector4());
 }
Exemple #5
0
        public static void Write
        (
            Color[] pixels,
            int width,
            int height,
            int bitDepth,
            bool alpha,
            bool greyscale,
            string filePath
        )
        {
            var info = new ImageInfo(
                width,
                height,
                bitDepth,
                alpha,
                greyscale,
                false//not implemented here yet//bitDepth==4
                );

            // open image for writing:
            PngWriter writer = FileHelper.CreatePngWriter(filePath, info, true);
            // add some optional metadata (chunks)
            var meta = writer.GetMetadata();

            int       numRows   = info.Rows;
            int       numCols   = info.Cols;
            ImageLine imageline = new ImageLine(info);

            for (int row = 0; row < numRows; row++)
            {
                //fill line:
                if (greyscale == false)
                {
                    if (alpha)
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            RGBA rgba = ToRGBA(pixels[IndexPngToTexture(row, col, numRows, numCols)], bitDepth);
                            ImageLineHelper.SetPixel(imageline, col, rgba.r, rgba.g, rgba.b, rgba.a);
                        }
                    }
                    else
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            RGB rgb = ToRGB(pixels[IndexPngToTexture(row, col, numRows, numCols)], bitDepth);
                            ImageLineHelper.SetPixel(imageline, col, rgb.r, rgb.g, rgb.b);
                        }
                    }
                }
                else
                {
                    if (alpha == false)
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            int r = ToInt(pixels[IndexPngToTexture(row, col, numRows, numCols)].r, bitDepth);
                            ImageLineHelper.SetPixel(imageline, col, r);
                        }
                    }
                    else
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            int a = ToInt(pixels[IndexPngToTexture(row, col, numRows, numCols)].a, bitDepth);
                            ImageLineHelper.SetPixel(imageline, col, a);
                        }
                    }
                }

                //write line:
                writer.WriteRow(imageline, row);
            }
            writer.End();
        }
 public static string Color(this string str, RGBA color) => $"<color=#{color:X}>{str}</color>";
Exemple #7
0
 /// <summary>
 /// Initializes the channel equalization filter.
 /// </summary>
 /// <param name="channel">Channel of RGBA model</param>
 public EqualizeChannel(RGBA channel)
 {
     Channel = channel;
 }
Exemple #8
0
	public HashCode GenerateHashCodeForEnhance( RGBA rgba, Long zoom, HashCode parent ){
		
		
	}
        public static void Write
        (
            Color[] pixels,
            int width,
            int height,
            int bitDepth,
            bool alpha,
            bool greyscale,
            string filePath
        )
        {
            var imageInfo = new ImageInfo(
                width,
                height,
                bitDepth,
                alpha,
                greyscale,
                false                //not implemented here yet//bitDepth==4
                );

            // open image for writing:
            PngWriter writer = FileHelper.CreatePngWriter(filePath, imageInfo, true);

            // add some optional metadata (chunks)
            var meta = writer.GetMetadata();

            meta.SetTimeNow(0);              // 0 seconds fron now = now

            int numRows  = imageInfo.Rows;
            int numCols  = imageInfo.Cols;
            int channels = imageInfo.Channels;

            for (int row = 0; row < numRows; row++)
            {
                int[] ints = new int[imageInfo.SamplesPerRow];

                //fill line:
                if (greyscale == false)
                {
                    if (alpha)
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            RGBA <int> rgba = ToRGBA(pixels[IndexPngToTexture(row, col, numRows, numCols)], bitDepth);
                            ImageLineHelper.SetPixel(ints, rgba, col, channels);
                        }
                    }
                    else
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            RGB <int> rgb = ToRGB(pixels[IndexPngToTexture(row, col, numRows, numCols)], bitDepth);
                            ImageLineHelper.SetPixel(ints, rgb, col, channels);
                        }
                    }
                }
                else
                {
                    if (alpha == false)
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            int R = ToInt(pixels[IndexPngToTexture(row, col, numRows, numCols)].r, bitDepth);
                            ImageLineHelper.SetPixel(ints, R, col, channels);
                        }
                    }
                    else
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            int A = ToInt(pixels[IndexPngToTexture(row, col, numRows, numCols)].a, bitDepth);
                            ImageLineHelper.SetPixel(ints, A, col, channels);
                        }
                    }
                }

                //write line:
                ImageLine imageline = new ImageLine(imageInfo, ImageLine.ESampleType.INT, false, ints, null, row);
                writer.WriteRow(imageline, row);
            }
            writer.End();
        }
Exemple #10
0
 public extern static void gtk_color_chooser_get_rgba(IntPtr chooser, out RGBA color);
Exemple #11
0
 /// <summary>
 /// Initializes the channel hide filter.
 /// </summary>
 /// <param name="channel">Channel of RGBA model</param>
 public HideChannel(RGBA channel)
 {
     Channel = channel;
 }
Exemple #12
0
 public static string ToHtmlString(this RGBA color)
 {
     return($"{color:X}");
 }
Exemple #13
0
 public HashCode GenerateHashCodeForEnhance(RGBA rgba, Long zoom, HashCode parent)
 {
 }
Exemple #14
0
 public void Text(RGBA color, float x, float y, string text, float fontsize = 16)
 {
 }
Exemple #15
0
        /// <summary>
        /// Reads the windowstyle from a filestream.
        /// </summary>
        /// <param name="binread">The System.IO.BinaryReader to use.</param>
        public void Open(BinaryReader binread)
        {
            _sig = new string(binread.ReadChars(4));
            _version = binread.ReadInt16();
            _edgeWidth = binread.ReadByte();
            _backgroundMode = binread.ReadByte();
            for (int i = 0; i < _edgeColors.Length; ++i)
            {
                _edgeColors[i] = new RGBA();
                _edgeColors[i].ReadData(binread);
            }
            for (int i = 0; i < _edgeOffset.Length; ++i) _edgeOffset[1] = binread.ReadByte();
            binread.ReadBytes(36); // reserved

            switch (_version)
            {
                case 2:
                    for (int i = 0; i < _images.Length; ++i)
                    {
                        short width = binread.ReadInt16();
                        short height = binread.ReadInt16();
                        BitmapLoader loader = new BitmapLoader(width, height);
                        _images[i] = loader.LoadFromStream(binread, width * height * 4);
                        loader.Close();
                    }
                    break;
            }
        }
        /// <summary>
        /// Construct a new DefineBitsLossLess2Tag object
        /// from an image object.
        /// </summary>
        /// <param name="characterId">Character id.</param>
        /// <param name="image">Image.</param>
        /// <returns></returns>
        public static DefineBitsLossLess2Tag FromImage(ushort characterId, Image image)
        {
            if (image.RawFormat.Equals(ImageFormat.Bmp) == false &&
                image.RawFormat.Equals(ImageFormat.MemoryBmp) == false)
            {
                throw new InvalidImageFormatException();
            }

            Bitmap bitmap = (Bitmap)image;

            byte        format   = 0;
            PixelFormat pxFormat = image.PixelFormat;

            if (pxFormat == PixelFormat.Format8bppIndexed)
            {
                format = 3;
            }
            else if (pxFormat == PixelFormat.Format16bppRgb555 ||
                     pxFormat == PixelFormat.Format16bppRgb565)
            {
                format = 4;
            }
            else if (pxFormat == PixelFormat.Format24bppRgb)
            {
                format = 5;
            }
            else
            {
                throw new InvalidPixelFormatException();
            }

            DefineBitsLossLess2Tag bmp = new DefineBitsLossLess2Tag();

            bmp.CharacterId  = characterId;
            bmp.BitmapFormat = format;
            bmp.BitmapWidth  = (ushort)image.Width;
            bmp.BitmapHeight = (ushort)image.Height;

            int imageSize = bitmap.Width * bitmap.Height;

            if (bmp.BitmapFormat == 3)
            {
                //TODO
            }
            else if (bmp.BitmapFormat == 4 ||
                     bmp.BitmapFormat == 5)
            {
                RGBA[] bitmapPixelData = new RGBA[imageSize];
                int    k = 0;
                for (int i = 0; i < bitmap.Height; i++)
                {
                    for (int j = 0; j < bitmap.Width; j++)
                    {
                        Color color = bitmap.GetPixel(j, i);
                        bitmapPixelData[k] = new RGBA((byte)color.R, (byte)color.G, (byte)color.B, (byte)color.A);
                        k++;
                    }
                }
                bmp.AlphaBitmapData = new AlphaBitmapData(bitmapPixelData);
            }

            return(bmp);
        }
        static void ProcessNByteRow(ImageLine imageLine, Color[] pixels)
        {
            int       row      = imageLine.ImageRow;
            ImageInfo imgInfo  = imageLine.ImgInfo;
            int       numRows  = imgInfo.Rows;
            int       numCols  = imgInfo.Cols;
            int       bitDepth = imgInfo.BitDepth;
            int       channels = imgInfo.Channels;
            float     max      = GetBitDepthMaxValue(bitDepth);
            var       scanline = imageLine.Scanline;

            for (int col = 0; col < numCols; col++)
            {
                int        i = col * channels;
                RGBA <int> rgba;
                if (channels == 4)
                {
                    rgba = new RGBA <int> {
                        R = scanline[i],
                        G = scanline[i + 1],
                        B = scanline[i + 2],
                        A = scanline[i + 3]
                    };
                }
                else if (channels == 3)
                {
                    rgba = new RGBA <int> {
                        R = scanline[i],
                        G = scanline[i + 1],
                        B = scanline[i + 2],
                        A = int.MaxValue
                    };
                }
                else if (channels == 2)
                {
                    int val = scanline[i + 1];
                    int a   = scanline[i];
                    rgba = new RGBA <int> {
                        R = val, G = val, B = val,
                        A = a
                    };
                }
                else if (channels == 1)
                {
                    int val = scanline[i];
                    rgba = new RGBA <int> {
                        R = val, G = val, B = val, A = val
                    };
                }
                else
                {
                    Debug.LogError($"{channels} channels not implemented");
                    return;
                }

                Color color = new Color {
                    r = (float)rgba.R / max,
                    g = (float)rgba.G / max,
                    b = (float)rgba.B / max,
                    a = (float)rgba.A / max
                };
                pixels[IndexPngToTexture(row, col, numRows, numCols)] = color;
            }
        }
Exemple #18
0
 public void Rectangle(RGBA color, float x, float y, float width, float height, bool fill = true)
 {
 }
Exemple #19
0
        private void ParseTag(ISwfTag tag)
        {
            switch (tag.TagType)
            {
            case TagType.DefineSprite:
                ParseDefineSpriteTag((DefineSpriteTag)tag);
                break;

            case TagType.DefineShape:
                ParseDefineShapeTag((DefineShapeTag)tag);
                break;

            case TagType.DefineShape2:
                ParseDefineShape2Tag((DefineShape2Tag)tag);
                break;

            case TagType.DefineShape3:
                ParseDefineShape3Tag((DefineShape3Tag)tag);
                break;

            case TagType.DefineShape4:
                ParseDefineShape4Tag((DefineShape4Tag)tag);
                break;

            case TagType.JPEGTables:
                // not retained
                break;

            case TagType.DefineBits:
                ParseDefineBits((DefineBitsTag)tag);
                break;

            case TagType.DefineBitsJPEG2:
                ParseDefineBits((DefineBitsTag)tag);
                break;

            case TagType.DefineBitsJPEG3:
                ParseDefineBits((DefineBitsTag)tag);
                break;

            case TagType.DefineBitsLossless:
                ParseDefineBitsLossless((DefineBitsLosslessTag)tag);
                break;

            case TagType.DefineBitsLossless2:
                if (!addedFullBitmap)
                {
                    addedFullBitmap = true;
                    DefineBitsLosslessTag t = (DefineBitsLosslessTag)tag;
                    fullBitmapId = t.CharacterId;
                    //DefineBitsLosslessTag t = new DefineBitsLosslessTag(true);
                    //t.CharacterId = ot.CharacterId;
                    //t.BitmapFormat = ot.BitmapFormat;
                    t.Width         = (uint)fullBitmap.Bitmap.Width;
                    t.Height        = (uint)fullBitmap.Bitmap.Height;
                    t.OrgBitmapData = null;
                    uint   pxCount = t.Width * t.Height;
                    RGBA[] pxs     = new RGBA[pxCount];

                    fullBitmap.LockBitmap();
                    for (int i = 0; i < pxCount; i++)
                    {
                        int       x  = (int)(i % t.Width);
                        int       y  = (int)(Math.Floor((double)(i / t.Width)));
                        PixelData pd = fullBitmap.GetPixel(x, y);
                        pxs[i] = new RGBA(pd.red, pd.green, pd.blue, pd.alpha);
                    }
                    t.BitmapData = pxs;
                    fullBitmap.UnlockBitmap();
                }
                break;

            case TagType.UnsupportedDefinition:
                break;
            }
        }
Exemple #20
0
 public static string ToHtmlString(this RGBA color) => $"{color:X}";
Exemple #21
0
        private void UpdateCell(int row, int col)
        {
            var cell = Cells[row][col];
            var elem = BdtBoard.GetAt(row, col);

            Board.UpdateCell(row, col, (img) =>
            {
                img.Graphics.Clear(RGBA.White);
                img.MakeTransparent(RGBA.White);
                var color = RGBA.White;
                switch (elem.Type)
                {
                case TrenElementType.City: color = RGBA.Black; break;

                case TrenElementType.Track:
                    if (elem.InUse)
                    {
                        switch (elem.Color)
                        {
                        case TrenColor.Black: color = RGBA.Black; break;

                        case TrenColor.Blue: color = new RGBA()
                        {
                            B = 255, A = 255
                        }; break;

                        case TrenColor.Green: color = new RGBA()
                        {
                            G = 255, A = 255
                        }; break;

                        case TrenColor.Orange: color = new RGBA()
                        {
                            R = 255, G = 150, A = 255
                        }; break;

                        case TrenColor.Pink: color = new RGBA()
                        {
                            R = 200, G = 50, B = 50, A = 255
                        }; break;

                        case TrenColor.Red: color = new RGBA()
                        {
                            R = 255, A = 255
                        }; break;

                        case TrenColor.White: color = RGBA.White; break;

                        case TrenColor.Yellow: color = new RGBA()
                        {
                            R = 255, G = 255, A = 255
                        }; break;

                        default: throw new Exception("Unknown track color : " + elem.Color);
                        }
                    }
                    else
                    {
                        color = new RGBA()
                        {
                            R = 150, G = 150, B = 150, A = 255
                        }
                    };
                    break;

                case TrenElementType.Button: color = RGBA.Black; break;

                case TrenElementType.Destination: break;

                default: throw new Exception("Unknow tren type : " + elem.Type);
                }

                img.Graphics.Polygon(color, cell.NormalizedPoints, fill: true, border: true);
            });
        }
Exemple #22
0
        public static unsafe UnmanagedImage GetChannelAsImage(this UnmanagedImage image, RGBA channel)
        {
            var c  = (short)channel;
            var pb = image.GetPixelFormatSizeInBytes();

            if (c < 0 ||
                c >= pb)
            {
                throw new ArgumentOutOfRangeException(nameof(c));
            }

            var wb  = pb * image.Width;
            var pad = image.Stride - wb;

            var result = UnmanagedImage.Create(image.Width, image.Height, PixelFormat.Format8bppIndexed);

            var d = (byte *)image.ImageData + c;
            var e = (byte *)result.ImageData;

            for (var dT0 = d + (image.Stride * image.Height); d < dT0; d += pad)
            {
                for (var dToLine = d + wb; d < dToLine; d += pb, e++)
                {
                    *e = *d;
                }
            }

            return(result);
        }
Exemple #23
0
 private string GetMaxColorString(RGBA color)
 {
     return($"color {color.R} {color.G} {color.B} {color.A}");
 }
        public void Deserialize(string input)
        {
            string[] vals = input.Split(',');
            Family = vals [0];

            FontSlant slant;

            if (vals.Length > 1 && Enum.TryParse <FontSlant> (vals [1], out slant))
            {
                Slant = slant;
            }
            else
            {
                Slant = FontSlant.Normal;
            }

            FontWeight weight;

            if (vals.Length > 2 && Enum.TryParse <FontWeight> (vals [2], out weight))
            {
                Weight = weight;
            }
            else
            {
                Weight = FontWeight.Normal;
            }

            double scale;

            if (vals.Length > 3 && double.TryParse(vals [3], out scale))
            {
                Scale = scale;
            }
            else
            {
                Scale = 12.0;
            }

            double lineSpacing;

            if (vals.Length > 4 && double.TryParse(vals [4], out lineSpacing))
            {
                LineSpacing = lineSpacing;
            }
            else
            {
                LineSpacing = Scale / 2;
            }

            Color = new RGBA();
            if (vals.Length > 5)
            {
                string[] colors = vals [5].Split('|');
                byte     red, green, blue;
                if (byte.TryParse(colors [0], out red) &&
                    byte.TryParse(colors [1], out green) &&
                    byte.TryParse(colors [2], out blue))
                {
                    Color = new RGBA(red, green, blue);//red, green, blue);
                }
            }

            if (vals.Length > 6)
            {
                Underline = Convert.ToBoolean(vals [6]);
            }
        }
Exemple #25
0
        //public MaterialScript() { }

        public MaterialScript(H3D Scene, int MdlIndex, int AnimIndex = -1)  //TODO: Needs more object-oriented-ness?
        {
            if (MdlIndex != -1)
            {
                H3DModel Mdl = Scene.Models[MdlIndex];

                if (Mdl.Materials.Count < 1)
                {
                    return;                          //if model has no materials, abort
                }
                //
                int             stageN;
                PICATexEnvStage stage;

                //Initialize script Stringbuilder
                script = new StringBuilder("vtxColor = VertexColor()\n");
                script.Append("scriptPath = getThisScriptFilename()\nscriptPath = getFilenamePath scriptPath\n\n");
                //TODO: add script path get, append it to texture files

                foreach (H3DMaterial Mtl in Mdl.Materials)
                {
                    #region >=============(Basic Material Setup)=============<
                    //Assign basic properties
                    script.Append(
                        $"{Mtl.Name}_mat = standardMaterial()\n"
                        + $"{Mtl.Name}_mat.name = \"{Mtl.Name}_mat\"\n"
                        + $"{Mtl.Name}_mat.shaderByName = \"phong\"\n"
                        + $"{Mtl.Name}_mat.showInViewport = true\n"
                        + $"{Mtl.Name}_mat.ambient = {GetMaxColorString(Mtl.MaterialParams.AmbientColor)}\n"
                        + $"{Mtl.Name}_mat.diffuse = {GetMaxColorString(Mtl.MaterialParams.DiffuseColor)}\n"      //TODO: should these colors include the alpha value?
                        + $"{Mtl.Name}_mat.specular = {GetMaxColorString(Mtl.MaterialParams.Specular0Color)}\n"
                        + $"{Mtl.Name}_mat.specularLevel = {Mtl.MaterialParams.Specular0Color.A/2.55d}\n"
                        //TODO: set 2-sidedness
                        + '\n');

                    //create bitmap maps for textures
                    if (Mtl.Texture0Name != null && Mtl.Texture0Name.Length > 0)
                    {
                        script.Append(GetTextureString(Mtl, 0));
                    }
                    if (Mtl.Texture1Name != null && Mtl.Texture1Name.Length > 0)
                    {
                        script.Append(GetTextureString(Mtl, 1));
                    }
                    if (Mtl.Texture2Name != null && Mtl.Texture2Name.Length > 0)
                    {
                        script.Append(GetTextureString(Mtl, 2));
                    }
                    script.Append('\n');

                    //find the greatest used map channel (may be unreliable, assumes all map channels on the mesh are used by at least one texture)
                    maxMapChannel = 0;
                    for (int i = 0; i < Mtl.MaterialParams.TextureCoords.Length; i++)
                    {//TODO: is scale != <0,0> the best way to tell if the texture coord is used?
                        if (Mtl.MaterialParams.TextureSources[i] + 1 > maxMapChannel && Mtl.MaterialParams.TextureCoords[i].MappingType == H3DTextureMappingType.UvCoordinateMap && Mtl.MaterialParams.TextureCoords[i].Scale != Vector2.Zero)
                        {
                            maxMapChannel = (int)Mtl.MaterialParams.TextureSources[i] + 1;
                        }
                    }

                    #endregion


                    #region >=============(Diffuse Map Creation)=============<
                    //create diffuse composite map
                    script.Append("comp = compositeMap()\n");

                    //Setup diffuse map stages
                    stageN = 1;
                    for (int j = 0; j < Mtl.MaterialParams.TexEnvStages.Length; j++)
                    {
                        stage = Mtl.MaterialParams.TexEnvStages[j];
                        if (stage.IsColorPassThrough)
                        {
                            continue;                                                           //if passthrough stage, skip
                        }
                        if (stage.UpdateColorBuffer)                                            //if this stage updates the color Buffer
                        {
                            script.Append("buffer = copy(comp)\n");                             //  store copy of composite map as "buffer"
                            if (stage.Source.Color[0] != PICATextureCombinerSource.Previous)    //  if current stage is not using previous   //TODO: Check for "Previous" in 1 or 2?
                            {
                                script.Append("comp = compositeMap()\n");                       //    start a new composite map
                                stageN = 1;
                            }
                        }

                        //assign the stage's const color
                        stageColor = GetConstColor(Mtl, j);

                        //create layers based on combiner type //TODO: put more comments here
                        for (int i = 0; i < combinerTxtCount[(int)(stage.Combiner.Color)]; i++)
                        {
                            //if operand is "Previous" don't add a layer for it
                            if (stage.Source.Color[i] == PICATextureCombinerSource.Previous)
                            {
                                continue;                                                               //TODO: Throw exception if 1 or 2 is "Previous"?
                            }
                            if (i == 2 && stage.Combiner.Color == PICATextureCombinerMode.Interpolate)  //if combiner mode is "Interpolate", assign the last source as a mask to the previous layer
                            {
                                script.Append($"comp.mask[{stageN-1}] = {GetSourceStringColor(stage, i)}\n");
                            }
                            else  //otherwise add a layer for the source and set the layer's blend mode based on the stage's combiner mode
                            {
                                script.Append($"comp.mapList[{stageN}] = {GetSourceStringColor(stage, i)}\n");
                                script.Append($"comp.blendMode[{stageN}] = {combinerOps[(int)(stage.Combiner.Color), i]}\n");
                                stageN++;
                            }
                        }
                    }

                    //assign composite map to main material
                    script.Append($"{Mtl.Name}_mat.diffuseMap = comp\n");
                    #endregion


                    #region >=============(Alpha Map Creation)=============<
                    //only create/assign alpha if it's used
                    if (!Mtl.MaterialParams.AlphaTest.Enabled && Mtl.MaterialParams.BlendFunction.ColorDstFunc == PICABlendFunc.Zero && Mtl.MaterialParams.BlendFunction.AlphaDstFunc == PICABlendFunc.Zero)
                    {
                        //Alpha source of "DestinationColor" is a special exception
                        if (Mtl.MaterialParams.BlendFunction.AlphaSrcFunc == PICABlendFunc.DestinationColor)//if alpha src = DestinationColor, use vtx alpha
                        {
                            script.Append("vtxAlpha = VertexColor()\n"
                                          + $"vtxAlpha.map = {maxMapChannel + 1}\n"
                                          + "vtxAlpha.subid = 1\n");
                            script.Append($"{Mtl.Name}_mat.opacityMap = vtxAlpha\n");
                        }
                        script.Append("\n\n");
                        continue;   //skip to next material
                    }

                    //reenable texture alpha if alpha test is enabled
                    if (Mtl.MaterialParams.AlphaTest.Enabled)  //TODO: this could be better somehow
                    {
                        if (Mtl.Texture0Name != null && Mtl.Texture0Name.Length > 0)
                        {
                            script.AppendLine($"txt{0}.alphasource = 0");
                        }
                        if (Mtl.Texture1Name != null && Mtl.Texture1Name.Length > 0)
                        {
                            script.AppendLine($"txt{1}.alphasource = 0");
                        }
                        if (Mtl.Texture2Name != null && Mtl.Texture2Name.Length > 0)
                        {
                            script.AppendLine($"txt{2}.alphasource = 0");
                        }
                        script.Append('\n');
                    }


                    //create alpha composite map
                    script.Append("comp = compositeMap()\n");

                    //Setup alpha map stages
                    stageN = 1;
                    for (int j = 0; j < Mtl.MaterialParams.TexEnvStages.Length; j++)
                    {
                        stage = Mtl.MaterialParams.TexEnvStages[j];
                        if (stage.IsAlphaPassThrough)
                        {
                            continue;                                                           //if passthrough stage, skip
                        }
                        if (stage.UpdateAlphaBuffer)                                            //if this stage updates the alpha Buffer
                        {
                            script.Append("buffer = copy(comp)\n");                             //  store copy of composite map as "buffer"
                            if (stage.Source.Alpha[0] != PICATextureCombinerSource.Previous)    //  if current stage is not using previous   //TODO: Check for "Previous" in 1 or 2
                            {
                                script.Append("comp = compositeMap()\n");                       //    start a new composite map
                                stageN = 1;
                            }
                        }

                        //assign the stage's const color
                        stageColor = GetConstColor(Mtl, j);

                        //create layers based on combiner type
                        for (int i = 0; i < combinerTxtCount[(int)(stage.Combiner.Alpha)]; i++)
                        {
                            //if operand is "Previous" don't add a layer for it
                            if (stage.Source.Alpha[i] == PICATextureCombinerSource.Previous)
                            {
                                continue;                                                               //TODO: Throw exception if 1 or 2 is "Previous"?
                            }
                            if (i == 2 && stage.Combiner.Alpha == PICATextureCombinerMode.Interpolate)  //if combiner mode is "Interpolate", assign the last source as a mask to the previous layer
                            {
                                script.Append($"comp.mask[{stageN - 1}] = {GetSourceStringAlpha(stage, i)}\n");
                            }
                            else  //otherwise add a layer for the source and set the layer's blend mode based on the stage's combiner mode
                            {
                                script.Append($"comp.mapList[{stageN}] = {GetSourceStringAlpha(stage, i)}\n");
                                script.Append($"comp.blendMode[{stageN}] = {combinerOps[(int)(stage.Combiner.Alpha), i]}\n");
                                stageN++;
                            }
                        }
                    }

                    //assign composite map to main material
                    script.Append($"{Mtl.Name}_mat.opacityMap = comp\n");
                    #endregion

                    script.Append("\n\n");
                }

                //create material assignment loop
                script.Append("for OBJ in Geometry do\n(\n  if OBJ.material != undefined then\n  (\n");
                foreach (H3DMaterial Mtl in Mdl.Materials)
                {
                    script.Append($"    if OBJ.material.name == \"{Mtl.Name}_mat\" then OBJ.material = {Mtl.Name}_mat\n");
                }
                script.Append("  )\n)\n");
            } //MdlIndex != -1
        }
Exemple #26
0
        public void LoadBinaryData(byte[] inData)
        {
            using (MemoryStream ms = new MemoryStream(inData))
            {
                using (BinaryReader br = new BinaryReader(ms))
                {
                    this.TextureCount = br.ReadUInt32();
                    this.GroupCount = br.ReadUInt32();
                    this.PortalCount = br.ReadUInt32();
                    this.LightCount = br.ReadUInt32();
                    this.DoodadNameCount = br.ReadUInt32();
                    this.DoodadDefinitionCount = br.ReadUInt32();
                    this.DoodadSetCount = br.ReadUInt32();

                    this.BaseAmbientColour = br.ReadRGBA();
                    this.AreaTableID = new UInt32ForeignKey("WMOAreaTable", "WMOID", br.ReadUInt32());
                    this.BoundingBox = br.ReadBox();
                    this.Flags = (RootFlags) br.ReadUInt32();
                }
            }
        }
        private void tsmiCopyRGB_Click(object sender, EventArgs e)
        {
            RGBA rgba = colorPicker.SelectedColor.RGBA;

            ClipboardHelpers.CopyText($"{rgba.Red}, {rgba.Green}, {rgba.Blue}");
        }
Exemple #28
0
 public static string Color(this string str, RGBA color)
 {
     return($"<color=#{color:X}>{str}</color>");
 }
Exemple #29
0
 /// <summary>
 /// Initializes the channel show filter.
 /// </summary>
 /// <param name="channel">Channel of RGBA model</param>
 public ShowChannel(RGBA channel)
 {
     Channel = channel;
 }
Exemple #30
0
 public void Clear(RGBA color)
 {
     Graphics.FillRectangle(GetCachedSolidBrush(color), 0, 0, Width, Height);
 }
Exemple #31
0
        /// <summary>
        /// Load materials in stream.
        /// </summary>
        /// <param name="stream">Stream to use.</param>
        /// <returns>Material definitions.</returns>
        public static IEnumerable <NsbmdMaterial> ReadTex0(Stream stream, int blockoffset, out int ptexnum, out int ppalnum, out List <NSBMDTexture> texs, out List <NSBMDPalette> pals)
        {
            EndianBinaryReader reader = new EndianBinaryReader(stream, Endianness.LittleEndian);
            UInt32             blocksize, blockptr, blocklimit;
            int    texnum;
            UInt32 texdataoffset;
            int    texdatasize;
            UInt32 sptexoffset;  // for 4x4 compressed texels only
            int    sptexsize;    // for 4x4 compressed texels only
            UInt32 spdataoffset; // for 4x4 compressed texels only
            int    palnum;
            UInt32 paldefoffset;
            UInt32 paldataoffset;
            int    paldatasize;

            NsbmdMaterial[] material = null;
            int             i, j;

            texs = new List <NSBMDTexture>();
            pals = new List <NSBMDPalette>();

            blockptr   = (uint)(blockoffset + 4); // already read the block ID, so skip 4 bytes
            blocksize  = reader.ReadUInt32();     // block size
            blocklimit = (uint)(blocksize + blockoffset);
            Console.WriteLine("DEBUG: blockoffset = {0}, blocksize = {1}", blockoffset, blocksize);

            stream.Skip(4);                         // skip 4 padding 0s
            texdatasize = reader.ReadUInt16() << 3; // total texture data size div8
            stream.Skip(6);                         // skip 6 bytes
            texdataoffset = (uint)(reader.ReadUInt32() + blockoffset);

            stream.Skip(4);                                           // skip 4 padding 0s
            sptexsize = reader.ReadUInt16() << 3;                     // for format 5 4x4-texel, data size div8
            stream.Skip(6);                                           // skip 6 bytesmhm
            sptexoffset  = (uint)(reader.ReadUInt32() + blockoffset); // for format 5 4x4-texel, data offset
            spdataoffset = (uint)(reader.ReadUInt32() + blockoffset); // for format 5 4x4-texel, palette info

            stream.Skip(4);                                           // skip 4 bytes
            paldatasize = reader.ReadUInt16() << 3;                   // total palette data size div8
            stream.Skip(2);                                           // skip 2 bytes
            paldefoffset  = (uint)(reader.ReadUInt32() + blockoffset);
            paldataoffset = (uint)(reader.ReadUInt32() + blockoffset);

            //	printf( "texdataoffset = %08x texdatasize = %08x\n", texdataoffset, texdatasize );
            //	printf( "sptexoffset = %08x sptexsize = %08x spdataoffset = %08x\n", sptexoffset, sptexsize, spdataoffset );
            //	printf( "paldataoffset = %08x paldatasize = %08x\n", paldataoffset, paldatasize );

            ////////////////////////////////////////////////
            // texture definition

            stream.Skip(1);               // skip dummy '0'
            texnum   = reader.ReadByte(); // no of texture
            blockptr = (uint)stream.Position;
            stream.Seek(paldefoffset, SeekOrigin.Begin);
            stream.Skip(1);             // skip dummy '0'
            palnum = reader.ReadByte(); // no of palette
            stream.Seek(blockptr, SeekOrigin.Begin);

            Console.WriteLine("texnum = {0}, palnum = {1}", texnum, palnum);

            // allocate memory for material, great enough to hold all texture and palette
            material = new NsbmdMaterial[(texnum > palnum ? texnum : palnum)];
            for (i = 0; i < material.Length; i++)
            {
                material[i] = new NsbmdMaterial();
            }


            stream.Skip(14 + (texnum * 4)); // go straight to texture info

            for (i = 0; i < texnum; i++)
            {
                UInt32 offset;
                int    param;
                int    format;
                int    width;
                int    height;

                var mat = material[i];

                offset = (uint)(reader.ReadUInt16() << 3);
                param  = reader.ReadUInt16();   // texture parameter
                stream.Skip(4);                 // skip 4 bytes

                format     = (param >> 10) & 7; // format 0..7, see DSTek
                width      = 8 << ((param >> 4) & 7);
                height     = 8 << ((param >> 7) & 7);
                mat.color0 = (param >> 13) & 1;

                if (format == 5)
                {
                    mat.texoffset = offset + sptexoffset; // 4x4-Texel Compressed Texture
                }
                else
                {
                    mat.texoffset = offset + texdataoffset;
                }

                mat.format = format;
                mat.width  = width;
                mat.height = height;
                NSBMDTexture t = new NSBMDTexture();
                t.format = format;
                t.width  = width;
                t.height = height;
                t.color0 = (param >> 13) & 1;
                texs.Add(t);
            }

            ////////////////////////////////////////////
            // copy texture names
            for (i = 0; i < texnum; i++)
            {
                material[i].texname         = Utils.ReadNSBMDString(reader);
                reader.BaseStream.Position -= 16;
                texs[i].texname             = Utils.ReadNSBMDString(reader);
            }

            ////////////////////////////////////////////////
            // calculate each texture's size
            for (i = 0; i < texnum; i++)
            {
                int[] bpp = { 0, 8, 2, 4, 8, 2, 8, 16 };

                var mat = material[i];
                mat.texsize = (uint)(mat.width * mat.height * bpp[mat.format] / 8);
                Console.WriteLine("tex {0} '{1}': offset = {2} size = {3} [W,H] = [{4}, {5}]",
                                  i, mat.texname, mat.texoffset, mat.texsize, mat.width, mat.height);
                texs[i].texsize = (uint)(mat.width * mat.height * bpp[mat.format] / 8);
            }

            ////////////////////////////////////////////////
            // palette definition
            stream.Seek(paldefoffset + 2, SeekOrigin.Begin);    // skip palnum, already read
            stream.Seek(14 + (palnum * 4), SeekOrigin.Current); // go straight to palette info
            for (i = 0; i < palnum; i++)
            {
                uint curOffset = (uint)((reader.ReadUInt16() << 3) + paldataoffset);
                stream.Seek(2, SeekOrigin.Current); // skip 2 bytes
                material[i].paloffset = curOffset;
                NSBMDPalette t = new NSBMDPalette();
                t.paloffset = curOffset;
                pals.Add(t);
            }

            ////////////////////////////////////////////////
            // copy palette names
            for (i = 0; i < palnum; i++)
            {
                var mat = material[i];
                mat.palname = Utils.ReadNSBMDString(reader);
                reader.BaseStream.Position -= 16;
                pals[i].palname             = Utils.ReadNSBMDString(reader);
            }

            ////////////////////////////////////////////////
            // calculate each palette's size
            // assume the palettes are stored sequentially

            /*for (i = 0; i < palnum - 1; i++)
             * {
             *  int r;
             *  var mat = material[i];
             *  r = i;
             *  try { while (material[r].paloffset == mat.paloffset) r++; }
             *  catch { }
             *  // below is RotA stupid way to calculate the size of palette: next's offset - current's offset
             *  // it works most of the time
             *  if (r != palnum)
             *  {
             *      mat.palsize = material[r].paloffset - mat.paloffset;
             *      pals[i].palsize = material[r].paloffset - mat.paloffset;
             *  }
             *  else
             *  {
             *      mat.palsize = blocklimit - mat.paloffset;
             *      pals[i].palsize = blocklimit - mat.paloffset;
             *  }
             *  //printf("pal '%s' size = %d\n", mat->palname, mat->palsize);
             * }
             * material[i].palsize = blocklimit - material[i].paloffset;
             * pals[i].palsize = blocklimit - material[i].paloffset;*/
            List <int> offsets = new List <int>();

            for (int k = 0; k < pals.Count; k++)
            {
                if (!offsets.Contains((int)pals[k].paloffset))
                {
                    offsets.Add((int)pals[k].paloffset);
                }
            }
            offsets.Add((int)blocklimit);
            offsets.Sort();
            for (int k = 0; k < pals.Count; k++)
            {
                int pallength;
                int l = -1;
                do
                {
                    l++;
                }while (offsets[l] - pals[k].paloffset <= 0);//nsbtx.PalInfo.infoBlock.PalInfo[i + j].Palette_Offset - nsbtx.PalInfo.infoBlock.PalInfo[i].Palette_Offset == 0)
                pallength = offsets[l] - (int)pals[k].paloffset;
                //RGBA[] c_ = pals[k].paldata;
                //List<RGBA> c = new List<RGBA>();
                //c.AddRange(pals[k].paldata.Take(pallength / 2));
                //pals[k].paldata = c.ToArray();
                pals[k].palsize     = (uint)pallength;
                material[k].palsize = (uint)pallength;
            }

            ////////////////////////////////////////////////
            // traverse each texture
            for (i = 0; i < texnum; i++)
            {
                var mat = material[i];
                stream.Seek(mat.texoffset, SeekOrigin.Begin);

                ////////////////////////////////////////////////
                // read texture into memory
                byte[] by = reader.ReadBytes((int)mat.texsize);
                mat.texdata     = by;
                texs[i].texdata = by;

                Console.WriteLine("DEBUG: texoffset = {0}, texsize = {1}", mat.texoffset, mat.texsize);

                ////////////////////////////////////////////////
                // additional data for format 5 4x4 compressed texels
                if (mat.format == 5)
                {
                    UInt32 r = mat.texsize / 2;//>> 1;
                    stream.Seek(spdataoffset + (mat.texoffset - sptexoffset) / 2, SeekOrigin.Begin);

                    by             = reader.ReadBytes((int)r);
                    mat.spdata     = by;
                    texs[i].spdata = by;
                    Console.WriteLine("DEBUG: 4x4-texel spdataoffset = {0}, spdatasize = {1}", spdataoffset, r);

                    //spdataoffset += r;
                }
            }


            ////////////////////////////////////////////////
            // traverse each palette
            for (i = 0; i < palnum; i++)
            {
                try
                {
                    NsbmdMaterial mat      = material[i];
                    var           palentry = mat.palsize >> 1;

                    RGBA[] rgbq = new RGBA[palentry];

                    Console.WriteLine("DEBUG: converting pal '{0}', palentry = {1}", mat.palname, palentry);

                    stream.Seek(mat.paloffset, SeekOrigin.Begin);
                    for (j = 0; j < palentry; j++)
                    {
                        UInt16 p = reader.ReadUInt16();
                        rgbq[j].R = (byte)(((p >> 0) & 0x1f) << 3);           // red
                        rgbq[j].G = (byte)(((p >> 5) & 0x1f) << 3);           // green
                        rgbq[j].B = (byte)(((p >> 10) & 0x1f) << 3);          // blue
                        //rgbq[j].RotA = (p&0x8000) ? 0xff : 0;
                        rgbq[j].A = (p & 0x8000) == 0 ? (byte)0xff : (byte)0; //0xff; // alpha
                    }
                    mat.paldata     = rgbq;
                    pals[i].paldata = rgbq;
                }
                catch
                {
                }
            }

            ptexnum = texnum;
            ppalnum = palnum;

            return(material);
        }
Exemple #32
0
 /// <summary>
 /// Instantitates a blank window for your use.
 /// </summary>
 public Windowstyle()
 {
     _version = 2;
     for (int i = 0; i < _edgeColors.Length; ++i) _edgeColors[i] = new RGBA();
     for (int i = 0; i < _images.Length; ++i) _images[i] = new Bitmap(16, 16, PixelFormat.Format32bppPArgb);
 }
Exemple #33
0
 public override string ToString()
 {
     return(RGBA.ToString("X8"));
 }
Exemple #34
0
        public async void Clear(RGBA color)
        {
            await Surface.SetFillStyleAsync(ColorCache(color));

            await Surface.FillRectAsync(x : 0, y : 0, Width, Height);
        }
Exemple #35
0
 private SPICA.Math3D.RGBA ConvertRGBA(RGBA color)
 {
     return(new SPICA.Math3D.RGBA(color.R, color.G, color.B, color.A));
 }
Exemple #36
0
        public ModelMaterial(byte[] inData)
        {
            using (MemoryStream ms = new MemoryStream(inData))
            {
                using (BinaryReader br = new BinaryReader(ms))
                {
                    this.Flags = (MaterialFlags) br.ReadUInt32();
                    this.Shader = (ShaderTypes) br.ReadUInt32();
                    this.BlendMode = (BlendingMode) br.ReadUInt32();

                    this.FirstTextureOffset = br.ReadUInt32();
                    this.FirstColour = br.ReadRGBA();
                    this.FirstFlags  = (MaterialFlags)br.ReadUInt32();

                    this.SecondTextureOffset = br.ReadUInt32();
                    this.SecondColour = br.ReadRGBA();

                    this.GroundType = new UInt32ForeignKey("TerrainType", "ID", br.ReadUInt32());
                    this.ThirdTextureOffset = br.ReadUInt32();
                    this.BaseDiffuseColour = br.ReadRGBA();
                    this.ThirdFlags = (MaterialFlags)br.ReadUInt32();

                    this.RuntimeData1 = br.ReadUInt32();
                    this.RuntimeData2 = br.ReadUInt32();
                    this.RuntimeData3 = br.ReadUInt32();
                    this.RuntimeData4 = br.ReadUInt32();
                }
            }
        }
        private void ReadFromFile(string filename)
        {
            if (!File.Exists(filename))
                throw new FileNotFoundException();

            using (BinaryReader reader = new BinaryReader(File.OpenRead(filename)))
            {
                if (!new String(reader.ReadChars(4)).Equals(".rws"))
                    throw new WindowStyleException(filename, "Invalid file header.");
                _version = reader.ReadInt16();
                _edgeWidth = reader.ReadByte();
                _backgroundMode = reader.ReadByte();
                for (int i = 0; i < _edgeColors.Length; ++i) {
                    _edgeColors[i] = new RGBA(reader);
                }
                _edgeOffsets = reader.ReadBytes(4);
                reader.ReadBytes(36); // reserved

                switch (_version)
                {
                    case 2:
                        Image[] images = new Image[4];
                        for (int i = 0; i < 9; ++i)
                        {
                            int width = reader.ReadInt16();
                            int height = reader.ReadInt16();
                            if (i < 7 && i % 2 == 0)
                                images[i / 2] = new Image((uint)width, (uint)height, reader.ReadBytes(width * height * 4));
                            else
                            {
                                int index = (i == 8 ? i : i - 1) / 2;
                                _textures[index] = new Texture((uint)width, (uint)height);
                                _textures[index].Update(reader.ReadBytes(width * height * 4));
                                _sprites[index] = new Sprite(_textures[index]);
                                _textures[index].Repeated = true;
                            }
                        }
                        _atlas.Update(images);
                        break;
                }
            }
        }