Find the outline of a union of grid-aligned squares - math

How to get the co-ordinates of the outline shape formed using smaller grid blocks.
For example, If I used 32x32 unit blocks for construct a shape (any shape).
Then how can I get overall co-ordinates of the shape, including the negative spaces.
For example:
One could arrange the blocks like this:
(each block is 32x32 and coordinates refer to bottom left corner of the block)
Block 1 - (0,0)
BLock 2 - (32,0)
Block 3 - 64,0)
Block 4 - (64,32)
Block 5 - (64, 64)
BLock 6 - (32, 64)
BLock 6 - (0 64)
Block 7 - (0, 32)
Now you can see this will create an empty space in the middle.
So what I would like to know is, how to get the coordinates of the above shape such that I get:
Main Block = (0,0), (96,0), (0,96)
Empty space = (32,32), (64,32), (64,64), (32,64)
Is there any mathematical solution to this?
Eventually I will be doing complex shapes.
thanks
******** edit ****
Hi,
How to deal with this condition?
<------------------^<----^
| || |
V------------------>| |
<------^ /^| |
| |<------^ / || |
| || |/ || |
V------>V------>V-->V---->
i would like the result to be like this
<-------------------<----^
| |
V ^-----------> |
| | / |
| <-------^ / |
| |/ |
V------>------->--->----->

Think of each square as an outline comprised of four vectors going in a counter-clockwise chain.
<-----^
| |
| |
V----->
So for all the squares in your shape, take the union of their outline vectors. If two outline vectors in the union are identical but go in opposite directions, they cancel each other out and are removed from the union.
For example, for two squares that are side by side the union is 8 vectors
<-----^<-----^
| || |
| || |
V----->V----->
which reduces to 6 vectors because the two vertical vectors in the middle cancel:
<-----<-----^
| |
| |
V----->----->
For the example you gave, the result of this will be (after cancellations):
<-----<-----<-----^
| |
| |
V ^-----> ^
| | | |
| | | |
V <-----V ^
| |
| |
V----->----->----->
You just have to connect up the vectors in the final reduced union to read off the outline paths. Note that the inner outline ("the hole") runs clockwise.

You would probably need to focus on Boolean Polygon Operations, unions in your case. There are plenty of papers covering the 2D boolean polygon operations and constructive planar geometry, see the Wikipedia: http://en.wikipedia.org/wiki/Boolean_operations_on_polygons.

