# Question
Title: Extensible 2D Rendering with ECS Architecture
I am currently creating a 2D game/game engine using an ECS architecture. Currently I have a `renderer_2d` system which is a function that takes all `Sprite` and `Text` components and draws them using a `draw` function in a `Renderer` interface. The `draw` function takes in a handle to a texture, pipeline and an array of vertices to be drawn. The `Renderer` is an interface to the Graphics API, currently Vulkan or OpenGL and handles texture creation and draw calls.

I would like to allow my `renderer_2d` system to be extensible and I am wondering what the best way to do this would be. I would like to add other types of objects to be rendered, such as tilemaps, etc. and in the future support multiple passes (e.g. world and UI). I was thinking of a few various methods.

1. Allowing systems to queue draw calls and placing them in the graphics queue at end of frame
2. Registering callback functions/lambdas called when the system is executed which each make draw calls

I am a unsure on what would be the ideal way(s) to implement this. The engine is targeting 2D games and so I do not plan to support complex 3D meshes, etc.

# Answer
> 2 votes
A little bit of both.

To be able to queue render calls is useful. In particular in 3D. The render system can group them (e.g. by materials) and execute the groups in a preferred order (e.g. non transparent things first). You could also do deferred shading, and batching, batching, batching.

On the other hand an strategy pattern is a good idea. Each entity that can be drawn would have a draw strategy associated, and then render system can call the code for that strategy to handle rendering.

Now, let us consider:

* Which is better to implement on top of the other?

You can have an strategy that queues render calls. It does not give you all the benefits, but will allow you entities that change how they are rendered dynamically.

And you can have strategies that queue render calls. I think this gives you the best of both worlds. In fact, the strategy that queues the calls could be useful for grouping and batching.

Thus it is better to have strategies that queue render calls.
* Which can be made as an extension of the other?

Let us say you implemented systems that queue render calls. You can have components that mark the entities so they are handled by different systems. And each of these system queue render calls.

On the other hand, let us say you implemented render strategies. That is, you have a render strategy component that the render system gets, and depending on its value it calls an strategy to render. To implement a strategy that allows queuing calls you would need to store the queued somewhere so that strategy can get them. It is not clear where.

Thus, if you are going to implement one, to later have the option to built the other on top, implement queued render calls.

It appears that allowing systems to queue render calls is better. You can go with that.

---
Tags: c++, architecture, rendering, entity-component-system
---


# Question
Title: Why clip in clip space - confusion with Gribb-Hartmann clip plane extraction
I understand to extract clip planes from the perspective matrix one can follow the methodology laid out by Gribb-Hartman as documented here:

http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf

However, I have noted that, given a perspective transformation matrix, such as the one provided by glm::perspective, you will get you planes in the form of the general plane equation ax+by+cz+d in view space.

Yet, as far as I am aware that once the 4D co-ordinates of a vertex, *(where w == 1)*, are multiplied by a perspective matrix, they are considered to be in clip space, prior to their division by 'W' to bring them in to Normalized Device Coordinates form (NDC).

I understand that testing whether to clip a vertex or point in clip space is easy enough, as if the following inequalities are met, the vertex should not be clipped.

If this is the case, why do we ever need to extract the planes to be in view space?

Additionally if we consider the line P-\>Q and lets assume:

P is inside the viewing frustum

Q is outside the viewing frustum

we will need to generate a new vertex with point R which resides on the line P-\>Q but it needs to exist on the intersecting plane.

If the planes we extract using Gribb-Hartmann are in view space, how can we create the vertex R in clip space? As I can see as the extracted planes exist in view space, it would be logical to test the line P-\>Q in view space for the intersection and produce the vertex R and them remove Q from out buffer. So why is clip space not just cliping space?

I am very confused

Thanks for any insight.

# Answer
> 0 votes
**TL;DR;**

* Clipping is one form of culling, and it is best done in GPU. But there are other forms of culling, some of which we do in CPU. Which are useful, because they mean sending less polygons to the GPU. And thus, calling the clip space culling space would not be accurate.
* And there are other uses for those planes aside from clipping. Including but not limited to frustum culling. However cutting triangles by creating vertex in the intersection with a plane is not the common case today.

---

**Why do we need to extract the planes?**

> why do we ever need to extract the planes to be in view space?

There are multiple reasons to extract the planes. And, yes frustum culling would be one reason. It usually involves discarding meshes in CPU before sending them to the GPU.

We can use the same approach described in the linked document to extract planes in whatever space we need, it is matter of which matrices we use. And usually we want the planes in world space. But why extract them in the view space in particular? I don't know. But we can!

I suppose you got the idea in the same place you got the idea of cutting triangles with the planes by inserting vertex. But I'm here to tell you to don't do that.

---

**Why is the clip space called like that?**

> So why is clip space not just culling space?

*Here I'm interpreting this question as if it were asking about the name "clip space".*

Clipping is a type of culling, but not the only one. The other common culling operations are backface culling, occlusion culling and frustum culling. There are others, for example normal culling is basically backface culling but done in CPU before sending the data to the GPU. Which is not entirely disimilar to how frustum culling is basically clipping except done in CPU before sending the data to the GPU.

---

**Why do we cull before sending the data to the GPU?**

We cull in CPU because that way we send less data to the GPU. Sometimes too many vertex become the bottle neck and have a real impact on performance. *For a good while polygon count was on the top of the list of performance concerns, and still is, depending who you ask.* So we will use levels of detail (using meshes with less vertex when they are far away from the camera), and we will do all sort of culling.

---

**What does frustum culling mean anyway?**

*I assure you that when people complain that a game engine does not do frustum culling, the GPU is still clipping, but the complaint is not about nothing.*

By frustum culling we might mean to not send meshes that we can be certain to be outside of view (Or even to discard individual faces depending on the position of the camera, as some games do). Doing this is important for open world games where there is plenty of geometry in every direction.

You would, of course, combine this some form of space partitioning. Due to the fact that discarding an entire partition is better than discarding individual meshes.

For games set in interiors, you can use an hybrid portal based occlusion and frustum culling (where portal means door or window or similar). Which is done by first finding what portals are in the viewing frustum. And then figuring out what rooms they connect to, and find portals in them. Except you are going to clip the viewing frustum to the portal (so you have a smaller - skewed, not centered - viewing frustum that represents the view through the portal), and use that to find if there are any portals in view in the other room. And so on. Of course, for each room you can do frustum culling, not with the original viewing frustum but with the frustum(s) after clipping through the portal(s) that lead to that room.

Also, by frustum culling, if you dig enough - or you are looking at some old documentation - you will find the technique of cutting triangles by adding vertex in the intersection with the planes, so that we only send the pieces that are inside the viewing frustum to the GPU. *This was absolutely worth doing back in the day of immediate mode rendering and render lists. I'm not convinced it is worth doing today.*

However, here is something similar - from my own experience - that I needed those planes for: to generate meshes based on the viewing frustum (instead of cutting them). In particular, I wanted an "infinite" plane. No, I can't put vertex at infinity and then cut the mesh to the viewing frustum. But I can extract the planes of the viewing frustum, compute where they intersect the plane I want, and that tells me where to put the vertex to represent it. Similarly when I want "infinite" lines, I can follow the same approach. *I also needed this to work in orthographic and perspective projections.*

---

**Why don't we project meshes to clip space in CPU and do frustum culling that way?**

> So why is clip space not just culling space?

*Here I'm interpreting this question as if it were asking about where to do clipping operations.*

The GPU is faster doing that. So, clip polygons in clip space in the GPU, where it is faster.

However, as I was saying, polygon count is important. We want to do something in the CPU that is faster. That something is frustum culling.

Plus, be aware that we might be doing frustum culling by a different frustums (such as I described above when talking about portals). *And I also want to mention that not every rendering technique uses meshes (e.g. ray casting/marching).*

---

**How can frustum culling in the CPU be faster than clipping in the GPU?**

If we are going to do this in CPU we are going to take shortcuts. For instance, if we define a sphere that is guaranteed to contain a mesh and we find that the sphere is entirely outside of the viewing frustum, then we are certain the whole mesh is outside the viewing frustum.

Similarly we could use AABB or OBB instead of spheres. In fact, if you have space partitioning, chances are the partition is an AABB (either you are using an oct-tree or chunks or similar), and if it is entirely outside the viewing frustum, any mesh entirely inside the partition is outside the viewing frustum.

*You might also be interested in bounding volume hierarchies.*

By the way, assuming we are working with a perspective projection: You can test against the viewing line with the dot product (of the viewing direction and the direction from the camera to the point being tested). It is a coarse test, and you need to compute the threshold for the dot product depending on the the vertical and horizontal viewing angle with trigonometry - thankfully viewing angle does not change often. A more refined alternative is to make an horizontal test and a vertical test. *And that is another way to define the planes. However, it only works on a - centered, not skewed - perspective projection.*

*As you can see, we can discard who knows how many vertex in a few checks in CPU.*

---
Tags: opengl, graphics-programming, glm
---


# Question
Title: Dividing amount of exp between rank A and B into a curve?
In my game I have a rank system. You start at rank A, and then you can level from level 1 to level 10. When you reach level 10, you get promoted to rank B, and you go from level 1 to 10 again, and then you get promoted to rank C, etc etc.

Getting from rank A to rank B takes a pre-determined amount of experience, which translates to a predetermined amount of real-world time. For example: getting from rank A to rank B costs 1200 experience, which translates to a week of game time.

What I'd like to achieve however, is to make leveling up early on in the rank easier than later on, so that when you rank up, its easier to achieve the first few levels, and the later levels are harder/take more time. Almost a bit like an exponential curve.

So really what I'm trying to do is divide the total amount of experience it takes to the next rank (total amount: 1200xp) by 10, into some kind of exponential-like curve, in a way that finally it'll still add up to 1200xp.

Does anybody know of such a formula/piece of code?

# Answer
If you want a progression where the cost to level up from \\$L\_n\\$ to \\$L\_{n+1}\\$ increases by some ratio \\$r\\$ each time:

