# Question
Title: Trouble adding C++ actor component to blueprint in Unreal 5
I'm a veteran C++ dev, but so far I've only been working with blueprints in Unreal. I'm now attempting to mix the two.

I have a blueprint actor I'd like to attach a component to, but the actor component is defined as a C++ class. The class doesn't show up in the editor as an addable component. As far as UE5 is concerned, that class doesn't exist (even though I used "Tools-\>New C++ Class" to create it).

I have "meta=(BlueprintSpawnableComponent)" in the UCLASS definition at the top of the header. So far, everything is just as UE generated it - no changes.

I've tried building the solution through VS and also restarting UE to no avail. I noticed the .cpp and .h for the new class weren't included in the VS solution by default, so I had to add them manually. That also did not fix the problem. I'm getting roughly 10k errors when I try to build in VS, but it's my understanding that I should ignore those.

# Answer
> 1 votes
Apparently the VS solution has to be regenerated, and it's done via windows explorer and not the unreal editor. I right clicked the UE5 project file and selected "Generate Visual Studio Project Files". I had to install a .net runtime I was missing before it would work. Afterward, I was able to find the class in UE5 and add the component to the actor.

---
Tags: c++, unreal, blueprints, unreal-5
---


# Question
Title: How to read a data from text file in unity
Can anybody help me out with giving the steps needed for reading data from the text file in unity and how can the script be added.

# Answer
> 11 votes
## C# Version.

```
using System.IO;

void readTextFile(string file_path)
{
   StreamReader inp_stm = new StreamReader(file_path);

   while(!inp_stm.EndOfStream)
   {
       string inp_ln = inp_stm.ReadLine( );
       // Do Something with the input.
   }

   inp_stm.Close( );
}

```

EDIT: (Fixed an error on line 9; changed "stm.ReadLine();" to "inp\_stm.ReadLine();")

# Answer
> 30 votes
There's a class named TextAssets which is used for text file reading. http://docs.unity3d.com/Manual/class-TextAsset.html Here you can find the supported file format.

So if you want to read the text file, the script would be like this:

```
class YourClassName : MonoBehaviour{
    public TextAsset textFile;     // drop your file here in inspector

    void Start(){
        string text = textFile.text;  //this is the content as string
        byte[] byteText = textFile.bytes;  //this is the content as byte array
    }
}

```

or you can read the text as resource like this:

```
TextAsset text = Resources.Load("YourFilePath") as TextAsset;

```

# Answer
> 6 votes
You can do this in the same way you would in .NET

```
string word = File.ReadAllText(txtFilePath);

```

This code snippet can be used in any location you wish then.

# Answer
> 3 votes
This code is working fine for me to read the content in the text file

```
import System.IO;

var filename = "data.txt";

function Start () {
    var source = new StreamReader(Application.dataPath + "/" + filename);
    var fileContents = source.ReadToEnd();
    source.Close();
    var lines = fileContents.Split("\n"[0]);
    for(line in lines) {
        print(line);
    }
}

```

# Answer
> 0 votes
We can use `TextAsset` data type to access text file content in Unity3D.

Try the following code,

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

public class Global : MonoBehaviour
{
    public TextAsset textFile;

    // Start is called before the first frame update
    void Start()
    {
        getFileContents();
    }

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

    }

    void getFileContents() {
        string data = textFile.text.Split('\n');
        for(line in data) {
            Debug.Log(line);
        }
    }
}

```

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


title: Making a 2D Grid Map UI in Unity

text:
# Question
Title: Making a 2D Grid Map UI in Unity
I am trying to make a simple 2D square grid for a map UI. The game itself is also 2D and the player can only make discrete movements between the square, but the player view is first person (you see a painted view of the scenery at that square), so the 2D square map is just for the map, not the main game view.

So the map would look something like this:

This would be used in the minimap, and also in a semi-fullscreen overlay map view that the player can pull up.

What is the best way to do this in Unity?

I tried using a GridLayoutGroup and adding one Image child for each square. For a simple 100x100 map, though, this leads to 10,000 game objects each just representing one tile in the map.

It seems like this is what Tilemaps would be good at, but I don't see a way to use Tilemaps in the minimap or an overlay on top of the main view.

# Answer
> 2 votes
You could use a setup with two cameras. The first one pointing at the 1st person view of the player. The second one pointing at a Tilemap and rendering to a render texture by setting that render texture as the "Target Texture" in the camera component. That render texture can then be used as the source texture of a RawImage UI object. So you can place that minimap window on a canvas, just like any other UI object.

Which camera renders what can be controlled via layers. Or alternatively you can just try to design the spacial layout of your scene in a way that the two cameras and the things they render never get close enough to each other for anything to ever appear in the field of view of the wrong camera. Usually I would not advise that (because you never know how your scene might evolve), but your use-case sounds simple enough that it could work.

---
Tags: unity, 2d, tilemap, tiles, minimap
---


# Question
Title: Why are we not using integers in game physics?
We can use integer for game physics (or without physics, simply object representation): mass, position and rotation, where the integers represent, for example, the number of milligrams, millimeters or (1/56000) of a degree. However, almost all game code I've seen *recently* use floating points.

Is it slower to use integers for game physics calculations? Are there any other advantages and disadvantages from the developer's point of view for using integers? Or it is because all our hardwares

# Answer
The days where floating point computations were (significantly) slower than integer calculations are long gone. If I'm not mistaken it was the Pentium CPU that first leveled the playing field of floats vs integers.

So there's actually no reason whatsoever to not use float (or even double) for any calculation that benefits from it. The use of integers to represent floating points was just a crook in order to avoid the performance impact of floating point calculations on older hardware.

In fact modern (desktop) CPUs don't even make much of a difference between float and double, especially on 64bit CPUs running a 64bit OS.
> 8 votes

# Answer
You *can* use integers for the **inputs** to your physics system. Although you're likely going to have to use non-standard units of measure. Typically we see meters per second, kilograms, etc. Using smaller units just so we can more easily round the values to whole numbers isn't hard, it's just kind of silly.

However, as soon as you want to perform any calculations, you're going to want to use floats, not integers. Any formula that has a division involved is going to want to use floating point values.

The reason we use floating point values is because it's closer to what we use in mathematics and real world physics. There's no reason to constrain ourselves to integers. Floating point calculations are very fast on modern CPUs.
> 1 votes

# Answer
I would add here that there is a reason to consider alternative physics models than floating points in applications like when having a large world in games. Typically, the farther from the origin you go, the less space you have for digits and thus the lower precision your calculations have. This causes rounding errors to accumulate and physics to break. Some games where this limitation is observed include Minecraft, BeamNG, and VR Chat. I'm unsure if it's actually worth it (or is practical) to use a pure integer model to fix this since it can be fixed with other methods. For example, having many origins with a number ID and simply cycling between them such that floating numbers never get high enough to lose precision.
> 1 votes

---
Tags: physics, performance
---


# Question
Title: XR Hands don't appear when I put down controllers
I'm trying to get hand tracking working in Unity using the XR Interaction Toolkit (XRI) and XR Hands.

I'm testing this in the Unity Editor on an Oculus/Meta Quest 2 headset via Oculus Link or Air Link.

I put my controllers down, but the hand prefabs aren't appearing as if the cameras never see my hands.

# Answer
Ensure that the Oculus/Meta Quest app is set as the default OpenXR runtime. You can do this by opening the Oculus app going to Settings and changing "OpenXR Runtime" as seen in the screen shot.
> 0 votes

---
Tags: unity, virtual-reality
---


# Question
Title: Do you need to know JavaScript to make games with RPG Maker?
Do I have to know how to code in JavaScript to make good games in RPG Maker MZ? I'm asking cause I know you don't really have to code in RPG Maker. I already tried some programming languages, so I have some experience.

# Answer
This is fairly subjective, since it depends on your thresholds for deeming a game to be "good". But what we can say objectively is that all versions of RPG Maker contain their own scripting system you can use without writing any JavaScript, and which is sufficient for implementing conventional RPG mechanics.

I'll say the user experience of scripting with this system is not great — it's lots of repetitive clicking to create even simple scripts, but it is doable.

You can also incorporate existing plugins made for the engine, to customize it beyond the default template without writing new JavaScript yourself (instead leveraging JavaScript that others have written).

No matter what interface you're using to create your scripts though, you'll still be using all the same programming skills. The difference is just syntax, and how readily the language exposes the features you want for a specific game mechanic. So if you're going to have to learn a kind of programming to use the in-engine scripting anyway, you might as well learn JavaScript or whatever other language works with the engine of your choice.
> 4 votes

---
Tags: javascript, rpg-maker
---


# Question
Title: Is Unreal Engine using Monte Carlo path tracing or similar methods?
Is Unreal Engine using Monte Carlo path tracing or similar methods in which efficient pseudo random number generators are crucial to make their renders?

I know it is needed for typical renders, but if you create some world in the game, do you also make render of the world?

As someone suggested in comments I'll explain why I'm interested in that topic. I'm interested in PRNG generators and I'm working on my own. I'm wondering if a game developer or Unreal Engine could benefit significantly if, for example, they had a PRNG generator that was 2 times faster than the best generators currently available. The fact that there will be benefits in Monte Carlo path tracing method itself is clear, but I don't know how important this method is in games.

# Answer
Monte Carlo path tracing is more commonly used for offline renders — when you can spend between many seconds to sometimes hours rendering a single frame.

Realtime games have a time budget of milliseconds, so this method is still too slow for drawing frames on demand during gameplay. Instead, games are typically rendered with rasterization, with some special effects filled in with raytracing or raymarching (usually with only single rays per pixel, rather than accumulating hundreds of distinct paths as in MCPT).

It's possible to use slower rendering processes as a pre-processing step at build time, like baking a lightmap that encodes global illumination. Monte Carlo path tracing could potentially be used here, but I'm not familiar enough with Unreal's global illumination features to say for sure whether that's a technique they use.
> 1 votes

# Answer
Unreal does actually include a path tracing renderer, but it's not a real time one.

It serves a couple of purposes:

* A "ground truth" reference to help develop real time approximations to the slow but accurate path-traced result result.
* High quality non-realtime rendering (e.g. video creation).

The path tracer is documented at https://docs.unrealengine.com/5.2/en-US/path-tracer-in-unreal-engine/
> 3 votes

---
Tags: rendering, unreal-5
---


title: How to compute visible area of a sphere

text:
# Question
Title: How to compute visible area of a sphere
I have a number of spheres in my scene. I also have another object that I want to scale depending on the amount of a selected sphere that is visible (it can be occluded by multiple other spheres passing in front of it). Can anyone recommend an efficient way to accomplish this? My renderer is written in Metal. The calculation only depends on the visible region of one selected sphere.

# Answer
Trying to do this analytically will get intractable very very fast - adding each new sphere will increase the complexity substantially (not sure if it is exponential or not, need to think about that), as each pair of spheres needs to be checked for overlap so you don't double count.

Assuming that you are using view coordinates and don't need super high accuracy, one approach is rendering into an off screen buffer with the selected sphere set to one particular color, and the other spheres a different color or black. Use whatever resolution you need to get the desired accuracy and count pixels of the selected color.

It looks like you can then do the pixel counting on the GPU, which is great in this case, because the buffer is already there: https://stackoverflow.com/questions/44346198/counting-coloured-pixels-on-the-gpu-theory

Of course, this approach doesn't work if you want it in terms of sphere surface area.
> 2 votes

---
Tags: shaders, sphere, occlusion, metal
---


# Question
Title: Custom TextMeshPro Shader doesn't render on Android
I wanted to make build of a project using custom shader for TextMeshPro text assets. It renders nicely on PC but It gives me block instead when build for the meta Quest 2. For me it looks like it doesn't read the alpha from the atlas assets, thus giving block instead of cutout. Is there a way to prevent this behaviour, in build option or shader ?

Screenshot from unity scene panel (same result in PCVR build)

Screenshot from quest 2 build (android)

Here is the shader (URP)

```
Shader "Unlit/InvertFontAtlas"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent" }
        Cull off

        Blend SrcAlpha OneMinusSrcAlpha
        AlphaToMask On

        Blend OneMinusDstColor Zero
        AlphaToMask On

        Pass
        {
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.0 Alpha:Blend

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

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

            sampler2D _MainTex;

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

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col;
                col.rgb = _Color;
                col.a = tex2D(_MainTex, i.uv).a;

                return col;

            }

            ENDCG

        }

    }
    FallBack "Diffuse"
}

