Wednesday, 18 February 2015

Realistic planet Earth Shader for Unity 3d - Massive update

For some time now my realistic planet Earth shader is available at Unity 3d store :
https://www.assetstore.unity3d.com/#/content/23363

Video : https://www.youtube.com/watch?v=wVm_hW5zVpg

Current demo : http://abdeveloper.com/earth/unityprojects.html

I want to thank you all for support and decided to release huge update that will contain:
30 new randomly generated Earth like planets + 30 Real time Night transitions
10 new clouds

I also added facility to switch between planets, change clouds and increase zoom rate.







Tuesday, 10 February 2015

Using reflection to dynamically set the value on the class property in ASP.NET MVC

We have a situation where we received some data from API and we save each file into NameValueCollection. Each property match our class property, so we want to use reflection to dynamically set values for our class from values in NameValueCollection. This is very fast and easy way to not repeat ourselves when mapping values from one object to another.

I used unit test to demonstrate functionality. 
class PolicyManager
    {
        public string ImportJobTypeID { get; set; }
        public string ImportDate { get; set; }
        public string ImportSourceID { get; set; }
        public string APIUserID { get; set; }
        public string APIUserKey { get; set; }
        public string ImportTypeID { get; set; }
        public string ImportUID { get; set; }
        public string Title { get; set; }
        public string FirstName { get; set; }
        public string Surname { get; set; }
        public string Company { get; set; }
        public string Tel { get; set; }
        public string Email { get; set; }
        public string DOB { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }

        public static NameValueCollection RetrieveDataFromAPIMockUp()
        {
            dynamic values = new NameValueCollection() {
                {"ImportJobTypeID", "1"},
                {"ImportDate", DateTime.Today.ToString()},
                {"ImportSourceID", "1"},
                {"APIUserID", "7"},
                {"APIUserKey", "f4a03091a6a505d10fdebeb707d59e42"},
                {"ImportTypeID", "3"},
                {"ImportUID", DateTime.Now.ToString()},
                {"Title", "Mr"},
                {"FirstName", "Adam"},
                {"Surname", "Black"},
                {"Company", "AbDeveloper.com"},
                {"Tel", "07817 458784"},
                {"Email", "ab@example.com"},
                {"DOB", "10/04/1974"},
                {"Address1", "36 Portland"},
                {"Address2", "Avenue"}
              
            };

            return values;
        }
    }

Because we know exactly what properties we are getting from API it is ok to create a class that matches those properties.
Static method RetrieveDataFromAPIMockUp will generate some dummy data(for test purposes only, this is what we would get from API).

Now simple test.

{
        [TestMethod]
        public void TestReflection()
        {
            PolicyManager pManager = new PolicyManager();

            NameValueCollection values = PolicyManager.RetrieveDataFromAPIMockUp();

            foreach (var value in values)
            {
                PropertyInfo propInfo = typeof(PolicyManager).GetProperty(value.ToString());
                if (propInfo != null)
                {
                    propInfo.SetValue(pManager, values[value.ToString()]);
                }
            }
        }
    }

Pic 1 shows the result and confirm that method works as expected.
If API will change and send more properties our method will still works but will ignore it.

Using reflection to dynamically set the value on the class property in ASP.NET MVC
pic 1

Saturday, 17 January 2015

Adding Existing Database Diagram Using Linq To Sql in VS 2013 ASP.NET MVC Video




Very simple way of getting database diagram to be printed on the screen showing all the column names and relationship between tables.
I used Visual Studio 2013 and MVC web application, but principle should work with different VS versions and project types.

Friday, 9 January 2015

Combining constructors in C# - Cascading constructors

We have a basic Address class.

public class Address
{
public Guid addressId { get; set; }
public string houseNumber {get;set;}
public string additionalAddressInfo { get; set; }
public string roadName {get;set;}
public string town { get; set; }
public float? latitude { get; set; }
public float? longitude { get; set; }


