Created
January 5, 2013 17:42
-
-
Save anonymous/4462684 to your computer and use it in GitHub Desktop.
Simple Terrain Generator and 3D Plotter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import Image | |
import ImageDraw | |
import random | |
import math | |
import pyglet | |
import pyglet.gl as gl | |
w = 257 | |
h = 257 | |
randomness = 1.99 | |
data = [[0 for x in range (w)] for y in range(h)] | |
def fill_rect(data, bx, by, w, tl, tr, bl, br): | |
t = (tl + tr) // 2 | |
l = (tl + bl) // 2 | |
b = (bl + br) // 2 | |
r = (tr + br) // 2 | |
c = min(255, math.trunc(((random.random() * 2 - 1) * w * randomness + (tl + tr + bl + br)) // 4)) | |
w2 = w // 2 | |
data[bx][by + w2] = t | |
data[bx + w2][by] = l | |
data[bx + w2][by + w2] = c | |
data[bx + w][by + w2] = r | |
data[bx + w2][by + w] = b | |
# recursion, only if there's space left to fill | |
if (w > 1): | |
fill_rect(data, bx, by, w2, tl, t, l, c) | |
fill_rect(data, bx + w2, by, w2, t, tr, c, r) | |
fill_rect(data, bx, by + w2, w2, l, c, bl, b) | |
fill_rect(data, bx + w2, by + w2, w2, c, r, b, br) | |
# init grid with random heights | |
data[0][0] = random.randint(0, 255) | |
data[w - 1][0] = random.randint(0, 255) | |
data[0][h - 1] = random.randint(0, 255) | |
data[w - 1][h - 1] = random.randint(0, 255) | |
fill_rect(data, 0, 0, w - 1, data[0][0], data[w - 1][0], data[0][h - 1], data[w - 1][h - 1]) | |
window = pyglet.window.Window(resizable=True) | |
gl.glEnable(gl.GL_DEPTH_TEST) | |
@window.event | |
def on_draw(): | |
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) | |
gl.glLoadIdentity() | |
gl.glColor3f(0.0, 0.5, 0.0) | |
for x in range(w - 1): | |
gl.glBegin(gl.GL_QUAD_STRIP) | |
for y in range(h - 1): | |
gl.glVertex3f((x - 128) / 128., (y - 128) / 128., -data[x][y] / 256.) | |
gl.glVertex3f((x - 128) / 128., (y - 127) / 128., -data[x][y + 1] / 256.) | |
gl.glVertex3f((x - 127) / 128., (y - 128) / 128., -data[x + 1][y] / 256.) | |
gl.glVertex3f((x - 127) / 128., (y - 127) / 128., -data[x + 1][y + 1] / 256.) | |
gl.glEnd() | |
return pyglet.event.EVENT_HANDLED | |
@window.event | |
def on_resize(width, height): | |
gl.glViewport(0, 0, width, height) | |
gl.glMatrixMode(gl.GL_PROJECTION) | |
gl.glLoadIdentity() | |
gl.gluPerspective(45.0, width / float(height), 0.1, 100.0) | |
gl.glMatrixMode(gl.GL_MODELVIEW) | |
gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE); | |
return pyglet.event.EVENT_HANDLED | |
@window.event | |
def on_key_release(symbol, modifiers): | |
if symbol == pyglet.window.key.Q: | |
pyglet.app.exit() | |
pyglet.app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment