Пример #1
0
def main():
    train_directory = '/home/mihai/Proiecte/AAM/Dataset/'
    shape_train_files = []
    texture_train_files = []

    for file_name in os.listdir(train_directory):
        if file_name.endswith(".pts"):
            file_name = os.path.splitext(file_name)[0]
            file_path = os.path.join(train_directory, file_name)
            shape_train_files.append(file_path + '.pts')
            texture_train_files.append(file_path + '.pgm')

    train_shapes = Shape()
    train_shapes.load(shape_train_files)

    aligned_shapes = train_shapes.align()
    mean_shape = Shape.mean(aligned_shapes)
    pca = train_shapes.pca(train_shapes.shapes)

    train_textures = Texture()
    train_textures.load(texture_train_files, train_shapes.shapes, mean_shape)
Пример #2
0
 def load_image_data(self):
     # load and process image
     img = Image.open(self.image_filename)
     img = img.convert('RGBA')
     # flip for openGL
     img = img.transpose(Image.FLIP_TOP_BOTTOM)
     self.image_width, self.image_height = img.size
     # any pixel that is "transparent color" will be made fully transparent
     # any pixel that isn't will be opaque + tinted FG color
     for y in range(self.image_height):
         for x in range(self.image_width):
             # TODO: PIL pixel access shows up in profiler, use numpy array
             # assignment instead
             color = img.getpixel((x, y))
             if color[:3] == self.transparent_color[:3]:
                 # MAYBE-TODO: does keeping non-alpha color improve sampling?
                 img.putpixel((x, y), (color[0], color[1], color[2], 0))
     self.texture = Texture(img.tobytes(), self.image_width,
                            self.image_height)
     # flip image data back and save it for later, eg image conversion
     img = img.transpose(Image.FLIP_TOP_BOTTOM)
     self.image_data = img
Пример #3
0
    def __init__(self, path, prefix):
        # TODO: handle multiple spritesheets
        texture = Texture(path + prefix + "-0.png")

        # Parse the *.csv file
        self.__images = dict()
        with open(path + prefix + ".csv") as file_:
            csvFile = csv.reader(file_)

            for meta in csvFile:
                # Parse each individual element
                # Format: __images[sprite name] = (sheet file, top left corner, size)
                self.__images[meta[0]] = (meta[1], (int(meta[2]),
                                                    int(meta[3])),
                                          (int(meta[4]), int(meta[5])))

            file_.close()

        # Pick a sprite and assume all the other sprites are the same size
        tilew, tileh = self.__images.values()[0][2]

        # Call the parent's constructor
        super(TileSet, self).__init__(texture, tilew, tileh)
Пример #4
0
 def __init__(self, app, src_color_list, log):
     self.init_success = False
     self.app = app
     # generate a unique non-user-facing palette name
     name = 'PaletteFromList_%s' % time.time()
     self.filename = self.name = self.base_filename = name
     colors = []
     for color in src_color_list:
         # assume 1 alpha if not given
         if len(color) == 3:
             colors.append((color[0], color[1], color[2], 255))
         else:
             colors.append(color)
     self.colors = [(0, 0, 0, 0)] + colors
     lightest = 0
     darkest = 255 * 3 + 1
     for color in self.colors:
         luminosity = color[0]*0.21 + color[1]*0.72 + color[2]*0.07
         if luminosity < darkest:
             darkest = luminosity
             self.darkest_index = len(self.colors) - 1
         elif luminosity > lightest:
             lightest = luminosity
             self.lightest_index = len(self.colors) - 1
     # create texture
     img = Image.new('RGBA', (MAX_COLORS, 1), (0, 0, 0, 0))
     x = 0
     for color in self.colors:
         img.putpixel((x, 0), color)
         x += 1
     self.texture = Texture(img.tobytes(), MAX_COLORS, 1)
     if log and not self.app.game_mode:
         self.app.log("generated new palette '%s'" % (self.name))
         self.app.log('  unique colors: %s' % int(len(self.colors)-1))
         self.app.log('  darkest color index: %s' % self.darkest_index)
         self.app.log('  lightest color index: %s' % self.lightest_index)
