texts: What is closing and separating velocity in Ian Millington's game physics book?

texts:
I'm working on a physics engine in C++ and chose Ian Millington's Physics Engine Development book as a guide and reference to help me out understand physics concepts and how to implement them.
Yesterday I was reading through the Hard Constraints chapter, particularly the simple collision resolution section and came across an explanation of a physics formula that I couldn't fully comprehend. Millington says "The closing velocity is the total speed at which two objects are moving together" and it is calculated with the following formula:
$$V_c= \dot{P}_a\cdot(\widehat{P_b-P_a})+\dot{P}_b\cdot(\widehat{P_a-P_b})$$
Where \$V_c\$ is the closing velocity, \$P_a\$ and \$P_b\$ are object \$a\$ and \$b\$ respectively. Also he further discusses another formula called the separating velocity which is written as follows:
$$V_s=(\dot{P}_a-\dot{P}_b)\cdot(\widehat{P_a-P_b})$$
Where \$V_s\$ is the separating velocity. Now I don't really understand what these formulas actually are or what they represent in the physics world. I also have trouble wrapping my head around why we need these formulas to perform collision resolution since he used the separating velocity formula to resolve the velocity upon collision and why we need the dot product. It would be really helpful if someone can provide visual explanation that would significantly help me understand what's going on.


texts:
Long story short, I had to roll my own physics engine for my game because box2D and similar packages weren't compatible with the portal based layouts in my game.

So I've made a constraint system and a collision system, which both work somewhat well. But i can't figure out how to combine them, because the constraints are sort of integrated across a time step, while a collision happens at a distinct moment in time, after which the velocity changes drastically, unlike the minor adjustments made in constraints.

How are these two systems integrated with each other?


texts: What in-game user interfaces are available?

texts:
I'm wondering what options are available for in-game interface libraries (not OS-level interfaces) and what are your opinions about them?

Please put only one library per answer and follow this template.

Name
Link to website
Cost
License (if free or open source)
General summary / Opinion


texts: Lighting in Minecraft/Block-esque worlds

texts:
Chaps,
I'm sure we all know at a high level how Minecraft's lighting engine works. Light sources flood surrounding blocks with light, which themselves flood their neighbors and so forth.
However, I believe this doesn't fully explain the picture. For example, consider this image:

Image 01

Clearly the vertical faces of the sand are lower light level than the horizontal faces. With the left faces being even darker than the front faces. I'm unable to see how any incarnation of the above method would produce such results - all faces are exposed to sunlight, they should all be the same brightness surely...

Does Minecraft use an additional layer of OpenGL diffuse lighting? If so, where is the light source? The Sun? What about in caves?
Any insight on this would be much appreciated - Many Thanks!!!


texts: Why are there lines in between my tiles?

texts:
I'm making a top down XNA game.  The maps are created by tiles.  A problem I recently noticed is a 'grid' of lines between the tiles.  It only shows up sometimes and only depending on the camera position.  I let XNA handle the positioning, why are these lines showing up?

Here is a picture with the lines:

However, after moving my camera over just a bit, it magically goes back to how it is supposed to appear:

Thanks for any help!

EDIT:

This is the best I can do for source code, this is an extremely large project and the rendering is done it multiple areas:

Main Render Loop For dynamic elements such as tiles:

    spriteBatch.Begin(SpriteSortMode.Deferred, Nothing, SamplerState.LinearClamp, Nothing, Nothing, Nothing, Matrix.CreateTranslation(CameraX, CameraY, 0))
    Mode.Render(spriteBatch, False)
    For Each j As [Delegate] In DynamicInjectionList
        j.DynamicInvoke(spriteBatch)
    Next
    DynamicInjectionList.Clear()
    spriteBatch.End()

Mode.Render:

For x As Integer = 0 To GRIDMAX - 1
    For y As Integer = 0 To GRIDMAX - 1
        For z As Integer = 0 To 2
            Dim ter As TiledTerrain = Terrain(x, y, z)
            If ter IsNot Nothing Then
                sb.Draw(CBaseClient.TextureLibrary("TileMap"), New Rectangle(x * GRIDSIZE, y * GRIDSIZE, GRIDSIZE, GRIDSIZE), New Rectangle(ter.Texture_X, ter.Texture_Y, GRIDSIZE, GRIDSIZE), Color.White)
            End If
        Next
    Next
Next

TiledTerrain.vb Class:

Imports ProtoBuf

<ProtoContract()> _
Public Class TiledTerrain

    <ProtoMember(1)> _
    Public Property X As Integer
    <ProtoMember(2)> _
    Public Property Y As Integer
    <ProtoMember(3)> _
    Public Property Z As Integer

    <ProtoMember(4)> _
    Public Property Texture_X As Integer
    <ProtoMember(5)> _
    Public Property Texture_Y As Integer

End Class

My Research:

I've done some searching into it and this is was I've found:

This problem is called tearing (I believe?)
It is commonly caused by using a floating point data type to hold the tile position (I'm using Integer so this shouldn't be a problem right?)


texts: Is quake3/ioquake's OOP good to do a large game?

texts:
Everybody heard about the release of the Quake3 source code.

But since it's plain C but uses OOP a little, isn't it too complex to decipher or to use for large projects such as a 3rd person shooter/hack&slash with smooth camera movements ?

Would it be a good idea to use it instead of Ogre, I want to be sure it's really harder to use since it's only an engine dedicated to FPS.

Ogre seems to be a standard OSS, especially when thinking about OOP, but since I'm not looking for complex effects and since the rendering quality of quake3 seems to be good enough to me, I wanted to ask what did the release of the quake3 engine changed for open source developpers (except the infamous invsqrt method).

I heard Carmack released it for students or people alike, but C++ is here: is quake3's code obsolete compared to Ogre's when it comes to learning ?


texts:
I've heard from several sources that it's a better approach to pass the model matrix to a shader via a uniform rather than an attribute.

I also know that the idea of a uniform is, that it has the same value for each frame.

If so, how can i change the uniforms value for each object i have in the scene?


texts: What framerate should I aim for on a mobile phone?

texts:
The higher the framerate, the better the game looks, but the faster it drains the battery.

What's a happy medium?

(I'm making a relatively simple 2D game with sprites moving constantly. I want the movement to appear smooth but I know how irritating it is when a simple game sucks your battery dry.)


texts: Android developer/publisher royalty sharing

texts:
I am creating and Android game, and will need to partner with a publisher. I am curious about how this is typically implemented. Probably publishers are going to have a difficult time trusting some developer that they don't know to pay them, assuming the develop puts the game up on Google Play. So will the publisher want the apk file so that they can put it up on Google Play themselves?
Or does Google Play have a mechanism where the royalties can be automatically split between two parties from sales/IAP?
I know that all contracts will be different and it will depend, but I'm just looking to get a general idea of what is usual/typical.


texts: How to smoothly change the target of smooth follow without camera glitch?

texts: I am trying to change the target of the smooth follow at runtime, but there is a glitch in the camera since the targets are different sizes. I tried using lerp and smooth damp both gave the same result. How do I overcome the jerk in camera motion?


texts: C++ glGenBuffers does not return proper VBOID when called in thread

texts:
I'm currently learning to properly use multithreading in C++ in combination with OpenGL and GLFW, and I encounter a strange bug in my application.
I'm generating a procedurally generated terrain in a sidethread, but everytime I want to create the buffer for the generated terrain(chunk), glGenBuffers() just gives me back the value I put in! It does not create a proper buffer. I even checked with gDEBugger, no VBO's created.

Here's the pseudo code:

void init(){ //This is in the main thread!
    sharedWindow = glfwCreateWindow(1, 1, "shared", NULL, NULL);
    mainWindow = glfwCreateWindow(400, 400, "main", NULL, sharedWindow);
    glfwMakeContextCurrent(mainWindow);
}

void terrainGeneratorLoop() { //This is in another thread!
    glfwMakeContextCurrent(sharedWindow);
    while(running){

        /* Generate vertex data for terrain */

        //Upload generated data into GPU:
        unsigned int m_vbo = -1;
        glGenBuffers(1, &m_vbo); //After this call, m_vbo is still -1 (Well actually 4294967295, but you get the point)
        glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
        glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(vertex), &data.at(0), GL_STATIC_DRAW);
    }
    glfwMakeContextCurrent(nullptr);
}

I'm pretty sure I'm doing something wrong with my context handling and that shared window. And sorry because of the fact that this is only pseudo code, my structure of the project and classes is way to complex to paste in in here!

EDIT:
When I call the terrainGeneratorLoop() in the main thread, everything works as It should.


texts: Why does the player fall down when in between platforms? Tile based platformer

texts:
I've been working on a 2D platformer and have gotten the collision working, except for one tiny problem. My games a tile based platformer and whenever the player is in between two tiles, he falls down.
Here is my code, it's fire off using an ENTER_FRAME event. It's only for collision from the bottom for now.

        var i:int;
        var j:int;
        var platform:Platform;
        var playerX:int = player.x/20;
        var playerY:int = player.y/20;
        var xLoopStart:int = (player.x - player.width)/20;
        var yLoopStart:int = (player.y  - player.height)/20;
        var xLoopEnd:int = (player.x + player.width)/20;
        var yLoopEnd:int = (player.y + player.height)/20;
        var vy:Number = player.vy/20;
        var hitDirection:String;
        for(i = yLoopStart; i <= yLoopEnd; i++)
        {
            for(j = xLoopStart; j <= xLoopStart; j++)
            {
                if(platforms[i*36 + j] != null && platforms[i*36 + j] != 0)
                {
                    platform = platforms[i*36 + j];
                    if(player.hitTestObject(platform) && i >= playerY)
                    {
                        hitDirection = "bottom";
                    }
                }
            }
        }

This isn't the final version, going to replace hitTest with something more reliable , but this is an interesting problem and I'd like to know whats happening. Is my code just slow? Would firing off the code with a TIMER event fix it? Any information would be great.


texts: How to get the 3D location of a click in unreal engine 4?

texts:
I'm trying to do a board game in unreal engine 4.
I've set up pawns and a board actors.  However, I would like to be able to decide on which case of the board the player clicked.  The board is one piece and I'm not sure splitting it up would render it nice.

Is there a way to get back the 3D position of a click in unreal engine ?

Thanks for any help !


texts: How is Unity's GetComponent implemented in C#

texts:
I'm just curious that what aspects of the C# language Unity's GetComponent method uses.

In the C# language we have reflection that lets programmers access a variable by its type. Is GetComponent just some type of reflection C# for certain Unity defined types?


texts: What would be a good way to implement/render a 2D tiled map for a browser game?

texts:
I coded a a little RPG in ruby and I used an array to contain the map squares. The elements of the array (which defines the X coordinates) are arrays themselves whose elements defines the Y coordinate, and each of these are arrays too which stores the terrain data on first position, and player/npc/objects/buildings on following positions.

