コード例 #1
0
ファイル: wind.py プロジェクト: samcorcoran/everett
def generate_wind(nodes, cells, prevailing_wind_bearing=270, average_wind_speed=7.0):
    import noise
    import math
    import numpy as np
    for n in nodes:
        wind_bearing = (int(round(180.0 * noise.pnoise3(n.x, n.y, n.z))) + 360) % 360  # in degrees
        wind_strength = (8 * noise.pnoise3(n.x, n.y, n.z)) + 16.0  # kmph

        # move the generated random wind bearing towards the prevailing wind a little
        wind_vector = np.add(np.array([wind_strength * math.cos(math.radians(90 - wind_bearing)),
                                       wind_strength * math.cos(math.radians(wind_bearing))]),
                             np.array([average_wind_speed * math.cos(math.radians(90 - prevailing_wind_bearing)),
                                       average_wind_speed * math.cos(math.radians(prevailing_wind_bearing))]))

        wind_strength = math.sqrt(math.pow(wind_vector[0], 2) + math.pow(wind_vector[1], 2)) #  sqrt((x2-x1)^2 + (y2-y1)^2) = vector magnitude
        wind_bearing = int(round(math.degrees(math.atan(wind_vector[1]/wind_vector[0])))) # tan-1((y2-y1)/x2-x1)) = vector bearing

        n.set_feature(['wind', 'bearing'], wind_bearing)
        n.set_feature(['wind', 'strength'], wind_strength)
        n.set_feature(['wind', 'vector', 'x'], wind_vector[0])
        n.set_feature(['wind', 'vector', 'y'], wind_vector[1])
        n.wind = Wind(wind_bearing, wind_strength, wind_vector)
    for c in cells:
        wind_vector = np.sum(np.array([n.wind.vector for n in c.nodes]), axis=0)
        wind_strength = math.sqrt(math.pow(wind_vector[0], 2) + math.pow(wind_vector[1], 2))  #  sqrt((x2-x1)^2 + (y2-y1)^2) = vector magnitude
        wind_bearing = int(round(math.degrees(math.atan(wind_vector[1]/wind_vector[0]))))  # tan-1((y2-y1)/x2-x1)) = vector bearing

        c.wind = Wind(wind_bearing, wind_strength, wind_vector)
コード例 #2
0
	def __init__(self, freq=8, width=32):
		"""Generate the 3D noise texture.

		freq -- frequency of generated noise over the width of the 
		texture.

		width -- Width of the texture in texels. The texture is cubic,
		thus all sides are the same width. Must be a power of two.
		Using a larger width can reduce artifacts caused by linear
		interpolation of the noise texture, at the cost of video
		memory, and possibly slower texture access.
		"""
		self.freq = freq
		self.width = width
		scale = float(freq) / width
		width2 = width**2
		texel = (ctypes.c_ushort * (2 * width**3))()
		for z in range(width):
			for y in range(width):
				for x in range(width):
					texel[(x + (y * width) + (z * width2)) * 2] = int((pnoise3(
						x * scale, y * scale, z * scale, 
						repeatx=freq, repeaty=freq, repeatz=freq) + 1.0) * 32767)
					texel[(x + (y * width) + (z * width2)) * 2 + 1] = int((pnoise3(
						x * scale, y * scale, z * scale, 
						repeatx=freq, repeaty=freq, repeatz=freq, base=freq + 1) + 1.0) * 32767)
		self.data = texel
コード例 #3
0
ファイル: sample.py プロジェクト: dribnet/discgen
def anchors_noise_offsets(anchors, offsets, rows, cols, spacing, z_step, x_indices_str, y_indices_str, x_minscale, y_minscale, x_maxscale, y_maxscale):
    from noise import pnoise3
    from plat.interpolate import lerp

    only_anchor = None
    if len(anchors) == 1:
        only_anchor = anchors[0]

    dim = len(anchors[0])
    x_offset = offset_from_string(x_indices_str, offsets, dim)
    y_offset = offset_from_string(y_indices_str, offsets, dim)

    num_row_anchors = (rows + spacing - 1) / spacing
    num_col_anchors = (cols + spacing - 1) / spacing

    newanchors = []
    cur_anchor_index = 0
    for j in range(num_row_anchors):
        y_frac = float(j) / num_row_anchors
        for i in range(num_col_anchors):
            if only_anchor is None:
                cur_anchor = anchors[cur_anchor_index]
                cur_anchor_index += 1
            else:
                cur_anchor = only_anchor
            x_frac = float(i) / num_col_anchors
            n1 = 0.5 * (1.0 + pnoise3(x_frac, y_frac, z_step, octaves=4, repeatz=2))
            n2 = 0.5 * (1.0 + pnoise3(100+x_frac, 100+y_frac, z_step, octaves=4, repeatz=2))
            x_scale = lerp(n1, x_minscale, x_maxscale)
            y_scale = lerp(n2, y_minscale, y_maxscale)
            # print("{}, {} produced {} -> {}, {} = {}".format(i,j,n1,x_minscale, x_maxscale,x_scale))
            newanchors.append(cur_anchor + x_scale * x_offset + y_scale * y_offset)
    return np.array(newanchors)
