BLOG

Notes from the KAYAC hyper-casual team

Interactive Content Linking a Web Browser and Unity with Firebase

Takumi Fukasawa

Hello. I'm Fukasawa from the CL Technology Department. I joined straight out of university, and this is my fifth year. (Takumi Fukasawa | KAYAC Inc.)

After about three years on the web front end, working mainly on WebGL projects, I've recently been working on AR content and on event and exhibition projects using Unity, Unreal Engine and the like. I love shaders.

I've written an Advent Calendar article every year since I joined, so while I'm at it, here are the past ones.

2015 ... WebGL isn't scary either! The recommended order to learn canvas libraries efficiently - KAYAC engineers' blog

2016 ... [Goodbye gulp] Building a simple front-end development environment with npm-scripts - KAYAC engineers' blog

2017 ... [WebGL] Sprite animation in 3D space with shaders - KAYAC engineers' blog

2018 ... The development flow of WebGL content and the points to keep in mind - KAYAC engineers' blog


The finished product

As shown below, I made a mock-up that uses a phone browser as a controller, moving an effect in Unity as you drag your finger across the screen. The source is here.

Dragging on a phone browser moves an effect in Unity

takumifukasawa/BrowserControlsUnityExample

I'll walk through the source below, but in places a single script does all sorts of things at once. It's only a mock-up, so I prioritized getting a prototype working quickly over making it scalable!

Approach

To make something happen in a Unity app in response to input in a phone browser (here, dragging a finger), I use the following setup. → shows the direction of communication.

Web → Firebase → WebSocket (Node.js local server) → Unity

Routing it through WebSocket, which supports two-way communication, makes two-way communication between Firebase and Unity possible. The setup here only goes one way, but it could go both ways too.

Environment

  • PC side
    • Windows 10
    • Unity 2019.2.15f HDRP
    • Node.js: v12.13.1
      • For running WebSocket on a local server
  • Browser side
    • iOS 13.2 Safari
  • Folder structure
    • Unity side
    • Web browser side
    • Node.js server side

On the Unity side I'll try out VFX Graph with HDRP. The WebSocket link doesn't depend on the graphics side, so it should work fine with the built-in pipeline or any SRP. In my environment it also connected fine with the built-in pipeline. I haven't tried it with a Mac as the PC, but if you can reproduce the same setup, it should work.

The folder structure in the repository looks like this.

- BrowserControlsUnityExample/
  - UnityFirebaseWebSocketHDRP/ # Unity project
    ...
  - WebController/
    - index.html # web browser page for operating
    ...
  - WebSocketServer/
    - index.js/ # script for the Node.js local server that starts the WebSocket
    ...

1. Preparing Firebase

Firebase has two database features, Firebase Realtime Database and Firestore, and here I use Firebase Realtime Database.

By the way, のびー explains the difference between the two in great detail in this article for this year's Advent Calendar.

Let's use Firebase Realtime Database and Firestore for what each is good at - KAYAC engineers' blog

To use Firebase from JS in the browser, you just paste in the snippet you're given when you create the web app, or the one from the admin console.

The Firebase snippet for a web app

Since what I want to pass along is touch input, I'll use a simple structure that just stores the coordinates. As I'll explain later, using the browser's touch coordinates as is on the Unity side is awkward, so I store values normalized to 0-1.

The data structure in Firebase Realtime Database

To write data with the structure above to Firebase from the browser, you can use code like the following. It's amazing that this is all it takes to talk to Firebase.

One thing to watch out for: since we're using the database feature, don't forget to load firebase-database.js. With Firebase, you load a separate script for each feature you use.

  <!-- The core Firebase JS SDK is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/7.6.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.6.0/firebase-database.js"></script>
  <script>
    // Your web app's Firebase configuration
    const firebaseConfig = {
      apiKey: "xxxxx",
      authDomain: "xxxxx",
      databaseURL: "xxxxx",
      projectId: "xxxxx",
      storageBucket: "xxxxx",
      messagingSenderId: "xxxxx",
      appId: "xxxxx"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);

    const ref = firebase.database().ref("coords");

    ref.set({ x: 0.5, y: 0.5 });
  </script>

