def main():
    simplex = OpenSimplex()

    print("Generating 2D image...")
    im = Image.new("L", (WIDTH, HEIGHT))
    for y in range(0, HEIGHT):
        for x in range(0, WIDTH):
            value = simplex.noise2d(x / FEATURE_SIZE, y / FEATURE_SIZE)
            color = int((value + 1) * 128)
            im.putpixel((x, y), color)
    im.save("noise2d.png")

    print("Generating 2D slice of 3D...")
    im = Image.new("L", (WIDTH, HEIGHT))
    for y in range(0, HEIGHT):
        for x in range(0, WIDTH):
            value = simplex.noise3d(x / FEATURE_SIZE, y / FEATURE_SIZE, 0.0)
            color = int((value + 1) * 128)
            im.putpixel((x, y), color)
    im.save("noise3d.png")

    print("Generating 2D slice of 4D...")
    im = Image.new("L", (WIDTH, HEIGHT))
    for y in range(0, HEIGHT):
        for x in range(0, WIDTH):
            value = simplex.noise4d(x / FEATURE_SIZE, y / FEATURE_SIZE, 0.0, 0.0)
            color = int((value + 1) * 128)
            im.putpixel((x, y), color)
    im.save("noise4d.png")
class Benchmark:
    def __init__(self):
        self.simplex = OpenSimplex(seed=0)

    def run(self, number=100000):
        for i in _range(number):
            self.simplex.noise2d(0.1, 0.1)
            self.simplex.noise3d(0.1, 0.1, 0.1)
            self.simplex.noise4d(0.1, 0.1, 0.1, 0.1)
Exemple #3
0
class Game(object):
    def __init__(self):
        self.gen = OpenSimplex(random.randint(0, sys.maxint))

    def noise(self, nx, ny):
        return self.gen.noise2d(nx, ny) / 2.0 + 0.5

    def create_height_map(self, width, height):
        fwidth = float(width)
        fheight = float(height)
        result = array.array('B')
        for y in xrange(height):
            for x in xrange(width):
                nx = x / fwidth - 0.5
                ny = y / fheight - 0.5
                value = self.noise(10 * nx, 10 * ny)
                result.append(int(255 * value if value != 1.0 else 255))
        return result
Exemple #4
0
                    append_face(f"usemtl {block}\nf {i1} {i2} {i7} {i4}")
                    append_face(f"f {i1} {i2} {i5} {i3}")
                    append_face(f"f {i4} {i7} {i8} {i6}")
                    append_face(f"f {i1} {i4} {i6} {i3}")
                    append_face(f"f {i2} {i5} {i8} {i7}")
                    append_face(f"f {i3} {i5} {i8} {i6}")
                    num_blocks+=1

    file.write("\n".join([f"v {p[0]} {p[1]} {p[2]}" for p in points.values()]) + "\n" + "\n".join(faces.values()) + "\n")
    print(num_blocks)

with open("test.obj", "w+") as f:
    seed = 1281134870109837483
    randomness = Random(seed)
    noise = OpenSimplex(seed=seed)
    chunks = {}

    radius = 1 if len(sys.argv) < 2 else int(sys.argv[1])

    print(f"Generating {(radius*2)**2} chunks...")
    start = pf()

    for x in range(-radius, radius):
        for z in range(-radius, radius):
            chunks[x, z] = noisy_chunk(noise, randomness, x, z)

    print(f"Done generating chunks. ({(pf() - start):02.02f} seconds for {len(chunks)} chunks)")

    # print("Adding ore pockets...")
    # start = pf()
Exemple #5
0
def main():
    global SEALEVEL
    global FEATURE_SIZE
    global WATER_LEVEL
    global SIZE
    global pathx
    global pathz
    MIN = 500
    MAX = 0
    CNT = 0
    TOT = 0
    pathx = []
    pathz = []

    if (len(sys.argv) > 1):
        if (sys.argv[1]):
            SIZE = int(sys.argv[1])
        else:
            SIZE = 1000
        if (sys.argv[2]):
            SEED = int(sys.argv[2])
        else:
            SEED = 0
        if (sys.argv[3]):
            WATER_LEVEL = float(sys.argv[3])
        else:
            WATER_LEVEL = 15.0
        if (sys.argv[4]):
            FEATURE_SIZE = float(sys.argv[4])
        else:
            FEATURE_SIZE = 24.0
    else:
        SIZE = 1000
        SEED = 0
        WATER_LEVEL = 15.0
        FEATURE_SIZE = 24.0
    print("Generating world of size " + str(SIZE) + " by " + str(SIZE) + "...")
    print("Seed " + str(SEED) + " Water Percentage " + str(WATER_LEVEL) +
          " Land Feature Variant " + str(FEATURE_SIZE) + ".")
    global MAXX
    MAXX = SIZE
    global MAXZ
    MAXZ = SIZE
    global Y
    Y = [[0 for x in range(MAXX)] for z in range(MAXZ)]
    global MOVE_NW
    MOVE_NW = [[0 for x in range(MAXX)] for z in range(MAXZ)]
    global MOVE_N
    MOVE_N = [[0 for x in range(MAXX)] for z in range(MAXZ)]
    global MOVE_NE
    MOVE_NE = [[0 for x in range(MAXX)] for z in range(MAXZ)]
    global MOVE_E
    MOVE_E = [[0 for x in range(MAXX)] for z in range(MAXZ)]
    global MOVE_SE
    MOVE_SE = [[0 for x in range(MAXX)] for z in range(MAXZ)]
    global MOVE_S
    MOVE_S = [[0 for x in range(MAXX)] for z in range(MAXZ)]
    global MOVE_SW
    MOVE_SW = [[0 for x in range(MAXX)] for z in range(MAXZ)]
    global MOVE_W
    MOVE_W = [[0 for x in range(MAXX)] for z in range(MAXZ)]
    global SEEDS
    SEEDS = [[random.randint(0, SIZE) for x in range(MAXX)]
             for z in range(MAXZ)]

    simplex = OpenSimplex(seed=SEED)
    for z in range(0, MAXX):
        for x in range(0, MAXZ):
            value = simplex.noise3d(x / FEATURE_SIZE, z / FEATURE_SIZE, 0.0)
            y = int((value + 1) * 128)
            if (y > MAX):
                MAX = y
            if (y < MIN):
                MIN = y
            Y[x][z] = y

    SEALEVEL = int((MAX - MIN) * (WATER_LEVEL / 100)) + MIN
    print("Make water level " + str(SEALEVEL) + " or below..")
    # waterify W by displaying everything below SEALEVEL+1 as ~

    # calculate movement costs in all direction for W but only above SEALEVEL
    for Z in range(MAXZ):
        for X in range(MAXX):
            if (Y[X][Z] > SEALEVEL):
                # process movement
                # MOVE_NW[X][Z] = calmove(X,Z,1)
                # MOVE_N[X][Z]  = calmove(X,Z,2)
                # MOVE_NE[X][Z] = calmove(X,Z,3)
                # MOVE_E[X][Z]  = calmove(X,,Z,4)
                # MOVE_SE[X][Z] = calmove(X,Z,5)
                # MOVE_S[X][Z]  = calmove(X,Z,6)
                # MOVE_SW[X][Z] = calmove(X,Z,7)
                # MOVE_W[X][Z]  = calmove(X,Z,8)
                # special cases, corners and X=MAXX, Z=MAXZ
                if (X == 0):
                    # process N, NE, E, SE, S
                    if (Z == 0):
                        # process E, SE, S
                        MOVE_NW[X][Z] = MOVE_N[X][Z] = MOVE_NE[X][Z] = MOVE_W[
                            X][Z] = MOVE_SW[X][Z] = False
                        MOVE_E[X][Z] = calmove(X, Z, 4)
                        MOVE_SE[X][Z] = calmove(X, Z, 5)
                        MOVE_S[X][Z] = calmove(X, Z, 6)
                        continue
                    if (Z == MAXZ):
                        # BOTTOM LEFT CORNER, no   process S, SW, W
                        MOVE_W[X][Z] = MOVE_NW[X][Z] = MOVE_SE[X][Z] = MOVE_S[
                            X][Z] = MOVE_SW[X][Z] = False
                        MOVE_NE[X][Z] = calmove(X, Z, 3)
                        MOVE_N[X][Z] = calmove(X, Z, 2)
                        MOVE_E[X][Z] = calmove(X, Z, 4)
                        continue
                    # X is 0 moving down left edge of world, no NW, SW, W
                    MOVE_NW[X][Z] = False
                    MOVE_N[X][Z] = calmove(X, Z, 2)
                    MOVE_NE[X][Z] = calmove(X, Z, 3)
                    MOVE_E[X][Z] = calmove(X, Z, 4)
                    MOVE_SE[X][Z] = calmove(X, Z, 5)
                    MOVE_S[X][Z] = calmove(X, Z, 6)
                    MOVE_SW[X][Z] = MOVE_W[X][Z] = False
                if (X == MAXX):
                    if (Z == 0):
                        # TOP RIGHT CORNER, no NW, N, NE, E, SE
                        MOVE_NW[X][Z] = MOVE_N[X][Z] = MOVE_NE[X][Z] = MOVE_E[
                            X][Z] = MOVE_SE[X][Z] = False
                        MOVE_S[X][Z] = calmove(X, Z, 6)
                        MOVE_SW[X][Z] = calmove(X, Z, 7)
                        MOVE_W[X][Z] = calmove(X, Z, 8)
                        continue
                    if (Z == MAXZ):
                        # BOTTOM RIGHT CORNER, no NE, E, SE, S, SW
                        MOVE_NW[X][Z] = calmove(X, Z, 1)
                        MOVE_N[X][Z] = calmove(X, Z, 2)
                        MOVE_NE[X][Z] = MOVE_E[X][Z] = MOVE_SE[X][Z] = MOVE_S[
                            X][Z] = MOVE_SW[X][Z] = False
                        MOVE_W[X][Z] = calmove(X, Z, 8)
                        continue
                    # X is MAXX moving down right edge of world, no NE, E, SE
                    MOVE_NW[X][Z] = calmove(X, Z, 1)
                    MOVE_N[X][Z] = calmove(X, Z, 2)
                    MOVE_NE[X][Z] = MOVE_E[X][Z] = MOVE_SE[X][Z] = False
                    MOVE_S[X][Z] = calmove(X, Z, 6)
                    MOVE_SW[X][Z] = calmove(X, Z, 7)
                    MOVE_W[X][Z] = calmove(X, Z, 8)
                    continue
                if (Z == 0):
                    # moving across the top, no NW, N, NE
                    MOVE_NW[X][Z] = MOVE_N[X][Z] = MOVE_NE[X][Z] = False
                    MOVE_E[X][Z] = calmove(X, Z, 4)
                    MOVE_SE[X][Z] = calmove(X, Z, 5)
                    MOVE_S[X][Z] = calmove(X, Z, 6)
                    MOVE_SW[X][Z] = calmove(X, Z, 7)
                    MOVE_W[X][Z] = calmove(X, Z, 8)
                    continue
                if (Z == MAXZ):
                    # moving across the bottom, no SE, S, SW
                    MOVE_NW[X][Z] = calmove(X, Z, 1)
                    MOVE_N[X][Z] = calmove(X, Z, 2)
                    MOVE_NE[X][Z] = calmove(X, Z, 3)
                    MOVE_E[X][Z] = calmove(X, Z, 4)
                    MOVE_SE[X][Z] = MOVE_S[X][Z] = MOVE_SW[X][Z] = False
                    MOVE_W[X][Z] = calmove(X, Z, 8)
                    continue
                # Special cases done, not near an edge
                MOVE_NW[X][Z] = calmove(X, Z, 1)
                MOVE_N[X][Z] = calmove(X, Z, 2)
                MOVE_NE[X][Z] = calmove(X, Z, 3)
                MOVE_E[X][Z] = calmove(X, Z, 4)
                MOVE_SE[X][Z] = calmove(X, Z, 5)
                MOVE_S[X][Z] = calmove(X, Z, 6)
                MOVE_SW[X][Z] = calmove(X, Z, 7)
                MOVE_W[X][Z] = calmove(X, Z, 8)

    addrivers(SEED)

    print('Generated. Normalizing...')
    # normalize W
    for Z in range(MAXZ):
        for X in range(MAXX):
            Y[X][Z] = normalize_around(X, Z)
            V = Y[X][Z]
            if (MIN > V):
                MIN = V
            if (MAX < V):
                MAX = V
            CNT = CNT + 1
            TOT = TOT + V
    AVG = TOT / CNT
    print("Normalize results: MAX " + str(MAX) + " MIN " + str(MIN) + " CNT " +
          str(CNT) + " AVG " + str(AVG))

    display_cell(84, 73, SEALEVEL)

    print("Creating map representations:")
    print("PGM world.pgm [", end='')
    createfilepgm("data/world.pgm", MAX)
    print("DONE]")
    print("PPM world.ppm [", end='')
    createfileppm("data/world.ppm")
    print("DONE]")
    print("TEXT world.txt [", end='')
    createfiletext("data/world.txt")
    print("DONE]")
    print("Saving generated world to files.")
    write_Y()
    write_D()
    write_M()
 def __init__(self):
     self.simplex = OpenSimplex(seed=0)
