A mech game prototype, pushed by Gemini 4 Carbon
agent
+1:48reasoning
Initial suspicion focuses on specific code files related to outlines, blocks, views, rendering, and various "kit" components. These files appear central to the system's core functionality, spanning multiple languages and domains. These are now marked as high priority to read closely.
read_file{"Path":"~/work/sortie/src/view/clip.ts"}
input
{ "Path": "~/work/sortie/src/view/clip.ts" }result, 140 lines
Showing lines 1-139 of 139 1: import * as THREE from 'three'; 2: import { model, type ModelName } from '../render/assets'; 3: import { STRIKER_DECALS, applyDecals } from '../render/decals'; 4: import { treatEyes } from '../render/eyes'; 5: import type { ThrustReading } from '../render/exhaust'; 6: import { setLook, look } from '../render/look'; 7: import { MechRig, POSES } from '../render/mech'; 8: import type { PaletteName } from '../render/palette'; 9: import { Pipeline } from '../render/pipeline'; 10: import { addSpaceLight, createBackdrop, followSun, spaceEnvironment } from '../render/space'; 11: import { BEND_POSE, SHOT_NAMES, clipFrames, mixPose, shotView, type ShotName } from './clip-plan'; 12: import { CameraRig } from './cameras'; 13: import { benchInput } from './thrusters'; 14: 15: /** 16: * A review clip of one model, rendered frame by frame so it comes out the same on any machine. Driven by 17: * tools/clip.mjs, which calls window.__clip.render(i) and pipes the frames into ffmpeg. 18: * /?view=clip&model=block_dummy&shots=chase,turn&fps=24&palette=merc&look=kit 19: * Any model with the 22 joint rig. Lab lineups hold many frames under slots, so they don't rig. 20: */ 21: export async function startClip(canvas: HTMLCanvasElement, q: URLSearchParams) { 22: setLook(q.get('look')); 23: await document.fonts.ready; 24: const w = Number(q.get('w') ?? 854), h = Number(q.get('h') ?? 480), fps = Number(q.get('fps') ?? 24); 25: const shots = (q.get('shots')?.split(',') ?? SHOT_NAMES) as ShotName[]; 26: const frames = clipFrames(shots, fps); 27: 28: const scene = new THREE.Scene(); 29: const camera = new THREE.PerspectiveCamera(35, w / h, 0.3, 2e5); 30: const backdrop = createBackdrop(); 31: const pipe = new Pipeline(canvas, scene, camera, backdrop); 32: pipe.resize(w, h); 33: const sun = addSpaceLight(scene); 34: scene.environment = spaceEnvironment(pipe.renderer, backdrop); 35: scene.environmentIntensity = 0.8 * look().fill; 36: 37: const name = (q.get('model') ?? 'striker') as ModelName; 38: const palette = (q.get('palette') ?? 'merc') as PaletteName; 39: const root = await model(name, palette); 40: if (name === 'striker') applyDecals(root, STRIKER_DECALS); 41: treatEyes(root, 'spill'); 42: scene.add(root); 43: const rig = new MechRig(root); 44: root.updateMatrixWorld(true); 45: rig.apply(POSES.stand); 46: root.updateMatrixWorld(true); 47: const box = new THREE.Box3().setFromObject(root); 48: const height = box.getSize(new THREE.Vector3()).y; 49: const footY = box.min.y; 50: const size = height / 17.6; 51: 52: const light = new THREE.PointLight('#ffffff', 0, 0, 2); 53: scene.add(light); 54: 55: // the pilot and deck for the scale shot: a person is the one thing everyone knows the size of 56: const ground = new THREE.Group(); 57: const deck = new THREE.Mesh(new THREE.CircleGeometry(height * 2, 48), new THREE.MeshStandardMaterial({ color: '#2a2f36', roughness: 0.85, metalness: 0.2 })); 58: deck.rotation.x = -Math.PI / 2; 59: deck.position.y = footY; 60: ground.add(deck); 61: const pilot = await model('lab_pilot' as ModelName, palette); 62: pilot.traverse((o) => { if (/^slot\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; }); 63: // lab slot 0 stands at x = -.55: bring the pilot beside the frame's foot, facing the camera 64: pilot.position.set(0.55 + height * 0.3, footY, height * 0.16); 65: pilot.rotation.y = 0.4; 66: ground.add(pilot); 67: scene.add(ground); 68: 69: // the game's chase camera, read for its numbers: this view moves its own camera 70: const chase = new CameraRig(); 71: const reading: ThrustReading = { x: 0, y: 0, z: 0, boosting: false }; 72: const centre = new THREE.Vector3(); 73: const offset = new THREE.Vector3(); 74: const look_ = new THREE.Vector3(); 75: const up = new THREE.Vector3(0, 1, 0); 76: const yawQ = new THREE.Quaternion(); 77: const DT = 1 / 120; 78: let clock = 0; 79: 80: const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => { 81: const f = benchInput(state, t); 82: reading.x = f.thrust.x; 83: reading.y = f.thrust.y; 84: reading.z = f.thrust.z; 85: reading.boosting = f.boosting; 86: reading.assault = f.assault; 87: reading.quick = f.quick; 88: rig.thrust(reading, clock, dt); 89: rig.lightExhaust(light); 90: }; 91: 92: const render = (i: number) => { 93: const f = frames[i]; 94: const v = shotView(f); 95: // thrusters step at 120 Hz whatever the clip's frame rate, as a game would 96: const dt = f.cut ? 0 : 1 / fps; 97: if (f.cut) for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); } 98: for (let s = 0; s < dt - 1e-9; s += DT) { 99: clock += DT; 100: feed(f.state, Math.max(0, f.stateT - dt + s), DT); 101: } 102: if (dt === 0) feed(f.state, f.stateT, 0); 103: 104: root.rotation.y = THREE.MathUtils.degToRad(v.mechYaw); 105: rig.apply(v.bend > 0 ? mixPose(POSES.stand, BEND_POSE, v.bend) : POSES[v.pose]); 106: root.updateMatrixWorld(true); 107: ground.visible = v.ground; 108: centre.set(0, footY + height * v.lookAt, 0); 109: const fov = v.chase ? chase.camera.fov : 35; 110: if (camera.fov !== fov) { 111: camera.fov = fov; 112: camera.updateProjectionMatrix(); 113: } 114: if (v.chase) { 115: // where the game's chase camera sits (src/view/cameras.ts), over the shoulder, scaled to the frame 116: yawQ.setFromAxisAngle(up, THREE.MathUtils.degToRad(v.camYaw)); 117: offset.set(chase.shoulder * size, chase.chaseOffset.y * size, chase.chaseOffset.z * size).applyQuaternion(yawQ); 118: camera.position.copy(centre).add(offset); 119: look_.set(chase.shoulder * size, (chase.chaseOffset.y - chase.lookDrop) * size, 400).applyQuaternion(yawQ).add(centre); 120: camera.up.copy(up); 121: camera.lookAt(look_); 122: } else { 123: const yaw = THREE.MathUtils.degToRad(v.camYaw), pitch = THREE.MathUtils.degToRad(v.pitch); 124: camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(v.dist * height).add(centre); 125: if (v.ground) camera.position.y = Math.max(camera.position.y, footY + 1.6); // eye height, above the deck 126: camera.up.copy(up); 127: camera.lookAt(centre); 128: } 129: camera.updateMatrixWorld(true); 130: followSun(sun, centre); 131: pipe.render(); 132: // read straight after the draw, in the same task, while the buffer still holds it 133: return canvas.toDataURL('image/jpeg', 0.93); 134: }; 135: 136: const win = window as unknown as { __clip: unknown; __ready: boolean }; 137: win.__clip = { frames: frames.length, fps, render }; 138: win.__ready = true; 139: }read_file{"Path":"~/work/sortie/src/view/clip-plan.ts"}
input
{ "Path": "~/work/sortie/src/view/clip-plan.ts" }result, 105 lines
Showing lines 1-104 of 104 1: import type { Pose } from '../render/mech'; 2: import type { BenchState } from './thrusters'; 3: 4: /** 5: * The timeline of a review clip (src/view/clip.ts), as a pure function of frame number, so a clip is the 6: * same every run whatever the machine's speed. Shots frame the model and nothing here is a design choice: 7: * the chase shot sits where the game's camera sits, the rest show it from all round, bending and to scale. 8: */ 9: export const SHOTS = { chase: 3.5, orbit: 3, turn: 4, bend: 3, scale: 2.5 } as const; 10: export type ShotName = keyof typeof SHOTS; 11: export const SHOT_NAMES = Object.keys(SHOTS) as ShotName[]; 12: 13: /** Thruster states through a shot: [start second, state]. */ 14: const SCHEDULE: Partial<Record<ShotName, [number, BenchState][]>> = { 15: chase: [[0, 'cruise'], [1, 'boost'], [2.4, 'quick'], [3, 'cruise']], 16: orbit: [[0, 'boost'], [1.4, 'brake'], [2.2, 'idle']], 17: }; 18: 19: export interface ClipFrame { 20: shot: ShotName; 21: /** Seconds into the shot, and the same as a 0..1 fraction. */ 22: t: number; 23: u: number; 24: state: BenchState; 25: /** Seconds since this thruster state began. */ 26: stateT: number; 27: /** First frame of a shot: everything snaps. */ 28: cut: boolean; 29: } 30: 31: export function clipFrames(shots: readonly ShotName[], fps: number): ClipFrame[] { 32: const out: ClipFrame[] = []; 33: for (const shot of shots) { 34: const n = Math.max(1, Math.round(SHOTS[shot] * fps)); 35: const plan = SCHEDULE[shot] ?? [[0, 'idle'] as [number, BenchState]]; 36: for (let i = 0; i < n; i++) { 37: const t = i / fps; 38: let at = plan[0]; 39: for (const p of plan) if (p[0] <= t + 1e-9) at = p; 40: out.push({ shot, t, u: n > 1 ? i / (n - 1) : 0, state: at[1], stateT: t - at[0], cut: i === 0 }); 41: } 42: } 43: return out; 44: } 45: 46: /** Where things are in a shot. Lengths are in frame heights, angles in degrees. Yaw 0 looks at the 47: * frame's front, 180 at its back. `chase` means the game's chase camera, turned by mechYaw. */ 48: export interface ShotView { 49: chase: boolean; 50: mechYaw: number; 51: camYaw: number; 52: pitch: number; 53: dist: number; 54: /** Look point height as a fraction of the frame's height. */ 55: lookAt: number; 56: pose: 'flight' | 'stand'; 57: /** How far toward BEND_POSE, 0..1. */ 58: bend: number; 59: /** The pilot and the deck are in shot. */ 60: ground: boolean; 61: } 62: 63: const ease = (x: number) => x * x * (3 - 2 * x); 64: 65: export function shotView(f: ClipFrame): ShotView { 66: const base = { chase: false, mechYaw: 0, camYaw: 0, pitch: 8, dist: 2.4, lookAt: 0.5, pose: 'stand', bend: 0, ground: false } as ShotView; 67: switch (f.shot) { 68: case 'chase': { 69: // a gentle turn and back: the camera trails the frame, so the stars pan and the frame leans in shot 70: const turn = Math.sin(f.u * Math.PI * 2) * 22; 71: return { ...base, chase: true, mechYaw: turn, camYaw: turn * 0.75, pose: 'flight' }; 72: } 73: case 'orbit': 74: return { ...base, camYaw: 165 - 75 * ease(f.u), pitch: 12, dist: 2.2, pose: 'flight' }; 75: case 'turn': 76: return { ...base, camYaw: 180 + 360 * f.u }; 77: case 'bend': 78: return { ...base, camYaw: 35, pitch: 6, bend: Math.sin(f.u * Math.PI) ** 2 }; 79: case 'scale': 80: // from the deck beside the pilot, looking up at the frame, pushing in slowly 81: return { ...base, camYaw: 28, pitch: -6 + 2 * f.u, dist: 2.25 - 0.15 * ease(f.u), lookAt: 0.42, ground: true }; 82: } 83: } 84: 85: /** A deliberately large range of motion, to find plates that collide or joints that show. Glances at 86: * every limb: one arm up and forward, the other out, one knee high, a twist. */ 87: export const BEND_POSE: Pose = { 88: torso: [12, 18, 0], head: [-8, -24, 0], 89: 'upperarm.L': [-115, 0, 22], 'forearm.L': [-80, 0, 0], 90: 'upperarm.R': [-20, 0, -72], 'forearm.R': [-100, 0, 0], 91: 'thigh.L': [-85, 0, 10], 'shin.L': [100, 0, 0], 'foot.L': [-22, 0, 0], 92: 'thigh.R': [-8, 0, -14], 'shin.R': [22, 0, 0], 'foot.R': [8, 0, 0], 93: 'binder.L': [-20, 0, 0], 'binder.R': [20, 0, 0], 94: }; 95: 96: /** A blend of two poses, joint by joint. */ 97: export function mixPose(a: Pose, b: Pose, w: number): Pose { 98: const out: Pose = {}; 99: for (const j of new Set([...Object.keys(a), ...Object.keys(b)]) as Set<keyof Pose>) { 100: const p = a[j] ?? [0, 0, 0], q = b[j] ?? [0, 0, 0]; 101: out[j] = [p[0] + (q[0] - p[0]) * w, p[1] + (q[1] - p[1]) * w, p[2] + (q[2] - p[2]) * w]; 102: } 103: return out; 104: }read_file{"Path":"~/work/sortie/src/render/look.ts"}
input
{ "Path": "~/work/sortie/src/render/look.ts" }result, 214 lines
Showing lines 1-213 of 213 1: import * as THREE from 'three'; 2: 3: // The rendering style: how much edge wear, recess grime, ink lining, paint variation and film grain. 4: // Two candidates under review: a weathered "field" machine and a clean "kit" (a painted model kit). 5: 6: export interface Look { 7: name: 'field' | 'kit' | 'service' | 'sketch'; 8: /** Convex edges lightened (worn paint catching light), 0..1. */ 9: ridge: number; 10: /** Recesses and seams darkened (grime), 0..1. */ 11: valley: number; 12: /** Dark lining at creases, seams and silhouettes, 0..1. */ 13: ink: number; 14: /** Paint variation across surfaces (albedo and roughness noise), 0..1. */ 15: grime: number; 16: /** Film grain and vignette strength, 0..1. */ 17: grain: number; 18: vignette: number; 19: /** Paint finish: roughness for armour paint and whether it has a clear coat. */ 20: paintRough: number; 21: gloss: boolean; 22: /** Edges chip to bare metal in a broken pattern (field) instead of a clean highlight (kit). */ 23: chipped: boolean; 24: /** How far paint colours are pulled toward grey (weathered field paint). */ 25: desaturate: number; 26: /** Soft fill from the environment, as a multiplier: low for hard field light, high for a studio look. */ 27: fill: number; 28: /** Cel-banded lighting, pencil hatching in shadow, and a paper tone (the sketch look). */ 29: toon?: boolean; 30: hatch?: number; 31: paper?: number; 32: } 33: 34: export const LOOKS: Record<Look['name'], Look> = { 35: field: { name: 'field', ridge: 0.85, valley: 0.7, ink: 0.15, grime: 1, grain: 0.045, vignette: 0.35, paintRough: 0.66, gloss: false, 36: chipped: true, desaturate: 0.28, fill: 0.5 }, 37: kit: { name: 'kit', ridge: 0.22, valley: 0.2, ink: 0.95, grime: 0, grain: 0, vignette: 0.12, paintRough: 0.32, gloss: true, 38: chipped: false, desaturate: 0, fill: 1.15 }, 39: // between field and kit: kit's lining at two-thirds, field's wear at a lighter touch, semi-matte 40: service: { name: 'service', ridge: 0.5, valley: 0.45, ink: 0.6, grime: 0.5, grain: 0.025, vignette: 0.25, paintRough: 0.48, gloss: false, 41: chipped: true, desaturate: 0.12, fill: 0.85 }, 42: sketch: { name: 'sketch', ridge: 0.1, valley: 0.25, ink: 1, grime: 0, grain: 0.02, vignette: 0.2, paintRough: 0.55, gloss: false, 43: chipped: false, desaturate: 0.12, fill: 0.85, toon: true, hatch: 1, paper: 1 }, 44: }; 45: 46: let current: Look = LOOKS.field; 47: export const look = () => current; 48: export function setLook(name: string | null) { 49: current = LOOKS[(name as Look['name']) ?? 'field'] ?? LOOKS.field; 50: return current; 51: } 52: 53: /** Screen-space surface detail from the normal/depth pre-pass: [redacted: secret] wear, grime, ink. */ 54: export const DetailShader = { 55: uniforms: { 56: tDiffuse: { value: null }, 57: tNormal: { value: null }, 58: tDepth: { value: null }, 59: px: { value: new THREE.Vector2(1, 1) }, 60: near: { value: 0.5 }, 61: far: { value: 60000 }, 62: ridgeK: { value: 0.5 }, 63: valleyK: { value: 0.5 }, 64: inkK: { value: 0.2 }, 65: chipped: { value: 0 }, 66: hatch: { value: 0 }, 67: projInv: { value: new THREE.Matrix4() }, 68: viewInv: { value: new THREE.Matrix4() }, 69: }, 70: vertexShader: 'varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }', 71: fragmentShader: /* glsl */ ` 72: #include <packing> 73: uniform sampler2D tDiffuse, tNormal, tDepth; 74: uniform vec2 px; 75: uniform float near, far, ridgeK, valleyK, inkK, chipped, hatch; 76: uniform mat4 projInv, viewInv; 77: varying vec2 vUv; 78: float hash3(vec3 p) { return fract(sin(dot(p, vec3(7.1, 157.3, 113.7))) * 43758.5); } 79: float vnoise(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f); 80: return mix(mix(mix(hash3(i), hash3(i + vec3(1,0,0)), f.x), mix(hash3(i + vec3(0,1,0)), hash3(i + vec3(1,1,0)), f.x), f.y), 81: mix(mix(hash3(i + vec3(0,0,1)), hash3(i + vec3(1,0,1)), f.x), mix(hash3(i + vec3(0,1,1)), hash3(i + vec3(1,1,1)), f.x), f.y), f.z); } 82: vec3 worldAt(vec2 uv) { 83: float d = texture2D(tDepth, uv).x; 84: vec4 v = projInv * vec4(uv * 2.0 - 1.0, d * 2.0 - 1.0, 1.0); 85: return (viewInv * vec4(v.xyz / v.w, 1.0)).xyz; 86: } 87: vec4 N(vec2 uv) { vec4 n = texture2D(tNormal, uv); return vec4(n.xyz * 2.0 - 1.0, n.a); } 88: float Z(vec2 uv) { return -perspectiveDepthToViewZ(texture2D(tDepth, uv).x, near, far); } 89: void main() { 90: vec4 c = texture2D(tDiffuse, vUv); 91: vec4 n0 = N(vUv); 92: if (n0.a < 0.5) { gl_FragColor = c; return; } 93: vec4 l = N(vUv - vec2(px.x, 0.0)), r = N(vUv + vec2(px.x, 0.0)), d = N(vUv - vec2(0.0, px.y)), u = N(vUv + vec2(0.0, px.y)); 94: float z0 = Z(vUv); 95: // convex where neighbouring normals spread apart, concave where they close in 96: float curv = ((r.x - l.x) * r.a * l.a + (u.y - d.y) * u.a * d.a) * 0.5; 97: float ridge = smoothstep(0.08, 0.45, curv); 98: float valley = smoothstep(0.08, 0.45, -curv); 99: // ink at creases and wherever depth steps (seams, overlaps, silhouettes) 100: float turn = max(max(1.0 - dot(n0.xyz, l.xyz), 1.0 - dot(n0.xyz, r.xyz)), max(1.0 - dot(n0.xyz, u.xyz), 1.0 - dot(n0.xyz, d.xyz))); 101: float zs = max(max(abs(Z(vUv - vec2(px.x, 0.0)) - z0), abs(Z(vUv + vec2(px.x, 0.0)) - z0)), 102: max(abs(Z(vUv - vec2(0.0, px.y)) - z0), abs(Z(vUv + vec2(0.0, px.y)) - z0))); 103: float edge = max(smoothstep(0.35, 0.7, turn), smoothstep(0.015, 0.04, zs / z0)); 104: edge = max(edge, 1.0 - min(min(l.a, r.a), min(u.a, d.a))); 105: // detail fades with distance so far-off ships don't turn to noise 106: float near_ = 1.0 - smoothstep(60.0, 600.0, z0); 107: vec3 col = c.rgb; 108: // grime settles in recesses: darker and a little brown 109: col = mix(col, col * vec3(0.55, 0.5, 0.45), valley * valleyK * near_); 110: if (chipped > 0.5) { 111: // chipped paint on convex edges shows the metal beneath, in a broken pattern fixed to the surface 112: vec3 wp = worldAt(vUv); 113: float n = vnoise(wp * 3.1) * 0.65 + vnoise(wp * 11.0) * 0.35; 114: float chip = ridge * smoothstep(0.42, 0.62, n) * ridgeK * near_; 115: col = mix(col, vec3(0.32, 0.33, 0.35) * (0.6 + 0.8 * vnoise(wp * 23.0)), chip); 116: } else { 117: col += (vec3(1.0) - col) * ridge * ridgeK * 0.45 * near_ * clamp(dot(col, vec3(0.33)) * 2.0, 0.3, 1.0); 118: } 119: if (hatch > 0.0) { 120: // pencil hatching in shadow: one direction in half shade, crossed in deep shade 121: float lum = dot(col, vec3(0.3, 0.59, 0.11)); 122: vec2 fc = gl_FragCoord.xy; 123: float h1 = step(0.55, fract((fc.x + fc.y) / 6.0)); 124: float h2 = step(0.55, fract((fc.x - fc.y) / 6.0)); 125: float shade1 = 1.0 - smoothstep(0.18, 0.32, lum), shade2 = 1.0 - smoothstep(0.08, 0.18, lum); 126: col *= 1.0 - hatch * 0.35 * (h1 * shade1 + h2 * shade2); 127: } 128: col = mix(col, col * 0.18, edge * inkK * mix(0.4, 1.0, near_)); 129: gl_FragColor = vec4(col, c.a); 130: }`, 131: }; 132: 133: /** After tone mapping: vignette and fine grain. */ 134: export const GradeShader = { 135: uniforms: { tDiffuse: { value: null }, grain: { value: 0 }, vignette: { value: 0 }, time: { value: 0 }, paper: { value: 0 } }, 136: vertexShader: 'varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }', 137: fragmentShader: /* glsl */ ` 138: uniform sampler2D tDiffuse; uniform float grain, vignette, time, paper; varying vec2 vUv; 139: float h(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233)) + time) * 43758.5453); } 140: void main() { 141: vec4 c = texture2D(tDiffuse, vUv); 142: vec2 q = vUv - 0.5; 143: c.rgb *= 1.0 - vignette * smoothstep(0.25, 0.85, dot(q, q) * 2.2); 144: c.rgb += (h(vUv * 1000.0) - 0.5) * grain; 145: if (paper > 0.0) { 146: // a warm paper tone and its fibre, multiplied under the picture 147: float fib = fract(sin(dot(floor(gl_FragCoord.xy / 2.0), vec2(12.9898, 78.233))) * 43758.5453); 148: vec3 tone = vec3(1.0, 0.97, 0.9) * (0.94 + 0.06 * fib); 149: c.rgb = mix(c.rgb, c.rgb * tone + vec3(0.03, 0.025, 0.015), paper); 150: } 151: gl_FragColor = c; 152: }`, 153: }; 154: 155: /** World-space paint variation: blotches in albedo and roughness so large panels aren't uniform. */ 156: export function addPaintVariation(m: THREE.MeshStandardMaterial, amount: number) { 157: if (amount <= 0) return; 158: const prev = m.onBeforeCompile; 159: m.onBeforeCompile = (shader, r) => { 160: prev?.call(m, shader, r); 161: shader.vertexShader = shader.vertexShader 162: .replace('#include <common>', '#include <common>\nvarying vec3 vPaintPos;') 163: .replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvPaintPos = (modelMatrix * vec4(transformed, 1.0)).xyz;'); 164: shader.fragmentShader = shader.fragmentShader 165: .replace('#include <common>', `#include <common> 166: varying vec3 vPaintPos; 167: float pn(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f); 168: float a = fract(sin(dot(i, vec3(7.1, 157.3, 113.7))) * 43758.5); 169: float b = fract(sin(dot(i + vec3(1,0,0), vec3(7.1, 157.3, 113.7))) * 43758.5); 170: float c2 = fract(sin(dot(i + vec3(0,1,0), vec3(7.1, 157.3, 113.7))) * 43758.5); 171: float d = fract(sin(dot(i + vec3(1,1,0), vec3(7.1, 157.3, 113.7))) * 43758.5); 172: float e = fract(sin(dot(i + vec3(0,0,1), vec3(7.1, 157.3, 113.7))) * 43758.5); 173: float f2 = fract(sin(dot(i + vec3(1,0,1), vec3(7.1, 157.3, 113.7))) * 43758.5); 174: float g = fract(sin(dot(i + vec3(0,1,1), vec3(7.1, 157.3, 113.7))) * 43758.5); 175: float hh = fract(sin(dot(i + vec3(1,1,1), vec3(7.1, 157.3, 113.7))) * 43758.5); 176: return mix(mix(mix(a, b, f.x), mix(c2, d, f.x), f.y), mix(mix(e, f2, f.x), mix(g, hh, f.x), f.y), f.z); } 177: #ifdef PAINT_LITE 178: float paintN(vec3 p) { return pn(p * 0.7); } 179: #else 180: float paintN(vec3 p) { return pn(p * 0.7) * 0.5 + pn(p * 2.3) * 0.3 + pn(p * 9.0) * 0.2; } 181: #endif`) 182: .replace('#include <color_fragment>', `#include <color_fragment> 183: float pv = paintN(vPaintPos); 184: // blotches, plus dirt streaks running down the surfaces (the low tier keeps the broad blotches only) 185: #ifdef PAINT_LITE 186: float streak = 0.0; 187: #else 188: float streak = pn(vec3(vPaintPos.x * 3.0, vPaintPos.y * 0.25, vPaintPos.z * 3.0)); 189: #endif 190: diffuseColor.rgb *= 1.0 - ${(0.14 * amount).toFixed(3)} * smoothstep(0.3, 0.8, pv) - ${(0.1 * amount).toFixed(3)} * smoothstep(0.55, 0.9, streak);`) 191: .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment> 192: roughnessFactor = clamp(roughnessFactor + ${(0.12 * amount).toFixed(3)} * (paintN(vPaintPos * 1.7) - 0.5), 0.05, 1.0);`); 193: }; 194: const key = m.customProgramCacheKey?.bind(m); 195: m.customProgramCacheKey = () => `${key ? key() : ''}paint${amount}`; 196: painted.add(m); 197: setLite(m, paintLite); 198: } 199: 200: /** Paint variation's fine noise is dear per pixel on a weak GPU: the low tier keeps one octave. */ 201: const painted = new Set<THREE.Material>(); 202: let paintLite = false; 203: function setLite(m: THREE.Material, on: boolean) { 204: m.defines ??= {}; 205: if (on === 'PAINT_LITE' in m.defines) return; 206: if (on) m.defines.PAINT_LITE = ''; 207: else delete m.defines.PAINT_LITE; 208: m.needsUpdate = true; 209: } 210: export function setPaintLite(on: boolean) { 211: paintLite = on; 212: for (const m of painted) setLite(m, on); 213: }read_file{"Path":"~/work/sortie/src/render/materials.ts"}
input
{ "Path": "~/work/sortie/src/render/materials.ts" }result, 131 lines
Showing lines 1-130 of 130 1: import * as THREE from 'three'; 2: import type { Palette, Role } from './palette'; 3: import { addPaintVariation, look } from './look'; 4: 5: /** Painted armour roles: their finish follows the look (matte field paint or gloss kit paint). */ 6: const PAINT = new Set<Role>(['main', 'accent', 'trim', 'hull', 'suit', 'donor_a', 'donor_b', 'donor_c', 'primer', 'handpaint', 7: 'warpaint']); 8: /** Unpainted roles: no wear, grime or ink lines from the detail pass (alien crystal). */ 9: export const BARE = new Set<Role>(['crystal', 'crystal_lit']); 10: 11: // Physically based materials by role: painted armour, bare and dark metal, glass, and unlit glows 12: // that feed the bloom. 13: 14: /** Diagonal hazard stripes from world position, so no UVs are needed. */ 15: function addStripes(m: THREE.MeshStandardMaterial) { 16: m.onBeforeCompile = (shader) => { 17: shader.vertexShader = shader.vertexShader 18: .replace('#include <common>', '#include <common>\nvarying vec3 vStripePos;') 19: .replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvStripePos = (modelMatrix * vec4(transformed, 1.0)).xyz;'); 20: shader.fragmentShader = shader.fragmentShader 21: .replace('#include <common>', '#include <common>\nvarying vec3 vStripePos;') 22: .replace( 23: '#include <color_fragment>', 24: `#include <color_fragment> 25: float stripe = step(0.5, fract((vStripePos.x + vStripePos.y + vStripePos.z) * 0.6)); 26: diffuseColor.rgb = mix(vec3(0.03, 0.03, 0.035), diffuseColor.rgb, stripe);`, 27: ); 28: }; 29: m.customProgramCacheKey = () => 'stripes'; 30: } 31: 32: const cache = new Map<string, THREE.Material>(); 33: 34: let bands: THREE.DataTexture | null = null; 35: /** Three lighting bands for the sketch look: shade, half-tone, lit. */ 36: function toonBands() { 37: if (bands) return bands; 38: const d = new Uint8Array([60, 60, 60, 140, 255, 255]); 39: bands = new THREE.DataTexture(d, d.length, 1, THREE.RedFormat); 40: bands.minFilter = bands.magFilter = THREE.NearestFilter; 41: bands.needsUpdate = true; 42: return bands; 43: } 44: 45: export function material(palette: Palette, role: Role, key: string): THREE.Material { 46: const l = look(); 47: const id = `${key}:${role}:${l.name}`; 48: const hit = cache.get(id); 49: if (hit) return hit; 50: const p = palette[role] ?? { color: '#ff00ff' }; 51: let m: THREE.Material; 52: if (p.glow) { 53: m = new THREE.MeshBasicMaterial({ color: new THREE.Color(p.color).multiplyScalar(p.glow) }); 54: } else { 55: // A floor on roughness: a near-mirror catching the sun makes a highlight brighter than the 56: // half-float buffers can hold, and the bloom smears that across the whole screen. 57: const painted = PAINT.has(role); 58: // a lacquered livery keeps its own finish under a matte look: its roughness at most, and a clear coat 59: const lacquer = painted ? p.lacquer ?? 0 : 0; 60: const paintRough = lacquer ? Math.min(l.paintRough, p.rough ?? l.paintRough) : l.paintRough; 61: const roughness = Math.max(0.2, painted ? paintRough : p.rough ?? 0.5); 62: const coat = painted ? Math.max(l.gloss ? 0.6 : 0, lacquer) : p.coat ?? 0; 63: const color = new THREE.Color(p.color); 64: if (painted && l.desaturate > 0) { 65: // weathered paint: pulled toward grey and warmed slightly, less so under lacquer 66: const grey = color.r * 0.3 + color.g * 0.59 + color.b * 0.11; 67: color.lerp(new THREE.Color(grey, grey, grey), l.desaturate * (1 - lacquer * 0.6)).multiply(new THREE.Color(1.0, 0.98, 0.94)); 68: } 69: if (l.toon) { 70: const t = new THREE.MeshToonMaterial({ color, gradientMap: toonBands() }); 71: t.name = role; 72: if (role === 'hazard') addStripes(t as unknown as THREE.MeshStandardMaterial); 73: cache.set(id, t); 74: return t; 75: } 76: const s = coat >= 0.5 77: ? new THREE.MeshPhysicalMaterial({ color, roughness, metalness: p.metal ?? 0, clearcoat: coat, clearcoatRoughness: 0.25 }) 78: : new THREE.MeshStandardMaterial({ color, roughness, metalness: p.metal ?? 0 }); 79: if (p.emit) s.emissive.copy(color).multiplyScalar(p.emit); 80: if (role === 'hazard') addStripes(s); 81: else if (painted || role === 'frame' || role === 'joint' || role === 'rust') addPaintVariation(s, l.grime * (painted ? 1 : 0.6)); 82: if (p.rust) addRust(s, p.rust); 83: m = s; 84: } 85: m.name = role; 86: cache.set(id, m); 87: return m; 88: } 89: 90: /** Rust from world position, so no UVs are needed: blotches that grow with `amount`, streaks running down 91: * from them, rougher and duller where the paint has gone. */ 92: function addRust(m: THREE.MeshStandardMaterial, amount: number) { 93: const prev = m.onBeforeCompile; 94: m.onBeforeCompile = (shader, r) => { 95: prev?.call(m, shader, r); 96: shader.vertexShader = shader.vertexShader 97: .replace('#include <common>', '#include <common>\nvarying vec3 vRustPos;') 98: .replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvRustPos = (modelMatrix * vec4(transformed, 1.0)).xyz;'); 99: shader.fragmentShader = shader.fragmentShader 100: .replace('#include <common>', `#include <common> 101: varying vec3 vRustPos; 102: float rn(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f); 103: vec3 k = vec3(12.9, 78.2, 37.7); 104: return mix(mix(mix(fract(sin(dot(i, k)) * 43758.5), fract(sin(dot(i + vec3(1,0,0), k)) * 43758.5), f.x), 105: mix(fract(sin(dot(i + vec3(0,1,0), k)) * 43758.5), fract(sin(dot(i + vec3(1,1,0), k)) * 43758.5), f.x), f.y), 106: mix(mix(fract(sin(dot(i + vec3(0,0,1), k)) * 43758.5), fract(sin(dot(i + vec3(1,0,1), k)) * 43758.5), f.x), 107: mix(fract(sin(dot(i + vec3(0,1,1), k)) * 43758.5), fract(sin(dot(i + vec3(1,1,1), k)) * 43758.5), f.x), f.y), f.z); } 108: float rustMask(vec3 p) { 109: // patches where paint has gone, fine-grained, and thin streaks running down from them 110: float blot = rn(p * 1.3) * 0.6 + rn(p * 4.7) * 0.4; 111: float t = 1.0 - ${(0.7 * amount).toFixed(3)}; 112: float streak = smoothstep(0.6, 0.82, rn(vec3(p.x * 9.0, p.y * 0.22, p.z * 9.0))) * smoothstep(t - 0.2, t, rn(p * 0.9)); 113: return clamp(smoothstep(t, t + 0.06, blot) + streak * 0.6, 0.0, 1.0); 114: }`) 115: .replace('#include <color_fragment>', `#include <color_fragment> 116: float rm = rustMask(vRustPos); 117: vec3 rc = mix(vec3(0.15, 0.065, 0.03), vec3(0.34, 0.14, 0.055), rn(vRustPos * 6.0)); 118: diffuseColor.rgb = mix(diffuseColor.rgb, rc, rm);`) 119: .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment> 120: roughnessFactor = mix(roughnessFactor, 0.92, rm);`) 121: .replace('#include <metalnessmap_fragment>', `#include <metalnessmap_fragment> 122: metalnessFactor = mix(metalnessFactor, 0.15, rm);`); 123: }; 124: const key = m.customProgramCacheKey?.bind(m); 125: m.customProgramCacheKey = () => `${key ? key() : ''}rust${amount}`; 126: } 127: 128: export function isRole(name: string): name is Role { 129: return /^[a-z_]+$/.test(name); 130: }read_file{"Path":"~/work/sortie/kit/lib.py"}
input
{ "Path": "~/work/sortie/kit/lib.py" }result, 438 lines
Showing lines 1-437 of 437 1: """Modelling helpers shared by every kit script. 2: 3: Blender units are metres, Z is up, and models face -Y (Blender's front view). The glTF exporter turns 4: that into three.js's Y up with models facing +Z. 5: 6: Parts are solids built from a few primitives: 7: loft cross-sections stacked along an axis (most armour, limbs, hulls) 8: prism a 2D outline pushed through a depth 9: two_view a front outline and a side outline intersected, the classic hard-surface blockout 10: Every solid gets a material role (main, accent, frame, glow_eye, ...). The game maps roles to toon 11: materials, so one model can wear any faction's paint. 12: """ 13: import math 14: 15: import bmesh 16: import bpy 17: from mathutils import Matrix, Vector 18: 19: # Preview colours only, for anyone opening a .blend. The game ignores them. 20: PREVIEW = { 21: "main": (0.86, 0.87, 0.9), "accent": (0.12, 0.3, 0.55), "trim": (0.85, 0.55, 0.12), 22: "frame": (0.2, 0.21, 0.24), "joint": (0.12, 0.12, 0.14), "visor": (0.05, 0.06, 0.08), 23: "glow_eye": (0.3, 1.0, 0.9), "glow_core": (0.3, 1.0, 0.9), "glow_thruster": (0.6, 0.78, 1.0), 24: "glow_exhaust": (0.31, 0.56, 1.0), 25: "metal": (0.55, 0.57, 0.6), "hull": (0.72, 0.73, 0.75), "hull_dark": (0.32, 0.33, 0.36), 26: "deck": (0.25, 0.26, 0.28), "hazard": (0.9, 0.75, 0.1), "light": (1.0, 0.97, 0.9), 27: "screen": (0.2, 0.8, 0.75), "glass": (0.1, 0.2, 0.25), "lamp_red": (1.0, 0.2, 0.15), 28: "lamp_green": (0.3, 1.0, 0.4), "suit": (0.14, 0.19, 0.36), "glow_hot": (0.92, 1.0, 0.98), 29: # raider salvage (palette.ts): donor paint, primer, rust, hand paint 30: "donor_a": (0.78, 0.76, 0.72), "donor_b": (0.24, 0.34, 0.43), "donor_c": (0.36, 0.38, 0.26), "primer": (0.54, 0.55, 0.52), 31: "rust": (0.42, 0.23, 0.13), "handpaint": (0.93, 0.89, 0.8), "warpaint": (0.76, 0.23, 0.15), 32: # markings: pattern codes, service text, unit codes (a decal layer in geometry) 33: "stencil": (0.13, 0.14, 0.16), 34: "crystal": (0.8, 0.81, 0.84), "crystal_lit": (0.55, 0.45, 0.78), "glow_violet": (0.66, 0.48, 1.0), 35: } 36: 37: 38: def reset(): 39: for o in list(bpy.data.objects): 40: bpy.data.objects.remove(o, do_unlink=True) 41: for coll in (bpy.data.meshes, bpy.data.materials): 42: for item in list(coll): 43: coll.remove(item) 44: 45: 46: def material(role): 47: m = bpy.data.materials.get(role) 48: if m is None: 49: m = bpy.data.materials.new(role) 50: c = PREVIEW.get(role, (0.7, 0.7, 0.7)) 51: m.diffuse_color = (*c, 1.0) 52: return m 53: 54: 55: def link(o): 56: bpy.context.scene.collection.objects.link(o) 57: return o 58: 59: 60: def empty(name, at=(0, 0, 0), parent=None, **extras): 61: """A joint or marker. Children keep their world placement when parented to it.""" 62: o = link(bpy.data.objects.new(name, None)) 63: o.empty_display_size = 0.4 64: o.location = Vector(at) if parent is None else parent.matrix_world.inverted() @ Vector(at) 65: if parent is not None: 66: o.parent = parent 67: for k, v in extras.items(): 68: o[k] = v 69: bpy.context.view_layer.update() 70: return o 71: 72: 73: def attach(o, parent): 74: """Parent without moving: geometry is authored in world (rest pose) coordinates.""" 75: bpy.context.view_layer.update() 76: mw = o.matrix_world.copy() 77: o.parent = parent 78: o.matrix_parent_inverse = parent.matrix_world.inverted() 79: o.matrix_world = mw 80: return o 81: 82: 83: # ---- 2D outlines ------------------------------------------------------------------------------------------ 84: def octo(w, d, c=0.2, cf=None, cb=None, x=0.0, y=0.0): 85: """A chamfered rectangle, w along X and d along Y, CCW seen from above. The front (-Y) and back 86: chamfers can differ: cf, cb. Returns 8 points.""" 87: cf = c if cf is None else cf 88: cb = c if cb is None else cb 89: hw, hd = w / 2, d / 2 90: cf, cb = min(cf, hw * 0.95, hd * 0.95), min(cb, hw * 0.95, hd * 0.95) 91: return [(x - hw + cf, y - hd), (x + hw - cf, y - hd), (x + hw, y - hd + cf), (x + hw, y + hd - cb), 92: (x + hw - cb, y + hd), (x - hw + cb, y + hd), (x - hw, y + hd - cb), (x - hw, y - hd + cf)] 93: 94: 95: def circle(r, n=12, x=0.0, y=0.0, phase=0.5): 96: return [(x + r * math.cos(2 * math.pi * (i + phase) / n), y + r * math.sin(2 * math.pi * (i + phase) / n)) 97: for i in range(n)] 98: 99: 100: def ccw(poly): 101: a = sum(poly[i][0] * poly[(i + 1) % len(poly)][1] - poly[(i + 1) % len(poly)][0] * poly[i][1] 102: for i in range(len(poly))) 103: return poly if a > 0 else list(reversed(poly)) 104: 105: 106: # ---- solids (bmesh) --------------------------------------------------------------------------------------- 107: def loft(rings, axis="z", caps=True): 108: """rings: [(height, [(u, v), ...]), ...], all with the same point count. With axis "z" the outline 109: is (x, y) at height z; "y" means (x, z) outlines along y; "x" means (y, z) outlines along x.""" 110: bm = bmesh.new() 111: loops = [] 112: for h, pts in rings: 113: loop = [] 114: for u, v in pts: 115: p = {"z": (u, v, h), "y": (u, h, v), "x": (h, u, v)}[axis] 116: loop.append(bm.verts.new(p)) 117: loops.append(loop) 118: n = len(loops[0]) 119: for a, b in zip(loops, loops[1:]): 120: for i in range(n): 121: j = (i + 1) % n 122: bm.faces.new((a[i], a[j], b[j], b[i])) 123: if caps: 124: bm.faces.new(list(reversed(loops[0]))) 125: bm.faces.new(loops[-1]) 126: _outward(bm) 127: return bm 128: 129: 130: def prism(poly, lo, hi, plane="xz"): 131: """A 2D outline pushed through [lo, hi]. plane "xz": outline in (x, z), depth along y. 132: "yz": (y, z) along x. "xy": (x, y) along z.""" 133: poly = ccw(poly) 134: axis = {"xz": "y", "yz": "x", "xy": "z"}[plane] 135: return loft([(lo, poly), (hi, poly)], axis=axis) 136: 137: 138: def _outward(bm): 139: bmesh.ops.recalc_face_normals(bm, faces=bm.faces) 140: 141: 142: def merge(*bms): 143: out = bmesh.new() 144: for b in bms: 145: me = bpy.data.meshes.new("_tmp") 146: b.to_mesh(me) 147: out.from_mesh(me) 148: bpy.data.meshes.remove(me) 149: b.free() 150: return out 151: 152: 153: def transform(bm, m): 154: bmesh.ops.transform(bm, matrix=m, verts=bm.verts) 155: return bm 156: 157: 158: def mirror_x(bm): 159: """A mirrored copy (left from right) with the winding fixed.""" 160: me = bpy.data.meshes.new("_m") 161: bm.to_mesh(me) 162: out = bmesh.new() 163: out.from_mesh(me) 164: bpy.data.meshes.remove(me) 165: bmesh.ops.scale(out, vec=(-1, 1, 1), verts=out.verts) 166: bmesh.ops.reverse_faces(out, faces=out.faces) 167: return out 168: 169: 170: def rot(axis, deg, about=(0, 0, 0)): 171: c = Vector(about) 172: return Matrix.Translation(c) @ Matrix.Rotation(math.radians(deg), 4, axis) @ Matrix.Translation(-c) 173: 174: 175: # ---- objects ---------------------------------------------------------------------------------------------- 176: def solid(name, bm, role, parent=None, bevel=0.0, segs=1, angle=40, smooth=False, outline=True, panels=None): 177: """Turn a bmesh into an object with a material role, an optional chamfer on edges sharper than 178: `angle`, flat or smooth shading, parented to a joint without moving. Armour roles get panel 179: seams on their large faces unless panels=False.""" 180: me = bpy.data.meshes.new(name) 181: bm.to_mesh(me) 182: bm.free() 183: me.materials.append(material(role)) 184: o = link(bpy.data.objects.new(name, me)) 185: if bevel > 0: 186: mod = o.modifiers.new("bevel", "BEVEL") 187: mod.width = bevel 188: mod.segments = segs 189: mod.limit_method = "ANGLE" 190: mod.angle_limit = math.radians(angle) 191: mod.use_clamp_overlap = True 192: mod.miter_outer = "MITER_ARC" 193: bake(o) 194: if panels is None: 195: panels = role in ("main", "accent", "hull") and not smooth 196: if panels: 197: panel_lines(o) 198: me = o.data 199: if smooth: 200: me.shade_smooth() 201: me.set_sharp_from_angle(angle=math.radians(35)) 202: if not outline: 203: o["outline"] = False 204: if parent is not None: 205: attach(o, parent) 206: return o 207: 208: 209: def panel_lines(o, min_area=1.1, width=0.05, depth=0.016): 210: """Recess every large face slightly inside a thin border: reads as panel seams on armour.""" 211: bm = bmesh.new() 212: bm.from_mesh(o.data) 213: faces = [f for f in bm.faces if f.calc_area() > min_area] 214: if faces: 215: bmesh.ops.inset_individual(bm, faces=faces, thickness=width, depth=-depth, use_even_offset=True) 216: bm.to_mesh(o.data) 217: bm.free() 218: return o 219: 220: 221: def bake(o): 222: dg = bpy.context.evaluated_depsgraph_get() 223: me = bpy.data.meshes.new_from_object(o.evaluated_get(dg)) 224: old = o.data 225: o.modifiers.clear() 226: o.data = me 227: me.name = old.name 228: bpy.data.meshes.remove(old) 229: return o 230: 231: 232: def boolean(target, cutter_bm, op="DIFFERENCE", role=None): 233: """Cut (or intersect/union) a solid object with a bmesh volume. With a role, the faces the cutter 234: leaves behind (the inside of a cavity) take that material.""" 235: me = bpy.data.meshes.new("_cut") 236: cutter_bm.to_mesh(me) 237: cutter_bm.free() 238: if role is not None: 239: me.materials.append(material(role)) 240: cutter = link(bpy.data.objects.new("_cut", me)) 241: bpy.context.view_layer.update() 242: cutter.matrix_world = target.matrix_world.copy() 243: mod = target.modifiers.new("bool", "BOOLEAN") 244: mod.operation = op 245: mod.object = cutter 246: mod.solver = "EXACT" 247: if role is not None: 248: mod.material_mode = "TRANSFER" 249: bake(target) 250: bpy.data.objects.remove(cutter, do_unlink=True) 251: bpy.data.meshes.remove(me) 252: return target 253: 254: 255: def two_view(front, side, top=None, span=60.0): 256: """Intersect a front outline (x, z) with a side outline (y, z), and optionally a top outline 257: (x, y). Returns a bmesh. The classic way to block out armour and heads.""" 258: a = prism(front, -span, span, "xz") 259: me = bpy.data.meshes.new("_tv") 260: a.to_mesh(me) 261: a.free() 262: o = link(bpy.data.objects.new("_tv", me)) 263: boolean(o, prism(side, -span, span, "yz"), "INTERSECT") 264: if top is not None: 265: boolean(o, prism(top, -span, span, "xy"), "INTERSECT") 266: bm = bmesh.new() 267: bm.from_mesh(o.data) 268: bpy.data.objects.remove(o, do_unlink=True) 269: return bm 270: 271: 272: def clip(bm, x=(-60, 60), y=(-60, 60), z=(-60, 60)): 273: """The part of a solid inside an axis-aligned box. Cutting one envelope into several boxes with 274: gaps between them gives separate shells over the same form.""" 275: me = bpy.data.meshes.new("_clip") 276: bm.to_mesh(me) 277: bm.free() 278: o = link(bpy.data.objects.new("_clip", me)) 279: cut = loft([(z[0], [(x[0], y[0]), (x[1], y[0]), (x[1], y[1]), (x[0], y[1])]), 280: (z[1], [(x[0], y[0]), (x[1], y[0]), (x[1], y[1]), (x[0], y[1])])]) 281: boolean(o, cut, "INTERSECT") 282: out = bmesh.new() 283: out.from_mesh(o.data) 284: data = o.data 285: bpy.data.objects.remove(o, do_unlink=True) 286: bpy.data.meshes.remove(data) 287: return out 288: 289: 290: def copy(bm): 291: me = bpy.data.meshes.new("_copy") 292: bm.to_mesh(me) 293: out = bmesh.new() 294: out.from_mesh(me) 295: bpy.data.meshes.remove(me) 296: return out 297: 298: 299: def _keep_side(bm, co, no, below): 300: """Keep the part of a solid below (or above) a plane and cap the opening.""" 301: geom = bm.verts[:] + bm.edges[:] + bm.faces[:] 302: res = bmesh.ops.bisect_plane(bm, geom=geom, plane_co=co, plane_no=no, clear_outer=below, clear_inner=not below) 303: edges = [e for e in res["geom_cut"] if isinstance(e, bmesh.types.BMEdge)] 304: if edges: 305: bmesh.ops.holes_fill(bm, edges=edges, sides=0) 306: bmesh.ops.recalc_face_normals(bm, faces=bm.faces) 307: return bm 308: 309: 310: def halves(bm, co, no, gap=.04): 311: """Split a solid along a plane into two capped pieces with a gap between them: a panel seam 312: with real depth, so the dark frame beneath shows through.""" 313: co, no = Vector(co), Vector(no).normalized() 314: a = _keep_side(copy(bm), co - no * gap / 2, no, below=True) 315: b = _keep_side(bm, co + no * gap / 2, no, below=False) 316: return a, b 317: 318: 319: def panels(bm, cuts, gap=.04): 320: """Cut a solid by several planes [(point, normal), ...] into panels with seams between them.""" 321: pieces = [bm] 322: for co, no in cuts: 323: out = [] 324: for p in pieces: 325: for h in halves(p, co, no, gap): 326: if len(h.faces) >= 4: 327: out.append(h) 328: else: 329: h.free() 330: pieces = out 331: return pieces 332: 333: 334: def fold(objs, t, half, y0, y1): 335: """Fold the front of a part into a shallow V: in front of y0 (fully in front of y1) every vertex 336: moves forward (-Y) by t * (half - |x|), so the centre line becomes a ridge and both sides angle 337: back. Meshes are cut on the centre line first so flat plates fold instead of tilting. Works on 338: mesh coordinates, which are the authored ones.""" 339: for ob in objs: 340: bm = bmesh.new() 341: bm.from_mesh(ob.data) 342: if bm.verts and min(v.co.y for v in bm.verts) < y0: 343: geom = bm.verts[:] + bm.edges[:] + bm.faces[:] 344: bmesh.ops.bisect_plane(bm, geom=geom, plane_co=(0, 0, 0), plane_no=(1, 0, 0)) 345: for v in bm.verts: 346: ax = abs(v.co.x) 347: if v.co.y < y0 and ax < half: 348: w = min(1.0, (y0 - v.co.y) / (y0 - y1)) 349: v.co.y -= t * (half - ax) * w * w * (3 - 2 * w) 350: bm.to_mesh(ob.data) 351: bm.free() 352: 353: 354: def piston(p0, p1, r=.12, n=8): 355: """A hydraulic piston from p0 to p1: a body over the first 60%, a thinner rod the rest, end eyes.""" 356: p0, p1 = Vector(p0), Vector(p1) 357: axis = p1 - p0 358: m = Matrix.Translation(p0) @ Vector((0, 0, 1)).rotation_difference(axis.normalized()).to_matrix().to_4x4() 359: L = axis.length 360: body = loft([(0, circle(r, n)), (L * .6, circle(r, n))]) 361: rod = loft([(L * .55, circle(r * .45, n)), (L, circle(r * .45, n))]) 362: eyes = merge(loft([(-r * .4, circle(r * .7, n)), (r * .4, circle(r * .7, n))]), 363: loft([(L - r * .4, circle(r * .6, n)), (L + r * .4, circle(r * .6, n))])) 364: return transform(merge(body, rod, eyes), m) 365: 366: 367: def subd(bm, levels=2, sharp=45, crease=1.0): 368: """Smooth a low-poly cage with Catmull-Clark subdivision. Edges whose faces meet at more than 369: `sharp` degrees are creased, so they stay crisp while everything else rounds off: helmets and 370: shells that are soft where they should be and hard where they shouldn't.""" 371: me = bpy.data.meshes.new("_subd") 372: bm.to_mesh(me) 373: bm.free() 374: attr = me.attributes.get("crease_edge") or me.attributes.new("crease_edge", "FLOAT", "EDGE") 375: probe = bmesh.new() 376: probe.from_mesh(me) 377: probe.edges.ensure_lookup_table() 378: lim = math.radians(sharp) 379: for e in probe.edges: 380: f = e.link_faces 381: if len(f) == 2 and f[0].normal.angle(f[1].normal, 0) > lim: 382: attr.data[e.index].value = crease 383: probe.free() 384: o = link(bpy.data.objects.new("_subd", me)) 385: mod = o.modifiers.new("subd", "SUBSURF") 386: mod.levels = mod.render_levels = levels 387: bake(o) 388: out = bmesh.new() 389: out.from_mesh(o.data) 390: data = o.data 391: bpy.data.objects.remove(o, do_unlink=True) 392: bpy.data.meshes.remove(data) 393: return out 394: 395: 396: def cylinder(r, z0, z1, n=10, r1=None, axis="z", at=(0, 0)): 397: """An n-sided cylinder (or cone with r1) between z0 and z1 along an axis, centred at `at` in the 398: other two coordinates.""" 399: r1 = r if r1 is None else r138 more lines not shown.