texts: How to run a pathfinder thread and game thread concurrently

texts:
Issue:

I want to be able to set up my game loop to work concurrently with my pathfinder request, that would be a queue which different units request for in order in the pathfinder thread.

My current attempts have so far failed.

   -

while (ConqEngine->IsRunning())
{
    bool running = ConqEngine->IsRunning();
    // Draw the scene
    ConqEngine->DrawScene();
    updateTime = ConqEngine->Timer(); // Frame Timer
    s1.pathfinderthread(ref(unitsneedpathfinding)) // this here, beginning of
    if (menuloop)
    {
        initial_menu_loop(loaded_men_interface, menuloop, loadloop, infoloop ,textControl);
    }
    else if (loadloop)
    {
        preconqload(loadloop, gameloop, startingx, pipnumber);
    }
    else if (infoloop)
    {
        if (ConqEngine->AnyKeyHit())
        {
            ConqEngine->RemoveSprite(MainAB.LoadingSprite);
            infoloop = false;
            menuloop = true;

        }
    }
else if (gameloop)
{
    if (game_n_setup)
    {
        SetupMusic("sound/RA2.ogg");
        sMusic.play();
        game_n_setup = false;
    }

    ConqCamera->LookAt(0, 0, 0);
    CamLastFrame = CameraVec;
    gameloop_interface(cspeed, CameraVec, displaycubes, dcubestime, CamLastFrame,
    draycasttime, CitySprite, cityspriteno, wealthtick, myFont, myFont2, textControl);
    gameloop_player(wealthtick, gameloop, menuloop);
    gameloop_units();
    //gameloop_interface()
    if (ConqEngine->KeyHit(Key_Escape))
    {
        gameloop = false;
        loadloop = false;
        menuloop = false;
        ConqEngine->Stop();
    }

    s1.join();
}

}

Currently what this attempts to do is that i have a bool for gameloop as a global, and a global[currently] lists of units needing pathfinding, and i am trying to execute the thread each frame seperately from the rest of the thing running, and then do a join at the end to force the program to wait for all to be completed but this causes a crash.

What is a good structure for multithreading my game with a pathing requester ? I'm honestly not sure how to tackle this the best way, I don't mind my Unit having to wait a few seconds, as that would look somewhat realistic anyway, a thinking animation is really no problem for me.

Is there a standard practice for seperating out the game loop with something else?


texts:
I'm having some trouble figuring how to deal with state management in my entities.

I don't have trouble with Game state management, like pause and menus, since these are not handled as an entity component system; just with state in entities/components.

Drawing from Orcs Must Die as an example, I have my MainCharacter and Trap entities which only have their components like PositionComponent, RenderComponent, PhysicsComponent.

On each update the Entity will call update on its components. I also have a generic EventManager with listeners for different event types.

Now I need to be able to place the traps: first select the trap and trap position then place the trap.

When placing a trap it should appear in front of the MainCharacter, rendered in a different way and following it around. When placed it should just respond to collisions and be rendered in the normal way.

How is this usually handled in component based systems?

(This example is specific but can help figure out the general way to deal with entities states.)


texts: Sharing functions across multiple shaders

texts:
Simple question:

In GLSL, is there a way to share functions across multiple shaders, or do I have to define all functions in every shader that needs them?


texts: How do I destroy a Box2D body on contact without getting an IsLocked assertion error?

texts:
I get this error when attempting to remove a body from the world:

  java:
  /var/lib/hudson/jobs/libgdx/workspace/trunk/gdx/jni/Box2D/Dynamics/b2World.cpp:134:
  void b2World::DestroyBody(b2Body*): Assertion 'IsLocked() == false'
  failed.

What am I doing wrong?


texts: Bilinear filtering: Selecting pixels to interpolate between

texts:
When looking for implementations of bilinear filtering online, all the ones I can find seem to just pick the current pixel, and the three pixels to the bottom and right side of the current pixel.

However, is this even correct, or do you actually have to get the nearest neighbors to the current pixel (from the 8 surrounding pixels) depending on the texture coordinate?

Also, how would I select between the 8 options as efficiently as possible in shaders?


texts: Compute min/max position of tile in compute shader

texts:
I'm trying to implement tiled deferred lighting with OpenGL compute shaders.
For that, I need to compute the minimum and maximum position of each tile.

My first approach was to use atomicCounters for the computation, like that:

shared int minX;
shared int minY;
shared int minZ;
shared int maxX;
shared int maxY;
shared int maxZ;
...
atomicMin(minX, positionWorld.x);
atomicMax(minY, positionWorld.y);
barrier();

// now the shared variables contain the min/max
// position per tile

But that runs painfully slow (I guess because the atomic operations aren't very well for  parallel processing).

So what would be the best / fastest way to do this?


texts: Level/Asset design for performance Unity

texts:
I am a big fan of modular assets.
Currently I am designing a 3d game for mobile and I don't know how I should create my levels to get the most out of the device.

Should I...

create lots of "small" (1x1x1 meter) assets and build my level using them
or create one geometry for the entire level?

What about textures?
Should "all" objects share one highres texture and only display their part using the right UV settings (like say in minecraft)or should I create an individual texture for each object?


texts: Marching cubes density function: noise sampling leaves holes in plane

texts:
I'm following the GPU Gems 3 chapter 1 (Generating Complex Procedural Terrains Using the GPU). The main difference is that I'm using the CPU for generating the mesh(es) based off of marching cubes. And I have this problem that I'm not sure how to solve or even debug.

In Figure 1-8, they start adding noise to the plane at y=0:

density += noiseVol.Sample(TrilinearRepeat, ws).x;

I tried to do the same thing, but I got a plane with island-like holes in it:

Here is my density function:

float densityFunction(Vector3 ws) {
    float density = -ws.y;
    density += noise[(int)ws.x, (int)ws.y, (int)ws.z];
    return density;
}

noise is a 3-dimensional float array of pink (Perlin) noise whose mean is 0. It has a frequency of 2 and 3 octaves with half persistence. Its standard deviation is ~ 0.2. And it varies around ±0.65.

The isolevel of the marching cubes algorithm is set to 0.

What could be causing this undesired effect?


texts: OpenGL Texture Zig-Zag Artifacts Over Time

texts:
I'm working on a deferred shading renderer in OpenGL, where I write all geometry output to Colour, Normal and Depth textures and then apply lighting effects later.

Everything seems fine except once every few weeks, constant zigzag-like patterns appear past a certain depth (below the player's knees in the screenshot below). These zigzag patterns are at the same screen coordinates regardless of my pitch and yaw in the game:

I'm not sure what information to provide to resolve this issue, as it seems to me like a GPU error. Each zigzag square is 16x16 pixels, which could be the warp size on my NVIDIA GTX 960. Restarting the program resolves the problem and it doesn't happen again for a few weeks.

My guess is that sections of the fragment shader are failing to write to multiple render targets as I see the same pattern on the Colour, Normal and Depth textures.

The blue colour you can see on the left side of the zigzag pattern is the water at the bottom of the map, which is rendered after the post-processing stage and does not have these artifacts.

Any help with this would be greatly appreciated.


texts: OpenGL never reverts to default FrameBuffer

texts:
So I'm trying to change the texture using FBOs, When I run it, The whole game gets drawn in the new FBO that I created then deleted, Here's the function
public void ChangeTextureBuffer(int width, int height, ByteBuffer newBuffer) {
    int frameID = glGenFramebuffers();
    glBindFramebuffer(GL_FRAMEBUFFER_BINDING, frameID);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ID, 0);
    glViewport(0, 0, width, height);

    Texture texture = new Texture(width, height, newBuffer);
    glBindTexture(GL_TEXTURE_2D, texture.ID);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex2f(-1, -1);

    glTexCoord2f(1, 0);
    glVertex2f(1, -1);

    glTexCoord2f(1, 1);
    glVertex2f(1, 1);

    glTexCoord2f(0, 1);
    glVertex2f(-1, 1);
    glEnd();

    texture.Delete();
    glDeleteFramebuffers(frameID);

    glBindTexture(GL_TEXTURE_2D, 0);
    glBindFramebuffer(GL_FRAMEBUFFER_BINDING, 0);
}

And here's what I'm getting

It's getting drawn where I want it to be with the size that I want, I just don't want everything to be drawn there.
Also when I delete a texture or framebuffer, OpenGL isn't reusing the id, I don't know if that's a feature or a bug.
EDIT: Here's how its supposed to look, Everything getting drawn in its place, I just want to change the text on the bottom left side to show the FPS


texts: Do I have to resize and manually move the checkbox with a Unity Toggle?

texts:
I have a Toggle UI element (the stock one from Unity 5.2), and when I resize it to make the text legible, the checkbox doesn't resize or move:

Am I missing something, or is the control implementation incomplete?


texts:
I have strings named like this:

list_1 = {"a", "b", "c"};
list_2 = {"v", "t", "d"};
list_3 = {"e", "a", "b"};
..
list_100 = {"g", "q", "z"};

and I have a variable:

int counter;

and I have string[] myList; which I define as below:

if (counter==1){
   myList = list_1;
}
else if (counter==2){
   myList = list_2;
}
else if (counter==3){
   myList = list_3;
}
...

else {
    myList = list_100;
}

Is there a way to shorten this code, so that if score == i, then I can assign myList = list_i?

ty so much!


texts: How do I create this type of mixed 2D/3D character model?

texts:
I'm interested in how this little Lively Hamster Flash game's character is modelled and animated.

The head seems 3D. The back always shows a black outline, so I assume it is 2D.

Is this a Flash-provided effect? How could I create such a model?


texts: Removing all destroyed objects from a list

texts:
I am a little confused on deleting objects in a List. I realise that clearing the list doesn't destroy the gameobject in Unity. Hence I have written this routine to destroy and remove:
//clear all block sprites away
for (int i = 0; i < blockSprites.Count; i++)
{
    Destroy(blockSprites[i]);
}
blockSprites.Clear();

But what if I only wanted to destroy some of the elements (a variable amount)?
In that scenario the List.Clear() function wouldn't work. Would I have to make another list of indexes in order to go through destroying and removing from the list in two sweeps. Or is there a better way?


texts:
I don't know how to name what I am searching for... Force, Impact?
It's easier to explain with an image for me.
We have two GameObjects with colliders, A and B. They can move in any direction (top down game with 360° movement possibilities).
First case (left): A go to the right at a speed of 2, B to the left at a speed of 1 and they collide. How to calculate that A take 1 damage (from the speed of B in its direction) and B take 2.
Second case: A go to the right at speed of 2 and B to the right at speed of 1. A take 0 damage and B take 1.

I am using Collision2D which doesn't have "impulse" property.
I have no idea how to calculate thing like this manually.


texts: Console (CMD like) in a DirectX application

texts:
I really need a console for the game i'm making. I am programming a first person camera right now and i want to see what is going on with the variables (to be more specific i need to know if i'm getting the mouse input as i want or no) and i don't know how to see it. I searched online A LOT and i found tons of scripts with no explanation so i don't know what to do.
What i need is the "noob" line of command you get when you don't use WINAPI. The one you have from just writing your code into the dev c++.
I know it sounds like i have no idea of what i'm saying but i don't know how to ekplain it better.


