Saturday, February 6, 2016

Using Unity3D's UNET to Make a Multi-Playered Model that Allows Users to Take Turns

Intro
So this is a base model that can be expanded to fit a number of multi-playered games that require the users to take turns, such as board games, Jenga, Battleship, etc... In this tutorial we're going to be making a "game" that allows for an infinite number of players to connect and change the color of a central block when it is their turn. https://youtu.be/c5dOCmh2RMQ

1)     Create a flat plain, color it if you wish.
2)     Create an Empty GameObject and name it NetworkManager
a)     Add the component Network->(Network Manager HUD)
3)     Create an empty GameObject, name it Player. Make it a prefab, delete from the Object hierarchy. Even though the player won’t have a physical body that they will be controlling, this step is necessary for the NetworkManager to manage the players.
a)     Give it a Network->NetworkIdentity Component.
b)     Create and attach the PlayerControllerScript to the Player Object.
using UnityEngine;

using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;

public class PlayerController : NetworkBehaviour
{
    [SyncVar]
    public Color cubeColor;
    [SyncVar]
    private GameObject objectID;
    //determines which player's turn it is
    [SyncVar]
    public int turn;
    //determines which player the current player is
    public uint player;
    private NetworkIdentity objNetId;

    Text playerText;
    Text identityText;

    void OnDestroy()
    {
        GameStateManager.removePlayer((int)player);
    }

    void Start()
    {
        //The network manager assigns network identities dynamically,
        //so just use this value as the current player's id
        player =  this.GetComponent<NetworkIdentity>().netId.Value;

        //add player id to network
        GameStateManager.addPlayer((int)player);

        //get the current turn
        turn = GameStateManager.getPlayerTurn();

        //initialize player text, tells who's turn it is
        playerText = GameObject.FindGameObjectWithTag("PlayerTurnText").GetComponent<Text>();
        playerText.text = "It's working";
        //tells you which player you are
        identityText = GameObject.FindGameObjectWithTag("IdentityText").GetComponent<Text>();
        identityText.text = "Player " + turn;
        identityText.color = new Color(Random.value, Random.value, Random.value, Random.value);
    }

    // Update is called once per frame
    void Update()
    {
        if (isLocalPlayer)
        {
            //checks to see if the player clicked
            CheckIfClicked();
            //makes sure that the player turn text is synced
            CmdGetTurn();
            changeTurnText();
        }
    }

    void CheckIfClicked()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //update the variable
            CmdGetTurn();
            //check if it's my turn, if not, exit out
            if (turn != player) return;
            CmdChangeTurn();

            //change the color
            objectID = GameObject.FindGameObjectsWithTag("Tower")[0];
            cubeColor = new Color(Random.value, Random.value, Random.value, Random.value);
            CmdChangeColor(objectID, cubeColor);
        }
    }
 
    //updates state on the server
    [Command]
    void CmdChangeTurn()
    {
        if (turn == player) GameStateManager.nextTurn();
        turn = GameStateManager.getPlayerTurn();
        //syncs this all clients connected on server
        RpcUpdateTurn(turn);
    }

    /*
    * Changes the turn text of the player
    */
    void changeTurnText()
    {
        if (turn == player)
            playerText.text = "Your turn. ";
        else if (turn != player)
            playerText.text = "Opponent's turn. ";
    }

    [ClientRpc]
    void RpcUpdateTurn(int i)
    {
        turn = i;
        changeTurnText();
    }
       

    [Command]
    void CmdGetTurn()
    {
        turn = GameStateManager.getPlayerTurn();   
    }

    [Command]
    void CmdChangeColor(GameObject go, Color c)
    {
        objNetId = go.GetComponent<NetworkIdentity>();
        objNetId.AssignClientAuthority(connectionToClient);
        RpcUpdateTower(go, c);
        objNetId.RemoveClientAuthority(connectionToClient);
    }

    /*
     * Being sent from server to
     */
    [ClientRpc]
    void RpcUpdateTower(GameObject go, Color c)
    {
        go.GetComponent<Renderer>().material.color = c;
    
    }  
}
4)     Create a Cube Object, and name it Tower. Make it a prefab and delete from the hierarchy.
a)     Give it a Network->NetworkTransform. Ensure that the Transform Sync Mod is “Sync Transform”
5)     Create an empty object named TowerSpawnLoc, make it a prefab, delete from hierarchy.
6)     Create an empty object named GameManager
a)     Create and attach TowerSpawnLoc script to it
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using System;
using UnityEngine.UI;

