BLOG

Notes from the KAYAC hyper-casual team

Making My Debug UI Independent of UGUI with a Homemade Raycaster

Takashi Hirayama

The DebugUi sample screen

Hello. I'm Hirayama from the Technology Department.

I wrote before about making a debug UI library, but it turned out not to work on HoloLens, so I improved it. I've overwritten the previous code, but please note that, unlike last time, it hasn't been tested in an actual product, and the interface differs from before. There's also a package.

In this article I'll write about something I did along the way: making my own Raycaster, the mechanism that detects clicks and drags.

Raycaster overview

To determine which gameObject a mouse or touch input was aimed at, EventSystem uses something called a Raycaster.

Hit detection against Colliders placed in 3D space is handled by PhysicsRaycaster, and hit detection against elements inside a Canvas by GraphicRaycaster.

Both are classes that inherit from UnityEngine.EventSystems.BaseRaycaster, and are attached as components to some gameObject. According to the official code, it looks like they're built to register themselves in a static list inside EventSystems in OnEnable and OnDisable.

No matter how many Raycasters there are, only one event fires, so if, for example, it fires on a Button in a Canvas, a cube with a Collider at the same position on screen won't fire.

Background to this change

The selling point of my debug UI library is that it creates only one gameObject no matter how many buttons or sliders there are. Drawing was done with a CommandBuffer, and clicks and drags were picked up with GraphicRaycaster. GraphicRaycaster can't be used without a Canvas, yet the Canvas's drawing wasn't being used, so I was in the icky position of using AddComponent to add a Canvas just to receive events.

Normally, if you want to detect clicks and so on for something drawn with a MeshRenderer, you'd attach a PhysicsRaycaster to the Camera and attach a Collider to the object with the MeshRenderer. It would have been nice if I could do that, but unfortunately it doesn't work here.

That's because in my DebugUi, elements like buttons and sliders don't have gameObjects, and there's only one GameObject no matter how many buttons there are. You can't tell which button was hit. Even if that could be worked around somehow, with many UI elements such as buttons on screen, you'd need a Collider with a fairly complex shape. You'd probably need a MeshCollider. What's more, the elements move, so in the worst case you'd end up setting vertices every frame. I don't see a very bright future there.

With GraphicRaycaster, on the other hand, implementing ICanvasRaycastFilter.IsRaycastLocationValid() makes it easy to control things like "don't fire if the cursor is between buttons". That's why I was using a Canvas alongside it, icky as it was.

Recently, though, I learned that you can make your own Raycaster. That changes things.

Implementation

In short, all I need is "something like GraphicRaycaster" that works without a Canvas. GraphicRaycaster inherits from BaseRaycaster, so if I make a class that inherits from it in the same way, I should be able to do the same thing without a Canvas.

I tried it, and it worked.

