title: Writing a server for a multiplayer game

text:
# Question
Title: Writing a server for a multiplayer game
I've been looking on the internet, but I can't really find any good answers to all my questions..

I started to think about writing a little multiplayer game on my own and after thinking and thinking and thinking about how I should begin I came to the conclusion, that implementing the network communication part at first wouldn't be a bad idea since the testing part becomes "easier".

So my first question is:

Is there any library that would make my life easier if I wanted to write the server part in C++?

I just don't know how one would implement the communication between server and client. Imagine a game that is made up of blocks (like minecraft if you want) but the client should only receive a tiny part of that map. So my question at this one is: Would you send raw byte data? Or would you use more abstract formats like XML? Let us assume that this should work with "many" clients as well..

And here is another thing..

Would one use either a single thread that collects all connections and sends requests to specific worker threads or would you create a new thread for every single connection that is established to the server?

# Answer
One library to use is ENet, which implements a generic network API suitable for many games. Or libevent even, which just handles the low-level network events.

There is not a direct need for threads on most platforms, though Windows forces their use for large numbers of clients. Separate threads can be useful when you need a fixed response time or a constant packet send rate, less so for less action-y games.

Send raw bye data, compressed/packed as best you can. It lets clients with worse connections play better, is faster, and keeps your server bandwidth costs down. Some platforms (not yours most likely) have requirements that the game be playable at some low bandwidth like 128kbps, so packing your packets efficiently is a good skill to cultivate. Good game network programmers tend to get hired quickly and paid towards the higher end for game devs, and knowing how to keep bandwidth usage low is part of that skill set. XML is great for a number of reasons, but being small isn't one of them.

Packing mostly comes down to only using as many bits as you need and no more. If all your tiles can be enumerated with 4 bits, pack two tiles per byte. It's a bit more work when things don't line up nicely, but not much. If you use floats, consider writing the code for 16-bit half-precision or custom precision and use that as appropriate (its only a few lines of code - I have a simple template that supports arbitrary mantissa and exponent sizes and optional sign bit that I can also use for half-precision; converting to and from single and double precision is super simple.)

It can be helpful to have a bitstream (vs the usual byte stream) buffer that you can read and write values to.

Actually handling the networking part differs heavily by platform, which is why libevent is useful. Best recommendation there is to not worry deeply about it unless you want to be a pro game network coder. If you so want to learn, your best bet is to just read a lot of books and online docs on hoe each OS's network stack and API works. Making Linux work well is very different than an XBox, for instance.

Only send meaningful changes. If an object is not moving, there is no need to send position. Likewise, if the client he already been sent a chunk if the world and it hadn't changed, don't send it again.

Use some form of Area of Interest filtering to send only relevant things to each client. The client cant see an object 10 miles away, so don't send updates about that object. Just send updates about nearby objects.

As always, read the Gaffer on Games networking articles for a good light introduction to networking games.
> 7 votes

# Answer
To answer your first question, yes there is. In fact there is a lot of libraries available for network programming in C++.

Since you're writing a game already then I'd suggest using the sockets from SFML or maybe even use SFML to create your game.

http://www.sfml-dev.org/tutorials/1.2/network-sockets.php

On the other hand you could always take a look at boost or qt as well.

About the packet usage, always think about speed and peformance. Sending in XML format would require larger packets which would decrease the speed and performance and may/may not create lag.

About threads for the connections. Well as I have already suggested SFML then I'd just referre to the selector they have: http://www.sfml-dev.org/tutorials/1.2/network-selector.php

Also writing both the client and server in the same language would be far the best idea in my opinion, because first of all you can share your code much easier, handling packets will be a lot easier as well, because you could just use the same packet layout over and over. As well cryptography implementation would be way easier. You would also end up doing a lot of double work.
> 2 votes

# Answer
I understand you said you wish for the server to be in c++, but since you tagged Java I will go with that instead as I do not have experience with c++.

Library called Kryonet is designed for games and provides a server and client implementation and can serialize any class and send it across the wire also works on android with LibGDX which for me is a plus.

Transfer of data can be either XML or data if you are going with sending chunks of the map (like minecraft) then the raw chunk file would be best. Updates on the other hand would need a structure to be sent (Note: Kryonet will allow sending of a file and sending of a class which gives you both raw and structured you would need).

As for your other questions, I will let others answer as Kryonet pretty much abstracted a lot of those issue so I yet to encounter them.
> 0 votes

# Answer
Reaching every platform is crucial. Linux and Mac geeks are enthusiastic about games that support them from day one. Speed up your game after you get at least one non windows (Android, Dream, Linux, iOS) version up.

Structure your data in XML, then worry about compressing it to efficient packets, later. In most cases, a generic compression of XML is good enough. If not, optimize the piggy high performance bottlenecks.

C++ is for pros. Consider something friendlier for your first game. A lisp is good. Java is good. CPU speed / compiled code will not be your bottleneck, in 2017. Your network will.

Map out every millisecond of user time, and be very wary of any delay over 400ms for any user action.
> -1 votes

---
Tags: c++, java, multiplayer, server
---


# Question
Title: Can't understand why transformation doesn't work
To make a simple transformation like a rotation I want to use linear algebra -multiplying the `vec4 vertex_position` by a `mat4 transformation`

If `alpha` is the angle of rotation, then the `mat4` is structured like this:

```
|first      |second    |third |forth|
|cos(alpha) |sin(alpha)|0     |0    |
|sin(alpha) |cos(alpha)|0     |0    |
|0          |0         |0     |0    |
|0          |0         |0     |0    |

```

This matrix represents a rotation in the xy plane.

The transformation doesn't work though - can anyone spot my mistake?

# Answer
> 2 votes
Usually you should include more details than just "doesn't work" (symptoms, example input-output, etc), but here the errors are pretty obvious:

* Missing negative sign (for a rotation matrix, your columns should remain orthogonal, so if you took the dot product of the first two columns you should get zero)
* Missing ones in the z & w axes (if you're not rotating those axes, pass them through unchanged. w in particular can cause unexpected behaviour if zeroed out, as it's important to how vertices are translated & projected in 3D rendering)

All told you probably want something more like this:

```
|cos(alpha)   -sin(alpha)   0    0  |
|sin(alpha)    cos(alpha)   0    0  |
|    0             0        1    0  |
|    0             0        0    1  |

```

---
Tags: opengl, android, mathematics, opengl-es, linear-algebra
---


# Question
Title: How much do inconsistencies in update timing matter?
Yesterday I wrote my first game loop with fixed timesteps. It is supposed to run every 50 ms, however it runs at 50-53 ms. Does it matter?

I'm guessing no, but I figured I would ask anyway.

```
startTime = std::chrono::high_resolution_clock::now();

while(running == true){

    updateTime = std::chrono::high_resolution_clock::now();

    deltaTime = std::chrono::duration_cast<std::chrono::milliseconds>(updateTime - lastUpdateTime).count();
    lag += deltaTime;

    eventChecker();
    keyboardManager();

    while(lag >= MS_PER_UPDATE){
        update();
        lastUpdateTime = updateTime;
        //cout << lag << "|";
        lag -= MS_PER_UPDATE;
    }

    render(lag / MS_PER_UPDATE);

}

```

# Answer
Small variation might not seem like much, but it really depends on what you are doing in your loop. To put in persepective, running at 50ms a step gives you 20 steps per second. Running at 53ms a step gives you a bit less than 19 steps per second, so about one lost frame. In the span of a full minute you will loose about 68 frames (or about 3 seconds of game time)

If you were making a game heavily based on timing, this could be noticeable for the player. In an idle game that is meant to be left open in the background, this could result in drift. Some things like physics can also end up giving odd behavior.

HOWEVER, there is a bigger concern. You might want to read this post about update timesteps Right now you are getting that small variation. What will it be like in a month when you add more code to your game loop. If AI runs an A\* algorithm in one, frame or you perform some search in another, those frames will likely not return in the time you are expecting.

Or try running your game on a crummy computer, or one with tasks running in the background.

If timing is important, do NOT, make things depended on your frame rate. The much better solution is to keep track of the time between frames.

For example instead of

x+=3;//Move 3 spaces every step

x+=3\*dt;//move 3\*dt every step.

dt is the time since the last frame. If the game is running slow, dt will be bigger, and things will move further to compensate.

**Edit: milliseconds are typically abbreviated as ms rather than Ms**
> 1 votes

---
Tags: c++, game-loop, fixed-timestep
---


# Question
Title: Why does the Texture from AssetManager displays black rectangles only (LibGDX)?
I loaded and get a texture from assetmanager but whenever I test the app it only shows black rectangles instead of the texture. I tried finding some probable cause for this in my code but I can't find any. Here's my code:

MainGame.java

```
public class MainGame  extends Game {

...
...
@Override
    public void create () {
        EnemyAssets.load();
        EnemyAssets.manager.finishLoading();
        screenWidth = Gdx.graphics.getWidth();
        screenHeight = Gdx.graphics.getHeight();
        camera = new OrthographicCamera();
        camera.setToOrtho(false,screenWidth, screenHeight);
        batch = new SpriteBatch();
}

@Override
    public void render () {

        super.render();
        batch.begin();
        batch.end();
    }

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

```

EnemyAnimation.java: (Here is where I get the asset from AssetsManager)

```
public class EnemyAnimation extends Actor{

    MainGame app;
    LevelOneScreen levelOneScreen;

    private Animation enemyAnimation;
    private static final int  FRAME_COLS_WALK = 10;
    private static final int  FRAME_ROWS_WALK= 1;
    public TextureRegion   currentFrame;
    public float enemyW;
    public float enemyH;
    public float enemyWidth;
    public float enemyHeight;
    private float stateTime = 0f;

    public float enemyX;
    public float enemyY;
    final float delta = Gdx.graphics.getDeltaTime();

    public float enemyXBound;
    public float enemyYBound;

public EnemyAnimation(final MainGame app) {
        this.app = app;
        this.enemyX = enemyX;
        this.enemyY = enemyY;
        Texture enemySprite = EnemyAssets.manager.get("enemySprite.png",Texture.class);
        enemySprite.setFilter(Texture.TextureFilter.MipMapLinearNearest,Texture.TextureFilter.MipMapLinearNearest);

        TextureRegion[][] tmp = TextureRegion.split(enemySprite, (int) enemySprite.getWidth() / FRAME_COLS_WALK, (int) enemySprite.getHeight() / FRAME_ROWS_WALK);
        TextureRegion[] enemyTexRegion = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
        int index = 0 ;
        for (int i = 0; i < FRAME_ROWS_WALK; i++) {
            for (int j = 0; j < FRAME_COLS_WALK; j++) {
                enemyTexRegion[index++] = tmp[i][j];
            }
        }

        enemyAnimation = new Animation(0.044f,enemyTexRegion);
        currentFrame = enemyAnimation.getKeyFrame(stateTime, true);
        enemyW = currentFrame.getRegionWidth();
        enemyH= currentFrame.getRegionHeight();
        enemyXBound = getX();
        enemyYBound = getY();
        enemyWidth = app.screenWidth*0.166667f;
        enemyHeight = enemyWidth *(enemyH/enemyW);

        this.setSize(enemyWidth, enemyHeight);
        this.setBounds(enemyXBound,enemyYBound,enemyWidth,enemyHeight);
        this.isTouchable();

    }

 public void draw(Batch batch, float parentAlpha) {

        super.draw(batch, parentAlpha);

        final float delta = Gdx.graphics.getDeltaTime();

        stateTime += delta;

        TextureRegion currentFrame = enemyAnimation.getKeyFrame(stateTime, true);

        batch.draw(currentFrame,getX(),getY(),enemyWidth,enemyHeight);

    }
}

```

EnemyAssets.java (Here is my AssetsManager)

```
public class EnemyAssets {

    public static final AssetManager manager = new AssetManager();

    public static void load(){
        manager.load("enemySprite.png",Texture.class);
    }
    public static void dispose(){
        manager.dispose();
    }
}

```

LevelOneScreen.java

```
public class LevelOneScreen implements Screen {

    public MainGame app;
    private Stage stage;
    private Stage stageNinja;
    public EnemyAnimation enemyAnimation;
    private float deltaTime = Gdx.graphics.getDeltaTime();

    public Array<EnemyAnimation> enemyAnimate;

public LevelOneScreen(final MainGame app){
    this.app = app;
    this.stage = new Stage(new StretchViewport(app.screenWidth, app.screenHeight, app.camera));
    this.stageNinja = new Stage(new StretchViewport(app.screenWidth, app.screenHeight, app.camera));
    enemyAnimate = new Array<EnemyAnimation>();
    enemyAnimate.add(new EnemyAnimation(app));
    enemyAnimation = new EnemyAnimation(app);
}

@Override
public void show() {

    InputMultiplexer inputMultiplexer = new InputMultiplexer();
    inputMultiplexer.addProcessor(stage);
    inputMultiplexer.addProcessor(stageNinja);
    Gdx.input.setInputProcessor(inputMultiplexer);

    enemyAct1();

}

public void enemyAct1(){

    for(int i = 1; i < 6; i++){enemyAnimate.add(new EnemyAnimation(app));}

    enemyAnimate.get(1).setPosition(app.screenWidth*0.1f,app.screenHeight);

    stageNinja.addActor(enemyAnimate.get(1));
        enemyAnimate.get(1).addAction(moveTo(app.screenWidth*0.1f,enemyDestination,enemyTimeDrop1));

    enemyAnimate.get(2).setPosition(app.screenWidth*0.1f+enemyAnimation.enemyWidth,app.screenHeight+enemyAnimation.enemyHeight);
        stageNinja.addActor(enemyAnimate.get(2));
   enemyAnimate.get(2).addAction(moveTo(app.screenWidth*0.1f+enemyAnimation.enemyWidth,enemyDestination,enemyTimeDrop2));

    enemyAnimate.get(3).setPosition(app.screenWidth*0.1f+enemyAnimation.enemyWidth*2f,app.    stageNinja.addActor(enemyAnimate.get(3)); enemyAnimate.get(3).addAction(moveTo(app.screenWidth*0.1f+enemyAnimation.enemyWidth*2f,enemyDestination,enemyTimeDrop3));

}

@Override
public void render(float delta) {

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

    update(delta);
}

public void update(float deltaTime){

    stage.draw();
    stageNinja.draw();

    stage.act(deltaTime);
    stageNinja.act(deltaTime);

    app.batch.begin();
    app.batch.end();

}

@Override
public void resize(int width, int height) {
    app.camera.setToOrtho(false, app.screenWidth, app.screenHeight);
    app.camera.update();
    stage.getViewport().setScreenSize(app.screenWidth, app.screenHeight);
    stageNinja.getViewport().setScreenSize(app.screenWidth, app.screenHeight);
}

    @Override
    public void dispose() {
        stage.dispose();
        stageNinja.dispose();

    }
}

```

# Answer
> 0 votes
You are loading `enemySprite.png`

```
manager.load("enemySprite.png",Texture.class);

```

but then trying to get `enemy128.png` instead

```
Texture enemySprite = EnemyAssets.manager.get("enemy128.png",Texture.class);

```

---
Tags: android, libgdx, animation, asset-management, android-studio
---


# Question
Title: How to create UI with multiple panels for multiple resolutions
I am trying to create scene that has multiple panels, but only one is visible. When user clicks on appropriate button a transition is happening: camera moves to the right revealing panel on the right or it moves down revealing panel that is down.

My first attempt was to have some C# script/controller that will change position of all three panels at the same time using `Vector.lerp`, however, problem that I see is multiple resolution. If I have resolution other than 480x800, panels overlap and I can't make transitions right (for example, to move right I move all three panels on the x-axis by -480).

How would I do this?

# Answer
The way I would approach it would be to set up a canvas to 'Scale with Screen Size' using Unitys Canvas Scaler, set the reference resolution to the size of your primary target device, and then add 3 Panel as children of the canvas. Use the anchors in the Rect-Tranform section of the Inspector to set each Panel to stretch the full height and width of the Canvas. Position the starting panel inside the canvas, and the other panels to the right and below the canvas as you illustrated in the picture provided above.

Whenever the end users screen size is larger or smaller than your target display, the 'Scale with Screen Size' option will scale the canvas up or down appropriately, along with all of it's child UI objects (the panels being the primary point of interest in your case). Basically the panels will always be the full size of the screen regardless of the end users screen resolution. You might want to take a look through Unity's guide on Designing for Multiple Resolutions for more details.

In regards to moving the panels I would be inclined to use an Animator Controller to create the screen transitions, you can read through the documentation on this approach here, but there's also a tutorial here with a demo displayed in web player, you're mainly interested in the sliding settings menu which is in part 2, but look through part 1 first to get the necessary background. You could also achieve this by adjusting the panels position with a Lerp in a script which sounds like what you've attempted, but I think the using an Animation Controller would be a simpler approach.

Based on the description of your problem and the picture provided I think you only really need to move two panels at a time, the active one and the one you wish to transition to, but that's a design choice for you to make.

There's a Live Training video series from Unity that takes an in depth look at their UI system, which might be worth taking a look at too.
> 1 votes

---
Tags: unity, c#, gui, ui-design, scene
---


# Question
Title: How would I access a method from another script?
I have two scripts. I create a reference to my instance of `SoulManagement` from `Soul`, but I can not access it's method, and I can not figure out why. Why can't I access my method?

---

### `SoulManagement`

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

public class SoulManagement : MonoBehaviour
{
    int Souls;

    void SoulPlusMinus(int SoulValue)
    {
        Souls += SoulValue;
    }
}

```

### `Soul`

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

public class Soul : MonoBehaviour
{
    public SoulManagement soulmanager;
    public int SoulValue;

    void Start()
    {
        soulmanager = FindObjectOfType<SoulManagement> ();
    }
    void OnTriggerStay2D()
    {
        soulmanager.SoulPlusMinus (SoulValue);
    }
}

```

# Answer
## Making Methods Accessible

When we create methods, we often must explicitly state the *accessibility*. A `private` method can only be accessed from within the class1, while a `public` method can be accessed from *outside* of the class. If you do not specify the accessibility, this will default to `private`. If you later deal with *inheritancy*, it is worth noting that a `protected` method will remain *private*, while still allowing access to classes that derive from that class.

In this case, we have a method signature of `void SoulPlusMinus(int SoulValue)`. From the provided example, you *want* to use ***`public`***`void SoulPlusMinus(int SoulValue)`.

---

### Easy Access for Management Classes

With a name like `SoulManagement`, we can infer that this class manages your `Soul` classes. Classes like this are often designed in a way that only *one* instance should be running. In other words, you would not have *many* soul managers; you would only have *one*.

If this description fits your intended functionality, creating a *singleton* pattern may provide additional benefit, and extend your access to the class methods. A singleton pattern helps assure that we retain the one instance of the class, and by creating a static self-reference, we can then make that class accessible from *anywhere*. You can read more on singleton patterns over at Stack Overflow Documentation.

---

This is your `SoulManagement` class as a singleton variation:

```
public class SoulManagement : MonoBehaviour
{
    ///<summary>Self-reference should always point to our active instance.</summary>
    public static SoulManagement instance;

    void Awake()
    {
        // If we do not currently have a SoulManagement instance,
        if(instance == null)
        {
            // This is our SoulManagement instance; link the instance reference.
            instance = this;
        }
        else if(instance != this)
        {
            // If we DO have an instance reference, and it is NOT this instance,
            // We already have a SoulManagement class; destroy this instance.
            Destroy(gameObject);
        }
    }

    int Souls;

    public void SoulPlusMinus(int SoulValue)
    {
        Souls += SoulValue;
    }
}

```

Using this approach, you can simply call `SoulManagement.instance.SoulPlusMinus()` from *anywhere*, without having to set up a direct reference to the instance.
> 1 votes

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


title: Touchable Hud with Actors in Libgdx

text:
# Question
Title: Touchable Hud with Actors in Libgdx
I am writing a Tower Defense for Android. Right now my LevelScreen contains a Background-Actor which is pan-able and some zones to buy Towers - after buying them you can upgrade them further. When you click a Zone or a Tower, a small overlay on the bottom appears (another actor) - click it to buy. My main Problem was that the overlay stayed where you clicked and didn't move when you pan the Screen. I solved this by changing the overlay's draw method to

```
batch.setProjectionMatrix(game.batch.getProjectionMatrix());
batch.draw(texture,actorX,actorY);
batch.setProjectionMatrix(levelScreen.stage.getCamera().combined);

```

I set it backwards for further Actors who should stay where they are - Towers for example - but I kinda don't know what I am really doing.

I am now only able to fire the touchDown Event on these actors when I pan to the bottom left of the Screen and click where the Actor's Icon is.

I tried a few things:

