Solving#

Framing, placement, lettering and balloons. These modules are internal – they are documented because the decisions in them are the interesting part of the project, not because their signatures are promised to stay put.

scenet.solve.camera#

Camera framing: shot type into scale and vertical placement.

The central rule, and the one most easily got wrong: a shot type names where the frame cuts the body, not what fraction of the panel a figure fills. Encoding the fraction instead bakes in one body and one pose, so a child and an adult would come out the same height. See docs/reference/shot_types.md, which is normative.

The second rule: one camera, one scale. A camera has a single focal length, so every actor at the same distance is scaled identically and a taller character is taller in frame. Scaling each actor to fit its own crop would silently erase height differences, which is precisely what a comic uses to characterise people.

class scenet.solve.camera.ShotSpec[source]#

Bases: object

A crop landmark, and the empty space left above the head and below the feet.

__init__(crop, headroom, footroom=0.0)#
class scenet.solve.camera.CameraSolution[source]#

Bases: object

The camera’s verdict for a panel: one scale, shared by every actor.

property was_pulled_back: bool#

Whether the camera had to retreat from the requested framing.

Surfaced to the user through CompileResult.notes. Retreating silently would leave a panel that quietly is not the shot that was asked for.

pulled_back_to(scale)[source]#

Retreat the camera until the cast fits across the frame.

A shot type is a statement about vertical framing – where the frame cuts the body. When several actors cannot fit side by side at that scale, a real camera moves back: everyone gets smaller and more of the body comes into view. So the requested shot behaves as an upper bound on tightness rather than an exact contract, and the amount of retreat is recorded here so the result stays inspectable rather than mysterious.

Return type:

CameraSolution

property head_top_y: float#

Where the reference actor’s head-top lands.

root_y_framed(puppet)[source]#

Place this puppet by its own head, as if framed alone.

Used for actors that share no ground line with anyone: each is composed independently within the frame.

Return type:

float

root_y_on_ground(puppet, ground_y)[source]#

Place this puppet so its feet meet a given ground line.

This is what makes two characters of different heights stand together convincingly: feet align, heads do not.

Return type:

float

feet_below_root(puppet)[source]#

How far below the root joint this puppet’s feet sit, at this camera scale.

Parameters:

puppet (PuppetSpec) – The character being placed.

Return type:

float

Returns:

Distance in panel units.

ground_y_of(puppet, root_y)[source]#

The ground line a puppet stands on, given where its root joint is.

The inverse of root_y_on_ground, and how ground_shared_with gets its target: take one actor’s ground line, then place the other so their feet meet it.

Parameters:
  • puppet (PuppetSpec) – The character.

  • root_y (float) – Where its root joint sits vertically.

Return type:

float

Returns:

The y coordinate of its feet.

__init__(scale, headroom, footroom, panel_height, shot, reference, pullback=1.0)#
scenet.solve.camera.headroom_for(shot, angle)[source]#

Empty space to leave above the head, as a fraction of panel height.

A shot type has two halves and they use different units. The crop landmark is anatomical – the waist, the chest, the shoulders – which is what stops a shot type baking in one body and one pose. The headroom is a plain fraction of panel height, because it is about composition within the frame rather than about anatomy. See docs/reference/shot_types.md, which is normative.

Angle changes headroom rather than perspective. This compiler is orthographic, so a tilted camera cannot foreshorten anything – but the amount of air above the head is the compositional cue readers actually take from an angle, and it is one that survives being drawn flat.

A low camera looks up and the subject looms, so headroom tightens; a high camera looks down and it opens out.

Parameters:
Return type:

float

Returns:

Headroom as a fraction of panel height, never below MINIMUM_ANGLE_HEADROOM for a tilted camera – so that extreme_close_up, whose base headroom is zero, still shifts under an angle instead of staying flush against the top edge.

Example

>>> from scenet import CameraAngle, ShotType
>>> from scenet.solve.camera import headroom_for
>>> [
...     headroom_for(ShotType.MEDIUM_SHOT, angle)
...     for angle in (CameraAngle.LOW, CameraAngle.EYE_LEVEL, CameraAngle.HIGH)
... ]
[0.05, 0.1, 0.16000000000000003]
scenet.solve.camera.visible_height(puppet, shot)[source]#

Native height of the portion of the body the frame will show.

Return type:

float

scenet.solve.camera.solve_camera(reference, *, shot, angle, panel_height, footroom=None, named=None)[source]#

Resolve the camera against a reference actor.

Everything else in the panel inherits this scale. The reference is the actor the shot is composed on – by convention the first in the cast, which is the one the author wrote first and therefore the one the panel is about. named is how the cast names its puppet, which the solution records; left out, the puppet’s own name.

Return type:

CameraSolution

scenet.solve.staging#

Horizontal placement, vertical grounding and draw order.

This is where Cassowary earns its place. The arithmetic is trivial – centring a figure on a third is one division – but the conflicts are not. Two actors both asked to stand centre must be pushed apart; a crowded panel must let figures bleed off the edge rather than overlap. Expressed as priorities, that resolves itself. Written by hand it becomes an ever-growing cascade of special cases.

Priorities used:

required  actors never overlap, and keep their declared left-to-right order
strong    actors stay inside the panel
weak      actors sit on their requested anchor

Bounds are deliberately strong rather than required. Letting a figure bleed past the panel edge is ordinary comics practice, and far better than refusing to compile a crowded panel.

class scenet.solve.staging.Placement[source]#

Bases: object

Where one actor’s root joint ends up, and how it is drawn.

property origin: Point#

Where this actor’s root joint lands, as a point.

__init__(actor_id, reference, pose, expression, x, y, scale, facing_right, depth)#
scenet.solve.staging.horizontal_order(panel)[source]#

A total left-to-right order over the cast.

Declared left_of relations are honoured; everything else is broken by anchor position and then by actor id. The tiebreak matters more than it looks: the solver needs a total order to write non-overlap constraints against, and it must be the same total order on every run or the output stops being deterministic.

Return type:

tuple[str, ...]

scenet.solve.staging.depth_order(panel)[source]#

Painter’s order from in_front_of / behind relations.

Depth is the longest chain of actors behind a given one, so anything not mentioned stays at zero and the common case adds no noise to the output.

Return type:

dict[str, int]

scenet.solve.staging.solve_staging(panel, library, camera=None)[source]#

Resolve every actor’s position, scale, facing and draw order.

Return type:

tuple[tuple[Placement, ...], CameraSolution]

scenet.solve.backdrop#

Resolving a setting into tonal masses: geometry, value, and draw order.

The solver still never sees artwork. A backdrop reaches it as the same kind of geometric contract everything else does – polygons, a value, an integer depth – and the emitter is left with nothing to decide.

Why masses rather than drawn geometry

Crisp architecture needs a vanishing point, and this is deliberately a flat, orthographic compiler, so drawn buildings would fight the compiler’s own model. Soft tonal masses have no perspective to get wrong. That is the structural argument; the other is that this is simply how comics establish place.

Notan – the Japanese light/dark mass principle, which entered Western art teaching through Arthur Wesley Dow’s Composition (1899) – holds that place is read from the arrangement of masses rather than from rendered detail. Layered silhouette depth gives the arrangement: foreground near-black, each receding plane paler. And aerial perspective supplies the parametric rule for free – with distance, value contrast drops toward the atmosphere colour. Three numbers per plane, monotonic in depth. That is notation, not interpretation, which is what makes it belong in a compiler.

Shape grammars, as a formalism rather than a library

Silhouette profiles are generated with the split/repeat/subdivide operations of CGA shape grammar (Mueller et al., Procedural Modeling of Buildings, SIGGRAPH 2006). It is reused as a formalism: there is no open-source Python implementation of CGA, and the reference one is commercial, inside Esri CityEngine. See docs/explanation/prior_art.md.

The discipline that comes with it is worth stating: how many of a thing there are is derived from the geometry – a wider span gets more bays – and only how big each one is comes from the seed. Random counts make a backdrop flicker between panels that ought to look related.

Determinism

Every profile is seeded from the declared content and the panel size, through blake2b – never a clock, never hash(), which is salted per process and would agree with itself all day while disagreeing with tomorrow’s build. Every profile is also generated inside the frame by construction, so there is nothing to clip; shapely stays where it earns its place, in the balloon occlusion cost.

scenet.solve.backdrop.ATMOSPHERE = 4#

The rung beyond the farthest plane: the atmosphere itself.