What I am trying to do is render those terrain data "squares" to a 2D tiled map in the browser.

The map does not need to refresh or be dynamically fetched as you scroll it, (at least at this stage of development) but an implementation which would allow me to do so in future is a possible path.

Being a total beginner at web design/rendering the things that I thought of are: HTML tables, HTML5 canvas, some JS framework which is designed exactly with this purpose (which I do not know of = please advice).

I know about gameQuery but I've never used it and I don't know if it's going to slow everything down as I will be adding new features (scrolling, ajax).

I really don't know of any other alternatives, maybe there any lighter approaches? Easier or more minimalistic ways ? More targeted JS framework which is the right tool for the job? Maybe just some html canvas code, or even simple image maps, or images with absolute positioning will be enough?

The thing is that I'd like to start simple, and then gradually make it better, so I'd like something which will give me a bit of gratification in the beginning but that also has room for improvement and is headed toward new web technologies

p.s. Flash is excluded of course...

Update: rewrote the question in a more decent english (hopefully) :)


texts: Unity: How do I get the coordinates of the vertices of a blender mesh?

texts:
I have gameobjects in my scene called icospheres that I have made in Blender, and I am trying to get the coordinates of their vertices. Below is an image of my scene; each triangle is a separate gameobject, blender mesh and is called an icosphere:

Here is the code I am using:

    var meshFilter = icosphere.GetComponent<MeshFilter>();
    var vertices = meshFilter.mesh.vertices;
    GameObject.Find("Fauna Manager").GetComponent<FaunaManager>().PlaceFauna(tree, vertices[0], icosphere);
    GameObject.Find("Fauna Manager").GetComponent<FaunaManager>().PlaceFauna(tree, vertices[1], icosphere);
    GameObject.Find("Fauna Manager").GetComponent<FaunaManager>().PlaceFauna(tree, vertices[2], icosphere);

The bottom 3 lines of code call a function that should in theory place another gameobject on top of the 3 coordinates that have been calculated above, however this does not happen. The tree-placing functions work completely and have been tested so the problem is definitely with the coordinates. I printed out the coordinates and the length of the array that holds them. The array is of length 3 as it should be however the coordinates are completely off. The trees have been placed a long way away from the icosphere which means the coordinates are clearly wrong. Where have I gone wrong?

example of coordinates: -0.1, 0.0, -0.1
centre of icosphere for reference: -0.7431812, 0.4044746, -4.932096

Above you can see that the coordinates are well off


texts: How do I consolidate the differences between iOS and Android update loops?

texts:
I'm currently working on moving some Android-ndk code to the iPhone.

From looking at some samples it seems that the main loop is handled for you and all you've got to do is override the render method on the view to handle the rendering. Then add a selector to handle the update methods. The render method itself looks like it's attached to the windows refresh.

But in android I've got my own game loop that controls the rendering and updates using C++ time.h. Is it possible to implement the same here bypassing Apple's loop? I'd really like the keep the structures of the code similar.


texts: Greedy Meshing : Slow to rebuild when updating chunk

texts:
I've a problem with my voxel based game. The game is sliced into chunks (Like Minecraft), each chunk is 16x256x16 blocks.
When I started the project, I used a basic culling system when hidden blocks where not sent to the chunk buffer. It was running well, the only problem was my memory usage, even with the culling algorithm, the amount of vertices was incredibly high and it has a real impact on the memory (16x16 chunks loaded -> 2-3go ram in usage).
So I decided to move with the greedy meshing algorithm, after the implementation the memory usage problem was solved (16x16 chunks loaded -> 200-300mo), however a new problem appears and I don't really know how to solve it.

Each time I place/break a block, I need to update the chunk mesh in order to recalculate each vertex position. But greedy algorithm is not as fast as the culling one. So when I place/break a block, the game freezes for less than 0.1ms. I know the greedy meshing algorithm is a slow process, especially with a 16x256x16 sized chunk.

Here's where my greedy algorithm come from :
https://0fps.net/2012/06/30/meshing-in-a-minecraft-game/

So, do you think the problem come from the fact that my greedy algorithm is not optimized ?
Does the greedy algorithm is really necessary ?

Hope one of you can help me !

Thank you guys !


texts: Why would a game engine developer use both DirectX and OpenGL?

texts:
It's very common for cross-platform game engines to support both DirectX and OpenGL, and even Vulkan. Why would a studio want to write abstraction code 2, 3, or even 4 times? OpenGL/Vulkan are practically on par with DirectX.

In my experience, businesses care about their bottom line. Paying developers to write duplicate code gets expensive very quickly. It'd be nice to use the most native API for each target platform, but I don't understand how the cost and overhead is worth it.

Since Windows support OpenGL/Vulkan, why bother writing the DirectX code when the final game will look nearly identical?


texts: manipulate textures in real time using GPU

texts:
I'm looking for some way (tutorial, library or build in option) to draw texture on JMonkey in real time. So I have 2 images one a normal texture that is fairly big(4000x4000) and another much smaller texture (100x100) the second texture is white(or we can set alpha high) with something drawn on it (say a tree) now I would like said drawing (tree) to be drawn on the bigger texture in such a way that it does not massively slow down the system and that it easily ignores the unused pixels.

I already know I can use a for loop to change each value of a texture but that is a CPU computation I would much rather, if possible, offload this to the GPU.


texts:
I intend to write a game in Python and, later, if needed, offload any performance-critical sections of code to C++. I want to use Python basically because I am really familiar with the language and I find writing game logic in it to be easier. However, unlike game logic which runs at a constant rate(50-60 ticks/s), you usually want to do rendering as fast as the hardware allows. Given this, the renderer will probably be the first thing to optimize out.

Arpoaches

The game is overall written in Python, the game loop as well, the renderer is written in C/C++ and called from Python
The game is written in Python, the loop is written in C/C++ and call the game logic which is Python, and renderer which is C++(I intend to do this with Cython)
The game, loop and renderer are written in C++, only the logic is written in Python

I personally dislike the third option because I've tried it before and designing the abstraction layer between C++ and Python is a bit of a hassle compared to the other way round.

Question

Considering each approach what would be the incurred overhead of 1 and 2 compared to 3, and 1 compared to 2?


texts: How do I render an object's position trail of a constant length?

texts:
I want to show a trail of the last points that the object has been in, but I want that trail to always be a certain length, regardless of the object's speed. How can I do that?

At the moment, I have an array of 100 points. When it gets full, I overwrite the oldest one.

However, if the object is staying still (or moves slowly), the old points are overwritten and the trail becomes shorter. I want the the trail to always be 100 pixels total length.


texts:
I'm currently creating a system that essentially creates a world at run-time based on a seed I choose. In this system, I made it so that there are certain "chunks" that divide up different sections of the world, and in these sections, I have different meshes that are completely unique to that chunk. Each chunk is also divided into 4 subchunks, which are exactly half the width and height of it's chunk.

The purpose of the chunks and subchunks is so as the player, you could walk around the level, with the current chunk, as well as the adjacent chunks stored into memory with their meshes, and those adjacent chunks, which cannot be seem from where the player is, are loaded, however their meshes are not currently loaded, and as the player moves, the system will load and unload these chunks meshes into memory, that way only the meshes needed to render are loaded in at this time.