Exemple #7
0
bot = bot + interp_lights((0, 8.5, 31.75), (0, 27.5, 51.75), 38)

# Right top
rt = [(8-x, y, z) for x, y, z in lt]

lightmap = lt+bot+rt
min_x = min(x for x,y,z in lightmap)
min_y = min(y for x,y,z in lightmap)
min_z = min(z for x,y,z in lightmap)
lightmap = [(x-min_x, y-min_y, z-min_z) for x,y,z in lightmap] # re-origin on extreme
max_x = max(x for x,y,z in lightmap)
max_y = max(y for x,y,z in lightmap)
max_z = max(z for x,y,z in lightmap)


simplex_a = OpenSimplex(seed=0)
simplex_b = OpenSimplex(seed=1)
simplex_c = OpenSimplex(seed=2)
simplex_scale_x = 0.02
simplex_scale_y = 0.02
simplex_scale_z = 0.02
def simplex_hsl_as_rgb(x, y, z, w):
    x = x * simplex_scale_x
    y = y * simplex_scale_y
    z = z * simplex_scale_z
    h = (simplex_a.noise4d(x, y, z, w)+1)*360
    s = 100-(simplex_b.noise4d(x, y, z, w)+1)*5
    l = 50+(simplex_c.noise4d(x, y, z, w))*5
    r, g, b = hsluv.hsluv_to_rgb([h, s, l])
    return (r*256, g*256, b*256)
def run(args):
    img = cv2.imread(args.img)
    img = cv2.resize(img, (800, 600), cv2.INTER_AREA)
    ## create a flow field
    H, W = img.shape[:2]

    x_noise = OpenSimplex(240)
    y_noise = OpenSimplex(32)
    field = np.zeros((H, W, 2))
    for y in range(H):
        for x in range(W):
            mult = 0.0015
            x_val = x_noise.noise2d(x=mult * x, y=mult * y)
            y_val = y_noise.noise2d(x=mult * x, y=mult * y)
            field[y, x, :] = (x_val, y_val)

    # draw_field(field, N_particles=2000)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).astype(np.float64) / 256
    sigma = 3
    gray = cv2.GaussianBlur(gray, ksize=(0, 0), sigmaX=sigma)
    # cv2.imshow("cv: gray", gray)
    # c = cv2.waitKey(0)
    # if c == ord('q'):
    #     import sys
    #     sys.exit(1)
    points = draw_field(field, guide=1 - gray, N_particles=10000)

    # ## draw the image with the flow field

    # cv2.namedWindow('cv: img', cv2.WINDOW_NORMAL)
    # cv2.imshow("cv: img", img)
    # # cv2.imshow("cv: field", np.linalg.norm(field, axis=2))
    # cv2.imshow("cv: field", field[..., 0])
    # cv2.resizeWindow('cv: img', 800, 600)
    # c = cv2.waitKey(0)
    # if c == ord('q'):
    #     import sys
    #     sys.exit(1)

    x_margin_mm = 10
    y_margin_mm = 10
    H = 210  # A4
    W = 297  # A4

    to_draw = resize_and_center(points, H, W, x_margin_mm, x_margin_mm,
                                y_margin_mm, y_margin_mm)
    vis_drawing(to_draw, 'r-', linewidth=0.5)
    to_draw = optimize(to_draw, line_simplification_threshold=0.1)
    vis_drawing(to_draw, 'k-', linewidth=0.5)
    plt.plot([0, W, W, 0, 0], [0, 0, H, H, 0], 'k:')
    plt.axis('equal')
    plt.gca().invert_yaxis()
    plt.show()

    H = 210  # A4
    W = 297  # A4

    with Plotter('/dev/ttyUSB0', 115200) as p:
        p.load_config('config.json')
        p.set_input_limits((0, 0), (W, 0), (0, H), (W, H))
        p.draw_polylines(to_draw)
    return 0
Exemple #9
0
 def __init__(self, seed, diameter):
     self.tmp = OpenSimplex(seed)
     self.d = diameter
     self.x = 0
     self.y = 0
Exemple #10
0
import pygame as pg
import sys
import numpy as np
import noise as no
from opensimplex import OpenSimplex

scale = 30.
seed = np.random.randint(0, 10000)
print(seed)
tmp = OpenSimplex(seed)
dim = [256, 256]
sdf = pg.display.set_mode(dim)


def tri(a):
    a = (a + 1) / 2
    # a=1-a*(1-a)
    a = int(256 * a)
    return [a, a, a]


def noi(b, k):
    # a= int(128*(pnoise3(i,j,k)+1))
    # return tri(tmp.noise3d(x, y, k))
    return np.array([
        np.array([tri(tmp.noise2d(i, j)) for j in b], dtype=np.uint8)
        for i in b
    ],
                    dtype=np.uint8)

import numpy as np
from opensimplex import OpenSimplex
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import io
import imageio


def plot_arrow(x, y, dir):
    plt.plot([x, x + np.cos(dir)], [y, y + np.sin(dir)], c='b')


simp = OpenSimplex()
n = 512
D_MAX = 2
T_MAX = 2 * np.pi
NUM_FRAMES = 150
x = np.linspace(0, D_MAX, n)
y = np.linspace(0, D_MAX, n)
z = .5 * np.cos(np.linspace(0, T_MAX, NUM_FRAMES))
t = .5 * np.sin(np.linspace(0, T_MAX, NUM_FRAMES))
NUM_LAYERS = 3
canvas = np.zeros((len(x), len(y), NUM_LAYERS)).astype(int)
NUM_SAMPLE_LAYERS = 2
samples = np.zeros((len(x), len(y), NUM_SAMPLE_LAYERS))
palette = {
    0: [73, 89, 103],
    1: [189, 213, 234],
    2: [87, 115, 153],
    3: [255, 79, 121]
}
Exemple #12
0
from opensimplex import OpenSimplex
import numpy as np
from PIL import Image
import math
import random