   public Address(string houseNumber, string additionalAddressInfo, string roadName, string town, float? latitude, float? longitude)
   {
   this.addressId = System.Guid.NewGuid();
   this.houseNumber = houseNumber;
   this.additionalAddressInfo = additionalAddressInfo;
   this.roadName = roadName;
   this.town = town;
   this.latitude = latitude;
   this.longitude = longitude;
   }


   public Address(AddressFromCSV addressFromCSV) : this(addressFromCSV.houseNumber, addressFromCSV.additionalAddressInfo,
   addressFromCSV.roadName,addressFromCSV.town,addressFromCSV.latitude,addressFromCSV.longitude)
   {
   }
}

and additional class that inherits from Address class.
public class AddressFromCSV : Address
{
   public string source { get; set; }
   public DateTime csvUploadedDate { get; set; }
   public string uploadedBy { get; set; }
   public string browserType { get; set; }
}
We are using AddressFromCSV  when uploading csv file with addresses.

We want to create a new Address object from AddressFromCSV class. There are few ways of doing that.
We can create new new Address and pass all fields from AddressFromCSV class.
Address address = new Address(addressFromCSV.houseNumber, addressFromCSV.additionalAddressInfo, addressFromCSV.roadName, addressFromCSV.town, addressFromCSV.latitude, addressFromCSV.longitude);
Or we can use cascading constructor and pass whole AddressFromCSV class to Address constructor.
We already defined constructor in Address that will expecAddressFromCSV class so all we have to do is to pass this class.

Address address = new Address(addressFromCSV);
As you can see second method is much cleaner and if we want to change something in the future we have to do it only in one place - in Address constructor.


Monday, 10 November 2014

2# Twisted lasers - Reflecting laser beam

For the last couple of evenings (after daily job as developer) I was working on Twisted lasers game, exactly on laser reflection. As a player you have ability to rotate mirror and depends on mirror rotation laser beam will be reflected. 
For laser beam I used line renderer. 
To find out if an object is placed on laser beam I used Physics.LineCast.
If object is mirror we want to instantiate new line renderer where initial position is hit point and destination position depends on laser beam origin direction. 



I know the code is a bit dirty, not optimized and refactored, but this is just initial mock up and hopefully find better solution.

LateUpdate function:

if(myhit.transform.tag == "Mirror")
   {
    // depends on X rotation of mirror object, manipulate laser beam

    this.lineRenderer.SetPosition(1, myhit.transform.position);
    myhit.transform.tag = "OnLaser";
    GameObject lr = Instantiate(this.gameObject, originBeam, transform.rotation) as GameObject;

    Vector3 reflectVector = CalculateReflectVector(myhit.transform, originBeam);

    lr.GetComponent().SetPosition(0, myhit.transform.position);
    lr.GetComponent().SetPosition(1, reflectVector);

    lr.GetComponent().originBeam = myhit.transform.position;
    lr.GetComponent().directionBeam = reflectVector;

    laserBeamAdded = true;

   }

