It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have translated the code from javascript to c# which can be found by going to this excellent demo at http://fractal.qfox.nl/dragon.js
My translation is intended to produce just a single dragon upon clicking the button but I think I have missed something in my version.
See the Wikipedia article: Dragon Curve for more information.
Incomplete dragon fractal output:
Code:
public partial class MainPage : UserControl
{
PointCollection pc;
Int32[] pattern = new Int32[] { 1, 1, 0, 2, 1, 0, 0, 3 };
Int32[] position = new Int32[] { 0, 0, 0, 0, 0, 0, 0, 0 };
Boolean toggle;
Char r = default(Char);
Int32 distance = 10; // line length
Int32 step = 100; // paints per step
Int32 skip = 10; // folds per paint
Double x = 0;
Double y = 0;
Int32 a = 90;
public MainPage()
{
InitializeComponent();
}
private void btnFire_Click(object sender, RoutedEventArgs e)
{
x = canvas.ActualWidth / 3;
y = canvas.ActualHeight / 1.5;
pc = new PointCollection();
var n = step;
while (--n > 0)
{
List<Char> s = getS(skip);
draw(s);
}
Polyline p = new Polyline();
p.Stroke = new SolidColorBrush(Colors.Red);
p.StrokeThickness = 0.5;
p.Points = pc;
canvas.Children.Add(p);
}
List<Char> getS(Int32 n)
{
List<Char> s1 = new List<Char>();
while (n-- > 0) s1.Add(getNext(0));
return s1;
}
void draw(List<Char> s)
{
pc.Add(new Point(x, y));
for (Int32 i = 0, n = s.Count; i < n; i++)
{
pc.Add(new Point(x, y));
Int32 j;
if (int.TryParse(s[i].ToString(), out j) && j != 0)
{
if ((a + 90) % 360 != 0)
{
a = (a + 90) % 360;
}
else
{
a = 360; // Right
}
}
else
{
if (a - 90 != 0)
{
a = a - 90;
}
else
{
a = 360; // Right
}
}
// new target
if (a == 0 || a == 360)
{
y -= distance;
}
else if (a == 90)
{
x += distance;
}
else if (a == 180)
{
y += distance;
}
else if (a == 270)
{
x -= distance;
}
// move
pc.Add(new Point(x, y));
}
}
Char getNext(Int32 n)
{
if (position[n] == 7)
{
r = getNext(n + 1);
position[n] = 0;
}
else
{
var x = position[n] > 0 ? pattern[position[n]] : pattern[0];
switch (x)
{
case 0:
r = '0';
break;
case 1:
r = '1';
break;
case 2:
if (!toggle)
{
r = '1';
}
else
{
r = '0';
}
toggle = !toggle;
break;
}
position[n] = position[n] + 1;
}
return r;
}
}
I cleaned up the code, and tried to get how the pattern and position arrays should work to produce the correct sequence, but I couldn't figure it out. The last item in the pattern array is for example never used...
There is however a simpler method implementing the getNext method using just a counter:
bool getNext() {
cnt++;
return (cnt & ((cnt & -cnt) << 1)) != 0;
}
I have used that method before (about 20 years ago), and I found this implementation on the dragon curve wikipedia page.
The cleaned up code with this getNext implementation looks like this:
public partial class MainPage : UserControl {
PointCollection pc;
int cnt = 0;
int distance = 10; // line length
int steps = 1024; // number of paints
int x = 0;
int y = 0;
int a = 90;
public MainPage() {
InitializeComponent();
}
private void btnFire_Click(object sender, RoutedEventArgs e) {
x = (int)(canvas.ActualWidth / 3);
y = (int)(canvas.ActualHeight / 1.5);
pc = new PointCollection();
draw(getS(steps));
Polyline p = new Polyline();
p.Stroke = new SolidColorBrush(Colors.Red);
p.StrokeThickness = 0.5;
p.Points = pc;
canvas.Children.Add(p);
}
List<bool> getS(int n) {
List<bool> s1 = new List<bool>();
while (n-- > 0) {
s1.Add(getNext());
}
return s1;
}
void draw(List<bool> s) {
pc.Add(new Point(x, y));
foreach (bool z in s) {
a = (a + (z ? 90 : 270)) % 360;
// new target
switch (a) {
case 90: x += distance; break;
case 180: y += distance; break;
case 270: x -= distance; break;
default: y -= distance; break;
}
// move
pc.Add(new Point(x, y));
}
}
bool getNext() {
cnt++;
return (cnt & ((cnt & -cnt) << 1)) != 0;
}
}
Related
I'am trying to Draw a Triangle in through three points, with known coordinates enclosed within the Triangle.
I wrote this algorithm to do all this, but the code is slow.
Can anyone give me another easy and faster way to draw a Triangle?
I have got the algorithm of drawing the line from this site but do not mention the post sorry.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
public partial class Form1 : Form
{
int Screen_height;
int Screen_width;
List<int> Pointsx = new List<int>(new int[] { });
List<int> Pointsy = new List<int>(new int[] { });
List<int> edge_one_Tranglex= new List<int>(new int[] { });
List<int> edge_one_Trangley = new List<int>(new int[] { });
List<int> edge_two_Tranglex = new List<int>(new int[] { });
List<int> edge_two_Trangley = new List<int>(new int[] { });
List<int> edge_three_Tranglex = new List<int>(new int[] { });
List<int> edge_three_Trangley = new List<int>(new int[] { });
int edge = 1;
Bitmap bmp;
int start = 0;
int center_x;
int center_y;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Screen_height = panel1.Height;
Screen_width = panel1.Width;
Console.WriteLine(" " + Screen_height + "," + Screen_width);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
if (start == 0)
{
var sw = new Stopwatch();
sw.Start();
bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.BackgroundImage = (Image)bmp;
panel1.BackgroundImageLayout = ImageLayout.None;
//from x to x2 and from y to y2
//D_line(100, 10, -100, 20);
D_Triangle(-300, 10, 100, 20, 100, -100);
sw.Stop();
Console.WriteLine("" + sw.Elapsed);
start += 1;
}
}
public void D_line(int x, int y, int x2, int y2)
{
center_x = Screen_width / 2;
center_y = Screen_height / 2;
line(center_x + x, center_y - y, center_x + x2, center_y - y2);
}
public void line(int x, int y, int x2, int y2)
{
int w = x2 - x;
int h = y2 - y;
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0;
if (w < 0) dx1 = -1; else if (w > 0) dx1 = 1;
if (h < 0) dy1 = -1; else if (h > 0) dy1 = 1;
if (w < 0) dx2 = -1; else if (w > 0) dx2 = 1;
int longest = Math.Abs(w);
int shortest = Math.Abs(h);
if (!(longest > shortest))
{
longest = Math.Abs(h);
shortest = Math.Abs(w);
if (h < 0) dy2 = -1; else if (h > 0) dy2 = 1;
dx2 = 0;
}
int numerator = longest >> 1;
for (int i = 0; i <= longest; i++)
{
//putpixel(x, y, color);
bmp.SetPixel(x, y, Color.Red);
//my code
if (edge == 1)
{
edge_one_Tranglex.Add(x);
edge_one_Trangley.Add(y);
}
if (edge == 2)
{
edge_two_Tranglex.Add(x);
edge_two_Trangley.Add(y);
}
if (edge == 3)
{
edge_three_Tranglex.Add(x);
edge_three_Trangley.Add(y);
}
if (edge >= 4)
{
if (!Pointsx.Contains(x) || !Pointsy.Contains(y))
{
Pointsx.Add(x);
Pointsy.Add(y);
}
}
numerator += shortest;
if (!(numerator < longest))
{
numerator -= longest;
x += dx1;
y += dy1;
}
else
{
x += dx2;
y += dy2;
}
}
edge++;
// edge_two_Trangle.ForEach(p => Console.WriteLine(p));
}
void D_Triangle(int x1, int y1, int x2, int y2, int x3, int y3)
{
D_line(x1, y1, x2, y2);
D_line(x2, y2, x3, y3);
D_line(x3, y3, x1, y1);
int a = edge_two_Tranglex.Count();
for(int i =1; i < a -1;)
{
line(center_x + x1, center_y - y1, edge_two_Tranglex[i], edge_two_Trangley[i]);
i++;
}
}
}
I am new to C# and graphing world. I am trying to plot serial data coming from Arduino as double datatype on ZedGraph in C#. I am unable to plot it. The graph is appearing with only the scale Y axis scale setting itself to the output value but nothing else. I shall be grateful for your help!! Thanks. Below is my code
PS: I put a message box to see the output and it is showing the correct output from the Arduino.
using System;
using System.Drawing;
using System.Windows.Forms;
using ZedGraph;
using System.IO.Ports;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
static string indata;
double x;
double d;
public Form1()
{
InitializeComponent();
PlotSerial();
// DrawGraph();
}
private void PlotSerial()
{
SerialPort sprt;
sprt = new SerialPort("COM4");
sprt.BaudRate = 115200;
try
{
sprt.Open();
}
catch (Exception)
{
MessageBox.Show("Check port");
}
// initializing zed graph
GraphPane pane = zedGraph.GraphPane;
PointPairList list2 = new PointPairList();
pane.YAxisList.Clear();
//X-Axis Settings
pane.XAxis.Scale.MinorStep = 1;
pane.XAxis.Scale.MajorStep = 5;
XDate time = new XDate(DateTime.Now.ToOADate());
pane.XAxis.Type = AxisType.Date;
pane.XAxis.Scale.Format = "ss";
pane.XAxis.Scale.Min = new XDate(DateTime.Now);
pane.XAxis.Scale.Max = new XDate(DateTime.Now.AddSeconds(25));
pane.XAxis.Scale.MinorUnit = DateUnit.Second;
pane.XAxis.Scale.MajorUnit = DateUnit.Second;
indata = sprt.ReadLine();
MessageBox.Show(indata);
bool result = Double.TryParse(indata, out d);
// double xmin = -50;
//double xmax = 50;
//for x = 0 To 36
//for (double x = xmin; x <= xmax; x += 1)
//for (int i = 1; i < 20; i++)
{
list2.Add(x, d);
}
Scale xScale1 = zedGraph.MasterPane.PaneList[0].XAxis.Scale;
if (time.XLDate > xScale1.Max)
{
xScale1.Max = (XDate)(DateTime.Now.AddSeconds(1));
xScale1.Min = (XDate)(DateTime.Now.AddSeconds(-40));
}
/*
// byte[] buffer = new byte[20];
indata = (byte)sprt.ReadByte();
//MessageBox.Show(indata);
//double xmin = -2;
//double xmax = 2;
// for (= xmin; x <= xmax; x +=1)
list2.Add(x, indata);
*/
pane.XAxis.Title.Text = "X Axis";
int axis2 = pane.AddYAxis("Y Axis");
LineItem myCurve2 = pane.AddCurve("Serialport_Curve", list2, Color.Blue, SymbolType.Diamond);
myCurve2.YAxisIndex = axis2;
pane.YAxisList[axis2].Title.FontSpec.FontColor = Color.Black;
zedGraph.AxisChange();
zedGraph.Invalidate();
}
private double f1(double x)
{
if (x == 0)
{
return 1;
}
return Math.Sin(x) / x;
}
private double f2(double x)
{
if (x == 0)
{
return 1;
}
return 10 * Math.Sin(x * 0.5) / x;
}
private double f3(double x)
{
if (x == 0)
{
return 1;
}
return 0.1 * Math.Sin(x * 2) / x;
}
}
}
I am creating a class with specific number of objects.When these objects are created and drawn on screen with that capacity again I reinitialize that class.The problem is that I want to reinitialize in such a way that if new objects are created then previous must be persist/drawn on the screen.I am not able to get the logic.
crShade = new CreateShade[Obj_num]; for (int i = incr_Obj; i < crShade.Length; i++) {
int r = rad.Next(0, 7); int x = 0; switch (r) {
case 0: x = 0; break; case 1: x = 120; break; case 2: x = 240; break; case 3: x = 360; break;
}
X_pos.Add(x); crShade[i] = new CreateShade(x, -60, clr[3]); _Shade.Add(crShade[i]);
}
--
public class CreateShade {
public int posX; public int posY; public Color color; Random r = new Random(); private int width = 120; private int height = 60; public static bool _Fall; public static bool check; public static List<int> y_pos = new List<int>(); int balance = 0; public CreateShade(int x, int y, Color color) {
int random = r.Next(0, 4); this.posY = y; this.posX = x; this.color = color;
}
public void draw(SpriteBatch batch) {
batch.Draw(Vimap_ScreenManager.blank, new Rectangle(posX, posY, width, height), color);
}
public void update() {
int counter = 0; if (posY != 740-balance) {
posY += 10; if (counter != y_pos.Count) {
if (new Rectangle(posX, posY, 120, 60).Intersects(new Rectangle(VimapGamePage.X_pos.ElementAt(counter), y_pos.ElementAt(counter), 120, 60))) {
balance = counter * 60;
}
else {
counter++;
}
}
//check = true;
}
else {
y_pos.Add(posY); _Fall = true; // VimapGamePage.End_Reach = true;
}
}
public void Move_X(Point p) {
if (p.X <= 240) {
if (p.X >= 0 && p.X <= 120) {
posX = 0;
}
else if (p.X > 120 && p.X <= 240) {
posX = 120;
}
}
else if (p.X > 240) {
if (p.X > 240 && p.X <= 360) {
posX = 240;
}
else if (p.X > 360 && p.X <= 480) {
posX = 360;
}
}
}
}
I used this code for segmentation, I'm trying to detect pixels one by one because my object is a binary, not a grayscale. when i run the program, it draws 2 object. The first object is successfully drawn (object still has a black color and a red rectangle), but the second object fails get drawn. Screenshot is here. Please help me, why does this happen?
#region Edge Detection
private void btnSegmentasi_Click(object sender, EventArgs e)
{
Segments = new List<ImageSegment>();
Bitmap bmp = (Bitmap)pb2.Image;
imageArea = new Rectangle(0, 0, pb2.Image.Width - 1, pb2.Image.Height - 1);
for (int y = 0; y < pb2.Image.Height; y++)
{
for (int x = 0; x < pb2.Image.Width; x++)
{
bool skip = false;
foreach (ImageSegment segment in Segments)
{
if (pointIsInRect(x, y, segment.Rect))
{
skip = true;
break;
}
}
if (skip) continue;
Color warna = bmp.GetPixel(x, y);
if (warna.G == 0)
startEdgeDetection(x, y, ref bmp);
}
}
DGVProses.DataSource = Segments;
if (Segments.Count > 0)
{
Graphics g = pb2.CreateGraphics();
Rectangle[] rects = (from theSegment in Segments select theSegment.Rect).ToArray();
g.DrawRectangles(new Pen(Brushes.Red), rects);
g.Dispose();
}
}
private void startEdgeDetection(int x, int y, ref Bitmap bmp)
{
Point startPoint = new Point(x, y);
Point currPoint = new Point(x, y);
int sudut = 180;
int xMin = x, yMin = y, xMax = x, yMax = y;
do
{
sudut -= 45;
Point offset = angleToPoint(ref sudut);
Point trialPoint = new Point(currPoint.X + offset.X, currPoint.Y + offset.Y);
if (!pointIsInRect(trialPoint.X, trialPoint.Y, imageArea))
continue;
Color theColor = bmp.GetPixel(trialPoint.X, trialPoint.Y);
if (theColor.G == 0)
{
currPoint = trialPoint;
sudut -= 180;
if (currPoint.X > xMax)
xMax = currPoint.X;
else if (currPoint.X < xMin)
xMin = currPoint.X;
if (currPoint.Y > yMax)
yMax = currPoint.Y;
else if (currPoint.Y < yMin)
yMin = currPoint.Y;
if (sudut < 0)
sudut += 360;
if (currPoint == startPoint && sudut == 180)
break;
}
}
while (!(currPoint == startPoint && sudut == 180));
Rectangle r = new Rectangle(xMin, yMin, xMax - xMin + 1, yMax - yMin + 1);
Bitmap newImage = new Bitmap(r.Width + 2, r.Height + 2);
using (Graphics g = Graphics.FromImage(newImage))
{
g.FillRectangle(Brushes.White, 0, 0, newImage.Width, newImage.Height);
g.DrawImage(bmp, new Rectangle(1, 1, r.Width, r.Height), r, GraphicsUnit.Pixel);
g.Dispose();
}
Segments.Add(new ImageSegment(r, newImage));
}
private Point angleToPoint(ref int sudut)
{
if (sudut < 0)
sudut += 360;
switch (sudut)
{
case 135: return new Point(-1, -1);
case 90: return new Point(0, -1);
case 45: return new Point(1, -1);
case 0: return new Point(1, 0);
case 315: return new Point(1, 1);
case 270: return new Point(0, 1);
case 225: return new Point(-1, 1);
default: return new Point(-1, 0);
}
}
private bool pointIsInRect(int x, int y, Rectangle rect)
{
if (x < rect.X)
return false;
if (x > rect.X + rect.Width)
return false;
if (x < rect.Y)
return false;
if (x > rect.Y + rect.Height)
return false;
return true;
}
#endregion
Okay, I think I've now got a clue of how your algorithm is supposed to work. I'd guess you are running around in circles within the object. I do not really know why it does not happen for the first object, but this is another story.
When you enter startEdgeDetection you start at some point, check if it's black, move by an angle and repeat the whole procedure. You stop when the current point reaches the starting point. The crux is, that this algorithm does not guarantee to walk the whole object, but may just do the following (I do not know it is exactly like this, but pretty much):
OOOOOO
O####O
O####O
OOOOOO
OOOOOO
O*###O
O####O
OOOOOO
OOOOOO
O**##O
O####O
OOOOOO
OOOOOO
O**##O
O#*##O
OOOOOO
OOOOOO
O**##O
O**##O
OOOOOO
O = pixels filled with white
# = pixels filled with black
* = pixels you stepped through
You've reached your starting point again and the algorithm stops, but the bounding box does not contain the whole object, but just a part. If all of your objects bounding boxes have either a width or a height of 1 you fill up your whole object with bounding boxes, hence it appears red.
You'll have to fix the startEdgeDetection to avoid the described case and make sure that you really detect the edge.
I made up a simple class that finds the bounding box of an object. It should be easy to apply it to your problem.
public class BoundingBoxCalculator
{
Bitmap bitmapToCalculateBoundingBoxFor;
Point startingPoint;
Point[] neighborOffsets =
{new Point(-1,-1),
new Point(0,-1),
new Point(1,-1),
new Point(-1, 0),
new Point(1, 0),
new Point(-1,1),
new Point(0,1),
new Point(1,1)};
public BoundingBoxCalculator(Bitmap bitmapContainingObject, Point borderPoint)
{
this.bitmapToCalculateBoundingBoxFor = bitmapContainingObject;
this.startingPoint = borderPoint;
}
public Rectangle CalculateBoundingBox()
{
List<Point> edgePoints = CalculateEdge();
int minX = edgePoints.Min(p => p.X);
int maxX = edgePoints.Max(p => p.X);
int minY = edgePoints.Min(p => p.Y);
int maxY = edgePoints.Max(p => p.Y);
return new Rectangle(minX, minY, maxX - minX, maxY - minY);
}
List<Point> CalculateEdge()
{
List<Point> edgePoints = new List<Point>();
Point currentPoint = startingPoint;
do
{
IEnumerable<Point> neighboringEdgePoints = GetNeighboringEdgePoints(currentPoint);
IEnumerable<Point> neighboringEdgePointsNotVisited = from p in neighboringEdgePoints where !edgePoints.Contains(p) select p;
edgePoints.Add(currentPoint);
if(neighboringEdgePointsNotVisited.Count() == 0
&& neighboringEdgePoints.Contains(startingPoint))
{
currentPoint = startingPoint;
}
else if(neighboringEdgePointsNotVisited.Count() == 1)
{
Point nextPoint = neighboringEdgePointsNotVisited.First();
currentPoint = nextPoint;
}
else if(neighboringEdgePointsNotVisited.Count() > 1)
{
Point nextPoint = GetPointWithMinDistance(currentPoint, neighboringEdgePointsNotVisited);
currentPoint = nextPoint;
}
else
{
throw new Exception();
}
} while(currentPoint != startingPoint);
return edgePoints;
}
Point GetPointWithMinDistance(Point origin, IEnumerable<Point> pointsToTest)
{
double minDistance = double.MaxValue;
Point pointWithMinDistance = new Point(0,0);
foreach(Point pointToTest in pointsToTest)
{
double currentDistance = GetPointsDistance(origin, pointToTest);
if(currentDistance < minDistance)
{
minDistance = currentDistance;
pointWithMinDistance = pointToTest;
}
}
return pointWithMinDistance;
}
double GetPointsDistance(Point p1, Point p2)
{
return Math.Sqrt((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y));
}
IEnumerable<Point> GetNeighboringEdgePoints(Point currentPoint)
{
IEnumerable<Point> neighboringPoints = GetNeighboringPoints(currentPoint);
List<Point> neighboringEdgePoints = new List<Point>();
foreach(Point pointToTest in neighboringPoints)
{
if(GetNeighboringPoints(pointToTest).Count() < 8)
{
neighboringEdgePoints.Add(pointToTest);
}
}
return neighboringEdgePoints;
}
IEnumerable<Point> GetNeighboringPoints(Point currentPoint)
{
List<Point> neighbors = new List<Point>();
for(int offsetsCount = 0; offsetsCount < neighborOffsets.Length; offsetsCount++)
{
Point currentPointWithOffset = AddPointOffset(currentPoint, neighborOffsets[offsetsCount]);
if(IsInImage(currentPointWithOffset) &&
IsInObject(currentPointWithOffset))
{
neighbors.Add(currentPointWithOffset);
}
}
return neighbors;
}
bool IsInImage(Point pointToTest)
{
return pointToTest.X >= 0
&& pointToTest.X < bitmapToCalculateBoundingBoxFor.Width
&& pointToTest.Y >= 0
&& pointToTest.Y < bitmapToCalculateBoundingBoxFor.Height;
}
bool IsInObject(Point pointToTest)
{
Color colorInPointPosition = bitmapToCalculateBoundingBoxFor.GetPixel(pointToTest.X, pointToTest.Y);
//assume object is color is not white
return colorInPointPosition.R != 255
|| colorInPointPosition.G != 255
|| colorInPointPosition.B != 255;
}
Point AddPointOffset(Point point, Point offset)
{
return new Point(point.X + offset.X, point.Y + offset.Y);
}
}
Find an example at:
https://dotnetfiddle.net/49bnTV
I just tested it with a rectangle, but I guess it should work with any shape. Just give it a try.
I'm attempting to add semi-realistic water into my tile-based, 2D platformer. The water must act somewhat lifelike, with a pressure model that runs entirely local. (IE. Can only use data from cells near it) This model is needed because of the nature of my game, where you cannot be certain that the data you need isn't inside an area that isn't in memory.
I've tried one method so far, but I could not refine it enough to work with my constraints.
For that model, each cell would be slightly compressible, depending on the amount of water in the above cell. When a cell's water content was larger than the normal capacity, the cell would try to expand upwards. This created a fairly nice simulation, abeit slow (Not lag; Changes in the water were taking a while to propagate.), at times. When I tried to implement this into my engine, I found that my limitations lacked the precision required for it to work. I can provide a more indepth explanation or a link to the original concept if you wish.
My constraints:
Only 256 discrete values for water level. (No floating point variables :( ) -- EDIT. Floats are fine.
Fixed grid size.
2D Only.
U-Bend Configurations must work.
The language that I'm using is C#, but I can probably take other languages and translate it to C#.
The question is, can anyone give me a pressure model for water, following my constraints as closely as possible?
How about a different approach?
Forget about floats, that's asking for roundoff problems in the long run. Instead, how about a unit of water?
Each cell contains a certain number of units of water. Each iteration you compare the cell with it's 4 neighbors and move say 10% (change this to alter the propagation speed) of the difference in the number of units of water. A mapping function translates the units of water into a water level.
To avoid calculation order problems use two values, one for the old units, one for the new. Calculate everything and then copy the updated values back. 2 ints = 8 bytes per cell. If you have a million cells that's still only 8mb.
If you are actually trying to simulate waves you'll need to also store the flow--4 values, 16 mb. To make a wave put some inertia to the flow--after you calculate the desired flow then move the previous flow say 10% of the way towards the desired value.
Try treating each contiguous area of water as a single area (like flood fill) and track 1) the lowest cell(s) where water can escape and 2) the highest cell(s) from which water can come, then move water from the top to the bottom. This isn't local, but I think you can treat the edges of the area you want to affect as not connected and process any subset that you want. Re-evaluate what areas are contiguous on each frame (re-flood on each frame) so that when blobs converge, they can start being treated as one.
Here's my code from a Windows Forms demo of the idea. It may need some fine tuning, but seems to work quite well in my tests:
public partial class Form1 : Form
{
byte[,] tiles;
const int rows = 50;
const int cols = 50;
public Form1()
{
SetStyle(ControlStyles.ResizeRedraw, true);
InitializeComponent();
tiles = new byte[cols, rows];
for (int i = 0; i < 10; i++)
{
tiles[20, i+20] = 1;
tiles[23, i+20] = 1;
tiles[32, i+20] = 1;
tiles[35, i+20] = 1;
tiles[i + 23, 30] = 1;
tiles[i + 23, 32] = 1;
tiles[21, i + 15] = 2;
tiles[21, i + 4] = 2;
if (i % 2 == 0) tiles[22, i] = 2;
}
tiles[20, 30] = 1;
tiles[20, 31] = 1;
tiles[20, 32] = 1;
tiles[21, 32] = 1;
tiles[22, 32] = 1;
tiles[33, 32] = 1;
tiles[34, 32] = 1;
tiles[35, 32] = 1;
tiles[35, 31] = 1;
tiles[35, 30] = 1;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (SolidBrush b = new SolidBrush(Color.White))
{
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < cols; x++)
{
switch (tiles[x, y])
{
case 0:
b.Color = Color.White;
break;
case 1:
b.Color = Color.Black;
break;
default:
b.Color = Color.Blue;
break;
}
e.Graphics.FillRectangle(b, x * ClientSize.Width / cols, y * ClientSize.Height / rows,
ClientSize.Width / cols + 1, ClientSize.Height / rows + 1);
}
}
}
}
private bool IsLiquid(int x, int y)
{
return tiles[x, y] > 1;
}
private bool IsSolid(int x, int y)
{
return tiles[x, y] == 1;
}
private bool IsEmpty(int x, int y)
{
return IsEmpty(tiles, x, y);
}
public static bool IsEmpty(byte[,] tiles, int x, int y)
{
return tiles[x, y] == 0;
}
private void ProcessTiles()
{
byte processedValue = 0xFF;
byte unprocessedValue = 0xFF;
for (int y = 0; y < rows; y ++)
for (int x = 0; x < cols; x++)
{
if (IsLiquid(x, y))
{
if (processedValue == 0xff)
{
unprocessedValue = tiles[x, y];
processedValue = (byte)(5 - tiles[x, y]);
}
if (tiles[x, y] == unprocessedValue)
{
BlobInfo blob = GetWaterAt(new Point(x, y), unprocessedValue, processedValue, new Rectangle(0, 0, 50, 50));
blob.ProcessMovement(tiles);
}
}
}
}
class BlobInfo
{
private int minY;
private int maxEscapeY;
private List<int> TopXes = new List<int>();
private List<int> BottomEscapeXes = new List<int>();
public BlobInfo(int x, int y)
{
minY = y;
maxEscapeY = -1;
TopXes.Add(x);
}
public void NoteEscapePoint(int x, int y)
{
if (maxEscapeY < 0)
{
maxEscapeY = y;
BottomEscapeXes.Clear();
}
else if (y < maxEscapeY)
return;
else if (y > maxEscapeY)
{
maxEscapeY = y;
BottomEscapeXes.Clear();
}
BottomEscapeXes.Add(x);
}
public void NoteLiquidPoint(int x, int y)
{
if (y < minY)
{
minY = y;
TopXes.Clear();
}
else if (y > minY)
return;
TopXes.Add(x);
}
public void ProcessMovement(byte[,] tiles)
{
int min = TopXes.Count < BottomEscapeXes.Count ? TopXes.Count : BottomEscapeXes.Count;
for (int i = 0; i < min; i++)
{
if (IsEmpty(tiles, BottomEscapeXes[i], maxEscapeY) && (maxEscapeY > minY))
{
tiles[BottomEscapeXes[i], maxEscapeY] = tiles[TopXes[i], minY];
tiles[TopXes[i], minY] = 0;
}
}
}
}
private BlobInfo GetWaterAt(Point start, byte unprocessedValue, byte processedValue, Rectangle bounds)
{
Stack<Point> toFill = new Stack<Point>();
BlobInfo result = new BlobInfo(start.X, start.Y);
toFill.Push(start);
do
{
Point cur = toFill.Pop();
while ((cur.X > bounds.X) && (tiles[cur.X - 1, cur.Y] == unprocessedValue))
cur.X--;
if ((cur.X > bounds.X) && IsEmpty(cur.X - 1, cur.Y))
result.NoteEscapePoint(cur.X - 1, cur.Y);
bool pushedAbove = false;
bool pushedBelow = false;
for (; ((cur.X < bounds.X + bounds.Width) && tiles[cur.X, cur.Y] == unprocessedValue); cur.X++)
{
result.NoteLiquidPoint(cur.X, cur.Y);
tiles[cur.X, cur.Y] = processedValue;
if (cur.Y > bounds.Y)
{
if (IsEmpty(cur.X, cur.Y - 1))
{
result.NoteEscapePoint(cur.X, cur.Y - 1);
}
if ((tiles[cur.X, cur.Y - 1] == unprocessedValue) && !pushedAbove)
{
pushedAbove = true;
toFill.Push(new Point(cur.X, cur.Y - 1));
}
if (tiles[cur.X, cur.Y - 1] != unprocessedValue)
pushedAbove = false;
}
if (cur.Y < bounds.Y + bounds.Height - 1)
{
if (IsEmpty(cur.X, cur.Y + 1))
{
result.NoteEscapePoint(cur.X, cur.Y + 1);
}
if ((tiles[cur.X, cur.Y + 1] == unprocessedValue) && !pushedBelow)
{
pushedBelow = true;
toFill.Push(new Point(cur.X, cur.Y + 1));
}
if (tiles[cur.X, cur.Y + 1] != unprocessedValue)
pushedBelow = false;
}
}
if ((cur.X < bounds.X + bounds.Width) && (IsEmpty(cur.X, cur.Y)))
{
result.NoteEscapePoint(cur.X, cur.Y);
}
} while (toFill.Count > 0);
return result;
}
private void timer1_Tick(object sender, EventArgs e)
{
ProcessTiles();
Invalidate();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int x = e.X * cols / ClientSize.Width;
int y = e.Y * rows / ClientSize.Height;
if ((x >= 0) && (x < cols) && (y >= 0) && (y < rows))
tiles[x, y] = 2;
}
}
}
From a fluid dynamics viewpoint, a reasonably popular lattice-based algorithm family is the so-called Lattice Boltzmann method. A simple implementation, ignoring all the fine detail that makes academics happy, should be relatively simple and fast and also get reasonably correct dynamics.