Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, September 13, 2020

Orbital velocity and altitude calculations in C#

Just thought I'd share a C# snippet for calculating nominal orbital speed if you have the center mass and orbital radius. And to go the other way if you have the center mass and speed to get the nominal orbital radius.


public static class OrbitalCalculations
{
    public const double G = 0.0000000000667d;
    public static double NominalOrbitalSpeed(double centerMass, double orbitalRadius)
    {
        if (orbitalRadius.IsZero())
            return 0;
        return Math.Sqrt(G * centerMass / orbitalRadius);
    }
    public static double NominalOrbitalRadius(double centerMass, double speed)
    {
        if (speed.IsZero())
            return 0;
        return G * centerMass / (speed * speed);
    }
    public static bool IsZero(this double d, double tolerance = 0.0001)
    {
        return Math.Abs(d) < tolerance;
    }
}
If you want the math behind and more: 
Hope this helps someone out there! : )

Thursday, March 19, 2020

A TwoWay or OneWayToSource binding cannot work on the read-only property

I ran into an InvalidOperationException when binding to a read-only property in the model

I.e. my model looks something like this:
public class Customer
{
 public Guid Id { get; set; }
 public string Name { get; set; }
 public List Orders { get; set; }
 public double CalculatedProperty => Orders.Sum(x => x.TotalPrice);
}
And my binding in XAML something like:
{Binding CalculatedProperty, StringFormat='0.00'}

To get around this, we need to update the binding to set the Mode to something else then TwoWay or OneWayToSource, simplest is to just set it to OneWay like the following:
{Binding CalculatedProperty, StringFormat='0.00', Mode=OneWay}



Hope this helps someone out there!

Full exceptioon stack-trace
System.InvalidOperationException
  HResult=0x80131509
  Message=A TwoWay or OneWayToSource binding cannot work on the read-only property 'CalculatedProperty' of type 'Model.Entity.Customer'.
  Source=PresentationFramework
  StackTrace:
   at MS.Internal.Data.PropertyPathWorker.CheckReadOnly(Object item, Object info)
   at MS.Internal.Data.PropertyPathWorker.ReplaceItem(Int32 k, Object newO, Object parent)
   at MS.Internal.Data.PropertyPathWorker.UpdateSourceValueState(Int32 k, ICollectionView collectionView, Object newValue, Boolean isASubPropertyChange)
   at MS.Internal.Data.ClrBindingWorker.AttachDataItem()
   at System.Windows.Data.BindingExpression.Activate(Object item)
   at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
   at System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Run(Object arg)
   at MS.Internal.Data.DataBindEngine.OnLayoutUpdated(Object sender, EventArgs e)
   at System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()
   at System.Windows.ContextLayoutManager.UpdateLayout()
   at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
   at System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
   at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run()
   at UI.WPF.App.Main()

  This exception was originally thrown at this call stack:
 MS.Internal.Data.PropertyPathWorker.CheckReadOnly(object, object)
 MS.Internal.Data.PropertyPathWorker.ReplaceItem(int, object, object)
 MS.Internal.Data.PropertyPathWorker.UpdateSourceValueState(int, System.ComponentModel.ICollectionView, object, bool)
 MS.Internal.Data.ClrBindingWorker.AttachDataItem()
 System.Windows.Data.BindingExpression.Activate(object)
 System.Windows.Data.BindingExpression.AttachToContext(System.Windows.Data.BindingExpression.AttachAttempt)
 System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(bool)
 MS.Internal.Data.DataBindEngine.Task.Run(bool)
 MS.Internal.Data.DataBindEngine.Run(object)
 MS.Internal.Data.DataBindEngine.OnLayoutUpdated(object, System.EventArgs)
    ...
    [Call Stack Truncated]

Wednesday, March 20, 2019

MonoGame: Static Camera Tutorial and code


Some of you may have noticed my series on openGL with openTK in C# that I wrote some years ago. Since then my life has been quite full of stuff happening so I never got around to look at lightning or other stuff to make sure that I would end up with a working engine.

Lately I found MonoGame and started to experiment with it, turns out that it has much of the stuff that I want to use so I ended up writing some stuff with it.

Here I thought that I would share a basic static camera class and its usage as it took some time for me to understand how to get it working together with the BasicEffect class provided by MonoGame.

Some code. Let's start to look at the interface that we would want to use with out cameras.

public interface ICamera
{
    Matrix ViewMatrix { get; }
    Matrix ProjectionMatrix { get; }
    void Update(GameTime gameTime);
}

We want our cameras to expose their View and Projection matrices as they will be used to integrate the camera with MonoGame BasicEffect.
Also, as we will be using this interface with all of our cameras we may want to update it in each frame, hence the Update(GameTime gametTime) method. GameTime is provided by MonoGame and contains two timespans, time since game start and time since last frame.


Next we look at the actual StaticCamera, a camera that once created will remain static in the world. I.e. you place it at a position and point it towards something interesting and it will look at that position until you remove the camera. Useful for some scenarios and a good stepping point for creating more advanced camera classes.

We want our camera to have a Position in in the game world and a Direction.

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
public class StaticCamera : ICamera
{
    public Vector3 Position { get; }
    public float FieldOfView { get; }
    public float NearPlane { get; }
    public float FarPlane { get; }
    public Vector3 Direction { get; }
    public Matrix ViewMatrix { get; }
    public Matrix ProjectionMatrix { get; }

    public StaticCamera(GraphicsDevice graphicsDevice, float fieldOfViewDegrees, float nearPlane, float farPlane)
        : this(graphicsDevice, fieldOfViewDegrees, nearPlane, farPlane, Vector3.Zero, -Vector3.UnitZ)
    { }

    public StaticCamera(GraphicsDevice graphicsDevice, float fieldOfViewDegrees, float nearPlane, float farPlane, Vector3 position, Vector3 target)
    {
        FieldOfView = fieldOfViewDegrees * 0.0174532925f;
        Position = position;
        Direction = Vector3.Normalize(target - position);
        ViewMatrix = Matrix.CreateLookAt(Position, Direction, Vector3.Up);
        ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(
            FieldOfView,
            graphicsDevice.Viewport.AspectRatio,
            nearPlane,
            farPlane);
    }
    public void Update(GameTime gameTime)
    { }
}

We have two constructors, the first one takes a GraphicsDevice reference that we need to figure out what resolution and especially what aspect ration our current view port has. (i.e. screen resolution/window size)
Also, we want to specify the lense angle in degrees. I.e. 60 degree lense.
The near and far clipping planes, i.e. we will only want to render objects that are between those two distances from the camera.
The first constructor creates a camera located at coordinates (0, 0, 0) looking inward (0, -1, 0)

The second constructor takes also the position and target to look at.
We calculate the radians of the camera lense by multiplying the field of view degrees with 0.01745...
After that we figure out the direction that the camera points at by subtracting the camera location from the target and normalizing the result.

To get the ViewMatrix we use the Matrix.CreateLookAt function that takes Position, Direction and an up vector
To get the ProjectionMatrix we use the Matrix.CreatePerspectiveFieldOfView function that takes the field of view, aspect ration and near/far planes.
This is pretty much all for a simple static camera using the MonoGame framework.

Next step is to use the camera.

private ICamera _camera;
protected override void LoadContent()
{
 _camera = new StaticCamera(GraphicsDevice, 60, 1, 200, new Vector3(1, -10, 0), Vector3.Zero);
}

I put the above code in my Game1.cs file. As the default Game1 class inherits from Game, it will have GraphicsDevice provided and we just need to send it into the constructor together with field of view angle, near and far planes, position and target coordinates to look at.

All of my game objects inherit from the following abstract GameObject class
public abstract class AGameObject
{
 public Vector3 Coordinates;
 public Vector3 Rotation;
 public Vector3 Velocity;
 public float Scale = 1f;
}
So each game object has a position in the game world that is stored in Coordinates, it also has an rotation, velocity and scale.


Whenever we want to render a game object in a scene, we wrap it in a Renderable object that also has a model and a Draw method:
public class Renderable
{
 public VertexPositionNormalTexture[] Model;
 public BasicEffect BasicEffect;
 public AGameObject GameObject;