scenet.solve.backdrop.FALL_CONTRAST_THRESHOLD = 0.5#

Above this lightness – of the sky as the cloud leaves it, not of the bare sky – rain is drawn in ink rather than in the paper colour. Inkers flip the same way and for the same reason: a white streak over a noon sky is invisible and a black one over midnight is too. The choice is made here rather than in the emitter, because it is a decision about the panel.

Snow does not flip. Snow is white – a convention rather than a value on the depth ladder, and a black snowflake is not a thing any comic has ever drawn. The overcast veil above is what gives it something to read against.

scenet.solve.backdrop.FOREGROUND_SPAN_KEEP = 0.6#

How much of its declared span a foreground mass keeps, held against its outer edge.

A foreground mass is a repoussoir – the doorway or the wall you are standing behind, which frames the panel. left reaches past the middle of the panel, and a foreground mass that wide stops framing the composition and starts burying it: the first contact sheet had alley hiding everything of the figure above the knees. A full-width foreground is left alone, because asking for one is asking for a silhouette.

scenet.solve.backdrop.GROUND_START: dict[Plane, float] = {Plane.FAR: 0.0, Plane.FOREGROUND: 0.68, Plane.MID: 0.16, Plane.NEAR: 0.4}#

Where a ground-like mass begins below the horizon, as a fraction of the distance from the horizon to the bottom edge.

Ground, floor and water all run to the bottom edge, so a nearer one drawn from the horizon would bury every plane behind it – the near quayside would simply erase the water. Starting each one lower leaves the planes behind it showing as bands, and that stack of receding bands is the depth cue.

The exception is the farthest ground-like mass in a panel, which meets the horizon itself: there is nothing behind it to reveal, and a strip of bare paper along the horizon reads as a mistake. See _ground_start.

scenet.solve.backdrop.PLANE_SCALE: dict[Plane, float] = {Plane.FAR: 0.55, Plane.FOREGROUND: 1.45, Plane.MID: 0.8, Plane.NEAR: 1.0}#

How much larger the same mass is drawn nearer the reader. Size perspective alongside aerial perspective: a near hill is not merely darker than a far one, it is bigger.

scenet.solve.backdrop.TONE_INDEX: dict[Plane, int] = {Plane.FAR: 3, Plane.FOREGROUND: 0, Plane.MID: 2, Plane.NEAR: 1}#

Which rung of the ladder each plane takes. Front to back, so the foreground is the darkest and the far plane the palest of the four.

class scenet.solve.backdrop.ResolvedAtmosphere[source]#

Bases: object

What the air is doing, resolved.

time#

When the panel happens.

Type:

TimeOfDay

weather#

What is falling, if anything.

Type:

Weather

tone#

The atmosphere’s own value at this hour.

Type:

str

veil#

The turbulence layer – fog, or cloud for rain and snow.

Type:

ResolvedVeil | None

streaks#

Rain, as (start, end) pairs all at one angle.

Type:

tuple[tuple[Point, Point], ...]

flecks#

Snow, as discs.

Type:

tuple[Circle, ...]

streak_width#

Stroke width for a streak, in panel units.

Type:

float

fall_tone#

What rain and snow are drawn in, chosen against the atmosphere so they stay visible at every hour.

Type:

str

colour#

The atmosphere’s tone in the panel’s palette, or "" in mono.

Type:

str

fall_colour#

The falling tone in the panel’s palette: "" in mono, and for snow, which is white by convention rather than a rung of the ladder.

Type:

str

__init__(time, weather, tone, veil=None, streaks=(), flecks=(), streak_width=0.0, fall_tone='', colour='', fall_colour='')#
class scenet.solve.backdrop.ResolvedBackdrop[source]#

Bases: object

Everything behind, around and in front of the cast.

horizon#

Where the ground meets what is behind it, in panel units. None over a supplied picture, whose horizon is wherever the artist put it.

Type:

float | None

masses#

The tonal masses, back to front.

Type:

tuple[ResolvedMass, ...]

atmosphere#

The air, or None when the weather is clear.

Type:

ResolvedAtmosphere | None

seed#

What every profile in here was generated from.

Type:

int

image#

The supplied picture behind everything, or None.

Type:

ResolvedImage | None

occluders()[source]#

The masses a balloon should prefer not to sit on, with their planes.

Masses are not exclusions. Balloons sit over backgrounds routinely; that is the point of having a background. This feeds a soft cost instead.

A supplied picture is not among them. It is one plane whose content the solver does not know, so there is nothing to price: a balloon may sit anywhere on it.

Return type:

tuple[tuple[tuple[Point, ...], Plane], ...]

__init__(horizon, seed, masses=(), atmosphere=None, image=None)#
class scenet.solve.backdrop.ResolvedImage[source]#

Bases: object

A supplied picture, placed.

pixels#

Its size, (width, height): the one fact about the file the solver has.

Type:

tuple[int, int]

fit#

How it fills the panel.

Type:

Fit

box#

Where it lands, in panel units – larger than the panel under cover, inside it under contain.

Type:

BBox

__init__(pixels, fit, box)#
class scenet.solve.backdrop.ResolvedMass[source]#

Bases: object

One tonal mass, resolved to a numeric polygon.

id#

Stable identifier, m0, m1, … back to front.

Type:

str

kind#

What it is made of, kept so a Core document stays readable.

Type:

MassKind

plane#

How far back it sits.

Type:

Plane

depth#

Its place in the painter’s order, shared with the actors.

Type:

int

tone#

The #rrggbb fill.

Type:

str

polygon#

The silhouette, in panel coordinates.

Type:

tuple[Point, ...]

colour#

The tone’s twin in the panel’s palette, or "" in mono.

Type:

str

__init__(id, kind, plane, depth, tone, polygon, colour='')#
class scenet.solve.backdrop.ResolvedVeil[source]#

Bases: object

The turbulence layer, as parameters rather than as pixels.

SVG has Perlin noise built in through feTurbulence, and the specification includes reference code, so a fixed seed is reproducible by definition – the emitted text is identical. Browsers agree only approximately on what to paint from it, which is fine and is why the determinism contract is on the SVG text and has never been on pixels. See docs/reference/language/index.md.

colour is the tone’s twin in the panel’s palette, or "" in mono.

tone: str#

The grey it is painted in.

opacity: float#

How opaque it is at its densest, from 0 to 1.

frequency: float#

The noise’s base frequency, per panel unit.

octaves: int#

How many octaves of noise are summed.

seed: int#

The noise’s seed, fixed so the SVG text is the same every time.

colour: str#

The tone’s twin in the panel’s palette, or empty in mono.

__init__(tone, opacity, frequency, octaves, seed, colour='')#
scenet.solve.backdrop.colour_for(tone, time, palette)[source]#

The colour a resolved grey is drawn in: its twin on the same rung of the same hour.

Called on a value the solver has already decided, never in place of the decision. That order is the colour policy: which rung a mass takes, and whether rain is inked or papered, are settled on the grey, and the palette only says what the settled grey looks like. So a tinted panel with its colours taken out is the mono one.

Parameters:
  • tone (str) – A grey the solver resolved for this hour.

  • time (TimeOfDay) – The hour, which selects the row of the ladder.

  • palette (Palette) – What the panel is drawn in.

Return type:

str

Returns:

The #rrggbb twin, or "" when there is none – in mono, and for a value that is not a rung of the ladder – snow is white by convention, not by value.

Example

>>> from scenet import Palette, TimeOfDay
>>> from scenet.solve.backdrop import colour_for
>>> colour_for("#eeeeee", TimeOfDay.DAY, Palette.TINTED)
'#ddf2ff'
>>> colour_for("#eeeeee", TimeOfDay.DAY, Palette.MONO)
''
scenet.solve.backdrop.contrast_ratio(one, other)[source]#

How far apart two neutral values read, on the WCAG scale.

Measured in relative luminance, not in the OKLab lightness lightness returns, and the two sitting in one file is deliberate rather than an oversight. The ladder is spaced in OKLab because that predicts even perceived steps, which is what makes four planes recede evenly. Legibility is checked here because WCAG is where the published threshold comes from, and a floor is only worth stating if it is the number the standard states.

Parameters:
  • one (str) – A #rrggbb neutral grey.

  • other (str) – The value to compare it against.

Return type:

float

Returns:

A ratio in 1.0 .. 21.0, symmetric in its arguments.

Raises:

ValueError – Either tone has a hue. A colour is measured by its grey, never itself.

Example

>>> from scenet.solve.backdrop import contrast_ratio
>>> round(contrast_ratio("#000000", "#ffffff"), 1)
21.0
scenet.solve.backdrop.depth_for(plane, *, frontmost_actor)[source]#

Painter’s order for a plane, against the cast that is already placed.

Parameters:
  • plane (Plane) – How far back the mass sits.

  • frontmost_actor (int) – The largest depth any actor in this panel was given.

Return type:

int

Returns:

A depth for the existing (depth, id) sort. Backdrop planes are negative, so they land behind every actor; the foreground takes one above the frontmost, so it draws over the cast and still under the lettering.

scenet.solve.backdrop.fit_box(pixels, panel, fit)[source]#

Where a picture lands in a panel: centred, scaled, never stretched.

cover scales it until it fills the panel, so one pair of edges overhangs equally; contain until it fits inside, so the panel shows round it on two sides. SVG’s preserveAspectRatio says the same in its own words, xMidYMid slice and meet, and a renderer that follows it draws exactly this rectangle.

Parameters:
  • pixels (tuple[int, int]) – The picture’s size, (width, height); only its proportions matter.

  • panel (BBox) – The rectangle to fill.

  • fit (Fit) – How.

Return type:

BBox

Returns:

The picture’s rectangle, in the panel’s units.

Example

>>> from scenet import Fit
>>> from scenet.geom import BBox
>>> from scenet.solve.backdrop import fit_box
>>> fit_box((960, 640), BBox(0.0, 0.0, 1200.0, 600.0), Fit.COVER)
BBox(x=0.0, y=-100.0, width=1200.0, height=800.0)
scenet.solve.backdrop.lightness(tone)[source]#

The OKLab lightness a neutral grey sits at.

The inverse of how the ladder was built, so that monotonicity is checkable rather than asserted. For a neutral, OKLab’s matrices cancel and L is the cube root of the linear value, which is the whole conversion – and that linear value is exactly the relative luminance contrast_ratio weighs, so the two share one linearisation rather than each carrying its own copy of the sRGB transfer curve.

Parameters:

tone (str) – A #rrggbb neutral grey.

Return type:

float

Returns:

Lightness in 0.0 .. 1.0.

Raises:

ValueError – The tone has a hue. A colour is measured by its grey, never itself.

Example

>>> from scenet.solve.backdrop import lightness
>>> round(lightness("#ffffff"), 3)
1.0
scenet.solve.backdrop.seed_for(setting, width, height)[source]#

A stable seed for one panel’s backdrop.

Derived from the declared content and the panel size, so the same source produces the same silhouettes forever – and two panels that differ get different ones.

blake2b rather than hash(), deliberately and load-bearingly: hash() is salted per process, so a seed derived from it agrees with itself all day and disagrees with tomorrow’s build. That is exactly the failure a golden-file test cannot see.

Parameters:
  • setting (SettingSpec) – The declared setting.

  • width (float) – Panel width in panel units.

  • height (float) – Panel height in panel units.

Return type:

int

Returns:

A 32-bit seed.

scenet.solve.backdrop.solve_backdrop(setting, panel, *, frontmost_actor=0, pixels=None, palette=Palette.MONO)[source]#

Resolve a declared setting into masses, tones and atmosphere.

Parameters:
  • setting (SettingSpec) – The declared setting.

  • panel (BBox) – The panel rectangle. Not the margined frame: a backdrop bleeds to the edge, exactly as artwork does, and only lettering is kept inside a margin.

  • frontmost_actor (int) – The largest depth any actor was given, so a foreground mass can be placed in front of the whole cast.

  • pixels (tuple[int, int] | None) – The supplied picture’s size, read from its file, when the setting names one. It is all the solver is told of it.

  • palette (Palette) – What the panel is drawn in. Every value is decided on the grey first, and the palette only adds each one’s twin; see colour_for.

Raises:

ValueError – A picture is named and its size not given, or the other way round.

Return type:

ResolvedBackdrop | None

Returns:

The resolved backdrop, or None when there is nothing to draw – which is what every panel written before this block existed gets.

Example

>>> from scenet import SettingSpec
>>> from scenet.geom import BBox
>>> from scenet.solve.backdrop import solve_backdrop
>>> solve_backdrop(SettingSpec(), BBox(0.0, 0.0, 800.0, 600.0)) is None
True
scenet.solve.backdrop.tone_for(kind, plane, time)[source]#

The value a mass is filled with.

Value comes from the plane and from nothing else, which is what keeps the notan reading literal: masses at one distance read as one mass, and the arrangement is what carries the place. Two kinds sit off their own plane’s rung, and both stay on the ladder rather than beside it:

  • sky is the atmosphere. It is at infinite distance whatever plane it was filed under, so it always takes the last rung.

  • window is a hole showing a more distant plane, so it takes the rung one step farther back than the wall it is cut into.

Parameters:
  • kind (MassKind) – What the mass is made of.

  • plane (Plane) – How far back it sits.

  • time (TimeOfDay) – When the panel happens, which selects the ladder.

Return type:

str

Returns:

A #rrggbb neutral grey.

Example

>>> from scenet import MassKind, Plane, TimeOfDay
>>> from scenet.solve.backdrop import tone_for
>>> tone_for(MassKind.SKY, Plane.FAR, TimeOfDay.NIGHT)
'#4d4d4d'

scenet.solve.text#

Text measurement and line breaking.

Nothing downstream can proceed without this. A balloon’s size is a function of its text, wrapped at some measure, in a specific font – and placement, occlusion and reading order all depend on that size. So wrapping is decided here, during compilation, and the result is carried through Panel Core as explicit lines. The emitter never re-measures and therefore can never disagree with the solver.

Determinism demands the font be fixed. It arrives as a declared dependency rather than a system lookup precisely because “whatever font this machine happens to have” is the opposite of reproducible.

scenet.solve.text.ITALIC_FONT_PATH = PosixPath('/home/runner/work/scenet/scenet/.venv/lib/python3.14/site-packages/font_source_sans_pro/files/SourceSansPro-It.ttf')#

The italic face of the same family, for the caption kinds letterers set in italic. A real font file rather than a skew transform: a synthetic oblique measures as the roman face and draws as neither, which is exactly the disagreement between measurement and rendering this module exists to prevent. It costs nothing to use – it ships in the same declared dependency.

scenet.solve.text.BOLD_ITALIC_FONT_PATH = PosixPath('/home/runner/work/scenet/scenet/.venv/lib/python3.14/site-packages/font_source_sans_pro/files/SourceSansPro-BoldIt.ttf')#

The bold italic face of the same family, for emphasis. Blambot: “There’s almost no plain bold in comics dialogue. Typically, bold italic is used when emphasis is placed on a word.” A real file for the same reason the italic is one.

scenet.solve.text.DISPLAY_FONT_PATH = PosixPath('/home/runner/work/scenet/scenet/src/scenet/fonts/Bangers-Regular.ttf')#

The display face sound effects are lettered in: Bangers, by Vernon Adams, drawn in the manner of mid-century comic cover lettering. Not of the same family, and not meant to be – a sound effect is letters treated as picture, not as text. No package carries it, so it is vendored under scenet/fonts/ with its licence, the SIL OFL 1.1, beside it. A file of the package rather than a system font, for the same reason as every face.

scenet.solve.text.SHIPPED_FACES: dict[Face, Path] = {Face.BOLD_ITALIC: PosixPath('/home/runner/work/scenet/scenet/.venv/lib/python3.14/site-packages/font_source_sans_pro/files/SourceSansPro-BoldIt.ttf'), Face.DISPLAY: PosixPath('/home/runner/work/scenet/scenet/src/scenet/fonts/Bangers-Regular.ttf'), Face.ITALIC: PosixPath('/home/runner/work/scenet/scenet/.venv/lib/python3.14/site-packages/font_source_sans_pro/files/SourceSansPro-It.ttf'), Face.REGULAR: PosixPath('/home/runner/work/scenet/scenet/.venv/lib/python3.14/site-packages/font_source_sans_pro/files/SourceSansPro-Regular.ttf')}#

The shipped family, face by face.

scenet.solve.text.Run#

A run of text in one face: what a line of lettering is made of.

alias of tuple[str, Face]

scenet.solve.text.PAIR_LOOKUP = 2#

GPOS lookup types, from the OpenType specification: pair adjustment, and the extension that wraps a lookup of another type when a table outgrows 16-bit offsets.