public Vector3 CalculateReflectVector(Transform hitBeam, Vector3 originBeam)
 {
  // Calculate second line renderer Vector 3
  if (originBeam.y < hitBeam.position.y) {
    Debug.Log ("Laser under");
    Debug.Log (hitBeam.transform.eulerAngles.z);
    // origin laser under target
    if ((int)hitBeam.transform.eulerAngles.z == 45) {
      return new Vector3 (hitBeam.transform.position.x + laserOffset, hitBeam.transform.position.y, hitBeam.transform.position.z);
    } else {
      return new Vector3 (hitBeam.transform.position.x - laserOffset, hitBeam.transform.position.y, hitBeam.transform.position.z);
    }
  } else if (originBeam.y > hitBeam.position.y) {
    Debug.Log ("Laser top");
    // origin laser at the top of the target
    if ((int)hitBeam.transform.eulerAngles.z == 45) {
      return new Vector3 (hitBeam.transform.position.x - laserOffset, hitBeam.transform.position.y, hitBeam.transform.position.z);
    } else {
      return new Vector3 (hitBeam.transform.position.x + laserOffset, hitBeam.transform.position.y, hitBeam.transform.position.z);
    }
  } else if (originBeam.x < hitBeam.position.x) {
    // origin laser at right
    if ((int)hitBeam.transform.eulerAngles.z == 45) {
     return new Vector3 (hitBeam.transform.position.x, hitBeam.transform.position.y + laserOffset, hitBeam.transform.position.z);
    } else {
    return new Vector3 (hitBeam.transform.position.x, hitBeam.transform.position.y - laserOffset, hitBeam.transform.position.z);
    }
  }

  else if (originBeam.x > hitBeam.position.x) {
   // origin laser at right
   if ((int)hitBeam.transform.eulerAngles.z == 45) {
    return new Vector3 (hitBeam.transform.position.x, hitBeam.transform.position.y - laserOffset, hitBeam.transform.position.z);
   } else {
    return new Vector3 (hitBeam.transform.position.x, hitBeam.transform.position.y + laserOffset, hitBeam.transform.position.z);
   }
  }
  
  
  // if fails
  return originBeam;
 }

Tuesday, 28 October 2014

Using async and await for Asynchronous calls in C# and VB

We are going to user asynchronous call to get length of web that we requested.

Download : C# or VB

Create new WPF project.



Add textbox and button.


Rename button to runAsyncButton and textbox to resultsWindow.
You can either do that  by adding x:Name property for each element, or click an element and get the properties and change name.
<Button x:Name="runAsyncButton" ... />
<TextBox x:Name="resultsWindow" .../>

Double click on button and click method is generated.

Xaml code for grid should looks similar:



Add this to your click method :
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
   resultsWindow.Clear();
   resultsWindow.Text += "Asynchronous call started";
   runAsyncButton.IsEnabled = false;
   runAsyncButton.Content = "Running...";
   await SumPageSizesAsync();
   runAsyncButton.IsEnabled = true;

   runAsyncButton.Content = "Run";
   resultsWindow.Text += "\n Asynchronous call finished";
}


As you can see method needs to have async keyword to perform as an asynchronous call.
Await keyword on SumPageSizesAsync method works in pair with async and tells method to wait before continuing if method is still being executed. 

We have to write SumPageSizesAsync method:


private async Task SumPageSizesAsync()
{
   List<string> urlList = SetUpURLList();

   foreach(var url in urlList)
   {
      // return contents as a byte array
      Byte[] urlContent = await GetURLContentsAsync(url);

      DisplayResults(url, urlContent);
   }

}


To populate list with url addresses:



private List<string> SetUpURLList()
{
   List<string> urls = new List<string>() { 

   "http://msdn.microsoft.com/library/windows/apps/br211380.aspx",
   "http://msdn.microsoft.com",
   "http://msdn.microsoft.com/en-us/library/hh290136.aspx"
};

return urls;
}


Now we have to write the core method - GetURLContentsAsync.


private async Task<byte> GetURLContentsAsync(string url)
{
   MemoryStream content = new MemoryStream();

   HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);

   // Send request and wait for response

   Task<webresponse> responseTask = webReq.GetResponseAsync();

   using (WebResponse response = await responseTask)
   {
      using (Stream responseStream = response.GetResponseStream())
      {
         await responseStream.CopyToAsync(content);
      }
   }
   return content.ToArray();
}


Final method is DisplayResults.

private void DisplayResults(string url, Byte[] content)
{    
   var bytes = content.Length;  
   resultsWindow.Text += string.Format("\n {0} {1}", url, bytes); 
} 


Run the program.




Saturday, 18 October 2014

Unity 3d frozes when loading or closing project

Occasionally I encounter issue which prevent me from closing Unity 3d or loading new project. After googling I found out that there is a process abd.exe running in the background that cause Unity to behave oddly. If your project is set up to Android project you are likely to have this process running.
More info about adb process can be found here : http://www.file.net/process/adb.exe.html