seed = OpenSimplex(random.randint(0, 1000))  # object used to generate noise
w, h = 400, 300  # dimensions of the map
f = 0.03  # base frequency. scales frequency of all octaves
hvar = 5.0  # height variance. used to alter height values to a more desirable level
elevation = [[0 for x in range(w)] for y in range(h)]
maxE, maxA, maxB, maxC = -999.0, -999.0, -999.0, -999.0
minE, minA, minB, minC = 999.0, 999.0, 999.0, 999.0


def simplex(x, y):  # simplex algorithm used to create noise for height map
    return (seed.noise2d(x, y) + 1) / 2


def adjustment_function(
        num,
        pow):  # adjusts heights of elevation map to make stronger contrasts
    return math.pow(num, pow)  # currently just original raised to a power


class Octave:
    def __init__(self, weight, frequency, array):
        self.weight = weight
        self.frequency = frequency
        self.array = array
        print("\ncreated octave with weight: " + str(self.weight) +
class Terrain(object):
    def __init__(self, song):
        self.app = QtGui.QApplication(sys.argv)
        self.window = gl.GLViewWidget()
        self.window.setGeometry(0, 200, 1280, 720)
        self.window.show()
        self.window.setWindowTitle('Terrain')
        self.window.setCameraPosition(distance=28, elevation=2, azimuth=0)
        self.nstep = 1
        self.ypoints1 = [i for i in range(-25, 26, self.nstep)]
        self.xpoints1 = [i for i in range(-52, -1, self.nstep)]
        self.ypoints2 = [i for i in range(-25, 26, self.nstep)]
        self.xpoints2 = [i for i in range(2, 53, self.nstep)]
        self.nfaces = len(self.ypoints1)
        self.perlin = OpenSimplex()
        self.offset = 0
        self.beat, self.posbeat = self.BeatMaker(song)
        self.beatindex = 0
        self.color_choice = [{
            "R": (117 / 255),
            "G": (221 / 255),
            "B": (221 / 255)
        }, {
            "R": (25 / 255),
            "G": (123 / 255),
            "B": (189 / 255)
        }, {
            "R": (11 / 255),
            "G": (19 / 255),
            "B": (43 / 255)
        }, {
            "R": (144 / 255),
            "G": (41 / 255),
            "B": (35 / 255)
        }, {
            "R": (144 / 255),
            "G": (41 / 255),
            "B": (35 / 255)
        }]

        def mesh_init(X, Y, Ampli):
            verts = np.array([[
                x, y,
                Ampli * self.perlin.noise2d(x=x / 5, y=y / 5 + self.offset)
            ] for x in X for y in Y],
                             dtype=np.float32)

            faces = []
            colors = []
            for m in range(self.nfaces - 1):
                yoff = m * self.nfaces
                for n in range(self.nfaces - 1):
                    faces.append([
                        n + yoff, yoff + n + self.nfaces,
                        yoff + n + self.nfaces + 1
                    ])
                    faces.append(
                        [n + yoff, yoff + n + 1, yoff + n + self.nfaces + 1])
                    colors.append(
                        [int(117 / 255),
                         int(221 / 255),
                         int(221 / 255), 0.78])
                    colors.append(
                        [int(117 / 255),
                         int(221 / 255),
                         int(221 / 255), 0.8])

            return np.array(verts), np.array(faces), np.array(colors)

        verts1, faces1, colors1 = mesh_init(self.ypoints1, self.xpoints1, 0.2)
        verts2, faces2, colors2 = mesh_init(self.ypoints2, self.xpoints2, 0.2)
        self.m1 = gl.GLMeshItem(
            vertexes=verts1,
            faces=faces1,
            faceColors=colors1,
            smooth=False,
            drawEdges=False,
        )
        self.m1.setGLOptions('additive')
        self.window.addItem(self.m1)
        self.m2 = gl.GLMeshItem(
            vertexes=verts2,
            faces=faces2,
            faceColors=colors2,
            smooth=False,
            drawEdges=False,
        )
        self.m2.setGLOptions('additive')
        self.window.addItem(self.m2)

    def start(self):
        """
        get the graphics window open and setup
        """

        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()

    def animation(self):
        """
        calls the update method to run in a loop
        """
        timer = QtCore.QTimer()
        timer.timeout.connect(self.update)
        timer.start(10)
        self.start()
        self.update()

    def update(self):
        """
        update the mesh and shift the noise each time
        """
        def mesh_init(X, Y, Ampli):
            verts = np.array([[
                x, y,
                Ampli * self.perlin.noise2d(x=(x / 5) + self.offset, y=(y / 5))
            ] for x in X for y in Y],
                             dtype=np.float32)

            faces = []
            colors = []
            a = int(self.posbeat[self.beatindex] * 4)
            if a > 4:
                a = 4

            color = self.color_choice[a]
            for m in range(self.nfaces - 1):
                yoff = m * self.nfaces
                for n in range(self.nfaces - 1):
                    faces.append([
                        n + yoff, yoff + n + self.nfaces,
                        yoff + n + self.nfaces + 1
                    ])
                    faces.append(
                        [n + yoff, yoff + n + 1, yoff + n + self.nfaces + 1])
                    colors.append([color["R"], color["G"], color["B"], 0.795])
                    colors.append([color["R"], color["G"], color["B"], 0.8])

            return np.array(verts), np.array(faces), np.array(colors)

        if self.beatindex < len(self.beat):
            verts1, faces1, colors1 = mesh_init(self.ypoints1, self.xpoints1,
                                                3 * self.beat[self.beatindex])
            verts2, faces2, colors2 = mesh_init(self.ypoints2, self.xpoints2,
                                                3 * self.beat[self.beatindex])
            self.m1.setMeshData(vertexes=verts1,
                                faces=faces1,
                                faceColors=colors1)
            self.m2.setMeshData(vertexes=verts2,
                                faces=faces2,
                                faceColors=colors2)
            self.offset -= 0.18
            self.window.grabFrameBuffer().save("frames10/" +
                                               str(self.beatindex) + '.png')
            self.beatindex += 1
        else:
            print("done")

    def BeatMaker(self, song):
        spf = wave.open(song, "r")
        signal = spf.readframes(-1)
        signal = np.frombuffer(signal, "int16")
        signal = signal.astype(float)
        fs = spf.getframerate()
        print(fs)
        print(len(signal))
        signal = np.array([signal[t] for t in range(0, 3639500, 2900)])
        print(len(signal))
        return signal / np.max(signal), np.absolute(2 * signal /
                                                    np.max(signal))
    def __init__(self, song):
        self.app = QtGui.QApplication(sys.argv)
        self.window = gl.GLViewWidget()
        self.window.setGeometry(0, 200, 1280, 720)
        self.window.show()
        self.window.setWindowTitle('Terrain')
        self.window.setCameraPosition(distance=28, elevation=2, azimuth=0)
        self.nstep = 1
        self.ypoints1 = [i for i in range(-25, 26, self.nstep)]
        self.xpoints1 = [i for i in range(-52, -1, self.nstep)]
        self.ypoints2 = [i for i in range(-25, 26, self.nstep)]
        self.xpoints2 = [i for i in range(2, 53, self.nstep)]
        self.nfaces = len(self.ypoints1)
        self.perlin = OpenSimplex()
        self.offset = 0
        self.beat, self.posbeat = self.BeatMaker(song)
        self.beatindex = 0
        self.color_choice = [{
            "R": (117 / 255),
            "G": (221 / 255),
            "B": (221 / 255)
        }, {
            "R": (25 / 255),
            "G": (123 / 255),
            "B": (189 / 255)
        }, {
            "R": (11 / 255),
            "G": (19 / 255),
            "B": (43 / 255)
        }, {
            "R": (144 / 255),
            "G": (41 / 255),
            "B": (35 / 255)
        }, {
            "R": (144 / 255),
            "G": (41 / 255),
            "B": (35 / 255)
        }]

        def mesh_init(X, Y, Ampli):
            verts = np.array([[
                x, y,
                Ampli * self.perlin.noise2d(x=x / 5, y=y / 5 + self.offset)
            ] for x in X for y in Y],
                             dtype=np.float32)

            faces = []
            colors = []
            for m in range(self.nfaces - 1):
                yoff = m * self.nfaces
                for n in range(self.nfaces - 1):
                    faces.append([
                        n + yoff, yoff + n + self.nfaces,
                        yoff + n + self.nfaces + 1
                    ])
                    faces.append(
                        [n + yoff, yoff + n + 1, yoff + n + self.nfaces + 1])
                    colors.append(
                        [int(117 / 255),
                         int(221 / 255),
                         int(221 / 255), 0.78])
                    colors.append(
                        [int(117 / 255),
                         int(221 / 255),
                         int(221 / 255), 0.8])

            return np.array(verts), np.array(faces), np.array(colors)

        verts1, faces1, colors1 = mesh_init(self.ypoints1, self.xpoints1, 0.2)
        verts2, faces2, colors2 = mesh_init(self.ypoints2, self.xpoints2, 0.2)
        self.m1 = gl.GLMeshItem(
            vertexes=verts1,
            faces=faces1,
            faceColors=colors1,
            smooth=False,
            drawEdges=False,
        )
        self.m1.setGLOptions('additive')
        self.window.addItem(self.m1)
        self.m2 = gl.GLMeshItem(
            vertexes=verts2,
            faces=faces2,
            faceColors=colors2,
            smooth=False,
            drawEdges=False,
        )
        self.m2.setGLOptions('additive')
        self.window.addItem(self.m2)
Exemple #15
0
    def __init__(self, song):
        self.app = QtGui.QApplication(sys.argv)
        self.window = gl.GLViewWidget()
        self.window.setGeometry(0, 500, 1280, 720)
        self.window.show()
        self.window.setWindowTitle('Terrain')
        self.window.setCameraPosition(pos=QtGui.QVector3D(0, 0, 0),
                                      distance=105,
                                      elevation=0,
                                      azimuth=90)
        self.nstep = 1
        self.ypoints1 = [i for i in range(-200, 201, self.nstep)]
        self.xpoints1 = [i for i in range(-10, 11, self.nstep)]
        self.ypoints2 = [i for i in range(-200, 201, self.nstep)]
        self.xpoints2 = [i for i in range(-10, 11, self.nstep)]
        self.nfaces1 = len(self.ypoints1)
        self.nfaces2 = len(self.xpoints1)
        self.perlin = OpenSimplex()
        self.offset = 0
        self.beat, self.posbeat = self.BeatMaker(song)
        self.beatindex = 0
        self.t = 0
        self.color_choice = [{
            "R": (115 / 255),
            "G": (115 / 255),
            "B": (115 / 255)
        }, {
            "R": (64 / 255),
            "G": (64 / 255),
            "B": (64 / 255)
        }, {
            "R": (38 / 255),
            "G": (38 / 255),
            "B": (38 / 255)
        }, {
            "R": (38 / 255),
            "G": (38 / 255),
            "B": (38 / 255)
        }, {
            "R": (11 / 255),
            "G": (19 / 255),
            "B": (43 / 255)
        }]

        def mesh_init(X, Y, z, Ampli):
            verts = np.array([[
                x, y,
                z + Ampli * self.perlin.noise2d(x=x / 5, y=y / 5 + self.offset)
            ] for x in X for y in Y],
                             dtype=np.float32)
            # for j in range(0, len(verts)):
            #     if abs(verts[j, 1]) > 20:
            #         verts[j, 2] = 100
            faces = []
            colors = []
            for m in range(self.nfaces2 - 1):
                yoff = m * self.nfaces2
                for n in range(self.nfaces1 - 1):
                    faces.append([
                        n + yoff, yoff + n + self.nfaces1,
                        yoff + n + self.nfaces1 + 1
                    ])
                    faces.append(
                        [n + yoff, yoff + n + 1, yoff + n + self.nfaces1 + 1])
                    colors.append(
                        [int(117 / 255),
                         int(221 / 255),
                         int(221 / 255), 1])
                    colors.append(
                        [int(117 / 255),
                         int(221 / 255),
                         int(221 / 255), 1])

            return np.array(verts), np.array(faces), np.array(colors)

        verts1, faces1, colors1 = mesh_init(self.ypoints1, self.xpoints1, 5,
                                            0.2)
        verts2, faces2, colors2 = mesh_init(self.ypoints2, self.xpoints2, -5,
                                            0.2)
        self.m1 = gl.GLMeshItem(
            vertexes=verts1,
            faces=faces1,
            faceColors=colors1,
            smooth=False,
            drawEdges=False,
        )
        self.m1.setGLOptions('additive')
        self.window.addItem(self.m1)
        self.m2 = gl.GLMeshItem(
            vertexes=verts2,
            faces=faces2,
            faceColors=colors2,
            smooth=False,
            drawEdges=False,
        )
        self.m2.setGLOptions('additive')
        self.window.addItem(self.m2)
Exemple #16
0
class Terrain(object):
    def __init__(self, song):
        self.app = QtGui.QApplication(sys.argv)
        self.window = gl.GLViewWidget()
        self.window.setGeometry(0, 500, 1280, 720)
        self.window.show()
        self.window.setWindowTitle('Terrain')
        self.window.setCameraPosition(pos=QtGui.QVector3D(0, 0, 0),
                                      distance=105,
                                      elevation=0,
                                      azimuth=90)
        self.nstep = 1
        self.ypoints1 = [i for i in range(-200, 201, self.nstep)]
        self.xpoints1 = [i for i in range(-10, 11, self.nstep)]
        self.ypoints2 = [i for i in range(-200, 201, self.nstep)]
        self.xpoints2 = [i for i in range(-10, 11, self.nstep)]
        self.nfaces1 = len(self.ypoints1)
        self.nfaces2 = len(self.xpoints1)
        self.perlin = OpenSimplex()
        self.offset = 0
        self.beat, self.posbeat = self.BeatMaker(song)
        self.beatindex = 0
        self.t = 0
        self.color_choice = [{
            "R": (115 / 255),
            "G": (115 / 255),
            "B": (115 / 255)
        }, {
            "R": (64 / 255),
            "G": (64 / 255),
            "B": (64 / 255)
        }, {
            "R": (38 / 255),
            "G": (38 / 255),
            "B": (38 / 255)
        }, {
            "R": (38 / 255),
            "G": (38 / 255),
            "B": (38 / 255)
        }, {
            "R": (11 / 255),
            "G": (19 / 255),
            "B": (43 / 255)
        }]

        def mesh_init(X, Y, z, Ampli):
            verts = np.array([[
                x, y,
                z + Ampli * self.perlin.noise2d(x=x / 5, y=y / 5 + self.offset)
            ] for x in X for y in Y],
                             dtype=np.float32)
            # for j in range(0, len(verts)):
            #     if abs(verts[j, 1]) > 20:
            #         verts[j, 2] = 100
            faces = []
            colors = []
            for m in range(self.nfaces2 - 1):
                yoff = m * self.nfaces2
                for n in range(self.nfaces1 - 1):
                    faces.append([
                        n + yoff, yoff + n + self.nfaces1,
                        yoff + n + self.nfaces1 + 1
                    ])
                    faces.append(
                        [n + yoff, yoff + n + 1, yoff + n + self.nfaces1 + 1])
                    colors.append(
                        [int(117 / 255),
                         int(221 / 255),
                         int(221 / 255), 1])
                    colors.append(
                        [int(117 / 255),
                         int(221 / 255),
                         int(221 / 255), 1])

            return np.array(verts), np.array(faces), np.array(colors)

        verts1, faces1, colors1 = mesh_init(self.ypoints1, self.xpoints1, 5,
                                            0.2)
        verts2, faces2, colors2 = mesh_init(self.ypoints2, self.xpoints2, -5,
                                            0.2)
        self.m1 = gl.GLMeshItem(
            vertexes=verts1,
            faces=faces1,
            faceColors=colors1,
            smooth=False,
            drawEdges=False,
        )
        self.m1.setGLOptions('additive')
        self.window.addItem(self.m1)
        self.m2 = gl.GLMeshItem(
            vertexes=verts2,
            faces=faces2,
            faceColors=colors2,
            smooth=False,
            drawEdges=False,
        )
        self.m2.setGLOptions('additive')
        self.window.addItem(self.m2)

    def start(self):
        """
        get the graphics window open and setup
        """

        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()

    def animation(self):
        """
        calls the update method to run in a loop
        """
        # timer = QtCore.QTimer()
        # timer.timeout.connect(self.update)
        # timer.start(10)
        self.start()

    def update(self):
        """
        update the mesh and shift the noise each time
        """
        def mesh_init(X, Y, z, Ampli, signe):

            verts = np.array([[
                x + (Ampli / 1.5) * self.perlin.noise2d(
                    x=y / 10, y=y / 10 - self.offset + self.offset), y,
                (z + signe * np.sqrt(10**2 - x**2) - signe * Ampli *
                 self.perlin.noise2d(x=x / 5, y=y / 5 + self.offset))
            ] if abs(x) < 10 else [x, y, 0] for y in Y for x in X],
                             dtype=np.float32)
            faces = []
            colors = []
            a = int(self.posbeat[self.beatindex] * 4)
            if a > 4:
                a = 4

            color = self.color_choice[a]
            # print(color["R"])
            for m in range(self.nfaces1 - 1):
                yoff = m * self.nfaces2
                for n in range(self.nfaces2 - 1):
                    faces.append([
                        n + yoff, yoff + n + self.nfaces2,
                        yoff + n + self.nfaces2 + 1
                    ])
                    faces.append(
                        [n + yoff, yoff + n + 1, yoff + self.nfaces2 + n + 1])
                    colors.append([color["R"], color["G"], color["B"], 1])
                    colors.append([color["R"], color["G"], color["B"], 0.995])

            return np.array(verts), np.array(faces), np.array(colors)

        stime = time.time()
        if self.beatindex < len(self.beat):
            verts1, faces1, colors1 = mesh_init(self.xpoints1, self.ypoints1,
                                                0,
                                                10 * self.beat[self.beatindex],
                                                1)
            verts2, faces2, colors2 = mesh_init(self.xpoints2, self.ypoints2,
                                                0,
                                                10 * self.beat[self.beatindex],
                                                -1)
            self.m1.setMeshData(vertexes=verts1,
                                faces=faces1,
                                faceColors=colors1)
            self.m2.setMeshData(vertexes=verts2,
                                faces=faces2,
                                faceColors=colors2)

            self.window.setCameraPosition(
                pos=QtGui.QVector3D(0, 0, 0),
                distance=200,
                elevation=4 *
                (self.perlin.noise2d(x=self.beat[self.beatindex + 1],
                                     y=self.beat[self.beatindex])),
                azimuth=90 + 4 *
                (self.perlin.noise2d(x=self.beat[self.beatindex + 1],
                                     y=self.beat[self.beatindex])))
            self.offset -= 0.2
            self.window.grabFrameBuffer().save("frames/" +
                                               str(self.beatindex) + '.png')
            self.beatindex += 1

        else:
            print("done")
        self.t += (time.time() - stime) / 30
        print('{:.0f} FPS'.format(self.t))

    def BeatMaker(self, song):
        spf = wave.open(song, "r")
        signal = spf.readframes(-1)
        signal = np.frombuffer(signal, "int16")
        signal = signal.astype(float)
        fs = spf.getframerate()
        print(fs)

        signal = np.array(
            [signal[t] for t in range(0, len(signal), int((2 * fs) / 30))])
        signalabs = np.absolute(signal)

        return (signal - np.mean(signal)) / (
            np.max(signal) - np.min(signal)), 5 * np.absolute(
                signalabs - np.mean(signalabs) /
                (np.max(signalabs) - np.min(signalabs))) / max(
                    np.absolute(signalabs - np.mean(signalabs) /
                                (np.max(signalabs) - np.min(signalabs))))
    if not os.path.isfile(imagePath):
        print(imagePath, "can't be found")
        exit()

    img = cv2.imread(imagePath)
    if img is None:
        print(imagePath, "is not an image")
        exit()

    img = cv2.resize(img, None, fx=INPUT_SCALE, fy=INPUT_SCALE)

    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)

    simplex = OpenSimplex()
    noise = np.zeros((20, 20))

    pb = ProgressBar(total=NB_FRAMES - 1,
                     decimals=1,
                     length=40,
                     fill='-',
                     zfill=' ')

    print("Your animation is in process : ")

    for step in range(NB_FRAMES):
        stepPercent = step / NB_FRAMES
        pb.print_progress_bar(step)

        tx = dT * math.cos(stepPercent * 2 * math.pi)