The problem that I'm having is when I move from one chunk to another, and load the new chunks meshes, and unload the unnecessary chunks meshes, there's a lag spike that only lasts for about half a second. (But it quite noticable) The spike IS NOT coming from the loading and unloading of the mesh, (my memory manager is fast with allocation and deallocation and the loading and unloading are handled on a separate thread) the problem is when I go to change the memory inside the vertex and index buffers. (Which whenever there is a swap, adds AND removes 4 times each during one game loop.

Does anyone have any idea on how I should handle my open world objects? A good reference would be something along the lines of Skyrim or World of Warcraft; They have the large terrain in these worlds and they are most definitely not 100% loaded in the game at once, so how would I go about making it that so as you progress through the world, objects are handled with little to no skip?

Thanks a lot for the help in advance, and if there is clarification needed, simply ask.

Edit: Added code showing my AddVerts function, which is used to pass vertex data to the GPU.

// unsigned int* AddVerts(const VertexFormat *pVerts, const unsigned int nNumVerts)
// returns  :   unsigned int*           offset in buffer to where the mesh is located
// ins      :   const VertexFormat*     vertices to pass on to the GPU
//              const unsigned int      number of vertices allocated for the const VertexFormat*
void *buffer = nullptr;
unsigned int nSize = nNumVerts*sizeof(VertexFormat);

if( ( m_unBufferFlags & D3DUSAGE_DYNAMIC ) != 0 )
    m_pVertexBuffer->Lock(nVertLocation*sizeof(VertexFormat), nSize, &buffer, D3DLOCK_NOOVERWRITE);
else
    m_pVertexBuffer->Lock(nVertLocation*sizeof(VertexFormat), nSize, &buffer, 0);

// copy data to buffer
memcpy(buffer, pVerts, nNumVerts*sizeof(VertexFormat));
m_pVertexBuffer->Unlock();

m_dllOffsets.addTail(nVertLocation);

return &(m_dllOffsets.GetTail()->element);


texts: Reseting a multiplayer scene in UNET, without losing connections

texts:
I have a game with only one scene, which has the basic Network Manager HUD.

After I click "Host", and a few players join one by one, I want to restart the scene, so the early joiners won't have advantage.

Specifically: I want to reset the scene so it's in the "server was just started* " state, every player is connected and their gameobjects have just spawned on the spawn location.

I tried this line, but it fully restarts the scene, and even worse, now the HUD won't even pop up:

NetworkManager.singleton.ServerChangeScene(SceneManager.GetActiveScene().name);

Is there a simpler way than manually resetting everything to a hardcoded initial state?

(*the state in which the scene is after I click "Host")


texts: MiniMax strategy - What is the context of the numbers?

texts:
I've watched a new videos about the MiniMax concept and invariably the lecturer will say that the computer has 2 parties, Min and Max; Min always takes lower number and Max takes higher number.

The problem I have is this.

I'm finding it hard to understand why Min takes the lower number at all or why Max takes the higher number at all?

What is the reasoning and context for these numbers?

I mean, logically I know that 7 is higher than 3; but that doesn't mean anything by itself.

What is the context of the numbers?

Many thanks


texts: Why isn't more culling being done on the GPU?

texts:
I'm interested in game development and 3D graphics; however, I'm not very experienced, so I apologize in advance if this comes across as ignorant or overly general.

The impression I get is that quite often the bottleneck in 3D games comes from the CPU having to make draw calls to the GPU. Culling seems to generally be performed on the CPU and then, for each frame, the CPU has to transfer the culled scene graph over to the GPU memory for rendering and display.

However, why can't culling be done on the GPU? It seems to be a very repetitive and predictable task that has to be done for every frame and would benefit from parallelization. Why not store the whole active scene graph in the GPU RAM; let the CPU just update what needs to be updated each frame (due to physics, animation, scripting, whatever); then fire a single 'draw' call to the GPU and have it cull and render everything? It seems to me it should be more efficient, because it would hugely reduce the amount of data transfer going on between CPU/GPU.


texts:
I am looking at here and while it's well organized a lot of links are broken:
http://www.realtimerendering.com/intersections.html

I am trying to find fast code that will give me the hit point and the normal of the hit point on the sphere. I saw a lot of functions that only checks if there is collision but nothing else.

I looked at Real Time Collision Detection book but it doesn't seem to have it either.

Any ideas?


texts: How to display text and numbers in SFML 2.0

texts:
I want to display some text and numerical data over my OpenGL scene in SFML 2.0. I've looked at the SFML 1.6 text tutorials here. But I can't get the code to work.
There is (as of yet) no text tutorial for 2.0


texts:
I'm unsure if this question would be more appropriate in stackoverflow, so apologies before hand if it should be moved.

Given that I know the user's hardware (Video Card, RAM, CPU, screen resolution, etc.) is it possible to make a rough estimate of the expected FPS when comparing with the game's minimum and recommended system requirements?

I see some gaming websites with those estimates and I was wondering how do they do it.


texts:
I am trying to run an example from the redbook 8th edition and I am receiving a segmentation fault in line:

glCreateBuffers( NumBuffers, Buffers );

file.cpp

//////////////////////////////////////////////////////////////////////////////
//
//  Triangles.cpp
//
//////////////////////////////////////////////////////////////////////////////

#include "vgl.h"
#include "LoadShaders.h"

enum VAO_IDs { Triangles, NumVAOs };
enum Buffer_IDs { ArrayBuffer, NumBuffers };
enum Attrib_IDs { vPosition = 0 };

GLuint  VAOs[NumVAOs];
GLuint  Buffers[NumBuffers];

const GLuint  NumVertices = 6;

//----------------------------------------------------------------------------
//
// init
//

void
init( void )
{
    glGenVertexArrays( NumVAOs, VAOs );
    glBindVertexArray( VAOs[Triangles] );

    GLfloat  vertices[NumVertices][2] = {
        { -0.90f, -0.90f }, {  0.85f, -0.90f }, { -0.90f,  0.85f },  // Triangle 1
        {  0.90f, -0.85f }, {  0.90f,  0.90f }, { -0.85f,  0.90f }   // Triangle 2
    };

    glCreateBuffers( NumBuffers, Buffers );
    glBindBuffer( GL_ARRAY_BUFFER, Buffers[ArrayBuffer] );
    glBufferStorage( GL_ARRAY_BUFFER, sizeof(vertices), vertices, 0);

    ShaderInfo  shaders[] =
    {
        { GL_VERTEX_SHADER, "triangles.vert" },
        { GL_FRAGMENT_SHADER, "triangles.frag" },
        { GL_NONE, NULL }
    };

    GLuint program = LoadShaders( shaders );
    glUseProgram( program );

    glVertexAttribPointer( vPosition, 2, GL_FLOAT,
                           GL_FALSE, 0, BUFFER_OFFSET(0) );
    glEnableVertexAttribArray( vPosition );
}

//----------------------------------------------------------------------------
//
// display
//

void
display( void )
{
    static const float black[] = { 0.0f, 0.0f, 0.0f, 0.0f };

    glClearBufferfv(GL_COLOR, 0, black);

    glBindVertexArray( VAOs[Triangles] );
    glDrawArrays( GL_TRIANGLES, 0, NumVertices );
}

//----------------------------------------------------------------------------
//
// main
//

int main( int argc, char** argv )
{
    if ( !glfwInit() )
    {
        exit(EXIT_FAILURE);
    }

    //glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    GLFWwindow* window = glfwCreateWindow(300, 300, "Triangles", NULL, NULL);
    if ( !window )
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glewInit();

    init();

    while (!glfwWindowShouldClose(window))
    {
        display();
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);

    glfwTerminate();
}

I am compiling :

g++ -O2 -g -o run opengl.cpp LoadShaders.cpp -lGL -lGLU -lGLEW -lglut -lglfw -lX11 -lm


texts: Is it possible to zoom out and zoom in in Unity Editor in Scene View faster than just with the help of scroll wheel on the mouse? I hope there are exist some shortcut for that. Am I right?


texts: How can I support retina/high-DPI/high-res graphics in libgdx?

texts:
I'm not sure if I'm missing it somewhere or if this just doesn't exist, but I'd like to support "retina" graphics on desktop displays that support them (like the newer MacBook Pro), but I can't find a way to change the density of the LWJGL canvas in Libgdx.

Is this possible? How can I do it?


texts:
I noticed a problem in Unity's third person controller's ground check.

The ground check should detect whether or not the player is standing on the ground. It does so by sending out a ray beneath the player.

However, if the player stands on top and in middle of two boxes and there is a space between these boxes, then the ray shoots into the gap and the player thinks he is not in contact with the ground, which looks like this:

I am unable to move.
You can clearly see that the ray is in the gap and thus the player animator airborne blend tree is active.

What is the best way to solve this problem?

I was thinking of shooting multiple rays, from the same origin but with different angles. And OnGround should only be true, if X% of these rays hit the "ground". Or is there a better way?


texts: Correct way to set up camera buffer [DirectX]

texts:
I would like to play with two different implementation of particle system in my project (ok, actually not mine, but I am working on it).
I copied the particle system successfully, however, faced the camera buffer initialization problem, highlight this code:
bool ParticleShader::Render(Direct3DManager* direct, ParticleSystem* particlesystem, Camera* camera)
{
    bool result;

    result = SetShaderParameters(direct->GetDeviceContext(), camera, direct->GetWorldMatrix(), camera->GetViewMatrix(), direct->GetProjectionMatrix(), particlesystem->GetTexture());
    if (!result)
        return false;

    RenderShader(direct->GetDeviceContext(), particlesystem->GetVertexCount(), particlesystem->GetInstaceCount(), particlesystem->GetIndexCount());
    return true;
}

If I just call SetShaderParameters with the same args, there is a bug obviously: particle system scene sticks to the camera (originally, it looks like this).
I checked the params in debug mode and found out that the difference is in the World matrix. The DXUT CFirstPersonCamera is used in my project and it changed the World matrix while moving around the scene whereas in the original particle system project it's constant (identity matrix).
I understand that there is a difference between DXUT camera and the default project camera at the ideological level. Nevertheless, I am a newbie in Graphic it's too difficult to realize how to change the code in a proper way.
Thank you in advance


texts: what's wrong with my lookAt and move forward code?

texts:
so am still in the process of getting familiar with libGdx and one of the fun things i love to do is to make basics method for reusability on future projects, and for now am stacked on getting a Sprite rotate toward target (vector2) and then move forward based on that rotation
the code am using is this :

    // set angle
   public void lookAt(Vector2 target) {

      float angle = (float) Math.atan2(target.y - this.position.y, target.x
            - this.position.x);
      angle = (float) (angle * (180 / Math.PI));

      setAngle(angle);

   }

   // move forward
   public void moveForward() {
      this.position.x += Math.cos(getAngle())*this.speed;
      this.position.y += Math.sin(getAngle())*this.speed;
   }

and this is my render method  :

    @Override
   public void render(float delta) {
      // TODO Auto-generated method stub
      Gdx.gl.glClearColor(0, 0, 0.0f, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

      // groupUpdate();

      Vector3 mousePos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
      camera.unproject(mousePos);
      ball.lookAt(new Vector2(mousePos.x, mousePos.y));
      //

      if (Gdx.input.isTouched()) {
         ball.moveForward();
      }

      batch.begin();
      batch.draw(ball.getSprite(), ball.getPos().x, ball.getPos().y, ball
            .getSprite().getOriginX(), ball.getSprite().getOriginY(), ball
            .getSprite().getWidth(), ball.getSprite().getHeight(), .5f,
            .5f, ball.getAngle());
      batch.end();
   }

the goal is to make the ball always look at the mouse cursor, and then move forward when i click, am also using this camera :

// create the camera and the SpriteBatch
  camera = new OrthographicCamera();
  camera.setToOrtho(false, 800, 480);

aaaand the result was so creepy lol

Thank you


texts: XNA - Static classes from game libraries executing after content pipeline extensions, how to avoid the problem?

texts:
Alright, formulated this way I'm sure it sounds obscure, but I'll do my best to describe my problem.

First, let me explain what's wrong with my real source code.

I'm making a platformer, and here are the current components of my game: a Level, which is holding its own grid of tiles and also the tile sheets and a Tile, which just keeps the name of its tile sheet and index within the tile sheet. All these are within a separate XNA game project, named GameLib.

Here is how my levels are formatted in a text file:

x x . . . . .

. . . b g r .

. . . . . . .

X X X X X X X

Where . represents an empty tile, b represents a blue platform, X represents a block with a random color, etc.

Instead of doing all the work of loading a level within the Level class, I decided to take advantage of the content pipeline extension and create a LevelContentPipelineExtension.

As soon as I started, I quickly realized that I didn't want to hard-code 20+ lines of the kind:

if (symbol == 'b')
    return new Tile(/*...*/);

So, in the hope of at least centralizing all the content creation into one class, I made a static class, called LevelContentCreation, which holds the information about which symbol creates what and all this kind of stuff. It also holds a list of all the asset paths of the tile sheets, to load them later on. This class is within my GameLib game library project.

The problem is, I'm using this LevelContentCreation static class in both my Level class (to load the actual tile sheets) and my content pipeline extension (to know which symbol represents what tile)...

And here's how my LevelContentCreation class looks like:

public static class LevelContentCreation
{
    private static Dictionary<char, TileCreationInfo> AvailableTiles =
        CreateAvailableTiles();

    private static List<string> AvailableTileSheets { get; set; }

    /* ... rest of the class */
}

Now, since the LevelContentCreation class is part of the game library, the content pipeline extension tries to use it but the call to CreateAvailableTiles() never happens and I'm unable to load a Level object from the content pipeline.

I know this is because the content pipeline executes before the actual compilation or something like that, but how can I fix the problem?

I can't really move the LevelContentCreation class to the pipeline extension, because then the Level class wouldn't be able to use it... I'm pretty lost and I don't know what to do... I know these are pretty bad design decisions, and I'd like it if somebody could point me in the right direction.

Thank you for your precious time.

If anything is not clear enough or if I should provide more information/code, please leave a comment below.

A little more information about my projects:

Game - XNA Windows game project. Contains references to: Engine, GameLib and GameContent
GameLib - XNA game library project. Contains references to: Engine
GameContent - XNA content project. Contains references to: LevelContentPipelineExtension
Engine - XNA game library project. No references.
LevelContentPipelineExtension - XNA content pipeline extension. Contains references to: Engine and GameLib

I know close to nothing about XNA 4.0 and I'm a little bit lost about how content works now. If you need more information, tell me.


texts: How can I achieve the realtime clouds/sky effect of Lumion?

texts:
Does anyone know how they do this? They're not truly volumetric - you can't fly through them - it's still a texture.

http://vimeo.com/16534222

It looks like it's a perlin based solution, but I really can't work out how they get the fantastic lighting! How can I achieve this effect?

To be clear, I'm not talking about the sky (which would be a variation on CIE/Preetham) or sun shafts or any other effect - i'm talking purely about the clouds, which are rendered straight to the skybox texture.


texts: How to code camera for layered map in unity

texts:
For a current unity project I need a layered map like in Dwarf Fortress. The game will take place in a 3D city enviroment and the camera should be 'snapped' to layers. So there will be (for example) a cave layer, ground layer and floor 1 - 3 layer. The player should be able to navigate the camera up and down with a keypress. So if the player is looking currently at the ground layer and press + the camera should snip to floor 1 layer. All layers below the current level will be blurred and all levels above wont be visible (or at least faded out very strong)

My question now is: Is the layer system of unity useful for such a scenario, or is it better to implement an own data structure? I know about the ability of ignoring layers for rendering and raycasting but can the system be extended to support the features described above?


texts: Lightwight cross browser library for server side push?

texts:
I am looking for a lightweight javascript library that allows the server to push update information to the client reliably and regularly. We use a fixed turn time of 300ms and often there are only about 20 bytes of changes. So doing polling using XMLHttpRequest would imply a huge overhead (3-way tcp handshake, http request headers, http response header).

There area number of alternatives, but they have limited browser support:

streaming <script>-tags in another frame (does this work on IE?)
MIME multipart/x-mixed-replace responses (Firefox, Safari, Opera only?)
WebSockets (removed from recent beta version of Firefox and announced to be removed from Opera 11 because of security issues)
Server-sent events (only Opera?)
Java / Flash relays (requires the users to have those plugins installed)
Polling using XMLHttpRequest (huge overhead)

Is there a website which has recent information on which technology works in which browser?  Are there javascript libraries which provide a common cross browser interface that hides the messy details? (Yes, i know that it still requires me to write multiple server sides, but that is rather easy. And more important it is easy to write automatic tests for the server sides).


texts: Collision detection between many objects

texts:
I'm working in a 2d environment and have hundreds of objects, brute force collision checking would be out of the question, but would my method below work?

For example, lets say I have a std::vector<GameObj*> objectsVector to hold all objects and a std::multimap<Point2D, GameObj*> objectsMap (basically a map which takes a 2d point representing a GameObject's coordinate as a key and the object itself as a value) to get any object associated with a point. If I want to do collision checking for an object, I could use a function that looks like this:

void World::checkForCollisions()
{
    for (int i = 0; i < objectsVector; ++i) {
        GameObj* currObj = objectsVector[i];
        for (
                int x = (int)currObj->getX() - (int)currObject->getWidth();
                x < currObj->getX() + 2*currObj->getWidth();
                x++
            )
        {
            for (
                    int y = (int)currObj->getY() - (int)currObject->getHeight();
                    y < currObj->getY() + 2*currObj->getHeight();
                    y++
                )
            {
                pair<multimap<Point2D, GameObj*>::iterator,multimap<Point2D, GameObj*>> range = objectsMap.equal_range(Point2D(x, y));
                for (
                        multimap<Point2D, GameObj*>::iterator it=range.first;
                        it!=range.second;
                        ++it
                    )
                {
                    if (checkCollision(currObj, it->second))
                        currObj->handleCollision(it->second);
                }
            }
        }
    }
}

Is this even remotely efficient? Because it doesn't seem to be. It basically just scrolls through the vector and checks to see if it collides with nearby objects. Problem is, I have to use 2 containers AND when things move, I have to pretty much reinitialize the entire map, because the keys would be invalid! Is there any way to improve this collision-checking function, or should I scrap the whole thing altogether and use spatial hashes or a quad-tree?


texts: Turning on Vertex Attribute Divisor With Instanced Rendering Renders Nothing

texts:
When I render with glDrawArraysInstanced with the vertex attribute divisor set to zero, the triangle appears as expected. But when the divisor is set to any value other than zero, the triangle disappears. This is the code I am using to render:

static const u32 NUM_TRIANGLES = 1;
struct Vertex
{
    f32 x;
    f32 y;
 };
 static const Vertex g_triangles[NUM_TRIANGLES*3] =
 {
    {0.125f, 0.125f},{-0.125f,0.125f},{-0.125f,-0.125f},
 };
 glGenVertexArrays(1, &g_vao);
 glBindVertexArray(g_vao);

 glGenBuffers(1, &g_vbo);
 glBindBuffer(GL_ARRAY_BUFFER, g_vbo);
 glBufferData(GL_ARRAY_BUFFER, sizeof(g_triangles), nullptr,
             GL_DYNAMIC_DRAW);
 glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(g_triangles),
                reinterpret_cast<const void*>(&g_triangles));
 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0,
                       reinterpret_cast<void*>(0));
 glEnableVertexAttribArray(0);
 glVertexAttribDivisor(0, 1); // Setting this to 0 renders the triangle

 // This is the draw call
 glDrawArraysInstanced(GL_TRIANGLES, 0, 3, NUM_TRIANGLES);

Here are my shaders:

#version 420 core
layout (location = 0) in vec2 v;
void main()
{
    gl_Position = vec4(v, 0.0f, 1.0f);
}

#version 420 core
out vec4 out_color;
void main()
{
    out_color = vec4(1.0f,0.0f,0.0f,1.0f);
}

My problem is similar to
OpenGL 2D instancing: glDrawArraysInstanced with a divisor renders nothing, but that question wasn't resolved.


texts:
I'm using the simplex noise to create Minecraft like terrain.
I can only achieve hills like this.

Does anyone know how to use simplex to make more dynamic landscapes?


texts: What is an easy way to work subsurface scattering into a raycaster?

texts:
I've got some neat effects with path tracing:

I want to add in an ability to do subsurface scattering, but I'm unsure of the general algorithm.  With path tracing, it's:

foreach pixel:
    trace( ray into scene )
        color = 0
        if( ray hits an object )
            if( that object is emissive )
                color += object.emissive_color
            if( that object is translucent )
                color += trace( object.refracted ray into scene )
            if( that object is specular )
                color += trace( object.specularly-reflected ray into scene )
            if( that object is diffuse )
                color += trace( object.random-direction reflection ray into scene )

        return color

That's the rough outline.  Where does subsurface scattering go and how can I integrate it?


texts: line to point collision without doing three square roots

texts:
Is it possible to test a point to line collision without doing three square roots? Here's how I'm currently doing it:

I have point P that I want to check is on the line, and point A and B for the two ends of the line. I use the Pythagorean equation to get length PA, PB, and AB. Now I check to see if PA + PB = AB. if PA + PB is larger than AB, the point cannot be on the line.

private boolean PTLCollisionCheck(float px, float py, float ax, float ay, float bx, float by) {
    float PA = (float) Math.sqrt(((px - ax) * (px - ax)) + ((py - ay) * (py - ay)));
    float PB = (float) Math.sqrt(((px - bx) * (px - bx)) + ((py - by) * (py - by)));
    float lineLength = (float) Math.sqrt(((ax - bx) * (ax - bx)) + ((ay - by) * (ay - by)));
    return (PA + PB) <= (lineLength + 1);
}


texts: Libgdx OrthographicCamera culling problem with zooming

texts:
When I set zoom on an orthographic camera to anything above 1 I get a strange black border on the bottom of the screen.

I suspect that this might be some sort of culling problem. I use a viewport to control the game resolution, and no matter the size the borders are there.

The camera is set on a direction (-1,-1,-1) basicaly isometric. Also it is positioned well above to origin at (1113,1113,-1113). Far plane at 7777 near at 0.00001f. The ground plane is at 0,0,0 laying in the xz axis, with an other plane on top of it sligtly off to the left and with a 45 degrees on its axis to face the camera.

Here is an image of the problem:

Posting code wont really help here since I only use defaults almost everywhere, but if you need it just tell.


texts: How would I properly flip a character when they reach the edge of a ground object in Unity 2D?

texts:
The idea here is that the raycast shoots downwards from an empty game object and when it detects that there is no ground below it the character should bounce back and walk the other way. When I get to the edge of my platform the character just gets stuck in place and keeps rotating on the Y axis.

public class npcAI : MonoBehaviour
{
public float speed;
public float distance;
private bool movingRight = true;
public Transform groundDetection; //raycast goes downward from this point

private Vector2 movementDirection;

void Start()
{
    //Initialise direction
    movementDirection = Vector2.right;
}

void Update()
{
    transform.Translate(movementDirection * speed * Time.deltaTime);
    RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, distance);
    if (groundInfo.collider == false)
    {
        if (movingRight)
        {
            movingRight = false;
            movementDirection = Vector2.left;
      transform.localScale -= new Vector3(0.30F, 0, 0);

        }
        else
        {
            movingRight = true;
            movementDirection = Vector2.right;
      transform.localScale += new Vector3(0.30F, 0, 0);
        }

    }
}

The code above was edited to reflect the answer below. If you find yourself attempting to do the same thing and need to flip your sprite when you reach the edge change 0.30F to whatever double the X value of your sprite is in order to flip it. My sprites scale was (0.15, 0.15, 0) so I used 0.30F to flip my sprite. Be mindful of when you should use -= and when you should use +=.


texts: Should I add error handling to SDL_GL_SetAttribute?

texts:
As the title says, I wonder if I should handle errors for :

SDL_GL_SetAttribute

Can it actually fail to set?

And if it can, what could be a reason for it to fail?


texts: How to sleep for the desired duration between game loop iterations?

texts:
My game loop below doesn't sleep as log as it should. The delta value always ends up less than 1, when it's supposed to be 16.6666 or close to 16.6666

double targetTime = 1000.0 / 60.0;//1000 millisecunts / 60 fps
long startTime;
long endTime = System.currentTimeMillis();
long delta;

long timer = System.currentTimeMillis();
int frameCount = 0;
while(running){
    startTime = System.currentTimeMillis();
    delta = startTime - endTime;
    endTime = startTime;

    tick(delta);
    render();
    frameCount +=1;
    try{Thread.sleep(targetTime - delta);}catch(InterruptedException e){}

    if(System.currentTimeMillis() - timer >= 1000){
        System.out.println("Rendered frames: " + frameCount);
    }
}


texts: What is a CPU-efficient cloth simulation technique for a 2D game?

texts: Are there techniques for simulation of cloth and hair in an efficient (in other words, not too CPU-intensive) manner? I only need to calculate the key points as the drawing will be done in 2D.


texts: Linux: blit image on screen without stuttering at a stable frame rate

texts:
I'm working on a very simple game, and one of the project goals is to minimise the use of libraries.

I'm drawing every frame into a buffer, which is then displayed using XPutImage (see the code of the main loop). This simple code is used to limit FPS:

// Limit FPS
{
  u64 current_timestamp = LinuxGetWallClock();
  u64 ns_elapsed = LinuxGetWallClock() - last_timestamp;

  if (ns_elapsed < target_nspf) {
    struct timespec ts;
    ts.tv_sec = 0;
    ts.tv_nsec = target_nspf - ns_elapsed;  // time to sleep
    clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL);

    while (ns_elapsed < target_nspf) {
      ns_elapsed = LinuxGetWallClock() - last_timestamp;
    }
  } else {
    // printf("Frame missed\n");
  }

  last_timestamp = LinuxGetWallClock();
}