public class TowerSpawnLoc : NetworkBehaviour
{
    [SerializeField]
    GameObject towerPrefab;
    [SerializeField]
    GameObject towerSpawn;

    public override void OnStartServer()
    {
        SpawnTower();
    }

    void SpawnTower()
    {
        GameObject go = GameObject.Instantiate(towerPrefab, towerSpawn.transform.position, Quaternion.identity) as GameObject;
        NetworkServer.Spawn(go);
    }
}
i) Add the parameters, Tower Prefab->Tower, Tower Spawn->TowerSpawnLoc
b)     Create and attach the GameStateManager
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using System.Collections.Generic;

public class GameStateManager : NetworkBehaviour
{
    //an enum, Player 1 = 1, Player 2 = 2.
    public static int playerTurn = -1;
    public static ArrayList connectedPlayers = new ArrayList();

    //call this every time a player connects
    public static void addPlayer(int networkId)
    {
        connectedPlayers.Add(networkId);
    }

    //call this every time a player disconnects
    public static void removePlayer(int networkId)
    {
        connectedPlayers.Remove(networkId);
    }

    public static int getPlayerTurn()
    {
        if (playerTurn == -1) playerTurn = (int)connectedPlayers[0];
        return playerTurn;
    }

    /*
     * Increment the player's turn
     */
    public static void nextTurn()
    {
        int currentIndex = connectedPlayers.IndexOf(playerTurn);
        if (currentIndex == connectedPlayers.Count - 1) playerTurn = (int)connectedPlayers[0];
        else playerTurn = (int)connectedPlayers[currentIndex + 1];
    }
}


Wednesday, January 13, 2016

Final Semester!

This week I've begun the final semester at the University of Utah! Part of me is excited to be finished with school, but part of me is sad. I've had some great classes, and I've had interesting electives, but there's other electives I'd like to take that I won't have a chance to, such as Natural Language Processing, Compilers, Advanced Algorithms, Machine Learning, Artificial Intelligence, etc... I've contemplated pursuing my Master's Degree and taking these courses. I know that I'll probably get exposure to these topics in my professional career, and I don't have to be enrolled in the University to learn any particular subject!
While I am infected with the infamous "senior-itis", I chose a particularly difficult final semester. Thus far in my schooling career, I've taken electives that focus on application building. I enjoy developing software. When I started this major, I wanted to know how to make websites, desktop applications, and mobile apps. For the first year and a half, I felt like I didn't know how build anything that would be useful in the real world. I was unsatisfied. Then I started taking electives that bridged the abstract programming skills I learned into creating real world applications. In my Databases class, I created a robust website to manage a bookstore. In my Web Software Architecture course, we learned how to create complex websites from scratch. I designed and implemented my own multi-user Android App, that utilized a REST API that I created myself. It was a great feeling, knowing that I could create applications that could be useful and help people!
Our Undergraduate Adviser discouraged people from taking courses that I just described. He said that all you learned from those courses was how to program, and you can learn how to program at any job. Ironically he's the instructor for the Web Software Architecture course. He emphasized the need to take classes that were more low-level, and more involved with math. He said that that was the difference between a mere programmer, and a computer scientist. I don't agree 100% but, now that I feel comfortable in the different facets of software development, the more inclined I find myself towards wanting to learn more about the low-level layers, and math based stuff.
I've chosen to take Data-Mining and Computer Vision to finish up my schooling career. They're both heavily involved with Linear Algebra, Discrete Math, Probability, Statistics and 3D Calculus. It's going to be a challenge, but I want to step outside my comfort zone and learn more about these topics. I feel like data-mining is essential in the world of big data. I don't see the amount of generated data decreasing any time soon. Also image recognition is going to be very important as the world immerses itself deeper and deeper into a digital era.

