# Question
Title: Is there a PBR-like material system for audio?
With visual/rendering materials, a very popular system for this is PBR. Materials made using PBR may define properties like albedo color, normal maps, emission, roughness, metallic, specular, etc. This allows creating objects that interact with light in a realistic way, using general-purpose parameters.

With physics materials, it's common for them to define friction, restitution/bounciness, absorbency, etc. This allows defining how objects react to each other when sliding against each other or impacting each other in the physics engine, using general-purpose parameters.

With audio materials, such as those used for calculating footstep sounds, impact sounds, bullet hole sounds, etc, as far as I know most games just use a hard-coded list of sounds. For example a game may define an object as sounding like "wood", so you walk on that object and it plays the wood footstep sound.

However, I am interested in building an engine-agnostic representation of audio materials, so a hard-coded list of sounds is not ideal. I would prefer to have a series of parameters like PBR provides for visual materials. For example if game engine A has "wood" and "birch wood", and game engine B has only "wood", I would like to be able to convert "birch wood" into parameters, then game engine B can play the closest equivalent sound to those parameters, or possibly interpolate between sounds, or procedurally generate sounds.

Is there a PBR-like material system for audio? Is there a way to define how objects sound using a series of parameters instead of a hard-coded list of strings? Some set of parameters to define audio resonance, brittleness, impact response, thermal response, moisture response, hollowness, reverberation, etc? Do any existing game engines have this? What about other software like those used to make movies?

# Answer
> 2 votes
There is something analogous to physically based **rendering** for audio: physical modelling synthesis.

However, while you will find models that contain more or less simple parameters, **you will not find *one* model that works — you will not find a direct equivalent of the visual “PBR material” concept.** This is because the problem of producing a complete realistic sound is analogous to the problem of producing a complete realistic image: you don't just need one material, but a “scene” in which sound waves propagate and are changed.

To produce an image, we use a rendering algorithm and a prepared data set which encodes decisions about what light rays and what surface details are worth calculating. To produce a sound, we need to decide what signal-processing elements are worth calculating, and what the graph of interactions between them is.

