sketches

block detection

right vector

To generate the bocks of building based on the roads structure, the method I’m building is based on a simple idea: when you arrives at a crossroad, you take the first street on the right and you go on like this until you reach a dead-end or your starting point. If you reach your starting point, the succession of roads you took defines a block of building. In theory. This technique has been suggested by Michel Cleempoel, on the way back from school.

After a bit of preparation of the road network (removing orphan roads, having no connection with others, and dead-ends parts of the roads), the real problem arouse: how do you define right in a 3d environment, without an absolute ground reference. Indeed, I can configure the generator to use the Y axis (top axis in ogre3d) in addition to X & Z.

At a crossroad, you may have several possibilities of roads. In the research, these possible roads are reduced to 3d vectors, all starting at world’s origin. The goal is to find the closest vector on the right of the current one, called the main 3d vector in the graphic above..

The right is a complex idea, because it induces an idea of rotation. The closest on the right doesn’t mean the most perpendicular road on the right side. Let say I have 4 roads to choose from. Two going nearly in the opposite direction of the road i’m on, one perpendicular and one going straight on.

If I compute the angles these roads have with the current one, results are:

5°,

-5°,

90°,

and 170°.

The winner is not the 90°, but the 5° road! If I sort them, the last one must be the -5°, who is the first on the left.

3d plane from a 3d vector

The first thing to do is to define reference plane. To do so, you get the normal vector of the road by doing a cross product with the UP axis (Y axis in this case). The normal gives you a second vector, perpendicular to the road, and therefore defines a plane. Let’s call it VT plane, for Vector-Normal plane. For calculation, we need the vector perpendicular to this plane, rendered by crossing the road and its normal, let’s call it the tangent vector. Until here, it’s basic 3d geometry.

projection of 3d vectors on a plane

We can now project all the possible roads on the VT plane. These are the yellow vectors in the graphic. The math are clearly explained by tmpearce[2]. Once implemented, it looks like this:

The projected vectors will help the angle calculation. Indeed, the current vector and the projected ones being coplanar, they share the same normal. The way to get the angle between 2 coplanar vectors is described by Dr. Martin von Gagern[3], once again. See Plane embedded in 3D paragraph for the code i’ve used.

And… tadaaammmm! The number rendered by the method is the angle i was searching for, displayed in degrees in the graphic above.

It seems nearly impossible to create the relation between half-edges correctly in one pass: some half-edges tries to connect to not yet created half-edges. If the half-edges are generated on the fly, it will imply a check at each half-edge (HE) generation, to validate if the HE is already created or not.

A better approach seems to be: generation of all of them + creation of structures for crossroads, holding a pointer to the RoadDot and the list of all HEs connected to it. Connections can be resolved locally in a second pass. Let's try it.

Not yet functional: blocks are crossing roads...

The issue was coming from a method that sort the connections of a roaddot: RoadDot::rightSort(RDList& sorted). In its first implementation, I was just looping over the connections and storing in a list the result of the method RoadDot::getRight(RoadDot* from);, without checking in any way the angles between these dots. The block crossing street issue was caused by this inconsistency. I now use a skip list and I always use the first connection as a reference. Code is simple:

Each time a dot on the right is retrieved, it is added to the skip list for the next search. Sorting, in a word...

Algorithm can be very painful... but when they are logically correct, they work marvellously! The generation time of each map is nearly unchanged, and results are perfect: no holes!

Last screenshot shows the block rendered as plain shapes. The big yellow one is the outer bound of the map! With a method to measure surfaces of a random polygon, I'll be able to have the precise city area.

method

The first implementation of block detection was using the road's segment. The algorithm was starting with the 2 first dots of the first road and was travelling across the network by performing a getRight() at each dot having more than 2 connections.

A --- B ---- C ---- E
|
|
D
A: {B}
B: {B,C}
C: {B,D,E}
E: {C}

The main issue of this method was that some blocks were not detected! Each time I was passing by through a dot, I was storing wich connections I used. In some cases, the dot needed to be used one time more than its number of connection.

A much better way to perform the search for blocks is based on the half-edges[4] technique. Indeed, each block uses a serie of half-edges, and these half-edges are used only by it. This approach is similar to directed graphs[5].

surfaces

The implementation of the method has been rather quick, even if the results have to be better checked, via a comparaison with a bounding box for instance. The color mapping in the screenshots below is as follow:

image #3: block outline, a small cross indicates the center of each block

Reviewing surface calculation process > there was an inversion of axis in the computation, and it was missing absolute methods at several places. Surface is validated against the bounding box area. Before corrections, the surface was bigger than the bounding box...

Large and small network.

Fill and stroke of the same map.

Fill and stroke of the same map.

There is a strange cutted edges on a lot of blocks. The block detection must miss a dot in several cases... I hope the bug is not in the half-edges linkage. Must be investigated.

