Friday 26 May 2017

Animation stuff

So today I was bored. I just finished Season 2 of Broadchurch and had no idea what to do. So I decided to try my hand at animation. I found this really good tutorial over here.
https://design.tutsplus.com/series/animation-for-beginners--cms-923
 More specifically I went into the character walking part of the tutorial.

Now while drawing, I realised I didn't have a way to see how my animation turned out.

So I hacked away a nice little program in C# Winforms to view it.
I dubbed it "AnimationHelper". It's fairly basic without much features, but also very simple to use. Zip up all the image files (png only;it's by design, I hate all other file formats) of the animation and load that into the program, either through the Open File button or through Drag N' Drop. The default is 1 frame per second which can be adjusted, and I have a pause/play button.

That's basically all there is. Not even a "Developer" section attributing myself as the creator, or loading directly from psd/xcf files (Photoshop and Gimp respectively),or adjusting the position,or spritesheet adjusting, or basic editing, or exporting it as a video. None of that fancy stuff.

But it got the job done nicely, and I liked stuff I made myself which I can trust.

Side-thought : The code was hacked together so badly I'm not sure I can even trust my own code.....The Irony.

If you're looking to use something like this and are looking for a Download Link, Let me reassure you I will definitely not release this. It's an abomination. It's a single-platform only hacked together code in a couple hours by someone who barely even knows C#. The only good thing I could say about it is its simplicity.

If you want something like this I suggest this place (I am not sponsored, this is not mine)

https://www.leshylabs.com/apps/spriteSheetAnimator/

It's written in HTML5 by the way, so if you're worried about not having a connection when you want to use it, Just hit Ctrl+S (Or whatever the Apple Equivalent is...) on the page.

Well.... back to drawing instead of procrastinating at my terrible art skills and making a program for no reason.

Wednesday 24 May 2017

You Won't BELIEVE what I found in the new Spiderman : Homecoming trailer!

Note that I like to pander about, talking about whatever comes to mind, if you want to get straight to the analysis scroll down till you see the code.

I found decorative computer code. There, now send me an angry comment for the clickbait and be on your way, Internet stranger.
(But pls remember to tweet how angry you are and don't forget to link this and Google Plus this (I don't judge you for using that) and Facebook and send this to all your friends! Email if you have too! Or -gasp- talk to your friends about this!)
....
plz
....
 i hvae no raeders
....
I am broken inside
...
 :'(
....

Anyway here's Spidey's suit given to him by Tony