-Adding another Stage as a HUD(I couldn't Access the lower stage anymore or the other way around)

-Moving the actor.x and actor.y along (I was unable to even find where the actor went)

-Adding another camera (led to nothing)

-Updating the actors Position using

```
stage.getCamera().unproject(myPoint)

```

(same as when I tried to move the actor)

So, which is a good way to implement what I look for? Basically, TL;DR: I am looking for a way of letting some Actors stay relative to Screen while moving some Actors with the world while panning around.

I am pretty sure there a similar questions but None of them really helped me and I have restricted Internet-Access (for example I can't Access badlogicgames.com).

# Answer
> 1 votes
> Adding another Stage as a HUD(I couldn't Access the lower stage anymore or the other way around)

It's the solution i'm using, and for me it's working fine. Assuming that by "couldn't access" you meant you couldn't handle input, you have to know there is a solution for this : InputMultiplexer.

It allows you to handle event for multiples scenes and/or input processors.

**Code Example :**

```
Stage scene;
Stage hud;
...
InputMultiplexer multiplexer = new InputMultiplexer();
multiplexer.addProcessor(hud);
multiplexer.addProcessor(scene);
Gdx.input.setInputProcessor(multiplexer);

```

# Answer
> 0 votes
Yes, you need two stages, one of the UI and one for the game. You can find a code sample here on LibGDX.info:

https://libgdx.info/multiplexing/

Hope it helps!

---
Tags: android, libgdx, hud
---


title: Map Engine Rendering Broken

text:
# Question
Title: Map Engine Rendering Broken
So I've been making my own tile map engine in LibGDX as the one currently implemented doesn't support collision detection with scaling. So I've come up with my own Layer and Map class and a drawing function for the map. Currently this is what it produces:

Here's the rendering code:

```
public void draw(SpriteBatch batch) {
    for(Layer layer : layers) {
        for(int x = 0; x < layer.getTileMap().length; x++) {
            for(int y = 0; y < layer.getTileMap()[x].length; y++) {
                batch.draw(layer.getTiles()[layer.getTileMap()[x][y]],
                        xOffset + (x * ((layer.getTileWidth() * scale))), yOffset + (y * ((layer.getTileHeight() * scale))),
                        (layer.getTileWidth() * scale), (layer.getTileHeight() * scale));
            }
        }
    }
}

```

EDIT: Yes, I'm aware the map looks weird, it's just random textures thrown in from a tile-sheet.

# Answer
Here's the new rendering code:

```
public void draw(SpriteBatch batch) {
    for(Layer layer : layers) {
        for(int y = 0; y < layer.getTileMap().length; y++) {
            for(int x = 0; x < layer.getTileMap()[y].length; x++) {
                batch.draw(layer.getTiles()[layer.getTileMap()[x][y]],
                        xOffset + (x * ((layer.getTileWidth() * scale))), yOffset + (y * ((layer.getTileHeight() * scale))),
                        (layer.getTileWidth() * scale), (layer.getTileHeight() * scale));
            }
        }
    }
}

```

The `x` and `y` simply needed to be switched.
> 0 votes

---
Tags: opengl, libgdx, tiles, tilemap, maps
---


# Question
Title: D3DX11CompileFromFile() function problem DirectX11
What do i have to include to use the `D3DX11CompileFromFile()` function on DirectX11? I'm using visual studio 2015 and reading the "3D Game programming guide" (Frank Luna) and i'm having problem using that function, any solutions? I read online that is not usable anymore and that now i have to use the `D3DCompileFromFile()` function, but i have no idea how to do it

# Answer
> 1 votes
`D3DX11async.h`, according to the documentation. Note that the documentation also specifies the function is deprecated in Windows 8, and entirely usable in Windows store applications, and that may be why you are having trouble.

You should use `D3DCompileFromFile` instead, as you've read on the internet. It's parameters are nearly identical to the set of parameters to `D3DX11CompileFromFile`, so with very few modifications you should be able to simply replace one with the other.

---
Tags: directx, directx11, c++
---


# Question
Title: There is no valid constructor to convert from (const float*) to DirectX::XMFLOAT4
I'm following the "3D game programming with DirectX 11" book (Frank Luna) and i'm having this issue. There is no valid constructor to convert from (const float\*) to DirectX::XMFLOAT4

```
namespace Colors {

    XMGLOBALCONST XMVECTORF32 White = { 1.0f, 1.0f, 1.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Black = { 0.0f, 0.0f, 0.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Red = { 1.0f, 0.0f, 0.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Green = { 0.0f, 1.0f, 0.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Blue = { 0.0f, 0.0f, 1.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Yellow = { 1.0f, 1.0f, 0.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Cyan = { 0.0f, 1.0f, 1.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Magenta = { 1.0f, 0.0f, 1.0f, 1.0f };

    XMGLOBALCONST XMVECTORF32 Silver = { 0.75f, 0.75f, 0.75f, 1.0f };
    XMGLOBALCONST XMVECTORF32 LightSteelBlue = { 0.69f, 0.77f, 0.87f, 1.0f };
}

```

The error is here

```
Vertex vertices[] = {
    { XMFLOAT3(-1.0f, -1.0f, -1.0f), (const float*)&Colors::White },
    {XMFLOAT3(-1.0f, +1.0f, -1.0f), (const float*)&Colors::Black },
    {XMFLOAT3(+1.0f, +1.0f, -1.0f), (const float*)&Colors::Red },
    {XMFLOAT3(+1.0f, -1.0f, -1.0f), (const float*)&Colors::Green},
    {XMFLOAT3(-1.0f, -1.0f, +1.0f), (const float*)&Colors::Blue},
    {XMFLOAT3 (-1.0f, +1.0f, +1.0f), (const float*)&Colors::Yellow},
    {XMFLOAT3 (+1.0f, +1.0f, +1.0f), (const float*)&Colors::Cyan},
    {XMFLOAT3 (+1.0f, -1.0f, +1.0f), (const float*)&Colors::Magenta}
};

```

and this is the struct Vertex

```
struct Vertex {
        XMFLOAT3 Pos; XMFLOAT4 Color;
    };

```

# Answer
`XMFLOAT4` only has a constructor taking a `const float*` when the compiler is compiling the file as C++. If the constructor isn't visible, the TU being compiled when the error is generated may not be compiled as C++.

It's also possible you have a version of the header where the constructor is marked explicit, which means you'll need to explicitly specify that you are invoking it: `XMVECTOR4((const float*)&Colors::Red)` for example.

Without further information it's really impossible to say more.
> 1 votes

---
Tags: directx11, c++
---


# Question
Title: Performance of manipulating a mesh in realtime
Does Unity allow **streaming mesh data** that can be continuously changed?

I have a level that is dynamically changing based on some parameters. The number of triangles stays the same, they just change positions.

I'm speaking of around **2000 triangles** that need their position updated each frame (they follow a spline that is computed on CPU), running on mobile phones.

I can't use a `TrailRenderer` because the object is a whole level. I can't use bones, because I need to know the final position for each vertex for my custom collision code.

The mesh should be marked `Mesh.MarkDynamic`.

# Answer
> 10 votes
Yes, you can change a mesh at runtime.

1. get the current mesh from your object using `Mesh mesh = GetComponent<MeshFilter>().mesh`. Alternatively, if you want to replace the mesh with a completely new one, create one with `Mesh mesh = new Mesh();` and assign it to your object with `GetComponent<MeshFilter>().mesh = mesh;`
2. When you intend to modify the same mesh every frame, you should call the `MarkDynamic()` method on it. This might improve performance in that situation (thanks, Kroltan).
3. Modify the `Mesh` object. It is a reference-type, so any changes you make will be reflected by the object which owns the mesh. For a minimum functional mesh you need to set at least its `.vertices` and `.triangles` component, if you want it to be textured also the `uv` component. If you are really just going to change the positions of vertices of an existing mesh, then the `.vertices` property is likely the only one you need. But keep in mind that you have little control over the order in which your 3d modeling program saves the vertices of a 3d model, so a slight change to the model can mean that the indexes of all vertices change in a completely unpredictable way.
4. When you are finished, call `mesh.RecalculateNormals()` which is required by almost every shader to calculate brightness levels correctly.
5. Calling `mesh.RecalculateTangents()` is also required for some shaders, especially those which use bump mapping. This step depends on the normals, so it needs to be executed after you recalculated the normals.
6. You should also call `mesh.RecalculateBounds()`. This is required for reliably detecting if the mesh is off-screen (so it can be culled) and for collision detection if you are using it as a MeshCollider. This method actually gets called automatically when you set the .triangles, but not when you set the .vertices.

Will it be fast enough for mobile phones? That depends on countless factors, like what kind of mobile phone you are talking about, how often you are going to change the mesh, how effective your mesh changing algorithm is, what shaders you are using and much more. You need to test it for yourself. By the way, if your changes will usually be localized, it might help to break down your terrain into multiple sub-objects and only update the meshes of those which were affected.

# Answer
> 4 votes
As Philipp said, you *can* change the mesh at runtime. You might have performance issues though (it's not "streaming" at all); in particular `RecalculateNormals` will probably be quite long.

If you're willing to accept the maintenance burden, another possibility is to compute the vertices position directly in the vertex shader. Since you have custom collision code, you'll have to compute 2 versions : one on the CPU, one on the GPU.

If you plan to use a MeshCollider, this idea is useless (it needs a Mesh anyway).

EDIT : I completely forgot about Mesh.MarkDynamic. This is definitely the way to go. I'll leave my answer just in case, though.

---
Tags: unity, 3d-meshes, realtime, dynamic-mesh
---


title: Client side prediction physics

text:
# Question
Title: Client side prediction physics
I'm trying to build a simple networked game and I'm having trouble keeping a jump in-sync on the client and server.

I've read the free gaffer on games articles and it's helped somewhat but I'm still not completing grasping the theory behind how to keep physics in sync.

Right now I have a character that can move right and left. This is kept in sync perfectly by sending all of the inputs and then relaying them to the clients.

For the jump command..

```
- I send a packet indicating that i'm jumping.
- The client then predicts the jump
- The server begins to simulate the jump and tells the other clients that client X is jumping
- that then gets simulated on their clients

```

The issue is that if I keep on jumping on the spot eventually the jumps will begin to overlap. I came up with some makeshift solutions to that, but realized that if I started moving and jumping at the same time it wasn't simulating everything perfectly and sometimes the player would land on the tip of a platform on one client and miss it on the server/other client.

Right now everything is being done locally so there's virtually no lag. I figured the reason it's becoming out of sync is because of jitter.

I'm just a little confused in figuring out how to fix this. How do I get it so the client side prediction is 100% perfect in a local environment when incorporating physics?

# Answer
> 7 votes
Client-side prediction depends very heavily on a deterministic physics model that **exactly** replicates the way the game object behaves on both the client and the server. Even small floating point errors, differing random seeds, or slight differences in time if your time step is not fixed can cause very different results. These results can then rapidly diverge or cause game-breaking bugs (such as the player landing on the platform on one client and not others).

I suspect that is occurring here. While I can't give you an exact solution without seeing the way you've written your code I can offer some advice based on my own experience writing movement and physics using client-side prediction.

First, our research:

I also used Gaffer on Games as a source as well as the Source Multiplayer Networking article and Gabriel Gambetta's Fast-Paced Multiplayer series. While Gaffer on Games covers these concepts very well I found Gambetta's explanation simpler and easier to follow when I was first learning the concepts and I found Valve's article great to help connect the concepts to a live game application. They may help you similarly as well.

Second, your comments about your own simulation:

> For the jump command..
>
> > * I send a packet indicating that i'm jumping.
> > * The client then predicts the jump
> > * The server begins to simulate the jump and tells the other clients that client X is jumping
> > * that then gets simulated on their clients

You did not mention it in that quote, so just in case: you should be doing client-side reconciliation when the results of the server return back to that game object's controlling client. This is described very well in the Gabriel Gambetta series however a quick rundown of this approach is as follows:

1. What you listed above occurs with two differences: 1) each input is sent to the server with some unique id; common ones include the time at the moment or an incrementing integer id. 2) the inputs are stored along with that id in a queue to be used later.
2. When the server updates the controlling client on the game state, the id of the last input processed server-side is sent back with it.
3. The client sets the new game state (anything the server says is absolute).
4. The client then looks at the queue of inputs and the 'last input id' sent from the server and drops any inputs with an id less than or equal to that returned by the server.
5. All the inputs left in the queue are re-simulated all at once back to the present to ensure that the client-side prediction is an accurate as possible.

It should be noted, this process only happens on the controlling client because the other clients do not have the past input information.

> The issue is that if I keep on jumping on the spot eventually the jumps will begin to overlap. I came up with some makeshift solutions to that, but realized that if I started moving and jumping at the same time it wasn't simulating everything perfectly and sometimes the player would land on the tip of a platform on one client and miss it on the server/other client.

Rather than sending a packet indicating you're moving, a packet indicating you're jumping, and so on, a common approach to sending input to the server is to bundle up all the input for all used buttons into one single packet. This is sending the state of all game relevant keys to the server. The server then has a packet containing all the inputs values as they were seen at the point of update/prediction on the client which it should be able to use to re-simulate the frame exactly as it was on the client.

> Right now everything is being done locally so there's virtually no lag. I figured the reason it's becoming out of sync is because of jitter.
>
> I'm just a little confused in figuring out how to fix this. How do I get it so the client side prediction is 100% perfect in a local environment when incorporating physics?

Some latency & jitter alone should not cause the issues that you're seeing with sync from my experience. The client-side prediction model is designed to make the simulation appear smooth and non-laggy regardless of fluctuating network conditions. A part of that is keeping the client and server in sync despite these conditions.

If I'm understanding correctly, then in your current model, It's possible out of sync errors could happen in this case for example:

1. Client starts moving and jumps at the same time.
2. Packet containing the movement input is sent to the server.
3. Packet containing the jump command is sent to the server but experiences a delay.
4. Server starts processing the movement but because the jump packet did not arrive on time, some movement has already occurred before the server computes the jump putting the client and server out of sync.

So, bundling up all of your input into one packet to send to the server rather than sending a packet for jumping separate from movement should solve the largest part of your out of sync issue since the server will be able to simulate an entire frame from **exactly** the same input state the client would have simulated it.

Next would be to look into implementing client-side reconciliation to reduce potential errors in the prediction code and thus warping of your character. This will be important once you are running your server on a remote box and latency begins to come into play since some inputs will occur before the server gets back to you, hence why you want to replay the ones the server hasn't processed.

Also, reviewing your code and ensuring that the update loops are happening **exactly** the same on client and server may help you identify some issues.

For example, in my own project I ran into a situation once I implemented collision where I was handling outstanding packets slightly differently on client and server (all at once in one tick, as opposed to one per tick) which worked perfectly for movement but caused my collision to rapidly become out of sync since the detection occurred after all movement was applied.

# Answer
> 0 votes
in my opinion

```
- I send a packet indicating that i'm jumping and wait for next packet .
-
- The server begins to simulate the jump and tells all clients ( including me ) that
  client X is jumping with current state , coordinate , and direction
  ( example 25% of jump with coordinate Y = 10 direction south , or maybe
  50% of jump with coordinate Y = 20 direction south , ect.. )
-
- that then gets simulated at my device & other client device based at jumping state
-
- The state is increased each time new packet is send (0.1% , 0.5% , 1% , 5% .... 100% )

-
- if other client / me is lagging , the player will stop ( in mid air) and wait for
  the next packet
-
- If after a few second not receive packet , the device start showing signal picture
  ( or anything like that )
-
- If other client / me simulated that current jump state is 10% but received packet from
  server that the jumping state is 90% , the device will position the player at 90% state

```

---
Tags: physics, networking, server, movement-prediction, client
---


# Question
Title: Two reflective surfaces facing each other in openGL
How do I render 2 reflective surfaces, Example a mirror, face each other? To render a single surface I would use a cube map by rendering from the object on six directions.

But to render 2 surfaces it is becoming a paradox on which one to render first! Can anyone gimme a spark?

https://learnopengl.com/#!Advanced-OpenGL/Cubemaps

I used this tutorial

# Answer
> 3 votes
There aren't many options for this:

1. Use the previous frame's rendering result in a feed-back loop, initialize with black, or transparent, or a fake reflection texture
2. Same as 1 but render a few extra times quickly within 1 frame to reduce reflection lag
3. Use pure ray-tracing with a limit on ray bounces

Number 3 is impractical in most situations.

---
Tags: opengl, cubemap
---


# Question
Title: Unity Vertex shader recalculate renderer bounds
I've made a simple billboard gpu instancing vertex shader that manipulates the verticies of an object based on the projection matrix. The problem is that the renderer bounds does not update to encapsulate the object. If the objects render bounds goes out of view the objects dissapears because of frustrum culling, is there a way to recalculate the render bounds after manipulating the verticies or manually manipulate the bounds to be the maximum size that the object that be.

# Answer
> 0 votes
You can't recalculate the bounds in the vertex shader itself (culling happens before we've even decided to send those vertices to the GPU), but we can manually set the bounds in a C# script:

```
// Note: this copies the mesh, to avoid changes rippling out and affecting
// all instances of it, including the asset in your project folder.
// If you're sure you already have a unique mesh, you can use .sharedMesh
// to avoid creating a copy.
Mesh mesh = GetComponent<MeshFilter>().mesh;
mesh.bounds = new Bounds(center, size);

```

As you say, if you set up these bounds to encapsulate the maximum volume any of your vertices might occupy, then it won't be frustum culled as long as any part of that zone is within the camera's frustum.

---
Tags: unity, shaders, bounding-boxes, cg, vertex-shader
---


title: Identify shading language in Trove

text:
# Question
Title: Identify shading language in Trove
I'm playing this voxel game named Trove, running it in DirectX, their requirements are DirectX 10 and OpenGL 3.2

The character entity in this game emits light when it gets close to any surfaces (walls, floor, etc). I am assuming that they codded that into these shaders unified files.

I want to put this light on like the smallest value or remove it completely as a personal mod for myself. (the game is very modable, another guy edited these files are moved the glare and the fog, I am interested in doing that too, since a patch came and broke his mod)

So, I was wondering what shading language is that, so that I can look up and learn the right thing to make this work in the end.

This game is free to play on steam.

I've extracted the game files and they have this folder called **shadersunified** and I've uploaded all the content at indexed shadersunified folder

I am completely new to this kind of modding, I have absolutely no knowledge, but I do know programming like C++, C#, Pawn, Java, Javascript.

I need some directions toward what this game uses so that I know what to look into :D . Or if any of you can do these changes, I would love that even more.

# Answer
I can't comment since I don't have enough rep yet.

As UnholySheep said in the comments to your question, looking at the .common files you can find out that this is indeed a custom shader language. Specifically './programs/common/kdefines.common' indicates this.

The file I mentioned defines their custom types and functions as the relevant type/function in either HLSL or GLSL, whichever is being used on the target platform.

Since you say that you're new to this:

If you want to mod the shaders for Trove you will be safe to use the same syntax and style that they've used in their own shaders, however it would be helpful to you to research and have knowledge in both HLSL and GLSL. This is to ensure that your shaders work entirely as you expect when writing them since there is no guarantee that whoever defined this custom language defined it to *exactly* match the specifications of both HLSL and GLSL (depending on the use cases, requirements, etc).
> 3 votes

---
Tags: glsl, hlsl, cg, shading
---


title: Map not loading from text file

text:
# Question
Title: Map not loading from text file
Ok, so I have a text file filled with 0s and 1s. When there are 1s, I want the code to add a block to the block array. For some reason it is not reading it right at all.

World.java:

```
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.*;

class World {
    Image ground;
    Block[] blocks;
    int mapWidth = 40;
    int mapHeight = 22;

    void setWorld(String map) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(map));
            String line;
            int enc = -1;
            int x = 0;
            int y = 0;
            while ((line = br.readLine()) != null) {
                String values[] = line.split(" ");
                for (String str : values) {
                    int str_int = Integer.parseInt(str);
                    if (str_int == 1) {
                        enc++;
                        System.out.println("x: " + x + ", y: " + y);
                        //blocks[enc] = new Block(x * 32, y * 32, 32, 32, 1);
                    }
                    y++;
                }
                x++;
            }

        } catch (Exception e) { e.printStackTrace(); }
        System.out.println("hi");
    }
}

```

# Answer
> -1 votes
I fixed it.

I swapped the `x` and the `y` increments, and set `x` to `0` when I incremented `y`. I also use a list to store the blocks, instead of an array.

---
Tags: tilemap
---


# Question
Title: Why does my Unity Android export fail with "No resource identifier found"?
When I try to export my Unity game to Android, I get this error:

> CommandInvokationFailure: Failed to re-package resources. See the Console for details.
>
> AndroidManifest.xml:4: error: No resource identifier found for attribute 'isGame' in package 'android'
>
> AndroidManifest.xml:4: error: No resource identifier found for attribute 'banner' in package 'android'

What could cause this?

# Answer
> 1 votes
The reported error commonly derives from not having your Android SDK up to date. This has been confirmed at Unity Answers and Stack Overflow.

Updating your Android SDK to *at least* API level 21 (also known as Lollipop) should fix your problem. Regardless, it is a good idea to ensure you have the *latest* version of the Android SDK.

Further confirmation at Unity Answers implies that Unity *should* have detected this problem, and automatically attempted to upgrade your SDK. The fact that it *does not* implies the presence of a bug, which you may consider reporting

---

Contrary to the other answer, you ***do not*** need to specifically target the API, in your build. `isGame` and `banner` are both members of the application declaration. The application declaration has an API *requirement* of API Level 1 - it has always been there.

As such, versions that pre-date Lollipop will not freak out over newer inclusions; they just wont use them.

# Answer
> 0 votes
You need to build against **API level 21** or higher. If using Ant, then edit **project.properties** and use:

```
target=android-21

```

---
Tags: unity, android
---


# Question
Title: When should iOS gamecenter authentication be called?
I'm integrating GameCenter leaderboards into my iOS game. The game has a home screen with a play and "High Scores" button, the game screen itself, and a finished screen with you score, another "High Scores" button, and some other stuff.

When installing the GameCenter package it recommended that you call the authentication function as soon as the device is ready. In this case, if a user that is logged into GameCenter opens the app it immediately says "Welcome back XX" and the player can continue like normal. However, if a user is not logged in, as soon as they open the app they are greeted with the GameCenter login page, which to me is a bad user experience.

The alternative is to only do the initial authorization when the user clicks to see the high scores, if they are logged in it takes them to the leaderboard, if not it prompts them to log in. The problem with this is if they don't try to view high scores until the game is over it would not have saved their score to the leaderboard (as I have it automatically submit if logged in on Game Over).

Which of these two choices is the best? I don't see the first option occur too often as I'm rarely/never greeted with a GameCenter login as I enter a game. Although number 1 is recommended by the plugin I installed. Should I have a dedicated "Sign in" button?

# Answer
> 1 votes
You should go with the recommended method of authenticating as soon as possible.

The annoyance of not being logged in is not as big as you think it is. Authentication is persistent across games. This means, your customer is likely to be signed in already using another unrelated game.

From the documentation:

*Because a player stays authenticated until they explicitly sign out of Game Center, it is quite common that an authenticated player is already on the device.*

---
Tags: ios, user-experience, game-center
---


title: What pattern is used to render tiles?

text:
# Question
Title: What pattern is used to render tiles?
I want to render a tile-based map and I am not sure which class structure to use to keep logic and rendering separeted.

My class structure so far on the logic side: One abstract parent `class Tile` with an attribute `int tileType` and one class extending Tile for every kind of tile. Every of the extending class defines the value, for example in the `class Tree extends Tile` I have `tileType = 2` and in the `class Wall extends Tile` I have `tileType = 3`.

When I render a map, I go through the array of tiles and do something like this:

```
switch (tileType) {
...
case 2: texture = treeTexture; break;
case 3: texture = wallTexture; break;
...
}
draw(texture, x, y);

```

I wonder if the class structure makes sense and if this is a good solution to render tiles? Or what other solutions are there to render tiled maps while keeping logic and rendering separated?

# Answer
The way i am doing this kind of job is :

```
class Tile
{
public:
    enum Type
    {
        Water,//0
        Grass,//1
        Snow,//2
        Sand//3
    };
    enum Type2// secondary type
    {
        Mountain,
        Forrest,
        None
    };
public:
    Tile(std::shared_ptr<Surface> surf, int x, int y, int width , int height,Type type);
    void Draw(int x , int y ,Graphics& gfx);
    void InitLayout2(std::shared_ptr<Surface> surf, Type2 type);
private:
    std::shared_ptr<Surface> m_terrain;
    std::shared_ptr<Surface> m_terrain2;
    Type m_type;
    Type2 m_type2;
    RectI m_rect;
    bool m_Passable;
};

```

then map owns all tiles std::vector m\_tiles; and the way i am setting this vector is i am using map.png file , then read each of a pixel call function : `Tile::Type CheckTyle(Color c);` witch return me what type of tile it is then switch return value and assign tile with a pointer to surface
> 1 votes

# Answer
The best way I can think to eliminate the coupling between tiles and the rendering system is to pass whatever structure holds the map data to the rendering system.

**The simple answer** is, somewhere, something has to be coupled. I agree having your tiles or your map draw themselves directly is a maintainability nightmare in the long run. Even giving the rendering system an overload function, draw() which can take a world or map object and digest it to make each draw call based on type, direction, etc.

**The real answer** is you also need to decouple the rendering system from the map and tiles which it needs to draw. To do so is simple, but important as it pushes the non-graphic jobs out of your logical tile object and will also push the logical map parsing code out of your rendering system... You need a world object, and a matching system which is intimate with tiles and worlds. This being tiles only real dependency can split data up into blocks that other systems can parse. So, get image from tile type becomes a world job, then you pass that returned image object to the renderer.. This gives everything a nice engine layer to rest on, while keeping everything simple.
> 1 votes

---
Tags: architecture, rendering, data-structure
---


title: Only 4 point lights display in unity

text:
# Question
Title: Only 4 point lights display in unity
When ever I have more than 4 point lights in my scene, only 4 show up. Why does it do that? Is there anything I can do to show more than 4 at a time?

# Answer
> 2 votes
Rendering lights is very GPU-costly operation. Forward rendering in particular.

You can increase the amount of lights Unity will render from the quality settings. If you are using a lot of dynamic lights in your game, you might want to consider switching to deferred lighting to make rendering lights a bit more optimized. If you are using static lights and objects, consider enabling light map baking.

---
Tags: unity, lighting
---


# Question
Title: Unity Raw Image ui not showing when small
I have some Images online that I download using `WWW` class and the use as UI elements.
So far all of them where working perfectly but now the one I added recently is acting up.
First you should know that all of the images are being downloaded by the same script and handled by that so there should be no difference between their materials and stuff AFAIK (if I'm missing something please tell me).
Second , the problem is that this particular image only shows up when it's taking more than one sixth of the screen, for example if I make it bigger by changing it's size in the inspector, or if I go to scene view and zoom in on it, it starts to fade in the larger it gets on the screen.
Also, I changed the picture to something that was working properly to make sure it's not from the image.

```

    public IEnumerator AddTools(Tool Tool)
    {
        Texture2D T = new Texture2D(4, 4, TextureFormat.DXT1, true);
        SpriteTool ST = new SpriteTool();
        ST.TheTool = new UnityEngine.Texture();
        ST.ID = Tool.ID;
        ST.ToolName = Tool.Name;
        ST.Type = Tool.Type;
        WWW wWw = new WWW(Tool.Url);
        while (!wWw.isDone)
        {
            yield return wWw.progress;
        }
        wWw.LoadImageIntoTexture(T);
        ST.TheTool = T;
        ST.TheTool.name = Tool.Name;
        SpriteTool PA = ObjectTools.SingleOrDefault(p => p.ID == ST.ID);
    }

```

The SpriteTool Type is a class I made for storing some of the information needed to build the UI element later.

```

    private GameObject CreateButton(SpriteTool item = null, float angle = 0)
    {
        Texture2D T2D = (Texture2D)item.TheTool;
        T2D.SetPixels(T2D.GetPixels(0, 0, T2D.width, T2D.height));
        T2D.Apply();
        GameObject Tool = new GameObject();
        Tool.transform.SetParent(GUICanvas.transform);
        //There was some code for positioning the element and resizing it that I
        //did not include but I can see in the scene view that the size and the position
        //are what they supposed to be so that's not the problem
        Tool.AddComponent();//The type is RawImage
        Tool.GetComponent().texture = T2D;//the type is RawImage
     }

```

# Answer
> 1 votes
Disappearing texture when scaled down sounds awfully lot like missing mip-levels. You probably need to generate mipmaps for the loaded texture on runtime. This is done by calling `Texture2D.Apply()` on your texture.

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Start() {
        Texture2D texture = new Texture2D(128, 128);

        // Generate white texture
        for (int y = 0; y < texture.height; y++) {
            for (int x = 0; x < texture.width; x++) {
                texture.SetPixel(x, y, Color.white);
            }
        }

        texture.Apply(); // Generate mipmaps
    }
}

```

If using just the `Apply()` method does not work for your texture loaded with the WWW class, you need to use a little hack:

```
texture.SetPixels( texture.GetPixels(0,0,texture.width,texture.height) );
texture.Apply();

```

One option is to create a texture before loading the image from WWW with using WWW.LoadImageIntoTexture:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {

    public string url = "https://docs.unity3d.com/uploads/Main/ShadowIntro.png";
    public bool hasMipmaps = true;

    IEnumerator Start() {

        Texture2D tex;
        tex = new Texture2D(4, 4, TextureFormat.DXT1, hasMipmaps);
        WWW www = new WWW(url);
        yield return www;
        www.LoadImageIntoTexture(tex);
    }
}

```

In this last example, the data from the WWW class will replace the texture size and maybe also the format.

---
Tags: unity, c#, image, ui-design
---


# Question
Title: How to compute a heightmap and use as 3d voxel floating point
When you want to compute a heightmap and use for 3d voxel binary, it's easy.

solid are maybe 1, and air are 0, easy.

But in my case I would like to have a smooth terrain, so the solution is the floating point value. But now I cannot say "Hey, it's 1 so it's solid !" because when I use 1 or -1 with a threshold to 0. It's will work, sure, but look like blocky, not smooth.

When you compute a 3d noise, it's easy you just have to set the computed value (scaled from -1 to 1, threshold to 0). It's will look nice. But for 2d noise...

Let's say, 0 is the minHeight and 500 maxHeight. The 2d noise function is scaled between 0 and 1.

At x:0, y:0, let's say the final value of the height is 250, that the middle. (noise output 0.5 scaled from 0/1 to 0/500)

But for each height, what I am supposed to set ? In binary case, solid are 1, air 0. But in floating point case, what should be the value ?

I tried to apply the noise result (0 to 1), and where y \> computedHeight (computedHeight=250) the value is -1.

It's look blocky (That normal) but I don't have the right solution.

So what I am supposed to set to each y voxel ?

---

Ok my question look confusing, sorry for that.

I can easily get a smooth terrain based on heightmap value. Here is a screenshot.

As you can see, when I combine it with 3d layer, there is a problem, cave is blocky.

Why this problem, I guess it because the cave value are between -1 to 0, nice. But the ground layer that `computeNoise*maxHeight-y` which give nice result but the value is wrong ! And I'm looking for a better way to compute the heightmap (ground layer) to have correct value and get a smooth cave. :)

Here is my pseudo code of how I generate my voxel array.

```
for (var x = 0; x < sizeXz + 1; x++) {
    for (var z = 0; z < sizeXz + 1; z++) {
        var compute = Biome.ComputeXz(voxelX, voxelZ);
        for (var y = 0; y < sizeY + 1; y++) {
            data[x, y, z] = Biome.GetY(compute, voxelX, voxelY, voxelZ);
        }
    }
}

```

Then

```
public ... GetY(...){
    var computedHeight = Scale(compute.value, 0, maxHeight, 0, 1); //Scale noise 0-1 to 0-MaxHeight
    var currentValue = computedHeight-pos.y;
    var currentType = BlockType.Rock;
    if(pos.y > computedHeight)
        currentType = BlockType.Air;
    return new Block(currentType, currentValue);
}

```

This work, this look nice (see ground layer image), but the value are wrong because if you lower, you'll get some value like -82.28389, because of the -y to the currentValue which means further you are from the threshold further from 0 the value will be.

And the cave layer which is a raw output from the noise function (so a value between -1 and 1).

As you know Marching cube do a interpolation between each voxel so I let you imagine why the result is so blocky between the cave which output value like 0.0x and ground output like xx.x

Sorry for the long post.

# Answer
> 1 votes
That's up to you. You have to define a limit (in your case between 0 and 1) which determines which positions are in or out of your terrain. So let's say your values go from 0 to 1, you define 0.5 as the limit, then you can interpret it as every position with a value below 0.5 is outside of your terrain, while every value over 0.5 is inside of your terrain.

You can then change this value and influence how much of your terrain is actually visible.

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


# Question
Title: What is the best way of storing transformations for an object and then applying them with OpenGL?
First some background info...

I have been working on a platformer game, which I draw with OpenGL. The platforms are *cubes* and the player is a *cube*.

The platforms and the player *(both cubes)* are given a position, from which the vertices should be drawn. However, the first cube is at position *\[0, 0, 0\]* and I would like the player to be on top of this cube. The size of the cubes and player is *\[0.5, 0.5, 0.5\]* initially.

However, I didn't manage to get the player on *\[0, 1, 0\]* *(cubes are drawn from their center point I remembered)*, because the scaling didn't seem to work, which led me to believe the method I'm using to store the translations and scaling is inherently bad.

---

I am currently storing the translations and scaling in a matrix, which is part of the object. The object also holds the vertices and the VBO. Let's call it `class Cube`, which thus holds `glm::mat4 m_transform`.

I expose `m_transform` and pass it with `glUniformMatrix4fv(shader.GetUniformLocation("model"), 1, GL_FALSE, glm::value_ptr(m_transform));`

And at some point I call `glDrawArrays(GL_TRIANGLES, 0, 36);` to draw the platform/player cube.

So to alter the position of such a cube, I would alter `m_transform`. Such as: `m_transform = glm::translate(m_transform, vec);` where `glm::vec3 vec` is the desired translation to apply.

However, the issues arise when u wish to scale a cube as well, so if we scale with `vec3(0, 2, 0)`, the translations will be twice as large. And I'm unsure where to go from here.

---

I've read that having different matrices for translation, rotation and scaling is the way to go, which I will try, however, I would like to know what the best practices are surrounding this subject.

Any suggestions are much appreciated!

# Answer
> 1 votes
With this shader, you have to pass a single model matrix, `model`, which is the final object transformation:

```
glUniformMatrix4fv(shader.GetUniformLocation("model"), 1, GL_FALSE, glm::value_ptr(m_transform));

```

But you still can have three different matrices, one for each transformation: translation, rotation and scale, and pass a matrix that is the product of those three transformations.

The thing to remember here is: **order does matter**. Because as you said, if you first **translate** an object, and then **scale** it, the translation shall be scaled, and your object won't be on wanted position.

This is why transformations are generally computed in that order:

```
glm::mat4 translation = glm::translate(glm::mat4(1.0f), position); // Translation matrix
glm::mat4 rotation = glm::toMat4(orientation); // Rotation matrix
glm::mat4 scale = glm::scale(glm::mat4(1.0f), scaleVector); // Scale matrix

m_transformation = trans * rot * scale; // Final transformation matrix.

```

See this related answer for more about transformations order.

---
Tags: opengl, movement, matrix, glm
---


title: Determining how loud an AudioClip is

text:
# Question
Title: Determining how loud an AudioClip is
I have some code that uses `GetSpectrumData` from an AudioSource playing a song to create a level layout for the player to play. I want to add a functionality where the players can upload their own songs and play the levels created with the data from these songs. Unfortunately, when comparing different audio files, I encountered this:

As you can see, the amplitude differs drastically from clip to clip, subsequently creating levels that are trivial to complete or almost impossible. **I want to find a way to determine this "loudness"** so I can tone it down or amplify it with a multiplier after getting the data from the song. Also, **is there a way to extract this data without playing the song?**

# Answer
> 12 votes
A manual way to do that is to use AudioClip.GetData to get the sample data in an array. Then loop through the data and find the Root Mean Square to find the "loudness" of the audio clip.

You can also then scale the whole array so that the maximum value is 1.0f and write it back to the audioclip with AudioClip.SetData. This is called normalizing audio, and it makes samples have the loudest point to max volume. Note that this does not take in to account that if your audio clips are very low volume, but have very high peaks. There are more advanced techniques for that (noted below).

Unity also is doing normalization automatically by default. So if you have not touched the import settings, this operation is done automatically and you do not need to worry about it. If you still have the issue even though you are sure the audio is normalized, you then probably need to compress the audio with dynamic range compression (note: very different thing from data compression, has nothing to do with file sizes or memory usage) to fit your needs with external software.

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


# Question
Title: Why is fog in games exponential and has a start distance?
In most tutorials I see on how to achieve fog with shaders the fog is exponential and has a minimum / start distance from the camera. Why? Both seem counterintuitive, especially the minimum distance. Is this an artistic / design choice or is this how our eyes see fog in real life?

# Answer
This is a legacy from fixed pipeline fog equations, where you typically had one of three options available:

* Linear blended between a start distance and an end distance.
* Exponential based on density.
* Exponential-squared based on density.

For example, the documentation for glFog and for Direct3D 9 fog equations.

A sample tutorial making reference to these three equations (you can cross-check with the documentation and determine that they are the same).

Another sample tutorial referring to fog in the fixed pipeline versus implementing it yourself in a shader.

GLSL 1.10.59 specification containing documentation of built-in uniforms for fog, allowing glFog calls to be used with shaders.

Using shaders you are of course not restricted to these equations, and you can adapt them, modify them, or write your own as you see fit. However, tutorial material does tend to either emulate the older equations or take them as a starting point, because they are a familiar reference (and early versions of GLSL even provided access to glFog parameters via built-in uniforms). You see the very same with lighting, where tutorials typically follow the old fixed pipeline lighting models too (and likewise early versions of GLSL provided access to lighting state too).

(Interesting aside: fixed-pipeline fog did not support specifying a start distance with exponential fog which suggests that some tutorial authors may not have paid as close attention to the documentation as they could have).
> 2 votes

---
Tags: opengl, 3d, shaders, directx
---


title: Strange behavior in collision detection

text:
# Question
Title: Strange behavior in collision detection
I am making a 2d platform game with a tiled map,i now avoid passing through the walls an the ground but when the character hit the ground it shakes vertically,and when i make it walk on a wall it shakes horizontally. the atualization code:

```
public void atualizar() {

    this.detectarColisoes(mapa.getTilesAdjacentes(this.getXAbsoluto(),this.getYAbsoluto(),this.getXAbsoluto()+this.getWidth(),this.getYAbsoluto()+this.getHeight()));
    if(movendo){

        this.setVelX(direcao*5);
        if(this.getVelX()>0 && colisaoLateral==1){
            this.setVelX(0);
        }
        if(this.getVelX()<0 && colisaoLateral==-1){
            this.setVelX(0);
        }
    }else if(this.getVelX()!=0){
        if(this.getVelX()>0){
            this.setVelX(this.getVelX()-1);
        }else{
            this.setVelX(this.getVelX()+1);
        }

    }
    if(this.getXRelativo()>490 && this.getVelX()>0){
        mapa.moveMapX(this.getVelX());
    }
    if(this.getXRelativo()<150 &&this.getVelX()<0){
        mapa.moveMapX(this.getVelX());
    }
    if(estadoSalto==2 && this.getVelY()>0){
        estadoSalto=1;
    }

    super.atualizar();
    if(estadoSalto!=0){
        this.gravidade();
    }
    System.out.println(estadoSalto);

}

```

the code for the collision detection:

```
public void detectarColisoes(ArrayList<Rectangle> adjTiles){
    Rectangle chara=new Rectangle(this.getXAbsoluto(),this.getYAbsoluto(),this.getWidth(),this.getHeight());
    if(adjTiles.isEmpty()){
        if(estadoSalto!=2){
            estadoSalto=1;
        }
    }
    boolean caindo=true;
    this.colisaoLateral=0;
    for(Rectangle aux:adjTiles){
        Rectangle ints=aux.intersection(chara);
        if(!ints.isEmpty()){

            if(ints.height<ints.width){

                if(ints.y>chara.y ){

                    estadoSalto=0;
                    this.setVelY(0);
                    this.setY(this.getYAbsoluto()-ints.height);
                    nSaltos=1;

                    caindo=false;

                }

            }else{
                if(ints.x>chara.x){
                    this.setX(this.getXAbsoluto()-ints.width+1);
                    this.colisaoLateral=1;

                }else{
                    this.setX(this.getXAbsoluto()+ints.width-1);
                    this.colisaoLateral=-1;
                }

            }
        }
    }
    if(caindo){
        estadoSalto=1;
    }

}

```

# Answer
The problem comes from the fact that you do your collision detection **before** moving. Just move the line `this.detectarColisoes(...);` to the end of the `actualizar()` method and that will fix the problem.

Please note that naming your variables in english is a **good practice** especially if you want to get help from this site, as reading portuguese names is not helping most of us.
> 2 votes

---
Tags: java, collision-detection, bug
---


title: Spawning/Updating objects from client

text:
# Question
Title: Spawning/Updating objects from client
I hope this is the right place to ask my question... I have been working on a game (all 2D) and I'm facing some problem with the networking part (pretty much a beginner).

My game idea is a shared screen (the server) and multiple devices (clients) where every player will get different tasks/objectives. So after I spawn the players initially I just set them to not active on the server. That way the players can share the screen. After spawning the player on the client side, the player will have a screen to select an avatar and enter their name. On the server side, I would like to have the player selected avatar and name show up by spawning another object. The problem is that once the object is spawned it's not being updated on the server with the information from the client, even when using \[Command\].

Images to help understand the problem: https://i.stack.imgur.com/00M0K.jpg

Any help is appreciated it :)

