Jump to content

[1.3] kOS Scriptable Autopilot System v1.1.3.0


erendrake

Recommended Posts

Is there any way to store a variable on the ship? I remember beginning to use this mod a few ages ago, but the fact all the variables were "global" put me off. It does interest me very much as a mod, tho.

If not currently possible, may I suggest some writable hooks like SHIP:CUSTOMVALUES:WHATEVER be implemented?

Link to comment
Share on other sites

Is there any way to store a variable on the ship? I remember beginning to use this mod a few ages ago, but the fact all the variables were "global" put me off. It does interest me very much as a mod, tho.

If not currently possible, may I suggest some writable hooks like SHIP:CUSTOMVALUES:WHATEVER be implemented?

Variables are global to all code running on the same kOS processor, but they aren't shared between ships or even between multiple processors on the same ship. You don't need any kind of ship-specific storage.

Link to comment
Share on other sites

Variables are global to all code running on the same kOS processor, but they aren't shared between ships or even between multiple processors on the same ship. You don't need any kind of ship-specific storage.

However, the system for remembering the state of a variable in a saved game and bringing it back (or even bringing it back after leaving the scene and coming back to it), has some problems right now. The original system is ancient and was designed for when it only had to deal with integers, floats, and strings. A lot of the newer data types don't "serialize" properly into the savegame file.

At the moment, you need to either keep the entire run contained in one 'scene', or make it so that nothing it remembers is important when leaving the scene, so it can re-run code again from scratch and recalculate everything when you return to the scene.

- - - Updated - - -

Is there any way to store a variable on the ship? I remember beginning to use this mod a few ages ago, but the fact all the variables were "global" put me off. It does interest me very much as a mod, tho.

If not currently possible, may I suggest some writable hooks like SHIP:CUSTOMVALUES:WHATEVER be implemented?

If you thought all variables were global to the *entire game*, then you misunderstand what's happening. They're only global in the sense that if you run a script on the vessel, and then that script in turn contains a command to run another script nested inside itself, the second script will be working in the same variable namespace as the first script was.

It does not mean that if vessel A is running a program that its variables will be seen by vessel B. THAT is kept separate. There is one variable namespace per Vessel. Actually, it's even more separate than that. There's one variable namespace per CPU on the vessel. If you attach two CX-4151 Comptronix parts to the same vessel, each one will have its own separate namespace.

Link to comment
Share on other sites

I was thinking that kOS has hit a new maturity point where it's probably worth it to have another Challenge contest like the ancient one from over a year ago. That contest really helped spur kOS on because it made people try areas the mod wasn't so good at, which helped explore the edges of what it could do, and helped figure out what things would be helpful to add to it. I had a lot of fun back then being a participant in it, although some things were a lot harder than they needed to be.

Things have gotten a lot more mature and I think it's time for a new challenge contest.

I had an idea myself for a nice one but I don't want to post it for the following reasons:

1: The challenge forum has the rule that you shouldn't make a contest for which you haven't posted a proof of your own ability to succeed at it (i.e. your own entry into your own contest, so to speak). This rule was established because there had been a few cases of people being jerks posting contests they knew cannot be done, designed to trick people into wasting their time trying. They would often say "oh trust me it can be done, I've done it, but I won't show you my solution until you start posting yours", when they know it can't actually be done. The purpose behind the requirement was to prove a minimal entry is possible. It doesn't have to be your best entry, and you can re-enter a second, better scoring entry later on. It's just meant as the proof of concept to prove you're not lying about the challenge being possible.)

2: I decided that I should really recuse myself from participating in any challenge contests about kOS after I became more heavily involved in helping develop it. I've got too much ability to change the mod to make it into what I need it to be ("Oh look the mod is missing a feature I'd need to do this task - so I'll go and add it in and get that feature into the next release, and get the release out in time for my contest entry..."). I've also got too much "inside information", as in "Oh, this feature's not documented that well, but no worries, I'm the one who wrote it, so I know how it works without the docs." I've also got more "lead time' than others do. I can start writing scripts using new features before the new features are publicly mentioned.

It's the combo of #1 and #2 that I think mean I can't really lead a Challenge Contest myself. To lead the contest I need to show my own entry into it. But I don't think I should be entering myself into a challenge.

That being said, this is the idea I had for a potential contest:

kOS Space Station Crew Exchange Challenge

The challenge starts with a sandbox-mode saved game, made available for public download, in which there exists a space station in orbit around Kerbin.

The space station has the following things on it:

  • A port with nametag="Easy Port" - a docking port along the station's main central axis, at one end, clear of obstructions.
  • A port with nametag="Medium Port" - a docking port located not along the station's main axis, at a weird diagonal angle, and aligned askew from its center of mass.
  • A port with nametag="Hard Port" - a docking port similar to "Medium Port", but not only is it at a weird angle and not central, it's located in a dangerous way with breakable solar panel obstacles around, making it likely that you'll break the solar panels if you just try to dock straight at the port clumsily.
  • Crew onboard.

You're allowed to build whatever docking ship you like to dock to the station, but depending on the design of its docking port, it may be worth more or less points. It should have crew space for at least 1 crew. It can have more but it's actually detrimental to your score to do so, as you'll be scored based on least monoprop used, and larger ships are going to use more - you're best to go with just 1 crew capacity.

The challenge is to start from that saved game and attempt to do the following:

  • 1. Launch your craft from KSC to orbit. must be automated by script
  • 2. Rendezvous your craft with the station. must be automated by script
  • 3. Dock your craft to the station without breaking anything (like a solar panel). must be automated by script
  • 4. Exchange 1 crew member between the craft and the station - move one crew out of the craft and one crew into it. You are allowed to do this step manually with the stock crew transfer mouse interface.
  • 5. Undock your craft from from the station. You are allowed to do this step manually with the docking port's right mouse button menu
  • 7. Move your craft away from the station safely without breaking anything (like a solar panel). must be automated by script
  • 8. Return the crew member to Kerbin intact, trying to land close to the KSC if you can. must be automated by script

You are allowed to use the interactive terminal for file and run commands: COPY, SWITCH TO, RUN, etc, at any point during the mission, and doing so will not count as "doing things manually" (thus if you can't fit the entire sequence of scripts on the ship at once, that's fine - you can swap files in and out.). THIS mission is not intended to be a signal-delay challenge mission where you can't type commands. It all takes place within near-Kerbin orbit.

Things that could be used as criteria to affect your score (although I haven't really thought through which of these are more important, and how they should balance against each other, or which of them should be dropped. A good challenge should really only contain about 4-5 scoring criteria. Too much more and it gets messy to track):

  • more points for docking to the harder ports on the station.
  • more points for using a harder docking port on your own ship (one not just easily aimed out the nose of your ship, but one that you have to calculate directions from weirdly, like the harder ones on the station described above).
  • less points the more monopropellant fuel was consumed. Docking with mechjeb can be monopropellant-hungry, and I'd like to think a specialized kOS script can do it better.
  • less points the more torque power the docking craft had (more points for doing it all on RCS). (Yes I know there's a bug about using ships that don't have torque, but there's also a supposed fix donated by github user soulsource that should come out the next time there's a release).
  • less points for more time elapsed (on the gameworld's clock, not the user's time) between start of the savegame's timestamp to the timestamp of the final landing. This will effectively reward people for managing to get a good rendezvous quickly.
  • More points the closer to KSC the landing site was.
  • Reusability ratio: Compare the recovery cost of the amount of your craft that landed on return to the initial cost of it at launch. Better reusability ratios mean better scores. (The purpose of adding this scoring criterion would be to give a boost to the scores of people who managed to do it with an SSTO. SSTO's present harder scripting challenges and should be rewarded for it. This would do so because they're landing the whole ship again and only payed for the fuel.)) (For this to work you probably need the initial save game to be a career mode game so it can calculate funds. I can show you how to set up bogus data to make a career mode game have lots of funds and upgraded buildings. The only reason for making it career-mode would be to turn on KSP's calculation of ship cost so you can perform this scoring.

Again, I don't recommend all the above be used, but they're a clue as to what could go into the scoring criteria.

Is anyone willing to set up a thing like this, and take the lead on it in the forum? (Or, to make it all your own idea, to counterpropose a different challenge). I just like the idea of there being a kOS challenge in the forums. It's been a while and I'm thinking about it. I'm thinking about docking because that's the most recent scripting I was working on.

Edited by Steven Mading
Messed up the list tags and the italics tags
Link to comment
Share on other sites

Why limit the scope to just :GetField? Why not just allow a script to print whatever string it feels like to a PostScreenMessage, regardless of whether it's coming from a :GETFIELD or something else? Just implement it at the basic string level and you get :getfield for free that way, along with all sorts of other stuff.

Hey Steve.

How's this for simple?

I tagged it onto the print function. Just add hud$ to your text and it prints a screen message. < print "hud$Hello World!".

In misc.cs

[Function("print")]
public class FunctionPrint : FunctionBase
{
public override void Execute(SharedObjects shared)
{
string textToPrint = shared.Cpu.PopValue().ToString();
string replacedString = textToPrint.Replace("hud$", "");
shared.Screen.Print(replacedString);
if (textToPrint.StartsWith("hud$"))
{
ScreenMessages.PostScreenMessage( replacedString,3.0f, ScreenMessageStyle.UPPER_CENTER);
}
}

}

Link to comment
Share on other sites

Hey Steve.

How's this for simple?

I tagged it onto the print function. Just add hud$ to your text and it prints a screen message. < print "hud$Hello World!".

I'd prefer just giving people direct control over all the parts of screenmessage - the position, the delay, etc.

Maybe as a function:

hudtext( "Hello World", "top", 5). // top position, for 5 seconds.

- - - Updated - - -

Here's a demo of some docking maneuvering:

Link to comment
Share on other sites

I was thinking that kOS has hit a new maturity point where it's probably worth it to have another Challenge contest like the ancient one from over a year ago. That contest really helped spur kOS on because it made people try areas the mod wasn't so good at, which helped explore the edges of what it could do, and helped figure out what things would be helpful to add to it. I had a lot of fun back then being a participant in it, although some things were a lot harder than they needed to be.

Things have gotten a lot more mature and I think it's time for a new challenge contest.

I had an idea myself for a nice one but I don't want to post it for the following reasons:

1: The challenge forum has the rule that you shouldn't make a contest for which you haven't posted a proof of your own ability to succeed at it (i.e. your own entry into your own contest, so to speak). This rule was established because there had been a few cases of people being jerks posting contests they knew cannot be done, designed to trick people into wasting their time trying. They would often say "oh trust me it can be done, I've done it, but I won't show you my solution until you start posting yours", when they know it can't actually be done. The purpose behind the requirement was to prove a minimal entry is possible. It doesn't have to be your best entry, and you can re-enter a second, better scoring entry later on. It's just meant as the proof of concept to prove you're not lying about the challenge being possible.)

2: I decided that I should really recuse myself from participating in any challenge contests about kOS after I became more heavily involved in helping develop it. I've got too much ability to change the mod to make it into what I need it to be ("Oh look the mod is missing a feature I'd need to do this task - so I'll go and add it in and get that feature into the next release, and get the release out in time for my contest entry..."). I've also got too much "inside information", as in "Oh, this feature's not documented that well, but no worries, I'm the one who wrote it, so I know how it works without the docs." I've also got more "lead time' than others do. I can start writing scripts using new features before the new features are publicly mentioned.

It's the combo of #1 and #2 that I think mean I can't really lead a Challenge Contest myself. To lead the contest I need to show my own entry into it. But I don't think I should be entering myself into a challenge.

That being said, this is the idea I had for a potential contest:

kOS Space Station Crew Exchange Challenge

The challenge starts with a sandbox-mode saved game, made available for public download, in which there exists a space station in orbit around Kerbin.

The space station has the following things on it:

  • A port with nametag="Easy Port" - a docking port along the station's main central axis, at one end, clear of obstructions.
  • A port with nametag="Medium Port" - a docking port located not along the station's main axis, at a weird diagonal angle, and aligned askew from its center of mass.
  • A port with nametag="Hard Port" - a docking port similar to "Medium Port", but not only is it at a weird angle and not central, it's located in a dangerous way with breakable solar panel obstacles around, making it likely that you'll break the solar panels if you just try to dock straight at the port clumsily.
  • Crew onboard.

You're allowed to build whatever docking ship you like to dock to the station, but depending on the design of its docking port, it may be worth more or less points. It should have crew space for at least 1 crew. It can have more but it's actually detrimental to your score to do so, as you'll be scored based on least monoprop used, and larger ships are going to use more - you're best to go with just 1 crew capacity.

The challenge is to start from that saved game and attempt to do the following:

  • 1. Launch your craft from KSC to orbit. must be automated by script
  • 2. Rendezvous your craft with the station. must be automated by script
  • 3. Dock your craft to the station without breaking anything (like a solar panel). must be automated by script
  • 4. Exchange 1 crew member between the craft and the station - move one crew out of the craft and one crew into it. You are allowed to do this step manually with the stock crew transfer mouse interface.
  • 5. Undock your craft from from the station. You are allowed to do this step manually with the docking port's right mouse button menu
  • 7. Move your craft away from the station safely without breaking anything (like a solar panel). must be automated by script
  • 8. Return the crew member to Kerbin intact, trying to land close to the KSC if you can. must be automated by script

You are allowed to use the interactive terminal for file and run commands: COPY, SWITCH TO, RUN, etc, at any point during the mission, and doing so will not count as "doing things manually" (thus if you can't fit the entire sequence of scripts on the ship at once, that's fine - you can swap files in and out.). THIS mission is not intended to be a signal-delay challenge mission where you can't type commands. It all takes place within near-Kerbin orbit.

