def GetMesh(): global scl, angle, terrain vertices = [] j = 0 for y in range(-alteredH // 2, alteredH // 2, scl * 2): i = 0 for x in range((-alteredW // 2), alteredW // 2, scl): verts = [ Vector(x, y, terrain[j][i]), Vector(x, y + scl, terrain[j][i]) ] verts = [ each.RotationX(60, Vector(0, 0, 0), return_new=False) for each in verts ] '''try random values, by all means.''' orthographicProjs = [ Matrix([[(1 - (5 - r.z / 10) / 100), 0, 0], [0, (1 - (5 - r.z / 10) / 100), 0]]) for r in verts ] verts = [ each.applyTransformation(orthographicProjs[i]) for i, each in enumerate(verts) ] vertices.append(verts) i += 1 j += 1 return vertices
def update(self): if not self.pinned: self.Edges() self.applyForce(Vector(0,gravity)) self.vel += (self.acc*deltaTime)*self.friction self.pos += self.vel*deltaTime self.acc = Vector(0,0)
def __init__(self, pos=None,pinned=False): self.pos = Vector(w//2+random.randint(-2,2),h//2+random.randint(-1,1)) if pos is None else pos ## FOR INIT VELOCITY self.oldPos = Vector(self.pos.x+random.random()-7,self.pos.y) # self.oldPos = copy.copy(self.pos) self.r = 3 self.pinned = pinned
def __init__(self, pos=None,pinned=False): self.pos = Vector(w//2,h//2+200) if pos is None else pos # self.vel = Vector(randint(-5,5),randint(-5,5)).normalized() * 50 self.vel = Vector(0,0) self.acc = Vector(0,0) self.r = 3 self.pinned = pinned self.friction = .99
def GetLines(self): lines = [] for i, each in enumerate(self.lims): v = Vector(0, 0, 0) v.elems[i] = each proj(v) v = self.rotate(v) lines.append(v) return lines
def GetAVertices(self): dist = 5 x,y = self.root.x,self.root.y x1,y1 = x+self.x,y+self.y x2,y2 = x+(self.x-dist),y + self.y-dist x3,y3 = x+(self.x-dist),y + self.y+dist Vertices = [(Vector(x1,y1),Vector(x2,y2)),(Vector(x1,y1),Vector(x3,y3))] for i,(v1,v2) in enumerate(Vertices): nv1 = v1.rotate(self.finPos,self.angle) nv2 = v2.rotate(self.finPos,self.angle) Vertices[i] = (nv1,nv2) return Vertices
def adjustVelocity(self): v1 = (self.normalVector-self.pos).normalized() v2 = (self.vel).normalized() try: angBw = math.acos(v1.dot(v2))*180/math.pi angBw = 0 if abs(angBw)<1 else angBw except: angBw = 180 if self.down else 0 ang = self.angle + 180 if angBw != 0 else self.angle ve= Vector(math.cos(0),math.sin(0))*self.vel.GetMagnitude() ve.rotate(Vector(0,0),ang) self.vel =ve
def flow(boid,colored): global spacing,vectors x,y = boid.pos.x,boid.pos.y x,y = int(x//spacing), int(y//spacing) VectorsOnY = (h//spacing)+1 if h%spacing != 0 else h//spacing ind = (x*VectorsOnY)+y try: force = vectors[ind] # pygame.draw.circle(screen,(255,255,255),(force.root.x,force.root.y),3) acc = Vector(force.x,force.y) acc = acc.SetMag(force.origMag*2) boid.applyForce(acc) boid.c = (force.r,0,force.b) if colored else (51,51,51) ## set the color to the vector's color or jus gray except: boid.c = (51,51,51)
def GetDigits(self): digs = [] for i, (min_, max_) in enumerate(self.alteredLims): lim = 200 sign = 1 if i == 0 else -1 vals = np.linspace(-max_, max_, 2 * lim)[::self.scale] for ind, j in enumerate(range(-lim, lim, self.scale)): v = Vector(0, 0, 0) v.elems[i] = j * sign proj(v) v = self.rotate(v) digs.append((v, round((vals[ind]), 1), i)) return digs
def Edges(self): if self.pos.x> w-5: p = Vector(w-5,copy.copy(self.pos.y)) self.applyForce(p-self.pos) if self.pos.x< 5: p = Vector(5,copy.copy(self.pos.y)) self.applyForce(p-self.pos) if self.pos.y> h-5: p = Vector(copy.copy(self.pos.x),h-5) self.applyForce(p-self.pos) if self.pos.y< 5: p = Vector(copy.copy(self.pos.x),5) self.applyForce(p-self.pos)
def setNearest(v1,v2, nearest, minDist): if v1 != None: v1 = Vector(*v1) d = dist(v1,v2,sqr=True) if d < minDist: nearest = v1 minDist = d return (nearest, minDist)
def __init__(self,root,x,y,angle=0): super().__init__(x,y) self.root = root self.angle = math.degrees(math.atan((self.y)/self.x)) if self.x != 0 else 0 self.angle = self.angle if angle == 0 else angle self.origMag = self.GetMagnitude() self.mag = self.clampMagnitude() self.sumX = (self.root.x + self.x) self.sumY = (self.root.y + self.y) self.finPos = Vector(self.sumX,self.sumY) self.finPos = self.finPos.rotate(self.root,angle) if angle != 0 else self.finPos; self.angle = self.angle + 180 if (self.sumY > self.root.y and self.sumX < self.root.x) or (self.sumY-self.root.y <= 0 and self.root.x > self.sumX) else self.angle if self.x == 0: if self.sumY > self.root.y: self.angle = 90 else: self.angle = -90 self.arrowVertices = self.GetAVertices()
def GetMesh(): global scl,angle,terrain vertices = [] for y in range(scl+50,h-450,15): verts = [] for x in range(w//2-100,w//2 + w-1130,15): verts.append(Particle(Vector(x,y))) vertices.append(verts) return vertices
def GetMesh(): global scl,angle,terrain vertices = [] ## THESE VALUES ARE AD HOC.. for y in range(scl,h-300,20): verts = [] for x in range(w//2-100,w//2 + w-1100,20): verts.append(Particle(Vector(x,y))) vertices.append(verts) return vertices
def __init__(self,pos,vel=None,acc=None,magnitude=None,dampeningAffect = 1,mass=1,maxTrail=0): self.pos = pos self.vel = Vector(math.cos(math.radians(random.choice([-180,0]))),math.sin(math.radians(random.choice(range(0,360))))) if vel is None else vel self.acc = acc self.damp = dampeningAffect self.trail = [] self.maxTrail = 0 self.speed = 3+scale/10 self.radius = 3 self.prevPos = self.pos
def fixEndpoints(self): dx = (self.p2.x - self.p1.x) dy = (self.p2.y - self.p1.y) disT = dist(self.p1,self.p2) offSet = (self.length-disT)/disT/2 offSet = Vector(dx*offSet,dy*offSet) if not self.p1.pinned: self.p1.pos -= offSet if not self.p2.pinned: self.p2.pos += offSet
def __init__(self): self.pos = (Vector(w//2+250+75,h//2)) self.vel = Vector(0,0) self.acc = Vector(0,0) self.car = False #self.img = pygame.image.load(imgPath) #self.img = self.img.convert_alpha() #self.img = pygame.transform.scale(self.img,(52,52)) #self.OrigImg = copy.copy(self.img) self.r = 10 self.shouldDie = False self.lastCrossed = 0 self.angle = 0 self.maxSpeed = 5 self.dampening = .99 self.prev = 0 self.vertices = self.GetVertices() # self.headingVector = self.vertices[0]-self.pos self.score = 0 self.down = False self.normalVector = self.GetNormalVector()
def go(): global vectors,spcaing for x in range(0,w,spacing): for y in range(0,h,spacing): print(x,w,scale) reX,reY = ((x)-(w//2))/scale,(((y)-(h//2)))/scale print(reX,reY) v1 = func1(reX,reY) v2 = func2(reX,reY) newV = DiffRootVector(Vector(x,y),v1,v2) print(v1,v2) vectors.append(newV)
def GetDataPoints(self): dpoints = [] for ind, each in enumerate(self.datapoints): v = Vector(*each) v.y *= -1 v.z *= -1 proj(v) v = self.rotate(v) color = (255, 0, 0) if self.Colors is None else self.Colors[self.y[ind]] dpoints.append((v, color)) return dpoints
class DiffRootVector(Vector): ## ROOT IS A VECTOR def __init__(self,root,x,y,angle=0): super().__init__(x,y) self.root = root self.angle = math.degrees(math.atan((self.y)/self.x)) if self.x != 0 else 0 self.angle = self.angle if angle == 0 else angle self.origMag = self.GetMagnitude() self.mag = self.clampMagnitude() self.sumX = (self.root.x + self.x) self.sumY = (self.root.y + self.y) self.finPos = Vector(self.sumX,self.sumY) self.finPos = self.finPos.rotate(self.root,angle) if angle != 0 else self.finPos; self.angle = self.angle + 180 if (self.sumY > self.root.y and self.sumX < self.root.x) or (self.sumY-self.root.y <= 0 and self.root.x > self.sumX) else self.angle if self.x == 0: if self.sumY > self.root.y: self.angle = 90 else: self.angle = -90 self.arrowVertices = self.GetAVertices() def GetAVertices(self): dist = 5 x,y = self.root.x,self.root.y x1,y1 = x+self.x,y+self.y x2,y2 = x+(self.x-dist),y + self.y-dist x3,y3 = x+(self.x-dist),y + self.y+dist Vertices = [(Vector(x1,y1),Vector(x2,y2)),(Vector(x1,y1),Vector(x3,y3))] for i,(v1,v2) in enumerate(Vertices): nv1 = v1.rotate(self.finPos,self.angle) nv2 = v2.rotate(self.finPos,self.angle) Vertices[i] = (nv1,nv2) return Vertices def draw(self,screen): ## MAKE THE COLOR DEPENDENT ON THE VECTOR's length ## WOULD PROBABLY USE SOME SCALE FUCTION FOR DRAWING THE VECTOR #pygame.draw.line(screen,(self.r,0,self.b),(self.root.x,self.root.y),(self.sumX,self.sumY),2) pygame.draw.line(screen,(self.r,0,self.b),(self.root.x,self.root.y),(self.finPos.x,self.finPos.y),2) for v1,v2 in self.arrowVertices: pygame.draw.line(screen,(self.r,0,self.b),(v1.x,v1.y),(v2.x,v2.y),2) def clampMagnitude(self): maxMag = (w//2)/(scale) # maxMag = Vector(func1(w//scale,h//scale),func2(w//scale,h//scale)).GetMagnitude() mag = self.GetMagnitude()*(1+((scale-1)/100)) ratio = mag/maxMag ratio = min(1,ratio) self.r = 255*ratio self.b = 255*(1-ratio) new = self.SetMag(np.clip(mag,0,20)) self.x,self.y = new.x,new.y return new
def update(self,screen): if not self.angle == self.prev: self.adjustVelocity() self.pos += self.vel*deltaTime self.vel += self.acc*deltaTime self.normalVector = self.GetNormalVector() self.vertices = self.GetVertices(self.pos) self.rotate(self.angle) self.acc = Vector(0,0) self.vel *= self.dampening self.ConstructEndPoints() self.CheckIfCrossedLandMarks() self.prev = self.angle
def DrawCircularPath(r,pos,shapeSides = 9,animate=True,putLandMarks=False): global boundries,landMarks,numlandMarks i = 0 ## TO MAKE A NONAGON I HAVE TO MAKE AN INCREAMENT OF 40, because yk all the opposite side are 40 degrees ## I CAN ACTUALLY MAKE ANY REGULAR POLYGON, all I have to do is increments = 360/# of sides ## SO YEA A CIRCLE IS ACTUALLY A POLYGON WITH INFINITE SIDES increments = 360/shapeSides x1,y1 = pos.x+r,pos.y while i < 360: i += increments noise = 0 x2 = pos.x+(r+noise)*math.cos(math.radians(-i)) y2 = pos.y+(r+noise)*math.sin(math.radians(-i)) boundries.append(Boundry(Vector(x1,y1),Vector(x2,y2))) if animate: pygame.draw.line(screen,(255,255,255),(x1,y1),(x2,y2),2) clock.tick(100) pygame.display.update() CheckEvent() if putLandMarks and int(i % ((increments)/numlandMarks)) == 0: landMarks.append(Vector(pos.x+(250 + (r-250) / 2)*math.cos(math.radians(-i)),(pos.y+(250 +(r-250)/2)*math.sin(math.radians(-i))))) x1,y1 = x2,y2
def GetCube(): Vertices = [ Vector(-50, -50, 50), Vector(50, -50, 50), Vector(50, 50, 50), Vector(-50, 50, 50), Vector(-50, -50, -50), Vector(50, -50, -50), Vector(50, 50, -50), Vector(-50, 50, -50), ] for each in Vertices: each.x += 100 ## JUST MESSING AROUND WITH THE CENTER each.y += 100 return Vertices
def go1(): global vectors,spcaing for x in range(0,w,spacing): for y in range(0,h,spacing): clock.tick(1000) screen.fill((0,0,0)) reX,reY = ((x)-(w//2))/scale,(((y)-(h//2)))/scale v1 = func1(reX,reY) v2 = func2(reX,reY) newV = DiffRootVector(Vector(x,y),v1,v2) vectors.append(newV) [v.draw() for v in vectors] pygame.display.update() CheckEvent()
def update(self,screen,deltaTime): '''so integral of v is pos, which is xo + vt, so the new pos is, current pos + velocity*howmuch time has passed''' '''in our case that would be the time b/w frames, which i could either compute''' '''or just be naive and say it's 1/frameRate ''' self.pos += self.vel *self.speed* deltaTime self.vel += self.acc * deltaTime self.show();self.edges() pygame.draw.line(screen,self.c,(self.prevPos.x,self.prevPos.y),(self.pos.x,self.pos.y),1) self.prevPos=self.pos if self.maxTrail != 0: if not len(self.trail) >= self.maxTrail: self.trail.append(particle(self.pos)) else: self.process() [p.show() for p in self.trail] self.acc = Vector(0,0)
def GetVertices(self,pos=None,shape='SQUARE'): if shape == 'TRIANGLE': r = self.r pos = self.pos if pos is None else pos topVertex = Vector(self.pos.x+r,self.pos.y) bottomLeft = Vector(self.pos.x-r,self.pos.y-r) bottomRight = Vector(self.pos.x-r,self.pos.y+r) return [topVertex,bottomLeft,bottomRight] elif shape == 'SQUARE': r = self.r pos = self.pos if pos is None else pos topLeft = Vector(self.pos.x-r,self.pos.y+r) topRight = Vector(self.pos.x+r,self.pos.y+r) bottomLeft = Vector(self.pos.x-r,self.pos.y-r) bottomRight = Vector(self.pos.x+r,self.pos.y-r) return [topLeft,topRight,bottomRight,bottomLeft] else: raise Exception(shape + ' is invalid, puta.');
def drawLine(v1, v2): x1, y1, x2, y2 = v1.x, v1.y, v2.x, v2.y wThresh, hThresh = w // 2, h // 2 pygame.draw.line(screen, (0, 255, 0), (wThresh + x1, hThresh + y1), (wThresh + x2, hThresh + y2), 2) def DrawLines(vert): for i in range(4): drawLine(vert[i], vert[(i + 1) % 4]) drawLine(vert[i + 4], vert[((i + 1) % 4) + 4]) drawLine(vert[i], vert[i + 4]) Cube = GetCube() Center = Vector(100, 100, 0) #LOOKS PRETTY COOL with center = (0,0,0) too while run: screen.fill((0, 0, 0)) RotatedCube = [v.RotationX(angle, Center) for v in Cube] RotatedCube = [v.RotationZ(angle, Center) for v in RotatedCube] orthographicProjs = [ Matrix([ [(1 - (.5 - r.z / 3) / 100), 0, 0], ## NAIVE ATTEMPT TO MODEL PRESPECTIVE PROJECTIONS [0, (1 - (.5 - r.z / 3) / 100), 0] ]) for r in RotatedCube ] projs = [ v.applyTransformation(orthographicProjs[i]) for i, v in enumerate(RotatedCube) ]
def ChaseTarget(self,pos): pos = Vector(pos[0],pos[1]) direction = pos-self.pos #self.vel = direction self.applyForce(direction-self.vel)
class Car: def __init__(self): self.pos = (Vector(w//2+250+75,h//2)) self.vel = Vector(0,0) self.acc = Vector(0,0) self.car = False #self.img = pygame.image.load(imgPath) #self.img = self.img.convert_alpha() #self.img = pygame.transform.scale(self.img,(52,52)) #self.OrigImg = copy.copy(self.img) self.r = 10 self.shouldDie = False self.lastCrossed = 0 self.angle = 0 self.maxSpeed = 5 self.dampening = .99 self.prev = 0 self.vertices = self.GetVertices() # self.headingVector = self.vertices[0]-self.pos self.score = 0 self.down = False self.normalVector = self.GetNormalVector() ## TRIANGLE def GetVertices(self,pos=None,shape='SQUARE'): if shape == 'TRIANGLE': r = self.r pos = self.pos if pos is None else pos topVertex = Vector(self.pos.x+r,self.pos.y) bottomLeft = Vector(self.pos.x-r,self.pos.y-r) bottomRight = Vector(self.pos.x-r,self.pos.y+r) return [topVertex,bottomLeft,bottomRight] elif shape == 'SQUARE': r = self.r pos = self.pos if pos is None else pos topLeft = Vector(self.pos.x-r,self.pos.y+r) topRight = Vector(self.pos.x+r,self.pos.y+r) bottomLeft = Vector(self.pos.x-r,self.pos.y-r) bottomRight = Vector(self.pos.x+r,self.pos.y-r) return [topLeft,topRight,bottomRight,bottomLeft] else: raise Exception(shape + ' is invalid, puta.'); def adjustVelocity(self): v1 = (self.normalVector-self.pos).normalized() v2 = (self.vel).normalized() try: angBw = math.acos(v1.dot(v2))*180/math.pi angBw = 0 if abs(angBw)<1 else angBw except: angBw = 180 if self.down else 0 ang = self.angle + 180 if angBw != 0 else self.angle ve= Vector(math.cos(0),math.sin(0))*self.vel.GetMagnitude() ve.rotate(Vector(0,0),ang) self.vel =ve def ChaseTarget(self,pos): pos = Vector(pos[0],pos[1]) direction = pos-self.pos #self.vel = direction self.applyForce(direction-self.vel) def applyForce(self,f): self.acc += f def updateVertices(self): for each in self.vertices: each += self.vel*deltaTime; def GetNormalVector(self): dist = 20; v = DiffRootVector(self.pos,dist,0,angle=self.angle); return v.finPos; def update(self,screen): if not self.angle == self.prev: self.adjustVelocity() self.pos += self.vel*deltaTime self.vel += self.acc*deltaTime self.normalVector = self.GetNormalVector() self.vertices = self.GetVertices(self.pos) self.rotate(self.angle) self.acc = Vector(0,0) self.vel *= self.dampening self.ConstructEndPoints() self.CheckIfCrossedLandMarks() self.prev = self.angle def UpdateAngle(self,angle): self.angle += angle if self.angle > 360: self.angle = self.angle- 360 elif self.angle < 0: self.angle = 360-self.angle def SetVel(self,vel): self.vel = vel return self def SetAcc(self,acc): self.acc = acc return self def draw(self,screen): global img if not self.car: vert=self.vertices done = False for i in range(1,len(self.vertices)): c = (255,255,255) if not done else (255,0,0) pygame.draw.line(screen,c,(vert[i-1].x,vert[i-1].y),(vert[i].x,vert[i].y),2) done = not done pygame.draw.line(screen,(255,255,255),(vert[0].x,vert[0].y),(vert[-1].x,vert[-1].y),2) else: screen.blit(self.img,(self.pos.x,self.pos.y)) def rotate(self,angle): global maxSpeed if not self.car: for i,each in enumerate(self.vertices): self.vertices[i] = each.rotate(self.pos,self.angle) else: self.img = pygame.transform.rotate(self.OrigImg,-angle) return self def ConstructEndPoints(self): l = [] for i in range(len(self.vertices)-1): l.append((self.vertices[i],self.vertices[i+1])) l.append((self.vertices[0],self.vertices[-1])) self.segments = l def CheckForCollision(self,bound): for each in self.segments: x1,y1 = each[0] x2,y2 = each[1] pos =CollisionPoint((x1,y1,x2,y2),(bound.x1,bound.y1,bound.x2,bound.y2)) if pos is None : continue x,y = pos if (min(x1,x2)<=x<=max(x1,x2) and min(y1,y2)<=y<=max(y1,y2)) and (min(bound.x1,bound.x2)<=x<=max(bound.x1,bound.x2) and min(bound.y1,bound.y2)<=y<=max(bound.y1,bound.y2)): pygame.draw.circle(screen, (255,255,255),(int(x),int(y)),5) return True if self.shouldDie: return True return False def hasCollided(self,bounds): for bound in bounds: if self.CheckForCollision(bound): return True return False def CheckIfCrossedLandMarks(self): self.lastCrossed += 1 for each in self.landMarks: if (self.pos - each).GetMagnitude() < 80: self.landMarks.remove(each); self.score = self.score +1 if not self.down else self.score self.lastCrossed = 0 if self.landMarks == []: self.landMarks = copy.deepcopy(self.origlandMarks) if self.lastCrossed > 120: self.shouldDie = True
sign = -1 if boid.down else 1 rays = CreateRays((boid.pos.x+boid.r*cos(rad(boid.angle)),boid.pos.y+boid.r*sin(rad(boid.angle))),boid.angle); return rays def setLandMarks(pop): global landMarks for each in pop: each.phenotype.landMarks = copy.deepcopy(landMarks) each.phenotype.origlandMarks = copy.deepcopy(landMarks) # boid = Car() # rays = CreateRaysForBoid(boid) boundries =[] animate= True landMarks = [] numlandMarks = 15 DrawCircularPath(400,Vector(w//2,h//2),animate=animate,putLandMarks=True) DrawCircularPath(250,Vector(w//2,h//2),animate=animate) INCREAMENT = 30 neat = setup(Car,360//INCREAMENT,4,max_pop = 25) # boid.landMarks = landMarks # boid.origlandMarks = copy.deepcopy(landMarks) pop = copy.copy(neat.population) setLandMarks(pop) # boid = Car() # dna = torch.load('D:\\model_.pt') # boid.landMarks = landMarks # boid.origlandMarks = copy.deepcopy(landMarks) while run: # clock.tick(frameRate)