```

**ANSWER:**

As mentionned by Kevin the *AlphaToMask On* does not render on Android setup. the workaround is to use the clip(alpha - 0.1). It works better with TextMeshPro clip with 0.5 value instead of 0.1 which gives a bolder font. So the corrected shader looks like that:

```
Shader "Unlit/InvertFontAtlas"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent" }
        Cull off

        Blend SrcAlpha OneMinusSrcAlpha
        //AlphaToMask On

        Blend OneMinusDstColor Zero
        //AlphaToMask On

        Pass
        {
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.0 Alpha:Blend

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

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

            sampler2D _MainTex;

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

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col;
                col.rgb = _Color;
                col.a = tex2D(_MainTex, i.uv).a;
                // here the clip line
                clip(col.a - 0.5);
                return col;

            }

            ENDCG

        }

    }
    FallBack "Diffuse"
}

```

# Answer
The `AlphaToMask` flag is intended for use with multisample anti-aliasing MSAA. It's possible that you're using a different quality setting in the Editor than on mobile; if I recall correctly, MSAA is disabled in the default quality setting that is applied to mobile devices.

In general, I would not recommend using MSAA on mobile devices due to the high performance cost.

Additionally, on the Unity forums, bgolus (who is the forums' leading expert on shaders) reports that AlphaToMask is not supported on all Android devices. However, he recommends a simple workaround:

> Just adding the below line will fix it.

```
clip(alpha - 0.1);

```

> Replace `alpha` with whatever your shader's output alpha is just before the return. That solution will also actually fix the "unsolvable" problem too as it'll ensure alpha testing is being used in the cases that the hardware or drivers aren't properly supporting it.
> 2 votes

---
Tags: unity, android, shaders, oculus, text-mesh-pro
---


title: Name for groups of cards in a card game

text:
# Question
Title: Name for groups of cards in a card game
What would you call the groups of cards in a card game, including both piles (draw, discard...) and hands?

I'm coding a generic card game engine and I've been unable to find a good name for the base class from which Pile and Hand would inherit. I've temporarily named it Group but it's way too vague.

Ideas: CardGroup, CardSet, Position, Stack...

# Answer
In Magic the Gathering, the different places that cards or other objects can exist in are called ***zones***. Your hand is a zone, your deck is a zone, your discard pile is a zone, etc. Zones have different characteristics defining whether they are publicly or privately visible, which player can access them, and whether the card order matters. This may or may not be a good level of abstraction as it doesn't really refer to the groups of cards themselves but rather the places those groups exist, as some zones can contain things other than cards.
> 2 votes

# Answer
When I did this a couple years ago, I called them all "piles", and a hand (fan) was just a special subcategory of pile that could hover off-table and have private visibility to one player.
> 3 votes

---
Tags: terminology, oop, card-game
---


# Question
Title: How to subscribe for events for easy unit testing?
I've run into the same problem multiple times that is begging for a solution. I try to write a lot of decoupled code to make my MonoBehaviour scripts as reusable as possible. This means that I end up using events sometimes. However, when I try to unit test my code I always run into problems with events.

I usually subscribe and unsubscribe to events in OnEnable and OnDisable (sometimes Awake and OnDestroy). However, when writing my unit tests, then I can't test any behaviour dependent on such events since these Unity event functions don't get called in a unit test.

I've tried making the unity event functions public for testing purposes. But this seems to seriously break encapsulation. I've also made functions like public ListenToEvents() that does all the event subscribing, and gets called from OnEnable() and can then also be called in my unit test.

I've read in many places (and see the reasons why) you should never make something public just for unit testing purposes, but I'm struggling how to get event-related behaviour to be tested.

I know about the Humble Object Pattern, which I think could be a good solution here. However, I really like having a single script I can share with myself or someone else for reuse, and this tends to create additional classes/files.

A common example I'm having trouble testing is something like the following MonoBehaviour code (untested code)

```
bool ignoreInput = false;

void OnEnable() {
    KeyboardEvents.OnIgnoreAllInput += IgnoreInput;
}

void OnDisable() {
    KeyboardEvents.OnIgnoreAllInput -= IgnoreInput;
}

void IgnoreInput() {
    ignoreInput = true;
}

