Art == Programming == Solitude

I am a programmer, not a writer. But I enjoy good writing. There is something in the process of writing or any kind of artistic activity that attracts me a lot. I always try to follow the process to make my programming look like art. To express my feelings through programming! Wait, is that possible… I don’t know yet.

But there was something always bugging me. The way an artist create is totally opposite of a programmer. They create in emotion, while we create in system.  And you can make a lot of differences between us. Of course there are some similarities as well. But what joins these two fields is solitude.

Why solitude? If you search Google with the word solitude, you will find a definition like – “the state or situation of being alone”. And that phrase says it all. We both create our best work in solitude. Our ideas, design, creativity, work, innovation flourish in solitude and we come with our masterpiece.

It’s not easy as I wrote it. Not even possible for everyone (like me?), but you can try it. Be with your solitude.

Ending The Year With Compilers

So… Last day of 2013. Not really thought of posting something today, but when browsing something reminded me my blog and I thought I should share what I am doing at the last day of this year.

For past couple of days, I am furiously reading about Compilers. How to make one? From scratch or with tools? Starting points? Which books or tutorial? etc.

Now I will share what I have learnt in these days.

It is not true that I didn’t know about how compilers or interpreters work before, but that wasn’t sufficient for making a compiler (trivially). First, I started with Language Implementation Patterns book. This is an awesome book by the creator of Antlr. From this book I learnt about LL(1) and LL(k) parser, how to build a lexer with input buffering, building parse tree, homogeneous and heterogeneous AST (Abstract Syntax Tree) and how to walk those trees.

But there was a problem, in that book the author showed you the data structure for different kind of AST, but he didn’t show you how to build one from the parser. So my search began again, I tried the famous Dragon book, a little filled with theory (and I like theory),  but I didn’t found what I was looking for. Then reading some recommendation from stackoverflow, I tried Modern Compiler Implementation in Java. But alas! Nowhere to be found. Another book I tried was Engineering A Compiler, 2nd Ed, this book had that part, but it focuses more on pseudo algorithm rather than some implementation in a particular language.

Then suddenly I found a book which filled the gap. Programming Language Processors In Java. It has most of the things I found in the patterns book PLUS building AST from the parser part.

Now I am reading about Symbol Tables and Scoping from both the books (patterns and processors) and comparing the approaches.

Hope the new year will bring a new programming language out of me.

Happy New Year

Steve Jobs Again !!!

It’s a very long time since my last post, but nothing has changed much. I am still the same. My last post was a video of Steve Jobs which inspired me so much, today I want to share one of the lectures he gave. Am I becoming a Jobs fan? Or am I trying to find something in his words, which will change me, I won’t be the same anymore…

Here is the link, read and be enlightened-

http://news.stanford.edu/news/2005/june15/jobs-061505.html

How to pass leisure… Haskell!!!

After the end of Spring 2013 in my university, it seems like there is infinite leisure and no work to do. Not sure when the next semester will start, so I thought of doing something interesting. After some frustrating search in Google, I decided to look into Haskell and believe it or not, it’s good. This language is actually smart, let’s see if I can outsmart it.

By the way, this is the book I am reading right now to learn Haskell. Real World Haskell. This is the free online version of the book. Enjoy functional world :-)

Component Entity Systems Again!

In a previous post of mine, I just denied the term CES (Component Entity Systems). Yes, I denied the term, not the concept. But after posting, I thought I should research some more about the topic and find some concrete example which validates the term CES.

From what I found out (thanks to GameDev, GamesFromWithin, T=Machine, Chris Granger), it’s clear to me that I didn’t really understood what CES actually is.

I am a OOP programmer from the start, so I think in terms of classes and objects. That is what stops you from accepting CES.

I knew that entity is an unique ID, so I thought like this:


class Entity

{

int id;

}

This is a very simplified version of what I thought, but you got the idea, right? I thought of Entities as class.

But now I know they are pure int.

Components can be class or struct, but they must contain only data. They actually represent state.

But how about combining that id and a list of components. Maybe we should make a class that has an int and a list of components? That’s what I though, that’s what every OOP programmer thinks.

