motionkit2d 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- motionkit2d/__init__.py +49 -0
- motionkit2d/__main__.py +115 -0
- motionkit2d/acceleration.py +121 -0
- motionkit2d/assets.py +319 -0
- motionkit2d/audio.py +87 -0
- motionkit2d/audio_analysis.py +55 -0
- motionkit2d/camera.py +56 -0
- motionkit2d/catalog.py +79 -0
- motionkit2d/characters/__init__.py +4 -0
- motionkit2d/characters/actions.py +125 -0
- motionkit2d/characters/builder.py +15 -0
- motionkit2d/characters/expressions.py +81 -0
- motionkit2d/compiler.py +162 -0
- motionkit2d/composition.py +50 -0
- motionkit2d/constraints.py +91 -0
- motionkit2d/cues.py +15 -0
- motionkit2d/draw.py +416 -0
- motionkit2d/dynamics.py +109 -0
- motionkit2d/effects.py +131 -0
- motionkit2d/environments.py +86 -0
- motionkit2d/export.py +235 -0
- motionkit2d/fonts/LICENSE.txt +130 -0
- motionkit2d/fonts/LiberationSans-Regular.ttf +0 -0
- motionkit2d/fonts/LiberationSerif-Bold.ttf +0 -0
- motionkit2d/fonts/LiberationSerif-Regular.ttf +0 -0
- motionkit2d/gpu.py +512 -0
- motionkit2d/layout.py +89 -0
- motionkit2d/manifest.py +96 -0
- motionkit2d/mixer.py +92 -0
- motionkit2d/preset_library.py +41 -0
- motionkit2d/presets.py +33 -0
- motionkit2d/props.py +126 -0
- motionkit2d/qc.py +78 -0
- motionkit2d/quality.py +122 -0
- motionkit2d/rig.py +325 -0
- motionkit2d/scene_graph.py +154 -0
- motionkit2d/timeline.py +174 -0
- motionkit2d/transitions.py +51 -0
- motionkit2d/typography.py +118 -0
- motionkit2d/visual_effects.py +104 -0
- motionkit2d-1.0.0.dist-info/METADATA +140 -0
- motionkit2d-1.0.0.dist-info/RECORD +45 -0
- motionkit2d-1.0.0.dist-info/WHEEL +5 -0
- motionkit2d-1.0.0.dist-info/entry_points.txt +2 -0
- motionkit2d-1.0.0.dist-info/top_level.txt +1 -0
motionkit2d/audio.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Audio sources positioned in seconds on the output video timeline."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from math import isfinite
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class AudioCue:
|
|
9
|
+
path: str | Path
|
|
10
|
+
start: float = 0
|
|
11
|
+
volume: float = 1
|
|
12
|
+
source_offset: float = 0
|
|
13
|
+
duration: float | None = None
|
|
14
|
+
fade_in: float = 0
|
|
15
|
+
fade_out: float = 0
|
|
16
|
+
loop: bool = False
|
|
17
|
+
kind: str = 'sfx'
|
|
18
|
+
envelope: tuple = () # (local seconds, gain), linearly interpolated
|
|
19
|
+
ducking: float = 1 # BGM multiplier while a voice cue is active
|
|
20
|
+
|
|
21
|
+
def __post_init__(self):
|
|
22
|
+
if any(not isfinite(v) or v<0 for v in (self.start,self.volume,self.source_offset,self.fade_in,self.fade_out,self.ducking)):
|
|
23
|
+
raise ValueError('Audio start and volume must be finite and nonnegative')
|
|
24
|
+
if self.duration is not None and (not isfinite(self.duration) or self.duration<=0):
|
|
25
|
+
raise ValueError('Audio duration must be positive')
|
|
26
|
+
if self.kind not in {'bgm','sfx','voice'} or self.ducking>1 or type(self.loop) is not bool:
|
|
27
|
+
raise ValueError('Invalid audio kind, loop or ducking gain')
|
|
28
|
+
previous=-1
|
|
29
|
+
for time,gain in self.envelope:
|
|
30
|
+
if not isfinite(time) or not isfinite(gain) or time<0 or gain<0 or time<=previous:
|
|
31
|
+
raise ValueError('Envelope requires increasing nonnegative times and gains')
|
|
32
|
+
previous=time
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def source_duration(path):
|
|
36
|
+
import json
|
|
37
|
+
import shutil
|
|
38
|
+
import subprocess
|
|
39
|
+
ffprobe=shutil.which('ffprobe')
|
|
40
|
+
if not ffprobe: raise FileNotFoundError('ffprobe required for audio duration')
|
|
41
|
+
result=subprocess.check_output([ffprobe,'-v','error','-show_entries','format=duration','-of','json',str(path)])
|
|
42
|
+
return float(json.loads(result)['format']['duration'])
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def cue_length(cue,seconds):
|
|
46
|
+
available=max(0,seconds-cue.start)
|
|
47
|
+
if cue.loop: return available
|
|
48
|
+
source=max(0,source_duration(cue.path)-cue.source_offset)
|
|
49
|
+
length=min(cue.duration,source) if cue.duration is not None else source
|
|
50
|
+
return min(available,length)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def audio_filters(cues,seconds,rate=48000):
|
|
54
|
+
"""FFmpeg filter graph; cue envelopes use local track time before delay."""
|
|
55
|
+
filters=[]
|
|
56
|
+
voices=[(cue.start,cue.start+cue_length(cue,seconds)) for cue in cues if cue.kind=='voice']
|
|
57
|
+
for i,cue in enumerate(cues,1):
|
|
58
|
+
operations=[f'aresample={rate}',f'atrim=start={cue.source_offset}'+(f':duration={cue.duration}' if cue.duration is not None else ''),'asetpts=PTS-STARTPTS']
|
|
59
|
+
length=None
|
|
60
|
+
if cue.loop:
|
|
61
|
+
source=max(0,source_duration(cue.path)-cue.source_offset)
|
|
62
|
+
segment=min(source,cue.duration) if cue.duration is not None else source
|
|
63
|
+
if segment<=0: raise ValueError('Cannot loop an empty audio segment')
|
|
64
|
+
operations.append(f'aloop=loop=-1:size={max(1,round(segment*rate))}')
|
|
65
|
+
if cue.fade_out or cue.loop or (cue.kind=='bgm' and cue.ducking<1):
|
|
66
|
+
length=cue_length(cue,seconds)
|
|
67
|
+
operations.append(f'atrim=duration={length:.9f}')
|
|
68
|
+
if cue.fade_in: operations.append(f'afade=t=in:st=0:d={cue.fade_in}')
|
|
69
|
+
if cue.fade_out and length:
|
|
70
|
+
fade=min(length,cue.fade_out)
|
|
71
|
+
operations.append(f'afade=t=out:st={length-fade:.9f}:d={fade:.9f}')
|
|
72
|
+
expression=str(cue.volume)
|
|
73
|
+
if cue.envelope:
|
|
74
|
+
points=cue.envelope
|
|
75
|
+
env=str(points[-1][1])
|
|
76
|
+
for (a,ga),(b,gb) in reversed(list(zip(points,points[1:]))):
|
|
77
|
+
env=f'if(lt(t,{b}),{ga}+({gb-ga})*(t-{a})/{b-a},{env})'
|
|
78
|
+
env=f'if(lt(t,{points[0][0]}),{points[0][1]},{env})'
|
|
79
|
+
expression+=f'*({env})'
|
|
80
|
+
if cue.kind=='bgm' and cue.ducking<1:
|
|
81
|
+
active='+'.join(f'(gte(t,{start-cue.start})*lt(t,{end-cue.start}))' for start,end in voices)
|
|
82
|
+
if active: expression+=f'*if(gt({active},0),{cue.ducking},1)'
|
|
83
|
+
operations.extend([f"volume='{expression}':eval=frame",f'adelay={round(cue.start*rate)}S:all=1'])
|
|
84
|
+
filters.append(f'[{i}:a:0]'+','.join(operations)+f'[a{i}]')
|
|
85
|
+
inputs=''.join(f'[a{i}]' for i in range(1,len(cues)+1))
|
|
86
|
+
filters.append(f'{inputs}amix=inputs={len(cues)}:normalize=0,apad,atrim=duration={seconds:.9f}[mix]')
|
|
87
|
+
return filters
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""PCM analysis via FFmpeg. Beat estimates are onset heuristics, not ground truth."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from math import isfinite
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class BeatMap:
|
|
12
|
+
times: tuple
|
|
13
|
+
bpm: float | None = None
|
|
14
|
+
|
|
15
|
+
def nearest(self,time):
|
|
16
|
+
if not self.times: raise ValueError('Beat map is empty')
|
|
17
|
+
return min(self.times,key=lambda value:abs(value-time))
|
|
18
|
+
|
|
19
|
+
def phase(self,time):
|
|
20
|
+
if self.bpm is None or self.bpm<=0: raise ValueError('Beat map has no BPM')
|
|
21
|
+
return ((time-(self.times[0] if self.times else 0))*self.bpm/60)%1
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def decode_audio(path,*,rate=22050,mono=True):
|
|
25
|
+
if type(rate) is not int or rate<1000: raise ValueError('Invalid sample rate')
|
|
26
|
+
ffmpeg=shutil.which('ffmpeg')
|
|
27
|
+
if not ffmpeg: raise FileNotFoundError('ffmpeg required for audio analysis')
|
|
28
|
+
raw=subprocess.check_output([ffmpeg,'-v','error','-i',str(path),'-vn',*(['-ac','1'] if mono else []),'-ar',str(rate),'-f','f32le','pipe:1'])
|
|
29
|
+
return np.frombuffer(raw,dtype='<f4').copy(),rate
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def analyze_samples(samples,rate,*,window=.02,min_interval=.25):
|
|
33
|
+
values=np.asarray(samples,dtype=float)
|
|
34
|
+
if values.ndim!=1 or not len(values) or not np.all(np.isfinite(values)) or rate<=0 or window<=0 or min_interval<=0:
|
|
35
|
+
raise ValueError('Expected nonempty finite mono PCM and positive timing')
|
|
36
|
+
size=max(1,round(rate*window)); count=(len(values)+size-1)//size
|
|
37
|
+
padded=np.pad(values,(0,count*size-len(values))).reshape(count,size)
|
|
38
|
+
rms=np.sqrt(np.mean(padded*padded,axis=1)); onset=np.maximum(0,np.diff(rms,prepend=0))
|
|
39
|
+
threshold=max(float(np.max(onset))*.12,float(np.median(onset)+2*np.std(onset)))
|
|
40
|
+
candidates=[i for i in range(len(onset)) if onset[i]>threshold and onset[i]>=onset[max(0,i-1)] and onset[i]>=onset[min(len(onset)-1,i+1)]]
|
|
41
|
+
selected=[]
|
|
42
|
+
for i in candidates:
|
|
43
|
+
if not selected or (i-selected[-1])*size/rate>=min_interval: selected.append(i)
|
|
44
|
+
elif onset[i]>onset[selected[-1]]: selected[-1]=i
|
|
45
|
+
times=tuple(i*size/rate for i in selected)
|
|
46
|
+
bpm=float(60/np.median(np.diff(times))) if len(times)>=3 else None
|
|
47
|
+
peak=float(np.max(np.abs(values)))
|
|
48
|
+
return {'seconds':len(values)/rate,'peak':peak,'rms':float(np.sqrt(np.mean(values*values))),
|
|
49
|
+
'clipped_samples':int(np.count_nonzero(np.abs(values)>=1)),
|
|
50
|
+
'waveform':rms.tolist(),'window_seconds':size/rate,'beats':BeatMap(times,bpm)}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def analyze_audio(path,**options):
|
|
54
|
+
samples,rate=decode_audio(path)
|
|
55
|
+
return analyze_samples(samples,rate,**options)
|
motionkit2d/camera.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""World-space camera; positive rotation follows the rig's CCW convention."""
|
|
2
|
+
from dataclasses import dataclass, replace
|
|
3
|
+
from math import isfinite, sin, pi, exp
|
|
4
|
+
|
|
5
|
+
from .rig import Transform
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class Camera2D:
|
|
10
|
+
x: float = 0
|
|
11
|
+
y: float = 0
|
|
12
|
+
scale: float = 1
|
|
13
|
+
rotation: float = 0
|
|
14
|
+
|
|
15
|
+
def __post_init__(self):
|
|
16
|
+
Transform(self.x,self.y,self.scale,self.rotation)
|
|
17
|
+
|
|
18
|
+
def transform(self,width,height):
|
|
19
|
+
tr=Transform(scale=self.scale,rotation=-self.rotation)
|
|
20
|
+
dx,dy=tr.vector((-self.x,-self.y))
|
|
21
|
+
return Transform(width/2+dx,height/2+dy,self.scale,-self.rotation)
|
|
22
|
+
|
|
23
|
+
def world_to_screen(self,point,width,height):
|
|
24
|
+
return self.transform(width,height).point(point)
|
|
25
|
+
|
|
26
|
+
def screen_to_world(self,point,width,height):
|
|
27
|
+
from .scene_graph import inverse_point
|
|
28
|
+
return inverse_point(self.transform(width,height),point)
|
|
29
|
+
|
|
30
|
+
def pan(self,dx,dy): return replace(self,x=self.x+dx,y=self.y+dy)
|
|
31
|
+
def zoom(self,factor): return replace(self,scale=self.scale*factor)
|
|
32
|
+
def focus_on(self,point): return replace(self,x=point[0],y=point[1])
|
|
33
|
+
def dolly(self,point,factor): return self.focus_on(point).zoom(factor)
|
|
34
|
+
def follow(self,target,t=0,anchor='head'): return self.focus_on(target.anchor(anchor,t))
|
|
35
|
+
|
|
36
|
+
def shake(self,t,*,amplitude=3,frequency=18):
|
|
37
|
+
return self.pan(amplitude*sin(t*frequency*2*pi),amplitude*sin(t*frequency*2*pi*1.37))
|
|
38
|
+
|
|
39
|
+
def impulse(self,t,*,start=0,duration=.4,amplitude=8):
|
|
40
|
+
if duration<=0 or not all(isfinite(v) for v in (t,start,duration,amplitude)):
|
|
41
|
+
raise ValueError('Invalid camera impulse')
|
|
42
|
+
elapsed=t-start
|
|
43
|
+
return self if elapsed<0 or elapsed>=duration else self.shake(elapsed,amplitude=amplitude*exp(-6*elapsed/duration))
|
|
44
|
+
|
|
45
|
+
def parallax(self,depth):
|
|
46
|
+
if not isfinite(depth) or depth<0: raise ValueError('Depth must be nonnegative')
|
|
47
|
+
return replace(self,x=self.x*depth,y=self.y*depth)
|
|
48
|
+
|
|
49
|
+
def frame_subjects(self,bounds,width,height,*,padding=30):
|
|
50
|
+
bounds=tuple(bounds)
|
|
51
|
+
if not bounds or padding<0 or width<=2*padding or height<=2*padding:
|
|
52
|
+
raise ValueError('Invalid framing bounds or padding')
|
|
53
|
+
x0=min(b.x for b in bounds); y0=min(b.y for b in bounds)
|
|
54
|
+
x1=max(b.x+b.width for b in bounds); y1=max(b.y+b.height for b in bounds)
|
|
55
|
+
scale=min((width-2*padding)/max(1,x1-x0),(height-2*padding)/max(1,y1-y0))
|
|
56
|
+
return Camera2D((x0+x1)/2,(y0+y1)/2,scale)
|
motionkit2d/catalog.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Inspectable asset registry. Projects may register their own namespaced props."""
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
|
|
4
|
+
from . import draw
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class Asset:
|
|
9
|
+
name: str
|
|
10
|
+
size: tuple
|
|
11
|
+
anchors: dict
|
|
12
|
+
paint: object
|
|
13
|
+
defaults: dict = field(default_factory=dict)
|
|
14
|
+
description: str = ''
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Registry:
|
|
18
|
+
def __init__(self):
|
|
19
|
+
self._assets={}
|
|
20
|
+
|
|
21
|
+
def register(self,asset):
|
|
22
|
+
from math import isfinite
|
|
23
|
+
if '.' not in asset.name or asset.name in self._assets:
|
|
24
|
+
raise ValueError('Asset needs a unique package.name')
|
|
25
|
+
if len(asset.size)!=2 or any(type(v) is not int or v<=0 for v in asset.size):
|
|
26
|
+
raise ValueError('Asset size must be positive')
|
|
27
|
+
if not callable(asset.paint) or any(len(p)!=2 or not all(isfinite(v) for v in p) for p in asset.anchors.values()):
|
|
28
|
+
raise ValueError('Asset needs a painter and finite 2D anchors')
|
|
29
|
+
self._assets[asset.name]=asset
|
|
30
|
+
return asset
|
|
31
|
+
|
|
32
|
+
def get(self,name):
|
|
33
|
+
return self._assets[name]
|
|
34
|
+
|
|
35
|
+
def describe(self):
|
|
36
|
+
return [dict(name=a.name,package=a.name.rsplit('.',1)[0],size=a.size,
|
|
37
|
+
anchors=a.anchors,parameters=a.defaults,description=a.description,
|
|
38
|
+
usage=f"Prop(catalog.get('{a.name}'), transform=Transform(x=100, y=100))")
|
|
39
|
+
for a in self._assets.values()]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def chair(im, wood, metal):
|
|
43
|
+
d=draw.draw(im)
|
|
44
|
+
draw.rect(d,9,4,64,63,8,wood)
|
|
45
|
+
draw.rect(d,16,13,50,43,4,'#D8B588')
|
|
46
|
+
for x in (15,69):
|
|
47
|
+
draw.line(d,[(x,64),(x-3,142)],metal,7,True)
|
|
48
|
+
draw.rect(d,3,68,78,12,4,wood)
|
|
49
|
+
draw.line(d,[(10,118),(69,118)],metal,3)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def backpack(im, color, pocket):
|
|
53
|
+
d=draw.draw(im)
|
|
54
|
+
draw.line(d,[(17,18),(17,6),(33,6),(33,18)],'#233B50',5,True)
|
|
55
|
+
draw.rect(d,3,17,44,56,10,color)
|
|
56
|
+
draw.rect(d,10,42,30,24,6,pocket)
|
|
57
|
+
draw.line(d,[(13,48),(36,48)],'#EBC584',2)
|
|
58
|
+
draw.line(d,[(12,23),(12,34)],'#DCE9EA',2)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def board(im, color, frame):
|
|
62
|
+
d=draw.draw(im)
|
|
63
|
+
draw.rect(d,0,0,360,140,7,frame)
|
|
64
|
+
draw.rect(d,8,8,344,120,3,color)
|
|
65
|
+
draw.text(im,180,49,'LỚP HỌC',26,c='#D5E8D8',style='sans')
|
|
66
|
+
draw.line(d,[(58,83),(302,83)],'#99B9AA',1.5)
|
|
67
|
+
draw.text(im,180,105,'Mỗi ngày, một điều mới',14,c='#D5E8D8',style='sans')
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
catalog=Registry()
|
|
71
|
+
catalog.register(Asset('school.chair',(84,146),{'seat':(42,68),'feet':(42,146)},chair,
|
|
72
|
+
dict(wood='#B98555',metal='#415460'),'Chair; seat is top surface'))
|
|
73
|
+
catalog.register(Asset('school.backpack',(50,76),{'handle':(25,6),'bottom':(25,73)},backpack,
|
|
74
|
+
dict(color='#D58A57',pocket='#B96C43'),'Backpack held by handle'))
|
|
75
|
+
catalog.register(Asset('school.board',(360,140),{'center':(180,70)},board,
|
|
76
|
+
dict(color='#244E47',frame='#BB966B'),'Classroom chalkboard'))
|
|
77
|
+
|
|
78
|
+
from .props import register_props
|
|
79
|
+
register_props(catalog)
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Procedural action clips. Time is seconds; sampling is deterministic.
|
|
2
|
+
|
|
3
|
+
Social clips provide gestures; partner placement and object transfer use
|
|
4
|
+
scene transforms and Attachment constraints, not an automatic planner.
|
|
5
|
+
"""
|
|
6
|
+
from dataclasses import dataclass, replace
|
|
7
|
+
from math import sin, cos, pi, isfinite
|
|
8
|
+
|
|
9
|
+
from .expressions import Face
|
|
10
|
+
|
|
11
|
+
_NAMES = ('stand walk breathe blink idle look_around run turn step_back walk_away '
|
|
12
|
+
'lie_down lean kneel crouch wave point nod shake_head cry laugh tremble sigh '
|
|
13
|
+
'texting scroll phone_call check_phone hug handshake hold_hands push_away '
|
|
14
|
+
'pick_up put_down drink throw').split()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def action_names():
|
|
18
|
+
return tuple(_NAMES)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class Action:
|
|
23
|
+
name: str
|
|
24
|
+
speed: float = 1
|
|
25
|
+
intensity: float = 1
|
|
26
|
+
|
|
27
|
+
def __post_init__(self):
|
|
28
|
+
if self.name not in _NAMES:
|
|
29
|
+
raise ValueError(f'Unknown action: {self.name}')
|
|
30
|
+
if not isfinite(self.speed) or self.speed<=0 or not isfinite(self.intensity) or not 0<=self.intensity<=1:
|
|
31
|
+
raise ValueError('Action needs positive speed and intensity in [0,1]')
|
|
32
|
+
|
|
33
|
+
def pose(self,t,appearance):
|
|
34
|
+
from ..rig import Pose, stand, walk, sit, reach
|
|
35
|
+
n=self.name; t=t*self.speed; s=sin(2*pi*t); c=cos(2*pi*t)
|
|
36
|
+
base=stand(appearance)
|
|
37
|
+
if n in {'walk','walk_away','step_back','run'}:
|
|
38
|
+
result=walk(-t if n=='step_back' else t,appearance,stride=34 if n=='run' else 22,period=.45 if n=='run' else .8)
|
|
39
|
+
return base.blend(result,self.intensity)
|
|
40
|
+
j=dict(base.joints)
|
|
41
|
+
if n=='turn':
|
|
42
|
+
j={k:(x*cos(pi*min(1,max(0,t))),y) for k,(x,y) in j.items()}
|
|
43
|
+
if n in {'breathe','idle','sigh','cry','laugh','tremble'}:
|
|
44
|
+
offset=(1.5*s if n not in {'tremble','cry'} else 1.5*sin(35*t))
|
|
45
|
+
for k,(x,y) in j.items():
|
|
46
|
+
if k not in {'feet','foot_left','foot_right'}:
|
|
47
|
+
j[k]=(x+(offset if n=='tremble' else 0),y+offset)
|
|
48
|
+
if n in {'crouch','kneel'}:
|
|
49
|
+
j=dict(sit(appearance).joints)
|
|
50
|
+
for k in ('hip','head','shoulder_left','shoulder_right','elbow_left','elbow_right','hand_left','hand_right'):
|
|
51
|
+
x,y=j[k]; j[k]=(x,y+30)
|
|
52
|
+
if n=='kneel': j['knee_left']=(-20,-3); j['foot_left']=(-50,0)
|
|
53
|
+
if n=='lie_down':
|
|
54
|
+
j={k:(-y,x-20) for k,(x,y) in j.items()}
|
|
55
|
+
if n=='lean':
|
|
56
|
+
j={k:(x-y*.18,y) for k,(x,y) in j.items()}
|
|
57
|
+
if n in {'nod','shake_head'}:
|
|
58
|
+
x,y=j['head']; j['head']=(x+(4*s if n=='shake_head' else 0),y+(3*s if n=='nod' else 0))
|
|
59
|
+
targets={
|
|
60
|
+
'wave':(46+8*s,-199), 'point':(89,-168),
|
|
61
|
+
'texting':(20,-142), 'scroll':(20+3*s,-142),
|
|
62
|
+
'check_phone':(25,-144), 'phone_call':(23,-191),
|
|
63
|
+
'hug':(47,-151), 'handshake':(60,-125),
|
|
64
|
+
'hold_hands':(55,-110), 'push_away':(80,-160),
|
|
65
|
+
'pick_up':(30,-105+25*c), 'put_down':(30,-105-25*c),
|
|
66
|
+
'drink':(18,-185), 'throw':(35+35*s,-175-15*c),
|
|
67
|
+
}
|
|
68
|
+
if n in targets:
|
|
69
|
+
# Targets are relative to the actual shoulder, so torso proportions work.
|
|
70
|
+
tx,ty=targets[n]; shoulder=j['shoulder_right']
|
|
71
|
+
target=(shoulder[0]+tx-17,shoulder[1]+ty+168)
|
|
72
|
+
dx,dy=target[0]-shoulder[0],target[1]-shoulder[1]
|
|
73
|
+
distance=(dx*dx+dy*dy)**.5
|
|
74
|
+
if distance>77:
|
|
75
|
+
target=(shoulder[0]+dx*77/distance,shoulder[1]+dy*77/distance)
|
|
76
|
+
j=dict(reach(Pose(j),target).joints)
|
|
77
|
+
if n in {'texting','hug'}:
|
|
78
|
+
right=j['hand_right']; left=j['shoulder_left']
|
|
79
|
+
target=(right[0]-12,right[1]+3)
|
|
80
|
+
dx,dy=target[0]-left[0],target[1]-left[1]; distance=(dx*dx+dy*dy)**.5
|
|
81
|
+
if distance>77: target=(left[0]+dx*77/distance,left[1]+dy*77/distance)
|
|
82
|
+
j=dict(reach(Pose(j),target,side='left',bend=-1).joints)
|
|
83
|
+
return base.blend(Pose(j),self.intensity)
|
|
84
|
+
|
|
85
|
+
def face(self,t,base):
|
|
86
|
+
if self.name=='blink': return replace(base,blink=(t*self.speed)%3<.12)
|
|
87
|
+
if self.name=='look_around': return replace(base,gaze=(sin(t*self.speed*2),0))
|
|
88
|
+
if self.name=='cry': return Face('cry',self.intensity,tears=self.intensity)
|
|
89
|
+
if self.name=='laugh': return Face('laugh',self.intensity)
|
|
90
|
+
return base
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Performance:
|
|
94
|
+
"""Override selected arm/head joints while retaining the base body's gait."""
|
|
95
|
+
def __init__(self, appearance, *, body=None, arms=None, head=None, face=None, gaze=None):
|
|
96
|
+
self.appearance=appearance
|
|
97
|
+
self.channels={name:Action(value) if isinstance(value,str) else value
|
|
98
|
+
for name,value in dict(body=body,arms=arms,head=head).items()}
|
|
99
|
+
if any(value is not None and not isinstance(value,Action) for value in self.channels.values()):
|
|
100
|
+
raise TypeError('Performance channels require Action or action name')
|
|
101
|
+
self.expression=Face(face) if isinstance(face,str) else face or Face()
|
|
102
|
+
self.gaze=gaze
|
|
103
|
+
|
|
104
|
+
def pose(self,t):
|
|
105
|
+
from ..rig import Pose, stand
|
|
106
|
+
body=self.channels['body']
|
|
107
|
+
j=dict((body.pose(t,self.appearance) if body else stand(self.appearance)).joints)
|
|
108
|
+
for channel,keys in (('arms',('elbow_left','elbow_right','hand_left','hand_right')),('head',('head',))):
|
|
109
|
+
clip=self.channels[channel]
|
|
110
|
+
if clip:
|
|
111
|
+
overlay=clip.pose(t,self.appearance).joints
|
|
112
|
+
# Align arm overrides to the body's moving shoulders.
|
|
113
|
+
for key in keys:
|
|
114
|
+
side=key.rsplit('_',1)[-1]
|
|
115
|
+
anchor='shoulder_'+side if channel=='arms' else 'hip'
|
|
116
|
+
delta=tuple(a-b for a,b in zip(j[anchor],overlay[anchor]))
|
|
117
|
+
j[key]=tuple(v+d for v,d in zip(overlay[key],delta))
|
|
118
|
+
return Pose(j)
|
|
119
|
+
|
|
120
|
+
def face(self,t):
|
|
121
|
+
result=self.expression(t) if callable(self.expression) else self.expression
|
|
122
|
+
for clip in self.channels.values():
|
|
123
|
+
if clip: result=clip.face(t,result)
|
|
124
|
+
if self.gaze is not None: result=replace(result,gaze=self.gaze(t) if callable(self.gaze) else self.gaze)
|
|
125
|
+
return result
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Build characters by composing the same validated Appearance used by the rig."""
|
|
2
|
+
from dataclasses import replace
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class CharacterBuilder:
|
|
6
|
+
def __init__(self, appearance=None, **appearance_fields):
|
|
7
|
+
from ..rig import Appearance
|
|
8
|
+
self.appearance=replace(appearance or Appearance(),**appearance_fields)
|
|
9
|
+
|
|
10
|
+
def with_appearance(self, **fields):
|
|
11
|
+
return CharacterBuilder(replace(self.appearance,**fields))
|
|
12
|
+
|
|
13
|
+
def build(self, **character_options):
|
|
14
|
+
from ..rig import Character
|
|
15
|
+
return Character(self.appearance,**character_options)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Facial parameters sampled without render history."""
|
|
2
|
+
from dataclasses import dataclass, replace
|
|
3
|
+
from math import isfinite
|
|
4
|
+
|
|
5
|
+
from .. import draw
|
|
6
|
+
from ..effects import curve
|
|
7
|
+
|
|
8
|
+
EXPRESSIONS = {
|
|
9
|
+
'neutral': (0, 0, 0), 'happy': (1, -.2, .15),
|
|
10
|
+
'sad': (-1, .7, 0), 'anxious': (-.5, .9, .3),
|
|
11
|
+
'angry': (-.6, -1, .2), 'surprised': (0, .8, 1),
|
|
12
|
+
'laugh': (1, -.4, .8), 'cry': (-1, .8, .5),
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Face:
|
|
18
|
+
expression: str = 'neutral'
|
|
19
|
+
intensity: float = 1
|
|
20
|
+
gaze: tuple = (0, 0)
|
|
21
|
+
blink: bool = False
|
|
22
|
+
tears: float = 0
|
|
23
|
+
# Continuous smile, brow and mouth-opening controls for transitions.
|
|
24
|
+
controls: tuple | None = None
|
|
25
|
+
|
|
26
|
+
def __post_init__(self):
|
|
27
|
+
if self.expression not in EXPRESSIONS:
|
|
28
|
+
raise ValueError(f'Unknown expression: {self.expression}')
|
|
29
|
+
values = (self.intensity, self.tears, *self.gaze)
|
|
30
|
+
if len(self.gaze) != 2 or not all(isfinite(v) for v in values):
|
|
31
|
+
raise ValueError('Face parameters must be finite')
|
|
32
|
+
if not 0 <= self.intensity <= 1 or not 0 <= self.tears <= 1 or any(abs(v)>1 for v in self.gaze):
|
|
33
|
+
raise ValueError('Intensity/tears in [0,1]; gaze in [-1,1]')
|
|
34
|
+
if self.controls is not None and (len(self.controls)!=3 or not all(isfinite(v) for v in self.controls)):
|
|
35
|
+
raise ValueError('Face controls need three finite values')
|
|
36
|
+
|
|
37
|
+
def values(self):
|
|
38
|
+
return self.controls if self.controls is not None else tuple(v*self.intensity for v in EXPRESSIONS[self.expression])
|
|
39
|
+
|
|
40
|
+
def blend(self, other, amount):
|
|
41
|
+
p=max(0,min(1,amount))
|
|
42
|
+
if p==0: return self
|
|
43
|
+
if p==1: return other
|
|
44
|
+
lerp=lambda a,b:a+(b-a)*p
|
|
45
|
+
return replace(other, controls=tuple(lerp(a,b) for a,b in zip(self.values(),other.values())),
|
|
46
|
+
gaze=tuple(lerp(a,b) for a,b in zip(self.gaze,other.gaze)),
|
|
47
|
+
tears=lerp(self.tears,other.tears), blink=self.blink if p<.5 else other.blink)
|
|
48
|
+
|
|
49
|
+
def draw(self, image, transform, center, head=1, view='profile'):
|
|
50
|
+
if view=='back':
|
|
51
|
+
return
|
|
52
|
+
hx,hy=center
|
|
53
|
+
d=draw.draw(image)
|
|
54
|
+
point=lambda x,y:transform.point((hx+x*head,hy+y*head))
|
|
55
|
+
line=lambda pts,c,w=1.4:draw.line(d,[point(x,y) for x,y in pts],c,w*head*transform.scale,True)
|
|
56
|
+
smile,brow,opening=self.values()
|
|
57
|
+
eyes=(-7,8) if view=='front' else (9,)
|
|
58
|
+
for x in eyes:
|
|
59
|
+
if self.blink:
|
|
60
|
+
line([(x-2,1),(x+2,1)],'#273447')
|
|
61
|
+
else:
|
|
62
|
+
ex,ey=x+2*self.gaze[0],1+2*self.gaze[1]
|
|
63
|
+
line([(ex,ey-.8),(ex,ey+.8)],'#273447',2.4)
|
|
64
|
+
line([(x-3,-5-brow*2),(x+3,-5+brow*2)],'#493B39')
|
|
65
|
+
if self.tears:
|
|
66
|
+
line([(x,5),(x,5+16*self.tears)],'#79CFF5',2)
|
|
67
|
+
mx=0 if view=='front' else 10
|
|
68
|
+
if opening>.15:
|
|
69
|
+
# Polygon follows the same transform as the rig, including flip.
|
|
70
|
+
draw.polygon(d,[point(mx-3,9),point(mx+3,9),point(mx+2,10+7*opening),point(mx-2,10+7*opening)],'#773C45')
|
|
71
|
+
else:
|
|
72
|
+
line([(mx-4,10),(mx,10+3*smile),(mx+4,10)],'#9E5D53')
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def expression_transition(before='neutral', after='happy', duration=.5, *, start=0, ease='smooth'):
|
|
76
|
+
if not isfinite(duration) or duration<=0 or not isfinite(start):
|
|
77
|
+
raise ValueError('Expression transition requires finite start and positive duration')
|
|
78
|
+
a=Face(before) if isinstance(before,str) else before
|
|
79
|
+
b=Face(after) if isinstance(after,str) else after
|
|
80
|
+
curve(0,ease)
|
|
81
|
+
return lambda t:a.blend(b,curve((t-start)/duration,ease))
|