Go Utes!

Saturday, January 9, 2016

Quarter Note Triplet vs. 16th Note Music Pattern

Introduction

While recording at the studio this week, I was discussing with the producers about two common drum patterns, that people often get mixed up. It's a very subtle difference, but they challenged me to go home and to look at it more thoroughly, so I did. I created each drum pattern in MIDI and compared them.  I also wrote out the beat in sheet music to help me see the difference. In this article, I included an mp3 track of 4 measures of each drum pattern so you can listen to the difference.


1. 16th Note Music Pattern

Notice that each of the notes are eighth notes, and are aligned on a 16th note grid. Very simple beat.


2.  Quarter Note Triplet Pattern

The most interesting part of this is the kick drum in the first two beats, so I cut out the last two beats. Notice that the grid is locked on triplets.


3. Comparison of Beats on a 16th Note Grid

So I lay the two on each tracks next to each other to compare them. Lo and behold, they're different.
The top beat in green is the triplet quarter notes. Notice how the notes don't line up at all on the 16th note grid? The 16th note pattern is in red.


4. Comparison of Beats on a Triplet Grid

This is similar to the graphic above, except this is on a triplet grid. Surprisingly, the red 16th note pattern lines up within the lines.


5. Sheet Music Notation Comparison

I used TuxGuitar guitar tab notation to write this sheet music. It allows me to tab drum beats.


6. Conclusion

I love music and since I've started college, I haven't had many opportunities to nerd out and analyze small music details like this. I wanted to document what I learned, and specifically share this with my band, because one of our songs has a beat like this. We've been guilty of playing both of the beats in the same run through of the song. So hopefully this will help us pick one, and stick with it. I personally like the 16th note pattern better. I feel like it's heavier.

Wednesday, December 30, 2015

SQL, many small queries or one big queries?


When writing an application, it seems conceptually simpler to make many small queries. On a small scale, this seems to be okay. What about large scale applications? Would the application take a performance hit?

Here's some pseudocode that given a list of employee ids, gives you a list of employee names:

      //simple function that returns a name given an employee id
      func getName(var id) {
              data:= sqlQuery("SELECT employee.name FROM employee WHERE employee.id = " + id + ";")
              return data;
      }

      func Main(){
            Int[] ids := [1, 2 3]
            Str[] names := []
            ids.forEach id => do
                  names.add(getName(id))
            end
      }

For me, this seems clean and easy to read. Every time that you want an name, provide the method with an id. Simple. But does this solution scale? What if the list of ids was 50,000 names, or even 50 million? The overhead of the DB parsing and processing each request and potential network traffic make the idea that fewer queries are generally faster, make sense. This does make the application code a bit more complex


 func getName(Int[] ids) {
              sqlString:= ""
              ids.forEach id => do
                   sqlString += "or employee.id = " + id
              end
              Str[] names := sqlQuery("SELECT employee.name FROM employee WHERE employee.id =" + sqlString +";")
              return names ;
      }

 func Main(){
            Int[] ids := generateRandomIds(50000)
            Str[] names := getNames(ids)
         
      }


Here's a couple of posts that I read about the subject:

  • http://dba.stackexchange.com/questions/76973/what-is-faster-one-big-query-or-many-small-queries
  • https://technet.microsoft.com/en-us/library/ms190623(v=sql.105).aspx

Saturday, December 26, 2015

How to configure a RESTful server with WAMP hosted on EC2 instance

This is a RESTful server implementation for my Android app. It is written in PHP, and uses MYSQL. I'm hosting it on WAMP. It accepts GET, POST, PUT, and DELETE requests. It sends and accepts responses in JSON. This was harder than expected to implement, so I hope that this helps somebody out. I launched this on my local Windows Machine for development, and on an EC2 Windows Instance.

