I'm doing all my expensive calculations in a background thread and need to be able to assign pictureBox1.Image after each cycle of calculations. I use to do this using delegates, but its been a long time and things don't seem to work that way anymore.
I tried putting the assignment in a WorkerCompleted event handler, but then I can't figure out how to restart backgroundWorker1. I've been at this all day and feel enormously frustrated, this use to be so easy to do.
This is the most relevant part of the code:
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using KnownColorsPalette;
namespace Color_Visualizer
{
public partial class Form1 : Form
{
static CultureInfo m_culture = CultureInfo.CurrentCulture;
double[,][] distances = new double[3000, 3000][];
FastPixel m_fp;
public Form1()
{
InitializeComponent();
WindowState = FormWindowState.Maximized;
this.pictureBox1.LoadCompleted += new System.ComponentModel.AsyncCompletedEventHandler(PictureBox1_LoadCompleted);
CoordinateSystem.AssignMe(this);
}
private void Form1_Load(object sender, EventArgs e)
{
ReadColors(); // Reads text file alternating name and RGB hex of
// Wikipedia's 1200+ named colors.
Point3D p = new Point3D(127.5, 127.5, 127.5);
foreach (FoundColors fc in m_lColors.Values)
fc.pt = fc.color - p;
Coord = new CoordinateSystem(new Plane(new Point3D(-127.5, -127.5, -127.5), new Point3D(-1, 0, 0)));
backgroundWorker1.RunWorkerAsync();
}
double fSpeed = 5;
Point3D m_pNormal = new Point3D();
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
double fAngle, fRadius, d;
Point3D vU, vV;
Point pLocation = new Point();
m_pNormal = Coord.Plane.Normal;
fAngle = Math.Atan2(m_pNormal.y, m_pNormal.x);
fRadius = Math.Sqrt(m_pNormal.x * m_pNormal.x + m_pNormal.y * m_pNormal.y);
fAngle += fSpeed * 180 / Math.PI;
m_pNormal.x = Math.Cos(fAngle) * fRadius;
m_pNormal.y = Math.Sin(fAngle) * fRadius;
m_fp.Lock();
m_fp.Clear(Color.Black);
foreach (FoundColors fc in m_lColors.Values)
{
vU = new Point3D(Coord.U);
d = dist(fc.pt, ref vU);
vV = Coord.V;
vV.mult(d);
pLocation.X = (int)(m_midHoriz + vU.norm());
pLocation.Y = (int)(m_midVert + vV.norm());
m_fp.SetPixel(pLocation, fc.color);
}
m_fp.Unlock();
}
double m_fDist, m_fDot;
public double dist(Point3D pt, ref Point3D vU)
{
double c1 = pt.dot(vU);
double c2 = vU.dot(vU);
double b = c1 / c2;
vU.mult(b);
m_fDot = pt.dot(Coord.Normal);
m_fDist = pt.norm(pt - vU);
return m_fDist;
}
double m_midHoriz, m_midVert;
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
pictureBox1.Image = m_fp.Bitmap;
}
private void Form1_Resize(object sender, EventArgs e)
{
m_midHoriz = pictureBox1.Width / 2;
m_midVert = pictureBox1.Height / 2;
m_fp = new FastPixel(new Bitmap(pictureBox1.Width, pictureBox1.Height));
}
}
}
And this is part of my support code:
using System;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
namespace Color_Visualizer
{
public partial class Form1 : Form
{
class CoordinateSystem
{
const int MAX = 256;
const double PlaneWidth = 600;
static Form1 Me;
static Point3D axisZ = new Point3D(0, 0, 1);
static Point3D axisY = new Point3D(0, 1, 0);
private Plane m_plane = new Plane(new Point3D(128, 128, 128), new Point3D(-128, 0, 0));
private Point3D m_pV = new Point3D(0, 0, 0);
private Point3D m_pU = new Point3D(0, 0, 0);
private double m_fInc;
public CoordinateSystem(Plane axAxis)
{
m_fInc = PlaneWidth / Me.ClientSize.Height;
Plane = axAxis;
}
public static void AssignMe(Form1 form) { Me = form; }
public Point3D U { get { return m_pU; } protected set { m_pU = value; } }
public Point3D V { get { return m_pV; } protected set { m_pV = value; } }
public Point3D Normal { get { return m_plane.Normal; } set { m_plane.Normal = value; } }
static double COSerror = 0.99619469809174553229501040247389;
public Plane Plane
{
get { return m_plane; }
set {
m_plane = value;
if (m_plane.dot(axisZ) > COSerror)
U = U.cross(m_plane, axisY);
else
U = U.cross(m_plane, axisZ);
U.div(U.norm());
V = U.cross(U, m_plane);
V.div(V.norm());
}
}
}
[DebuggerDisplayAttribute("x = {x}, y = {y}, z = {z}")]
public class Point3D
{
public double x, y, z;
public Point3D(double _x, double _y, double _z) { x = _x; y = _y; z = _z; }
public Point3D(Point3D p) { x = p.x; y = p.y; z = p.z; }
public Point3D() { x = 0; y = 0; z = 0; }
public bool Equals(Point3D p) { return x == p.x & y == p.y & z == p.z; }
public override bool Equals(object obj) { return Equals((Point3D)obj); }
public static bool operator ==(Point3D p1, Point3D p2) { return p1.Equals(p2); }
public static bool operator !=(Point3D p1, Point3D p2) { return !p1.Equals(p2); }
public static Point3D operator -(Point3D e, Point3D s) { return new Point3D(e.x - s.x, e.y - s.y, e.z - s.z); }
public static Point3D operator +(Point3D e, Point3D s) { return new Point3D(e.x + s.x, e.y + s.y, e.z + s.z); }
public static Point3D operator *(double m, Point3D v) { return new Point3D(m * v.x, m * v.y, m * v.z); }
public static Point3D operator *(Point3D v, double m) { return new Point3D(v.x / m, v.y / m, v.z / m); }
public static Point3D operator /(double m, Point3D v) { return new Point3D(m * v.x, m * v.y, m * v.z); }
public static Point3D operator /(Point3D v, double m) { return new Point3D(v.x / m, v.y / m, v.z / m); }
public static implicit operator Color(Point3D p) { return Color.FromArgb((int)p.x, (int)p.y, (int)p.z); }
public static implicit operator Point3D(Color c) { return new Point3D(c.R, c.G, c.B); }
//public override int GetHashCode()
//{
// unchecked
// {
// var hash = new SpookyHash();
// hash.Update(x);
// hash.Update(y);
// hash.Update(z);
// return hash.Final().GetHashCode();
// }
//}
// dot product (3D) which allows vector operations in arguments
public double dot(Point3D u, Point3D v) { return u.x * v.x + u.y * v.y + u.z * v.z; }
public double dot(Point3D u) { return u.x * x + u.y * y + u.z * z; }
public double norm(Point3D v) { return Math.Sqrt(dot(v, v)); } // norm = length of vector
public double norm() { return Math.Sqrt(dot(this, this)); } // norm = length of vector
public double dist(Point3D u, Point3D v) { return norm(u - v); } // distance = norm of difference
public double dist(Point3D u) { return norm(this - u); }
public Point3D cross(Point3D u, Point3D v) { return new Point3D(u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x); }
public Point3D cross(Point3D u) { return new Point3D(u.y * z - u.z * y, u.z * x - u.x * z, u.x * y - u.y * x); }
public void add(Point3D p) { x += p.x; y += p.y; z += p.z; }
public void mult(double m) { x *= m; y *= m; z *= m; }
public void div(double m) { x /= m; y /= m; z /= m; }
}
class Plane : Point3D
{
Point3D m_pNormal;
public Plane(Point3D pOrigin, Point3D pNormal) : base(pOrigin) { m_pNormal = pNormal; }
public Plane(Point3D p) : base(p) { }
public Plane(double x, double y, double z) : base(x, y, z) { }
public Point3D Normal { get { return m_pNormal; } set { m_pNormal = value; } }
public double PointToPlane(Point3D p) { return p.dot(Normal); }
}
private CoordinateSystem m_coordSys;
private CoordinateSystem Coord
{
get { return m_coordSys; }
set { m_coordSys = value; }
}
}
}
And more support code:
[DebuggerDisplayAttribute("{name}, R={color.R}, G={color.G}, B={color.B}")]
class FoundColors
{
public Color color = Color.Empty;
public string name = "";
public CIELab_Color cLab;
public Point3D pt;
public List<int> lClosest = new List<int>();
public int nFarthest;
public FoundColors(FoundColors fc)
{
color = fc.color;
name = fc.name;
cLab = new CIELab_Color(fc.cLab.CIE_L, fc.cLab.CIE_a, fc.cLab.CIE_b);
lClosest.AddRange(fc.lClosest);
nFarthest = fc.nFarthest;
}
public FoundColors() { }
}
The Invoke method does work if I immediately Thread.Sleep() for 200ms.
m_fp.Unlock();
this.Invoke((MethodInvoker)delegate () { pictureBox1.Image = m_fp.Bitmap; });
Thread.Sleep(200);
} while (true);
Haven't tested the lower limit, but it won't be consistent across machines, so reporting it won't be informative.
Open a new thread and create a while in of the function
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
workerThread.Start();
public void DoWork()
{
while (!_shouldStop)
{
//REFRESH YOUR IMAGE
}
}
Related
I want to instantiate GameObjects(specifically hexagonal tiles) at the hexagonalCoodinates(hexcoordinates).
For this I wrote a custom coordinate system.
But I found out that unity doesn't accept anything other than Vector3 or transform.
How do I make it do that?
Or is there a easier way to do this?
This is the method to generate the gameObjects
private void TouchCell(Vector3 point)//This method instantiates cubes
{
point = transform.InverseTransformPoint(point);
HexCoordinates coordinates = HexCoordinates.FromPosition(point);
Instantiate(cubes, coordinates, Quaternion.identity);//<-The coordinate variable here is a hex coordinate.
Debug.Log("Touched at:" + coordinates);
}
And This is the Hex coordinate generator:
public struct HexCoordinates
{
public int X { get; private set; }
public int Z { get; private set; }
public int Y { get
{
return -X - Z;
} }
public HexCoordinates(int x,int z)
{
X = x;
Z = z;
}
public static HexCoordinates FromOffsetCoordinates(int x,int z)
{
return new HexCoordinates(x-z/2, z);
}
public override string ToString()
{
return "("+X.ToString()+","+Y.ToString()+","+Z.ToString()+")";
}
public string ToStringOnSeperateLines()
{
return X.ToString() + "\n" +Y.ToString()+ "\n" + Z.ToString();
}
public static HexCoordinates FromPosition(Vector3 point)//This converts the Vector3 to Hex coords
{
float x = point.x / (HexMetrics.InnerRadius * 2f);
float y = -x;
float offset = point.z / (HexMetrics.OuterRadius * 3f);
x -= offset;
y -= offset;
int iX = Mathf.RoundToInt(x);
int iY = Mathf.RoundToInt(y);
int iZ = Mathf.RoundToInt(-x - y);
if (iX + iY + iZ != 0)
{
float dX = Mathf.Abs(x-iX);
float dY = Mathf.Abs(y - iY);
float dZ = Mathf.Abs(-x-y-iZ);
if(dX>dY&&dX>dZ)
{
iX = -iY - iZ;
}
else if(dZ>dY)
{
iZ = -iX - iY;
}
}
return new HexCoordinates(iX,iZ);
}
}
Just convert from your HexCoordinates to Vector3 using any way:
create method for HexCoordinates, something like public Vector3 ToVector3() {...}
create implicit operator for implicit cast to Vector3
public struct HexCoordinates
{
public int X { get; private set; }
public int Z { get; private set; }
public int Y => -X - Z;
public HexCoordinates(int x,int z)
{
X = x;
Z = z;
}
...
public static implicit operator Vector3(HexCoordinates coords)
{
Vector3 result = // convert to Vector3
// Vector3 result = ToVector3() -- or like this for code reuse
return result;
}
public Vector3 ToVector3()
{
Vector3 result = //convert to Vector3
return result;
}
}
And then you can extend Unity's Object class and add overloading for Instantiate() method that will accept HexCoordinates, convert to Vector3 and call Instantiate()
public static class ObjectExtension
{
public static void Instantiate(this Object obj, Object origin, HexCoordinates coords, Quaternion q)
{
Vector3 position = coords.ToVector3();
obj.Instantiate(origin, position, q);
}
}
Also if you create implicit cast for your HexCoordinates to Vector3 you don't need to create overloading for Instantiate() method because converting will be implicitly
You are using using catlike coding's code. (This would have been helpful to mention in the question ;) ). In part 3 of the tutorial featuring this hex coordinate system, you can see how they would do something like below, accessing a hex inside of an array by calculating an index:
public HexCell GetCell (Vector3 position) {
position = transform.InverseTransformPoint(position);
HexCoordinates coordinates = HexCoordinates.FromPosition(position);
int index = coordinates.X + coordinates.Z * width + coordinates.Z / 2;
return cells[index];
}
So, since a HexCell has a transform.position, you can use that to get its center (making sure you don't access out of bounds):
private void TouchCell(Vector3 point)
{
point = transform.InverseTransformPoint(point);
HexCoordinates coordinates = HexCoordinates.FromPosition(point);
int index = coordinates.X + coordinates.Z * width + coordinates.Z / 2;
if (index >=0 && index < cells.Length)
{
Vector3 worldPos = cells[index].transform.position;
Instantiate(cubes, worldPos, Quaternion.identity);
Debug.Log("Touched at:" + coordinates);
}
}
Better yet, it may be worthwhile to make a method to retrieve this index, for the sake of code reuse:
private bool IsValidCellIndex(Vector3 point, out int index)
{
point = transform.InverseTransformPoint(point);
HexCoordinates coordinates = HexCoordinates.FromPosition(point);
index = coordinates.X + coordinates.Z * width + coordinates.Z / 2;
return index >=0 && index < cells.Length;
}
private void TouchCell(Vector3 point)
{
if (IsValidCellIndex(point, out int index))
{
Vector3 worldPos = cells[index].transform.position;
Instantiate(cubes, worldPos, Quaternion.identity);
Debug.Log("Touched at:" + worldPos);
}
}
Or, just use GetCell as the tutorial does :)
In Unity 3D, I am trying to build a Dictionary of PathNodes keyed by NodeCoordinates. I have overridden GetHashCode in NodeCoordinate and it should return a constant unique value. If I loop through the keys of the dictionary, the lookup works fine, but if I create a new NodeCoordinate with the coordinates of a PathNode that should exist, the lookup fails even though the hash codes are equal.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PathNode : MonoBehaviour {
public static Dictionary<NodeCoordinate, PathNode> pathNodes;
public PathNode left;
public PathNode right;
public PathNode forward;
public PathNode backward;
private NodeCoordinate coord;
void Awake()
{
if (PathNode.pathNodes == null)
{
PathNode.pathNodes = new Dictionary<NodeCoordinate, PathNode>();
}
NodeCoordinate coord = new NodeCoordinate(transform.position.x, transform.position.z);
this.coord = coord;
PathNode.pathNodes.Add(coord, this);
NodeCoordinate leftChord = new NodeCoordinate(coord.x - 1, coord.z);
NodeCoordinate rightChord = new NodeCoordinate(coord.x + 1, coord.z);
NodeCoordinate forwardChord = new NodeCoordinate(coord.x, coord.z + 1);
NodeCoordinate backwardChord = new NodeCoordinate(coord.x, coord.z - 1);
if (PathNode.pathNodes.ContainsKey(leftChord))
{
this.left = PathNode.pathNodes[leftChord];
this.left.right = this;
}
if (PathNode.pathNodes.ContainsKey(rightChord))
{
this.right = PathNode.pathNodes[rightChord];
this.right.left = this;
}
if (PathNode.pathNodes.ContainsKey(forwardChord))
{
this.forward = PathNode.pathNodes[forwardChord];
this.forward.backward = this;
}
if (PathNode.pathNodes.ContainsKey(backwardChord))
{
this.backward = PathNode.pathNodes[backwardChord];
this.backward.forward = this;
}
}
private static bool debug = true;
void Update()
{
if (debug)
{
foreach (NodeCoordinate coord in PathNode.pathNodes.Keys)
{
Debug.Log(coord + " : " + PathNode.pathNodes[coord] + " : " + coord.GetHashCode());
}
foreach (PathNode node in PathNode.pathNodes.Values)
{
NodeCoordinate leftChord = new NodeCoordinate(node.coord.x - 1, node.coord.z);
PathNode leftNode;
Debug.Log("Left: " + leftChord + " : " + PathNode.pathNodes.TryGetValue(leftChord, out leftNode) + " : " + leftChord.GetHashCode());
}
debug = false;
}
}
}
public class NodeCoordinate
{
public float x;
public float z;
public NodeCoordinate(float x, float z)
{
this.x = x;
this.z = z;
}
public bool Equals(NodeCoordinate coord)
{
return (this.x == coord.x && this.z == coord.z);
}
public override int GetHashCode()
{
return string.Format("{0}x{1}", this.x, this.z).GetHashCode();
}
public override string ToString()
{
return "Coordinate: " + this.x + " x " + this.z;
}
}
This is the output from my little debug:
debug log
As you can see, when looping through the keys, the lookups with hashcodes 2137067561 and 1824497336 work, but when I instantiate a new NodeCoordinate and try to look it up, it has the same hashcode but the lookup fails. Any idea why this is happening? Thanks.
The problem is that your NodeCoordinate class doesn't define equality in a way that the dictionary would use. You have a method like this:
public bool Equals(NodeCoordinate coord)
... but you neither override IEquatable<NodeCoordinate> nor do you override Equals(object).
Personally I'd suggest doing both - and implementing a simpler hash code that doesn't require string formatting:
public sealed class NodeCoordinate : IEquatable<NodeCoordinate>
{
public float X { get; }
public float Z { get; }
public NodeCoordinate(float x, float z)
{
X = x;
Z = z;
}
public override Equals(object other) => Equals(other as NodeCoordinate);
public bool Equals(NodeCoordinate coord) =>
coord != null && this.X == coord.X && this.Z == coord.Z;
public override int GetHashCode()
{
int hash = 23;
hash = hash * 31 + X;
hash = hash * 31 + Z;
return hash;
}
public override string ToString() => $"Coodinate: {X} x {Z}";
}
(Note that I've also made it immutable and used properties instead of public fields. I've used C# 6 syntax for simplicity, but it wouldn't be hard to translate to C# 5 if necessary.)
So for some reason, when I add a IEqualityComparer with the exact same logic, it works.
Changed the declaration of the dictionary to this:
if (PathNode.pathNodes == null)
{
PathNode.pathNodes = new Dictionary<NodeCoordinate, PathNode>(new NodeCoordinateComparer());
}
Added this:
public class NodeCoordinateComparer : IEqualityComparer<NodeCoordinate>
{
public bool Equals(NodeCoordinate a, NodeCoordinate b)
{
return (a.x == b.x && a.z == b.z);
}
public int GetHashCode(NodeCoordinate coord)
{
return string.Format("{0}x{1}", coord.x, coord.z).GetHashCode();
}
}
Here is the core of my code. I've tried Invoke every which way to China, but I always get the same big red X and an ObjectDisposed exception on Form1. (Edited out unrelated code for brevity.)
using System;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using KnownColorsPalette;
namespace Color_Visualizer
{
public partial class Form1 : Form
{
static CultureInfo m_culture = CultureInfo.CurrentCulture;
FastPixel m_fp; // FastPixel encapsulates
// Bitmap.LockBits() funcs & data
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
double fAngle, fRadius, d;
Point3D vU, vV;
Point pLocation = new Point();
do
{
m_pNormal = Coord.Plane.Normal;
fAngle = Math.Atan2(m_pNormal.y, m_pNormal.x);
fRadius = Math.Sqrt(m_pNormal.x * m_pNormal.x + m_pNormal.y * m_pNormal.y);
fAngle += fSpeed * 180 / Math.PI;
m_pNormal.x = Math.Cos(fAngle) * fRadius;
m_pNormal.y = Math.Sin(fAngle) * fRadius;
m_fp.Lock();
m_fp.Clear(Color.Black);
foreach (FoundColors fc in m_lColors.Values)
{
vU = new Point3D(Coord.U);
d = dist(fc.pt, ref vU);
vV = Coord.V;
vV.mult(d);
pLocation.X = (int)(m_midHoriz + vU.norm());
pLocation.Y = (int)(m_midVert + vV.norm());
m_fp.SetPixel(pLocation, fc.color);
}
m_fp.Unlock();
Invoke((MethodInvoker)delegate { pictureBox1.Image = m_fp.Bitmap; });
} while (true);
}
public Form1()
{
InitializeComponent();
WindowState = FormWindowState.Maximized;
CoordinateSystem.AssignMe(this);
}
void ReadColors() // I saved all of Wikipedia's 1200+ named colors
{ // as a text file.
}
private void Form1_Load(object sender, EventArgs e)
{
ReadColors();
Point3D p = new Point3D(127.5, 127.5, 127.5);
foreach (FoundColors fc in m_lColors.Values)
fc.pt = fc.color - p; // My Point3D class has
// implicit operator casts to and
// from Color.
Coord = new CoordinateSystem(new Plane(new Point3D(-127.5, -127.5, -127.5), new Point3D(-1, 0, 0)));
backgroundWorker1.RunWorkerAsync();
}
double fSpeed = 5;
Point3D m_pNormal = new Point3D();
double m_fDist, m_fDot;
public double dist(Point3D pt, ref Point3D vU)
{
double c1 = pt.dot(vU);
double c2 = vU.dot(vU);
double b = c1 / c2;
vU.mult(b);
//m_fDot = pt.dot(Coord.Normal);
m_fDist = pt.norm(pt - vU);
return m_fDist;
}
double m_midHoriz, m_midVert;
private void Form1_Resize(object sender, EventArgs e)
{
m_midHoriz = pictureBox1.Width / 2;
m_midVert = pictureBox1.Height / 2;
m_fp = new FastPixel(new Bitmap(pictureBox1.Width, pictureBox1.Height));
}
}
}
This is just support code, not central to my question:
Sorting.cs
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using KnownColorsPalette;
namespace Color_Visualizer
{
public partial class Form1 : Form
{
public static ColorComp m_compClr = new ColorComp();
public static NameComp m_compName = new NameComp();
SortedList<Color, FoundColors> m_lColors = new SortedList<Color, FoundColors>(m_compClr);
SortedList<string, FoundColors> m_lColorByName = new SortedList<string, FoundColors>(m_compName);
[DebuggerDisplayAttribute("{name}, R={color.R}, G={color.G}, B={color.B}")]
class FoundColors
{
public Color color = Color.Empty;
public string name = "";
public CIELab_Color cLab;
public Point3D pt;
public List<int> lClosest = new List<int>();
public int nFarthest;
public FoundColors(FoundColors fc)
{
color = fc.color;
name = fc.name;
cLab = new CIELab_Color(fc.cLab.CIE_L, fc.cLab.CIE_a, fc.cLab.CIE_b);
lClosest.AddRange(fc.lClosest);
nFarthest = fc.nFarthest;
}
public FoundColors() { }
}
struct sort
{
public double dist;
public int index;
public sort(double _d, int _i) { dist = _d; index = _i; }
}
class DistComp : IComparer<sort>
{
int IComparer<sort>.Compare(sort x, sort y)
{
if ((object)x == null)
if ((object)y == null)
return 0;
else
return -1;
if ((object)y == null) return 1;
if (x.dist > y.dist) return -1;
return 1;
}
}
public class NameComp : IComparer<string>
{
int IComparer<string>.Compare(string x, string y)
{
if ((object)x == null)
if ((object)y == null)
return 0;
else
return -1;
if ((object)y == null) return 1;
return x.CompareTo(y);
}
}
public class ColorComp : IComparer<Color>
{
int IComparer<Color>.Compare(Color x, Color y)
{
if ((object)x == null)
if ((object)y == null)
return 0;
else
return -1;
if ((object)y == null) return 1;
if (x.R > y.R)
return -1;
else if (x.R < y.R)
return 1;
else if (x.G > y.G)
return -1;
else if (x.G < y.G)
return 1;
else if (x.B > y.B)
return -1;
else if (x.B < y.B)
return 1;
return 0;
}
}
}
}
And lastly some more support code, CoordinateSystem.cs:
using System;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
namespace Color_Visualizer
{
public partial class Form1 : Form
{
class CoordinateSystem
{
const int MAX = 256;
const double PlaneWidth = 600;
static Form1 Me;
static Point3D axisZ = new Point3D(0, 0, 1);
static Point3D axisY = new Point3D(0, 1, 0);
private Plane m_plane = new Plane(new Point3D(128, 128, 128), new Point3D(-128, 0, 0));
private Point3D m_pV = new Point3D(0, 0, 0);
private Point3D m_pU = new Point3D(0, 0, 0);
private double m_fInc;
public CoordinateSystem(Plane axAxis)
{
m_fInc = PlaneWidth / Me.ClientSize.Height;
Plane = axAxis;
}
public static void AssignMe(Form1 form) { Me = form; }
public Point3D U { get { return m_pU; } protected set { m_pU = value; } }
public Point3D V { get { return m_pV; } protected set { m_pV = value; } }
public Point3D Normal { get { return m_plane.Normal; } set { m_plane.Normal = value; } }
static double COSerror = 0.99619469809174553229501040247389;
public Plane Plane
{
get { return m_plane; }
set {
m_plane = value;
if (m_plane.dot(axisZ) > COSerror)
U = U.cross(m_plane, axisY);
else
U = U.cross(m_plane, axisZ);
U.div(U.norm());
V = U.cross(U, m_plane);
V.div(V.norm());
}
}
}
[DebuggerDisplayAttribute("x = {x}, y = {y}, z = {z}")]
public class Point3D
{
public double x, y, z;
public Point3D(double _x, double _y, double _z) { x = _x; y = _y; z = _z; }
public Point3D(Point3D p) { x = p.x; y = p.y; z = p.z; }
public Point3D() { x = 0; y = 0; z = 0; }
public bool Equals(Point3D p) { return x == p.x & y == p.y & z == p.z; }
public override bool Equals(object obj) { return Equals((Point3D)obj); }
public static bool operator ==(Point3D p1, Point3D p2) { return p1.Equals(p2); }
public static bool operator !=(Point3D p1, Point3D p2) { return !p1.Equals(p2); }
public static Point3D operator -(Point3D e, Point3D s) { return new Point3D(e.x - s.x, e.y - s.y, e.z - s.z); }
public static Point3D operator +(Point3D e, Point3D s) { return new Point3D(e.x + s.x, e.y + s.y, e.z + s.z); }
public static Point3D operator *(double m, Point3D v) { return new Point3D(m * v.x, m * v.y, m * v.z); }
public static Point3D operator *(Point3D v, double m) { return new Point3D(v.x / m, v.y / m, v.z / m); }
public static Point3D operator /(double m, Point3D v) { return new Point3D(m * v.x, m * v.y, m * v.z); }
public static Point3D operator /(Point3D v, double m) { return new Point3D(v.x / m, v.y / m, v.z / m); }
public static implicit operator Color(Point3D p) { return Color.FromArgb((int)p.x, (int)p.y, (int)p.z); }
public static implicit operator Point3D(Color c) { return new Point3D(c.R, c.G, c.B); }
//public override int GetHashCode()
//{
// unchecked
// {
// var hash = new SpookyHash();
// hash.Update(x);
// hash.Update(y);
// hash.Update(z);
// return hash.Final().GetHashCode();
// }
//}
// dot product (3D) which allows vector operations in arguments
public double dot(Point3D u, Point3D v) { return u.x * v.x + u.y * v.y + u.z * v.z; }
public double dot(Point3D u) { return u.x * x + u.y * y + u.z * z; }
public double norm(Point3D v) { return Math.Sqrt(dot(v, v)); } // norm = length of vector
public double norm() { return Math.Sqrt(dot(this, this)); } // norm = length of vector
public double dist(Point3D u, Point3D v) { return norm(u - v); } // distance = norm of difference
public double dist(Point3D u) { return norm(this - u); }
public Point3D cross(Point3D u, Point3D v) { return new Point3D(u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x); }
public Point3D cross(Point3D u) { return new Point3D(u.y * z - u.z * y, u.z * x - u.x * z, u.x * y - u.y * x); }
public void add(Point3D p) { x += p.x; y += p.y; z += p.z; }
public void mult(double m) { x *= m; y *= m; z *= m; }
public void div(double m) { x /= m; y /= m; z /= m; }
}
class Plane : Point3D
{
Point3D m_pNormal;
public Plane(Point3D pOrigin, Point3D pNormal) : base(pOrigin) { m_pNormal = pNormal; }
public Plane(Point3D p) : base(p) { }
public Plane(double x, double y, double z) : base(x, y, z) { }
public Point3D Normal { get { return m_pNormal; } set { m_pNormal = value; } }
public double PointToPlane(Point3D p) { return p.dot(Normal); }
}
private CoordinateSystem m_coordSys;
private CoordinateSystem Coord
{
get { return m_coordSys; }
set { m_coordSys = value; }
}
}
Only the 1st code segment is genuinely relevant to the question, but I know someone will ask for it, so I included much of the supporting code.
Note that I have also tried such things as diverse as the ProgressChanged event (after enabling it in Properties of course) and various forms of delegates. This use to be a fairly simple matter with old delegates, but I spent 10 hours today with no success, and I almost never fail to find working code examples, even if I have to wade thru dozens of inferior answers. There is an utter profusion of contradictory answers to this question depending on the date of the post and the kind of approach suggested.
The Invoke method does work if I immediately Thread.Sleep() for 200ms. Haven't tested the lower limit, but it won't be consistent across machines, so reporting it won't be informative.
Update this code
...
m_fp.Unlock();
var capturedBitmap = m_fp.Bitmap.Clone();
Invoke((MethodInvoker)delegate { pictureBox1.Image = capturedBitmap; });
...
You are probably getting the red x because you are modifying the bitmap as you assign it to the picture box. Clone the bitmap so you are not playing with the one in your picturebox.
I'm trying to create a find method from scratch to see if two objects are equal given that the results of certain methods are equal, using the Equals method to do so. I know using the Find/Contains methods would be faster, but I'm not allowed use them. The signature of the method is "static int Find(List c, Coffee x)" Find seeks x in c and returns a valid index (e.g., 0, 1) if x exists in c, returns -1 otherwise. The equals method must be used to determine equivalency. If the passed object isn't equal to an object currently in the list, it is added to the list (the list contains two types of objects that derive from a base class, so the list can store both types). Equivalency is defined by name, cost, demand, holding cost(h) and roasttype(M) for regular and name, cost, demand, holding cost(h) and minimum quantity(also M) for decaf. Here's what I have so far (it's a lot of code that could probably be written better):
class EOQCalculator4
{
static void Main(string[] args)
{
// Create objects and references
Coffee obv = new Coffee();
Decaf decafCoffee = null;
Regular regularCoffee = null;
List<Coffee> inventory = new List<Coffee>();
// Prompt user for input and store it as a string
Console.Write("Enter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast ");
string s = Console.ReadLine();
// Loop
while (!s.ToLower().Equals("q"))
{
// Split string up and assign componets to variables
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string name = values[0];
string demand = (values[1]);
string cost = (values[2]);
string type = values[3];
// Check for > 0 and convert to numbers
float D = CheckDemand(demand);
float C = CheckCost(cost);
float M = 0;
if (type.StartsWith("D:"))
{
type = Regex.Match(type, #"\d+").Value;
M = CheckMin(type);
decafCoffee = new Decaf(name, D, C, M);
inventory.Add(decafCoffee);
}
else if (type.StartsWith("R:"))
{
if (type.Contains("light"))
{
M = 1;
regularCoffee = new Regular(name, D, C, M);
inventory.Add(regularCoffee);
}
else if (type.Contains("medium"))
{
M = 2;
regularCoffee = new Regular(name, D, C, M);
inventory.Add(regularCoffee);
}
else if (type.Contains("dark"))
{
M = 3;
regularCoffee = new Regular(name, D, C, M);
inventory.Add(regularCoffee);
}
else Console.WriteLine("\nError, please enter all lower case \"dark\", \"medium\", or \"light\" next time.");
}
else Console.WriteLine("\nError, please enter either \"D:\" followed by a number or \"R:\" followed by roast type next time.");
Console.Write("\nEnter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast: ");
s = Console.ReadLine();
} // End loop
// Sort and display values
var sortedList = inventory.OrderBy(i => i.Q()).ToList();
Console.WriteLine("\nName \t C ($) Demand \t Detail Q(lbs.) TAC ($) T(weeks) ");
for (int j = 0; j < inventory.Count; j++)
{
Console.WriteLine("{0}", sortedList[j].toString());
}
Console.WriteLine(obv.toStringQ());
}
#region CheckMethods
// Data validation methods
public static float CheckDemand(String R)
{
float number;
while (!float.TryParse(R, out number) || number <= 0)
{
Console.Write("Please enter a number greater than 0 for demand: ");
R = Console.ReadLine();
} return number;
}
public static float CheckCost(String R)
{
float number;
while (!float.TryParse(R, out number) || number <= 0)
{
Console.Write("Please enter a number greater than 0 for cost: ");
R = Console.ReadLine();
} return number;
}
public static float CheckMin(String R)
{
float number;
while (!float.TryParse(R, out number) || number <= 0)
{
Console.Write("Please enter a number greater than 0 for minimum quantity: ");
R = Console.ReadLine();
} return number;
}
public class Coffee
{
// Members
private static float sumQ = 0;
private static int mcount;
private float k = 20;
private float mc;
private string mName;
private float md;
private float q;
private float mh;
private float tac;
private float min = 0;
private float type = 0;
Coffee i = new Coffee();
public override bool Equals(object obj)
{
if (obj is Coffee)
{
bool isNameEqual = i.Name.Equals(this.Name);
bool isuCostEqual = i.Cost.Equals(this.Cost);
bool isDemandEqual = i.Demand.Equals(this.Demand);
bool ishCostEqual = i.h.Equals(this.h);
bool isMinEqual = i.getMin.Equals(this.min);
return (isNameEqual && isuCostEqual && isDemandEqual && ishCostEqual && isMinEqual);
}
return false;
}
// Default Constructor
public Coffee()
{ mcount = 0; }
// Full Constructor
public Coffee(string Name, float d, float c, float m)
{
mName = Name;
md = d;
mc = c;
mh = (float).30 * mc;
type = m;
min = m;
mcount++;
}
public Coffee(string Name, float d, float c)
{
mName = Name;
md = d;
mc = c;
mh = (float).30 * mc;
mcount++;
}
// Copy Constructor
public Coffee(Coffee e)
{
this.mName = e.mName;
this.md = e.md;
this.mh = e.mh;
this.mc = e.mc;
this.q = e.q;
mcount++;
}
// Destructor
~Coffee()
{ mcount--; }
// Properties
#region Properties
public float getMin
{
get { return min; }
}
public float getType
{
get { return type; }
}
public string Name
{
get { return mName; }
}
public float h
{
get { return mh; }
}
public float Cost
{
get { return mc; }
}
public float Demand
{
get { return md; }
}
public float getQ
{
get { return q; }
}
public float K
{
get { return k; }
}
public float getSumQ
{
get { return sumQ; }
set { sumQ = value; }
}
#endregion
// Methods
public virtual float Q()
{
q = (float)Math.Sqrt(2 * md * k / mh);
sumQ += q;
return q;
}
public virtual float TAC()
{
tac = q / 2 * mh + md * k / q + md * mc;
return tac;
}
public virtual float T()
{
float t = (q / (md / 52));
return t;
}
public virtual string toString()
{
string a = String.Format("{0,-10:s} {1,-10:f2} {2,-13:f0} {3,-11:f0} {4,-11:f2} {5,-0:f2}", mName, mc, md, Q(), TAC(), T());
return a;
}
public virtual string toStringQ()
{
string c = String.Format("\nIf you purchase all of the coffee you will need space to hold {0,-0:f2} of coffee", sumQ);
return c;
}
}
}
public class Decaf : Coffee
{
// Members
private float k = 30;
private float min;
private float q;
// Constructor
public Decaf(string Name, float d, float c, float m)
: base(Name, d, c)
{
min = m;
}
// Methods
public override float Q()
{
q = (float)Math.Sqrt(2 * Demand * k / h);
if (q < min)
{
return min;
}
else return q;
}
public override float TAC()
{
getSumQ += Q();
return Q() / 2 * h + Demand * k / Q() + Demand * Cost;
}
public override float T()
{
return (Q() / (Demand / 52));
}
public override string toString()
{
string a = String.Format("{0,-11:s}{1,-11:f2}{2,-12:f0}{3,-9:f0}{4,-12:f0}{5,-13:f2}{6,-10:f2}", Name, Cost, Demand, min, Q(), TAC(), T());
return a;
}
}
}
// Enumerator
[Flags] enum RoastType { light = 1, medium = 2, dark = 3 }
public class Regular : Coffee
{
// Members
RoastType roast;
private float q;
private float k = 20;
// Constructor
public Regular(string Name, float d, float c, float r)
: base(Name, d, c)
{
int x = (int) r;
roast = (RoastType) x;
roast.ToString();
}
// Methods
public override float Q()
{
q = (float)Math.Sqrt(2 * Demand * k / h);
return q;
}
public override float TAC()
{
getSumQ += Q();
return Q() / 2 * h + Demand * k / Q() + Demand * Cost;
}
public override float T()
{
return (Q() / (Demand / 52));
}
public override string toString()
{
string b = String.Format("{0,-11:s}{1,-11:f2}{2,-12:f0}{3,-9:s}{4,-12:f0}{5,-13:f2}{6,-10:f2}", Name, Cost, Demand, roast.ToString(), Q(), TAC(), T());
return b;
}
}
}
Assuming I implemented the equals method correctly, where/how would I implement the "static int Find(List<Coffee> c, Coffee x)" method?
As it stands your overridden Equals method won't work correctly. Equals tests for reference equality i.e. if two object references point to the same object. See MSDN for more info on Equals.
If you are just wanting to make sure that the same two coffees (with the same name, demand cost and type) are not added, then you can perform a simple value check on those fields, something like (method added to your Coffee class)
public bool CoffeeIsSame(Coffee c2)
{
return (this.Name == c2.Name) && (this.Demand == this.Demand) && (this.Cost == c2.Cost) && (this.Type == c2.Type);
}
Your Find method could look something like this:
static bool Find(List c, Coffee x)
{
bool result = false;
foreach(Coffee coffee in c)
{
result = coffee.CoffeeIsSame(x);
if (result)
{
break;
}
}
return result;
}
To implement your static Find method, you could add it to your Coffee class. Then you call it like this (using some of your code from your Main method as an example):
...
else if (type.Contains("dark"))
{
M = 3;
regularCoffee = new Regular(name, D, C, M);
if (!Coffee.Find(inventory, regularCoffee))
{
inventory.Add(regularCoffee);
}
}
...
Hope that helps,
cheers
Was a bit shocked to discover that System.Drawing.PointF appears to have operators for subtracting sizes but not other PointFs. So I'm trying to write my own PointF class, but it needs to be able to have System.Drawing.Points automatically converted to it, or it really doesn't add any convenience. So I wrote these constructors:
public PointF(float x = 0, float y = 0)
{
this.x = x;
this.y = y;
}
public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }
But I'm still getting this error:
cannot convert from 'System.Drawing.Point' to 'my_namespace.PointF'
(I have a function that accepts a my_namespace.PointF but I'm passing in a System.Drawing.Point).
Shouldn't the 3rd constructor kick in and auto-convert it?
Do you have an implicit conversion defined in your my_namespace.PointF class? It won't automatically convert otherwise.
public PointF(float x = 0, float y = 0)
{
this.x = x;
this.y = y;
}
public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }
//add this:
public static implicit operator PointF(System.Drawing.Point pt)
{ return new PointF(pt); }
Have you considered the option of writing an 'extension method' instead of rolling out your own class ?
You can't have operator overloading per se via extn. methods (proposed in next revision of the framework).. but you should be able to use a synonymous method called Add() for + and get by.
This compiles for me:
class PointF {
float x; float y;
public PointF(float x, float y)
{
this.x = x;
this.y = y;
}
public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }
public static implicit operator PointF(System.Drawing.Point pt) { return new PointF(pt); }
public static implicit operator PointF(System.Drawing.PointF pt) { return new PointF(pt); }
}
//....
static void test(pointf.PointF p) {
}
//....
test(new System.Drawing.PointF(1, 1));