Rendering a Point Cloud inside Unity

May 27th, 2014

Here is a short example of how to render a point cloud using MeshRenderer inside Unity, have in mind that you have a limit of 65k points per mesh, so if you want to render more points, you need to split them.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class PointCloud : MonoBehaviour {

	private Mesh mesh;
	int numPoints = 60000;

	// Use this for initialization
	void Start () {
		mesh = new Mesh();

		GetComponent<MeshFilter>().mesh = mesh;

	void CreateMesh() {
		Vector3[] points = new Vector3[numPoints];
		int[] indecies = new int[numPoints];
		Color[] colors = new Color[numPoints];
		for(int i=0;i<points.Length;++i) {
			points[i] = new Vector3(Random.Range(-10,10), Random.Range (-10,10), Random.Range (-10,10));
			indecies[i] = i;
			colors[i] = new Color(Random.Range(0.0f,1.0f),Random.Range (0.0f,1.0f),Random.Range(0.0f,1.0f),1.0f);

		mesh.vertices = points;
		mesh.colors = colors;
		mesh.SetIndices(indecies, MeshTopology.Points,0);


And here is the code for the material’s shader, that will use the vertex color from the mesh:

Shader "Custom/VertexColor" {
	SubShader {
	Pass {
		LOD 200
		#pragma vertex vert
		#pragma fragment frag

		struct VertexInput {
			float4 v : POSITION;
			float4 color: COLOR;
		struct VertexOutput {
			float4 pos : SV_POSITION;
			float4 col : COLOR;
		VertexOutput vert(VertexInput v) {
			VertexOutput o;
			o.pos = mul(UNITY_MATRIX_MVP, v.v);
			o.col = v.color;
			return o;
		float4 frag(VertexOutput o) : COLOR {
			return o.col;



And this is how you enable GL_VERTEX_PROGRAM_POINT_SIZE and GL_POINT_SMOOTH, so you could set the point size in your shader and have smooth points. Uou must attach this script to your main Camera. The code was found on this thread


using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;

public class EnablePointSize : MonoBehaviour 
	const UInt32 GL_VERTEX_PROGRAM_POINT_SIZE = 0x8642;
	const UInt32 GL_POINT_SMOOTH = 0x0B10;
	const string LibGLPath =
	"libGL";  // Untested on Linux, this may not be correct
	null;   // OpenGL ES platforms don't require this feature
	public static extern void glEnable(UInt32 cap);
	private bool mIsOpenGL;
	void Start()
		mIsOpenGL = SystemInfo.graphicsDeviceVersion.Contains("OpenGL");
	void OnPreRender()
		if (mIsOpenGL)

Posting an Image via Tumblr V2 API inside Unity

May 24th, 2014

For a project I needed to upload screenshots from my Unity project to Tumblr, so I got into the whole OAuth & Tumblr encoding mess. I am posting the final working source code, with the hope that it will save someone the two days of struggle.

using UnityEngine;
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Security.Cryptography;
using System.IO;
public class URLUtils {
	private static string _UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
	public static string URLEncodeBytes(byte[] value, bool encodePercent)
		var osb = new StringBuilder(value.Length * 3);
		for (var x = 0; x < value.Length; x++)
			var b = value[x];
			if( (char)b == '%') {
				osb.Append ("%25");
			} else if ((_UnreservedChars.IndexOf((char)b) == -1) && ((char)b) != '~' && (((char)b) != '%'))
				osb.AppendFormat("%{0:X2}", b);
		if(encodePercent)	{
			osb = osb.Replace("%", "%25");// Revisit to encode actual %'s
		return osb.ToString();
public class TumblrOAuth : MonoBehaviour {
	private string consumerKey = "";
	private string consumerSecret = "";
	private string accessToken = "";
	private string accessTokenSecret = "";
	void Start () {
		string imagePath = "file://"+Application.dataPath + "/../image.png";
		StartCoroutine(UploadImage("", imagePath));
	private static string GenerateTimeStamp()
		// Default implementation of UNIX time of the current UTC time
		TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
		return Convert.ToInt64(ts.TotalSeconds, CultureInfo.CurrentCulture).ToString(CultureInfo.CurrentCulture);
	private static string GenerateNonce()
		// Just a simple implementation of a random number between 123400 and 9999999
		return new System.Random().Next(123400, int.MaxValue).ToString();
	IEnumerator UploadImage(string blogAddress, string imagePath) {
		string uri =  string.Format("{0}/post",blogAddress);
		// download image
		WWW img = new WWW(imagePath);
		yield return img;
		// signature
		Dictionary<string, string> options = new Dictionary<string, string>();
		string timestamp = GenerateTimeStamp();
		string nonce = timestamp+GenerateNonce();
		string method = "POST";
		options.Add("oauth_nonce", nonce);
		options.Add("oauth_timestamp", timestamp);
		var stringBuilder = new StringBuilder();
		//the key value pairs have to be sorted by encoded key
		var dictionary = new SortedDictionary<string, string>
			{"oauth_token", accessToken},
			{"oauth_consumer_key", consumerKey},
			{"oauth_timestamp", timestamp},
			{"oauth_nonce", nonce},
			{"oauth_signature_method", "HMAC-SHA1"},
			{"oauth_version", "1.0"},
			// post params
		// encode all params
		foreach (var keyValuePair in dictionary)
			byte[] bytesValue = System.Text.Encoding.ASCII.GetBytes(keyValuePair.Value);
			string encodedValue;
			if(keyValuePair.Key.IndexOf("data") > -1) {
				// encode image data directly from the image bytes
				// when creating the signature the % must be changed with %25, hence the true param for URLEncodeBytes
				encodedValue = URLUtils.URLEncodeBytes(img.bytes, true);
			} else {
				encodedValue = URLUtils.URLEncodeBytes(bytesValue,false);
			byte[] bytesKey = System.Text.Encoding.ASCII.GetBytes(keyValuePair.Key);
			string encodedKey = URLUtils.URLEncodeBytes(bytesKey,false);
			//append a = between the key and the value and a & after the value
			stringBuilder.Append(string.Format("{0}%3D{1}%26", encodedKey, encodedValue));
		// the holy signature base!
		string signatureBaseString = stringBuilder.ToString().Substring(0, stringBuilder.Length - 3);
		string signatureKey =
			Uri.EscapeDataString(consumerSecret) + "&" +
		var hmacsha1 = new HMACSHA1(
		// teh signature string
		string signatureString = Convert.ToBase64String(
		signatureString = Uri.EscapeDataString(signatureString);
		// the authorize header
		string auth =  "OAuth oauth_token=\""+accessToken+"\", oauth_consumer_key=\""+consumerKey+"\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\""+timestamp+"\", oauth_nonce=\""+nonce+"\", oauth_version=\"1.0\", oauth_signature=\""+signatureString+"\"";
		// the post data
		// we have to build it ourselves, because if we use WWWForm, it will enforce it's own way of
		// encoding the image data, and it will break things
		// we don't change % to %25 when adding the post data
		string imgDataEncoded = URLUtils.URLEncodeBytes(img.bytes, false);
		StringBuilder postData = new StringBuilder();
		postData.Append (imgDataEncoded);
		postData.Append ("&type=photo");
		// send request
		Hashtable headers = new Hashtable();
		headers["Authorization"] = auth;
		headers["Content-type"] = "application/x-www-form-urlencoded";
		WWW web = new WWW(uri, System.Text.Encoding.ASCII.GetBytes(postData.ToString()), headers);
		yield return web;
		if (!string.IsNullOrEmpty(web.error))
			Debug.Log(string.Format("GetAccessToken - failed. error : {0}", web.error));
		} else {
			Debug.Log (web.text);

The main problem was how to encode the raw data from the image, so we could generate the OAuth signature base and the Tumblr post params correctly. The code is pretty self explanatory, so I won’t go into the details.

To get the initial access token and secret, I used a great command line tool:

Flatdown – Development Progress

March 12th, 2014

Here are couple of screenshots from the game I am working on. It’s being made inside Unity, but I used Openframeworks to make the Level Editor. You can follow the progress of the game development at:


photo 1 (1)

photo 2

Level Editor:

Screen Shot 2014-03-10 at 3.22.23 PM



I am doing an new game

February 20th, 2014

I am doing a game, it’s for mobile, but I am going to release it on desktops too (Thanks, Unity!).

Flat Down is a minimalistic, retro styled, action game, which will stretch your fingers and test your reactions. All levels are algorithmically generated, depending on the difficulty (I am going to do a separate post about my approach to level design).

I am still at prototyping stage, so here are couple of screenshots:

Flat Down iOS Screenshots
Flat Down iOS Screenshot

If anybody wants to be a beta tester, feel free to hit me up!

Global Game Jam 2014

January 31st, 2014

I took part in the first local Global Game Jam, here in Sofia and it was AWESOME! I learned more about doing games for two days, then for the last 6 months. The team I was part of, was entirely of people I met at the jam, so I ended making new friends, which I really hope to work with again! To make the long story short here is a link to our cool game:



Baking MoGraph Animations and importing to Unity

November 8th, 2013

Here is a short tutorial on how to bake MoGraph animations into keyframes, so you could easily import and play them inside Unity. Feel free to message me, if you have any questions.

Baking Mograph Animations and importing to Unity from Kamen Dimitrov on Vimeo.