public void UpdateMovement() {
    if (ignoreInput) return;

    // trying to unit test this
    if (Input.GetKeyDown(Keycode.A) {
        MoveForward();
    }
    else {
        DontMove();
    }
}

```

the issue with the above code, is that I can unit test MoveForward and DontMove, but I can't unit test whether they are correctly controlled by ignoreInput, since in my unit test there's no way (as written) to get OnEnable and OnDisable to be called. I'm also aware of Unity PlayMode tests, that do call such methods, but these are very clunky and slow to run and as far as I can tell can't be called from an IDE.

Ideally my unit test would be something like this:

```
ScriptUnderTest testScript = new GameObject().AddComponent<ScriptUnderTest>();
KeyboardEvents.IgnoreAllInput();
testScript.UpdateMovement();
Assert.That( <Some result of DontMove happened> )

```

This test always fails because OnEnable is not being called, and so invoking the event does nothing to the script.

I'd love know how to better set up the MonoBehaviour to make this test work.

Side Question: Do you subscribe to events in OnEnable? Is there a best practice for where in monobehaviours to do this?

# Answer
> -1 votes
The MonoBehaviour that is being tested requires the `[ExecuteInEditMode]` for special Unity methods to be executed in edit mode tests.

```
[ExecuteInEditMode]
public class SomeMonoBehaviour : MonoBehaviour {...}

```

This will call classes such as `OnEnable()` and `OnDisable()` methods during edit mode tests, so that subscribed events are also called as part of the test.

Note that this will also subscribe to the events when using the editor.

---
Tags: unity, events, monobehaviour, unit-testing
---


# Question
Title: Why can't I edit the rotation property in prefab mode so that rotation changes apply to all instances?
I am learning using the Explore Unity Course. In the picture you can see I've instantiated many hats from the same prefab.

I want to rotate the hat in prefab mode so that the change will apply to all hats, but the rotation property is inactive, as shown in the picture.

Why can't I edit the rotation property in prefab mode? Is there a way to rotate all the hats at once?

# Answer
When you spawn a prefab instance, it gets its own position and rotation, so those properties are effectively overridden on all instances.

What you can do if you want to flip the hat upright is tick the "Flip X" and "Flip Y" checkboxes in the SpriteRenderer component - this will do the same thing visually as a 180 degree rotation.

If you want to be able to control rotation of all instances at once to a finer degree, you can set up a hierarchy like so:

* Prefab root & rigidbody
    + Hat sprite & collider

Then you can rotate the hat visual within its parent, and all prefab instances will have their visible child rotate the same way, since only the root's transform is overridden by default.
> 2 votes

---
Tags: unity, rotation, prefabs
---


# Question
Title: Terrain object's textures flickering on long distances
I'm making RTS project on Unity3D.

I created terrain with Unity's standard Terrain tool, and added textures of grass, mood etc. on it. Then, for creating "man-made" objects of terrain (roads, sidewalks, road curbs etc) - I'm created this objects in separate assets, and placed on terrain.

And I have one issue with this solution. On moving camera away from the terrain, terrain's texture(e.g. mood) are flickering under roads, sidewalks and other objects. AFAIK, this bug caused by insuficcient accuracy of floating-point coordinates in Unity3D engine (?).

Now, as I concerned, my approach to creating terrain objects is not correct. I must create one mesh with terrain, and all manmade objects in 3D modeling software, and then create UV-map for texturing all of it. Is this approach correct? If "yes", is any special approach for modelling and texturing so large and complex object as terrain?

# Answer
> 2 votes
What you are experiencing is commonly referred to as Z-figthing. That might help with finding some additional leads/ideas. And I would not call it a "bug", just a regular challenge in 3D applications.

Changing the far and near clipping plane values can help with the Z-buffer resolution, more specifically increasing the value for the near plane (see this exaplantion):

> Remember that the key to Z-fighting is the ratio between the near and far planes.
>
> For example:
>
> Near: 0.1, Far: 1000
>
> Near: 0.5, Far: 1000
>
> You've only offset your near plane by 0.4 world units. It's not a huge distance. The ratio between your near and far planes just improved 5 fold, however.
>
> So don't just automatically crank down the far plane, as you can often get more mileage cranking up the near plane. Often without much/any noticeable difference too!
>
> Also, you should remember that the z-buffer is not linear. So you inherently get greater precision closer to the camera than you do further away. This is logical and helpful, but it makes it even more important not to needlessly set your nearplane too low or you're wasting a huge proportion of your z-precision on things you don't need/won't see.

Some further potentially helpful links:

# Answer
> 0 votes
I am probably late, but, I made the following videos which solve many flickering issues:

https://www.youtube.com/watch?v=Lls93SG94Os

---
Tags: unity, textures, terrain, terrain-rendering
---


title: How to smooth a voxel mesh?

text:
# Question
Title: How to smooth a voxel mesh?
Currently I have refined voxels, I want to smooth it to achieve accurate projection. After some web search, I came across smoothing algorithms such as Catmull-Clark, Doo-Sabin etc. Along with this, I read one should need the connectivity information to use smoothing algorithm on the outer face of voxel and the connectivity information can be established using the Half edge data structure.

I understand that I need to feed voxel data to Half edge data structure so that I can proceed with a further step but the thing is I didn't get proper idea to use CGAL's Half edge data structure. Moreover, the documentation didn't help me much. Can someone help me to figure this out?.

For example, I have taken sphere as input geometry (First Image). After voxelization, I used intersection algorithm to identify boundary cells which represent actual input geometry as you can see in the above image. Either we can take voxels outside boundary or inside the boundary for projection. Since projecting inside voxels on the surface mesh is quite easy. So directly by using ray shooting on refned voxels, I identified those voxels which are inside boundary voxels. Inside voxels also represents geometry which also looks like in middle image.

From middle Image, we can see that the size of the cells varies from one to another. I want to identify outermost faces from it so that I can use a smoothing algorithm to eliminate Cartesian front to achieve accurate projection.

# Answer
> 0 votes
Do you have any data beyond "solid" vs "not solid" for each voxel? If you have continuous data, such as from the squared distance function that yields the sphere, you can use an isosurface extraction algorithm such as Dual Contouring.

If you don't have this data, you could try to come up with a method of producing it given the voxels (e.g. blurring), but it might alter the locations of the boundaries.

# Answer
> 0 votes
KdotJPG brings up a very good question. Is the volumetric data simply 0s and 1s, or are there intermediate values allowed as well?

Are you using Marching Cubes to convert the density data to triangles?

There is Taubin smoothing. However, smoothing in general can magnify flaws in meshes. For instance, if you're using Marching Cubes, and you do NOT sort the input vertices/density values, then the mesh will inevitably suffer from cracks.

So, are you using Marching Cubes?

You may see my code at https://github.com/sjhalayka/meshdim In particular https://github.com/sjhalayka/meshdim/blob/d69c0e13998ed9a96f8aa652cd54080556814b12/mesh.cpp#L849

# Answer
> 0 votes
I know I'm a little late but who cares

1. I will warn you in case you are as stupid as I was, you cannot simply reuse vertices because it can lead to two cubes touching only corners or edges to share vertices, which makes calculating normals impossible.
2. The easiest way to smoothen voxel mesh is interpolating between vertexPosition + vertexNormal and vertexPosition - vertexNormal like:

```
P0 = vertexPosition + vertexNormal;
P1 = vertexPosition - vertexNormal;
S0 = abs(f(P0) - t);
S1 = abs(f(P1) - t);
vertexPosition = (P0 *S1 + P1 * S0)/(S0 + S1);

```

where `t` is surface level and `f` is scalar field. for `vertexNormal` you can use average normals of adjacent faces or, for better effect, use gradient of scalar field, but usually the first one is good enough.

---
Tags: data-structure, computational-geometry
---


# Question
Title: How to read pixel data from a ID3D12Resource?
I'm trying to read pixel data of a D3D12 render target (`ID3D12Resource`) for h264 encoding/streaming, I tried asking on DirectX Discord and also GPT and still I got no chance and a working solution.

I am making a unity3D plugin and I have access to following components from unity :

```
static ID3D12Device*                    s_D3D12Device;
static ID3D12CommandQueue*              s_CommandQueue;
static ID3D12Fence*                     s_FrameFence;

```

I also have a pointer to ID3D12Resource which I got using `Texture.GetNativeTexturePtr` and I call the native `OnRenderFinished` from unity on HDRP `RenderPipelineManager.endCameraRendering`

My result data is :

```
struct PIXEL
{
    UINT8 r, g, b, a;
    PIXEL(UINT8 red, UINT8 green, UINT8 blue, UINT8 alpha) : r(red), g(green), b(blue), a(alpha) {}
};

static PIXEL*   RenderPixelData = nullptr;

```

I know how to do this in D3D11 but I can't find any correct way to perform this in D3D12, I will be really thankful if someone help me with this.

```
void OnRenderFinished()
{
    if (!s_RenderTexture) { u2merr("Error At Line %d", __LINE__); return; }
    if (!RenderPixelData) { u2merr("Error At Line %d", __LINE__); return; }

    HRESULT res = 0;

    size_t pixelDataSize = RenderTextureDesc.Width * RenderTextureDesc.Height * sizeof(PIXEL);
    UINT width = RenderTextureDesc.Width; UINT height = RenderTextureDesc.Height;

    // How to Read Data from s_RenderTexture

    printf("> ");
}

```

# Answer
> 2 votes
The steps you want are roughly:

1. Create a `D3D12_RESOURCE_STATE_COPY_DEST` resource on a `D3D12_HEAP_TYPE_READBACK` heap.
2. Transition the render target to `D3D12_RESOURCE_STATE_COPY_SOURCE`.
3. Use `CopyTextureRegion()` to copy to your new resource.
4. Use a fence to wait for the copy to complete.
5. Read from the `D3D12_HEAP_TYPE_READBACK` texture using Map().

You might find the ScreenGrab code under https://github.com/microsoft/DirectXTex useful, as it's essentially doing what you want to do.

---
Tags: unity, c++, directx12
---


title: Force even window dimensions

text:
# Question
Title: Force even window dimensions
## Force even resolution window

I am using GLFW/glfw3 OpenGL to write 2D games.

Some of my shaders have artifacts that only appear when the window size has an odd value. Eg 1201 by 1024 creates artifacts. 1200 by 1024 does not have artifacts.

The artifacts are unacceptable and must be fixed.

There are two solutions.

1. Rewrite all the shaders (which I would like to avoid as the source of the artifact is that I use a lot of integers rather than floats. There is a lot to rewrite / redesign)
2. And the easy quick fix... Ensure the screen size is always even.

Example code;

```
unsigned int windowWidth{wS->N->GetUInt("windowWidth")};
unsigned int windowHeight{wS->N->GetUInt("windowHeight")};
glfwCreateWindow(
     std::max(320, windowWidth / 2 * 2),   // even
     std::max(200, windowHeight / 2 * 2),  // even
     (const char*)&wS->N->GetString("appName")[0],
     NULL, NULL
 );

```

## Question

Is there any reason to avoid forcing even resolutions / window size?

Fullscreen I believe is OK as I don't know of any display the has an odd dimension.

Will this cause problems in windowed mode on any OS or setup?

# Answer
> 2 votes
Here are the problems I can think of:

1. If you wish to support resizing, this may be extra trouble. But you can fix the window size when the user stops dragging.
2. On Unix desktops, *tiling window managers* force windows to take on certain sizes regardless of the application's requested size. (If you're not familiar, think of them as a sort of virtual multi-monitor system where each window is always “full screen” within one of the regions.) In this case, I think it would be reasonable to render with an extra black line at the edge of the viewport — don't change your shader algorithm, just render at the next smaller even size.

---
Tags: opengl, glfw, window-management
---


# Question
Title: Does MonoBehaviour have a method that is called in editor when the object is created?
I'm coming from Unreal, and in Unreal you can use the constructor to make logic that is called in editor (as well as when beginning play). This is useful for some things, but Unity documentation says that you shouldn't try to use the constructor of a MonoBehaviour.

I used to think Awake() was called in editor, but it isn't, it's called before Start() but only in play mode.

So, is there some other Method that is called in editor AND in game?

# Answer
Yes, `OnValidate()` gets called *only* in the Editor (including play mode in-editor) in a few situations:

* When the component is added to a game object
* When a prefab containing the component is instantiated
* When the user changes data in the component's Inspector fields
* When entering play mode
* When reloading the C# assembly containing the `MonoBehaviour` following a code change
* When building the game

Because it can be called repeatedly during the lifetime of a single object, if you want to do any one-time initialization then you'll need to use a flag or some telltale state to check if the object has already been initialized, and skip it if so. If you want the behaviour to be called in both the editor and built executables, you can make a separate `Initialize()` method and call it from both `OnValidate()` and `Awake()`.

Note that `OnValidate()` can be called from the loading thread, so it can't be used to perform any tasks that are main-thread-only. What it can do though is set up a listener to invoke the required actions on the main thread after it's run.

There is also `Reset()` which is called in-editor when a component is added to an object, *before* `OnValidate()` and when manually resetting a component via its context menu. It's not called repeatedly in the lifetime of a single object outside of this manual intervention, but it also does not get called when instantiating a prefab.
> 3 votes

---
Tags: unity, c#, editors, monobehaviour
---


title: Changing one axis to another

text:
# Question
Title: Changing one axis to another
Apologies for the bad title -- I have no idea how to explain this problem succinctly.

I have two 3D vectors. One is the player's movement direction, and the other is the direction towards a wall they are climbing. I need to make it so when the player is moving towards or away from the wall, they are actually moving up and down. All while preserving the sideways movement as it would be without climbing.

I've tried to understand cross products and other vector maths, but I cannot figure this out. Thank you for any help you can provide.

Edit: an simple scenario for clarity (y = vertical):

```
Vector3 directionOfMovement = (1.0, 0.0, 0.0)
Vector3 directionTowardsWall = (1.0, 0.0, 0.0)
Vector3 myRequiredResult = (0.0, 1.0, 0.0)

```

I need it to work when the directions are at odd angles as well.

# Answer
```
// If directionTowardsWall has magnitude 1.0, this dot product gives the
// signed length of the component of movement along that direction.
float projection = Vector3.Dot(directionOfMovement, directionTowardsWall);

// That component as a vector is then that length times the direction.
Vector3 movementTowardsWall =  projection * directionTowardsWall;

// The component parallel to the wall is what remains after subtracting
// the towards/away component.
Vector3 movementAlongWall = directionOfMovement - movementTowardsWall;

// And the movement on the vertical axis is the signed length of the projection.
movementAlongWall.y += projection;

```
> 0 votes

---
Tags: vector, direction
---


# Question
Title: Rigidbody2D goes over destination when moving with Vector2.Lerp
I'm rounding the position of an object (the blue cube) when the player stops pushing it using

```
Rigidbody2D.MovePosition(transform.position,RoundedPosition,lerpValue);

```

The object slides toward the desired position, and when it reaches it, it stops and then it moves about 0.05 units over the position it stopped.

Here's the script

```
bool IsPushing = false;
bool RoundingPosition = false;
Vector3 RoundedPos;
public float lerp;
Rigidbody2D PlayerRb;
Rigidbody2D rb;
void Start()
{
    rb = GetComponent<Rigidbody2D>();
    PlayerRb = GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody2D>();
}

Vector3 GetRoundedPos()
{
    return new Vector3(Mathf.Floor(transform.position.x) + 0.5f, Mathf.Floor(transform.position.y) + 0.5f, 0);
}

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        IsPushing = true;
    }
}

