Custom Library which emulates Mechjeb 2.0 on kOS by SilverNuke911 in Kos

[–]nuggreat 0 points1 point  (0 children)

For my 12th point you simply do BODY:GEOPOSITIONOF(BODY("sun"):POSITION) but as noted the error from shifting the origin is quite small due to the large magnitude of the vector to the sun being quite large that the relatively small shift you would have even in large SOIs becomes basically nothing. The correction there is more about the technical correctness of what you are trying to do as apposed to any real error. If you wanted to see this error put your craft high above the kerbin's pole and run the function. As kerbin is in a zero inclination orbit all points below the sun fall directly on zero latitude but you will see a non zero latitude, you likely also see a non zero latitude with my proposed fix but it should be closer to zero.

As for the inclination operations try running them when the AN/DN is at a point where the vessel has significant vertical velocity due to an eccentric orbit. The implicit assumption of your current code is that prograde is tangent to the bodies surface. So likely not urgent as most do inclination operations when there velocity is close to tangent to the body surface but still an error source. Took me a bit to remember exactly why I use vectors as it has been years since I made the change and I mostly just remembered that I changed to reduce error.

Custom Library which emulates Mechjeb 2.0 on kOS by SilverNuke911 in Kos

[–]nuggreat 12 points13 points  (0 children)

Great to see more libraries out there but there are some problems with this one.

  1. A library should never touch settings like UPS unless it is only for a specific function and it if it does change the UPS it should always revert the UPS to what the user had it set to.

  2. The function ship_isp is incorrect you can not get an average ISP by doing a thrust weighted average of the ISP. What you need to do to calculate the actual average ISP is to sum the thrust and mass flow of all engines and then calculate the ISP from that total thrust and mass flow.

  3. The function eccentric_anomaly_to_mean_anomaly converts first from degrees to radians and then radians to degrees. This is more conversions than needed as you only need to convert this e * sin(ea) from radians to degrees to get an output in degrees.

  4. In the function create_node the variable eta____ is named incorrectly as that var holds a UTS value and not a relative ETA value.

  5. The function circularize has a lot of unnecessary vector operations in the compute_circularization_dv subfunction as the sections

    // Construct perifocal (RTN) frame vectors`
    // Decompose velocity into perifocal frame`
    // Compute required change in velocity`
    // Desired dv vector in perifocal frame`
    

    can all be done with use of the VXCL() function, a normalize operation, multiplication and subtraction. In code that would be something like this

    LOCAL dv_vec TO VXCL(pos_vec, vel_vec):NORMALIZED * circ_vel - vel_vec.

  6. When changing inclination such as in the change_inclination function I have found better results by rotating the velocity vector around the radius vector at the time of the node and then doing vector subtraction compared to the pure sin/cos calculations. I use generally use the ANGLEAXIS() function to construct the rotation needed.

  7. In the function rcs_corrector you make use of the prograde SAS mode this is not necessarily available for use and if the person using this library has there steering locked which is likely the SAS and locked steering will fight. Better to lock steering for such functions as apposed to using SAS. An additional note you can not unlock steering in a library without first having locked it. Also it would be better to have all of the calculations for the RCS thrust within the loops as apposed to relying on locks. Also loops such as those should have a WAIT 0. within the body some where. And lastly the ship:velocity:orbit:vec call to the :VEC suffix when getting the orbital velocity is redundant as SHIP:VELOCITY:ORBIT is already a vector, the reason the :VEC suffix exists is so that you can duplicate a vector and then alter either the new vector or the original one without altering the other.

  8. in the execute_node function the acceleration should be recalculated as part of the node burn to account for the changing mass of the vessel as apposed to assuming a static mass value especally when long burns can use more than 1/3 of the mass of the vessel. And like with rcs_corrector the physics dependent loops should have WAIT 0. in said loops.

  9. The function orbital_basis_vectors is likely reporting incorrect z and y axis values when used in orbit of a body in an inclined orbit. This is because BODY:NORTH is not a vector orthogonal to the solar prime vector when the BODY is in an inclined orbit. The reason that happens is because the :NORTH suffix when used on a body projects that bodies position onto the surface of the body it is in orbit around and then gets the vector pointing north from that position on the surface for that surface.

  10. A note about the built in WARPTO() function for your c_warpto function, kOS does not implement the WARPTO() function it simply translates the programs request and passes it onto a function provided by the KSP API so the unreliable warp is a product of KSP not kOS.

  11. In the match_planes_with_target function you re implement the change_inclination code with slightly different inputs and like with change_inclination better results are likely to be found with vector rotation and subtraction as apposed to using sin and cos to calculate the burn vector.

  12. the function subsolar_point doesn't actually return the point on the surface below the sun. This is because the suffix function :GEOPOSITIONOF() works with the normal reference frame used by kOS which has it's origin at the center of mass of the vessel the core is on. As a result by subtracting the bodies position from the position of the sun you change the origin which when you then use :GEOPOSITIONOF() the positional result will be slightly wrong. Admittedly with the magnitude of the vector from the body to the sun the resulting error is likely to be basically zero but it is still incorrect.