(Image courtesy of Sony, screencapped from the Youtube trailer, (98027 views as of writing) all of these are from there, don't sue me please :(  
 I'm also pretty sure it's legal for me to use this under fair use as long as I don't use it in it's entirety for educational purposes or something like that, so there's that. Sorry for rambling, readers. Wait I thought I have no readers?)

Looks pretty cool, apparently the red and blue isn't painted on but is emitted through the suit. Handy
for changing colour schemes and logos in the future without having to come up with the old "Upgraded suit" cliche.

Looks like the entire suit is a circuit. And guess what, it's programmable too!



Anyways here is the code, presumably in-universe written by Tony Stark. I believe this is the first time we see his actual code on-screen in the MCU.



So, either Tony left some code for Spidey to play with (but he blocked out most of it with "The Training Wheel Protocol", wow Tony. Just. Wow.).

I heavily suspect there is more code at the top and bottom, but the screen is scrolled somewhere in the middle of the code. That also explains the "boxAnchor + offset" meaningless code at the bottom, it's not fully displayed and maybe it's a typo or something.

If someone could identify the language used (assuming it's a real language), I would appreciate it. Right now my theory is....Javascript? I honestly have no clue.

So let's take a look at the code. I've written down for you, the non-existent reader's, convenience

MODEM BACKUP
boxTopLeft = box.toComp([0,0]);
boxBottomRight = box.toComp([box.width,box.height]);
boxAnchor = box.toComp(box.anchorPoint); xRatio = deltaX/distanceEdge;

deltaVec = sub(targetPos,boxAnchor);
deltaX = deltaVec[0];
deltaY = deltaVex[1];
xRatio = 1;
yRatio = 1;

if (deltaX>0)
{
    //target is right of anchorPoint
    xDistanceToEdge = boxTopLeft[0] - boxAnchor[0];
    xRatio = deltaX / xDistanceToEdge;
}

else if (deltaX<0)
{
    xDistanceToEdge = boxTopLeft[0] - boxAnchor[0];
    xRatio = deltaX / xDistanceToEdge;
}

if (deltaY>0)
{
    //target is below anchorPoint
    yDistanceToEdge = boxBottomRight[1] - boxAnchor[1];
    yRatio = deltaY / yDistanceToEdge;
}

else if (deltaY<0)
{
    yDistanceToEdge = boxTopLeft[1] - boxAnchor[1];
    yRatio = deltaY / yDistanceToEdge;
}

ratio = (xRatio>yRatio) ? xRatio:yRatio;
offset = div(deltaVec,ratio);
boxAnchor + offset

.;
MYCONFIGPROGRAM,SH
CREATE_SAMPLE_FILES,SH            BLURRY
./BACKUP:
DAVINCIPROGRAM.SH POWER.NEURAL.;     BLURRY
# FIND -INAME "POWER.NEURAL.1"

So yeah. Sorry I can't read the super blurred out section on the left.
Tony Stark has some really buggy code.By the way if you want, look at the picture you can see his style of writing code, the positioning of brackets and the like. Just an interesting observation, a man's style of writing is as expressive as his walking gait and personality in my opinion.

So at first glance, I think it's definitely something to do with geometry as evidenced by all the coordinates of Xs and Ys and Vectors.

Now I was too lazy to actually read the code, so I made up 2 hypotheses as to what it could be
  1. Detection for where to shoot web (it was mentioned there was 576 possible web shooter combinations in the trailer)
  2. Spidey's Heads Up Display GUI
Yes. Spiderman does have a HUD like Iron Man.



Honestly I like him better independent. Ah well it's a kick-ass cool suit.

I ruled out the first theory because  it seemed to simple for pattern recognition and the like.For some daft reason, I also ruled it out because of the lack of a 'z' coordinate in the real world. Only a little later did I realise that cameras on the suit (if there are any) would capture in 2d hence the lack of a z coordinate.

So it's likely to be used somewhere in Spiderman's HUD.

But what is it actually?

it seems to have an input a deltaVec 2d coordinate, a bounding box which I assume contains the deltaVec (it makes sense), and the target 2d coordinate I assume is away from the box.


(Yeah, sorry I didn't have my tablet at the time and now I'm too lazy)

First off it calculates the ratio between a) distance between the delta and the side of the box (in the direction of the target) b) distance between the input and the target.
Rinse and repeat for all possible cases for both x and y (4 cases, calculate X for left and right, calculate Y for up and down).

Note within a note : It may seem there are cleaner ways to do this with less code (i.e: taking the absolute value only so that eliminates
the need for if statements), but after some thinking, the code provided is actually the most readable way of doing this.

It seems to target the higher ratio first, that is, the one with a further distance to target and smaller distance to side of box,
then divide the delta vector by that "bigger" ratio.
What I don't get is why it chooses the "bigger" ratio for dividing *both* x and y coordinates in the vector. it would make more sense
for

offset = div(deltaVec[0],xRatio);
offset = div(deltaVec[1],yRatio);

where deltaVec[0] and deltaVec[1] are the x and y coordinate respectively.
THIS would have created a still weird but totally slightly more logical normalization.
No idea why it does what it does. Hit me up with a comment if you have a theory and definitely contact me if you managed crack the whole thing wide open and figured out what it does.

For the curious wondering what a normalization is, Wolfram Alpha defines it as so:
The normalized vector of x is a vector in the same direction but with norm (length) 1.
 This is used in conjunction with targetCoordinates-playerCoordinates to get the direction vector to move and multiply that with a speed float instead to control the speed. So a player from (0,0) to enemy (3,3) would give (3-0,3-0) and thus (3,3) as the direction (northeast). So That's is essentially moving (1,1) at a speed of 3 units per second. What normalising does is take the (3,3) and makes it into a (1,1) but the ratios must still be the same (3:3 is equal to 1:1)

Yes I understand the so-called "normalization"  does not have a unit length of 1. I'm still fairly sure the ratios are still the same though. I have no idea why or how they Tony did it like this. Genius level code obfuscation?