import numpy
from PIL import Image

from opensimplex import OpenSimplex

WIDTH = 64
OPEN_SIMPLEX = OpenSimplex(seed=12345)


def main():
    im = Image.new('L', (WIDTH, WIDTH))
    for y in range(WIDTH):
        for x in range(WIDTH):
            value = OPEN_SIMPLEX.noise2d(x / 8., y / 8.)
            color = int((value + 1.) * 128.)
            im.putpixel((x, y), color)
    im.show()


def _main():
    data = numpy.zeros((WIDTH, WIDTH, 3), dtype=numpy.uint8)

    for _y in range(WIDTH):
        row = data[_y]
        for _x in range(WIDTH):
            _v = (OPEN_SIMPLEX.noise2d(_x / 8., _y / 8.) + 1.) * 128.
            row[_x] = [_v, _v, _v]

    img = Image.fromarray(data)
    img.show()  # View in default viewer
Exemple #19
0
 def __init__(self):
     self.chunk_array = np.empty((15, 15), dtype=object)
     self.spnoise = OpenSimplex()
Exemple #20
0
import pygame
import sys
import random
import math
from opensimplex import OpenSimplex

filters = 4
timer = pygame.time.Clock()
screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption("clowd")
surface = pygame.Surface((400, 400), pygame.SRCALPHA)
seed = OpenSimplex(random.randint(1, 100))
for i in range(400):
    for j in range(100):
        density = max(
            seed.noise2d(x=i / 80, y=j / 20) * 250 *
            math.sin(math.pi * j / 100), 0)
        pygame.draw.rect(surface, (255, 255, 255, density),
                         pygame.Rect(i, j + 100, 1, 1))