texts: Should UI systems update naively with events and data from outside, or should they be coupled to some game state/singleton to know to change itself?

texts:
I'm making a game in Unity for my game dev course in uni. I hope the question isn't too confusing but I have bolded sort of like a TLDR at the bottom.
My level currently has a pregame UI panel, to set number of players and lives, and that panel gets hidden in midgame. When a winner is found, the midgame UI is hidden, and I unhide an endgame UI panel which shows the name of the last survivor, and the LevelManager emits these events that tell my UI to do that, along with data about who won, the player object that won, etc.
I have an EventManager singleton that I currently use that the UIManager can use to subscribe to the LevelManager emitting a game end event. I pass through data or params using CustomEventArgs, and the UI can use that data to update itself. So essentially, I'm using the former method in my title, where a UIManager just hides or shows panels based on its own method calls that it receives through events from the LevelManager, and has no idea whether or not the game is over, or done, or is started, it just does its own method calls based on the events it's subscribed to and I manually show and hide pregame/postgame panels in these methods.
But I was wondering whether or not a better way would be to add some sort of state machine to the LevelManager and just have the UIManager change based on tracking state changes of the LevelManager. If the LevelManager changes its own state, the UIManager would just receive information about the LevelManager's change in state and hide/show its own panels automatically depending on the current game state? I feel like since the UI is so near the LevelManager in terms of having to use the LevelManager's information, I should be having the UIManager ask for and receive data from the LevelManager directly, instead of changing UI naively with event calls and data passed in params from ouside.
What do you all think? Should a UI system stay sort of uncoupled from a game manager and only change itself based on method calls and passing in data with params, or should the UI system just keep a reference to some global game state and know when and what to change through changes in this global state?


texts: Computer Games Technolgy or Software Engineering?

texts:
I'm in the last year of my college and going to university next year. Could you tell me what the difference between Software Engineering and Computer Games Technology is?

I know a bit of both but don't know the actual difference. I'm kind off in a dilemma between these two. I want to be a programmer, I'd love to go into gaming but I heard getting a job within a computer games company is really hard.


texts: How do I fairly distribute resources among factories when resources are near exhausted?

texts:
The main resource in my game is mass, stored as a floating point number that changes over time. Resource nodes increase mass and factories drain it. For example, if I have a resource node yielding 5 mass per second, I'll gain 5 * deltaT mass each game step. Mass is displayed rounded to the nearest integer, and gain/loss indicators are displayed by tenths.

How should I handle mass hitting zero? This creates a race condition if multiple factories are trying to build at once: Factories first in the queue or which drain less resource get priority once some more resource comes in and so build faster than the others.

How can I deal with this? Should I skip the step entirely?


texts: GLSL vertex shaders with movements vs vertex off the screen

texts:
If i have a vertex shader that manage some movements and variations about the position of some vertex in my OpenGL context, OpenGL is smart enough to just run this shader on only the vertex visible on the screen?

This part of the OpenGL programmable pipeline is not clear to me because all the sources are not really really clear about this, they talk about fragments and pixels and I get that, but what about vertex shaders?

If you need a reference i'm reading from this right now and this online book has a couple of examples about this.


texts:
I'm trying to create a mechanic in my puzzle game in which if the player clicks on one of the flying game objects, the object's gravity would be enabled and world physics would be applied to it. Initially, I thought I could use the 'enabled' feature to create such a mechanic but I noticed that the RigidBody class does not contain 'enabled'.

Could there be any other way that would allow me to disable the GameObject's gravity or RigidBody component when it is instantiated?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Plane : MonoBehaviour
{
    private bool clicked = false;
    [SerializeField] private Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.enabled = false;
    }

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

    }
}


texts: How to move while a timer is going in an event

texts:
I'm trying to make a switch activated gate and this is what I have setup so far "picture #1"

but what happens when the timer is going on, I cannot move.
so what I'm trying to do is go through the gate "while the gate is open" but have a timer to reset the gate to close.


texts: Game thread, render thread, animation/inverse kinematics, and synchronization

texts: In a multithreaded setup with a game logic thread and a render thread, with some kind of skin mesh animation with inverse kinematics plus etc how does animation work? Does the game logic thread just update a number saying time T in the animation and then the render thread infers Who owns the skin mesh animation, the game logic thread or the render thread? How is it stored in the scene graph if it is stored there at all? When the game logic updates does it do the computation of the skin mesh animation and the computation of the inverse kinematics and then store the result directly in the scene graph or is it stored indirectly and the render thread does the computation?


texts:
So I'm not looking for anything realistic like a physics engine, just want to say that first.  I'm working on a simple top-down game and I'm trying to get friction working with deltaTime.

This was my old code:

friction = Math.pow(0.99f, deltaTime * maxFPS);

This worked well and I applied the friction each frame.  However, I need to refactor this code since I do not know what the possible maxFPS will be (it could be 30, 60, 120 - it depends on the device limitations).

So here's my new code:

friction = Math.pow(0.6f, deltaTime);

This eliminates the need to know the maxFPS and gives me (roughly) the same output value to apply each frame.

My issue is this: I do not just set the friction to a static value, it changes depending on other factors.

So with my old code, for example, the value I would raise to a power to get friction would range anywhere from 0.6f to 1.0f.

With the new code, I have to use different values since the power is different, so the new range would be 0.0000000000001f to 1.0f.

This just doesn't seem (and feel, when playing the game) right.  The range is way too big and from 0.2 - 1.0f the results are all nearly the same value (0.98+, very "slippery" friction) - it doesn't seem like a linear gradient (if that makes sense) the way 0.6f - 1.0f with my old method was.

Just wondering what the common method is to implement frame-independent friction, if I'm doing it right and if there is anything I can do to get the same "feel" I was getting before.


texts: FreeGLUT keyboard IO timing and synchronization

texts:
Using FreeGLut's keyboard callbacks,
glutKeyboardFunc();
glutKeyboardUpFunc();

glutSpecialFunc();
glutSpecialUpFunc();

