"""Turn letters and numbers into solid 3D models -- Open 3D Models tutorial script.

    blender -b -P text_to_3d.py -- "HELLO 2026"
One model per character (spaces skipped), each saved as FBX and GLB in a folder
text_to_3d/ next to this script. Change HEIGHT, DEPTH, DETAIL or FONT below.

Licence: CC BY 4.0, Open 3D Models (open3dmodel.org)
"""
import os
import sys

import bmesh
import bpy
from mathutils import Vector

HEIGHT = 20.0     # capital letter height, in Blender units
DEPTH = 5.0       # how thick the letters are
DETAIL = 5        # curve steps per segment: lower = fewer triangles, more faceted curves
FONT = None       # path to a .ttf/.otf you are allowed to redistribute; None = Blender's own font

text = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "ABC123"
here = os.path.dirname(os.path.abspath(__file__)) if "__file__" in globals() else "."
out_dir = os.path.join(here, "text_to_3d")
os.makedirs(out_dir, exist_ok=True)


def character(ch):
    bpy.ops.wm.read_factory_settings(use_empty=True)
    curve = bpy.data.curves.new(ch, "FONT")         # same as Add > Text in the viewport
    curve.body = ch
    if FONT:
        curve.font = bpy.data.fonts.load(FONT)
    curve.size = 1.0
    curve.resolution_u = DETAIL
    curve.extrude = 0.5                              # Object Data > Geometry > Extrude
    temp = bpy.data.objects.new("temp", curve)
    bpy.context.scene.collection.objects.link(temp)
    graph = bpy.context.evaluated_depsgraph_get()
    mesh = bpy.data.meshes.new_from_object(temp.evaluated_get(graph))   # = Convert to Mesh
    bpy.data.objects.remove(temp)

    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5)
    lo = Vector([min(v.co[i] for v in bm.verts) for i in range(3)])
    hi = Vector([max(v.co[i] for v in bm.verts) for i in range(3)])
    scale = HEIGHT / 0.7                 # capitals are 0.7 high at size 1 in Blender's font
    for v in bm.verts:                   # stand it up: height on Z, depth on Y, centred
        v.co = Vector(((v.co.x - (lo.x + hi.x) / 2) * scale,
                       -(v.co.z - (lo.z + hi.z) / 2) * DEPTH / (hi.z - lo.z),
                       v.co.y * scale))
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
    bm.to_mesh(mesh)
    bm.free()
    for poly in mesh.polygons:
        poly.use_smooth = False

    ob = bpy.data.objects.new(ch, mesh)
    bpy.context.scene.collection.objects.link(ob)
    name = {"?": "question-mark", "!": "exclamation", ".": "dot", "&": "ampersand"}.get(ch, ch)
    bpy.ops.export_scene.fbx(filepath=os.path.join(out_dir, name + ".fbx"),
                             apply_scale_options="FBX_SCALE_ALL")
    bpy.ops.export_scene.gltf(filepath=os.path.join(out_dir, name + ".glb"), export_format="GLB")
    print(ch, "->", name, sum(len(p.vertices) - 2 for p in mesh.polygons), "triangles")


for ch in dict.fromkeys(text.replace(" ", "")):    # each character once, in order
    character(ch)