I know this is very late to the discussion, but I recently had to deal with the same problem, and came up with the following algorithm, described in a somewhat high level here.
First, some terminology. As seen in the picture, we label the top left cell "r0c0" (i.e. row 0 column 0), and the one to the right "r0c1" and so on. We say that the edge to the left of rxcy starts at x,y and goes to x,(y+1) and so on.
The idea is to first find the points at which the outline should change direction.
That is the corners of the shape. I did this by first making a 2d array of numbers where the number was 1 if there was a cell in that place, and 0 otherwise.
Then I looped over the 2d array, and found that the top left point of a cell should be included if either the cell above and the cell to the right were both not there, or if they were both there and the cell above and to the left was not there. Similarly for the three other corners of the cell. We also remember to label the points according to what intercardinal direction they are in their cell (north west, north east and so on)
After this we have a list of points. We then start by finding the top left point of those and traversing. We know to start going right after the top left point. Using the image, we go right from a north west point. We then find the point that has the same y coordinate, but an x-coordinate larger, but the least largest of the points to the right. We also know that the next corner we hit should have an intercardinal direction of north west or north east, as we can't go from north to west by going right.
In the picture we would hit the north east point at r3c6. We then know to go down after that, because going to a north east point from the right means going down afterwards. We continue like this until we can find no more points.
There might still be points left after all this. This means we have disjoint cells, or that there is a hole. So just do the whole thing again.
I get that this wall of text is quite difficult to follow along with, so here is some typescript code, that will hopefully make it a bit simpler (sorry, don't know php). If you have any questions, please reach out. Also, this code can probably be optimized.
The main function is the createOutlines function
type Position = {row: number; column: number};
type Dimensions = { rows: number; columns: number };
type Point = {
x: number;
y: number;
};
type Direction = 'up' | 'left' | 'right' | 'down';
type InterCardinal = 'nw' | 'ne' | 'sw' | 'se';
type OutlinePoint = {
point: Point;
interCardinal: InterCardinal;
};
function findOutlinePoints(
positions: Position[],
dimensions: Dimensions
): OutlinePoint[] {
// Essentially a grid of 1 and undefined where it is 1 if there is a cell in that position
// The JSON.parse(JSON.stringify()) part is just a deep copy, as javascript is quite weird
const matrixOfPoints: (number | undefined)[][] = JSON.parse(JSON.stringify(Array(dimensions.rows).fill([])));
positions.forEach(({ row, column }) => {
matrixOfPoints[row][column] = 1;
});
const points: OutlinePoint[] = [];
for (let rowIndex = 0; rowIndex < dimensions.rows; rowIndex++) {
const row = matrixOfPoints[rowIndex];
if (row.length === 0) {
continue;
}
for (let columnIndex = 0; columnIndex < dimensions.columns; columnIndex++) {
const cell = row[columnIndex];
if (!cell) {
continue;
}
// Find the values of cells around the center cell
const nw = matrixOfPoints[rowIndex - 1]?.[columnIndex - 1];
const n = matrixOfPoints[rowIndex - 1]?.[columnIndex];
const ne = matrixOfPoints[rowIndex - 1]?.[columnIndex + 1];
const w = matrixOfPoints[rowIndex]?.[columnIndex - 1];
const e = matrixOfPoints[rowIndex]?.[columnIndex + 1];
const sw = matrixOfPoints[rowIndex + 1]?.[columnIndex - 1];
const s = matrixOfPoints[rowIndex + 1]?.[columnIndex];
const se = matrixOfPoints[rowIndex + 1]?.[columnIndex + 1];
// Add the points
// Top left point
if ((n == null && w == null) || (n != null && nw == null && w != null)) {
// The north west point of this cell is a corner point, so add this point and specify that it is a north west (nw) point
points.push({
point: { x: columnIndex, y: rowIndex },
interCardinal: 'nw'
});
}
// Top right point
if ((n == null && e == null) || (n != null && ne == null && e != null)) {
points.push({
point: { x: columnIndex + 1, y: rowIndex },
interCardinal: 'ne'
});
}
// Bottom left
if ((w == null && s == null) || (w != null && sw == null && s != null)) {
points.push({
point: { x: columnIndex, y: rowIndex + 1 },
interCardinal: 'sw'
});
}
// Bottom right
if ((e == null && s == null) || (e != null && se == null && s != null)) {
points.push({
point: { x: columnIndex + 1, y: rowIndex + 1 },
interCardinal: 'se'
});
}
}
}
return points;
}
// Finds the point that is left most, and of the left most points, the one that is highest. Also finds the index of that point in the list
function findTopLeftOutlinePoint(
outlinePoints: OutlinePoint[]
): [OutlinePoint | undefined, number] {
let topLeftPoint: OutlinePoint | undefined = undefined;
let index = -1;
outlinePoints.forEach((p, i) => {
if (topLeftPoint == null) {
topLeftPoint = p;
index = i;
return;
}
if (
p.point.x < topLeftPoint.point.x ||
(p.point.x <= topLeftPoint.point.x &&
p.point.y < topLeftPoint.point.y)
) {
index = i;
topLeftPoint = p;
}
});
return [topLeftPoint, index];
}
/** E.g. going, "up", coming to "nw", one has to go "right" */
const NextDirection: Record<Direction, Record<InterCardinal, Direction>> = {
up: {
nw: 'right',
ne: 'left',
sw: 'left',
se: 'right'
},
down: {
nw: 'left',
ne: 'right',
sw: 'right',
se: 'left'
},
right: {
nw: 'up',
ne: 'down',
sw: 'down',
se: 'up'
},
left: {
nw: 'down',
ne: 'up',
sw: 'up',
se: 'down'
}
};
// Given the previous point, and the direction, find the next point from the list of points
function findNextPoint(
previousPointInPath: OutlinePoint,
points: OutlinePoint[],
direction: Direction
): [OutlinePoint, number] | undefined {
// e.g. if coming from nw going right, we should find a point that has the same y coordinates, and has an interCardinal of ne or se
let nextPointIndex: number | undefined;
let nextPoint: OutlinePoint | undefined;
switch (direction) {
case 'right':
// We are going "right"
points.forEach((p, i) => {
if (
// The next point should have the same y coordinate
p.point.y === previousPointInPath.point.y &&
// The next point should have a larger x coordinate
p.point.x > previousPointInPath.point.x &&
// If the previous point is north, then the next point should be north as well. Similar for south
p.interCardinal[0] === previousPointInPath.interCardinal[0]
) {
if (nextPoint == null) {
nextPoint = p;
nextPointIndex = i;
return;
} else if (p.point.x < nextPoint.point.x) {
// This is closer to the previous point than the one we already found
nextPoint = p;
nextPointIndex = i;
return;
}
}
});
break;
case 'left':
points.forEach((p, i) => {
if (
p.point.y === previousPointInPath.point.y &&
p.point.x < previousPointInPath.point.x &&
p.interCardinal[0] === previousPointInPath.interCardinal[0]
) {
if (nextPoint == null) {
nextPoint = p;
nextPointIndex = i;
return;
} else if (p.point.x > nextPoint.point.x) {
nextPoint = p;
nextPointIndex = i;
return;
}
}
});
break;
case 'up':
points.forEach((p, i) => {
if (
p.point.x === previousPointInPath.point.x &&
p.point.y < previousPointInPath.point.y &&
p.interCardinal[1] === previousPointInPath.interCardinal[1]
) {
if (nextPoint == null) {
nextPoint = p;
nextPointIndex = i;
return;
} else if (p.point.y > nextPoint.point.y) {
nextPoint = p;
nextPointIndex = i;
return;
}
}
});
break;
case 'down':
points.forEach((p, i) => {
if (
p.point.x === previousPointInPath.point.x &&
p.point.y > previousPointInPath.point.y &&
p.interCardinal[1] === previousPointInPath.interCardinal[1]
) {
if (nextPoint == null) {
nextPoint = p;
nextPointIndex = i;
return;
} else if (p.point.y < nextPoint.point.y) {
nextPoint = p;
nextPointIndex = i;
return;
}
}
});
break;
}
// If we didn't find anything, we should close the loop
if (nextPoint == null || nextPointIndex == null) return undefined;
return [nextPoint, nextPointIndex];
}
// Find the oultine of cells in a grid.
function createOutlines(
positions: Position[],
dimensions: Dimensions
): OutlinePoint[][] {
const points = findOutlinePoints(positions, dimensions);
const paths: OutlinePoint[][] = [];
while (points.length > 0) {
// This loop creates new outlines until there are no points left
const pathPoints: OutlinePoint[] = [];
const [topLeftPoint, index] = findTopLeftOutlinePoint(points);
if (topLeftPoint == null) return [];
// Remove the top left point
points.splice(index, 1);
// And add it to the path
pathPoints.push(topLeftPoint);
let direction: Direction = 'up';
while (true) {
const previousPointInPath = pathPoints[pathPoints.length - 1];
direction = NextDirection[direction][previousPointInPath.interCardinal];
const nextPointInfo = findNextPoint(previousPointInPath, points, direction);
if (nextPointInfo == null) {
// We have reached the end
pathPoints.push(topLeftPoint); // Add the first point to the end to make a loop
paths.push(pathPoints);
break;
}
const [nextPoint, nextPointIndex] = nextPointInfo;
points.splice(nextPointIndex, 1);
pathPoints.push(nextPoint);
}
}
return paths;
}

Related

ZigZag path onMouseDrag with paper.js

Hi im tryign to create a zigzag path using Path.js's onMouseDrag function but getting in to a bit of a muddle here is a sketch
and code
var path
var zigzag
var length
var count
var delta=[]
tool.fixedDistance= 20
function onMouseDown(event){
path= new Path()
path.add(event.point)
zigzag= new Path()
}
function onMouseDrag(event){
event.delta += 90
path.add(event.delta)
delta.push(event.delta)
}
function onMouseUp(event){
length= path.segments.length
zigzag= new Path()
zigzag.add(event.point)
console.log(delta)
delta.forEach(( zig , i) => {
zigzag.add(i % 2 == 0 ? zig + 20 : zig - 20)
})
zigzag.selected= true
}
Based on my previous answer, here is a sketch demonstrating a possible way to do it.
let line;
let zigZag;
function onMouseDown(event) {
line = new Path({
segments: [event.point, event.point],
strokeColor: 'black'
});
zigZag = createZigZagFromLine(line);
}
function onMouseDrag(event) {
line.lastSegment.point = event.point;
if (zigZag) {
zigZag.remove();
}
zigZag = createZigZagFromLine(line);
}
function createZigZagFromLine(line) {
const zigZag = new Path({ selected: true });
const count = 20, length = line.length;
for (let i = 0; i <= count; i++) {
const offset = i / count * length;
const normal = i === 0 || i === count
? new Point(0, 0)
: line.getNormalAt(offset) * 30;
const point = line.getPointAt(offset).add(i % 2 == 0 ? normal
: -normal);
zigZag.add(point);
}
return zigZag;
}

Find the Elements within the given distance within Tree

I have a tree which as certain elements, I have a method essentially returns a list of elements that are within the distance.
Example
In the tree above, once I have my method, I should be able to input a data and distance. Lets say the data I input is 1 and the distance is 2. In this case, the method should output elements, [2,3,4] because I should be able to output data that is less than or equal to the given distance.
I know how to output data that have a distance of 2 away, but I am struggling to include data that includes data that is 1 away as well.
void printkdistanceNodeDown(Node node, int k)
{
if (node == null || k < 0)
return;
if (k == 0)
{
System.out.print(node.data);
System.out.println("");
return;
}
// Recur for left and right subtrees
printkdistanceNodeDown(node.left, k - 1);
printkdistanceNodeDown(node.right, k - 1);
}
int printkdistanceNode(Node node, Node target, int k)
{
if (node == null)
return -1;
if (node == target)
{
printkdistanceNodeDown(node, k);
return 0;
}
// Recur for left subtree
int dl = printkdistanceNode(node.left, target, k);
// Check if target node was found in left subtree
if (dl != -1)
{
if (dl + 1 == k)
{
System.out.print(node.data);
System.out.println("");
}
else
printkdistanceNodeDown(node.right, k - dl - 2);
// Add 1 to the distance and return value for parent calls
return 1 + dl;
}
// MIRROR OF ABOVE CODE FOR RIGHT SUBTREE
// Note that we reach here only when node was not found in left
// subtree
int dr = printkdistanceNode(node.right, target, k);
if (dr != -1)
{
if (dr + 1 == k)
{
System.out.print(node.data);
System.out.println("");
}
else
printkdistanceNodeDown(node.left, k - dr - 2);
return 1 + dr;
}
// If target was neither present in left nor in right subtree
return -1;
}

Implementing a wall in get successor for A*

I have a get successor function C# which get the successor for Nodes in a grid
public ArrayList GetSuccessors()
{
ArrayList successors = new ArrayList ();
for (int xd=-1;xd<=1;xd++)
{
for (int yd=-1;yd<=1;yd++)
{
if ((xd != 0 && yd == 0) || (xd == 0 && yd != 0)) // to take only up - down - right - left
{
if (Map.getMap(x + xd, y + yd) != -1)
{
// generate a new node where the parent node is the existance, goal node, cost , x , y
Node n = new Node(this, this._goalNode, Map.getMap(x + xd, y + yd), x + xd, y + yd);
// to elemenat duplication
if (!n.isMatch(this.parentNode) && !n.isMatch(this))
successors.Add(n);
}
}
}
}
return successors;
}
for getMap function it's just return if the value inside the map 1 or -1 if it's 1 then I take this node if it's -1 then No it's an obstacles.
My question is how I can implement a condition so that if there is a wall between
[0,0] and [0,1] in the grid don't take [0,1] as a successor for [0,0]
thank you

Ray.direction where camera (object) is looking at

I am doing simple collision detection and although I can easily detect up/down objects with a THREE.ray, I am having a hard time to find what's in front/back of a camera (or any object) when they rotate? I tried projecting a ray with a projector and to display how that ray shoots using helper arrow. Once I start rotating camera around Y axis, ray points to inverse direction or just acts weirdly...
ray = new THREE.Ray();
projector = new THREE.Projector();
vector = projector.projectVector( coll.getObject().matrix.getPosition().clone(), camera );
ray.direction = vector.normalize();
ray.origin = coll.getObject().matrix.getPosition().clone();
helper.setDirection(ray.direction.clone());
helper.position = ray.origin.clone();
I ended up setting a cube around my object attached to a camera and shooting rays through vertices added up, like this:
vertices = coll.getObject().geometry.vertices;
rad = coll.getObject().boundRadius+1;
var directions = {
"up": [4,1],
"down": [6,2],
"front": [3,4],
"back": [7,0],
"left": [5,6],
"right": [1,2],
};
var collisions = {
"up": {},
"down": {},
"front": {},
"back": {},
"left": {},
"right": {},
};
for (key in directions){
(directions[key].length > 1) ? localVertex = vertices[directions[key][0]].clone().addSelf(vertices[directions[key][1]].clone()) : localVertex = vertices[directions[key][0]].clone();
globalVertex = coll.getObject().matrix.multiplyVector3(localVertex);
directionVector = globalVertex.subSelf( coll.getObject().position );
ray = new THREE.Ray( coll.getObject().position.clone(), directionVector.clone().normalize(), 0, 1000 );
intersects = ray.intersectObjects(obj, true);
if (intersects.length > 0) {
distance = intersects[ 0 ].distance;
if (distance >= 0 && distance <= rad) {
collisions[key] = intersects[ 0 ];
} else {
collisions[key] = false;
}
} else {
collisions[key] = false;
++falseCount;
}
}
}
return (falseCount !== 6) ? collisions : false;

