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,
)
)
var conn = new Connection ("Launch to Minmus");
var sc = conn.SpaceCenter ();
var vessel = sc.ActiveVessel;
var mj = conn.MechJeb ();
// Wait until the condition is true
void WaitFor (Expression<Func<bool>> condition)
{
var evnt = conn.AddEvent (condition);
lock (evnt.Condition) {
evnt.Wait ();
}
}
// Print each step of the autopilot. Returns the status stream.
Stream<string> PrintSteps (Expression<Func<string>> autopilotStatus)
{
var last = "";
var status = conn.AddStream (autopilotStatus);
status.AddCallback ((string value) => {
// The step, without the figures that change on each update
var line = value.Split ('\n') [0];
var step = Regex.Split (line, "[0-9∞]") [0];
step = step.TrimEnd (' ', ':', '=');
if (step.Length > 0 && step != last) {
last = step;
Console.WriteLine (step);
}
});
return status;
}
void PrintOrbit ()
{
var orbit = vessel.Orbit;
Console.WriteLine (
"Orbit of {0}, {1:F0} km by {2:F0} km", orbit.Body.Name,
orbit.ApoapsisAltitude / 1000,
orbit.PeriapsisAltitude / 1000);
}
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <krpc.hpp>
#include <krpc/function_stream.hpp>
#include <krpc/services/krpc.hpp>
#include <krpc/services/mech_jeb.hpp>
#include <krpc/services/space_center.hpp>
#include <memory>
#include <string>
using krpc::services::KRPC;
using krpc::services::MechJeb;
using krpc::services::SpaceCenter;
// Wait until the condition is true
void wait_for(const KRPC::Expression& condition) {
auto event = krpc::add_event(condition);
event.acquire();
event.wait();
event.release();
}
// Print each step of the autopilot, from a stream of its status
void print_steps(krpc::Stream<std::string> status) {
auto last = std::make_shared<std::string>();
status.add_callback([last](const std::string& value) {
// The step, without the figures that change on each update
std::string step = value.substr(0, value.find('\n'));
step = step.substr(
0, std::min(step.find_first_of("0123456789"), step.find("\u221e")));
step.erase(step.find_last_not_of(" :=") + 1);
if (!step.empty() && step != *last) {
*last = step;
std::cout << step << std::endl;
}
});
}
void print_orbit(SpaceCenter::Vessel vessel) {
auto orbit = vessel.orbit();
std::printf("Orbit of %s, %.0f km by %.0f km\n",
orbit.body().name().c_str(), orbit.apoapsis_altitude() / 1000,
orbit.periapsis_altitude() / 1000);
}
int main() {
krpc::Connection conn = krpc::connect("Launch to Minmus");
SpaceCenter sc(conn);
MechJeb mj(conn);
auto vessel = sc.active_vessel().value();
auto e = KRPC::Expression::bind(conn);
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define sleep_ms(ms) Sleep(ms)
#else
#define _POSIX_C_SOURCE 200809L
#include <time.h>
static void sleep_ms(long ms) {
struct timespec duration = {ms / 1000, (ms % 1000) * 1000000};
nanosleep(&duration, NULL);
}
#endif
#include <krpc_cnano.h>
#include <krpc_cnano/services/mech_jeb.h>
#include <krpc_cnano/services/space_center.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
// Print the step of an autopilot's status, if it differs from the last
static void print_step(const char* status, char* last, size_t size) {
// The step, without the figures that change on each update
size_t length = strcspn(status, "\n0123456789");
const char* infinity = strstr(status, "∞");
if (infinity && (size_t)(infinity - status) < length)
length = infinity - status;
while (length > 0 && strchr(" :=", status[length - 1])) length--;
if (length == 0 || length >= size) return;
if (strncmp(status, last, length) == 0 && last[length] == '\0') return;
memcpy(last, status, length);
last[length] = '\0';
printf("%s\n", last);
}
static void print_orbit(krpc_connection_t conn,
krpc_SpaceCenter_Vessel_t vessel) {
krpc_SpaceCenter_Orbit_t orbit;
krpc_SpaceCenter_Vessel_Orbit(conn, &orbit, vessel);
krpc_SpaceCenter_CelestialBody_t body;
krpc_SpaceCenter_Orbit_Body(conn, &body, orbit);
char* name = NULL;
krpc_SpaceCenter_CelestialBody_Name(conn, &name, body);
double apoapsis, periapsis;
krpc_SpaceCenter_Orbit_ApoapsisAltitude(conn, &apoapsis, orbit);
krpc_SpaceCenter_Orbit_PeriapsisAltitude(conn, &periapsis, orbit);
printf("Orbit of %s, %.0f km by %.0f km\n", name, apoapsis / 1000,
periapsis / 1000);
krpc_free(name);
}
// Execute the vessel's maneuver nodes, and wait for the burns
static void execute_nodes(krpc_connection_t conn,
krpc_MechJeb_ManeuverPlanner_t planner) {
krpc_MechJeb_ManeuverPlanner_ExecuteAllNodes(conn, planner);
bool executing = true;
while (executing) {
sleep_ms(100);
krpc_MechJeb_ManeuverPlanner_ExecutingNode(conn, &executing, planner);
}
}
int main() {
krpc_connection_t conn;
if (krpc_open_serial(&conn, "COM0") != KRPC_OK) return 1;
if (krpc_connect(conn, "Launch to Minmus") != KRPC_OK) return 1;
krpc_SpaceCenter_Vessel_t vessel;
krpc_SpaceCenter_ActiveVessel(conn, &vessel);
krpc_SpaceCenter_Control_t control;
krpc_SpaceCenter_Vessel_Control(conn, &control, vessel);
public class LaunchToMinmus {
static Connection connection;
static Vessel vessel;
/** Wait until the condition is true. */
static void waitFor(Expression condition) {
Event event = connection.addEvent(condition);
synchronized (event.getCondition()) {
event.waitFor();
}
}
/** Print each step of the autopilot, from a stream of its status. */
static void printSteps(Stream<String> status) {
String[] last = {""};
status.addCallback(value -> {
// The step, without the figures that change on each update
String line = value.split("\n", -1)[0];
String step = line.split("[0-9∞]", -1)[0];
step = step.replaceAll("[ :=]+$", "");
if (!step.isEmpty() && !step.equals(last[0])) {
last[0] = step;
System.out.println(step);
}
});
}
/** Execute the vessel's maneuver nodes, and wait for the burns. */
static void executeNodes(ManeuverPlanner planner) {
planner.executeAllNodes();
Expression.Bound e = Expression.bind(connection);
waitFor(e.not(
e.call(connection.getCall(planner, "getExecutingNode"))));
}
static void printOrbit() {
Orbit orbit = vessel.getOrbit();
System.out.printf(
"Orbit of %s, %.0f km by %.0f km%n", orbit.getBody().getName(),
orbit.getApoapsisAltitude() / 1000,
orbit.getPeriapsisAltitude() / 1000);
}
public static void main(String[] args) {
connection = Connection.newInstance("Launch to Minmus");
SpaceCenter sc = SpaceCenter.newInstance(connection);
vessel = sc.getActiveVessel();
MechJeb mj = MechJeb.newInstance(connection);
Expression.Bound e = Expression.bind(connection);
local krpc = require 'krpc'
local socket = require 'socket'
local conn = krpc.connect('Launch to Minmus')
local sc = conn.space_center
local vessel = sc.active_vessel
local mj = conn.mech_jeb
-- Wait until the condition is true
local function wait_for(condition)
while not condition() do
socket.sleep(0.1)
end
end
-- Wait for the autopilot to disengage, printing each of its steps
local function wait_for_steps(autopilot)
local last = ''
while autopilot.enabled do
-- The step, without the figures that change on each update
local line = autopilot.status:match('^[^\n]*')
local step = line:gsub('∞.*', ''):match('^[^%d]*')
step = step:gsub('[ :=]*$', '')
if step ~= '' and step ~= last then
last = step
print(step)
end
socket.sleep(0.1)
end
end
local function print_orbit()
local orbit = vessel.orbit
print(string.format('Orbit of %s, %.0f km by %.0f km',
orbit.body.name,
orbit.apoapsis_altitude / 1000,
orbit.periapsis_altitude / 1000))
end
import { connect } from "@krpc-org/krpc";
const conn = await connect({ name: "Launch to Minmus" });
const sc = conn.spaceCenter;
const vessel = await sc.getActiveVessel();
const control = await vessel.getControl();
const mj = conn.mechJeb;
/**
* Wait until the condition is true.
* @template {object} C
* @param {(
* captures: import("@krpc-org/krpc").OnServer<C>,
* ) => boolean} condition
* @param {C} captures
*/
async function waitFor(condition, captures) {
const event = await conn.addEvent(condition, captures);
await event.wait();
}
/**
* Print each step of the autopilot. Returns the status stream.
* @param {{ getStatus(): Promise<string> }} autopilot
*/
async function printSteps(autopilot) {
let last = "";
const status = await conn.addStream(() => autopilot.getStatus());
status.addCallback((value) => {
// The step, without the figures that change on each update
const line = value.split("\n")[0];
const step = line.split(/[0-9∞]/)[0].replace(/[ :=]+$/, "");
if (step && step !== last) {
last = step;
console.log(step);
}
});
return status;
}
async function printOrbit() {
const orbit = await vessel.getOrbit();
const body = await orbit.getBody();
const apoapsis = (await orbit.getApoapsisAltitude()) / 1000;
const periapsis = (await orbit.getPeriapsisAltitude()) / 1000;
console.log(
`Orbit of ${await body.getName()}, ` +
`${apoapsis.toFixed(0)} km by ${periapsis.toFixed(0)} km`,
);
}
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 target orbit, set as in the Ascent Guidance window
var ascent = mj.AscentGuidance;
ascent.AscentType = AscentType.Classic;
ascent.DesiredOrbitAltitude = 100000;
ascent.DesiredInclination = 0;
// The Ascent Settings window
var settings = ascent.Settings;
settings.Autostage = true;
settings.LimitAngleOfAttack = true;
settings.MaxAngleOfAttack = 5;
settings.Autowarp = true;
// Print each step of the autopilot
var status = PrintSteps (() => ascent.Status);
ascent.Enabled = true;
vessel.Control.ActivateNextStage ();
// Wait for the autopilot to disengage, once the orbit is circular
WaitFor (() => !ascent.Enabled);
status.Remove ();
PrintOrbit ();
// The target orbit, set as in the Ascent Guidance window
auto ascent = mj.ascent_guidance();
ascent.set_ascent_type(MechJeb::AscentType::classic);
ascent.set_desired_orbit_altitude(100000);
ascent.set_desired_inclination(0);
// The Ascent Settings window
auto settings = ascent.settings();
settings.set_autostage(true);
settings.set_limit_angle_of_attack(true);
settings.set_max_angle_of_attack(5);
settings.set_autowarp(true);
// Print each step of the autopilot
auto status = ascent.status_stream();
print_steps(status);
ascent.set_enabled(true);
vessel.control().activate_next_stage();
// Wait for the autopilot to disengage, once the orbit is circular
wait_for(e.not_(e.call(ascent.enabled_call())));
status.remove();
print_orbit(vessel);
// The target orbit, set as in the Ascent Guidance window
krpc_MechJeb_AscentGuidance_t ascent;
krpc_MechJeb_AscentGuidance(conn, &ascent);
krpc_MechJeb_AscentGuidance_set_AscentType(
conn, ascent, KRPC_MECHJEB_ASCENTTYPE_CLASSIC);
krpc_MechJeb_AscentGuidance_set_DesiredOrbitAltitude(conn, ascent,
100000);
krpc_MechJeb_AscentGuidance_set_DesiredInclination(conn, ascent, 0);
// The Ascent Settings window
krpc_MechJeb_AscentSettings_t settings;
krpc_MechJeb_AscentGuidance_Settings(conn, &settings, ascent);
krpc_MechJeb_AscentSettings_set_Autostage(conn, settings, true);
krpc_MechJeb_AscentSettings_set_LimitAngleOfAttack(conn, settings, true);
krpc_MechJeb_AscentSettings_set_MaxAngleOfAttack(conn, settings, 5);
krpc_MechJeb_AscentSettings_set_Autowarp(conn, settings, true);
krpc_MechJeb_AscentGuidance_set_Enabled(conn, ascent, true);
krpc_SpaceCenter_Control_ActivateNextStage(conn, NULL, control);
// Wait for the autopilot to disengage, once the orbit is circular,
// and print each of its steps
char step[128] = "";
bool enabled = true;
while (enabled) {
char* status = NULL;
krpc_MechJeb_AscentGuidance_Status(conn, &status, ascent);
print_step(status, step, sizeof(step));
krpc_free(status);
sleep_ms(100);
krpc_MechJeb_AscentGuidance_Enabled(conn, &enabled, ascent);
}
print_orbit(conn, vessel);
// The target orbit, set as in the Ascent Guidance window
AscentGuidance ascent = mj.getAscentGuidance();
ascent.setAscentType(AscentType.CLASSIC);
ascent.setDesiredOrbitAltitude(100000);
ascent.setDesiredInclination(0);
// The Ascent Settings window
AscentSettings settings = ascent.getSettings();
settings.setAutostage(true);
settings.setLimitAngleOfAttack(true);
settings.setMaxAngleOfAttack(5);
settings.setAutowarp(true);
// Print each step of the autopilot
Stream<String> status = connection.addStream(ascent, "getStatus");
printSteps(status);
ascent.setEnabled(true);
vessel.getControl().activateNextStage();
// Wait for the autopilot to disengage, once the orbit is circular
waitFor(e.not(e.call(connection.getCall(ascent, "getEnabled"))));
status.remove();
printOrbit();
-- The target orbit, set as in the Ascent Guidance window
local ascent = mj.ascent_guidance
ascent.ascent_type = mj.AscentType.classic
ascent.desired_orbit_altitude = 100000
ascent.desired_inclination = 0
-- The Ascent Settings window
local settings = ascent.settings
settings.autostage = true
settings.limit_angle_of_attack = true
settings.max_angle_of_attack = 5
settings.autowarp = true
ascent.enabled = true
vessel.control:activate_next_stage()
-- Wait for the autopilot to disengage, once the orbit is circular
wait_for_steps(ascent)
print_orbit()
// The target orbit, set as in the Ascent Guidance window
const ascent = await mj.getAscentGuidance();
await ascent.setAscentType(mj.AscentType.classic);
await ascent.setDesiredOrbitAltitude(100000);
await ascent.setDesiredInclination(0);
// The Ascent Settings window
const settings = await ascent.getSettings();
await settings.setAutostage(true);
await settings.setLimitAngleOfAttack(true);
await settings.setMaxAngleOfAttack(5);
await settings.setAutowarp(true);
// Print each step of the autopilot
let status = await printSteps(ascent);
await ascent.setEnabled(true);
await control.activateNextStage();
// Wait for the autopilot to disengage, once the orbit is circular
await waitFor(({ ascent }) => !ascent.enabled, { ascent });
await status.remove();
await printOrbit();
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()
var planner = mj.ManeuverPlanner;
planner.Autowarp = true;
// Stage once a stage burns out, during the burns too
mj.Utilities.Staging.Enabled = true;
// Execute the vessel's maneuver nodes, and wait for the burns
void ExecuteNodes ()
{
planner.ExecuteAllNodes ();
WaitFor (() => !planner.ExecutingNode);
}
// Target Minmus, and wait for MechJeb to see the target
var minmus = sc.Bodies ["Minmus"];
sc.TargetBody = minmus;
var targetController = mj.TargetController;
WaitFor (() => targetController.NormalTargetExists);
// Match planes with Minmus, at the nearest relative node
var plane = planner.OperationPlane;
plane.TimeSelector.TimeReference = TimeReference.RelNearestAd;
plane.MakeNodes ();
ExecuteNodes ();
// The Hohmann transfer, to an encounter with no capture burn
var transfer = planner.OperationTransfer;
transfer.TimeSelector.TimeReference = TimeReference.Computed;
transfer.Capture = false;
transfer.MakeNodes ();
ExecuteNodes ();
// Fine tune the encounter, for a periapsis 20 km above Minmus
var correction = planner.OperationCourseCorrection;
correction.FinalPeriapsisAltitude = 20000;
correction.MakeNodes ();
ExecuteNodes ();
// Warp into Minmus' sphere of influence
sc.WarpTo (sc.UT + vessel.Orbit.TimeToSOIChange + 60);
// Circularize at the periapsis
var circularize = planner.OperationCircularize;
circularize.TimeSelector.TimeReference = TimeReference.Periapsis;
circularize.MakeNodes ();
ExecuteNodes ();
sc.ClearTarget ();
PrintOrbit ();
auto planner = mj.maneuver_planner();
planner.set_autowarp(true);
// Stage once a stage burns out, during the burns too
mj.utilities().staging().set_enabled(true);
// Execute the vessel's maneuver nodes, and wait for the burns
auto execute_nodes = [&]() {
planner.execute_all_nodes();
wait_for(e.not_(e.call(planner.executing_node_call())));
};
// Target Minmus, and wait for MechJeb to see the target
auto minmus = sc.bodies()["Minmus"];
sc.set_target_body(minmus);
auto target_controller = mj.target_controller();
wait_for(e.call(target_controller.normal_target_exists_call()));
// Match planes with Minmus, at the nearest relative node
auto plane = planner.operation_plane();
plane.time_selector().set_time_reference(
MechJeb::TimeReference::rel_nearest_ad);
plane.make_nodes();
execute_nodes();
// The Hohmann transfer, to an encounter with no capture burn
auto transfer = planner.operation_transfer();
transfer.time_selector().set_time_reference(
MechJeb::TimeReference::computed);
transfer.set_capture(false);
transfer.make_nodes();
execute_nodes();
// Fine tune the encounter, for a periapsis 20 km above Minmus
auto correction = planner.operation_course_correction();
correction.set_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
auto circularize = planner.operation_circularize();
circularize.time_selector().set_time_reference(
MechJeb::TimeReference::periapsis);
circularize.make_nodes();
execute_nodes();
sc.clear_target();
print_orbit(vessel);
krpc_MechJeb_ManeuverPlanner_t planner;
krpc_MechJeb_ManeuverPlanner(conn, &planner);
krpc_MechJeb_ManeuverPlanner_set_Autowarp(conn, planner, true);
// Stage once a stage burns out, during the burns too
krpc_MechJeb_Utilities_t utilities;
krpc_MechJeb_Utilities(conn, &utilities);
krpc_MechJeb_Autostaging_t staging;
krpc_MechJeb_Utilities_Staging(conn, &staging, utilities);
krpc_MechJeb_Autostaging_set_Enabled(conn, staging, true);
// Target Minmus, and wait for MechJeb to see the target
krpc_dictionary_string_object_t bodies = KRPC_NULL_DICTIONARY;
krpc_SpaceCenter_Bodies(conn, &bodies);
krpc_SpaceCenter_CelestialBody_t minmus = KRPC_NULL;
for (size_t i = 0; i < bodies.size; i++)
if (!strcmp(bodies.entries[i].key, "Minmus"))
minmus = bodies.entries[i].value;
KRPC_FREE_DICTIONARY(bodies);
krpc_SpaceCenter_set_TargetBody(conn, minmus);
krpc_MechJeb_TargetController_t target_controller;
krpc_MechJeb_TargetController(conn, &target_controller);
bool target_exists = false;
while (!target_exists) {
sleep_ms(100);
krpc_MechJeb_TargetController_NormalTargetExists(conn, &target_exists,
target_controller);
}
// Match planes with Minmus, at the nearest relative node
krpc_list_object_t nodes = KRPC_NULL_LIST;
krpc_MechJeb_OperationPlane_t plane;
krpc_MechJeb_ManeuverPlanner_OperationPlane(conn, &plane, planner);
krpc_MechJeb_TimeSelector_t time_selector;
krpc_MechJeb_OperationPlane_TimeSelector(conn, &time_selector, plane);
krpc_MechJeb_TimeSelector_set_TimeReference(
conn, time_selector, KRPC_MECHJEB_TIMEREFERENCE_RELNEARESTAD);
krpc_MechJeb_OperationPlane_MakeNodes(conn, &nodes, plane);
KRPC_FREE_LIST(nodes);
execute_nodes(conn, planner);
// The Hohmann transfer, to an encounter with no capture burn
krpc_MechJeb_OperationTransfer_t transfer;
krpc_MechJeb_ManeuverPlanner_OperationTransfer(conn, &transfer, planner);
krpc_MechJeb_OperationTransfer_TimeSelector(conn, &time_selector,
transfer);
krpc_MechJeb_TimeSelector_set_TimeReference(
conn, time_selector, KRPC_MECHJEB_TIMEREFERENCE_COMPUTED);
krpc_MechJeb_OperationTransfer_set_Capture(conn, transfer, false);
krpc_MechJeb_OperationTransfer_MakeNodes(conn, &nodes, transfer);
KRPC_FREE_LIST(nodes);
execute_nodes(conn, planner);
// Fine tune the encounter, for a periapsis 20 km above Minmus
krpc_MechJeb_OperationCourseCorrection_t correction;
krpc_MechJeb_ManeuverPlanner_OperationCourseCorrection(conn, &correction,
planner);
krpc_MechJeb_OperationCourseCorrection_set_FinalPeriapsisAltitude(
conn, correction, 20000);
krpc_MechJeb_OperationCourseCorrection_MakeNodes(conn, &nodes,
correction);
KRPC_FREE_LIST(nodes);
execute_nodes(conn, planner);
// Warp into Minmus' sphere of influence
double ut, time_to_soi_change;
krpc_SpaceCenter_UT(conn, &ut);
krpc_SpaceCenter_Orbit_t orbit;
krpc_SpaceCenter_Vessel_Orbit(conn, &orbit, vessel);
krpc_SpaceCenter_Orbit_TimeToSOIChange(conn, &time_to_soi_change, orbit);
krpc_SpaceCenter_WarpTo(conn, ut + time_to_soi_change + 60, 100000, 2);
// Circularize at the periapsis
krpc_MechJeb_OperationCircularize_t circularize;
krpc_MechJeb_ManeuverPlanner_OperationCircularize(conn, &circularize,
planner);
krpc_MechJeb_OperationCircularize_TimeSelector(conn, &time_selector,
circularize);
krpc_MechJeb_TimeSelector_set_TimeReference(
conn, time_selector, KRPC_MECHJEB_TIMEREFERENCE_PERIAPSIS);
krpc_MechJeb_OperationCircularize_MakeNodes(conn, &nodes, circularize);
KRPC_FREE_LIST(nodes);
execute_nodes(conn, planner);
krpc_SpaceCenter_ClearTarget(conn);
print_orbit(conn, vessel);
ManeuverPlanner planner = mj.getManeuverPlanner();
planner.setAutowarp(true);
// Stage once a stage burns out, during the burns too
mj.getUtilities().getStaging().setEnabled(true);
// Target Minmus, and wait for MechJeb to see the target
CelestialBody minmus = sc.getBodies().get("Minmus");
sc.setTargetBody(minmus);
TargetController targetController = mj.getTargetController();
waitFor(e.call(
connection.getCall(targetController, "getNormalTargetExists")));
// Match planes with Minmus, at the nearest relative node
OperationPlane plane = planner.getOperationPlane();
plane.getTimeSelector().setTimeReference(
TimeReference.REL_NEAREST_AD);
plane.makeNodes();
executeNodes(planner);
// The Hohmann transfer, to an encounter with no capture burn
OperationTransfer transfer = planner.getOperationTransfer();
transfer.getTimeSelector().setTimeReference(TimeReference.COMPUTED);
transfer.setCapture(false);
transfer.makeNodes();
executeNodes(planner);
// Fine tune the encounter, for a periapsis 20 km above Minmus
OperationCourseCorrection correction =
planner.getOperationCourseCorrection();
correction.setFinalPeriapsisAltitude(20000);
correction.makeNodes();
executeNodes(planner);
// Warp into Minmus' sphere of influence
sc.warpTo(
sc.getUT() + vessel.getOrbit().getTimeToSOIChange() + 60,
100000, 2);
// Circularize at the periapsis
OperationCircularize circularize =
planner.getOperationCircularize();
circularize.getTimeSelector().setTimeReference(
TimeReference.PERIAPSIS);
circularize.makeNodes();
executeNodes(planner);
sc.clearTarget();
printOrbit();
local planner = mj.maneuver_planner
planner.autowarp = true
-- Stage once a stage burns out, during the burns too
mj.utilities.staging.enabled = true
-- Execute the vessel's maneuver nodes, and wait for the burns
local function execute_nodes()
planner:execute_all_nodes()
wait_for(function() return not planner.executing_node end)
end
-- Target Minmus, and wait for MechJeb to see the target
local minmus = sc.bodies['Minmus']
sc.target_body = minmus
wait_for(function() return mj.target_controller.normal_target_exists end)
-- Match planes with Minmus, at the nearest relative node
local 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
local 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
local 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
local circularize = planner.operation_circularize
circularize.time_selector.time_reference = mj.TimeReference.periapsis
circularize:make_nodes()
execute_nodes()
sc.clear_target()
print_orbit()
const planner = await mj.getManeuverPlanner();
await planner.setAutowarp(true);
// Stage once a stage burns out, during the burns too
const staging = await (await mj.getUtilities()).getStaging();
await staging.setEnabled(true);
/** Execute the vessel's maneuver nodes, and wait for the burns. */
async function executeNodes() {
await planner.executeAllNodes();
await waitFor(({ planner }) => !planner.executingNode, { planner });
}
// Target Minmus, and wait for MechJeb to see the target
const minmus = (await sc.getBodies()).get("Minmus");
await sc.setTargetBody(minmus);
const targetController = await mj.getTargetController();
await waitFor(
({ targetController }) => targetController.normalTargetExists,
{ targetController },
);
// Match planes with Minmus, at the nearest relative node
const plane = await planner.getOperationPlane();
await (await plane.getTimeSelector()).setTimeReference(
mj.TimeReference.relNearestAd,
);
await plane.makeNodes();
await executeNodes();
// The Hohmann transfer, to an encounter with no capture burn
const transfer = await planner.getOperationTransfer();
await (await transfer.getTimeSelector()).setTimeReference(
mj.TimeReference.computed,
);
await transfer.setCapture(false);
await transfer.makeNodes();
await executeNodes();
// Fine tune the encounter, for a periapsis 20 km above Minmus
const correction = await planner.getOperationCourseCorrection();
await correction.setFinalPeriapsisAltitude(20000);
await correction.makeNodes();
await executeNodes();
// Warp into Minmus' sphere of influence
const orbit = await vessel.getOrbit();
const soiChange = (await sc.getUT()) + (await orbit.getTimeToSOIChange());
await sc.warpTo(soiChange + 60);
// Circularize at the periapsis
const circularize = await planner.getOperationCircularize();
await (await circularize.getTimeSelector()).setTimeReference(
mj.TimeReference.periapsis,
);
await circularize.makeNodes();
await executeNodes();
await sc.clearTarget();
await printOrbit();
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)
// Execute the vessel's maneuver nodes, and wait for the burns
void ExecuteNodes ()
{
planner.ExecuteAllNodes ();
WaitFor (() => !planner.ExecutingNode);
}
// Execute the vessel's maneuver nodes, and wait for the burns
auto execute_nodes = [&]() {
planner.execute_all_nodes();
wait_for(e.not_(e.call(planner.executing_node_call())));
};
// Execute the vessel's maneuver nodes, and wait for the burns
static void execute_nodes(krpc_connection_t conn,
krpc_MechJeb_ManeuverPlanner_t planner) {
krpc_MechJeb_ManeuverPlanner_ExecuteAllNodes(conn, planner);
bool executing = true;
while (executing) {
sleep_ms(100);
krpc_MechJeb_ManeuverPlanner_ExecutingNode(conn, &executing, planner);
}
}
/** Execute the vessel's maneuver nodes, and wait for the burns. */
static void executeNodes(ManeuverPlanner planner) {
planner.executeAllNodes();
Expression.Bound e = Expression.bind(connection);
waitFor(e.not(
e.call(connection.getCall(planner, "getExecutingNode"))));
}
-- Execute the vessel's maneuver nodes, and wait for the burns
local function execute_nodes()
planner:execute_all_nodes()
wait_for(function() return not planner.executing_node end)
end
/** Execute the vessel's maneuver nodes, and wait for the burns. */
async function executeNodes() {
await planner.executeAllNodes();
await waitFor(({ planner }) => !planner.executingNode, { planner });
}
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
// Stage once a stage burns out, during the burns too
mj.Utilities.Staging.Enabled = true;
// Stage once a stage burns out, during the burns too
mj.utilities().staging().set_enabled(true);
// Stage once a stage burns out, during the burns too
krpc_MechJeb_Utilities_t utilities;
krpc_MechJeb_Utilities(conn, &utilities);
krpc_MechJeb_Autostaging_t staging;
krpc_MechJeb_Utilities_Staging(conn, &staging, utilities);
krpc_MechJeb_Autostaging_set_Enabled(conn, staging, true);
// Stage once a stage burns out, during the burns too
mj.getUtilities().getStaging().setEnabled(true);
-- Stage once a stage burns out, during the burns too
mj.utilities.staging.enabled = true
// Stage once a stage burns out, during the burns too
const staging = await (await mj.getUtilities()).getStaging();
await staging.setEnabled(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)
// Target Minmus, and wait for MechJeb to see the target
var minmus = sc.Bodies ["Minmus"];
sc.TargetBody = minmus;
var targetController = mj.TargetController;
WaitFor (() => targetController.NormalTargetExists);
// Target Minmus, and wait for MechJeb to see the target
auto minmus = sc.bodies()["Minmus"];
sc.set_target_body(minmus);
auto target_controller = mj.target_controller();
wait_for(e.call(target_controller.normal_target_exists_call()));
// Target Minmus, and wait for MechJeb to see the target
krpc_dictionary_string_object_t bodies = KRPC_NULL_DICTIONARY;
krpc_SpaceCenter_Bodies(conn, &bodies);
krpc_SpaceCenter_CelestialBody_t minmus = KRPC_NULL;
for (size_t i = 0; i < bodies.size; i++)
if (!strcmp(bodies.entries[i].key, "Minmus"))
minmus = bodies.entries[i].value;
KRPC_FREE_DICTIONARY(bodies);
krpc_SpaceCenter_set_TargetBody(conn, minmus);
krpc_MechJeb_TargetController_t target_controller;
krpc_MechJeb_TargetController(conn, &target_controller);
bool target_exists = false;
while (!target_exists) {
sleep_ms(100);
krpc_MechJeb_TargetController_NormalTargetExists(conn, &target_exists,
target_controller);
}
// Target Minmus, and wait for MechJeb to see the target
CelestialBody minmus = sc.getBodies().get("Minmus");
sc.setTargetBody(minmus);
TargetController targetController = mj.getTargetController();
waitFor(e.call(
connection.getCall(targetController, "getNormalTargetExists")));
-- Target Minmus, and wait for MechJeb to see the target
local minmus = sc.bodies['Minmus']
sc.target_body = minmus
wait_for(function() return mj.target_controller.normal_target_exists end)
// Target Minmus, and wait for MechJeb to see the target
const minmus = (await sc.getBodies()).get("Minmus");
await sc.setTargetBody(minmus);
const targetController = await mj.getTargetController();
await waitFor(
({ targetController }) => targetController.normalTargetExists,
{ targetController },
);
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()
// Match planes with Minmus, at the nearest relative node
var plane = planner.OperationPlane;
plane.TimeSelector.TimeReference = TimeReference.RelNearestAd;
plane.MakeNodes ();
ExecuteNodes ();
// Match planes with Minmus, at the nearest relative node
auto plane = planner.operation_plane();
plane.time_selector().set_time_reference(
MechJeb::TimeReference::rel_nearest_ad);
plane.make_nodes();
execute_nodes();
// Match planes with Minmus, at the nearest relative node
krpc_list_object_t nodes = KRPC_NULL_LIST;
krpc_MechJeb_OperationPlane_t plane;
krpc_MechJeb_ManeuverPlanner_OperationPlane(conn, &plane, planner);
krpc_MechJeb_TimeSelector_t time_selector;
krpc_MechJeb_OperationPlane_TimeSelector(conn, &time_selector, plane);
krpc_MechJeb_TimeSelector_set_TimeReference(
conn, time_selector, KRPC_MECHJEB_TIMEREFERENCE_RELNEARESTAD);
krpc_MechJeb_OperationPlane_MakeNodes(conn, &nodes, plane);
KRPC_FREE_LIST(nodes);
execute_nodes(conn, planner);
// Match planes with Minmus, at the nearest relative node
OperationPlane plane = planner.getOperationPlane();
plane.getTimeSelector().setTimeReference(
TimeReference.REL_NEAREST_AD);
plane.makeNodes();
executeNodes(planner);
-- Match planes with Minmus, at the nearest relative node
local plane = planner.operation_plane
plane.time_selector.time_reference = mj.TimeReference.rel_nearest_ad
plane:make_nodes()
execute_nodes()
// Match planes with Minmus, at the nearest relative node
const plane = await planner.getOperationPlane();
await (await plane.getTimeSelector()).setTimeReference(
mj.TimeReference.relNearestAd,
);
await plane.makeNodes();
await executeNodes();
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()
// The Hohmann transfer, to an encounter with no capture burn
var transfer = planner.OperationTransfer;
transfer.TimeSelector.TimeReference = TimeReference.Computed;
transfer.Capture = false;
transfer.MakeNodes ();
ExecuteNodes ();
// The Hohmann transfer, to an encounter with no capture burn
auto transfer = planner.operation_transfer();
transfer.time_selector().set_time_reference(
MechJeb::TimeReference::computed);
transfer.set_capture(false);
transfer.make_nodes();
execute_nodes();
// The Hohmann transfer, to an encounter with no capture burn
krpc_MechJeb_OperationTransfer_t transfer;
krpc_MechJeb_ManeuverPlanner_OperationTransfer(conn, &transfer, planner);
krpc_MechJeb_OperationTransfer_TimeSelector(conn, &time_selector,
transfer);
krpc_MechJeb_TimeSelector_set_TimeReference(
conn, time_selector, KRPC_MECHJEB_TIMEREFERENCE_COMPUTED);
krpc_MechJeb_OperationTransfer_set_Capture(conn, transfer, false);
krpc_MechJeb_OperationTransfer_MakeNodes(conn, &nodes, transfer);
KRPC_FREE_LIST(nodes);
execute_nodes(conn, planner);
// The Hohmann transfer, to an encounter with no capture burn
OperationTransfer transfer = planner.getOperationTransfer();
transfer.getTimeSelector().setTimeReference(TimeReference.COMPUTED);
transfer.setCapture(false);
transfer.makeNodes();
executeNodes(planner);
-- The Hohmann transfer, to an encounter with no capture burn
local transfer = planner.operation_transfer
transfer.time_selector.time_reference = mj.TimeReference.computed
transfer.capture = false
transfer:make_nodes()
execute_nodes()
// The Hohmann transfer, to an encounter with no capture burn
const transfer = await planner.getOperationTransfer();
await (await transfer.getTimeSelector()).setTimeReference(
mj.TimeReference.computed,
);
await transfer.setCapture(false);
await transfer.makeNodes();
await executeNodes();
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()
// Fine tune the encounter, for a periapsis 20 km above Minmus
var correction = planner.OperationCourseCorrection;
correction.FinalPeriapsisAltitude = 20000;
correction.MakeNodes ();
ExecuteNodes ();
// Fine tune the encounter, for a periapsis 20 km above Minmus
auto correction = planner.operation_course_correction();
correction.set_final_periapsis_altitude(20000);
correction.make_nodes();
execute_nodes();
// Fine tune the encounter, for a periapsis 20 km above Minmus
krpc_MechJeb_OperationCourseCorrection_t correction;
krpc_MechJeb_ManeuverPlanner_OperationCourseCorrection(conn, &correction,
planner);
krpc_MechJeb_OperationCourseCorrection_set_FinalPeriapsisAltitude(
conn, correction, 20000);
krpc_MechJeb_OperationCourseCorrection_MakeNodes(conn, &nodes,
correction);
KRPC_FREE_LIST(nodes);
execute_nodes(conn, planner);
// Fine tune the encounter, for a periapsis 20 km above Minmus
OperationCourseCorrection correction =
planner.getOperationCourseCorrection();
correction.setFinalPeriapsisAltitude(20000);
correction.makeNodes();
executeNodes(planner);
-- Fine tune the encounter, for a periapsis 20 km above Minmus
local correction = planner.operation_course_correction
correction.final_periapsis_altitude = 20000
correction:make_nodes()
execute_nodes()
// Fine tune the encounter, for a periapsis 20 km above Minmus
const correction = await planner.getOperationCourseCorrection();
await correction.setFinalPeriapsisAltitude(20000);
await correction.makeNodes();
await executeNodes();
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()
// Warp into Minmus' sphere of influence
sc.WarpTo (sc.UT + vessel.Orbit.TimeToSOIChange + 60);
// Circularize at the periapsis
var circularize = planner.OperationCircularize;
circularize.TimeSelector.TimeReference = TimeReference.Periapsis;
circularize.MakeNodes ();
ExecuteNodes ();
// Warp into Minmus' sphere of influence
sc.warp_to(sc.ut() + vessel.orbit().time_to_soi_change() + 60);
// Circularize at the periapsis
auto circularize = planner.operation_circularize();
circularize.time_selector().set_time_reference(
MechJeb::TimeReference::periapsis);
circularize.make_nodes();
execute_nodes();
// Warp into Minmus' sphere of influence
double ut, time_to_soi_change;
krpc_SpaceCenter_UT(conn, &ut);
krpc_SpaceCenter_Orbit_t orbit;
krpc_SpaceCenter_Vessel_Orbit(conn, &orbit, vessel);
krpc_SpaceCenter_Orbit_TimeToSOIChange(conn, &time_to_soi_change, orbit);
krpc_SpaceCenter_WarpTo(conn, ut + time_to_soi_change + 60, 100000, 2);
// Circularize at the periapsis
krpc_MechJeb_OperationCircularize_t circularize;
krpc_MechJeb_ManeuverPlanner_OperationCircularize(conn, &circularize,
planner);
krpc_MechJeb_OperationCircularize_TimeSelector(conn, &time_selector,
circularize);
krpc_MechJeb_TimeSelector_set_TimeReference(
conn, time_selector, KRPC_MECHJEB_TIMEREFERENCE_PERIAPSIS);
krpc_MechJeb_OperationCircularize_MakeNodes(conn, &nodes, circularize);
KRPC_FREE_LIST(nodes);
execute_nodes(conn, planner);
// Warp into Minmus' sphere of influence
sc.warpTo(
sc.getUT() + vessel.getOrbit().getTimeToSOIChange() + 60,
100000, 2);
// Circularize at the periapsis
OperationCircularize circularize =
planner.getOperationCircularize();
circularize.getTimeSelector().setTimeReference(
TimeReference.PERIAPSIS);
circularize.makeNodes();
executeNodes(planner);
-- Warp into Minmus' sphere of influence
sc.warp_to(sc.ut + vessel.orbit.time_to_soi_change + 60)
-- Circularize at the periapsis
local circularize = planner.operation_circularize
circularize.time_selector.time_reference = mj.TimeReference.periapsis
circularize:make_nodes()
execute_nodes()
// Warp into Minmus' sphere of influence
const orbit = await vessel.getOrbit();
const soiChange = (await sc.getUT()) + (await orbit.getTimeToSOIChange());
await sc.warpTo(soiChange + 60);
// Circularize at the periapsis
const circularize = await planner.getOperationCircularize();
await (await circularize.getTimeSelector()).setTimeReference(
mj.TimeReference.periapsis,
);
await circularize.makeNodes();
await executeNodes();
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)
)
// 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;
var legs = vessel.Parts.Legs [0].Part;
while (vessel.Control.CurrentStage > legs.DecoupleStage + 1)
vessel.Control.ActivateNextStage ();
// Limit the lander's thrust, so its lowest throttle leaves it
// falling
foreach (var engine in vessel.Parts.Engines)
engine.ThrustLimit = 0.3f;
// Land on Minmus' Great Flats, and wait for MechJeb to see the
// target
var landing = mj.LandingGuidance;
landing.SetTarget (minmus, 0, -6);
WaitFor (() => targetController.PositionTargetExists);
// The settings of the Landing Guidance window
landing.TouchdownSpeed = 1;
landing.DeployGears = true;
landing.Autowarp = true;
// Print each step of the autopilot
status = PrintSteps (() => landing.Status);
landing.LandAtTarget ();
// Wait for the autopilot to disengage, once the vessel has landed
WaitFor (() => !landing.Enabled);
status.Remove ();
sc.ClearTarget ();
var flight = vessel.Flight ();
Console.WriteLine (
"Landed at latitude {0:F2}, longitude {1:F2}",
flight.Latitude, flight.Longitude);
conn.Dispose ();
}
}
// 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().set_enabled(false);
auto 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 (auto engine : vessel.parts().engines()) engine.set_thrust_limit(0.3);
// Land on Minmus' Great Flats, and wait for MechJeb to see the target
auto landing = mj.landing_guidance();
landing.set_target(minmus, 0, -6);
wait_for(e.call(target_controller.position_target_exists_call()));
// The settings of the Landing Guidance window
landing.set_touchdown_speed(1);
landing.set_deploy_gears(true);
landing.set_autowarp(true);
// Print each step of the autopilot
status = landing.status_stream();
print_steps(status);
landing.land_at_target();
// Wait for the autopilot to disengage, once the vessel has landed
wait_for(e.not_(e.call(landing.enabled_call())));
status.remove();
sc.clear_target();
auto flight = vessel.flight();
std::printf("Landed at latitude %.2f, longitude %.2f\n",
flight.latitude(), flight.longitude());
}
// Stage until the next stage would drop the landing legs. This drops
// the stages below the lander, and activates the lander's engine.
krpc_MechJeb_Autostaging_set_Enabled(conn, staging, false);
krpc_SpaceCenter_Parts_t parts;
krpc_SpaceCenter_Vessel_Parts(conn, &parts, vessel);
krpc_list_object_t legs = KRPC_NULL_LIST;
krpc_SpaceCenter_Parts_Legs(conn, &legs, parts);
krpc_SpaceCenter_Part_t legs_part;
krpc_SpaceCenter_Leg_Part(conn, &legs_part, legs.items[0]);
KRPC_FREE_LIST(legs);
int32_t legs_stage, current_stage;
krpc_SpaceCenter_Part_DecoupleStage(conn, &legs_stage, legs_part);
krpc_SpaceCenter_Control_CurrentStage(conn, ¤t_stage, control);
while (current_stage > legs_stage + 1) {
krpc_SpaceCenter_Control_ActivateNextStage(conn, NULL, control);
krpc_SpaceCenter_Control_CurrentStage(conn, ¤t_stage, control);
}
// Limit the lander's thrust, so its lowest throttle leaves it falling
krpc_list_object_t engines = KRPC_NULL_LIST;
krpc_SpaceCenter_Parts_Engines(conn, &engines, parts);
for (size_t i = 0; i < engines.size; i++)
krpc_SpaceCenter_Engine_set_ThrustLimit(conn, engines.items[i], 0.3);
KRPC_FREE_LIST(engines);
// Land on Minmus' Great Flats, and wait for MechJeb to see the target
krpc_MechJeb_LandingGuidance_t landing;
krpc_MechJeb_LandingGuidance(conn, &landing);
krpc_MechJeb_LandingGuidance_SetTarget(conn, landing, minmus, 0, -6);
target_exists = false;
while (!target_exists) {
sleep_ms(100);
krpc_MechJeb_TargetController_PositionTargetExists(conn, &target_exists,
target_controller);
}
// The settings of the Landing Guidance window
krpc_MechJeb_LandingGuidance_set_TouchdownSpeed(conn, landing, 1);
krpc_MechJeb_LandingGuidance_set_DeployGears(conn, landing, true);
krpc_MechJeb_LandingGuidance_set_Autowarp(conn, landing, true);
krpc_MechJeb_LandingGuidance_LandAtTarget(conn, landing);
// Wait for the autopilot to disengage, once the vessel has landed, and
// print each of its steps
step[0] = '\0';
enabled = true;
while (enabled) {
char* status = NULL;
krpc_MechJeb_LandingGuidance_Status(conn, &status, landing);
print_step(status, step, sizeof(step));
krpc_free(status);
sleep_ms(100);
krpc_MechJeb_LandingGuidance_Enabled(conn, &enabled, landing);
}
krpc_SpaceCenter_ClearTarget(conn);
krpc_SpaceCenter_Flight_t flight;
krpc_SpaceCenter_Vessel_Flight(conn, &flight, vessel, KRPC_NULL);
double latitude, longitude;
krpc_SpaceCenter_Flight_Latitude(conn, &latitude, flight);
krpc_SpaceCenter_Flight_Longitude(conn, &longitude, flight);
printf("Landed at latitude %.2f, longitude %.2f\n", latitude, longitude);
krpc_disconnect(conn);
}
// Stage until the next stage would drop the landing legs. This
// drops the stages below the lander, and activates the lander's
// engine.
mj.getUtilities().getStaging().setEnabled(false);
Part legs = vessel.getParts().getLegs().get(0).getPart();
while (vessel.getControl().getCurrentStage()
> legs.getDecoupleStage() + 1) {
vessel.getControl().activateNextStage();
}
// Limit the lander's thrust, so its lowest throttle leaves it
// falling
for (Engine engine : vessel.getParts().getEngines()) {
engine.setThrustLimit(0.3f);
}
// Land on Minmus' Great Flats, and wait for MechJeb to see the
// target
LandingGuidance landing = mj.getLandingGuidance();
landing.setTarget(minmus, 0, -6);
waitFor(e.call(connection.getCall(
targetController, "getPositionTargetExists")));
// The settings of the Landing Guidance window
landing.setTouchdownSpeed(1);
landing.setDeployGears(true);
landing.setAutowarp(true);
// Print each step of the autopilot
status = connection.addStream(landing, "getStatus");
printSteps(status);
landing.landAtTarget();
// Wait for the autopilot to disengage, once the vessel has landed
waitFor(e.not(e.call(connection.getCall(landing, "getEnabled"))));
status.remove();
sc.clearTarget();
Flight flight = vessel.flight(null);
System.out.printf(
"Landed at latitude %.2f, longitude %.2f%n",
flight.getLatitude(), flight.getLongitude());
connection.close();
}
}
-- 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
local legs = vessel.parts.legs[1].part
while vessel.control.current_stage > legs.decouple_stage + 1 do
vessel.control:activate_next_stage()
end
-- Limit the lander's thrust, so its lowest throttle leaves it falling
for _, engine in ipairs(vessel.parts.engines) do
engine.thrust_limit = 0.3
end
-- Land on Minmus' Great Flats, and wait for MechJeb to see the target
local landing = mj.landing_guidance
landing:set_target(minmus, 0, -6)
wait_for(function() return mj.target_controller.position_target_exists end)
-- The settings of the Landing Guidance window
landing.touchdown_speed = 1
landing.deploy_gears = true
landing.autowarp = true
landing:land_at_target()
-- Wait for the autopilot to disengage, once the vessel has landed
wait_for_steps(landing)
sc.clear_target()
local flight = vessel:flight()
print(string.format('Landed at latitude %.2f, longitude %.2f',
flight.latitude, flight.longitude))
// Stage until the next stage would drop the landing legs. This drops
// the stages below the lander, and activates the lander's engine.
await staging.setEnabled(false);
const parts = await vessel.getParts();
const legs = await (await parts.getLegs())[0].getPart();
const legsStage = await legs.getDecoupleStage();
while ((await control.getCurrentStage()) > legsStage + 1) {
await control.activateNextStage();
}
// Limit the lander's thrust, so its lowest throttle leaves it falling
for (const engine of await parts.getEngines()) {
await engine.setThrustLimit(0.3);
}
// Land on Minmus' Great Flats, and wait for MechJeb to see the target
const landing = await mj.getLandingGuidance();
await landing.setTarget(minmus, 0, -6);
await waitFor(
({ targetController }) => targetController.positionTargetExists,
{ targetController },
);
// The settings of the Landing Guidance window
await landing.setTouchdownSpeed(1);
await landing.setDeployGears(true);
await landing.setAutowarp(true);
// Print each step of the autopilot
status = await printSteps(landing);
await landing.landAtTarget();
// Wait for the autopilot to disengage, once the vessel has landed
await waitFor(({ landing }) => !landing.enabled, { landing });
await status.remove();
await sc.clearTarget();
const flight = await vessel.flight();
const latitude = await flight.getLatitude();
const longitude = await flight.getLongitude();
console.log(
`Landed at latitude ${latitude.toFixed(2)}, ` +
`longitude ${longitude.toFixed(2)}`,
);
await conn.close();
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
// 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;
var legs = vessel.Parts.Legs [0].Part;
while (vessel.Control.CurrentStage > legs.DecoupleStage + 1)
vessel.Control.ActivateNextStage ();
// Limit the lander's thrust, so its lowest throttle leaves it
// falling
foreach (var engine in vessel.Parts.Engines)
engine.ThrustLimit = 0.3f;
// 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().set_enabled(false);
auto 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 (auto engine : vessel.parts().engines()) engine.set_thrust_limit(0.3);
// Stage until the next stage would drop the landing legs. This drops
// the stages below the lander, and activates the lander's engine.
krpc_MechJeb_Autostaging_set_Enabled(conn, staging, false);
krpc_SpaceCenter_Parts_t parts;
krpc_SpaceCenter_Vessel_Parts(conn, &parts, vessel);
krpc_list_object_t legs = KRPC_NULL_LIST;
krpc_SpaceCenter_Parts_Legs(conn, &legs, parts);
krpc_SpaceCenter_Part_t legs_part;
krpc_SpaceCenter_Leg_Part(conn, &legs_part, legs.items[0]);
KRPC_FREE_LIST(legs);
int32_t legs_stage, current_stage;
krpc_SpaceCenter_Part_DecoupleStage(conn, &legs_stage, legs_part);
krpc_SpaceCenter_Control_CurrentStage(conn, ¤t_stage, control);
while (current_stage > legs_stage + 1) {
krpc_SpaceCenter_Control_ActivateNextStage(conn, NULL, control);
krpc_SpaceCenter_Control_CurrentStage(conn, ¤t_stage, control);
}
// Limit the lander's thrust, so its lowest throttle leaves it falling
krpc_list_object_t engines = KRPC_NULL_LIST;
krpc_SpaceCenter_Parts_Engines(conn, &engines, parts);
for (size_t i = 0; i < engines.size; i++)
krpc_SpaceCenter_Engine_set_ThrustLimit(conn, engines.items[i], 0.3);
KRPC_FREE_LIST(engines);
// Stage until the next stage would drop the landing legs. This
// drops the stages below the lander, and activates the lander's
// engine.
mj.getUtilities().getStaging().setEnabled(false);
Part legs = vessel.getParts().getLegs().get(0).getPart();
while (vessel.getControl().getCurrentStage()
> legs.getDecoupleStage() + 1) {
vessel.getControl().activateNextStage();
}
// Limit the lander's thrust, so its lowest throttle leaves it
// falling
for (Engine engine : vessel.getParts().getEngines()) {
engine.setThrustLimit(0.3f);
}
-- 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
local legs = vessel.parts.legs[1].part
while vessel.control.current_stage > legs.decouple_stage + 1 do
vessel.control:activate_next_stage()
end
-- Limit the lander's thrust, so its lowest throttle leaves it falling
for _, engine in ipairs(vessel.parts.engines) do
engine.thrust_limit = 0.3
end
// Stage until the next stage would drop the landing legs. This drops
// the stages below the lander, and activates the lander's engine.
await staging.setEnabled(false);
const parts = await vessel.getParts();
const legs = await (await parts.getLegs())[0].getPart();
const legsStage = await legs.getDecoupleStage();
while ((await control.getCurrentStage()) > legsStage + 1) {
await control.activateNextStage();
}
// Limit the lander's thrust, so its lowest throttle leaves it falling
for (const engine of await parts.getEngines()) {
await engine.setThrustLimit(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.