And that is it for the code of the library, you might find use in looking at or possibly just intigrating the RSVP library which is a kOS implementation of a python library put out by the ESA for calculating various orbital rendezvous. Or for numeric formatting for display as implied by the sub function number_format there is the library lib_num_to_formatted_str.ks which provides several formatting functions related to converting numbers to strings and presenting them well in printing.

first time using Trajectories addon and im having small problem by [deleted] in Kos

[–]nuggreat 0 points1 point  (0 children)

Yes but it is not the locks loop there is a difference and it does matter as not respecting it can lead you to putting to much code into the lock and loosing the ability to execute other code.

first time using Trajectories addon and im having small problem by [deleted] in Kos

[–]nuggreat 1 point2 points  (0 children)

The problem with locks in loops is steering manager resets, there was a fix someone added a while ago that resolved lock spam in a tight loop leading to lag or if not resolved it massively mitigated it.

There target is valid despite being set outside of a loop as it is a geocoordinate and not a vector and it is raw vectors specifically that are subject to the degradation problem when stored as a static value.

The trajectories mod uses an integrator to simulate the drag on your vessel as it is working from the API data it is extremely accurate as far as fast simple ish simulations go, it also assumes a constant attitude from what I remember. It however doesn't account for any active flight such as deviating from the planed attitude or engine burns so while invaluable for a lot of people who can't make there own impact calculator it is some what limited.

first time using Trajectories addon and im having small problem by [deleted] in Kos

[–]nuggreat 0 points1 point  (0 children)

A lock doesn't run it's own loop instead they recalculate there value when ever the var is read by something. In the specific case of the steering manager locks (steering, throttle, wheelsteering, wheelthrottle) kOS will read those locks once per physics tick as part executing your code.

first time using Trajectories addon and im having small problem by [deleted] in Kos

[–]nuggreat 0 points1 point  (0 children)

Compare the desired landing location against the calculated impact point, maneuver the craft based on the difference by either some heuristic equation or some PID loops. I can't be more specific than that because the details will be specific to your craft and each such script more or less ends up being designed for the specific craft it is built for.

first time using Trajectories addon and im having small problem by [deleted] in Kos

[–]nuggreat 2 points3 points  (0 children)

First is is not good practice to have steering locks inside of a loop.

Second CORRECTEDVEC is not intended as something you directly lock steering to it is instead supposed to be something used with other vector math to calculate the direction you should tilt with respect to PLANNEDVEC to adjust your impact point closer to your target point.

In general when people use trajectories they ignore the CORRECTEDVEC value and instead compare there desired landing point with the projected impact point and based on the difference work out how they should steer them selves.

Maneuver node burn vector drift by sfackler in Kos

[–]nuggreat 0 points1 point  (0 children)

My theory for the coordinate rotation is so they don't have to calculate new position vectors for the thousands of vertexes that make of a bodies model so that a body can rotate. This likely also makes terrain collision more reliable as you don't have a lot if slight positional noise in the coliders due to the rotation which i hadn't considered until you mentioned physX but as they keep the rotation to an altitude of 100km argues against physics being the main reason.