コード例 #4
0
ファイル: main.py プロジェクト: robertpfeiffer/gnome-fortress
def make_terrain():
    terrain=[[1-int(abs(noise.pnoise3(i*0.4+0.5,j*0.1+0.5,0.5))*2)
              for i in range(500)] 
             for j in range(5000)]

    for x in range(5000):
        for y in range(50):
            terrain[x][y]=3
        terrain[x][50]=2

    for x in range(100):
        for y in range(500):
            terrain[-x][y]=4
            terrain[x][y]=4

    for x in range(5000):
        for y in range(50,100):
            ri=random.random()
            if terrain[x][y]==0 and terrain[x][y+1]==1:
                if ri<0.05:
                    terrain[x][y]=9
            if terrain[x][y]==0 and terrain[x][y+1]==1:
                if ri<0.2:
                    terrain[x][y]=6
            if terrain[x][y]==1:
                if ri<0.007:
                    terrain[x][y]=8
        for y in range(110,200):
            ri=random.random()
            if terrain[x][y]==1:
                if ri<0.002:
                    terrain[x][y]=10
    return terrain
コード例 #5
0
ファイル: animate_tex.py プロジェクト: greyarea/noise
def create_3d_texture(width, scale):
	"""Create a grayscale 3d texture map with the specified 
	pixel width on each side and load it into the current texture
	unit. The luminace of each texel is derived using the input 
	function as:

	v = func(x * scale, y * scale, z * scale)

	where x, y, z = 0 in the center texel of the texture.
	func(x, y, z) is assumed to always return a value in the 
	range [-1, 1].
	"""
	coords = range(width)
	texel = (ctypes.c_byte * width**3)()
	half = 0 #width * scale / 2.0 

	for z in coords:
		for y in coords:
			for x in coords:
				v = pnoise3(x * scale - half, y * scale - half, z * scale - half, 4)
				texel[x + (y * width) + (z * width**2)] = int(v * 127.0)
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
	glTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE, width, width, width, 0, 
		GL_LUMINANCE, GL_BYTE, ctypes.byref(texel))
	return texel
コード例 #6
0
ファイル: meshtoy.py プロジェクト: StephenLujan/meshtoy
def main2():
    logging.info("(this might take a while...)")
    samples = 50
    t = time.time()
    # from stl import mesh
    diameter = 10
    radius = diameter / 2
    half = radius / 2

    # X, Y, Z = np.mgrid[:diameter, :diameter, :diameter]
    # print "X"
    # print X
    # print "Y"
    # print Y
    # print "Z"
    # print Z
    # u = (X-50)**2 + (Y-50)**2 + (Z-50)**2 - 25**2 + pnoise3(X,Y,Z,octaves=3)*3
    # u = (X-radius)**2 + (Y-radius)**2 + (Z-radius)**2 - half**2 #+ pnoise3(X,Y,Z,octaves=3)*3
    # u = [[[(X)**2 + (Y)**2 + (Z)**2 - 25**2 + pnoise3(X,Y,Z,octaves=3)*3 for X in range(-100,100)] for Y in range(-100,100)] for Z in range(-100,100)]
    u = np.ndarray((200, 200, 200))
    for X in range(-100, 100):
        for Y in range(-100, 100):
            for Z in range(-100, 100):
                # print v
                u[X + 100, Y + 100, Z + 100] = ((X) ** 2 + (Y) ** 2 + (Z) ** 2) + pnoise3(X * 0.05, Y * 0.05, Z * 0.05,
                                                                                          octaves=3) * 30
    # print u
    # Extract the 0-isosurface

    logging.debug("u")
    logging.debug(u)
    vertices, triangles = mcubes.marching_cubes(u, 60)
    logging.info("mesh completed in %f seconds" % (time.time() - t))

    meshexport.export(vertices, triangles)
