Category Archives: Uncategorized

ThreeBody 2.0

Infinite Force? Forty year old FORTRAN to the rescue!

I continue to be fascinated by the complexity that comes from the simple problem of three masses interacting through gravity. Last year I released the ThreeBody app to demonstrate some of this complexity – challenging users to place three bodies so they would stay together. For bodies at rest this is probably impossible (although I am not aware of a proof).  An early commenter asked exactly the right question: “Is the ejection of a body physical or an artifact of the simulation?”.

In the case of my app, in most cases it was an artifact of the simulation. I have been on a journey to remove this artifact and better demonstrate that it is STILL very hard to find solutions that stay together and this is now purely because of the physics and not the implementation.

The result is a significant reboot of ThreeBody, one that allows velocities to be added to the bodies and as a bonus has a gallery of very cool known stable three body solutions.

Close Encounters Have Near-Infinite Force

The force of gravity scales as 1/r^2. Start with two bodes at rest a fixed distance apart, attracted by gravity. As they get close, r (the distance between them), gets small and 1/r^2 becomes HUGE. In a game simulation applying a huge force for a short time step can result in an object moving a large distance, often far beyond the other object. In reality the pair would get the same very big force restraining them as they move past the closest approach. If you think about energy conservation and ignore the collision – it is impossible for the two bodies to fly apart. They can only get as far apart as they started (assuming they started at rest). If two bodies interacting do fly apart – it is an artifact of the simulation not coping well with the very large forces at close approach.

Simulation artifacts have been a well known issue in gravitational simulations since the beginning of computer astronomy experiments in the 1960s. There are ways to transform (“regularize”) the co-ordinates and the forces so that the infinities do not arise during close encounters. This is commonly done in scientific-grade simulations but in game physics is not typically demanded (since the collision usually results in some form of destruction).

Since my app was trying to model these close encounters, it needed a higher pedigree solution.

As usual, I started by buying more physics books and downloading papers. This convinced me that I did need to have a regularizing algorithm and also showed me that doing one from scratch would take some time. Since there is no substitute for running code, my next step was to look and see what researchers were using and if I could adapt it. There are some fantastic programs available (see references below) although many are instrumented for research, scaled for many masses and do not not need to be concerned about real-time performance. These programs are BIG and generally written in FORTRAN or C and I was hoping to continue to use C# within Unity.

I finally found the code TRIPLE from Aarseth and Zare developed in FORTRAN in 1974. It was about one thousand lines. After several attempts using tools to do Fortran to C to C# and experiments building the code as a C library and calling from Unity, I decided that the simplest approach was just to transcribe the code by hand. As an added bonus I would gain a much deeper insight into how the algorithm worked. The code then needed a bit of re-arranging to meet the real-time needs of evolution during a graphical application, and changes in reference frame (since the algorithm operates in the center of mass frame).

ThreeBody now uses the TRIPLE engine and the encounters continue to be very fascinating – even more than before. For masses with no initial velocity it is still difficult to find long lived solutions. The full version of ThreeBody allows the bodies to be given initial velocities allowing even more solutions to be explored. The full version also allows a choice of integration engine; you can go back to Leapfrog to see just how different the results are and monitor the change in total energy – which indicates the error in integration. There is also a higher pedigree non-regularized Hermite integrator for comparison to Leapfrog.

A large gallery of very cool three body solutions is now part of the app. Ranging from solutions found by Euler and Lagrange in the 1770s to those found as recently as 2013. These are hypnotically beautiful – even though not all of them a stable.

For those who want to delve further an annotated reference section is provided.

Resources and References

Three Body Solutions:

Broucke (1975) On Relative Periodic Solutions of the Planar Three Body Problem, Cel.Mech, 12, p439 SAO/NASA

Henon (1974) Families of periodic orbits in the three-body problem, Celestial Mechanics, vol. 10, Nov. 1974, p. 375-388. SAO/NASA

Suvakov (2013) Numerical Search for Periodic Solutions in the Vicinity of the Figure-Eight Orbit: Slaloming around Singularities on the Shape Sphere arxiv

Suvakov and Dmitrasinovic (2013) Three Classes of Newtonian Three-Body Planar Periodic Orbits arxiv

Regularization:

Aarseth, Zare (1972) A regularization of the three-body problem. Celestial Mechanics, vol. 10, Oct. 1974, p. 185-205. SAO/NASA

The discussion in The Basics of Regularization Theory by Celletti provides a very accessible introduction. More discussion can be found in Heggie & Hut, and Aarseth.

Books:

Aarseth (2009) Gravitational N-Body Problems, Cambridge Univ. Press. (Very comprehensive, detailed discussion of algorithms.)

Heggie, Hut (2003) The Gravitational Million-Body Problem, Cambridge Univ. Press. (A readable, wider ranging overview of N-body simulations and the behaviour of star clusters)

Roy (2004) Orbital Motion, CRC Press (Derives Euler and Lagrange three body solutions. One of the classic texts of orbital mechanics.)