Everything works fine and as expected, but every now and then the image stutters, as if the X server has buffered up a few frames' worth of images and then flushed them all in a single go. This happens irrespective of frame misses.

Note: I'm not talking about image tearing here.

I realise that the code above is not supposed to provide a stable frame rate, and occasionally one frame might be displayed for too long, and another frame might get lost and never displayed, but I don't see how that thing alone can cause the terrible occasional stuttering.

My only guess would be that clock_nanosleep may sleep for longer than I asked for.

Questions:

Is my guess above correct?
If not, what might be the reason?
Are there any ways to address this problem without having to use OpenGL to wait on vblank?

Thanks.


texts:
I'm trying to make a Chunk class for my Tile class creating Chunks of 25 Tiles each, But for some reason it doesn't work correctly
Tile.cs extends Sprite.cs

  class Tile : Sprite
    {
        public TileType TileType { get; set; }

        public Tile(Texture2D texture, Vector2 position, SpriteBatch spriteBatch) : base(texture, position, spriteBatch)
        {
        }
    }

Sprite.cs

    class Sprite
    {
        public Vector2 Position { get; set; }

        public Texture2D Texture { get; set; }

        public SpriteBatch SpriteBatch { get; set; }

        public Sprite(Texture2D texture, Vector2 position, SpriteBatch spriteBatch)
        {
            this.Position = position;
            this.Texture = texture;
            this.SpriteBatch = spriteBatch;
        }

        public virtual void Draw()
        {
            SpriteBatch.Draw(Texture, Position, Color.White);
        }
    }

