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.
Files changed (45) hide show
  1. motionkit2d/__init__.py +49 -0
  2. motionkit2d/__main__.py +115 -0
  3. motionkit2d/acceleration.py +121 -0
  4. motionkit2d/assets.py +319 -0
  5. motionkit2d/audio.py +87 -0
  6. motionkit2d/audio_analysis.py +55 -0
  7. motionkit2d/camera.py +56 -0
  8. motionkit2d/catalog.py +79 -0
  9. motionkit2d/characters/__init__.py +4 -0
  10. motionkit2d/characters/actions.py +125 -0
  11. motionkit2d/characters/builder.py +15 -0
  12. motionkit2d/characters/expressions.py +81 -0
  13. motionkit2d/compiler.py +162 -0
  14. motionkit2d/composition.py +50 -0
  15. motionkit2d/constraints.py +91 -0
  16. motionkit2d/cues.py +15 -0
  17. motionkit2d/draw.py +416 -0
  18. motionkit2d/dynamics.py +109 -0
  19. motionkit2d/effects.py +131 -0
  20. motionkit2d/environments.py +86 -0
  21. motionkit2d/export.py +235 -0
  22. motionkit2d/fonts/LICENSE.txt +130 -0
  23. motionkit2d/fonts/LiberationSans-Regular.ttf +0 -0
  24. motionkit2d/fonts/LiberationSerif-Bold.ttf +0 -0
  25. motionkit2d/fonts/LiberationSerif-Regular.ttf +0 -0
  26. motionkit2d/gpu.py +512 -0
  27. motionkit2d/layout.py +89 -0
  28. motionkit2d/manifest.py +96 -0
  29. motionkit2d/mixer.py +92 -0
  30. motionkit2d/preset_library.py +41 -0
  31. motionkit2d/presets.py +33 -0
  32. motionkit2d/props.py +126 -0
  33. motionkit2d/qc.py +78 -0
  34. motionkit2d/quality.py +122 -0
  35. motionkit2d/rig.py +325 -0
  36. motionkit2d/scene_graph.py +154 -0
  37. motionkit2d/timeline.py +174 -0
  38. motionkit2d/transitions.py +51 -0
  39. motionkit2d/typography.py +118 -0
  40. motionkit2d/visual_effects.py +104 -0
  41. motionkit2d-1.0.0.dist-info/METADATA +140 -0
  42. motionkit2d-1.0.0.dist-info/RECORD +45 -0
  43. motionkit2d-1.0.0.dist-info/WHEEL +5 -0
  44. motionkit2d-1.0.0.dist-info/entry_points.txt +2 -0
  45. motionkit2d-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,49 @@
