After some contemplation I’ve created what I hope is a suitable solution. A few tables have been added, the ‘user group’ table and the ‘user group member’ table. The ‘follower’ table has been swallowed up by the ‘user group’ table. When a user is created two default user groups are create the ‘Followers’ group and the ‘Followees’ group.

The ‘Followers’ and ‘Followees’ groups have the special property that they can’t be renamed or deleted, I’d imagine that people would probably rename their followers to bellends or something. The ‘Followers’ group also has the special property that anyone can add themselves to it, since anyone can follower anybody if they wish.

To automatically create the ‘Followers’ and ‘Followees’ groups I’ve added a trigger to the ‘user’ table that inserts the groups when a new user is insert. I’ve actually used numerous triggers mainly for updating the modified field of the rows when updated. Detailed information about triggers can be found here. Here is the trigger to insert the ‘Followers’ and ‘Followees’ groups:

	DELIMITER $$
	
	CREATE TRIGGER `INSERT_ADD_FOLLOWERS` AFTER INSERT
	ON `USER` FOR EACH ROW
	BEGIN
	INSERT INTO `USER_GROUP`(`user_id`, `name`, `type`) VALUES (NEW.`user_id`, 'Followers', 1);
	INSERT INTO `USER_GROUP`(`user_id`, `name`, `type`) VALUES (NEW.`user_id`, 'Followees', 2);
	END$$

	DELIMITER ;

The new solution amends the problems we were having earlier and adds a new feature ‘groups’. The user can now create a group and grant them access permissions with ease. Also they can remove a single user from the group without affecting the other members.

Authorisation

Since I wish for it to be possible for others to use the Scriblet users data we need a way to allow clients, such as website or apps, access to a users data once the user has allowed the client access. It is not preferrable for each and every client to know the user’s credientals (username and password). The current method used for authorising access to private resources is OAuth 2.0, used by Facebook, Twitter and Google. The idea behind OAuth 2.0 is to essentially ask the user to authorise a client then hand out access tokens that the client can use to access the user’s resources.

OAuth 2.0 Flow

The OAuth 2.0 flow is described in this video here. Here is a summary:
  1. Developer registers a client id, secret and redirect url for Sriblet.
  2. The user authorises the client.
  3. Scriblet sends an authorisation code, which is short lived, to the redirect url.
  4. The client then returns the authorisation code and the client secret.
  5. Scriblet returns an access token and a refresh token.
  6. The client then begins to access the user’s resources using the access token; requesting new ones when needed.

This is great the user can use the client and access their data as well as remove access whenever they wish. However, this assumes a particular type of client a web app, since the authorisation code is sent to the reditect url. What if the client is an Android app with no web interface. It might be easiest to allow clients that can securely store the client secret to request an access token using their id and secret.

The Database Now

A few more tables have been added to implement the features and additions described above. The database is becoming rather large and I’m thinking of introducing a commenting system and some crude analytics.


Fig. 1 Scriblet Modified ER Diagram

The first step to building a database is to determine the types of resource or objects it is going to contain and the relationships between the objects. The Scriblet database will contain the following:

  • User: user_id, name, password, etc
  • Project Book: project_book_id, user_id, title, public, etc
  • Project Book Item: project_book_item_id, project_book_id, title, contents, public, etc
  • Tag: tag_id, user_id, name, etc
  • Tag Map: tag_map_id, tag_id, project_book_item_id, etc
  • Follower: tag_map_id, tag_id, project_book_item_id, etc
  • Access: tag_map_id, tag_id, project_book_item_id, etc
And the relationships between them are:
  • User has many Project Books
  • User has many Tags
  • Project Book has many Project Book Items
  • Project Book Item has many Tag Maps
  • User has many Followers

The Tagging System

The tagging system I’ve chosen is the Toxi solution thought up by toxi, here now. The toxi solution separates the tags into a table and in order to tag an item, a project item say, you create a tagmap entry connecting the item and the tag, hopefully Fig. 1 will enlighten things. The are a couple of other solutions described here, but they’re pretty flawed.

Access

I’d like it to be possible for the user to create a project book and specify whom they wish to be able to see or edit it. One way I was thing of was to have a ‘public_to’ field in the PROJECT_BOOK table, which will indicate that the project book is private, viewable by people the user is following or viewable by everyone. But this is rather limited you can’t, for instance, say I wish for Joe Bloggs to see this plus I also wish for the user to determine who can edit it.