class scenet.solve.text.Styled[source]#

Bases: object

Text with the face every character is set in.

What lettering is measured and drawn as once emphasis is read: I _told_ you is the plain text I told you with told in bold italic. A string of one face is the same thing with every character in that face, and measures exactly as the string always did.

text#

The characters, markers already removed.

Type:

str

faces#

One face per character.

Type:

tuple[Face, ...]

classmethod of(text, face=Face.REGULAR)[source]#

Text all in one face.

Return type:

Styled

slice(start, end)[source]#

The characters from start up to end, with their faces.

Return type:

Styled

property runs: tuple[tuple[str, Face], ...]#

The text cut wherever the face changes, as (text, face) pairs.

__init__(text, faces)#
scenet.solve.text.styled(text, base=Face.REGULAR)[source]#

Read a line as written into the faces it is lettered in.

Parameters:
  • text (str) – Dialogue or a caption, emphasis markers and all.

  • base (Face) – The face the line is set in – italic for most captions. Emphasis is bold italic whatever the base, which is the letterers’ convention for a stressed word in an italic caption as much as in a roman balloon.

Return type:

Styled

Returns:

The text without its markers, each character in its face.

Raises:

EmphasisError – A span was opened and never closed. The IR refuses such text, so this only happens to a caller building lettering by hand.

Example

>>> from scenet.solve.text import styled
>>> [(text, face.value) for text, face in styled("I _told_ you").runs]
[('I ', 'regular'), ('told', 'bold_italic'), (' you', 'regular')]
class scenet.solve.text.TextBlock[source]#

Bases: object

Wrapped text, measured.

runs: tuple[tuple[tuple[str, Face], ...], ...]#

Each line cut into runs of one face. A line with no emphasis is one run.

property aspect: float#

Width divided by height, or 0.0 for an empty block.

The quantity the line breaker optimises. Lettering convention wants a balloon wider than it is tall – see TARGET_ASPECT.

property raggedness: float#

How unbalanced the lines are, from 0 (equal) to nearly 1 (one line tiny).

__init__(lines, width, height, font_size, line_height, line_widths=(), runs=())#
scenet.solve.text.FAMILY_NAME = 1#

name table entries: the family and the style within it, as a font’s own four-face (regular, italic, bold, bold italic) naming gives them. The legacy pair rather than the typographic one, because it is what a renderer matches font-family against across the most systems.

scenet.solve.text.load_metrics(path=None)[source]#

Cached metrics. Parsing a 300 KB font per balloon would be absurd.

Return type:

FontMetrics

class scenet.solve.text.Typeface[source]#

Bases: object

A lettering family: one font file per face.

A face left as None is the shipped one, loaded only when something is set in it – a panel with no emphasis never opens the bold italic file.

regular#

Dialogue, and spoken captions.

Type:

FontMetrics | None

italic#

Every other caption kind.

Type:

FontMetrics | None

bold_italic#

Emphasis, in either.

Type:

FontMetrics | None

display#

Sound effects. Bangers when not given, whatever the other faces are.

Type:

FontMetrics | None

Example

>>> from scenet.ir import Face
>>> from scenet.solve.text import Typeface
>>> Typeface().face(Face.BOLD_ITALIC).path.name
'SourceSansPro-BoldIt.ttf'
face(face)[source]#

The metrics for one face of the family.

Return type:

FontMetrics

measure(text, font_size)[source]#

Width of styled text, each character measured in its own face.

Kerned within a face and never across a change of face: two faces are two fonts, and a pair adjustment belongs to one font’s pairs. Otherwise the same sum, in the same order, as FontMetrics.measure, so text in one face measures to the last bit exactly as the plain string does.

Return type:

float

__init__(regular=None, italic=None, bold_italic=None, display=None)#
scenet.solve.text.wrap_styled(text, typeface, font_size, measure)[source]#

Greedy word wrap of styled text at a given measure.

Greedy rather than Knuth-Plass: balloons hold a handful of words, where the optimal-fit algorithm’s advantage vanishes, and greedy is trivially deterministic.

A single word longer than the measure is left to overflow rather than being hyphenated or broken. Breaking a word mid-way in comic lettering looks like a mistake, and the balloon widening to fit is the correct outcome.

Each line is measured in the faces it is set in, so a stressed word is wider here exactly as it will be drawn wider – and can push its neighbour onto the next line.

Return type:

list[Styled]

scenet.solve.text.wrap_to_width(text, metrics, font_size, measure)[source]#

Greedy word wrap of plain text at a given measure; see wrap_styled.

Return type:

list[str]

scenet.solve.text.candidate_measures(words, metrics, font_size)[source]#

Every line measure at which the wrapping can change.

A line is always some contiguous run of words, so the widths of all such runs are exactly the measures worth trying. Anything between two of them produces the same break points as the lower one.

The obvious shortcut – dividing total width by the desired line count – looks equivalent and is not. For “You forgot your umbrella!” it never proposes the measure that fits “You forgot your”, so the good two-line break is unreachable and the search settles for a ragged three-line block instead. Balloons hold a few dozen words at most, so enumerating runs costs nothing.

Return type:

list[float]

scenet.solve.text.layout_text(text, *, font_size, metrics=None, typeface=None, target_aspect=2.0)[source]#

Wrap text into the best-shaped block for a balloon.

Scored on how close the block comes to the target aspect ratio, plus a penalty per line. The penalty is what stops a three-word phrase being split: purely on aspect, breaking “I know.” into two lines scores marginally better than leaving it alone, which is not something any letterer would do.

Parameters:
  • text (str | Styled) – Plain text, set in the regular face, or styled text from styled.

  • font_size (float) – Type size in panel units.

  • metrics (FontMetrics | None) – The regular face, in place of the family’s.

  • typeface (Typeface | None) – The family to measure in. Defaults to the shipped one.

  • target_aspect (float) – The width-to-height ratio the block aims for.

Return type:

TextBlock

Returns:

The best block – its lines as plain text, and its runs the faces they are set in.

scenet.solve.text.balloon_size(block, padding_factor=0.55)[source]#

Outer dimensions of a balloon holding this text block.

Return type:

tuple[float, float]

scenet.solve.sfx#

Sound effects: letters set as part of the picture, and placed like it.

A sound effect is lettering treated as art. It is set in the display face rather than the balloon face, on one line, and bent and turned the way letterers bend and turn them – an arc, a rotation – as transforms of the glyph outlines Scenet already draws, so no renderer and no installed font has a say. Then it is placed the way everything else is placed: by generating candidate positions and scoring them, never at a coordinate.

What it may not do is the hard rule every box obeys: cover a face, leave the frame, lie under an inset. And two effects never overlap. What it prefers is to sit near the actor it comes from, or in the zone it names, and off any figure but its source’s.

What it does to everything else is cost them. Effects are placed before any balloon or caption – they are part of the picture, which lettering is placed over – and each one’s footprint then joins the emanata as ground a balloon pays to cover and is never forbidden to. Covering a sound effect deletes what the panel was saying, which is the argument for emanata too (docs/explanation/design_decisions.md).

They move nobody. An effect is placed after staging and the camera, from the figures those produced, and reaches neither.

scenet.solve.sfx.INK = '#111111'#

The two values an effect is drawn in: the stroke colour every balloon uses, and the paper the panel is printed on.

scenet.solve.sfx.SIZE_FACTORS: dict[SfxSize, float] = {SfxSize.LARGE: 4.0, SfxSize.MEDIUM: 2.6, SfxSize.SMALL: 1.6}#

How big each size is, as a multiple of the dialogue type size. Of the type, not of the figure, so an effect reads at a long shot as well as at a close-up.

class scenet.solve.sfx.EffectShape[source]#

Bases: object

An effect laid out around its own centre, before it is placed.

glyphs#

Every letter, the origin at the effect’s centre.

Type:

tuple[PlacedGlyph, ...]

footprint#

What the letters cover, outline included: a convex polygon.

Type:

Polygon

font_size#

The type size, in panel units.

Type:

float

stroke_width#

The outline’s width, in panel units.

Type:

float

metrics#

The face it is set in.

Type:

FontMetrics

__init__(glyphs, footprint, font_size, stroke_width, metrics)#
class scenet.solve.sfx.PlacedEffect[source]#

Bases: object

One effect after placement, before it is reduced to a Core document.

id#

s0, s1, … in script order.

