texts: How does Visual Studio integrate with Unreal Engine better than Code::Blocks does?

texts:
Background: I want to start using Unreal Engine 4, but I'm not sure which IDE I should use. I've narrowed it down to Code::Blocks (which I want for a couple good reasons) and Visual Studio 2015 (which is the industry standard).

I know that Unreal is made to use VS and it thus integrates far better with it (e.g. debugging Unreal projects apparently works in VS but not C::B). However, I haven't found any other examples of VS's superiority in this situation, and without the context of Unreal I would definitely like to use Code::Blocks instead1.

So, how does VS integrate with Unreal better than C::B does?

Note: I am not asking which is better, and I am not asking for a general comparison between the two. I just want to know exactly why people say VS is better with Unreal, so I can make an informed decision.

1Reasons: I am likely going to want to be on Linux in the near future, so I would like to get used to Code::Blocks now instead of having to learn how to use two different IDEs. Also, I am working on coding with some of my friends and for various reasons they won't/can't use VS. I would prefer to use the same IDE as them, so that we can keep stuff consistent.


texts: Unexpected result when generating world with 2 perlin noises

texts:
I try to generate a world with a temperature and an humidity noise to generate biome based on the y values of the two. I take the y values and round them on a 33 base for the humidity and 25 for the temperature then add the two to get 12 possibilities of biome. to test it I first tried generating a chunk by assining the sum of humidity and temperature to their y location. I was expecting to get multiple platform at different height (12 possibilities of height) but I instead got this
even if it doesn't look like it, there are random patterns within the bigger layers. i don't understand why I got that result (which looks pretty sick not gonna lie).
here is my script
const int seed = 50;
const int FREQUENCE = 100;
const int AMPLITUDE = 100;
const int size = 100;

int[] BIOME_DATA = { 0, 33, 66, 25, 58, 91, 50, 83, 116, 75, 108, 141 };

int[] temp_VERT = new int[100 * 100];
int[] hum_VERT = new int[100 * 100];
public int[] biome_VALUE = new int[100 * 100];

void Start()
{
    //generate the y values for the humidity vertices
    for (int x = (int)transform.position.x, i = 0 ; x < size+ (int)transform.position.x; x++)
    {
        for (int z = (int)transform.position.z; z < size+(int)transform.position.z; z++)
        {
            float y = Mathf.PerlinNoise((float)x+seed / FREQUENCE, (float)z / FREQUENCE) * AMPLITUDE;
            y = Mathf.Floor(y / 33) * 33;
            hum_VERT[i] = (int)y;
            i++;
        }
    }

    //generate the y values for the temperature vertices
    for (int x = (int)transform.position.x, i = 0; x < size+ (int)transform.position.x; x++)
    {
        for (int z = (int)transform.position.z; z < size+ (int)transform.position.z; z++)
        {
            float y = Mathf.PerlinNoise((float)x-seed / FREQUENCE, (float)z / FREQUENCE) * AMPLITUDE;
            y = Mathf.Floor(y / 25) * 25;
            temp_VERT[i] = (int)y;
            i++;
        }
    }

    //assigne une valeur représentant un biome pour chaque vertex
    for(int i = 0; i < biome_VALUE.Length; i++)
    {
        biome_VALUE[i] = System.Array.IndexOf(BIOME_DATA, (hum_VERT[i] + temp_VERT[i]));
        //biome_VALUE[i] = new Vector2(temp_VERT[i],hum_VERT[i]);
    }

    GenerateChunk(biome_VALUE);
}

void GenerateChunk(int[] Y_VERTICES)
{
    Mesh meshy;
    MeshRenderer meshRenderer = GetComponent<MeshRenderer>();
    meshRenderer.sharedMaterial = new Material(Shader.Find("Standard"));
    MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();

    Vector3[] VERTICES = new Vector3[Y_VERTICES.Length];
    List<Vector2> UV = new List<Vector2>();
    List<int> TRIANGLES = new List<int>();
    List<Vector3> NORMALS = new List<Vector3>();

    meshy = new Mesh();

    //création des Vecteur
    for (int i = 0, x = 0; x < size; x++)
    {
        for (int z = 0; z < size; z++)
        {
            VERTICES[i] = new Vector3(x+transform.position.x, BIOME_DATA[Y_VERTICES[i]], z+transform.position.z);
            i++;

        }
    }

    //création des normales
    for (int i = 0; i < VERTICES.Length; i++)
    {
        NORMALS.Add(-Vector3.forward);
    }

    //création des triangles
    for (int x = 0; x < size - 1; x++)
    {
        for (int z = 0; z < size - 1; z++)
        {
            int i = size * x + z;
            TRIANGLES.Add(i);
            TRIANGLES.Add(i + 1);
            TRIANGLES.Add(i + size);
            TRIANGLES.Add(i + size + 1);
            TRIANGLES.Add(i + size);
            TRIANGLES.Add(i + 1);
        }
    }

    //création des uv
    for (int i = 0; i < VERTICES.Length; i++)
    {
        UV.Add(new Vector2(VERTICES[i].x, VERTICES[i].z));
    }

    //assignation des valeurs
    meshy.vertices = VERTICES;
    meshy.triangles = TRIANGLES.ToArray();
    meshy.uv = UV.ToArray();
    meshy.normals = NORMALS.ToArray();
    meshFilter.mesh = meshy;
}

}


texts: Cube changes position when I use a script to change its UV mapping

texts:
I try to code a Minecraft like game with Unity 2017.3. I found a C# script for creating a UV mapped cube with the following layout, using my own texture with 64x64 pixel sides:

If I run the game my cube is now placed in the air. How do I control its position?

Here is the script I'm using:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof (MeshFilter))]
[RequireComponent(typeof (MeshRenderer))]
public class UVMapping : MonoBehaviour {

    void Start () {

        float size = 1f;

        Vector3[] vertices = {
            new Vector3(0, size, 0),
            new Vector3(0, 0, 0),
            new Vector3(size, size, 0),
            new Vector3(size, 0, 0),
            new Vector3(0, 0, size),
            new Vector3(size, 0, size),
            new Vector3(0, size, size),
            new Vector3(size, size, size),
            new Vector3(0, size, 0),
            new Vector3(size, size, 0),
            new Vector3(0, size, 0),
            new Vector3(0, size, size),
            new Vector3(size, size, 0),
            new Vector3(size, size, size),
        };

        int[] triangles = {
            0, 2, 1, // front
            1, 2, 3,
            4, 5, 6, // back
            5, 7, 6,
            6, 7, 8, //top
            7, 9 ,8,
            1, 3, 4, //bottom
            3, 5, 4,
            1, 11,10,// left
            1, 4, 11,
            3, 12, 5,//right
            5, 12, 13
        };

        Vector2[] uvs = {
            new Vector2(0, 0.66f),
            new Vector2(0.25f, 0.66f),
            new Vector2(0, 0.33f),
            new Vector2(0.25f, 0.33f),
            new Vector2(0.5f, 0.66f),
            new Vector2(0.5f, 0.33f),
            new Vector2(0.75f, 0.66f),
            new Vector2(0.75f, 0.33f),
            new Vector2(1, 0.66f),
            new Vector2(1, 0.33f),
            new Vector2(0.25f, 1),
            new Vector2(0.5f, 1),
            new Vector2(0.25f, 0),
            new Vector2(0.5f, 0),
        };

        Mesh mesh = GetComponent<MeshFilter> ().mesh;
        mesh.Clear ();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.uv = uvs;
        mesh.Optimize (); // this is deprecated
        mesh.RecalculateNormals ();
    }
}


texts:
If I am running DirectX 11 in debug mode (D3D11_CREATE_DEVICE_DEBUG), I am constantly getting these warnings:

D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets: Resource being set to OM DepthStencil is still bound on input! [ STATE_SETTING WARNING #9: DEVICE_OMSETRENDERTARGETS_HAZARD]
D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing PS shader resource slot 6 to NULL. [ STATE_SETTING WARNING #7: DEVICE_PSSETSHADERRESOURCES_HAZARD]

It is because I am setting a resource as a render target while it is currently bound to the PS. However, my rendering flow is set up such as it relies on the api to force the resource slot to null, and it works.

Is there any reason I should be bothered with these warnings or I can rely on the api to enforce this every time? I only tested on 2 GPU-s: Intel HD 3000 and Nvidia GT525m.


texts: I have a script that changes an object to a broken version of itself when clicked, but it keeps rotating the object

texts:
So I have made a script in unity that you put on an object and when you click the object it will delete the object and replace it with a broken one I made in blender. My problem is that when I click the object and it deletes it, for some reason unity will take the broken object and rotate it 90 degrees. My only guesses of whats happening is, it's my code that is causing it or in my blender files when I bring them into unity some are flipped 90 degrees while others aren't. I would really appreciate any help anyone could give me. Also I will have a link to a video to demonstrate the problem better and I will include my code below.

https://www.youtube.com/watch?v=U5NubLl-hLw

Thanks, Nova

using UnityEngine;
using System.Collections;

public class Destruction : MonoBehaviour
{
    public GameObject destructionPiece;

    void OnMouseDown()
    {
        Instantiate (destructionPiece, transform.position, transform.rotation);
        Destroy(gameObject);
    }
}


texts: How to Prevent Sticking to Overhead Slopes

texts:
I am having an issue with overhead slopes in my 2D platformer.

I implement slopes using a LineSegment class. My player sprite has a spine attribute which is just a line segment from the midtop of his bounding rect to its midbottom. If this spine ever intersects a slope's line segment, the sprite is adjusted upwards or downwards so that his midtop or midbottom is at the intersection point. To determine which direction to adjust, I look at where the previous bounding rect's center is in relation to this intersection point.

def collide_with_slopes(sprite, slopes):

    # create midline for the sprite
    spine = LineSegment(sprite.game, sprite.midtop, sprite.midbottom)

    # check if midline intersects any slope
    slopes = [slope for slope in slopes if spine.intersects_segment(slope)]

    if slopes:
        slope = slopes[0]
        intersection_point = spine.intersects_segment_at_point(slope)

        # sprite above slope
        if sprite.previous_bounding_rect.centery < intersection_point.y:

                sprite.on_slope = True
                sprite.pos.y = intersection_point.y - sprite.bounding_rect.height/2
                sprite.vel.y = 0

        # sprite below slope
        elif sprite.previous_bounding_rect.centery > intersection_point.y:

                sprite.on_slope = False
                sprite.pos.y = intersection_point.y + sprite.bounding_rect.height/2 + 1
                sprite.vel.y = 0

    elif not slopes:
        sprite.on_slope = False

This approach works well for slopes under the player, but I am having an issue with overhead slopes.

They work fine when the player jumps without horiztonal movement.

The problem is when the player is moving in the same direction that the overhead slope descends.

The sprite sticks to the ceiling and glides down the slope as if zip-lining.

I believe the problem is that even after slope resolution, if the player is pressing right, the sprite's new position will still be intersecting the slope on the subsequent frame, causing the slope code to keep readjusting the midtop point to be on the slope.

How can I fix this issue?

I have tried adjusting the sprite down a few extra pixels upon upward collision with a slope, but the result looks and feels bad.

I have also tried decomposing the update to my position into its x and y component, and only checking for slope intersections after one or the other. This did not solve the issue.


texts:
Out of curiosity (and peace of the mind...) I wondered how DirectX decides which attribute from a struct corresponds to the right variable inside an HLSL cbuffer-register(x) (apart from the order/type they are declared with).

My main concern is my structs not only have member variables but 2 constructors each. So how can I be sure the constructors are not at the beginning of my struct definition (memory wise - C++ question I guess) so my variables would overflow after my cbuffer ? Additionnaly, can I only rely on declare-order/type matching ?

Is there a more precise/explicit way than doing :

struct foo {
    int a;
    int b;
    int c;

    foo () {}
    foo (int a, int b, int c) : a{a}, b{b}, c{c} {}
}

D3D11_BUFFER_DESC constantBufferDesc;
...
constantBufferDesc.ByteWidth = sizeof(foo) + (16 - sizeof(foo) % 16);
hr = g_d3dDevice->CreateBuffer(...);
g_d3dDeviceContext->VSSetConstantBuffers(0, 1, &fooBuffer);
g_d3dDeviceContext->UpdateSubresource(&fooBuffer, 0, nullptr, &foo, 0, 0);

With HLSL :

cbuffer foo: register(b0) {
    // constructor here ?
    int a;
    // constructor here ?
    int b;
    int c;
    // constructor here ?
}

I am aware this is more a C++ question - Thanks for your insight.


texts:
I have been reading about NativeArray, but I have to admit I do not understand it.

From the documentation:

  A NativeArray exposes a buffer of native memory to managed code, making it possible to share data between managed and native without marshalling costs.

I have to admit I do not understand a word of what is being said in here.

What is the point of using it instead of normal arrays, or List? Would it be possible for someone to show me an example of how to use it, and how not to use it?


texts: Longest path algorithm for roguelike maze generation

texts:
I have a simple grid-based map composed of rooms, like this (A=entrance, B=exit):

   0 1 2 3
  #########
0 #B# #####
  #########
1 #   ### #
  #########
2 # #     #
  # #     #
3 # #     #
  #########
4 # ###   #
  #########
5 ###A    #
  ###     #
6 ###     #
  #########

And I'm stuck trying to make a suitable algorithm to create a path of doors between the rooms, in such a way that the player has to explore most of the map before finding the exit.

In other words, I'm trying to find the longest possible path from A to B.

(I'm aware that this problem can be solved for acyclic graphs; however, in this case there can be cycles.)

EDIT: Another example where rooms are connected using floodfill, and the exit is chosen as the farthest room from the entrance:

   0 1 2 3
  #########
0 #B#     #
  # #-#####
1 # | #   #
  ### #   #
2 ### #   #
  ###-#-###
3 #   | ###
  #-#######
4 #A|     #
  # #     #
5 # #     #
  # #     #
6 # #     #
  #########

Note that the path to the exit is not the longest possible path at all.


texts: Creating lots of sprites dynamically in libgdx

texts: I´m creating Groups that contains Sprites and adding bodies with box2D, but when I create many of this my animation gets very slow. How can I handle it?


texts: How do I make an extensible engine in XNA?

texts: I making a new engine for my game, based on the component system. Every game object is a set of some components, like render, physics, AI, etc. I want to make my game extensible; I now how to make a plugin system with .NET, but how do I make my game able to add new resources from plugins, at runtime? How should such the plugin that stores content look? I want to make simple system, like "Total Annihilation" has, to be able to add new units.


texts: If I know a given action will result in a collision, should I allow the action to occur anyway?

texts:
I've finished programming my game engine, and now that I've been testing it, I've been noticing some graphics problems.

The big one is that when a player tries to push against a wall, their character will "jiggle" against it as it constantly tries to enter the wall's space and the collision detection constantly pushes it back outside.

What is the proper way to handle such a situation?

My first instinct was, if moving in a certain direction causes a collision, disable movement in that direction until the entity's position has changed. I.e., once an object falls onto a platform, disable gravity until the object is no longer above a platform.

Is there a better way to resolve repeated collision detections between the same two objects in the same overlapping space?


texts: OpenGL ES 2.0: 2D game rendering, no performance gain with glDraw call batching

texts:
I just did a small benchmark. To my surprise batching sprites into a single draw call doesn't give any significant performance boost. Following are my results:

Hardware: iPod touch 4

Extra info: OpenGL ES 2.0. 1 sprite (64x64) having some transparency (smiley face with drop shadow). NO rotation, NO scale. (Texture is bound only once at the start in the init function). Compiled in "Release" mode.

The first column labeled 'N' shows number of sprites being tested. Second column shows FPS when sprites are batched in a huge vertex array (only 1 draw call). Third column shows FPS on multi draw calls, eg: 5000 draw calls for 5000 sprites.

Benchmark 1: Alpha blending off

Benchmark 2: Alpha blending ON

Smiley image used:

Source code:

For single draw call:

Vertex hugeArray[SPRITE_COUNT*6];
GLsizei stride = sizeof(Vertex);
int drawCallCount = 0;

const GLvoid* pCoords = &hugeArray[0].Position[0];
const GLvoid* pColors = &hugeArray[0].Color[0];
const GLvoid* pTexCoords = &hugeArray[0].Texture[0];

glVertexAttribPointer(positionSlot, 2, GL_FLOAT, GL_FALSE, stride, pCoords);
glVertexAttribPointer(colorSlot, 4, GL_FLOAT, GL_FALSE, stride, pColors);
glVertexAttribPointer(textureSlot, 2, GL_FLOAT, GL_FALSE, stride, pTexCoords);

GLsizei vertexCount = sizeof(hugeArray) / sizeof(Vertex);
glDrawArrays(GL_TRIANGLES, 0, vertexCount);
drawCallCount++;

cout << "DrawCall Count: " << drawCallCount << endl;

For multiple draw calls:

Vertex hugeArray[SPRITE_COUNT*6];
GLsizei stride = sizeof(Vertex);
int drawCallCount = 0;

for(int i = 0; i < SPRITE_COUNT; i++){

    const GLvoid* pCoords = &hugeArray[i*6].Position[0];
    const GLvoid* pColors = &hugeArray[i*6].Color[0];
    const GLvoid* pTexCoords = &hugeArray[i*6].Texture[0];

    glVertexAttribPointer(positionSlot, 2, GL_FLOAT, GL_FALSE, stride, pCoords);
    glVertexAttribPointer(colorSlot, 4, GL_FLOAT, GL_FALSE, stride, pColors);
    glVertexAttribPointer(textureSlot, 2, GL_FLOAT, GL_FALSE, stride, pTexCoords);

    GLsizei vertexCount = 6;
    glDrawArrays(GL_TRIANGLES, 0, vertexCount);
    drawCallCount++;
}
cout << "DrawCall Count: " << drawCallCount << endl;

I thought that batching sprites into a huge array resulting in a single draw call would give a HUGE performance gain but benchmarks show otherwise. Any ideas what is going on here?

Thanks for reading the question :)


texts: How to sort polygons without a depth buffer

texts:
Please help me getting understanding how did they sort polygons in old games from the eighties.
They did not use z-buffer or anything like this, thats for sure.

Please look at the screenshot. How would one decide that the green surface should be drawn after the table polygons?
The center of the table surface is closer to the viewer from object center, closest vertex point of view. The green surface has the farthest Z. Oh, this big gray table is not split into smaller polygons.
How did they know to draw the green poly after the big gray table surface?


texts:
Is there any cross platform libraries available for handling input from a microphone?

I am thinking beyond voice chat to noise / voice recognition.

I am putting together a plan for a role playing game and in thinking of features I was thinking it would be nice if the player could be standing in a crowded place and yell and have the npc's react to that and look at the player for example.

As I plan to make this an open source project I want to make it as cross platform friendly as possible.


texts: How can I create 2D shadows that let me detect when the player is inside them?

texts:
I'm working on a 2D platform game, and I want my platforms to cast shadows along with some way to detect if the player is inside the shadow area (that is, not hit by the sun).

More specifically: I have a character, some platforms and a sun. When the player is under the shadow of some platform he is safe. If he goes to a location when the sunlight hit him, then he starts losing heath until he enters other shadow spot.

Right now the shadows are boxes with a transparent/diffuse material. Boxes are good because I can determine when the player enters or leaves them, but they are are ugly and don't have any animation. I need a shadow that changes when the sun changes its position, without losing the ability to determine when the player is inside a shadow (I think this can be done using a ray cast)?

How can I accomplish this?


texts: 2D Textures are shown through objects in front of it(OpenGL)

texts:
I am learning to use pyglet and learning about applying 2D textures to planes in pyglet.  When I apply the 2D texture to the plane it works fine.   When I make multiple objects with the same texture , one in front of the other, i have a problem.

The texture behind the first texture draws through it.  And the texture behind that has the same property.

I would like to disable this so the front texture is shown and obscures the back textures.

In my resize function I called

glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glShadeModel(GL_SMOOTH)

and in my on_draw function i call

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glEnable(GL_TEXTURE_2D)

I am using a perspective camera
with

gluLookAt(velx,0,vely,velx,0,vely-10,0,1,0);

where velx is the x position for the camera
and vely is the z position for the camera

Am I processing the texture incorrectly causing this?  What should I do to change this?

The images positions are in order on the z axis -10,-20,-40, and -60.

[EDIT]
Here is a screenshot of what I was saying

The GreenBox is in the front and the Red box is behind it

This is the drawing function that i am using.  I believe that it is clearing the depth buffer.

@window.event

def on_draw():

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

for x in range(0,4):
    for y in range(0,4):
        glPushMatrix()
        if x % 2== 0 and y % 2==0:
            glBindTexture(texture.target,texture.id)
        else:
            glBindTexture(texture2.target,texture2.id)
        glTranslatef(x*4.0,0,y*-10.0)
        glBegin(GL_QUADS)

        glTexCoord2f(0.0, 0.0)
        glVertex3f(-1,-1,-10)
        glTexCoord2f(0.0, 1.0)
        glVertex3f(-1,1,-10)
        glTexCoord2f(1.0, 1.0)
        glVertex3f(1,1,-10)
        glTexCoord2f(1.0, 0.0)
        glVertex3f(1,-1,-10)

        glEnd()

        glPopMatrix()


texts:
I’ve spent the days reading all sources I can find on the use of Color palettes in games, but there is a real lack of real world examples.
Most Color palette tools generate 4-5 colours.

I am making a game where I have environment, houses, characters, items, etc. How does one Color coordinates that? How large should my palette be and should it contain the shades/tints of each Color?

Having a hard time understanding how to use Color in games, my game is low poly but I feel like I always end up with ugly colours.


texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimFlyertransportationController : MonoBehaviour
{
    public GameObject JetFlame;
    public bool turnOffOn = false;

    // Start is called before the first frame update
    void Start()
    {
        TurnAllAnimtorsOff(transform, turnOffOn);

        if (turnOffOn)
        {
            JetFlame.SetActive(false);
        }
        else
        {
            JetFlame.SetActive(true);
        }
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void TurnAllAnimtorsOff(Transform root, bool onOff)
    {
        Animator[] animators = root.GetComponentsInChildren<Animator>();

        foreach (Animator a in animators)
        {
            if (onOff)
            {
                a.enabled = false;
            }
            else
            {
                a.enabled = true;
            }
        }
    }
}

I want that if in runtime I change the turnOffOn flag state apply the changes in real time in the Update for all Animators and also for the JetFlame.  Now it's only aply the changes in the editor before running the game.


texts: VS Graphics Diagnostic Tools and IDXGIFactory::EnumAdapters()

texts:
I have the following constructor for my main application class where i enumerate all adapters, that looks something like this:

CApplication::CApplication()
{
    IDXGIFactory* factory;
    CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory));

    IDXGIAdapter* adapter;
    unsigned adapterIndex = 0;
    while (factory->EnumAdapters(adapterIndex, &adapter) != DXGI_ERROR_NOT_FOUND)
    {
        mAdapters.push_back(adapter);
        ++adapterIndex;
    }

    ReleaseCOM(factory);
    //...
    HRESULT hr = D3D11CreateDevice(
        mAdapters[adapterIndexToUse],
        mDriverType, nullptr,
        createDeviceFlags,
        nullptr, 0, D3D11_SDK_VERSION,
        &md3d11Device, &mFeatureLevel, &md3d11ImmediateContext);
}

I have Intel HD Graphics 4000 as  primary display adapter and NVIDIA GeForce GT 620M as "back-up" display adapter which do all the heavy work.(i.e. rendering in games)

I want to use Visual Studio 2013 Graphics Diagnostic tools while using NVIDIA GPU, and since NVIDIA GPU is secondary adapter, this corresponds to setting adapterIndexToUse=1.
Problem is that while enumerating adapters only Indel GPU gets enumerated.
That is, call to factory->EnumAdapter(adapterIndex, &adapter) returns DXGI_ERROR_NOT_FOUND if adapterIndex > 0 while using Visual Studio Graphics Diagnostic tools and so my mAdapters class attribute which is std::vector<IDXGIAdapter*> have size 1 causing out of bounds exception when we try to create the Device with adapterIndexToUse specified as 1 (So i use my secondary NVIDIA GPU).

Only cause of this error i have come to think of is that Graphics Diagnostic tools is only supported on primary display adapter, but i don't see why that would be the case.


texts: How can I check on a large number of points to see if they're inside the camera's frustum?

texts: I have a locally stored database on my Android project, it is a database of approx 100,000 Point3D(double,double,double). I need to check if each of these points are inside of the camera's frustum in unity. Will I most likely be running into performance issues querying the database and feeding all live Point3D's to unity per frame? What would be the best way to go about this if I am approaching this from the wrong direction?


texts: How to increase the thickness (Size) of a plane in Unity

texts: I am making a small game where you have to roll around and not fall of a platform. I am using a plane to simulate the ground, but it is really thin. Is there a way to make it thicker by increasing a variable?


texts: Where and how to smooth a voxel-based terrain surface?

texts:
I want to smooth the blocky terrain in a Minecraft-like world. The smoothing affects visual appearance and physics but not the logic of placing and picking blocks. I have my mathematical formula to smooth the cubes in a way the voxel grid stays recognizable. But I have no clue how to implement such an effect.

Moreover I do not know how to store and render the effect at all. My smoothing algorithm provides a height for each pixel of a block based on the surrounding blocks. This would result in million of triangles so I might need another approach.

Therefore I thought about calculating the smooth surface dynamically in a shader on the GPU. I never used the geometry shader or the tessellation shader before, but doing so sounds reasonable to me. But with this approach things become difficult when I want to apply correct physics to the smooth terrain surface since the triangles would only be stored on the GPU.

How can I effectively generate a detailed smoothed mesh and access the result for the physics simulation? Is there a technique to implement my idea without the creating of loads of additional triangles?


texts: Calculating the latitude & longitude of a raycast hit point on a sphere

texts:
I am working on a game where you look at a sphere and get the latitude and longitude of the position.

I get the position on the globe with a raycast along the direction the user is looking. Using this I pass the position and the radius into a method to get the correct latitude and longitude.

Problem

I don't believe my math is correct on this one and I am having some trouble figuring it out.

Code

void Update () {

    if (Physics.Raycast(transform.position, direction: transform.forward, hitInfo: out hit, maxDistance: range))
    {
        Vector3 pointHit = hit.point;
        radius = earth.GetComponent<SphereCollider>().radius;
        //radius = earth.GetComponentInChildren<Renderer>().bounds.extents.magnitude;
        FromVector3(pointHit, radius);
    }
}

public void FromVector3(Vector3 position, float sphereRadius)
{
    float lat = (float)(Math.Acos(position.y / sphereRadius));
    float lon = (float)Math.Atan(position.x / position.z);

    //convert from radians to degrees
    lat *= Mathf.Rad2Deg;
    lon *= Mathf.Rad2Deg;

    Debug.Log(lat + ", " + lon);
}

Output

My Output for latitude ranges from 89 to 90 and doesn't change very much

My Output for longitude ranges from -11 to 11


texts: Finding a point between 2 moving points colinearly , given 2 moving points and distance

texts:
P/S: The engine I work on doesn't have grouping integration. That's why I need a formula to change the position.

A------B---------------C

A and C are moving points that can move anywhere

A = (xa, ya), C = (xc, yc)

B (xb, yb) is a point between A and C colinearly

With one condition that distance of AB = constant = r, distance of AC can be varied.

How to find xb and yb?

Asked from Mathematics StackExchange:

  Deepak says:

  The locus of all possible points B is a circle centred on A and of
  radius r. The intersection between this circle and line AC will give
  you point B (and another point opposite it on the circle which you can
  neglect).

  Try to write down the relevant equations and solve them?

Example: http://www.mathopenref.com/collinear.html


texts:
I want to find the texture coordinates for point P. I have the vertices of the triangle and their corresponding uv coordinates.

The numbers in the little squares in the texture represent color values.

What are the steps of computing the uv coordinates of P?


texts: My bullet changes the velocity depending on where I click

texts:
I want to build a little 2D-Sidescrolling shooter and I'm now at the shooting script.

I already figured out how to shoot a bullet towards my mouse pointer. I got something like this :

Vector3 shootDirection;
        shootDirection = Input.mousePosition;
        shootDirection.z = 0.0f;
        shootDirection = Camera.main.ScreenToWorldPoint (shootDirection);
        shootDirection = shootDirection - transform.position;

        shootDirection.Normalize ();

        Rigidbody2D bulletInstance = Instantiate (rocket, transform.position, Quaternion.identity) as Rigidbody2D;
        bulletInstance.velocity = new Vector2 (shootDirection.x * speed, shootDirection.y * speed);

Now obviously the bullet goes faster if my Direction coordinates are big and slower if they are smaller. Have you some better code for me or how can I fix that issue?

I added now some loop like this, which brings a horrible performance, but kinda works out for the problem, but I'm still looking for a better solution.

while (((shootDirection.x * speed) + (shootDirection.y * speed)) < 20) {
            speed += 0.1f;
        }

So the loop makes sure that the overall speed is always almost the same, but this solution ends in an infinity loop if the values get too small.


texts: UE4 bone sockets imported from blender have buggy local transform

texts:
I'm exporting this armature with two sockets for left and right hands. As you can see on the Transforms location and rotation are all 0s.

Here's my export settings on blender:

Now I import it into UE4 and if I check the socket I get this:

The Y axis local transform has value -0.085241. And I cannot get rid of it for the life of me.


texts:
I would like to write a small software which will hook into the League of Legends client and record my performances and store them locally, because Riot only stores last 10 matches. Is there some way through which I can trigger an event when I finish a game ? For those who know, I would like it to work similarly to League Recorder, but it will record only your final stats (KDA, Gold, Creep Score, etc.).
I was thinking of searching for the client in the process list, and doing some checks by getting the last 10 matches, but I don't know of any way to see which user is logged in and how to download the history. I'm currently not bound to any languages, and I can work in C++/C#/Java.


texts:
I'm thinking of implementing a 3D tile system for my engine, and tie it to it's world streaming system as well. As in, using it for it's terrain for an open world in an engine that theoretically can support up to about 80 kilometers squared even if it won't be fully used.

The game will be making use of both free form movement, and tiled movement when it comes to combat. With cover systems involved.

I was wandering about a few questions.

How viable is it to use a bunch of smaller tiles for terrain? Think Dota 2 Reborn. Where the increased levels are guaranteed to be flat and at exact heights. And there will be hills and the like connecting them.

If I was to use tiles, do I need to weld the vertexes and recompute the normals for the affected vertices?

If I do not need to connect them, will it cause any visible artifacts? Or any sort of performance hits? I know I can batch all the standard tiles. But I don't think the same can be said if I treat the terrain tiles like normal terrain when it comes to texturing.


texts: LibGDX Stage and Viewport management for Actors?

texts:
So I've done research about how to use Stage, Actor and Viewports etc. To optimize the game for most devices running Android. I'm pretty sure that the viewport is configured or the background image is just being drawn over the screen without actually using the viewport. That is fine though. So I'm basically telling the viewport to draw an image over the whole screen and it seems that that applies to actors also. So I guess the viewport is trying to draw the actor over the whole screen.

When testing the app on emulators with different screen sizes the actor is not resized (probably because of the viewport setting), but how can I get the actor to resize so that the actor fits in the world? The world will be the whole screen of the device.

Do I need to use two viewports where one is for UI (background so far) and another for the game? If I need to do that wouldn't the UI viewport need to be the screen size and the Game viewport holding the world size would have size constants? If so, then I don't have the whole screen size as the world, but drawing the Game viewport using the screen width and height would probably result in drawing the actor over the whole screen again, right?

And I've seen in some tutorials that they often set a constant unit of the world width and world height. Wouldn't that fail to fit all devices since they have a specific constant for width and height?

I want all of my Actors to be resized so that they fit inside the world (screen size).

UPDATE TO CLARIFY MY QUESTION

As you see the background is scaled up and down due to being drawn as the width and height of the screen, I guess, but I need the actors to also be scaled up or down. The actors can't remain the same size for all screens.

MyGdxGame

public class MyGdxGame extends ApplicationAdapter {

private OrthographicCamera camera;
private Stage stage;
private Viewport viewport;
private Texture textureBackground;

@Override
public void create () {
    camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    camera.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);

    final float GAME_WORLD_WIDTH = Gdx.graphics.getWidth();
    final float GAME_WORLD_HEIGHT = Gdx.graphics.getHeight();
    viewport = new FitViewport(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT, camera);

    stage = new Stage(viewport);
    MyActor actor = new MyActor(new Texture("badlogic.jpg"));
    actor.setPosition(0, 0);
    stage.addActor(actor);
    stage.getViewport().apply();
    Gdx.input.setInputProcessor(stage);

    textureBackground = new Texture("TheWorld.png");
}

@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height);
    stage.getCamera().position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
}

