text:
What's the difference between Raytracing and Physically-based-rendering?
I know raytracing is a technique based on the route calculation done by the light, following the rays through the interaction with the surfaces, and that Pbr is a collection of render techniques that are more or less based on the theory which matches that of the physical world, aiming to mimic light in a physically plausible way.
Is it possible to implement both into a Rendering engine?
What's the difference?

Yes, you can... sort of.
DirectX announced a support for hardware based ray-tracing a couple of weeks ago and Epic Games (creators of Unreal Engine) have already made a demo with the models from the new Star Wars movies (check it out here).
This can make reflections much easier to create and should eliminate cube map based rendering almost completely.
There is a catch though, it is very slow. They had to run it on a 1280p screen with a Titan X to get 60FPS, which is a big problem considering how many people have 4k screens.
So yes, it's possible, but we'll still have to stick to cheating our way through different rendering techniques for a while and it's unlikely it will replace rasterizing very soon.

Isn't there a way to make raycasting a bit faster (t the cost of quality of course)? Or would it be wise to stick to pbr?

@Gabriele There's a technique called raymarching. Instead of calculating the distance analytically, you either go a set distance every time and check if you collided with the object or use a distance field, which approximates the distance to the closest object, so you never overshoot. It's very fast (90% of shadertoy.com is just that), but you have to implement it yourself

oh okay.. that would also reduce the light bounces, wouldn't it?

@Gabriele Vierti not really, at that point you can do anything, it's the same as raytracing, but you get the distance easier

There are two different aspects of a renderer in play here:

How do we determine which bits of surface are visible on each screen pixel (including direct visibility or reflection), and what lighting those surfaces receive? Here we have two families of techniques:

Raytracing & Path Tracing renderers do this by modelling the way rays travel through the scene, including rays through each screen pixel and rays from each light source, seeing where they strike scene geometry first, and where they bounce to.

Rasterizing renderers do this by breaking surfaces into small pieces like triangles, and projecting them onto the screen, using a depth buffer to handle layering. For determining whether a point is lit or in shadow, we do the same thing from the light's point of view, saving the result to a "shadow map" texture we can sample when rendering the camera view.

Now that we know what surface we're drawing and what lighting it receives, how do we colour it so that its material appears to respond to light in the right way?

Older renderers, both raytracing and rasterizing style, relied on simple/idealized models of how materials bounce light, like perfect cosine Lambertian reflectance. That's why when you look at older 3D renderings, even raytraced output tends to have a slightly surreal, plastic-y appearance. The rays are hitting the right spots, but there's something just a bit off about how the material interacts with that light. Real world materials are more complicated.

In physically based renderers, the materials' response to light is grounded in more sophisticated models and often direct measurements of real materials, including things like microfacets, surface anisotropy, fresnel effects, energy conservation, etc. See this earlier answer for some examples of how this affects the appearance of rendered objects and how artists work with them. This work started in offline/ray- & path-traced rendering for films, and more recently made its way into games' rasterizing renderers. The use of these more sophisticated models helps the shading of objects look more natural and accurate over a range of lighting conditions.

So yes, you can combine physically based shading with a raytracing renderer, as they relate to different parts of the problem of rendering a scene.

Raytracing works in some fashion that light does as it travels trough the world, by casting rays, bouncing off surfaces/passing trough them. Only that rays are cast from the eye/camera and tries to find the intersection between a surface and a light source and returns the result of the path. It's actually closer to a physical simulation than PBR techniques for games has it in its name. And to get a good quality image you need to cast a good amount of rays. Which is computational heavy. Raytracing by itself does not mean PBR though. Next to CPU you also need a lot of Ram for this.
PBR for games as is, is similar to any other traditional rendering technique. Where triangles are clipped and rasterized first and the data between vertices interpolated in each shader stage. After just rasterizing the triangles we already have the fragments to work with. The output pixel is calculated by using some PBR principles by combining Albedo, Metallic, roughness values with additional light settings( which can be precomputed/baked for static objects).The name Physical Based Rendering simply implies that it is using some principles of actual physics model. However it does not mean it actually is, as in it just borrows a few ideas but not the exact model. Many things in game render techniques come down to faking it.
Actually simulating lights bouncing off surfaces is very computationally expensive. And these new raytracting apis for gpus are just one step closer to achieving realistic visuals.
wiki article for ray tracing concept
This one is not directly on game graphics, it's still relevant

So, if i understand correctly, Raycasting is more accurate and gives better results, but is heavy on performance, while pbr is not as heavy but still gives good results?

Current PBR techniques for games are far cheaper yes, and with good artists/technical artists you can create very impressive visuals. When PBR is implemented correctly it also means that it will look the same across each game/engine. Raytracing can definitely do more realistic computations as it's closer to the physical model, but with current hardware I doubt you will see a render engine running on full raytracing. At best what we will see is a combo of the two.


text:
How can I dynamically switch between graphics APIs?
In games like the new "Doom", you have a console, from which you can use commands to reduce the game's quality or even to switch graphics API, from Opengl to Vulkan and viceversa.

How is this done? I think it reconstructs the window context based on the chosen graphics API (maybe?). How could this be implemented?

I haven't seen how Doom does it, but if you make a game reasonably organised and have separated the game logic from the graphics library, it's possible to just switch which graphics library you are pointing to. Most likely you need to re-construct the context (which would mean re-creating the window as you said) but one could theoretically handle the context themselves and only use a graphics library for the drawing part.

Thanks. The way Doom does it is through an in-game console btw

Often times the game just kills the graphics context and restarts it. Many games require you to restart the game so that graphics settings can be reinitialized.

@GabrieleVierti Does it close the window and re-open it? if not, probably they have separate code to handle the window and separate for the graphics context, but I could be wrong.

@TomTsagk Yes, apparently it closes the window and reopens it

It does more than that. There's two executables, DOOMx64.exe and DOOMx64vk.exe. I'm going to make an educated guess and assume that it simply saves the state, shuts down, starts up the alternate exe and reloads the state

A common way to approach this, assuming you actually want to (see postscript for why you may not), is to implement your game in terms of a rendering interface and simply implement that interface for all graphics API back-ends you want to support.
For example if your game is only capable of drawing colored squares:
struct IRenderer {
  virtual void Initialize() = 0;
  virtual void Shutdown() = 0;
  virtual void DrawSquare(int x, int y, const Color& color) = 0;
};

You then implement this interface for D3D and OpenGL (and anything else you want to support):
struct D3DRenderer : IRenderer { ...details... };
struct OpenGLRenderer : IRenderer { ...details... };

There's a huge spectrum of specific options you could use to do this, ranging from the direct approach to using PIMPL to hide the implementation, putting the implementation directly in the game versus shoving it off into a DLL in case the user never wants to switch, et cetera. The subject would make an interesting book.
Then, to swap at runtime, when the user issues the appropriate command, you call Shutdown() on the current renderer, initialize a new renderer and call Initialize() on it, and continue.
Rendering is a fundamental part of a game, so it's likely you will need to spend a non-trivial amount of time setting up the code to execute this handoff correctly. You're almost certainly going to have to close and re-open the underlying OS window, depending on the APIs you use, although you may be able to do some tricks there. But more importantly you're going to have to make sure every outstanding game object that has any kind of reference to some object in the rendering API gets that object swapped out with a replacement or otherwise knows how to handle this major bit of platform infrastructure being swapped out underneath it.
You can be as blunt about it as requiring the user to essentially terminate the gameplay session and restart from the main menu (this is probably the more common approach), or you can be as complex about it as trying to hot-reload everything so cleanly you preserve the precise state of everything's animation, et cetera. The latter is way harder. I'd recommend you look at techniques used for "hot reloading" general game assets to learn about the basic stuff you'd need to do there.

That said, I don't generally recommend people do this. Especially small teams or hobby developers. It takes a lot of effort, as you can hopefully see by even my rough sketch above. For that effort, you get very little payoff. It's an interesting technical achievement but the ability to hot-swap rendering systems in the middle of the game isn't usually a major selling feature.
If you are small or single-person team, I would generally recommend you support different rendering backends at compile time only, and only when necessary to get the "best" API for your supported platforms. If you're going to ship on Windows and macOS and want to support D3D12 and Metal so you can achieve optimal graphics quality and performance on each platform, great. But if you also want to include OpenGL and Vulkan on those same two platforms you've massively increased the workload for yourself and you're likely to end up with substandard implementations of everything instead of good implementations of a specifically chosen technology.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Child transform's position not updated as parent moves
I have a parent game object Object1. It has a child, which is simply an empty game object called ReferencePoint. ReferencePoint can be any arbitrary point on Object1 itself.
I have another game object Object2. It has a public field called RotationReference, of type Transform. In the inspector, the ReferencePoint on Object1 is assigned to the RotationReference field on  Object2.
As Object1 moves, I expect ReferencePoint to change its position as well. Object2 is supposed to change its rotation to face its RotationReference -- in this case, the ReferencePoint on Object1:
public override void Rotate()
{
    Vector3 relativeRotationReferencePosition =
        this.RotationReference.position - this.transform.position;

    this.transform.rotation = Quaternion.LookRotation(relativeRotationReferencePosition);
}

However, I noticed that Object2 is not rotating at all, even when Object1 is moving. When I step through the call stack multiple times, I discover that this.RotationReference.position always has the same value, even though Object1 is moving.
What am I missing here?

what language are you using

This might sound silly, but I get the feeling you've done a mistake somewhere and the empty objects do not move, when you think they are. Have you done anything to ensure that they move as expected? Like debugging it's position, or even just giving them a mesh so that you can see them while the game is running ?

If the problem is that the position itself does not change, probably it is due to some mistake in assigning a value to rotationReference. Check that you do not change its value anywhere in the code. And it is "RotationReference = ReferencePoint" not the other way round and so on.
Also I don't see why you need referencePoint on object1 and not just use Object1 itself as the target. But maybe I just don't understand what you're trying to do.

Thank you for your reply! The value is not mutated anywhere in code. The reason for using a referencePoint is complicated; but, long story short: The existing models that I have to work with (created in and imported from an external program) require some hacks for them to behave properly in the scene.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Quaternion.Lerp does not actually rotate object when called inside an "if" clause
Let's say I have a RotatableObject class, which inherits from MonoBehaviour. Here is its Start() method:
private void Start() {
    this.startingLocalRotation = this.transform.localRotation;
    this.finalLocalRotation = Quaternion.Euler(this.startingLocalRotation.eulerAngles.x, -150f, this.startingLocalRotation.eulerAngles.z);

    // Initialize other private fields
}

It has a method called Rotate(), defined as follows:
private void Rotate() {
    this.transform.localRotation = Quaternion.Lerp(this.startingLocalRotation, this.finalLocalRotation, 0.2f);
}

Given the following Update() method, the object rotates as expected:
private void Update() {
    this.Rotate();
}

However, if I make the following changes to Update(), then the object does not actually rotate, even though the Rotate() method is hit:
private void Update() {
    if (this.SomeCondition) {
        this.Rotate();
    }
}

this.SomeCondition always has the value true over multiple frames.
What is my mistake, and how can I fix it?
EDIT:
In response to this comment:

When you say "the object rotates as expected" do you mean that the
  object rotates from starting angles until final angles and then stops
  rotating (without the if) ?

Yes.

could you provide some more details about what SomeCondition is?

this.SomeCondition is determined by the state of another object, say, Puppy. E.g. if puppyInstance.Mood == Mood.Happy, then this.SomeCondition is true.

Did you try replacing the condition with the word true

No, I have not tried that. However, when stepping through the call stack in debug mode, I can see that this.SomeCondition is true and Rotate() is called -- I managed to step into the Rotate() method itself.
EDIT:
I tried the first approach described in this answer. However, it did not produce the effects that I was aiming for.
I set a breakpoint here:
transform.localRotation = Quaternion.Lerp(
   startingLocalRotation,
   finalLocalRotation,
   _rotationProgress
);

Every single time the breakpoint was hit in the Update() call, I could see that the value of _rotationProgress was steadily increasing. However, the value of transform.localRotation never actually changed -- it was always (-0.7, 0.7, 0.0, 0.0).
If I updated transform.localRotation outside of an if clause, however, that game object rotates as expected -- transform.localRotation gets updated as _rotationProgress gets updated.
EDIT:
Never mind, I am an idiot. The problem lies elsewhere in the code. The suggested approach works and I have accepted it as the answer.

When you say "the object rotates as expected" do you mean that the object rotates from starting angles until final angles and then stops rotating (without the if) ? Also could you provide some more details about what SomeCondition is? Did you try replacing the condition with the word true, did you put a Debug.Log before the Rotate to make sure the if is running properly?

@TomTsagk Thank you for your comment. I have updated my question with answers to your questions.

I have tested your code exactly, line by line, without the if, and as I expected, your object does not rotate from start to final angles, instead it keeps the rotation based on the Lerp with t=0.2f. I assume this means you tried to simplify your code and failed, so you might want to edit that.

Thank you for your comment. Do you mind explaining what you mean by "instead it keeps the rotation based on the Lerp with t=0.2f"? Additionally, the object actually does rotate when I run the code supplied in this post... I don't know why we are seeing different results. :-(

Inside function Rotate you set the localRotation to be a Lerp between the beginning and end of your angles, but for the last argument you give a constant of 0.2f which means it should return the exact same rotation everytime it runs, which becomes the rotation of your object. If your object is rotating, it means that you are running different code, or that object's parent is rotating, and as a result this one is rotating too.

@TomTsagk Thank you for your reply. What should I supply as the last argument if I would like it to rotate independently of its parent object?

You need to accumulate some progress between your start and your end. For instance...
[Tooltip("How long the rotation should take to complete, in seconds")]
public float rotationDuration = 2f;
float _rotationProgress = 0f;

private void Rotate() {
    // Accumulate rotation progress.
    _rotationProgress = Mathf.Clamp01(_rotationProgress + Time.deltaTime/rotationDuration);

    // Blend to the appropriate fraction of the way between start & final
    transform.localRotation = Quaternion.Lerp(
       startingLocalRotation,
       finalLocalRotation,
       _rotationProgress
    );
}

Or you can use the current localRotation itself as your progress measure, using an exponential ease-out style of Lerp:
[Range(0f, 1f)]
public float smoothness = 0.9f;

private void Rotate() {
    // Correct the exponential blend speed for the current framerate.
    float blend = 1f - Mathf.Pow(smoothness, Time.deltaTime * 30f);

    // Blend a small incremental step from where we are now to where we're going.
    transform.localRotation = Quaternion.Lerp(
       transform.localRotation,
       finalLocalRotation,
       blend
    );
}

Or using the RotateTowards method:
[Tooltip("Speed to rotate, in degrees per second")]
public float rotationSpeed = 180f;

private void Rotate() {
    // Rotate at a fixed speed toward the destination.
    transform.localRotation = Quaternion.RotateTowards(
       transform.localRotation,
       finalLocalRotation,
       rotationSpeed * Time.deltaTime
    );
}

Thank you for your reply! I will test this out tomorrow. I will accept your answer once I verify that it works. :-)

Hi, I tried the first approach that you described, and while I can see that _rotationProgress steadily increases, nonetheless the game object itself isn't actually rotating. When I set a breakpoint at the re-assignment of transform.localRotation, the value of _rotationProgress gets larger every time I hit the breakpoint, but transform.localRotation itself keeps staying the same.

I have updated my question to include this information.

Never mind, I am an idiot. The problem lies elsewhere in the code. The suggested approach works and I have accepted your answer.

Try multiplying the last value in the Lerp function by Time.deltaTime. I’m not by my computer to check my old scripts where I used the Lerp function, but I think I remember doing something with Time.deltaTime

This will not have the desired effect on its own, but will instead cause the object to vibrate between different fractions of the way between start & end depending on how long each frame happens to be. It won't on its own introduce memory so it can make forward progress toward the goal.


text:
Uniform arrays do not work on every GPU
I am trying to implement instanced rendering for objects that repeat, so I came up with idea I could simply group objects that loaded same model files, create array with their Model matrices and so on, and finally pass this array as uniform array to shaders, which will be indexed by gl_instanceID to get correct model matrix for given objects.
C++ implementation looks pretty much like this:
    std::vector RelativePositions, Scales;
    std::vector Models;
int ctr = 0;
bool first = true;
int isz = 0; obj->getIndices(isz);

// pDrawData->refObjects holds all Object3D instances which share same model geometry

for (std::list<IObject3D*>::iterator pObj = pDrawData->refObjects.begin(); pObj != pDrawData->refObjects.end(); pObj++) {
    IObject3D *obj = *pObj;
    int render = prepareForRender(obj, flags, isShadow, offset);
    if (!render) continue;
    if (first) {    //this is gonna be same for all objects of this class
        setUniform(Type, (int)obj->getType());
        setUniform(Flags, (int)obj->getFlags());
        first = false;
    }
    Scales.push_back(obj->getScale());
    RelativePositions.push_back(obj->getPos());
    Models.push_back(obj->getModel());
    ctr++;
}
if (ctr) {
    int Rem = 0;
    const int Step = MAX_OBJ_PER_INST;  // = 64
    for (size_t i = 0, j = Scales.size(); i < j; i+=Step) {
        Rem = Scales.size() - i;
        if (Rem > Step) Rem = Step;
        //following functions set uniform array of specified length
        setUniform(Scale, Scales.data()+i, Rem);
        setUniform(RelativePosition, RelativePositions.data()+i, Rem);
        setUniform(Model, Models.data()+i, Rem);
        glDrawElementsInstanced(GL_TRIANGLES, (GLsizei)isz, GL_UNSIGNED_INT, 0, Rem);
    }
}

Rendering object is done via Vertex Shader > Tess Control Shader > Tess Eval Shader > Geom Shader > FragmentShader.
Instance ID is being passed using flat out/in int InstanceID; from shader to shader while being once set in Vertex shader as gl_InstanceID.
Tessellation Evaluation Shader logics look like this:
    #version 430
    layout(triangles) in;

    in vec3 tcPosition[];
    in vec3 tcTexCoord[];
    in vec3 tcNormal[];
    flat in int tcInstanceID[];

    out vec3 tePosition;
    out vec3 teDistance;
    out vec3 teTexCoord;
    out vec3 teNormal;
    flat out int teInstanceID;

    #define MAX_OBJ_PER_INST 64

    uniform mat4 Model[MAX_OBJ_PER_INST];
    uniform vec3 Scale[MAX_OBJ_PER_INST];
    uniform vec3 RelativePosition[MAX_OBJ_PER_INST];

    // ... other uniforms

    void main(void)
    {
        vec3 p0 = gl_TessCoord.x * tcPosition[0];
        vec3 p1 = gl_TessCoord.y * tcPosition[1];
        vec3 p2 = gl_TessCoord.z * tcPosition[2];

        // ... other stuff ...

        teDistance = gl_TessCoord;
        tePosition = (p0 + p1 + p2);
        teInstanceID = tcInstanceID[0];

        switch(Type){
            // ... other types ...
            default:
                tePosition = (vec4(tePosition,1)* Model[teInstanceID]).xyz * Scale[teInstanceID] + RelativePosition[teInstanceID];
                break;
        }
    }

This works fine when I run it on any nVidia GPU when on laptop, but when I try to run it on AMD GPU or Intel Integrated Graphics, it suddenly doesn't work and I only get blank screen.
But if I remove uniform arrays and pass only single variable for uniform, so all instances would suddenly have same model matrix, position and scale, it works even on other GPUs, so problem is definitely with arrays...
Is there any solution to this?

"only works on NVidia" is generally an.indicator that you're doing something wrong. NVidia's GL driver is more permissive and can accept incorrect behaviour which other vendors do not. Have you tried checking for errors?

