def RandomlyPositionAssets(self, system, initLoc, finalLoc, terrain, terrain_length, terrain_width, should_scale=False): diag_obs = 5 for i in range(diag_obs): x = np.linspace(initLoc.x, finalLoc.x, diag_obs + 2)[1:-1] y = np.linspace(initLoc.y, finalLoc.y, diag_obs + 2)[1:-1] pos = chrono.ChVectorD(x[i], y[i], 0) pos.z = terrain.GetHeight(pos) rot = chrono.Q_from_AngZ(np.random.uniform(0, np.pi)) offset = chrono.ChVectorD(pos.y, -pos.x, 0) offset = offset.GetNormalized() * (np.random.random() - 0.5) * 20 rand_asset = np.random.choice(self.assets).Copy() rand_asset.pos = pos + offset rand_asset.rot = rot if should_scale: rand_asset.scale = np.random.uniform(rand_asset.scale_range[0], rand_asset.scale_range[1]) self.assets.append(rand_asset) for i, asset in enumerate(self.assets[:-diag_obs]): success = True for i in range(101): if i == 100: success = False break pos = self.GenerateRandomPosition(terrain, terrain_length, terrain_width) scale = 1 if should_scale: scale = np.random.uniform(asset.scale_range[0], asset.scale_range[1]) if (pos - initLoc).Length() < 15 or (pos - finalLoc).Length() < 15: continue closest_asset = min(self.assets, key=lambda x: (x.pos - pos).Length()) overlap = 0 if (closest_asset.pos - pos).Length() < scale + closest_asset.scale + overlap: continue break if not success: continue rot = chrono.Q_from_AngZ(np.random.uniform(0, np.pi)) asset.pos = pos asset.rot = rot asset.scale = scale for asset in self.assets: system.Add(asset.body) asset.CreateCollisionModel()
def __init__(self, x_half, y_half, z, t0): # making 4 turns to get to the end point q = chrono.Q_from_AngZ(randint(0, 3) * (-np.pi / 2)) flip = pow(-1, randint(0, 1)) route = randint(0, 1) points = chrono.vector_ChVectorD() if route == 0: beginPos = [-x_half, -y_half * flip] endPos = [x_half, y_half * flip] deltaX = (endPos[0] - beginPos[0]) / 3 deltaY = (endPos[1] - beginPos[1]) / 2 for i in range(6): point = chrono.ChVectorD( beginPos[0] + deltaX * m.floor((i + 1) / 2), beginPos[1] + deltaY * m.floor(i / 2), z) point = q.Rotate(point) points.append(point) if route == 1: xs = np.asarray([-1, 0, 1 / 3, 1 / 3, 0, -1]) ys = np.asarray([1, 4 / 5, 1 / 2, -1 / 2, -4 / 5, -1]) * flip for x, y in zip(xs, ys): point = chrono.ChVectorD(x * x_half, y * y_half, z) point = q.Rotate(point) points.append(point) super(BezierPath, self).__init__(points) self.current_t = np.random.rand(1)[0] * 0.5
def add_asset(self, asset: 'Any'): if isinstance(asset, chrono.ChBody): self._system._system.AddBody(asset) return if isinstance(asset, WABody): if not hasattr(asset, 'size') or not hasattr(asset, 'position'): raise AttributeError( "Body must have 'size', and 'position' fields") position = asset.position yaw = 0 if not hasattr(asset, 'yaw') else asset.yaw size = asset.size body_type = 'box' if hasattr(asset, 'body_type'): body_type = asset.body_type if body_type == 'sphere': body = chrono.ChBodyEasySphere(size.length, 1000, True, False) body.SetBodyFixed(True) elif body_type == 'box': body = chrono.ChBodyEasyBox( size.x, size.y, size.z, 1000, True, False) body.SetBodyFixed(True) else: raise ValueError( f"'{asset.body_type}' not a supported body type.") body.SetPos(WAVector_to_ChVector(position)) body.SetRot(chrono.Q_from_AngZ(-yaw + WA_PI / 2)) if hasattr(asset, 'color'): color = asset.color body.AddAsset(chrono.ChColorAsset( chrono.ChColor(color.x, color.y, color.z))) texture = chrono.ChVisualMaterial() texture.SetDiffuseColor( chrono.ChVectorF(color.x, color.y, color.z)) chrono.CastToChVisualization( body.GetAssets()[0]).material_list.append(texture) if hasattr(asset, 'texture'): texture = chrono.ChVisualMaterial() texture.SetKdTexture(get_wa_data_file(asset.texture)) chrono.CastToChVisualization( body.GetAssets()[0]).material_list.append(texture) self._system._system.AddBody(body) asset.chrono_body = body super().add_asset(asset)
def reset(self): n = 2 * np.random.randint(0, 4) b1 = 0 b2 = 0 r1 = n r2 = n r3 = n r4 = n r5 = n t1 = 0 t2 = 0 t3 = 0 c = 0 self.assets = AssetList(b1, b2, r1, r2, r3, r4, r5, t1, t2, t3, c) # Create systems self.system = chrono.ChSystemNSC() self.system.Set_G_acc(chrono.ChVectorD(0, 0, -9.81)) self.system.SetSolverType(chrono.ChSolver.Type_BARZILAIBORWEIN) self.system.SetSolverMaxIterations(150) self.system.SetMaxPenetrationRecoverySpeed(4.0) # Create the terrain rigid_terrain = True self.terrain = veh.RigidTerrain(self.system) if rigid_terrain: patch_mat = chrono.ChMaterialSurfaceNSC() patch_mat.SetFriction(0.9) patch_mat.SetRestitution(0.01) patch = self.terrain.AddPatch(patch_mat, chrono.ChVectorD(0, 0, 0), chrono.ChVectorD(0, 0, 1), self.terrain_length * 1.5, self.terrain_width * 1.5) else: self.bitmap_file = os.path.dirname( os.path.realpath(__file__)) + "/../utils/height_map.bmp" self.bitmap_file_backup = os.path.dirname( os.path.realpath(__file__)) + "/../utils/height_map_backup.bmp" shape = (252, 252) generate_random_bitmap(shape=shape, resolutions=[(2, 2)], mappings=[(-1.5, 1.5)], file_name=self.bitmap_file) try: patch = self.terrain.AddPatch( chrono.CSYSNORM, # position self.bitmap_file, # heightmap file (.bmp) "test", # mesh name self.terrain_length * 1.5, # sizeX self.terrain_width * 1.5, # sizeY self.min_terrain_height, # hMin self.max_terrain_height) # hMax except Exception: print('Corrupt Bitmap File') patch = self.terrain.AddPatch( chrono.CSYSNORM, # position self.bitmap_file_backup, # heightmap file (.bmp) "test", # mesh name self.terrain_length * 1.5, # sizeX self.terrain_width * 1.5, # sizeY self.min_terrain_height, # hMin self.max_terrain_height) # hMax patch.SetTexture(veh.GetDataFile("terrain/textures/grass.jpg"), 200, 200) patch.SetColor(chrono.ChColor(0.8, 0.8, 0.5)) self.terrain.Initialize() ground_body = patch.GetGroundBody() ground_asset = ground_body.GetAssets()[0] visual_asset = chrono.CastToChVisualization(ground_asset) visual_asset.SetStatic(True) vis_mat = chrono.ChVisualMaterial() vis_mat.SetKdTexture(veh.GetDataFile("terrain/textures/grass.jpg")) visual_asset.material_list.append(vis_mat) theta = random.random() * 2 * np.pi x, y = self.terrain_length * 0.5 * np.cos( theta), self.terrain_width * 0.5 * np.sin(theta) z = self.terrain.GetHeight(chrono.ChVectorD(x, y, 0)) + 0.25 ang = np.pi + theta self.initLoc = chrono.ChVectorD(x, y, z) self.initRot = chrono.Q_from_AngZ(ang) self.vehicle = veh.Gator(self.system) self.vehicle.SetContactMethod(chrono.ChContactMethod_NSC) self.vehicle.SetChassisCollisionType(veh.ChassisCollisionType_NONE) self.vehicle.SetChassisFixed(False) self.m_inputs = veh.Inputs() self.vehicle.SetInitPosition( chrono.ChCoordsysD(self.initLoc, self.initRot)) self.vehicle.SetTireType(veh.TireModelType_TMEASY) self.vehicle.SetTireStepSize(self.timestep) self.vehicle.Initialize() if self.play_mode: self.vehicle.SetChassisVisualizationType( veh.VisualizationType_MESH) self.vehicle.SetWheelVisualizationType(veh.VisualizationType_MESH) self.vehicle.SetTireVisualizationType(veh.VisualizationType_MESH) else: self.vehicle.SetChassisVisualizationType( veh.VisualizationType_PRIMITIVES) self.vehicle.SetWheelVisualizationType( veh.VisualizationType_PRIMITIVES) self.vehicle.SetTireVisualizationType( veh.VisualizationType_PRIMITIVES) self.vehicle.SetSuspensionVisualizationType( veh.VisualizationType_PRIMITIVES) self.vehicle.SetSteeringVisualizationType( veh.VisualizationType_PRIMITIVES) self.chassis_body = self.vehicle.GetChassisBody() # self.chassis_body.GetCollisionModel().ClearModel() # size = chrono.ChVectorD(3,2,0.2) # self.chassis_body.GetCollisionModel().AddBox(0.5 * size.x, 0.5 * size.y, 0.5 * size.z) # self.chassis_body.GetCollisionModel().BuildModel() self.chassis_collision_box = chrono.ChVectorD(3, 2, 0.2) # Driver self.driver = veh.ChDriver(self.vehicle.GetVehicle()) # create goal # pi/4 ang displ delta_theta = (random.random() - 0.5) * 1.0 * np.pi gx, gy = self.terrain_length * 0.5 * np.cos( theta + np.pi + delta_theta), self.terrain_width * 0.5 * np.sin(theta + np.pi + delta_theta) self.goal = chrono.ChVectorD( gx, gy, self.terrain.GetHeight(chrono.ChVectorD(gx, gy, 0)) + 1.0) i = 0 while (self.goal - self.initLoc).Length() < 15: gx = random.random() * self.terrain_length - self.terrain_length / 2 gy = random.random() * self.terrain_width - self.terrain_width / 2 self.goal = chrono.ChVectorD(gx, gy, self.max_terrain_height + 1) if i > 100: print('Break') break i += 1 # self.goal = chrono.ChVectorD(75, 0, 0) # Origin in Madison WI self.origin = chrono.ChVectorD(43.073268, -89.400636, 260.0) self.goal_coord = chrono.ChVectorD(self.goal) sens.Cartesian2GPS(self.goal_coord, self.origin) self.goal_sphere = chrono.ChBodyEasySphere(.55, 1000, True, False) self.goal_sphere.SetBodyFixed(True) sphere_asset = self.goal_sphere.GetAssets()[0] visual_asset = chrono.CastToChVisualization(sphere_asset) vis_mat = chrono.ChVisualMaterial() vis_mat.SetAmbientColor(chrono.ChVectorF(0, 0, 0)) vis_mat.SetDiffuseColor(chrono.ChVectorF(.2, .2, .9)) vis_mat.SetSpecularColor(chrono.ChVectorF(.9, .9, .9)) visual_asset.material_list.append(vis_mat) visual_asset.SetStatic(True) self.goal_sphere.SetPos(self.goal) if self.play_mode: self.system.Add(self.goal_sphere) # create obstacles # start = t.time() self.assets.Clear() self.assets.RandomlyPositionAssets(self.system, self.initLoc, self.goal, self.terrain, self.terrain_length * 1.5, self.terrain_width * 1.5, should_scale=False) # Set the time response for steering and throttle inputs. # NOTE: this is not exact, since we do not render quite at the specified FPS. steering_time = 0.75 # time to go from 0 to +1 (or from 0 to -1) throttle_time = .5 # time to go from 0 to +1 braking_time = 0.3 # time to go from 0 to +1 self.SteeringDelta = (self.timestep / steering_time) self.ThrottleDelta = (self.timestep / throttle_time) self.BrakingDelta = (self.timestep / braking_time) self.manager = sens.ChSensorManager(self.system) self.manager.scene.AddPointLight(chrono.ChVectorF(100, 100, 100), chrono.ChVectorF(1, 1, 1), 5000.0) self.manager.scene.AddPointLight(chrono.ChVectorF(-100, -100, 100), chrono.ChVectorF(1, 1, 1), 5000.0) # Let's not, for the moment, give a different scenario during test """ if self.play_mode: self.manager.scene.GetBackground().has_texture = True; self.manager.scene.GetBackground().env_tex = "sensor/textures/qwantani_8k.hdr" self.manager.scene.GetBackground().has_changed = True; """ # ----------------------------------------------------- # Create a self.camera and add it to the sensor manager # ----------------------------------------------------- #chrono.ChFrameD(chrono.ChVectorD(1.5, 0, .875), chrono.Q_from_AngAxis(0, chrono.ChVectorD(0, 1, 0))), self.camera = sens.ChCameraSensor( self.chassis_body, # body camera is attached to 20, # scanning rate in Hz chrono.ChFrameD( chrono.ChVectorD(.65, 0, .75), chrono.Q_from_AngAxis(0, chrono.ChVectorD(0, 1, 0))), # offset pose self.camera_width, # number of horizontal samples self.camera_height, # number of vertical channels chrono.CH_C_PI / 2, # horizontal field of view 6 # supersampling factor ) self.camera.SetName("Camera Sensor") self.camera.PushFilter(sens.ChFilterRGBA8Access()) if self.play_mode: self.camera.PushFilter( sens.ChFilterVisualize(self.camera_width, self.camera_height, "RGB Camera")) self.manager.AddSensor(self.camera) # ----------------------------------------------------- # Create a self.gps and add it to the sensor manager # ----------------------------------------------------- gps_noise_none = sens.ChGPSNoiseNone() self.gps = sens.ChGPSSensor( self.chassis_body, 15, chrono.ChFrameD( chrono.ChVectorD(0, 0, 0), chrono.Q_from_AngAxis(0, chrono.ChVectorD(0, 1, 0))), self.origin, gps_noise_none) self.gps.SetName("GPS Sensor") self.gps.PushFilter(sens.ChFilterGPSAccess()) self.manager.AddSensor(self.gps) # have to reconstruct scene because sensor loads in meshes separately (ask Asher) # start = t.time() if self.assets.GetNum() > 0: # self.assets.TransformAgain() # start = t.time() for asset in self.assets.assets: if len(asset.frames) > 0: self.manager.AddInstancedStaticSceneMeshes( asset.frames, asset.mesh.shape) # self.manager.ReconstructScenes() # self.manager.AddInstancedStaticSceneMeshes(self.assets.frames, self.assets.shapes) # self.manager.Update() # print('Reconstruction :: ', t.time() - start) self.old_dist = (self.goal - self.initLoc).Length() self.step_number = 0 self.c_f = 0 self.isdone = False self.render_setup = False self.dist0 = (self.goal - self.chassis_body.GetPos()).Length() if self.play_mode: self.render() # print(self.get_ob()[1]) return self.get_ob()
def getPosRot(self, t): pos = self.eval(t) posD = self.par_evalD(t) alpha = m.atan2(posD.y, posD.x) rot = chrono.Q_from_AngZ(alpha) return pos, rot
link_gearBC.Initialize(mbody_gearB, mbody_truss, chrono.CSYSNORM) link_gearBC.Set_local_shaft1( chrono.ChFrameD(chrono.VNULL, chrono.Q_from_AngX(-m.pi / 2))) link_gearBC.Set_local_shaft2( chrono.ChFrameD(chrono.ChVectorD(0, 0, -4), chrono.QUNIT)) link_gearBC.Set_tau(radB / radC) link_gearBC.Set_epicyclic( True) # <-- this means: use a wheel with internal teeth! mphysicalSystem.AddLink(link_gearBC) # ...the bevel gear at the side, radD = 5 mbody_gearD = chrono.ChBodyEasyCylinder(radD, 0.8, 1000, True, False, mat) mphysicalSystem.Add(mbody_gearD) mbody_gearD.SetPos(chrono.ChVectorD(-10, 0, -9)) mbody_gearD.SetRot(chrono.Q_from_AngZ(m.pi / 2)) mbody_gearD.AddAsset(cylinder_texture) # ...it is fixed to the truss using a revolute joint with horizontal axis (must rotate # the default ChLink creation coordys 90 degrees on the Y vertical, since the revolute # axis is the Z axis) link_revoluteD = chrono.ChLinkLockRevolute() link_revoluteD.Initialize( mbody_gearD, mbody_truss, chrono.ChCoordsysD(chrono.ChVectorD(-10, 0, -9), chrono.Q_from_AngY(m.pi / 2))) mphysicalSystem.AddLink(link_revoluteD) # ... Let's make a 1:1 gear between wheel A and wheel D as a bevel gear: Chrono does not require # special info for this case -the position of the two shafts and the transmission ratio are enough- link_gearAD = chrono.ChLinkGear()
v3 = chrono.ChVectorD(0.5, 0.2, 0) v4 = chrono.ChVectorD(0.6, 0.3, 0) v5 = chrono.ChVectorD(0.5, 0.5, 0.1) v6 = chrono.ChVectorD(0, 0.5, 0.1) splinepoints = chrono.vector_ChVectorD([v1, v2, v3, v4, v5, v6]) mspline = chrono.ChLineBspline(3, splinepoints) mspline.SetClosed(True) f_line = chrono.ChFunctionPosition_line() f_line.SetLine(mspline) f_line.SetSpaceFunction(chrono.ChFunction_Ramp(0, 0.2)) # Create a spline rotation interpolation q1 = chrono.ChQuaternionD(1, 0, 0, 0) q2 = chrono.ChQuaternionD(0, 0, 1, 0) q3 = chrono.Q_from_AngZ(1.2) q4 = chrono.Q_from_AngZ(2.2) q5 = chrono.Q_from_AngZ(-1.2) q6 = chrono.ChQuaternionD(0, 1, 0, 0) spinerots = chrono.vector_ChQuaternionD([q1, q2, q3, q4, q5, q6]) f_rotspline = chrono.ChFunctionRotation_spline(1, [q1, q2, q3, q4, q5, q6]) f_rotspline.SetClosed(True) f_rotspline.SetSpaceFunction(chrono.ChFunction_Ramp(0, 0.2)) impose_2 = chrono.ChLinkMotionImposed() system.Add(impose_2) impose_2.Initialize(mmoved_2, mfloor, chrono.ChFrameD(mmoved_2.GetPos())) impose_2.SetPositionFunction(f_line) impose_2.SetRotationFunction(f_rotspline) # Visualize the position spline