To do this I could introduce an extra table ACCESS, which give a particular user access either to edit or view a certain project book. However, I can imagine this will produce anything other than clumsy or even down right ugly SQL statements. For example selecting all project books that can edit would look something like this:

	SELECT * 
	FROM `PROJECT_BOOK` 
	LEFT JOIN `ACCESS` ON `PROJECT_BOOK`.`project_book_id` = `ACCESS`.`project_book_id` 
	WHERE `PROJECT_BOOK`.`user_id` = $other_guys_id
	AND (
		`PROJECT_BOOK`.`public_to` = 2
		OR `PROJECT_BOOK`.`public_to` = 1 AND EXISTS(
			SELECT * 
			FROM `FOLLOWER` 
			WHERE `user_id` = $me AND `follower_id` = $other_guys_id
		)
		OR `ACCESS`.`public_to` = 0 AND `ACCESS`.`user_id` = $me 
	)

Not much of a looker. The query goes as follows is the project book viewable by everybody? (Yay/Damn) Is it viewable by people the user follows and am I one of those? (Yay/Damn) Finally, have I been given special access? (Yay/Damn). The query isn’t completely horrible but I think there are other problems such as should the project book be in a users list of project books as though they are the owner?

The problem with removing the ‘public_to’ field and using of the ACCESS table is that it would become difficult to allow access to all followees. However, the solution as it stands makes it difficult to add a group this isn’t all of the people followees. Hmm this is making me think a group access system would be best, like Google+s circles. A user defines a group and adds access permissions to that group.

For now I shall carry on with the non-follower stuff (the unfriendly bit?), since writing code is good and the follower stuff can be tacked on later. I shall keep this problem rattling round my head for now.

The Database

This entity relationship (ER) diagram rather succinctly sums up the structure of the database. The diagram was produced using the MySQL Workbench, which is a really useful tool for creating databases.


Fig. 1 Scriblet ER Diagram
It’s likely some adjustments will be made later.

This series is about the process of building a web app: deciding on which tools, building the front and back end, designing the experience, monetisation, every aspect required.

The Web App: ‘Scriblet’

The web app itself is Scriblet which is a simple project notebook application. The app will be that place where you put all of the images, URLs and thoughts you have while working on a project. As such there will be a number of ways of adding items to a notebook from a web and Android (possibly) interface to a Chrome extension, which I think could be very useful.

Considerations

The usual considerations, such as speed and compatibility with as many browsers as possible, are very important. The plan is to have a layered structure to the front end so, for instance, if IndexedDB is available use it to improve the experience otherwise fallback to using purely AJAX requests. Everybody gets an experience but the people using the modern browsers get the best experience.

A large benefit can be gained from minifying code and combining it into one file. This video, JavaScript Programming in the Large with Closure Tools, has convinced me that Closure Tools is the way to go due the powerful Closure Compiler.

Closure Tools

The Closure Tools is a set of tools developed by Google that ease the process of building fast and efficient web applications. Google themselves have used the tools for many of their popular web apps including Gmail and Google Maps. There are three parts to the Closure Tools: Closure Library, Closure Templates and Closure Compiler.

The Closure Library provides functions common tasks such as DOM manipulation and AJAX, similar to jQuery and Prototype, as well as UI elements such as a colour picker and a date picker. Closure Templates are a templating system used to build DOM elements.

The Closure Compiler is probably the most interesting tool in the Closure Tools. It minifies code and can perform complex analysis of the code to remove dead code and rewrite code into a more compact and efficient form. Here is a demonstration of the closure compiler.

Back End

The backend will use PHP and MySQL since they are powerful, popular and familiar to me. The back end will be a RESTful web service. A RESTful service constitutes a number of things but the only aspect of interest is the client-server separation. The client sends requests that act on a resource to the server, e.g. ‘remove project book 14305′, and the server processes. The client isn’t concerned by data storage or the process of retrieving the resource and the server isn’t concerned by how the resource is displayed. This style allows multiple different clients, e.g. web app client or and Android app client, to access the resources through the same service.