# Answer
Consider tagging player related variables with the syncvar attribute. See unity docs https://docs.unity3d.com/560/Documentation/Manual/UNetStateSync.html
> 0 votes

---
Tags: unity, 2d, unity-networking, spawning
---


# Question
Title: Is using isTouched or justTouched multiple times bad?
Suppose you have justTouched or isTouched method multiple times in your game screen, is that bad? Is it better to create booleans and as few input listeners as possible? or it doesn't matter?

# Answer
You can reference `justTouched` or `isTouched` as much as you like. I'd be surprised if they reevaluated on every call during a single frame. However, even if they were reevaluated each time you called them, it's likely to be one of the least of your performance concerns.

Make your game, then worry about these little optimizations later, when you're profiling the game to improve performance.
> 3 votes

---
Tags: java, android, libgdx
---


# Question
Title: OpenGL camera movement with mouse buttons
I am using modern OpenGL with glfw. I made a FPS camera with mouse and it works very well. But I want to move my mouse like Blender's model view mode. When I press the middle mouse button and move the mouse, it should move the camera. I tried it but I couldn't succeed it. I just want it like Blender.

That is my camera class (sorry for indentation):

```
#pragma once
#include <vector>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

enum Camera_Movement {
    FORWARD,
    BACKWARD,
    LEFT,
    RIGHT
};

const GLfloat YAW        = -90.0f;
const GLfloat PITCH      =  0.0f;
const GLfloat SPEED      =  3.0f;
const GLfloat SENSITIVTY =  0.05f;
const GLfloat ZOOM       =  45.0f;

class Camera
{
public:

glm::vec3 Position;
glm::vec3 Front;
glm::vec3 Up;
glm::vec3 Right;
glm::vec3 WorldUp;

GLfloat Yaw;
GLfloat Pitch;

GLfloat MovementSpeed;
GLfloat MouseSensitivity;
GLfloat Zoom;

Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up =            glm::vec3(0.0f, 1.0f, 0.0f), GLfloat yaw = YAW, GLfloat pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVTY), Zoom(ZOOM)
{
    this->Position = position;
    this->WorldUp = up;
    this->Yaw = yaw;
    this->Pitch = pitch;
    this->updateCameraVectors();
}
Camera(GLfloat posX, GLfloat posY, GLfloat posZ, GLfloat upX, GLfloat  upY, GLfloat upZ, GLfloat yaw, GLfloat pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVTY), Zoom(ZOOM)
{
    this->Position = glm::vec3(posX, posY, posZ);
    this->WorldUp = glm::vec3(upX, upY, upZ);
    this->Yaw = yaw;
    this->Pitch = pitch;
    this->updateCameraVectors();
}

glm::mat4 GetViewMatrix()
{
    return glm::lookAt(this->Position, this->Position + this->Front,  this->Up);
}

void ProcessKeyboard(Camera_Movement direction, GLfloat deltaTime)
{
    GLfloat velocity = this->MovementSpeed * deltaTime;
    if (direction == FORWARD)
        this->Position += this->Front * velocity;
    if (direction == BACKWARD)
        this->Position -= this->Front * velocity;
    if (direction == LEFT)
        this->Position -= this->Right * velocity;
    if (direction == RIGHT)
        this->Position += this->Right * velocity;
}

void ProcessMouseMovement(GLfloat xoffset, GLfloat yoffset, GLboolean  constrainPitch = true)
{
    xoffset *= this->MouseSensitivity;
    yoffset *= this->MouseSensitivity;

    this->Yaw   += xoffset;
    this->Pitch += yoffset;

    if (constrainPitch)
    {
        if (this->Pitch > 89.0f)
            this->Pitch = 89.0f;
        if (this->Pitch < -89.0f)
            this->Pitch = -89.0f;
    }

    this->updateCameraVectors();
}

void ProcessMouseScroll(GLfloat yoffset)
{
    if (this->Zoom >= 1.0f && this->Zoom <= 45.0f)
        this->Zoom -= yoffset;
    if (this->Zoom <= 1.0f)
        this->Zoom = 1.0f;
    if (this->Zoom >= 45.0f)
        this->Zoom = 45.0f;
}

private:
void updateCameraVectors()
{
    glm::vec3 front;
    front.x = cos(glm::radians(this->Yaw)) * cos(glm::radians(this-  >Pitch));
    front.y = sin(glm::radians(this->Pitch));
    front.z = sin(glm::radians(this->Yaw)) * cos(glm::radians(this->Pitch));
    this->Front = glm::normalize(front);
    this->Right = glm::normalize(glm::cross(this->Front, this->WorldUp));
    this->Up    = glm::normalize(glm::cross(this->Right, this->Front));
}
};

```