Code:

The “defacto standard” code is from Aarseth. This is all in FORTRAN. The TRIPLE integrator used in ThreeBody is derived from the TRIPLE code here.

Starlab is another widely used collection of programs.  The Hermite integrator offered as an option in ThreeBody is a modified version of an integrator in Starlab.

Learn Physics With This One Trick

When I look at new physics books (which I do far too often) I get a “Flowers for Algernon” feeling. There was a time when I knew about this stuff. That knowledge has seeped away over the past  fifteen years leaving me with a sense of loss and nostalgia. However, there is a trick I used in undergrad when I decided that I wanted to have the option of going to graduate school, that applies here. I am using it to get my physics kung-fu back.

gravity

First, some background.

I “speak” math with some fluency. In high school it was easy to pick up. I do not speak much else. Efforts to learn French, Spanish and Mandarin at various points in my life have all been tedious and I have never managed to get very far.

Although I speak math, I was a lousy student. In first year I was so close to the bottom of the class, that I doubt anyone below me returned for the next semester. I did manage to squeak up to being 30th percentile – and I would have told you I was working hard. What I told myself (after getting in to a good school) was that I was on a different curve now and that this was the new “level”. In reality I was looking at the material, “grazing the text”, nodding to myself that it all made sense and doing only the assigned questions as best I could.

In the middle of third year I decided it was time to open the door to grad school and using my “trick” I achieved an 85% average and made in onto the Dean’s list.

The “trick” is: Do EVERY question until you can do it PERFECTLY.

I didn’t say it was an easy trick.

It almost killed me.

For the entire term I was either in class or at my desk. I did every question multiple times. I filled in every gap in the derivation in the text books. I went back and repeated start to finish questions I had not gotten right the first time, until I could take a blank sheet of paper and get it right.

I learned by doing, using the material in the book to solve problems.

I got into grad school.

Back to the present…

There is a new physics textbook “Gravity” by Eric Poisson and Clifford Will. This book is a tour-de-force, beginning with Newtonian gravity, detouring into shapes due self gravity and tidal forces, three body orbits and then heading into techniques to model general relativity and gravitational waves in situations where full blown general relativity cannot give direct answers.

I have decided that I refuse to feel nostalgia and loss about this topic. I need to learn it.

Back to the trick. It is NOT any easier. After a fifteen year break, I have spent more that a few hours reminding myself about div, grad, curl and lots of other forgotten math. The progress is slow, but not painful. Chapter 1, question 1 took me two weeks. I had to refresh my knowledge of vector calculus, derive some results in the text and figure out Stoke’s theorem. When I go back to the text with a specific problem in mind, I read far more carefully. As I feel knowledge seeping back I am excited to discover the connections and see where physics leads. There is a sheer joy from simply using my brain much like the feeling I get from a long bike ride or XC ski. My justification is precisely the same – it’s challenging and it’s providing exercise for part of my body.

The questions in chapter one have taken me a little over two months. Chapter two is going a bit better, since I now have some of my math skills back. I do not have as much time to focus on this as I would like, but the time I can put in is rewarding – and I can go off on detours to remind myself about Green’s theorem – or whatever it is I need to re-learn. Right now I am “stuck” on a line in Chapter three that starts “expanding in terms of r/R we get” and I need to go find out about Taylor series of vector functions.

This may take some time, but the trick is working again.

[social4i size=”large” align=”float-right”]

The Unity 4.6 UI – Some Tidbits

Unity 4.6 provides a fantastic new UI framework. I will never use the old OnGui() again! I have been using the new framework for the past several months while Unity 4.6 was in beta. During this time I have collected a few tidbits on working with the framework.

Getting Started

The tutorials  are very good and the information in the manual is getting better all the time. I found the tutorials on Canvas, RectTransform, Button and Event System a bare minimum to get the idea of the whole thing.

Adapting for Mobile Screen Sizes

This was one of my first “care-abouts”. There are two things that are important to know. The first is the anchor system for the layout of elements  (see the RectTransform tutorial) but that is only part of the solution. The crucial other element is adding a CanvasScaler to your root canvas.

Screen Shot 2014-11-29 at 12.45.51 PM

Once attached to a Canvas this can then be set to give a reference size and you’re good to go. As the device screen size change your UI element will scale appropriately.

UI interactions with Scripts

In the C# world the Unity elements can be created and modified as you would expect. You will want one or both of the following includes:

using UnityEngine.UI;
using UnityEngine.EventSystems;

ColorBlock: Changing Button Colors

The ThreeBody game I am creating makes use of collections of buttons as radio boxes. I set the disabled and highlighted colors to reflect the color I want for unselected and selected. When it is time to enable a button, then the normal color of the button is set to the value in the highlighted color. It would be reasonable to expect that:

button.colors.normalColor = Color.white; // DOES NOT WORK!