Hit me up with a comment if I got normalization completely wrong.
Be as harsh as you want, I have no emotions.

Hit me up with a comment if I got spelling errors.
Be as harsh as you want, I have no emotions.

Hit me up with a comment if you want to talk.
Be as harsh as you want, I have no emotions.

Side-thoughts:
The script "DAVINCIPROGRAM.SH POWER.NEURAL.;" seems to indicate a shell script named after Leonardo Da Vinci. The word Neural, which I first read as Neutral (assuming like as in Live, Neutral, Earth/Ground) but upon reinspection it is most definitely Neural. This word, along with the word Da Vinci, leads me to believe that this is a shell script for activating a Artificial Neural Network (Artificial Intelligence) for pattern finding in the real world through cameras to estimate where best to shoot those webs. Keep in mind this is a long shot and just a not-very-useful movie-wise theory which will likely never get verified (or debuked).

What the heck is "xRatio = deltaX/distanceEdge;" for?
xRatio gets reassigned a few lines later without ever being used.
Perhaps out of the reach of the screen we could not see it was being used for something though.
Why that weird ugly style of coding for someone of the likes of Tony Stark? I do not know.

All in all I was impressed with how they handled the code in the trailer. It might not be the perfect code, but honestly it's good enough for just a quick glance even by a coder.It visually feels interesting while not falling into the trope of having animated ASCII art and colourful GUIS all over the place with an deliberately attention-seeking "Look at me I'm a computer genius look at these random 0s and 1s and scrolling of texts in a green font" type of code. It even seems to be doing something, something related to the suit without ever mentioning "Spider" or something in the code, though I still for the life of me do not know what that something is.