void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        IsPushing = false;
        RoundingPosition = true;
        RoundedPos = GetRoundedPos();
    }
}

void FixedUpdate()
{
    if (IsPushing)
    {
        if (new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) == Vector2.zero)
        {
            RoundingPosition = true;
            RoundedPos = GetRoundedPos();
        }
        else
            RoundingPosition = false;
    }

    if (RoundingPosition)
    {
        rb.MovePosition(Vector2.Lerp(transform.position, RoundedPos, lerp));
        if (Vector3.Distance(RoundedPos,transform.position) <= 0.0001f)
        {

            RoundingPosition = false;
            IsPushing = false;
            rb.MovePosition(RoundedPos);
        }
    }
}

```

Demonstration video: Demonstration

# Answer
It seems like the Rigidbody may have some velocity remaining from the MovePosition calls. Try to add line "rb.velocity=Vector2.Zero;":

if (Vector3.Distance(RoundedPos,transform.position) <= 0.0001f)
        {

            RoundingPosition = false;
            IsPushing = false;
            rb.MovePosition(RoundedPos);
            rb.velocity=Vector2.zero;
        }
```

> 1 votes

---
Tags: unity, 2d, physics, rigidbody
---


title: How to use SmoothDamp with speed?

text:
# Question
Title: How to use SmoothDamp with speed?
I have a moving platform which is being moved like this:

```
Vector2 currentPosition = rigidBody2d.position;
Vector2 movement = Vector2.MoveTowards(currentPosition, target, speed * Time.deltaTime);
rigidBody2d.MovePosition(movement);
velocity = (movement - currentPosition) / Time.deltaTime;

```

And I want to have the moving platform ease in and out of target speed when moving. Basically accelerate from starting position up to speed defined in `speed` parameter and then decelerate when near target position.

Someone told me to try using `SmoothDamp` instead of `MoveTowards` but I am a little perplexed with the behavior.

I've tried using it as follows:

```
Vector2 movement = Vector2.SmoothDamp(currentPosition, target, ref velocity, 0.1f, speed);

```

but no matter how much I modify the `smoothTime` the platform never goes near the set speed (`5`). It is mostly below 1 or around 1-1.1

What am I doing wrong here? How can I implement easing for my moving platform while still having it reach the set speed?

# Answer
> 0 votes
The speed parameter you are passing to the function is the maximum speed that `SmoothDamp` will give you, not the desired speed or such. It seems as if your distance is too short, such that it can be covered in the specified time (0.1 sec) without reaching the `maxSpeed`. You can indirectly adjust the speed by using a lower `smoothTime`. Note that you will probably not be able to reach exactly an actual speed of 5.

---
Tags: unity, movement, easing
---


title: How does Godot 4 copy vectors?

text:
# Question
Title: How does Godot 4 copy vectors?
I'm an old coder, but a newbie to Godot. I'm using version 4.

I got some unexpected (to me) behavior when I tried this code:

```
var vectorA := Vector2(1.0,0.0)
var vectorB := vectorA
print("A ", vectorA, " B ", vectorB)
vectorA.x = 3
print("A ", vectorA, " B ", vectorB)

```

I would have thought that `vectorB` and `vectorA` were aliases: change one, and you change them both. But the output was as follows:

```
A (1, 0) B (1, 0)
A (3, 0) B (1, 0)

```

This implies that it allocated a totally new `Vector2` object when I created `vectorB`. This brings up a lot of questions in my mind:

* Can you make aliases of objects, or does it always make a brand new one?
* Is it using pass-by-reference or pass-by-value when you call a function?
* Do I need to worry about allocating tons of memory, whenever I set one object equal to another? Will this slow my game way down?
* Or am I focusing on the wrong details, when I'm trying to optimize? I'm used to avoiding system calls and reusing old objects, but that may just be the wrong approach in Godot.

So what's going on behind the scenes when I set one `Vector2` equal to another?

Thanks.

# Answer
Checking the GDScript reference docs:

> # Built-in types
>
> Built-in types are stack-allocated. They are passed as values. **This means a copy is created on each assignment or when passing them as arguments to functions**. The only exceptions are Arrays and Dictionaries, which are passed by reference so they are shared. (Packed arrays such as PackedByteArray are still passed as values.)

Because these are stack allocated, memory for the copy is practically free - it slots into the "temporary scratch pad" space that the containing function uses for its work. There's no garbage collection overhead or lifetime complications like there would be for heap allocated memory. Depending on how the code is compiled, it may even be possible for the copy to be elided entirely when the system can detect that it's unnecessary (I cannot speak to the details of what optimizations Godot performs or could be upgraded to perform in future).

That means that unlike in languages like Java, JavaScript, or ActionScript, you don't gain any benefit from declaring a single long-lived member variable and re-using it for function temporaries. In fact, doing so *costs* memory by increasing your heap allocation size. The situation here is more closely analogous to C# `struct` types, where temporaries and copies are cheap (as long as the structure is small).

There is a small overhead to copying the values, but for small data structures like `Vector2` / `Vector3` (just 8 and 12 bytes, respectively), this cost is negligible, and adding indirection to try to eliminate it may have a heavier performance impact of its own.

So, consider these small stack-allocated types safe to use as disposable temporaries, and don't unnecessarily complicate your code by trying to minimize them.
> 5 votes

# Answer
Vectors in Godot are value types, not reference types. Furthermore, they are not considered objects.

But since "object" might mean slightly different things depending on context, I'll be more specific... `Vector2` is:

* A value type: a type such that the memory layout of the variables is the value, and not a reference to the value.
* A built-in type: a type that is provided as part of the language.
* A composite type: a type that can be decomposed into simpler values (withing the constraints of the language).

Furthermore, `Vector2` is not an entity type. So when you compare instances of `Vactor2` you are checking if they *have the same value* not if they *are the same*.

---

You might be wondering is `Vector2` a class? And the answer is that it depends on what you mean. `Vector2` is a C++ class (internally there is a `Vector2` class in the source code of Godot), but it is not a script class (it is not a class as far as the type system exposed by Godot is concerned).

Now, as you know, in general an "object" is an instance of a class. So if instances of `Vector2` are objects also depends on what you mean.

In fact, there is an `Object` class, which is the root of the class hierarchy in Godot, so we will call "object" to any instance of a `Object` or a class that extends `Object`... And `Vector2` is not a class (even if you consider it one, it does not extend `Object`). Which is why I claim that vectors in Godot are not considered objects.

---

> Can you make aliases of objects, or does it always make a brand new one?

There are reference types in Godot, `Vector2` is not one. You cannot make a direct reference to a `Vector2`. *Yes, pointers are direct references. GDScript is a pointer free language.*

---

> Is it using pass-by-reference or pass-by-value when you call a function?

