From fead577efd1dbb08880f915baaec9717c508e615 Mon Sep 17 00:00:00 2001 From: David Sowder Date: Sun, 11 Mar 2012 16:05:50 -0500 Subject: [PATCH 1/8] pull from pyflakes branch: unravel/mangle imports --- frustum.py | 37 +-- leveleditor.py | 653 ++++++++++++++++++++++----------------------- mcedit.py | 224 ++++++++-------- mceutils.py | 53 ++-- mcplatform.py | 17 +- renderer.py | 699 ++++++++++++++++++++++++------------------------- 6 files changed, 828 insertions(+), 855 deletions(-) diff --git a/frustum.py b/frustum.py index 3d27ce5..ef58b98 100644 --- a/frustum.py +++ b/frustum.py @@ -9,9 +9,10 @@ Based on code from: http://www.markmorley.com/opengl/frustumculling.html """ -from OpenGL.GL import * -from numpy import * -import logging + +import logging +import numpy +import OpenGL.GL context_log = logging.getLogger() @@ -30,9 +31,9 @@ def viewingMatrix(projection=None, model=None): matrix, the function will raise a RuntimeError """ if projection is None: - projection = glGetDoublev(GL_PROJECTION_MATRIX) + projection = OpenGL.GL.glGetDoublev(OpenGL.GL.GL_PROJECTION_MATRIX) if model is None: - model = glGetDoublev(GL_MODELVIEW_MATRIX) + model = OpenGL.GL.glGetDoublev(OpenGL.GL.GL_MODELVIEW_MATRIX) # hmm, this will likely fail on 64-bit platforms :( if projection is None or model is None: context_log.warn( @@ -44,20 +45,20 @@ def viewingMatrix(projection=None, model=None): if model: return model else: - return identity(4, 'd') - if allclose(projection, -1.79769313e+308): + return numpy.identity(4, 'd') + if numpy.allclose(projection, -1.79769313e+308): context_log.warn( """Attempt to retrieve projection matrix when uninitialised %s, model=%s""", projection, model, ) return model - if allclose(model, -1.79769313e+308): + if numpy.allclose(model, -1.79769313e+308): context_log.warn( """Attempt to retrieve model-view matrix when uninitialised %s, projection=%s""", model, projection, ) return projection - return dot(model, projection) + return numpy.dot(model, projection) class Frustum (object): @@ -84,15 +85,15 @@ def visible(self, points, radius): frustcullaccel C extension module) """ - distances = sum(self.planes[newaxis, :, :] * points[:, newaxis, :], -1) + distances = sum(self.planes[OpenGL.GL.newaxis, :, :] * points[:, OpenGL.GL.newaxis, :], -1) return ~any(distances < -radius, -1) def visible1(self, point, radius): - #return self.visible(array(point[newaxis, :]), radius) + #return self.visible(array(point[OpenGL.GL.newaxis, :]), radius) distance = sum(self.planes * point, -1) vis = ~any(distance < -radius) - #assert vis == self.visible(array(point)[newaxis, :], radius) + #assert vis == self.visible(array(point)[OpenGL.GL.newaxis, :], radius) return vis @@ -113,8 +114,8 @@ def fromViewingMatrix(cls, matrix=None, normalize=1): """ if matrix is None: matrix = viewingMatrix() - clip = ravel(matrix) - frustum = zeros((6, 4), 'd') + clip = numpy.ravel(matrix) + frustum = numpy.zeros((6, 4), 'd') # right frustum[0][0] = clip[3] - clip[0] frustum[0][1] = clip[7] - clip[4] @@ -155,10 +156,10 @@ def fromViewingMatrix(cls, matrix=None, normalize=1): @classmethod def normalize(cls, frustum): """Normalize clipping plane equations""" - magnitude = sqrt(frustum[:, 0] * frustum[:, 0] + frustum[:, 1] * frustum[:, 1] + frustum[:, 2] * frustum[:, 2]) + magnitude = numpy.sqrt(frustum[:, 0] * frustum[:, 0] + frustum[:, 1] * frustum[:, 1] + frustum[:, 2] * frustum[:, 2]) # eliminate any planes which have 0-length vectors, # those planes can't be used for excluding anything anyway... - frustum = compress(magnitude, frustum, 0) - magnitude = compress(magnitude, magnitude, 0) - magnitude = reshape(magnitude.astype('d'), (len(frustum), 1)) + frustum = numpy.compress(magnitude, frustum, 0) + magnitude = numpy.compress(magnitude, magnitude, 0) + magnitude = numpy.reshape(magnitude.astype('d'), (len(frustum), 1)) return frustum / magnitude diff --git a/leveleditor.py b/leveleditor.py index 8b06f3a..653e87d 100644 --- a/leveleditor.py +++ b/leveleditor.py @@ -23,44 +23,47 @@ """ -from collections import defaultdict -import gc +from albow.controls import Label, SmallValueDisplay, ValueDisplay +from albow.dialogs import Dialog, QuickDialog, wrapped_label +from albow import alert, ask, AttrRef, Button, Column, get_font, Grid, input_text, IntField, Label, Menu, root, Row, TableColumn, TableView, TextField, TimeField, ValueButton, Widget +from albow.openglwidgets import GLOrtho, GLPerspective, GLViewport +from collections import defaultdict, deque +import config +import copy +import csv from datetime import datetime, timedelta +from depths import DepthOffset +import editortools +from editortools.chunk import GeneratorPanel +from editortools.toolbasics import Operation +import frustum +import functools +import gc +from glbackground import GLBackground, Panel +import glutils +from glutils import FramebufferTexture, gl, Texture import itertools import logging -from OpenGL.GL import * +from math import isnan +import mceutils +import mcplatform +from mcplatform import askSaveFile +import numpy +import OpenGL # from OpenGL.GLUT import glutBitmapCharacter, GLUT_BITMAP_HELVETICA_18 -import time - -from pygame import display, event, key -from pygame.locals import * -from numpy import * - -from albow import * -from albow.dialogs import Dialog, wrapped_label, QuickDialog -from albow.openglwidgets import GLViewport, GLPerspective -from mceutils import * -from glutils import gl, Texture, FramebufferTexture -import glutils -# Label = GLLabel - -import config -from pymclevel import * -from glbackground import * -import editortools -from renderer import MCRenderer, PreviewRenderer -from depths import DepthOffset +import os +from os.path import dirname, isdir import platform - -import frustum -from collections import deque -from editortools.toolbasics import Operation +from pygame import display, event, key, KMOD_ALT, KMOD_CTRL, KMOD_LALT, KMOD_META, KMOD_RALT, KMOD_SHIFT, mouse, MOUSEMOTION +import pymclevel from pymclevel.infiniteworld import alphanum_key -import csv -from mcplatform import askSaveFile -from editortools.chunk import GeneratorPanel -from os.path import isdir, dirname +import release import renderer +from renderer import MCRenderer, PreviewRenderer +import time +import traceback + +# Label = GLLabel Settings = config.Settings("Settings") Settings.flyMode = Settings("Fly Mode", False) @@ -171,7 +174,7 @@ def __init__(self, editor): if cmd == "Cmd": hotkeys[-1] = ("Cmd-Q", hotkeys[-1][1], hotkeys[-1][2]) - buttons = HotkeyColumn(hotkeys, keysColumn, buttonsColumn) + buttons = mceutils.HotkeyColumn(hotkeys, keysColumn, buttonsColumn) # buttons.buttons[-1].ref = @@ -195,7 +198,7 @@ def key_down(self, evt): def unproject(x, y, z): try: - return GLU.gluUnProject(x, y, z) + return OpenGL.GLU.gluUnProject(x, y, z) except ValueError: # projection failed return 0, 0, 0 @@ -269,10 +272,10 @@ def pitch(self, val): def updateFov(self, val=None): hfov = self.fovSetting - fov = degrees(2.0 * arctan(self.size[0] / self.size[1] * tan(radians(hfov) * 0.5))) + fov = numpy.degrees(2.0 * numpy.arctan(self.size[0] / self.size[1] * numpy.tan(numpy.radians(hfov) * 0.5))) self.fov = fov - self.tang = tan(radians(fov)) + self.tang = numpy.tan(numpy.radians(fov)) def stopMoving(self): self.velocity = [0, 0, 0] @@ -334,9 +337,9 @@ def tickCamera(self, frameStartTime, inputs, inSpace): velocity = self.velocity # xxx learn to use matrix/vector libs i = inputs - yaw = radians(self.yaw) - cosyaw = -cos(yaw) - sinyaw = sin(yaw) + yaw = numpy.radians(self.yaw) + cosyaw = -numpy.cos(yaw) + sinyaw = numpy.sin(yaw) if alignMovementToAxes: cosyaw = int(cosyaw * 1.4) sinyaw = int(sinyaw * 1.4) @@ -344,7 +347,7 @@ def tickCamera(self, frameStartTime, inputs, inSpace): dy = int(dy * 1.6) dz = int(dz * 1.4) - directedInputs = normalize(( + directedInputs = mceutils.normalize(( i[0] * cosyaw + i[2] * dx, i[1] + i[2] * dy, i[2] * dz - i[0] * sinyaw, @@ -355,7 +358,7 @@ def tickCamera(self, frameStartTime, inputs, inSpace): # cameraImpulse = map(lambda x: x*impulse_factor, directedInputs) newVelocity = map(lambda a, b: a + b, velocity, cameraAccel) - velocityDir, speed = normalize_size(newVelocity) + velocityDir, speed = mceutils.normalize_size(newVelocity) # apply drag if speed: @@ -398,15 +401,13 @@ def tickCamera(self, frameStartTime, inputs, inSpace): def setModelview(self): pos = self.cameraPosition - look = array(self.cameraPosition) + look = numpy.array(self.cameraPosition) look += self.cameraVector up = (0, 1, 0) - GLU.gluLookAt(pos[0], pos[1], pos[2], + OpenGL.GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) - from math import isnan - def _cameraVector(self): return self._anglesToVector(self.yaw, self.pitch) @@ -417,9 +418,9 @@ def nanzero(x): else: return x - dx = -sin(radians(yaw)) * cos(radians(pitch)) - dy = -sin(radians(pitch)) - dz = cos(radians(yaw)) * cos(radians(pitch)) + dx = -numpy.sin(numpy.radians(yaw)) * numpy.cos(numpy.radians(pitch)) + dy = -numpy.sin(numpy.radians(pitch)) + dz = numpy.cos(numpy.radians(yaw)) * numpy.cos(numpy.radians(pitch)) return map(nanzero, [dx, dy, dz]) def updateMouseVector(self): @@ -437,8 +438,8 @@ def _mouseVector(self): y = self.get_root().height - y point1 = unproject(x, y, 0.0) point2 = unproject(x, y, 1.0) - v = array(point2) - point1 - v = normalize(v) + v = numpy.array(point2) - point1 + v = mceutils.normalize(v) return v def _blockUnderCursor(self, center=False): @@ -448,9 +449,9 @@ def _blockUnderCursor(self, center=False): """ try: if Settings.doubleBuffer.get(): - glReadBuffer(GL_BACK) + OpenGL.GL.glReadBuffer(OpenGL.GL.GL_BACK) else: - glReadBuffer(GL_FRONT) + OpenGL.GL.glReadBuffer(OpenGL.GL.GL_FRONT) except Exception, e: print "Exception during glReadBuffer: {0!r}".format(e) ws = self.get_root().size @@ -467,7 +468,7 @@ def _blockUnderCursor(self, center=False): y = ws[1] - y try: - pixel = glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT) + pixel = OpenGL.GL.glReadPixels(x, y, 1, 1, OpenGL.GL.GL_DEPTH_COMPONENT, OpenGL.GL.GL_FLOAT) newpoint = unproject(x, y, pixel[0]) except Exception, e: # print e @@ -500,7 +501,7 @@ def findBlockFaceUnderCursor(self, projectedPoint): d = [0, 0, 0] try: - intProjectedPoint = map(int, map(floor, projectedPoint)) + intProjectedPoint = map(int, map(numpy.floor, projectedPoint)) except ValueError: return None # catch NaNs intProjectedPoint[1] = max(0, intProjectedPoint[1]) @@ -524,20 +525,20 @@ def findBlockFaceUnderCursor(self, projectedPoint): try: block = self.editor.level.blockAt(*intProjectedPoint) - except ChunkNotPresent: + except pymclevel.ChunkNotPresent: return intProjectedPoint, d - if block == alphaMaterials.SnowLayer.ID: + if block == pymclevel.alphaMaterials.SnowLayer.ID: potentialOffsets.append((0, 1, 0)) else: # discard any faces that aren't likely to be exposed - for face, offsets in faceDirections: + for face, offsets in pymclevel.faceDirections: point = map(lambda a, b: a + b, intProjectedPoint, offsets) try: neighborBlock = self.editor.level.blockAt(*point) if block != neighborBlock: potentialOffsets.append(offsets) - except ChunkNotPresent: + except pymclevel.ChunkNotPresent: pass # check each component of the face vector to see if that face is exposed @@ -596,21 +597,21 @@ def toggleMouseLook(self): else: self.mouseLookOff() - mobs = entity.Entity.monsters + ["[Custom]"] + mobs = pymclevel.Entity.monsters + ["[Custom]"] - @alertException + @mceutils.alertException def editMonsterSpawner(self, point): mobs = self.mobs tileEntity = self.editor.level.tileEntityAt(*point) if not tileEntity: - tileEntity = TAG_Compound() - tileEntity["id"] = TAG_String("MobSpawner") - tileEntity["x"] = TAG_Int(point[0]) - tileEntity["y"] = TAG_Int(point[1]) - tileEntity["z"] = TAG_Int(point[2]) - tileEntity["Delay"] = TAG_Short(120) - tileEntity["EntityId"] = TAG_String(mobs[0]) + tileEntity = pymclevel.TAG_Compound() + tileEntity["id"] = pymclevel.TAG_String("MobSpawner") + tileEntity["x"] = pymclevel.TAG_Int(point[0]) + tileEntity["y"] = pymclevel.TAG_Int(point[1]) + tileEntity["z"] = pymclevel.TAG_Int(point[2]) + tileEntity["Delay"] = pymclevel.TAG_Short(120) + tileEntity["EntityId"] = pymclevel.TAG_String(mobs[0]) self.editor.level.addTileEntity(tileEntity) self.editor.addUnsavedEdit() @@ -661,9 +662,9 @@ def selectedMob(): panel.shrink_wrap() panel.present() - tileEntity["EntityId"] = TAG_String(selectedMob()) + tileEntity["EntityId"] = pymclevel.TAG_String(selectedMob()) - @alertException + @mceutils.alertException def editSign(self, point): block = self.editor.level.blockAt(*point) @@ -672,13 +673,13 @@ def editSign(self, point): linekeys = ["Text" + str(i) for i in range(1, 5)] if not tileEntity: - tileEntity = TAG_Compound() - tileEntity["id"] = TAG_String("Sign") - tileEntity["x"] = TAG_Int(point[0]) - tileEntity["y"] = TAG_Int(point[1]) - tileEntity["z"] = TAG_Int(point[2]) + tileEntity = pymclevel.TAG_Compound() + tileEntity["id"] = pymclevel.TAG_String("Sign") + tileEntity["x"] = pymclevel.TAG_Int(point[0]) + tileEntity["y"] = pymclevel.TAG_Int(point[1]) + tileEntity["z"] = pymclevel.TAG_Int(point[2]) for l in linekeys: - tileEntity[l] = TAG_String("") + tileEntity[l] = pymclevel.TAG_String("") self.editor.level.addTileEntity(tileEntity) @@ -713,7 +714,7 @@ def menu_picked(index): currentField.text += c # xxx view hierarchy currentField.insertion_point = len(currentField.text) - colorMenu = MenuButton("Color Code...", colors, menu_picked=menu_picked) + colorMenu = mceutils.MenuButton("Color Code...", colors, menu_picked=menu_picked) column = [Label("Edit Sign")] + lineFields + [colorMenu, Button("OK", action=panel.dismiss)] @@ -725,19 +726,19 @@ def menu_picked(index): for l, f in zip(linekeys, lineFields): tileEntity[l].value = f.value[:15] - @alertException + @mceutils.alertException def editContainer(self, point, containerID): tileEntityTag = self.editor.level.tileEntityAt(*point) if tileEntityTag is None: - tileEntityTag = TileEntity.Create(containerID) - TileEntity.setpos(tileEntityTag, point) + tileEntityTag = pymclevel.TileEntity.Create(containerID) + pymclevel.TileEntity.setpos(tileEntityTag, point) self.editor.level.addTileEntity(tileEntityTag) if tileEntityTag["id"].value != containerID: print "Not a {0}! \n".format(containerID), tileEntityTag return - backupEntityTag = deepcopy(tileEntityTag) + backupEntityTag = copy.deepcopy(tileEntityTag) def itemProp(key): # xxx do validation here @@ -759,10 +760,10 @@ class ChestWidget(Widget): id = itemProp("id") Damage = itemProp("Damage") Count = itemProp("Count") - itemLimit = TileEntity.maxItems.get(containerID, 255) + itemLimit = pymclevel.TileEntity.maxItems.get(containerID, 255) def slotFormat(slot): - slotNames = entity.TileEntity.slotNames.get(containerID) + slotNames = pymclevel.TileEntity.slotNames.get(containerID) if slotNames: return slotNames.get(slot, slot) return slot @@ -779,8 +780,8 @@ def slotFormat(slot): def itemName(id, damage): try: - return items.items.findItem(id, damage).name - except items.ItemNotFound: + return pymclevel.items.items.findItem(id, damage).name + except pymclevel.items.ItemNotFound: return "Unknown Item" def getRowData(i): @@ -799,10 +800,10 @@ def selectTableRow(i, evt): chestItemTable.click_row = selectTableRow fieldRow = ( - # IntInputRow("Slot: ", ref=AttrRef(chestWidget, 'Slot'), min= -128, max=127), - IntInputRow("ID: ", ref=AttrRef(chestWidget, 'id'), min=0, max=32767), - IntInputRow("DMG: ", ref=AttrRef(chestWidget, 'Damage'), min=-32768, max=32767), - IntInputRow("Count: ", ref=AttrRef(chestWidget, 'Count'), min=-128, max=127), + # mceutils.IntInputRow("Slot: ", ref=AttrRef(chestWidget, 'Slot'), min= -128, max=127), + mceutils.IntInputRow("ID: ", ref=AttrRef(chestWidget, 'id'), min=0, max=32767), + mceutils.IntInputRow("DMG: ", ref=AttrRef(chestWidget, 'Damage'), min=-32768, max=32767), + mceutils.IntInputRow("Count: ", ref=AttrRef(chestWidget, 'Count'), min=-128, max=127), ) def deleteFromWorld(): @@ -811,8 +812,8 @@ def deleteFromWorld(): id = item["id"].value Damage = item["Damage"].value - deleteSameDamage = CheckBoxLabel("Only delete items with the same damage value") - deleteBlocksToo = CheckBoxLabel("Also delete blocks placed in the world") + deleteSameDamage = mceutils.CheckBoxLabel("Only delete items with the same damage value") + deleteBlocksToo = mceutils.CheckBoxLabel("Also delete blocks placed in the world") if id not in (8, 9, 10, 11): # fluid blocks deleteBlocksToo.value = True @@ -875,7 +876,7 @@ def matches_itementity(e): progressInfo = "Deleting the item {0} from the entire world ({1} chunks)".format(itemName(chestWidget.id, 0), self.editor.level.chunkCount) - showProgress(progressInfo, deleteItemsIter(), cancel=True) + mceutils.showProgress(progressInfo, deleteItemsIter(), cancel=True) self.editor.addUnsavedEdit() chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag['Items']) - 1) @@ -900,11 +901,11 @@ def addItem(): slot += 1 if slot >= chestWidget.itemLimit: return - item = TAG_Compound() - item["id"] = TAG_Short(0) - item["Damage"] = TAG_Short(0) - item["Slot"] = TAG_Byte(slot) - item["Count"] = TAG_Byte(0) + item = pymclevel.TAG_Compound() + item["id"] = pymclevel.TAG_Short(0) + item["Damage"] = pymclevel.TAG_Short(0) + item["Slot"] = pymclevel.TAG_Byte(slot) + item["Count"] = pymclevel.TAG_Byte(0) tileEntityTag['Items'].append(item) addItemButton = Button("Add Item", action=addItem, enable=addEnable) @@ -927,7 +928,7 @@ def perform(self, recordUndo=True): def undo(self): level.addTileEntity(backupEntityTag) - return BoundingBox(TileEntity.pos(tileEntityTag), (1, 1, 1)) + return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1)) if chestWidget.dirty: op = ChestEditOperation() @@ -959,18 +960,18 @@ def leftClickDown(self, evt): if evt.num_clicks == 2: def distance2(p1, p2): - return sum(map(lambda a, b: (a - b) ** 2, p1, p2)) + return numpy.sum(map(lambda a, b: (a - b) ** 2, p1, p2)) point, face = self.blockFaceUnderCursor if point is not None: - point = map(lambda x: int(floor(x)), point) + point = map(lambda x: int(numpy.floor(x)), point) if self.editor.currentTool is self.editor.selectionTool: block = self.editor.level.blockAt(*point) if distance2(point, self.cameraPosition) > 4: blockEditors = { - alphaMaterials.MonsterSpawner.ID: self.editMonsterSpawner, - alphaMaterials.Sign.ID: self.editSign, - alphaMaterials.WallSign.ID: self.editSign, + pymclevel.alphaMaterials.MonsterSpawner.ID: self.editMonsterSpawner, + pymclevel.alphaMaterials.Sign.ID: self.editSign, + pymclevel.alphaMaterials.WallSign.ID: self.editSign, } edit = blockEditors.get(block) if edit: @@ -983,7 +984,7 @@ def distance2(p1, p2): if te and "Items" in te and "id" in te: self.editor.endSelection() self.editContainer(point, te["id"].value) - except ChunkNotPresent: + except pymclevel.ChunkNotPresent: pass def leftClickUp(self, evt): @@ -1052,7 +1053,7 @@ def sensitivityAdjust(d): def tooltipText(self): return self.editor.currentTool.worldTooltipText - floorQuad = array(((-4000.0, 0.0, -4000.0), + floorQuad = numpy.array(((-4000.0, 0.0, -4000.0), (-4000.0, 0.0, 4000.0), (4000.0, 0.0, 4000.0), (4000.0, 0.0, -4000.0), @@ -1065,7 +1066,7 @@ def updateFloorQuad(self): (4000.0, 0.0, -4000.0), ) - floorQuad = array(floorQuad, dtype='float32') + floorQuad = numpy.array(floorQuad, dtype='float32') if self.editor.renderer.inSpace(): floorQuad *= 8.0 floorQuad += (self.cameraPosition[0], 0.0, self.cameraPosition[2]) @@ -1086,32 +1087,32 @@ def _drawCeiling(self): lines.append((minx, 0, z)) lines.append((maxx, 0, z)) - glColor(0.3, 0.7, 0.9) - glVertexPointer(3, GL_FLOAT, 0, numpy.array(lines, dtype='float32')) + OpenGL.GL.glColor(0.3, 0.7, 0.9) + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(lines, dtype='float32')) - glEnable(GL_DEPTH_TEST) - glDepthMask(False) - glDrawArrays(GL_LINES, 0, len(lines)) - glDisable(GL_DEPTH_TEST) - glDepthMask(True) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + OpenGL.GL.glDepthMask(False) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_LINES, 0, len(lines)) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + OpenGL.GL.glDepthMask(True) def drawCeiling(self): - glMatrixMode(GL_MODELVIEW) - # glPushMatrix() + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) + # OpenGL.GL.glPushMatrix() x, y, z = self.cameraPosition x -= x % 16 z -= z % 16 y = self.editor.level.Height - glTranslate(x, y, z) + OpenGL.GL.glTranslate(x, y, z) self.ceilingList.call(self._drawCeiling) - glTranslate(-x, -y, -z) + OpenGL.GL.glTranslate(-x, -y, -z) _floorQuadList = None @property def floorQuadList(self): if not self._floorQuadList: - self._floorQuadList = DisplayList() + self._floorQuadList = glutils.DisplayList() return self._floorQuadList _ceilingList = None @@ -1119,7 +1120,7 @@ def floorQuadList(self): @property def ceilingList(self): if not self._ceilingList: - self._ceilingList = DisplayList() + self._ceilingList = glutils.DisplayList() return self._ceilingList @property @@ -1132,12 +1133,12 @@ def floorColor(self): # floorColor = (0.0, 0.0, 1.0, 0.1) def _drawFloorQuad(self): - glDepthMask(True) - glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) - glVertexPointer(3, GL_FLOAT, 0, self.floorQuad) - glColor(*self.floorColor) - with gl.glEnable(GL_BLEND, GL_DEPTH_TEST, GL_POLYGON_OFFSET_FILL): - glDrawArrays(GL_QUADS, 0, 4) + OpenGL.GL.glDepthMask(True) + OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, self.floorQuad) + OpenGL.GL.glColor(*self.floorColor) + with gl.glEnable(OpenGL.GL.GL_BLEND, OpenGL.GL.GL_DEPTH_TEST, OpenGL.GL.GL_POLYGON_OFFSET_FILL): + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) @property def drawSky(self): @@ -1155,20 +1156,20 @@ def drawSky(self, val): def drawSkyBackground(self): if self.skyList is None: - self.skyList = DisplayList() + self.skyList = glutils.DisplayList() self.skyList.call(self._drawSkyBackground) def _drawSkyBackground(self): - glMatrixMode(GL_MODELVIEW) - glPushMatrix() - glLoadIdentity() - glMatrixMode(GL_PROJECTION) - glPushMatrix() - glLoadIdentity() - glEnableClientState(GL_COLOR_ARRAY) - - quad = array([-1, -1, -1, 1, 1, 1, 1, -1], dtype='float32') - colors = array([0x48, 0x49, 0xBA, 0xff, + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) + OpenGL.GL.glPushMatrix() + OpenGL.GL.glLoadIdentity() + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) + OpenGL.GL.glPushMatrix() + OpenGL.GL.glLoadIdentity() + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) + + quad = numpy.array([-1, -1, -1, 1, 1, 1, 1, -1], dtype='float32') + colors = numpy.array([0x48, 0x49, 0xBA, 0xff, 0x8a, 0xaf, 0xff, 0xff, 0x8a, 0xaf, 0xff, 0xff, 0x48, 0x49, 0xBA, 0xff, ], dtype='uint8') @@ -1177,20 +1178,20 @@ def _drawSkyBackground(self): if alpha > 0.0: if alpha < 1.0: - glEnable(GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) - glVertexPointer(2, GL_FLOAT, 0, quad) - glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors) - glDrawArrays(GL_QUADS, 0, 4) + OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, quad) + OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, colors) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) if alpha < 1.0: - glDisable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) - glDisableClientState(GL_COLOR_ARRAY) - glMatrixMode(GL_PROJECTION) - glPopMatrix() - glMatrixMode(GL_MODELVIEW) - glPopMatrix() + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) + OpenGL.GL.glPopMatrix() + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) + OpenGL.GL.glPopMatrix() enableMouseLag = Settings.enableMouseLag.configProperty() @@ -1202,24 +1203,24 @@ def drawFog(self): def drawFog(self, val): self._drawFog = val - fogColor = array([0.6, 0.8, 1.0, 1.0], dtype='float32') - fogColorBlack = array([0.0, 0.0, 0.0, 1.0], dtype='float32') + fogColor = numpy.array([0.6, 0.8, 1.0, 1.0], dtype='float32') + fogColorBlack = numpy.array([0.0, 0.0, 0.0, 1.0], dtype='float32') def enableFog(self): - glEnable(GL_FOG) + OpenGL.GL.glEnable(OpenGL.GL.GL_FOG) if self.drawSky: - glFogfv(GL_FOG_COLOR, self.fogColor) + OpenGL.GL.glFogfv(OpenGL.GL.GL_FOG_COLOR, self.fogColor) else: - glFogfv(GL_FOG_COLOR, self.fogColorBlack) + OpenGL.GL.glFogfv(OpenGL.GL.GL_FOG_COLOR, self.fogColorBlack) - glFogf(GL_FOG_DENSITY, 0.002) + OpenGL.GL.glFogf(OpenGL.GL.GL_FOG_DENSITY, 0.002) def disableFog(self): - glDisable(GL_FOG) + OpenGL.GL.glDisable(OpenGL.GL.GL_FOG) def getCameraPoint(self): distance = self.editor.currentTool.cameraDistance - return [i for i in itertools.imap(lambda p, d: int(floor(p + d * distance)), + return [i for i in itertools.imap(lambda p, d: int(numpy.floor(p + d * distance)), self.cameraPosition, self.cameraVector)] @@ -1231,7 +1232,7 @@ def setup_projection(self): distance = 1.0 if self.editor.renderer.inSpace(): distance = 8.0 - GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) + OpenGL.GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) def setup_modelview(self): self.setModelview() @@ -1306,13 +1307,13 @@ def setup_projection(self): minx, maxx = - w, w miny, maxy = - h, h minz, maxz = -4000, 4000 - GL.glOrtho(minx, maxx, miny, maxy, minz, maxz) + OpenGL.GL.glOrtho(minx, maxx, miny, maxy, minz, maxz) def setup_modelview(self): x, y, z = self.cameraPosition - glRotate(90.0, 1.0, 0.0, 0.0) - glTranslate(-x, 0, -z) + OpenGL.GL.glRotate(90.0, 1.0, 0.0, 0.0) + OpenGL.GL.glTranslate(-x, 0, -z) def zoom(self, f): x, y, z = self.cameraPosition @@ -1354,7 +1355,7 @@ def rightClickUp(self, evt): def mouse_move(self, evt): pass - @alertException + @mceutils.alertException def mouse_drag(self, evt): if evt.buttons[2]: @@ -1444,7 +1445,7 @@ def __init__(self, mcedit): tooltipText="Memory used for vertexes") def dataSize(): - if not isinstance(self.level, MCInfdevOldLevel): + if not isinstance(self.level, pymclevel.MCInfdevOldLevel): try: return len(self.level.root_tag) except: @@ -1459,7 +1460,7 @@ def size(c): return len(c.compressedTag) return 0 - return sum(size(c) for c in chunks.itervalues()) + return numpy.sum(size(c) for c in chunks.itervalues()) mbldReadout = SmallValueDisplay(width=60, get_value=lambda: "MBd: %0.1f" % (dataSize() / 1000000.), @@ -1467,22 +1468,22 @@ def size(c): def showViewOptions(): col = [] - col.append(CheckBoxLabel("Entities", fg_color=(0xff, 0x22, 0x22), ref=Settings.drawEntities.propertyRef())) - col.append(CheckBoxLabel("Items", fg_color=(0x22, 0xff, 0x22), ref=Settings.drawItems.propertyRef())) - col.append(CheckBoxLabel("TileEntities", fg_color=(0xff, 0xff, 0x22), ref=Settings.drawTileEntities.propertyRef())) - col.append(CheckBoxLabel("TileTicks", ref=Settings.drawTileTicks.propertyRef())) - col.append(CheckBoxLabel("Unpopulated Chunks", fg_color=renderer.TerrainPopulatedRenderer.color, + col.append(mceutils.CheckBoxLabel("Entities", fg_color=(0xff, 0x22, 0x22), ref=Settings.drawEntities.propertyRef())) + col.append(mceutils.CheckBoxLabel("Items", fg_color=(0x22, 0xff, 0x22), ref=Settings.drawItems.propertyRef())) + col.append(mceutils.CheckBoxLabel("TileEntities", fg_color=(0xff, 0xff, 0x22), ref=Settings.drawTileEntities.propertyRef())) + col.append(mceutils.CheckBoxLabel("TileTicks", ref=Settings.drawTileTicks.propertyRef())) + col.append(mceutils.CheckBoxLabel("Unpopulated Chunks", fg_color=renderer.TerrainPopulatedRenderer.color, ref=Settings.drawUnpopulatedChunks.propertyRef())) - col.append(CheckBoxLabel("Sky", ref=Settings.drawSky.propertyRef())) - col.append(CheckBoxLabel("Fog", ref=Settings.drawFog.propertyRef())) - col.append(CheckBoxLabel("Ceiling", + col.append(mceutils.CheckBoxLabel("Sky", ref=Settings.drawSky.propertyRef())) + col.append(mceutils.CheckBoxLabel("Fog", ref=Settings.drawFog.propertyRef())) + col.append(mceutils.CheckBoxLabel("Ceiling", ref=Settings.showCeiling.propertyRef())) - col.append(CheckBoxLabel("Hidden Ores", + col.append(mceutils.CheckBoxLabel("Hidden Ores", ref=Settings.showHiddenOres.propertyRef())) - col.append(CheckBoxLabel("Chunk Redraw", fg_color=(0xff, 0x99, 0x99), + col.append(mceutils.CheckBoxLabel("Chunk Redraw", fg_color=(0xff, 0x99, 0x99), ref=Settings.showChunkRedraw.propertyRef())) col = Column(col, align="r") @@ -1648,7 +1649,7 @@ def createOneCopyPanel(sch): deleteButton = Button("Delete", action=lambda: (self.deleteCopiedSchematic(sch))) saveButton = Button("Save", action=lambda: (self.exportSchematic(sch))) sizeLabel = Label("{0} x {1} x {2}".format(sch.Length, sch.Width, sch.Height)) - if isinstance(sch, MCSchematic): + if isinstance(sch, pymclevel.MCSchematic): sch.compress() length = len(sch.compressedTag) else: @@ -1670,28 +1671,28 @@ def createOneCopyPanel(sch): panel.anchor = "whrt" return panel - @alertException + @mceutils.alertException def showAnalysis(self, schematic): self.analyzeBox(schematic, schematic.bounds) def analyzeBox(self, level, box): entityCounts = defaultdict(int) tileEntityCounts = defaultdict(int) - types = zeros(4096, dtype='uint32') + types = numpy.zeros(4096, dtype='uint32') def _analyzeBox(): i = 0 for (chunk, slices, point) in level.getChunkSlices(box): i += 1 yield i, box.chunkCount - blocks = array(chunk.Blocks[slices], dtype='uint16') - blocks |= (array(chunk.Data[slices], dtype='uint16') << 8) - b = bincount(blocks.ravel()) + blocks = numpy.array(chunk.Blocks[slices], dtype='uint16') + blocks |= (numpy.array(chunk.Data[slices], dtype='uint16') << 8) + b = numpy.bincount(blocks.ravel()) types[:b.shape[0]] += b for ent in chunk.getEntitiesInBox(box): if ent["id"].value == "Item": - v = items.items.findItem(ent["Item"]["id"].value, + v = pymclevel.items.items.findItem(ent["Item"]["id"].value, ent["Item"]["Damage"].value).name else: v = ent["id"].value @@ -1699,11 +1700,11 @@ def _analyzeBox(): for ent in chunk.getTileEntitiesInBox(box): tileEntityCounts[ent["id"].value] += 1 - with setWindowCaption("ANALYZING - "): - showProgress("Analyzing {0} blocks...".format(box.volume), _analyzeBox(), cancel=True) + with mceutils.setWindowCaption("ANALYZING - "): + mceutils.showProgress("Analyzing {0} blocks...".format(box.volume), _analyzeBox(), cancel=True) - entitySum = sum(entityCounts.values()) - tileEntitySum = sum(tileEntityCounts.values()) + entitySum = numpy.sum(entityCounts.values()) + tileEntitySum = numpy.sum(tileEntityCounts.values()) presentTypes = types.nonzero() blockCounts = sorted([(level.materials[t & 0xff, t >> 8], types[t]) for t in presentTypes[0]]) @@ -1833,20 +1834,20 @@ def reloadToolbar(self): longDistanceMode = Settings.longDistanceMode.configProperty() def genSixteenBlockTexture(self): - has12 = GL.glGetString(GL_VERSION) >= "1.2" + has12 = OpenGL.GL.glGetString(OpenGL.GL.GL_VERSION) >= "1.2" if has12: maxLevel = 2 - mode = GL.GL_LINEAR_MIPMAP_NEAREST + mode = OpenGL.GL.GL_LINEAR_MIPMAP_NEAREST else: maxLevel = 1 - mode = GL.GL_LINEAR + mode = OpenGL.GL.GL_LINEAR def makeSixteenBlockTex(): darkColor = (0x30, 0x30, 0x30, 0xff) lightColor = (0x80, 0x80, 0x80, 0xff) w, h, = 256, 256 - teximage = zeros((w, h, 4), dtype='uint8') + teximage = numpy.zeros((w, h, 4), dtype='uint8') teximage[:] = 0xff teximage[:, ::16] = lightColor teximage[::16, :] = lightColor @@ -1854,11 +1855,11 @@ def makeSixteenBlockTex(): teximage[-1:] = darkColor teximage[:, -1:] = darkColor teximage[:, :2] = darkColor - # GL.glTexParameter(GL.GL_TEXTURE_2D, - # GL.GL_TEXTURE_MIN_FILTER, - # GL.GL_NEAREST_MIPMAP_NEAREST), - GL.glTexParameter(GL.GL_TEXTURE_2D, - GL_TEXTURE_MAX_LEVEL, + # OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, + # OpenGL.GL.GL_TEXTURE_MIN_FILTER, + # OpenGL.GL.GL_NEAREST_MIPMAP_NEAREST), + OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, + OpenGL.GL.GL_TEXTURE_MAX_LEVEL, maxLevel - 1) for lev in range(maxLevel): @@ -1871,49 +1872,49 @@ def makeSixteenBlockTex(): teximage[:, -1:] = darkColor teximage[:, :2] = darkColor - GL.glTexImage2D(GL.GL_TEXTURE_2D, lev, GL.GL_RGBA8, + OpenGL.GL.glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, lev, OpenGL.GL.GL_RGBA8, w / step, h / step, 0, - GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, + OpenGL.GL.GL_RGBA, OpenGL.GL.GL_UNSIGNED_BYTE, teximage[::step, ::step].ravel()) return Texture(makeSixteenBlockTex, mode) def showProgress(self, *a, **kw): - return showProgress(*a, **kw) + return mceutils.showProgress(*a, **kw) def drawConstructionCube(self, box, color, texture=None): if texture == None: texture = self.sixteenBlockTex # textured cube faces - glEnable(GL_BLEND) - glEnable(GL_DEPTH_TEST) - glDepthMask(False) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + OpenGL.GL.glDepthMask(False) # edges within terrain - glDepthFunc(GL_GREATER) + OpenGL.GL.glDepthFunc(OpenGL.GL.GL_GREATER) try: - glColor(color[0], color[1], color[2], max(color[3], 0.35)) + OpenGL.GL.glColor(color[0], color[1], color[2], max(color[3], 0.35)) except IndexError: print color raise - glLineWidth(1.0) - drawCube(box, cubeType=GL_LINE_STRIP) + OpenGL.GL.glLineWidth(1.0) + mceutils.drawCube(box, cubeType=OpenGL.GL.GL_LINE_STRIP) # edges on or outside terrain - glDepthFunc(GL_LEQUAL) - glColor(color[0], color[1], color[2], max(color[3] * 2, 0.75)) - glLineWidth(2.0) - drawCube(box, cubeType=GL_LINE_STRIP) + OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LEQUAL) + OpenGL.GL.glColor(color[0], color[1], color[2], max(color[3] * 2, 0.75)) + OpenGL.GL.glLineWidth(2.0) + mceutils.drawCube(box, cubeType=OpenGL.GL.GL_LINE_STRIP) - glDepthFunc(GL_LESS) - glColor(color[0], color[1], color[2], color[3]) - glDepthFunc(GL_LEQUAL) - drawCube(box, texture=texture, selectionBox=True) - glDepthMask(True) + OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LESS) + OpenGL.GL.glColor(color[0], color[1], color[2], color[3]) + OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LEQUAL) + mceutils.drawCube(box, texture=texture, selectionBox=True) + OpenGL.GL.glDepthMask(True) - glDisable(GL_BLEND) - glDisable(GL_DEPTH_TEST) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) def loadFile(self, filename): if self.level and self.unsavedEdits > 0: @@ -1925,7 +1926,7 @@ def loadFile(self, filename): self.freezeStatus("Loading " + filename) try: - level = fromFile(filename) + level = pymclevel.fromFile(filename) except Exception, e: traceback.print_exc() alert(u"I don't know how to open {0}:\n\n{1!r}".format(filename, e)) @@ -1948,12 +1949,12 @@ def loadFile(self, filename): if pdim and pdim in level.dimensions: level = level.dimensions[pdim] - except (KeyError, PlayerNotFound): # TagNotFound + except (KeyError, pymclevel.PlayerNotFound): # TagNotFound # player tag not found, maybe try: self.currentViewport.cameraPosition = level.playerSpawnPosition() except KeyError: # TagNotFound - self.currentViewport.cameraPosition = array((0, level.Height * 0.75, 0)) + self.currentViewport.cameraPosition = numpy.array((0, level.Height * 0.75, 0)) self.mainViewport.yaw = -45. self.mainViewport.pitch = 0.0 @@ -1983,15 +1984,15 @@ def loadLevel(self, level): self.clearUnsavedEdits() [t.levelChanged() for t in self.toolbar.tools] - if isinstance(self.level, MCInfdevOldLevel): + if isinstance(self.level, pymclevel.MCInfdevOldLevel): if self.level.parentWorld: dimensions = self.level.parentWorld.dimensions else: dimensions = self.level.dimensions dimensionsMenu = [("Earth", "0")] - dimensionsMenu += [(MCAlphaDimension.dimensionNames.get(dimNo, "Dimension {0}".format(dimNo)), str(dimNo)) for dimNo in dimensions] - for dim, name in MCAlphaDimension.dimensionNames.iteritems(): + dimensionsMenu += [(pymclevel.MCAlphaDimension.dimensionNames.get(dimNo, "Dimension {0}".format(dimNo)), str(dimNo)) for dimNo in dimensions] + for dim, name in pymclevel.MCAlphaDimension.dimensionNames.iteritems(): if dim not in dimensions: dimensionsMenu.append((name, str(dim))) @@ -2017,7 +2018,7 @@ def presentMenu(): resp = ask("It looks like this level is completely empty! You'll have to create some chunks before you can get started.", responses=["Create Chunks", "Cancel"]) if resp == "Create Chunks": x, y, z = self.mainViewport.cameraPosition - box = BoundingBox((x - 128, 0, z - 128), (256, self.level.Height, 256)) + box = pymclevel.BoundingBox((x - 128, 0, z - 128), (256, self.level.Height, 256)) self.selectionTool.setSelection(box) self.toolbar.selectTool(8) self.toolbar.tools[8].createChunks() @@ -2028,7 +2029,7 @@ def removeNetherPanel(self): self.remove(self.netherPanel) self.netherPanel = None - @alertException + @mceutils.alertException def gotoEarth(self): assert self.level.parentWorld self.removeNetherPanel() @@ -2037,7 +2038,7 @@ def gotoEarth(self): x, y, z = self.mainViewport.cameraPosition self.mainViewport.cameraPosition = [x * 8, y, z * 8] - @alertException + @mceutils.alertException def gotoNether(self): self.removeNetherPanel() x, y, z = self.mainViewport.cameraPosition @@ -2070,7 +2071,7 @@ def initWindowCaption(self): title = title.encode('ascii', 'replace') display.set_caption(title) - @alertException + @mceutils.alertException def reload(self): filename = self.level.filename # self.discardAllChunks() @@ -2078,17 +2079,17 @@ def reload(self): self.loadFile(filename) - @alertException + @mceutils.alertException def saveFile(self): - with setWindowCaption("SAVING - "): - if isinstance(self.level, ChunkedLevelMixin): # xxx relight indev levels? + with mceutils.setWindowCaption("SAVING - "): + if isinstance(self.level, pymclevel.ChunkedLevelMixin): # xxx relight indev levels? level = self.level if level.parentWorld: level = level.parentWorld for level in itertools.chain(level.dimensions.itervalues(), [level]): - if "Canceled" == showProgress("Lighting chunks", level.generateLightsIter(), cancel=True): + if "Canceled" == mceutils.showProgress("Lighting chunks", level.generateLightsIter(), cancel=True): return if self.level == level: @@ -2316,7 +2317,7 @@ def generateStars(self): r = starDistance - randPoints = (random.random(size=starCount * 3)) * 2.0 * r + randPoints = (numpy.random.random(size=starCount * 3)) * 2.0 * r randPoints.shape = (starCount, 3) nearbyPoints = (randPoints[:, 0] < r) & (randPoints[:, 1] < r) & (randPoints[:, 2] < r) @@ -2327,23 +2328,23 @@ def generateStars(self): randPoints[::4, 2] = -randPoints[::4, 2] randPoints[1::4, 2] = -randPoints[1::4, 2] - randsizes = random.random(size=starCount) * 6 + 0.8 + randsizes = numpy.random.random(size=starCount) * 6 + 0.8 vertsPerStar = 4 - vertexBuffer = zeros((starCount, vertsPerStar, 3), dtype='float32') + vertexBuffer = numpy.zeros((starCount, vertsPerStar, 3), dtype='float32') def normvector(x): - return x / sqrt(sum(x * x, 1))[:, newaxis] + return x / numpy.sqrt(numpy.sum(x * x, 1))[:, numpy.newaxis] viewVector = normvector(randPoints) - rmod = random.random(size=starCount * 3) * 2.0 - 1.0 + rmod = numpy.random.random(size=starCount * 3) * 2.0 - 1.0 rmod.shape = (starCount, 3) referenceVector = viewVector + rmod - rightVector = normvector(cross(referenceVector, viewVector)) * randsizes[:, newaxis] # vector perpendicular to viewing line - upVector = normvector(cross(rightVector, viewVector)) * randsizes[:, newaxis] # vector perpendicular previous vector and viewing line + rightVector = normvector(numpy.cross(referenceVector, viewVector)) * randsizes[:, numpy.newaxis] # vector perpendicular to viewing line + upVector = normvector(numpy.cross(rightVector, viewVector)) * randsizes[:, numpy.newaxis] # vector perpendicular previous vector and viewing line p = randPoints p1 = p + (- upVector - rightVector) @@ -2365,10 +2366,10 @@ def drawStars(self): self.mainViewport.cameraPosition = map(lambda x: x / 128.0, pos) self.mainViewport.setModelview() - glColor(.5, .5, .5, 1.) + OpenGL.GL.glColor(.5, .5, .5, 1.) - glVertexPointer(3, GL_FLOAT, 0, self.starVertices) - glDrawArrays(GL_QUADS, 0, len(self.starVertices) / 3) + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, self.starVertices) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(self.starVertices) / 3) self.mainViewport.cameraPosition = pos self.mainViewport.setModelview() @@ -2519,7 +2520,7 @@ def key_down(self, evt): # =========================================================== elif mods & KMOD_SHIFT: - raise GLError(err=1285, description="User pressed CONTROL-SHIFT-F9, requesting a GL Memory Error") + raise OpenGL.GL.GLError(err=1285, description="User pressed CONTROL-SHIFT-F9, requesting a GL Memory Error") else: try: expr = input_text(">>> ", 600) @@ -2535,7 +2536,7 @@ def causeError(): if mods & KMOD_ALT: alert("MCEdit, a Minecraft World Editor\n\nCopyright 2010 David Rio Vierra") elif mods & KMOD_SHIFT: - alertException(causeError)() + mceutils.alertException(causeError)() else: causeError() @@ -2690,7 +2691,7 @@ def repairRegions(self): alert("Repairs complete. See the console window for details.") - @alertException + @mceutils.alertException def showWorldInfo(self): ticksPerDay = 24000 ticksPerHour = ticksPerDay / 24 @@ -2714,20 +2715,20 @@ def composeMCTime(d, h, m, t): items = [] t = functools.partial(isinstance, self.level) - if t(MCInfdevOldLevel): - if self.level.version == MCInfdevOldLevel.VERSION_ANVIL: + if t(pymclevel.MCInfdevOldLevel): + if self.level.version == pymclevel.MCInfdevOldLevel.VERSION_ANVIL: levelFormat = "Minecraft Infinite World (Anvil Format)" - elif self.level.version == MCInfdevOldLevel.VERSION_MCR: + elif self.level.version == pymclevel.MCInfdevOldLevel.VERSION_MCR: levelFormat = "Minecraft Infinite World (Region Format)" else: levelFormat = "Minecraft Infinite World (Old Chunk Format)" - elif t(MCIndevLevel): + elif t(pymclevel.MCIndevLevel): levelFormat = "Minecraft Indev (.mclevel format)" - elif t(MCSchematic): + elif t(pymclevel.MCSchematic): levelFormat = "MCEdit Schematic" - elif t(ZipSchematic): + elif t(pymclevel.ZipSchematic): levelFormat = "MCEdit Schematic (Zipped Format)" - elif t(MCJavaLevel): + elif t(pymclevel.MCJavaLevel): levelFormat = "Minecraft Classic or raw block array" else: levelFormat = "Unknown" @@ -2754,7 +2755,7 @@ def composeMCTime(d, h, m, t): if hasattr(self.level, 'RandomSeed'): seed = self.level.RandomSeed - seedInputRow = IntInputRow("RandomSeed: ", width=250, ref=AttrRef(self.level, "RandomSeed")) + seedInputRow = mceutils.IntInputRow("RandomSeed: ", width=250, ref=AttrRef(self.level, "RandomSeed")) items.append(seedInputRow) if hasattr(self.level, 'GameType'): @@ -2780,7 +2781,7 @@ def action(): items.append(gametypeRow) - if isinstance(self.level, MCInfdevOldLevel): + if isinstance(self.level, pymclevel.MCInfdevOldLevel): chunkCount = self.level.chunkCount chunkCountLabel = Label("Number of chunks: {0}".format(chunkCount)) @@ -2855,21 +2856,21 @@ def decreaseViewDistance(self): self.addWorker(self.renderer) Settings.viewDistance.set(self.renderer.viewDistance) - @alertException + @mceutils.alertException def askLoadWorld(self): - if not os.path.isdir(mcplatform.saveFileDir): - alert(u"Could not find the Minecraft saves directory!\n\n({0} was not found or is not a directory)".format(mcplatform.saveFileDir)) + if not os.path.isdir(pymclevel.saveFileDir): + alert(u"Could not find the Minecraft saves directory!\n\n({0} was not found or is not a directory)".format(pymclevel.saveFileDir)) return worldPanel = Widget() - potentialWorlds = os.listdir(mcplatform.saveFileDir) - potentialWorlds = [os.path.join(mcplatform.saveFileDir, p) for p in potentialWorlds] - worldFiles = [p for p in potentialWorlds if MCInfdevOldLevel.isLevel(p)] + potentialWorlds = os.listdir(pymclevel.saveFileDir) + potentialWorlds = [os.path.join(pymclevel.saveFileDir, p) for p in potentialWorlds] + worldFiles = [p for p in potentialWorlds if pymclevel.MCInfdevOldLevel.isLevel(p)] worlds = [] for f in worldFiles: try: - lev = MCInfdevOldLevel(f) + lev = pymclevel.MCInfdevOldLevel(f) except Exception, e: print f, ": ", repr(e) continue @@ -2952,18 +2953,18 @@ def createNewLevel(self): label = Label("Creating a new world.") generatorPanel = GeneratorPanel() - xinput = IntInputRow("X: ", ref=AttrRef(newWorldPanel, "x")) - yinput = IntInputRow("Y: ", ref=AttrRef(newWorldPanel, "y")) - zinput = IntInputRow("Z: ", ref=AttrRef(newWorldPanel, "z")) - finput = IntInputRow("f: ", ref=AttrRef(newWorldPanel, "f"), min=0, max=3) + xinput = mceutils.IntInputRow("X: ", ref=AttrRef(newWorldPanel, "x")) + yinput = mceutils.IntInputRow("Y: ", ref=AttrRef(newWorldPanel, "y")) + zinput = mceutils.IntInputRow("Z: ", ref=AttrRef(newWorldPanel, "z")) + finput = mceutils.IntInputRow("f: ", ref=AttrRef(newWorldPanel, "f"), min=0, max=3) xyzrow = Row([xinput, yinput, zinput, finput]) - seedinput = IntInputRow("Seed: ", width=250, ref=AttrRef(newWorldPanel, "seed")) + seedinput = mceutils.IntInputRow("Seed: ", width=250, ref=AttrRef(newWorldPanel, "seed")) - winput = IntInputRow("East-West Chunks: ", ref=AttrRef(newWorldPanel, "w"), min=0) - hinput = IntInputRow("North-South Chunks: ", ref=AttrRef(newWorldPanel, "h"), min=0) + winput = mceutils.IntInputRow("East-West Chunks: ", ref=AttrRef(newWorldPanel, "w"), min=0) + hinput = mceutils.IntInputRow("North-South Chunks: ", ref=AttrRef(newWorldPanel, "h"), min=0) # grassinputrow = Row( (Label("Grass: ") # from editortools import BlockButton - # blockInput = BlockButton(alphaMaterials, alphaMaterials.Grass) + # blockInput = BlockButton(pymclevel.alphaMaterials, pymclevel.alphaMaterials.Grass) # blockInputRow = Row( (Label("Surface: "), blockInput) ) types = ["Survival", "Creative"] @@ -2987,7 +2988,7 @@ def action(): result = Dialog(client=newWorldPanel, responses=["Create", "Cancel"]).present() if result == "Cancel": return - filename = mcplatform.askCreateWorld(saveFileDir) + filename = mcplatform.askCreateWorld(pymclevel.saveFileDir) print filename if not filename: @@ -3003,7 +3004,7 @@ def action(): self.freezeStatus("Creating world...") try: - newlevel = MCInfdevOldLevel(filename=filename, create=True, random_seed=seed) + newlevel = pymclevel.MCInfdevOldLevel(filename=filename, create=True, random_seed=seed) # chunks = list(itertools.product(xrange(w / 2 - w + cx, w / 2 + cx), xrange(h / 2 - h + cz, h / 2 + cz))) if generatorPanel.generatorChoice.selectedChoice == "Flatland": @@ -3015,14 +3016,14 @@ def action(): newlevel.setPlayerSpawnPosition((x, y + 1, z)) newlevel.GameType = gametypeButton.gametype newlevel.saveInPlace() - worker = generatorPanel.generate(newlevel, BoundingBox((x - w * 8, 0, z - h * 8), (w * 16, newlevel.Height, h * 16))) + worker = generatorPanel.generate(newlevel, pymclevel.BoundingBox((x - w * 8, 0, z - h * 8), (w * 16, newlevel.Height, h * 16))) - if "Canceled" == showProgress("Generating chunks...", worker, cancel=True): + if "Canceled" == mceutils.showProgress("Generating chunks...", worker, cancel=True): raise RuntimeError("Canceled.") if y < 64: y = 64 - newlevel.setBlockAt(x, y, z, alphaMaterials.Sponge.ID) + newlevel.setBlockAt(x, y, z, pymclevel.alphaMaterials.Sponge.ID) self.loadFile(filename) except Exception, e: @@ -3089,11 +3090,11 @@ def pasteSchematic(self, schematic): def deleteSelectedBlocks(self): self.selectionTool.deleteBlocks() - @alertException + @mceutils.alertException def undo(self): if len(self.undoStack) == 0: return - with setWindowCaption("UNDOING - "): + with mceutils.setWindowCaption("UNDOING - "): self.freezeStatus("Undoing the previous operation...") op = self.undoStack.pop() op.undo() @@ -3163,13 +3164,13 @@ def gl_draw(self): self.frameSamples.pop(0) self.frameSamples.append(timeDelta) - frameTotal = sum(self.frameSamples) + frameTotal = numpy.sum(self.frameSamples) self.averageFPS = 1000000. / ((frameTotal.microseconds + 1000000 * frameTotal.seconds) / float(len(self.frameSamples)) + 0.00001) r = self.renderer - chunkTotal = sum(r.chunkSamples) + chunkTotal = numpy.sum(r.chunkSamples) cps = 1000000. / ((chunkTotal.microseconds + 1000000 * chunkTotal.seconds) / float(len(r.chunkSamples)) + 0.00001) self.averageCPS = cps @@ -3189,7 +3190,7 @@ def gl_draw(self): dl=len(glutils.DisplayList.allLists), dlcount=glutils.gl.listCount, t=len(glutils.Texture.allTextures), g=len(gc.garbage)) - if isinstance(self.level, MCInfdevOldLevel): + if isinstance(self.level, pymclevel.MCInfdevOldLevel): self.debugString += "Loa: {0}, Dec: {1}, ".format(len(self.level.loadedChunkQueue), len(self.level.decompressedChunkQueue)) if self.renderer: @@ -3205,7 +3206,7 @@ def createWorkInfoPanel(self): progress = Label("{0} chunks ({1} pending updates)".format(len(w.chunkRenderers), len(w.invalidChunkQueue))) col = Column((label, progress), align="l", width=200) infos.append(col) - elif isinstance(w, RunningOperation): + elif isinstance(w, RunningOperation): # **FIXME** Where is RunningOperation supposed to come from? -David Sowder 20120311 label = Label(w.description) progress = Label(w.progress) col = Column((label, progress), align="l", width=200) @@ -3247,7 +3248,7 @@ def updateInspectionString(self, blockPosition): try: if self.debug: - if isinstance(self.level, MCIndevLevel): + if isinstance(self.level, pymclevel.MCIndevLevel): bl = self.level.blockLightAt(*blockPosition) blockID = self.level.blockAt(*blockPosition) bdata = self.level.blockDataAt(*blockPosition) @@ -3255,7 +3256,7 @@ def updateInspectionString(self, blockPosition): blockID, bdata, self.level.materials.names[blockID][bdata]) self.inspectionString += "Data: %d, Light: %d, " % (bdata, bl) - elif isinstance(self.level, pymclevel.infiniteworld.ChunkedLevelMixin): + elif isinstance(self.level, pymclevel.ChunkedLevelMixin): sl = self.level.skylightAt(*blockPosition) bl = self.level.blockLightAt(*blockPosition) bdata = self.level.blockDataAt(*blockPosition) @@ -3303,19 +3304,19 @@ def updateInspectionString(self, blockPosition): blockID, self.level.materials.names[blockID][0]) except Exception, e: - self.inspectionString += "Chunk {0} had an error: {1!r}".format((int(floor(blockPosition[0])) >> 4, int(floor(blockPosition[2])) >> 4), e) + self.inspectionString += "Chunk {0} had an error: {1!r}".format((int(numpy.floor(blockPosition[0])) >> 4, int(numpy.floor(blockPosition[2])) >> 4), e) pass def drawWireCubeReticle(self, color=(1.0, 1.0, 1.0, 1.0), position=None): - glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) - glEnable(GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) + OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) blockPosition, faceDirection = self.blockFaceUnderCursor blockPosition = position or blockPosition - drawTerrainCuttingWire(BoundingBox(blockPosition, (1, 1, 1)), c1=color) + mceutils.drawTerrainCuttingWire(pymclevel.BoundingBox(blockPosition, (1, 1, 1)), c1=color) - glDisable(GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) def drawString(self, x, y, color, string): return @@ -3323,18 +3324,18 @@ def drawString(self, x, y, color, string): def freezeStatus(self, string): return -# glColor(1.0, 0., 0., 1.0) +# OpenGL.GL.glColor(1.0, 0., 0., 1.0) # -# # glDrawBuffer(GL_FRONT) -# glMatrixMode(GL_PROJECTION) -# glPushMatrix() +# # glDrawBuffer(OpenGL.GL.GL_FRONT) +# OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) +# OpenGL.GL.glPushMatrix() # glRasterPos(50, 100) # for i in string: # glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(i)) # -# # glDrawBuffer(GL_BACK) -# glMatrixMode(GL_PROJECTION) -# glPopMatrix() +# # glDrawBuffer(OpenGL.GL.GL_BACK) +# OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) +# OpenGL.GL.glPopMatrix() # glFlush() # display.flip() # # while(True): pass @@ -3424,23 +3425,23 @@ def idleHandler(evt): ## ## print blockCount, fbo ## -## destBlocks = zeros(blockCount, 'uint8') +## destBlocks = numpy.zeros(blockCount, 'uint8') ## (sourceTex, destTex) = glGenTextures(2) ## ## glBindTexture(GL_TEXTURE_3D, sourceTex) ## glTexImage3D(GL_TEXTURE_3D, 0, 1, ## level.Width, level.Length, level.Height, -## 0, GL_RED, GL_UNSIGNED_BYTE, +## 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE, ## blocks) ## ## # return ## -## glBindTexture(GL_TEXTURE_2D, destTex) -## glTexImage2D(GL_TEXTURE_2D, 0, 1, +## glBindTexture(OpenGL.GL.GL_TEXTURE_2D, destTex) +## glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, 0, 1, ## level.Width, level.Length, -## 0, GL_RED, GL_UNSIGNED_BYTE, destBlocks) -## glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) -## glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, destTex, 0) +## 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE, destBlocks) +## glTexParameter(OpenGL.GL.GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) +## glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, OpenGL.GL.GL_TEXTURE_2D, destTex, 0) ## ## vertShader = glCreateShader(GL_VERTEX_SHADER) ## @@ -3476,13 +3477,13 @@ def idleHandler(evt): ## ## glUseProgram(prog); ## # return -## glDisable(GL_DEPTH_TEST); -## glVertexPointer(2, GL_FLOAT, 0, [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]); -## glDrawArrays(GL_QUADS, 0, 4); -## glEnable(GL_DEPTH_TEST); +## OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST); +## OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]); +## OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4); +## OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST); ## ## glFlush(); -## destBlocks = glGetTexImage(GL_TEXTURE_2D, 0, GL_RED, GL_UNSIGNED_BYTE); +## destBlocks = glGetTexImage(OpenGL.GL.GL_TEXTURE_2D, 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE); ## print destBlocks, destBlocks[0:8]; ## raise SystemExit; @@ -3532,7 +3533,7 @@ def __init__(self, rect, tools, *args, **kw): t.hotkey = i + 1 self.toolTextures = {} - self.toolbarDisplayList = DisplayList() + self.toolbarDisplayList = glutils.DisplayList() self.reloadTextures() def set_parent(self, parent): @@ -3619,7 +3620,7 @@ def toolTextureChanged(self): def reloadTextures(self): self.toolTextureChanged() - self.guiTexture = loadPNGTexture('gui.png') + self.guiTexture = mceutils.loadPNGTexture('gui.png') self.toolTextures = {} for tool in self.tools: @@ -3629,27 +3630,27 @@ def reloadTextures(self): tool.markerList.invalidate() def drawToolbar(self): - glEnableClientState(GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) - glColor(1., 1., 1., 1.) + OpenGL.GL.glColor(1., 1., 1., 1.) w, h = self.toolbarTextureSize self.guiTexture.bind() - glVertexPointer(3, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( 1, h + 1, 0.5, w + 1, h + 1, 0.5, w + 1, 1, 0.5, 1, 1, 0.5, ), dtype="f4")) - glTexCoordPointer(2, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( 0, 0, w, 0, w, h, 0, h, ), dtype="f4")) - glDrawArrays(GL_QUADS, 0, 4) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) for i in range(len(self.tools)): tool = self.tools[i] @@ -3658,44 +3659,44 @@ def drawToolbar(self): try: if not tool.toolIconName in self.toolTextures: filename = "toolicons" + os.sep + "{0}.png".format(tool.toolIconName) - self.toolTextures[tool.toolIconName] = loadPNGTexture(filename) + self.toolTextures[tool.toolIconName] = mceutils.loadPNGTexture(filename) x = 20 * i + 4 y = 4 w = 16 h = 16 self.toolTextures[tool.toolIconName].bind() - glVertexPointer(3, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( x, y + h, 1, x + w, y + h, 1, x + w, y, 1, x, y, 1, ), dtype="f4")) - glTexCoordPointer(2, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( 0, 0, w * 16, 0, w * 16, h * 16, 0, h * 16, ), dtype="f4")) - glDrawArrays(GL_QUADS, 0, 4) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) except Exception, e: print "Exception: {0!r}".format(e) - glDisableClientState(GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) gfont = None def gl_draw(self): - glEnable(GL_TEXTURE_2D) - glEnable(GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) self.toolbarDisplayList.call(self.drawToolbar) - glColor(1.0, 1.0, 0.0) + OpenGL.GL.glColor(1.0, 1.0, 0.0) - # glEnable(GL_BLEND) + # OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) # with gl.glPushMatrix(GL_TEXTURE): - # glLoadIdentity() + # OpenGL.GL.glLoadIdentity() # self.gfont.flatPrint("ADLADLADLADLADL") try: @@ -3718,29 +3719,29 @@ def gl_draw(self): ty = 0. tw = 24. th = 24. - glEnableClientState(GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) self.guiTexture.bind() - glVertexPointer(3, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( tx, ty, 2, tx + tw, ty, 2, tx + tw, ty + th, 2, tx, ty + th, 2, ), dtype="f4")) - glTexCoordPointer(2, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( texx, texy + texh, texx + texw, texy + texh, texx + texw, texy, texx, texy, ), dtype="f4")) - glDrawArrays(GL_QUADS, 0, 4) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) - glDisableClientState(GL_TEXTURE_COORD_ARRAY) - glDisable(GL_TEXTURE_2D) + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) - redOutBoxes = zeros(9 * 4 * 2, dtype='float32') + redOutBoxes = numpy.zeros(9 * 4 * 2, dtype='float32') cursor = 0 for i in range(len(self.tools)): t = self.tools[i] @@ -3755,8 +3756,8 @@ def gl_draw(self): cursor += 8 if cursor: - glColor(1.0, 0.0, 0.0, 0.3) - glVertexPointer(2, GL_FLOAT, 0, redOutBoxes) - glDrawArrays(GL_QUADS, 0, cursor / 2) + OpenGL.GL.glColor(1.0, 0.0, 0.0, 0.3) + OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, redOutBoxes) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, cursor / 2) - glDisable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) diff --git a/mcedit.py b/mcedit.py index f8ec821..63b2f91 100755 --- a/mcedit.py +++ b/mcedit.py @@ -5,55 +5,51 @@ Startup, main menu, keyboard configuration, automatic updating. """ -import os -import os.path -import sys -import config -import shutil -import functools -import traceback -import logging - -import pygame -from pygame.constants import * -from pygame import key, display, rect +import albow +from albow.dialogs import Dialog from albow.openglwidgets import GLViewport from albow.root import RootWidget -from albow.dialogs import Dialog -from albow import * +import config +import directories +import functools from glbackground import Panel - -from OpenGL import GL -from numpy import * - -from pymclevel.mclevel import MCInfdevOldLevel, saveFileDir -from pymclevel.materials import * -MCInfdevOldLevel.loadedChunkLimit = 0 - -from release import release - +import glutils import leveleditor +from leveleditor import ControlSettings, Settings +import logging +import mceutils import mcplatform -from mceutils import * from mcplatform import platform_open -from leveleditor import Settings, ControlSettings +import numpy +from OpenGL import GL +import os +import os.path +import pygame +from pygame import display, key, rect +import pymclevel +import release +import shutil +import sys +import traceback + +pymclevel.MCInfdevOldLevel.loadedChunkLimit = 0 ESCAPE = '\033' -class FileOpener(Widget): +class FileOpener(albow.Widget): is_gl_container = True def __init__(self, mcedit, *args, **kwargs): kwargs['rect'] = mcedit.rect - Widget.__init__(self, *args, **kwargs) + albow.Widget.__init__(self, *args, **kwargs) self.anchor = 'tlbr' self.mcedit = mcedit helpColumn = [] - label = Label("{0} {1} {2} {3} {4} {5}".format( + label = albow.Label("{0} {1} {2} {3} {4} {5}".format( config.config.get('Keys', 'Forward'), config.config.get('Keys', 'Left'), config.config.get('Keys', 'Back'), @@ -66,7 +62,7 @@ def __init__(self, mcedit, *args, **kwargs): helpColumn.append(label) def addHelp(text): - label = Label(text) + label = albow.Label(text) label.anchor = 'whrt' label.align = "r" helpColumn.append(label) @@ -77,21 +73,21 @@ def addHelp(text): addHelp("Hold SHIFT to move along a major axis") addHelp("Hold ALT for details") - helpColumn = Column(helpColumn, align="r") + helpColumn = albow.Column(helpColumn, align="r") helpColumn.topright = self.topright helpColumn.anchor = "whrt" #helpColumn.is_gl_container = True self.add(helpColumn) - keysColumn = [Label("")] + keysColumn = [albow.Label("")] buttonsColumn = [leveleditor.ControlPanel.getHeader()] shortnames = [] for world in self.mcedit.recentWorlds(): shortname = os.path.basename(world) try: - if MCInfdevOldLevel.isLevel(world): - lev = MCInfdevOldLevel(world) + if pymclevel.MCInfdevOldLevel.isLevel(world): + lev = pymclevel.MCInfdevOldLevel(world) shortname = lev.LevelName if lev.LevelName != lev.displayName: shortname = u"{0} ({1})".format(lev.LevelName, lev.displayName) @@ -112,13 +108,13 @@ def addHelp(text): ('F{0}'.format(i + 1), shortnames[i], self.createLoadButtonHandler(world)) for i, world in enumerate(self.mcedit.recentWorlds())]) - commandRow = HotkeyColumn(hotkeys, keysColumn, buttonsColumn) + commandRow = mceutils.HotkeyColumn(hotkeys, keysColumn, buttonsColumn) commandRow.anchor = 'lrh' sideColumn = mcedit.makeSideColumn() sideColumn.anchor = 'wh' - contentRow = Row((commandRow, sideColumn)) + contentRow = albow.Row((commandRow, sideColumn)) contentRow.center = self.center contentRow.anchor = "rh" self.add(contentRow) @@ -134,7 +130,7 @@ def idleevent(self, evt): def key_down(self, evt): keyname = key.name(evt.key) - if keyname == 'f4' and (key.get_mods() & (KMOD_ALT | KMOD_LALT | KMOD_RALT)): + if keyname == 'f4' and (key.get_mods() & (pygame.KMOD_ALT | pygame.KMOD_LALT | pygame.KMOD_RALT)): raise SystemExit if keyname in ('f1', 'f2', 'f3', 'f4', 'f5'): self.mcedit.loadRecentWorldNumber(int(keyname[1])) @@ -247,32 +243,32 @@ class KeyConfigPanel(Dialog): def __init__(self): Dialog.__init__(self) - keyConfigTable = TableView(columns=[TableColumn("Command", 400, "l"), TableColumn("Assigned Key", 150, "r")]) + keyConfigTable = albow.TableView(columns=[albow.TableColumn("Command", 400, "l"), albow.TableColumn("Assigned Key", 150, "r")]) keyConfigTable.num_rows = lambda: len(self.keyConfigKeys) keyConfigTable.row_data = self.getRowData keyConfigTable.row_is_selected = lambda x: x == self.selectedKeyIndex keyConfigTable.click_row = self.selectTableRow - tableWidget = Widget() + tableWidget = albow.Widget() tableWidget.add(keyConfigTable) tableWidget.shrink_wrap() self.keyConfigTable = keyConfigTable - buttonRow = (Button("Assign Key...", action=self.askAssignSelectedKey), - Button("Done", action=self.dismiss)) + buttonRow = (albow.Button("Assign Key...", action=self.askAssignSelectedKey), + albow.Button("Done", action=self.dismiss)) - buttonRow = Row(buttonRow) + buttonRow = albow.Row(buttonRow) - choiceButton = ChoiceButton(["WASD", "Arrows", "Numpad"], choose=self.choosePreset) + choiceButton = mceutils.ChoiceButton(["WASD", "Arrows", "Numpad"], choose=self.choosePreset) if config.config.get("Keys", "Forward") == "up": choiceButton.selectedChoice = "Arrows" if config.config.get("Keys", "Forward") == "[8]": choiceButton.selectedChoice = "Numpad" - choiceRow = Row((Label("Presets: "), choiceButton)) + choiceRow = albow.Row((albow.Label("Presets: "), choiceButton)) self.choiceButton = choiceButton - col = Column((tableWidget, choiceRow, buttonRow)) + col = albow.Column((tableWidget, choiceRow, buttonRow)) self.add(col) self.shrink_wrap() @@ -310,7 +306,7 @@ def askAssignKey(self, configKey, labelString=None): if labelString is None: labelString = "Press a key to assign to the action \"{0}\"\n\nPress ESC to cancel.".format(configKey) - label = Label(labelString) + label = albow.Label(labelString) panel.add(label) panel.shrink_wrap() @@ -361,34 +357,34 @@ def packChanged(): self.texturePackChoice.selectedChoice = self.texturePack self.texturePackChoice.choices = packs - self.texturePackChoice = texturePackChoice = ChoiceButton(getPacks(), choose=packChanged) + self.texturePackChoice = texturePackChoice = mceutils.ChoiceButton(getPacks(), choose=packChanged) if self.texturePack in self.texturePackChoice.choices: self.texturePackChoice.selectedChoice = self.texturePack - texturePackRow = Row((Label("Skin: "), texturePackChoice)) + texturePackRow = albow.Row((albow.Label("Skin: "), texturePackChoice)) - fieldOfViewRow = FloatInputRow("Field of View: ", + fieldOfViewRow = mceutils.FloatInputRow("Field of View: ", ref=Settings.fov.propertyRef(), width=100, min=25, max=120) - targetFPSRow = IntInputRow("Target FPS: ", + targetFPSRow = mceutils.IntInputRow("Target FPS: ", ref=Settings.targetFPS.propertyRef(), width=100, min=1, max=60) - bufferLimitRow = IntInputRow("Vertex Buffer Limit (MB): ", + bufferLimitRow = mceutils.IntInputRow("Vertex Buffer Limit (MB): ", ref=Settings.vertexBufferLimit.propertyRef(), width=100, min=0) - fastLeavesRow = CheckBoxLabel("Fast Leaves", + fastLeavesRow = mceutils.CheckBoxLabel("Fast Leaves", ref=Settings.fastLeaves.propertyRef(), tooltipText="Leaves are solid, like Minecraft's 'Fast' graphics") - roughGraphicsRow = CheckBoxLabel("Rough Graphics", + roughGraphicsRow = mceutils.CheckBoxLabel("Rough Graphics", ref=Settings.roughGraphics.propertyRef(), tooltipText="All blocks are drawn the same way (overrides 'Fast Leaves')") - enableMouseLagRow = CheckBoxLabel("Enable Mouse Lag", + enableMouseLagRow = mceutils.CheckBoxLabel("Enable Mouse Lag", ref=Settings.enableMouseLag.propertyRef(), tooltipText="Enable choppy mouse movement for faster loading.") - settingsColumn = Column((fastLeavesRow, + settingsColumn = albow.Column((fastLeavesRow, roughGraphicsRow, enableMouseLagRow, texturePackRow, @@ -397,17 +393,17 @@ def packChanged(): bufferLimitRow, ), align='r') - settingsColumn = Column((Label("Settings"), + settingsColumn = albow.Column((albow.Label("Settings"), settingsColumn)) - settingsRow = Row((settingsColumn,)) + settingsRow = albow.Row((settingsColumn,)) - optionsColumn = Column((settingsRow, Button("OK", action=mcedit.removeGraphicOptions))) + optionsColumn = albow.Column((settingsRow, albow.Button("OK", action=mcedit.removeGraphicOptions))) self.add(optionsColumn) self.shrink_wrap() def _reloadTextures(self, pack): - if hasattr(alphaMaterials, "terrainTexture"): + if hasattr(pymclevel.alphaMaterials, "terrainTexture"): self.mcedit.displayContext.loadTextures() texturePack = Settings.skin.configProperty(_reloadTextures) @@ -421,67 +417,67 @@ def __init__(self, mcedit): self.mcedit = mcedit - autoBrakeRow = CheckBoxLabel("Autobrake", + autoBrakeRow = mceutils.CheckBoxLabel("Autobrake", ref=ControlSettings.autobrake.propertyRef(), tooltipText="Apply brake when not pressing movement keys") - swapAxesRow = CheckBoxLabel("Swap Axes Looking Down", + swapAxesRow = mceutils.CheckBoxLabel("Swap Axes Looking Down", ref=ControlSettings.swapAxes.propertyRef(), tooltipText="Change the direction of the Forward and Backward keys when looking down") - cameraAccelRow = FloatInputRow("Camera Acceleration: ", + cameraAccelRow = mceutils.FloatInputRow("Camera Acceleration: ", ref=ControlSettings.cameraAccel.propertyRef(), width=100, min=5.0) - cameraDragRow = FloatInputRow("Camera Drag: ", + cameraDragRow = mceutils.FloatInputRow("Camera Drag: ", ref=ControlSettings.cameraDrag.propertyRef(), width=100, min=1.0) - cameraMaxSpeedRow = FloatInputRow("Camera Max Speed: ", + cameraMaxSpeedRow = mceutils.FloatInputRow("Camera Max Speed: ", ref=ControlSettings.cameraMaxSpeed.propertyRef(), width=100, min=1.0) - cameraBrakeSpeedRow = FloatInputRow("Camera Braking Speed: ", + cameraBrakeSpeedRow = mceutils.FloatInputRow("Camera Braking Speed: ", ref=ControlSettings.cameraBrakingSpeed.propertyRef(), width=100, min=1.0) - mouseSpeedRow = FloatInputRow("Mouse Speed: ", + mouseSpeedRow = mceutils.FloatInputRow("Mouse Speed: ", ref=ControlSettings.mouseSpeed.propertyRef(), width=100, min=0.1, max=20.0) - invertRow = CheckBoxLabel("Invert Mouse", + invertRow = mceutils.CheckBoxLabel("Invert Mouse", ref=ControlSettings.invertMousePitch.propertyRef(), tooltipText="Reverse the up and down motion of the mouse.") - spaceHeightRow = IntInputRow("Low Detail Height", + spaceHeightRow = mceutils.IntInputRow("Low Detail Height", ref=Settings.spaceHeight.propertyRef(), tooltipText="When you are this far above the top of the world, move fast and use low-detail mode.") - blockBufferRow = IntInputRow("Block Buffer", + blockBufferRow = mceutils.IntInputRow("Block Buffer", ref=Settings.blockBuffer.propertyRef(), min=1, tooltipText="Amount of memory used for temporary storage. When more than this is needed, the disk is used instead.") - setWindowPlacementRow = CheckBoxLabel("Set Window Placement", + setWindowPlacementRow = mceutils.CheckBoxLabel("Set Window Placement", ref=Settings.setWindowPlacement.propertyRef(), tooltipText="Try to save and restore the window position.") - windowSizeRow = CheckBoxLabel("Window Resize Alert", + windowSizeRow = mceutils.CheckBoxLabel("Window Resize Alert", ref=Settings.shouldResizeAlert.propertyRef(), tooltipText="Reminds you that the cursor won't work correctly after resizing the window.") - visibilityCheckRow = CheckBoxLabel("Visibility Check", + visibilityCheckRow = mceutils.CheckBoxLabel("Visibility Check", ref=Settings.visibilityCheck.propertyRef(), tooltipText="Do a visibility check on chunks while loading. May cause a crash.") - longDistanceRow = CheckBoxLabel("Long-Distance Mode", + longDistanceRow = mceutils.CheckBoxLabel("Long-Distance Mode", ref=Settings.longDistanceMode.propertyRef(), tooltipText="Always target the farthest block under the cursor, even in mouselook mode. Shortcut: ALT-Z") - flyModeRow = CheckBoxLabel("Fly Mode", + flyModeRow = mceutils.CheckBoxLabel("Fly Mode", ref=Settings.flyMode.propertyRef(), tooltipText="Moving forward and backward will not change your altitude in Fly Mode.") - self.goPortableButton = goPortableButton = Button("Change", action=self.togglePortable) + self.goPortableButton = goPortableButton = albow.Button("Change", action=self.togglePortable) goPortableButton.tooltipText = self.portableButtonTooltip() - goPortableRow = Row((ValueDisplay(ref=AttrRef(self, 'portableLabelText'), width=250, align='r'), goPortableButton)) + goPortableRow = albow.Row((albow.ValueDisplay(ref=albow.AttrRef(self, 'portableLabelText'), width=250, align='r'), goPortableButton)) - reportRow = CheckBoxLabel("Report Crashes", + reportRow = mceutils.CheckBoxLabel("Report Crashes", ref=Settings.reportCrashes.propertyRef(), tooltipText="Automatically report fatal errors to the author.") @@ -512,15 +508,15 @@ def __init__(self, mcedit): goPortableRow, ) - rightcol = Column(options, align='r') - leftcol = Column(inputs, align='r') + rightcol = albow.Column(options, align='r') + leftcol = albow.Column(inputs, align='r') - optionsColumn = Column((Label("Options"), - Row((leftcol, rightcol), align="t"))) + optionsColumn = albow.Column((albow.Label("Options"), + albow.Row((leftcol, rightcol), align="t"))) - settingsRow = Row((optionsColumn,)) + settingsRow = albow.Row((optionsColumn,)) - optionsColumn = Column((settingsRow, Button("OK", action=self.dismiss))) + optionsColumn = albow.Column((settingsRow, albow.Button("OK", action=self.dismiss))) self.add(optionsColumn) self.shrink_wrap() @@ -550,12 +546,12 @@ def togglePortable(self): textChoices[1] = "This will move your schematics to your Documents folder and your settings to your Preferences folder. Continue?" alertText = textChoices[mcplatform.portable] - if ask(alertText) == "OK": + if albow.ask(alertText) == "OK": try: [mcplatform.goPortable, mcplatform.goFixed][mcplatform.portable]() except Exception, e: traceback.print_exc() - alert(u"Error while moving files: {0}".format(repr(e))) + albow.alert(u"Error while moving files: {0}".format(repr(e))) self.goPortableButton.tooltipText = self.portableButtonTooltip() @@ -592,11 +588,11 @@ def __init__(self, displayContext, *args): if len(sys.argv) > 1: for arg in sys.argv[1:]: f = arg.decode(sys.getfilesystemencoding()) - if isdir(join(saveFileDir, f)): - f = join(saveFileDir, f) + if os.path.isdir(os.path.join(pymclevel.saveFileDir, f)): + f = os.path.join(pymclevel.saveFileDir, f) self.droppedLevel = f break - if exists(f): + if os.path.exists(f): self.droppedLevel = f break @@ -704,7 +700,7 @@ def setRecentWorlds(self, worlds): def makeSideColumn(self): def showhistory(): try: - with file(os.path.join(mcplatform.dataDir), 'history.txt') as f: + with file(os.path.join(directories.dataDir), 'history.txt') as f: history = f.read() history = "\n".join(history.split("\n")[:16]) @@ -713,13 +709,13 @@ def showhistory(): except Exception, e: history = "Exception while reading history.txt: {0}".format(e) - if ask(history, ["Show history.txt", "OK"]) == "Show history.txt": - platform_open(os.path.join(mcplatform.dataDir), "history.txt") + if albow.ask(history, ["Show history.txt", "OK"]) == "Show history.txt": + platform_open(os.path.join(directories.dataDir), "history.txt") def showLicense(): - platform_open(os.path.join(mcplatform.dataDir, "LICENSE.txt")) + platform_open(os.path.join(directories.dataDir, "LICENSE.txt")) - readmePath = os.path.join(mcplatform.dataDir, "README.html") + readmePath = os.path.join(directories.dataDir, "README.html") hotkeys = ([("", "Keys", @@ -744,7 +740,7 @@ def showLicense(): showLicense), ]) - c = HotkeyColumn(hotkeys) + c = mceutils.HotkeyColumn(hotkeys) return c @@ -778,7 +774,7 @@ def resized(self, dw, dh): if not hasattr(self, 'resizeAlert'): self.resizeAlert = self.shouldResizeAlert if self.resizeAlert: - alert("Window size increased. You may have problems using the cursor until MCEdit is restarted.") + albow.alert("Window size increased. You may have problems using the cursor until MCEdit is restarted.") self.resizeAlert = False shouldResizeAlert = Settings.shouldResizeAlert.configProperty() @@ -809,7 +805,7 @@ def createNewWorld(self): self.add(self.editor) self.focus_switch = self.editor - alert("World created. To expand this infinite world, explore the world in Minecraft or use the Chunk Control tool to add or delete chunks.") + albow.alert("World created. To expand this infinite world, explore the world in Minecraft or use the Chunk Control tool to add or delete chunks.") def removeEditor(self): self.remove(self.editor) @@ -819,7 +815,7 @@ def removeEditor(self): def confirm_quit(self): if self.editor.unsavedEdits: - result = ask("There are {0} unsaved changes.".format(self.editor.unsavedEdits), + result = albow.ask("There are {0} unsaved changes.".format(self.editor.unsavedEdits), responses=["Save and Quit", "Quit", "Cancel"]) if result == "Save and Quit": self.saveAndQuit() @@ -851,14 +847,14 @@ def main(self): rootwidget.add(mcedit) rootwidget.focus_switch = mcedit - if 0 == len(alphaMaterials.yamlDatas): - alert("Failed to load minecraft.yaml. Check the console window for details.") + if 0 == len(pymclevel.alphaMaterials.yamlDatas): + albow.alert("Failed to load minecraft.yaml. Check the console window for details.") if mcedit.droppedLevel: mcedit.loadFile(mcedit.droppedLevel) if mcedit.closeMinecraftWarning: - answer = ask("Warning: You must close Minecraft completely before editing. Save corruption may result. Get Satisfaction to learn more.", ["Get Satisfaction", "Don't remind me again.", "OK"], default=1, cancel=1) + answer = albow.ask("Warning: You must close Minecraft completely before editing. Save corruption may result. Get Satisfaction to learn more.", ["Get Satisfaction", "Don't remind me again.", "OK"], default=1, cancel=1) if answer == "Get Satisfaction": mcplatform.platform_open("http://getsatisfaction.com/mojang/topics/region_file_cache_interferes_with_map_editors_risking_save_corruption") if answer == "Don't remind me again.": @@ -916,7 +912,7 @@ def main(argv): try: if not os.path.exists(mcplatform.schematicsDir): shutil.copytree( - os.path.join(mcplatform.dataDir, u'stock-schematics'), + os.path.join(directories.dataDir, u'stock-schematics'), mcplatform.schematicsDir ) except Exception, e: @@ -946,16 +942,16 @@ def getWindowSize(self): return max(20, w), max(20, h) def displayMode(self): - displayMode = OPENGL | RESIZABLE + displayMode = pygame.OPENGL | pygame.RESIZABLE if Settings.doubleBuffer.get(): - displayMode |= DOUBLEBUF + displayMode |= pygame.DOUBLEBUF return displayMode def reset(self): pygame.key.set_repeat(500, 100) try: - display.gl_set_attribute(GL_SWAP_CONTROL, Settings.vsync.get()) + display.gl_set_attribute(pygame.GL_SWAP_CONTROL, Settings.vsync.get()) except Exception, e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) @@ -988,9 +984,9 @@ def reset(self): config.saveConfig() try: - iconpath = os.path.join(mcplatform.dataDir, 'favicon.png') + iconpath = os.path.join(directories.dataDir, 'favicon.png') iconfile = file(iconpath, 'rb') - icon = image.load(iconfile, 'favicon.png') + icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception, e: logging.warning('Unable to set icon: {0!r}'.format(e)) @@ -1015,7 +1011,7 @@ def loadTextures(self): def makeTerrainTexture(mats): w, h = 1, 1 - teximage = zeros((w, h, 4), dtype='uint8') + teximage = numpy.zeros((w, h, 4), dtype='uint8') teximage[:] = 127, 127, 127, 255 GL.glTexImage2D( @@ -1031,25 +1027,25 @@ def makeTerrainTexture(mats): ) textures = ( - (classicMaterials, 'terrain-classic.png'), - (indevMaterials, 'terrain-classic.png'), - (alphaMaterials, 'terrain.png'), - (pocketMaterials, 'terrain-pocket.png') + (pymclevel.classicMaterials, 'terrain-classic.png'), + (pymclevel.indevMaterials, 'terrain-classic.png'), + (pymclevel.alphaMaterials, 'terrain.png'), + (pymclevel.pocketMaterials, 'terrain-pocket.png') ) for mats, matFile in textures: try: if mats.name == 'Alpha': - tex = loadAlphaTerrainTexture() + tex = mceutils.loadAlphaTerrainTexture() else: - tex = loadPNGTexture(matFile) + tex = mceutils.loadPNGTexture(matFile) self.terrainTextures[mats.name] = tex except Exception, e: logging.warning( 'Unable to load terrain from {0}, using flat colors.' 'Error was: {1!r}'.format(matFile, e) ) - self.terrainTextures[mats.name] = Texture( + self.terrainTextures[mats.name] = glutils.Texture( functools.partial(makeTerrainTexture, mats) ) mats.terrainTexture = self.terrainTextures[mats.name] diff --git a/mceutils.py b/mceutils.py index 3554c39..a4c6754 100644 --- a/mceutils.py +++ b/mceutils.py @@ -18,29 +18,26 @@ Exception catching, some basic box drawing, texture pack loading, oddball UI elements """ -from OpenGL import GL, GLU -import numpy +from albow.controls import ValueDisplay +from albow import alert, ask, Button, Column, Label, root, Row, ValueButton, Widget +import config +from cStringIO import StringIO +from datetime import datetime +import directories +from errorreporting import reportCrash, reportException import httplib -import sys +import mcplatform +import numpy +from OpenGL import GL, GLU import os import platform -import traceback -import zipfile -from cStringIO import StringIO -from datetime import datetime - -from pygame import image, display import png -import config -import release -import mcplatform -from albow import ask, alert, Widget, Button, ValueButton, Column, Row, Label, root +from pygame import display, image import pymclevel -from albow.controls import ValueDisplay -from pymclevel import materials - - -from errorreporting import reportException, reportCrash +import release +import sys +import traceback +import zipfile def alertException(func): @@ -55,14 +52,12 @@ def _alertException(*args, **kw): return _alertException -from pymclevel.faces import * - def drawFace(box, face, type=GL.GL_QUADS): x, y, z, = box.origin x2, y2, z2 = box.maximum - if face == FaceXDecreasing: + if face == pymclevel.faces.FaceXDecreasing: faceVertices = numpy.array( (x, y2, z2, @@ -71,7 +66,7 @@ def drawFace(box, face, type=GL.GL_QUADS): x, y, z2, ), dtype='f4') - elif face == FaceXIncreasing: + elif face == pymclevel.faces.FaceXIncreasing: faceVertices = numpy.array( (x2, y, z2, @@ -80,7 +75,7 @@ def drawFace(box, face, type=GL.GL_QUADS): x2, y2, z2, ), dtype='f4') - elif face == FaceYDecreasing: + elif face == pymclevel.faces.FaceYDecreasing: faceVertices = numpy.array( (x2, y, z2, x, y, z2, @@ -88,7 +83,7 @@ def drawFace(box, face, type=GL.GL_QUADS): x2, y, z, ), dtype='f4') - elif face == FaceYIncreasing: + elif face == pymclevel.faces.FaceYIncreasing: faceVertices = numpy.array( (x2, y2, z, x, y2, z, @@ -96,7 +91,7 @@ def drawFace(box, face, type=GL.GL_QUADS): x2, y2, z2, ), dtype='f4') - elif face == FaceZDecreasing: + elif face == pymclevel.faces.FaceZDecreasing: faceVertices = numpy.array( (x, y, z, x, y2, z, @@ -104,7 +99,7 @@ def drawFace(box, face, type=GL.GL_QUADS): x2, y, z, ), dtype='f4') - elif face == FaceZIncreasing: + elif face == pymclevel.faces.FaceZIncreasing: faceVertices = numpy.array( (x2, y, z2, x2, y2, z2, @@ -356,7 +351,7 @@ def slurpZipExt(zipextfile): if foliageColorFile is not None: w, h, data = loadPNGData(slurpZipExt(foliageColorFile)) color = data[77, 55, :3] - materials.alphaMaterials.flatColors[17, 0, :3] = color # xxxxxxx + pymclevel.materials.alphaMaterials.flatColors[17, 0, :3] = color # xxxxxxx color = [c / 255.0 for c in color] LeafBlockRenderer.leafColor = color @@ -366,7 +361,7 @@ def slurpZipExt(zipextfile): if grassColorFile is not None: w, h, data = loadPNGData(slurpZipExt(grassColorFile)) color = data[77, 55, :3] - materials.alphaMaterials.flatColors[2, 0, :3] = color # xxxxxxx + pymclevel.materials.alphaMaterials.flatColors[2, 0, :3] = color # xxxxxxx color = [c / 255.0 for c in color] GenericBlockRenderer.grassColor = color @@ -384,7 +379,7 @@ def _loadFunc(): def loadPNGData(filename_or_data): # if filename[1:4] != "PNG": if isinstance(filename_or_data, basestring): - filename_or_data = os.path.join(mcplatform.dataDir, filename_or_data) + filename_or_data = os.path.join(directories.dataDir, filename_or_data) filename_or_data = filename_or_data.encode(sys.getfilesystemencoding()) else: # path = numpy.fromstring(filename, 'uint8') diff --git a/mcplatform.py b/mcplatform.py index d1f3171..47901a7 100644 --- a/mcplatform.py +++ b/mcplatform.py @@ -18,11 +18,10 @@ Platform-specific functions, folder paths, and the whole fixed/portable nonsense. """ -import sys +import directories import os -from os.path import join, exists, dirname - -from directories import * +from os.path import dirname, exists, join +import sys enc = sys.getfilesystemencoding() @@ -32,9 +31,9 @@ plat = "win32" if platform.architecture()[0] == "64bit": plat = "win-amd64" - sys.path.append(join(dataDir, "pymclevel", "build", "lib." + plat + "-2.6").encode(enc)) + sys.path.append(join(directories.dataDir, "pymclevel", "build", "lib." + plat + "-2.6").encode(enc)) -os.environ["YAML_ROOT"] = join(dataDir, "pymclevel").encode(enc) +os.environ["YAML_ROOT"] = join(directories.dataDir, "pymclevel").encode(enc) from pygame import display @@ -336,7 +335,7 @@ def platform_open(path): win32_window_size = True ini = u"mcedit.ini" -parentDir = dirname(dataDir) +parentDir = dirname(directories.dataDir) docsFolder = documents_folder() portableConfigFilePath = os.path.join(parentDir, ini) portableSchematicsDir = os.path.join(parentDir, u"MCEdit-schematics") @@ -419,7 +418,7 @@ def portableConfigExists(): schematicsDir = fixedSchematicsDir portable = False -filtersDir = os.path.join(dataDir, "filters") +filtersDir = os.path.join(directories.dataDir, "filters") if filtersDir not in [s.decode(sys.getfilesystemencoding()) if isinstance(s, str) else s @@ -434,4 +433,4 @@ def portableConfigExists(): else: jarStorage = ServerJarStorage() -items.items = items.Items(join(dataDir, "pymclevel", "items.txt")) +items.items = items.Items(join(directories.dataDir, "pymclevel", "items.txt")) diff --git a/renderer.py b/renderer.py index 258d29b..cf0ef82 100644 --- a/renderer.py +++ b/renderer.py @@ -37,36 +37,17 @@ One per block type, plus one for low detail and one for Entity """ -from collections import deque - -from numpy import * -import itertools - -from pymclevel import * -del sum -del any -del all # xxx use builtin all, fix the wild imports later +from collections import defaultdict, deque from datetime import datetime, timedelta -from time import sleep -from threading import Thread -from collections import defaultdict - from depths import DepthOffset - -import OpenGL - -from OpenGL import GL -from OpenGL.GL import * -from OpenGL.GLU import * -from OpenGL.GLUT import * -from OpenGL.GL.ARB.vertex_buffer_object import * -from OpenGL.GL.EXT.framebuffer_object import * - -from pymclevel.faces import * -import config -from mceutils import reportCrash from glutils import gl, Texture +import logging +import numpy +import OpenGL +import pymclevel +import sys +#import time def chunkMarkers(chunkSet): @@ -162,7 +143,7 @@ def makeDisplayLists(self): showRedraw = self.renderer.showRedraw if not (showRedraw and self.needsBlockRedraw): - glEnableClientState(GL_COLOR_ARRAY) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) renderers = self.blockRenderers @@ -176,7 +157,7 @@ def makeDisplayLists(self): lists[blockRenderer.renderstate].append(l) if not (showRedraw and self.needsBlockRedraw): - glDisableClientState(GL_COLOR_ARRAY) + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) self.needsRedisplay = False self.renderstateLists = lists @@ -245,16 +226,16 @@ def vertexArraysDone(self): def done(self): return len(self.invalidLayers) == 0 -_XYZ = s_[..., 0:3] -_ST = s_[..., 3:5] -_XYZST = s_[..., :5] -_RGBA = s_[..., 20:24] -_RGB = s_[..., 20:23] -_A = s_[..., 23] +_XYZ = numpy.s_[..., 0:3] +_ST = numpy.s_[..., 3:5] +_XYZST = numpy.s_[..., :5] +_RGBA = numpy.s_[..., 20:24] +_RGB = numpy.s_[..., 20:23] +_A = numpy.s_[..., 23] def makeVertexTemplates(xmin=0, ymin=0, zmin=0, xmax=1, ymax=1, zmax=1): - return array([ + return numpy.array([ # FaceXIncreasing: [[xmax, ymin, zmax, (zmin * 16), 16 - (ymin * 16), 0x0b], @@ -302,12 +283,12 @@ def makeVertexTemplates(xmin=0, ymin=0, zmin=0, xmax=1, ymax=1, zmax=1): def createPrecomputedVertices(): height = 16 - precomputedVertices = [zeros(shape=(16, 16, height, 4, 6), # x,y,z,s,t,rg, ba + precomputedVertices = [numpy.zeros(shape=(16, 16, height, 4, 6), # x,y,z,s,t,rg, ba dtype='float32') for d in faceVertexTemplates] - xArray = arange(16)[:, newaxis, newaxis, newaxis] - zArray = arange(16)[newaxis, :, newaxis, newaxis] - yArray = arange(height)[newaxis, newaxis, :, newaxis] + xArray = numpy.arange(16)[:, numpy.newaxis, numpy.newaxis, numpy.newaxis] + zArray = numpy.arange(16)[numpy.newaxis, :, numpy.newaxis, numpy.newaxis] + yArray = numpy.arange(height)[numpy.newaxis, numpy.newaxis, :, numpy.newaxis] for dir in range(len(faceVertexTemplates)): precomputedVertices[dir][_XYZ][..., 0] = xArray @@ -316,7 +297,7 @@ def createPrecomputedVertices(): precomputedVertices[dir][_XYZ] += faceVertexTemplates[dir][..., 0:3] # xyz precomputedVertices[dir][_ST] = faceVertexTemplates[dir][..., 3:5] # s - precomputedVertices[dir].view('uint8')[_RGB] = faceVertexTemplates[dir][..., 5, newaxis] + precomputedVertices[dir].view('uint8')[_RGB] = faceVertexTemplates[dir][..., 5, numpy.newaxis] precomputedVertices[dir].view('uint8')[_A] = 0xff return precomputedVertices @@ -328,14 +309,14 @@ class ChunkCalculator (object): cachedTemplate = None cachedTemplateHeight = 0 - whiteLight = array([[[15] * 16] * 16] * 16, uint8) + whiteLight = numpy.array([[[15] * 16] * 16] * 16, numpy.uint8) precomputedVertices = createPrecomputedVertices() def __init__(self, level): self.makeRenderstates(level.materials) # del xArray, zArray, yArray - self.nullVertices = zeros((0,) * len(self.precomputedVertices[0].shape), dtype=self.precomputedVertices[0].dtype) + self.nullVertices = numpy.zeros((0,) * len(self.precomputedVertices[0].shape), dtype=self.precomputedVertices[0].dtype) from leveleditor import Settings Settings.fastLeaves.addObserver(self) @@ -353,31 +334,31 @@ def release(self): class renderstateLowDetail(object): @classmethod def bind(self): - glDisable(GL_CULL_FACE) - glDisable(GL_TEXTURE_2D) + OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) @classmethod def release(self): - glEnable(GL_CULL_FACE) - glEnable(GL_TEXTURE_2D) + OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) class renderstateAlphaTest(object): @classmethod def bind(self): - glEnable(GL_ALPHA_TEST) + OpenGL.GL.glEnable(OpenGL.GL.GL_ALPHA_TEST) @classmethod def release(self): - glDisable(GL_ALPHA_TEST) + OpenGL.GL.glDisable(OpenGL.GL.GL_ALPHA_TEST) class _renderstateAlphaBlend(object): @classmethod def bind(self): - glEnable(GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) @classmethod def release(self): - glDisable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) class renderstateWater(_renderstateAlphaBlend): pass @@ -388,17 +369,17 @@ class renderstateIce(_renderstateAlphaBlend): class renderstateEntity(object): @classmethod def bind(self): - glDisable(GL_DEPTH_TEST) - # glDisable(GL_CULL_FACE) - glDisable(GL_TEXTURE_2D) - glEnable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + # OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) @classmethod def release(self): - glEnable(GL_DEPTH_TEST) - # glEnable(GL_CULL_FACE) - glEnable(GL_TEXTURE_2D) - glDisable(GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + # OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) renderstates = ( renderstatePlain, @@ -438,7 +419,7 @@ def makeRenderstates(self, materials): # portal ] - self.materialMap = materialMap = zeros((256,), 'uint8') + self.materialMap = materialMap = numpy.zeros((256,), 'uint8') materialMap[1:] = 1 # generic blocks materialCount = 2 @@ -448,29 +429,29 @@ def makeRenderstates(self, materials): br.materialIndex = materialCount materialCount += 1 - self.exposedMaterialMap = array(materialMap) + self.exposedMaterialMap = numpy.array(materialMap) self.addTransparentMaterials(self.exposedMaterialMap, materialCount) def addTransparentMaterials(self, mats, materialCount): transparentMaterials = [ - alphaMaterials.Glass, - alphaMaterials.GlassPane, - alphaMaterials.IronBars, - alphaMaterials.MonsterSpawner, - alphaMaterials.Vines, - alphaMaterials.Fire, + pymclevel.materials.alphaMaterials.Glass, + pymclevel.materials.alphaMaterials.GlassPane, + pymclevel.materials.alphaMaterials.IronBars, + pymclevel.materials.alphaMaterials.MonsterSpawner, + pymclevel.materials.alphaMaterials.Vines, + pymclevel.materials.alphaMaterials.Fire, ] for b in transparentMaterials: mats[b.ID] = materialCount materialCount += 1 - hiddenOreMaterials = arange(256, dtype='uint8') + hiddenOreMaterials = numpy.arange(256, dtype='uint8') hiddenOreMaterials[2] = 1 # don't show boundaries between dirt,grass,sand,gravel,stone hiddenOreMaterials[3] = 1 hiddenOreMaterials[12] = 1 hiddenOreMaterials[13] = 1 - roughMaterials = ones((256,), dtype='uint8') + roughMaterials = numpy.ones((256,), dtype='uint8') roughMaterials[0] = 0 addTransparentMaterials(None, roughMaterials, 2) @@ -487,7 +468,7 @@ def calcFacesForChunkRenderer(self, cr): try: chunk = level.getChunk(cx, cz) except Exception, e: - warn(u"Error reading chunk: %s", e) + logging.warn(u"Error reading chunk: %s", e) yield return @@ -543,30 +524,30 @@ def getNeighboringChunks(self, chunk): level = chunk.world neighboringChunks = {} - for dir, dx, dz in ((FaceXDecreasing, -1, 0), - (FaceXIncreasing, 1, 0), - (FaceZDecreasing, 0, -1), - (FaceZIncreasing, 0, 1)): + for dir, dx, dz in ((pymclevel.faces.FaceXDecreasing, -1, 0), + (pymclevel.faces.FaceXIncreasing, 1, 0), + (pymclevel.faces.FaceZDecreasing, 0, -1), + (pymclevel.faces.FaceZIncreasing, 0, 1)): if not level.containsChunk(cx + dx, cz + dz): - neighboringChunks[dir] = ZeroChunk(level.Height) + neighboringChunks[dir] = pymclevel.infiniteworld.ZeroChunk(level.Height) else: # if not level.chunkIsLoaded(cx+dx,cz+dz): # raise StopIteration try: neighboringChunks[dir] = level.getChunk(cx + dx, cz + dz) - except (ChunkNotPresent, ChunkMalformed): - neighboringChunks[dir] = ZeroChunk(level.Height) + except (pymclevel.mclevelbase.ChunkNotPresent, pymclevel.mclevelbase.ChunkMalformed): + neighboringChunks[dir] = pymclevel.infiniteworld.ZeroChunk(level.Height) return neighboringChunks def getAreaBlocks(self, chunk, neighboringChunks): chunkWidth, chunkLength, chunkHeight = chunk.Blocks.shape - areaBlocks = zeros((chunkWidth + 2, chunkLength + 2, chunkHeight + 2), uint8) + areaBlocks = numpy.zeros((chunkWidth + 2, chunkLength + 2, chunkHeight + 2), numpy.uint8) areaBlocks[1:-1, 1:-1, 1:-1] = chunk.Blocks - areaBlocks[:1, 1:-1, 1:-1] = neighboringChunks[FaceXDecreasing].Blocks[-1:, :chunkLength, :chunkHeight] - areaBlocks[-1:, 1:-1, 1:-1] = neighboringChunks[FaceXIncreasing].Blocks[:1, :chunkLength, :chunkHeight] - areaBlocks[1:-1, :1, 1:-1] = neighboringChunks[FaceZDecreasing].Blocks[:chunkWidth, -1:, :chunkHeight] - areaBlocks[1:-1, -1:, 1:-1] = neighboringChunks[FaceZIncreasing].Blocks[:chunkWidth, :1, :chunkHeight] + areaBlocks[:1, 1:-1, 1:-1] = neighboringChunks[pymclevel.faces.FaceXDecreasing].Blocks[-1:, :chunkLength, :chunkHeight] + areaBlocks[-1:, 1:-1, 1:-1] = neighboringChunks[pymclevel.faces.FaceXIncreasing].Blocks[:1, :chunkLength, :chunkHeight] + areaBlocks[1:-1, :1, 1:-1] = neighboringChunks[pymclevel.faces.FaceZDecreasing].Blocks[:chunkWidth, -1:, :chunkHeight] + areaBlocks[1:-1, -1:, 1:-1] = neighboringChunks[pymclevel.faces.FaceZIncreasing].Blocks[:chunkWidth, :1, :chunkHeight] return areaBlocks def getFacingBlockIndices(self, areaBlocks, areaBlockMats): @@ -574,18 +555,18 @@ def getFacingBlockIndices(self, areaBlocks, areaBlockMats): exposedFacesX = (areaBlockMats[:-1, 1:-1, 1:-1] != areaBlockMats[1:, 1:-1, 1:-1]) - facingBlockIndices[FaceXDecreasing] = exposedFacesX[:-1] - facingBlockIndices[FaceXIncreasing] = exposedFacesX[1:] + facingBlockIndices[pymclevel.faces.FaceXDecreasing] = exposedFacesX[:-1] + facingBlockIndices[pymclevel.faces.FaceXIncreasing] = exposedFacesX[1:] exposedFacesZ = (areaBlockMats[1:-1, :-1, 1:-1] != areaBlockMats[1:-1, 1:, 1:-1]) - facingBlockIndices[FaceZDecreasing] = exposedFacesZ[:, :-1] - facingBlockIndices[FaceZIncreasing] = exposedFacesZ[:, 1:] + facingBlockIndices[pymclevel.faces.FaceZDecreasing] = exposedFacesZ[:, :-1] + facingBlockIndices[pymclevel.faces.FaceZIncreasing] = exposedFacesZ[:, 1:] exposedFacesY = (areaBlockMats[1:-1, 1:-1, :-1] != areaBlockMats[1:-1, 1:-1, 1:]) - facingBlockIndices[FaceYDecreasing] = exposedFacesY[:, :, :-1] - facingBlockIndices[FaceYIncreasing] = exposedFacesY[:, :, 1:] + facingBlockIndices[pymclevel.faces.FaceYDecreasing] = exposedFacesY[:, :, :-1] + facingBlockIndices[pymclevel.faces.FaceYIncreasing] = exposedFacesY[:, :, 1:] return facingBlockIndices def getAreaBlockLights(self, chunk, neighboringChunks): @@ -597,36 +578,36 @@ def getAreaBlockLights(self, chunk, neighboringChunks): if lights != None: finalLight = lights if skyLight != None: - finalLight = maximum(skyLight, lights) + finalLight = numpy.maximum(skyLight, lights) - areaBlockLights = ones((chunkWidth + 2, chunkLength + 2, chunkHeight + 2), uint8) + areaBlockLights = numpy.ones((chunkWidth + 2, chunkLength + 2, chunkHeight + 2), numpy.uint8) areaBlockLights[:] = 15 areaBlockLights[1:-1, 1:-1, 1:-1] = finalLight - nc = neighboringChunks[FaceXDecreasing] - maximum(nc.SkyLight[-1:, :chunkLength, :chunkHeight], + nc = neighboringChunks[pymclevel.faces.FaceXDecreasing] + numpy.maximum(nc.SkyLight[-1:, :chunkLength, :chunkHeight], nc.BlockLight[-1:, :chunkLength, :chunkHeight], areaBlockLights[0:1, 1:-1, 1:-1]) - nc = neighboringChunks[FaceXIncreasing] - maximum(nc.SkyLight[:1, :chunkLength, :chunkHeight], + nc = neighboringChunks[pymclevel.faces.FaceXIncreasing] + numpy.maximum(nc.SkyLight[:1, :chunkLength, :chunkHeight], nc.BlockLight[:1, :chunkLength, :chunkHeight], areaBlockLights[-1:, 1:-1, 1:-1]) - nc = neighboringChunks[FaceZDecreasing] - maximum(nc.SkyLight[:chunkWidth, -1:, :chunkHeight], + nc = neighboringChunks[pymclevel.faces.FaceZDecreasing] + numpy.maximum(nc.SkyLight[:chunkWidth, -1:, :chunkHeight], nc.BlockLight[:chunkWidth, -1:, :chunkHeight], areaBlockLights[1:-1, 0:1, 1:-1]) - nc = neighboringChunks[FaceZIncreasing] - maximum(nc.SkyLight[:chunkWidth, :1, :chunkHeight], + nc = neighboringChunks[pymclevel.faces.FaceZIncreasing] + numpy.maximum(nc.SkyLight[:chunkWidth, :1, :chunkHeight], nc.BlockLight[:chunkWidth, :1, :chunkHeight], areaBlockLights[1:-1, -1:, 1:-1]) minimumLight = 4 # areaBlockLights[areaBlockLights 0 - flatcolors[overmask] = level.materials.flatColors[:, 0][overblocks[overmask]][:, newaxis] + flatcolors[overmask] = level.materials.flatColors[:, 0][overblocks[overmask]][:, numpy.newaxis] if self.detailLevel == 2: heightfactor = (y / float(2.0 * ch.world.Height)) + 0.5 - flatcolors[..., :3] *= heightfactor[:, newaxis, newaxis] + flatcolors[..., :3] *= heightfactor[:, numpy.newaxis, numpy.newaxis] - _RGBA = s_[..., 12:16] + _RGBA = numpy.s_[..., 12:16] va0.view('uint8')[_RGBA] = flatcolors va0[_XYZ][:, :, 0] *= step @@ -1125,10 +1106,10 @@ def makeChunkVertices(self, ch): self.vertexArrays = [va0] return - va1 = array(vertexArray) - va1[..., :3] += faceVertexTemplates[FaceXIncreasing, ..., :3] + va1 = numpy.array(vertexArray) + va1[..., :3] += faceVertexTemplates[pymclevel.faces.FaceXIncreasing, ..., :3] - va1[_XYZ][:, (0, 1), 1] = depths[nonAirBlocks].ravel()[:, newaxis] # stretch to floor + va1[_XYZ][:, (0, 1), 1] = depths[nonAirBlocks].ravel()[:, numpy.newaxis] # stretch to floor va1[_XYZ][:, (1, 2), 0] -= 1.0 # turn diagonally va1[_XYZ][:, (2, 3), 1] -= 0.5 # drop down to prevent intersection pixels @@ -1140,9 +1121,9 @@ def makeChunkVertices(self, ch): va1.view('uint8')[_RGBA] = flatcolors grassmask = topBlocks[nonAirBlocks] == 2 # color grass sides with dirt's color - va1.view('uint8')[_RGBA][grassmask] = level.materials.flatColors[:, 0][[3]][:, newaxis] + va1.view('uint8')[_RGBA][grassmask] = level.materials.flatColors[:, 0][[3]][:, numpy.newaxis] - va2 = array(va1) + va2 = numpy.array(va1) va2[_XYZ][:, (1, 2), 0] += step va2[_XYZ][:, (0, 3), 0] -= step @@ -1177,28 +1158,28 @@ def makeGenericVertices(self, facingBlockIndices, blocks, blockMaterials, blockD continue def setTexture(): - vertexArray[_ST] += texMap(theseBlocks, bdata, direction)[:, newaxis, 0:2] + vertexArray[_ST] += texMap(theseBlocks, bdata, direction)[:, numpy.newaxis, 0:2] setTexture() def setGrassColors(): - grass = theseBlocks == alphaMaterials.Grass.ID + grass = theseBlocks == pymclevel.materials.alphaMaterials.Grass.ID vertexArray.view('uint8')[_RGB][grass] *= self.grassColor def getBlockLight(): return facingBlockLight[blockIndices] def setColors(): - vertexArray.view('uint8')[_RGB] *= getBlockLight()[..., newaxis, newaxis] + vertexArray.view('uint8')[_RGB] *= getBlockLight()[..., numpy.newaxis, numpy.newaxis] if self.materials.name in ("Alpha", "Pocket"): - if direction == FaceYIncreasing: + if direction == pymclevel.faces.FaceYIncreasing: setGrassColors() - # leaves = theseBlocks == alphaMaterials.Leaves.ID + # leaves = theseBlocks == pymclevel.materials.alphaMaterials.Leaves.ID # vertexArray.view('uint8')[_RGBA][leaves] *= [0.15, 0.88, 0.15, 1.0] -# snow = theseBlocks == alphaMaterials.SnowLayer.ID -# if direction == FaceYIncreasing: +# snow = theseBlocks == pymclevel.materials.alphaMaterials.SnowLayer.ID +# if direction == pymclevel.faces.FaceYIncreasing: # vertexArray[_XYZ][snow, ...,1] -= 0.875 # -# if direction != FaceYIncreasing and direction != FaceYDecreasing: +# if direction != pymclevel.faces.FaceYIncreasing and direction != pymclevel.faces.FaceYDecreasing: # vertexArray[_XYZ][snow, ...,2:4,1] -= 0.875 # vertexArray[_ST][snow, ...,2:4,1] += 14 # @@ -1235,8 +1216,8 @@ def makeLeafVertices(self, facingBlockIndices, blocks, blockMaterials, blockData data = blockData[blockIndices] data &= 0x3 # ignore decay states leaves = (data == 0) | (data == 3) - pines = (data == alphaMaterials.PineLeaves.blockData) - birches = (data == alphaMaterials.BirchLeaves.blockData) + pines = (data == pymclevel.materials.alphaMaterials.PineLeaves.blockData) + birches = (data == pymclevel.materials.alphaMaterials.BirchLeaves.blockData) texes = texMap(18, data, 0) else: blockIndices = materialIndices @@ -1249,8 +1230,8 @@ def makeLeafVertices(self, facingBlockIndices, blocks, blockMaterials, blockData data = blockData[blockIndices] data &= 0x3 # ignore decay states leaves = (data == 0) - pines = (data == alphaMaterials.PineLeaves.blockData) - birches = (data == alphaMaterials.BirchLeaves.blockData) + pines = (data == pymclevel.materials.alphaMaterials.PineLeaves.blockData) + birches = (data == pymclevel.materials.alphaMaterials.BirchLeaves.blockData) type3 = (data == 3) leaves |= type3 @@ -1261,12 +1242,12 @@ def makeLeafVertices(self, facingBlockIndices, blocks, blockMaterials, blockData if not len(vertexArray): continue - vertexArray[_ST] += texes[:, newaxis] + vertexArray[_ST] += texes[:, numpy.newaxis] if not self.chunkCalculator.fastLeaves: vertexArray[_ST] -= (0x10, 0x0) - vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., newaxis, newaxis] + vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] if self.materials.name in ("Alpha", "Pocket"): vertexArray.view('uint8')[_RGB][leaves] *= self.leafColor vertexArray.view('uint8')[_RGB][pines] *= self.pineLeafColor @@ -1308,27 +1289,27 @@ def makePlantVertices(self, facingBlockIndices, blocks, blockMaterials, blockDat texes = texMap(blocks[blockIndices], bdata, 0) blockLight = areaBlockLights[1:-1, 1:-1, 1:-1] - lights = blockLight[blockIndices][..., newaxis, newaxis] + lights = blockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] colorize = None if self.materials.name == "Alpha": - colorize = (theseBlocks == alphaMaterials.TallGrass.ID) & (bdata != 0) + colorize = (theseBlocks == pymclevel.materials.alphaMaterials.TallGrass.ID) & (bdata != 0) - for direction in (FaceXIncreasing, FaceXDecreasing, FaceZIncreasing, FaceZDecreasing): + for direction in (pymclevel.faces.FaceXIncreasing, pymclevel.faces.FaceXDecreasing, pymclevel.faces.FaceZIncreasing, pymclevel.faces.FaceZDecreasing): vertexArray = self.makeTemplate(direction, blockIndices) if not len(vertexArray): return - if direction == FaceXIncreasing: + if direction == pymclevel.faces.FaceXIncreasing: vertexArray[_XYZ][..., 1:3, 0] -= 1 - if direction == FaceXDecreasing: + if direction == pymclevel.faces.FaceXDecreasing: vertexArray[_XYZ][..., 1:3, 0] += 1 - if direction == FaceZIncreasing: + if direction == pymclevel.faces.FaceZIncreasing: vertexArray[_XYZ][..., 1:3, 2] -= 1 - if direction == FaceZDecreasing: + if direction == pymclevel.faces.FaceZDecreasing: vertexArray[_XYZ][..., 1:3, 2] += 1 - vertexArray[_ST] += texes[:, newaxis, 0:2] + vertexArray[_ST] += texes[:, numpy.newaxis, 0:2] vertexArray.view('uint8')[_RGBA] = 0xf # ignore precomputed directional light vertexArray.view('uint8')[_RGB] *= lights @@ -1438,7 +1419,7 @@ class TorchBlockRenderer(BlockRenderer): torchOffsetsStraight, ] + [torchOffsetsStraight] * 10 - torchOffsets = array(torchOffsets, dtype='float32') + torchOffsets = numpy.array(torchOffsets, dtype='float32') torchOffsets[1][..., 3, :, 0] -= 0.5 @@ -1486,11 +1467,11 @@ def makeTorchVertices(self, facingBlockIndices, blocks, blockMaterials, blockDat vertexArray.view('uint8')[_RGBA] = 0xff vertexArray[_XYZ] += torchOffsets[:, direction] - if direction == FaceYIncreasing: + if direction == pymclevel.faces.FaceYIncreasing: vertexArray[_ST] = self.upCoords - if direction == FaceYDecreasing: + if direction == pymclevel.faces.FaceYDecreasing: vertexArray[_ST] = self.downCoords - vertexArray[_ST] += texes[:, newaxis, direction] + vertexArray[_ST] += texes[:, numpy.newaxis, direction] arrays.append(vertexArray) yield self.vertexArrays = arrays @@ -1499,10 +1480,10 @@ def makeTorchVertices(self, facingBlockIndices, blocks, blockMaterials, blockDat class RailBlockRenderer(BlockRenderer): - blocktypes = [alphaMaterials.Rail.ID, alphaMaterials.PoweredRail.ID, alphaMaterials.DetectorRail.ID] + blocktypes = [pymclevel.materials.alphaMaterials.Rail.ID, pymclevel.materials.alphaMaterials.PoweredRail.ID, pymclevel.materials.alphaMaterials.DetectorRail.ID] renderstate = ChunkCalculator.renderstateAlphaTest - railTextures = array([ + railTextures = numpy.array([ [(0, 128), (0, 144), (16, 144), (16, 128)], # east-west [(0, 128), (16, 128), (16, 144), (0, 144)], # north-south [(0, 128), (16, 128), (16, 144), (0, 144)], # south-ascending @@ -1523,9 +1504,9 @@ class RailBlockRenderer(BlockRenderer): [(0, 192), (0, 208), (16, 208), (16, 192)], # unknown ], dtype='float32') - railTextures -= alphaMaterials.blockTextures[alphaMaterials.Rail.ID, 0, 0] + railTextures -= pymclevel.materials.alphaMaterials.blockTextures[pymclevel.materials.alphaMaterials.Rail.ID, 0, 0] - railOffsets = array([ + railOffsets = numpy.array([ [0, 0, 0, 0], [0, 0, 0, 0], @@ -1549,16 +1530,16 @@ class RailBlockRenderer(BlockRenderer): ], dtype='float32') def makeRailVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, areaBlockLights, texMap): - direction = FaceYIncreasing + direction = pymclevel.faces.FaceYIncreasing blockIndices = self.getMaterialIndices(blockMaterials) yield bdata = blockData[blockIndices] railBlocks = blocks[blockIndices] - tex = texMap(railBlocks, bdata, FaceYIncreasing)[:, newaxis, :] + tex = texMap(railBlocks, bdata, pymclevel.faces.FaceYIncreasing)[:, numpy.newaxis, :] # disable 'powered' or 'pressed' bit for powered and detector rails - bdata[railBlocks != alphaMaterials.Rail.ID] &= ~0x8 + bdata[railBlocks != pymclevel.materials.alphaMaterials.Rail.ID] &= ~0x8 vertexArray = self.makeTemplate(direction, blockIndices) if not len(vertexArray): @@ -1572,7 +1553,7 @@ def makeRailVertices(self, facingBlockIndices, blocks, blockMaterials, blockData blockLight = areaBlockLights[1:-1, 1:-1, 1:-1] - vertexArray.view('uint8')[_RGB] *= blockLight[blockIndices][..., newaxis, newaxis] + vertexArray.view('uint8')[_RGB] *= blockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] yield self.vertexArrays = [vertexArray] @@ -1580,9 +1561,9 @@ def makeRailVertices(self, facingBlockIndices, blocks, blockMaterials, blockData class LadderBlockRenderer(BlockRenderer): - blocktypes = [alphaMaterials.Ladder.ID] + blocktypes = [pymclevel.materials.alphaMaterials.Ladder.ID] - ladderOffsets = array([ + ladderOffsets = numpy.array([ [(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], [(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], @@ -1593,7 +1574,7 @@ class LadderBlockRenderer(BlockRenderer): ] + [[(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)]] * 10, dtype='float32') - ladderTextures = array([ + ladderTextures = numpy.array([ [(0, 192), (0, 208), (16, 208), (16, 192)], # unknown [(0, 192), (0, 208), (16, 208), (16, 192)], # unknown @@ -1610,13 +1591,13 @@ def ladderVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, yield bdata = blockData[blockIndices] - vertexArray = self.makeTemplate(FaceYIncreasing, blockIndices) + vertexArray = self.makeTemplate(pymclevel.faces.FaceYIncreasing, blockIndices) if not len(vertexArray): return vertexArray[_ST] = self.ladderTextures[bdata] vertexArray[_XYZ] += self.ladderOffsets[bdata] - vertexArray.view('uint8')[_RGB] *= blockLight[blockIndices][..., newaxis, newaxis] + vertexArray.view('uint8')[_RGB] *= blockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] yield self.vertexArrays = [vertexArray] @@ -1637,25 +1618,25 @@ def makeSnowVertices(self, facingBlockIndices, blocks, blockMaterials, blockData # def makeFaceVertices(self, direction, blockIndices, exposedFaceIndices, blocks, blockData, blockLight, facingBlockLight, texMap): # return [] - if direction != FaceYIncreasing: + if direction != pymclevel.faces.FaceYIncreasing: blockIndices = snowIndices & exposedFaceIndices else: blockIndices = snowIndices facingBlockLight = areaBlockLights[self.directionOffsets[direction]] - lights = facingBlockLight[blockIndices][..., newaxis, newaxis] + lights = facingBlockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] vertexArray = self.makeTemplate(direction, blockIndices) if not len(vertexArray): continue - vertexArray[_ST] += texMap([self.snowID], 0, 0)[:, newaxis, 0:2] + vertexArray[_ST] += texMap([self.snowID], 0, 0)[:, numpy.newaxis, 0:2] vertexArray.view('uint8')[_RGB] *= lights - if direction == FaceYIncreasing: + if direction == pymclevel.faces.FaceYIncreasing: vertexArray[_XYZ][..., 1] -= 0.875 - if direction != FaceYIncreasing and direction != FaceYDecreasing: + if direction != pymclevel.faces.FaceYIncreasing and direction != pymclevel.faces.FaceYDecreasing: vertexArray[_XYZ][..., 2:4, 1] -= 0.875 vertexArray[_ST][..., 2:4, 1] += 14 @@ -1672,11 +1653,11 @@ class RedstoneBlockRenderer(BlockRenderer): def redstoneVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, areaBlockLights, texMap): blockIndices = self.getMaterialIndices(blockMaterials) yield - vertexArray = self.makeTemplate(FaceYIncreasing, blockIndices) + vertexArray = self.makeTemplate(pymclevel.faces.FaceYIncreasing, blockIndices) if not len(vertexArray): return - vertexArray[_ST] += alphaMaterials.blockTextures[55, 0, 0] + vertexArray[_ST] += pymclevel.materials.alphaMaterials.blockTextures[55, 0, 0] vertexArray[_XYZ][..., 1] -= 0.9 bdata = blockData[blockIndices] @@ -1685,7 +1666,7 @@ def redstoneVertices(self, facingBlockIndices, blocks, blockMaterials, blockData # bdata &= 0xe0 bdata[bdata > 0] |= 0x80 - vertexArray.view('uint8')[_RGBA][..., 0] = bdata[..., newaxis] + vertexArray.view('uint8')[_RGBA][..., 0] = bdata[..., numpy.newaxis] vertexArray.view('uint8')[_RGBA][..., 0:3] *= [1, 0, 0] yield @@ -1697,14 +1678,14 @@ def redstoneVertices(self, facingBlockIndices, blocks, blockMaterials, blockData class FeatureBlockRenderer(BlockRenderer): -# blocktypes = [alphaMaterials.Button.ID, -# alphaMaterials.StoneFloorPlate.ID, -# alphaMaterials.WoodFloorPlate.ID, -# alphaMaterials.WoodenDoor.ID, -# alphaMaterials.IronDoor.ID, +# blocktypes = [pymclevel.materials.alphaMaterials.Button.ID, +# pymclevel.materials.alphaMaterials.StoneFloorPlate.ID, +# pymclevel.materials.alphaMaterials.WoodFloorPlate.ID, +# pymclevel.materials.alphaMaterials.WoodenDoor.ID, +# pymclevel.materials.alphaMaterials.IronDoor.ID, # ] # - blocktypes = [alphaMaterials.Fence.ID] + blocktypes = [pymclevel.materials.alphaMaterials.Fence.ID] buttonOffsets = [ [[-14 / 16., 6 / 16., -5 / 16.], @@ -1740,23 +1721,23 @@ class FeatureBlockRenderer(BlockRenderer): [-14 / 16., -7 / 16., 5 / 16.], ], ] - buttonOffsets = array(buttonOffsets) + buttonOffsets = numpy.array(buttonOffsets) buttonOffsets[buttonOffsets < 0] += 1.0 dirIndexes = ((3, 2), (-3, 2), (1, 3), (1, 3), (-1, 2), (1, 2)) def buttonVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, areaBlockLights, texMap): - blockIndices = blocks == alphaMaterials.Button.ID + blockIndices = blocks == pymclevel.materials.alphaMaterials.Button.ID axes = blockIndices.nonzero() - vertexArray = zeros((len(axes[0]), 6, 4, 6), dtype=float32) - vertexArray[_XYZ][..., 0] = axes[0][..., newaxis, newaxis] - vertexArray[_XYZ][..., 1] = axes[2][..., newaxis, newaxis] - vertexArray[_XYZ][..., 2] = axes[1][..., newaxis, newaxis] + vertexArray = numpy.zeros((len(axes[0]), 6, 4, 6), dtype=numpy.float32) + vertexArray[_XYZ][..., 0] = axes[0][..., numpy.newaxis, numpy.newaxis] + vertexArray[_XYZ][..., 1] = axes[2][..., numpy.newaxis, numpy.newaxis] + vertexArray[_XYZ][..., 2] = axes[1][..., numpy.newaxis, numpy.newaxis] vertexArray[_XYZ] += self.buttonOffsets vertexArray[_ST] = [[0, 0], [0, 16], [16, 16], [16, 0]] - vertexArray[_ST] += texMap(alphaMaterials.Stone.ID, 0)[newaxis, :, newaxis] + vertexArray[_ST] += texMap(pymclevel.materials.alphaMaterials.Stone.ID, 0)[numpy.newaxis, :, numpy.newaxis] # if direction == 0: # for i, j in enumerate(self.dirIndexes[direction]): @@ -1784,22 +1765,22 @@ def buttonVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, fenceTemplates = makeVertexTemplates(3 / 8., 0, 3 / 8., 5 / 8., 1, 5 / 8.) def fenceVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, areaBlockLights, texMap): - fenceMask = blocks == alphaMaterials.Fence.ID + fenceMask = blocks == pymclevel.materials.alphaMaterials.Fence.ID fenceIndices = fenceMask.nonzero() yield - vertexArray = zeros((len(fenceIndices[0]), 6, 4, 6), dtype='float32') + vertexArray = numpy.zeros((len(fenceIndices[0]), 6, 4, 6), dtype='float32') for i in range(3): j = (0, 2, 1)[i] - vertexArray[..., i] = fenceIndices[j][:, newaxis, newaxis] # xxx swap z with y using ^ + vertexArray[..., i] = fenceIndices[j][:, numpy.newaxis, numpy.newaxis] # xxx swap z with y using ^ vertexArray[..., 0:5] += self.fenceTemplates[..., 0:5] - vertexArray[_ST] += alphaMaterials.blockTextures[alphaMaterials.WoodPlanks.ID, 0, 0] + vertexArray[_ST] += pymclevel.materials.alphaMaterials.blockTextures[pymclevel.materials.alphaMaterials.WoodPlanks.ID, 0, 0] - vertexArray.view('uint8')[_RGBA] = self.fenceTemplates[..., 5][..., newaxis] + vertexArray.view('uint8')[_RGBA] = self.fenceTemplates[..., 5][..., numpy.newaxis] - vertexArray.view('uint8')[_RGB] *= areaBlockLights[1:-1, 1:-1, 1:-1][fenceIndices][..., newaxis, newaxis, newaxis] + vertexArray.view('uint8')[_RGB] *= areaBlockLights[1:-1, 1:-1, 1:-1][fenceIndices][..., numpy.newaxis, numpy.newaxis, numpy.newaxis] vertexArray.shape = (vertexArray.shape[0] * 6, 4, 6) yield self.vertexArrays = [vertexArray] @@ -1816,7 +1797,7 @@ def getBlocktypes(cls, mats): # North - FaceXDecreasing # West - FaceZIncreasing # East - FaceZDecreasing - stairTemplates = array([makeVertexTemplates(**kw) for kw in [ + stairTemplates = numpy.array([makeVertexTemplates(**kw) for kw in [ # South - FaceXIncreasing {"xmin":0.5}, # North - FaceXDecreasing @@ -1841,9 +1822,9 @@ def stairVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, a x, z, y = materialIndices.nonzero() for _ in ("slab", "step"): - vertexArray = zeros((len(x), 6, 4, 6), dtype='float32') + vertexArray = numpy.zeros((len(x), 6, 4, 6), dtype='float32') for i in range(3): - vertexArray[_XYZ][..., i] = (x, y, z)[i][:, newaxis, newaxis] + vertexArray[_XYZ][..., i] = (x, y, z)[i][:, numpy.newaxis, numpy.newaxis] if _ == "step": vertexArray[_XYZST] += self.stairTemplates[4][..., :5] @@ -1851,9 +1832,9 @@ def stairVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, a else: vertexArray[_XYZST] += self.stairTemplates[stairData][..., :5] - vertexArray[_ST] += texMap(stairBlocks, 0)[..., newaxis, :] + vertexArray[_ST] += texMap(stairBlocks, 0)[..., numpy.newaxis, :] - vertexArray.view('uint8')[_RGB] = self.stairTemplates[4][newaxis, ..., 5, newaxis] + vertexArray.view('uint8')[_RGB] = self.stairTemplates[4][numpy.newaxis, ..., 5, numpy.newaxis] vertexArray.view('uint8')[_RGB] *= 0xf vertexArray.view('uint8')[_A] = 0xff @@ -1870,23 +1851,23 @@ class SlabBlockRenderer(BlockRenderer): blocktypes = [slabID] def slabFaceVertices(self, direction, blockIndices, exposedFaceIndices, blocks, blockData, blockLight, facingBlockLight, texMap): - if direction != FaceYIncreasing: + if direction != pymclevel.faces.FaceYIncreasing: blockIndices = blockIndices & exposedFaceIndices - lights = facingBlockLight[blockIndices][..., newaxis, newaxis] + lights = facingBlockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] bdata = blockData[blockIndices] vertexArray = self.makeTemplate(direction, blockIndices) if not len(vertexArray): return vertexArray - vertexArray[_ST] += texMap(self.slabID, bdata, direction)[:, newaxis, 0:2] + vertexArray[_ST] += texMap(self.slabID, bdata, direction)[:, numpy.newaxis, 0:2] vertexArray.view('uint8')[_RGB] *= lights - if direction == FaceYIncreasing: + if direction == pymclevel.faces.FaceYIncreasing: vertexArray[_XYZ][..., 1] -= 0.5 - if direction != FaceYIncreasing and direction != FaceYDecreasing: + if direction != pymclevel.faces.FaceYIncreasing and direction != pymclevel.faces.FaceYDecreasing: vertexArray[_XYZ][..., 2:4, 1] -= 0.5 vertexArray[_ST][..., 2:4, 1] += 8 @@ -1903,8 +1884,8 @@ class WaterBlockRenderer(BlockRenderer): def waterFaceVertices(self, direction, blockIndices, exposedFaceIndices, blocks, blockData, blockLight, facingBlockLight, texMap): blockIndices = blockIndices & exposedFaceIndices vertexArray = self.makeTemplate(direction, blockIndices) - vertexArray[_ST] += texMap(self.waterID, 0, 0)[newaxis, newaxis] - vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., newaxis, newaxis] + vertexArray[_ST] += texMap(self.waterID, 0, 0)[numpy.newaxis, numpy.newaxis] + vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] return vertexArray makeFaceVertices = waterFaceVertices @@ -1918,8 +1899,8 @@ class IceBlockRenderer(BlockRenderer): def iceFaceVertices(self, direction, blockIndices, exposedFaceIndices, blocks, blockData, blockLight, facingBlockLight, texMap): blockIndices = blockIndices & exposedFaceIndices vertexArray = self.makeTemplate(direction, blockIndices) - vertexArray[_ST] += texMap(self.iceID, 0, 0)[newaxis, newaxis] - vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., newaxis, newaxis] + vertexArray[_ST] += texMap(self.iceID, 0, 0)[numpy.newaxis, numpy.newaxis] + vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] return vertexArray makeFaceVertices = iceFaceVertices @@ -2034,8 +2015,8 @@ def chunkDistance(self, cpos): camx -= ox camz -= oz - camcx = int(floor(camx)) >> 4 - camcz = int(floor(camz)) >> 4 + camcx = int(numpy.floor(camx)) >> 4 + camcz = int(numpy.floor(camz)) >> 4 cx, cz = cpos @@ -2193,8 +2174,8 @@ def discardChunksOutsideViewDistance(self): return (ox, oz) = origin bytes = 0 - # chunks = fromiter(self.chunkRenderers.iterkeys(), dtype='int32', count=len(self.chunkRenderers)) - chunks = fromiter(self.chunkRenderers.iterkeys(), dtype='i,i', count=len(self.chunkRenderers)) + # chunks = numpy.fromiter(self.chunkRenderers.iterkeys(), dtype='int32', count=len(self.chunkRenderers)) + chunks = numpy.fromiter(self.chunkRenderers.iterkeys(), dtype='i,i', count=len(self.chunkRenderers)) chunks.dtype = 'int32' chunks.shape = len(self.chunkRenderers), 2 @@ -2272,7 +2253,7 @@ def invalidateChunk(self, cx, cz, layers=None): self.invalidChunkQueue.append((cx, cz)) # xxx encapsulate def invalidateChunksInBox(self, box, layers=None): - box = BoundingBox(box) + box = pymclevel.BoundingBox(box) if box.minx & 0xf == 0: box.minx -= 1 if box.miny & 0xf == 0: @@ -2379,12 +2360,12 @@ def makeFloorTex(self): color0 = (0xff, 0xff, 0xff, 0x22) color1 = (0xff, 0xff, 0xff, 0x44) - img = array([color0, color1, color1, color0], dtype='uint8') + img = numpy.array([color0, color1, color1, color0], dtype='uint8') - GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) - GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) + OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, OpenGL.GL.GL_TEXTURE_MIN_FILTER, OpenGL.GL.GL_NEAREST) + OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, OpenGL.GL.GL_TEXTURE_MAG_FILTER, OpenGL.GL.GL_NEAREST) - GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, 2, 2, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, img) + OpenGL.GL.glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, 0, OpenGL.GL.GL_RGBA, 2, 2, 0, OpenGL.GL.GL_RGBA, OpenGL.GL.GL_UNSIGNED_BYTE, img) def invalidateChunkMarkers(self): self.loadableChunkMarkers.invalidate() @@ -2395,54 +2376,54 @@ def _drawLoadableChunkMarkers(self): sizedChunks = chunkMarkers(chunkSet) - glPushAttrib(GL_FOG_BIT) - glDisable(GL_FOG) + OpenGL.GL.glPushAttrib(OpenGL.GL.GL_FOG_BIT) + OpenGL.GL.glDisable(OpenGL.GL.GL_FOG) - glEnable(GL_BLEND) - glEnable(GL_POLYGON_OFFSET_FILL) - glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) - glEnable(GL_DEPTH_TEST) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) - glEnableClientState(GL_TEXTURE_COORD_ARRAY) - glEnable(GL_TEXTURE_2D) - glColor(1.0, 1.0, 1.0, 1.0) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glColor(1.0, 1.0, 1.0, 1.0) self.floorTexture.bind() - # chunkColor = zeros(shape=(chunks.shape[0], 4, 4), dtype='float32') + # chunkColor = numpy.zeros(shape=(chunks.shape[0], 4, 4), dtype='float32') # chunkColor[:]= (1, 1, 1, 0.15) # -# cc = array(chunks[:,0] + chunks[:,1], dtype='int32') +# cc = numpy.array(chunks[:,0] + chunks[:,1], dtype='int32') # cc &= 1 # coloredChunks = cc > 0 # chunkColor[coloredChunks] = (1, 1, 1, 0.28) # chunkColor *= 255 -# chunkColor = array(chunkColor, dtype='uint8') +# chunkColor = numpy.array(chunkColor, dtype='uint8') # - # glColorPointer(4, GL_UNSIGNED_BYTE, 0, chunkColor) + # OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, chunkColor) for size, chunks in sizedChunks.iteritems(): if not len(chunks): continue - chunks = array(chunks, dtype='float32') + chunks = numpy.array(chunks, dtype='float32') - chunkPosition = zeros(shape=(chunks.shape[0], 4, 3), dtype='float32') - chunkPosition[:, :, (0, 2)] = array(((0, 0), (0, 1), (1, 1), (1, 0)), dtype='float32') + chunkPosition = numpy.zeros(shape=(chunks.shape[0], 4, 3), dtype='float32') + chunkPosition[:, :, (0, 2)] = numpy.array(((0, 0), (0, 1), (1, 1), (1, 0)), dtype='float32') chunkPosition[:, :, (0, 2)] *= size - chunkPosition[:, :, (0, 2)] += chunks[:, newaxis, :] + chunkPosition[:, :, (0, 2)] += chunks[:, numpy.newaxis, :] chunkPosition *= 16 - glVertexPointer(3, GL_FLOAT, 0, chunkPosition.ravel()) + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, chunkPosition.ravel()) # chunkPosition *= 8 - glTexCoordPointer(2, GL_FLOAT, 0, (chunkPosition[..., (0, 2)] * 8).ravel()) - glDrawArrays(GL_QUADS, 0, len(chunkPosition) * 4) + OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, (chunkPosition[..., (0, 2)] * 8).ravel()) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(chunkPosition) * 4) - glDisableClientState(GL_TEXTURE_COORD_ARRAY) - glDisable(GL_TEXTURE_2D) - glDisable(GL_BLEND) - glDisable(GL_DEPTH_TEST) - glDisable(GL_POLYGON_OFFSET_FILL) - glPopAttrib() + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glPopAttrib() def drawLoadableChunkMarkers(self): - if not self.isPreviewer or isinstance(self.level, MCInfdevOldLevel): + if not self.isPreviewer or isinstance(self.level, pymclevel.MCInfdevOldLevel): self.loadableChunkMarkers.call(self._drawLoadableChunkMarkers) # self.drawCompressedChunkMarkers() @@ -2452,53 +2433,53 @@ def drawCompressedChunkMarkers(self): if 0 == len(chunkPositions): return - chunkPositions = array(chunkPositions) + chunkPositions = numpy.array(chunkPositions) chunkLoaded = [self.level.chunkIsLoaded(*c) for c in chunkPositions] - chunkLoaded = array(chunkLoaded, dtype='bool') + chunkLoaded = numpy.array(chunkLoaded, dtype='bool') chunkCompressed = [self.level.chunkIsCompressed(*c) for c in chunkPositions] - chunkCompressed = array(chunkCompressed, dtype='bool') + chunkCompressed = numpy.array(chunkCompressed, dtype='bool') chunkDirty = [self.level.chunkIsDirty(*c) for c in chunkPositions] - chunkDirty = array(chunkDirty, dtype='bool') + chunkDirty = numpy.array(chunkDirty, dtype='bool') - vertexBuffer = zeros((len(chunkPositions), 4, 3), dtype='float32') + vertexBuffer = numpy.zeros((len(chunkPositions), 4, 3), dtype='float32') - vertexBuffer[..., (0, 2)] = array(((0, 0), (0, 1), (1, 1), (1, 0)), dtype='float32') + vertexBuffer[..., (0, 2)] = numpy.array(((0, 0), (0, 1), (1, 1), (1, 0)), dtype='float32') - vertexBuffer[..., (0, 2)] += chunkPositions[:, newaxis] + vertexBuffer[..., (0, 2)] += chunkPositions[:, numpy.newaxis] vertexBuffer[..., (0, 2)] *= 16 vertexBuffer[..., 1] = 128 - colorBuffer = zeros((len(chunkCompressed), 4, 4), dtype='uint8') + colorBuffer = numpy.zeros((len(chunkCompressed), 4, 4), dtype='uint8') colorBuffer[:] = (0x00, 0x00, 0x00, 0x33) colorBuffer[chunkLoaded] = (0xff, 0xff, 0xff, 0x66) colorBuffer[chunkCompressed] = (0xff, 0xFF, 0x00, 0x66) colorBuffer[chunkDirty] = (0xff, 0x00, 0x00, 0x66) - cc = array(chunkPositions[:, 0] + chunkPositions[:, 1], dtype='int32') + cc = numpy.array(chunkPositions[:, 0] + chunkPositions[:, 1], dtype='int32') cc &= 1 coloredChunks = cc > 0 colorBuffer[coloredChunks] *= 0.75 - glEnable(GL_BLEND) - glEnable(GL_POLYGON_OFFSET_FILL) - glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) - glEnable(GL_DEPTH_TEST) - glEnableClientState(GL_COLOR_ARRAY) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) - glVertexPointer(3, GL_FLOAT, 0, vertexBuffer) - glColorPointer(4, GL_UNSIGNED_BYTE, 0, colorBuffer) - glDrawArrays(GL_QUADS, 0, len(vertexBuffer) * 4) + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, vertexBuffer) + OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, colorBuffer) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(vertexBuffer) * 4) - glDisableClientState(GL_COLOR_ARRAY) + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) - glDisable(GL_POLYGON_OFFSET_FILL) - glDisable(GL_DEPTH_TEST) + OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) - glDisable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) needsImmediateRedraw = False viewingFrustum = None @@ -2531,7 +2512,7 @@ def createMasterLists(self): for rs in chunkLists: if len(chunkLists[rs]): - lists[rs] = array(chunkLists[rs], dtype='uint32').ravel() + lists[rs] = numpy.array(chunkLists[rs], dtype='uint32').ravel() # lists = lists[lists.nonzero()] self.masterLists = lists @@ -2544,14 +2525,14 @@ def callMasterLists(self): continue if self.alpha != 0xff and renderstate is not ChunkCalculator.renderstateLowDetail: - glEnable(GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) renderstate.bind() - glCallLists(self.masterLists[renderstate]) + OpenGL.GL.glCallLists(self.masterLists[renderstate]) renderstate.release() if self.alpha != 0xff and renderstate is not ChunkCalculator.renderstateLowDetail: - glDisable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) errorLimit = 10 @@ -2566,38 +2547,38 @@ def draw(self): chunksDrawn = 0 - with gl.glPushMatrix(GL_MODELVIEW): + with gl.glPushMatrix(OpenGL.GL.GL_MODELVIEW): dx, dy, dz = self.origin - glTranslate(dx, dy, dz) + OpenGL.GL.glTranslate(dx, dy, dz) - glEnable(GL_CULL_FACE) - glEnable(GL_DEPTH_TEST) + OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) self.level.materials.terrainTexture.bind() - glEnable(GL_TEXTURE_2D) - glEnableClientState(GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) offset = DepthOffset.PreviewRenderer if self.isPreviewer else DepthOffset.Renderer - glPolygonOffset(offset, offset) - glEnable(GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glPolygonOffset(offset, offset) + OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) self.createMasterLists() try: self.callMasterLists() - except GLError, e: + except OpenGL.GL.GLError, e: if self.errorLimit: self.errorLimit -= 1 traceback.print_exc() print e - glDisable(GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) - glDisable(GL_CULL_FACE) - glDisable(GL_DEPTH_TEST) + OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) - glDisable(GL_TEXTURE_2D) - glDisableClientState(GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) # if self.drawLighting: self.drawLoadableChunkMarkers() @@ -2698,7 +2679,7 @@ def workOnChunk(self, c): if self.level.containsChunk(*c): cr = self.getChunkRenderer(c) if self.viewingFrustum: - # if not self.viewingFrustum.visible(array([[c[0] * 16 + 8, 64, c[1] * 16 + 8, 1.0]]), 64).any(): + # if not self.viewingFrustum.visible(numpy.array([[c[0] * 16 + 8, 64, c[1] * 16 + 8, 1.0]]), 64).any(): if not self.viewingFrustum.visible1([c[0] * 16 + 8, self.level.Height / 2, c[1] * 16 + 8, 1.0], self.level.Height / 2): raise StopIteration yield @@ -2719,7 +2700,7 @@ def workOnChunk(self, c): except Exception: fn = c - info(u"Skipped chunk {f}: {e}".format(e=e, f=fn)) + logging.info(u"Skipped chunk {f}: {e}".format(e=e, f=fn)) redrawChunks = 0 @@ -2763,7 +2744,7 @@ class PreviewRenderer(MCRenderer): def rendermain(): renderer = MCRenderer() - renderer.level = mclevel.loadWorld("World1") + renderer.level = pymclevel.mclevel.loadWorld("World1") renderer.viewDistance = 6 renderer.detailLevelForChunk = lambda * x: 0 start = datetime.now() @@ -2786,33 +2767,33 @@ def rendermain(): # display.init( (640, 480), OPENGL | DOUBLEBUF ) from mcedit import GLDisplayContext - from OpenGL import GLU + #from OpenGL import GLU cxt = GLDisplayContext() import pygame # distance = 4000 - glMatrixMode(GL_PROJECTION) - glLoadIdentity() - GLU.gluPerspective(35, 640.0 / 480.0, 0.5, 4000.0) + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) + OpenGL.GL.glLoadIdentity() + OpenGL.GLU.gluPerspective(35, 640.0 / 480.0, 0.5, 4000.0) h = 366 pos = (0, h, 0) look = (0.0001, h - 1, 0.0001) up = (0, 1, 0) - GL.glMatrixMode(GL_MODELVIEW) - GL.glLoadIdentity() + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) + OpenGL.GL.glLoadIdentity() - GLU.gluLookAt(pos[0], pos[1], pos[2], + OpenGL.GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) - glClearColor(0.0, 0.0, 0.0, 1.0) + OpenGL.GL.glClearColor(0.0, 0.0, 0.0, 1.0) framestart = datetime.now() frames = 200 for i in range(frames): - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) + OpenGL.GL.glClear(OpenGL.GL.GL_COLOR_BUFFER_BIT | OpenGL.GL.GL_DEPTH_BUFFER_BIT) renderer.draw() pygame.display.flip() @@ -2824,7 +2805,7 @@ def rendermain(): evt = pygame.event.poll() if evt.type == pygame.MOUSEBUTTONDOWN: break - # sleep(3.0) + # time.sleep(3.0) import traceback From e043aa4b7a72672728be60bcf8dd9f1e72d76219 Mon Sep 17 00:00:00 2001 From: David Sowder Date: Wed, 14 Mar 2012 19:41:38 -0500 Subject: [PATCH 2/8] Fix bad search/replace error for blockMaterials.clip() identified by codewarrior0 --- renderer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/renderer.py b/renderer.py index cf0ef82..3873c45 100644 --- a/renderer.py +++ b/renderer.py @@ -658,7 +658,7 @@ def computeGeometry(self, chunk, areaBlockMats, facingBlockIndices, areaBlockLig blockData = blockData & 0xf blockMaterials = areaBlockMats[1:-1, 1:-1, 1:-1] if self.roughGraphics: - blockMaterials.numpy.clip(0, 1, blockMaterials) + blockMaterials.clip(0, 1, blockMaterials) sx = sz = slice(0, 16) asx = asz = slice(0, 18) From 8b1d869c3353da8b9b1c630181586f0bbae2938e Mon Sep 17 00:00:00 2001 From: David Sowder Date: Fri, 16 Mar 2012 08:30:51 -0500 Subject: [PATCH 3/8] shuffle module import style for OpenGL to import the module instead of the package in a few files --- frustum.py | 12 +-- leveleditor.py | 253 +++++++++++++++++++++++++------------------------ renderer.py | 252 ++++++++++++++++++++++++------------------------ 3 files changed, 259 insertions(+), 258 deletions(-) diff --git a/frustum.py b/frustum.py index ef58b98..6298024 100644 --- a/frustum.py +++ b/frustum.py @@ -12,7 +12,7 @@ import logging import numpy -import OpenGL.GL +from OpenGL import GL context_log = logging.getLogger() @@ -31,9 +31,9 @@ def viewingMatrix(projection=None, model=None): matrix, the function will raise a RuntimeError """ if projection is None: - projection = OpenGL.GL.glGetDoublev(OpenGL.GL.GL_PROJECTION_MATRIX) + projection = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) if model is None: - model = OpenGL.GL.glGetDoublev(OpenGL.GL.GL_MODELVIEW_MATRIX) + model = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) # hmm, this will likely fail on 64-bit platforms :( if projection is None or model is None: context_log.warn( @@ -85,15 +85,15 @@ def visible(self, points, radius): frustcullaccel C extension module) """ - distances = sum(self.planes[OpenGL.GL.newaxis, :, :] * points[:, OpenGL.GL.newaxis, :], -1) + distances = sum(self.planes[GL.newaxis, :, :] * points[:, GL.newaxis, :], -1) return ~any(distances < -radius, -1) def visible1(self, point, radius): - #return self.visible(array(point[OpenGL.GL.newaxis, :]), radius) + #return self.visible(array(point[GL.newaxis, :]), radius) distance = sum(self.planes * point, -1) vis = ~any(distance < -radius) - #assert vis == self.visible(array(point)[OpenGL.GL.newaxis, :], radius) + #assert vis == self.visible(array(point)[GL.newaxis, :], radius) return vis diff --git a/leveleditor.py b/leveleditor.py index 653e87d..dbd5e8a 100644 --- a/leveleditor.py +++ b/leveleditor.py @@ -49,7 +49,8 @@ import mcplatform from mcplatform import askSaveFile import numpy -import OpenGL +from OpenGL import GL +from OpenGL import GLU # from OpenGL.GLUT import glutBitmapCharacter, GLUT_BITMAP_HELVETICA_18 import os from os.path import dirname, isdir @@ -198,7 +199,7 @@ def key_down(self, evt): def unproject(x, y, z): try: - return OpenGL.GLU.gluUnProject(x, y, z) + return GLU.gluUnProject(x, y, z) except ValueError: # projection failed return 0, 0, 0 @@ -404,7 +405,7 @@ def setModelview(self): look = numpy.array(self.cameraPosition) look += self.cameraVector up = (0, 1, 0) - OpenGL.GLU.gluLookAt(pos[0], pos[1], pos[2], + GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) @@ -449,9 +450,9 @@ def _blockUnderCursor(self, center=False): """ try: if Settings.doubleBuffer.get(): - OpenGL.GL.glReadBuffer(OpenGL.GL.GL_BACK) + GL.glReadBuffer(GL.GL_BACK) else: - OpenGL.GL.glReadBuffer(OpenGL.GL.GL_FRONT) + GL.glReadBuffer(GL.GL_FRONT) except Exception, e: print "Exception during glReadBuffer: {0!r}".format(e) ws = self.get_root().size @@ -468,7 +469,7 @@ def _blockUnderCursor(self, center=False): y = ws[1] - y try: - pixel = OpenGL.GL.glReadPixels(x, y, 1, 1, OpenGL.GL.GL_DEPTH_COMPONENT, OpenGL.GL.GL_FLOAT) + pixel = GL.glReadPixels(x, y, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT) newpoint = unproject(x, y, pixel[0]) except Exception, e: # print e @@ -1087,25 +1088,25 @@ def _drawCeiling(self): lines.append((minx, 0, z)) lines.append((maxx, 0, z)) - OpenGL.GL.glColor(0.3, 0.7, 0.9) - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(lines, dtype='float32')) + GL.glColor(0.3, 0.7, 0.9) + GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(lines, dtype='float32')) - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) - OpenGL.GL.glDepthMask(False) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_LINES, 0, len(lines)) - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) - OpenGL.GL.glDepthMask(True) + GL.glEnable(GL.GL_DEPTH_TEST) + GL.glDepthMask(False) + GL.glDrawArrays(GL.GL_LINES, 0, len(lines)) + GL.glDisable(GL.GL_DEPTH_TEST) + GL.glDepthMask(True) def drawCeiling(self): - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) - # OpenGL.GL.glPushMatrix() + GL.glMatrixMode(GL.GL_MODELVIEW) + # GL.glPushMatrix() x, y, z = self.cameraPosition x -= x % 16 z -= z % 16 y = self.editor.level.Height - OpenGL.GL.glTranslate(x, y, z) + GL.glTranslate(x, y, z) self.ceilingList.call(self._drawCeiling) - OpenGL.GL.glTranslate(-x, -y, -z) + GL.glTranslate(-x, -y, -z) _floorQuadList = None @@ -1133,12 +1134,12 @@ def floorColor(self): # floorColor = (0.0, 0.0, 1.0, 0.1) def _drawFloorQuad(self): - OpenGL.GL.glDepthMask(True) - OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, self.floorQuad) - OpenGL.GL.glColor(*self.floorColor) - with gl.glEnable(OpenGL.GL.GL_BLEND, OpenGL.GL.GL_DEPTH_TEST, OpenGL.GL.GL_POLYGON_OFFSET_FILL): - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) + GL.glDepthMask(True) + GL.glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) + GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.floorQuad) + GL.glColor(*self.floorColor) + with gl.glEnable(GL.GL_BLEND, GL.GL_DEPTH_TEST, GL.GL_POLYGON_OFFSET_FILL): + GL.glDrawArrays(GL.GL_QUADS, 0, 4) @property def drawSky(self): @@ -1160,13 +1161,13 @@ def drawSkyBackground(self): self.skyList.call(self._drawSkyBackground) def _drawSkyBackground(self): - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) - OpenGL.GL.glPushMatrix() - OpenGL.GL.glLoadIdentity() - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) - OpenGL.GL.glPushMatrix() - OpenGL.GL.glLoadIdentity() - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) + GL.glMatrixMode(GL.GL_MODELVIEW) + GL.glPushMatrix() + GL.glLoadIdentity() + GL.glMatrixMode(GL.GL_PROJECTION) + GL.glPushMatrix() + GL.glLoadIdentity() + GL.glEnableClientState(GL.GL_COLOR_ARRAY) quad = numpy.array([-1, -1, -1, 1, 1, 1, 1, -1], dtype='float32') colors = numpy.array([0x48, 0x49, 0xBA, 0xff, @@ -1178,20 +1179,20 @@ def _drawSkyBackground(self): if alpha > 0.0: if alpha < 1.0: - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + GL.glEnable(GL.GL_BLEND) - OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, quad) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, colors) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) + GL.glVertexPointer(2, GL.GL_FLOAT, 0, quad) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, 0, colors) + GL.glDrawArrays(GL.GL_QUADS, 0, 4) if alpha < 1.0: - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_BLEND) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) - OpenGL.GL.glPopMatrix() - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) - OpenGL.GL.glPopMatrix() + GL.glDisableClientState(GL.GL_COLOR_ARRAY) + GL.glMatrixMode(GL.GL_PROJECTION) + GL.glPopMatrix() + GL.glMatrixMode(GL.GL_MODELVIEW) + GL.glPopMatrix() enableMouseLag = Settings.enableMouseLag.configProperty() @@ -1207,16 +1208,16 @@ def drawFog(self, val): fogColorBlack = numpy.array([0.0, 0.0, 0.0, 1.0], dtype='float32') def enableFog(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_FOG) + GL.glEnable(GL.GL_FOG) if self.drawSky: - OpenGL.GL.glFogfv(OpenGL.GL.GL_FOG_COLOR, self.fogColor) + GL.glFogfv(GL.GL_FOG_COLOR, self.fogColor) else: - OpenGL.GL.glFogfv(OpenGL.GL.GL_FOG_COLOR, self.fogColorBlack) + GL.glFogfv(GL.GL_FOG_COLOR, self.fogColorBlack) - OpenGL.GL.glFogf(OpenGL.GL.GL_FOG_DENSITY, 0.002) + GL.glFogf(GL.GL_FOG_DENSITY, 0.002) def disableFog(self): - OpenGL.GL.glDisable(OpenGL.GL.GL_FOG) + GL.glDisable(GL.GL_FOG) def getCameraPoint(self): distance = self.editor.currentTool.cameraDistance @@ -1232,7 +1233,7 @@ def setup_projection(self): distance = 1.0 if self.editor.renderer.inSpace(): distance = 8.0 - OpenGL.GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) + GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) def setup_modelview(self): self.setModelview() @@ -1307,13 +1308,13 @@ def setup_projection(self): minx, maxx = - w, w miny, maxy = - h, h minz, maxz = -4000, 4000 - OpenGL.GL.glOrtho(minx, maxx, miny, maxy, minz, maxz) + GL.glOrtho(minx, maxx, miny, maxy, minz, maxz) def setup_modelview(self): x, y, z = self.cameraPosition - OpenGL.GL.glRotate(90.0, 1.0, 0.0, 0.0) - OpenGL.GL.glTranslate(-x, 0, -z) + GL.glRotate(90.0, 1.0, 0.0, 0.0) + GL.glTranslate(-x, 0, -z) def zoom(self, f): x, y, z = self.cameraPosition @@ -1834,13 +1835,13 @@ def reloadToolbar(self): longDistanceMode = Settings.longDistanceMode.configProperty() def genSixteenBlockTexture(self): - has12 = OpenGL.GL.glGetString(OpenGL.GL.GL_VERSION) >= "1.2" + has12 = GL.glGetString(GL.GL_VERSION) >= "1.2" if has12: maxLevel = 2 - mode = OpenGL.GL.GL_LINEAR_MIPMAP_NEAREST + mode = GL.GL_LINEAR_MIPMAP_NEAREST else: maxLevel = 1 - mode = OpenGL.GL.GL_LINEAR + mode = GL.GL_LINEAR def makeSixteenBlockTex(): darkColor = (0x30, 0x30, 0x30, 0xff) @@ -1855,11 +1856,11 @@ def makeSixteenBlockTex(): teximage[-1:] = darkColor teximage[:, -1:] = darkColor teximage[:, :2] = darkColor - # OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, - # OpenGL.GL.GL_TEXTURE_MIN_FILTER, - # OpenGL.GL.GL_NEAREST_MIPMAP_NEAREST), - OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, - OpenGL.GL.GL_TEXTURE_MAX_LEVEL, + # GL.glTexParameter(GL.GL_TEXTURE_2D, + # GL.GL_TEXTURE_MIN_FILTER, + # GL.GL_NEAREST_MIPMAP_NEAREST), + GL.glTexParameter(GL.GL_TEXTURE_2D, + GL.GL_TEXTURE_MAX_LEVEL, maxLevel - 1) for lev in range(maxLevel): @@ -1872,9 +1873,9 @@ def makeSixteenBlockTex(): teximage[:, -1:] = darkColor teximage[:, :2] = darkColor - OpenGL.GL.glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, lev, OpenGL.GL.GL_RGBA8, + GL.glTexImage2D(GL.GL_TEXTURE_2D, lev, GL.GL_RGBA8, w / step, h / step, 0, - OpenGL.GL.GL_RGBA, OpenGL.GL.GL_UNSIGNED_BYTE, + GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, teximage[::step, ::step].ravel()) return Texture(makeSixteenBlockTex, mode) @@ -1887,34 +1888,34 @@ def drawConstructionCube(self, box, color, texture=None): texture = self.sixteenBlockTex # textured cube faces - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) - OpenGL.GL.glDepthMask(False) + GL.glEnable(GL.GL_BLEND) + GL.glEnable(GL.GL_DEPTH_TEST) + GL.glDepthMask(False) # edges within terrain - OpenGL.GL.glDepthFunc(OpenGL.GL.GL_GREATER) + GL.glDepthFunc(GL.GL_GREATER) try: - OpenGL.GL.glColor(color[0], color[1], color[2], max(color[3], 0.35)) + GL.glColor(color[0], color[1], color[2], max(color[3], 0.35)) except IndexError: print color raise - OpenGL.GL.glLineWidth(1.0) - mceutils.drawCube(box, cubeType=OpenGL.GL.GL_LINE_STRIP) + GL.glLineWidth(1.0) + mceutils.drawCube(box, cubeType=GL.GL_LINE_STRIP) # edges on or outside terrain - OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LEQUAL) - OpenGL.GL.glColor(color[0], color[1], color[2], max(color[3] * 2, 0.75)) - OpenGL.GL.glLineWidth(2.0) - mceutils.drawCube(box, cubeType=OpenGL.GL.GL_LINE_STRIP) - - OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LESS) - OpenGL.GL.glColor(color[0], color[1], color[2], color[3]) - OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LEQUAL) + GL.glDepthFunc(GL.GL_LEQUAL) + GL.glColor(color[0], color[1], color[2], max(color[3] * 2, 0.75)) + GL.glLineWidth(2.0) + mceutils.drawCube(box, cubeType=GL.GL_LINE_STRIP) + + GL.glDepthFunc(GL.GL_LESS) + GL.glColor(color[0], color[1], color[2], color[3]) + GL.glDepthFunc(GL.GL_LEQUAL) mceutils.drawCube(box, texture=texture, selectionBox=True) - OpenGL.GL.glDepthMask(True) + GL.glDepthMask(True) - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + GL.glDisable(GL.GL_BLEND) + GL.glDisable(GL.GL_DEPTH_TEST) def loadFile(self, filename): if self.level and self.unsavedEdits > 0: @@ -2366,10 +2367,10 @@ def drawStars(self): self.mainViewport.cameraPosition = map(lambda x: x / 128.0, pos) self.mainViewport.setModelview() - OpenGL.GL.glColor(.5, .5, .5, 1.) + GL.glColor(.5, .5, .5, 1.) - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, self.starVertices) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(self.starVertices) / 3) + GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.starVertices) + GL.glDrawArrays(GL.GL_QUADS, 0, len(self.starVertices) / 3) self.mainViewport.cameraPosition = pos self.mainViewport.setModelview() @@ -2520,7 +2521,7 @@ def key_down(self, evt): # =========================================================== elif mods & KMOD_SHIFT: - raise OpenGL.GL.GLError(err=1285, description="User pressed CONTROL-SHIFT-F9, requesting a GL Memory Error") + raise GL.GLError(err=1285, description="User pressed CONTROL-SHIFT-F9, requesting a GL Memory Error") else: try: expr = input_text(">>> ", 600) @@ -3308,15 +3309,15 @@ def updateInspectionString(self, blockPosition): pass def drawWireCubeReticle(self, color=(1.0, 1.0, 1.0, 1.0), position=None): - OpenGL.GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) - OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) + GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) blockPosition, faceDirection = self.blockFaceUnderCursor blockPosition = position or blockPosition mceutils.drawTerrainCuttingWire(pymclevel.BoundingBox(blockPosition, (1, 1, 1)), c1=color) - OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) def drawString(self, x, y, color, string): return @@ -3324,18 +3325,18 @@ def drawString(self, x, y, color, string): def freezeStatus(self, string): return -# OpenGL.GL.glColor(1.0, 0., 0., 1.0) +# GL.glColor(1.0, 0., 0., 1.0) # -# # glDrawBuffer(OpenGL.GL.GL_FRONT) -# OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) -# OpenGL.GL.glPushMatrix() +# # glDrawBuffer(GL.GL_FRONT) +# GL.glMatrixMode(GL.GL_PROJECTION) +# GL.glPushMatrix() # glRasterPos(50, 100) # for i in string: # glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(i)) # -# # glDrawBuffer(OpenGL.GL.GL_BACK) -# OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) -# OpenGL.GL.glPopMatrix() +# # glDrawBuffer(GL.GL_BACK) +# GL.glMatrixMode(GL.GL_PROJECTION) +# GL.glPopMatrix() # glFlush() # display.flip() # # while(True): pass @@ -3431,17 +3432,17 @@ def idleHandler(evt): ## glBindTexture(GL_TEXTURE_3D, sourceTex) ## glTexImage3D(GL_TEXTURE_3D, 0, 1, ## level.Width, level.Length, level.Height, -## 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE, +## 0, GL_RED, GL.GL_UNSIGNED_BYTE, ## blocks) ## ## # return ## -## glBindTexture(OpenGL.GL.GL_TEXTURE_2D, destTex) -## glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, 0, 1, +## glBindTexture(GL.GL_TEXTURE_2D, destTex) +## glTexImage2D(GL.GL_TEXTURE_2D, 0, 1, ## level.Width, level.Length, -## 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE, destBlocks) -## glTexParameter(OpenGL.GL.GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) -## glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, OpenGL.GL.GL_TEXTURE_2D, destTex, 0) +## 0, GL_RED, GL.GL_UNSIGNED_BYTE, destBlocks) +## glTexParameter(GL.GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) +## glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL.GL_TEXTURE_2D, destTex, 0) ## ## vertShader = glCreateShader(GL_VERTEX_SHADER) ## @@ -3477,13 +3478,13 @@ def idleHandler(evt): ## ## glUseProgram(prog); ## # return -## OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST); -## OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]); -## OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4); -## OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST); +## GL.glDisable(GL.GL_DEPTH_TEST); +## GL.glVertexPointer(2, GL.GL_FLOAT, 0, [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]); +## GL.glDrawArrays(GL.GL_QUADS, 0, 4); +## GL.glEnable(GL.GL_DEPTH_TEST); ## ## glFlush(); -## destBlocks = glGetTexImage(OpenGL.GL.GL_TEXTURE_2D, 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE); +## destBlocks = glGetTexImage(GL.GL_TEXTURE_2D, 0, GL_RED, GL.GL_UNSIGNED_BYTE); ## print destBlocks, destBlocks[0:8]; ## raise SystemExit; @@ -3630,27 +3631,27 @@ def reloadTextures(self): tool.markerList.invalidate() def drawToolbar(self): - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) - OpenGL.GL.glColor(1., 1., 1., 1.) + GL.glColor(1., 1., 1., 1.) w, h = self.toolbarTextureSize self.guiTexture.bind() - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(( 1, h + 1, 0.5, w + 1, h + 1, 0.5, w + 1, 1, 0.5, 1, 1, 0.5, ), dtype="f4")) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, numpy.array(( 0, 0, w, 0, w, h, 0, h, ), dtype="f4")) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) + GL.glDrawArrays(GL.GL_QUADS, 0, 4) for i in range(len(self.tools)): tool = self.tools[i] @@ -3666,37 +3667,37 @@ def drawToolbar(self): h = 16 self.toolTextures[tool.toolIconName].bind() - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(( x, y + h, 1, x + w, y + h, 1, x + w, y, 1, x, y, 1, ), dtype="f4")) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, numpy.array(( 0, 0, w * 16, 0, w * 16, h * 16, 0, h * 16, ), dtype="f4")) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) + GL.glDrawArrays(GL.GL_QUADS, 0, 4) except Exception, e: print "Exception: {0!r}".format(e) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) gfont = None def gl_draw(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + GL.glEnable(GL.GL_TEXTURE_2D) + GL.glEnable(GL.GL_BLEND) self.toolbarDisplayList.call(self.drawToolbar) - OpenGL.GL.glColor(1.0, 1.0, 0.0) + GL.glColor(1.0, 1.0, 0.0) - # OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + # GL.glEnable(GL.GL_BLEND) # with gl.glPushMatrix(GL_TEXTURE): - # OpenGL.GL.glLoadIdentity() + # GL.glLoadIdentity() # self.gfont.flatPrint("ADLADLADLADLADL") try: @@ -3719,27 +3720,27 @@ def gl_draw(self): ty = 0. tw = 24. th = 24. - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) self.guiTexture.bind() - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(( tx, ty, 2, tx + tw, ty, 2, tx + tw, ty + th, 2, tx, ty + th, 2, ), dtype="f4")) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, numpy.array(( texx, texy + texh, texx + texw, texy + texh, texx + texw, texy, texx, texy, ), dtype="f4")) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) + GL.glDrawArrays(GL.GL_QUADS, 0, 4) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) - OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) + GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) + GL.glDisable(GL.GL_TEXTURE_2D) redOutBoxes = numpy.zeros(9 * 4 * 2, dtype='float32') cursor = 0 @@ -3756,8 +3757,8 @@ def gl_draw(self): cursor += 8 if cursor: - OpenGL.GL.glColor(1.0, 0.0, 0.0, 0.3) - OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, redOutBoxes) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, cursor / 2) + GL.glColor(1.0, 0.0, 0.0, 0.3) + GL.glVertexPointer(2, GL.GL_FLOAT, 0, redOutBoxes) + GL.glDrawArrays(GL.GL_QUADS, 0, cursor / 2) - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_BLEND) diff --git a/renderer.py b/renderer.py index 3873c45..6ee74fd 100644 --- a/renderer.py +++ b/renderer.py @@ -44,7 +44,7 @@ from glutils import gl, Texture import logging import numpy -import OpenGL +from OpenGL import GL import pymclevel import sys #import time @@ -143,7 +143,7 @@ def makeDisplayLists(self): showRedraw = self.renderer.showRedraw if not (showRedraw and self.needsBlockRedraw): - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) + GL.glEnableClientState(GL.GL_COLOR_ARRAY) renderers = self.blockRenderers @@ -157,7 +157,7 @@ def makeDisplayLists(self): lists[blockRenderer.renderstate].append(l) if not (showRedraw and self.needsBlockRedraw): - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) + GL.glDisableClientState(GL.GL_COLOR_ARRAY) self.needsRedisplay = False self.renderstateLists = lists @@ -334,31 +334,31 @@ def release(self): class renderstateLowDetail(object): @classmethod def bind(self): - OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) + GL.glDisable(GL.GL_CULL_FACE) + GL.glDisable(GL.GL_TEXTURE_2D) @classmethod def release(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) + GL.glEnable(GL.GL_CULL_FACE) + GL.glEnable(GL.GL_TEXTURE_2D) class renderstateAlphaTest(object): @classmethod def bind(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_ALPHA_TEST) + GL.glEnable(GL.GL_ALPHA_TEST) @classmethod def release(self): - OpenGL.GL.glDisable(OpenGL.GL.GL_ALPHA_TEST) + GL.glDisable(GL.GL_ALPHA_TEST) class _renderstateAlphaBlend(object): @classmethod def bind(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + GL.glEnable(GL.GL_BLEND) @classmethod def release(self): - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_BLEND) class renderstateWater(_renderstateAlphaBlend): pass @@ -369,17 +369,17 @@ class renderstateIce(_renderstateAlphaBlend): class renderstateEntity(object): @classmethod def bind(self): - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) - # OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_DEPTH_TEST) + # GL.glDisable(GL.GL_CULL_FACE) + GL.glDisable(GL.GL_TEXTURE_2D) + GL.glEnable(GL.GL_BLEND) @classmethod def release(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) - # OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glEnable(GL.GL_DEPTH_TEST) + # GL.glEnable(GL.GL_CULL_FACE) + GL.glEnable(GL.GL_TEXTURE_2D) + GL.glDisable(GL.GL_BLEND) renderstates = ( renderstatePlain, @@ -767,9 +767,9 @@ def makeVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, ar def makeArrayList(self, chunkPosition, showRedraw): l = gl.glGenLists(1) - OpenGL.GL.glNewList(l, OpenGL.GL.GL_COMPILE) + GL.glNewList(l, GL.GL_COMPILE) self.drawArrays(chunkPosition, showRedraw) - OpenGL.GL.glEndList() + GL.glEndList() return l def drawArrays(self, chunkPosition, showRedraw): @@ -777,11 +777,11 @@ def drawArrays(self, chunkPosition, showRedraw): y = 0 if hasattr(self, 'y'): y = self.y - with gl.glPushMatrix(OpenGL.GL.GL_MODELVIEW): - OpenGL.GL.glTranslate(cx << 4, y, cz << 4) + with gl.glPushMatrix(GL.GL_MODELVIEW): + GL.glTranslate(cx << 4, y, cz << 4) if showRedraw: - OpenGL.GL.glColor(1.0, 0.25, 0.25, 1.0) + GL.glColor(1.0, 0.25, 0.25, 1.0) self.drawVertices() @@ -795,11 +795,11 @@ def drawFaceVertices(self, buf): return stride = elementByteLength - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, stride, (buf.ravel())) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, stride, (buf.ravel()[3:])) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) + GL.glVertexPointer(3, GL.GL_FLOAT, stride, (buf.ravel())) + GL.glTexCoordPointer(2, GL.GL_FLOAT, stride, (buf.ravel()[3:])) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) class EntityRendererGeneric(BlockRenderer): @@ -811,23 +811,23 @@ def drawFaceVertices(self, buf): return stride = elementByteLength - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, stride, (buf.ravel())) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, stride, (buf.ravel()[3:])) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) + GL.glVertexPointer(3, GL.GL_FLOAT, stride, (buf.ravel())) + GL.glTexCoordPointer(2, GL.GL_FLOAT, stride, (buf.ravel()[3:])) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) - OpenGL.GL.glDepthMask(False) + GL.glDepthMask(False) - OpenGL.GL.glPolygonMode(OpenGL.GL.GL_FRONT_AND_BACK, OpenGL.GL.GL_LINE) + GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE) - OpenGL.GL.glLineWidth(2.0) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) + GL.glLineWidth(2.0) + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glPolygonMode(OpenGL.GL.GL_FRONT_AND_BACK, OpenGL.GL.GL_FILL) + GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) - OpenGL.GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) - with gl.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL, OpenGL.GL.GL_DEPTH_TEST): - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glDepthMask(True) + GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) + with gl.glEnable(GL.GL_POLYGON_OFFSET_FILL, GL.GL_DEPTH_TEST): + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) + GL.glDepthMask(True) def _computeVertices(self, positions, colors, offset=False, chunkPosition=(0, 0)): cx, cz = chunkPosition @@ -959,35 +959,35 @@ def drawFaceVertices(self, buf): return stride = elementByteLength - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, stride, (buf.ravel())) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, stride, (buf.ravel()[3:])) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) + GL.glVertexPointer(3, GL.GL_FLOAT, stride, (buf.ravel())) + GL.glTexCoordPointer(2, GL.GL_FLOAT, stride, (buf.ravel()[3:])) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) - OpenGL.GL.glDepthMask(False) + GL.glDepthMask(False) - # OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) + # GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) + GL.glDisable(GL.GL_CULL_FACE) - with gl.glEnable(OpenGL.GL.GL_DEPTH_TEST): - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) + with gl.glEnable(GL.GL_DEPTH_TEST): + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) + GL.glEnable(GL.GL_CULL_FACE) - OpenGL.GL.glPolygonMode(OpenGL.GL.GL_FRONT_AND_BACK, OpenGL.GL.GL_LINE) + GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE) - OpenGL.GL.glLineWidth(1.0) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glLineWidth(2.0) - with gl.glEnable(OpenGL.GL.GL_DEPTH_TEST): - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glLineWidth(1.0) + GL.glLineWidth(1.0) + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) + GL.glLineWidth(2.0) + with gl.glEnable(GL.GL_DEPTH_TEST): + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) + GL.glLineWidth(1.0) - OpenGL.GL.glPolygonMode(OpenGL.GL.GL_FRONT_AND_BACK, OpenGL.GL.GL_FILL) - OpenGL.GL.glDepthMask(True) + GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) + GL.glDepthMask(True) -# OpenGL.GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) -# with gl.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL, OpenGL.GL.GL_DEPTH_TEST): -# OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) +# GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) +# with gl.glEnable(GL.GL_POLYGON_OFFSET_FILL, GL.GL_DEPTH_TEST): +# GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) # def makeChunkVertices(self, chunk): @@ -1026,12 +1026,12 @@ def drawFaceVertices(self, buf): return stride = 16 - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, stride, numpy.ravel(buf.ravel())) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype='uint8').ravel()[12:])) + GL.glVertexPointer(3, GL.GL_FLOAT, stride, numpy.ravel(buf.ravel())) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype='uint8').ravel()[12:])) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) + GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) def makeChunkVertices(self, ch): step = 1 @@ -2362,10 +2362,10 @@ def makeFloorTex(self): img = numpy.array([color0, color1, color1, color0], dtype='uint8') - OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, OpenGL.GL.GL_TEXTURE_MIN_FILTER, OpenGL.GL.GL_NEAREST) - OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, OpenGL.GL.GL_TEXTURE_MAG_FILTER, OpenGL.GL.GL_NEAREST) + GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) + GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) - OpenGL.GL.glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, 0, OpenGL.GL.GL_RGBA, 2, 2, 0, OpenGL.GL.GL_RGBA, OpenGL.GL.GL_UNSIGNED_BYTE, img) + GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, 2, 2, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, img) def invalidateChunkMarkers(self): self.loadableChunkMarkers.invalidate() @@ -2376,17 +2376,17 @@ def _drawLoadableChunkMarkers(self): sizedChunks = chunkMarkers(chunkSet) - OpenGL.GL.glPushAttrib(OpenGL.GL.GL_FOG_BIT) - OpenGL.GL.glDisable(OpenGL.GL.GL_FOG) + GL.glPushAttrib(GL.GL_FOG_BIT) + GL.glDisable(GL.GL_FOG) - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) - OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) - OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + GL.glEnable(GL.GL_BLEND) + GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) + GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) + GL.glEnable(GL.GL_DEPTH_TEST) - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) - OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glColor(1.0, 1.0, 1.0, 1.0) + GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) + GL.glEnable(GL.GL_TEXTURE_2D) + GL.glColor(1.0, 1.0, 1.0, 1.0) self.floorTexture.bind() # chunkColor = numpy.zeros(shape=(chunks.shape[0], 4, 4), dtype='float32') @@ -2399,7 +2399,7 @@ def _drawLoadableChunkMarkers(self): # chunkColor *= 255 # chunkColor = numpy.array(chunkColor, dtype='uint8') # - # OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, chunkColor) + # GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, 0, chunkColor) for size, chunks in sizedChunks.iteritems(): if not len(chunks): continue @@ -2410,17 +2410,17 @@ def _drawLoadableChunkMarkers(self): chunkPosition[:, :, (0, 2)] *= size chunkPosition[:, :, (0, 2)] += chunks[:, numpy.newaxis, :] chunkPosition *= 16 - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, chunkPosition.ravel()) + GL.glVertexPointer(3, GL.GL_FLOAT, 0, chunkPosition.ravel()) # chunkPosition *= 8 - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, (chunkPosition[..., (0, 2)] * 8).ravel()) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(chunkPosition) * 4) + GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, (chunkPosition[..., (0, 2)] * 8).ravel()) + GL.glDrawArrays(GL.GL_QUADS, 0, len(chunkPosition) * 4) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) - OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) - OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) - OpenGL.GL.glPopAttrib() + GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) + GL.glDisable(GL.GL_TEXTURE_2D) + GL.glDisable(GL.GL_BLEND) + GL.glDisable(GL.GL_DEPTH_TEST) + GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) + GL.glPopAttrib() def drawLoadableChunkMarkers(self): if not self.isPreviewer or isinstance(self.level, pymclevel.MCInfdevOldLevel): @@ -2464,22 +2464,22 @@ def drawCompressedChunkMarkers(self): coloredChunks = cc > 0 colorBuffer[coloredChunks] *= 0.75 - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) - OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) - OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) + GL.glEnable(GL.GL_BLEND) + GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) + GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) + GL.glEnable(GL.GL_DEPTH_TEST) + GL.glEnableClientState(GL.GL_COLOR_ARRAY) - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, vertexBuffer) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, colorBuffer) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(vertexBuffer) * 4) + GL.glVertexPointer(3, GL.GL_FLOAT, 0, vertexBuffer) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, 0, colorBuffer) + GL.glDrawArrays(GL.GL_QUADS, 0, len(vertexBuffer) * 4) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) + GL.glDisableClientState(GL.GL_COLOR_ARRAY) - OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) + GL.glDisable(GL.GL_DEPTH_TEST) - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_BLEND) needsImmediateRedraw = False viewingFrustum = None @@ -2525,14 +2525,14 @@ def callMasterLists(self): continue if self.alpha != 0xff and renderstate is not ChunkCalculator.renderstateLowDetail: - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + GL.glEnable(GL.GL_BLEND) renderstate.bind() - OpenGL.GL.glCallLists(self.masterLists[renderstate]) + GL.glCallLists(self.masterLists[renderstate]) renderstate.release() if self.alpha != 0xff and renderstate is not ChunkCalculator.renderstateLowDetail: - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_BLEND) errorLimit = 10 @@ -2547,38 +2547,38 @@ def draw(self): chunksDrawn = 0 - with gl.glPushMatrix(OpenGL.GL.GL_MODELVIEW): + with gl.glPushMatrix(GL.GL_MODELVIEW): dx, dy, dz = self.origin - OpenGL.GL.glTranslate(dx, dy, dz) + GL.glTranslate(dx, dy, dz) - OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + GL.glEnable(GL.GL_CULL_FACE) + GL.glEnable(GL.GL_DEPTH_TEST) self.level.materials.terrainTexture.bind() - OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glEnable(GL.GL_TEXTURE_2D) + GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) offset = DepthOffset.PreviewRenderer if self.isPreviewer else DepthOffset.Renderer - OpenGL.GL.glPolygonOffset(offset, offset) - OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + GL.glPolygonOffset(offset, offset) + GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) self.createMasterLists() try: self.callMasterLists() - except OpenGL.GL.GLError, e: + except GL.GLError, e: if self.errorLimit: self.errorLimit -= 1 traceback.print_exc() print e - OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) - OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + GL.glDisable(GL.GL_CULL_FACE) + GL.glDisable(GL.GL_DEPTH_TEST) - OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glDisable(GL.GL_TEXTURE_2D) + GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) # if self.drawLighting: self.drawLoadableChunkMarkers() @@ -2767,33 +2767,33 @@ def rendermain(): # display.init( (640, 480), OPENGL | DOUBLEBUF ) from mcedit import GLDisplayContext - #from OpenGL import GLU + from OpenGL import GLU cxt = GLDisplayContext() import pygame # distance = 4000 - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) - OpenGL.GL.glLoadIdentity() - OpenGL.GLU.gluPerspective(35, 640.0 / 480.0, 0.5, 4000.0) + GL.glMatrixMode(GL.GL_PROJECTION) + GL.glLoadIdentity() + GLU.gluPerspective(35, 640.0 / 480.0, 0.5, 4000.0) h = 366 pos = (0, h, 0) look = (0.0001, h - 1, 0.0001) up = (0, 1, 0) - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) - OpenGL.GL.glLoadIdentity() + GL.glMatrixMode(GL.GL_MODELVIEW) + GL.glLoadIdentity() - OpenGL.GLU.gluLookAt(pos[0], pos[1], pos[2], + GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) - OpenGL.GL.glClearColor(0.0, 0.0, 0.0, 1.0) + GL.glClearColor(0.0, 0.0, 0.0, 1.0) framestart = datetime.now() frames = 200 for i in range(frames): - OpenGL.GL.glClear(OpenGL.GL.GL_COLOR_BUFFER_BIT | OpenGL.GL.GL_DEPTH_BUFFER_BIT) + GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) renderer.draw() pygame.display.flip() From 6eed08c8f597118691f204f31b2e8d1e53ce5a01 Mon Sep 17 00:00:00 2001 From: David Sowder Date: Tue, 20 Mar 2012 21:28:56 -0500 Subject: [PATCH 4/8] frustrum.py: GL.newaxis should be numpy.newaxis, so make it so --- frustum.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/frustum.py b/frustum.py index 6298024..5be957e 100644 --- a/frustum.py +++ b/frustum.py @@ -85,15 +85,15 @@ def visible(self, points, radius): frustcullaccel C extension module) """ - distances = sum(self.planes[GL.newaxis, :, :] * points[:, GL.newaxis, :], -1) + distances = sum(self.planes[numpy.newaxis, :, :] * points[:, numpy.newaxis, :], -1) return ~any(distances < -radius, -1) def visible1(self, point, radius): - #return self.visible(array(point[GL.newaxis, :]), radius) + #return self.visible(array(point[numpy.newaxis, :]), radius) distance = sum(self.planes * point, -1) vis = ~any(distance < -radius) - #assert vis == self.visible(array(point)[GL.newaxis, :], radius) + #assert vis == self.visible(array(point)[numpy.newaxis, :], radius) return vis From e6902af034f5dcd00e973ac566d5d4a14193de49 Mon Sep 17 00:00:00 2001 From: David Sowder Date: Sun, 11 Mar 2012 16:05:50 -0500 Subject: [PATCH 5/8] pull from pyflakes branch: unravel/mangle imports --- frustum.py | 37 +-- leveleditor.py | 653 ++++++++++++++++++++++----------------------- mcedit.py | 222 ++++++++-------- mceutils.py | 51 ++-- mcplatform.py | 17 +- renderer.py | 699 ++++++++++++++++++++++++------------------------- 6 files changed, 826 insertions(+), 853 deletions(-) diff --git a/frustum.py b/frustum.py index 3d27ce5..ef58b98 100644 --- a/frustum.py +++ b/frustum.py @@ -9,9 +9,10 @@ Based on code from: http://www.markmorley.com/opengl/frustumculling.html """ -from OpenGL.GL import * -from numpy import * -import logging + +import logging +import numpy +import OpenGL.GL context_log = logging.getLogger() @@ -30,9 +31,9 @@ def viewingMatrix(projection=None, model=None): matrix, the function will raise a RuntimeError """ if projection is None: - projection = glGetDoublev(GL_PROJECTION_MATRIX) + projection = OpenGL.GL.glGetDoublev(OpenGL.GL.GL_PROJECTION_MATRIX) if model is None: - model = glGetDoublev(GL_MODELVIEW_MATRIX) + model = OpenGL.GL.glGetDoublev(OpenGL.GL.GL_MODELVIEW_MATRIX) # hmm, this will likely fail on 64-bit platforms :( if projection is None or model is None: context_log.warn( @@ -44,20 +45,20 @@ def viewingMatrix(projection=None, model=None): if model: return model else: - return identity(4, 'd') - if allclose(projection, -1.79769313e+308): + return numpy.identity(4, 'd') + if numpy.allclose(projection, -1.79769313e+308): context_log.warn( """Attempt to retrieve projection matrix when uninitialised %s, model=%s""", projection, model, ) return model - if allclose(model, -1.79769313e+308): + if numpy.allclose(model, -1.79769313e+308): context_log.warn( """Attempt to retrieve model-view matrix when uninitialised %s, projection=%s""", model, projection, ) return projection - return dot(model, projection) + return numpy.dot(model, projection) class Frustum (object): @@ -84,15 +85,15 @@ def visible(self, points, radius): frustcullaccel C extension module) """ - distances = sum(self.planes[newaxis, :, :] * points[:, newaxis, :], -1) + distances = sum(self.planes[OpenGL.GL.newaxis, :, :] * points[:, OpenGL.GL.newaxis, :], -1) return ~any(distances < -radius, -1) def visible1(self, point, radius): - #return self.visible(array(point[newaxis, :]), radius) + #return self.visible(array(point[OpenGL.GL.newaxis, :]), radius) distance = sum(self.planes * point, -1) vis = ~any(distance < -radius) - #assert vis == self.visible(array(point)[newaxis, :], radius) + #assert vis == self.visible(array(point)[OpenGL.GL.newaxis, :], radius) return vis @@ -113,8 +114,8 @@ def fromViewingMatrix(cls, matrix=None, normalize=1): """ if matrix is None: matrix = viewingMatrix() - clip = ravel(matrix) - frustum = zeros((6, 4), 'd') + clip = numpy.ravel(matrix) + frustum = numpy.zeros((6, 4), 'd') # right frustum[0][0] = clip[3] - clip[0] frustum[0][1] = clip[7] - clip[4] @@ -155,10 +156,10 @@ def fromViewingMatrix(cls, matrix=None, normalize=1): @classmethod def normalize(cls, frustum): """Normalize clipping plane equations""" - magnitude = sqrt(frustum[:, 0] * frustum[:, 0] + frustum[:, 1] * frustum[:, 1] + frustum[:, 2] * frustum[:, 2]) + magnitude = numpy.sqrt(frustum[:, 0] * frustum[:, 0] + frustum[:, 1] * frustum[:, 1] + frustum[:, 2] * frustum[:, 2]) # eliminate any planes which have 0-length vectors, # those planes can't be used for excluding anything anyway... - frustum = compress(magnitude, frustum, 0) - magnitude = compress(magnitude, magnitude, 0) - magnitude = reshape(magnitude.astype('d'), (len(frustum), 1)) + frustum = numpy.compress(magnitude, frustum, 0) + magnitude = numpy.compress(magnitude, magnitude, 0) + magnitude = numpy.reshape(magnitude.astype('d'), (len(frustum), 1)) return frustum / magnitude diff --git a/leveleditor.py b/leveleditor.py index d6145e6..14e74e5 100644 --- a/leveleditor.py +++ b/leveleditor.py @@ -23,44 +23,47 @@ """ -from collections import defaultdict -import gc +from albow.controls import Label, SmallValueDisplay, ValueDisplay +from albow.dialogs import Dialog, QuickDialog, wrapped_label +from albow import alert, ask, AttrRef, Button, Column, get_font, Grid, input_text, IntField, Label, Menu, root, Row, TableColumn, TableView, TextField, TimeField, ValueButton, Widget +from albow.openglwidgets import GLOrtho, GLPerspective, GLViewport +from collections import defaultdict, deque +import config +import copy +import csv from datetime import datetime, timedelta +from depths import DepthOffset +import editortools +from editortools.chunk import GeneratorPanel +from editortools.toolbasics import Operation +import frustum +import functools +import gc +from glbackground import GLBackground, Panel +import glutils +from glutils import FramebufferTexture, gl, Texture import itertools import logging -from OpenGL.GL import * +from math import isnan +import mceutils +import mcplatform +from mcplatform import askSaveFile +import numpy +import OpenGL # from OpenGL.GLUT import glutBitmapCharacter, GLUT_BITMAP_HELVETICA_18 -import time - -from pygame import display, event, key -from pygame.locals import * -from numpy import * - -from albow import * -from albow.dialogs import Dialog, wrapped_label, QuickDialog -from albow.openglwidgets import GLViewport, GLPerspective -from mceutils import * -from glutils import gl, Texture, FramebufferTexture -import glutils -# Label = GLLabel - -import config -from pymclevel import * -from glbackground import * -import editortools -from renderer import MCRenderer, PreviewRenderer -from depths import DepthOffset +import os +from os.path import dirname, isdir import platform - -import frustum -from collections import deque -from editortools.toolbasics import Operation +from pygame import display, event, key, KMOD_ALT, KMOD_CTRL, KMOD_LALT, KMOD_META, KMOD_RALT, KMOD_SHIFT, mouse, MOUSEMOTION +import pymclevel from pymclevel.infiniteworld import alphanum_key -import csv -from mcplatform import askSaveFile -from editortools.chunk import GeneratorPanel -from os.path import isdir, dirname +import release import renderer +from renderer import MCRenderer, PreviewRenderer +import time +import traceback + +# Label = GLLabel Settings = config.Settings("Settings") Settings.flyMode = Settings("Fly Mode", False) @@ -171,7 +174,7 @@ def __init__(self, editor): if cmd == "Cmd": hotkeys[-1] = ("Cmd-Q", hotkeys[-1][1], hotkeys[-1][2]) - buttons = HotkeyColumn(hotkeys, keysColumn, buttonsColumn) + buttons = mceutils.HotkeyColumn(hotkeys, keysColumn, buttonsColumn) # buttons.buttons[-1].ref = @@ -195,7 +198,7 @@ def key_down(self, evt): def unproject(x, y, z): try: - return GLU.gluUnProject(x, y, z) + return OpenGL.GLU.gluUnProject(x, y, z) except ValueError: # projection failed return 0, 0, 0 @@ -269,10 +272,10 @@ def pitch(self, val): def updateFov(self, val=None): hfov = self.fovSetting - fov = degrees(2.0 * arctan(self.size[0] / self.size[1] * tan(radians(hfov) * 0.5))) + fov = numpy.degrees(2.0 * numpy.arctan(self.size[0] / self.size[1] * numpy.tan(numpy.radians(hfov) * 0.5))) self.fov = fov - self.tang = tan(radians(fov)) + self.tang = numpy.tan(numpy.radians(fov)) def stopMoving(self): self.velocity = [0, 0, 0] @@ -334,9 +337,9 @@ def tickCamera(self, frameStartTime, inputs, inSpace): velocity = self.velocity # xxx learn to use matrix/vector libs i = inputs - yaw = radians(self.yaw) - cosyaw = -cos(yaw) - sinyaw = sin(yaw) + yaw = numpy.radians(self.yaw) + cosyaw = -numpy.cos(yaw) + sinyaw = numpy.sin(yaw) if alignMovementToAxes: cosyaw = int(cosyaw * 1.4) sinyaw = int(sinyaw * 1.4) @@ -344,7 +347,7 @@ def tickCamera(self, frameStartTime, inputs, inSpace): dy = int(dy * 1.6) dz = int(dz * 1.4) - directedInputs = normalize(( + directedInputs = mceutils.normalize(( i[0] * cosyaw + i[2] * dx, i[1] + i[2] * dy, i[2] * dz - i[0] * sinyaw, @@ -355,7 +358,7 @@ def tickCamera(self, frameStartTime, inputs, inSpace): # cameraImpulse = map(lambda x: x*impulse_factor, directedInputs) newVelocity = map(lambda a, b: a + b, velocity, cameraAccel) - velocityDir, speed = normalize_size(newVelocity) + velocityDir, speed = mceutils.normalize_size(newVelocity) # apply drag if speed: @@ -398,15 +401,13 @@ def tickCamera(self, frameStartTime, inputs, inSpace): def setModelview(self): pos = self.cameraPosition - look = array(self.cameraPosition) + look = numpy.array(self.cameraPosition) look += self.cameraVector up = (0, 1, 0) - GLU.gluLookAt(pos[0], pos[1], pos[2], + OpenGL.GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) - from math import isnan - def _cameraVector(self): return self._anglesToVector(self.yaw, self.pitch) @@ -417,9 +418,9 @@ def nanzero(x): else: return x - dx = -sin(radians(yaw)) * cos(radians(pitch)) - dy = -sin(radians(pitch)) - dz = cos(radians(yaw)) * cos(radians(pitch)) + dx = -numpy.sin(numpy.radians(yaw)) * numpy.cos(numpy.radians(pitch)) + dy = -numpy.sin(numpy.radians(pitch)) + dz = numpy.cos(numpy.radians(yaw)) * numpy.cos(numpy.radians(pitch)) return map(nanzero, [dx, dy, dz]) def updateMouseVector(self): @@ -437,8 +438,8 @@ def _mouseVector(self): y = self.get_root().height - y point1 = unproject(x, y, 0.0) point2 = unproject(x, y, 1.0) - v = array(point2) - point1 - v = normalize(v) + v = numpy.array(point2) - point1 + v = mceutils.normalize(v) return v def _blockUnderCursor(self, center=False): @@ -448,9 +449,9 @@ def _blockUnderCursor(self, center=False): """ try: if Settings.doubleBuffer.get(): - glReadBuffer(GL_BACK) + OpenGL.GL.glReadBuffer(OpenGL.GL.GL_BACK) else: - glReadBuffer(GL_FRONT) + OpenGL.GL.glReadBuffer(OpenGL.GL.GL_FRONT) except Exception: logging.exception('Exception during glReadBuffer') ws = self.get_root().size @@ -467,7 +468,7 @@ def _blockUnderCursor(self, center=False): y = ws[1] - y try: - pixel = glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT) + pixel = OpenGL.GL.glReadPixels(x, y, 1, 1, OpenGL.GL.GL_DEPTH_COMPONENT, OpenGL.GL.GL_FLOAT) newpoint = unproject(x, y, pixel[0]) except Exception: return 0, 0, 0 @@ -498,7 +499,7 @@ def findBlockFaceUnderCursor(self, projectedPoint): d = [0, 0, 0] try: - intProjectedPoint = map(int, map(floor, projectedPoint)) + intProjectedPoint = map(int, map(numpy.floor, projectedPoint)) except ValueError: return None # catch NaNs intProjectedPoint[1] = max(0, intProjectedPoint[1]) @@ -522,20 +523,20 @@ def findBlockFaceUnderCursor(self, projectedPoint): try: block = self.editor.level.blockAt(*intProjectedPoint) - except ChunkNotPresent: + except pymclevel.ChunkNotPresent: return intProjectedPoint, d - if block == alphaMaterials.SnowLayer.ID: + if block == pymclevel.alphaMaterials.SnowLayer.ID: potentialOffsets.append((0, 1, 0)) else: # discard any faces that aren't likely to be exposed - for face, offsets in faceDirections: + for face, offsets in pymclevel.faceDirections: point = map(lambda a, b: a + b, intProjectedPoint, offsets) try: neighborBlock = self.editor.level.blockAt(*point) if block != neighborBlock: potentialOffsets.append(offsets) - except ChunkNotPresent: + except pymclevel.ChunkNotPresent: pass # check each component of the face vector to see if that face is exposed @@ -594,21 +595,21 @@ def toggleMouseLook(self): else: self.mouseLookOff() - mobs = entity.Entity.monsters + ["[Custom]"] + mobs = pymclevel.Entity.monsters + ["[Custom]"] - @alertException + @mceutils.alertException def editMonsterSpawner(self, point): mobs = self.mobs tileEntity = self.editor.level.tileEntityAt(*point) if not tileEntity: - tileEntity = TAG_Compound() - tileEntity["id"] = TAG_String("MobSpawner") - tileEntity["x"] = TAG_Int(point[0]) - tileEntity["y"] = TAG_Int(point[1]) - tileEntity["z"] = TAG_Int(point[2]) - tileEntity["Delay"] = TAG_Short(120) - tileEntity["EntityId"] = TAG_String(mobs[0]) + tileEntity = pymclevel.TAG_Compound() + tileEntity["id"] = pymclevel.TAG_String("MobSpawner") + tileEntity["x"] = pymclevel.TAG_Int(point[0]) + tileEntity["y"] = pymclevel.TAG_Int(point[1]) + tileEntity["z"] = pymclevel.TAG_Int(point[2]) + tileEntity["Delay"] = pymclevel.TAG_Short(120) + tileEntity["EntityId"] = pymclevel.TAG_String(mobs[0]) self.editor.level.addTileEntity(tileEntity) self.editor.addUnsavedEdit() @@ -659,9 +660,9 @@ def selectedMob(): panel.shrink_wrap() panel.present() - tileEntity["EntityId"] = TAG_String(selectedMob()) + tileEntity["EntityId"] = pymclevel.TAG_String(selectedMob()) - @alertException + @mceutils.alertException def editSign(self, point): block = self.editor.level.blockAt(*point) @@ -670,13 +671,13 @@ def editSign(self, point): linekeys = ["Text" + str(i) for i in range(1, 5)] if not tileEntity: - tileEntity = TAG_Compound() - tileEntity["id"] = TAG_String("Sign") - tileEntity["x"] = TAG_Int(point[0]) - tileEntity["y"] = TAG_Int(point[1]) - tileEntity["z"] = TAG_Int(point[2]) + tileEntity = pymclevel.TAG_Compound() + tileEntity["id"] = pymclevel.TAG_String("Sign") + tileEntity["x"] = pymclevel.TAG_Int(point[0]) + tileEntity["y"] = pymclevel.TAG_Int(point[1]) + tileEntity["z"] = pymclevel.TAG_Int(point[2]) for l in linekeys: - tileEntity[l] = TAG_String("") + tileEntity[l] = pymclevel.TAG_String("") self.editor.level.addTileEntity(tileEntity) @@ -711,7 +712,7 @@ def menu_picked(index): currentField.text += c # xxx view hierarchy currentField.insertion_point = len(currentField.text) - colorMenu = MenuButton("Color Code...", colors, menu_picked=menu_picked) + colorMenu = mceutils.MenuButton("Color Code...", colors, menu_picked=menu_picked) column = [Label("Edit Sign")] + lineFields + [colorMenu, Button("OK", action=panel.dismiss)] @@ -723,18 +724,18 @@ def menu_picked(index): for l, f in zip(linekeys, lineFields): tileEntity[l].value = f.value[:15] - @alertException + @mceutils.alertException def editContainer(self, point, containerID): tileEntityTag = self.editor.level.tileEntityAt(*point) if tileEntityTag is None: - tileEntityTag = TileEntity.Create(containerID) - TileEntity.setpos(tileEntityTag, point) + tileEntityTag = pymclevel.TileEntity.Create(containerID) + pymclevel.TileEntity.setpos(tileEntityTag, point) self.editor.level.addTileEntity(tileEntityTag) if tileEntityTag["id"].value != containerID: return - backupEntityTag = deepcopy(tileEntityTag) + backupEntityTag = copy.deepcopy(tileEntityTag) def itemProp(key): # xxx do validation here @@ -756,10 +757,10 @@ class ChestWidget(Widget): id = itemProp("id") Damage = itemProp("Damage") Count = itemProp("Count") - itemLimit = TileEntity.maxItems.get(containerID, 255) + itemLimit = pymclevel.TileEntity.maxItems.get(containerID, 255) def slotFormat(slot): - slotNames = entity.TileEntity.slotNames.get(containerID) + slotNames = pymclevel.TileEntity.slotNames.get(containerID) if slotNames: return slotNames.get(slot, slot) return slot @@ -776,8 +777,8 @@ def slotFormat(slot): def itemName(id, damage): try: - return items.items.findItem(id, damage).name - except items.ItemNotFound: + return pymclevel.items.items.findItem(id, damage).name + except pymclevel.items.ItemNotFound: return "Unknown Item" def getRowData(i): @@ -796,10 +797,10 @@ def selectTableRow(i, evt): chestItemTable.click_row = selectTableRow fieldRow = ( - # IntInputRow("Slot: ", ref=AttrRef(chestWidget, 'Slot'), min= -128, max=127), - IntInputRow("ID: ", ref=AttrRef(chestWidget, 'id'), min=0, max=32767), - IntInputRow("DMG: ", ref=AttrRef(chestWidget, 'Damage'), min=-32768, max=32767), - IntInputRow("Count: ", ref=AttrRef(chestWidget, 'Count'), min=-128, max=127), + # mceutils.IntInputRow("Slot: ", ref=AttrRef(chestWidget, 'Slot'), min= -128, max=127), + mceutils.IntInputRow("ID: ", ref=AttrRef(chestWidget, 'id'), min=0, max=32767), + mceutils.IntInputRow("DMG: ", ref=AttrRef(chestWidget, 'Damage'), min=-32768, max=32767), + mceutils.IntInputRow("Count: ", ref=AttrRef(chestWidget, 'Count'), min=-128, max=127), ) def deleteFromWorld(): @@ -808,8 +809,8 @@ def deleteFromWorld(): id = item["id"].value Damage = item["Damage"].value - deleteSameDamage = CheckBoxLabel("Only delete items with the same damage value") - deleteBlocksToo = CheckBoxLabel("Also delete blocks placed in the world") + deleteSameDamage = mceutils.CheckBoxLabel("Only delete items with the same damage value") + deleteBlocksToo = mceutils.CheckBoxLabel("Also delete blocks placed in the world") if id not in (8, 9, 10, 11): # fluid blocks deleteBlocksToo.value = True @@ -872,7 +873,7 @@ def matches_itementity(e): progressInfo = "Deleting the item {0} from the entire world ({1} chunks)".format(itemName(chestWidget.id, 0), self.editor.level.chunkCount) - showProgress(progressInfo, deleteItemsIter(), cancel=True) + mceutils.showProgress(progressInfo, deleteItemsIter(), cancel=True) self.editor.addUnsavedEdit() chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag['Items']) - 1) @@ -897,11 +898,11 @@ def addItem(): slot += 1 if slot >= chestWidget.itemLimit: return - item = TAG_Compound() - item["id"] = TAG_Short(0) - item["Damage"] = TAG_Short(0) - item["Slot"] = TAG_Byte(slot) - item["Count"] = TAG_Byte(0) + item = pymclevel.TAG_Compound() + item["id"] = pymclevel.TAG_Short(0) + item["Damage"] = pymclevel.TAG_Short(0) + item["Slot"] = pymclevel.TAG_Byte(slot) + item["Count"] = pymclevel.TAG_Byte(0) tileEntityTag['Items'].append(item) addItemButton = Button("Add Item", action=addItem, enable=addEnable) @@ -924,7 +925,7 @@ def perform(self, recordUndo=True): def undo(self): level.addTileEntity(backupEntityTag) - return BoundingBox(TileEntity.pos(tileEntityTag), (1, 1, 1)) + return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1)) if chestWidget.dirty: op = ChestEditOperation() @@ -956,18 +957,18 @@ def leftClickDown(self, evt): if evt.num_clicks == 2: def distance2(p1, p2): - return sum(map(lambda a, b: (a - b) ** 2, p1, p2)) + return numpy.sum(map(lambda a, b: (a - b) ** 2, p1, p2)) point, face = self.blockFaceUnderCursor if point is not None: - point = map(lambda x: int(floor(x)), point) + point = map(lambda x: int(numpy.floor(x)), point) if self.editor.currentTool is self.editor.selectionTool: block = self.editor.level.blockAt(*point) if distance2(point, self.cameraPosition) > 4: blockEditors = { - alphaMaterials.MonsterSpawner.ID: self.editMonsterSpawner, - alphaMaterials.Sign.ID: self.editSign, - alphaMaterials.WallSign.ID: self.editSign, + pymclevel.alphaMaterials.MonsterSpawner.ID: self.editMonsterSpawner, + pymclevel.alphaMaterials.Sign.ID: self.editSign, + pymclevel.alphaMaterials.WallSign.ID: self.editSign, } edit = blockEditors.get(block) if edit: @@ -980,7 +981,7 @@ def distance2(p1, p2): if te and "Items" in te and "id" in te: self.editor.endSelection() self.editContainer(point, te["id"].value) - except ChunkNotPresent: + except pymclevel.ChunkNotPresent: pass def leftClickUp(self, evt): @@ -1049,7 +1050,7 @@ def sensitivityAdjust(d): def tooltipText(self): return self.editor.currentTool.worldTooltipText - floorQuad = array(((-4000.0, 0.0, -4000.0), + floorQuad = numpy.array(((-4000.0, 0.0, -4000.0), (-4000.0, 0.0, 4000.0), (4000.0, 0.0, 4000.0), (4000.0, 0.0, -4000.0), @@ -1062,7 +1063,7 @@ def updateFloorQuad(self): (4000.0, 0.0, -4000.0), ) - floorQuad = array(floorQuad, dtype='float32') + floorQuad = numpy.array(floorQuad, dtype='float32') if self.editor.renderer.inSpace(): floorQuad *= 8.0 floorQuad += (self.cameraPosition[0], 0.0, self.cameraPosition[2]) @@ -1083,32 +1084,32 @@ def _drawCeiling(self): lines.append((minx, 0, z)) lines.append((maxx, 0, z)) - glColor(0.3, 0.7, 0.9) - glVertexPointer(3, GL_FLOAT, 0, numpy.array(lines, dtype='float32')) + OpenGL.GL.glColor(0.3, 0.7, 0.9) + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(lines, dtype='float32')) - glEnable(GL_DEPTH_TEST) - glDepthMask(False) - glDrawArrays(GL_LINES, 0, len(lines)) - glDisable(GL_DEPTH_TEST) - glDepthMask(True) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + OpenGL.GL.glDepthMask(False) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_LINES, 0, len(lines)) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + OpenGL.GL.glDepthMask(True) def drawCeiling(self): - glMatrixMode(GL_MODELVIEW) - # glPushMatrix() + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) + # OpenGL.GL.glPushMatrix() x, y, z = self.cameraPosition x -= x % 16 z -= z % 16 y = self.editor.level.Height - glTranslate(x, y, z) + OpenGL.GL.glTranslate(x, y, z) self.ceilingList.call(self._drawCeiling) - glTranslate(-x, -y, -z) + OpenGL.GL.glTranslate(-x, -y, -z) _floorQuadList = None @property def floorQuadList(self): if not self._floorQuadList: - self._floorQuadList = DisplayList() + self._floorQuadList = glutils.DisplayList() return self._floorQuadList _ceilingList = None @@ -1116,7 +1117,7 @@ def floorQuadList(self): @property def ceilingList(self): if not self._ceilingList: - self._ceilingList = DisplayList() + self._ceilingList = glutils.DisplayList() return self._ceilingList @property @@ -1129,12 +1130,12 @@ def floorColor(self): # floorColor = (0.0, 0.0, 1.0, 0.1) def _drawFloorQuad(self): - glDepthMask(True) - glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) - glVertexPointer(3, GL_FLOAT, 0, self.floorQuad) - glColor(*self.floorColor) - with gl.glEnable(GL_BLEND, GL_DEPTH_TEST, GL_POLYGON_OFFSET_FILL): - glDrawArrays(GL_QUADS, 0, 4) + OpenGL.GL.glDepthMask(True) + OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, self.floorQuad) + OpenGL.GL.glColor(*self.floorColor) + with gl.glEnable(OpenGL.GL.GL_BLEND, OpenGL.GL.GL_DEPTH_TEST, OpenGL.GL.GL_POLYGON_OFFSET_FILL): + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) @property def drawSky(self): @@ -1152,20 +1153,20 @@ def drawSky(self, val): def drawSkyBackground(self): if self.skyList is None: - self.skyList = DisplayList() + self.skyList = glutils.DisplayList() self.skyList.call(self._drawSkyBackground) def _drawSkyBackground(self): - glMatrixMode(GL_MODELVIEW) - glPushMatrix() - glLoadIdentity() - glMatrixMode(GL_PROJECTION) - glPushMatrix() - glLoadIdentity() - glEnableClientState(GL_COLOR_ARRAY) - - quad = array([-1, -1, -1, 1, 1, 1, 1, -1], dtype='float32') - colors = array([0x48, 0x49, 0xBA, 0xff, + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) + OpenGL.GL.glPushMatrix() + OpenGL.GL.glLoadIdentity() + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) + OpenGL.GL.glPushMatrix() + OpenGL.GL.glLoadIdentity() + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) + + quad = numpy.array([-1, -1, -1, 1, 1, 1, 1, -1], dtype='float32') + colors = numpy.array([0x48, 0x49, 0xBA, 0xff, 0x8a, 0xaf, 0xff, 0xff, 0x8a, 0xaf, 0xff, 0xff, 0x48, 0x49, 0xBA, 0xff, ], dtype='uint8') @@ -1174,20 +1175,20 @@ def _drawSkyBackground(self): if alpha > 0.0: if alpha < 1.0: - glEnable(GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) - glVertexPointer(2, GL_FLOAT, 0, quad) - glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors) - glDrawArrays(GL_QUADS, 0, 4) + OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, quad) + OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, colors) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) if alpha < 1.0: - glDisable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) - glDisableClientState(GL_COLOR_ARRAY) - glMatrixMode(GL_PROJECTION) - glPopMatrix() - glMatrixMode(GL_MODELVIEW) - glPopMatrix() + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) + OpenGL.GL.glPopMatrix() + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) + OpenGL.GL.glPopMatrix() enableMouseLag = Settings.enableMouseLag.configProperty() @@ -1199,24 +1200,24 @@ def drawFog(self): def drawFog(self, val): self._drawFog = val - fogColor = array([0.6, 0.8, 1.0, 1.0], dtype='float32') - fogColorBlack = array([0.0, 0.0, 0.0, 1.0], dtype='float32') + fogColor = numpy.array([0.6, 0.8, 1.0, 1.0], dtype='float32') + fogColorBlack = numpy.array([0.0, 0.0, 0.0, 1.0], dtype='float32') def enableFog(self): - glEnable(GL_FOG) + OpenGL.GL.glEnable(OpenGL.GL.GL_FOG) if self.drawSky: - glFogfv(GL_FOG_COLOR, self.fogColor) + OpenGL.GL.glFogfv(OpenGL.GL.GL_FOG_COLOR, self.fogColor) else: - glFogfv(GL_FOG_COLOR, self.fogColorBlack) + OpenGL.GL.glFogfv(OpenGL.GL.GL_FOG_COLOR, self.fogColorBlack) - glFogf(GL_FOG_DENSITY, 0.002) + OpenGL.GL.glFogf(OpenGL.GL.GL_FOG_DENSITY, 0.002) def disableFog(self): - glDisable(GL_FOG) + OpenGL.GL.glDisable(OpenGL.GL.GL_FOG) def getCameraPoint(self): distance = self.editor.currentTool.cameraDistance - return [i for i in itertools.imap(lambda p, d: int(floor(p + d * distance)), + return [i for i in itertools.imap(lambda p, d: int(numpy.floor(p + d * distance)), self.cameraPosition, self.cameraVector)] @@ -1228,7 +1229,7 @@ def setup_projection(self): distance = 1.0 if self.editor.renderer.inSpace(): distance = 8.0 - GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) + OpenGL.GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) def setup_modelview(self): self.setModelview() @@ -1303,13 +1304,13 @@ def setup_projection(self): minx, maxx = - w, w miny, maxy = - h, h minz, maxz = -4000, 4000 - GL.glOrtho(minx, maxx, miny, maxy, minz, maxz) + OpenGL.GL.glOrtho(minx, maxx, miny, maxy, minz, maxz) def setup_modelview(self): x, y, z = self.cameraPosition - glRotate(90.0, 1.0, 0.0, 0.0) - glTranslate(-x, 0, -z) + OpenGL.GL.glRotate(90.0, 1.0, 0.0, 0.0) + OpenGL.GL.glTranslate(-x, 0, -z) def zoom(self, f): x, y, z = self.cameraPosition @@ -1351,7 +1352,7 @@ def rightClickUp(self, evt): def mouse_move(self, evt): pass - @alertException + @mceutils.alertException def mouse_drag(self, evt): if evt.buttons[2]: @@ -1437,7 +1438,7 @@ def __init__(self, mcedit): tooltipText="Memory used for vertexes") def dataSize(): - if not isinstance(self.level, MCInfdevOldLevel): + if not isinstance(self.level, pymclevel.MCInfdevOldLevel): try: return len(self.level.root_tag) except: @@ -1452,7 +1453,7 @@ def size(c): return len(c.compressedTag) return 0 - return sum(size(c) for c in chunks.itervalues()) + return numpy.sum(size(c) for c in chunks.itervalues()) mbldReadout = SmallValueDisplay(width=60, get_value=lambda: "MBd: %0.1f" % (dataSize() / 1000000.), @@ -1460,22 +1461,22 @@ def size(c): def showViewOptions(): col = [] - col.append(CheckBoxLabel("Entities", fg_color=(0xff, 0x22, 0x22), ref=Settings.drawEntities.propertyRef())) - col.append(CheckBoxLabel("Items", fg_color=(0x22, 0xff, 0x22), ref=Settings.drawItems.propertyRef())) - col.append(CheckBoxLabel("TileEntities", fg_color=(0xff, 0xff, 0x22), ref=Settings.drawTileEntities.propertyRef())) - col.append(CheckBoxLabel("TileTicks", ref=Settings.drawTileTicks.propertyRef())) - col.append(CheckBoxLabel("Unpopulated Chunks", fg_color=renderer.TerrainPopulatedRenderer.color, + col.append(mceutils.CheckBoxLabel("Entities", fg_color=(0xff, 0x22, 0x22), ref=Settings.drawEntities.propertyRef())) + col.append(mceutils.CheckBoxLabel("Items", fg_color=(0x22, 0xff, 0x22), ref=Settings.drawItems.propertyRef())) + col.append(mceutils.CheckBoxLabel("TileEntities", fg_color=(0xff, 0xff, 0x22), ref=Settings.drawTileEntities.propertyRef())) + col.append(mceutils.CheckBoxLabel("TileTicks", ref=Settings.drawTileTicks.propertyRef())) + col.append(mceutils.CheckBoxLabel("Unpopulated Chunks", fg_color=renderer.TerrainPopulatedRenderer.color, ref=Settings.drawUnpopulatedChunks.propertyRef())) - col.append(CheckBoxLabel("Sky", ref=Settings.drawSky.propertyRef())) - col.append(CheckBoxLabel("Fog", ref=Settings.drawFog.propertyRef())) - col.append(CheckBoxLabel("Ceiling", + col.append(mceutils.CheckBoxLabel("Sky", ref=Settings.drawSky.propertyRef())) + col.append(mceutils.CheckBoxLabel("Fog", ref=Settings.drawFog.propertyRef())) + col.append(mceutils.CheckBoxLabel("Ceiling", ref=Settings.showCeiling.propertyRef())) - col.append(CheckBoxLabel("Hidden Ores", + col.append(mceutils.CheckBoxLabel("Hidden Ores", ref=Settings.showHiddenOres.propertyRef())) - col.append(CheckBoxLabel("Chunk Redraw", fg_color=(0xff, 0x99, 0x99), + col.append(mceutils.CheckBoxLabel("Chunk Redraw", fg_color=(0xff, 0x99, 0x99), ref=Settings.showChunkRedraw.propertyRef())) col = Column(col, align="r") @@ -1640,7 +1641,7 @@ def createOneCopyPanel(sch): deleteButton = Button("Delete", action=lambda: (self.deleteCopiedSchematic(sch))) saveButton = Button("Save", action=lambda: (self.exportSchematic(sch))) sizeLabel = Label("{0} x {1} x {2}".format(sch.Length, sch.Width, sch.Height)) - if isinstance(sch, MCSchematic): + if isinstance(sch, pymclevel.MCSchematic): sch.compress() length = len(sch.compressedTag) else: @@ -1662,28 +1663,28 @@ def createOneCopyPanel(sch): panel.anchor = "whrt" return panel - @alertException + @mceutils.alertException def showAnalysis(self, schematic): self.analyzeBox(schematic, schematic.bounds) def analyzeBox(self, level, box): entityCounts = defaultdict(int) tileEntityCounts = defaultdict(int) - types = zeros(4096, dtype='uint32') + types = numpy.zeros(4096, dtype='uint32') def _analyzeBox(): i = 0 for (chunk, slices, point) in level.getChunkSlices(box): i += 1 yield i, box.chunkCount - blocks = array(chunk.Blocks[slices], dtype='uint16') - blocks |= (array(chunk.Data[slices], dtype='uint16') << 8) - b = bincount(blocks.ravel()) + blocks = numpy.array(chunk.Blocks[slices], dtype='uint16') + blocks |= (numpy.array(chunk.Data[slices], dtype='uint16') << 8) + b = numpy.bincount(blocks.ravel()) types[:b.shape[0]] += b for ent in chunk.getEntitiesInBox(box): if ent["id"].value == "Item": - v = items.items.findItem(ent["Item"]["id"].value, + v = pymclevel.items.items.findItem(ent["Item"]["id"].value, ent["Item"]["Damage"].value).name else: v = ent["id"].value @@ -1691,11 +1692,11 @@ def _analyzeBox(): for ent in chunk.getTileEntitiesInBox(box): tileEntityCounts[ent["id"].value] += 1 - with setWindowCaption("ANALYZING - "): - showProgress("Analyzing {0} blocks...".format(box.volume), _analyzeBox(), cancel=True) + with mceutils.setWindowCaption("ANALYZING - "): + mceutils.showProgress("Analyzing {0} blocks...".format(box.volume), _analyzeBox(), cancel=True) - entitySum = sum(entityCounts.values()) - tileEntitySum = sum(tileEntityCounts.values()) + entitySum = numpy.sum(entityCounts.values()) + tileEntitySum = numpy.sum(tileEntityCounts.values()) presentTypes = types.nonzero() blockCounts = sorted([(level.materials[t & 0xff, t >> 8], types[t]) for t in presentTypes[0]]) @@ -1825,20 +1826,20 @@ def reloadToolbar(self): longDistanceMode = Settings.longDistanceMode.configProperty() def genSixteenBlockTexture(self): - has12 = GL.glGetString(GL_VERSION) >= "1.2" + has12 = OpenGL.GL.glGetString(OpenGL.GL.GL_VERSION) >= "1.2" if has12: maxLevel = 2 - mode = GL.GL_LINEAR_MIPMAP_NEAREST + mode = OpenGL.GL.GL_LINEAR_MIPMAP_NEAREST else: maxLevel = 1 - mode = GL.GL_LINEAR + mode = OpenGL.GL.GL_LINEAR def makeSixteenBlockTex(): darkColor = (0x30, 0x30, 0x30, 0xff) lightColor = (0x80, 0x80, 0x80, 0xff) w, h, = 256, 256 - teximage = zeros((w, h, 4), dtype='uint8') + teximage = numpy.zeros((w, h, 4), dtype='uint8') teximage[:] = 0xff teximage[:, ::16] = lightColor teximage[::16, :] = lightColor @@ -1846,11 +1847,11 @@ def makeSixteenBlockTex(): teximage[-1:] = darkColor teximage[:, -1:] = darkColor teximage[:, :2] = darkColor - # GL.glTexParameter(GL.GL_TEXTURE_2D, - # GL.GL_TEXTURE_MIN_FILTER, - # GL.GL_NEAREST_MIPMAP_NEAREST), - GL.glTexParameter(GL.GL_TEXTURE_2D, - GL_TEXTURE_MAX_LEVEL, + # OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, + # OpenGL.GL.GL_TEXTURE_MIN_FILTER, + # OpenGL.GL.GL_NEAREST_MIPMAP_NEAREST), + OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, + OpenGL.GL.GL_TEXTURE_MAX_LEVEL, maxLevel - 1) for lev in range(maxLevel): @@ -1863,48 +1864,48 @@ def makeSixteenBlockTex(): teximage[:, -1:] = darkColor teximage[:, :2] = darkColor - GL.glTexImage2D(GL.GL_TEXTURE_2D, lev, GL.GL_RGBA8, + OpenGL.GL.glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, lev, OpenGL.GL.GL_RGBA8, w / step, h / step, 0, - GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, + OpenGL.GL.GL_RGBA, OpenGL.GL.GL_UNSIGNED_BYTE, teximage[::step, ::step].ravel()) return Texture(makeSixteenBlockTex, mode) def showProgress(self, *a, **kw): - return showProgress(*a, **kw) + return mceutils.showProgress(*a, **kw) def drawConstructionCube(self, box, color, texture=None): if texture == None: texture = self.sixteenBlockTex # textured cube faces - glEnable(GL_BLEND) - glEnable(GL_DEPTH_TEST) - glDepthMask(False) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + OpenGL.GL.glDepthMask(False) # edges within terrain - glDepthFunc(GL_GREATER) + OpenGL.GL.glDepthFunc(OpenGL.GL.GL_GREATER) try: - glColor(color[0], color[1], color[2], max(color[3], 0.35)) + OpenGL.GL.glColor(color[0], color[1], color[2], max(color[3], 0.35)) except IndexError: raise - glLineWidth(1.0) - drawCube(box, cubeType=GL_LINE_STRIP) + OpenGL.GL.glLineWidth(1.0) + mceutils.drawCube(box, cubeType=OpenGL.GL.GL_LINE_STRIP) # edges on or outside terrain - glDepthFunc(GL_LEQUAL) - glColor(color[0], color[1], color[2], max(color[3] * 2, 0.75)) - glLineWidth(2.0) - drawCube(box, cubeType=GL_LINE_STRIP) + OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LEQUAL) + OpenGL.GL.glColor(color[0], color[1], color[2], max(color[3] * 2, 0.75)) + OpenGL.GL.glLineWidth(2.0) + mceutils.drawCube(box, cubeType=OpenGL.GL.GL_LINE_STRIP) - glDepthFunc(GL_LESS) - glColor(color[0], color[1], color[2], color[3]) - glDepthFunc(GL_LEQUAL) - drawCube(box, texture=texture, selectionBox=True) - glDepthMask(True) + OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LESS) + OpenGL.GL.glColor(color[0], color[1], color[2], color[3]) + OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LEQUAL) + mceutils.drawCube(box, texture=texture, selectionBox=True) + OpenGL.GL.glDepthMask(True) - glDisable(GL_BLEND) - glDisable(GL_DEPTH_TEST) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) def loadFile(self, filename): if self.level and self.unsavedEdits > 0: @@ -1916,7 +1917,7 @@ def loadFile(self, filename): self.freezeStatus("Loading " + filename) try: - level = fromFile(filename) + level = pymclevel.fromFile(filename) except Exception, e: logging.exception( 'Wasn\'t able to open a file {file => %s}' % filename @@ -1941,12 +1942,12 @@ def loadFile(self, filename): if pdim and pdim in level.dimensions: level = level.dimensions[pdim] - except (KeyError, PlayerNotFound): # TagNotFound + except (KeyError, pymclevel.PlayerNotFound): # TagNotFound # player tag not found, maybe try: self.currentViewport.cameraPosition = level.playerSpawnPosition() except KeyError: # TagNotFound - self.currentViewport.cameraPosition = array((0, level.Height * 0.75, 0)) + self.currentViewport.cameraPosition = numpy.array((0, level.Height * 0.75, 0)) self.mainViewport.yaw = -45. self.mainViewport.pitch = 0.0 @@ -1976,15 +1977,15 @@ def loadLevel(self, level): self.clearUnsavedEdits() [t.levelChanged() for t in self.toolbar.tools] - if isinstance(self.level, MCInfdevOldLevel): + if isinstance(self.level, pymclevel.MCInfdevOldLevel): if self.level.parentWorld: dimensions = self.level.parentWorld.dimensions else: dimensions = self.level.dimensions dimensionsMenu = [("Earth", "0")] - dimensionsMenu += [(MCAlphaDimension.dimensionNames.get(dimNo, "Dimension {0}".format(dimNo)), str(dimNo)) for dimNo in dimensions] - for dim, name in MCAlphaDimension.dimensionNames.iteritems(): + dimensionsMenu += [(pymclevel.MCAlphaDimension.dimensionNames.get(dimNo, "Dimension {0}".format(dimNo)), str(dimNo)) for dimNo in dimensions] + for dim, name in pymclevel.MCAlphaDimension.dimensionNames.iteritems(): if dim not in dimensions: dimensionsMenu.append((name, str(dim))) @@ -2010,7 +2011,7 @@ def presentMenu(): resp = ask("It looks like this level is completely empty! You'll have to create some chunks before you can get started.", responses=["Create Chunks", "Cancel"]) if resp == "Create Chunks": x, y, z = self.mainViewport.cameraPosition - box = BoundingBox((x - 128, 0, z - 128), (256, self.level.Height, 256)) + box = pymclevel.BoundingBox((x - 128, 0, z - 128), (256, self.level.Height, 256)) self.selectionTool.setSelection(box) self.toolbar.selectTool(8) self.toolbar.tools[8].createChunks() @@ -2021,7 +2022,7 @@ def removeNetherPanel(self): self.remove(self.netherPanel) self.netherPanel = None - @alertException + @mceutils.alertException def gotoEarth(self): assert self.level.parentWorld self.removeNetherPanel() @@ -2030,7 +2031,7 @@ def gotoEarth(self): x, y, z = self.mainViewport.cameraPosition self.mainViewport.cameraPosition = [x * 8, y, z * 8] - @alertException + @mceutils.alertException def gotoNether(self): self.removeNetherPanel() x, y, z = self.mainViewport.cameraPosition @@ -2063,7 +2064,7 @@ def initWindowCaption(self): title = title.encode('ascii', 'replace') display.set_caption(title) - @alertException + @mceutils.alertException def reload(self): filename = self.level.filename # self.discardAllChunks() @@ -2071,17 +2072,17 @@ def reload(self): self.loadFile(filename) - @alertException + @mceutils.alertException def saveFile(self): - with setWindowCaption("SAVING - "): - if isinstance(self.level, ChunkedLevelMixin): # xxx relight indev levels? + with mceutils.setWindowCaption("SAVING - "): + if isinstance(self.level, pymclevel.ChunkedLevelMixin): # xxx relight indev levels? level = self.level if level.parentWorld: level = level.parentWorld for level in itertools.chain(level.dimensions.itervalues(), [level]): - if "Canceled" == showProgress("Lighting chunks", level.generateLightsIter(), cancel=True): + if "Canceled" == mceutils.showProgress("Lighting chunks", level.generateLightsIter(), cancel=True): return if self.level == level: @@ -2309,7 +2310,7 @@ def generateStars(self): r = starDistance - randPoints = (random.random(size=starCount * 3)) * 2.0 * r + randPoints = (numpy.random.random(size=starCount * 3)) * 2.0 * r randPoints.shape = (starCount, 3) nearbyPoints = (randPoints[:, 0] < r) & (randPoints[:, 1] < r) & (randPoints[:, 2] < r) @@ -2320,23 +2321,23 @@ def generateStars(self): randPoints[::4, 2] = -randPoints[::4, 2] randPoints[1::4, 2] = -randPoints[1::4, 2] - randsizes = random.random(size=starCount) * 6 + 0.8 + randsizes = numpy.random.random(size=starCount) * 6 + 0.8 vertsPerStar = 4 - vertexBuffer = zeros((starCount, vertsPerStar, 3), dtype='float32') + vertexBuffer = numpy.zeros((starCount, vertsPerStar, 3), dtype='float32') def normvector(x): - return x / sqrt(sum(x * x, 1))[:, newaxis] + return x / numpy.sqrt(numpy.sum(x * x, 1))[:, numpy.newaxis] viewVector = normvector(randPoints) - rmod = random.random(size=starCount * 3) * 2.0 - 1.0 + rmod = numpy.random.random(size=starCount * 3) * 2.0 - 1.0 rmod.shape = (starCount, 3) referenceVector = viewVector + rmod - rightVector = normvector(cross(referenceVector, viewVector)) * randsizes[:, newaxis] # vector perpendicular to viewing line - upVector = normvector(cross(rightVector, viewVector)) * randsizes[:, newaxis] # vector perpendicular previous vector and viewing line + rightVector = normvector(numpy.cross(referenceVector, viewVector)) * randsizes[:, numpy.newaxis] # vector perpendicular to viewing line + upVector = normvector(numpy.cross(rightVector, viewVector)) * randsizes[:, numpy.newaxis] # vector perpendicular previous vector and viewing line p = randPoints p1 = p + (- upVector - rightVector) @@ -2358,10 +2359,10 @@ def drawStars(self): self.mainViewport.cameraPosition = map(lambda x: x / 128.0, pos) self.mainViewport.setModelview() - glColor(.5, .5, .5, 1.) + OpenGL.GL.glColor(.5, .5, .5, 1.) - glVertexPointer(3, GL_FLOAT, 0, self.starVertices) - glDrawArrays(GL_QUADS, 0, len(self.starVertices) / 3) + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, self.starVertices) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(self.starVertices) / 3) self.mainViewport.cameraPosition = pos self.mainViewport.setModelview() @@ -2512,7 +2513,7 @@ def key_down(self, evt): # =========================================================== elif mods & KMOD_SHIFT: - raise GLError(err=1285, description="User pressed CONTROL-SHIFT-F9, requesting a GL Memory Error") + raise OpenGL.GL.GLError(err=1285, description="User pressed CONTROL-SHIFT-F9, requesting a GL Memory Error") else: try: expr = input_text(">>> ", 600) @@ -2528,7 +2529,7 @@ def causeError(): if mods & KMOD_ALT: alert("MCEdit, a Minecraft World Editor\n\nCopyright 2010 David Rio Vierra") elif mods & KMOD_SHIFT: - alertException(causeError)() + mceutils.alertException(causeError)() else: causeError() @@ -2683,7 +2684,7 @@ def repairRegions(self): alert("Repairs complete. See the console window for details.") - @alertException + @mceutils.alertException def showWorldInfo(self): ticksPerDay = 24000 ticksPerHour = ticksPerDay / 24 @@ -2707,20 +2708,20 @@ def composeMCTime(d, h, m, t): items = [] t = functools.partial(isinstance, self.level) - if t(MCInfdevOldLevel): - if self.level.version == MCInfdevOldLevel.VERSION_ANVIL: + if t(pymclevel.MCInfdevOldLevel): + if self.level.version == pymclevel.MCInfdevOldLevel.VERSION_ANVIL: levelFormat = "Minecraft Infinite World (Anvil Format)" - elif self.level.version == MCInfdevOldLevel.VERSION_MCR: + elif self.level.version == pymclevel.MCInfdevOldLevel.VERSION_MCR: levelFormat = "Minecraft Infinite World (Region Format)" else: levelFormat = "Minecraft Infinite World (Old Chunk Format)" - elif t(MCIndevLevel): + elif t(pymclevel.MCIndevLevel): levelFormat = "Minecraft Indev (.mclevel format)" - elif t(MCSchematic): + elif t(pymclevel.MCSchematic): levelFormat = "MCEdit Schematic" - elif t(ZipSchematic): + elif t(pymclevel.ZipSchematic): levelFormat = "MCEdit Schematic (Zipped Format)" - elif t(MCJavaLevel): + elif t(pymclevel.MCJavaLevel): levelFormat = "Minecraft Classic or raw block array" else: levelFormat = "Unknown" @@ -2747,7 +2748,7 @@ def composeMCTime(d, h, m, t): if hasattr(self.level, 'RandomSeed'): seed = self.level.RandomSeed - seedInputRow = IntInputRow("RandomSeed: ", width=250, ref=AttrRef(self.level, "RandomSeed")) + seedInputRow = mceutils.IntInputRow("RandomSeed: ", width=250, ref=AttrRef(self.level, "RandomSeed")) items.append(seedInputRow) if hasattr(self.level, 'GameType'): @@ -2773,7 +2774,7 @@ def action(): items.append(gametypeRow) - if isinstance(self.level, MCInfdevOldLevel): + if isinstance(self.level, pymclevel.MCInfdevOldLevel): chunkCount = self.level.chunkCount chunkCountLabel = Label("Number of chunks: {0}".format(chunkCount)) @@ -2848,21 +2849,21 @@ def decreaseViewDistance(self): self.addWorker(self.renderer) Settings.viewDistance.set(self.renderer.viewDistance) - @alertException + @mceutils.alertException def askLoadWorld(self): - if not os.path.isdir(mcplatform.saveFileDir): - alert(u"Could not find the Minecraft saves directory!\n\n({0} was not found or is not a directory)".format(mcplatform.saveFileDir)) + if not os.path.isdir(pymclevel.saveFileDir): + alert(u"Could not find the Minecraft saves directory!\n\n({0} was not found or is not a directory)".format(pymclevel.saveFileDir)) return worldPanel = Widget() - potentialWorlds = os.listdir(mcplatform.saveFileDir) - potentialWorlds = [os.path.join(mcplatform.saveFileDir, p) for p in potentialWorlds] - worldFiles = [p for p in potentialWorlds if MCInfdevOldLevel.isLevel(p)] + potentialWorlds = os.listdir(pymclevel.saveFileDir) + potentialWorlds = [os.path.join(pymclevel.saveFileDir, p) for p in potentialWorlds] + worldFiles = [p for p in potentialWorlds if pymclevel.MCInfdevOldLevel.isLevel(p)] worlds = [] for f in worldFiles: try: - lev = MCInfdevOldLevel(f) + lev = pymclevel.MCInfdevOldLevel(f) except Exception: continue else: @@ -2944,18 +2945,18 @@ def createNewLevel(self): label = Label("Creating a new world.") generatorPanel = GeneratorPanel() - xinput = IntInputRow("X: ", ref=AttrRef(newWorldPanel, "x")) - yinput = IntInputRow("Y: ", ref=AttrRef(newWorldPanel, "y")) - zinput = IntInputRow("Z: ", ref=AttrRef(newWorldPanel, "z")) - finput = IntInputRow("f: ", ref=AttrRef(newWorldPanel, "f"), min=0, max=3) + xinput = mceutils.IntInputRow("X: ", ref=AttrRef(newWorldPanel, "x")) + yinput = mceutils.IntInputRow("Y: ", ref=AttrRef(newWorldPanel, "y")) + zinput = mceutils.IntInputRow("Z: ", ref=AttrRef(newWorldPanel, "z")) + finput = mceutils.IntInputRow("f: ", ref=AttrRef(newWorldPanel, "f"), min=0, max=3) xyzrow = Row([xinput, yinput, zinput, finput]) - seedinput = IntInputRow("Seed: ", width=250, ref=AttrRef(newWorldPanel, "seed")) + seedinput = mceutils.IntInputRow("Seed: ", width=250, ref=AttrRef(newWorldPanel, "seed")) - winput = IntInputRow("East-West Chunks: ", ref=AttrRef(newWorldPanel, "w"), min=0) - hinput = IntInputRow("North-South Chunks: ", ref=AttrRef(newWorldPanel, "h"), min=0) + winput = mceutils.IntInputRow("East-West Chunks: ", ref=AttrRef(newWorldPanel, "w"), min=0) + hinput = mceutils.IntInputRow("North-South Chunks: ", ref=AttrRef(newWorldPanel, "h"), min=0) # grassinputrow = Row( (Label("Grass: ") # from editortools import BlockButton - # blockInput = BlockButton(alphaMaterials, alphaMaterials.Grass) + # blockInput = BlockButton(pymclevel.alphaMaterials, pymclevel.alphaMaterials.Grass) # blockInputRow = Row( (Label("Surface: "), blockInput) ) types = ["Survival", "Creative"] @@ -2979,7 +2980,7 @@ def action(): result = Dialog(client=newWorldPanel, responses=["Create", "Cancel"]).present() if result == "Cancel": return - filename = mcplatform.askCreateWorld(saveFileDir) + filename = mcplatform.askCreateWorld(pymclevel.saveFileDir) if not filename: return @@ -2994,7 +2995,7 @@ def action(): self.freezeStatus("Creating world...") try: - newlevel = MCInfdevOldLevel(filename=filename, create=True, random_seed=seed) + newlevel = pymclevel.MCInfdevOldLevel(filename=filename, create=True, random_seed=seed) # chunks = list(itertools.product(xrange(w / 2 - w + cx, w / 2 + cx), xrange(h / 2 - h + cz, h / 2 + cz))) if generatorPanel.generatorChoice.selectedChoice == "Flatland": @@ -3006,14 +3007,14 @@ def action(): newlevel.setPlayerSpawnPosition((x, y + 1, z)) newlevel.GameType = gametypeButton.gametype newlevel.saveInPlace() - worker = generatorPanel.generate(newlevel, BoundingBox((x - w * 8, 0, z - h * 8), (w * 16, newlevel.Height, h * 16))) + worker = generatorPanel.generate(newlevel, pymclevel.BoundingBox((x - w * 8, 0, z - h * 8), (w * 16, newlevel.Height, h * 16))) - if "Canceled" == showProgress("Generating chunks...", worker, cancel=True): + if "Canceled" == mceutils.showProgress("Generating chunks...", worker, cancel=True): raise RuntimeError("Canceled.") if y < 64: y = 64 - newlevel.setBlockAt(x, y, z, alphaMaterials.Sponge.ID) + newlevel.setBlockAt(x, y, z, pymclevel.alphaMaterials.Sponge.ID) self.loadFile(filename) except Exception: @@ -3081,11 +3082,11 @@ def pasteSchematic(self, schematic): def deleteSelectedBlocks(self): self.selectionTool.deleteBlocks() - @alertException + @mceutils.alertException def undo(self): if len(self.undoStack) == 0: return - with setWindowCaption("UNDOING - "): + with mceutils.setWindowCaption("UNDOING - "): self.freezeStatus("Undoing the previous operation...") op = self.undoStack.pop() op.undo() @@ -3154,13 +3155,13 @@ def gl_draw(self): self.frameSamples.pop(0) self.frameSamples.append(timeDelta) - frameTotal = sum(self.frameSamples) + frameTotal = numpy.sum(self.frameSamples) self.averageFPS = 1000000. / ((frameTotal.microseconds + 1000000 * frameTotal.seconds) / float(len(self.frameSamples)) + 0.00001) r = self.renderer - chunkTotal = sum(r.chunkSamples) + chunkTotal = numpy.sum(r.chunkSamples) cps = 1000000. / ((chunkTotal.microseconds + 1000000 * chunkTotal.seconds) / float(len(r.chunkSamples)) + 0.00001) self.averageCPS = cps @@ -3180,7 +3181,7 @@ def gl_draw(self): dl=len(glutils.DisplayList.allLists), dlcount=glutils.gl.listCount, t=len(glutils.Texture.allTextures), g=len(gc.garbage)) - if isinstance(self.level, MCInfdevOldLevel): + if isinstance(self.level, pymclevel.MCInfdevOldLevel): self.debugString += "Loa: {0}, Dec: {1}, ".format(len(self.level.loadedChunkQueue), len(self.level.decompressedChunkQueue)) if self.renderer: @@ -3196,7 +3197,7 @@ def createWorkInfoPanel(self): progress = Label("{0} chunks ({1} pending updates)".format(len(w.chunkRenderers), len(w.invalidChunkQueue))) col = Column((label, progress), align="l", width=200) infos.append(col) - elif isinstance(w, RunningOperation): + elif isinstance(w, RunningOperation): # **FIXME** Where is RunningOperation supposed to come from? -David Sowder 20120311 label = Label(w.description) progress = Label(w.progress) col = Column((label, progress), align="l", width=200) @@ -3238,7 +3239,7 @@ def updateInspectionString(self, blockPosition): try: if self.debug: - if isinstance(self.level, MCIndevLevel): + if isinstance(self.level, pymclevel.MCIndevLevel): bl = self.level.blockLightAt(*blockPosition) blockID = self.level.blockAt(*blockPosition) bdata = self.level.blockDataAt(*blockPosition) @@ -3246,7 +3247,7 @@ def updateInspectionString(self, blockPosition): blockID, bdata, self.level.materials.names[blockID][bdata]) self.inspectionString += "Data: %d, Light: %d, " % (bdata, bl) - elif isinstance(self.level, pymclevel.infiniteworld.ChunkedLevelMixin): + elif isinstance(self.level, pymclevel.ChunkedLevelMixin): sl = self.level.skylightAt(*blockPosition) bl = self.level.blockLightAt(*blockPosition) bdata = self.level.blockDataAt(*blockPosition) @@ -3294,19 +3295,19 @@ def updateInspectionString(self, blockPosition): blockID, self.level.materials.names[blockID][0]) except Exception, e: - self.inspectionString += "Chunk {0} had an error: {1!r}".format((int(floor(blockPosition[0])) >> 4, int(floor(blockPosition[2])) >> 4), e) + self.inspectionString += "Chunk {0} had an error: {1!r}".format((int(numpy.floor(blockPosition[0])) >> 4, int(numpy.floor(blockPosition[2])) >> 4), e) pass def drawWireCubeReticle(self, color=(1.0, 1.0, 1.0, 1.0), position=None): - glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) - glEnable(GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) + OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) blockPosition, faceDirection = self.blockFaceUnderCursor blockPosition = position or blockPosition - drawTerrainCuttingWire(BoundingBox(blockPosition, (1, 1, 1)), c1=color) + mceutils.drawTerrainCuttingWire(pymclevel.BoundingBox(blockPosition, (1, 1, 1)), c1=color) - glDisable(GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) def drawString(self, x, y, color, string): return @@ -3314,18 +3315,18 @@ def drawString(self, x, y, color, string): def freezeStatus(self, string): return -# glColor(1.0, 0., 0., 1.0) +# OpenGL.GL.glColor(1.0, 0., 0., 1.0) # -# # glDrawBuffer(GL_FRONT) -# glMatrixMode(GL_PROJECTION) -# glPushMatrix() +# # glDrawBuffer(OpenGL.GL.GL_FRONT) +# OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) +# OpenGL.GL.glPushMatrix() # glRasterPos(50, 100) # for i in string: # glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(i)) # -# # glDrawBuffer(GL_BACK) -# glMatrixMode(GL_PROJECTION) -# glPopMatrix() +# # glDrawBuffer(OpenGL.GL.GL_BACK) +# OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) +# OpenGL.GL.glPopMatrix() # glFlush() # display.flip() # # while(True): pass @@ -3415,23 +3416,23 @@ def idleHandler(evt): ## ## print blockCount, fbo ## -## destBlocks = zeros(blockCount, 'uint8') +## destBlocks = numpy.zeros(blockCount, 'uint8') ## (sourceTex, destTex) = glGenTextures(2) ## ## glBindTexture(GL_TEXTURE_3D, sourceTex) ## glTexImage3D(GL_TEXTURE_3D, 0, 1, ## level.Width, level.Length, level.Height, -## 0, GL_RED, GL_UNSIGNED_BYTE, +## 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE, ## blocks) ## ## # return ## -## glBindTexture(GL_TEXTURE_2D, destTex) -## glTexImage2D(GL_TEXTURE_2D, 0, 1, +## glBindTexture(OpenGL.GL.GL_TEXTURE_2D, destTex) +## glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, 0, 1, ## level.Width, level.Length, -## 0, GL_RED, GL_UNSIGNED_BYTE, destBlocks) -## glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) -## glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, destTex, 0) +## 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE, destBlocks) +## glTexParameter(OpenGL.GL.GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) +## glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, OpenGL.GL.GL_TEXTURE_2D, destTex, 0) ## ## vertShader = glCreateShader(GL_VERTEX_SHADER) ## @@ -3467,13 +3468,13 @@ def idleHandler(evt): ## ## glUseProgram(prog); ## # return -## glDisable(GL_DEPTH_TEST); -## glVertexPointer(2, GL_FLOAT, 0, [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]); -## glDrawArrays(GL_QUADS, 0, 4); -## glEnable(GL_DEPTH_TEST); +## OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST); +## OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]); +## OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4); +## OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST); ## ## glFlush(); -## destBlocks = glGetTexImage(GL_TEXTURE_2D, 0, GL_RED, GL_UNSIGNED_BYTE); +## destBlocks = glGetTexImage(OpenGL.GL.GL_TEXTURE_2D, 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE); ## print destBlocks, destBlocks[0:8]; ## raise SystemExit; @@ -3526,7 +3527,7 @@ def __init__(self, rect, tools, *args, **kw): t.hotkey = i + 1 self.toolTextures = {} - self.toolbarDisplayList = DisplayList() + self.toolbarDisplayList = glutils.DisplayList() self.reloadTextures() def set_parent(self, parent): @@ -3613,7 +3614,7 @@ def toolTextureChanged(self): def reloadTextures(self): self.toolTextureChanged() - self.guiTexture = loadPNGTexture('gui.png') + self.guiTexture = mceutils.loadPNGTexture('gui.png') self.toolTextures = {} for tool in self.tools: @@ -3623,27 +3624,27 @@ def reloadTextures(self): tool.markerList.invalidate() def drawToolbar(self): - glEnableClientState(GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) - glColor(1., 1., 1., 1.) + OpenGL.GL.glColor(1., 1., 1., 1.) w, h = self.toolbarTextureSize self.guiTexture.bind() - glVertexPointer(3, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( 1, h + 1, 0.5, w + 1, h + 1, 0.5, w + 1, 1, 0.5, 1, 1, 0.5, ), dtype="f4")) - glTexCoordPointer(2, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( 0, 0, w, 0, w, h, 0, h, ), dtype="f4")) - glDrawArrays(GL_QUADS, 0, 4) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) for i in range(len(self.tools)): tool = self.tools[i] @@ -3652,44 +3653,44 @@ def drawToolbar(self): try: if not tool.toolIconName in self.toolTextures: filename = "toolicons" + os.sep + "{0}.png".format(tool.toolIconName) - self.toolTextures[tool.toolIconName] = loadPNGTexture(filename) + self.toolTextures[tool.toolIconName] = mceutils.loadPNGTexture(filename) x = 20 * i + 4 y = 4 w = 16 h = 16 self.toolTextures[tool.toolIconName].bind() - glVertexPointer(3, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( x, y + h, 1, x + w, y + h, 1, x + w, y, 1, x, y, 1, ), dtype="f4")) - glTexCoordPointer(2, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( 0, 0, w * 16, 0, w * 16, h * 16, 0, h * 16, ), dtype="f4")) - glDrawArrays(GL_QUADS, 0, 4) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) except Exception: logging.exception('Error while drawing toolbar.') - glDisableClientState(GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) gfont = None def gl_draw(self): - glEnable(GL_TEXTURE_2D) - glEnable(GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) self.toolbarDisplayList.call(self.drawToolbar) - glColor(1.0, 1.0, 0.0) + OpenGL.GL.glColor(1.0, 1.0, 0.0) - # glEnable(GL_BLEND) + # OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) # with gl.glPushMatrix(GL_TEXTURE): - # glLoadIdentity() + # OpenGL.GL.glLoadIdentity() # self.gfont.flatPrint("ADLADLADLADLADL") try: @@ -3712,29 +3713,29 @@ def gl_draw(self): ty = 0. tw = 24. th = 24. - glEnableClientState(GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) self.guiTexture.bind() - glVertexPointer(3, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( tx, ty, 2, tx + tw, ty, 2, tx + tw, ty + th, 2, tx, ty + th, 2, ), dtype="f4")) - glTexCoordPointer(2, GL_FLOAT, 0, numpy.array(( + OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( texx, texy + texh, texx + texw, texy + texh, texx + texw, texy, texx, texy, ), dtype="f4")) - glDrawArrays(GL_QUADS, 0, 4) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) - glDisableClientState(GL_TEXTURE_COORD_ARRAY) - glDisable(GL_TEXTURE_2D) + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) - redOutBoxes = zeros(9 * 4 * 2, dtype='float32') + redOutBoxes = numpy.zeros(9 * 4 * 2, dtype='float32') cursor = 0 for i in range(len(self.tools)): t = self.tools[i] @@ -3749,8 +3750,8 @@ def gl_draw(self): cursor += 8 if cursor: - glColor(1.0, 0.0, 0.0, 0.3) - glVertexPointer(2, GL_FLOAT, 0, redOutBoxes) - glDrawArrays(GL_QUADS, 0, cursor / 2) + OpenGL.GL.glColor(1.0, 0.0, 0.0, 0.3) + OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, redOutBoxes) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, cursor / 2) - glDisable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) diff --git a/mcedit.py b/mcedit.py index 86fff6d..ee12816 100755 --- a/mcedit.py +++ b/mcedit.py @@ -5,55 +5,51 @@ Startup, main menu, keyboard configuration, automatic updating. """ -import os -import os.path -import sys -import config -import shutil -import functools -import traceback -import logging - -import pygame -from pygame.constants import * -from pygame import key, display, rect +import albow +from albow.dialogs import Dialog from albow.openglwidgets import GLViewport from albow.root import RootWidget -from albow.dialogs import Dialog -from albow import * +import config +import directories +import functools from glbackground import Panel - -from OpenGL import GL -from numpy import * - -from pymclevel.mclevel import MCInfdevOldLevel, saveFileDir -from pymclevel.materials import * -MCInfdevOldLevel.loadedChunkLimit = 0 - -from release import release - +import glutils import leveleditor +from leveleditor import ControlSettings, Settings +import logging +import mceutils import mcplatform -from mceutils import * from mcplatform import platform_open -from leveleditor import Settings, ControlSettings +import numpy +from OpenGL import GL +import os +import os.path +import pygame +from pygame import display, key, rect +import pymclevel +import release +import shutil +import sys +import traceback + +pymclevel.MCInfdevOldLevel.loadedChunkLimit = 0 ESCAPE = '\033' -class FileOpener(Widget): +class FileOpener(albow.Widget): is_gl_container = True def __init__(self, mcedit, *args, **kwargs): kwargs['rect'] = mcedit.rect - Widget.__init__(self, *args, **kwargs) + albow.Widget.__init__(self, *args, **kwargs) self.anchor = 'tlbr' self.mcedit = mcedit helpColumn = [] - label = Label("{0} {1} {2} {3} {4} {5}".format( + label = albow.Label("{0} {1} {2} {3} {4} {5}".format( config.config.get('Keys', 'Forward'), config.config.get('Keys', 'Left'), config.config.get('Keys', 'Back'), @@ -66,7 +62,7 @@ def __init__(self, mcedit, *args, **kwargs): helpColumn.append(label) def addHelp(text): - label = Label(text) + label = albow.Label(text) label.anchor = 'whrt' label.align = "r" helpColumn.append(label) @@ -77,21 +73,21 @@ def addHelp(text): addHelp("Hold SHIFT to move along a major axis") addHelp("Hold ALT for details") - helpColumn = Column(helpColumn, align="r") + helpColumn = albow.Column(helpColumn, align="r") helpColumn.topright = self.topright helpColumn.anchor = "whrt" #helpColumn.is_gl_container = True self.add(helpColumn) - keysColumn = [Label("")] + keysColumn = [albow.Label("")] buttonsColumn = [leveleditor.ControlPanel.getHeader()] shortnames = [] for world in self.mcedit.recentWorlds(): shortname = os.path.basename(world) try: - if MCInfdevOldLevel.isLevel(world): - lev = MCInfdevOldLevel(world) + if pymclevel.MCInfdevOldLevel.isLevel(world): + lev = pymclevel.MCInfdevOldLevel(world) shortname = lev.LevelName if lev.LevelName != lev.displayName: shortname = u"{0} ({1})".format(lev.LevelName, lev.displayName) @@ -112,13 +108,13 @@ def addHelp(text): ('F{0}'.format(i + 1), shortnames[i], self.createLoadButtonHandler(world)) for i, world in enumerate(self.mcedit.recentWorlds())]) - commandRow = HotkeyColumn(hotkeys, keysColumn, buttonsColumn) + commandRow = mceutils.HotkeyColumn(hotkeys, keysColumn, buttonsColumn) commandRow.anchor = 'lrh' sideColumn = mcedit.makeSideColumn() sideColumn.anchor = 'wh' - contentRow = Row((commandRow, sideColumn)) + contentRow = albow.Row((commandRow, sideColumn)) contentRow.center = self.center contentRow.anchor = "rh" self.add(contentRow) @@ -134,7 +130,7 @@ def idleevent(self, evt): def key_down(self, evt): keyname = key.name(evt.key) - if keyname == 'f4' and (key.get_mods() & (KMOD_ALT | KMOD_LALT | KMOD_RALT)): + if keyname == 'f4' and (key.get_mods() & (pygame.KMOD_ALT | pygame.KMOD_LALT | pygame.KMOD_RALT)): raise SystemExit if keyname in ('f1', 'f2', 'f3', 'f4', 'f5'): self.mcedit.loadRecentWorldNumber(int(keyname[1])) @@ -247,32 +243,32 @@ class KeyConfigPanel(Dialog): def __init__(self): Dialog.__init__(self) - keyConfigTable = TableView(columns=[TableColumn("Command", 400, "l"), TableColumn("Assigned Key", 150, "r")]) + keyConfigTable = albow.TableView(columns=[albow.TableColumn("Command", 400, "l"), albow.TableColumn("Assigned Key", 150, "r")]) keyConfigTable.num_rows = lambda: len(self.keyConfigKeys) keyConfigTable.row_data = self.getRowData keyConfigTable.row_is_selected = lambda x: x == self.selectedKeyIndex keyConfigTable.click_row = self.selectTableRow - tableWidget = Widget() + tableWidget = albow.Widget() tableWidget.add(keyConfigTable) tableWidget.shrink_wrap() self.keyConfigTable = keyConfigTable - buttonRow = (Button("Assign Key...", action=self.askAssignSelectedKey), - Button("Done", action=self.dismiss)) + buttonRow = (albow.Button("Assign Key...", action=self.askAssignSelectedKey), + albow.Button("Done", action=self.dismiss)) - buttonRow = Row(buttonRow) + buttonRow = albow.Row(buttonRow) - choiceButton = ChoiceButton(["WASD", "Arrows", "Numpad"], choose=self.choosePreset) + choiceButton = mceutils.ChoiceButton(["WASD", "Arrows", "Numpad"], choose=self.choosePreset) if config.config.get("Keys", "Forward") == "up": choiceButton.selectedChoice = "Arrows" if config.config.get("Keys", "Forward") == "[8]": choiceButton.selectedChoice = "Numpad" - choiceRow = Row((Label("Presets: "), choiceButton)) + choiceRow = albow.Row((albow.Label("Presets: "), choiceButton)) self.choiceButton = choiceButton - col = Column((tableWidget, choiceRow, buttonRow)) + col = albow.Column((tableWidget, choiceRow, buttonRow)) self.add(col) self.shrink_wrap() @@ -310,7 +306,7 @@ def askAssignKey(self, configKey, labelString=None): if labelString is None: labelString = "Press a key to assign to the action \"{0}\"\n\nPress ESC to cancel.".format(configKey) - label = Label(labelString) + label = albow.Label(labelString) panel.add(label) panel.shrink_wrap() @@ -361,34 +357,34 @@ def packChanged(): self.texturePackChoice.selectedChoice = self.texturePack self.texturePackChoice.choices = packs - self.texturePackChoice = texturePackChoice = ChoiceButton(getPacks(), choose=packChanged) + self.texturePackChoice = texturePackChoice = mceutils.ChoiceButton(getPacks(), choose=packChanged) if self.texturePack in self.texturePackChoice.choices: self.texturePackChoice.selectedChoice = self.texturePack - texturePackRow = Row((Label("Skin: "), texturePackChoice)) + texturePackRow = albow.Row((albow.Label("Skin: "), texturePackChoice)) - fieldOfViewRow = FloatInputRow("Field of View: ", + fieldOfViewRow = mceutils.FloatInputRow("Field of View: ", ref=Settings.fov.propertyRef(), width=100, min=25, max=120) - targetFPSRow = IntInputRow("Target FPS: ", + targetFPSRow = mceutils.IntInputRow("Target FPS: ", ref=Settings.targetFPS.propertyRef(), width=100, min=1, max=60) - bufferLimitRow = IntInputRow("Vertex Buffer Limit (MB): ", + bufferLimitRow = mceutils.IntInputRow("Vertex Buffer Limit (MB): ", ref=Settings.vertexBufferLimit.propertyRef(), width=100, min=0) - fastLeavesRow = CheckBoxLabel("Fast Leaves", + fastLeavesRow = mceutils.CheckBoxLabel("Fast Leaves", ref=Settings.fastLeaves.propertyRef(), tooltipText="Leaves are solid, like Minecraft's 'Fast' graphics") - roughGraphicsRow = CheckBoxLabel("Rough Graphics", + roughGraphicsRow = mceutils.CheckBoxLabel("Rough Graphics", ref=Settings.roughGraphics.propertyRef(), tooltipText="All blocks are drawn the same way (overrides 'Fast Leaves')") - enableMouseLagRow = CheckBoxLabel("Enable Mouse Lag", + enableMouseLagRow = mceutils.CheckBoxLabel("Enable Mouse Lag", ref=Settings.enableMouseLag.propertyRef(), tooltipText="Enable choppy mouse movement for faster loading.") - settingsColumn = Column((fastLeavesRow, + settingsColumn = albow.Column((fastLeavesRow, roughGraphicsRow, enableMouseLagRow, texturePackRow, @@ -397,17 +393,17 @@ def packChanged(): bufferLimitRow, ), align='r') - settingsColumn = Column((Label("Settings"), + settingsColumn = albow.Column((albow.Label("Settings"), settingsColumn)) - settingsRow = Row((settingsColumn,)) + settingsRow = albow.Row((settingsColumn,)) - optionsColumn = Column((settingsRow, Button("OK", action=mcedit.removeGraphicOptions))) + optionsColumn = albow.Column((settingsRow, albow.Button("OK", action=mcedit.removeGraphicOptions))) self.add(optionsColumn) self.shrink_wrap() def _reloadTextures(self, pack): - if hasattr(alphaMaterials, "terrainTexture"): + if hasattr(pymclevel.alphaMaterials, "terrainTexture"): self.mcedit.displayContext.loadTextures() texturePack = Settings.skin.configProperty(_reloadTextures) @@ -421,67 +417,67 @@ def __init__(self, mcedit): self.mcedit = mcedit - autoBrakeRow = CheckBoxLabel("Autobrake", + autoBrakeRow = mceutils.CheckBoxLabel("Autobrake", ref=ControlSettings.autobrake.propertyRef(), tooltipText="Apply brake when not pressing movement keys") - swapAxesRow = CheckBoxLabel("Swap Axes Looking Down", + swapAxesRow = mceutils.CheckBoxLabel("Swap Axes Looking Down", ref=ControlSettings.swapAxes.propertyRef(), tooltipText="Change the direction of the Forward and Backward keys when looking down") - cameraAccelRow = FloatInputRow("Camera Acceleration: ", + cameraAccelRow = mceutils.FloatInputRow("Camera Acceleration: ", ref=ControlSettings.cameraAccel.propertyRef(), width=100, min=5.0) - cameraDragRow = FloatInputRow("Camera Drag: ", + cameraDragRow = mceutils.FloatInputRow("Camera Drag: ", ref=ControlSettings.cameraDrag.propertyRef(), width=100, min=1.0) - cameraMaxSpeedRow = FloatInputRow("Camera Max Speed: ", + cameraMaxSpeedRow = mceutils.FloatInputRow("Camera Max Speed: ", ref=ControlSettings.cameraMaxSpeed.propertyRef(), width=100, min=1.0) - cameraBrakeSpeedRow = FloatInputRow("Camera Braking Speed: ", + cameraBrakeSpeedRow = mceutils.FloatInputRow("Camera Braking Speed: ", ref=ControlSettings.cameraBrakingSpeed.propertyRef(), width=100, min=1.0) - mouseSpeedRow = FloatInputRow("Mouse Speed: ", + mouseSpeedRow = mceutils.FloatInputRow("Mouse Speed: ", ref=ControlSettings.mouseSpeed.propertyRef(), width=100, min=0.1, max=20.0) - invertRow = CheckBoxLabel("Invert Mouse", + invertRow = mceutils.CheckBoxLabel("Invert Mouse", ref=ControlSettings.invertMousePitch.propertyRef(), tooltipText="Reverse the up and down motion of the mouse.") - spaceHeightRow = IntInputRow("Low Detail Height", + spaceHeightRow = mceutils.IntInputRow("Low Detail Height", ref=Settings.spaceHeight.propertyRef(), tooltipText="When you are this far above the top of the world, move fast and use low-detail mode.") - blockBufferRow = IntInputRow("Block Buffer", + blockBufferRow = mceutils.IntInputRow("Block Buffer", ref=Settings.blockBuffer.propertyRef(), min=1, tooltipText="Amount of memory used for temporary storage. When more than this is needed, the disk is used instead.") - setWindowPlacementRow = CheckBoxLabel("Set Window Placement", + setWindowPlacementRow = mceutils.CheckBoxLabel("Set Window Placement", ref=Settings.setWindowPlacement.propertyRef(), tooltipText="Try to save and restore the window position.") - windowSizeRow = CheckBoxLabel("Window Resize Alert", + windowSizeRow = mceutils.CheckBoxLabel("Window Resize Alert", ref=Settings.shouldResizeAlert.propertyRef(), tooltipText="Reminds you that the cursor won't work correctly after resizing the window.") - visibilityCheckRow = CheckBoxLabel("Visibility Check", + visibilityCheckRow = mceutils.CheckBoxLabel("Visibility Check", ref=Settings.visibilityCheck.propertyRef(), tooltipText="Do a visibility check on chunks while loading. May cause a crash.") - longDistanceRow = CheckBoxLabel("Long-Distance Mode", + longDistanceRow = mceutils.CheckBoxLabel("Long-Distance Mode", ref=Settings.longDistanceMode.propertyRef(), tooltipText="Always target the farthest block under the cursor, even in mouselook mode. Shortcut: ALT-Z") - flyModeRow = CheckBoxLabel("Fly Mode", + flyModeRow = mceutils.CheckBoxLabel("Fly Mode", ref=Settings.flyMode.propertyRef(), tooltipText="Moving forward and backward will not change your altitude in Fly Mode.") - self.goPortableButton = goPortableButton = Button("Change", action=self.togglePortable) + self.goPortableButton = goPortableButton = albow.Button("Change", action=self.togglePortable) goPortableButton.tooltipText = self.portableButtonTooltip() - goPortableRow = Row((ValueDisplay(ref=AttrRef(self, 'portableLabelText'), width=250, align='r'), goPortableButton)) + goPortableRow = albow.Row((albow.ValueDisplay(ref=albow.AttrRef(self, 'portableLabelText'), width=250, align='r'), goPortableButton)) - reportRow = CheckBoxLabel("Report Crashes", + reportRow = mceutils.CheckBoxLabel("Report Crashes", ref=Settings.reportCrashes.propertyRef(), tooltipText="Automatically report fatal errors to the author.") @@ -512,15 +508,15 @@ def __init__(self, mcedit): goPortableRow, ) - rightcol = Column(options, align='r') - leftcol = Column(inputs, align='r') + rightcol = albow.Column(options, align='r') + leftcol = albow.Column(inputs, align='r') - optionsColumn = Column((Label("Options"), - Row((leftcol, rightcol), align="t"))) + optionsColumn = albow.Column((albow.Label("Options"), + albow.Row((leftcol, rightcol), align="t"))) - settingsRow = Row((optionsColumn,)) + settingsRow = albow.Row((optionsColumn,)) - optionsColumn = Column((settingsRow, Button("OK", action=self.dismiss))) + optionsColumn = albow.Column((settingsRow, albow.Button("OK", action=self.dismiss))) self.add(optionsColumn) self.shrink_wrap() @@ -550,12 +546,12 @@ def togglePortable(self): textChoices[1] = "This will move your schematics to your Documents folder and your settings to your Preferences folder. Continue?" alertText = textChoices[mcplatform.portable] - if ask(alertText) == "OK": + if albow.ask(alertText) == "OK": try: [mcplatform.goPortable, mcplatform.goFixed][mcplatform.portable]() except Exception, e: traceback.print_exc() - alert(u"Error while moving files: {0}".format(repr(e))) + albow.alert(u"Error while moving files: {0}".format(repr(e))) self.goPortableButton.tooltipText = self.portableButtonTooltip() @@ -589,8 +585,8 @@ def __init__(self, displayContext, *args): if len(sys.argv) > 1: for arg in sys.argv[1:]: f = arg.decode(sys.getfilesystemencoding()) - if os.path.isdir(os.path.join(saveFileDir, f)): - f = os.path.join(saveFileDir, f) + if os.path.isdir(os.path.join(pymclevel.saveFileDir, f)): + f = os.path.join(pymclevel.saveFileDir, f) self.droppedLevel = f break if os.path.exists(f): @@ -701,7 +697,7 @@ def setRecentWorlds(self, worlds): def makeSideColumn(self): def showhistory(): try: - with file(os.path.join(mcplatform.dataDir), 'history.txt') as f: + with file(os.path.join(directories.dataDir), 'history.txt') as f: history = f.read() history = "\n".join(history.split("\n")[:16]) @@ -710,13 +706,13 @@ def showhistory(): except Exception, e: history = "Exception while reading history.txt: {0}".format(e) - if ask(history, ["Show history.txt", "OK"]) == "Show history.txt": - platform_open(os.path.join(mcplatform.dataDir), "history.txt") + if albow.ask(history, ["Show history.txt", "OK"]) == "Show history.txt": + platform_open(os.path.join(directories.dataDir), "history.txt") def showLicense(): - platform_open(os.path.join(mcplatform.dataDir, "LICENSE.txt")) + platform_open(os.path.join(directories.dataDir, "LICENSE.txt")) - readmePath = os.path.join(mcplatform.dataDir, "README.html") + readmePath = os.path.join(directories.dataDir, "README.html") hotkeys = ([("", "Keys", @@ -741,7 +737,7 @@ def showLicense(): showLicense), ]) - c = HotkeyColumn(hotkeys) + c = mceutils.HotkeyColumn(hotkeys) return c @@ -775,7 +771,7 @@ def resized(self, dw, dh): if not hasattr(self, 'resizeAlert'): self.resizeAlert = self.shouldResizeAlert if self.resizeAlert: - alert("Window size increased. You may have problems using the cursor until MCEdit is restarted.") + albow.alert("Window size increased. You may have problems using the cursor until MCEdit is restarted.") self.resizeAlert = False shouldResizeAlert = Settings.shouldResizeAlert.configProperty() @@ -806,7 +802,7 @@ def createNewWorld(self): self.add(self.editor) self.focus_switch = self.editor - alert("World created. To expand this infinite world, explore the world in Minecraft or use the Chunk Control tool to add or delete chunks.") + albow.alert("World created. To expand this infinite world, explore the world in Minecraft or use the Chunk Control tool to add or delete chunks.") def removeEditor(self): self.remove(self.editor) @@ -816,7 +812,7 @@ def removeEditor(self): def confirm_quit(self): if self.editor.unsavedEdits: - result = ask("There are {0} unsaved changes.".format(self.editor.unsavedEdits), + result = albow.ask("There are {0} unsaved changes.".format(self.editor.unsavedEdits), responses=["Save and Quit", "Quit", "Cancel"]) if result == "Save and Quit": self.saveAndQuit() @@ -848,8 +844,8 @@ def main(self): rootwidget.add(mcedit) rootwidget.focus_switch = mcedit - if 0 == len(alphaMaterials.yamlDatas): - alert("Failed to load minecraft.yaml. Check the console window for details.") + if 0 == len(pymclevel.alphaMaterials.yamlDatas): + albow.alert("Failed to load minecraft.yaml. Check the console window for details.") if mcedit.droppedLevel: mcedit.loadFile(mcedit.droppedLevel) @@ -882,7 +878,7 @@ def main(self): raise SystemExit() if mcedit.closeMinecraftWarning: - answer = ask("Warning: You must close Minecraft completely before editing. Save corruption may result. Get Satisfaction to learn more.", ["Get Satisfaction", "Don't remind me again.", "OK"], default=1, cancel=1) + answer = albow.ask("Warning: You must close Minecraft completely before editing. Save corruption may result. Get Satisfaction to learn more.", ["Get Satisfaction", "Don't remind me again.", "OK"], default=1, cancel=1) if answer == "Get Satisfaction": mcplatform.platform_open("http://getsatisfaction.com/mojang/topics/region_file_cache_interferes_with_map_editors_risking_save_corruption") if answer == "Don't remind me again.": @@ -941,7 +937,7 @@ def main(argv): try: if not os.path.exists(mcplatform.schematicsDir): shutil.copytree( - os.path.join(mcplatform.dataDir, u'stock-schematics'), + os.path.join(directories.dataDir, u'stock-schematics'), mcplatform.schematicsDir ) except Exception, e: @@ -971,16 +967,16 @@ def getWindowSize(self): return max(20, w), max(20, h) def displayMode(self): - displayMode = OPENGL | RESIZABLE + displayMode = pygame.OPENGL | pygame.RESIZABLE if Settings.doubleBuffer.get(): - displayMode |= DOUBLEBUF + displayMode |= pygame.DOUBLEBUF return displayMode def reset(self): pygame.key.set_repeat(500, 100) try: - display.gl_set_attribute(GL_SWAP_CONTROL, Settings.vsync.get()) + display.gl_set_attribute(pygame.GL_SWAP_CONTROL, Settings.vsync.get()) except Exception, e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) @@ -1013,9 +1009,9 @@ def reset(self): config.saveConfig() try: - iconpath = os.path.join(mcplatform.dataDir, 'favicon.png') + iconpath = os.path.join(directories.dataDir, 'favicon.png') iconfile = file(iconpath, 'rb') - icon = image.load(iconfile, 'favicon.png') + icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception, e: logging.warning('Unable to set icon: {0!r}'.format(e)) @@ -1040,7 +1036,7 @@ def loadTextures(self): def makeTerrainTexture(mats): w, h = 1, 1 - teximage = zeros((w, h, 4), dtype='uint8') + teximage = numpy.zeros((w, h, 4), dtype='uint8') teximage[:] = 127, 127, 127, 255 GL.glTexImage2D( @@ -1056,25 +1052,25 @@ def makeTerrainTexture(mats): ) textures = ( - (classicMaterials, 'terrain-classic.png'), - (indevMaterials, 'terrain-classic.png'), - (alphaMaterials, 'terrain.png'), - (pocketMaterials, 'terrain-pocket.png') + (pymclevel.classicMaterials, 'terrain-classic.png'), + (pymclevel.indevMaterials, 'terrain-classic.png'), + (pymclevel.alphaMaterials, 'terrain.png'), + (pymclevel.pocketMaterials, 'terrain-pocket.png') ) for mats, matFile in textures: try: if mats.name == 'Alpha': - tex = loadAlphaTerrainTexture() + tex = mceutils.loadAlphaTerrainTexture() else: - tex = loadPNGTexture(matFile) + tex = mceutils.loadPNGTexture(matFile) self.terrainTextures[mats.name] = tex except Exception, e: logging.warning( 'Unable to load terrain from {0}, using flat colors.' 'Error was: {1!r}'.format(matFile, e) ) - self.terrainTextures[mats.name] = Texture( + self.terrainTextures[mats.name] = glutils.Texture( functools.partial(makeTerrainTexture, mats) ) mats.terrainTexture = self.terrainTextures[mats.name] diff --git a/mceutils.py b/mceutils.py index 0301dfc..2fc4555 100644 --- a/mceutils.py +++ b/mceutils.py @@ -18,29 +18,26 @@ Exception catching, some basic box drawing, texture pack loading, oddball UI elements """ -from OpenGL import GL, GLU -import numpy +from albow.controls import ValueDisplay +from albow import alert, ask, Button, Column, Label, root, Row, ValueButton, Widget +import config +from cStringIO import StringIO +from datetime import datetime +import directories +from errorreporting import reportCrash, reportException import httplib -import sys +import mcplatform +import numpy +from OpenGL import GL, GLU import os import platform -import traceback -import zipfile -from cStringIO import StringIO -from datetime import datetime - -from pygame import image, display, Surface import png -import config -import release -import mcplatform -from albow import ask, alert, Widget, Button, ValueButton, Column, Row, Label, root +from pygame import display, image, Surface import pymclevel -from albow.controls import ValueDisplay -from pymclevel import materials - - -from errorreporting import reportException, reportCrash +import release +import sys +import traceback +import zipfile def alertException(func): @@ -55,14 +52,12 @@ def _alertException(*args, **kw): return _alertException -from pymclevel.faces import * - def drawFace(box, face, type=GL.GL_QUADS): x, y, z, = box.origin x2, y2, z2 = box.maximum - if face == FaceXDecreasing: + if face == pymclevel.faces.FaceXDecreasing: faceVertices = numpy.array( (x, y2, z2, @@ -71,7 +66,7 @@ def drawFace(box, face, type=GL.GL_QUADS): x, y, z2, ), dtype='f4') - elif face == FaceXIncreasing: + elif face == pymclevel.faces.FaceXIncreasing: faceVertices = numpy.array( (x2, y, z2, @@ -80,7 +75,7 @@ def drawFace(box, face, type=GL.GL_QUADS): x2, y2, z2, ), dtype='f4') - elif face == FaceYDecreasing: + elif face == pymclevel.faces.FaceYDecreasing: faceVertices = numpy.array( (x2, y, z2, x, y, z2, @@ -88,7 +83,7 @@ def drawFace(box, face, type=GL.GL_QUADS): x2, y, z, ), dtype='f4') - elif face == FaceYIncreasing: + elif face == pymclevel.faces.FaceYIncreasing: faceVertices = numpy.array( (x2, y2, z, x, y2, z, @@ -96,7 +91,7 @@ def drawFace(box, face, type=GL.GL_QUADS): x2, y2, z2, ), dtype='f4') - elif face == FaceZDecreasing: + elif face == pymclevel.faces.FaceZDecreasing: faceVertices = numpy.array( (x, y, z, x, y2, z, @@ -104,7 +99,7 @@ def drawFace(box, face, type=GL.GL_QUADS): x2, y, z, ), dtype='f4') - elif face == FaceZIncreasing: + elif face == pymclevel.faces.FaceZIncreasing: faceVertices = numpy.array( (x2, y, z2, x2, y2, z2, @@ -356,7 +351,7 @@ def slurpZipExt(zipextfile): if foliageColorFile is not None: w, h, data = loadPNGData(slurpZipExt(foliageColorFile)) color = data[77, 55, :3] - materials.alphaMaterials.flatColors[17, 0, :3] = color # xxxxxxx + pymclevel.materials.alphaMaterials.flatColors[17, 0, :3] = color # xxxxxxx color = [c / 255.0 for c in color] LeafBlockRenderer.leafColor = color @@ -366,7 +361,7 @@ def slurpZipExt(zipextfile): if grassColorFile is not None: w, h, data = loadPNGData(slurpZipExt(grassColorFile)) color = data[77, 55, :3] - materials.alphaMaterials.flatColors[2, 0, :3] = color # xxxxxxx + pymclevel.materials.alphaMaterials.flatColors[2, 0, :3] = color # xxxxxxx color = [c / 255.0 for c in color] GenericBlockRenderer.grassColor = color diff --git a/mcplatform.py b/mcplatform.py index d1f3171..47901a7 100644 --- a/mcplatform.py +++ b/mcplatform.py @@ -18,11 +18,10 @@ Platform-specific functions, folder paths, and the whole fixed/portable nonsense. """ -import sys +import directories import os -from os.path import join, exists, dirname - -from directories import * +from os.path import dirname, exists, join +import sys enc = sys.getfilesystemencoding() @@ -32,9 +31,9 @@ plat = "win32" if platform.architecture()[0] == "64bit": plat = "win-amd64" - sys.path.append(join(dataDir, "pymclevel", "build", "lib." + plat + "-2.6").encode(enc)) + sys.path.append(join(directories.dataDir, "pymclevel", "build", "lib." + plat + "-2.6").encode(enc)) -os.environ["YAML_ROOT"] = join(dataDir, "pymclevel").encode(enc) +os.environ["YAML_ROOT"] = join(directories.dataDir, "pymclevel").encode(enc) from pygame import display @@ -336,7 +335,7 @@ def platform_open(path): win32_window_size = True ini = u"mcedit.ini" -parentDir = dirname(dataDir) +parentDir = dirname(directories.dataDir) docsFolder = documents_folder() portableConfigFilePath = os.path.join(parentDir, ini) portableSchematicsDir = os.path.join(parentDir, u"MCEdit-schematics") @@ -419,7 +418,7 @@ def portableConfigExists(): schematicsDir = fixedSchematicsDir portable = False -filtersDir = os.path.join(dataDir, "filters") +filtersDir = os.path.join(directories.dataDir, "filters") if filtersDir not in [s.decode(sys.getfilesystemencoding()) if isinstance(s, str) else s @@ -434,4 +433,4 @@ def portableConfigExists(): else: jarStorage = ServerJarStorage() -items.items = items.Items(join(dataDir, "pymclevel", "items.txt")) +items.items = items.Items(join(directories.dataDir, "pymclevel", "items.txt")) diff --git a/renderer.py b/renderer.py index 258d29b..cf0ef82 100644 --- a/renderer.py +++ b/renderer.py @@ -37,36 +37,17 @@ One per block type, plus one for low detail and one for Entity """ -from collections import deque - -from numpy import * -import itertools - -from pymclevel import * -del sum -del any -del all # xxx use builtin all, fix the wild imports later +from collections import defaultdict, deque from datetime import datetime, timedelta -from time import sleep -from threading import Thread -from collections import defaultdict - from depths import DepthOffset - -import OpenGL - -from OpenGL import GL -from OpenGL.GL import * -from OpenGL.GLU import * -from OpenGL.GLUT import * -from OpenGL.GL.ARB.vertex_buffer_object import * -from OpenGL.GL.EXT.framebuffer_object import * - -from pymclevel.faces import * -import config -from mceutils import reportCrash from glutils import gl, Texture +import logging +import numpy +import OpenGL +import pymclevel +import sys +#import time def chunkMarkers(chunkSet): @@ -162,7 +143,7 @@ def makeDisplayLists(self): showRedraw = self.renderer.showRedraw if not (showRedraw and self.needsBlockRedraw): - glEnableClientState(GL_COLOR_ARRAY) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) renderers = self.blockRenderers @@ -176,7 +157,7 @@ def makeDisplayLists(self): lists[blockRenderer.renderstate].append(l) if not (showRedraw and self.needsBlockRedraw): - glDisableClientState(GL_COLOR_ARRAY) + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) self.needsRedisplay = False self.renderstateLists = lists @@ -245,16 +226,16 @@ def vertexArraysDone(self): def done(self): return len(self.invalidLayers) == 0 -_XYZ = s_[..., 0:3] -_ST = s_[..., 3:5] -_XYZST = s_[..., :5] -_RGBA = s_[..., 20:24] -_RGB = s_[..., 20:23] -_A = s_[..., 23] +_XYZ = numpy.s_[..., 0:3] +_ST = numpy.s_[..., 3:5] +_XYZST = numpy.s_[..., :5] +_RGBA = numpy.s_[..., 20:24] +_RGB = numpy.s_[..., 20:23] +_A = numpy.s_[..., 23] def makeVertexTemplates(xmin=0, ymin=0, zmin=0, xmax=1, ymax=1, zmax=1): - return array([ + return numpy.array([ # FaceXIncreasing: [[xmax, ymin, zmax, (zmin * 16), 16 - (ymin * 16), 0x0b], @@ -302,12 +283,12 @@ def makeVertexTemplates(xmin=0, ymin=0, zmin=0, xmax=1, ymax=1, zmax=1): def createPrecomputedVertices(): height = 16 - precomputedVertices = [zeros(shape=(16, 16, height, 4, 6), # x,y,z,s,t,rg, ba + precomputedVertices = [numpy.zeros(shape=(16, 16, height, 4, 6), # x,y,z,s,t,rg, ba dtype='float32') for d in faceVertexTemplates] - xArray = arange(16)[:, newaxis, newaxis, newaxis] - zArray = arange(16)[newaxis, :, newaxis, newaxis] - yArray = arange(height)[newaxis, newaxis, :, newaxis] + xArray = numpy.arange(16)[:, numpy.newaxis, numpy.newaxis, numpy.newaxis] + zArray = numpy.arange(16)[numpy.newaxis, :, numpy.newaxis, numpy.newaxis] + yArray = numpy.arange(height)[numpy.newaxis, numpy.newaxis, :, numpy.newaxis] for dir in range(len(faceVertexTemplates)): precomputedVertices[dir][_XYZ][..., 0] = xArray @@ -316,7 +297,7 @@ def createPrecomputedVertices(): precomputedVertices[dir][_XYZ] += faceVertexTemplates[dir][..., 0:3] # xyz precomputedVertices[dir][_ST] = faceVertexTemplates[dir][..., 3:5] # s - precomputedVertices[dir].view('uint8')[_RGB] = faceVertexTemplates[dir][..., 5, newaxis] + precomputedVertices[dir].view('uint8')[_RGB] = faceVertexTemplates[dir][..., 5, numpy.newaxis] precomputedVertices[dir].view('uint8')[_A] = 0xff return precomputedVertices @@ -328,14 +309,14 @@ class ChunkCalculator (object): cachedTemplate = None cachedTemplateHeight = 0 - whiteLight = array([[[15] * 16] * 16] * 16, uint8) + whiteLight = numpy.array([[[15] * 16] * 16] * 16, numpy.uint8) precomputedVertices = createPrecomputedVertices() def __init__(self, level): self.makeRenderstates(level.materials) # del xArray, zArray, yArray - self.nullVertices = zeros((0,) * len(self.precomputedVertices[0].shape), dtype=self.precomputedVertices[0].dtype) + self.nullVertices = numpy.zeros((0,) * len(self.precomputedVertices[0].shape), dtype=self.precomputedVertices[0].dtype) from leveleditor import Settings Settings.fastLeaves.addObserver(self) @@ -353,31 +334,31 @@ def release(self): class renderstateLowDetail(object): @classmethod def bind(self): - glDisable(GL_CULL_FACE) - glDisable(GL_TEXTURE_2D) + OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) @classmethod def release(self): - glEnable(GL_CULL_FACE) - glEnable(GL_TEXTURE_2D) + OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) class renderstateAlphaTest(object): @classmethod def bind(self): - glEnable(GL_ALPHA_TEST) + OpenGL.GL.glEnable(OpenGL.GL.GL_ALPHA_TEST) @classmethod def release(self): - glDisable(GL_ALPHA_TEST) + OpenGL.GL.glDisable(OpenGL.GL.GL_ALPHA_TEST) class _renderstateAlphaBlend(object): @classmethod def bind(self): - glEnable(GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) @classmethod def release(self): - glDisable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) class renderstateWater(_renderstateAlphaBlend): pass @@ -388,17 +369,17 @@ class renderstateIce(_renderstateAlphaBlend): class renderstateEntity(object): @classmethod def bind(self): - glDisable(GL_DEPTH_TEST) - # glDisable(GL_CULL_FACE) - glDisable(GL_TEXTURE_2D) - glEnable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + # OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) @classmethod def release(self): - glEnable(GL_DEPTH_TEST) - # glEnable(GL_CULL_FACE) - glEnable(GL_TEXTURE_2D) - glDisable(GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + # OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) renderstates = ( renderstatePlain, @@ -438,7 +419,7 @@ def makeRenderstates(self, materials): # portal ] - self.materialMap = materialMap = zeros((256,), 'uint8') + self.materialMap = materialMap = numpy.zeros((256,), 'uint8') materialMap[1:] = 1 # generic blocks materialCount = 2 @@ -448,29 +429,29 @@ def makeRenderstates(self, materials): br.materialIndex = materialCount materialCount += 1 - self.exposedMaterialMap = array(materialMap) + self.exposedMaterialMap = numpy.array(materialMap) self.addTransparentMaterials(self.exposedMaterialMap, materialCount) def addTransparentMaterials(self, mats, materialCount): transparentMaterials = [ - alphaMaterials.Glass, - alphaMaterials.GlassPane, - alphaMaterials.IronBars, - alphaMaterials.MonsterSpawner, - alphaMaterials.Vines, - alphaMaterials.Fire, + pymclevel.materials.alphaMaterials.Glass, + pymclevel.materials.alphaMaterials.GlassPane, + pymclevel.materials.alphaMaterials.IronBars, + pymclevel.materials.alphaMaterials.MonsterSpawner, + pymclevel.materials.alphaMaterials.Vines, + pymclevel.materials.alphaMaterials.Fire, ] for b in transparentMaterials: mats[b.ID] = materialCount materialCount += 1 - hiddenOreMaterials = arange(256, dtype='uint8') + hiddenOreMaterials = numpy.arange(256, dtype='uint8') hiddenOreMaterials[2] = 1 # don't show boundaries between dirt,grass,sand,gravel,stone hiddenOreMaterials[3] = 1 hiddenOreMaterials[12] = 1 hiddenOreMaterials[13] = 1 - roughMaterials = ones((256,), dtype='uint8') + roughMaterials = numpy.ones((256,), dtype='uint8') roughMaterials[0] = 0 addTransparentMaterials(None, roughMaterials, 2) @@ -487,7 +468,7 @@ def calcFacesForChunkRenderer(self, cr): try: chunk = level.getChunk(cx, cz) except Exception, e: - warn(u"Error reading chunk: %s", e) + logging.warn(u"Error reading chunk: %s", e) yield return @@ -543,30 +524,30 @@ def getNeighboringChunks(self, chunk): level = chunk.world neighboringChunks = {} - for dir, dx, dz in ((FaceXDecreasing, -1, 0), - (FaceXIncreasing, 1, 0), - (FaceZDecreasing, 0, -1), - (FaceZIncreasing, 0, 1)): + for dir, dx, dz in ((pymclevel.faces.FaceXDecreasing, -1, 0), + (pymclevel.faces.FaceXIncreasing, 1, 0), + (pymclevel.faces.FaceZDecreasing, 0, -1), + (pymclevel.faces.FaceZIncreasing, 0, 1)): if not level.containsChunk(cx + dx, cz + dz): - neighboringChunks[dir] = ZeroChunk(level.Height) + neighboringChunks[dir] = pymclevel.infiniteworld.ZeroChunk(level.Height) else: # if not level.chunkIsLoaded(cx+dx,cz+dz): # raise StopIteration try: neighboringChunks[dir] = level.getChunk(cx + dx, cz + dz) - except (ChunkNotPresent, ChunkMalformed): - neighboringChunks[dir] = ZeroChunk(level.Height) + except (pymclevel.mclevelbase.ChunkNotPresent, pymclevel.mclevelbase.ChunkMalformed): + neighboringChunks[dir] = pymclevel.infiniteworld.ZeroChunk(level.Height) return neighboringChunks def getAreaBlocks(self, chunk, neighboringChunks): chunkWidth, chunkLength, chunkHeight = chunk.Blocks.shape - areaBlocks = zeros((chunkWidth + 2, chunkLength + 2, chunkHeight + 2), uint8) + areaBlocks = numpy.zeros((chunkWidth + 2, chunkLength + 2, chunkHeight + 2), numpy.uint8) areaBlocks[1:-1, 1:-1, 1:-1] = chunk.Blocks - areaBlocks[:1, 1:-1, 1:-1] = neighboringChunks[FaceXDecreasing].Blocks[-1:, :chunkLength, :chunkHeight] - areaBlocks[-1:, 1:-1, 1:-1] = neighboringChunks[FaceXIncreasing].Blocks[:1, :chunkLength, :chunkHeight] - areaBlocks[1:-1, :1, 1:-1] = neighboringChunks[FaceZDecreasing].Blocks[:chunkWidth, -1:, :chunkHeight] - areaBlocks[1:-1, -1:, 1:-1] = neighboringChunks[FaceZIncreasing].Blocks[:chunkWidth, :1, :chunkHeight] + areaBlocks[:1, 1:-1, 1:-1] = neighboringChunks[pymclevel.faces.FaceXDecreasing].Blocks[-1:, :chunkLength, :chunkHeight] + areaBlocks[-1:, 1:-1, 1:-1] = neighboringChunks[pymclevel.faces.FaceXIncreasing].Blocks[:1, :chunkLength, :chunkHeight] + areaBlocks[1:-1, :1, 1:-1] = neighboringChunks[pymclevel.faces.FaceZDecreasing].Blocks[:chunkWidth, -1:, :chunkHeight] + areaBlocks[1:-1, -1:, 1:-1] = neighboringChunks[pymclevel.faces.FaceZIncreasing].Blocks[:chunkWidth, :1, :chunkHeight] return areaBlocks def getFacingBlockIndices(self, areaBlocks, areaBlockMats): @@ -574,18 +555,18 @@ def getFacingBlockIndices(self, areaBlocks, areaBlockMats): exposedFacesX = (areaBlockMats[:-1, 1:-1, 1:-1] != areaBlockMats[1:, 1:-1, 1:-1]) - facingBlockIndices[FaceXDecreasing] = exposedFacesX[:-1] - facingBlockIndices[FaceXIncreasing] = exposedFacesX[1:] + facingBlockIndices[pymclevel.faces.FaceXDecreasing] = exposedFacesX[:-1] + facingBlockIndices[pymclevel.faces.FaceXIncreasing] = exposedFacesX[1:] exposedFacesZ = (areaBlockMats[1:-1, :-1, 1:-1] != areaBlockMats[1:-1, 1:, 1:-1]) - facingBlockIndices[FaceZDecreasing] = exposedFacesZ[:, :-1] - facingBlockIndices[FaceZIncreasing] = exposedFacesZ[:, 1:] + facingBlockIndices[pymclevel.faces.FaceZDecreasing] = exposedFacesZ[:, :-1] + facingBlockIndices[pymclevel.faces.FaceZIncreasing] = exposedFacesZ[:, 1:] exposedFacesY = (areaBlockMats[1:-1, 1:-1, :-1] != areaBlockMats[1:-1, 1:-1, 1:]) - facingBlockIndices[FaceYDecreasing] = exposedFacesY[:, :, :-1] - facingBlockIndices[FaceYIncreasing] = exposedFacesY[:, :, 1:] + facingBlockIndices[pymclevel.faces.FaceYDecreasing] = exposedFacesY[:, :, :-1] + facingBlockIndices[pymclevel.faces.FaceYIncreasing] = exposedFacesY[:, :, 1:] return facingBlockIndices def getAreaBlockLights(self, chunk, neighboringChunks): @@ -597,36 +578,36 @@ def getAreaBlockLights(self, chunk, neighboringChunks): if lights != None: finalLight = lights if skyLight != None: - finalLight = maximum(skyLight, lights) + finalLight = numpy.maximum(skyLight, lights) - areaBlockLights = ones((chunkWidth + 2, chunkLength + 2, chunkHeight + 2), uint8) + areaBlockLights = numpy.ones((chunkWidth + 2, chunkLength + 2, chunkHeight + 2), numpy.uint8) areaBlockLights[:] = 15 areaBlockLights[1:-1, 1:-1, 1:-1] = finalLight - nc = neighboringChunks[FaceXDecreasing] - maximum(nc.SkyLight[-1:, :chunkLength, :chunkHeight], + nc = neighboringChunks[pymclevel.faces.FaceXDecreasing] + numpy.maximum(nc.SkyLight[-1:, :chunkLength, :chunkHeight], nc.BlockLight[-1:, :chunkLength, :chunkHeight], areaBlockLights[0:1, 1:-1, 1:-1]) - nc = neighboringChunks[FaceXIncreasing] - maximum(nc.SkyLight[:1, :chunkLength, :chunkHeight], + nc = neighboringChunks[pymclevel.faces.FaceXIncreasing] + numpy.maximum(nc.SkyLight[:1, :chunkLength, :chunkHeight], nc.BlockLight[:1, :chunkLength, :chunkHeight], areaBlockLights[-1:, 1:-1, 1:-1]) - nc = neighboringChunks[FaceZDecreasing] - maximum(nc.SkyLight[:chunkWidth, -1:, :chunkHeight], + nc = neighboringChunks[pymclevel.faces.FaceZDecreasing] + numpy.maximum(nc.SkyLight[:chunkWidth, -1:, :chunkHeight], nc.BlockLight[:chunkWidth, -1:, :chunkHeight], areaBlockLights[1:-1, 0:1, 1:-1]) - nc = neighboringChunks[FaceZIncreasing] - maximum(nc.SkyLight[:chunkWidth, :1, :chunkHeight], + nc = neighboringChunks[pymclevel.faces.FaceZIncreasing] + numpy.maximum(nc.SkyLight[:chunkWidth, :1, :chunkHeight], nc.BlockLight[:chunkWidth, :1, :chunkHeight], areaBlockLights[1:-1, -1:, 1:-1]) minimumLight = 4 # areaBlockLights[areaBlockLights 0 - flatcolors[overmask] = level.materials.flatColors[:, 0][overblocks[overmask]][:, newaxis] + flatcolors[overmask] = level.materials.flatColors[:, 0][overblocks[overmask]][:, numpy.newaxis] if self.detailLevel == 2: heightfactor = (y / float(2.0 * ch.world.Height)) + 0.5 - flatcolors[..., :3] *= heightfactor[:, newaxis, newaxis] + flatcolors[..., :3] *= heightfactor[:, numpy.newaxis, numpy.newaxis] - _RGBA = s_[..., 12:16] + _RGBA = numpy.s_[..., 12:16] va0.view('uint8')[_RGBA] = flatcolors va0[_XYZ][:, :, 0] *= step @@ -1125,10 +1106,10 @@ def makeChunkVertices(self, ch): self.vertexArrays = [va0] return - va1 = array(vertexArray) - va1[..., :3] += faceVertexTemplates[FaceXIncreasing, ..., :3] + va1 = numpy.array(vertexArray) + va1[..., :3] += faceVertexTemplates[pymclevel.faces.FaceXIncreasing, ..., :3] - va1[_XYZ][:, (0, 1), 1] = depths[nonAirBlocks].ravel()[:, newaxis] # stretch to floor + va1[_XYZ][:, (0, 1), 1] = depths[nonAirBlocks].ravel()[:, numpy.newaxis] # stretch to floor va1[_XYZ][:, (1, 2), 0] -= 1.0 # turn diagonally va1[_XYZ][:, (2, 3), 1] -= 0.5 # drop down to prevent intersection pixels @@ -1140,9 +1121,9 @@ def makeChunkVertices(self, ch): va1.view('uint8')[_RGBA] = flatcolors grassmask = topBlocks[nonAirBlocks] == 2 # color grass sides with dirt's color - va1.view('uint8')[_RGBA][grassmask] = level.materials.flatColors[:, 0][[3]][:, newaxis] + va1.view('uint8')[_RGBA][grassmask] = level.materials.flatColors[:, 0][[3]][:, numpy.newaxis] - va2 = array(va1) + va2 = numpy.array(va1) va2[_XYZ][:, (1, 2), 0] += step va2[_XYZ][:, (0, 3), 0] -= step @@ -1177,28 +1158,28 @@ def makeGenericVertices(self, facingBlockIndices, blocks, blockMaterials, blockD continue def setTexture(): - vertexArray[_ST] += texMap(theseBlocks, bdata, direction)[:, newaxis, 0:2] + vertexArray[_ST] += texMap(theseBlocks, bdata, direction)[:, numpy.newaxis, 0:2] setTexture() def setGrassColors(): - grass = theseBlocks == alphaMaterials.Grass.ID + grass = theseBlocks == pymclevel.materials.alphaMaterials.Grass.ID vertexArray.view('uint8')[_RGB][grass] *= self.grassColor def getBlockLight(): return facingBlockLight[blockIndices] def setColors(): - vertexArray.view('uint8')[_RGB] *= getBlockLight()[..., newaxis, newaxis] + vertexArray.view('uint8')[_RGB] *= getBlockLight()[..., numpy.newaxis, numpy.newaxis] if self.materials.name in ("Alpha", "Pocket"): - if direction == FaceYIncreasing: + if direction == pymclevel.faces.FaceYIncreasing: setGrassColors() - # leaves = theseBlocks == alphaMaterials.Leaves.ID + # leaves = theseBlocks == pymclevel.materials.alphaMaterials.Leaves.ID # vertexArray.view('uint8')[_RGBA][leaves] *= [0.15, 0.88, 0.15, 1.0] -# snow = theseBlocks == alphaMaterials.SnowLayer.ID -# if direction == FaceYIncreasing: +# snow = theseBlocks == pymclevel.materials.alphaMaterials.SnowLayer.ID +# if direction == pymclevel.faces.FaceYIncreasing: # vertexArray[_XYZ][snow, ...,1] -= 0.875 # -# if direction != FaceYIncreasing and direction != FaceYDecreasing: +# if direction != pymclevel.faces.FaceYIncreasing and direction != pymclevel.faces.FaceYDecreasing: # vertexArray[_XYZ][snow, ...,2:4,1] -= 0.875 # vertexArray[_ST][snow, ...,2:4,1] += 14 # @@ -1235,8 +1216,8 @@ def makeLeafVertices(self, facingBlockIndices, blocks, blockMaterials, blockData data = blockData[blockIndices] data &= 0x3 # ignore decay states leaves = (data == 0) | (data == 3) - pines = (data == alphaMaterials.PineLeaves.blockData) - birches = (data == alphaMaterials.BirchLeaves.blockData) + pines = (data == pymclevel.materials.alphaMaterials.PineLeaves.blockData) + birches = (data == pymclevel.materials.alphaMaterials.BirchLeaves.blockData) texes = texMap(18, data, 0) else: blockIndices = materialIndices @@ -1249,8 +1230,8 @@ def makeLeafVertices(self, facingBlockIndices, blocks, blockMaterials, blockData data = blockData[blockIndices] data &= 0x3 # ignore decay states leaves = (data == 0) - pines = (data == alphaMaterials.PineLeaves.blockData) - birches = (data == alphaMaterials.BirchLeaves.blockData) + pines = (data == pymclevel.materials.alphaMaterials.PineLeaves.blockData) + birches = (data == pymclevel.materials.alphaMaterials.BirchLeaves.blockData) type3 = (data == 3) leaves |= type3 @@ -1261,12 +1242,12 @@ def makeLeafVertices(self, facingBlockIndices, blocks, blockMaterials, blockData if not len(vertexArray): continue - vertexArray[_ST] += texes[:, newaxis] + vertexArray[_ST] += texes[:, numpy.newaxis] if not self.chunkCalculator.fastLeaves: vertexArray[_ST] -= (0x10, 0x0) - vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., newaxis, newaxis] + vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] if self.materials.name in ("Alpha", "Pocket"): vertexArray.view('uint8')[_RGB][leaves] *= self.leafColor vertexArray.view('uint8')[_RGB][pines] *= self.pineLeafColor @@ -1308,27 +1289,27 @@ def makePlantVertices(self, facingBlockIndices, blocks, blockMaterials, blockDat texes = texMap(blocks[blockIndices], bdata, 0) blockLight = areaBlockLights[1:-1, 1:-1, 1:-1] - lights = blockLight[blockIndices][..., newaxis, newaxis] + lights = blockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] colorize = None if self.materials.name == "Alpha": - colorize = (theseBlocks == alphaMaterials.TallGrass.ID) & (bdata != 0) + colorize = (theseBlocks == pymclevel.materials.alphaMaterials.TallGrass.ID) & (bdata != 0) - for direction in (FaceXIncreasing, FaceXDecreasing, FaceZIncreasing, FaceZDecreasing): + for direction in (pymclevel.faces.FaceXIncreasing, pymclevel.faces.FaceXDecreasing, pymclevel.faces.FaceZIncreasing, pymclevel.faces.FaceZDecreasing): vertexArray = self.makeTemplate(direction, blockIndices) if not len(vertexArray): return - if direction == FaceXIncreasing: + if direction == pymclevel.faces.FaceXIncreasing: vertexArray[_XYZ][..., 1:3, 0] -= 1 - if direction == FaceXDecreasing: + if direction == pymclevel.faces.FaceXDecreasing: vertexArray[_XYZ][..., 1:3, 0] += 1 - if direction == FaceZIncreasing: + if direction == pymclevel.faces.FaceZIncreasing: vertexArray[_XYZ][..., 1:3, 2] -= 1 - if direction == FaceZDecreasing: + if direction == pymclevel.faces.FaceZDecreasing: vertexArray[_XYZ][..., 1:3, 2] += 1 - vertexArray[_ST] += texes[:, newaxis, 0:2] + vertexArray[_ST] += texes[:, numpy.newaxis, 0:2] vertexArray.view('uint8')[_RGBA] = 0xf # ignore precomputed directional light vertexArray.view('uint8')[_RGB] *= lights @@ -1438,7 +1419,7 @@ class TorchBlockRenderer(BlockRenderer): torchOffsetsStraight, ] + [torchOffsetsStraight] * 10 - torchOffsets = array(torchOffsets, dtype='float32') + torchOffsets = numpy.array(torchOffsets, dtype='float32') torchOffsets[1][..., 3, :, 0] -= 0.5 @@ -1486,11 +1467,11 @@ def makeTorchVertices(self, facingBlockIndices, blocks, blockMaterials, blockDat vertexArray.view('uint8')[_RGBA] = 0xff vertexArray[_XYZ] += torchOffsets[:, direction] - if direction == FaceYIncreasing: + if direction == pymclevel.faces.FaceYIncreasing: vertexArray[_ST] = self.upCoords - if direction == FaceYDecreasing: + if direction == pymclevel.faces.FaceYDecreasing: vertexArray[_ST] = self.downCoords - vertexArray[_ST] += texes[:, newaxis, direction] + vertexArray[_ST] += texes[:, numpy.newaxis, direction] arrays.append(vertexArray) yield self.vertexArrays = arrays @@ -1499,10 +1480,10 @@ def makeTorchVertices(self, facingBlockIndices, blocks, blockMaterials, blockDat class RailBlockRenderer(BlockRenderer): - blocktypes = [alphaMaterials.Rail.ID, alphaMaterials.PoweredRail.ID, alphaMaterials.DetectorRail.ID] + blocktypes = [pymclevel.materials.alphaMaterials.Rail.ID, pymclevel.materials.alphaMaterials.PoweredRail.ID, pymclevel.materials.alphaMaterials.DetectorRail.ID] renderstate = ChunkCalculator.renderstateAlphaTest - railTextures = array([ + railTextures = numpy.array([ [(0, 128), (0, 144), (16, 144), (16, 128)], # east-west [(0, 128), (16, 128), (16, 144), (0, 144)], # north-south [(0, 128), (16, 128), (16, 144), (0, 144)], # south-ascending @@ -1523,9 +1504,9 @@ class RailBlockRenderer(BlockRenderer): [(0, 192), (0, 208), (16, 208), (16, 192)], # unknown ], dtype='float32') - railTextures -= alphaMaterials.blockTextures[alphaMaterials.Rail.ID, 0, 0] + railTextures -= pymclevel.materials.alphaMaterials.blockTextures[pymclevel.materials.alphaMaterials.Rail.ID, 0, 0] - railOffsets = array([ + railOffsets = numpy.array([ [0, 0, 0, 0], [0, 0, 0, 0], @@ -1549,16 +1530,16 @@ class RailBlockRenderer(BlockRenderer): ], dtype='float32') def makeRailVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, areaBlockLights, texMap): - direction = FaceYIncreasing + direction = pymclevel.faces.FaceYIncreasing blockIndices = self.getMaterialIndices(blockMaterials) yield bdata = blockData[blockIndices] railBlocks = blocks[blockIndices] - tex = texMap(railBlocks, bdata, FaceYIncreasing)[:, newaxis, :] + tex = texMap(railBlocks, bdata, pymclevel.faces.FaceYIncreasing)[:, numpy.newaxis, :] # disable 'powered' or 'pressed' bit for powered and detector rails - bdata[railBlocks != alphaMaterials.Rail.ID] &= ~0x8 + bdata[railBlocks != pymclevel.materials.alphaMaterials.Rail.ID] &= ~0x8 vertexArray = self.makeTemplate(direction, blockIndices) if not len(vertexArray): @@ -1572,7 +1553,7 @@ def makeRailVertices(self, facingBlockIndices, blocks, blockMaterials, blockData blockLight = areaBlockLights[1:-1, 1:-1, 1:-1] - vertexArray.view('uint8')[_RGB] *= blockLight[blockIndices][..., newaxis, newaxis] + vertexArray.view('uint8')[_RGB] *= blockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] yield self.vertexArrays = [vertexArray] @@ -1580,9 +1561,9 @@ def makeRailVertices(self, facingBlockIndices, blocks, blockMaterials, blockData class LadderBlockRenderer(BlockRenderer): - blocktypes = [alphaMaterials.Ladder.ID] + blocktypes = [pymclevel.materials.alphaMaterials.Ladder.ID] - ladderOffsets = array([ + ladderOffsets = numpy.array([ [(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], [(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], @@ -1593,7 +1574,7 @@ class LadderBlockRenderer(BlockRenderer): ] + [[(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)]] * 10, dtype='float32') - ladderTextures = array([ + ladderTextures = numpy.array([ [(0, 192), (0, 208), (16, 208), (16, 192)], # unknown [(0, 192), (0, 208), (16, 208), (16, 192)], # unknown @@ -1610,13 +1591,13 @@ def ladderVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, yield bdata = blockData[blockIndices] - vertexArray = self.makeTemplate(FaceYIncreasing, blockIndices) + vertexArray = self.makeTemplate(pymclevel.faces.FaceYIncreasing, blockIndices) if not len(vertexArray): return vertexArray[_ST] = self.ladderTextures[bdata] vertexArray[_XYZ] += self.ladderOffsets[bdata] - vertexArray.view('uint8')[_RGB] *= blockLight[blockIndices][..., newaxis, newaxis] + vertexArray.view('uint8')[_RGB] *= blockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] yield self.vertexArrays = [vertexArray] @@ -1637,25 +1618,25 @@ def makeSnowVertices(self, facingBlockIndices, blocks, blockMaterials, blockData # def makeFaceVertices(self, direction, blockIndices, exposedFaceIndices, blocks, blockData, blockLight, facingBlockLight, texMap): # return [] - if direction != FaceYIncreasing: + if direction != pymclevel.faces.FaceYIncreasing: blockIndices = snowIndices & exposedFaceIndices else: blockIndices = snowIndices facingBlockLight = areaBlockLights[self.directionOffsets[direction]] - lights = facingBlockLight[blockIndices][..., newaxis, newaxis] + lights = facingBlockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] vertexArray = self.makeTemplate(direction, blockIndices) if not len(vertexArray): continue - vertexArray[_ST] += texMap([self.snowID], 0, 0)[:, newaxis, 0:2] + vertexArray[_ST] += texMap([self.snowID], 0, 0)[:, numpy.newaxis, 0:2] vertexArray.view('uint8')[_RGB] *= lights - if direction == FaceYIncreasing: + if direction == pymclevel.faces.FaceYIncreasing: vertexArray[_XYZ][..., 1] -= 0.875 - if direction != FaceYIncreasing and direction != FaceYDecreasing: + if direction != pymclevel.faces.FaceYIncreasing and direction != pymclevel.faces.FaceYDecreasing: vertexArray[_XYZ][..., 2:4, 1] -= 0.875 vertexArray[_ST][..., 2:4, 1] += 14 @@ -1672,11 +1653,11 @@ class RedstoneBlockRenderer(BlockRenderer): def redstoneVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, areaBlockLights, texMap): blockIndices = self.getMaterialIndices(blockMaterials) yield - vertexArray = self.makeTemplate(FaceYIncreasing, blockIndices) + vertexArray = self.makeTemplate(pymclevel.faces.FaceYIncreasing, blockIndices) if not len(vertexArray): return - vertexArray[_ST] += alphaMaterials.blockTextures[55, 0, 0] + vertexArray[_ST] += pymclevel.materials.alphaMaterials.blockTextures[55, 0, 0] vertexArray[_XYZ][..., 1] -= 0.9 bdata = blockData[blockIndices] @@ -1685,7 +1666,7 @@ def redstoneVertices(self, facingBlockIndices, blocks, blockMaterials, blockData # bdata &= 0xe0 bdata[bdata > 0] |= 0x80 - vertexArray.view('uint8')[_RGBA][..., 0] = bdata[..., newaxis] + vertexArray.view('uint8')[_RGBA][..., 0] = bdata[..., numpy.newaxis] vertexArray.view('uint8')[_RGBA][..., 0:3] *= [1, 0, 0] yield @@ -1697,14 +1678,14 @@ def redstoneVertices(self, facingBlockIndices, blocks, blockMaterials, blockData class FeatureBlockRenderer(BlockRenderer): -# blocktypes = [alphaMaterials.Button.ID, -# alphaMaterials.StoneFloorPlate.ID, -# alphaMaterials.WoodFloorPlate.ID, -# alphaMaterials.WoodenDoor.ID, -# alphaMaterials.IronDoor.ID, +# blocktypes = [pymclevel.materials.alphaMaterials.Button.ID, +# pymclevel.materials.alphaMaterials.StoneFloorPlate.ID, +# pymclevel.materials.alphaMaterials.WoodFloorPlate.ID, +# pymclevel.materials.alphaMaterials.WoodenDoor.ID, +# pymclevel.materials.alphaMaterials.IronDoor.ID, # ] # - blocktypes = [alphaMaterials.Fence.ID] + blocktypes = [pymclevel.materials.alphaMaterials.Fence.ID] buttonOffsets = [ [[-14 / 16., 6 / 16., -5 / 16.], @@ -1740,23 +1721,23 @@ class FeatureBlockRenderer(BlockRenderer): [-14 / 16., -7 / 16., 5 / 16.], ], ] - buttonOffsets = array(buttonOffsets) + buttonOffsets = numpy.array(buttonOffsets) buttonOffsets[buttonOffsets < 0] += 1.0 dirIndexes = ((3, 2), (-3, 2), (1, 3), (1, 3), (-1, 2), (1, 2)) def buttonVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, areaBlockLights, texMap): - blockIndices = blocks == alphaMaterials.Button.ID + blockIndices = blocks == pymclevel.materials.alphaMaterials.Button.ID axes = blockIndices.nonzero() - vertexArray = zeros((len(axes[0]), 6, 4, 6), dtype=float32) - vertexArray[_XYZ][..., 0] = axes[0][..., newaxis, newaxis] - vertexArray[_XYZ][..., 1] = axes[2][..., newaxis, newaxis] - vertexArray[_XYZ][..., 2] = axes[1][..., newaxis, newaxis] + vertexArray = numpy.zeros((len(axes[0]), 6, 4, 6), dtype=numpy.float32) + vertexArray[_XYZ][..., 0] = axes[0][..., numpy.newaxis, numpy.newaxis] + vertexArray[_XYZ][..., 1] = axes[2][..., numpy.newaxis, numpy.newaxis] + vertexArray[_XYZ][..., 2] = axes[1][..., numpy.newaxis, numpy.newaxis] vertexArray[_XYZ] += self.buttonOffsets vertexArray[_ST] = [[0, 0], [0, 16], [16, 16], [16, 0]] - vertexArray[_ST] += texMap(alphaMaterials.Stone.ID, 0)[newaxis, :, newaxis] + vertexArray[_ST] += texMap(pymclevel.materials.alphaMaterials.Stone.ID, 0)[numpy.newaxis, :, numpy.newaxis] # if direction == 0: # for i, j in enumerate(self.dirIndexes[direction]): @@ -1784,22 +1765,22 @@ def buttonVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, fenceTemplates = makeVertexTemplates(3 / 8., 0, 3 / 8., 5 / 8., 1, 5 / 8.) def fenceVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, areaBlockLights, texMap): - fenceMask = blocks == alphaMaterials.Fence.ID + fenceMask = blocks == pymclevel.materials.alphaMaterials.Fence.ID fenceIndices = fenceMask.nonzero() yield - vertexArray = zeros((len(fenceIndices[0]), 6, 4, 6), dtype='float32') + vertexArray = numpy.zeros((len(fenceIndices[0]), 6, 4, 6), dtype='float32') for i in range(3): j = (0, 2, 1)[i] - vertexArray[..., i] = fenceIndices[j][:, newaxis, newaxis] # xxx swap z with y using ^ + vertexArray[..., i] = fenceIndices[j][:, numpy.newaxis, numpy.newaxis] # xxx swap z with y using ^ vertexArray[..., 0:5] += self.fenceTemplates[..., 0:5] - vertexArray[_ST] += alphaMaterials.blockTextures[alphaMaterials.WoodPlanks.ID, 0, 0] + vertexArray[_ST] += pymclevel.materials.alphaMaterials.blockTextures[pymclevel.materials.alphaMaterials.WoodPlanks.ID, 0, 0] - vertexArray.view('uint8')[_RGBA] = self.fenceTemplates[..., 5][..., newaxis] + vertexArray.view('uint8')[_RGBA] = self.fenceTemplates[..., 5][..., numpy.newaxis] - vertexArray.view('uint8')[_RGB] *= areaBlockLights[1:-1, 1:-1, 1:-1][fenceIndices][..., newaxis, newaxis, newaxis] + vertexArray.view('uint8')[_RGB] *= areaBlockLights[1:-1, 1:-1, 1:-1][fenceIndices][..., numpy.newaxis, numpy.newaxis, numpy.newaxis] vertexArray.shape = (vertexArray.shape[0] * 6, 4, 6) yield self.vertexArrays = [vertexArray] @@ -1816,7 +1797,7 @@ def getBlocktypes(cls, mats): # North - FaceXDecreasing # West - FaceZIncreasing # East - FaceZDecreasing - stairTemplates = array([makeVertexTemplates(**kw) for kw in [ + stairTemplates = numpy.array([makeVertexTemplates(**kw) for kw in [ # South - FaceXIncreasing {"xmin":0.5}, # North - FaceXDecreasing @@ -1841,9 +1822,9 @@ def stairVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, a x, z, y = materialIndices.nonzero() for _ in ("slab", "step"): - vertexArray = zeros((len(x), 6, 4, 6), dtype='float32') + vertexArray = numpy.zeros((len(x), 6, 4, 6), dtype='float32') for i in range(3): - vertexArray[_XYZ][..., i] = (x, y, z)[i][:, newaxis, newaxis] + vertexArray[_XYZ][..., i] = (x, y, z)[i][:, numpy.newaxis, numpy.newaxis] if _ == "step": vertexArray[_XYZST] += self.stairTemplates[4][..., :5] @@ -1851,9 +1832,9 @@ def stairVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, a else: vertexArray[_XYZST] += self.stairTemplates[stairData][..., :5] - vertexArray[_ST] += texMap(stairBlocks, 0)[..., newaxis, :] + vertexArray[_ST] += texMap(stairBlocks, 0)[..., numpy.newaxis, :] - vertexArray.view('uint8')[_RGB] = self.stairTemplates[4][newaxis, ..., 5, newaxis] + vertexArray.view('uint8')[_RGB] = self.stairTemplates[4][numpy.newaxis, ..., 5, numpy.newaxis] vertexArray.view('uint8')[_RGB] *= 0xf vertexArray.view('uint8')[_A] = 0xff @@ -1870,23 +1851,23 @@ class SlabBlockRenderer(BlockRenderer): blocktypes = [slabID] def slabFaceVertices(self, direction, blockIndices, exposedFaceIndices, blocks, blockData, blockLight, facingBlockLight, texMap): - if direction != FaceYIncreasing: + if direction != pymclevel.faces.FaceYIncreasing: blockIndices = blockIndices & exposedFaceIndices - lights = facingBlockLight[blockIndices][..., newaxis, newaxis] + lights = facingBlockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] bdata = blockData[blockIndices] vertexArray = self.makeTemplate(direction, blockIndices) if not len(vertexArray): return vertexArray - vertexArray[_ST] += texMap(self.slabID, bdata, direction)[:, newaxis, 0:2] + vertexArray[_ST] += texMap(self.slabID, bdata, direction)[:, numpy.newaxis, 0:2] vertexArray.view('uint8')[_RGB] *= lights - if direction == FaceYIncreasing: + if direction == pymclevel.faces.FaceYIncreasing: vertexArray[_XYZ][..., 1] -= 0.5 - if direction != FaceYIncreasing and direction != FaceYDecreasing: + if direction != pymclevel.faces.FaceYIncreasing and direction != pymclevel.faces.FaceYDecreasing: vertexArray[_XYZ][..., 2:4, 1] -= 0.5 vertexArray[_ST][..., 2:4, 1] += 8 @@ -1903,8 +1884,8 @@ class WaterBlockRenderer(BlockRenderer): def waterFaceVertices(self, direction, blockIndices, exposedFaceIndices, blocks, blockData, blockLight, facingBlockLight, texMap): blockIndices = blockIndices & exposedFaceIndices vertexArray = self.makeTemplate(direction, blockIndices) - vertexArray[_ST] += texMap(self.waterID, 0, 0)[newaxis, newaxis] - vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., newaxis, newaxis] + vertexArray[_ST] += texMap(self.waterID, 0, 0)[numpy.newaxis, numpy.newaxis] + vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] return vertexArray makeFaceVertices = waterFaceVertices @@ -1918,8 +1899,8 @@ class IceBlockRenderer(BlockRenderer): def iceFaceVertices(self, direction, blockIndices, exposedFaceIndices, blocks, blockData, blockLight, facingBlockLight, texMap): blockIndices = blockIndices & exposedFaceIndices vertexArray = self.makeTemplate(direction, blockIndices) - vertexArray[_ST] += texMap(self.iceID, 0, 0)[newaxis, newaxis] - vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., newaxis, newaxis] + vertexArray[_ST] += texMap(self.iceID, 0, 0)[numpy.newaxis, numpy.newaxis] + vertexArray.view('uint8')[_RGB] *= facingBlockLight[blockIndices][..., numpy.newaxis, numpy.newaxis] return vertexArray makeFaceVertices = iceFaceVertices @@ -2034,8 +2015,8 @@ def chunkDistance(self, cpos): camx -= ox camz -= oz - camcx = int(floor(camx)) >> 4 - camcz = int(floor(camz)) >> 4 + camcx = int(numpy.floor(camx)) >> 4 + camcz = int(numpy.floor(camz)) >> 4 cx, cz = cpos @@ -2193,8 +2174,8 @@ def discardChunksOutsideViewDistance(self): return (ox, oz) = origin bytes = 0 - # chunks = fromiter(self.chunkRenderers.iterkeys(), dtype='int32', count=len(self.chunkRenderers)) - chunks = fromiter(self.chunkRenderers.iterkeys(), dtype='i,i', count=len(self.chunkRenderers)) + # chunks = numpy.fromiter(self.chunkRenderers.iterkeys(), dtype='int32', count=len(self.chunkRenderers)) + chunks = numpy.fromiter(self.chunkRenderers.iterkeys(), dtype='i,i', count=len(self.chunkRenderers)) chunks.dtype = 'int32' chunks.shape = len(self.chunkRenderers), 2 @@ -2272,7 +2253,7 @@ def invalidateChunk(self, cx, cz, layers=None): self.invalidChunkQueue.append((cx, cz)) # xxx encapsulate def invalidateChunksInBox(self, box, layers=None): - box = BoundingBox(box) + box = pymclevel.BoundingBox(box) if box.minx & 0xf == 0: box.minx -= 1 if box.miny & 0xf == 0: @@ -2379,12 +2360,12 @@ def makeFloorTex(self): color0 = (0xff, 0xff, 0xff, 0x22) color1 = (0xff, 0xff, 0xff, 0x44) - img = array([color0, color1, color1, color0], dtype='uint8') + img = numpy.array([color0, color1, color1, color0], dtype='uint8') - GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) - GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) + OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, OpenGL.GL.GL_TEXTURE_MIN_FILTER, OpenGL.GL.GL_NEAREST) + OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, OpenGL.GL.GL_TEXTURE_MAG_FILTER, OpenGL.GL.GL_NEAREST) - GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, 2, 2, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, img) + OpenGL.GL.glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, 0, OpenGL.GL.GL_RGBA, 2, 2, 0, OpenGL.GL.GL_RGBA, OpenGL.GL.GL_UNSIGNED_BYTE, img) def invalidateChunkMarkers(self): self.loadableChunkMarkers.invalidate() @@ -2395,54 +2376,54 @@ def _drawLoadableChunkMarkers(self): sizedChunks = chunkMarkers(chunkSet) - glPushAttrib(GL_FOG_BIT) - glDisable(GL_FOG) + OpenGL.GL.glPushAttrib(OpenGL.GL.GL_FOG_BIT) + OpenGL.GL.glDisable(OpenGL.GL.GL_FOG) - glEnable(GL_BLEND) - glEnable(GL_POLYGON_OFFSET_FILL) - glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) - glEnable(GL_DEPTH_TEST) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) - glEnableClientState(GL_TEXTURE_COORD_ARRAY) - glEnable(GL_TEXTURE_2D) - glColor(1.0, 1.0, 1.0, 1.0) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glColor(1.0, 1.0, 1.0, 1.0) self.floorTexture.bind() - # chunkColor = zeros(shape=(chunks.shape[0], 4, 4), dtype='float32') + # chunkColor = numpy.zeros(shape=(chunks.shape[0], 4, 4), dtype='float32') # chunkColor[:]= (1, 1, 1, 0.15) # -# cc = array(chunks[:,0] + chunks[:,1], dtype='int32') +# cc = numpy.array(chunks[:,0] + chunks[:,1], dtype='int32') # cc &= 1 # coloredChunks = cc > 0 # chunkColor[coloredChunks] = (1, 1, 1, 0.28) # chunkColor *= 255 -# chunkColor = array(chunkColor, dtype='uint8') +# chunkColor = numpy.array(chunkColor, dtype='uint8') # - # glColorPointer(4, GL_UNSIGNED_BYTE, 0, chunkColor) + # OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, chunkColor) for size, chunks in sizedChunks.iteritems(): if not len(chunks): continue - chunks = array(chunks, dtype='float32') + chunks = numpy.array(chunks, dtype='float32') - chunkPosition = zeros(shape=(chunks.shape[0], 4, 3), dtype='float32') - chunkPosition[:, :, (0, 2)] = array(((0, 0), (0, 1), (1, 1), (1, 0)), dtype='float32') + chunkPosition = numpy.zeros(shape=(chunks.shape[0], 4, 3), dtype='float32') + chunkPosition[:, :, (0, 2)] = numpy.array(((0, 0), (0, 1), (1, 1), (1, 0)), dtype='float32') chunkPosition[:, :, (0, 2)] *= size - chunkPosition[:, :, (0, 2)] += chunks[:, newaxis, :] + chunkPosition[:, :, (0, 2)] += chunks[:, numpy.newaxis, :] chunkPosition *= 16 - glVertexPointer(3, GL_FLOAT, 0, chunkPosition.ravel()) + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, chunkPosition.ravel()) # chunkPosition *= 8 - glTexCoordPointer(2, GL_FLOAT, 0, (chunkPosition[..., (0, 2)] * 8).ravel()) - glDrawArrays(GL_QUADS, 0, len(chunkPosition) * 4) + OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, (chunkPosition[..., (0, 2)] * 8).ravel()) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(chunkPosition) * 4) - glDisableClientState(GL_TEXTURE_COORD_ARRAY) - glDisable(GL_TEXTURE_2D) - glDisable(GL_BLEND) - glDisable(GL_DEPTH_TEST) - glDisable(GL_POLYGON_OFFSET_FILL) - glPopAttrib() + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glPopAttrib() def drawLoadableChunkMarkers(self): - if not self.isPreviewer or isinstance(self.level, MCInfdevOldLevel): + if not self.isPreviewer or isinstance(self.level, pymclevel.MCInfdevOldLevel): self.loadableChunkMarkers.call(self._drawLoadableChunkMarkers) # self.drawCompressedChunkMarkers() @@ -2452,53 +2433,53 @@ def drawCompressedChunkMarkers(self): if 0 == len(chunkPositions): return - chunkPositions = array(chunkPositions) + chunkPositions = numpy.array(chunkPositions) chunkLoaded = [self.level.chunkIsLoaded(*c) for c in chunkPositions] - chunkLoaded = array(chunkLoaded, dtype='bool') + chunkLoaded = numpy.array(chunkLoaded, dtype='bool') chunkCompressed = [self.level.chunkIsCompressed(*c) for c in chunkPositions] - chunkCompressed = array(chunkCompressed, dtype='bool') + chunkCompressed = numpy.array(chunkCompressed, dtype='bool') chunkDirty = [self.level.chunkIsDirty(*c) for c in chunkPositions] - chunkDirty = array(chunkDirty, dtype='bool') + chunkDirty = numpy.array(chunkDirty, dtype='bool') - vertexBuffer = zeros((len(chunkPositions), 4, 3), dtype='float32') + vertexBuffer = numpy.zeros((len(chunkPositions), 4, 3), dtype='float32') - vertexBuffer[..., (0, 2)] = array(((0, 0), (0, 1), (1, 1), (1, 0)), dtype='float32') + vertexBuffer[..., (0, 2)] = numpy.array(((0, 0), (0, 1), (1, 1), (1, 0)), dtype='float32') - vertexBuffer[..., (0, 2)] += chunkPositions[:, newaxis] + vertexBuffer[..., (0, 2)] += chunkPositions[:, numpy.newaxis] vertexBuffer[..., (0, 2)] *= 16 vertexBuffer[..., 1] = 128 - colorBuffer = zeros((len(chunkCompressed), 4, 4), dtype='uint8') + colorBuffer = numpy.zeros((len(chunkCompressed), 4, 4), dtype='uint8') colorBuffer[:] = (0x00, 0x00, 0x00, 0x33) colorBuffer[chunkLoaded] = (0xff, 0xff, 0xff, 0x66) colorBuffer[chunkCompressed] = (0xff, 0xFF, 0x00, 0x66) colorBuffer[chunkDirty] = (0xff, 0x00, 0x00, 0x66) - cc = array(chunkPositions[:, 0] + chunkPositions[:, 1], dtype='int32') + cc = numpy.array(chunkPositions[:, 0] + chunkPositions[:, 1], dtype='int32') cc &= 1 coloredChunks = cc > 0 colorBuffer[coloredChunks] *= 0.75 - glEnable(GL_BLEND) - glEnable(GL_POLYGON_OFFSET_FILL) - glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) - glEnable(GL_DEPTH_TEST) - glEnableClientState(GL_COLOR_ARRAY) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) - glVertexPointer(3, GL_FLOAT, 0, vertexBuffer) - glColorPointer(4, GL_UNSIGNED_BYTE, 0, colorBuffer) - glDrawArrays(GL_QUADS, 0, len(vertexBuffer) * 4) + OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, vertexBuffer) + OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, colorBuffer) + OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(vertexBuffer) * 4) - glDisableClientState(GL_COLOR_ARRAY) + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) - glDisable(GL_POLYGON_OFFSET_FILL) - glDisable(GL_DEPTH_TEST) + OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) - glDisable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) needsImmediateRedraw = False viewingFrustum = None @@ -2531,7 +2512,7 @@ def createMasterLists(self): for rs in chunkLists: if len(chunkLists[rs]): - lists[rs] = array(chunkLists[rs], dtype='uint32').ravel() + lists[rs] = numpy.array(chunkLists[rs], dtype='uint32').ravel() # lists = lists[lists.nonzero()] self.masterLists = lists @@ -2544,14 +2525,14 @@ def callMasterLists(self): continue if self.alpha != 0xff and renderstate is not ChunkCalculator.renderstateLowDetail: - glEnable(GL_BLEND) + OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) renderstate.bind() - glCallLists(self.masterLists[renderstate]) + OpenGL.GL.glCallLists(self.masterLists[renderstate]) renderstate.release() if self.alpha != 0xff and renderstate is not ChunkCalculator.renderstateLowDetail: - glDisable(GL_BLEND) + OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) errorLimit = 10 @@ -2566,38 +2547,38 @@ def draw(self): chunksDrawn = 0 - with gl.glPushMatrix(GL_MODELVIEW): + with gl.glPushMatrix(OpenGL.GL.GL_MODELVIEW): dx, dy, dz = self.origin - glTranslate(dx, dy, dz) + OpenGL.GL.glTranslate(dx, dy, dz) - glEnable(GL_CULL_FACE) - glEnable(GL_DEPTH_TEST) + OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) self.level.materials.terrainTexture.bind() - glEnable(GL_TEXTURE_2D) - glEnableClientState(GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) offset = DepthOffset.PreviewRenderer if self.isPreviewer else DepthOffset.Renderer - glPolygonOffset(offset, offset) - glEnable(GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glPolygonOffset(offset, offset) + OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) self.createMasterLists() try: self.callMasterLists() - except GLError, e: + except OpenGL.GL.GLError, e: if self.errorLimit: self.errorLimit -= 1 traceback.print_exc() print e - glDisable(GL_POLYGON_OFFSET_FILL) + OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) - glDisable(GL_CULL_FACE) - glDisable(GL_DEPTH_TEST) + OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) + OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) - glDisable(GL_TEXTURE_2D) - glDisableClientState(GL_TEXTURE_COORD_ARRAY) + OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) + OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) # if self.drawLighting: self.drawLoadableChunkMarkers() @@ -2698,7 +2679,7 @@ def workOnChunk(self, c): if self.level.containsChunk(*c): cr = self.getChunkRenderer(c) if self.viewingFrustum: - # if not self.viewingFrustum.visible(array([[c[0] * 16 + 8, 64, c[1] * 16 + 8, 1.0]]), 64).any(): + # if not self.viewingFrustum.visible(numpy.array([[c[0] * 16 + 8, 64, c[1] * 16 + 8, 1.0]]), 64).any(): if not self.viewingFrustum.visible1([c[0] * 16 + 8, self.level.Height / 2, c[1] * 16 + 8, 1.0], self.level.Height / 2): raise StopIteration yield @@ -2719,7 +2700,7 @@ def workOnChunk(self, c): except Exception: fn = c - info(u"Skipped chunk {f}: {e}".format(e=e, f=fn)) + logging.info(u"Skipped chunk {f}: {e}".format(e=e, f=fn)) redrawChunks = 0 @@ -2763,7 +2744,7 @@ class PreviewRenderer(MCRenderer): def rendermain(): renderer = MCRenderer() - renderer.level = mclevel.loadWorld("World1") + renderer.level = pymclevel.mclevel.loadWorld("World1") renderer.viewDistance = 6 renderer.detailLevelForChunk = lambda * x: 0 start = datetime.now() @@ -2786,33 +2767,33 @@ def rendermain(): # display.init( (640, 480), OPENGL | DOUBLEBUF ) from mcedit import GLDisplayContext - from OpenGL import GLU + #from OpenGL import GLU cxt = GLDisplayContext() import pygame # distance = 4000 - glMatrixMode(GL_PROJECTION) - glLoadIdentity() - GLU.gluPerspective(35, 640.0 / 480.0, 0.5, 4000.0) + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) + OpenGL.GL.glLoadIdentity() + OpenGL.GLU.gluPerspective(35, 640.0 / 480.0, 0.5, 4000.0) h = 366 pos = (0, h, 0) look = (0.0001, h - 1, 0.0001) up = (0, 1, 0) - GL.glMatrixMode(GL_MODELVIEW) - GL.glLoadIdentity() + OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) + OpenGL.GL.glLoadIdentity() - GLU.gluLookAt(pos[0], pos[1], pos[2], + OpenGL.GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) - glClearColor(0.0, 0.0, 0.0, 1.0) + OpenGL.GL.glClearColor(0.0, 0.0, 0.0, 1.0) framestart = datetime.now() frames = 200 for i in range(frames): - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) + OpenGL.GL.glClear(OpenGL.GL.GL_COLOR_BUFFER_BIT | OpenGL.GL.GL_DEPTH_BUFFER_BIT) renderer.draw() pygame.display.flip() @@ -2824,7 +2805,7 @@ def rendermain(): evt = pygame.event.poll() if evt.type == pygame.MOUSEBUTTONDOWN: break - # sleep(3.0) + # time.sleep(3.0) import traceback From 37ab31b777c3e1946b57e1fb363410f23b1e7bb9 Mon Sep 17 00:00:00 2001 From: David Sowder Date: Wed, 14 Mar 2012 19:41:38 -0500 Subject: [PATCH 6/8] Fix bad search/replace error for blockMaterials.clip() identified by codewarrior0 --- renderer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/renderer.py b/renderer.py index cf0ef82..3873c45 100644 --- a/renderer.py +++ b/renderer.py @@ -658,7 +658,7 @@ def computeGeometry(self, chunk, areaBlockMats, facingBlockIndices, areaBlockLig blockData = blockData & 0xf blockMaterials = areaBlockMats[1:-1, 1:-1, 1:-1] if self.roughGraphics: - blockMaterials.numpy.clip(0, 1, blockMaterials) + blockMaterials.clip(0, 1, blockMaterials) sx = sz = slice(0, 16) asx = asz = slice(0, 18) From b11bbee6df3872b7ee5bf50768688d7f01e08571 Mon Sep 17 00:00:00 2001 From: David Sowder Date: Fri, 16 Mar 2012 08:30:51 -0500 Subject: [PATCH 7/8] shuffle module import style for OpenGL to import the module instead of the package in a few files --- frustum.py | 12 +-- leveleditor.py | 257 +++++++++++++++++++++++++------------------------ renderer.py | 252 ++++++++++++++++++++++++------------------------ 3 files changed, 261 insertions(+), 260 deletions(-) diff --git a/frustum.py b/frustum.py index ef58b98..6298024 100644 --- a/frustum.py +++ b/frustum.py @@ -12,7 +12,7 @@ import logging import numpy -import OpenGL.GL +from OpenGL import GL context_log = logging.getLogger() @@ -31,9 +31,9 @@ def viewingMatrix(projection=None, model=None): matrix, the function will raise a RuntimeError """ if projection is None: - projection = OpenGL.GL.glGetDoublev(OpenGL.GL.GL_PROJECTION_MATRIX) + projection = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) if model is None: - model = OpenGL.GL.glGetDoublev(OpenGL.GL.GL_MODELVIEW_MATRIX) + model = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) # hmm, this will likely fail on 64-bit platforms :( if projection is None or model is None: context_log.warn( @@ -85,15 +85,15 @@ def visible(self, points, radius): frustcullaccel C extension module) """ - distances = sum(self.planes[OpenGL.GL.newaxis, :, :] * points[:, OpenGL.GL.newaxis, :], -1) + distances = sum(self.planes[GL.newaxis, :, :] * points[:, GL.newaxis, :], -1) return ~any(distances < -radius, -1) def visible1(self, point, radius): - #return self.visible(array(point[OpenGL.GL.newaxis, :]), radius) + #return self.visible(array(point[GL.newaxis, :]), radius) distance = sum(self.planes * point, -1) vis = ~any(distance < -radius) - #assert vis == self.visible(array(point)[OpenGL.GL.newaxis, :], radius) + #assert vis == self.visible(array(point)[GL.newaxis, :], radius) return vis diff --git a/leveleditor.py b/leveleditor.py index 14e74e5..6b6e896 100644 --- a/leveleditor.py +++ b/leveleditor.py @@ -49,7 +49,8 @@ import mcplatform from mcplatform import askSaveFile import numpy -import OpenGL +from OpenGL import GL +from OpenGL import GLU # from OpenGL.GLUT import glutBitmapCharacter, GLUT_BITMAP_HELVETICA_18 import os from os.path import dirname, isdir @@ -198,7 +199,7 @@ def key_down(self, evt): def unproject(x, y, z): try: - return OpenGL.GLU.gluUnProject(x, y, z) + return GLU.gluUnProject(x, y, z) except ValueError: # projection failed return 0, 0, 0 @@ -404,7 +405,7 @@ def setModelview(self): look = numpy.array(self.cameraPosition) look += self.cameraVector up = (0, 1, 0) - OpenGL.GLU.gluLookAt(pos[0], pos[1], pos[2], + GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) @@ -449,10 +450,10 @@ def _blockUnderCursor(self, center=False): """ try: if Settings.doubleBuffer.get(): - OpenGL.GL.glReadBuffer(OpenGL.GL.GL_BACK) + GL.glReadBuffer(GL.GL_BACK) else: - OpenGL.GL.glReadBuffer(OpenGL.GL.GL_FRONT) - except Exception: + GL.glReadBuffer(GL.GL_FRONT) + except Exception, e: logging.exception('Exception during glReadBuffer') ws = self.get_root().size if center: @@ -468,7 +469,7 @@ def _blockUnderCursor(self, center=False): y = ws[1] - y try: - pixel = OpenGL.GL.glReadPixels(x, y, 1, 1, OpenGL.GL.GL_DEPTH_COMPONENT, OpenGL.GL.GL_FLOAT) + pixel = GL.glReadPixels(x, y, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT) newpoint = unproject(x, y, pixel[0]) except Exception: return 0, 0, 0 @@ -1084,25 +1085,25 @@ def _drawCeiling(self): lines.append((minx, 0, z)) lines.append((maxx, 0, z)) - OpenGL.GL.glColor(0.3, 0.7, 0.9) - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(lines, dtype='float32')) + GL.glColor(0.3, 0.7, 0.9) + GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(lines, dtype='float32')) - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) - OpenGL.GL.glDepthMask(False) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_LINES, 0, len(lines)) - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) - OpenGL.GL.glDepthMask(True) + GL.glEnable(GL.GL_DEPTH_TEST) + GL.glDepthMask(False) + GL.glDrawArrays(GL.GL_LINES, 0, len(lines)) + GL.glDisable(GL.GL_DEPTH_TEST) + GL.glDepthMask(True) def drawCeiling(self): - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) - # OpenGL.GL.glPushMatrix() + GL.glMatrixMode(GL.GL_MODELVIEW) + # GL.glPushMatrix() x, y, z = self.cameraPosition x -= x % 16 z -= z % 16 y = self.editor.level.Height - OpenGL.GL.glTranslate(x, y, z) + GL.glTranslate(x, y, z) self.ceilingList.call(self._drawCeiling) - OpenGL.GL.glTranslate(-x, -y, -z) + GL.glTranslate(-x, -y, -z) _floorQuadList = None @@ -1130,12 +1131,12 @@ def floorColor(self): # floorColor = (0.0, 0.0, 1.0, 0.1) def _drawFloorQuad(self): - OpenGL.GL.glDepthMask(True) - OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, self.floorQuad) - OpenGL.GL.glColor(*self.floorColor) - with gl.glEnable(OpenGL.GL.GL_BLEND, OpenGL.GL.GL_DEPTH_TEST, OpenGL.GL.GL_POLYGON_OFFSET_FILL): - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) + GL.glDepthMask(True) + GL.glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) + GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.floorQuad) + GL.glColor(*self.floorColor) + with gl.glEnable(GL.GL_BLEND, GL.GL_DEPTH_TEST, GL.GL_POLYGON_OFFSET_FILL): + GL.glDrawArrays(GL.GL_QUADS, 0, 4) @property def drawSky(self): @@ -1157,13 +1158,13 @@ def drawSkyBackground(self): self.skyList.call(self._drawSkyBackground) def _drawSkyBackground(self): - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) - OpenGL.GL.glPushMatrix() - OpenGL.GL.glLoadIdentity() - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) - OpenGL.GL.glPushMatrix() - OpenGL.GL.glLoadIdentity() - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) + GL.glMatrixMode(GL.GL_MODELVIEW) + GL.glPushMatrix() + GL.glLoadIdentity() + GL.glMatrixMode(GL.GL_PROJECTION) + GL.glPushMatrix() + GL.glLoadIdentity() + GL.glEnableClientState(GL.GL_COLOR_ARRAY) quad = numpy.array([-1, -1, -1, 1, 1, 1, 1, -1], dtype='float32') colors = numpy.array([0x48, 0x49, 0xBA, 0xff, @@ -1175,20 +1176,20 @@ def _drawSkyBackground(self): if alpha > 0.0: if alpha < 1.0: - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + GL.glEnable(GL.GL_BLEND) - OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, quad) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, colors) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) + GL.glVertexPointer(2, GL.GL_FLOAT, 0, quad) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, 0, colors) + GL.glDrawArrays(GL.GL_QUADS, 0, 4) if alpha < 1.0: - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_BLEND) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) - OpenGL.GL.glPopMatrix() - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) - OpenGL.GL.glPopMatrix() + GL.glDisableClientState(GL.GL_COLOR_ARRAY) + GL.glMatrixMode(GL.GL_PROJECTION) + GL.glPopMatrix() + GL.glMatrixMode(GL.GL_MODELVIEW) + GL.glPopMatrix() enableMouseLag = Settings.enableMouseLag.configProperty() @@ -1204,16 +1205,16 @@ def drawFog(self, val): fogColorBlack = numpy.array([0.0, 0.0, 0.0, 1.0], dtype='float32') def enableFog(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_FOG) + GL.glEnable(GL.GL_FOG) if self.drawSky: - OpenGL.GL.glFogfv(OpenGL.GL.GL_FOG_COLOR, self.fogColor) + GL.glFogfv(GL.GL_FOG_COLOR, self.fogColor) else: - OpenGL.GL.glFogfv(OpenGL.GL.GL_FOG_COLOR, self.fogColorBlack) + GL.glFogfv(GL.GL_FOG_COLOR, self.fogColorBlack) - OpenGL.GL.glFogf(OpenGL.GL.GL_FOG_DENSITY, 0.002) + GL.glFogf(GL.GL_FOG_DENSITY, 0.002) def disableFog(self): - OpenGL.GL.glDisable(OpenGL.GL.GL_FOG) + GL.glDisable(GL.GL_FOG) def getCameraPoint(self): distance = self.editor.currentTool.cameraDistance @@ -1229,7 +1230,7 @@ def setup_projection(self): distance = 1.0 if self.editor.renderer.inSpace(): distance = 8.0 - OpenGL.GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) + GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) def setup_modelview(self): self.setModelview() @@ -1304,13 +1305,13 @@ def setup_projection(self): minx, maxx = - w, w miny, maxy = - h, h minz, maxz = -4000, 4000 - OpenGL.GL.glOrtho(minx, maxx, miny, maxy, minz, maxz) + GL.glOrtho(minx, maxx, miny, maxy, minz, maxz) def setup_modelview(self): x, y, z = self.cameraPosition - OpenGL.GL.glRotate(90.0, 1.0, 0.0, 0.0) - OpenGL.GL.glTranslate(-x, 0, -z) + GL.glRotate(90.0, 1.0, 0.0, 0.0) + GL.glTranslate(-x, 0, -z) def zoom(self, f): x, y, z = self.cameraPosition @@ -1826,13 +1827,13 @@ def reloadToolbar(self): longDistanceMode = Settings.longDistanceMode.configProperty() def genSixteenBlockTexture(self): - has12 = OpenGL.GL.glGetString(OpenGL.GL.GL_VERSION) >= "1.2" + has12 = GL.glGetString(GL.GL_VERSION) >= "1.2" if has12: maxLevel = 2 - mode = OpenGL.GL.GL_LINEAR_MIPMAP_NEAREST + mode = GL.GL_LINEAR_MIPMAP_NEAREST else: maxLevel = 1 - mode = OpenGL.GL.GL_LINEAR + mode = GL.GL_LINEAR def makeSixteenBlockTex(): darkColor = (0x30, 0x30, 0x30, 0xff) @@ -1847,11 +1848,11 @@ def makeSixteenBlockTex(): teximage[-1:] = darkColor teximage[:, -1:] = darkColor teximage[:, :2] = darkColor - # OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, - # OpenGL.GL.GL_TEXTURE_MIN_FILTER, - # OpenGL.GL.GL_NEAREST_MIPMAP_NEAREST), - OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, - OpenGL.GL.GL_TEXTURE_MAX_LEVEL, + # GL.glTexParameter(GL.GL_TEXTURE_2D, + # GL.GL_TEXTURE_MIN_FILTER, + # GL.GL_NEAREST_MIPMAP_NEAREST), + GL.glTexParameter(GL.GL_TEXTURE_2D, + GL.GL_TEXTURE_MAX_LEVEL, maxLevel - 1) for lev in range(maxLevel): @@ -1864,9 +1865,9 @@ def makeSixteenBlockTex(): teximage[:, -1:] = darkColor teximage[:, :2] = darkColor - OpenGL.GL.glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, lev, OpenGL.GL.GL_RGBA8, + GL.glTexImage2D(GL.GL_TEXTURE_2D, lev, GL.GL_RGBA8, w / step, h / step, 0, - OpenGL.GL.GL_RGBA, OpenGL.GL.GL_UNSIGNED_BYTE, + GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, teximage[::step, ::step].ravel()) return Texture(makeSixteenBlockTex, mode) @@ -1879,33 +1880,33 @@ def drawConstructionCube(self, box, color, texture=None): texture = self.sixteenBlockTex # textured cube faces - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) - OpenGL.GL.glDepthMask(False) + GL.glEnable(GL.GL_BLEND) + GL.glEnable(GL.GL_DEPTH_TEST) + GL.glDepthMask(False) # edges within terrain - OpenGL.GL.glDepthFunc(OpenGL.GL.GL_GREATER) + GL.glDepthFunc(GL.GL_GREATER) try: - OpenGL.GL.glColor(color[0], color[1], color[2], max(color[3], 0.35)) + GL.glColor(color[0], color[1], color[2], max(color[3], 0.35)) except IndexError: raise - OpenGL.GL.glLineWidth(1.0) - mceutils.drawCube(box, cubeType=OpenGL.GL.GL_LINE_STRIP) + GL.glLineWidth(1.0) + mceutils.drawCube(box, cubeType=GL.GL_LINE_STRIP) # edges on or outside terrain - OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LEQUAL) - OpenGL.GL.glColor(color[0], color[1], color[2], max(color[3] * 2, 0.75)) - OpenGL.GL.glLineWidth(2.0) - mceutils.drawCube(box, cubeType=OpenGL.GL.GL_LINE_STRIP) - - OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LESS) - OpenGL.GL.glColor(color[0], color[1], color[2], color[3]) - OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LEQUAL) + GL.glDepthFunc(GL.GL_LEQUAL) + GL.glColor(color[0], color[1], color[2], max(color[3] * 2, 0.75)) + GL.glLineWidth(2.0) + mceutils.drawCube(box, cubeType=GL.GL_LINE_STRIP) + + GL.glDepthFunc(GL.GL_LESS) + GL.glColor(color[0], color[1], color[2], color[3]) + GL.glDepthFunc(GL.GL_LEQUAL) mceutils.drawCube(box, texture=texture, selectionBox=True) - OpenGL.GL.glDepthMask(True) + GL.glDepthMask(True) - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + GL.glDisable(GL.GL_BLEND) + GL.glDisable(GL.GL_DEPTH_TEST) def loadFile(self, filename): if self.level and self.unsavedEdits > 0: @@ -2359,10 +2360,10 @@ def drawStars(self): self.mainViewport.cameraPosition = map(lambda x: x / 128.0, pos) self.mainViewport.setModelview() - OpenGL.GL.glColor(.5, .5, .5, 1.) + GL.glColor(.5, .5, .5, 1.) - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, self.starVertices) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(self.starVertices) / 3) + GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.starVertices) + GL.glDrawArrays(GL.GL_QUADS, 0, len(self.starVertices) / 3) self.mainViewport.cameraPosition = pos self.mainViewport.setModelview() @@ -2513,7 +2514,7 @@ def key_down(self, evt): # =========================================================== elif mods & KMOD_SHIFT: - raise OpenGL.GL.GLError(err=1285, description="User pressed CONTROL-SHIFT-F9, requesting a GL Memory Error") + raise GL.GLError(err=1285, description="User pressed CONTROL-SHIFT-F9, requesting a GL Memory Error") else: try: expr = input_text(">>> ", 600) @@ -3299,15 +3300,15 @@ def updateInspectionString(self, blockPosition): pass def drawWireCubeReticle(self, color=(1.0, 1.0, 1.0, 1.0), position=None): - OpenGL.GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) - OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) + GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) blockPosition, faceDirection = self.blockFaceUnderCursor blockPosition = position or blockPosition mceutils.drawTerrainCuttingWire(pymclevel.BoundingBox(blockPosition, (1, 1, 1)), c1=color) - OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) def drawString(self, x, y, color, string): return @@ -3315,18 +3316,18 @@ def drawString(self, x, y, color, string): def freezeStatus(self, string): return -# OpenGL.GL.glColor(1.0, 0., 0., 1.0) +# GL.glColor(1.0, 0., 0., 1.0) # -# # glDrawBuffer(OpenGL.GL.GL_FRONT) -# OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) -# OpenGL.GL.glPushMatrix() +# # glDrawBuffer(GL.GL_FRONT) +# GL.glMatrixMode(GL.GL_PROJECTION) +# GL.glPushMatrix() # glRasterPos(50, 100) # for i in string: # glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(i)) # -# # glDrawBuffer(OpenGL.GL.GL_BACK) -# OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) -# OpenGL.GL.glPopMatrix() +# # glDrawBuffer(GL.GL_BACK) +# GL.glMatrixMode(GL.GL_PROJECTION) +# GL.glPopMatrix() # glFlush() # display.flip() # # while(True): pass @@ -3422,17 +3423,17 @@ def idleHandler(evt): ## glBindTexture(GL_TEXTURE_3D, sourceTex) ## glTexImage3D(GL_TEXTURE_3D, 0, 1, ## level.Width, level.Length, level.Height, -## 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE, +## 0, GL_RED, GL.GL_UNSIGNED_BYTE, ## blocks) ## ## # return ## -## glBindTexture(OpenGL.GL.GL_TEXTURE_2D, destTex) -## glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, 0, 1, +## glBindTexture(GL.GL_TEXTURE_2D, destTex) +## glTexImage2D(GL.GL_TEXTURE_2D, 0, 1, ## level.Width, level.Length, -## 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE, destBlocks) -## glTexParameter(OpenGL.GL.GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) -## glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, OpenGL.GL.GL_TEXTURE_2D, destTex, 0) +## 0, GL_RED, GL.GL_UNSIGNED_BYTE, destBlocks) +## glTexParameter(GL.GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) +## glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL.GL_TEXTURE_2D, destTex, 0) ## ## vertShader = glCreateShader(GL_VERTEX_SHADER) ## @@ -3468,13 +3469,13 @@ def idleHandler(evt): ## ## glUseProgram(prog); ## # return -## OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST); -## OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]); -## OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4); -## OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST); +## GL.glDisable(GL.GL_DEPTH_TEST); +## GL.glVertexPointer(2, GL.GL_FLOAT, 0, [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]); +## GL.glDrawArrays(GL.GL_QUADS, 0, 4); +## GL.glEnable(GL.GL_DEPTH_TEST); ## ## glFlush(); -## destBlocks = glGetTexImage(OpenGL.GL.GL_TEXTURE_2D, 0, GL_RED, OpenGL.GL.GL_UNSIGNED_BYTE); +## destBlocks = glGetTexImage(GL.GL_TEXTURE_2D, 0, GL_RED, GL.GL_UNSIGNED_BYTE); ## print destBlocks, destBlocks[0:8]; ## raise SystemExit; @@ -3624,27 +3625,27 @@ def reloadTextures(self): tool.markerList.invalidate() def drawToolbar(self): - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) - OpenGL.GL.glColor(1., 1., 1., 1.) + GL.glColor(1., 1., 1., 1.) w, h = self.toolbarTextureSize self.guiTexture.bind() - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(( 1, h + 1, 0.5, w + 1, h + 1, 0.5, w + 1, 1, 0.5, 1, 1, 0.5, ), dtype="f4")) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, numpy.array(( 0, 0, w, 0, w, h, 0, h, ), dtype="f4")) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) + GL.glDrawArrays(GL.GL_QUADS, 0, 4) for i in range(len(self.tools)): tool = self.tools[i] @@ -3660,37 +3661,37 @@ def drawToolbar(self): h = 16 self.toolTextures[tool.toolIconName].bind() - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(( x, y + h, 1, x + w, y + h, 1, x + w, y, 1, x, y, 1, ), dtype="f4")) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, numpy.array(( 0, 0, w * 16, 0, w * 16, h * 16, 0, h * 16, ), dtype="f4")) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) - except Exception: + GL.glDrawArrays(GL.GL_QUADS, 0, 4) + except Exception, e: logging.exception('Error while drawing toolbar.') - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) gfont = None def gl_draw(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + GL.glEnable(GL.GL_TEXTURE_2D) + GL.glEnable(GL.GL_BLEND) self.toolbarDisplayList.call(self.drawToolbar) - OpenGL.GL.glColor(1.0, 1.0, 0.0) + GL.glColor(1.0, 1.0, 0.0) - # OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + # GL.glEnable(GL.GL_BLEND) # with gl.glPushMatrix(GL_TEXTURE): - # OpenGL.GL.glLoadIdentity() + # GL.glLoadIdentity() # self.gfont.flatPrint("ADLADLADLADLADL") try: @@ -3713,27 +3714,27 @@ def gl_draw(self): ty = 0. tw = 24. th = 24. - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) self.guiTexture.bind() - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(( tx, ty, 2, tx + tw, ty, 2, tx + tw, ty + th, 2, tx, ty + th, 2, ), dtype="f4")) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, numpy.array(( + GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, numpy.array(( texx, texy + texh, texx + texw, texy + texh, texx + texw, texy, texx, texy, ), dtype="f4")) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, 4) + GL.glDrawArrays(GL.GL_QUADS, 0, 4) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) - OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) + GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) + GL.glDisable(GL.GL_TEXTURE_2D) redOutBoxes = numpy.zeros(9 * 4 * 2, dtype='float32') cursor = 0 @@ -3750,8 +3751,8 @@ def gl_draw(self): cursor += 8 if cursor: - OpenGL.GL.glColor(1.0, 0.0, 0.0, 0.3) - OpenGL.GL.glVertexPointer(2, OpenGL.GL.GL_FLOAT, 0, redOutBoxes) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, cursor / 2) + GL.glColor(1.0, 0.0, 0.0, 0.3) + GL.glVertexPointer(2, GL.GL_FLOAT, 0, redOutBoxes) + GL.glDrawArrays(GL.GL_QUADS, 0, cursor / 2) - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_BLEND) diff --git a/renderer.py b/renderer.py index 3873c45..6ee74fd 100644 --- a/renderer.py +++ b/renderer.py @@ -44,7 +44,7 @@ from glutils import gl, Texture import logging import numpy -import OpenGL +from OpenGL import GL import pymclevel import sys #import time @@ -143,7 +143,7 @@ def makeDisplayLists(self): showRedraw = self.renderer.showRedraw if not (showRedraw and self.needsBlockRedraw): - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) + GL.glEnableClientState(GL.GL_COLOR_ARRAY) renderers = self.blockRenderers @@ -157,7 +157,7 @@ def makeDisplayLists(self): lists[blockRenderer.renderstate].append(l) if not (showRedraw and self.needsBlockRedraw): - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) + GL.glDisableClientState(GL.GL_COLOR_ARRAY) self.needsRedisplay = False self.renderstateLists = lists @@ -334,31 +334,31 @@ def release(self): class renderstateLowDetail(object): @classmethod def bind(self): - OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) + GL.glDisable(GL.GL_CULL_FACE) + GL.glDisable(GL.GL_TEXTURE_2D) @classmethod def release(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) + GL.glEnable(GL.GL_CULL_FACE) + GL.glEnable(GL.GL_TEXTURE_2D) class renderstateAlphaTest(object): @classmethod def bind(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_ALPHA_TEST) + GL.glEnable(GL.GL_ALPHA_TEST) @classmethod def release(self): - OpenGL.GL.glDisable(OpenGL.GL.GL_ALPHA_TEST) + GL.glDisable(GL.GL_ALPHA_TEST) class _renderstateAlphaBlend(object): @classmethod def bind(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + GL.glEnable(GL.GL_BLEND) @classmethod def release(self): - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_BLEND) class renderstateWater(_renderstateAlphaBlend): pass @@ -369,17 +369,17 @@ class renderstateIce(_renderstateAlphaBlend): class renderstateEntity(object): @classmethod def bind(self): - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) - # OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_DEPTH_TEST) + # GL.glDisable(GL.GL_CULL_FACE) + GL.glDisable(GL.GL_TEXTURE_2D) + GL.glEnable(GL.GL_BLEND) @classmethod def release(self): - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) - # OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glEnable(GL.GL_DEPTH_TEST) + # GL.glEnable(GL.GL_CULL_FACE) + GL.glEnable(GL.GL_TEXTURE_2D) + GL.glDisable(GL.GL_BLEND) renderstates = ( renderstatePlain, @@ -767,9 +767,9 @@ def makeVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, ar def makeArrayList(self, chunkPosition, showRedraw): l = gl.glGenLists(1) - OpenGL.GL.glNewList(l, OpenGL.GL.GL_COMPILE) + GL.glNewList(l, GL.GL_COMPILE) self.drawArrays(chunkPosition, showRedraw) - OpenGL.GL.glEndList() + GL.glEndList() return l def drawArrays(self, chunkPosition, showRedraw): @@ -777,11 +777,11 @@ def drawArrays(self, chunkPosition, showRedraw): y = 0 if hasattr(self, 'y'): y = self.y - with gl.glPushMatrix(OpenGL.GL.GL_MODELVIEW): - OpenGL.GL.glTranslate(cx << 4, y, cz << 4) + with gl.glPushMatrix(GL.GL_MODELVIEW): + GL.glTranslate(cx << 4, y, cz << 4) if showRedraw: - OpenGL.GL.glColor(1.0, 0.25, 0.25, 1.0) + GL.glColor(1.0, 0.25, 0.25, 1.0) self.drawVertices() @@ -795,11 +795,11 @@ def drawFaceVertices(self, buf): return stride = elementByteLength - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, stride, (buf.ravel())) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, stride, (buf.ravel()[3:])) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) + GL.glVertexPointer(3, GL.GL_FLOAT, stride, (buf.ravel())) + GL.glTexCoordPointer(2, GL.GL_FLOAT, stride, (buf.ravel()[3:])) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) class EntityRendererGeneric(BlockRenderer): @@ -811,23 +811,23 @@ def drawFaceVertices(self, buf): return stride = elementByteLength - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, stride, (buf.ravel())) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, stride, (buf.ravel()[3:])) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) + GL.glVertexPointer(3, GL.GL_FLOAT, stride, (buf.ravel())) + GL.glTexCoordPointer(2, GL.GL_FLOAT, stride, (buf.ravel()[3:])) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) - OpenGL.GL.glDepthMask(False) + GL.glDepthMask(False) - OpenGL.GL.glPolygonMode(OpenGL.GL.GL_FRONT_AND_BACK, OpenGL.GL.GL_LINE) + GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE) - OpenGL.GL.glLineWidth(2.0) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) + GL.glLineWidth(2.0) + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glPolygonMode(OpenGL.GL.GL_FRONT_AND_BACK, OpenGL.GL.GL_FILL) + GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) - OpenGL.GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) - with gl.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL, OpenGL.GL.GL_DEPTH_TEST): - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glDepthMask(True) + GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) + with gl.glEnable(GL.GL_POLYGON_OFFSET_FILL, GL.GL_DEPTH_TEST): + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) + GL.glDepthMask(True) def _computeVertices(self, positions, colors, offset=False, chunkPosition=(0, 0)): cx, cz = chunkPosition @@ -959,35 +959,35 @@ def drawFaceVertices(self, buf): return stride = elementByteLength - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, stride, (buf.ravel())) - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, stride, (buf.ravel()[3:])) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) + GL.glVertexPointer(3, GL.GL_FLOAT, stride, (buf.ravel())) + GL.glTexCoordPointer(2, GL.GL_FLOAT, stride, (buf.ravel()[3:])) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:])) - OpenGL.GL.glDepthMask(False) + GL.glDepthMask(False) - # OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) + # GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) + GL.glDisable(GL.GL_CULL_FACE) - with gl.glEnable(OpenGL.GL.GL_DEPTH_TEST): - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) + with gl.glEnable(GL.GL_DEPTH_TEST): + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) + GL.glEnable(GL.GL_CULL_FACE) - OpenGL.GL.glPolygonMode(OpenGL.GL.GL_FRONT_AND_BACK, OpenGL.GL.GL_LINE) + GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE) - OpenGL.GL.glLineWidth(1.0) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glLineWidth(2.0) - with gl.glEnable(OpenGL.GL.GL_DEPTH_TEST): - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glLineWidth(1.0) + GL.glLineWidth(1.0) + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) + GL.glLineWidth(2.0) + with gl.glEnable(GL.GL_DEPTH_TEST): + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) + GL.glLineWidth(1.0) - OpenGL.GL.glPolygonMode(OpenGL.GL.GL_FRONT_AND_BACK, OpenGL.GL.GL_FILL) - OpenGL.GL.glDepthMask(True) + GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) + GL.glDepthMask(True) -# OpenGL.GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) -# with gl.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL, OpenGL.GL.GL_DEPTH_TEST): -# OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) +# GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) +# with gl.glEnable(GL.GL_POLYGON_OFFSET_FILL, GL.GL_DEPTH_TEST): +# GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) # def makeChunkVertices(self, chunk): @@ -1026,12 +1026,12 @@ def drawFaceVertices(self, buf): return stride = 16 - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, stride, numpy.ravel(buf.ravel())) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype='uint8').ravel()[12:])) + GL.glVertexPointer(3, GL.GL_FLOAT, stride, numpy.ravel(buf.ravel())) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype='uint8').ravel()[12:])) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(buf) * 4) - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) + GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) + GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) def makeChunkVertices(self, ch): step = 1 @@ -2362,10 +2362,10 @@ def makeFloorTex(self): img = numpy.array([color0, color1, color1, color0], dtype='uint8') - OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, OpenGL.GL.GL_TEXTURE_MIN_FILTER, OpenGL.GL.GL_NEAREST) - OpenGL.GL.glTexParameter(OpenGL.GL.GL_TEXTURE_2D, OpenGL.GL.GL_TEXTURE_MAG_FILTER, OpenGL.GL.GL_NEAREST) + GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) + GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) - OpenGL.GL.glTexImage2D(OpenGL.GL.GL_TEXTURE_2D, 0, OpenGL.GL.GL_RGBA, 2, 2, 0, OpenGL.GL.GL_RGBA, OpenGL.GL.GL_UNSIGNED_BYTE, img) + GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, 2, 2, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, img) def invalidateChunkMarkers(self): self.loadableChunkMarkers.invalidate() @@ -2376,17 +2376,17 @@ def _drawLoadableChunkMarkers(self): sizedChunks = chunkMarkers(chunkSet) - OpenGL.GL.glPushAttrib(OpenGL.GL.GL_FOG_BIT) - OpenGL.GL.glDisable(OpenGL.GL.GL_FOG) + GL.glPushAttrib(GL.GL_FOG_BIT) + GL.glDisable(GL.GL_FOG) - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) - OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) - OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + GL.glEnable(GL.GL_BLEND) + GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) + GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) + GL.glEnable(GL.GL_DEPTH_TEST) - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) - OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glColor(1.0, 1.0, 1.0, 1.0) + GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) + GL.glEnable(GL.GL_TEXTURE_2D) + GL.glColor(1.0, 1.0, 1.0, 1.0) self.floorTexture.bind() # chunkColor = numpy.zeros(shape=(chunks.shape[0], 4, 4), dtype='float32') @@ -2399,7 +2399,7 @@ def _drawLoadableChunkMarkers(self): # chunkColor *= 255 # chunkColor = numpy.array(chunkColor, dtype='uint8') # - # OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, chunkColor) + # GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, 0, chunkColor) for size, chunks in sizedChunks.iteritems(): if not len(chunks): continue @@ -2410,17 +2410,17 @@ def _drawLoadableChunkMarkers(self): chunkPosition[:, :, (0, 2)] *= size chunkPosition[:, :, (0, 2)] += chunks[:, numpy.newaxis, :] chunkPosition *= 16 - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, chunkPosition.ravel()) + GL.glVertexPointer(3, GL.GL_FLOAT, 0, chunkPosition.ravel()) # chunkPosition *= 8 - OpenGL.GL.glTexCoordPointer(2, OpenGL.GL.GL_FLOAT, 0, (chunkPosition[..., (0, 2)] * 8).ravel()) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(chunkPosition) * 4) + GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, (chunkPosition[..., (0, 2)] * 8).ravel()) + GL.glDrawArrays(GL.GL_QUADS, 0, len(chunkPosition) * 4) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) - OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) - OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) - OpenGL.GL.glPopAttrib() + GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) + GL.glDisable(GL.GL_TEXTURE_2D) + GL.glDisable(GL.GL_BLEND) + GL.glDisable(GL.GL_DEPTH_TEST) + GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) + GL.glPopAttrib() def drawLoadableChunkMarkers(self): if not self.isPreviewer or isinstance(self.level, pymclevel.MCInfdevOldLevel): @@ -2464,22 +2464,22 @@ def drawCompressedChunkMarkers(self): coloredChunks = cc > 0 colorBuffer[coloredChunks] *= 0.75 - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) - OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) - OpenGL.GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_COLOR_ARRAY) + GL.glEnable(GL.GL_BLEND) + GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) + GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers) + GL.glEnable(GL.GL_DEPTH_TEST) + GL.glEnableClientState(GL.GL_COLOR_ARRAY) - OpenGL.GL.glVertexPointer(3, OpenGL.GL.GL_FLOAT, 0, vertexBuffer) - OpenGL.GL.glColorPointer(4, OpenGL.GL.GL_UNSIGNED_BYTE, 0, colorBuffer) - OpenGL.GL.glDrawArrays(OpenGL.GL.GL_QUADS, 0, len(vertexBuffer) * 4) + GL.glVertexPointer(3, GL.GL_FLOAT, 0, vertexBuffer) + GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, 0, colorBuffer) + GL.glDrawArrays(GL.GL_QUADS, 0, len(vertexBuffer) * 4) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_COLOR_ARRAY) + GL.glDisableClientState(GL.GL_COLOR_ARRAY) - OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) + GL.glDisable(GL.GL_DEPTH_TEST) - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_BLEND) needsImmediateRedraw = False viewingFrustum = None @@ -2525,14 +2525,14 @@ def callMasterLists(self): continue if self.alpha != 0xff and renderstate is not ChunkCalculator.renderstateLowDetail: - OpenGL.GL.glEnable(OpenGL.GL.GL_BLEND) + GL.glEnable(GL.GL_BLEND) renderstate.bind() - OpenGL.GL.glCallLists(self.masterLists[renderstate]) + GL.glCallLists(self.masterLists[renderstate]) renderstate.release() if self.alpha != 0xff and renderstate is not ChunkCalculator.renderstateLowDetail: - OpenGL.GL.glDisable(OpenGL.GL.GL_BLEND) + GL.glDisable(GL.GL_BLEND) errorLimit = 10 @@ -2547,38 +2547,38 @@ def draw(self): chunksDrawn = 0 - with gl.glPushMatrix(OpenGL.GL.GL_MODELVIEW): + with gl.glPushMatrix(GL.GL_MODELVIEW): dx, dy, dz = self.origin - OpenGL.GL.glTranslate(dx, dy, dz) + GL.glTranslate(dx, dy, dz) - OpenGL.GL.glEnable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) + GL.glEnable(GL.GL_CULL_FACE) + GL.glEnable(GL.GL_DEPTH_TEST) self.level.materials.terrainTexture.bind() - OpenGL.GL.glEnable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glEnableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glEnable(GL.GL_TEXTURE_2D) + GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) offset = DepthOffset.PreviewRenderer if self.isPreviewer else DepthOffset.Renderer - OpenGL.GL.glPolygonOffset(offset, offset) - OpenGL.GL.glEnable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + GL.glPolygonOffset(offset, offset) + GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) self.createMasterLists() try: self.callMasterLists() - except OpenGL.GL.GLError, e: + except GL.GLError, e: if self.errorLimit: self.errorLimit -= 1 traceback.print_exc() print e - OpenGL.GL.glDisable(OpenGL.GL.GL_POLYGON_OFFSET_FILL) + GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) - OpenGL.GL.glDisable(OpenGL.GL.GL_CULL_FACE) - OpenGL.GL.glDisable(OpenGL.GL.GL_DEPTH_TEST) + GL.glDisable(GL.GL_CULL_FACE) + GL.glDisable(GL.GL_DEPTH_TEST) - OpenGL.GL.glDisable(OpenGL.GL.GL_TEXTURE_2D) - OpenGL.GL.glDisableClientState(OpenGL.GL.GL_TEXTURE_COORD_ARRAY) + GL.glDisable(GL.GL_TEXTURE_2D) + GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) # if self.drawLighting: self.drawLoadableChunkMarkers() @@ -2767,33 +2767,33 @@ def rendermain(): # display.init( (640, 480), OPENGL | DOUBLEBUF ) from mcedit import GLDisplayContext - #from OpenGL import GLU + from OpenGL import GLU cxt = GLDisplayContext() import pygame # distance = 4000 - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) - OpenGL.GL.glLoadIdentity() - OpenGL.GLU.gluPerspective(35, 640.0 / 480.0, 0.5, 4000.0) + GL.glMatrixMode(GL.GL_PROJECTION) + GL.glLoadIdentity() + GLU.gluPerspective(35, 640.0 / 480.0, 0.5, 4000.0) h = 366 pos = (0, h, 0) look = (0.0001, h - 1, 0.0001) up = (0, 1, 0) - OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) - OpenGL.GL.glLoadIdentity() + GL.glMatrixMode(GL.GL_MODELVIEW) + GL.glLoadIdentity() - OpenGL.GLU.gluLookAt(pos[0], pos[1], pos[2], + GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) - OpenGL.GL.glClearColor(0.0, 0.0, 0.0, 1.0) + GL.glClearColor(0.0, 0.0, 0.0, 1.0) framestart = datetime.now() frames = 200 for i in range(frames): - OpenGL.GL.glClear(OpenGL.GL.GL_COLOR_BUFFER_BIT | OpenGL.GL.GL_DEPTH_BUFFER_BIT) + GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) renderer.draw() pygame.display.flip() From b366a331bde43e1ec4372271256ef0d9e02205c7 Mon Sep 17 00:00:00 2001 From: David Sowder Date: Tue, 20 Mar 2012 21:28:56 -0500 Subject: [PATCH 8/8] frustrum.py: GL.newaxis should be numpy.newaxis, so make it so --- frustum.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/frustum.py b/frustum.py index 6298024..5be957e 100644 --- a/frustum.py +++ b/frustum.py @@ -85,15 +85,15 @@ def visible(self, points, radius): frustcullaccel C extension module) """ - distances = sum(self.planes[GL.newaxis, :, :] * points[:, GL.newaxis, :], -1) + distances = sum(self.planes[numpy.newaxis, :, :] * points[:, numpy.newaxis, :], -1) return ~any(distances < -radius, -1) def visible1(self, point, radius): - #return self.visible(array(point[GL.newaxis, :]), radius) + #return self.visible(array(point[numpy.newaxis, :]), radius) distance = sum(self.planes * point, -1) vis = ~any(distance < -radius) - #assert vis == self.visible(array(point)[GL.newaxis, :], radius) + #assert vis == self.visible(array(point)[numpy.newaxis, :], radius) return vis