 public Renderable(AGameObject gameObject, GraphicsDevice graphicsDevice)
 {
  GameObject = gameObject;
  BasicEffect = new BasicEffect(graphicsDevice)
  {
   AmbientLightColor = Vector3.One,
   LightingEnabled = true,
   DiffuseColor = Vector3.One,
  };
 }

 public void Draw(GraphicsDevice graphicsDevice, ICamera camera)
 {
  var t2 = Matrix.CreateTranslation(GameObject.Coordinates.X, GameObject.Coordinates.Y, GameObject.Coordinates.Z);
  var r1 = Matrix.CreateRotationX(GameObject.Rotation.X);
  var r2 = Matrix.CreateRotationY(GameObject.Rotation.Y);
  var r3 = Matrix.CreateRotationZ(GameObject.Rotation.Z);
  var s = Matrix.CreateScale(GameObject.Scale);

  BasicEffect.World = r1 * r2 * r3 * s * t2;

  BasicEffect.View = camera.ViewMatrix;
  BasicEffect.Projection = camera.ProjectionMatrix;
  
  BasicEffect.EnableDefaultLighting();

  foreach (var pass in BasicEffect.CurrentTechnique.Passes)
  {
   pass.Apply();

   graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, Model, 0, Model.Length / 3);
  }

 }
}

Here we can see that the render method takes a graphicsDevice and camera. Here we take the ViewMatrix from the camera and put it in the BasicEffect.View, and the same goes for the ProjectionMatrix that is put in BasicEffect.Projection.
The BasicEffect.World receives the rotated, scaled and translated matrix generated from the GameObject.

Now we need to look up our Draw method in the main game file (Game1.cs) and place calls to render our Renderables there
private List<Renderable> _scene = new List<Renderable>();
private readonly RasterizerState _rasterizerState = new RasterizerState
{
    CullMode = CullMode.CullClockwiseFace
};

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.RasterizerState = _rasterizerState;
    GraphicsDevice.Clear(Color.CornflowerBlue);
    foreach(var x in _scene)
    {
        x.Draw(GraphicsDevice, _camera);
    }
    base.Draw(gameTime);
}
First we tell the graphics device to save some time by culling triangles that are backwards facing, we then clear the scene to a background color.
For simplicity we store all our Renderables in a list called _scene and iterate through it and call Draw on each element.


I hope this helps someone out there to get unstuck when starting to use MonoGame.

All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment or share on social media, not required but much appreciated! :)

Wednesday, October 17, 2018

Teaching myself Unity - Logging to screen


I've played around quite a lot with OpenGL and built my own engine to some extent (as you can see in other posts on this blog). But I want to create games, doing that with a home-written engine puts a lot of focus on the engine and very little on the actual game. So I decided to try out Unity as it seems popular and has nice integration with Visual Studio


Getting started

Install both and start Unity.
First screen in Unity. Just click on the New button to the upper right to create our first project
Name the project and select where it should be placed on disk. I also disabled unity analytics as I don't think that this test project would have any usage for it.


Configure script editor

Next step is to make sure that Unity thinks that Visual Studio should be used for script editing
Go to Edit menu -> Preferences and in the popup select External Tools and make sure that External Script Editor is set to Visual Studio 2017 (Community). Or any other version of Visual Studio if you have the licensed versions

Logging to screen

I like to have stuff happening on the screen, and in my mind the first step should be to add logging to screen so that we can follow what happens in the game without having to tab out to the Unity editor (or when we run the game outside of the development environment)
So, how to accomplish logging to screen?

In the project tab. Assets folder, create a new folder and name it Scripts
  • Create a new folder called scripts (see above picture)
  • Create a new C# script in that folder and call it Logger
In the SampleScene create a new empty GameObject and call it Screen Logger
  • Create a new GameObject and call it Screen Logger
  • Select the Screen Logger GameObject and drag the Logger script to the Inspector view for the screen logger to attach the script to the GameObject
Screen Logger Game Object with attached Logger script in the Inspector view
Next, let's create the UI component that we will log to.
  • Right click in the Sample Scene tab and select UI -> Text
  • Rename the newly created Text to Log
Scene view with the Log Text control (New Text), 2D view selected in the upper left corner and the white line is the borders of the canvas

  • Go to the Scene view and click on the 2D button at the top so that we can position our UI component
  • Select the Log Game Object and move your mouse cursor over the Scene view and press F on the keyboard. This will find and focus the view on that particular component. 
  • Zoom out with your mouse-wheel so that you see the canvas borders
Resized textbox to fill the upper area of the canvas
  • Resize the textbox so that it fills the upper area of the canvas. Notice the color change of the canvas border when the textbox is at the border. 
In the Inspector, set stretch and anchor to the top of the canvas
  • Select the text box and go to the inspector. Select stretch and anchor point according to the picture above

Logger script

So, now we have our UI component setup and placed at the top of the canvas area, lets look at the Logger script.
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Logger : MonoBehaviour
{
    public static Logger Instance { get; private set; }
    public Text Log;
    private List<string> _logLines = new List<string>();

    void Start()
    {
        Instance = this;
    }

    void Update()
    {
        // test code to check that this works
        Write(Time.fixedTime.ToString());
    }

    public void Write(string text)
    {
        _logLines.Add(text);
        if (_logLines.Count > 3)
            _logLines.RemoveAt(0);
        Log.text = string.Join(Environment.NewLine, _logLines.ToArray());
    }
}

  • Each script is generated with a Start and Update method. 
  • The static Logger Instance will help us access this script from outside (Singleton pattern). We assign it with this in the Start method (Start is guaranteed to only execute once)
  • Next we add a using UnityEngine.UI; line to the top and a public variable called Text Log. This will allow us access to an UI component in the scene. We will connect them in a later step, here we just say that we will be using a GameObject of type Text
  • After that we define a private variable that holds a list of strings that have been logger and initialize it inline
  • Now, create a new method called Write that takes a string as parameter.
  • Add the input parameter to the list of strings and then we make sure that the list doesn't grow by removing old items if there are more then 3 items in the collection.
  • Lastly we join all strings in the list with a new line between each and assign it to the text field of the Text UI component.
And that's pretty much it. You can of course play around with more information but this is the basic logging capability that I am after.
Notice the Update method calls the Write each frame, this is only for testing purposes and the whole Update method can be removed once we know that the script works.

Connect our Log text element to our Logger script in the Screen Logger game object inspection Click on the small circle to the right of the field to popup the Select Text dialog. It will show all GameObjects in the scene of the type Text.
So, our script is done. Now we just have to connect the correct Text component to it
  • In the inspector for Screen Logger, click on the small circle to the right of the Log field to popup the Select Text dialog
  • As we only have one Text component in the scene at the moment, just select it and close the popup


The end result of our logger in action, currently printing out the time each frame

So it works, you can now remove the Update method from the script as it is not really needed.

Usage from other scripts:


Logger.Instance.Write("information that we want to put on screen");

That's it!

All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment or share a link on social media, not required but appreciated! :)

Saturday, September 29, 2018

Immutability in .NET

First off, what are immutable objects

Immutable is pretty much a fancy word for unchangeable. In other words, once you create an object it will have the same properties for its entire life. No way to reassign for example a name, if you want to do that you would have to create a new object with the same properties but with the new name. Immutable = Not Mutable

Why bother?

I didn't understand the point of immutable objects, I though that as long as we encapsulate and follow good object oriented guidelines then we are good to go.. Right?
Let's look at a naive example of things that can go wrong:
public class CSharpPoco
{
    private uint _value;
    public uint Value => _value;
    public void Increment()
    {
        _value++;
    }
    public uint GetNext()
    {
        Increment();
        return _value;
    }
}
        
public class ServiceLayer
{
    private CSharpPoco _poco = new CSharpPoco();
    public CSharpPoco GetPoco()
    {
        return _poco;
    }
    public uint PreviewNextValue()
    {
        return _poco.GetNext();
    }
}