Simply saying adb is one of the Android SDK processes.

Shut all adb process from task manager panel and that should fix the problem.


Thursday, 9 October 2014

2 Simple rules to improve performance in Unity 3d when writing Scripts

So you created beautiful looking game that run 90 fps on your machine and then your exported it to mobile device and your excitement disappeared once you opened it -slow, lag, unplayable. If you haven't experienced that either you are genius talented video game designer or your game is not very resource demanding. I have been in this situation and my solution was to carefully start optimizing game so it will run much smoother and users that still have few years old devices(like me) can enjoy the game. This is not holy grail unity tutorial, but it definitely helps me in many occasions.

It is very important to think about performance in an early stage when creating video game/app using unity game engine. Some bad design can cause headache in the future, especially when your game gets bigger and more resource demanding.

Of course writing optimised script is not the only way to improve performance in unity games. Another way is to reuse materials, avoid using transparent shader on mobile devices etc.

Due to my experience I found out that those 2 very simple tricks works well.

1. Cache an object when using it often (especially in Update function).


Example.

   void Start ()

   {

       double totalA = 0;

       double totalB = 0;

       int counter = 1000000;

       // Caching our transform

       Transform tr = GetComponent();

       var currentTime = DateTime.Now;

       // First test with cache

       for (int i = 0; i < counter;i++)

       {

           Vector3 vec = tr.position;

           vec.x = 10;

           tr.position = vec;

       }

       totalA = (DateTime.Now - currentTime).TotalMilliseconds;

       // Second test with no cache

       currentTime = DateTime.Now;

       for (int k = 0; k < counter; k++)

       {

           Vector3 vec = transform.position;

           vec.x = 10;

           transform.position = vec;

       }  

       totalB = (DateTime.Now - currentTime).TotalMilliseconds;

       print (totalA);

       print (totalB);

   }

1st loop will perform faster.

2. Use static variables rather than public.


 Static variable belongs to an class rather than object, therefore it is faster to access. Careful as if the same class is being used for the same prefabs(eg enemy), if you kill one enemy, all of them will be dead.  If that approach at least helped you to get extra fps let me know!

Tuesday, 9 September 2014

Implementing API in ASP.NET MVC application

Full project can be downloaded here.

We are going to create simple API that will return either collection of movies or single movie in Json format by default, however depends on browser results might be displayed in XML format.
I focused only on GET method in this tutorial.
 
1. Create new MVC application in Visual Studio.
2. In models create interface IMoviesRepository, class Movie and MoviesRepository

public interface IMoviesRepository
    {
        IQueryable<Movie> GetAll();
        Movie GetById(int id);
        Movie Add(Movie movie);
        bool Edit(Movie movie);
        bool Remove(Guid? id);
    }

public class Movie
    {
        public int movieId { get; set; }
        public string name { get; set; }
        public string releaseYear { get; set; }
    }

public class MovieRepository : IMoviesRepository
    {
        private List<Movie> _listOfMovies = new List<Movie>();

        public MovieRepository()
        {
            _listOfMovies.Add(new Movie { 
                movieId = 1,
                name = "Keyboard massacre", 
                releaseYear = "1999" });

            _listOfMovies.Add(new Movie { 
                movieId = 2, 
                name = "Keyboard massacre 2",
                releaseYear = "2000" });

            _listOfMovies.Add(new Movie { 
                movieId = 3,
                name = "Keyboard massacre 3 ",
                releaseYear = "2001" });
        }

        public IQueryable<Movie> GetAll()
        {
            return _listOfMovies.AsQueryable();
        }

        public Movie GetById(int id)
        {
            return _listOfMovies.Find(m => m.movieId == id);
        }

        public Movie Add(Movie movie)
        {
            throw new NotImplementedException();
        }

        public bool Edit(Movie movie)
        {
            throw new NotImplementedException();
        }

        public bool Remove(Guid? id)
        {
            throw new NotImplementedException();
        }
    }