screen.blit(surface, (0, 0))
frames = 400
while True:
    surface.scroll(dx=-1)
    pygame.draw.rect(surface, (0, 0, 0, 0), pygame.Rect(399, 0, 1, 400))
    for j in range(100):
        density = max(
            seed.noise2d(x=frames / 80, y=j / 20) * 250 *
            math.sin(math.pi * j / 100), 0)
        pygame.draw.rect(surface, (255, 255, 255, density),
                         pygame.Rect(399, j + 100, 1, 1))
Exemple #21
0
class Mesh:
    def __init__(self):  # pass in self, and the app & view attributes
        self.app = QtGui.QApplication(
            sys.argv
        )  # the window titl this be the GUI for our project, allowing us to see all of the visuals
        self.view = gl.GLViewWidget(
        )  # this is going to be the view widget that we need to be able to add meshes
        self.view.show()  # shows the view widget
        self.view.setWindowTitle(
            'Mesh')  #sets the window title to whatever we want
        self.noise = OpenSimplex()
        self.offSet = 0  # change the noise value as we loop through the animation
        self.RATE = 44100  # standard refresh rate for videos
        self.CHUNK = 1024  # standard chunk size for data; this is why our grid is 32 x 32
        self.audioData = None  # this will keep track of the audio data we read
        self.p = pyaudio.PyAudio()  # instance of a pyaudio class
        self.stream = self.p.open(
            format=pyaudio.paInt16,
            channels=1,
            rate=self.RATE,
            input=True,
            output=True,
            frames_per_buffer=self.CHUNK)  # this is how we read audio data

        vertices = []  # vertices is an np array of [x, y, z] coordinates
        for row in range(32):  # row corresponds to the y value
            for col in range(32):  # col corresponds to the x value
                vertices.append([
                    col, row, self.noise.noise2d(x=row, y=col)
                ])  # add noise to the z coord to create a random terrain

        faces = [
        ]  # faces is an np array of [vertex1, vertex2, vertex3] using indices from the vertices np array
        for n in range(31):  # row
            for k in range(31):  # column
                # first point of FIRST triangle; to the right of the first; directly below the first
                faces.append([n * 32 + k, n * 32 + k + 1, (n + 1) * 32 + k])
                # first point of SECOND triangle (same as last point of first triangle); to the right of the first; at the top (same as second position of first triangle)
                faces.append([(n + 1) * 32 + k, (n + 1) * 32 + k + 1,
                              n * 32 + k + 1])

        colors = []
        for i in range(341):  #ratio between 0 to 1 ...divide by length of row
            colors.append([1, 0, 0, 0.6])
            colors.append([0, 1, 0, 0.6])
            colors.append([0, 0, 1, 0.6])
        colors.append([1, 0, 0, 0.6])

        v = np.array(vertices)
        f = np.array(faces)
        c = np.array(colors)

        self.mesh = gl.GLMeshItem(vertexes=v, faces=f, faceColors=c)
        self.mesh.setGLOptions("additive")
        self.view.addItem(self.mesh)
        self.view.setWindowTitle('me$h')

    def update(self):
        self.audioData = self.stream.read(
            self.CHUNK, exception_on_overflow=False
        )  # this reads incoming audiodata self.CHUNK bytes at a time
        # important to set exception_on_overflow in line above to False in order to prevent program from crashing
        audio_obj = struct.unpack(str(2 * self.CHUNK) + 'B', self.audioData)
        audio_obj = np.array(audio_obj, dtype='b')[::2] + 128
        audio_obj = np.array(audio_obj, dtype='int32') - 128
        audio_obj = audio_obj * 0.04
        audio_obj = audio_obj.reshape(32, 32)

        vertices = []  # vertices is an np array of [x, y, z] coordinates
        for row in range(32):  # row corresponds to the y value
            for col in range(32):  # col corresponds to the x value
                vertices.append([
                    col, row, audio_obj[row][col] * self.noise.noise2d(
                        x=row + self.offSet, y=col + self.offSet)
                ])

        self.offSet -= 0.1  # each time the update function gets called, self.offSet decrements by 0.1

        faces = [
        ]  # faces is an np array of [vertex1, vertex2, vertex3] using indices from the vertices np array
        for n in range(31):  # row
            for k in range(31):  # column
                # first point of FIRST triangle; to the right of the first; directly below the first
                faces.append([n * 32 + k, n * 32 + k + 1, (n + 1) * 32 + k])
                # first point of SECOND triangle (same as last point of first triangle); to the right of the first; at the top (same as second position of first triangle)
                faces.append([(n + 1) * 32 + k, (n + 1) * 32 + k + 1,
                              n * 32 + k + 1])

        colors = []
        for i in range(341):  #ratio between 0 to 1 ...divide by length of row
            colors.append([1, 0, 0, 0.6])
            colors.append([0, 1, 0, 0.6])
            colors.append([0, 0, 1, 0.6])
        colors.append([1, 0, 0, 0.6])

        v = np.array(vertices)
        f = np.array(faces)
        c = np.array(colors)

        self.mesh.setMeshData(vertexes=v,
                              faces=f,
                              vertexColors=c,
                              drawEdges=True)

    def animation(self):
        timer = QtCore.QTimer()
        timer.timeout.connect(self.update)
        timer.start(10)
        self.run()  # call the start function to kick off animation
        self.update()  # call the update function to kick off animation

    def run(
        self
    ):  # this function actually executes our Mesh instance and enables the GUI to run!
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()
Exemple #22
0
from opensimplex import OpenSimplex
from random import randint
"""
SETUP
"""
# Constants
WIDTH = 200
HEIGHT = 200
RESOLUTION = 7  #Larger value makes scale larger and more smooth
SEED = randint(1, 10000000)

# Variables
_map = []
ops = OpenSimplex(seed=SEED)
"""
FUNCTIONS
"""


def fillBlank(mapp):
    mapp.clear()
    for y in range(HEIGHT):
        mapp.append([-1] * WIDTH)


def printMap():
    for y in range(HEIGHT):
        print(_map[y])


def fileWrite():
Exemple #23
0
from opensimplex import OpenSimplex
from config import SEED, WIDTH, LENGTH, PAD, UNPADDED_LENGTH, UNPADDED_WIDTH
import numpy as np

xs = np.linspace(start=0, stop=UNPADDED_WIDTH - 1, num=UNPADDED_WIDTH)
ys = np.linspace(start=0, stop=UNPADDED_LENGTH - 1, num=UNPADDED_LENGTH)
xs, ys = np.meshgrid(xs, ys)

xs_longer = np.linspace(start=0, stop=WIDTH - 1, num=WIDTH)
ys_longer = np.linspace(start=0, stop=LENGTH - 1, num=LENGTH)
xs_longer, ys_longer = np.meshgrid(xs_longer, ys_longer)

gen = OpenSimplex(seed=SEED)