We can choose to produce an image by brute force using a path tracing renderer without the approximations that are used for real-time graphics, and trade off efficiency for generality and realism. Similarly, we can produce a sound by creating a model of the **physical structure of the vibrating elements,** and running a finite element method calculation that simulates how the vibrations propagate through the object(s) and out through the air. But this is not cheap, especially because your simulation step rate cannot simply be the 30-120 Hz that satisfies human vision, but rather 40+ kHz. (This has been done experimentally in real time, using input from a physics engine to excite the finite element mesh and thus producing physically-based collision sounds; unfortunately I don't have a link to the paper as I happened across it many years ago.)

It is possible to write down reusable descriptions of much simpler synthesis systems — the graph of signal processing elements I mentioned previously. This is the closest analogue of a “PBR material” in the audio synthesis world. However, I am not aware of very much standardization in this area; the possible nodes and parameters are usually unique to a specific tool. One exception I'm aware of is the Web Audio API being a specification rather than a program; however, it doesn't come with a way to define its graphs as data rather than programs.

Another factor is that the things you can readily reproduce using simple synthesis elements are generally not similar to complex everyday sounds — rather, they tend to be excessively musical. This is analogous to how a visual material will involve **textures**, in order not to look like a too-perfect plastic or metal shape.

Similarly, you can start with one or more sound samples and manipulate them in physically based ways. The most common form of this is spatial audio: besides just volume and panning, you can have:

* frequency-dependent attenuation, dependent on the frequencies the materials in the environment absorbs preferentially
* Doppler effect simulation for moving objects
* reverberation for the enclosing room

(Note that these are all approximations of specific elements the true propagation of sound, just like much of real-time graphics is approximation of the propagation of photons, and just like graphics, you *can* use a ray-tracing approach to better model propagation, but it requires more computation.)

Beyond those, there are also ways to parameterize processing of a sound sample to make it useful for more purposes, such as objects of different sizes or related materials:

* Pitch shifting for objects of different sizes
* Apply a filter (low-pass, high-pass, equalization…)
* Granular synthesis: play many overlapping short sounds, and adjust the timing, pitch (or rather, playback rate), density, and mix of multiple samples to produce a continuously variable, complex output.

However, all of this will still usually be done starting with specific sound samples for the application. You could hope to find matching samples that suit your needs, and shape them using filters, but I think in practice you should expect to **bring your own sounds just like you bring your own textures**. You might pick them out of an asset library, but you'll still be picking them, not just getting an automatic match from a physical description. Unfortunately.

Your idea of going from “wood” to “birch wood” automatically would be difficult for two reasons: first, there is not any standard for what the “generic wood impact sound” would be like (in frequency spectrum *before* any added filters), and second, the sound will be very different depending on what the actual wood structure involved is (a tree? A deck? A wooden box?) because that affects the resonances. **You *can* use parameters to stretch a few sounds to cover many more cases** — it's just that there is no one unified “PBR sound material”, but a bunch of arbitrary choices.

In summary: **Expect to treat sound as an art creation problem,** not something the engine can do for you.

---
Tags: audio, materials, pbr
---


# Question
Title: How can I correctly pass 2 vertices instead of all 4 for a quad to a vertex shader?
If I am rendering quads, but all the quads will be axis-aligned (that is, their plane is always parallel to either the X Y or Z plane), I thought I could cut vertex video memory usage in half by passing opposite corners (6 floats) instead of all corners (12 floats) to the vertex shader per instance. Provided to the shader would be a buffer of these opposing corners and a per-instance vertex ID which would be from `[0, 4)`.

There are 3 orderings for vertices in a quad, which I call C, Z, and X, where C is the most standard. This determine which vertex ID corresponds to which corner. Here are some graphs to illustrate the relationship between the vertex ID and the corresponding corner:

C:

```
3----2
     |
     |
0----1

```

Z:

```
2----3
 \
  \
   \
    \
0----1

```

X:

```
2----1
 \  /
  \/
  /\
 /  \
0    3

```

I would like to be able to, given only the ID and 2 vertices, determine the location in 3D space of the vertex corresponding to ID. If the planes are axis-aligned, I could pass a normal ID and use a `switch` statement or so in the shader but I would prefer to be able to do this **implicitly**. Since the planes are axis-aligned one of the coordinates in one of the points will **equal** the corresponding coordinate in the other plane.

I have thought about how I can arrange the data into a new vertex given only vertex-ID and 2 opposite points but I ran into a difficulty. For each of the 4 points, I either use an XYZ value from the low or high corner. I know that if I go with C, for example, if vertex ID is 0 the result will just be the lower vertex and if the ID is 2 the result will be the higher one.

But for the other 2, I will need to grab some values from the lower vertex and some from the higher vertex. But given only vertex ID, no matter what I try, I cannot seem to be able to produce a quad whose vertex order (C/Z/X) is consistent. For example if I make a table (`l` or `h` means the resulting vertex will have the corresponding coordinate from the low or high vertex respectively):

```
VID 0 1 2 3
Dim
0   l l h h
1   l h h l
2   l h l h

```

This does create squares with correct coordinates given the vertex ID and only 2 opposite corners corresponding to the square, but the issue is, if the square is X-aligned, the resulting vertex ordering is X-style, Y-aligned gives Z-style ordering, and Z-aligned gives C-style ordering. I need them to have **consistent** ordering.

I have thought about all these tables I could make about which (low/high) vertex we pick an XYZ coordinate from given the vertex ID, and there are only 4096 possibilities, and none of them seem to satisfy the requirements of giving a consistent vertex-ordering style. So this alone cannot solve the problem. I will need some other strategy.

This question is more theoretical than programmatic, but how can I, given only 2 opposing vertices and a vertex ID, get the Nth vertex corresponding of 4 vertices of a square described by the opposite vertices, where the resulting vertex-ordering is correct and consistent?

# Answer
I'm going to ignore your commentary about the possible ordering of four supplied quad vertices, as I don't think it's relevant to the question.

The question(s) as I understand them, are:

(a) can you supply only two corner verticies of an axis-aligned 3d quad, and automatically determine the normal. (short answer: no, not in the general case)

(b) how can you generate the four vertices of an axis-aligned quad given the corner vertices when you know the normal?

(c) is this a worthwhile optimization of anything useful (short answer: probably not)

---

The reason you can't omit the quad-normal (or axis alignment) is that if the corner verticies happen to lie on *two* axis-aligned planes, you will have no way to disambiguate which one you wanted.

```
Imagine the (x,y,z) corner points (0,0,0) and (1,0,0)

```

Did you want a y-axis aligned plane or a z-axis aligned plane? There is no way to know without giving it the normal, because both the y and z coordinates match.

This becomes apparent when you generate the coordinates for the y-axis and z-axis aligned quads... because both of them share the two points above as corners.

```
y-axis quad : (0,0,0) (0,0,1) (1,0,0) (1,0,1)
z-axis quad : (0,0,0) (0,1,0) (1,0,0) (1,1,0)

```

---

To generate the 4 corners of the axis-aligned quad given the normal, you are going to permutate the coordinates around the other axis. This becomes simpler if you think about it in 2d on the axis.

```
Given two 2d corners: (a,b) (c,d)
The four corners are: (a,b) (a,d) (c,d) (c,b)

For example: (0,1) (2,3) -> (0,1) (0,3) (2,3) (2,1)

```

To do this in 3d, you simply add the 3rd coordinate for axis-alignment without changing it:

```
X-aligned: (X,a,b) (X,c,d) -> (X,a,b) (X,a,d) (X,c,d) (X,c,b)
Y-aligned: (a,Y,b) (c,Y,d) -> (a,Y,b) (a,Y,d) (c,Y,d) (c,Y,b)
Z-aligned: (a,b,Z) (c,d,Z) -> (a,b,Z) (z,d,Z) (c,d,Z) (c,b,Z)

```

---

The reason this probably isn't a useful optimization to do on 3d GPUs has to do with how GPUs handle conditionals.

In the GPU, if you put in a switch, which you must have to choose between the three axis alignment cases above, ALL GPU cores need to follow *every* branch of the switch, ignoring the cases that don't apply to them. This means you are running all three lines above on all GPU cores for all QUADS in your quad list. The GPU will run the vertex code faster if you supply the extra vertices so it doesn't have to run the conditional.

Also, by supplying the axis information in a packed form (one byte), you are going to unalign the entire quad vertex buffer. Instead of each Quad being 4x3x16bits, each quad will be 2x3x16bits + 8bits (axis). If you are just loading a buffer and sending it to the GPU it's probably fine but if your CPU is generating the quad-buffer, then the unaligned 16bit floats could potentially slow things down quite a bit in the CPU generation.

Are there situations where this could produce a speedup? Maybe.... If you have pre-calculated quad-buffers with extremely large numbers of only axis-aligned-quads, then you could reduce the size of those buffers substantially. You could even remove the axis-alignment byte, by instead supplying a per-draw-call list of three ints (# x-axis aligned, # y-axis aligned, # z-axis aligned) and then pre-order the quad-corner list so all the x-axis aligned quad are first, followed by y-axis-aligned, followed by z-axis aligned. This would basically make the size of your "axis aligned quad draw" buffer down by half, so for **very** large numbers of only axis aligned quads, that could be relevant.

However, I can't imagine the application for which this is relevant.

Voxel bricks can be drawn faster by using the GPU for the ray-marching of the voxel grid itself.

Further, even if you want to use the CPU to do it, voxel bricks are generally uniform size, so you don't need the flexibility of arbitrary corners, and can instead just supply the center point of the voxel and the face-number (1-6).
> 1 votes

---
Tags: geometry, metal
---


# Question
Title: Transparent Composite Object In Unity HDRP
Potentially a big question, but it seems like it should be simple enough. I have an object in my game composed of multiple parts (connected GameObjects with their own renderers). I want to make this entire object semi-transparent, without seeing the parts of the object through itself.

Here's an example of what I have so far:

There are two cubes, with another stretched cube connecting them. The sphere in the background is just to show an object in the background. Notice how you can see the ends of the connecting cube inside the other cubes. That's what I *don't* want. I only want the front-most faces of the overall "composite object" to be visible. I want inner faces of the object to be occluded, while keeping the object as a whole semi-transparent.

Turning on "depth write" almost sort of works, but it gives me this:

I've searched for hours to try and figure out how to implement this. This is the closest thing I've found, but it's for URP, and I can't figure out how to translate it over to HDRP. I've run into talk about creating shaders, but at this point I've never touched shader design (on any platform), and can hardly begin to figure out how I would accomplish this.

I feel like I can't be the first person to have this problem in this setup. Can anyone outline for me how to get the transparency I need, specifically in Unity's High Definition Render Pipeline?

**EDIT:**

Trying the suggestion from:
Fade in rendering mode doesn't work as intended

I've duplicated the object and applied the following shader to one of the overlapping copies.

```
Shader "Unlit/DepthReserve"
{
    Properties
    {
    }
    SubShader
    {
        Tags { "RenderType" = "Opaque" "Queue"="AlphaTest+1" }
        LOD 100

        Blend Zero One

        Pass
        {

        }
    }
}

```

This very nearly works, but it results in some strange glitching. Watch how the background object erratically pokes through the transparent one when I move the camera.

If there's a way to fix that, this method (as hacky a workaround as it is) could work for me.

# Answer
Blend Zero One is equivalent to rendering nothing and just showing the background as the shader output is multiplied by zero and the frame buffer is multiplied by one.

However, using Alpha overrides the Blend mode. This is just a guess, but it could be there is some blend mode race condition because of this override.

What you want, is to render in the AlphaTest pass (which is front-to-back sorted with z-writes), with an Alpha Transparent Blend mode. Try this?

```
Shader "Unlit/DepthReserve"
{
    Properties
    {
    }
    SubShader
    {
        Tags { "Queue" = "AlphaTest+1" "RenderType" = "Transparent" }
        LOD 100

        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {

        }
    }
}

```

This thread may be helpful:

https://forum.unity.com/threads/difference-between-alphatest-and-transparent-renderqueue.458750/

you can also add `#pragma debug` and look at the compiled shader
> 0 votes

---
Tags: unity, transparency, hdrp
---


# Question
Title: OnPointerDown / OnPointerUp aren't working in world-space canvases
I'm working on a project where I have a main UI (Screen Space - Overlay canvas) and various game objects that have little popups above them (World Space canvas) that the player should be able to click on. Everything on the main UI works fine, but the `OnPointerDown` and `OnPointerUp` methods on the World Space canvases aren't firing when I click on them.

Things I've made sure to check:

* The canvases have a Graphic Raycaster
* The canvases have their Event Camera set to the scene's camera
* The Image on the canvas that's supposed to get clicked on has Raycast Target set to `true`

This was all working fine in Unity 2018, but in 2019 it's not. Is this a bug, or has something changed that I just don't know about? Either way, is there any way to fix this?

# Answer
For anyone still having this in 2023:

There is likely some component that's already consuming the OnPointerDown() event before it reaches your script. Check if there are other components in the hierarchy that have IPointerDownHandler or IPointerUpHandler.
> 1 votes

---
Tags: unity, unity-ui
---


# Question
Title: Extract a rotation matrix given a camera direction (vector) and a up vector for the camera?
I am having some issues constructing a rotation matrix from a camera direction vector.

The Up vector is computed from the camera direction as such:

```
up = cross(cross(direc,(0,1,0)),direc)

```

How do i given the up vector and a camera direction vector compute the rotation vector, that tells the camera how it should be rotated such that it points toward my object?

# Answer
*NOTE: Edited because it was likely too verbose (source).*

A rotation matrix actually always defines an orthonormal basis. What this means is each column defines one of your original axes in its rotated state. For example, consider a simple rotation matrix around the z-axis (more on rotation matrices here). Let's say we plug in Pi / 2, in other words, we rotate counterclockwise at a right angle.

```
| cos(Pi/2) -sin(Pi/2) 0 |   | 0 -1  0 |    x-axis: ( 0, 1, 0)
| sin(Pi/2)  cos(Pi/2) 0 | = | 1  0  0 |    y-axis: (-1, 0, 0)
|    0          0      1 |   | 0  0  1 |    z-axis: ( 0, 0, 1)

```

Which is exactly what you'd expect. The z-axis stays the same. The x-axis rotates 90 degrees, to where the y-axis used to be, and the y-axis rotates 90 degrees further from that, to the negative x-axis.

In camera coördinates, I'm going to assume the following (which is free of choice):

* The x-axis (column 1) points to the right of your camera: the **right** vector.
* The y-axis (column 2) points upwards from your camera: the **up** vector.
* The z-axis (column 3) points straight out of your camera: the **forward** vector.

You already have your forward vector (I'm assuming that's the 'direc' vector you're talking about). However, the way you're calculating your up vector doesn't seem right. If you know the right hand rule, apply it twice for each of your cross products, and you'll end up with some vector pointing towards the negative y-axis, which is probably not what you want.

There's actually a few ways to calculate your remaining two vectors, but it's not quite clear what you're going for, so I'll give you the most straightforward (but least flexible) approach. We'll calculate the up vector always pointing as close towards the sky (which is to say, towards (0, 1, 0)) as possible. First make sure your **forward vector is normalized**. Then do this:

```
UP = (-Fx * Fy, Fx² + Fz², -Fy * Fz)
RIGHT = cross(UP, FORWARD)

```

with (Fx, Fy, Fz) being the forward vector. Normalize your up and right vector, plug all three of them in their respective columns in your rotation matrix, and you're done.

There's two drawbacks to this approach:

* It bugs out when your camera points perfectly up or down, so make sure that never happens by limiting your viewing angle.
* You can't easily 'roll' your camera around the z-axis (imagine tilting your head left or right).

Otherwise this should work fine.
> 5 votes

# Answer
As python code (assumes x to the right and y down in camera space):

```
def camera_rotation_matrix(pointing_direction: np.ndarray, up_vector: np.ndarray):
    forward = pointing_direction / np.linalg.norm(pointing_direction)
    right = np.cross(forward, up_vector)
    right /= np.linalg.norm(right)
    up = np.cross(forward, right)
    up /= np.linalg.norm(up)
    return np.column_stack((right, up, forward))

```
> 1 votes

---
Tags: rotation, matrix, transformation
---


# Question
Title: Flying AI shakes when chasing and avoiding obstacles simultaneously
I've got a problem with my flying AI in Unity. When it just chases a target it's ok, but my system contains avoiding obstacles so when it starts to do it, it shakes weirdly.

As I understood using `Debug.Log`, that happens because of simultaneous switching between chasing and avoiding obstacles. It's been biting me for several days, but I still don't know how to fix it.

Here's my code:

using Cinemachine;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class EnemyNew : MonoBehaviour
{
    [Header("Settings")]
    public int HP;
    public float speed;
    public float detectionRadius;
    public int gunsCount;
    public Vector3 stoppingDistance;
    public LayerMask obstacleLayer;
    [HideInInspector]public bool alive;
    [HideInInspector]public float distance;
    [Header("Components")]
    public Rocket target;
    private AudioSource audioSource;
    RaycastHit hit;
    void Start()
    {
        alive = true;
        audioSource = GetComponent<AudioSource>();
    }
    void FixedUpdate()
    {
        distance = Vector3.Distance(transform.position, target.transform.position);

        if(distance <= 100)
        {
            if (target.isAlive)
            {
                Vector3 direction = target.transform.position - transform.position;
                Physics.SphereCast(transform.position, transform.localScale.magnitude, direction, out hit, detectionRadius, obstacleLayer);
                if (hit.collider != null)
                {
                    Debug.Log("Avoidence");
                    Vector3 avoidanceDirection = Vector3.Cross(hit.point, hit.normal);
                    transform.position = Vector3.MoveTowards(transform.position, avoidanceDirection, speed * Time.deltaTime);
                }
                else
                {
                    Debug.Log("Movement");
                    transform.position = Vector3.MoveTowards(transform.position, target.transform.position + stoppingDistance, speed * Time.deltaTime);
                }
            }
        }
    }
```
</code></pre>

# Answer
If I'm understanding correctly, the issue is that you're oscillating back and forth between two states...

State 1 is when you're out of collision range and it moves normally.

State 2 is when it's avoiding an obstacle.

Since there are only two states, you're going to hit a scenario where avoidance moves you *just* far enough away to switch to moving, which could move you back into range, causing you to start avoiding, etc, etc...

Instead of having a hard, binary transition between the two states, why not fade/ease between them?

For example (untested):

```
if (target.isAlive)
{
    Vector3 direction = target.transform.position - transform.position;
    Physics.SphereCast(transform.position, transform.localScale.magnitude, direction, out hit, detectionRadius, obstacleLayer);

    //Calculate the "normal movement" position every time
    var movementResult = Vector3.MoveTowards(transform.position, target.transform.position + stoppingDistance, speed * Time.deltaTime);
    if (hit.collider != null)
    {
        Debug.Log("Avoidence");
        Vector3 avoidanceResult = Vector3.MoveTowards(transform.position, Vector3.Cross(hit.point, hit.normal), speed * Time.deltaTime);
        var distance = (transform.position - hit.point).magnitude;
        if(distance < ???) {
            // We're really close, just avoid.
            movementResult = avoidanceResult;
        } else {
           // We're close but not too close. Blend between normal movement and avoidance.

           var invProximity = distance / detectionRadius;
           movementResult = invProximity * movementResult + (1-invProximity) * avoidanceResult;
        }
    }
    transform.position = movementResult;
}

```

That way, as you cross the boundary where your avoidance code is triggered, there's no significant change, but as you get closer, you start avoiding harder.

It's up to you where you set the inner and outer "boundaries", but the idea is that outside the outer boundary, it's normal, inside the inner it's avoidance, and in between you cross fade.
> 0 votes

---
Tags: unity, c#, movement, ai, collision-avoidance
---


# Question
Title: How does planar shadow projection interact with perspective projection?
This question is about planar shadows as explained in Frank Luna's DX11 book. The author presents the 4x4 shadow matrix, whose bottom right element is **n**\\$\cdot\\$**L** (where **n** is the plane's normal and **L** is the light ray vector).

Projecting a shadow for a point **P** requires multiplying **P** by the shadow matrix, then dividing by the resulting *w* component (**n**\\$\cdot\\$**L**). He explains that the division is done as part of the perspective divide, however I fail to understand how it's carried out. Multiplying a projected shadow vertex by the perspective projection matrix overrides the vertex's *w* component with its *z* component. What am I missing here?

# Answer
> 1 votes
As mentioned in the question, the author makes a rather misleading statement:

> Observe that this equation modifies the *w*-component so that *sw*=**n**\\$\cdot\\$**L**. Thus, when the perspective divide takes place, each coordinate of **s** will be divided by **n**\\$\cdot\\$**L**; this is how we get the division by **n**\\$\cdot\\$**L** using matrices.

(The equation in question is the planar shadow projection equation.)

Transforming a projected shadow vertex into clip space using the perspective projection matrix does indeed override the vertex's *w* component with its *z* component, thus knocking out the **n**\\$\cdot\\$**L** factor. Therefore it doesn't play a role in the perspective divide and doesn't get factored into the NDCs.

To see why this results in a correct projection, suppose that we transform a vertex using the shadow matrix, then divide by **n**\\$\cdot\\$**L** and transform the resulting point into clip space using the perspective projection matrix. (It doesn't matter if we do the division before or after the transformations since it's a scalar, and scalar-matrix multiplication is commutative.) We end up with the same clip space coordinates we would get if we didn't do the division, except all coordinates are divided by **n**\\$\cdot\\$**L**.

Since all clip space coordinates are divided by **n**\\$\cdot\\$**L** (including the *w* component), the perspective divide will simply cancel it out. In other words, we can simply ignore the **n**\\$\cdot\\$**L** as it plays no factor in perspective projection, and the resulting NDCs are correct as if we performed the division to begin with.

---

## Caveats

Since we ignore the **n**\\$\cdot\\$**L**, the intermediate **clip space** coordinates are actually *incorrect* (in a matter of fact, any intermediate representation such as world space and view space coordinates would also be incorrect. Only NDCs are correct). As explained in the last paragraph, correct clip space coordinates should all be divided by **n**\\$\cdot\\$**L**. The problem is that the hardware uses the clip space coordinates for some fixed-function ops such as clipping and perspective-correct interpolation.

**n**\\$\cdot\\$**L** could be negative depending on the angle between the vectors. Negative **n**\\$\cdot\\$**L** means the clip space *z* component will also be negative even if the shadow is projected in front of the camera (since if we had done the division, it would be positive). In this case the hardware will clip the vertex out. To prevent that, the **L** direction should be chosen such that it points *towards* the light source.

Additionally, the hardware uses the clip space *w* component for perspective-correct interpolation of vertex shader output attributes. Since this coordinate is incorrect if not divided by **n**\\$\cdot\\$**L**, interpolation ends up incorrect. Therefore care must be taken to do the division if such attributes are needed. But for planar shadows we should be fine if we don't do anything in particular because the normal used for lighting is constant anyway (because we project onto planes) and shadows are colored black such that all light calculations end up being zero regardless of input factors.

---
Tags: directx, shadows, shadow-mapping, directxmath
---


# Question
Title: Seamless way to have touch be mapped to Input.mousePosition again in new input system
had not expected such a basic mapping to not come as default... what is the simplest way to do that simple mapping - that does not require modifying existing scripts?

# Answer
The whole idea of the new input system is to stop using the legacy `Input` class entirely. It's a full replacement, not just a few extra features.

If you want legacy scripts relying on `Input` to keep working unchanged, you can run both input systems under `Project Settings > Player > Active Input Handling`, as shown in the documentation:

This means you're asking your Unity game to do twice as much work piping input through two different systems every frame. It's OK during early migration and testing, but I'd strongly recommend biting the bullet and editing the old scripts so everything in your project uses the same input system.
> 0 votes

---
Tags: unity
---


# Question
Title: In Unity shaders, how is IN.worldRefl calculated?
I want to know how the world reflection vector in shaders is calculated so that I can manipulate it, but there is no documentation on what it does or how Unity calculates it. How is the reflection vector calculated and exactly what does it do?

# Answer
> 2 votes
The reflection vector is calculated as below:

```
float3 refl = 2.0 * o.Normal * dot(o.Normal, IN.viewDir) - IN.viewDir;
//float3 refl = IN.worldRefl;

```

That equation is similar to specular reflection.

---
Tags: unity, shaders, geometry, reflection-rendering
---


title: Pygame code/file structure

text:
# Question
Title: Pygame code/file structure
I am currently working on a Pygame project and would like to seek your advice on best practices for organizing my code, particularly when it comes to creating additional scripts. I find myself indecisive with where to place certain functionalities, such as handling grid lines and GUI components. For example I created my `Surface` in main file (where the game loop is) and then made a separate file named `grid.py` with this code:

```
def draw_lines(screen: pg.Surface, scroll_x):
    screen.fill((255, 255, 255))

    for line in range(MAX_COL):
        pg.draw.line(screen, "black", (line * TILE_SIZE - scroll_x, 0),
         (line * TILE_SIZE - scroll_x, HEIGHT))
    for line in range(MAX_ROW):
        pg.draw.line(screen, "black", (0, line * TILE_SIZE), (WIDTH, line * TILE_SIZE))

```

then am calling this function every time I iterate through the game loop. (I also need to import this function into my main file)

What I find out about this approach is that am creating many files with usually just a few functions and I wonder if there is some more efficient and elegant way to handle this things. Im open to any suggestions!

# Answer
> 0 votes
Creating many files is not bad practice in personal projects. It allows you to keep your code easily maintainable. However I would recommend planning what is game stuff and what is engine stuff (in your case you said GUI components and grid lines). Thoroughly defining what each piece of code belongs to will give you a better idea on how to group them. Therefore you will know naturally when it's appropriate to create separate files.

**Strictly my opinion that doesn't take into account what others say**, I found out that from coding a lot that grouping things in classes tends to give me more understanding of how the code should look like in the future (for possible refactoring).

---
Tags: architecture, python, pygame
---


# Question
Title: How to detect colored pixel of Sprite3D texture with perspective camera ray?
I've tried to ray cast my mouse position to Sprite3D on screen but I have some problems with it.

```
func _input(event):
    if event is InputEventMouse:
        mouse = event.position
    if event is InputEventMouseButton and event.pressed:
        if event.button_index == MOUSE_BUTTON_LEFT:
            get_selection()

func get_selection():
    var worldspace = player.camera_3d.get_world_3d().direct_space_state
    var start = player.camera_3d.project_ray_origin(mouse)
    var end = player.camera_3d.project_position(mouse, 1000)

    var query = PhysicsRayQueryParameters3D.create(start, end)

    var result = worldspace.intersect_ray(query)

```

**Brief setting of my project** My character/enemy is a Sprite3D in CharacterBody3D with small collision box only on its feet. I want the mouse to detect the shape of colored pixels of my character/enemy I saw on screen but intersect\_ray() always return with collider in the object, so it went through the character to the floor object instead.

**Why I don't set the collision box to match the height of sprite?** Camera is attached to player with 45 degree angle looking down to the player and it can zoom-in-out and tilt then it will look\_at() player again at its new position. While tilting, character's visual is also tilted to parallel with camera. So I think its collision box couldn't be the same size as sprite because sprite's height will be changing all the time and collision box cannot be tilted into the ground too.

```
visuals.rotation.x = camera_3d.rotation.x

```

**So my question is...** Is there a way to do a manual raycasting? or to calculate colored pixels' positions from characters/enemy on screen compare to mouse position and know if it's player or enemy. Please keep in mind that camera can zoom-in or zoom-out and tilting.

Thank you in advance

# Answer
Reading the pixels would involve getting the texture from the viewport and querying that. Which is doable, if somewhat annoying. It is similar to: How would I mask the player node out of a canvas shader?.

---

Instead I'm going to suggest to dedicate a physics layer for things you want to be able to pick up like this.

You can specify to your `PhysicsRayQueryParameters3D` what layers it should detect by setting its `collision_mask`, so it only picks objects that have the layer you want.

So you can have a second physics body (an `StaticBody3D` would do) which is in that dedicated layer and has a collider that matches the `Sprite3D` much closer.

That is, you can keep your current physics object with its collider which would have layer and mask that interact with the game world (this one could have a wide base, for example), and a second physics object that only has a layer that allows you to pick it up but won't interact with anything in the game world (so it can be thin and tall to better match the `Sprite3D`).

*You could rotate this second physics body to `look_at` the `get_viewport().get_camera_3d()` if you need to mimic billboarding. And you can also update its collision shape in runtime if needed.*

---

*By the way, your physic objects have a property `input_ray_pickable` which enables `_input_event`, if that works for you, it might save you some coding (you might not need `intersect_ray`). If it doesn't, having it enabled is a waste, so consider turning it off.*
> 1 votes

---
Tags: sprites, godot, raycasting
---


# Question
Title: c++ SFML Window in std::thread ignore animation
I have a main window whose loop is just in the program and a Window class in which separate `sf::RenderWindow` objects are created and the loops for them are in `std::thread`, so when adding a button to such a window, the animation is simply ignored, although if you add exactly the same button to the main window, then everything will work fine.

I run this function in the `std::thread`:

```
void Render() {

    sf::Event event;
    MSG msg = {};

    if (prepare_window_function != nullptr) {
        prepare_window_function(this);
    }

    while (Window_ptr->isOpen()) {

        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {

            if (msg.message == 160) {
                std::ofstream coords("DaTa_hats/_ParamS_/coords");
                coords << Window_ptr->getPosition().x << " " << Window_ptr->getPosition().y << std::endl;
                coords.close();
            }

            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        while (Window_ptr->pollEvent(event)) {

            if (event.type == sf::Event::KeyReleased and event.key.code == sf::Keyboard::D) {
                Developer_Mode = 1;
            }
            if (event.type == sf::Event::KeyReleased and event.key.code == sf::Keyboard::Escape) {
                Developer_Mode = 0;
            }

            Handle_Events(event);
        }

        Window_ptr->clear(sf::Color(100, 100, 100, 255));

        if (Is_Rendering) {
            Draw_All();
        }

        Window_ptr->display();

        if (Pause_After_Start) {
            Pause();
            Pause_After_Start = 0;
        }
    }
}

```

`Handel_Events` and `Draw_All` are functions from a DLL, their contents are the same as the functions of the main window

# Answer
I found the problem. I forgot to limit the frame rate, after adding: `setFramerateLimit(60)` it all works fine.
> 0 votes

---
Tags: c++, sfml
---


title: A good genetic system?

text:
# Question
Title: A good genetic system?
I was trying to come up with a genetic system for my game. However, after doing the math I found the system I had in mind won't really work.

Characters have 5 stats that can range from 0 to 12. What I was planning on doing was averaging each stat, and then rolling two numbers for each. The one that would be inherited for each stat would be the one closest to the average.

However, I found the bias isn't that great. For any number between 0 and 12, there's a 23/144 chance, or about a 15% chance of it occurring. This means say that if the two parents had a 12 in a score, there was an 85% chance about that the offspring's score would be lower than 12. Clearly, that isn't going to work. If both parents have the highest number, the odds should be weighed far more towards them.

I could increase the number of rolls, but adding more rolls decreases the odds of the farthest result too much.

If it matters, I'm trying to recreate the genetic system of The Sims 2. I have no idea how it generated its results, other than that all possibilities would possible but somehow weighted based on the parents. The totals of all 5 stats were also always between 25 and 35. I know how that was accomplished, but it doesn't help me with the first part.

I did think of an alternate method, but I don't like it much either. I was thinking of taking the averages of the parents, and then incrementing every stat at random x times, then doing it again x times but this time decrementing. This however doesn't work too well either. Either it would heavily weigh scores towards the middle, or it would make it nigh impossible for a child to match its parent. If I added too many increments/decrements, it would probably result in the final stats bearing no resemblence to the parents. I may as well just be starting with 0, and incrementing stats at random until a total of 30 is reached.

What would be a good system for my game?

update: Thinking about the latter system, I've come to realize its inherently flawed. The problem comes from the fact that the program has to either increment or decrement first. I could have it alternate back and forth, but it may not help much. The issue arises in the fact that no value can be raised above 12. I solved this by having the problem just skip over stats that are 12 when its incrementing, and skipping over values of 0 when its decrementing. This means that if a stat is 0, it has a 0% chance of being incremented, and the other four have a 25% chance of being incremented. When it switches to decrementing, all have a 20% chance of being decremented (assuming none of them are zero of course). Thus the 12 stat is more likely to be decremented than incremented, while the remaining stats are more likely to incremented instead. Stats of 0 would suffer the same problem, but in reverse. This means that this system actually evens out the numbers, and makes it nigh impossible to have a stat of 12 or 0. In order for that to happen, the program would have to in its six tries not chose these stats all six times. That's less than 1/5000 chance about. So clearly this system sucks. Thus I need to pick something more neutral.

There does need to be a randomization element to it. If I just had all the offspring's stats be the average of its parents, then all siblings would have the exact same stats. There has to be some way for them to vary.

# Answer
My approach would be to take three numbers per stat, mother, father and a random roll between 0 and 12, and then take the average. That will mean that the score will usually be somewhere between mother and father. But for exceptionally good or bad parents, there will be some regression to the mean, and for cases where both parents are very similar, there is a good chance that the child will be slightly better or worse than them. Extremely good or extremely bad values would be quite rare in this system, but possible.

This system could be refined further by changing the respective weights of the parents genes and the random factor.

However, this system doesn't have any guarantees about the sum of the stats. In order to then get a total sum between 25 and 35, I would then "normalize" the stats. I would do that by:

1. calculating their sum
2. divide that sum by the desired sum of 30 to get the factor of how much that sum is above or below the desired sum.
3. apply that factor by dividing each individual stat by it
4. round the results to the nearest integer.

Example:

```
A: 5
B: 7
C: 10
D: 5
E: 9

Sum: 36

```

This character is 36 / 30 = 1.2 times as good as they should be. So we divide all stats by 1.2 and then round them:

```
A: 5   / 1.2  = 4.166 ~= 4
B: 7   / 1.2  = 5.833 ~= 6
C: 10  / 1.2  = 8.333 ~= 8
D: 5   / 1.2  = 4.166 ~= 4
E: 9   / 1.2  = 7.5   ~= 8

Sum: 30

```

Note that if you have 5 values that sum up to 30, and you round each one up or down to the nearest integer, then you always end up somewhere between 25 and 35.
> 1 votes

# Answer
You could consider taking some inspiration from biology, emulating genes by making the visible stat just the "phenotype" expressed by an underlying "genotype" in the data used under the hood.

So for instance, instead of storing a stat as one number 0-12, maybe it's four separate "genes" each holding a value 0-3 (convenient to store in a "nibble" of 4 bits — half a byte), and the visible stat is the sum of these four genes.

So a sim with a 12 stat definitely has all 3 genes, but a sim with a 6 could have genotypes 0 0 3 3 or 1 1 2 2 or 0 1 2 3 etc.

When creating offspring, emulate crossover and dominance interactions between genes by randomly selecting two genes from each parent to make the four genetic components of the child's stat. Then you can add mutation by having a small chance that each gene mutates to a random value.

You can preferentially mutate-to-decrease when at the high end of the 25-35 total band, and mutate-to-increase at the low end, but without preferentially targeting 0s or 3s specifically. So an individual who's been tweaked to fit the target range can still have some extreme genes in the mix; they don't all gravitate to the average.

(Before any bio geeks storm the comments: yes, this is not how mitosis/mutation/etc. actually works. If you wanted, you could have each parent contain two copies of every gene, then pass on one of those two copies to the child, then have some rule for which copy/copies affect the stat... but I think that's more complex than you need to go for this feature, and the simplified approximation "loosely inspired" by biology gives fewer surprising results where a child gets all the parents' recessive genes and has drastically different stats, looking like a glitch)

With this approach, parents with high stats due to having a lot of 3s will tend to have children with a lot of 3s and similarly high stats, but not always, and likewise for low stats. The chance mutation still gives some chance of children having very different stats — any value *could* arise by mutation, but values not too different from the parents' are more likely — and you can control how often this happens by tuning the mutation rate.
> 1 votes

# Answer
To "see the parents" in their young ones you could implement following system: each stat has a 33.3% chance to be inherited from the father, 33.3% chance to be inherited from the mother and 33.4% chance to be a random values between 0 and 12. If the value is inherited from a parent you could make it a range of +-1 around that to not have the exact values of the parent.
At the end you can randomly increase/decrease values until you hit your desired total, but I would suggest to have a much greater chance to change the not-inherited values in this step as to not destroy the feeling of inheritance.
To make it even safer you could make a rule that always at least one stat is inherited from each parent, so you always have at least one stat where you can say: "I inherited that from my father/mother"
> 0 votes

---
Tags: mathematics, game-design
---


title: What is a "normal" in game development

text:
# Question
Title: What is a "normal" in game development
I'm new in Game development and probably this is a silly question. I had a look online but haven't found a clear answer, I did it bit quick but enough to evaluate that this is a confusing topic without prior experience.

The most topic I found regarding **normals** in game development they assume you already know what they talk about, but I don't.

I found this --\> https://relativity.net.au/gaming/java/normals.html which is helpful already but I'd like a more in depths explanation.

* What is a "normal" in game development?
* Why do we need it?

For context, I'm using Three.js which uses normals, here a 'helper' where you can visualize these 'normals arrows' https://threejs.org/docs/#examples/en/helpers/VertexNormalsHelper ThreeJs uses WebGL (OpenGL) and when setting a triangle manually, if you don't set the normals and add a material that is supposed to reflect the light it appears black. Well now that I think maybe, is because it needs to know what is up and what is down? Bit confused

# Answer
# Direct Answer

I see that other answer going into technical details, but I don't know if that hits the spot for answering "What are even normals" - so here's a plain English answer for contrast:

**A normal is the direction that a surface is facing.**

# Why does it not just use both sides?

A 3D model consists of points in 3D space (= "vertices"), 3 or more of which can be combined to form a surface that we can see (= "face").

In reality, if you have a surface-like-thing, like a sheet of paper, you can see it from both sides. But for the faces in 3D rendering, that would be a waste. Consider a 3D model of, let's say, a person: The faces on the back side, we only see from the back - because if we look at that model from the front, they are blocked by the faces that form that person's front side.

A normal allows us to easily identify those we don't need to render: Calculate the angle between the direction of your "camera" and a normal, and if it's smaller than 90°, you can skip it while rendering. Compared to other stuff, that angle calculation is such simple, fast math that we just saved roundabout half the effort - or in other words, doubled our performance.

# Use Case: Glass Shader

Consider a sheet of glass.

Glass has a certain visual effect (in real life) that I was never really aware of, until someone explicitly told me: If you look at that sheet "head-on", it's transparent. The more angled of a viewpoint you take, the less transparent it becomes - for example, becoming more and more green.

I'm spelling it out for completeness' sake, because you probably already see where this is going: A glass shader usually gradually replaces transparency with some green-ish or blue-ish colour, the smaller the angle between the camera and the glass normal gets.

# Use Case: Normal Map

Thing of the grooves in a brick wall: If you just make it a box with a texture, it will look very, well, flat. If you create a little 3D cube for every brick in there, the rendering engine will have to do a lot of extra work to calculate all that geometry, for something that's literally just a wall.

A "normal map" takes the x,y,z parts of a normal direction, and stores them in the r,g,b data of a pixel. That way, you get an "image" that looks kinda ugly , but where every pixel stores information about at which "angle" that part of the texture is:

A normal map can give it the illusion of it being 3D, because of the way the shadows move around the bricks when the light source moves. On the other hand, computationally it's extremely cheap: The renderer needs to draw every pixel anyway, it just uses the pixel-specific normal instead of the "global" normal for that surface - and the geometry is nothing more than a box.

The illusion of normal maps doesn't work at extreme angles, because then it becomes obvious that the thing is flat in 3D space. But for things like e.g. the floor, which you usually don't see that way, it adds a lot for little cost.

# Summary

There are other, and much more advanced things that people do with normals. However, those can fill whole books. In the same vein, some things in this answer are a bit simplified.

As a general summary, I would say rendering is simulating how light bounces off of things and then reaches our virtual camera, and *it is very helpful to know which way something is facing, when we want to simulate light reflecting off of it*.
> 44 votes

# Answer
In the context of geometry, a normal is a vector that is oriented perpendicular to a given object. It is commonly used for lighting calculations, but it can also be used to for calculating visibility, collision or situations where you need to know which way something is facing.

The article you linked also mentions the counter clockwise order of the points. That's also known as the winding & it's important because there's two vectors that are perpendicular to a plane:

The winding follows the handedness of the coordinate system. GPU pipelines use winding to perform backface culling and explicit normal data for shading.

Computationally, the normal to any two non zero vectors \\$p\\$ and \\$q\\$ is equal to their cross product \\$p \times q\\$. It's also possible to have vertex normals. Typically a vertex normal is computed as the normalized average of the surface normals of the polygons that contain that vertex.

But those aren't the only options and sometimes it's useful to use normals that differ from the geometry. For instance a normal map uses the RGB components of pixel within a texture to represent the XYZ components a normal. These can then be used in lighting calculation to simulate small displacements details without adding additional geometry.

As a corollary, if you have a model that renders incorrectly in a weird inside out sort off way, or the surface details look inverted, check the format for the normals and possibly the order of the points - using the wrong normals can cause things to point in the opposite of the intended direction.
> 33 votes

---
Tags: opengl, javascript, geometry, normals
---


title: Actual Custom Nodes in Godot

text:
# Question
Title: Actual Custom Nodes in Godot
So I am creating a plugin for Godot 4, and I want to create an actual custom node. What do I mean by that?

First to create a custom node I do:

```
@tool
extends CharacterBody2D
class_name Player2D

```

But the problem is, when adding the node, it keeps the same script. Easy fix though, create a new node to be added.

```
@tool
extends Player2D
class_name NewPlayer2D

```

but now we have a problem. It still keeps the same script. How do I create a node that I can add, that automatically starts with

```
extends Player2D

```

for me to use?

# Answer
> 1 votes
If you make an script like this:

```
@tool
extends CharacterBody2D
class_name Player2D

```

Then you can add a `CharacterBody2D` to your scene, give it an script, and it is write this:

```
extends Player2D

```

And it should work. *You might need to add `@tool` to it, depending on what you want it to do.*

*This has pushed me to make my scripts more reusable. As I often need to consider how to extend them other than adding an script to them. Some times that means creating nodes that expect to be placed as children of a node of an specific type. In other cases it means having a node interact with their children, or adding custom signals, or export nodes variables.*

---

If you were to add the custom class via en `EditoPlugin` with the now discouraged API `add_custom_type` instead of using `class_name` what you would gain is Godot preventing you from *removing* the script, and avoding a bit of namespace pollution. *Which for me be too little gain for the hassle, as `EditorPlugin`s also need to be enabled in the editor.*

However, I want to note that if you need custom behavior **in the editor**, you could create an `EditorPlugin` that handles your nodes (for your case it could handle `CharacterBody2D` for example), so the extra logic you need is not on a base class. *While the `EditorPlugin` won't execute in runtime, it can manipulate the scene in the editor, for example automatically adding other nodes with their own scripts, which would execute in runtime.*

---

However, it seems you want to be able to add a `Player2D` to the scene and have it appear without an script... In that case the `Player2D` class must not be an script. Which at the time of writing means to either:

This would also allow you to avoid overload from the GDScript runtime. Which makes it a good idea for performance critical code once other avenues of optimization have been exhausted. Also since it is less attractive for quick prototyping, the usual advice is to design what you want with GDScript and then port it.

---
Tags: godot, gdscript, godot-4, plugin
---


# Question
Title: What would be the best way to gradually increase the speed of a 2D arcade game with gravity physics in Unity?
I'm somewhat new to Unity, so I'd like to hear some more experienced thoughts on this. I'm using C# if that helps.

I'm currently working on an arcade game somewhat similar to "Doodle Jump" except, instead of controlling the character, you place platforms to prevent an AI character from falling.

I want to increase the speed of the game over time to make it progressively more difficult for the player. I initially tried just making the camera gradually accelerate upwards, but this made it so the character eventually doesn't fall quickly enough to keep up. Hence, I would like to increase the speed of *everything* in the level.

My current solution is as follows:

```
private void AccelerateLevel()
{
    Time.timeScale += timeIncrement;
}

```

I call this in `Update()` in the character's movement script.

However, as I understand it, this might not be consistent for different framerates - is that right? Is there a better way of doing this, or is this the best/most consistent way?

# Answer
> this might not be consistent for different framerates - is that right?

`Time.timeScale` is independent of framerate. Unity will continue to try to render at the same framerate regardless of time scale. However, time scale can affect performance and indirectly cause inconsistent behavior affected by framerate:

Increasing the time scale also increases the number of physics updates that must be performed per second of real time, unless you then increase the `Time.fixedDeltaTime` property. Increasing the `fixedDeltaTime` will affect the accuracy of the physics and eventually will lead to strange and undesired behavior.

If you have any expensive code which runs at regular intervals, increasing the time scale will make this expensive code run more often. As a simple example:

```
private IEnumerator UpdatePath() {
    var delay = new WaitForSeconds(.1f);
    while (true) {
        yield return delay;
        // For the sake of example, let's say this function is fairly slow:
        CalculateNewPath();
    }
}

```

In this example, we calculate a new path every 0.1 seconds of in-game time. At 60fps and the default time scale of 1, that would mean that we calculate the path every 6th frame. Now imagine we set the time scale to 6. Now we'll need to calculate the path every 60th of a second in real time, which means we're now running this expensive function every frame!

This example illustrates another issue - let's say that a player's device doesn't have good performance and can only manage 30fps. This means at a time scale of 1, they would run `CalculateNewPath()` every 3 frames. At a time scale of 6, they would need to run `CalculateNewPath()` every half of a frame (since `WaitForSeconds()` doesn't work like that, the function would still only get called once per frame, now every 0.2 seconds of scaled time)! This type of issue can force you to put all of your game logic into FixedUpdate() functions to ensure the code runs at the correct interval even if the framerate is low.
> 1 votes

---
Tags: unity, c#, rigidbody, timestep
---


# Question
Title: Game loop isn't performing well enough, so my frame rate is too low (Windows Form + GDI+)
I decided to learn about building games, so I picked up C# to use it along with Windows Form - I already have C# experience, so that was the main reason I did so. That said, I tasked myself to build a simple Windows Form app that renders a noise image targeting hopefully at 60 FPS. I'm using the GDI+ APIs to render bitmaps on screen; however, **I noticed the app isn't even close to render 60 FPS - it renders around 36-39 FPS on a release build.**

I should mention I'm a totally newbie in both Windows Form, and image rendering, so I believe my code isn't optimized at all. I'm sharing below the code snippet the app runs in order to loop infinitely to render the noise images.

```
    private static Bitmap GetStaticNoise(int width, int height)
    {
        var bitmap = new Bitmap(width, height);
        for (int y = 0; y < bitmap.Height; y++)
        {
            for (int x = 0; x < bitmap.Width; x++)
            {
                Color color = Color.Black;

                var rnd = Random.Shared.Next(0, 2);
                if (rnd % 2 == 0)
                {
                    color = Color.White;
                }

                bitmap.SetPixel(x, y, color);
            }
        }

        return bitmap;
    }

    private void Form1_Load(object? sender, EventArgs e)
    {
        Task.Factory.StartNew(() =>
        {
            var frameStopwatch = new Stopwatch();

            var screenGraphics = _screen.CreateGraphics();

            var font = new Font(FontFamily.GenericMonospace, 30);

            var ct = cts.Token;
            while (!ct.IsCancellationRequested)
            {
                for (int frame = 0; frame < 60; frame++)
                {
                    frameStopwatch.Restart();

                    // generates "noise"
                    Bitmap bitmap = GetStaticNoise(_screen.ClientSize.Width, _screen.ClientSize.Height);
                    screenGraphics.DrawImage(bitmap, new Point(0, 0));

                    bitmap.Dispose();

                    frameStopwatch.Stop();

                    screenGraphics.DrawString(frameStopwatch.ElapsedMilliseconds.ToString(), font, Brushes.Red, new Point(0, 0));

                    //Thread.Sleep(Math.Max(0, _frameCooldown.Milliseconds - (int)frameStopwatch.ElapsedMilliseconds));
                }
            }

        }, TaskCreationOptions.LongRunning);
    }

```

**Any advice about what could be changed here it's appreciated**. Also, any resource that could be useful to learn about using GDI+ for game development with Windows Form is also **appreciated** (or any resource that could help me understanding for instance this situation I'm running into).

Ah! the Windows Form is on `.NET 6.0`. I'm also attaching a picture of the bitmap rendered on screen (upper left corner shows the time in MS to render the frame)

**EDIT:** thank you so much for the comments, etc. I did follow the recommendations, and I realized I wasn't even hitting the FPS I mentioned above :(. I added a fps counter, and I'm seeing 29-30 FPS - I will update my code to use something different than GDI+ - and eventually use something else for developing games. I'm attaching below the updated code.

```
public partial class Form1 : Form
{
    private readonly Bitmap _bitmap;
    private readonly Graphics _bitmapGraphics;

private readonly Random _rnd = new Random();

private readonly int _whiteArg = Color.White.ToArgb();
private readonly int _blackArg = Color.Black.ToArgb();

private readonly int[] _noise;

private readonly PictureBox _screen;
private readonly Graphics _screenGraphics;

private readonly CancellationTokenSource cts = new CancellationTokenSource();

public Form1()
{
    InitializeComponent();

    _screen = new PictureBox
    {
        ClientSize = this.ClientSize
    };
    _screenGraphics = _screen.CreateGraphics();

    _bitmap = new Bitmap(_screen.ClientSize.Width, _screen.ClientSize.Height);
    _bitmapGraphics = Graphics.FromImage(_bitmap);

    _noise = new int[_screen.ClientSize.Width * _screen.ClientSize.Height];

    Controls.Add(_screen);

    this.Load += Form1_Load;
    this.FormClosing += Form1_FormClosing;
}

private void Form1_FormClosing(object? sender, FormClosingEventArgs e)
{
    cts.Cancel();
}

private void SetNoise()
{
    for (int i = 0; i < _noise.Length; i++)
    {
        int val = _rnd.Next(0, 2);

        _noise[i] = val == 1 ? _whiteArg : _blackArg;
    }

    var bitmapData = _bitmap.LockBits(new Rectangle(0, 0, _bitmap.Width, _bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

    var ptr = bitmapData.Scan0;

    System.Runtime.InteropServices.Marshal.Copy(_noise, 0, ptr, _noise.Length);

    _bitmap.UnlockBits(bitmapData);
}

private void Form1_Load(object? sender, EventArgs e)
{
    Task.Factory.StartNew(() =>
    {
        var ct = cts.Token;

        var font = new Font("Times New Roman", 32, FontStyle.Regular, GraphicsUnit.Pixel);

        var sw = new Stopwatch();

        int frames = 0;
        int lastFps = 0;
        long timeSpentInMs = 0;

        while (!ct.IsCancellationRequested)
        {
            sw.Start();

            SetNoise();

            sw.Stop();

            frames++;
            timeSpentInMs += sw.ElapsedMilliseconds;

            _bitmapGraphics.DrawString(lastFps.ToString(), font, Brushes.Red, 0, 0);
            _screenGraphics.DrawImage(_bitmap, new Point(0, 0));

            // a second has elapsed
            if (timeSpentInMs - 1_000 >= 0)
            {
                lastFps = frames;

                frames = 0;
                timeSpentInMs -= 1_000;
                sw.Reset();
            }
        }

    }, TaskCreationOptions.LongRunning);
}

```

}

# Answer
> 41 votes
TLDR: Get DirectBitmap from https://stackoverflow.com/a/34801225 and add

```
        public void SetPixel(int x, int y, int argb)
        {
            int index = x + (y * Width);

            Bits[index] = argb;
        }

```

then change GetStaticNoise to

```
        readonly static int white = Color.White.ToArgb();
        readonly static int black = Color.Black.ToArgb();
        readonly static Random NoiseRnd = new Random();
        private static DirectBitmap GetStaticNoise(int width, int height)
        {
            var bitmap = new DirectBitmap(width, height);
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    var rnd = NoiseRnd.Next(0, 2);

                    bitmap.SetPixel(x, y, rnd == 0 ? white : black);
                }
            }

            return bitmap;
        }

```

Long story: I have done stupid things in the past and know how to optimize your code

To start with, there is no need to guess when you can just ask code profiler to tell why your code is slow :)

Roughly 96% of CPU time is spent in `GetStaticNoise` in which major culprit is, unsurprisingly, `SetPixel`.

Before dealing with big fat pixel setting, lets take a look at other lines with surprisingly high CPU time.

* bitmap.Width and bitmap.Height does bunch of stuff under the hood.
* preset colors isn't a simple integer, but a fat object.
* Random.Shared creates Random object for each call. It is also thread-safe, which means there will be some performance cost hidden inside
* Ternary conditional operator generates different bytecode than full IF, and can be faster for conditional assignments

Few seconds of refactor later you get about +10% performance for "free".

You could optimize further by reusing Bitmap, but for that size would have to be either constant or hook into `OnSizeChanged` event.

Knowing that `SetPixel` is a performance hog, you can just search for "c# fast SetPixel" and just copy&paste ready to use solution from another SE post. Make sure to read through the comments on why it is not a perfect solution.

Lo and behold, performance increased tenfold just by not using SetPixel unnecessary safety logic.

But that ain't the end, let's run profiler again to get reminded that `Color` object sucks for game development.

With color already being prefetched, we can preconvert it as well and suddenly code is so fast that property getter becomes performance hog, taking whole 5%!

Chopping properties away you can reach spot where Random numbers takes longer to generate than SetPixel.

But at this point we have pretty much reached limits of software rendering on windows desktop. For faster performance you'll need to use GPU.

To clarify on using Ternary Operator as performance optimization: Two-element array is twice as fast as full If statement, and Ternary Operator is ~30% faster than array. Original code used modulo 2 to check parity, but with Random already returning only 0 or 1 it can be used without modulo for small performance gain.

But if you reorder IF statements slightly, you can squeeze out a bit more performance:  Have in mind that (ab)using array indexes as logic (pointers) should work better in native code, without all the fancy memory management of .NET. Or it might not, depending on performance tricks done by CPU's themselves. Micro optimizations are tricky.

However, if your loop is tight enough and dataset fits into cpu cache, results will become

In the end, the real winner is white\*0, but... that won't work in opaque ARGB colors, where A is 255.

TLDR: microoptimizations are hard and CPU doing its own tricks makes it even harder :)

# Answer
> 17 votes
When things bog down, check your inner loop. That's the code being run the most often, so even a small inefficiency there stacks up. Here we see:

```
Color color = Color.Black;

var rnd = Random.Shared.Next(0, 2);
if (rnd % 2 == 0)
{
    color = Color.White;
}

bitmap.SetPixel(x, y, color);

```

Two top suspects:

* `Random.Shared.Next(0, 2)` \- that "Shared" means this object is shared between threads, so to protect it from bugs when two threads try to generate a random number at the same time, there's probably a mutex (mutual exclusion) lock guarding it. That means for every single pixel, this code is acquiring and releasing a lock. That's relatively inexpensive when there are no other threads contesting it, but we have to check every time.

Make your own local instance of `Random` outside the loop and use that to avoid this overhead.

This is also using a heavier-duty random algorithm than you need (probably a Mersenne Twister). For a basic static effect like this, you could probably get away with a simple Xorshift or similar PRNG that you can run entirely out of L1 cache.
* `bitmap.SetPixel(x, y, color)` \- setting pixels one by one is often very slow, as we need to make sure the copy of the bitmap we're writing to isn't currently being used, take exclusive control of it, set one tiny bit of memory, then potentially re-upload the changed version to the GPU for rendering. (I don't know exactly what steps GDI uses though)

Game APIs will often expose a way to set the whole bitmap at once, which is much more efficient. We'll set our colour bits in our own buffer or array, then only at the end of the loop do we ask the bitmap to replace its entire contents with that array.

I'm not deeply familiar with GDI, but it looks like you can call `Bitmap.LockBits` to get access to the bitmap's `BitmapData` buffer before the loop, write all your data into that without extra overhead, then unlock it once at the end. (Thanks to Basic for suggesting a better route than I'd initially found!)

In a typical game context, we'd usually get this work off the CPU entirely and do noise generation on the GPU in a shader. That way we can process many pixels in parallel, rather than one at a time in sequence like CPU code. So you may want to consider switching from Windows Forms to a tech stack that makes it easier to offload graphics work this way. Engines like Godot and Unity both support C#, while giving you a richer toolbox of features that are helpful for game development.

# Answer
> 3 votes
I wonder, do you really need to render noise that is uniquely random down to the pixel?

Or would it be okay if it just *appears* random?

If you're alright with an approach that relies on staggered texture tiling instead of C# noise generation, please read on.

You may already be familiar with the cicada principle. The idea is that layering tiled images that repeat in prime number intervals makes the tiling less noticeable to the eye. This works for non-noise tiled image textures too, but is even less noticeable in the case of noise. Using transparency is one way to accomplish this. Another is blend modes.

A demo of the concept can even be constructed with a few still images and plain CSS.

359px

257px

193px

```
/* general appearance for demo */
    body {
      padding: 20px;
      background-color: #222;
    }
    .demo-cont {
      display: flex;
      justify-content: center;
    }
    .div-size {
      width: 50%;
      height: 360px;
      border-radius: 6px;
    }

    /* noise effect from here */
    .color-noise {
      background-repeat: repeat;
      background-position: center;
      background-blend-mode: hue;
      background-image:
        /* each image has a different prime number resolution */
        url(https://i.stack.imgur.com/ZWudq.png), /* 359px tile */
        url(https://i.stack.imgur.com/HiXuV.png), /* 257px tile */
        url(https://i.stack.imgur.com/3kPSN.png); /* 193px tile */
      background-size:
        /* CSS screen pixels are double-size, so halve that res to get the true resolution.
        Optionally, scale to fine-tune, or just create a more varied anti-aliased look. */
        calc(359px * 0.5),
        calc(257px * 0.55),
        calc(193px * 0.67);
    }

    @keyframes filter-anim {
      /* Rotating hue and over-saturating color "moves" the perceived brightness around.
      This remains visible in grayscale. */
      0%   {filter: hue-rotate(0deg)   saturate(4) grayscale(1);}
      100% {filter: hue-rotate(360deg) saturate(4) grayscale(1);}
    }

    .color-noise.animate {
      animation: filter-anim 0.5s infinite linear;
    }
```

```
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Cicada Noise</title>
</head>
<body>
  <div class="demo-cont">
    <div class="color-noise animate div-size"></div>
  </div>
</body>
</html>
```

I don't know if this approach will be suitable for your project, but it's a "think outside the box" sort of technique that may be more performant than traditional generated noise. If anyone tests this out, I would be curious to hear how it performs in your game. Cheers.

---
Tags: c#, graphics, performance, game-loop, windows-forms
---


# Question
Title: Unity RB Controller Jitter on a Moving Platform
**Brief Description:** I have a RB based character controller that I want to move along with my Train platform (non physics based) when the player steps on it.

**Main Problem** I manage to make the player follow the platform, but I also have a **camera jitter problem** that I can't solve without breaking player follow the Train platform logic.

**Video showing the jitter.**

**Important:** I'm not getting any jitter when only moving the camera

**Important:** I'm not getting any jitter when only moving the Character without moving the camera

this applies to both when the player is on a moving platform, or off the platform

https://www.youtube.com/watch?v=9M4dt00dEes

**My Camera Implementation**

For handling the camera I'm using Cinemachine, alongside a CameraHolder which is a separate gameobject from the player.

I'm setting the transform of the cameraHolder Gameobject to the players position in late Update

```
private void LateUpdate()
{
    transform.position = cameraPosition.position;
}

```

The Headbob Offset gameobject is a child in the cameraHolder without any movement.

**Player Controller Movement**

I'm using this code in FixedUpdate to handle my player movement

```
    private void HandleMovement()
{
    //old input system
    //float horizontal = Input.GetAxis("Horizontal");
    //float vertical = Input.GetAxis("Vertical");
    //Vector2 movementDir = new Vector2(horizontal, vertical).normalized;

    //New input system
    movementDir = GameInput.instance.GetMovementVectorNormalised();
    Vector3 currentVelocity = rb.velocity;
    Vector3 targetVelocity = new Vector3(movementDir.x, 0, movementDir.y);
    targetVelocity *= speed;

    targetVelocity = transform.TransformDirection(targetVelocity);

    Vector3 velocityChange = targetVelocity - currentVelocity;
    velocityChange = new Vector3(velocityChange.x, 0, velocityChange.z);

    Vector3.ClampMagnitude(velocityChange, maxForce);

    rb.AddForce(velocityChange, ForceMode.VelocityChange);
}

```

RB interpolation is set to Interpolate

**Train Platform Movement Script**

```
private void FixedUpdate()
{
transform.position += transform.forward * currentSpeed * Time.deltaTime;
}

```

**Important** I'm using FixedUpdate, but my train platform has no RB on it, I'm using FixedUpdate, because otherwise my player doesn't follow the train position change.

**What I've Tried so far**

**1. Lerping Camera Position**

Instead of setting the camera position to the cameraHolder, I tried lerping. It solved the overall jitter in the game, but my whole train platform became jiterry when moving.

```
        private void LateUpdate()
{
    transform.position = Vector3.Lerp(transform.position, cameraPosition.position, lerpSpeed * Time.deltaTime);
}

```

Videos showing the problem

jitter almost solved https://www.youtube.com/watch?v=sxXXk\_oVpsg Train jitter https://www.youtube.com/watch?v=85biDT\_nl\_4

**2. Add dumping to Cinemachine virtual camera**

results are the same as with lerping. everything else is smooth besides the train

I'll provide any necessary information if I haven't mentioned something here

# Answer
Changing FixedTimeStep to 0.01 from 0.02 resolved the jitter issue!
> 0 votes

---
Tags: unity, camera, moving-platforms, cinemachine
---


title: How to Code Rhythm Sync

text:
# Question
Title: How to Code Rhythm Sync
I'm trying to make an object's movement automatically sync to the music in Unity. I want a way to get the "key points" (when there is a loud beat) and make the object dash at those moments.

Basically, I just want the object to feel like it is synced with the music.

So how would I be able to get these points? A simple code or an explanation of a function I could use would be appreciated.

# Answer
> -1 votes
I used an open source code to do this.

It's a Unity project by retrogeek46 and the link is: https://github.com/retrogeek46/Beat-Detection---Unity

In the project there is a script which detects a beat and changes the cube's color (in the Update()) when a beat occurs.

---
Tags: unity, audio, music
---


# Question
Title: How to render a portion of a texture (upscaled) without affecting the border with SDL2?
I noticed that render a portion of the texture, upscaling it, it affects is border values with the proximity of the outside remaining parts of the texture (when not using Neareast neighbour interpolation)

This is a problem when those 2 portions are 2 different frames: basically it is interpolating the border with the outside of the texture when need rescaling.

This causes frame/sprite artifacts.

Consider a texture atlas with multiple frames next to each other. Copying one frame is resulting having the border interpolated with another frame and this most likely is creating an artifact.

Is there any way to strictly render a portion of texture making SDL Renderer ignoring whatever else is outside the rect?

Simply copy and rescale only the rect given?

e.g: The 2 frames:

1st frame on the bottom is altered by the values of the 2nd frame

2nd frame on the top is altered by the values of the 1st frame

This issue doesn't happen if adding 1 pixel pad among the 2 frames or using 1 texture per frame. I am wondering is there any SDL2 settings to avoid this unwanted (subpixels?) interpolation?

Please also note that all the operations are performed with exact integers, so don't understand really from where that "noise" could come from. Could it be from some Video drivers settings?

# Answer
The problem exists when not using Nearest Neighbors interpolation and upscaling textures.

I have solved this problem creating a padding around each frame of 2 pixels when loading and composing the texture atlas and added the padding when retrieving the frame area. Even though 1 pixel could be enough, but in general could be N pixel(s) depending on the case.

On the other hand it requires a little more memory to store all the frames.

An alternative could be to use 1 frame per texture eventually.
> 0 votes

---
Tags: textures, sdl2, scale, texture-atlas, rendertexture
---


# Question
Title: Calculating average ttk given accuracy and healing
I'm trying to calculate the expected ttk for weapons in my game but I'm having trouble because players can miss and enemies can heal.

Let's say an enemy has 100 health and every second you have a \\$p\\$ probability of dealing \\$d\\$ damage. The enemy heals for a consistent \\$h\\$ health per second.

I've broken it down to this piecewise recursive equation: $$ T(x) = \begin{cases} 0 & x\leq h \\ 1+p\*T(x+h-d)+(1-p)\*T(x+h) & h\lt x\leq 100 \\ T(100) & 100\lt x \end{cases} $$ where \\$T(x)\\$ represents the average ttk of the player in seconds given they are on \\$x\\$ health, but haven't made any progress on finding a closed form version.

# Answer
If an approximation is sufficient then on average the target will take *p\*d* damage per second and heal for *h*, so their net life loss will be *p\*d-h* per second. Assuming *p\*d-h* \> 0, the time to kill is approximately:

$$\frac{x}{p\*d-h}$$

The reason this is an approximation is that it does not take into account overkill damage. For example, against a 100 health target (with zero healing) weapons that deal 60 or 90 damage both take 2 shots to kill, but this formula will return a different value.

If you need an exact value, then there will be no nice closed form for this. The easiest approach is to simulate a lot of iterations, or you could build the health transitions into the state space of a Markov chain and compute the absorption (death) percentages at each second. I have a post on the statistics exchange with some python code for Markov chains, but it's probably not necessary for your use case.
> 3 votes

# Answer
## Partial answer: no healing

In your case the healing is the culprit, which makes the whole thing extremly hard to calculate. I hope my equation for the special case of h = 0 (no healing) helps you along the way.

Minimum amount of shots required \\$n\_{min}\\$ (all shots hit) $$ n\_{min}= \lceil\frac{x}{d}\rceil $$

Chance for a killing sequence of only hits (\\$n\_{min}\\$ shots and all hit): $$ P(n\_{min}) = p^{n\_{min}} $$

Chance for a killing sequence with \\$k\\$ misses (\\$n\_{min} + k\\$ shots) $$ p^{n\_{min}}\*(1-p)^{k} $$ Since the missed shots can happen anywhere in the sequence, we have to multiply this by the number of possible permutations. Since this is a form of Binomial distribution this would be: $$ {n\_{min}+k \choose n\_{min}} $$ But this contains also permutations that end in one or multiple missed shots, where the target would be already dead before the end of the sequence. So lets only account for those permutations that end in a hit. With one event fixed we have to substract 1 from top and bottom. $$ {n\_{min}+k-1 \choose n\_{min}-1} $$ This leads us to the formular to calculate the chance to need any amount of shots to kill the target.

$$ P(n\_{min}+k) = {n\_{min}+k-1 \choose n\_{min}-1} \*p^{n\_{min}}\*(1-p)^{k} $$

To get the average number of shots required, we multiply each chance with the amount of shots and sum everything up. Since it is possible to miss indefinetly, it is an infinite sum with ever shrinking summands.

The average number of shots neccessary (\\$n\_{avg}\\$)is : $$ n\_{avg} = \sum\_{k=0}^\infty( (n\_{min}+k)\*P(n\_{min}+k)) $$ $$ n\_{avg} = \sum\_{k=0}^\infty( (n\_{min}+k)\*{n\_{min}+k-1 \choose n\_{min}-1} \*p^{n\_{min}}\*(1-p)^{k} ) $$ Maybe someone else is able to fit the healing into this.
> 1 votes

---
Tags: mathematics, game-design
---


# Question
Title: How can I generate random lakes and rivers in my game?
I have a 2D block building game and am trying to make randomly generated lakes and rivers. I have looked into the Perlin noise algorithm, but, I couldn't get it to generate random and nice results.

I have been trying to use the python noise library, but, it didn't create maps very randomly.

Is there some seed function I am missing on that library to make it more random? What variable do I change if I want it to go more random? If possible, give me a less technical answer, with less math and more python terms.

The map is a 2D tiled map. Here is some examples of the non-randomness of the other algorithm. The following code was outputted 3 times in a row. I was randomizing the octaves and frequency with something like this: `freq = 16.0 * random.randint(1, 500000) * 0.000001 + 0.5`

```
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1
1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1
1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1
1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1
1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1

```

This is the code that produced the output above:

```
"""Writes a 256x256 grayscale simplex noise texture file in pgm format
(see http://netpbm.sourceforge.net/doc/pgm.html)
"""
# $Id: 2dtexture.py 21 2008-05-21 07:52:29Z casey.duncan $

import sys
from noise import pnoise2
import random
octaves = random.randint(1, 500000) * 0.000001 + 0.5
freq = 16.0 * octaves
for y in range(30):
    for x in range(40):
        n = int(pnoise2(x/freq, y / freq, 1)*10+3)
        if n>=1:
            n=1
        else:
            n=0
        print n,
    print

```

# Answer
Well, as it seems, you are not seeding the random number generator. In python, it can be easily done with just a random.seed().

And I can see too you're generating a number between 1 and 500000 and making it be between 0 and 1. It's a functional method, but it is capped to just 500000 possibilities. You're better with just using `random.random()` it already generates a number between 0 and 1, but with much more possibilities! If you still need a number between 0.5 and 1.0, as your code suggests, you could just do: `(random.random() * 0.5) + 0.5`

Your final code should look as follow:

```
import sys
from noise import pnoise2
import random
random.seed()
octaves = random.random()
# octaves = (random.random() * 0.5) + 0.5
freq = 16.0 * octaves
for y in range(30):
    for x in range(40):
        n = int(pnoise2(x/freq, y / freq, 1)*10+3)
        if n>=1:
            n=1
        else:
            n=0
        print n,
    print

```

That's all!
> 7 votes

# Answer
This isn't answering your specific programming question, but consider that creating lakes and rivers isn't about randomly placing blobs of water and strips of water between them. It's about terrain height - about depressions (basins) that turn into lakes, and water that flows from higher to lower spots.

If you want a great example of creating lakes and rivers that make sense, you might check out this blog post -\> http://simblob.blogspot.com/2010/09/polygon-map-generation-part-1.html It's a good reference for this kind of thing if your goal is reasonably realistic hydrography.
> 8 votes

# Answer
It's very simple: if you're getting the same map three times in a row (or more), it's because you didn't randomize the seed.

What does this mean?

Computers are inherently deterministic (non-random), so they simulate randomness. It's actually repeatably random (that's why we call it "pseudo random number generator").

How does this work?

When you create a random number, you have the option of giving it a "seed." The important thing is **if you always use the same seed, you will always get the same sequence of random numbers, in the same order.** Always. This can be good or bad.

In your case, it looks like you're not seeding the random generator, and by default, you're getting the same seed -- it probably uses some component of your date/time. Hence, I recommend you randomize it.

As Gusatavo mentioned in his answer, you need to call random.seed(). The docs state that "if X \[the default parameter\] is omitted or `None`, current system time is used." This should be sufficient.
> 2 votes

# Answer
*On the topic of rivers ...*

I came across some articles that mentioned modelling erosion from rain and use the resulting map as a base of a water flow map. The original article is gone now, sadly, but I could find a link at Wayback Machine, so added it for reference.

> **Erosion**
>
> ...
>
> In most of the world, by far the largest influence on the shape of landforms is fluvial (water-based) erosion. Water flows downhill, carrying sediment along with it, carving out valleys and river basins. This is a massively complex phenomenon, and modelling it correctly is a very active research area, but we can get a long way by sketching a simple version of the process.
>
> We need to start by tracing the routes that water would take over the grid. For each grid point, we say that water flows to its lowest neighbour, and so on down until we reach the edge of the map. This gives a map of water flow.
>
> There's an obvious problem when we reach gridpoints which are lower than all of their neighbours. Do we route the water back uphill? This will probably lead to cycles in the water system, which are trouble. Instead, we want to fill in these gaps (often called sinks or depressions), so that the water always runs downhill all the way to the edge.
>
> It's easy to see how to fill in a single gridpoint, but as the depression gets bigger, and possibly links up with other depressions, the number of possible cases multiplies enormously. Luckily, there's an algorithm for filling depressions, called the Planchon-Darboux algorithm.

> **The Planchon-Darboux algorithm**
>
> The algorithm works by finding the lowest surface with the following two properties:
>
> * The surface is everywhere at least as high as the input surface.
> * Every non-edge point has a neighbor which is lower than it.
>
> To calculate this, we start with an infinitely high surface everywhere except on the edge, where we use the original heights. Then, on each iteration, we find points which have a neighbor which is lower than them, and set their height to their original height, or the height of their lowest neighbor (plus a small amount), whichever is higher. We halt when we can go a full iteration without changing any point.

> With the water routing calculated, we can work out how much water is flowing through each point. I assume that rainfall is constant across the whole map, and iterate through the points in descending order, passing the rainfall, plus the accumulated water flux, from each point to its 'downhill point'. This gives a map of water flux, which usually converges into a nice branching river structure, with lots of small streams feeding a larger central channel.

Source: http://web.archive.org/web/20230523171532/http://mewo2.com/notes/terrain/

Here's an example of the Planchon-Darboux algorithm implemented in C++

```
void gen::MapGenerator::_fillDepressions() {
    NodeMap<double> finalHeightMap(&_vertexMap, _heightMap.max());
    dcel::Vertex v;
    for (unsigned int i = 0; i < _vertexMap.edge.size(); i++) {
        v = _vertexMap.edge[i];
        finalHeightMap.set(v, _heightMap(v));
    }

    double eps = 1e-5;
    std::vector<int> *neighbours;
    for (;;) {
        bool heightUpdated = false;
        for (unsigned int i = 0; i < _heightMap.size(); i++) {
            if (_heightMap(i) == finalHeightMap(i)) {
                continue;
            }

            neighbours = _neighbourMap.getPointer(i);
            for (unsigned int nidx = 0; nidx < neighbours->size(); nidx++) {
                double nval = finalHeightMap(neighbours->at(nidx));
                if (_heightMap(i) >= nval + eps) {
                    finalHeightMap.set(i, _heightMap(i));
                    heightUpdated = true;
                    break;
                }

                double hval = nval + eps;
                if ((finalHeightMap(i) > hval) && (hval > _heightMap(i))) {
                    finalHeightMap.set(i, hval);
                    heightUpdated = true;
                }
            }
        }

        if (!heightUpdated) {
            break;
        }
    }

    _heightMap = finalHeightMap;
}

```

Source: https://github.com/rlguy/FantasyMapGenerator/blob/master/src/mapgenerator.cpp

---

Other links and/or approaches that could be interesting:
> 0 votes

---
Tags: 2d, python, procedural-generation, perlin-noise
---


# Question
Title: Converting number in name of gameobject into alpha keycode
So I have no idea if there is a way to do this, but I'm trying to find a way to turn an alpha number in a game object name string into an Alpha key code, which I'm going to use in an Input.GetKey. Heres my code:

```
string slot = transform.parent.parent.name;
string refinedSlot = slot[11];
KeyCode keySlot = KeyCode.Alpha/*refinedSlot*/;

```

Thanks in advance. I also know that refinedSlot is probably useless, but I added it in case it might be usefull.

# Answer
If `slot` is a `string` then `slot[11]` is one character of this string and is of type `char`.

Fortunately the digits in Unity's `KeyCode` Enum are backed by the same integer value as the corresponding characters. Therefore, we can simply cast the character to this `KeyCode` enum.

```
string slot = transform.parent.parent.name;
char refinedSlot = slot[11];
KeyCode keySlot = (KeyCode)refinedSlot;

```

A safer way to extract the last character of a string (whose exact length needs not to be known) is to use the C# 8.0 Indices and ranges feature. By eliminating the temp variables, we get

```
var keySlot = (KeyCode)transform.parent.parent.name[^1];

```
> 1 votes

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