2. Web → Firebase

From here on, I'll go through the steps in the order the data flows. First, the part that connects the web page and Firebase.

Building on the Firebase code above, I send coordinates to Firebase as the user touches the screen. Visually, it looks something like this.

Drawing the touch trail on a canvas

Here's an excerpt of the source.

// WebController/index.html

...

  <div id="wrapper">
    <canvas id="canvas"></canvas>
  </div>

  <!-- The core Firebase JS SDK is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/7.6.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.6.0/firebase-database.js"></script>

  <script>
    // Your web app's Firebase configuration
    const firebaseConfig = {
      apiKey: "xxxxx",
      authDomain: "xxxxx",
      databaseURL: "xxxxx",
      projectId: "xxxxx",
      storageBucket: "xxxxx",
      messagingSenderId: "xxxxx",
      appId: "xxxxx"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);

    const ref = firebase.database().ref("coords");

    const wrapper = document.getElementById("wrapper");
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");

    let wrapperWidth;
    let wrapperHeight;

    // queue of touch coordinates
    const coords = [];

    function onWindowResize() {
      wrapperWidth = wrapper.offsetWidth;
      wrapperHeight = wrapper.offsetHeight;
      aspect = wrapperWidth / wrapperHeight;
      canvas.width = wrapperWidth;
      canvas.height = wrapperHeight;
    }

    function tick() {
      ctx.fillStyle = "rgba(0, 0, 0, 0.15)";
      ctx.fillRect(0, 0, wrapperWidth, wrapperHeight);
      let i = coords.length;
      // paint once for each coordinate queued in touchmove
      while(i--) {
        const coord = coords[coords.length - (i + 1)];
        ctx.fillStyle = "rgb(255, 255, 255)";
        ctx.beginPath();
        ctx.arc(coord.x, coord.y, 40, 0, Math.PI * 2, true);
        ctx.fill();
        ctx.closePath();
        coords.splice(i, 1);
      }
      requestAnimationFrame(tick);
    }

    canvas.addEventListener("touchmove", (e) => {
      const touch = e.touches[0];
      const { clientX, clientY } = touch;
      // queue it so it can be painted inside the animation loop
      coords.push({
        x: clientX,
        y: clientY
      });
      // normalize the coordinates to 0-1
      // in real use, take the screen ratio (the canvas aspect ratio) into account
      const normalizedCoord = {
        x: (clientX / wrapperWidth) * 2 - 1,
        y: (clientY / wrapperHeight) * 2 - 1,
      };
      // send the normalized coordinates
      ref.set(normalizedCoord);
    });

    onWindowResize();
    window.addEventListener('resize', onWindowResize);
    // paint it black at the very start
    ctx.fillStyle = "rgba(0, 0, 0, 1)";
    ctx.fillRect(0, 0, wrapperWidth, wrapperHeight);
    requestAnimationFrame(tick);
  </script>

I put all the JS and CSS inside the HTML. Safari on iOS 13 supports ES6 syntax, so I just wrote plain ES6.

There's a lot of canvas-related code in there, but the only part that talks to Firebase is inside touchmove.

As I noted in a code comment, I don't take the aspect ratio (the canvas's width-to-height ratio) into account here, so when you drag diagonally, the angle differs between the browser and the Unity side depending on that ratio. For real use, you'll want to take the aspect ratio into account.

3. Firebase -> WebSocket

This section covers connecting WebSocket and Firebase on the Node.js server.

3.1 Starting a WebSocket with Node.js

To handle WebSocket in Node.js, I use the ws module. socket.io is another well-known WebSocket module. I haven't looked into it closely, but apparently socket.io uses ws internally and has more features. Since this is just a mock-up, I'll use ws, the thinner of the two.

ws

First, install ws.

