# blender -b -P crab_mask.py -- in.glb out_debug.glb out_tris.json  XMAX YMIN NZ
import bpy, sys, json, mathutils
a=sys.argv[sys.argv.index("--")+1:]; src,dbg,tris=a[0],a[1],a[2]; XMAX,YMIN,NZ=map(float,a[3:6])
bpy.ops.wm.read_factory_settings(use_empty=True); bpy.ops.import_scene.gltf(filepath=src)
o=[x for x in bpy.context.scene.objects if x.type=="MESH"][0]; me=o.data; mw=o.matrix_world; nm=mw.to_3x3().inverted().transposed()
vs=[mw@v.co for v in me.vertices]
xs=[v.x for v in vs]; ys=[v.y for v in vs]; zs=[v.z for v in vs]
print("RANGE x",min(xs),max(xs)," y",min(ys),max(ys)," z",min(zs),max(zs))
uv=me.uv_layers.active.data; out=[]
cyan=bpy.data.materials.new("cyan"); cyan.diffuse_color=(0,1,1,1); me.materials.append(cyan); ci=len(me.materials)-1
n=0
for p in me.polygons:
    c=mw@p.center; nn=(nm@p.normal).normalized()
    if abs(c.x)<XMAX and c.y>YMIN and (nn.z>NZ or nn.y>0.2):
        p.material_index=ci; n+=1
        out.append([[uv[li].uv[0],uv[li].uv[1]] for li in p.loop_indices])
print("FACES",n,len(me.polygons))
json.dump(out,open(tris,"w"))
bpy.ops.export_scene.gltf(filepath=dbg,export_format="GLB")
