-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.ts
More file actions
595 lines (488 loc) · 23 KB
/
Copy pathtree.ts
File metadata and controls
595 lines (488 loc) · 23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
import { createCanvas, CanvasRenderingContext2D } from 'canvas';
import { spawn, type ChildProcessWithoutNullStreams } from 'child_process';
import { createHash, randomBytes } from 'crypto';
import * as fs from 'fs';
import { SeededRandom } from '../core/seeded-random';
import type { Color } from '../types/color';
import { DEFAULT_CONFIG, type Config } from '../types/config';
import type { Generate } from '../models/generate';
import type { GeneratorResult } from '../types/generator-result';
import type { Context } from 'baojs';
import { get } from 'http';
import { getFFmpegArgs } from '../core/ffmpeg-args';
export class Tree implements Generate {
getInfo(config?: Config): Promise<GeneratorResult> {
if (!config) {
throw new Error('Config is required to get tree info.');
}
const rand = new SeededRandom(config.seed);
const startPos = new Vector2(0, 0);
const initialLength = 200;
const maxDepth = 7;
const fullTree = generateFullTree(rand, startPos, initialLength, -90, maxDepth, 0);
const bounds = calculateBounds(fullTree);
const scale = Math.min(
(config.width - config.padding * 2) / (bounds.maxX - bounds.minX),
(config.height - config.padding * 2) / (bounds.maxY - bounds.minY)
);
const treeCenterX = bounds.minX + (bounds.maxX - bounds.minX) / 2;
const targetCenterX = config.width / 2;
const offsetX = targetCenterX - treeCenterX * scale;
const offsetY = (config.height - config.padding) - bounds.maxY * scale;
return Promise.resolve({
trunkStartPosition: { x: offsetX, y: offsetY }
});
}
async generate(con: Context, onStream?:(process:ChildProcessWithoutNullStreams,videoStream:ChildProcessWithoutNullStreams['stdout']) => void, CONFIG: Config = DEFAULT_CONFIG): Promise<GeneratorResult> {
console.log("Generating Tree");
const canvas = createCanvas(CONFIG.width, CONFIG.height);
const ctx = canvas.getContext('2d');
const rand = new SeededRandom(CONFIG.seed);
// Generate logical tree roughly centered at 0,0 first, then shift
// We use a dummy start position, we will move it later
const startPos = new Vector2(0, 0);
const initialLength = 200; // Arbitrary unit, will be scaled
const maxDepth = 7;
const fullTree = generateFullTree(
rand,
startPos,
initialLength,
-90,
maxDepth,
0
);
const bounds = calculateBounds(fullTree);
const treeWidth = bounds.maxX - bounds.minX;
const treeHeight = bounds.maxY - bounds.minY;
// Available space
const availW = CONFIG.width - (CONFIG.padding * 2);
const availH = CONFIG.height - (CONFIG.padding * 2);
// Scale to fit (maintain aspect ratio)
const scaleX = availW / treeWidth;
const scaleY = availH / treeHeight;
const finalScale = Math.min(scaleX, scaleY);
// Calculate offsets to center the tree
// We want the bounding box center to align with canvas center
// However, for a tree, it usually looks best if the "root" is at the bottom-center
// But since we want it "perfectly in frame", let's center the bounding box vertically too,
// or align bottom. Let's align bottom of tree to bottom margin.
const treeCenterX = bounds.minX + (treeWidth / 2);
const targetCenterX = CONFIG.width / 2;
const offsetX = targetCenterX - (treeCenterX * finalScale);
// Align bottom: bounds.maxY should be at CONFIG.height - padding
// Note: Canvas Y goes down. -90 deg means Y decreases.
// bounds.maxY is likely the root (0), bounds.minY is the top leaves.
const offsetY = (CONFIG.height - CONFIG.padding) - (bounds.maxY * finalScale);
console.log(` Tree Width: ${treeWidth.toFixed(0)}, Height: ${treeHeight.toFixed(0)}`);
console.log(` Scale: ${finalScale.toFixed(3)}`);
console.log(` Offset: ${offsetX.toFixed(0)}, ${offsetY.toFixed(0)}`);
const maxDistance = getMaxDist(fullTree);
console.log(` Max Growth Distance: ${maxDistance.toFixed(0)}`);
if (CONFIG.photoOnly) {
console.log("📸 Generating final tree image only (video creation skipped).");
// Set growth to maximum to draw the final state
const currentGrowthDist = maxDistance + 700;
ctx.clearRect(0, 0, CONFIG.width, CONFIG.height);
const branches: SimpleBranch[] = [];
let entities: Entity[] = [];
flattenTreeOrganic(fullTree, branches, entities, currentGrowthDist, finalScale, offsetX, offsetY);
const leaves = entities.filter(e => e.type === 'leaf');
const fruits = entities.filter(e => e.type === 'fruit');
leaves.sort((a, b) => a.center.y - b.center.y);
fruits.sort((a, b) => a.center.y - b.center.y);
entities = leaves.concat(fruits);
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = '#3E2723';
for (const b of branches) {
ctx.beginPath();
ctx.lineWidth = b.strokeWidth;
ctx.moveTo(b.start.x, b.start.y);
ctx.quadraticCurveTo(b.control.x, b.control.y, b.end.x, b.end.y);
ctx.stroke();
}
ctx.strokeStyle = '#6D4C41';
for (const b of branches) {
if (b.strokeWidth < 1) continue;
ctx.beginPath();
ctx.lineWidth = b.strokeWidth * 0.5;
const off = -1;
ctx.moveTo(b.start.x + off, b.start.y + off);
ctx.quadraticCurveTo(b.control.x + off, b.control.y + off, b.end.x + off, b.end.y + off);
ctx.stroke();
}
for (const e of entities) {
const prevAlpha = ctx.globalAlpha;
ctx.globalAlpha = (e.opacity ?? 1);
ctx.fillStyle = 'rgba(0,0,0,0.1)';
ctx.beginPath();
ctx.arc(e.center.x + 2, e.center.y + 5, e.radius, 0, Math.PI * 2);
ctx.fill();
const g = ctx.createRadialGradient(e.center.x - e.radius * 0.3, e.center.y - e.radius * 0.3, e.radius * 0.1, e.center.x, e.center.y, e.radius);
g.addColorStop(0, `rgba(${e.highlightColor.r},${e.highlightColor.g},${e.highlightColor.b},1)`);
g.addColorStop(1, `rgba(${e.baseColor.r},${e.baseColor.g},${e.baseColor.b},1)`);
ctx.beginPath();
ctx.fillStyle = g;
ctx.arc(e.center.x, e.center.y, e.radius, 0, Math.PI * 2);
ctx.fill();
if (e.type === 'fruit') {
ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
ctx.beginPath();
ctx.arc(e.center.x - e.radius * 0.3, e.center.y - e.radius * 0.3, e.radius * 0.25, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = prevAlpha;
}
const finalBuffer = canvas.toBuffer('image/png');
if (CONFIG.save_as_file) {
fs.writeFileSync(CONFIG.imageFilename, finalBuffer);
}
console.log(`\n✅ Image generation complete!`);
console.log(` Image saved: ${CONFIG.imageFilename}`);
return {
imageBuffer: finalBuffer,
imagePath: CONFIG.save_as_file ? CONFIG.imageFilename : undefined,
trunkStartPosition: { x: offsetX, y: offsetY }
}; // Exit after saving the image
}
const ffmpegArgs = getFFmpegArgs(CONFIG);
console.log(`🎥 Spawning FFmpeg process: ${CONFIG.filename}`);
const ffmpeg = spawn('ffmpeg', ffmpegArgs);
if (onStream) {
onStream(ffmpeg, ffmpeg.stdout);
}
const totalFrames = CONFIG.durationSeconds * CONFIG.fps;
for (let frame = 0; frame < totalFrames; frame++) {
const t = frame / (totalFrames - 1);
// Organic Growth: Distance based
// We grow past maxDistance to ensure fruits have time to grow (they have a 500-unit delay)
const currentGrowthDist = t * (maxDistance + 700);
// Clear Rect for TRANSPARENT background
ctx.clearRect(0, 0, CONFIG.width, CONFIG.height);
const branches: SimpleBranch[] = [];
let entities: Entity[] = [];
flattenTreeOrganic(fullTree, branches, entities, currentGrowthDist, finalScale, offsetX, offsetY);
// Separate leaves & fruits for rendering order
const leaves = entities.filter(e => e.type === 'leaf');
const fruits = entities.filter(e => e.type === 'fruit');
// Sort all entities back-to-front (top/back first), fruits drawn last so they appear on top
leaves.sort((a, b) => a.center.y - b.center.y);
fruits.sort((a, b) => a.center.y - b.center.y);
// Fruits are always drawn on top, never culled
entities = leaves.concat(fruits);
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// DRAW TREE TRUNK
ctx.strokeStyle = '#3E2723';
for (const b of branches) {
ctx.beginPath();
ctx.lineWidth = b.strokeWidth;
ctx.moveTo(b.start.x, b.start.y);
ctx.quadraticCurveTo(b.control.x, b.control.y, b.end.x, b.end.y);
ctx.stroke();
}
ctx.strokeStyle = '#6D4C41';
for (const b of branches) {
if (b.strokeWidth < 1) continue;
ctx.beginPath();
ctx.lineWidth = b.strokeWidth * 0.5;
const off = -1;
ctx.moveTo(b.start.x + off, b.start.y + off);
ctx.quadraticCurveTo(b.control.x + off, b.control.y + off, b.end.x + off, b.end.y + off);
ctx.stroke();
}
// DRAW LEAVES & FRUITS
for (const e of entities) {
// Use per-entity opacity (fade-in) and restore after drawing
const prevAlpha = ctx.globalAlpha;
ctx.globalAlpha = (e.opacity ?? 1);
// Shadow (will be affected by globalAlpha so it fades with the entity)
ctx.fillStyle = 'rgba(0,0,0,0.1)';
ctx.beginPath();
ctx.arc(e.center.x + 2, e.center.y + 5, e.radius, 0, Math.PI * 2);
ctx.fill();
// Main Gradient
const g = ctx.createRadialGradient(
e.center.x - e.radius * 0.3,
e.center.y - e.radius * 0.3,
e.radius * 0.1,
e.center.x,
e.center.y,
e.radius
);
// We rely on globalAlpha for fade; color stops are fully opaque
g.addColorStop(0, `rgba(${e.highlightColor.r},${e.highlightColor.g},${e.highlightColor.b},1)`);
g.addColorStop(1, `rgba(${e.baseColor.r},${e.baseColor.g},${e.baseColor.b},1)`);
ctx.beginPath();
ctx.fillStyle = g;
ctx.arc(e.center.x, e.center.y, e.radius, 0, Math.PI * 2);
ctx.fill();
// Extra shine for fruits
if (e.type === 'fruit') {
ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
ctx.beginPath();
ctx.arc(e.center.x - e.radius * 0.3, e.center.y - e.radius * 0.3, e.radius * 0.25, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = prevAlpha;
}
const buffer = canvas.toBuffer('image/png');
const ok = ffmpeg.stdin.write(buffer);
if (!ok) await new Promise(resolve => ffmpeg.stdin.once('drain', resolve));
// if (frame % 30 === 0) {
// const pct = Math.round((frame / totalFrames) * 100);
// console.log('progress:', pct + '%');
// }
}
ffmpeg.stdin.end();
// Wait for FFmpeg to finish encoding
await new Promise<void>((resolve, reject) => {
ffmpeg.on('close', (code) => {
if (code === 0) resolve();
else reject(new Error(`FFmpeg exited with code ${code}`));
});
ffmpeg.on('error', reject);
});
return {
videoPath: CONFIG.filename,
trunkStartPosition: { x: offsetX, y: offsetY }
};
}
}
class Vector2 {
constructor(public x: number, public y: number) { }
static zero = () => new Vector2(0, 0);
}
interface Entity {
center: Vector2;
radius: number;
baseColor: Color;
highlightColor: Color;
type: 'leaf' | 'fruit';
distFromRoot: number; // Distance from root for timing
opacity?: number; // 0..1 fade-in multiplier
attachmentPoint?: Vector2; // Where the leaf/fruit attaches to the branch
}
class Branch {
constructor(
public start: Vector2,
public end: Vector2,
public strokeWidth: number,
public control: Vector2,
public length: number, // Actual length
public distFromRoot: number, // Cumulative distance
public children: Branch[] = [],
public entities: Entity[] = []
) { }
}
class SimpleBranch {
constructor(
public start: Vector2,
public end: Vector2,
public strokeWidth: number,
public control: Vector2
) { }
}
interface Bounds {
minX: number; maxX: number; minY: number; maxY: number;
}
const coerceIn = (val: number, min: number, max: number) => Math.max(min, Math.min(val, max));
function smoothStep(t: number): number {
return t * t * (3 - 2 * t);
}
function generateFullTree(
rand: SeededRandom,
start: Vector2,
length: number,
angle: number,
depth: number,
currentDist: number,
): Branch {
const angleOffset = rand.nextFloat(-20, 20); // More twisty
const radAngle = (angle + angleOffset) * (Math.PI / 180);
const endX = start.x + length * Math.cos(radAngle);
const endY = start.y + length * Math.sin(radAngle);
const end = new Vector2(endX, endY);
const dx = end.x - start.x;
const dy = end.y - start.y;
const mid = new Vector2(start.x + dx * 0.5, start.y + dy * 0.5);
const perpLen = rand.nextFloat(-0.2, 0.2) * length;
const branchLength = Math.sqrt(dx * dx + dy * dy);
let perpX = 0, perpY = 0;
if (branchLength !== 0) {
perpX = (-dy / branchLength) * perpLen;
perpY = (dx / branchLength) * perpLen;
}
const control = new Vector2(mid.x + perpX, mid.y + perpY);
const strokeWidth = Math.max(2, (depth * 4 + rand.nextFloat(-1, 1)));
const children: Branch[] = [];
const entities: Entity[] = [];
if (depth > 0) {
const branchCount = rand.nextInt(2, 3); // 2 to 3 branches
for (let i = 0; i < branchCount; i++) {
const angleVariation = rand.nextFloat(-45, 45);
const newAngle = angle + angleVariation;
const newLength = length * rand.nextFloat(0.7, 0.9);
children.push(generateFullTree(
rand,
end,
newLength,
newAngle,
depth - 1,
currentDist + length,
));
}
}
// Bigger leaves, attached to branches
if (depth <= 4) {
const count = rand.nextInt(4, 7);
let fruitCount = { count: 0 }; // Reset fruit count per branch
for (let i = 0; i < count; i++) {
// BIGGER LEAVES: 25-45 radius
const radius = rand.nextFloat(1, 10);
// Random position near the branch end/middle
const t = rand.nextFloat(0.3, 0.95); // Position along branch
const px = (1 - t) * start.x + t * end.x;
const py = (1 - t) * start.y + t * end.y;
// This is the attachment point on the branch
const attachmentPoint = new Vector2(px, py);
// Offset from the attachment point. Reduced for tighter clustering.
const offsetX = rand.nextFloat(-40, 40);
const offsetY = rand.nextFloat(-40, 40);
const eX = px + offsetX;
const eY = py + offsetY;
// Entity distance is based on where it attaches along the branch
const entityDist = currentDist + (length * t);
// Decision: Fruit or Leaf?
// Enforce a cooldown to prevent clustering
const canBeFruit = fruitCount.count < 1;
const isFruit = canBeFruit && rand.nextFloat(0, 1) > 0.99;
if (isFruit) {
fruitCount.count++;
const fruitPalette: [Color] = [
{ r: 255, g: 0, b: 0, a: 1 },
];
const color: Color = fruitPalette[rand.nextInt(0, fruitPalette.length)] ?? { r: 255, g: 0, b: 0, a: 1 };
// Fruits grow LAST: add a large offset to their distFromRoot so they appear at the very end
const fruitDelay = 100; // They'll start growing 500 units after their branch
entities.push({
center: new Vector2(eX, eY),
radius: radius,
baseColor: { r: color.r, g: color.g, b: color.b, a: 1.0 },
highlightColor: { r: Math.min(255, color.r + 50), g: Math.min(255, color.g + 50), b: Math.min(255, color.b + 50), a: 1.0 },
type: 'fruit',
distFromRoot: entityDist + fruitDelay,
attachmentPoint: attachmentPoint
});
} else {
const rBase = 45 + rand.nextFloat(0, 20); // Slight natural warmth
const gBase = 110 + rand.nextFloat(0, 40); // Strongest channel (green)
const bBase = 30 + rand.nextFloat(0, 25); // Earthy greens
entities.push({
center: new Vector2(eX, eY),
radius: radius,
baseColor: { r: rBase, g: gBase, b: bBase, a: 1.0 },
highlightColor: { r: rBase + 40, g: gBase + 40, b: bBase + 40, a: 1.0 },
type: 'leaf',
distFromRoot: entityDist,
attachmentPoint: attachmentPoint
});
}
}
}
return new Branch(start, end, strokeWidth, control, length, currentDist, children, entities);
}
// Recurse tree to find min/max coords
function calculateBounds(b: Branch, currentBounds: Bounds = { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity }): Bounds {
// Check branch points
currentBounds.minX = Math.min(currentBounds.minX, b.start.x, b.end.x, b.control.x);
currentBounds.maxX = Math.max(currentBounds.maxX, b.start.x, b.end.x, b.control.x);
currentBounds.minY = Math.min(currentBounds.minY, b.start.y, b.end.y, b.control.y);
currentBounds.maxY = Math.max(currentBounds.maxY, b.start.y, b.end.y, b.control.y);
// Check entities (leaves expand bounds)
b.entities.forEach(e => {
currentBounds.minX = Math.min(currentBounds.minX, e.center.x - e.radius);
currentBounds.maxX = Math.max(currentBounds.maxX, e.center.x + e.radius);
currentBounds.minY = Math.min(currentBounds.minY, e.center.y - e.radius);
currentBounds.maxY = Math.max(currentBounds.maxY, e.center.y + e.radius);
});
b.children.forEach(child => calculateBounds(child, currentBounds));
return currentBounds;
}
// Find the maximum path length in the tree for animation timing
function getMaxDist(b: Branch): number {
let max = b.distFromRoot + b.length;
for (const child of b.children) {
max = Math.max(max, getMaxDist(child));
}
return max;
}
function flattenTreeOrganic(
b: Branch,
branchList: SimpleBranch[],
entityList: Entity[],
progressDistance: number, // The 'water level' of growth
scale: number,
offsetX: number,
offsetY: number
) {
const tStart = new Vector2(b.start.x * scale + offsetX, b.start.y * scale + offsetY);
const tEnd = new Vector2(b.end.x * scale + offsetX, b.end.y * scale + offsetY);
const tControl = new Vector2(b.control.x * scale + offsetX, b.control.y * scale + offsetY);
// This branch starts growing when the "progress wave" hits its start distance
// It finishes growing when the wave hits its end distance
const startDist = b.distFromRoot;
const endDist = b.distFromRoot + b.length;
if (progressDistance > startDist) {
// Calculate how much of this specific branch is grown
let localT = (progressDistance - startDist) / b.length;
localT = coerceIn(localT, 0, 1);
if (localT > 0) {
// Bezier Interpolation for "growing" tip
const omt = 1 - localT;
const curControlX = omt * tStart.x + localT * tControl.x;
const curControlY = omt * tStart.y + localT * tControl.y;
const q1X = omt * tControl.x + localT * tEnd.x;
const q1Y = omt * tControl.y + localT * tEnd.y;
const curEndX = omt * curControlX + localT * q1X;
const curEndY = omt * curControlY + localT * q1Y;
// Stroke thickens as it ages (start thickness vs tip thickness)
const visibleStroke = b.strokeWidth * scale * localT;
branchList.push(new SimpleBranch(
tStart,
new Vector2(curEndX, curEndY),
visibleStroke,
new Vector2(curControlX, curControlY)
));
// They start growing when the growth wave passes their specific attachment point
b.entities.forEach(entity => {
if (progressDistance > entity.distFromRoot) {
// How far past the entity are we?
const age = progressDistance - entity.distFromRoot;
// Grow in over 150 units of distance
const growSpeed = 150;
let growthP = age / growSpeed;
growthP = coerceIn(growthP, 0, 1);
// Smooth growth using easing
const radiusScale = smoothStep(growthP);
if (radiusScale > 0.01) {
const finalCenterX = entity.center.x * scale + offsetX;
const finalCenterY = entity.center.y * scale + offsetY;
entityList.push({
...entity,
center: new Vector2(finalCenterX, finalCenterY),
// radius grows smoothly from near-zero to full size
radius: entity.radius * scale * radiusScale,
// Full opacity during growth (no fading)
opacity: 1.0
});
}
}
});
}
}
// Recurse
b.children.forEach(child => {
flattenTreeOrganic(child, branchList, entityList, progressDistance, scale, offsetX, offsetY);
});
}