How can I draw a line while only using vertices and indices? - rust

I use wgpu as my graphics backend for my project.
this is my current implementation:
pub fn draw_line(
points: Vec<[f32; 2]>,
) -> (Vec<Vertex>, Vec<u16>) {
let mut vertices: Vec<Vertex> = Vec::new();
let mut indices: Vec<u16> = Vec::new();
let w = WIDTH / 2.0;
let x1 = points[0][0];
let x2 = points[1][0];
let y1 = points[0][1];
let y2 = points[1][1];
let color: [f32; 3] = [1.0, 1.0, 1.0];
vertices.push(Vertex { position: [x1, y1 - w, 0.0], color });
vertices.push(Vertex { position: [x1, y1 + w, 0.0], color });
vertices.push(Vertex { position: [x2, y2 + w, 0.0], color });
vertices.push(Vertex { position: [x2, y2 - w, 0.0], color });
indices.push(2);
indices.push(1);
indices.push(0);
indices.push(2);
indices.push(0);
indices.push(3);
return (vertices, indices);
}
But when trying to draw a line between 2 points the width of the line gets distorted relative to the height difference of those points.
And the X and Y values of point1 must be smaller than the ones on point2 otherwise they dont show up because wgpu needs either Clockwise or CounterClockwise front faces
Is there any better function that that returns the vertices and indices, for a line between 2 Points

Untested but should work:
pub fn draw_line(
points: Vec<[f32; 2]>,
) -> (Vec<Vertex>, Vec<u16>) {
let mut vertices: Vec<Vertex> = Vec::new();
let mut indices: Vec<u16> = Vec::new();
let w = WIDTH / 2.0;
let x1 = points[0][0];
let x2 = points[1][0];
let y1 = points[0][1];
let y2 = points[1][1];
let color: [f32; 3] = [1.0, 1.0, 1.0];
let dx = x2 - x1;
let dy = y2 - y1;
let l = dx.hypot (dy);
let u = dx * WIDTH * 0.5 / l;
let v = dy * WIDTH * 0.5 / l;
vertices.push(Vertex { position: [x1 + v, y1 - u, 0.0], color });
vertices.push(Vertex { position: [x1 - v, y1 + u, 0.0], color });
vertices.push(Vertex { position: [x2 - v, y2 + u, 0.0], color });
vertices.push(Vertex { position: [x2 + v, y2 - u, 0.0], color });
indices.push(2);
indices.push(1);
indices.push(0);
indices.push(2);
indices.push(0);
indices.push(3);
return (vertices, indices);
}

Related

Is there a better way to generate points on a circle than trying out points in the equation x^2 + y^2 = r^2?

I have seen many apps which draw circles e.g pygame for python, p5.js for javascript. But I cannot find a method to find out points on a circle efficiently. My current solution to the problem involves trying out all the numbers in the square in which the circle can be inscribed.
This can't be the most efficient method to do it. What is the method used at the industry level? Does it involve optimization or is it a whole new method?
A Midpoint Circle Algorithm could be used.
And an implementation e.g. in C from rosettacode.org:
#define plot(x, y) put_pixel_clip(img, x, y, r, g, b)
void raster_circle(
image img,
unsigned int x0,
unsigned int y0,
unsigned int radius,
color_component r,
color_component g,
color_component b )
{
int f = 1 - radius;
int ddF_x = 0;
int ddF_y = -2 * radius;
int x = 0;
int y = radius;
plot(x0, y0 + radius);
plot(x0, y0 - radius);
plot(x0 + radius, y0);
plot(x0 - radius, y0);
while(x < y)
{
if(f >= 0)
{
y--;
ddF_y += 2;
f += ddF_y;
}
x++;
ddF_x += 2;
f += ddF_x + 1;
plot(x0 + x, y0 + y);
plot(x0 - x, y0 + y);
plot(x0 + x, y0 - y);
plot(x0 - x, y0 - y);
plot(x0 + y, y0 + x);
plot(x0 - y, y0 + x);
plot(x0 + y, y0 - x);
plot(x0 - y, y0 - x);
}
}

Project 2D points onto Circle/Curve