When in the glutMainLoop pipeline do these functions get called? In other systems (C# + OpenTK, XNA, etc.) , I'd use a polled (vs interrupt-driven) approach to perform keyboard IO. That is, in the Update phase of the game loop, I'd do the following:

update currentKeyboardState via an OpenTK, etc. framework call that returns an array with the state (up, down) of each key

Iterate through a map of keys, transition states (pressed, held, and released), and associated event handlers

Where a key transition has occurred that has an attached event handler (determined by comparing currentKeyboardState[key] with previousKeyboardState[key]), call it.

when all handlers have been processed, copy currentKeyboardState to previousKeyboardState.

In this case, there's no place or requirement for the GLut keyboard functions. However, it appears I have to do things differently in C++. I can, but I'm unsure of when the callbacks registered with GLut are actually called. Are these issued at the beginning/end of the main loop (activated through glutEnterMainLoop(), or are they arbitrarily called, interrupting the main loop no matter it's current state?
If the latter is the case, it seems that I'd need to add a new keyboard state collection, giving

previousKeyboardState(), the state of the keyboard at the end of the previous loop
currentKeyboardState(), the state of the keyboard at the beginning of the current loop
nextKeyboardState(), collection modified by the glutKeyboard*() and glutSpecial*() callbacks, and copied/moved into currentKeyboardState() before the Update phase begins.

Or, I could:

Create a std::queue<pair<int,bool>>, where ::first is the key code from one of the keyboard callbacks, and ::second indicates if it is an "up" or "down" event.

In the GLut callbacks, add events to this queue. (This may be better implemented as a map to avoid duplicate events for each key, again depending on when and how these callbacks are activated)

At the beginning of the update phase, I would use the queue contents to update the keyboard state arrays.
Of course, this doesn't really solve the problem if a keyboard callback is activated while I'm processing the queue. There are ways around that, also, but this is starting to become really hairy.

The Question
Do I need to be concerned about GLut keyboard callbacks happening during the main loop, or are they guaranteed to only be called between loop iterations (from the point of view of my application)? If the former, what are best practice for dealing with this?
Also, are these callbacks executed in the same thread as the main loop? Should I worry about concurrency issues not only on Windows, but OSX and Linux?
Edit
I've replaced freeGLut with GLFW, which works a bit more like I'd expect. I'd still like some insight on this, though.


texts: How to handle collisions without ugly conditionals and type checking?

texts:
(I asked a similar question, but this one is far more specific).

How can I handle collisions without having to do a lot of type checking and if statements?

People here suggested that when spotting a collision, the collision detector should notify both entities in the collision, and the entities themselves will encapsulate the logic to react to the collision.

I like the idea of having the entities themselves decide how to handle the collisions. However I'm not sure how to avoid doing a lot of type checking and if statements inside the handleCollision methods.

For example (in psuedocode):

class CollisionDetector{
    foreach entity in entities
        foreach otherEntity in entities
            if(collision(entity,otherEntity)) entity.handleCollision(otherEntity);
}

class Entity{
    // .. stuff omitted
    void abstract handleCollision();
}

class Alien extends Entity{
    // .. stuff omitted
    void handleCollision(Entity entity){
        // lots of ugly conditionals and type checking
        if(entity instanceof Missile) die();
        if(entity instanceof Alien) lifePoints -= ((Alien)entity).getDamagePoints();
        if(entity instanceof Wall) setVelocity(0,0);
        // .. etc
    }
}

In OOP we should try to avoid type checking and employ Polymorphism. But I don't see how this can be done in this case.

Is there a way to avoid the ugly type checking and lots of conditionals? Or should I just make my peace with it? How is this most commonly done?


texts: TiledMap taking a lot of time to load in libgdx

texts:
I am developing a game using libGdx in which a level has 2400 * 450 tiles Map and each tile is of 4 pixels. I am also using box2d in my game.

My problem is that when I run the game on my phone it takes a lot of time to load the screen (more than a minute).
How can I reduce this loading time?

I created tilemap using Tiled and I am using Android Studio.

Below is my code (SCALE is 2.0f and PPM is 4)

@Override
public void show() {
    w = Gdx.graphics.getWidth();
    h = Gdx.graphics.getHeight();

    camera = new OrthographicCamera();
    camera.setToOrtho(false, w / SCALE, h / SCALE);
    camera.update();
    viewport = new FitViewport(w / SCALE, h / SCALE  ,camera);
    viewport.apply();
  .
  .
  .

    map = new TmxMapLoader().load("maps/lvl3.tmx");
    tmr = new OrthogonalTiledMapRenderer(map, 1/SCALE);

}

@Override
public void render(float delta) {
    update(Gdx.graphics.getDeltaTime());

    //Render
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    tmr.render();

    .
    .
    .
    b2dr.render(world, camera.combined.scl(PPM));
}

public void update(float delta) {

    world.step(1 / 60f, 6, 2);
    cameraUpdate(delta);
    tmr.setView(camera);
    batch.setProjectionMatrix(camera.combined);
}

@Override
public void resize(int width, int height) {
    camera.setToOrtho(false, width / SCALE, height / SCALE);

    viewport.update( width , height );
}

Please help and thanks in advance


texts: Getting grid coordinates of cells bordering a square region

texts: I have a board that is 4x4 ( the blue cells) with the origin (0 , 0) being in the bottom left for example, how can I get the coords which are adjacent to the board (the red cells) to store them in an array?


texts: Unity 2D: Change one instanced prefab then make all the others on the scene like it

texts:
I want to get this thing working:
I have a prefab with coins, some obstacles and enemies, and i want it to be instantiated each time the player got to the right or left on the stage, to make the stage kinda loop. Then, if the player get a coin in this prefab, this coin will not exist in any other prefab, so if the player goes back to his original place, this coin wouldn't be duplicated(because the idea is a loop)

And it can't delete from the original prefab, because then if we start the game again it'll not have the coins anymore.

Exactly like this:
https://www.youtube.com/watch?v=ETxoUDWCBvE

As you can see, when the blue bird gets the other birds, the yellow bird it isn't there anymore if you go back, because the stage kinda loops, and i want to do that.

How enemies would work? Or there's another way of doing this?


texts: Gamepad default trigger identification in Windows

texts:
I'm currently writing an interface driver for my Moga Power Pro controller on Windows.  I'd like to release it for others to use, but first I have some questions on expected default mappings for the triggers.

Specifically, how do other gamepads map the triggers, as viewed from the Windows joy.cpl Game Controllers panel?  And which axis are they normally mapped to?  Some axes default to the center value, others can default to zero, and the different axes might be treated differently inside games.  Triggers are naturally zero-to-full, but I don't want someone to download my interface driver and suddenly find the triggers are always active because Windows thinks the axis ought to be centered and reads it always tilted to one side.

I realize every controller is different, so this may be a bit subjective, but the closer I can set it to some form of standard the better.  Or is this something I shouldn't even need to worry about, that games which expect a trigger input will handle on their own?


texts: Indexing a point outside of a 3D signed distance field

texts: I have a 3D signed distance field that is voxelized into a grid, surrounding an object. However, I would like to query the signed distance field to determine the shortest possible distance between points outside of the signed distance field grid, and the mesh itself. Is there any way to determine this distance without increasing the size of the signed distance field? Thank you!


texts: Authoritative Server Movement and Collision

texts:
I am attempting to write a proof of concept in preparation to do my first networked game. I have decided to do an authoritative server with client side prediction.

I am trying to implement my architecture like this diagram from an excellent article on the subject

In the article, the data that is synchronized is the player's position. This works great for turn based games, but what about real time games?

In my game, each entity has a position and a velocity vector. It is the server's job to detect collisions. I have attempted to send the server velocity changes, but I am having an issue where the server's position and the client's position begins to diverge because their clocks are not perfectly synchronized.

So my question is, is it standard practice to send positions as the synchronized state between a client and server instead of a velocity vector? Will changing to synchronizing positions instead of velocities open my game up to cheating? Is there a better way to synchronize the players' states with the server?

Also, if I use positions, doesn't that mean that the other players are going to be seen in a past state? Will that mean that the server might send a player killed message before the collision is visible to the player in the present?


texts:
I want to analyse my Unity code, as to say all of my scripts, to check if there are obvious bugs or code smells. SonarQube does not support Unity as far as I know. I have heard of Gendarme but I don't know what it is worth, it is stated in this post that it can be used with Unity but there was no update on the GitHub repo for the last 4 years .

Then, is there any known code analizer that use the Unity basecode and can be used in a good development workflow ?


texts: Drawing huge amount of tiles in Monogame (XNA) efficiently

texts:
I'm asking this question because I haven't found a definitive answer to it.

Let me first of all state a few things about the game and what I have already done. The game is a going to be a RTS set in a procedurally generated world using Simplex noise. The world consists of chunks which are 16 x 16 in size made of sprites that are 64 x 64. I've managed to load and unload chunks dynamically, which works just fine. The world is going to look a bit like Rimworld, so top-down with different layers of sprites (terrain first, transition sprites, trees, decals etc). Newly generated worlds may contain entities that may affect the environment (eg. a village that has become a town) and thereby the chunk. I'm sure this can be calculated using some sort of function, but it's something to take note of.

The main issue I have is when I zoom out, more and more tiles are drawn which severely affects the performance. At about 30000 sprites, the draw section takes 8 ms which is half of what is required to run at 60 FPS. And that's just the terrain. I am using texture atlases to limit draw counts (30000 sprites drawn in 6 counts).

The goal is to be able to zoom out from town/village/city level all the way to being able to see an entire country. This has to be done dynamically (eg. not by clicking on a minimap icon, but just scroll back just like in Supreme Commander).

I've read many articles about this issue, but I haven't found or seen a clear example of where it would work. Here's a list of techniques I have found that are supposed to work:

Dirty rectangles, as described here, where you only draw new stuff and keep the rest in the backbuffer. This makes a lot of sense, but I am clueless as to how to implement this in Monogame.
My preffered choice: make extensive use of RenderTargets, as described here, where you draw to a RenderTarget and then save it as a texture. In my case a 16 x 16 chunk consisting of 64 x 64 would create a 1024 x 1024 texture. I really doubt this will work in terms of performance, but the result would consist of highly detailed textures and is also great to use considering the fact that most of it is static (terrain/trees etc), and doesn't change as much. But this also means that everytime a change is made to a chunk, that Texture2D has to be changed using SetData, which from what I've experienced is quite CPU intensive. However if the textures were 16 x 16 it may actually work, and it would also cut down own memory and disk usage.
Til textures by specifying the SourceRectangle in SpriteBatch. For huge grasslands/oceans this is a plus, since only one sprite is drawn. However for detailed terrain with different colours and different sprites mixed together (biomes and biome transitions) I'm afraid it won't make a huge difference.
My own solution, which compromises detail, was to use a standard white 64 x 64 tile, give it the colour of the surrounding 4 tiles and then scale it so it covers the 4 previous tiles. The difference here (besides the tile having a plain colour) is that the landscape visibly changed. I should also mention that forests still have to be drawn individually since they aren't perfectly square.

If anyone has any idea on how to tackle this problem, even if it means compromising certain things (such as detail, or using 16 x 16 sprites), I would love to hear it.


texts: Unity3d - Immediately force transition without waiting until current animation ends

texts:
I created a animation Controller and attached it to the Animator component of my main camera. My Animation Controller looks like this:

I am building a Main Menue. If the user presses on the buttons, then the camera is animated to different places in the world.

Each transition is linked with a condition, e.g. the Transition going from CameraIdle to ToLoadscreen has a condition called GoToLoadscreen which is a boolean parameter, the camera is only getting animated to the Loadscreen, if its value is true.

However, the transition is only starting after the current animation CameraIdle finished playing, as you can see in the next picture, CameraIdle is still getting played even though the parameter GoToLoadscreen is set to true.

How can I force the transition?


texts:
In my game, I will have more than 100 types of cards,
and before the actual game, player can select 6 of them and will be shown as 6 buttons on the scene.
The card have its own ID, card name, and a 3D game Object prefab, and have a function call perfromCardAction which performs different actions.

public class cardA:cardInterface {
     private int ID;
     private string cardName;
     private Texture2D cardImage;
     private GameObject card3DObject;

     ...Constructor...

     private override void prefromCardAction(){
     ...do Card A action...
     }
}

A script cardManager should get the 6 object player selected and stored in an array.
And set the button's Image as card's 2D image.
when the button is click, that card's prefromCardAction should be called.

So my main quesstions are:
What pattern should I used so that easier manage my cards objects?
I believe I should use Factory so that I can do something like:

selectedCardArray[0]=CardFactory.createCard("CardA");

If yes, I would like to ask:
How should I code all my card class (cardA, cardB, cardC...)?
separate into different c# script and implement cardInterface and override the perfromCardAction?


texts: Toon/cel shading with variable line width?

texts:
I see a few broad approaches out there to doing cel shading:

Duplication & enlargement of model with flipped normals (not an option for me)
Sobel filter / fragment shader approaches to edge detection
Stencil buffer approaches to edge detection
Geometry (or vertex) shader approaches that calculate face and edge normals

Am I correct in assuming the geometry-centric approach gives the greatest amount of control over lighting and line thickness, as well eg. for terrain where you might see the silhouette line of a hill merging gradually into a plain?

What if I didn't need pixel lighting on my terrain surfaces? (And I probably won't as I plan to use cell-based vertex- or texturemap-based lighting/shadowing.) Would I then be better off sticking with the geometry-type approach, or go for a screen space / fragment approach instead to keep things simpler? If so, how would I get the "inking" of hills  within the mesh silhouette, rather than only the outline of the entire mesh (with no "ink" details inside that outline? (AKA suggestive contours, creases).

Lastly, is it possible to cheaply emulate the flipped-normals approach, using a geometry shader? My concern with this is that I could certainly duplicate every single vertex and scale these accordingly, but how would I approach flipping normals, and distinct colouring in the fragment shader?

What I want - varying line thickness with intrusive lines inside the silhouette...

What I don't want...

EDIT: Further research has turned up the following...

Since I have a massive vertex count on terrain, even considering distance-based LoD, neither flipped-normals nor a geometry shader based approach (even with frustum culling) would be a sensible option due to sheer computational complexity involved in duplication & scaling of all uploaded vertices.

Considering that I don't need per-pixel lighting in the form of solid-tone shading on the terrain surfaces, it also becomes less prudent to consider any face-normal based approaches -- otherwise a requirement for correct surface lighting -- as these are naturally quite expensive to calculate. It is however true that they give the finest degree of control; for example, the ability to shade edges using "artistic" strokes: Beautiful, but again, not really viable for a massively complex game environment.

Stencil buffers are something I'd rather avoid as I'd prefer to do all work in shaders. (The above example with the red outline was done with a stencil buffer -- old school.)

This leaves fragment shader image-space approaches. Computational complexity is reduced to the number of fragments rather than the number of vertices (in my case, this is 10-100x fewer operations than I would have to do in the geometry shader). This requires more than one render pass in order to generate a g-buffer (consisting of a normal buffer and optionally a depth buffer as well) to which we can apply discontinuity filters (eg. Sobel operator). Depth discontinuity is what enables suggestive contours and creases. My only quibble with this approach is the inability to provide finer control over inked edge widths, though with the right algorithm in the fragment shader, I'm sure this would be possible.

So the question now becomes more specific: How exactly would I go about getting variable edge widths, particularly on the outer silhouette, in a fragment shader?


texts: What is the most efficient way to blur in a shader?

texts:
I'm currently working on screen space reflections. I have perfectly reflective mirror-like surfaces working, and I now need to use a blur to make the reflection on surfaces with a low specular gloss value look more diffuse. I'm having difficulty deciding how to apply the blur, though.

My first idea was to just sample a lower mip level of the screen rendertarget. However, the rendertarget uses SurfaceFormat.HalfVector4 (for HDR effects), which means XNA won't allow linear filtering. Point filtering looks horrible and really doesn't give the visual cue that I want.

I've thought about using some kind of Box/Gaussian blur, but this would not be ideal. I've already thrashed the texture cache in the raymarching phase before the blur even occurs (a worst case reflection could be 32 samples per pixel), and the blur kernel to make the reflections look sufficiently diffuse would be fairly large.

Does anyone have any suggestions? I know it's doable, as Photon Workshop achieved the effect in Unity.


texts: How to make pngs into tilemap and sprites for unity

texts:
I have a tilemap in png form from Pyxel Edit I want to put in Unity. I tried to just use the png but I realized I can't do that and am now stuck.
The backgrounds are not there because I used a decent software for the art but I have not got the foggiest clue as to how to make a tileset using the pngs. Unfortunately most of the replies here about pngs to tilesets are about Pygame which I am not using.
Here is an image of the tileset I made:


texts: GPU optimization question: pre-computed or procedural?

texts:
I'm learning shader program and need some general direction.

I want to add noise to my laser beam.

Which is the best way to handle it?

I could pre-compute an image and pass it to the shader. I could then use the image to change the opacity and easily animate the smoke by changing the offset of the texture lookup.

I could also generate noise in the shader and do the same thing the texture was used for.

Is it generally better to avoid I/O to the graphics card or the opposite?


texts: Legal issues with nba player names, profiles, logos?

texts:
I am searching for this topic and I found a similar question asked
check here:
Legal issues around using real players names and team emblems in an open source game

however I have specific questions where I don't know where to ask.

So I'll make an nba-quiz mini game and I need to know if there might cause some trouble using player profile images, names, team names and logos.

I found about a dozen suck mobile apps which use real names also some use photos as well.

In case I need a permission or check the customs, where to contact? where can I find such regulations?

Lets say I am allowed to use profile images, can I use the official images found on nba.com or yahoo or any sports website?

If not, where to get all player photos? sure can't capture them one by one :)

As for team logos, there are logo-quiz apps which mentions hundreds of logos of different international famous companies, I don't think the app owner contacted each company.

Any related information would help.

Thanks


texts:
I need to clamp a 2D coordinate to fit within an ellipse.

Call of Duty: Modern Warfare 2 does something similar where capture points are translated from a 3D vector in the world to a 2D screen coordinate and then the 2D coordinates are clamped within an ellipse.

When the capture points are in view they're within the bounds of the ellipse.

When they're behind you they are clamped to be within the bounds of the ellipse.

Given a 2D coordinate that could be off screen, etc, what is the math behind clamping it within an ellipse?


texts: Is it ok to use NPOT textures with OpenGL in this situation?

texts:
I drew some icons to use on orthographic projection and instead of loading each icon file individually as a texture I thought of putting them all together in one single file. Now I have a file 72x36 which is not a power of two. This texture is divide in two icons, both with 36px wide.

I didn't remember about this restriction when designing the texture but I eventually noticed it when the texture didn't load because I have an if statement checking if the texture is a power of two, if it's not, than the texture is not loaded. I commented that code to see if the texture loaded anyway and it did. The texture was loaded and properly applied to the area I wanted.

To draw the first icon I do this:

glBindTexture(GL_TEXTURE_2D, gameTextures.hudKeys);
glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 36);
    glTexCoord2f(0.5, 0); glVertex2f(36, 36);
    glTexCoord2f(0.5, 1); glVertex2f(36, 0);
    glTexCoord2f(0, 1); glVertex2f(0, 0);
glEnd();

And for the second this:

glBindTexture(GL_TEXTURE_2D, gameTextures.hudKeys);
glBegin(GL_QUADS);
    glTexCoord2f(0.5, 0); glVertex2f(0, 36);
    glTexCoord2f(1, 0); glVertex2f(36, 36);
    glTexCoord2f(1, 1); glVertex2f(36, 0);
    glTexCoord2f(0.5, 1); glVertex2f(0, 0);
glEnd();

Which is easy to understand, I only use half of the texture depending on which icon I want.

I don't want my icons to be distorted or stretched, the icons were designed with 36x36 in mind. If I use a power of 2 texture, for instance 128x64 (that's the lowest possible to fit a 72x36 texture), how do I properly map the 36x36 texture area I want to the quad?

