Repository navigation
Expand file tree
/
Copy pathproject.js
More file actions
2801 lines (2447 loc) Β· 93.8 KB
/
Copy pathproject.js
File metadata and controls
2801 lines (2447 loc) Β· 93.8 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
/**
* Disk Scheduling Simulator & OS Storage Architecture Lab - Core Engine
* Implements:
* - Classical OS Schedulers: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK, F-SCAN, N-Step SCAN, User Custom
* - Linux Kernel Schedulers: Deadline Scheduler, CFQ (Completely Fair Queuing), NOOP / None
* - Storage Architecture: Mechanical Magnetic HDD vs. NAND Flash NVMe SSD
* - Visualizers: 1D Track, 2D Graph, 2D Platter, 3D Multi-Platter Cylinder Stack, SSD Flash Grid, Linux Queues
* - In-Browser Custom JavaScript Algorithm Code Sandbox
* - Interactive Drag-to-Scrub Timeline, Web Speech Voice Narration, and Spatial Web Audio
*/
// ==========================================================================
// DOM Element References
// ==========================================================================
const canvas = document.getElementById('diskCanvas');
const ctx = canvas.getContext('2d');
const canvasWrapper = document.getElementById('canvasWrapper');
const canvasTooltip = document.getElementById('canvasTooltip');
const clickToInjectBanner = document.getElementById('clickToInjectBanner');
const deviceHddBtn = document.getElementById('deviceHddBtn');
const deviceSsdBtn = document.getElementById('deviceSsdBtn');
const requestsInput = document.getElementById('requests');
const headInput = document.getElementById('head');
const maxCylinderInput = document.getElementById('maxCylinder');
const algorithmSelect = document.getElementById('algorithm');
const nStepGroup = document.getElementById('nStepGroup');
const nStepSizeInput = document.getElementById('nStepSize');
const directionGroup = document.getElementById('directionGroup');
const presetSelect = document.getElementById('presetSelect');
const requestCountBadge = document.getElementById('requestCountBadge');
const liveStreamToggleBtn = document.getElementById('liveStreamToggleBtn');
const togglePhysicsBtn = document.getElementById('togglePhysicsBtn');
const physicsDrawer = document.getElementById('physicsDrawer');
const rpmSelect = document.getElementById('rpmSelect');
const trackSeekTimeInput = document.getElementById('trackSeekTime');
const chsCyl = document.getElementById('chsCyl');
const chsHead = document.getElementById('chsHead');
const chsSec = document.getElementById('chsSec');
const chsLbaResult = document.getElementById('chsLbaResult');
const startBtn = document.getElementById('startBtn');
const compareBtn = document.getElementById('compareBtn');
const randomBtn = document.getElementById('randomBtn');
const voiceToggleBtn = document.getElementById('voiceToggleBtn');
const voiceIcon = document.getElementById('voiceIcon');
const audioToggleBtn = document.getElementById('audioToggleBtn');
const audioIcon = document.getElementById('audioIcon');
const themeToggleBtn = document.getElementById('themeToggleBtn');
const themeIcon = document.getElementById('themeIcon');
const exportMenuBtn = document.getElementById('exportMenuBtn');
const exportMenu = document.getElementById('exportMenu');
const exportSolutionBtn = document.getElementById('exportSolutionBtn');
const exportCsvBtn = document.getElementById('exportCsvBtn');
const exportPngBtn = document.getElementById('exportPngBtn');
const timelineScrubber = document.getElementById('timelineScrubber');
const timelineStepBadge = document.getElementById('timelineStepBadge');
const playBtn = document.getElementById('playBtn');
const pauseBtn = document.getElementById('pauseBtn');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const jumpStartBtn = document.getElementById('jumpStartBtn');
const jumpEndBtn = document.getElementById('jumpEndBtn');
const resetBtn = document.getElementById('resetBtn');
const speedSlider = document.getElementById('speedSlider');
const speedValue = document.getElementById('speedValue');
const telemetryCardTitle = document.getElementById('telemetryCardTitle');
const seekMetricLabel = document.getElementById('seekMetricLabel');
const seekMetricUnit = document.getElementById('seekMetricUnit');
const totalSeekElem = document.getElementById('totalSeek');
const totalSeekTimeMsElem = document.getElementById('totalSeekTimeMs');
const rotDelayMsElem = document.getElementById('rotDelayMs');
const totalAccessTimeMsElem = document.getElementById('totalAccessTimeMs');
const reversalsCountElem = document.getElementById('reversalsCount');
const currentStepDisplayElem = document.getElementById('currentStepDisplay');
const totalStepsElem = document.getElementById('totalSteps');
const progressBarFill = document.getElementById('progressBarFill');
const tabTrack = document.getElementById('tabTrack');
const tabGraph = document.getElementById('tabGraph');
const tabPlatter = document.getElementById('tabPlatter');
const tab3DStack = document.getElementById('tab3DStack');
const tabSsd = document.getElementById('tabSsd');
const tabLinux = document.getElementById('tabLinux');
const tabSandbox = document.getElementById('tabSandbox');
const tabComparison = document.getElementById('tabComparison');
const tabQuiz = document.getElementById('tabQuiz');
const viewModeBadge = document.getElementById('viewModeBadge');
const sandboxOverlay = document.getElementById('sandboxOverlay');
const sandboxCodeEditor = document.getElementById('sandboxCodeEditor');
const sandboxConsoleLog = document.getElementById('sandboxConsoleLog');
const sandboxResetBtn = document.getElementById('sandboxResetBtn');
const sandboxRunBtn = document.getElementById('sandboxRunBtn');
const quizOverlay = document.getElementById('quizOverlay');
const quizQuestionText = document.getElementById('quizQuestionText');
const quizScenarioDetails = document.getElementById('quizScenarioDetails');
const quizOptionsGrid = document.getElementById('quizOptionsGrid');
const quizFeedbackBox = document.getElementById('quizFeedbackBox');
const quizFeedbackText = document.getElementById('quizFeedbackText');
const quizNextBtn = document.getElementById('quizNextBtn');
const quizScoreElem = document.getElementById('quizScore');
const quizTotalElem = document.getElementById('quizTotal');
const quizStreakBadge = document.getElementById('quizStreakBadge');
const algoTitle = document.getElementById('algoTitle');
const algoTag = document.getElementById('algoTag');
const algorithmDescriptionElem = document.getElementById('algorithmDescription');
const algoSpecsGrid = document.getElementById('algoSpecsGrid');
const specComplexity = document.getElementById('specComplexity');
const specStarvation = document.getElementById('specStarvation');
const specDirectional = document.getElementById('specDirectional');
const stepDetailsElem = document.getElementById('stepDetails');
const serviceOrderChipsElem = document.getElementById('serviceOrderChips');
// ==========================================================================
// Application State
// ==========================================================================
let simulationState = null;
let comparisonState = null;
let deviceMode = 'HDD'; // 'HDD' | 'SSD'
let currentView = 'track'; // 'track' | 'graph' | 'platter' | 'stack3d' | 'ssd' | 'linux' | 'sandbox' | 'comparison' | 'quiz'
let currentStep = -1;
let isPlaying = false;
let animationSpeed = 3;
let soundEnabled = true;
let voiceEnabled = false;
let audioCtx = null;
let currentTheme = localStorage.getItem('disk_sim_theme') || 'dark';
let nodeHitboxes = [];
let platterAngle = 0;
let isLiveStreaming = false;
let liveStreamTimer = null;
// Quiz State
let quizScore = 0;
let quizTotal = 0;
let quizStreak = 0;
let currentQuizData = null;
// Default Sandbox Code Template
const defaultSandboxCode = `/**
* Custom Scheduling Algorithm
* @param {number[]} requests - Array of cylinder requests
* @param {number} head - Initial head position
* @param {number} maxCylinder - Maximum cylinder limit
* @returns {object} { order: number[], totalSeek: number, steps: Array }
*/
function myCustomScheduler(requests, head, maxCylinder) {
const order = [];
const steps = [];
let totalSeek = 0;
let current = head;
// Example: Sort requests by distance to head (Greedy SSTF variant)
const pending = [...requests];
while (pending.length > 0) {
pending.sort((a, b) => Math.abs(a - current) - Math.abs(b - current));
const next = pending.shift();
const seek = Math.abs(next - current);
totalSeek += seek;
steps.push({
from: current,
to: next,
seek: seek,
cumulative: totalSeek,
explanation: \`Custom seek: \${current} β \${next} (\${seek} cyl)\`
});
order.push(next);
current = next;
}
return { order, totalSeek, steps };
}`;
// Algorithm Theoretical Profiles
const algorithmProfiles = {
FCFS: {
name: "First-Come, First-Served",
tag: "FCFS",
complexity: "O(N)",
starvation: "No (Fair)",
directional: "No",
description: "Processes disk requests in the exact arrival order. Completely fair with zero starvation, but often suffers from excessive seek times when requests are scattered."
},
SSTF: {
name: "Shortest Seek Time First",
tag: "SSTF",
complexity: "O(NΒ²)",
starvation: "Yes (High)",
directional: "No",
description: "Greedily selects the request closest to current head position. Drastically reduces total seek time, but distant requests near boundaries can starve indefinitely under continuous traffic."
},
SCAN: {
name: "SCAN (Elevator Algorithm)",
tag: "SCAN",
complexity: "O(N log N)",
starvation: "No",
directional: "Yes",
description: "The head sweeps continuously in one direction servicing requests until reaching the extreme disk boundary (0 or Max), then reverses. Balances wait times and prevents starvation."
},
CSCAN: {
name: "Circular SCAN (C-SCAN)",
tag: "C-SCAN",
complexity: "O(N log N)",
starvation: "No",
directional: "Yes",
description: "Sweeps in one direction servicing requests to the boundary, then performs an immediate rapid return to the opposite boundary without servicing. Provides more uniform wait times across all cylinders."
},
LOOK: {
name: "LOOK (Optimized Elevator)",
tag: "LOOK",
complexity: "O(N log N)",
starvation: "No",
directional: "Yes",
description: "An optimization of SCAN: the head only travels as far as the furthest requested cylinder in the current direction and reverses immediately without traveling to empty disk limits."
},
CLOOK: {
name: "Circular LOOK (C-LOOK)",
tag: "C-LOOK",
complexity: "O(N log N)",
starvation: "No",
directional: "Yes",
description: "An optimization of C-SCAN: the head sweeps to the highest requested cylinder, then jumps directly to the lowest pending requested cylinder without touching cylinder 0 or Max."
},
FSCAN: {
name: "F-SCAN (Freeze-Queue SCAN)",
tag: "F-SCAN",
complexity: "O(N log N)",
starvation: "No",
directional: "Yes",
description: "Uses two sub-queues. When a scan begins, all existing requests are frozen in Queue 1 and serviced with SCAN. Any new arriving requests are buffered into Queue 2, completely eliminating dynamic starvation."
},
NSTEPSCAN: {
name: "N-Step SCAN (Batched SCAN)",
tag: "N-STEP",
complexity: "O(N log N)",
starvation: "No",
directional: "Yes",
description: "Segments the request queue into sub-batches of size N. Each batch is serviced completely using SCAN before advancing to the next batch, preventing arm stickiness."
},
DEADLINE: {
name: "Linux Deadline Scheduler",
tag: "DEADLINE",
complexity: "O(N log N)",
starvation: "No (Guaranteed)",
directional: "Yes",
description: "Maintains separate Read and Write FIFO queues with hard expiration deadlines (500ms for Reads, 5000ms for Writes) alongside a sorted sector queue. Prioritizes expired reads to prevent process stalls."
},
CFQ: {
name: "Linux CFQ (Completely Fair Queuing)",
tag: "CFQ",
complexity: "O(P * N)",
starvation: "No",
directional: "Round-Robin",
description: "Allocates synchronous I/O time slices to competing processes (e.g., MySQL vs Backup vs Player), ensuring fair storage bandwidth sharing without letting any single process monopolize the disk."
},
NOOP: {
name: "Linux NOOP / None (NVMe SSD Optimal)",
tag: "NOOP",
complexity: "O(N)",
starvation: "No",
directional: "No",
description: "Performs simple FIFO request merging without sector sorting. Zero CPU overhead; standard for modern NVMe SSDs and Flash arrays where mechanical seek latency is non-existent."
},
USER_ORDER: {
name: "User Input Sequence",
tag: "CUSTOM",
complexity: "O(N)",
starvation: "No",
directional: "No",
description: "Executes disk requests in the exact sequence provided by the user, enabling custom step analysis and verification."
},
SANDBOX: {
name: "User Sandbox Algorithm",
tag: "SANDBOX",
complexity: "Dynamic",
starvation: "Custom",
directional: "Custom",
description: "Custom scheduling algorithm written by the user in the JavaScript Code Sandbox."
}
};
// ==========================================================================
// Theme Switcher & Device Mode Handlers
// ==========================================================================
function applyTheme(theme) {
currentTheme = theme;
document.documentElement.setAttribute('data-theme', theme);
themeIcon.textContent = theme === 'light' ? 'βοΈ' : 'π';
themeToggleBtn.title = `Switch to ${theme === 'light' ? 'Dark' : 'Light'} Theme [T]`;
localStorage.setItem('disk_sim_theme', theme);
renderCurrentView();
}
themeToggleBtn.addEventListener('click', () => {
applyTheme(currentTheme === 'dark' ? 'light' : 'dark');
});
// Device Mode (HDD vs SSD)
deviceHddBtn.addEventListener('click', () => setDeviceMode('HDD'));
deviceSsdBtn.addEventListener('click', () => setDeviceMode('SSD'));
function setDeviceMode(mode) {
deviceMode = mode;
deviceHddBtn.classList.toggle('active', mode === 'HDD');
deviceSsdBtn.classList.toggle('active', mode === 'SSD');
if (mode === 'SSD') {
algorithmSelect.value = 'NOOP';
telemetryCardTitle.textContent = 'Flash Memory & Bus Telemetry';
seekMetricLabel.textContent = 'Random Access IOPS';
seekMetricUnit.textContent = 'ops';
switchView('ssd');
} else {
telemetryCardTitle.textContent = 'Performance & Latency Telemetry';
seekMetricLabel.textContent = 'Total Head Movement';
seekMetricUnit.textContent = 'cyl';
switchView('track');
}
if (simulationState) runSingleSimulation();
}
// ==========================================================================
// Web Audio Synthesizer & Web Speech API Voice Narration
// ==========================================================================
function initAudio() {
if (!audioCtx) {
const AudioContext = window.AudioContext || window.webkitAudioContext;
if (AudioContext) {
audioCtx = new AudioContext();
}
}
}
function playStepSound(seekDistance, maxCylinder, targetCylinder) {
if (!soundEnabled) return;
try {
initAudio();
if (!audioCtx || audioCtx.state === 'suspended') {
audioCtx?.resume();
}
if (!audioCtx) return;
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
const panner = audioCtx.createStereoPanner ? audioCtx.createStereoPanner() : null;
const ratio = Math.min(1, seekDistance / (maxCylinder || 200));
const freq = deviceMode === 'SSD' ? 880 : 540 - ratio * 260;
osc.type = deviceMode === 'SSD' ? 'triangle' : 'sine';
osc.frequency.setValueAtTime(freq, audioCtx.currentTime);
gain.gain.setValueAtTime(0.08, audioCtx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + 0.12);
if (panner && targetCylinder !== undefined) {
// Pan stereo based on cylinder position (-1.0 to +1.0)
const panVal = ((targetCylinder / (maxCylinder || 200)) * 2) - 1;
panner.pan.setValueAtTime(Math.max(-1, Math.min(1, panVal)), audioCtx.currentTime);
osc.connect(gain);
gain.connect(panner);
panner.connect(audioCtx.destination);
} else {
osc.connect(gain);
gain.connect(audioCtx.destination);
}
osc.start();
osc.stop(audioCtx.currentTime + 0.12);
} catch (e) {
// Graceful audio fallback
}
}
function speakStep(stepText) {
if (!voiceEnabled || !('speechSynthesis' in window)) return;
window.speechSynthesis.cancel();
const utter = new SpeechSynthesisUtterance(stepText);
utter.rate = 1.2;
utter.pitch = 1.0;
window.speechSynthesis.speak(utter);
}
voiceToggleBtn.addEventListener('click', () => {
voiceEnabled = !voiceEnabled;
voiceIcon.textContent = voiceEnabled ? 'π£οΈ' : 'ποΈ';
voiceToggleBtn.title = voiceEnabled ? 'Voice Narration Enabled [V]' : 'Voice Narration Disabled [V]';
if (!voiceEnabled && 'speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
});
// ==========================================================================
// CHS to LBA Addressing Calculator
// ==========================================================================
function updateChsCalculation() {
const c = parseInt(chsCyl.value, 10) || 0;
const h = parseInt(chsHead.value, 10) || 0;
const s = parseInt(chsSec.value, 10) || 1;
const headsPerCyl = 4;
const sectorsPerTrack = 63;
// LBA = (C * HeadsPerCyl + H) * SectorsPerTrack + (S - 1)
const lba = (c * headsPerCyl + h) * sectorsPerTrack + (s - 1);
chsLbaResult.textContent = `LBA: ${lba.toLocaleString()}`;
}
chsCyl.addEventListener('input', updateChsCalculation);
chsHead.addEventListener('input', updateChsCalculation);
chsSec.addEventListener('input', updateChsCalculation);
// ==========================================================================
// Hardware Physics Engine
// ==========================================================================
function getHardwareParams() {
const rpm = parseInt(rpmSelect.value, 10) || 7200;
const trackSeekRate = parseFloat(trackSeekTimeInput.value) || 0.15;
return { rpm, trackSeekRate };
}
function calculateHardwareLatency(totalSeek, requestCount) {
if (deviceMode === 'SSD') {
// SSD: Zero seek, ~0.04ms flash controller latency
const totalAccessTime = (0.04 * Math.max(1, requestCount)).toFixed(2);
return {
rpm: 0,
rotDelayPerReq: '0.00',
totalSeekTime: '0.00',
totalRotDelay: '0.00',
totalAccessTime
};
}
const { rpm, trackSeekRate } = getHardwareParams();
const rotDelayPerReq = (0.5 * (60 / rpm)) * 1000;
const totalRotDelay = rotDelayPerReq * Math.max(1, requestCount);
const totalSeekTime = requestCount > 0 ? (2.0 * requestCount) + (totalSeek * trackSeekRate) : 0;
const totalTransferTime = 0.05 * Math.max(1, requestCount);
const totalAccessTime = totalSeekTime + totalRotDelay + totalTransferTime;
return {
rpm,
rotDelayPerReq: rotDelayPerReq.toFixed(2),
totalSeekTime: totalSeekTime.toFixed(2),
totalRotDelay: totalRotDelay.toFixed(2),
totalAccessTime: totalAccessTime.toFixed(2)
};
}
togglePhysicsBtn.addEventListener('click', () => {
const isHidden = physicsDrawer.style.display === 'none';
physicsDrawer.style.display = isHidden ? 'block' : 'none';
togglePhysicsBtn.textContent = isHidden
? 'βοΈ Hardware Drive Physics (RPM & Latency) β΄'
: 'βοΈ Hardware Drive Physics (RPM & Latency) βΎ';
});
rpmSelect.addEventListener('change', () => {
if (simulationState) updateUI(simulationState, currentStep);
});
trackSeekTimeInput.addEventListener('input', () => {
if (simulationState) updateUI(simulationState, currentStep);
});
// ==========================================================================
// Helper Utilities & Input Parsing
// ==========================================================================
function parseRequests(str) {
return str
.split(',')
.map(x => parseInt(x.trim(), 10))
.filter(x => !isNaN(x));
}
function clampRequests(requests, maxCylinder) {
return requests.filter(r => r >= 0 && r <= maxCylinder);
}
function getSelectedDirection() {
const checked = document.querySelector('input[name="direction"]:checked');
return checked ? checked.value : 'high';
}
function updateRequestBadge() {
const reqs = parseRequests(requestsInput.value);
requestCountBadge.textContent = `${reqs.length} items`;
}
requestsInput.addEventListener('input', updateRequestBadge);
// Preset Workload Loader
presetSelect.addEventListener('change', (e) => {
const val = e.target.value;
if (val === 'silberschatz') {
requestsInput.value = "98, 183, 37, 122, 14, 124, 65, 67";
headInput.value = "53";
maxCylinderInput.value = "199";
} else if (val === 'stallings') {
requestsInput.value = "55, 58, 39, 18, 90, 160, 150, 38, 184";
headInput.value = "100";
maxCylinderInput.value = "199";
} else if (val === 'clustered') {
requestsInput.value = "10, 12, 15, 18, 180, 185, 190, 195, 14, 188";
headInput.value = "50";
maxCylinderInput.value = "199";
} else if (val === 'extremes') {
requestsInput.value = "0, 199, 5, 195, 10, 190, 20, 180";
headInput.value = "100";
maxCylinderInput.value = "199";
}
updateRequestBadge();
presetSelect.selectedIndex = 0;
if (simulationState) runSingleSimulation();
});
// Random Workload Generator
randomBtn.addEventListener('click', () => {
const maxCyl = parseInt(maxCylinderInput.value, 10) || 199;
const count = 8;
const set = new Set();
while (set.size < count) {
set.add(Math.floor(Math.random() * (maxCyl + 1)));
}
const randomHead = Math.floor(Math.random() * (maxCyl + 1));
requestsInput.value = Array.from(set).join(', ');
headInput.value = randomHead.toString();
updateRequestBadge();
if (simulationState) runSingleSimulation();
});
// Audio Toggle
audioToggleBtn.addEventListener('click', () => {
soundEnabled = !soundEnabled;
audioIcon.textContent = soundEnabled ? 'π' : 'π';
audioToggleBtn.title = soundEnabled ? 'Sound Effects Enabled' : 'Sound Effects Muted';
});
// Algorithm Select changes
algorithmSelect.addEventListener('change', () => {
const algo = algorithmSelect.value;
const hasDirection = ['SCAN', 'CSCAN', 'LOOK', 'CLOOK', 'FSCAN', 'NSTEPSCAN', 'DEADLINE'].includes(algo);
directionGroup.style.display = hasDirection ? 'block' : 'none';
nStepGroup.style.display = algo === 'NSTEPSCAN' ? 'block' : 'none';
updateAlgoProfilePreview(algo);
});
function updateAlgoProfilePreview(algoKey) {
const prof = algorithmProfiles[algoKey] || algorithmProfiles.FCFS;
algoTitle.textContent = prof.name;
algoTag.textContent = prof.tag;
algorithmDescriptionElem.innerHTML = `<p>${prof.description}</p>`;
algoSpecsGrid.style.display = 'grid';
specComplexity.textContent = prof.complexity;
specStarvation.textContent = prof.starvation;
specDirectional.textContent = prof.directional;
}
speedSlider.addEventListener('input', (e) => {
animationSpeed = parseInt(e.target.value, 10);
speedValue.textContent = `${animationSpeed}x`;
});
// ==========================================================================
// Complete Scheduling Algorithms Suite (11 Schedulers)
// ==========================================================================
function computeReversals(steps) {
let reversals = 0;
let prevDir = 0;
for (const step of steps) {
const diff = step.to - step.from;
if (diff !== 0) {
const dir = diff > 0 ? 1 : -1;
if (prevDir !== 0 && dir !== prevDir) {
reversals++;
}
prevDir = dir;
}
}
return reversals;
}
// 1. User Order / Custom Sequence
function simulateUserOrder(requests, head) {
const order = [...requests];
const steps = [];
let totalSeek = 0;
let current = head;
for (let i = 0; i < order.length; i++) {
const seek = Math.abs(order[i] - current);
totalSeek += seek;
steps.push({
from: current,
to: order[i],
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `Raw sequence: cylinder ${current} β ${order[i]} (|${order[i]} - ${current}| = ${seek} cyl)`
});
current = order[i];
}
const reversals = computeReversals(steps);
return { order, totalSeek, steps, reversals };
}
// 2. FCFS
function fcfs(requests, head) {
const order = [...requests];
const steps = [];
let totalSeek = 0;
let current = head;
for (let i = 0; i < order.length; i++) {
const seek = Math.abs(order[i] - current);
totalSeek += seek;
steps.push({
from: current,
to: order[i],
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `FCFS Queue: Service cylinder ${order[i]} from ${current} (|${order[i]} - ${current}| = ${seek} cyl)`
});
current = order[i];
}
const reversals = computeReversals(steps);
return { order, totalSeek, steps, reversals };
}
// 3. SSTF
function sstf(requests, head) {
let remaining = [...requests];
const order = [];
const steps = [];
let totalSeek = 0;
let current = head;
while (remaining.length > 0) {
let closestIdx = 0;
let closestDist = Math.abs(remaining[0] - current);
for (let i = 1; i < remaining.length; i++) {
const dist = Math.abs(remaining[i] - current);
if (dist < closestDist) {
closestDist = dist;
closestIdx = i;
}
}
const next = remaining[closestIdx];
order.push(next);
totalSeek += closestDist;
steps.push({
from: current,
to: next,
seek: closestDist,
cumulative: totalSeek,
isBoundary: false,
explanation: `SSTF Min Seek: Picked cylinder ${next} (closest to ${current}, distance: ${closestDist} cyl). Pending: [${remaining.filter((_, i) => i !== closestIdx).join(', ')}]`
});
current = next;
remaining.splice(closestIdx, 1);
}
const reversals = computeReversals(steps);
return { order, totalSeek, steps, reversals };
}
// 4. SCAN
function scan(requests, head, maxCylinder, direction = 'high') {
const order = [];
const steps = [];
let totalSeek = 0;
let current = head;
const right = requests.filter(r => r >= head).sort((a, b) => a - b);
const left = requests.filter(r => r < head).sort((a, b) => b - a);
if (direction === 'high') {
for (const r of right) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `SCAN Moving β (High): Service cylinder ${r} from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
if (left.length > 0 && current !== maxCylinder) {
const seek = Math.abs(maxCylinder - current);
totalSeek += seek;
steps.push({
from: current,
to: maxCylinder,
seek: seek,
cumulative: totalSeek,
isBoundary: true,
explanation: `SCAN Hit End Boundary: Head reaches Max cylinder ${maxCylinder} to reverse direction (seek: ${seek} cyl)`
});
order.push(maxCylinder);
current = maxCylinder;
}
for (const r of left) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `SCAN Reversed β (Low): Service cylinder ${r} from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
} else {
const leftDesc = requests.filter(r => r <= head).sort((a, b) => b - a);
const rightAsc = requests.filter(r => r > head).sort((a, b) => a - b);
for (const r of leftDesc) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `SCAN Moving β (Low): Service cylinder ${r} from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
if (rightAsc.length > 0 && current !== 0) {
const seek = Math.abs(0 - current);
totalSeek += seek;
steps.push({
from: current,
to: 0,
seek: seek,
cumulative: totalSeek,
isBoundary: true,
explanation: `SCAN Hit Min Boundary: Head reaches cylinder 0 to reverse direction (seek: ${seek} cyl)`
});
order.push(0);
current = 0;
}
for (const r of rightAsc) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `SCAN Reversed β (High): Service cylinder ${r} from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
}
const reversals = computeReversals(steps);
return { order, totalSeek, steps, reversals };
}
// 5. C-SCAN
function cscan(requests, head, maxCylinder, direction = 'high') {
const order = [];
const steps = [];
let totalSeek = 0;
let current = head;
if (direction === 'high') {
const right = requests.filter(r => r >= head).sort((a, b) => a - b);
const left = requests.filter(r => r < head).sort((a, b) => a - b);
for (const r of right) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `C-SCAN Moving β (High): Service cylinder ${r} from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
if (left.length > 0) {
if (current !== maxCylinder) {
const seek = Math.abs(maxCylinder - current);
totalSeek += seek;
steps.push({
from: current,
to: maxCylinder,
seek: seek,
cumulative: totalSeek,
isBoundary: true,
explanation: `C-SCAN Reached Max: Travel to cylinder ${maxCylinder} before circular wrap (seek: ${seek} cyl)`
});
order.push(maxCylinder);
current = maxCylinder;
}
const jumpSeek = maxCylinder - 0;
totalSeek += jumpSeek;
steps.push({
from: current,
to: 0,
seek: jumpSeek,
cumulative: totalSeek,
isBoundary: true,
explanation: `C-SCAN Circular Wrap: Rapid return jump ${current} β 0 without servicing (seek: ${jumpSeek} cyl)`
});
order.push(0);
current = 0;
for (const r of left) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `C-SCAN Post-Wrap: Service cylinder ${r} moving β from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
}
} else {
const left = requests.filter(r => r <= head).sort((a, b) => b - a);
const right = requests.filter(r => r > head).sort((a, b) => b - a);
for (const r of left) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `C-SCAN Moving β (Low): Service cylinder ${r} from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
if (right.length > 0) {
if (current !== 0) {
const seek = Math.abs(0 - current);
totalSeek += seek;
steps.push({
from: current,
to: 0,
seek: seek,
cumulative: totalSeek,
isBoundary: true,
explanation: `C-SCAN Reached 0: Travel to cylinder 0 before circular wrap (seek: ${seek} cyl)`
});
order.push(0);
current = 0;
}
const jumpSeek = maxCylinder - 0;
totalSeek += jumpSeek;
steps.push({
from: current,
to: maxCylinder,
seek: jumpSeek,
cumulative: totalSeek,
isBoundary: true,
explanation: `C-SCAN Circular Wrap: Jump 0 β ${maxCylinder} without servicing (seek: ${jumpSeek} cyl)`
});
order.push(maxCylinder);
current = maxCylinder;
for (const r of right) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `C-SCAN Post-Wrap: Service cylinder ${r} moving β from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
}
}
const reversals = computeReversals(steps);
return { order, totalSeek, steps, reversals };
}
// 6. LOOK
function look(requests, head, direction = 'high') {
const order = [];
const steps = [];
let totalSeek = 0;
let current = head;
if (direction === 'high') {
const right = requests.filter(r => r >= head).sort((a, b) => a - b);
const left = requests.filter(r => r < head).sort((a, b) => b - a);
for (const r of right) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `LOOK Moving β (High): Service cylinder ${r} from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
for (const r of left) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `LOOK Reversing at Peak ${right[right.length - 1] || current}: Service cylinder ${r} β from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
} else {
const left = requests.filter(r => r <= head).sort((a, b) => b - a);
const right = requests.filter(r => r > head).sort((a, b) => a - b);
for (const r of left) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,
isBoundary: false,
explanation: `LOOK Moving β (Low): Service cylinder ${r} from ${current} (seek: ${seek} cyl)`
});
order.push(r);
current = r;
}
for (const r of right) {
const seek = Math.abs(r - current);
totalSeek += seek;
steps.push({
from: current,
to: r,
seek: seek,
cumulative: totalSeek,