In the service layer we have 2 methods to call, get the poco and preview its next value.
The following service code would throw the side effect exception:

var service = new ServiceLayer();
var poco = service.GetPoco();
var firstValue = poco.Value;
var preview = service.GetPreviewValue();
if (preview <= firstValue)
    throw new Exception("preview can't be smaller then or equal to the previus value");
if (poco.Value == preview)
    throw new Exception("side effect");

Meaning, we get an unexpected side-effect by calling the second method in the service. It manages to change the value of the first service calls result. It was zero, but after the preview call it has been set to 1. This is quite a simple example, but after having debugged scenarios like these in production code with huge code bases.. You get the idea, a unexpected side effect is often a cause for hard-to-find bugs.
So, how could immutability have helped us here? once the var poco = service.GetPoco() was called, the result would never change. Preferably we would not be able to reasign the variable poco to other references either (similar to the const keyword in TypeScript or F# let). So instead of var I would have liked a const poco = service.

What options do we have in .NET?

Readonly objects in C# with constructor lists

public class CSharpImmutableConstructorList
{
    public readonly Guid Id;
    public readonly string Name;
    public readonly string DisplayName;
    public CSharpImmutableConstructorList(Guid id, string name, string displayName)
    {
        Id = id;
        Name = name;
        DisplayName = displayName;
    }

    public CSharpImmutableConstructorList SetDisplayName(string displayName)
    {
        return new CSharpImmutableConstructorList(Id, Name, displayName);
    }
}
Basically the magic here is done by the readonly keyword that states that only the constructor can set the value of the variable. Once it has been set, it can only be read. For larger objects, it can get a little heavy on the constructor and you have to supply all the values every time you want to change. For example the SetDisplayName function, it supplies the Id and Name even though they have the same value as before.
If we add more properties to this class, we would have to change all calls to the constructor and add the new properties for them as well. So a little heavy on the maintenance side.

Readonly objets in C# with Modify pattern

public class CSharpImmutableModifyPattern
{
    public readonly Guid Id;
    public readonly string Name;
    public readonly string DisplayName;
    public static CSharpImmutableModifyPattern Default { get; } = new CSharpImmutableModifyPattern(Guid.Empty, string.Empty, string.Empty);
    private CSharpImmutableModifyPattern(Guid id, string name, string displayName)
    {
        Id = id;
        Name = name;
        DisplayName = displayName;
    }
    public CSharpImmutableModifyPattern Modify(Guid? id = null, string name = null, string displayName = null)
    {
        return new CSharpImmutableModifyPattern
            (
                id ?? Id,
                name ?? Name,
                displayName ?? DisplayName
            );
    }
    public CSharpImmutableModifyPattern SetDisplayName(string displayName)
    {
        return Modify(displayName: displayName);
    }
}
This is pretty much the same pattern as I've described in a previous post (Functional adventures in .NET C# - Part 1, immutable objects), the difference is that we use the readonly members instead of get-only fields.
Also note that the constructor is set to private to prevent usage of it from outside, instead we will use the Default static get-only field that sets up a default invariant of the class and call the new method Modify on it.
The nice thing with the Modify pattern is that you don't have to supply anything else then the changed property as shown in the SetDisplayName method. Even if we add new parameters, we don't have to change the SetDisplayName method as it specifies that it only wants to supply the displayName and nothing else.

Record types in F#

module Techdump =
    open System
    type FSharpRecord =
        {
            Id : Guid
            Name : string
            DisplayName : string
        }
        member this.SetDisplayName displayName =
            { this with DisplayName = displayName }

The F# Record version of the same type as show before. Used from C# this type feels similar to the C# Constructor List version as you have to supply all the constructor parameters when calling new. The magic happens in the SetDisplayName function that takes a new displayName value and then calls the record constructor with the current record and whatever fields have changed. I.e. the with keyword in record construction. We get the power of CSharpImmutableModifyPattern, but without having to maintain a Modify method, it is all included in the language.


Performance

In this part we will look at the run-time performance the different immutable patterns described above. 

Performance test source code


CSharpPoco
public class CSharpPoco
{
    public Guid Id { get; private set; }
    public string Name { get; private set; }
    public string DisplayName { get; private set; }
    public CSharpPoco(Guid id, string name, string displayName)
    {
        Id = id;
        Name = name;
        DisplayName = displayName;
    }

    public void SetDisplayName(string displayName)
    {
        DisplayName = displayName;
    }
}
Added a C# poco object so that we have a baseline to run against. I.e, here we just mutate the object. No new instance is created, this is the traditional way of changing a value in an object.

Performance tester
public class ImmutabilityPerformance
{
 public void Execute()
 {
  Log("--------------------------------------");
  Log("... ImmutabilityPerformance");
  ExecuteTest(1_000_000);
 }
 
 
 private void ExecuteTest(int iterations)
 {
  string s = string.Empty;
  try
  {
   var data = new List<string> { "Melissa Lewis", "Maya", "Smith", "Beverly Marsh", "Jane Vasko", "Molly Bloom" };
   var csharpPocoTimings = new RunningAverage();
   var fsharpRecordTimings = new RunningAverage();
   var csharpConstructorTimings = new RunningAverage();
   var csharpModifyTimings = new RunningAverage();
   for (int i = 0; i < iterations; i++)
   {
    var csharpPoco = new CSharpPoco(Guid.NewGuid(), "Jessica Chastain", "Jessica Chastain");
    var fsharpRecordOriginal = new Techdump.FSharpRecord(Guid.NewGuid(), "Jessica Chastain", "Jessica Chastain");
    var csharpConstructorOriginal = new CSharpImmutableConstructorList(Guid.NewGuid(), "Jessica Chastain", "Jessica Chastain");
    var csharpModifyOriginal = CSharpImmutableModifyPattern.Default.Modify(Guid.NewGuid(), "Jessica Chastain", "Jessica Chastain");

    for (int dataIndex = 0; dataIndex < data.Count; dataIndex++)
    {
     var item = data[dataIndex];


     csharpPocoTimings.Add(TimeAction(() =>
     {
      csharpPoco.SetDisplayName(item);
     }));
     if (csharpPoco != null)
      s = csharpPoco.DisplayName;

     Techdump.FSharpRecord fsharpRecordModified = null;
     fsharpRecordTimings.Add(TimeAction(() =>
     {
      fsharpRecordModified = fsharpRecordOriginal.SetDisplayName(item);
     }));
     if (fsharpRecordModified != null)
      s = fsharpRecordModified.DisplayName;

     CSharpImmutableConstructorList csharpConstructorModified = null;
     csharpConstructorTimings.Add(TimeAction(() =>
     {
      csharpConstructorModified = csharpConstructorOriginal.SetDisplayName(item);
     }));
     if (fsharpRecordModified != null)
      s = csharpConstructorModified.DisplayName;

     CSharpImmutableModifyPattern csharpModifyModified = null;
     csharpModifyTimings.Add(TimeAction(() =>
     {
      csharpModifyModified = csharpModifyOriginal.SetDisplayName(item);
     }));
     if (csharpModifyModified != null)
      s = csharpModifyModified.DisplayName;
    }
   }
   Log($"CSharpPoco\tIterations:\t{iterations}\tAverage:\t{csharpPocoTimings.Average:0.000}\tticks\tTotal:\t{csharpPocoTimings.Total:0.000}\tticks");
   Log($"FSharpRecord\tIterations:\t{iterations}\tAverage:\t{fsharpRecordTimings.Average:0.000}\tticks\tTotal:\t{fsharpRecordTimings.Total:0.000}\tticks");
   Log($"CSharpImmutableConstructorList\tIterations:\t{iterations}\tAverage:\t{csharpConstructorTimings.Average:0.000}\tticks\tTotal:\t{csharpConstructorTimings.Total:0.000}\tticks");
   Log($"CSharpImmutableModifyPattern\tIterations:\t{iterations}\tAverage:\t{csharpModifyTimings.Average:0.000}\tticks\tTotal:\t{csharpModifyTimings.Total:0.000}\tticks");
  }
  catch (Exception ex)
  {
   Log($"Fail\tDataCount\t2\tIterations:\t{iterations}\tFailed\t{ex.Message}");
  }
 }


 private float TimeAction(Action action)
 {
  var sw = Stopwatch.StartNew();
  action();
  sw.Stop();
  return sw.ElapsedTicks;
 }

 private void Log(string s)
 {
  Console.WriteLine(s);
  File.AppendAllText(@"c:\temp\enumToStringTest.txt", $"{s}{Environment.NewLine}");
 }
 
}

And the RunningAverage class from a previous post.

Results

ImmutabilityPerformance
Iterations
Average (ticks)
Total (ticks)
CSharpPoco 1000000 0.090 537402
FSharpRecord 1000000 0.121727156
CSharpImmutableConstructorList 1000000 0.120 720220
CSharpImmutableModifyPattern 1000000 0.161 965545

Here we can see that the poco baseline test is the fastest by far. Using the F# Record type and C# locked down object with constructor are pretty much equal in execution. The modify pattern in the C# code really drops the performance but gives more readable code, at least if we have long constructor lists in objects.

Rewritten increment example

Let's go back and look at the first increment example again and try to rewrite it with immutability
public class CSharpImmutable
{
    public readonly uint Value;
    public CSharpImmutable(uint value)
    {
        Value = value;
    }
    public CSharpImmutable Increment()
    {
        return new CSharpImmutable(Value + 1);
    }
    public uint GetNext()
    {
        return Value + 1;
    }
}

And in F#
type FsharpIncrement =
    {
        Value : uint32    
    }
    member this.Increment () =
        { this with Value = this.Value + 1u }
    member this.GetNext () =
        this.Value + 1u

Conclusions

In my opinion Immutable objects are the way to go if you want to write maintainable code for the long run, what technique you choose is entirely up to you. There are probably other ways to achieve the same that I don't know about, if you have ideas please post a comment!

After I started writing F# code, and started getting all the immutability features for free and especially the with keyword for records has persuaded me to start writing all my core business models in F#.
let point' = { point with X = 2; }
In my eyes, that line of code just there, is so damn beautiful.



All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment or share a link, not required but appreciated! :)

