Saturday, 9 May 2015

Multi texture pack optimized for Game Engines. Coming soon to Unity and UDK market.

Finishing work on multi texture package for Unity 3d asset store and Unreal market place.
Each material consist of 4 textures (diffuse, normal, height and ambient occlusion). 
Textures that are tillable are perfectly seamless. 
First launch will consist of 60 materials - 240 textures! 
Future update is already planned. 

Actual screenshot from planes in Unity Engine 5 with default light settings.

Categories:
Enironment -> Trees, Grass Frozen, Sand
Floor ->Asphalt, Carpet, Concrete, Gravel & Rock, Medieval, Metal, Stone, Wood
Glass
Leather
Fabric
Roof
Walls -> Bones, Brick, Concrete, Rock, Temples
Misc - Containers

























Tuesday, 31 March 2015

SCi Fi Kit - Unity3d and UDK

Started working on Sci Fi Kit. Package will include sci fi levels, objects such as crates, barrels, pipes etc, preety much everything you would expect to find in Sci Fi game. High influence from Deus Ex, Dead Space. I will also include sci fi sounds(ambient & fx). I will target Unity 5 users and UE4 so I can use full power of new features in both game engines.


I will keep posting and adding more images from work.
Si
Sci Fi Crate 1 - Simple crate with no extra features. 168 tris.



Sci Fi Crate 2 - Found concept here : concept
Simple low poly model with 1200 tris, Baked normal from high poly and added few details to normal map. Wanted to keep it simple, however I will add more details(only to normal map) and few extra stripes of paint, possibly on the edges. Exported model to Unity 3d and looks almost the same as on the picture below.


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!