But then again, fools know nothing.
(that was supposed to be a profound endin-

Sunday 5 February 2017

New Direction

Hello! I'm sure you're glad to learn that this blog isn't dead yet =)





There we go, a notification to remind you that there's something new in store. so... what's the message?

Basically, I've come up a new idea for an app, thus explaining the title, as I would be gearing my learning experience towards realizing this new app idea that I've conceived. What's it about? Well, that part would unfortunately have to remain a mystery for now, but it is safe to say that the mechanism of Notification plays a big role in this app(which is also why my very first priority was to learn how to code a phone notification).

That's about it for this update, really. I admit guiltily that I haven't really been spending as much time on programming as I should, so hopefully this post serves as a reminder for myself to set the wheels rolling and devote more time in this endeavor of mine.

After all that's what a notification is for, right? A reminder.

Tuesday 10 January 2017

Baby steps

Alright, I'm officially a beginner developer now! Looking at that fancy emulator booting up to my simple program, I'm already thrilled to my bones with excitement. This also marks my transition into Javaprogramming instead of my old tool C++, as android studio provides a native support for java.

Alrighty, first things first. My primary objective today shall be to run a makeshift app on my smartphone. Nice and simple, ey?

--- 1.5 hours of excruciating troubleshooting later ---



I've finally managed to install adb drivers on my computer! Gosh.


"file path not accessible..." "phone not detected..." tons of unexpected issues seem to jump out of thin air to dissuade me of my very first attempt, and the worst of all - I can't find anyone else online with the same problem as me! I'm forced to go the hard way, digging through forums after forums, restarting my computer a good number of times and downloading strange files on the Internet with only one thing in mind: One of these oddballs is going to fix my problem.

But of course, bad spell doesn't last forever, and eventually my Android Studio reported a build success and all the files begin compiling. I held my breath for a good dozen of seconds, then voila! My phone screen lights up with a blank screen and a lonely textbook that says 'Name'. Almost in an instant the voice in my head telling me that 'I'm wasting this whole night on nothing' was pulverized, and I'm left with a heartfelt glee.

This is gonna be fun.

Monday 9 January 2017

New Beginnings - Android App Development

So me and my friend decided to embark on a learning journey to hone our programming skills and I'm very excited getting into this big ambitious project. Since this is my very first post on the site, I'll start off by introducing myself! Hooray!

My online alias is ImSandwich, and I'm avid sandwich eater. My favorite combination of food? Ice cream sandwich, of course! For that very reason, I am a fan of Android(referencing to OS Android 4.0, "Ice Cream Sandwich"). Sorry, Apple! You're still my third favorite fruit though ~(^.^)~

With that in mind, I settled on spending the next half year in pursuit of mobile phone app dev. I have toyed around with Visual Basic, C# and C++ programming on Visual Studio IDE before, and now I can't wait to extend my reach by delving into Android app development. Let's take a look at my progress as of right now...

Buckle up folks, because a new guy is coming to town!







As you can see, I'm already making baby steps towards my dream, and I promise you I'll keep you updated on every niche of my progress, keeping no truths hidden about the life of a school-teenager trying to get his hands on the computer world. To spice things up, my friend and I have challenged each other to report our individual progress once every 3 days, so fear not that this blog will ever go silent! We might want to come up with punishment ideas for whomever breaks this rule, but in the meantime, I should get started with all dem Youtube tutorials!

Ciao

Sunday 8 January 2017

Adventures in pathfinding (and more!)

Looking at my to-do list, I realised I haven't done any projects with pathfinding yet. "Whelp, I better get to it then".

Although my original goal was to create a Pacman clone, I find the code too bloated to work with. More on this later in the article.

This article was aimed to non coders but it slowly turned into something a bit more complex....Just ignore the parts you don't understand. I try to use as much non confusing terminology as possible.

Also keep in mind I wrote this around midnight while I was very sleep deprived. And apparently blogspot hates me because it keeps glitching out on me.

What is Pathfinding?

"Pathfinding...is the plotting, by a computer application, of the shortest route between two points." - Wikipedia.

It is typically used in video games to find the points an enemy would need to move to get to the player (i.e: Pacman). Here, the two 'points' are x and y coordinates. Pathfinding itself however is not bound to 2d Cartesian planes. For example, it could be bound to a 3d space to find the route from one point in 3d space and another. Another example, which is what is typically used in 3d video games, is to create a navigation mesh, or navmesh, a polygon where each edge is connected to another navmesh.


Algorithms

There are plenty of pathfinding algorithms out there, Djikstra's algorithm, A* algorithm, Breadth first search, etc.

I will be concentrating on Breadth first search, Greedy Best first search, and A*.

The reason why is because I find the level of difficulty in implementing those to be in ascending order, so I could code the former and add on to it for the next algorithm.

Coding language

Now was the time to decide what language to use. I considered C++, Python and Javascript with HTML5 to work with. Each had their pros and cons.

C++

Pros:

I am familiar with the language.

Cons:

Bad for quick prototyping, making small changes (which would be inevitable seeing as this is my first time implementing pathfinding algorithm) would require long compilation times.

Python

Pros:

Good for quick prototyping, because it is an interpreted language.

Cons:
I personally don't like Python.


And so I decided to go with Javascript, or more specifically, ECMAScript6, because I wanted to have classes and OOP capabilities. At the time it seemed like a good idea.....

Tile Editor

So I needed somewhere to design the level maze.
Now obviously I am too lazy to write my own tile editor, so I went with Tiled. Search it up, I don't want to link to it. It exported to a JSON file which played nicely with the Javascript code.

How it works

First off, the Breadth first search algorithm. What this basically does it is to "visit" to all directly adjacent nodes from the destination goal, and repeat the process for every adjacent node until it reaches the goal.  From there, it backtracks to get the route. Think of it like you want it to traverse as evenly as possible in all directions. You never wander too far off in one direction, each step you take, you  go back and go one step forward in all the other directions.

What is a node you ask? Well in this case, it's just the position in the game. The x and y coordinate combined.


Pseudocode 
  
BFS
Args: Destination position, Current position
Nodes.push(x);

FOR x in adjacent(Current)
      x->parent = Current
      BFS(Destination, x)

After a few iterations, it would look something like this (the white square is the enemy and I am the red square) 

  Funny how it looks like a ship, right?

Greedy Best first search

GBFS
Args: Destination position, Current position
FOR x in adjacent(current position)
       x->parent = current
      x->score   =  distance(Destination,x)
      GBFS(Destination position, Nodes.GetLowestScore())

So it favours the one which, according to the distance function, is the closest path. This sometimes leads to false alarms though, because you may traverse so far near to the destination only to find it is blocked.

A*
Args: Destination position, Current position
FOR x in adjacent(current position)
       x->parent = current
      x->score   =  distance(Destination,x) + x->parent->score
      GBFS(Destination position, Nodes.GetLowestScore())
 
A* uses the distance from the starting point in addition to the distance to the destination .

Both A* and Greedy Best first search worked the same in my level....

Here is a random screenshot of me trying to find a bug
What is happening is that my code "visits" every adjacent node, assigns a parent, and repeats itself with the next node. A nice way I found out for debugging was to use a "Blob", which is something like an internal file, to gather the debugging information,set the MIME type to a text file, and use it to create a blob:// url, which would make a downloadable text file. Otherwise I would have to keep going to the Inspect Element console to check for debugging info, which was very inconvenient.

Other Stuff

Views

This was also my first time implementing "View"s, allowing me to zoom in/out as well as to "follow"
the player. Surprisingly, it was not that difficult. I had a ProjectionScale multiply every speed variable and size variables, and as for the Viewport, I simply added two variables, scrollx and scrolly, to determine where in the screen to go to.

Here's a screenshot of a bug I thought was interesting early on in the development.

Code maintainability

I'm sure it's more of my less than impressive coding skills at fault, but I found difficulty in maintaining the code. In javascript, there are no "private" fields for classes (there are techniques to simulate this however, but I didn't implement that) making everything very cluttered.

Oh? There's something wrong with my m_collisionRect, let me add breakpoints to every place that is modified in Player.js.

"Two hours of debugging later.."

Oh! so I actually modified Player's collision rect in the GameplayScene file instead as a quick fix! Well... That's two hours of my life I'm never getting back.

In addition to that, being a C++ kinda guy, I felt very uncomfortable doing what I assume is copying everything whenever I pass it to a function instead of being able to pass it as a reference. I even miss having pointers!

In future, if I were to use Javascript for HTML5 games, I would firstly go to a good site to re-learn Javascript. Then I would ignore everything OOP and simply use vanilla Javascript, perhaps with the Phaser library. (Google it, I don't want to link.)

5 Steps to Polishing it

At some point in the future, I would polish up the code and then turn it into a real pacman game. Turning it into a real pacman game shouldn't be too difficult, just add the pellets and more ghosts enemies. Interestingly, the ghosts in the original Pacman had very specific characteristics. The red one would follow you directly behind, the pink one would try to cut off your paths by going in front of you. The orange one is stupid and moves randomly. Finally, the blue one would alternate between the other three. On top of all this, the ghosts would periodically all at the same time move to the four corners of the game.

Back to my tech demo thing,

First off, adding title screens and pause menus. This gives the first impression on the player instead of just launching them into a game.

Second, Animation, animation, animation. Moving objects are aesthetically pleasing for our eyes. Having a mostly stationary game like mine leads to boring visuals.

Third, Bright colours! Same idea as above. Makes it nicer to look at.

Fourth, smaller levels! While the one I did was okay for testing the pathfinding algorithm, smaller, nicely designed levels gives it a more "compact" feel as well as reducing the player's concentration on unnecessary lengths of tiles. This also everything to be a bit bigger, which is good because you don't have to squint your eyes.

Fifth, Music and SFX! An often underappreciated trait. The music needs to follow the mood of the game, and not be too short and repetitive. Appropriate sound effects are also very powerful in being more immersive. This is, besides the graphics, the main way of "rewarding"  the player for doing such actions such as collecting a pellet or defeating a ghost. The sound (and flashy colours) is what makes the experience all the more addictive!

Conclusion

Well, I can conclude I am very bad at coding efficiently and completing goals. My time management also needs improving, there was a time I forgot all about this project and only continued on it yesterday. But the important thing is I learned how to implement pathfinding algorithms and can concentrate more on the code design patterns next time instead of "quickly prototyping" the algorithm and making a mess of the code in the progress due to me having "temporary quick fixes" which then escalates to the universe blowing up. Okay, maybe not the universe, but the code base will definitely be messed up and if I didn't use a repository, I could lose weeks worth of code.

Also it's very important now I can brag tell people I know how pathfinding algorithms work and go into detail of the inner workings.