Type:

str

order#

Its number in the panel’s one reading order.

Type:

int

text#

The sound, as written.

Type:

str

source#

The actor it comes from, if any.

Type:

str | None

font_size#

The type size.

Type:

float

glyphs#

Every letter, in panel units.

Type:

tuple[PlacedGlyph, ...]

zone#

The footprint, placed: what balloons paid to avoid.

Type:

Polygon

fill#

What the letters are filled with, or none.

Type:

str

stroke#

What they are outlined in.

Type:

str

stroke_width#

The outline’s width.

Type:

float

hollow#

Whether it is an open effect, all outline.

Type:

bool

__init__(id, order, text, source, font_size, glyphs, zone, fill, stroke, stroke_width, hollow)#
class scenet.solve.sfx.PlacedGlyph[source]#

Bases: object

One letter of an effect, where it is drawn.

character#

The letter.

Type:

str

origin#

Where its baseline starts, in panel units once the effect is placed.

Type:

Point

angle#

Its rotation in degrees, clockwise, about origin.

Type:

float

__init__(character, origin, angle)#
scenet.solve.sfx.layout_effect(event, *, dialogue_size, typeface)[source]#

Set an effect’s letters, bend and turn them, and find what they cover.

The letters are kerned and advanced exactly as any lettering is. An arc puts their baselines on a circle whose length is the line’s own, so the letters keep their spacing as it bends; each is turned to the tangent there. The whole is then centred on its own middle and turned by rotate.

Parameters:
  • event (SfxEvent) – The effect.

  • dialogue_size (float) – The panel’s dialogue type size, which the effect’s is a multiple of.

  • typeface (Typeface) – The family whose display face the effect is set in.

Return type:

EffectShape

Returns:

The effect, centred on the origin.

Example

>>> from scenet import SfxEvent
>>> from scenet.solve.sfx import layout_effect
>>> from scenet.solve.text import Typeface
>>> shape = layout_effect(SfxEvent(text="BLAM"), dialogue_size=30, typeface=Typeface())
>>> [glyph.character for glyph in shape.glyphs]
['B', 'L', 'A', 'M']
scenet.solve.sfx.place_effects(events, *, actors, hulls, panel, dialogue_size, typeface, marks=(), blocked=(), inside=None, bystanders=Bystanders(faces=(), bodies=()))[source]#

Place every sound effect, in script order, before any balloon is placed.

Parameters:
  • events (Sequence[tuple[int, SfxEvent]]) – Each effect with its index in the script, which is its reading order.

  • actors (Mapping[str, Speaker]) – The cast, as lettering sees them, by actor id.

  • hulls (Mapping[str, Polygon]) – Their silhouettes, by actor id.

  • panel (BBox) – The rectangle effects stay inside, margins applied.

  • dialogue_size (float) – The dialogue type size, which effect sizes are multiples of.

  • typeface (Typeface) – The family whose display face effects are set in.

  • marks (Sequence[BaseGeometry]) – Emanata, which effects prefer not to cover.

  • blocked (Sequence[BBox]) – Areas drawn over the panel, such as insets.

  • inside (Polygon | None) – The shape every effect must lie within, for a panel that is not a rectangle.

  • bystanders (Bystanders) – Figures a picture draws that nobody cast: their faces are as forbidden as a cast member’s, and their bodies cost as much.

Return type:

tuple[PlacedEffect, ...]

Returns:

The effects, placed.

Raises:

SfxPlacementError – An effect had no legal position anywhere in the panel.

scenet.solve.speakers#

What lettering needs to know about somebody in the panel, and nothing else.

Balloon, caption and sound-effect placement used to read posed puppets directly. They need far less than a puppet carries: a face no box may cover, a point a tail aims at, a silhouette that is costly to cover, and – for a puppet – where its eyes are and which way it is looking. That is the whole interface, and this module is it.

It is what lets a figure that a supplied picture draws be lettered by the same rules as a puppet Scenet posed: its contract declares a face, a mouth and a body in the picture’s pixels, and once those are mapped into the panel the placer cannot tell the two apart. Nobody here ever sees artwork, the picture’s or a puppet’s.

scenet.solve.speakers.STILL = Vector(dx=0.0, dy=0.0)#

Looking nowhere in particular: no line of sight for a balloon to block.

scenet.solve.speakers.MIN_BODY_POINTS = 3#

The fewest points that enclose an area.

class scenet.solve.speakers.Speaker[source]#

Bases: object

Somebody in the panel, as lettering placement sees them.

face#

The disc no balloon, caption or sound effect may cover.

Type:

Circle

mouth#

Where a tail aims. Stopped on face’s outline when it lies inside it, as a letterer stops a tail at the head rather than stabbing into it.

Type:

Point

body#

The silhouette a box pays to cover, as a polygon, or empty when none is known – a figure whose contract declares only a face.

Type:

tuple[Point, ...]

eyes#

Where a line of sight starts, if it is known.

Type:

Point | None

gaze#

Which way they are looking. Zero for nobody in particular, and for a figure a picture draws, whose gaze nobody declared: the gaze term then costs nothing.

Type:

Vector

property outline: tuple[Point, ...]#

The points that bound them: the body, or the corners of the face’s square.

What a sound they make is centred on and searched around.

Example

>>> from scenet.geom import Circle, Point
>>> from scenet.solve.speakers import Speaker
>>> Speaker(Circle(10.0, 10.0, 2.0), Point(10.0, 11.0)).outline[0]
Point(x=8.0, y=8.0)
__init__(face, mouth, body=(), eyes=None, gaze=Vector(dx=0.0, dy=0.0))#
scenet.solve.speakers.speaker_of(puppet)[source]#

A posed puppet, reduced to what lettering reads.

The mouth is the puppet’s mouth anchor, or the face’s centre for one that declares none – where the tail of a balloon it speaks has always aimed.

Parameters:

puppet (ResolvedPuppet) – The posed puppet.

Return type:

Speaker

Returns:

Its face, mouth, hull, eyes and gaze. A hull of fewer than three points has no area – a puppet that draws nothing but a face has its joints for a silhouette – and is no body: the face alone is known, as for a figure that declares one.

class scenet.solve.speakers.Bystanders[source]#

Bases: object

Figures drawn in the panel who are not in its cast: always in the way, never heard.

A picture can draw more people than a panel casts – a crowd, of whom two speak. Each face it declares is still a face, so it is as forbidden to lettering as a speaker’s; each body still costs, and nobody is forgiven covering it, since nobody speaks from it.

faces#

Their faces, in the order the contract declares them.

Type:

tuple[Circle, ...]

bodies#

Their silhouettes, for those who have one, in the same order.

Type:

tuple[Polygon, ...]

classmethod of(figures)[source]#

Bystanders from the figures nobody cast.

Parameters:

figures (Sequence[Speaker]) – Each figure, as lettering sees them.

Return type:

Bystanders

Returns:

Their faces, and the bodies of those that declare one.

__init__(faces=(), bodies=())#
scenet.solve.speakers.NOBODY = Bystanders(faces=(), bodies=())#

A panel with nobody in it but its cast.

scenet.solve.figures#

Figures a supplied picture draws, placed in the panel through the picture’s fit.

An artwork contract declares each figure in the picture’s own pixels. The picture is fitted to the panel – centred, scaled, never stretched (fit_box) – and every declared point goes through the same transform, so a face lands exactly where the picture draws it, under cover and contain alike. One scale serves both axes, because the picture keeps its proportions.

Nothing here moves anybody. The solver chooses no position for a figure: the artist did. It only translates the contract into the panel’s units, for lettering to work around.

class scenet.solve.figures.PlacedFigure[source]#

Bases: object

One figure the picture draws, in panel units.

name#

Its name in the contract.

Type:

str

face#

Its face, which no lettering may cover.

Type:

Circle

mouth#

Where a tail it speaks ends, if declared.

Type:

Point | None

body#

Its silhouette, or empty when none is declared.

Type:

tuple[Point, ...]

property speaker: Speaker#

The figure as lettering sees it: no gaze, and the face’s centre for a mouth.

__init__(name, face, mouth=None, body=())#
class scenet.solve.figures.PlacedPicture[source]#

Bases: object

What a picture’s contract declares, placed.

figures#

Each figure, in the order the contract declares them.

Type:

tuple[PlacedFigure, ...]

keep_out#

Each region lettering should stay off, in the same order.

Type:

tuple[tuple[Point, ...], ...]

