MechJeb#

MechJeb is an autopilot. The MechJeb service follows MechJeb’s windows: a script sets what a player would set in a window, then engages the autopilot. This tutorial walks through a script that flies the stock PT Series Munsplorer from the launch pad to the surface of Minmus. MechJeb adds itself to every command pod, so the craft needs no extra part.

The tutorial includes the script in each of the client languages kRPC supports. Download the whole program in your chosen language:

Python, C#, C++, C, Java, Lua, JavaScript

The script starts with its helpers. wait_for waits until a condition is true, with an event. print_steps prints each step of an autopilot, from a stream of its status. print_orbit prints the vessel’s orbit. The C and Lua clients have no events or streams, so their scripts poll. Each waits for an autopilot in a loop that prints its steps, and the C program defines sleep_ms to pause between calls:

import re

import krpc

conn = krpc.connect(name="Launch to Minmus")
sc = conn.space_center
vessel = sc.active_vessel
mj = conn.mech_jeb


def wait_for(condition):
    """Wait until the condition is true."""
    event = conn.add_event(condition)
    with event.condition:
        event.wait()


def print_steps(autopilot):
    """Print each step of the autopilot. Returns the status stream."""
    steps = []

    def print_step(status):
        # The step, without the figures that change on each update
        lines = status.splitlines()
        step = re.split("[0-9\u221e]", lines[0])[0] if lines else ""
        step = step.rstrip(" :=")
        if step and step not in steps[-1:]:
            steps.append(step)
            print(step)

    status = conn.add_stream(getattr, autopilot, "status")
    status.add_callback(print_step)
    return status


def print_orbit():
    orbit = vessel.orbit
    print(
        "Orbit of %s, %.0f km by %.0f km"
        % (
            orbit.body.name,
            orbit.apoapsis_altitude / 1000,
            orbit.periapsis_altitude / 1000,
        )
    )

Ascent to Orbit#

The first part of the script launches the vessel into a 100 km circular orbit with Ascent Guidance, and prints each step of the autopilot as it climbs:

# The target orbit, set as in the Ascent Guidance window
ascent = mj.ascent_guidance
ascent.ascent_type = mj.AscentType.classic
ascent.desired_orbit_altitude = 100000
ascent.desired_inclination = 0

# The Ascent Settings window
settings = ascent.settings
settings.autostage = True
settings.limit_angle_of_attack = True
settings.max_angle_of_attack = 5
settings.autowarp = True

# Print each step of the autopilot
status = print_steps(ascent)

ascent.enabled = True
vessel.control.activate_next_stage()

# Wait for the autopilot to disengage, once the orbit is circular
wait_for(lambda: not ascent.enabled)
status.remove()
print_orbit()

The script sets the target orbit on AscentGuidance, and the settings of MechJeb’s Ascent Settings window on AscentGuidance.settings. With AscentSettings.autostage on, MechJeb stages the vessel once the first stage is activated. The autopilot disengages once it has circularized the orbit.

AscentGuidance.ascent_type picks the ascent path. The classic path flies a turn whose shape AscentGuidance.classic_path sets. The PVG path, Primer Vector Guidance, computes its own path, and is the one for Realism Overhaul. Its settings are on AscentGuidance.pvg_settings.

Transfer to Minmus#

The second part takes the vessel from its orbit of Kerbin to a 20 km orbit of Minmus. It plans each maneuver with the Maneuver Planner, and has MechJeb execute it:

planner = mj.maneuver_planner
planner.autowarp = True

# Stage once a stage burns out, during the burns too
mj.utilities.staging.enabled = True


def execute_nodes():
    """Execute the vessel's maneuver nodes, and wait for the burns."""
    planner.execute_all_nodes()
    wait_for(lambda: not planner.executing_node)


# Target Minmus, and wait for MechJeb to see the target
minmus = sc.bodies["Minmus"]
sc.target_body = minmus
wait_for(lambda: mj.target_controller.normal_target_exists)

# Match planes with Minmus, at the nearest relative node
plane = planner.operation_plane
plane.time_selector.time_reference = mj.TimeReference.rel_nearest_ad
plane.make_nodes()
execute_nodes()

# The Hohmann transfer, to an encounter with no capture burn
transfer = planner.operation_transfer
transfer.time_selector.time_reference = mj.TimeReference.computed
transfer.capture = False
transfer.make_nodes()
execute_nodes()

# Fine tune the encounter, for a periapsis 20 km above Minmus
correction = planner.operation_course_correction
correction.final_periapsis_altitude = 20000
correction.make_nodes()
execute_nodes()

# Warp into Minmus' sphere of influence
sc.warp_to(sc.ut + vessel.orbit.time_to_soi_change + 60)

# Circularize at the periapsis
circularize = planner.operation_circularize
circularize.time_selector.time_reference = mj.TimeReference.periapsis
circularize.make_nodes()
execute_nodes()

sc.clear_target()
print_orbit()

Each operation of ManeuverPlanner is an object with the settings of the planner’s window. Its make_nodes method, such as OperationPlane.make_nodes(), adds the maneuver nodes, which the planner then executes:

def execute_nodes():
    """Execute the vessel's maneuver nodes, and wait for the burns."""
    planner.execute_all_nodes()
    wait_for(lambda: not planner.executing_node)