Create interface first and then MovieRepository that will inherit IMoviesRepository and simply right click on class name and apply Implement Interface.



3. Add new folder to your main project WebApiControllers and add Api Controller. Call itMoviesController.cs.



Add this to your main controller class.


MovieRepository movieRepository;

        public MoviesController()
        {
            this.movieRepository = new MovieRepository();
        } 


Calling default constructor will make sure that all repositories are in place. It is good practice to call all services that will be required for controller - we are making sure that our application is loose coupled. If you are familiar with dependency injection this is quite common concept.

As I mentioned I will focus only on GET method, so replace both GET methods with custom code.

You controller should like this :


public class MoviesController : ApiController
    {
        MovieRepository movieRepository;

        public MoviesController()
        {
            this.movieRepository = new MovieRepository();
        }

        // GET api/movies
        public IQueryable<Movie> Get()
        {
            return movieRepository.GetAll();
        }

        // GET api/movies/5
        public Movie Get(int id)
        {
            return movieRepository.GetById(id);
        }

        // POST api/movies
        public void Post([FromBody]string value)
        {
        }

        // PUT api/movies/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/movies/5
        public void Delete(int id)
        {
        }
    }

4. Run your application now and call localhost:YourPortNumber/api/movies

In my case: http://localhost:53909/api/movies

You should get this results in Chrome:


If you run it in IE you will be asked to save file. By opening it in notepad you get JSON results

[{"movieId":1,"name":"Keyboard massacre","releaseYear":"1999"},{"movieId":2,"name":"Keyboard massacre 2","releaseYear":"2000"},{"movieId":3,"name":"Keyboard massacre 3 ","releaseYear":"2001"}]

5. We could improve GetById method. If movie can not be found we want to return HttpResponseException.