Пример #5
0
'''
from gl import *
from texture import Texture
from obj import ObjReader
from envmap import Envmap
from sphere import *

if __name__ == '__main__':
    '''Main Program'''

    brick = Material(diffuse=color(0.8, 0.25, 0.25), spec=16)
    stone = Material(diffuse=color(0.4, 0.4, 0.4), spec=32)
    mirror = Material(spec=64, matType=REFLECTIVE)
    glass = Material(spec=64, ior=1.5, matType=TRANSPARENT)

    deskMat = Material(texture=Texture('./TexturesAndMaterials/wood2.bmp'))
    woodMat_4 = Material(texture=Texture('./TexturesAndMaterials/wood4.bmp'))
    woodMat_4_1 = Material(
        texture=Texture('./TexturesAndMaterials/wood4-1.bmp'))

    earthMat = Material(texture=Texture('./TexturesAndMaterials/earthDay.bmp'))
    jupiterMat = Material(
        texture=Texture('./TexturesAndMaterials/2k_jupiter.bmp'))
    moonMat = Material(texture=Texture('./TexturesAndMaterials/2k_moon.bmp'))
    sunMat = Material(texture=Texture('./TexturesAndMaterials/2k_sun.bmp'))

    bookMat = Material(texture=Texture('./TexturesAndMaterials/book1-1.bmp'))
    concretewallMat = Material(
        texture=Texture('./TexturesAndMaterials/concretewall.bmp'))
    bookMat_2 = Material(texture=Texture('./TexturesAndMaterials/book2-1.bmp'))
    bookMat_3 = Material(texture=Texture('./TexturesAndMaterials/book3.bmp'))
Пример #6
0
 def test_init_data_store(self):
     data = np.zeros((10,10), dtype=np.uint8)
     T = Texture(data=data, store=True, copy=False)
     assert T._data is data
Пример #7
0
from gl import *
from texture import Texture
from obj import ObjReader
from envmap import Envmap
from sphere import *

if __name__ == '__main__':
    brick = Material(diffuse=color(0.8, 0.25, 0.25), spec=16)
    stone = Material(diffuse=color(0.4, 0.4, 0.4), spec=32)
    mirror = Material(spec=64, matType=REFLECTIVE)
    glass = Material(spec=64, ior=1.5, matType=TRANSPARENT)

    EscritorioMAt = Material(texture=Texture('./Utils/madera22.bmp'))
    Mantel = Material(texture=Texture('./Utils/mantel.bmp'))
    GoldLampMaterial = Material(texture=Texture('./Utils/lamp.bmp'))

    DiscoBall = Material(texture=Texture('./Utils/discob.bmp'))

    speakers = Material(texture=Texture('./Utils/bass2.bmp'))
    MaterialPared = Material(texture=Texture('./Utils/pared.bmp'))

    width = 1920
    height = 1080
    r = Raytracer(width, height)
    r.glClearColor(0.2, 0.6, 0.8)
    r.glClear()

    r.envmap = Envmap('./Utils/dark.bmp')

    # Lights
    r.pointLights.append(
Пример #8
0
 def load_icon_texture(self, img_filename):
     img = Image.open(img_filename)
     img = img.convert('RGBA')
     img = img.transpose(Image.FLIP_TOP_BOTTOM)
     return Texture(img.tobytes(), *img.size)
Пример #9
0
 def test_invalid_views(self):
     data = np.zeros((10,10), dtype=np.uint8)
     T = Texture(data=data)
     Z = T[5:,5:]
     T.resize((5,5))
     assert Z._valid == False
Пример #10
0
    def renderAnimation(self, animName, clearColor=[150.0/255, 57.0/255, 80.0/255, 1.0], width=800, height=600):
        # TODO this creates an error with me
        #from glmodule import *
        from texture import Texture
        from core import G

        dst = Texture( size = (width, height) )

        # Bind a framebuffer (render-to-texture)
        framebuffer = glGenFramebuffers(1)
        glBindFramebuffer(GL_FRAMEBUFFER, framebuffer)
        glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst.textureId, 0)
        glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst.textureId, 0)

        # Bind the depth buffer
        depthrenderbuffer = glGenRenderbuffers(1)
        glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer)
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height)
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer)

        if clearColor is not None:
            glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3])
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glDepthFunc(GL_LEQUAL)
        glEnable(GL_DEPTH_TEST)

        glViewport(0, 0, width, height)
        self.defineCamera(width, height, not self.kinectCamTggle.selected)

        self.animated.setActiveAnimation(animName)
        anim = self.animated.getAnimation(animName)
        surface = np.empty((height, width, 4), dtype = np.uint8)
        depth_surface = np.empty((height, width, 1), dtype = np.float32)
        depth_surface_16 = np.empty((height, width, 1), dtype = np.uint16)
        
        obj = self.human.mesh.object3d
        oldShading = obj.shadeless
        obj.parent.setShadeless(True)
        #obj.parent.transparentPrimitives = 0
        
        bg = self.backgroundImage.mesh.object3d
        
        for frameIdx in xrange(anim.nFrames):
            self.animated.setToFrame(frameIdx)
            
            bg.draw() # TODO fix how to get this into depth image as well
            obj.draw()

            glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, surface)
            img = Image(data = np.ascontiguousarray(surface[::-1,:,:3]))
            outpath = os.path.join(DATA_PATH, 'rgb_%s_%s.png' % (animName, frameIdx))  # TODO this doesn't indicate the projection matrix, not enough info to differ
            log.message("Saving to " + outpath)
            img.save(outpath)
            
            # http://pyopengl.sourceforge.net/documentation/manual-3.0/glReadPixels.xhtml#param-format
            glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, depth_surface)
            depth_img = Image(data = np.ascontiguousarray(depth_surface[::-1,:,:3]))
            depth_outpath = os.path.join(DATA_PATH, 'd_32f_%s_%s.png' % (animName, frameIdx))  # TODO this doesn't indicate the projection matrix, not enough info to differ
            log.message("Saving to " + depth_outpath)
            depth_img.save(depth_outpath)
            
            # Also save the image as uint8 image
            glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, depth_surface_16)
            #depth_img8 = Image(data = np.ascontiguousarray(depth_surface_8[::-1,:,:3]))
            depth_img_16 = Image(data = np.ascontiguousarray(depth_surface_16[::-1,:,:1]))
            depth_outpath_16 = os.path.join(DATA_PATH, 'd_ui16_%s_%s.png' % (animName, frameIdx))  # TODO this doesn't indicate the projection matrix, not enough info to differ
            log.message("Saving to " + depth_outpath_16)
            depth_img_16.save(depth_outpath_16)
            
            
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        obj.parent.setShadeless(oldShading)

        # Unbind texture
        glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0)
        glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0)
        glBindFramebuffer(GL_FRAMEBUFFER, 0)

        glDeleteFramebuffers(np.array([framebuffer]))

        gui3d.app.mainwin.canvas.resizeGL(G.windowWidth, G.windowHeight)
        # TODO save alpha as depth

        return surface
Пример #11
0
def renderSkin(dst,
               vertsPerPrimitive,
               verts,
               index=None,
               objectMatrix=None,
               texture=None,
               UVs=None,
               textureMatrix=None,
               color=None,
               clearColor=None):

    if isinstance(dst, Texture):
        glBindTexture(GL_TEXTURE_2D, dst.textureId)
    elif isinstance(dst, Image):
        dst = Texture(image=dst)
    elif isinstance(dst, tuple):
        dst = Texture(size=dst)
    else:
        raise RuntimeError('Unsupported destination: %r' % dst)

    width, height = dst.width, dst.height

    framebuffer = glGenFramebuffers(1)
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer)
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                           GL_TEXTURE_2D, dst.textureId, 0)
    glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                           GL_TEXTURE_2D, dst.textureId, 0)

    if clearColor is not None:
        glClearColor(clearColor[0], clearColor[1], clearColor[2],
                     clearColor[3])
        glClear(GL_COLOR_BUFFER_BIT)

    glVertexPointer(verts.shape[-1], GL_FLOAT, 0, verts)

    if texture is not None and UVs is not None:
        if isinstance(texture, Image):
            tex = Texture()
            tex.loadImage(texture)
            texture = tex
        if isinstance(texture, Texture):
            texture = texture.textureId
        glEnable(GL_TEXTURE_2D)
        glEnableClientState(GL_TEXTURE_COORD_ARRAY)
        glBindTexture(GL_TEXTURE_2D, texture)
        glTexCoordPointer(UVs.shape[-1], GL_FLOAT, 0, UVs)

    if color is not None:
        glColorPointer(color.shape[-1], GL_UNSIGNED_BYTE, 0, color)
        glEnableClientState(GL_COLOR_ARRAY)
    else:
        glDisableClientState(GL_COLOR_ARRAY)
        glColor4f(1, 1, 1, 1)

    glDisableClientState(GL_NORMAL_ARRAY)
    glDisable(GL_LIGHTING)

    glDepthMask(GL_FALSE)
    glDisable(GL_DEPTH_TEST)
    # glDisable(GL_CULL_FACE)

    glPushAttrib(GL_VIEWPORT_BIT)
    glViewport(0, 0, width, height)

    glMatrixMode(GL_MODELVIEW)
    glPushMatrix()
    if objectMatrix is not None:
        glLoadTransposeMatrixd(objectMatrix)
    else:
        glLoadIdentity()

    glMatrixMode(GL_PROJECTION)
    glPushMatrix()
    glLoadIdentity()
    glOrtho(0, 1, 0, 1, -100, 100)

    if textureMatrix is not None:
        glMatrixMode(GL_TEXTURE)
        glPushMatrix()
        glLoadTransposeMatrixd(textureMatrix)

    if index is not None:
        glDrawElements(g_primitiveMap[vertsPerPrimitive - 1], index.size,
                       GL_UNSIGNED_INT, index)
    else:
        glDrawArrays(g_primitiveMap[vertsPerPrimitive - 1], 0, verts[:, :,
                                                                     0].size)

    if textureMatrix is not None:
        glMatrixMode(GL_TEXTURE)
        glPopMatrix()

    glMatrixMode(GL_PROJECTION)
    glPopMatrix()

    glMatrixMode(GL_MODELVIEW)
    glPopMatrix()

    glPopAttrib()

    glEnable(GL_DEPTH_TEST)
    glDepthMask(GL_TRUE)

    glEnable(GL_LIGHTING)
    glEnableClientState(GL_NORMAL_ARRAY)

    glEnableClientState(GL_COLOR_ARRAY)

    glDisable(GL_TEXTURE_2D)
    glDisableClientState(GL_TEXTURE_COORD_ARRAY)

    surface = np.empty((height, width, 4), dtype=np.uint8)
    glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, surface)
    surface = Image(data=np.ascontiguousarray(surface[::-1, :, :3]))

    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                           GL_TEXTURE_2D, 0, 0)
    glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                           GL_TEXTURE_2D, 0, 0)
    glBindFramebuffer(GL_FRAMEBUFFER, 0)
    glDeleteFramebuffers(np.array([framebuffer]))

    return surface
Пример #12
0
 def test_resize_bad_shape(self):
     data = np.zeros((10,10), dtype=np.uint8)
     T = Texture(data=data)
     with self.assertRaises(ValueError):
         T.resize((5,5,5))
Пример #13
0
 def test_resize_view(self):
     data = np.zeros((10,10), dtype=np.uint8)
     T = Texture(data=data)
     with self.assertRaises(RuntimeError):
         T[...].resize((5,5))
Пример #14
0
 def test_set_oversized_data(self):
     data = np.zeros((10,10), dtype=np.uint8)
     T = Texture(data=data)
     T.set_data( np.ones((20,20)) )
     assert T.shape == (20,20)
     assert len(T._pending_data) == 1
Пример #15
0
 def test_init_none(self):
     with self.assertRaises(ValueError):
         T = Texture()
Пример #16
0
 def test_set_misshaped_data(self):
     data = np.zeros(10, dtype=np.uint8)
     T = Texture(data=data)
     with self.assertRaises(ValueError):
         T.set_data( np.ones((10,10)))
Пример #17
0
 def test_set_misplaced_data(self):
     data = np.zeros((10,10), dtype=np.uint8)
     T = Texture(data=data)
     with self.assertRaises(ValueError):
         T.set_data( np.ones((5,5)), offset=(8,8) )
Пример #18
0
 def test_init_data_store_copy(self):
     data = np.zeros((10,10), dtype=np.uint8)
     T = Texture(data=data, store=True, copy=True)
     assert T._data is not data
     assert T._data is not None
Пример #19
0
from render import Render
from texture import Texture

ren = Render()
ren.glCreateWindow(600, 800)
# ren.loadObj('./models/bears.obj', 9, 2, 40)

tex = Texture('./models/RmhDktMako.bmp')

## Medium shot
ren.lookAt(
    cameraPos= [-1, 0, 2],
    cameraTarget= [0, 0, 0],
    up= [0, 1, 0]
)
ren.loadObj(
    filename='./models/RmhDktMako.obj',
    translate=[0, 0, 0],
    scale=[0.2, 0.2, 0.2],
    rotate=[0, 0, 0],
    texture=tex,
    light=[0, 0, 1]
)
ren.glFinish('medium')

# ## Dutch angle
# ren.glCreateWindow(600, 800)
# ren.lookAt(
#     cameraPos= [-1, 0, 2],
#     cameraTarget= [0, 0, 0],
#     up= [0, 1, 1]
Пример #20
0
    def generateVideoButton(self):
        # for i in range(len(self.shapes)):
        #     print " "
        #     print self.shapes[i].name
        #     for j in range(len(self.shapes[i].faces)):
        #         print self.shapes[i].faces[j].faceOrientation, " : ", self.shapes[i].faces[j].facePoints
        
        mb = ModelBuilder()
        Models = []
        for i in self.shapes:
            each_model = mb.BuildModel(i)
            # Print out the 3D model's vertex and texel coordinate
            # print "Print out the 3D model's vertex and texel coordinate---------------------------"
            # for j in each_model:
            #     # j is one polygon
            #     print "Vertex is:"
            #     for k in j.Vertex:
            #         print k.x, k.y, k.z
            #     print "Texel is:"
            #     for n in j.Texel:
            #         print n.u, n.v
            Models.append(each_model)
        print "Models list size: ", len(Models)
        img = cv2.imread("project.png",cv2.CV_LOAD_IMAGE_COLOR)
        texture = Texture(img)
        points = []
        
        for i in range(0,len(Models),1):
            
            pointsOfEachModel = []
            if (i<5): # for single model building 4,11,12,13 and ground
                fileIndex = i
                for j in range(len(Models[i])): # j is surfaces of each model
                    pointsOfEachFace = texture.putTexture(Models[i][j])
                    pointsOfEachModel.extend(pointsOfEachFace)
                
            elif i==5: #5-6 compound building 10
                fileIndex = 5
                for j in range(5, 7):
                    for k in range(len(Models[j])): 
                        pointsOfEachFace = texture.putTexture(Models[j][k])
                        pointsOfEachModel.extend(pointsOfEachFace)

            elif i==7: #7-12 compound building 9
                fileIndex = 6
                for j in range(7, 13):
                    for k in range(len(Models[j])): 
                        pointsOfEachFace = texture.putTexture(Models[j][k])
                        pointsOfEachModel.extend(pointsOfEachFace)

            elif (i-13)>=0 and (i-13)%2==0: #compound buildings 1-8
                multiple = (i-13)/2
                fileIndex = 7 + multiple
                for j in range(i, i+2):
                    for k in range(len(Models[j])): 
                        pointsOfEachFace = texture.putTexture(Models[j][k])
                        pointsOfEachModel.extend(pointsOfEachFace)

            else:
                continue

            points = pointsOfEachModel
            fileRGB = open("Models/model_"+str(fileIndex)+".dat", "w+")
            for k in range(len(pointsOfEachModel)):
                point = "{0},{1},{2},{r},{g},{b}\n".format(points[k].x, points[k].y,points[k].z,r=points[k].r, g=points[k].g, b=points[k].b)
                fileRGB.write(point)
            print "Model "+str(fileIndex)+":"+str(k)+" points generated"

        print "----------UI Phase Finished----------"
        print "All models have been generated, please use main.py to generate fraems of video"
Пример #21
0
#      '-;           |      .'
#         \           \    /
#         | 7  .__  _.-\   \
#         | |  |  ``/  /`  /
#        /,_|  |   /,_/   /
#           /,_/      '`-'

from ase.io import read
from ase.data import covalent_radii as cr
from ase.data.colors import jmol_colors as colors_us
import numpy as np
a = read("POSCAR")

zoom = 30
x, y, z = a.get_cell()
Tex = Texture(int(x[0] * zoom), int(y[1] * zoom))

colors = []
for col in colors_us:
    r, g, b = col
    color = (255, int(r * 255), int(g * 255), int(b * 255))
    colors.append(color)

for x, atom in enumerate(a):
    print x
    num = atom.number
    color = colors[num]
    radius = int(cr[num] * zoom)
    x = atom.position[0] * zoom
    y = atom.position[1] * zoom
    depth = -atom.position[2] * zoom
Пример #22
0
def line3d(points, thickness=1, radius=None, arrow_head=False, **kwds):
    r"""
    Draw a 3d line joining a sequence of points.

    One may specify either a thickness or radius. If a thickness is
    specified, this line will have a constant diameter regardless of
    scaling and zooming. If a radius is specified, it will behave as a
    series of cylinders.

    INPUT:


    -  ``points`` - a list of at least 2 points

    -  ``thickness`` - (default: 1)

    -  ``radius`` - (default: None)

    -  ``arrow_head`` - (default: False)

    -  ``color`` - a word that describes a color

    -  ``rgbcolor`` - (r,g,b) with r, g, b between 0 and 1
       that describes a color

    -  ``opacity`` - (default: 1) if less than 1 then is
       transparent


    EXAMPLES:

    A line in 3-space::

        sage: line3d([(1,2,3), (1,0,-2), (3,1,4), (2,1,-2)])

    The same line but red::

        sage: line3d([(1,2,3), (1,0,-2), (3,1,4), (2,1,-2)], color='red')

    The points of the line provided as a numpy array::

        sage: import numpy
        sage: line3d(numpy.array([(1,2,3), (1,0,-2), (3,1,4), (2,1,-2)]))

    A transparent thick green line and a little blue line::

        sage: line3d([(0,0,0), (1,1,1), (1,0,2)], opacity=0.5, radius=0.1, \
                     color='green') + line3d([(0,1,0), (1,0,2)])

    A Dodecahedral complex of 5 tetrahedrons (a more elaborate examples
    from Peter Jipsen)::

        sage: def tetra(col):
        ...       return line3d([(0,0,1), (2*sqrt(2.)/3,0,-1./3), (-sqrt(2.)/3, sqrt(6.)/3,-1./3),\
        ...              (-sqrt(2.)/3,-sqrt(6.)/3,-1./3), (0,0,1), (-sqrt(2.)/3, sqrt(6.)/3,-1./3),\
        ...              (-sqrt(2.)/3,-sqrt(6.)/3,-1./3), (2*sqrt(2.)/3,0,-1./3)],\
        ...              color=col, thickness=10, aspect_ratio=[1,1,1])
        ...
        sage: v  = (sqrt(5.)/2-5/6, 5/6*sqrt(3.)-sqrt(15.)/2, sqrt(5.)/3)
        sage: t  = acos(sqrt(5.)/3)/2
        sage: t1 = tetra('blue').rotateZ(t)
        sage: t2 = tetra('red').rotateZ(t).rotate(v,2*pi/5)
        sage: t3 = tetra('green').rotateZ(t).rotate(v,4*pi/5)
        sage: t4 = tetra('yellow').rotateZ(t).rotate(v,6*pi/5)
        sage: t5 = tetra('orange').rotateZ(t).rotate(v,8*pi/5)
        sage: show(t1+t2+t3+t4+t5, frame=False)

    TESTS:

    Copies are made of the input list, so the input list does not change::

        sage: mypoints = [vector([1,2,3]), vector([4,5,6])]
        sage: type(mypoints[0])
        <type 'sage.modules.vector_integer_dense.Vector_integer_dense'>
        sage: L = line3d(mypoints)
        sage: type(mypoints[0])
        <type 'sage.modules.vector_integer_dense.Vector_integer_dense'>

    The copies are converted to a list, so we can pass in immutable objects too::

        sage: L = line3d(((0,0,0),(1,2,3)))

    This function should work for anything than can be turned into a
    list, such as iterators and such (see ticket #10478)::

        sage: line3d(iter([(0,0,0), (sqrt(3), 2, 4)]))
        sage: line3d((x, x^2, x^3) for x in range(5))
        sage: from itertools import izip; line3d(izip([2,3,5,7], [11, 13, 17, 19], [-1, -2, -3, -4]))
    """
    points = list(points)
    if len(points) < 2:
        raise ValueError, "there must be at least 2 points"
    for i in range(len(points)):
        x, y, z = points[i]
        points[i] = float(x), float(y), float(z)
    if radius is None:
        L = Line(points, thickness=thickness, arrow_head=arrow_head, **kwds)
        L._set_extra_kwds(kwds)
        return L
    else:
        v = []
        if kwds.has_key('texture'):
            kwds = kwds.copy()
            texture = kwds.pop('texture')
        else:
            texture = Texture(kwds)
        for i in range(len(points) - 1):
            line = shapes.arrow3d if i == len(points)-2 and arrow_head else shapes.LineSegment
            v.append(line(points[i], points[i+1], texture=texture, radius=radius, **kwds))
        w = sum(v)
        w._set_extra_kwds(kwds)
        return w
Пример #23
0
'''
from gl import *
from texture import Texture
from obj import ObjReader
from envmap import Envmap
from sphere import *