My Chunk.cs

class Chunk : Sprite
    {
        public Tile[,] Tiles { get; set; }

        public const int CHUNK_SIZE = 25;

        public Chunk(Texture2D texture, Vector2 position, SpriteBatch spriteBatch) : base(texture, position, spriteBatch)
        {
            Tiles = new Tile[CHUNK_SIZE, CHUNK_SIZE];

            GenerateChunks();
        }

        public void GenerateChunks()
        {
            for (int x = 0; x < CHUNK_SIZE; x++)
            {
                for (int y = 0; y < CHUNK_SIZE; y++)
                {
                    Vector2 tilePos = new Vector2(Texture.Width * x, Texture.Height * y);
                    Tiles[x, y] = new Tile(Texture, Position, SpriteBatch);
                }
            }
        }

        public override void Draw()
        {
            foreach (var tile in Tiles)
                tile.Draw();
        }
    }

And my World.cs

 class World
    {
        float NoiseValues { get; set; }

        public Chunk[,] Chunks { get; set; }

        public SpriteBatch SpriteBatch { get; set; }

        public Texture2D Texture { get; set; }

        public int Height { get; set; }

        public int Width { get; set; }

        public const int CHUNK_TILE_SIZE = 400;

        private float NoiseScale = 0.1f; //Smaller the scale the better caves

        private Random Random;

        public World(SpriteBatch spriteBatch, Texture2D texture, int x, int y)
        {
            this.Height = y;
            this.Width = x;

            this.SpriteBatch = spriteBatch;

            this.Texture = texture;

            Chunks = new Chunk[x, y];

            Random = new Random();

            Simplex.Noise.Seed = Random.Next();

            GenerateBasicWorld();
        }

        public void GenerateBasicWorld()
        {
            for (int x = 0; x < this.Width; x++)
            {
                for (int y = 0; y < this.Height; y++)
                {
                    NoiseValues = Simplex.Noise.CalcPixel2D(x, y, NoiseScale); //Just a simplex noise for further generation doesn't affect current gen

                    Vector2 chunkPos = new Vector2(16 * x, 16 * y);
                    Chunks[x, y] = new Chunk(Texture, chunkPos, SpriteBatch);

                    System.Diagnostics.Debug.WriteLine(NoiseValues);
                }
            }
        }

        public void Draw()
        {
            foreach (var chunk in Chunks)
                chunk.Draw();
        }
    }

My initialization goes like this:

World world = new World(spriteBatch, tilesTexture[0], 5, 5);

What I'm currently getting is 5x5 tile set drawn.

I'm expecting to get 5 chunks on X axis and 5 chunks on Y axis, each chunk has to be made of 25 tiles, am I missing something out? Thanks.


texts: Godot 3 - Trying to make a character dash (wavedash)

texts:
So, I'm trying to make a character do a wavedash in Godot 3 and I don't know what I'm missing here. When I press 'Z', the character should burst speed and then a few miliseconds later it should decelerate back to the normal speed. Tried to use a while loop, adding the var to the motion, but it didn't work.

Here's the code (testing only in the right direction).

extends KinematicBody2D
const UP = Vector2(0, -1)
const GRAVITY = 20
const ACCELERATION = 50
var MAX_SPEED = 150
var JUMP_HEIGHT = -400
var MAX_DSPEED = 300
var motion = Vector2()
var CAN_DASH = true
var ADD_SPEED = 0

func _physics_process(delta):

motion.y += GRAVITY
var friction = false

if Input.is_action_pressed("ui_right"):
    motion.x = min(motion.x+ACCELERATION, MAX_SPEED)
    $Sprite.flip_h = false
    $Sprite.play("Run")
    if Input.is_action_pressed("dash"):
        ADD_SPEED = 300
        while ADD_SPEED > 0:
            ADD_SPEED -= 3
            motion.x = min(motion.x+ADD_SPEED, MAX_DSPEED)

elif Input.is_action_pressed("ui_left"):
    motion.x = max(motion.x-ACCELERATION, -MAX_SPEED)
    $Sprite.flip_h = true
    $Sprite.play("Run")
else:
    $Sprite.play("Idle")
    friction = true
    motion.x = lerp(motion.x, 0, 0.2)
    JUMP_HEIGHT = -400

if is_on_floor():
    if Input.is_action_just_pressed("ui_up"):
        motion.y = JUMP_HEIGHT
    if friction == true:
        motion.x = lerp(motion.x, 0, 0.2)
else:
    if motion.y < 0:
        $Sprite.play("Jump")
    else:
        $Sprite.play("Fall")
    if friction == true:
        motion.x = lerp(motion.x, 0, 0.05)
motion = move_and_slide(motion, UP)
pass


texts: How to approach skinning a snake made of cubes and is it right method for snake 3d game

texts:
I'm making a 3d snake game clone for studies and prettly much got everything to work, I have a 3d ground object surrounded by walls, and a snake head piece (cube). when you start the game 2 additional snake body (cube) are being added and follow the head in a snake like movement, every time you eat an apple additional snake piece is added.

I want instead of cubes to have a snake object (which I got already) my question is what is the approach to make the cubes act like the bones of the snake object and make the snake object get it's shape from it's "bones".

also maybe there's a way to add bones to the snake object I got in a program like 3dsMax ? and then make the bones act like the cube pieces I got in the game and it will work?

I also tried cutting the body of the snake object I got and adding each snake body cube the cutted snake body object but then it doesn't get the look I want (smooth snake that can turn in 3d) so I think the right idea is to have one big object that get it's positon and rotation based on smaller bone objects.


texts:
After hours of googling and pulling several hairs out, I decided to open this thread.

I want to make a game, in which the player walks around a sphere (like super Mario galaxy) and the camera should stay fixed over the player and point down on its head but I can't seem to get anywhere near of the right method. So, how can I realise this?

Thanks.


texts: Help with Resolving Pixel Perfect Collision

texts:
Hi I'm having trouble resolving "Collision detection between axis-aligned bounding box and bitmap (pixel perfect) terrain on a Worms type game". (Read previous question to find more information about the game).

The player has got properties such as velocity, acceleration, gravity applied to it on its update method. I have controls that allow the player to "land" on a surface by detecting the pixel immediately below it and then stopping the velocity if that object is solid. I am having trouble with moving the character.

Currently when I move the character left or right the code should work in my head to move the character up, but it seams to still want to go into the ground. Could you help me to resolve the collisions for moving?

Below is the code I implement for Walking left or right. It is called immediately before the update method for sprite. This method is called from the Player class update method.

            boolean solidPixel;
            //Create a bitmask from top to bottom of the pixels
            for(int i=0;i<boundHeight;i++){
                //If true then collision
                solidPixel = TerrainObj.isPixelSolid(x+(getBound().halfWidth*direction),y-getBound().halfHeight+i);
                //if any of the pixels are solid then we've hit a wall
                //so act accordingly and exit the application
                if(solidPixel && i < getBound().halfHeight/4){
                    //
                    //Cannot move in the direction
                    velocity.x = 0;
                    break;
                }
                //if the bottom (left/right)quater of the sprite is
                //solid then its a slope
                if(solidPixel && i >= getBound().halfHeight/4){
                    //Position the item -(up) by the amount of pixels the
                    //gradient is
                    position.y+=(getBound().halfHeight*2)-i;
                    break;
                }
            }

Any help is much appreciated how I could approach the issue to stop the player ever moving into the ground to provide prefect collision detection.

Sorry for the long post, wanted to put as much information in as possible.


texts: Folding selected Parent Game Object in the hierarchy

texts:
I am folding selected parent gameObject with this editor script. It all works well but it also folds other expanded gameObjects which should not happen. For example under two different parents, if I collapse one parent gameObject, even the other parent gameObject gets collapsed. How do I not let this happen?
The problem is at:
rootGameObjects.AddRange (SceneManager.GetSceneAt (i).GetRootGameObjects ());

It takes the root gameObject in a scene but not the selected gameObject in the hierarchy.
Here's the rest of the code:
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;

public static class CollapseTools {
    private static int wait = 0;
    private static int undoIndex;

    public static void CollapseGameObjects () {
        EditorApplication.update -= CollapseGameObjects;
        CollapseGameObjects (new MenuCommand (null));
    }