Friday, September 28, 2018

FSharp Enum ToString vs. C# Enum Dictionary Lookup for Localization


I was reading Tao Liu's post regarding enums with space for localization to save time and I just had to run a test if this really was faster then defining a lookup table?


On my computer
--------------------------------------
... FsharpEnumToString vs. CSharpEnumDictionaryLookup
FSharpToString  Iterations: 10000000;  Average: 0,287 ticks; Total: 14374450,000 ticks;
CSharpLookup    Iterations: 10000000;  Average: 0,134 ticks; Total: 6688315,000 ticks;

So, a simple dictionary lookup is still faster then ToString of a F# enum.
So I'll guess my team will keep the localization as data files / database table that is loaded at runtime into a variable. This way we can outsource the translations to other teams and specialists while keeping the code clean. A misspelled enum member by a tired developer does not result in a hotfix of an application with new builds etc, just a data file update in runtime.


The code used to perform this test:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using fsharp.techdump;

namespace techdump.console.Tests
{
    public class FsharpEnumToStringVsLookup
    {
        private Dictionary<CSharpEnum, string> _lookup = new Dictionary<CSharpEnum, string>
        {
            { CSharpEnum.Registration, "Registration" },
            { CSharpEnum.UnderReview, "Under Review" },
            { CSharpEnum.Approval, "Approval" },
            { CSharpEnum.Release, "Release" },
            { CSharpEnum.PostRelase, "Post Release" }
        };
        private enum CSharpEnum
        {
            Registration = 0,
            UnderReview = 1,
            Approval = 2,
            Release = 3,
            PostRelase = 4,
        }
        public void Execute()
        {
            Log("--------------------------------------");
            Log("... FsharpEnumToString vs. CSharpEnumDictionaryLookup");
            ExecuteTest(10_000_000);
        }
        
        
        private void ExecuteTest(int iterations)
        {
            string s = string.Empty;
            try
            {
                var index = new List<int> { 0, 1, 2, 3, 4 };
                var fsharpToStringTimings = new RunningAverage();
                var csharpLookupTimings = new RunningAverage();
                for (int i = 0; i < iterations; i++)
                {
                    for (int dataIndex = 0; dataIndex < index.Count; dataIndex++)
                    {
                        var item = index[dataIndex];
                        var fsharpEnumMember = (Techdump.FsharpEnum)item;
                        fsharpToStringTimings.Add(TimeAction(() =>
                        {
                            s = item.ToString();
                        }));
                        if (!string.IsNullOrEmpty(s))
                            s = string.Empty;
                        var csharpEnumMember = (CSharpEnum)item;
                        csharpLookupTimings.Add(TimeAction(() =>
                        {
                            s = _lookup[csharpEnumMember];
                        }));
                        if (!string.IsNullOrEmpty(s))
                            s = string.Empty;
                    }
                }
                Log($"FSharpToString\tIterations:\t{iterations}\tAverage:\t{fsharpToStringTimings.Average:0.000}\tticks\tTotal:\t{fsharpToStringTimings.Total:0.000}\tticks");
                Log($"CSharpLookup\tIterations:\t{iterations}\tAverage:\t{csharpLookupTimings.Average:0.000}\tticks\tTotal:\t{csharpLookupTimings.Total:0.000}\tticks");
            }
            catch (Exception ex)
            {
                Log($"Fail\tDataCount\t2\tIterations:\t{iterations}\tFailed\t{ex.Message}");
            }
        }


        private float TimeAction(Action action)
        {
            var sw = Stopwatch.StartNew();
            action();
            sw.Stop();
            return sw.ElapsedTicks;
        }

        private void Log(string s)
        {
            Console.WriteLine(s);
            File.AppendAllText(@"c:\temp\enumToStringTest.txt", $"{s}{Environment.NewLine}");
        }
        
    }
    
}

FSharp Enum defined as follows:
namespace fsharp.techdump

module Techdump =
    type public FsharpEnum =
        Registration = 0
        | ``Under Review``=1
        | Approval = 2
        | Release = 3
        | ``Post Release`` = 4


And the RunningAverage class from a previous post.


Wednesday, September 26, 2018

GeoCoordinateWatcher and GMap.NET

Playing around a little with the GMap.NET - Maps For Windows and figured I would use my computers location as a startup point for the map view.
Ended up encapsulating System.Device.Location.GeoCoordinateWatcher in a static class to get around the NaN coordinates returned from an uninitialized GeoCoordinateWatcher as it turns out that GMap.NET doesn't like NaN at all.
using System.Device.Location;

namespace dreamstatecoding.blogspot.com
{
    public static class GeoProvider
    {
        private static GeoCoordinateWatcher _watcher = new GeoCoordinateWatcher();
        public static bool IsInitialized { get; private set; }

        static GeoProvider()
        {
            _watcher.PositionChanged += _watcher_PositionChanged;
            _watcher.Start();
        }
        public static void Cleanup()
        {
            _watcher.Stop();
            _watcher.Dispose();
            _watcher = null;
        }
        private static void _watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            IsInitialized = true; ;
        }

        public static GeoCoordinate GetCoordinates()
        {
            var coordinates = _watcher.Position.Location;
            if (double.IsNaN(coordinates.Latitude))
                return new GeoCoordinate(0, 0);
            return coordinates;
        }
    }
}

Usage: Giving the provider some time to get hold of the first coordinates. If it doesn't, the coordinate returned would be longitude:0;latitude:0. So pretty much in the ocean outside of Africa.
private void SetupMap()
{  
 for(int i = 0; i < 1000; i++)
 {
  if (GeoProvider.IsInitialized)
   break;
  Thread.Sleep(151);
 }
 var coordinates = GeoProvider.GetCoordinates();
 gmap.MapProvider = GMapProviders.GoogleMap;
 gmap.Position = new PointLatLng(coordinates.Latitude, coordinates.Longitude);
 gmap.MinZoom = 0;
 gmap.MaxZoom = 24;
 gmap.Zoom = 15;
}

