What is the problem with my midpoint algorithm? - processing

I just started to learn processing and I have a few problems that I couldn't solve. I hope someone could help me. This should draw lines where i could choose the starting and finishing points with mousePressed(), but I failed before trying implementing that.
//int x1, x2, y1, y2;
void setup() {
size(640, 480);
}
void draw() {
midpoint(0, 0, 100, 100);
}
//void mousePressed() {
// pmouseX =x1;
// pmouseY =y1;
// mouseX =x2;
// mouseY =y2;
//}
void midpoint(int x1, int y1, int x2, int y2) {
int dx, dy, d, x, y;
dx = x2-x1;
dy = y2-y1;
d = 2*dy-dx;
x = x1;
y = y1;
for (int i = 1; i <dx; i++) {
point(x, y);
if (d>0) {
y++;
d+=2*(dy-dx);
} else {
d+=2*dy;
}
x++;
}
}
My problem is that it will not always draw the line.
e.g.
midpoint(0,0,100,100);
it will draw it
midpoint(100,100,0,0);
it draws nothing.
It should draw the same line if I exchange the points coordinates, or draw a single point if the coordinates are the same.

In Bresenham's midpoint line algorithm you have to be careful with the gradient of the line drawn, the base algorithm you described only works for gradients between 0 and 1. In order to deal with gradients that are steeper (m > 1 or m < -1), you have to switch the roles of the x and y values, therefore you have to step in y and then calculate x. Also to deal with negative steps just switch the point order.
void midpoint(int x1, int y1, int x2, int y2) {
// Is gradient of line greater than 1
boolean steep = abs(y2-y1) > abs(x2-x1);
int temp;
if (steep) { // If gradient > 1
// Swap roles of x and y components to step in y instead
temp = y1;
y1 = x1;
x1 = temp;
temp = y2;
y2 = x2;
x2 = temp;
}
if (x2 < x1) {
// Swap points such that step in x is positive
temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
// Change in x and y which are now both positive
int dx = x2 - x1;
int dy = abs(y2 - y1);
// Step in y
int sy = y2 > y1 ? 1 : -1;
int y = y1;
// Decision variable
int d = 2*dy-dx;
// Small step in x
for (int x=x1; x<=x2; x++) {
// Depending on gradient plot x and y
if (steep) {
point(y, x);
} else {
point(x, y);
}
// Update decision parameter
if (d>0) {
y += sy;
d+=2*(dy-dx);
}else{
d+=2*dy;
}
}
}

Related

Drawing two parallel lines with a certain distance away

I made a program that creates parallel lines from the mouse coordinates with a certain distance away which can be modified by the distance variable at the beginning of the code. The problem is that it does not work as it should when drawing.
Line 1 and Line 2 are the lines that are parallel to the line formed from the mouse coordinates, the "pointSlope" variable.
distance = 30
function setup() {
createCanvas(600, 600);
}
function draw() {
lineCreate([pmouseX,pmouseY], [mouseX,mouseY])
}
function lineCreate(point1, point2) {
fill(0)
stroke(0)
x0 = point1[0];
x1 = point2[0];
y0 = point1[1];
y1 = point2[1];
if (abs(x1 - x0) > abs(y1 - y0)) {
if (x0 > x1) {
let t = x0; x0 = x1; x1 = t;
t = y0; y0 = y1; y1 = t;
}
for (let x = x0; x <= x1; x++) {
let slope = (y1-y0) * (x-x0) / (x1-x0)
let y = y0 + (y1-y0) * (x-x0) / (x1-x0);
line1 = y + distance*Math.sqrt(1+pow(slope,2))
line2 = y - distance*Math.sqrt(1+pow(slope,2))
circle(x, line1, 2, 2);
circle(x, line2, 2, 2);
}
} else {
if (y0 > y1) {
let t = x0; x0 = x1; x1 = t;
t = y0; y0 = y1; y1 = t;
}
for (let y = y0; y <= y1; y++) {
let x = x0 + (x1-x0) * (y-y0) / (y1-y0);
circle(x, y, 2, 2);
}
}
}
I think that using vectors may help you in this situation, try this code as example:
let dist = 40;
function setup() {
createCanvas(600, 600);
v = createVector();
noStroke();
}
function draw() {
lineCreate();
}
function lineCreate() {
v.x = mouseX-pmouseX; v.y = mouseY-pmouseY;
h = v.heading();
LX = dist*cos(h+PI/2); LY = dist*sin(h+PI/2);
RX = dist*cos(h-PI/2); RY = dist*sin(h-PI/2);
for (let i=0; i<v.mag(); i++) {
fill(0).circle(pmouseX+i*cos(h),pmouseY+i*sin(h),2);
fill(160).circle(pmouseX+LX+i*cos(h),pmouseY+LY+i*sin(h),2);
fill(160).circle(pmouseX+RX+i*cos(h),pmouseY+RY+i*sin(h),2);
}
}
Here we are drawing two parallel lines in road-like path, but as you can see there are gaps in turns caused by using pmouse. I think, that it will not be possible to get rid of these artifacts, if you not move away from using the pmouse to more complex ways of calculating the trajectory.

Is there a way to move lines from one place to another randomly?

Actually I'm trying to convert this JavaScript code to processing code. But got stuck.
var leftToRight = Math.random() >= 0.5;
if(leftToRight) {
context.moveTo(x, y);
context.lineTo(x + width, y + height);
} else {
context.moveTo(x + width, y);
context.lineTo(x, y + height);
}
context.stroke();
This is what I came up with and I know its fundamentally wrong but there must be a way. If anyone can at least point me in the right direction it would be great.
void draw() {
line(x1, y1, x2, y2);
for(int i = 0; i < 1000; i++) {
if(x1 == 0) {
x1 = width;
y1 = 0;
x2 = 0;
y2 = height;
line(x1, y1, x2, y2);
} else if(x1 == width) {
x1 = 0;
y1 = 0;
x2 = width;
y2 = height;
line(x1, y1, x2, y2);
}
}
Due to the nature of your question, it was difficult to assume what exactly you needed answered. For simplicity's sake, I assume you want the Java code converted to Processing. Hence, I will be ignoring what you wrote in your second code snippet.
The Java code essentially does the following:
Generates a random number from 0.0 to 1.0
Chooses one output based on whether the number is greater than 0.5:
Creates a line from (x, y) to (x + width, y + height) or
Creates a line from (x + width, y) to (x, y + height).
Here's a sample of Processing code that may assist you in this. This code is very close to that of the Java snippet you provided, as that is what you asked for.
int x = 0, y = 0;
if(random(0, 1) > 0.5) line(x, y, x + width, y + height);
else line(x + width, y, x, y + height);
When run, the canvas will show either this:
or this:
I hope this helps.

How to rotate a square in processing?

I've been trying to rotate a square for a project, I've done research and think I have the right formula to calculate the rotated points. I calculate the points as if they're individual around the center of the square. How to fix it?
//Declaring variables
float x0, y0, xo, yo,x1,y1,x2,y2,x3,y3, theta, newx, newy, s, c;
void setup() {
size (800,800);
//To debug
//frameRate(1);
fill(0);
//Initializing variables
xo = 400;
yo = 400;
x0 = 350;
y0 = 450;
x1 = 350;
y1 = 350;
x2 = 450;
y2 = 350;
x3 = 450;
y3 = 450;
theta = radians(5);
s = sin(theta);
c = cos(theta);
}
void draw() {
//Reseting the background
background(255);
//Drawing the square
quad(x0,y0,x1,y1,x2,y2,x3,y3);
//Doing the rotations
x0 = rotateX(x0,y0);
y0 = rotateY(x0,y0);
x1 = rotateX(x1,y1);
y1 = rotateY(x1,y1);
x2 = rotateX(x2,y2);
y2 = rotateY(x2,y2);
x3 = rotateX(x3,y3);
y3 = rotateY(x3,y3);
}
//Rotate x coordinate method
float rotateX(float x, float y) {
x -= xo;
newx = x * c - y * s;
x = newx + xo;
return x;
}
//Rotate y coordinate method
float rotateY(float x, float y) {
y -= yo;
newy = x * s - y * c;
y = newy + yo;
return y;
}
There are two things:
1) You have a sign error in rotateY(). The y term should have a positive sign:
newy = x * s + y * c;
2) When you do this:
x0 = rotateX(x0,y0);
y0 = rotateY(x0,y0);
... then the first call modifies x0, which the second call then uses. But the second call needs the original coordinates to rotate correctly:
float x0Rotated = rotateX(x0, y0);
y0 = rotateY(x0, y0);
x0 = x0Rotated;
The same thing for the other points.