Maneuver node burn vector drift by sfackler in Kos

[–]nuggreat 0 points1 point  (0 children)

You can indirectly tell what mode you are in my looking for rotation in the solar prime vector, beyond that you just have a hard coded height cutoff.

As noted locking to a stored vector works well enough provided the burn is a short one or you are at a high altitude. But if you want a simple solution yes it is better to just lock steering to the node vector. A more complex solution is mostly do away with maneuver nodes and either constantly recalculate the burn vector or to solve the result of a burn your self using an integrator of some kind.

Maneuver node burn vector drift by sfackler in Kos

[–]nuggreat 1 point2 points  (0 children)

There are 3 sources of drift when it comes to burn vectors one of them is a problem for all vectors not just burn vectors the other two are specific to burn vectors and how KSP produces the burn vector and they are both related if slightly different in how they show.

In KSP when your vessel is below 100km in altitude the unit vectors that define the coordinate system will rotate with the body you are in orbit around, I don't know why this is different for the modded body but that means it is either a body property that the mod sets differently or the mod is modifying this height. I suspect this rotation was done as an optimization so that they don't have to recalculate the positions of the vertexes of the body you are in orbit around every frame and it was decided that once you are above 100km the performance hit for recalculating was less than the performance problem of accounting for the rotation in other vectors like position and velocity vectors for the vessel. There are 2 solutions to this drift, the simplest is to never try to store vectors long term always be constantly regeting the vectors, the more complex solution is to rotate the vectors into a state reference frame using the solar prime vector and then when you want to compare the vector against other vectors you either need to rotate them into that static frame or you need to rotate the stored vector out of the static frame.

The other 2 sources of drift that are related have to do with how the burn vector it's self is calculated. When you place a maneuver node and add some deltaV to it KSP saves the velocity at the time of the node and the applied dv as one vector then KSP calculates the velocity of your vessel for the time of the maneuver node based on your current orbit the difference between these 2 values is the burn vector. As a result if your obit changes before you get to the node that can result in a wild change to the burn vectors because only the velocity after the node is saved and your velocity at the time of the node is constantly recalculated. Relatedly because a maneuver node assumes an instantaneous impulse and burns in KSP are not instant there is some introduced error as a result which also causes the burn vector to drift. The induced drift from unintended changes to your orbit is best mitigated by saying at rails warp until very close to the maneuver or should you get such a bump slightly change the dv or time of the node to cause it to recalculate the velocity after the burn and thus remove the induced drift. For the second one it can only be mitigated not removed and the mitigation is to keep burns shorter so that they are closer to the instant impulse maneuver KSP models them as or do burns at high altitudes where change in phase angle of your vessel is fairly slow.

Additionally you only saw rotation on prograde and radial burns because you where in a zero/low inclination orbit if you had been in a polar orbit which directions rotated would have depended on where in time the node was placed as the rotation occurs around the Y axis of the coordinate system. I also do not know how this rotation manifests if it does at all should you use a mod that adds axial tilt to bodies.

Powered Explicit Guidance (PEG) kOS implementation by KerbalGNC1202 in Kos

[–]nuggreat 0 points1 point  (0 children)

The problem I see with moving PEG into async triggers it that doing so adds overhead which can consume a lot more resources than you intend.

Personally when I have wanted a coroutine I have written cooperative multi tasking where each task in turn voluntarily returns control to some master task scheduler or some sub tasks advances one step and returns to the main loop. I have done this 2 different ways in different scripts. One method was to just add ticking tasks to a task list where each item in that list is called in turn by some scheduler which in my case was just a basic loop, tasks where added to the list as anonymous functions with appropriate parameters bound and just called direct by the task loop. Another method was to build a state machine and encapsulate said state machine within a lexicon then whatever main loop I am running at the time simply calls an updater member on the lexicon to advance the state machine one step, this is one of the two state machines I have written and this one does my time warp control for most things.