It seems that the thread in the GeoCoordinateWatcher is not set to Background as default. So I just force kill it when the application shuts down for now. I put this in my Program.cs file in the WinForms project:
[STAThread]
static void Main()
{
 Application.ApplicationExit += Application_ApplicationExit;
 
 Application.EnableVisualStyles();
 Application.SetCompatibleTextRenderingDefault(false);
 Application.Run(new Form1());
}        
private static void Application_ApplicationExit(object sender, EventArgs e)
{
 GeoProvider.Cleanup();
}


All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment or share a link, not required but appreciated! :)

Wednesday, March 21, 2018

Functional Adventures in F# - Getting rid of loops


Solving problems without loops.....

This post is part of a series:
Functional Adventures in F# - A simple planner
Functional Adventures in F# - Calling F# from C#
Functional Adventures in F# - Using Map Collections
Functional Adventures in F# - Application State
Functional Adventures in F# - Types with member functions
Functional Adventures in F# - Getting rid of loops
Functional Adventures in F# - Getting rid of temp variables
Functional Adventures in F# - The MailboxProcessor
Functional Adventures in F# - Persisting Application State
Functional Adventures in F# - Adding Snapshot Persisting
Functional Adventures in F# - Type-safe identifiers
Functional Adventures in F# - Event sourcing lessons learned

This time lets look at a real issue when coming from an imperative language and trying functional programming.
The example problem (that I crashed into when rewriting some game logic in F#) is that of spawning new Ships in a space game. We do not want to spawn 2 ships on top of each other, so we generate the default spawning coordinate and then test if it is safe to use, if not we move the ship a bit and try again....

How I solved it in C#..
private Ship FindClosestFreeCoordinate(ImmutableList<Fleet> state, Ship newShip)
{
    var shipsWithinSafetyDistance = ShipsWithinSafetyDistance(state, newShip);
    while (shipsWithinSafetyDistance.Any())
    {
        var newCoordinates = newShip.Coordinates.Position.Add(Vector3.UnitXVector);
        newShip = newShip.Modify(coordinates: newShip.Coordinates.Modify(position: newCoordinates));
        shipsWithinSafetyDistance = ShipsWithinSafetyDistance(state, newShip);
    }
    return newShip;
}

private List<Ship> ShipsWithinSafetyDistance(ImmutableList<Fleet> state, Ship newShip)
{
    return (from fleet in state
        from
            ship in fleet.Ships
        where
            ship.Distance(newShip) < 5
        select ship).ToList();
}

Translating the ShipsWithinSafetyDistance function is no problem. We just use the Map.filter function...
static member private shipsWithinSafetyDistance (unit:Unit) (state:UnitStore) =
    Map.filter (fun key value -> unit.distanceToUnit value < 5.0) state.Units
Ah, yes.. I switched from a ImmutableList in C# to a Map in F#, just to keep things interesting (and to get faster Key lookups)


So, the tricky part here is the while loop. Most loops can be rewritten with Map/List functions like map, filter and fold etc... But this time I don't see how to use them as I don't have a Collection of any sort here so my brain keeps yelling "Write a loooooop", as that is the way I have solved this kind of problems for the past 20+ years... So...
How should we do it in F#??? We have some other constructs to use that fit the functional idea better.

static member private findClosestFreeCoordinate (unit:Unit) (state:UnitStore) =
 let rec findClosestFreeCoordinateRecursive (unit:Unit) (state:UnitStore) = 
  let shipsWithinSafetyDistance = shipsWithinSafetyDistance unit state
  match shipsWithinSafetyDistance with
  | a when a.IsEmpty -> unit
  | _ ->  let newUnit = { unit with Coordinates = unit.Coordinates + Vector3.UnitX }
    findClosestFreeCoordinateRecursive newUnit state
 findClosestFreeCoordinateRecursive unit state
Recursion!
At least for this problem, it seems to be a good option. Here we define a function, findClosestFreeCoordinateRecursive with the rec keyword to let the compiler know that it will be called recursively. In the function body we match the result list with IsEmpty and return the input value or else call the recursive function with a new copy of the unit with new coordinates.

Call stack.. Is there a risk for stack overflow with this?
Lets open the dll output with ILSpy to check what actually goes on behind the scenes
ILSpy of F# Recursive Function
Turns out, that the current F# compiler in the background uses a while loop. The key here is that we do not, instead we define a short and concise function where we state what it is that we want done, how it is solved behind the scene in detail is not up to us. At some point, there is always someone that needs to write the ifs and loops, but lets keep them away from the application code that we write.

So there, lets move the last shipsWithinSafetyDistance to inner scope of our function and we are set
static member private findClosestFreeCoordinate (unit:Unit) (state:UnitStore) =
 let shipsWithinSafetyDistance (unit:Unit) (state:UnitStore) =
  Map.filter (fun _ value -> unit.distanceToUnit value < 50.0) state.Units
 let rec findClosestFreeCoordinateRecursive (unit:Unit) (state:UnitStore) = 
  let shipsWithinSafetyDistance = shipsWithinSafetyDistance unit state
  match shipsWithinSafetyDistance with
  | a when a.IsEmpty -> unit
  | _ ->  let newUnit = { unit with Coordinates = unit.Coordinates + Vector3.UnitX }
    findClosestFreeCoordinateRecursive newUnit state
 findClosestFreeCoordinateRecursive unit state

All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment, not required but appreciated! :)

Hope this helps someone out there!


Sunday, March 11, 2018

Functional Adventures in F# - Calling F# from C#


I have quite a lot of code lying around that is written in C# and going into a new project, the most natural is to start with C# as the core application. Now when I am exploring the functional paradigm with F#, I still want to be able to call all the F# code from C#. In other words, the most natural is to add new functionality to my existing applications using F# and not try to accomplish the 'everything shall be written in F#' utopia.

This post is part of a series:
Functional Adventures in F# - A simple planner
Functional Adventures in F# - Calling F# from C#
Functional Adventures in F# - Using Map Collections
Functional Adventures in F# - Application State
Functional Adventures in F# - Types with member functions
Functional Adventures in F# - Getting rid of loops
Functional Adventures in F# - Getting rid of temp variables
Functional Adventures in F# - The MailboxProcessor
Functional Adventures in F# - Persisting Application State
Functional Adventures in F# - Adding Snapshot Persisting
Functional Adventures in F# - Type-safe identifiers
Functional Adventures in F# - Event sourcing lessons learned

So, first off. We need to give our C# project the knowledge of F# types. So lets Nuget the FSharp.Core package and we are all set!

After that, calling the F# code from C# is easy. Lets use the code that we wrote in the last post with the Planner module.

We had 2 different types described in the module, the ScheduledAction that was a record type and the Schedule that was a list of ScheduledActions.

Lets look at some code:
using System;
using Microsoft.FSharp.Collections;

namespace app.Components
{
    public class Main
    {
        private FSharpList<Planner.ScheduledAction> _schedule;
        public bool Shutdown { get; set; }

        public void MainLoop()
        {
            while (!Shutdown)
            {
                var executableActions = Planner.getExecutableActions(DateTime.UtcNow, _schedule);
                foreach (var action in executableActions)
                {
                    Execute(action);
                    _schedule = Planner.removeFromSchedule(action, _schedule);
                }
            }
        }

        private void Execute(Planner.ScheduledAction action)
        {
            // execute business logic here
        }
    }
}

As you an see, the Schedule type did not follow through as I expected. It is exposed a FSharpList<ScheduledAction>, i.e. we need to write the whole thing instead of just using Schedule. Other then that there seems to be nothing strange here. Planner is identified by intellisense as a class.

If we try to modify the name of the ScheduledAction that we have received from the F# code, the code will not compile but instead show you the error
Property or indexer 'Planner.ScheduledAction.name' cannot be assigned to -- it is read only
This is due to that everything defined in F# is immutable (well almost everything).
So that is that, it just reference the FSharp.Core and your F# project from your C# project and you are good to go.