Determine position of number in a grid of numbers centered around 0 and increasing in spiral

I've got the following grid of numbers centered around 0 and increasing in spiral. I need an algorithm which would receive number in spiral and return x; y - numbers of moves how to get to that number from 0. For example for number 9 it would return -2; -1. For 4 it would be 1; 1.
25|26|... etc.
24| 9|10|11|12
23| 8| 1| 2|13
22| 7| 0| 3|14
21| 6| 5| 4|15
20|19|18|17|16
This spiral can be slightly changed if it would help the algorithm to be better.
Use whatever language you like. I would really appreciate mathematical explanation.
Thank you.
First we need to determine which cycle (distance from center) and sector (north, east, south or west) we are in. Then we can determine the exact position of the number.
The first numbers in each cycle is as follows: 1, 9, 25
This is a quadratic sequence: first(n) = (2n-1)^2 = 4n^2 - 4n + 1
The inverse of this is the cycle-number: cycle(i) = floor((sqrt(i) + 1) / 2)
The length of a cycle is: length(n) = first(n+1) - first(n) = 8n
The sector will then be:
sector(i) = floor(4 * (i - first(cycle(i))) / length(cycle(i)))
Finally, to get the position, we need to extrapolate from the position of the first number in the cycle and sector.
To put it all together:
def first(cycle):
x = 2 * cycle - 1
return x * x
def cycle(index):
return (isqrt(index) + 1)//2
def length(cycle):
return 8 * cycle
def sector(index):
c = cycle(index)
offset = index - first(c)
n = length(c)
return 4 * offset / n
def position(index):
c = cycle(index)
s = sector(index)
offset = index - first(c) - s * length(c) // 4
if s == 0: #north
return -c, -c + offset + 1
if s == 1: #east
return -c + offset + 1, c
if s == 2: #south
return c, c - offset - 1
# else, west
return c - offset - 1, -c
def isqrt(x):
"""Calculates the integer square root of a number"""
if x < 0:
raise ValueError('square root not defined for negative numbers')
n = int(x)
if n == 0:
return 0
a, b = divmod(n.bit_length(), 2)
x = 2**(a+b)
while True:
y = (x + n//x)//2
if y >= x:
return x
x = y
Example:
>>> position(9)
(-2, -1)
>>> position(4)
(1, 1)
>>> position(123456)
(-176, 80)
Do you mean something like this? I did not implement any algorithm and the code can be written better but it works - that's always a start :) Just change the threshold value for whatever you wish and you'll get the result.
static int threshold=14, x=0, y=0;
public static void main(String[] args) {
int yChange=1, xChange=1, count=0;
while( !end(count) ){
for (int i = 0; i < yChange; i++) {
if( end(count) )return;
count++;
y--;
}
yChange++;
for (int i = 0; i < xChange; i++) {
if( end(count) )return;
count++;
x++;
}
xChange++;
for (int i = 0; i < yChange; i++) {
if( end(count) )return;
count++;
y++;
}
yChange++;
for (int i = 0; i < xChange; i++) {
if( end(count) )return;
count++;
x--;
}
xChange++;
}
}
public static boolean end(int count){
if(count<threshold){
return false;
}else{
System.out.println("count: "+count+", x: "+x+", y: "+y);
return true;
}
}

Resources