    [MenuItem ("GameObject/Collapse GameObjects", priority = 40)]
    private static void CollapseGameObjects (MenuCommand command) {
        // This happens when this button is clicked via hierarchy's right click context menu
        // and is called once for each object in the selection. We don't want that, we want
        // the function to be called only once
        if (command.context) {
            EditorApplication.update -= CollapseGameObjects;
            EditorApplication.update += CollapseGameObjects;

            return;
        }

        List<GameObject> rootGameObjects = new List<GameObject> ();
#if UNITY_2018_3_OR_NEWER
        // Check if a prefab stage is currently open
        var prefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage ();
        if (prefabStage != null && prefabStage.stageHandle.IsValid ())
            rootGameObjects.Add (prefabStage.prefabContentsRoot);
        else
#endif
        {
            int sceneCount = SceneManager.sceneCount;
            for (int i = 0; i < sceneCount; i++)
                rootGameObjects.AddRange (SceneManager.GetSceneAt (i).GetRootGameObjects ());
        }

        if (rootGameObjects.Count > 0) {
            Undo.IncrementCurrentGroup ();
            Selection.objects = Selection.objects;
            undoIndex = Undo.GetCurrentGroup ();

            Selection.objects = rootGameObjects.ToArray ();

            EditorApplication.update -= CollapseHelper;
            EditorApplication.update += CollapseHelper;
        }
    }

    private static void CollapseHelper () {
        if (wait < 1) // Increase the number if script doesn't always work
            wait++;
        else {
            EditorApplication.update -= CollapseHelper;
            wait = 0;

            EditorWindow focusedWindow = EditorWindow.focusedWindow;
            if (focusedWindow != null)
                focusedWindow.SendEvent (new Event { keyCode = KeyCode.LeftArrow, type = EventType.KeyDown, alt = true });

            Undo.RevertAllDownToGroup (undoIndex);
        }
    }
}


texts: Why would one use a separate alpha mask for sprites?

texts:
I've seen tilesets of the game Braid, and for each tileset in the main folder there is an alpha map for it in "alpha" folder.

I wonder, why just not to draw your image as it is (with transparent parts where you want), export to PNG format and parse it to RGBA texture?

Why would one use a separate alpha map for this, is there some kind of performance benefit?


texts:
I wrote a game server in udp, now I don't know if the matchmaker be in tcp or udp.
Because I know udp is connectionless and I think the matchmaker should be in tcp because they will connect to each other .


texts: How to use an A* Pathfinding System across uneven environments?

texts: I am developing a game in Unity3D. I want an enemy character to follow the player around. The problem is, my surface is uneven and full of mountains. I am using aarongranberg's pathfinding project. Every time that a player climbs a hill or a mountain, the enemy stops because the grid is flat and it considers the mountain to be an obstacle. How do I solve this problem ?


texts: What is the advantage of wrapping D3D in a class versus a namespace?

texts:
Almost all the tutorials and books use a class wrapper for Direct3D. But I haven't found any scenario in which using more than one instance of Direct3D system (the "device" and state, et cetera) is required.

Is there any advantage to using a class instead of a namespace? Is there ever a case where using more than one is required?


texts: Problem using glm::lookAt and glm::perspective

texts:
I'm trying to change the code from the 22th tutorial at http://ogldev.atspace.co.uk/, using the GLM library, but the result seems wrong.
The problem is shown in the below picture:

While it should be:

This program displays a model onto the screen. The model is loaded using a library and I ensure that all of its vertices, normals, and texuture coordinates are loaded correctly. The problem seems to be at creating the Projection - model - view matrix. I searched for the use of GLM and use the below code to calcualate that matrix:

    glm::vec3 Pos(3.0f, 7.0f, -10.0f);
    glm::vec3 Target(0.0f, -0.2f, 1.0f);
    glm::vec3 Up(0.0, 1.0f, 0.0f);

    glm::mat4 viewMat = glm::lookAt(Pos, Target, Up);
    glm::mat4 perMat = glm::perspective(60.0f, (float)WINDOW_WIDTH/WINDOW_HEIGHT, 1.0f, 100.0f);

    glm::mat4 modelMat = glm::scale(glm::mat4(1.0f),glm::vec3(0.1f, 0.1f, 0.1f));
    modelMat = glm::rotate(modelMat, m_scale, glm::vec3(0.0f, 1.0f, 0.0f));
    modelMat = glm::translate(modelMat, glm::vec3(0.0f, 0.0f, 10.0f));

    //FINAL MATRIX
    glm::mat4 PVMMat = perMat * viewMat * modelMat;

After that, I supplied the matrix to the shader like this:

glUniformMatrix4fv(m_WVPLocation, 1, GL_TRUE, &PVMMat[0][0]);

Finally, in the shader, I calculate the gl_Position as below:

//vertex shader
void main()
{
    gl_Position = gWVP * vec4(Position, 1.0);
    TexCoord0   = TexCoord;
    Normal0     = (gWorld * vec4(Normal, 0.0)).xyz;
    WorldPos0   = (gWorld * vec4(Position, 1.0)).xyz;
}";
//Fragment shader
void main()
{
    FragColor = texture2D(gSampler, TexCoord0.xy);
}";

I tried my best for a few days and I can't see any error in the way I use glm::lookAt and  gml::perspective. This is exactly as in the manual on the GLM website. Could you suggest some reason for the problems I'm seeing, or some way for me to further investigate the error? Thanks so much. I hope to see your answer.


texts:
I am creating a prototype enemy swordsman, and I'd like to be able to parry his attacks, like the parry system from VR Dungeon Knight.

This is my method of implementation:

Parent a sword to his hand that has a child cube trigger collider + kinematic rigidbody + a custom script called ParryableWeapon.
In the animation clip, when he raises his hand before his swing, use an AnimationEvent to tell the ParryableWeapon to start 'listening' for a parry. This is done by checking an internal boolean during OnTriggerEnter of the sword.
If the ParryableWeapon collides with another ParryableWeapon while listening, the UnityEvent 'OnParried' is invoked.
After the swing completes, use another AnimationEvent to tell ParryableWeapon to stop 'listening'.

I have a simple model and animation from the Asset store that I'm using to accomplish this. For some reason, the OnParried event is only being fired every 5 or so swings at a stationary test sword.

I played the animation frame by frame, and I found that the enemy swords' position sometimes does not go through the other sword, despite them being on a collision course. In one frame, the enemy sword is to the left of the other, and in the next frame, it is on the other side.

It seems that the interpolated frames between the animation keyframes can only sometimes collide with the other sword. What would be the proper way to remedy this? Adding more keyframes to the animation? Some sort of calculation of the sword's path between the two keyframes?


texts: Is there an optimal method to implement moving background?

texts:
I am trying to develop a little game using libGDX. We have a hero who jumps and world consist of dynamically created moving platforms in an auto side-scrolling manner.
I wanted background to scroll at half speed of foreground objects to establish a moving background effect.

For this I came up with this idea: Have a 1024px X 240px image  and each time render executes select a 256px X 240px region from that texture according to backgroundObject X position. Something like this:

And this is my code:

    bgTexture = new Texture(Gdx.files.internal("data/bg.png"));
    bgTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);

And this code executes inside render method.

    bgRegion= new TextureRegion(bgTexture, -1 * (int)bgObj.getX(),0,256,240); //bgObj is a scrollable object where in each update changes X value of position(Vector2): moves left.
    bgRegion.flip(false, true);

    batcher.draw(bgRegion, 0, 0, Variables.ScreenWidth / 2, Variables.ScreenHeight / 2);

Now, I am wondering if there is a better method to implement this effect? My method seems to have high system resource cost.


texts: I have about 60 3D models with each model being about 4mb in size.If i import them all to unity, my app will be about 240mb in size!.My app requires internet access so should i just upload my models to a server or something?


texts: Issues with 2D raycasting lighting under limitations of HLSL 3.0 pixel shader

texts:
I've been writing my own HLSL pixel shader for dynamic lighting using raycasting. Unfortunately, since I'm using this out of XNA, I can only use up to ps_3_0. As you can see, the limitations difference between 3 and 4 are drastic, especially in instruction slots and temp registers:

Specifically, I'm running out of instruction slots. This limitation is preventing me from having accurate rays. (As in the amount of pixels the ray's position increases by from the light source has to be a lot less than I want)

Here's what it looks like.
And here's the relevant part of the code:

//Cast rays (Point Light)
float4 CastRays(float2 texCoord: TEXCOORD0) : COLOR0
{
    float dir;
    float2 move;
    float2 rayPos;

    float2 pixelPos = float2(texCoord.x * width, texCoord.y * height);

    float dist = distance(pixelPos, lightPos);

    if (sqrt(dist) <= lightSize)
    {
        rayPos = lightPos;
        dir = atan2(lightPos.y - pixelPos.y, lightPos.x - pixelPos.x);
        move = float2(cos(dir), sin(dir)) * rayLength;
        for (int ii = 0; ii < clamp(dist / rayLength, 0, 7); ii++)
        {
            if (tex2D(s0, float2(rayPos.x / width, rayPos.y / height)).a > 0)
            {
                return black;
            }
            rayPos -= move;
        }
    }
    else
    return black;

    float light = 1 - clamp((float)abs(sqrt(dist)) / lightSize, 0.0, 1.0);
    return lightColor * light;
}

The limitation variable I've put in place is rayLength. The larger this number, the less accurate the rays are. I can give more specific examples of what this looks like if anybody wants.

I'm very new to the concept of raycasting, and fairly new to HLSL. Is there any way I can make this work under the limitations and/or increase the limits?

Thank you.


texts:
I have a simple 2-D breakout clone. It works fine, except for one bug.

If I move mouse over game window, it will get input from mouse(mouse movement), and event queue will instantly be flooded with this input. For example, if player pressed left arrow, but moved his mouse over a window before, he will have to wait enough frames for mouse events to get processed.
Is there a way to ignore mouse event? At least these movement ones. Everything is okay when mouse doesn't move, but after it moves it's terrible.

I'm using SDL 2.0, programming on Debian-based linux. Using C++.

Code for handling events looks like this(requested):

void gameEngine::HandleEvents()
{
    if( SDL_PollEvent(&gameEvent) != 0 )
    {
        HandleEngineEvents();
        gameLevel.HandleEvents(gameEvent);
    }
}

HandleEngineEvents() :

void gameEngine::HandleEngineEvents()
{
    if( gameEvent.type == SDL_QUIT)
    {
        running = false;
    }
    else if( gameEvent.type == SDL_KEYDOWN && gameEvent.key.repeat == 0 )
    {
        if( gameEvent.key.keysym.sym == SDLK_ESCAPE )
        {
            running = false;
        }
    }
}

Level::HandleEvents() :

void Level::HandleEvents(SDL_Event& gameEvent)
{
    player.HandleEvents(gameEvent);
}

Player::HandleEvents() :