__init__(figures=(), keep_out=())#
scenet.solve.figures.place_figures(contract, image)[source]#

Map a contract from the picture’s pixels into the panel.

Parameters:
Return type:

PlacedPicture

Returns:

The figures and keep-out regions, in panel units.

Example

>>> from scenet import Fit
>>> from scenet.assets.artwork import ArtworkContract
>>> from scenet.geom import BBox
>>> from scenet.solve.backdrop import ResolvedImage
>>> from scenet.solve.figures import place_figures
>>> contract = ArtworkContract.model_validate(
...     {
...         "size": [200, 100],
...         "figures": {"ana": {"face": {"center": [50, 40], "radius": 10}}},
...     }
... )
>>> picture = ResolvedImage((200, 100), Fit.COVER, BBox(-50.0, 0.0, 400.0, 200.0))
>>> place_figures(contract, picture).figures[0].face
Circle(cx=50.0, cy=80.0, r=20.0)

scenet.solve.balloons#

Placing everything in a panel that carries words: balloons, captions, and tails.

Placement is a scored search over candidate positions rather than a sweep of a cost grid. Balloons belong in a small number of sensible places relative to their speaker – around the head, or tucked into a corner – so generating those directly is both cheaper than scanning cells and produces more natural results. This is the approach used in the cartographic label-placement literature, which is the same problem.

The constraint that naive implementations miss is reading order. A box may never sit above-and-left of the one before it in the script – above-and-right, in a panel read right to left – because that makes the panel read in the wrong order. That is a correctness bug in a comic, not a cosmetic one, so it is enforced as a hard filter rather than scored.

Read right to left, the lettering is the mirror image, and nothing else is. Every rule and tiebreak reading decides – the order itself, which candidate is tried first, where an unplaced box would rather start – is mirrored, so a mirrored panel read right to left is lettered as the mirror of the original. The scene is not mirrored: the figures, their gaze, sound effects and every tail stay as staged.

Captions go through this machinery rather than a parallel one. The placement principles the lettering references give for floating text – keep off the important figures, preserve the space of the art, keep the reading order flowing – are the ones already implemented here. What differs is where a caption wants to be: a balloon mildly dislikes hugging the panel edge, and a caption is looking for exactly that.

So the two are placed in one pass in script order, sharing the list of boxes already down. Placing every caption first would be simpler and wrong: a caption written after the dialogue would then impose reading order on balloons that precede it.

scenet.solve.balloons.SMALL_TYPE_FRACTION = 0.75#

Small lettering against the panel’s dialogue size: a step down a letterer would make by eye, as the caption size is one. The balloon keeps the padding the normal size would have, which is what makes small type read as muttered rather than as a smaller balloon.

scenet.solve.balloons.READING_STARTS: dict[Direction, PlacementZone] = {Direction.LTR: PlacementZone.TOP_LEFT, Direction.RTL: PlacementZone.TOP_RIGHT}#

Where a box with no zone of its own would rather start: where reading starts. A locale caption sits there by convention, and an off-panel voice with no side named is heard from there. A zone the author writes is a place on the panel, and does not follow.

scenet.solve.balloons.CAPTION_COLOURS: dict[CaptionTone, str] = {CaptionTone.WARM: '#fef0a1'}#

What a tone is drawn in when the palette has colour: the twin of its grey, a colour with the grey’s OKLab lightness. Only warm has one – the classic yellow locale caption – and paper, pale and ink stay neutral in every palette. Generated by scripts/make_palette.py (OKLCh chroma 0.100, hue 100) and checked against it by tests/test_warm_caption.py, with the lettering floor measured on the colour.

scenet.solve.balloons.CAPTION_INK = '#111111'#

What lettering is drawn in, and its opposite. CAPTION_INK is the emitter’s stroke colour, restated here because the choice between the two is made in the solver.

scenet.solve.balloons.LETTERING_FLOOR = 4.5#

The floor a caption’s own lettering must clear against its fill: WCAG AA for body text. This is the contrast a reader actually gets, because the box is opaque and the text sits on the fill whatever is behind it. letter_tone is what holds it, and tests/test_setting.py is what proves every tone in the palette does.

scenet.solve.balloons.SEPARATION_FLOOR = 3.0#

The floor at which a box separates from the plane behind it: WCAG AA for large text, which is the right comparison for a filled rectangle rather than for type.

Not every tone clears this on every rung, and none is required to. White on a noon sky is 1.16:1, which is the whole reason tone exists. What the palette owes the author is an escape from every background the compiler can produce – at least one tone above this floor for every rung of every row – and that is what is tested.

class scenet.solve.balloons.TailRoute[source]#

Bases: object

The pointer from balloon to mouth.

A straight tail is correct almost always. control is set only when the direct route was obstructed and the tail had to bend around something.

property is_curved: bool#

Whether this tail had to bend around a face.

Reported in CompileResult.notes, since a curved tail is a sign the panel is crowded enough to be worth a second look.

__init__(start, end, control=None)#
class scenet.solve.balloons.PlacedBalloon[source]#

Bases: object

One balloon after placement, before it is reduced to a Core document.

id#

Stable identifier, b0, b1, … in script order.

Type:

str

speaker#

Actor id of whoever is talking.

Type:

str

order#

Position in reading order, counting from zero.

Type:

int

kind#

Which sort of balloon to draw.

Type:

BalloonKind

box#

Where it ended up.

Type:

BBox

block#

The text, already broken into lines and measured.

Type:

TextBlock

tail#

The route from balloon to mouth – or, for a speaker off panel, to the frame on their side.

Type:

TailRoute

off_panel#

The side of the frame an off-panel speaker is on, as resolved, or None for one who is drawn.

Type:

Side | None

__init__(id, speaker, order, kind, box, block, tail, off_panel=None)#
class scenet.solve.balloons.PlacedCaption[source]#

Bases: object

One caption after placement, before it is reduced to a Core document.

id#

Stable identifier, c0, c1, … in the order the captions appear.

Type:

str

order#

Position in the panel’s reading order, which captions share with balloons – so a caption between two lines of dialogue takes the number between theirs.

Type:

int

kind#

What the box is doing, which decides how it is set.

Type:

CaptionKind

box#

Where it ended up.

Type:

BBox

block#

The text, already quoted where the kind calls for it, broken into lines and measured against the face it will be drawn in.

Type:

TextBlock

fill#

The value the box is filled with, resolved from the declared tone.

Type:

str

ink#

The value its lettering is drawn in, chosen against fill so the text reads on the box it sits in.

Type:

str

speaker#

Who is talking, for a spoken caption. They are off panel, so this is not an actor id and resolves to nobody in the cast.

Type:

str | None

colour#

The fill’s twin in the panel’s palette, or "" when there is none.

Type:

str

There is no tail, which is the reason this is not a fifth BalloonKind.

__init__(id, order, kind, box, block, fill='#ffffff', ink='#111111', speaker=None, colour='')#
class scenet.solve.balloons.ScriptLayout[source]#

Bases: object

Everything in a panel that carries words, placed.

Separate tuples rather than one merged sequence: they reduce to different Core types, and the thing that orders them – order – is on each.

__init__(captions=(), balloons=(), effects=())#
scenet.solve.balloons.route_tail(balloon, mouth, obstacles, speaker_face=None)[source]#

Route a tail from the balloon toward the speaker’s mouth.

Straight is right almost always, so it is tried first. Only when the direct line crosses another character’s face does the tail bend, and then via a single control point chosen from a handful of lateral offsets.

Grid pathfinding is deliberately not used here. A tail is a short tapered stroke, and A-star produces a jointed path that looks nothing like one drawn by hand.

Return type:

TailRoute

scenet.solve.balloons.letter_tone(fill)[source]#

What a caption filled with this value is lettered in.

Ink over a pale box, paper over a dark one, chosen by contrast rather than by a threshold on the tone – the same rule and the same reason as falling rain in solve/backdrop.py, where a white streak is invisible against noon and a black one against midnight. Inkers flip the same way.

Resolved here rather than in the emitter because which mark reads is a fact about the panel, not a rendering preference: the emitter must not be able to draw a box in a value the solver did not choose.

Parameters:

fill (str) – The #rrggbb the box is filled with.

Return type:

str

Returns:

The value the lettering is drawn in.

Example

>>> from scenet.solve.balloons import letter_tone
>>> letter_tone("#ffffff"), letter_tone("#090909")
('#111111', '#ffffff')
scenet.solve.balloons.caption_colour(tone, palette)[source]#