コード例 #7
0
ファイル: effects.py プロジェクト: ksmetana/mens-amplio
    def render(self, model, params, frame):
        # Noise spatial scale, in number of noise datapoints at the fundamental frequency
        # visible along the length of the sculpture. Larger numbers "zoom out".
        # For perlin noise, we have multiple octaves of detail, so staying zoomed in lets
        # us have a lot of detail from the higher octaves while still having gradual overall
        # changes from the lower-frequency noise.

        s = self.zoom # defaults to 0.6

        # Time-varying vertical offset. "Flow" upwards, slowly. To keep the parameters to
        # pnoise3() in a reasonable range where conversion to single-precision float within
        # the module won't be a problem, we need to wrap the coordinates at the point where
        # the noise function seamlessly tiles. By default, this is at 1024 units in the
        # coordinate space used by pnoise3().

        z0 = math.fmod(params.time * self.time_const, 1024.0)

        for i, rgb in enumerate(frame):
            # Normalized XYZ in the range [0,1]
            x, y, z = model.edgeCenters[i]

            # Perlin noise with some brightness scaling
            level = 1.2 * (0.35 + noise.pnoise3(x*s, y*s, z*s + z0, octaves=3))

            for w,v in enumerate(self.color):
                rgb[w] += v * level
コード例 #8
0
def create_noise(width=240, scale=1.0/48):
	coords = range(width)
	v = np.zeros((width, width, width))
	for z in coords:
		for y in coords:
			for x in coords:
				v[x][y][z] = (pnoise3(x * scale, y * scale , z * scale, octaves=8, persistence=.25) + 1.0)/2.0
	return v
コード例 #9
0
ファイル: test.py プロジェクト: Connor124/Gran-Theft-Crop-Toe
 def test_perlin_3d_range(self):
     from noise import pnoise3
     for i in range(-10000, 10000):
         x = -i * 0.49
         y = i * 0.67
         z = -i * 0.727
         n = pnoise3(x, y, z)
         self.assertTrue(-1.0 <= n <= 1.0, (x, y, z, n))
コード例 #10
0
ファイル: test.py プロジェクト: Connor124/Gran-Theft-Crop-Toe
 def test_perlin_3d_octaves_range(self):
     from noise import pnoise3
     for i in range(-1000, 1000):
         x = i * 0.22
         y = -i * 0.77
         z = -i * 0.17
         for o in range(10):
             n = pnoise3(x, y, z, octaves=o + 1)
             self.assertTrue(-1.0 <= n <= 1.0, (x, y, z, n))
	def create_noise(self):
		matrix_size = self.matrix_size
		scale = self.noise_scale
		coords = range(matrix_size)

		v = np.zeros((matrix_size, matrix_size, matrix_size))
		for z in coords:
			for y in coords:
				for x in coords:
					v[x][y][z] = (pnoise3(x * scale, y * scale , z * scale, octaves=8, persistence=.25) + 1.0)/2.0
		return v
コード例 #12
0
    def step(self, amt):
        octaves = 1
        freq = 16.0
        data = []
        for y in range(self.height):
            for x in range(self.width):
                v = int(pnoise3(x / self._freq, y / self._freq, self._step / self._freq, octaves=self._octaves) * 127.0 + 128.0)
                c = colors.hue2rgb_rainbow(v)
                self._led.set(x,y, c)

        self._step += amt
コード例 #13
0
ファイル: noisey.py プロジェクト: ColtonPhillips/blair-isle
def generatePerlinNoise(width,height,octaves=16,persistance=0.7,lacunarity=3.0,repeatx=10024,repeaty=10024,base=0):
	base = random.randint(0,1024)
	print (base)
	big_number = float(max(width,height) + 2)
	from noise import pnoise3
	my_noise = [[r for r in range(width)] for i in range(height)]
	_r = random.random()
	for i in range(0,height):
		for j in range(0,width):
			#my_noise[i][j] = (1.0 + pnoise3(float(i)/big_number, float(j)/big_number, _r, octaves,persistance,lacunarity,repeatx,repeaty,base)) / 2.0
			my_noise[i][j] = (1.0 + pnoise3(float(i)/big_number, float(j)/big_number, _r,octaves,persistance, lacunarity,repeatx,repeaty,base)) / 2.0
	return my_noise		