void Player::HandleEvents(SDL_Event& gameEvent)
{
    if(gameEvent.type == SDL_KEYDOWN && gameEvent.key.repeat == 0)
    {
        switch(gameEvent.key.keysym.sym)
        {
        case SDLK_RIGHT:
             velocity += 1;
            break;
        case SDLK_LEFT:
            velocity -= 1;
            break;
        default:
            break;
        }
    }
    else if(gameEvent.type == SDL_KEYUP && gameEvent.key.repeat == 0)
    {
        switch(gameEvent.key.keysym.sym)
        {
        case SDLK_RIGHT:
             velocity -= 1;
            break;
        case SDLK_LEFT:
            velocity += 1;
            break;
        default:
            break;
        }
    }
}


texts: Displaying sprites in a 2.5D raycasting engine

texts:
I'm developing a raycasting engine like the one used in DOOM, Wolfenstein 3D, etc.

My engine is capable of correctly displaying walls and textures on walls, but I'm stuck at sprites rendering.

Given that my engine is based on lines and angles only (just trigonometry), is there a way to render sprites without going for matrices? And if so, which technique should I use?


texts:
Is there a function in the CryEngine Lua API to open the ~ Console?
I cannot find it in the Lua (ScriptBind) API reference.


texts:
I am using Lazy Foo's Production tutorials for making an SDL game in C in Xcode 6.1 - http://lazyfoo.net/tutorials/SDL/index.php#Hello%20SDL. I'm using Xcode 7 but I don't think they are very different.

In the second tutorial (http://lazyfoo.net/tutorials/SDL/02_getting_an_image_on_the_screen/index.php).
I cannot seem to compile properly without an error regarding one of the functions.

The function prototype:

//Frees media and shuts down SDL
void close();

Then the function declaration:

void close()
{
    //Deallocate surface
    SDL_FreeSurface( gHelloWorld );
    gHelloWorld = NULL;

    //Destroy window
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;

    //Quit SDL subsystems
    SDL_Quit();
}

And then the function call at the end:

close();

I am getting these errors and am not quite sure how to fix them. Other solutions online are for problems that are not quite the same as mine.

SDL_Tutorial/SDL_Tutorial/using_image.c:28:6: Conflicting types for 'close'

SDL_Tutorial/SDL_Tutorial/using_image.c:28:6: Conflicting types for 'close'

SDL_Tutorial/SDL_Tutorial/using_image.c:127:5: Implicit declaration of function 'close' is invalid in C99

SDL_Tutorial/SDL_Tutorial/using_image.c:127:11: Too few arguments to function call, expected 1, have 0

clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any help would be much appreciated, as I am struggling to make progress with learning SDL game programming at the moment.

Thank you.


texts: How to make this game loop deterministic

texts:
I am using the following game loop for my pacman clone:

long prevTime = System.currentTimeMillis();
        while (running) {
            long curTime = System.currentTimeMillis();
            float frameTime = (curTime - prevTime) / 1000f;
            prevTime = curTime;

            while (frameTime > 0.0f) {
                final float deltaTime = Math.min(frameTime, TIME_STEP);
                update(deltaTime);
                frameTime -= deltaTime;
            }

            repaint();
        }

The thing is, I don't always get the same ghost movement every time I run the game (their logic is deterministic), so it must be the game loop. I imagine it's due to the final float deltaTime = Math.min(frameTime, TIME_STEP); line. What's the best way of modifying this to perform the exact same way every time I run it? Also, any further improvements I can make?


texts: How can I make sprites from multiple images using SDL2?

texts:
Using SDL2 in C++ I can load textures with out problem however, I have sprites that are from about 15 different png's that I was hoping I could load them all up and for loop through them. However, when I try this it looks like the image is still .

I am hoping that I wouldn’t have to photo shop them into one image and shift/pan through that considering I have about 3K of images to go through.

can some one provide an example of how this could be done cleanly?

I have been working on this for a while for a bit and yes, this is probably a coding mistake as I am learning C++ still and know that for me to learn is to take up a project.

int main ( int argc, char *argv[] )
{

    SDL_Init(SDL_INIT_EVERYTHING);
    Window = SDL_CreateWindow("NEW WINDOW",100,100,300,300,SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
    renderer = SDL_CreateRenderer(Window,-1,SDL_RENDERER_ACCELERATED);

    if (Window == NULL)
    {
        std::cout << "Window Couldn't be Created!\n";
    }

    struct imagebatch
    {
        const char *image;
    };

    imagebatch foto;

    //  A for loop is needed here to loop through Healer0.png Healer1.png to Healer15.png
    foto.image = "DData/towners/healer/healer/Healer0.png";
    HealerTexture = IMG_LoadTexture(renderer,foto.image);

    //loads an image;
    //HealerTexture = IMG_LoadTexture(renderer,"DData/towners/healer/healer/Healer0.png");

    //defines the rect of this image;
    SDL_Rect HealerRect;
    HealerRect.x = 0;
    HealerRect.y = 0;
    HealerRect.w = 90;
    HealerRect.h = 90;

    while (!quit)
    {
        while( SDL_PollEvent( &event ) != 0 )
        {
            //User requests quit
            if( event.type == SDL_QUIT )
            {
                quit = true;
            }
        }
        SDL_RenderClear(renderer);

        //Blit everything here.
        SDL_RenderCopy(renderer,HealerTexture,NULL,&HealerRect);

        SDL_RenderPresent(renderer);
    }
    close();

    return 0;
}

Full code is here: http://pastebin.com/H5fD6cfX


texts:
There are 64k cubes, 64k-1 's materials are assigned to sharedMaterial of first cube. But unity is not batching them together. Only cubes themselves are batched.

Static color(but different per cube)
Dynamic position and rotation per cube

How can I force unity to batch them all so it sends all cube data with only an array then draw once instead of drawing 64k times?

Each cube has a constructor as:

public class Test : MonoBehaviour {
    public static System.Random r { get; set; }
    // Use this for initialization
    public static Material m=null;
    void Start () {
        if (r == null)
            r = new System.Random();
        sayac++;
        if (m == null)
            m = GetComponent<Renderer>().sharedMaterial;
        else
            GetComponent<Renderer>().material = m;
        GetComponent<Renderer>().material.color = new Color((float)r.NextDouble(), (float)r.NextDouble(), 1);
        var mesh= GetComponent<MeshFilter>().mesh;
        var vertices  = mesh.vertices;
        var colors  = new Color[vertices.Length];
        var i  = 0;
        while (i < vertices.Length)
        {
            colors[i] = new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble());
            i++;
        }
        mesh.colors = colors;
        mesh.UploadMeshData(false);
        mesh.Optimize();
    }

}

and they are instantiated from a cube as:

    for(int i=0;i<1024*64;i++){
        var pos = new Vector3(i % 64, (i /64) % 64, (i / 4096) % 64);
        pos*=2.5f;
        var cu = Instantiate(ref_cu, pos, Quaternion.identity);
        cu .name = "cube_" + i;
    }

After deleting 'material.color' lines, batching has started. But now cubes are not easily seen as with different colors. I need them different colored but not changing. Static color but different per cube. How it looks now:

its not easy to see individual cubes.

public class Test : MonoBehaviour {
    public static System.Random r { get; set; }
    // Use this for initialization
    public static Material m=null;
    void Start () {
        if (r == null)
            r = new System.Random();
        sayac++;
        if (m == null)
            m = GetComponent<Renderer>().sharedMaterial;
        else
            GetComponent<Renderer>().material = m;

    }

}


texts: How does re-glBufferData()'ing interact with glVertexAttribPointer?

texts:
I understand the basic sequence: glGenBuffers() creates a "buffer object name," glBindBuffer() creates the actual buffer object (as well as binding the name), glBufferData() "creates and initializes a buffer object's data store," and glVertexAttribPointer() sets the format of the buffer data, as well as saving the buffer object binding as part of vertex attrib array state.
The tricky thing that I'm unsure of is if the glVertexAttribPointer() stuff remains valid if the the "buffer object data store" (but not the buffer object itself) is blown away by a new call to glBufferData(). I'm aware that this isn't usually a good idea - use glBufferSubData() when just rewriting buffers - but glBufferData() seems like the only option if it needs to be resized. Plus, I'm just curious.
The reference pages make it sound like it could go either way - in particular (https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVertexAttribPointer.xhtml):

If pointer is not NULL, a non-zero named buffer object must be bound
to the GL_ARRAY_BUFFER target (see glBindBuffer), otherwise an error
is generated. pointer is treated as a byte offset into the buffer
object's data store. The buffer object binding
(GL_ARRAY_BUFFER_BINDING) is saved as generic vertex attribute array
state (GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING) for index index.
When a generic vertex attribute array is specified, size, type,
normalized, stride, and pointer are saved as vertex array state, in
addition to the current vertex array buffer object binding.

It seems like both the byte offset and the buffer object binding could remain valid, even if the data store was replaced by something different. But I could also see it being implemented such that at the time of the call, the binding captures a specific pointer into the data store, which becomes invalidated if the data store is replaced. Neither way seems to be precluded by the wording.


texts: How to create class for storing different types of vertex?

texts:
I am writing graphics engine for educational pursoses and have some problems.

I need to have ability to use different vertex formats (for example position+normal+uv or position+normal+uv+bones+weights).
I have different structs for these formats and have a class HardwareBuffer that stores OpenGL vertex and index buffers.
The problem is to give this class the ability to work with different types of vertices.
There are a way to make this class template and use like this:

HardwareBuffer<VertexPosNormUV> buffer;
buffer.addVertex(VertexPosNormUV(vector3(1, 1, 1), vector3(1, 0, 0), vector2(1, 0)));

But in my engine there is an interface IRenderer that have virtual method drawDataFromHardwaveBuffer. Also there is a class OpenGLRenderer that is inherited from it. And now I can't pass my hardware buffer object to this method because there isn't a way to use template virtual methods.

Renderer renderer = createRenderer(GraphicsDriver::OpenGL3);
renderer->drawDataFromHardwaveBuffer(buffer); // can't make this method template

I can write functions for every type of vertex but this is not a solution.

How can I solve the problem?


texts: How should I implement a dialogue box in Pygame?

texts:
I'm working on a small RPG with Pygame, using Python 3.5.1. I've spent a week trying to find a decent tutorial or example for a dialogue box implementation that would pull dialogue from a source file (eg. an XML file) and support choices, with little success. Of course, getting the data is a trivial task. However, I can't think of a good way to implement the presentation side.

Here's my question: What would be the best way to implement a dialogue system that supports choices, while keeping the code relatively easy to understand?

In case you want to take a peek at the project, the source code can be found here.


texts: How can I stop my collision detection from registering multiple times per frame?

texts:
I am working on a side-scroller shooter right now. Everything is working fine along with the collision detection however, my problem is that the collision triggers my health deduction code multiple times per bullet. Here is the code where the bullet hits a turret. Supposedly doing 5.0 damage but instead it randomly does a lot more damage since the collision runs multiple times with just one bullet. How could I prevent this?

void TurretCollision()
{
 int BulletNo = 0;
        int MissileNo = 0;

for (BulletNo = 0; BulletNo < MAX_BULLETS; BulletNo++)
{
    if (Turret[1] == true)
    {
        //cout << TurretH[1];
        if ((BulletX[BulletNo] >= 103 && BulletX[BulletNo] <= 103.09) && (BulletY[BulletNo] <= -38 && BulletY[BulletNo] >= -45))
        {
            BulletActive[BulletNo] = false;
            TurretTrial = TurretTrial - 5.0;

            if (TurretTrial <= 0.0)
            {
                Turret[1] = false;
            }
        }
    }

}

}


texts: Run some objc code very early in unity iOS game lifetime

texts:
I want to hook up a crash reporting service to my unity iOS game. It's just one line of objC to add, as early into the app lifecycle as possible, but I'm not sure how to get it to run. I know I could make a native plugin and then call that from some Awake() function in C#, but that's too late for my purposes.

I'm not a native iOS developer, but I know enough to be dangerous. I have been able to google enough that I know I want something to with UnityAppController, probably preStartUnity(). But that's all.

Has anyone got further resources on how to do this? Or another way, if I'm barking up the wrong tree?

edit: I'm on unity 4.6.


texts: Resource and game state management for multiplayer game server

texts:
I'm building a virtual world kind of engine. It's mostly for fun and learning. But I would like to get it right from the very beginning, so it is stable and can be scaled relatively easily.

I've been reading a lot lately about architecture of multiplayer real-time games (and real-time 3D games in general) but still there are some questions unanswered.

For now, I know the following:

the server will be the authority, and clients will be "slaves";
the game engine core will be based on subsystems (like physics subsystem, game logic subsystem etc.) and all the communications
between those subsystems will be implemented using pub/sub approach;
I'll use enet for networking, and my network layer will be as a separate subsystem, which will just plug into the pub/sub system (so other game server components don't have to know anything about the network layer);
physics engine - some free library, haven't decided yet. I guess, I'll use the same physics engine on the server and on the clients,
and implement client-side prediction;
I would like my server to be cross-platform (Windows and Unix/Linux) so I'm thinking about using new C++11 features (like cross-platform threading support etc.). I know, C++11 is not stable yet, but I guess, it will be stable at the time when I have something working (Visual Studio 11 Beta and the latest GCC already support many C++11 features, so I guess, it's good to go). Using C++11 I could avoid some other 3rd party libraries, like Boost;
game state storage - MySQL. I'm not yet sure, what strategy I'll use to flush the game state from memory to the database, but I think, it'll be mixed - more important state changes will be stored immediately, and less important ones will be stored in batches in some background process.

