def __init__(self,*args, **kwargs): #win.Win.__init__(self,width=320,height=240,*args, **kwargs) win.Win.__init__(self,*args, **kwargs) self.cont = controller.Controller(minidom.parse(resource.file("jake_graph_FINAL.xml")).documentElement) self.sub = subtitles.Subtitles() #setup the drawer module with current window vars. Since we have to do this, it might be better if we make drawer a singleton drawer.setVars(self)
def mapreader(filename): f = resource.file(filename) xml = ET.XML(f.read()) f.close() layer = xml.find("layer") width = int(layer.attrib['width']) height = int(layer.attrib['height']) tilewidth = int(xml.attrib['tilewidth']) tileheight = int(xml.attrib['tileheight']) data = zlib.decompress(base64.b64decode(xml.find("layer/data").text)) unpack_format = 'I' * (width * height) data = struct.unpack(unpack_format, data) rev_tiles = [row for row in row_walker(data, width)] tiles = [] for row in reversed(rev_tiles): tiles.extend(row) objectlayer = xml.find("objectgroup") objects = {'other':[]} for obj in objectlayer: obj_type = obj.attrib['type'] x = int(obj.attrib['x']) / tilewidth y = height - int(obj.attrib['y']) / tileheight - 1 data = (x, y) if obj_type == 'other': objects[obj_type].append(data) data = objects[obj_type] elif obj_type == 'seed': seed = int(obj.attrib['name']) data += (seed,) objects[obj_type] = data return width, height, tiles, objects
def split_into_random(fileName): for i in range(300): fp = file(fileName, 'rb') size = random.randint(1, 30) buf = fp.read(size * 20 * 1024) with open('stream_data/' + str(i), 'wb') as f: f.write(buf)
def load_level(fname): try: with resource.file(fname,"rb") as f: return Level(pickle.load(f)) except resource.ResourceNotFoundException: try: with open(fname,"rb") as f: return Level(pickle.load(f)) except IOError: return None
def LoadTextures(self): '''texture 0-5: faces, 6-11: hints, 12: blending screen, 13: char''' i = self.loading if i < len(self.textures): # for i in xrange(len(self.textures)): if i < len(self.ary_norm): imgfile = TEXIMG_FACE % i # bmp24 256x256 elif i <= len(self.ary_norm) * 2: imgfile = TEXIMG_HINT else: imgfile = TEXIMG_CHAR[i - len(self.ary_norm) * 2 - 1] # * (bug in fast code) # Both resource.texture and resource.image are faster than image.load. # When 'dat = img.get_image_data().get_data()', # img.load returns a str, but resource.* returns a list of int. # So convert dat to str by ''.join(map(chr, dat)), it is very slow way. # Must be skip ''.join(map(chr, dat)) and it = iter() uses int directory, # and change r, g, b, a = [ord(it.next()) ... to [it.next() ... # with fix handling type of ModifyTexture and DrawBlendCharOnBuffer. # img = resource.texture(imgfile) # img = resource.image(imgfile, flip_x=False, flip_y=False, rotate=0) img = image.load(imgfile, file=resource.file(imgfile, mode='rb')) self.textures[i] = img.get_texture() ix, iy = img.width, img.height rawimage = img.get_image_data() formatstr = 'RGBA' pitch = rawimage.width * len(formatstr) dat = rawimage.get_data(formatstr, pitch) if isinstance(dat[0], int): dat = ''.join(map(chr, dat)) # slow * self.dat[i] = (dat, ix, iy) if i > len(self.ary_norm): # skip face(0-5) and hint(6:white) j = i - len(self.ary_norm) d = [] # it = iter(dat if isinstance(dat[0], int) else map(ord, dat)) # fast * it = iter(dat) while it.__length_hint__(): # r, g, b, a = [it.next() for k in xrange(4)] # fast * r, g, b, a = [ord(it.next()) for k in xrange(4)] if i < len(self.ary_norm) * 2 and r >= 128 and g >= 128 and b >= 128: r, g, b = r if j & 1 else 0, g if j & 2 else 0, b if j & 4 else 0 elif i == len(self.ary_norm) * 2: r, g, b, a = [int(self.instbgc[k] * 255) for k in xrange(4)] else: r, g, b, a = r, g, b, 255 * (r + g + b) / (255 * 3) d.append('%c%c%c%c' % (r, g, b, a)) dat = ''.join(d) glEnable(self.textures[i].target) glBindTexture(self.textures[i].target, self.textures[i].id) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, dat) self.loading = i + 1
def load(self,fname): mtllines = resource.file(fname,"ru") mname = None mat_dl = None mat_params = {'Ka':GL_AMBIENT, 'Kd': GL_DIFFUSE, 'Ks':GL_SPECULAR, 'Ke':GL_EMISSION} tname = None for line in mtllines: tokens = line.split() if not tokens or line[0] == '#': continue if tokens[0] == 'newmtl': if mname: if not tname: glDisable(GL_TEXTURE_2D) glEndList() tname = None mname = tokens[1] mat_dl = self.mat_dls.get(mname) if mat_dl is None: mat_dl = self.mat_dls[mname] = glGenLists(2) glNewList(mat_dl, GL_COMPILE) elif tokens[0] == 'Ns': glMaterialf(GL_FRONT, GL_SHININESS, float(tokens[1])) elif tokens[0] in mat_params: params = map(float,tokens[1:]) floats4 = Mat4Floats(1.0,1.0,1.0,1.0) for i,f in enumerate(params): floats4[i] = f self.mat_trans[mname] = (floats4[3] < 1.0) glMaterialfv(GL_FRONT, mat_params[tokens[0]],floats4) elif tokens[0] == 'map_Kd' and not NOTEXTURES: # need a texture glEnable(GL_TEXTURE_2D) glCallList(mat_dl+1) # will bind texture glEndList() tname = tokens[1] tex = resource.texture(tokens[1]) glNewList(mat_dl+1,GL_COMPILE) if tex: self.mat_textures[tname] = tex trans = self.mat_trans.get(mname,False) self.mat_trans[mname] = trans glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D,tex.id) # will end list before starting next one, or at end if mname: if not tname: glDisable(GL_TEXTURE_2D) glEndList()
def load_from_file(self, filename): mapfile = resource.file(filename) data = json.load(mapfile) self._load_images(data['images']) self.tiles = [] for line in reversed(data['tiles']): tile_line = [] for tile_number in line: image = self.tile_images[tile_number] tile = Tile(image=image, batch=self._batch) tile.solid = image.solid tile_line.append(tile) self.tiles.append(tile_line) self.set_camera_position(0, 0)
def loadEntities(levelName): lineCount = 0 entities = [] with resource.file(levelName+'.txt') as levelFile: for line in levelFile: lineCount += 1 lineErr = "(line " + str(lineCount) + ")" if len(line.strip()) == 0: continue # skip blank lines if line.strip().startswith('#'): continue # skip comment lines try: data = list(literal_eval(line)) except: print lineErr, "This line could not be parsed:", line continue entityType, args = data[0], data[1:] if entityType not in constructors: raise Exception("{0} This is not a entity type: '{1}'".format(lineErr, entityType)) constructor = constructors[entityType] if issubclass(constructor, Blob): controller = args[0] if controller not in allControllers: raise Exception("{0} This is not a valid controller: '{1}'".format(lineErr, controller)) args[0] = allControllers[controller] try: newEntity = constructor(*args) except: print lineErr, "Constructing", entityType, "failed. probably weird arguments:", args if chrashOnFail: raise # TODO: test me! continue entities.append(newEntity) return entities
def load(self,node): """ filename is location of graph xml data file. graph xml data file will contain information concerning clips """ self.graphxml = node self.clipxml = minidom.parse(resource.file(self.graphxml.getAttribute("clipxml"))).documentElement #set up clipmap self.clipmap = dict() for i in utils.getChildren(self.clipxml,"clip"): type = i.getAttribute("type") c = getattr(clip,type,clip.DummyClip)(i) c.preload(False,True) self.clipmap[i.getAttribute("name")] = c #setup transition graph self.graphmap = dict() for e in utils.getChildren(self.graphxml,"clipnode"): if e.getAttribute("id") == "1": print "setting active clip", e.getAttribute("name") self.active = e.getAttribute("name") self.graphmap[e.getAttribute("name")] = GraphNode(e,self.clipmap[e.getAttribute("clip")]) self.getActiveClip().play()
class PanView(object): def __init__(self, window): self.win = window def on_mouse_release(self, x, y, button, modifiers): self.win.remove_handlers(self) def on_mouse_press(self, x, y, button, modifiers): self.win.remove_handlers(self) def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): self.win.tx += dx self.win.ty += dy if __name__ == '__main__': # We swap Y and Z, moving to left-handed system media.listener.up_orientation = (0, -1, 0) # Start facing up (er, forwards) media.listener.forward_orientation = (0, 0, 1) media.listener.label = 'Listener' w = SoundSpaceWindow() r = reader.SpaceReader(w) r.read(resource.file('space.txt')) for player in w.players: player.play() pass w.run()
def main(): w = window.Window(vsync=False, resizable=True) w.set_mouse_cursor(w.get_system_mouse_cursor('text')) @w.event def on_key_press(symbol, modifiers): if sys.platform == 'darwin': accel = key.MOD_COMMAND else: accel = key.MOD_CTRL if modifiers & accel: if symbol == key.B: toggle_style('bold') elif symbol == key.I: toggle_style('italic') elif symbol in (key.EQUAL, key.NUM_ADD): add_font_size(2) elif symbol in (key.MINUS, key.NUM_SUBTRACT): add_font_size(-2) if symbol == key.ESCAPE: w.has_exit = True def toggle_style(attribute): old = caret.get_style(attribute) if old == style.INDETERMINATE: value = True else: value = not old caret.set_style({attribute: value}) def add_font_size(size): old_size = caret.get_style('font_size') if old_size in (style.INDETERMINATE, None): old_size = 12 caret.set_style({'font_size': old_size + size}) def on_resize(width, height): text.x = border text.y = height - border text.width = width - border * 2 text.height = height - border * 2 caret._update() w.push_handlers(on_resize) if len(sys.argv) > 1: content = open(sys.argv[1]).read() else: content = resource.file('info.att').read() # Draw to this border so we can test clipping. border = 50 batch = graphics.Batch() doc = attributed(content) text = layout.IncrementalTextLayout(doc, w.width-border*2, w.height-border*2, multiline=True, batch=batch) caret = caret_module.Caret(text) caret.color = (0, 0, 0) caret.visible = True caret.position = 0 w.push_handlers(caret) fps = clock.ClockDisplay(font=font.load('', 10, dpi=96), color=(0, 0, 0, 1), interval=1., format='FPS: %(fps)d') fps.label.x = 2 fps.label.y = 15 stats_text = font.Text(font.load('', 10, dpi=96), '', x=2, y=2, color=(0, 0, 0, 1)) def update_stats(dt): states = batch.state_map.values() usage = 0. blocks = 0 domains = 0 fragmentation = 0. free_space = 0. capacity = 0. for state in states: for domain in state.values(): domains += 1 free_space += domain.allocator.get_free_size() fragmentation += domain.allocator.get_fragmented_free_size() capacity += domain.allocator.capacity blocks += len(domain.allocator.starts) if free_space: fragmentation /= free_space else: fragmentation = 0. free_space /= capacity usage = 1. - free_space stats_text.text = \ 'States: %d Domains: %d Blocks: %d Usage: %d%% Fragmentation: %d%%' % \ (len(states), domains, blocks, usage * 100, fragmentation * 100) clock.schedule_interval(update_stats, 1) glClearColor(1, 1, 1, 1) glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) while not w.has_exit: clock.tick() w.dispatch_events() w.clear() batch.draw() fps.draw() stats_text.draw() glPushAttrib(GL_CURRENT_BIT) glColor3f(0, 0, 0) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glRectf(border - 2, border - 2, w.width - border + 4, w.height - border + 4) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glPopAttrib() w.flip()
def split(filename): fp = file(filename, 'rb') buf = fp.read(128 * 1024 * 1024) with open('../../BigData/openwhisk/data/train.txt', 'wb') as f: f.write(buf)
def load_obj(self,fname,on_polygon=None): """ Load the .obj file, drawing each sub-object into a display list, and setting each material into a display list A piece called xxx_Origin has one vertex which marks the origin for piece 'xxx', and just adds a glTranslate before and after drawing 'xxx'. """ objlines = resource.file(fname,"ru") self.origins = {} def int0(s): if s: return int(s) else: return 0 def coords(tokens,rotaxes=False): xyz = [float(c) for c in tokens[1:4]] if rotaxes: xyz.insert(0,xyz.pop()) return xyz piece = '' mesh_dl = None npoints = 0 primitives = {1:GL_POINTS, 2: GL_LINES, 3:GL_TRIANGLES, 4:GL_QUADS} vertices = [] normals = [] tcoords = [] rotaxes = False firstline = objlines.next() if "Exported from Wings 3D" in firstline: rotaxes = True for line in objlines: tokens = line.split() if not tokens or line[0] == '#': continue key = tokens[0] if key == 'mtllib': self.mat_dls.load(tokens[1]) elif key == 'o': if piece.endswith("_Origin") and len(vertices): self.origins[piece[:-7]] = vertices[-1] elif npoints: glEnd() npoints = 0 if mesh_dl: glEndList() piece = tokens[1] if piece.endswith("_Origin"): mesh_dl = None else: mesh_dl = self.mesh_dls[piece] = glGenLists(1) self.mesh_trans[piece] = False glNewList(mesh_dl,GL_COMPILE) elif key == 'v': vertices.append(coords(tokens, rotaxes)) elif key == 'vn': normals.append(coords(tokens, rotaxes)) elif key == 'vt': tcoords.append(coords(tokens)) elif key == 'usemtl': if npoints: glEnd() npoints = 0 mdl = self.mat_dls.get(tokens[1]) if mdl is not None: # a material we have loaded glCallList(mdl) self.mesh_trans[piece] |= self.mat_dls.is_transparent(tokens[1]) elif key == 'f': points = [map(int0, s.split('/')) for s in tokens[1:]] if len(points) != npoints: if npoints: glEnd() npoints = len(points) prim = primitives.get(npoints, GL_POLYGON) glBegin(prim) for v, t, n in points: if n: glNormal3f(*normals[n-1]) if t: glTexCoord2f(*tcoords[t-1]) glVertex3f(*vertices[v-1]) if on_polygon: on_polygon(piece,[vertices[v-1] for v,t,n in points]) if npoints > 4: # GL_POLYGON npoints = -1 # can't continue without a glEnd() if piece.endswith("_Origin") and len(vertices): self.origins[piece[:-7]] = vertices[-1] elif npoints: glEnd() npoints = 0 if mesh_dl: glEndList() # Now wrap extra glTranslatef around the pieces with origins for piece,(vx,vy,vz) in self.origins.items(): dl_old = self.mesh_dls.get(piece) if not dl_old: continue dl_new = glGenLists(1) self.mesh_dls[piece] = dl_new self.mesh_dls[dl_old] = dl_old # stash it so __del__ can release it later with gl_compile(dl_new): glTranslatef(-vx,-vy,-vz) glCallList(dl_old) glTranslatef(vx,vy,vz)
def main(): w = window.Window(vsync=False, resizable=True) w.set_mouse_cursor(w.get_system_mouse_cursor('text')) @w.event def on_key_press(symbol, modifiers): if sys.platform == 'darwin': accel = key.MOD_COMMAND else: accel = key.MOD_CTRL if modifiers & accel: if symbol == key.B: toggle_style('bold') elif symbol == key.I: toggle_style('italic') elif symbol in (key.EQUAL, key.NUM_ADD): add_font_size(2) elif symbol in (key.MINUS, key.NUM_SUBTRACT): add_font_size(-2) if symbol == key.ESCAPE: w.has_exit = True def toggle_style(attribute): old = caret.get_style(attribute) if old == style.INDETERMINATE: value = True else: value = not old caret.set_style({attribute: value}) def add_font_size(size): old_size = caret.get_style('font_size') if old_size in (style.INDETERMINATE, None): old_size = 12 caret.set_style({'font_size': old_size + size}) def on_resize(width, height): text.x = border text.y = height - border text.width = width - border * 2 text.height = height - border * 2 caret._update() w.push_handlers(on_resize) if len(sys.argv) > 1: content = open(sys.argv[1]).read() else: content = resource.file('info.att').read() # Draw to this border so we can test clipping. border = 50 batch = graphics.Batch() doc = attributed(content) text = layout.IncrementalTextLayout(doc, w.width - border * 2, w.height - border * 2, multiline=True, batch=batch) caret = caret_module.Caret(text) caret.color = (0, 0, 0) caret.visible = True caret.position = 0 w.push_handlers(caret) fps = clock.ClockDisplay(font=font.load('', 10, dpi=96), color=(0, 0, 0, 1), interval=1., format='FPS: %(fps)d') fps.label.x = 2 fps.label.y = 15 stats_text = font.Text(font.load('', 10, dpi=96), '', x=2, y=2, color=(0, 0, 0, 1)) def update_stats(dt): states = list(batch.state_map.values()) usage = 0. blocks = 0 domains = 0 fragmentation = 0. free_space = 0. capacity = 0. for state in states: for domain in list(state.values()): domains += 1 free_space += domain.allocator.get_free_size() fragmentation += domain.allocator.get_fragmented_free_size() capacity += domain.allocator.capacity blocks += len(domain.allocator.starts) if free_space: fragmentation /= free_space else: fragmentation = 0. free_space /= capacity usage = 1. - free_space stats_text.text = \ 'States: %d Domains: %d Blocks: %d Usage: %d%% Fragmentation: %d%%' % \ (len(states), domains, blocks, usage * 100, fragmentation * 100) clock.schedule_interval(update_stats, 1) glClearColor(1, 1, 1, 1) glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) while not w.has_exit: clock.tick() w.dispatch_events() w.clear() batch.draw() fps.draw() stats_text.draw() glPushAttrib(GL_CURRENT_BIT) glColor3f(0, 0, 0) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glRectf(border - 2, border - 2, w.width - border + 4, w.height - border + 4) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glPopAttrib() w.flip() main()