def __init__(self, center, radius, color=Color()): self._pp = Plane(Vector(), Vector(), Color()) self._pn = Plane(Vector(), Vector(), Color()) Sphere.__init__(self, center, radius, color) self.set_reflectivity(0.2) self.set_orientation(Vector()) self.set_cosine(1.0)
def __init__(self, center, radius, color = Color()): self._pp = Plane(Vector(), Vector(), Color()) self._pn = Plane(Vector(),Vector(), Color()) Sphere.__init__(self, center, radius, color) self.set_reflectivity(0.2) self.set_orientation( Vector() ) self.set_cosine(1.0)
def __init__(self, center = Vector(0.0,0.0,0.0), radius = 1.0, color = Color(), orientation = Vector(0.0,1.0,0.0)): Sphere.__init__(self, center, radius, color) self.set_orientation(orientation) self.set_reflectivity(0.9,0.1)
def loadObjects(self): print("____Load standard Objects____") self.objects = [ Sphere(np.array([0, 5, 1]), 1, self.rot), Sphere(np.array([-1.5, 2, 1]), 1, self.gruen), Sphere(np.array([1.5, 2, 1]), 1, self.blau), Plane(np.array([0, -2, 5]), np.array([0, 1, 0]), self.grey), Rectangle(np.array([-1.5, 2, 1]), np.array([1.5, 2, 1]), np.array([0, 5, 1]), self.gelb) ]
def testNormal(self): phongRed = Phong(Point3(.8, .1, .1), Point3(.9, .9, .9), 2.0) testSphere = Sphere(Point3(1.0, -3.0, 0.0), 1.0, phongRed) intersection1 = testSphere.findIntersection(Point3(1.0, 0, 0), Vector3(0, -1, 0)) normal1 = testSphere.getNormal(intersection1) self.assertTrue(normal1.x == 0.0) self.assertTrue(normal1.y == 1.0) self.assertTrue(normal1.z == 0.0)
class ShapeTester: print('welcome to Shape Tester') print('Please choose \'box\', \'pyramid\', or \'sphere\'') while True: shape = input('>') if shape == 'box': print('You Chose Box') width = int(input('choose a width: ')) height = int(input('choose a height: ')) length = int(input('choose a length: ')) b1 = Box(length, width, height) print('The Volume is: %f' % b1.getVolume()) print('The Surface Area is %f' % b1.getSurfArea()) elif shape == 'pyramid': print('You Chose Pyramid') width = int(input('choose a width: ')) height = int(input('choose a height: ')) length = int(input('choose a length: ')) p1 = Pyramid(length, width, height) print('The Volume is: %f' % p1.getVolume()) print('The Surface Area is %f' % p1.getSurfArea()) elif shape == 'sphere': print('You Chose Sphere') radius = int(input('choose a radius: ')) s1 = Sphere(radius) print('The Volume is: %f' % s1.getVolume()) print('The Surface Area is: %f' % s1.getSurfArea()) else: print('incorrect syntax try again')
class ShapeTester: print('Welcome to the Shape Tester') print('Please type \'Box\', \'Sphere\', or \'Pyramid\'') while True i= input('>') if i == 'Box': print('Alright, let us start with a box.') width= int(input("Please enter a width:")) length= int(input("Please input a length: ")) height= int(input("Please input a height: ")) b1=Box(width,length,height) print('Volume: %s' % b1.getVolume()) print('Surface Area: %s' % b1.getSA()) elif i == 'Sphere': print('Alright, let us start with a sphere.') radius = int(input("Please enter a radius: ")) s1=Sphere(radius) print('Volume: %s' % s1.getVolume()) print('Surface Area: %s' % s1.getSA()) elif i == 'Pyramid': print('Alright, let us start with a pyramid.') width= int(input("Please enter a width:")) length= int(input("Please input a length: ")) height= int(input("Please input a height: ")) p1=Pyramid(length,width,height) print('Volume: %s' % p1.getVolume()) print('Surface Area: %s' % p1.getSA()) else: print('mmmmmmm, try again.')
def __init__(self, width, height): self.width = width self.height = height self.eye_x = self.eye_y = self.eye_z = 0 self.radius = 100 self.phi = 0.0 self.theta = 90.0 self.up_x = 0 self.up_y = 1 self.up_z = 0 self.scale = 1 self.surface = Surface(lambda x, y: 50 * (sin(x * pi / 180) + cos(y * pi / 180))) self.light = Light() self.cube = Cube(10) self.sphere = Sphere(20) self.enable_light_source = True
def randomSphereScene(): world = HitableList() # Bottom "plane" world.add(Sphere(Vec3(0,-1000,0), 1000, Lambertian(Vec3(0.5, 0.5, 0.5)))) # three large spheres world.add(Sphere(Vec3(0, 1, 0), 1.0, Dielectric(1.5))) world.add(Sphere(Vec3(-4, 1, 0), 1.0, Lambertian(Vec3(0.4, 0.2, 0.1)))) world.add(Sphere(Vec3(4, 1, 0), 1.0, Metal(Vec3(0.7, 0.6, 0.5), 0.0))) # numerous small spheres i = 1 for a in range(-11, 11): for b in range(-11, 11): chooseMat = random.random() center = Vec3(a + 0.9*random.random(), 0.2, b + 0.9*random.uniform(0,1)) if (center - Vec3(4, 0.2, 0)).length() > 0.9: if chooseMat < 0.8: # diffuse albedo = Vec3.random() * Vec3.random() world.add(Sphere(center, 0.2, Lambertian(albedo))) elif chooseMat < 0.95: # metal albedo = random.uniform(.5, 1) fuzz = random.uniform(0, .5) world.add(Sphere(center, 0.2, Metal(albedo, fuzz))) else: # glass world.add(Sphere(center, 0.2, Dielectric(1.5))) return world
def calculateSphere(self, problems: dict) -> dict: S = Sphere() solutionDict = {} for key in list(problems.keys()): task = problems[key] valueType = next(iter(task.keys())) value = next(iter(task.values())) if valueType == 'r': S.radius = value elif valueType == 'Ao': S.Ao = value elif valueType == 'ERROR': S.error = True else: S.volume = value solutionDict[key] = S.getValues() return solutionDict
def load_sphere(line_group): """ Reads data from source and creates a Sphere object """ global shape_list position = [float(x) for x in line_group[0].split()] radius = [float(x) for x in line_group[1].split()] radius = radius[0] opacity = [float(x) for x in line_group[2].split()] color = [float(x) for x in line_group[3].split()] sphere = Sphere(position, radius, opacity, color) shape_list.append(sphere) print "sphere created"
def testIntersection(self): phongRed = Phong(Point3(.8, .1, .1), Point3(.9, .9, .9), 2.0) testSphere = Sphere(Point3(0.0, 3.0, 0.0), 1.0, phongRed) intersection1 = testSphere.findIntersection(Point3(0, 0, 0), Vector3(0, 1, 0)) self.assertTrue(intersection1.x == 0) self.assertTrue(intersection1.y == 2.0) self.assertTrue(intersection1.z == 0) intersection2 = testSphere.findIntersection(Point3(0, 8, 0), Vector3(0, -.5, 0)) self.assertTrue(intersection2.x == 0) self.assertTrue(intersection2.y == 4.0) self.assertTrue(intersection2.z == 0) intersection3 = testSphere.findIntersection(Point3(5, 3, 0), Vector3(-10, 0, 0)) self.assertTrue(intersection3.x == 1.0) self.assertTrue(intersection3.y == 3.0) self.assertTrue(intersection3.z == 0) intersection4 = testSphere.findIntersection(Point3(0, 3, -5), Vector3(0, 0, 2)) self.assertTrue(intersection4.x == 0.0) self.assertTrue(intersection4.y == 3.0) self.assertTrue(intersection4.z == -1.0) intersection5 = testSphere.findIntersection(Point3(0, 3, -5), Vector3(0, 0, -2)) self.assertTrue(intersection5.x == float('inf')) self.assertTrue(intersection5.y == float('inf')) self.assertTrue(intersection5.z == float('inf'))
def draw(self, photo, pixels): self.pixels = pixels self.texture = photo self.sphere = Sphere(500, 20, 20) self.camMat = CameraMatrix((700, 1, 1), (1, 1, 1)) self.projMat = ProjectionMatrix(math.pi * (2.0 / 3.0), 800 / 600, 100, 1000) self.sphere.transform(self.camMat, self.projMat) self.triangles = self.sphere.getTriangles() for triangle in self.triangles: self.currTriangle = triangle self.getpoints(triangle) self.sorted = sorted(self.points, key=lambda tup: tup[1], reverse=True) self.fill()
def Refraction(ray, air_ind, glass_ind, env="air"): sphere = Sphere(position=Vector(2, 2, 2), radius=1.0) print "ray.ray_origin", ray.origin print "ray.ray_dir", ray.ray_dir t_min = sphere.get_intersect(ray_origin=ray.origin, ray_dir=ray.ray_dir.normalize()) print "t_min", t_min intersect_point = ray.origin.clone().add( (ray.ray_dir.normalize().clone()).constant_multiply(t_min * 0.001)) print "intersect_point", intersect_point normal_vector = sphere.surface_normal(point=intersect_point.clone(), ray_origin=ray.origin.clone(), ray_dir=ray.ray_dir.clone()) print "normal_vector", normal_vector c_1 = normal_vector.normalize().clone().dot( ray.ray_dir.normalize().clone()) if env == "air": n = air_ind / glass_ind c_1 = -c_1 print "n", n # print "c_1", c_1 else: n = glass_ind / air_ind print "n", n normal_vector = normal_vector.normalize().constant_multiply(-1) k = (1 - (n**2) * (1 - (c_1)**2)) if k < 0: return "K is negative" c_2 = math.sqrt(k) part_1 = ray.ray_dir.normalize().constant_multiply(n) part_2 = normal_vector.normalize().clone().constant_multiply( (n * c_1 - c_2)) ref_ray_dir = (part_1.clone().add(part_2.clone())).normalize() # print "ref_ray_dir", ref_ray_dir ref_ray = Ray(origin=intersect_point, ray_dir=ref_ray_dir) # print "env", env # print "n", n return ref_ray
def addSphere(self): #Adds a renderobject from proper data, if the data is not proper, the program will not do anything d = self.getData() if len(d) == 0: messagebox.showerror( "Error", "A value-error has appeared. Enter proper values") else: rnge = d[6] rgb = [d[7], d[8], d[9]] sphere = Sphere(d[0], d[1], d[2], d[3]) renderObj = TkinterRender(self.__mainCanvas, sphere, d[4], d[5], rgb, rnge) self.__renderObjects.append(renderObj) self.objectSetup()
def test_get_intersect(self): S = Sphere(Vector(5.0, 0.0, 0.0)) self.assertEqual( S.get_intersect(Vector(0.0, 0.0, 0.0), Vector(1.0, 0.0, 0.0)), 4.0) S = Sphere(Vector(5, 0.0, -1.0)) t = S.get_intersect(Vector(0.0, 0.0, 0.0), Vector(1.0, 0.0, 0.0)) self.assertTrue((5.0 - abs(t)) <= 0.0001)
def init_spheres(self): for s in range(len(self.spheres)): random_position = glm.vec3([ random.random() - 0.5, random.random() - 0.5, random.random() - 0.5 ]) * 7500.0 random_radius = 200 + (800 * random.random()) random_color = glm.vec3( [random.random(), random.random(), random.random()]) random_opacity = random.random() self.spheres[s] = (Sphere(random_position, random_radius, random_color, random_opacity))
def __init__(self, coordinates=None, particle=None, instrument=None, **kwargs): ''' Keywords ---------- coordinates : numpy.ndarray [3, npts] array of x, y and z coordinates where field is calculated particle : Particle Object representing the particle. Default: Sphere() instrument : Instrument Object resprenting the light-scattering instrument ''' self.coordinates = coordinates self.particle = particle or Sphere(**kwargs) self.instrument = instrument or Instrument(**kwargs)
def _sphere_with_values(self, name): s = Sphere() # TODO: feels like we should have a generic function for parsing # gherkin tables digit = re.compile(r'^[-+]?\d*\.?\d+$') tuple3 = re.compile(r'^\([-+]?\d*\.?\d+\s*,\s*[-+]?\d*\.?\d+\s*,\s*' r'[-+]?\d*\.?\d+\)$') subattr = re.compile(r'.*\..*') scaling = re.compile(r'^scaling\([-+]?\d*\.?\d+\s*,\s*[-+]?\d*\.?\d+\s*,' r'\s*[-+]?\d*\.?\d+\)$') for row in self.table: attr = str(row[0]) obj = s print(obj, attr) while subattr.match(attr): print(attr.split('.')) obj = getattr(obj, attr.split('.', 2)[0]) attr = attr.split('.', 2)[1] print(obj, attr) value = row[1] if digit.match(value): print("DIGIT", attr, float(value)) setattr(obj, attr, float(value)) if tuple3.match(value): values = value.replace("(", "").replace(")", "").split(',') print("TUPLE3", attr, float(values[0]), float(values[1]), float(values[2])) setattr( obj, attr, Colour(float(values[0]), float(values[1]), float(values[2]))) if scaling.match(value): values = value.split('(')[1].replace("(", "").replace(")", "").\ split(',') print( "SCALING", attr, Transformation.Scaling(float(values[0]), float(values[1]), float(values[2]))) setattr( obj, attr, Transformation.Scaling(float(values[0]), float(values[1]), float(values[2]))) setattr(world, name, s)
def sphere(self): print 'Type in the variable you already know.' try: self.r = float(raw_input('r = ')) except (ValueError): self.r = 0 try: self.d = float(raw_input('d = ')) except (ValueError): self.d = 0 try: self.V = float(raw_input('V = ')) except (ValueError): self.V = 0 try: self.M = float(raw_input('O = ')) except (ValueError): self.M = 0 try: self.U = float(raw_input('U = ')) except (ValueError): self.U = 0 variables = {} if self.r != 0: variables['r'] = self.r if self.d != 0: variables['d'] = self.d if self.V != 0: variables['V'] = self.V if self.M != 0: variables['O'] = self.M if self.U != 0: variables['U'] = self.U return Sphere(variables)
class ShapeTester: print('Welcome to ShapeTester') while True: print('Please choose \'box\', \'pyramid\', or \'sphere\'') width = 0 length = 0 height = 0 radius = 0 t = input('>') if t == 'box': print('You chose \'box\'!') width = int(input('Choose a width: ')) length = int(input('Choose a length: ')) height = int(input('Choose a height: ')) b1 = Box(length, width, height) print('Volume: %f' % b1.getVolume()) print('Surface Area: %f' % b1.getSurf()) elif t == 'pyramid': print('You chose \'pyramid\'!') length = int(input('Choose length: ')) width = int(input('Choose width: ')) height = int(input('Choose height of pyramid: ')) p1 = Pyramid(length, width, height) print('Volume: %f' % p1.getVolume()) print('Surface Area: %f' % p1.getSurf()) elif t == 'sphere': print('You chose \'sphere\'!') radius = int(input('Chose radius: ')) s1 = Sphere(radius) print('Volume: %f' % s1.getVolume()) print('Surface Area: %f' % s1.getSurf()) print('Circumference: %f' % s1.getCircum()) else: print('Incorrect syntax, try again')
from Vector import Vector from Ray import Ray from Triangle import Triangle from Sphere import Sphere from Triangle import Triangle from Screen2D import Screen2D from Viewport import Viewport from PointLight import PointLight import math import sys ray = Ray(origin=Vector(0.0, 0.0, 0.0), ray_dir=Vector(1.0, 1.0, 0.5)) sphere = Sphere(position=Vector(2, 2, 2), radius=1.0) t_min = sphere.get_intersect(ray_origin=Vector(0.0, 0.0, 0.0), ray_dir=Vector(1.0, 1.0, 0.5)) print t_min intersect_point = ray.origin.clone().add( ray.ray_dir.clone().constant_multiply(t_min)) normal_vector = sphere.surface_normal(point=intersect_point.clone(), ray_origin=ray.origin.clone(), ray_dir=ray.ray_dir.clone()) # print "normal_vector", normal_vector # print "ray_dir", ray.ray_dir # print "ray_dir_normalize", ray.ray_dir.normalize() # print "intersect_point", intersect_point def Refraction(ray, air_ind, glass_ind, env="air"): sphere = Sphere(position=Vector(2, 2, 2), radius=1.0) print "ray.ray_origin", ray.origin print "ray.ray_dir", ray.ray_dir
class Drawer: def __init__(self, raster): self.raster = raster self.sphere = None self.camMat = None self.projMat = None self.sorted = None self.point = None self.points = None self.triangles = None self.currTriangle = None self.texture = None self.pixels = None self.color = (174,198,207) def draw(self, photo, pixels): self.pixels = pixels self.texture = photo self.sphere = Sphere(500, 20, 20) self.camMat = CameraMatrix((700, 1, 1), (1, 1, 1)) self.projMat = ProjectionMatrix(math.pi * (2.0 / 3.0), 800 / 600, 100, 1000) self.sphere.transform(self.camMat, self.projMat) self.triangles = self.sphere.getTriangles() for triangle in self.triangles: self.currTriangle = triangle self.getpoints(triangle) self.sorted = sorted(self.points, key=lambda tup: tup[1], reverse=True) self.fill() def getpoints(self, tr): x1 = int((tr.v1.p1[0])*400+400) y1 = int(-(tr.v1.p1[1])*300+300) x2 = int((tr.v2.p1[0]) * 400 + 400) y2 = int(-(tr.v2.p1[1]) * 300 + 300) x3 = int((tr.v3.p1[0]) * 400 + 400) y3 = int(-(tr.v3.p1[1]) * 300 + 300) self.points=((x1,y1), (x2,y2), (x3,y3)) def interpolate(self, p): p1 = (p[0]/float(400)-1, 1-(p[1]/float(300))) xVertex = self.currTriangle.getBestScaleVertex(0) yVertex = self.currTriangle.getBestScaleVertex(1) xscale =float(xVertex.t[0])/float(xVertex.p1[0]) yscale =float(yVertex.t[1])/float(yVertex.p1[1]) x = p1[0] * xscale y = p1[1] * yscale imgX = x*(self.texture.size[0]) if(imgX == self.texture.size[0]): imgX -= 1 imgY = (y*self.texture.size[1]) if (imgY == self.texture.size[1]): imgY -= 1 return int(imgX), int(imgY) def putpixel(self, x, y, val): p = self.interpolate((x, y)) try: r,g,b = self.pixels[p[0], p[1]] except IndexError: r = 127 g = 127 b = 127 self.raster.put('#%02x%02x%02x' % (r,g,b), (x, y)) def fill(self): n = len(self.points) k = 0 ymax = self.sorted[0][1] ymin = self.sorted[len(self.sorted) - 1][1] aet = ActiveEdgeTable() for y in range(ymax, ymin + 1, -1): while k <= n and self.sorted[k][1] == y: i = self.points.index(self.sorted[k]) if self.points[(i - 1) % n][1] < self.points[i][1]: aet.add(self.points[i][0], self.points[i][1], self.points[(i - 1) % n][0], self.points[(i - 1) % n][1]) elif self.points[(i - 1) % n][1] > self.points[i][1]: aet.removeEdge(self.points[(i - 1) % n][0], self.points[(i - 1) % n][1], self.points[i][0], self.points[i][1]) if self.points[(i + 1) % n][1] < self.points[i][1]: aet.add(self.points[i][0], self.points[i][1], self.points[(i + 1) % n][0], self.points[(i + 1) % n][1]) elif self.points[(i + 1) % n][1] > self.points[i][1]: aet.removeEdge(self.points[(i + 1) % n][0], self.points[(i + 1) % n][1], self.points[i][0], self.points[i][1]) k = k + 1 j = 0 aet.sort() while (j <= len(aet.edges) - 2): for xx in range(int(math.ceil(aet.edges[j].x)), int(round(aet.edges[j + 1].x))): self.putpixel(xx, y, self.color) j = j + 2 aet.remove(y) aet.update()
def __init__(self, blobFileName, garnetProfile, rockCompo, rockVolume, sampleName, numBins=0): self.composition = rockCompo #This is a list of ComponentMol objects that define the rock composition self.grtProfile = garnetProfile #This is the CompoProfile object that is a half profile that defines the zoning in the garnet self.rockVol = rockVolume #Now need to open up the blob file to build the crystal list blobDF = pd.read_excel( blobFileName ) #Assumes that formatting has not changed from default blob output self.name = sampleName self.crystalList = [] #Empty list to fill with Shape entries blobDF = blobDF.dropna( ) #Sometimes empty rows at the end mess up calculations #Choose temperature and pressure range: title = "PT range" msg = "Please provide min and max temperature and pressure" fieldNames = ["Tmin", "Tmax", "Pmin", "Pmax"] fieldValues = easygui.multenterbox(msg, title, fieldNames) # make sure that none of the fields was left blank # Gotta make things a little bit idiot proof while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) self.T1 = int(fieldValues[0].strip()) self.T2 = int(fieldValues[1].strip()) self.P1 = int(fieldValues[2].strip()) self.P2 = int(fieldValues[3].strip()) #Ask user to choose if using spheres or ellipsoids msg = "Are garnets spheres or ellipsoids?" title = "" choices = ["Sphere", "Ellipsoid"] reply = "Sphere" #Ellipsoid doesnt do much atm # reply = easygui.buttonbox(msg,title,choices) #reply = "Sphere" #Only works for Spheres right now, need to think about size independent growth of ellipsoids if (reply == choices[0]): volume = list(blobDF['Volume (mm^3)']) for i in range(len(volume)): #If spheres, it will recalculate the radius from the volume #if not math.isnan(volume[i]): thisRad = (volume[i] * 3 / (4 * math.pi))**(1. / 3) self.crystalList.append(Sphere(thisRad)) elif (reply == choices[1]): #If ellipsoid it uses the PEllipsoid data # #It should be that rad1 > rad2 > rad3 # rad1 = list(blobDF['PEllipsoid Rad1 (mm)']) # rad2 = list(blobDF['PEllipsoid Rad2 (mm)']) # rad3 = list(blobDF['PEllipsoid Rad3 (mm)']) # for i in range(len(rad1)): # if not math.isnan(rad1[i]): # self.crystalList.append(Ellipsoid(rad1[i],rad2[i],rad3[i])) #Average out the ratios so all ellipsoids are the same shape and grow with the same dimensions avgEllipsoid = self.getAvgEllipsoid(blobDF) volume = list(blobDF['Volume (mm^3)']) for i in range(len(volume)): #Need to rescale the avg ellipsoid to fit the volume of each garnet #if not math.isnan(volume[i]): ratioAB = avgEllipsoid.aAx / avgEllipsoid.bAx ratioBC = avgEllipsoid.bAx / avgEllipsoid.cAx thisA = ((3 * ratioAB**2 * ratioBC * volume[i]) / (math.pi * 4))**(1 / 3) thisB = thisA / ratioAB thisC = thisB / ratioBC self.crystalList.append(Ellipsoid(thisA, thisB, thisC)) else: print("Error: No option chosen") return #Okay now we need to stretch the garnet profile to fit with the long dimension of the ellipsoid or the radius of the sphere #This is so the profile matches up with the biggest garnet self.quickSortCrystals(0, len(self.crystalList) - 1) self.numCrystals = [] #Added support for binning but I dont think its needed #Still the code is here if (numBins > 0): #Break things up into seperate bins binSize = ( self.crystalList[0].getDim() - self.crystalList[len(self.crystalList) - 1].getDim()) / numBins newCrystalList = [] hiBin = self.crystalList[0].getDim() #make new crystalList with a crystalSize equal to he highest radius in that bin interval for i in range(numBins): thisInterval = hiBin - i * binSize #each value in bins represent the upperbounds of that bin nextInterval = hiBin - (i + 1) * binSize numInBin = 0 biggestInBin = Sphere(0) for crystal in self.crystalList: if crystal.getDim() <= thisInterval and crystal.getDim( ) > nextInterval: numInBin += 1 if crystal.getDim() > biggestInBin.getDim(): biggestInBin = crystal #the biggest in the bin is the crystal that gets put in the new crystalList if numInBin > 0: newCrystalList.append(biggestInBin) self.numCrystals.append(numInBin) self.crystalList = newCrystalList travRad = max( self.grtProfile.x ) #Radius of the garnet measured in the microprobe profile minDiff = sys.float_info.max # for i in range (len(self.crystalList) - 1): # radDiff = self.crystalList[i].getDim()-self.crystalList[i+1].getDim() # if radDiff > 0: # minDiff = min(radDiff,minDiff) #This makes sure that a shell is not bigger than the difference in radius between any two garnets self.shellThick = min(minDiff, self.crystalList[0].getDim() / NUM_SHELLS) #Instead of stretching, lets try extrapolating the core inwards: radAdd = self.crystalList[0].getDim() - travRad msg = "Extrapolate to core or stretch profile?" title = "" choices = ["Extrapolate", "Stretch"] reply = easygui.buttonbox(msg, title, choices) if radAdd > 0 and reply == choices[ 0]: #In case the biggest garnet has a radius smaller than traverse length self.grtProfile.extrapCore(CORE_AVG_INDEX, radAdd) else: scaleFactor = self.crystalList[0].getDim( ) / travRad #The scaling factor to convert the x values in grtProfile to be the same size as the radius or a axis of ellipsoid for i in range(len(self.grtProfile.x)): #Rescale x self.grtProfile.x[i] = scaleFactor * self.grtProfile.x[i] self.grtProfile.scipyInterp( ) #Initialize the interpolated numpy arrays self.garnetList = [ ] #This is what we will be working with for the most part, it is where all the garnets will grow and be stored
from Sphere import Sphere from Cuboid import Cuboid radius = int(input()) scolor = str(input()) l = float(input()) w = float(input()) h = float(input()) ccolor = str(input()) sphere = Sphere(radius) sphere.setColor(scolor) cuboid = Cuboid(l, w, h) cuboid.setColor(ccolor) print("{}({}),{},{}".format(sphere.__str__(), sphere.getRadius(), round(sphere.getVolume(), 1), sphere.getColor())) print("{}({},{},{}),{},{}".format(cuboid.__str__(), int(cuboid.getLength()), int(cuboid.getWidth()), int(cuboid.getHeight()), round(cuboid.getVolume(), 1), cuboid.getColor()))
sphereRadius = .5 sphereMaterialColor = Vector(255, 255, 255) sphere2MaterialColor = Vector(0,255,255) sphereMaterialSpecularColor = Vector(0, 255, 255) sphereMaterialSpecularStrength = .5 sphereMaterial = Material( sphere2MaterialColor, sphereMaterialSpecularColor, sphereMaterialSpecularStrength,.0) sphereMaterial2 = Material( Vector(64, 64, 64), sphereMaterialSpecularColor, sphereMaterialSpecularStrength, .5) #sphereMaterial3 = Material( #Vector(0, 255, 0), sphereMaterialSpecularColor, sphereMaterialSpecularStrength, 0) sphere = Sphere(sphereMaterial2, sphereCenter, sphereRadius) #sphere2 = Sphere(sphereMaterial, Point3D(.2, .2, .5), .1) #sphere3 = Sphere(sphereMaterial2, Point3D(-.2, -.1, .5), .1) #sphere4 = Sphere(sphereMaterial3, Point3D(0, -.1, .5), .1) lights = [light, light3] objects = [sphere] #objects = [sphere, sphere2, sphere3, sphere4] #Now loop over every pixel in our frame #For every pixel #Figure out where in camera space that pixel is #Then figure out where in world space that pixel is #Then shoot a ray from the world space origin of the camera to that world space location #Then loop over each object in the scene #For ever object that ray collides with
import matplotlib.pyplot as plt from SphereCylinder import SphereCylinder from Sphere import Sphere a = SphereCylinder() b = Sphere() xa, ya = a.get_points(0) xb, yb = b.get_points(0) plt.plot(xa,ya, 'ro') plt.plot(xb,yb, 'bo') plt.xlabel('X coordinates') plt.ylabel('Y coordinates') plt.show()
import random from PIL import Image from Sphere import Sphere from Ray import Ray from ViewPort import ViewPort #create a viewport and image v = ViewPort(500,500) im = Image.new("RGB",(v.w,v.h)) pix = im.load() #define a sphere radius = 1.0 center = np.array([0,0, -2.5]) s = Sphere(radius,center,np.array([255,0,0])) #define a ray ray = Ray(np.array([0,0,0]),np.array([0,0,-1])) # define a light direction ldir = np.array([0,0,1]) #light direction kd = 0.75 #reflectivity illum = 1.0 #light luminosity def phongDiffuse(x,n,mat): """Implements a Phong-style diffuse shading function Args: x: is a point on a surface
from Sphere import Sphere from Cuboid import Cuboid spRadius = float(input()) spColor = str(input()) cuLength = float(input()) cuWidth = float(input()) cuHeight = float(input()) cuColor = str(input()) sp = Sphere(spRadius, spColor) cu = Cuboid(cuLength, cuWidth, cuHeight, cuColor) print( str(sp) + ":(%d),%.1f,%s" % (sp.getRadius(), sp.getVolume(), sp.getColor())) print( str(cu) + ":(%d,%d,%d),%.1f,%s" % (cu.getLength(), cu.getWidth(), cu.getHeight(), cu.getVolume(), cu.getColor()))
if __name__ == '__main__': from Sphere import Sphere import matplotlib.pyplot as plt # Create coordinate grid for image x = np.arange(0, 201) y = np.arange(0, 201) xv, yv = np.meshgrid(x, y) xv = xv.flatten() yv = yv.flatten() zv = np.zeros_like(xv) coordinates = np.stack((xv, yv, zv)) # Place a sphere in the field of view, above the focal plane particle = Sphere() particle.r_p = [125, 75, 100] particle.a_p = 0.5 particle.n_p = 1.45 # Form image with default instrument instrument = Instrument() instrument.magnification = 0.135 instrument.wavelength = 0.447 instrument.n_m = 1.335 k = instrument.wavenumber() # Use Generalized Lorenz-Mie theory to compute field kernel = GeneralizedLorenzMie(coordinates, particle, instrument) field = kernel.field() # Compute hologram from field and show it field *= np.exp(-1.j * k * particle.z_p) field[0, :] += 1.
measure = input("What shape do you want? \n1. Box \n2. Sphere \n3. Pyramid \n") if measure == 1: l = input("What is the length: ") h = input("What is the height: ") w = input("What is the width: ") #print ("Box mode has been selected.") #box1 = Box(4, 2000, 2) box1.displayBox() box1.calcVal() box1.calcSur if measure == 2: r = input("What is the radius: ") sphere1 = Sphere(r) sphere1.displaySphere() sphere1.calcVol() sphere1.calcSur() if measure == 3: l = input("What is the length: ") h = input("What is the height: ") w = input("What is the width: ") pyramid1 = Pyramid(l, h, w) pyramid1.displayPyramid() pyramid1.calcVol() pyramid1.calcSur() else: print "Type the numbers 1, 2, or 3 next time"
if __name__ == '__main__': from Sphere import Sphere import matplotlib.pyplot as plt from time import time # Create coordinate grid for image x = np.arange(0, 201) y = np.arange(0, 201) xv, yv = np.meshgrid(x, y) xv = xv.flatten() yv = yv.flatten() zv = np.zeros_like(xv) coordinates = np.stack((xv, yv, zv)) # Place a sphere in the field of view, above the focal plane particle = Sphere() particle.r_p = [150, 150, 200] particle.a_p = 0.5 particle.n_p = 1.45 # Form image with default instrument instrument = Instrument() instrument.magnification = 0.135 instrument.wavelength = 0.447 instrument.n_m = 1.335 k = instrument.wavenumber() # Use Generalized Lorenz-Mie theory to compute field kernel = GeneralizedLorenzMie(coordinates, particle, instrument) kernel.field() start = time() field = kernel.field() print("Time to calculate: {}".format(time() - start))
f = hf.normalize((np.subtract(c, e))) #z coordinate s = hf.normalize(np.cross(f, up)) #x coordiante u = np.cross(s, f) #y coordinate #intern camera parameters alpha = np.deg2rad(FOV) / 2.0 viewheight = 2 * np.tan(alpha) #heigth of viewport viewWidth = ASPRATIO * viewheight #width of viewport pixelWidth = viewWidth / WIDTH #width of a pixel pixelHeigth = viewheight / HEIGHT #height of a pixel """init scene""" objectList = [] if MODE == 6: objectList.append( Sphere(hf.cVector(0, 5, 20), 2, mat(hf.cVector(0, 0, 255), 32, 1, 0.7, 0.1))) objectList.append( Sphere(hf.cVector(-1, 1, 5), 0.2, mat(hf.cVector(255, 100, 0), 1, 0.2, 0.3, 0.4))) objectList.append( Sphere(hf.cVector(-1, -4, 3), 1, mat(hf.cVector(255, 70, 30), 1, 0.2, 0.3, 0.4))) objectList.append( Sphere(hf.cVector(-1, 1, 2), 0.2, mat(hf.cVector(30, 240, 24), 1, 0.2, 0.3, 0.4))) objectList.append( Sphere(hf.cVector(4, 2, 10), 3, mat(hf.cVector(100, 0, 255), 20, 0.6, 0.9, 0.1))) objectList.append( Triangle(hf.cVector(1, 4, 20), hf.cVector(3, -6, 20), hf.cVector(-2.5, -2, 20),
def main(): try: fps = 50 surface = pygame.display.set_mode((600, 600)) pygame.init() origin = (surface.get_width() / 2, surface.get_height() / 2) theta = 1 step = math.pi / 180 center_x = surface.get_width() / 2 center_y = surface.get_height() / 2 # Cube( surface, color, center3d, size) spheres = ( Fire(surface, pygame.Rect(100, 100, 400, 200), 2), Sphere(surface, (100, 0, 0), Vec3d(-1.5, -1.5, -1.5), Vec3d(1, 1, 1)), #Sphere(surface, (100, 0, 0), Vec3d(0, 0, 0), Vec3d(1, 1, 1)), #Sphere(surface, (100, 0, 0), Vec3d(1.5, 1.5, 1.5), Vec3d(1, 1, 1)), Circle(surface, (100, 0, 0), Vec3d(1.5, -1.5, -1.5), Vec3d(1, 1, 1)), Tree(surface, pygame.Color(0, 100, 100), Vec2d(300, 500), 5, 50), Tree(surface, pygame.Color(0, 100, 100), Vec2d(330, 500), 5, 100), Starfield(surface, stars=100, depth=10), InfoRenderer(surface, pygame.Color(0, 255, 0), pos=Vec2d(100, 100), size=10), ScrollText(surface, "Dolor Ipsum Dolor uswef", 400, pygame.Color(255, 255, 0)), SinusText(surface, "Dolor Ipsum Dolor uswef", 200, 30, 2, pygame.Color(0, 255, 255)), ) clock = pygame.time.Clock() size_angle = 0 size_angle_step = math.pi / 720 cg = ColorGradient(0.0, 0.05, 0.05) background_gradient = GradientBackground(surface) # for 3d projection fov = 2 viewer_distance = 256 pause = False while True: clock.tick(fps) events = pygame.event.get() for event in events: if event.type == pygame.QUIT: sys.exit(0) keyinput = pygame.key.get_pressed() if keyinput is not None: # print keyinput if keyinput[pygame.K_ESCAPE]: sys.exit(1) #if keyinput[pygame.K_z]: # theta[2] += math.pi / 180 #if keyinput[pygame.KMOD_SHIFT | pygame.K_z]: # theta[2] -= math.pi / 180 #if keyinput[pygame.K_x]: # theta[0] += math.pi / 180 #if keyinput[pygame.KMOD_SHIFT | pygame.K_x]: # theta[0] -= math.pi / 180 #if keyinput[pygame.K_y]: # theta[1] += math.pi / 180 #if keyinput[pygame.KMOD_SHIFT | pygame.K_y]: # theta[1] -= math.pi / 180 if keyinput[pygame.K_UP]: viewer_distance += 1 if keyinput[pygame.K_DOWN]: viewer_distance -= 1 if keyinput[pygame.K_PLUS]: fov += .1 if keyinput[pygame.K_MINUS]: fov -= .1 if keyinput[pygame.K_p]: pause = not pause if keyinput[pygame.K_r]: viewer_distance = 256 fov = 2 if pause is not True: surface.fill((0, 0, 0, 255)) background_gradient.update() for thing in spheres: if type(thing) == InfoRenderer: thing.update(lines=("viewer_distance : %f" % viewer_distance, "fov: %f" % fov)) continue elif type(thing) == Tree: thing.update() continue elif type(thing) in ( Sphere, Circle, ): # rotate thing.rotate(dx=theta, dy=theta, dz=0.0, offset2d=Vec2d(0, 0)) theta += step * 16 # color changing color = cg.get_color() thing.set_color(color=color) # size wobbling # size_angle += size_angle_step # thing.set_size(0.5 + math.sin(size_angle) * 0.125) # draw thing.update(viewer_distance=viewer_distance, fov=fov) continue elif type(thing) in ( SinusText, ScrollText, ): thing.update() elif type(thing) == Tree: thing.update(center=Vec2d(0, 0), viewer_distance=viewer_distance, fov=fov) else: thing.update() pygame.display.flip() except KeyboardInterrupt: print('shutting down')
self.camera.direction = self.camera.direction.modulus_add(Vector(0, 0.08, 0), Vector(2 * pi, 2 * pi, 2 * pi)) print(self.camera.direction) if 's' in pressed_keys: self.camera.direction = self.camera.direction.modulus_add(Vector(0, -0.08, 0), Vector(2 * pi, 2 * pi, 2 * pi)) if 'Up' in pressed_keys: self def on_key_press(event): pressed_keys.add(event.keysym) def on_key_release(event): pressed_keys.remove(event.keysym) s = Scene(1500, 800, master=tk.Tk()) objects = [(Sphere(2, 7, 0, 3), (70, 0,0))] while True: start_time = int(round(time.time() * 1000)) s.draw_vision(objects) s.apply_user_input() s.update() end_time = int(round(time.time() * 1000)) print(end_time - start_time) if 60 > end_time - start_time: time.sleep((60 - end_time + start_time) / 1000)
def makesphere(): b = Sphere(float(input("radius of sphere "))) print("volume is " + str(b.volume())) print("surface area is " + str(b.surfacearea()))
ray = Ray(np.array([0.0, 0.0, 0.0]), np.array([0.0, 0.0, -1.0])) point = np.array([0.0, -10.0, 0.0]) normal = np.array([0.0, -1.0, 0.0]) p = Plane(point, normal, np.array([1.0, 1.0, 1.0]), 1.0, 1.0, 0.05, 150, 0.6, "plane1") tree.insert(p) radius = 3 center = np.array([-10.0, -7.0, -17.0]) s = Sphere(radius, center, np.array([0.289, 0.2845, 0.3779]), 1.0, 1.0, 1.0, 4, 0.0, "sphere1", noise=True, priori1=np.array([0.8, 0.6, 1.0]), priori2=np.array([1.0, 1.0, 1.0]), noisyText="noisetext.png") tree.insert(s) center = np.array([3.0, -7.0, -17.0]) s1 = Sphere(radius, center, np.array([0.289, 0.2845, 0.3779]), 1.0, 1.0, 1.0,
def _sphere(self, name): setattr(world, name, Sphere())