// GET api/movies/5
        public Movie Get(int id)
        {
            var movie = movieRepository.GetById(id);
            if (movie == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return movie;
        }

6. There are few rules that you have to be aware. You have to name your GET method starting with Get. So For instance GetCollectionOfMovies. By calling http://localhost:53909/api/movies you get the same results as if your method would call just Get. There is a way to force user to type full name of your method http://localhost:53909/api/GetCollectionOfMovies and this will require changing routing in Global.asax file. I will mention that in one of next tutorials.


Sunday, 7 September 2014

1# Twisted lasers - Puzzle game - First look

Recently I started working on a puzzle game which main objective is to move laser beam source to designated location by using mirrors that will change the direction of laser. Very easy concept, however there will be more obstacles and more tools to use apart from mirrors.

So far I was able to create a custom grid that can be very easily modified. For instance if game requires 8x8 or 6x6 grid this can be changed by providing correct input for Building Grid script.


// Constant offset value
  xOffSet = (float)10/gridColumns;
  yOffset = (float)10/gridRows;

  firstTile = CreateSingleGridTile(firstPoint, secondPoint, thirdPoint, fourthPoint,  0, 0);
  firstTile.renderer.enabled = false;

  GameObject grid = new GameObject();

  // This method can be used from other Scripts to build extra grids, inventory systems etc
  BuildGrid (ref grid, gridRows, gridColumns, arrayOfTiles, "SingleTile", xOffSet, yOffset, zOffset, firstTile,  firstPoint);

  // Set main beam position

  var positionOfBeamToAppear = arrayOfTiles[xMainBeam, yMainBeam];

  mainLaserBeam.transform.position = new Vector3(positionOfBeamToAppear.transform.position.x -xOffSet/2, positionOfBeamToAppear.transform.position.y - yOffset/2, positionOfBeamToAppear.transform.position.z +zOffset);

  var positionOfLaserTargetToAppear = arrayOfTiles[xLaserTarget, yLaserTarget];
  
  laserTarget.transform.position = new Vector3(positionOfLaserTargetToAppear.transform.position.x -xOffSet/2, positionOfLaserTargetToAppear.transform.position.y - yOffset/2, positionOfLaserTargetToAppear.transform.position.z +zOffset);

 }

 public void BuildGrid (ref GameObject grid,
                        int gridRows,
                        int gridColumns,
                        GameObject[,] arrayOfTiles,
                        string tagName,
                        float xOffSet,
                        float yOffset,
                        float zOffset,
                        GameObject firstTile,
                        Vector3 initialBuildPosition
                        )
 {

  bool nextRow = false;
  for (int row = 0; row < gridRows; row++) {
   for (int column = 0; column < gridColumns; column++) {
    if (row == 0 && column == 0) {
     grid = Instantiate (firstTile, new Vector3 (initialBuildPosition.x, initialBuildPosition.y, initialBuildPosition.z - zOffset), Quaternion.identity) as GameObject;
     arrayOfTiles [row, column] = grid;
     grid.renderer.enabled = true;
    }
    else {
     if (!nextRow) {
      grid = Instantiate (arrayOfTiles [row, column - 1], new Vector3 (arrayOfTiles [row, column - 1].transform.position.x + xOffSet, initialBuildPosition.y, initialBuildPosition.z - zOffset), Quaternion.identity) as GameObject;
     }
     else {
      grid = Instantiate (arrayOfTiles [row - 1, column], new Vector3 (arrayOfTiles [row - 1, column].transform.position.x, arrayOfTiles [row - 1, column].transform.position.y - yOffset, arrayOfTiles [row - 1, column].transform.position.z), Quaternion.identity) as GameObject;
     }
     arrayOfTiles [row, column] = grid;
     grid.renderer.enabled = true;
    }
    // Based on name we can easily find the position of tile
    grid.name = string.Format ("{0}_{1}:{2}", tagName, row, column);
    grid.tag = tagName;
    grid.collider.enabled =true;
   }
   nextRow = true;
  }
 }

 // Update is called once per frame
 void Update () {

 }

 public GameObject CreateSingleGridTile(Vector3 firstPoint,Vector3 secondPoint,Vector3 thirdPoint,Vector3 fourthPoint, int xArrayIndex, int yArrayIndex )
 {
  GameObject gridTile = new GameObject(string.Format("Reference_{0}:{1}", xArrayIndex,yArrayIndex) );

  MeshFilter meshFilter = (MeshFilter)gridTile.AddComponent(typeof(MeshFilter));

  meshFilter.mesh = CreateMesh(firstPoint,secondPoint, thirdPoint, fourthPoint);

  gridTile.AddComponent();

  MeshRenderer renderer = gridTile.AddComponent(typeof(MeshRenderer)) as MeshRenderer;
  renderer.material.shader = Shader.Find ("Mobile/Particles/Additive");

  renderer.material.mainTexture = tileTexture;

  float gridItemWidth = (float)1/gridColumns;
  float gridItemHeight = (float)1/gridRows;

  gridTile.transform.localScale = new Vector3(gridItemWidth,gridItemHeight,+zOffset);

  // Set grid Tile position
  // TODO add variable to calculate the grid difference 

  gridTile.collider.enabled = false;
  return gridTile;

 }


 Mesh CreateMesh(Vector3 firstPoint, Vector3 secondPoint, Vector3 thirdPoint, Vector3 fourthPoint)
 {
  Mesh m = new Mesh();
  m.name = "ScriptedMesh";
  m.vertices = new Vector3[] {
   firstPoint,
   secondPoint,
   thirdPoint,
   fourthPoint
  };
  m.uv = new Vector2[] {
   new Vector2 (0, 0),
   new Vector2 (1, 0),
   new Vector2(1, -1),
   new Vector2 (0, -1)
  };
  m.triangles = new int[] { 0, 1, 2, 0,2,3};
  //m.RecalculateNormals();

  //m.Optimize();
  
  return m;
 }