Repository navigation
Expand file tree
/
Copy pathlocal-osc-server.js
More file actions
1195 lines (1010 loc) Β· 50.5 KB
/
Copy pathlocal-osc-server.js
File metadata and controls
1195 lines (1010 loc) Β· 50.5 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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* Local OSC Server for WebGL Fluid Simulation
* Runs on local network for TouchOSC control
* Works with FTP-hosted fluid simulation
*/
const osc = require('node-osc');
const WebSocket = require('ws');
const os = require('os');
const TelegramBot = require('node-telegram-bot-api');
// Configuration
const OSC_PORT = 8000;
const WEBSOCKET_PORT = 8001;
const CORS_ORIGINS = ['*']; // Allow all origins for local network
// Telegram Bot Configuration
let TELEGRAM_BOT_TOKEN = '';
class FluidOSCServer {
constructor() {
this.clients = new Set();
this.oscServer = null;
this.wsServer = null;
this.telegramBot = null;
this.networkIP = this.getNetworkIP();
// Telegram waitlist tracking
this.telegramWaitlist = [];
this.waitlistInterval = 1; // Default 1 second
this.processingTimer = null; // Timer for processing queue
// Throttling for performance - limit OSC message rate
this.lastMessageTime = {};
this.throttleInterval = 16; // ~60fps (16ms between messages)
// OSC velocity tracking for velocity-based drawing
this.oscPointers = {}; // Track position and movement for each channel
// Preset definitions
this.promptPresets = [
{
name: 'Blooming Flower',
prompt: 'blooming flower with delicate petals, vibrant colors, soft natural lighting, botanical beauty, detailed macro photography, spring garden atmosphere'
},
{
name: 'Jellyfish Ballet',
prompt: 'giant glowing jellyfish, slow graceful movement, neon blue and pink bioluminescence, flowing tendrils like silk, underwater ballet, dreamlike ocean atmosphere'
},
{
name: 'Fractal Jellyfish',
prompt: 'evolving fractal jellyfish, recursive growth, rainbow light trails, kaleidoscopic motion'
},
{
name: 'Aurora Mountains',
prompt: 'northern lights over snow-capped mountains, aurora borealis, starry night sky, ethereal green and purple lights, pristine wilderness'
},
{
name: 'Floating Islands',
prompt: 'floating islands with waterfalls, magical gardens, ethereal mist, fantasy landscape, soft pastel colors, Studio Ghibli style'
},
{
name: 'Magic Forest',
prompt: 'bioluminescent mushrooms, glowing forest at night, magical blue and green lights, fairy tale atmosphere, mystical fog'
},
{
name: 'Cotton Candy',
prompt: 'fluffy cotton candy texture, pastel pink and blue swirls, soft dreamy atmosphere, sweet confection, carnival vibes, whimsical and light'
},
{
name: 'Spirit River',
prompt: 'glowing water streams, ghostly silhouettes drifting, soft ethereal mist'
},
{
name: 'Jellyfish Eye',
prompt: 'hyperrealistic eye macro shot, extreme close-up iris detail, glowing jellyfish reflected in the eye, wet glossy texture, ultra-sharp eyelashes, cinematic lighting, surreal bioluminescent glow inside the pupil, hyper-detailed photorealism'
},
{
name: 'Spirit Eye',
prompt: 'hyperrealistic human eye close-up, iris patterned like coral reef, glowing jellyfish swimming inside reflection, golden sunlight refracting in water-like cornea, organic textures, magical natural atmosphere, ultra-detailed vibrant realism'
},
{
name: 'Underwater Corals',
prompt: 'vibrant coral reef city, tropical fishes and jellyfishes swimming, underwater sunbeams, crystal clear water, marine life paradise'
},
{
name: 'Lightning Storm',
prompt: 'electric lightning bolts, storm clouds, energy discharge, dramatic sky, purple and white electricity, powerful atmosphere'
},
{
name: 'Fractal Spell Casting',
prompt: 'magical spell effects, glowing runes, mystical energy swirls, fantasy magic, ethereal particles, wizard\'s study, arcane symbols, kaleidoscopic motion'
},
{
name: 'Van Gogh',
prompt: 'Van Gogh style swirling sky, impressionist brushstrokes, flowing paint texture, vibrant yellows and blues, artistic masterpiece'
}
];
this.controlNetPresets = {
balanced: {
name: 'Balanced',
description: 'Good for general use with moderate control',
params: {
CONTROLNET_POSE_SCALE: 0.65,
CONTROLNET_HED_SCALE: 0.41,
CONTROLNET_CANNY_SCALE: 0.00,
CONTROLNET_DEPTH_SCALE: 0.21,
CONTROLNET_COLOR_SCALE: 0.26,
DENOISE_X: 3,
DENOISE_Y: 6,
DENOISE_Z: 6
}
},
portrait: {
name: 'Portrait',
description: 'Optimized for human subjects with strong pose control',
params: {
CONTROLNET_POSE_SCALE: 0.85,
CONTROLNET_HED_SCALE: 0.70,
CONTROLNET_CANNY_SCALE: 0.40,
CONTROLNET_DEPTH_SCALE: 0.60,
CONTROLNET_COLOR_SCALE: 0.75,
DENOISE_X: 2,
DENOISE_Y: 4,
DENOISE_Z: 6
}
},
composition: {
name: 'Composition',
description: 'Strong structural control with Canny and Depth',
params: {
CONTROLNET_POSE_SCALE: 0.40,
CONTROLNET_HED_SCALE: 0.45,
CONTROLNET_CANNY_SCALE: 0.80,
CONTROLNET_DEPTH_SCALE: 0.75,
CONTROLNET_COLOR_SCALE: 0.35,
DENOISE_X: 4,
DENOISE_Y: 8,
DENOISE_Z: 12
}
},
artistic: {
name: 'Artistic',
description: 'More creative freedom with subtle controls',
params: {
CONTROLNET_POSE_SCALE: 0.30,
CONTROLNET_HED_SCALE: 0.75,
CONTROLNET_CANNY_SCALE: 0.25,
CONTROLNET_DEPTH_SCALE: 0.35,
CONTROLNET_COLOR_SCALE: 0.40,
DENOISE_X: 6,
DENOISE_Y: 12,
DENOISE_Z: 18
}
}
};
// OSC parameter mapping
this.oscMap = {
// Fluid Physics
'/fluid/density': { param: 'DENSITY_DISSIPATION', min: 0, max: 4, type: 'slider' },
'/fluid/velocity': { param: 'VELOCITY_DISSIPATION', min: 0, max: 4, type: 'slider' },
'/fluid/pressure': { param: 'PRESSURE', min: 0, max: 1, type: 'slider' },
'/fluid/vorticity': { param: 'CURL', min: 0, max: 50, type: 'slider' },
'/fluid/splat': { param: 'OSC_SPLAT_RADIUS', min: 0.01, max: 1, type: 'slider' },
// Main Toggles
'/toggle/paused': { param: 'PAUSED', type: 'toggle' },
'/toggle/colorful': { param: 'COLORFUL', type: 'toggle' },
'/toggle/animate': { param: 'ANIMATE', type: 'toggle' },
// Visual Effects Toggles
'/toggle/bloom': { param: 'BLOOM', type: 'toggle' },
'/toggle/sunrays': { param: 'SUNRAYS', type: 'toggle' },
'/toggle/shading': { param: 'SHADING', type: 'toggle' },
'/toggle/transparent': { param: 'TRANSPARENT', type: 'toggle' },
// Input Mode Toggles
'/toggle/velocity_drawing': { param: 'VELOCITY_DRAWING', type: 'toggle' },
// FORCE_CLICK removed - mouse-only feature, should not be controlled via OSC
'/toggle/fluid_drawing': { action: 'toggleFluidDrawing', type: 'button' },
'/toggle/audio': { action: 'toggleAudioBlob', type: 'button' },
'/toggle/camera': { action: 'toggleCamera', type: 'button' },
'/toggle/media': { action: 'toggleMedia', type: 'button' },
// Visual Effects Intensities
'/visual/bloom_intensity': { param: 'BLOOM_INTENSITY', min: 0.1, max: 2, type: 'slider' },
'/visual/sunray_weight': { param: 'SUNRAYS_WEIGHT', min: 0.3, max: 1, type: 'slider' },
// Animation
'/animation/animate': { param: 'ANIMATE', type: 'toggle' },
'/animation/paused': { param: 'PAUSED', type: 'toggle' },
'/animation/liveliness': { param: 'LIVELINESS', min: 0, max: 1, type: 'slider' },
'/animation/chaos': { param: 'CHAOS', min: 0, max: 1, type: 'slider' },
'/animation/breathing': { param: 'BREATHING', min: 0, max: 1, type: 'slider' },
'/animation/color_life': { param: 'COLOR_LIFE', min: 0, max: 1, type: 'slider' },
'/animation/interval': { param: 'ANIMATION_INTERVAL', min: 0, max: 1, type: 'slider' },
// AI/ML Parameters
'/ai/inference_steps': { param: 'INFERENCE_STEPS', min: 1, max: 100, type: 'slider' },
'/ai/seed': { param: 'SEED', min: 0, max: 1000, type: 'slider' },
'/ai/guidance_scale': { param: 'GUIDANCE_SCALE', min: 1, max: 20, type: 'slider' },
'/ai/delta': { param: 'DELTA', min: 0, max: 1, type: 'slider' },
// ControlNet
'/controlnet/pose': { param: 'CONTROLNET_POSE_SCALE', min: 0, max: 1, type: 'slider' },
'/controlnet/hed': { param: 'CONTROLNET_HED_SCALE', min: 0, max: 1, type: 'slider' },
'/controlnet/canny': { param: 'CONTROLNET_CANNY_SCALE', min: 0, max: 1, type: 'slider' },
'/controlnet/depth': { param: 'CONTROLNET_DEPTH_SCALE', min: 0, max: 1, type: 'slider' },
'/controlnet/color': { param: 'CONTROLNET_COLOR_SCALE', min: 0, max: 1, type: 'slider' },
// Denoise
'/denoise/x': { param: 'DENOISE_X', min: 0, max: 45, type: 'slider' },
'/denoise/y': { param: 'DENOISE_Y', min: 0, max: 45, type: 'slider' },
'/denoise/z': { param: 'DENOISE_Z', min: 0, max: 45, type: 'slider' },
// Audio
'/audio/reactivity': { param: 'AUDIO_REACTIVITY', min: 0.1, max: 3.0, type: 'slider' },
'/audio/delay': { param: 'AUDIO_DELAY', min: 0, max: 1, type: 'slider' },
'/audio/opacity': { param: 'AUDIO_OPACITY', min: 0, max: 1, type: 'slider' },
'/audio/colorful': { param: 'AUDIO_COLORFUL', min: 0, max: 1, type: 'slider' },
'/audio/edge_softness': { param: 'AUDIO_EDGE_SOFTNESS', min: 0, max: 1, type: 'slider' },
// Media Controls
'/media/scale': { param: 'MEDIA_SCALE', min: 0.1, max: 2.0, type: 'slider' },
'/media/background_scale': { param: 'BACKGROUND_IMAGE_SCALE', min: 0.1, max: 2.0, type: 'slider' },
'/media/fluid_media_scale': { param: 'FLUID_MEDIA_SCALE', min: 0.1, max: 2.0, type: 'slider' },
'/media/fluid_camera_scale': { param: 'FLUID_CAMERA_SCALE', min: 0.1, max: 2.0, type: 'slider' },
// Input Modes (special handling)
'/input/fluid_drawing': { action: 'toggleFluidDrawing', type: 'button' },
'/input/audio': { action: 'toggleAudioBlob', type: 'button' },
'/input/camera': { action: 'toggleCamera', type: 'button' },
'/input/media': { action: 'toggleMedia', type: 'button' },
// Brush/Fluid Colors (RGB format, values 0-1)
'/brush/r': { param: 'STATIC_COLOR.r', min: 0, max: 1, type: 'slider' },
'/brush/g': { param: 'STATIC_COLOR.g', min: 0, max: 1, type: 'slider' },
'/brush/b': { param: 'STATIC_COLOR.b', min: 0, max: 1, type: 'slider' },
'/brush/rgb': { param: 'STATIC_COLOR', type: 'color' },
'/color/background/r': { param: 'BACK_COLOR.r', min: 0, max: 1, type: 'slider' },
'/color/background/g': { param: 'BACK_COLOR.g', min: 0, max: 1, type: 'slider' },
'/color/background/b': { param: 'BACK_COLOR.b', min: 0, max: 1, type: 'slider' },
'/color/background/rgb': { param: 'BACK_COLOR', type: 'color' },
// Actions
'/action/reset': { action: 'resetValues', type: 'button' },
'/action/screenshot': { action: 'captureScreenshot', type: 'button' },
'/action/record': { action: 'toggleVideoRecording', type: 'button' },
// Telegram Controls
'/telegram/receive': { action: 'toggleTelegramReceive', type: 'toggle' },
'/telegram/clear': { action: 'clearTelegramWaitlist', type: 'button' },
'/telegram/interval': { param: 'TELEGRAM_WAITLIST_INTERVAL', min: 1, max: 30, type: 'slider' },
// TouchOSC XY Pad Support (your primary format)
'/multixy/1': { channel: 1, type: 'xy_pad' },
'/multixy/2': { channel: 2, type: 'xy_pad' },
'/multixy/3': { channel: 3, type: 'xy_pad' },
'/multixy/4': { channel: 4, type: 'xy_pad' },
'/multixy/5': { channel: 5, type: 'xy_pad' },
};
}
handleVelocityDrawing(channel, x, y) {
const pointerId = `osc_${channel}`;
const currentTime = Date.now();
// Track OSC pointer velocity for smooth drawing
// Get or create pointer for this channel
if (!this.oscPointers[pointerId]) {
this.oscPointers[pointerId] = {
x: x,
y: y,
prevX: x,
prevY: y,
lastTime: currentTime,
isActive: true
};
// Send initial position without velocity (like mouse down)
this.sendVelocityDrawingMessage(channel, x, y, 0, 0, 'start');
return;
}
const pointer = this.oscPointers[pointerId];
const deltaTime = currentTime - pointer.lastTime;
// Calculate movement deltas
const deltaX = x - pointer.prevX;
const deltaY = y - pointer.prevY;
// Calculate velocity (movement per second)
const velocity = deltaTime > 0 ? Math.sqrt(deltaX * deltaX + deltaY * deltaY) / (deltaTime / 1000) : 0;
// Update pointer state
pointer.prevX = pointer.x;
pointer.prevY = pointer.y;
pointer.x = x;
pointer.y = y;
pointer.lastTime = currentTime;
// Send velocity-based drawing message
this.sendVelocityDrawingMessage(channel, x, y, deltaX, deltaY, 'move');
console.log(`π― OSC Velocity Drawing ${channel}: (${x.toFixed(3)}, ${y.toFixed(3)}) v=${velocity.toFixed(2)} Ξ(${deltaX.toFixed(3)}, ${deltaY.toFixed(3)})`);
}
sendVelocityDrawingMessage(channel, x, y, deltaX, deltaY, type) {
const message = {
type: 'osc_velocity_drawing',
channel: channel,
x: x,
y: y,
deltaX: deltaX,
deltaY: deltaY,
drawingType: type
};
// Broadcast to WebSocket clients
this.clients.forEach(client => {
if (client.readyState === 1) { // WebSocket.OPEN
client.send(JSON.stringify(message));
}
});
}
getNetworkIP() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
// Skip internal and non-IPv4 addresses
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return 'localhost';
}
start() {
this.startOSCServer();
this.startWebSocketServer();
// Telegram bot will be started when token is received from client
this.printStartupInfo();
}
startOSCServer() {
this.oscServer = new osc.Server(OSC_PORT, '0.0.0.0', () => {
console.log(`ποΈ OSC Server listening on ${this.networkIP}:${OSC_PORT}`);
});
this.oscServer.on('message', (msg) => {
this.handleOSCMessage(msg);
});
this.oscServer.on('error', (err) => {
console.error('β OSC Server error:', err);
});
}
startWebSocketServer() {
this.wsServer = new WebSocket.Server({
port: WEBSOCKET_PORT,
host: '0.0.0.0'
});
this.wsServer.on('connection', (ws, req) => {
const clientIP = req.socket.remoteAddress;
console.log(`π WebSocket client connected from ${clientIP}`);
this.clients.add(ws);
// Handle messages from client
ws.on('message', (data) => {
try {
const message = JSON.parse(data.toString());
this.handleClientMessage(message);
} catch (error) {
console.error('β Error parsing client message:', error);
}
});
// Send welcome message with server info
ws.send(JSON.stringify({
type: 'server_info',
networkIP: this.networkIP,
oscPort: OSC_PORT,
websocketPort: WEBSOCKET_PORT,
availableAddresses: Object.keys(this.oscMap)
}));
ws.on('close', () => {
this.clients.delete(ws);
console.log(`π WebSocket client disconnected from ${clientIP}`);
});
ws.on('error', (err) => {
console.error('β WebSocket error:', err);
this.clients.delete(ws);
});
});
console.log(`π WebSocket Server listening on ${this.networkIP}:${WEBSOCKET_PORT}`);
}
handleClientMessage(message) {
switch (message.type) {
case 'telegram_prompt_applied':
// Client notifies that a prompt has been applied
const appliedEntry = this.removeFromWaitlist(message.promptId);
if (appliedEntry && appliedEntry.chatId) {
if (message.isPreset && message.presetName) {
// Send preset-specific feedback
this.sendPromptPresetAppliedFeedback(appliedEntry.chatId, message.presetName, appliedEntry.prompt, appliedEntry.from);
} else {
// Send regular prompt feedback
this.sendPromptAppliedFeedback(appliedEntry.chatId, appliedEntry.prompt, appliedEntry.from);
}
}
break;
case 'controlnet_preset_applied':
// Client notifies that a ControlNet preset has been applied
const appliedPreset = this.removeFromWaitlistByPreset(message.presetName, message.chatId);
if (appliedPreset && appliedPreset.chatId) {
this.sendControlNetPresetAppliedFeedback(appliedPreset.chatId, appliedPreset.presetName, appliedPreset.presetDescription, appliedPreset.from);
}
break;
case 'telegram_waitlist_interval_changed':
// Client notifies of interval change
this.updateWaitlistInterval(message.interval);
break;
case 'telegram_waitlist_cleared':
// Client notifies that waitlist was cleared
this.telegramWaitlist = [];
this.stopTelegramProcessing();
console.log('π± Server waitlist cleared by client');
break;
case 'telegram_token_updated':
// Client sends updated Telegram token
this.updateTelegramToken(message.token);
break;
default:
console.log('π± Unknown client message type:', message.type);
}
}
sendQueueStatusFeedback(chatId, waitlistEntry) {
if (!this.telegramBot) return;
const position = this.telegramWaitlist.findIndex(item => item.id === waitlistEntry.id) + 1;
const queueLength = this.telegramWaitlist.length;
// Calculate actual estimated wait time based on processing timeline
let estimatedWaitSeconds = 0;
let expectedTime = new Date();
if (position === 1) {
// First in queue - will be processed within the current interval
estimatedWaitSeconds = 0;
expectedTime = new Date(Date.now() + (this.waitlistInterval * 1000));
} else {
// Calculate based on when this item will actually be processed
// If there's a first item, calculate from when it was added
const firstItem = this.telegramWaitlist[0];
if (firstItem && firstItem.addedAt) {
const firstItemWaitTime = (Date.now() - firstItem.addedAt) / 1000;
const remainingTimeForFirst = Math.max(0, this.waitlistInterval - firstItemWaitTime);
// This item will be processed after (position-1) intervals, minus time already elapsed
estimatedWaitSeconds = remainingTimeForFirst + ((position - 2) * this.waitlistInterval);
} else {
// Fallback to old calculation if addedAt is not available
estimatedWaitSeconds = (position - 1) * this.waitlistInterval;
}
expectedTime = new Date(Date.now() + (estimatedWaitSeconds * 1000));
}
// Customize message based on preset type
const isControlNetPreset = waitlistEntry.type === 'controlnet_preset';
const icon = isControlNetPreset ? 'βοΈ' : 'π';
const itemType = isControlNetPreset ? 'ControlNet preset' : 'Prompt';
let message = `${icon} ${itemType} added to queue: "${waitlistEntry.prompt}"\n\n`;
if (position === 1) {
message += `π― Position: #${position} (next to be processed)\n`;
message += `β±οΈ Expected processing: within ${this.waitlistInterval} seconds\n`;
message += `βοΈ Current interval: ${this.waitlistInterval}s`;
} else {
message += `π Position: #${position} of ${queueLength}\n`;
// Show seconds if less than 60 seconds, otherwise show minutes
if (estimatedWaitSeconds < 60) {
const displaySeconds = Math.max(0, Math.ceil(estimatedWaitSeconds));
message += `β³ Estimated wait: ~${displaySeconds} second${displaySeconds !== 1 ? 's' : ''}\n`;
} else {
const estimatedWaitMinutes = Math.ceil(estimatedWaitSeconds / 60);
message += `β³ Estimated wait: ~${estimatedWaitMinutes} minute${estimatedWaitMinutes !== 1 ? 's' : ''}\n`;
}
message += `π Expected processing: ${expectedTime.toLocaleTimeString('de-DE', { hour12: false })}\n`;
message += `βοΈ Current interval: ${this.waitlistInterval}s`;
}
this.telegramBot.sendMessage(chatId, message);
console.log(`π± Sent queue status to ${waitlistEntry.from}: position ${position}/${queueLength}`);
}
sendPromptAppliedFeedback(chatId, prompt, from) {
if (!this.telegramBot) return;
const timestamp = new Date().toLocaleString();
const message = `β
Your prompt has been applied!\n\n` +
`π¨ "${prompt}"\n\n` +
`β° Applied at: ${timestamp}\n\n` +
`The fluid simulation is now using your prompt. Enjoy! π`;
this.telegramBot.sendMessage(chatId, message);
console.log(`π± Sent application confirmation to ${from}`);
}
sendToPublicGroup(waitlistEntry) {
if (!this.telegramBot) return;
const position = this.telegramWaitlist.findIndex(item => item.id === waitlistEntry.id) + 1;
const queueLength = this.telegramWaitlist.length;
// Use the same improved calculation as in sendQueueStatusFeedback
let estimatedWaitSeconds = 0;
let expectedTime = new Date();
if (position === 1) {
// First in queue - will be processed within the current interval
estimatedWaitSeconds = 0;
expectedTime = new Date(Date.now() + (this.waitlistInterval * 1000));
} else {
// Calculate based on when this item will actually be processed
const firstItem = this.telegramWaitlist[0];
if (firstItem && firstItem.addedAt) {
const firstItemWaitTime = (Date.now() - firstItem.addedAt) / 1000;
const remainingTimeForFirst = Math.max(0, this.waitlistInterval - firstItemWaitTime);
estimatedWaitSeconds = remainingTimeForFirst + ((position - 2) * this.waitlistInterval);
} else {
// Fallback to old calculation if addedAt is not available
estimatedWaitSeconds = (position - 1) * this.waitlistInterval;
}
expectedTime = new Date(Date.now() + (estimatedWaitSeconds * 1000));
}
// Customize message based on preset type
const isControlNetPreset = waitlistEntry.type === 'controlnet_preset';
const icon = isControlNetPreset ? 'βοΈ' : 'π¨';
const itemType = isControlNetPreset ? 'ControlNet preset' : 'prompt';
let message = `${icon} New ${itemType} in queue: "${waitlistEntry.prompt}"\n`;
message += `π€ From: ${waitlistEntry.from}\n`;
message += `π Position: #${position} of ${queueLength}\n`;
if (position === 1) {
message += `β±οΈ Processing: within ${this.waitlistInterval} seconds\n`;
} else {
// Show seconds if less than 60 seconds, otherwise show minutes
if (estimatedWaitSeconds < 60) {
const displaySeconds = Math.max(0, Math.ceil(estimatedWaitSeconds));
message += `β³ Estimated wait: ~${displaySeconds} second${displaySeconds !== 1 ? 's' : ''}\n`;
} else {
const estimatedWaitMinutes = Math.ceil(estimatedWaitSeconds / 60);
message += `β³ Estimated wait: ~${estimatedWaitMinutes} minute${estimatedWaitMinutes !== 1 ? 's' : ''}\n`;
}
message += `π Expected processing: ${expectedTime.toLocaleTimeString('de-DE', { hour12: false })}\n`;
}
message += `βοΈ Interval: ${this.waitlistInterval}s`;
// Send to public group using channel username
this.telegramBot.sendMessage('@diffusionprompts', message).catch(error => {
console.error('β Failed to send to public group:', error.message);
});
console.log(`π’ Sent to public group: "${waitlistEntry.prompt}" from ${waitlistEntry.from}`);
}
updateWaitlistInterval(newInterval) {
this.waitlistInterval = newInterval;
console.log(`π± Updated waitlist interval to ${newInterval} seconds`);
// Restart processing timer with new interval
if (this.processingTimer) {
this.stopTelegramProcessing();
if (this.telegramWaitlist.length > 0) {
this.startTelegramProcessing();
}
}
}
startTelegramProcessing() {
if (this.processingTimer) return; // Already running
const interval = this.waitlistInterval * 1000; // Convert to milliseconds
this.processingTimer = setInterval(() => {
this.processNextTelegramPrompt();
}, interval);
console.log(`π± Started server-side Telegram processing timer (${this.waitlistInterval}s intervals)`);
}
stopTelegramProcessing() {
if (this.processingTimer) {
clearInterval(this.processingTimer);
this.processingTimer = null;
console.log('π± Stopped server-side Telegram processing timer');
}
}
processNextTelegramPrompt() {
if (this.telegramWaitlist.length === 0) {
this.stopTelegramProcessing();
return;
}
const nextItem = this.telegramWaitlist.shift(); // Remove first item (FIFO)
console.log(`π± Server processing: "${nextItem.prompt}" from ${nextItem.from} (type: ${nextItem.type || 'prompt'})`);
// Send apply message to all connected clients
const applyMessage = {
type: nextItem.type === 'controlnet_preset' ? 'apply_controlnet_preset' : 'apply_telegram_prompt',
...nextItem // Include all the original data
};
this.broadcastToClients(applyMessage);
console.log(`π± Sent apply message to clients for: "${nextItem.prompt}"`);
}
updateTelegramToken(newToken) {
TELEGRAM_BOT_TOKEN = newToken || '';
console.log(`π± Updated Telegram bot token: ${newToken && newToken.trim() ? 'Token set' : 'Token cleared'}`);
// Stop current bot first
this.stopTelegramBot();
// Start bot with new token if provided and not empty
if (newToken && newToken.trim()) {
this.startTelegramBot();
}
}
removeFromWaitlist(promptId) {
const index = this.telegramWaitlist.findIndex(item => item.id === promptId);
if (index !== -1) {
const removed = this.telegramWaitlist.splice(index, 1)[0];
console.log(`π± Removed from server waitlist: "${removed.prompt}" from ${removed.from}`);
return removed;
}
return null;
}
removeFromWaitlistByPreset(presetName, chatId) {
const index = this.telegramWaitlist.findIndex(item =>
item.type === 'controlnet_preset' &&
item.presetKey === presetName &&
item.chatId === chatId
);
if (index !== -1) {
const removed = this.telegramWaitlist.splice(index, 1)[0];
console.log(`π± Removed ControlNet preset from server waitlist: "${removed.presetName}" from ${removed.from}`);
return removed;
}
return null;
}
sendControlNetPresetAppliedFeedback(chatId, presetName, presetDescription, from) {
if (!this.telegramBot) return;
const timestamp = new Date().toLocaleString();
const message = `β
**${presetName}** preset has been applied!\n\n` +
`βοΈ ${presetDescription}\n\n` +
`β° Applied at: ${timestamp}\n\n` +
`The fluid simulation parameters have been updated! π`;
this.telegramBot.sendMessage(chatId, message, { parse_mode: 'Markdown' });
console.log(`π± Sent ControlNet preset application confirmation to ${from}`);
}
sendPromptPresetAppliedFeedback(chatId, presetName, prompt, from) {
if (!this.telegramBot) return;
const timestamp = new Date().toLocaleString();
const message = `β
**${presetName}** preset applied!\n\n` +
`π¨ "${prompt}"\n\n` +
`β° Applied at: ${timestamp}\n\n` +
'The fluid simulation is now using this visual theme! π';
this.telegramBot.sendMessage(chatId, message, { parse_mode: 'Markdown' });
console.log(`π± Sent prompt preset application confirmation to ${from}`);
}
startTelegramBot() {
// Check if token is provided before attempting to start
if (!TELEGRAM_BOT_TOKEN || TELEGRAM_BOT_TOKEN.trim() === '') {
console.log('π± Telegram bot token not provided - Telegram functionality disabled');
return;
}
try {
this.telegramBot = new TelegramBot(TELEGRAM_BOT_TOKEN, { polling: true });
console.log('π± Telegram bot started successfully - ready to receive messages');
// Handle text messages
this.telegramBot.on('message', (msg) => {
const chatId = msg.chat.id;
const messageText = msg.text;
// Skip if it's a command (starts with /)
if (messageText && !messageText.startsWith('/')) {
console.log(`π± Telegram message from ${msg.from.first_name || 'Unknown'}: ${messageText}`);
// Add to server-side waitlist tracking
const waitlistEntry = {
prompt: messageText,
from: msg.from.first_name || 'Unknown User',
chatId: chatId,
timestamp: new Date().toLocaleString(),
id: Date.now() + Math.random(),
addedAt: Date.now() // Add timestamp for accurate wait calculations
};
this.telegramWaitlist.push(waitlistEntry);
// Send queue status feedback
this.sendQueueStatusFeedback(chatId, waitlistEntry);
// Also send to public group
this.sendToPublicGroup(waitlistEntry);
// Start processing if this is the first item
if (this.telegramWaitlist.length === 1 && !this.processingTimer) {
this.startTelegramProcessing();
}
}
});
// Handle /start command
this.telegramBot.onText(/\/start/, (msg) => {
const chatId = msg.chat.id;
this.telegramBot.sendMessage(chatId,
'π Welcome to Diffusion Prompt Bot!\n\n' +
'Send me any text message and I\'ll use it as a prompt for the fluid simulation.\n\n' +
'Commands:\n' +
'β’ /preset - View and apply preset configurations\n' +
'β’ Just type your prompt and send it!\n\n' +
'Examples:\n' +
'β’ "cosmic nebula with swirling colors"\n' +
'β’ "underwater coral reef scene"\n' +
'β’ "abstract geometric patterns"\n\n' +
'Let\'s create something amazing! π¨'
);
});
// Handle /preset command
this.telegramBot.onText(/\/preset/, (msg) => {
const chatId = msg.chat.id;
const keyboard = {
inline_keyboard: [
[
{ text: 'π¨ Prompt Presets', callback_data: 'show_prompt_presets' },
{ text: 'βοΈ ControlNet Presets', callback_data: 'show_controlnet_presets' }
]
]
};
this.telegramBot.sendMessage(chatId,
'ποΈ **Preset Categories**\n\n' +
'**Prompt Presets**: Ready-made visual themes and styles\n' +
'**ControlNet Presets**: Parameter configurations for different control modes\n\n' +
'Choose a category to see available presets:',
{
reply_markup: keyboard,
parse_mode: 'Markdown'
}
);
});
// Handle callback queries for preset interactions
this.telegramBot.on('callback_query', (callbackQuery) => {
const msg = callbackQuery.message;
const chatId = msg.chat.id;
const data = callbackQuery.data;
// Answer the callback query to remove loading state
this.telegramBot.answerCallbackQuery(callbackQuery.id);
if (data === 'show_prompt_presets') {
this.sendPromptPresets(chatId);
} else if (data === 'show_controlnet_presets') {
this.sendControlNetPresets(chatId);
} else if (data.startsWith('apply_prompt_')) {
const presetIndex = parseInt(data.split('_')[2]);
this.applyPromptPreset(chatId, presetIndex);
} else if (data.startsWith('apply_controlnet_')) {
const presetKey = data.split('_')[2];
this.applyControlNetPreset(chatId, presetKey);
} else if (data === 'back_to_presets') {
// Show main preset menu again
const keyboard = {
inline_keyboard: [
[
{ text: 'π¨ Prompt Presets', callback_data: 'show_prompt_presets' },
{ text: 'βοΈ ControlNet Presets', callback_data: 'show_controlnet_presets' }
]
]
};
this.telegramBot.editMessageText(
'ποΈ **Preset Categories**\n\n' +
'**Prompt Presets**: Ready-made visual themes and styles\n' +
'**ControlNet Presets**: Parameter configurations for different control modes\n\n' +
'Choose a category to see available presets:',
{
chat_id: chatId,
message_id: msg.message_id,
reply_markup: keyboard,
parse_mode: 'Markdown'
}
);
}
});
// Handle errors
this.telegramBot.on('error', (error) => {
console.error('β Telegram Bot error:', error);
});
console.log('π± Telegram Bot started successfully');
} catch (error) {
console.error('β Failed to start Telegram Bot:', error);
console.log('β οΈ Continuing without Telegram Bot functionality...');
}
}
stopTelegramBot() {
if (this.telegramBot) {
try {
this.telegramBot.stopPolling();
this.telegramBot = null;
console.log('π± Telegram Bot stopped successfully');
} catch (error) {
console.error('β Error stopping Telegram Bot:', error);
}
}
}
handleOSCMessage(msg) {
const [address, ...args] = msg;
const value = args.length === 1 ? args[0] : args;
// Throttle messages for performance
const now = Date.now();
const lastTime = this.lastMessageTime[address] || 0;
if (now - lastTime < this.throttleInterval) {
// Skip this message - too frequent
return;
}
this.lastMessageTime[address] = now;
console.log(`π¨ OSC: ${address} = ${value}`);
const mapping = this.oscMap[address];
if (!mapping) {
console.log(`β οΈ Unknown OSC address: ${address}`);
return;
}
// Process the message based on type
let processedValue = value;
if (mapping.type === 'slider') {
// Normalize value to 0-1 range, then scale to parameter range
const normalizedValue = Math.max(0, Math.min(1, value));
if (mapping.min !== undefined && mapping.max !== undefined) {
processedValue = mapping.min + (normalizedValue * (mapping.max - mapping.min));
}
} else if (mapping.type === 'toggle') {
processedValue = value > 0;
} else if (mapping.type === 'color') {
// Handle RGB color messages (expects array [r, g, b] with values 0-1)
if (Array.isArray(value) && value.length >= 3) {
processedValue = {
r: Math.max(0, Math.min(1, value[0])),
g: Math.max(0, Math.min(1, value[1])),
b: Math.max(0, Math.min(1, value[2]))
};
} else {
console.log(`β οΈ Invalid color value: ${value}. Expected [r, g, b] array.`);
return;
}
} else if (mapping.type === 'position') {
// Handle splat position trigger (expects array [x, y] or [x, y, force])
if (Array.isArray(value) && value.length >= 2) {
processedValue = {
x: Math.max(0, Math.min(1, value[0])),
y: Math.max(0, Math.min(1, value[1])),
force: value.length >= 3 ? Math.max(0.1, Math.min(3.0, value[2])) : 1.0
};
} else {
console.log(`β οΈ Invalid position value: ${value}. Expected [x, y] or [x, y, force] array.`);
return;
}
} else if (mapping.type === 'xy_pad') {
// Handle TouchOSC XY pad format - velocity-based drawing
const channel = mapping.channel;
// TouchOSC sends two separate arguments: args[0] = y, args[1] = x (flipped for multixy)
if (args.length >= 2 && typeof args[0] === 'number' && typeof args[1] === 'number') {
const x = 1.0 - Math.max(0, Math.min(1, args[1])); // Flipped X: use args[1] and invert (1-x)
const y = Math.max(0, Math.min(1, args[0])); // Flipped: use args[0] for Y
// Send velocity-based drawing only (old parameter system removed)
this.handleVelocityDrawing(channel, x, y);
console.log(`π― TouchOSC XY Pad ${channel}: X=${x.toFixed(3)}, Y=${y.toFixed(3)} (velocity drawing only)`);
return;
} else if (Array.isArray(value) && value.length >= 2) {
// Fallback: XY pad sending [y, x] array (flipped for multixy)
const x = 1.0 - Math.max(0, Math.min(1, value[1])); // Flipped X: use value[1] and invert (1-x)
const y = Math.max(0, Math.min(1, value[0])); // Flipped: use value[0] for Y
// Send velocity-based drawing only (old parameter system removed)
this.handleVelocityDrawing(channel, x, y);
console.log(`π― TouchOSC XY Pad ${channel}: X=${x.toFixed(3)}, Y=${y.toFixed(3)} (velocity drawing only)`);
return;
} else {
console.log(`β οΈ TouchOSC XY Pad ${channel}: Expected 2 args, got ${args.length}: [${args.join(', ')}]`);
return;
}
}
// Send to all connected WebSocket clients
const message = {
type: 'osc_message',
address: address,
parameter: mapping.param || null,
action: mapping.action || null,
value: processedValue,
originalValue: value,
mappingType: mapping.type
};
this.broadcastToClients(message);
}
broadcastToClients(message) {
const messageStr = JSON.stringify(message);
this.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(messageStr);
}
});
}
printStartupInfo() {
console.log(`
π Fluid OSC Server Started
============================
π Network IP: ${this.networkIP}
ποΈ OSC Port: ${OSC_PORT}
π WebSocket: ${WEBSOCKET_PORT}
π± TouchOSC Setup:
Host: ${this.networkIP}
Port (outgoing): ${OSC_PORT}
π Website Setup:
Upload fluid files to FTP
Access via: http://your-ftp-domain.com
OSC will auto-connect to: ${this.networkIP}:${WEBSOCKET_PORT}
π Available OSC Addresses: ${Object.keys(this.oscMap).length} total
π‘ Examples: