Jump to content

[1.8.x to 1.12.x] kRPC: Control the game using C#, C++, Java, Lua, Python, Ruby, Haskell, C (Arduino)... (v0.5.2, 18th March 2023)


djungelorm

Recommended Posts

Java support, too! :cool: This is going to be fun. Got the connection test script from the tutorials working, and eagerly looking forward to port some badly slow kOS code containing two nested loops (100 steps each or more) to a kRPC client. Behold! so much possibilities! :o

Thumbs up and thanks, this really made my day (and will do for some others coming). Great stuff.

Edited by plonk
running KSP 1.2.2 / kRPC 0.3.8
Link to comment
Share on other sites

@cantab  - I hadn't done anything in Python until I started with KRPC - it's been a GREAT excuse to learn something that's been on my list for ages.   I admit I've still got a lot to learn about the philosophy of it - it turns out Python is half programming language and half religion, apparently? :P  

We've started putting together this resource of examples -  https://github.com/krpc/krpc-library    It's got a lot of room to grow, but in my folder I've got fairly simple approaches to some fairly complicated tasks - you can see how to use a PID controller to manage throttle, then see how that gets applied in a complete ascent script...  or how the exact same PID controller gets used to steer the vessel's RCS thrusters for a totally automated docking, as an example.

If you have questions about anything...  I've found this thread is frequented by smart and helpful people so don't hesitate to ask! 

Link to comment
Share on other sites

Is it possible to get the transformation matrix to convert from one frame to another? Since I ran into issues with singularities in the default KRPC AutoPilot (need to apply forces close to the vertical axis), I've been working on implementing Wie, Weiss, and Araposthathis 1988's quaternion attitude controller, as well as a LQR attitude controller, both of which need the inertia tensor, which comes by default in the vessel frame (which doesn't work very well for attitude control...). I could implement what I need by deriving a rotation matrix from the vessel's pointing angle (since I know the relation between the frame axes), but this is somewhat of a kludge.

Link to comment
Share on other sites

55 minutes ago, artwhaley said:

https://krpc.github.io/krpc/tutorials/reference-frames.html#converting-between-reference-frames      

That link may do what you need?  the space_center service has facilities for converting directions, forces, rotations, and positions from one reference frame to another?

The problem is that I need the entire inertia tensor matrix, which is a not-particularly-nice-in-the-general-case 3x3 matrix. While I could transform the (three) torque vectors to the vessel frame from my guidance frame and back, that's an additional 6 RPC calls per iteration I would rather avoid. If I can get a vessel to guidance frame transformation matrix, then all I have to do is multiply the inertia tensor by the vessel to guidance frame matrix, and then I have an inertia tensor in terms of the guidance frame. 

Since I constructed the guidance frame, and can relate the vessel frame to the guidance frame with a rotation matrix based on the vessel's attitude, it's not an ideal solution (very complicated and application-specific, for one).  

Link to comment
Share on other sites

Ahhh.   I don't believe that is built into the server.   With everything you're trying to accomplish, and your obvious experience in programming...  have you thought about building your own KRPC service for the ingame C# side?   KRPC makes it very easy to tie your own plugin into KRPC - this way you could offload what calculations and controls you wanted to your external script, but also create your own methods server side for items like this that would unduly tax the RPC link?

https://krpc.github.io/krpc/extending.html

has the details on that.   

 

Link to comment
Share on other sites

Hey,

don't know if i can ask this here, but i have done some simple rocket launch scripts. But now in my vacations i want to go a bit further, with classes and maybe a system which is not only responsible for the active_vessel.
Can someone maybe give me some hints, regarding class structure and ideas about an system(you can pm me or something like that)
Really like kRPC :)

Regards
Moritz

Link to comment
Share on other sites

8 hours ago, moritz31 said:

Hey,

don't know if i can ask this here, but i have done some simple rocket launch scripts. But now in my vacations i want to go a bit further, with classes and maybe a system which is not only responsible for the active_vessel.
Can someone maybe give me some hints, regarding class structure and ideas about an system(you can pm me or something like that)
Really like kRPC :)

Regards
Moritz

You can ask anything!   And that's even the sort of thing that will get an answer!  

I'm going to assume you're working in Python?  Classes are handled like any class in python - you define them and then create an instance of them.  To my (rather new to python) mind, they're great for a couple of things - 1, when you have a set of related functions and variables that it makes sense to roll together, and 2 - when you're going to want multiple copies of the same code/variables at the same time.   

As far as more advanced scripts go - Launches are a good place to start.  I know of three fully developed ones - 

The one on the documentation wiki you've probably already found - 

https://krpc.github.io/krpc/tutorials/launch-into-orbit.html

@Kerbart's  which is a GREAT example of how python lets you organize a script into classes and make them all work together (though it's still a bit over my head!)

https://github.com/bart-r-willems/krpc-launch/blob/master/launch.py

and mine - which is more linear and less pythonic, but handles most cases to get you to orbit.  

https://github.com/artwhaley/krpc-library/blob/master/Art_Whaleys_KRPC_Demos/Simple_Launch_Script.py

Link to comment
Share on other sites

11 hours ago, lushr said:

The problem is that I need the entire inertia tensor matrix, which is a not-particularly-nice-in-the-general-case 3x3 matrix. While I could transform the (three) torque vectors to the vessel frame from my guidance frame and back, that's an additional 6 RPC calls per iteration I would rather avoid. If I can get a vessel to guidance frame transformation matrix, then all I have to do is multiply the inertia tensor by the vessel to guidance frame matrix, and then I have an inertia tensor in terms of the guidance frame. 

Since I constructed the guidance frame, and can relate the vessel frame to the guidance frame with a rotation matrix based on the vessel's attitude, it's not an ideal solution (very complicated and application-specific, for one).  

By vessel to guidance frame transformation matrix, I assume you mean just a rotation matrix? I think you could use SpaceCenter.TransformRotation to get the rotation matrix you are after (but as a quaternion) by calling this method with the identity quaternion (0,0,0,1), from = vessel frame, to = guidance frame. And all in one RPC call!

Also, I'd be very interested in hearing about your experiences/code using LQR or Wie, Weiss, and Araposthathis quaternion attitude controllers. The current autopilot uses a PID based controller that I designed with a very limited knowledge of control theory... and it could do with upgrading to something more fancy!

Link to comment
Share on other sites

  • 4 weeks later...

So I'm on Ubuntu 16.04, I've run 'pip install --upgrade krpc' and pip3 as well.  Installed kRPC v0.3.9 from CKAN into a clean KSP 1.3.0 install.  In Python 2, any time I try to get anything from the vessel, I get this:

 

>>> import krpc                           
>>> conn = krpc.connect(name="ssto")      
>>> ship = conn.space_center.active_vessel
>>> print ship.name                                                                          
Traceback (most recent call last):                                                           
  File "<stdin>", line 1, in <module>                                                        
  File "<string>", line 1, in <lambda>                                                       
  File "/usr/local/lib/python2.7/dist-packages/krpc/client.py", line 85, in _invoke          
    service, procedure, args, param_names, param_types, return_type)                         
  File "/usr/local/lib/python2.7/dist-packages/krpc/client.py", line 119, in _build_request  
    request.arguments.add(position=i, value=Encoder.encode(value, typ))                      
  File "/usr/local/lib/python2.7/dist-packages/krpc/encoder.py", line 45, in encode          
    return cls._encode_value(object_id, cls._types.as_type('uint64'))                        
  File "/usr/local/lib/python2.7/dist-packages/krpc/encoder.py", line 87, in _encode_value   
    return getattr(_ValueEncoder, 'encode_' + typ.protobuf_type)(value)                      
  File "/usr/local/lib/python2.7/dist-packages/krpc/encoder.py", line 154, in encode_uint64  
    return cls._encode_varint(value)                                                         
  File "/usr/local/lib/python2.7/dist-packages/krpc/encoder.py", line 123, in _encode_varint
    protobuf_encoder._VarintEncoder()(write, value)                                          
TypeError: EncodeVarint() takes exactly 3 arguments (2 given)                                
>>>                                                                                          

I'm guessing I've got some sort of version mismatch?

 

EDIT: It looks like it's a version mismatch between krpc and protobuf - except that the changelog at https://github.com/krpc/krpc/releases/tag/v0.3.9 says protobuf v3.3.0, I downgraded from 3.4.0 and it still doesn't work. 

 

protobuf function: https://github.com/google/protobuf/blob/master/python/google/protobuf/internal/encoder.py#L375 

 

Edited by lordcirth
Link to comment
Share on other sites

They changed the interface for the encoder function in protobuf version 3.4.0 (unfortunately they don't expose the functionality as a public interface....)

Downgrading to 3.3.0 should fix this. Are you sure you downgraded the package correctly? Maybe try isolating it using a virtualenv?

Link to comment
Share on other sites

  • 2 weeks later...
1 hour ago, Fillipuster said:

First of all, amazing addition to KSP! This is a joy to use.

I'm having trouble understand how I would go about checking if the current game scene is a certain game scene.

How would I do that?

-FP

When writing plugins for KSP, it's HighLogic.LoadedScene which returns GameScenes.Loading or any of values in the table below. IDK if that applies in KPRC though.

LOADING   
LOADINGBUFFER   
MAINMENU   
SETTINGS   
CREDITS   
SPACECENTER   
EDITOR   
FLIGHT   
TRACKSTATION   
PSYSTEM 
Link to comment
Share on other sites

I don't think he's trying to modify the plugin, I think he's trying to make a client...  if I understand right!  

I'm a novice too at c# - mostly learning as I hack at KRPC's server code for various reasons, and I haven't done a c# client yet, but I THINK what you're looking for are the classes in the client.  Now, spaceCenter() is accessed as a method, so you probably would need to use reflection to grab it...  and I hate reflection.   BUTTTTT I think I can get you going without that.

I haven't TESTED this code but it didn't throw errors in visual studio and SEEMS like it would work.   You can explicitly define the type of a KRPC.Client.Connection object, and hold THAT in your user defined class... then access it's spaceCenter method when you need to.  A quick example would be - 

                KRPC.Client.Connection conn = connection;
                KRPC.Client.Services.SpaceCenter.Vessel vessel = conn.SpaceCenter().ActiveVessel;

 

And I also explicitly defined the type for a vessel.   There...  may WELL be a way to explicitly define the type for a spaceCenter object as well... but my five minutes of poking through the autocomplete suggestions didn't show it to me, and this SHOULD get you going until smarter people chime in and make it easier for you.

Link to comment
Share on other sites

Thanks djungelorm for this great mod!

I used it for learning my first programming language (Java). I created an library that could be seen as an extension to yours. Because this is the first real software I have created, it could be that it is an over engineered clusterlove, but its working, which is nice. If someone wants to try it -> here is the link to the source code and precomiled libraries and executables.

It basically is an "autopilot" that can launch your vessel into an desired orbit around the planet. It also can be used as a library for other projects providing methods for getting the deltaV of any given stage, saving the current orbit of the vessel, automatic staging, formulas for calculating transfers, the mass, parts, burntime, and switching between true, mean and ecc anomaly and a lot more. 

For me it was just about testing what I could do, but in the end it's gotten bigger and bigger. 

If anybody has improvements or tips for me how I can improve my coding skills your feedback will be deeply appreciated!!!

Link to comment
Share on other sites

Thanks for the suggestion @TheRagingIrishman, I worked around it by saving a reference to the active vessel instead of the SpaceCenter.

 

Now, I've run in to another conundrum. I'm wanting to reference the latest 3.9 kRPC dll in a Unity project, but I'm having trouble. Supposedly, it's a straight forward procedure to add external dlls, you simply drag-n-drop them. The problem arises with the fact that kRPC 3.9 uses .NET 4, which is not supported by Unity. I'd love if there was a way to work around this, hence me writing a reply to this thread. Can you somehow "downgrade" to .NET3.5 (which Unity supports)? Can you somehow make Unity eat the kRPC3.9 even though it's .NET4?

Any input is much appreciated :D

I figured it out myself. In case anyone is interested in adding kRPC to a Unity project, do the following:

1. Get the kRPC client dll from here: https://github.com/krpc/krpc/releases/download/v0.3.9/krpc-csharp-0.3.9.zip

2. Unpack and place the dll file in the Unity project.

3. Change the build settings by going to Files->Build Settings->Player Settings and changing Scripting Runtime Version to .NET4.x.

4. Simply use kRPC in Unity scripts like you would any other C# project.

-FP

Edited by Fillipuster
Found Solution
Link to comment
Share on other sites

On 03/09/2017 at 11:22 AM, Fillipuster said:

First of all, amazing addition to KSP! This is a joy to use.

I'm having trouble understand how I would go about checking if the current game scene is a certain game scene.

How would I do that?

-FP

You can get this from a client script by calling KRPC.CurrentGameScene (http://krpc.github.io/krpc/csharp/api/krpc.html#property-KRPC.Client.Services.KRPC.KRPC.CurrentGameScene)

For example, in python:

import krpc
conn = krpc.connect()
print conn.krpc.current_game_scene

Also, it returns an enum (see the docs at the link above for all the possible values)

Link to comment
Share on other sites

5 minutes ago, djungelorm said:

You can get this from a client script by calling KRPC.CurrentGameScene (http://krpc.github.io/krpc/csharp/api/krpc.html#property-KRPC.Client.Services.KRPC.KRPC.CurrentGameScene)

For example, in python:


import krpc
conn = krpc.connect()
print conn.krpc.current_game_scene

Also, it returns an enum (see the docs at the link above for all the possible values)

Ah, nice! Thanks man.

Now that I see you're online, may I just compliment you on kRPC. It's a complete game-changer for simpit/physical control panel makers! Without kRPC, me and my uncle wouldn't be able to make the board we are making right now.

Thank you!

Link to comment
Share on other sites

My pleasure :D Glad you're enjoying it!!!

Regarding .NET 3.5 support, I've actually implemented this for the upcoming v0.3.10 but haven't released it yet. If you want to try it out now you can use this pre-release version:  https://krpc.s3.amazonaws.com/deploy/master/966.1/krpc-0.3.10-58-gf0c66fe.zip

If you extract that archive, then look in the client folder, and extract the archive for the C# client there is a net35 folder containing the dll.

(There is no easy way to get the v0.3.9 library working with .NET 3.5 as it requires code changes - for example the System.Tuple class which it relies on is not available in .NET 3.5)

Link to comment
Share on other sites

2 minutes ago, djungelorm said:

My pleasure :D Glad you're enjoying it!!!

Regarding .NET 3.5 support, I've actually implemented this for the upcoming v0.3.10 but haven't released it yet. If you want to try it out now you can use this pre-release version:  https://krpc.s3.amazonaws.com/deploy/master/966.1/krpc-0.3.10-58-gf0c66fe.zip

If you extract that archive, then look in the client folder, and extract the archive for the C# client there is a net35 folder containing the dll.

(There is no easy way to get the v0.3.9 library working with .NET 3.5 as it requires code changes - for example the System.Tuple class which it relies on is not available in .NET 3.5)

I see. Although not tested fully yet, it seems to work by using Unity's experimental .NET4.6 script runtime environment.

Sidenote: you should make a serial communication API to talk to Arduinos directly via kRPC (or other serial connections), and an Arduino sketch to go along with it :3

Link to comment
Share on other sites

I should! I've been working on a major update the the underlying workings of kRPC that would make adding more communication protocols quite simple. Hoping to get it released "soon" - although I think I said the same something similar over a year ago... I guess that's the problem with hobby projects!

Link to comment
Share on other sites

2 minutes ago, djungelorm said:

I should! I've been working on a major update the the underlying workings of kRPC that would make adding more communication protocols quite simple. Hoping to get it released "soon" - although I think I said the same something similar over a year ago... I guess that's the problem with hobby projects!

I feel you man. Same deal for my controller project.

Another sidenote: Being the creator of kRPC; would you happen to know of anyone who has made standalone map-views or navball displays using kRPC? I've been looking for both for ages, but no one seem to have made something like it. I'd preferably not have to make a map view and navball view from scratch in Unity :P

Alas, I'm just using you as a hotline now xD sorry...

I don't know if you've ever done serial stuff with Arduino, but it's quite simple. A system like it directly integrated in to kRPC would significantly up the game-changeification factor of kRPC!

Link to comment
Share on other sites

42 minutes ago, Fillipuster said:

Another sidenote: Being the creator of kRPC; would you happen to know of anyone who has made standalone map-views or navball displays using kRPC? I've been looking for both for ages, but no one seem to have made something like it. I'd preferably not have to make a map view and navball view from scratch in Unity :P

Unfortunately I've not heard of such a project (although, maybe check if Telemachus does something like that, Although off the top of my head I don't think it does...)

If you do build your own, you could probably use an open source library to do the actual visualization part. I imagine there are lots of options out there. You'd just need to tie it to kRPC as the data source which shouldn't be too hard. I guess it won't look exactly like the KSP map view though. I did a quick google and found this, for example: http://jat.sourceforge.net/

Link to comment
Share on other sites

3 minutes ago, djungelorm said:

Unfortunately I've not heard of such a project (although, maybe check if Telemachus does something like that, Although off the top of my head I don't think it does...)

If you do build your own, you could probably use an open source library to do the actual visualization part. I imagine there are lots of options out there. You'd just need to tie it to kRPC as the data source which shouldn't be too hard. I guess it won't look exactly like the KSP map view though. I did a quick google and found this, for example: http://jat.sourceforge.net/

Interesting... I'll have to consider using JAT for the map-view clone. Somehow I do feel that it would be easier to do in Unity. I'm more familiar with Unity and C#. I just have to crack the code of drawing elliptical lines using the orbital data from kRPC. No easy task :(...

Link to comment
Share on other sites

This thread is quite old. Please consider starting a new thread rather than reviving this one.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...