> npm init // package name etc. as you like
> npm i ws

Next, I create a Node server that uses WebSocket, in a file named index.js.

// WebSocketServer/index.js

const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;
const wss = new WebSocketServer({
  port: 8080
});

// attach the event for WebSocketServer connections
wss.on('connection', (ws) => {
  // event when a message is received
  ws.on('message', (message) => {
    // send the string "Hello World." to all connected clients
    wss.clients.forEach((client) => {
      if(client.readyState === WebSocket.OPEN) {
        client.send("Hello World.");
      }
    });
  });
});

3.2 Linking WebSocket and Firebase

Now Node.js just needs to receive data from Firebase and notify Unity over WebSocket, and its job is done. To use Firebase from Node.js you need the admin module, so install it.

> npm i firebase-admin

I'll modify the program from before.

To use Firebase from Node.js, you need to authenticate with the Firebase Admin SDK.

Click the gear icon at the top left → Project settings → Service accounts, and do the following.

  1. Download the private key and rename it to whatever you like
  2. Copy and paste the Node.js snippet, and change the private key path to match the name you chose in step 1.

The Service accounts tab in the Firebase project settings

The Firebase Admin SDK snippet for Node.js

Now I'll build the part that sends the coordinates to Unity with ws.

To keep it simple, I'll send x and y joined into a single string.

If the data coming from the browser is { x : 0.5, y: 0.3 }, the idea is that the string 0.5,0.3 gets passed to Unity.

When you build real content, the data you want to pass will probably be more complex, so sending it as JSON would likely be easier to work with.

// WebSocketServer/index.js

const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;
const wss = new WebSocketServer({
  port: 8080
});

const admin = require("firebase-admin");

const serviceAccount = require("./serviceAccountKey.json"); // download the json file for authentication and load it

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "xxx" // you can find this in the Firebase admin console
});

const db = admin.database();
const ref = db.ref("coords");

ref.on('value', (snapshot) => {
  const val = snapshot.val();
  const sendValue = `${val.x},${val.y}`; 
  console.log("==================");
  console.log("value changed.");
  console.log(val);
  console.log(sendValue);
  wss.clients.forEach((client) => {
    if(client.readyState === WebSocket.OPEN) {
      client.send(sendValue);
    }
  });
}, (errorObject) => {
  console.log(`failed: ${errorObject.code}`);
});

4. WebSocket -> Unity

4.1 websocket-sharp

This library makes it easy to use WebSocket in Unity.

sta/websocket-sharp

First, open the sln file in Visual Studio and build it. I did a Debug build with the Any CPU configuration. The examples aren't needed, so I deleted them in Visual Studio.

Building websocket-sharp in Visual Studio

Put the built dll file under Assets/Plugins. If there's no Plugins folder, create one. You can just drag and drop it in, like any other asset.

The built websocket-sharp dll

Placing the dll under Assets/Plugins

The dll imported into the Unity project

4.2 Unity

Now let's connect Unity to the WebSocket server. The script is explained in comments in the source.

Here the WebSocket connection code and the code that moves the transform are in the same place, but in practice you'll probably handle many different kinds of processing through WebSocket, so something like UniRx could help separate the concerns and make things easier to follow.

// ClientSample.cs

using UnityEngine;
using WebSocketSharp;

public class ClientSample : MonoBehaviour
{
    // so the movable range can be set in the inspector
    [SerializeField]
    private Vector2 movableRange = new Vector2(5, 5);
    
    private WebSocket ws;
    private Vector3 position;
    