if __name__ == '__main__':
    '''Main Program'''

    brick = Material(diffuse = color(0.8, 0.25, 0.25 ), spec = 16)
    stone = Material(diffuse = color(0.4, 0.4, 0.4 ), spec = 32)
    mirror = Material(spec = 64, matType = REFLECTIVE)
    glass = Material(spec = 64, ior = 1.5, matType= TRANSPARENT) 

    boxMat = Material(texture = Texture('box.bmp'))

    # earthMat = Material(texture = Texture('earthDay.bmp'))


    width = 512
    height = 512
    r = Raytracer(width,height)
    r.glClearColor(0.2, 0.6, 0.8)
    r.glClear()

    # r.envmap = Envmap('envmap.bmp')

    # Lights
    r.pointLights.append( PointLight(position = V3(-4,4,0), intensity = 0.5))
    # r.dirLight = DirectionalLight(direction = V3(1, -1, -2), intensity = 0.5)
Пример #24
0
 def __init__(self, ui, textureFile):
     super(SimpleScreen, self).__init__(ui)
     self._texture = Texture(textureFile)
Пример #25
0
 def test_resize_unresizeable(self):
     data = np.zeros((10,10), dtype=np.uint8)
     T = Texture(data=data, resizeable=False)
     with self.assertRaises(RuntimeError):
         T.resize((5,5))