def gradient_array():
    x_rad = np.ones_like(xs) - abs(xs - UNPADDED_WIDTH / 2) / (UNPADDED_WIDTH *
                                                               0.5)
    y_rad = np.ones_like(ys) - abs(ys - UNPADDED_WIDTH / 2) / (UNPADDED_WIDTH *
                                                               0.5)
    return np.sqrt(x_rad * y_rad)


def noise_layer(frequency, length=UNPADDED_LENGTH, width=UNPADDED_WIDTH):
    layer = np.zeros((length, width))
    for x in range(length):
        for y in range(width):
            layer[x, y] += gen.noise2d(x * frequency / length,
                                       y * frequency / width)
    return layer
Exemple #24
0
class Terrain(object):
    def __init__(self):
        """
        Initialize the graphics window and mesh
        """

        # setup the view window
        self.app = QtGui.QApplication(sys.argv)
        self.w = gl.GLViewWidget()
        self.w.setGeometry(0, 110, 1920, 1080)
        self.w.show()
        self.w.setWindowTitle('Terrain')
        self.w.setCameraPosition(distance=30, elevation=8)

        # constants and arrays
        self.nsteps = 1
        self.ypoints = range(-20, 22, self.nsteps)
        self.xpoints = range(-20, 22, self.nsteps)
        self.nfaces = len(self.ypoints)
        self.offset = 0

        # perlin noise object
        self.tmp = OpenSimplex()

        # create the veritices array
        verts = np.array([
            [
                x, y, 1.5 * self.tmp.noise2d(x=n / 5, y=m / 5)
            ] for n, x in enumerate(self.xpoints) for m, y in enumerate(self.ypoints)
        ], dtype=np.float32)

        # create the faces and colors arrays
        faces = []
        colors = []
        for m in range(self.nfaces - 1):
            yoff = m * self.nfaces
            for n in range(self.nfaces - 1):
                faces.append([n + yoff, yoff + n + self.nfaces, yoff + n + self.nfaces + 1])
                faces.append([n + yoff, yoff + n + 1, yoff + n + self.nfaces + 1])
                colors.append([0, 0, 0, 0])
                colors.append([0, 0, 0, 0])

        faces = np.array(faces)
        colors = np.array(colors)

        # create the mesh item
        self.m1 = gl.GLMeshItem(
            vertexes=verts,
            faces=faces, faceColors=colors,
            smooth=False, drawEdges=True,
        )
        self.m1.setGLOptions('additive')
        self.w.addItem(self.m1)

    def update(self):
        """
        update the mesh and shift the noise each time
        """
        verts = np.array([
            [
                x, y, 2.5 * self.tmp.noise2d(x=n / 5 + self.offset, y=m / 5 + self.offset)
            ] for n, x in enumerate(self.xpoints) for m, y in enumerate(self.ypoints)
        ], dtype=np.float32)

        faces = []
        colors = []
        for m in range(self.nfaces - 1):
            yoff = m * self.nfaces
            for n in range(self.nfaces - 1):
                faces.append([n + yoff, yoff + n + self.nfaces, yoff + n + self.nfaces + 1])
                faces.append([n + yoff, yoff + n + 1, yoff + n + self.nfaces + 1])
                colors.append([n / self.nfaces, 1 - n / self.nfaces, m / self.nfaces, 0.7])
                colors.append([n / self.nfaces, 1 - n / self.nfaces, m / self.nfaces, 0.8])

        faces = np.array(faces, dtype=np.uint32)
        colors = np.array(colors, dtype=np.float32)

        self.m1.setMeshData(
            vertexes=verts, faces=faces, faceColors=colors
        )
        self.offset -= 0.18

    def start(self):
        """
        get the graphics window open and setup
        """
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()

    def animation(self):
        """
        calls the update method to run in a loop
        """
        timer = QtCore.QTimer()
        timer.timeout.connect(self.update)
        timer.start(10)
        self.start()
        self.update()