You pass by value. You cannot choose to pass by reference. And, again, Godot has both value types and reference types (so you can have a reference type passed by value).

You might work around this by passing the values inside of an `Array` (`Array` is a reference type, i.e. not a value type).

---

> Do I need to worry about allocating tons of memory, whenever I set one object equal to another? Will this slow my game way down?

*Depends on what you call "object"...*

No, you don't have to worry about allocation when you are setting a variable to an instance of a reference type.

You might worry about some large composite value types, which would be the case of packed arrays (`Packed*Array` are value types).

---

> Or am I focusing on the wrong details, when I'm trying to optimize? I'm used to avoiding system calls and reusing old objects, but that may just be the wrong approach in Godot.

I suppose you remember what they say about premature optimization. With that out of the way...

Yes, using a built-in method (I mean, something from the standard library) will be more performant than doing it in a script. However, I believe it is useful to figuring out if you can save a few calls, for another reason: a common experience for Godot beginners is to implement something to later discover Godot already has it.

And yes, a lot of allocations can become a problem. However, you will find that you can iterate your design much faster if you don't worry about it. And once you have settled on your design, you can work on optimize it if it is necessary.

---

I want to note that you have a time budget, which is split between your scripts, rendering, physics, and a few other systems. As long as they complete in time, the user would not perceive a performance degradation. Thus, if you are not going over budget, it is harmless if the GDScript code is less than optimal. But don't forget that the hardware is also a factor.

---

> So what's going on behind the scenes when I set one Vector2 equal to another?

This is a copy:

```
var vectorA := Vector2(1.0,0.0)
var vectorB := vectorA

```

Simple. Being these value types, there is no ref-counting, no pointer fiddling, no flagging... It is a true, honest, copy.

Furthermore, these are local variables, correct? In that case they will be freed when the method ends. You are not leaking anything. You are not adding pressure to a garbage collector. Nothing like that.

---

A few extra notes about Godot type system and memory management:

* All objects (instances of classes that are `Object`) are reference types.
* If they extend `RefCounted` they are... reference counted.
* Otherwise you free them manually.
* If they extend `Node` you can use `queue_free` which will free them sometime in the future between frames.
* Otherwise you would free them deterministically with `free`.
* You could avoid a lot of `Node` allocations by working with server classes. *But the code becomes more rigid. So, as I said above, iterate your design first, and afterwards see if you need this.*

---

In fact, you will find that many game engines and frameworks - not only Godot - opt to have value type vectors (e.g. `Vector2`), plus they will have ways to keep lists of vectors compact in memory (e.g. `PackedVector2Array`). This makes it easier to move memory to the graphic back end, and this improvement in performance outweighs the losses caused by crating copies.

---

Finally, you could write C# or C++ for Godot which could potentially be more performant than GDScript (And I say potentially because bad code is bad regardless of language). Yet you can mix languages. So you can make your game in GDScript, and then port the parts that could use some extra performance.
> 2 votes

---
Tags: optimization, memory-efficiency, gdscript, godot-4
---