@Override
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    stage.getBatch().setProjectionMatrix(stage.getCamera().combined);
    stage.getCamera().update();

    stage.getBatch().begin();
    stage.getBatch().draw(textureBackground, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    stage.getBatch().end();

    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}
}

MyActor

package com.mygdx.game;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;

public class MyActor extends Actor {

    private Texture texture;
    public MyActor(Texture texture) {
        this.texture = texture;
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        batch.draw(texture, getX(), getY());
    }
}

Images:

Research links:

Using two viewports for UI and Game

Viewports and World units

LibGDX Viewport Tutorial


texts: Particle-system in the GPU in Unity: how to load/store data from/to a texture in the shader?

texts:
I have been implementing a simple GPU-based particle system in Unity, for my current game. The setup is indeed not very elaborated: the shader receives a set of coordinates passed trough the position of the vectors of a mesh, then generates a quad on the fly (via geometry shader). And then, it applies the mesh texture as the texture to the generated quad.

Performance, by doing this, has showed an incredible boost in my game in comparison to using Unity's built-in system. Therefore, I am trying to extend it a bit further and implement now a couple of functionalities: a) particles' lifetime; b) particles that "blink", i.e. that are not displayed for a few microseconds.

In order to achieved both tasks, I imagine that I need a way to store information for each particle from one frame to the next. However, this certainly cannot be done at the mesh level due to performance concerns: downloading or uploading information from the mesh is very expensive. Besides computational shaders (which are currently out of consideration), the only way I read about is using a texture to store the information.

