# Terrain Chunking Logic, bpy

I'm just getting into scripting in blender, and I'm trying to write a script that will split a terrain mesh into equal chunks. This is what I have so far

import bpy

terrain = bpy.context.active_object

chunk_size = 31

#deselect all faces
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.editmode_toggle()

#main loop
for i in range(16):
#select chunk_base
obj = bpy.context.active_object
obj.data.polygons[0].select = True

#enter_edit_mode
bpy.ops.object.editmode_toggle()

#select_chunk
for i in range(chunk_size):
bpy.ops.mesh.select_more()

#separate chunk
bpy.ops.mesh.separate(type='SELECTED')

#exit_editmode
bpy.ops.object.editmode_toggle()


And it does split the mesh into chunks of equal sizes, however, if I were to apply this to a larger, or higher resolution mesh, it would still create only 16 chunks, due to the range in the for loop. I need to find a way to automatically set the number of iterations of the loop, based on the number of vertices in the mesh.

I've thought of using the dimensions of the mesh, however this wouldn't account for the resolution of the mesh.

Any suggestions would be helpful. thank you.

I did it!,

based on a comment on this post from 'batFINGER', suggesting to get the number of vertices using:

len(obj.data.polygons)


I initially thought of calculating the number of chunks that the terrain will need based on the returned value, however this would mean that it would only work on squair terrains.

However, moving off of this solution I converted the for loop to a while loop, this means that I will continue to create chunks as long as the object has any polygons left. This is my final code :

import bpy

terrain = bpy.context.active_object

chunk_size = 31

#deselect all faces
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.editmode_toggle()

#main loop
while len(terrain.data.vertices) > 0:
#select chunk_base
obj = bpy.context.active_object
obj.data.polygons[0].select = True

#enter_edit_mode
bpy.ops.object.editmode_toggle()

#select_chunk
for i in range(chunk_size):
bpy.ops.mesh.select_more()

#separate chunk
bpy.ops.mesh.separate(type='SELECTED')

#exit_editmode
bpy.ops.object.editmode_toggle()