def parse_images(data_center, prefix='../data/clean_data', min_throughput=100, min_diff=100): images = {} data_dir = '%s/%s' % (prefix, data_center) for c in os.listdir(data_dir): with open('%s/%s' % (data_dir, c)) as f: cur_pulls = {} for i, e in enumerate(json.load(f)): repo, etype, tag = util.parse_uri(e['uri']) if repo is None: continue if etype == 'manifests': img = Image(repo, tag) img = images.setdefault(str(img), img) cur_pulls[repo] = img else: img = cur_pulls.get(repo) if img is None: continue dgst = tag img.add_layer(dgst, e['size']) return { img_id: img for img_id, img in images.items() if len(img.layers) > 0 }
def triangleTest1(): tris = edgemtx() img = Image(500, 500) for x in range(0, 500, 50): for y in range(0, 500, 50): addTriangle(tris, x, y, 0, x + 25, y, 0, 250, 250, 250) drawTriangles(tris, img) img.display()
def textureTest(): help(Reader) r = Reader(file=open('tesx.png')) rgb = list(r.asRGBA()[2]) print len(rgb),len(rgb[0]) img = Image(500,500) drawTexturedTri(150,150,300,100,100,300,1,0,0,1,1,1,rgb,(255,255,0),img) img.savePpm('t.ppm')
def circleTest1(): import math m = edgemtx() addEdgesFromParam(m, lambda t: 250 + 100 * math.cos(t * 2 * math.pi), lambda t: 250 + 100 * math.sin(t * 2 * math.pi), lambda t: 0, 0.01) img = Image(500, 500) drawEdges(m, img) img.display()
def mtxTest1(): m1 = [[2, 2, 3], [3, 2, 2]] m2 = [[1, 5], [6.5, 4], [1, -0.7]] m3 = [[1, 2, 3, 1], [5, 2, -1, 3], [-1, -5, 3, 6], [2, 4, -7, 2]] k1 = 2.5 k2 = 3.5 id3 = matrix.id(3) id2 = matrix.id(2) print 'identity 3x3' print matrix.toStr(id3) print 'identity 2x2' print matrix.toStr(id2) print 'm1 2x3' print matrix.toStr(m1) print 'sanity checks: m1 * id3 = m1, id2 * m1 = m1' m1again = matrix.multiply(m1, id3) m1evenmore = matrix.multiply(id2, m1) print matrix.toStr(m1again) print matrix.toStr(m1evenmore) print 'testing size mismatch id3 * m1:' try: matrix.multiply(id3, m1) except ArithmeticError: print 'it errored, that\'s good' print 'm2 3x2' print matrix.toStr(m2) m12 = matrix.multiply(m1, m2) print 'm1 * m2, should be a 2x2' print matrix.toStr(m12) m21 = matrix.multiply(m2, m1) print 'm2 * m1, should be a 3x3' print matrix.toStr(m21) print '10 * (m2 * m1)' print matrix.toStr(matrix.multiply(10, m21)) print '(m2 * m1) * 10' print matrix.toStr(matrix.multiply(m21, 10)) print '10 * 10' print matrix.multiply(10, 10) print 'Adding edge (1, 1, 1), (2, 3, 2.5)' m = edgemtx() addEdge(m, 1, 1, 1, 2, 3, 2.5) print matrix.toStr(m) print 'm3' print matrix.toStr(m3) print 'Transforming edge matrix' print matrix.toStr(matrix.multiply(m3, m)) img = Image(500, 500) for loc in range(0, 500, 4): edges = edgemtx() addEdge(edges, 125, loc, 100, loc + 1, 375, 100) addEdge(edges, loc + 1, 375, 100, 375, 500 - loc - 2, 100) addEdge(edges, 375, 500 - loc - 2, 100, 500 - loc - 3, 125, 100) addEdge(edges, 500 - loc - 3, 125, 100, 125, loc + 4, 100) drawEdges(edges, img, (255 - loc / 2, loc / 2, 127)) # crossfade r + g img.display()
def sphinput(): lx, ly, lz = tuple(input('light position x,y,z: ')) vz = int(input('viewer position z: ')) vx = vy = 250 Ia = tuple(input('ambient color r,g,b: ')) Id = tuple(input('light color r,g,b: ')) Is = tuple(input('spectral color r,g,b: ')) Ka = Kd = tuple(input('ball color r,g,b: ')) Ks = 255, 255, 255 a = int(input('shininess a: ')) n = 1. / float(input('sphere steps: ')) r = float(input('radius: ')) cx, cy, cz = tuple(input('center position x,y,z: ')) tris = transform.T(cx, cy, cz) * edgeMtx.sphere(r, n) zbuf = [[None] * 500 for i in xrange(500)] zbuf[250][250] = 1 print zbuf[251][250] img = Image(500,500) triList = [] for i in range(0, len(tris[0]) - 2, 3): triList.append(tuple(tris[0][i : i + 3] + tris[1][i : i + 3] + tris[2][i : i + 3])) triList.sort(key=lambda t: -sum(t[6:9])) print 'sorted lis' for x1, x2, x3, y1, y2, y3, z1, z2, z3 in triList: nx1, ny1, nz1 = normalize(x1 - cx, y1 - cy, z1 - cz) nx2, ny2, nz2 = normalize(x2 - cx, y2 - cy, z2 - cz) nx3, ny3, nz3 = normalize(x3 - cx, y3 - cy, z3 - cz) shadePix = drawShadedTri(x1,y1,z1,x2,y2,z2,x3,y3,z3,nx1,ny1,nz1,nx2,ny2,nz2,nx3,ny3,nz3,lx,ly,lz,vx,vy,vz,Ia,Id,Is,Ka,Kd,Ks,a,zbuf) img.setPixels(shadePix) img.display() img.saveAs('sph.png')
def sphereshade(): lx, ly, lz = 700,100,0 vx, vy = 250, 250 Ia = (100, 100, 100) Id = (255, 0, 0) Is = (255, 150, 150) Ks = (128, 128, 128) zbuf = [[None for _ in xrange(500)] for _ in ge(500)] tris = transform.T(250, 250, 0) * edgeMtx.sphere(200, .02) sts = edgeMtx.edgemtx() edgeMtx.addCircle(sts,0,0,0,500,.05) sts = transform.T(250,250,0)*transform.R('y', -45)*transform.R('x', 90)*sts sts = zip(*sts)[::2] ke=0 for lx,ly,lz,_ in sts: img = Image(500,500) triList = [] for i in range(0, len(tris[0]) - 2, 3): triList.append(tuple(tris[0][i : i + 3] + tris[1][i : i + 3] + tris[2][i : i + 3])) triList.sort(key=lambda t: sum(t[6:9])) print 'sorted lis' for x1, x2, x3, y1, y2, y3, z1, z2, z3 in triList: nx1, ny1, nz1 = normalize(x1 - 250, y1 - 250, z1) nx2, ny2, nz2 = normalize(x2 - 250, y2 - 250, z2) nx3, ny3, nz3 = normalize(x3 - 250, y3 - 250, z3) shadePix = drawShadedTri(x1,y1,z1,x2,y2,z2,x3,y3,z3,nx1,ny1,nz1,nx2,ny2,nz2,nx3,ny3,nz3,lx,ly,lz,vx,vy,vz,Ia,Id,Is,Ka,Kd,Ks,a,zbuf) img.setPixels(shadePix) img.savePpm('shade/%d.ppm'%(ke)) if ke == 0: img.display() ke+=1 print ke
def marioTest(): from time import time tc = {} chdir('mario') triset = obj.parse('mario.obj','mario.mtl') mat = transform.T(250, 400, 0) * transform.R('z', 180) * transform.S(1.5,1.5,1.5) for i in range(len(triset)): triset[i][0] = mat * triset[i][0] img = Image(500,500) mat = transform.T(250,400,0)*transform.R('y',5)*transform.T(-250,-400,0) textureTriMtxs(triset,img,tc) print len(tc) img.display() for i in range(72): print 'making image...', a = time() img = Image(500,500) print (time() - a) * 1000, 'ms' print 'transforming...', a = time() for j in range(len(triset)): triset[j][0] = mat * triset[j][0] print (time() - a) * 1000, 'ms' print 'texturing...', a = time() textureTriMtxs(triset, img,tc) print (time() - a) * 1000, 'ms' print 'saving...', a = time() img.savePpm('../animar/%d.ppm'%(i)) print (time() - a) * 1000, 'ms' print i, 'drawn'
def load_images(data_center, prefix='../data/images'): data_dir = '%s/%s' % (prefix, data_center) with open('%s/layers.json' % data_dir) as f: layers = {l['digest']: l for l in json.load(f)} with open('%s/images.json' % data_dir) as f: images = {} for i in json.load(f): img = pb2.Image(repo=i['repo'], tag=i['tag'], parent=i['parent'], aliases=i['aliases'], layers=[ pb2.Layer(digest=dgst, size=layers[dgst]['size']) for dgst in i['layers'] ]) images[Image.ID(img.repo, img.tag)] = img return images
def shadetest(): x1, y1, z1 = 100, 100, 200 x2, y2, z2 = 300, 150, 0 x3, y3, z3 = 150, 300, 0 nx1, ny1, nz1 = normalize(x1, y1, z1) nx2, ny2, nz2 = normalize(x2, y2, z2) nx3, ny3, nz3 = normalize(x3, x3, z3) lx, ly, lz = 300, 300, 300 col = (255, 150, 30) Ia = (255,200,150) Id = (255,200, 150) Is = (255,200,150) Ka = (0,200,100) Kd = (0,200,100) Ks = (255,255,255) a = 0.5 img = Image(500, 500) shadePix = drawShadedTri(x1,y1,z1,x2,y2,z2,x3,y3,z3,nx1,ny1,nz1,nx2,ny2,nz2,nx3,ny3,nz3,lx,ly,lz,Ia,Id,Is,Ka,Kd,Ks,a) print shadePix img.setPixels(shadePix) img.display()
def marioshadetest(): img = Image(500, 500) # TODO implement lights, texcache, zbuf lights = [Light(409.1, 409.1, 0, (30, 10, 10), (200, 50, 50), (255, 150, 150)), Light(25, 250, 50, (5, 30, 10), (50, 200, 50), (150, 255, 150)), Light(250, 25, 100, (10, 20, 30), (50, 50, 200), (150, 150, 255))] fov = 90 cam = Camera(250, 250, 200, 0, 0, 0, -250,-250, 1 / math.tan(fov / 2.)) camT = transform.T(cam.x,cam.y,cam.z)*transform.C2(cam, 500, -500) print matrix.toStr(camT) lballs = [] sphere = edgeMtx.sphere(20, .1) for l in lights: lightball = transform.T(l.x, l.y, l.z) * sphere lballs.append([lightball, l.Id]) texcache = {} chdir('mario') tris = obj.parse('mario.obj','mario.mtl') mrot = transform.R('z', 180)*transform.R('y', 180) m = transform.T(250,380,0)*transform.S(1.2, 1.2, 1.2)*mrot apply(m, tris) applyNorms(mrot, tris) # ROTATE MARIO # mrot = transform.R('y', 5) # m = transform.T(250, 380, 0) * mrot * transform.T(-250, -380, 0) # ROTATE LIGHTS m = transform.T(250, 250, 0) * transform.R('z', 5) * transform.T(-250, -250, 0) for i in range(72): a = time() zbuf = [[None]*500 for j in xrange(500)] img = Image(500, 500) for ball, col in lballs: edgeMtx.drawTriangles(ball, img, col, col, False) tricam = applied(camT, tris) tricam.sort(key=lambda tri: -tri[0].z - tri[1].z - tri[2].z) for tri in tricam: #for j in xrange(3): # pt = tri[j] # pt.x += cam.x # pt.y += cam.y # pt.z += cam.z img.setPixels(renderTriangle(*tri + [cam.vx, cam.vy, cam.vz, lights, texcache, zbuf])) if i == 0: img.display() img.saveAs('proj.png') img.savePpm('../marshade/%d.ppm' % (i)) # ROTATE MARIO # apply(m, tris) # applyNorms(mrot, tris) # ROTATE LIGHTS for ball in lballs: ball[0] = m * ball[0] for l in lights: x = dot4xyz(m[0], l.x, l.y, l.z) y = dot4xyz(m[1], l.x, l.y, l.z) z = dot4xyz(m[2], l.x, l.y, l.z) l.x = x l.y = y l.z = z print i, 'in', (time() - a) * 1000, 'ms' chdir('..') img.display() img.saveAs('marshade.png')
addEdgesFromParam(m, lambda t: 250 + 100 * math.cos(t * 2 * math.pi), lambda t: 250 + 100 * math.sin(t * 2 * math.pi), lambda t: 0, 0.01) img = Image(500, 500) drawEdges(m, img) img.display() def circleTest2(): m = edgemtx() for theta in range(36): costheta = math.cos(theta) def fx(t): return 250 + 100 * math.cos(t * 2 * math.pi) * costheta if __name__ == '__main__': import transform m = transform.T(250, 250, 0) * transform.R('x', 30) * transform.R( 'y', 30) * sphere(200, .05) mat = transform.T(250, 250, 0) * transform.R('y', 5) * transform.T( -250, -250, 0) for i in range(72): img = Image(500, 500) drawTriangles(m, img) m = mat * m print i, 'iter' img.savePpm('sphere/%d.ppm' % (i))
def line8(x0, y0, x1, y1): pts = [] x = x0 y = y0 a = 2 * (y1 - y0) b = x0 - x1 d = a - b b *= 2 while x <= x1: pts.append((x, y)) if d < 0: y -= 1 d -= b x += 1 d += a return pts if __name__ == '__main__': print 'Running line test' img = Image(500, 500) xys = [(125, 0), (375, 0), (0, 125), (0, 375), (500, 125), (500, 375), (125, 500), (375, 500), (500, 500), (0, 0), (250, 0), (0, 250), (250, 500), (500, 250), (0, 500), (500, 0)] pts = [pt for coords in xys for pt in lineByY(250, 250, *coords)] for pt in pts: if 500 > pt[0] >= 0 and 500 > pt[1] >= 0: img.setPixel(pt[0], 499 - pt[1], (255, 0, 0)) img.display()
elif inp == 'scale': inp = raw_input('') trans = S(*iparse(inp)) * trans elif inp == 'move': inp = raw_input('') trans = T(*iparse(inp)) * trans elif inp == 'rotate': inp = raw_input('') axis, t = (i.strip() for i in inp.split(' ')) trans = R(axis.lower(), float(t)) * trans elif inp == 'apply': print edges edges = trans * edges print edges elif inp == 'display': img = Image(500, 500) drawEdges(edges, img) img.flipUD().display() elif inp == 'save': inp = raw_input('').strip() img = Image(500, 500) drawEdges(edges, img) if inp[-4:] == '.ppm': img.flipUD().savePpm(inp) else: img.flipUD().saveAs(inp) elif inp == 'saveframe': inp = raw_input('').strip() img = Image(500, 500) drawEdges(projected(edges, cam), img) img.flipUD().savePpm('%s%d.ppm' % (inp, frc))
from line import line from base import Image img = Image(500, 500) y = lambda x: 500 * (x / 250. - 1)**2 dy = lambda x: 4 * (x / 250. - 1) xs = range(0, 501, 4) ys = [y(x) for x in xs] xys = zip(xs, ys) points = [] for x, y in xys: slope = dy(x) y0 = int(-slope * x + y) y500 = int(slope * (500 - x) + y) pts = line(0, y0, 500, y500) pts = filter(lambda tup: 500 > tup[0] >= 0 and 500 > tup[1] >= 0, pts) coloredpoints = [(px, py, (x / 2, y / 2, (x + y) / 4)) for px, py in pts] points.extend(coloredpoints) img.setPixels(points) img.saveAs('cool.png') img.display()
def run(filename): """ This function runs an mdl script """ color = [255, 255, 255] tmp = TransMatrix() p = mdl.parseFile(filename) #print p if p: (commands, symbols) = p else: print "Parsing failed." return frames = None basename = 'anim' varying = False # pass 1 for command in commands: cmd = command[0] args = command[1:] if cmd == 'frames': frames = args[0] elif cmd == 'basename': basename = args[0] elif cmd == 'vary': varying = True if varying: if frames is None: err('Frames not set.') if basename == 'anim': warn('Basename not set, using default of anim.') # pass 2 upd = lambda d, n: 0 if d.update(n) else d frameList = [ upd({k: v[1] for k, v in symbols.iteritems() if v[0] == 'knob'}, {None: 1}) for _ in range(frames) ] for command in commands: cmd = command[0] args = command[1:] if cmd == 'set': for frame in frameList: frame[args[0]] = args[1] elif cmd == 'setall': for frame in frameList: for key in frame.keys(): frame[key] = args[0] elif cmd == 'vary': val = args[3] inc = (1. * args[4] - args[3]) / (args[2] - args[1]) for frid in range(args[1], args[2] + 1): frameList[frid][args[0]] = val val += inc imgs = [] # pass for each frame print 'Pass 2 complete, beginning image rendering...' a = time.time() for frame in frameList: objects = runFrame(frame, commands) img = Image(500, 500) draw(objects, img) imgs.append(img) print 'Images rendered in %f ms' % (int( (time.time() - a) * 1000000) / 1000.) print 'Saving images...' a = time.time() for i in range(len(imgs)): imgs[i].savePpm('anim/%s%03d.ppm' % (basename, i)) print 'Images saved in %f ms' % (int( (time.time() - a) * 1000000) / 1000.) print 'Creating animation... (converting to gif)' a = time.time() makeAnimation(basename, 'ppm') print 'Animation created in %f ms' % (int( (time.time() - a) * 1000000) / 1000.) # clearAnim() else: cstack = [TransMatrix()] frc = 0 img = Image(500, 500) objects = [] for command in commands: inp = command[0] if inp == 'line': edges = edgemtx() addEdge(edges, *command[1:7]) edges = cstack[-1] * edges objects.append((EDGE, edges)) #drawEdges(cstack[-1] * edges, img) elif inp == 'ident': cstack[-1] = TransMatrix() elif inp == 'scale': cstack[-1] *= transform.S(*command[1:4]) elif inp == 'move': cstack[-1] *= transform.T(*command[1:4]) elif inp == 'rotate': cstack[-1] *= transform.R(*command[1:3]) elif inp == 'display': drawObjects(objects, img) img.flipUD().display() elif inp == 'save': drawObjects(objects, img) if inp[-4:] == '.ppm': img.flipUD().savePpm(command[1]) else: img.flipUD().saveAs(command[1]) elif inp == 'saveframe': drawObjects(objects, img) img.flipUD().savePpm('%s%d.ppm' % (command[1], frc)) frc += 1 elif inp == 'circle': edges = edgemtx() addCircle(*(edges, ) + command[1:5] + (.01, )) edges = cstack[-1] * edges objects.append((EDGE, edges)) #drawEdges(cstack[-1] * edges, img) elif inp == 'bezier': edges = edgemtx() addBezier(*(edges, ) + command[1:9] + (.01, )) edges = cstack[-1] * edges objects.append((EDGE, edges)) #drawEdges(cstack[-1] * edges, img) elif inp == 'hermite': edges = edgemtx() addHermite(*(edges, ) + command[1:9] + (.01, )) edges = cstack[-1] * edges objects.append((EDGE, edges)) #drawEdges(cstack[-1] * edges, img) elif inp == 'clear': img = Image(500, 500) elif inp == 'clearstack': cstack = [TransMatrix()] elif inp == 'box': polys = edgemtx() shape.addBox(*(polys, ) + command[1:7]) polys = cstack[-1] * polys objects.append((POLY, polys)) #drawTriangles(cstack[-1] * polys, img, wireframe=True) elif inp == 'sphere': polys = edgemtx() shape.addSphere(*(polys, ) + command[1:5] + (.05, )) polys = cstack[-1] * polys objects.append((POLY, polys)) #drawTriangles(cstack[-1] * polys, img, wireframe=True) elif inp == 'torus': polys = edgemtx() shape.addTorus(*(polys, ) + command[1:6] + (.05, .05)) polys = cstack[-1] * polys objects.append((POLY, polys)) #drawTriangles(cstack[-1] * polys, img, wireframe=True) elif inp == 'push': cstack.append(cstack[-1].clone()) elif inp == 'pop': cstack.pop()
def _build_images( self, images: Iterable[pb2.Image], existed: Iterable[pb2.Image], layers: Dict[str, Layer], ) -> List[Image]: to_build, refs, exist = {}, {}, set() for i in existed: img = Image(i.repo, i.tag) aliases = [str(img)] + list(i.aliases) for a in aliases: refs[a] = img exist.add(a) for i in images: ls = [layers[l.digest] for l in i.layers if l.digest in layers] img = Image(i.repo, i.tag, aliases=i.aliases, layers=ls) img_id = str(img) to_build[img_id] = img aliases = [img_id] + list(i.aliases) for a in aliases: refs[a] = img for i in images: if i.parent: to_build[Image.ID(i.repo, i.tag)].parent = refs.get( i.parent, Image(*i.parent.split(':'))) # elect a major image to build and tag other aliases elected = set() for i in dict(to_build).values(): elected.add(str(i)) for a in i.aliases: if a not in elected: to_build.pop(a, None) def _build(idx, total, image): with sema: logging.info('[%d/%d] Building image %s ...' % (idx, total, image)) image.build(self.__build_dir, self.registry) logging.info('[%d/%d] Pushing image %s to %s ...' % (idx, total, image, self.registry)) image.push(self.registry) logging.info('[%d/%d] Deleting image %s ...' % (idx, total, image)) image.prune(self.registry) if len(image.aliases) > 0: logging.info( '[%d/%d] Pushing %d aliases of %s to %s ...' % (idx, total, len(image.aliases), image, self.registry)) image.push_aliases(self.registry) logging.info('Building a total of %d images' % len(to_build)) built = set() ready = [ i for i in to_build.values() if not i.parent or str(i.parent) in built or str(i.parent) in exist ] while ready: procs = [ mp.Process(target=_build, args=( len(built) + idx + 1, len(to_build), i, )) for idx, i in enumerate(ready) ] sema = mp.Semaphore( min(int(mp.cpu_count() * self.__scaling_factor), len(ready))) logging.info('Building %d images' % len(procs)) try: for p in procs: p.start() for p in procs: p.join() finally: for p in procs: if p.is_alive(): p.terminate() for i in ready: built.add(str(i)) del to_build[str(i)] ready = [ i for i in to_build.values() if not i.parent or str(i.parent) in built or str(i.parent) in exist ] logging.info('Built %d images' % len(built)) return list(to_build.values())
print 'm1 * m2, should be a 2x2' print matrix.toStr(m12) m21 = matrix.multiply(m2, m1) print 'm2 * m1, should be a 3x3' print matrix.toStr(m21) print '10 * (m2 * m1)' print matrix.toStr(matrix.multiply(10, m21)) print '(m2 * m1) * 10' print matrix.toStr(matrix.multiply(m21, 10)) print '10 * 10' print matrix.multiply(10, 10) print 'Adding edge (1, 1, 1), (2, 3, 2.5)' m = edgemtx() addEdge(m, 1, 1, 1, 2, 3, 2.5) print matrix.toStr(m) print 'm3' print matrix.toStr(m3) print 'Transforming edge matrix' print matrix.toStr(matrix.multiply(m3, m)) img = Image(500, 500) for loc in range(0, 500, 4): edges = edgemtx() addEdge(edges, 125, loc, 100, loc + 1, 375, 100) addEdge(edges, loc + 1, 375, 100, 375, 500 - loc - 2, 100) addEdge(edges, 375, 500 - loc - 2, 100, 500 - loc - 3, 125, 100) addEdge(edges, 500 - loc - 3, 125, 100, 125, loc + 4, 100) drawEdges(edges, img, (255 - loc / 2, loc / 2, 127)) # crossfade r + g img.display()
def camtest(): import shape fov = 100 cam = Camera(0.5,0.5,0.8,0,0,0,0,0,1 / math.tan(fov / 2.)) camargs = [100,100,-50,-300] camT = transform.C3(*camargs)*transform.T(-250, -250,-175) print camT ncamT = transform.C3invT(*camargs) print ncamT v = [250,250,1000] lights = [Light(500,0,500,(20,20,20),(200,200,200),(255,255,255)), Light(500,500,200,(20,20,20),(200,200,200),(255,255,255)), Light(0,250,500,(20,20,20),(200,200,200),(255,255,255)) ] camlights = [] for l in lights: x = dot4xyz(camT[0], l.x, l.y, l.z) y = dot4xyz(camT[1], l.x, l.y, l.z) z = dot4xyz(camT[2], l.x, l.y, l.z) w = dot4xyz(camT[3], l.x, l.y, l.z)*1. print x/w*250,y/w*250,z/w*250 camlights.append(Light(x/w*250, y/w*250, z/w*250,l.Ia,l.Id,l.Is)) tris, norms = shape.box(200,200,-100,100,100,200) print norms print ncamT * norms print list(triIter(tris)) trot = transform.R('y',5) nrot = transform.TransMatrix() nrot.lst = matrix.transpose(transform.R('y',-5)) tmat = transform.T(250,250,0)*trot*transform.T(-250,-250,0) tris = tmat*tmat*tmat*tris norms= trot*trot*trot*norms print norms print ncamT*norms amb = Texture(False, [255,0,0]) diff = Texture(False, [255,0,0]) spec = Texture(False, [255,150,150]) mat = Material(amb, diff, spec, 10) for i in range(72): #print tris tricam = camT * tris #print tricam #tricam[3] = [1.] * len(tricam[3]) #tricam = transform.T(*v) * tricam print 'trans done' a = time() zbuf = [[None]*500 for _ in range(500)] img = Image(500,500) trit = list(triIter(tricam)) #print trit,tricam trit.sort(key=lambda tri: -tri[0][2] - tri[1][2] - tri[2][2]) normcam = ncamT*norms normt = [] for j in range(len(normcam[0])): sgn = (normcam[3][j] > 0) * 2 - 1 normt.append(normalize(normcam[0][j]*sgn, normcam[1][j]*sgn, normcam[2][j]*sgn)) print normt #print len(trit), len(normt) for j in range(len(trit)): # (p1, p2, p3, mat, vx, vy, vz, lights, texcache, zbuf): t = trit[j] ps = [] for pt in t: pt[0]+=250 pt[1]+=250 pt[2]+=0 print pt ps.append(Point(*pt + normt[j] + [0,0])) img.setPixels(renderTriangle(*ps + [mat] + v + [camlights, {}, zbuf])) for t in trit: l = line(*t[0][:2]+t[1][:2]) l += line(*t[0][:2]+t[2][:2]) l += line(*t[2][:2]+t[1][:2]) img.setPixels([p + ((0,0,0),) for p in l]) for j in range(len(trit)): t = trit[j] ps = [] for pt in t: nls = line(pt[0] - 4, pt[1], pt[0] + 4, pt[1]) nls += line(pt[0], pt[1] - 4, pt[0], pt[1] + 4) nls += line(pt[0] - 4, pt[1] - 4, pt[0] + 4, pt[1] + 4) nls += line(pt[0] - 4, pt[1] + 4, pt[0] + 4, pt[1] - 4) nls += line(pt[0], pt[1], pt[0] + normt[j][0]*20, pt[1] + normt[j][1]*20) print normt[j][0], normt[j][1] img.setPixels([p + ((0,255,0),) for p in nls]) img.savePpm('cube/%d.ppm'%(i)) tris = tmat * tris norms = nrot * norms print norms print i, (time() - a) * 1000, 'ms'
def runFrame(frame, commands): step = 0.02 cstack = [TransMatrix()] img = Image(500, 500) objects = [] for command in commands: inp = command[0] args = command[1:] if inp == 'line': edges = edgemtx() addEdge(edges, *command[1:7]) edges = cstack[-1] * edges objects.append((EDGE, edges)) #drawEdges(cstack[-1] * edges, img) elif inp == 'ident': cstack[-1] = TransMatrix() elif inp == 'scale': kval = frame[args[3]] cstack[-1] *= transform.S(*args[:3]) * transform.S( kval, kval, kval) # scaling a scale with scale elif inp == 'move': kval = frame[args[3]] cstack[-1] *= transform.T(*[i * kval for i in args[:3]]) elif inp == 'rotate': kval = frame[args[2]] cstack[-1] *= transform.R(args[0], args[1] * kval) elif inp == 'circle': edges = edgemtx() addCircle(*(edges, ) + command[1:5] + (.01, )) edges = cstack[-1] * edges objects.append((EDGE, edges)) #drawEdges(cstack[-1] * edges, img) elif inp == 'bezier': edges = edgemtx() addBezier(*(edges, ) + command[1:9] + (.01, )) edges = cstack[-1] * edges objects.append((EDGE, edges)) #drawEdges(cstack[-1] * edges, img) elif inp == 'hermite': edges = edgemtx() addHermite(*(edges, ) + command[1:9] + (.01, )) edges = cstack[-1] * edges objects.append((EDGE, edges)) #drawEdges(cstack[-1] * edges, img) elif inp == 'clearstack': cstack = [TransMatrix()] elif inp == 'box': vxs = cstack[-1] * shape.genBoxPoints(*command[1:7]) tris = shape.genBoxTris() shape.fixOverlaps(vxs, tris) objects.append((POLY, flatTrisFromVT(vxs, tris))) #polys = edgemtx() #shape.addBox(*(polys,) + command[1:7]) #polys = cstack[-1] * polys #objects.append((POLY, polys)) #drawTriangles(cstack[-1] * polys, img, wireframe=True) elif inp == 'sphere': vxs = cstack[-1] * shape.genSpherePoints(*command[1:5] + (step, )) tris = shape.genSphereTris(step) shape.fixOverlaps(vxs, tris) objects.append((POLY, autoTrianglesFromVT(vxs, tris))) #polys = edgemtx() #shape.addSphere(*(polys,) + command[1:5] + (.05,)) #polys = cstack[-1] * polys #objects.append((POLY, polys)) #drawTriangles(cstack[-1] * polys, img, wireframe=True) elif inp == 'torus': vxs = cstack[-1] * shape.genTorusPoints(*command[1:6] + (step, step)) tris = shape.genTorusTris(step, step) shape.fixOverlaps(vxs, tris) objects.append((POLY, autoTrianglesFromVT(vxs, tris))) #polys = edgemtx() #shape.addTorus(*(polys,) + command[1:6] + (.05, .05)) #polys = cstack[-1] * polys #objects.append((POLY, polys)) #drawTriangles(cstack[-1] * polys, img, wireframe=True) elif inp == 'push': cstack.append(cstack[-1].clone()) elif inp == 'pop': cstack.pop() return objects
norm[3 - i - j] = dir addEdge(n, *norm * 2) ak[3 - i - j] += dim[3 - i - j] return m, n if __name__ == '__main__': from base import Image import transform cube = edgemtx() addBoxPoints(cube, 125, 125, -125, 250, 250, 250) m = edgemtx() xTrans = transform.T(250, 250, 0) * transform.R('x', 18) * transform.T( -250, -250, 0) yTrans = transform.T(250, 250, 0) * transform.R('y', 18) * transform.T( -250, -250, 0) for d in 'xyz': trans = transform.T(250, 250, 0) * transform.R(d, 15) * transform.T( -250, -250, 0) for i in range(24): addToEdgeMtx(m, cube) cube = trans * cube cube = m m = edgemtx() cube = transform.T(250, 250, 0) * transform.R('y', 49) * transform.R( 'x', 67) * transform.R('z', 23) * transform.T(-250, -250, 0) * cube img = Image(500, 500) drawEdges(cube, img) img.display() img.saveAs('badsphere.png')