Or maybe I can keep doing using this NPOT texture or should I still really create a power of 2 texture? How to fix the problem above then?


texts:
As can be seen in the following video:

https://youtu.be/zb3uMUqub00

The dropdown stays stuck open when Unity launches the game. This happens even with a non-modified dropdown that is plopped as a new UI object inside the canvas.

I tried a blank project, and the issue does not reproduce. I tried in a blank project, and the dropdown works. I tried researching a solution, but not too sure how to find one with this problem. Maybe someone here will have an idea or two.

The repo can be downloaded at https://github.com/DenisLabrecque/Warglobe if desired.


texts: Unity Animation Controller and walking diagonally keeps switching between the two diagonals?

texts:
Using Unity 2019.4.1f1 Personal.

I have the above Animation Controller. When only walking in one direction at a time and when you stop you stay facing that direction, this works as planned.

All of the transitions do not have an exit time and have a fixed duration of 0. I don't know what info to give as this is the first time I've used animation. Let me know and I'll add relevant details.
Here's my update function that updates the variables in the animator:
void Update() {
  float h = Input.GetAxisRaw("Horizontal");
  float v = Input.GetAxisRaw("Vertical");

  animator.SetFloat("Horizontal", h);
  animator.SetFloat("Vertical", v);

  if (Mathf.Abs(v) < Mathf.Abs(h)) {
    // flips the renderer to reuse other handed image
    spriteRenderer.flipX = h > 0;
  }

  // no actual movement until I figure this out
}

What I'm experiencing that I want to fix is when running diagonally:

It seems that when walking diagonally then the animator variables for Horizontal and Vertical are both either 1 or -1 and this causes the alternating of the sprites. What I'd like to happen is that the state machine would deterministically pick either N/S sprites or E/W sprites when moving diagonally. Turning on "Can Transition To Self" seems to properly pick a direction and stick to it but it fails to animate when only moving in a single direction. It looks like it's constantly transitioning to itself which starts over the cycle so I've left that unchecked on all transitions.
I'm not sure what the best way to fix this is. Most attempts I've tried so far complicate the state machine to the point it's unmaintainable. I also couldn't find anything about introducing priorities in a way that fixed the jitter.
What's the idiomatic Unity way to achieve clean diagonal movement in 2D?


texts: How do I create this windblown snow effect?

texts:
How do I create this snowy wind kind of effect, where wisps of snow appear to blow through the air close to the ground?

I have seen this in several games like Skyrim, the new God of War, but I don't know what name to call it by.

I found this God of war gameplay https://youtu.be/b7u59Iutb0c


texts: Techniques for drawing lines, with mouse, on 3D objects in WebGL or OpenGL?

texts:
Can anyone point me to techniques for drawing lines, with the mouse, on 3D objects in WebGL or OpenGL?

Here's the effect I'm looking for, using WebGL: http://www.spacegoo.com/cadillac/

I can imagine the general idea - projecting a ray onto the surface, then perhaps using normals and UVs, transform the intersections into UV-space and drawing the line on a texture, which gets mapped onto the object.

Would love to find some proper literature on it though.


texts: Does anyone know where I can find wp7 indie game sales data?

texts:
I am curious about whether to develop an xna game for the windows phone 7. It would be nice to know how the games are doing on that platform sales wise.

Something like this would be very helpful:
http://www.xboxist.com/xbox-360/games/xna-community-games-is-a-failed-experiment-010122.php


texts: rotation matrix problems - opengl and own types

texts:
In an effort to learn things deeper I'm writing my own mathematics for the first time instead of using libraries. As far as I can tell my matrix multiplication is correct, and translation and scaling work fine. I am however, struggling to debug the rotations. I've tried pretty much everything I can think to check and it still won't function as expected. If I set the angle to zero then as expected the Model matrix will not be effected. Changing to 1.0f will explode, the only value which results in expected behaviours seems to be zero... I haven't written a view matrix yet and I've been trying to debug this with the projection(orthographic) matrix on and off. Below is code with some notes.

Matrices are linear arrays of 16 values. i32 is an int, f32 is float, internal is static.

inline m4x4 operator*(m4x4 a, m4x4 b){
  //TODO redo this with simd
  m4x4 Result = {};

  for (i32 Row = 0; Row <= 3; ++Row)
  {
    for (i32 Col = 0; Col <= 3; ++Col)
    {
      for (i32 n = 0; n <= 3; ++n)
      {
        Result.c[(Row * 4) + Col] += a.c[(Row * 4) + n] * b.c[4 * n + Col];
      }
    }
  }

  return (Result); }