# Question
Title: Unknown enum type when modding Minecraft recipes with CraftTweaker
I want to make some new Recipes with CraftTweaker, which uses machines from the Create mod (I'm using Life In The Village 3), but I have the following error in my scripts:

```
[ERROR]: Error while running scripts:
org.openzen.zenscript.lexer.ParseException: CreateLapisDiamond.zs:16:57: Unknown enum type <constant:create:heat_condition:"heated">
at TRANSFORMER/crafttweaker@9.1.207/com.blamejared.crafttweaker.api.bracket.custom.EnumConstantBracketHandler.lambda$parse$1(EnumConstantBracketHandler.java:53)
at java.base/java.util.Optional.orElseThrow(Optional.java:403)
at TRANSFORMER/crafttweaker@9.1.207/com.blamejared.crafttweaker.api.bracket.custom.EnumConstantBracketHandler.parse(EnumConstantBracketHandler.java:53)
at TRANSFORMER/crafttweaker@9.1.207/com.blamejared.crafttweaker.impl.script.scriptrun.runner.IgnorePrefixCasingBracketParser.parse(IgnorePrefixCasingBracketParser.java:37)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readPrimaryExpression(ParsedExpression.java:562)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readPostfixExpression(ParsedExpression.java:364)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readUnaryExpression(ParsedExpression.java:359)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readMulExpression(ParsedExpression.java:288)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readAddExpression(ParsedExpression.java:258)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readShiftExpression(ParsedExpression.java:237)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readCompareExpression(ParsedExpression.java:166)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readAndExpression(ParsedExpression.java:156)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readXorExpression(ParsedExpression.java:146)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readOrExpression(ParsedExpression.java:136)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readAndAndExpression(ParsedExpression.java:126)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readOrOrExpression(ParsedExpression.java:110)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readConditionalExpression(ParsedExpression.java:97)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readAssignExpression(ParsedExpression.java:49)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.parse(ParsedExpression.java:40)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedCallArguments.parse(ParsedCallArguments.java:46)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readPostfixExpression(ParsedExpression.java:399)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readUnaryExpression(ParsedExpression.java:359)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readMulExpression(ParsedExpression.java:288)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readAddExpression(ParsedExpression.java:258)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readShiftExpression(ParsedExpression.java:237)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readCompareExpression(ParsedExpression.java:166)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readAndExpression(ParsedExpression.java:156)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readXorExpression(ParsedExpression.java:146)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readOrExpression(ParsedExpression.java:136)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readAndAndExpression(ParsedExpression.java:126)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readOrOrExpression(ParsedExpression.java:110)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readConditionalExpression(ParsedExpression.java:97)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.readAssignExpression(ParsedExpression.java:49)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.expression.ParsedExpression.parse(ParsedExpression.java:40)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.statements.ParsedStatement.parse(ParsedStatement.java:299)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.statements.ParsedStatement.parse(ParsedStatement.java:81)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.ParsedFile.parse(ParsedFile.java:215)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zenscript.parser.ParsedFile.parse(ParsedFile.java:158)
at TRANSFORMER/crafttweaker@9.1.207/org.openzen.zencode.java.ScriptingEngine.createScriptedModule(ScriptingEngine.java:123)
at TRANSFORMER/crafttweaker@9.1.207/com.blamejared.crafttweaker.impl.script.scriptrun.runner.ScriptRunner.runScripts(ScriptRunner.java:86)
at TRANSFORMER/crafttweaker@9.1.207/com.blamejared.crafttweaker.impl.script.scriptrun.runner.ScriptRunner.run(ScriptRunner.java:69)
at TRANSFORMER/crafttweaker@9.1.207/com.blamejared.crafttweaker.impl.script.scriptrun.DecoratedRunKind$DecoratedScriptRunner.run(DecoratedRunKind.java:27)
at TRANSFORMER/crafttweaker@9.1.207/com.blamejared.crafttweaker.impl.script.scriptrun.ScriptRun.executeRun(ScriptRun.java:88)
at TRANSFORMER/crafttweaker@9.1.207/com.blamejared.crafttweaker.impl.script.scriptrun.ScriptRun.execute(ScriptRun.java:54)
at TRANSFORMER/crafttweaker@9.1.207/com.blamejared.crafttweaker.impl.script.ScriptReloadListener.apply(ScriptReloadListener.java:78)
at TRANSFORMER/crafttweaker@9.1.207/com.blamejared.crafttweaker.impl.script.ScriptReloadListener.m_5787_(ScriptReloadListener.java:37)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.server.packs.resources.SimplePreparableReloadListener.m_10789_(SimplePreparableReloadListener.java:13)
at java.base/java.util.concurrent.CompletableFuture$UniAccept.tryFire(CompletableFuture.java:718)
at java.base/java.util.concurrent.CompletableFuture$Completion.run(CompletableFuture.java:482)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.server.packs.resources.SimpleReloadInstance.m_143940_(SimpleReloadInstance.java:69)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.util.thread.BlockableEventLoop.m_6367_(BlockableEventLoop.java:198)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.util.thread.ReentrantBlockableEventLoop.m_6367_(ReentrantBlockableEventLoop.java:23)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.util.thread.BlockableEventLoop.m_7245_(BlockableEventLoop.java:163)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.util.thread.BlockableEventLoop.m_18701_(BlockableEventLoop.java:176)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.Minecraft.m_205125_(Minecraft.java:2082)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.Minecraft.doLoadLevel(Minecraft.java:1909)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.Minecraft.m_91200_(Minecraft.java:1873)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.gui.screens.worldselection.WorldSelectionList$WorldListEntry.m_101744_(WorldSelectionList.java:473)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.gui.screens.worldselection.WorldSelectionList$WorldListEntry.m_101704_(WorldSelectionList.java:330)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.gui.screens.worldselection.WorldSelectionList$WorldListEntry.m_6375_(WorldSelectionList.java:257)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.gui.components.AbstractSelectionList.m_6375_(AbstractSelectionList.java:323)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.gui.components.events.ContainerEventHandler.m_6375_(ContainerEventHandler.java:27)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.MouseHandler.m_168084_(MouseHandler.java:88)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.gui.screens.Screen.m_96579_(Screen.java:528)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.MouseHandler.m_91530_(MouseHandler.java:85)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.MouseHandler.m_168091_(MouseHandler.java:185)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.util.thread.BlockableEventLoop.execute(BlockableEventLoop.java:118)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.MouseHandler.m_91565_(MouseHandler.java:184)
at MC-BOOTSTRAP/org.lwjgl.glfw/org.lwjgl.glfw.GLFWMouseButtonCallbackI.callback(GLFWMouseButtonCallbackI.java:36)
at MC-BOOTSTRAP/org.lwjgl/org.lwjgl.system.JNI.invokeV(Native Method)
at MC-BOOTSTRAP/org.lwjgl.glfw/org.lwjgl.glfw.GLFW.glfwWaitEventsTimeout(GLFW.java:3174)
at TRANSFORMER/minecraft@1.18.2/com.mojang.blaze3d.systems.RenderSystem.m_69830_(RenderSystem.java:225)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.Minecraft.m_91383_(Minecraft.java:1071)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.Minecraft.m_91374_(Minecraft.java:665)
at TRANSFORMER/minecraft@1.18.2/net.minecraft.client.main.Main.main(Main.java:205)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at MC-BOOTSTRAP/fmlloader@1.18.2-40.2.0/net.minecraftforge.fml.loading.targets.CommonClientLaunchHandler.lambda$launchService$0(CommonClientLaunchHandler.java:31)
at MC-BOOTSTRAP/cpw.mods.modlauncher@9.1.3/cpw.mods.modlauncher.LaunchServiceHandlerDecorator.launch(LaunchServiceHandlerDecorator.java:37)
at MC-BOOTSTRAP/cpw.mods.modlauncher@9.1.3/cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:53)
at MC-BOOTSTRAP/cpw.mods.modlauncher@9.1.3/cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:71)
at MC-BOOTSTRAP/cpw.mods.modlauncher@9.1.3/cpw.mods.modlauncher.Launcher.run(Launcher.java:106)
at MC-BOOTSTRAP/cpw.mods.modlauncher@9.1.3/cpw.mods.modlauncher.Launcher.main(Launcher.java:77)
at MC-BOOTSTRAP/cpw.mods.modlauncher@9.1.3/cpw.mods.modlauncher.BootstrapLaunchConsumer.accept(BootstrapLaunchConsumer.java:26)
at MC-BOOTSTRAP/cpw.mods.modlauncher@9.1.3/cpw.mods.modlauncher.BootstrapLaunchConsumer.accept(BootstrapLaunchConsumer.java:23)
at cpw.mods.bootstraplauncher@1.0.0/cpw.mods.bootstraplauncher.BootstrapLauncher.main(BootstrapLauncher.java:149)
[ERROR]: Scripts are invalid!

```

Here is the script I am using:

```
import crafttweaker.api.item.IItemStack;
import crafttweaker.api.ingredient.IIngredient;
import crafttweaker.api.recipe.FurnaceRecipeManager;

import mods.create.IProcessingRecipeManager;
import mods.create.MechanicalCrafterManager;
import mods.create.CrushingManager;
import mods.create.SplashingManager;
import mods.create.CompactingManager;
import mods.create.FillingManager;
import mods.create.MixingManager;
import mods.create.PressingManager;

<recipetype:create:compacting>.addRecipe("compact_coal", <constant:create:heat_condition:"heated">, [<item:minecraft:coal>], [<item:minecraft:charcoal>], 100);

<recipetype:create:crushing>.addRecipe("crush_lapis", [<item:minecraft:lapis_lazuli> * 2, <item:minecraft:lapis_lazuli> % 50], <item:create:asurine>, 100);
<recipetype:create:crushing>.addRecipe("crush_dia", [<item:minecraft:diamond> % 1], <item:minecraft:coal_block>, 400);

```

How do I resolve this error?

# Answer
> 0 votes
"Unknown enum type" means the game doesn't recognize `<constant:create:heat_condition:"heated">` as being a valid label for a state.

So, let's search for that key phrase `constant:create:heat_condition` to find out what *are* valid enum values we can use to describe heat conditions.

When I do this, the first result is HeatCondition - CraftTweaker Documentation, which says the available values are:

```
<constant:create:heat_condition:none>
<constant:create:heat_condition:heated>
<constant:create:heat_condition:superheated>

```

Note that there are no quotation marks around `heated`, but in your script, there are. That means you should delete the quotation marks around `heated` in your script, so it matches one of the values above exactly.

---
Tags: java, scripting, minecraft-modding
---


# Question
Title: Multiple game servers on one dedicated machine with different IP’s
I apologize if this is not the proper place to ask this question but I am hoping that if you folks cannot help then you would know of someone or somewhere to send me to get the answers that I have desperately been searching for. I have currently purchased a dedicated machine from a hosting service. I am running Windows 2019 on the machine. I do not have much experience with dedicated machines. I am currently running 2 Rust game servers on the same IP with different ports but the servers are fairly laggy. I am wanting to run the servers with 2 different IP's which I have 5 usable IP's. Please help me as I have been searching and trying to find the answer to these issues.

# Answer
This Rust server documentation https://www.bestrusthosting.com/guides/how-to-configure-your-rust-server-all-options-explained/

Says you can set the server bind IP address in the console or config file

> `+server ip x.x.x.x`
>
> This is also important. As you’d expect, it changes the IP address your users will connect to. However, less obvious is the fact it should be set to 0.0.0.0 for most setups. This will let it automatically adjust to your current IP address. The only time you need to set it manually is if you have multiple IPs.

That said, once the server is started/bound to a port, it doesn't care what port/IP is being used, it's just talking to a "socket".

Outside a few very rare cases -like a DDoS attack saturating a network interface- there should be no practical difference between using 2 ports on the same IP or 1 port on 2 IPs.

I suspect you've mis-diagnosed the bottleneck.

Try opening whatever performance monitoring tools you have access to and checking CPU/Disk/Memory utilisation.
> 1 votes

---
Tags: server
---


# Question
Title: Destroying game object destroys additional object
I am building a simple hyper casual game and faced a strange issue when destroying one object destroyes another not related object.

As you can see when white cube collides with black rectangle, cube is destroyed(which is expected) and also one more rectangle is destroyed(first from the top, and it is not expected).

```
public class Obstacle : MonoBehaviour {

    private SpriteRenderer sr;

    [SerializeField]
    private float moveSpeed;

    private void Awake() {
        sr = GetComponent<SpriteRenderer>();
    }

    private void Update() {
        transform.Translate(Vector3.down * moveSpeed * Time.deltaTime);
    }
}

```

code for white cube

```
public class PlayerUnit : MonoBehaviour {

    private void OnCollisionEnter2D(Collision2D collision) {
        Destroy(gameObject);
    }
}

```

code for Input controller

```
public class TouchManagerScript : MonoBehaviour {

[SerializeField]
private float moveSpeed;

[SerializeField]
private PlayerInput playerInput;

private InputAction touchPositionAction;
private InputAction touchPressAction;

private Vector2 direction = Vector2.left;

private void Start() {
    touchPressAction = playerInput.actions["TouchPress"];
    touchPositionAction = playerInput.actions["TouchPosition"];

    touchPressAction.performed += TouchPressAction_performed;
}

private void OnDisable() {
    touchPressAction.performed -= TouchPressAction_performed;
}

private void Update() {
    transform.Translate(direction * moveSpeed * Time.deltaTime);
}

private void TouchPressAction_performed(InputAction.CallbackContext context) {
    Vector2 value = touchPositionAction.ReadValue<Vector2>();

    direction = value.x < Camera.main.pixelWidth / 2 ? Vector2.left : Vector2.right;
}
}

```

Obstacle Generator

```
public class ObstaclesGenerator : MonoBehaviour {

private GameObject leftWall;
private Transform leftWallBorderPoint;

private GameObject rightWall;
private Transform rightWallBorderPoint;

private Transform yPoint;

[SerializeField]
private GameObject obstacle;

private float minXObstacleSize = 1.5f;

private float maxXObstacleSize = 3f;

private float cooldown;

private void Awake() {
    this.leftWall = GameObject.FindGameObjectWithTag("LeftWall");
    this.rightWall = GameObject.FindGameObjectWithTag("RightWall");

    this.leftWallBorderPoint = leftWall.transform.Find("Border");
    this.rightWallBorderPoint = rightWall.transform.Find("Border");

    this.yPoint = transform.Find("ObstacleGenerationPoint");
}

void Update() {
    if (cooldown <= 0) {
        cooldown = Random.Range(1f, 2f);

        GenerateObstacle();
    } else {
        cooldown -= Time.deltaTime;
    }
}

private void GenerateObstacle() {
    int random = Random.Range(0, 2);

    // choose obstacle side (left / right)
    float xCoord = random == 0 ? leftWallBorderPoint.position.x : rightWallBorderPoint.position.x;
    Vector3 instantiationPoint = new Vector3(xCoord / 1.3f, yPoint.transform.position.y, 0);

    GameObject instantiatedObstacle = Instantiate(obstacle, instantiationPoint, Quaternion.identity);
    // randomize obstacle size
    instantiatedObstacle.transform.localScale = new Vector3(Random.Range(minXObstacleSize, maxXObstacleSize), instantiatedObstacle.transform.localScale.y, 0);
}
}

```

Reference remover (isTrigger)

```
public class ObstaclesReferenceRemover : MonoBehaviour {

    private void OnTriggerEnter2D(Collider2D collision) {
        Destroy(collision.gameObject);
    }
}

```

My Unity Scene

Right and left walls -\> simple rectangles with just sprite renderers. Main road -\> simple 2d rectangle

Scipts -\> empty object
ObstacleGenerator -\> empty with ObstacleGenerator script
ObstacleGenerationPoint -\> empty object simply to have a ref point to instantiate obstacles

Player -\> contains box collider 2D, rigidbody, TouchManagerScript and PlayerUnit.

Input -\> contains input system reference

Obstacle reference remover -\> just wide rectangle which acts as trigger, when obstacle reaches it, it gets destroyed.

# Answer
I'm new here and am by no means an expert, but when you destroy the collision for the cube as you did with the destroy.gameobject shouldn't the variable be under the public class of PlayerUnit and not ObstaclesReferenceRemover? Maybe we need a separate code to remove that reference after the cube is destroyed to clear the screen so to speak. right now it looks to me like they both get destroyed because of that. But, i'm new and i could be dead wrong.
> 0 votes

# Answer
It turned out that obstacle disappeared not because it was destroyed. Something was wrong with rendering. Changing sorting layer for obstacle or setting higher order in default layer fixes the problem.

I am curious why it even happens because sorting layer of the obstacle is not being updated after the collision and still it was disappearing.

Also only last obstacles were disappearing.
> 0 votes

---
Tags: unity, collision-detection
---


title: Choose rotation facing direction

text:
# Question
Title: Choose rotation facing direction
I am rotating a gameobject in Unity so it always faces another gameobject. However I want to be able to decide which side is going to face the target. I want to be able to change the facing point to any of the color sides of the sphere. So for example the yellow point will be facing the target instead of the green.

Here is my code

```

    private void Update() {
        float singleStep = speed * Time.deltaTime;

        Vector3 facing_Dir = transform.forward;
        Vector3 targetDirection = target_Ga.transform.position - transform.position;

        Vector3 newDirection = Vector3.RotateTowards(facing_Dir, targetDirection, singleStep, 0.0f);

        transform.rotation = Quaternion.LookRotation(newDirection);
    }

```

# Answer
After your calculations on the object to look at the cube, apply a rotation on the `transform`, based on which side you want it to look at.

For example:

```
private void Update() {
    ...
    transform.rotation = Quaternion.LookRotation(newDirection);
    transform.Rotate(90, 0, 1, 0);
}

```

This should make your object "look" at the cube, but then rotate it so that a different side of the object is looking at the cube now.

It's been a while since I last touched Unity, so I haven't tested the code above. You might need to play around with the order on which transformation happens first, but hopefully this can give you the right idea on how to achieve the desired effect.
> 0 votes

---
Tags: unity, rotation
---


# Question
Title: How can I rotate cubemap in shadergraph?
I know how to rotate cube map with legacy surface shader

Shader Rotation Matrix:

```
uniform float4x4 _Rotation;
          o.Emission = texCUBE (_Cube,  mul(_Rotation, float4(IN.worldRefl,0))).rgb;

```

RotateCubeMap:

```
using UnityEngine;

public class RotateCubeMap : MonoBehaviour
{
    public float speed = 20;
    private MeshRenderer _meshRenderer;

    private void Awake()
    {
        _meshRenderer = GetComponent<MeshRenderer>();
    }

    public void Update()
    {
        var rot = Quaternion.Euler (0, Time.time*speed, 0);
        var m = new Matrix4x4 ();
        m.SetTRS(Vector3.zero, rot,new Vector3(1,1,1) );
        _meshRenderer.material.SetMatrix ("_Rotation", m);
    }
}

```

I tried to recreate it by shadergraph

but it didn't work!

I need a result like this:

# Answer
I understood what is my problem!

It's because Instead of multiplying `WorldReflect` with `Rotation Matrix`

I multiplied the `ObjectSpaceViewDirection` with `Rotation Matrix`

so I could fix it by using custom function:

Custom function basic setup:

use this script inside the shader:

```
float3 WorldReflect = reflect(-ObjectSpaceViewDirection, ObjectSpaceNormal);
OutPut =  SAMPLE_TEXTURECUBE_LOD(_CubeMap, sampler_CubeMap, mul(Rotation, float4(WorldReflect,0)) , 0);

```
> 1 votes

# Answer
Possibly found a simpler way without a custom function.

Use the `Rotate About Axis Node` and just set the `Axis` you want to rotate around (vertical is Y) to 1 and others to 0.

Connect the `ViewDirection` Node to the `In` and the `Out` to the `SampleCubeMap ViewDir`.
> 1 votes

# Answer
I stumbled uppon this thread a bit late, but this could be of help to other people.

I recreated the rotation inside shadergraph. Heres the image:

Basically is just calculate reflection vector between view direction and normal vector, and then rotate about axis, in this case Y needs to be set to 1 and voila. Plug it into a Sample Cubemap.

Hope this helps!
> 0 votes

---
Tags: unity, shaders, unity-shader-graph
---


# Question
Title: Is there a simple way to find where our code is keeping references to disposed/pooled objects?
In our c# game we use object pools to store sprites once the Dispose() method gets called.Then when the Sprite.Create method gets called if a sprite is in the pool it gets depooled, cleared and returned.An uncommon but excruciatingly hard to tackle issue arises if some class by mistake is keeping a reference to the disposed objects and starts using/updating/moving it even if it's actually being used for something completely different by that time.

Is this a common issue? I remember calling it "pool object resurrection" but it could just be me giving it a funny name.

If it is a common issue, what is the strategy to find the "broken / resurrection" reference that links an object already "Dispose()d" to another object that could use it even after the item was recycled from the pool? Thank you!

# Answer
If you're game for a larger refactoring, one good way to defend against this is to change the signature of your "return to pool" function.

Instead of an instance method, make it a static method that takes a `ref` parameter and nulls it out, so:

```
mySprite.Dispose();

```

...becomes:

```
Sprite.Recycle(ref mySprite);
// variable mySprite now holds the value null
// and any attempt to use it will throw an exception.

```

This won't defend against something like:

```
var alias = mySprite;
Sprite.Recycle(ref alias);
// alias is null but mySprite still holds a reference to the recycled sprite.

```

...but that's a more complex pattern you'd rarely write accidentally.
> 1 votes

---
Tags: c#, xna, sprites, monogame, object-pools
---


# Question
Title: What is the best way to store level data in HTML5
I am currently making a game in HTML5 using canvas, and it is currently just 1 js script and HTML file with references to png files for assets. Right now, I have the level data baked into the script, which works for now, but as I build up the game more and more, I am starting to use more and more lines in the code. Right now, I have ~300 lines of code dedicated to level data, and that's only about 1/50th of the planned size of the game map (It's a REALLY big game). I've considered having txt files with level data stored on the web server, and using the fetch function, but the act of obtaining it has to be asynchronous from the rest of the code, which I might be able to code around, but I don't even know if that's how actual web devs do it.