Then, in general terms, my question is how to do that? Being more specific, I can't quite understand how a texture could store, for instance, the position or the lifetime of each particle. Sure, each pixel of the texture has a RGBA information, but that is just it. Besides,in Unity, RGBA is set from 0 to 1 and, worse, RenderTexture does not have a SetPixel function. Therefore:

1) how can each pixel store position and lifetime of each particle?
2) how can each particle known which is its respective pixel and loard/save from/to it?

If anyone could show me a couple of lines of shader pseudo-code, that would be amazing and ideal. But conceptual explanations are very much welcome too.


texts: How do I correctly use singletons in C++ engine programming?

texts:
I know singletons are bad, my old game engine used a singleton 'Game' object that handles everything from holding all data to the actual game loop. Now I'm making a new one.

The problem is, to draw something in SFML you use window.draw(sprite) where window is an sf::RenderWindow. There are 2 options I see here:

Make a singleton Game object which every entity in the game retrieves (what I used before)
Make this the constructor for entities: Entity(x, y, window, view, ...etc) (this is just ridiculous and annoying)

What would be the proper way to do this while keeping an Entity's constructor to just x and y?

I could try and keep track of everything I make in the main game loop, and just manually draw their sprite in the game loop, but that too seems messy, and I also want absolute full control over an entire draw function for the entity.


texts: XNA - Obtaining depth from the scene's render target?

texts:
Possible Duplicate:
  Depth buffer and render target

I'm currently rendering my scene to a render target so it can be used for rendering methods such as post processing and order independent transparency.

rtScene = new RenderTarget2D(
            GraphicsDevice,
            GraphicsDevice.PresentationParameters.BackBufferWidth,
            GraphicsDevice.PresentationParameters.BackBufferHeight,
            false,
            SurfaceFormat.Rgba64,
            DepthFormat.Depth24Stencil8,        // Requires a depth format for objects to be drawn correctly (e.g. wireframe model surrounding model)
            0,
            RenderTargetUsage.PreserveContents
            );

I am required to use RenderTargetUsage.PreserveContents so that the same render target can be rendered to multiple times, once for each of the draw methods below.

DrawBackground
DrawDeferred
DrawForward
DrawTransparent

The problem is that DrawTransparent requires a copy of the scene's depth as a texture.

Is there any way to obtain this from the scene render target above (rtScene)?

I can't have more than one render target with RenderTargetUsage.PreserveContents as this causes problems on hardware such as the XBOX 360, so rendering the depth to a separate render target at the same time as I render the scene isn't possible as far as I can tell.

Would I be able to get around this problem by "Ping-Ponging" two render targets (using the more compatible RenderTargetUsage.DiscardContents) and using the result for the depth texture?


texts: XNA/C# Shadows look strange in orthographic

texts:
I have implemented shadows in to my game engine. They look fine when rendered in projection mode as a projected light, however I get a strange "blocky" look when they are put into orho'. I will be rendering much bigger scenes (MMO size maps, for example) and Ive heard that rendering in orthographic for the shadow map will give a better result, and it does in some ways. I dislike rendering with projective perspective as you can see the view frustum, whereas this doesnt happen with orthographic.

Here is the code I have for rendering every update:

    public void UpdateLightData()
    {
        Matrix lightsView;
        Matrix lightsProjection;
        ambientPower = 0.2f;
        lightPower = 2f;

        cameraFrustum.Matrix = player.view * player.projection;
        lightPos = new Vector3(0, 30, 0);
        lightsView = Matrix.CreateLookAt(lightPos, new Vector3(-2, 3, -10), new Vector3(0, 1, 0));
        lightsProjection = Matrix.CreateOrthographic(Globals.device.Viewport.Width, Globals.device.Viewport.Height, 0.1f, 100f);
        //lightsProjection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, 1f, 5f, 100f);

        lightsViewProjectionMatrix = lightsView * lightsProjection;
    }

Here is a screenshot of ProjectionPerspective:
https://www.dropbox.com/s/yen671frsft4kdl/Screenshot%202015-03-07%2016.00.32.png?dl=0

Here is what it looks like in orthographic:
https://www.dropbox.com/s/jj6h4zgodda38fe/Screenshot%202015-03-07%2016.01.19.png?dl=0


texts: Is it possible to rotate an isometric tile map, either in LibGDX or Tiled map editor? My problem is that LibGDX renders the (0, 0) position from Tiled at bottom-left corner like it usually does (see the attachments), however that introduces awkwardness when editing the map as you have to keep in mind that the top corner of the map will be the left corner when rendered in game. Is there any workaround for this?


texts: What is a right datatype in C++ for OpenGL scene representation with use of GLSL

texts:
I am programming in C++ OpenGl with GLSL. Until now I have been using a data structure that is composed of std::vector filled with structures of vertexes and with their parameters (position , normal, color ...) as a global variable for all the code.
My question is, as I am using VBOs for drawing - is this a good approach to this problem?

I am asking because I happen to have a lot of memory related trouble with this structure.  I am trying to generate a terrain with a lot of vertices - more than 1 million. This seems to work, but as I refill the buffer I get memory related issues (crushes that occur, more or less randomly).

So again the question is, is this a good data structure to use / and look for the faults in my code, or should I change to something else? Or what data structure would be advisable?


texts:
I was attempting to make a game in Construct 2 by using my Spriter Models plugin. However, when I imported the model, rescaled it & changed a few things, I got this:

As seen in the picture, the Spriter model is not touching the platform ground.

Do you know of any ways I could have the model touch the ground?

Thanks in advance,

Jamie

Ps. Here is the link to the files, just in case you guys might wanna have a look at it:

https://drive.google.com/folderview?id=0B11opD9YgSqWbVhaNEVTcGhIRTA&usp=sharing

Pps. You will need the Spriter plugin for Construct 2 to open the project file. The Spriter model files will need Spriter to open it.


texts: How to detect when a character is walking on an item in Java?

texts:
To detect if a character is on an item on the floor, I can check every item on the map and do a collision check, and repeat the process every iteration.

Is there another way to do it, without checking every item?

I'm using Java, maybe the language offers a smart way to do this.


texts: Problem to match font size to the screen resolution in libgdx

texts:
I'm having problems to show text on my game at same size on different screens, and I did a simple test.

This test consists to show a text fitting at the screen, I want the text has the same size independently from the screen and from DPI.

I've found this and this answer that I think should solve my problem but don't. In desktop the size is ok, but in my phone is too big.

This is the result on my Nexus 4: (768x1280, 2.0 density)

And this is the result on my MacBook: (480x800, 0.6875 density)

I'm using the Open Sans Condensed (link to google fonts)

As you can see on desktop looks good, but on the phone is so big.

Here the code of my test:

public class TextTest extends ApplicationAdapter
{
    private static final String TAG = TextTest.class.getName();
    private static final String TEXT = "Tap the screen to start";

    private OrthographicCamera camera;
    private Viewport viewport;

    private SpriteBatch batch;
    private BitmapFont font;

    @Override
    public void create ()
    {
        Gdx.app.log(TAG, "Screen size: "+Gdx.graphics.getWidth()+"x"+Gdx.graphics.getHeight());
        Gdx.app.log(TAG, "Density: "+Gdx.graphics.getDensity());

        camera = new OrthographicCamera();
        viewport = new ExtendViewport(Gdx.graphics.getWidth(), Gdx.graphics.getWidth(), camera);
        batch = new SpriteBatch();

        FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/OpenSans-CondLight.ttf"));
        font = createFont(generator, 64);
        generator.dispose();
    }

