├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── feature_request.md │ └── bug_report.md ├── pull_request_template.md └── workflows │ └── create_release.yml ├── images ├── demo_preview.png └── social_media_preview.png ├── .gitignore ├── src ├── hill_climb.ks ├── main.ks ├── maneuver.ks ├── lambert.ks ├── validate.ks ├── README.md ├── search.ks ├── refine.ks ├── transfer.ks └── orbit.ks ├── CHANGELOG.md ├── README.md └── LICENSE.md /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false -------------------------------------------------------------------------------- /images/demo_preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maneatingape/rsvp/HEAD/images/demo_preview.png -------------------------------------------------------------------------------- /images/social_media_preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maneatingape/rsvp/HEAD/images/social_media_preview.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Linux 2 | .directory 3 | *~ 4 | 5 | # macOS 6 | .DS_Store 7 | 8 | # Windows 9 | Thumbs.db 10 | [Dd]esktop.ini -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | --- 5 | 6 | ## Feature Request 7 | 8 | **Before creating a feature request please check that:** 9 | 10 | - [ ] [Issues list](https://github.com/maneatingape/rsvp/issues) does not already contain this feature. 11 | 12 | **Is your feature request related to a problem? Please describe.** 13 | 14 | _A clear and concise description of what the problem is._ 15 | 16 | **Describe the solution you'd like** 17 | 18 | _A clear and concise description of what you want to happen._ 19 | 20 | **Describe alternatives you've considered** 21 | 22 | _A clear and concise description of any alternative solutions or features you've considered._ 23 | 24 | **Additional context** 25 | 26 | _Add any other context or screenshots about the feature request here._ 27 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | --- 5 | 6 | ## Bug Report 7 | 8 | **Before creating a bug report please check that:** 9 | 10 | - [ ] [Issues list](https://github.com/maneatingape/rsvp/issues) does not already contain this bug report. 11 | 12 | **Describe the bug** 13 | 14 | A clear and concise description of what the bug is. 15 | 16 | **To Reproduce** 17 | 18 | Steps to reproduce the behavior: 19 | 1. Script sample 20 | 2. Vessel situation (e.g. orbital parameters, universal timestamp) 21 | 22 | **Expected behavior** 23 | 24 | A clear and concise description of what you expected to happen. 25 | 26 | **Screenshots and/or Savegame file** 27 | 28 | If helpful, add screenshots and/or attach a copy of the save game file. 29 | 30 | **Environment:** 31 | 32 | - Operating System (Windows/macOS/Linux) 33 | - KSP version 34 | - kOS version 35 | - RSVP version 36 | - Mods installed 37 | 38 | **Additional context** 39 | 40 | Add any other context about the problem here. 41 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | **Please check the PR fulfills these basic requirements** 2 | 3 | - [ ] PR has merged or rebased most recent commits from upstream repo 4 | - [ ] The commit messages are descriptive, helpful and informative 5 | - [ ] The code follows the code style of this project 6 | - [ ] README has been updated (for features) 7 | 8 | **What kind of change does this PR introduce?** 9 | 10 | - [ ] Bug fix (non-breaking change which fixes an issue) 11 | - [ ] New feature (non-breaking change which adds functionality) 12 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 13 | - [ ] Documentation update 14 | - [ ] Other 15 | 16 | **Motivation and Context** 17 | 18 | _(What problem does it solve?)_ 19 | 20 | **What is the current behavior?** 21 | 22 | _(You can link to an open issue here)_ 23 | 24 | **What is the new behavior (if this is a feature change) or expected behaviour (if this is a bug fix)?** 25 | 26 | _(Please describe the new/expected functionality)_ 27 | 28 | **How has this been tested?** 29 | 30 | _(Please describe how you tested your changes)_ 31 | 32 | **Does this PR introduce a breaking change?** 33 | 34 | _(What changes might users need to make in their scripts due to this PR?)_ 35 | 36 | **Other information** 37 | 38 | _(Anything else relevant e.g. screenshots, save game files)_ 39 | -------------------------------------------------------------------------------- /.github/workflows/create_release.yml: -------------------------------------------------------------------------------- 1 | # Trigger on release tag 2 | on: 3 | push: 4 | tags: 5 | - 'v*' 6 | 7 | name: Latest Release 8 | 9 | jobs: 10 | build: 11 | name: Create Release 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: Checkout Code 15 | uses: actions/checkout@v2 16 | 17 | - name: Create Asset 18 | env: 19 | RELEASE_VERSION: ${{ github.ref }} 20 | run: | 21 | mkdir rsvp 22 | cp -r src/*.ks rsvp 23 | cp LICENSE.md rsvp 24 | echo $RELEASE_VERSION > rsvp/VERSION.txt 25 | date -u >> rsvp/VERSION.txt 26 | zip -r rsvp.zip rsvp 27 | 28 | - name: Create Release 29 | id: create_release 30 | uses: actions/create-release@v1 31 | env: 32 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 33 | with: 34 | tag_name: ${{ github.ref }} 35 | release_name: Release ${{ github.ref }} 36 | draft: true 37 | prerelease: false 38 | 39 | - name: Upload Release Asset 40 | uses: actions/upload-release-asset@v1 41 | env: 42 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 43 | with: 44 | upload_url: ${{ steps.create_release.outputs.upload_url }} 45 | asset_path: ./rsvp.zip 46 | asset_name: rsvp.zip 47 | asset_content_type: application/zip -------------------------------------------------------------------------------- /src/hill_climb.ks: -------------------------------------------------------------------------------- 1 | @lazyglobal off. 2 | 3 | parameter export. 4 | export("line_search", line_search@). 5 | export("grid_search", grid_search@). 6 | 7 | // Convenience wrapper for searching a single dimension. 8 | local function line_search { 9 | parameter cost, x, step_size, step_threshold. 10 | 11 | local dimensions is list(v(1, 0, 0), v(-1, 0, 0)). 12 | local position is v(x, 0, 0). 13 | local minimum is cost(position). 14 | 15 | return coordinate_descent(dimensions, cost, position, minimum, step_size, step_threshold). 16 | } 17 | 18 | // Convenience wrapper for searching two dimensions. 19 | local function grid_search { 20 | parameter cost, x, y, scale_y, minimum, step_size, step_threshold. 21 | 22 | local dimensions is list(v(1, 0, 0), v(-1, 0, 0), v(0, scale_y, 0), v(0, -scale_y, 0)). 23 | local position is v(x, y, 0). 24 | 25 | return coordinate_descent(dimensions, cost, position, minimum, step_size, step_threshold). 26 | } 27 | 28 | // Coordinate descent is a variant of the hill climbing algorithm, where only 29 | // one dimension (x, y or z) is minimized at a time. This algorithm implements 30 | // this with a simple binary search approach. This converges reasonable quickly 31 | // wihout too many invocations of the "cost" function. 32 | // 33 | // The approach is: 34 | // (1) Choose an initial starting position 35 | // (2) Determine the lowest cost at a point "step_size" distance away, looking 36 | // in both positive and negative directions on the x, y and z axes. 37 | // (3) Continue in this direction until the cost increases 38 | // (4) Reduce the step size by half, terminating if below the threshold 39 | // then go to step (2) 40 | local function coordinate_descent { 41 | parameter dimensions, cost, position, minimum, step_size, step_threshold. 42 | 43 | local next_position is position. 44 | local direction is "none". 45 | 46 | local function test { 47 | parameter test_direction. 48 | 49 | local test_position is position + step_size * test_direction. 50 | local test_cost is cost(test_position). 51 | 52 | if test_cost < minimum { 53 | set minimum to test_cost. 54 | set next_position to test_position. 55 | set direction to test_direction. 56 | } 57 | // Stop if we are currently line searching. 58 | else if direction = test_direction { 59 | set direction to "none". 60 | } 61 | } 62 | 63 | until step_size < step_threshold { 64 | if direction = "none" { 65 | for test_direction in dimensions { 66 | test(test_direction). 67 | } 68 | } 69 | else { 70 | test(direction). 71 | } 72 | 73 | if direction = "none" { 74 | set step_size to step_size * 0.5. 75 | } 76 | else { 77 | set position to next_position. 78 | } 79 | } 80 | 81 | return lex("position", position, "minimum", minimum). 82 | } -------------------------------------------------------------------------------- /src/main.ks: -------------------------------------------------------------------------------- 1 | @lazyglobal off. 2 | 3 | // Local functions are added to this lexicon by the "export" method 4 | // in order to make them available to other scripts while preventing pollution 5 | // of the global namespace. 6 | global rsvp is lex(). 7 | 8 | // List of all source files. Omit extenstion so that users can use 9 | // compiled version if desired. 10 | local source_files is list( 11 | "hill_climb", 12 | "lambert", 13 | "main", 14 | "maneuver", 15 | "orbit", 16 | "refine", 17 | "search", 18 | "transfer", 19 | "validate" 20 | ). 21 | 22 | export("goto", goto@). 23 | export("compile_to", compile_to@). 24 | import(). 25 | 26 | local function goto { 27 | parameter destination, options is lex(). 28 | 29 | // Thoroughly check supplied parameters, options and game state for 30 | // correctness. If any problems are found, print validation details 31 | // to the console then exit early. 32 | local maybe is rsvp:validate_parameters(destination, options). 33 | 34 | if not maybe:success { 35 | print maybe. 36 | return maybe. 37 | } 38 | 39 | // Find the lowest deltav cost transfer using the specified settings. 40 | local settings is maybe:settings. 41 | local tuple is rsvp:find_launch_window(destination, settings). 42 | local craft_transfer is tuple:transfer. 43 | local result is tuple:result. 44 | 45 | // If no node creation has been requested return predicted transfer details, 46 | // otherwise choose betwen the 4 combinations of possible transfer types. 47 | if settings:create_maneuver_nodes <> "none" { 48 | // Both "origin_type" and "destination_type" are either the string 49 | // "vessel" or "body", so can be used to construct the function 50 | // names for transfer, for example "vessel_to_vessel" or "body_to_body". 51 | local key is settings:origin_type + "_to_" + settings:destination_type. 52 | set result to rsvp[key](destination, settings, craft_transfer, result). 53 | 54 | if not result:success { 55 | // Print details to the console 56 | if settings:verbose { 57 | print result. 58 | } 59 | 60 | // In the case of failure delete any manuever nodes created. 61 | if settings:cleanup_maneuver_nodes { 62 | for maneuver in allnodes { 63 | remove maneuver. 64 | } 65 | } 66 | } 67 | } 68 | 69 | return result. 70 | } 71 | 72 | // Add delegate to the global "rsvp" lexicon. 73 | local function export { 74 | parameter key, value. 75 | 76 | rsvp:add(key, value). 77 | } 78 | 79 | // Add functions from all other scripts into lexicon. User can use compiled 80 | // versions of the source, trading off less storage space vs harder to debug 81 | // error messages. 82 | local function import { 83 | local source_root is scriptpath():parent. 84 | 85 | for filename in source_files { 86 | local source_path is source_root:combine(filename). 87 | 88 | runoncepath(source_path, export@). 89 | } 90 | } 91 | 92 | // Compiles source files and copies them to a new location. This is useful to 93 | // save space on processor hard disks that have limited capacity. 94 | // The trade-off is that error messages are less descriptive. 95 | local function compile_to { 96 | parameter destination. 97 | 98 | local source_root is scriptpath():parent. 99 | local destination_root is path(destination). 100 | 101 | // Check that path exists and is a directory. 102 | if not exists(destination_root) { 103 | print destination_root + " does not exist". 104 | return. 105 | } 106 | if open(destination_root):isfile { 107 | print destination_root + " is a file. Should be a directory". 108 | return. 109 | } 110 | 111 | for filename in source_files { 112 | local source_path is source_root:combine(filename + ".ks"). 113 | local destination_path is destination_root:combine(filename + ".ksm"). 114 | 115 | print "Compiling " + source_path. 116 | compile source_path to destination_path. 117 | } 118 | 119 | print "Succesfully compiled " + source_files:length + " files to " + destination_root. 120 | } -------------------------------------------------------------------------------- /src/maneuver.ks: -------------------------------------------------------------------------------- 1 | @lazyglobal off. 2 | 3 | parameter export. 4 | export("create_maneuver", create_maneuver@). 5 | export("create_raw_maneuver", create_raw_maneuver@). 6 | 7 | // Convenience wrapper around a maneuver node that provides methods to predict 8 | // details of future encounters. 9 | local function create_maneuver { 10 | parameter from_vessel, epoch_time, deltav. 11 | 12 | local osv is rsvp:orbital_state_vectors(ship, epoch_time). 13 | local projection is maneuver_node_vector_projection(osv, deltav). 14 | 15 | return create_raw_maneuver(from_vessel, epoch_time, projection). 16 | } 17 | 18 | // Create a "raw" node using exactly the deltav without modifying it. 19 | local function create_raw_maneuver { 20 | parameter from_vessel, epoch_time, deltav. 21 | 22 | local maneuver is node(epoch_time, deltav:x, deltav:y, deltav:z). 23 | add maneuver. 24 | 25 | return lex( 26 | "time", node_time@:bind(maneuver), 27 | "deltav", node_deltav@:bind(maneuver), 28 | "delete", node_delete@:bind(maneuver), 29 | "patch_details", patch_details@:bind(maneuver, from_vessel), 30 | "validate_patches", validate_patches@:bind(maneuver) 31 | ). 32 | } 33 | 34 | // Returns the vector projection of a velocity vector onto the given orbital 35 | // state vector. This comes in useful as most vectors use KSP's raw coordinate 36 | // system, however maneuver node's prograde, radial and normal components are 37 | // relative to the vessel's velocity and position *at the time of the node*. 38 | local function maneuver_node_vector_projection { 39 | parameter osv, craft_velocity. 40 | 41 | // Unit vectors in vessel prograde and normal directions. 42 | local unit_prograde is osv:velocity:normalized. 43 | local unit_normal is vcrs(osv:velocity, osv:position):normalized. 44 | // KSP quirk: Manuever node "radial" is not the usual meaning of radial 45 | // in the sense of a vector from the center of the parent body towards 46 | // the ship, but rather a vector orthogonal to prograde and normal vectors. 47 | local unit_radial is vcrs(unit_normal, unit_prograde). 48 | 49 | // Components of velocity parallel to respective unit vectors. 50 | local component_radial is vdot(unit_radial, craft_velocity). 51 | local component_normal is vdot(unit_normal, craft_velocity). 52 | local component_prograde is vdot(unit_prograde, craft_velocity). 53 | 54 | return v(component_radial, component_normal, component_prograde). 55 | } 56 | 57 | local function node_time { 58 | parameter maneuver. 59 | 60 | return time():seconds + maneuver:eta. 61 | } 62 | 63 | local function node_deltav { 64 | parameter maneuver. 65 | 66 | return maneuver:deltav:mag. 67 | } 68 | 69 | local function node_delete { 70 | parameter maneuver. 71 | 72 | remove maneuver. 73 | } 74 | 75 | // Finds the first orbital patch that matches destination body, then returns 76 | // the predicted time, velocity and periapsis details of the ship at the exact 77 | // moment when it will enter the destination's SOI. 78 | local function patch_details { 79 | parameter maneuver, from_vessel, destination. 80 | 81 | local predicted_orbit is maneuver:orbit. 82 | 83 | until not predicted_orbit:hasnextpatch { 84 | local soi_time is time():seconds + predicted_orbit:nextpatcheta. 85 | set predicted_orbit to predicted_orbit:nextpatch. 86 | 87 | if predicted_orbit:body = destination { 88 | local soi_velocity is velocityat(ship, soi_time):orbit. 89 | local periapsis_altitude is predicted_orbit:periapsis. 90 | local periapsis_time is rsvp:time_at_periapsis(predicted_orbit). 91 | 92 | // When the destination is a moon (rather than a planet) then 93 | // "velocityat" returns value relative to the parent planet *not* 94 | // the moon, even though ship is within moon's SOI at "patch_time". 95 | if from_vessel and destination:hasbody and destination:body:hasbody { 96 | local adjustment is velocityat(destination, soi_time):orbit. 97 | set soi_velocity to soi_velocity - adjustment. 98 | } 99 | 100 | return lex( 101 | "soi_time", soi_time, 102 | "soi_velocity", soi_velocity, 103 | "periapsis_altitude", periapsis_altitude, 104 | "periapsis_time", periapsis_time 105 | ). 106 | } 107 | } 108 | 109 | return "none". 110 | } 111 | 112 | // Validate that the actual projected orbit patches match expectation. 113 | // This checks for any unexpected encounters along the way, 114 | // for example Kerbin's Mun or Duna's Ike getting in the way. 115 | local function validate_patches { 116 | parameter maneuver, expected, arrival_time. 117 | 118 | local predicted_orbit is maneuver:orbit. 119 | local actual is list(). 120 | 121 | actual:add(predicted_orbit:body). 122 | 123 | until not predicted_orbit:hasnextpatch or arrival_time < time():seconds + predicted_orbit:nextpatcheta { 124 | set predicted_orbit to predicted_orbit:nextpatch. 125 | actual:add(predicted_orbit:body). 126 | } 127 | 128 | if list_equals(expected, actual) { 129 | return lex("success", true). 130 | } 131 | else { 132 | local message is "Unexpected encounter " + to_string(actual) + ", expected " + to_string(expected). 133 | return lex("success", false, "problems", lex(401, message)). 134 | } 135 | } 136 | 137 | // Compare two lists for equality 138 | local function list_equals { 139 | parameter first, second. 140 | 141 | if first:length <> second:length { 142 | return false. 143 | } 144 | 145 | for i in range(0, first:length) { 146 | if first[i] <> second[i] { 147 | return false. 148 | } 149 | } 150 | 151 | return true. 152 | } 153 | 154 | local function to_string { 155 | parameter items. 156 | 157 | local names is list(). 158 | 159 | for item in items { 160 | names:add(item:name). 161 | } 162 | 163 | return "'" + names:join(" => ") + "'". 164 | } -------------------------------------------------------------------------------- /src/lambert.ks: -------------------------------------------------------------------------------- 1 | @lazyglobal off. 2 | 3 | parameter export. 4 | export("lambert", lambert@). 5 | 6 | // This code is a Kerboscript port of the PyKep project Lambert's problem solver, 7 | // developed by the European Space Agency, available at 8 | // https://github.com/esa/pykep 9 | // 10 | // The algorithm and equations are described in excellent detail in the paper 11 | // "Revisiting Lambert’s problem" by Dario Izzio, available at 12 | // https://www.esa.int/gsp/ACT/doc/MAD/pub/ACT-RPR-MAD-2014-RevisitingLambertProblem.pdf 13 | // 14 | // As a derivative work it is licensed under the GNU GPL 3.0, a copy of which 15 | // is included in the root of this repository. 16 | // 17 | // The same variable names and structure used in the algorithm described in the 18 | // paper and original C++ code are reused as much as possible. 19 | // 20 | // Major simplifying differences: 21 | // * Multi-revolution transfer orbits are not considered 22 | // * Time of flight is always calculated using Lancaster's formula 23 | // 24 | // Minor syntactical changes: 25 | // * As kOS is case-insensitive and also to increase clarity, the magnitude of 26 | // the r1 and r2 vectors are denoted m1 and m2, rather than R1 and R2. 27 | // * The original code reuses the name "tof", both for the user specified time 28 | // of flight and also for the iterative error when finding the value of "x". 29 | // To reduce confusion the second use case is denoted "tau" in this code. 30 | // * kOS supports the exponential operator ^ so this is used instead of repeated 31 | // multiplication and division of intermediate variables. 32 | // This operator has the highest precedence, however in some complex equations 33 | // it is surrounded by parentheses in order to aid clarity. 34 | // * Kerboscript syntax supports vector multiplication and addition, considerably 35 | // simplifying the syntax when calculating v1 and v2. 36 | // * The time of flight function uses some already calculated variables from the 37 | // householder function. Variable names and the signs of some formulas are 38 | // changed to match. 39 | // 40 | // Parameters: 41 | // r1 [Vector] Position of the origin planet at departure time 42 | // r2 [Vector] Position of the destination planet at arrival time 43 | // tof [Scalar] Time of flight (arrival time minus departure time) 44 | // mu [Scalar] Standard gravitational parameter 45 | // flip_direction [Boolean] Change transfer direction between prograde/retrograde 46 | local function lambert { 47 | parameter r1, r2, tof, mu, flip_direction. 48 | 49 | // Calculate "lambda" and normalized time of flight "t" 50 | local m1 is r1:mag. 51 | local m2 is r2:mag. 52 | local c is (r1 - r2):mag. 53 | local s is (m1 + m2 + c) / 2. 54 | local lambda is sqrt(1 - c / s). 55 | local t is tof * sqrt(2 * mu / s ^ 3). 56 | 57 | // Create unit vectors 58 | local ir1 is r1:normalized. 59 | local ir2 is r2:normalized. 60 | local ih is vcrs(ir1, ir2):normalized. 61 | local it1 is vcrs(ih, ir1):normalized. 62 | local it2 is vcrs(ih, ir2):normalized. 63 | 64 | // Change transfer direction between prograde/retrograde either if requested 65 | // XOR if transfer angle is greater than 180 degrees. 66 | if (ih:y < 0) <> flip_direction { 67 | set it1 to -it1. 68 | set it2 to -it2. 69 | set lambda to -lambda. 70 | } 71 | 72 | // The clever part of this algorithm is reducing the problem down to a 73 | // function of a single variable "x" (the Lancaster-Blanchard variable). 74 | // This function is well behaved over almost all possible values of x 75 | // and also has well behaved 1st, 2nd and 3rd order derivatives. 76 | // This allows us to solve for x using a iterative numerical method then 77 | // use that value to determine the desired velocities of the transfer orbit 78 | // at points r1 and r2. 79 | local x is iterative_root_finder(lambda, t). 80 | 81 | // Construct velocity vectors from "x" 82 | local y is sqrt(1 - lambda ^ 2 * (1 - x ^ 2)). 83 | local z is lambda * y. 84 | local rho is (m1 - m2) / c. 85 | local gamma is sqrt(mu * s / 2). 86 | 87 | local vr1 is (z - x) - rho * (x + z). 88 | local vr2 is (x - z) - rho * (x + z). 89 | local vt is sqrt(1 - rho ^ 2) * (y + lambda * x). 90 | 91 | local v1 is (gamma / m1) * (vr1 * ir1 + vt * it1). 92 | local v2 is (gamma / m2) * (vr2 * ir2 + vt * it2). 93 | 94 | return lex("v1", v1, "v2", v2). 95 | } 96 | 97 | // Helper function to run iterative root finding algorithms. 98 | local function iterative_root_finder { 99 | parameter lambda, t. 100 | 101 | local x is initial_guess(lambda, t). 102 | local delta is 1. 103 | local iterations is 0. 104 | 105 | until abs(delta) < 0.00001 or iterations = 15 { 106 | set delta to householders_method(lambda, t, x). 107 | set x to x - delta. 108 | set iterations to iterations + 1. 109 | } 110 | 111 | return x. 112 | } 113 | 114 | // The formulas for the initial guess of "x" are so accurate that on average 115 | // only 2 to 3 iterations of Householder's method are needed to converge. 116 | local function initial_guess { 117 | parameter lambda, t. 118 | 119 | local t0 is constant:degtorad * arccos(lambda) + lambda * sqrt(1 - lambda ^ 2). 120 | local t1 is (2 / 3) * (1 - lambda ^ 3). 121 | 122 | if t >= t0 { 123 | return (t0 / t) ^ (2 / 3) - 1. 124 | } else if t <= t1 { 125 | return (5 * t1 * (t1 - t)) / (2 * t * (1 - lambda ^ 5)) + 1. 126 | } else { 127 | return (t0 / t) ^ (ln(t1 / t0) / ln(2)) - 1. 128 | } 129 | } 130 | 131 | // 3rd order Householder's method. For some context the method of order 1 is the 132 | // well known Newton's method and the method of order 2 is Halley's method. 133 | local function householders_method { 134 | parameter lambda, t, x. 135 | 136 | local a is 1 - x ^ 2. 137 | local y is sqrt(1 - lambda ^ 2 * a). 138 | local tau is time_of_flight(lambda, a, x, y). 139 | local delta is tau - t. 140 | 141 | local dt is (3 * tau * x - 2 + 2 * (lambda ^ 3) * x / y) / a. 142 | local ddt is (3 * tau + 5 * x * dt + 2 * (1 - lambda ^ 2) * (lambda ^ 3) / (y ^ 3)) / a. 143 | local dddt is (7 * x * ddt + 8 * dt - 6 * (1 - lambda ^ 2) * (lambda ^ 5) * x / (y ^ 5)) / a. 144 | 145 | return delta * (dt ^ 2 - delta * ddt / 2) / (dt * (dt ^ 2 - delta * ddt) + (dddt * delta ^ 2) / 6). 146 | } 147 | 148 | // Calculate the time of flight using Lancaster's formula. 149 | local function time_of_flight { 150 | parameter lambda, a, x, y. 151 | 152 | local b is sqrt(abs(a)). 153 | local f is b * (y - lambda * x). 154 | local g is lambda * a + x * y. 155 | 156 | // For the hyperbolic case when "a" is less than zero, large values of "x" 157 | // can cause slight numeric inaccuracies in the values of "f" and "g" to 158 | // accumulate and result in a negative sum. The "max" function acts as a 159 | // guard in this case to prevent errors when taking the log of this value. 160 | local psi is choose constant:degtorad * arccos(g) if a > 0 else ln(max(1e-300, f + g)). 161 | 162 | return (psi / b - x + lambda * y) / a. 163 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## v9 4 | 5 | ### Bug Fixes 6 | * Support kOS 1.4.0.0 by renaming local variables to avoid conflict with built-in names. 7 | 8 | ### New Features 9 | * The restriction on running the script when the craft is not in a stable orbit has been relaxed, so that finding future transfer times can happen when on the ground. Maneuver nodes can still only be created when the craft is in a stable orbit. 10 | 11 | ## v8 12 | 13 | ### Bug Fixes 14 | * Add a safety check that the predicted insertion velocity at the boundary of the destination's SOI is above the minimum possible (based on the desired final periapsis). This is similar to the existing check that the ejection velocity from the origin is greater than the minimum possible. This prevents an error occuring during transfer refinement in some scenarios when the initial raw point-to-point Lambert solution predicts an intercept velocity less than this minimum. 15 | 16 | ## v7 17 | 18 | ### New Features 19 | This release increases the speed of the hill climbing algorithm when searching the pork chop plot in certain scenarios. The larger the relative difference between the origin and destination orbits, the more benefit this provides. The eventual transfer found and delta-v needed is the same as before but takes less time to find. 20 | 21 | For example a transfer search from Kerbin to Duna takes the same time. A transfer search from Moho to Eeloo takes 15% of the previous time. 22 | 23 | ### Technical Improvements 24 | * When verbose mode is enabled, print details if a problem occurs during a transfer search. 25 | * Add CPU speed boost to quickstart code snippet 26 | 27 | ## v6 28 | 29 | ### New Features 30 | 31 | This release adds a new mathematical approach to refining transfers when the ratio of the destination SOI to Periapsis exceeds a threshold. This fixes 2 issues: 32 | * Transfers to larger moons (especially in the Jool system) are much less likely to go astray. 33 | * Polar orbit orientation when travelling to Mun or Ike no longer results in huge delta-v values. 34 | 35 | The new approach is based on the paper [A new method of patched-conic for interplanetary orbit](https://doi.org/10.1016/j.ijleo.2017.10.153) by Jin Li, Jianhui Zhao and Fan Li. 36 | 37 | Given a velocity vector at SOI boundary, periapsis altitude and inclination, this approach calculates the position vector that satisifies these contraints. This position vector is combined in a feedback loop with the Lambert solver to refine the initial estimate from one that only considers planets as points to one that takes the SOI spheres into account. This removes the need both for the `impact_parameter` function and the line search algorithm simplifying the vessel-to-body case. The body-to-body case also simplifies into a single step instead of two. 38 | 39 | For vessels and planets with a SOI to Periapsis ratio of less than 1% the existing strategy is used. This strategy considers the planets as a zero-width point on the assumption that over large distance only small adjustments will be need to the predicted transfer. 40 | 41 | However some bodies in KSP have extremely large SOI to Periapsis ratios, for example Ike (38%), Mun (23%) and Tylo (17%). For transfers to and from these bodies, the SOI sphere needs to be taken into account when finding the lowest cost transfer. The `offset_from_soi_edge` and `duration_from_soi_edge` function in `orbit.ks` predict the time and position where a craft will exit/enter SOI. 42 | 43 | Interestingly another challenge with very large SOI to Periapsis ratios is that the minimum escape velocity can be higher than the desired transfer. For example a direct Hohmann transfer from Laythe to Vall is impossible, as the minmum escape velocity from Laythe is *higher* than the velocity required. The search algorithm now supports a minimum value for deltav, making this type of transfer possible. 44 | 45 | ### Bug Fixes 46 | * Fix calculation of periapis time when insertion orbit is mathematically elliptical. Insertion manuever node will now be placed in the correct location. 47 | * Fix bug in a guard clause in the Lambert solver that was throwing `NaN` exception is certain situations. 48 | 49 | ### Technical Improvements 50 | * Add validation check to `final_orbit_periapsis` option to ensure that supplied value is within SOI radius of destination. 51 | * Refactor maneuver related code from `orbit.ks` to `maneuver.ks`. 52 | 53 | ## v5 54 | 55 | ### Bug Fixes 56 | * Fix issue [`Tried to push NAN into the stack when attempting an intercept from a nearly-approaching orbit`](https://github.com/maneatingape/rsvp/issues/6). This was preventing a craft that had just missed an intercept from correcting its orbit. The root cause was slight numeric inaccuracies in the Lambert solver for certain time of flight calculations resulting in an attempt to take the log of a negative number. Added a guard to protect against this edge case. 57 | 58 | ### Technical Improvements 59 | * Add `build_documentation` [Github Action](https://github.com/features/actions) that creates documentation in the same format as kOS. On any change to the `doc` folder, this action will automatically run the [Sphinx generator](https://www.sphinx-doc.org/en/master/) to convert raw `.rst` text files to HTML, then publish the changes to Github Pages. This keeps a clean separation in the repository between the raw source files and the generated output. 60 | 61 | ## v4 62 | 63 | Support `.ksm` compiled files. 64 | 65 | ### New Features 66 | * Implement issue [`Running other files should not include extension`](https://github.com/maneatingape/rsvp/issues/5). Add ability to use more compact compiled version of the source on craft that have limited volume space. Compiled files take about 20% of the space of the raw source, resulting in a significant space savings. 67 | * Add `compile_to` convenience function that compiles the source to a user-specified destination, for example a kOS processor hard drive. 68 | 69 | ## v3 70 | 71 | Improve handling of objects on hyperbolic orbits. 72 | 73 | ### Technical Improvements 74 | * Use different strategy when calculating default `search_duration`, `max_time_of_flight` and `search_interval` values for a destination with a hyperbolic orbit, for example an asteroid or comet. This change prevents a `Tried to push Infinity onto the stack` error that occurred because the approach used for planets assumes an elliptical orbit with a finite orbital period. 75 | 76 | ## v2 77 | 78 | First bugfix, first new feature and first technical improvement. 79 | 80 | ### New Features 81 | * Add `cleanup_maneuver_nodes` option. Enabled by default, this will delete any maneuver nodes created if any problem occurs when creating the transfer, in order to leave a clean slate for the next attempt. 82 | 83 | ### Bug Fixes 84 | * Fix issue [`search.ks fails when time:seconds > 2^31`](https://github.com/maneatingape/rsvp/issues/4). The kOS `range` expression expects values to fit within a signed 32 bit integer. This caused the script to break when run on save games with a universal time greater than 2³¹ seconds or about 233 years. Replaced the `range` expression with a `from` loop as a straightforward workaround. 85 | 86 | ### Technical Improvements 87 | * Calculate the time at destination periapsis (used when creating the arrival node) directly from Keplerian orbital parameters of the intercept patch. This is more efficient and accurate than the previous approach, which used a line search to find the closest approach distance by trying different times. 88 | 89 | ## v1 90 | 91 | Initial public release. -------------------------------------------------------------------------------- /src/validate.ks: -------------------------------------------------------------------------------- 1 | @lazyglobal off. 2 | 3 | parameter export. 4 | export("validate_parameters", validate_parameters@). 5 | 6 | // Default value and validation function for each possible option key. 7 | local delegates is lex( 8 | "verbose", list(false, validate_boolean(1)), 9 | "create_maneuver_nodes", list("none", validate_list(2, list("none", "first", "both"))), 10 | "earliest_departure", list("default", validate_scalar(3)), 11 | "search_duration", list("default", validate_scalar(4)), 12 | "search_interval", list("default", validate_scalar(5)), 13 | "max_time_of_flight", list("default", validate_scalar(6)), 14 | "final_orbit_periapsis", list(100000, validate_scalar(7)), 15 | "final_orbit_type", list("circular", validate_list(8, list("circular", "elliptical", "none"))), 16 | "final_orbit_orientation", list("prograde", validate_list(9, list("prograde", "polar", "retrograde"))), 17 | "cleanup_maneuver_nodes", list(true, validate_boolean(10)) 18 | ). 19 | 20 | // Collect valid options into "settings" and error messages into "problems". 21 | local function validate_parameters { 22 | parameter destination, options. 23 | 24 | local settings is lex(). 25 | local problems is lex(). 26 | 27 | function setting { 28 | parameter key, value. 29 | settings:add(key, value). 30 | } 31 | 32 | function problem { 33 | parameter key, value. 34 | problems:add(key, value). 35 | } 36 | 37 | validate_prerequisites(problem@). 38 | validate_orbital_constraints(destination, setting@, problem@). 39 | validate_options(destination, options, setting@, problem@). 40 | 41 | if problems:length = 0 { 42 | return lex("success", true, "settings", settings). 43 | } 44 | else { 45 | return lex("success", false, "problems", problems). 46 | } 47 | } 48 | 49 | // Basic sanity checks. 50 | local function validate_prerequisites { 51 | parameter problem. 52 | 53 | if ship <> kuniverse:activevessel { 54 | problem(101, "Ship '" + ship:name + "'' is not active vessel"). 55 | } 56 | else if hasnode { 57 | problem(102, "Existing maneuver node already exists"). 58 | } 59 | 60 | if not career():canmakenodes { 61 | problem(104, "Career mode has not unlocked maneuver nodes"). 62 | } 63 | if career():patchlimit = 0 { 64 | problem(105, "Career mode has not unlocked patched conics"). 65 | } 66 | } 67 | 68 | // Sanity check destination type and relation to vessel. 69 | local function validate_orbital_constraints { 70 | parameter destination, setting, problem. 71 | 72 | if destination:istype("vessel") { 73 | setting("destination_type", "vessel"). 74 | } 75 | else if destination:istype("body") { 76 | setting("destination_type", "body"). 77 | } 78 | else { 79 | problem(201, "Parameter 'destination' is not expected type Orbitable (Vessels and Bodies)"). 80 | return. 81 | } 82 | 83 | if not destination:hasbody { 84 | problem(202, "Destination '" + destination:name + "' is not orbiting a parent body"). 85 | return. 86 | } 87 | 88 | if destination = ship { 89 | problem(203, "Origin and destination must be different"). 90 | } 91 | if destination = ship:body { 92 | problem(204, "Ship '" + ship:name + "' is already in orbit around destination"). 93 | } 94 | 95 | if ship:body = destination:body { 96 | setting("origin_type", "vessel"). 97 | } 98 | else if ship:body:hasbody and ship:body:body = destination:body { 99 | setting("origin_type", "body"). 100 | } 101 | else { 102 | problem(205, "Destination '" + destination:name + "' is not orbiting a direct common parent or grandparent of ship '" + ship:name + "'"). 103 | } 104 | } 105 | 106 | local function validate_options { 107 | parameter destination, options, setting, problem. 108 | 109 | if not options:istype("lexicon") { 110 | problem(301, "Parameter 'options' is not expected type Lexicon"). 111 | return. 112 | } 113 | 114 | // Check for keys that aren't valid when destination is a vessel. 115 | if destination:istype("vessel") { 116 | local not_applicable is list("periapsis", "type", "orientation"). 117 | local found is list(). 118 | 119 | for suffix in not_applicable { 120 | local key is "final_orbit_" + suffix. 121 | if options:haskey(key) { 122 | found:add(key). 123 | } 124 | } 125 | 126 | if found:length > 0 { 127 | problem(302, "Option " + to_string(found) + " not applicable to Vessel"). 128 | } 129 | } 130 | 131 | // Check that final orbit periapsis is within destination SOI 132 | if destination:istype("body") { 133 | local key is "final_orbit_periapsis". 134 | local limit is floor(destination:soiradius - destination:radius). 135 | 136 | if options:haskey(key) and options[key] >= limit { 137 | problem(304, "Option '" + key + "'' must be less than " + limit). 138 | } 139 | } 140 | 141 | // Manuever nodes can only be created when the ship is in a stable orbit 142 | if ship:status <> "orbiting" { 143 | local key is "create_maneuver_nodes". 144 | 145 | if options:haskey(key) and options[key] <> "none" { 146 | problem(305, "Cannot create manuever nodes when ship '" + ship:name + "' is not in stable orbit"). 147 | } 148 | } 149 | 150 | // Check for unknown keys that indicate a typo. 151 | local found is list(). 152 | 153 | for key in options:keys { 154 | if not delegates:haskey(key) { 155 | found:add(key). 156 | } 157 | } 158 | 159 | if found:length > 0 { 160 | problem(303, "Option " + to_string(found) + " not recognised"). 161 | } 162 | 163 | // For each setting use either provided option or sensible default. 164 | for key in delegates:keys { 165 | local default_value is delegates[key][0]. 166 | local validate_option is delegates[key][1]. 167 | 168 | if options:haskey(key) { 169 | validate_option(key, options[key], setting, problem). 170 | } 171 | else { 172 | setting(key, default_value). 173 | } 174 | } 175 | } 176 | 177 | local function validate_boolean { 178 | parameter code. 179 | 180 | return { 181 | parameter key, value, setting, problem. 182 | 183 | if value:istype("boolean") { 184 | setting(key, value). 185 | } 186 | else { 187 | problem(code, "Option '" + key + "' is '" + value + "', expected boolean"). 188 | } 189 | }. 190 | } 191 | 192 | local function validate_scalar { 193 | parameter code. 194 | 195 | return { 196 | parameter key, value, setting, problem. 197 | 198 | if value:istype("scalar") and value > 0 { 199 | setting(key, value). 200 | } 201 | else { 202 | problem(code, "Option '" + key + "' is '" + value + "', expected positive number"). 203 | } 204 | }. 205 | } 206 | 207 | local function validate_list { 208 | parameter code, items. 209 | 210 | return { 211 | parameter key, value, setting, problem. 212 | 213 | if items:contains(value) { 214 | setting(key, value). 215 | } 216 | else { 217 | problem(code, "Option '" + key + "' is '" + value + "', expected one of " + to_string(items)). 218 | } 219 | }. 220 | } 221 | 222 | local function to_string { 223 | parameter items. 224 | 225 | return "'" + items:join("', '") + "'". 226 | } -------------------------------------------------------------------------------- /src/README.md: -------------------------------------------------------------------------------- 1 | # Technical Details 2 | 3 | ## Lambert Solver [(lambert.ks)](lambert.ks) 4 | 5 | The core functionality is built around a [Lambert's problem](https://en.wikipedia.org/wiki/Lambert%27s_problem) solver. Given the position of two planets and a duration, this calculates the delta-v required for a transfer orbit between the two positions that will take exactly that duration. 6 | 7 | The Lambert solver code is a kOS port of the [PyKep project](https://github.com/esa/pykep) developed by the European Space Agency. The algorithm and equations are described in excellent detail in the paper [Revisiting Lambert’s problem](https://www.esa.int/gsp/ACT/doc/MAD/pub/ACT-RPR-MAD-2014-RevisitingLambertProblem.pdf) by Dario Izzio. 8 | 9 | The original code is very robust and flexible. For the KSP universe some simplifications have been made, in particular multi-revolution transfer orbits are not considered. Interestingly, the Kerboscript code is more concise than the C++ original, thanks to first class support for vector math and the exponent operator, coming in at around 100 lines not including comments. 10 | 11 | ## Porkchop Plot Search [(search.ks)](search.ks) 12 | 13 | Graphing the delta-v values returned by the Lambert solver, with departure time along the x-axis and arrival time (or time of flight) along the y-axis, yields the famous [porkchop plot.](https://en.wikipedia.org/wiki/Porkchop_plot) This shows the lowest delta-v transfer times between two planets. 14 | 15 | However the brute force approach of generating every point of this graph would take far too long on kOS. Instead an [iterated local search](https://en.wikipedia.org/wiki/Iterated_local_search) gives a decent probability of finding the global minimum in a shorter time. 16 | 17 | Simple heuristics based on the origin and destination orbits provide sensible defaults for the search parameters. These parameters can be overriden by the user for fine-grained control. 18 | 19 | ## Coordinate Descent [(hill_climb.ks)](hill_climb.ks) 20 | 21 | The [coordinate descent](https://en.wikipedia.org/wiki/Coordinate_descent) implementation used by RSVP is a variant of the classic [hill climbing](https://en.wikipedia.org/wiki/Hill_climbing) algorithm. Given a starting point, it always attempts to go "downhill" to a region of lower value, stopping once it cannot go any further. The algorithm is completely general purpose and flexible, taking an arbitrary "cost" function, for example delta-v magnitude or distance to periapsis. The implementation can search up to three dimensions, however currently only the one and two dimensional variants are used. 22 | 23 | ## Orbital Utilities [(orbit.ks)](orbit.ks) 24 | 25 | Toolkit of functions related to orbital mechanics that: 26 | * Use the [vis-viva equation](https://en.wikipedia.org/wiki/Vis-viva_equation) to calculate the delta-v between elliptical orbits and hyperbolic transfers, in order to determine the ejection and insertion delta-v values. 27 | * Calculate projected [orbital state vectors](https://en.wikipedia.org/wiki/Orbital_state_vectors) for planets and vessels at any time. 28 | * Determine the amount that planets bend hyperbolic trajectories to determine both the correct ejection angle and the [impact parameter](https://en.wikipedia.org/wiki/Hyperbolic_trajectory#Impact_parameter) for insertions. 29 | * Provide default value for the time of flight based on the [Hohmann transfer](https://en.wikipedia.org/wiki/Hohmann_transfer_orbit) period. 30 | * Provide default value for search duration based on [Synodic period](https://en.wikipedia.org/wiki/Orbital_period#Synodic_period). 31 | * Determine the time at periapsis using the Keplerian orbital parameters and the formula for [mean anomaly](https://en.wikipedia.org/wiki/Mean_anomaly). 32 | 33 | ## Transfer [(transfer.ks)](transfer.ks) 34 | 35 | Takes the raw search information returned by `search.ks` then uses it to create initial maneuver nodes. The maneuver nodes are then refined using feedback loops that depend on the specific situation. 36 | 37 | There are four situations: 38 | * **Vessel to Vessel** *(asteroids and comets also count as vessels)* 39 | Vessel to vessel transfers within the same [SOI](https://en.wikipedia.org/wiki/Sphere_of_influence_(astrodynamics)) are the most straightforward case. The values from the Lambert solver are accurate enough to be used directly with no modifications, resulting in very precise intercepts, even over interplanetary distances. 40 | * **Vessel to Body** 41 | The initial Vessel to Body transfer is *too* accurate, resulting in a transfer that collides dead center with the destination. An `orbit.ks` function returns the impact parameter, that is the distance that we should offset in order to miss by roughly our desired periapsis. This is used as an inital value to a feedback loop, where the value is refined until the projected orbit is very close (to within 1%) of the target figure. 42 | * **Body to Vessel** 43 | The transfer velocities returned by the raw search make some simplifying assumptions. The vessel is assumed to leave from a point at exactly the center of the planet and the affect of the planet's gravity are not taken into account. To refine the initial transfer, a feedback loop measures the projected velocity of the vessel just at the moment it leaves the origin planet's SOI, then re-runs the Lambert solver to calculate what it should actually be. This error is applied to the original maneuver node, then the procedure repeats until the error drops below a threshold, resulting in a much more accurate transfer. 44 | * **Body to Body** 45 | The previous two approaches are combined when travelling from planet to planet. Firstly the body-to-vessel feedback loop is used to create a transfer that hits the destination planet dead center. Then the impact parameter and desired final orbit orientation are combined to calculate an offset from the planet in order to "miss" by the right amount in the right direction. Finally the transfer feedback loop is re-run with this new offset, resulting in a good approximation to the final desired orbit. 46 | 47 | ## Maneuver Node Helper [(maneuver.ks)](maneuver.ks) 48 | 49 | Wrapper around a raw kOS maneuver node that provides methods to predict details of future encounters. Projected arrival time and arrival velocity at the moment the ship enters an SOI are used to calculate the impact parameter and also used in the `transfer.ks` feedback loop refinement. Projected periapsis time and periapsis altitude are used to create arrival maneuver nodes at a destination body. 50 | 51 | ## Parameter Validation [(validate.ks)](validate.ks) 52 | 53 | Checks that the types and values of user-supplied options match expectations. Additionally checks that the desired transfer is possible and reasonable, then also sanity checks that the save game actually allows maneuver nodes and flight planning (if career mode). Accumulates descriptive error messages to assist and guide the user. As this library is intended to be used within other scripts, the goal is to catch as much as possible up front then fail fast, rather than fail later with a difficult to understand stack trace. 54 | 55 | ## Entrypoint [(main.ks)](main.ks) 56 | 57 | Loads all the other scripts, then orchestrates the high level logic flow. When loading other scripts, the kOS `scriptpath` function is used so that the library can be located anywhere the user wants. To prevent pollution of the global namespace, all functions are scoped local then loaded into the `rsvp` lexicon, so that there is only a single external interface. 58 | 59 | ## Refine [(refine.ks)](refine.ks) 60 | 61 | Compose several orbital sub-functions to build the overall "cost" function used when searching the porkchop plot. The most important difference is between point-to-point transfers and soi-to-soi transfers. 62 | 63 | Point to point transfers treat the origin and destination as zero-width points and only use a single invocation of the Lamber solver for each point on the plot. 64 | 65 | SOI to SOI transfers take the spherical nature of the source and destination into account and run the Lambert solver multiple times, refining the position and time of the transfer for more accuracy. However as this is slower, it is only used when the ration of a body's SOI to its periapsis exceeds a threshold. -------------------------------------------------------------------------------- /src/search.ks: -------------------------------------------------------------------------------- 1 | @lazyglobal off. 2 | 3 | parameter export. 4 | export("find_launch_window", find_launch_window@). 5 | 6 | local function find_launch_window { 7 | parameter destination, settings. 8 | 9 | // For vessel-to-vessel or vessel-to-body transfers the origin considered 10 | // for search purposes is the vessel itself, otherwise use the parent body. 11 | local origin is choose ship if settings:origin_type = "vessel" else ship:body. 12 | 13 | // Use different defaults for asteroids and comets. 14 | local hyperbolic is destination:orbit:eccentricity >= 1. 15 | local extrasolar is hyperbolic and not destination:body:hasbody. 16 | 17 | // Calculate any default settings values using simple rules-of-thumb. 18 | local now is time():seconds. 19 | 20 | local earliest_departure is settings:earliest_departure. 21 | if earliest_departure = "default" { 22 | set earliest_departure to now + 120. 23 | } 24 | 25 | local search_duration is settings:search_duration. 26 | if search_duration = "default" { 27 | if extrasolar { 28 | set search_duration to origin:orbit:period. 29 | } 30 | else if hyperbolic { 31 | set search_duration to 0.5 * (rsvp:time_at_soi_edge(destination) - now). 32 | } 33 | else { 34 | local max_period is rsvp:max_period(origin, destination). 35 | local synodic_period is rsvp:synodic_period(origin, destination). 36 | set search_duration to max(max_period, synodic_period). 37 | } 38 | } 39 | 40 | local max_time_of_flight is settings:max_time_of_flight. 41 | if max_time_of_flight = "default" { 42 | if extrasolar { 43 | set max_time_of_flight to origin:orbit:period. 44 | } 45 | else if hyperbolic { 46 | set max_time_of_flight to 0.5 * (rsvp:time_at_soi_edge(destination) - now). 47 | } 48 | else { 49 | set max_time_of_flight to rsvp:ideal_hohmann_transfer_period(origin, destination). 50 | } 51 | } 52 | 53 | local search_interval is settings:search_interval. 54 | if search_interval = "default" { 55 | if extrasolar or hyperbolic { 56 | set search_interval to 0.5 * origin:orbit:period. 57 | } 58 | else { 59 | set search_interval to 0.5 * rsvp:min_period(origin, destination). 60 | } 61 | } 62 | 63 | local search_threshold is max(120, min(0.002 * search_interval, 3600)). 64 | 65 | // Build cost function. 66 | local transfer_details is rsvp:build_transfer_details(origin, destination, settings). 67 | 68 | // Find lowest deltav transfer. 69 | local craft_transfer is iterated_local_search( 70 | settings:verbose, 71 | earliest_departure, 72 | search_duration, 73 | max_time_of_flight, 74 | search_interval, 75 | search_threshold, 76 | transfer_details). 77 | 78 | // Re-run the Lambert solver to obtain deltav values. 79 | local details is transfer_details(craft_transfer:flip_direction, craft_transfer:departure_time, craft_transfer:arrival_time). 80 | 81 | // Construct nested result structure 82 | local departure is lex("time", craft_transfer:departure_time, "deltav", details:ejection). 83 | local arrival is lex("time", craft_transfer:arrival_time, "deltav", details:insertion). 84 | local predicted is lex("departure", departure, "arrival", arrival). 85 | local result to lex("success", true, "predicted", predicted). 86 | 87 | return lex("transfer", craft_transfer, "result", result). 88 | } 89 | 90 | // Local search algorithms such as hill climbing, gradient descent or 91 | // coordinate descent can easily get stuck in local minima. 92 | // 93 | // A simple way to work around this drawback is to start several searches at 94 | // different coordinates. There is then a good chance that at least one of the 95 | // searches will find the global minimum. 96 | // 97 | // Our solution space is the classic porkchop plot, where the x coordinate is 98 | // departure time and the y coordinate is time of flight. The Lambert solver and 99 | // orbital parameters provides the "cost" function of the delta-v requirement 100 | // at any given (x,y) point. 101 | local function iterated_local_search { 102 | parameter verbose, earliest_departure, search_duration, max_time_of_flight, search_interval, step_threshold, total_deltav. 103 | 104 | local x is earliest_departure. 105 | local latest_departure is earliest_departure + search_duration. 106 | 107 | // The default max_time_of_flight is twice the ideal Hohmann transfer time, 108 | // so setting the intial guess to half of that will be reasonably close to 109 | // the final value in most cases. 110 | local y is max_time_of_flight * 0.5. 111 | // The porkchop plot is not scaled evenly in the x and y dimensions. 112 | // Especially for transfers with a very large ratio between the periapsis 113 | // and apoapsis (for example Moho to Eeloo) each search interval is tall 114 | // and narrow. The step size is based on the x direction, so can be slow 115 | // when the hill climb algorithm is searching in the y direction. To speed 116 | // up the search, scale the step_size in the y direction. 117 | // The width of the search space is 3 search intervals (see min_x and 118 | // max_x declarations below) and the height is max_time_of_flight. 119 | local step_size is search_interval * 0.1. 120 | local scale_y is max_time_of_flight / (3 * search_interval). 121 | 122 | // Sneaky trick here. When comparing a scalar and a string, kOS converts the 123 | // scalar to a string then compares them lexicographically. 124 | // This means that *any* number will always be less than the string "max" 125 | // as "m" is a higher codepoint than the numeric digits 0-9. 126 | local result is lex("total_deltav", "max"). 127 | local invocations is 0. 128 | 129 | until x > latest_departure { 130 | // Restrict x to a limited range of the total search space to save time. 131 | // If x wanders too far from its original value, then most likely the 132 | // previous search has already found that minimum or the next search will 133 | // find it. 134 | local min_x is max(earliest_departure, x - search_interval). 135 | local max_x is min(latest_departure, x + 2 * search_interval). 136 | 137 | // Calculate the intial delta-v value at the starting point and also figure 138 | // out which direction we should be going. 139 | local prograde_deltav is cost(false, v(x, y, 0)). 140 | local retrograde_deltav is cost(true, v(x, y, 0)). 141 | local flip_direction is retrograde_deltav < prograde_deltav. 142 | local initial_deltav is choose retrograde_deltav if flip_direction else prograde_deltav. 143 | 144 | function cost { 145 | parameter flip_direction, v1. 146 | 147 | // y is always bounded to the interval [0, max_time_of_flight] 148 | if v1:x < min_x or v1:x > max_x or v1:y < 0 or v1:y > max_time_of_flight { 149 | return "max". 150 | } 151 | else { 152 | set invocations to invocations + 1. 153 | local details is total_deltav(flip_direction, v1:x, v1:x + v1:y). 154 | return details:ejection + details:insertion. 155 | } 156 | } 157 | 158 | // Start a search from this location, updating "result" if "candidate" delta-v is lower. 159 | local candidate is rsvp:grid_search(cost@:bind(flip_direction), x, y, scale_y, initial_deltav, step_size, step_threshold). 160 | local departure_time is candidate:position:x. 161 | local arrival_time is candidate:position:x + candidate:position:y. 162 | local total_deltav is candidate:minimum. 163 | 164 | if verbose { 165 | print "Search offset: " + seconds_to_kerbin_time(x). 166 | print " Departure: " + seconds_to_kerbin_time(departure_time). 167 | print " Arrival: " + seconds_to_kerbin_time(arrival_time). 168 | print " Delta-v: " + safe_round(total_deltav). 169 | } 170 | 171 | if total_deltav < result:total_deltav { 172 | set result to lex( 173 | "departure_time", departure_time, 174 | "arrival_time", arrival_time, 175 | "total_deltav", total_deltav, 176 | "flip_direction", flip_direction 177 | ). 178 | } 179 | 180 | set invocations to invocations + 2. 181 | set x to x + search_interval. 182 | } 183 | 184 | if verbose { 185 | print "Invocations: " + invocations. 186 | print "Best Result". 187 | print " Departure: " + seconds_to_kerbin_time(result:departure_time). 188 | print " Arrival: " + seconds_to_kerbin_time(result:arrival_time). 189 | print " Delta-v: " + safe_round(result:total_deltav). 190 | } 191 | 192 | return result. 193 | } 194 | 195 | // Convert epoch seconds to human readable string. 196 | local function seconds_to_kerbin_time { 197 | parameter seconds. 198 | 199 | local time_span is time(seconds). 200 | 201 | return time_span:calendar + " " + time_span:clock. 202 | } 203 | 204 | // Safely round a variable that could be a string 205 | local function safe_round { 206 | parameter x. 207 | 208 | return choose round(x) if x:istype("scalar") else x. 209 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RSVP [![version-badge]][release-link] [![download-badge]][release-link] 2 | 3 | [version-badge]: https://img.shields.io/github/v/release/maneatingape/rsvp 4 | [download-badge]: https://img.shields.io/github/downloads/maneatingape/rsvp/total 5 | [release-link]: https://github.com/maneatingape/rsvp/releases/latest 6 | 7 | *RSVP* is a [kOS](https://ksp-kos.github.io/KOS/) library that finds orbital [launch windows](https://en.wikipedia.org/wiki/Launch_window) in the game [Kerbal Space Program](https://www.kerbalspaceprogram.com/). The acronym stands for "Rendezvous s’il vous plaît", a playful pun on the regular meaning of the phrase. 8 | 9 | This library enables players to make automated low delta-v transfers between two planets or vessels in-game, either directly from their own kOS scripts or from the kOS console. It provides a scriptable alternative to existing tools, such as the excellent web based [Launch Window Planner](https://alexmoon.github.io/ksp/) or the snazzy [MechJeb Maneuver Planner](https://github.com/MuMech/MechJeb2/wiki/Maneuver-Planner). 10 | 11 | ## Features 12 | 13 | * Integrates with your kOS scripts. 14 | * Creates departure and arrival maneuver nodes. 15 | * Supports rendezvous between vessels, planets, moons, asteroids and comets. 16 | * Adapts to planetary packs such as [Galileo's Planet Pack](https://forum.kerbalspaceprogram.com/index.php?/topic/152136-ksp-181-galileos-planet-pack-v164-01-july-2020/), [Outer Planets Mods](https://forum.kerbalspaceprogram.com/index.php?/topic/184789-131-18x-outer-planets-mod-v226-4th-feb-2020/) and [JNSQ](https://forum.kerbalspaceprogram.com/index.php?/topic/184880-181-jnsq-090-03-feb-2020/). 17 | 18 | This short video shows these features in action: 19 | [![Demo Video](images/demo_preview.png)](https://vimeo.com/442344803) 20 | 21 | ## Quickstart 22 | 23 | 1. Go to the [Releases](https://github.com/maneatingape/rsvp/releases) tab, then download latest version of `rsvp.zip`. 24 | 2. Unzip into `/Ships/Script` directory. This step adds the library to the kOS archive volume, making it available to all vessels. 25 | 3. Launch a craft into a stable orbit of Kerbin. 26 | 4. Run this script from the craft: 27 | ``` 28 | set config:ipu to 2000. 29 | runoncepath("0:/rsvp/main"). 30 | local options is lexicon("create_maneuver_nodes", "both", "verbose", true). 31 | rsvp:goto(duna, options). 32 | ``` 33 | This will find the next transfer window from Kerbin to Duna then create the corresponding maneuver nodes necessary to make the journey. Additionally it will print details to the console during the search. 34 | 35 | --- 36 | 37 | ## Configuration 38 | 39 | The following options allow players to customize and tweak the desired transfer orbit. The general philosophy is that sensible defaults are provided for each option so that only custom values need to be provided. Specify options by adding them as key/value pairs to the `options` lexicon parameter. 40 | 41 | ### Verbose 42 | 43 | Prints comprehensive details to the kOS console if set to "True". 44 | 45 | | Key | Default value | Accepted values | 46 | |:----|:--------------|:----------------| 47 | | `verbose` | False | `Boolean` | 48 | 49 | ### Create Maneuver Nodes 50 | 51 | Whether or not to create maneuver nodes that will execute the desired journey. The value "none" can be used for planning, the script will return details of the next transfer window. 52 | 53 | | Key | Default value | Accepted values | 54 | |:----|:--------------|:----------------| 55 | | `create_maneuver_nodes` | None | One of `String` values "none", "first" or "both" | 56 | 57 | ### Cleanup Maneuver Nodes 58 | 59 | If any problems are enountered when creating the transfer then remove and cleanup any maneuver nodes that have been created. Defaults to true but can be disabled for debugging purposes. 60 | 61 | | Key | Default value | Accepted values | 62 | |:----|:--------------|:----------------| 63 | | `cleanup_maneuver_nodes` | True | `Boolean` | 64 | 65 | ### Earliest Departure 66 | 67 | When to start searching for transfer windows. Time can be in the vessel's past, present or future. The only restriction is that the time must be greater than the epoch time (Year 1, Day 1, 0:00:00) 68 | 69 | | Key | Default value | Accepted values | 70 | |:----|:--------------|:----------------| 71 | | `earliest_departure` | Current universal time of CPU vessel plus 2 minutes | Seconds from epoch as `Scalar` | 72 | 73 | ### Search Duration 74 | 75 | Only search for transfer windows within the specified duration from earliest departure. Restricting the search duration can come in handy when time is of the essence. Increasing the duration may reveal a lower cost delta-v transfer to patient players. 76 | 77 | | Key | Default value | Accepted values | 78 | |:----|:--------------|:----------------| 79 | | `search_duration` | Maximum of origin orbital period, destination orbital period or their synodic period | Duration in seconds as `Scalar` | 80 | 81 | ### Search Interval 82 | 83 | How frequently new sub-searches are started within the search duration. Lower values may result in better delta-v values being discovered, however the search will take longer to complete. 84 | 85 | | Key | Default value | Accepted values | 86 | |:----|:--------------|:----------------| 87 | | `search_interval` | Half the minimum of origin orbital period and destination orbital period | Duration in seconds as `Scalar` | 88 | 89 | ### Maximum time of flight 90 | 91 | Maximum duration of the transfer orbit between origin and destination. Some reasons it may come in useful to adjust this are life support mods, challenge requirements and career mode contract deadlines. 92 | 93 | | Key | Default value | Accepted values | 94 | |:----|:--------------|:----------------| 95 | | `max_time_of_flight` | Twice the time of a idealized Hohmann transfer between origin and destination | Duration in seconds as `Scalar` | 96 | 97 | ### Final Orbit Periapsis[*](#note-on-vessel-rendezvous) 98 | 99 | Sets desired destination orbit periapsis in meters. 100 | 101 | | Key | Default value | Accepted values | 102 | |:----|:--------------|:----------------| 103 | | `final_orbit_periapsis` | 100,000m | Altitude in meters as `Scalar` | 104 | 105 | ### Final Orbit Type[*](#note-on-vessel-rendezvous) 106 | 107 | The insertion orbit can be one of three types: 108 | * **None** 109 | Use when an aerocapture, flyby or extreme lithobraking is intended at the destination. When calculating the total delta-v the insertion portion is considered zero. 110 | * **Circular** 111 | Capture into a circular orbit at the altitude specified by `final_orbit_periapsis`. Does not change inclination. If the origin and destination bodies are inclined then this orbit will be inclined too. 112 | * **Elliptical** 113 | Capture into a highly elliptical orbit with apoapsis *just* inside the destination's SOI and periapsis at the altitude specified by `final_orbit_periapsis`. This can come in useful if the vessel will send a separate lander down to the surface or the intention is to visit moons of the destination. 114 | 115 | | Key | Default value | Accepted values | 116 | |:----|:--------------|:----------------| 117 | | `final_orbit_type` | Circular | One of `String` values "none", "circular" or "elliptical" | 118 | 119 | ### Final Orbit Orientation[*](#note-on-vessel-rendezvous) 120 | 121 | The orbit orientation can be one of three types: 122 | * **Prograde** 123 | Rotation of the final orbit will be the same as the rotation of the planet. Suitable for most missions. 124 | * **Polar** 125 | Orbit will pass over the poles of the planet at 90 degrees inclination. Useful for survey missions. 126 | * **Retrograde** 127 | Orbit will be the opposite to the rotation of the planet. An example use for this setting is solar powered craft that need to arrive on the daylight side of the planet. 128 | 129 | | Key | Default value | Accepted values | 130 | |:----|:--------------|:----------------| 131 | | `final_orbit_orientation` | Prograde | One of `String` values "prograde", "polar" or "retrograde" | 132 | 133 | ### Note on Vessel rendezvous 134 | 135 | Vessel destinations are treated slightly differently to Celestial body destinations. Setting a vessel as the destination disables the `final_orbit_periapsis`, `final_orbit_type` and `final_orbit_orientation` options. 136 | 137 | --- 138 | 139 | ## Integrating with your scripts 140 | 141 | RSVP is designed with some quality of life features to make it as straightforward as possible to use within your own scripts. 142 | 143 | * There is only a single global `rsvp` variable as the entrypoint. All other functions, variables and delegates are locally scoped so that you don't have to worry about name collisions. 144 | * The library can be located anywhere as long as all script files are in the same directory. The suggested location is `0:/rsvp`, however you are free to choose any other volume or path. 145 | * Detailed return values indicate success or failure. The return value is a lexicon that will always have a top-level boolean `success` key. Check this value before proceeding with the rest of your script. 146 | 147 | For example, a successful result is: 148 | ``` 149 | LEXICON of 3 items: 150 | ["success"] = True 151 | ["predicted"] = LEXICON of 2 items: 152 | ["departure"] = LEXICON of 2 items: 153 | ["time"] = 5055453.38357352 154 | ["deltav"] = 1036.59841185951 155 | ["arrival"] = LEXICON of 2 items: 156 | ["time"] = 10766955.6939971 157 | ["deltav"] = 642.186439333725 158 | ["actual"] = LEXICON of 2 items: 159 | ["departure"] = LEXICON of 2 items: 160 | ["time"] = 5055629.63357352 161 | ["deltav"] = 1056.03106245216 162 | ["arrival"] = LEXICON of 2 items: 163 | ["time"] = 10768356.5846979 164 | ["deltav"] = 647.973826829273 165 | ``` 166 | An example of a transfer with problems is: 167 | ``` 168 | LEXICON of 2 items: 169 | ["success"] = False 170 | ["problems"] = LEXICON of 2 items: 171 | [1] = "Option 'verbose' is 'qux', expected boolean" 172 | [303] = "Option 'foo_bar' not recognised" 173 | ``` 174 | * To save space on the limited hard disks of kOS processors you can compile the source to `.ksm` files that are about 20% of the size of the raw source. A convenience `rsvp:compile_to` function exists for this purpose. For example, the following code will compile the source from the archive then copy the compiled files to the hard disk of the current processor. 175 | ``` 176 | runoncepath("0:/rsvp/main"). 177 | createdir("1:/rsvp"). 178 | rsvp:compile_to("1:/rsvp"). 179 | ``` 180 | 181 | ## Technical Details 182 | 183 | The [source code readme](src) contains detailed descriptions of the under-the-hood mechanisms. Each script file is thoroughly commented to describe both what the code is doing, but also more importantly *why*. 184 | 185 | ## Suggest a feature or report a bug 186 | 187 | If you have an idea for a feature or have found a bug then you can [create an issue here](https://github.com/maneatingape/rsvp/issues/new/choose). Before you do so, please check that the issue doesn't already exist in the [isses list](https://github.com/maneatingape/rsvp/issues). -------------------------------------------------------------------------------- /src/refine.ks: -------------------------------------------------------------------------------- 1 | @lazyglobal off. 2 | 3 | parameter export. 4 | export("build_transfer_details", build_transfer_details@). 5 | 6 | // Compose several orbital sub-functions to build the overall "cost" function 7 | // used when searching the porkchop plot. The most important difference is 8 | // between point-to-point transfers and soi-to-soi transfers. 9 | // 10 | // Point to point transfers treat the origin and destination as zero-width points 11 | // and only use a single invocation of the Lamber solver for each point on the 12 | // plot. 13 | // 14 | // SOI to SOI transfers take the spherical nature of the source and destination 15 | // into account and run the Lambert solver multiple times, refining the position 16 | // and time of the transfer for more accuracy. However as this is slower, it is 17 | // only used when the ration of a body's SOI to its periapsis exceeds a threshold. 18 | local function build_transfer_details { 19 | parameter origin, destination, settings. 20 | 21 | local from_vessel is settings:origin_type = "vessel". 22 | local to_vessel is settings:destination_type = "vessel". 23 | local initial_orbit_periapsis is max(ship:periapsis, 0). 24 | 25 | local transfer_deltav is rsvp:transfer_deltav:bind(origin, destination). 26 | local validate_ejection_orbit is build_validate_ejection_orbit(from_vessel). 27 | local validate_insertion_orbit is build_validate_insertion_orbit(to_vessel, destination, settings). 28 | local ejection_deltav is build_ejection_deltav(from_vessel, origin, initial_orbit_periapsis). 29 | local insertion_deltav is build_insertion_deltav(to_vessel, destination, settings). 30 | local success is build_success(ejection_deltav, insertion_deltav). 31 | 32 | if (from_vessel or below_soi_threshold(origin)) and (to_vessel or below_soi_threshold(destination)) { 33 | return build_point_to_point_transfer(transfer_deltav, validate_ejection_orbit, validate_insertion_orbit, success). 34 | } 35 | else { 36 | local adjust_departure is choose build_nop_adjustment(origin) 37 | if from_vessel else build_adjust_departure(origin, initial_orbit_periapsis). 38 | 39 | local adjust_arrival is choose build_nop_adjustment(destination) 40 | if to_vessel else build_adjust_arrival(destination, settings). 41 | 42 | return build_soi_to_soi_transfer(transfer_deltav, validate_ejection_orbit, validate_insertion_orbit, success, origin, adjust_departure, adjust_arrival). 43 | } 44 | } 45 | 46 | // Convenience method that returns a value indicating that the transfer 47 | // is not possible, for example orbital constraints are breached or the 48 | // iterative refinement failed to converge. 49 | local function failure { 50 | return lex("ejection", "none", "insertion", "none"). 51 | } 52 | 53 | // Check if a body's SOI to Periapsis ration is below a threshold of 1%. 54 | // All planets except Jool in the stock game are under this threshold. 55 | // All moons except Gilly and Pol are over this threshold. 56 | local function below_soi_threshold { 57 | parameter destination_body. 58 | 59 | local ratio is destination_body:soiradius / destination_body:orbit:periapsis. 60 | 61 | return ratio < 0.01. 62 | } 63 | 64 | // Returns a delegate that validates transfer orbit constraints. 65 | // Vessels are free to make any manuever no matter how small. 66 | // 67 | // Due to KSP's finite SOI, each celestial body has a deltav floor that a 68 | // transfer cannot go below. For planets this doesn't matter too 69 | // much, as the delta-v to the nearest neighbour will easily exceed this. 70 | // However for moons with large SOI to Periapsis ratio, the minimum value can be 71 | // high. For example a direct Hohmann transfer from Laythe to Vall is impossible 72 | // as Laythe's minimum escape velocity is greater than this value. 73 | local function build_validate_ejection_orbit { 74 | parameter from_vessel. 75 | 76 | if from_vessel { 77 | return { 78 | parameter details. 79 | return true. 80 | }. 81 | } 82 | else { 83 | // Apoapsis is the worse case scenario. Use this rather than periapsis, 84 | // as at this stage we don't know exactly where in the vessel's orbit 85 | // the departure manuever node will end up. 86 | local minimum_escape_velocity is rsvp:minimum_escape_velocity(ship:orbit:body, ship:orbit:apoapsis). 87 | 88 | return { 89 | parameter details. 90 | return details:dv1:mag > minimum_escape_velocity. 91 | }. 92 | } 93 | } 94 | 95 | // Similar to the previous function, returns a delegate that makes sure the 96 | // injection orbit is above the minimum possible velocity based on the 97 | // desired periapsis. 98 | // 99 | // This is to prevent errors when in some situtations the initial point to point 100 | // transfer returned from the Lambert solver is below the minimum possible. 101 | local function build_validate_insertion_orbit { 102 | parameter to_vessel, destination, settings. 103 | 104 | if to_vessel { 105 | return { 106 | parameter details. 107 | return true. 108 | }. 109 | } 110 | else { 111 | // Minimum ejection and insertion values are the same due to the fact 112 | // orbits are symmetrical when direction is reversed. 113 | local minimum_insertion_velocity is rsvp:minimum_escape_velocity(destination, settings:final_orbit_periapsis). 114 | 115 | return { 116 | parameter details. 117 | return details:dv2:mag > minimum_insertion_velocity. 118 | }. 119 | } 120 | } 121 | 122 | local function build_ejection_deltav { 123 | parameter from_vessel, origin, craft_altitude. 124 | 125 | local prefix is choose "vessel" if from_vessel else "equatorial". 126 | local delegate is rsvp[prefix + "_ejection_deltav"]. 127 | 128 | return delegate:bind(origin, craft_altitude). 129 | } 130 | 131 | local function build_insertion_deltav { 132 | parameter to_vessel, destination, settings. 133 | 134 | local prefix is choose "vessel" if to_vessel else settings:final_orbit_type. 135 | local delegate is rsvp[prefix + "_insertion_deltav"]. 136 | local final_orbit_periapsis is settings:final_orbit_periapsis. 137 | 138 | return delegate:bind(destination, final_orbit_periapsis). 139 | } 140 | 141 | // Combine the delegates returned by the previous two function into a single 142 | // convenience delegate. 143 | local function build_success { 144 | parameter ejection_deltav, insertion_deltav. 145 | 146 | return { 147 | parameter details. 148 | 149 | return lex( 150 | "ejection", ejection_deltav(details), 151 | "insertion", insertion_deltav(details:dv2) 152 | ). 153 | }. 154 | } 155 | 156 | // Vessels have no SOI and need no adjustment. Returns the same position and 157 | // time that has been passed in. 158 | local function build_nop_adjustment { 159 | parameter orbitable. 160 | 161 | return { 162 | parameter epoch_time, deltav. 163 | 164 | local osv is rsvp:orbital_state_vectors(orbitable, epoch_time). 165 | 166 | osv:add("adjusted_position", osv:position). 167 | osv:add("adjusted_time", epoch_time). 168 | 169 | return osv. 170 | }. 171 | } 172 | 173 | // Calculate the position where a vessel will exit the origin SOI and the 174 | // duration of the journey from periapsis to edge of SOI, given a desired 175 | // ejection velocity. 176 | // 177 | // One minor quirk, the orbit orientation is based on an injection trajectory, 178 | // so a prograde ejection is a "retrograde" injection. 179 | local function build_adjust_departure { 180 | parameter origin_body, craft_altitude. 181 | 182 | return { 183 | parameter epoch_time, deltav. 184 | 185 | local duration is rsvp:duration_from_soi_edge(origin_body, craft_altitude, deltav). 186 | local adjusted_time is epoch_time + duration. 187 | local osv is rsvp:orbital_state_vectors(origin_body, adjusted_time). 188 | local offset is rsvp:offset_from_soi_edge(origin_body, craft_altitude, "retrograde", deltav). 189 | 190 | osv:add("adjusted_position", osv:position + offset). 191 | osv:add("adjusted_time", adjusted_time). 192 | 193 | return osv. 194 | }. 195 | } 196 | 197 | // Calculate the position that a vessel should enter the SOI, in order to 198 | // end up at the desired orientation and altitude. 199 | local function build_adjust_arrival { 200 | parameter destination_body, settings. 201 | 202 | local craft_altitude is settings:final_orbit_periapsis. 203 | local orientation is settings:final_orbit_orientation. 204 | 205 | return { 206 | parameter epoch_time, deltav. 207 | 208 | local duration is rsvp:duration_from_soi_edge(destination_body, craft_altitude, deltav). 209 | local adjusted_time is epoch_time - duration. 210 | local osv is rsvp:orbital_state_vectors(destination_body, adjusted_time). 211 | local offset is rsvp:offset_from_soi_edge(destination_body, craft_altitude, orientation, deltav). 212 | 213 | osv:add("adjusted_position", osv:position + offset). 214 | osv:add("adjusted_time", adjusted_time). 215 | 216 | return osv. 217 | }. 218 | } 219 | 220 | // Point to point transfer neglecting the size of any SOIs. 221 | local function build_point_to_point_transfer { 222 | parameter transfer_deltav, validate_ejection_orbit, validate_insertion_orbit, success. 223 | 224 | return { 225 | parameter flip_direction, departure_time, arrival_time. 226 | 227 | local details is transfer_deltav(flip_direction, departure_time, arrival_time). 228 | local validated is validate_ejection_orbit(details) and validate_insertion_orbit(details). 229 | 230 | return choose success(details) if validated else failure(). 231 | }. 232 | } 233 | 234 | // Iteratively refine initial transfer in order to take SOI size into account. 235 | local function build_soi_to_soi_transfer { 236 | parameter transfer_deltav, validate_ejection_orbit, validate_insertion_orbit, success, origin, adjust_departure, adjust_arrival. 237 | 238 | local mu is origin:body:mu. 239 | 240 | return { 241 | parameter flip_direction, departure_time, arrival_time. 242 | 243 | local details is transfer_deltav(flip_direction, departure_time, arrival_time). 244 | local validated is validate_ejection_orbit(details) and validate_insertion_orbit(details). 245 | 246 | if not validated { 247 | return failure(). 248 | } 249 | 250 | local previous_delta is "max". 251 | local delta is 1. 252 | local iterations is 0. 253 | 254 | until delta < 1 { 255 | local departure is adjust_departure(departure_time, details:dv1). 256 | local arrival is adjust_arrival(arrival_time, details:dv2). 257 | 258 | local r1 is departure:adjusted_position. 259 | local r2 is arrival:adjusted_position. 260 | local time_of_flight is arrival:adjusted_time - departure:adjusted_time. 261 | 262 | local solution is rsvp:lambert(r1, r2, time_of_flight, mu, flip_direction). 263 | local dv1 is solution:v1 - departure:velocity. 264 | local dv2 is arrival:velocity - solution:v2. 265 | 266 | set delta to (details:dv1 - dv1):mag + (details:dv2 - dv2):mag. 267 | set details to lex("dv1", dv1, "dv2", dv2, "osv1", departure). 268 | set iterations to iterations + 1. 269 | set validated to validate_ejection_orbit(details) and validate_insertion_orbit(details). 270 | 271 | if iterations < 10 and delta < previous_delta and validated { 272 | set previous_delta to delta. 273 | } 274 | else { 275 | return failure(). 276 | } 277 | } 278 | 279 | return success(details). 280 | }. 281 | } -------------------------------------------------------------------------------- /src/transfer.ks: -------------------------------------------------------------------------------- 1 | @lazyglobal off. 2 | 3 | parameter export. 4 | export("vessel_to_vessel", vessel_to_vessel@). 5 | export("vessel_to_body", vessel_to_body@). 6 | export("body_to_vessel", body_to_vessel@). 7 | export("body_to_body", body_to_body@). 8 | 9 | // Vessel to vessel rendezvous (asteroids and comets also technically count 10 | // as vessels) within the same SOI is the most straightforward case. The values 11 | // from the Lambert solver are more than accurate enough to be used directly 12 | // resulting in very precise intercepts, even over interplanetary distances. 13 | local function vessel_to_vessel { 14 | parameter destination, settings, craft_transfer, result. 15 | 16 | // Calculate transfer orbit details from search result 17 | local flip_direction is craft_transfer:flip_direction. 18 | local departure_time is craft_transfer:departure_time. 19 | local arrival_time is craft_transfer:arrival_time. 20 | local details is rsvp:transfer_deltav(ship, destination, flip_direction, departure_time, arrival_time). 21 | 22 | // 1st node 23 | local maneuver is create_vessel_node(departure_time, details:dv1). 24 | local departure is lex("time", departure_time, "deltav", details:dv1:mag). 25 | result:add("actual", lex("departure", departure)). 26 | 27 | // Check for unexpected encounters 28 | local expected_patches is list(ship:body). 29 | local validate_patches is maneuver:validate_patches(expected_patches, arrival_time). 30 | 31 | if not validate_patches:success { 32 | return validate_patches. 33 | } 34 | 35 | // 2nd node 36 | if settings:create_maneuver_nodes = "both" { 37 | create_vessel_node(arrival_time, details:dv2). 38 | local arrival is lex("time", arrival_time, "deltav", details:dv2:mag). 39 | result:actual:add("arrival", arrival). 40 | } 41 | 42 | return result. 43 | } 44 | 45 | // Vessel to body rendezvous requires some tweaking in order for the ship 46 | // to avoid colliding directly with the center of the destination. 47 | local function vessel_to_body { 48 | parameter destination, settings, craft_transfer, result. 49 | 50 | // Calculate transfer orbit details from search result. This transfer will be 51 | // *too* accurate with a trajectory that collides with the center of the body. 52 | local flip_direction is craft_transfer:flip_direction. 53 | local departure_time is craft_transfer:departure_time. 54 | local arrival_time is craft_transfer:arrival_time. 55 | local details is rsvp:transfer_deltav(ship, destination, flip_direction, departure_time, arrival_time). 56 | 57 | // Refine the transfer, taking destination's SOI into account. 58 | local delta is 1. 59 | local iterations is 0. 60 | local final_orbit_periapsis is settings:final_orbit_periapsis. 61 | local final_orbit_orientation is settings:final_orbit_orientation. 62 | 63 | until delta < 0.01 or iterations = 15 { 64 | local offset is rsvp:offset_from_soi_edge(destination, final_orbit_periapsis, final_orbit_orientation, details:dv2). 65 | local duration is rsvp:duration_from_soi_edge(destination, final_orbit_periapsis, details:dv2). 66 | 67 | local next is rsvp:transfer_deltav(ship, destination, flip_direction, departure_time, arrival_time - duration, ship:body, offset). 68 | local delta is (next:dv2 - details:dv2):mag. 69 | 70 | set details to next. 71 | set iterations to iterations + 1. 72 | } 73 | 74 | // Create initial maneuver node 75 | local maneuver is create_vessel_node(departure_time, details:dv1). 76 | 77 | // Check for unexpected encounters 78 | local expected_patches is list(ship:body, destination). 79 | local validate_patches is maneuver:validate_patches(expected_patches, arrival_time). 80 | 81 | if not validate_patches:success { 82 | return validate_patches. 83 | } 84 | 85 | // Add actual departure deltav to the result. This will differ slightly 86 | // from the predicted value due to the offset tweaks. 87 | local departure is lex("time", departure_time, "deltav", maneuver:deltav()). 88 | result:add("actual", lex("departure", departure)). 89 | 90 | // 2nd node 91 | if settings:create_maneuver_nodes = "both" { 92 | local arrival is create_body_arrival_node(destination, settings, maneuver). 93 | result:actual:add("arrival", arrival). 94 | } 95 | 96 | return result. 97 | } 98 | 99 | // Vessel to body rendezvous is not as accurate as other transfer types, so a 100 | // correction burn is recommended once in interplanetary space. 101 | local function body_to_vessel { 102 | parameter destination, settings, craft_transfer, result. 103 | 104 | // 1st node 105 | local maybe is create_body_departure_node(false, destination, settings, craft_transfer). 106 | 107 | // Node creation could fail due to unexpected encounter 108 | if not maybe:success { 109 | return maybe. 110 | } 111 | 112 | // Check for unexpected encounters 113 | local maneuver is maybe:maneuver. 114 | local expected_patches is list(ship:body, ship:body:body). 115 | local arrival_time is craft_transfer:arrival_time. 116 | local validate_patches is maneuver:validate_patches(expected_patches, arrival_time). 117 | 118 | if not validate_patches:success { 119 | return validate_patches. 120 | } 121 | 122 | // Add actual departure deltav to the result. This will differ quite a bit 123 | // from the predicted value due to the difficulties ejecting from a body 124 | // exactly at the predicted time and orientation. 125 | local departure is lex("time", maneuver:time(), "deltav", maneuver:deltav()). 126 | result:add("actual", lex("departure", departure)). 127 | 128 | // 2nd node 129 | if settings:create_maneuver_nodes = "both" { 130 | local osv1 is rsvp:orbital_state_vectors(ship, arrival_time). 131 | local osv2 is rsvp:orbital_state_vectors(destination, arrival_time). 132 | local deltav is osv2:velocity - osv1:velocity. 133 | create_vessel_node(arrival_time, deltav). 134 | 135 | local arrival is lex("time", arrival_time, "deltav", deltav:mag). 136 | result:actual:add("arrival", arrival). 137 | } 138 | 139 | return result. 140 | } 141 | 142 | // Body to body rendezvous is reasonably accurate as the predicted intercept 143 | // can be used to refine the initial transfer. 144 | local function body_to_body { 145 | parameter destination, settings, craft_transfer, result. 146 | 147 | // 1st node 148 | local maybe is create_body_departure_node(true, destination, settings, craft_transfer). 149 | 150 | // Node creation could fail due to unexpected encounter 151 | if not maybe:success { 152 | return maybe. 153 | } 154 | 155 | // Check for unexpected encounters 156 | local maneuver is maybe:maneuver. 157 | local expected_patches is list(ship:body, ship:body:body, destination). 158 | local arrival_time is craft_transfer:arrival_time. 159 | local validate_patches is maneuver:validate_patches(expected_patches, arrival_time). 160 | 161 | if not validate_patches:success { 162 | return validate_patches. 163 | } 164 | 165 | // Add actual departure deltav to the result. This will differ somewhat 166 | // from the predicted value due to the difficulties ejecting from a body 167 | // exactly at the predicted time and orientation. 168 | set maneuver to maybe:maneuver. 169 | local departure is lex("time", maneuver:time(), "deltav", maneuver:deltav()). 170 | result:add("actual", lex("departure", departure)). 171 | 172 | // 2nd node 173 | if settings:create_maneuver_nodes = "both" { 174 | local arrival is create_body_arrival_node(destination, settings, maneuver). 175 | result:actual:add("arrival", arrival). 176 | } 177 | 178 | return result. 179 | } 180 | 181 | // Creates both departure and arrival nodes for vessels, as the steps are the 182 | // same for both situations. 183 | local function create_vessel_node { 184 | parameter epoch_time, deltav. 185 | 186 | return rsvp:create_maneuver(true, epoch_time, deltav). 187 | } 188 | 189 | // Create an arrival node for a body, using the various "final_orbit..." 190 | // setttings to result in the desired orbit periapsis and shape. 191 | local function create_body_arrival_node { 192 | parameter destination, settings, maneuver. 193 | 194 | local patch_details is maneuver:patch_details(destination). 195 | local soi_velocity is patch_details:soi_velocity. 196 | local periapsis_altitude is patch_details:periapsis_altitude. 197 | local periapsis_time is patch_details:periapsis_time. 198 | 199 | local insertion_deltav is rsvp[settings:final_orbit_type + "_insertion_deltav"]. 200 | local deltav is insertion_deltav(destination, periapsis_altitude, soi_velocity). 201 | 202 | // Brake by the right amount at the right time. 203 | rsvp:create_raw_maneuver(false, periapsis_time, v(0, 0, -deltav)). 204 | 205 | return lex("time", periapsis_time, "deltav", deltav). 206 | } 207 | 208 | // Creates an ejection maneuver node by applying a feedback loop to refine it. 209 | // The initial transfer will be incorrect as it assumes that the vessel 210 | // is floating in free space and neglects the time taken to climb out of the 211 | // origin planet's SOI. 212 | // We re-calculate the transfer immediately after leaving the origin's SOI 213 | // then feedback this error in order to correct our initial guess. This 214 | // converges rapidly to an accurate intercept. 215 | local function create_body_departure_node { 216 | parameter to_body, destination, settings, craft_transfer. 217 | 218 | local flip_direction is craft_transfer:flip_direction. 219 | local departure_time is craft_transfer:departure_time. 220 | local arrival_time is craft_transfer:arrival_time. 221 | 222 | local parent is ship:body. 223 | local grandparent is parent:body. 224 | local expected_patches is list(parent, grandparent). 225 | 226 | // Initial guess 227 | local details is rsvp:transfer_deltav(parent, destination, flip_direction, departure_time, arrival_time). 228 | local departure_deltav is details:dv1. 229 | local maneuver is create_maneuver_node_in_correct_location(departure_time, departure_deltav). 230 | 231 | // Refine the node 232 | local delta is v(1, 0, 0). 233 | local iterations is 0. 234 | local final_orbit_periapsis is settings:final_orbit_periapsis. 235 | local final_orbit_orientation is settings:final_orbit_orientation. 236 | local duration is 0. 237 | local offset is v(0, 0, 0). 238 | 239 | until delta:mag < 0.01 or iterations = 15 { 240 | // Expect the unexpected 241 | local patch_details is maneuver:patch_details(grandparent). 242 | local soi_time is choose "max" if patch_details = "none" else patch_details:soi_time. 243 | local validate_patches is maneuver:validate_patches(expected_patches, soi_time). 244 | 245 | if not validate_patches:success { 246 | return validate_patches. 247 | } 248 | 249 | // Take SOI into account 250 | if to_body { 251 | set offset to rsvp:offset_from_soi_edge(destination, final_orbit_periapsis, final_orbit_orientation, details:dv2). 252 | set duration to rsvp:duration_from_soi_edge(destination, final_orbit_periapsis, details:dv2). 253 | } 254 | 255 | // Calculate correction using predicted flight path 256 | local details is rsvp:transfer_deltav(ship, destination, flip_direction, soi_time, arrival_time - duration, grandparent, offset). 257 | 258 | // Update our current departure velocity with this correction. 259 | set delta to details:dv1. 260 | set iterations to iterations + 1. 261 | set departure_time to maneuver:time(). 262 | set departure_deltav to departure_deltav + delta. 263 | 264 | // Apply the new node, rinse and repeat. 265 | maneuver:delete(). 266 | set maneuver to create_maneuver_node_in_correct_location(departure_time, departure_deltav). 267 | } 268 | 269 | return lex("success", true, "maneuver", maneuver). 270 | } 271 | 272 | // Creates maneuver node at the correct location around the origin planet in 273 | // order to eject at the desired orientation. 274 | // Using the raw magnitude of the delta-v as our cost function handles 275 | // mutliple situtations and edge cases in one simple robust approach. 276 | // For example prograde/retrograde ejection combined with 277 | // clockwise/anti-clockwise orbit gives at least 4 valid possibilities 278 | // that need to handled. 279 | // 280 | // Additionaly this method implicitly includes the necessary adjustment 281 | // to the manuever node position to account for the radial component 282 | // of the ejection velocity. 283 | // 284 | // Finally it can handle non-perfectly circular and inclined orbits. 285 | local function create_maneuver_node_in_correct_location { 286 | parameter departure_time, departure_deltav. 287 | 288 | function ejection_details { 289 | parameter cost_only, v1. 290 | 291 | local epoch_time is v1:x. 292 | local osv is rsvp:orbital_state_vectors(ship, epoch_time). 293 | local ejection_deltav is rsvp:vessel_ejection_deltav_from_body(ship:body, osv, departure_deltav). 294 | 295 | return choose ejection_deltav:mag if cost_only else ejection_deltav. 296 | } 297 | 298 | // Search for time in ship's orbit where ejection deltav is lowest. 299 | local cost is ejection_details@:bind(true). 300 | local result is rsvp:line_search(cost, departure_time, 120, 1). 301 | local ejection_deltav is ejection_details(false, result:position). 302 | 303 | return rsvp:create_maneuver(false, result:position:x, ejection_deltav). 304 | } -------------------------------------------------------------------------------- /src/orbit.ks: -------------------------------------------------------------------------------- 1 | @lazyglobal off. 2 | 3 | parameter export. 4 | export("transfer_deltav", transfer_deltav@). 5 | export("orbital_state_vectors", orbital_state_vectors@). 6 | export("equatorial_ejection_deltav", equatorial_ejection_deltav@). 7 | export("vessel_ejection_deltav", vessel_ejection_deltav@). 8 | export("vessel_ejection_deltav_from_body", vessel_ejection_deltav_from_body@). 9 | export("circular_insertion_deltav", orbit_insertion_deltav@:bind(true)). 10 | export("elliptical_insertion_deltav", orbit_insertion_deltav@:bind(false)). 11 | export("vessel_insertion_deltav", vessel_insertion_deltav@). 12 | export("none_insertion_deltav", none_insertion_deltav@). 13 | export("minimum_escape_velocity", minimum_escape_velocity@). 14 | export("ideal_hohmann_transfer_period", ideal_hohmann_transfer_period@). 15 | export("synodic_period", synodic_period@). 16 | export("max_period", max_period@). 17 | export("min_period", min_period@). 18 | export("time_at_periapsis", time_at_periapsis@). 19 | export("time_at_soi_edge", time_at_soi_edge@). 20 | export("duration_from_soi_edge", duration_from_soi_edge@). 21 | export("offset_from_soi_edge", offset_from_soi_edge@). 22 | 23 | // Calculates the delta-v needed to transfer between origin and destination 24 | // planets at the specified times. 25 | // 26 | // Simplifying assumption: 27 | // * The distance to the SOI edge from the center of the planet is small enough 28 | // (relative to the interplanetary transfer distance) that we can assume the 29 | // position at SOI edge is a close enough approximation to the position 30 | // supplied to the Lambert solver. 31 | // 32 | // Parameters: 33 | // origin [Body] Departure planet that vessel will leave from. 34 | // destination [Body] Destination planet that vessel will arrive at. 35 | // flip_direction [Boolean] Change transfer direction between prograde/retrograde 36 | // departure [Scalar] Departure time in seconds from epoch 37 | // arrival [Scalar] Arrival time in seconds from epoch 38 | local function transfer_deltav { 39 | parameter origin, destination, flip_direction, departure_time, arrival_time, parent is origin:body, offset is v(0, 0, 0). 40 | 41 | local time_of_flight is arrival_time - departure_time. 42 | local osv1 is orbital_state_vectors(origin, departure_time, parent). 43 | local osv2 is orbital_state_vectors(destination, arrival_time, parent). 44 | 45 | local r1 is osv1:position. 46 | local r2 is osv2:position + offset. 47 | local mu is parent:mu. 48 | 49 | // Now that we know the positions of the planets at our departure and 50 | // arrival time, solve Lambert's problem to determine the velocity of the 51 | // transfer orbit that links the planets at both positions. 52 | local solution is rsvp:lambert(r1, r2, time_of_flight, mu, flip_direction). 53 | local dv1 is solution:v1 - osv1:velocity. 54 | local dv2 is osv2:velocity - solution:v2. 55 | 56 | return lex("dv1", dv1, "dv2", dv2, "osv1", osv1). 57 | } 58 | 59 | // Returns the cartesian orbital state vectors of position and velocity 60 | // at any specified time in the present, past or future. 61 | local function orbital_state_vectors { 62 | parameter orbitable, epoch_time, parent is orbitable:body. 63 | 64 | // To determine the position of a planet at a specific time "t" relative to 65 | // its parent body using the "positionat" function, you must subtract the 66 | // *current* position of the parent body, not the position of the parent 67 | // body at time "t" as might be expected. 68 | local position is positionat(orbitable, epoch_time) - parent:position. 69 | // "velocityat" already returns orbital velocity relative to the parent 70 | // body, so no further adjustment is needed. 71 | local craft_velocity is velocityat(orbitable, epoch_time):orbit. 72 | 73 | return lex("position", position, "velocity", craft_velocity). 74 | } 75 | 76 | // Calculate the delta-v required to eject into a hyperbolic transfer orbit 77 | // at the correct inclination from the desired radius "r1". 78 | // 79 | // Simplifying assumption: 80 | // * Vessel is currently in a perfectly circular equatorial orbit at radius "r1" 81 | // and velocity "v1" at 0 degrees inclination. 82 | // 83 | // Our required delta-v, "v1" and 've" form a triangle with angle "i" between 84 | // sides 'v1" and "ve'. The length of the 3rd side is the magnitude of our required 85 | // delta-v and can be determined using the cosine rule. We calculate the cosine 86 | // directly from the magnitudes of "v2" and its normal component. 87 | // 88 | // The "body_insertion_deltav" function comment contains details on 89 | // the formulas used to calculate "v1" and "ve". 90 | local function equatorial_ejection_deltav { 91 | parameter origin, craft_altitude, transfer_details. 92 | 93 | local mu is origin:mu. 94 | local r1 is origin:radius + craft_altitude. 95 | local r2 is origin:soiradius. 96 | 97 | local v1 is sqrt(mu / r1). 98 | local v2 is transfer_details:dv1:mag. 99 | local ve is sqrt(v2 ^ 2 + mu * (2 / r1 - 2 / r2)). 100 | 101 | local osv1 is transfer_details:osv1. 102 | local unit_normal is vcrs(osv1:velocity, osv1:position):normalized. 103 | local normal_component is vdot(unit_normal, transfer_details:dv1). 104 | 105 | local sin_i is normal_component / v2. 106 | local cos_i is sqrt(1 - sin_i ^ 2). 107 | local ejection_deltav is sqrt(ve ^ 2 + v1 ^ 2 - 2 * ve * v1 * cos_i). 108 | 109 | return ejection_deltav. 110 | } 111 | 112 | // Vessels have no SOI or gravity so the delta-v required is exactly the 113 | // transfer orbit departure or arrival delta-v. 114 | local function vessel_ejection_deltav { 115 | parameter origin, craft_altitude, transfer_details. 116 | 117 | return transfer_details:dv1:mag. 118 | } 119 | 120 | // Calculates the delta-v required for a vessel to eject into the desired 121 | // transfer orbit, using its actual current orbit. As the vessel climbs out of 122 | // the gravity well of the origin there are two effects to consider: 123 | // * It slows down as it trades kinetic energy for potential energy, so that 124 | // initial excess velocity must be higher than our desired transfer velocity. 125 | // * The gravity of the origin bends our trajectory as we escape, so that the 126 | // initial velocity vector must be adjusted to compensate. 127 | local function vessel_ejection_deltav_from_body { 128 | parameter origin, osv, departure_deltav. 129 | 130 | local mu is origin:mu. 131 | local r1 is osv:position:mag. 132 | local r2 is origin:soiradius. 133 | 134 | local v2 is departure_deltav:mag. 135 | local ve is sqrt(v2 ^ 2 + mu * (2 / r1 - 2 / r2)). 136 | 137 | // Calculate the eccentricity and semi-major axis of the escape hyperbola 138 | // (or possibly ellipse as KSP "chops" off the top of an ellipse once past 139 | // SOI, so you can escape even if mathematically the orbit is not a hyperbola). 140 | local e is ve ^ 2 * r1 / mu - 1. 141 | local a is r1 / (1 - e). 142 | // Calculate hyperbolic eccentric anomaly at a distance r2 from the focus. 143 | local cosh_E is (a - r2) / (a * e). 144 | // Slope of the velocity at a distance r2 from the focus: 145 | // dy = b * cosh(E) 146 | // dx = -a * sinh(E) 147 | // dy / dx = (b / -a) * cosh(E) / sinh(E) 148 | // Replace (b / -a) with sqrt(e ^ 2 - 1) 149 | // Replace sinh(E) with sqrt(cosh(E) ^ 2 - 1) 150 | local m is cosh_E * sqrt((e ^ 2 - 1) / (cosh_E ^ 2 - 1)). 151 | 152 | // Now that we know the angle that the origin bends our escape trajectory, 153 | // we work backwards to determine the initial escape velocity vector. 154 | // Starting with the desired transfer velocity at SOI edge given by 155 | // "departure_deltav", we first invert the rotation acquired during escape, 156 | // then scale by the appropriate factor and finally subtract the vessel's 157 | // current velocity to give the delta-v required. 158 | // 159 | // "slope_angle" is exactly 90 degrees in the case of a parabolic ejection 160 | // (barely escaping, eccentricity is 1) and approaches 0 degrees as the 161 | // hyperbolic excess velocity and eccentricity tends to infinity. 162 | // 163 | // Additionally for the special case in KSP where you can escape with an 164 | // mathematically elliptical orbit (impossible in real life, however KSP 165 | // "chops" off the top of an orbit once you exceed SOI radius) 166 | // the angle is greater than 90 degrees. For example, a situation where this 167 | // can occur is during a Laythe to Tylo transfer. 168 | local slope_angle is 90 - arctan(m). 169 | local ship_normal is vcrs(osv:velocity, osv:position). 170 | local inverse_rotation is angleaxis(slope_angle, ship_normal). 171 | local ejection_velocity is (ve / v2) * departure_deltav * inverse_rotation. 172 | 173 | return ejection_velocity - osv:velocity. 174 | } 175 | 176 | // Calculate the delta-v required to convert a hyperbolic intercept orbit 177 | // into a circular or elliptical orbit around the target planet 178 | // with the desired periapsis. 179 | // 180 | // To simplify calculations no inclination change is made, so that the delta-v 181 | // required will simply be the difference between the hyperbolic velocity 182 | // at "r1" and the elliptical orbital velocity at "r1". 183 | // 184 | // For an elliptical orbit at radius "r1" the orbital velocity "v1" is 185 | // straightforward to calculate using the vis-viva equation. Circular orbits 186 | // are a special case with semi-major axis equal to the final altitude. 187 | // 188 | // Calculating the hyperbolic velocity (denoted "ve") at "r1" is more fun 189 | // and can be determined by applying the vis-visa equation twice. 190 | // Our velocity "v2" at the edge of the SOI (radius denoted "r2") can be 191 | // closely approximated as the magnitude of the "transfer_details:dv2" vector. 192 | // 193 | // The vis-viva equation states that: 194 | // [Equation 1] v2 ^ 2 = mu * (2 / r2 - 1 / a) 195 | // 196 | // Re-arranging gives: 197 | // [Equation 2] -1 / a = (v2 ^ 2) / mu - 2 / r2 198 | // 199 | // Applying the equation again at "r1" gives: 200 | // [Equation 3] v ^ 2 = mu * (2 / r1 - 1 / a) 201 | // 202 | // Substituting 2 into 3 gives: 203 | // [Equation 4] v ^ 2 = mu * (2 / r1 + (v2 ^ 2) / mu - 2 / r2) 204 | // 205 | // Re-arranging slightly: 206 | // [Equation 5] v ^ 2 = (v2 ^ 2) + mu * (2 / r1 - 2 / r2) 207 | // 208 | // Taking the square root of equation 5 then subtracting 'v1" gives the delta-v 209 | // required to capture into the desired orbit. 210 | local function orbit_insertion_deltav { 211 | parameter is_circular, destination, craft_altitude, arrival_velocity. 212 | 213 | local mu is destination:mu. 214 | local r1 is destination:radius + craft_altitude. 215 | local r2 is destination:soiradius. 216 | 217 | // For elliptical orbits set apoapsis to 99% of the SOI radius 218 | // in order to leave some wiggle room. 219 | local a is choose r1 if is_circular else (r1 + 0.99 * r2) / 2. 220 | 221 | local v1 is sqrt(mu * (2 / r1 - 1 / a)). 222 | local v2 is arrival_velocity:mag. 223 | local ve is sqrt(v2 ^ 2 + mu * (2 / r1 - 2 / r2)). 224 | 225 | return ve - v1. 226 | } 227 | 228 | // Vessels have no SOI or gravity so the delta-v required is exactly the 229 | // transfer orbit departure or arrival delta-v. 230 | local function vessel_insertion_deltav { 231 | parameter destination, craft_altitude, arrival_velocity. 232 | 233 | return arrival_velocity:mag. 234 | } 235 | 236 | // Calculate the delta-v required for a flyby, aerocapture or extreme lithobrake... 237 | local function none_insertion_deltav { 238 | parameter destination, craft_altitude, arrival_velocity. 239 | 240 | return 0. 241 | } 242 | 243 | // Calculate the minimum velocity that a craft can leave its current SOI with. 244 | // As all KSP SOIs are finite, this will always be non-zero. For most planets 245 | // this will be less than the minimum Hohmann transfer velocity to the nearest 246 | // neighbour. 247 | // 248 | // For some moons with very large SOIs relative to their orbits this value will 249 | // be *greater*. For example, Laythe's minimum escape velocity is higher than 250 | // a direct Hohmann transfer to Vall, and even higher than a Hohmann transfer 251 | // to Tylo at certain phase angles. 252 | // 253 | // For maximum safety factor this assumes that the ejection burn takes place at 254 | // the current apoapsis, giving the maximum possible value. If the ejection burn 255 | // takes place anywhere else on the orbit, then the actual value will be lower. 256 | local function minimum_escape_velocity { 257 | parameter celestial_body, craft_altitude. 258 | 259 | local mu is celestial_body:mu. 260 | local r1 is celestial_body:radius + craft_altitude. 261 | local r2 is celestial_body:soiradius. 262 | 263 | local a is (r1 + r2) / 2. 264 | local ve is sqrt(mu * (2 / r2 - 1 / a)). 265 | 266 | return ve. 267 | } 268 | 269 | // Calculate the time of flight for an idealized Hohmann transfer orbit between 270 | // two planets. This provides an approximate initial guess when searching the 271 | // solution space provided by the Lambert solver. 272 | // 273 | // Simplifying assumptions: 274 | // * Both planet's orbits are circular (eccentricity is ignored). 275 | // * Transfer angle is exactly 180 degrees. 276 | // 277 | // This means that the idealized transfer orbit is an elliptical orbit with a 278 | // semi-major axis equal to the average of both planet's semi-major axes. 279 | // The period can then be determined analytically using Kepler's 3rd law. 280 | local function ideal_hohmann_transfer_period { 281 | parameter origin, destination. 282 | 283 | local a is (origin:orbit:semimajoraxis + destination:orbit:semimajoraxis) / 2. 284 | local mu is origin:body:mu. 285 | 286 | return 2 * constant:pi * sqrt(a ^ 3 / mu). 287 | } 288 | 289 | // Calculate the syndodic period. This is the time between conjunctions when 290 | // both planets have the same ecliptic longtitude or alternatively when both 291 | // planets return to the same phase angle. Eccentricity and inclination are 292 | // not considered so the planets will not necessarily be in exactly the same 293 | // three dimensional position relative to each other. 294 | // 295 | // The closer two planets' orbital period the longer the synodic period, 296 | // approaching infinity as the orbital periods converge. Intuitively this makes 297 | // sense. If two planets' orbits are exactly the same then they are always at 298 | // the same phase angle. 299 | // 300 | // This value is included in the heuristic when determining the search duration 301 | // to prevent it from being too short. For example two planets with short but 302 | // similar orbital periods would have a long synodic period that needs to be 303 | // searched to reliably return to lowest cost delta-v transfer. 304 | local function synodic_period { 305 | parameter origin, destination. 306 | 307 | local p1 is origin:orbit:period. 308 | local p2 is destination:orbit:period. 309 | 310 | return abs(p1 * p2 / (p1 - p2)). 311 | } 312 | 313 | // Returns the maximum period of either the origin or destination. 314 | local function max_period { 315 | parameter origin, destination. 316 | 317 | return max(origin:orbit:period, destination:orbit:period). 318 | } 319 | 320 | // Returns the minimum period of either the origin or destination. 321 | local function min_period { 322 | parameter origin, destination. 323 | 324 | return min(origin:orbit:period, destination:orbit:period). 325 | } 326 | 327 | // Calculate the time at periapsis from orbital parameters. Hyperbolic intercept 328 | // orbits will have a negative semi-majoraxis and negative mean anomaly at epoch. 329 | // The mean anomaly increases to zero as the object approaches periapsis, then 330 | // becomes positive and continously increasing until the object leaves the SOI. 331 | local function time_at_periapsis { 332 | parameter craft_orbit. 333 | 334 | // By definition, mean anomaly is zero at periapsis. 335 | return time_at_mean_anomaly(craft_orbit, 0). 336 | } 337 | 338 | // Calculate the universal time for an object at a certain point in an orbit 339 | // given the mean anomaly at that point. 340 | local function time_at_mean_anomaly { 341 | parameter craft_orbit, M. 342 | 343 | // Calculate mean motion "n" using absolute value of semi-majoraxis 344 | // to handle both elliptical and hyperbolic cases 345 | local mu is craft_orbit:body:mu. 346 | local a is craft_orbit:semimajoraxis. 347 | local n is sqrt(mu / abs(a ^ 3)). 348 | 349 | // Get reference mean anomaly and epoch time. 350 | local t0 is craft_orbit:epoch. 351 | local M0 is craft_orbit:meananomalyatepoch * constant:degtorad. // Careful with units 352 | 353 | // Calculate mean anomaly difference, clamping to the range [0, 2π] 354 | // so that all times are in the future. 355 | local delta_M is M - M0. 356 | if delta_M < 0 { 357 | set delta_M to delta_M + 2 * constant:pi. 358 | } 359 | 360 | return t0 + delta_M / n. 361 | } 362 | 363 | // Calculate the time at which an object on a hyperbolic orbit will leave its 364 | // current SOI. Positive mean anomaly is when the object is past periapsis and 365 | // heading towards the edge of the SOI. 366 | local function time_at_soi_edge { 367 | parameter destination. 368 | 369 | local r2 is destination:body:soiradius. 370 | local destination_orbit is destination:orbit. 371 | local a is destination_orbit:semimajoraxis. 372 | local e is destination_orbit:eccentricity. 373 | 374 | // Calculate mean anomaly from eccentric anomaly using hyperbolic variant 375 | // of Keplers' equation. 376 | local cosh_H is (a - r2) / (a * e). 377 | local sinh_H is sqrt(cosh_H ^ 2 - 1). 378 | local H is ln(cosh_H + sinh_H). 379 | local M is e * sinh_H - H. 380 | 381 | return time_at_mean_anomaly(destination_orbit, M). 382 | } 383 | 384 | // Calculate the time duration that a vessel will take from the edge of 385 | // destination SOI to periapsis. This function is similar to the 386 | // "time_at_soi_edge" function, the keys differences are: 387 | // * Returns relative duration instead of an absolute time. 388 | // * Derives the orbital parameters from arrival velocity and desired periapsis. 389 | // * Handles both hyperbolic and elliptical injection orbits. 390 | local function duration_from_soi_edge { 391 | parameter destination, craft_altitude, arrival_deltav. 392 | 393 | local mu is destination:mu. 394 | local r1 is destination:radius + craft_altitude. 395 | local r2 is destination:soiradius. 396 | 397 | local v2 is arrival_deltav:sqrmagnitude. 398 | local ve is v2 + mu * (2 / r1 - 2 / r2). 399 | 400 | local e is ve * r1 / mu - 1. 401 | local a is r1 / (1 - e). 402 | local n is sqrt(mu / abs(a ^ 3)). 403 | local M is "none". 404 | 405 | if e < 1 { 406 | local cos_E is (a - r2) / (a * e). 407 | local sin_E is sqrt(1 - cos_E ^ 2). 408 | local EA is arccos(cos_E) * constant:degtorad. 409 | set M to EA - e * sin_E. 410 | } 411 | else { 412 | local cosh_H is (a - r2) / (a * e). 413 | local sinh_H is sqrt(cosh_H ^ 2 - 1). 414 | local H is ln(cosh_H + sinh_H). 415 | set M to e * sinh_H - H. 416 | } 417 | 418 | return M / n. 419 | } 420 | 421 | // This function is based on the approach from the paper: 422 | // "A new method of patched-conic for interplanetary orbit" 423 | // by Jin Li, Jianhui Zhao and Fan Li 424 | // https://doi.org/10.1016/j.ijleo.2017.10.153 425 | // 426 | // Given a velocity vector at SOI boundary, periapsis altitude and inclination, 427 | // it derives the position vector "r" that satisifies the contraints. 428 | // This position vector is combined in a feedback loop with the Lambert solver 429 | // to refine the initial estimate from one that only considers planets as points 430 | // to one that takes the SOI spheres into account. 431 | // 432 | // A key insight not in the original paper is that the minimum value of inclination 433 | // can be derived from the equations for "h" and that using this value simplifies 434 | // the equations considerably. As these equations use KSP's coordinate system, 435 | // the x-z plane is the ecliptic and the y-axis is the north pole of the sun. 436 | local function offset_from_soi_edge { 437 | parameter destination, craft_altitude, orientation, arrival_deltav. 438 | 439 | local mu is destination:mu. 440 | local r1 is destination:radius + craft_altitude. 441 | local r2 is destination:soiradius. 442 | 443 | local v1 is arrival_deltav. 444 | local v2 is v1:sqrmagnitude. 445 | local ve is sqrt(v2 + mu * (2 / r1 - 2 / r2)). 446 | 447 | // Specific angular momentum vector, chosen to minimize inclination. 448 | local h_mag is ve * r1. 449 | local n_mag is v1:x ^ 2 + v1:z ^ 2. 450 | local h is "none". 451 | 452 | if orientation = "polar" { 453 | set h to v(v1:z, 0, -v1:x) * (h_mag / sqrt(n_mag)). 454 | } 455 | else { 456 | local sign is choose 1 if orientation = "prograde" else -1. 457 | local cos_i is sign * sqrt(n_mag / v2). 458 | set h to v(-v1:x * v1:y / n_mag, 1, -v1:y * v1:z / n_mag) * (h_mag * cos_i). 459 | } 460 | 461 | // Given "v1", "h" and "delta" (the dot product of "r" and "v1") 462 | // derive the position vector "r". 463 | local delta is sqrt(v2 * r2 ^ 2 - h_mag ^ 2). 464 | local r_x is delta * v1:x + h:z * v1:y - h:y * v1:z. 465 | local r_y is delta * v1:y + h:x * v1:z - h:z * v1:x. 466 | local r_z is delta * v1:z + h:y * v1:x - h:x * v1:y. 467 | 468 | return v(r_x, r_y, r_z) / v2. 469 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ### GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | 7 | 8 | Everyone is permitted to copy and distribute verbatim copies of this 9 | license document, but changing it is not allowed. 10 | 11 | ### Preamble 12 | 13 | The GNU General Public License is a free, copyleft license for 14 | software and other kinds of works. 15 | 16 | The licenses for most software and other practical works are designed 17 | to take away your freedom to share and change the works. By contrast, 18 | the GNU General Public License is intended to guarantee your freedom 19 | to share and change all versions of a program--to make sure it remains 20 | free software for all its users. We, the Free Software Foundation, use 21 | the GNU General Public License for most of our software; it applies 22 | also to any other work released this way by its authors. You can apply 23 | it to your programs, too. 24 | 25 | When we speak of free software, we are referring to freedom, not 26 | price. Our General Public Licenses are designed to make sure that you 27 | have the freedom to distribute copies of free software (and charge for 28 | them if you wish), that you receive source code or can get it if you 29 | want it, that you can change the software or use pieces of it in new 30 | free programs, and that you know you can do these things. 31 | 32 | To protect your rights, we need to prevent others from denying you 33 | these rights or asking you to surrender the rights. Therefore, you 34 | have certain responsibilities if you distribute copies of the 35 | software, or if you modify it: responsibilities to respect the freedom 36 | of others. 37 | 38 | For example, if you distribute copies of such a program, whether 39 | gratis or for a fee, you must pass on to the recipients the same 40 | freedoms that you received. You must make sure that they, too, receive 41 | or can get the source code. And you must show them these terms so they 42 | know their rights. 43 | 44 | Developers that use the GNU GPL protect your rights with two steps: 45 | (1) assert copyright on the software, and (2) offer you this License 46 | giving you legal permission to copy, distribute and/or modify it. 47 | 48 | For the developers' and authors' protection, the GPL clearly explains 49 | that there is no warranty for this free software. For both users' and 50 | authors' sake, the GPL requires that modified versions be marked as 51 | changed, so that their problems will not be attributed erroneously to 52 | authors of previous versions. 53 | 54 | Some devices are designed to deny users access to install or run 55 | modified versions of the software inside them, although the 56 | manufacturer can do so. This is fundamentally incompatible with the 57 | aim of protecting users' freedom to change the software. The 58 | systematic pattern of such abuse occurs in the area of products for 59 | individuals to use, which is precisely where it is most unacceptable. 60 | Therefore, we have designed this version of the GPL to prohibit the 61 | practice for those products. If such problems arise substantially in 62 | other domains, we stand ready to extend this provision to those 63 | domains in future versions of the GPL, as needed to protect the 64 | freedom of users. 65 | 66 | Finally, every program is threatened constantly by software patents. 67 | States should not allow patents to restrict development and use of 68 | software on general-purpose computers, but in those that do, we wish 69 | to avoid the special danger that patents applied to a free program 70 | could make it effectively proprietary. To prevent this, the GPL 71 | assures that patents cannot be used to render the program non-free. 72 | 73 | The precise terms and conditions for copying, distribution and 74 | modification follow. 75 | 76 | ### TERMS AND CONDITIONS 77 | 78 | #### 0. Definitions. 79 | 80 | "This License" refers to version 3 of the GNU General Public License. 81 | 82 | "Copyright" also means copyright-like laws that apply to other kinds 83 | of works, such as semiconductor masks. 84 | 85 | "The Program" refers to any copyrightable work licensed under this 86 | License. Each licensee is addressed as "you". "Licensees" and 87 | "recipients" may be individuals or organizations. 88 | 89 | To "modify" a work means to copy from or adapt all or part of the work 90 | in a fashion requiring copyright permission, other than the making of 91 | an exact copy. The resulting work is called a "modified version" of 92 | the earlier work or a work "based on" the earlier work. 93 | 94 | A "covered work" means either the unmodified Program or a work based 95 | on the Program. 96 | 97 | To "propagate" a work means to do anything with it that, without 98 | permission, would make you directly or secondarily liable for 99 | infringement under applicable copyright law, except executing it on a 100 | computer or modifying a private copy. Propagation includes copying, 101 | distribution (with or without modification), making available to the 102 | public, and in some countries other activities as well. 103 | 104 | To "convey" a work means any kind of propagation that enables other 105 | parties to make or receive copies. Mere interaction with a user 106 | through a computer network, with no transfer of a copy, is not 107 | conveying. 108 | 109 | An interactive user interface displays "Appropriate Legal Notices" to 110 | the extent that it includes a convenient and prominently visible 111 | feature that (1) displays an appropriate copyright notice, and (2) 112 | tells the user that there is no warranty for the work (except to the 113 | extent that warranties are provided), that licensees may convey the 114 | work under this License, and how to view a copy of this License. If 115 | the interface presents a list of user commands or options, such as a 116 | menu, a prominent item in the list meets this criterion. 117 | 118 | #### 1. Source Code. 119 | 120 | The "source code" for a work means the preferred form of the work for 121 | making modifications to it. "Object code" means any non-source form of 122 | a work. 123 | 124 | A "Standard Interface" means an interface that either is an official 125 | standard defined by a recognized standards body, or, in the case of 126 | interfaces specified for a particular programming language, one that 127 | is widely used among developers working in that language. 128 | 129 | The "System Libraries" of an executable work include anything, other 130 | than the work as a whole, that (a) is included in the normal form of 131 | packaging a Major Component, but which is not part of that Major 132 | Component, and (b) serves only to enable use of the work with that 133 | Major Component, or to implement a Standard Interface for which an 134 | implementation is available to the public in source code form. A 135 | "Major Component", in this context, means a major essential component 136 | (kernel, window system, and so on) of the specific operating system 137 | (if any) on which the executable work runs, or a compiler used to 138 | produce the work, or an object code interpreter used to run it. 139 | 140 | The "Corresponding Source" for a work in object code form means all 141 | the source code needed to generate, install, and (for an executable 142 | work) run the object code and to modify the work, including scripts to 143 | control those activities. However, it does not include the work's 144 | System Libraries, or general-purpose tools or generally available free 145 | programs which are used unmodified in performing those activities but 146 | which are not part of the work. For example, Corresponding Source 147 | includes interface definition files associated with source files for 148 | the work, and the source code for shared libraries and dynamically 149 | linked subprograms that the work is specifically designed to require, 150 | such as by intimate data communication or control flow between those 151 | subprograms and other parts of the work. 152 | 153 | The Corresponding Source need not include anything that users can 154 | regenerate automatically from other parts of the Corresponding Source. 155 | 156 | The Corresponding Source for a work in source code form is that same 157 | work. 158 | 159 | #### 2. Basic Permissions. 160 | 161 | All rights granted under this License are granted for the term of 162 | copyright on the Program, and are irrevocable provided the stated 163 | conditions are met. This License explicitly affirms your unlimited 164 | permission to run the unmodified Program. The output from running a 165 | covered work is covered by this License only if the output, given its 166 | content, constitutes a covered work. This License acknowledges your 167 | rights of fair use or other equivalent, as provided by copyright law. 168 | 169 | You may make, run and propagate covered works that you do not convey, 170 | without conditions so long as your license otherwise remains in force. 171 | You may convey covered works to others for the sole purpose of having 172 | them make modifications exclusively for you, or provide you with 173 | facilities for running those works, provided that you comply with the 174 | terms of this License in conveying all material for which you do not 175 | control copyright. Those thus making or running the covered works for 176 | you must do so exclusively on your behalf, under your direction and 177 | control, on terms that prohibit them from making any copies of your 178 | copyrighted material outside their relationship with you. 179 | 180 | Conveying under any other circumstances is permitted solely under the 181 | conditions stated below. Sublicensing is not allowed; section 10 makes 182 | it unnecessary. 183 | 184 | #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 185 | 186 | No covered work shall be deemed part of an effective technological 187 | measure under any applicable law fulfilling obligations under article 188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 189 | similar laws prohibiting or restricting circumvention of such 190 | measures. 191 | 192 | When you convey a covered work, you waive any legal power to forbid 193 | circumvention of technological measures to the extent such 194 | circumvention is effected by exercising rights under this License with 195 | respect to the covered work, and you disclaim any intention to limit 196 | operation or modification of the work as a means of enforcing, against 197 | the work's users, your or third parties' legal rights to forbid 198 | circumvention of technological measures. 199 | 200 | #### 4. Conveying Verbatim Copies. 201 | 202 | You may convey verbatim copies of the Program's source code as you 203 | receive it, in any medium, provided that you conspicuously and 204 | appropriately publish on each copy an appropriate copyright notice; 205 | keep intact all notices stating that this License and any 206 | non-permissive terms added in accord with section 7 apply to the code; 207 | keep intact all notices of the absence of any warranty; and give all 208 | recipients a copy of this License along with the Program. 209 | 210 | You may charge any price or no price for each copy that you convey, 211 | and you may offer support or warranty protection for a fee. 212 | 213 | #### 5. Conveying Modified Source Versions. 214 | 215 | You may convey a work based on the Program, or the modifications to 216 | produce it from the Program, in the form of source code under the 217 | terms of section 4, provided that you also meet all of these 218 | conditions: 219 | 220 | - a) The work must carry prominent notices stating that you modified 221 | it, and giving a relevant date. 222 | - b) The work must carry prominent notices stating that it is 223 | released under this License and any conditions added under 224 | section 7. This requirement modifies the requirement in section 4 225 | to "keep intact all notices". 226 | - c) You must license the entire work, as a whole, under this 227 | License to anyone who comes into possession of a copy. This 228 | License will therefore apply, along with any applicable section 7 229 | additional terms, to the whole of the work, and all its parts, 230 | regardless of how they are packaged. This License gives no 231 | permission to license the work in any other way, but it does not 232 | invalidate such permission if you have separately received it. 233 | - d) If the work has interactive user interfaces, each must display 234 | Appropriate Legal Notices; however, if the Program has interactive 235 | interfaces that do not display Appropriate Legal Notices, your 236 | work need not make them do so. 237 | 238 | A compilation of a covered work with other separate and independent 239 | works, which are not by their nature extensions of the covered work, 240 | and which are not combined with it such as to form a larger program, 241 | in or on a volume of a storage or distribution medium, is called an 242 | "aggregate" if the compilation and its resulting copyright are not 243 | used to limit the access or legal rights of the compilation's users 244 | beyond what the individual works permit. Inclusion of a covered work 245 | in an aggregate does not cause this License to apply to the other 246 | parts of the aggregate. 247 | 248 | #### 6. Conveying Non-Source Forms. 249 | 250 | You may convey a covered work in object code form under the terms of 251 | sections 4 and 5, provided that you also convey the machine-readable 252 | Corresponding Source under the terms of this License, in one of these 253 | ways: 254 | 255 | - a) Convey the object code in, or embodied in, a physical product 256 | (including a physical distribution medium), accompanied by the 257 | Corresponding Source fixed on a durable physical medium 258 | customarily used for software interchange. 259 | - b) Convey the object code in, or embodied in, a physical product 260 | (including a physical distribution medium), accompanied by a 261 | written offer, valid for at least three years and valid for as 262 | long as you offer spare parts or customer support for that product 263 | model, to give anyone who possesses the object code either (1) a 264 | copy of the Corresponding Source for all the software in the 265 | product that is covered by this License, on a durable physical 266 | medium customarily used for software interchange, for a price no 267 | more than your reasonable cost of physically performing this 268 | conveying of source, or (2) access to copy the Corresponding 269 | Source from a network server at no charge. 270 | - c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | - d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | - e) Convey the object code using peer-to-peer transmission, 288 | provided you inform other peers where the object code and 289 | Corresponding Source of the work are being offered to the general 290 | public at no charge under subsection 6d. 291 | 292 | A separable portion of the object code, whose source code is excluded 293 | from the Corresponding Source as a System Library, need not be 294 | included in conveying the object code work. 295 | 296 | A "User Product" is either (1) a "consumer product", which means any 297 | tangible personal property which is normally used for personal, 298 | family, or household purposes, or (2) anything designed or sold for 299 | incorporation into a dwelling. In determining whether a product is a 300 | consumer product, doubtful cases shall be resolved in favor of 301 | coverage. For a particular product received by a particular user, 302 | "normally used" refers to a typical or common use of that class of 303 | product, regardless of the status of the particular user or of the way 304 | in which the particular user actually uses, or expects or is expected 305 | to use, the product. A product is a consumer product regardless of 306 | whether the product has substantial commercial, industrial or 307 | non-consumer uses, unless such uses represent the only significant 308 | mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to 312 | install and execute modified versions of a covered work in that User 313 | Product from a modified version of its Corresponding Source. The 314 | information must suffice to ensure that the continued functioning of 315 | the modified object code is in no case prevented or interfered with 316 | solely because modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or 331 | updates for a work that has been modified or installed by the 332 | recipient, or for the User Product in which it has been modified or 333 | installed. Access to a network may be denied when the modification 334 | itself materially and adversely affects the operation of the network 335 | or violates the rules and protocols for communication across the 336 | network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | #### 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders 364 | of that material) supplement the terms of this License with terms: 365 | 366 | - a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | - b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | - c) Prohibiting misrepresentation of the origin of that material, 372 | or requiring that modified versions of such material be marked in 373 | reasonable ways as different from the original version; or 374 | - d) Limiting the use for publicity purposes of names of licensors 375 | or authors of the material; or 376 | - e) Declining to grant rights under trademark law for use of some 377 | trade names, trademarks, or service marks; or 378 | - f) Requiring indemnification of licensors and authors of that 379 | material by anyone who conveys the material (or modified versions 380 | of it) with contractual assumptions of liability to the recipient, 381 | for any liability that these contractual assumptions directly 382 | impose on those licensors and authors. 383 | 384 | All other non-permissive additional terms are considered "further 385 | restrictions" within the meaning of section 10. If the Program as you 386 | received it, or any part of it, contains a notice stating that it is 387 | governed by this License along with a term that is a further 388 | restriction, you may remove that term. If a license document contains 389 | a further restriction but permits relicensing or conveying under this 390 | License, you may add to a covered work material governed by the terms 391 | of that license document, provided that the further restriction does 392 | not survive such relicensing or conveying. 393 | 394 | If you add terms to a covered work in accord with this section, you 395 | must place, in the relevant source files, a statement of the 396 | additional terms that apply to those files, or a notice indicating 397 | where to find the applicable terms. 398 | 399 | Additional terms, permissive or non-permissive, may be stated in the 400 | form of a separately written license, or stated as exceptions; the 401 | above requirements apply either way. 402 | 403 | #### 8. Termination. 404 | 405 | You may not propagate or modify a covered work except as expressly 406 | provided under this License. Any attempt otherwise to propagate or 407 | modify it is void, and will automatically terminate your rights under 408 | this License (including any patent licenses granted under the third 409 | paragraph of section 11). 410 | 411 | However, if you cease all violation of this License, then your license 412 | from a particular copyright holder is reinstated (a) provisionally, 413 | unless and until the copyright holder explicitly and finally 414 | terminates your license, and (b) permanently, if the copyright holder 415 | fails to notify you of the violation by some reasonable means prior to 416 | 60 days after the cessation. 417 | 418 | Moreover, your license from a particular copyright holder is 419 | reinstated permanently if the copyright holder notifies you of the 420 | violation by some reasonable means, this is the first time you have 421 | received notice of violation of this License (for any work) from that 422 | copyright holder, and you cure the violation prior to 30 days after 423 | your receipt of the notice. 424 | 425 | Termination of your rights under this section does not terminate the 426 | licenses of parties who have received copies or rights from you under 427 | this License. If your rights have been terminated and not permanently 428 | reinstated, you do not qualify to receive new licenses for the same 429 | material under section 10. 430 | 431 | #### 9. Acceptance Not Required for Having Copies. 432 | 433 | You are not required to accept this License in order to receive or run 434 | a copy of the Program. Ancillary propagation of a covered work 435 | occurring solely as a consequence of using peer-to-peer transmission 436 | to receive a copy likewise does not require acceptance. However, 437 | nothing other than this License grants you permission to propagate or 438 | modify any covered work. These actions infringe copyright if you do 439 | not accept this License. Therefore, by modifying or propagating a 440 | covered work, you indicate your acceptance of this License to do so. 441 | 442 | #### 10. Automatic Licensing of Downstream Recipients. 443 | 444 | Each time you convey a covered work, the recipient automatically 445 | receives a license from the original licensors, to run, modify and 446 | propagate that work, subject to this License. You are not responsible 447 | for enforcing compliance by third parties with this License. 448 | 449 | An "entity transaction" is a transaction transferring control of an 450 | organization, or substantially all assets of one, or subdividing an 451 | organization, or merging organizations. If propagation of a covered 452 | work results from an entity transaction, each party to that 453 | transaction who receives a copy of the work also receives whatever 454 | licenses to the work the party's predecessor in interest had or could 455 | give under the previous paragraph, plus a right to possession of the 456 | Corresponding Source of the work from the predecessor in interest, if 457 | the predecessor has it or can get it with reasonable efforts. 458 | 459 | You may not impose any further restrictions on the exercise of the 460 | rights granted or affirmed under this License. For example, you may 461 | not impose a license fee, royalty, or other charge for exercise of 462 | rights granted under this License, and you may not initiate litigation 463 | (including a cross-claim or counterclaim in a lawsuit) alleging that 464 | any patent claim is infringed by making, using, selling, offering for 465 | sale, or importing the Program or any portion of it. 466 | 467 | #### 11. Patents. 468 | 469 | A "contributor" is a copyright holder who authorizes use under this 470 | License of the Program or a work on which the Program is based. The 471 | work thus licensed is called the contributor's "contributor version". 472 | 473 | A contributor's "essential patent claims" are all patent claims owned 474 | or controlled by the contributor, whether already acquired or 475 | hereafter acquired, that would be infringed by some manner, permitted 476 | by this License, of making, using, or selling its contributor version, 477 | but do not include claims that would be infringed only as a 478 | consequence of further modification of the contributor version. For 479 | purposes of this definition, "control" includes the right to grant 480 | patent sublicenses in a manner consistent with the requirements of 481 | this License. 482 | 483 | Each contributor grants you a non-exclusive, worldwide, royalty-free 484 | patent license under the contributor's essential patent claims, to 485 | make, use, sell, offer for sale, import and otherwise run, modify and 486 | propagate the contents of its contributor version. 487 | 488 | In the following three paragraphs, a "patent license" is any express 489 | agreement or commitment, however denominated, not to enforce a patent 490 | (such as an express permission to practice a patent or covenant not to 491 | sue for patent infringement). To "grant" such a patent license to a 492 | party means to make such an agreement or commitment not to enforce a 493 | patent against the party. 494 | 495 | If you convey a covered work, knowingly relying on a patent license, 496 | and the Corresponding Source of the work is not available for anyone 497 | to copy, free of charge and under the terms of this License, through a 498 | publicly available network server or other readily accessible means, 499 | then you must either (1) cause the Corresponding Source to be so 500 | available, or (2) arrange to deprive yourself of the benefit of the 501 | patent license for this particular work, or (3) arrange, in a manner 502 | consistent with the requirements of this License, to extend the patent 503 | license to downstream recipients. "Knowingly relying" means you have 504 | actual knowledge that, but for the patent license, your conveying the 505 | covered work in a country, or your recipient's use of the covered work 506 | in a country, would infringe one or more identifiable patents in that 507 | country that you have reason to believe are valid. 508 | 509 | If, pursuant to or in connection with a single transaction or 510 | arrangement, you convey, or propagate by procuring conveyance of, a 511 | covered work, and grant a patent license to some of the parties 512 | receiving the covered work authorizing them to use, propagate, modify 513 | or convey a specific copy of the covered work, then the patent license 514 | you grant is automatically extended to all recipients of the covered 515 | work and works based on it. 516 | 517 | A patent license is "discriminatory" if it does not include within the 518 | scope of its coverage, prohibits the exercise of, or is conditioned on 519 | the non-exercise of one or more of the rights that are specifically 520 | granted under this License. You may not convey a covered work if you 521 | are a party to an arrangement with a third party that is in the 522 | business of distributing software, under which you make payment to the 523 | third party based on the extent of your activity of conveying the 524 | work, and under which the third party grants, to any of the parties 525 | who would receive the covered work from you, a discriminatory patent 526 | license (a) in connection with copies of the covered work conveyed by 527 | you (or copies made from those copies), or (b) primarily for and in 528 | connection with specific products or compilations that contain the 529 | covered work, unless you entered into that arrangement, or that patent 530 | license was granted, prior to 28 March 2007. 531 | 532 | Nothing in this License shall be construed as excluding or limiting 533 | any implied license or other defenses to infringement that may 534 | otherwise be available to you under applicable patent law. 535 | 536 | #### 12. No Surrender of Others' Freedom. 537 | 538 | If conditions are imposed on you (whether by court order, agreement or 539 | otherwise) that contradict the conditions of this License, they do not 540 | excuse you from the conditions of this License. If you cannot convey a 541 | covered work so as to satisfy simultaneously your obligations under 542 | this License and any other pertinent obligations, then as a 543 | consequence you may not convey it at all. For example, if you agree to 544 | terms that obligate you to collect a royalty for further conveying 545 | from those to whom you convey the Program, the only way you could 546 | satisfy both those terms and this License would be to refrain entirely 547 | from conveying the Program. 548 | 549 | #### 13. Use with the GNU Affero General Public License. 550 | 551 | Notwithstanding any other provision of this License, you have 552 | permission to link or combine any covered work with a work licensed 553 | under version 3 of the GNU Affero General Public License into a single 554 | combined work, and to convey the resulting work. The terms of this 555 | License will continue to apply to the part which is the covered work, 556 | but the special requirements of the GNU Affero General Public License, 557 | section 13, concerning interaction through a network will apply to the 558 | combination as such. 559 | 560 | #### 14. Revised Versions of this License. 561 | 562 | The Free Software Foundation may publish revised and/or new versions 563 | of the GNU General Public License from time to time. Such new versions 564 | will be similar in spirit to the present version, but may differ in 565 | detail to address new problems or concerns. 566 | 567 | Each version is given a distinguishing version number. If the Program 568 | specifies that a certain numbered version of the GNU General Public 569 | License "or any later version" applies to it, you have the option of 570 | following the terms and conditions either of that numbered version or 571 | of any later version published by the Free Software Foundation. If the 572 | Program does not specify a version number of the GNU General Public 573 | License, you may choose any version ever published by the Free 574 | Software Foundation. 575 | 576 | If the Program specifies that a proxy can decide which future versions 577 | of the GNU General Public License can be used, that proxy's public 578 | statement of acceptance of a version permanently authorizes you to 579 | choose that version for the Program. 580 | 581 | Later license versions may give you additional or different 582 | permissions. However, no additional obligations are imposed on any 583 | author or copyright holder as a result of your choosing to follow a 584 | later version. 585 | 586 | #### 15. Disclaimer of Warranty. 587 | 588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT 592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 596 | CORRECTION. 597 | 598 | #### 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR 602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES 604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT 605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR 606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM 607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER 608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 609 | 610 | #### 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | ### How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these 626 | terms. 627 | 628 | To do so, attach the following notices to the program. It is safest to 629 | attach them to the start of each source file to most effectively state 630 | the exclusion of warranty; and each file should have at least the 631 | "copyright" line and a pointer to where the full notice is found. 632 | 633 | 634 | Copyright (C) 635 | 636 | This program is free software: you can redistribute it and/or modify 637 | it under the terms of the GNU General Public License as published by 638 | the Free Software Foundation, either version 3 of the License, or 639 | (at your option) any later version. 640 | 641 | This program is distributed in the hope that it will be useful, 642 | but WITHOUT ANY WARRANTY; without even the implied warranty of 643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 644 | GNU General Public License for more details. 645 | 646 | You should have received a copy of the GNU General Public License 647 | along with this program. If not, see . 648 | 649 | Also add information on how to contact you by electronic and paper 650 | mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands \`show w' and \`show c' should show the 661 | appropriate parts of the General Public License. Of course, your 662 | program's commands might be different; for a GUI interface, you would 663 | use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or 666 | school, if any, to sign a "copyright disclaimer" for the program, if 667 | necessary. For more information on this, and how to apply and follow 668 | the GNU GPL, see . 669 | 670 | The GNU General Public License does not permit incorporating your 671 | program into proprietary programs. If your program is a subroutine 672 | library, you may consider it more useful to permit linking proprietary 673 | applications with the library. If this is what you want to do, use the 674 | GNU Lesser General Public License instead of this License. But first, 675 | please read . 676 | --------------------------------------------------------------------------------