inline m4x4 GetRotationZ(f32 angle) {
  m4x4 Result;
  f32 c = Cos(angle);
  f32 s = Sin(angle);

  Result =  { c, s, 0, 0,
         -s, c, 0, 0,
         0, 0, 1, 0,
         0, 0, 0, 1 };

    return (Result); }

inline m4x4 RotateZ(m4x4 m, f32 angle) {
  m4x4 Rotation = GetRotationZ(angle);
  m4x4 Result = Rotation * m;

  return (Result); }

internal void DrawSprite(sprite Sprite, v2 Position, v2 Size, f32 RotationAngle, v3 Colour) {
  glUseProgram(Sprite.ShaderProgram);
  glBindVertexArray(Sprite.VAO);

#if 0
  Position = v2{400, 300};
  Size = v2{100.0f, 100.0f};
  RotationAngle = 0.0f;
#endif

#if 0
  m4x4 Projection = Orthographic(0.0f, 800.0f, 0.0f, 600.0f, -1.0f, 1.0f);
  u32 ProjectionUniformID = glGetUniformLocation(GlobalSprite.ShaderProgram, "Projection");
  glUniformMatrix4fv(ProjectionUniformID, 1, GL_TRUE, &Projection.c[0]);
#endif

  m4x4 Model = IdentityMatrix();
  Position.x = Position.x * 0.01f;
  Position.y = Position.y * 0.01f;
  Model = Translate(Model, V3(Position, 0.0f));

  Model = Translate(Model, v3{0.5f * Size.x, 0.5f * Size.y, 0.0f});
  //Model = RotateZ(Model, RotationAngle);
  Model = RotateZ(Model, 45.0f);
  Model = Translate(Model, v3{-0.5f * Size.x, -0.5f * Size.y, 0.0f});
  Size = v2{0.25, 0.25};
  Model = Scale(Model, V3(Size, 1.0f));

  u32 ModelUniformID = glGetUniformLocation(Sprite.ShaderProgram, "Model");
  glUniformMatrix4fv(ModelUniformID, 1, GL_TRUE, &Model.c[0]);
  glDrawArrays(GL_TRIANGLES, 0, 6); }

Next the shader source

char *VertexShaderSource = R"(
  #version 330 core
  layout (location = 0) in vec4 PositionAndTextureCoords;
  uniform mat4 Model;
  uniform mat4 Projection;

  out vec2 TexCoords;
  void main()
  {
     TexCoords = vec2(PositionAndTextureCoords.zw);
     //gl_Position = vec4(PositionAndTextureCoords.xy, 0.0f, 1.0f);
     //gl_Position = Model * vec4(PositionAndTextureCoords.xy, 0.0f, 1.0f);
     //gl_Position = Projection * Model * vec4(PositionAndTextureCoords.xy, 0.0f, 1.0f);
     gl_Position = Model * vec4(PositionAndTextureCoords.xy, 0.0f, 1.0f);
  }
)";

char *FragmentShaderSource = R"(
   #version 330 core
   in vec2 TexCoords;
   uniform sampler2D Texture;

   out vec4 FragColour;
   void main()
   {
     FragColour = texture(Texture, TexCoords);
   }
)";

I've stepped through the debugger, I've checked every line of code again and again, I've worked through a few matrices by hand and still I don't know whats going wrong. It should be something so very trivial yet I can't seem to find the bug...

Below are pictures demonstrating the difference between 0.0f and 1.0f, as of this state of the code it not only skews and rotates incorrectly, but its scaling is well off as well.


texts: C++:Segmentation fault (core dumped) while creating gameobject

texts:
i made a small code to debug and i get this error

player inherit from gameobject

code

///main
#include "game.h"

 gameobject* pla;

int main()
{

    std::vector<gameobject*> objects;

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

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

/// gameobject
pragma once

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

class gameobject
{

    public:

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

        int numberID=0;

    protected:

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

        float velox;
        float veloy;

        SDL_Rect crop;
        SDL_Rect pos;

        SDL_Texture* tex;

////player.h

#pragma once

#include "gameobject.h"

class gameobject;

class player : public gameobject
{

public:

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

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

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

    int i = 0;

private:

    ~player() override;

};

/// player.cpp

#include "player.h"

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

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

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

    this->numberID = gameobject::numberID;

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

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

}

void player::init()
{
}

void player::tick()
{

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

}

void player::render(SDL_Renderer* ren)
{

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

}

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

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

player::~player(){}


texts: How to render models using a personalized projection matrix?

texts:
I'm creating a game with a great sprite demand. Out team is considering automatizing the sprite generation using 3D models. The problem is we have a very particular ortographic projection:

We have already set up a good projection matrix. The problem is none of the 3D renderer of nowadays have an option for using custom matrixes.

How is this kind of problem dealt with?


texts: How to use prefab only when in inventory game object?

texts:
I created an empty game object named "inventory", whenever I click on an object it transfers into that game object :

and I got this far with the script:

//Transforms
public Transform Knife; //will use the knife prefab
public Transform IceBlock; //will use the iceblock prefab
public Transform Bomb;//will use the bomb prefab
public Transform Chain;//will use the chain prefab
public Transform inventory;//will use the inventory gameobject
private bool knife;
private bool ice;
private bool bomb;
private bool chain;
void fInventory()
{
    if (inventory != null)
    {
        foreach (Transform child in inventory.transform) // child is a gameobject inside of the inventory gameobject
        {
            if (child.name == Knife.name)
            {
                knife = true;
            }
            else if (child.name == IceBlock.name) { ice = true; }
            else if (child.name == Bomb.name) { bomb = true; }
            else if (child.name == Chain.name) { chain = true; }
        }
    }
}
void Update() {
    fInventory();
    if (knife)
        //use knife
    if (ice)
       //use ice
    //........etc
}
}

but as you can see, it's pretty hardcoded.
So what I want this to do is whenever I pick up an gameobject with the name example:"knife", I will be able to use the Knife Transform, and while this script works it really looks ugly and inefficient.
Is there any other way to check if two tranform names are the same without using an if-else statement?
Hope the question was clear enough, and please just point me in a direction!


texts: How to change two rotation axes in Unity without affecting the third?

texts:
I have a GameObject in Unity and I need to change its X and Z rotation without doing anything with the Y, as that would mess up everything.
Note that this sets the Y rotation to 0 and I don't want that (I want it to let it be be what it already is), so this isn't any good:

gameObject.transform.rotation = Quaternion.Euler(someNewAngle, 0f, someNewAngle);

What should I do?


texts: Making a mobile app from a board game. Copyright infringement?

texts:
Me and a friend got hooked on a board game and soon realized that we didn't need the board game to play, instead we could play it with pen and paper with extreme ease and satisfaction. The next step was to develop a simple android app to play it.
We have been using this to play and it's fun, and we are interested in publishing it, but we are worried eventual copyright issues. The concept of the game - itself very simple, merely a type of trivia game, where each round has different rules - is the same, the name is different as is all the art.
Does anybody know if we infringe copyrights if we were to publish it?

Thanks


texts:
I'm in the case I need to transform a Quaternion coordinate system to a concrete one, let me explain.

I'm implementing an orientation tracker for VR headsets, I have the orientation of the device and it workd as expected.
Also I've implemented a function to recenter the device, this function takes the current orientation, obtains the conjugated quaternion and stores it as the zero pose, so when the orientation is retrieved the current orientation quaternion is multiplied by the zero pose and returns the current position. This also works as expected.

Next I've implemented a mouse emulator based on this orientation, I have a Plane composed by (p, n) being p a point in the plane and n the plane's normal (basically (0, 0, 100), (0,0,-1)). To retrieve the mouse position I project a ray (p=(0,0,0),n=((0,0,1) * q)) to the plane and take the (x,y) values of the intersecting point as the mouse coordinates. This also works, but only if the headset axes are aligned to the world axes.

For example, if the user has the headset correctly worn when the pose is reset (take current pose conjugate as the zero pose) then if you look up the mouse moves up, if you move right it moves right, and even if you roll your head the tracking is correct, but if the user has the headset wrongly placed (inclined to some side) when the zero pose is reset then the movement is incorrect as the axes don't match.

I hope this image explains it better than me.

This is the code for calculating the mouse position (it includes a low-filter as smoothing):

    public void UpdateParameters(float ScreenDistance, Vector2 ScreenSize, Vector2 ScreenResolution, float SmoothingFactor)
    {
        smoothFactor = SmoothingFactor;
        size = ScreenSize;
        resolution = ScreenResolution;

        screenZero = resolution / 2;

        xScale = ScreenResolution.X / ScreenSize.X;
        yScale = ScreenResolution.Y / ScreenSize.Y;

        pointOnPlane = new Vector3(0, 0, ScreenDistance);

    }

    public void UpdateInput(Quaternion Orientation)
    {
        Vector3 rotatedNormal = Vector3.Normalize(Vector3.Transform(rayNormal, Orientation));
        float T = Vector3.Dot(planeNormal, pointOnPlane) / Vector3.Dot(planeNormal, rotatedNormal);
        Vector3 pointInPlane = rotatedNormal * T;

        int x = (int)(pointInPlane.X * xScale + screenZero.X);
        int y = (int)(pointInPlane.Y * yScale + screenZero.Y);

        Vector2 np = new Vector2(x, y);
        Vector2 p = new Vector2(prevX, prevY);

        Vector2 ip = Vector2.Lerp(p, np, smoothFactor);

        x = (int)ip.X;
        y = (int)ip.Y;

        if (x != prevX || y != prevY)
        {
            prevX = x;
            prevY = y;

            if (MouseMove != null)
                MouseMove(this, new MouseEventArgs { X = x, Y = y });
        }

    }

And this is the code to calculate the zero pose:

if (recenter)
{
    ZeroPose = Quaternion.Conjugate(fusion.Quaternion);
    recenter = false;
}

So the question, how can I transform the arbitary HMD axes to world axes in order to get the mouse movement right?

Thanks in advance.


texts:
Edit: I figured out what problem I was facing, it's called Texture/Pixel bleeding, which I was not aware of yet. I posted an answer below consisting of a small description of the problem and a link to a post, that I felt explained the problem pretty well.