    private BitmapFont createFont(FreeTypeFontGenerator generator, float dp)
    {
        FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();

        int fontSize = (int)(dp * Gdx.graphics.getDensity());
        parameter.size = fontSize;

        Gdx.app.log(TAG, "Font size: "+fontSize+"px");

        return generator.generateFont(parameter);
    }

    @Override
    public void render ()
    {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        int w = -(int)(font.getBounds(TEXT).width / 2);

        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        font.setColor(Color.BLACK);
        font.draw(batch, TEXT, w, 0);
        batch.end();
    }

    @Override
    public void resize(int width, int height)
    {
        viewport.update(width, height);
    }

    @Override
    public void dispose()
    {
        font.dispose();
        batch.dispose();
    }
}

I'm trying to find a neat way to fix this.
What I'm doing wrong? is the camera? the viewport?

UPDATE:

What I want is to keep the same margins in proportion, independently of the screen size or resolution. This image illustrates what I mean.


texts: Client side latency when using prediction

texts:
I've implemented Client-Side prediction into my game, where when input is received by the client, it first sends it to the server and then acts upon it just as the server will, to reduce the appearance of lag.  The problem is, the server is authoritative, so when the server sends back the position of the Entity to the client, it undo's the effect of the interpolation and creates a rubber-banding effect.

For example:
Client sends input to server -> Client reacts on input -> Server receives and reacts on input - > Server sends back response -> Client reaction is undone due to latency between server and client

To solve this, I've decided to store the game state and input every tick in the client, and then when I receive a packet from the server, get the game state from when the packet was sent and simulate the game up to the current point.

My questions:

Won't this cause lag? If I'm receiving 20/30 EntityPositionPackets a second, that means I have to run 20-30 simulations of the game state.

How do I sync the client and server tick? Currently, I'm sending the milli-second the packet was sent by the server, but I think it's adding too much complexity instead of just sending the tick.  The problem with converting it to sending the tick is that I have no guarantee that the client and server are ticking at the same rate, for example if the client is an old-end PC.


texts: Why does my simple OpenGL shadow map fail?

texts:
I want to render a simple shadow map for grass, where closer looks brighter and further looks darker, from the view of the light point. I can't get it to work.

Here is the relevant code:

//setting up buffers
gl.glGenFramebuffers(1, framebuff);
gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, framebuff.get(0));

gl.glGenTextures(2, textureBuff);
gl.glBindTexture(GL4.GL_TEXTURE_2D, textureBuff.get(0));
gl.glTexStorage2D(GL4.GL_TEXTURE_2D, 1, GL4.GL_R32F, displayWidth, displayHeight);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_MAG_FILTER, GL4.GL_LINEAR);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_MIN_FILTER, GL4.GL_LINEAR_MIPMAP_LINEAR);
gl.glFramebufferTexture(GL4.GL_FRAMEBUFFER, GL4.GL_COLOR_ATTACHMENT0, textureBuff.get(0), 0);

gl.glBindTexture(GL4.GL_TEXTURE_2D, textureBuff.get(1));
gl.glTexStorage2D(GL4.GL_TEXTURE_2D, 1, GL4.GL_DEPTH_COMPONENT32F, displayWidth, displayHeight);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_MAG_FILTER, GL4.GL_LINEAR);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_MIN_FILTER, GL4.GL_LINEAR_MIPMAP_LINEAR);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_COMPARE_MODE, GL4.GL_COMPARE_REF_TO_TEXTURE);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_COMPARE_FUNC, GL4.GL_LEQUAL);
gl.glFramebufferTexture(GL4.GL_FRAMEBUFFER, GL4.GL_DEPTH_ATTACHMENT, textureBuff.get(1), 0);
gl.glDrawBuffer(GL4.GL_NONE);

if(gl.glCheckFramebufferStatus(GL4.GL_FRAMEBUFFER) != GL4.GL_FRAMEBUFFER_COMPLETE)
         System.out.println(gl.glCheckFramebufferStatus(GL4.GL_FRAMEBUFFER));