What a caption’s box is drawn in, in a palette, beside the value it is filled with.

The value and the lettering are decided on the grey, whatever the palette; this only says what that grey looks like when the palette has colour.

Parameters:
  • tone (CaptionTone) – The tone the caption declares.

  • palette (Palette) – What the panel is drawn in.

Return type:

str

Returns:

The tone’s #rrggbb twin, or "" when there is none – in mono, and for every tone but warm.

Example

>>> from scenet import CaptionTone, Palette
>>> from scenet.solve.balloons import caption_colour
>>> caption_colour(CaptionTone.WARM, Palette.TINTED)
'#fef0a1'
>>> caption_colour(CaptionTone.WARM, Palette.MONO)
''
scenet.solve.balloons.caption_text(events, index)[source]#

The text of a caption, with quotation marks where the kind calls for them.

Blambot’s rule for a run of one speaker’s spoken captions: an opening quote on each, a closing quote only on the last. Consecutive boxes are one continuous line of off-panel speech, and closing each of them would read as four separate interruptions.

Applied here, before measurement, and carried through Panel Core as part of the resolved lines. Adding the marks in the emitter would make the text wider than the box that was drawn for it.

Parameters:
Return type:

str

Returns:

The text to letter.

Example

>>> from scenet import CaptionEvent, CaptionKind
>>> from scenet.solve.balloons import caption_text
>>> run = (
...     CaptionEvent(text="Get down!", kind=CaptionKind.SPOKEN),
...     CaptionEvent(text="All of you!", kind=CaptionKind.SPOKEN),
... )
>>> caption_text(run, 0).endswith("”")
False
>>> caption_text(run, 1).endswith("”")
True
scenet.solve.balloons.place_script(events, speakers, panel, *, bystanders=(), keep_out=(), metrics=None, italic_metrics=None, typeface=None, font_size=None, type_size=None, lettering_height=None, backdrop=None, emanata=None, exclusions=(), inside=None, bounds=None, outline=None, direction=Direction.LTR, palette=Palette.MONO)[source]#

Place every sound effect, then every balloon and caption in script order.

Greedy rather than jointly optimised: each box is placed against those already down, which is exactly how reading order works – a box constrains its successor, never its predecessor. That makes the greedy pass the natural formulation rather than a compromise.

One pass over the whole script, not captions and then balloons. The two share the list of boxes already placed, so a caption written between two lines of dialogue is read between them.

Parameters:
  • events (Sequence[SayEvent | CaptionEvent | SfxEvent | SayEvent | CaptionEvent | SfxEvent]) – The panel’s script, in reading order.

  • speakers (Mapping[str, Speaker]) – Everybody in the cast who is drawn, keyed by actor id, as lettering sees them: posed puppets, or figures a picture draws.

  • panel (BBox) – The rectangle to compose within, margins already applied.

  • bystanders (Sequence[Speaker]) – Figures a picture draws that nobody cast. Their faces are as forbidden as a speaker’s, and their bodies cost as much, never forgiven.

  • keep_out (Sequence[Sequence[Point]]) – Regions of a picture lettering should stay off. A soft cost, at the weight of emanata, and never an exclusion.

  • metrics (FontMetrics | None) – Font to measure roman lettering against, in place of the family’s.

  • italic_metrics (FontMetrics | None) – Font to measure italic captions against, in place of the family’s.

  • typeface (Typeface | None) – The lettering family, emphasis face included. Defaults to the shipped one; metrics and italic_metrics replace single faces of it.

  • font_size (float | None) – Override for every type size, dialogue and captions alike, in panel units. For tests that want one size throughout.

  • type_size (float | None) – The dialogue size the author set with lettering.size, in panel units. Captions keep their proportion to it. Takes the place of lettering_height, which only matters when no size was set.

  • lettering_height (float | None) – The height type sizes are a fraction of, in place of the frame’s own. A page passes one value to every panel on it, so a short panel and a tall one letter alike.

  • backdrop (ResolvedBackdrop | None) – The resolved setting, if the panel has one. Its masses are a soft cost, never an exclusion: a balloon over a sky is the ordinary case.

  • emanata (Mapping[str, Sequence[Sequence[Point]]] | None) – Actor id to the zones of the marks drawn around them. Also a soft cost, and a heavier one than a body, but never an exclusion.

  • exclusions (Sequence[BBox]) – Areas that are drawn over, such as an inset: as hard as a face, since words under them could not be read. They take no part in reading order.

  • inside (Sequence[tuple[float, float]] | None) – The shape every box must lie within, when the panel is not a rectangle, margins already applied – as panel has them. A box must also lie within panel; candidates are still generated in it.

  • bounds (BBox | None) – The panel’s own rectangle, margins not applied: the frame an off-panel speaker’s tail ends on. Defaults to panel.

  • outline (Sequence[tuple[float, float]] | None) – The panel’s own outline when it is not a rectangle, margins not applied, which that tail ends on instead.

  • direction (Direction) – Which way the panel is read. It decides the reading order and every tiebreak reading decides, and nothing about the picture.

  • palette (Palette) – What the panel is drawn in. It decides no position and no lettering, only the colour a caption’s box has beside its value; see caption_colour.

Return type:

ScriptLayout

Returns:

Everything that carries words, placed.

Raises:

scenet.solve.page#

Page layout: tiers of panels, or of columns of panels, into frames.

Plain arithmetic, with no constraint solver. Tiers are ordered top to bottom and panels left to right within a tier, and each takes a share of what the margins and gutters leave, in proportion to its weight – the same model as CSS Grid’s fr tracks with a gap. A tier of columns is split the same way twice: across into columns, then down each column into its panels, with the tier gutter between them. There is nothing to choose between, so nothing for Cassowary to do: its value in this project is the priority system that settles conflicting preferences (docs/explanation/prior_art.md), and a strict grid has none.

The order panels are written in is the order they are read in. In a tier of panels that is the Z-path. In a tier of columns it is down each column before across, which is what readers do when a panel spanning the tier blocks the way across (Cohn, Navigating Comics, 2013); PageLayout refuses columns where nothing blocks it. An inset is where readers agree least, splitting about evenly between it and the panel it sits in, so it is read after its parent unless it says otherwise.

Read right to left, as manga are, a tier’s first panel or column is at the right. The tier is laid out by the same arithmetic over its panels in the other order, so each frame is exactly the one a left-to-right page gives that panel with the tier written the other way round. Nothing is mirrored: a slanted gutter leans the way its slant says, an inset sits in the corner its at names, a bleed is on the sides it names, and a column is still read top to bottom. An end panel stays an end panel and keeps its width, so a layout one direction refuses, the other refuses too – except a bleed on a side that, the other way round, is a gutter.

A panel can bleed: each side its placement’s bleed names runs past the margin and the trim to the bleed line. The frame keeps two more boxes: what the reader sees, out to the trim, and the frame as it was, where its lettering keeps.

scenet.solve.page.LETTERING_TIERS = 3#

Type on a page is set as if every panel were one tier of a page this many tiers tall. Three tiers of the default page letter at about 1.2% of the page’s height, which on a printed comic page is about eight points – the size lettering is usually set at. It is also exactly what a single panel letters at today when it is a third of a page tall, so nothing changes for a panel that was already the size it ends up on the page.

class scenet.solve.page.Frame[source]#

Bases: object

Where one panel goes on its page.

panel#

The panel’s name.

Type:

str

x#

Left edge.

Type:

float

y#

Top edge.

Type:

float

width#

Frame width.

Type:

float

height#

Frame height.

Type:

float

inset_of#

For an inset, the panel it is set into; None otherwise.

Type:

str | None

clearance#

For an inset, the area it covers with its ring of white: the frame grown by a gutter on every side. It is painted white under the inset, and its parent’s lettering keeps clear of it. None for a panel that is no inset.

Type:

BBox | None

outline#

For a panel in a slanted tier, its four corners, clockwise from the top left, in page units; the frame is their bounding box. None for a rectangle.

Type:

tuple[tuple[float, float], ...] | None

bleed#

The sides the frame runs out to the bleed line on: its frame is then the larger box, partly past the page’s edge.

Type:

tuple[Side, ...]

visible#

For a panel that bleeds, its frame out to the trim only: what the reader sees, which its cast is staged and framed in.

Type:

BBox | None

live#

