mirror of
https://github.com/mankidev/antialgorithm.git
synced 2026-11-30 19:33:35 -10:00
Tie roughness to the method, add idea and region seeds
This commit is contained in:
1 parent
7f1af10f2a
commit
7f92b83069
5 files changed
+384
-134
No files matched your search
@@ -18,9 +18,9 @@ The scripts need Python 3. `check.py` also needs numpy, Pillow and `rsvg-convert
|
||||
|
||||
## Scripts
|
||||
|
||||
`seed.py` rolls a starting point when the request is thin: a making method, colors, layout, type, a setting and an object. It draws from system randomness, so two people sending the same prompt start in different places.
|
||||
`seed.py` rolls a starting point when the request is thin. A visual seed gives a making method, colors, layout, type, a verb and a scale for the idea, a setting, a region and, half the time, an object. A text seed gives a voice, a way in and a register. An idea seed gives a verb, a constraint, a scale and a pressure. It draws from system randomness, so two people sending the same prompt start in different places.
|
||||
|
||||
`rough.py` takes an SVG and shakes its straight lines, shapes and letters, and breaks the even spacing of repeated marks, so a poster drawn in code stops looking plotted.
|
||||
`rough.py` takes an SVG and shakes its straight lines, shapes and letters, and breaks the even spacing of repeated marks, so a hand-made look drawn in code stops looking plotted. It is only for hand-made methods such as print, paint, stamps and ink; screen, camera and render looks keep their own marks.
|
||||
|
||||
`check.py` renders an SVG at full size and at icon size and lists text that runs off an edge, sits under a shape, has low contrast or is too small.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: antialgorithm
|
||||
description: Stops the safe, average, comfortable pick that AI reaches for first. Use whenever a creative choice is made: ideas, names, story, game mechanics, visual style, color, layout, UI, composition, wording, tone, titles, descriptions. Also use when the user says "too generic", "boring", "typical AI", "too safe", "cliche", "average", "seen it before".
|
||||
description: Stops the safe, average, comfortable pick that AI reaches for first. Use when a creative choice is left open to Claude: ideas, names, story, game mechanics, visual style, color, poster or page layout, composition, wording, tone, titles, descriptions. Not for code identifiers, bug fixes or choices the user already made. Also use when the user says "too generic", "boring", "typical AI", "too safe", "cliche", "average", "seen it before".
|
||||
---
|
||||
|
||||
# antialgorithm
|
||||
@@ -13,7 +13,7 @@ The answer must differ from one user to the next, and you cannot see what others
|
||||
|
||||
1. If the request carries real context, such as a project, a place, a person, a purpose or a constraint, start from that.
|
||||
2. If the request is thin and the work is short, such as a few slogans, a name or a short text, do not stop at a question. Make the work from a seed or a stated guess, then ask one short question at the end that would make it fit better. The question asks for a fact about the case, not for leave to redo the work. If the work is long or costly, such as a full design, a long text or a game system, ask the one short question first: who it is for, where it lives or what it is about.
|
||||
3. If the request is thin and the user wants the work now, or cannot answer, roll a seed: `python3 scripts/seed.py visual`, `text` or `idea` (paths are relative to this skill's folder). Use what it gives as the starting point. You may roll one axis again once with `--only <axis>` if it truly fights the subject. Then tie the seed to the subject with a reason.
|
||||
3. If the request is thin and the user wants the work now, or cannot answer, roll a seed: `python3 scripts/seed.py visual`, `text` or `idea` (paths are relative to this skill's folder). Use what it gives as the starting point. A visual seed also gives a verb and a scale: build the idea behind the piece from them, who does what, instead of a twist you think of yourself. You may roll one axis again once with `--only <axis>` if it truly fights the subject. The region places the setting: names, jokes, habits and the way people speak come from the people of that region, while the words stay in the language set near the end of this skill. Then tie the seed to the subject with a reason.
|
||||
|
||||
Never pick the start point by thinking about what would be most interesting. That thought lands on the same place for all users.
|
||||
|
||||
@@ -33,7 +33,9 @@ Do not write what any writer would write about any subject. If a sentence could
|
||||
|
||||
Prefer the concrete detail over the general claim. Prefer the plain word over the impressive one. Prefer the unexpected but true angle over the expected summary.
|
||||
|
||||
Do not reach for the common opening, the common structure or the common ending. If the shape of the text is the shape most texts use, change the shape.
|
||||
A concrete detail is a thing a person could see, touch or do there. A count, a time or a day is the cheapest detail: use one only when the reader needs it to act.
|
||||
|
||||
Do not reach for the common opening, the common structure or the common ending. If the shape of the text is the shape most texts use, change the shape, but only inside the length and format the user set.
|
||||
|
||||
These are the marks of default AI text. Do not use them:
|
||||
|
||||
@@ -51,6 +53,8 @@ These are the marks of default AI text. Do not use them:
|
||||
|
||||
Write the text a real person in this situation would write: shorter, built on the real facts of this case, and with an end that just stops.
|
||||
|
||||
This list covers the marks that come from picking the default. To clean the rest of the AI marks from a finished text, run a separate editing pass or a text cleanup skill if one is installed.
|
||||
|
||||
## Visuals
|
||||
|
||||
Do not use the look that a tool or a model would produce with no instructions. If the palette, layout, lighting, pose or framing is what you would get from a plain prompt, it is the default.
|
||||
@@ -59,13 +63,25 @@ Pick the look from the subject itself: its material, its place, its time, its mo
|
||||
|
||||
Do not center, balance and smooth it all by habit. Balance is a choice, not a starting point.
|
||||
|
||||
The method marks below are for posters, covers, promo images and other pieces made to be looked at. They do not apply to:
|
||||
|
||||
- Interfaces: buttons, menus, panels and game HUD keep a clean grid, exact alignment and centered labels. Pick their palette, shape language and wording with this skill, not their wobble.
|
||||
- Pixel art and block models: when another skill or tool owns how they are drawn, use this skill only to choose the subject, palette and composition.
|
||||
|
||||
A new subject is not enough. AI images are known by their finish, not by their topic. The finish is: smooth gradients, soft glow, perfect geometry, tiles that repeat with no change, clean edges on all shapes, even spacing, one default font, and the same polish on all parts. If the image has this finish, it looks made by AI whatever it shows.
|
||||
|
||||
Decide how a person would make this thing by hand or by machine: a print, a stamp, a cut paper piece, a photocopy, a painted sign, a photo. Then obey the limits of that method: its few colors, its grain, its slips, its uneven ink, its rough edges. The limits are what make it look made.
|
||||
Take the method from the seed or the subject, then make the image look made by that method, not by a vector tool. Each method leaves its own marks, and those marks replace the AI finish:
|
||||
|
||||
Let the shapes be imperfect where a hand or a machine would make them so. Lines vary in width, edges break, colors miss their place a little, repeats drift. Keep this real and sparse, not a noise filter laid over a clean image.
|
||||
- Print and paint: few inks, colors that miss their place, uneven ink, broken edges, the grain of the paper.
|
||||
- Screens and machines: the pixel or dot grid, scan lines, bleed and bloom, faded bands, steps where a gradient runs out of colors, the font the machine has.
|
||||
- Camera and science: sensor grain or noise, light that falls off, blur where focus or motion puts it, the false colors of the instrument, a crop the camera chose.
|
||||
- Material and light: the seams, joints and thickness of the material, and light that bends, reflects or glows the way that material does.
|
||||
|
||||
Code makes perfect marks and a hand does not. When the image is made in code, the geometry itself must carry the hand, not only the surface on top of it:
|
||||
Keep these marks real and sparse, not a noise filter laid over a clean image. Some methods are clean by nature, such as a glossy render, a CAD drawing or a spreadsheet chart. Keep those clean and let their light, grid and tools say what they are.
|
||||
|
||||
Do not reach for a hand-drawn wobble when the method is not made by hand. A wobbly line on an LED board, an x-ray or a 3D render is a second default laid over the first. Look at the result at icon size: if it reads as a flat vector drawing whatever the seed said, the method is missing.
|
||||
|
||||
When the method is made by hand, code must carry the hand in the geometry, not only in the surface on top of it:
|
||||
|
||||
- No line is exactly straight and no curve is a clean math function. Points drift a little, strokes swell and thin, ends are blunt or overshoot.
|
||||
- Repeated marks, such as hatching, dots, stripes or tiles, change in spacing, length and angle from one to the next.
|
||||
@@ -73,9 +89,9 @@ Code makes perfect marks and a hand does not. When the image is made in code, th
|
||||
- Letters are not a system font in a perfect row. Draw them, cut them, stamp them or at least break their edges, and let their baseline and spacing move a little.
|
||||
- The layout is placed by eye, not snapped to equal columns and equal gaps.
|
||||
|
||||
Look at the result at full size. If the lines look plotted, the curves look computed or the text looks typed, it still reads as machine made, however much grain is on it.
|
||||
Look at the result at full size. If a hand-made piece has lines that look plotted, curves that look computed or text that looks typed, it still reads as machine made, however much grain is on it.
|
||||
|
||||
Typing coordinates by hand gives clean marks. Generate irregular marks with a short script instead of writing them one by one. Stop at the number of marks the eye needs: a poster built from thousands of tiny pieces is slow to make and heavy to open, so keep an SVG under about 200 KB. For an SVG, `python3 scripts/rough.py in.svg out.svg [--amount 1.0]` breaks straight lines, rects, polygons, circles and paths, moves repeated marks off their even spacing, and shakes letters a little while keeping small text calm. It is a start, not a style: the method and the design still have to carry the look.
|
||||
Typing coordinates by hand gives clean marks. Generate the method's marks with a short script instead of writing them one by one. Stop at the number of marks the eye needs: a poster built from thousands of tiny pieces is slow to make and heavy to open, so keep an SVG under about 200 KB. For an SVG, `python3 scripts/rough.py in.svg out.svg [--amount 1.0]` breaks straight lines, rects, polygons, circles and paths, moves repeated marks off their even spacing, and shakes letters a little while keeping small text calm. Use it only for methods made by hand, such as print, paint, cut paper, stamps, chalk and ink. It is a start, not a style: the method and the design still have to carry the look.
|
||||
|
||||
Before showing any SVG, run `python3 scripts/check.py file.svg`. It renders the image at full size and at icon size, and lists text that runs off an edge, is covered by a shape, has low contrast or is too small. Fix all of it, run it again, then open both renders and look at them yourself. It does not see letters drawn as paths or text that spills out of its own box, so check those by eye. For other formats, render the image and do the same checks by eye.
|
||||
|
||||
@@ -98,8 +114,8 @@ Give one recommendation and the reason for it. Do not hide behind a long neutral
|
||||
This skill makes its own habits. An escape that worked once turns into the new safe pick if you use it again. Watch for these and do not reach for them by reflex:
|
||||
|
||||
- An old, analog or printed look chosen because it reads as "not AI", not because the subject asks for it.
|
||||
- The same small palette, the same paper, the same texture from one piece to the next.
|
||||
- Made-up names that all come from one stock: sea and tide words, old trades, rope and salt, small English towns. Take names from the seed's setting and the people who would live there.
|
||||
- The same small palette, the same paper, the same texture, the same wobbly line from one piece to the next.
|
||||
- Made-up names that all come from one stock: sea and tide words, old trades, rope and salt, small English towns. Take names from the way the people who live there name things, not from a list of objects found in the place.
|
||||
- A cream, beige or off-white ground. Take the ground from the subject: its night, its wall, its water, its screen.
|
||||
- Exact times, dates and numbers used only to look concrete.
|
||||
- A clever frame borrowed from another domain, such as a table, a map, a form or a schedule, laid over the subject.
|
||||
@@ -116,7 +132,7 @@ Ask three questions about your answer:
|
||||
2. Is this what most people would make first? If yes, move it.
|
||||
3. Can I say why this choice fits here, in one sentence, using a fact about this project? If not, the choice has no reason.
|
||||
|
||||
Write all text in the work in the language the user wrote in. The seed's setting may shape the look and the names of people and places, but dates, times, lineups, buttons, labels and all other words stay in the user's language.
|
||||
Write all text in the work in the language the user wrote in, unless the user's standing rules name another language for that kind of text, such as one fixed language for code, project names, game names or a store page. Those rules win. The seed's setting and region may shape the look and the names of people and places, but dates, times, lineups, buttons, labels and all other words stay in the language chosen this way.
|
||||
|
||||
Keep the length and format the user gave. If they asked for four sentences, write four. Do not add notes, options or extra parts they did not ask for.
|
||||
|
||||
|
||||
+31
-7
@@ -99,13 +99,36 @@ def main():
|
||||
|
||||
parent = {c: p for p in root.iter() for c in p}
|
||||
|
||||
def has_filter(el):
|
||||
return "filter" in el.attrib or "filter" in el.get("style", "")
|
||||
|
||||
def filtered(el):
|
||||
while el is not None:
|
||||
if "filter" in el.attrib or "filter" in el.get("style", ""):
|
||||
if has_filter(el):
|
||||
return True
|
||||
el = parent.get(el)
|
||||
return False
|
||||
|
||||
def ancestor_filtered(el):
|
||||
return filtered(parent.get(el))
|
||||
|
||||
own_filter = [has_filter(t) for t in texts(root)]
|
||||
plain = None
|
||||
if any(own_filter):
|
||||
nf = copy.deepcopy(tree)
|
||||
for t in texts(nf.getroot()):
|
||||
t.attrib.pop("filter", None)
|
||||
st = t.get("style", "")
|
||||
if "filter" in st:
|
||||
t.set("style", re.sub(r"filter\s*:[^;]*;?", "", st))
|
||||
nf_svg = os.path.join(out, "_nofilter.svg")
|
||||
nf_png = os.path.join(out, "_nofilter.png")
|
||||
write(nf, nf_svg)
|
||||
render(nf_svg, nf_png, args.width)
|
||||
plain = np.asarray(Image.open(nf_png).convert("RGB"), dtype=np.float32)
|
||||
os.remove(nf_svg)
|
||||
os.remove(nf_png)
|
||||
|
||||
problems = []
|
||||
tmp = tempfile.mkdtemp()
|
||||
n = len(texts(root))
|
||||
@@ -155,10 +178,10 @@ def main():
|
||||
sides.append("bottom")
|
||||
if sides:
|
||||
problems.append(f"text '{name}': runs off the {'/'.join(sides)} edge")
|
||||
height_px = (ys.max() - ys.min() + 1) / scale
|
||||
lines = max(1, len(texts(root)[i].findall(f"{{{SVG_NS}}}tspan")))
|
||||
if height_px / lines < 7 and not sides:
|
||||
problems.append(f"text '{name}': very small, about {height_px / lines:.0f} units tall")
|
||||
share = (ys.max() - ys.min() + 1) / scale / lines / max(w, h)
|
||||
if share < 0.012 and not sides:
|
||||
problems.append(f"text '{name}': very small, about {share * 100:.1f}% of the image side (want 1.2%+)")
|
||||
|
||||
rgba = np.asarray(Image.open(pp).convert("RGBA"), dtype=np.float32)
|
||||
inner = rgba[p:p + ch, p:p + cw]
|
||||
@@ -169,7 +192,8 @@ def main():
|
||||
continue
|
||||
own = np.zeros_like(full)
|
||||
own[:ih, :iw] = inner[:ih, :iw, :3]
|
||||
cover = np.abs(full - own).mean(axis=2)[mask].mean()
|
||||
base = plain if own_filter[i] and plain is not None else full
|
||||
cover = (np.abs(base - own).mean(axis=2)[mask] > 60).mean()
|
||||
ring = np.zeros_like(mask)
|
||||
r = max(2, int(3 * scale))
|
||||
for dy in (-r, 0, r):
|
||||
@@ -178,8 +202,8 @@ def main():
|
||||
ring &= ~mask
|
||||
lum = lambda c: c @ np.array([0.2126, 0.7152, 0.0722], dtype=np.float32)
|
||||
contrast = abs(lum(full[mask]).mean() - lum(full[ring]).mean()) if ring.any() else 255
|
||||
if cover > 60 and not filtered(texts(root)[i]):
|
||||
problems.append(f"text '{name}': covered or changed by something drawn over it")
|
||||
if cover > 0.04 and not ancestor_filtered(texts(root)[i]):
|
||||
problems.append(f"text '{name}': {cover * 100:.0f}% covered or changed by something drawn over it")
|
||||
elif contrast < 30:
|
||||
problems.append(f"text '{name}': low contrast with what is behind it ({contrast:.0f}, want 30+)")
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
+214
-80
@@ -36,12 +36,101 @@ def fmt(x):
|
||||
return f"{x:.2f}".rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
def pt(p):
|
||||
return f"{fmt(p[0])},{fmt(p[1])}"
|
||||
|
||||
|
||||
def lerp(a, b, t):
|
||||
return (a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t)
|
||||
|
||||
|
||||
def split_cubic(p0, c1, c2, p1):
|
||||
a, b, c = lerp(p0, c1, 0.5), lerp(c1, c2, 0.5), lerp(c2, p1, 0.5)
|
||||
d, e = lerp(a, b, 0.5), lerp(b, c, 0.5)
|
||||
m = lerp(d, e, 0.5)
|
||||
return (p0, a, d, m), (m, e, c, p1)
|
||||
|
||||
|
||||
def parse_path(d):
|
||||
toks = TOK.findall(d)
|
||||
segs = []
|
||||
cmd = None
|
||||
cur = start = (0.0, 0.0)
|
||||
last_c = last_q = None
|
||||
i = 0
|
||||
while i < len(toks):
|
||||
if toks[i].isalpha():
|
||||
cmd = toks[i]
|
||||
i += 1
|
||||
if cmd in "Zz":
|
||||
segs.append(("Z",))
|
||||
cur = start
|
||||
last_c = last_q = None
|
||||
continue
|
||||
if cmd is None or cmd in "Zz":
|
||||
i += 1
|
||||
continue
|
||||
c = cmd.lower()
|
||||
n = ARGS[c]
|
||||
chunk = toks[i:i + n]
|
||||
if len(chunk) < n or any(t.isalpha() for t in chunk):
|
||||
break
|
||||
a = [float(t) for t in chunk]
|
||||
i += n
|
||||
ox, oy = cur if cmd.islower() else (0.0, 0.0)
|
||||
new_c = new_q = None
|
||||
if c == "m":
|
||||
p = (a[0] + ox, a[1] + oy)
|
||||
segs.append(("M", p))
|
||||
start = p
|
||||
cmd = "l" if cmd.islower() else "L"
|
||||
elif c == "l":
|
||||
p = (a[0] + ox, a[1] + oy)
|
||||
segs.append(("L", p))
|
||||
elif c == "h":
|
||||
p = (a[0] + ox, cur[1])
|
||||
segs.append(("L", p))
|
||||
elif c == "v":
|
||||
p = (cur[0], a[0] + oy)
|
||||
segs.append(("L", p))
|
||||
elif c in "cs":
|
||||
if c == "c":
|
||||
c1 = (a[0] + ox, a[1] + oy)
|
||||
rest = a[2:]
|
||||
else:
|
||||
c1 = (2 * cur[0] - last_c[0], 2 * cur[1] - last_c[1]) if last_c else cur
|
||||
rest = a
|
||||
c2 = (rest[0] + ox, rest[1] + oy)
|
||||
p = (rest[2] + ox, rest[3] + oy)
|
||||
segs.append(("C", c1, c2, p))
|
||||
new_c = c2
|
||||
elif c in "qt":
|
||||
if c == "q":
|
||||
q1 = (a[0] + ox, a[1] + oy)
|
||||
p = (a[2] + ox, a[3] + oy)
|
||||
else:
|
||||
q1 = (2 * cur[0] - last_q[0], 2 * cur[1] - last_q[1]) if last_q else cur
|
||||
p = (a[0] + ox, a[1] + oy)
|
||||
c1 = lerp(cur, q1, 2 / 3)
|
||||
c2 = lerp(p, q1, 2 / 3)
|
||||
segs.append(("C", c1, c2, p))
|
||||
new_q = q1
|
||||
else:
|
||||
p = (a[5] + ox, a[6] + oy)
|
||||
segs.append(("A", a[0], a[1], a[2], int(a[3]), int(a[4]), p))
|
||||
cur = p
|
||||
last_c, last_q = new_c, new_q
|
||||
return segs
|
||||
|
||||
|
||||
class Rougher:
|
||||
def __init__(self, amp, rng, filter_id, box):
|
||||
def __init__(self, amp, rng, root, box):
|
||||
self.amp = amp
|
||||
self.rng = rng
|
||||
self.filter_id = filter_id
|
||||
self.root = root
|
||||
self.box = box
|
||||
self.free = True
|
||||
self.filter_id = None
|
||||
|
||||
def j(self, scale=1.0):
|
||||
return self.rng.gauss(0, self.amp * scale)
|
||||
@@ -49,33 +138,37 @@ class Rougher:
|
||||
def jx(self, x, scale):
|
||||
x0, _, w, _ = self.box
|
||||
d = self.j(scale)
|
||||
if x <= x0 + 1:
|
||||
if self.free and x <= x0 + 1:
|
||||
return x - abs(d) - 1
|
||||
if x >= x0 + w - 1:
|
||||
if self.free and x >= x0 + w - 1:
|
||||
return x + abs(d) + 1
|
||||
return x + d
|
||||
|
||||
def jy(self, y, scale):
|
||||
_, y0, _, h = self.box
|
||||
d = self.j(scale)
|
||||
if y <= y0 + 1:
|
||||
if self.free and y <= y0 + 1:
|
||||
return y - abs(d) - 1
|
||||
if y >= y0 + h - 1:
|
||||
if self.free and y >= y0 + h - 1:
|
||||
return y + abs(d) + 1
|
||||
return y + d
|
||||
|
||||
def jp(self, p, scale=0.6):
|
||||
return (self.jx(p[0], scale), self.jy(p[1], scale))
|
||||
|
||||
def steps(self, a, b):
|
||||
return max(1, int(math.hypot(b[0] - a[0], b[1] - a[1]) / (self.amp * 18 + 1e-6)))
|
||||
|
||||
def wobble(self, pts, closed):
|
||||
out = []
|
||||
seq = pts + ([pts[0]] if closed else [])
|
||||
for (x0, y0), (x1, y1) in zip(seq, seq[1:]):
|
||||
n = max(1, int(math.hypot(x1 - x0, y1 - y0) / (self.amp * 18 + 1e-6)))
|
||||
for a, b in zip(seq, seq[1:]):
|
||||
n = self.steps(a, b)
|
||||
for k in range(n):
|
||||
t = k / n
|
||||
out.append((self.jx(x0 + (x1 - x0) * t, 0.6), self.jy(y0 + (y1 - y0) * t, 0.6)))
|
||||
out.append(self.jp(lerp(a, b, k / n)))
|
||||
if not closed:
|
||||
ex, ey = seq[-1]
|
||||
out.append((self.jx(ex, 0.6), self.jy(ey, 0.6)))
|
||||
d = "M" + " L".join(f"{fmt(x)},{fmt(y)}" for x, y in out)
|
||||
out.append(self.jp(seq[-1]))
|
||||
d = "M" + " L".join(pt(p) for p in out)
|
||||
return d + ("Z" if closed else "")
|
||||
|
||||
def to_path(self, el, d):
|
||||
@@ -128,57 +221,106 @@ class Rougher:
|
||||
a = math.tau * k / n
|
||||
r = 1 + 0.5 * self.j(1 / max(rx, ry)) + 0.015 * math.sin(3 * a + drift)
|
||||
pts.append((cx + rx * r * math.cos(a), cy + ry * r * math.sin(a)))
|
||||
d = "M" + " L".join(f"{fmt(x)},{fmt(y)}" for x, y in pts) + "Z"
|
||||
d = "M" + " L".join(pt(p) for p in pts) + "Z"
|
||||
small = max(rx, ry) < self.amp * 6
|
||||
self.to_path(el, d)
|
||||
if small:
|
||||
self.shift(el)
|
||||
|
||||
def straight(self, out, a, b):
|
||||
n = self.steps(a, b)
|
||||
for k in range(1, n):
|
||||
out.append("L" + pt(self.jp(lerp(a, b, k / n))))
|
||||
|
||||
def curve(self, out, seg, ja, jb, depth=0):
|
||||
p0, c1, c2, p1 = seg
|
||||
if depth < 3 and math.hypot(p1[0] - p0[0], p1[1] - p0[1]) > self.amp * 30:
|
||||
left, right = split_cubic(*seg)
|
||||
jm = self.jp(left[3])
|
||||
self.curve(out, left, ja, jm, depth + 1)
|
||||
self.curve(out, right, jm, jb, depth + 1)
|
||||
return
|
||||
da = (ja[0] - p0[0], ja[1] - p0[1])
|
||||
db = (jb[0] - p1[0], jb[1] - p1[1])
|
||||
k1 = (c1[0] + da[0] + self.j(0.35), c1[1] + da[1] + self.j(0.35))
|
||||
k2 = (c2[0] + db[0] + self.j(0.35), c2[1] + db[1] + self.j(0.35))
|
||||
out.append(f"C{pt(k1)} {pt(k2)} {pt(jb)}")
|
||||
|
||||
def path(self, el):
|
||||
toks = TOK.findall(el.get("d", ""))
|
||||
out, cmd, i, argi = [], None, 0, 0
|
||||
while i < len(toks):
|
||||
t = toks[i]
|
||||
if t.isalpha():
|
||||
cmd, argi = t, 0
|
||||
out.append(t)
|
||||
i += 1
|
||||
continue
|
||||
v = float(t)
|
||||
if cmd is None:
|
||||
out.append(t)
|
||||
segs = parse_path(el.get("d", ""))
|
||||
if not segs or segs[0][0] != "M":
|
||||
return
|
||||
out = []
|
||||
cur = start = (0.0, 0.0)
|
||||
jcur = jstart = cur
|
||||
for s in segs:
|
||||
kind = s[0]
|
||||
if kind == "M":
|
||||
cur = start = s[1]
|
||||
jcur = jstart = self.jp(cur)
|
||||
out.append("M" + pt(jcur))
|
||||
elif kind == "L":
|
||||
self.straight(out, cur, s[1])
|
||||
cur, jcur = s[1], self.jp(s[1])
|
||||
out.append("L" + pt(jcur))
|
||||
elif kind == "C":
|
||||
jend = self.jp(s[3])
|
||||
self.curve(out, (cur, s[1], s[2], s[3]), jcur, jend)
|
||||
cur, jcur = s[3], jend
|
||||
elif kind == "A":
|
||||
_, rx, ry, rot, large, sweep, p = s
|
||||
jcur = self.jp(p)
|
||||
out.append(f"A{fmt(rx)} {fmt(ry)} {fmt(rot)} {large} {sweep} {pt(jcur)}")
|
||||
cur = p
|
||||
else:
|
||||
c = cmd.lower()
|
||||
n = ARGS.get(c, 2) or 1
|
||||
pos = argi % n
|
||||
rel = cmd.islower()
|
||||
if c == "a" and pos < 5:
|
||||
out.append(t)
|
||||
elif rel:
|
||||
out.append(fmt(v + self.j(0.35)))
|
||||
elif c == "h" or (c != "v" and (pos % 2 == 0 if c != "a" else pos == 5)):
|
||||
out.append(fmt(self.jx(v, 0.6)))
|
||||
else:
|
||||
out.append(fmt(self.jy(v, 0.6)))
|
||||
argi += 1
|
||||
i += 1
|
||||
self.straight(out, cur, start)
|
||||
out.append("Z")
|
||||
cur, jcur = start, jstart
|
||||
el.set("d", " ".join(out))
|
||||
|
||||
def text(self, el, size):
|
||||
chars = "".join(el.itertext())
|
||||
if not chars or list(el):
|
||||
return
|
||||
k = 0.25 if size < 16 else (0.6 if size < 32 else 1.0)
|
||||
def ensure_filter(self):
|
||||
if self.filter_id:
|
||||
return self.filter_id
|
||||
used = {e.get("id") for e in self.root.iter() if e.get("id")}
|
||||
fid, k = "rough-edge", 2
|
||||
while fid in used:
|
||||
fid, k = f"rough-edge-{k}", k + 1
|
||||
defs = next((c for c in self.root if tag(c) == "defs"), None)
|
||||
if defs is None:
|
||||
defs = ET.Element(f"{{{SVG_NS}}}defs")
|
||||
self.root.insert(0, defs)
|
||||
f = ET.SubElement(defs, f"{{{SVG_NS}}}filter", {"id": fid, "x": "-5%", "y": "-5%", "width": "110%", "height": "110%"})
|
||||
ET.SubElement(f, f"{{{SVG_NS}}}feTurbulence", {"type": "fractalNoise", "baseFrequency": "0.9", "numOctaves": "2", "seed": str(self.rng.randint(1, 9999)), "result": "n"})
|
||||
ET.SubElement(f, f"{{{SVG_NS}}}feDisplacementMap", {"in": "SourceGraphic", "in2": "n", "scale": fmt(self.amp * 2.2), "xChannelSelector": "R", "yChannelSelector": "G"})
|
||||
self.filter_id = fid
|
||||
return fid
|
||||
|
||||
def shake(self, el, chars, k):
|
||||
n = len(chars)
|
||||
rot = [fmt(self.rng.gauss(0, 2.2 * k)) for _ in range(n)]
|
||||
offs = [self.rng.gauss(0, self.amp * 0.5 * k) for _ in range(n)]
|
||||
dys = [offs[0]] + [offs[i] - offs[i - 1] for i in range(1, n)]
|
||||
if not n:
|
||||
return
|
||||
if not el.get("rotate"):
|
||||
el.set("rotate", " ".join(rot))
|
||||
if not el.get("dy"):
|
||||
el.set("dy", " ".join(fmt(d) for d in dys))
|
||||
if size >= 28 and not el.get("filter"):
|
||||
el.set("filter", f"url(#{self.filter_id})")
|
||||
el.set("rotate", " ".join(fmt(self.rng.gauss(0, 2.2 * k)) for _ in range(n)))
|
||||
own = el.get("dy", "")
|
||||
if len(NUM.findall(own)) > 1:
|
||||
return
|
||||
offs = [self.rng.gauss(0, self.amp * 0.5 * k) for _ in range(n)]
|
||||
dys = [offs[0] + fnum(own)] + [offs[i] - offs[i - 1] for i in range(1, n)]
|
||||
el.set("dy", " ".join(fmt(d) for d in dys))
|
||||
|
||||
def text(self, el, size):
|
||||
k = 0.25 if size < 16 else (0.6 if size < 32 else 1.0)
|
||||
kids = list(el)
|
||||
if not kids:
|
||||
self.shake(el, el.text or "", k)
|
||||
else:
|
||||
for t in el.iter():
|
||||
if t is not el and tag(t) == "tspan" and not list(t):
|
||||
ts = style_get(t, "font-size")
|
||||
tsize = fnum(ts, size) if ts else size
|
||||
self.shake(t, t.text or "", 0.25 if tsize < 16 else (0.6 if tsize < 32 else 1.0))
|
||||
if size >= 28 and not el.get("filter") and "".join(el.itertext()).strip():
|
||||
el.set("filter", f"url(#{self.ensure_filter()})")
|
||||
|
||||
def walk(self, el, size):
|
||||
fs = style_get(el, "font-size")
|
||||
@@ -188,33 +330,27 @@ class Rougher:
|
||||
t = tag(child)
|
||||
if t in SKIP:
|
||||
continue
|
||||
was = self.free
|
||||
if child.get("transform"):
|
||||
self.free = False
|
||||
if t == "text":
|
||||
cs = style_get(child, "font-size")
|
||||
self.text(child, fnum(cs, size) if cs else size)
|
||||
continue
|
||||
if t == "line":
|
||||
self.line(child)
|
||||
elif t == "rect":
|
||||
self.rect(child)
|
||||
elif t == "polyline":
|
||||
self.poly(child, False)
|
||||
elif t == "polygon":
|
||||
self.poly(child, True)
|
||||
elif t in ("circle", "ellipse"):
|
||||
self.ellipse(child)
|
||||
elif t == "path":
|
||||
self.path(child)
|
||||
self.walk(child, size)
|
||||
|
||||
|
||||
def add_filter(root, fid, amp, seed):
|
||||
defs = next((c for c in root if tag(c) == "defs"), None)
|
||||
if defs is None:
|
||||
defs = ET.Element(f"{{{SVG_NS}}}defs")
|
||||
root.insert(0, defs)
|
||||
f = ET.SubElement(defs, f"{{{SVG_NS}}}filter", {"id": fid, "x": "-5%", "y": "-5%", "width": "110%", "height": "110%"})
|
||||
ET.SubElement(f, f"{{{SVG_NS}}}feTurbulence", {"type": "fractalNoise", "baseFrequency": "0.9", "numOctaves": "2", "seed": str(seed), "result": "n"})
|
||||
ET.SubElement(f, f"{{{SVG_NS}}}feDisplacementMap", {"in": "SourceGraphic", "in2": "n", "scale": fmt(amp * 2.2), "xChannelSelector": "R", "yChannelSelector": "G"})
|
||||
else:
|
||||
if t == "line":
|
||||
self.line(child)
|
||||
elif t == "rect":
|
||||
self.rect(child)
|
||||
elif t == "polyline":
|
||||
self.poly(child, False)
|
||||
elif t == "polygon":
|
||||
self.poly(child, True)
|
||||
elif t in ("circle", "ellipse"):
|
||||
self.ellipse(child)
|
||||
elif t == "path":
|
||||
self.path(child)
|
||||
self.walk(child, size)
|
||||
self.free = was
|
||||
|
||||
|
||||
def main():
|
||||
@@ -231,9 +367,7 @@ def main():
|
||||
box = vb if len(vb) == 4 else [0.0, 0.0, fnum(root.get("width"), 600), fnum(root.get("height"), 600)]
|
||||
w, h = box[2], box[3]
|
||||
amp = args.amount * math.hypot(w, h) / 720 * 1.4
|
||||
fid = "rough-edge"
|
||||
add_filter(root, fid, amp, rng.randint(1, 9999))
|
||||
Rougher(amp, rng, fid, box).walk(root, 16.0)
|
||||
Rougher(amp, rng, root, box).walk(root, 16.0)
|
||||
tree.write(args.dst, encoding="unicode", xml_declaration=False)
|
||||
print(f"wrote {args.dst} (amp {amp:.2f})")
|
||||
|
||||
|
||||
+110
-34
@@ -1,25 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import random
|
||||
import sys
|
||||
|
||||
rng = random.SystemRandom()
|
||||
|
||||
VISUAL = {
|
||||
"method": [
|
||||
"woodcut", "linocut", "screen print", "letterpress", "rubber stamp", "spray stencil",
|
||||
"cut paper collage", "torn magazine collage", "photocopy zine", "gouache", "watercolor wash",
|
||||
"ink brush", "ballpoint sketch", "marker on cardboard", "chalk on a blackboard", "oil pastel",
|
||||
"embroidery", "cross stitch", "knitting chart", "mosaic tiles", "stained glass", "neon tubes",
|
||||
"hand painted shop sign", "enamel sign", "glazed ceramic", "tape on a wall", "LED dot matrix",
|
||||
"old CRT screen", "thermal receipt printer", "airbrush", "clay model photo", "glossy 3D render",
|
||||
"chrome and glass render", "holographic foil", "flash film photo", "long exposure photo",
|
||||
"infrared photo", "x-ray image", "thermal camera image", "satellite image", "microscope image",
|
||||
"blueprint", "technical pen drawing", "map engraving", "banknote engraving", "vinyl sticker",
|
||||
"felt shapes", "sticky notes on glass", "strict Swiss grid typography", "brutalist web page",
|
||||
"acid rave flyer", "Y2K chrome", "halftone newspaper photo", "children's crayon drawing",
|
||||
"pencil on graph paper", "spray paint graffiti", "light painting", "shadow puppets",
|
||||
"folded paper", "string and pins", "wet ink on tissue", "carved wood relief", "chalk on pavement",
|
||||
METHOD_FAMILIES = {
|
||||
"hand and print": [
|
||||
"woodcut", "screen print", "rubber stamp", "spray stencil", "cut paper collage",
|
||||
"photocopy zine", "gouache", "ink brush", "ballpoint sketch", "marker on cardboard",
|
||||
"embroidery", "hand painted shop sign", "children's crayon drawing", "spray paint graffiti",
|
||||
"chalk on pavement",
|
||||
],
|
||||
"screen and machine": [
|
||||
"LED dot matrix", "old CRT screen", "thermal receipt printer", "brutalist web page",
|
||||
"early 3D video game", "phone screenshot", "spreadsheet chart", "vector icon set",
|
||||
"glitched video frame", "airport departure board", "arcade cabinet art", "e-ink display",
|
||||
"low poly render", "CAD wireframe", "pixel font on a car dashboard",
|
||||
],
|
||||
"camera and science": [
|
||||
"flash film photo", "long exposure photo", "infrared photo", "x-ray image",
|
||||
"thermal camera image", "satellite image", "microscope image", "security camera still",
|
||||
"night vision footage", "macro photo", "drone photo from straight above", "sonar scan",
|
||||
"weather radar map", "motion blur photo", "underwater photo",
|
||||
],
|
||||
"material and light": [
|
||||
"neon tubes", "stained glass", "mosaic tiles", "glazed ceramic", "glossy 3D render",
|
||||
"chrome and glass render", "holographic foil", "clay model photo", "inflatable plastic",
|
||||
"folded paper", "string and pins", "carved wood relief", "light painting",
|
||||
"shadow puppets", "frosted acrylic with backlight",
|
||||
],
|
||||
}
|
||||
|
||||
VISUAL = {
|
||||
"color": [
|
||||
"one ink only", "black and white with one accent", "two colors that clash",
|
||||
"colors taken from the subject's material", "full color with one hue in charge",
|
||||
@@ -46,20 +59,44 @@ VISUAL = {
|
||||
TEXT = {
|
||||
"voice": [
|
||||
"a witness in first person", "instructions in second person", "a plain list",
|
||||
"a short letter", "overheard dialogue", "a public notice", "numbered steps",
|
||||
"one long sentence", "short fragments", "question and answer", "a log with entries",
|
||||
"a note left for someone", "a review by someone tired", "a label on a box",
|
||||
"a short letter", "overheard dialogue", "one long sentence", "short fragments",
|
||||
"question and answer", "a note left for someone", "a review by someone tired",
|
||||
"a child explaining it", "someone who disagrees", "a voice from the future looking back",
|
||||
"a rumor passed on",
|
||||
],
|
||||
"entry": [
|
||||
"a sound", "a smell", "a single object", "a number that matters", "a mistake",
|
||||
"a rule", "a place", "an hour of the day", "the ending", "a body feeling",
|
||||
"a thing that is missing", "a price", "a complaint", "a habit",
|
||||
"a sound", "a smell", "a single object", "a mistake", "a rule", "a place",
|
||||
"the ending", "a body feeling", "a thing that is missing", "a complaint", "a habit",
|
||||
"a misunderstanding", "a gesture", "a question nobody answers",
|
||||
],
|
||||
"register": [
|
||||
"plain", "formal", "dry", "warm", "blunt", "playful", "terse", "careful", "nervous", "proud",
|
||||
],
|
||||
}
|
||||
|
||||
IDEA = {
|
||||
"verb": [
|
||||
"trade", "hide", "build", "repair", "sort", "follow", "trap", "grow", "deliver", "swap",
|
||||
"borrow", "steal", "listen", "stack", "balance", "burn", "wash", "guess", "herd", "queue",
|
||||
"bargain", "cook", "dig", "signal", "wait", "measure", "lose", "rescue", "copy", "share",
|
||||
],
|
||||
"constraint": [
|
||||
"only one try", "it gets worse when you wait", "you cannot see it directly",
|
||||
"someone else controls half of it", "all of it is borrowed and must go back",
|
||||
"it only works in one place", "two rules that fight", "the tool wears out with use",
|
||||
"the crowd decides", "you are too small for it", "nobody speaks the same language",
|
||||
"the reward is also the cost", "it must be done in silence", "it happens to many at once",
|
||||
],
|
||||
"scale": [
|
||||
"one person", "a family", "a street", "a whole town", "a crowd of strangers",
|
||||
"a machine", "an animal", "a single room", "two rivals", "a team that does not get along",
|
||||
],
|
||||
"pressure": [
|
||||
"a deadline", "a rival", "a debt", "weather", "a rule that changes", "noise", "hunger",
|
||||
"a promise", "a rumor", "running out of space", "a guest who will not leave", "fatigue",
|
||||
],
|
||||
}
|
||||
|
||||
ANCHOR = [
|
||||
"ladder", "bicycle", "glove", "mirror", "bread", "magnet", "compass", "hinge", "fog", "bee",
|
||||
"copper", "thread", "lamp", "drum", "sponge", "scissors", "ice", "cactus", "radio", "bridge",
|
||||
@@ -78,24 +115,61 @@ SETTING = [
|
||||
"a desert town at noon", "a mountain village above the clouds", "a rooftop in a huge city",
|
||||
"a parking lot after closing", "a tropical market in the rain", "a frozen lake", "a rice terrace",
|
||||
"a highway service station", "a night bus", "a dense housing block courtyard", "a jungle river",
|
||||
"a shopping mall basement", "a steppe under a big sky", "a ferry crossing a wide river",
|
||||
"an industrial suburb", "a cable car station", "a salt flat", "a volcanic island",
|
||||
"a pine forest in snow", "a stadium after the match", "a subway platform", "a hot spring town",
|
||||
"an orchard in bloom", "a border crossing", "a fishing harbor in the tropics", "a canyon",
|
||||
"a university dorm", "a wind farm", "a crowded old bazaar", "a new town still being built",
|
||||
"a riverside at dusk in a hot country", "a ski lift", "a tea plantation", "an airport at 3am",
|
||||
"a car wash", "a hilltop monastery", "a laundromat", "a container port", "a savanna road",
|
||||
"a glass office tower", "a village wedding tent", "a lighthouse on a cold coast",
|
||||
"a shopping mall basement", "a steppe under a big sky", "an industrial suburb",
|
||||
"a cable car station", "a salt flat", "a volcanic island", "a pine forest in snow",
|
||||
"a stadium after the match", "a subway platform", "a hot spring town", "an orchard in bloom",
|
||||
"a border crossing", "a canyon", "a university dorm", "a wind farm", "a crowded old bazaar",
|
||||
"a new town still being built", "a ski lift", "a tea plantation", "an airport at night",
|
||||
"a car wash", "a hilltop monastery", "a laundromat", "a savanna road", "a glass office tower",
|
||||
"a village wedding tent", "a server room", "a hospital corridor", "a school gym",
|
||||
"a gas station in the mountains", "a food court", "a construction crane cab",
|
||||
]
|
||||
|
||||
KINDS = {"visual": VISUAL, "text": TEXT}
|
||||
REGION = [
|
||||
"Georgia (the country)", "northern Chile", "Kerala", "Hokkaido", "the Scottish Highlands",
|
||||
"Anatolia", "Sicily", "Ghana", "Mongolia", "Quebec", "Java", "the Faroe Islands", "Oaxaca",
|
||||
"Morocco", "Finnish Lapland", "the Philippines", "Patagonia", "Kenya", "Vietnam", "Iceland",
|
||||
"Bavaria", "Poland", "Sri Lanka", "the Andes of Peru", "Portugal", "Nigeria", "Korea",
|
||||
"Brazil's northeast", "Ukraine", "Ethiopia", "Wales", "Nepal", "Senegal", "Sardinia",
|
||||
"Kazakhstan", "the Basque Country", "Tasmania", "Cuba", "Bangladesh", "the American Midwest",
|
||||
"Iran", "Croatia", "Colombia", "Taiwan", "Egypt", "Norway", "Bolivia", "Uzbekistan",
|
||||
]
|
||||
NO_ANCHOR = [
|
||||
"no single object, build it from a pattern of the place",
|
||||
"no single object, only type",
|
||||
"no single object, a crowd of people",
|
||||
"no single object, numbers or data from the subject",
|
||||
"no single object, a field of light or color",
|
||||
"no single object, the surface of the place up close",
|
||||
]
|
||||
|
||||
|
||||
def method():
|
||||
family = rng.choice(list(METHOD_FAMILIES))
|
||||
return rng.choice(METHOD_FAMILIES[family])
|
||||
|
||||
|
||||
def pools(kind):
|
||||
if kind == "visual":
|
||||
return {"method": None, **VISUAL}
|
||||
if kind == "text":
|
||||
return dict(TEXT)
|
||||
return dict(IDEA)
|
||||
|
||||
|
||||
def roll(kind):
|
||||
pools = dict(KINDS[kind]) if kind in KINDS else {**VISUAL, **TEXT}
|
||||
out = {name: rng.choice(items) for name, items in pools.items()}
|
||||
out = {}
|
||||
for name, items in pools(kind).items():
|
||||
out[name] = method() if items is None else rng.choice(items)
|
||||
if kind == "visual":
|
||||
out["verb"] = rng.choice(IDEA["verb"])
|
||||
out["scale"] = rng.choice(IDEA["scale"])
|
||||
out["setting"] = rng.choice(SETTING)
|
||||
out["anchor"] = rng.choice(ANCHOR)
|
||||
out["region"] = rng.choice(REGION)
|
||||
if kind == "visual" and rng.random() < 0.5:
|
||||
out["anchor"] = rng.choice(NO_ANCHOR)
|
||||
else:
|
||||
out["anchor"] = rng.choice(ANCHOR)
|
||||
return out
|
||||
|
||||
|
||||
@@ -106,7 +180,9 @@ def main():
|
||||
args = ap.parse_args()
|
||||
seed = roll(args.kind)
|
||||
if args.only:
|
||||
seed = {args.only: seed.get(args.only, rng.choice(ANCHOR))}
|
||||
if args.only not in seed:
|
||||
sys.exit(f"no axis '{args.only}' for {args.kind}; axes: {', '.join(seed)}")
|
||||
seed = {args.only: seed[args.only]}
|
||||
for k, v in seed.items():
|
||||
print(f"{k}: {v}")
|
||||
|
||||
|
||||
Reference in new issue
Block a user