I'm building a little engine for myself (okay, let's say framework) to learn using DirectX 11. I'm pretty pleased with the results so far but today I ran into a little problem I was not able to solve. When rendering a textured model there are ugly gaps at some polygon joints observable. I will depict the issue more clearly with images of the example I'm rendering at the moment. My model consists of simple cuboids, one of those uses the following part of the UV map (marked vertices and triangles in yellow to clarify, the lines and points are not actually part of the texture).

(As you can see, The cuboid has 14 vertices
Now, I want to display the the pixels discrete. That means: Don't smooth the pixels. Doing this I got visual issues seen in the screenshot below. This is a screenshot of the edge, where the two triangles meet.

(When I use smoothed pixels by using a linear filter when creating the sampler Description there are no real gaps, but the edges of the plane are influenced by the color that would have been the gap)
As you can see, there is a gap between polygons. The corresponding spot on the uv map is marked in red on the top picture. This behaviour is observable at every spot two polygons, that are not adjacent on the UV map, meet. Also note how the gap is partly filled with orange/pink, the color that is adjacent to the polygon on the UV map (Pixels of other meshes, in this case the right arm).
Steps I took to find a solution:

First I thought it could be caused by float inaccuracies. Moving every Vertex a little bit (the minimum a float can encode) to the inside of the UV-Map would probably solve the issues. But I think that this would be one hell of a workaround and can't be the solution.
Changed the texture to be 16x16 (instead of 13x12) because I thought this would decrease the inaccuracies with float, but it didn't help much.
I thought changing the filtering to something different could help, but I wasn't lucky.
I even tried modifying the uv coordinates inside the Pixel Shader, but this was doomed to fail and resulted in some weird (but in some way funny) results.
Googled around with various keyword, but couldn't find anything that appeared to solve this issue.
When I tested drawing it as a wireframe the edge was drawn in orange/pink

I'm probably missing the obvious here, but how can I fix this and get rid of the gaps?
I triple checked that all vertex data (x|y|z and u|v) are correct. Is there any kind of filter I am missing? Or do I even have to use some nasty workaround (like surrounding the actual texture on the uv map with an extra row of correctly colored pixels)? I would like to resolve this before going on.
Thanks in advance to anyone taking the time to read (and even answer or point me in the right direction) this presumably stupid question.
In case it's relevant here is the data for the 4 involved vertices(numbering as depicted above). First Vector is x|y|z, second one u|v:
vertices[ 0] = { { -1, -1.5f, .5f },{  9.f / 16.f, 5.f / 16.f }};
vertices[ 1] = { {  1, -1.5f, .5f },{ 11.f / 16.f, 5.f / 16.f }};

vertices[11] = { { -1, -1.5f, .5f },{  8.f / 16.f, 4.f / 16.f }};
vertices[12] = { {  1, -1.5f, .5f },{  6.f / 16.f, 4.f / 16.f }};

(A screenshot of the complete model in case the look of the whole thing wasn't clear. There are also fragments visible at the head and the top of the arm. )


texts: Getting a Specific Component in an Entity Component System

texts:
I've got component class:

class Component
{
public:
    Component();
    ...
};

then my various components derive from the base Component class

class VelocityCom : public Component
{
public:
    VelocityCom();
    ...
};

and then an entity class that holds the components and is able to return a specific component for manipulation

class Entity
{
public:
    Entity();
    std::unique_ptr<Component> getComponent(...);
private:
    std::vector<Component> components;
};

The problem that I'm having with this approach lies withing the act of getting a specific component. Let's say I want to get a pointer to the velocity component. I can't just have whateverEntity.getComponent(Types::Velocity); because the method returns a Component and not a VelocityCom. I thought about casting the Component pointer to a VelocityCom pointer but it seems that a lot of people don't like the idea of downcasting. So my question is what is a good way to get a specific component in an entity component system? Is downcasting okay in this situation or should I change my implementation to where I don't have to?


texts: Character rotation according to camera causes rapid flipping when game starts

texts:
When I load my scene, my character rotates +90 and -90 on the X axis very fast about 4 or 5 times, and then he stops at -90 on X axis (lays back down).

When I move the character, the rotations are just the way I want them, but I need to fix that weird bug at the beginning of the game.

Here's my character's movement logic. It's based on the rotation of the camera, which is a child of my character object.

void Update() {
    Vector2 vec = new Vector2(horizontal, vertical);
    vec = Vector2.ClampMagnitude(vec, 1);

    Vector3 camF = cam.transform.forward;
    Vector3 camR = cam.transform.right;

    camF.y = 0;
    camR.y = 0;
    camF = camF.normalized;
    camR = camR.normalized;

    transform.position += (camF * vec.y + camR * vec.x) * Time.deltaTime * MoveSpeed;

    Vector3 deltaPosition = transform.position - prevPosition;

    if (deltaPosition != Vector3.zero)
    {
        transform.forward = deltaPosition;
    }

    prevPosition = transform.position;
}


texts:
How Unity can work on Web if the code is written in C#? I understand that you can compile the C# code to a shared library and use it in Java (for Android) in ObjectiveC (for iOS) to enable Unity on multiple platforms, but you cant use shared library on JS. Does Unity do language to language translation from C# to JS to enable Unity on Web?

As I understand now starting from Unity 5.0 it even doesn't use Unity Web Player.


texts: Partial object culling without alpha + transparency?

texts:
I am trying to partially cull an object which has subsurface scattering.  It's simple to do it with an alpha channel, however, using an alpha channel with transparency will disable subsurface scattering.

Potentially relevant information: I am using Unity 2018.3.0b12 with v4.8.0-preview HDRP

Example: here I am achieving the effect with alpha + transparency. The object is either fully opaque or invisible


texts: What compatibility checks should i do while creating Direct3D device, swap chain etc

texts:
I've done DirectX apps for 1.5 years now, mainly to teach myself but now i would like to make games for public. So i was wondering would it work for others just leaving the values default ie. swap chain's refresh rate to 60 without checking the users monitors refresh rate.
Could you tell me what things should not be ignored in situations like this, thanks.

There's no SDL or SFML in my programs just pure C++, DirectX and WinAPI.


texts:
So I have this script (pasting the entire thing in it's current state) :

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Events;
using ooparts.dungen;
using UnityEngine.UI;

    public class RoomMapManager : MonoBehaviour
    {
        public Map mapPrefap;
        private Map mapInstance;

        public int MapSizeX;
        public int MapSizeZ;
        public int MaxRooms;
        public int MinRoomSize;
        public int MaxRoomSize;
        public Image coverPanel;
        public int TileSizeFactor = 1;
        public static int TileSize;
        private UnityAction mapGenerationListener;
        private void Awake()
        {
            //  mapGenerationListener = new UnityAction(FadeCover);
        }
        private void OnEnable()
        {
            // EventManager.StartListening("GenerationComplete", mapGenerationListener);
        }
        private void OnDisable()
        {
            // EventManager.StopListening("GenerationComplete", mapGenerationListener);
        }
        void FadeCover()
        {
            Time.timeScale = 1;
            coverPanel.color = new Color(0, 0, 0, 0);
            coverPanel.raycastTarget = false;
        }
        void Start()
        {
            //TileSize = TileSizeFactor;
            //BeginGame();
        }

        void Update()
        {
            if (Input.GetKeyDown(KeyCode.R))
            {
                RestartGame();
            }
        }

        private void BeginGame()
        {
            mapInstance = Instantiate(mapPrefap);
            mapInstance.RoomCount = MaxRooms;
            mapInstance.MapSize = new IntVector2(MapSizeX, MapSizeZ);
            mapInstance.RoomSize.Min = MinRoomSize;
            mapInstance.RoomSize.Max = MaxRoomSize;
            TileSize = TileSizeFactor;
            //coverPanel.color = new Color(0, 0, 0, 1);
            //coverPanel.raycastTarget = false;
            //Time.timeScale = 0;
            mapInstance.Generate();
        }

        private void RestartGame()
        {
            EventManager.TriggerEvent("GameRestarted");
            StopAllCoroutines();
            for (int i = 0; i < mapInstance._rooms.Count; i++)
            {
                foreach (GameObject g in mapInstance._rooms[i].Monsters)
                {
                    Destroy(g);
                }
            }
            Destroy(mapInstance.gameObject);

            //BeginGame();
            SceneManager.LoadScene("Prototype2");
        }
    }

Notice how Awake, OnEnable and Start do nothing. When this script is attachet as a component to a gameObject the scene where this gameObject is loads very slowly. I mean it takes like 30s to 1 min for it to load even in the editor. THe behaviour is the same when I build the project both to PC and Android. When I start the scene itself from the editor there is no delay. I have no idea what might be causing this.


texts: How to make far block graphically better?

texts:
What calcules can I do to make far objects looking better?

My game

Here's what I see if I go back with the camera in my test-rendering scene:

As you can see the result is not one of the bests: borders are not defined well and the texture itself is not nice to see.

Minecraft

Here's for example an image of Minecraft far blocks rendering:

As you can see the result is better than mine. Minecraft seem blurring far blocks or something like that.

Trove

This is another game cube-based called Trove.

Here I appreciate how it defines block borders by treading them with a black line.

TO MAKE IT SHORT:

EXCLUDING LIGHTS!!!

(I know that lights make their part in graphical improvement but I think that there is something more in mc and trove shaders)

1) How can I blur texture like Minecraft does? (I don't know actually if its a blur)

2) How can I highlight borders of the block like Trove does?

P.s: I'm using OpenGL 3.1+!


texts: joystick movement for Geometry Wars clone

texts:
I am kinda new in game programming, but I've got a semestral work to make a game, so I decided to do a clone of Geometry Wars. Despite that the game is really simple (in principle), I have ran into a problem I can not solve. I use SDL, OpenGL in C (vanilla C, so no C++/C# and stuff, only procedural ANSI (I think ANSI) C). When I get input from joystick, it is fine in the console (if I flush it to the output, it will make immediate action) but when I draw a simple dot (it shouldn't be that time consuming to draw a dot on screen) it have a slight to severe input lag (up to 3 sec.). But that's only the first part of my problem, because it not only renders slow, the movement is totally different from that I make with joystick. Here is the code:

void pollInput()
{
    SDL_JoystickUpdate ();
    SDL_PollEvent(&event);
    double XYValue;
    if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) )
    {
        if( event.jaxis.axis == 0)
        {
            XYValue = event.jaxis.value / 2500.0;
            XYValue = floor(XYValue);
            player.playerX += (XYValue);
            printf("X: %.0lf\n", XYValue);
        }
        if( event.jaxis.axis == 1)
        {
            XYValue = event.jaxis.value / 2500.0;
            XYValue = floor(XYValue);
            player.playerY += (-XYValue);
            printf("Y: %.0lf\n", XYValue);
        }
    }
}