Moving along Bezier Curve in processing

My code for the ball moving in a Bezier Curve from start to the middle of the curve is:
void ballMove()
{
if(y[0]==height*1/10)
{
bezier (x[0], y[0],x[1], y[1], x[2], y[2], x[3], y[3]);
float x0; float x1; float x2; float x3;
float y0; float y1; float y2; float y3;
x0 = x[0]; x1 = x[1]; x2 = x[2]; x3 = x[3];
y0 = y[0]; y1 = y[1]; y2 = y[2]; y3 = y[3];
float t = (frameCount/100.0)%1;
float x = bezierPoint(x0, x1, x2, x3, t);
float y = bezierPoint( y0, y1, y2, y3, t);
if(t>=0.5)
{
t=0;
}
while(t==0.5)
{
a=x;
b=y;
}
while(t>0.5)
{
ellipse(a,b,30,30);
}
fill(255,0,0);
if(t!=0)
{
ellipse(x, y, 15, 15);
}
}
}
I have defined everything in setup, draw etc, but i want to launch the ball from the start to the middle of the Bezier Curve only one time whenever space is pressed.
The current version shows me the loop. How can i do that?
Tried Everything like return, break, changing the t parameter etc, but the code doesn't work. I'm new in processing.
Do you have any suggestions?
Biggest mistake that you make is altering value of t after you calculated x and y positions of red ball. To avoid this you need first calculate t between [0, 1] in you case [0, 0.5] and then alter this value according to state of your program.
Second mistake you made while calculating t from frameCount. First you use modulo to extract numbers [0, 50] and then map it in range [0, 0.5] like this
float t = (frameCount % 50) * 0.01;
You also mentioned that you want to repeat this animation after pressing some key. For this you will need keyPressed method and some global variables to represent state of program and store starting frame of animation (because frameCount should be read only). So basic functionality can be achieved like this:
boolean run = false;
float f_start = 0;
void ballMove() {
noFill();
bezier (x0, y0, x1, y1, x2, y2, x3, y3);
float t = ((frameCount - f_start) % 50) * 0.01;
if (run == false) {
t = 0;
}
float x = bezierPoint(x0, x1, x2, x3, t);
float y = bezierPoint( y0, y1, y2, y3, t);
fill(255, 0, 0);
ellipse(x, y, 5, 5);
}
void keyPressed() {
run = !run;
f_start = frameCount;
}
Hope this will help you. Next time pls post an MCVE so we do not need to fight with your code.