コード例 #14
0
ファイル: meshtoy-GTS.py プロジェクト: StephenLujan/meshtoy
    def octant(x_offset, y_offset, z_offset):
        array = np.ndarray((samples, samples, samples))
        for x in range(samples):
            for y in range(samples):
                for z in range(samples):
                    x2, y2, z2 = x + x_offset, y + y_offset, z + z_offset
                    noise = AMPLITUDE * pnoise3(x2 * FREQUENCY, y2 * FREQUENCY, z2 * FREQUENCY, octaves=2)
                    array[x, y, z] = x2 ** 2 + y2 ** 2 +  z2 ** 2 - half ** 2 + noise

        logging.debug("array")
        logging.debug(array)
        # Extract the 0-isosurface
        return mcubes.marching_cubes(array, 0)
    def create_noise(self):
        """If a noise file was not found, this will create a noise file using pnoise3"""

        matrix_size = self.matrix_size
        scale = self.noise_scale
        coords = range(matrix_size)

        v = np.zeros((matrix_size, matrix_size, matrix_size))
        for z in coords:
            for y in coords:
                for x in coords:
                    v[x][y][z] = (pnoise3(x * scale, y * scale , z * scale, octaves=8, persistence=.25) + 1.0)/2.0
        return v
コード例 #16
0
ファイル: planet.py プロジェクト: tps12/Dorftris
    def sample(self, latitude, longitude):
        lat, lon = [v*pi/180 for v in latitude, longitude]
        c = cos(lat)
        x, y, z = c * cos(lon), c * sin(lon), sin(lat)

        octaves = 12
        persist = 0.7

        b = 1 if pnoise3(x+self.seeds[0],
                         y+self.seeds[1],
                         z+self.seeds[2], 4, persist) > -0.125 else -1
        value = pnoise3(x+self.seeds[3],
                        y+self.seeds[4],
                        z+self.seeds[5], octaves, persist)
        if value > 0.25:
            value *= 1.25 * b
        elif value > 0:
            value *= b
        else:
            value *= 3

        scale = 7000
        return scale * value
コード例 #17
0
ファイル: terrain.py プロジェクト: samcorcoran/everett
def generate_uniform_altitudes(nodes, max_height=1000.0, min_height=-1000.0, target_wateriness=0.5):
    import noise
    noise_offset = (1.0 - 2.0*target_wateriness)
    noise_max = 1.0 + noise_offset
    noise_min = -1.0 + noise_offset
    half_range = (max_height - min_height) / 2.0
    for n in nodes:
        noise_point = noise.pnoise3(n.x, n.y, n.z, octaves=2) + noise_offset
        # noise_point = noise.pnoise2(n.longitude, n.latitude, repeatx=360.0, repeaty=180.0, octaves=2) + noise_offset
        # noise_point = noise.snoise3(n.x, n.y, n.z) + noise_offset
        try:
            if noise_point < 0:
                n.altitude = (min_height * noise_point) / noise_min
            elif noise_point > 0:
                n.altitude = (max_height * noise_point) / noise_max
            else:
                n.altitude = 0.0
        except ZeroDivisionError:
            n.altitude = 0.0
コード例 #18
0
ファイル: meshtoy-GTS.py プロジェクト: StephenLujan/meshtoy
def main2():
    logging.info("(this might take a while...)")
    samples = 50
    t = time.time()
    #from stl import mesh
    diameter = 10
    radius = diameter / 2
    half= radius / 2
    
    u = np.ndarray((200,200,200))
    for X in range(-100,100):
        for Y in range(-100,100):
            for Z in range(-100,100):
                u[X+100,Y+100,Z+100] = ((X)**2 + (Y)**2 + (Z)**2) + pnoise3(X*0.05,Y*0.05,Z*0.05,octaves=3)*30
    
    logging.debug("u")
    logging.debug(u)
    vertices, triangles = gts.marching_cubes(u, 60)
    logging.info("mesh completed in %f seconds" % (time.time() - t))

    meshexport.export(vertices, triangles)
コード例 #19
0
ファイル: meshtoy.py プロジェクト: StephenLujan/meshtoy
def octant_array(samples, isosurface, x_offset, y_offset, z_offset, spherefactor=1):
    """

    :param samples: the number of samples per dimension per octant,
     the full model would have samples**3 * 8 samples
    :param isosurface:
    :param x_offset: controls which octant
    :param y_offset:
    :param z_offset:
    :param spherefactor: power to apply to the spherical component. use 0.5 for a linear sphere.
    :return: a numpy.ndarray
    """
    array = np.ndarray((samples, samples, samples))
    isosurface **= 2
    for x in range(samples):
        for y in range(samples):
            for z in range(samples):
                x2, y2, z2 = x + x_offset, y + y_offset, z + z_offset
                noise = AMPLITUDE * pnoise3(x2 * FREQUENCY, y2 * FREQUENCY, z2 * FREQUENCY, octaves=2)
                array[x, y, z] = isosurface - pow(x2 ** 2 + y2 ** 2 + z2 ** 2,spherefactor) - noise
    return array