would work. It does not. Instead you need to make a temporary copy of the ColorBlock and then modify its elements and copy back the ColorBlock:

    // flip to highlighted color
    private void EnableButton(GameObject go) {
        Button b2 = go.GetComponent<Button>(); 
        ColorBlock cb2 = b2.colors;
        cb2.normalColor = cb2.highlightedColor;
        b2.colors = cb2;        
    }

Touch Events and Buttons

Button touch events will still fall through into code that handles touches so it becomes important to screen out those touches that are over top of buttons. A technique that works for both mouse and touch events is:

    private bool IsTouchOnButton() {
        GameObject go = EventSystem.current.currentSelectedGameObject
        if (go != null) {
            if ( go.GetComponent<Button>() != null) {
                return true;
            }
        }
        return false;        
    }

 Panel Fading and CanvasGroup

There is not a lot said about panels in the tutorials or online docs. These appear to be containers for holding a subset of the UI being developed. I found them useful for Settings Menus and High Score panes. In order to run a fade effect on these panels, you can add a CanvasGroup (which then has a field “alpha” that allows direct control over fading). An example of such a fade coroutine is:

    public GameObject menuPanel; 
    private const float FADE_TIME = 0.5f;
    private const float FADE_STEPS = 10f;
    private const float FADE_INCR = FADE_TIME/FADE_STEPS;
    
    private IEnumerator FadeMenuPanel(bool visible) {
        CanvasGroup cg = menuPanel.GetComponent<CanvasGroup>();
        if (!visible) {
            for (float i=FADE_STEPSi > 0i--) {
                cg.alpha = i/FADE_STEPS;
                yield return new WaitForSeconds(FADE_INCR);
            }
            cg.alpha = 0.0f;
            menuPanel.SetActive(false);
        } else {
            menuPanel.SetActive(true); 
            cg.alpha = 0f;
            for (float i = 0fi <= FADE_STEPSi++) {
                cg.alpha = i/FADE_STEPS;
                yield return new WaitForSeconds(FADE_INCR);
            }
            cg.alpha = 1.0f;            
        }
    }

Note that in my case I also change the panel active status. This needs to be done at the end of the fade out or the start of the fade in for the object to stay visible during the fade.

Off-Topic: Trail Renderers

This is not part of the new Unity UI theme but as part of getting ThreeBody ready I had to learn a bit about TrailRenders. I use these to leave paths behind the “stars” in ThreeBody so the orbital paths can be seen. I always had weird issues with setting materials and colors until I finally found some clear advice on the forums about the material choice. I need to choose a particle material and the trails look best with a mobile/particle/vertex-lit shader on that material. To get solid colors I have created a simple 128×128 solid color PNG, imported as a texture.

Another tidbit is how to recycle objects once you have used trail generation. To get rid of the trail I ended up setting the trail length to -1, then counting 5 update cycles before setting the object inactive and putting it back into my object pool. I played around with coroutines for this but they ended up creating more complications – and a simple synchronous design won out.

Hope some of these save you some time.

[social4i size=”large” align=”float-right”]

Thank You Apple For Rejecting My App

One way I cling to the notion that I still know something about physics is to create oddball mobile physics apps. Since this is a side-project my goal is to spend most of the time on physics and less on the time-intensive UI tuning. I have moved to Unity and while learning Unity I decided to try and make a mobile game inspired by a spinning magnet office toy I had had for years.

IMG_0886

When I look at something like this I wonder what might happen if I could change the number of arms, number of “propellers” and a game/simulation seems like a good way to explore these ideas.

In my initial enthusiasm for Spinor I decided that adding leaderboards would be a good idea. It would encourage people to share their love of my awesome game and take me on the road to self-sufficiency as an indie developer. This meant that I needed to add code to track login state and provide options on the level select screen and game over screen. I found a way to spooge it in. What I had was “workable” and I went ahead and started to submit Spinor for Android, BB10 and iOS.

Google will take pretty much anything. Within hours my app was up on Google Play.

Amazon approved it.

Blackberry approved it.

Apple rejected it.

They rejected it on the basis that the level select and game over screens were “too ugly”.

They were right.
IMG_0883
The level select screen was one of those things that is not the fun part of developing the app, and I had just plopped in some touchable tiles and some hacky strings using the Unity OnGUI() approach. It *was* ugly. I then decided this was a great time to search the Unity asset store. I quickly discovered the Mad Level Manager and decided to grab it when it went on sale. The end result is a cleaner looking game that is more presentable.

IMG_0885

The chaos of magnetically interacting systems *is* cool – and I enjoyed watching some of the odd interactions that result.

IMG_0823

Next time I’ll be submitting to Apple FIRST. They give the best feedback.

[social4i size=”large” align=”float-right”]

Potential

Potential is now available on BlackBerry World and Google Play.

The idea for the game came from watching my kids play with the BuckyBall magnet toys on a coffee table – taking turns placing them and trying to keep them apart. The interactions were sudden and dynamic. It seemed a great choice of the kind of app I like to write – lots of physics.

The result can be seen here:

This is my entry in an internal hackathon at work. The development did take some interesting turns that I may now have time to blog about.