Drawing command (unsure if it's correct):

//gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, framebuff.get(0));
gl.glViewport(0, 0, displayWidth, displayWidth);
gl.glEnable(GL4.GL_POLYGON_OFFSET_FILL);
gl.glPolygonOffset(2.0f, 4.0f);

/*
gl.glClearBufferfv(GL4.GL_COLOR, 0, new float[] {0, 0, 0}, 0);
gl.glClearDepth(1.0f);
gl.glClear(GL4.GL_DEPTH_BUFFER_BIT);*/

setupMVPMatrix();
gl.glBindVertexArray(vaoBuff.get(0));

gl.glUseProgram(shaderProgram);
gl.glDrawArraysInstanced(GL4.GL_TRIANGLE_STRIP, 0, 5, 512 * 512);

gl.glDisable(GL4.GL_POLYGON_OFFSET_FILL);
//gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, 0);

When I comment the glBindFramebuffer(), the grass appears correctly with the white color (from the light point of view, which shows the matrix should be correct):

But if I call glBindFramebuffer() with the depth test enabled, everything just disappears. I have also checked the framebuffer status, yet it seems there is no error.

What might cause this?


texts: Storing large array of tiles, but allowing easy access to data

texts:
I've been thinking about this for a while. I have a 2D tile bases platformer in XNA with a large array of tile data, I've been running into memory problems with large maps. (I will add chunks soon!)

Currently, Each tile contains an Item along with other properties like how its rotated, if it has forground / background, etc.

An Item is static and has properties like the name, tooltip, type of item, how much light it emits, the collision it does to player, etc. Examples:

public class Item
{
    public static List<Item> Items;

    public Collision blockCollisionType;
    public string nameOfItem;
    public bool someOtherVariable,etc,etc

    public static Item Air
    public static Item Stone;
    public static Item Dirt;
    static Item()
    {
       Items = new List<Item>()
       {
            (Stone = new Item()
            {
                nameOfItem = "Stone",
                blockCollisionType = Collision.Solid,
            }),
            (Air = new Item()
            {
                nameOfItem = "Air",
                blockCollisionType = Collision.Passable,
            }),

        };
    }
}

Would be an Item, The array of Tiles would contain a Tile for each point,

public class Tile
{
     public Item item; //What type it is
     public bool onBackground;
     public int someOtherVariables,etc,etc
}

Now, Most would probably use an enum, or a form of ID to identify blocks. Well my system is really nice just to find out about an item. I can simply do tiles[x,y].item.Name To get the name for example. I realized my Item property of the tile is over 1000 Bytes! Wow! What I'm looking for is a way to use an ID (Int or byte depending on how many items) instead of an Item but still have a method for retreiving data about the type of item a tile contains.


texts: Can I create an offscreen plain surface with a pointer to pre-allocated surface data?

texts:
I thought I read somewhere that one could create a 'offscreen plain surface' from an existing system memory buffer, but I cannot seem to find the reference anymore.

My use case is copying a frame from video memory to a pre-allocated buffer, and right now I perform this in two steps: copying to an 'offscreen plain surface' (GetRenderTargetData), and from that to a pre-allocated buffer.  If I could create the surface from the pre-allocated buffer, it would save a copy. I am using Direct3D9Ex on Windows 7.


texts: Hide client-server communication from HTTP debuggers

texts:
I'm developing a mostly off-line game. However, it'll communicate with the server for the following:

Collect data, statistical purposes (Yup, players will be notified and can opt-out).
Trigger and generate resources for daily gifts, events, etc...

The problem is, if I used any HTTP debugger (Say, Charles Proxy) I can see everything (No encryption is being used).

I want to hide the data about daily gifts, events, etc... or else any player with malicious intent can tamper with the requests/responses as s/he sees fit (which can affect other players as well).

Seems far-fetched?

Actually, I wanted to apply some kind of encryption, however, I came across few games that managed to hid their activity altogether. Doing a quick research, it seems they use SOCKS and not HTTP, A thing I have a lack of experience in.
Example of such games includes Clash of Clans.

So is there a practical way to achieve the desired results?


texts: Detecting collision between browser window middle point and other sprites visible in the window

texts:
In HTML5 canvas, I have an object which is always in the middle point. On the big map there are other moving objects. I want to detect if the middle point of the window hit any shape we see on the window. I wonder if there is a way to only detect collision between the middle point and the shapes that are visible in the window so I don't have to iterate through all shapes on the map (could be many thousands of shapes).

Is there a good solution to this kind of collision detection? Assume that I have already known how to write the collision detection code for the middle point and shapes.


texts: How to get "this" object collider name when OnTriggerEnter is fired?

texts:
I have a "car" object with 2 colliders attached, a base and a top collider. Then I have a script attached to my car.
I'm using OnTriggerEnter event to detect collisions with an invisible "Checkpoint".
The problem is that OnTriggerEnter is called twice, I suppose because it is called either from the base collider and top collider.
I want to check my object collider's name.
OnTriggerEnter expose me with "other" collider; however, how can I test my collider's name?


texts: Adding lighting to custom vertex shader in Unity

texts:
What's the simplest way to add shadow functionality based on the modified vertices, nothing I've found online seems to work
 Shader "Unlit/HyperUnlit"
 {
     Properties
     {
         _MainTex ("Texture", 2D) = "white" {}
         _Color("Color", Color) = (1,1,1,1)
     }
     SubShader
     {
         Tags { "RenderType"="Opaque" }
         LOD 100

         Pass
         {
             CGPROGRAM
             #pragma vertex vert
             #pragma fragment frag

             #include "UnityCG.cginc"
             #include "Complex.cginc"

             struct appdata
             {
                 float4 vertex : POSITION;
                 float2 uv : TEXCOORD0;
             };

             struct v2f
             {
                 float2 uv : TEXCOORD0;
                 UNITY_FOG_COORDS(1)
                 float4 vertex : SV_POSITION;
             };

             sampler2D _MainTex;
             float4 _MainTex_ST;
             fixed4 _Color;

             //Params
             float Tscale;
             float3 Tpos;
             float klein;
             float Rscale;

             //Mobius Transformation (a,b,c,d)
             float2 a;
             float2 b;
             float2 c;
             float2 d;

             v2f vert (appdata v)
             {
                 v2f o;
                 //Reduce to float3
                 float3 worldPos = mul(unity_ObjectToWorld, float4(v.vertex.xyz, 1)).xyz;

                 //2. Apply linear transformations
                 worldPos *= Tscale;
                 worldPos += Tpos;

                 //3. Apply mobius transformation
                 worldPos = MobiusXZ(a,b,c,d, worldPos);

                 //4. Klein?
                 if (klein==1)
                 {
                     worldPos = PoincareToKlein(worldPos);
                 }

                 //5. Scale to disk radius
                 worldPos *= Rscale;

                 //Convert back to ? space
                 o.vertex = mul(UNITY_MATRIX_VP, float4(worldPos, 1));

                 //transform position to clip space
                 //o.vertex = UnityObjectToClipPos(v.vertex);
                 o.uv = TRANSFORM_TEX(v.uv, _MainTex);

                 return o;
             }

             fixed4 frag (v2f i) : SV_Target
             {
                 // sample the texture
                 fixed4 col = tex2D(_MainTex, i.uv) * _Color;
                 return col;
             }
             ENDCG
         }
         UsePass "Legacy Shaders/VertexLit/SHADOWCASTER"
     }
 }


texts: Projectile Not Correctly Inheriting Parent Velocity (Unity3D)

texts:
I am trying to fire projectiles from a player who is moving at very high speeds. The issue is that the bullets do not seem to inherit the angular velocity. If the player is moving in a straight line at 500 U/s, then the bullet correctly inherits that velocity and adds its own speed onto that:

GameObject bullet = Instantiate(projectile, gun.transform.position, gun.transform.rotation);
bullet.GetComponent<Rigidbody>().velocity = r.velocity + bullet.transform.forward *bulletSpeed;

However, if the player is turning really quickly, it does not inherit the rotational velocity, and the bullet looks like it veers off to the side.

How can I implement this? I tried assigning the angular velocity of the player to the bullet, but this just caused the bullet to spin while moving in the same direction.

Some extra details:

I am using rigidbody.MoveRotation() to rotate my player, but I manually calculated angularVelocity to assign it to the bullet
I tried moving the player with AddTorque(), but could not produce any results with the bullets


texts: Resources to help study of Quake 3 engine

texts:
Are there good resources ( manuals, tutorials, etc ) to start studying the code of the Quake 3 engine beyond the code itself?

I'm very interested in know how it's structured for educational purposes and maybe to do some modifications.


texts: How do you register two or more keys properly?

texts:
I am experimenting with KeyListeners and I thought about how do I register two or more keys, this is my code so far:
package engine.listeners;

import engine.Frame;
import engine.KeyCodes;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import javax.swing.*;

public class Key extends KeyAdapter implements KeyCodes, ActionListener {

    private static HashSet<Integer> keyMap = new HashSet<>();
    private Timer tm;

    public Key() {
        tm = new Timer(0, this);
        tm.start();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (!keyMap.contains(e.getKeyCode())) keyMap.add(e.getKeyCode());
    }

    @Override
    public void keyReleased(KeyEvent e) {
        keyMap.remove(e.getKeyCode());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int x = Frame.moveMe.getX();
        int y = Frame.moveMe.getY();
        if (keyMap.contains(arrowLeft)) Frame.moveMe.setXY(--x, y);
        if (keyMap.contains(arrowUp)) Frame.moveMe.setXY(x, --y);
        if (keyMap.contains(arrowRight)) Frame.moveMe.setXY(++x, y);
        if (keyMap.contains(arrowDown)) Frame.moveMe.setXY(x, ++y);
    }
}

Right here, it's doing 2 registered keys properly, for example arrow left and arrow top goes diagonal left top.
But one thing I noticed, sometimes when I registered 3 or more keys, it's not working properly for example: arrow left, arrow right, and arrow up should just go up, but what happened is it ignored the key 'right', and so it continues going diagonal top left.
Is there a way to improve this? or should I implement another type of listener that is not buggy as KeyListener?


texts: Should I share classes on the server with the client?

texts:
I am fortunate being able to use the same programming language on both the server and client (javascript). I would therefore like to share my code and classes between server and client, like Half-Life (and possibly others) did.

To make things simple, suppose I have an MMO with a Player and an Enemy class, with a position, velocity, and health.

var Player = function() {
    this.health = 100;
    this.x = 0;
    this.y = 0;
}

var Enemy = function() {
    this.health = 100;
    this.x = 0;
    this.y = 0;
}

I know ideally these should inherit from each other (or use a CES system). But my question is as follows:

Since these classes will be used on the client and server (since both client and server needs to know about these entities) with some but not all shared logic, would it not be crazy to define two separate classes on both the server and client?

What are the advantages and disadvantages of sharing classes between server and client?

Are there any helpful websites with tips/tricks for this approach?


texts:
I'm currently trying to implement a move-to-drag behaviour in a 2d grid based game. I want to update the camera such that if follows the "head" of the trail being drawn - In this case, the nodes it is made up of some nodes returned from A* pathfinding utility implementation.

AStarPathfind pather = new AStarPathfindAroundWalls(
    LayerMask.GetMask("Walls"),
    Camera.main.ScreenToWorldPoint(Input.mousePosition)
);
List<Vector2> trailPoints = pather.FindPath(new Vector2(this.transform.position.x, this.transform.position.y));
Camera.main.transform.position = new Vector3(
    trailPoints[ArrowTrailPoints.Count - 1].x,
    trailPoints[ArrowTrailPoints.Count - 1].y,
    Camera.main.transform.position.z
);

When I run this code, the camera sucessfully does indeed snap to the head of the path, but unfortunately, the mouse remains where it originally was, and since this code is ran during an update loop, it will simply keep adding to the path until it can no longer do so. Essentially I would like it to go to the next tile, update the camera, reset the mouse position and then await where the next part of the path should be drawn (of course, this is not possible, since I cannot modify the mouse position directly).

I've tried storing the trail points as a property in the object, and then removing the last known position from the calculation, like so

Camera.main.ScreenToWorldPoint(Input.mousePosition) - lastTrailPoints[lastTrailPoints.Count - 1]

so that the input position would be relative to the amount offset by the camera... but with no success, so I'm starting to think I'm way off using this method. If I do something like

Camera.main.ScreenToWorldPoint(Input.mousePosition) - (MovementNodes[MovementNodes.Count - 1] - this.transform.position)

Then things work almost as expected, but the mouse will still move off of the screen, and I want to keep it centered over the actual head of the trail (where the camera is).

(black cross = current mouse position, green cross = where I want the mouse pointer to be located, camera is centered over the arrow head/green cross)

Has anyone implemented something similar before and know of a solution?


texts: Is Updating Sprite/Entity Movement Using Framerate Necessary?

texts:
Apologies if this is a dumb question I'm still new to this, but I'm trying to understand if calculations of sprite movements/hitboxes/etc. is necessary or is generally better than just using fixed values to calculate movement or events (i.e movement += velocity/framerate vs. movement += velocity/constant).

The main reason I ask is that while following tutorials for basic movements they use the frame rate to determine how to move the sprites, but I haven't seen a full explanation as to why things are done that way. While I was using these tutorials, things seemed to work well, but after I moved past them I've run into odd issues. I'm not sure if that was just because the games in the tutorials were very simple, like pong and breakout, and I just didn't notice these problems.

For example, I made a very simple demo where I take a sprite and have it bounce off the edges of the screen. When it reaches the edge the velocity reverses and it goes in the opposite direction. While the numbers show as correctly calculated, visually it's wrong, either rebounding early or beyond the edges of the screen. However, when I replace frame rate with a constant number it works perfectly. Even when I replace the frame rate with a random value of particular range (say 45-60) it works well. It seems to me on the occasion that the frame rate dips below 30, it throws off everything and doesn't recover.

I've heard about limiting frame rate and that makes sense in a capping the top way, but is limiting it below also something that is done? If so, it doesn't seem too different from just putting in a constant and I wonder what benefits using frame rate even has at that point.

tl;dr: I guess what I'm asking is what are the pros and cons of using frame rate to determine how things move/interact vs using constant values and will it create problems down the line if I try to forgo frame rate completely?


texts:
I have some difficulties to understand how to correctly use GetTickCount() as I have
some problems in my little game. I have to place on a case a space ship. This one will shoot
with a certain frequence some missiles.

Edit: It works good now, I edit the code below. However there is an other problem, I don't know why there is only one shooting space ship.

I hope someone has an explanation for that.

MyGameEngine::MyGameEngine(...) : tickTime(0) {}     // for the constructor...

DWORD prev_frame_tick;
DWORD curr_frame_tick = GetTickCount();

// function called everytime (loop)
void MyGameEngine::idle() {

    prev_frame_tick = curr_frame_tick;
    curr_frame_tick = GetTickCount();
    tickTime += curr_frame_tick - prev_frame_tick;
    int i;

    // SPACE SHIP
    for (i = 0; i < ship->size(); i++)
    {
        // verify if tickTime > freqShoot : if true return new missile with correct positions
        Missile* m = ship->at(i)->tick(tickTime);

        if (m != NULL) {
            missiles->push_back(m);
            std::cout << "new miss" << std::endl;    // I have to put this, however nothing on screen
            tickTime = 0;
        }
    }

    // MISSILES ANIMATION
    for (i = 0; i < missiles->size(); i++)
    {
        missiles->at(i)->tick();

        if (missiles->at(i)->getBordDroitX() > 1.0f) {
            missiles->erase(missiles->begin() + i);
        }
    }
}

Missile* Ship::tick(DWORD t) {
    Missile* m = NULL;
    if (t > freqTir) {
        m = new Missile(posX, posY, width, height, numCase);
    }
    return m;
}


texts:
Rendering foliage usually involves "hanging" triangles and textures that have completely transparent areas. I'm interested in knowing how are these usually handled by a 3D engine.

The first thing that comes into mind is blending, but the issue with blending is that it requires depth sorting and while on a per-object basis this isn't an issue, proper foliage drawing would require that all triangles on the object are depth sorted otherwise parts of the foliage object behind the transparent parts of branches or leaves could potentially not get rendered at all. Even with per-triangle depth sorting, the issue wouldn't go away completely.

Another approach would be to use discard in the fragment shader, however that could prevent the GPU from performing the early depth test. Is this an issue though? Maybe foliage is usually rendered with basic fragment shaders, so the performance impact is negligible?

As you can see, i have a few ideas on how this could be done, what i'm looking for though is how it is actually done. I'm sure that lots of people have hands-on experience with this, so please share practical solutions.


texts: Terrain Rendering/Update Failure Python 3.x

texts:
I have begun to create a procedurally generated RPG using Python, and I am having trouble with rendering the terrain.
What is happening:
I generate some terrain from some files, or create/save new terrain, and display it on the screen as a 2D B&W heightmap; black = low elevation, white = high elevation. The data are stored in .txt files, formatted as a series of arrays populated with floats.
When the game loads, the terrain is displayed properly, however, once you begin to move around, the terrain begins to act funky.

If you move far from where you start, the terrain becomes gridlike.
If you move horizontally, the terrain becomes somewhat vertically offset.
If you move vertically, the terrain does not update.
Even if you DO move horizontally before/after moving vertically, the terrain will not update vertically, only horizontally.

What I just said, but with images/video.
EDIT: I think the problem occurs in this block of code, but I can't be sure. This is taken from grid_generator.py. It returns a merged grid from the 3x3 area around a given point, where merge, loadGrid, and findAdjFnames are custom functions within grid_generator.py.
def threeBYthree(x,y):
    g = []
    for gy in range(-1,2):
        g.append([])
        for gx in range(-1,2):
            adj = findAdjFnames(x + gx,y + gy)
            print(adj)
            shouldSave = not os.path.isfile('./assets/grids/' + str(x + gx) + '_' + str(y + gy) + '.txt')
            print(shouldSave)
            g[gy + 1].append(loadGrid(str(x + gx) + '_' + str(x + gy) + '.txt', adjF = adj, andSave = shouldSave))

    #merge upper four
    g3a = merge(g[0][0],g[0][1],g[1][0],g[1][1])

    #merge bottom-left two
    g3b = []
    for y in range(len(g[2][0])):
        g3b.append(g[2][0][y] + g[2][1][y][1:])

    #merge top-right two
    g3c = []
    for y in range(len(g[0][2])+len(g[1][2])):
        if y < len(g[0][2]):
            g3c.append(g[0][2][y])
        elif y == len(g[0][2]):
            pass
        else:
            g3c.append(g[1][2][y-len(g[0][2])])

    #merge all
    g3d = merge(g3a,g3c,g3b,g[2][2])

    return g3d

The problem may occur somewhere else, but this bit is what I most recently worked on before the code stopped working.
Pastebin files:
Terrain functions: grid_generator.py
Main game loop: main_test.py
Terrain file for coordinate (0,0): 0_0.txt
NOTE: irrelevant, and some necessary, functions have been removed for privacy and security reasons. If you feel that this includes information required for a fix, please comment.


texts: Compressed vs Uncompressed Textures differences?

texts:
What is the difference?

As far as i know, compressed textures would speed things up, because the PCIe bus has to transfer less amount of data, and the interconnect is the main latency issue with GPU's. For this i'm certain.

What i'm not sure of, and this is what i mainly want an answer to is, does the GPU decompress the textures on the fly, or does it display the uncompressed textures? In other words, is there any visual impact of using the compressed textures? The GPU decompresses them automatically? Does this vary with the compression algorithm used, or is it a GPU specific thing?

Thanks in advance.


texts: How can I replace an object with a prefab so the prefab will be at the same position of the gameobject?

texts:
I have some doors in the scene, each door at another position.
I took one of the doors added to it a light and made a prefab of the door.

Now I want to replace all the other doors with the prefab.

Example of the door with the light I added and this door is also a prefab:

And this is example of another door that is not yet replaced by the prefab door with the light:

I want to replace this door with the prefab door with the light at the first screenshot. The question is if there is a easy way to do the replace ?

I have more doors that I want to replace.


texts: 2D platformer:How to avoid "bouncing descend" when walking down slopes?

texts:
I've been working on implementing slope collision by SAT(Separating Axis Theorem). And then I have a trouble. When my character walks down slope, it moves like a bouncing ball:

The slope has 3 sprites (45°):

Here is my current code with JavaScript:

slopes.forEach((slope) => {
    //Minimum Translation Vector
    let mtv = character.collidesWith(slope);

    if(mtv.overlap !== 0) {
        character.velocityY = 0;
        character.positionY -= mtv.overlap;
    }
});

It works good when moving up, but bouncing when down, I have no idea how to keep the character stay on slope when walking down. Please, any help would be appreciated.


texts: How to chain actions/animations together and delay their execution?

texts:
I'm trying to build a simple game with a number of screens - 'TitleScreen', 'LoadingScreen', 'PlayScreen', 'HighScoreScreen' - each of which has it's own draw & update logic methods, sprites, other useful fields, etc. This works well for me as a game dev beginner, and it runs.

However, on my 'PlayScreen' I want to run some animations before the player gets control - dropping in some artwork, playing some sound effects, generally prettifying things a little. However, I'm not sure what the best way to chain animations / sound effects / other timed general events is.

I could make an intermediary screen, 'PrePlayScreen', which simply has all of this hardcoded like so:

Update(){
     Animation anim1 = new Animation(.....);
     Animation anim2 = new Animation(.....);
     anim1.Run();
     if(anim1.State == AnimationState.Complete)
          anim2.Run();
     if(anim2.State == AnimationState.Complete)
          // Load 'PlayScreen' screen
}

But this doesn't seem so great - surely their must be a better way? I then thought, 'Hey - an AnimationManager! That'd be awesome!'. But then that creeping OOP panic set in as I thought about it some more.

If I create the Animation in my Screen, then add it to the AnimationManager (which may or may not be a GameComponent hooked up to Update/Draw), how can I get 'back' to it? To signal commands like start / end / repeat? I'd still need to keep a reference to the object in my Screen so that I could still communicate with it once it's buried in the bosom of a List in my AnimationManager. This seems bad.

I've also tried using events - call 'Update' on all the animations in the PlayScreen update loop, but crucially all of the animations have a bool flag ('Active') which determines whether they should begin. The first animation has this set to 'true', all others 'false'. On completion the first animation raises an event, which sets animation 2's bool flag to true (and so it then runs). Once animation 2 is complete another 'anim complete' event is raised, and the screen state changes.

Considering the game I'm making is basically as simple as it gets I know I'm overthinking this... it's just the paradigm shift from web -> game development is making me break out in a serious case of the stupids.


texts: How can I fix these errors with Panda3D's sample projects?

texts:
I just installed the latest Panda3D packages on a Mint 12 32-bit virtual machine. Then I downloaded and configured Eclipse and tried to run the Asteroids sample project. The window is created properly. But after rendering the scence once the game freezes. This happens with the other sample apps, too.

Here's the error log:

DirectStart: Starting the game.
Known pipe types:
  glxGraphicsPipe
(all display modules loaded.)
:display:gsg:glgsg(warning): Occlusion queries advertised as supported by OpenGL runtime, but could not get pointers to extension functions.
OpenGL Warning: glXChooseFBConfig returning NULL, due to attrib=0x6, next=0xffffffff
:display:glxdisplay(warning): No suitable FBConfig contexts available; using XVisual only.
depth_bits=16 color_bits=24 alpha_bits=8 stencil_bits=8 accum_bits=64 back_buffers=1 stereo=1 force_hardware=1
AL lib: pulseaudio.c:331: PulseAudio returned minreq > tlength/2; expect break up
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 5703 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4654 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4654 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 5703 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 3057 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 3057 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
OpenGL Warning: No pincher, please call crStateSetCurrentPointers() in your SPU
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 5703 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 5703 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 3661 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 3661 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 5703 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display(error): Deactivating glxGraphicsStateGuardian.

What can I do to fix the problem ?


texts: How to connect to a server without hard coded passwords?

texts:
I have two features in my game that need to a server of some kind that require authentication: a bug reporter and a leaderboard.

The bug reporter will take the users report and add it as a card to my trello board. In my code I have my personal accounts key and token, the board name, and the list name. This is hard coded so if someone ever decompiled my game, they could destroy my trello board. They could spam it, add new lists, delete my existing lists etc.

The leaderboard can't use something like steamworks leaderboards or gamecenter leaderboards as I intend to sell my game on many different stores, some of which don't have leaderboard systems. I also don't want to have to manage different leaderboard systems for every store - that will get messy.

How can I connect to my own server with a database of scores without hard coding the password into my script?

I've seen people say to put it into App.Config, but I believe that is only for winforms/wpf etc. Some say to store it in an encrypted config file, but then I will need to store the key to decrypt it somewhere... Others say it's completely pointless and futile.

Surely there must be a way!


texts: Handling buildings in isometric tile based games

texts:
A simple question, to which i couldn't find a definitive answer - how to manage buildings on a tiled map? Should the building be sliced in to tiles or one big image?

EDIT:
The game is being built from scratch using C++/SDL 2.0, it will be a turn based strategy, something like Fallout 1 & 2 without the hex grid, a simple square grid, where the Y axis is squished by 50%.
Buildings can span multiple tiles, the characters move tile by tile. For now, the terrain is completely flat. Some basic functionality is in place, so I'm aiming to advancing the terrain and levels them selves - adding buildings, gates, cliffs, not sure about the elevation.


texts:
I am planing to Write a Text adventure and I don't know how to make the text draw letter by letter in any other way than changing the variable from
h to he to hel to hell to hello
That would be a terrible amount of work since there are tons of dialogue.

Here is the source code so far

protected override void Update(GameTime gameTime)
{
    //input code removed for clarity

    if (Dialogue == 1)
    {
        Row1 = "Input Text 1 Here.";
        Row2 = "Input Text 2 Here.";
        Row3 = "Input Text 3 Here.";
        Row4 = "Input Text 4 Here.";
    }
    if (Dialogue == 2)
    {
        Row1 = "Text 1";
        Row2 = "Text 2";
        Row3 = "Text 3";
        Row4 = "Text 4";
    }

    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin();
    spriteBatch.Draw(sampleBG, new Rectangle(0, 0, 800, 600), Color.White);
    spriteBatch.Draw(TextBG, new Rectangle(0, 400, 800, 200), Color.White);
    spriteBatch.DrawString(defaultfont, Row1, new Vector2(10, (textheight + (rowspace * 0))), Color.Black);
    spriteBatch.DrawString(defaultfont, Row2, new Vector2(10, (textheight + (rowspace * 1))), Color.Black);
    spriteBatch.DrawString(defaultfont, Row3, new Vector2(10, (textheight + (rowspace * 2))), Color.Black);
    spriteBatch.DrawString(defaultfont, Row4, new Vector2(10, (textheight + (rowspace * 3))), Color.Black);
    spriteBatch.End();
    base.Draw(gameTime);
}


texts:
I would just like to know if there is a way to work out the distance of a jump depending on how fast the player is going. For example if the player has a velocity X of 10 and he presses the jump button he should jump further than if his X velocity was, say 4.

I have a working jump mechanic that when the jump button is pressed the velocity is set to a predefined value like -10; Then slowly gravity brings it down but I want it to feel more realistic by applying the jump distance according to his speed

Any way to implement this?


texts: (Tiled) Background stops being rendered in libGDX

texts:
I'm using Tiled and I created my background as an image in a Tile Layer.
When I load the map in LibGDX, it shows fine. However when the camera moves, the whole background dissapears.

The problem is solved if I add the background as an Image Layer.

Any idea what's causing the problem in the Tile Layer?


texts: Can and should a game design be patented?

texts:
I have an idea for a game that I want to develop and I feel is unique, and I'm wondering if I should patent it.  I read on the web that games can be patented, but just because it can be done doesn't mean that it makes sense to do it.

I actually don't really want patent it (it's expensive, a hassle and I don't believe in patenting of ideas... unless it's something truly revolutionary). However, I'm concerned a bigger company could come along, with more experienced game designers and developers and steal the idea.


