def scene(t): """ Returns the scene at time 't' (in seconds) """ head_location = np.array(location) - np.array([0, 0, head_size]) import vapory light = vapory.LightSource([15, 15, 1], 'color', [light_intensity] * 3) background = vapory.Box( [0, 0, 0], [1, 1, 1], vapory.Texture( vapory.Pigment( vapory.ImageMap('png', '"../files/VISUEL_104.png"', 'once')), vapory.Finish('ambient', 1.2)), 'scale', [self.background_depth, self.background_depth, 0], 'translate', [ -self.background_depth / 2, -.45 * self.background_depth, -self.background_depth / 2 ]) me = vapory.Sphere( head_location, head_size, vapory.Texture(vapory.Pigment('color', [1, 0, 1]))) self.t = t self.update() objects = [background, me, light] for i_lame in range(self.N_lame): #print(i_lame, self.lame_length[i_lame], self.lame_width[i_lame]) objects.append( vapory.Box( [ -self.lame_length[i_lame] / 2, 0, -self.lame_width[i_lame] / 2 ], [ self.lame_length[i_lame] / 2, self.lames_height, self.lame_width[i_lame] / 2 ], vapory.Pigment('color', [1, 1, 1]), vapory.Finish('phong', 0.8, 'reflection', reflection), 'rotate', (0, -self.lames[2, i_lame] * 180 / np.pi, 0), #HACK? 'translate', (self.lames[0, i_lame], 0, self.lames[1, i_lame]))) objects.append(light) return vapory.Scene(vapory.Camera('angle', fov, "location", location, "look_at", look_at), objects=objects, included=["glass.inc"])
def _generate_objects(representations): objects = [] for rep in representations: if rep['type'] == 'spheres': for (x, y, z), r, c in zip(rep['options']['coordinates'], rep['options']['radii'], rep['options']['colors']): # Generate the shape sphere = vp.Sphere( [x,y,z] , r, vp.Texture( vp.Pigment( 'color', hex2rgb(c)) )) objects.append(sphere) elif rep['type'] == 'points': # Render points as small spheres for (x, y, z), c, s in zip(rep['options']['coordinates'], rep['options']['colors'], rep['options']['sizes']): # Point = sphere with a small radius sphere = vp.Sphere( [x,y,z] , s * 0.15, vp.Texture( vp.Pigment( 'color', hex2rgb(c)) )) objects.append(sphere) elif rep['type'] == 'surface': verts = rep['options']['verts'] faces = rep['options']['faces'] color = rep['options']['color'] triangles = verts.take(faces, axis=0) for v1, v2, v3 in triangles: povt = vp.Triangle(v1.tolist(), v2.tolist(), v3.tolist(), vp.Texture(vp.Pigment('color', hex2rgb(color)))) objects.append(povt) elif rep['type'] == 'cylinders': start = rep['options']['startCoords'] end = rep['options']['endCoords'] radii = rep['options']['radii'] colors = rep['options']['colors'] for s, e, r, c in zip(start, end, radii, colors): cylinder = vp.Cylinder(s.tolist(), e.tolist(), r, vp.Texture(vp.Pigment('color', hex2rgb(c)))) objects.append(cylinder) else: print("No support for representation type: %s" % rep['type']) return objects
def make_circular_spherical_lens(roc1, roc2, thickness, radius, n, *args): sag1 = functions.calc_sphere_sag(roc1, radius) sag2 = functions.calc_sphere_sag(roc2, radius) sections = [] surface1 = vp.Sphere([0, 0, roc1], abs(roc1)) if roc1 > 0: sections.append( vp.Intersection(surface1, vp.Cylinder([0, 0, 0], [0, 0, sag1], radius))) elif roc1 < 0: sections.append( vp.Difference(vp.Cylinder([0, 0, sag1], [0, 0, 0], radius), surface1)) sections.append( vp.Cylinder([0, 0, max(sag1, 0)], [0, 0, thickness + min(sag2, 0)], radius)) surface2 = vp.Sphere([0, 0, thickness + roc2], abs(roc2)) if roc2 < 0: sections.append( vp.Intersection( surface2, vp.Cylinder([0, 0, thickness + sag2], [0, 0, thickness], radius))) elif roc2 > 0: sections.append( vp.Difference( vp.Cylinder([0, 0, thickness], [0, 0, thickness + sag2], radius), surface2)) lens = vp.Union(*sections, vp.Texture('T_Glass3'), vp.Interior('ior', n), *args) return lens
def povray_test(): """ Just a purple sphere """ scene = vapory.Scene( vapory.Camera('location', [0.0, 0.5, -4.0], 'direction', [0,0,1.5], 'look_at', [0, 0, 0]), objects = [ vapory.Background("color", [0.85, 0.75, 0.75]), vapory.LightSource([0, 0, 0], 'color',[1, 1, 1], 'translate', [-5, 5, -5]), vapory.LightSource ([0, 0, 0], 'color', [0.25, 0.25, 0.25], 'translate', [600, -600, -600]), vapory.Box([-0.5, -0.5, -0.5], [0.5, 0.5, 0.5], vapory.Texture( vapory.Pigment( 'color', [1,0,0]), vapory.Finish('specular', 0.6), vapory.Normal('agate', 0.25, 'scale', 0.5)), 'rotate', [45,46,47]) ] ) # We use antialiasing. Remove this option for faster rendering. scene.render("cube.png", width=300, height=300, antialiasing=0.001)
def render(self, screen_size): light = vap.LightSource([3, 3, 3], 'color', [3, 3, 3], 'parallel', 'point_at', [0, 0, 0]) camera = vap.Camera('location', [0.5 * 1, -2 * 1, 3 * 1], 'look_at', [0, 0, 0], 'rotate', [20, 0, 0]) ground = vap.Plane([0, 0, 1], 0, vap.Texture('T_Stone33')) walls = [wall.rendered for wall in self.wall] robots = [bot.rendered for bot in self.robot] obj = self.obj.rendered obj_pos_str = '\"{:2.2f}, {:2.2f}, {:2.2f}\"'.format( *self.obj.body.getPosition()) for ir, robot in enumerate(self.robot): logger.info('{} - {:2.2f}, {:2.2f}, {:2.2f} - {st}'.format( ir, *robot.body.getPosition(), st=self.sim_time)) logger.info('{} - {}'.format(obj_pos_str, self.sim_time)) # obj_pos = vap.Text('ttf', '\"timrom.ttf\"', obj_pos_str, 0.1, '0.1 * x', 'rotate', # '<100,0,10>', 'translate', '-3*x', 'finish', # '{ reflection .25 specular 1 diffuse 0.1}', 'scale', [0.25, 0.25, 0.25]) scene = vap.Scene( camera, [light, ground, vap.Background('color', [0.2, 0.2, 0.3]), obj] + robots + walls, included=["colors.inc", "textures.inc", "glass.inc", "stones.inc"]) return scene.render(height=screen_size, width=screen_size, antialiasing=0.01, remove_temp=False)
def rendered(self): return vap.Box([-s / 2 for s in self._size], [s / 2 for s in self._size], vap.Texture('T_Ruby_Glass' if not self._color else vap. Pigment('color', self._color)), vap.Interior('ior', 4), 'matrix', self.body.getRotation() + self.body.getPosition())
def PovrayArrow(position, direction, color): """ This function creates the arrow with the library vapory (https://pypi.org/project/Vapory/). It helps to process the image. :param position: It is the position where the object is going to be ubicated. :type position: list :param direction: It is the course along which the object moves. :type direction: list :param color: It is representes by the RGB color model. It is an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. :type color: list :return: It returns an ``Union()`` of three 3D figures, that represent the ``PovrayArrow()``. :rtype: ``Union()`` """ position = numpy.array(position) direction = numpy.array(direction) * 0.9 base_point_cylinder = position - 0.5 * direction cap_point_cone = position + 0.7 * direction cap_point_cylinder = base_point_cone = base_point_cylinder + 0.7 * direction radius_cylinder = 1 / 20 base_radius_cone = 1 / 6 texture = vapory.Texture(vapory.Pigment("color", color), vapory.Finish("roughness", 0, "ambient", 0.2)) cylinder = vapory.Cylinder(base_point_cylinder, cap_point_cylinder, radius_cylinder, texture) cone = vapory.Cone(base_point_cone, base_radius_cone, cap_point_cone, 0.0, texture) sphere = vapory.Sphere( position, 2 * radius_cylinder, vapory.Texture(vapory.Pigment("color", [0, 0, 0])), ) return vapory.Union(sphere, vapory.Union(cone, cylinder))
def povray_cells(goodArguments): with h5py.File(goodArguments.vbl_simulation_output_filename, 'r') as f: h5_cells_grp = f[goodArguments.grp_pattern + "/cells"] pos = h5_cells_grp['cell_center_pos'] pos = np.asarray(pos) rad = h5_cells_grp['cell_radii'] rad = np.asarray(rad) o2 = h5_cells_grp['o2'] o2 = np.asarray(o2) x_min= np.min(pos[:,0]) x_max = np.max(pos[:,0]) center_x = x_min+0.5*(x_max-x_min) y_min= np.min(pos[:,1]) y_max = np.max(pos[:,1]) center_y = x_min+0.5*(y_max-y_min) z_min= np.min(pos[:,2]) z_max = np.max(pos[:,2]) center_z = z_min+0.5*(z_max-z_min) print('x: [%f,%f]' % (x_min, x_max)) print('y: [%f,%f]' % (y_min, y_max)) print('z: [%f,%f]' % (z_min, z_max)) print('%f, %f, %f' %(center_x,center_y,center_z)) #o2 = o2/np.max(o2) # x = pos[:,0] # y = pos[:,1] # z = pos[:,2] # s = rad[:,0] camera = vapory.Camera('location', [700,700,-700], 'look_at', [0,0,0]) light = vapory.LightSource([1000,-1000,-1000], 'color', [1, 1, 1]) light2 = vapory.LightSource([0,0,0], 'color',[1, 1, 1], 'translate', [1000,-1000,-1000] ) light3 = vapory.LightSource([500,-1000,500], 'color', [1, 1, 1] ) myObjectList = [] myObjectList.append(light) myObjectList.append(light2) myObjectList.append(light3) cuttingY = vapory.Plane([0,1,0], 0,) cuttingX = vapory.Plane([1,0,0], -1,) max_rad = np.max(rad) max_o2 = np.max(o2) n= 10000 for (aPosition, aRadius, aO2Value) in zip(pos[0:n], rad[0:n], o2[0:n]): thisSphere = vapory.Sphere( aPosition, aRadius[0]) color = matplotlib.cm.hsv(aO2Value[0]/max_o2) #print(color[0:3]) #cuttedSphere = vapory.Intersection(thisSphere, cuttingY, vapory.Texture( vapory.Pigment( 'color', color[0:3] ))) #cuttedSphere = vapory.Intersection(thisSphere, cuttingY, cuttingX) #cuttedSphere = thisSphere #myObjectList.append(cuttedSphere) #myObjectList.append(thisSphere) # myObjectList.append(vapory.Sphere( aPosition, aRadius[0], vapory.Texture( vapory.Pigment( 'color', matplotlib.cm.Blues(aO2Value[0]/max_o2) )))) myObjectList.append(vapory.Sphere( aPosition, aRadius[0], vapory.Texture( vapory.Pigment( 'color', [1,0,0] )))) scene = vapory.Scene( camera, objects= myObjectList, defaults = [vapory.Finish( 'ambient', 1.5)],) scene.render("purple_sphere.png", width=400, height=300, antialiasing=0.01, remove_temp=True)
def make_cali_img_pairs(w, h, loc, look_at, direct1, direct2, rotate=[0, 0, 0], trans=[0, 0, 0], ctype=None, rand_amount=1): cali_dir = os.path.join(CFD, "caliimg") light = vp.LightSource( # [2,4,-3], [0, 0, -10000], 'color', "White", 'rotate', [30, 0, 0], 'rotate', [0, 88, 0]) # White light background = vp.Background("color", "White") # White background center = np.array(look_at) + (np.random.rand(3) - 0.5) * rand_amount sphere = vp.Sphere( center, 0.1, # center, radius vp.Texture(vp.Pigment('color', "Black"))) # Black point l_camera = vp.Camera('location', loc, 'direction', direct1, 'up', [0, 1, 0], 'right', [1 * w / h, 0, 0], 'look_at', look_at) l_scene = vp.Scene(l_camera, objects=[background, light, sphere], included=["colors.inc"]) l_img_path = os.path.join(cali_dir, "left.png") l_scene.render(l_img_path, width=w, height=h, auto_camera_angle=False) r_camera = vp.Camera('location', loc, 'direction', direct2, 'up', [0, 1, 0], 'right', [1 * w / h, 0, 0], 'look_at', look_at, 'rotate', rotate, 'translate', trans) r_scene = vp.Scene(r_camera, objects=[background, light, sphere], included=["colors.inc"]) r_img_path = os.path.join(cali_dir, "right.png") r_scene.render(r_img_path, width=w, height=h, auto_camera_angle=False) with open(os.path.join(cali_dir, "left.pov"), "wb") as f: f.write(l_scene.__str__()) with open(os.path.join(cali_dir, "right.pov"), "wb") as f: f.write(r_scene.__str__()) return cv2.imread(l_img_path), cv2.imread(r_img_path)
def main(): # helpers color = lambda col : vapory.Texture(vapory.Pigment('color', col)) texture = lambda text : vapory.Texture(text) # Begin setup s1 = experiment.ExperimentSphere(argsf1, texture('White_Wood'), semantic_label=1) s2 = experiment.ExperimentSphere(argsf2, texture('White_Wood'), semantic_label=2) # experiment global exp exp = experiment.Experiment(image_shape=image_shape, num_classes=num_classes, N=N, data_root=root, output_format=output_formats, fps=fps, mode='L') exp.add_object(vapory.LightSource([0, 5*image_shape[0], 0], 'color', [1,1,1])) exp.add_object(vapory.LightSource([5*image_shape[0], 0, 0], 'color', [1,1,1])) # Background exp.add_object(vapory.Plane( [0,0,1], 10*max(r1, r2), vapory.Texture( vapory.Pigment(vapory.ImageMap('png', '"scripts/images/harper.png"')), 'scale', '300', 'translate', [image_shape[0] // 2, 2*image_shape[1] // 3, 0]))) exp.add_object(s1) exp.add_object(s2) if debug: (image, _) , _ = exp.render_scene(0) plt.imshow(image[:,:,0], cmap='gray') plt.show() else: exp.run()
def _build_scene(self, shape): """ Creates each object and appends them to the objects list """ objects = [] # add parts to scene positions, sizes = shape.convert_to_positions_sizes() for position, size in zip(positions, sizes): lb = position - (size / 2.0) ub = position + (size / 2.0) objects.append( vapory.Box( lb, ub, vapory.Texture(vapory.Pigment('color', [1.0, 1.0, 1.0])))) # add light objects.append(self.light) return objects
def make_square_spherical_lens(roc1: float, roc2: float, thickness: float, side_length: float, n: float, *args): radius = side_length / 2**0.5 sag1 = functions.calc_sphere_sag(roc1, radius) sag2 = functions.calc_sphere_sag(roc2, radius) hsl = side_length / 2 sections = [] if np.isfinite(roc1): surface1 = vp.Sphere([0, 0, roc1], abs(roc1)) if roc1 > 0: sections.append( vp.Intersection(surface1, vp.Box([-hsl, -hsl, 0], [hsl, hsl, sag1]))) elif roc1 < 0: sections.append( vp.Difference(vp.Box([-hsl, -hsl, sag1], [hsl, hsl, 0]), surface1)) sections.append( vp.Box([-hsl, -hsl, max(sag1, 0)], [hsl, hsl, thickness + min(sag2, 0)])) surface2 = vp.Sphere([0, 0, thickness + roc2], abs(roc2)) if np.isfinite(roc2): if roc2 < 0: sections.append( vp.Intersection( surface2, vp.Box([-hsl, -hsl, thickness + sag2], [hsl, hsl, thickness]))) elif roc2 > 0: sections.append( vp.Difference( vp.Box([-hsl, -hsl, thickness], [hsl, hsl, thickness + sag2]), surface2)) lens = vp.Union( *sections, vp.Texture('T_Glass2'), vp.Interior('ior', n), *args) # , *args) vp.Texture( vp.Pigment( 'color', [1,0,1] )) return lens
def renderPopSpheres(): nb_spheres = 50 R = 5. centers = np.random.randint(100, size=(nb_spheres, 3)) radius = np.random.randn(nb_spheres) * R + R couleurs = np.random.randint(255, size=(nb_spheres, 4)) / 255. camera = vapory.Camera('location', [150, 150, 150], 'look_at', [0, 0, 0]) bg = vapory.Background('color', [1, 1, 1]) light = vapory.LightSource([100, 100, 100], 'color', [1, 1, 1]) light3 = vapory.LightSource([0, 0, 0], 'color', [1, 1, 1]) light2 = vapory.LightSource([50, 50, 50], 'color', [1, 1, 1]) obj = [light, light2, light3, bg] for i in range(nb_spheres): sphere = vapory.Sphere( centers[i, ], radius[i], vapory.Texture( vapory.Finish('ambient', 0, 'reflection', 0, 'specular', 0, 'diffuse', 1), vapory.Pigment('color', couleurs[i, ]))) obj.append(sphere) scene = vapory.Scene(camera, objects=obj) scene.render("spheres.png", width=3000, height=3000)
def scene(pack, cmap=None, rot=0, camera_height=0.7, camera_dist=1.5, angle=None, lightstrength=1.1, orthographic=False, pad=None, floatercolor=(.6, .6, .6)): """ Render a scene. Requires `vapory` package, which requires the `povray` binary. Parameters ---------- cmap : a colormap Returns ------- scene : vapory.Scene, which can be rendered using its `.render()` method. """ import vapory import numpy as np try: import matplotlib as mpl import matplotlib.cm as mcm vmin, vmax = min(pack.sigmas), max(pack.sigmas) sm = mcm.ScalarMappable(norm=mpl.colors.Normalize(vmin, vmax), cmap=cmap) cols = [sm.to_rgba(s) for s in pack.sigmas] except ImportError: if not isinstance(cmap, list): raise ValueError( "matplotlib could not be imported, and cmap not recognizeable as a list" ) cols = list(cmap) except TypeError: if not isinstance(cmap, list): raise ValueError( "matplotlib could not convert cmap to a colormap, and cmap not recognizeable as a list" ) cols = list(cmap) if floatercolor is not None: ix, _ = pack.backbone() ns, = np.nonzero(~ix) for n in ns: cols[n] = floatercolor rs = np.remainder(pack.rs + .5, 1) - .5 spheres = [ vapory.Sphere(xyz, s / 2., vapory.Texture(vapory.Pigment('color', col[:3]))) for xyz, s, col in zip(rs, pack.sigmas, cols) ] extent = (-.5, .5) corners = [ np.array((x, y, z)) for x in extent for y in extent for z in extent ] pairs = [(c1, c2) for c1 in corners for c2 in corners if np.allclose(np.sum((c1 - c2)**2), 1) and sum(c1 - c2) > 0] radius = 0.01 col = vapory.Texture(vapory.Pigment('color', [.5, .5, .5])) cyls = [vapory.Cylinder(c1, c2, 0.01, col) for c1, c2 in pairs] caps = [vapory.Sphere(c, radius, col) for c in corners] light_locs = [[8., 5., -3.], [-6., 6., -5.], [-6., -7., -4.], [10., -5., 7.]] rotlocs = [[ x * np.cos(rot) - z * np.sin(rot), y, z * np.cos(rot) + x * np.sin(rot) ] for x, y, z in light_locs] lights = [ #vapory.LightSource( [2,3,5], 'color', [1,1,1] ), vapory.LightSource(loc, 'color', [lightstrength] * 3) for loc in rotlocs ] cloc = [ np.cos(rot) * camera_dist, camera_dist * camera_height, np.sin(rot) * camera_dist ] mag = sqrt(sum([d**2 for d in cloc])) direction = [-v * 2 / mag for v in cloc] if angle is None: if pad is None: pad = max(pack.sigmas) w = sqrt(2) + pad angle = float(np.arctan2(w, 2 * camera_dist)) * 2 * 180 / np.pi camera = vapory.Camera('location', cloc, 'look_at', [0, 0, 0], 'angle', angle) # vapory.Camera('orthographic', 'location', cloc, 'direction', direction, 'up', [0,2,0], 'right', [2,0,0]) return vapory.Scene(camera, objects=lights + spheres + cyls + caps + [vapory.Background("color", [1, 1, 1])])
def __init__(self): self.texture = vapory.Texture(vapory.Pigment("color", [1, 0, 1])) self.loop_object = vapory.Box([0, 0, 0], 2, self.texture)
def generateScenes(): delta=0.1 nbcubes=100 light = vapory.LightSource( [2,4,-7], 'color', [2,2,2] ) ambientlight=AmbientLight([1,1,1]) objects=[light] rotation=[np.random.rand()*180,np.random.rand()*180,np.random.rand()*180] for k in range(nbcubes): center=[0+np.random.randn()*3,0+np.random.randn()*2,0+np.random.rand()*2] #sphere=vapory.Sphere( center, 0.5, vapory.Pigment( 'color', [1,1,1])) #sphere=vapory.Sphere( center, 0.5, vapory.Pigment( 'color', np.random.rand(3) ),vapory.Finish('phong', 0.8,'reflection', 0.5)) #objects.append(sphere) #center=[0+np.random.randn()*2,0+np.random.randn()*2,0+np.random.rand()*2] #objects.append(vapory.Box( [-0.5,-0.5,-0.5], [ 0.5,0.5,0.5 ], 'rotate',rotation , 'translate',center ,vapory.Pigment( 'color', np.random.rand(3) ),vapory.Finish('phong', 0.8,'reflection', 0.0))) #center=[0+np.random.randn()*2,0+np.random.randn()*2,0+np.random.rand()*1.0] #sphere=vapory.Sphere( center, 0.5, vapory.Pigment( 'color', [1,1,1])) #sphere=vapory.Sphere( center, 0.5, vapory.Pigment( 'color', np.random.rand(3) ),vapory.Finish('phong', 0.8,'reflection', 0.5)) #objects.append(sphere) center=[0+np.random.randn()*3,0+np.random.randn()*2,0+np.random.rand()*2] #objects.append(vapory.Box( [-0.5,-0.5,-0.5], [ 0.5,0.5,0.5 ], 'rotate',rotation , 'translate',center ,vapory.Pigment( 'color', np.random.rand(3) ),vapory.Finish('phong', 0.8,'reflection', 0.1))) #objects.append(vapory.Box( [-0.5,-0.5,-0.5], [ 0.5,0.5,0.5 ], 'rotate',rotation , 'translate',center ,vapory.Pigment( 'color',[1,1,1] ))) #objects.append(vapory.Box( [-0.5,-0.5,-0.5], [ 0.5,0.5,0.5 ], 'rotate',rotation , 'translate',center,vapory.Texture('Rosewood'))) objects.append(vapory.Box( [-0.5,-0.5,-0.5], [ 0.5,0.5,0.5 ], 'rotate',rotation , 'translate',center,vapory.Texture('White_Marble'))) #ground = vapory.Plane([0,1,0],0, vapory.Texture('Rosewood')) #objects.append(ground) camera_left = vapory.Camera( 'location', [0-delta,0,-5], 'look_at', [0-delta,0,0] ) # <= Increase for better quality camera_right = vapory.Camera( 'location', [0+delta,0,-5], 'look_at', [0+delta,0,0]) # <= Increase for better quality scene_left = vapory.Scene( camera_left, objects= objects,included = ["colors.inc", "textures.inc"],) scene_right = vapory.Scene( camera_right, objects= objects,included = ["colors.inc", "textures.inc"],) return scene_left,scene_right
"""Create a (test) dataset of a single sphere flying in a parabolic arc. Outputs a tfrecord in data/arcing_sphere. (Should be run from $ARTIFICE) """ import vapory import numpy as np import matplotlib.pyplot as plt from test_utils import experiment from artifice.utils import dataset debug = False # helpers color = lambda col: vapory.Texture(vapory.Pigment('color', col)) # dataset parameters root = "data/arcing_sphere/" # root dir for fname fps = 30 # frame rate of the video time_step = 1 / float(fps) # time per frame seconds = 5 # number of seconds in the video N = int(seconds / time_step) # number of frames output_formats = {'mp4'} # write to a video fname = root + 'arcing_sphere' # extensions from output_formats image_shape = (512, 512) # image shape num_classes = 2 # including background # physical sphere parameters. 1 povray unit = 1 cm radius = 50 # radius mass = 2 # mass in kilograms
def getScene(self, *, cameraLocation=[100,100,50], cameraTarget=[0,0,0], lightLocation=[100,100,100], lightColor=[1,1,1], backgroundColor=[0,0,0], objectColor=[0.5,0.5,0.5], rotationAxis=None, rotationAngle=None): # POVRay uses a left-handed coordinate system, so we have to flip the Z axis on all geometric vectors cameraLocation[2] = -cameraLocation[2] cameraTarget[2] = -cameraTarget[2] lightLocation[2] = -lightLocation[2] vertices = self.getUniqueVertices() if rotationAxis and rotationAngle: rotationMatrix = rotation_matrix(rotationAxis, rotationAngle) # Z axis must be flipped in vertex coords as well, before the transform vertexArgs = [ len(vertices) ] + [ list(np.dot(rotationMatrix, np.array([x,y,-z]))) for x,y,z in vertices ] else: vertexArgs = [ len(vertices) ] + [ [x,y,-z] for x,y,z in vertices ] # even if there is no rotation we must flip Z axis triangleIndices = self.getTriangleIndicesForUniqueVertices() faceArgs = [ len(triangleIndices) ] + list(map(list, triangleIndices)) normales = np.zeros((len(vertices), 3)) npvertices = np.array(vertices) for v0, v1, v2 in triangleIndices: triangleNormale = np.cross(npvertices[v1,:]-npvertices[v0,:], npvertices[v2,:]-npvertices[v0,:]) triangleNormale /= np.linalg.norm(triangleNormale) triangleArea = np.dot(npvertices[v1,:]-npvertices[v0,:], npvertices[v2,:]-npvertices[v0,:])/2 normales[v0,:] += triangleNormale*triangleArea normales[v1,:] += triangleNormale*triangleArea normales[v2,:] += triangleNormale*triangleArea normales /= np.linalg.norm(normales, axis=1, keepdims=True) # for i in range(len(vertices)): # print(f'Vertex {vertices[i]} has normale {normales[i]} (product {np.dot(vertices[i], normales[i])})') # print(f'{np.dot(vertices[i], normales[i])}') if rotationAxis and rotationAngle: rotationMatrix = rotation_matrix(rotationAxis, rotationAngle) # Z axis must be flipped in vertex coords as well, before the transform normaleArgs = [ len(vertices) ] + [ list(np.dot(rotationMatrix, np.array([x,y,-z]))) for x,y,z in [ normales[i,:] for i in range(len(vertices)) ] ] else: # even if there is no rotation we must flip Z axis normaleArgs = [ len(vertices) ] + [ [x,y,-z] for x,y,z in [ normales[i,:] for i in range(len(vertices)) ] ] # print('Rendering with camera at {} and light at {}'.format(str(cameraLocation), str(lightLocation))) asteroid = vpr.Mesh2(vpr.VertexVectors(*vertexArgs), vpr.NormalVectors(*normaleArgs), vpr.FaceIndices(*faceArgs), vpr.Texture(vpr.Pigment('color', 'rgb', [0.5, 0.5, 0.5]), vpr.Normal('bumps', 0.75, 'scale', 0.0125), vpr.Finish('phong', 0.1) ) ) # vpr.Texture(vpr.Pigment('color', objectColor))) return vpr.Scene( vpr.Camera('location', cameraLocation, 'look_at', cameraTarget, 'sky', [0,0,-1]), objects = [ vpr.LightSource(lightLocation, 'color', lightColor), vpr.Background('color', backgroundColor), asteroid ], included = ["colors.inc", "textures.inc"] # ,defaults = [vpr.Finish( 'ambient', 0.0, 'diffuse', 0.0)] ,global_settings = [ 'ambient_light <0,0,0>' ] )
def plot_frames(beads, sim, ti, tf, savebase, colorid): """ plot frames within the specified time window""" ### define the color for the spheres print 'defining colors' if colorid == "id": sphere_rgbcolor = gen_colors_based_on_id(sim.nbeads, sim.npols, beads.pid) elif colorid == "orient": sphere_rgbcolor = gen_colors_based_on_orient(sim.nbeads, sim.npols, beads.ori) ### create povray settings print 'creating povray settings' sphere_radius, img_widthpx, img_heightpx, povray_includes, \ povray_defaults, sun1, sun2, background, povray_cam, quality \ = gen_img_settings_quality(sim.lx) zi = np.zeros((sim.nbeads), dtype=np.float32) ### set general plot properties os.system("mkdir -p " + savebase) savebase = data_separator.gen_folder_path(savebase, '_', sim.phaseparams) os.system("mkdir -p " + savebase) ### plot the frames for step in range(ti, tf): time = step * sim.dt print 'Step / Total : ', step, tf ### create povray items print 'generating povray item' particles = vapory.Object( \ vapory.Union( \ *[ vapory.Sphere([beads.xi[step, 0, j], beads.xi[step, 1, j],zi[j]], \ sphere_radius, vapory.Texture( \ vapory.Pigment('color', sphere_rgbcolor[j]), \ vapory.Finish('phong',1)) ) for j in range(0, sim.nbeads ) ] ) ) ### generate povray objects print 'generating povray objects' povray_objects = [sun1, sun2, background, particles] ### create the scene scene = vapory.Scene(camera=povray_cam, objects=povray_objects, included=povray_includes, defaults=povray_defaults) ### render image print 'rendering scene' savename = "pov-frame-" + "{0:05d}".format(int(step)) + ".png" scene.render(outfile=savename, width=img_widthpx, height=img_heightpx, \ antialiasing=0.001, quality=quality, remove_temp=True) ### move the image to the correct destination os.system('mv ' + savename + ' ' + savebase) return
def main(): # helpers color = lambda col: vapory.Texture(vapory.Pigment('color', col)) # initial state, in SI units global initial, current initial = {} initial['x1'] = np.array([x1, y1]) / 100. initial['v1'] = np.array([vx1, vy1]) / 100. initial['x2'] = np.array([x2, y2]) / 100. initial['v2'] = np.array([vx2, vy2]) / 100. # Calculate initial acceleration with equations of motion initial['a1'], initial['a2'] = calculate_acceleration( initial['x1'], initial['x2']) current = initial.copy() # Begin setup s1 = experiment.ExperimentSphere(argsf1, vapory.Texture('White_Wood'), semantic_label=1) s2 = experiment.ExperimentSphere(argsf2, vapory.Texture('White_Wood'), semantic_label=2) # experiment exp = experiment.Experiment(image_shape=image_shape, num_classes=num_classes, N=N, data_root=root, output_format=output_formats, fps=fps, mode='L') exp.add_object( vapory.LightSource([0, 5 * image_shape[0], 0], 'color', [1, 1, 1])) exp.add_object( vapory.LightSource([5 * image_shape[0], 0, -2 * image_shape[0]], 'color', [1, 1, 1])) # Background # TODO: make this an actually interesting experiment with a background image. exp.add_object( vapory.Plane([0, 0, 1], 10 * max(r1, r2), vapory.Texture( vapory.Pigment( vapory.ImageMap('png', '"scripts/images/harper.png"')), 'scale', '300', 'translate', [image_shape[0] // 2, 2 * image_shape[1] // 3, 0]))) if do_walls: global walls border = min(r1, r2) walls = np.zeros(4) # top, left, bottom, right walls[:2] = exp.unproject_to_image_plane((border, border))[:2] walls[2:] = exp.unproject_to_image_plane( (image_shape[0] - border, image_shape[1] - border))[:2] walls /= 100. # convert to meters exp.add_object(s1) exp.add_object(s2) if debug: (image, _), _ = exp.render_scene(0) plt.imshow(np.squeeze(image), cmap='gray') plt.show() else: exp.run()
def rendered(self): return vap.Sphere( list(self.body.getPosition()), self._radius, vap.Texture( vap.Pigment('color', self._color if self._color else [1, 0, 1])))
def _generate_objects(representations): objects = [] for rep in representations: if rep['rep_type'] == 'spheres': for i, (x, y, z) in enumerate(rep['options']['coordinates']): r = rep['options']['radii'][i] c = rep['options']['colors'][i] # Generate the shape sphere = vp.Sphere([x, y, z], r, vp.Texture(vp.Pigment('color', hex2rgb(c)))) objects.append(sphere) elif rep['rep_type'] == 'points': # Render points as small spheres for i, (x, y, z) in enumerate(rep['options']['coordinates']): c = rep['options']['colors'][i] s = rep['options']['sizes'][i] if not 'alpha' in rep['options']: t = 1.0 else: t = rep['options']['alpha'][i] # Point = sphere with a small radius sphere = vp.Sphere([x, y, z], s * 0.15, vp.Texture( vp.Pigment('color', 'rgbf', hex2rgb(c) + (1 - t, ))), vp.Interior('ior', 1.0)) objects.append(sphere) elif rep['rep_type'] == 'surface': verts = rep['options']['verts'] faces = rep['options']['faces'] color = rep['options']['color'] triangles = verts.take(faces, axis=0) for v1, v2, v3 in triangles: povt = vp.Triangle( v1.tolist(), v2.tolist(), v3.tolist(), vp.Texture(vp.Pigment('color', hex2rgb(color)))) objects.append(povt) elif rep['rep_type'] == 'cylinders': start = rep['options']['startCoords'] end = rep['options']['endCoords'] colors = rep['options']['colors'] for i, (s, e) in enumerate(zip(start, end)): r = rep['options']['radii'][i] c = rep['options']['colors'][i] t = _get_transparency(rep['options'], i) cylinder = vp.Cylinder( s.tolist(), e.tolist(), r, vp.Texture( vp.Pigment('color', 'rgbf', hex2rgb(c) + (1 - t, )))) objects.append(cylinder) elif rep['rep_type'] == 'lines': start = rep['options']['startCoords'] end = rep['options']['endCoords'] colors = rep['options']['startColors'] for i, (s, e) in enumerate(zip(start, end)): #r = rep['options']['radii'][i] r = 0.02 c = colors[i] t = _get_transparency(rep['options'], i) cylinder = vp.Cylinder( s.tolist(), e.tolist(), r, vp.Texture( vp.Pigment('color', 'rgbf', hex2rgb(c) + (1 - t, )))) objects.append(cylinder) else: raise ValueError("No support for representation rep_type: %s" % rep['rep_type']) return objects
def scene(pack, cmap=None, rot=0, camera_height=0.7, camera_dist=1.5, angle=None, lightstrength=1.1, orthographic=False, pad=None, floater_color=(.6, .6, .6), bgcolor=(1, 1, 1), box_color=(.5, .5, .5), group_indexes=None, clip=False): """ Render a 3D scene. Requires `vapory` package, which requires the `povray` binary. Parameters ---------- cmap : a colormap box_color : Color to draw the box. 'None' => don't draw box. floater_color : Color for floaters. 'None' => same color as non-floaters (use cmap). group_indexes : a list of indexes for each "group" that should remain together on the same side of the box. clip : clip the spheres at the edge of the box. Returns ------- scene : vapory.Scene, which can be rendered using its `.render()` method. """ import vapory import numpy as np try: import matplotlib as mpl import matplotlib.cm as mcm vmin, vmax = min(pack.diameters), max(pack.diameters) sm = mcm.ScalarMappable(norm=mpl.colors.Normalize(vmin, vmax), cmap=cmap) cols = [sm.to_rgba(s) for s in pack.diameters] except ImportError: if not isinstance(cmap, list): raise ValueError( "matplotlib could not be imported, and cmap not recognizeable as a list" ) cols = list(cmap) except TypeError: if not isinstance(cmap, list): raise ValueError( "matplotlib could not convert cmap to a colormap," + " and cmap not recognizeable as a list") cols = list(cmap) if floater_color is not None: ix, _ = pack.backbone() ns, = np.nonzero(~ix) for n in ns: cols[n] = floater_color mod_add = .5 if not clip else 0. rs = np.remainder(pack.rs + mod_add, 1) - mod_add if group_indexes is not None: for ix in group_indexes: xs = pack.rs[ix, :] com = np.mean(xs, axis=0) comdiff = (np.remainder(com + mod_add, 1) - mod_add) - com rs[ix, :] = xs + comdiff if clip: spheres = [] cube = vapory.Box((-.5, -.5, -.5), (.5, .5, .5)) dxs = [-1., 0.] drs = np.array([(dx, dy, dz) for dx in dxs for dy in dxs for dz in dxs]) maxr = 0 for xyz, s, col in zip(rs, pack.diameters, cols): for dr in drs: r = dr + xyz if np.any(abs(r) - s / 2. > .5): # not in the box continue sphere = vapory.Sphere(r, s / 2.) cutsphere = vapory.Intersection( cube, sphere, vapory.Texture(vapory.Pigment('color', col[:3]))) spheres.append(cutsphere) if np.amax(r) > maxr: maxr = np.amax(r) else: spheres = [ vapory.Sphere(xyz, s / 2., vapory.Texture(vapory.Pigment('color', col[:3]))) for xyz, s, col in zip(rs, pack.diameters, cols) ] maxr = np.amax(np.amax(np.abs(rs), axis=1) + pack.diameters / 2.) extent = (-.5, .5) corners = [ np.array((x, y, z)) for x in extent for y in extent for z in extent ] pairs = [(c1, c2) for c1 in corners for c2 in corners if np.allclose(np.sum((c1 - c2)**2), 1) and sum(c1 - c2) > 0] radius = 0.01 cyls, caps = [], [] if box_color is not None: col = vapory.Texture(vapory.Pigment('color', box_color)) cyls = [vapory.Cylinder(c1, c2, 0.01, col) for c1, c2 in pairs] caps = [vapory.Sphere(c, radius, col) for c in corners] light_locs = [[8., 5., -3.], [-6., 6., -5.], [-6., -7., -4.], [10., -5., 7.]] rotlocs = [[ x * np.cos(rot) - z * np.sin(rot), y, z * np.cos(rot) + x * np.sin(rot) ] for x, y, z in light_locs] lights = [ # vapory.LightSource( [2,3,5], 'color', [1,1,1] ), vapory.LightSource(loc, 'color', [lightstrength] * 3) for loc in rotlocs ] cloc = [ np.cos(rot) * camera_dist, camera_dist * camera_height, np.sin(rot) * camera_dist ] # mag = sqrt(sum([d**2 for d in cloc])) # direction = [-v*2/mag for v in cloc] if angle is None: if pad is None: pad = max(pack.diameters) w = sqrt(2) * maxr + pad angle = float(np.arctan2(w, 2 * camera_dist)) * 2 * 180 / np.pi camera = vapory.Camera('location', cloc, 'look_at', [0, 0, 0], 'angle', angle) # vapory.Camera('orthographic', 'location', cloc, 'direction', # direction, 'up', [0,2,0], 'right', [2,0,0]) return vapory.Scene(camera, objects=(lights + spheres + cyls + caps + [vapory.Background("color", bgcolor)]))