1
+ """Tools for writing, animating, rendering and validating 2D scenes in Python."""
2
+ from . import assets, draw, effects, presets
3
+ from .effects import Key, Track, tween
4
+ from .export import render, save_frame, storyboard, verify, frame_strip
5
+ from .timeline import Frame, Scene, Transition, Video, layers
6
+ from .rig import Transform, Appearance, Pose, Character, Prop, Attachment, stand, walk, reach, sit, pose_transition
7
+ from .catalog import Asset, Registry, catalog
8
+ from .cues import Cues
9
+ from .audio import AudioCue
10
+ from .layout import Layout, Rect, TextBlock, text_block
11
+ from .gpu import GPUCanvas, GPUUnavailable, gpu_info
12
+ from .characters import Face, expression_transition, CharacterBuilder, Action, Performance, action_names
13
+ from .scene_graph import Node, SceneGraph
14
+ from .camera import Camera2D
15
+ from .environments import Environment, Bedroom, Cafe, Study, Park, LivingRoom, Street
16
+ from .composition import SafeZone, fit, arrange, composition, overlaps
17
+ from .visual_effects import EffectRegistry, effects_registry, chain
18
+ from .transitions import register_transition, transition_names
19
+ from .typography import AnimatedText, Subtitle, subtitle_timing, reading_time
20
+ from .audio_analysis import BeatMap, analyze_audio, analyze_samples
21
+ from .compiler import ManifestError, compile_episode, load_manifest
22
+ from .preset_library import PresetLibrary
23
+ from .constraints import MotionPath, find_path, align, contain, collisions
24
+ from .dynamics import Ballistic, Emitter, spring, morph_polygon
25
+ from .mixer import mix_audio, loudness, normalize_audio, BeatTrack, SpeechSynthesizer
26
+ from .manifest import resolve_manifest, save_manifest, preflight
27
+ from .qc import quality_report, decoded_frames
28
+
29
+ __version__ = '1.0.0'
30
+
31
+ __all__ = [
32
+ 'Frame','Key','Scene','Track','Transition','Video','assets','draw','effects',
33
+ 'layers','presets','render','save_frame','storyboard','tween','verify',
34
+ 'Transform','Appearance','Pose','Character','Prop','Attachment','stand','walk',
35
+ 'reach','sit','pose_transition','Asset','Registry','catalog','Cues','AudioCue',
36
+ 'Layout','Rect','TextBlock','text_block','frame_strip',
37
+ 'GPUCanvas','GPUUnavailable','gpu_info',
38
+ 'Face','expression_transition','CharacterBuilder','Action','Performance','action_names',
39
+ 'Node','SceneGraph','Camera2D','Environment','Bedroom','Cafe','Study','Park','LivingRoom','Street',
40
+ 'SafeZone','fit','arrange','composition','overlaps','EffectRegistry','effects_registry','chain',
41
+ 'register_transition','transition_names','AnimatedText','Subtitle','subtitle_timing','reading_time',
42
+ 'BeatMap','analyze_audio','analyze_samples','ManifestError','compile_episode','load_manifest',
43
+ 'PresetLibrary',
44
+ 'MotionPath','find_path','align','contain','collisions',
45
+ 'Ballistic','Emitter','spring','morph_polygon',
46
+ 'mix_audio','loudness','normalize_audio','BeatTrack','SpeechSynthesizer',
47
+ 'resolve_manifest','save_manifest','preflight',
48
+ 'quality_report','decoded_frames',
49
+ ]
@@ -0,0 +1,115 @@
1
+ """Command line interface for MotionKit 2D."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ import runpy
6
+ import sys
7
+
8
+ from . import Video, render, save_frame, storyboard, verify, frame_strip, catalog, gpu_info
9
+
10
+
11
+ def main():
12
+ parser=argparse.ArgumentParser(description=__doc__)
13
+ parser.add_argument('project',type=Path,nargs='?',help='Python VIDEO project or schema_version=1 JSON manifest')
14
+ parser.add_argument('--catalog',action='store_true',help='List bundled assets as JSON')
15
+ parser.add_argument('--output',type=Path)
16
+ parser.add_argument('--audio',type=Path,help='Optional soundtrack source')
17
+ parser.add_argument('--expect-audio',action='store_true',help='Require an audio stream when verifying')
18
+ parser.add_argument('--crf',type=int,default=18)
19
+ parser.add_argument('--backend',choices=('auto','cpu','gpu'),default='auto')
20
+ parser.add_argument('--encoder',choices=('auto','cpu','nvenc','qsv','amf'),default='auto')
21
+ parser.add_argument('--speed',choices=('fast','balanced','quality'),default='balanced')
22
+ parser.add_argument('--workers',default='auto',help='Legacy CPU frame workers: auto or a positive integer')
23
+ parser.add_argument('--devices',action='store_true',help='Probe GPU rendering and real hardware encoding')
24
+ mode=parser.add_mutually_exclusive_group()
25
+ mode.add_argument('--frame',type=int)
26
+ mode.add_argument('--storyboard',action='store_true')
27
+ mode.add_argument('--verify',action='store_true')
28
+ mode.add_argument('--validate',action='store_true',help='Preflight graph properties at every frame and check audio sources')
29
+ mode.add_argument('--quality',action='store_true',help='QC rendered source frames; exit 1 FAIL, 2 INCOMPLETE')
30
+ parser.add_argument('--qc-video',type=Path,help='Decode this MP4 for --quality instead of rendering source frames')
31
+ mode.add_argument('--strip',help='Consecutive frame interval START:STOP (exclusive)')
32
+ args=parser.parse_args()
33
+ if args.devices:
34
+ from .export import _binary
35
+ from .acceleration import probe_encoder, ENCODERS
36
+ ffmpeg=_binary('ffmpeg')
37
+ print(json.dumps({'gpu':gpu_info(),'encoders':[
38
+ probe_encoder(ffmpeg,c,1024,576,30,args.speed) for c in ENCODERS.values()]},indent=2))
39
+ return
40
+ if args.catalog:
41
+ print(json.dumps(catalog.describe(),ensure_ascii=False,indent=2))
42
+ return
43
+ if args.project is None:
44
+ parser.error('project is required unless --catalog is used')
45
+
46
+ if args.expect_audio and not args.verify:
47
+ parser.error('--expect-audio is only used with --verify')
48
+ if args.qc_video and not args.quality: parser.error('--qc-video requires --quality')
49
+ if args.audio and any((args.frame is not None,args.storyboard,args.verify,args.strip)):
50
+ parser.error('--audio is only used when rendering MP4')
51
+ project_path=args.project.resolve()
52
+ if project_path.suffix.lower()=='.json':
53
+ from .compiler import load_manifest, ManifestError
54
+ try: video=load_manifest(project_path)
55
+ except ManifestError as error: parser.error(str(error))
56
+ else:
57
+ sys.path.insert(0,str(project_path.parent))
58
+ try:
59
+ project=runpy.run_path(str(project_path))
60
+ finally:
61
+ sys.path.pop(0)
62
+ video=project.get('VIDEO')
63
+ if not isinstance(video,Video):
64
+ parser.error('The project must expose VIDEO = Video(...)')
65
+ base=Path('output')/args.project.stem
66
+ if args.quality:
67
+ from .qc import quality_report
68
+ result=quality_report(video,decoded_path=args.qc_video)
69
+ if args.output:
70
+ from .manifest import save_manifest
71
+ save_manifest(result,args.output)
72
+ print(json.dumps(result,indent=2,ensure_ascii=False))
73
+ raise SystemExit({'PASS':0,'FAIL':1,'INCOMPLETE':2}[result['status']])
74
+ if args.validate:
75
+ from .manifest import preflight
76
+ try: result=preflight(video)
77
+ except (ValueError,TypeError,KeyError,OSError) as error: parser.error(str(error))
78
+ print(json.dumps(result,indent=2))
79
+ return
80
+ if args.frame is not None:
81
+ result=save_frame(video,args.frame,args.output or base.with_name(f'{base.name}_{args.frame:04d}.png'))
82
+ elif args.storyboard:
83
+ result=storyboard(video,args.output or base.with_name(f'{base.name}_storyboard.png'))
84
+ elif args.verify:
85
+ result=verify(video,args.output or base.with_suffix('.mp4'),audio=args.expect_audio or bool(video.audio))
86
+ print(json.dumps(result,indent=2))
87
+ return
88
+ elif args.strip:
89
+ try:
90
+ start,stop=map(int,args.strip.split(':'))
91
+ if not 0<=start<stop<=video.frame_count:
92
+ raise ValueError
93
+ except ValueError:
94
+ parser.error('--strip requires 0 <= START < STOP <= frame_count')
95
+ result=frame_strip(video,range(start,stop),args.output or base.with_name(f'{base.name}_strip.png'))
96
+ else:
97
+ try:
98
+ workers='auto' if args.workers=='auto' else int(args.workers)
99
+ if workers!='auto' and workers<1: raise ValueError
100
+ except ValueError:
101
+ parser.error('--workers requires auto or a positive integer')
102
+ def progress(index,total):
103
+ if index%90==0 or index==total:
104
+ print(f'{index}/{total} frames',flush=True)
105
+ report={}
106
+ result=render(video,args.output or base.with_suffix('.mp4'),
107
+ audio=args.audio,crf=args.crf,progress=progress,
108
+ backend=args.backend,encoder=args.encoder,speed=args.speed,
109
+ workers=workers,project_path=project_path,report=report)
110
+ print(json.dumps(report,indent=2))
111
+ print(result)
112
+
113
+
114
+ if __name__=='__main__':
115
+ main()
@@ -0,0 +1,121 @@
1
+ """Encoder capability checks and bounded, Windows-safe legacy frame workers."""
2
+ from collections import deque
3
+ from concurrent.futures import ProcessPoolExecutor
4
+ from functools import lru_cache
5
+ import multiprocessing
6
+ import os
7
+ from pathlib import Path
8
+ import runpy
9
+ import subprocess
10
+ import sys
11
+
12
+
13
+ ENCODERS={'cpu':'libx264','nvenc':'h264_nvenc','qsv':'h264_qsv','amf':'h264_amf'}
14
+
15
+
16
+ def encoder_options(codec,quality=18,speed='balanced'):
17
+ if speed not in ('fast','balanced','quality'):
18
+ raise ValueError('speed must be fast, balanced or quality')
19
+ level=('fast','balanced','quality').index(speed)
20
+ if codec=='libx264':
21
+ return ['-c:v',codec,'-preset',('veryfast','medium','slow')[level],'-crf',str(quality)]
22
+ if codec=='h264_nvenc':
23
+ return ['-c:v',codec,'-preset',('p1','p4','p7')[level],'-rc','vbr','-cq',str(max(1,quality)),'-b:v','0']
24
+ if codec=='h264_qsv':
25
+ return ['-c:v',codec,'-preset',('veryfast','medium','veryslow')[level],'-global_quality',str(quality)]
26
+ if codec=='h264_amf':
27
+ return ['-c:v',codec,'-quality',('speed','balanced','quality')[level],'-rc','cqp',
28
+ '-qp_i',str(quality),'-qp_p',str(quality)]
29
+ raise ValueError(f'Unsupported encoder: {codec}')
30
+
31
+
32
+ @lru_cache(maxsize=48)
33
+ def probe_encoder(ffmpeg,codec,width,height,fps,speed='balanced'):
34
+ """Actually initialize/encode, rather than trusting ffmpeg -encoders."""
35
+ if codec=='libx264': return {'available':True,'codec':codec}
36
+ cmd=[ffmpeg,'-v','error','-f','lavfi','-i',f'color=c=black:s={width}x{height}:r={fps}',
37
+ '-frames:v','1',*encoder_options(codec,18,speed),'-pix_fmt','yuv420p','-f','null','-']
38
+ try:
39
+ result=subprocess.run(cmd,capture_output=True,timeout=12)
40
+ reason=result.stderr.decode(errors='replace').strip()
41
+ return {'available':result.returncode==0,'codec':codec,**({'reason':reason} if reason else {})}
42
+ except (OSError,subprocess.TimeoutExpired) as error:
43
+ return {'available':False,'codec':codec,'reason':str(error)}
44
+
45
+
46
+ def select_encoder(ffmpeg,requested,width,height,fps,speed):
47
+ if requested not in ('auto',*ENCODERS):
48
+ raise ValueError('encoder must be auto, cpu, nvenc, qsv or amf')
49
+ attempts=[]
50
+ choices=('nvenc','qsv','amf','cpu') if requested=='auto' else (requested,)
51
+ for choice in choices:
52
+ result=probe_encoder(ffmpeg,ENCODERS[choice],width,height,fps,speed)
53
+ attempts.append(result)
54
+ if result['available']: return ENCODERS[choice],attempts
55
+ raise RuntimeError(f'Encoder {requested} is unavailable: {attempts[-1].get("reason", "unknown error")}')
56
+
57
+
58
+ _WORKER_VIDEO=None
59
+ _WORKER_RAW=False
60
+
61
+
62
+ def _signature(video):
63
+ return (video.width,video.height,video.fps,video.frame_count,video.starts,video.lengths,
64
+ tuple(scene.name for scene in video.scenes))
65
+
66
+
67
+ def _initialize_worker(project_path,expected,raw):
68
+ global _WORKER_VIDEO,_WORKER_RAW
69
+ project=Path(project_path)
70
+ sys.path.insert(0,str(project.parent))
71
+ if project.suffix.lower()=='.json':
72
+ from .compiler import load_manifest
73
+ _WORKER_VIDEO=load_manifest(project)
74
+ else:
75
+ namespace=runpy.run_path(str(project),run_name='__motionkit_worker_project__')
76
+ _WORKER_VIDEO=namespace.get('VIDEO')
77
+ if _WORKER_VIDEO is None or _signature(_WORKER_VIDEO)!=expected:
78
+ raise ValueError('Worker project VIDEO differs from the video passed to render()')
79
+ _WORKER_RAW=raw
80
+
81
+
82
+ def _render_worker(index):
83
+ image=_WORKER_VIDEO._frame_image(index) if _WORKER_RAW else _WORKER_VIDEO.frame(index)
84
+ return image.tobytes()
85
+
86
+
87
+ def worker_count(requested,video,project_path,*,backend='auto'):
88
+ native=backend!='cpu' and any(scene.gpu_paint is not None for scene in video.scenes)
89
+ if requested=='auto':
90
+ if not project_path or native: return 1
91
+ # Leave memory for project caches, encoder and GPU staging, not only RGB bytes.
92
+ frame_bytes=video.width*video.height*4*4
93
+ budget=max(1,(256*1024*1024)//max(1,frame_bytes*2))
94
+ return max(1,min(4,os.cpu_count() or 1,budget,video.frame_count))
95
+ if type(requested) is not int or requested<1:
96
+ raise ValueError('workers must be a positive integer or auto')
97
+ if requested>1 and not project_path:
98
+ raise ValueError('workers > 1 requires project_path so Windows workers can reload VIDEO')
99
+ if requested>1 and native:
100
+ raise ValueError('Native GPU scenes use one GL context; use workers=1 or auto')
101
+ return min(requested,video.frame_count)
102
+
103
+
104
+ def parallel_frames(video,project_path,workers,*,raw=False):
105
+ """Ordered streaming; never queue an entire video in RAM."""
106
+ context=multiprocessing.get_context('spawn')
107
+ with ProcessPoolExecutor(max_workers=workers,mp_context=context,
108
+ initializer=_initialize_worker,initargs=(str(Path(project_path).resolve()),_signature(video),raw)) as pool:
109
+ pending=deque()
110
+ next_index=0
111
+ # One result per worker, plus at most one replacement per yielded result.
112
+ for _ in range(min(workers,video.frame_count)):
113
+ pending.append(pool.submit(_render_worker,next_index)); next_index+=1
114
+ try:
115
+ while pending:
116
+ result=pending.popleft().result()
117
+ if next_index<video.frame_count:
118
+ pending.append(pool.submit(_render_worker,next_index)); next_index+=1
119
+ yield result
120
+ finally:
121
+ for future in pending: future.cancel()
motionkit2d/assets.py ADDED
@@ -0,0 +1,319 @@
1
+ """Silhouettes, interface props and depth-sorted snake geometry."""
2
+ import math as m
3
+ from dataclasses import dataclass
4
+ from functools import lru_cache
5
+
6
+ import numpy as np
7
+ from PIL import Image
8
+
9
+ from .draw import (S, BRASS, GRAY, WHITE, clamp, cubic, draw, font, halo, heart, lerp,
10
+ line, mix, oval, paste, polygon, ramp, rect, text)
11
+
12
+ SNAKE, SCALE_LIGHT, SCALE_DARK = '#45BF68', '#A0EE94', '#248D44'
13
+
14
+ def snake_geometry(sample,count=221):
15
+ if count<2:
16
+ raise ValueError('a snake path requires at least two samples')
17
+ path=[]
18
+ for i in range(count):
19
+ u=i/(count-1)
20
+ x,y,z=sample(u)
21
+ a,b,_=sample(max(0,u-.002))
22
+ c,d,_=sample(min(1,u+.002))
23
+ tangent=m.atan2(d-b,c-a)
24
+ path.append((x,y,z,tangent,u))
25
+ return path
26
+
27
+ def snake(im,path,*,width=9,progress=1,depth=None,t=0,darkness=0):
28
+ if progress<=0:
29
+ return
30
+ d=draw(im)
31
+ pigment=mix(SNAKE,'#338E51',.46 if depth is False else 0)
32
+ body=mix(pigment,'#101D14',darkness)
33
+ edge=mix('#173D2B','#09110C',darkness)
34
+ points=[p for p in path if p[4]<=progress+.00001]
35
+ if len(points)<2:
36
+ return
37
+ def visible(point):
38
+ return depth is None or (point[2]>=0)==depth
39
+ def radius(p):
40
+ return width*(.025+.975*p[4]**.69)
41
+ def strip(section):
42
+ for extra,col in [(1.25,edge),(0,body)]:
43
+ left,right=[],[]
44
+ for p in section:
45
+ x,y,_,angle,_=p
46
+ r=radius(p)+extra
47
+ nx,ny=-m.sin(angle)*r,m.cos(angle)*r
48
+ left.append((x+nx,y+ny))
49
+ right.append((x-nx,y-ny))
50
+ polygon(d,left+right[::-1],col)
51
+ for i,p in enumerate(section):
52
+ if round(p[4]*(len(path)-1))%4!=1:
53
+ continue
54
+ x,y,_,angle,u=p
55
+ r=radius(p)
56
+ for j,side in enumerate([-.58,-.065,.52]):
57
+ k=round(u*len(path))*3+j
58
+ wobble=.38*m.sin(k*31.17)
59
+ tilt=side+wobble*.23
60
+ xx=x-m.sin(angle)*r*tilt+m.cos(angle)*wobble*3
61
+ yy=y+m.cos(angle)*r*tilt+m.sin(angle)*wobble*3
62
+ spot=max(.45,min(1.7,r*(.134+.06*m.cos(k*15.71))))
63
+ oval(d,xx,yy,spot,spot,mix(SCALE_LIGHT if (k+j)%4<2 else SCALE_DARK,'#132318',darkness))
64
+ start=None
65
+ for i,p in enumerate(points):
66
+ if visible(p):
67
+ if start is None:
68
+ start=max(0,i-1)
69
+ elif start is not None:
70
+ strip(points[start:i+1])
71
+ start=None
72
+ if start is not None:
73
+ strip(points[start:])
74
+ head=points[-1]
75
+ if not visible(head) or progress<.06:
76
+ return
77
+ x,y,_,angle,u=head
78
+ r=radius(head)
79
+ def at(a,b):
80
+ co,si=m.cos(angle),m.sin(angle)
81
+ return x+co*a-si*b,y+si*a+co*b
82
+ if (t*1.23+.29)%1>.49:
83
+ tip=1.3*r+10
84
+ for side in [-1,1]:
85
+ line(d,[at(r,0),at(tip-4,0),at(tip,side*3.4)],mix('#E34B5C','#34181E',darkness),1.5,True)
86
+ crown=[at(1.43*r*m.cos(a),1.17*r*m.sin(a)) for a in np.linspace(0,2*m.pi,45)]
87
+ polygon(d,crown,edge)
88
+ polygon(d,[at(1.30*r*m.cos(a),1.04*r*m.sin(a)) for a in np.linspace(0,2*m.pi,45)],body)
89
+ for side in [-1,1]:
90
+ xx,yy=at(r*.49,side*r*.62)
91
+ eye=max(1,r*.24)
92
+ oval(d,xx,yy,eye,eye,mix('#F4CB5A','#514B29',darkness))
93
+ oval(d,xx,yy,eye*.41,eye*.61,'#111915')
94
+ for a,b in [(-.55,-.25),(-.47,.22),(.08,0)]:
95
+ xx,yy=at(a*r,b*r)
96
+ oval(d,xx,yy,max(.55,r*.13),max(.55,r*.13),mix('#7ADD80','#16291D',darkness))
97
+
98
+ def crawl(head,y,length,t,waves=3.7):
99
+ return snake_geometry(lambda u:(head+(1-u)*length,y+(3+8*m.sin(m.pi*u)**.65 if 0<=u<=1 else 3)*
100
+ m.sin((1-u)*waves*2*m.pi-t*8),1))
101
+
102
+ def coil(cx,bottom,top,rx,ry,turns,t,*,end_forward=True):
103
+ finish=m.pi/2+.06 if end_forward else m.pi-.25
104
+ start=finish-2*m.pi*turns
105
+ def sample(u):
106
+ theta=start+u*2*m.pi*turns
107
+ # Flatten the final neck so its head points left in screen space.
108
+ neck=ramp(u,.945,1)
109
+ r=rx*(.89+.11*m.sin(m.pi*clamp(u))+.017*m.cos(t*3.1+u*9))
110
+ x=cx+r*m.cos(theta)-neck*rx*.07
111
+ y=lerp(bottom,top,u)+ry*m.sin(theta)*(1-.66*neck)
112
+ return x,y,m.sin(theta)
113
+ return snake_geometry(sample)
114
+
115
+ def coil_at(im,path,prop,*,width=9,progress=1,darkness=0,t=0):
116
+ snake(im,path,width=width,progress=progress,depth=False,t=t,darkness=darkness)
117
+ prop()
118
+ snake(im,path,width=width,progress=progress,depth=True,t=t,darkness=darkness)
119
+
120
+ def orbit(cx,cy,rx,ry,start,span):
121
+ return snake_geometry(lambda u:(cx+rx*m.cos(start+span*u),cy+ry*m.sin(start+span*u),1))
122
+
123
+ @lru_cache(maxsize=1)
124
+ def phone_shell():
125
+ layer=Image.new('RGBA',(296*S,534*S))
126
+ d=draw(layer)
127
+ rect(d,13,12,270,510,25,'#111B1A','#566661',1.5)
128
+ rect(d,20,19,256,496,19,'#101D1A','#263931',1)
129
+ line(d,[(112,504),(184,504)],'#52635C',2.4,True)
130
+ return layer
131
+
132
+ def phone_base():
133
+ return phone_shell().copy()
134
+
135
+ def phone_text(im,x,y,label,size=14,**kw):
136
+ text(im,x,y,label,size,style='sans',align='left',**kw)
137
+
138
+ @dataclass(frozen=True)
139
+ class Message:
140
+ text: str
141
+ at: float = 0
142
+ sent: bool = False
143
+
144
+ def _wrap(value, face, width):
145
+ lines = []
146
+ for paragraph in value.split('\n'):
147
+ current=''
148
+ for char in paragraph:
149
+ if current and face.getlength(current+char)>width*S:
150
+ split=current.rfind(' ')
151
+ if split>0:
152
+ lines.append(current[:split])
153
+ current=current[split+1:]
154
+ else:
155
+ lines.append(current)
156
+ current=''
157
+ current+=char
158
+ lines.append(current.strip())
159
+ return lines
160
+
161
+ def _shorten(value,face,width):
162
+ if face.getlength(value)<=width*S:
163
+ return value
164
+ while face.getlength(value+'…')>width*S:
165
+ value=value[:-1]
166
+ return value.rstrip()+'…'
167
+
168
+ def phone_chat(t,messages,*,name='Tin nhắn',avatar='#D8AE54'):
169
+ """Build a chat phone. New messages appear at their local time in seconds."""
170
+ layer=phone_base()
171
+ d=draw(layer)
172
+ line(d,[(43,66),(36,73),(43,80)],'#C5D1CA',1.6,True)
173
+ oval(d,65,73,13,13,avatar)
174
+ phone_text(layer,86,71,_shorten(name,font(16,'sans'),174),16)
175
+ line(d,[(25,100),(271,100)],'#253830',1)
176
+ face=font(13,'sans')
177
+ bubbles=[]
178
+ for message in messages:
179
+ if t<message.at:
180
+ continue
181
+ lines=_wrap(message.text,face,200)
182
+ if len(lines)>20:
183
+ lines=lines[:19]+['…']
184
+ width=max(face.getlength(row)/S for row in lines)+20
185
+ height=max(31,len(lines)*17+12)
186
+ bubbles.append((message,lines,width,height))
187
+ used=0
188
+ visible=[]
189
+ for bubble in reversed(bubbles):
190
+ if used+bubble[3]>371:
191
+ break
192
+ visible.append(bubble)
193
+ used+=bubble[3]+9
194
+ y=115
195
+ for message,lines,width,height in reversed(visible):
196
+ strength=ramp(t,message.at,message.at+.22)
197
+ chip='#315A80' if message.sent else '#273733'
198
+ x=260-width if message.sent else 36
199
+ rect(d,x,y,width,height,11,mix('#101D1A',chip,strength))
200
+ for i,row in enumerate(lines):
201
+ phone_text(layer,x+10,y+13+17*i,row,13,c=mix('#101D1A',WHITE,strength))
202
+ y+=height+9
203
+ return layer
204
+
205
+ @lru_cache(maxsize=1)
206
+ def sunset():
207
+ w,h=232,236
208
+ layer=Image.new('RGB',(w*S,h*S))
209
+ d=draw(layer)
210
+ for y in range(h*S):
211
+ q=y/(h*S-1)
212
+ c=mix('#F6C97C','#BB683E',q/.58) if q<.58 else mix('#BB683E','#472C2C',(q-.58)/.42)
213
+ d.line([(0,y),(w*S,y)],fill=c)
214
+ halo(layer,150,72,112,95,'#FFD58A',.6)
215
+ oval(d,147,73,31,30,'#F4BB73')
216
+ ridge=[(x,153+9*m.sin(x/34)+9*m.cos(x/66)) for x in range(0,w+1,2)]
217
+ polygon(d,ridge+[(w,h),(0,h)],'#704238')
218
+ front=[(x,183+10*m.cos(x/41)+6*m.sin(x/17)) for x in range(0,w+1,2)]
219
+ polygon(d,front+[(w,h),(0,h)],'#503437')
220
+ c='#272126'
221
+ oval(d,108,123,14,17,c)
222
+ hair=cubic((95,120),(90,137),(91,155),(78,181),36)+cubic((78,181),(100,190),(122,169),(121,131),36)
223
+ polygon(d,hair,c)
224
+ polygon(d,[(101,134),(113,133),(114,158),(123,183),(133,236),(84,236),(94,186),(96,152)],c)
225
+ line(d,[(112,152),(138,139),(159,112),(169,102)],c,8,True)
226
+ line(d,[(99,154),(86,180),(82,205)],c,7,True)
227
+ mask=Image.new('L',layer.size)
228
+ rect(draw(mask),0,0,w-.5,h-.5,9,255)
229
+ layer.putalpha(mask)
230
+ return layer
231
+
232
+ def phone_feed(*,time='04:51',header='Bảng tin',author='Bạn bè',caption='',reaction='',picture=None):
233
+ """Build a phone feed with caller-supplied text and an optional PIL image."""
234
+ layer=phone_base()
235
+ d=draw(layer)
236
+ phone_text(layer,36,49,_shorten(time,font(27,'sans'),218),27)
237
+ phone_text(layer,36,80,_shorten(header,font(13,'sans'),218),13,c=GRAY)
238
+ line(d,[(26,105),(269,105)],'#2A3934',1)
239
+ oval(d,51,132,12,12,'#DFB855')
240
+ phone_text(layer,72,131,_shorten(author,font(16,'sans'),186),16)
241
+ for i,row in enumerate(_wrap(caption,font(14,'sans'),222)[:2]):
242
+ phone_text(layer,36,158+i*17,row,14)
243
+ art=sunset() if picture is None else picture.convert('RGBA').resize((232*S,236*S),Image.Resampling.LANCZOS)
244
+ paste(layer,art,(32*S,190*S))
245
+ if reaction:
246
+ row=_shorten(reaction,font(13,'sans'),180)
247
+ width=font(13,'sans').getlength(row)/S+42
248
+ rect(d,34,444,width,32,15,'#272F2C','#415049',.7)
249
+ heart(layer,51,460,14)
250
+ phone_text(layer,65,460,row,13)
251
+ return layer
252
+
253
+ def place_phone(im,layer,x,y,tilt=0,amount=1,*,scale=1):
254
+ from .effects import sprite
255
+ sprite(im,layer,x,y,scale=scale,rotation=tilt,opacity=amount)
256
+
257
+ def full_lemon(im,x,y,s):
258
+ if s<.005:
259
+ return
260
+ d=draw(im)
261
+ def p(points):
262
+ return [(x+a*s,y+b*s) for a,b in points]
263
+ outline=cubic((-113,0),(-94,-9),(-71,-73),(9,-63),38)
264
+ outline+=cubic((9,-63),(69,-62),(84,-18),(109,-8),38)
265
+ outline+=cubic((109,-8),(119,4),(101,12),(94,16),20)
266
+ outline+=cubic((94,16),(57,75),(-34,78),(-79,41),35)
267
+ outline+=cubic((-79,41),(-100,17),(-123,11),(-113,0),25)
268
+ polygon(d,p(outline),'#E6AC32')
269
+ oval(d,x,y-2*s,98*s,61*s,'#EDBB3D')
270
+ oval(d,x-6*s,y-8*s,88*s,49*s,'#F8C94B')
271
+ highlight=cubic((-79,-14),(-63,-44),(-20,-57),(13,-49),30)
272
+ highlight+=cubic((13,-49),(-18,-43),(-48,-24),(-79,-14),30)
273
+ polygon(d,p(highlight),'#FFE591')
274
+
275
+ def lemon_slice(im,x,y,rx,ry,phase=0):
276
+ if rx<.8 or ry<.8:
277
+ return
278
+ d=draw(im)
279
+ oval(d,x,y,rx,ry,'#DFA632','#F5CC55',1)
280
+ oval(d,x,y,rx*.918,ry*.922,'#FFF2BB')
281
+ oval(d,x,y,rx*.80,ry*.814,'#F6CA60')
282
+ for i in range(8):
283
+ a=phase+i*m.tau/8
284
+ b=a+m.tau/8-.061
285
+ sector=[(x+rx*.075*m.cos((a+b)/2),y+ry*.075*m.sin((a+b)/2))]
286
+ sector.extend((x+rx*.79*m.cos(theta),y+ry*.808*m.sin(theta)) for theta in np.linspace(a+.024,b,22))
287
+ polygon(d,sector,['#FAD271','#F6C454','#F8CB60','#FFD77F'][i%4])
288
+ line(d,[(x,y),(x+rx*.815*m.cos(a),y+ry*.825*m.sin(a))],'#FFF1B9',1.55,True)
289
+ oval(d,x,y,rx*.065,ry*.066,'#FFF2BD')
290
+
291
+ def capsule(im,x,y,w,h,value,*,fill='#2D4A3B',stroke='#517664',c=WHITE,size=15):
292
+ rect(draw(im),x-w/2,y-h/2,w,h,h/2,fill,stroke,.7)
293
+ text(im,x,y-.6,value,size,style='sans',c=c)
294
+
295
+
296
+ def balance(im,x,floor,*,scale=1,tilt=13):
297
+ """Draw a two-pan balance. Return the left and right pan anchors."""
298
+ if scale<=0:
299
+ raise ValueError('balance scale must be positive')
300
+ d=draw(im)
301
+ pivot=floor-324*scale
302
+ theta=m.radians(tilt)
303
+ dx=260*scale*m.cos(theta)
304
+ dy=260*scale*m.sin(theta)
305
+ ends=[(x-dx,pivot-dy),(x+dx,pivot+dy)]
306
+ polygon(d,[(x-7*scale,pivot),(x+7*scale,pivot),
307
+ (x+10*scale,floor-18*scale),(x-10*scale,floor-18*scale)],'#A6A27F')
308
+ polygon(d,[(x-8*scale,floor-29*scale),(x+8*scale,floor-29*scale),
309
+ (x+58*scale,floor),(x-58*scale,floor)],'#A8A280')
310
+ line(d,ends,BRASS,6*scale,True)
311
+ oval(d,x,pivot,11*scale,11*scale,'#444839',BRASS,2*scale)
312
+ anchors=[]
313
+ for arm_x,arm_y in ends:
314
+ pan=arm_y+136*scale
315
+ line(d,[(arm_x-78*scale,pan),(arm_x,arm_y),(arm_x+78*scale,pan)],BRASS,scale)
316
+ oval(d,arm_x,pan,82*scale,9*scale,'#817D60','#D3CC9F',1.2*scale)
317
+ oval(d,arm_x,pan-2*scale,78*scale,4*scale,'#404738')
318
+ anchors.append((arm_x,pan-4*scale))
319
+ return tuple(anchors)