$$L\_1 = a,\quad L\_2 = a \cdot 4, \quad L\_3 = a \cdot r^2, \quad ... L\_n = a \cdot r^{n-1}$$

That's called a geometric sequence. (We say it grows "geometrically")

If you add up a bunch of terms, that's called a *geometric series*, and there's a handy formula for it:

$$\displaystyle \sum\_{i=1}^n L\_i = \frac {a (1 - r^n)} {1 - r}$$

We'll arbitrarily choose a value for \\$r\\$ to decide how curvy we want our curve: values closer to 1 give us a flat line, and higher values make steeper curves. But watch out - you might be tempted to reach for a value like 2 or 3 here, but the exponential stacking will quickly turn this into a gruelling slog by the end (\\$2^8 = 256\\$, so your final level of a rank would take *two hundred times* more work than the first!).

Let's choose a really shallow \\$r\\$ for starters, like 1.02 (each level costs 2% more XP than the previous). We can change this later if we like.

Here we want \\$n = 9\\$ (because once we level up from level 9, we cross over to the next rank and go back to level 1). So subbing those into the formula above, we get:

$$\displaystyle \sum\_{n=1}^9 L\_i = \frac {a (1 - r^9)} {1 - r} = \frac {a (1 - 1.02^9)} {1 - 1.02} \approx \frac {a (-0.195093) } {-0.02} \approx 9.754628 a$$

And now it's a simple matter to solve for \\$a\\$ to make the total equal to the total XP you want between ranks A and B:

$$\begin{align} 9.7546284311155456 a &= 1200\\ a &= \frac {1200} {9.7546284311155456}\\ a &\approx 123.018525 \end{align}$$

Ah, but here we run into a bit of a problem. All this math is for continuous real numbers. But for XP targets, we usually want integers. And we might even have other constraints, like wanting each XP threshold to be a nice round multiple of 10 or 50 or 100. There's probably a fancy integer programming solution to that, but myself, this is where I'd head to a spreadsheet.

In this Google Sheet (on the "WeekXP" tab), I've implemented the formula above, and added a column where I round the XP numbers to the closest integer.

You can see that using \\$r = 1.2\\$ in this example, the rounding doesn't quite work out - we total up to 1 XP higher than we meant to. So, you can either play with the numbers a bit or add a rounding bias until the number comes out to exactly the value you want, or just fudge the numbers by hand (for instance, subtracting the error from the last level in the sequence).
> 3 votes

---
Tags: mathematics, game-design, algorithm
---


# Question
Title: How to make a singleton "game manager" object/class that only loads once and can be accessed from any scene?
I would like to have a single "Game Manager" game object or class that contains numerous parameters and tweens or other functions that would be necessary to access throughout my app across various scenes.

I see this is a common need people voice, and an apparently good script was posted here:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using JetBrains.Annotations;

public abstract class Singleton<T> : Singleton where T : MonoBehaviour {
    #region  Fields
    [CanBeNull]
    private static T _instance;

    [NotNull]
    // ReSharper disable once StaticMemberInGenericType
    private static readonly object Lock = new object();

    [SerializeField]
    private bool _persistent = true;
    #endregion

    #region  Properties
    [NotNull]
    public static T Instance {
        get {
            if (Quitting) {
                Debug.LogWarning($"[{nameof(Singleton)}<{typeof(T)}>] Instance will not be returned because the application is quitting.");
                // ReSharper disable once AssignNullToNotNullAttribute
                return null;
            }
            lock (Lock) {
                if (_instance != null)
                    return _instance;
                var instances = FindObjectsOfType<T>();
                var count = instances.Length;
                if (count > 0) {
                    if (count == 1)
                        return _instance = instances[0];
                    Debug.LogWarning($"[{nameof(Singleton)}<{typeof(T)}>] There should never be more than one {nameof(Singleton)} of type {typeof(T)} in the scene, but {count} were found. The first instance found will be used, and all others will be destroyed.");
                    for (var i = 1; i < instances.Length; i++)
                        Destroy(instances[i]);
                    return _instance = instances[0];
                }

                Debug.Log($"[{nameof(Singleton)}<{typeof(T)}>] An instance is needed in the scene and no existing instances were found, so a new instance will be created.");
                return _instance = new GameObject($"({nameof(Singleton)}){typeof(T)}")
                           .AddComponent<T>();
            }
        }
    }
    #endregion

    #region  Methods
    private void Awake() {
        if (_persistent)
            DontDestroyOnLoad(gameObject);
        OnAwake();
    }

    protected virtual void OnAwake() { }
    #endregion
}

public abstract class Singleton : MonoBehaviour {
    #region  Properties
    public static bool Quitting { get; private set; }
    #endregion

    #region  Methods
    private void OnApplicationQuit() {
        Quitting = true;
    }
    #endregion
}

```

In Unity, how do I correctly implement the singleton pattern?

However, I don't actually understand how to use this or what to do with it.

Do I attach this script to a GameObject? Do I need to attach it to one in each scene? Is the idea to attach it to one GameObject in every scene and then the script will automatically kill any duplicates that accidentally get made? I presume if I just attach it to one GameObject in one scene, then if that scene doesn't load it won't be loaded either.

But if I add it to one GameObject in a dummy scene that only loads once on starting the application and never again, this should work right?

I tried attaching it to a GameObject and it says I can't because it's abstract. So I have no idea what to do.

Further, if I wanted to add to that script `public float exampleWidth = 1000.0f;` and then be able to access that from anywhere in my game, where in the script would I be meaning to put it?

Then let's say I'm writing in another script attached to another GameObject and want to access something from this like `exampleWidth` how do I write that? How do I `get` the gameObject holding this script from another scene? Should I find it on Awake/Start in every scene that needs it somehow?

Ideally I want:

* This singleton object/script should always be running.
* If there is none currently in existence, I need one made.
* It should not be destroyed on switching scenes

The other problem I wonder about with this script is when it checks for duplicates and tries to preserve `instances[0]`, how do we know if `instances[0]` is the original or the new duplicate? It seems it might be random whether the new duplicate or the old original survives.

If you wanted the old original to always survive, could this be possible? For example, if I started a tween loop in the singleton and I want this tween loop to constantly survive so I can use it smoothly and seamlessly even across scene changes, would this be possible? Or would it be best to like I said attach this to just one GameObject in a dummy scene and load that at start up only once?

Thanks for any ideas.

# Answer
This here is an abstract class. Which means you can not use it directly. You have to write a class which inherits from this class. Further, the class is a generic. Which means it is "a class for other classes". This is not newbie-stuff. This is C# for adults!

If I understand this contraption correctly, then it seems to allow you to create an attachable singleton MonoBehaviour class like this:

```
public class GameManager : Singleton<GameManager> {
    public float exampleWidth = 1000.0f;
}

```

You can also have any Unity event methods like `Update` in this class. With one exception, though: If you want to use the `Awake` event method, you have to declare it like this instead: `protected override void OnAwake()`.

This is the component you need to attach to an empty game object.

When you don't want it to get deleted on scene switches, check the "persistent" checkbox in its inspector.

Now other classes can access it like this: `GameManager.Instance.exampleWidth` .

> The other problem I wonder about with this script is when it checks for duplicates and tries to preserve instances\[0\], how do we know if instances\[0\] is the original or the new duplicate? It seems it might be random whether the new duplicate or the old original survives.

It's only going to do that the very first time another script requests the `.Instance`. At that point it's undefined which one of the objects in the scene is "the original". But this is not supposed happen anyway. When you receive that warning, then you screwed up.

When you create a second GameManager later, then the `.Instance` property is going to ignore it. It is just going to return the object cached in the private variable `_instance`. It won't search for other instances again (which is good, because `FindObjectsOfType` is a very slow method and thus shouldn't be called more often than strictly necessary).
> 3 votes

# Answer
Add this `Awake()` to your `GameManager` script, Attach this Script to a `Empty GameObject` at the starting scene of your game, it will not be destroyed till the end of the Application Cycle.

```
public class GameManager:MonoBehaviour
{
    public static GameManager Instance {get;private set;}
    void Awake()
    {
        if(Instance==null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
            Destroy(gameObject);
    }

    public int variable1 = 0;
}

```

You can call variable using

```
GameManager.Instance.variable1

```
> 0 votes

---
Tags: unity, asset-management
---


# Question
Title: How to protoype a multiplayer game whose fun comes from having lots of features
I've seen plenty of testimonies that to make a good game and not waste time, one should prototype early, quickly see if the core is fun as is, and not focus on graphics, menus, sound, secondary features, etc and I agree with it.

However, I'm creating a game whose very philosophy seems to be at odds with this. I want to make a real-time, 2D, 1v1 PVP game (or against AI), in which the player explores, sneaks, setup traps, tries to find synergies with their findings (items, spells, powerups, whatever), inevitably faces their opponent sometimes and must use all this to be smarter and kill them.

The first problem is that the whole point (and what would make it fun according to me), is that the world will be full of very diverse randomly generated various crap, often with both useful and hurtful features, that you must make work together while avoiding if possible the anti-synergies that will inevitably come up. I enjoy roguelites for that reason (and the replayability) and want the same feeling.

But then, don't I need to implement a vast amount of features (even very basically) to find out if that concept is in fact as fun to play as I think ?

The second problem is that a good part of the fun should come from outsmarting your opponent. So I quickly need to either setup a way to have 2 players playing at the same time (LAN ? through a server ? seems a complex and difficult topic and not very prototypy). Or create an AI to make up for it, but it has to be smart enough to make it interesting, which again, seems to go against the "implement quickly and test" philosophy.

The 2 players don't have to be identical in capabilities (especially AI), it could also make a fun challenge to find how to put together a way to beat the dumb, vastly stronger AI.

I'm open on the game features themselves, I don't have a goal set in stone, which is why I'm protoyping in the first place, but I'd like to keep as much of the philosophy above as possible.

Note that the secrecy/surprise factor makes it impossible to do split-screen.

**How can I prototype such a game ?**

(Using Unity2D for now if that changes anything, seemed like an easy way to get something started)

# Answer
> 3 votes
No amount of auxiliary content and features can save a game with a bad core game loop.

When you look at games based around creeping featurism ("Minecraft", "The Sims", "Runescape"...), then it can get difficult to even recognize the core game loop under all the bells and whistles. But it is always there if you look properly.

So make sure you identify the core game loop of your design, prototype it first, and then design all other features to feed into it. Don't worry about your game not being complex enough. What matters first is that you nail down a solid core game loop which provides a minimum viable game experience even without content. Then you can add features and content on top of it.

For this particular game (as far as you describe it), the core game loop seems to be:

* Explore the environment
* Acquire resources
* Weaponize resources against the opponent

This is a loop which can be prototyped with just one resource which has a very basic mechanic.

When you got that working and it feels good enough, then you can start to add other resources with other mechanics, synergies and anti-synergies to add more complexity to the game. But make sure to evaluate each new addition carefully. Make sure it's balanced, does not make other features infeasible and is interesting for both the user **and** the player it's used on.

---
Tags: unity, game-design, multiplayer, ai, prototyping
---


title: 3D image projected to 2D image

text:
# Question
Title: 3D image projected to 2D image
We know real world images are 3D.when we projects image from real world this image projects into 2D image where Z component is constant or zero. But when capture the below image which seems to 3D(z seems to be not constant.)See this image which seems to be 3D:

My question is how is it 2D image? I am confusing it may be 3D image.

# Answer
The image posted is 2D in the sense that you cannot 'look behind' anything in the image based solely on the information presented.

Here's a 3d scene being projected onto a 2d plane (source: Wikipedia entry on 3d projection)

And in the next scene, I've added an additional cube:

Despite this addition, the 2D projection of the scene remains unchanged. Looking at the 2D projection, we can infer *some* 3D information about the scene (such as the relative depth, width & height of the blue cube), but we don't have enough information to determine everything in the 3D scene from which the 2D projection was made.
> 2 votes

# Answer
I believe the confusion might come from the term "3D computer graphics", because what is 3D about 3D computer graphics is not the pictures it produces, but their representation in the computer.

To be clear, there could be 3D pictures, but then we are talking about specialized output hardware. Except, of course, that "3D" is also a buzzword. We have had many attempts at "3D" to the point that "3D glasses" went from being made of cardboard and having one red and one blue "lenses", to use fast blinking, to use polarized filters, and don't be surprised if people start calling "3D glasses" to some incarnation of VR/AR headset. And then we have all the things that got the moniker of "hologram". *Don't get me started on the metaverse.*

But 3D computer graphics imply none of that. Instead, it implies that there is a 3D representation in a computer from which we can create different pictures from different view points. We even talk about virtual cameras that we configure to do that. We often take it from granted when developing 3D games.

---

When you take a picture with a real (not virtual) regular camera, you do get one particular view of a real 3D world. But you only got that view. You are not getting a 3D representation that you can use to create different pictures from different view points.

You could use a more advance camera to get depth information. And these would give you point cloud data. Which can be considered 3D. However, if you did one such capture and try to create pictures form different view points, you will find that orbiting around with a virtual camera reveals nothing. But, with enough captures with the same technique you can create a full 3D representation of an object or a place. To learn more on the topic, see Photogrammetry and 3D scanning. You may also be interested in 3D imaging such as used in medial applications. *Those are 3D.*

Bringing this to game-development, such tools are useful to create realistic assets (both objects and scenarios) to use in video games. *For AR games, scanning the area surrounding the player will help to integrate the virtual elements. And VR games might want to scan the area surrounding the player so they have an idea of how much space they have to work with, and give some indication to the user that they might be about to bump into something.*

---

You can, of course, use a 2D picture to represent something 3D. We do it all the time. And we doing by using projections. In particular, you can define axis in a 2D picture, like you did. And doing so, you defined a one way transformation from 3D to 2D (edit: actually I think you need to know the length in 3D of those lines). But that does not make picture 3D (it is still flat, be it on a flat screen, on a piece of paper, or similar), it is not enough to make the transformation back from 2D to 3D.

However, it is not an entirely wrong idea. We - humans - can look at a 2D picture of a 3D space and have a sense of depth. This is by taking clues such as what is in or out of focus, what we expect to be parallel or orthogonal lines, and our experience with perspective and light. We are good at this, because we do it all the time. Our sense of depth perception comes chiefly from using two 2D pictures (one from each eye). *However, I shall remind you we can fall victims of optical illusions. Such as the famous Ames room.*

*And we will take advantage of this when developing video games, we trust that the player will understand intuitively that the pictures on the screen represent a 3D space. And, of course, there are some unique challenges that arise from the fact that the player is only looking at 2D pictures. For example, did you know that before Mario 64 had a shadow always below the character, players had a hard time with jump because they could not guess where the character was going to land? To be fair, I don't know if that is the motivation to add the shadow, or is it just that the light system in the game isn't great, but it is true that the shadow helped players with the jumps, and this is a learned lesson in usability.*

Computers can also do the same to some extend. Both using multiple cameras to try to create a 3D representation in real time, or to infer a 3D space from a 2D picture (see computer vision). These are active fields of research, with a very tangible application in autonomous vehicles, and also in robotics/domotics in general.

*And to end on a video game related note...*

While autonomous vehicles do not have a direct application in video games. Video games have a direct application in training their software agents. More precisely, in creating 3D environments to test the software agents. And the more realistic and extensive we can make them, the better. That way, when the software agent that will drive the autonomous vehicle is given control of the real car, we have good confidence that it works correctly.
> 2 votes

---
Tags: 3d, projection, terminology, perspective
---


# Question
Title: Is there a way to convert built Unity game back into a project?
I accidentally deleted my game. I had been working on it for about 2 months and I accidentally deleted it while cleaning up my files. I am so smh. I have a ton of builds of the game though and since the game and all its scripts were converted to a file. Would I be able to un-pack said build back into a Unity project? I am not that cut about the game because I didn't like it but I did spend a lot of time on it. Oh yeah and also it was a school assignment.

# Answer
No, you cannot unpack a Unity build into the source files for the project.

You can decompile the managed assemblies to get equivalent C# code out of them, but it won't be exactly the code you wrote. It will likely be mangled and harder to read, lacking comments etc.

You can try to extract assets like textures too, but you won't get your original files back. In order to make them fast to load and efficient to display on graphics hardware, Unity converts files to GPU friendly formats and applies various compression strategies to them as part od the build process. This can be lossy — the texture you get at the end is not necessarily a pixel-for-pixel match with the input image.

If you have one specific script you don't remember how to write, or one specific image asset you can't re-make, then these strategies might be worthwhile to get a starting point you can then edit by hand back to what you want it to be.

But for most purposes you'll be better off remaking the project from scratch, using what you learned the first time around to do it better this time.

One such lesson should be to use a version control system and keep a backup somewhere so you never land in this situation again.
> 4 votes

# Answer
Yes, you can. Try programs like AssetRipper (which's a fork of uTinyRipper program).

How well these programs cope with unpacking depends on the unity version, the older it is, the better.
> 1 votes

---
Tags: unity, file, build
---


# Question
Title: Painter's theorem inside and outside test
I have read from Hearn and Baker computer graphics book. I read the test#2 painter's theorem which image is given below.

This image showing surface S is completely behind the surface S', by checking Substitute the coordinates of all vertices of S(x, y,z) into the plane equation of S' and check for the sign. If all vertices of S are inside S' then S is behind S'. (Fig. 1).

i. e. Ax + By+ Cz + D \< 0 ,x, y, z are S vertices.

---

But I have read from this websites which showing this concepts but in totally opposite manner. See this image: I read from that site, which showing opposite thing on same image. This showing all vertices of S are outside of S'.

i. e. Ax + By+ Cz + D \> 0 ,x, y, z are S vertices.

My question is how is it possible Hearn and Baker saying S is completely inside the surface S' but my mentioned website saying S is outside of S' by sign test of plane equation?

# Answer
> 2 votes
I'm not familiar with the exact situation being discussed here — it's been a while since I've worked with plane equations — but in general, much of the math in computer graphics has opportunities to change signs or axes and get the same answers. A surface is a 2-dimensional object and when you embed it in a 3-dimensional space you need an arbitrary convention defining which side of it is “inside” and which side is “outside”. In this case,

$$Ax + By + Cz + D \> 0$$

is the same inequality as

$$(-A)x + (-B)y + (-C)z + (-D) \< 0$$

so if we compute the coefficients of the plane in a way which swaps the signs, then our front-or-behind tests should also be reversed to come up with the same results.

The web site you link mentions

> A, B, C, D are from plane equation of P (choose normal away from view plane since define "outside" with respect to the view plane)

If you “choose normal” the opposite way, you will get the opposite set of coefficients.

The math works the same either way, but it's good to pick existing conventions and stick with them (and document which one you're using), because mixing them up is a great way to get confused, especially as two unintended swaps can cancel out and get the right answer by an unintended route, creating a lurking bug that pops up and makes all your graphics disappear when you change one of those two parts.

---

Another example of arbitrary binary choices:

In GPU triangle mesh rendering, a commonly seen example of an arbitrary sign choice is choosing whether your triangles have their vertices ordered counterclockwise or clockwise, when viewed from the outside/above. Either convention works, and allows the GPU to efficiently skip rendering half of the model of a solid object, by skipping all triangles whose vertices are in the opposite order (as projected on the screen) and therefore must be facing the back-side of the mesh which should never be seen because the front-side is hiding it and the object is supposed to be opaque and solid.

---
Tags: 3d, rendering, projection, objects, surface-shader
---


# Question
Title: Unity split camera without refit the center
Before attempting to mark this question as duplicate or send me here, hear me out:

I was trying to make a coincidence rangefinder effect, say I have a view like this:

In a coincidence rangefinder, it would be split into 2 parts, upper and lower, each produced by a different camera, like this:

(Note the middle may not be aligned)

But if I directly mark the 2 cameras in Unity by `X Y` and `W H` (`0, 0, 1, 0.5` and `0, 0.5, 1, 1`), they will recenter themselves, producing the following effect:

So how can I change the viewport rectangle so that the camera is clipped instead of refitted?

# Answer
> 1 votes
You can achieve this effect using an oblique frustum, as described in the documentation.

Here's an example that takes two cameras and configures them to occupy the top and bottom halves of the screen, so that combined (if they were looking from the same location/orientation) they appear as one seamless camera view.

```
public class ScreenSplitter : MonoBehaviour
{
    public Camera top;
    public Camera bottom;