All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment, not required but appreciated! :)

Hope this helps someone out there!

Wednesday, March 7, 2018

OpenGL 4 with OpenTK in C# Part 15: Object picking by mouse


This time we will go through how to use the mouse to pick objects on the screen.

This is part 15 of my series on OpenGL4 with OpenTK.
For other posts in this series:
OpenGL 4 with OpenTK in C# Part 1: Initialize the GameWindow
OpenGL 4 with OpenTK in C# Part 2: Compiling shaders and linking them
OpenGL 4 with OpenTK in C# Part 3: Passing data to shaders
OpenGL 4 with OpenTK in C# Part 4: Refactoring and adding error handling
OpenGL 4 with OpenTK in C# Part 5: Buffers and Triangle
OpenGL 4 with OpenTK in C# Part 6: Rotations and Movement of objects
OpenGL 4 with OpenTK in C# Part 7: Vectors and Matrices
OpenGL 4 with OpenTK in C# Part 8: Drawing multiple objects
OpenGL 4 with OpenTK in C# Part 9: Texturing
OpenGL 4 with OpenTK in C# Part 10: Asteroid Invaders
Basic bullet movement patterns in Asteroid Invaders
OpenGL 4 with OpenTK in C# Part 11: Mipmap
OpenGL 4 with OpenTK in C# Part 12: Basic Moveable Camera
OpenGL 4 with OpenTK in C# Part 13: IcoSphere
OpenGL 4 with OpenTK in C# Part 14: Basic Text
OpenGL 4 with OpenTK in C# Part 15: Object picking by mouse

Introduction

As I've written in previous posts, I'm still not that good with all the math etc. writing these posts is a way for me to learn and hopefully someone else out there finds it useful as well. This time I found a great post that goes into the details of ray-casting to pick objects in 3D space over at Anton Gerdelan's blog: antongerdelan.net/opengl/raycasting.html

I've taken his base solution and made it work with the code-base that we use in this tutorial series. It did not work directly, so a lot of time was spent on what was going wrong.
So, now that credit is where it belongs, lets look at the code.

Code

First we want to calculate the ray from our camera location based on the mouse click on the screen. So first we need to subscribe to mouse events. So in our OnLoad method, we will add the following event handler.
MouseUp += OnMouseUp;

In our event handler we will check that it is the correct button and send the coordinates to the actual object picking method
private void OnMouseUp(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
    if (mouseButtonEventArgs.Button != MouseButton.Left)
        return;
    PickObjectOnScreen(mouseButtonEventArgs.X, mouseButtonEventArgs.Y);
}

This is the method that calculates the ray from the camera and into the screen. It takes the mouse coordinates and then backtracks the transformations back to world space. For more details, check antongerdelan.net/opengl/raycasting.html.
private void PickObjectOnScreen(int mouseX, int mouseY)
{
    // heavily influenced by: http://antongerdelan.net/opengl/raycasting.html
    // viewport coordinate system
    // normalized device coordinates
    var x = (2f * mouseX) / Width - 1f;
    var y = 1f - (2f * mouseY) / Height;
    var z = 1f;
    var rayNormalizedDeviceCoordinates = new Vector3(x, y, z);

    // 4D homogeneous clip coordinates
    var rayClip = new Vector4(rayNormalizedDeviceCoordinates.X, rayNormalizedDeviceCoordinates.Y, -1f, 1f);

    // 4D eye (camera) coordinates
    var rayEye = _projectionMatrix.Inverted() * rayClip;
    rayEye = new Vector4(rayEye.X, rayEye.Y, -1f, 0f);

    // 4D world coordinates
    var rayWorldCoordinates = (_camera.LookAtMatrix.Inverted() * rayEye).Xyz;
    rayWorldCoordinates.Normalize();
    FindClosestAsteroidHitByRay(rayWorldCoordinates);
}

After that we need to add a method that checks if the game object has been hit by the ray. I added this to the AGameObject class so that all game objects can be picked. Basically we begin by checking if the origin of the ray is inside the sphere that we are checking against. After that we check if the ray is pointing away from the object and lastly we perform Pythagorean method to determine if the ray is within the radius of the sphere that we are looking at. This ray method is something that I've had lying around for a while and used for various purposes.

public double? IntersectsRay(Vector3 rayDirection, Vector3 rayOrigin)
{
    var radius = _scale.X;
    var difference = Position.Xyz - rayDirection;
    var differenceLengthSquared = difference.LengthSquared;
    var sphereRadiusSquared = radius * radius;
    if (differenceLengthSquared < sphereRadiusSquared)
    {
        return 0d;
    }
    var distanceAlongRay = Vector3.Dot(rayDirection, difference);
    if (distanceAlongRay < 0)
    {
        return null;
    }
    var dist = sphereRadiusSquared + distanceAlongRay * distanceAlongRay - differenceLengthSquared;
    var result = (dist < 0) ? null : distanceAlongRay - (double?)Math.Sqrt(dist);
    return result;
}

The above method is called from the following that iterates all the objects currently active in the game and then tries to find the object that is closest (if there are many) to the origin of the ray.

private void FindClosestAsteroidHitByRay(Vector3 rayWorldCoordinates)
{
    AGameObject bestCandidate = null;
    double? bestDistance = null;
    foreach (var gameObject in _gameObjects)
    {
        if (!(gameObject is SelectableSphere) && !(gameObject is Asteroid))
            continue;
        var candidateDistance = gameObject.IntersectsRay(rayWorldCoordinates, _camera.Position);
        if (!candidateDistance.HasValue)
            continue;
        if (!bestDistance.HasValue)
        {
            bestDistance = candidateDistance;
            bestCandidate = gameObject;
            continue;
        }
        if (candidateDistance < bestDistance)
        {
            bestDistance = candidateDistance;
            bestCandidate = gameObject;
        }
    }
    if (bestCandidate != null)
    {
        switch (bestCandidate)
        {
            case Asteroid asteroid:
                _clicks += asteroid.Score;
                break;
            case SelectableSphere sphere:
                sphere.ToggleModel();
                break;
        }
    }
}

As you can see above, we have introduced a new GameObject for this part of the tutorial series, the SelectableSphere. It looks like the following:
public class SelectableSphere : AGameObject
{
    private ARenderable _original;
    private ARenderable _secondaryModel;
    public SelectableSphere(ARenderable model, ARenderable secondaryModel, Vector4 position, Vector4 direction, Vector4 rotation)
        : base(model, position, direction, rotation, 0)
    {
        _original = model;
        _secondaryModel = secondaryModel;
    }


    public override void Update(double time, double delta)
    {
        _rotation.Y = (float) ((time + GameObjectNumber) * 0.5);
        var d = new Vector4(_rotation.X, _rotation.Y, 0, 0);
        d.Normalize();
        _direction = d;
        base.Update(time, delta);
    }

    public void ToggleModel()
    {
        if (_model == _original)
            _model = _secondaryModel;
        else
            _model = _original;
    }
}
Basically an endlessly rotating sphere that will toggle its model when selected.

And lastly we generate these spheres in 2 layers in the OnLoad method in our MainWindow to have stuff on screen that can be selected.
var maxX = 2.5f;
var maxY = 1.5f;
for (float x = -maxX; x < maxX; x += 0.5f)
{
    for (float y = -maxY; y < maxY; y += 0.5f)
    {
        _gameObjects.Add(_gameObjectFactory.CreateSelectableSphere(new Vector4(x, y, -5f, 0)));
    }
}
for (float x = -maxX; x < maxX; x += 0.65f)
{
    for (float y = -maxY; y < maxY; y += 0.65f)
    {
        _gameObjects.Add(_gameObjectFactory.CreateSelectableSphereSecondary(new Vector4(x, y, -6f, 0)));
    }
}


End results


For the complete source code for the tutorial at the end of this part, go to: https://github.com/eowind/dreamstatecoding

So there, thank you for reading. Hope this helps someone out there : )



Thursday, December 21, 2017

WinForms TextBox Get as Double or Integer