shrinking

After detection, blocks are 'glued' to roads. An offset has to be applied on the shape in order to leave some space for the road itself. The first approach used was to shrink the shape by applying an offset of x along each dot normal. Calculation of the normal is straight forward: perpendicular of the previous segment direction + perpendicular of the next segment direction divided by 2. In pseudo code, it gives:

Approach: a first attempt is performed to shrink the shape at the requested factor. One processed, the generated edges directions are compared to the original shape. If some edges directions are opposite to the originals, I retrieve the intersection between the 2 segments linking the origins to the generated points.

A new shape is produce in witch the point a and b are merged, becoming i.

The possible factor for this pass is equals to:

possible_factor = factor * length( a,i ) / length( a, a² )

A new shrink attempt is performed on basis of the new shape, in wich a & b are merged into i, by a factor of orginial_factor - possible_factor.

It's not going too bad, but the process is still very unstable.

The lack of split events management is provoking this kind of issues:

The point 0 should not be allowed to cross the edge 4,5, and 2 sub polygons should be produced to finish the shrink process.

The method used until now was to try to go to the target factor and check, once applied, if there was issues. If yes, a rollback was performed to the first edge event. A new polygon was generated and a new test performed and so on until the target factor was reached. Shrinking this way causes issues when the shrink factor was far above the maximum (aberrations occur), or the factor between 2 edge events was too small.

In short: trying to go somewhere, hitting a wall on the way and only than seeking a door. It is a bit too stupid to hope the algo will behave in a consistent way...

Edge events are located at the intersection of the dots' normal. Finding them is easy, especially when you already have a method to process intersections of lines and segments [8]. Some of the intersections are pointing toward the center of the shape, others outward. I called this property inner. To render it, I have to verify if the intersection is on the right or left side of the vector.

Once done, we just have to pick the smallest intersection factor depending on the factor sign. We can now anticipate the edge events, before making an attempt to shrink.

If shrink factor is less than the smallest intersection factor:

If the shrink factor is high, new polygons are generated on the way, each one containing a reference to the first edge event.

Due to the lack of split event (the next challenge), there are still huge glitches in the process:

Split events

Anticipation of split events requires some brain power.

In the first try, I was computing the intersections between concave angles ( > 180°) and all the segments of the shape. It was nice, in a static shape. But when you shrink a shape, ALL points move, implying that pair point-segment you selected might not be the one where the split event will occur! The prediction was functional, but essentially wrong.

After a cigaret, a full album of the the Mamas & the Papas[9], some sketches on paper and a sketch on inkscape, a simple solution appeared:

computing the intersections between concave angles' normal and vector prepared for edge events;

keeping the intersection where

distance to its origin is the smallest and

direction is opposite to the normal (to validate).

Colors are inverted in the images below, regarding the color code described in edge events.

The method currently in test is based on intersections between angle bisectors, same approach as the edge events.

During polygon generation, all bisectors are tested on all others, in a separated pass. Bisectors are opposite to the normal vector, this is why you will find - normal in the code below.

It is not yet correct: the intersction is inside the shape, ok, but the closest intersection is rarely the good one. Speed is not correctly implemented.

It seems that speed have to be taken into account more seriously. All points move together, meaning that the angle difference between the points influences the crossing time. The more opposite the angles are, the fastest they will cross each other.

Distance and speed have to influence the intersection choice.

Current calculation is not correct. In the first screenshots above, the first split event happens between point 4 and segment 8-9. If 4 is moved a bit, the first split event happens between point 1 and segment 3-4.

Observations:

case #1: intersection involves segment 0-1

case #2: intersection involves segment 1-2

case #3: intersection involves segment 6-7, even if the bisector is crossing the segment 7-8

Resume of the system to resolve.

Basic computation for split events is ok. The red circle in screenshots below shows the predicted split event position. The second screenshot has been generated by manually adjusting the shrink value. The red point and the actual split event occur at the same location.

The math to find the point is based on a line / segment intersection detection. The line is the bisector of the concave point. All polygon's segments are tested against this line. If an intersection is detected, the distance between the concave point has to be divided.

There is still some work to be done, simultaneous split events for instance, or segment's swap when too close from a border, see observations here above.

With a little help from my friend[10], the calculaton is finally perfect. Indeed, the angle between the bisector and the segment influences the division of the distance between the concave point and the intersection.

If the segment is perpendicular to the segment, the form:
File:Split-event-anticipation01.png

distance / ( 1 + sin( PI + concave_angle ) )

is correct. But as soon the bisector has a slight angle, the allowed shrink factor has to be reduced by the sinus of the angle between the bisector and the segment.

This gives the intersection point, not yet enough to trigger the split event. It has to be finished with this:

max_factor = dr * sin( intersecta );