So if this is not the solution, then how can we approach this? Let’s refactor the above question. Instead of saying the word combining, if we say that, how about mapping that int and a list of components. You got it right? It’s a familiar data structure, a Map. The int and list of components will be the key value pairs.

Then again, games need logic which alters the states. And that is what systems are for. They alter the state.

But what are they, a class with list of entities and an update method? No way, it will just be a function which takes every entity that has an component which this function will update.

Let’s be a little bit more specific, if we have a renderComponent then there will be a function named renderer which will take entities with renderComponent and that renderer function will render that entity.

So that’s it, No more classes, no more inheritance, just a data structure and some functions to manipulate them.

But what are the CES good for? and where do they fall apart? umm… needs some research :D But at least I know what I am going to post next!

Object Oriented Programming and Component Entity Systems In Games

Programming games are fun. It always has been. But games are also software, so they also need the proper organization of code. Proper organization of the code helps reusing it many more times when needed or reusing parts of it. From a software perspective, games need to follow some programming paradigm, after structured programming came OOP (Object Oriented Programming) and now CES (Component Entity Systems).

There are many books, articles and forum post out there discussing/proving the need to transfer from structured languages like – C to OOP languages like – C++. Now it’s changing towards component entity systems. No one is advising to change any language but rather think differently.

So what is the difference between OOP and CES? In one sentence, OOP is about inheritance and CES is about composition of objects. But do we really need CES? Or a better question might be isn’t CES also a subset of OOP?

Whatever posts or articles I have seen on CES tells the problems of inheritance and shows us the path towards composition. But I really don’t see why composition isn’t being considered as OOP. Many books I have read on Java, C++ and general OOP advises to use composition instead of inheritance when necessary. Some books even advised to think about composition first and if that doesn’t solve the problem then use inheritance.

In CES, components tend to have only data (in most cases) but every OOP language provides/accepts defining a class with only data, that means it is accepted in OOP. Entities contain needed components (Composition, also allowed in OOP and is OOP) and systems act on them (functions/methods, polymorphism etc. pure OOP).

So every CES is OOP, but not every OOP is CES (remember, Inheritance).

So what am I trying to say? Remove the concept of CES? NO. Absolutely not. CES has some nice features like – dynamic plugging, better reuse etc. My point is that, whenever it’s better to use inheritance, we will use it and whenever inheritance is not the better solution then we will use composition and will still call that OOP, not CES.

MATRIX JAVA CLASS


/*
* Author: Kazi Sami
* A simple but generalized Matrix class
* For creating matrices of different types
* and performing valid operations on them
*
*/

public class Matrix
{
private double[][] matrix; // the container (2d array) to hold the matrix elements
private int rows, columns;

// Constructor 1
// Takes specified no. of rows and columns and creates the matrix
public Matrix(int _rows, int _columns)
{
rows = _rows;
columns = _columns;
matrix = new double[rows][columns];
}

// Constructor 2
// Takes a 2d array and makes it a matrix
public Matrix(double[][] _matrix)
{
rows = _matrix.length;
columns = _matrix[0].length;
matrix = _matrix;
}

// Takes a specific location of the matrix (row, column)
// And returns it, return -1.0 if index is out of bounds
public double get(int _row, int _column)
{
if(_row >= 0 && _row < rows && _column >= 0 && _column < columns)
return matrix[_row][_column];
else
return -1.0;
}

// Takes a specific location of the matrix (row, column) and sets the given value
public void set(int _row, int _column, double _value)
{
matrix[_row][_column] = _value;
}

// Checks if its a square matrix
public boolean isSquare()
{
return rows == columns;
}

// Returns the transpose matrix of this one. (transpose = changing columns into rows and vice versa)
public Matrix transpose()
{
double[][] transpose = new double[columns][rows];
for(int i = 0; i < columns; i++)
{
for(int j = 0; j < rows; j++)
transpose[i][j] = matrix[j][i];
}
return new Matrix(transpose);
}

// Multiplies every element in the matrix with a given _scalar
public void scalarMul(int _scalar)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
matrix[i][j] *= _scalar;
}
}