how to calculate the dist() from mouseX, mouseY to a rectangle in Processing

If it was the dist to a point it would be
dist(mouseX, mouseY, x, y)
for
point(x,y)
but how can I calculate dist() from the mouse's current position to
rectMode(CORNERS);
rect(x1,y2,x2,y2);
Thanks
Something like this should do it:
float distrect(float x, float y, float x1, float y1, float x2, float y2){
float dx1 = x - x1;
float dx2 = x - x2;
float dy1 = y - y1;
float dy2 = y - y2;
if (dx1*dx2 < 0) { // x is between x1 and x2
if (dy1*dy2 < 0) { // (x,y) is inside the rectangle
return min(min(abs(dx1), abs(dx2)),min(abs(dy1),abs(dy2)));
}
return min(abs(dy1),abs(dy2));
}
if (dy1*dy2 < 0) { // y is between y1 and y2
// we don't have to test for being inside the rectangle, it's already tested.
return min(abs(dx1),abs(dx2));
}
return min(min(dist(x,y,x1,y1),dist(x,y,x2,y2)),min(dist(x,y,x1,y2),dist(x,y,x2,y1)));
}
Basically, you need to figure out if the closes point is on one of the sides, or in the corner. This picture may help, it shows the distance of a point from a rectangle for different positions of the point:
Here's a somewhat interactive program which accomplishes what you're looking for. You can drop it into Processing and run it if you would like.
EDIT: Here's a screenshot:
// Declare vars.
int x_click = -20; // Initializes circle and point off-screen (drawn when draw executes)
int y_click = -20;
float temp = 0.0;
float min_dist = 0.0;
int x1, x2, x3, x4, y1, y2, y3, y4;
// Setup loop.
void setup() {
size(400, 400);
// Calculate the points of a 40x40 centered rectangle
x1 = width/2 - 20;
y1 = height/2 - 20;
x2 = width/2 + 20;
y2 = y1;
x3 = x1;
y3 = height/2 + 20;
x4 = x2;
y4 = y3;
}
// Draw loop.
void draw(){
background(255);
// Draws a purple rectangle in the center of the screen.
rectMode(CENTER);
fill(154, 102, 200);
rect(width/2, height/2, 40, 40);
// Draws an orange circle where the user last clicked.
ellipseMode(CENTER);
fill(204, 102, 0);
ellipse(x_click, y_click, 10, 10);
// Draws black point where the user last clicked.
fill(0);
point(x_click, y_click);
// Draws min dist onscreen.
textAlign(CENTER);
fill(0);
text("min dist = " + min_dist, width/2, height/2 + 150);
}
void mousePressed(){
x_click = mouseX;
y_click = mouseY;
// If the click isn't perpendicular to any side of the rectangle, the min dist is a corner.
if ( ((x_click <= x1) || (x_click >= x2)) && ((y_click <= y1) || (y_click >= y3)) ) {
min_dist = min(min(dist(x1,y1,x_click,y_click),dist(x2,y2,x_click,y_click)), min(dist(x3,y3,x_click,y_click),dist(x4,y4,x_click,y_click)));
} else if( (x_click > x1) && (x_click < x2) && ((y_click < y1) || (y_click > y3)) ) {
// outside of box, closer to top or bottom
min_dist = min(abs(y_click - y1), abs(y_click - y3));
} else if( (y_click > y1) && (y_click < y3) && ((x_click < x1) || (x_click > x2)) ) {
// outside of box, closer to right left
min_dist = min(abs(x_click - x1), abs(x_click - x2));
} else {
// inside of box, check against all boundaries
min_dist = min(min(abs(y_click - y1), abs(y_click - y3)),min(abs(x_click - x1), abs(x_click - x2)));
}
// Print to console for debugging.
//println("minimum distance = " + min_dist);
}
This is what I use. If you are only interested in the relative distance there is probably no need to take the square root which should make it slightly quicker.
- (NSInteger) distanceFromRect: (CGPoint) aPoint rect: (CGRect) aRect
{
NSInteger posX = aPoint.x;
NSInteger posY = aPoint.y;
NSInteger leftEdge = aRect.origin.x;
NSInteger rightEdge = aRect.origin.x + aRect.size.width;
NSInteger topEdge = aRect.origin.y;
NSInteger bottomEdge = aRect.origin.y + aRect.size.height;
NSInteger deltaX = 0;
NSInteger deltaY = 0;
if (posX < leftEdge) deltaX = leftEdge - posX;
else if (posX > rightEdge) deltaX = posX - rightEdge;
if (posY < topEdge) deltaY = topEdge - posY;
else if (posY > bottomEdge) deltaY = posY - bottomEdge;
NSInteger distance = sqrt(deltaX * deltaX + deltaY * deltaY);
return distance;
}

Resources