First, DebugUiManager used to inherit from UnityEngine.UI.Graphic; I stopped that and made it inherit from BaseRaycaster.

   public class DebugUiManager : BaseRaycaster
        , IPointerClickHandler
        , IPointerDownHandler
        , IPointerUpHandler
        , IBeginDragHandler
        , IDragHandler
    {

Then I implement what's required: the eventCamera property and the Raycast function. For eventCamera, I already had the camera used for drawing in a field, so it just returns that, and the Raycast function does pretty much exactly what IsRaycastLocationValid() used to do.

public override void Raycast(
    PointerEventData eventData,
    List<RaycastResult> resultAppendList)
{
    // If it hits something, take the event; if it hits nothing, let it through
    var sp = eventData.position;
    float x = sp.x;
    float y = sp.y;
    ConvertCoordFromUnityScreen(ref x, ref y);
    bool hit = false;

    // true while dragging. Otherwise various events can no longer be received
    if (isDragging)
    {
        hit = true;
    }
    // true if it hits something
    else if (_root.RaycastRecursive(0, 0, x, y))
    {
        hit = true;
    }
    else
    {
        // If it misses, treat it as released.
        _input.isPointerDown = false;
        _input.pointerX = -float.MaxValue;
        _input.pointerY = -float.MaxValue;
        hit = false;
    }
    // If it hit, add a raycastResult
    if (hit)
    {
        var result = new RaycastResult
        {
            gameObject = gameObject, // self
            module = this,
            distance = _screenPlaneDistance,
            worldPosition = _camera.transform.position + (_camera.transform.forward * _screenPlaneDistance),
            worldNormal = -_camera.transform.forward,
            screenPosition = eventData.position,
            index = resultAppendList.Count,
            sortingLayer = 0,
            sortingOrder = 32767
        };
        resultAppendList.Add(result);
    }
}

First, it converts the screen coordinates it receives into DebugUi's internal coordinates (ConvertCoordFromUnityScreen). DebugUi uses a coordinate system with a virtual resolution that you specify and Y pointing down. If you set the virtual resolution to 1136x640, then whatever the actual resolution, it's scaled as if the screen were 1136x640 (if the aspect ratio differs, there's leftover space so that everything fits).

Next, it recursively asks each UI element, such as buttons and sliders, whether it's under the pointer (RaycastRecursive()). If one is hit, it puts the result in a RaycastResult and adds it to the List it received as an argument. The UI elements are 2D, and all rectangles at that, so this calculation is much simpler and faster than what PhysicsRaycaster does. Writing your own isn't much work.

As for what to put in the RaycastResult, the official PhysicRaycaster code is a good reference. I pretty much copied it.

There are some differences, though. RaycastResult.gameObject, which should normally hold the thing that was hit, is set to the gameObject that DebugUiManager is attached to, whatever was hit. That's because there's no other gameObject.

sortingOrder is hard-coded to 32767, on the assumption that "nothing should have a higher priority than DebugUi". This way, if any DebugUi element is hit, other Colliders and Canvas elements won't respond.

Other applications

I think a similar trick could be used when one gameObject is internally divided into multiple parts and you want to know which of them was tapped. For example, you might generate a mesh dynamically to scatter particles but still want each particle to respond when tapped.

Of course, if the standard approach of preparing a gameObject, MeshRenderer and Collider for every particle doesn't cause any load problems, there's no need to do anything like this. But in a case where there's no physics, no collisions between particles, yet you still want tap detection, and each particle has only four vertices or so, the overhead of gameObjects, MeshRenderers and Colliders feels a bit wasteful.

About the DebugUi improvements

I made the Raycaster as part of improving DebugUi, so from here on I'll cover that too.

Summary of improvements

  • Stopped drawing with CommandBuffer and switched to a plain MeshRenderer
    • Also usable on HoloLens
  • Made my own Raycaster so it doesn't depend on UnityEngine.UI
  • Placement features: right-aligned, centered, bottom-aligned and so on
  • Added features to the menu (DebugUiMenu)
  • Made the graph (DebugUiGraph) more capable
  • Safe area support
  • Major code cleanup

As I said at the start, what triggered the changes was that nothing was drawn on HoloLens. I didn't investigate the cause in detail, but in VR and AR, drawing runs for each of the two eyes, so my guess is that something goes wrong with a CommandBuffer, which runs only once per camera. I might be able to get it to show up with some tweaking, but if I place it in 3D space with a standard MeshRenderer, it's the same as any other model, so it should show up for sure.

Of the other changes, some I made because I needed them, and some just because they somehow bothered me. Making my own Raycaster was likewise for the emotional reason that "creating a Canvas is icky"; it wasn't all that necessary.

Switching to MeshRenderer

Drawing with a CommandBuffer was purely a matter of personal taste; the standard way to draw things in Unity is MeshRenderer. I decided to set my taste aside and do it the way it's meant to be done.

Along with this, I simplified the initialization and removed the need to place a GameObject in the scene. If you call DebugUiManager.Create() with the camera to use for drawing, a child gameObject is created under it, and three components, DebugUiManager, MeshRenderer and MeshFilter, are attached automatically.

void Start()
{
    _debugUi = DebugUiManager.Create(
        _camera,
        _textShader,
        _texturedShader,
        _font,
     referenceScreenWidth: 1136,
     referenceScreenHeight: 640,
     screenPlaneDistance: 100f,
     triangleCapacity: 8192);
}

The hierarchy window at runtime

If you look at the hierarchy window at runtime, you'll see DebugUi as a child of Main Camera, and DebugUiMesh as its child. These are created when Create() runs. You don't need to prepare them in advance.

The actual drawing with the MeshRenderer is done by DebugPrimitiveRenderer. Feel free to use it as a sample of generating a mesh dynamically and drawing it.

Choosing the placement

You can now choose the placement when adding an element. In the sample, the window is placed at the bottom right.

_debugUi.Add(_sampleWindow, 0, 0, DebugUi.AlignX.Right, DebugUi.AlignY.Bottom);

Centering is also possible. The implementation is in DebugUiPanel.

I extended DebugUiMenu so it can express hierarchical menus.

A hierarchical menu

At first only the three items at the top, SubA, 1 and 2, are shown, and pressing SubA makes A1, A2 and SubB appear. Pressing SubB makes B1 and B2 appear as well.

_menu = new DebugUiMenu(100, 40);
var subA = new DebugUiSubMenu("SubA", 100, 40, DebugUi.Direction.Down);
subA.AddItem("A1", () => Debug.Log("A1"));
subA.AddItem("A2", () => Debug.Log("A2"));
var subB = new DebugUiSubMenu("SubA", 100, 40, DebugUi.Direction.Down);
subB.AddItem("B1", () => Debug.Log("B1"));
subB.AddItem("B2", () => Debug.Log("B2"));
subA.AddSubMenu(subB, DebugUi.Direction.Right);
_menu.AddSubMenu(subA, DebugUi.Direction.Down);
_menu.AddItem("1", () => Debug.Log("1"));
_menu.AddItem("2", () => Debug.Log("2"));
_debugUi.Add(_menu, 0, 0);

By creating a DebugUiSubMenu and calling AddSubMenu on a DebugUiMenu, you can make the hierarchy deeper.

You can also set the direction in which items are laid out. In the example above, the root menu expands in the default rightward direction, placing SubA, 1 and 2 to the right in that order. SubA, on the other hand, expands downward, so A1, A2 and SubB are lined up vertically going down. And B1 and B2, which come out when you press SubB, are shifted to the right and then placed downward.

Graphs

I extended DebugUiGraph to make it somewhat more usable.

A graph

The graph's scale is adjusted automatically, and the values at the bottom and top edges are shown. Also, though it doesn't appear in this example, multiple graph lines can be shown. Each can have a different color.

The values at the top and bottom edges are hard to read when they aren't round numbers, so I'd like to restrict them to round ones, but that will have to wait until I have some free time.

Better text size adjustment

Button text is sized automatically according to the button's size, but it didn't work very well.

The method was "draw with a font size equal to the button's width divided by the number of characters", but that leaves a lot of empty space. For example, with a width of 200 and 10 characters, the font size is 20. Font size is roughly the height of a character, so if all the characters are Latin letters, the text ends up quite narrow. As a result, there's space left over. The space isn't used effectively, and the text is harder to read.

With this change, it first does the layout calculation at a provisional size, measures the width, and calculates the scale factor from that.

To avoid doing the layout calculation twice, it packs everything into the vertex array at the provisional size, and once the scale factor is known, it scales the vertices in the vertex array. Even if the text changes every frame, the scale factor changes along with it, which is nice. It's frustrating that this "pack it first, then scale it" didn't occur to me in the first place. The core of the implementation is in DebugPrimitiveRenderer, and the code that uses it is in DebugPrimitiveRenderer2D and DebugPrimitiveRenderer3D.

Safe area support

Things placed at the edge of the screen were disappearing on the iPhoneX and the like, so I fixed that. It looks at Screen.safeArea and doesn't draw in the cut-off parts. By default, it paints the safeArea in light red so you can tell (see the screenshot at the top).

Cleaning up the internal implementation

Previously, a class called DebugUiControl, the base of the UI element classes, had all the tree-manipulation features. It even had features like adding children, removing children and changing the order of children.

However, most DebugUiControl-derived classes have no children. Buttons, sliders, text and so on have no children, so the features were excessive, and you could actually call the function that adds a child to a button.

So I split the features related to having children out into DebugUiContainer.

Closing

Is it just me, or is building these development support features strangely fun?

Now that I've experimented with running an HTTP server on the client side, getting the UI defined with this DebugUi library to show up in the browser too isn't so far off.

But in practical terms, finding this fun isn't a good thing. I can hear an inner voice saying, "Stop building development environments and make games! That's what Unity is for!" But it can't be helped, right? The standard stuff alone isn't enough.

As I wrote in a previous article, smartphone performance has come to the point where it's not that different from home consoles. If some company goes ahead and "builds something with the same technology and the same money as a home-console title", and it sells, that will quickly become the standard on smartphones too.

If development scale reaches home-console level, you'll need the same level of development support that home-console development has, so I think building up tools will matter more than it has so far.

To do that quickly and cheaply, and to make fun games in a fun way, I think it would help to be in a situation where we can see lots of examples from other companies. Every company is probably making debugging features anyway, so how about every company putting code unrelated to their products on GitHub and making it public?

Personally, for anything not directly tied to a product, I want to follow a policy of "make something, publish it right away".

Addendum: using it with LWRP

Currently, if you use it in a project that uses LWRP (LightWeight Render Pipeline), everything renders purple, at least in an Android build with 2019.1.3. It works fine in the editor, which makes it a rather nasty bug.

The shader is customized to handle the font texture, and that's probably the problem. For one thing, the "conditions for using homemade shaders with LWRP" aren't clear, and it doesn't feel like something I could fix after 30 minutes of looking into it. We don't currently need an urgent fix at our company, but if there are requests, I'll look into it and deal with it (and I'll probably blog about what I find out).