aboutsummaryrefslogtreecommitdiffstats
path: root/blender/bolapeluda.py
blob: fe7a3773794e63e9fc768ba1c05d51ffae46f152 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# -*- coding: utf-8 -*-
"""BOLA PELUDA - the hairy ball theorem (Brouwer, 1912).

Each hair lies down along the tangent field v(p) = A x p, as much as the
field is strong: where |v| vanishes (the two poles of axis A) the hair has
nowhere to lie and stands up. So the swirl is not drawn by hand, it comes
from the same computation that combs the rest.
"""
import math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bpy
from mathutils import Vector, Matrix
from base import *

NAME_KEY = "bolapeluda"
R = 1.15                  # sphere radius
LARGO = 0.34              # hair length
K = 7                     # points per hair
N = 1500                  # number of hairs
THRESHOLD = 0.42             # |v| below this, the hair never lies down
CZ = 0.50                 # height of the centre in the frame

# Combings: (axis, kind). The axes lie almost in the screen plane (XZ) so the
# TWO zeros fall on the silhouette and show together.
#   rot -> field v = A x p          (combs in circles, like latitudes)
#   mer -> field v = A - (A.p) p    (combs from pole to pole, along meridians)
# Both vanish exactly where p is parallel to A: that is where the swirl is.
COMBINGS = [((0.80, -0.05, 0.60), "rot"),
            ((-0.58, -0.05, 0.82), "mer"),
            ((0.97, -0.08, -0.22), "rot"),
            ((0.12, -0.05, 0.99), "mer"),
            ((-0.86, -0.06, -0.50), "rot"),
            ((0.80, -0.05, 0.60), "rot")]


def normalize_text(v):
    n = math.sqrt(sum(c * c for c in v))
    return tuple(c / n for c in v) if n > 1e-9 else (0.0, 0.0, 1.0)


def cross_m(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def sphere_points(n):
    """Fibonacci spiral: spreads n points almost evenly over the sphere."""
    pts, ga = [], math.pi * (3 - math.sqrt(5))
    for i in range(n):
        z = 1 - 2 * (i + 0.5) / n
        r = math.sqrt(max(0.0, 1 - z * z))
        th = ga * i
        pts.append((r * math.cos(th), r * math.sin(th), z))
    return pts


def field(p, axis_obj, kind_m):
    if kind_m == "mer":
        d = sum(a * b for a, b in zip(axis_obj, p))
        return tuple(axis_obj[i] - d * p[i] for i in range(3))
    return cross_m(axis_obj, p)


def hair(p, axis_obj, combed, kind_m="rot", radio=R, largo=LARGO):
    """Returns the K points of the hair rooted at p and the value of |v| there."""
    v = field(p, axis_obj, kind_m)
    m = math.sqrt(sum(c * c for c in v))
    if m > 1e-6:
        t = tuple(c / m for c in v)
    else:                                  # at the zero there is no direction: it stands up
        t = normalize_text(cross_m(p, (0.0, 0.0, 1.0)) if abs(p[2]) < 0.9 else (1.0, 0.0, 0.0))
    b = combed * min(1.0, m / THRESHOLD)
    pos = [tuple(c * radio for c in p)]
    step = largo / (K - 1)
    for j in range(1, K):
        s = j / (K - 1.0)
        phi = b * (math.pi / 2) * s ** 0.85
        cs, sn = math.cos(phi), math.sin(phi)
        d = (p[0] * cs + t[0] * sn, p[1] * cs + t[1] * sn, p[2] * cs + t[2] * sn)
        a = pos[-1]
        pos.append((a[0] + d[0] * step, a[1] + d[1] * step, a[2] + d[2] * step))
    return pos, m


def torus_hairs(nu=60, nv=24, RT=0.90, rt=0.34, largo=0.22):
    """Donut hairs, combed by the toroidal tangent field: it never vanishes."""
    splines, radios = [], []
    for i in range(nu):
        u = 2 * math.pi * i / nu
        cu, su = math.cos(u), math.sin(u)
        for j in range(nv):
            w = 2 * math.pi * j / nv
            cw, sw = math.cos(w), math.sin(w)
            p = ((RT + rt * cw) * cu, (RT + rt * cw) * su, rt * sw)
            n = (cw * cu, cw * su, sw)                  # normal
            t = (-su, cu, 0.0)                          # toroidal tangent, |t| = 1
            pos = [p]
            step = largo / (K - 1)
            for k in range(1, K):
                s = k / (K - 1.0)
                phi = (math.pi / 2) * s ** 0.85
                cs, sn = math.cos(phi), math.sin(phi)
                d = (n[0] * cs + t[0] * sn, n[1] * cs + t[1] * sn, n[2] * cs + t[2] * sn)
                a = pos[-1]
                pos.append((a[0] + d[0] * step, a[1] + d[1] * step, a[2] + d[2] * step))
            splines.append(pos)
            radios.append([1.0 - 0.72 * (k / (K - 1.0)) for k in range(K)])
    return splines, radios


def build_scene(T):
    sc = scene_setup()
    lens, FRAME_H = 70.0, 6.0
    camera_obj((0.0, -lens / 36.0 * FRAME_H, 0.0), (0.0, 0.0, 0.0), lens=lens)
    bpy.context.scene.camera.data.sensor_fit = 'VERTICAL'
    bpy.context.scene.camera.data.sensor_height = 36.0

    light_obj("key", 'AREA', (-3.2, -4.6, 3.8), 800, "blanco", size_u=5.0, sight=(0, 0, CZ))
    light_obj("fill", 'AREA', (3.8, -3.6, -1.2), 260, "celeste", size_u=5.0, sight=(0, 0, CZ))
    light_obj("rim", 'AREA', (0.4, 4.2, 2.6), 620, "ambar", size_u=4.0, sight=(0, 0, CZ))

    rig = bpy.data.objects.new("rig", None)
    bpy.context.collection.objects.link(rig)
    rig.location = (0, 0, CZ)

    m_skin = material("piel", "azul", rough=0.55, metal=0.1)
    ball = sphere("bola", R * 0.985, m_skin, seg_m=64, rings=36)
    ball.parent = rig

    base_points = sphere_points(N)
    splines = [hair(p, COMBINGS[0][0], 0.0)[0] for p in base_points]
    radios = [[1.0 - 0.70 * (j / (K - 1.0)) for j in range(K)] for _ in base_points]
    hair_a = curve_poly("pelo_a", splines, thickness_px=0.0135, radios=radios,
                       mat=material("m_pelo", "ambar", rough=0.42, emit=0.55))
    hair_b = curve_poly("pelo_b", splines, thickness_px=0.0135, radios=radios,
                       mat=material("m_remol", "rosa", rough=0.42, emit=1.9))
    hair_a.parent = hair_b.parent = rig

    # marks on the zeros
    tick_list = []
    for k in range(2):
        g = bpy.data.objects.new(f"marca{k}", None)
        bpy.context.collection.objects.link(g)
        g.parent = rig
        ring = torus(f"anillo{k}", 0.34, 0.024,
                      material(f"mm{k}", "rosa", emit=3.2), u=48, v=10)
        ring.parent = g
        tick_list.append(g)

    # the donut, combed in one go
    sp_t, ra_t = torus_hairs()
    rig_t = bpy.data.objects.new("rig_toro", None)
    bpy.context.collection.objects.link(rig_t)
    rig_t.location = (0, 0, CZ)
    donut = torus("rosquilla", 0.90, 0.335, material("piel_t", "azul", rough=0.55))
    donut.parent = rig_t
    hair_t = curve_poly("pelo_toro", sp_t, thickness_px=0.0125, radios=ra_t,
                        mat=material("m_pelo_t", "verde", rough=0.42, emit=0.8))
    hair_t.parent = rig_t
    rig_t.rotation_mode = 'ZYX'        # first it spins about its axis, then it tilts
    rig_t.scale = (0, 0, 0)

    tag_m = {"esf": txt_m("2", size_u=0.52, color="ambar"),
           "ros": txt_m("0", size_u=0.52, color="verde"),
           "pie": txt_m("agujeros que cuentan", size_u=0.19, color="gris")}
    for o in tag_m.values():
        o.scale = (0, 0, 0)
    return dict(rig=rig, rig_t=rig_t, ball=ball, hair_a=hair_a, hair_b=hair_b,
                tick_list=tick_list, base=base_points, tag_m=tag_m, skin=m_skin, donut_obj=donut)


def main():
    T = Timeline(NAME_KEY)
    ob = build_scene(T)
    base, hair_a, hair_b = ob["base"], ob["hair_a"], ob["hair_b"]
    cache = {"clave": None}

    def comb(axis_idx, combed):
        key_name = (axis_idx, round(combed, 3))
        if cache["clave"] == key_name:
            return
        cache["clave"] = key_name
        axis_obj = normalize_text(COMBINGS[axis_idx][0])
        kind_m = COMBINGS[axis_idx][1]
        sp, ra_a, ra_b = [], [], []
        for p in base:
            pos, m = hair(p, axis_obj, combed, kind_m)
            sp.append(pos)
            tap = [1.0 - 0.70 * (j / (K - 1.0)) for j in range(K)]
            swirl = m < THRESHOLD * 0.62 and combed > 0.25
            ra_a.append([0.0 if swirl else t for t in tap])
            ra_b.append([t * 1.25 if swirl else 0.0 for t in tap])
        rebuild_curve(hair_a, sp