How to setup:

  1. Download WAMP onto your local machine.
  2. Modify the httpd.conf which is located in wamp/bin/apache/Apache2.4.4/conf. -Append this line to the end: Alias /users "c:/wamp/www/api/index.php"
  3. Create a folder and file named c/wamp/www/api/index.php
  4. Place this code in index.php. (And obviously modify it to you needs.)
  5. Restart your WAMP server. (Or start it if it's never been started.)
  6. Navigate to the URL http://localhost/quotes Note: You may need to try http://localhost:80/quotes orhttp://localhost:8080/quotes if your server is configured as such. You may need to reconfigure wamp to accept connections on port 8080 because Skype defaults to 80.
  7. Customize and enjoy! Use Postman to test it out.

Get the code here.

Sunday, December 6, 2015

Music Based Authentication | Video Demo

Here' s a live demo of my Network Security team project, Music Based Authentication. Here I show authenticating with a MIDI keyboard, and on my PC keyboard.


Thursday, December 3, 2015

Help Me Gather Research for my University Project by Answering Three Simple Questions! Music Based Authentication


TAKE SURVEY

UPDATE:

We're most interested in your thoughts about a music based password, more than a specific implementation. Our current implementation includes but hypothetically isn't limited to taking in input from a physical MIDI keyboard, and a computer program that maps keystrokes to musical notes. (See the first iteration of our interface below!)

Description

I'm working on a team project for my Network Security class at the University of Utah. We are creating a music based authentication system. When creating a password, you not only want something that is strong and secure, but also easy to remember. Many current password methods enforce it's users to create strong passwords that are hard to remember. (e.g. You've seen password generators ask you to choose a password that contains at least one-upper case letter, one lower-case letter, one number, be at least 8 characters, have no repeated values and a special character.) We are arguing that remembering a musical melody is easier to remember than a long password string. I always seem to get songs stuck in my head, but I can never remember long and complex passwords.

Our professor has asked us to conduct a small amount of research, to branch out from our anecdotal evidence, to see if people found the idea of using music based authentication instead of regular password authentication useful.

Please take this quick 3-question survey and let us know if you think a music-based password would be useful or interesting!

Thank you for your time and interest!




Other factors to consider

There's other ways of authenticating, which are worth considering when deciding whether a music based authentication would be useful from a user point of view. 
  • Biometrics, such as fingerprint or eye scanners. 
  • Last Pass: a platform that stores all of your passwords
  • Using Facebook or Google Account to log in.

My anecdotal evidence

This idea is more of a cool novelty. I got the idea mostly because of the video game, Resident Evil. Parts of the game require you to play musical melodies on a grand piano to advance to the next part of the level.
Also I think that musical melodies, such as "Ode to Joy" are much simpler to remember than long strings. I can picture the melody quite clearly in my head, even though it has been 3 years since I've heard it or played it. I constantly find myself looking for the Forgot Password? button on many of my online accounts, even though I just reset the password a couple weeks ago.  



Resident Evil, playing Moonlight Sonata to advance in the level.

Is music based authentication actually secure? How secure?

This section is irrelevant to the question we pose in our survey; I only include this if you're interested, or your decision of it's usefulness depends on whether or not the password is strong or not. There's three aspects to consider when answering this question. The second and third aspects being more interesting, and ultimately the focus of our project:

  1.  We are using a TLS 1.2 handshake to set-up a connection between a client and server that will provide key network security features, such as perfect forward secrecy, protection from an eavesdropper, server break-in, person in the middle, and offline dictionary attacks. A shared secret is used to produce session keys that will encrypt correspondence between the server and client.
  2. We are interested in figuring out just how complex a musical password can be, how many bits of entropy does it have? Typing a string password, the only factor is the order of the individual characters. Music not only has to worry about the order of notes, but rhythm, note duration (quarter notes, half notes, eighth notes), note dynamics (ff, f, m, p), etc... We are currently researching and investigating this question. 
  3. Some passwords are easy to guess because they are common, or follow patterns. I imagine the melody of "Twinkle Twinkle Little Star" being a common password. We're interested in how to choose a strong non-predictable melody that is also easy to remember.
Our protocol
revised api complete.png

Current GUI Interface


Notice that notes are mapped to keyboard notes.