// Returns the number of rows in this matrix
public int getRows()
{
return rows;
}

// Returns the number of columns in this matrix
public int getColumns()
{
return columns;
}

// Multiplies this Matrix with a given matrix (if its possible)
// Returns the resulted matrix
public Matrix mul(Matrix toMul)
{
if(this.getColumns() == toMul.getRows())
{
double[][] result = new double[this.getRows()][toMul.getColumns()];
for(int i = 0; i < this.getRows(); i++)
{
for(int j = 0; j < toMul.getColumns(); j++)
{
for(int row = i, incRow = 0, column = j, incColumn = 0; incRow < this.getRows() && incColumn < toMul.getColumns(); incRow++, incColumn++)
result[i][j] += this.get(row, incRow) * toMul.get(column, incColumn);
}
}
return new Matrix(result);
}
return null;
}

// Returns an indentity matrix based on given rows and columns
public Matrix getIdentity(int _rows, int _columns)
{
double[][] identity = new double[_rows][_columns];
for(int i = 0; i < _rows; i++)
{
for(int j = 0; j < _columns; j++)
{
if(i == j)
identity[i][j] = 1.0;
}
}
return new Matrix(identity);
}

// Adds given matrix to this one and returns resulted matrix
public Matrix add(Matrix _given)
{
if(this.getRows() == _given.getRows() && this.getColumns() == _given.getColumns())
{
double[][] result = new double[rows][columns];
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
result[i][j] = this.get(i, j) + _given.get(i, j);
}
}
return new Matrix(result);
}
return null;
}

// Substracts given matrix to this one and returns resulted matrix
public Matrix sub(Matrix _given)
{
if(this.getRows() == _given.getRows() && this.getColumns() == _given.getColumns())
{
double[][] result = new double[rows][columns];
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
result[i][j] = this.get(i, j) - _given.get(i, j);
}
}
return new Matrix(result);
}
return null;
}

public String toString()
{
StringBuilder result = new StringBuilder();
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
result.append(matrix[i][j] + " ");
}
result.append("\n");
}
return result.toString();
}
}


public class TestMatrix
{
public static void main(String[] args)
{
double[][] test1 =
{
{1.0, 1.0, 1.0},
{1.0, 1.0, 1.0}
};

Matrix matrix1 = new Matrix(test1);

System.out.println(matrix1);

double[][] test2 =
{
{1.0, 1.0, 1.0},
{1.0, 1.0, 1.0}
};

Matrix matrix2 = new Matrix(test2);

System.out.println(matrix1.add(matrix2));

System.out.println(matrix1.sub(matrix2));

System.out.println(matrix1.getIdentity(3, 3));

System.out.println(matrix1.getIdentity(3, 3));

double[][] test3 =
{
{2.0, 3.0, 4.0},
{1.0, 1.0, 1.0}
};

Matrix matrix3 = new Matrix(test3);

System.out.println(matrix3.transpose());

double[][] test4 =
{
{1.0, 1.0},
{1.0, 1.0}
};

Matrix matrix4 = new Matrix(test4);

double[][] test5 =
{
{1.0, 1.0},
{1.0, 1.0}
};

Matrix matrix5 = new Matrix(test5);

System.out.println(matrix4.mul(matrix5));
}
}

Vector class in Java


/*
* Author: Kazi Sami
* A simple but generalized vector class.
* This can be used to make any dimensional vectors.
* Implements mathematical vector operations.
* The crossProduct() method is an exception. It only deals with 3d vectors.
*
*/

import java.util.Arrays;

