
"PIL image texture."

import PIL.Image

from glitch.texture import Texture

class ImageTexture(Texture):
    "PIL image texture."

    def __init__(self, image):
        (width, height) = image.size

        if image.mode == 'RGBA':
            data = image.tostring("raw", "RGBA", 0, -1)
        elif image.mode == 'RGBX' or image.mode == 'RGB':
            data = image.tostring("raw", "RGBX", 0, -1)
        else:
            raise ValueError

        Texture.__init__(self, width, height, data)

    @classmethod
    def from_file(cls, path):
        return cls(PIL.Image.open(path))

    def set_from_image(self, image):
        (self.width, self.height) = image.size
        self.data = image.tostring("raw", "RGBX", 0, -1)

    def load_file(self, path):
        image = PIL.Image.open(path)
        self.set_from_image(image)

class ImageSequenceTexture(ImageTexture):
    """A sequence of images.

    When rendered, this loads the current image based on the context value
    C{frame}.
    """

    def __init__(self, pattern):
        """pattern should be in the form `image-%06d.jpg' to refer to
        a sequence of images like image-000001.jpg"""
        self.pattern = pattern
        self.version = 1
        self.load_file(pattern % (1)) # XXX avoid forced initialization?

    def upload(self, ctx):
        self.load_file(self.pattern % (ctx['frame']))
        ImageTexture.upload(self, ctx)

    def update(self, ctx):
        self.version = ctx['frame']
        ImageTexture.update(self, ctx)