texts: Why would a Bounding Sphere and BoundingBox not intersect (when they should)?

texts:
I have a bounding sphere and a bounding box that should be intersecting, however, Intersects(...) is returning false. For example, the following returns false:

new BoundingSphere(new Vector3(500, 105, 0), 25).Intersects(
    new BoundingBox(new Vector3(466,219,0), new Vector3(519,26,0))
)


texts:
I have some NPCS protecting a treasure room in a friendly building. But if the player comes close they turn hostile. I don't know if the NPCS should attack everyone when triggered or only attack the player that triggered them. The latter seems good but if another player could sneak behind the guards whilst they attack someone else and succeed in an easy victory. How should I tackle this issue. If I use the former a random person who didn't do anything but is peacefully looking at the situation could get attacked which isn't RP-Friendly.

By adding more NPCS it kills a main attacker faster however doesn't solve the latter.

By adding more NPCS in the room would cause problems as it is smaller than a cubicle because of the design of the room being centred on the middle but making it larger it loses it's attention.

By simply removing the guards but adding another room before the treasure room, where the guards are. This is ok to stop the first issue because not many players will enter but it will lose the curiosity of guards guarding a door but rather another door.


texts:
How do I render halfspace fog? From my interpretation, I have a transparent plane in the scene. Then I use a function that returns a fog color in my shader.
Do I render the transparent plane by itself or with the other objects in the scene?
And also, do I make the plane transparent?


