Quick answer: ds_grid_set_grid_region doesn’t clip. The source rect and the destination offset must both stay inside their grids. Clamp the rect to the overlap of both before copying.
A chunk-based world copies a region from a generated grid into the world grid. Near the world edges it errors or writes garbage — the copy ran past the grid bounds.
Region Copy Has No Clipping
ds_grid_set_grid_region(dest, src, x1, y1, x2, y2, xpos, ypos) copies the source rect to (xpos, ypos) in dest. If that rect plus offset extends past dest’s size — or x1/y1/x2/y2 exceed src’s size — you get an out-of-bounds write.
Clamp Before Copying
var dw = ds_grid_width(dest);
var dh = ds_grid_height(dest);
// how much of the source actually fits at (xpos, ypos)
var cw = min(x2 - x1, dw - xpos) ;
var ch = min(y2 - y1, dh - ypos);
if (cw > 0 && ch > 0 && xpos >= 0 && ypos >= 0) {
ds_grid_set_grid_region(dest, src, x1, y1, x1 + cw, y1 + ch, xpos, ypos);
}
Compute the clipped width/height that fits, skip the copy entirely if nothing fits.
Also Clip the Negative Side
If xpos can be negative (chunk partly off the left edge), shift x1 right by -xpos and clamp xpos to 0. Handle both edges or you’ll only fix half the bug.
Verifying
Generate and copy chunks at every world edge and corner. No errors, no garbage rows. Interior chunks copy fully; edge chunks copy their visible portion.
“ds_grid region copy trusts you. Clamp the rect to the overlap of both grids before every copy.”
Wrap clamped region copy in one helper — every chunk system needs it, and the off-by-one math is easy to get wrong twice.