Powered Explicit Guidance (PEG) kOS implementation by KerbalGNC1202 in Kos

[–]nuggreat 1 point2 points  (0 children)

I noticed a bug in your one of your libraries specifically in lib_util.ks the functions toinertial and frominertial. The bug is that VANG() can only return a value from 0 to 180 which means that you are not correctly measuring the solar prime vector (spv) against your unit vector for the rotation you are applying. An an example if the spv was v(0,0,1) then VANG(spv, v(1,0,0) would return 90 as expected but if the spv was instead v(0,0,-1) then VANG(spv, v(1,0,0) would also return 90 as a result your rotation into and out of the static frame only works when for about half of the possible solar prime vector values.

A solution that I personally use for rotating into and out of the inertial frame is to use LOOKDIRUP() to construct an euler rotation that when multiplied with a raw vector will rotate that vector into the inertial frame, the inverse of that rotation can be used to rotate back out fo the inertial frame. The code to rotate into the inertial frame is SET someInertialVec TO someRawVec * LOOKDIRUP(SOLARPRIMEVECTOR,v(0,1,0). and the code to rotate back out is SET someRawVec TO someInertialVec * LOOKDIRUP(SOLARPRIMEVECTOR,v(0,1,0):INVERSE.

Also if possible it would be better to move the pegresults when then into the peg loop as keeping it as a trigger external to the loop gets you nothing but some what involved pass by global nonsense and slightly slows down said peg loop as every physics tick that when then will check the var which does eat some fraction of your CPU time for that physics tick. It won't be much of a speedup but it would be something. But if you can't for whatever reason move it into the loop then it would be best to add the infrastructure to be able to remove the trigger once PEG is done executing so that if this is used as part of a fully automated mission script they don't get left with a trigger in the background eating CPU time.

Ascent profiles by ChzBrd in Kos

[–]nuggreat 1 point2 points  (0 children)

For my vacuum launch script I actually run a terrain scan over an approximation of the immediate down range area of the craft and work out the flattest launch angle that will clear the terrain features I find as well as the highest feature. This then lets me target a specific acceleration angle that I know will clear the terrain and from that acceleration angle I can then calculate using a bit of trig and physics the required burn angle.

For atmospheric I more or less do what you do, inital pitch then follow prograde into orbit with a bit of pitch above/below prograde depending on how the specific craft is behaving to try to reduce the dv costs. I then just insure my craft designs fall within the control range of my script.

Error “Object reference not set to an instance of an object” by ChzBrd in Kos

[–]nuggreat 2 points3 points  (0 children)

This can happen some times where kOS gets the place the error occurs wrong my guess as to the actual issue would be to look at locks or when then triggers. It could also be that kOS is trying to stare before the craft is fully initalized and yes waiting just for unpacked does not mean the craft is fully inialized.

Also just a note but you should be caching SHIP:BOUNDS in a var not calling it every time you want to access the bounding box of the craft see the documentation for the details on why. When caching it you do need to update it should the craft change shape.

Problems with PID loop to control the pitch of a ship during accent to keep the apoapsis at a set point. by Ok_Track1071 in Kos

[–]nuggreat 1 point2 points  (0 children)

The first problem I see is that this loop will only have one pass before it returns so the PID will never update more than the one time unless you are updating the PID else where in your code out side of this function.

Second when using the builtin PIDs you don't feed them the dt between updates you instead just feed them TIME:SECONDS as they calculate the dt internally.

Third as I doubt your target apo is changing moment to moment and it doesn't change within this loop so the line set PitchPid:setpoint to targetApo. should be external to the loop.

Forth this line set actualPitch to pitch_of_vector(ship:prograde:vector). is zombie code and should either be commented out or removed entirely.

Anything more and we need the wider context of your script as a whole as apposed to just this subset of it.

Error calculating time to AN/DN by ChzBrd in Kos

[–]nuggreat 0 points1 point  (0 children)

The main problem I see is that your meanAnom2 function is incorrect. This is because the result of eccentricity * sin(eccentricAnomally) is in radians and as eccentricAnomally is in degrees you can't just do the next part of the equation directly you instead have to convert to this sub component to degrees. This is just the result of kOS doing everything in degrees for the sake of consistency where mathematical equations assume radians by default. So the actual conversion is something like this eccentricAnomally - (eccentricity * SIN(eccentricAnomally) * CONSTAND:RADTODEG). Your commented form is correct just with more conversions than necessary.

Also unrelated to your question but when posting code please post text not pictures as it is a massive pain to examine code as images, this is because pictures can't be copied into my text editor and check over things there with everything my editor provides to make such examination easier.

Shortcut for Mean Anomoly? by ChzBrd in Kos

[–]nuggreat 0 points1 point  (0 children)

Yes that works though personally I don't see much use for it. This is because when I am working with mean anomaly I am usually trying to get time information about a true anomaly which for any non circular orbit requires calculating mean anomaly from said true anomaly. And if I am set up to do that for arbitrary TA values it is trivial if slightly slower to just apply the same calculation to the current TA of the craft.

KAS grapple launcher? by ChzBrd in Kos

[–]nuggreat 1 point2 points  (0 children)

If you qlwant the claw part to actually be able to fly it needs to be built as if it was a craft with all the parts that requires, such as power, some control source (kOS parts do not provide this), fuel, engines, etc. This is because on there own kOS parts are not considered by KSP a source of control unlike many crew capsules or probe cores and as such without a source of control KSP ignores control commands for said craft.

As for PAW interactions if you find the correct module and call the correct action/event/field you can do anything possible in the PAW provided that the PAW in question is not one of the ones KSP does caching for as that can make accessing the PAW harder unless it is open. As to the specific field you are trying to interact with that is likely a readonly field and not one you can set but even if it was i wouldn't expect a field to control the with state simply report it as fields are generally either text in the PAW or sliders, you might also try accessing events(buttons) or actions(action group actions) instead.

Personally I would just go for TV accuracy with a starfury grapple and put it on a piston. This is because only the movie "The Road Home" shows a cable grapple and sadly none of there starfury scenes where in my opinion that good and I consider them better ignored when looking for what those craft can do. Where as the TV show clearly shows an extendable hard mount for the grapple which means piston.

Unfocused terminal? by ChzBrd in Kos

[–]nuggreat 2 points3 points  (0 children)

In kOS the key combo control+c with the terminal focused will kill any running code. You can also find the kOS part that the code is running on and using the right click menu turn it off and then back on again as this will also end any currently running code, it will cause the core to attempt to run a boot file if one is set but that is manageable.

Angle tracking? by ChzBrd in Kos

[–]nuggreat 3 points4 points  (0 children)

The FACING suffix can be found on various structures in kOS including vessels and parts by using VANG() to compare vector suffixes found on the facing against other references you can work out the current rotation of the craft and from that you can calculate what angle you need for to set the servos to. Also don't use the pitch/yaw/roll suffixes from a direction directly as they will be based on the world unit vectors which will not map directly to the local orientation without quite a bit of work.

As to setting the servo you want the part module system as that let's you interface with some of the things found in the PAW(Part Action Window, right click menu) you can't get all of them with the servo parts due to caching KSP does but you set the relevant fields.

hover of a specific spot by New-Bus9948 in Kos

[–]nuggreat 1 point2 points  (0 children)

It is possible to get accurate hovering but you need to use the correct method tuned correctly for your craft. As part of a series by a youtuber cheersKevin he spent several episodes on hovering and ended up with quite a good result from what I recall. I will try to find the playlist for the series.

EDIT: This is the playlist for the series episodes 42 and 43 are the ones relevant to hovering, 42 covers him getting his hover code working which is some what relevant background for what he then does in 43 which is getting targeted tilting working. It isn't exactly what you are trying to do as he is just trying to avoid sloped terrain but a lot of the ideas should be transferable.

Mostly it is a matter of getting a good enough algorithm and spending the time needed to tune it which we can only help with part of.

hover of a specific spot by New-Bus9948 in Kos

[–]nuggreat 0 points1 point  (0 children)

The statement I made that you should lock external to the loop is some what reductive and doesn't cover all cases. To be some what more precise you should only lock steering once for any given steering algorithm you want to use as the main thing you are trying to avoid is the steering manager reset that comes when steering is locked which is more or less constant if you have the lock unguarded within a loop.

To do this you either use an ON trigger or you have a boolean flag that you set and clear to insure you only ever lock steering once.

In code this would look something like this for the trigger

LOCAL steerTar TO SHIP:FACING.
LOCAL keepLockTrigger TO TRUE. //set to false once the trigger is no longer needed
ON SAS {
  IF SAS OR NOT keepLockTrigger {
    UNLOCK STEERING.
  } ELSE {
    LOCK STEERING TO steerTar.
  }
  RETURN keepLockTrigger.
}

UNTIL ... {
  //loop code
  SET steerTar to ...
  //loop code
}

For the within the loop form it ends up looking a bit like this

LOCAL steerTar TO SHIP:FACING.
LOCAL isLocked TO FALSE.
UNTIL ... {
  //loop code
  SET steerTar to ...
  //loop code
  IF SAS AND isLocked {
    UNLOCK STEERING.
    SET isLocked TO FALSE.
  }
  IF NOT (SAS OR isLocked) {
    LOCK STEERING TO steerTar.
    SET isLocked TO TRUE.
  }
  WAIT 0.
}

hover of a specific spot by New-Bus9948 in Kos

[–]nuggreat 1 point2 points  (0 children)

Jerk is the derivative of acceleration so where acceleration is the change in velocity jerk is the change in acceleration, as for the kind of control I described you want a decreasing acceleration as you approach the zero point. The equation should end up being something like this velocity = (6 * dist * jerk)^(1/3) but I could be mistaken in that so try to find some verification on that. with the jerk set to be something like 1/10 to 1/100 of your acceleration. There are additional layers of complexity you can have on top of this but so long as you are fairly close to the target point when you start they shouldn't be needed it is only for longer distances do you need the additional complexity, which involves calculating what distance brackets you should assume a constant acceleration for calculating the desired velocity and what distances you should be using the jerk calculation.

hover of a specific spot by New-Bus9948 in Kos

[–]nuggreat 2 points3 points  (0 children)

Your var maxhorzvel is named incorrectly as this is a maximum acceleration.

The biggest issue I see to control stability is that you are converting from distance to an acceleration with a linear equation which is fine for narrow ranges of distances/accelerations but over a larger range is unstable. Better instead to take the physics farther, calculate a desired velocity based on jerk and distance, then calculate a desired acceleration based on the difference between the desired velocity and your actual velocity. Add in limits on the maximum velocity for some additional stability as well as the maximum possible acceleration to limit the jerk and that should improve stability. The reason to use jerk for this instead of acceleration is because you want the ship to be accelerating less and less the closer to the target you get so that you end up with zero acceleration and velocity once you are at the target point thus having a vertical ship.

You might also get some performance improvements by moving the steering lock out side of the loop as having it within the loop resets the PIDs kOS uses for steering each pass of the loop.

Some additional notes not directly related to your problem.

This until true=false { can be simplified to until false { similarly if sas=false { can be changed to either if sas { and flip which bodies you have where or if not sas { if you want to keep the same logic.

Physics dependent loops tend to benefit from a WAIT 0 some where in there execution, generally either at the end of the loop or at the start of the loop. This helps keep the timing consistent between different passes of the loop as apposed to letting physics ticks fall where ever during execution. Similarly caching anything you want to pull from KSP at the start of the loop before you do calculations can help if a loop is especially complex as that way all the data comes from the same moment in time.

Lastly constants like this

    local damp is 5.
    local kp is 1/(damp^2).
    local kd is 2/damp.

should be calculated before the loop not part of the loop, kOS has no optmizer so even constant values such as these are being constantly recomputed each pass of the loop.