Esempio n. 1
0
        public static ResourceTemplate RenderResourceType(ResourceTypeInfo info, string[] exts, Palette p)
        {
            var image = info.EditorSprite;
            using (var s = GlobalFileSystem.OpenWithExts(image, exts))
            {
                // TODO: Do this properly
                var shp = new ShpReader(s) as ISpriteSource;
                var frame = shp.Frames.Last();

                var bitmap = new Bitmap(frame.Size.Width, frame.Size.Height, PixelFormat.Format8bppIndexed);
                bitmap.Palette = p.AsSystemPalette();
                var data = bitmap.LockBits(bitmap.Bounds(),
                    ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

                unsafe
                {
                    byte* q = (byte*)data.Scan0.ToPointer();
                    var stride = data.Stride;

                    for (var i = 0; i < frame.Size.Width; i++)
                        for (var j = 0; j < frame.Size.Height; j++)
                            q[j * stride + i] = frame.Data[i + frame.Size.Width * j];
                }

                bitmap.UnlockBits(data);
                return new ResourceTemplate { Bitmap = bitmap, Info = info, Value = shp.Frames.Count() - 1 };
            }
        }
Esempio n. 2
0
        public void RemoveTest()
        {
            Palette palette = new Palette
            {
                new PaletteEntry(0, Colors.Red),
                new PaletteEntry(2, Colors.Blue),
                new PaletteEntry(1, Colors.Green)
            };

            Assert.AreEqual(3, palette.Count);
            Assert.AreEqual(new PaletteEntry(0, Colors.Red), palette[0]);
            Assert.AreEqual(new PaletteEntry(2, Colors.Blue), palette[1]);
            Assert.AreEqual(new PaletteEntry(1, Colors.Green), palette[2]);

            bool result = palette.Remove(1);
            Assert.IsTrue(result);
            Assert.AreEqual(2, palette.Count);
            Assert.AreEqual(new PaletteEntry(0, Colors.Red), palette[0]);
            Assert.AreEqual(new PaletteEntry(2, Colors.Blue), palette[1]);

            result = palette.Remove(2);
            Assert.IsTrue(result);
            Assert.AreEqual(1, palette.Count);
            Assert.AreEqual(new PaletteEntry(0, Colors.Red), palette[0]);

            result = palette.Remove(1);
            Assert.IsFalse(result);
            Assert.AreEqual(1, palette.Count);

            result = palette.Remove(0);
            Assert.IsTrue(result);
            Assert.AreEqual(0, palette.Count);
        }
Esempio n. 3
0
        public static ActorTemplate RenderActor(ActorInfo info, TileSet tileset, Palette p)
        {
            var image = RenderSprites.GetImage(info);

            using (var s = GlobalFileSystem.OpenWithExts(image, tileset.Extensions))
            {
                var shp = new ShpReader(s);
                var bitmap = RenderShp(shp, p);

                try
                {
                    using (var s2 = GlobalFileSystem.OpenWithExts(image + "2", tileset.Extensions))
                    {
                        var shp2 = new ShpReader(s2);
                        var roofBitmap = RenderShp(shp2, p);

                        using (var g = System.Drawing.Graphics.FromImage(bitmap))
                            g.DrawImage(roofBitmap, 0, 0);
                    }
                }
                catch { }

                return new ActorTemplate
                {
                    Bitmap = bitmap,
                    Info = info,
                    Appearance = info.Traits.GetOrDefault<EditorAppearanceInfo>()
                };
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Copies the rectangle to point.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="sourceRectangle">The source rectangle.</param>
        /// <param name="destination">The destination.</param>
        /// <param name="destinationPoint">The destination point.</param>
        /// <param name="flip">if set to <c>true</c> [flip].</param>
        public static void CopyRectangleToPoint( this Bitmap source, Rectangle sourceRectangle, Bitmap destination, Point destinationPoint, Palette palette, bool reverseX, bool reverseY )
        {
            BitmapData bmdSource = source.LockBits( new Rectangle( 0, 0, source.Width, source.Height ), ImageLockMode.ReadOnly, source.PixelFormat );
            BitmapData bmdDest = destination.LockBits( new Rectangle( 0, 0, destination.Width, destination.Height ), ImageLockMode.WriteOnly, destination.PixelFormat );

            int width = sourceRectangle.Width;
            int height = sourceRectangle.Height;
            int x = destinationPoint.X;
            int y = destinationPoint.Y;
            CalcOffset calcX = reverseX ?
                (CalcOffset)(col => (width - col - 1)) :
                (CalcOffset)(col => col);
            CalcOffset calcY = reverseY ?
                (CalcOffset)(row => (height - row - 1)) :
                (CalcOffset)(row => row);

            for (int col = 0; col < sourceRectangle.Width; col++)
            {
                for (int row = 0; row < sourceRectangle.Height; row++)
                {
                    int index = bmdSource.GetPixel( col + sourceRectangle.X, row + sourceRectangle.Y );
                    if (palette.Colors[index % 16].A != 0)
                    {
                        bmdDest.SetPixel8bpp(
                            x + calcX( col ),
                            y + calcY( row ),
                            index );
                    }
                }
            }

            source.UnlockBits( bmdSource );
            destination.UnlockBits( bmdDest );
        }
Esempio n. 5
0
		IndexedBitmap CreateImage()
		{
			var image = new IndexedBitmap(100, 100, 8, Generator);
			var ega = Palette.GetEgaPalette();
			var pal = new Palette(ega);
			
			// must have at least 256 colors for an 8-bit bitmap
			while (pal.Count < 256)
				pal.Add(Colors.Black);
			image.Palette = pal;
			using (var bd = image.Lock())
			{
				unsafe
				{
					var brow = (byte*)bd.Data;
					for (int y = 0; y < image.Size.Height; y++)
					{
						byte* b = brow;
						var col = -y;
						for (int x = 0; x < image.Size.Width; x++)
						{
							while (col < 0)
								col = ega.Count + col;
							while (col >= ega.Count)
								col -= ega.Count;
							*b = (byte)col++;
							b++;
						}
						brow += bd.ScanWidth;
					}
				}
			}
			return image;
			
		}
Esempio n. 6
0
        public CommandDPForm()
        {
            InitializeComponent();
            this.pbImage.Image = new Bitmap(CommandDPForm.IMG_WIDTH, CommandDPForm.IMG_HEIGHT);

            Graphics imgGraphics = Graphics.FromImage(this.pbImage.Image);
            imgGraphics.Clear(Color.White);
            this.calcStretch();

            this.tool = Palette.LINE;
            this.tsbLine.Tag = Palette.LINE;
            this.tsbRectangle.Tag = Palette.RECTANGLE;
            this.tsbEllipse.Tag = Palette.ELLIPSE;

            this.tsbLeft.Tag = MoveType.LEFT;
            this.tsbUp.Tag = MoveType.UP;
            this.tsbRight.Tag = MoveType.RIGHT;
            this.tsbDown.Tag = MoveType.DOWN;

            this.tscbLineWidth.SelectedIndex = 0;
            this.tsbColor.BackColor = Color.Black;

            this.editor = new Editor();
            this.tscbShapes.Items.Add(new EmptyShape(Pens.White));
            this.tscbShapes.SelectedIndex = 0;
        }
Esempio n. 7
0
		IndexedBitmap CreateImage()
		{
			var image = new IndexedBitmap (100, 100, 8);
			var pal = new Palette (Palette.GetEgaPalette ());
			
			// must have at least 256 colors for an 8-bit bitmap
			while (pal.Count < 256)
				pal.Add (Color.Black);
			image.Palette = pal;
			var bd = image.Lock ();
			
			unsafe {
				int col = 0;
				byte* brow = (byte*)bd.Data;
				for (int y = 0; y < image.Size.Height; y++) {
					byte* b = brow;
					for (int x = 0; x < image.Size.Width; x++) {
						if (col >= pal.Count) 
							col = 0;
						*b = (byte)col++;
						b++;
					}
					brow += bd.ScanWidth;
				}
			}
			image.Unlock (bd);
			return image;
			
		}
Esempio n. 8
0
 public void InitPalette( WorldRenderer wr )
 {
     var paletteName = "{0}{1}".F( info.BaseName, owner.InternalName );
     var newpal = new Palette(wr.Palette(info.BasePalette).Palette,
                      new PlayerColorRemap(info.RemapIndex, owner.ColorRamp));
     wr.AddPalette(paletteName, newpal, info.AllowModifiers);
 }
Esempio n. 9
0
		protected override XCImageCollection LoadFileOverride(string directory,string file,int imgWid,int imgHei,Palette pal)
		{
			System.IO.Stream tabStream=null;

			string tabBase = file.Substring(0,file.LastIndexOf("."));

			try
			{
			    if(System.IO.File.Exists(directory+"\\"+tabBase+TAB_EXT))
			        tabStream = System.IO.File.OpenRead(directory+"\\"+tabBase+TAB_EXT);

			    return new PckFile(System.IO.File.OpenRead(directory+"\\"+file),
			        tabStream,
			        2,
			        pal,
			        imgHei,
			        imgWid);
			}
			catch(Exception)
			{
				if(System.IO.File.Exists(directory+"\\"+tabBase+TAB_EXT))
					tabStream = System.IO.File.OpenRead(directory+"\\"+tabBase+TAB_EXT);

				return new PckFile(System.IO.File.OpenRead(directory+"\\"+file),
					tabStream,
					4,
					pal,
					imgHei,
					imgWid);
			}
		}
Esempio n. 10
0
        public static void RenderTile(BitmapData canvas, int x, int y, Tile tile, Palette palette, int paletteIndex,
            bool flipX, bool flipY, bool transparent)
        {
            int* start = (int*)canvas.Scan0 + canvas.Stride * y / 4 + x;

            for (int py = 0; py < 8; py++)
            {
                int* current = start;
                int actualY = flipY ? (7 - py) : py;

                for (int px = 0; px < 8; px++)
                {
                    byte colorIndex = tile[flipX ? (7 - px) : px, actualY];

                    if (!transparent || (colorIndex != 0))
                    {
                        *current = palette.GetColor(paletteIndex, colorIndex).Argb;
                    }

                    current++;
                }

                start += canvas.Stride / 4;
            }
        }
Esempio n. 11
0
        public static Palette GetDefaultPalette()
        {
            var swatches = new Swatches(); 
            var pal = new Palette();
            pal.Add(swatches.FadedDarkBlue);
            pal.Add(swatches.BrightOrange);
            pal.Add(swatches.SimpleGreen);
            pal.Add(swatches.PurpleByzantium);
            pal.Add(swatches.Jonquil);
            pal.Add(swatches.FireEngineRed);
            pal.Add(swatches.LightGray);
            pal.Add(swatches.DeepBlue);
            pal.Add(swatches.DarkGray);
            pal.Add(swatches.ForestGreen);
            pal.Add(swatches.Carmine);
            pal.Add(swatches.BrightPink);
            pal.Add(swatches.Eggplant);
            pal.Add(swatches.Byzantine);
            pal.Add(swatches.JungleGreen);
            pal.Add(swatches.Black);
            pal.Add(swatches.Jonquil);
            pal.Add(swatches.Chamoisee);

            return pal;
        }
Esempio n. 12
0
    void Start()
    {
        r = new RandomSeed(DateTime.Now.Millisecond);

        //First we create the buffer. This will contain all our sprites
        buffer = new GameObject[NUM_LAYERS,WIDTH,HEIGHT];

        //Second, we find a pointer to the level data
        LD_Cave ld = new LD_Cave(WIDTH, HEIGHT, r.getSeed(),new Vector2(0,0));
        //LD_Dungeon ld = new LD_Dungeon(WIDTH, HEIGHT, r.getSeed(), new Vector2(0,0));
        ld.generate();

        //Next, we generate a color palette
        palette = new Palette(r);

        //Third, we translate the level into sprites
        for(int layer = 0; layer < NUM_LAYERS; layer++)
        {
            for(int y = 0; y < HEIGHT; y++)
            {
                for(int x = 0; x < WIDTH; x++)
                {
                    buffer[layer,x,y] = makeSprite(x,y,ld.mapData[layer,x,y],layer); //ld.mapData[layer,x,y]
                }//for
            }//for
        }//for
    }
Esempio n. 13
0
		public XCImage(Bitmap b,int idx)
		{
			fileNum = idx;
			image = b;
			this.idx = null;
			palette = null;
		}
Esempio n. 14
0
 /// <summary>
 /// Load theme from xml.
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public static bool Load(string path)
 {
     if (!File.Exists(path))
         return false;
     palette = XmlSerializer.Load<Palette>(path);
     return true;
 }
 public void InitPalette( WorldRenderer wr )
 {
     var paletteName = "{0}{1}".F( info.BaseName, owner.InternalName );
     var newpal = new Palette(wr.GetPalette(info.BasePalette),
                      new PlayerColorRemap(info.PaletteFormat, owner.ColorRamp));
     wr.AddPalette(paletteName, newpal);
 }
Esempio n. 16
0
		protected override XCImageCollection LoadFileOverride(string directory, string file, int imgWid, int imgHei, Palette pal)
		{
			XCImageCollection collect = new XCImageCollection();
			XCImage img = new SPKImage(pal, File.OpenRead(directory + "\\" + file),imgWid,imgHei);
			collect.Add(img);

			return collect;
		}
 public void RegisterAppearance(ChartAppearance appearance, ViewType viewType, Palette palette)
 {
     AppearanceColors row = new AppearanceColors(appearance, palette);
     matrix.Add(row);
     for (int i = 0; i <= palette.Count; i++)
         row[i] = AddStyleEditor(AppearanceImageHelper.CreateImage(viewType, appearance, palette, i), i);
     lastRegisteredAppearance++;
 }
Esempio n. 18
0
        public void AddPalette(string name, Palette p)
        {
            if (palettes.ContainsKey(name))
                throw new InvalidOperationException("Palette {0} has already been defined".F(name));

            palettes.Add(name, p);
            indices.Add(name, allocated++);
        }
Esempio n. 19
0
		//entries must not be compressed
		public XCImage(byte[] entries,int width, int height, Palette pal,int idx)
		{
			fileNum=idx;
			this.idx=entries;
			palette=pal;

			if(pal!=null)
				image = Bmp.MakeBitmap8(width,height,entries,pal.Colors);
		}
Esempio n. 20
0
		protected IXCTileset(string name)
			: base(name)
		{
			myPal = GameInfo.DefaultPalette;
			mapSize = new MapSize(60, 60, 4);
			mapDepth = 0;
			underwater = true;
			baseStyle = false;
		}
Esempio n. 21
0
    public Document(FractalSettings settings)
        : base(NSObject.AllocAndInitInstance("Document"))
    {
        m_settings = settings;

        AppDelegate app = NSApplication.sharedApplication().delegate_().To<AppDelegate>();

        m_engine = new ComputeEngine(m_settings);
        m_palette = app.DefaultPalette;
    }
Esempio n. 22
0
 public int AddPalette(string name, Palette p)
 {
     palettes.Add(name, p);
     indices.Add(name, allocated);
     for (int i = 0; i < 256; i++)
     {
         this[new Point(i, allocated)] = p.GetColor(i);
     }
     return allocated++;
 }
        public void OnGenerated(Palette palette)
        {
            Color vibrantDark = new Color(palette.GetDarkVibrantColor(Resource.Color.appMain));
            Color dullDark = new Color(palette.GetDarkMutedColor(Resource.Color.appDark));

            SupportActionBar.SetBackgroundDrawable(new ColorDrawable(vibrantDark));
            SupportActionBar.SetDisplayShowTitleEnabled(false);
            SupportActionBar.SetDisplayShowTitleEnabled(true);
            Window.SetStatusBarColor(dullDark);
        }
Esempio n. 24
0
		public EditorPane(XCImage img)
		{
			this.SetStyle(ControlStyles.DoubleBuffer|ControlStyles.UserPaint|ControlStyles.AllPaintingInWmPaint,true);
			this.img = img;
			pal=null;
			lines=false;

			imgWidth = PckImage.Width*square;
			imgHeight = PckImage.Height*square;
		}
        private static void CreateStudyProgressPalette()
        {
            var entry1 = new PaletteEntry(Color.FromArgb(124, 186, 180), Color.FromArgb(127, 192, 185));
            var entry2 = new PaletteEntry(Color.FromArgb(146, 199, 226), Color.FromArgb(117, 181, 214));
            var entry3 = new PaletteEntry(Color.FromArgb(183, 140, 155), Color.FromArgb(200, 164, 176));
            var entry4 = new PaletteEntry(Color.FromArgb(242, 202, 132), Color.FromArgb(246, 211, 149));
            var entry5 = new PaletteEntry(Color.FromArgb(167, 202, 116), Color.FromArgb(172, 206, 118));

            studyProgressPalette = new Palette(StudyProgressPaletteName,
                new[] {entry1, entry2, entry3, entry4, entry5});
        }
Esempio n. 26
0
        public static Bitmap RenderGrid(TileSet tileSet, Palette palette, TileGrid tileGrid, bool transparent)
        {
            Bitmap bitmap = new Bitmap(tileGrid.Width * tileGrid.TileWidth, tileGrid.Height * tileGrid.TileHeight,
                PixelFormat.Format32bppArgb);

            BitmapData canvas = bitmap.LockBits();
            RenderGrid(canvas, 0, 0, tileSet, palette, tileGrid, transparent);
            bitmap.UnlockBits(canvas);

            return bitmap;
        }
 public void Show(Point location)
 {
     if (this.palette != null)
     {
         this.DestroyPalette(this.palette);
     }
     this.palette = new Palette(this, location);
     this.palette.Font = this.font;
     this.palette.Show();
     this.palette.Focus();
     this.palette.LostFocus += new EventHandler(this.OnPaletteLostFocus);
 }
Esempio n. 28
0
		public PalPanel()
		{
			this.SetStyle(ControlStyles.DoubleBuffer|ControlStyles.UserPaint|ControlStyles.AllPaintingInWmPaint,true);
			myPal = null;
			this.MouseDown+=new MouseEventHandler(mouseDown);
			//Width=(width+2*space)*NumAcross;
			//Height=(height+2*space)*NumAcross;
			clickX=-100;
			clickY=-100;
			selIdx=-1;
			mode = SelectMode.Single;
		}
        public void Setup()
        {
            string paletteFile = @"ColourTables\gameboy.act";
            _palette = Palette.FromFile( paletteFile );

            _pc = new PaletteControl();
            _pc.Value = _palette;

            _form = new Form();
            _form.Controls.Add( _pc );

            _form.Show();
        }
Esempio n. 30
0
        public static Palette GetPaletteFromRange(uint startcolor, int steps)
        {
            var c0 = new Viziblr.Colorspace.ColorHSL(new Viziblr.Colorspace.ColorRGB(startcolor));
            var c1 = new Viziblr.Colorspace.ColorHSL(new Viziblr.Colorspace.ColorRGB(0xff000000));

            var pal = new Palette();
            foreach (double x in RangeSteps(c0.L, c1.L, steps))
            {
                var cx = new Viziblr.Colorspace.ColorHSL(c0.H, c0.S, x);
                var cx_rgb = new Viziblr.Colorspace.ColorRGB32Bit(cx);
                pal.AddARGB(cx_rgb.ToUInt());
            }
            return pal;
        }
Esempio n. 31
0
        /// <summary>
        /// Changes the images starting from index.
        /// </summary>
        /// <param name="groupID"></param>
        /// <param name="index"></param>
        /// <param name="newDatas"></param>
        /// <returns></returns>
        public void ChangeImageData(string groupID, int index, ImageData[] newDatas)
        {
            if (newDatas[0].GetUsedColors().Length > 255)
            {
                throw new Exception("Imported images cannot have more than 255 colors!");
            }

            //Prepare the new palette
            Palette p = paletteCollection.GetPalette();

            int palettePosition = 0;
            int addedLength     = 0;
            int oldIndex        = (GetImage(index) as GfxImage)?.jobIndex ?? 0;

            for (int j = 0; j < newDatas.Length; j++)
            {
                if (index + j >= images.Length)
                {
                    Array.Resize(ref images, index + j + 1);

                    paletteCollection.GetPilFile().Resize(images.Length);
                    p.AddEntry();

                    paletteCollection.GetPilFile().SetOffset(index + j, (paletteCollection.GetPilFile().GetOffset(index + j - 1) + 256 * 2));

                    images[index + j] = new GfxImage(
                        null,
                        p,
                        paletteCollection.GetOffset(index + j));

                    images[index + j].jobIndex = index + j;

                    offsetTable.AddOffset();

                    offsetTable.offsetTable[index + j] = (int)baseStream.Length + addedLength;
                }

                GfxImage i = images[index + j];

                if (i.jobIndex != oldIndex)
                {
                    palettePosition = 0;
                }

                int start = paletteCollection.GetOffset(i.jobIndex);

                i.Width  = newDatas[j].width;
                i.Height = newDatas[j].height;
                //i.DataOffset = offsetTable.GetImageOffset(index + j) + 12;

                palettePosition += RecreatePaletteAt(start, palettePosition, newDatas[j]);

                i.buffer     = i.CreateImageData(newDatas[j]);
                addedLength += i.buffer.Length;

                int nextImageStartOffset = offsetTable.GetImageOffset(index + j + 1);                                                        //Get the current offset of the next image
                int offset = Math.Max(0, offsetTable.GetImageOffset(index + j) + i.HeaderSize + i.buffer.Length - nextImageStartOffset - 1); //Our data could be larger, calculate how much larger

                if (offset != 0)                                                                                                             //We want to move all images that follow our changed image, if our new image is bigger
                {
                    offsetTable.AddOffsetToFollowing(index + j + 1, offset);
                }

                i.DataOffset = 0;                 //Hack, the data is still at the same offset, but the way the we handle the reading forces us to set it to 0, as we write the new image data to buffer[0...] instead of buffer[DataOffset...]

                oldIndex = i.jobIndex;

                Console.WriteLine($"{j}/{newDatas.Length} importing...");
            }
            //return GetDataBufferCollection(groupID);
        }
Esempio n. 32
0
        public void editEventPalette(ulong id, string name)
        {
            Palette palette = data.Pallets.First(o => o.Id == id);

            data.Events.ToLookup(ev => ev.MPalette.First(p => p.Palette.Id == palette.Id).Palette.Name = name);
        }
Esempio n. 33
0
        public int RecreatePaletteAt(int paletteOffset, int additionOffset, ImageData orig)
        {
            Palette p = paletteCollection.GetPalette();

            if (additionOffset == 0)
            {
                for (int i = 0; i < 256; i++)
                {
                    p.SetColor(paletteOffset + i, Palette.RGBToPalette(0, 255, 255));
                }
                //p.SetColor(paletteOffset + 0, Palette.RGBToPalette(255, 0, 0));
                //p.SetColor(paletteOffset + 1, Palette.RGBToPalette(0, 255, 0));
                additionOffset = 1;
            }


            List <uint> colorsToBeChecked = new List <uint>(orig.GetUsedColors());
            List <uint> colorsToBeAdded   = new List <uint>();

            for (int i = paletteOffset; i < colorsToBeChecked.Count + paletteOffset; i++)
            {
                if (colorsToBeChecked[i - paletteOffset] == Palette.RGBToPalette(255, 0, 0) || colorsToBeChecked[i - paletteOffset] == Palette.RGBToPalette(0, 255, 0))
                {
                    continue;
                }

                if (p.GetIndex(paletteOffset, colorsToBeChecked[i - paletteOffset]) == -1)
                {
                    colorsToBeAdded.Add(colorsToBeChecked[i - paletteOffset]);
                }
            }


            for (int i = paletteOffset + additionOffset; i < colorsToBeAdded.Count + paletteOffset + additionOffset; i++)
            {
                p.SetColor(i, colorsToBeAdded[i - paletteOffset - additionOffset]);
            }

            return(colorsToBeAdded.Count);
        }
    public void ReadAnimData(int auxPalIndex)
    {
        int[] AnimX  = new int[390];
        int[] AnimY  = new int[390];
        int[] AnimXY = new int[776];//For UW2
        int[] UW2_X  = { 35, 36, 37, -1, 39, 40, 41, 42, -1, 44, 45, 46, -1, 48, 49, 50, 51, -1, -1, -1, -1, -1, 57, 58, 59, -1, -1, 62, 63, 64, -1, 132, 133, 134, -1, 136, 137, 138, 139, -1, 141, 142, 143, -1, 145, 146, 147, 148, -1, -1, -1, -1, -1, 154, 155, 156, -1, -1, 159, 160, 161, -1, 229, 230, 231, -1, 233, 234, 235, 236, -1, 238, 239, 240, -1, 242, 243, 244, 245, -1, -1, -1, -1, -1, 251, 252, 253, -1, -1, 256, 257, 258, -1, -1, -1, -1, -1, 330, 331, 332, -1, -1, 335, -1, 337, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 423, 424, 425, -1, 427, 428, 429, 430, -1, 432, 433, 434, -1, 436, 437, 438, 439, -1, -1, -1, -1, -1, 446, 447, 448, -1, -1, -1, 450, 451, 452, 520, 521, 522, -1, 524, 525, 526, 527, -1, 529, 530, 531, -1, 533, 534, 535, 536, -1, -1, -1, -1, -1, 542, 543, 544, -1, -1, 547, 548, 549, -1, 617, 618, 619, -1, 621, 622, 623, 624, -1, 626, 627, 628, -1, 630, 631, 632, 633, -1, -1, -1, -1, -1, 639, 640, 641, -1, -1, 644, 645, 646, -1, -1, -1, -1, -1, 718, 719, 720, -1, 723, -1, 725, -1, -1 };
        int[] UW2_Y  = { 66, 67, 68, -1, 70, 71, 72, 73, -1, 75, 76, 77, -1, 79, 80, 81, 82, -1, -1, -1, -1, -1, 88, 89, 90, -1, -1, 93, 94, 95, -1, 163, 164, 165, -1, 167, 168, 169, 170, -1, 172, 173, 174, -1, 176, 177, 178, 179, -1, -1, -1, -1, -1, 185, 186, 187, -1, -1, 190, 191, 192, -1, 260, 261, 262, -1, 264, 265, 266, 267, -1, 269, 270, 271, -1, 273, 274, 275, 276, -1, -1, -1, -1, -1, 282, 283, 284, -1, -1, 287, 288, 289, -1, -1, -1, -1, -1, 361, 362, 363, -1, -1, 366, -1, 368, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 454, 455, 456, -1, 458, 459, 460, 461, -1, 463, 464, 465, -1, 467, 468, 469, 470, -1, -1, -1, -1, -1, 476, 477, 478, -1, -1, -1, 481, 482, 483, 551, 552, 553, -1, 555, 556, 557, 558, -1, 560, 561, 562, -1, 564, 565, 566, 567, -1, -1, -1, -1, -1, 573, 574, 575, -1, -1, 578, 579, 580, -1, 648, 649, 650, -1, 652, 653, 654, 655, -1, 657, 658, 659, -1, 661, 662, 663, 664, -1, -1, -1, -1, -1, 670, 671, 672, -1, -1, 675, 676, 677, -1, -1, -1, -1, -1, 749, 750, 751, -1, 754, -1, 756, -1, -1 };


        string datfile = "data\\weapons.dat";
        string cmfile  = "data\\weapons.cm";
        string grfile  = "data\\weapons.gr";

        if (_RES == GAME_UW2)
        {
            datfile = "data\\weap.dat";
            cmfile  = "data\\weap.cm";
            grfile  = "data\\weap.gr";
        }
        char[] AnimData;
        char[] textureFile;
        int    offset    = 0;
        int    GroupSize = 28;    //28 for uw1

        int MaxHeight = 112;
        int MaxWidth  = 172;

        if (_RES == GAME_UW2)
        {
            MaxHeight = 128;
            MaxWidth  = 208;
        }
        int add_ptr = 0;
        int alpha   = 0;

        DataLoader.ReadStreamFile(BasePath + datfile, out AnimData);
        DataLoader.ReadStreamFile(BasePath + grfile, out textureFile);
        if (_RES != GAME_UW2)
        {
            GroupSize = 28;

            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < GroupSize; j++)
                {
                    AnimX[j + offset] = (int)DataLoader.getValAtAddress(AnimData, add_ptr++, 8);
                }
                for (int j = 0; j < GroupSize; j++)
                {
                    AnimY[j + offset] = (int)DataLoader.getValAtAddress(AnimData, add_ptr++, 8);
                }
                offset = offset + GroupSize;
            }
        }
        else
        {        //In UW2 I just read the values into one array
            for (int i = 0; i <= AnimData.GetUpperBound(0); i++)
            {
                AnimXY[i] = (int)DataLoader.getValAtAddress(AnimData, add_ptr++, 8);
            }
        }


        add_ptr = 0;

        int NoOfTextures = textureFile[2] << 8 | textureFile[1];

        if (_RES == GAME_UW2)
        {
            NoOfTextures = 230;
        }
        ImageCache = new Texture2D[NoOfTextures + 1];

        for (int i = 0; i < NoOfTextures; i++)
        {
            long    textureOffset = DataLoader.getValAtAddress(textureFile, (i * 4) + 3, 32);
            int     BitMapWidth   = (int)DataLoader.getValAtAddress(textureFile, textureOffset + 1, 8);
            int     BitMapHeight  = (int)DataLoader.getValAtAddress(textureFile, textureOffset + 2, 8);
            int     datalen;
            Palette auxpal = PaletteLoader.LoadAuxilaryPal(Loader.BasePath + cmfile, GameWorldController.instance.palLoader.Palettes[PaletteNo], auxPalIndex);
            char[]  imgNibbles;
            char[]  outputImg;
            char[]  srcImg;

            datalen       = (int)DataLoader.getValAtAddress(textureFile, textureOffset + 4, 16);
            imgNibbles    = new char[Mathf.Max(BitMapWidth * BitMapHeight * 2, datalen * 2)];
            textureOffset = textureOffset + 6;                  //Start of raw data.

            copyNibbles(textureFile, ref imgNibbles, datalen, textureOffset);
            //LoadAuxilaryPal(auxPalPath, auxpal, pal, auxPalIndex);
            srcImg    = new char[BitMapWidth * BitMapHeight];
            outputImg = new char[MaxWidth * MaxHeight];
            //Debug.Log("i= " + i + " datalen= " + datalen);
            if (datalen >= 6)
            {
                srcImg = DecodeRLEBitmap(imgNibbles, datalen, BitMapWidth, BitMapHeight, 4);
            }


            //Paste source image into output image.
            int ColCounter = 0; int RowCounter = 0;
            int cornerX;            // = AnimX[i];
            int cornerY;            // = AnimY[i];
            if (_RES != GAME_UW2)
            {
                cornerX = AnimX[i];
                cornerY = AnimY[i];
            }
            else
            {            //Read from XY
                if (UW2_X[i] != -1)
                {
                    cornerX = AnimXY[UW2_X[i]];
                    cornerY = AnimXY[UW2_Y[i]];
                }
                else
                {
                    cornerX = 0;
                    cornerY = BitMapHeight;
                }
            }

            if ((_RES == GAME_UW1) || ((_RES == GAME_UW2) && (UW2_X[i] != -1)))          //Only create if UW1 image or a valid uw2 one
            {
                bool ImgStarted = false;
                for (int y = 0; y < MaxHeight; y++)
                {
                    for (int x = 0; x < MaxWidth; x++)
                    {
                        if ((cornerX + ColCounter == x) && (MaxHeight - cornerY + RowCounter == y) && (ColCounter < BitMapWidth) && (RowCounter < BitMapHeight))
                        {                        //the pixel from the source image is here
                            ImgStarted = true;
                            outputImg[x + (y * MaxWidth)] = srcImg[ColCounter + (RowCounter * BitMapWidth)];
                            ColCounter++;
                        }
                        else
                        {
                            alpha = 0;                          //0
                            outputImg[x + (y * MaxWidth)] = (char)alpha;
                        }
                    }
                    if (ImgStarted == true)
                    {                    //New Row on the src image
                        RowCounter++;
                        ColCounter = 0;
                    }
                }

                ImageCache[i] = Image(outputImg, 0, MaxWidth, MaxHeight, "name_goes_here", auxpal, true);
            }
        }
    }
Esempio n. 35
0
 /// <summary>
 /// Assigns all required parameters.
 /// </summary>
 /// <param name="parameters">Required base parameters.</param>
 /// <param name="palette">Required color palette.</param>
 /// <param name="power">Exponent required for the generalized fractal equation.</param>
 public MandelbrotSet(BaseParameters parameters, Palette palette, double power)
     : base(parameters, palette, power)
 {
 }
Esempio n. 36
0
        void Core_LoadTitleScreen_FE7(
            Palette bg_palette, Tileset bg_tileset,
            Palette mg_palette, Tileset mg_tileset, TSA_Array mg_tsa,
            Palette fg_palette, Tileset fg_tileset)
        {
            GBA.Bitmap result;
            Palette    palette = Palette.Empty(256);

            for (int i = 0; i < bg_palette.Count; i++)
            {
                palette.Set(GBA.Palette.MAX * 15 + i, bg_palette[i]);
            }
            for (int i = 0; i < mg_palette.Count; i++)
            {
                palette.Set(GBA.Palette.MAX * 14 + i, mg_palette[i]);
            }
            for (int i = 0; i < fg_palette.Count; i++)
            {
                palette.Set(i, fg_palette[i]);
            }
            result        = new GBA.Bitmap(GBA.Screen.WIDTH, GBA.Screen.HEIGHT);
            result.Colors = palette;

            if (BG_CheckBox.Checked)
            {
                GBA.Image bg = bg_tileset.ToImage(GBA.Screen.W_TILES, GBA.Screen.H_TILES + 1, bg_palette.ToBytes(false));
                for (int y = 0; y < GBA.Screen.HEIGHT; y++)
                {
                    for (int x = 0; x < GBA.Screen.WIDTH; x++)
                    {
                        if (x < 8 && y < 8)
                        {
                            result[x, y] = GBA.Palette.MAX * 15 + bg[x, GBA.Screen.HEIGHT + y];
                        }
                        else
                        {
                            result[x, y] = GBA.Palette.MAX * 15 + bg[x, y];
                        }
                    }
                }
            }
            if (MG_CheckBox.Checked)
            {
                TSA_Image mg = new TSA_Image(mg_palette, mg_tileset, mg_tsa);
                for (int y = 0; y < mg.Height; y++)
                {
                    for (int x = 0; x < mg.Width; x++)
                    {
                        if (mg[x, y] != 0)
                        {
                            result[x, 8 + y] = GBA.Palette.MAX * 14 + mg[x, y];
                        }
                    }
                }
            }
            if (FG_CheckBox.Checked)
            {
                bool      jap      = (Core.CurrentROM.Version == GameVersion.JAP);
                bool      eur      = (Core.CurrentROM.Version == GameVersion.EUR);
                Palette[] palettes = Palette.Split(fg_palette, 8);
                GBA.Image fg;
                // durandal sword
                fg = fg_tileset.ToImage(32, 32, palettes[0].ToBytes(false));
                Core_DrawLayer(result, fg, new Rectangle(0, 0, 192, 112), 32, 16);
                // large 'FIRE EMBLEM' title
                fg.Colors = palettes[4];
                Core_DrawLayer(result, fg, new Rectangle(0, GBA.Screen.HEIGHT, GBA.Screen.WIDTH, 48), 2, jap ? 52 : 54);
                Core_DrawLayer(result, fg, new Rectangle(0, GBA.Screen.HEIGHT - 48, GBA.Screen.WIDTH, 48), 0, jap ? 48 : 52);
                // Nintendo & IS copyrights
                fg.Colors = palettes[2];
                Core_DrawLayer(result, fg, new Rectangle(0, GBA.Screen.WIDTH - 16, GBA.Screen.HEIGHT - 16, 8), eur ?   8 : 16, GBA.Screen.HEIGHT - 16);
                Core_DrawLayer(result, fg, new Rectangle(0, GBA.Screen.WIDTH - 8, GBA.Screen.HEIGHT - 64, 8), eur ? 136 : GBA.Screen.HEIGHT, GBA.Screen.HEIGHT - 16);
                // 'Press Start'
                fg.Colors = palettes[1];
                Core_DrawLayer(result, fg, new Rectangle(128, 208, 96, 16), jap ? 80 : 72, 120);
                if (jap)
                {   // japanese subtitle
                    fg.Colors = palettes[3];
                    Core_DrawLayer(result, fg, new Rectangle(144, 224, 112, 32), 64, 96);
                    // japanese 'FIRE EMBLEM' overhead
                    fg.Colors = palettes[2];
                    Core_DrawLayer(result, fg, new Rectangle(0, 208, 128, 16), 56, 40);
                }
            }
            Current        = result;
            CurrentPalette = palette;
        }
Esempio n. 37
0
 public bool TryGetPalette(int palletId, out Palette palette)
 {
     return(_palettes.TryGetValue(palletId, out palette));
 }
Esempio n. 38
0
 public DragonPainter(IImageHolder imageHolder, DragonSettings settings, Palette palette)
 {
     this.imageHolder = imageHolder;
     this.settings    = settings;
     this.palette     = palette;
 }
Esempio n. 39
0
 public void InitializeCrossesForAllColors(Palette allColors)
 {
     Parallel.ForEach(allColors, color => GetCross(color.Argb));
 }
Esempio n. 40
0
 public PaletteSettingsAction(Palette palette)
 {
     this.palette = palette;
 }
Esempio n. 41
0
        public CHNKTEX(Stream input)
        {
            Sections = GetSections(input).ToList();

            TXIF = new BinaryReaderX(new MemoryStream(Sections.FirstOrDefault(s => s.Magic == "TXIF").Data)).ReadStruct <TXIF>();
            var txim  = Sections.FirstOrDefault(s => s.Magic == "TXIM");
            var txims = Sections.Where(s => s.Magic == "TXIM").ToList();
            var txpl  = Sections.FirstOrDefault(s => s.Magic == "TXPL");
            var tx4i  = Sections.FirstOrDefault(s => s.Magic == "TX4I");

            IsMultiTXIM = txims.Count > 1;
            HasMap      = tx4i != null;

            int width = TXIF.Width, height = TXIF.Height;
            var paddedWidth = 2 << (int)Math.Log(TXIF.Width - 1, 2);
            var imgCount    = Math.Max((int)TXIF.ImageCount, 1);
            var bitDepth    = 8 * txim.Data.Length / height / paddedWidth / (!IsMultiTXIM ? imgCount : 1);

            BitDepth = (TXIMBitDepth)bitDepth;
            var bmp = new Bitmap(paddedWidth, height);
            var pal = new Palette(txpl.Data, new RGBA(5, 5, 5)).colors;

            // TODO: This check needs to be replaced with something more concrete later
            var isL8 = bitDepth == 8 && txim.Data.Any(b => b > pal.Count());

            if (isL8)
            {
                BitDepth = TXIMBitDepth.L8;
            }

            if (HasMap)
            {
                for (var i = 0; i < paddedWidth * height; i++)
                {
                    // TODO: Finish figuring out TX4I
                    var(x, y, z)    = (i % paddedWidth, i / paddedWidth, 0);
                    var(a, b, c, d) = (i & -(4 * paddedWidth), i & (3 * paddedWidth), i & (paddedWidth - 4), i & 3);
                    var bits  = (txim.Data[a / 4 + b / paddedWidth + c] >> 2 * d) & 3;
                    var entry = BitConverter.ToInt16(tx4i.Data, x / 4 * 2 + y / 4 * (paddedWidth / 2));
                    if (entry < 0 || bits < 3)
                    {
                        z = 2 * (entry & 0x3FFF) + bits;
                    }
                    bmp.SetPixel(x, y, z >= pal.Count() ? Color.Black : pal.ToList()[z]);
                }

                Bitmaps.Add(bmp);
            }
            else
            {
                for (var i = 0; i < imgCount; i++)
                {
                    if (isL8)
                    {
                        // Create L8 palette
                        var list = new List <Color>()
                        {
                            Color.FromArgb(0, 0, 0, 0)
                        };
                        for (int j = 1; j < Math.Pow(2, bitDepth); j++)
                        {
                            list.Add(Color.FromArgb(255, j, j, j));
                        }
                        pal = list;
                    }

                    var settings = new ImageSettings
                    {
                        Width   = width,
                        Height  = height,
                        Format  = new Palette(pal, bitDepth),
                        Swizzle = new Linear(paddedWidth)
                    };
                    Bitmaps.Add(Common.Load(txims[i].Data, settings));
                }
            }
        }
Esempio n. 42
0
        private void btnApply_Click(object sender, EventArgs e)
        {
            bool hasChanges = false;

            for (int i = 0; i < lbBefore.Items.Count; i++)
            {
                if (lbBefore.Items[i] != lbAfter.Items[i])
                {
                    hasChanges = true;
                    break;
                }
            }

            if (!hasChanges) //Quit out if no changes
            {
                this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                return;
            }

            //if the mode is texture, then do something new.
            //if the mode is palette, then generate the palette BEFORE making the image

            if (Mode == SharedMode.Texture)
            {
                //IDEA: AVERAGE ALL THE IMAGES TOGETHER, THEN MAKE A CI PALETTE/TEXTURE FROM THAT. THEN WE HAVE OUR TEXTURE.
                //       AFTER THAT, WE NEED TO ASSIGN PALETTES TO IT. I GUESS WE CAN AVERAGE ALL COLORS THAT HIT EACH POINT
                //       FOR EACH IMAGE

                //Slow process
                Bitmap refImage = new Bitmap(Images[0].Image);

                int width      = Images[0].Image.Width;
                int height     = Images[0].Height;
                int pixelCount = width * height;
                int imageCount = lbAfter.Items.Count;
                int colorCount = Images[0].ImageReference.BasePalettes[0].Colors.Length;

                int[] redCount   = new int[pixelCount];
                int[] blueCount  = new int[pixelCount];
                int[] greenCount = new int[pixelCount];
                int[] alphaCount = new int[pixelCount];

                foreach (BitmapWrapper wrapper in lbAfter.Items)
                {
                    for (int j = 0; j < width; j++)
                    {
                        for (int i = 0; i < height; i++)
                        {
                            Color pixel = wrapper.BMP.GetPixel(i, j);
                            redCount[i + j * wrapper.BMP.Width]   += pixel.R;
                            greenCount[i + j * wrapper.BMP.Width] += pixel.G;
                            blueCount[i + j * wrapper.BMP.Width]  += pixel.B;
                            alphaCount[i + j * wrapper.BMP.Width] += pixel.A;
                        }
                    }
                }

                for (int j = 0; j < height; j++)
                {
                    for (int i = 0; i < width; i++)
                    {
                        refImage.SetPixel(i, j,
                                          Color.FromArgb(alphaCount[i + j * width] / imageCount,
                                                         redCount[i + j * width] / imageCount,
                                                         greenCount[i + j * width] / imageCount,
                                                         blueCount[i + j * width] / imageCount));
                    }
                }

                //Now do the set-texture palette search method
                Palette tempPalette      = new Palette(-1, new byte[colorCount * 2]);
                byte[]  finalTextureData = TextureConversion.ImageToBinary(Images[0].Format, Images[0].PixelSize, refImage, ref tempPalette, true);
                Images[0].ImageReference.Texture.RawData = finalTextureData;

                //Now take this and do some stupid shit
                for (int k = 0; k < imageCount; k++)
                {
                    redCount   = new int[colorCount];
                    greenCount = new int[colorCount];
                    blueCount  = new int[colorCount];
                    alphaCount = new int[colorCount];

                    Bitmap img = (Bitmap)lbAfter.Items[k];

                    for (int j = 0; j < height; j++)
                    {
                        for (int i = 0; i < width; i++)
                        {
                            Color color = img.GetPixel(i, j);

                            int textureNum = 0;
                            if (Images[k].PixelSize == Texture.PixelInfo.Size_8b)
                            {
                                textureNum = finalTextureData[i + j * height];
                            }
                            else
                            {
                                byte val = finalTextureData[(i + j * height) / 2];
                                if ((i + j * height) % 2 == 0)
                                {
                                    textureNum = val >> 4;
                                }
                                else
                                {
                                    textureNum = val & 0xF;
                                }
                            }

                            redCount[textureNum]   += color.R;
                            greenCount[textureNum] += color.G;
                            blueCount[textureNum]  += color.B;
                            alphaCount[textureNum] += color.A;
                        }
                    }

                    //Now that we have the colors added up, we calculate the new colors and that's our new palette!
                    Color[] colors = new Color[colorCount];

                    for (int i = 0; i < colorCount; i++)
                    {
                        colors[i] = Color.FromArgb(alphaCount[i] / imageCount,
                                                   redCount[i] / imageCount,
                                                   greenCount[i] / imageCount,
                                                   blueCount[i] / imageCount);
                    }

                    byte[] newPaletteData = TextureConversion.PaletteToBinary(colors);
                    Images[k].ImageReference.BasePalettes[0].RawData = newPaletteData;
                }
            }
            else
            {
                PaletteMedianCutAnalyzer paletteMaker = new PaletteMedianCutAnalyzer();
                foreach (BitmapWrapper wrapper in lbAfter.Items)
                {
                    for (int i = 0; i < wrapper.BMP.Width; i++)
                    {
                        for (int j = 0; j < wrapper.BMP.Height; j++)
                        {
                            paletteMaker.AddColor(wrapper.BMP.GetPixel(i, j));
                        }
                    }
                }

                Color[] colors         = paletteMaker.GetPalette(Images[0].ImageReference.BasePalettes[0].Colors.Length);
                byte[]  paletteData    = TextureConversion.PaletteToBinary(colors);
                Palette palette        = new Palette(-1, paletteData);
                byte[]  newPaletteData = palette.RawData;
                Images[0].ImageReference.BasePalettes[0].RawData = newPaletteData;

                if (Images[0].PaletteEncoding[0] == MK64Image.MK64ImageEncoding.MIO0)
                {
                    N64DataElement element;
                    if (!RomProject.Instance.Files[0].HasElementExactlyAt(Images[0].PaletteOffset[0], out element))
                    {
                        throw new Exception();
                    }
                    MIO0Block block       = (MIO0Block)element;
                    byte[]    oldMIO0Data = block.DecodedData;

                    Array.Copy(newPaletteData, 0, oldMIO0Data, Images[0].PaletteBlockOffset[0], newPaletteData.Length);

                    byte[] compressedNewMIO0 = MIO0.Encode(oldMIO0Data);

                    block.RawData = compressedNewMIO0;
                }

                //Now generate the images
                for (int i = 0; i < Images.Count; i++)
                {
                    MK64Image image   = Images[i];
                    Bitmap    bmp     = ((BitmapWrapper)lbAfter.Items[i]).BMP;
                    byte[]    newData = TextureConversion.ImageToBinary(image.Format, image.PixelSize, bmp, ref palette, false);

                    if (newData == null || newData.Length == 0)
                    {
                        MessageBox.Show("Error: Couldn't convert image file!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    image.ImageReference.Texture.RawData = newData;
                    image.ImageReference.UpdateImage();

                    if (image.TextureEncoding == MK64Image.MK64ImageEncoding.MIO0)
                    {
                        N64DataElement element;
                        if (!RomProject.Instance.Files[0].HasElementExactlyAt(image.TextureOffset, out element))
                        {
                            throw new Exception();
                        }
                        MIO0Block block = (MIO0Block)element;

                        byte[] MIO0Data = block.DecodedData;

                        Array.Copy(newData, 0, MIO0Data, image.TextureBlockOffset, newData.Length);

                        byte[] compressedNewMIO0 = MIO0.Encode(MIO0Data);

                        block.RawData = compressedNewMIO0;
                    }
                }
            }
        }
Esempio n. 43
0
 public KochPainter(IImageHolder imageHolder, Palette palette)
 {
     this.imageHolder = imageHolder;
     this.palette     = palette;
 }
Esempio n. 44
0
        void Core_LoadTitleScreen_FE8(
            Palette bg_palette, Tileset bg_tileset, TSA_Array bg_tsa,
            Palette mg_palette, Tileset mg_tileset, TSA_Array mg_tsa,
            Palette fg_palette, Tileset fg_tileset)
        {
            GBA.Bitmap result;
            Palette    palette = Palette.Empty(256);

            for (int i = 0; i < bg_palette.Count; i++)
            {
                bg_palette[i] = bg_palette[i].SetAlpha(false);
                palette.Set(GBA.Palette.MAX * 15 + i, bg_palette[i]);
            }
            for (int i = 0; i < mg_palette.Count; i++)
            {
                palette.Set(GBA.Palette.MAX * 14 + i, mg_palette[i]);
            }
            for (int i = 0; i < fg_palette.Count; i++)
            {
                palette.Set(i, fg_palette[i]);
            }
            result        = new GBA.Bitmap(GBA.Screen.WIDTH, GBA.Screen.HEIGHT);
            result.Colors = palette;

            if (BG_CheckBox.Checked)
            {
                TSA_Image bg = new TSA_Image(bg_palette, bg_tileset, bg_tsa);
                for (int y = 0; y < bg.Height; y++)
                {
                    for (int x = 0; x < bg.Width; x++)
                    {
                        if (bg[x, y] != 0)
                        {
                            result[x, y] = GBA.Palette.MAX * 15 + bg[x, y];
                        }
                    }
                }
            }
            if (MG_CheckBox.Checked)
            {
                TSA_Image mg = new TSA_Image(mg_palette, mg_tileset, mg_tsa);
                for (int y = 0; y < mg.Height; y++)
                {
                    for (int x = 0; x < mg.Width; x++)
                    {
                        if (mg[x, y] != 0)
                        {
                            result[x, y] = GBA.Palette.MAX * 14 + mg[x, y];
                        }
                    }
                }
            }
            if (FG_CheckBox.Checked)
            {
                Palette[] palettes = Palette.Split(fg_palette, 8);
                GBA.Image fg;
                if (Core.CurrentROM.Version == GameVersion.JAP)
                {
                    // large 'FIRE EMBLEM' title logo
                    fg = fg_tileset.ToImage(32, 32, palettes[2].ToBytes(false));
                    Core_DrawLayer(result, fg, new Rectangle(0, 48, 240, 48), 0, 44);   // shadow
                    Core_DrawLayer(result, fg, new Rectangle(0, 0, 240, 48), 0, 39);    // logo
                    Core_DrawLayer(result, fg, new Rectangle(240, 0, 16, 16), 216, 39); // TM
                    // small 'FIRE EMBLEM' overhead
                    fg.Colors = palettes[1];
                    Core_DrawLayer(result, fg, new Rectangle(128, 104, 120, 16), 60, 26);
                    // 'THE SACRED STONES' subtitle/scroll thingy
                    fg.Colors = palettes[3];
                    Core_DrawLayer(result, fg, new Rectangle(0, 104, 128, 32), 56, 87);
                    // 'Press START'
                    fg.Colors = palettes[0];
                    Core_DrawLayer(result, fg, new Rectangle(128, 120, 80, 16), 80, 124);
                    // Nintendo & IS copyrights
                    fg.Colors = palettes[1];
                    Core_DrawLayer(result, fg, new Rectangle(0, 96, 240, 8), 16, 148);
                }
                else
                {
                    // large 'FIRE EMBLEM' title logo
                    fg = fg_tileset.ToImage(32, 32, palettes[2].ToBytes(false));
                    Core_DrawLayer(result, fg, new Rectangle(0, 32, 240, 32), 4, 53);   // shadow
                    Core_DrawLayer(result, fg, new Rectangle(0, 0, 240, 32), 4, 48);    // logo
                    Core_DrawLayer(result, fg, new Rectangle(240, 0, 16, 16), 220, 41); // TM
                    // 'THE SACRED STONES' subtitle/scroll thingy
                    fg.Colors = palettes[3];
                    Core_DrawLayer(result, fg, new Rectangle(0, 72, 208, 32), 16, 85);
                    // 'Press START'
                    fg.Colors = palettes[0];
                    Core_DrawLayer(result, fg, new Rectangle(208, 72, 48, 16), 72, 124);
                    Core_DrawLayer(result, fg, new Rectangle(208, 88, 48, 16), 120, 124);
                    // Nintendo & IS copyrights
                    fg.Colors = palettes[1];
                    Core_DrawLayer(result, fg, new Rectangle(0, 64, 240, 8), 4, 148);
                }
            }
            Current        = result;
            CurrentPalette = palette;
        }
Esempio n. 45
0
 public KochPainter(IImageHolder imageHolder, Palette palette)
 {
     this.imageHolder = imageHolder;
     this.palette     = palette;
     imageSize        = imageHolder.GetImageSize();
 }
 public IsWinningOrangeRule_Should()
 {
     _activePlayerPalette = new Palette(1);
     _opponentPalettes    = new List <Palette>();
 }
Esempio n. 47
0
        public static ResourceTemplate RenderResourceType(ResourceTypeInfo info, string[] exts, Palette p)
        {
            var image = info.SpriteNames[0];

            using (var s = FileSystem.OpenWithExts(image, exts))
            {
                var shp   = new ShpReader(s);
                var frame = shp[shp.ImageCount - 1];

                var bitmap = new Bitmap(shp.Width, shp.Height, PixelFormat.Format8bppIndexed);
                bitmap.Palette = p.AsSystemPalette();
                var data = bitmap.LockBits(bitmap.Bounds(),
                                           ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

                unsafe
                {
                    byte *q      = (byte *)data.Scan0.ToPointer();
                    var   stride = data.Stride;

                    for (var i = 0; i < shp.Width; i++)
                    {
                        for (var j = 0; j < shp.Height; j++)
                        {
                            q[j * stride + i] = frame.Image[i + shp.Width * j];
                        }
                    }
                }

                bitmap.UnlockBits(data);
                return(new ResourceTemplate {
                    Bitmap = bitmap, Info = info, Value = shp.ImageCount - 1
                });
            }
        }
Esempio n. 48
0
 private void UpdatePalette(Palette palette = null)
 {
     Render();
     bblBattleBackgrounds.Datas = bblBattleBackgrounds.Datas;
 }
    int ReadUW2PageFileData(char[] assocFile, int AuxPalNo, string fileCrit, CritterAnimInfo critanim, int spriteIndex, Palette paletteToUse)
    {
        //Debug.Log(fileCrit + " starting at  "  + spriteIndex);
        Palette pal = paletteToUse;

        char[] critterFile;
        //char[] auxpalval=new char[32];
        //Palette[] auxpal = new Palette[32];
        //int auxPalNo = PaletteNo;
        int AddressPointer;


        //pal = new palette[256];
        //getPalette(PaletteFile, pal, 0);//always palette 0?

        DataLoader.ReadStreamFile(fileCrit, out critterFile);


        //UW2 uses a different method
        //Starting at offset 0x80
        //fprintf(LOGFILE, "\n\t//%s - palette = %d", fileCrit, auxPalNo);
        //auxPalNo=2;
        AddressPointer = 0;                        //auxPalNo * 32;

        char[] auxPalVal = new char[32];
        for (int j = 0; j < 32; j++)
        {
            auxPalVal[j] = (char)DataLoader.getValAtAddress(critterFile, (AddressPointer) + (AuxPalNo * 32) + j, 8);
        }

        //int i = 0;
        int MaxWidth    = 0;
        int MaxHeight   = 0;
        int MaxHotSpotX = 0;
        int MaxHotSpotY = 0;

        for (int pass = 0; pass <= 1; pass++)
        {
            if (pass == 0)
            {                                    //First pass is getting max image sizes
                for (int index = 128; index < 640; index = index + 2)
                {
                    int frameOffset = (int)DataLoader.getValAtAddress(critterFile, index, 16);
                    if (frameOffset != 0)
                    {
                        int BitMapWidth  = (int)DataLoader.getValAtAddress(critterFile, frameOffset + 0, 8);
                        int BitMapHeight = (int)DataLoader.getValAtAddress(critterFile, frameOffset + 1, 8);
                        int hotspotx     = (int)DataLoader.getValAtAddress(critterFile, frameOffset + 2, 8);
                        int hotspoty     = (int)DataLoader.getValAtAddress(critterFile, frameOffset + 3, 8);
                        if (hotspotx > BitMapWidth)
                        {
                            hotspotx = BitMapWidth;
                        }
                        if (hotspoty > BitMapHeight)
                        {
                            hotspoty = BitMapHeight;
                        }
                        if (BitMapWidth > MaxWidth)
                        {
                            MaxWidth = BitMapWidth;
                        }
                        if (BitMapHeight > MaxHeight)
                        {
                            MaxHeight = BitMapHeight;
                        }
                        if (hotspotx > MaxHotSpotX)
                        {
                            MaxHotSpotX = hotspotx;
                        }
                        if (hotspoty > MaxHotSpotY)
                        {
                            MaxHotSpotY = hotspoty;
                        }
                    }                            //End frameoffsetr first pass
                }                                //End for loop first pass
            }                                    //End first pass
            else
            {                                    //Extract images
                if (MaxHotSpotX * 2 > MaxWidth)
                {                                //Try and center the hot spot in the image.
                    MaxWidth = MaxHotSpotX * 2;
                }
                char[] outputImg;
                outputImg = new char[MaxWidth * MaxHeight * 2];
                for (int index = 128; index < 640; index = index + 2)
                {
                    int frameOffset = (int)DataLoader.getValAtAddress(critterFile, index, 16);
                    if (frameOffset != 0)
                    {
                        int BitMapWidth  = (int)DataLoader.getValAtAddress(critterFile, frameOffset + 0, 8);
                        int BitMapHeight = (int)DataLoader.getValAtAddress(critterFile, frameOffset + 1, 8);
                        int hotspotx     = (int)DataLoader.getValAtAddress(critterFile, frameOffset + 2, 8);
                        int hotspoty     = (int)DataLoader.getValAtAddress(critterFile, frameOffset + 3, 8);
                        int compression  = (int)DataLoader.getValAtAddress(critterFile, frameOffset + 4, 8);
                        int datalen      = (int)DataLoader.getValAtAddress(critterFile, frameOffset + 5, 16);
                        //Adjust the hotspots from the biggest point back to the image corners
                        int cornerX; int cornerY;
                        cornerX = MaxHotSpotX - hotspotx;
                        cornerY = MaxHotSpotY - hotspoty;
                        if (cornerX <= 0)
                        {
                            cornerX = 0;
                        }
                        else
                        {
                            cornerX = cornerX - 1;
                        }
                        if (cornerY <= 0)
                        {
                            cornerY = 0;
                        }

                        if (true)
                        {
                            //Merge the image into a new big image at the hotspot coordinates.;
                            char[] srcImg;

                            srcImg = new char[BitMapWidth * BitMapHeight * 2];
                            ArtLoader.ua_image_decode_rle(critterFile, srcImg, compression == 6 ? 5 : 4, datalen, BitMapWidth * BitMapHeight, frameOffset + 7, auxPalVal);
                            cornerY = MaxHeight - cornerY;                                                                                    //y is from the top left corner

                            int  ColCounter = 0; int RowCounter = 0;
                            bool ImgStarted = false;
                            for (int y = 0; y < MaxHeight; y++)
                            {
                                for (int x = 0; x < MaxWidth; x++)
                                {
                                    if ((cornerX + ColCounter == x) && (MaxHeight - cornerY + RowCounter == y) && (ColCounter < BitMapWidth) && (RowCounter < BitMapHeight))
                                    {                                                                                                            //the pixel from the source image is here
                                        ImgStarted = true;
                                        outputImg[x + (y * MaxWidth)] = srcImg[ColCounter + (RowCounter * BitMapWidth)];
                                        ColCounter++;
                                    }
                                    else
                                    {
                                        outputImg[x + (y * MaxWidth)] = (char)0;                                                                                                                      //alpha
                                    }
                                }
                                if (ImgStarted == true)
                                {                                                                                                //New Row on the src image
                                    RowCounter++;
                                    ColCounter = 0;
                                }
                            }
                            //Set the heights for output
                            BitMapWidth  = MaxWidth;
                            BitMapHeight = MaxHeight;

                            //Debug.Log(fileCrit + " "  + spriteIndex);

                            Texture2D imgData = ArtLoader.Image(outputImg, 0, BitMapWidth, BitMapHeight, "namehere", pal, true);
                            AnimInfo.animSprites[spriteIndex++] = Sprite.Create(imgData, new Rect(0f, 0f, BitMapWidth, BitMapHeight), new Vector2(0.5f, 0.0f));
                        }
                    }                            //end extrac frameoffset
                }                                //End for loop extract
            }                                    //End extract images
        }
        //Debug.Log(fileCrit + " returning  "  + spriteIndex);
        return(spriteIndex);
    }
Esempio n. 50
0
        void Core_InsertImage(string filepath)
        {
            IDisplayable image;

            try
            {
                Palette palette = Core.FindPaletteFile(filepath);

                if (TSA_Label.Checked && TSA_PointerBox.Value != new Pointer())
                {
                    int width = TSA_FlipRows_CheckBox.Checked ?
                                ((TSA_Image)Image_ImageBox.Display).Tiling.Width :
                                (int)Width_NumBox.Value;
                    int height = TSA_FlipRows_CheckBox.Checked ?
                                 ((TSA_Image)Image_ImageBox.Display).Tiling.Height :
                                 (int)Height_NumBox.Value;

                    if (palette == null)
                    {
                        image = new TSA_Image(
                            width, height,
                            new GBA.Bitmap(filepath),
                            Palette.MAX,
                            true);
                    }
                    else
                    {
                        image = new TSA_Image(
                            width, height,
                            new GBA.Bitmap(filepath),
                            palette,
                            Palette.MAX,
                            true);
                    }
                }
                else if (Tileset_8bpp_RadioButton.Checked)
                {
                    image = new GBA.Bitmap(filepath, palette);
                }
                else
                {
                    image = new GBA.Image(filepath, palette);
                }
            }
            catch (Exception ex)
            {
                Program.ShowError("Could not load image file.", ex);
                Core_Update();
                return;
            }

            if (image is GBA.TSA_Image)
            {
                Core_Insert(
                    Palette.Merge(((TSA_Image)image).Palettes),
                    ((TSA_Image)image).Graphics.ToBytes(false),
                    ((TSA_Image)image).Tiling);
                return;
            }
            if (image is GBA.Bitmap)
            {
                Core_Insert(
                    ((Bitmap)image).Colors,
                    ((Bitmap)image).ToBytes());
                return;
            }
            if (image is GBA.Image)
            {
                Core_Insert(
                    ((Image)image).Colors,
                    new Tileset((Image)image).ToBytes(false));
                return;
            }
            Program.ShowError("Image couldn't be inserted because of an internal error.");
        }
Esempio n. 51
0
        public string ProcessFigure(string figure, string gender, ICollection <ClothingParts> clothingParts, bool hasHabboClub)
        {
            figure = figure.ToLower();
            gender = gender.ToUpper();

            string rebuildFigure = string.Empty;

            #region Check clothing, colors & Habbo Club
            string[] figureParts = figure.Split('.');
            foreach (string part in figureParts.ToList())
            {
                string type = part.Split('-')[0];

                if (_setTypes.TryGetValue(type, out FigureSet figureSet))
                {
                    int partId        = Convert.ToInt32(part.Split('-')[1]);
                    int colorId       = 0;
                    int secondColorId = 0;

                    if (figureSet.Sets.TryGetValue(partId, out Set set))
                    {
                        #region Gender Check
                        if (set.Gender != gender && set.Gender != "U")
                        {
                            if (figureSet.Sets.Count(x => x.Value.Gender == gender || x.Value.Gender == "U") > 0)
                            {
                                partId = figureSet.Sets.FirstOrDefault(x => x.Value.Gender == gender || x.Value.Gender == "U").Value.Id;

                                //Fetch the new set.
                                figureSet.Sets.TryGetValue(partId, out set);

                                colorId = GetRandomColor(figureSet.PalletId);
                            }
                        }
                        #endregion

                        #region Colors
                        if (set.Colorable)
                        {
                            //Couldn't think of a better way to split the colors, if I looped the parts I still have to remove Type-PartId, then loop color 1 & color 2. Meh

                            int splitterCounter = part.Count(x => x == '-');
                            if (splitterCounter == 2 || splitterCounter == 3)
                            {
                                #region First Color
                                if (!string.IsNullOrEmpty(part.Split('-')[2]))
                                {
                                    if (int.TryParse(part.Split('-')[2], out colorId))
                                    {
                                        colorId = Convert.ToInt32(part.Split('-')[2]);

                                        Palette palette = GetPalette(colorId);
                                        if (palette != null && colorId != 0)
                                        {
                                            if (figureSet.PalletId != palette.Id)
                                            {
                                                colorId = GetRandomColor(figureSet.PalletId);
                                            }
                                        }
                                        else if (palette == null && colorId != 0)
                                        {
                                            colorId = GetRandomColor(figureSet.PalletId);
                                        }
                                    }
                                    else
                                    {
                                        colorId = 0;
                                    }
                                }
                                else
                                {
                                    colorId = 0;
                                }
                                #endregion
                            }

                            if (splitterCounter == 3)
                            {
                                #region Second Color
                                if (!string.IsNullOrEmpty(part.Split('-')[3]))
                                {
                                    if (int.TryParse(part.Split('-')[3], out secondColorId))
                                    {
                                        secondColorId = Convert.ToInt32(part.Split('-')[3]);

                                        Palette palette = GetPalette(secondColorId);
                                        if (palette != null && secondColorId != 0)
                                        {
                                            if (figureSet.PalletId != palette.Id)
                                            {
                                                secondColorId = GetRandomColor(figureSet.PalletId);
                                            }
                                        }
                                        else if (palette == null && secondColorId != 0)
                                        {
                                            secondColorId = GetRandomColor(figureSet.PalletId);
                                        }
                                    }
                                    else
                                    {
                                        secondColorId = 0;
                                    }
                                }
                                else
                                {
                                    secondColorId = 0;
                                }
                                #endregion
                            }
                        }
                        else
                        {
                            string[] ignore = new string[] { "ca", "wa" };

                            if (ignore.Contains(type))
                            {
                                if (!string.IsNullOrEmpty(part.Split('-')[2]))
                                {
                                    colorId = Convert.ToInt32(part.Split('-')[2]);
                                }
                            }
                        }
                        #endregion

                        if (set.ClubLevel > 0 && !hasHabboClub)
                        {
                            partId = figureSet.Sets.FirstOrDefault(x => x.Value.Gender == gender || x.Value.Gender == "U" && x.Value.ClubLevel == 0).Value.Id;

                            figureSet.Sets.TryGetValue(partId, out set);

                            colorId = GetRandomColor(figureSet.PalletId);
                        }

                        if (secondColorId == 0)
                        {
                            rebuildFigure = rebuildFigure + type + "-" + partId + "-" + colorId + ".";
                        }
                        else
                        {
                            rebuildFigure = rebuildFigure + type + "-" + partId + "-" + colorId + "-" + secondColorId + ".";
                        }
                    }
                }
            }
            #endregion

            #region Check Required Clothing
            foreach (string requirement in _requirements)
            {
                if (!rebuildFigure.Contains(requirement))
                {
                    if (requirement == "ch" && gender == "M")
                    {
                        continue;
                    }

                    if (_setTypes.TryGetValue(requirement, out FigureSet figureSet))
                    {
                        Set set = figureSet.Sets.FirstOrDefault(x => x.Value.Gender == gender || x.Value.Gender == "U").Value;
                        if (set != null)
                        {
                            int partId  = figureSet.Sets.FirstOrDefault(x => x.Value.Gender == gender || x.Value.Gender == "U").Value.Id;
                            int colorId = GetRandomColor(figureSet.PalletId);

                            rebuildFigure = rebuildFigure + requirement + "-" + partId + "-" + colorId + ".";
                        }
                    }
                }
            }
            #endregion

            #region Check Purcashable Clothing
            if (clothingParts != null)
            {
                ICollection <ClothingItem> purchasableParts = PlusEnvironment.GetGame().GetCatalog().GetClothingManager().GetClothingAllParts;

                figureParts = rebuildFigure.TrimEnd('.').Split('.');
                foreach (string part in figureParts.ToList())
                {
                    int partId = Convert.ToInt32(part.Split('-')[1]);
                    if (purchasableParts.Count(x => x.PartIds.Contains(partId)) > 0)
                    {
                        if (clothingParts.Count(x => x.PartId == partId) == 0)
                        {
                            string type = part.Split('-')[0];

                            if (_setTypes.TryGetValue(type, out FigureSet figureSet))
                            {
                                Set set = figureSet.Sets.FirstOrDefault(x => x.Value.Gender == gender || x.Value.Gender == "U").Value;
                                if (set != null)
                                {
                                    partId = figureSet.Sets.FirstOrDefault(x => x.Value.Gender == gender || x.Value.Gender == "U").Value.Id;
                                    int colorId = GetRandomColor(figureSet.PalletId);

                                    rebuildFigure = rebuildFigure + type + "-" + partId + "-" + colorId + ".";
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            return(rebuildFigure);
        }
Esempio n. 52
0
    /// <summary>
    /// Loads the image at index.
    /// </summary>
    /// <returns>The <see cref="UnityEngine.Texture2D"/>.</returns>
    /// <param name="index">Index.</param>
    /// <param name="palToUse">Pal to use.</param>
    /// If the index is greater than 209 I return a floor texture.
    public Texture2D LoadImageAt(int index, Palette palToUse)
    {
        if (_RES == GAME_UWDEMO)
        {        //Point the UW1 texture files to the demo files
            TextureSplit = 48;
            pathTexW_UW1 = pathTexW_UW0;
            pathTexF_UW1 = pathTexF_UW0;
        }
        if (_RES == GAME_UW2)
        {
            FloorDim = 64;
        }

        switch (_RES)
        {
        case GAME_SHOCK:
        {
            if (texturesFLoaded == false)
            {
                if (!DataLoader.ReadStreamFile(BasePath + pathTex_SS1, out texturebufferT))
                {
                    return(base.LoadImageAt(index));
                }
                else
                {
                    texturesFLoaded = true;
                }
            }
            //Load the chunk requested
            //For textures this is index + 1000
            DataLoader.Chunk art_ark;
            if (DataLoader.LoadChunk(texturebufferT, index + 1000, out art_ark))
            {
                switch (art_ark.chunkContentType)
                {
                case 2:
                case 17:
                {
                    long textureOffset   = (int)DataLoader.getValAtAddress(art_ark.data, 2 + (0 * 4), 32);
                    int  CompressionType = (int)DataLoader.getValAtAddress(art_ark.data, textureOffset + 4, 16);
                    int  Width           = (int)DataLoader.getValAtAddress(art_ark.data, textureOffset + 8, 16);
                    int  Height          = (int)DataLoader.getValAtAddress(art_ark.data, textureOffset + 10, 16);
                    if ((Width > 0) && (Height > 0))
                    {
                        if (CompressionType == 4)
                        {                                                        //compressed
                            char[] outputImg;
                            //  UncompressBitmap(art_ark+textureOffset+BitMapHeaderSize, outputImg,Height*Width);
                            UncompressBitmap(art_ark.data, textureOffset + BitMapHeaderSize, out outputImg, Height * Width);
                            return(Image(outputImg, 0, Width, Height, "namehere", palToUse, true));
                        }
                        else
                        {                                                        //Uncompressed
                            return(Image(art_ark.data, textureOffset + BitMapHeaderSize, Width, Height, "namehere", palToUse, true));
                        }
                    }
                    else
                    {
                        return(base.LoadImageAt(index));
                    }
                }
                    //break;
                }
            }

            return(base.LoadImageAt(index));
        }

        case GAME_UW2:
        {
            if (LoadMod)
            {
                if (File.Exists(ModPathW + sep + index.ToString("d3") + ".tga"))
                {
                    return(TGALoader.LoadTGA(ModPathW + sep + index.ToString("d3") + ".tga"));
                }
            }
            if (texturesFLoaded == false)
            {
                if (!DataLoader.ReadStreamFile(BasePath + pathTex_UW2, out texturebufferT))
                {
                    return(base.LoadImageAt(index));
                }
                else
                {
                    texturesFLoaded = true;
                }
            }
            long textureOffset = DataLoader.getValAtAddress(texturebufferT, ((index) * 4) + 4, 32);
            return(Image(texturebufferT, textureOffset, FloorDim, FloorDim, "name_goes_here", palToUse, false));
        }


        case GAME_UWDEMO:
        case GAME_UW1:
        default:
        {
            if (index < TextureSplit)
            {                    //Wall textures
                if (texturesWLoaded == false)
                {
                    if (!DataLoader.ReadStreamFile(BasePath + pathTexW_UW1, out texturebufferW))
                    {
                        return(base.LoadImageAt(index));
                    }
                    else
                    {
                        texturesWLoaded = true;
                    }
                }
                if (LoadMod)
                {
                    if (File.Exists(ModPathW + sep + index.ToString("d3") + ".tga"))
                    {
                        return(TGALoader.LoadTGA(ModPathW + sep + index.ToString("d3") + ".tga"));
                    }
                }
                long textureOffset = DataLoader.getValAtAddress(texturebufferW, (index * 4) + 4, 32);
                return(Image(texturebufferW, textureOffset, 64, 64, "name_goes_here", palToUse, false));
            }
            else
            {                    //Floor textures (to match my list of textures)
                if (texturesFLoaded == false)
                {
                    if (!DataLoader.ReadStreamFile(BasePath + pathTexF_UW1, out texturebufferF))
                    {
                        return(base.LoadImageAt(index));
                    }
                    else
                    {
                        texturesFLoaded = true;
                    }
                }
                if (LoadMod)
                {
                    if (File.Exists(ModPathF + sep + index.ToString("d3") + ".tga"))
                    {
                        return(TGALoader.LoadTGA(ModPathF + sep + index.ToString("d3") + ".tga"));
                    }
                }
                long textureOffset = DataLoader.getValAtAddress(texturebufferF, ((index - TextureSplit) * 4) + 4, 32);
                return(Image(texturebufferF, textureOffset, FloorDim, FloorDim, "name_goes_here", palToUse, false));
            }
        }                //end switch
        }
    }
Esempio n. 53
0
        public ConverterForm()
        {
            InitializeComponent();

            Bitmap bitmap = (Bitmap)Bitmap.FromFile("Letters.png");

            Color previousColor = Color.Black;
            int   previousCount = 0;

            for (int i = 0; i < 33; i++)
            {
                Color color = (i != 32 ? bitmap.GetPixel(0, i * 12) : Color.Black);
                if (color.R == previousColor.R && color.G == previousColor.G && color.B == previousColor.B)
                {
                    previousCount++;
                }
                else if (i != 0)
                {
                    int     index   = 0;
                    Palette palette = Palette.DefaultPalette;
                    for (int j = 0; j < palette.NumColors; j++)
                    {
                        if (palette.Colors[j] == previousColor)
                        {
                            index = j;
                            break;
                        }
                    }
                    Console.WriteLine((previousCount != 0 ? ((i - previousCount - 1) + "-") : "") + (i - 1) + ":\t" + previousColor.R + ", " + previousColor.G + ", " + previousColor.B + " (" + index + ")");
                    previousCount = 0;
                }
                previousColor = color;
            }

            Color[] colors = new Color[] {
                Color.FromArgb(131, 151, 151),
                Color.FromArgb(239, 243, 243),
                Color.FromArgb(239, 243, 243),
                Color.FromArgb(119, 119, 175),
                Color.FromArgb(239, 239, 255),
                Color.FromArgb(243, 235, 255),
                Color.FromArgb(67, 135, 227),
                Color.FromArgb(215, 247, 255),
                Color.FromArgb(215, 247, 255),
                Color.FromArgb(207, 255, 255),
                Color.FromArgb(207, 255, 255),
                Color.FromArgb(71, 175, 39),
                Color.FromArgb(207, 243, 223),
                Color.FromArgb(183, 219, 103),
                Color.FromArgb(195, 255, 179),
                Color.FromArgb(223, 247, 191),
                Color.FromArgb(223, 227, 163),
                Color.FromArgb(255, 255, 195),
                Color.FromArgb(255, 255, 195),
                Color.FromArgb(243, 203, 27),
                Color.FromArgb(255, 219, 163),
                Color.FromArgb(255, 111, 23),
                Color.FromArgb(247, 239, 195),
                Color.FromArgb(203, 175, 111),
                Color.FromArgb(231, 219, 195),
                Color.FromArgb(255, 227, 195),
                Color.FromArgb(255, 191, 191),
                Color.FromArgb(227, 7, 0),
                Color.FromArgb(255, 219, 215),
                Color.FromArgb(219, 59, 143),
                Color.FromArgb(255, 215, 239),
                Color.FromArgb(255, 219, 215)
            };

            for (int i = 0; i < 32; i++)
            {
                CustomControls.RCTLabel label2 = new CustomControls.RCTLabel();
                label2.FontType     = CustomControls.Visuals.FontType.Bold;
                label2.ForeColor    = colors[i];
                label2.Location     = new System.Drawing.Point(164, 26 + i * 14);
                label2.Name         = "rctColorLabel" + i;
                label2.OutlineColor = System.Drawing.Color.FromArgb(23, 35, 35);
                label2.Size         = new System.Drawing.Size(140, 14);
                label2.TabIndex     = 22;
                label2.Text         = ((RemapColors)i).ToString();
                label2.TextAlign    = System.Drawing.ContentAlignment.TopLeft;
                this.Controls.Add(label2);

                CustomControls.RCTLabel label = new CustomControls.RCTLabel();
                label.ForeColor = Color.FromArgb(23, 35, 35);
                label.Location  = new System.Drawing.Point(140, 26 + i * 14);
                label.Name      = "rctColorIndexLabel" + i;
                label.Size      = new System.Drawing.Size(24, 14);
                label.TabIndex  = 22;
                label.FontType  = CustomControls.Visuals.FontType.Regular;
                label.Text      = "(" + i + ")";
                label.TextAlign = System.Drawing.ContentAlignment.TopLeft;
                this.Controls.Add(label);
            }

            //WritePalette("palette_water.pal", PaletteWithWater);
            //WritePalette("palette_no_water.pal", PaletteNoWater);
            image = new Bitmap(300, 400);
            Graphics g = Graphics.FromImage(image);

            for (int i = 0; i < PaletteWithWater.Length; i++)
            {
                int   size  = 10;
                int   x     = (i % 12) * size;
                int   y     = (i / 12) * size;
                Brush brush = new SolidBrush(PaletteWithWater[i]);
                g.FillRectangle(brush, new Rectangle(x, y, size, size));
                brush.Dispose();
            }
            g.Dispose();
            this.pictureBox1.Image = image;
        }
Esempio n. 54
0
        public const int ChunkSize = 8;                 // 8x8 chunks ==> 192x192 bitmaps.

        Bitmap RenderChunk(int u, int v)
        {
            var bitmap = new Bitmap(ChunkSize * TileSet.TileSize, ChunkSize * TileSet.TileSize);

            var data = bitmap.LockBits(bitmap.Bounds(),
                                       ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            unsafe
            {
                int *p      = (int *)data.Scan0.ToPointer();
                var  stride = data.Stride >> 2;

                for (var i = 0; i < ChunkSize; i++)
                {
                    for (var j = 0; j < ChunkSize; j++)
                    {
                        var tr       = Map.MapTiles.Value[u * ChunkSize + i, v *ChunkSize + j];
                        var tile     = TileSet.Templates[tr.type].Data;
                        var index    = (tr.index < tile.TileBitmapBytes.Count) ? tr.index : (byte)0;
                        var rawImage = tile.TileBitmapBytes[index];
                        for (var x = 0; x < TileSet.TileSize; x++)
                        {
                            for (var y = 0; y < TileSet.TileSize; y++)
                            {
                                p[(j * TileSet.TileSize + y) * stride + i * TileSet.TileSize + x] = Palette.GetColor(rawImage[x + TileSet.TileSize * y]).ToArgb();
                            }
                        }

                        if (Map.MapResources.Value[u * ChunkSize + i, v *ChunkSize + j].type != 0)
                        {
                            var resourceImage = ResourceTemplates[Map.MapResources.Value[u * ChunkSize + i, v *ChunkSize + j].type].Bitmap;
                            var srcdata       = resourceImage.LockBits(resourceImage.Bounds(),
                                                                       ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

                            int *q         = (int *)srcdata.Scan0.ToPointer();
                            var  srcstride = srcdata.Stride >> 2;

                            for (var x = 0; x < TileSet.TileSize; x++)
                            {
                                for (var y = 0; y < TileSet.TileSize; y++)
                                {
                                    var c = q[y * srcstride + x];
                                    if ((c & 0xff000000) != 0)                                          /* quick & dirty, i cbf doing real alpha */
                                    {
                                        p[(j * TileSet.TileSize + y) * stride + i * TileSet.TileSize + x] = c;
                                    }
                                }
                            }

                            resourceImage.UnlockBits(srcdata);
                        }
                    }
                }
            }

            bitmap.UnlockBits(data);

            if (ShowGrid)
            {
                using (var g = SGraphics.FromImage(bitmap))
                {
                    var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                    ControlPaint.DrawGrid(g, rect, new Size(2, Game.CellSize), Color.DarkRed);
                    ControlPaint.DrawGrid(g, rect, new Size(Game.CellSize, 2), Color.DarkRed);
                    ControlPaint.DrawGrid(g, rect, new Size(Game.CellSize, Game.CellSize), Color.Red);
                }
            }

            return(bitmap);
        }
Esempio n. 55
0
 public KochFractalAction(IImageHolder imageHolder, Palette palette)
 {
     this.imageHolder = imageHolder;
     this.palette     = palette;
 }
Esempio n. 56
0
 public BindingList <Event> addEventMP(ulong id, Palette palette)
 {
     data.Events[data.Events.IndexOf(data.Events.First(o => o.Id == id))].MPalette.Add(new Event.MyPalette(palette, 0, 0));
     return(getData().Events);
 }
Esempio n. 57
0
        /// <summary>
        /// Initializes DirectDraw and all the surfaces to be used.
        /// </summary>
        private void InitializeDirectDraw()
        {
            SurfaceDescription description  = new SurfaceDescription(); // Describes a surface.
            Random             randomNumber = new Random();             // Random number for position and velocity.
            ColorKeyFlags      flags        = new ColorKeyFlags();

            displayDevice = new Device();                                                       // Create a new DirectDrawDevice.
            displayDevice.SetCooperativeLevel(this, CooperativeLevelFlags.FullscreenExclusive); // Set the cooperative level.

            try
            {
                displayDevice.SetDisplayMode(screenWidth, screenHeight, 8, 0, false); // Set the display mode width and height, and 8 bit color depth.
            }
            catch (UnsupportedException)
            {
                MessageBox.Show("Device doesn't support required mode. Sample will now exit.", "UnsupportedException caught");
                Close();
                return;
            }

            description.SurfaceCaps.PrimarySurface = description.SurfaceCaps.Flip = description.SurfaceCaps.Complex = true;
            description.BackBufferCount            = 1;      // Create 1 backbuffer.

            front = new Surface(description, displayDevice); // Create the surface using the description above.

            SurfaceCaps caps = new SurfaceCaps();

            caps.BackBuffer = true;                                                // Caps of the surface.
            back            = front.GetAttachedSurface(caps);                      // Get the attached surface that matches the caps, which will be the backbuffer.

            pal           = new Palette(displayDevice, bitmapFileName);            // Create a new palette, using the bitmap file.
            pe            = pal.GetEntries(0, 256);                                // Store the palette entries.
            front.Palette = pal;                                                   // The front surface will use this palette.

            description.Clear();                                                   // Clear the data out from the SurfaceDescription class.
            surfaceLogo = new Surface(bitmapFileName, description, displayDevice); // Create the sprite bitmap surface.

            ColorKey key = new ColorKey();                                         // Create a new colorkey.

            key.ColorSpaceHighValue = key.ColorSpaceLowValue = 0;
            flags = ColorKeyFlags.SourceDraw;
            surfaceLogo.SetColorKey(flags, key); // Set the colorkey to the bitmap surface. 144 is the index used for the colorkey, which is black in this palette.

            description.Clear();
            description.SurfaceCaps.OffScreenPlain = true;
            description.Width  = 200; // Set the width and height of the surface.
            description.Height = 20;

            text           = new Surface(description, displayDevice); // Create the surface using the above description.
            text.ForeColor = Color.FromArgb(indexWhite);              // Because this is a palettized environment, the app needs to use index based colors, which
                                                                      // do not correspond to pre-defined color values. For this reason, the indexWhite variable exists
                                                                      // and contains the index where the color white is stored in the bitmap's palette. The app makes use
                                                                      // of the static FromArgb() method to convert the index to a Color value.
            text.ColorFill(indexBlack);
            text.DrawText(0, 0, textHelp, false);

            for (int i = 0; i < numSprites; i++)
            {
                // Set the sprite's position and velocity
                sprite[i].posX = (randomNumber.Next() % screenWidth);
                sprite[i].posY = (randomNumber.Next() % screenHeight);

                sprite[i].velX = 500.0f * randomNumber.Next() / Int32.MaxValue - 250.0f;
                sprite[i].velY = 500.0f * randomNumber.Next() / Int32.MaxValue - 250.0f;
            }
        }
Esempio n. 58
0
        public async Task Run()
        {
            if (options.Canvas == CanvasType.Moon)
            {
                throw new Exception("Moon canvas is not designed for bots");
            }

            if (options.SessionName != null)
            {
                logger.LogTechState("Loading session...");
                SessionManager sessionManager = new SessionManager(proxySettings);
                session = sessionManager.GetSession(options.SessionName);
                logger.LogTechInfo("Session loaded");
            }

            logger.LogTechState("Connecting to API...");
            PixelPlanetHttpApi api = new PixelPlanetHttpApi
            {
                ProxySettings = proxySettings,
                Session       = session
            };
            UserModel user = await api.GetMeAsync(finishToken);

            logger.LogTechInfo("Successfully connected");
            if (options.SessionName != null)
            {
                if (user.Name != null)
                {
                    logger.LogTechInfo($"Session is alive; user \"{user.Name}\"");
                }
                else
                {
                    throw new SessionExpiredException();
                }
            }

            canvas = user.Canvases[options.Canvas];

            LoggerExtensions.MaxCoordXYLength = 1 + (int)Math.Log10(canvas.Size / 2);
            ValidateCanvas();

            palette           = new Palette(canvas.Colors, canvas.Is3D);
            colorNameResolver = new ColorNameResolver(options.Canvas);

            await LoadImage();

            logger.LogTechState("Calculating pixel placing order...");
            CalculateOrder();
            logger.LogTechInfo("Pixel placing order is calculated");

            InitCache();

            mapUpdatedResetEvent = new ManualResetEvent(false);
            cache.OnMapUpdated  += (o, e) =>
            {
                logger.LogDebug("cache.OnMapUpdated event fired");
                mapUpdatedResetEvent.Set();
            };
            if (options.DefenseMode)
            {
                gotGriefed             = new AutoResetEvent(false);
                cache.OnMapUpdated    += (o, e) => gotGriefed.Set();
                waitingGriefLockObject = new object();
            }
            Thread statsThread = new Thread(StatsCollectionThreadBody);

            statsThread.Start();
            do
            {
                try
                {
                    using (WebsocketWrapper wrapper = new WebsocketWrapper(logger, false, proxySettings, session, options.Canvas))
                    {
                        wrapper.OnConnectionLost += (o, e) => mapUpdatedResetEvent.Reset();
                        cache.Wrapper             = wrapper;
                        cache.DownloadChunks();
                        wrapper.OnMapChanged += LogMapChanged;
                        ClearPlaced();
                        bool wasChanged;
                        do
                        {
                            repeatingFails = false;
                            wasChanged     = await PerformBuildingCycle(wrapper);

                            if (!wasChanged && options.DefenseMode)
                            {
                                logger.Log("Image is intact, waiting...", MessageGroup.Info);
                                lock (waitingGriefLockObject)
                                {
                                    logger.LogDebug("Run(): acquiring grief waiting lock");
                                    gotGriefed.Reset();
                                    gotGriefed.WaitOne();
                                }
                                logger.LogDebug("Run(): got griefed");
                                await Task.Delay(ThreadSafeRandom.Next(500, 3000), finishToken);
                            }
                        } while (options.DefenseMode || wasChanged);
                        logger.Log("Building is finished", MessageGroup.Info);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    logger.LogError($"Unhandled exception: {ex.GetBaseException().Message}");
                    logger.LogDebug(ex.ToString());
                    int delay = repeatingFails ? 30 : 10;
                    repeatingFails = true;
                    logger.LogTechState($"Reconnecting in {delay} seconds...");
                    Thread.Sleep(TimeSpan.FromSeconds(delay));
                    continue;
                }
            } while (true);
        }
Esempio n. 59
0
        void Core_LoadTitleScreen_FE6(
            Palette mg_palette, Tileset mg_tileset,
            Tileset fg_tileset, TSA_Array mg_tsa,
            Palette bg_palette, Tileset bg_tileset)
        {
            GBA.Bitmap result;
            Palette    palette = Palette.Empty(256);

            for (int i = 0; i < mg_palette.Count; i++)
            {
                palette.Set(i, mg_palette[i]);
            }
            for (int i = 0; i < bg_palette.Count; i++)
            {
                bg_palette[i] = bg_palette[i].SetAlpha(false);
                palette.Set(GBA.Palette.MAX * 15 + i, bg_palette[i]);
            }
            result        = new GBA.Bitmap(GBA.Screen.WIDTH, GBA.Screen.HEIGHT);
            result.Colors = palette;

            if (BG_CheckBox.Checked)
            {
                GBA.Image bg = bg_tileset.ToImage(GBA.Screen.W_TILES + 2, GBA.Screen.H_TILES, bg_palette.ToBytes(false));
                for (int y = 0; y < GBA.Screen.HEIGHT; y++)
                {
                    for (int x = 0; x < GBA.Screen.WIDTH; x++)
                    {
                        result[x, y] = GBA.Palette.MAX * 15 + bg[x, y];
                    }
                }
            }
            if (MG_CheckBox.Checked)
            {
                TSA_Image mg = new TSA_Image(mg_palette, mg_tileset, mg_tsa);
                for (int y = 0; y < GBA.Screen.HEIGHT; y++)
                {
                    for (int x = 0; x < GBA.Screen.WIDTH; x++)
                    {
                        if (mg.GetColor(x, y).Value != 0)
                        {
                            result[x, y] = mg[x, y];
                        }
                    }
                }
            }
            if (FG_CheckBox.Checked)
            {
                Palette[] palettes = Palette.Split(mg_palette, 8);
                GBA.Image fg;
                // large japanese 'FIRE EMBLEM' title
                fg = mg_tileset.ToImage(32, 25, palettes[4].ToBytes(false));
                Core_DrawLayer(result, fg, new Rectangle(0, 152, GBA.Screen.WIDTH, 48), 0, 48);
                Core_DrawLayer(result, fg, new Rectangle(0, 104, GBA.Screen.WIDTH, 48), 0, 40);
                // small english 'FIRE EMBLEM'
                fg = fg_tileset.ToImage(32, 32, palettes[2].ToBytes(false));
                Core_DrawLayer(result, fg, new Rectangle(0, 0, 128, 16), 99, 27);
                // Nintendo & IS copyrights
                Core_DrawLayer(result, fg, new Rectangle(0, 48, 208, 8), 16, 152);
                // japanese subtitle scroll thingy
                fg.Colors = palettes[3];
                Core_DrawLayer(result, fg, new Rectangle(128, 16, 120, 32), 64, 85);
                // 'Press Start'
                fg.Colors = palettes[1];
                Core_DrawLayer(result, fg, new Rectangle(128, 0, 80, 16), 80, 120);
            }
            Current        = result;
            CurrentPalette = palette;
        }
Esempio n. 60
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Environment.CurrentDirectory)
                          .AddJsonFile("LoruleConfig.json");

            var config         = builder.Build();
            var editorSettings = config.GetSection("Editor").Get <EditorOptions>();
            var assetLocation  = Path.Combine(editorSettings.Location, "Assets", "Bitmaps", "legend");

            if (!Directory.Exists(assetLocation))
            {
                Directory.CreateDirectory(assetLocation);
            }


            Dictionary <string, Palette> pals = new Dictionary <string, Palette>();

            foreach (var palfile in Directory.GetFiles(editorSettings.Location + @"\Extractions\setoa", "*.pal"))
            {
                var pallete = Palette.FromFile(palfile);

                pals[Path.GetFileNameWithoutExtension(palfile)] = pallete;
            }

            Palette palette = null;

            foreach (var file in Directory.GetFiles(editorSettings.Location + @"\Extractions\setoa", "*.*").OrderBy(i => i.Length).ToArray())
            {
                if (Path.GetExtension(file) == ".epf")
                {
                    var epf = EPFImage.FromFile(file);

                    var palleteName = File.Exists(Path.GetFileNameWithoutExtension(file) + ".pal")
                        ? Path.GetFileNameWithoutExtension(file)
                        : "legend";

                    palette = pals[palleteName];

                    foreach (var frame in epf.Frames)
                    {
                        if (frame.RawData.Length > 0 && palette != null)
                        {
                            var bitmap = frame.Render(frame.Width, frame.Height, frame.RawData, palette,
                                                      EPFFrame.ImageType.EPF);
                            bitmap.Save(
                                Path.Combine(assetLocation,
                                             Path.GetFileNameWithoutExtension(file) + ".bmp"),
                                ImageFormat.Bmp);
                        }
                    }
                }

                if (Path.GetExtension(file) == ".spf")
                {
                    var spf = SpfFile.FromFile(file);

                    foreach (var frame in spf.Frames)
                    {
                        frame.FrameBitmap?.Save(
                            Path.Combine(assetLocation,
                                         Path.GetFileNameWithoutExtension(spf.FileName) + $"{spf.FrameCount}.bmp"),
                            ImageFormat.Bmp);
                    }
                }

                if (Path.GetExtension(file) == ".txt")
                {
                    var data = await File.ReadAllLinesAsync(file);

                    if (data != null && data.Length > 0)
                    {
                        AssetControl control = new AssetControl();
                        for (var index = 0; index < data.Length; index++)
                        {
                            var line = data[index];

                            if (line == "<CONTROL>")
                            {
                                control.Name = data[index + 1].Replace("<NAME>", string.Empty).Replace("\"", "").Trim();
                                control.Type = data[index + 2].Replace("<TYPE>", string.Empty).Replace("\"", "").Trim();

                                var rect      = data[index + 3].Replace("<RECT>", string.Empty).Replace("\"", "").Trim();
                                var rectparts = rect.Split(" ");

                                if (rectparts.Length == 4)
                                {
                                    TryParse(rectparts[0], out var x);
                                    TryParse(rectparts[1], out var y);
                                    TryParse(rectparts[2], out var w);
                                    TryParse(rectparts[3], out var h);

                                    control.Rect = new Rectangle(x, y, w, h);
                                }

                                if (data[index + 4] == "\t<IMAGE>")
                                {
                                    var imageparts = data[index + 5].Replace("\t\t", string.Empty).Replace("\"", "")
                                                     .Trim().Split(" ");

                                    if (imageparts.Length == 2)
                                    {
                                        control.Image      = imageparts[0];
                                        control.FrameCount = imageparts[1];
                                    }
                                    else
                                    {
                                        control.Image = imageparts[0];
                                    }
                                }
                            }

                            if (line == "<ENDCONTROL>")
                            {
                                ControiAssetControls.Add(control);
                                control = new AssetControl();
                            }
                        }
                    }
                }
            }


            List <AssetControl> saveableControls = new List <AssetControl>();


            foreach (var control in ControiAssetControls)
            {
                if (!string.IsNullOrEmpty(control.Image) && Path.GetExtension(control.Image) == ".spf")
                {
                    var path = Path.GetRelativePath(Path.Combine(assetLocation, editorSettings.Location), assetLocation);

                    if (File.Exists(path))
                    {
                        control.Image = path;
                        saveableControls.Add(control);
                    }
                }
            }

            var jsonFile = JsonConvert.SerializeObject(saveableControls);

            File.WriteAllText(assetLocation + "\\metafile.json", jsonFile);
        }