Windows GDI has these functions:
MoveTo();
LineTo();
They accept coordinates where to start drawing and where to stop drawing.
But how are these functions implemented?? (especially LineTo)
Do they need to calculate all points between point A and point B??
How is this line drawn exactly??
Yes, they calculate each individual point between A and B.
The most common way to do this efficiently is known as Bresenham's Line Algorithm.
Note that Windows LineTo does not draw the last point. When line segments are drawn one after another, this prevents the endpoints from being double drawn.
nobody who never saw the Windows source code can answer this in-depth...
BUT Windows is just as any other software: it needs some algorithm to draw a line... one such algorithm you can see here http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
The Moveto is "easier" in that it just updates the current coordinates the system know of...
It doesn't need to calculate all points between A and B (which are infinite) but only the discrete pixels between A and B. That's usually a standard line rasterization algorithm. See Wikipedia for Bresenham's line rasterization algorithm, which is the standard school book example and usually the base for more flexible rasterization algorithms.
I suspect there is more going on that just (a form of) Bresenham as there is also (optional) anti-aliasing. see this article for what might be the implemented algoritm (Xiaolin Wu's line algorithm)
Related
I have a path drawn in Illustrator, and I need to break the path into section of 100 px. I can't figure out the logic. A line consist of 2 points x1,y1 and x2, y2. And this is for a straight line. My line may have angles/curve, so what do I need to do, to figure out the distance between 2 pixels.Here is a graphic illustration of my line and the sections, which I need to select/extract:
From the shape above, I need to break it into section of lines(note these are not straight lines).
Try referencing the Bug Algorithm. It's a very simple intuitive approach to path planning. I've uploaded an example written in LabVIEW here, but I know there are plenty of others available.
The Bug Algorithm generates a continuous line; a lot of data points; however you can keep a running average of the general diretion it's heading in and detect sharp changes in angles as an important node in the path. This allows you to segment paths from possibly thousands of data points into just a handful.
There are two aspects in your question:
how do I break a path at some point,
how do I find points spaced by a certain distance.
To answer the first, the type of primitives that define the path matters. Assuming a sequence of Bezier cubics, you will resort to the de Casteljau's algorithm: it allows you to construct the control points that correspond to a desired section of a given Bezier arc, from the original control points. Then, a section of a path will be obtained as a starting section of an initial Bezier, then (possibly) a sequence of whole Bezier arcs, and finally the ending section of a last Bezier arc.
To answer the second, assuming that you need an accurate answer, you will need to resort to numerical integration of the arc length along the path. Refer to this post: https://math.stackexchange.com/a/1171564/65203.
For a simple approximation, you can flatten the curve (approximate it as a polyline) and compute the accumulated segment lengths (or even count the pixels if your curve renderer gives you access to this information).
This process is not trivial.
I am looking for an algorithm that given two meshes could clip one using another.
The simplest form of this is clipping a mesh using a plane. I've already implemented that by following something similar to what is described here.
What it does is basically inspecting all mesh vertices and triangles with respect to the plane (the plane's normal and point are given). If the triangle is completely above the plane, it is left untouched. If it falls completely below the plane, it is discarded. If some of the edges of the triangle intersect with the plane, the intersecting points with the plane are calculated and added as the new vertices. Finally a cap is generated for the hole on the place the mesh was cut.
The problem is that the algorithm assumes that the plane is unlimited, therefore whatever is in its path is clipped. In the simplest form, I need an extension of this without the assumption of a plane of "infinite" size.
To clarify, imagine that we have a 3D model of a desk with 2 boxes on it. The boxes are adjacent (but not touching or stacked). The user will define a cutting plane of a limited width and height underneath the first box and performs the cut. We end up with a desk model (mesh) with a box on it and another box (mesh) that can be freely moved around/manipulated.
In the general form, I'd like the user to be able to define a bounding box for the box he/she wants to separate from the desk model and perform the cut using that bounding box.
If I could extend the algorithm I already have to an algorithm with limited-sized planes, that would be great for now.
What you're looking for are constructive solid geometry/boolean algorithms with arbitrary meshes. It's considerably more complex than slicing meshes by an infinite plane.
Among the earliest and simplest research in this area, and a good starting point, is Constructive Solid Geometry for Polyhedral Objects by Trumbore and Hughes.
http://cs.brown.edu/~jfh/papers/Laidlaw-CSG-1986/main.htm
From the original paper:
More elaborate solutions extend upon this subject with a variety of data structures.
The real complexity of the operation lies in the slicing algorithm to slice one triangle against another. The nightmare of implementing robust CSG lies in numerical precision. It's easy when you involve objects far more complex than a cube to run into cases where a slice is made just barely next to a vertex (at which point you have the tough decision of merging the new split vertex or not prior to carrying out more splits), where polygons are coplanar (or almost), etc.
So I suggest initially erring on the side of using very high-precision floating point numbers, possibly even higher than double precision to focus on getting something working correctly and robustly. You can optimize later (first pass should be to use an accelerator like an octree/kd-tree/bvh), but you'll avoid many headaches this way in your first iteration.
This is vastly simpler to implement at render time if you're focusing on a raytracer rather than a modeling software, e.g. With raytracers, all you have to do to do this kind of arbitrary clipping is pretend that an object used to subtract from another has its polygons flipped in the culling process, e.g. It's easy to solve robustly at the ray level, but quite a bit harder to do robustly at the geometric level.
Another thing you can do to make your life so much easier if you can afford it is to voxelize your object, find subtractions/additions/unions of voxels, and then translate the voxels back into a mesh. This is so much easier to make robust, but harder to do efficiently and the voxel->polygon conversion can get quite involved if you want better results than what marching cubes provide.
It's a really tough area to do extremely well and requires perseverance, and thus the reason for the existence of things like this: http://carve-csg.com/about.
If someone is interested, currently there is a solution for this problem in CGAL library. It allows clipping one triangular mesh using another mesh as bounding volume. The usage example can be found here.
To detect if a point is in a polygon, you project a line from the point, to infinity, and see how many of polygon's vertices it intersects with... simple enough. My problem is that if the ray intersects the polygon on one of the points, then it is counted as intersecting two segments, and considered outside the polygon. I altered my function to make it only count one of the segments when the ray intersects a point of the polygon, but there are cases where a line could intersect the point while still being outside as well. Take this image as an example:
If you assume the point in the top left is "infinity", and cast a ray to either of the other points, both intersect at a point of the polygon, and would count as intersecting the same number of vertices even though one is inside, and one is outside.
Is there a way to compensate for that, or do I just have to assume that those fringe cases won't pop up?
If the ray crosses a side exactly on a vertex, only count that side if the other vertex is above the ray. That will fix your corner case.
For example in the picture you posted, the lower ray crosses two sides of the square at the top-left vertex, but one side is above the ray and the other below, so that contributes 1 and the target point is found to be inside. The upper ray crosses two sides at the top-right vertex, both sides are below the ray, so they contribute 0 to the count and the target point is found to be outside.
Update:
I remembered reading an article which describes a technique for dealing with singular cases in general. Please read my other answer if interested.
While my first answer should do the trick for this simple problem, I can't help but mention that there exist general techniques for dealing with these kinds of special cases.
This article describes a technique for dealing with these kinds of issues in general. And one of the first examples they provide happens to be the algorithm you ask about!
The idea is to apply Automatic differentiation aka Dual numbers to compute symbolic perturbations.
By the way the same technique can also be used to avoid handling 0/0 as a special case in programs!
Here is the blog post I originally learned this from, it gives some great background to the technique, and the author blogs a lot about automatic differentiation (AD).
Despite appearances AD is a very practical technique especially in languages with good support for operator overloading (eg: C++, Haskell, Python ...) and I have used it in "real life" (industrial applications in C++).
Send ray in another direction.
If you try n+1 different directions (n is number of polygon points) one of them surely will not pass through any vertex.
This will simplify the code compared to consideration of corner cases.
Worst case becomes O(n)*CheckComplexity(n) which is likely O(n^2). If it's not acceptable, you can just sort all vertices by direction from the point to them and select middle of some interval. This will give O(n*log n).
This question already has answers here:
svg: generate 'outline path'
(2 answers)
Closed 5 years ago.
I want to convert a stroked path to a filled object. (Programmatically, in JavaScript.)
The line is just a simple curved line, a sequence of coordinates. I can render this line as a path, and give it a stroke of a certain thickness... but I'm trying to get a filled shape rather than a stroked line, so that I can do further modifications on it, such as warping it, so the resulting 'stroke' might vary in thickness or have custom bits cut out of it (neither of these things are possible with a real SVG stroke, as far as I can tell).
So I'm trying to manually 'thicken' a line into a solid shape. I can't find any function that does this – I've looked through the docs of D3.js and Raphaël, but no luck. Does anyone know of a library/function that would do this?
Or, even better: if someone could explain to me the geometry theory about how I would do this task manually, by taking the list of line coordinates I have and working out a new path that effectively 'strokes' it, that would be amazing. To put it another way, what does the browser do when you tell it to stroke a path – how does it work out what shape the stroke should be?
There has been a similar question recently:
svg: generate 'outline path'
All in all, this is a non-trivial task. As mentioned in my answer to the linked question, PostScript has a command for generating paths that produce basically the same output as a stroke, called strokepath. If you look at what Ghostscript spits out when you run the code I posted at the linked question, it's pretty ugly. And even Inkscape doesn't really do a good job. I just tried Path => Outline stroke in Inkscape (I think that's what the English captions should say), and what came out didn't really look the same as the stroked path.
The "simplest" case would be if you only have non-self-intersecting polylines, polygons or paths that don't contain curves because in general, you can't draw exact "parallel" Bézier curves to the right and the left of a non-trivial Bézier curve that would delimit the stroked area - it's mathematically non-existent. So you would have to approximate it one way or the other. For straight line segments, the exact solution can be found comparatively easily.
The classic way of rendering vector paths with curves/arcs in them is to approximate everything with a polyline that is sufficiently smooth. De Casteljau's Algorithm is typically used for turning Bézier curves into line segments. (That's also basically what comes out when you use the strokepath command in Ghostscript.) You can then find delimiting parallel line segments, but have to join them correctly, using the appropriate linejoin and miterlimit rules. Of course, don't forget the linecaps.
I thought that self-intersecting paths might be tricky because you might get hollow areas inside the path, i.e. the "crossing area" of a black path might become white. This might not be an issue for open paths when using nonzero winding rule, but I'd be cautious about this. For closed paths, you probably need the two "delimiting" paths to run in opposite orientation. But I'm not sure right now whether this really covers all the potential pitfalls.
Sorry if I cause a lot of confusion with this and maybe am not of much help.
This page has a fairly good tutorial on bezier curves in general with a nice section on offset curves.
http://pomax.github.io/bezierinfo/
A less precise but possibly faster method can be found here.
http://seant23.wordpress.com/2010/11/12/offset-bezier-curves/
There is no mathematical answer, because the curve parallel to a bezier curve is not generally a bezier curve. Most methods have degenerate cases, especially when dealing with a series of curves.
Think of a simple curve as one with no trouble spots. No cusps, no loops, no inflections, and ideally a strictly increasing curvature. Chop up all the starting curves into these simple curves. Find all the offset curves of these simple curves. Put all the offset curves back together dealing with gaps and intersections. Quadratic curves are much more tractable if you have the option to work with them.
I think most browsers do something similar to processingjs, as they have degenerate cases even with quadratic curves. For example, look at the curve 200,300 719,301 500,300 with a thickness of 100 or more.
The standard method is the Tiller-Hanson algorithm (Offsets of Two-Dimensional Profiles, 1984, which irritatingly is not on line for free) which creates a good approximation. The idea is that because the control points of each Bezier curve lie on lines tangent to the start and end of the curve, a parallel curve will have the same property. So we offset the start and the end of the curve, then find new control points using these intersections. However, that gives very bad results for sharp curves, so the first step is to bisect the original curve, which is very easy to do to Bezier curves, until it turns through a sufficiently small angle.
Other refinements are needed to deal with (i) intersections between the parallels, on the inside of each vertex; (ii) inserting an arc of a circle to fill the gap on the outside of each vertex; and (iii) adding end-caps - square, butt or circular.
Tiller-Hanson is difficult to implement, but there's a good open-source implementation in the FreeType library, in ftstroke.c (http://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/src/base/ftstroke.c).
I'm sorry to say that it can be quite difficult to integrate this code, but I have used it successfully, and it works well.
Crayon Physics Deluxe is a commercial game that came out recently. Watch the video on the main link to get an idea of what I'm talking about.
It allows you to draw shapes and have them react with proper physics. The goal is to move a ball to a star across the screen using contraptions and shapes you build.
While the game is basically a wrapper for the popular Box2D Physics Engine, it does have one feature that I'm curious about how it is implemented.
Its drawing looks very much like a Crayon. You can see the texture of the crayon and as it draws it varies in thickness and darkness just like an actual crayon drawing would look like.
(source: kloonigames.com)
(source: kloonigames.com)
The background texture is freely available here.
What kind of algorithm would be used to render those lines in a way that looks like a Crayon? Is it a simple texture applied with a random thickness and darkness or is there something more going on?
I remember reading (a long time ago) a short description of an algorithm to do so:
for the general form of the line, you split the segment in two at a random point, and move this point slightly away from it's position (the variation depending on the distance of the point to the extremity). Repeat recursively/randomly. In this way, you lines are not "perfect" (straight line)
for a given segment you can "overshoot" a little bit, by extending one extremity or the other (or both). In this way, you don't have perfect joints. If i remember well, the best was to extends the original extremities, but you can do this for the sub-segment if you want to visibly split them.
draw the lines with pattern/stamp
there was also the (already mentioned) possibility to drawn with different starting and ending opacity (to mimic the tendency to release the pen at the end of drawing)
You can use a different size for the stamp on the beginning and the end of the line (also to mimic the tendency to release the pen at the end of drawing). For the same effect, you can also draw the line twice, with a small variation for one of the extremity (be careful with the alpha in this case, as the line will be drawn twice)
Last, for a given line, you can do the previous modifications several times (ie draw the line twice, with different variations) : human tend to repeat a line if they make some mistakes.
Regards
If you blow the image up you can see a repeating stamp-pattern .. there's probably a small assortment that it uses as it moves from a to b - might even rotate them ..
The wavering of the line can't be all that difficult to do. Divide into a bunch of random segments, pick positions slightly away from the direct route and draw splines.
Here's a paper that uses a lot of math to simulate the deposition of wax on paper using a model of friction. But I think your best bet is to just use a repeating pattern, as another reader mentioned, and vary the opacity according to pressure.
For the imperfect line drawing parts, I have a blog entry describing how to do it using bezier curves.
You can base darkness on speed. That's just measuring the distance traveled by the cursor between this frame and the last frame (remember Pythagorean theorem) and then when you go to draw that line segment on screen, adjust the alpha (opacity) according to the distance you measured.
There is a paper available called Mimicking Hand Drawn Pencil Lines which covers a bit of what you are after. Although it doesn't present a very detailed view of the algorithm, the authors do cover the basics of the steps that they used.
This paper includes high level descriptions of how they generated the lines, as well as how they generated the textures for the lines, and they get results which are similar to what you want.
This article on rendering chart series to look like XKCD comics has an algorithm for perturbing lines which may be relevant. It doesn't cover calculating the texture of a crayon drawn line, but it does offer an approach to making a straight line look imperfect in a human-like way.
Example output:
I believe the easiest way would simply be to use a texture with random darkness (some gradients, maybe) throughout, and set size randomly.