Exemple #25
0
    def generate_heightmap(self, env_name, env_length, current_height):
        if env_name == "flat":
            hm = np.ones((self.env_width, env_length)) * current_height

        if env_name == "tiles":
            sf = 3
            hm = np.random.randint(0, 55,
                                   size=(self.env_width // sf, env_length // sf)).repeat(sf, axis=0).repeat(sf, axis=1)
            hm_pad = np.zeros((self.env_width, env_length))
            hm_pad[:hm.shape[0], :hm.shape[1]] = hm
            hm = hm_pad + current_height

        if env_name == "pipe":
            pipe_form = np.square(np.linspace(-1.2, 1.2, self.env_width))
            pipe_form = np.clip(pipe_form, 0, 1)
            hm = 255 * np.ones((self.env_width, env_length)) * pipe_form[np.newaxis, :].T
            hm += current_height

        if env_name == "holes":
            hm = cv2.imread(os.path.join(os.path.dirname(os.path.realpath(__file__)), "assets/holes1.png"))
            h, w, _ = hm.shape
            patch_y = 14
            patch_x = int(14 * self.s_len / 150.)
            rnd_h = np.random.randint(0, h - patch_x)
            rnd_w = np.random.randint(0, w - patch_y)
            hm = hm[rnd_w:rnd_w + patch_y, rnd_h:rnd_h + patch_x]
            hm = np.mean(hm, axis=2)
            hm = hm * 1.0 + 255 * 0.3
            hm = cv2.resize(hm, dsize=(env_length, self.env_width), interpolation=cv2.INTER_CUBIC) / 2.

        if env_name == "inverseholes":
            hm = cv2.imread(os.path.join(os.path.dirname(os.path.realpath(__file__)), "assets/holes1.png"))
            h, w, _ = hm.shape
            patchsize = 10
            while True:
                rnd_h = np.random.randint(0, h - patchsize)
                rnd_w = np.random.randint(0, w - patchsize)
                hm_tmp = hm[rnd_w:rnd_w + patchsize, rnd_h:rnd_h + patchsize]
                #assert hm.shape == (10,10,3)
                if np.min(hm_tmp[:, :2, :]) > 160: break

            hm = np.mean(hm_tmp, axis=2)
            hm = cv2.resize(hm, dsize=(env_length, self.env_width), interpolation=cv2.INTER_CUBIC)
            hm = 255 - hm
            hm *= 0.5
            hm += 127

        if env_name == "bumps":
            hm = cv2.imread(os.path.join(os.path.dirname(os.path.realpath(__file__)), "assets/bumps2.png"))
            h, w, _ = hm.shape
            patchsize = 50
            rnd_h = np.random.randint(0, h - patchsize)
            rnd_w = np.random.randint(0, w - patchsize)
            hm = hm[rnd_w:rnd_w + patchsize, rnd_h:rnd_h + patchsize]
            hm = np.mean(hm, axis=2)
            hm = cv2.resize(hm, dsize=(env_length, self.env_width), interpolation=cv2.INTER_CUBIC) / 2. + 127

        if env_name == "stairs":
            hm = np.ones((self.env_width, env_length)) * current_height
            stair_height = 45
            stair_width = 4

            initial_offset = 0
            n_steps = math.floor(env_length / stair_width) - 1

            for i in range(n_steps):
                hm[:, initial_offset + i * stair_width: initial_offset  + i * stair_width + stair_width] = current_height
                current_height += stair_height

            hm[:, n_steps * stair_width:] = current_height


        if env_name == "verts":
            wdiv = 4
            ldiv = 14
            hm = np.random.randint(0, 75,
                                   size=(self.env_width // wdiv, env_length // ldiv),
                                   dtype=np.uint8).repeat(wdiv, axis=0).repeat(ldiv, axis=1)
            hm[:, :50] = 0
            hm[hm < 50] = 0
            hm = 75 - hm


        if env_name == "triangles":
            cw = 10
            # Make even dimensions
            M = math.ceil(self.env_width)
            N = math.ceil(env_length)
            hm = np.zeros((M, N), dtype=np.float32)
            M_2 = math.ceil(M / 2)

            # Amount of 'tiles'
            Mt = 2
            Nt = int(env_length / 10.)
            obstacle_height = 50
            grad_mat = np.linspace(0, 1, cw)[:, np.newaxis].repeat(cw, 1)
            template_1 = np.ones((cw, cw)) * grad_mat * grad_mat.T * obstacle_height
            template_2 = np.ones((cw, cw)) * grad_mat * obstacle_height

            for i in range(Nt):
                if np.random.choice([True, False]):
                    hm[M_2 - cw: M_2, i * cw: i * cw + cw] = np.rot90(template_1, np.random.randint(0, 4))
                else:
                    hm[M_2 - cw: M_2, i * cw: i * cw + cw] = np.rot90(template_2, np.random.randint(0, 4))

                if np.random.choice([True, False]):
                    hm[M_2:M_2 + cw:, i * cw: i * cw + cw] = np.rot90(template_1, np.random.randint(0, 4))
                else:
                    hm[M_2:M_2 + cw:, i * cw: i * cw + cw] = np.rot90(template_2, np.random.randint(0, 4))

            hm += current_height


        if env_name == "perlin":
            oSim = OpenSimplex(seed=int(time.time()))

            height = 100

            M = math.ceil(self.env_width)
            N = math.ceil(env_length)
            hm = np.zeros((M, N), dtype=np.float32)

            scale_x = 20
            scale_y = 20
            octaves = 4  # np.random.randint(1, 5)
            persistence = 1
            lacunarity = 2

            for i in range(M):
                for j in range(N):
                    for o in range(octaves):
                        sx = scale_x * (1 / (lacunarity ** o))
                        sy = scale_y * (1 / (lacunarity ** o))
                        amp = persistence ** o
                        hm[i][j] += oSim.noise2d(i / sx, j / sy) * amp

            wmin, wmax = hm.min(), hm.max()
            hm = (hm - wmin) / (wmax - wmin) * height
            hm += current_height


        return hm, current_height
Exemple #26
0
import math, os
from opensimplex import OpenSimplex

gen = OpenSimplex()


def noise(nx, ny, freq, octave, power):
    sum_ = 0
    if octave == 0:
        octave = 1
    #for x in range(1, octave):
    #    sum_ += (1/x)*gen.noise2d(freq*nx*(x**2), freq*ny*(x**2)) / 2.0 + 0.5
    for x in range(1, octave):
        sum_ += (1 / float(x)) * (gen.noise2d(freq * nx *
                                              (2**x), freq * ny *
                                              (2**x)) / 2.0 + 0.5)
    #sum_ = gen.noise2d(freq*nx, freq*ny) + 0.5*gen.noise2d(2*freq*nx, 2*freq*ny) + 0.25*gen.noise2d(4*freq*nx, 4*freq*nx)#/ 2.0 + 0.5
    return (sum_)**power


def convert_to_terrain(num, blocks):
    for n in range(1, blocks + 1):
        if num < (float(n) / blocks):
            return n
        elif num > 1:
            return 1


def wanking_cunt(x_width, y_height, freq, octaves, power, features):
    array = []
    if not os.path.exists('map.dat'):
Exemple #27
0
 def __init__(self):
     self.gen = OpenSimplex(random.randint(0, sys.maxint))
def draw_field(field, guide=None, N_particles=50000, vis=False):
    ''' draw vector field

    args:
    field - (H, W, 2) np array
    guide - (H, W) np array image '''
    lines = []

    if guide is None:
        guide_counter = np.ones(field.shape[:2])
    else:
        guide_counter = guide.copy()

    def sample_field_point(probs, n=1):
        N_points = probs.size
        lin_coords = np.random.choice(N_points,
                                      size=n,
                                      replace=False,
                                      p=probs.flatten())
        coords = np.unravel_index(lin_coords, probs.shape)
        coords = np.array(coords).T
        if n == 1:
            coords = coords[0]
        return coords

    guide_scale = 1
    guide_counter = cv2.resize(guide_counter,
                               dsize=(0, 0),
                               fx=guide_scale,
                               fy=guide_scale)
    probs = guide_counter.copy()**1.4
    probs /= np.sum(probs)
    max_prob = np.amax(probs)
    orig_guide = guide_counter.copy()

    rot_noise = OpenSimplex(117)
    rot_noise_mult = 0.555

    start_pts = []

    H, W = field.shape[:2]
    for part_i in tqdm.tqdm(range(N_particles)):
        if np.random.rand() > 0.5:
            sign = -1
        else:
            sign = 1

        line = []
        pos = sample_field_point(probs)
        prob = probs[pos[0], pos[1]]
        # pos /= guide_scale
        pos = pos[::-1].astype(np.float64)  # convert to (x, y)
        start_pts.append(pos.copy())

        # perturbation_angle = np.random.randn()
        # perturbation_angle /= 3
        perturbation_angle = rot_noise.noise2d(x=rot_noise_mult * pos[0],
                                               y=rot_noise_mult * pos[1])
        perturbation_angle /= 1.6
        c, s = np.cos(perturbation_angle), np.sin(perturbation_angle)
        perturbation_rot = np.array([[c, -s], [s, c]])

        line.append(pos.copy())
        particle_paint_left = (
            (max_prob - prob) / max_prob)**0.5 * 30 * guide_scale
        # print(f"particle_paint_left: {particle_paint_left}")
        stop_line = False
        vals = []
        while particle_paint_left > 0:
            field_pos = np.round(pos)
            force = field[int(field_pos[1]), int(field_pos[0]), :]
            old_pos = pos.copy()
            # if np.linalg.norm(force) < 0.0001:
            #     force += 1
            # to_add = sign * force
            to_add = sign * force / np.linalg.norm(force)
            to_add = np.matmul(perturbation_rot, to_add.T).T
            pos += to_add
            # pos = np.round(pos)
            if np.logical_or(np.any(pos < 0), np.any(pos >= (W, H))):
                break

            segment = bresenham(old_pos, np.round(pos))
            prev_xy = None
            for xy in segment:
                xy = np.floor(guide_scale * np.array(xy)).astype(np.int32)
                if np.all(xy == prev_xy):
                    continue
                prev_xy = xy.copy()
                try:
                    val = orig_guide[xy[1], xy[0]].copy()
                    vals.append(val)
                    if np.abs(vals[-1] - vals[0]) > (30.0 / 256):
                        stop_line = True
                        break
                    particle_paint_left -= 1
                    if particle_paint_left <= 0:
                        stop_line = True
                        break
                except IndexError:
                    stop_line = True
                    break
            if np.all(force == 0):
                # print('noforce')
                break

            line.append(pos.copy())

            if stop_line:
                # print('stop_line')
                break

        line = np.array(line)
        if len(line) >= 2:
            lines.append(line)
        if vis:
            plt.plot(line[:, 0], line[:, 1], 'k-', lw=0.1, alpha=0.5)

    if vis:
        plt.axis('image')
        plt.gca().invert_yaxis()
        # plt.figure()
        # start_pts = np.array(start_pts)
        # plt.plot(start_pts[:, 0], start_pts[:, 1], 'k.', markersize=0.3)
        # plt.axis('image')
        # plt.gca().invert_yaxis()
        # plt.imshow(guide_counter)
        # plt.colorbar()
        plt.show()
    return lines
Exemple #29
0
# Noisy Fire effect, ported from
# https://gist.github.com/StefanPetrick/1ba4584e534ba99ca259c1103754e4c5
import time
import neopixel
import random
from visualisation import Visualisation
import logging
from opensimplex import OpenSimplex
from .utils import millis, scale, toRGB
import adafruit_fancyled.adafruit_fancyled as fancy
from math import sin, cos, sqrt

noise = OpenSimplex()

logger = logging.getLogger(__name__)


class NoisyColoursVisualisation(Visualisation):
    def __init__(self, pixels: neopixel.NeoPixel, num_pixels: int):
        super().__init__(pixels, num_pixels)
        self.x = [0 for x in range(0, 100)]
        self.y = [0 for x in range(0, 100)]

        for i in range(0, 100):
            angle = (i * 256) / 100
            self.x[i] = cos(angle)
            self.y[i] = sin(angle)

    def doTask(self):
        while self.running:
            scale_val = 1000
Exemple #30
0
        r = x - rho * residual
        x = prox_l2(r, theta)

        pbar.set_postfix(iter=loop, loss=np.linalg.norm(residual))

        loop += 1

    return x


if (__name__ == '__main__'):

    pl.close('all')

    seed = np.random.randint(low=0, high=10000)
    noise = OpenSimplex(seed=125)  #seed=123)

    # Set orbital properties
    p_rotation = 23.934
    p_orbit = 365.256363 * 24.0
    phi_orb = np.pi
    inclination = 0.0  #np.pi/2
    obliquity = 90. * np.pi / 180.0
    phi_rot = np.pi

    nside = 16
    npix = hp.nside2npix(nside)
    polar_angle, azimuthal_angle = hp.pixelfunc.pix2ang(nside, np.arange(npix))

    x = np.sin(polar_angle) * np.cos(azimuthal_angle)
    y = np.sin(polar_angle) * np.sin(azimuthal_angle)
Exemple #31
0
 def __init__(self, seed=0):
     self.simplex_fn = OpenSimplex(seed=seed)
Exemple #32
0
        for idx in range(self.strip_length):
            val = self.op.noise2d(idx / self.x_div(),
                                  self.counter / self.y_div())
            val = scale(val, 0, 3, -1, 1)
            self.pixels[idx]['color'] = num_to_rgb(val) + (self.color.a, )

        # update counter
        self.counter += 1


def num_to_rgb(val, max_val=3):
    i = (val * 255 / max_val)
    r = round(math.sin(0.024 * i + 0) * 127 + 128)
    g = round(math.sin(0.024 * i + 2) * 127 + 128)
    b = round(math.sin(0.024 * i + 4) * 127 + 128)
    return (r, g, b)


if __name__ == '__main__':
    import matplotlib.pyplot as plt

    noise = []
    op = OpenSimplex(seed=1)
    for idx in range(256):
        noise.append([op.noise2d(jdx / 8, idx / 8) for jdx in range(256)])

    plt.imshow(noise, cmap='gray', interpolation='lanczos')
    plt.colorbar()

    plt.show()
Exemple #33
0
 def __init__(self, seed, width = 50, height = 50):
     self.openSimplex = OpenSimplex(seed)
     self.load_tiles(width, height)
Exemple #34
0
from random import randint
from opensimplex import OpenSimplex
tmp = OpenSimplex(seed=randint(1, 100000))

#Import for main program
from PIL import Image
from tkinter import filedialog
from math import sqrt

#Initialise width / height
width = 1000
height = 1000

#Import gradient picture - 200*1 image used to texture perlin noise
#R,G,B,Alpha
gradient = Image.open("image.png")
gradlist = list(gradient.getdata())

#Create new image
img = Image.new('RGBA', (width, height), color=(255, 255, 255, 255))


def pixel(x, y):
    distance = sqrt(abs(x - 3)**2 + abs(y - 3)**2)
    simplex = -distance * 1.3
    for r in range(0, 12):
        simplex += (tmp.noise2d(x * 1.28**r, y * 1.28**r) / (r + 1) * 2.56)
    simplex -= 3 * (abs(x - 5.8) + abs(x - 0.2) + abs(y - 5.8) + abs(y - 0.2) -
                    12)
    simplex -= 2 * (abs(2 * x - 11) + abs(2 * x - 1) + abs(2 * y - 11) +
                    abs(2 * y - 1) - 20)
Exemple #35
0
class World(object):
    def __init__(self, name):
        # Batch 是用于批处理渲染的顶点列表的集合
        self.batch3d = pyglet.graphics.Batch()
        # 透明方块
        self.batch3d_transparent = pyglet.graphics.Batch()
        # 为了分开绘制3D物体和2D的 HUD, 我们需要两个 Batch
        self.batch2d = pyglet.graphics.Batch()
        # 存档名
        self.name = name
        # 种子
        self.seed = archiver.load_info(name)['seed']
        # Simplex 噪声函数
        self.simplex = OpenSimplex(seed=self.seed)
        # world 存储着世界上所有的方块
        self.world = {}
        # 类似于 world, 但它只存储要显示的方块
        self.shown = {}
        self._shown = {}
        # 记录玩家改变的方块
        self.change = {}
        self.sectors = {}
        self.queue = deque()
        # 初始化是否完成
        self.is_init = True

    def init_world(self):
        # 放置所有方块以初始化世界, 非常耗时
        get_game().loading.draw()
        if archiver.load_info(self.name)['type'] == 'flat':
            self.init_flat_world()
        else:
            self.init_random_world()
        archiver.load_block(self.name, self.add_block, self.remove_block)
        self.is_init = False

    def init_flat_world(self):
        # 生成平坦世界
        for x in range(-MAX_SIZE, MAX_SIZE + 1):
            for z in range(-MAX_SIZE, MAX_SIZE + 1):
                self.add_block((x, 0, z), 'bedrock', record=False)
        for x in range(-MAX_SIZE, MAX_SIZE + 1):
            for y in range(1, 6):
                for z in range(-MAX_SIZE, MAX_SIZE + 1):
                    if y == 5:
                        self.add_block((x, y, z), 'grass', record=False)
                    else:
                        self.add_block((x, y, z), 'dirt', record=False)

    def init_random_world(self):
        # 生成随机世界
        for x in range(-MAX_SIZE, MAX_SIZE + 1):
            for z in range(-MAX_SIZE, MAX_SIZE + 1):
                self.add_block((x, 0, z), 'bedrock', record=False)
        for x in range(-MAX_SIZE, MAX_SIZE + 1):
            for z in range(-MAX_SIZE, MAX_SIZE + 1):
                h = int(
                    self.simplex.noise2d(x=x / 20, y=z / 20) * 5 + SEA_LEVEL)
                for y in range(1, h):
                    self.add_block((x, y, z), 'dirt', record=False)
                else:
                    self.add_block((x, h, z), 'grass', record=False)

    def hit_test(self, position, vector, max_distance=8):
        """
        从当前位置开始视线搜索, 如果有任何方块与之相交, 返回之.
        如果没有找到, 返回 (None, None)

        :param: position 长度为3的元组, 当前位置
        :param: vector 长度为3的元组, 视线向量
        :param: max_distance 在多少方块的范围内搜索
        """
        m = 8
        x, y, z = position
        dx, dy, dz = vector
        previous = None
        for _ in range(max_distance * m):
            key = normalize((x, y, z))
            if key != previous and key in self.world:
                return key, previous
            previous = key
            x, y, z = x + dx / m, y + dy / m, z + dz / m
        else:
            return None, None

    def exposed(self, position):
        # 如果 position 所有的六个面旁边都有方块, 返回 False. 否则返回 True
        x, y, z = position
        for dx, dy, dz in FACES:
            pos = (x + dx, y + dy, z + dz)
            if pos not in self.world:
                return True
        else:
            return False

    def add_block(self, position, block, immediate=True, record=True):
        """
        在 position 处添加一个方块

        :param: pssition 长度为3的元组, 要添加方块的位置
        :param: block 方块
        :param: immediate 是否立即绘制方块
        :param: record 是否记录方块更改(在生成地形时不记录)
        """
        if position in self.world:
            self.remove_block(position, immediate, record=False)
        if -64 <= position[1] < 512:
            # 建筑限制为-64格以上, 512格以下
            if record == True:
                self.change[pos2str(position)] = block
            if block in blocks:
                self.world[position] = blocks[block]
                self.world[position].on_build(get_game(), position)
            else:
                # 将不存在的方块替换为 missing
                self.world[position] = blocks['missing']
            self.sectors.setdefault(sectorize(position), []).append(position)
            if self.exposed(position):
                self.show_block(position)
            if not self.world[position].transparent:
                self.check_neighbors(position)
        else:
            if position[1] >= 256:
                get_game().dialogue.add_dialogue(
                    get_lang('game.text.build_out_of_world')[0] % 512)
            else:
                get_game().dialogue.add_dialogue(
                    get_lang('game.text.build_out_of_world')[1])

    def remove_block(self, position, immediate=True, record=True):
        """
        在 position 处移除一个方块

        :param: position 长度为3的元组, 要移除方块的位置
        :param: immediate 是否要从画布上立即移除方块
        :param: record 是否记录方块更改(在 add_block 破坏后放置时不记录)
        """
        if position in self.world:
            # 不加这个坐标是否存在于世界中的判断有极大概率会抛出异常
            self.world[position].on_destroy(get_game(), position)
            del self.world[position]
            if record:
                self.change[pos2str(position)] = 'air'
            self.sectors[sectorize(position)].remove(position)
            if position in self.shown:
                self.hide_block(position)
            self.check_neighbors(position)

    def get(self, position):
        return self.world.get(position, None)

    def check_neighbors(self, position):
        """
        检查 position 周围所有的方块, 确保它们的状态是最新的.
        这意味着将隐藏不可见的方块, 并显示可见的方块.
        通常在添加或删除方块时使用.
        """
        x, y, z = position
        for dx, dy, dz in FACES:
            key = (x + dx, y + dy, z + dz)
            if key not in self.world:
                continue
            if self.exposed(key):
                if key not in self.shown:
                    self.world[key].on_neighbor_change(self.world, key,
                                                       position)
                    self.show_block(key)
            else:
                if key in self.shown:
                    self.world[key].on_neighbor_change(self.world, key,
                                                       position)
                    self.hide_block(key)

    def show_block(self, position, immediate=True):
        """
        在 position 处显示方块, 这个方法假设方块在 add_block() 已经添加

        :param: position 长度为3的元组, 要显示方块的位置
        :param: immediate 是否立即显示方块
        """
        block = self.world[position]
        self.shown[position] = block
        if immediate:
            self._show_block(position, block)
        else:
            self._enqueue(self._show_block, position, block)

    def _show_block(self, position, block):
        """
        show_block() 方法的私有实现

        :param: position 长度为3的元组, 要显示方块的位置
        :param: block 方块
        """
        vertex_data = list(block.get_vertices(*position))
        texture_data = list(block.texture_data)
        color_data = None
        if hasattr(block, 'get_color'):
            _, y, _ = position
            if y <= 10:
                t = 0.8
            else:
                t = 0.8 - (y - 0.8) * 1 / 600
            h = 0.35
            color_data = block.get_color(t, h)
        count = len(texture_data) // 2
        batch = self.batch3d
        if block.transparent:
            batch = self.batch3d_transparent
        if color_data is None:
            self._shown[position] = batch.add(count, GL_QUADS, block.group,
                                              ('v3f/static', vertex_data),
                                              ('t2f/static', texture_data))
        else:
            self._shown[position] = batch.add(count, GL_QUADS, block.group,
                                              ('v3f/static', vertex_data),
                                              ('t2f/static', texture_data),
                                              ('c3f/static', color_data))

    def hide_block(self, position, immediate=True):
        """
        隐藏在 position 处的方块, 它不移除方块

        :param: position 长度为3的元组, 要隐藏方块的位置
        :param: immediate 是否立即隐藏方块
        """
        self.shown.pop(position)
        if immediate:
            self._hide_block(position)
        else:
            self._enqueue(self._hide_block, position)

    def _hide_block(self, position):
        # hide_block() 方法的私有实现
        self._shown.pop(position).delete()

    def show_sector(self, sector):
        # 确保该区域中的方块都会被绘制
        for position in self.sectors.get(sector, []):
            if position not in self.shown and self.exposed(position):
                self.show_block(position, False)

    def hide_sector(self, sector):
        # 隐藏区域
        for position in self.sectors.get(sector, []):
            if position in self.shown:
                self.hide_block(position, False)

    def change_chunk(self, before, after):
        """
        改变玩家所在区域

        :param: before 之前的区域
        :param: after 现在的区域
        """
        before_set = set()
        after_set = set()
        pad = 4
        for dx in range(-pad, pad + 1):
            for dy in [0]:
                for dz in range(-pad, pad + 1):
                    if dx**2 + dy**2 + dz**2 > (pad + 1)**2:
                        continue
                    if before:
                        x, y, z = before
                        before_set.add((x + dx, y + dy, z + dz))
                    if after:
                        x, y, z = after
                        after_set.add((x + dx, y + dy, z + dz))
        else:
            show = after_set - before_set
            hide = before_set - after_set
            for sector in show:
                self.show_sector(sector)
            for sector in hide:
                self.hide_sector(sector)

    def _enqueue(self, func, *args):
        # 把 func 添加到内部的队列
        self.queue.append((func, args))

    def _dequeue(self):
        # 从内部队列顶部弹出函数并调用之
        func, args = self.queue.popleft()
        func(*args)

    def process_queue(self):
        # 处理事件
        if not self.is_init:
            start = time.perf_counter()
            while self.queue and time.perf_counter(
            ) - start < 1.0 / TICKS_PER_SEC:
                self._dequeue()

    def process_entire_queue(self):
        # 处理所有事件
        while self.queue:
            self._dequeue()

    def draw(self):
        self.batch3d.draw()
        self.batch3d_transparent.draw()