For a panel that bleeds, its frame as it was before: what its lettering keeps inside, the page’s margin being the live area.

Type:

BBox | None

__init__(panel, x, y, width, height, inset_of=None, clearance=None, outline=None, bleed=(), visible=None, live=None)#
scenet.solve.page.lettering_height(page_format)[source]#

The height every panel on a page takes its type size from.

A panel letters at a fixed fraction of a height. Alone, that height is its own; on a page it is this one, the same for every panel, so a short panel and a tall one letter alike, as no letterer would do otherwise.

Parameters:

page_format (PageFormat) – The page.

Return type:

float

Returns:

A third of the height inside the margins (see LETTERING_TIERS).

scenet.solve.page.resolve_frames(page_format, page, *, index=0, direction=Direction.LTR)[source]#

Lay out one page.

Parameters:
  • page_format (PageFormat) – Size, margin and gutters.

  • page (PageSpec) – The tiers, already validated to have room for what they hold.

  • index (int) – The page’s position among the pages, from 0, to locate a mistake.

  • direction (Direction) – Which way the page is read. Right to left, each tier’s first panel or column is at the right.

Return type:

tuple[Frame, ...]

Returns:

One frame per panel, in reading order – tier by tier, and within a tier left to right – right to left, for a page read that way – or, for a tier of columns, column by column and top to bottom in each. An inset comes right after the panel it is set into, or right before it when it says read: before.

Raises:

RuleViolationError – Rule page-layout, for two insets in one panel that overlap, or a bleed on a side that does not reach the page’s margin. Each is found here, where the frames are worked out, and scenet check runs this too, so the finding is still located.

Example

>>> from scenet import PageFormat, PageSpec
>>> from scenet.solve.page import resolve_frames
>>> page = PageSpec.model_validate(
...     {"tiers": [{"panels": [{"use": "a"}, {"use": "b", "width": 2}]}]}
... )
>>> [(f.panel, f.x, f.width) for f in resolve_frames(PageFormat(), page)]
[('a', 100.0, 586.67), ('b', 726.67, 1173.33)]

scenet.solve.describe#

The words a panel is read in, for a reader who cannot see it.

Two things, both built here so that Panel Core carries them and the emitter copies them without deciding anything:

  • A description of what the panel shows. The author’s, when there is one – written as description:, or a comic script’s prose. Otherwise generated from what the panel holds, covering what AccessComics (Lee, Joh, Yoo & Oh) found blind readers wanted narrated: the shot, the place and the hour, who is where, facing whom, with what face and what marks. "Medium shot. A street at night, in the rain. Alice, left, pointing, angry, looking at Bob; Bob, right, arms crossed, sweating."

  • A label for each script entry: who says it, how, and the words – "Bob, whispering: I know." – in the one reading order balloons, captions and sound effects share.

Generated text is templated English, and that is its limit: a French script’s prose is read in French, but the words round its dialogue are English. Every phrase is in a table below, keyed by the enum it reads, so a value with no phrase is a test failure rather than a gap a reader hears. Nothing depends on a locale, or on the order a set or a dict happens to iterate in: the cast is read in reading order – left to right, or right to left for a comic read that way – ties broken by id. Where each stands, “left” or “right”, is said as it is on the panel either way.

This sees no artwork. Where a figure is comes in as one number, its face’s x, the same rounded value Panel Core records.

scenet.solve.describe.ANGLES: dict[CameraAngle, str] = {CameraAngle.EYE_LEVEL: '', CameraAngle.HIGH: 'from a high angle', CameraAngle.LOW: 'from a low angle'}#

The camera’s height, said after the shot; eye level goes without saying.

scenet.solve.describe.EXPRESSIONS: dict[str, str] = {'surprise': 'surprised'}#

Expressions whose name is not a word that can follow a name. Any other is read as written, an underscore a space: a puppet of one’s own names its own.

scenet.solve.describe.INDOOR: frozenset[MassKind] = frozenset({MassKind.CEILING, MassKind.FLOOR, MassKind.FURNITURE, MassKind.WALL, MassKind.WINDOW})#

COCO-Stuff’s indoor supercategories: masses that make a backdrop an interior.

scenet.solve.describe.MARKS: dict[Mark, str] = {Mark.BRIFFITS: 'dashing off', Mark.GRAWLIXES: 'swearing', Mark.PLEWDS: 'sweating', Mark.SQUEANS: 'dizzy'}#

Walker’s marks, read as what they say – the table in Mark.

scenet.solve.describe.PLACE_NAMES: dict[Place, str] = {Place.ALLEY: 'An alley', Place.DESERT: 'A desert', Place.DOCKS: 'The docks', Place.FIELD: 'A field', Place.FOREST: 'A forest', Place.MOUNTAIN: 'A mountainside', Place.OFFICE: 'An office', Place.ROOM: 'A room', Place.SHORE: 'A shore', Place.STREET: 'A street'}#

Each named place, as the start of a sentence.

scenet.solve.describe.SHOTS: dict[ShotType, str] = {ShotType.BIG_CLOSE_UP: 'Big close-up', ShotType.CLOSE_UP: 'Close-up', ShotType.COWBOY: 'Cowboy shot', ShotType.EXTREME_CLOSE_UP: 'Extreme close-up', ShotType.FULL_SHOT: 'Full shot', ShotType.LONG_SHOT: 'Long shot', ShotType.MEDIUM_CLOSE_UP: 'Medium close-up', ShotType.MEDIUM_FULL: 'Medium full shot', ShotType.MEDIUM_SHOT: 'Medium shot', ShotType.WIDE: 'Long shot'}#

Each rung of the shot ladder, as a letterer’s script would name it.

scenet.solve.describe.WEATHERS: dict[Weather, str] = {Weather.CLEAR: '', Weather.FOG: 'in fog', Weather.RAIN: 'in the rain', Weather.SNOW: 'in the snow'}#

What the air is doing; a clear sky goes without saying.

scenet.solve.describe.describe(panel, faces, width)[source]#

What the panel shows, in words: the author’s, or generated from what it holds.

Parameters:
  • panel (PanelIR) – The validated panel.

  • faces (Mapping[str, float]) – Each actor’s face-centre x, as Panel Core records it.

  • width (float) – The panel’s width, which “left” and “right” are thirds of.

Return type:

str

Returns:

One paragraph.

Example

>>> from scenet import parse_panel
>>> from scenet.solve.describe import describe
>>> panel = parse_panel("setting: {place: docks, time: night}")
>>> describe(panel, {}, 1000.0)
'The docks at night.'
scenet.solve.describe.label(event)[source]#

One script entry as it is read: who, how, and the words.

The words are the author’s, with emphasis markers off – never the lettered lines, which are broken to fit and, for a spoken caption, carry quotation marks that are lettering rather than speech.

Example

>>> from scenet import SayEvent
>>> from scenet.solve.describe import label
>>> label(SayEvent(by="bob", text="I _know_", kind="whisper"))
'Bob, whispering: I know.'
Return type:

str

scenet.solve.describe.labels(script)[source]#

Every entry’s label, in script order, which is reading order.

Return type:

tuple[str, ...]

scenet.solve.describe.name(actor)[source]#

An actor id as a name: an underscore a space, and a lower-case id capitalised.

An id written in capitals, as a comic script writes its cast, is kept as it is.

Example

>>> from scenet.solve.describe import name
>>> [name(actor) for actor in ("alice", "guard_left", "ALICE")]
['Alice', 'Guard left', 'ALICE']
Return type:

str

scenet.solve.describe.sentence(text)[source]#

A line as a sentence: one space between words, and a full stop if it has no end.

So two lines one after the other are heard as two – Hi and Hello would otherwise run together. A line that already ends, inside its quotation marks or not, is left as it is.

Example

>>> from scenet.solve.describe import sentence
>>> [sentence(line) for line in ("Hi", "You what?!", "“Get down”")]
['Hi.', 'You what?!', '“Get down”.']
Return type:

str

scenet.solve.describe.traits(pose, expression, marks)[source]#

How a figure stands, its face and its marks, as a description says them.

What goes without saying – standing, a neutral face – is left out. The one phrasing of a figure: the description reads it, and so does the boxes export.

Example

>>> from scenet import Mark
>>> from scenet.solve.describe import traits
>>> traits("hands_on_hips", "surprise", [Mark.PLEWDS])
['hands on hips', 'surprised', 'sweating']
>>> traits("standing_neutral", "neutral", [])
[]
Return type:

list[str]