It works perfectly! In the sketch, I automatically reduce factor to max_factor, result is always good.

selection

The selection of the first split event for a specific point is much more tricky than expected.

In the case below, the bisector of the sharp angle do not cross the closest segment. The selection process remove the segment from the candidates. Result is dramatic: during shrink, this segment will cross the bisector! Anticipation is not correctly processed.

The graph below shows a way to fix this. Let's call the point with the orange bisector the current point.

Split event selection process for the current point, step by step:

segment normal dot current bisector is less than 0 > segment is out, the segment is oriented towards the current point, implying that another segment leading this one will cross the bisector closer > green intersection is removed;

if intersection point between segment and current bisector is in segment > already solved by current code > blue intersection is processed;

if intersection point between segment and current bisector is not in segment (pink intersection), do one of the bisectors of segment points cross the segment formed by current point and intersection point?

if yes > the segment, dragged by its point, will certainly cross the bisector at one point during shrink! > orange intersection is valid > pink intersection is processed;

if no > continue;

last test concern the distance evaluation: the closest intersection must be kept, but in the case of outside crossing, the intersection has to be moved much closer from the current point, and the factor to apply depends on the angle of the bisector crossing the [current, intersection] segment.

Better selection of split event is implemented. The problem case here above is solved. Algorithm has changed a bit.

Operations:

if normal of the segment is not in the same direction has the current bisector, skipping segment

retrieval intersection between bisector and line passing by the 2 points

if intersection is not in the same direction as the current bisector, skipping segment

calculation of intersection position, same as before

if intersection happens outside of the segment and none of the normals of segment points cross the current bisector, skipping segment

if there is already a split event detected for the current point and the shrink factor is higher than the previous event, skipping segment

storage of the event if all conditions are ok

once done, if an edge event exists for the current point, deletion of the split event

Note that tests 1, 3 & 5 are inverted for outer events.

Limitations

There are still logical mistakes at step 5 of the algorithm. The exact test is this one:

Lines 3 & 4 test the shrink_multiplier of pu (current point) and pi, one of the segment's point. The shrink_multiplier is eqivalent to the speed of point, it is used to multiply the factor passed to the Multigon::shrink() method. The concav parameter is used to know if the event happens when shrinking or inflating the polygon. The idea was to only test the crossing of the normal and the bisector if the segment point is going 'faster' than the current point. This leads to errors in split event selection, shown here below.

The problem is clear: the test forces the selection of the point having the biggest shrink_multiplier, without taking into account other facts, such has the distance of the intersection, etc.

After a bit of brain juice spread on paper, the resolution of the problem became obvious. If the split event happens outside of the segment, the split event is kept if the current point is the last to reach the intersection between bisectors. It's a basic math problem...[12]

Inner split events are now ok, but there is still some issues on the external selection. This shapes does not behave nicely on outer split. On the right side, cyan polygon, in the first case, and on the left (green polygon) in the second. The split event is triggered from the wrong point.

Solved in 2 minutes: error was due to a stupid inverted test on distance for outer splits...

Simplier version (p5.js)

One of the big problem in split event detection is when the bisector of the point is not crossing the segment (see selection of segment for details).

The first implemented method was based on detection of bisectors' intersection. The method is unsafe. A better method is to create a temporary polygon representing the surface covered by the segment when shrunk, and verify that the event point is belonging to the surface.

It has been implemented in this sketch ():

manipulation:

right-click & drag points to move them

right-click & drag anywhere else to modify offset

C++

It was time to leave Java and re-implement the methods in C++. I'm working in openfremworks to prepare the library. The classes processing the polygons are 100% independent from OF's one, even the vector3 class. Details of the code will be done once the lib will be finished.

The important idea is to use a **Multigon** object, able to manage several polygon. It will be very useful when split events will occur. It also allows to cut into smaller polygon a self-intersecting polygon.

For the moment:

multiple edge events are managed correctly &

polygon grows or shrink smoothly.

In the current vetrsion, several improvements have been done:

new event collapse, indicates when a shape is too small to be shrinked;

when a shape collapse, the position of its center is kept along the shrink steps;

concurrent events (collapse, edge & split) are managed correctly in different subparts of the general shape;

and the whole is not crashing anymore (!).

There are still errors in split events calculations, as shown in the video. Once done, the next worksite will focus on shapes with sharp spikes, when the angle between 2 segments is equal to 360°.

After refining split event selection process, shrink can be performed on complex shapes. Screenshots below are random generated shapes with 100 points.

video

Visual syntax:

left polygon is the original shape to shrink;

result of the process is display on the right;

each time an "event" occurs, a trail is left behind.

once a polygon is split, each part of it gets a different color;

stable red lines shows where the first edge event will happen;

green & magenta lines shows where the first split event will happen.

2.5d