I am really stuck here. And another question came to my mind, is it a good idea to add the input from joystick to the XY coords of the player? Shouldn't I make it like acceleration? If yes, would you kindly write a pseudocode for that? Thank you for your replies guys!


texts: Instantiate GameObjects and change Material when it hits on the ground

texts:
There is a code for instantiate cube into the list and change a  Material of each clone when it hits on the ground
The following code works but not in Real-Time. Update function works like a Start function for a Foreach method
How to get a value of  item.transform.position.y in the Update function Real-Time?
public GameObject cubePrefab;
public Material RedMat;
public float GroudLevel = 0.5f;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
         List<GameObject> cloneList = new List<GameObject>();
         //instantiate clones into the list
         for (int i = 0; i < 10; i++)
         {
            var clone = Instantiate (cubePrefab,new Vector3(Random.Range(-3f, 3f),
            Random.Range(4f, 10.5f),Random.Range(-3f, 3f)), Quaternion.identity);
            cloneList.Add(clone);
         }

         //if clone is grounded change a Material for each clone
         foreach (var item in cloneList)
         {
            //Debug.Log(item.transform.position.y);

            //check if clone is on the ground
            if(item.transform.position.y < GroudLevel)
            {
             item.GetComponent<Renderer>().material = RedMat;
            }

        }

    }
}

There is a screenshot for a GroudLevel = 7


texts: Java 2D - Cannot get code to work for generating points for a line with a start point and Angle

texts:
I am developing a Java 2D video game.  I am trying to write code to generate points for a line (actually a projectile path), at a specified angle, from a given start point.  There seems to be something wrong with my Math.  The points are to be used for moving a projectile from the top of the screen, towards the target (a submarine) which sits at the bottom.

I am suspicuous issue has to do with fact the origin of Java 2D coordinate system is 0,0 at top of the screen, not at bottom left for cartesian coordinate system.  Note: I am not a Math person.  So please excuse me if I am getting the terms wrong.

Here is what I am doing:

xloc, yloc - the initial location of the projectile I want to move towards the sub location

// Get slope of the line
float m= ((float)((int) yloc - subYcoord))/((int) xloc - subXcoord);

double radians= Math.atan(m);

double ycoord= yloc;
double xcoord= xloc;

int speed= 1;

// This is how I am attempting to generate the points for the path for the projectile to take

while (true) {

    xcoord += speed * Math.cos (radians);
    ycoord -= speed * Math.sin (radians);

    if (((int) ycoord)>= gunBaseYcoord) {

        break;
    }

    // WayPoints is my list of points to move the Projectile towards the sub at    bottom of the screen

    Point aPoint= new Point((int) xcoord, (int) ycoord);
    wayPoints.add(aPoint);
}

This does not seem to work for angles of 245 degrees.

As an example, if x,y are: 660, 35 (this would be my start point for the projectile), and subXcoord, subYcoord are: 169, 500

I get a slope of: -.947 (should be like: 245 degrees)

The radian is: -.758

I get degrees of: -43 (now this doesn't look right)

Appreciate any help with this!
Thanks!


texts: Is it possible to fake momentum by tracking an objects last known positions?

texts:
Basically I am making a melee combat system. I want to be able to apply force based on where/how things are hit.
I am NOT using physics simulations for this, which is why I cannot just rely on that.
Instead, can I track the part of the sword that hits the target somehow, to work it's average momentum/direction of attack?
I tried by just using the last frame position and the current frame position, but this doesn't give a great angle (as the sword rotates a lot, it always taps it towards the player, when really all the momentum is going directly left).
Is there a formula for working this out? Or is it as something as simple as just totally up the directional changes each frame, with some kind of decay time.


texts:
I did Frustum Culling in my engine, but it does not work correctly. All shown in the video:

Video

If the approximation is too close, the model disappears. On the right in the console you can see that one model is rendered less. With what it can be connected?

Frustum creation code:

bool FrustumCulling::update(ID3D11Device* device, const Camera & view, float angle, float ratio, float _near, float rear)
{
    Vector3 pos = (Vector3)view.getViewPosition();
    Vector3 d = pos - (Vector3)view.getViewDirection();
    d.normalize();
    Vector3 right = (Vector3)view.getViewHeight();
    right = right.cross(d);
    right.normalize();
    Vector3 up = Vector3::cross(d, right);
    // get h and w near and rear planes
    float val = angle * 0.5;
    float tang = (float)tan(val);
    float nh = _near * tang; // near height
    float nw = nh * ratio; // near width
    float rh = rear * tang; // rear height
    float rw = rh * ratio; // near width
    // generate 8 vertex frustum
    Vector3 fc = pos - d * rear;
    Vector3 ftl = fc + up * rh - right * rw; // ftl - Far(rear) Top Left
    Vector3 ftr = fc + up * rh + right * rw;
    Vector3 fbl = fc - up * rh - right * rw;
    Vector3 fbr = fc - up * rh + right * rw;
    Vector3 nc = pos - d * _near;
    Vector3 ntl = nc + up * nh - right * nw;
    Vector3 ntr = nc + up * nh + right * nw;
    Vector3 nbl = nc - up * nh - right * nw;
    Vector3 nbr = nc - up * nh + right * nw;
    // generate 6 planes frustum
    Plane3 p(ntr, ntl, ftl);
    data.planes[TOP] = PlanesFrustum(p.getPlane());

    p = Plane3(nbl, nbr, fbr);
    data.planes[BOTTOM] = PlanesFrustum(p.getPlane());

    p = Plane3(ntl, nbl, fbl);
    data.planes[LEFT] = PlanesFrustum(p.getPlane());

    p = Plane3(nbr, ntr, fbr);
    data.planes[RIGHT] = PlanesFrustum(p.getPlane());

    p = Plane3(ftr, ftl, fbl);
    data.planes[FARP] = PlanesFrustum(p.getPlane());

    p = Plane3(ntl, ntr, nbr);
    data.planes[NEARP] = PlanesFrustum(p.getPlane());
}

Model verification code (cube bbox) to hit frustum:

bool modelCheckFrustum(Vector3 * v)
{
    for(int k = 0;k<8;k++)
    {
        Vector3 p0 = v[k];
        int isFrustum(0);
        for(int l = 0; l<PLANES_SIZE;l++)
        {
            Vector4 n = planes[l].pl; //
            float value = shortDistanseFromPointToPlane(n, p0);
            if(value > 0.f) // point in current plane
                ++isFrustum;
        }
        if (isFrustum == PLANES_SIZE)// point in frusrtum
            return true; // model in frustum
    }
    return false; // model not in frustum
}

PLANES_SIZE - count planes, == 6

planes - array planes frustum

planes - Vector4, when x,y,z - a,b,c, and w - d

Method shortDistanseFromPointToPlane:

float shortDistanseFromPointToPlane(Vector4 p, Vector3 p0)
{
    return p.x*p0.x + p.y*p0.y + p.z*p0.z + p.w;
}

Distance to the front and rear planes:

float SCREEN_DEPTH = 1000.f;
float SCREEN_NEAR = 0.01f;

Creating a matrix of perspectives:

matrixProjection = Matrix::CreatePerspectiveFovLHMatrix(GeneralMath::PI / 4, w / (float)h, SCREEN_NEAR, SCREEN_DEPTH);

w, i - width and height window

How to fix this nasty bug? Thank.

P.S.: I did frustum culing in this lesson.

UPD1:

I created a model frustum, and it shows that not a single BBox vertex got inside the frustum. Now I know the reason, it remains to come up with a solution to this problem :)

Image:


texts: Collision resolution in case of collision with multiple objects

texts:
I have static objects and movable objects. The collisions are detected using the separating-axis-theorem.
For example, in this situation I have two static objects (in red):

and a movable object between the two:

My algorithm is able to compute the collision between two of these objects, and it also spits out a perfect resolution vector (meaning a minimum-displacement-vector) to the collision.
So for example, when I check the collision between the green rectangle and the right red rectangle, the algorithm spits out a vector that tells me how I need to move the green rectangle in order to resolve the collision:

Notice that I just quickly drew this in MSPaint, so in that picture it could actually be that the minimum-translation-vector pushes the green rectangle out on the top, but I'm going to assume here that pushing it out to the left/right is actually shorter.
The general way of approaching this would be to only resolve the collision of one collision per frame, instead of all at once. But in my case, this would result in flip-flopping:
First, the solver detects two collisions but only resolves the collision between the right rectangle and the green rectangle:

Then, in the next frame, it detects only one collision which is between the left red rectangle and the green rectangle, and resolves it:

As you can see, this doesn't actually resolve the collision (for example by pushing the green rectangle out to the top), and instead just flip flops between the two states infinitely.
How can I solve this?


texts: How can I make it so that my player object doesn't penetrate world collision when I'm holding down movement keys in that direction?

texts:
Right now I have a player object and an obstacle, both with bounding box rectangles around them. The issue is that when my player runs into this obstacle, as long as I'm holding down the movement key, my player goes slightly inside the obstacle, then when I let go of the key my player is placed outside of it.

The movement code in the update function of my player class is as follows:

if (Input.isKeyDown(Keys.Left))
{
    velocityX += 5;
}
_position.X += velocityX;

The collision code in my SpriteManager game component is:

if(player.collisionRect.Intersects(platform.CollisionRect))
{
    if(player.position.X >= (platform.position.x - player.width))
    {
        player.velocityX = 0;
        player.position.X = platform.position.X - player.width;
    }
}

I have searched online for the past two days and have been unable to find any solution to this problem and I have been unable to figure out what I have been doing wrong. Even though this seems like a fairly simple problem.  Any help would be greatly appreciated!

Edit: I can tell that my issue is that when I collide, my player is still moving into my object by the amount of velocityX. So what I need to do is check if there is about the be a collision with the box, however I am still unsure of how to do this.


texts: Prevent collisions between mobs/npcs/units piloted by computer AI : How to avoid mobile obstacles?

texts:
Lets says we have character a starting at point A and character b starting at point B. character a is headed to point B and character b is headed to point A. There are several simple ways to find the path(I will be using Dijkstra). The question is, how do I take preventative action in the code to stop the two from colliding with one another?

case2: Characters a and b start from the same point in different times. Character b starts later and is the faster of the two. How do I make character b walk around character a without going through it?

