def set_data(self, arr): arr = np.asarray(arr) self.src_format, self.dst_format = fmts_from_shape(arr.shape, self._texture_dim) # Float is default type if arr.dtype == np.uint8: arr = np.ascontiguousarray(arr) self.src_type = gl.GL_UNSIGNED_BYTE elif arr.dtype == np.float32: arr = np.ascontiguousarray(arr) self.src_type = gl.GL_FLOAT else: arr = np.astype(np.float32) self.src_type = gl.GL_FLOAT self._arr = arr if self._id: gl.glDeleteTextures(1, gl.byref(self._id)) id = gl.GLuint() gl.glGenTextures(1, gl.byref(id)) self._id = id gl.glPixelStorei (gl.GL_UNPACK_ALIGNMENT, 1) gl.glPixelStorei (gl.GL_PACK_ALIGNMENT, 1) gl.glBindTexture (self.target, self._id) gl.glTexParameterf (self.target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameterf (self.target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameterf (self.target, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP) gl.glTexParameterf (self.target, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP) self._setup_tex() self.update()
def __init__(self): self.fbo = gl.GLuint(0) self.rendered_texture = gl.GLuint(0) self.depthrenderbuffer = gl.GLuint(0) self.pickingbuffer = gl.GLuint(0) self.vertex_buffer = gl.GLuint(0) self.program = GlProgram(shaders.vertex_copy, shaders.fragment_copy) gl.glGenBuffers(1, pointer(self.vertex_buffer)) data = (gl.GLfloat * 16)(-1, -1, 0, 0, - 1, 1, 0, 1, 1, 1, 1, 1, 1, -1, 1, 0) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(data), data, gl.GL_STATIC_DRAW) gl.glGenFramebuffers(1, pointer(self.fbo)) if not self.fbo: logging.error('failed fbo') gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.fbo) gl.glGenTextures(1, pointer(self.rendered_texture)) if not self.rendered_texture: logging.error('failed rendered_texture') gl.glGenRenderbuffers(1, pointer(self.depthrenderbuffer)) gl.glGenRenderbuffers(1, pointer(self.pickingbuffer)) self.resize(1, 1)
def __init__(self, size: Tuple[int, int], component: int, data): self.width, self.height = size sized_format = (gl.GL_R8, gl.GL_RG8, gl.GL_RGB8, gl.GL_RGBA8)[component - 1] self.format = (gl.GL_R, gl.GL_RG, gl.GL_RGB, gl.GL_RGBA)[component - 1] gl.glActiveTexture(gl.GL_TEXTURE0 + 0) # If we need other texture unit... self.texture_id = texture_id = gl.GLuint() gl.glGenTextures(1, byref(self.texture_id)) if self.texture_id.value == 0: raise ShaderException("Cannot create Texture.") gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_id) gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1) try: gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, sized_format, self.width, self.height, 0, self.format, gl.GL_UNSIGNED_BYTE, data) except gl.GLException: raise gl.GLException( f"Unable to create texture. {gl.GL_MAX_TEXTURE_SIZE} {size}") gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) weakref.finalize(self, Texture.release, texture_id)
def upload(self): """Upload the local atlas data into graphics card memory """ if not self.textureID: self.textureID = gl.GLuint(0) gl.glGenTextures(1, ctypes.byref(self.textureID)) logging.debug("Uploading Texture Font {} to graphics card".format( self.name)) gl.glBindTexture(gl.GL_TEXTURE_2D, self.textureID) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) if self.format == 'alpha': gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_ALPHA, self.width, self.height, 0, gl.GL_ALPHA, gl.GL_UNSIGNED_BYTE, self.data.ctypes) else: gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, self.width, self.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, self.data.ctypes) logging.debug("Upload of Texture Font {} complete".format(self.name)) gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
def texture_from_data(internalformat, size, data_format, data_type, data): '''Create texture from a data buffer (whatever can be passed as pointer to ctypes) internalformat - GL_RGBA8 or GL_RGB8 recommended size - a 1-, 2- or 3-tuple describing the image sizes data_format - see 'format' parameter of glDrawPixels data_type - see 'type' parameter of glDrawPixels data - pointer to memory''' size = list(size) dimensions = len(size) binding = getattr(gl, 'GL_TEXTURE_BINDING_{0:d}D'.format(dimensions)) target = getattr(gl,'GL_TEXTURE_{0:d}D'.format(dimensions)) texImage = getattr(gl,'glTexImage{0:d}D'.format(dimensions)) oldbind = ctypes.c_uint(0) gl.glGetIntegerv(binding, ctypes.cast(ctypes.byref(oldbind), ctypes.POINTER(ctypes.c_int))) texid = ctypes.c_uint(0) gl.glEnable(target) gl.glGenTextures(1, ctypes.byref(texid)) gl.glBindTexture(target, texid) gl.glTexParameteri(target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) args = [target, 0, internalformat] + size + [0, data_format, data_type, data] texImage(*args) gl.glBindTexture(target, oldbind) return texid
def __init__(self, env, sync=True, tps=60, aspect_ratio=None): obs = env.reset() self._image = self.get_image(obs, env) assert len(self._image.shape ) == 3 and self._image.shape[2] == 3, 'must be an RGB image' image_height, image_width = self._image.shape[:2] if aspect_ratio is None: aspect_ratio = image_width / image_height # guess a screen size that doesn't distort the image too much but also is not tiny or huge display = pyglet.canvas.get_display() screen = display.get_default_screen() max_win_width = screen.width * 0.9 max_win_height = screen.height * 0.9 win_width = image_width win_height = int(win_width / aspect_ratio) while win_width > max_win_width or win_height > max_win_height: win_width //= 2 win_height //= 2 while win_width < max_win_width / 2 and win_height < max_win_height / 2: win_width *= 2 win_height *= 2 win = pyglet.window.Window(width=win_width, height=win_height) self._key_handler = pyglet.window.key.KeyStateHandler() win.push_handlers(self._key_handler) win.on_close = self._on_close gl.glEnable(gl.GL_TEXTURE_2D) self._texture_id = gl.GLuint(0) gl.glGenTextures(1, ctypes.byref(self._texture_id)) gl.glBindTexture(gl.GL_TEXTURE_2D, self._texture_id) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA8, image_width, image_height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, None) self._env = env self._win = win # self._render_human = render_human self._key_previous_states = {} self._steps = 0 self._episode_steps = 0 self._episode_returns = 0 self._prev_episode_returns = 0 self._tps = tps self._sync = sync self._current_time = 0 self._sim_time = 0 self._max_sim_frames_per_update = 4
def setup_framebuffer(): gl.glGenFramebuffers(1, ctypes.byref(framebuffer)) gl.glGenTextures(1, ctypes.byref(input_texture)) gl.glGenTextures(1, ctypes.byref(rendered_texture)) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, framebuffer) # Set up the input texture gl.glBindTexture(gl.GL_TEXTURE_3D, input_texture) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_WRAP_R, gl.GL_CLAMP_TO_EDGE) # Set up the render target texture gl.glBindTexture(gl.GL_TEXTURE_3D, rendered_texture) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST)
def upload(self): ''' Upload atlas data into video memory. ''' glEnable( GL_TEXTURE_2D ) if self.texid is None: self.texid = GLuint(0) glGenTextures(1,ctypes.byref(self.texid)) glBindTexture( GL_TEXTURE_2D, self.texid ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ) if self.depth == 1: glTexImage2D( GL_TEXTURE_2D, 0, GL_ALPHA, self.width, self.height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, self.data.ctypes ) elif self.depth == 3: glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, self.width, self.height, 0, GL_RGB, GL_UNSIGNED_BYTE, self.data.ctypes ) else: glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, self.width, self.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, self.data.ctypes ) glBindTexture( GL_TEXTURE_2D, 0 )
def build_buffer(): buffer = gl.GLuint(0) gl.glGenFramebuffers(1, ctypes.byref(buffer)) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, buffer) texture = gl.GLuint(0) gl.glGenTextures(1, ctypes.byref(texture)) gl.glEnable(gl.GL_TEXTURE_2D) gl.glBindTexture(gl.GL_TEXTURE_2D, texture) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, BUF_WIDTH, BUF_HEIGHT, 0, gl.GL_RGBA, gl.GL_FLOAT, None) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, texture, 0) if (gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) != gl.GL_FRAMEBUFFER_COMPLETE): raise RuntimeError('Framebuffer incomplete !') gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) gl.glDisable(gl.GL_TEXTURE_2D) return buffer, texture
def upload(self): ''' Upload atlas data into video memory. ''' glEnable(GL_TEXTURE_2D) if self.texid is None: self.texid = GLuint(0) glGenTextures(1, ctypes.byref(self.texid)) glBindTexture(GL_TEXTURE_2D, self.texid) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) if self.depth == 1: glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, self.width, self.height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, self.data.ctypes) elif self.depth == 3: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, self.width, self.height, 0, GL_RGB, GL_UNSIGNED_BYTE, self.data.ctypes) else: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.width, self.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, self.data.ctypes) glBindTexture(GL_TEXTURE_2D, 0)
def create_image_texture(imgfile): """Create a 2D texture from an image file. """ image = pyglet.image.load(imgfile) data = image.get_data("RGBA", image.width * 4) tex = gl.GLuint() gl.glGenTextures(1, ct.pointer(tex)) gl.glBindTexture(gl.GL_TEXTURE_2D, tex) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, image.width, image.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data, ) gl.glBindTexture(tex, 0) return tex
def setupFBOandTextures(self): self.framebufferA0 = (gl.GLuint * args["resolution"])() self.A0_tex = gl.GLuint(0) self.draw_buffersA0 = (gl.GLenum * args["resolution"])( gl.GL_COLOR_ATTACHMENT0) gl.glGenFramebuffers(args["resolution"], self.framebufferA0) gl.glGenTextures(1, ctypes.byref(self.A0_tex)) #create textures #A gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_3D, self.A0_tex) gl.glTexImage3D(gl.GL_TEXTURE_3D, 0, gl.GL_RED, args["resolution"], args["resolution"], args["resolution"], 0, gl.GL_RED, gl.GL_FLOAT, 0) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) #A for i in range(args["resolution"]): gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferA0[i]) gl.glFramebufferTexture3D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_3D, self.A0_tex, 0, i) assert (gl.glCheckFramebufferStatus( gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE)
def data(self, buffer_type, data, offset): if buffer_type != "texture": gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[buffer_type]) if buffer_type == "color": offset *= 16 else: offset *= 12 gl_data = to_gl_float(data) length = len(data) * 4 gl.glBufferSubData(gl.GL_ARRAY_BUFFER, offset, length, gl_data) if buffer_type == "vertex": self.vertex_count += int(len(data) / 3) else: self.buffers["texture"] = gl.GLuint(0) gl.glGenTextures(1, self.buffers["texture"]) gl.glBindTexture(data.target, data.id) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, texture.width, texture.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, texture_data)
def buffer_texture(width, height): id_ = gl.GLuint() gl.glGenTextures(1, byref(id_)) gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_TEXTURE_BIT) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glEnable(gl.GL_TEXTURE_2D) gl.glBindTexture(gl.GL_TEXTURE_2D, id_) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, (gl.GLubyte * (width*height * 4))(), ) gl.glFlush() gl.glBindTexture(gl.GL_TEXTURE_2D, 0) gl.glPopAttrib() return id_
def __init__(self, width, height, window, num_color_attachments=1, mapping_mode=None, provide_depth=False, provide_stencil=False): """"Create an arbitrary layer framebuffer, I'll add stencil and depthbuffers if I ever package this for resuse, in pyweek, those args are pretty much placeholders""" if mapping_mode is None: mapping_mode = gl.GL_NEAREST assert not provide_stencil, 'stencil buffer not implemented' assert not provide_depth, 'depth buffer not implemented' self.window = window self.width = width self.height = height self.bufferId = gl.GLuint(0) self.textureIds = [] self.buffer_args = [] #create the vram objects? gl.glGenFramebuffers(1, rf(self.bufferId)) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.bufferId) for bufferIndex in range(num_color_attachments): newTex = gl.GLuint(0) gl.glGenTextures(1, rf(newTex)) self.textureIds.append(newTex) gl.glBindTexture(gl.GL_TEXTURE_2D, newTex) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, width, height, 0, gl.GL_RGB, gl.GL_UNSIGNED_INT, 0) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, mapping_mode) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, mapping_mode) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0 + bufferIndex, gl.GL_TEXTURE_2D, newTex, 0) self.buffer_args.append(gl.GL_COLOR_ATTACHMENT0 + bufferIndex) #assign one of the vram objects to the framebuffer cache? if provide_depth: self.buffer_args.append(gl.GL_DEPTH_ATTACHMENT) if provide_stencil: self.buffer_args.append(gl.GL_STENCIL_ATTACHMENT) self.buffers_provided = (gl.GLenum * len(self.buffer_args))(*self.buffer_args) gl.glDrawBuffers(len(self.buffer_args), self.buffers_provided) self.textures = [ Texture(self.width, self.height, gl.GL_TEXTURE_2D, texId.value) for texId in self.textureIds ] assert gl.glCheckFramebufferStatus( gl.GL_FRAMEBUFFER ) == gl.GL_FRAMEBUFFER_COMPLETE, "I don't know why this happened, but at least I can find out"
def _updateFrameTexture(self): if self._nextFrameT is None: # movie has no current position, need to reset the clock # to zero in order to have the timing logic work # otherwise the video stream would skip frames until the # time since creating the movie object has passed self._videoClock.reset() self._nextFrameT = 0 #only advance if next frame (half of next retrace rate) if self._nextFrameT > self.duration: self._onEos() elif (self._numpyFrame is not None) and \ (self._nextFrameT > (self._videoClock.getTime()-self._retraceInterval/2.0)): return None self._numpyFrame = self._mov.get_frame(self._nextFrameT) useSubTex=self.useTexSubImage2D if self._texID is None: self._texID = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self._texID)) useSubTex=False #bind the texture in openGL GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID)#bind that name to the target GL.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_WRAP_S,GL.GL_REPEAT) #makes the texture map wrap (this is actually default anyway) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) # data from PIL/numpy is packed, but default for GL is 4 bytes #important if using bits++ because GL_LINEAR #sometimes extrapolates to pixel vals outside range if self.interpolate: GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR) if useSubTex is False: GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB8, self._numpyFrame.shape[1],self._numpyFrame.shape[0], 0, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) else: GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, self._numpyFrame.shape[1], self._numpyFrame.shape[0], GL.GL_RGB, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) else: GL.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_MAG_FILTER,GL.GL_NEAREST) GL.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_MIN_FILTER,GL.GL_NEAREST) if useSubTex is False: GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB8, self._numpyFrame.shape[1],self._numpyFrame.shape[0], 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) else: GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, self._numpyFrame.shape[1], self._numpyFrame.shape[0], GL.GL_BGR, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) GL.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE)#?? do we need this - think not! if not self.status==PAUSED: self._nextFrameT += self._frameInterval
def create(cls, width, height, target=gl.GL_TEXTURE_2D, internalformat=gl.GL_RGBA, min_filter=None, mag_filter=None): """Create a Texture Create a Texture with the specified dimentions, target and format. On return, the texture will be bound. :Parameters: `width` : int Width of texture in pixels. `height` : int Height of texture in pixels. `target` : int GL constant giving texture target to use, typically ``GL_TEXTURE_2D``. `internalformat` : int GL constant giving internal format of texture; for example, ``GL_RGBA``. If ``None``, the texture will be created but not initialized. `min_filter` : int The minifaction filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST`` `mag_filter` : int The magnification filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST`` :rtype: :py:class:`~pyglet.image.Texture` """ min_filter = min_filter or cls.default_min_filter mag_filter = mag_filter or cls.default_mag_filter tex_id = gl.GLuint() gl.glGenTextures(1, byref(tex_id)) gl.glBindTexture(target, tex_id.value) if target != gl.GL_TEXTURE_2D_MULTISAMPLE: gl.glTexParameteri(target, gl.GL_TEXTURE_MIN_FILTER, min_filter) gl.glTexParameteri(target, gl.GL_TEXTURE_MAG_FILTER, mag_filter) if internalformat is not None: blank = (gl.GLubyte * (width * height * 4))() gl.glTexImage2D(target, 0, internalformat, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, blank) gl.glFlush() texture = cls(width, height, target, tex_id.value) texture.min_filter = min_filter texture.mag_filter = mag_filter if target is gl.GL_TEXTURE_RECTANGLE: texture.tex_coords = (0, 0, 0, width, 0, 0, width, height, 0, 0, height, 0) else: texture.tex_coords = cls.tex_coords return texture
def __init__(self, image, f, t): self.image = image self.format = f self.type = t self.uploaded = False self.handle = GLuint() glGenTextures(1, self.handle) glBindTexture(GL_TEXTURE_2D, self.handle) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
def createFramebuffer(width, height): """Function for setting up additional buffer""" # create a new framebuffer fboId = GL.GLuint() GL.glGenFramebuffers(1, ctypes.byref(fboId)) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, fboId) # create a texture to render to, required for warping texId = GL.GLuint() GL.glGenTextures(1, ctypes.byref(texId)) GL.glBindTexture(GL.GL_TEXTURE_2D, texId) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA32F_ARB, int(width), int(height), 0, GL.GL_RGBA, GL.GL_FLOAT, None) GL.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, texId, 0) # create a render buffer rbId = GL.GLuint() GL.glGenRenderbuffers(1, ctypes.byref(rbId)) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, rbId) GL.glRenderbufferStorage( GL.GL_RENDERBUFFER, GL.GL_DEPTH24_STENCIL8, int(width), int(height)) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, rbId) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, rbId) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, 0) # clear the buffer GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glClear(GL.GL_STENCIL_BUFFER_BIT) GL.glClear(GL.GL_DEPTH_BUFFER_BIT) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0) return fboId, texId, rbId
def __init__(self, width, height): self.id = gl.GLuint(0) gl.glGenTextures(1, ctypes.byref(self.id)) self.bind() gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_FLOAT, None) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) self.unbind()
def create_cubemap_texture(imgfiles): """Create a cubemap texture from image files. :param imgfiles: a list of six strings specifying the path to the cubemap images. In the order [pos+X, pos-X, pos+Y, ..., pos-Z] """ if len(imgfiles) != 6: raise ValueError( "exactly six images are required for a cubemap texture") # generate a new texture cubemap = gl.GLuint() gl.glGenTextures(1, ct.pointer(cubemap)) # bind it to `GL_TEXTURE_CUBE_MAP` and set the filter and wrap mode gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, cubemap) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_R, gl.GL_CLAMP_TO_EDGE) # it seems we need to flip the images to make the cubemap look correct faces = [ImageOps.flip(Image.open(img)) for img in imgfiles] # set the faces of the cubemap texture for i, face in enumerate(faces): width, height = face.size try: data = face.tobytes("raw", "RGBX", 0, -1) except TypeError: data = face.tobytes("raw", "RGBA", 0, -1) gl.glTexImage2D( gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data, ) gl.glGenerateMipmap(gl.GL_TEXTURE_CUBE_MAP) gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, 0) return cubemap
def create_cubemap_texture(imgfiles): """Create a cubemap texture from image files. """ if len(imgfiles) != 6: raise ValueError( "exactly six images are required for a cubemap texture") # generate a new texture cubemap = gl.GLuint() gl.glGenTextures(1, ct.pointer(cubemap)) # bind it to `GL_TEXTURE_CUBE_MAP` and set the filter and wrap mode gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, cubemap) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_R, gl.GL_CLAMP_TO_EDGE) faces = [Image.open(img) for img in imgfiles] # set the faces of the cubemap texture for i, face in enumerate(faces): width, height = face.size try: data = face.tobytes("raw", "RGBX", 0, -1) except TypeError: data = face.tobytes("raw", "RGBA", 0, -1) gl.glTexImage2D( gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data, ) gl.glGenerateMipmap(gl.GL_TEXTURE_CUBE_MAP) gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, 0) return cubemap
def make_texture(filename, indexed=False): name = gl.GLuint(0) gl.glGenTextures(1, pointer(name)) gl.glBindTexture(gl.GL_TEXTURE_2D, name) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) image = PIL.Image.open(filename) if indexed: assert image.mode == 'P' else: image = image.convert('RGBA') logging.debug('loading {} mode={}'.format(filename, image.mode)) width, height = image.size if indexed: assert len(image.tobytes()) == width * height gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, # level gl.GL_R8, width, height, 0, gl.GL_RED, gl.GL_UNSIGNED_BYTE, ctypes.create_string_buffer(image.tobytes())) else: assert len(image.tobytes()) == width * height * 4 gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, # level gl.GL_RGBA8, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, ctypes.create_string_buffer(image.tobytes())) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) return name
def setup_framebuffer(): gl.glGenFramebuffers(1, ctypes.byref(framebuffer)) gl.glGenTextures(1, ctypes.byref(rendered_texture)) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, framebuffer) # Set up the texture as the target for color output gl.glBindTexture(gl.GL_TEXTURE_2D, rendered_texture) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, FB_WIDTH, FB_HEIGHT, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, 0) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, rendered_texture, 0) draw_buffers = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0) gl.glDrawBuffers(1, draw_buffers) assert gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE
def __init__(self, texture_width, texture_height, max_textures): self.texture_width = texture_width self.texture_height = texture_height self.max_textures = max_textures self.textures = [] # an array to keep track of the textures we've already added self.texture_array = gl.GLuint(0) # create our texture array gl.glGenTextures(1, self.texture_array) gl.glBindTexture(gl.GL_TEXTURE_2D_ARRAY, self.texture_array) gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) # disable texture filtering for magnification (return the texel that's nearest to the fragment's texture coordinate) gl.glTexImage3D( # set the dimensions of our texture array gl.GL_TEXTURE_2D_ARRAY, 0, gl.GL_RGBA, self.texture_width, self.texture_height, self.max_textures, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, None)
def init_gl(self): '''initialize the opengl resources needed for presenting windows * a shader program * a vertex buffer * a texture for Label windows ''' self.program = GlProgram(shaders.vertex_flat, shaders.fragment_flat) self.buffer = gl.GLuint(0) gl.glGenBuffers(1, pointer(self.buffer)) self.texture = gl.GLuint(0) gl.glGenTextures(1, pointer(self.texture)) gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
def __init__(self, texture_width, texture_height, max_textures): self.texture_width = texture_width self.texture_height = texture_height self.max_textures = max_textures self.textures = [] self.texture_array = gl.GLuint(0) gl.glGenTextures(1, self.texture_array) gl.glBindTexture(gl.GL_TEXTURE_2D_ARRAY, self.texture_array) gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MIN_FILTER, options.MIPMAP_TYPE) gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexImage3D( gl.GL_TEXTURE_2D_ARRAY, 0, gl.GL_RGBA, self.texture_width, self.texture_height, self.max_textures, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, None)
def build_kernel(size=256): # From GPU Gems # Chapter 24. High-Quality Filtering # Kevin Bjorke, NVIDIA # http://http.developer.nvidia.com/GPUGems/gpugems_ch24.html # # Mitchell Netravali Reconstruction Filter # a = 1.0, b = 0.0 - cubic B-spline # B = 1/3, b = 1/3 - recommended # a = 0.5, b = 0.0 - Catmull-Rom spline def MitchellNetravali(x, a=1, b=0): x = math.fabs(x) if x < 1.0: return ((12-9*a-6*b) *x*x*x + (-18+12*a+6*b)*x*x + (6-2*a))/6.0 elif x < 2.0: return ((-a-6*b)*x*x*x + (6*a+30*b)*x*x + (-12*a-48*b)*x + (8*a+24*b))/6.0 else: return 0 data = (gl.GLfloat*(4*size))() for i in range(size): x = i/float(size-1) data[i*4+0] = MitchellNetravali(x+1) data[i*4+1] = MitchellNetravali(x) data[i*4+2] = MitchellNetravali(1-x) data[i*4+3] = MitchellNetravali(2-x) texid = gl.GLuint() gl.glGenTextures(1, ctypes.byref(texid)) kernel = texid.value gl.glPixelStorei (gl.GL_UNPACK_ALIGNMENT, 1) gl.glPixelStorei (gl.GL_PACK_ALIGNMENT, 1) gl.glBindTexture (gl.GL_TEXTURE_1D, texid) gl.glTexParameterf (gl.GL_TEXTURE_1D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameterf (gl.GL_TEXTURE_1D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameterf (gl.GL_TEXTURE_1D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP) gl.glTexParameterf (gl.GL_TEXTURE_1D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP) gl.glTexImage1D (gl.GL_TEXTURE_1D, 0, gl.GL_RGBA16, size, 0, gl.GL_RGBA, gl.GL_FLOAT, data) return kernel
def __init__(self, images, format=None): assert len(images) == 6 refimg = pyglet.image.load( images[0] ) # Create a new texture binding for this cubemap self.texture_id = gl.GLuint() gl.glGenTextures(1, ctypes.byref( self.texture_id )) gl.glBindTexture( gl.GL_TEXTURE_CUBE_MAP, self.texture_id ) if format is None: format = { 'RGB': gl.GL_RGB, 'RGBA': gl.GL_RGBA, 'L': gl.GL_LUMINANCE, 'LA': gl.GL_LUMINANCE_ALPHA, 'A': gl.GL_ALPHA, 'BGR': gl.GL_BGR, 'BGRA': gl.GL_BGRA }[ refimg.format ] for param in ( ( gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR ), ( gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR ), ( gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE ), ( gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE ), ( gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_R, gl.GL_CLAMP_TO_EDGE )): gl.glTexParameteri(*param) for (idx, cube) in enumerate(( gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X, gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, gl.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z)): img = pyglet.image.load( images[idx] ) gl.glTexParameteri( gl.GL_TEXTURE_CUBE_MAP, gl.GL_GENERATE_MIPMAP, gl.GL_TRUE ) img.blit_to_texture( cube, 0, 0, 0, 0, format ) self.texture_group_a = ReflectionMapTextureGroup(self.texture_id) self.texture_group_b = GenCoordTextureGroup( parent=self.texture_group_a)
def _setup(self): self.name = gl.GLuint() gl.glCreateFramebuffers(1, byref(self.name)) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.name) self.cubemap_texture = gl.GLuint() gl.glGenTextures(gl.GL_TEXTURE_CUBE_MAP, byref(self.name)) gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, self.cubemap_texture) w, h = self.size # initialize the texture (IMPORTANT!!!) for i in range(6): gl.glTexImage2D(gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.GL_DEPTH_COMPONENT, w, h, 0, gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT, 0) gl.glFramebufferTexture2D(gl.GL_DRAW_FRAMEBUFFER, gl.GL_DEPTH_ATTACHMENT, gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X, self.cubemap_texture, 0) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_BASE_LEVEL, 0) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MAX_LEVEL, 0) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_R, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_DEPTH_TEXTURE_MODE, gl.GL_LUMINANCE) gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, 0) status = gl.glCheckFramebufferStatus(gl.GL_DRAW_FRAMEBUFFER) assert status == gl.GL_FRAMEBUFFER_COMPLETE, f"Could not setup framebuffer! {status}"
def make_texture(filename, indexed=False): name = gl.GLuint(0) gl.glGenTextures(1, pointer(name)) gl.glBindTexture(gl.GL_TEXTURE_2D, name) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) image = PIL.Image.open(filename) if indexed: assert image.mode == 'P' else: image = image.convert('RGBA') logging.debug('loading {} mode={}'.format(filename, image.mode)) width, height = image.size if indexed: assert len(image.tobytes()) == width * height gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, # level gl.GL_R8, width, height, 0, gl.GL_RED, gl.GL_UNSIGNED_BYTE, ctypes.create_string_buffer(image.tobytes())) else: assert len(image.tobytes()) == width * height * 4 gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, # level gl.GL_RGBA8, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, ctypes.create_string_buffer(image.tobytes())) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) return name
def refresh_font_texture(self): # save texture state last_texture = gl.GLint() gl.glGetIntegerv(gl.GL_TEXTURE_BINDING_2D, byref(last_texture)) width, height, pixels = self.io.fonts.get_tex_data_as_rgba32() if self._font_texture is not None: gl.glDeleteTextures(1, self._font_texture) self._font_texture = gl.GLuint() gl.glGenTextures(1, byref(self._font_texture)) gl.glBindTexture(gl.GL_TEXTURE_2D, self._font_texture) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, pixels) self.io.fonts.texture_id = self._font_texture gl.glBindTexture(gl.GL_TEXTURE_2D, cast((c_int*1)(last_texture), POINTER(c_uint)).contents) self.io.fonts.clear_tex_data()
def _create_texture(textureID=None, texture_size=None): # create a texture for Rendering Color if textureID is not None: rgb_texture = textureID else: rgb_texture = (c_uint * 1)() ; gl.glGenTextures(1, rgb_texture) rgb_texture = rgb_texture[0] width, height = texture_size gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, rgb_texture) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, None) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) return rgb_texture
def create_point_texture(size, feather=0): """Create and load a circular grayscale image centered in a square texture with a width and height of size. The radius of the circle is size / 2. Since size is used as the texture width and height, it should typically be a power of two. Feather determines the softness of the edge of the circle. The default, zero, creates a hard edged circle. Larger feather values create softer edges for blending. The point at the center of the texture is always white. Return the OpenGL texture name (id) for the resulting texture. This value can be passed directy to a texturizer or glBindTexture """ from pyglet import gl assert feather >= 0, 'Expected feather value >= 0' coords = range(size) texel = (gl.GLfloat * size**2)() r = size / 2.0 c = feather + 1.0 for y in coords: col = y * size for x in coords: d = math.sqrt((x - r)**2 + (y - r)**2) if d < r and (1.0 - 1.0 / (d / r - 1.0)) < 100: texel[x + col] = c**2 / c**(1.0 - 1.0 / (d / r - 1.0)) else: texel[x + col] = 0 id = gl.GLuint() gl.glGenTextures(1, ctypes.byref(id)) gl.glBindTexture(gl.GL_TEXTURE_2D, id.value) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 4) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_LUMINANCE, size, size, 0, gl.GL_LUMINANCE, gl.GL_FLOAT, ctypes.byref(texel)) gl.glFlush() return id.value
def create_texobject(self, color_table, format=gl.GL_RGB, internalformat=gl.GL_RGB): k = (tuple(color_table), format, internalformat) texobj = self._texobjects.get(k) if texobj: return texobj width = { gl.GL_RGB: 3, gl.GL_RGBA: 4, gl.GL_LUMINANCE: 1, gl.GL_LUMINANCE_ALPHA: 2}[format] texobj = gl.GLuint() gl.glGenTextures( 1, ctypes.byref(texobj) ) gl.glEnable( gl.GL_TEXTURE_1D ) gl.glBindTexture( gl.GL_TEXTURE_1D, texobj ) gl.glTexEnvi( gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_DECAL ) gl.glTexParameteri( gl.GL_TEXTURE_1D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST ) gl.glTexParameteri( gl.GL_TEXTURE_1D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST ) gl.glTexParameteri( gl.GL_TEXTURE_1D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP ) gl.glPixelStorei( gl.GL_UNPACK_ALIGNMENT, 1 ) gl.glTexImage1D( gl.GL_TEXTURE_1D, 0, internalformat, width, 0, format, gl.GL_UNSIGNED_BYTE, color_table ) group = TextureBindGroup(texobj, target=gl.GL_TEXTURE_1D, parent=tex_enable_group_1D(target=gl.GL_TEXTURE_1D)) #group = CellShaderGroup(texobj, color_table, width, # format, internalformat) self._texobjects[k] = texobj self._defaultgroups[texobj.value] = group return texobj
def __init__(self, imagedata, imagedatatype, size): self.size=( float(size[0]),float(size[1]) ) self.texcoords=(0.0,0.0,1.0,1.0) self.padding=(0,0,0,0) self._header_bar=[0,0,None,None] self.width, self.height = size[0], size[1] id = c.c_uint() gl.glGenTextures(1, c.byref(id)) self.id = id.value texture_data = (c.c_ubyte * (self.width * self.height * 4))() for i, u in enumerate(imagedata): texture_data[i]= u gl.glBindTexture(gl.GL_TEXTURE_2D, self.id) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, self.width, self.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, texture_data) gl.glTexParameteri(gl.GL_TEXTURE_2D,gl.GL_TEXTURE_MAG_FILTER,gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D,gl.GL_TEXTURE_MIN_FILTER,gl.GL_LINEAR) gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
def __init__(self): self.__value = None buf = ct.c_uint() gl.glGenTextures(1, ct.byref(buf)) self.__value = buf.value
def setupFBOandTextures(self): self.framebufferA0 = gl.GLuint(0) self.framebufferA1 = gl.GLuint(0) self.framebufferB0 = gl.GLuint(0) self.framebufferB1 = gl.GLuint(0) self.A0_tex = gl.GLuint(0) self.A1_tex = gl.GLuint(0) self.B0_tex = gl.GLuint(0) self.B1_tex = gl.GLuint(0) self.draw_buffersA0 = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0) self.draw_buffersA1 = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0) self.draw_buffersB0 = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0) self.draw_buffersB1 = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0) gl.glGenFramebuffers(1, ctypes.byref(self.framebufferA0)) gl.glGenFramebuffers(1, ctypes.byref(self.framebufferA1)) gl.glGenFramebuffers(1, ctypes.byref(self.framebufferB0)) gl.glGenFramebuffers(1, ctypes.byref(self.framebufferB1)) gl.glGenTextures(1, ctypes.byref(self.A0_tex)) gl.glGenTextures(1, ctypes.byref(self.A1_tex)) gl.glGenTextures(1, ctypes.byref(self.B0_tex)) gl.glGenTextures(1, ctypes.byref(self.B1_tex)) #A gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferA0) gl.glBindTexture(gl.GL_TEXTURE_2D, self.A0_tex) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, self.dimx, self.dimy, 0, gl.GL_RGBA, gl.GL_FLOAT, self.Ap) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, self.A0_tex, 0) gl.glDrawBuffers(1, self.draw_buffersA0) assert gl.glCheckFramebufferStatus( gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferA1) # Set up the texture as the target for color output gl.glBindTexture(gl.GL_TEXTURE_2D, self.A1_tex) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, self.dimx, self.dimy, 0, gl.GL_RGBA, gl.GL_FLOAT, self.Ap) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, self.A1_tex, 0) gl.glDrawBuffers(1, self.draw_buffersA1) assert gl.glCheckFramebufferStatus( gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE #B gl.glActiveTexture(gl.GL_TEXTURE2) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferB0) gl.glBindTexture(gl.GL_TEXTURE_2D, self.B0_tex) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, self.dimx, self.dimy, 0, gl.GL_RGBA, gl.GL_FLOAT, self.Bp) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, self.B0_tex, 0) gl.glDrawBuffers(1, self.draw_buffersB0) assert gl.glCheckFramebufferStatus( gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE gl.glActiveTexture(gl.GL_TEXTURE3) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferB1) # Set up the texture as the target for color output gl.glBindTexture(gl.GL_TEXTURE_2D, self.B1_tex) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, self.dimx, self.dimy, 0, gl.GL_RGBA, gl.GL_FLOAT, self.Bp) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, self.B1_tex, 0) gl.glDrawBuffers(1, self.draw_buffersB1) assert gl.glCheckFramebufferStatus( gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE
def __init__(self, width, height): """Creates a FBO""" self.initialized = False assert self.supported() self.width = width self.height = height self.framebuffer_id = ctypes.c_uint(0) self.depthbuffer_id = ctypes.c_uint(0) self.texture_id = ctypes.c_uint(0) # Frame buffer gl.glGenFramebuffersEXT( 1, # number of buffers created ctypes.byref(self.framebuffer_id), # dest. id ) self.initialized = True with self._bound_context(gl.GL_FRAMEBUFFER_EXT): # Depth buffer gl.glGenRenderbuffersEXT( 1, # no. of buffers created ctypes.byref(self.depthbuffer_id), # dest. id ) gl.glBindRenderbufferEXT( gl.GL_RENDERBUFFER_EXT, # target self.depthbuffer_id, # id ) gl.glRenderbufferStorageEXT( gl.GL_RENDERBUFFER_EXT, # target gl.GL_DEPTH_COMPONENT, # internal format self.width, self.height, # size ) gl.glFramebufferRenderbufferEXT( gl.GL_FRAMEBUFFER_EXT, # target gl.GL_DEPTH_ATTACHMENT_EXT, # attachment point gl.GL_RENDERBUFFER_EXT, # renderbuffer target self.depthbuffer_id, # renderbuffer id ) # Target Texture gl.glGenTextures( 1, # no. of textures ctypes.byref(self.texture_id), # dest. id ) gl.glBindTexture( gl.GL_TEXTURE_2D, # target self.texture_id, # texture id ) # Black magic (props to pyprocessing!) # (nearest works, as well as linear) gl.glTexParameteri( gl.GL_TEXTURE_2D, # target gl.GL_TEXTURE_MAG_FILTER, # property name gl.GL_LINEAR, # value ) gl.glTexParameteri( gl.GL_TEXTURE_2D, # target gl.GL_TEXTURE_MIN_FILTER, # property name gl.GL_LINEAR, # value ) # Attach texture to FBO gl.glTexImage2D( gl.GL_TEXTURE_2D, # target 0, # mipmap level (0=default) gl.GL_RGBA8, # internal format self.width, self.height, # size 0, # border gl.GL_RGBA, # format gl.GL_UNSIGNED_BYTE, # type None, # data ) gl.glFramebufferTexture2DEXT( gl.GL_FRAMEBUFFER_EXT, # target gl.GL_COLOR_ATTACHMENT0_EXT, # attachment point gl.GL_TEXTURE_2D, # texture target self.texture_id, # tex id 0, # mipmap level ) # sanity check status = gl.glCheckFramebufferStatusEXT(gl.GL_FRAMEBUFFER_EXT) assert status == gl.GL_FRAMEBUFFER_COMPLETE_EXT
def load_texture(file_name, x=0, y=0, width=0, height=0, scale=1): """ Load image from disk and create a texture. Args: :filename (str): Name of the file to that holds the texture. Returns: Integer identifier for the new texture. Raises: None >>> import arcade >>> arcade.open_window("Drawing Example", 800, 600) >>> name = "examples/images/meteorGrey_big1.png" >>> texture = load_texture(name, 1, 1, 50, 50) >>> arcade.close_window() """ # See if we already loaded this file, and we can just use a cached version. if file_name in load_texture.texture_cache: return load_texture.texture_cache[file_name] source_image = PIL.Image.open(file_name) source_image_width, source_image_height = source_image.size if x != 0 or y != 0 or width != 0 or height != 0: if x > source_image_width: raise SystemError("Can't load texture starting at an x of {} " "when the image is only {} across." .format(x, source_image_width)) if y > source_image_height: raise SystemError("Can't load texture starting at an y of {} " "when the image is only {} high." .format(y, source_image_height)) if x + width > source_image_width: raise SystemError("Can't load texture ending at an x of {} " "when the image is only {} wide." .format(x + width, source_image_width)) if y + height > source_image_height: raise SystemError("Can't load texture ending at an y of {} " "when the image is only {} high." .format(y + height, source_image_height)) image = source_image.crop((x, y, x + width, y + height)) else: image = source_image # image = _trim_image(image) image_width, image_height = image.size image_bytes = image.convert("RGBA").tobytes("raw", "RGBA", 0, -1) texture = GL.GLuint(0) GL.glGenTextures(1, ctypes.byref(texture)) GL.glBindTexture(GL.GL_TEXTURE_2D, texture) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) # Appveyor work-around appveyor = True if not appveyor: GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_BORDER) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_BORDER) else: GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR) GLU.gluBuild2DMipmaps(GL.GL_TEXTURE_2D, GL.GL_RGBA, image_width, image_height, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, image_bytes) image_width *= scale image_height *= scale result = Texture(texture, image_width, image_height) load_texture.texture_cache[file_name] = result return result
def _updateFrameTexture(self): """Update texture pixel store to contain the present frame. Decoded frame image samples are streamed to the texture buffer. """ if self._nextFrameT is None or self._nextFrameT < 0: # movie has no current position (or invalid position -JK), # need to reset the clock to zero in order to have the # timing logic work otherwise the video stream would skip # frames until the time since creating the movie object has passed self._videoClock.reset() self._nextFrameT = 0.0 # only advance if next frame (half of next retrace rate) if self._nextFrameT > self.duration: self._onEos() elif self._numpyFrame is not None: if self._nextFrameT > (self._videoClock.getTime() - self._retraceInterval / 2.0): return None while self._nextFrameT <= (self._videoClock.getTime() - self._frameInterval * 2): self.nDroppedFrames += 1 if self.nDroppedFrames <= reportNDroppedFrames: logging.warning( "{}: Video catchup needed, advancing self._nextFrameT from" " {} to {}".format(self._videoClock.getTime(), self._nextFrameT, self._nextFrameT + self._frameInterval)) if self.nDroppedFrames == reportNDroppedFrames: logging.warning( "Max reportNDroppedFrames reached, will not log any more dropped frames" ) self._nextFrameT += self._frameInterval try: self._numpyFrame = self._mov.get_frame(self._nextFrameT) except OSError: if self.autoLog: logging.warning( "Frame {} not found, moving one frame and trying again". format(self._nextFrameT), obj=self) self._nextFrameT += self._frameInterval self._updateFrameTexture() useSubTex = self.useTexSubImage2D if self._texID is None: self._texID = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self._texID)) useSubTex = False GL.glActiveTexture(GL.GL_TEXTURE0) # bind that name to the target GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) # bind the texture in openGL GL.glEnable(GL.GL_TEXTURE_2D) # makes the texture map wrap (this is actually default anyway) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP) # data from PIL/numpy is packed, but default for GL is 4 bytes GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) # important if using bits++ because GL_LINEAR # sometimes extrapolates to pixel vals outside range if self.interpolate: GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR) if useSubTex is False: GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB8, self._numpyFrame.shape[1], self._numpyFrame.shape[0], 0, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) else: GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, self._numpyFrame.shape[1], self._numpyFrame.shape[0], GL.GL_RGB, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) else: GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) if useSubTex is False: GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB8, self._numpyFrame.shape[1], self._numpyFrame.shape[0], 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) else: GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, self._numpyFrame.shape[1], self._numpyFrame.shape[0], GL.GL_BGR, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) GL.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE) # ?? do we need this - think not! if self.status == PLAYING: self._nextFrameT += self._frameInterval
def __init__( self, ctx: "Context", size: Tuple[int, int], *, components: int = 4, dtype: str = "f1", data: Any = None, filter: Tuple[gl.GLuint, gl.GLuint] = None, wrap_x: gl.GLuint = None, wrap_y: gl.GLuint = None, target=gl.GL_TEXTURE_2D, depth=False, ): """ A texture can be created with or without initial data. NOTE: Currently does not support multisample textures even thought ``samples`` is exposed. :param Context ctx: The context the object belongs to :param Tuple[int,int] size: The size of the texture :param int components: The number of components (1: R, 2: RG, 3: RGB, 4: RGBA) :param str dtype: The data type of each component: f1, f2, f4 / i1, i2, i4 / u1, u2, u4 :param Any data: The byte data of the texture. bytes or anything supporting the buffer protocol. :param Tuple[gl.GLuint, gl.GLuint] filter: The minification/magnification filter of the texture :param gl.GLuint wrap_x: Wrap mode x :param gl.GLuint wrap_y: Wrap mode y :param int target: The texture type :param bool depth: creates a depth texture if `True` """ self._ctx = ctx self._width, self._height = size self._dtype = dtype self._components = components self._alignment = 1 self._target = target self._samples = 0 self._depth = depth self._compare_func = None # Default filters for float and integer textures # Integer textures should have NEAREST interpolation # by default 3.3 core doesn't really support it consistently. if "f" in self._dtype: self._filter = gl.GL_LINEAR, gl.GL_LINEAR else: self._filter = gl.GL_NEAREST, gl.GL_NEAREST self._wrap_x = gl.GL_REPEAT self._wrap_y = gl.GL_REPEAT if self._components not in [1, 2, 3, 4]: raise ValueError("Components must be 1, 2, 3 or 4") gl.glActiveTexture( gl.GL_TEXTURE0) # Create textures in the default channel (0) self._glo = glo = gl.GLuint() gl.glGenTextures(1, byref(self._glo)) if self._glo.value == 0: raise RuntimeError( "Cannot create Texture. OpenGL failed to generate a texture id" ) gl.glBindTexture(self._target, self._glo) if data is not None: byte_length, data = data_to_ctypes(data) if self._target == gl.GL_TEXTURE_2D: self._texture_2d(data) else: raise ValueError("Unsupported texture target") self.filter = filter or self._filter self.wrap_x = wrap_x or self._wrap_x self.wrap_y = wrap_y or self._wrap_y self.ctx.stats.incr("texture") weakref.finalize(self, Texture.release, self._ctx, glo)
def load_textures(file_name, image_location_list, mirrored=False, flipped=False): """ Load a set of textures off of a single image file. Args: :file_name: Name of the file. :image_location_list: List of image locations. Each location should be a list of four numbers. ``[x, y, width, height]``. :mirrored=False: If set to true, the image is mirrored left to right. :flipped=False: If set to true, the image is flipped upside down. Returns: :list: List of textures loaded. Raises: :SystemError: >>> import arcade >>> arcade.open_window("Drawing Example", 800, 600) >>> image_location_list = [[591, 5, 64, 93], ... [655, 10, 75, 88], ... [730, 7, 54, 91], ... [784, 3, 59, 95], ... [843, 6, 56, 92]] >>> texture_info_list = arcade.load_textures( \ "examples/images/character_sheet.png", image_location_list) >>> arcade.close_window() """ source_image = PIL.Image.open(file_name) source_image_width, source_image_height = source_image.size texture_info_list = [] for image_location in image_location_list: x, y, width, height = image_location if x > source_image_width: raise SystemError("Can't load texture starting at an x of {} " "when the image is only {} across." .format(x, source_image_width)) if y > source_image_height: raise SystemError("Can't load texture starting at an y of {} " "when the image is only {} high." .format(y, source_image_height)) if x + width > source_image_width: raise SystemError("Can't load texture ending at an x of {} " "when the image is only {} wide." .format(x + width, source_image_width)) if y + height > source_image_height: raise SystemError("Can't load texture ending at an y of {} " "when the image is only {} high." .format(y + height, source_image_height)) image = source_image.crop((x, y, x + width, y + height)) # image = _trim_image(image) if mirrored: image = PIL.ImageOps.mirror(image) if flipped: image = PIL.ImageOps.flip(image) image_width, image_height = image.size image_bytes = image.convert("RGBA").tobytes("raw", "RGBA", 0, -1) texture = GL.GLuint(0) GL.glGenTextures(1, ctypes.byref(texture)) GL.glBindTexture(GL.GL_TEXTURE_2D, texture) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) # Appveyor work-around appveyor = True if not appveyor: GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_BORDER) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_BORDER) else: GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR) GLU.gluBuild2DMipmaps(GL.GL_TEXTURE_2D, GL.GL_RGBA, image_width, image_height, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, image_bytes) texture_info_list.append(Texture(texture, width, height)) return texture_info_list
def __init__(self, font_name, size): FT = freetype2.FT # easier access to constants self.lib = freetype2.get_default_lib() # Load font and check it is monotype face = self.lib.find_face(font_name) face.set_char_size(size=size, resolution=90) if face.face_flags & FT.FACE_FLAG_FIXED_WIDTH == 0: raise 'Font is not monotype' # Determine largest glyph size width, height, ascender, descender = 0, 0, 0, 0 for c in range(32, 128): face.load_char(c, FT.LOAD_RENDER | FT.LOAD_FORCE_AUTOHINT) bitmap = face.glyph.bitmap width = max(width, bitmap.width) ascender = max(ascender, face.glyph.bitmap_top) descender = max(descender, bitmap.rows - face.glyph.bitmap_top) height = ascender + descender # Generate texture data Z = numpy.zeros((height * 6, width * 16), dtype=numpy.ubyte) for j in range(6): for i in range(16): face.load_char(32 + j * 16 + i, FT.LOAD_RENDER | FT.LOAD_FORCE_AUTOHINT) bitmap = face.glyph.bitmap.copy_with_array() x = i * width + face.glyph.bitmap_left y = j * height + ascender - face.glyph.bitmap_top Z[y:y + bitmap.rows, x:x + bitmap.width].flat = bitmap.buffer # Bound texture self.texture_ids = (pyglet.gl.GLuint * 1)() gl.glGenTextures(1, self.texture_ids) self.texture_id = self.texture_ids[0] gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_id) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_ALPHA, Z.shape[1], Z.shape[0], 0, gl.GL_ALPHA, gl.GL_UNSIGNED_BYTE, Z.tostring()) # Generate display lists dx, dy = width / float(Z.shape[1]), height / float(Z.shape[0]) self.base = gl.glGenLists(8 * 16) for i in range(8 * 16): c = chr(i) x = i % 16 y = i // 16 - 2 gl.glNewList(self.base + i, gl.GL_COMPILE) if (c == '\n'): gl.glPopMatrix() gl.glTranslatef(0, -height, 0) gl.glPushMatrix() elif (c == '\t'): gl.glTranslatef(4 * width, 0, 0) elif (i >= 32): gl.glBegin(gl.GL_QUADS) gl.glTexCoord2d((x) * dx, (y + 1) * dy), gl.glVertex2d(0, -height) gl.glTexCoord2d((x) * dx, (y) * dy), gl.glVertex2d(0, 0) gl.glTexCoord2d((x + 1) * dx, (y) * dy), gl.glVertex2d(width, 0) gl.glTexCoord2d((x + 1) * dx, (y + 1) * dy), gl.glVertex2d(width, -height) gl.glEnd() gl.glTranslatef(width, 0, 0) gl.glEndList()
def load_texture(file_name: str, x: float = 0, y: float = 0, width: float = 0, height: float = 0, mirrored: bool = False, flipped: bool = False, scale: float = 1) -> arcade.Texture: """ Load image from disk and create a texture. Args: :filename (str): Name of the file to that holds the texture. :x (float): X position of the crop area of the texture. :y (float): Y position of the crop area of the texture. :width (float): Width of the crop area of the texture. :height (float): Height of the crop area of the texture. :scale (float): Scale factor to apply on the new texture. Returns: The new texture. Raises: None >>> import arcade >>> arcade.open_window(800,600,"Drawing Example") >>> name = "arcade/examples/images/meteorGrey_big1.png" >>> texture1 = load_texture(name, 1, 1, 50, 50) >>> texture2 = load_texture(name, 1, 1, 50, 50) >>> texture = load_texture(name, 200, 1, 50, 50) Traceback (most recent call last): ... ValueError: Can't load texture starting at an x of 200 when the image is only 101 across. >>> texture = load_texture(name, 1, 50, 50, 50) Traceback (most recent call last): ... ValueError: Can't load texture ending at an y of 100 when the image is only 84 high. >>> texture = load_texture(name, 1, 150, 50, 50) Traceback (most recent call last): ... ValueError: Can't load texture starting at an y of 150 when the image is only 84 high. >>> texture = load_texture(name, 0, 0, 400, 50) Traceback (most recent call last): ... ValueError: Can't load texture ending at an x of 400 when the image is only 101 wide. >>> arcade.close_window() """ # See if we already loaded this file, and we can just use a cached version. cache_name = "{}{}{}{}{}{}{}{}".format(file_name, x, y, width, height, scale, flipped, mirrored) if cache_name in load_texture.texture_cache: return load_texture.texture_cache[cache_name] source_image = PIL.Image.open(file_name) source_image_width, source_image_height = source_image.size if x != 0 or y != 0 or width != 0 or height != 0: if x > source_image_width: raise ValueError("Can't load texture starting at an x of {} " "when the image is only {} across.".format( x, source_image_width)) if y > source_image_height: raise ValueError("Can't load texture starting at an y of {} " "when the image is only {} high.".format( y, source_image_height)) if x + width > source_image_width: raise ValueError("Can't load texture ending at an x of {} " "when the image is only {} wide.".format( x + width, source_image_width)) if y + height > source_image_height: raise ValueError("Can't load texture ending at an y of {} " "when the image is only {} high.".format( y + height, source_image_height)) image = source_image.crop((x, y, x + width, y + height)) else: image = source_image # image = _trim_image(image) if mirrored: image = PIL.ImageOps.mirror(image) if flipped: image = PIL.ImageOps.flip(image) image_width, image_height = image.size image_bytes = image.convert("RGBA").tobytes("raw", "RGBA", 0, -1) texture = gl.GLuint(0) gl.glGenTextures(1, ctypes.byref(texture)) gl.glBindTexture(gl.GL_TEXTURE_2D, texture) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) glu.gluBuild2DMipmaps(gl.GL_TEXTURE_2D, gl.GL_RGBA, image_width, image_height, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, image_bytes) image_width *= scale image_height *= scale result = Texture(texture, image_width, image_height) load_texture.texture_cache[cache_name] = result return result
def __init__(self, env, sync=True, tps=60, aspect_ratio=None, display_info=False): self._record_dir = None self._movie_writer = None self._episode = 0 self._display_info = display_info self._seconds_to_display_done_info = 0 obs = env.reset() self._image = self.get_image(obs, env) assert (len(self._image.shape) == 3 and self._image.shape[2] == 3), "must be an RGB image" image_height, image_width = self._image.shape[:2] if aspect_ratio is None: aspect_ratio = image_width / image_height # guess a screen size that doesn't distort the image too much but also is not tiny or huge display = pyglet.canvas.get_display() screen = display.get_default_screen() max_win_width = screen.width * 0.9 max_win_height = screen.height * 0.9 win_width = image_width win_height = int(win_width / aspect_ratio) while win_width > max_win_width or win_height > max_win_height: win_width //= 2 win_height //= 2 while win_width < max_win_width / 2 and win_height < max_win_height / 2: win_width *= 2 win_height *= 2 self._info_width = win_width // 2 if display_info: win_width += self._info_width win = pyglet.window.Window(width=win_width, height=win_height) self._key_handler = pyglet.window.key.KeyStateHandler() win.push_handlers(self._key_handler) win.on_close = self._on_close gl.glEnable(gl.GL_TEXTURE_2D) self._texture_id = gl.GLuint(0) gl.glGenTextures(1, ctypes.byref(self._texture_id)) gl.glBindTexture(gl.GL_TEXTURE_2D, self._texture_id) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, gl.GL_RGBA8, image_width, image_height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, None, ) self._env = env self._win = win self._key_previous_states = {} self._steps = 0 self._episode_steps = 0 self._episode_return = 0 self._prev_episode_return = 0 self._last_info = {} self._tps = tps self._sync = sync self._current_time = 0 self._sim_time = 0 self._max_sim_frames_per_update = 4 self._info_label = pyglet.text.Label( "<label>", font_name="Courier New", font_size=self._win.height // 42, multiline=True, x=self._win.width - self._info_width + 10, y=self._win.height // 2, width=self._info_width, anchor_x="left", anchor_y="center", ) self._done_info_label = pyglet.text.Label( "<label>", font_name="Courier New", font_size=self._win.height // 42, multiline=True, x=self._win.width // 2, y=self._win.height // 2, width=self._info_width, anchor_x="center", anchor_y="center", )