I have a list of XY points which represent text in a "dot matrix" form. The origin of the first point in the set in the set is 0,0(upper left point). (I can change the points to incremental coordinates too)
I would like to project or wrap the points around a radius like so:
I've tried to follow this answer, but the results are not what I expect:
How To Project Point Onto a Sphere
I've also tried converting to Polar coordinates and imposing
the R coordinate to determine the Theta and the convert back to cartesian, but that does not work either.
For example, the letter T produces this which should then be projected to the curve:
0, .0
0.1, .0
0.2, .0
0.2, .-0.1
0.2, .-0.2
0.2, .-0.3
0.2, .-0.4
0.2, .-0.5
0.2, .-0.6
0.3, .0
0.4, .0
What is the process to get my points to follow a radial curve
Say you want to curve around a circle centered at (cx, cy) with radius r, using dots with size (diameter) 0.1.
The distance, d the center of a dot at (x, y) is from center of the circle is:
d = r + y - size / 2
(I've subtracted size / 2 to get the position of the center of dot)
The angle theta (in radians) around the circle is:
theta = (x + size / 2) / r
The position of the dot is then:
dx = cx + d * cos(theta)
dy = cy - d * sin(theta)
Here's an example using SVG and Javascript
var svg = document.getElementById('curve-text');
var NS = "http://www.w3.org/2000/svg";
var points = [
[0, 0],
[0.1, 0],
[0.2, 0],
[0.2, -0.1],
[0.2, -0.2],
[0.2, -0.3],
[0.2, -0.4],
[0.2, -0.5],
[0.2, -0.6],
[0.3, 0],
[0.4, 0]
];
var cx = 2;
var cy = 2;
var r = 2;
var size = 0.1;
drawCircle(cx, cy , r - 0.7);
var circumference = Math.PI * 2 * r;
var angle = 360 / circumference;
var radians = 1 / r;
// Add 12 copies of the letter T around the circle
for (var j = 0; j < 12; j++) {
for (var i = 0; i < points.length; i++) {
addDots(points[i][0] + j, points[i][1], size, cx, cy, r)
}
}
function drawCircle(cx, cy , r) {
var circle = document.createElementNS(NS, 'circle');
circle.setAttributeNS(null, 'cx', cx);
circle.setAttributeNS(null, 'cy', cy);
circle.setAttributeNS(null, 'r', r);
circle.setAttributeNS(null, 'fill', 'none');
circle.setAttributeNS(null, 'stroke', 'black');
circle.setAttributeNS(null, 'stroke-width', '0.02');
svg.appendChild(circle);
}
function addDots(x, y, size, cx, cy, r) {
var dotR = size / 2;
var d = r + (y - dotR);
var theta = (x + dotR) / r;
var x = cx + d * Math.cos(theta);
var y = cy - d * Math.sin(theta);
var dot = document.createElementNS(NS, 'circle');
dot.setAttributeNS(null, 'cx', x);
dot.setAttributeNS(null, 'cy', y);
dot.setAttributeNS(null, 'r', dotR);
svg.appendChild(dot);
}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 4" id="curve-text" width="200" height="200">
</svg>
You need to take the (X, Y) coordinates as if they were (Θ, R) polar coordinates (in this order), and convert to Cartesian.
Experiment a little to understand the effect of horizontal or vertical translation before the transformation, as well as h/v scaling. Ensure that for all points R > r, the radius of the circle.

Draw a line in a bitmap (possibly with piston)

I want to draw a line in a bitmap, e.g. from pixel (10, 10) to pixel (90, 90). The line must have a specific width.
Using piston image, I am able to draw a single pixel:
let mut image = ImageBuffer::<image::Rgb<u8>>::new(100, 100);
image.get_pixel_mut(5, 5).data = [255, 255, 255];
image.save("output.png");
However there is no method to draw a line.
I suppose I have to use piston::graphics for that, but I can’t find any ressource how to do it (any example involves a window that provides a context on which graphics works on).
In addition to the great answer above: there is now direct support for drawing lines and many more shapes (even texts) in the imageproc library (see also the examples there):
extern crate image;
extern crate imageproc;
use image::{Rgb, RgbImage};
use imageproc::drawing::draw_line_segment_mut;
fn main() {
let mut img = RgbImage::new(100, 100);
draw_line_segment_mut(
&mut img,
(5f32, 5f32), // start point
(95f32, 95f32), // end point
Rgb([69u8, 203u8, 133u8]), // RGB colors
);
img.save("output.png").unwrap();
}
If you drop the width requirement and don't need antialiasing either, you could use something like Bresenham's line algorithm (also on Rosetta Code):
extern crate image;
use image::RgbImage;
fn draw_line(img: &mut RgbImage, x0: i64, y0: i64, x1: i64, y1: i64) {
// Create local variables for moving start point
let mut x0 = x0;
let mut y0 = y0;
// Get absolute x/y offset
let dx = if x0 > x1 { x0 - x1 } else { x1 - x0 };
let dy = if y0 > y1 { y0 - y1 } else { y1 - y0 };
// Get slopes
let sx = if x0 < x1 { 1 } else { -1 };
let sy = if y0 < y1 { 1 } else { -1 };
// Initialize error
let mut err = if dx > dy { dx } else {-dy} / 2;
let mut err2;
loop {
// Set pixel
img.get_pixel_mut(x0 as u32, y0 as u32).data = [255, 255, 255];
// Check end condition
if x0 == x1 && y0 == y1 { break };
// Store old error
err2 = 2 * err;
// Adjust error and start position
if err2 > -dx { err -= dy; x0 += sx; }
if err2 < dy { err += dx; y0 += sy; }
}
}
fn main() {
let mut img = RgbImage::new(256, 256);
draw_line(&mut img, 10, 10, 246, 128);
draw_line(&mut img, 128, 10, 10, 246);
img.save("output.png").unwrap();
}
Output:
As a primitive form of adding thickness, you could repeat drawing the line with some offset. Alternatively, draw a filled rectangle where the height of the rectangle corresponds to the thickness of the desired line.
There's a ticket open in the imageproc project to add anti aliased line drawing support: https://github.com/PistonDevelopers/imageproc/issues/97

How to connect 4 points on a plane so they do not fold on themselves(they always create a Quadrilateral)

I have created a small Raphael app to showcase my struggle.
I created four handles which can be moved. A 'sheet' is covering the entire screen except for the square between the 4 handles.
Whenever the handles are dragged the sheet is placed accordingly.
What ends up happening is that in certain situations, the sheet folds on itself.
It's best if you just see the fiddle. You'll get what I'm talking about
http://jsfiddle.net/8qtffq0s/
How can I avoid this?
Notice: The screen is white. The black part is the sheet, and the white part is a gap in the sheet and not the other way around.
//raphael object
var paper = Raphael(0, 0, 600, 600)
//create 4 handles
h1 = paper.circle(50, 50, 10).attr("fill","green")
h2 = paper.circle(300, 50, 10).attr("fill", "blue")
h3 = paper.circle(300, 300, 10).attr("fill", "yellow")
h4 = paper.circle(50, 300, 10).attr("fill", "red")
//create covering sheet
path = ["M", 0, 0, "L", 600, 0, 600, 600, 0, 600, 'z', "M", h1.attrs.cx, h1.attrs.cy,"L", h4.attrs.cx, h4.attrs.cy, h3.attrs.cx, h3.attrs.cy, h2.attrs.cx, h2.attrs.cy,'z']
sheet = paper.path(path).attr({ "fill": "black", "stroke": "white" }).toBack()
//keep starting position of each handle on dragStart
var startX,startY
function getPos(handle) {
startX= handle.attrs.cx
startY = handle.attrs.cy
}
//Redraw the sheet to match the new handle placing
function reDrawSheet() {
path = ["M", 0, 0, "L", 600, 0, 600, 600, 0, 600, 'z', "M", h1.attrs.cx, h1.attrs.cy, "L", h4.attrs.cx, h4.attrs.cy, h3.attrs.cx, h3.attrs.cy, h2.attrs.cx, h2.attrs.cy, 'z']
sheet.attr("path",path)
}
//enable handle dragging
h1.drag(function (dx, dy) {
this.attr("cx", startX + dx)
this.attr("cy", startY + dy)
reDrawSheet()
},
function () {
getPos(this)
})
h2.drag(function (dx, dy) {
this.attr("cx", startX + dx)
this.attr("cy", startY + dy)
reDrawSheet()
},
function () {
getPos(this)
})
h3.drag(function (dx, dy) {
this.attr("cx", startX + dx)
this.attr("cy", startY + dy)
reDrawSheet()
},
function () {
getPos(this)
})
h4.drag(function (dx, dy) {
this.attr("cx", startX + dx)
this.attr("cy", startY + dy)
reDrawSheet()
},
function () {
getPos(this)
})
Update: I improved the function "reDrawSheet" so now it can classify the points on the strings as top left, bottom left, bottom right, and top right
This solved many of my problems, but in some cases the sheet still folds on it self.
new fiddle: http://jsfiddle.net/1kj06co4/
new code:
function reDrawSheet() {
//c stands for coordinates
c = [{ x: h1.attrs.cx, y: h1.attrs.cy }, { x: h4.attrs.cx, y: h4.attrs.cy }, { x: h3.attrs.cx, y: h3.attrs.cy }, { x: h2.attrs.cx, y: h2.attrs.cy }]
//arrange the 4 points by height
c.sort(function (a, b) {
return a.y - b.y
})
//keep top 2 points
cTop = [c[0], c[1]]
//arrange them from left to right
cTop.sort(function (a, b) {
return a.x - b.x
})
//keep bottom 2 points
cBottom = [c[2], c[3]]
//arrange them from left to right
cBottom.sort(function (a, b) {
return a.x - b.x
})
//top left most point
tl = cTop[0]
//bottom left most point
bl = cBottom[0]
//top right most point
tr = cTop[1]
//bottom right most point
br = cBottom[1]
path = ["M", 0, 0, "L", 600, 0, 600, 600, 0, 600, 'z', "M", tl.x,tl.y, "L", bl.x,bl.y, br.x,br.y, tr.x,tr.y, 'z']
sheet.attr("path",path)
}
To make things super clear, this is what I'm trying to avoid:
Update 2:
I was able to avoid the vertices from crossing by checking which path out of the three possible paths is the shortest and choosing it.
To do so, I added a function that checks the distance between two points
function distance(a, b) {
return Math.sqrt(Math.pow(b.x - a.x, 2) + (Math.pow(b.y - a.y, 2)))
}
And altered the code like so:
function reDrawSheet() {
//c stands for coordinates
c = [{ x: h1.attrs.cx, y: h1.attrs.cy }, { x: h4.attrs.cx, y: h4.attrs.cy }, { x: h3.attrs.cx, y: h3.attrs.cy }, { x: h2.attrs.cx, y: h2.attrs.cy }]
//d stands for distance
d=distance
//get the distance of all possible paths
d1 = d(c[0], c[1]) + d(c[1], c[2]) + d(c[2], c[3]) + d(c[3], c[0])
d2 = d(c[0], c[2]) + d(c[2], c[3]) + d(c[3], c[1]) + d(c[1], c[0])
d3 = d(c[0], c[2]) + d(c[2], c[1]) + d(c[1], c[3]) + d(c[3], c[0])
//choose the shortest distance
if (d1 <= Math.min(d2, d3)) {
tl = c[0]
bl = c[1]
br = c[2]
tr = c[3]
}
else if (d2 <= Math.min(d1, d3)) {
tl = c[0]
bl = c[2]
br = c[3]
tr = c[1]
}
else if (d3 <= Math.min(d1, d2)) {
tl = c[0]
bl = c[2]
br = c[1]
tr = c[3]
}
path = ["M", 0, 0, "L", 600, 0, 600, 600, 0, 600, 'z', "M", tl.x,tl.y, "L", bl.x,bl.y, br.x,br.y, tr.x,tr.y, 'z']
sheet.attr("path",path)
}
Now the line does not cross itself like the image I attached about, but the sheet "flips" so everything turns black.
You can see the path is drawn correctly to connect the for points by the white stroke, but it does not leave a gap
new fiddle: http://jsfiddle.net/1kj06co4/1/
Picture of problem:
So... the trouble is to tell the inside from the outside.
You need the following functions:
function sub(a, b) {
return { x: a.x - b.x , y: a.y - b.y };
}
function neg(a) {
return { x: -a.x , y: -a.y };
}
function cross_prod(a, b) {
// 2D vecs, so z==0.
// Therefore, x and y components are 0.
// Return the only important result, z.
return (a.x*b.y - a.y*b.x);
}
And then you need to do the following once you've found tl,tr,br, and bl:
tlr = sub(tr,tl);
tbl = sub(bl,tl);
brl = sub(bl,br);
btr = sub(tr,br);
cropTL = cross_prod( tbl, tlr );
cropTR = cross_prod(neg(tlr),neg(btr));
cropBR = cross_prod( btr, brl );
cropBL = cross_prod(neg(brl),neg(tbl));
cwTL = cropTL > 0;
cwTR = cropTR > 0;
cwBR = cropBR > 0;
cwBL = cropBL > 0;
if (cwTL) {
tmp = tr;
tr = bl;
bl = tmp;
}
if (cwTR == cwBR && cwBR == cwBL && cwTR!= cwTL) {
tmp = tr;
tr = bl;
bl = tmp;
}
My version of the fiddle is here. :) http://jsfiddle.net/1kj06co4/39/