I always end up returning to Windows Forms when I want to code some tool or prototype an idea. This time I just want to share two extension methods for retrieving the contents of a TextBox as an Integer or a Double.

public static double AsDouble(this TextBox textBox)
{
 var s = textBox.Text.Replace(",", ".").Trim();
 return double.TryParse(s, out var d) ? d : double.NaN;
}
public static int AsInt(this TextBox textBox)
{
 var s = textBox.Text.Trim();
 return int.TryParse(s, out var i) ? i : 0;
}

The colon to period replacement is to ensure that Swedish formatting works with the default parser. No guarantee that it will work with all cultures.


All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment, not required but appreciated! :)

Hope this helps someone out there!

Wednesday, November 15, 2017

Distances to human readable text in C#


Needed a function that converts a double to a human readable distance in my latest project, ended up writing the following function.
Input argument is in meters.
For values less than 1 meter, the result is given as centimeters.
For values up to 10 km, the values are given with one decimal.
Values up to one tenth of an Astronomical Unit are given as kilometers.
Values between one tenth of an Astronomical Unit and one tenth of a Parsec are given in Astronimical Units.
Values larger then one tenth of a Parsec are given in Parsecs.

Example output
Input
Output
0.533
53 cm
-1 -1 m
1 1 m
3,08568E+16 1.0 pc
3,08568E+17 10.0 pc
1,49598E+12 10.0 AU
1000 1.0 km
10000 10 km


The code for you to use as you please:
public const double AstronomicalUnit = 149597870700;
// https://en.wikipedia.org/wiki/Parsec
public static double Parsec { get; } = (648000 / Math.PI) * AstronomicalUnit;
public static string ToReadableDistanceFavorParsec(double meters, CultureInfo cultureInfo = null)
{
    if (cultureInfo == null)
        cultureInfo = CultureInfo.InvariantCulture;
    var sign = meters.Sign() > 0 ? string.Empty : "-";
    meters = meters.Abs();
    if (meters > (Parsec / 10))
    {
        return $"{sign}{(meters / Parsec).ToString("0.0", cultureInfo)} pc";
    }

    if (meters > (AstronomicalUnit / 10))
    {
        return $"{sign}{(meters / AstronomicalUnit).ToString("0.0", cultureInfo)} AU";
    }

    if (meters > (997))
    {

        if (meters >= (10000))
        {
            return $"{sign}{(meters / 1000).ToString("0", cultureInfo)} km";
        }
        return $"{sign}{(meters / 1000).ToString("0.0", cultureInfo)} km";
    }

    if (meters < 1)
    {
        return $"{sign}{meters * 100:0} cm";
    }
    return sign + meters.ToString("0") + " m";
}


All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment, not required but appreciated! :)

Hope this helps someone out there!

Friday, October 13, 2017

System.Math extension methods

Why

Because I've lately started to think a little more functional, this also allows for nice chaining of calls to the Math class.

How to use

Say you want to calculate the angle between 2 vectors by taking arc cosine of our dot product to give us the angle:
With normal Math usage..
var dot = vector1.X* vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z;
double radians = Math.Acos(dot);
Same example with our extensions
var dot = vector1.X* vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z;
double radians = dot.Acos();

The above example but with a method to calculate the dot product.
double radians = vector1.Dot(vector2).Acos();


Code for your pleasure

public static class MathExtensions
{
    public static decimal Abs(this decimal d)
    {
        return Math.Abs(d);
    }
    public static float Abs(this float d)
    {
        return Math.Abs(d);
    }
    public static double Abs(this double d)
    {
        return Math.Abs(d);
    }
    public static int Abs(this int d)
    {
        return Math.Abs(d);
    }
    public static long Abs(this long d)
    {
        return Math.Abs(d);
    }
    public static short Abs(this short d)
    {
        return Math.Abs(d);
    }
    public static short Abs(this byte d)
    {
        return Math.Abs(d);
    }
    public static decimal Max(this decimal d, decimal x)
    {
        return Math.Max(d, x);
    }
    public static float Max(this float d, float x)
    {
        return Math.Max(d, x);
    }
    public static double Max(this double d, double x)
    {
        return Math.Max(d, x);
    }
    public static int Max(this int d, int x)
    {
        return Math.Max(d, x);
    }
    public static long Max(this long d, long x)
    {
        return Math.Max(d, x);
    }
    public static short Max(this short d, short x)
    {
        return Math.Max(d, x);
    }
    public static short Max(this byte d, byte x)
    {
        return Math.Max(d, x);
    }
    public static decimal Min(this decimal d, decimal x)
    {
        return Math.Min(d, x);
    }
    public static float Min(this float d, float x)
    {
        return Math.Min(d, x);
    }
    public static double Min(this double d, double x)
    {
        return Math.Min(d, x);
    }
    public static int Min(this int d, int x)
    {
        return Math.Min(d, x);
    }
    public static long Min(this long d, long x)
    {
        return Math.Min(d, x);
    }
    public static short Min(this short d, short x)
    {
        return Math.Min(d, x);
    }
    public static short Min(this byte d, byte x)
    {
        return Math.Min(d, x);
    }

    public static int Sign(this decimal d)
    {
        return Math.Sign(d);
    }
    public static int Sign(this float d)
    {
        return Math.Sign(d);
    }
    public static int Sign(this double d)
    {
        return Math.Sign(d);
    }
    public static int Sign(this int d)
    {
        return Math.Sign(d);
    }
    public static int Sign(this long d)
    {
        return Math.Sign(d);
    }
    public static int Sign(this short d)
    {
        return Math.Sign(d);
    }
    public static int Sign(this byte d)
    {
        return Math.Sign(d);
    }
    public static decimal Floor(this decimal d)
    {
        return Math.Floor(d);
    }
    public static double Floor(this float d)
    {
        return Math.Floor(d);
    }
    public static double Floor(this double d)
    {
        return Math.Floor(d);
    }
    public static decimal Round(this decimal d)
    {
        return Math.Round(d);
    }
    public static decimal Round(this decimal d, int x)
    {
        return Math.Round(d, x);
    }
    public static decimal Round(this decimal d, int x, MidpointRounding mr)
    {
        return Math.Round(d, x, mr);
    }
    public static decimal Round(this decimal d, MidpointRounding mr)
    {
        return Math.Round(d, mr);
    }
    public static double Round(this float d)
    {
        return Math.Round(d);
    }
    public static double Round(this double d)
    {
        return Math.Round(d);
    }
    public static double Round(this double d, int x)
    {
        return Math.Round(d, x);
    }
    public static double Round(this double d, int x, MidpointRounding mr)
    {
        return Math.Round(d, x, mr);
    }
    public static double Round(this double d, MidpointRounding mr)
    {
        return Math.Round(d, mr);
    }
    public static decimal Ceiling(this decimal d)
    {
        return Math.Ceiling(d);
    }
    public static double Ceiling(this float d)
    {
        return Math.Ceiling(d);
    }
    public static double Ceiling(this double d)
    {
        return Math.Ceiling(d);
    }
    public static double Acos(this double d)
    {
        return Math.Acos(d);
    }
    public static double Asin(this double d)
    {
        return Math.Asin(d);
    }
    public static double Atan(this double d)
    {
        return Math.Atan(d);
    }
    public static double Atan2(this double d, double x)
    {
        return Math.Atan2(d, x);
    }
    public static double Cos(this double d)
    {
        return Math.Cos(d);
    }
    public static double Cosh(this double d)
    {
        return Math.Cosh(d);
    }
    public static double Exp(this double d)
    {
        return Math.Exp(d);
    }
    public static double Sin(this double d)
    {
        return Math.Sin(d);
    }
    public static double Sinh(this double d)
    {
        return Math.Sinh(d);
    }
    public static double Tan(this double d)
    {
        return Math.Tan(d);
    }
    public static double Tanh(this double d)
    {
        return Math.Tanh(d);
    }
    public static long BigMul(this int a, int b)
    {
        return Math.BigMul(a, b);
    }
    public static double IEEERemainder(this double d, double y)
    {
        return Math.IEEERemainder(d, y);
    }
    public static double Log(this double d)
    {
        return Math.Log(d);
    }
    public static double Log(this double d, double x)
    {
        return Math.Log(d, x);
    }
    public static double Log10(this double d)
    {
        return Math.Log10(d);
    }
    public static double Sqrt(this double d)
    {
        return Math.Sqrt(d);
    }
    public static decimal Truncate(this decimal d)
    {
        return Math.Truncate(d);
    }
    public static double Truncate(this double d)
    {
        return Math.Truncate(d);
    }
    public static double Pow(this double d, double power)
    {
        return Math.Pow(d, power);
    }
}