Things that could be used as criteria to affect your score (although I haven't really thought through which of these are more important, and how they should balance against each other, or which of them should be dropped. A good challenge should really only contain about 4-5 scoring criteria. Too much more and it gets messy to track):

  • more points for docking to the harder ports on the station.
  • more points for using a harder docking port on your own ship (one not just easily aimed out the nose of your ship, but one that you have to calculate directions from weirdly, like the harder ones on the station described above).
  • less points the more monopropellant fuel was consumed. Docking with mechjeb can be monopropellant-hungry, and I'd like to think a specialized kOS script can do it better.
  • less points the more torque power the docking craft had (more points for doing it all on RCS). (Yes I know there's a bug about using ships that don't have torque, but there's also a supposed fix donated by github user soulsource that should come out the next time there's a release).
  • less points for more time elapsed (on the gameworld's clock, not the user's time) between start of the savegame's timestamp to the timestamp of the final landing. This will effectively reward people for managing to get a good rendezvous quickly.
  • More points the closer to KSC the landing site was.
  • Reusability ratio: Compare the recovery cost of the amount of your craft that landed on return to the initial cost of it at launch. Better reusability ratios mean better scores. (The purpose of adding this scoring criterion would be to give a boost to the scores of people who managed to do it with an SSTO. SSTO's present harder scripting challenges and should be rewarded for it. This would do so because they're landing the whole ship again and only payed for the fuel.)) (For this to work you probably need the initial save game to be a career mode game so it can calculate funds. I can show you how to set up bogus data to make a career mode game have lots of funds and upgraded buildings. The only reason for making it career-mode would be to turn on KSP's calculation of ship cost so you can perform this scoring.

Again, I don't recommend all the above be used, but they're a clue as to what could go into the scoring criteria.

Is anyone willing to set up a thing like this, and take the lead on it in the forum? (Or, to make it all your own idea, to counterpropose a different challenge). I just like the idea of there being a kOS challenge in the forums. It's been a while and I'm thinking about it. I'm thinking about docking because that's the most recent scripting I was working on.

I like the idea of this, especially since it's more or less what I've been trying to do (my difficulty is time, with my family at home and work, I have little time to play games). I think it'd be worth making a standard "station" craft file that anyone participates can download, perhaps even a save file with the station already in orbit. It would help standardize the challenge. If someone takes this up, please PM me the link to your challenge, and I'll place it as a sticky on the subreddit for kos as well!

Also, thanks very much for the tutorial! At least I know it's possible to do what I've been trying to do. I'll see if I can get it before you make your longer tutorial. Thanks again!

Link to comment
Share on other sites

perhaps even a save file with the station already in orbit. It would help standardize the challenge.

I realize that what I posted was a giant wall of text that it was easy to miss stuff in, but that actually is what I was suggesting doing.

(The bit where it says: The challenge starts with a sandbox-mode saved game, made available for public download, in which there exists a space station in orbit around Kerbin.)

(Later on I mentioned that if you want percentage of cost returned back (for SSTOs) to be part of the challenge scoring it would have to be a career-mode saved game instead of sandbox, just because KSP won't show you the amount of recovery refund in sandbox mode.)

Also, thanks very much for the tutorial! At least I know it's possible to do what I've been trying to do. I'll see if I can get it before you make your longer tutorial. Thanks again!

That's sort of why I split it into two parts. I'm unsure whether or not I *should* show the script yet if there might be a contest going on, and I'm still waffling on that.

Link to comment
Share on other sites

I realize that what I posted was a giant wall of text that it was easy to miss stuff in, but that actually is what I was suggesting doing.

(The bit where it says: The challenge starts with a sandbox-mode saved game, made available for public download, in which there exists a space station in orbit around Kerbin.)

(Later on I mentioned that if you want percentage of cost returned back (for SSTOs) to be part of the challenge scoring it would have to be a career-mode saved game instead of sandbox, just because KSP won't show you the amount of recovery refund in sandbox mode.)

That's sort of why I split it into two parts. I'm unsure whether or not I *should* show the script yet if there might be a contest going on, and I'm still waffling on that.

I must come off as as an idiot sometimes...

I've only one question about your script. Are you using raw controls for rotation, or is it possible to figure out the correct vectors to use cooked controls? As in, you're able to lock steering and/or lookdirup to rotate the ship to place the port in the correct orientation?

Link to comment
Share on other sites

I must come off as as an idiot sometimes...

I've only one question about your script. Are you using raw controls for rotation, or is it possible to figure out the correct vectors to use cooked controls? As in, you're able to lock steering and/or lookdirup to rotate the ship to place the port in the correct orientation?

In principle it should be possible to lock steering, because with a lookat and a lookup vector (the blue arrows in the second half of that video), you can construct a Direction and LOCK STEERING to that. My only reason for not doing that was that I was *also* setting myself the task of testing out the raw controls and wanted to get them working, so I do everything with SHIP:CONTROL. I do think that LOCK STEERING for the rotation, combined with raw controls for the translation, should be a viable tactic.\

Incidentally, before I added LOOKDIRUP(v1,v2) as a function, it wouldn't have been a viable tactic because you could only have controlled the aim of the central axis of your ship with LOCK STEERING, and in order to put your own ship's offcentered port where you want it, you need to put the roll just how you want it too. That may have also influenced my decision. I was writing the script *while* adding the new Direction methods, and LOOKDIRUP wasn't there yet when I started. I added it largely because of the deficiency of the system I found while trying out this task.

Edited by Steven Mading
Link to comment
Share on other sites

...is it possible to figure out the correct vectors to use cooked controls? As in, you're able to lock steering and/or lookdirup to rotate the ship to place the port in the correct orientation?

Be aware that there is currently a bug with locked steering for craft when the "control from" part is not aligned with the root parts original axis, or possibly triggered by docking, or something. It's still unclear. The point is, cooked controls can be used for this, and I've done it, but you'll probably run into problems with docking ports that aren't on the nose of the ship, depending on how you write the code. As a result, I switched my docking code over to raw controls.

Link to comment
Share on other sites

"control from" part is not aligned with the root parts original axis [...] you'll probably run into problems with docking ports that aren't on the nose of the ship,

This is true and how I worked around it in my script from the video was this: I don't do a "control from" my docking port. Instead I calculate which rotation Direction goes from ship's control orientation to my docking port's orientation. Once I know that rotational offset, I can use it to point my nose rotated the opposite way to that without using "control from here". (In other words, if my docking port is rotated 45 degrees yawed from my control orientation, then when I discover the orientation I want my docking port in, I should point my nose -45 degrees yawed from that. The new Direction suffixes and constructors make this possible.)

- - - Updated - - -

Can I operate KAS winches with a script? Or, does anyone have a script for a sky crane?

I assume KAS is a mod of some sort? If so, then the answer is most likely yes, because kOS now allows you to generically access many of the things other mods enable you to do. Basically, if it appears on the rightclick menu of a part, or is a thing you're allowed to assign into an action group, then kOS should be able to access it in theory. But you have to jump through a few hoops to do it.. Start here for reading how:

http://ksp-kos.github.io/KOS_DOC/general/parts_and_partmodules.html

Note, there's a bug in those docs I didn't fix yet: At one point the docs say this:


IF somevessel:PARTSDUBBED("my favorite engine"):LENGTH == 0 {
PRINT "There is no part named 'my favorite engine'.".
}.

And he double-equals "==" is wrong for kerboscript syntax. It should be a single-equals "=",

Edited by Steven Mading
Link to comment
Share on other sites

This is true and how I worked around it in my script from the video was this: I don't do a "control from" my docking port. Instead I calculate which rotation Direction goes from ship's control orientation to my docking port's orientation. Once I know that rotational offset, I can use it to point my nose rotated the opposite way to that without using "control from here". (In other words, if my docking port is rotated 45 degrees yawed from my control orientation, then when I discover the orientation I want my docking port in, I should point my nose -45 degrees yawed from that. The new Direction suffixes and constructors make this possible.)

In your video, are the offsets for the different docking ports hardcoded, or is your script able to calculate the offset and make adjustments on its own? I'm assuming your script calculates it, as each port is it a wildly different point.

Link to comment
Share on other sites

In your video, are the offsets for the different docking ports hardcoded, or is your script able to calculate the offset and make adjustments on its own? I'm assuming your script calculates it, as each port is it a wildly different point.

At one point I do the following up front (before the main loop starts). At this point, myPort has already been selected to be the Part for the port, picked by using SHIP:PARTSDUBBED("whatever") where "whatever" is the name you see me typing into the nametag for the "this" ship (rather than for the "other" ship).


// Find axis of rotation, and angle around that axis, to rotate from my ship:facing to my myPort:PORTFACING.

set rotAngle to VANG( SHIP:FACING:VECTOR, myPort:PORTFACING:VECTOR ).
set rotAxis to VCRS( SHIP:FACING:VECTOR, myPort:PORTFACING:VECTOR ).
set rotAxis to rotAxis:NORMALIZED.

// Splitting the rotAxis into its 3 component parts, in a reference frame that is oriented
// to match my ship:facing:
set rotAxisX to VDOT( rotAxis, SHIP:FACING:STARVECTOR ).
set rotAxisY to VDOT( rotAxis, SHIP:FACING:TOPVECTOR ).
set rotAxisZ to VDOT( rotAxis, SHIP:FACING:FOREVECTOR ).

// Then, further down, constantly being updated in my loop, I do this to get the information about the target port:


set otherPortRot to otherPort:PORTFACING.
set otherPortInverseRot to ANGLEAXIS(180,otherPortRot:TOPVECTOR)*otherPort:PORTFACING.

Then further down, I use that to work out what direction I should be steering my nose at to make my port orient with the other port:


set otherPortInverseRotAxis to otherPortInverseRot*V( rotAxisX, rotAxisY, rotAxisZ ).
set myPortRotRelToOther to ANGLEAXIS(-rotAngle,otherPortInverseRotAxis)*otherPortInverseRot.

At this point, you should be able to LOCK STEERING TO myPortRotRelToOther.

Link to comment
Share on other sites

This language can be really annoying. The lack of support only adds to the frustration. (One reason why I really wished it was a more established language like Lua with custom api.)

Anyhow I digress. I was beginning to write some basic launch codes and cant figure out what kOS wants from me. Any help would be greatly appreciated.

Here is the code: http://pastebin.com/Q8gj4cPm

If I remove the second "if" it will auto adjust at +110 m/s but if I add the second it stays at full throttle.

Link to comment
Share on other sites

This language can be really annoying. The lack of support only adds to the frustration. (One reason why I really wished it was a more established language like Lua with custom api.)

Anyhow I digress. I was beginning to write some basic launch codes and cant figure out what kOS wants from me. Any help would be greatly appreciated.

Here is the code: http://pastebin.com/Q8gj4cPm

If I remove the second "if" it will auto adjust at +110 m/s but if I add the second it stays at full throttle.

A dot ends the statement. An else cannot exist as a standalone statement - it needs to be a clause hanging off of an if. Therefore don't have a dot after the closing brace of an if when it's followed by an else, because doing so makes the else hang off on its own as the start of a new statement, and it's not allowed to be the start of a new statement.

(I'm reacting to your comment in the pastebin code about how it called it an error to have an else if where your second if goes.)

I have good news for you, there does already exist an established language in which you could write an autopilot for KSP, and in fact people have done so. The established language is called Csharp. In fact, the proof that this is possible is called mechjeb.

The problem with making it work in Lua is at that point all you're *really* be doing is just making an API bridge to a new language, and at that point you may as well make THAT be the project, rather than autopiloting being the point of it.

People in fact *have* tried doing that sort of thing before, and it ends up having to be done as some sort of bridge between KSP and software that runs as a separate executable *outside* of KSP. There was a project to turn key KSP API calls into RPC calls so you could hook into them from whatever external program running whatever external language you like. I haven't heard much from it lately - probably because the project is a lot bigger than it looks at first and it's easy for a programmer to lose interest in a project when that happens.

The thing that kOS does uniquely is that it tries to run inside the game, using the limitations of the game engine itself, by simulating a virtual machine, running virtual opcodes, that executes a number of virtual machine opcodes per unity update so the programmer making the script is presented with the illusion that it can just run code straight through endlessly without having to make everything it does be a quick hook that exits fast.

While it is in *principle* possible to support other languages that way, doing so for any arbitrary language requires making that virtual machine a heck of a lot more complex than it currently is.

People mistakenly think, for example, that the reason kerboscript doesn't have local variables is because it's hard to add to the syntax. No. It's easy to add to the syntax. What's hard is making the underlying fake machine language more versatile so there's actually something to compile the kerboscript INTO that will do it.

Link to comment
Share on other sites

People mistakenly think, for example, that the reason kerboscript doesn't have local variables is because it's hard to add to the syntax. No. It's easy to add to the syntax. What's hard is making the underlying fake machine language more versatile so there's actually something to compile the kerboscript INTO that will do it.

Not so long ago, I suggested ferram to add another part to FAR mod. Simple placeholder for variables, like maximum roll angle, maximum AoA, pitch damper for example.

Those should be read from variable placeholder and set FAR flight assistance variables by kOS. This is usefull, since there is no general good or bad options since each craft is different. I'm still learning to use kOS, but my first idea, besides IR parts, that kOS will be usefull to make better autopilot than stock SAS or MechJeb.

Problem with both, stock SAS and MechJeb is that those doesn't watch altitude/speed in optimal way and watch craft limitations, so that craft don't fall in dangerous AoA area or have too much speed on too low altitude or too low speed for high altitude. Most important factor is "Q", preasure below wing that produce lift.

Good kOS autopilot should watch that, speed and altitude for subsonic and supersonic speeds, how much "Q" you will need for optimal ascent path that will produce enough lift, because as you gain speed you loose lift at supersonic speeds. You also need to watch AoA and be carefull that craft don't exceed it's limits.

So, idea is if such part exists like variable placeholder, it would be possible to make script that is valid for all crafts, loaded from archive in kOS on launch and that script will use per craft values for limitations from variable placeholder. I have created some realy stable SSTOs, puting those in orbit is realy simple, but a litle tedious. Once I create stable craft, I would like to be relieved from tedious tasks :). kOS comes as solution for that.

I would probably bother you more with that once I start to use kOS more seriously :)

Link to comment
Share on other sites

At one point I do the following up front (before the main loop starts). At this point, myPort has already been selected to be the Part for the port, picked by using SHIP:PARTSDUBBED("whatever") where "whatever" is the name you see me typing into the nametag for the "this" ship (rather than for the "other" ship).


// Find axis of rotation, and angle around that axis, to rotate from my ship:facing to my myPort:PORTFACING.

set rotAngle to VANG( SHIP:FACING:VECTOR, myPort:PORTFACING:VECTOR ).
set rotAxis to VCRS( SHIP:FACING:VECTOR, myPort:PORTFACING:VECTOR ).
set rotAxis to rotAxis:NORMALIZED.

// Splitting the rotAxis into its 3 component parts, in a reference frame that is oriented
// to match my ship:facing:
set rotAxisX to VDOT( rotAxis, SHIP:FACING:STARVECTOR ).
set rotAxisY to VDOT( rotAxis, SHIP:FACING:TOPVECTOR ).
set rotAxisZ to VDOT( rotAxis, SHIP:FACING:FOREVECTOR ).

// Then, further down, constantly being updated in my loop, I do this to get the information about the target port:


set otherPortRot to otherPort:PORTFACING.
set otherPortInverseRot to ANGLEAXIS(180,otherPortRot:TOPVECTOR)*otherPort:PORTFACING.

Then further down, I use that to work out what direction I should be steering my nose at to make my port orient with the other port:


set otherPortInverseRotAxis to otherPortInverseRot*V( rotAxisX, rotAxisY, rotAxisZ ).
set myPortRotRelToOther to ANGLEAXIS(-rotAngle,otherPortInverseRotAxis)*otherPortInverseRot.

At this point, you should be able to LOCK STEERING TO myPortRotRelToOther.

That works perfectly!

The ship points exactly where I want it to, and now I understand better what's going on. I'm going to have to think about this a lot more, but I've got a good idea how I want the movement to to work now. Thanks again!

Link to comment
Share on other sites

Variables are global to all code running on the same kOS processor, but they aren't shared between ships or even between multiple processors on the same ship. You don't need any kind of ship-specific storage.
If you thought all variables were global to the *entire game*, then you misunderstand what's happening.

Yeah, I totally misunderstood it. Thanks guys!

Link to comment
Share on other sites

This language can be really annoying. The lack of support only adds to the frustration.

What kind of support would you like?

* We have a pretty active little community on the forums and on reddit.

* We have put some serious work into the documentation. your exact issue would have been cleared up by reading the page on flow control here http://ksp-kos.github.io/KOS_DOC/language/flow.html#if-else

do you want phone support for this free addon for a game? or a kOS tag on stackoverflow so you can cut and paste scripts someone else wrote?

Link to comment
Share on other sites

Hello. I always wanted to have something like kOS functions available in KSP. Separate files almost make it, but one thing that bothered me for quite a long time was lack of local variables. This makes recursion impossible, and I have to use long names (can't use just "start" as name, because it is very likely used somewhere else too). So, I wrote a "preprocessor" for kOS. The idea is that the computer should have a stack for keeping separate functions' variables separately. This is implemented as a kOS list in boot.ks, which looks as follows:

SET stack_size TO 1000.

PRINT "Initializing stack (size: "+stack_size+" variables).".
SET __STACK TO LIST().
SET __SP TO 0.
UNTIL __SP>=stack_size {
__STACK:ADD(0). // placeholder
SET __SP TO __SP+1.
}
SET __SP TO 0.
PRINT "Done.".

Then, let's say I want the following code, calculating factorial, to work:

//@return varToReturn

DECLARE PARAMETER varNum.

IF varNum<=1{
SET varToReturn TO 1.
}
ELSE{
RUN factorial(varNum-1).
SET varToReturn TO retVal*varNum.
}


PRINT "Factorial of "+varNum+" is "+varToReturn+".".

So I pass it through my preprocessor:

python stack_maker.py < factorial_old.ks > factorial.ks

That gives me a new file, called factorial.ks, with the following contents:

//@return __STACK[__SP]

DECLARE PARAMETER varNum.
SET __STACK[__SP+1] TO varnum.

IF __STACK[__SP+1]<=1{
SET __STACK[__SP] TO 1.
}
ELSE{
SET __SP TO __SP+2.
RUN factorial(__STACK[__SP-1]-1).
SET retval TO __STACK[__SP].
SET __SP TO __SP-2.
SET __STACK[__SP] TO retVal*__STACK[__SP+1].
}

PRINT "Factorial of "+__STACK[__SP+1]+" is "+__STACK[__SP]+".".

Yeah, I know it's ugly, but you won't be looking at this code. You should only edit "source file" - the original one, and then run through the preprocessor again. When you're ready, go to KSP and run the program:

run factorial(5).
Factorial of 1 is 1.
Factorial of 2 is 2.
...
Factorial of 5 is 120.

If anyone wants to use it, here are some design decisions I had to make:

- all variables need to start with the prefix "var" (case doesn't matter) - this is because I am not skilled enough to write a full-scale language parser, which distinguishes between variables and function names, and so on. Also, even if I did that, my preprocessor would change built-in variables, such as "TIME" to stack variables too, which would be a bad thing. As a compromise, I made the user explicitly name variables varStuff (at least it's not kerStuff :P)

- you have to initialize stack before calling any program (just run boot.ks)

- if you want to return something (one variable at most), you have to put the "//@return varStuff" directive on the top of the source.

- if you want to access the returned value, you have to use variable called "retVal". See above for example use.

Link to the preprocessor itself:

https://github.com/akrasuski1/KerbalPreprocessor/tree/master

Note that you have to have Python installed to run it. Thanks for any feedback.

Note to developers: maybe something similar to this can be implemented in the kOS itself? It would definitely be better, because all of the above decisions wouldn't matter - I'm sure you already recognize variables in some way - so the prefix "var" would not be needed. If new syntax was added, "retVal" variable wouldn't be needed too - how about: "SET f TO RUN factorial(5)." ? IDK, it's just an idea.

Edited by akrasuski1
Link to comment
Share on other sites

Note to developers: maybe something similar to this can be implemented in the kOS itself? It would definitely be better, because all of the above decisions wouldn't matter - I'm sure you already recognize variables in some way - so the prefix "var" would not be needed. If new syntax was added, "retVal" variable wouldn't be needed too - how about: "SET f TO RUN factorial(5)." ? IDK, it's just an idea.

The only reasons it hasn't been done already is:

1: free time to implement it

2: we're not too happy with RUN program being the way to de-facto do functions, so we really need to make essentially two systems: local to program and local to function.

3: indecision over whether to implement global functions first, then implement user structures, then turn user structure into user classes by adding functions to them to become methods, or to do it the other way around: implement user structures first, then user methods, then say that all user functions must be class methods.

It really does need something, though, so that indecision is just an excuse delaying things.

Link to comment
Share on other sites

A dot ends the statement. An else cannot exist as a standalone statement - it needs to be a clause hanging off of an if. Therefore don't have a dot after the closing brace of an if when it's followed by an else, because doing so makes the else hang off on its own as the start of a new statement, and it's not allowed to be the start of a new statement.

I removed the "." after the first if statement and added else but I still have the same problem that it wont decrease throttle. If you could post how to properly write it I would really appreciate it! kOS is driving me up the wall. Im sure Im just missing something obvious.

- - - Updated - - -

What kind of support would you like?

* We have a pretty active little community on the forums and on reddit.

* We have put some serious work into the documentation. your exact issue would have been cleared up by reading the page on flow control here http://ksp-kos.github.io/KOS_DOC/language/flow.html#if-else

do you want phone support for this free addon for a game? or a kOS tag on stackoverflow so you can cut and paste scripts someone else wrote?

... Wow someone is salty... What I meant was compared to any of the more widely used languages, kOS does not have the same level of support simply because it is only used for ksp. The only two places I have found to reference would be the official page and the wikia which in several instances have contradicted one another.

TL;DR Calm down dude. Steven helped me out already (thanks, btw Steven). If you are trying to be a troll, then you are laughable. If you aren't, take a freakin chill pill. lol

Edited by HunterForce
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
×
×
  • Create New...