"""A low-poly figure built from simple shapes -- Open 3D Models tutorial script.

Run it from Blender's Scripting tab (Text > Open, then Run Script), or headless:
    blender -b -P lowpoly_figure.py
It makes a 1.8 m figure out of tapered prisms and spheres, gives every part a flat
colour, and saves lowpoly_figure.glb next to this script.

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

import bmesh
import bpy
from mathutils import Vector

COLOURS = {                     # name: (r, g, b) in sRGB 0..1
    "skin":   (0.85, 0.62, 0.48),
    "hair":   (0.30, 0.18, 0.10),
    "shirt":  (0.20, 0.42, 0.62),
    "trouser": (0.25, 0.25, 0.30),
    "shoe":   (0.12, 0.09, 0.07),
    "belt":   (0.45, 0.30, 0.15),
    "eye":    (0.05, 0.05, 0.06),
}


def material(name):
    m = bpy.data.materials.get(name)
    if m:
        return m
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    lin = [c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in COLOURS[name]]
    m.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (*lin, 1)
    m.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value = 0.8
    return m


def add(name, bm, colour):
    me = bpy.data.meshes.new(name)
    bm.to_mesh(me)
    bm.free()
    for p in me.polygons:
        p.use_smooth = False            # flat shading = the low-poly look
    me.materials.append(material(colour))
    ob = bpy.data.objects.new(name, me)
    bpy.context.scene.collection.objects.link(ob)
    return ob


def prism(name, colour, a, b, ra, rb, sides=6):
    """A tapered prism from point a (radius ra) to point b (radius rb): arms, legs, neck."""
    a, b = Vector(a), Vector(b)
    turn = Vector((0, 0, 1)).rotation_difference((b - a).normalized())
    bm = bmesh.new()
    rings = []
    for z, r in ((0, ra), ((b - a).length, rb)):
        rings.append([bm.verts.new(a + turn @ Vector((math.cos(2 * math.pi * i / sides) * r,
                                                      math.sin(2 * math.pi * i / sides) * r, z)))
                      for i in range(sides)])
    for i in range(sides):
        j = (i + 1) % sides
        bm.faces.new((rings[0][i], rings[0][j], rings[1][j], rings[1][i]))
    bm.faces.new(list(reversed(rings[0])))
    bm.faces.new(rings[1])
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
    return add(name, bm, colour)


def ball(name, colour, centre, size, segments=8, rings=6):
    """A low-resolution sphere, stretched by size=(x, y, z): head, hands, shoulders."""
    bm = bmesh.new()
    bmesh.ops.create_uvsphere(bm, u_segments=segments, v_segments=rings, radius=1)
    bmesh.ops.scale(bm, vec=size, verts=bm.verts)
    bmesh.ops.translate(bm, vec=Vector(centre), verts=bm.verts)
    return add(name, bm, colour)


def block(name, colour, centre, size):
    bm = bmesh.new()
    bmesh.ops.create_cube(bm, size=1)
    bmesh.ops.scale(bm, vec=size, verts=bm.verts)
    bmesh.ops.translate(bm, vec=Vector(centre), verts=bm.verts)
    return add(name, bm, colour)


def build():
    bpy.ops.wm.read_factory_settings(use_empty=True)
    # legs and shoes (mirrored with s = -1, +1)
    for s in (-1, 1):
        x = 0.09 * s
        prism("leg", "trouser", (x, 0, 0.88), (x, 0, 0.10), 0.075, 0.050)
        block("shoe", "shoe", (x, -0.03, 0.04), (0.10, 0.24, 0.08))
    # body: hips, belly, chest (a taper from waist to shoulders)
    prism("hips", "trouser", (0, 0, 0.84), (0, 0, 1.00), 0.16, 0.15, sides=8)
    prism("belt", "belt", (0, 0, 0.975), (0, 0, 1.025), 0.158, 0.162, sides=8)
    prism("chest", "shirt", (0, 0, 1.00), (0, 0, 1.45), 0.15, 0.20, sides=8)
    # arms hang slightly out from the body
    for s in (-1, 1):
        sh, el, wr = (0.21 * s, 0, 1.42), (0.26 * s, 0.01, 1.15), (0.28 * s, -0.02, 0.90)
        ball("shoulder", "shirt", sh, (0.07, 0.07, 0.07), 6, 4)
        prism("upper arm", "shirt", sh, el, 0.060, 0.050)
        prism("forearm", "skin", el, wr, 0.045, 0.035)
        ball("hand", "skin", (wr[0], wr[1], wr[2] - 0.06), (0.035, 0.03, 0.06), 6, 4)
    # neck, head, hair, eyes, nose
    prism("neck", "skin", (0, 0, 1.44), (0, 0, 1.56), 0.05, 0.045)
    ball("head", "skin", (0, 0, 1.65), (0.10, 0.11, 0.13), 10, 7)
    ball("hair", "hair", (0, 0.02, 1.70), (0.11, 0.115, 0.11), 10, 5)
    for s in (-1, 1):
        block("eye", "eye", (0.035 * s, -0.103, 1.66), (0.018, 0.01, 0.022))
    prism("nose", "skin", (0, -0.10, 1.65), (0, -0.135, 1.61), 0.018, 0.006, sides=4)


build()
out = os.path.join(os.path.dirname(os.path.abspath(__file__)) if "__file__" in dir() else ".",
                   "lowpoly_figure.glb")
bpy.ops.export_scene.gltf(filepath=out, export_format="GLB")
print("saved", out)
