Got a question. I am working on a Voxel Engine for a game I’m working on. I have the voxel engine running good. I’ve created a Visual Node editor for generating the voxel terrain and I just over night multithreaded everything I possibly could. It’s running pretty smoothly. I am now adding new ways of generating the terrain and wanted to add in Height map support. I then remembered I can’t call any Unity API methods from threads other then the main thread. So I am now unable to call the get pixel method on the height map. What is the best way to add in Height map support with out using Unity’s built in methods?
I came up with the following which seems to work but is it the best way or is there a better way that I’m over looking?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace LibNoise.Generator
{
class Heightmap : ModuleBase
{
private Texture2D heightmap;
Dictionary<Vector2, Color> pixels = new Dictionary<Vector2, Color>();
private float width;
private float height;
private Vector2 Scale;
public Heightmap(Texture2D h)
: base(0)
{
if (h != null)
{
Scale = new Vector2(500, 500);
heightmap = h;
for (int x = 0; x < heightmap.width; x++)
{
for (int z = 0; z < heightmap.height; z++)
{
pixels.Add(new Vector2(x, z), heightmap.GetPixel(x, z));
}
}
width = heightmap.width;
height = heightmap.height;
}
}
public override double GetValue(double x, double y, double z)
{
int _x = Mathf.FloorToInt((float)x / Scale.x * width);
int _z = Mathf.FloorToInt((float)z / Scale.y * height);
Vector2 pos = new Vector2(_x, _z);
if (pixels.ContainsKey(pos))
return pixels[pos].grayscale;
return 0;
}
}
}