コード例 #20
0
ファイル: meshtoy.py プロジェクト: StephenLujan/meshtoy
def main3():
    logging.info("(this might take a while...)")
    t = time.time()
    # from stl import mesh
    samples = 50
    radius = samples / 2.0
    half = radius / 2.0

    array = np.ndarray((samples, samples, samples))
    for x in range(samples):
        for y in range(samples):
            for z in range(samples):
                noise = AMPLITUDE * pnoise3(x * FREQUENCY, y * FREQUENCY, z * FREQUENCY, octaves=2)
                array[x, y, z] = x ** 2 + y ** 2 + z ** 2 - half ** 2 + noise

    logging.debug("array")
    logging.debug(array)
    # Extract the 0-isosurface
    vertices, triangles = mcubes.marching_cubes(array, 0)
    logging.info("mesh completed in %f seconds" % (time.time() - t))

    meshexport.export(vertices, triangles)
コード例 #21
0
ファイル: perlin.py プロジェクト: Dayleryn/rgb_table
def draw_dots():
    global z,z2,mmin,mmax
    clear_grid()

    for x in range(WIDTH):
        for y in range(HEIGHT):
            c = noise.pnoise3(x * scale, y * scale, z * scale, octave, repeatx=WIDTH, repeaty=HEIGHT)

            if c > mmax: mmax = c
            if c < mmin: mmin = c
        
            c = c + math.fabs(mmin)
            c = c / (mmax + math.fabs(mmin))
            if mode == 1:
                c = (c + 0.2) % 1
                grid[x][y] = [c,1,1]
            elif mode == 2:
                c = (c + z2) % 1
                grid[x][y] = [c,1,1]
            else:
                grid[x][y] = [z2%1,1,c]

    z += .1
    z2 += .005
コード例 #22
0
ファイル: test.py プロジェクト: Connor124/Gran-Theft-Crop-Toe
 def test_perlin_3d_base(self):
     from noise import pnoise3
     x, y, z = 0.1, 0.7, 0.33
     self.assertEqual(pnoise3(x, y, z), pnoise3(x, y, z, base=0))
     self.assertNotEqual(pnoise3(x, y, z), pnoise3(x, y, z, base=5))
     self.assertNotEqual(pnoise3(x, y, z, base=5), pnoise3(x, y, z, base=1))
コード例 #23
0
ファイル: main.py プロジェクト: robertpfeiffer/gnome-fortress
def make_shadow_terrain():
    terrain=[[1-int(abs(noise.pnoise3(i*0.6+0.5,j*0.2+0.5,0.8))*5)
              for i in range(500)] 
             for j in range(5000)]

    return terrain
コード例 #24
0
ファイル: noise_test.py プロジェクト: highway900/random_maps
HEIGHT = 256


def clamp(x, a, b):
    return min(max(float(x), float(a)), float(b))

def scaleVal(val, inlow, inhigh, outlow, outhigh):
    return ((val - float(inlow)) / (float(inhigh) - float(inlow))) * (float(outhigh) - float(outlow)) + float(outlow)
   
img = []
for y in range(HEIGHT):
    t = tuple()
    for x in range(WIDTH):
        nx = scaleVal(x, 0, WIDTH, -1.0, 1.0)
        ny = scaleVal(y, 0, HEIGHT, -1.0, 1.0)
        val = noise.pnoise3(nx, ny, 1, octaves=int(sys.argv[1]), persistence=int(sys.argv[2]), lacunarity=float(sys.argv[3]), repeatx=256, repeaty=256, base=int(sys.argv[4]))
        
        nval = int(scaleVal(val, -1.0, 1.0, 0, 255))
        
        #nval = clamp(nval, 155, 255)
       
        if nval < 140:
            nval = 10
        else:
            nval = 255

        t += (nval, nval, nval,)
    img.append(t)

if img:
    with open('random_map_pnoise.png', 'wb') as f:
コード例 #25
0
ファイル: mapgen.py プロジェクト: Skelpdar/PyrateMapGenerator
from PIL import Image
import math
import noise

width, height = (640, 480)
seed = 3600
centerx, centery = (256, 256)
heightmultiplier = 2

data = []

for x in range(0, width):
    a = []
    for y in range(0, height):
        # Perlin noise data
        value = noise.pnoise3(x / width, y / height, seed, persistence=0.4, lacunarity=3, octaves=32) * heightmultiplier

        # Gradient mask
        mask = math.sqrt((centerx - x) ** 2 + (centery - y) ** 2) / width
        a.append(value - mask)

    data.append(a)

im = Image.new("RGB", (width, height))

for idx, x in enumerate(data):
    for idy, y in enumerate(x):
        # Elevation colors
        if y < 0.02:
            im.putpixel((idx, idy), (0, 0, 255))
        elif y < 0.05: