title: OpenGL ES model loader is slow?

text:
# Question
Title: OpenGL ES model loader is slow?
I'm trying to load a 3D model in OpenGL ES, and I managed to find a project on "sourceForge" that can do this job.

When I downloaded it and played the app, it took 50 second to load a small object (100 kb), so I changed the model for another that contains about twenty vertices (15 kb), but the application takes more than 10 second to download even this tiny model.

What is the problem, and how can I make this faster?

This is my obj parser

```
public class OBJParser {
    int numVertices=0;
    int numFaces=0;
    Context context;

    Vector<Short> faces=new Vector<Short>();
    Vector<Short> vtPointer=new Vector<Short>();
    Vector<Short> vnPointer=new Vector<Short>();
    Vector<Float> v=new Vector<Float>();
    Vector<Float> vn=new Vector<Float>();
    Vector<Float> vt=new Vector<Float>();
    Vector<TDModelPart> parts=new Vector<TDModelPart>();
    Vector<Material> materials=null;

    public OBJParser(Context ctx){
        context=ctx;
    }

    public TDModel parseOBJ(String fileName) {
        BufferedReader reader=null;
        String line = null;
        Material m=null;

        try { //try to open file
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
        }       catch(IOException e){
        }
        try {//try to read lines of the file
            while((line = reader.readLine()) != null) {
                Log.v("obj",line);
                if(line.startsWith("f")){//a polygonal face
                    processFLine(line);
                }
                else
                    if(line.startsWith("vn")){
                        processVNLine(line);
                    }
                    else
                        if(line.startsWith("vt")){
                            processVTLine(line);
                        }
                        else
                            if(line.startsWith("v")){ //line having geometric position of single vertex
                                processVLine(line);
                            }
                            /*else
                                if(line.startsWith("usemtl")){
                                    try{//start of new group
                                    if(faces.size()!=0){//if not this is not the start of the first group
                                        TDModelPart model=new TDModelPart(faces, vtPointer, vnPointer, m,vn);
                                        parts.add(model);
                                    }
                                    String mtlName=line.split("[ ]+",2)[1]; //get the name of the material
                                    for(int i=0; i<materials.size(); i++){//suppose .mtl file already parsed
                                        m=materials.get(i);
                                        if(m.getName().equals(mtlName)){//if found, return from loop
                                            break;
                                        }
                                        m=null;//if material not found, set to null
                                    }
                                    faces=new Vector<Short>();
                                    vtPointer=new Vector<Short>();
                                    vnPointer=new Vector<Short>();
                                    }
                                    catch (Exception e) {
                                        // TODO: handle exception
                                    }
                                }
                                else
                                    if(line.startsWith("mtllib")){
                                        materials=MTLParser.loadMTL(line.split("[ ]+")[1]);
                                        for(int i=0; i<materials.size(); i++){
                                            Material mat=materials.get(i);
                                            Log.v("materials",mat.toString());
                                        }
                                    }*/
            }
        }
        catch(IOException e){
            System.out.println("wtf...");
        }
        if(faces!= null){//if not this is not the start of the first group
            TDModelPart model=new TDModelPart(faces, vtPointer, vnPointer, m,vn);
            parts.add(model);
        }
        TDModel t=new TDModel(v,vn,vt,parts);
        t.buildVertexBuffer();
        Log.v("models",t.toString());
        return t;
    }

    private void processVLine(String line){
        String [] tokens=line.split("[ ]+"); //split the line at the spaces
        int c=tokens.length;
        for(int i=1; i<c; i++){ //add the vertex to the vertex array
            v.add(Float.valueOf(tokens[i]));
        }
    }
    private void processVNLine(String line){
        String [] tokens=line.split("[ ]+"); //split the line at the spaces
        int c=tokens.length;
        for(int i=1; i<c; i++){ //add the vertex to the vertex array
            vn.add(Float.valueOf(tokens[i]));
        }
    }
    private void processVTLine(String line){
        String [] tokens=line.split("[ ]+"); //split the line at the spaces
        int c=tokens.length;
        for(int i=1; i<c; i++){ //add the vertex to the vertex array
            vt.add(Float.valueOf(tokens[i]));
        }
    }
    private void processFLine(String line){
        String [] tokens=line.split("[ ]+");
        int c=tokens.length;

        if(tokens[1].matches("[0-9]+")){//f: v
            if(c==4){//3 faces
                for(int i=1; i<c; i++){
                    Short s=Short.valueOf(tokens[i]);
                    s--;
                    faces.add(s);
                }
            }
            else{//more faces
                Vector<Short> polygon=new Vector<Short>();
                for(int i=1; i<tokens.length; i++){
                    Short s=Short.valueOf(tokens[i]);
                    s--;
                    polygon.add(s);
                }
                faces.addAll(Triangulator.triangulate(polygon));//triangulate the polygon and add the resulting faces
            }
        }
        if(tokens[1].matches("[0-9]+/[0-9]+")){//if: v/vt
            if(c==4){//3 faces
                for(int i=1; i<c; i++){
                    Short s=Short.valueOf(tokens[i].split("/")[0]);
                    s--;
                    faces.add(s);
                    s=Short.valueOf(tokens[i].split("/")[1]);
                    s--;
                    vtPointer.add(s);
                }
            }
            else{//triangulate
                Vector<Short> tmpFaces=new Vector<Short>();
                Vector<Short> tmpVt=new Vector<Short>();
                for(int i=1; i<tokens.length; i++){
                    Short s=Short.valueOf(tokens[i].split("/")[0]);
                    s--;
                    tmpFaces.add(s);
                    s=Short.valueOf(tokens[i].split("/")[1]);
                    s--;
                    tmpVt.add(s);
                }
                faces.addAll(Triangulator.triangulate(tmpFaces));
                vtPointer.addAll(Triangulator.triangulate(tmpVt));
            }
        }
        if(tokens[1].matches("[0-9]+//[0-9]+")){//f: v//vn
            if(c==4){//3 faces
                for(int i=1; i<c; i++){
                    Short s=Short.valueOf(tokens[i].split("//")[0]);
                    s--;
                    faces.add(s);
                    s=Short.valueOf(tokens[i].split("//")[1]);
                    s--;
                    vnPointer.add(s);
                }
            }
            else{//triangulate
                Vector<Short> tmpFaces=new Vector<Short>();
                Vector<Short> tmpVn=new Vector<Short>();
                for(int i=1; i<tokens.length; i++){
                    Short s=Short.valueOf(tokens[i].split("//")[0]);
                    s--;
                    tmpFaces.add(s);
                    s=Short.valueOf(tokens[i].split("//")[1]);
                    s--;
                    tmpVn.add(s);
                }
                faces.addAll(Triangulator.triangulate(tmpFaces));
                vnPointer.addAll(Triangulator.triangulate(tmpVn));
            }
        }
        if(tokens[1].matches("[0-9]+/[0-9]+/[0-9]+")){//f: v/vt/vn

            if(c==4){//3 faces
                for(int i=1; i<c; i++){
                    Short s=Short.valueOf(tokens[i].split("/")[0]);
                    s--;
                    faces.add(s);
                    s=Short.valueOf(tokens[i].split("/")[1]);
                    s--;
                    vtPointer.add(s);
                    s=Short.valueOf(tokens[i].split("/")[2]);
                    s--;
                    vnPointer.add(s);
                }
            }
            else{//triangulate
                Vector<Short> tmpFaces=new Vector<Short>();
                Vector<Short> tmpVn=new Vector<Short>();
                //Vector<Short> tmpVt=new Vector<Short>();
                for(int i=1; i<tokens.length; i++){
                    Short s=Short.valueOf(tokens[i].split("/")[0]);
                    s--;
                    tmpFaces.add(s);
                    //s=Short.valueOf(tokens[i].split("/")[1]);
                    //s--;
                    //tmpVt.add(s);
                    //s=Short.valueOf(tokens[i].split("/")[2]);
                    //s--;
                    //tmpVn.add(s);
                }
                faces.addAll(Triangulator.triangulate(tmpFaces));
                vtPointer.addAll(Triangulator.triangulate(tmpVn));
                vnPointer.addAll(Triangulator.triangulate(tmpVn));
            }
        }
    }
}

```

# Answer
There's nothing inherently slow or fast about OpenGL, or Java for that matter, when it comes to loading models. The following basic rules apply:

* You're hitting the disk, so fewer large reads are going to be *much* faster than lots of small reads.
* Loading binary files is typically going to be faster than parsing plain text.
* If the model needs conversion from the format and layout it's stored in to the format and layout it's going to be used in, then that's going to slow things down as well.

The fastest model loading basically happens when you can memory-map a binary file and pass the resulting pointer, with unmodified/un-parsed data, directly to a glBufferData call. Any work beyond that is going to slow things down, and the more work that is done, the slower things will be.

Based on all of this, you'll see that .obj is actually a horrible format for consuming directly by a 3D application. If you need an interchange format that's readable by anything and is in human-readable plain-text, it meets those criteria. If you care about getting the model off-disk and into-memory as fast as possible at load time in a real-time application, it sucks - which is why nobody actually uses it for production-quality work.

Instead, if you must use .obj, you should include as part of your toolchain a final conversion step to a nice fast binary format that your program can quickly and easily load.
> 1 votes

# Answer
10 seconds for 20 verts model is way too long.

And it seems there's not much you can do to speedup this exact library. It constructs lots of temporary strings instead of referencing substrings within the file. It runs regular expressions to match the face data indices, and does it multiple times until matching structure found, with pos/norm/texco format being tested the last.

That's not how you do it. Normally you'd just read out integer numbers until you find a delimiter (whitespace or '/'), and then see how many numbers within group you've found.

And then instead of primitive types it operates on boxed values. Yes, generics needs classes, but it doesn't have to be a Vector.

You'd better look for some other model loader library.
> 0 votes

---
Tags: java, performance, opengl-es, obj, model-loader
---


title: Could not load PNG in SDL2?

text:
# Question
Title: Could not load PNG in SDL2?
I have three image files, one is Techs.png, one is Techs.gif and one is Techs.bmp. I have used SDL\_image 2.0.5 and SDL 2. When I load the image of Techs.gif and Techs.bmp, there is no error, but when I load the image of Techs.png. SDL\_Surface\*Surface=IMG\_Load("Techs.png"), an error occurs, I cannot load this image and Surface always returns NULL, I am using Visual Studio 2019. Can someone help me, thanks.

# Answer
> 0 votes
When in doubt, make sure you read the documentation for the functions you use. There are sometimes hidden gems and very useful tips there.

In this case, we can see that there is a function called `IMG_GetError()` which should be used to retrieve a human readable message of the error you got.

Using this, you'll be able to narrow down the possible sources of issues.

---
Tags: c++, sdl2
---


# Question
Title: How to store unique keys for an infinitely generated, chunked world?
My game is made up of chunks which are identified in world space with and X and Y coordinate. Each chunk contains 16 tiles by 16 tiles by 4 layers. So that I don't have to loop over every single tile every time I want to access things such as hitboxes or animation frames I store that tile's value as keys in various dictionaries such as "Animations" or "Collidables". Until now I have been doing it like this:

```
        public string GetTileKey(int layer)
    {
        string XString = X.ToString();
        if (XString.Length < 4)
        {
            XString = XString.PadLeft(4, '0');
        }
        string YString = Y.ToString();
        if (YString.Length < 4)
        {
            YString = YString.PadLeft(4, '0');
        }
        return layer.ToString() + XString + YString;

    }

```

which as you can imagine, slows things down considerably!

After chatting with a few awesome people in discord I was suggested a bitwise method which would store the first few bits as the X coordinate, the second few as the Y, and the last 2 as the layer like so:

```
public int GetTileKeyAsInt(int layer, IInformationContainer container)
    {
        return (X << 16) | (Y << 9) | layer;
    }

```

(The container parameter is not currently used, I was trying things out with its X and Y coordinates. It's really just the chunk)

which works fantastic when used with X and Y values which are between 0 and 128 and which are not negative. In addition it guaranteed no duplicate keys.

I quickly realized this wouldn't work with my world, which requires both positive and negative coordinates and an "infinitely" expanding number of chunks.

What is a better way to do this? I was planning on using a float or a double and using the first bit as the sign value, and the next eight (4 and 4) to store the X and Y coordinates of local tiles within chunks and then allocating the rest of the bits to allow for a massive number of allowable chunks. I'll admit I'm not super familiar with bitwise operations or even really the specifics between int, float and double :( but from what I've gathered it doesn't actually make sense to do bitwise operations with anything larger than an Int 32!

# Answer
Although our world may be functionally infinite, we typically need only a finite, contiguous chunk of it at a time. We can exploit that structure to make our lives easier and our code faster.

One neat way to do this is with what's called a **clipmap**. Here we lay down a finite grid of tiles for our scene. Let's say for simplicity it's 1024x1024 tile on each side, or 64x64 chunks' worth, letting us simulate and display over a million tiles at a time. (You can of course make this smaller or larger as needed)

When we reach the right edge of our grid, we wrap around to the left edge and just keep going, recycling parts of the map we already used now that they're safely out of view "behind" us.

Using modular arithmetic via fast bitwise AND operations, we can look at this wrap-around local grid as a sliding window that roams around our infinite world. As long as our viewport into the world is narrower than this window, we never see the edge.

Let's say the tile at the center of the player's current view is stored as two signed longs (hey, we want to roam over a huuuuuuge area, right?). In the clipmap, that tile is stored at...

```
// 2^10 = 1024 (powers of 2 let us use bitwise tricks)
const int CLIPMAP_POWER = 10;
const int CLIPMAP_SIZE = 1 << CLIPMAP_POWER;
// Set all bits smaller than our clipmap size
const int CLIPMAP_MASK = CLIPMAP_SIZE - 1;

Vector2Int GetClipmapPosition(long globalX, long globalY) {
    return new Vector2Int((int)(globalX & CLIPMAP_MASK), (int)(globalY & CLIPMAP_MASK));
}

```

In fact, we can use this function to map any tile anywhere in the world to its designated place in the clipmap.

Yes, two tiles A & B can collide at the same clipmap position, but only if they're a multiple of 1024 tiles apart - ie. only if we've traveled so far from A that it's been clipped out of view, and our rolling window has wrapped around and recycled its place for tile B.

That illustrates a useful property of clipmaps: although the window roams around, you never need to shift a tile you've already loaded into a new place - shuffling your contents down the way you might when removing an item from the head of a list. A column of tiles that's disappeared off the left side of the screen far enough to be recycled can just be overwritten in-place with the new column of tiles, ready to enter from the right side of the screen. If you're using arrays of value types, this keeps your memory layout contiguous & predictable to get the maximum benefit of the CPU's caching features.

When iterating over the visible range of tiles to render, we just need to take the wrap-around into account:

```
Vector2Int start = GetClipmapPosition(centerX - range, centerY - range);
Vector2Int end = GetClipmapPosition(centerX + range, centerY + range);

for(int x = start.x, x != end.x, x = (x + 1) & CLIPMAP_MASK) {
    for(int y = start.y, y != end.y; y = (y + 1) & CLIPMAP_MASK) {
        DoSomethingWith(clipmap[x, y]);
    }
}

```

Now every tile that we care about (ie. those that are currently loaded at any particular moment) has a nice, simple, unchanging address, guaranteed not to collide with any other loaded tile, and it's compact enough to convert to an ID using the trick you're already familiar with:

```
public struct LocalTileID {
    int x;
    int y;
    byte layer;

    public int GetHashCode() {
        return  (layer << (2 * CLIPMAP_POWER))
              | ( x    <<      CLIPMAP_POWER )
              | ( y );
    }
}

```
> 1 votes

---
Tags: c#, monogame, procedural-generation, tiles
---


# Question
Title: Destroy multiple actors by pressing a button
I'm making a simple project to learn Unreal Engine.

I have 50 actors (blueprints) and at the start a function will loop 5 times and spawn 5 of the 50 actors randomly.

How can I destroy the actors by pressing a button, irrespective of which of the 50 actors are spawned?

# Answer
> 1 votes
As you're using SpawnActorFromClass to create these actors, you need to tell Unreal what they are so that later, it can find a reference to them and destroy them.

Create an Array of Actors and before you run your loop, make sure you empty it.

The SpawnActorFromClass module has a "Return Value" pin which you can use to add items to this array.

When it's time to destroy the actors, loop through the array and with a Get box, call "Destroy Actor" command, plug in the output pin of the Get to destroy all 5 actors.

---
Tags: unreal-4, unreal, blueprints
---


# Question
Title: Why is enabling GL_FRAMEBUFFER_SRGB making the colours brighter?
My understanding of gamma correction is as follows: We want to do colour math in linear space so we can lerp etc. between colour values and get the results we expect. But human eyes don't have a linear response to light, so we need to modify the colours just before displaying them. sRGB is then commonly used colour space for this. Furthermore, since paint programs and colour pickers talk about colour in sRGB, the colours typically need to be linearized before math is performed on them.

**EDIT 2:** Turns out I had the following conversions backwards. The rest of the question is left unchanged for context, but I don't want to lead someone else down the same incorrect path.

The actual curve mapping sRGB to linear space is an exponential curve over the range 0 to 1. Linear to sRGB is raising the colour to the power of 2.2. sRGB to linear is taking the 2.2th root of the colour. So since we are in the range 0 to 1 Linear to sRGB make the colours less bright, and sRGB to linear does the opposite.

In my program I'm pulling values out of an GL\_R8 texture, interpreting them as alpha values and taking a vec4 as a vertex attribute we'll call `colour` and multiplying it by `vec4(1.0, 1.0, 1.0, alpha)` to produce the final colour in the fragment shader. If I set the `colour` attribute to a known colour and enable the `GL_FRAMEBUFFER_SRGB` flag, then the colour I get is too bright, and it is exactly as bright as it would be if the sRGB to linear conversion was not applied.

For example if I pass in the colour #222222 I get #666666 actually rendered to the screen according to an external colour picking tool. If I convert the colour #222222 to three floats by dividing by 255.0 I get three copies of 0.13333333. 0x22 = 34 in base 10, 34.0 / 255.0 = 0.13333333. The 2.2th root of 0.13333333 is 0.40017032. 0.40017032 * 255.0 gives us 102. 102 in hex is the 0x66 we were expecting.

At first I thought that the problem was that it wasn't applying the linear to sRGB conversion to the output of the shader for some reason, since things were too bright. So I did some searching and found this answer but that states that the only way that the linear to sRGB conversion will only be applied if GL\_FRAMEBUFFER\_SRGB is enabled. I'm getting the opposite behavior: the colours are too bright only if GL\_FRAMEBUFFER\_SRGB is enabled!

I then realized that openGL can't magically know what the semantics of my `colour` vertex attribute are. So it can't be automatically converting my `colour` to linear space, unless it's doing something weird and error prone like checking the name of the attribute or just converting every `vec3` or `vec4`. If that was a desired feature, a shader keyword or something would have been a better way to do that.

So I'm confused as to how I'm getting this result. I'm not currently doing any colour math in the shader besides what I've already mentioned, besides alpha blending. But I might want to do more of that later, including loading more textures in the fragment shader so I would like to sort out this weirdness, rather than just disabling GL\_FRAMEBUFFER\_SRGB and leaving the same mess for myself if I do end up doing more complicated stuff later.

**EDIT 1**: My windowing library says that my pixel format is sRGB so I don't think that is the issue. If I run `glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_FRONT_LEFT, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &result)`, `result` gets set to `GL_SRGB`. If I check `GL_FRONT_RIGHT`, `GL_BACK_LEFT`, and `GL_BACK_RIGHT` I get `GL_LINEAR`, `GL_SRGB`, and `GL_LINEAR` respectively. But according to this page since I didn't set any stereo rendering settings, then the `RIGHT` buffers shouldn't matter.

# Answer
My shaders work in the linear space, and I rely on `glEnable( GL_FRAMEBUFFER_SRGB )` to do the conversion.

To drive the monitor (which has **a very low response** for dark/low values,) OpenGL needs to increase the (dark) values in my framebuffer.

So yes, enabling `GL_FRAMEBUFFER_SRGB` is supposed to make your rendered image brighter.

Now, where it gets interesting is, that as far as I am aware, none of the 3D graphics fileformats properly specifies the colour space for the colour-per-vertex or colour-per-face that are in the file. So you typically assume them to be non-linear.

So, as you load an OBJ file, you should expect that the author intended the colours to be in non-linear space. Hence, before using them in your shaders, you need to convert them to linear (make them darker.)

OpenGL will then take your framebuffer output and make them lighter again (as you observed.)

I recommend the following sanity check for you:

* Just render a picture with nothing in it, other than glClear() with colour (0.05, 0.05, 0.05)
* With `GL_FRAMEBUFFER_SRGB` **disabled**, it should be nearly indistinguishable from black.
* With `GL_FRAMEBUFFER_SRGB` **enabled**, it should be grey, because 0.05 is then considered linear, and hence produce 5% of the photons that pure white does: This is plenty of light to be discernible from black.

So, yes, with a linear-colour mind-space, you need to be aware that low values in the framebuffer (or low values in your object's model) are actually a lot brighter than what you are used to in the traditional gamma-curved colour space or CRTs and LCDs.

Let me conclude by linking to Tom Forsyth's excellent article on SRGB.
> 1 votes

# Answer
It's not the display colors that got brighter, only the textures. You need to set the internal format of them to GL\_SRGB:

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB, ...)

```
> 0 votes

---
Tags: opengl, fragment-shader, color, srgb
---


# Question
Title: Strange diagonal line artifact in simple ripple shader
I have a simple shader, converted from GLSL to HLSL. This is the original: https://www.shadertoy.com/view/tdKSWG

The problem is that there is a very visible diagonal line artifact going from UV(1,1) to UV(0,0) and this artifact is not visible in the GLSL original.

No artifacts visible when ripples are started in any other screen position:

The sampler AddressU is set to "Wrap" and in shadertoy it is set to "Repeat", it should do the same but the waves still get reflected at the screen border (It works fine in GLSL)...

Does anyone know how to fix this?

This is my HLSL version:

```
//-- Include some common stuff
#include "mta-helper.fx"

float STRENGTH = 5.0;
float MODIFIER = 0.91;
float STEP = 2.6;
float FADESTRENGTH = 20;
float2 iResolution = {1024,512};
float3 iMouse = {0,0,0};
texture buffer;

sampler myself = sampler_state
{
    Texture = (buffer);
    MinFilter = Linear;
    MagFilter = Linear;
    MipFilter = Linear;
    AddressU = Wrap;
    AddressV = Mirror;
};

//------------------------------------------------------------------------------------------
// Structure of data sent to the vertex shader
//------------------------------------------------------------------------------------------
struct VSInput
{
    float4 Position : POSITION0;
    float4 Diffuse : COLOR0;
    float2 TexCoord : TEXCOORD0;
};

//------------------------------------------------------------------------------------------
// Structure of data sent to the pixel shader ( from the vertex shader )
//------------------------------------------------------------------------------------------
struct PSInput
{
    float4 Position : POSITION0;
    float4 Diffuse : COLOR0;
    float2 TexCoord: TEXCOORD0;
};

//------------------------------------------------------------------------------------------
// VertexShaderFunction
//------------------------------------------------------------------------------------------
PSInput VertexShaderFunction(VSInput VS)
{
    PSInput PS = (PSInput)0;

    // Calculate screen pos of vertex
    PS.Position = MTACalcScreenPosition(VS.Position);

    // Pass through color and tex coord
    PS.TexCoord = VS.TexCoord;
    //PS.TexCoord.y -= 0.5;
    PS.Diffuse = VS.Diffuse;
    return PS;
}

float4 psFunction(PSInput PS) : COLOR0
{

    float4 color = tex2D(myself, PS.TexCoord);
    float value = 0;

    float3 direction = float3(STEP, STEP, 0) / iResolution.xyy;

    float s1 = tex2D(myself, PS.TexCoord - direction.zy).r;
    float s2 = tex2D(myself, PS.TexCoord - direction.xz).r;
    float s3 = tex2D(myself, PS.TexCoord + direction.xz).r;
    float s4 = tex2D(myself, PS.TexCoord + direction.zy).r;

    if (length(PS.TexCoord - iMouse.xy) < 0.005 && iMouse.z == 1) {
        value = STRENGTH * smoothstep(3, 0.5, length(iMouse.xy - PS.TexCoord));
    }

    value += -(color.g - 0.5) * 2 + (s1 + s2 + s3 + s4 - 2);
    value *= MODIFIER;
    value = value * 0.5 + 0.5;

    float alphaFade = saturate(FADESTRENGTH * PS.TexCoord.y) * saturate(FADESTRENGTH * (1 - PS.TexCoord.y));
    return float4(value, color.r, value, alphaFade);
}

technique shield
{
    pass P0
    {
        VertexShader = compile vs_3_0 VertexShaderFunction();
        PixelShader  = compile ps_3_0 psFunction();
    }
}

```

# Answer
> 1 votes
This guy had the same problem, he needed to ping-pong between 2 textures for the alternating of read/write during rendering. I did that now, AND IT WORKS. Its impossible to use one and the same renderTarget in one and the same frame for reading AND writing, you have to use 2 renderTargets. One for reading and one for writing. And in the next frame you have to swap them.

https://community.khronos.org/t/wave-ripple-fragment-shader-working-but-with-strange-side-effects/76194/3

Here is the full code with my (new) ripples effect that is actually working fine:

```
--Lua script code
local w, h = guiGetScreenSize()
local shaders = {}
local bufferIndex = 0
local qualityX = 1000 -- Quality of render target
local qualityY = 500

function createShader()
local shadergroup = {dxCreateShader("buffer.fx", 0, 100, false, "object"), dxCreateRenderTarget(qualityX, qualityY), dxCreateRenderTarget(qualityX, qualityY)}
if shadergroup[1] and shadergroup[2] and shadergroup[3] then
    dxSetShaderValue(shadergroup[1], "texelSize", {1/qualityX, 1/qualityY, qualityX, qualityY})
    table.insert(shaders, shadergroup)
else
    if isElement(shadergroup[1]) then destroyElement(shadergroup[1]) end
    if isElement(shadergroup[2]) then destroyElement(shadergroup[2]) end
    if isElement(shadergroup[3]) then destroyElement(shadergroup[3]) end
end
end
addEventHandler("onClientResourceStart", resourceRoot, createShader)

function update()
local mouseX, mouseY, click = 0, 0, 0
if getKeyState("mouse1") and mouseX then
    click, mouseX, mouseY = 1, getCursorPosition()
end
for i, shadergroup in pairs(shaders) do
    if shadergroup[1] and shadergroup[2] and shadergroup[3] then

    --set renderTarget to A for writing, give shader renderTarget B for reading
    --next frame set renderTarget to B for writing, give shader renderTarget A for reading

        bufferIndex = (bufferIndex + 1) % 2 -- this swaps between 0 and 1 each frame

        local readTarget = shadergroup[2]
        local writeTarget = shadergroup[3]
        if bufferIndex == 0 then
            readTarget = shadergroup[3]
            writeTarget = shadergroup[2]
        end

        dxSetShaderValue(shadergroup[1], "iMouse", {mouseX * qualityX, mouseY * qualityY, click}) -- pass current mouse state
        dxSetShaderValue(shadergroup[1], "buffer", readTarget) -- pass current render target for reading color to the shader

        dxSetRenderTarget(writeTarget) -- set the new writing render target
        dxDrawImage(0, 0, qualityX, qualityY, shadergroup[1]) -- draw the shader to the render target
        dxSetRenderTarget()

        dxDrawImage(0, 0, 800, 400, writeTarget) -- draw final image

    end
end
end
addEventHandler("onClientRender", root, update) -- execute code each frame

//Shader code, PS 2.0 required
static const float FADE_SPEED = 0.99; // how fast should the ripples fade out
static const float MOUSE_RADIUS = 5.0; // how large is the ripple that a mouse click creates
static const int BORDER_FADE_STRENGTH = 20; // strength of fading-out at the screen border

float4 texelSize = {0.001, 0.002, 1000, 500}; // texelSize = 1/width, 1/height, width, height
float3 iMouse = {0,0,0}; // x, y mouse position in pixels, z = 1 -> click
texture buffer;

float4x4 gWorld : WORLD;
float4x4 gView : VIEW;
float4x4 gProjection : PROJECTION;

sampler readTarget = sampler_state
{
    Texture = (buffer);
    AddressU = Wrap; // Wrap = ripples will come out of the other screen side
    AddressV = Mirror; // Mirror = ripples will bounce off the screen border
};

//------------------------------------------------------------------------------------------
// Structure of data sent to the vertex shader
//------------------------------------------------------------------------------------------
struct VSInput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
};

//------------------------------------------------------------------------------------------
// Structure of data sent to the pixel shader ( from the vertex shader )
//------------------------------------------------------------------------------------------
struct PSInput
{
    float4 Position : POSITION0;
    float2 TexCoord: TEXCOORD0;
};

//------------------------------------------------------------------------------------------
// VertexShaderFunction
//------------------------------------------------------------------------------------------
PSInput VertexShaderFunction(VSInput VS)
{
    PSInput PS = (PSInput)0;

    // Calculate screen pos of vertex
    float4 posWorld = mul(VS.Position, gWorld);
    float4 posWorldView = mul(posWorld, gView);
    PS.Position = mul(posWorldView, gProjection);

    // Pass through color and TexCoord
    PS.TexCoord = VS.TexCoord; // PS.TexCoord = texture coordinates in a range of 0-1
    return PS;
}

float3 fetch(float2 coord, float2 offset){
    return tex2D(readTarget, coord + offset).rgb;
}

float4 psFunction(PSInput PS) : COLOR0
{
    float weight = (fetch(PS.TexCoord, float2(0, texelSize.y)).r // expand the ripple in all 4 directions
            + fetch(PS.TexCoord, float2(0, -texelSize.y)).r
            + fetch(PS.TexCoord, float2(texelSize.x, 0)).r
            + fetch(PS.TexCoord, float2(-texelSize.x, 0)).r) / 2;
    float t = FADE_SPEED * (weight - fetch(PS.TexCoord, float2(0, 0)).g);

    if (iMouse.z == 1 && length(iMouse.xy - PS.TexCoord * texelSize.zw) <= MOUSE_RADIUS) // add the ability to add ripples by clicking
    {
        t = 1;
    }

    float4 finalColor = float4(t, fetch(PS.TexCoord, float2(0, 0)).r, 0, 1); // dont forget to set alpha to a value greater than 0 or you wont see anything

    return finalColor;
}

technique ripple
{
    pass P0
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader  = compile ps_2_0 psFunction();
    }
}

```

**Screenshot:**

---
Tags: glsl, hlsl
---


# Question
Title: Simulate Unlit Shader using Physically Base Material Shader
Is there a way to have a physically based material shader look like an unlit shader?

Note: this question is *not* unity specific. I am trying to understand in general if it is possible to maybe(?) set the physically based material to a bunch of 0s and black/white maps to "zero it" to unlit.

# Answer
> 1 votes
Make your albedo 100% black, so that no light reflects from it diffusely.

Use maximum roughness to minimize the effect of specular highlights. Or, if your material has a specular multiplier exposed, set that to zero.

Place your surface texture into the emissive channel, and try to adjust the intensity value to match the exposure settings used by the camera.

This way, any light received from the object is coming 100% from your texture, not from reflected light.

---
Tags: shaders, materials
---


# Question
Title: ASSIMP skeletal animation with some FBX files has issues - weird node added
Hi I'm trying to work load fbx files to my OpenGL Renderer using ASSIMP.

However, weird nodes that are not in the original fbx file are added whenever I load the file with the ASSIMP importer.

For example, this is part of the node hierarchy printed while loading the nodes in a DFS matter.

```
mixamorig:LeftForeArm_$AssimpFbx$_Translation
ㄴmixamorig:LeftForeArm_$AssimpFbx$_PreRotation
 ㄴmixamorig:LeftForeArm_$AssimpFbx$_Rotation
  ㄴmixamorig:LeftForeArm_$AssimpFbx$_Scaling
   ㄴmixamorig:LeftForeArm

```

However, according to the original file, there should only be `mixamorig:LeftForeArm`.

This fbx file might be weird since usually in the case of other fbx files, I can get the node's translation, rotation, scaling keyframes directly from aiNodeAnim using the node's name. I never saw a case where the keyframe itself become a node.

Is there a way to resolve this issue?

# Answer
Assimp::Importer importer; // add the next code,you'll get a sigle node importer.SetPropertyBool(AI\_CONFIG\_IMPORT\_FBX\_PRESERVE\_PIVOTS, false);
> -1 votes

---
Tags: skeletal-animation, fbx, assimp
---


# Question
Title: Rigged through Blender (Rigify) and Errors in Unity
I am working on a Unity scene and as the 3D model is missing the bones, I ended up going to Blender for the rigging.

For that, I followed the procedure that Unity suggests by using the add-on Rigify. I was also following this tutorial, which was really helpful.

After exporting from Blender (in .fbx) and importing it on Unity, I went through the configurations (as @vcard suggested here)

In the "Rig" section, I pressed the button "Configure" (to configure the Avatar Definitions) and came across an error "Character is not in T pose".

I solved this one quite fast by accessing the menu "Pose" (in the Inspector) and then "Enforce T Pose".

After that, back in the scene, I came across the following error on the Inspector:

> Invalid Avatar Rig Configuration: Missing or invalid transform: Required human bone 'Head' not found.

I went straight to the configurations and decided to add the specific bones to the Head that appeared on the inspector (in the Avatar Definitions configurator). With that, I came found out that the problem is really the organization where there were placed by Rigify.

Any guidance is appreciated.

# Answer
As I didn't find the ideal order for the structure that allowed Unity to recognize the existence of the bones 'head' and 'neck' (that were present), I ended up using another platform: **Mixamo** (check here how to upload and rig 3D characters).

> I strongly recommend **Mixamo** as it is online, free and super simple to use.

---

## Process

1. Start by uploading the character:

2. Press "Next".
3. Place the markers. If your character is symmetric, before positioning the markers, activate "Use Symmetry" (which simplifies even more the task).

That's it. This is the Skeleton view in the review process:

Then I downloaded it in the format "FBX for Unity" and imported in Unity.

Now the Santa can finally close its arms:
> 2 votes

---
Tags: unity, animation, blender, rigging
---


# Question
Title: Unity 2D: Can’t resolve ArgumentOutOfRangeException: Index was out of range
I am very much a novice to coding with no background on this at all so the code you see here may be terrible.

Basically I’m making an endless runner, made up of a player character and a set of obstacle prefabs. The obstacle prefabs have a trigger on them so that when the player hits it, it spawns the next prefab. I’m using the code below, and when the player hits the first spawn trigger it will spawn a prefab, but on tripping the next trigger it gives me the ArgumentOutOfRangeException error in the console and doesn’t spawn anything.

public class ObsTrigger : MonoBehaviour {

```
 public GameObject spawnTrigger;
 [SerializeField] private List<Transform> obstacleList;

 private void OnTriggerEnter2D(Collider2D other)
 {
     if (other.CompareTag("Player"))
     {
         for (int i = 0; i < obstacleList.Count; i++)
         {
             spawnObstacle();
         }
     }
 }

 public void spawnObstacle()
 {
     {
         Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count -1)];
         Instantiate(chosenLevelPart);
     }
 }

```

}

If anyone can point me in the right direction I would really appreciate it!

# Answer
In the following chunk of code, you should check if there are any elements in your obstacle list before you try to access them

```
public void spawnObstacle()
{
    Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count -1)];
    Instantiate(chosenLevelPart);
}

```

should be

```
public void spawnObstacle()
{
    if (obstalceList.Count > 0)
    {
        Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count -1)];
        Instantiate(chosenLevelPart);
    }
}

```

because if there are no objects in the list, obstacleList\[0\] will still attempt to access the first element of the list, which would then be out of range.
> 1 votes

---
Tags: unity
---


# Question
Title: C++: passing gameobject as a parameter and then into vector
firstly iam used to java and new to c++ so maybe this will looks a noob's question i will explain this and give a pseudo code and then c++ just so you can understand me

i have a **player** class which inherit from **gameobject** and a **handler** class which update all the game objects(stored in vector) and render them i have a function to add objects but i get errors every time (i work with SDL2 if this gonna help)

**pseudo code**:

```
///some class
handler hand = new handler();
gameObject pla = new player();
hand.addObject(pla);  ----> here

/// handler class

vector<gameObject> objects;

void addObjects(gameObject object)
{
   objects.push(object);  ------> specially here
}

```

**C++ code**

```
/// game class

handler hand = new handler();
gameobject* pla = new player();
hand->addobject(pla);

/// handler class

vector<gameobject*> objects;

void addobject(gameobject* object)
{
    objects.push_back(object); -----> here
}

```

i have searched for a week and nothing i used **unique\_ptr** but nothing every time new error some times **std::bad\_alloc** sometimes **objects has been deleted**

i am confused please guide me to the right way to do this

thank you

# Answer
Your crashes is mostly because of improper handling of the object's ownership.

When you add something to a collection, you should clearly understand who's owning the object. Is that handler owns the added objects now, and may delete those when time has come? Or is that handler only references the objects, and there's some other subsystem that will destroy the objects? Get clear with ownership first, because implementation will differ.

Assigning `unique_ptr` to a collection assumes ownership is transferred to that collection. There's no other way to `push_back` the `unique_ptr` into a `vector`. There can't be multiple copies of the same `unique_ptr`. Well, technically you could construct multiple `unique_ptr` from the very same raw pointer, but that's a big no-no.

In case your `handler` will own the objects, the next example is possible:

```
#include <vector>
#include <memory>

using std::vector;
using std::unique_ptr;
using std::move;

/// gameobjec base class
class gameobject
{
public:
    virtual ~gameobject() {};
};

/// player class
class player: public gameobject
{
public:
    float* some_data;

    player(int map_size)
    {
        some_data = new float[map_size];
    }

    ~player()
    {
        delete[] some_data;
    }
};

/// handler class
class handler
{
public:
    vector<gameobject*> objects;
    vector<unique_ptr<gameobject> > objects_auto;

    void addobject(gameobject* object)
    {
        objects.push_back(object);
    }

    void addobject(unique_ptr<gameobject>& object)
    {
        objects_auto.push_back(move(object));
    }

    void add_raw_to_auto(gameobject* object)
    {
        objects_auto.push_back(unique_ptr<gameobject>(object));
    }

    ~handler()
    {
        // objects behind raw pointers must be explicitly deleted
        for(auto obj: objects)
            delete obj;

        // nothing needs to be done about unique_ptr containers
    }
};

int main()
{
    handler* hand = new handler();

    for(int i=0; i<100; ++i)
    {
        // add raw pointer to a collection of raw pointers
        gameobject* pla = new player(i);
        hand->addobject(pla);

        // add unique_ptr to a collection of unique_ptr
        unique_ptr<gameobject> pla_auto(new player(i*2));
        hand->addobject(pla_auto);

        // add raw pointer to a collection of unique ptr
        gameobject* pla_raw = new player(i);
        hand->add_raw_to_auto(pla_raw);
    }

    delete hand;
}

```

Since in `handler` you're storing the pointer to a base class, you should make virtual destructor there, so the collections of pointers to different objects inherited from that base class will be properly destroyed. A memory leaks are possible if the base class' destructor isn't virtual.
> 1 votes

---
Tags: c++, sdl2, gameobject, objects, memory
---


# Question
Title: The A * algorithm in the map has many moving objects
I am using the A * algorithm for my game, it is a kind of Isometric map with lots of tiles. If all the game objects are trees, rocks, houses and only one game object is a moving hero, the A * algorithm works well because then all objects are objects static except for my hero. I use a function: Check\_Block (i, j) where i is the row and j is the column of the map. This function will return false if at that location there is a rock or house or tree, etc. But if there are many heroes moving together, I will not be able to use this function because the heroes are not in position permanent.

I have a solution if the hero is in a certain cell, Map \[i\] \[j\] = Hero. But if there are many heroes in the same box, I think this solution no longer good. Can someone show me a solution?

# Answer
Your issue is that you are over complicating your requirements.

If a hero occupies a cell, then the cell is blocked. Do not allow "hero" objects to occupy the same cell. A\* only cares if the cell is blocked or not, so all you need to do is tell it if the cell is walkable.

Whenever a hero moves(changes cell), update your grid. Mark it's previous position(cell) in the grid as clear, and mark it's new position(cell) as blocked.

Allow the "hero" objects to store their own position in the grid.

Once all positions are updated, compute new paths for all "hero" objects.

Your algorithm should be as follows:

```
for hero: heroes loop
    grid[hero position] = clear
    hero update position
    grid[hero position] = blocked
end loop

for hero: heroes loop
    compute A* path for hero
end loop

```

The A\* algorithm does not care what is in the cell; Only if it is blocked, or clear.

What constitutes blocked or clear is up to you. You could decide that any number of heroes can occupy the same cell, in which case, a cell with another hero in it, is traversible to other heroes. This has nothing to do with A\*, but is part of your game rules.
> -1 votes

---
Tags: c++, sdl
---


# Question
Title: How can I change the Google Play Console language?
How can I change the Google Play Console language? Here you can see that the language is not English:

# Answer
From the Google Support Page:

> The Admin console uses the same language you choose in your Account settings.

So to change the language you have to change your language in account settings. To do this follow these steps (from Google Support again):

> 1. Sign in to your account.
> 2. In the "Account preferences" section, select **Language & Input Tools**.
> 3. Choose **Language**.
> 4. To change your language, select edit **Edit** .
> 5. Choose your language from the dropdown box and select **Ok**.
> 27 votes

# Answer
In the url change hl=ru to hl=en.
> 22 votes

# Answer
Nowadays, i could not see language prefs on Google Play Console. Instead of Play Console, you can change language via Google Account. After you click on it,

* Click **Data & personalization**,
* Scroll down the page until the **General preferences for the web** title and then you will see the **Language** preference. You can change account language with this way.

After you completed steps above, Go to Play Console. You will see the portal language which was changed.
> 5 votes

# Answer
You can do this by changing URL only. As it is a client account, I don't want to mess things up for him by changing whole account language so I only add parameter `hl=en` in the URL.

For example, change this:

* `https://play.google.com/apps/publish/?account=`

Into this:

* `https://play.google.com/apps/publish/?hl=en&account=`
> 3 votes

# Answer
I had same issue and changing account settings language didn't help. But I solved it by changing default Chrome language. So if you tried changing your account language settings and it didn't work, go to chrome://settings/languages and move your preferred language to the top. Reload page and it should work
> 1 votes

---
Tags: google-play
---


# Question
Title: Prevent replay attacks on multiplayer character movement
When a client first connects to the server a Diffie-Hellman key exchange occurs to securely get private encryption keys to encrypt all packets.

The problem comes in: what if someone sniffing packets resend a "move right" command? Since they are simply resending the packet the encryption is still correct, and since movement commands can come at anytime, multiple times, the server cant just ignore multiple of the same packets.

**Q:** How do i prevent a packet-sniffer from replaying a move-right player command.

Edit: would the answer be timestamps included in the encrypted message? and then maybe any movement commands that are older then 500ms are dropped?

# Answer
The most likely way such packets could occur is through cheats that people would code for your game. Either the cheat would hijack the connection on the client's side and send duplicate packets, or your client itself would be compromised by the cheat and send whatever the cheater wanted. No amount of encryption can protect against that, but what helps against both these approaches is making sure that if the server receives more packets, it doesn't mean that more things happen.

The best way to do this would be to write your netcode such that each player sends only one packet per tick, containing all actions the player performed during that tick. This packet should contain the *number of the tick* those actions occurred on. Then your netcode could filter out any inappropriate packets by tick (ignore packets whose tick is not unique, or whose tick number is a lot too early or too late for the current game time).

It needs to be verified separately that the actions can all be performed by the player in that tick, but that verification should strictly be part of your game code and not your netcode. Also, client packets may arrive at the server out of order, so you should take care to process them in order via some method, but how to do this properly is beyond the scope of your question.
> 3 votes

---
Tags: networking, multiplayer, client-server, security, packet
---


# Question
Title: I'm getting empty errors Unity 2019.2.14f1 Windows 10
A week ago I was editing a script in my Unity Project with VSCode(I normally work in Visual Studio) and saved it. As soon as I saved it 4 blank errors popped up. Since then I've tried everything to get rid of them but to little avail. Please, help me.

I've already done a lot of searching and the main thing that comes up is to switch my scripting runtime to .Net 3.5. But in Unity 2019.2.14f1 the version I'm using this is no longer supported. They are also talking about Windows 7 but I'm on Windows 10.

https://forum.unity.com/threads/four-blank-errors-in-each-new-project.599980/

I tried to delete the meta of all script files but that did not help. I've tried to uninstall everything of Unity, and I mean everything. I uninstalled and deleted all Unity versions, the hub, and all app/roaming data. The reinstalled Unity. I made an empty project and the error was gone until I made 1 new script and the error reappeared.

Only when I have no scripts in my project the error disappears.

What do I do now? Any suggestions?

# Answer
Go to C:\Program Files\Unity\Hub\Editor\2019.2.14f1\Editor\Data\Tools\RoslynScripts folder Open the batch file in notepad and paste the following:

```
 @ECHO OFF
 set APPLICATION_CONTENTS=%~dp0..\..
 echo host set to %APPLICATION_CONTENTS%
 "C:\Program Files\Unity\Hub\Editor\2019.2.14f1\Editor\Data\Tools\Roslyn\csc.exe" /shared %*
 exit /b %ERRORLEVEL%

```

Found the answer here: https://answers.unity.com/questions/1680858/blank-console-error-on-empty-project-with-a-single.html
> 1 votes

---
Tags: unity
---


# Question
Title: How to set my game to load low-level drivers from a different System32 folder path
The title says it all I'm doing a test with my game and I need to know how to set it up where my game loads low-level drivers from a System32 Folder that is in another path instead of this

example: C:\Windows\System32

a new path I want to have my game load drivers from: D:\Windows\System32

and can I make my game load low-level drivers from this path with some c++ coding in visual studio?

# Answer
Usually games load their .dlls from several places, including their own folder. I recommend putting anything you need loaded in the folder along with the game.

Requiring a D:\Windows\System32 would be not be a good idea because not everybody has a D: drive.
> 0 votes

# Answer
I would advise against doing what you're trying to do, simply because you'll waste a lot of time.

Microsoft released drivers are released by, well... Microsoft. They integrate with the OS they produce. In ways that you do not want to mess with or work around: you'll most likely miss a reference: You'll set up Driver A that usually relies on Driver file X. If you forget to put that Driver file X at the correct location (because it's not documented, or you don't even know it exists), it will use the system one and have your tests fail, or it could simply crash.

Instead, I suggest you set up a workstation just for that, to test the "other set of drivers". The process is much more straight forward, is much more documented (hey you can do a system backup right after you set it up and restore it when you have more tests!), much less error prone, and will end up having you wasting much less time.
> 0 votes

---
Tags: filesystem, operating-system
---


# Question
Title: Deactivate current object in array and activate next one by using button click?
How to deactivate current object in array and activate next one by using button click?

```
public GameObject[] gameObjects;
private int numOfgameObjects;

void Start()
{

  //current object
  gameObjects[0].SetActive(true);

  int numOfgameObjects = gameObjects.Length;

  for (int i = 0; i < numOfgameObjects ; i++)
  {
      gameObjects[i].SetActive(false);
  }

}

public void NextPrefab_ButtonClick()
{
  // Some Code to deactivate current object and activate next one
}

```

# Answer
> 1 votes
This is pretty trivial: just track the index of the current selection in a variable, and increment that variable when you want to select the next item. You may want to work your way through some beginner C# tutorials if this use of variables is unfamiliar.

```
public GameObject[] gameObjects;

// Track which object we've currently selected.
int _selectedObjectIndex = -1;

public void SelectObject(int selectedIndex)
{
    // Disable the previous selected object, if any.
    if(_selectedObjectIndex >= 0)
        gameObjects[_selectedObjectIndex].SetActive(false);

    // Update our selected index and activate the corresponding object.
    _selectedObjectIndex = selectedIndex;
    gameObjects[selectedIndex].SetActive(true);
}

void Start()
{
    for (int i = 0; i < gameObjects.Length; i++)
    {
        gameObjects[i].SetActive(false);
    }

    SelectObject(0);
}

public void NextPrefab_ButtonClick()
{
    // Compute the next index in the list.
    // The modulo operator % "wraps" our index around to zero when we pass the last object.
    int nextObjectIndex = (_selectedObjectIndex + 1) % gameObjects.Length;
    SelectObject(nextObjectIndex);
}

```

---
Tags: unity
---


# Question
Title: MMO Client-Server Spoofing Vulnerabilities
Ive created a working authoritative client-server system using LiteNetLib for my game however im wondering if packet sniffing+modification is a real worry i should be developing for.

I read some information that other Client sniffing the packets of another client is pretty much impossible since the packets are routed through their ISP. **Therefore:** should i only worry about the client causing problems for the server, instead of also worrying about clients causing problems for other clients?

Currently im encrypting every packet sent by the client including movement commands such as 'move left'. My idea is that this will make *packet-sniffing* fail, *packet-modification* fail, and *packet-spoofing* fail.

If i remove my encryption doesn't that mean someone can spoof a packet by changing the packet source in the header? (thus sending game commands for another client - moving another player!). Usually when its encrypted i know that only the client with the secret key could have sent it, thus validating the packet source.

I see everyone saying that people shouldn't encrypt general traffic like this, but whats the truth here! Whats the best way?

# Answer
IP spoofing on the public Internet has become difficult because most ISPs take countermeasures to prevent it.

There isn't much one can do to screw with people's games, unless they control a router between the victim and the server. This in practice means the attacker would need to be (or have the powers to compel) an internet service provider or be on the same network as the victim and control their home router.

Unless your game is very, **very** competitive, most people won't bother with the logistics which are required to do MITM attacks or packet spoofing just to cheat. But there are a couple scenarios which might be worth protecting:

* Password authentication. If you send unencrypted passwords over the Internet, they might get eavesdropped. Not only could that lead to people getting their accounts on your game stolen, they could also lose accounts on other services, because there are still people who reuse passwords (even if they really should not).
* Real money trading. Does your game allow players to trade? Trade items which are so rare that people might pay real-world money for them? Then you need to secure those transactions, or people will try to perform MITM attacks to steal items from players.

For those reasons, adding encryption to your network protocol certainly doesn't hurt. Howerver, remember the golden rule of cryptography: **Never invent your own crypto!** Use tried and true algorithms and protocols, invented and implemented by people who know what they are doing. One out-of-the-box solution for this very scenario is TLS. One nice thing about TLS is that it starts every connection by exchanging an unique cryptographic key for that session. And that exchange happens in a very clever way so it can not be intercepted. That means one client doesn't have the knowledge to eavesdrop or impersonate other clients.
> 2 votes

---
Tags: networking, multiplayer, client-server, mmo, security
---


# Question
Title: How and why can Physics2D.Raycast method be used in an if statment, as it does not return a boolean value?
Pretty much as the title asks, why is this code possible?

```
if (Physics2D.Raycast(...)) {

}

```

even though the method itself returns `RaycastHit2D`?

# Answer
> 3 votes
The answer to questions about the Unity API can generally be found in the docs:

> RaycastHit2D implements an implicit conversion operator converting to bool which checks \[the collider\] property allowing it to be used as a simple condition check for whether a hit occurred or not.

What this means is that the `RaycastHit2D` structure's code looks something like this under the hood:

```
public struct RayCastHit2D {
    public Collider2D collider;

    public static implicit operator bool(RaycastHit2D hit) {
        return hit.collider != null;
    }
}

```

This says to the compiler "wherever you see a `RaycastHit2D` used like a boolean, you can automatically convert it by running this method (which returns `true` if there was a collider hit, and `false` otherwise), without requiring the user to type out the cast or comparison explicitly.

---
Tags: unity
---


# Question
Title: How to keep instantiating enemies up to a set max?
I am creating a castle defense game where the enemy regulary spawns (upto limit of 24 ). After the enemy reaches 24, I want to stop creating clones. So far, I have been successful but I want to make sure that if the enemy reaches 23, it starts instantiating upto 24. How?

```
    public GameObject[] spawnPosition;
    public GameObject enemy;
    [SerializeField]
    private float startTime;
    private float timeForSpawn;
    public float speed;
    public float enemyLimit;
    public List<GameObject> enemyList;
    public bool stopInstantiating;
    void Start () {
        stopInstantiating = false;
        enemyList = new List<GameObject> ();
        enemyLimit = 24f;
        timeForSpawn = startTime;
    }

    void Update () {

        Spawn ();
    }

    void Spawn () {

        timeForSpawn -= Time.deltaTime;
        if (timeForSpawn <= 0 && stopInstantiating == false) {
            timeForSpawn = startTime;
                for (int i = 0; i <= 2; i++) {
                Instantiate (enemy, spawnPosition [i].transform.position, Quaternion.identity);
                if (enemy != null&& stopInstantiating == false) {
                    enemyList.Add (enemy);
                    if (enemyList.Count >= enemyLimit) {
                        stopInstantiating = true;
                }
                }
            }
        }
}

}

```

I see that the list doesn't update itself as I delete the gameObjects in game. How to make sure that list updates and work on that.

# Answer
> 1 votes
There are a couple of ways to approach this problem. You could:

* Run a function that checks if an item in the list is empty, then remove that item.
* Use an array instead of a list, then give the Game Object the index number when instantiating. Now you can easily clear the array when the Game Object is destroyed. (This is probably the best and most efficient way.)
* Don't bother clearing, just check the entire list/array for empty elements when trying to spawn a new Game Object.

Since you know the maximum amount of instances that will be in the list at the same time, you should use an array instead since it's more efficient.

# Answer
> 1 votes
How about this:

* The enemy spawner has a counter of enemies, an int initialized at 0.
* Every frame it checks if the counter is bigger than some maximum.
* If not, you spawn an enemy, increment the counter and then, add a listener to the enemy.
* When the enemy dies, it fires off a method to decrease the counter again?

I can write down some pseudocode for you if you need it.

Edit: Here's what I came up with with. Mind you, this is pseudocode...

public class EnemySpawner{
    int enemyCount = 0;
    int enemyMax = 10;

    public void EventTick(){
        if(enemyCount < enemyMax){
            SpawnEnemy();
        }
    }

    //the important part goes here
    public void SpawnEnemy(){
        GameObject go = Instantiate(EnemyClass, Location, Rotation);
        go.EnemyKilled.AddListener(this);
        //after creating the enemy, you start listening to it's event
        enemyCount++;
    }
}

//now the tricky part
public class Enemy{
    public Event EnemyKilled;    //this creates something called "an event"

    public void OnDestroyed(){
        EnemyKilled.Invoke();    //this calls it out, everyone listening will react
    }
}
```

---
Tags: unity, c#
---


title: OpenGL texture shows as a white square

text:
# Question
Title: OpenGL texture shows as a white square
I am trying to draw a simple 32x32 PNG image using SharpGL and OpenGL 2.1. Despite many hours of searching, reading answers to similar questions, nothing could solve my issue. The image is showed as a white square.

I tried debugging OpenGL using `glGetError()` but it always returns 0. I have no idea of what could be the problem.

Some help would be very appreciated!

**Loading method**

```
public static GLImage LoadImagePNG(OpenGL gl, Bitmap bmp)
{
    bmp = ResizeTo(bmp, 32, 32);

    uint[] textures = new uint[1];
    gl.GenTextures(1, textures);

    uint texture = textures[0];

    gl.Enable(OpenGL.GL_TEXTURE_2D);

    BitmapData data = bmp.LockBits(
        new Rectangle(0, 0, bmp.Width, bmp.Height),
        ImageLockMode.ReadOnly,
        PixelFormat.Format32bppArgb
    );

    gl.BindTexture(OpenGL.GL_TEXTURE_2D, texture);

    gl.TexImage2D(
        OpenGL.GL_TEXTURE_2D,
        0,
        4,
        bmp.Width,
        bmp.Height,
        0,
        OpenGL.GL_RGBA,
        OpenGL.GL_UNSIGNED_BYTE,
        data.Scan0
    );

    Console.WriteLine(gl.GetError());

    bmp.UnlockBits(data);

    gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_S, OpenGL.GL_CLAMP_TO_EDGE);
    gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_T, OpenGL.GL_CLAMP_TO_EDGE);
    gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, OpenGL.GL_LINEAR);
    gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, OpenGL.GL_LINEAR);

    // not disposing the Bitmap on purpose (for now)

    return new GLImage(texture, bmp);
}

```

**Render method**

```
public static void DrawImage(OpenGL gl, GLImage img, double x, double y)
{
    gl.PushMatrix();
    gl.Translate(x, y, 0.0D);

    gl.ActiveTexture(OpenGL.GL_TEXTURE0);
    gl.BindTexture(OpenGL.GL_TEXTURE_2D, img.TextureID);
    gl.Enable(OpenGL.GL_TEXTURE_2D);

    gl.Begin(BeginMode.Quads);
        gl.TexCoord(0.0f, 0.0f); gl.Vertex(0, 0);
        gl.TexCoord(1.0f, 0.0f); gl.Vertex(img.Width, 0);
        gl.TexCoord(1.0f, 1.0f); gl.Vertex(img.Width, img.Height);
        gl.TexCoord(0.0f, 1.0f); gl.Vertex(0, img.Height);
    gl.End();

    gl.Disable(OpenGL.GL_TEXTURE_2D);

    gl.PopMatrix();
}

```

and `GLImage` being a custom class

**GLImage**

```
public class GLImage
{
    public uint TextureID { get; private set; }

    public Bitmap Bitmap { get; private set; }

    public double Width
    {
        get
        {
            return this.Bitmap.Width;
        }
    }

    public double Height
    {
        get
        {
            return this.Bitmap.Height;
        }
    }

    public GLImage(uint textureID, Bitmap bmp)
    {
        this.TextureID = textureID;
        this.Bitmap = bmp;
    }
}

```

Thank you!

# Answer
> 0 votes
*I'm the OP. As I posted as a visitor and registered afterwards, I don't seem to be able to answer any comment or edit my post. So I am going to answer here.*

---

## EDIT: Solution !

Alright, I finally made it work. The issue was quite simple (as always, right?). I did only one little thing differently between home and work: I was loading the image in a different thread. Just that. Now it works.

---

Thanks for your answers ebv and justix. Concerning justix, as Maximus Minimus said, I'm using OpenGL 2.1 so your answer doesn't apply to my case. I still appreciate your help!

I had the issue at work, got home and tried the same code there. It didn't work at first and then figured that my resizing method `ResizeTo` wasn't working properly: it was returning a full transparent image. It doesn't really explain why it showed a white square at work, because it drew a black square here at home which made more sense to me (R, G, B and A at 0 and blending disabled).

I fixed my method `ResizeTo`, enabled OpenGL's blending and it worked! I will try that code tomorrow at work and keep you guys updated.

---

**New method `ResizeTo`**

```
private static Bitmap ResizeTo(Bitmap bmp, int width, int height)
{
    return new Bitmap(bmp, new Size(width, height));
}

```

**Drawing**

```
gl.Enable(OpenGL.GL_BLEND);
gl.BlendFunc(OpenGL.GL_SRC_ALPHA, OpenGL.GL_ONE_MINUS_SRC_ALPHA);
DrawImage(img, 20, 20);
gl.Disable(OpenGL.GL_BLEND);

```

---

@ebv: I checked the internal format which I set to 4, and changed it to the constant GL\_RGBA8. Both worked just as well.

# Answer
> 0 votes
And check the "internal format" parameter of glTexImage2D() (now 4). Should be something like GL\_RGBA8 if it is a 4 channel texture with byte values.

---
Tags: c#
---


# Question
Title: Transform.RotateAround with Joystick Rotation
I want to rotate one object around another, so that it matches my current joystick rotation. I know `Transform.RotateAround` does this but I can't seem to find a way to match it with my joystick rotation.

This is my code so far:

```
void Update()
{
    joystick = InputManager.ActiveDevice;

    moveInput= joystick.RightStickX;

    if(currentState != CoreplayerState.stager) {
        RotateChar();
    }
}

public void RotateChar() {
    transform.RotateAround(target.position, zAxis, moveInput * rotateSpeed);
    transform.rotation = target.rotation;
}

```

# Answer
We can think of the x, y input on the joystick as just another vector in our game world. Transforming it through the pivot lets you match the plane of rotation to the orientation of the pivot.

How's this work for your use case?

```
public class JoystickMatch : MonoBehaviour {

    public Transform pivot;
    public float radius = 1f;

   void Update() {
       var joystick = InputManager.ActiveDevice;
       var heading = new Vector2(joystick.RightStickX, joystick.RightStickY);

       if(heading != Vector2.zero) {
           transform.position = pivot.TransformPoint(heading.normalized * radius);
           transform.rotation = pivot.rotation;
       }
   }
}

```
> 0 votes

---
Tags: unity, c#, rotation, joystick
---


# Question
Title: how to apply force/impulse perpendicular to the moving direction in box2d
How can i apply or impulse to an object perpendicular to its moving direction in a top down game. Like if object is moving up, i press left or right, then force or impulse should be applied to left or right direction(object can be at any angle).

# Answer
I used the below code which worked for me.

```
player.ApplyForce(  multiply(new b2Vec2(Math.cos(player.GetAngle()+Math.PI/2), Math.sin(player.GetAngle()+Math.PI/2) ),force_Mag),  player.GetWorldCenter() );

```
> 0 votes

---
Tags: box2d
---


# Question
Title: How to reset scene (stage1) when selecting it from Level stagemain menu
Good day I have a problem when the player finish stage 1 the screen look like this

Then going back to selecting level

When I try to play the stage 1 again. I want to reset the stage 1 so i can play it again. I only use Scene.LoadScene("stage1") in main menu to go to stage1 and Scene.LoadScene("mainmenu") to back to main menu

# Answer
> -1 votes
Just reload your scene when level is complete.

---
Tags: unity, c#, scene, scenemanager
---


# Question
Title: C++:Segmentation fault (core dumped) while creating gameobject
i made a small code to debug and i get this error

player inherit from gameobject

code

```
///main
#include "game.h"

 gameobject* pla;

int main()
{

    std::vector<gameobject*> objects;

    gameobject* pla = new player(32,32);  -----> error is here

    objects.push_back(pla);
    cout<<objects[0]->numberID<<endl;
    return 0;
}

/// gameobject
pragma once

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "game.h"

class gameobject
{

    public:

        virtual ~gameobject(){};
        virtual void init()=0;
        virtual void tick()=0;
        virtual void render(SDL_Renderer* ren)=0;
        virtual void destroy()=0;
        virtual void setVelx(int velx)=0;
        virtual void setVely(int vely)=0;

        int numberID=0;

    protected:

        int width = pos.w;
        int height = pos.h;
        int posx = pos.x;
        int posy = pos.y;

        float velox;
        float veloy;

        SDL_Rect crop;
        SDL_Rect pos;

        SDL_Texture* tex;

////player.h

#pragma once

#include "gameobject.h"

class gameobject;

class player : public gameobject
{

public:

    void init() override;
    void tick() override;
    void render(SDL_Renderer* ren) override;
   // SDL_Renderer* renderer;
    player(int pwidth,int pheight);

    void destroy() override{
        this->~player();
    }

    void setVelx(int velx) override;
    void setVely(int vely) override;

    int i = 0;

private:

    ~player() override;

};

/// player.cpp

#include "player.h"

player::player(int pwidth, int pheight)
{

    this->pos.w = pwidth; //width
    this->pos.h = pheight; // height
    this->pos.x = 100; //posx
    this->pos.y = 100; //posy

    // cout<<"yes iam ren : "<<ren<<endl;

    this->numberID = gameobject::numberID;

    gameobject::numberID++;
    //this->tex = IMG_LoadTexture(ren,"/home/younlok/Desktop/dash/res/pss.png");
    this->tex = game::textures[0];
    crop.x = 0;
    crop.y = 0;
    crop.w = 32;
    crop.h = 32;

    //game::hand->addObject(this);

}

void player::init()
{
}

void player::tick()
{

    this->pos.x += this->velox;
    this->pos.y += this->veloy;

}

void player::render(SDL_Renderer* ren)
{

 SDL_RenderCopy(ren,tex,&crop,&pos);

}

void player::setVelx(int velx)
{
    this->velox = velx;
}

void player::setVely(int vely)
{
    this->veloy = vely;
}

player::~player(){}

```

# Answer
*What is a segmentation fault?*

> Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.”

(Source).

*Huh? What? Where and how am I doing this??* During the *construction* of your object (not exactly in the constructor).

> — Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

(Source)

Let's look at your `gameobject` class.

```
class gameobject
{
    ...

    protected:

        int width = pos.w;
        int height = pos.h;
        int posx = pos.x;
        int posy = pos.y;
        ...
        SDL_Rect pos;

```

You're trying to use `pos` before it's been initialized.

Don't do that.

Here are a couple of suggestions:

* default-initialize your values with literals (i.e. using explicit default values) like 0 and *not* with another object in your class (I think that's kind of weird and risky).
* define a code standard that if the values are not default-initialized in the header, that's because they're initialized in the constructor.
* (this one my favourit) don't even use those four variables, because you already have a `SDL_Rect pos;` that has the information and that's against the DRY principle.

---

As a side note, this is weird and makes me suspect a design flaw:

```
    void destroy() override{
        this->~player();
    }

```

This implies that the `destroy()` method is the last one called before the object is released.

Why do you need a `destroy` method when you could just call `delete myPlayer;`?

Which then suggests you should take a look into smart pointers to avoid all of this memory management.
> 0 votes

---
Tags: c++, objects, memory
---


title: Help me to understand Geometry Clipmaps

text:
# Question
Title: Help me to understand Geometry Clipmaps
Ok, so It's a mesh of frames (high to low density) around the camera that adjusts the vertices Z by height-map values. But what happens, how does it work outside those frames? Its like the coarsest grid that somehave blends with the most outside clipmap (green in pic) frame? Or anything outside it, is not culled?

Edit: also how do collisions with terrain work, if the height values are calculated in vertex Shader?

# Answer
Since you mentioned the comments above were helpful, I'll try to elaborate on them as an answer.

> Ok, so \[a GeoClipmap is\] a mesh of frames (high to low density) around the camera that adjusts the vertices Z by height-map values. But what happens, how does it work outside those frames?

There is no "outside those frames". If you hit the edge of frame 4 and you still have more depth to cover in your camera's frustum, then you draw a frame 5. If you hit the edge of that and you still have more, you draw a frame 6. Beyond each frame is just another frame, until you've filled the volume that your camera can see, at which point you stop drawing.

Note that each clipmap frame is not necessarily a full ring. Many implementations use the frames just as an organizing structure, where the geometry being rendered is actually a collection of quad chunks. You're free to cull individual chunks from a frame that are too far away/left/right/behind to be visible in your camera's frustum.

> How do collisions with terrain work, if the height values are calculated in vertex Shader?

The height values used for drawing may be computed in the vertex shader in your case. The height values used for collision can be a completely separate set of data that you maintain and check on the CPU side.

For instance, you might want to render detail down to a granularity as fine as 5cm in the immediate neighbourhood of your camera, but you might be satisfied with a collision resolution of half a meter or more. You can use the same generator function to generate heights at your desired collision resolution, and use that data set to power your physics simulation, completely independent of what the GPU is drawing. This also lets you get a consistent physics resolution over your whole simulated area, rather than dealing with inconsistent physics between near & far objects due to different terrain resolution, or artifacts when transitioning from one resolution to another.
> 1 votes

---
Tags: level-of-detail
---


# Question
Title: Where can I find an accurate map of Earth for a real-time third-person game?
I want to create a game that will allow the player to move to any place on Earth. The game will not be first-person, but it will be possible to zoom in quite close nonetheless. What I am lacking is an accurate height-map of the planet. Textures such as albedo, specular or normal would also be very helpful.

I don't know if such textures exist, but an "accurate" height-map should have a resolution of at most a few meters.

The textures do not have to be 100% real. Some parts can be procedurally generated, as long as they look "realistic".

# Answer
> 0 votes
NASA has your back with the NASA Earth Observing System: https://eospso.nasa.gov/ The project has topography and albedo images of earth: https://visibleearth.nasa.gov/collection/1484/blue-marble

---
Tags: terrain, heightmap
---


# Question
Title: How would one implement having a total set of TCG cards vs the specific instances of said cards in a player's deck, hand, field, etc?
For example, let's say in total there may be 5 cards that are in the game, let's use:

Axe-thrower (3-cost, Creature, 5 Power, 3 Defense, Rush ability)

Ice Elemental (2-cost, Creature, 2 Power, 5 Defense, Crystalized ability)

Party Trick (3-cost, Spell, Swap the Power and defense of a single creature)

Blademaster (3-cost, Creature, 3 Power, 3 Defense, Gains +1/+1 for every other creature on the field)

Minefield (3-cost, Trap, Deal X damage to all enemies, where X is the number of creatures on the opponent's side of the field)

With those in mind, some have default values, which would be simple to store in the database, some would likely remain as 0's or another default value until their effects came into play, etc. Simple enough.

My question is more about how to handle the cards and their values once they're in decks, a player's hand, and on the field.

For example:

The Axe-Thrower is a 5/3 creature, but let's say it's buffed in some fashion - how am I differentiating an object which is the base version of a card, version the version which is modified in some way? The only values stored in the DB Would be the base values, not the modified ones, correct? Unless there was some kind of suspend functionality in which case I would have to track the modified values as well.

My initial thought of an implementation, at least for the Database side of things was as follows:

Cards (ID, Name) -- Base card

CardVersions (ID, CardID, Version, ImagePath, CardStatsID) -- Cards' stats dependent on version

CardStats (ID, Cost, Power, Defense) -- Stats for a given CardVersion

Now those would be the "base" cards, the following could be how the specific instances are handled?:

PlayerCards (ID, PlayerID, CardID, Count) -- Player's cards

Decks (ID, PlayerID, Name) -- Player's decks

DeckCards (ID, DeckID, PlayerCardID, Count) -- How many of a card in a given deck

Which is a decent start, I think, for the cards in a player's deck.

For the cards in a player's hand / on their field, would those all simply be references to the PlayerCards with objects that have modifiable versions of the stats? For example, a *GameCard* with Original Stats and Modified Stats, where the majority of the time, the Modified Stats will be the Original Stats to start, but will change as the cards are buffed or their abilities are invoked?

Am I missing a super-simple solution to this, what I would imagine, common case for TCGs?

# Answer
If you carefully read the text of Magic: the Gathering cards you will notice a distinction made between cards and 'permanents' and 'spells'. When a card is in play, say representing a creature that has been summoned, it is not just a card but a permanent. Things that aren't cards - like ephemeral 'tokens' made by other cards - are ALSO permanents if they're in play.

From a computer implemention perspective I think of this as having two different levels. Cards have all sorts of statistics associated with them but are essentially static. Very few very obscure effects track the identities of actual cards themselves. Most effects affect permanents, which would come in a few types: those that are a card would be a CardPermanent which contains a pointer to a card and represents a physical card on the battlefield, while a creature token that is created as a 'copy' of another permanent might be a TokenCopyPermanent that contains a pointer to another permanent.

Effects mostly affect permanents. Permanents can be enchanted, destroyed, damaged, blocked, etc. The card inside is mostly unaffected, but for example if a permanent that contains a card is destroyed, the card inside goes to the discard pile.

Your hand contains plain cards. You can't have tokens in your hand or in your deck. When you cast a card it goes onto the stack, where it's a SPELL rather than a permanent, and again you can have effects that affect spells (countering them, copying them, etc.) and you can create noncard spells, although I don't think MTG calls them 'tokens' in this case.

This multi level approach separates things quite nicely and I have used it in an implementation of a subset of magic's rules. It seems to have covered everything I've needed to do so far.
> 2 votes

---
Tags: game-design, databases
---


title: What scaling system to use in Box2d?

text:
# Question
Title: What scaling system to use in Box2d?
I'm worried about this *Caution* box from the Box2d manual:

> Box2D is tuned for MKS units. Keep the size of moving objects roughly between 0.1 and 10 meters. You'll need to use some scaling system when you render your environment and actors. The Box2D testbed does this by using an OpenGL viewport transform. DO NOT USE PIXELS.

I don't want to use OpenGL since I know nothing about it. I'm using SFML to render my game.

# Answer
> 1 votes
This caution box is telling you to not base your physics simulation on pixels. The pixels your game will be able to show will not be the same across all device, and is not a reliable measure to have your game consistent.

What it suggests is that you use "real world" sized objects in your *simulation*, and use your rendering engine to *display* the simulation. You really want to separate the two concerns and think in "real world" objects rather than in "pixels" (these become smaller each year that goes by).

In their examples, they use the concept of OpenGL's *viewport*, which is used to control what is rendered on the window.

In your case, might want to look into SFML's View. I have not worked with SFML a lot, but this is basically a wrapper of OpenGL's *viewport* concept.

So for example, you'll simulate your car with real dimensions (say 1.8m x 4.6m), you'll stick a sprite which has that scale to it, but you'll ask SFML to render a parking lot of 200 x 200 units (where units are 'meters' in your game). It'll scale the *view* appropriately so that it fits in your render window.

---
Tags: box2d, sfml
---


title: Rest API as Remote Data Storage

text:
# Question
Title: Rest API as Remote Data Storage
I'm currently working on a minor multiplayer project which is made like a hacking simulator where your character can login to a "console"-like interface to permanently manipulate the system with various commands. But now i want to convert this to a more persistent model like if two characters enter the same systems minutes apart, the second character should be able to see if the first character left traces of him being there and continue his damage or counter it.

Could all this be handled by a Rest API or what would be the more "right" way of doing it. ?

This will also work as the authentication for the player, which will initialize all multiplayer behaviour in the game.

# Answer
The short answer to your question is **yes**, a REST API is one way to store persistent data on a server than can be accessed by multiple players. But keep in mind that "REST API" is a category, not a ready-made solution you just install and use. A REST API is typically going to require three major components:

* A host or server (this by itself is a broad category that encompasses countless possible solutions)
* A database to store the data, such as MySQL or MongoDB
* Code that defines your API, in a language such as JavaScript or PHP. Your API code will handle and respond to web requests from clients, and interact with the database to read and write data.

Learning how to create a REST API can be overwhelming if you have no prior web development experience. *How* to build a REST API would be far too broad and subjective to cover in any one question. You may find it easier to use a BaaS platform that simplifies some of the setup for you, but these can come with their own bugs and limitations.
> 0 votes

---
Tags: unity, mmo, server, inventory, rest
---


# Question
Title: Pattern for modular ScriptableObject-Database?
Lets say we want to store game data inside of scriptableObjects and we have plenty of them... So we need to find a way to store them efficiently in a modular way.

What pattern could we use to code a scriptableObject database for providing a substainable base for our game data- scriptableObjects?

And are there any patterns or structures for extending our game data - scriptableObjects in order to construct them modular and flexible aswell ?

# Answer
You haven't provided enough detail to give a specific answer to your question, but here are some broad strokes:

ScriptableObject assets in your Unity source project are saved as individual files in the project `Assets` directory.

If you've got dozens of these asset files, you can probably just manually organize them into folders. E.g. `Assets\Data\Enemies\Normal` and `Assets\Data\Enemies\Bosses`, and refer to them from your components with serialized field references. E.g.

```
public class EnemyData : ScriptableObject {
    [SerializeField] private int hp = 10;
    public int HP => hp;
}

public class Enemy : MonoBehaviour {
    [SerializeField] private EnemyData data;
    private int hp;

    void Start() {
        hp = data.HP;
    }
}

```

If you've got hundreds or thousands of files, it can get cumbersome to manage them all in the project pane and to reference them from your scripts. Then, there are several ways to ease the management of these assets:

* You can create a custom editor window for browsing through and editing your assets. It's impossible to go into any further detail without knowing your specific use case.
* You can store the assets in a `Resources` folder and load them with the Resources system. Unity recommends not using the Resources system, but it can be useful for referencing large quantities of small files like ScriptableObject assets. For example, if your game has 1000 level data assets, you could store them in `Assets/Resources/Levels` and access them like this:

(ignore this line)

```
public LevelData GetLevelData(int levelNumber) {
    LevelData data = Resources.Load<LevelData>("Levels/" + levelNumber.ToString());
    return data;
}

```

There's also a new Addressable Asset System which serves a similar purpose but I haven't had a chance to use yet.

* You can also store large amounts of data in one asset by storing serialized types or arrays of serialized types. For example:

(ignore this line)

```
[System.Serializable]
public class SerializableLevelData {
    [SerializeField] private float duration;
    public float Duration => duration;
}

public class LevelCollection : ScriptableObject {
    [SerializeField] private List<SerializableLevelData> levels;
    public SerializableLevelData GetLevel(int index) {
        return levels[index];
    }
}

```
> 1 votes

---
Tags: unity, c#, assets, design-patterns, databases
---


# Question
Title: Problem with Blender model imported to Unity (Lighting problems)
I made a simple box in blender and imported it to unity. Now I'm facing with this weird lighting problem:

I've been messing around with normals, duplicated vertex, lots of things, even lightning properties but still I'm not getting any results at all. Why does this happen and how can I solve it?

Source blend file: https://drive.google.com/open?id=1Ze1JBRFBvhnnY-w36U2KDe7Q2zcfXsmf

# Answer
This isn't a problem with the mesh, it's a problem with your Unity light settings. Adjust the settings "Bias" and "Normal bias" on your light until the shadow seams go away.
> 0 votes

---
Tags: unity, lighting, blender
---


# Question
Title: Is there a difference between using one large mesh with 100k polygons and using 1000 meshes with 100 polygons each?
I'm planning on creating a first-person shooter for mobile. Now I know that fps games usually have a lot of meshes in the scene (trees, buildings, terrains, etc.). So I've been looking at a lot of Unity optimization tips. One thing I've noticed is that they always say "If you have a lot of objects in your scene, then each mesh must have low polygon count".

But how exactly does this help? If I have a lot of houses in my scene and I ensure that each house has very few polygons, wouldn't the total number of polygons in my scene be affecting the performance anyways? Or will my scene be rendered differently now that I've broken up the total polygon count into multiple parts?

# Answer
> 7 votes
There are two main components to the time it takes to process a draw call:

1. The time it takes to calculate all the results for every work item in the batch
2. The time it takes to upload info / switch states / ready the GPU to start working on it

As GPUs have gotten more powerful, most of the leaps and bounds have helped with point 1. They can now run hundreds of work items in parallel at blazing speeds, chewing through huge batches of geometry and shaded fragments.

They've gotten faster at point 2. as well, but the gains there are less dramatic because the work is often serial. If two draw calls issued back-to-back need different global state, in some cases the GPU has to wait for the previous call to finish completely before it can safely change that state and start working on the next call - even if it has hundreds of threads sitting idle in the meantime. This is called a pipeline flush.

So generally, we want to go wide as much as we can - give the GPU big jobs that can fill up all its threads, so it's never stuck waiting on work. Most games try to avoid unnecessary draw calls, and send their drawing instructions in big batches whenever they can.

So usually, one 100 k poly mesh is likely to render faster than 1000 100-poly meshes.

But wait, isn't that at odds with this advice?

> "If you have a lot of objects in your scene, then each mesh must have low polygon count"

Lots of models (ie. lots of separate draw calls) each needing very little work (few polygons) is the opposite of what modern GPUs are good at!

But Unity knows that GPUs prefer to work on big batches (and also that manually combining models together into a batch is a pain for developers), so it has some strategies to handle this for you.

If the engine notices that you have a lot of objects that use the same material (ie. same shader, parameters, and other pipeline state), then it will try to pack them together into a batch to send to the GPU as though they were one big mesh. It can do this both statically - combining meshes marked "static" in your scenes when you build your game - and dynamically - analyzing your dynamic meshes each frame and packing them as best it can to save draw calls at runtime.

This can be expensive to do optimally, so Unity has some strict limits in how much geometry it will try to process this way. It will only try to batch an object if it has no more than 300 vertices, and no more than 900 vertex attributes in total (eg. vertex position, normal, uv)

So, this is what the advice is telling you about:

* If you have a lot of models in your scene, the draw call switching costs can be high
* You can reduce the number of draw calls by combining the models into batches
* Unity will do this for you, but only if your models are quite small

# Answer
> 4 votes
Using more meshes with fewer polygons per mesh can improve performance when it allows the renderer to cull more objects. *Culling* refers to skipping objects during the render process, which improves performance. There are two main reasons why an object might get culled:

* View-frustum culling: Objects that are entirely outside the field of view of the camera may be culled.
* Occlusion culling: Objects that are entirely occluded (obscured from view) by closer objects can be culled. This is a complex process and requires you to have configured the scene correctly.

When you use very large meshes in your scene, they are less likely to be culled. If any part of a mesh is visible, the engine ends up rendering the entire mesh. Using a large number of smaller meshes makes it easier for the engine to determine objects to cull, because it's easier for them to be occluded or out of the view frustum.

I worked on a racing game for mobile where the 3D artist had created the wall around a track as a single 200,000 polygon mesh. At least some part of the wall was visible from all angles everywhere on the track, which meant all 200,000k polygons were always getting rendered. We solved this by breaking the wall into many small pieces, so that only the pieces that were actually in front of the player needed to be rendered.

Finding the right balance (of more small meshes vs. fewer large meshes) is a mixture of art and science, and what works best will depend on the specific needs of your game.

# Answer
> 1 votes
Lets say initiating a draw call takes 1 millisecond. Now lets say that it takes 10 milliseconds to draw 100 polygons.

A single call to draw 100 polygons costs 11 milliseconds

11ms * 1000 = 11 seconds.

For 100k polygons:

100,000 / 100 = 1000 * 10ms = 10 seconds.

Add on the 1ms for initiating the draw call = 10.001 seconds.

Drawing the 100k polygons once is 0.999 seconds (just over 10%) faster.

This is because state switching (task set up) on the gpu has a non-zero cost, which must be factored in when computing how long it will take for a task to be completed.

This is true of all computation, regardless of hardware or task specification.

It is this truism that led to Amdahl's Law.

---
Tags: unity, rendering, performance, optimization
---


# Question
Title: Player disappears when it collides with a tagged object
I am working on a simple game where the goal is to help a Player catch specific objects with a tag "Present".

After taking care of the models, animations I am now working on the collisions and counting UI.

For the collisions, on my Player Controller (I am using the ThridPersonUserController from the player Unity Standard Assets \- which simplified the whole animation process), I added the following functions:

```
    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Present")
        {
            Destroy(gameObject);
            count = count - 1;
            SetCountText();
        }
    }

    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();
        if (count == 0)
        {
            winText.text = "Thanks to you the Christmas will be memorable!";
        }
    }

```

However, like this, when the Player hits an object with the tag "Present", even though the counting is working properly, the player disappears.

I have tried to change the `OnCollisionEnter` to an `OnTriggerEnter`, like this:

```
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Present"))
        {
            Destroy(gameObject);
            count = count - 1;
            SetCountText();
        }
    }

```

However when the Player hits the objects with the tag "Present", they don't disappear.

My Player has a Capsule Collider and a Rigidbody.

The objects with the tag "Present" have a Box Collider and a Rigidbody.

Any guidance on how to make my Player stay in scene while removing the other objetcs and reducing the count is appreciated.

# Answer
I was destroying the wrong gameObject. Solved it by changing `Destroy(gameObject)` to `Destroy(other.gameObject)`.

```
void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Present")
        {
            Destroy(other.gameObject); //other.gameObject instead of just gameObject
            count = count - 1;
            SetCountText();
        }
    }

```

Additionally, as Samuel G pointed out, if the goal is to optimize for performance:

> Always use CompareTag() which is optimized for performance.
>
> Setting the Collider IsTrigger property well then make use of the OnTriggerEnter events and not the OnCollisionEnter anymore.

So, this is the final solution:

```
   void OnCollisionEnter(Collision other)
        {
            if (other.gameObject.CompareTag("Present"))
            {
                Destroy(other.gameObject); // this is destroying the other gameobject
                count = count - 1;
                SetCountText();
            }
        }

```
> 1 votes

# Answer
I think that you should use Destroy(other.gameobject) if you want to destroy other object and not a player.
> 2 votes

---
Tags: unity, c#, collision-detection
---