With minor adjustements, code is now able to process 3d polygons as 2d shapes. The UP axis component is removed form the shrink calculation but is kept for final output.

Demo:

On the last image, the lack of an average on the UP axis during edge events implies huge discontinuities in the shape.

Edge & split events results are now smoothed on UP axis. In images below, a highly randomised polygon with 200 points is shrink correctly, but the processing time is growing too fast to allow this kind of manipulation in real-time.

Demo:

Spike events

description

The code being more and more stable, even if a good cleanup in data structures is required (management of events and check of unnecessary fields in objects, points especially), it's the right time to start the implementation of a new kind of events. I've identified them nearly two month ago, and because they are not mentioned in the study of Peter Palfrader[7], I named them spike event. For humans, a spike event is a part of the polygon looking as a line, or a needle.

A spike event occurs when:

the computed normal of the point has its 2 axis at 0 (the up axis is not taken into account, we are working in 2.5d);

when two points have the same position and are connected to a point of the first kind.

In the first case, the event is flagged as crucial and has a reference to the first point leading to him and not being a spike event and the last point connected to him and being a spike event.

Example of 3 spike events, on point 0, 13 and 25, clockwise culling.

Polygon's points data in CSV format, showing that all spike events have their normal at 0,0.

These events are created in priority and prevents any other events to occur. Their processing must take place at highest priority when a shrink is requested.

detection

Next step is to identify if the split event concerns inward (shrink) or outward (inflate) offset. First attempt of identification based on direction's normals failed.

Detection of spike's direction is quite simple, but requires to travel along the polygon to the "basis" of the spike. This task is performed by using the links between points. Indeed, when a polygon is "link()", each point is connected to its predecessor (pointer to previous) and to its successor (pointer to next). When a point triggers a crucial spike event, the algorithm is looping upwards and simultaneously downwards until it find a pair of points that don't have the same position. All the pairs detected along the process are flagged as minor spike event, implying that they might disappear during spike event processing. It also avoid calculation of more complex events (edge and split) on these points.

When the basis of the spike is found, the spike is declared inner, or concave if none of the basis points are concave. In other cases (one or both concave), the spike is set to outer, or convex.

Last thing is to create a normal vector for the crucial spike's event. The detection of spike is based on the fact that normal vector has a length of 0. This is a property of the calculation (to be developed). During the spike detection, the normal of the point is a copy of the previous segment orientation, logically.

Spike curvature is mandatory to manage correctly the shrink process. If the shrink factor is positive (inwards), all outer spikes have to be removed form the polygon before applying the shrink. Process is reversed when shrink factor is negative (outwards). For the spike having the same orientation as the shrink factor, all crucial spike's points have to be duplicated and orientated at 45° and -45° of the original point normal. All other values can be kept: the minor spike's point has already the right informations. This implies creation of a spike event free copy of the current multigon[13] before performing the shrink process.

On coding level, the creation of this copy is tricky, due to the way the normal processing has been split:

This flow will fired exceptions when two points are at the same position: direction will have zero length, therefore normal vector will have zero length. The creation of two points at the position of a crucial spike event will end up in the detection of 2 spike events!!!

A more supervised creation method has to be put into place. All work done during process() can be skipped on the copied multigon, because it has already been done on the original. A special treatment has to be applied on crucial spikes: direction between duplicates is at 90° of the previous one, angles and normal have to computed correctly.

management

[The complete description of the process done during shrink when a shape is flagged as "spiky" will come later.]

Weights

The straight skeleton[6] being used here to generate the borders of the roads and the shapes of the building, it has been clear early in the development that the polygon's segments might react differently to the shrink factor. Each side of a polygon represents a portion of road. The road, depending on its importance, might have a different width. When the shrink is process, this differences of width generate discontinuities in the speed of the segments. The weight of the segment represents this idea, and is used as a multiplier on the shrink factor requested.

This image represents the difference of weight on different segment of the polygon. On the right, higher weights implies a bigger translation of the segment.

Events have to take the weight into account. A part of the work has been done on the split events, but the results are still buggy, see blue polygon on second and third screenshots.

Export/import

CSV and SVG exports are available (to be documented).

References

↑Finding the closest road on the right at a crossroad, originally posted in polymorph.cool

↑ 4.04.1The half-edge data structure is called that because instead of storing the edges of the mesh, we store half-edges. As the name implies, a half-edge is a half of an edge and is constructed by splitting an edge down its length. We'll call the two half-edges that make up an edge a pair. Half-edges are directed and the two edges of a pair have opposite directions. Source: flipcode.com. Doubly connected edge list, also known as half-edge data structure. Source:wikipedia

↑In mathematics, and more specifically in graph theory, a directed graph (or digraph) is a graph that is a set of vertices connected by edges, where the edges have a direction associated with them. Source:Directed graph