Пример #26
0
def plot3d_adaptive(f,
                    x_range,
                    y_range,
                    color="automatic",
                    grad_f=None,
                    max_bend=.5,
                    max_depth=5,
                    initial_depth=4,
                    num_colors=128,
                    **kwds):
    r"""
    Adaptive 3d plotting of a function of two variables.

    This is used internally by the plot3d command when the option
    ``adaptive=True`` is given.

    INPUT:


    -  ``f`` - a symbolic function or a Python function of
       3 variables.

    -  ``x_range`` - x range of values: 2-tuple (xmin,
       xmax) or 3-tuple (x,xmin,xmax)

    -  ``y_range`` - y range of values: 2-tuple (ymin,
       ymax) or 3-tuple (y,ymin,ymax)

    -  ``grad_f`` - gradient of f as a Python function

    -  ``color`` - "automatic" - a rainbow of num_colors
       colors

    -  ``num_colors`` - (default: 128) number of colors to
       use with default color

    -  ``max_bend`` - (default: 0.5)

    -  ``max_depth`` - (default: 5)

    -  ``initial_depth`` - (default: 4)

    -  ``**kwds`` - standard graphics parameters


    EXAMPLES:

    We plot `\sin(xy)`::

        sage: from sage.plot.plot3d.plot3d import plot3d_adaptive
        sage: x,y=var('x,y'); plot3d_adaptive(sin(x*y), (x,-pi,pi), (y,-pi,pi), initial_depth=5)
        Graphics3d Object
    """
    if initial_depth >= max_depth:
        max_depth = initial_depth

    from sage.plot.misc import setup_for_eval_on_grid
    g, ranges = setup_for_eval_on_grid(f, [x_range, y_range], plot_points=2)
    xmin, xmax = ranges[0][:2]
    ymin, ymax = ranges[1][:2]

    opacity = kwds.get('opacity', 1)

    if color == "automatic":
        texture = rainbow(num_colors, 'rgbtuple')
    else:
        if isinstance(color, list):
            texture = color
        else:
            kwds['color'] = color
            texture = Texture(kwds)

    factory = TrivialTriangleFactory()
    plot = TrianglePlot(factory,
                        g, (xmin, xmax), (ymin, ymax),
                        g=grad_f,
                        min_depth=initial_depth,
                        max_depth=max_depth,
                        max_bend=max_bend,
                        num_colors=None)

    P = IndexFaceSet(plot._objects)
    if isinstance(texture, (list, tuple)):
        if len(texture) == 2:
            # do a grid coloring
            xticks = (xmax - xmin) / 2**initial_depth
            yticks = (ymax - ymin) / 2**initial_depth
            parts = P.partition(lambda x, y, z: (int(
                (x - xmin) / xticks) + int((y - ymin) / yticks)) % 2)
        else:
            # do a topo coloring
            bounds = P.bounding_box()
            min_z = bounds[0][2]
            max_z = bounds[1][2]
            if max_z == min_z:
                span = 0
            else:
                span = (len(texture) - 1) / (max_z - min_z
                                             )  # max to avoid dividing by 0
            parts = P.partition(lambda x, y, z: int((z - min_z) * span))
        all = []
        for k, G in parts.iteritems():
            G.set_texture(texture[k], opacity=opacity)
            all.append(G)
        P = Graphics3dGroup(all)
    else:
        P.set_texture(texture)

    P.frame_aspect_ratio([1.0, 1.0, 0.5])
    P._set_extra_kwds(kwds)
    return P