# Answer
> 2 votes
There is no "best" way. Only the way that works best for your game.

But loading data from files via `fetch` at runtime is certainly not the worst idea. Working with asynchronous calls might seem a bit intimidating at first, but as a JavaScript web application developer there is no way around getting used to that. You are working with asynchronous processes all the time in JavaScript, so promises, callback functions and `asnc`/`await` are the daily bread and butter of web development.

This also applies to games, because every image and every sound file gets loaded asynchronously. If you use them before they are loaded, bad stuff can happen. So having a solid strategy for asset loading is important for any JavaScript+HTML game. The simplest solution is usually to have some form of "preloader" that receives a list of assets the game uses, loads them all, waits for their respective `onload` callback functions to run, and then starts the actual game when they all completed loading.

Regarding the format: JSON is certainly convenient, because you can just turn the string into a JavaScript object via `JSON.parse`. Some people might inject that the verbosity of the JSON format could lead to long load times. But keep in mind that most webservers will use HTTP-level compression automatically (which you as a JS developer don't even notice), and all the "bloat" of JSON is pretty compressible. But you can of course use any other format as well. If you really want to optimize and take full control over every single byte, then you could use your own file format and parse it via a `FileReader`.

# Answer
> 1 votes
## Files

The are many ways to move data between the server and client. Modern web APIs provide all the behaviours you may want.

Moving data is the bread and butter of the internet and thus there is a plethora of options open to you.

### JSON

Store your data as JSON files. JSON file format is specifically designed to transfer data structures across networks.

### Any

However any file can be transferred, the general rule is if it has a Media type AKA MIME type (Multipurpose Internet Mail Extensions), it's a file format that you can use to move data between server and client.

# Moving data

## Fetch API

Use the fetch API to load and decode the JSON directly into JS objects.

It is promise-based (asynchronous) and can easily be integrated into service workers so that your game can run as a web-app AKA PWA (Progressive Web application (offline)).

The fetch API can load any data not just JSON as long as your server is serving the files the API can load them.

### Fetch JSON Example

Very basic example loading JSON data with load animation loop, It's so very easy...

```
   const myData = {mapData: null};
   fetch("./myData/myJSONFile.json")              // Absolute or relative URI
      .then(data => data.json())                  // Decode data as JSON
      .then(mapData => myData.mapData = mapData)  // Assign data to local object
      .catch(e => console.error(e));              // Handle any and all
                                                  // possible data errors

   loadLoop();           // In load loop wait for data
                         // Show loading animation in this loop
   function loadLoop() {
       if (myData.mapData) { // data has loaded
           RequestAnimationFrame(mainLoop);  // start game
       } else {
           RequestAnimationFrame(loadLoop);  // still loading
       }
   }

```

## Streaming

You can also consider streaming data via the Streams API, Web Sockets API or modern Web Transport API if you have data content that is very large and impractical to wait to load.

At a low level you can use the Web RTC API (Web Real-Time Communication) to move streaming content between client server or even client client data streams.

You may have a huge map, use a stream to fetch map content as needed, rather than have to load and store the whole map client side.

And much more.

## Be creative

The web is an evolving entity and as such your imagination on how to use the latest API / technology may well be the next best practice.

After all writing games is all about being creative!

---
Tags: html5, html-canvas, data-structure, web
---


# Question
Title: Problem unrolling loop in compute shader
I'm pretty new to compute shaders and shader writing in general. I'm trying to write a compute shader for a procedural generation project I'm working on, it's purpose is to blend biomes together. The function works by taking a sample of points around the point it's trying to calculate, and counting up how many points of each biome are in the sample, then it uses this info to blend the biomes at the given point.

The problem is that I have to loop through all of the sample points, and I keep getting the error “forced to unroll loop, but unrolling failed.” I've tried various different things to try and fix such as using the `[loop]` attribute, in which case I get “can't unroll loops marked with loop attribute”, and I've tried using the `[unroll()]` attribute to specify the amount of iterations the loop goes through, but I get the unrolling failed message again. I was wondering if anyone could suggest a solution? Here is my code:

```
#pragma kernel CSMain

struct BlendInputData
{
    int x;
    int z;
    int i;
    int blendRadius;
    int biomeIndexIterat;
    int xSize;
    int zSize;
};

StructuredBuffer<BlendInputData> inputData;
StructuredBuffer<int> biomeList;
RWStructuredBuffer<float4> outputData;

static int blendRadius = inputData[0].blendRadius;
static int biomeIndexIterat = inputData[0].biomeIndexIterat;
static int xSize = inputData[0].xSize;
static int zSize = inputData[0].zSize;

int MeshIndexToBiomeIndex(int meshIndex)
{
    int biomeIndex = meshIndex;
    biomeIndex += (2 * blendRadius * blendRadius) + (blendRadius * xSize);
    biomeIndex += floor((meshIndex / (xSize + 1)) + 1) * 2 * blendRadius;
    return biomeIndex;
};

float Vector2Distance(int xOne, int yOne, int xTwo, int yTwo)
{
    float distance = sqrt(pow(xOne - xTwo, 2) + pow(yOne - yTwo, 2));
    return distance;
};

[numthreads(1, 1, 1)]

void CSMain(uint3 id : SV_DispatchThreadID)
{
    RWStructuredBuffer<float> blendedBiome;
    int x = inputData[id.x].x;
    int z = inputData[id.x].z;
    int i = inputData[id.x].i;
    int index = MeshIndexToBiomeIndex(i) - biomeIndexIterat - blendRadius;
    for (int sampleZ = -blendRadius; sampleZ <= blendRadius; sampleZ++)
    {
        for (int sampleX = -blendRadius; sampleX <= blendRadius; sampleX++)
        {
            int iterator = 1 - (floor(Vector2Distance(x, z, sampleX + x, sampleZ + z) / blendRadius));
            int biome = biomeList[index];
            blendedBiome[biome] += iterator;
            index++;
        }
        index += (biomeIndexIterat / blendRadius) - (2 * blendRadius) - 1;
    }

    float denominator = pow(blendedBiome[0], 2) + pow(blendedBiome[1], 2) + pow(blendedBiome[2], 2) + pow(blendedBiome[3], 2);
    blendedBiome[0] = pow(blendedBiome[0], 2) / denominator;
    blendedBiome[1] = pow(blendedBiome[1], 2) / denominator;
    blendedBiome[2] = pow(blendedBiome[2], 2) / denominator;
    blendedBiome[3] = pow(blendedBiome[3], 2) / denominator;

    outputData[id.x].x = blendedBiome[0];
    outputData[id.x].y = blendedBiome[1];
    outputData[id.x].z = blendedBiome[2];
    outputData[id.x].w = blendedBiome[3];
}

```

# Answer
> 0 votes
I have encountered a similar issue and I believe it is because you are assigning data to an array inside the loop. If you comment out the blendedBiome\[biome\] line you should find it compiles fine. Though obviously the shader would no longer do the job you want.

I think it is because after compilation the shader may try to run multiple iterations of the loop simultaneouly and therefore can come into conflict if the results can go to the same location. So it does not like it. By unrolling the loops it can prevent that from happening.

Sorry for being so late answering this but I have been investigating it recently as I have the same issue. If there is a solution I would love to know.

---
Tags: compute-shader
---


title: OpenGL Two-point perspective view

text:
# Question
Title: OpenGL Two-point perspective view
### Summary:

I want vertical lines to be drawn as vertical lines regardless of their position relative to the camera (distance/offset). I want the projection to be perspective so the furthest objects from camera look smaller while keeping their respective proportions.

**What am I trying to achieve:** A two (vanishing) point perspective like this one http://insidetheoutline.com/wp-content/uploads/2019/07/2\_Point\_Perspective\_Cityscape.jpg

**Why am I at it:** I'm really bad at 3D (obviously) therefore I'm trying to replace character models with 2D sprites like in Populous 3, or "The Game" quest in Fable 3. I also want to have a top-downish view like in isometric games. Alas, perspective distortion totally kills the effect, making sprites look skewed whenever they are off-center.

**What am I doing right now:**

```
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity;
  gluPerspective(FOV, wndWidth / wndHeight, zNear, zFar);
  // Googling lead me to this MV matrix, alas it's not working for me
  // {
  //  1, 0, 0, 0,
  //  0, 1, 0, 0,
  //  0, -camY/camZ, -camZ, 0,
  //  0, 0, 0, 1
  // }
  glMatrixMode(GL_MODELVIEW);
  glLoadMatrixf(@cam);
  // camX = camY = camZ = 50
  gluLookAt(
    camX, camY, camZ,
    0, 0, 0,
    0, 0, 1
  );
  // then I draw a uniform grid -5..5 by -5..5
  // and slightly off-center wireframe box to test if they are drawn correctly

```

Does it work? No, it doesn't. Provided matrix produce no result at all, so I had to change it to `{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -camY/camZ, -camZ, 1}`. Just like any text on a two-point perspective says: "Set one of the values in the last column to zero". I tried zero in any position, except the last one, to no avail. Generally, I get something like this:

The rightmost vertical line--the one that aligns with screen center--is vertical, just as I want all of them to be, but the others are skewed away.

**What else I managed to google:** Not much, really. I found an example that kinda looks like something I want to achieve, but they place the camera at ground level with zero Z delta, effectively eliminating the third vanishing point. In some other example, they just narrowed FOV to some absurdly low value, making it look like a two-point perspective to some extent.

I'm afraid I'm missing or misunderstanding something. I also not sure if the desired output will, in fact, look like I want, and I won't discard it if it's not.

# Answer
For true undistorted two-point perspective, the camera must always face horizontally, otherwise vertical lines will not project to vertical lines. So you need to edit your 'gluLookAt' call to make the camera face horizontally.

Unfortunately, this means that the horizon line will be at eye level with the observer, i.e. in the center of the screen. If most of the action happens below that horizon line, you'll end up with half a screen full of sky. To fix that, you have a few options:

### 1. Keep the camera as it is, but shift the entire view up.

This will cause the horizon to move up on screen, but also changes the projection center, so the viewer will have to move his head up as far as the horizon moves to see an undistorted view again. Note that people are actually rather used to viewing screens at an angle, so this might be tolerable in certain cases.

To do this, modify your code as follows:

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
glTranslatef(0, 0.5, 0); // Change 0.5 to the amount of half-screens you want to shift the horizon by
//glScalef(1, 0.97, 1); // If perspective distortion becomes too great, try this to mitigate it.
gluPerspective(FOV, wndWidth / wndHeight, zNear, zFar);

```

This is a rather unorthodox position for glTranslatef to be called at, but it's perfectly legal and should do exactly the right thing. The effect of this is essentially to "scroll down" on the screen.

### 2. Tilt the camera slightly down, and tilt all your sprites by the same angle.

This one is a pretty cheap trick to make verticals look vertical again, but it can be very effective if the art style supports it. Try it and see if you like it.

### 3. Tilt the camera down and draw sprites untilted.

Yes, vertical lines will not be parallel to the screen borders, but you'll deal with it, because that's how perspective works in real life. Take a photo at an angle, verticals will be crooked too. If it really looks that wrong to you, try adjusting your FOV setting to match your real life FOV as determined by your chair and computer screen, and move the camera farther away if necessary.

### 4. Put the entire UI on the top half of the screen.

This solution is perfect from a perspective math standpoint, but its applicability severely depends on the type of game you're making. If you have a UI-heavy game with lots of menus and buttons and windows and stuff, the sky is free real estate. If your game is a minimalist RPG, then this solution is not for you.

### 5. Combine several of the previous options.

All these options are more or less compatible with one another. It's up to you to determine by experiment which combination suits your game best.
> 2 votes

# Answer
I don't know if you are still interested or not, but I wanted to achieve the exact effect you were looking for, and managed to arrive at a solution via some messing around with algebra. I'm not using OpenGL right now, but you'll be able to adapt it easily enough, I would think.

I'm a bit pushed for time right now so I'll just give the answer without the derivation and explanation, but if you're interested I can come back and give that later. Please note that in my game world, Z is used for height. If you are using Y for height, you'll need to adjust accordingly.

Here's what you need.

Starting off with your standard 2 matricies, `model` (or modelView as I think of it), and `proj` (standard perspective projection matrix), do this:

```
auto tempMatrix = model * proj;
auto tempMatrixInverse = inverse(tempMatrix);
tempMatrix[2][0] = 0;
tempMatrix[2][1] = -proj[1][1];
tempMatrix[2][2] = 0;
tempMatrix[2][3] = 0;
auto proj2PointPerspective = proj * tempMatrixInverse  * tempMatrix;

```

Now just use `proj2PointPerspective` as the projection matrix. You can could also then blend between this new matrix and the standard one, in order to get a mix between 3 point and 2 point perspective.
> 0 votes

---
Tags: opengl
---


# Question
Title: How to separate player characters occupying the same board game space?
I'm trying to create a 2D "board game" type thing in Unity, and I would like each player to be visible within the same space.

The way I want to do that is by having it so when a player collides with another player, which will happen when it enters the same space, it is pushed away from the other player by a certain amount to make it visible and not completely overlap, because the players use the same sprites and are the same size.

I've tried to do this myself, but I end up pushing both the player I want to stay and the player I want to be pushed, and I'm not sure what to do.

# Answer
> 0 votes
Instead of using colliders, use data.

If you have a board (say 12 by 12 squares) make an array\[12,12\] and store a list of players in each location.

You can then check if the number of players at that array location is \>1 and then position your sprites accordingly.

---
Tags: unity, 2d, sprites, collision-resolution, board-game
---