Equidistant points across Bezier curves

Currently, I'm attempting to make multiple beziers have equidistant points. I'm currently using cubic interpolation to find the points, but because the way beziers work some areas are more dense than others and proving gross for texture mapping because of the variable distance. Is there a way to find points on a bezier by distance rather than by percentage? Furthermore, is it possible to extend this to multiple connected curves?
This is called "arc length" parameterization. I wrote a paper about this several years ago:
http://www.saccade.com/writing/graphics/RE-PARAM.PDF
The idea is to pre-compute a "parameterization" curve, and evaluate the curve through that.
distance between P_0 and P_3 (in cubic form), yes, but I think you knew that, is straight forward.
Distance on a curve is just arc length:
fig 1 http://www.codecogs.com/eq.latex?%5Cint_%7Bt_0%7D%5E%7Bt_1%7D%20%7B%20|P'(t)|%20dt
where:
fig 2 http://www.codecogs.com/eq.latex?P%27(t)%20=%20[%7Bx%27,y%27,z%27%7D]%20=%20[%7B%5Cfrac%7Bdx(t)%7D%7Bdt%7D,%5Cfrac%7Bdy(t)%7D%7Bdt%7D,%5Cfrac%7Bdz(t)%7D%7Bdt%7D%7D]
(see the rest)
Probably, you'd have t_0 = 0, t_1 = 1.0, and dz(t) = 0 (2d plane).
I know this is an old question but I recently ran into this problem and created a UIBezierPath extention to solve for an X coordinate given a Y coordinate and vise versa. Written in swift.
https://github.com/rkotzy/RKBezierMath
extension UIBezierPath {
func solveBezerAtY(start: CGPoint, point1: CGPoint, point2: CGPoint, end: CGPoint, y: CGFloat) -> [CGPoint] {
// bezier control points
let C0 = start.y - y
let C1 = point1.y - y
let C2 = point2.y - y
let C3 = end.y - y
// The cubic polynomial coefficients such that Bez(t) = A*t^3 + B*t^2 + C*t + D
let A = C3 - 3.0*C2 + 3.0*C1 - C0
let B = 3.0*C2 - 6.0*C1 + 3.0*C0
let C = 3.0*C1 - 3.0*C0
let D = C0
let roots = solveCubic(A, b: B, c: C, d: D)
var result = [CGPoint]()
for root in roots {
if (root >= 0 && root <= 1) {
result.append(bezierOutputAtT(start, point1: point1, point2: point2, end: end, t: root))
}
}
return result
}
func solveBezerAtX(start: CGPoint, point1: CGPoint, point2: CGPoint, end: CGPoint, x: CGFloat) -> [CGPoint] {
// bezier control points
let C0 = start.x - x
let C1 = point1.x - x
let C2 = point2.x - x
let C3 = end.x - x
// The cubic polynomial coefficients such that Bez(t) = A*t^3 + B*t^2 + C*t + D
let A = C3 - 3.0*C2 + 3.0*C1 - C0
let B = 3.0*C2 - 6.0*C1 + 3.0*C0
let C = 3.0*C1 - 3.0*C0
let D = C0
let roots = solveCubic(A, b: B, c: C, d: D)
var result = [CGPoint]()
for root in roots {
if (root >= 0 && root <= 1) {
result.append(bezierOutputAtT(start, point1: point1, point2: point2, end: end, t: root))
}
}
return result
}
func solveCubic(a: CGFloat?, var b: CGFloat, var c: CGFloat, var d: CGFloat) -> [CGFloat] {
if (a == nil) {
return solveQuadratic(b, b: c, c: d)
}
b /= a!
c /= a!
d /= a!
let p = (3 * c - b * b) / 3
let q = (2 * b * b * b - 9 * b * c + 27 * d) / 27
if (p == 0) {
return [pow(-q, 1 / 3)]
} else if (q == 0) {
return [sqrt(-p), -sqrt(-p)]
} else {
let discriminant = pow(q / 2, 2) + pow(p / 3, 3)
if (discriminant == 0) {
return [pow(q / 2, 1 / 3) - b / 3]
} else if (discriminant > 0) {
let x = crt(-(q / 2) + sqrt(discriminant))
let z = crt((q / 2) + sqrt(discriminant))
return [x - z - b / 3]
} else {
let r = sqrt(pow(-(p/3), 3))
let phi = acos(-(q / (2 * sqrt(pow(-(p / 3), 3)))))
let s = 2 * pow(r, 1/3)
return [
s * cos(phi / 3) - b / 3,
s * cos((phi + CGFloat(2) * CGFloat(M_PI)) / 3) - b / 3,
s * cos((phi + CGFloat(4) * CGFloat(M_PI)) / 3) - b / 3
]
}
}
}
func solveQuadratic(a: CGFloat, b: CGFloat, c: CGFloat) -> [CGFloat] {
let discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
return []
} else {
return [
(-b + sqrt(discriminant)) / (2 * a),
(-b - sqrt(discriminant)) / (2 * a)
]
}
}
private func crt(v: CGFloat) -> CGFloat {
if (v<0) {
return -pow(-v, 1/3)
}
return pow(v, 1/3)
}
private func bezierOutputAtT(start: CGPoint, point1: CGPoint, point2: CGPoint, end: CGPoint, t: CGFloat) -> CGPoint {
// bezier control points
let C0 = start
let C1 = point1
let C2 = point2
let C3 = end
// The cubic polynomial coefficients such that Bez(t) = A*t^3 + B*t^2 + C*t + D
let A = CGPointMake(C3.x - 3.0*C2.x + 3.0*C1.x - C0.x, C3.y - 3.0*C2.y + 3.0*C1.y - C0.y)
let B = CGPointMake(3.0*C2.x - 6.0*C1.x + 3.0*C0.x, 3.0*C2.y - 6.0*C1.y + 3.0*C0.y)
let C = CGPointMake(3.0*C1.x - 3.0*C0.x, 3.0*C1.y - 3.0*C0.y)
let D = C0
return CGPointMake(((A.x*t+B.x)*t+C.x)*t+D.x, ((A.y*t+B.y)*t+C.y)*t+D.y)
}
// TODO: - future implementation
private func tangentAngleAtT(start: CGPoint, point1: CGPoint, point2: CGPoint, end: CGPoint, t: CGFloat) -> CGFloat {
// bezier control points
let C0 = start
let C1 = point1
let C2 = point2
let C3 = end
// The cubic polynomial coefficients such that Bez(t) = A*t^3 + B*t^2 + C*t + D
let A = CGPointMake(C3.x - 3.0*C2.x + 3.0*C1.x - C0.x, C3.y - 3.0*C2.y + 3.0*C1.y - C0.y)
let B = CGPointMake(3.0*C2.x - 6.0*C1.x + 3.0*C0.x, 3.0*C2.y - 6.0*C1.y + 3.0*C0.y)
let C = CGPointMake(3.0*C1.x - 3.0*C0.x, 3.0*C1.y - 3.0*C0.y)
return atan2(3.0*A.y*t*t + 2.0*B.y*t + C.y, 3.0*A.x*t*t + 2.0*B.x*t + C.x)
}
}

Resources