Пример #27
0
from render import Render, V2, V3

from obj import Obj

from texture import Texture

from shaders import gourad, toon, outline, toon_mod

from utils import color

r = Render()
r.glCreateWindow(1000,1000)
r.glClear()

r.active_texture = Texture('./models/model.bmp')
r.active_shader = toon

#r.light = V3(1,0,0)

r.loadModel('./models/model.obj', V3(250,500,0), V3(150,150,150))

r.active_shader = outline

r.loadModel('./models/model.obj', V3(500,500,0), V3(150,150,150))

r.active_shader = toon_mod

r.loadModel('./models/model.obj', V3(750,500,0), V3(150,150,150))


r.glFinish('output2.bmp')
Пример #28
0
    def test_getitem_non_contiguous(self):

        data = np.zeros((10,10), dtype=np.uint8)
        T = Texture(data=data)
        with self.assertRaises(ValueError):
            Z = T[::2,::2]
bmp = Bitmap(1364, 1020)


def glInit():
    return bmp


if __name__ == '__main__':
    '''Main Program'''

    bmp = glInit()
    bmp.glCreateWindow(1000, 1000)
    bmp.glClear()
    bmp.glColor(1, 1, 1)

    backgorund = Texture('fondo.bmp')
    bmp.framebuffer = backgorund.pixels

    mapeoNormal = Texture('normalMapVidrio.bmp')

    bmp.lookAt(V3(-0.2, 0, 20), V3(0, 0, 0), norm(V3(0, 1, 0)))
    bmp.loadViewportMatrix(0, 0)

    bmp.glLoadObjModel("man.obj",
                       mtl="man.mtl",
                       scale=(0.09, 0.09, 0.09),
                       translate=(-2.8, -7.0, 10),
                       rotate=(0, 0, 0),
                       shader=2)
    bmp.glLoadObjModel("oso.obj",
                       mtl="oso.mtl",
Пример #30
0
    def test_setitem_wrong(self):

        data = np.zeros((10,10), dtype=np.uint8)
        T = Texture(data=data)
        with self.assertRaises(ValueError):
            T[::2,::2] = 1