Thank you.

# Answer
> 0 votes
First check if the middle mouse button is down, then get the movement of the mouse and convert it to a vector (to a vec3, where `x` is the movement on the x axis, `y` is the movement on the y axis and `z` is 0.

With glm create a rotation matrix using your camera's angles:

```
glm::mat4 rotPitch = glm::rotate(this->Pitch, glm::vec3(1, 0, 0));
glm::mat4 rotYaw = glm::rotate(this->Yaw, glm::vec3(0, 1, 0));
glm::mat4 rot = rotPitch * rotYaw;

```

Then multiply your movement vector with this matrix (you need to convert it to a 4d vector):

```
glm::vec3 transform = vec3(rot * glm::vec4(movement, 0));

```

Add this vector to the position of the camera and done

---
Tags: opengl, camera
---


title: Load destructible mesh at runtime

text:
# Question
Title: Load destructible mesh at runtime
Using the tutorial: Components and Collision as a guide, to dynamically load a SphereShape the following is done:

```
AClass::AClass()
{
    // Create USphereComponent
    USphereComponent *sphere = NULL;
    sphere = CreateDefaultSubobject<USphereComponent>(TEXT("Root"));
    sphere->InitSphereRadius(1.0f);
    sphere->SetCollisionProfileName(TEXT("PhysicsActor"));
    sphere->SetSimulatePhysics(true);
    sphere->WakeRigidBody();

    // Create UStaticMeshComponent
    UStaticMeshComponent *mesh = NULL;
    mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
    mesh->SetupAttachment(RootComponent);

    // Load asset from filesystem
#define ASSET TEXT("/Game/MobileStarterContent/Shapes/Shape_Sphere.Shape_Sphere")
    static ConstructorHelpers::FObjectFinder<UStaticMesh> asset(ASSET);
#undef ASSET
    if (asset.Succeeded())
        mesh->SetStaticMesh(asset.Object);

    RootComponent = sphere;
}

```

Now, when I try the same set of steps, but this time for an Actor that has a `UDestructibleComponent` instead of a `USphereComponent`:

```
AClass::AClass()
{
    // Create our UDestructibleComponent
    UDestructibleComponent *destructible = NULL;
    destructible = CreateDefaultSubobject<UDestructibleComponent>(TEXT("Root"));
    destructible->SetCollisionEnabled(ECollisionEnabled::PhysicsOnly);
    destructible->SetSimulatePhysics(true);
    destructible->SetEnableGravity(false);
    destructible->WakeRigidBody(NAME_None);

    // Load asset from filesystem
#define ASSET TEXT("/Game/MobileStarterContent/Shapes/Shape_Cube_DM")
    static ConstructorHelpers::FObjectFinder<UDestructibleMesh> asset(ASSET);
#undef ASSET
    if (asset.Succeeded())
        UE_LOG(LogTemp, Warning, TEXT("It worked!"));

    RootComponent = destructible;
}

```

I receive the following errors:

```
ConstructorHelpers.h:105:20: error: cannot initialize a parameter of type 'UObject *' with an lvalue of type 'UDestructibleMesh *'
ValidateObject( Object, PathName, ObjectToFind );
                ^~~~~~

ConstructorHelpers.h:29:19: error: incomplete type 'UDestructibleMesh' named in nested name specifier
UClass* Class = T::StaticClass();
                ^~~

```

I've also tried adding `.Shape_Cube_DM` to the end of the string, similar to how the first asset was imported, but no luck. What is the correct way to load a `DestructibleMesh` from the filesystem and apply it to the `UDestructibleComponent`?

# Answer
> 1 votes
Figured it out - the assets needs to be loaded as a `USkeletalMesh`, and then casted to a `UDestructibleMesh` whenever that type is needed.

```
// Sets default values
ADestructibleBox::ADestructibleBox()
{
    PrimaryActorTick.bCanEverTick = true;

    // Create our UDestructibleComponent
    UDestructibleComponent *destructible = NULL;
    destructible = CreateDefaultSubobject<UDestructibleComponent>(TEXT("Destructible"));
    destructible->SetCollisionEnabled(ECollisionEnabled::PhysicsOnly);
    destructible->SetSimulatePhysics(true);
    destructible->SetEnableGravity(false);
    destructible->WakeRigidBody(NAME_None);

#define ASSET TEXT("/Game/MobileStarterContent/Shapes/Shape_Cube_DM.Shape_Cube_DM")
    static ConstructorHelpers::FObjectFinder<USkeletalMesh> asset(ASSET);
#undef ASSET
    if (asset.Succeeded())
    {
        UE_LOG(LogTemp, Log, TEXT("Asset loading succeeded."));

        meshSkel = Cast<USkeletalMesh>(asset.Object);
        meshDest = Cast<UDestructibleMesh>(meshSkel);

        destructible->SetSkeletalMesh(meshSkel, true);
    }

    RootComponent = destructible;
}

```

---
Tags: 3d-meshes, assets, unreal-4
---


# Question
Title: Why would someone chose midpoint displacement over perlin noise for 3D terrain generation?
I myself am creating a terrain generation algorithm and would be interested in knowing why others have chosen midpoint displacement over perlin noise. Minecraft is an example where midpoint displacement was preferred. If anyone knows why I would be glad to hear it.

# Answer
Different methods of fractal generation tend to produce terrain with different characteristics. The reason for their use could be stylistic rather than for any technical performance reason. Different algorithms also allow you to change different parameters to give the final result. I have no direct answer re: MD vs Perlin though, sorry..
> 3 votes

# Answer
Notch posted about this on his blog:

> I used a 2D Perlin noise heightmap to set the shape of the world. Or, rather, I used quite a few of them. One for overall elevation, one for terrain roughness, and one for local detail. \[..\] But \[it had\] the disadvantage of being rather dull. Specifically, there’s no way for this method to generate any overhangs.
>
> So I switched the system over into a similar system based off 3D Perlin noise. Instead of sampling the “ground height”, I treated the noise value as the “density”, where anything lower than 0 would be air, and anything higher than or equal to 0 would be ground.
> 8 votes

# Answer
Here's some reasons to prefer midpoint displacement:

1. Midpoint displacement noise is meaningfully faster to calculate (in my experience).
2. And, Perlin noise has some biases; it only approximates full spectrum white noise but is closer to Gaussian; midpoint displacement may be generated with a uniform (or any) distribution.

But, as another answer said, it's my understanding that Minecraft does use Perlin noise; I don't see how you could efficiently implement midpoint displacement noise for Minecraft, where the map goes on forever. The advantage of Perlin noise here is that you can calculate it at any point without calculating any other points around it. For midpoint displacement, you have to generate it all at once, since you need the boundaries of each chunk to match.

(EDIT: Removed mention that midpoint displacement can produce wrapping heightmaps - Perlin can do this just as easily.)
> 0 votes

---
Tags: algorithm, minecraft-modding, terrain, perlin-noise
---


# Question
Title: How can I randomly pick points on a triangle?
Please can help me for a geometry query, I am working out fast mesh to voxel algorithm without using rays and complex maths...

What are the maths to sample N points on a triangle randomly? If you can sample randomly i think it means you know the same equation that can distribute points on a triangle at same spacing.

I found some info here but it's too difficult to understand:

https://math.stackexchange.com/questions/18686/uniform-random-point-in-triangle

http://mathworld.wolfram.com/TrianglePointPicking.html

The reason is to sample N points on every triangle and round each into a voxel space and send the rounded position of every sample as a true value to a boolean spacial voxel array of X,Y,Z true false values to represent voxels.

Thanks for any info's you may provide!

# Answer
> 3 votes
What you need is a specific coordinate system where instead of having right angles in the center, you have one of the angles of the triangles. The units on each axis are also equal to the length of the triangle's sides:

The units on the "y" axis are the length of AC, the units on the "x" axis equal to the length of AB.

If you project this into a right angle coordinate system, you get the following:

Much much better, now you want to get a random point in this.

For every point in this triangle we can say, that the sum of the coordinates (x + y) of it is always less than or equal to 1. Knowing this generating a random point inside can be done the following way (pseudo-code):

```
x := rand(0, 1)
y := rand(0, 1 - x)

```

Now you only need to convert this back to the original coordinate system, this can be done my converting the AC and AB sides to a vector and multiplying them with x and y:

```
vX := (C - A) * x
vY := (B - A) * y

```

This is in 2d, but this can be extended to 3d. You only need to do the last 2 steps (generating the random point in the equilateral triangle then projecting it to 3d).

# Answer
> 0 votes
Thanks a lot to Bálint for illustrating the problem. i found a result for random points although i don't actually understand it, so will have to study that theory.

```
function randomPointsOnPolygon () {

for( var xx = 0; xx <= 100; xx ++){
    var r1 = Random.value;
    var r2 = Random.value;
var P:Vector3=(1-Mathf.Sqrt(r1))*ta+(Mathf.Sqrt(r1)*(1-r2))*tb+(r2*Mathf.Sqrt(r1))*tc;

    var cube : GameObject      = GameObject.CreatePrimitive(PrimitiveType.Cube);
    cube.transform.position    = P;

    }
}

```

Random is fairly random, I tried ra = (xx * xx)%1 to mix the proportions up and fixed increment and random was best. Comment if you know how to make regular distribution. xx\*q % 1.0 gives these images:

THE REST OF THIS ANSWER IS SKIPPABLE: ITS HELPFUL INFO TO DEMONSTRATE THIS IS A VERY GOOD/BEST WAY TO SOLVE VOXEL TO MESH CONVERSION: it seems incredibly much speedier than a physics mesh to voxel version, online they had me checking all 12 edges of every cube for min max in every quadrant of space. checking 24 edges of one cube (raycast both directions) is slower than checking 24 points on a triangle,every which one is in a cube of space, to write to a bool array!

found this approximate sqrt for c# for it too http://blog.wouldbetheologian.com/2011/11/fast-approximate-sqrt-method-in-c.html

hint: optimize by number samples related to triangle size, using a fast tri size approximation because it's quite demanding on maths, otherwise 250 samples per triangle takes 1 second for a 2000mesh object so perhaps no optimization necessary.

Time take for 10,000 vertex mesh from 2000 triangles = 1 second, triangle vtx size mutiplied by mesh size multiplier, rounded random triangle points saved as math.round to linear bool array length 100,00,00 boolarr(z\*100\*100+y\*100+x) ... that's how you use a linear voxelbool aray in xyz loops. afterwards to fill the mesh, it's best to use the vertex normals to mark left and right facing triangles/cubes and to scan fill all left right voxels.

---
Tags: geometry, voxels
---


# Question
Title: Java - Genetic Algorithm - Multi Paint Components
Currently working on a Genetic Algorithm in Java where I'm using a JPanel to draw my population and my target. The technical code works (generate population, mutate, crossover, get genes, etc...) but I'm stuck with the code to draw all my population.

Currently each individuals have x, y, x velocity ,y velocity and an array of directions \["up", "up", "down", ...\] as attributes.

Tried to do:

```
// Draw the destination square in Red, individuals in Black
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.red);
    g2.fill(new Rectangle2D.Double(destinationX(),destinationY(), 10,10));
    g2.setColor(Color.black);
    // Draw each Individual in black
    for (Individual ind : Population)
      // read their genes one by one and repaint everytime to see the square move
}

```

But it's extremely messy, ugly and hard to debug.

How should I go from here? Should all individuals be JPanels that I'll add to the main JPanel? Do I need to use Threads? Any suggestion would be appreciated.

# Answer
If you are finding your code hard to read or debug you either need to abstract or encapsulate more. Each individual should be responsible for drawing itself, but does not need to be its own JFrame. Simply pass the graphics to each individual. Try splitting your code up like so:

```
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;

    drawDestiation(g2);

    drawIndividuals(g2);
}

private void drawIndividuals(Graphics2D g){
  for(Individual ind : Population){
      ind.drawSelf(g);
    }

}
```
> 1 votes

---
Tags: java
---


# Question
Title: How to disable Monogame pixel font antialiasing?
I am using Monogame 3.4 (I have held off upgrading to 3.5) and am on Windows 10. I'm drawing using the PointClamp setting (**as suggested in this similar question**).

Whenever I render text with DrawString(), the text is extremely antialiased, as shown below. However, any stretched *textures* I draw are **NOT** antialiased, and seem to use the PointClamp setting as expected.

Here are some examples of drawn text:

How do I disable text antialiasing so that fonts don't blur?

**EDIT**:

It seems that changing some import settings in the .mgcb changes the quality of the AA? When "processorParam:TextureFormat=Color" is changed to "processorParam:TextureFormat=Compressed", it makes the AA more pronounced. The issue is still not solved, but I feel like the font import settings may have something to do with it. Here is the .mgcb

```
#begin DwellFont.spritefont
/importer:FontDescriptionImporter
/processor:FontDescriptionProcessor
/processorParam:TextureFormat=Color
/build:DwellFont.spritefont

```

**EDIT 2**

Since this question got flagged as a duplicate, let me explain. The other question **I have already referenced above** uses PointClamping. I already use PointClamping, and it works fine with the textures I render (they aren't antialiased). It does not, however, work with my fonts. Therefor, that other question isn't applicable. I'm wondering why that is.

# Answer
> 1 votes
Basically you have to use the Font Texture feature, which allows you to create a texture with just about any content, as pixely or blurry as you like, and load it into a spritefont. Read more at: https://blogs.msdn.microsoft.com/shawnhar/2007/04/26/bitmap-fonts-in-xna/

Or just Google "XNA Font Texture".

# Answer
> 1 votes
I believe this could help you (quoting from Shawn Hargreaves' MSDN blog):

> At this point you may be worrying that drawing an entire font into a bitmap by hand is not your idea of fun. And you’d be right. I wouldn’t enjoy it much either.
>
> Fortunately, the kindly little gremlins who work at XNA CGP GSE Samples & Utilities, Inc, saw this problem coming and wrote a program to take care of it. This presents a user interface for selecting what TrueType font you want to use as a starting point.

---
Tags: c#, rendering, monogame, fonts
---


# Question
Title: Where should multiplayer games start? Client or server?
I'm starting to make a small multiplayer game, and even though I have experience with games and networking, there's just one thing that keep me from making this.

The question is: **When starting a multiplayer game, should one start making the server first, or the client first?**

This looks like a dead-lock for me, because while starting on the client, seems to be the a good option (you'll make a game, which you are already very good at doing probably, and you'll have something to look for progress), you will fall on the trap that probably most of the code effort you put into making that game will have to be thrown away and remade on the server side.

And starting on the server-side is just the opposite: You'll have nothing to look upon, so you can't know if you're making progress. And if that wasn't bad enough, you'll also have to throw lots of stuff away, since you have no game to check if that will have to indeed work like that.

Is there a correct answer for this?

# Answer
You develop both at the same time, inside the same executable or a DLL loaded by the game executable.

The game always run on a server, even when running single-player.

When running single player only an internal connection is used and the server is closed to the outside world (not listening to any sockets/ports).

Once you have the game working you can create a stand-alone server executable without the game code using the same code base.

This also lets you add the option for the player to "Open To LAN" his/her 1 player game and/or host without a dedicated server.
> 8 votes

# Answer
I would build the server first, this is a personal opinion, but I consider the server-side processing the 'heart' of the game.. The client will need the server's feedback to know what to do.
> 1 votes

---
Tags: networking, multiplayer
---