Quite a lot of overloads, I think I got them all but if you find that I've missed one, please comment on this post and I will add it!

All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment, not required but appreciated! :)

Hope this helps someone out there!


Sunday, October 1, 2017

Functional adventures in .NET C# - Part 2, Application State


This part we will look at how to store and manipulate application/game state in an ordered fashion. This is heavily inspired by the React/Redux web development (javascript) patterns. My thoughts were, why not use the same in my game code as the end results are pretty clean and structured?

This is part 2 of this series. Here are links to all the other posts:
Functional adventures in .NET C# - Part 1, Immutable Objects
Functional adventures in .NET C# - Part 2, Application State

Update 2018-03-15: I only wrote 2 posts on C# functional constructs. And after embarking on a large game project with it I started looking at F#. To read the F# source code of this post, head over to Functional Adventures in F# - Application State

General Idea

At any given point in time, the whole application state is stored in a class named Application State, it consists of different Stores and they in turn consist of the object model for each store. I.e. Fleet Store might contain Fleets that consists of Ships. All updates to the model are routed to the store in the form of Actions. The application state is immutable, meaning that any object that you get a reference to will never mutate into something else (see previous post in this series on Immutable objects)

Add object to a store
Say that you would like to create a new object in Store Y, this would yield in a new instance of Store Y that also contains the new object. And as Store Y belongs to Application State, it would need a new instance of that as well. That still point to the old instances of Store X & Z but a new instance of Y.

Update object in a store
If you in turn would like to update a object that is deeper in the structure inside Store Z, you would create a copy (call the Modify method) on that object. But as it returns a new object, you would have to propagate the change to the parent object (SetItem if it is in the System.Collections.Immutable namespace, or Modify if it is our own) and then propagate it to a new version of the application state object as well.

Remove object from a store
And it is pretty much the same for when you want to remove objects, you remove the object reference from the parent object by calling Remove or Modify depending on if it is a collection or our own object. And then you propagate the change up all the way to a new Application State object.


Code

So, now that we know the general idea lets look at some code. At the moment I decided to only propagate the change to the store and let the ApplicationState class be the entry point to the different stores. So not 100% immutable, only where it counts.. I.e. the model.

Application State

The ApplicationState (or GameState in this case) contains references to all the different stores.
public static class GameState
{
    private static FleetStore _fleetStore;

    public static FleetStore FleetStore
    {
        get
        {
            if(_fleetStore == null)
                _fleetStore = new FleetStore();
            return _fleetStore;
        }
        set
        {
            _fleetStore = value;
        }
    }
}
I decided to have this globally accessible so that the whole game can read the current application state  and dispatch actions from this static context.

Actions

Actions are pretty much POCOs (plain old class objects)
public class CreateFleet
{
    public string Name { get; }
    public CreateFleet(string name)
    {
        Name = name;
    }
}
These are safe objects, if any part of the application wants to change state they are not allowed to call the modify method by themselves. Even if they did they would not be able to propagate the change properly so that it becomes visible. Instead they create an Action object describing the change that they want to be done and send it to the Store.

Stores and Action Handlers

The store holds the immutable state of its model and handles all actions.
First of, lets look at the abstract base class for all of the stores.
public abstract class AStore<TItem>
{
 public ImmutableList<TItem> State { get; protected set; }
 private ImmutableDictionary<Type, Action<object>> _actionHandlers;
 private readonly object _lock = new object();
 public AStore()
 {
  State = ImmutableList<TItem>.Empty;
  _actionHandlers = ImmutableDictionary<Type, Action<object>>.Empty;
 }

 public void HandleAction(object action)
 {
  lock (_lock)
  {
   var actionType = action.GetType();
   var handlers = _actionHandlers;
   if (handlers.TryGetValue(actionType, out var actionHandler))
   {
    actionHandler(action);
   }
  }
 }

 public void HandleActionAsync(object action)
 {
  ThreadPool.QueueUserWorkItem(HandleAction, action);
 }

 protected void AddActionHandler(Type actionType, Action<object> actionHandler)
 {
  _actionHandlers = _actionHandlers.Add(actionType, actionHandler);
 }
}

First of, we have the State stored as a ImmutableList<T>, all changes to objects managed by this store will propagate to this State object and replace it with a new reference. The State is public and is read by the rest of the application.

Secondly we have a dictionary of Action Handlers. Here we can lookup the correct action handler with the help of the Type of the action.

There is only 2 public methods, HandleActionAsync. All it does is to dispatch the action to the threadpool.
The HandleAction is pretty basic, it tries to get an action handler for the object type it received and either dispatches the action to the correct handler or does nothing. All this is done inside a lock to ensure that only 1 thread is writing at a time.
I am not 100% satisfied with this solution to serialize the writes, if you have a better solution please do not hesitate to share in the comments!

There is also only 1 protected method, AddActionHandler. This is used by all sub-classes that inherit from this abstract class to register action handlers that are defined in their code.

Example of concrete store. In this case taken from my space game.
public class FleetStore : AStore<Fleet>
{
 private uint _currentFleetId;
 private uint _currentShipId;
 public FleetStore()
 {
  AddActionHandler(typeof(CreateFleet), CreateFleet);
  AddActionHandler(typeof(RemoveFleet), RemoveFleet);
  AddActionHandler(typeof(CreateShip), CreateShip);
  AddActionHandler(typeof(MoveShipToFleet), MoveShipToFleet);
  AddActionHandler(typeof(SetShipTargetVector), SetShipTargetVector);
 }
Here we see that in the constructor the class registers all action handlers with the help of the AddActionHandler method.

Example of Add action handler
private void CreateFleet(object action)
{
 var a = (CreateFleet) action;
 var fleet = Fleet.Default.Modify(_currentFleetId++, a.Name);
 State = State.Add(fleet);
}
Here we use the Fleet.Default reference (instead of calling new) to create a new immutable fleet and then call Add on the State list. And finally replace the State with the new State so that it sticks.

Example of Remove action handler
private void RemoveFleet(object action)
{
 var a = (RemoveFleet)action;
 var item = State.FirstOrDefault(x => x.Id == a.Id);
 State = State.Remove(item);
}
Here we find the item to remove with a query and then call Remove on the state list and replace the old state with the new state.

And finally an example of Update action handler
private void SetShipTargetVector(object action)
{
 var a = (SetShipTargetVector)action;
 var originalFleet = State.FirstOrDefault(x => x.Id == a.FleetId);
 var originalShip = originalFleet.Ships.FirstOrDefault(x => x.Id == a.ShipId);
 
 var ship = originalShip.Modify(targetCoordinates: a.Target);
 var ships = originalFleet.Ships.SetItem(originalFleet.Ships.IndexOf(originalShip), ship);
 var fleet = originalFleet.Modify(ships: ships);
 State = State.SetItem(State.IndexOf(originalFleet), fleet);
}
This is an update of a field a little bit deeper in the object structure.
First we need to find the Fleet from the state list.
After that we find the ship from the fleets list of ships.
Then we modify the ship and store the new state in a new variable.
Then we use the old ship to find the index in the list that we want to replace with the new ship. We store the new immutable list in a new variable.
After that we modify the fleet and set the new list of ships with the Modify command and store the new fleet.
Lastly we update the State with SetItem and replace the old State with the new one.


Hope this helps someone out there getting started with immutable application state in C#, or at least getting some new ideas. Thank you for reading, here's a video of one of our cats