def __init__(self, context, svgData): self.svgData = None self.texture = None self.context = context self.cache = None self.transform = SvgTransform() # Detect the type of data passed in if type(svgData) == file: self.svgData = svgData.read() elif type(svgData) == str: bitmapFile = svgData.replace(".svg", ".png") # Load PNG files directly if svgData.endswith(".png"): self.texture = Texture(svgData) # Check whether we have a prerendered bitmap version of the SVG file elif svgData.endswith(".svg") and os.path.exists(bitmapFile): Log.debug("Loading cached bitmap '%s' instead of '%s'." % (bitmapFile, svgData)) self.texture = Texture(bitmapFile) else: if not haveAmanith: e = "PyAmanith support is deprecated and you are trying to load an SVG file." Log.error(e) raise RuntimeError(e) Log.debug("Loading SVG file '%s'." % (svgData)) self.svgData = open(svgData).read() # Make sure we have a valid texture if not self.texture: if type(svgData) == str: e = "Unable to load texture for %s." % svgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e)
def __init__(self, context, ImgData): self.ImgData = None self.texture = None self.context = context self.cache = None self.filename = ImgData # Detect the type of data passed in if type(ImgData) == file: self.ImgData = ImgData.read() elif type(ImgData) == str: self.texture = Texture(ImgData) elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in self.texture = Texture() self.texture.loadImage(ImgData) # Make sure we have a valid texture if not self.texture: if type(ImgData) == str: e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) self.pixelSize = self.texture.pixelSize self.position = [0.0,0.0] self.scale = [1.0,1.0] self.angle = 0 self.color = (1.0,1.0,1.0) self.rect = (0,1,0,1) self.shift = -.5 self.createArrays()
def __init__(self, filename=None, fontsize=None, charset=DEFAULT_CHARSET): assert type(fontsize)==int if filename==None: filename=DEFAULT_FONT[0] if fontsize==None: fontsize=DEFAULT_FONT[1] # lets create the image for the texture from the font self._font=lib.Font(filename, fontsize) self._font.RenderSet(charset=charset) # make the glyph size details for each character image,extents=self._font.Render() #image=tools.fromSDLImageToPILImage(image) #print "IMAGE",image image.save("temp.png") self.extents=extents # call constructor Texture.__init__(self,image=image,filename=filename) # create the alpha numeric tex list self.charset=charset self._metrics=self._font.metrics # in a font, the tex's store is a hash rather than a list (not frames) self.texchars=dict([ (ch,Tex(self,*extents[ch])) for ch in charset]) self.texframes=[Tex(self,0.0,0.0,1.0,1.0)]
def AddTexture(self, Display, ID, Filename): if ID == "": return NewTexture = Texture() if not NewTexture.Load(Display, Filename): Log("Unable to Load Texture:", ID) return self.TexList[ID] = NewTexture
def initData(filepath=None, texpath=None): global objs if not filepath: filepath=Path("files/sphere.obj") if not texpath: texpath=Path("texture/earth") obj_data = io.read_obj(filepath) sphere = io.read_obj("files/sphere.obj") # cube_data = io.read_obj("files/cube.obj") obj = Object(obj_data, [1.0, 1.0, 1.0]) light = Object(sphere, [1.0, 1.0, 1.0]) sky = Object(sphere, [0.8, 0.8, 0.8]) if Path(texpath).is_dir(): obj_tex = Cubemap() else: obj_tex = Texture() obj_tex.load(Path(texpath)) stars = Texture() stars.load("texture/milky_way.jpg") moon = Texture() moon.load("texture/moon.jpg") # for key in earth.faces: # print(f'{key}: {earth.faces[key].filename}') sky.create(stars) obj.create(obj_tex) # obj.create() light.create(moon) objs = [obj, light, sky] # objs = [obj, light] # Place objects in center light.translate(-light.x, -light.y, -light.z) obj.translate(-obj.x, -obj.y, -obj.z) sky.translate(-sky.x, -sky.y, -sky.z-1) light.scale(0.1, 0.1, 0.1) sky.scale(10,10,10) sky.rotate('y', 145) gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LESS) # Unbind Vertex Array Object. gl.glBindVertexArray(0)
def tracker(i): boxes = Boxes(len(files)) tex = Texture() ims = Slicer() th = Threshold() hog = Hog() cells = Cells(sizeh, sizew) names = list(listdir(path)) names = names[i:i + batch_size] net = Network() net.load('data/net/dataset_184_nets_ann/', 'compile_config.txt', hog_block_size, hog_cell_size, hog_orientations) index = 0 while (len(names) > 0): index = len(names) - 1 name = names.pop() img = cv2.imread(path + name) img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) images, coords = ims.split(img_grey, sizeh, sizew, sizeh, sizew) signal = tex.analize(images, haralick_feature) indexes = th.threshold_mean(signal) #coords_f = [] #for x in indexes: # coords_f.append(coords[x]) coords = coords[indexes] coords = cells.group(coords) coords = cells.reorganize_coords(coords) for c in coords: part_img = img_grey[c[2]:c[3], c[0]:c[1]] part_img = cv2.resize(part_img, resize_img) part = hog.runOne(part_img, orient=hog_orientations, pixels=hog_cell_size, cells=hog_block_size) part = part.reshape((1, part.shape[0])) Y = net.predict(part)[0, 0] if (Y > thresh and c[0] != 0 and c[1] != 500 and abs(c[0] - c[1]) * abs(c[2] - c[3]) > 625): cells.box2(img, c) box = Box() box.box = [c[0], c[2], c[1], c[3]] boxes.add(index, box) cv2.imwrite(path_out + name, img) boxes.save('boxes_predicted_ann_25.b')
def __init__(self, main, ScreenManager, tileSizeX, tileSizeY, map="base"): self.main = main self.screenManager = ScreenManager self.display_surf = ScreenManager.display_surf self.middle = ScreenManager.size[0]/2 self.tileSizeX = tileSizeX # H self.tileSizeY = tileSizeY # W self.IsoMathHelper = None self._IsoMathHelperInit() self.MapPos = self.MapPosX, self.MapPosY = 0, 0 self.MapMovConst = 10 self.RegisterMapMovement() self.RecalculateDisplayTiles = True self.RDT_X_S = None self.RDT_X_E = None self.RDT_Y_S = None self.RDT_Y_E = None self.Map = Map(map) self.Map.loadMap() print(self.Map.sizeX) self.MapJSON = MapJSON(map) self.MapJSON.loadMap() print(self.MapJSON.sizeX) self.tiles = [] self.loadTextures() self.screenManager.setBackgrounColor(self.screenManager.colors["Black"], 1.0) self.MouseSelectedTexture = Texture("resources/graphics/map/select_tile.png") self.test = Texture("resources/graphics/map/holzblock.png") self.MouseActive = True self.InGameMenuActive = False self.button = Button(self.main, self.display_surf, self.screenManager.colors["Gray"], self.screenManager.colors["Blue"], self.screenManager.colors["Yellow"], self.screenManager.colors["White"], self.middle-200, (self.screenManager.size[1]/10)*2+140, 400, 80, "Create Level", 60, self.place) self.main.EventHandler.registerKEYDOWNevent(K_ESCAPE, self.KEYDOWNesc) self.main.EventHandler.registerMOUSEBUTTONDOWNevent(1, self.place) self.button.draw()
def _genTextures(self): self.BordSurf = pygame.Surface(self.size) self.HoverSurf = pygame.Surface(self.size) pygame.draw.rect(self.BordSurf, self.bord_color, self.Rect, self.border) pygame.draw.rect(self.BordSurf, self.in_color, self.InRect, 0) self.BordSurf.blit(self.textSurf, self.textRect) pygame.draw.rect(self.HoverSurf, self.hover_color, self.Rect, self.border) pygame.draw.rect(self.HoverSurf, self.in_color, self.InRect, 0) self.HoverSurf.blit(self.textSurf, self.textRect) self.HoverTexture = Texture(None, self.HoverSurf, self.Rect) self.BoardTexture = Texture(None, self.BordSurf, self.Rect)
def __init__(self, texture_filename, position_x, position_y, width, height): self.texture = Texture(texture_filename) self.x = position_x self.y = position_y self.size['width'] = width self.size['height'] = height
def __init__(self): self.texture = Texture('resources/piste2.png') self.tracklist = {} self.trackelt = [{ 'type': 'straight', 'L': 5.4 }, { 'type': 'turn', 'L': 0.7, 'sweep': math.radians(135) }, { 'type': 'straight', 'L': 2 }, { 'type': 'turn', 'L': 0.5, 'sweep': math.radians(78.65) }, { 'type': 'turn', 'L': 4.5, 'sweep': -math.radians(90) }, { 'type': 'turn', 'L': 0.8, 'sweep': math.radians(146.35) }, { 'type': 'straight', 'L': 1.7 }, { 'type': 'turn', 'L': 1.4, 'sweep': math.radians(90) }]
def generateTextureInfo(self): # Figure out texture size self.mTextureWidth, self.mTextureHeight = self.getTextureDimension(self.mTotalIndices) # Initialize an array of target textures based upon the chosen settings self.mTextures = [Texture(self.mTextureWidth, self.mTextureHeight, self.mView, view) for view in self.mView.getTextureViews()]
def testRenderToTexture(self): scale = 4 fullwidth, fullheight = 512, 512 width, height = int(fullwidth / scale), int(fullheight / scale) t = Texture() self.e.svg.setProjection((0, 0, fullwidth, fullheight)) t.prepareRenderTarget(width, height) t.setAsRenderTarget() glViewport(0, 0, width, height) glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.svg.transform.translate(width * scale / 2, height * scale / 2) self.svg.transform.rotate(3.141592) self.svg.draw() t.resetDefaultRenderTarget() glViewport(0, 0, fullwidth, fullheight) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0.0, 1.0, 0.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() t.bind() glEnable(GL_TEXTURE_2D) if not t.framebuffer.emulated: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glClear(GL_COLOR_BUFFER_BIT) glColor3f(1.0, 1.0, 1.0) glBegin(GL_TRIANGLE_STRIP) glTexCoord2f(0.0, 0.0) glVertex2f(0.0, 0.0) glTexCoord2f(1.0, 0.0) glVertex2f(1.0, 0.0) glTexCoord2f(0.0, 1.0) glVertex2f(0.0, 1.0) glTexCoord2f(1.0, 1.0) glVertex2f(1.0, 1.0) glEnd() self.e.video.flip() import time time.sleep(2)
def __init__(self, context, ImgData): self.ImgData = None self.texture = None self.context = context self.cache = None self.transform = SvgTransform() self.filename = ImgData self.triangVtx = np.zeros((4,2), dtype=float32) self.textriangVtx = np.zeros((4,2), dtype=float32) # Detect the type of data passed in if type(ImgData) == file: self.ImgData = ImgData.read() elif type(ImgData) == str: self.texture = Texture(ImgData) # bitmapFile = ImgData.replace(".svg", ".png") # # Load PNG files directly # if ImgData.endswith(".png"): # self.texture = Texture(ImgData) # elif ImgData.endswith(".jpg"): # self.texture = Texture(ImgData) # elif ImgData.endswith(".jpeg"): # self.texture = Texture(ImgData) # Check whether we have a prerendered bitmap version of the SVG file # elif ImgData.endswith(".svg") and os.path.exists(bitmapFile): # Log.debug("Loading cached bitmap '%s' instead of '%s'." % (bitmapFile, ImgData)) # self.texture = Texture(bitmapFile) # else: # if not haveAmanith: # e = "PyAmanith support is deprecated and you are trying to load an SVG file." # Log.error(e) # raise RuntimeError(e) # Log.debug("Loading SVG file '%s'." % (ImgData)) # self.ImgData = open(ImgData).read() elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in self.texture = Texture() self.texture.loadImage(ImgData) # Make sure we have a valid texture if not self.texture: if type(ImgData) == str: e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e)
def tracker(i): boxes = Boxes(len(files)) tex = Texture() ims = Slicer() th = Threshold() hog = Hog() cells = Cells(sizeh,sizew) names = list(listdir(path)) names = names[i:i+batch_size] f = open('data/net/dataset_184_nets_svm/svm_c_2_p_8_o_2.svm','rb') clf = pickle.load(f) f.close() while(len(names)>0): index = len(names)-1 name = names.pop() img = cv2.imread(path+name) img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) images,coords = ims.split(img_grey,sizeh,sizew,sizeh,sizew) signal_p = tex.analize(images,haralick_feature) indexes = th.threshold_mean(signal_p) coords_f = [] for x in indexes: coords_f.append(coords[x]) coords = cells.group(coords_f) coords = cells.reorganize_coords(coords) for c in coords: part_img = img_grey[c[2]:c[3],c[0]:c[1]] part_img = cv2.resize(part_img,resize_img) part = hog.runOne(part_img,orient=hog_orientations,pixels=hog_cell_size,cells=hog_block_size) part = part.reshape((1,part.shape[0])) Y = clf.predict(part) if(Y>thresh and c[0]!=0 and c[1]!=500 and abs(c[0]-c[1])*abs(c[2]-c[3])>625 ): cells.box2(img,c) box = Box() box.box = [c[0],c[2],c[1],c[3]] boxes.add(index,box) cv2.imwrite(path_out+name,img) boxes.save('boxes_predicted_svm_25.b')
def loadTexture(self, name, target, param = Texture.Parameters(), settings = Texture.Settings()): if name in self.textures: return self.textures[name] if name not in self.images: return None image = self.images[name] self.textures[name] = texture = Texture.create(name, image.data, image.width, image.height, target, image.textureFormat, param, settings) return texture
def loadTextureFile(self): if not self.textureFile: return f = open(self.textureFile, 'r') self.textures = [] for line in f: l = line.strip() if not l: continue self.textures.append(Texture(l))
def __init__(self, texture_filename, position_x, position_y, width, height, visible, speed): self.texture = Texture(texture_filename) self.x = position_x self.y = position_y self.size['width'] = width self.size['height'] = height self.visible = visible self.speed = speed
def tracker(i): boxes = Boxes(len(files)) tex = Texture() ims = Slicer() th = Threshold() cells = Cells(sizeh,sizew) names = list(listdir(path)) names = names[i:i+batch_size] f = open('svmsemhog.svm','rb') clf = pickle.load(f) f.close() while(len(names)>0): index = len(names)-1 name = names.pop() img = cv2.imread(path+name) img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) images,coords = ims.split(img_grey,sizeh,sizew,sizeh,sizew) signal_p = tex.analize(images,haralick_feature) indexes = th.threshold_mean(signal_p) coords_f = [] for x in indexes: coords_f.append(coords[x]) coords = cells.group(coords_f) coords = cells.reorganize_coords(coords) for c in coords: part_img = img_grey[c[2]:c[3],c[0]:c[1]] part_img = cv2.resize(part_img,resize_img).flatten() print(part_img) input() Y = clf.predict(part_img) if(Y>thresh and c[0]!=0 and c[1]!=500 and abs(c[0]-c[1])*abs(c[2]-c[3])>625 ): cells.box2(img,c) box = Box() box.box = [c[0],c[2],c[1],c[3]] boxes.add(index,box) cv2.imwrite(path_out+name,img) boxes.save('boxes_predicted_svm.b')
def __init__(self, file_name): global active_camera self.models = None self.cameras = None self.lights = None self.active_camera = active_camera # shared resources self.textures = {} # name -> tex lookup self.shaders = {} # name -> tex lookup self.meshes = {} # name -> tex lookup with open(file_name, "r") as fp: data = json.load(fp) # models self.models = {name: Model(m) for (name, m) in data["models"].items()} for model in self.models.values(): vert_file = model.io['shader']['vert'] frag_file = model.io['shader']['frag'] shader_name = vert_file.split('.')[0] shader = ResourceManager.get_shader(shader_name) if not shader: shader = Shader(vert_file, frag_file) ResourceManager.add_shader(shader_name, shader) model.shader = shader mesh_name = model.io['mesh'] # contains relative path string mesh = ResourceManager.get_mesh(mesh_name) if not mesh: mesh = Mesh(mesh_name) ResourceManager.add_mesh(mesh_name, mesh) model.mesh = mesh tex_files = model.io['textures'] for (layer, tex_file) in tex_files.items(): tex = ResourceManager.get_texture(tex_file) if not tex: tex = Texture(tex_file) ResourceManager.add_texture(tex_file, tex) model.textures[layer] = tex # cameras, set first camera to active self.cameras = { name: Camera(c) for (name, c) in data["cameras"].items() } if len(self.cameras) > 0: # get first items value active_camera = next(iter(self.cameras.items()))[1] logging.warn('camera needs to set shader uniforms') # lights self.lights = {name: Light(l) for (name, l) in data["lights"].items()} logging.warn('light needs to set shader uniforms')
def loadItemLabel(self, i): # Load the item label if it isn't yet loaded item = self.items[i] if self.itemLabels[i] is None: if isinstance(item, Song.SongInfo): label = self.engine.resource.fileName(self.library, item.songName, "label.png") else: assert isinstance(item, Song.LibraryInfo) label = self.engine.resource.fileName(item.libraryName, "label.png") if os.path.exists(label): self.itemLabels[i] = Texture(label)
def __init__(self, context, ImgData): self.ImgData = None self.texture = None self.context = context self.cache = None self.filename = ImgData # Detect the type of data passed in if isinstance(ImgData, file): self.ImgData = ImgData.read() elif isinstance(ImgData, basestring): self.texture = Texture(ImgData) elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in self.texture = Texture() self.texture.loadImage(ImgData) # Make sure we have a valid texture if not self.texture: if isinstance(ImgData, basestring): e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) self.pixelSize = self.texture.pixelSize #the size of the image in pixels (from texture) self.position = [0.0, 0.0] #position of the image in the viewport self.scale = [1.0, 1.0] #percentage scaling self.angle = 0 #angle of rotation (degrees) self.color = (1.0, 1.0, 1.0, 1.0) #glColor rgba self.rect = (0, 1, 0, 1) #texture mapping coordinates self.shift = -.5 #horizontal alignment self.vshift = -.5 #vertical alignment self.path = self.texture.name #path of the image file self.texArray = np.zeros((4, 2), dtype=np.float32) self.createTex()
def testRenderToTexture(self): scale = 4 fullwidth, fullheight = 512, 512 width, height = int(fullwidth / scale), int(fullheight / scale) t = Texture() self.e.svg.setProjection((0, 0, fullwidth, fullheight)) glViewport(0, 0, width, height) glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.svg.transform.translate(width * scale / 2, height * scale / 2) self.svg.transform.rotate(3.141592) self.svg.draw() glViewport(0, 0, fullwidth, fullheight) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0.0, 1.0, 0.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() t.bind() glEnable(GL_TEXTURE_2D) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glClear(GL_COLOR_BUFFER_BIT) glColor3f(1.0, 1.0, 1.0) glBegin(GL_TRIANGLE_STRIP) glTexCoord2f(0.0, 0.0) glVertex2f(0.0, 0.0) glTexCoord2f(1.0, 0.0) glVertex2f(1.0, 0.0) glTexCoord2f(0.0, 1.0) glVertex2f(0.0, 1.0) glTexCoord2f(1.0, 1.0) glVertex2f(1.0, 1.0) glEnd() self.e.video.flip() import time time.sleep(2)
def __init__(self, context, ImgData): self.ImgData = None self.texture = None self.context = context self.cache = None self.filename = ImgData # Detect the type of data passed in if isinstance(ImgData, file): self.ImgData = ImgData.read() elif isinstance(ImgData, basestring): self.texture = Texture(ImgData) elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in self.texture = Texture() self.texture.loadImage(ImgData) # Make sure we have a valid texture if not self.texture: if isinstance(ImgData, basestring): e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) self.pixelSize = self.texture.pixelSize #the size of the image in pixels (from texture) self.position = [0.0,0.0] #position of the image in the viewport self.scale = [1.0,1.0] #percentage scaling self.angle = 0 #angle of rotation (degrees) self.color = (1.0,1.0,1.0,1.0) #glColor rgba self.rect = (0,1,0,1) #texture mapping coordinates self.shift = -.5 #horizontal alignment self.vshift = -.5 #vertical alignment self.path = self.texture.name #path of the image file self.texArray = np.zeros((4,2), dtype=np.float32) self.createTex()
def __init__(self, path, text="", size=32, shadow=True): self.font = pygame.font.Font(os.path.join("..", "data", "fonts", path), int(size)) self.texture = Texture() self.cache = Cache() # attributes self.scale = (1.0, 1.0) # image bounds (width, height) self.position = (0, 0) # where in the window it should render self.angle = 0 # angle which the image is drawn self.color = (255, 255, 255, 255) # colour of the image self.rect = (0.0, 0.0, 1.0, 1.0) # left, top, right, bottom, crops the texture self.alignment = 1 # alignment of the text (left, center , right) self.shadow = True # does the font project a shadow self.text = None self.setText(text) # it is not necessary to enter a string upon initialization,
def cacheGlyph(self, ch): """ Add character and size to glyph caches @param ch: Character @return: Glyph instance """ # Font size self.glyphSizeCache[ch] = self.font.size(ch) # Font texture s = self.font.render(ch, True, (255, 255, 255)) t = Texture() t.setFilter(GL_LINEAR, GL_LINEAR) t.setRepeat(GL_CLAMP, GL_CLAMP) t.loadSurface(s, alphaChannel=True) del s self.glyphCache[ch] = t return t
def __init__(self, texture_path): self.texture_path = texture_path self.texture_size = 16 # 16*16 texture size self.textures = {} for texture in json.load(open(TEXTURE_CONFIG_FILE)).items(): name = texture[0] settings = texture[1] texture_coords = settings["texture_coords"] mining_level = settings["mining_level"] damage = settings["damage"] top, bottom, side = texture_coords self.textures[name] = Texture( name, self.get_texture_coordinates(top, bottom, side), mining_level, damage) self.indestructible_resources = [ resource for resource in self.textures.values() if resource.indestructible ] self.world_resources = [ texture for texture in list(self.textures.values()) if texture not in self.indestructible_resources ] self.resource_levels = [ self.textures["dirt"], self.textures["stone"], self.textures["bedrock"] ] self.wall_resource = self.textures["bedrock"] self.faces = [ (0, 1, 0), (0, -1, 0), (-1, 0, 0), (1, 0, 0), (0, 0, 1), (0, 0, -1), ]
def initializeGL(self): glClearColor(0.0, 0.0, 0.0, 1.0) glClearDepth(1.0) domeStr = "CanvasModel.Dome" self.shaders[domeStr + "_proj"] = Shader("shaders/dome_proj.vert", "shaders/dome_4proj.frag") self.shaders[domeStr + "_edgeblend"] = Shader( "shaders/dome_edgeblend.vert", "shaders/dome_edgeblend_4proj.frag") self.shaders[domeStr + "_inv_proj"] = Shader( "shaders/dome_inv_proj.vert", "shaders/dome_inv_proj.frag") # cycloramaStr = "CanvasModel.Cyclorama" # self.shaders[cycloramaStr+"_proj"] = Shader("shaders/cyclorama_proj.vert","shaders/dome_proj.frag") # self.shaders[cycloramaStr+"_edgeblend"] = Shader("shaders/cyclorama_edgeblend.vert","shaders/cyclorama_edgeblend.frag") # self.shaders[cycloramaStr+"_inv_proj"] = Shader("shaders/dome_inv_proj.vert","shaders/dome_inv_proj.frag") for textureFile in self.textureFiles: texFile = os.path.join(TEXTURE_PATH, textureFile) self.textures[textureFile[:-4]] = Texture(texFile)
def cacheGlyph(self, ch): """ Add character and size to glyph caches @param ch: Character @return: Glyph instance """ # Font size self.glyphSizeCache[ch] = self.font.size(ch) # Font texture s = self.font.render(ch, True, (255, 255, 255)) t = Texture() t.setFilter(GL_LINEAR, GL_LINEAR) t.setRepeat(GL_CLAMP, GL_CLAMP) t.loadSurface(s, alphaChannel = True) del s self.glyphCache[ch] = t return t
def __init__(self, context, imgPath): self.imgPath = None self.texture = None self.context = context self.cache = None self.transform = ImgTransform() # Load PNG files directly if imgPath.endswith(".png"): self.texture = Texture(imgPath) else: e = "Unsupported Image format." Log.error(e) raise RuntimeError(e) # Make sure we have a valid texture if not self.texture: e = "Unable to load texture for %s." % imgPath Log.error(e) raise RuntimeError(e)
def getGlyph(self, ch): """ Get the L{Texture} for a given character. @param ch: Character @return: L{Texture} instance """ try: return self.glyphCache[ch] except KeyError: s = self.font.render(ch, True, (255, 255, 255)) """ # Draw outlines import Image, ImageFilter srcImg = Image.fromstring("RGBA", s.get_size(), pygame.image.tostring(s, "RGBA")) img = Image.fromstring("RGBA", s.get_size(), pygame.image.tostring(s, "RGBA")) for y in xrange(img.size[1]): for x in xrange(img.size[0]): a = 0 ns = 3 n = 0 for ny in range(max(0, y - ns), min(img.size[1], y + ns)): for nx in range(max(0, x - ns), min(img.size[0], x + ns)): a += srcImg.getpixel((nx, ny))[3] n += 1 if a and srcImg.getpixel((x, y))[3] == 0: img.putpixel((x, y), (0, 0, 0, a / n)) s = pygame.image.fromstring(img.tostring(), s.get_size(), "RGBA") """ t = Texture() t.setFilter(GL_LINEAR, GL_LINEAR) t.setRepeat(GL_CLAMP, GL_CLAMP) t.loadSurface(s, alphaChannel = True) del s self.glyphCache[ch] = t return t
def render(self, text, pos = (0, 0), direction = (1, 0), scale = DEFAULT_SCALE): """ Draw some text. @param text: Text to draw @param pos: Text coordinate tuple (x, y) @param direction: Text direction vector (x, y, z) @param scale: Scale factor """ # deufeufeu : new drawing relaying only on pygame.font.render # : I know me miss special unicodes characters, but the gain # : is really important. def drawSquare(w,h,tw,th): glBegin(GL_TRIANGLE_STRIP) glTexCoord2f(0.0,th) glVertex2f(0,0) glTexCoord2f(tw,th) glVertex2f(w,0) glTexCoord2f(0.0,0.0) glVertex2f(0,h) glTexCoord2f(tw,0.0) glVertex2f(w,h) glEnd() if not text: return try: t,w,h = self.stringsCache.get(text) except KeyError: s = self.font.render(text, True, (255,255,255)) t = Texture() t.setFilter(GL_LINEAR, GL_LINEAR) t.setRepeat(GL_CLAMP, GL_CLAMP) t.loadSurface(s, alphaChannel = True) del s w, h = self.font.size(text) self.stringsCache.add(text,(t,w,h)) x, y = pos scale *= self.scale w, h = w*scale, h*scale tw,th = t.size glEnable(GL_TEXTURE_2D) glPushMatrix() glTranslatef(x,y,0) t.bind() if self.outline: glPushAttrib(GL_CURRENT_BIT) glPushMatrix() glColor4f(0, 0, 0, .25 * glGetDoublev(GL_CURRENT_COLOR)[3]) blur = 2 * DEFAULT_SCALE for offset in [(-.7, -.7), (0, -1), (.7, -.7), (-1, 0), (1, 0), (-.7, .7), (0, 1), (.7, .7)]: glPushMatrix() glTranslatef(blur * offset[0], blur * offset[1], 0) drawSquare(w,h,tw,th) glPopMatrix() glPopMatrix() glPopAttrib() if self.shadow: glPushAttrib(GL_CURRENT_BIT) glPushMatrix() glColor4f(0, 0, 0, 1) glTranslatef(.0022, .0005, 0) drawSquare(w,h,tw,th) glPopMatrix() glPopAttrib() drawSquare(w,h,tw,th) glPopMatrix() glDisable(GL_TEXTURE_2D) return
def render(self, text, pos = (0, 0), direction = (1, 0), scale = DEFAULT_SCALE, shadowoffset = (.0022, .0005)): """ Draw some text. @param text: Text to draw @param pos: Text coordinate tuple (x, y) @param direction: Text direction vector (x, y, z) @param scale: Scale factor """ # deufeufeu : new drawing relaying only on pygame.font.render # : I know me miss special unicodes characters, but the gain # : is really important. # evilynux : Use arrays to increase performance def drawSquare(w,h,tw,th): self.square_prim[1,0] = self.square_prim[3,0] = w self.square_prim[2,1] = self.square_prim[3,1] = h self.square_tex[0,1] = self.square_tex[1,1] = th self.square_tex[1,0] = self.square_tex[3,0] = tw glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointerf(self.square_prim) glTexCoordPointerf(self.square_tex) glDrawArrays(GL_TRIANGLE_STRIP, 0, self.square_prim.shape[0]) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY); if not text: return try: t,w,h = self.stringsCache.get(text) except KeyError: s = self.font.render(text, True, (255,255,255)) t = Texture() t.setFilter(GL_LINEAR, GL_LINEAR) t.setRepeat(GL_CLAMP, GL_CLAMP) t.loadSurface(s, alphaChannel = True) del s w, h = self.font.size(text) self.stringsCache.add(text,(t,w,h)) x, y = pos scale *= self.scale w, h = w*scale, h*scale tw,th = t.size glEnable(GL_TEXTURE_2D) glPushMatrix() glTranslatef(x,y,0) t.bind() if self.outline: glPushAttrib(GL_CURRENT_BIT) glPushMatrix() glColor4f(0, 0, 0, .25 * glGetDoublev(GL_CURRENT_COLOR)[3]) blur = 2 * DEFAULT_SCALE for offset in [(-.7, -.7), (0, -1), (.7, -.7), (-1, 0), (1, 0), (-.7, .7), (0, 1), (.7, .7)]: glPushMatrix() glTranslatef(blur * offset[0], blur * offset[1], 0) drawSquare(w,h,tw,th) glPopMatrix() glPopMatrix() glPopAttrib() if self.shadow: glPushAttrib(GL_CURRENT_BIT) glPushMatrix() glColor4f(0, 0, 0, 1) glTranslatef(shadowoffset[0], shadowoffset[1], 0) drawSquare(w,h,tw,th) glPopMatrix() glPopAttrib() drawSquare(w,h,tw,th) glPopMatrix() glDisable(GL_TEXTURE_2D) return
def loadFromFile(self, name): texture = Texture(name) return texture.loadImage()
iA, iB, iC = [dot(n, render.light) for n in (nA, nB, nC)] intensity = w * iA + v * iB + u * iC intensity = intensity / 4 if (tcolor): return color( int(tcolor[2] * intensity) if tcolor[0] * intensity > 0 else 0, int(tcolor[1] * intensity) if tcolor[1] * intensity > 0 else 0, int(tcolor[0] * intensity) if tcolor[2] * intensity > 0 else 0) else: return color(0, 0, 0) def table(render, **kwargs): tx, ty = kwargs['texture_coords'] return color(255, 255, 255) r = Render(800, 800) t = Texture('./models/model.bmp') r.light = V3(0, 1, 1) r.active_texture = t r.active_shader = fragment r.lookAt(V3(1, 0, 5), V3(0, 0, 0), V3(0, 1, 0)) r.load('./models/model.obj', translate=(0, 0, 0), scale=(1, 1, 1), rotate=(0, 0, 0)) r.draw_arrays('TRIANGLES') r.display('out.bmp')
class SvgDrawing: def __init__(self, context, svgData): self.svgData = None self.texture = None self.context = context self.cache = None self.transform = SvgTransform() # Detect the type of data passed in if type(svgData) == file: self.svgData = svgData.read() elif type(svgData) == str: bitmapFile = svgData.replace(".svg", ".png") # Load PNG files directly if svgData.endswith(".png"): self.texture = Texture(svgData) # Check whether we have a prerendered bitmap version of the SVG file elif svgData.endswith(".svg") and os.path.exists(bitmapFile): Log.debug("Loading cached bitmap '%s' instead of '%s'." % (bitmapFile, svgData)) self.texture = Texture(bitmapFile) else: if not haveAmanith: e = "PyAmanith support is deprecated and you are trying to load an SVG file." Log.error(e) raise RuntimeError(e) Log.debug("Loading SVG file '%s'." % (svgData)) self.svgData = open(svgData).read() # Make sure we have a valid texture if not self.texture: if type(svgData) == str: e = "Unable to load texture for %s." % svgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) def _cacheDrawing(self, drawBoard): self.cache.beginCaching() parser = sax.make_parser() sax.parseString(self.svgData, SvgHandler(drawBoard, self.cache)) self.cache.endCaching() del self.svgData def convertToTexture(self, width, height): if self.texture: return e = "SVG drawing does not have a valid texture image." Log.error(e) raise RuntimeError(e) #try: # self.texture = Texture() # self.texture.bind() # self.texture.prepareRenderTarget(width, height) # self.texture.setAsRenderTarget() # quality = self.context.getRenderingQuality() # self.context.setRenderingQuality(HIGH_QUALITY) # geometry = self.context.geometry # self.context.setProjection((0, 0, width, height)) # glViewport(0, 0, width, height) # self.context.clear() # transform = SvgTransform() # transform.translate(width / 2, height / 2) # self._render(transform) # self.texture.resetDefaultRenderTarget() # self.context.setProjection(geometry) # glViewport(*geometry) # self.context.setRenderingQuality(quality) #except TextureException, e: # Log.warn("Unable to convert SVG drawing to texture: %s" % str(e)) def _getEffectiveTransform(self): transform = SvgTransform(self.transform) transform.transform(self.context.transform) return transform def _render(self, transform): glMatrixMode(GL_TEXTURE) glPushMatrix() glMatrixMode(GL_MODELVIEW) glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT | GL_STENCIL_BUFFER_BIT | GL_TRANSFORM_BIT | GL_COLOR_BUFFER_BIT | GL_POLYGON_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT) if not self.cache: self.cache = SvgCache(self.context.drawBoard) self._cacheDrawing(self.context.drawBoard) self.cache.draw(transform) glPopAttrib() glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_MODELVIEW) def draw(self, color = (1, 1, 1, 1)): glMatrixMode(GL_TEXTURE) glPushMatrix() glMatrixMode(GL_PROJECTION) glPushMatrix() self.context.setProjection() glMatrixMode(GL_MODELVIEW) glPushMatrix() transform = self._getEffectiveTransform() if self.texture: glLoadIdentity() transform.applyGL() glScalef(self.texture.pixelSize[0], self.texture.pixelSize[1], 1) glTranslatef(-.5, -.5, 0) glColor4f(*color) self.texture.bind() glEnable(GL_TEXTURE_2D) glBegin(GL_TRIANGLE_STRIP) glTexCoord2f(0.0, 1.0) glVertex2f(0.0, 1.0) glTexCoord2f(1.0, 1.0) glVertex2f(1.0, 1.0) glTexCoord2f(0.0, 0.0) glVertex2f(0.0, 0.0) glTexCoord2f(1.0, 0.0) glVertex2f(1.0, 0.0) glEnd() glDisable(GL_TEXTURE_2D) else: self._render(transform) glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW)
class ImgDrawing(object): VTX_ARRAY = np.array([[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]], dtype=np.float32) #hard-coded quad for drawing textures onto def drawImage(image, scale = (1.0, -1.0), coord = (0, 0), rot = 0, \ color = (1,1,1,1), rect = (0,1,0,1), stretched = 0, fit = CENTER, \ alignment = CENTER, valignment = CENTER): """ Draws the image/surface to screen """ if not isinstance(image, ImgDrawing): return False image.setRect(rect) image.setScale(scale[0], scale[1], stretched) image.setPosition(coord[0], coord[1], fit) image.setAlignment(alignment) image.setVAlignment(valignment) image.setAngle(rot) image.setColor(color) image.draw() return True def __init__(self, context, ImgData): self.ImgData = None self.texture = None self.context = context self.cache = None self.filename = ImgData # Detect the type of data passed in if isinstance(ImgData, file): self.ImgData = ImgData.read() elif isinstance(ImgData, basestring): self.texture = Texture(ImgData) elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in self.texture = Texture() self.texture.loadImage(ImgData) # Make sure we have a valid texture if not self.texture: if isinstance(ImgData, basestring): e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) self.pixelSize = self.texture.pixelSize #the size of the image in pixels (from texture) self.position = [0.0,0.0] #position of the image in the viewport self.scale = [1.0,1.0] #percentage scaling self.angle = 0 #angle of rotation (degrees) self.color = (1.0,1.0,1.0,1.0) #glColor rgba self.rect = (0,1,0,1) #texture mapping coordinates self.shift = -.5 #horizontal alignment self.vshift = -.5 #vertical alignment self.path = self.texture.name #path of the image file self.texArray = np.zeros((4,2), dtype=np.float32) self.createTex() def createTex(self): tA = self.texArray rect = self.rect #topLeft, topRight, bottomRight, bottomLeft tA[0,0] = rect[0]; tA[0,1] = rect[3] tA[1,0] = rect[1]; tA[1,1] = rect[3] tA[2,0] = rect[1]; tA[2,1] = rect[2] tA[3,0] = rect[0]; tA[3,1] = rect[2] def width1(self): """ @return the width of the texture in pixels """ width = self.pixelSize[0] if width: return width else: return 0 def height1(self): """ @return the height of the texture in pixels """ height = self.pixelSize[1] if height is not None: return height else: return 0 def widthf(self, pixelw): """ @param pixelw - a width in pixels @return the scaled ratio of the pixelw divided by the pixel width of the texture """ width = self.pixelSize[0] if width is not None: wfactor = pixelw/width return wfactor else: return 0 def setPosition(self, x, y, fit = CENTER): """ Sets position of this image on screen @param fit: Adjusts the texture so the coordinate for the y-axis placement can be on the top side (1), bottom side (2), or center point (any other value) of the image """ if fit == CENTER: #y is center pass elif fit == TOP: #y is on top (not center) y = y - ((self.pixelSize[1] * abs(self.scale[1]))*.5*(self.context.geometry[3]/SCREEN_HEIGHT)) elif fit == BOTTOM: #y is on bottom y = y + ((self.pixelSize[1] * abs(self.scale[1]))*.5*(self.context.geometry[3]/SCREEN_HEIGHT)) self.position = [x,y] def setScale(self, width, height, stretched = 0): """ @param stretched: Bitmask stretching the image according to the following values 0) does not stretch the image 1) fits it to the width of the viewport 2) fits it to the height of the viewport 3) stretches it so it fits the viewport 4) preserves the aspect ratio while stretching """ if stretched & FULL_SCREEN: # FULL_SCREEN is FIT_WIDTH | FIT_HEIGHT xStretch = 1 yStretch = 1 if stretched & FIT_WIDTH: xStretch = float(self.context.geometry[2]) / self.pixelSize[0] if stretched & FIT_HEIGHT: yStretch = float(self.context.geometry[3]) / self.pixelSize[1] if stretched & KEEP_ASPECT: if stretched & FULL_SCREEN == FULL_SCREEN: #Note that on FULL_SCREEN | KEEP_ASPECT we will scale to the larger and clip. if xStretch > yStretch: yStretch = xStretch else: xStretch = yStretch else: if stretched & FIT_WIDTH: yStretch = xStretch else: xStretch = yStretch width *= xStretch height *= yStretch self.scale = [width, height] def setAngle(self, angle): self.angle = angle def setRect(self, rect): """ @param rect: The surface rectangle, this is used for cropping the texture """ if not rect == self.rect: self.rect = rect self.createTex() def setAlignment(self, alignment): """ @param alignment: Adjusts the texture so the coordinate for x-axis placement can either be on the left side (0), center point (1), or right(2) side of the image """ if alignment == CENTER:#center self.shift = -.5 elif alignment == LEFT: #left self.shift = 0 elif alignment == RIGHT:#right self.shift = -1.0 def setVAlignment(self, alignment): """ @param valignment: Adjusts the texture so the coordinate for y-axis placement can either be on the bottom side (0), center point (1), or top(2) side of the image """ if alignment == CENTER:#center self.vshift = -.5 if alignment == TOP:#bottom self.vshift = 0 elif alignment == BOTTOM:#top self.vshift = -1.0 def setColor(self, color): if len(color) == 3: color = (color[0], color[1], color[2], 1.0) self.color = color def draw(self): with cmgl.PushedSpecificMatrix(GL_TEXTURE): with cmgl.PushedSpecificMatrix(GL_PROJECTION): with cmgl.MatrixMode(GL_PROJECTION): self.context.setProjection() with cmgl.PushedMatrix(): glLoadIdentity() glTranslate(self.position[0], self.position[1], 0.0) glRotatef(-self.angle, 0, 0, 1) glScalef(self.scale[0], self.scale[1], 1.0) glScalef(self.pixelSize[0], self.pixelSize[1], 1) glTranslatef(self.shift, self.vshift, 0) glColor4f(*self.color) glEnable(GL_TEXTURE_2D) self.texture.bind() cmgl.drawArrays(GL_QUADS, vertices=ImgDrawing.VTX_ARRAY, texcoords=self.texArray) glDisable(GL_TEXTURE_2D)
class ImgDrawing(object): def __init__(self, context, ImgData): self.ImgData = None self.texture = None self.context = context self.cache = None self.transform = SvgTransform() self.filename = ImgData self.triangVtx = np.zeros((4,2), dtype=float32) self.textriangVtx = np.zeros((4,2), dtype=float32) # Detect the type of data passed in if type(ImgData) == file: self.ImgData = ImgData.read() elif type(ImgData) == str: self.texture = Texture(ImgData) # bitmapFile = ImgData.replace(".svg", ".png") # # Load PNG files directly # if ImgData.endswith(".png"): # self.texture = Texture(ImgData) # elif ImgData.endswith(".jpg"): # self.texture = Texture(ImgData) # elif ImgData.endswith(".jpeg"): # self.texture = Texture(ImgData) # Check whether we have a prerendered bitmap version of the SVG file # elif ImgData.endswith(".svg") and os.path.exists(bitmapFile): # Log.debug("Loading cached bitmap '%s' instead of '%s'." % (bitmapFile, ImgData)) # self.texture = Texture(bitmapFile) # else: # if not haveAmanith: # e = "PyAmanith support is deprecated and you are trying to load an SVG file." # Log.error(e) # raise RuntimeError(e) # Log.debug("Loading SVG file '%s'." % (ImgData)) # self.ImgData = open(ImgData).read() elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in self.texture = Texture() self.texture.loadImage(ImgData) # Make sure we have a valid texture if not self.texture: if type(ImgData) == str: e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) def convertToTexture(self, width, height): if self.texture: return e = "SVG drawing does not have a valid texture image." Log.error(e) raise RuntimeError(e) def _getEffectiveTransform(self): transform = SvgTransform(self.transform) transform.transform(self.context.transform) return transform def width1(self): width = self.texture.pixelSize[0] if not width == None: return width else: return 0 #myfingershurt: def height1(self): height = self.texture.pixelSize[1] if not height == None: return height else: return 0 def widthf(self, pixelw): width = self.texture.pixelSize[0] wfactor = pixelw/width if not width == None: return wfactor else: return 0 def draw(self, color = (1, 1, 1, 1), rect = (0,1,0,1), lOffset = 0.0, rOffset = 0.0): glMatrixMode(GL_TEXTURE) glPushMatrix() glMatrixMode(GL_PROJECTION) glPushMatrix() self.context.setProjection() glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() self._getEffectiveTransform().applyGL() glScalef(self.texture.pixelSize[0], self.texture.pixelSize[1], 1) glTranslatef(-.5, -.5, 0) glColor4f(*color) glEnable(GL_TEXTURE_2D) self.texture.bind() self.triangVtx[0,0] = 0.0-lOffset self.triangVtx[0,1] = 1.0 self.triangVtx[1,0] = 1.0-rOffset self.triangVtx[1,1] = 1.0 self.triangVtx[2,0] = 0.0+lOffset self.triangVtx[2,1] = 0.0 self.triangVtx[3,0] = 1.0+rOffset self.triangVtx[3,1] = 0.0 self.textriangVtx[0,0] = rect[0] self.textriangVtx[0,1] = rect[3] self.textriangVtx[1,0] = rect[1] self.textriangVtx[1,1] = rect[3] self.textriangVtx[2,0] = rect[0] self.textriangVtx[2,1] = rect[2] self.textriangVtx[3,0] = rect[1] self.textriangVtx[3,1] = rect[2] glEnableClientState(GL_TEXTURE_COORD_ARRAY) glEnableClientState(GL_VERTEX_ARRAY) glVertexPointerf(self.triangVtx) glTexCoordPointerf(self.textriangVtx) glDrawArrays(GL_TRIANGLE_STRIP, 0, self.triangVtx.shape[0]) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(GL_TEXTURE_2D) glPopMatrix() glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW)
class ImgDrawing(object): def __init__(self, context, ImgData): self.ImgData = None self.texture = None self.context = context self.cache = None self.filename = ImgData # Detect the type of data passed in if type(ImgData) == file: self.ImgData = ImgData.read() elif type(ImgData) == str: self.texture = Texture(ImgData) elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in self.texture = Texture() self.texture.loadImage(ImgData) # Make sure we have a valid texture if not self.texture: if type(ImgData) == str: e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) self.pixelSize = self.texture.pixelSize self.position = [0.0,0.0] self.scale = [1.0,1.0] self.angle = 0 self.color = (1.0,1.0,1.0) self.rect = (0,1,0,1) self.shift = -.5 self.createArrays() def createArrays(self): self.vtxArray = np.zeros((4,2), dtype=float32) self.texArray = np.zeros((4,2), dtype=float32) self.createVtx() self.createTex() def createVtx(self): vA = self.vtxArray #short hand variable casting #topLeft, topRight, bottomRight, bottomLeft vA[0,0] = 0.0; vA[0,1] = 1.0 vA[1,0] = 1.0; vA[1,1] = 1.0 vA[2,0] = 1.0; vA[2,1] = 0.0 vA[3,0] = 0.0; vA[3,1] = 0.0 def createTex(self): tA = self.texArray rect = self.rect #topLeft, topRight, bottomRight, bottomLeft tA[0,0] = rect[0]; tA[0,1] = rect[3] tA[1,0] = rect[1]; tA[1,1] = rect[3] tA[2,0] = rect[1]; tA[2,1] = rect[2] tA[3,0] = rect[0]; tA[3,1] = rect[2] def convertToTexture(self, width, height): if self.texture: return e = "SVG drawing does not have a valid texture image." Log.error(e) raise RuntimeError(e) def width1(self): width = self.pixelSize[0] if width: return width else: return 0 #myfingershurt: def height1(self): height = self.pixelSize[1] if height: return height else: return 0 def widthf(self, pixelw): width = self.pixelSize[0] if width: wfactor = pixelw/width return wfactor else: return 0 def setPosition(self, x, y): self.position = [x,y] def setScale(self, width, height): self.scale = [width, height] def setAngle(self, angle): self.angle = angle def setRect(self, rect): if not rect == self.rect: self.rect = rect self.createTex() def setAlignment(self, alignment): if alignment == 0: #left self.shift = 0 elif alignment == 1:#center self.shift = -.5 elif alignment == 2:#right self.shift = -1.0 def setColor(self, color): if len(color) == 3: color = (color[0], color[1], color[2], 1.0) self.color = color def draw(self): glMatrixMode(GL_TEXTURE) glPushMatrix() glMatrixMode(GL_PROJECTION) glPushMatrix() self.context.setProjection() glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glTranslate(self.position[0], self.position[1], 0.0) glScalef(self.scale[0], self.scale[1], 1.0) glRotatef(self.angle, 0, 0, 1) glScalef(self.pixelSize[0], self.pixelSize[1], 1) glTranslatef(self.shift, -.5, 0) glColor4f(*self.color) glEnable(GL_TEXTURE_2D) self.texture.bind() glEnableClientState(GL_TEXTURE_COORD_ARRAY) glEnableClientState(GL_VERTEX_ARRAY) glVertexPointerf(self.vtxArray) glTexCoordPointerf(self.texArray) glDrawArrays(GL_QUADS, 0, self.vtxArray.shape[0]) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(GL_TEXTURE_2D) glPopMatrix() glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW)
class ImgDrawing(object): def __init__(self, context, ImgData): self.ImgData = None self.texture = None self.context = context self.cache = None self.filename = ImgData # Detect the type of data passed in if type(ImgData) == file: self.ImgData = ImgData.read() elif type(ImgData) == str: self.texture = Texture(ImgData) elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in self.texture = Texture() self.texture.loadImage(ImgData) # Make sure we have a valid texture if not self.texture: if type(ImgData) == str: e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) self.pixelSize = self.texture.pixelSize #the size of the image in pixels (from texture) self.position = [0.0,0.0] #position of the image in the viewport self.scale = [1.0,1.0] #percentage scaling self.angle = 0 #angle of rotation (degrees) self.color = (1.0,1.0,1.0,1.0) #glColor rgba self.rect = (0,1,0,1) #texture mapping coordinates self.shift = -.5 #horizontal alignment self.vshift = -.5 #vertical alignment self.path = self.texture.name #path of the image file self.createArrays() def createArrays(self): self.vtxArray = np.zeros((4,2), dtype=np.float32) self.texArray = np.zeros((4,2), dtype=np.float32) self.createVtx() self.createTex() def createVtx(self): vA = self.vtxArray #short hand variable casting #topLeft, topRight, bottomRight, bottomLeft vA[0,0] = 0.0; vA[0,1] = 1.0 vA[1,0] = 1.0; vA[1,1] = 1.0 vA[2,0] = 1.0; vA[2,1] = 0.0 vA[3,0] = 0.0; vA[3,1] = 0.0 def createTex(self): tA = self.texArray rect = self.rect #topLeft, topRight, bottomRight, bottomLeft tA[0,0] = rect[0]; tA[0,1] = rect[3] tA[1,0] = rect[1]; tA[1,1] = rect[3] tA[2,0] = rect[1]; tA[2,1] = rect[2] tA[3,0] = rect[0]; tA[3,1] = rect[2] def width1(self): width = self.pixelSize[0] if width: return width else: return 0 #myfingershurt: def height1(self): height = self.pixelSize[1] if height: return height else: return 0 def widthf(self, pixelw): width = self.pixelSize[0] if width: wfactor = pixelw/width return wfactor else: return 0 def setPosition(self, x, y): self.position = [x,y] def setScale(self, width, height): self.scale = [width, height] def setAngle(self, angle): self.angle = angle def setRect(self, rect): if not rect == self.rect: self.rect = rect self.createTex() def setAlignment(self, alignment): if alignment == LEFT: #left self.shift = 0 elif alignment == CENTER:#center self.shift = -.5 elif alignment == RIGHT:#right self.shift = -1.0 def setVAlignment(self, alignment): if alignment == 0: #bottom self.vshift = 0 elif alignment == 1:#center self.vshift = -.5 elif alignment == 2:#top self.vshift = -1.0 def setColor(self, color): if len(color) == 3: color = (color[0], color[1], color[2], 1.0) self.color = color def draw(self): with cmgl.PushedSpecificMatrix(GL_TEXTURE): with cmgl.PushedSpecificMatrix(GL_PROJECTION): with cmgl.MatrixMode(GL_PROJECTION): self.context.setProjection() with cmgl.PushedMatrix(): glLoadIdentity() glTranslate(self.position[0], self.position[1], 0.0) glScalef(self.scale[0], self.scale[1], 1.0) glRotatef(self.angle, 0, 0, 1) glScalef(self.pixelSize[0], self.pixelSize[1], 1) glTranslatef(self.shift, self.vshift, 0) glColor4f(*self.color) glEnable(GL_TEXTURE_2D) self.texture.bind() cmgl.drawArrays(GL_QUADS, vertices=self.vtxArray, texcoords=self.texArray) glDisable(GL_TEXTURE_2D)
Then we Draw the stars in the sky, using a shader that use a random generator of white points, and that random has lower probability when y is greater. """ stars(r) """ We draw to moons, using an sphere model, each one has different texture and differnt shader to produce the effect of an celestial body. This models were made using bump mapping. """ #Draw the moon Iscaco t = Texture('./models/iscalo.bmp') r.active_texture = t r.active_light = norm(V3(0, 20, 0)) r.load('./models/sphere.obj', [-0.55, 0.70, 0], [0.22, 0.22, 0.22], [0, 0.2, 0]) r.active_shader = moon r.draw_arrays('TRIANGLES') #Draw the moon Urica t = Texture('./models/urica.bmp') r.active_texture = t r.load('./models/sphere.obj', [0.57, 0.80, 0], [0.20, 0.20, 0.20], [0, 0.2, 0]) r.active_shader = planet r.draw_arrays('TRIANGLES') """
mesh2 = Mesh("resources/meshes/plane2_p_n_uv1.ply") mesh2.load() mesh2.create() mesh2_mat = pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 0, 0])) # mesh3 = Mesh("resources/meshes/Dragon.ply") # mesh3.load() # mesh3.create() # mesh3_mat = pyrr.matrix44.create_from_translation(pyrr.Vector3([2, 1, .5])) shader1 = Shader("resources/shaders/shader1.vs", "resources/shaders/shader1.fs") shader1.load() shader1.create() # shader1.use() # needed tex1 = Texture("resources/images/marble.jpg") tex1.load() tex1.create() tex2 = Texture("resources/images/brickwall.jpg") tex2.load() tex2.create() tex3 = Texture("resources/images/StoneMarbleCalacatta004_COL_2K.jpg") tex3.load() tex3.create() light_pos = [0.0, 1.0, 3.0] # set global render states glClearColor(0, 0.1, 0.1, 1)
def render(self, text, pos=(0, 0), rotate=0, scale=DEFAULT_SCALE, shadowoffset=(.0022, .0005), align=LEFT, new=False, shadow=False, outline=False, shadowOpacity=1.0): """ Draw some text. @param text: Text to draw @param pos: Text coordinate tuple (x, y) @param rotate: Angle to rotate text, in degrees @param scale: Scale factor """ # deufeufeu : new drawing relaying only on pygame.font.render # : I know me miss special unicodes characters, but the gain # : is really important. # evilynux : Use arrays to increase performance def drawSquare(w, h, tw, th): self.square_prim[1, 0] = self.square_prim[3, 0] = w self.square_prim[2, 1] = self.square_prim[3, 1] = h self.square_tex[0, 1] = self.square_tex[1, 1] = th self.square_tex[1, 0] = self.square_tex[3, 0] = tw cmgl.drawArrays(GL_TRIANGLE_STRIP, vertices=self.square_prim, texcoords=self.square_tex) if not text: return try: t, w, h = self.stringsCache.get(text) except KeyError: s = self.font.render(text, True, (255, 255, 255)) t = Texture() t.setFilter(GL_LINEAR, GL_LINEAR) t.setRepeat(GL_CLAMP, GL_CLAMP) t.loadSurface(s, alphaChannel=True) del s w, h = self.font.size(text) self.stringsCache.add(text, (t, w, h)) x, y = pos scale *= self.scale w, h = w * scale * self.aspectRatioFactor, h * scale if align == CENTER: #we have already done all the calculating. Why not add this? - akedrou x -= (w / 2) elif align == RIGHT: x -= w y -= (h / 2) tw, th = t.size glEnable(GL_TEXTURE_2D) with cmgl.PushedMatrix(): if rotate: if not isinstance(rotate, tuple): glRotatef(rotate, 0, 0, 1.0) else: glRotatef(0, *rotate) glTranslatef(x, y, 0) t.bind() if self.outline or outline: with cmgl.PushedAttrib(GL_CURRENT_BIT): glColor4f(0, 0, 0, .25 * glGetDoublev(GL_CURRENT_COLOR)[3]) blur = 2 * DEFAULT_SCALE for offset in [(-.7, -.7), (0, -1), (.7, -.7), (-1, 0), (1, 0), (-.7, .7), (0, 1), (.7, .7)]: with cmgl.PushedMatrix(): glTranslatef(blur * offset[0], blur * offset[1], 0) drawSquare(w, h, tw, th) if self.shadow or shadow: with cmgl.PushedAttrib(GL_CURRENT_BIT): glColor4f( 0, 0, 0, glGetDoublev(GL_CURRENT_COLOR)[3] * shadowOpacity) with cmgl.PushedMatrix(): glTranslatef(shadowoffset[0], shadowoffset[1], 0) drawSquare(w, h, tw, th) drawSquare(w, h, tw, th) glDisable(GL_TEXTURE_2D)
def render(self, text, pos = (0, 0), rotate = 0, scale = DEFAULT_SCALE, shadowoffset = (.0022, .0005), align = LEFT, new = False): """ Draw some text. @param text: Text to draw @param pos: Text coordinate tuple (x, y) @param rotate: Angle to rotate text, in degrees @param scale: Scale factor """ # deufeufeu : new drawing relaying only on pygame.font.render # : I know me miss special unicodes characters, but the gain # : is really important. # evilynux : Use arrays to increase performance def drawSquare(w,h,tw,th): self.square_prim[1,0] = self.square_prim[3,0] = w self.square_prim[2,1] = self.square_prim[3,1] = h self.square_tex[0,1] = self.square_tex[1,1] = th self.square_tex[1,0] = self.square_tex[3,0] = tw cmglDrawArrays(GL_TRIANGLE_STRIP, vertices=self.square_prim, texcoords=self.square_tex) if not text: return try: t,w,h = self.stringsCache.get(text) except KeyError: s = self.font.render(text, True, (255,255,255)) t = Texture() t.setFilter(GL_LINEAR, GL_LINEAR) t.setRepeat(GL_CLAMP, GL_CLAMP) t.loadSurface(s, alphaChannel = True) del s w, h = self.font.size(text) self.stringsCache.add(text,(t,w,h)) x, y = pos scale *= self.scale w, h = w*scale*self.aspectRatioFactor, h*scale if align == CENTER: #we have already done all the calculating. Why not add this? - akedrou x -= (w/2) elif align == RIGHT: x -= w y -= (h/2) tw,th = t.size glEnable(GL_TEXTURE_2D) with cmglPushedMatrix(): if rotate: if not isinstance(rotate, tuple): glRotatef(rotate, 0, 0, 1.0) else: glRotatef(0, *rotate) glTranslatef(x,y,0) t.bind() if self.outline: with cmglPushedAttrib(GL_CURRENT_BIT): glColor4f(0, 0, 0, .25 * glGetDoublev(GL_CURRENT_COLOR)[3]) blur = 2 * DEFAULT_SCALE for offset in [(-.7, -.7), (0, -1), (.7, -.7), (-1, 0), (1, 0), (-.7, .7), (0, 1), (.7, .7)]: with cmglPushedMatrix(): glTranslatef(blur * offset[0], blur * offset[1], 0) drawSquare(w,h,tw,th) if self.shadow: with cmglPushedAttrib(GL_CURRENT_BIT): glColor4f(0, 0, 0, 1) with cmglPushedMatrix(): glTranslatef(shadowoffset[0], shadowoffset[1], 0) drawSquare(w,h,tw,th) drawSquare(w,h,tw,th) glDisable(GL_TEXTURE_2D)
class ImgDrawing: def __init__(self, context, imgPath): self.imgPath = None self.texture = None self.context = context self.cache = None self.transform = ImgTransform() # Load PNG files directly if imgPath.endswith(".png"): self.texture = Texture(imgPath) else: e = "Unsupported Image format." Log.error(e) raise RuntimeError(e) # Make sure we have a valid texture if not self.texture: e = "Unable to load texture for %s." % imgPath Log.error(e) raise RuntimeError(e) def convertToTexture(self, width, height): if self.texture: return e = "Img drawing does not have a valid texture image." Log.error(e) raise RuntimeError(e) def _getEffectiveTransform(self): transform = ImgTransform(self.transform) transform.transform(self.context.transform) return transform def draw(self, color = (1, 1, 1, 1)): glMatrixMode(GL_TEXTURE) glPushMatrix() glMatrixMode(GL_PROJECTION) glPushMatrix() self.context.setProjection() glMatrixMode(GL_MODELVIEW) glPushMatrix() transform = self._getEffectiveTransform() if self.texture: glLoadIdentity() transform.applyGL() glScalef(self.texture.pixelSize[0], self.texture.pixelSize[1], 1) glTranslatef(-.5, -.5, 0) glColor4f(*color) self.texture.bind() glEnable(GL_TEXTURE_2D) glBegin(GL_TRIANGLE_STRIP) glTexCoord2f(0.0, 1.0) glVertex2f(0.0, 1.0) glTexCoord2f(1.0, 1.0) glVertex2f(1.0, 1.0) glTexCoord2f(0.0, 0.0) glVertex2f(0.0, 0.0) glTexCoord2f(1.0, 0.0) glVertex2f(1.0, 0.0) glEnd() glDisable(GL_TEXTURE_2D) glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW)
class SvgDrawing: def __init__(self, context, svgData): self.svgData = None self.texture = None self.context = context self.cache = None self.transform = SvgTransform() # Detect the type of data passed in if type(svgData) == file: self.svgData = svgData.read() elif type(svgData) == str: bitmapFile = svgData.replace(".svg", ".png") # Load PNG files directly if svgData.endswith(".png"): self.texture = Texture(svgData) # Check whether we have a prerendered bitmap version of the SVG file elif svgData.endswith(".svg") and os.path.exists(bitmapFile): Log.debug("Loading cached bitmap '%s' instead of '%s'." % (bitmapFile, svgData)) self.texture = Texture(bitmapFile) else: if not haveAmanith: e = "PyAmanith support is deprecated and you are trying to load an SVG file." Log.error(e) raise RuntimeError(e) Log.debug("Loading SVG file '%s'." % (svgData)) self.svgData = open(svgData).read() # Make sure we have a valid texture if not self.texture: if type(svgData) == str: e = "Unable to load texture for %s." % svgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) def _cacheDrawing(self, drawBoard): self.cache.beginCaching() parser = sax.make_parser() sax.parseString(self.svgData, SvgHandler(drawBoard, self.cache)) self.cache.endCaching() del self.svgData def convertToTexture(self, width, height): if self.texture: return e = "SVG drawing does not have a valid texture image." Log.error(e) raise RuntimeError(e) #try: # self.texture = Texture() # self.texture.bind() # self.texture.prepareRenderTarget(width, height) # self.texture.setAsRenderTarget() # quality = self.context.getRenderingQuality() # self.context.setRenderingQuality(HIGH_QUALITY) # geometry = self.context.geometry # self.context.setProjection((0, 0, width, height)) # glViewport(0, 0, width, height) # self.context.clear() # transform = SvgTransform() # transform.translate(width / 2, height / 2) # self._render(transform) # self.texture.resetDefaultRenderTarget() # self.context.setProjection(geometry) # glViewport(*geometry) # self.context.setRenderingQuality(quality) #except TextureException, e: # Log.warn("Unable to convert SVG drawing to texture: %s" % str(e)) def _getEffectiveTransform(self): transform = SvgTransform(self.transform) transform.transform(self.context.transform) return transform def _render(self, transform): glMatrixMode(GL_TEXTURE) glPushMatrix() glMatrixMode(GL_MODELVIEW) glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT | GL_STENCIL_BUFFER_BIT | GL_TRANSFORM_BIT | GL_COLOR_BUFFER_BIT | GL_POLYGON_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT) if not self.cache: self.cache = SvgCache(self.context.drawBoard) self._cacheDrawing(self.context.drawBoard) self.cache.draw(transform) glPopAttrib() glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_MODELVIEW) def draw(self, color=(1, 1, 1, 1)): glMatrixMode(GL_TEXTURE) glPushMatrix() glMatrixMode(GL_PROJECTION) glPushMatrix() self.context.setProjection() glMatrixMode(GL_MODELVIEW) glPushMatrix() transform = self._getEffectiveTransform() if self.texture: glLoadIdentity() transform.applyGL() glScalef(self.texture.pixelSize[0], self.texture.pixelSize[1], 1) glTranslatef(-.5, -.5, 0) glColor4f(*color) self.texture.bind() glEnable(GL_TEXTURE_2D) glBegin(GL_TRIANGLE_STRIP) glTexCoord2f(0.0, 1.0) glVertex2f(0.0, 1.0) glTexCoord2f(1.0, 1.0) glVertex2f(1.0, 1.0) glTexCoord2f(0.0, 0.0) glVertex2f(0.0, 0.0) glTexCoord2f(1.0, 0.0) glVertex2f(1.0, 0.0) glEnd() glDisable(GL_TEXTURE_2D) else: self._render(transform) glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW)
def __init__(self,half_width,half_height,filename): self.compiler=Compiler() self.background_t = Texture(TEXDIR+filename) self.background_geom=self.compiler.quad(half_width,half_height)
def loadTexture(self, filename): self.texture = Texture(self.renderer, filename).filename
class FontObj(object): def __init__(self, path, text="", size=32, shadow=True): self.font = pygame.font.Font(os.path.join("..", "data", "fonts", path), int(size)) self.texture = Texture() self.cache = Cache() # attributes self.scale = (1.0, 1.0) # image bounds (width, height) self.position = (0, 0) # where in the window it should render self.angle = 0 # angle which the image is drawn self.color = (255, 255, 255, 255) # colour of the image self.rect = (0.0, 0.0, 1.0, 1.0) # left, top, right, bottom, crops the texture self.alignment = 1 # alignment of the text (left, center , right) self.shadow = True # does the font project a shadow self.text = None self.setText(text) # it is not necessary to enter a string upon initialization, # but it is upon time of rendering def getDimensions(self): self.width = self.pixelSize[0] * self.scale[0] self.height = self.pixelSize[1] * self.scale[1] # sets up the vertex and texture array coordinates def createArrays(self): # numpy zeros is used because it can generate an array that can # be used for assigning coordinates to quite quickly self.vtxArray = np.zeros((4, 3), dtype=float32) self.texArray = np.zeros((4, 2), dtype=float32) self.createVerts() self.createTex() self.getDimensions() # set up vertex coordinates def createVerts(self): vtxArray = self.vtxArray # top left, top right, bottom right, bottom left # vertices # by using these numbers pictures are now moved by the center # coordinate instead of the top left. I, personally, find it # easier to use. halfPS = (float(self.pixelSize[0]) / 2.0, float(self.pixelSize[1]) / 2.0) if (self.alignment == "left") or (self.alignment == "right"): vtxArray[0, 0] = 0 vtxArray[0, 1] = halfPS[1] vtxArray[1, 0] = self.pixelSize[0] vtxArray[1, 1] = halfPS[1] vtxArray[2, 0] = self.pixelSize[0] vtxArray[2, 1] = -halfPS[1] vtxArray[3, 0] = 0 vtxArray[3, 1] = -halfPS[1] else: vtxArray[0, 0] = -halfPS[0] vtxArray[0, 1] = halfPS[1] vtxArray[1, 0] = halfPS[0] vtxArray[1, 1] = halfPS[1] vtxArray[2, 0] = halfPS[0] vtxArray[2, 1] = -halfPS[1] vtxArray[3, 0] = -halfPS[0] vtxArray[3, 1] = -halfPS[1] # set up texture coordinates def createTex(self): rect = self.rect # not really necessary, it just saves on some typing # because I got sick of typing "self." all the time texArray = self.texArray # top left, top right, bottom right, bottom left # texture coordinates texArray[0, 0] = rect[0] texArray[0, 1] = rect[3] texArray[1, 0] = rect[2] texArray[1, 1] = rect[3] texArray[2, 0] = rect[2] texArray[2, 1] = rect[1] texArray[3, 0] = rect[0] texArray[3, 1] = rect[1] # changes what the font is supposed to say def setText(self, text): if type(text) == list: text = string.join(text, "") else: # converts any passed value into a string if text == None: text = "" else: text = str(text) self.text = text # checks cache to see if the text had already been set before # if so use that as the texture instead try: self.texture = self.cache.get(self.text) except KeyError: texture = Texture(surface=self.font.render(self.text, True, (255, 255, 255))) self.cache.add(text, texture) self.texture = self.cache.get(self.text) self.pixelSize = self.texture.pixelSize self.setScale(1, 1) # makes sure the surface is resized because # the text is now different self.rect = (0.0, 0.0, 1.0, 1.0) self.createArrays() def setAlignment(self, alignment): alignment = alignment.upper() if alignment == "LEFT": self.alignment = LEFT elif alignment == "RIGHT": self.alignment = RIGHT else: self.alignment = CENTER # changes the position of the image to x, y def setPosition(self, x, y): self.position = (x, y) # moves the image from its current position by x and y def slide(self, x=0, y=0): self.position = (self.position[0] + x, self.position[1] + y) # changes the size of the image and scales the surface def setScale(self, width, height): if self.scale[0] != width and self.scale[1] != height: if (width >= 0 and width <= 1) and (height >= 0 and height <= 1): self.scale = (width, height) else: self.scale = (float(width) / float(self.pixelSize[0]), float(height) / float(self.pixelSize[1])) self.getDimensions() def scaleWidth(self, width, keep_aspect_ratio=True): height = self.scale[1] if keep_aspect_ratio: height = self.scale[1] * (width / self.pixelSize[0]) self.scale = (width / self.pixelSize[0], height) self.getDimensions() def scaleHeight(self, height, keep_aspect_ratio=True): width = self.scale[0] if keep_aspect_ratio: width = self.scale[0] * (height / self.pixelSize[1]) self.setScale(width, height / self.pixelSize[1]) self.getDimensions() # rotates the image to the angle def setAngle(self, angle): self.angle = angle # rotates the image def rotate(self, angle): self.angle += angle # sets the colour of the image (RGBA 0.0 -> 1.0) def setColor(self, color): self.color = list(self.color) for i in range(len(color)): self.color[i] = color[i] # fades from the current color to the new color in the set amount of time # remember that the color must be in RGBA format def fade(self, color, milliseconds): color = [float(c) for c in color] # makes sure the color is an array of floats if list(self.color) != color: self.color = [self.color[i] + (color[i] - self.color[i]) / milliseconds for i in range(len(self.color))] return True return False # finally draws the image to the screen def draw(self): def render(position=self.position, scale=self.scale, angle=self.angle, color=self.color): glPushMatrix() x = position[0] if self.alignment == 0: x += float(self.pixelSize[0]) / 2.0 elif self.alignment == 2: x -= float(self.pixelSize[0]) / 2.0 glTranslatef(x, position[1], -0.1) glScalef(scale[0], -scale[1], 1.0) glRotatef(angle, 0, 0, 1) glColor4f(*color) self.texture.bind() glEnableClientState(GL_TEXTURE_COORD_ARRAY) glEnableClientState(GL_VERTEX_ARRAY) glVertexPointerf(self.vtxArray) glTexCoordPointerf(self.texArray) glDrawArrays(GL_QUADS, 0, self.vtxArray.shape[0]) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glPopMatrix() if self.shadow: render(position=(self.position[0] + 1, self.position[1] - 2), color=(0, 0, 0, self.color[3])) render()
class ImgDrawing: def __init__(self, context, ImgData): self.ImgData = None self.texture = None self.context = context self.cache = None self.transform = SvgTransform() # Detect the type of data passed in if type(ImgData) == file: self.ImgData = ImgData.read() elif type(ImgData) == str: bitmapFile = ImgData.replace(".svg", ".png") # Load PNG files directly if ImgData.endswith(".png"): self.texture = Texture(ImgData) elif ImgData.endswith(".jpg"): self.texture = Texture(ImgData) elif ImgData.endswith(".jpeg"): self.texture = Texture(ImgData) # Check whether we have a prerendered bitmap version of the SVG file elif ImgData.endswith(".svg") and os.path.exists(bitmapFile): Log.debug("Loading cached bitmap '%s' instead of '%s'." % (bitmapFile, ImgData)) self.texture = Texture(bitmapFile) else: if not haveAmanith: e = "PyAmanith support is deprecated and you are trying to load an SVG file." Log.error(e) raise RuntimeError(e) Log.debug("Loading SVG file '%s'." % (ImgData)) self.ImgData = open(ImgData).read() elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in self.texture = Texture() self.texture.loadImage(ImgData) # Make sure we have a valid texture if not self.texture: if type(ImgData) == str: e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) def _cacheDrawing(self, drawBoard): self.cache.beginCaching() parser = sax.make_parser() sax.parseString(self.ImgData, SvgHandler(drawBoard, self.cache)) self.cache.endCaching() del self.ImgData def convertToTexture(self, width, height): if self.texture: return e = "SVG drawing does not have a valid texture image." Log.error(e) raise RuntimeError(e) def _getEffectiveTransform(self): transform = SvgTransform(self.transform) transform.transform(self.context.transform) return transform def width1(self): width = self.texture.pixelSize[0] if not width == None: return width else: return 0 #myfingershurt: def height1(self): height = self.texture.pixelSize[1] if not height == None: return height else: return 0 def widthf(self, pixelw): width = self.texture.pixelSize[0] wfactor = pixelw/width if not width == None: return wfactor else: return 0 def _render(self, transform): glMatrixMode(GL_TEXTURE) glPushMatrix() glMatrixMode(GL_MODELVIEW) glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT | GL_STENCIL_BUFFER_BIT | GL_TRANSFORM_BIT | GL_COLOR_BUFFER_BIT | GL_POLYGON_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT) if not self.cache: self.cache = SvgCache(self.context.drawBoard) self._cacheDrawing(self.context.drawBoard) self.cache.draw(transform) glPopAttrib() glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_MODELVIEW) def draw(self, color = (1, 1, 1, 1), rect = (0,1,0,1), lOffset = 0.0, rOffset = 0.0): glMatrixMode(GL_TEXTURE) glPushMatrix() glMatrixMode(GL_PROJECTION) glPushMatrix() self.context.setProjection() glMatrixMode(GL_MODELVIEW) glPushMatrix() transform = self._getEffectiveTransform() if self.texture: glLoadIdentity() transform.applyGL() glScalef(self.texture.pixelSize[0], self.texture.pixelSize[1], 1) glTranslatef(-.5, -.5, 0) glColor4f(*color) glEnable(GL_TEXTURE_2D) self.texture.bind() triangVtx = array( [[0.0-lOffset, 1.0], [1.0-rOffset, 1.0], [0.0+lOffset, 0.0], [1.0+rOffset, 0.0]], dtype=float32) textriangVtx = array( [[rect[0], rect[3]], [rect[1], rect[3]], [rect[0], rect[2]], [rect[1], rect[2]]], dtype=float32) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glEnableClientState(GL_VERTEX_ARRAY) glTexCoordPointerf(textriangVtx) glVertexPointerf(triangVtx) glDrawArrays(GL_TRIANGLE_STRIP, 0, triangVtx.shape[0]) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(GL_TEXTURE_2D) else: self._render(transform) glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW)