using System;

namespace SharpQuake
{
	internal class FloodFiller
	{
		public void Perform()
		{
			int num = 0;
			uint[] table8to = vid.Table8to24;
			for (int i = 0; i < 256; i++)
			{
				if (table8to[i] == 255u)
				{
					num = i;
					break;
				}
			}
			if ((int)this._FillColor == num || this._FillColor == 255)
			{
				return;
			}
			int num2 = 0;
			this._Inpt = 0;
			this._Fifo[this._Inpt].x = 0;
			this._Fifo[this._Inpt].y = 0;
			this._Inpt = (this._Inpt + 1 & 4095);
			while (num2 != this._Inpt)
			{
				this._X = (int)this._Fifo[num2].x;
				this._Y = (int)this._Fifo[num2].y;
				this._Fdc = num;
				int num3 = this._X + this._Width * this._Y;
				num2 = (num2 + 1 & 4095);
				if (this._X > 0)
				{
					this.Step(num3 - 1, -1, 0);
				}
				if (this._X < this._Width - 1)
				{
					this.Step(num3 + 1, 1, 0);
				}
				if (this._Y > 0)
				{
					this.Step(num3 - this._Width, 0, -1);
				}
				if (this._Y < this._Height - 1)
				{
					this.Step(num3 + this._Width, 0, 1);
				}
				this._Skin.Data[this._Skin.StartIndex + num3] = (byte)this._Fdc;
			}
		}

		private void Step(int offset, int dx, int dy)
		{
			byte[] data = this._Skin.Data;
			int num = this._Skin.StartIndex + offset;
			if (data[num] == this._FillColor)
			{
				data[num] = byte.MaxValue;
				this._Fifo[this._Inpt].x = (short)(this._X + dx);
				this._Fifo[this._Inpt].y = (short)(this._Y + dy);
				this._Inpt = (this._Inpt + 1 & 4095);
				return;
			}
			if (data[num] != 255)
			{
				this._Fdc = (int)data[num];
			}
		}

		public FloodFiller(ByteArraySegment skin, int skinwidth, int skinheight)
		{
			this._Skin = skin;
			this._Width = skinwidth;
			this._Height = skinheight;
			this._Fifo = new FloodFiller.floodfill_t[4096];
			this._FillColor = this._Skin.Data[this._Skin.StartIndex];
		}

		private const int FLOODFILL_FIFO_SIZE = 4096;

		private const int FLOODFILL_FIFO_MASK = 4095;

		private ByteArraySegment _Skin;

		private FloodFiller.floodfill_t[] _Fifo;

		private int _Width;

		private int _Height;

		private int _X;

		private int _Y;

		private int _Fdc;

		private byte _FillColor;

		private int _Inpt;

		private struct floodfill_t
		{
			public short x;

			public short y;
		}
	}
}