public class Vector
{
private double[] components; // For holding vector components

// Constructor
// Creates a vector with specified dimension
public Vector(int _dimension)
{
if(_dimension >= 0)
components = new double[_dimension];
}

// Constructor 2
// Creates a vector with specified components
public Vector(double[] _components)
{
components = _components;
}

// Method for multiplying a vector with a scalar
public void scalarMul(int _scalar)
{
for(int i = 0; i < components.length; i++)
components[i] *= _scalar;
}

// Adds another Vector to this one
public void add(Vector _tobeadded)
{
if(this.dimension() == _tobeadded.dimension())
{
for(int i = 0; i < components.length; i++)
components[i] += _tobeadded.get(i);
}
}

// Adds the elements of a vector to this one
public void add(double[] _tobeadded)
{
if(components.length == _tobeadded.length)
{
for(int i = 0; i < components.length; i++)
components[i] += _tobeadded[i];
}
}

// Substracts another Vector from this one
public void substract(Vector _tobesubstracted)
{
if(this.dimension() == _tobesubstracted.dimension())
{
for(int i = 0; i < components.length; i++)
components[i] -= _tobesubstracted.get(i);
}
}

// Substracts the elements of a vector from this one
public void substract(double[] _tobesubstracted)
{
if(components.length == _tobesubstracted.length)
{
for(int i = 0; i < components.length; i++)
components[i] -= _tobesubstracted[i];
}
}

// Returns the magnitude or length or norm of the Vector
public double length()
{
double length = 0.00;

for(int i = 0; i < components.length; i++)
length += Math.pow(components[i], 2);

length = Math.sqrt(length);

return length;
}

// Normalize or resize to unit length and returns it
// If null vector, returns 0.00
public double normalize()
{
if(this.length() > 0)
return 1 / this.length();
else
return 0.00;
}

// Performs dot product with another vector
// Returns the scalar result
public double dotProduct(Vector _another)
{
double scalarResult = 0.00;
if(this.dimension() == _another.dimension())
{
for(int i = 0; i < components.length; i++)
scalarResult += components[i] * _another.get(i);
}
return scalarResult;
}

// Calculates cross product of this and the given vector.
// Returns another Vector.
public Vector crossProduct(Vector _given)
{
if(this.dimension() == 3 && _given.dimension() == 3)
{
double[] result = new double[3];
result[0] = (components[1] * _given.get(2)) - (components[2] * _given.get(1));
result[1] = (components[2] * _given.get(0)) - (components[0] * _given.get(2));
result[2] = (components[0] * _given.get(1)) - (components[1] * _given.get(0));
return new Vector(result);
}
else
return null;
}

// Returns if this and the given vectors are in the same side of a plane
public boolean isSameSide(Vector _given)
{
if(dotProduct(_given) > 0.00)
return true;
else
return false;
}

// Returns the dimension of this vector
public int dimension()
{
return components.length;
}

// Returns a specific component in the specified index
// If _index is out of bounds, then returns -1.00
public double get(int _index)
{
if(_index >= 0 && _index < components.length)
return components[_index];
else
return -1.00;
}

public String toString()
{
return Arrays.toString(components);
}

}

 


/*
* Author: Kazi Sami
* Some naive testing of the Vector class.
*/

public class VectorTest
{
public static void main(String[] args)
{
double[] vec3darray = {2.0, 3.0, 4.0};
Vector vec3d = new Vector(vec3darray); // A 3d vector
System.out.println(vec3d); // output: [2.0, 3.0, 4.0]
// Seems like the constructor and toString methods are working well

vec3d.scalarMul(2);
System.out.println(vec3d); // output: [4.0, 6.0, 8.0]
// scalarMul() is also working.

vec3d.add(new double[] {1.0, 2.0, 3.0});
System.out.println(vec3d); // output: [5.0, 8.0, 11.0]
// add() is working

vec3d.substract(new double[] {1.0, 2.0, 3.0});
System.out.println(vec3d); // output: [4.0, 6.0, 8.0]
// we're back! substract() is working

System.out.println(vec3d.length()); // output: 10.770329614269007 - tested by hand, seems alright
System.out.println(vec3d.normalize()); // output: 0.09284766908852593 - tested by hand, seems alright

System.out.println(vec3d.dotProduct(new Vector(new double[] {4.0, 6.0, 8.0}))); // output: 116.0 - tested by hand, seems alright
System.out.println(vec3d.crossProduct(new Vector(new double[] {2.0, 4.0, 4.0}))); // output: [-8.0, 0.0, 4.0] - tested by hand, seems alright
}
}