Using animations in your Android applications can help create an interesting and engaging experience for your users. They can be used in games and applications in a number of ways either as a visual treat or as a method to convey information. Fortunately Android has an animation framework that allows you to easily translate, rotate, scale and alter the alpha of (or a combination) a View. Common transitions like fade in/out or slide in from off screen are examples of animations the framework can produce. Animations and Interpolators The process of animating a View makes use of two classes the Animation and Interpolator classes. The Animation class describes various aspects of the animation such as the transformation (changes in position, alpha, etc) and the duration of the animation. The Interpolator class describes the rate of change of the animation, for example a ScaleAnimation with an AccelerateIterpolator results in a View that scales slowly at first and speeds up until the end of the animation. There are a number of different interpolators the most basic LinearInterpolator to more complex ones such as AccelerateInterpolator, AccelerateDecelerateInterpolter and OvershootInterpolator. Adding Animation to a View Here is res/layout/main.xml, it contains a button called ‘butt’ that is centred in the screen.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">

	<Button android:id="@+id/butt" android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:layout_centerInParent="true" android:text="Shake!"/>

</RelativeLayout>
Now we define our animation, res/anim/exampe_anim.xml , which is going to slide the button in from the bottom of the screen to the centre of the screen scaling from 0.5 to 1 as it travels all in 1.5 seconds. The p in 50%p means parent, since the Button is a primary child of the RelativeLayout this means 50% of the screen height.
<?xml version="1.0" encoding="utf-8"?>

	<set xmlns:android="http://schemas.android.com/apk/res/android"
	android:interpolator="@android:anim/decelerate_interpolator" android:shareInterpolator="true">

		<translate android:fromYDelta="50%p" android:toYDelta="0" android:duration="1500" />

		<scale android:fromYScale="0.5" android:toYScale="1" android:fromXScale="0.5"
		android:toXScale="1" android:duration="1500" />

</set>
To start the animation use AnimationUtils.loadAnimation(context, resID) to load the animation and the startAnimation(animation) method of the View class.
butt.startAnimation(AnimationUtils.loadAnimation(getBaseContext(), R.anim.example_anim));
Read more: Creating Custom Animations

Inverse Kinematics: Part 2 of 2

September 19th, 2010

Now on to the algorithm that requires a little mathematical understanding, the Jacobian matrix method. This method approximates the IK problem as a linear problem, which it almost is if you only change the angles of the joints by small amounts. Mathematics of the Method Starting with the vector of angles, Theta We have the forward kinematic function f, i.e the function that return the position of the endpoint, x, given the angles of the joints. Theta Our goal is to find Theta this can be done be firstly introducing the Jacobian matrix as well as differentiating w.r.t. time resulting in this, Theta Since, Theta Replacing the δ operators with Δ operators to approximate the differentiation, Theta Sets us up for an iterative solution. Outline of the Algorithm
  1. Calculate Δx = Goal – f(q) if the size to Δx is small enough exit loop
  2. Compute J-1. J may not be square in which case use the pseudo inverse (JTJ)-1JT
  3. Compute Δθ = J-1Δx
  4. θ = θ + Δθ
  5. Repeat
Read more: Example, Source and Notes
Preamble Actionscript is, for the most part, a dynamically typed language, which means that the types (i.e. String, int, GameObject) of variables are checked at run-time rather than at compile-time like they are in C and Java. This is supposedly beneficial to the programmer since such a language is more flexible. All sorts of crap like this is valid:
var i = new GameObject();
i = "1";
As you can see it’s possible to change the type of a reference to something entirely different. This can generate type errors at run-time since later you may try to call i.update(). Although this example is very obvious real world examples can be more nuanced and thus more complicated to find and fix. Casting and using ‘Strict Mode’ is a technique to essentially make Actionscript a little bit like a statically typed language.  The performance boost comes from firstly doing as much as possible at compile-time (thus less at run-time) and secondly helping the process of type checking by casting. Read more: Code, Results and Conclusion

New Flash Game! Orbital

September 14th, 2010

I recently released Orbital! And submitted it to ‘Made for Mobile’ contest over at Mochimedia. Description Use gravity and well timed rocket thrusts to slingshot your ship around the planets, collecting stars and destroying debris while saving fuel and minimising time taken. Controls Initially the ship is stationary holding down the left mouse button or your finger builds up your boost. Releasing fires your ship off with the power indicated in the top left corner. After the initial boost stage use the left mouse button or finger to active the rocket thrusts, these propel your ship in the direction of the cursor. Collide with stars to collect them. Debris can be destroyed with either the missile or the mine. Select which weapon with the button in the bottom left corner or press SPACE. Rockets fly straight and the mines are affected by gravity. Read more: Play the game