# Terrain Generation - Dividing a 2D Array Into Chunks

I have a rather difficult problem with my terrain generation plugin. I currently have it generating a single large 2D array with the outer array representing the X coordinate, the inner array representing the Z coordinate, and the final value representing the perlin noise value at those coordinates. This works perfectly, however if I were to go generate the terrain using these coordinates, depending on the input map size, it could easily result in a massive amount of lag.
To prevent this, I want to implement a “chunk” system, so instead of generating the entire map at once, it generates it in chunks 4 or 8 elements squared, with a very slight delay inbetween, making the process smoother and thereby improving user experience.
The problem is, I don’t know how I would go about dong this.

Here’s a small visualization of my noise map structure. The table indexes only go to 40, but in reality they could easily go above 5,000.
Note: I have the indexes incrementing by 4 since that is the minimum size of roblox’s terrain.

``````testTable = {
[4] = {
[4] = 0.53,
[8] = 0.62,
[12] = 0.37,
-- . . .
[40] = 0.98,
},
[8] = {
[4] = 0.21,
[8] = 0.73,
[12] = 0.57,
-- . . .
[40] = 0.56,
},
[12] = {
[4] = 0.23,
[8] = 0.42,
[12] = 0.14,
-- . . .
[40] = 0.01,
},
[16] = {
[4] = 0.09,
[8] = 0.67,
[12] = 0.72,
-- . . .
[40] = 1,
},
-- . . .
[40] = {
[4] = 0.37,
[8] = 0.61,
[12] = 0.96,
-- . . .
[40] = 0.05,
},
}
``````

Just thinking out loud here, you COULD store the position of an arbitrary corner of each chunk, and use that as the index for your table holding the chunks. Then, you can continue using your current system, except now they’re broken up into more individual datasets that can be generated individually. You can also store them with indicies in a specific range, knowing the position of the chunk and the size of each unit of terrain, and this allows you to use a numerical for loop instead, and just multiply the index by the unit size and add that to the chunk position

As for optimizing this any better than it’s already been, The only way I can think of is to use the full X-Y position as the index, and store values in a 1D array, as opposed to needing to do more than one table index, but I’m not sure that will provide any noticeable performance boost, if any at all.

In the Luau documentation, they state that a numerical loop is actually slower than a generic loop. Considering you are indexing a table in the numeric loop.

As suggested in discord, the best solution would be to have a delay at which you generate the terrain to increase performance. To do this you could dynamically change the delay between each (or every 2, 4, 8, 16, 32) generation(s) by the player’s FPS. When they drop FPS, you know to increase the delay and/or increase the number of generations per interval.

True. I guess it doesn’t need to be fancy. Looks like it was just a case of me overthinking things again. ¯\_(ツ)_/¯