    // Start is called before the first frame update
    void Start()
    {
        // save the initial position
        position = transform.position;
        //  create the WebSocket instance. Match the port to the one opened by the WebSocket on the Node.js side
        ws = new WebSocket("ws://localhost:8080");
        // event when the connection opens
        ws.OnOpen += (sender, e) =>
        {
            Debug.Log("open");
        };
        // event when a notification arrives. e.Data gives the data that was sent. In this case, the string joining the coordinates `0.5,0.5`
        ws.OnMessage += (sender, e) =>
        {
            var data = e.Data;
            // becomes an array of [x coordinate, y coordinate]
            string[] coords = data.Split(',');
            // convert the coordinates for Unity. This time we move the x and y axes
            // y is multiplied by -1 because Unity is Y-up, while the coordinates sent from the web have their origin at the top left and get larger going down
            position = new Vector3(
                float.Parse(coords[0]),
                float.Parse(coords[1]) * -1,
                0
            );
            position.x *= movableRange.x;
            position.y *= movableRange.y;
        };
        // event on error
        ws.OnError += (sender, e) =>
        {
            Debug.Log("error: " + e.Message);
        };
        // event when the connection closes
        ws.OnClose += (sender, e) =>
        {
            Debug.Log("close");
        };
        // start connecting
        ws.Connect();
    }

    // Update is called once per frame
    void Update()
    {
        // update the position in update
        transform.position = position;
    }

    void OnDestroy()
    {
        ws.Close();
        ws = null;
    }
}

Attach this to the object you want to move.

ClientSample attached to an object in the inspector

5. Running it

First, start the Node.js local server. In the repository, that means running WebSocketServer/index.js.

> cd WebSocketServer
> node index.js

Next, run Unity. Just press the Play button.

Finally, open the web browser. In the repository, all you need is to open WebController/index.html in a browser. It doesn't load any other local resources, so on a PC you can simply drag index.html into the browser. To view it on a phone, run something like browser-sync and connect from the same network, or upload it to a server. There's a package.json with browser-sync in WebController, so you can also start it with the following commands.

> cd WebController
> npm i
> npm start

or 

> npm i -g browser-sync
> cd WebController/
> browser-sync start --server

And then...

The object in Unity following the drag in the browser

You can link them up like this!!

6. Trying VFX

To hook it up to VFX, I make the position controllable from a script.

To control it from a script, you need to add a property to the Blackboard. Here, I control the center of Position(Sphere) in the Initialize block.

Exposing the center of Position (Sphere) as a Blackboard property in VFX Graph

Then you can change VFX values from the script by getting the VisualEffect component and setting the property's value. Here's an excerpt of the code; the full version is in the repository.

// ClientSampleVFX.cs

    [SerializeField]
    private GameObject vfxObject;

    private VisualEffect vfx;

...

    void Start()
    {
        vfx = vfxObject.GetComponent<VisualEffect>();
    }

...

    void Update()
    {
        vfx.SetVector3("CenterPosition", position);
    }

Attach this script to an object, and in the inspector, assign the object with the VFX Graph to vfxObject.

Finally, tweak the scene with post-processing and so on until it looks the way you like.

Done!!

It works!!

The finished VFX scene Controlling the VFX from a phone browser

Summary

I was worried that chaining Firebase and WebSocket might cause a noticeable delay, but in practice I didn't notice any at all. Even with the phone on 4G, it didn't bother me.

However, since it relies on an external service, Firebase, it depends heavily on network speed. For real use you need to check things carefully, such as whether the PC running Node.js has a fast connection and what the surrounding network environment is like. In an enclosed space where 4G drops to a single bar, it might be unusable. I also haven't tried it with multiple people, so it needs more experimenting and testing with various setups, such as what happens when lots of people connect at once.

Even so, where conditions allow, I think it opens up possibilities for interactive content at events, where visitors use their phones as controllers for a big screen. Participants just load a web page and their own phones become the controller, so it also seems like a good fit for things like sharing videos or photos of the experience on social media.

In closing

Thank you for reading!!

Let's try running Firebase Realtime Database from Node.js

On the questions "Is Socket.IO necessary?" or "Does WebSocket get through?", 2016 edition | blog.jxck.io

[Unity] Sending data to a Node.js server using WebSocket | Unlit Sphere

[Unity] Real-time communication in Unity with a WebSocket library | Prime Structure TECHLOG