ManeuverPlanner.autowarp has MechJeb warp time to each burn. While a node executes, ManeuverPlanner.executing_node is true.

AscentSettings.autostage applies only during the ascent. For the burns, the script turns on the autostaging of MechJeb’s Utilities window, Utilities.staging, which stages the vessel once a stage burns out:

# Stage once a stage burns out, during the burns too
mj.utilities.staging.enabled = True

MechJeb plans the transfer to its own target, which the game’s target sets. MechJeb reads the target on its next update, so the script waits for TargetController.normal_target_exists:

# Target Minmus, and wait for MechJeb to see the target
minmus = sc.bodies["Minmus"]
sc.target_body = minmus
wait_for(lambda: mj.target_controller.normal_target_exists)

Minmus orbits Kerbin at an inclination of 6 degrees, and the vessel’s orbit is equatorial. The plane change comes first, at the node where the two orbits cross:

# Match planes with Minmus, at the nearest relative node
plane = planner.operation_plane
plane.time_selector.time_reference = mj.TimeReference.rel_nearest_ad
plane.make_nodes()
execute_nodes()

Each operation picks the time of its maneuver with its TimeSelector. TimeReference.rel_nearest_ad is the nearer of the relative ascending and descending nodes.

The Hohmann transfer burns once to reach Minmus’ orbit. Minmus has a sphere of influence, so the transfer stops at the encounter, with OperationTransfer.capture off:

# The Hohmann transfer, to an encounter with no capture burn
transfer = planner.operation_transfer
transfer.time_selector.time_reference = mj.TimeReference.computed
transfer.capture = False
transfer.make_nodes()
execute_nodes()

TimeReference.computed has MechJeb compute the time of the burn, at the phase angle that reaches Minmus.

The transfer orbit passes Minmus at some distance. A course correction moves the periapsis at Minmus to 20 km:

# Fine tune the encounter, for a periapsis 20 km above Minmus
correction = planner.operation_course_correction
correction.final_periapsis_altitude = 20000
correction.make_nodes()
execute_nodes()

Last, the script warps into Minmus’ sphere of influence, and circularizes the orbit at its periapsis:

# Warp into Minmus' sphere of influence
sc.warp_to(sc.ut + vessel.orbit.time_to_soi_change + 60)

# Circularize at the periapsis
circularize = planner.operation_circularize
circularize.time_selector.time_reference = mj.TimeReference.periapsis
circularize.make_nodes()
execute_nodes()

Note

To launch straight into Minmus’ plane, and skip the plane change, target Minmus, enable the autopilot, and call AscentGuidance.launch_to_target_plane() in place of activating the first stage. MechJeb warps to the launch time and stages the vessel itself.

Landing on Minmus#

The last part lands the vessel on Minmus’ Great Flats with Landing Guidance, and prints the autopilot’s steps as it descends:

# Stage until the next stage would drop the landing legs. This drops
# the stages below the lander, and activates the lander's engine.
mj.utilities.staging.enabled = False
legs = vessel.parts.legs[0].part
while vessel.control.current_stage > legs.decouple_stage + 1:
    vessel.control.activate_next_stage()

# Limit the lander's thrust, so its lowest throttle leaves it falling
for engine in vessel.parts.engines:
    engine.thrust_limit = 0.3

# Land on Minmus' Great Flats, and wait for MechJeb to see the target
landing = mj.landing_guidance
landing.set_target(minmus, 0, -6)
wait_for(lambda: mj.target_controller.position_target_exists)

# The settings of the Landing Guidance window
landing.touchdown_speed = 1
landing.deploy_gears = True
landing.autowarp = True

# Print each step of the autopilot
status = print_steps(landing)

landing.land_at_target()

# Wait for the autopilot to disengage, once the vessel has landed
wait_for(lambda: not landing.enabled)
status.remove()

sc.clear_target()
flight = vessel.flight()
print(
    "Landed at latitude %.2f, longitude %.2f"
    % (flight.latitude, flight.longitude)
)

The landing legs are on the lander, above the transfer stage. The legs’ SpaceCenter.Part.decouple_stage is the stage that drops the lander. The script stages until that stage is next, which drops the transfer stage and activates the lander’s engine. It first turns off MechJeb’s autostaging, so the script alone stages the lander:

# Stage until the next stage would drop the landing legs. This drops
# the stages below the lander, and activates the lander's engine.
mj.utilities.staging.enabled = False
legs = vessel.parts.legs[0].part
while vessel.control.current_stage > legs.decouple_stage + 1:
    vessel.control.activate_next_stage()

# Limit the lander's thrust, so its lowest throttle leaves it falling
for engine in vessel.parts.engines:
    engine.thrust_limit = 0.3

MechJeb keeps the throttle at 5% or more. At full thrust, the lander’s engine is too strong for Minmus’ weak gravity, and the lander climbs even at 5% throttle. A thrust limit of 30% lets the lowest throttle leave the lander falling. ThrustLimiter.min_throttle sets that lowest throttle.

LandingGuidance.set_target() sets the landing target, as a latitude and longitude. The autopilot burns to deorbit over the target, then brakes to a hover 200 m above it. Once it has stopped drifting, it descends at LandingGuidance.touchdown_speed, and disengages once the vessel has landed.

See also

Migration from KRPC.MechJeb 0.7.1 for scripts written for KRPC.MechJeb 0.7.1.