does cvxpy need starting conditions provided is zeros are not satisfying contraints? - python
I am trying to modify the maxrect library to solve for maximum rectangles unconstrained by orientation.
looking at the code I see the constraints are:
""" :param coordinates:
A list of of [x, y] pairs describing a closed, convex polygon.
"""
coordinates = np.array(coordinates)
x_range = np.max(coordinates, axis=0)[0]-np.min(coordinates, axis=0)[0]
y_range = np.max(coordinates, axis=0)[1]-np.min(coordinates, axis=0)[1]
scale = np.array([x_range, y_range])
sc_coordinates = coordinates/scale
poly = Polygon(sc_coordinates)
inside_pt = (poly.representative_point().x,
poly.representative_point().y)
A1, A2, B = pts_to_leq(sc_coordinates)
bl = cvxpy.Variable(2)
tr = cvxpy.Variable(2)
br = cvxpy.Variable(2)
tl = cvxpy.Variable(2)
obj = cvxpy.Maximize(cvxpy.log(tr[0] - bl[0]) + cvxpy.log(tr[1] - bl[1]))
constraints = [bl[0] == tl[0],
br[0] == tr[0],
tl[1] == tr[1],
bl[1] == br[1],
]
for i in range(len(B)):
if inside_pt[0] * A1[i] + inside_pt[1] * A2[i] <= B[i]:
constraints.append(bl[0] * A1[i] + bl[1] * A2[i] <= B[i])
constraints.append(tr[0] * A1[i] + tr[1] * A2[i] <= B[i])
constraints.append(br[0] * A1[i] + br[1] * A2[i] <= B[i])
constraints.append(tl[0] * A1[i] + tl[1] * A2[i] <= B[i])
else:
constraints.append(bl[0] * A1[i] + bl[1] * A2[i] >= B[i])
constraints.append(tr[0] * A1[i] + tr[1] * A2[i] >= B[i])
constraints.append(br[0] * A1[i] + br[1] * A2[i] >= B[i])
constraints.append(tl[0] * A1[i] + tl[1] * A2[i] >= B[i])
that is, they convert each point in the circumscribing polygon to the Ax + Ay = B and check if the corners of the rectangle are inside of it, and maximize the diagonals. additionally, there are 4 constraints that ensure that the angles of the corners are aligned with the reference frame.
I was thinking I could just remove those 4 constraints.
However, this allows the rectangle to exceed the bounds of the circumscribing polygon. That may mean that I'm not entirely correct about the purpose of the above constraints. It could also be that now those points are allowed to drift from their cardinal orientation within the reference frame, so I tried adding different constraints to maintain cardinality of the rectangle's points:
if aligned:
constraints.append(bl[0] == tl[0])
constraints.append(br[0] == tr[0])
constraints.append(tl[1] == tr[1])
constraints.append(bl[1] == br[1])
else:
constraints.append(bl[0] < br[0])
constraints.append(bl[0] < tr[0])
constraints.append(tl[0] < br[0])
constraints.append(tl[0] < tr[0])
constraints.append(bl[1] < tl[1])
constraints.append(bl[1] < tr[1])
constraints.append(br[1] < tl[1])
constraints.append(br[1] < tr[1])
Could someone help me to see what I am missing?
sample problem:
square = Polygon([(0,0), (0,2), (2,2), (2,0)], [
[(0.5,0.5), (0.5,1.2), (1,1.2), (1,0.5)],
[(1.1,1.1), (1.1,1.5), (1.5,1.5), (1.5,1.1)]
])
line = LineString((square.exterior.coords[0], square.exterior.coords[1]))
max_hull = find_maximal_convex_hull(line, square)
print('max hull', max_hull.wkt, max_hull.area)
# this line calls my cvypy script
pa = get_maximal_rectangle(max_hull.exterior.coords)
max_rect = Polygon([(pa[0][0],pa[0][1]), (pa[0][0],pa[1][1]), (pa[1][0],pa[1][1]), (pa[1][0],pa[0][1])])
print('max rectangle', pa)
plt.axis(xmin=-0.125,xmax=2.125,ymin=-0.125,ymax=2.125)
plt.plot(*square.exterior.xy, color='g')
[plt.plot(*i.xy, color='y') for i in square.interiors]
plt.plot(*max_hull.exterior.xy, color='b')
[plt.plot(*i.xy, color='r') for i in max_hull.interiors]
plt.plot(*max_rect.exterior.xy, color='r')
plt.show()
in the above code I am given a complex shape and an edge. I must cut this down to a (roughly/nearly) largest convex shape, and the edge must intersect that shape. this work I've already done, it is assigned to the variable max_hull.
Now, I want the largest rectangle in the shape, regardless of orientation. In the image below, drawn from the code above, I show the outer square in green (the left edge is the required edge), its holes in yellow, the remaining convex shape, that is the outer polygon given to my cvypy in blue, -- it extends from the visible bottom line up to the top -- and the candidate rectangle returned from cvxpy in red.
the log output is:
<ipython-input-2-efd2419ff139>:272: ShapelyDeprecationWarning: Iteration over multi-part geometries is deprecated and will be removed in Shapely 2.0. Use the `geoms` property to access the constituent parts of a multi-part geometry.
for base in split(S, ll):
455 unique polygons considered
max hull POLYGON ((0 0.95, 0 2, 2 2, 2 1.95, 0 0.95)) 1.0999999999999999
max rectangle (array([7.13062842e-09, 9.50000011e-01]), array([1.99999998, 1.99999999]))
in order to use the maxrect library with modern cvypy and python, change get_max_rectangle (in init.py) solve statement to prob.solve() and the return statement. after applying my code, this is the customized function I am using:
import numpy as np
import cvxpy
from shapely.geometry import Polygon
def rect2poly(ll, ur):
"""
Convert rectangle defined by lower left/upper right
to a closed polygon representation.
"""
x0, y0 = ll
x1, y1 = ur
return [
[x0, y0],
[x0, y1],
[x1, y1],
[x1, y0],
[x0, y0]
]
def get_intersection(coords):
"""Given an input list of coordinates, find the intersection
section of corner coordinates. Returns geojson of the
interesection polygon.
"""
ipoly = None
for coord in coords:
if ipoly is None:
ipoly = Polygon(coord)
else:
tmp = Polygon(coord)
ipoly = ipoly.intersection(tmp)
# close the polygon loop by adding the first coordinate again
first_x = ipoly.exterior.coords.xy[0][0]
first_y = ipoly.exterior.coords.xy[1][0]
ipoly.exterior.coords.xy[0].append(first_x)
ipoly.exterior.coords.xy[1].append(first_y)
inter_coords = zip(
ipoly.exterior.coords.xy[0], ipoly.exterior.coords.xy[1])
inter_gj = {"geometry":
{"coordinates": [inter_coords],
"type": "Polygon"},
"properties": {}, "type": "Feature"}
return inter_gj, inter_coords
def two_pts_to_line(pt1, pt2):
"""
Create a line from two points in form of
a1(x) + a2(y) = b
"""
pt1 = [float(p) for p in pt1]
pt2 = [float(p) for p in pt2]
try:
slp = (pt2[1] - pt1[1]) / (pt2[0] - pt1[0])
except ZeroDivisionError:
slp = 1e5 * (pt2[1] - pt1[1])
a1 = -slp
a2 = 1.
b = -slp * pt1[0] + pt1[1]
return a1, a2, b
def pts_to_leq(coords):
"""
Converts a set of points to form Ax = b, but since
x is of length 2 this is like A1(x1) + A2(x2) = B.
returns A1, A2, B
"""
A1 = []
A2 = []
B = []
for i in range(len(coords) - 1):
pt1 = coords[i]
pt2 = coords[i + 1]
a1, a2, b = two_pts_to_line(pt1, pt2)
A1.append(a1)
A2.append(a2)
B.append(b)
return A1, A2, B
def get_maximal_rectangle(coordinates, aligned=False):
"""
Find the largest, inscribed, axis-aligned rectangle.
:param coordinates:
A list of of [x, y] pairs describing a closed, convex polygon.
"""
coordinates = np.array(coordinates)
x_range = np.max(coordinates, axis=0)[0]-np.min(coordinates, axis=0)[0]
y_range = np.max(coordinates, axis=0)[1]-np.min(coordinates, axis=0)[1]
scale = np.array([x_range, y_range])
sc_coordinates = coordinates/scale
rep_point = Polygon(sc_coordinates).representative_point()
inside_pt = (rep_point.x, rep_point.y)
A1, A2, B = pts_to_leq(sc_coordinates)
bl = cvxpy.Variable(2)
tr = cvxpy.Variable(2)
br = cvxpy.Variable(2)
tl = cvxpy.Variable(2)
obj = cvxpy.Maximize(cvxpy.log(tr[0] - bl[0]) + cvxpy.log(tr[1] - bl[1]))
constraints = []
if aligned:
constraints.append(bl[0] == tl[0])
constraints.append(br[0] == tr[0])
constraints.append(tl[1] == tr[1])
constraints.append(bl[1] == br[1])
else:
constraints.append(bl[0] < br[0])
constraints.append(bl[0] < tr[0])
constraints.append(tl[0] < br[0])
constraints.append(tl[0] < tr[0])
constraints.append(bl[1] < tl[1])
constraints.append(bl[1] < tr[1])
constraints.append(br[1] < tl[1])
constraints.append(br[1] < tr[1])
for i in range(len(B)):
if inside_pt[0] * A1[i] + inside_pt[1] * A2[i] <= B[i]:
constraints.append(bl[0] * A1[i] + bl[1] * A2[i] <= B[i])
constraints.append(tr[0] * A1[i] + tr[1] * A2[i] <= B[i])
constraints.append(br[0] * A1[i] + br[1] * A2[i] <= B[i])
constraints.append(tl[0] * A1[i] + tl[1] * A2[i] <= B[i])
else:
constraints.append(bl[0] * A1[i] + bl[1] * A2[i] >= B[i])
constraints.append(tr[0] * A1[i] + tr[1] * A2[i] >= B[i])
constraints.append(br[0] * A1[i] + br[1] * A2[i] >= B[i])
constraints.append(tl[0] * A1[i] + tl[1] * A2[i] >= B[i])
prob = cvxpy.Problem(obj, constraints)
#prob.solve(solver=cvxpy.CVXOPT, verbose=False, max_iters=1000, reltol=1e-9)
#prob.solve(solver=cvxpy.SCS, verbose=True, use_indirect=False, max_iters=int(1e5))
prob.solve()
bottom_left = np.array(bl.value).T * scale
top_right = np.array(tr.value).T * scale
#return list(bottom_left[0]), list(top_right[0])
return bottom_left, top_right
No other function in the above was modified.
The problem of finding an area-maximizing unconstrained rectangle contained in a polygon is non-convex, so you simply have no chance to express it using cvxpy.
The constraints you removed mean you have an axis-aligned rectangle, without them you just have an arbitrary 4-gon contained in the big polygon for which you are maximizing the product of two sides - not something intuitive or what you wanted.
See for instance https://docs.mosek.com/modeling-cookbook/powo.html#maximum-volume-cuboid
Related
How to increase FPS in ursina python
I want to create survival games with infinite block terrain(like Minecraft). So i using ursina python game engine, you can see it here So i using perlin noise to create the terrain with build-in ursina block model. I test for first 25 block and it work pretty good with above 100 FPS, so i start increase to 250 block and more because I want a infinite terrain. But i ran to some problem, when i increase to 100 block or more, my FPS start to decrease below 30 FPS (With i create just one layer). Here is my code: #-------------------------------Noise.py(I got on the github)------------------------- # Copyright (c) 2008, Casey Duncan (casey dot duncan at gmail dot com) # see LICENSE.txt for details """Perlin noise -- pure python implementation""" __version__ = '$Id: perlin.py 521 2008-12-15 03:03:52Z casey.duncan $' from math import floor, fmod, sqrt from random import randint # 3D Gradient vectors _GRAD3 = ((1,1,0),(-1,1,0),(1,-1,0),(-1,-1,0), (1,0,1),(-1,0,1),(1,0,-1),(-1,0,-1), (0,1,1),(0,-1,1),(0,1,-1),(0,-1,-1), (1,1,0),(0,-1,1),(-1,1,0),(0,-1,-1), ) # 4D Gradient vectors _GRAD4 = ((0,1,1,1), (0,1,1,-1), (0,1,-1,1), (0,1,-1,-1), (0,-1,1,1), (0,-1,1,-1), (0,-1,-1,1), (0,-1,-1,-1), (1,0,1,1), (1,0,1,-1), (1,0,-1,1), (1,0,-1,-1), (-1,0,1,1), (-1,0,1,-1), (-1,0,-1,1), (-1,0,-1,-1), (1,1,0,1), (1,1,0,-1), (1,-1,0,1), (1,-1,0,-1), (-1,1,0,1), (-1,1,0,-1), (-1,-1,0,1), (-1,-1,0,-1), (1,1,1,0), (1,1,-1,0), (1,-1,1,0), (1,-1,-1,0), (-1,1,1,0), (-1,1,-1,0), (-1,-1,1,0), (-1,-1,-1,0)) # A lookup table to traverse the simplex around a given point in 4D. # Details can be found where this table is used, in the 4D noise method. _SIMPLEX = ( (0,1,2,3),(0,1,3,2),(0,0,0,0),(0,2,3,1),(0,0,0,0),(0,0,0,0),(0,0,0,0),(1,2,3,0), (0,2,1,3),(0,0,0,0),(0,3,1,2),(0,3,2,1),(0,0,0,0),(0,0,0,0),(0,0,0,0),(1,3,2,0), (0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0), (1,2,0,3),(0,0,0,0),(1,3,0,2),(0,0,0,0),(0,0,0,0),(0,0,0,0),(2,3,0,1),(2,3,1,0), (1,0,2,3),(1,0,3,2),(0,0,0,0),(0,0,0,0),(0,0,0,0),(2,0,3,1),(0,0,0,0),(2,1,3,0), (0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0), (2,0,1,3),(0,0,0,0),(0,0,0,0),(0,0,0,0),(3,0,1,2),(3,0,2,1),(0,0,0,0),(3,1,2,0), (2,1,0,3),(0,0,0,0),(0,0,0,0),(0,0,0,0),(3,1,0,2),(0,0,0,0),(3,2,0,1),(3,2,1,0)) # Simplex skew constants _F2 = 0.5 * (sqrt(3.0) - 1.0) _G2 = (3.0 - sqrt(3.0)) / 6.0 _F3 = 1.0 / 3.0 _G3 = 1.0 / 6.0 class BaseNoise: """Noise abstract base class""" permutation = (151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9, 129,22,39,253,9,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180) period = len(permutation) # Double permutation array so we don't need to wrap permutation = permutation * 2 randint_function = randint def __init__(self, period=None, permutation_table=None, randint_function=None): """Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default permutation table generates the exact same noise pattern each time. An integer period can be specified, to generate a random permutation table with period elements. The period determines the (integer) interval that the noise repeats, which is useful for creating tiled textures. period should be a power-of-two, though this is not enforced. Note that the speed of the noise algorithm is indpendent of the period size, though larger periods mean a larger table, which consume more memory. A permutation table consisting of an iterable sequence of whole numbers can be specified directly. This should have a power-of-two length. Typical permutation tables are a sequnce of unique integers in the range [0,period) in random order, though other arrangements could prove useful, they will not be "pure" simplex noise. The largest element in the sequence must be no larger than period-1. period and permutation_table may not be specified together. A substitute for the method random.randint(a, b) can be chosen. The method must take two integer parameters a and b and return an integer N such that a <= N <= b. """ if randint_function is not None: # do this before calling randomize() if not hasattr(randint_function, '__call__'): raise TypeError( 'randint_function has to be a function') self.randint_function = randint_function if period is None: period = self.period # enforce actually calling randomize() if period is not None and permutation_table is not None: raise ValueError( 'Can specify either period or permutation_table, not both') if period is not None: self.randomize(period) elif permutation_table is not None: self.permutation = tuple(permutation_table) * 2 self.period = len(permutation_table) def randomize(self, period=None): """Randomize the permutation table used by the noise functions. This makes them generate a different noise pattern for the same inputs. """ if period is not None: self.period = period perm = list(range(self.period)) perm_right = self.period - 1 for i in list(perm): j = self.randint_function(0, perm_right) perm[i], perm[j] = perm[j], perm[i] self.permutation = tuple(perm) * 2 class SimplexNoise(BaseNoise): """Perlin simplex noise generator Adapted from Stefan Gustavson's Java implementation described here: http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf To summarize: "In 2001, Ken Perlin presented 'simplex noise', a replacement for his classic noise algorithm. Classic 'Perlin noise' won him an academy award and has become an ubiquitous procedural primitive for computer graphics over the years, but in hindsight it has quite a few limitations. Ken Perlin himself designed simplex noise specifically to overcome those limitations, and he spent a lot of good thinking on it. Therefore, it is a better idea than his original algorithm. A few of the more prominent advantages are: * Simplex noise has a lower computational complexity and requires fewer multiplications. * Simplex noise scales to higher dimensions (4D, 5D and up) with much less computational cost, the complexity is O(N) for N dimensions instead of the O(2^N) of classic Noise. * Simplex noise has no noticeable directional artifacts. Simplex noise has a well-defined and continuous gradient everywhere that can be computed quite cheaply. * Simplex noise is easy to implement in hardware." """ def noise2(self, x, y): """2D Perlin simplex noise. Return a floating point value from -1 to 1 for the given x, y coordinate. The same value is always returned for a given x, y pair unless the permutation table changes (see randomize above). """ # Skew input space to determine which simplex (triangle) we are in s = (x + y) * _F2 i = floor(x + s) j = floor(y + s) t = (i + j) * _G2 x0 = x - (i - t) # "Unskewed" distances from cell origin y0 = y - (j - t) if x0 > y0: i1 = 1; j1 = 0 # Lower triangle, XY order: (0,0)->(1,0)->(1,1) else: i1 = 0; j1 = 1 # Upper triangle, YX order: (0,0)->(0,1)->(1,1) x1 = x0 - i1 + _G2 # Offsets for middle corner in (x,y) unskewed coords y1 = y0 - j1 + _G2 x2 = x0 + _G2 * 2.0 - 1.0 # Offsets for last corner in (x,y) unskewed coords y2 = y0 + _G2 * 2.0 - 1.0 # Determine hashed gradient indices of the three simplex corners perm = self.permutation ii = int(i) % self.period jj = int(j) % self.period gi0 = perm[ii + perm[jj]] % 12 gi1 = perm[ii + i1 + perm[jj + j1]] % 12 gi2 = perm[ii + 1 + perm[jj + 1]] % 12 # Calculate the contribution from the three corners tt = 0.5 - x0**2 - y0**2 if tt > 0: g = _GRAD3[gi0] noise = tt**4 * (g[0] * x0 + g[1] * y0) else: noise = 0.0 tt = 0.5 - x1**2 - y1**2 if tt > 0: g = _GRAD3[gi1] noise += tt**4 * (g[0] * x1 + g[1] * y1) tt = 0.5 - x2**2 - y2**2 if tt > 0: g = _GRAD3[gi2] noise += tt**4 * (g[0] * x2 + g[1] * y2) return noise * 70.0 # scale noise to [-1, 1] def noise3(self, x, y, z): """3D Perlin simplex noise. Return a floating point value from -1 to 1 for the given x, y, z coordinate. The same value is always returned for a given x, y, z pair unless the permutation table changes (see randomize above). """ # Skew the input space to determine which simplex cell we're in s = (x + y + z) * _F3 i = floor(x + s) j = floor(y + s) k = floor(z + s) t = (i + j + k) * _G3 x0 = x - (i - t) # "Unskewed" distances from cell origin y0 = y - (j - t) z0 = z - (k - t) # For the 3D case, the simplex shape is a slightly irregular tetrahedron. # Determine which simplex we are in. if x0 >= y0: if y0 >= z0: i1 = 1; j1 = 0; k1 = 0 i2 = 1; j2 = 1; k2 = 0 elif x0 >= z0: i1 = 1; j1 = 0; k1 = 0 i2 = 1; j2 = 0; k2 = 1 else: i1 = 0; j1 = 0; k1 = 1 i2 = 1; j2 = 0; k2 = 1 else: # x0 < y0 if y0 < z0: i1 = 0; j1 = 0; k1 = 1 i2 = 0; j2 = 1; k2 = 1 elif x0 < z0: i1 = 0; j1 = 1; k1 = 0 i2 = 0; j2 = 1; k2 = 1 else: i1 = 0; j1 = 1; k1 = 0 i2 = 1; j2 = 1; k2 = 0 # Offsets for remaining corners x1 = x0 - i1 + _G3 y1 = y0 - j1 + _G3 z1 = z0 - k1 + _G3 x2 = x0 - i2 + 2.0 * _G3 y2 = y0 - j2 + 2.0 * _G3 z2 = z0 - k2 + 2.0 * _G3 x3 = x0 - 1.0 + 3.0 * _G3 y3 = y0 - 1.0 + 3.0 * _G3 z3 = z0 - 1.0 + 3.0 * _G3 # Calculate the hashed gradient indices of the four simplex corners perm = self.permutation ii = int(i) % self.period jj = int(j) % self.period kk = int(k) % self.period gi0 = perm[ii + perm[jj + perm[kk]]] % 12 gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1]]] % 12 gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2]]] % 12 gi3 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1]]] % 12 # Calculate the contribution from the four corners noise = 0.0 tt = 0.6 - x0**2 - y0**2 - z0**2 if tt > 0: g = _GRAD3[gi0] noise = tt**4 * (g[0] * x0 + g[1] * y0 + g[2] * z0) else: noise = 0.0 tt = 0.6 - x1**2 - y1**2 - z1**2 if tt > 0: g = _GRAD3[gi1] noise += tt**4 * (g[0] * x1 + g[1] * y1 + g[2] * z1) tt = 0.6 - x2**2 - y2**2 - z2**2 if tt > 0: g = _GRAD3[gi2] noise += tt**4 * (g[0] * x2 + g[1] * y2 + g[2] * z2) tt = 0.6 - x3**2 - y3**2 - z3**2 if tt > 0: g = _GRAD3[gi3] noise += tt**4 * (g[0] * x3 + g[1] * y3 + g[2] * z3) return noise * 32.0 def lerp(t, a, b): return a + t * (b - a) def grad3(hash, x, y, z): g = _GRAD3[hash % 16] return x*g[0] + y*g[1] + z*g[2] class TileableNoise(BaseNoise): """Tileable implemention of Perlin "improved" noise. This is based on the reference implementation published here: http://mrl.nyu.edu/~perlin/noise/ """ def noise3(self, x, y, z, repeat, base=0.0): """Tileable 3D noise. repeat specifies the integer interval in each dimension when the noise pattern repeats. base allows a different texture to be generated for the same repeat interval. """ i = int(fmod(floor(x), repeat)) j = int(fmod(floor(y), repeat)) k = int(fmod(floor(z), repeat)) ii = (i + 1) % repeat jj = (j + 1) % repeat kk = (k + 1) % repeat if base: i += base; j += base; k += base ii += base; jj += base; kk += base x -= floor(x); y -= floor(y); z -= floor(z) fx = x**3 * (x * (x * 6 - 15) + 10) fy = y**3 * (y * (y * 6 - 15) + 10) fz = z**3 * (z * (z * 6 - 15) + 10) perm = self.permutation A = perm[i] AA = perm[A + j] AB = perm[A + jj] B = perm[ii] BA = perm[B + j] BB = perm[B + jj] return lerp(fz, lerp(fy, lerp(fx, grad3(perm[AA + k], x, y, z), grad3(perm[BA + k], x - 1, y, z)), lerp(fx, grad3(perm[AB + k], x, y - 1, z), grad3(perm[BB + k], x - 1, y - 1, z))), lerp(fy, lerp(fx, grad3(perm[AA + kk], x, y, z - 1), grad3(perm[BA + kk], x - 1, y, z - 1)), lerp(fx, grad3(perm[AB + kk], x, y - 1, z - 1), grad3(perm[BB + kk], x - 1, y - 1, z - 1)))) #--------------------------Math.py(For InverseLefp)-------------------------------- def Clamp(t: float, minimum: float, maximum: float): """Float result between a min and max values.""" value = t if t < minimum: value = minimum elif t > maximum: value = maximum return value def InverseLefp(a: float, b: float, value: float): if a != b: return Clamp((value - a) / (b - a), 0, 1) return 0 #-----------------------------Game.py(Main code)---------------------- from ursina import * from ursina.prefabs import * from ursina.prefabs.first_person_controller import * from Math import InverseLefp import Noise app = Ursina() #The maximum height of the terrain maxHeight = 10 #Control the width and height of the map mapWidth = 10 mapHeight = 10 #A class that create a block class Voxel(Button): def __init__(self, position=(0,0,0)): super().__init__( parent = scene, position = position, model = 'cube', origin_y = .5, texture = 'white_cube', color = color.color(0, 0, random.uniform(.9, 1.0)), highlight_color = color.lime, ) #Detect user key input def input(self, key): if self.hovered: if key == 'right mouse down': #Place block if user right click voxel = Voxel(position=self.position + mouse.normal) if key == 'left mouse down': #Break block if user left click destroy(self) if key == 'escape': #Exit the game if user press the esc key app.userExit() #Return perlin noise value between 0 and 1 with x, y position with scale = noiseScale def GeneratedNoiseMap(y: int, x: int, noiseScale: float): #Check if the noise scale was invalid or not if noiseScale <= 0: noiseScale = 0.001 sampleX = x / noiseScale sampleY = y / noiseScale #The Noise.SimplexNoise().noise2 will return the value between -1 and 1 perlinValue = Noise.SimplexNoise().noise2(sampleX, sampleY) #The InverseLefp will make the value scale to between 0 and 1 perlinValue = InverseLefp(-1, 1, perlinValue) return perlinValue for z in range(mapHeight): for x in range(mapWidth): #Calculating the height of the block and round it to integer height = round(GeneratedNoiseMap(z, x, 20) * maxHeight) #Place the block and make it always below the player block = Voxel(position=(x, height - maxHeight - 1, z)) #Set the collider of the block block.collider = 'mesh' #Character movement player = FirstPersonController() #Run the game app.run() All file in same folder. It was working fine but the FPS is very low, so can anyone help?
I'm not able to test this code at the moment but this should serve as a starting point: level_parent = Entity(model=Mesh(vertices=[], uvs=[])) for z in range(mapHeight): for x in range(mapWidth): height = round(GeneratedNoiseMap(z, x, 20) * maxHeight) block = Voxel(position=(x, height - maxHeight - 1, z)) level_parent.model.vertices.extend(block.model.vertices) level_parent.collider = 'mesh' # call this only once after all vertices are set up For texturing, you might have to add the block.uvs from each block to level_parent.model.uvs as well. Alternatively, call level_parent.model.project_uvs() after setting up the vertices.
On my version of ursina engine (5.0.0) only this code: ` level_parent = Entity(model=Mesh(vertices=[], uvs=[])) for z in range(mapHeight): for x in range(mapWidth): height = round(GeneratedNoiseMap(z, x, 20) * maxHeight) block = Voxel(position=(x, height - maxHeight - 1, z)) #level_parent.model.vertices.extend(block.model.vertices) level_parent.combine().vertices.extend(block.combine().vertices) level_parent.collider = 'mesh' ` is working.
Efficiently get lattice points on line in square
A lattice point is a point with integer coordinates. The line is the perpendicular bisect between two lattice points A and B. (Every point on that line is equidistant from points A and B.) How can I efficiently compute the lattice points on that perpendicular bisect line within the square 0,0 → N,N? Here is a square, with some example points A and B ↓ The point M is the midpoint between A and B. My thinking has taken me thus far: The points LA, LB and RA, RB are a square you can easily compute to the left and right sides of the line AB. The midpoint LM between A and LB, and the midpoint RM A and RB is also on the perpendicular bisect line. So how can you use this information to very quickly compute the lattice points on the perpendicular bisect line between two points? this isn't homework, its just hobby coding
I might be over-thinking this, going by matovitch's latest code draft (which I've only had a brief glance at), but anyway... Let A = (A.x, A.y), B = (B.x, B.y), where (A.x, A.y, B.x, B.y) are integers. Then line p, the perpendicular bisector of AB, passes through M = (M.x, M.y) = ((A.x + B.x)/2, (A.y + B.y)/2) The product of the slopes of AB and p is -1, thus the slope of p is -(B.x - A.x) / (B.y - A.y) and hence in point-slope form the equation of p is (y - M.y) / (x - M.x) = (A.x - B.x) / (B.y - A.y) Rearranging, y*(B.y - A.y) + x*(B.x - A.x) = M.y * (B.y - A.y) + M.x * (B.x - A.x) = ((B.y + A.y) * (B.y - A.y) + (B.x + A.x) * (B.x - A.x)) / 2 = (B.y^2 - A.y^2 + B.x^2 - A.x^2) / 2 Clearly, for any lattice point (x, y), y*(B.y - A.y) + x*(B.x - A.x) must be an integer. So the line p will only pass through lattice points if (B.y^2 - A.y^2 + B.x^2 - A.x^2) is even. Now (B.y^2 - A.y^2 + B.x^2 - A.x^2) is even if & only if (A.x + B.x + A.y + B.y) is even, which is true if an even number of (A.x, A.y, B.x, B.y) are odd. In what follows, I assume that (A.x + B.x + A.y + B.y) is even. Let dx = (B.x - A.x) dy = (B.y - A.y) s = (B.y^2 - A.y^2 + B.x^2 - A.x^2) / 2 So the equation of p is y * dy + x * dx = s Because y, dy, x, dx & s are all integers that equation is a linear Diophantine equation, and the standard way to find the solutions of such an equation is to use the extended Euclidean algorithm. Our equation will only have solutions if the gcd (greatest common divisor) of dx & dy divides s. Fortunately, that's true in this case, but I won't give the proof here. Let Y, X be a solution of y * dy + x * dx = g, where g is the gcd(dx, dy), i.e., Y * dy + X * dx = g Y * dy/g + X * dx/g = 1 Let dy' = dy/g, dx' = dx/g, s' = s/g, so Y * dy' + X * dx' = 1 Dividing the last equation for p through by g, we get y * dy' + x * dx' = s' And we can now construct one solution for it. (Y * s') * dy' + (X * s') * dx' = s' i.e., (X * s', Y * s') is a lattice point on the line. We can get all solutions like this: (Y * s' + k * dx') * dy' + (X * s' - k * dy') * dx' = s', for all integers k. To restrict the solutions to the grid from (0, 0) to (W, H), we need to solve these inequalities for k: 0 <= X * s' - k * dy' <= W and 0 <= Y * s' + k * dx' <= H I won't show the solutions of those inequalities right here; for the details see the code below. #! /usr/bin/env python ''' Lattice Line Find lattice points, i.e, points with integer co-ordinates, on the line that is the perpendicular bisector of the line segment AB, where A & B are lattice points. See http://stackoverflow.com/q/31265139/4014959 Written by PM 2Ring 2015.07.08 Code for Euclid's algorithm & the Diophantine solver written 2010.11.27 ''' from __future__ import division import sys from math import floor, ceil class Point(object): ''' A simple 2D point ''' def __init__(self, x, y): self.x, self.y = x, y def __repr__(self): return "Point(%s, %s)" % (self.x, self.y) def __str__(self): return "(%s, %s)" % (self.x, self.y) def euclid(a, b): ''' Euclid's extended algorithm for the GCD. Returns a list of tuples of (dividend, quotient, divisor, remainder) ''' if a < b: a, b = b, a k = [] while True: q, r = a // b, a % b k.append((a, q, b, r)) if r == 0: break a, b = b, r return k def dio(aa, bb): ''' Linear Diophantine solver Returns [x, aa, y, bb, d]: x*aa + y*bb = d ''' a, b = abs(aa), abs(bb) swap = a < b if swap: a, b = b, a #Handle trivial cases if a == b: eqn = [2, a, -1, a] elif a % b == 0: q = a // b eqn = [1, a, 1-q, b] else: #Generate quotients & remainders list z = euclid(a, b)[::-1] #Build equation from quotients & remainders eqn = [0, 0, 1, 0] for v in z[1:]: eqn = [eqn[2], v[0], eqn[0] - eqn[2]*v[1], v[2]] #Rearrange & fix signs, if required if swap: eqn = eqn[2:] + eqn[:2] if aa < 0: eqn[:2] = [-eqn[0], -eqn[1]] if bb < 0: eqn[2:] = [-eqn[2], -eqn[3]] d = eqn[0]*eqn[1] + eqn[2]*eqn[3] if d < 0: eqn[0], eqn[2], d = -eqn[0], -eqn[2], -d return eqn + [d] def lattice_line(pA, pB, pC): ''' Find lattice points, i.e, points with integer co-ordinates, on the line that is the perpendicular bisector of the line segment AB, Only look for points in the rectangle from (0,0) to C Let M be the midpoint of AB. Then M = ((A.x + B.x)/2, (A.y + B.y)/2), and the equation of the perpendicular bisector of AB is (y - M.y) / (x - M.x) = (A.x - B.x) / (B.y - A.y) ''' nosolutions = 'No solutions found' dx = pB.x - pA.x dy = pB.y - pA.y #Test parity of co-ords to see if there are solutions if (dx + dy) % 2 == 1: print nosolutions return #Handle horizontal & vertical lines if dx == 0: #AB is vertical, so bisector is horizontal y = pB.y + pA.y if dy == 0 or y % 2 == 1: print nosolutions return y //= 2 for x in xrange(pC.x + 1): print Point(x, y) return if dy == 0: #AB is horizontal, so bisector is vertical x = pB.x + pA.x if x % 2 == 1: print nosolutions return x //= 2 for y in xrange(pC.y + 1): print Point(x, y) return #Compute s = ((pB.x + pA.x)*dx + (pB.y + pA.y)*dy) / 2 #s will always be an integer since (dx + dy) is even #The desired line is y*dy + x*dx = s s = (pB.x**2 - pA.x**2 + pB.y**2 - pA.y**2) // 2 #Find ex, ey, g: ex * dx + ey * dy = g, where g is the gcd of (dx, dy) #Note that g also divides s eqn = dio(dx, dy) ex, ey, g = eqn[::2] #Divide the parameters of the equation by the gcd dx //= g dy //= g s //= g #Find lattice limits xlo = (ex * s - pC.x) / dy xhi = ex * s / dy if dy < 0: xlo, xhi = xhi, xlo ylo = -ey * s / dx yhi = (pC.y - ey * s) / dx if dx < 0: ylo, yhi = yhi, ylo klo = int(ceil(max(xlo, ylo))) khi = int(floor(min(xhi, yhi))) print 'Points' for k in xrange(klo, khi + 1): x = ex * s - dy * k y = ey * s + dx * k assert x*dx + y*dy == s print Point(x, y) def main(): if len(sys.argv) != 7: print ''' Find lattice points, i.e, points with integer co-ordinates, on the line that is the perpendicular bisector of the line segment AB, where A & B are lattice points with co-ords (xA, yA) & (xB, yB). Only print lattice points in the rectangle from (0, 0) to (W, H) Usage: %s xA yA xB yB W H''' % sys.argv[0] exit(1) coords = [int(s) for s in sys.argv[1:]] pA = Point(*coords[0:2]) pB = Point(*coords[2:4]) pC = Point(*coords[4:6]) lattice_line(pA, pB, pC) if __name__ == '__main__': main() I haven't tested this code extensively, but it appears to work correctly. :)
Ok I sure did not explained my solution clearly, let's start again. Given a grid with twice the resolution, the middle point M will be on the grid. The minimal direction vector of the perpendicular bissector is given by V = (yB - yA, xA - xB) / gcd(yB - yA, xA - xB). Then we look at M and V modulo the lattice Z/2Z x Z/2Z to check if one can find a point M + iV with even coordinates (aka on the coarse grid). We can then compute a starting point S = M + jV (j = 0 or 1 in fact) on the lattice and get the famous set of points as {S + iV, i integer}. [Now running ;)] This C++ code print S and V, aka the nearest lattice point to the middle and the vector one can add or subtract to get the next/previous lattice point. You then have to filter the points to get those inside the square (test it here : http://coliru.stacked-crooked.com/a/ba9f8aec45e1c2ea) : int gcd(int n1, int n2) { n1 = (n1 > 0) ? n1 : -n1; n2 = (n2 > 0) ? n2 : -n2; if (n1 > n2) { int t = n1; n1 = n2; n2 = t; } while (n2 % n1 != 0) { int tmp = n2 % n1; n2 = n1; n1 = tmp; } return n1; } struct Point { const Point& operator=(const Point& rhs) { x = rhs.x; y = rhs.y; return *this; } const Point& operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; } const Point& operator-=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; } const Point& operator/=(int rhs) { x /= rhs; y /= rhs; return *this; } const Point& reduce() { return *this /= gcd(x, y); } int x; int y; }; const Point operator+(Point lhs, const Point& rhs) { lhs += rhs; return lhs; } const Point operator-(Point lhs, const Point& rhs) { lhs -= rhs; return lhs; } const Point operator/(Point lhs, int rhs) { lhs /= rhs; return lhs; } bool findBase(Point& p1, Point& p2, Point& oBase, Point& oDir) { Point m = p1 + p2; Point v = {p2.y - p1.y, p1.x - p2.x}; oDir = v.reduce(); if (m.x % 2 == 0 && m.y % 2 == 0) { oBase = m / 2; return true; } else if (((m.x % 2 == 0 && v.x % 2 == 0) && (m.y % 2 == 1 && v.y % 2 == 1)) || ((m.x % 2 == 1 && v.x % 2 == 1) && (m.y % 2 == 0 && v.y % 2 == 0)) || ((m.x % 2 == 1 && v.x % 2 == 1) && (m.y % 2 == 1 && v.y % 2 == 1))) { oBase = (m + v) / 2; return true; } else { return false; } }
Koch Snowflake in Python won't work
I'm having a problem with this Python program. It's supposed to draw a Koch-Snowflake with n iterations. The code does compile but it won't draw a snowflake and I can't find my mistake. I'd be very thankful if anyone could help me out with this! from math import sqrt from matplotlib import pyplot as plt class vector: def __init__(self,one,two): self.x = one self.y = two def printV(self): s = "(" + str(self.x) + "," + str(self.y) + ")" print s def __len__(self): l = sqrt(self.x**2 + self.y**2) return l def kochSnowflakeImpl(p1,p2): u = vector(p1.x + p2.x - p1.x, p1.y + p2.y - p1.y) array = [] #calculate n1 n1 = vector(p1.x + 1.0/3.0 * u.x, p1.y + (1.0/3.0) * u.y) #calculate n2 n2 = vector(p1.x + 2.0/3.0 * u.x,p1.y + 2.0/3.0 * u.y) v = vector(n1.y + n2.y - n1.y, -(n1.x + n2.x - n1.x)) #is an orthogonal vector to u #calculate n3 n3 = vector(n1.x + 0.5*u.x + sqrt(3.0)/2.0 * v.x, p1.y + 0.5*u.y + sqrt(3.0)/2.0* v.y) array.append([n1.x,n1.y]) array.append([n2.x,n2.y]) array.append([n3.x,n3.y]) return n1,n2,n3,array def kochSnowflake(level): p1 = vector(0,0) #format: p = (x,y) p2 = vector(1,0) p3 = vector(0.5,sqrt(3)/2) array = [[p1.x,p1.y],[p2.x,p2.y],[p3.x,p3.y],[p1.x,p1.y]] while level > 0: if level == 1: n1,n2,n3,array1 = kochSnowflakeImpl(p1,p2) n4,n5,n6,array2 = kochSnowflakeImpl(p2,p3) n7,n8,n9,array3 = kochSnowflakeImpl(p3,p2) for i in array1: array.append(i) for j in array2: array.append(j) for k in array3: array.append(k) else: n1,n2,n3,array1 = kochSnowflakeImpl(p1,p2) n11,n21,n31,array11 = kochSnowflakeImpl(n1,n3) n12,n22,n32,array12 = kochSnowflakeImpl(n3,n2) n4,n5,n6,array2 = kochSnowflakeImpl(p2,p3) n41,n52,n61,array21 = kochSnowflakeImpl(n4,n6) n42,n52,n62,array22 = kochSnowflakeImpl(n6,n5) n7,n8,n9,array3 = kochSnowflakeImpl(p1,p3) n71,n81,n91,array31 = kochSnowflakeImpl(n7,n9) n72,n82,n92,array32 = kochSnowflakeImpl(n9,n8) for i in array1: array.append(i) for i in array11: array.append(i) for i in array12: array.append(i) for j in array2: array.append(j) for j in array21: array.append(j) for j in array22: array.append(j) for k in array3: array.append(k) for k in array31: array.append(k) for k in array32: array.append(k) level -= 1 return array if __name__=='__main__': points = kochSnowflake(5) x,y = zip(*points) plt.plot(x, y) plt.show()
I decided it was time to turn the output of this code from a bad piece of string art from the '70s that didn't age well in the closet into a Koch snowflake. One problem is the OP added new points to the array in kochSnowflakeImpl() but forgot to add the original start and end points. The next problem was the n3 calculation as the two terms that summed to make each coordinate were from the same coordinate whereas one term should have been from the other coordinate. And the level logic in kochSnowflake() was hopeless. To simplify the code, I tossed the OP's vector class (which was reasonable) and substituted the more complete Vec2D class from Python turtle: from turtle import Vec2D from matplotlib import pyplot as plt SQRT_3 = 3.0 ** 0.5 def kochSnowflakeImpl(p1, p2): u = p2 - p1 v = Vec2D(-u[1], u[0]) n1 = p1 + u * (1.0 / 3.0) n2 = n1 + u * (1.0 / 6.0) + v * (SQRT_3 / 6.0) n3 = p1 + u * (2.0 / 3.0) return [p1, n1, n2, n3, p2] def kochSnowflake(level): p1 = Vec2D(0.0, 0.0) p2 = Vec2D(0.5, SQRT_3 / 2.0) p3 = Vec2D(1.0, 0.0) array = [p1, p2, p3, p1] for _ in range(level): new_array = [] for (p1, p2) in zip(array, array[1:]): new_array.extend(kochSnowflakeImpl(p1, p2)) array = new_array return array if __name__ == '__main__': points = kochSnowflake(4) x, y = zip(*points) plt.plot(x, y) plt.show() I don't think this code is quite correct as the snowflake looks a bit squat, but I believe it achieves the goal of the original code and is clean enough to build upon.
Area and perimeter of a figure made out of overlapping circles
I plan on writing this code in python, but this is more of a general algorithm-design problem than one having to do with any particular language. I'm writing code to simulate a hybrid rocket engine, and long story short, the problem involves finding both the perimeter and the area of a figure composed of many (possibly thousands) of overlapping circles. I saw this on stackexchange: Combined area of overlapping circles except I need to find the perimeter also. Someone in that thread mentioned Monte Carlo (random point guess) methods, but can that be used to find the perimeter as well as the area? Thanks in advance.
I am adding a second answer instead of expanding the first one, because I am quite positive that the other answer is correct, but I am not so sure if this answer is as correct. I have done some simple testing, and it seems to work, but please point out my errors. This is basically a quick-n-dirty implementation of what I stated before: from math import atan2, pi def intersectLine (a, b): s0, e0, s1, e1 = a [0], a [1], b [0], b [1] s = max (s0, s1) e = min (e0, e1) if e <= s: return (0, 0) return (s, e) class SectorSet: def __init__ (self, sectors): self.sectors = sectors [:] def __repr__ (self): return repr (self.sectors) def __iadd__ (self, other): acc = [] for mine in self.sectors: for others in other.sectors: acc.append (intersectLine (mine, others) ) self.sectors = [x for x in acc if x [0] != x [1] ] return self class Circle: CONTAINS = 0 CONTAINED = 1 DISJOINT = 2 INTERSECT = 3 def __init__ (self, x, y, r): self.x = float (x) self.y = float (y) self.r = float (r) def intersect (self, other): a, b, c, d, r0, r1 = self.x, self.y, other.x, other.y, self.r, other.r r0sq, r1sq = r0 ** 2, r1 ** 2 Dsq = (c - a) ** 2 + (d - b) ** 2 D = Dsq ** .5 if D >= r0 + r1: return Circle.DISJOINT, None, None if D <= abs (r0 - r1): return Circle.CONTAINED if r0 < r1 else Circle.CONTAINS, None, None dd = .25 * ( (D + r0 + r1) * (D + r0 - r1) * (D - r0 + r1) * (-D + r0 + r1) ) ** .5 x = (a + c) / 2. + (c - a) * (r0sq - r1sq) / 2. / Dsq x1 = x + 2 * (b - d) / Dsq * dd x2 = x - 2 * (b - d) / Dsq * dd y = (b + d) / 2. + (d - b) * (r0sq - r1sq) / 2. / Dsq y1 = y - 2 * (a - c) / Dsq * dd y2 = y + 2 * (a - c) / Dsq * dd return Circle.INTERSECT, (x1, y1), (x2, y2) def angle (self, point): x0, y0, x, y = self.x, self.y, point [0], point [1] a = atan2 (y - y0, x - x0) + 1.5 * pi if a >= 2 * pi: a -= 2 * pi return a / pi * 180 def sector (self, other): typ, i1, i2 = self.intersect (other) if typ == Circle.DISJOINT: return SectorSet ( [ (0, 360) ] ) if typ == Circle.CONTAINS: return SectorSet ( [ (0, 360) ] ) if typ == Circle.CONTAINED: return SectorSet ( [] ) a1 = self.angle (i1) a2 = self.angle (i2) if a1 > a2: return SectorSet ( [ (0, a2), (a1, 360) ] ) return SectorSet ( [ (a1, a2) ] ) def outline (self, others): sectors = SectorSet ( [ (0, 360) ] ) for other in others: sectors += self.sector (other) u = 2 * self.r * pi total = 0 for start, end in sectors.sectors: total += (end - start) / 360. * u return total def outline (circles): total = 0 for circle in circles: others = [other for other in circles if circle != other] total += circle.outline (others) return total a = Circle (0, 0, 2) b = Circle (-2, -1, 1) c = Circle (2, -1, 1) d = Circle (0, 2, 1) print (outline ( [a, b, c, d] ) ) Formula for calculating the intersecting points of two circles shamelessly stolen from here.
Let's say your have the circles c1, c2, ..., cn. Take c1 and intersect it with each other circle. Initialize an empty list of circle sectors for c1. If the intersection is zero points or one point and c1 is outside the other circle, then add a 360 degree sector to the list. If the intersection is zero points or one point and c1 is inside the other circle, then the effective outline of c1 is 0, stop processing c1 with an outline of 0 and take the next circle. If the intersection is two points, add the sector of c1, which is not in the other circle to the list of circle sectors of c1. The effective outline of c1, is the length of the intersection of all sectors within the list of sectors of c1. This intersection of sectors can consist of various disjoint sectors. Rinse and repeat for all circles and then sum up the resulting values.
Simplex Noise Function: Unexpected Results
I'm trying to adapt this noise module to a project I'm working on but I'm not getting the results I was expecting: https://pypi.python.org/pypi/noise/ Instead of a varied height-map, each row tends to have the exact same value. If I create something 250x250 it will generate the same value 250 times and then generate a new value 250 times until it ends. Here is the function I'm currently using. I understand this function fairly well but I'm just not sure how to get more "interesting" results. Thank you for your help. class SimplexNoise(BaseNoise): def noise2(self, x, y): """2D Perlin simplex noise. Return a floating point value from -1 to 1 for the given x, y coordinate. The same value is always returned for a given x, y pair unless the permutation table changes (see randomize above). """ # Skew input space to determine which simplex (triangle) we are in s = (x + y) * _F2 i = floor(x + s) j = floor(y + s) t = (i + j) * _G2 x0 = x - (i - t) # "Unskewed" distances from cell origin y0 = y - (j - t) if x0 > y0: i1 = 1; j1 = 0 # Lower triangle, XY order: (0,0)->(1,0)->(1,1) else: i1 = 0; j1 = 1 # Upper triangle, YX order: (0,0)->(0,1)->(1,1) x1 = x0 - i1 + _G2 # Offsets for middle corner in (x,y) unskewed coords y1 = y0 - j1 + _G2 x2 = x0 + _G2 * 2.0 - 1.0 # Offsets for last corner in (x,y) unskewed coords y2 = y0 + _G2 * 2.0 - 1.0 # Determine hashed gradient indices of the three simplex corners perm = BaseNoise.permutation ii = int(i) % BaseNoise.period jj = int(j) % BaseNoise.period gi0 = perm[ii + perm[jj]] % 12 gi1 = perm[ii + i1 + perm[jj + j1]] % 12 gi2 = perm[ii + 1 + perm[jj + 1]] % 12 # Calculate the contribution from the three corners tt = 0.5 - x0**2 - y0**2 if tt > 0: g = _GRAD3[gi0] noise = tt**4 * (g[0] * x0 + g[1] * y0) else: noise = 0.0 tt = 0.5 - x1**2 - y1**2 if tt > 0: g = _GRAD3[gi1] noise += tt**4 * (g[0] * x1 + g[1] * y1) tt = 0.5 - x2**2 - y2**2 if tt > 0: g = _GRAD3[gi2] noise += tt**4 * (g[0] * x2 + g[1] * y2) return noise * 70.0 # scale noise to [-1, 1] win = pygcurse.PygcurseWindow(85, 70, 'Generate') octaves = 2 ysize = 150 xsize = 150 freq = 32.0 * octaves for y in range(ysize): for x in range(xsize): tile = SimplexNoise.noise2(x / freq, y / freq, octaves) win.write(str(tile) + "\n")