case3:Lets say we have m such characters in each side and there is sufficient room to pass through without the characters overlapping with one another. How do I stop the two groups of characters from "walking on top of one another" and allow them pass around one another in a natural organic way.

A correct answer would be any algorithm, that given the path to the destination and a list of mobile objects that block the path, finds an alternative path or stops without stopping all units when there is sufficient room to traverse.


texts: Frustrum culling without per-mesh positions

texts:
I am trying to implement frustrum culling in a C++ renderer im writing but I feel like I hit a brick wall.
The plan is to load the Sponza level and per mesh create a collision box using Bullet physics library, which also holds the mesh translation, scale and rotation, then get the camera planes and check if the collision box falls inside the planes. I'm loading the Sponza level using the Assimp library, it loads fine and displays correctly but every node's transformation is at 0,0,0  which leads me to believe all the vertices are pre-translated already (even without optimization flags). I checked it out in Blender and even there the translation gizmo is at 0,0,0 for every mesh. I tried a couple different sponza files, FBX too but they all lack per mesh positions. Should I just give up on this? Are there other ways to perform frustrum culling?


texts: Do I lose any functionality using Visual Studio for Unity 3d?

texts:
MonoDevelop has always had a strange tendency to stop functioning in basic ways ... autocompletion, copy/paste-clipboard, error detecting, and other silly things.

I routinely fix this by running clean / rebuild all, then restarting MonoDevelop. But this is time-consuming. I've read that Monodevelop has issues...

If I switch to Visual Studio will I lose anything at all that I rely on with Monodevelop's integration to unity? Or will I in fact gain?


texts: How to create a second Window in OpenGL/GLFW

texts:
I would like to have 2 windows. 1 for display purposes and one for settings / buttons (for example to change the color of the background in my main display). How would I go about having a second window for these settings? Would I just create another window?

GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Settings", nullptr, nullptr);


texts: Java Swing KeyBindings do not recognize input in a weird way

texts:
I am new to programming, so forgive me if I make silly mistakes.

I want to make a game, and I started by making the player, and that's where I'm stuck at. I'm trying to use Keybindings (InputMap and ActionMap of a JComponent) to make the player move, but something really odd is happening. When I hold "A" to make the player move to the left, that's what he does. But if I then press "D" to make him move right, he just stands still. Then, if I release and press "D" again, it does move. This happens with all of my keyboards, and I had a similar problem when using a KeyListener.

This seems like a problem with another class, like the Player class, but it isn't: When the situation i described occurs, the AbstractActions I created aren't being called! And that was the same with the KeyPressed() method when I was using a KeyListener.

This is my class for managing keyboard-input:

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JLabel;
import javax.swing.KeyStroke;

public class KeyManager {

private JLabel keyManager;

private Action leftTrue, leftFalse, rightTrue, rightFalse;

public boolean left = false, right = false, up = false, down = false;

public KeyManager() {
    initActions();

    keyManager = new JLabel();
    System.out.println("called");

    keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("D"), "pressed_D");
    keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released D"), "released_D");
    keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("A"), "pressed_A");
    keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released A"), "released_A");

    keyManager.getActionMap().put("pressed_D", rightTrue);
    keyManager.getActionMap().put("pressed_A", leftTrue);
    keyManager.getActionMap().put("released_D", rightFalse);
    keyManager.getActionMap().put("released_A", leftFalse);
}

public JLabel getKeyManager() {
    return keyManager;
}

private void initActions() {

    leftTrue = new AbstractAction() {

        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("pressed a");
            left = true;

        }

    };
    leftFalse = new AbstractAction() {

        private static final long serialVersionUID = 2L;

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("released a");
            left = false;

        }

    };
    rightTrue = new AbstractAction() {

        private static final long serialVersionUID = 3L;

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("pressed d");
            right = true;

        }

    };
    rightFalse = new AbstractAction() {

        private static final long serialVersionUID = 4L;

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("released d");
            right = false;

        }

    };

}

}

The JLabel object is added to my JFrame in another class

I don't feel like my explanation of the problem made much sense, so here's a video of what's happening:

https://www.dropbox.com/s/7bs6r1kt6z489rf/JavaHelp.mov?dl=0

Does someone know how to fix this? :(


texts:
I'm trying to make invisible object with shadow by using it's shadow castting pass it additionaly shades back side of object itself. I mean object shades his back side and draws shadow on the background surface.(my unity version is Unity 5.6)

you can see this problem in below animated gif:

this is my shader for unity's shadow pass:

Shader "Test/ShadowCaster"
{
    SubShader
    {
    Tags{ "LightMode" = "ShadowCaster"  }
    Name "ShadowCaster"
        Pass
    {
        CGPROGRAM

#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_shadowcaster
#pragma fragmentoption ARB_precision_hint_fastest

#include "UnityCG.cginc"

        struct v2f
    {
        V2F_SHADOW_CASTER;
    };

    v2f vert(appdata_base v)
    {
        v2f o;
        TRANSFER_SHADOW_CASTER_NORMALOFFSET(o)
        return o;
    }

    float4 frag(v2f i) : COLOR
    {
        SHADOW_CASTER_FRAGMENT(i)
    }
        ENDCG
    }
    }
        FallBack Off
}


texts: How to import a NET .dll newer than 2.0 into Unity?

texts:
I'm trying to build one of the simple EventBus libraries from Github and import them into Unity. Here are the libs:

TinyMessenger and
RedBus

It's that simple - I take the source code, build it through the VS2015 and place the .dll into the Assets/Plugins folder.

Then, I have no way to use the lib's namespace (Unity doesn't read the file).

Both of these libraries are written in NET 3 or 4 and this is the failure's reason.
I've recompiled the second one (removed the System.Linq code, changed the project's version) to NET 2.0 and it worked, but that's not the point. I need the first library and it ain't easy to rewrite the entire 4.0 code to 2.0 without Linq.

As I remember, you can use System.Linq in Unity (at least, I did it once). This means that Unity uses some kind of trickery/magic, as always.

What's the problem here? Is there any way to get this working?


texts: how does an SM5 shader handle loops and if statements? (HLSL/CG)

texts:
How does an SM5 compilation handle loops and if-else statements, are branching execution routines unwound and if so, to what degree?

Is it only Direct Compute that can optimize branching code?

searchwords: dx11, shadermodel5,


texts: Deforming each vertex according to the user in OpenGL

texts:
I am trying to work on a project in OpenGL in which I want to make an animated complex-valued function plotter. Basically, I am trying to do the animation illustrated in the topmost image of this page:

https://en.m.wikipedia.org/wiki/Holomorphic_function

This means that I will need to tranform each vertex of my complex plane, and the way I tranform each vertex depends on the given function. Morevoer, this function is user-defined and is not known to the program.

Now, initially I had thought of passing a function pointer to the vertex shader but I just learned that it cannot be done (Till now, I had only worked in OpenGL 2.0. This is my first Advanced OpenGL project). How else can I do it?


texts: Why do my Box2D bodies occasionally get stuck and separate forcibly?

texts:
I'm making a space game with LibGDX and Box2D. I made a video here to illustrate the issue.

Verbal description: When objects collide, they sometimes get stuck together and are then suddenly separated by a strong force.

Both objects have identical body definitions and fixtures:

bod = new BodyDef();
bod.type       = type;
bod.allowSleep = false;

shape = new CircleShape();
shape.setRadius(values[0]);

fix = new FixtureDef();
fix.restitution = 0f;
fix.friction    = 1f;
fix.shape       = shape;
fix.density     = 1f;

worldBod = world.createBody(bod);
worldBod.setTransform(position.x, position.y, 0);
worldBod.createFixture(fix);

Why might this be happening? How can I fix it?

Update: Here is some more info.

The Player class contains a function update(float deltaTime) with the rest listed below

force.x += (directionVector.x * SPEED)*deltaTime;
force.y += (directionVector.y * SPEED)*deltaTime;

//This helps keep the object in control from preventing forces greater then 3
if(force.x >= 3){
    force.x = 3;
}if(force.x <= -3){
    force.x = -3;
}if(force.y >= 3){
    force.y = 3;
}if(force.y <= -3){
    force.y = -3;
}
//This quickly reduces the force back down to 0
force.x *= 0.5;
force.y *= 0.5;

this.getBody().applyForceToCenter(force, true);

In the render part of the main game class I step the world with

gameWorld.step(Gdx.graphics.getDeltaTime(), 6, 6);
//although increasing or decreasing the itterations seems not to help

and Finally the hexagon's are created using the ShapeRenderer pulling the position and

sr.setProjectionMatrix(camera.combined);
sr.begin(ShapeType.Line);
sr.circle(p1.getBody().getPosition().x, p1.getBody().getPosition().y, 1);
sr.circle(barrierPole.getBody().getPosition().x, barrierPole.getBody().getPosition().y, 1);
sr.end();


texts: How does Unity store references to GameObjects in a scene

texts: A Monobehaviour can have references to GameObjects in the same scene, but Prefabs, ScriptableObjects can't reference GameObjects in a scene. While  Assets, Objects and serialization  covers references to assets, i.e. actual files, it doesn't explain how references to scene objects work. But it has to be some kind of serialization, for example, do they also consist of a GUID part and a local id part when serialized?


texts: How do I project the Earth globe on a flat plane with minimal distortion?

texts:
I want to build a game where the game map is the planet Earth.
The game map needs to be on a 2d plane, with the Earth texture projected on it
If the player walks endelessly in one direction, it should just run laps around the Earth.
I want to split the map in several small tiles and Load on Demand as the player walks

I'm not sure how to best solve this problem. What Map Projection do I use? From my research it seems like most maping apps like Google Maps, or OSM etc use variations of the Mercator Projection. I can't use that because, while the player would be able lap around the earth when walking east, he wouldn't be able to walk north. It won't tile vertically.

Then the Peirce Quincuncial Projection looked promising, it's a perfectly tiled projection. But the problem then becomes distortion is too extreme here. Some places don't look the same. I can live with a tiny bit of distortion, but this is too much.

Then I found another common solution was using a Truncated Icosahedron (probably subdivided into smaller tiles for LoD). This looks like the best alternative so far. But now my problem is I'm not sure exactly how I would work out the algorithm to take tiles from the 3d Icosahedron and tile them side by side on a 2d plane. That would look like this:

How would I stretch it to fill the holes?

Is there some other obvious solution I'm missing? How do games like Pokémon Go do this kind of thing?