    [Range(0.0001f, 179f)]
    [Tooltip("Field of View of the combined camera, in degrees.")]
    public float combinedFOV = 60f;

    // Update the cameras live in the editor so we can preview changes.
    private void OnValidate() {
        if (top != null && bottom != null)
            UpdateCameraProjection();
    }

    // Apply changes on start-up.
    private void Start() {
        UpdateCameraProjection();
    }

    // Call this to enable the effect (eg. when switching to the rangefinder view)
    public void UpdateCameraProjection() {
        // At 1 m depth in front of the camera, how high does the top
        // of the frustum rise above the center of the view?
        float imageHeight = Mathf.Tan(combinedFOV * Mathf.Deg2Rad / 2);

        // We want our image from each half-camera to span *half* that height.
        float fov = Mathf.Atan(0.5f * imageHeight) * 2 * Mathf.Rad2Deg;
        top.fieldOfView = fov;
        bottom.fieldOfView = fov;

        // Set the viewports for each camera to cover their respective halves.
        top.rect = new Rect(0, 0.5f, 1, 0.5f);
        bottom.rect = new Rect(0, 0, 1, 0.5f);

        // Undo any overrides to the projection matrix to make sure
        // we're working from the standard for this FoV/viewport.
        top.ResetProjectionMatrix();

        // Apply obliqueness - shift so the projection axis
        // is at the bottom of its half-screen.
        var mat = top.projectionMatrix;
        mat[1, 2] = 1f;
        top.projectionMatrix = mat;

        // Repeat for the bottom camera, shifting so the projection axis
        // is at the top of its half-screen.
        bottom.ResetProjectionMatrix();
        mat = bottom.projectionMatrix;
        mat[1, 2] = -1f;
        bottom.projectionMatrix = mat;
    }
}

```

---
Tags: unity, camera
---


# Question
Title: Why aren't regular quadratic and cubic splines used much in games?
After investigating a bit about splines and reading a bunch of docs, I have noticed regular quadratic and cubic splines are not used very much in games.

Splines using quadratic/cubic Bézier curves, Catmull-Rom, B-splines, and other spline interpolation methods seem to be used widely though.

I can be totally wrong here but from books and tutorials I have seen that for regular cubic/quadratic you have to solve systems including first derivative for continuity and second derivative to match curvature. It seems that the most used splines (Bézier, Catmull-Rom, etc...) implicitly bring these features with fewer calculations.

Is this the reason that regular quadratic and cubic spline interpolation are not often used in game programming?

# Answer
> 2 votes
A nice place to start (without the mathematical heaviness associated with the Differential Geometry of Curves and Surfaces) would be this. The author discusses the uses and practical advantages or disadvantages of these curve primitives with use cases taken from a game designer's perspective (or from a game editor developer's perspective if you will).

---

**This source** seems to discuss the essentials: types of curves and their properties (Hermite, Bezier, Catmull-Rom, Cubic Splines), how to evaluate them.

---

Performance wise, this Dr. Dobbs article discusses what can be done to evaluate Bezier curves efficiently. Many others can be found as the field is really mature and the applications are widespread.

Finally, this is a digital book that discusses Bezier and Spline curves in minute detail. If you are already familiar with these concepts, you can skip to the chapters that explain what algorithms are used to evaluate them.

# Answer
> 1 votes
From the question its not entirely clear what "regular" means in "regular quadratic and cubic splines are not used much." If you mean standard cubic equations, such as ax^3 + bx^2 + c, the reason they are not widely used is there is no direct relationship between coefficients and spatial control points. Given a set of points one would have to solve a system of equations for the coefficients a,b,c. This is called curve fitting: it reduces dimensionality, is slow to compute, but is widely used in the sciences/statistics to approximate data with a lower-degree curve.

Bezier Cubic, Catmull-Rom and B-Splines are used primarily because they have **local control** (moving controls moves the curve in an expected way), **piecewise connectivity** (they can be placed end-to-end for arbitrary number of controls), **C1 or C2** continuity (smoothness) and may or may not interpolate their controls. The piecewise aspect is especially useful because it means you can have arbitrarily many data points (controls) and the curve will pass thru or near all of them. These features define the specialization of splines. Yet under-the-hood each of them does have a blending of standard cubic polynomials.

# Answer
> 0 votes
Graphics accelerator cards are not equipped to deal with them. Polygon-related operations like rasterization itself are taken care of quickly and automatically. The other operations require discrete points to operate on, like frustrum culling or even view projections.

These operations don't work at all with this kind of pipeline. They only work properly with a ray-tracing-like render algorithm. I say like to stave off any super pedantic people out there that might correct me and talk about other algorithms like photon-tracing that are basically the same thing.

When rendering triangles as in OGL you basically take discrete object data and transform them onto the screen. When you take these other more abstract graphics representations you don't have a discreet object at all. When you do ray tracing this doesn't really matter. When you do rendering like in OGL first you have to transform all of these into discrete objects (which generally look terrible compared to the "real" object). Or else use some kind of ray tracing with compute shaders or something and somehow put those results in among the results of your discreet rendering.

So while you can do it, it's mostly not practical to do so in OGL at least for a gaming application. Maybe it can be used here and there for certain things like allowing users to create content, but you won't see it used for data representation as the norm any time soon.

---
Tags: mathematics, interpolation, splines
---


# Question
Title: Make object follow another object like a dog sled
I'm trying to achieve the effect of a dog sled for a small prototype. All my attempts failed until now.

I have the following code (inspired from this)

```
using UnityEngine;

public class BlendFollower : MonoBehaviour
{

    const int MAX_FPS = 30;

    public Transform leader;
    public float lagSeconds = 0.5f;

    Vector3[] _positionBuffer;
    Vector3[] _rotationBuffer;
    float[] _timeBuffer;
    int _oldestIndex;
    int _newestIndex;

    // Use this for initialization
    void Start()
    {
        int bufferLength = Mathf.CeilToInt(lagSeconds * MAX_FPS);
        _positionBuffer = new Vector3[bufferLength];
        _rotationBuffer = new Vector3[bufferLength];
        _timeBuffer = new float[bufferLength];

        _positionBuffer[0] = _positionBuffer[1] = leader.position;
        _rotationBuffer[0] = _rotationBuffer[1] = leader.transform.eulerAngles;
        _timeBuffer[0] = _timeBuffer[1] = Time.time;

        _oldestIndex = 0;
        _newestIndex = 1;
    }

    void LateUpdate()
    {
        // Insert newest position into our cache.
        // If the cache is full, overwrite the latest sample.
        int newIndex = (_newestIndex + 1) % _positionBuffer.Length;
        if (newIndex != _oldestIndex)
            _newestIndex = newIndex;

        _positionBuffer[_newestIndex] = leader.position;
        _rotationBuffer[_newestIndex] = leader.transform.eulerAngles;
        _timeBuffer[_newestIndex] = Time.time;

        // Skip ahead in the buffer to the segment containing our target time.
        float targetTime = Time.time - lagSeconds;
        int nextIndex;
        while (_timeBuffer[nextIndex = (_oldestIndex + 1) % _timeBuffer.Length] < targetTime)
            _oldestIndex = nextIndex;

        // Interpolate between the two samples on either side of our target time.
        float span = _timeBuffer[nextIndex] - _timeBuffer[_oldestIndex];
        float progress = 0f;
        if (span > 0f)
        {
            progress = (targetTime - _timeBuffer[_oldestIndex]) / span;
        }

        transform.position = Vector3.Lerp(_positionBuffer[_oldestIndex], _positionBuffer[nextIndex], progress);
        transform.rotation = Quaternion.Lerp(Quaternion.Euler(_positionBuffer[_oldestIndex]), Quaternion.Euler(_positionBuffer[nextIndex]), progress);
    }
}

```

It's "okayish" for the follow; but at some point it will catch the leader; as for a 'sled dog' I don't want the followers to catch the leader but keep the same distance/time delay behind the leader.

I've tried every variation but still stuck with it. Is this even the best approach? How would you do it?

Thanks!

# Answer
> 1 votes
Here's a simple way to model an object towed from one end by a rope that can coil up shorter but never stretch longer than a given length.

```
public class SledFollow : MonoBehaviour {

    [SerializeField]
    [Tooltip("Object that pulls the sled.")]
    Transform _leader;

    [SerializeField]
    [Tooltip("Position on the sled's local z+ axis where its tow rope is attached")]
    float _attachmentDistance = 1;

    [SerializeField]
    [Tooltip("How far from the attachment point can the leader go before pulling?")]
    float _ropeLength = 1;

    Vector3 _attachmentPosition;

    void Start() {
        Vector3 localAttachment = new Vector3(0, 0, _attachmentDistance);
        _attachmentPosition = transform.TransformPoint(localAttachment);
    }

    void LateUpdate() {

        // When the leader moves further from the attachment point
        // than the length of the rope, move the attachment point toward
        // the leader until the rope is perfectly taut, not over-stretched.
        Vector3 displacement = _attachmentPosition - _leader.position;
        Vector3 rope = Vector3.ClampMagnitude(displacement, _ropeLength);
        _attachmentPosition = _leader.position + rope;

        // If you never scale the sled, you can skip this line.
        float leverLength = _attachmentDistance * transform.localScale.z;

        // When the attachment point moves, move this object as though
        // connected to it by a rigid lever that can't lengthen OR contract.
        displacement = transform.position - _attachmentPosition;
        Vector3 lever = displacement.normalized * leverLength;
        transform.position = _attachmentPosition + lever;

        // Rotate so the attachment point is along our forward vector.
        transform.rotation = Quaternion.LookRotation(-displacement);
    }
}

```

You may need to make some adjustments if the sled and leader have different heights or go over uneven terrain (such as keeping the sled's up vector aligned with the plane normal, using this function instead of a raw `LookRotation`), but this gets you the basics.

---
Tags: unity, movement, linear-algebra
---


# Question
Title: How do collisions work under the hood in Unity? Is it more performant to make (physics) Layers as specific as possible?
I'm trying to decide how granular to be with my layers.

I assume there's some spatial indexing going on, but...

* Does Unity do work for every pair of objects on compatible layers?
* Will Unity do some amount of work on each pair of compatible colliders even if they aren't near each other?
* How much less efficient is it to, say, have everything on the default layer and quickly break from OnTriggerEnter? As opposed to separating colliders into as many layers as possible to indicate colliders which should never be able to interact?
* Are there negative consequences to having too many layers?

I guess the main question here is: Is it best practice to separate my colliders into layers with as many specific purposes/interaction masks as applicable?

Examples of good layer setups and/or unity implementation details especially appreciated :)

# Answer
> 2 votes
> Does Unity do work for every pair of objects on compatible layers?

> Will Unity do some amount of work on each pair of compatible colliders even if they aren't near each other?

No. Both the PhysX engine for 3D physics and the Box2D engine for 2D physics include spatial partitions and broadphase passes designed to avoid doing detailed collision checks for every pair of colliders.

Both of these are extremely widely-used pieces of technology, in and outside of Unity, and have each been through many years of development and refinement. It's probably safe to assume they're not making a rookie mistake like checking all pairs in a \\$O(n^2)\\$ fashion wherever it can be easily avoided.

> How much less efficient is it to, say, have everything on the default layer and quickly break from OnTriggerEnter? As opposed to separating colliders into as many layers as possible to indicate colliders which should never be able to interact?

This will vary depending on the kinds of physics load you're throwing at it. The only way to get an exact number (like "30% more expensive") is to create a **test and profile it** in a scenario approximating your use case.

You know you'll be paying *at least* the cost to invoke a managed C# script function from unmanaged code, perform the check, and (possibly mispredict and backtrack to) the early-out. So it's reasonable to expect this will be more expensive. Whether it's a meaningful contributor to your game's total frame workload is something only your testing can determine conclusively.

> Are there negative consequences to having too many layers?

If you manage to measure a negative performance impact from "too many" layers, I would find it *very* surprising. The things that tend to choke games are when we're manipulating hundreds, thousands, or millions of objects. Given that there are only a maximum of 32 layers, even a substantial per-layer overhead just doesn't have that much room to stack up.

As above, measure to be certain, but I have never seen the addition of a layer cause a performance problem.

> Is it best practice to separate my colliders into layers with as many specific purposes/interaction masks as applicable?

I would recommend separating out layers *to the degree that it's convenient*. You usually hit diminishing returns trying to apply *any* optimization exhaustively, so start with the ones that cause the greatest inconvenience. Is it annoying to have to check whether a projectile hit a target of the same faction to avoid friendly fire? Split that into layers so the collision doesn't happen in the first place. Is this one off script use case easy enough to solve with a tag check without futzing with the layers? Probably safe to leave it as is until your profiling tells you otherwise.

---
Tags: unity, collision-detection, physics, layers
---


# Question
Title: What aspects do I need to consider when designing save-data of equipment reference in MySQL for online game?
Currently I have several things to save in MySQL for an online game. For simplicity let's say there are heroes, weapons and armors, where heroes can equip weapons and/or armors.

Now I am facing three options:

1. Each hero row keeps a weapon ID and an armor ID
2. Each weapon row keeps a hero ID and each armor row keeps a hero ID
3. Have one or more separate tables to store the equipping status.

One easy aspect I can think of is the storage size. If a player can own a lot of weapons but only a relatively small amount of heroes (which is true in most online games), then saving weapon IDs into the Hero table seems good.

However I am pretty sure this is not the only aspect I need to consider and as a matter of fact I found many other "experienced programmers" tend to do it the second way or third way, some of which worked in large game companies. Unfortunately as for now I couldn't talk to them any more to get advice.

What other aspects do I need to take into consideration when designing these type of cross-reference in user save-data?

# Answer
> 1 votes
I'm going to start by telling you the orthodox way to do this. So I'll start describing what you should consider and do. And I want to point this early because then I'm going to tell you to throw that away. What I want you to keep are the intuitions.

You need a reference between two tables, let us say heroes and weapons. *Spoilers: either way can work.*

You need to consider the multiplicity of the reference. In this case the hero has at most one weapon. And the weapon is held by at most one hero.

We need to consider the navigability. Which are you going to query?

* Given heroes, find out what weapon they have.
* Given weapons, find out what heroes have them.
* Both.

I'm not surprised if the answer is both. Which suggest you could make the reference either way.

By the way, the constraints aren't much different:

* If we are going to store the reference to the weapons on the heroes table, then you need:

+ A primary key in the weapon table. To uniquely identify weapons.
    + A foreign key going from the heroes table to the weapon table. To ensure that the weapon a hero has exists.
    + And a unique key on the weapon reference. So you can make sure that only one hero has the weapon.
* If we are going to store the reference to the hero on the weapon table, then you need:

+ A primary key in the hero table. To uniquely identify heroes.
    + A foreign key going from the weapon table to the heroes table. To ensure that the hero that has the weapon exists.
    + And a unique key on the hero reference. So you can make sure that the hero has only one weapon.

---

Now, if we have the freedom to make the references which ever way we prefer, what should we prefer? The answer is that you should prefer a tree or forest structure. That is, you want root tables.

Note: Cycles are allowed. However, special consideration should be put on any cycle. The problem with cycles is that they tend to introduce multiple sources of truth, which you might need to reconcile with constraints. And the constraints may result in a structure that is not easy to update.

My intuition is that heroes are more important than weapons, so the references should flow in that direction. However, this depends on the system (the game) you are doing. *You might as well have a game in which heroes are a resource, for example.* You have no reason to trust my intuition (after all I don't know your game), so how do you know you have a good structure? A tell-tale sign is that it has clear roots and leaves of references. Another is that making joins is easier. You should be able to tell in what direction the references go, without loops (any remaining cycle will have single root and leaf). *And my guess is that the weapon probably does not reference much of anything, so it could be a leaf. While the hero references other things, so it might be a root.*

---

Example: we have teachers that teach some topics, and student that study some topics. We want to make sure the student is studying under a teacher that teaches the topic the student study. Furthermore these are many-many relationships. A student can study multiple topics. A topic can be studied by multiple students. A teacher can teach multiple topics. And topic can be taught by multiple teachers. How do you model that database?

Clearly you have students, teachers and topics. Those are nouns. So make tables for those. For many-many relationships, we add auxiliary tables. So there should be student-topic table references both a student and a topic, and that tells you what topics the student studies. Similarly there should be a teacher-topic table. And hmm… I need to do something for student-teacher. *So you can go student - student-teacher - teacher - teacher-topic - topic - student-topic - student. That is a cycle.*

Now, in student-topic I need the reference to the teacher so I can verify with student-teacher via foreign key. And something similar happens with the other tables. As a result it would be impossible to update them individually. Furthermore they all end up having the same fields. This is telling you something: make a single table.

So, there will be tables for student, teacher and topic. And a table that references them three. That table is a root. It must be something important in the system. *And naming things in software engineering is hard.*

But look, if I add the corrects additional requirement it becomes clear: I want to know in what class room at what time. Where should I add that? Clearly I need a table for the class rooms and a reference from our root table. And I can add the class hours too. So the table represents a group of student that study a topic under a teacher at a class room at a time. It is a class! *The class is the root, everything else is a leaf.*

So, the common wisdom is that you will have some root tables in your system, and everything else comes from them in a forest structure (or as close to a forest structure as possible - In fact, you want it to be as close to a tree structure as possible).

---

And, finally to ease the queries, you can create views from joins of the tables.

---

This is the part where I tell you to throw that away. A database normalized is not the best for performance. For starter adding redundancy can improve performance. So you could store both a reference to the weapon in the hero and a reference to the hero in the weapon. For example.

However, if the argument is performance... You should profile!

Which query are you going to do more often? And how slow is to do that query query if you implement it each way? And what if you can keep data cached on the application side?

Also consider how and how often the information will change. If the changes need to happen often you might want to reduce the number of places the information has to be stored and referenced from. But if it isn't, you can afford to store in multiple places. However, you want to have a single place where you update and have it propagate to other places (e.g. using triggers).

In fact, if the data does not update often (that you say that online games only have a few heroes makes me think this is the case), you might *compile* the database. For example, you could create, design and test weapons in a tool that export them in a simple file format (e.g. json - this also makes it easier to put them in version control), and then a tool that generates a script to update the production database adding the weapon taking those files as input. And that script might take care of propagating the data or any additional updates that you need. *So, if you need to write both what weapon a hero has and what hero has a weapon, you can do that.*

---

Please notice that we could be asking this question about the heroes on a hero shooter or similar game, where there is a relatively short list of heroes for player to choose from. Or we could be asking this question about heroes, referring to the characters of each player, which are at least as many as there are players. That is there is hero (the actual hero instance) and hero (the platonic hero type). And the actual hero would reference the hero type. Which has the weapon? Is it that each hero type has a weapon equipped before a player selects it, and that is what you want to query. Or is it that each hero a player has selected has a weapon (possibly set by the player), and that is what you want to query. *Those are different queries.*

Similarly: there is weapon and weapon. For example, there could be vendor that sells swords. These swords don't exist as individual objects (if the vendor has inventory, it actually has tuples of quantity and the weapon type) and then when the use buys, the actual weapon is created.

If you need to model that, you would say that the weapon has a weapon type. That is, the weapon has a reference to the weapon type. And you could be browsing all the weapons on the inventory and want to know if the weapon is equipped by somebody. Or you could be browsing all the weapon types available at a vendor and want to know there a hero that has equipped a weapon of the same type. *Those are different queries.*

As you can imagine it make little sense to store a reference to the hero in the weapon type. Let alone verifying that. You would have to check that the actual weapon equipped by the hero is of a type that references the hero. *Hey, a cycle. Avoid.*

---

So, have a hard look at your requirements, extract the nouns that should become tables, and add any other auxiliary table you need. Take care of any cycles. If performance is a problem: profile. If you need to add redundancy for performance, do so. *In fact, if you need to merge or split tables, do so.* However, keep a single place where you do updates, and automate propagating the change. Tools such as constraints, views, triggers, and script generation can help.

---
Tags: savegame, mysql
---


# Question
Title: Blender`s assign material to face analog in Godot
I am very new to Godot. I am using version 3.4 stable on Windows 10.

I made a building in Blender and I wanted to make interior mapping instead of poor 2d windows textures. I found a material for that, and just assigned it to windows faces.

Unfortunately that model failed to be imported as .escn, so I decided to import it with one whole material, and then do the same last steps in Godot. I am going to use this shader for that.

I imported it, created new `ShaderMaterial`, then `VisualShader` and setup as you can see in screenshot.

What is next? How do I select windows faces and set to them interior mapping shader? Is that possible in Godot at all?

Mesh:

---

@Theraot solution is working:

# Answer
> 1 votes
If you are editing the `Mesh` resource, you should see in the Inspector Panel a series of properties named "Surface 1", "Surface 2" and so on. Each one has a material assigned. There you can replace the material with your new `ShaderMaterial` (alternatively you could edit the materials that were imported along with the model).

Similarly, if you are editing a `MeshIntance`, you should se a series of material properties which are overrides for the materials of the `Mesh` resource, and you can also se the `ShaderMaterial`.

If you don't see multiple surfaces/materials, then your model got a single surface. And no, Godot does not have the means to divide surfaces.

---

Addendum post edit: Yep, that is a signle material in your `MeshInstance`. Multiple look like this:

And in the `Mesh` they look like this:

You can open the `Mesh` resource from the `MeshInstance` by clicking on its Mesh property, it should be an `ArrayMesh`.

---

As you have certainly found out, you are not going going to get complex Blender materials on Godot. Both parts have a bit of blame here, because Blender materials are not standard, and only the simplest can be encoded in standard formats. If you are using a Godot exporter addon in Blender, it might try its best to translate the materials, but some just cannot be recreated, and that part has to do with Godot limitations.

Thus, my advice is to set simple materials for the different surfaces you need. And then if you need more complex materials, override them in Godot with materials that work on engine.

---
Tags: shaders, godot
---


# Question
Title: In which directory to write game save files/data?
I need a **definite list of directories, one or more per platform, of where to put game save files and other game generated data**. Either based on the OS developer specification, or because it is common usage if there is no recommendation.

Please **provide one answer per platform**, with different directories. Also, **example of how to get the directory location in C++ or C is best**, as it's the language you'll have more hard time.

Locations:

* Player's game data (saved games, config).
* Shared game data (like high-score or config for all computer users).
* Temporary game data (aka cache directory).

# Answer
# Windows (Xp and following)

Based on:

These locations assume that Windows is installed on the C: disk. Append your own directory with game name or game company then game name to these directories.

---

**If you use Window 8 Metro-style application**, you'll have to use a specific API instead of trying to reach directories. Read:

---

## Player's game data

Windows Vista and following:

> C:\Users\\{username}\AppData\Roaming

Windows Xp:

> C:\Documents and Settings\\{username}\Application Data

You can automatically get the right user-name-dependant address by getting the `APPDATA` environment variable.

Standard C (all compilers):

```
char* appdata = getenv("APPDATA");

```

Visual Studio 20xx (avoid getenv() warning saying it's not safe) - non Metro Style:

```
char *pValue;
size_t len;
errno_t err = _dupenv_s( &pValue, &len, "APPDATA" );

```

**Boost users**: at the moment I write this boost.filesystem (that is also a draft of the filesystem library proposed to the next C++ standard) doesn't implement yet a function to provide the right directory. However, there have been discussions about this before. Please feel free to update this section if things changed.

---

## Shared game data

Windows Vista and following:

> C:\ProgramData

Windows Xp:

> C:\Documents and Settings\All Users

You can automatically get the right address by getting the `PROGRAMDATA` environment variable.

Standard C (all compilers):

```
char* appdata = getenv("PROGRAMDATA");

```

Visual Studio 20xx (avoid getenv() warning saying it's not safe) - non Metro Style:

```
char *pValue;
size_t len;
errno_t err = _dupenv_s( &pValue, &len, "PROGRAMDATA" );

```

**Boost users**: at the moment I write this boost.filesystem (that is also a draft of the filesystem library proposed to the next C++ standard) doesn't implement yet a function to provide the right directory. However, there have been discussions about this before. Please feel free to update this section if things changed.

---

## Temporary game data

Windows Vista and following:

> C:\ProgramData

Windows Xp:

> C:\Documents and Settings\\{username}\Local Settings\Temp

You can automatically get the right address by getting the `TEMP` environment variable.

**C++ Boost users**: there is **a simple cross-platform boost.filesystem function** for this

```
namespace bfs = boost::filesystem;
const bfs::path TEMP_DIR = bfs::system_complete( bfs::temp_directory_path() ); // system_complete() call is optional

```

Standard C (all compilers):

```
char* appdata = getenv("TEMP");

```

Visual Studio 20xx (avoid getenv() warning saying it's not safe) - non Metro Style:

```
char *pValue;
size_t len;
errno_t err = _dupenv_s( &pValue, &len, "TEMP" );

```
> 22 votes

# Answer
# MacOS

Based on:

In unix-based OS, the `~` directory is automatically located at the user's home directory where user-specific data are located. This means that whatever the language, on these platforms you can access automatically this folder by using `~` instead of using a OS-specific function. Also note that `/` is the root path of the whole system, not a path to the root of the main disk.

Append your own directory with game name or game company then game name to these directories.

---

## Player's game data

Apple's guideline is to locate save and config files there to make them saved automatically in the cloud if available:

> ~/Documents

However, it is better (and more often used) practice to locate these files in:

> ~/Library/Application Support/

Just know that in this case the files will not be saved automatically to the cloud. If you want the player to choose, use the platform's API to make him choose.

## Shared game data

> /Library/Application Support

Notice that there is no `~`, it's not relative to user's home but to system's root.

## Temporary game data:

If the data don't need to be kept between executions:

> /tmp

If the data need to be kept between executions;

> /Library/Caches (for MacOSX)

**C++ Boost users**: there is **a simple cross-platform boost.filesystem function** for this

```
namespace bfs = boost::filesystem;
const bfs::path TEMP_DIR = bfs::system_complete( bfs::temp_directory_path() ); // system_complete() call is optional

```
> 15 votes

# Answer
# Linux Debian (Ubuntu, Fedora, etc.)

Based on:

In unix-based OS, the ~ directory is automatically located at the user's home directory where user-specific data are located. This means that whatever the language, on these platforms you can access automatically this folder by using ~ instead of using a OS-specific function. Also note that / is the root path of the whole system, not a path to the root of the main disk.

Append your own directory with game name or game company then game name to these directories.

---

# Player's game data

Traditionally, for the game Aquaria it would be:

> ~/.aquaria

Note that directories and files starting with `.` will be hidden by default to the user.

Most desktops now try to adhere to the XDG specification, which recommends

> $XDG\_CONFIG\_HOME/aquaria

or

> $XDG\_DATA\_HOME/aquaria

for configuration and savegames instead.

If `$XDG_CONFIG_HOME` not set use :

> ~/.config/aquaria

or

> ~/.local/aquaria

This is mostly to unclutter user's home directory, as well as allow users to run multiple profiles of an application if they deem it necessary. There are also other dedicated user-specific directories in the specification.

# Shared game data

> /var/games/

Shared config files should be located in

> /etc/games/

# Temporary game data

> /tmp
> 12 votes

# Answer
For **Linux/Unix** the **XDG Specification** says:

> If **$XDG\_DATA\_HOME** is either not set or empty, a default equal to **$HOME/.local/share** should be used. https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html

So for the above example of the game Aquaria:

* Wrong: ~/.local/aquaria
* Correct: ~/.local/share/aquaria

And if you write your own code this means, that you have to first check if the variable $XDG\_DATA\_HOME is set. If it is set, you have to use, what its content is.

If it is NOT set, then you have to use ~/.local/share/\[YOURGAME\]
> 0 votes

---
Tags: savegame
---


# Question
Title: Creating a game on Linux with SDL and distributing it
### TL, DR: Will I be able to get a single `.exe` file which will work smooth in a PC which does not have SDL or so installed ever. If not, how close will be the closest approach?

Yes, now, I want to start game development using C/C++ and I am on a Linux machine.

From the resources on the web, I saw that `SDL2` is a common API to use. However, I could not get satisfying answers about the following:

For me, it is important to be able to distrubite my games to my friends(let's say) with little amount of file. So, I wonder how this process works with SDL2. Will it be easy(or even possible, maybe?) to distribute a `.exe` file to my friends who are using Windows OS and don't have SDL2 installed? If it is so, a short description of the process would be very nice.

To make my point more clear, while I was using `pygame` module of `python` to develop a game(which includes sounds, images etc.), I was able to run `pyinstaller` with `--onefile` option on a Windows machine to get a **single executable** (`.exe`) and my friends who does not have even python installed was able to run the game without any problem. So my question is simply asking that whether it will be similar to this or not with `SDL2` case.

Thanks in advance.

p.s: Using a Windows machine to build the game is something I can do.

# Answer
> 1 votes
If you need a single executable file for the game that doesn't rely on other shared libraries being present, then what you want to do is to create a 'static' compilation. Whether or not this is possible will depend on what the libraries you depend on are, as they will need to be compiled statically into the binary along with the code that you write. This sometimes doesn't work... I guess an example would be *libcurl*, something to do with the networking part of *glibc* that it, in turn, relies on, so you will have a difficult time statically compiling code that relies on *libcurl*.

But of course, many games don't rely on *libcurl* (or any of the other libs that are resistant to static linking), so often it is quite possible, in the case of SDL2 you need to first do a static build of SDL2, this will produce a file `libSDL2.a`, the `.a` extension is used for static libraries. Then, when you compile your program, you need to link to `libSDL2.a` instead of the dynamic version of the library and you need to use your compiler's flag for a static build, in the case of GCC the flag is `-static`.

I think SDL's default build creates both the static and dynamic versions, so follow their normal compilation instructions to get the `.a` file. An example of its use and more details are provided in Wasin's blog, reproduced here:

```
gcc -Wall appcode.c /usr/local/lib/libSDL2.a -lm -liconv
-Wl,-framework,CoreAudio -Wl,-framework,AudioToolbox -Wl,-framework,ForceFeedback -lobjc -Wl,-framework,CoreVideo -Wl,-framework,Cocoa -Wl,-framework,Carbon -Wl,-framework,IOKit -Wl,-weak_framework,QuartzCore -Wl,-weak_framework,Metal

```

Let's break that down a bit. Most of this is generated by SDL2's compilation helper and is for what libraries SDL2 needs to pull in for what you're doing, these will all be in your `.a` file, but must still be named. We'll come back to these in a minute, but first, the parts that are important here are:

```
gcc -Wall appcode.c /usr/local/lib/libSDL2.a

```

`gcc` here is our compiler, `-Wall` just means to give 'all' warnings (but not really all, just a lot, to actually get all warnings you need some more flags, off the top of my head maybe `-Wextra` or `-pedantic`), not strictly needed for this. `appcode.c` is the game code you wrote, so put your file name there, and finally there is the statically compiled SDL2, the `.a` file.

How did we find this other long list of stuff? As Wasin explains on his page, it comes from the command `sdl2-config --static-libs`, and then he removes the `-L ... -lSDL2` part from the front because that is for the dynamic compilation of SDL2 itself and we want even that to be static here. The `sdl2-config` should come from SDL2 when you compile the library.

I think the key part that you need is that, in order to not have external dependencies, what you need to search for is how to statically compile your program. A statically compiled program should be good to go typically across a given OS+architecture combination, e.g. 64-bit Arm+Linux or 32bit x86 + Windows98 so you probably want to use only those general optimizations for as broad of architecture support as possible (that is, use a compiler flag for architecture like `-m64` and `-m32`, which targets 64 and 32 bit in general in order to support a wide range of architectures, not something `-march=native`).

To build a statically compiled SDL2 app for Windows is basically the same main steps.

1. Build SDL2 on your Windows dev machine and find where it put the static library (`libSDL2.a`).
2. Use the SDL2 tool to find the other libs that need pulling in (`sdl2-config --static-libs`).
3. Use some compiler on Windows to compile your program while linking to the static version of SDL2 (the `.a` file) and the static libs that the tool listed).

Alternatively, this can be possible to do all from Linux while targeting a Windows build via cross-compiling, but the details of that are beyond the scope I wish to cover here.

NOTE: This answer is for SDL2, it is my understanding that SDL1.2 is not as friendly to static linking.

Also note that if you do something like getting your game on Steam for your Windows users, they provide an included version of SDL1.2 and SDL2 with the Steam Runtime, so anyone downloading from Steam will not need to install SDL on their own as they will already have it. Actually, if they have Steam but your game isn't on Steam, I think it is still possible for them to use the runtime for your game. They would use the option to add a non-Steam game to their Steam library, and then right-click it and go to properties, then to the compatibility part and check the box to force compatibility settings and pick Steam Runtime from the dropdown menu. I mean, you probably don't want to ask them to install Steam just to play your game, but it might be an easy option if they mostly have Steam anyway.

Finally, there are reasons NOT to use a static library. Their benefits are mainly that they tend to be portable and reliable due to having few dependencies, mainly just OS and CPU architecture. Some of their downsides go hand-in-hand with the benefits. For instance, when shared libraries are patched for security and performance, the versions in the static compilation will not be unless you rebuild it with the new versions and your users download the new version. If you rely on large shared libraries normally (dynamic linking), then building statically can make your executable very large, as those shared libs all need to be in there in static form. Also, remember how I mentioned that when we build statically, we typically only optimize for a very general architecture? This means we may have less performance since the dynamic libraries on a particular user's system might be built for their specific architecture (e.g. I hear Gentoo users like to compile with `-march=native`). But on the plus side, static compilation could potentially allow better joint compilation optimization across libs and avoid the (arguably quite small) overhead of calling to an external dynamic library.

I'm sure there may be other potential snags I have overlooked, having not tested the process myself firsthand. Please feel free to add corrections and details in the comments. I know the question is old, but I answered because I was looking myself and it came up high in the search results.

---
Tags: c++, sdl, sdl2, c, linux
---


# Question
Title: How to visualize angle of projection in Oblique Parallel Projection?
We know that in **Oblique Parallel Projection** Point (x,y,z) is projected to position (x\_p,y\_p) on the view plane.Projector (oblique) from (x,y,z) to (x\_p,y\_p) makes an angle alpha. with the line (L) on the projection plane that joins (x\_p,y\_p) and (x,y). Line L is at an angle phi with the horizontal direction in the projection plane.See this **image1**:

And in Oblique Parallel Projection Angles, distances, and parallel lines in the plane are projected accurately.For example see below **image2**:

My question is where is the angle alpha in **image2**, I mean I see the angle phi on the image , so where is alpha in that image to understand better?I want to see 12 edges of original image projected to view plane with projector and angle alpha,phi levelling.

N. B:1 -- I am following Hearn and Baker book which screenshot like this.

N. B. -- I want to understand just intuition in easy way rather than details.

# Answer
> 2 votes
On OP request, I'm posting the images I produced as answer.

These were made with Sketchup. They show a cube a plane where the cube is projected in an oblique projection. The blue sectors represent the angle alpha, and green sectors represent the angle phi. Observe that the angle phi exists entirely in the projection plane, while alpha does not. Instead alpha is the angle between the projection plane and the segment that goes from a point to its projection. As a consequence it is impossible to depict alpha on the projection plane, since it goes out of it. Furthermore, depicting alpha requires knowing the relative position of the object and the projection plane.

*These images have perspective. It is odd to me that I'm using a projection to visualize another. However, I believe this is the best way to gain an intuition of it (actually I believe being able to orbit at will is better, but sans that here are multiple views).*

---

*I believe these are Cabinet, unless I'm confusing things.*

*Animation*:

---
Tags: 3d, graphics, projection, projection-matrix, visualization
---


# Question
Title: How to compute the origin/pivot point of objects in a hierarchy
I'm sorry if the title is bad, but i'll try my best to explain my problem.

Consider a simple hierarchy of objects (Object1 -\> Object2 -\> Object3)

If i now were to rotate Object1 by 45 degrees in the x axis, i believe Object2 and Object3 should also be rotated by 45 degrees in the x axis but the rotation origin changes and is inherited from the parent

I do understand that when working with matrices i just multiply the parent and child transforms together(afaik) but in my case i am not using matrices(For a solid reason)

Instead i just have 3 rotation functions(1 for each axis) and before each rotation i set the pivot point/origin like this:

```
for each vertex in object:
vertex.translate(-origin)
vertex.rotate(.....)
vertex.translate(+origin)

```

I am trying to figure out how to compute the origin for each object in a way where it inherits the rotation(?) from the parent.

What i thought i had to do is simply 'accumulate' origins, for example: If i use the same example as above where i rotate Object1 then i computed the origins the following way:

```
Object1.origin = Object1.origin
Object2.origin = Object1.origin + Object2.origin
Object3.origin = Object1.origin + Object2.origin + Object3.origin

```

But that doesn't seem to work, example of 4 objects in blender(i'll call them Object1, Object2, Object3, Object4, so Object1 has a child Object2 which has a child Object3 which has a child Object4) where i rotate Object1 in the x axis: https://i.imgur.com/PI9Jsm8.gif

Example of the same object being rotated in the x axis(by roughly the same amount) in my program where i set the origin for each rotation the way i explained above: https://i.imgur.com/geGqGP2.gif

This looks wrong, and im not sure what the right way to do it is, heres the pseudocode(as it's simpler to understand) that computes the origin for each object and rotates it:

```
// getAllChildren returns the object itself, it's children(including indirect children)
// so if use the above example and Object1 was the input, then it'd return Object1, Object2, Object3, Object4.
// if the input was Object2 it'd return Object2, Object3, Object4
// getUntilRootReverseOrder() returns all the parents of that object(including indirect ones)
// so if the input was Object4 then it would return Object3, Object2, Object1
// if the input was Object2 it would return Object1

for each object in object.getAllChildren() {
List parents = object.getUntilRootReverseOrder()
origin = object.origin
for each parent in parents {
    origin.add(parent.origin)
    object.setRotationOrigin(origin)
    object.rotate(...)
  }
}

```

My goal is to have the objects rotate the same exact was as in blender, any help & advice is much appreciated.

The reason why i am not using either matrices or quaternions is because i am working on a tool for a fairly old engine which just uses euler angles for rotations(it does not use matrices at all anywhere in the engine) however i am perfectly fine with using either matrices or quaternions as long as the end result can be encoded as euler angles (and of course i need the origin for each rotation) To be more specific, it is not a tool for just me(i am planning to make it open source) if i were to edit the engine itself and made it use matrices or quaternions, everyone who would use the tool would also have to do the same which isn't ideal.

Actual code of how i apply rotations if helpful at all:

```
    private void applyRotation(int[] labels, int dx, int dy, int dz) {
        for (int label : labels) {
            if (skeleton.getVertexGroup(label) == null) {
                continue;
            }
            for (int vertex : skeleton.getVertexGroup(label)) {
                skeleton.translate(vertex, -originX, -originY, -originZ);
                if (dz != 0) skeleton.rotateRoll(vertex, SINE[dz], COSINE[dz]); // roll
                if (dx != 0) skeleton.rotatePitch(vertex, SINE[dx], COSINE[dx]); // pitch
                if (dy != 0) skeleton.rotateYaw(vertex, SINE[dy], COSINE[dy]); // yaw
                skeleton.translate(vertex, +originX, +originY, +originZ);
            }
        }
    }

```

Example input & desired output:

Input: a rotation(eg 45 degrees in the x axis) for Object1 (I also have information about all the children of Object1 and their pivot points)

Desired output: The rotations for Object2, Object3, Object4 in euler angles(im assuming they're all 45 degrees in the x axis tho) and their pivot points(and of course also the pivot point of Object1)

The rotation is represented as a quaternion initially but can easily be converted to either a rotation matrix or even euler angles(afaik most math libraries have those functions built in)

Using matrices this is what i thought could potentially work, but im not 100% sure: if i were to rotate Bone1 which has 3 children(including indirect) (Bone 2-4)

```
float rotation = PI / 4; // 45 degrees

Matrix bone1Matrix = Matrix.identity().translate(Bone1.localPosition).rotateX(rotation)

Matrix bone2Matrix = bone1Matrix.multiply(Matrix.identity().translate(Bone2.localPosition).rotateX(rotation)

Matrix bone3Matrix = bone2Matrix.multiply(Matrix.identity().translate(Bone3.localPosition).rotateX(rotation)

Matrix bone4Matrix = bone3Matrix.multiply(Matrix.identity().translate(Bone4.localPosition).rotateX(rotation)

```

And the origin of each bone would just be the translation part of their matrix(just a guess)

the rotation of each bone would either be the accumulated rotation or the initial rotation(i'd assume it's the latter)

# Answer
> 0 votes
I figured it out, since my 3 other bones(bone 2-4) had no transformation applied to them, they all simply inherited the legs global transform(so in my case bone 2-4 matrices were just identity matrices)e

---
Tags: rotation
---


title: LWJGL - How to draw text on screen

text:
# Question
Title: LWJGL - How to draw text on screen
After some months on libGDX, I chose to make a little java game library based on LWJGL. I have already tried to do it, but got stuck on this same problem: how render text on screen.

The first time, I used Sick, but it was deprecated... how do I should do?

This time I tried this code, of couse it doesn't work (I read it on StackOverflow):

```
public class Starter {

private String GAME_NAME;
public String VERSION;
private int WIDTH, HEIGHT;
private static long window;

public Starter(@NotNull JJGLInfo info){
    Objects.requireNonNull(info);
    GAME_NAME = info.getGAME_NAME();
    VERSION = info.getGAME_VERSION();
    WIDTH = info.getWidth();
    HEIGHT = info.getHeight();
}

public void run(){

   System.out.println("Hello player by JJGL\nJJGL Version: " + VERSION + "\nLWJGL Version: " + Version.getVersion());

   this.init();
   this.loop();

   this.terminate();
}

private void terminate() {
    glfwFreeCallbacks(this.window);
    glfwDestroyWindow(this.window);

    glfwTerminate();
    glfwSetErrorCallback(null).free();
}

ByteBuffer pixels = this.getByteBufferFromString();
private void loop() {

    GL.createCapabilities();
    glClearColor(1f, 1f, 0f, 0f);

    while (!glfwWindowShouldClose(this.window)){
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glfwSwapBuffers(this.window);

        ByteBuffer pixels = this.getByteBufferFromString();
        glEnable(GL_TEXTURE_2D);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 1000, 200, 5, GL_BLUE, GL_UNSIGNED_BYTE, pixels);
        glEnd();

        if(Input.isKeyPressed(GLFW_KEY_A))
            System.out.println(1);

        glfwPollEvents();
    }
}

private ByteBuffer getByteBufferFromString(){

    String text = "ABCD";
    int s = 256; //Take whatever size suits you.
    BufferedImage b = new BufferedImage(s, s, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D g = b.createGraphics();
    g.drawString(text, 0, 0);

    int co = b.getColorModel().getNumComponents();

    byte[] data = new byte[co * s * s];
    b.getRaster().getDataElements(0, 0, s, s, data);

    ByteBuffer pixels = BufferUtils.createByteBuffer(data.length);
    pixels.put(data);
    pixels.rewind();
    return pixels;
}

/**
 * Initialize window
 */
private void init() {
    //Set Callback, when library get an error, it will be print
    GLFWErrorCallback.createPrint(System.err).set();

    //Let's initialize GLFW. Without this call, most of functions won't work
    if(!glfwInit()){
        throw new JJGLInitException("Could not initialize GLFW");
    }

    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);   //Make window hidden
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);  //Make window resizeable

    window = this.createWindow();

    glfwMakeContextCurrent(this.window);

    glfwShowWindow(this.window);
}

/**
 * Creating window. If you have passed -1 at one side,
 * it will be maximize (-1, 30 only width will be maximized)
 * @return
 */
private long createWindow() {
    //Getting info about screen
    GLFWVidMode glfwVidMode = glfwGetVideoMode(glfwGetPrimaryMonitor());

    if(this.WIDTH <= -1)
        this.WIDTH = glfwVidMode.width();

    if(this.HEIGHT <= -1)
        this.HEIGHT = glfwVidMode.width();

    //Creating window
    return  glfwCreateWindow(this.WIDTH, this.HEIGHT, this.GAME_NAME, MemoryUtil.NULL, MemoryUtil.NULL);
}

public static long getWindow() { return window; }
}

```

# Answer
> 1 votes
I see several issues and missing things in your approach. Foremost problem is that you are not issuing any actual OpenGL draw call, i.e. you are never telling OpenGL to render anything.

In your loop function you do:

```
     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
     glfwSwapBuffers(this.window);

```

This clears the back buffer (to yellow in your case) and then you immediately present the contents of this back buffer to your window with the `glfwSwapBuffers` command.

What you would need to do is in between these lines issue actual drawing commands, such as `glDrawArrays(...)` etc. For such a draw call to work, you need to pass some geometry to OpenGL. This can be done in several ways, modern GPUs and modern OpenGL, versions 3.x and 4.x, prefer to use so-called vertex buffers which reside in memory on the GPU. These vertex buffers are associated with so-called vertex arrays which you can use to actually relate your vertex data to certain vertex shader inputs.

I would recommend you look into basic tutorials such as ones on LearnOpenGL. I know the examples there are not written in Java, but the basic facts about how to use OpenGL should be very much applicable anyway.

---
Tags: java, lwjgl
---


title: Ray tracing the Next Week - Cornell Box

text:
# Question
Title: Ray tracing the Next Week - Cornell Box
I'm so excited to learn ray tracing and did a lot of fun. But I'm stuck at rendering empty Cornell Box scene.

It has some darker color along the bright color and it's seem different with the image in the book. Sorry if my English confuses you because I'm still learning it.

My source code about this project for someone want to check. https://github.com/trinhlehainam/StudyRayTracing

# Answer
> 1 votes
**I solved this.**

The bright color is look like rectangle because the light that is reflected by Lambertian material is scattered randomly in unit cube (with center is the unit normal) . I fixed this by just allow ray is scattered randomly point in unit sphere.

Final result

**Example code :**

Function to generate random vector

```
vec3 random(float min, float max)
{
    return { Random(min, max), Random(min, max), Random(min, max) };
}

```

Code show generate random position in unit sphere, with using dot product to check the the vector is in radius of unit sphere, and reject it when vector is generated outside the unit sphere.

```
vec3 random_in_unit_sphere()
{
    vec3 v = random(-1.0f, 1.0f);
    while (dot(v, v) >= 1)
        v = random(-1.0f, 1.0f);
    return v;
}

```

Then from the hit point we just use normal vector of hit surface like the center of unit sphere, and add with random vector position in unit sphere. This random vector will work as direction vector that bend normal vector to direction of scatter ray.

```
scatter_ray.direction = hit_surface.normal + random_in_unit_sphere();

```

# Answer
> 0 votes
I guess u did something like

```
vec3 vec3::random_unit_vector()
{
    auto x = drand(-1, 1);
    auto y = drand(-1, 1);
    auto z = drand(-1, 1);
    return vec3::unit(vec3(x, y, z);
}

```

I came across this post because I made the same error, normalize an uniformly distributed random vector is wrong, each axis has to be normally distributed.

Personally I don't like the retry idea, so I use the cylinder surface mapping to get random vec3 on unit sphere surface

```
vec3 vec3::random_unit_vector()
{
    // use cylinder surface mapping
    auto theta = 2.0 * M_PI * drand(0, 1);
    auto z = drand(-1, 1);
    auto r = ::sqrt(1.0 - z * z);

    return vec3
    {
        r * cos(theta),
        r * sin(theta),
        z
    };
}

```

and

```
vec3 vec3::random_unit_sphere()
{
    double u = drand();
    return cbrt(u) * vec3::random_unit_vector();
}

```

to get random vector inside unit sphere

---
Tags: raytracing
---


# Question
Title: Rendering a few simple world space ui images drastically impacts performance
I was hoping I could render a little world space ui icon over my trees when they have been marked for cutting. However just showing 70-80 world ui images cuts my FPS in half, using up almost 8ms per frame.

How are you supposed to do this in Unity?

This is all I enable when a tree is marked, parented to a world space canvas:

# Answer
World space UI shouldn't have had such an impact on performance. in fact, you're supposed to just use a dozen Canvases in a regular 30fps mobile game. I'm guessing your problem is because of *how* you are using it. Maybe take care of the scripts that interact with it? and Unity has a big article about performance tips of using Canvases, one of which is exactly ***not to enable/disable the canvas gameobject, but rather enable/disable just the Canvas Component***.

And then if you're still having issues, maybe try it on a new sample scene? you should have no performance impact if you add 10 empty world canvas to the new sample scene on a low end PC
> 1 votes

---
Tags: unity
---