def reset(self): self.yfinal = copy.deepcopy(self.resetState) self.y0 = copy.deepcopy(self.resetState) self.bodies = copy.deepcopy(self.resetBodies) target = "ShootMe" i = 0 while(i < len(self.bodies)): if(self.bodies[i].objectName == "ShootMe"): tries = 1 newPosition = 10 * np.random.randn(1,3)[0] d = np.linalg.norm(newPosition) collision = rb.checkCollision(self.bodies[0].X, newPosition, 5.5, self.bodies[0].P, self.bodies[0].mass) while(d > 12 or d < 7 or collision): newPosition = 10 * np.random.randn(1,3)[0] d = np.linalg.norm(newPosition) collision = rb.checkCollision(self.bodies[0].X, newPosition, 5.5, self.bodies[0].P, self.bodies[0].mass) tries += 1 print("Target took {0} tries and is at {1}".format(tries, newPosition)) self.bodies[i].X = newPosition ax1 = newPosition ax2 = np.linalg.norm(ax1) ax1 = ax1/ax2 #q2 = Quaternion(axis=ax, angle=np.pi/2) ax2 = self.bodies[0].q.rotation_matrix ax2 = np.dot(ax2, np.array([0.,0.,1.])) d = np.dot(ax1, ax2) self.prevd = d break i += 1 #print(self.bodies) self.t = 0. self.firedProjectiles = 0 return processStateOuput(self.yfinal, self.t, self.firedProjectiles)
def createObject(self, mass, dim, X, q, P, L, objectType, objectName="unknown", thrusts=np.array([0., 0., 0., 0., 0., 0., 0., 0.]), loadtime=1e+9): Ibody = self.blockIBody(dim[0], dim[1], dim[2], mass) r = rb.Body(mass, Ibody, np.linalg.inv(Ibody), X, q, P, L, objectType, objectName, thrusts, loadtime) self.bodies.append(r)
def runSimulation(self, agentActions): self.yfinal = self.Bodies_To_Array() i = 0 while(i < self.state_size*len(self.bodies)): self.y0[i] = self.yfinal[i] i += 1 #########tracking total output## if(self.trackTotalOutput): self.output = np.append(self.output,self.y0) entities = [] for b in self.bodies: entities.append(b.objectName) self.entityTracker.append(entities) ################################ i = 0 while(i < len(self.bodies)): if(self.bodies[i].alive == False): self.tempY = self.y0 self.y0 = self.removeObject(self.y0, self.bodies[i].objectName) i -= 1 i += 1 if(len(self.bodies) == 0): #print("NO MORE BODIES!") print("no more bodies") outState = processStateOuput(self.tempY, self.t, self.firedProjectiles) return outState, self.tempR, True #############agent actions added here########### #forward, back, up, down, left, right, rollleft, rollright targetPosition = np.array([0.,0.,0.]) ia = 0 i = 0 while(i < len(self.bodies)): if(self.bodies[i].objectType == "Agent"): action = self.action_space.actions[int(agentActions[ia])] self.y0[(i*self.state_size)+13:(i*self.state_size)+self.state_size] = self.action_space.actions[int(agentActions[i])] #print("Rotation: {0}".format(self.bodies[i].q)) #print("Time: {0}".format(self.t)) #print("Action: {0}".format(int(agentActions[ia]))) if(action[-1] == 1 and self.firedProjectiles < 4): #fire projectile #print("FIRE {0}".format(self.firedProjectiles)) self.addProjectile(self.bodies[i], 2.5) self.y0 = np.append(self.y0, self.State_To_Array(self.bodies[-1])) self.yfinal = self.y0 ia += 1 elif(self.bodies[i].objectType == "Target"): targetPosition = self.bodies[i].X elif(self.bodies[i].objectType == "Projectile"): targetradius = 5. #print("projectile: {0}".format(self.bodies[i].X)) #print("target: {0}".format(targetPosition)) collision = rb.checkCollision(self.bodies[i].X, targetPosition, targetradius, self.bodies[i].P, self.bodies[i].mass) if(collision): print("projectile hit target") self.bodies[i].alive = False reward = 1000. outState = processStateOuput(self.yfinal, self.t, self.firedProjectiles) return outState, reward, True #print("hit planet") i += 1 ############################################### self.r.set_initial_value(self.y0,0) self.r.integrate(self.r.t + self.tick_length) self.yfinal = self.r.y self.t += self.tick_length ##########################reward function######################### reward = -self.t self.tempR = reward #punish being slow ################################################################## if(self.t >= 7.5): #limit simulation to 15 seconds print("out of time") outState = processStateOuput(self.yfinal, self.t, self.firedProjectiles) return outState, reward, True return self.yfinal, reward, False
body.f_mass = self.f_mass body.f_Icm = self.f_Icm body.force_torque = self.force_torque class SimpleRocketModel(object): """A simple rocket that should follow the rocket equation.""" def __init__(self, **params): ICraftModel.__init__(self, **params) def f_mass(y, t): return y[13] if __name__ == "__main__": b = RigidBody.RigidBody() c = CraftModel() print("g= %f" % (EarthFrame.G * EarthFrame.earth_mass / (EarthFrame.earth_radius)**2)) mass = 1.0 b.f_mass = lambda y, t: mass b.f_Icm = lambda y, t: 0.4 * np.eye(3) * mass g_ft = CraftModel.gravity_force_factory() b.force_torque = CraftModel.gravity_force_factory() r = (EarthFrame.G * EarthFrame.earth_mass / (EarthFrame.omega_earth**2))**(1.0 / 3.0) v = r * EarthFrame.omega_earth print("r=%f" % r) b.set_xyz([r, 0, 0])
def __init__(self, file): self.file = file self.spriteBanks = [] self.templates = {} with open(self.file) as json_file: data = json.load(json_file) # Register the related frames if 'imageBanks' in data.keys(): for b in data["imageBanks"]: #create new bank bank = SpriteBank(b["id"], b["file"]) self.spriteBanks.append(bank) pyxel.image(b["id"]).load(0, 0, b["file"]) #add sprites for s in b["sprites"]: bank.addSprite( Sprite(Vector2f(s["pos_x"], s["pos_y"]), Vector2f(s["width"], s["height"]), Vector2f(s["pivot_x"], s["pivot_y"]), s["transparent"]), s["id"]) else: print("Warning: EntityFactory: no 'imageBanks' in " + self.file) # create entity if ('entities' in data.keys()): for name in data["entities"].keys(): templateData = data["entities"][name] template = Entity() # basic information template.size.x = templateData["size_x"] template.size.y = templateData["size_y"] if ('rigidbody' in templateData): template.addComponent('RigidBody', RigidBody()) # rendering informations if ('renderer' in templateData): palette = templateData["renderer"]["imageBank"] bank = self.spriteBanks[palette] renderer = templateData["renderer"] # prefab is rendered using an Animator if ('animations' in renderer): animations = [] #create the animations for a in renderer["animations"]: frames = [] for f in a["frames"]: frame = bank.searchByName(f) if frame != None: frames.append(frame) else: print( "Warning: EntityFactory: no sprite under the name " + str(f) + ", for loading " + name) animations.append( Animation(a["animationName"], bank, frames, a["interruptable"], 1.0 / a["speed"], a["loop"])) template.addComponent( 'Animator', Animator(palette, animations, renderer["defaultAnimation"])) # prefab is rendered using a SpriteRenderer elif ('spriteList' in renderer): spriteList = [] for s in renderer["spriteList"]: sprite = bank.searchByName(s) if sprite != None: spriteList.append(sprite) else: print( "Warning: EntityFactory: no sprite under the name " + str(s) + ", for loading " + name) template.addComponent('SpriteList', spriteList) template.addComponent('ComponentRenderer', SpriteRenderer(bank)) else: print( "Warning: EntityFactory: no component renderer for entity " + name) # collision informations if ('colliders' in templateData): colliderList = [] for c in templateData["colliders"]: collider = Collider(c["type"]) collider.position = Vector2f( c["pos_x"], c["pos_y"]) collider.size = Vector2f(c["width"], c["height"]) colliderList.append(collider) template.addComponent('ColliderList', colliderList) else: print( "Warning: EntityFactory: no colliders for entity " + name) # scripts if ('scripts' in templateData): scripts = [] for s in templateData["scripts"]: try: module = __import__(s["name"]) class_ = getattr(module, s["name"]) script = class_() scripts.append(script) except: print( "Warning: EntityFactory: script loading error for entity " + name) template.addComponent('Scripts', scripts) # register template self.templates[name] = template else: print("Warning: EntityFactory: no entities in " + self.file)