Yes, shader compiles correctly on other platforms too and I did not use any nV specific code anywhere, not even ext or some special functions

And what about errors at runtime, checking with glGetError?

Only because there is no error doesn't mean that your usage is completely to spec. I thought about memory alignment, which may be less restrictive on Nvidias side compared to others, but I haven't checked that. You should read the OpenGL spec for the functionality you are using, OpenGL implementations guarantee to support this, but are open to also support more.

You were right, I was not checking glGetError, so I set debug callback and now see that I had uniform vec3 RelativePositions[MAX_OBJ_PER_INST]; in one shader and uniform vec3 RelativePositions; in other shader. nVidia didn't have problem with this and treated second one simply as one-item array, but other GPUs have had problem with it.


text:
How to only allow user to rotate a game object clockwise?
I have a game object which can be rotated by the user:
public class RotatableObject : MonoBehaviour
{
    private void RotateAccordingTo(Hand hand)
    {
        Quaternion desiredRotation = hand.CurrentRotation;
        desiredRotation.y = 0;
        desiredRotation.z = 0;

        this.transform.localRotation = desiredRotation;
    }
}

Right now, the user is able to rotate it both counter-clockwise and clockwise.
I wish to modify the code so that the object does not rotate when the user tries to turn it counter-clockwise. It rotates only if the user is turning it clockwise.
How can I achieve this effect?

Mmmm, maybe you could make a quaternion delta, of the last rotation and the actual rotation, and there you could determine if the rotation's velocity points clockwise.

@LinkWindcrafter Thank you for your comment. Will you kindly use code to explain what you mean? Sorry for the stupid question.


text:
How make Unity wait before consuming next item in a list?
I have a class like so:
public class SomeObject : MonoBehaviour
{
    protected List<EdibleStuff> SomeItemsToConsume;

    private void StartConsuming()
    {
        this.SomeItemsToConsume
            .ForEach(item =>
            {
                StartCoroutine(Consume(item));
            });
    }

    private IEnumerator Consume(EdibleStuff edibleStuff)
    {
        yield return new WaitForSecondsRealtime(2);

        // Check whether edibleStuff is still fresh after 2 seconds
        // Figure out how to consume it -- e.g. by cooking, eating raw, whatever
    }
}

Before SomeObject consumes the next item in the SomeItemsToConsume list, I would like it to wait another short period of time, say, another 2 seconds.
I have tried these approches:

I added another yield return new WaitForSecondsRealtime(2); statement at the end of the Consume(EdibleStuff edibleStuff) method, but that did not work.
I added another co-routine, which simply contains the statement yield return new WaitForSecondsRealtime(2); in its definition, at the end of the ForEach loop, but that did not work either.

How can I achieve the effect I want?

You could put the ForEach inside the coroutine:
public class SomeObject : MonoBehaviour
{
    protected List<EdibleStuff> SomeItemsToConsume;

    private IEnumerator Consume()
    {
        this.SomeItemsToConsume
        .ForEach(item =>
        {
            WaitForSecondsRealtime wait = new WaitForSecondsRealtime(2);

            /// Process your item...

            yield return wait;
        });
    }
}

Since what it was done in your StartConsuming method was that in your loop a 'n' number of coroutines (being 'n' the count of your list) were being started at the same frame. Having it inside a coroutine makes sure that the List moves to the next element once the WaitForSecondsRealTime's keepWaiting property returns true, which is not on the same frame (even if the time passed were 0).
Hope it helps.

Thank you for your reply! Unfortunately, I do not have access to my repository until next week. Once I verify that your answer works, I will mark it as accepted.


text:
How can I achieve a 'warm' scene in Unity using post processing effects?
I've recently fallen inlove with this Cozy Tavern scene by Beholder, and am looking to replicate it's feel the best I can in unity as a learning exercise.
A lot of the scene's depth is added through lighting, and post processing effects. The lighting is simple enough to where I think I can reasonably replicate it with some trial/error using different lights, however the post-processing is where I get a bit lost.
It's clear that there are a few different effects going on, one of which being the increase in saturation, and a limited depth of field.
My guess is that I would need to write a few different shaders (or rather one?) to add these effects? Any input as to how I could achieve similar results would be greatly appreciated.

No Post Processing:

With Post Processing:

Looking at the image I spot colour grading, depth of field, and bloom effects, and maybe a subtle vignette, all of which are supported by the standard Unity post-processing stack, so you might not need to write new shaders at all. Have you tried playing with this asset?

Relatively new to Unity, so I didn't even know Unity had a standard stack, I will definitely have a look - thank you!


text:
Is there a way to duplicate the windows desktop zooming in SDL to make low res pixels look like stylyzed cartoon art?
When you hit the Win key and numpad plus key at the same time it opens the desktop magnifying glass and the effect of this on low res pixel art is to make it look like super cool stylized cartoon art. I want the game to look like this all the time. Is there a way to do this permanent i SDL or DirectX or OpenGL?
How I have achieved this image is to run the game in a small windows and have the windows 10 magnifying glass hoover over it and I hit print screen. And I want the game to look like this all the time in full screen.

Ps. This is the Gradius 3 ship that I use for place holder graphics for question asking purposes.

Look up pixel art scaling algorithms.

You could achieve this by using a viewport: https://wiki.libsdl.org/SDL_RenderSetViewport
You define a rectangle somewhere in your scene which will then fill the window. You can update where the rectangle is as your player moves around.

This will zoom the picture, yes. But without the fancy upscaling algorithm OP asked about.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Art Guide Theory: Lighting an Game Environment (Objectives, approach/workflow and mood) in PBR
What's the theory behind the Lighting an Game Environment in a Physically Based Renderer?
As far my research, lighting an scene is done with different Rules and Different Ways of Lighting an Scene depending upon the scene.
For an Interior scene - Omni Lights, Area Lights, point Lights and Spot Lights with baking is used to give proper amount of illumination.

whereas for an Outdoor Scene - Directional Lights, Area Lights, Point Lights are used to illuminate the scene with baking Lightmaps.

Usually to Light Individual Objects, 3 point Lighting is used and colors signify the Mood of the Scene.

But, the 3 point lighting is unfavorable for Game Environment, So, what's the Good way to start and what are the main objectives in Lighting an Scene?
How Lighting an Scene Contributes to the mood of the scene? like here -

Lights in Game Render by Game Engine, e.g. Unreal Engine, SnowDrop Game Engine and more.A Game World is as huge as a Big Land included many 3D Assets. Here's PBR study for game. And, Peachpit, Lighting Principle in Game Design. Retrieved on http://www.peachpit.com/articles/article.aspx?p=174370
3 Point Light is rarely seen in Game... Because 3 Point Light called "Studio Light", where can be seen in Photography Studio when a Photographer want to shoot a Fashion, Portrait, Product Photography.
What makes Game Environment different...Theory of Game Design: Because of the Game Mechanics, Game Design (Rules), Level Design and more.Game Lighting Technique in Game Design is used to Direct & Attract Players' Eyes about: Where is the Game Objective, Mission, Quest will be on. Where is the direction on Next Level will be. So, at the end, the Lighting of Game Environment is different than 3-Point Light. The Game Environment will included both Indoor and Outdoor. These Lighting Technique completely been controlled by Level Design matched "game objective, features, Game Mechanics, Game Art-styles, game Flow, levels, and more" at Pre-Production until Production Process. For example, Kratos in God of War 3, he saw a Sun Light surrounding a Treasure (Light direct Player's eyes look at the point). Plural Sight. Lighting for Games. Retrived from https://www.pluralsight.com/blog/film-games/understanding-the-importance-of-lighting-for-games

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Can I give a player money for completing my game?
As it says in the title, can I give a player that completes my game (which might be hard to complete) money?

Is this a question about law? If yes, it is probably best asked here: https://law.stackexchange.com/

if the player has to spend money to play the game (to purchase a copy/subscription, or microtransactions to get ahead) to have a shot at the prize, then gambling laws may apply. These vary from one jurisdiction to another and can influence what mechanics you can use, how you can promote it, who is allowed to participate in the contest, etc.

Yes you can; nothing is stopping you from giving other people your money. The question is do you want to?
This reminds me of the "aardwolf" secret in Wolfenstein 3D. The game was released with a secret message, "Call Apogee and say Aardwolf". This was planned as a contest; the first player to follow those instructions would win a prize. However Apogee (the publisher) backed out after realising that with the release of cheat programs and game editors, the prize would probably be won via illegitimate means.
That was 1991; now with the Internet, free game guides, Let's Plays, anyone can easily finish any game if they had the slightest motivation. This would defeat the purpose of offering a cash prize, which is presumably to encourage people to complete your game via actually playing it.
Instead, consider offering a token that has no monetary cost to you, like an achievement.

To add to that, maybe OP can offer money to the first 5 that finish the game, motivating people to start playing it, and once it becomes well known enough to have guides and cheats, there would be no price anymore.


text:
Pong AI - Raycasting
I've been focusing on other games recently but it annoyed me that I skipped the AI part of making my pong game a 1 player game too. I have found out how to RayCast but am struggling with being able to make a path to predict where the ball will end up on the computer side. I have managed to get the first ray to work but in the second if-statement from the code below, it's somehow a loop. If anyone is able to help me, I would be extremely grateful!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RaycastTest : MonoBehaviour {

private Rigidbody2D rb2d;
private RaycastHit2D hit;
private Vector2 predictedCollision;
private Vector2 collisionPoint;
private int numberOfCollisions;

void Start () {
    rb2d = GetComponent<Rigidbody2D> ();
    numberOfCollisions = 0;
}

void FixedUpdate () {
    //Directions of the ball (normalized)
    Vector3 forward3 = new Vector3 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y, 0) * 20;
    Vector2 forward2 = new Vector2 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y);

    // If the ball has just hit the player paddle
    if (BallMovement.isOnPath == true) {
        if (numberOfCollisions == 0) {
            //make sure we have the correct initial collision point from another script
            collisionPoint = BallMovement.collisionPoint;

            //draw and cast a ray to detect the next point of collision
            Debug.DrawRay (collisionPoint, forward3, Color.red, 20f);
            hit = Physics2D.Raycast (collisionPoint, forward2, Mathf.Infinity);
            //print the name of the object that has been hit
            print (hit.collider.name);

            //change the initial collision point to the new one
            collisionPoint = new Vector2 (hit.point.x, hit.point.y);
            print (collisionPoint);

            //add on to the number of collisions
            numberOfCollisions += 1;
            print (numberOfCollisions);
        }

        //if we still haven't reached the HitArea we need to do another bounce
        if (hit.collider.name != "HitArea") {

            //make sure we get the velocity after impact and reverse the direction of the y velocity.
            forward2 = new Vector2(rb2d.velocity.normalized.x, rb2d.velocity.normalized.y * -1f);
            forward3 = new Vector3 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y * -1f, 0) * 20;

            //draw and cast a ray to detect the next point of collision
            hit = Physics2D.Raycast(collisionPoint, forward2, Mathf.Infinity);
            Debug.DrawRay(collisionPoint, forward3, Color.red, 20f);

            //change the initial collision point to the new one
            collisionPoint = hit.point;
            print (collisionPoint);

            //add on to the number of collisions
            numberOfCollisions += 1;
        }

        //If we've hit the HitArea, we reset everything so it stops looping and we've got our predicted point of collision on the computer side.
        if (hit.collider.name == "HitArea") {
            predictedCollision = hit.point;
            numberOfCollisions = 0;
            BallMovement.isOnPath = false;
        }
    }
}

}

The loop isn't in this code (it's in the caller to this code); but I think I know what's causing it:
    //if we still haven't reached the HitArea we need to do another bounce
    if (hit.collider.name != "HitArea") {

This assumes that you WILL find a HitArea. This means the calling code will then call this function again and raycast again.
Were I to guess at why, you are probably allowing yourself no buffer between HitArea and your hit detection, so a bounce happens in an area that a bounce is not supposed to occur. This is likely an issue with your hit detection code, but could be fixed by shrinking your "hit area" to have a buffer around the edge so that when the edge of your pong-ball hits the edge of the screen it counts, rather than the middle.
Without more code it is not possible to definitively point to the root cause of the bug; but the loop your seeing IS because you're not colliding with "HitArea" for some reason.

Ok, awesome, thanks for the help. I'll try this tomorrow :)

If your ball is travelling straight towards its path, then you could do a delta of positions, or if it has a Rigidbody you could use it's velocity vector.

In both cases, you will get a vector that points to the current direction your ball is facing relative to the world space. You could then make a raycast from that velocity vector, so the hit point will be it's final destination with that velocity vector.
Example:
using UnityEngine;

public class ExampleBall : MonoBehaviour
{
    public Vector3 predictionPoint;
    private Vector3 latePosition;
    private Rigidbody rigidbody;

    void Awake()
    {
        rigidbody = GetComponent<Rigidbody>();
        latePosition = transform.position;
    }

    void Update()
    {
        /// With Velocity
        RaycastHit hit;
        if(Physics.Raycast(transform.position, rigidbody.velocity, out hit, Mathf.Infinity))
        {
            predictionPoint = hit.point;
        }

        /// With delta positions
        Vector3 delta = transform.position - latePosition;

        if(Physics.Raycast(transform.position, delta, out hit, Mathf.Infinity))
        {
            predictionPoint = hit.point;
        }

        latePosition = transformPosition;
    }
}

The script's predictionPoint is public, so you can access it, maybe it's expensive to make raycasts each frame, but it was for the sake of example.
You can also use extrapolations, considering your velocity vector, (LerpUnclamped does the trick). Example:
using UnityEngine;

public class ExampleBall : MonoBehaviour
{
    public Vector3 predictionPoint;
    public float pedictionTime;
    private Vector3 latePosition;
    private Rigidbody rigidbody;

    void Awake()
    {
        rigidbody = GetComponent<Rigidbody>();
        Vector3 delta = transform.position - latePosition;
    }

    void Update()
    {
        /// With Velocity
        predictionPoint = Vector3.LerpUnclamped(transform.position, transform.position + rigidbody.velocity, predictionTime);

        /// With delta positions
        Vector3 delta = transform.position - latePosition;
        predictionPoint = Vector3.LerpUnclamped(transform.position, transform.position + delta, predictionTime);

        latePosition = transformPosition;
    }
}

Hope it helps.

Thanks for the help. I'll definitely have a look at these tomorrow. :) It's just so nice to have a fresh perspective on something when you're staring at it - wondering what's wrong. Thanks again!


text:
Import 3D model into Unreal Engine 4
(Sorry if I misunderstood the context of what I want, I'm currently noob in game development).
I want to retrieve a 3D model from let's say Saints Row 3, and import it to Unreal Engine 4, is it possible ? If not is there a way to create it from scratch ?
What is the right way to achieve what I want ?

Can you explain what you want to do with this model? And is there a reason you're not able to use your own 3D model, a free asset, or one you've purchased for this purpose?

I simply want to use that imported character as an NPC or playable character in third-person view. Create my own 3D model would be great, but my fear is that I won't be able to create that 3D model's face exactly like the character from existing game. The point is it's extremely important for me to create an exact copy of my existing character, and I'm guessing that it might be impossible !

It's not impossible, but depending on your application it may be a breach of copyright. The creators of the original game put a lot of work into crafting that character and its model, and that creative work is theirs. For many applications, you'd need their express permission to use that character in your own project. Because of this, you might find game developers are reluctant to answer this question with anything other than "ask the creator for permission" — we don't want folks just taking our work or that of our colleagues in the industry, so we might not be inclined to make it easy. ;)

Oh thats interesting, but I have to mention that my character from existing game was created via In-Game's character customization system, so in fact my character is unique and custom (more or less) is it still impact on the copyright ? And if you dont mind I have another question to ask, is it still possible to create exact copy of the face of my character in let's say Autodesk Maya ? (For private and non-commercial usage of course)

The choice of parameters may be yours, but the mesh and textures are still another person's intellectual property, not your own.

Now I got it, importing is not an option at all. Im gonna create it from scratch, thank you !

Extracting assets from other games is not impossible, but you may find that game developers are reluctant to tell you how or make it easy for you.
That's because even if you've purchased a copy of a game and customized your own character, the underlying mesh and texture data that character uses are the products of other peoples' artistic and technical labour.
Legally, the copyright or licensing rights for those assets are owned by the creators or their studio/publisher (depending on the details of the agreements involved)
So, if we tell you how to extract this data, we're potentially making it easy for less scrupulous visitors to this site to steal content that belongs to us and our fellow developers.
There may be reasons to use this data that are protected under "Fair Use," but we can't guarantee that anything we write here will be used only in this way.
I'd recommend checking into game modding forums if you'd like to explore this further, with a caution to please use your powers only for good. :)


text:
Why is my AABB vs AABB code returning false positives
I am trying to do AABB vs AABB collision and the code is never finding a collision.
    private static boolean checkFullCollision(Entity entity, Entity entity1) {
    float[] amin = entity.getMin();
    float[] amax = entity.getMax();

    float[] bmin = entity1.getMin();
    float[] bmax = entity1.getMax();
    return  (amin[0] <= bmax[0] && amax[0] >= bmin[0]) &&
            (amin[1] <= bmax[1] && amax[1] >= bmin[1]) &&
            (amin[2] <= bmax[2] && amax[2] >= bmin[2]);
}

where I calculate my min and max.
    public float[] getMax() {
    final float[] max = new float[3];
    max[0] = position.x + this.max.x;
    max[1] = position.y + this.max.y;
    max[2] = position.z + this.max.z;
    //System.out.println(position);
    return max;
}

public float[] getMin() {
    final float[] min = new float[3];
    min[0] = position.x - this.min.x;
    min[1] = position.y - this.min.y;
    min[2] = position.z - this.min.z;
    return min;
}

Can someone help me please.
Thanks in advance

What do you mean by "not working"?

I figured out the answer.
For people trying to implement an aabb vs aabb collision here is the code.
private static boolean checkFullCollision(Entity entity, Entity id1) {
// VERY INPORTANY. The max and min are centered at the origin(0,0) and not at the entities posititon.

     Vector3f aextents = Vector3f.sub(entity.getModel().getMax(), entity.getModel().getMin(), null);
   Vector3f bextents = Vector3f.sub(entity.getModel().getMax(), entity.getModel().getMin(), null);

   boolean x = (abs(entity.getPosition().x - id1.getPosition().x) <= aextents.x + bextents.x);
   boolean y = (abs(entity.getPosition().y - id1.getPosition().y) <= aextents.y + bextents.y);
   boolean z = (abs(entity.getPosition().z - id1.getPosition().z) <= aextents.z + bextents.z);
   return x && y && z;
}

@AlexandreVaillancourt I will

@AlexandreVaillancourt see my other question


text:
How to get a reflex edge on a non-convex mesh
I am trying to implement a convex decomposition and I need to find the convex vertex on a mesh. Is there a algorithm that I can use to find the convex vertex on a mesh.

If you want to draw attention, I recommend editing the question to include more information about what you've researched and tried so far. For example, just doing a Google search for "find concave edges of mesh" turns up several descriptions of how to do this on the front page. Have you tried following these steps? If so, where did you get stuck, and what can we help explain or solve?

Here is some code that I used.
private static boolean isReflex(Vector3f p0, Vector3f p, Vector3f p1) {
    // TODO Auto-generated method stub
    return right(p1,p0,p);
}

private static boolean right(Vector3f a, Vector3f b, Vector3f p) {
    return Segment.getLocation(p,a,b) < 0;
}

public static float getLocation(Vector3f point, Vector3f linePoint1, Vector3f linePoint2) {
    Vector3f l = Vector3f.add(linePoint2, linePoint1, null);
    Vector3f p = Vector3f.sub(point, linePoint1, null);

    return Vector3f.angle(l, p);
}


text:
CreateGraphicsPipelineState
Hi!
Would someone answer my question, please?
Does the title's method create the same components always or verify possible duplicates?
For exaple:
I have one D3D12_INPUT_LAYOUT_DESC struct and two shaders need the same IL.
How many ILs will it create? (In the D3D11 one was enough).
Is it possible to avoid duplicates?
I highly appreciate the answer.

In DX12, you will be creating one input layout per pipeline state. This is preferable, because the driver will have all the knowledge of the shaders and input layout and it can do several optimizations with them, like inlining the vertex fetch inside the vertex shader. It can result in reduced latency when fetching a vertex buffer. Also, it can reduce traffic between VS-PS stage by omitting unused registers. And there are possibly many more opportunities to optimize. However, in your application you can share the input layout description with multiple PSOs.
Also note, that in DX11, indeed you could share input layouts between shaders and reuse one on the API side. But here the driver is deferring shader compilation until you actually use a shader and internally it can be creating multiple shader-input layout permutations behind the scenes. This can result in stuttering when the CPU can't keep up, so it is preferable to precompile these a'la DX12.


text:
Swapping in game currency for virtual goods. Client vs server. Best practice
I currently use a server back end to verify my managed in app currency purchases and update the user's coin value.
But what's the best practice to then deal with "in game purchases" where players swap their coin for virtual goods such as power ups etc.
I just realised that if I do it in the app then potentially a hacker could just remove the code so that they can buy some coins once then just perpetually buy whatever virtual goods they want.
Should I let my server back end deal with this instead, which would definitely solve the problem. Is this the best practice?

"If I do it in the app then potentially a hacker could just remove the code so that they can buy some coins once then just perpetually buy whatever virtual goods they want." Yes, that's right. If that's a situation you care about, then it sounds like you have your answer: everything you do on the client can be hacked. What do you need from us?

@DMGregory Best practices. As this stuff is new to me I wasn't sure if there was some other away of achieving the same thing via the Google API's in the client alone.

If the hacker can hack your code, can't they hack Google's too?

@DMGregory I dunno, that's why I'm asking. I thought Google might be quite sophisticated, or at least one would hope so ! I guess you're right. I've just been thinking that no matter how much security I might want to include, ultimately a hacker could just get my app to add 1000 of each power up if they wish regardless of if I deal with the powers ups on the server or not. So is there any point spending time writing the extra server code? Perhaps, weighing things up, I might as well just deal with the power ups on the client. I suppose the assumption is that most people aren't hackers.

It depends — can the powerups owned by one player affect other players or shared channels like leaderboards? If so, you'll want your server to ensure player B's can't be impacted by player A's hacking. You can't save player A from themselves, but you can limit them from getting a leg up on non-cheating players.

@DMGregory yeah that's true. Thanks for the chat it has been helpful.

I would prefer you to have the code executed on the server side. Then it would be less likely to be hacked.

I've just implemented server side virtual goods / in game currency exchange. It feels much nicer just separating the code from the client game application. And I have the comfort of knowing any potential hackers are more limited in what they can now do.

Well, if you were to use a pre-compiled language, you have even better security against hackers.

good point. Maybe a C++ conversion is on the cards !


text:
How do I test for collisions between two concave shapes decomposed into collections of convex polyhedra?
I am using convex decomposition with SAT (separating axis theorem) and I generate two arrays of convex pieces, How do I submit my arrays to my collision detection method which only takes two arguments.
public MTV testCollision(BroadPhasePair pair) {
    Entity entity = pair.getBody();
    Entity id1 = pair.getBody();

    List<Convex> entityConvex = ConvexDecomposer.decompose(entity);
    List<Convex> id1Convex = ConvexDecomposer.decompose(id1);
    return null;
}

private MTV testCollision(Convex body,Convex id1) {
    float overlap = Float.MAX_VALUE;
    Vector3f smallest = null;
    Vector3f[] axis1 = body.getAxis();
    Vector3f[] axis2 = id1.getAxis();

    for(Vector3f axis : axis1) {
        Projection p1 = body.project(axis);
        Projection p2 = id1.project(axis);

        if(!p1.overlapps(p2)) return null;
            float o = p1.getOverlap(p2);
            if(o < overlap) {
                overlap = o;
                smallest = axis;

        }
    }

    for(Vector3f axis : axis2) {
        Projection p1 = body.project(axis);
        Projection p2 = id1.project(axis);

        if(!p1.overlapps(p2)) {
            return null;
        }else {
            float o = p1.getOverlap(p2);
            if(o < overlap) {
                overlap = o;
                smallest = axis;
            }
        }
    }

    MTV mtv = new MTV(smallest, overlap);
    return null;

}

I want to be able to somehow submit my array into the testCollision method.

Note that you'll want to do your decomposition step once, up-front, at bake time or load time, and cache the resulting array for re-use. If you do it inside the test collision method every time you want to check for collisions, you'll end up performing a lot of redundant work.

@DMGregory so when I create the entities decompose the meshes then. This could could solve a lot of problems I've been having.

You just need to take every part of one body and check them against every part of the other body. Then you'll have a list of MTVs, which you need to get the smallest of the same way you do it in the SAT function (the one with the smallest overlap is the one you need)

but if you had more parts in one body than in another what then would you do.

@TheMaskedRebel As I said "you just need to take every part of one body and check them against every part of the other body". That's body parts in the first time body parts in the second amount of checks

Here is some code to help people who get stuck like me.
public MTV testCollision(BroadPhasePair pair) {
    Entity entity = pair.getBody();
    Entity id1 = pair.getBody();

    List<Convex> entityConvex = entity.getConvexes();
    List<Convex> id1Convex = id1.getConvexes();
    MTV mtv = null;
    float overlap = Float.MAX_VALUE;

    for(int i = 0; i< entityConvex.size();i++) {

        for(int j = 0;j < id1Convex.size();j++) {
            Convex convex = entityConvex.get(i);
            Convex convex2 = id1Convex.get(j);

            MTV temp = testCollision(convex, convex2);

            if(temp != null) {
                if(temp.getOverlap() < overlap) {
                    mtv = temp;
                    overlap = temp.getOverlap();
                }
            }
        }
    }
    return mtv;
}

private MTV testCollision(Convex body,Convex id1) {
    float overlap = Float.MAX_VALUE;
    Vector3f smallest = null;
    Vector3f[] axis1 = body.getAxis();
    Vector3f[] axis2 = id1.getAxis();

    for(Vector3f axis : axis1) {
        Projection p1 = body.project(axis);
        Projection p2 = id1.project(axis);

        if(!p1.overlapps(p2)) return null;
            float o = p1.getOverlap(p2);
            if(o < overlap) {
                overlap = o;
                smallest = axis;

        }
    }

    for(Vector3f axis : axis2) {
        Projection p1 = body.project(axis);
        Projection p2 = id1.project(axis);

        if(!p1.overlapps(p2)) {
            return null;
        }else {
            float o = p1.getOverlap(p2);
            if(p1.contains(p2) || p2.contains(p1)) {
                float min = abs(p1.getMin() - p2.getMin());
                float max = abs(p1.getMax() - p2.getMax());

                if(min < max) {
                    o += min;
                }else {
                    o += max;
                }
            }

            if(o < overlap) {
                overlap = o;
                smallest = axis;
            }

        }
    }

    MTV mtv = new MTV(smallest, overlap);
    return mtv;

}


text:
How do I split my screen to include a JFrame and a lwjgl screen
I a making a game and I'm going to make a little side GUI to create game items.
How can I have a window both include a Canvas element and an lwjgl window.

You can use the AWTGLCanvas to host your LWJGL context inside your GUI.
For LWJGL3, There's this demo of putting a LWJGL context in a canvas in the source: https://github.com/LWJGL/lwjgl3/blob/master/modules/samples/src/test/java/org/lwjgl/demo/system/jawt/JAWTDemo.java

+1 thanks but can I use the java canvas method with lwjgl.

this is a Java canvas with LWJGL.


text:
How do I get an aabb's collision normal
I have two aabbs and I need to know the collision normal of the to help me slide the aabbs across themselves. I have searched google but nothing really came up.
How do I get the collision normal of two aabbs colliding together

Just so you know, the MTV isn't always the best thing to use when dealing with collisions. It might give you directions that completely differ from how it would've reacted, especiall, at corners.

Translation just means adding / subtracting from a position. Have you tried adding the MTV to your position? Did that give different results than what you wanted? If so, tell us about those results and how they differ from what you want.


text:
What is the general architecture of a server for a game like rust/minecraft?
If a game's client is written in Unity or UE4 or another engine, is the server usually written in the same engine? Or is it written in standalone c++?
Does the server use a database like MySQL to store the locations of deployed structures and bases etc? Or is everything stored in memory in arrays or in another way?

As Philipp mentions below, different games make different decisions. If you can tell us more about your game project specifically, we can help you meet your game's particular needs within your working situation. What have you tried so far, and where are you stuck or finding trouble?

There is no one solution. It depends on the requirements of your game.
Some game engines offer server components, but I have seen games where the dev team decided that these do not fulfill their requirements, so they wrote their own and communicate with it using the low-level networking features of their engine. Note that client and server don't necessarily need to use the same programming language. My last multiplayer game used a client written in JavaScript (HTML5) and a server written in Java.
Regarding storage: When your game is played in rounds of a few minutes each, you can often do without any persistence on the gameserver and keep everything in memory. But if your game has a persistent game world, you want some form of data storage on hard drive so you can resume the game when the server needs to shut down (or crashes). I have once worked on a game where the gameserver handled a small persistent world using flatfiles. It didn't work well, but it worked. But if you have a large number of players, you want to store any information about offline players in a proper database to allow faster login times and ensure data consistency.


text:
Removing duplicate vertices on a mesh
I have a set of vertices and another set of indices. Sometimes I find that I have duplicate vertices in my mesh.
I tried at first to check if two identical vertices were in the array of vertices but that didn't work because I remembered that more that if one vertex  represents multiple edges then the vertex would be validly represented as multiple vertices in the vertices array.
Then I remembered that the indices help represent how the vertices are structured but I didn't know how to use them. So I came here to ask how to use them to detect duplicate vertices in a mesh.

Let us continue this discussion in chat.

"if one vertex represents multiple edges then the vertex would be validly represented as multiple vertices in the vertices array." This is not true. That's the job of the indices array. A unique vertex (including all attributes like normals/UVs/colours/etc, if used) that occurs in multiple triangles should still occur exactly once in the vertices array. It will just be referenced multiple times by the indices array. Multiple identical vertex entries in the vertices array is exactly the error that the answer below solves. If these dupes were correct as-is, we wouldn't need to fix anything.

First you'll need a lookup structure to look up vertices you've processed so far. This could be, for example, a dictionary keyed on the position of your vertices, or an octree/k-d tree/etc. Each entry will hold the updated index of the de-duplicated vertex at that position.
(If you're using this for display meshes, you'll want to count vertices with different normals/UVs as distinct, but if I recall correctly you're working on collision meshes so we can ignore this detail and treat vertices as pure positions)
Next you'll need a re-indexing list the same size as your initial list of vertex positions. This will hold the new index of each vertex after de-duplication.
Initialize a vertex count to zero. Iterate over your list of vertices, checking to see if each position (or one within a small rounding tolerance) is already in your lookup collection.

If there's no vertex recorded yet at that point, set the current vertex's new index to your current vertex count, and increment that count. Write this vertex and its new index into your lookup structure.
If you already have a vertex recorded at that point, set the current vertex's index to that recorded index and do not increment the vertex count.

Either way, write the new index you've chosen for this vertex into the re-indexing list.
At the end, or as you go, you can build your new vertex list, using only the first vertex with each new index.
Then you need to update your index list. For each entry in the list, replace it with the corresponding new index looked from your re-indexing list. ie. indices[i] = reindex[indices[i]];
Lastly, check to see whether any triangles have become degenerate (two or three indices all pointing to the same vertex) - if so, you can delete that whole triangle. (Swapping 3 indices from the end of the list, or moving the rest of the indices back 3 spaces to fill the gap)


text:
How can I convert my list of vertices and indices to a list of triangles?
I have a full 3D collision mesh that is represented by a list of vertices and another list of indices. I need to convert the list of vertices and the list of indices into a set of triangles.
First I tried to group every three vertices from the vertex list into a triangle, so vertices 0-2 were triangle 0, vertices 3-5 were triangle 1, etc. But that method did not produce the same triangles I see on the original mesh.
Then I remembered the indices list, but I didn't know how to use them. So I came here to ask: how can I use the indices list to make my list of triangles?

@DMGregory Is my latest edit useful

Yes, you're finally at least mentioning what you've tried and what it is about the problem that you didn't understand. That lets users figure out what kind of help you need. Next time, start with that. ;)

Typically, your list of indices looks like this:
[ 1st vertex index of triangle 0,
  2nd vertex index of triangle 0,
  3rd vertex index of triangle 0,

  1st vertex index of triangle 1,
  2nd vertex index of triangle 1,
  3rd vertex index of triangle 1,

  1st vertex index of triangle 2,
  ...etc
]

So the three vertices of triangle i are:

vertices[indices[3 * i]]
vertices[indices[3 * i + 1]]
vertices[indices[3 * i + 2]]

Here is what worked for me. Hope it helps someone else:
List<Triangle> triangles = new ArrayList<>();

    for(int i = 0;i * 3 < indices.length;i++) {
        Triangle triangle = null;

        Vertex p = new Vertex(vertices.get(indices[3 * i]));
        Vertex p1 = new Vertex(vertices.get(indices[3 * i + 1]));
        Vertex p2 = new Vertex(vertices.get(indices[3 * i + 2]));

        triangle = new Triangle(p,p1,p2);

        triangles.add(triangle);
    }

You'll want your for loop to run over the indices, not the vertices. In general, each vertex could participate in many triangles, so you might have more triangles than vertices. Your for loop should look something like for(int i = 0; i*3 < indices.size(), i++)

@DMGregory like this


text:
Getting the winding order of a mesh
I'm doing some topological operations on my mesh and I need to know the winding order for my mesh.
Since I will be importing models from different sources I will need to know whether the winding order is clockwise and anti-clockwise so I can get normals and things like that.
Question : Is there a way that I can determine the winding order of a list of vertices.
Edit 1: I am using a 3D mesh

Safe to assume this is in 3D? In 2D, we can assume that the side facing out of the screen is the front, and compute the winding order that way. In 3D, we need some additional information to know which side of the polygon is supposed to be the front (since a polygon that's wound clockwise when you look at it in one direction is wound counter-clockwise if you look at it from the opposite side). What's your source of ground truth for determining which side is "out"?

You don't need to know the winding order to get the normal. A simple cross product of the vertices already takes that into account.

@Bálint true, but there are two normals to a polygon in 3D: one pointing "out" and one pointing "in" — we usually use knowledge of the winding order to compute the outward-pointing normal. If the mesh might be wound either way then we'll need some other piece of information to tell us which side faces out.

@DMGregory is there anything else i need to add to ensure I get an answer

I asked above what information you have to distinguish the front/outside face of a polygon from the back/inside face, if you don't know its winding order in advance. Meshes can, in the most general/worst case, be a disorganized polygon soup without an interior volume, so we'll need some clues to work from to figure out which side is supposed to be the front. If you have any information at all about what kinds of meshes and shapes you're working with, that helps narrow the uncertainty.

@DMGregory  I'm working with 3D meshes such as trees and palms and small rocks and I store my info in triangles which you can see here.

You can't. Consult with the documentation of whatever software/format you are using to find out the winding order.

There is no way to automatically infer the winding order of a 3D mesh that will work for every possible input.
For instance, if I give you the triangle (0, 0, 0), (1, 0, 0), (0, 1, 0) alone with no other context, you don't know whether it's meant to be wound counter-clockwise (so its front faces out along the z- axis) or clockwise (so its front faces out along the z+ axis). (Assuming a left-handed coordinate system, but the coordinate system could just as well be right-handed, flipping the whole thing)
Both of these would be valid interpretations, and you'd need to ask the creator or use some knowledge about the mesh's format or what it's meant to represent to sort out which version is intended.
But there is a common special case where we can infer the correct facing with higher confidence: if your meshes represent solid objects and you have watertight manifold geometry. (This means that the mesh makes a continuous surface with no holes, gaps, loose edges, or single-sided fins)
If you have such a mesh, you can guess at its winding, then check whether that guess makes sense by seeing if it puts the front face of each polygon facing "out" of the solid rather than inside. (But note: there are rare cases where we make meshes that have been deliberately turned inside-out for various effects, so even this test isn't foolproof!)
It proceeds like this:

Pick a triangle/polygon arbitrarily
Construct that polygon's normal according to your guessed winding
Cast a ray through a point in that polygon, in the direction opposite its normal. Test this ray against every other polygon in the mesh (this can get expensive)

If you get an odd number of hits (hitting the back of another polygon, then possibly the front of another then the back of another, or any number of front-back pairs), then your winding guess looks correct. This is the pattern we'd expect to see when firing into a solid shape.
If you get an even number of hits, then your winding guess was probably incorrect, and you should use the opposite winding instead.

You can run this test for several different sample polygons in your mesh to build up consensus, and try to weed-out outliers due to non-manifold geometry like single-sided leaf fins.
As you can see though, it's a lot more work, and has fewer guarantees, than just inspecting your geometry source format to determine what winding is standard for that type, or asking whoever made the mesh.

(I originally skipped this case because you said you wanted to generate normals, and didn't mention that you had them available as input. But for completeness...)
If your mesh has normal vectors, then you can use these as the ground truth for the intended front facing direction (provided the creator of the model isn't doing anything too weird with manually-adjusted normals...)
Say you have a triangle with points (in order) a, b, c
Compute the expected normal of your triangle by taking the cross product:
 expectedNormal = Vector3.Cross(b - a, c - b);

Now compare that against the normals that came with your mesh (if your mesh has normals defined per vertex, you can average the three vertex normals for a triangle to get a triangle normal. Or you can average all the expectedNormal values for triangles bordering a given vertex to get a vertex normal instead)
agreement = Vector3.Dot(expectedNormal, sourceMeshNormal);

If agreement > 0 then your mesh is wound counter-clockwise when looking at it against its normal in a right-handed coordinate system, or clockwise if you're in a left-handed coordinate system. If agreement < 0 then your mesh is wound clockwise in a right-handed coordinate system, or counter-clockwise if you're in a left-handed coordinate system. If agreement is zero then the test is inconclusive for this triangle (someone's cranked the input normals to be near-zero or near-parallel to the surface for some reason), and you can try again with a different part of the mesh.

Let us continue this discussion in chat.

First you compute any consistent vertex ordering of the triangles (or polygons), i.e. an ordering that is consistent across neighboring faces (if no such ordering exists, the mesh is not a solid, or 2-manifold).
After that order the vertices along an arbitrary axis (let’s say the x-axis). The outward-pointing vertex normals for the vertex with minimum x-value, must have a negative x-coordinate. Compute the face normals for each adjacent face and chose the orientation such that their x-coordinate is negative. If your initial ordering was consistent, you can easily flip the entire ordering, according to these face normal orientations


text:
Finding the contact point of two spheres
Is there a way to get the normal and depth of two spheres that have collided.
I know that it is something to do with the center and radius of two spheres but I am not sure what

Downvoter, can you please explain why you downvoted. Feedback will be appreciated so I can modify the post.

This is probably the simplest 3D collision check.
Distance between sphere centers is length(c1.center - c2.center)
Depth is distance - radius1 - radius2 = length(c1.center - c2.center) - c1.radius - c2.radius
Normal is normalized(c1.center - c2.center) for c2 and the inverse of that for c1.

It may be worth mentioning that the point of contact on the surface of the sphere is c1.center - normal * c1.radius / c2.center + normal * c2.radius). If the spheres just touch without penetrating, then these two surface contact points will be the same.


text:
How can I generate the smallest enclosing sphere from a mesh?
I have a polygon which is defined by a set of vertices and I need the smallest sphere encompassing the mesh.
The spheres are defined by a position vector (x,y,z) and a radius.
Is there an algorithm that given a solid collision mesh with no holes generates the smallest sphere that encompasses a solid collision mesh with no holes in all cases

This is not a duplicate of this question because the question is only about a sphere encompassing a polygon soup a. I'm asking if there is an algorithm that given any solid collision mesh with no holes generates the smallest sphere that encompasses a solid collision mesh in all cases.

What have you tried? How did the solutions/research you did before hand not suffice?

@Tyyppi_77 the solutions did not suffice because they were costly and didn't work in all cases and this.

To improve your question, you should also list the solutions that did not suffice. Why is costly an issue? Does your game deform meshes rapidly at runtime, or is there another reason why you can't cache the result?

@Tyyppi_77 the main reason why the question is not a duplicate is because I am very specific about asking for the smallest sphere and he is not. Also, my meshes sometimes change at run time

There is still a lot of room for improving this question. What cases did you have that the other did not? What did you try that did not work?

@AlexandreVaillancourt he asks for a sphere but I ask for the smallest sphere

@AlexandreVaillancourt to be honest, I would try this but it is utterly puzzling to me

Yes, you mention "didn't work in all cases", what are these cases?

@AlexandreVaillancourt I had a solution but it was very costly and that is a problem because i need to do the calculations after run time because my meshes change

The slowest way is to take the center point of your model, which you say you have already, and measure to each and every vertex, saving the one with the maximum value. I assume there exist faster ways of doing this; but that's a place to start

@blurry thanks. Let us continue this discussion in chat. I hope to see you soon.

@AlexandreVaillancourt the cases where that when a mesh had vertices in some specific positions it wouldn't generate the smallest sphere

Solving the bounding sphere problem
Computing the bounding sphere for a set of given vertices means solving the minimum covering circle problem in three dimensions. There're many algorithms out there to find such a bounding sphere, like Welzl's algorithm (at this page you can find an implementation in Java), and many others. You can also check out Fischer's exact solver the open source Miniball algorithm is based on.
The minimum enclosing sphere problem can be solved with an average algorithmic complexity of O(n4) for a naive algorithm working on free vertices, down to an easy O(nk) where k is the number of vertices of the equivalent convex hull of your starting mesh.
Edit: such linear-time solution is optimized for a convex set of vertices only, because further assumptions can be made due to geometric properties of convexity. A mesh with just no holes isn't necessarily convex; for example, a C-shaped mesh has no holes, but it isn't convex either – you can connect its two edges with a segment, and part of it will lie outside the shape. A solid mesh may have fewer vertices to compute compared to a "holed" counterpart (and the CPU will be happy about it), but solidity doesn't imply convexity. Thus such mesh isn't eligible for the optimized algorithm mentioned above.
Consideration: exact vs. approximate solutions
As developers, we should be aware of many aspects in our games. Highly-detailed simulations (e.g. physics) or rich graphics imply a greater workload on CPU/GPU; on the other hand, prioritizing performances excessively may lead to a poor game experience due to low quality of simulation.
As coders, we must not waste resources when possible; we can optimize some operations in order to spend spare resources elsewhere if needed. As designers, we must define the minimum requirements for our game without being too greedy: a side-scrolling platformer will never need the same precision of physics simulation we expect from a top-quality racing game.
We need tradeoffs between results expected and resources required; every CPU clock is precious. If we can sacrifice some little realism without having the player noticing it and gain overall performances, this is a good way to go in my opinion.
An approximate, efficient algorithm
Having already aswered your question, if you don't really need the smallest sphere possible and an approximation of it is good enough, you can go with this algorithm.
algorithm MiniBall
    input: set V of points in space
    output: enclosing sphere in the form [center, radius]

    B = AABB(V)                // AABB from vertices
    C = mean(B.max + B.min)    // centroid of box B
    for each v in V:
        r = max(r, dist(C, v))        // distance to furthest point
    return [C, r]

The main idea is:

Consider the axis-aligned bounding-box, and use its centroid as origin. This ensures the sphere center will be always amongst the vertices;

Find the distance from the centroid to the furthest vertex, and use such distance as radius. This ensures that no points will lie outside of the sphere, at most on the sphere surface.

The complexity of this algorithm is O(n) where n is the number of vertices: you first read all vertices to find the bounding box corners, then you compute n distances between centroid and individual vertices.
It's quite fast, and may be more suitable for a real-time application with average precision requirements, such as a videogame.
Bonus: you can tweak the code line computing distance, and use the criterion that better suits your needs:

Max distance: no points outside of the sphere, at least one on the surface;

Min distance: no points inside the sphere, at least one on the surface (not really recommended in most cases);

Average distance: compute both the larger and smaller radii, and use mean(minR, maxR) as sphere radius. On average the sphere will split the vertices set into two halves. Some points may be inside the sphere, others outside of it, some can lie on the surface.

I edited the question liggiorgio. Does your answer still work now or is there any thing you want to add to it?

My answer still works, I updated it anyway to reflect the further details you included and expand my explanation.

Here is what I came up with after some feedback from  @nwp.

set the radius to 0

set the center to the first vertex.

add the radius incrementally to the absolute distance between the first point and each point on the mesh.

add the center incrementally to the radius halved.

add the entities position to the mesh.

For more info see this thread on chat.

@AlexandreVaillancourt it answers the question now

This does not give the smallest sphere. A simple counter example is 3 equidistant vertices. The smallest encompassing sphere would be center on the midpoint between them. If this solution solved your problem, then you need to reword your question to indicate you are looking for an approximation.

@Pikalek reworded the question

@Pikalek does the answer work with a solid collision mesh

@Pikalek do you have another counter example

Even with the rewording of the question, the example I gave still disproves the answer as given. Try drawing it out (the problem is the same in 2d & 3d). If after that, you're still unclear as to why the solution doesn't address the question, ping me in chat & I'll get back to you with illustrations.


text:
Passing data to objects and sub-systems
I am currently creating a game in C++ using SDL. Many game objects and sub-systems require the use of variables such as an SDL_Renderer for drawing to the screen and delta time for updating positions and there may be more added in the future (such as a TextureManager object). In this case the code for a game object might look something like this:
void Update(float deltaTime)
{
    // ...
}

void Render(SDL_Renderer* renderer)
{
    // ...
}

However, if another variable was added as a parameter, any subclasses would have to be updated and other systems made consistent with the new parameter.
Another way of passing data around would be to have one "storage class/structure" to store these variables and pass that instead. For example:
struct Data
{
    SDL_Renderer* renderer;
    float deltaTime;
    TextureManager textureManager;
};

My question is: what a good way of passing around data in a game engine? The first example would be bothersome to update if any changes were made to the parameters and would make adding more classes difficult. What about the second example? Would it be good design to have objects depend on a single class? Are there any other design patterns for passing around data without causing dependency issues?

Having built out my first game engine for the first time (in 20 years), and completely ignored alot of good literature (I should of read more but oh well :)).  I can offer a few quick insights into my issues and what dawned on me.  That question is why do I need to pass objects locally around, there are good reasons in many cases, but what I found was to limit that and at the least make it a pattern of use.
I won't go into actual architecture, because there are a number of ways to do this. I've used your model of update and render.  So it triggered some recollections.
Firstly I thought more about how to loosely couple systems together so I can swap out and enhance components as I went. One such method that worked for me was I found that by using an event manager (in my experience) where objects subscribed and unsubscribed from events removed about 80% of my coupling across the system.  All components had the right to post events to the system and really became the piping for alot in my game engine.  This event system was VERY basic, passing around an event type, subtype and a payload (it could be anything else, this is just my example).  I still have coupling afterwards but now only for creating certain entities in game.  The model itself allows you to have completely different classes and systems convey simple loosely coupled messaging between systems.  Having said that, my Eventmanager was a Singleton, which probably contradicts point 2 to a degree.
Secondly, Globals most of the time won't help, in fact, it just makes it worse in many cases (YES, they do help in some spots, so its actually cleaner way although they are a bit of a crutch) .  So I used container classes for the more major manager objects and don't be afraid to group managers into specific containers, my grouping was coarse, graphics and game logic managers for example.
In respects to globals, I found that it meant I had flattened the dependency tree of the various system components.  Removing the globals meant I was forced to address the hierarchy of my critical objects and order them more logically.  The globals were a reflection of my lack of planning in the architecture of my engine.   It has a number of roll improvements once I had fixed this, controlling the order of destruction and creation of objects was natural.  Rather than having to understand explicitly dependence of objects, it was implied and also enforced a standard.
Thirdly (and a little off topic), you will continue to learn and that will mean you will see patterns where you didn't before.  So don't be hard on yourself, there is code you will look at and say "What the hell was I thinking.".  Always revise, and improve.  You can read a book, but if you shoe horn yourself into a discipline/design and don't end up liking it, it will kill your enjoyment.  So diving in on your project can be a good and bad experience, but just keep learning.
Finally, all is a disclaimer, because of my experience with developing my own game.  I've learned alot and would redo some things from the start, but I have had some surprising results around design and execution just through learning.  good luck.  Everyone's experience is different, I'm sure you will get some good tips from others on here.

added more info on the globals, for me globals had demonstrated to me a a lack of planning and architecture in my game engine.  It also enforced more rigid and repeatable implementation patterns.

There is no ideal solution, it's just a matter of understanding Pros/Cons of each choices and endorse them.
void Update(float deltaTime)
{
    // ...
}

As you said, this will be a pain to refactor but it's not an impossible task. Moreover you can expect to have an API that become more and more stable over the time.
I would discourage to 'hide' this into a Struct, because 'Data' makes no sense. What if you have different function with different 'Data' struct. It will be a pain to understand the project when it grows. This is the inverse of the first solution: Quick now but hard latter.
However you can use struct when it make sense (just a dummy example):
struct FrameTime
{
    Millisecond  deltaTime;
    int          frameNumber;
};

Statics (or globals) make thing easier to use (but not easier int case of refactoring).
For instance a paradigm I like, because it's not really a Singleton but provide me a Global 'Main' access:
// Time.h
class Time
{
  public: // Public class API
    Millisecond getDeltaTime();

  public: // Static Main access (Better if in another class)
    static Milliseconds GetDeltaTime();
};

// Time.cpp
Millisecond Time::getDeltaTime()
{
  return ...;
}

static Time s_time;
Millisecond Time::GetDeltaTime()
{
return s_time.getDeltaTime();
}

// ...

void Update()
{
    Millisecond deltaTime = Time::GetDeltaTime();
    // ...
}

Then question is not, is it possible that you need something else than the 'Global delta time', because there is always a possibility.
But the question is, what happens if suddenly you need to provide an independent delta time. How much energy you will need to refactor it versus which is the risk.
This rarely happens, but it happens.

Thanks for the answer. Using some sort of static function setup like you have shown is a method that I will definitely consider using. Are there any immediate or future problems with using this method?

I use this solution for a while now and did not noticed any specific issue. What can happen also is, if you need to change an API used by a lot a static methods, you will have more refactor than if you just used the getInstance()


text:
Old tv effect in shader graph
I am trying to use Unity's shader graph to create this old tv effect:

I thought about using a noise node, and somehow randomize the noise's seed.
Can anyone help me?

I don't think I can answer you, but I did find this link on the subject. Bookmarking it myself!
https://thebookofshaders.com/11/

I accidentally managed to make such shader while playing around with nodes. Here's how the whole setup looks:

We're using Gradient Noise node, but to animate it, we're using Rotate node that rotates its UV (rotating the generated noise texture), with Time node connected to Rotation value. However, if you crank up Rotate's Center parameter to 10,10 it doesn't look like it's rotating anymore. Gradient's Scale parameter has to be 90+, but not too much because it looks worse then.

For more contrast, add Remap node and configure out value. In my case, [-6, 5] looks good.


text:
Best Practice for Validating Components in Unity/C#?
In my game there's a Unit class, which all soldiers use.  Not all soldiers have special abilities which require unique class components (like Stealth class).  Special abilities either exist on a unit from the start, or never.
Special classes like Stealth are monobehaviour classes which provide specific functionality, and the fact a unit is or is not Stealth will need referenced by other classes.  For example, the classes which handle unit shooting and detection must check whether a unit in proximity is stealth. I'm wondering what is the best way to handle this case with Unity, given components?
Right now the Unit class' Start function checks if the special class exists, and assigns a private boolean to true.  This boolean can only get accessed by a get function.  Does this make sense for more easily readable and secure code?  Or is it overengineering?
private bool isStealth;

if (GetComponent<Stealth>())
{
    isStealth = true;
}

public bool IsStealth()
{
    return isStealth;
}

What does the Stealth class look like?

@EdMarty edited, does this help? Stealth will be monobehaviour which does things like fading a unit in or out of stealth mode, which has implications in many other classes like unit detection and shooting.

Your solution is fine. Although “secure coding” is not what you’re doing so much as “decoupled coding” which is a laudable goal.
An even more decoupled alternative is to have the solution be more generic, so that the Unit class need not know about the Stealth class at all, for example by using an enum. It can then be extended if the Unit has other properties set up via Components without needing to modify the Unit class (more than trivially) for each property.
For example (warning: untested):
[Flags]
public enum UnitProperty {
    Stealth = 1,
    Boss = 2,
    Slow = 4,
    MadeOfJelly = 8,
    //etc.
}

public interface UnitPropertySource {
    UnitProperty GetProperty();
}

public class Stealth : MonoBehaviour, UnitPropertySource {
    public UnitProperty GetProperty() {
        return UnitProperty.Stealth;
    }
    //other stealthy stuff
}

public class Unit : MonoBehaviour {
    private UnitProperty properties;
    private void Start() {
        foreach (var propertySource in GetComponents<UnitPropertySource>()) {
           properties |= propertySource.GetProperty();
        }
    }
    public bool HasProperty(UnitProperty p) {
        return properties & p == p;
    }
    public bool IsStealth {
        get {
            return HasProperty(UnitProperty.Stealth);
        }
    }
    public bool IsMadeOfJelly {
        get {
            return HasProperty(UnitProperty.MadeOfJelly);
        }
    }
}

Your approach seems fine as long as a Stealth component cannot be added during runtime. Otherwise you should get rid of the bool field and just write your IsStealth method like so:
public bool IsStealth()
{
    return GetComponent<Stealth>();
}

Because a bool is returned, GetComponent<Stealth>() will be casted automatically.
Unity also provides a special method for validating values in MonoBehaviour called OnValidate.
This is useful if you have public fields (or in Unity docs sometimes called properties) that require validation. But in your case it makes more sense to validate during runtime, because the isStealth field should not be public if its value depends on some other component.

Calling GetComponent more than once is unnecessarily expensive just to check existence if its existence will never change.

@EdMarty That's basically what I wrote in my very first sentence.

What I mean is in general using GetComponent frequently is expensive, so finding a way to avoid it is better than just ignoring the problem.


text:
How do I deal with closely coupled systems in a game engine?
Let's say a game engine had a central game class as well as multiple systems (as objects) that are stored within it. These systems (such as input, rendering, sound, etc) would also be updated by this main game class. What if the input manager detects that the close button on the window if pressed. It would cause the game to shutdown by, say, calling a quit method inside the game class. This would be an example of a closely coupled system which is typically not good for future expansion of these systems. How would a closely coupled system like this be dealt with in order to make it more loosely coupled?

Events would help for this.
Take your InputManager example in the method where you detect the close button has been pressed instead of referencing the game class and calling the quit method you would fire an event lets say "OnWindowClosed" and then have your game class subscribe to that event.
That way you could theoretically have any class that needs to know the game is shutting down subscribe to the event and do whatever it needs to do when OnWindowClosed is triggered.
This way the subscriber (Game class) doesn't need to know anything about the publisher(Input Manager) other than it did something it may want to "respond" to.
Here is an example from my project, the ActorManager needs to listen for the OnMapLoad Event Triggering from MapManager in order to spawn the Actors into the scene after its been generated.
public class EventManager
{
    //define a delegate signature, the variables need to match up the event trigger
    public delegate void OnMapLoad(Vector3 mapSize, Dictionary<Vector3, Tile> currentMap);
    //define the event generally prefixed with "On"
    public static event OnMapLoad OnMapLoadCallBack;

    //and here's the event trigger itself
    public static void TriggerOnMapLoad(Vector3 mapSize, Dictionary<Vector3, Tile> currentMap)
    {
        //check to see if OnMapCallBack has subscribers
        if (OnMapLoadCallBack != null)
        {
            //if it does trigger the event with params (or without if you dont define any above)
            OnMapLoadCallBack(mapSize, currentMap);
        }
    }

}

public class ActorManager : MonoBehaviour
{

    public int teams = 2;
    public int teamMembers = 1;
    public GameObject toonPrefab;
    public GameObject aiPrefab;
    public List<Team> teamsList = new List<Team>();
    public Vector3 teamOneSpawn = new Vector3(0, 0, 0);
    public Vector3 teamTwoSpawn = new Vector3(0, 0, 0);
    //I'm using unity and you always want to be sure to subscribe and unsubscribe from events otherwise they will cause memory leaks, I'm simply doing it when the gameobject is instantiated and when it's disabled/removed
    void OnEnable()
    {
        //here I'm subscribing to the event and assigning the function Init to fire when the event is triggered, notice again the parameters must match the delegate you define
        EventManager.OnMapLoadCallBack += Init;
    }

    void OnDisable()
    {
        //unsubscribing here
        EventManager.OnMapLoadCallBack -= Init;
    }

    void Init(Vector3 mapSize, Dictionary<Vector3, Tile> currentMap)
    {
        CreateTeams(mapSize);
    }

public class MapManager : MonoBehaviour
{
    public void GenerateMap(BiomeData biome)
    {
        CreateFloor(biome);
        AddDecorations(biome);
        AddTrapTiles(biome);
        AddEnviroment(biome);

        //this is where I call the event from the Map Manager to let the Actor Manager know the map has finished loading
        EventManager.TriggerOnMapLoad(mapSize, currentMap);
    }
}


text:
When to use a lockstep protocol?
What types of games benefit most from lockstep? What games are not suitable for a lockstep protocol? What are the disadvantages of lockstep?

This question is a bit broad to answer definitively for all games, since different games will use different mixes of techniques for many varied reasons. If you're weighing applying lockstep in your current game project, you're likely to get better answers by focusing on your game's needs. What features are you implementing, what problems are you facing that you think lockstep might solve, or what problems are you facing implementing lockstep that you need to find solutions or alternatives for? This narrows the question to a scope where we can evaluate correct, working solutions to the problem.

By using lockstep, I am thinking my game will always be in sync across clients. the state of the game will always be 100% accurate across clients for everyone. My game is an action game but it's not that fast-paced.

Sounds good. Is there anything specific holding you back?

I don't want to spend time implementing a system that may not be optimal for my game. It doesn't seem like the system sees much use outside RTS games yet it seems like the perfect networking model to me so I feel I'm missing something.

StackExchange is better at troubleshooting a specific problem than at acting as a crystal ball to forecast what might go wrong in the future. If the techniques you're thinking of sound good to you, and you can't think of any specific problem with them, then I'd say it's at least worth prototyping to see if they hold up in practice.

That's not what I'm asking. I'm asking what aspects of a game would make implementing a lockstep ideal. There's tons of games out there and tons of genre, yet the amount of them that use lockstep is rather small I believe so there must be something about lockstep that makes it un-ideal for certain types of games or games with certain properties. What are they?