I guess, this information should be enough to see where I'm going to. And now the questions.

There are going to be lots of various resource files - textures, audio, meshes etc. Do I need a resource manager also on the game server or it will be enough to have a good resource manager on the clients only?
As the game world gets bigger and the number of clients grow, the resource manager needs lots of careful planing to avoid loading all the resources in memory and thus possibly causing low-memory issues. What is the best practice - do game servers load and keep the resources cached in RAM (and also unload them as necessary to avoid low memory issues) or this task is relayed completely to clients?

I've heard a lot about memory managers/heap allocators and how the game engine might benefit from a custom memory manager to track memory allocations, collect statistics, debug etc.
Will a custom memory manager give something valuable to the multiplayer server or it is enough to use custom macros around new/delete to track standard C++ memory allocations?

Could I use some NoSQL RAM database engine which periodically (or when there are enough dirty objects, or when system goes out of free physical RAM) flushes its state to some persistent database? Will the game server benefit from such approach? I don't want to use something just because it's modern and cool, I prefer simple (but still scalable) solutions.


texts: How can I replicate the look of Zelda: BotW in my own shaders?

texts:
At the moment I really want to develop a game with a similar shading technique that is used in Zelda BOTW however I do not know how I can achieve that look?

To me it looks like they are using a cel shading technique with rim lighting, however I do not know is how to design textures or use them to achieve similar results. Or even if I’ve got the right basic idea.

I would really like to know how these kind of aesthetics could be replicated and if it would be possible using a tool like Substance Designer (using a PBR workflow) or not.


texts: Texture Atlas and HLSL Shader for sprite tiling

texts:
I am trying to create a shader that allows to tile a specific region of a texture. This seem to be a common need however I can't seem to find any information about how to get this effect done.

The closest I have found is the following article made by Renaud Bedard which detail a little bit how he got it to work. : http://theinstructionlimit.com/wrap-spritesheet-atlas

I have tried to implement his process within a complete shader without any success.

float3x3 Matrices_Texture;

texture ColorTexture : DIFFUSE <
    string ResourceName = "default_color.dds";
    string UIName =  "Diffuse Texture";
    string ResourceType = "2D";
>;

sampler2D ColorSampler = sampler_state {
    Texture = <ColorTexture>;
    FILTER = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct vertexInput {
    float4 Position : POSITION0;
    float2 TextureCoordinates   : TEXCOORD0;
};

struct vertexOutput {
    float4 Position : POSITION0;
    float2 TextureCoordinates   : TEXCOORD0;
    float2 UV       : TEXCOORD1;
    float2 UVScale      : TEXCOORD2;
};

vertexOutput mainVS(vertexInput input)
{
    vertexOutput output;
    output.TextureCoordinates = mul(float3(input.TextureCoordinates, 1), Matrices_Texture).xy;
    output.UV = Matrices_Texture[2].xy;
    output.UVScale = float2(Matrices_Texture[0][0], Matrices_Texture[1][1]);
    output.Position = input.Position;
    return output;
}

float4 mainPS(vertexOutput input)  : COLOR0
{
    float2 tc = input.TextureCoordinates;
    tc = frac((tc - input.UV) / input.UVScale) * input.UVScale + input.UV;
    float4 sample = tex2D(ColorSampler, tc);
    return sample;
}

technique technique0 {
    pass p0 {
        CullMode = None;
        VertexShader = compile vs_3_0 mainVS();
        PixelShader = compile ps_3_0 mainPS();
    }
}

Note that I have zero experience with HLSL, I tried my best to use the correct types and sementic but I still can't seem to get anywhere with this. If someone could provide additionnal information, it would be greatly appreciated.

Currently, it looks like it is tiling in the preview of the material however when applied to an object, no texture is being displayed. (Testing inside FX Composer 2.5)


texts:
I'm been working on a 2D tile game (sidescroller perspective) and I decided to rework my tile engine. Right now I store a new tile instance per block in the world (so there are like 1000 TileStone instances in memory). My plan was to change the current tile engine so that I store only a small object which tells the renderer a stone tile should be drawn there. The TileStone, TileDirt classes only store the block properties like hardness, texture and so on.

With this design I ran into a bit of a problem, some tiles, for example, a chest tile should be able to store custom data like the contents of the chest, or for instance a windmill block which needs to update all of its logic every update tick.

What would be a good way of implementing a tile engine, that meets these requirements?

Programming language: Java, Library: LibGDX

Thanks in advance
-ProRed


texts: Splice enemy array to destroy enemy (js game)

texts:
I am currently working on a basic space invaders game. So far I have created the enemies, a main character, and a laser beam, collision detection between enemy and bullet, however when my bullet collides with my enemy sometimes one enemy is destroyed other times all or a couple of enemies are destroyed. Can you please inform me in what I am doing wrong.

this.crashWith = function(otherobj) {
    var myleft = this.x;
    var myright = this.x + (this.width);
    var mytop = this.y;
    var mybottom = this.y + (this.height);
    var otherleft = otherobj.x;
    var otherright = otherobj.x + (otherobj.width);
    var othertop = otherobj.y;
    var otherbottom = otherobj.y + (otherobj.height);
    var crash = true;
    if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
        crash = false;
    }
    return crash;
}
}

 function updateGameArea() {
var x, y;
for (y = 0; y < myObstacles.length; y += 1) {
    if (myGamePiece.crashWith(myObstacles[y])) {
        var ctx = myGameArea.context;
         ctx.fillText("Game Over", 150, 150);
         myGameArea.stop();

    }
 for (i = 0; i < bullets.length; i += 1) {
  if(myObstacles[y].crashWith(bullets[i])) {
   myObstacles.splice(myObstacles[y], 1);
}
}
}

Thank you in advance.


texts: Documentation/Spec for Flash's XFL layout?

texts:
Has anyone found an official spec or documentation on the XFL file layout?

Are there any design tools in existence or planned that can create XFL files? (Besides the official Adobe Flash Professional program)


texts:
For my multiplayer game, I'm trying to figure out a system to send multiple pieces of data from one client to another and separating pieces of data.

When sending a message, all parameter data has to be converted into a byte array (with BitConverter.GetBytes) and will arrive as such on the other side.

What I'm not sure about is how to send multiple numbers in one message and identify them. For example, how would I send a ushort and a ulong in a single byte array? Are there any clever methods to identify the individual numbers or will every number have to be packaged in 4 bytes each?


texts:
In Unity Shaderlab shader, Is there any way to apply _Atten value?
Using surface shader, and vertex/fragment shader I can do it easily.
But, I didn't find any reference to do that in Shaderlab syntax.

Shader "Diffuse" {
    Properties {
        _Atten ("Light Attenuation Power", Float) = 1.0 // <= how to apply?
        _Color ("Main Color", Color)            = (1,1,1,1)
        _MainTex ("Base (RGB) Transparency (A)", 2D) = "" {}
    }
    SubShader {
        Pass {
            SetTexture[_MainTex]
            {
                  constantColor [_Color]
                combine texture * constant, texture * constant
            }
        }
    }
}

this makes syntax error.

constantColor [_Atten * _Color]


texts: How to have multiple GameObjects sharing pieces of same material?

texts:
My question is: There's any way of having GameObjects sharing pieces of same Material, not a clone, but an extension of one? For example, in these case nine game objects sharing just the same material enlarged to fulfill the size of nine ones:

And in the case, I delete for example one in the middle, it will keep the same material enlarged with the blank space inside:

For this purpose, I used one material per object, but my intention is to use it just one texture for multiple objects, or for example, more of one texture in different parts of the same one. (Like the painting button we have in the custom Unity3D Terrains).


texts: How can I realistically simulate audio for multi-sensor processing?

texts:
I am performing audio simulations in Unreal Engine 4.

Ideally, I need realistic audio propagations. So microphones at multiple locations will experience propagation delays related to their distance from a sound source. Basically to be able to do spatial signal processing with a microphone array.

I have done some experiments with the Steam Audio plugin but I don't think that the propagation delays are built-in. Some research points to needing to add the propagation delays in post processing, but if the sound source is moving, then the problem becomes difficult.

How can I implement this in my project?


texts: How can I determine which square in my memory game was pressed?

texts:
I want to develop an simple memory game on Android.

The memory game have squares like the picture below. How should I determine which of the square is pressed? Should I use image buttons? Personally I don't think it is an good idea to make the game with image buttons. Could you suggest me an solution on how I should determine which of the square is pressed?