mpiston, mfloor, chrono.ChCoordsysD( crank_center + chrono.ChVectorD(crank_rad + rod_length, 0, 0), chrono.Q_ROTATE_Z_TO_X)) mysystem.Add(mjointC) # --------------------------------------------------------------------- # # Create an Irrlicht application to visualize the system # myapplication = chronoirr.ChIrrApp(mysystem, 'PyChrono example', chronoirr.dimension2du(1024, 768)) myapplication.AddTypicalSky() myapplication.AddTypicalLogo(chrono.GetChronoDataPath() + 'logo_pychrono_alpha.png') myapplication.AddTypicalCamera(chronoirr.vector3df(1, 1, 3), chronoirr.vector3df(0, 1, 0)) myapplication.AddTypicalLights() # ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items # in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes. # If you need a finer control on which item really needs a visualization proxy in # Irrlicht, just use application.AssetBind(myitem); on a per-item basis. myapplication.AssetBindAll() # ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets # that you added to the bodies into 3D shapes, they can be visualized by Irrlicht!
my_floor.SetPos(chrono.ChVectorD(0, -0.3, 0)) my_floor.SetBodyFixed(True) mysystem.Add(my_floor) my_color = chrono.ChColorAsset(0.2, 0.2, 0.5) my_floor.AddAsset(my_color) # --------------------------------------------------------------------- # # Create an Irrlicht application to visualize the system # myapplication = chronoirr.ChIrrApp(mysystem, 'Use OpenCascade shapes', chronoirr.dimension2du(1024, 768)) myapplication.AddTypicalSky(chrono.GetChronoDataPath() + 'skybox/') myapplication.AddTypicalLogo(chrono.GetChronoDataPath() + 'logo_pychrono_alpha.png') myapplication.AddTypicalCamera(chronoirr.vector3df(0.2, 0.2, -0.2)) myapplication.AddTypicalLights() # ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items # in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes. # If you need a finer control on which item really needs a visualization proxy in # Irrlicht, just use application.AssetBind(myitem); on a per-item basis. myapplication.AssetBindAll() # ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets # that you added to the bodies into 3D shapes, they can be visualized by Irrlicht!
# # The vehicle reference frame has Z up, X towards the front of the vehicle, and # Y pointing to the left. # # ============================================================================= import pychrono.core as chrono import pychrono.irrlicht as irr import pychrono.vehicle as veh import math # The path to the Chrono data directory containing various assets (meshes, textures, data files) # is automatically set, relative to the default location of this demo. # If running from a different directory, you must change the path to the data directory with: #chrono.SetChronoDataPath('path/to/data') veh.SetDataPath(chrono.GetChronoDataPath() + 'vehicle/') # Initial vehicle location and orientation initLoc = chrono.ChVectorD(0, 0, 0.5) initRot = chrono.ChQuaternionD(1, 0, 0, 0) # Visualization type for vehicle parts (PRIMITIVES, MESH, or NONE) chassis_vis_type = veh.VisualizationType_MESH suspension_vis_type = veh.VisualizationType_PRIMITIVES steering_vis_type = veh.VisualizationType_PRIMITIVES wheel_vis_type = veh.VisualizationType_MESH # Collision type for chassis (PRIMITIVES, MESH, or NONE) chassis_collision_type = veh.CollisionType_NONE # Type of tire model (RIGID, TMEASY)
patch_visual_asset = chrono.CastToChVisualization(patch_asset) vis_mat = chrono.ChVisualMaterial() # vis_mat.SetAmbientColor(chrono.ChVectorF(0, 0, 0)) vis_mat.SetKdTexture(chrono.GetChronoDataFile("vehicle/terrain/textures/dirt.jpg")) vis_mat.SetSpecularColor(chrono.ChVectorF(.0, .0, .0)) vis_mat.SetFresnelMin(0) vis_mat.SetFresnelMax(.1) patch_visual_asset.material_list.append(vis_mat) # Create the vehicle Irrlicht interface app = veh.ChWheeledVehicleIrrApp(my_rccar.GetVehicle()) app.SetSkyBox() app.AddTypicalLights(irr.vector3df(30, -30, 100), irr.vector3df(30, 50, 100), 250, 130) app.AddTypicalLogo(chrono.GetChronoDataPath() + 'logo_pychrono_alpha.png') app.SetChaseCamera(trackPoint, 1.5, 0.5) app.SetTimestep(step_size) # Create the driver system # driver = veh.ChIrrGuiDriver(app) driver = veh.ChDriver(my_rccar.GetVehicle()) # Set the time response for steering and throttle keyboard inputs. steering_time = 1.0 # time to go from 0 to +1 (or from 0 to -1) throttle_time = 1.0 # time to go from 0 to +1 braking_time = 0.3 # time to go from 0 to +1 # driver.SetSteeringDelta(render_step_size / steering_time) # driver.SetThrottleDelta(render_step_size / throttle_time) # driver.SetBrakingDelta(render_step_size / braking_time)
RING_GAP = 12.5 * UNIT_FACTOR SHAPE_THICKNESS = 0.01 SHAPE_PATH = 'shapes/printed_April18/Cone_32.obj' metrics = ['mm', 'cm', 'dm', 'm'] metric = metrics[int(math.fabs(round(math.log(UNIT_FACTOR, 10))))] HUMAN_DENSITY = 198.5 # Dkg/m^3 # --------------------------------------------------------------------- # # Create the simulation system and add items mysystem = chrono.ChSystemSMC() contact_method = chrono.ChMaterialSurface.SMC mysystem.Set_G_acc(chrono.ChVectorD(0., 0., 0.)) filepath = tool.obj_from_millimeter(chrono.GetChronoDataPath() + SHAPE_PATH, UNIT_FACTOR, f"_{metric}") # Import the shape shape = tool.load_shape(filepath, contact_method, 'textures/skin.jpg') shape.SetDensity(HUMAN_DENSITY) # Get shape bounding box dimensions bbmin, bbmax = chrono.ChVectorD(), chrono.ChVectorD() shape.GetTotalAABB(bbmin, bbmax) bbmin, bbmax = eval(str(bbmin)), eval(str(bbmax)) bb_dx = bbmax[0] - bbmin[0] bb_dy = bbmax[1] - bbmin[1] bb_dz = bbmax[2] - bbmin[2] shape.SetMass(100 * HUMAN_DENSITY * bb_dx * bb_dy * bb_dz)
# you can generate it from 3D modelers such as Blender, Maya, etc. # # NOTE: for collision purposes, the .obj mesh must be "watertight", i.e. having # no gaps in edges, no repeated vertexes, etc. # # NOTE: for visualization purposes only, i.e. if you do not use the mesh also for # collision, the mesh does not need to be watertight. # Method A: # - use the ChBodyEasyMesh # This will automatically create the visualization mesh, the collision mesh, # and will automatically compute the mass property (COG position respect to REF, # mass and inertia tensor) given an uniform density. body_A = chrono.ChBodyEasyMesh( chrono.GetChronoDataPath() + 'body_1_1.obj', # mesh filename 7000, # density kg/m^3 True, # use mesh for visualization? True) # use mesh for collision? body_A.SetPos(chrono.ChVectorD(0.5, 1, 0)) mysystem.Add(body_A) # Method B: # - create a ChBodyAuxRef, # - set mass and inertia tensor as you like # - set COG center of mass position respect to REF reference as you like # - attach a visualization shape based on a .obj triangle mesh # - add contact shape based on a .obj triangle mesh # This is more complicate than method A, yet this can be still preferred if you # need deeper control, ex. you want to provide two different meshes, one # with high level of detail just for the visualization and a coarse one for
# # Create the simulation system and add items # mysystem = chrono.ChSystemNSC() # Load a STEP file, containing a mechanism. The demo STEP file has been # created using a 3D CAD (in this case, SolidEdge v.18). # # Create the ChCascadeDoc, a container that loads the STEP model # and manages its subassembles mydoc = cascade.ChCascadeDoc() # load the STEP model using this command: load_ok = mydoc.Load_STEP(chrono.GetChronoDataPath() + "cascade/assembly.stp") # or specify abs.path: ("C:\\data\\cascade\\assembly.stp"); # print the contained shapes #mydoc.Dump(chrono.GetLog()) # In most CADs the Y axis is horizontal, but we want it vertical. # So define a root transformation for rotating all the imported objects. rotation1 = chrono.ChQuaternionD() rotation1.Q_from_AngAxis(-chrono.CH_C_PI / 2, chrono.ChVectorD(1, 0, 0)) # 1: rotate 90° on X axis rotation2 = chrono.ChQuaternionD() rotation2.Q_from_AngAxis(chrono.CH_C_PI, chrono.ChVectorD(0, 1, 0)) # 2: rotate 180° on vertical Y axis tot_rotation = chrono.ChQuaternionD() tot_rotation = rotation2 % rotation1 # rotate on 1 then on 2, using quaternion product
body_floor.SetPos(chrono.ChVectorD(0, -2, 0)) body_floor.SetMaterialSurface(brick_material) # Collision shape body_floor.GetCollisionModel().ClearModel() body_floor.GetCollisionModel().AddBox(3, 1, 3) # hemi sizes body_floor.GetCollisionModel().BuildModel() body_floor.SetCollide(True) # Visualization shape body_floor_shape = chrono.ChBoxShape() body_floor_shape.GetBoxGeometry().Size = chrono.ChVectorD(3, 1, 3) body_floor.GetAssets().push_back(body_floor_shape) body_floor_texture = chrono.ChTexture() body_floor_texture.SetTextureFilename(chrono.GetChronoDataPath() + 'concrete.jpg') body_floor.GetAssets().push_back(body_floor_texture) my_system.Add(body_floor) # Create the shaking table, as a box size_table_x = 1 size_table_y = 0.2 size_table_z = 1 body_table = chrono.ChBody() body_table.SetPos(chrono.ChVectorD(0, -size_table_y / 2, 0)) body_table.SetMaterialSurface(brick_material)
def run_sim(traits, trial_num, gen_num, difficulty_level): my_system = chrono.ChSystemNSC() # Set the default outward/inward shape margins for collision detection chrono.ChCollisionModel.SetDefaultSuggestedEnvelope(0.001) chrono.ChCollisionModel.SetDefaultSuggestedMargin(0.001) # Sets simulation precision my_system.SetMaxItersSolverSpeed(70) # Create a contact material (surface property)to share between all objects. rollfrict_param = 0.5 / 10.0 * 0.05 brick_material = chrono.ChMaterialSurfaceNSC() brick_material.SetFriction(0.5) brick_material.SetDampingF(0.2) brick_material.SetCompliance(0.0000001) brick_material.SetComplianceT(0.0000001) brick_material.SetRollingFriction(rollfrict_param) brick_material.SetSpinningFriction(0.00000001) brick_material.SetComplianceRolling(0.0000001) brick_material.SetComplianceSpinning(0.0000001) # Create the set of bricks in a vertical stack, along Y axis block_bodies = [] # visualizes bodies block_shapes = [] # geometry purposes current_y = 0 for block_index in range(0, 4): size_brick_x = traits[block_index][0] size_brick_z = traits[block_index][1] size_brick_y = traits[block_index][2] if size_brick_y < settings.MIN_DIMENSIONS_THRESHOLD or size_brick_x < settings.MIN_DIMENSIONS_THRESHOLD or size_brick_z < settings.MIN_DIMENSIONS_THRESHOLD: return [-50, traits] mass_brick = settings.BLOCK_MASS inertia_brick_xx = 1 / 12 * mass_brick * (pow(size_brick_z, 2) + pow(size_brick_y, 2)) inertia_brick_yy = 1 / 12 * mass_brick * (pow(size_brick_x, 2) + pow(size_brick_z, 2)) inertia_brick_zz = 1 / 12 * mass_brick * (pow(size_brick_x, 2) + pow(size_brick_y, 2)) body_brick = chrono.ChBody() body_brick.SetPos(chrono.ChVectorD(0, current_y + 0.5 * size_brick_y, 0)) # set initial position current_y += size_brick_y # set tower block positions # setting mass properties body_brick.SetMass(mass_brick) body_brick.SetInertiaXX(chrono.ChVectorD(inertia_brick_xx, inertia_brick_yy, inertia_brick_zz)) # set collision surface properties body_brick.SetMaterialSurface(brick_material) # Collision shape body_brick.GetCollisionModel().ClearModel() body_brick.GetCollisionModel().AddBox(size_brick_x / 2, size_brick_y / 2, size_brick_z / 2) # must set half sizes body_brick.GetCollisionModel().BuildModel() body_brick.SetCollide(True) # Visualization shape, for rendering animation body_brick_shape = chrono.ChBoxShape() body_brick_shape.GetBoxGeometry().Size = chrono.ChVectorD(size_brick_x / 2, size_brick_y / 2, size_brick_z / 2) if block_index % 2 == 0: body_brick_shape.SetColor(chrono.ChColor(0.65, 0.65, 0.6)) # set gray color only for odd bricks body_brick.GetAssets().push_back(body_brick_shape) my_system.Add(body_brick) block_bodies.append(body_brick) block_shapes.append(body_brick_shape); # Create the room floor body_floor = chrono.ChBody() body_floor.SetBodyFixed(True) body_floor.SetPos(chrono.ChVectorD(0, -2, 0)) body_floor.SetMaterialSurface(brick_material) # Floor's collision shape body_floor.GetCollisionModel().ClearModel() body_floor.GetCollisionModel().AddBox(3, 1, 3) # hemi sizes default: 3,1,3 body_floor.GetCollisionModel().BuildModel() body_floor.SetCollide(True) # Visualization shape body_floor_shape = chrono.ChBoxShape() body_floor_shape.GetBoxGeometry().Size = chrono.ChVectorD(3, 1, 3) body_floor.GetAssets().push_back(body_floor_shape) body_floor_texture = chrono.ChTexture() # body_floor_texture.SetTextureFilename(chrono.GetChronoDataPath() + 'concrete.jpg') body_floor.GetAssets().push_back(body_floor_texture) my_system.Add(body_floor) # Create the shaking table, as a box size_table_x = 1 size_table_y = 0.2 size_table_z = 1 body_table = chrono.ChBody() body_table.SetPos(chrono.ChVectorD(0, -size_table_y / 2, 0)) body_table.SetMaterialSurface(brick_material) # Collision shape body_table.GetCollisionModel().ClearModel() body_table.GetCollisionModel().AddBox(size_table_x / 2, size_table_y / 2, size_table_z / 2) # hemi sizes body_table.GetCollisionModel().BuildModel() body_table.SetCollide(True) # Visualization shape body_table_shape = chrono.ChBoxShape() body_table_shape.GetBoxGeometry().Size = chrono.ChVectorD(size_table_x / 2, size_table_y / 2, size_table_z / 2) body_table_shape.SetColor(chrono.ChColor(0.4, 0.4, 0.5)) body_table.GetAssets().push_back(body_table_shape) body_table_texture = chrono.ChTexture() # body_table_texture.SetTextureFilename(chrono.GetChronoDataPath() + 'concrete.jpg') body_table.GetAssets().push_back(body_table_texture) my_system.Add(body_table) # Makes the table shake link_shaker = chrono.ChLinkLockLock() # link_shaker.SetMotion_X() link_shaker.Initialize(body_table, body_floor, chrono.CSYSNORM) my_system.Add(link_shaker) # ..create the function for imposed y vertical motion, etc. mfunY = chrono.ChFunction_Sine(0, settings.TABLE_FREQ_Y, settings.TABLE_AMP_Y) # phase, frequency, amplitude # ..create the function for imposed z horizontal motion, etc. mfunZ = chrono.ChFunction_Sine(0, settings.TABLE_FREQ_Z, settings.TABLE_AMP_Z) # phase, frequency, amplitude # ..create the function for imposed x horizontal motion, etc. mfunX = chrono.ChFunction_Sine(2, 0, 0) # phase, frequency, amplitude print("Sim env_level " + str(difficulty_level)) if difficulty_level == settings.SHAKE_IN_X_AXIS_LEVEL: mfunX = chrono.ChFunction_Sine(2, settings.TABLE_FREQ_X, settings.TABLE_AMP_X) # phase, frequency, amplitude elif difficulty_level >= settings.SHAKE_IN_X_AND_Z_AXIS_LEVEL: increment = 0.25 * difficulty_level mfunX = chrono.ChFunction_Sine(2, settings.TABLE_FREQ_X + increment, settings.TABLE_AMP_X) # phase, frequency, amplitude mfunZ = chrono.ChFunction_Sine(0, settings.TABLE_FREQ_Z + increment, settings.TABLE_AMP_Z) # phase, frequency, amplitude link_shaker.SetMotion_Y(mfunY) link_shaker.SetMotion_Z(mfunZ) link_shaker.SetMotion_X(mfunX) # --------------------------------------------------------------------- # # Create an Irrlicht application to visualize the system window_name = "Tower Trial: " + str(trial_num) + " Gen: " + str(gen_num) if trial_num == -1: window_name = "Initializing Population..." app = chronoirr.ChIrrApp(my_system, window_name, chronoirr.dimension2du(settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT)) app.AddTypicalSky() app.AddTypicalLogo(chrono.GetChronoDataPath() + 'logo_pychrono_alpha.png') app.AddTypicalCamera(chronoirr.vector3df(settings.CAMERA_X, settings.CAMERA_Y, settings.CAMERA_Z)) app.AddLightWithShadow(chronoirr.vector3df(2, 4, 2), # point chronoirr.vector3df(0, 0, 0), # aimpoint 9, # radius (power) 1, 9, # near, far 30) # Committing visualization app.AssetBindAll() app.AssetUpdateAll(); app.AddShadowAll(); # --------------------------------------------------------------------- # # Run the simulation. This is where all of the constraints are set # app.SetTimestep(settings.SPEED) app.SetTryRealtime(True) app.GetDevice().run() fitness = 0 brick1_init = block_bodies[0].GetPos().y brick2_init = block_bodies[1].GetPos().y brick3_init = block_bodies[2].GetPos().y brick4_init = block_bodies[3].GetPos().y # Highest while True: brick1_curr_height = block_bodies[0].GetPos().y brick2_curr_height = block_bodies[1].GetPos().y brick3_curr_height = block_bodies[2].GetPos().y brick4_curr_height = block_bodies[3].GetPos().y # Highest # Break conditions if my_system.GetChTime() > settings.SIMULATION_RUNTIME: break if my_system.GetChTime() > settings.SIMULATION_RUNTIME / 2: mfunX = chrono.ChFunction_Sine(2, 0, 0) mfunZ = chrono.ChFunction_Sine(2, 0, 0) link_shaker.SetMotion_Z(mfunZ) link_shaker.SetMotion_X(mfunX) # If the blocks fall out of line if brick1_init - brick1_curr_height > settings.CANCEL_SIM_THRESHOLD or \ brick2_init - brick2_curr_height > settings.CANCEL_SIM_THRESHOLD or \ brick3_init - brick3_curr_height > settings.CANCEL_SIM_THRESHOLD or \ brick4_init - brick4_curr_height > settings.CANCEL_SIM_THRESHOLD: break # Record fitness every 1/1000 of the runtime if 0.01 > my_system.GetChTime() % ((1 / 1000) * settings.SIMULATION_RUNTIME) > 0: if settings.FITNESS_FUNCTION == settings.Fitness.SumLengths: # Sum of size_y fitness += block_shapes[0].GetBoxGeometry().GetLengths().y + \ block_shapes[1].GetBoxGeometry().GetLengths().y + \ block_shapes[2].GetBoxGeometry().GetLengths().y + \ block_shapes[3].GetBoxGeometry().GetLengths().y elif settings.FITNESS_FUNCTION == settings.Fitness.MaxPosition: # Max of y positions fitness += max(block_bodies[0].GetPos().y, block_bodies[1].GetPos().y, block_bodies[2].GetPos().y, block_bodies[3].GetPos().y) elif settings.FITNESS_FUNCTION == settings.Fitness.MaxPositionSumLengths: # Max * sum of sizes fitness += max(block_bodies[0].GetPos().y, block_bodies[1].GetPos().y, block_bodies[2].GetPos().y, block_bodies[3].GetPos().y) * \ block_shapes[0].GetBoxGeometry().GetLengths().y + \ block_shapes[1].GetBoxGeometry().GetLengths().y + \ block_shapes[2].GetBoxGeometry().GetLengths().y + \ block_shapes[3].GetBoxGeometry().GetLengths().y app.BeginScene() app.DrawAll() for substep in range(0, 5): app.DoStep() app.EndScene() app.GetDevice().closeDevice() print("Fitness: " + str(fitness) + " Gen: " + str(gen_num)) return [fitness, traits]
# # Create the simulation system and add items # mysystem = chrono.ChSystemNSC() # Load a STEP file, containing a mechanism. The demo STEP file has been # created using a 3D CAD (in this case, SolidEdge v.18). # # Create the ChCascadeDoc, a container that loads the STEP model # and manages its subassembles mydoc = cascade.ChCascadeDoc() # load the STEP model using this command: load_ok = mydoc.Load_STEP(chrono.GetChronoDataPath() + "cascade/IRB7600_23_500_m2000_rev1_01_decorated.stp") # or specify abs.path: ("C:\\data\\cascade\\assembly.stp"); if not load_ok: raise ValueError( "Warning. Desired STEP file could not be opened/parsed \n") CH_C_PI = 3.1456 # In most CADs the Y axis is horizontal, but we want it vertical. # So define a root transformation for rotating all the imported objects. rotation1 = chrono.ChQuaternionD() rotation1.Q_from_AngAxis(-CH_C_PI / 2, chrono.ChVectorD(1, 0, 0)) # 1: rotate 90° on X axis rotation2 = chrono.ChQuaternionD()
# CHRONO SETUP # Create the simulation system and add items mysystem = chrono.ChSystemSMC() mysystem.Set_G_acc(chrono.ChVectorD(0., 0., 0.)) # Remove gravity contact_method = chrono.ChMaterialSurface.SMC # Set global collision margins chrono.ChCollisionModel.SetDefaultSuggestedEnvelope(0.0001) chrono.ChCollisionModel.SetDefaultSuggestedMargin(0.0001) # --------------------------------------------------------------------- # SHAPE # Load and display the shape # Change the millimeters units into meters filepath = tool.obj_from_millimeter(chrono.GetChronoDataPath() + SHAPE_PATH, UNIT_FACTOR, f"_{metric}") # Import the shape shape = tool.load_shape(filepath, contact_method, 'textures/skin.jpg') shape.SetDensity(HUMAN_DENSITY) # Get shape bounding box dimensions bbmin, bbmax = chrono.ChVectorD(), chrono.ChVectorD() shape.GetTotalAABB(bbmin, bbmax) bbmin, bbmax = eval(str(bbmin)), eval(str(bbmax)) bb_dx = bbmax[0] - bbmin[0] bb_dy = bbmax[1] - bbmin[1] bb_dz = bbmax[2] - bbmin[2] min_radius = tool.get_shape_min_radius(SHAPE_PATH, bb_dx, bb_dy) * UNIT_FACTOR offset = 0.02 * bb_dz
realtime_timer = chrono.ChRealtimeStepTimer() step_number = 0 render_frame = 0 while (app.GetDevice().run()): time = my_bus.GetSystem().GetChTime() # End simulation if (time >= t_end): break # Render scene and output POV-Ray data if (step_number % render_steps == 0): app.BeginScene(True, True, irr.SColor(255, 140, 161, 192)) app.DrawAll() app.AddTypicalLogo(chrono.GetChronoDataPath() + 'logo_pychrono_alpha.png') app.EndScene() render_frame += 1 # Get driver inputs driver_inputs = driver.GetInputs() # Update modules (process inputs from other modules) driver.Synchronize(time) terrain.Synchronize(time) my_bus.Synchronize(time, driver_inputs, terrain) app.Synchronize(driver.GetInputModeAsString(), driver_inputs) # Advance simulation for one timestep for all modules driver.Advance(step_size)