texts: How do you accommodate newbies while still creating depth in the design of light/dark systems for MUDs (or other text-based games)?

texts:
I've been pondering a redesign of our MUD's light/dark system. Our current system accommodates new players by simply not saddling them with being unable to see should they happen to wander outside of a populated area at night. I would like, in redesigning the light system, to stop making accommodations. I take the accommodations as a sign the system is less than ideal for everyone.

I appreciate the way visual games are afforded to handle this; we can generally see the area around our character, and in some cases can obtain bonuses to the radius within which we can see. I haven't been able to come up with a good way to port this concept to a MUD, at least without a concept of relative position that our current code-base just doesn't support. If we didn't have multiple player sub-classes based on the darkness they can create, I would be inclined to make it so all players can see the room they're in, get rid of torches, and be done with it.

I've spent a few hours searching and have failed to dig up compelling discussions on the topic. I'm sure they exist--I find it hard to believe the topic hasn't been aired somewhere. I'm curious how others would approach a light/dark system needing no exceptions for newbies, while still being able to accommodate classes, such as the undead, which need darkness (indeed, part of their power comes from their ability to keep others from seeing.)


texts:
If you have SpriteA and SpriteB.

SpriteB is a child of SpriteA.

Does anyone have a mechanism to come up with the left, right, top, side of a boundingbox() of SpriteA?

What I'd like to do is align SpriteB with the edge of SpriteA. Right now when created, SpriteB is centered with SpriteA.


texts: Unity performance issues when rendering items

texts:
I'm trying to get the position of items in the game world and render them onto the screen. I've managed to get this working, however I seem to be running into major performance issues when ever I enable this feature. I am losing about 40-50 fps. I have a feeling this is related to iterating through the array doing the transformation within the OnGUI() life cycle method which is called multiple times a frame, however I'm not entirely sure. Any pointers would be appreciated, I'm still very new to game development.

Code in question:

private void OnGUI()
{
    if (showItems)
    {
        DrawLoot();
    }

    if (showItems && Time.time >= itemNextUpdateTime)
    {
        lootItems = UnityEngine.Object.FindObjectsOfType<LootItem>();
        itemNextUpdateTime = Time.time + itemUpdateInterval;
    }
}

Draw Method:

public void DrawLoot()
{
    foreach (LootItem item in lootItems)
    {
        if (item == null || item.name == null || item.name == string.Empty)
        {
            continue;
        }

        var pos = Camera.main.WorldToScreenPoint(item.transform.position);
        float itemDistance = Vector3.Distance(Camera.main.transform.position, item.transform.position);
        Vector3 vector = new Vector3(pos.x, pos.y, pos.z);
        if (itemDistance <= maxLootDrawingDistance && vector.z > 0.01)
        {
            string itemLabel = $"{item.Item.ShortName.Localized()} - {itemDistance}";
            GUI.Label(new Rect(vector.x - 50f, Screen.height - vector.y, 100f, 50f), itemLabel);
        }
    }
}


texts:
I am attempting to perform shadow mapping with deferred shading, using the following code:

for (auto light : m_ShadowDirs)
{
    //render shadow map
    shadowDirPass(m_ShadowBuffer, light);
    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_ONE);
    // activate shader for non shadow casting lights
    m_ShadowDirLightShader.activate();
    m_FrameBuffer.LightingPass(m_ShadowDirLightShader);
    m_ShadowDirLightShader.setUniform(("WSCamPos"), m_ActiveCamera->getPosition());
    m_ShadowDirLightShader.setDirLight(("dirLight"), static_cast<DirLightData&>(light->getLightData()));
    m_ShadowDirLightShader.setUniform(("ShadowTransform"), m_ShadowDirMatrix);
    //bind depth map
    m_ShadowDirLightShader.bindTexture(("shadowMap"),5, m_ShadowBuffer.getDepthTexture());
    //render
    renderQuad();
    glDisable(GL_BLEND);
}

shadowDirPass(m_ShadowBuffer, light); Simply renders the geometry to the shadow map.
m_FrameBuffer.LightingPass(m_ShadowDirLightShader); Just binds the Gbuffer textures.

I have two directional lights in the scene, one with red colour (1,0,0), and one with blue colour (0,0,1)

One would think that the scene would be coloured purple, but no.
Every time I render (for each) light, the image in the target framebuffer is overwritten completely, instead of blended together. To illustrate this, see the following images:

Above is the scene with a single red light.

Above is the same scene, with a single blue light, but from a different direction. (See shadows).

When I enable both lights, the result is as if the first light was never used, though by stepping through the code, I can confirm that it is definitely going through a render cycle.

I'm pretty sure than I've messed up the blending somehow, but I could use some guidance.


texts: Does iOS support BC4 compressed texture?

texts:
I've been designing a new OpenGL image algorithm using BC4 textures at its core.
It works well accross Windows and Mac, my main targets up to now.

But today, the customer added a new requirement : it should work on iOS too !
I'm starting to worry : is BC4 texture (named GL_COMPRESSED_RED_RGTC1 in OpenGL) supported on iOS devices (tablets & iphones alike) ?

I've read that iOS is OpenGL ES 2.0 capable. But i'm unable to know which textures are supported under this API (except PowerVR ones, which are not compatible with PC & Macs...)


texts: How can I get a 4x4 matrix from a bullet quaternion?

texts:
I'm trying to make a game using JavaScript with Ammo.js ( an implementation of bullet ) and Sylvester to do my matrix maths. The problem is I don't know how to turn the WXYZ that bullet gives into the 4x4 matrix Sylvester needs.

If there is a way to just get Bullet Physics to give me the 4x4 matrix please tell me! I am completely lost here.


texts: How to convert depth values into Unity's distance

texts:
I am new in Unity and now only studying for my work project. I need help with computing real distances from depth values. Can't figure it out.
My shader is:
Shader "Custom/MyDepthShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}

    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert // compile function vert as vertex shader
            #pragma fragment frag // compile function frag as fragment shader

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;
            sampler2D _CameraDepthTexture;

            fixed4 frag (v2f i) : SV_Target
            {
                float depth = tex2D(_CameraDepthTexture, i.uv).r;
                depth = Linear01Depth(depth);
                depth = depth * _ProjectionParams.z;
                return depth;
            }
            ENDCG
        }
    }
}

I Blit then these values from renderTexture to texture2D and use function GetPixel(i,j). Knowing, that a cube is at 1.5 units distance from camera I can't get this value from depth texture. Thank you for your help.
Now I suspect that I have got distance values, but they are biased by 0.5 for some reason... Can anyone explain this as well?
I found how to get distances from depth texture, so basically I can answer this question, but there is still unexplained bias in measurements.


texts: What's the "appLinkUrl" parameter in the "AppInvite" method for?

texts:
I'm trying to figure out what should I assign the appLinkUrl parameter of FB.Mobile.AppInvite method. In documentation it says:

  The AppLink URL to identify your app and also used for deep-linking

Should i pass my Play Store link to it?

Thanks in advance.

The documentation page for FB.Mobile.AppInvite: https://developers.facebook.com/docs/unity/reference/current/FB.Mobile.AppInvite


texts:
Recently, I've been making a 3D game (hint hint my questions), and I recently have modified a pixelization shader from a unity shader graph tutorial. The thing is, I want to render the shader on the WHOLE screen, not just a single object, but while researching, I've come across something called FBOs, that make it pretty much easier (basically just grabs the frame and turns it into an image for you to "process" it before it gets rendered on the screen), but I don't really want to use FBOs. How would I come across doing this? I've researched a little and came across using a quad, but since my game is 3D, not 2D, I have a perspective camera, so I don't know how that would turn out...
any help is appreciated!


texts: What strategies and patterns exist to handle large amounts of game entities?

texts:
I've been wondering this for some time now: Let's say you have a builder game like Anno and let's say you're in the very late game. You have literally thousands of production facilities placed. Each one of these needs base resources and time to produce an output. Also there's modules you can place onto the facility that give some sort of bonus.

Now: How would you make the game check each one of these and act accordingly (look if job is done, when done deliver output, start new job if resources available)?

The simplest I can think of is a loop over each of the facilities. But that just doesn't feel like a good idea due to the amount of facilities and the frequency on which game loops run.

Another thing I can think of is eventing. The facilities could inform the game core about state changes, but I'm having troubles seeing eventing and a game loop together.

As you probably can now tell I have no exp in game development but would like to get some input on that topic.