Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1809 lines (1615 loc) · 70.8 KB
/
Copy pathapp.js
File metadata and controls
1809 lines (1615 loc) · 70.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
// Main app state
const state = {
rows: 3,
columns: 3,
cellBorderPercentage: 25,
referenceColors: [],
capturedColors: [],
selectedCellIndex: null,
colorCardImage: null,
testImage: null,
processedTestImage: null,
polynomialDegree: 1,
regressionSolver: 'notebook',
samplingMethod: 'histogram',
useChartAlignment: false,
chartCorners: [[0.03, 0.03], [0.97, 0.03], [0.97, 0.97], [0.03, 0.97]],
activeAlignmentHandle: null,
isDraggingAlignment: false,
brightnessAdjustment: 0,
gammaValue: 1.0,
lutSize: 32,
lutFormat: 'png',
cubeTitle: 'Custom LUT',
lutImage: null,
cubeData: null,
useAdvancedProcessing: true,
applyRolloffCurves: true,
useWeightedRegression: false,
useBackgroundProcessing: true,
qualityMetrics: null,
previewWorker: null,
exportWorker: null,
previewJobId: 0,
workerTaskCounter: 0,
generationRevision: 0,
transformationModels: {
basic: {
red: null,
green: null,
blue: null
},
multivariate: {
red: null,
green: null,
blue: null
}
},
rolloffCurves: null,
isGeneratingLUT: false
};
document.addEventListener('DOMContentLoaded', function() {
// Call the original initialization
initializeSliders();
initializeTabs();
initializeReferenceGrid();
initializeColorCardUpload();
initializeTestImageUpload();
initializeProcessing();
initializeExport();
initializeEventListeners();
initializeTemplateControls();
initializeAlignmentControls();
// Restore the saved chart configuration before the user starts editing.
try {
if (localStorage.getItem('lutMakerTemplate')) {
loadTemplate();
}
} catch (error) {
// Browser storage is optional and can be disabled by privacy settings.
}
// Log welcome message
logMessage('Welcome to the Browser-based LUT Maker!', 'info');
});
// Debounce function to delay execution
function debounce(func, wait) {
let timeout;
let lastArgs;
let lastContext;
function executedFunction(...args) {
lastArgs = args;
lastContext = this;
const later = () => {
clearTimeout(timeout);
timeout = null;
func.apply(lastContext, lastArgs);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
}
executedFunction.cancel = () => {
clearTimeout(timeout);
timeout = null;
};
executedFunction.flush = () => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
func.apply(lastContext, lastArgs);
}
};
return executedFunction;
}
// Auto-apply adjustments when sliders stop moving
const autoApplyAdjustments = debounce(function() {
if (state.testImage) {
processTestImage();
}
}, 500); // Wait 500ms after user stops adjusting
const refreshColorExtraction = debounce(function() {
if (state.colorCardImage) {
extractColorsFromImage(state.colorCardImage);
}
}, 250);
function terminateWorker(slot, reason) {
const worker = state[slot];
if (!worker) {
return;
}
state[slot] = null;
worker.terminate();
if (reason && worker.taskReject) {
const error = new Error(reason);
error.name = 'AbortError';
worker.taskReject(error);
}
worker.taskReject = null;
}
function runWorkerTask(slot, payload, transferables = [], onProgress) {
return new Promise((resolve, reject) => {
terminateWorker(slot, 'Superseded by a newer processing request');
const worker = new Worker('lut-worker.js');
const taskId = ++state.workerTaskCounter;
state[slot] = worker;
worker.taskReject = reject;
const finish = () => {
if (state[slot] === worker) {
state[slot] = null;
}
worker.taskReject = null;
worker.terminate();
};
worker.addEventListener('message', event => {
const message = event.data;
if (!message || message.taskId !== taskId) {
return;
}
if (message.type === 'progress') {
if (onProgress) {
onProgress(message.value);
}
return;
}
finish();
if (message.type === 'error') {
reject(new Error(message.message));
} else {
resolve(message);
}
});
worker.addEventListener('error', event => {
finish();
reject(new Error(event.message || 'Background processing failed'));
});
worker.postMessage({ ...payload, taskId }, transferables);
});
}
async function transformImageData(imageData, slot = 'previewWorker') {
if (!state.useBackgroundProcessing || typeof Worker === 'undefined') {
return transformLutImageData(imageData);
}
const response = await runWorkerTask(
slot,
{
type: 'transformImage',
width: imageData.width,
height: imageData.height,
buffer: imageData.data.buffer,
options: getTransformOptions(true)
},
[imageData.data.buffer]
);
return new ImageData(new Uint8ClampedArray(response.buffer), response.width, response.height);
}
// Initialize sliders and inputs
function initializeSliders() {
// Rows slider
const rowsSlider = document.getElementById('rows-slider');
const rowsValue = document.getElementById('rows-value');
rowsSlider.addEventListener('input', function() {
state.rows = parseInt(this.value);
rowsValue.textContent = state.rows;
initializeReferenceGrid();
state.capturedColors = [];
updateCapturedColorsGrid();
invalidateTransformation();
refreshColorExtraction();
});
// Columns slider
const columnsSlider = document.getElementById('columns-slider');
const columnsValue = document.getElementById('columns-value');
columnsSlider.addEventListener('input', function() {
state.columns = parseInt(this.value);
columnsValue.textContent = state.columns;
initializeReferenceGrid();
state.capturedColors = [];
updateCapturedColorsGrid();
invalidateTransformation();
refreshColorExtraction();
});
// Cell border slider
const borderSlider = document.getElementById('border-slider');
const borderValue = document.getElementById('border-value');
borderSlider.addEventListener('input', function() {
state.cellBorderPercentage = parseInt(this.value);
borderValue.textContent = state.cellBorderPercentage + '%';
state.capturedColors = [];
updateCapturedColorsGrid();
invalidateTransformation();
refreshColorExtraction();
});
// Polynomial degree slider
const polySlider = document.getElementById('polynomial-slider');
const polyValue = document.getElementById('polynomial-value');
polySlider.addEventListener('input', function() {
state.polynomialDegree = parseInt(this.value);
polyValue.textContent = state.polynomialDegree;
invalidateTransformation();
});
// Brightness slider with auto-apply
const brightnessSlider = document.getElementById('brightness-slider');
const brightnessValue = document.getElementById('brightness-value');
brightnessSlider.addEventListener('input', function() {
state.brightnessAdjustment = parseInt(this.value);
brightnessValue.textContent = state.brightnessAdjustment;
invalidateGeneratedLUT();
autoApplyAdjustments(); // Debounced update while dragging
});
brightnessSlider.addEventListener('change', function() {
// Apply immediately when user releases the slider
autoApplyAdjustments.cancel();
if (state.testImage) {
processTestImage();
}
});
// Gamma slider with auto-apply
const gammaSlider = document.getElementById('gamma-slider');
const gammaValue = document.getElementById('gamma-value');
gammaSlider.addEventListener('input', function() {
state.gammaValue = parseFloat(this.value);
gammaValue.textContent = state.gammaValue.toFixed(1);
invalidateGeneratedLUT();
autoApplyAdjustments(); // Debounced update while dragging
});
gammaSlider.addEventListener('change', function() {
// Apply immediately when user releases the slider
autoApplyAdjustments.cancel();
if (state.testImage) {
processTestImage();
}
});
// CUBE size preset
const lutSizeSelect = document.getElementById('lut-size-select');
lutSizeSelect.addEventListener('change', function() {
state.lutSize = parseInt(this.value);
invalidateGeneratedLUT();
});
// LUT format select
const lutFormat = document.getElementById('lut-format');
lutFormat.addEventListener('change', function() {
state.lutFormat = this.value;
const isCube = this.value === 'cube';
document.getElementById('cube-size-control').hidden = !isCube;
document.getElementById('cube-title-control').hidden = !isCube;
invalidateGeneratedLUT();
});
document.getElementById('cube-title').addEventListener('input', function() {
state.cubeTitle = this.value;
invalidateGeneratedLUT();
});
}
// Helper function to log messages
function logMessage(message, type = 'info') {
const logContainer = document.getElementById('process-log');
const logEntry = document.createElement('div');
logEntry.className = `log-entry ${type}`;
logEntry.textContent = message;
logContainer.appendChild(logEntry);
while (logContainer.childElementCount > 200) {
logContainer.firstElementChild.remove();
}
logContainer.scrollTop = logContainer.scrollHeight;
}
// Update progress bar
function updateProgress(containerId, value) {
const progressBar = document.getElementById(`${containerId}-progress-bar`);
const boundedValue = Math.max(0, Math.min(100, value));
progressBar.style.width = `${boundedValue}%`;
const progressContainer = document.getElementById(`${containerId}-progress-container`);
progressContainer.setAttribute('aria-valuenow', String(boundedValue));
}
function invalidateGeneratedLUT(cancelActive = true) {
if (cancelActive && state.isGeneratingLUT) {
terminateWorker('exportWorker', 'LUT generation was cancelled because its settings changed');
setExportBusy(false);
}
state.generationRevision++;
state.cubeData = null;
state.lutImage = null;
document.getElementById('lut-download-container').hidden = true;
updateProgress('export', 0);
}
function invalidateTransformation() {
state.previewJobId++;
terminateWorker('previewWorker', 'Preview processing was cancelled because its settings changed');
state.transformationModels = {
basic: { red: null, green: null, blue: null },
multivariate: { red: null, green: null, blue: null }
};
state.rolloffCurves = null;
state.qualityMetrics = null;
document.getElementById('quality-report').hidden = true;
document.getElementById('process-next').disabled = true;
document.getElementById('test-next').disabled = true;
updateProgress('process', 0);
invalidateGeneratedLUT();
if (state.testImage) {
displayTestImage(state.testImage);
}
}
function getTransformOptions(quantizeOutput = false) {
return {
models: state.transformationModels,
useAdvancedProcessing: state.useAdvancedProcessing,
applyRolloffCurves: state.applyRolloffCurves,
rolloffCurves: state.rolloffCurves,
brightnessAdjustment: state.brightnessAdjustment,
gammaValue: state.gammaValue,
quantizeOutput
};
}
function setExportBusy(isBusy) {
state.isGeneratingLUT = isBusy;
const generateButton = document.getElementById('generate-lut');
const downloadButton = document.getElementById('download-lut');
generateButton.disabled = isBusy;
generateButton.textContent = isBusy ? 'Generating…' : 'Generate LUT';
downloadButton.disabled = isBusy;
}
// RGB to Hex conversion
function rgbToHex(rgb) {
return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
}
// Update the captured colors grid
function updateCapturedColorsGrid() {
const gridContainer = document.getElementById('captured-grid');
gridContainer.replaceChildren();
gridContainer.style.gridTemplateColumns = `repeat(${state.columns}, 1fr)`;
for (let i = 0; i < state.capturedColors.length; i++) {
const cell = document.createElement('div');
cell.className = 'color-cell';
cell.style.backgroundColor = rgbToHex(state.capturedColors[i]);
cell.title = `Captured ${i + 1}: ${state.capturedColors[i].join(', ')}`;
cell.setAttribute('aria-label', cell.title);
gridContainer.appendChild(cell);
}
// Also update target grid
const targetGrid = document.getElementById('target-grid');
targetGrid.replaceChildren();
targetGrid.style.gridTemplateColumns = `repeat(${state.columns}, 1fr)`;
for (let i = 0; i < state.referenceColors.length; i++) {
const cell = document.createElement('div');
cell.className = 'color-cell';
cell.style.backgroundColor = rgbToHex(state.referenceColors[i]);
cell.title = `Target ${i + 1}: ${state.referenceColors[i].join(', ')}`;
cell.setAttribute('aria-label', cell.title);
targetGrid.appendChild(cell);
}
}
// Initialize tabs
function initializeTabs() {
const tabButtons = document.querySelectorAll('.tab-btn');
const tabPanels = document.querySelectorAll('.tab-panel');
tabButtons.forEach(button => {
button.addEventListener('click', function() {
const tabId = this.getAttribute('data-tab');
// Only allow clicking on enabled tabs
if (this.disabled) return;
// Deactivate all tabs
tabButtons.forEach(btn => {
btn.classList.remove('active');
btn.setAttribute('aria-selected', 'false');
btn.tabIndex = -1;
});
tabPanels.forEach(panel => {
panel.classList.remove('active');
panel.hidden = true;
});
// Activate the clicked tab
this.classList.add('active');
this.setAttribute('aria-selected', 'true');
this.tabIndex = 0;
const activePanel = document.getElementById(`${tabId}-tab`);
activePanel.classList.add('active');
activePanel.hidden = false;
});
button.addEventListener('keydown', event => {
if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) {
return;
}
const enabledTabs = [...tabButtons].filter(tab => !tab.disabled);
const currentIndex = enabledTabs.indexOf(button);
let nextIndex;
if (event.key === 'Home') {
nextIndex = 0;
} else if (event.key === 'End') {
nextIndex = enabledTabs.length - 1;
} else {
const offset = ['ArrowRight', 'ArrowDown'].includes(event.key) ? 1 : -1;
nextIndex = (currentIndex + offset + enabledTabs.length) % enabledTabs.length;
}
enabledTabs[nextIndex].focus();
enabledTabs[nextIndex].click();
event.preventDefault();
});
});
// Next button handlers
document.getElementById('setup-next').addEventListener('click', function() {
enableTab('reference');
activateTab('reference');
});
document.getElementById('reference-next').addEventListener('click', function() {
enableTab('colorcard');
activateTab('colorcard');
});
document.getElementById('colorcard-next').addEventListener('click', function() {
refreshColorExtraction.flush();
enableTab('process');
activateTab('process');
});
document.getElementById('process-next').addEventListener('click', function() {
enableTab('test');
activateTab('test');
});
document.getElementById('test-next').addEventListener('click', function() {
enableTab('export');
activateTab('export');
});
// Previous button handlers
document.getElementById('reference-prev').addEventListener('click', function() {
activateTab('setup');
});
document.getElementById('colorcard-prev').addEventListener('click', function() {
activateTab('reference');
});
document.getElementById('process-prev').addEventListener('click', function() {
activateTab('colorcard');
});
document.getElementById('test-prev').addEventListener('click', function() {
activateTab('process');
});
document.getElementById('export-prev').addEventListener('click', function() {
activateTab('test');
});
}
// Enable a tab
function enableTab(tabId) {
const tabButton = document.querySelector(`.tab-btn[data-tab="${tabId}"]`);
if (tabButton) {
tabButton.disabled = false;
}
}
// Activate a tab
function activateTab(tabId) {
const tabButton = document.querySelector(`.tab-btn[data-tab="${tabId}"]`);
if (tabButton && !tabButton.disabled) {
tabButton.focus();
tabButton.click();
}
}
// Initialize reference color grid
function initializeReferenceGrid() {
const gridContainer = document.getElementById('reference-grid');
gridContainer.replaceChildren();
gridContainer.style.gridTemplateColumns = `repeat(${state.columns}, 1fr)`;
// Initialize with default colors if not already set
if (state.referenceColors.length !== state.rows * state.columns) {
state.referenceColors = Array(state.rows * state.columns).fill().map(() => [128, 128, 128]);
}
// Create color cells
for (let i = 0; i < state.rows * state.columns; i++) {
const cell = document.createElement('button');
cell.type = 'button';
cell.className = 'color-cell';
cell.dataset.index = i;
cell.style.backgroundColor = rgbToHex(state.referenceColors[i]);
cell.setAttribute('aria-label', `Edit reference color ${i + 1}: ${state.referenceColors[i].join(', ')}`);
cell.setAttribute('aria-pressed', state.selectedCellIndex === i ? 'true' : 'false');
cell.addEventListener('click', function() {
selectCell(parseInt(this.dataset.index));
});
gridContainer.appendChild(cell);
}
const preferredIndex = Number.isInteger(state.selectedCellIndex)
? Math.min(state.selectedCellIndex, state.referenceColors.length - 1)
: 0;
selectCell(preferredIndex);
}
// Select a color cell
function selectCell(index) {
state.selectedCellIndex = index;
// Update all cell borders
const cells = document.querySelectorAll('#reference-grid .color-cell');
cells.forEach(cell => {
cell.style.border = '1px solid #ddd';
cell.setAttribute('aria-pressed', 'false');
});
// Highlight selected cell
const selectedCell = document.querySelector(`#reference-grid .color-cell[data-index="${index}"]`);
if (selectedCell) {
selectedCell.style.border = '3px solid #000';
selectedCell.setAttribute('aria-pressed', 'true');
}
// Update color inputs
const [r, g, b] = state.referenceColors[index];
document.getElementById('red-input').value = r;
document.getElementById('green-input').value = g;
document.getElementById('blue-input').value = b;
// Update color preview
const colorPreview = document.getElementById('selected-color-preview');
colorPreview.style.backgroundColor = rgbToHex(state.referenceColors[index]);
}
function initializeColorCardUpload() {
const fileInput = document.getElementById('colorcard-upload');
fileInput.addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
loadImage(file, 'colorcard');
}
});
// Add demo image functionality properly
const demoButton = document.getElementById('use-demo-image');
if (demoButton) {
demoButton.addEventListener('click', function() {
loadDemoImage('colorcard');
});
}
};
function resetChartCorners() {
state.chartCorners = [[0.03, 0.03], [0.97, 0.03], [0.97, 0.97], [0.03, 0.97]];
}
function drawColorCardOverlay() {
const canvas = document.getElementById('colorcard-preview');
if (!state.colorCardImage || !canvas.width || !canvas.height) {
return;
}
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(state.colorCardImage, 0, 0, canvas.width, canvas.height);
if (!state.useChartAlignment) {
return;
}
const homography = LUTCore.calculateUnitSquareHomography(state.chartCorners);
const drawMappedLine = (fixedValue, vertical) => {
context.beginPath();
for (let step = 0; step <= 40; step++) {
const varyingValue = step / 40;
const [x, y] = vertical
? LUTCore.mapUnitSquarePoint(homography, fixedValue, varyingValue)
: LUTCore.mapUnitSquarePoint(homography, varyingValue, fixedValue);
const canvasX = x * canvas.width;
const canvasY = y * canvas.height;
if (step === 0) {
context.moveTo(canvasX, canvasY);
} else {
context.lineTo(canvasX, canvasY);
}
}
context.stroke();
};
context.save();
context.strokeStyle = 'rgba(255, 255, 255, 0.95)';
context.lineWidth = 3;
for (let column = 0; column <= state.columns; column++) {
drawMappedLine(column / state.columns, true);
}
for (let row = 0; row <= state.rows; row++) {
drawMappedLine(row / state.rows, false);
}
context.strokeStyle = 'rgba(20, 95, 180, 0.95)';
context.lineWidth = 1;
for (let column = 0; column <= state.columns; column++) {
drawMappedLine(column / state.columns, true);
}
for (let row = 0; row <= state.rows; row++) {
drawMappedLine(row / state.rows, false);
}
const labels = ['TL', 'TR', 'BR', 'BL'];
state.chartCorners.forEach(([x, y], index) => {
const canvasX = x * canvas.width;
const canvasY = y * canvas.height;
context.beginPath();
context.arc(canvasX, canvasY, 10, 0, Math.PI * 2);
context.fillStyle = index === state.activeAlignmentHandle ? '#ffc107' : '#ffffff';
context.fill();
context.strokeStyle = '#164f91';
context.lineWidth = 3;
context.stroke();
context.fillStyle = '#102a43';
context.font = 'bold 12px sans-serif';
context.fillText(`${index + 1} ${labels[index]}`, canvasX + 13, canvasY - 11);
});
context.restore();
}
function updateAlignmentPoint(event) {
if (state.activeAlignmentHandle === null) {
return;
}
const canvas = document.getElementById('colorcard-preview');
const bounds = canvas.getBoundingClientRect();
const x = Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width));
const y = Math.max(0, Math.min(1, (event.clientY - bounds.top) / bounds.height));
const nextCorners = state.chartCorners.map(point => [...point]);
nextCorners[state.activeAlignmentHandle] = [x, y];
try {
LUTCore.calculateUnitSquareHomography(nextCorners);
} catch (error) {
return;
}
state.chartCorners = nextCorners;
drawColorCardOverlay();
}
function initializeAlignmentControls() {
const canvas = document.getElementById('colorcard-preview');
const alignmentToggle = document.getElementById('alignment-toggle');
const alignmentControls = document.getElementById('alignment-controls');
document.getElementById('sampling-method').addEventListener('change', function() {
state.samplingMethod = this.value;
invalidateTransformation();
refreshColorExtraction();
});
alignmentToggle.addEventListener('change', function() {
state.useChartAlignment = this.checked;
alignmentControls.hidden = !this.checked;
canvas.classList.toggle('alignment-enabled', this.checked);
state.activeAlignmentHandle = null;
state.isDraggingAlignment = false;
drawColorCardOverlay();
invalidateTransformation();
refreshColorExtraction();
});
document.getElementById('reset-alignment').addEventListener('click', () => {
resetChartCorners();
drawColorCardOverlay();
invalidateTransformation();
refreshColorExtraction();
});
document.getElementById('rotate-alignment-left').addEventListener('click', () => {
state.chartCorners = [
state.chartCorners[1],
state.chartCorners[2],
state.chartCorners[3],
state.chartCorners[0]
];
drawColorCardOverlay();
invalidateTransformation();
refreshColorExtraction();
});
document.getElementById('rotate-alignment-right').addEventListener('click', () => {
state.chartCorners = [
state.chartCorners[3],
state.chartCorners[0],
state.chartCorners[1],
state.chartCorners[2]
];
drawColorCardOverlay();
invalidateTransformation();
refreshColorExtraction();
});
canvas.addEventListener('pointerdown', event => {
if (!state.useChartAlignment) {
return;
}
const bounds = canvas.getBoundingClientRect();
const point = [
(event.clientX - bounds.left) / bounds.width,
(event.clientY - bounds.top) / bounds.height
];
const distances = state.chartCorners.map(([x, y]) => Math.hypot(x - point[0], y - point[1]));
const closest = distances.indexOf(Math.min(...distances));
if (distances[closest] <= 0.08) {
state.activeAlignmentHandle = closest;
state.isDraggingAlignment = true;
invalidateTransformation();
canvas.setPointerCapture(event.pointerId);
updateAlignmentPoint(event);
event.preventDefault();
}
});
canvas.addEventListener('pointermove', event => {
if (state.isDraggingAlignment) {
updateAlignmentPoint(event);
}
});
const finishPointerMove = event => {
if (!state.isDraggingAlignment || state.activeAlignmentHandle === null) {
return;
}
updateAlignmentPoint(event);
state.isDraggingAlignment = false;
state.activeAlignmentHandle = null;
drawColorCardOverlay();
refreshColorExtraction();
};
canvas.addEventListener('pointerup', finishPointerMove);
canvas.addEventListener('pointercancel', finishPointerMove);
canvas.addEventListener('keydown', event => {
if (!state.useChartAlignment) {
return;
}
if (/^[1-4]$/.test(event.key)) {
state.activeAlignmentHandle = Number(event.key) - 1;
drawColorCardOverlay();
event.preventDefault();
return;
}
if (state.activeAlignmentHandle === null || !event.key.startsWith('Arrow')) {
return;
}
const step = event.shiftKey ? 0.01 : 0.002;
const point = [...state.chartCorners[state.activeAlignmentHandle]];
if (event.key === 'ArrowLeft') point[0] -= step;
if (event.key === 'ArrowRight') point[0] += step;
if (event.key === 'ArrowUp') point[1] -= step;
if (event.key === 'ArrowDown') point[1] += step;
const nextCorners = state.chartCorners.map(corner => [...corner]);
nextCorners[state.activeAlignmentHandle] = point.map(value => Math.max(0, Math.min(1, value)));
try {
LUTCore.calculateUnitSquareHomography(nextCorners);
} catch (error) {
return;
}
state.chartCorners = nextCorners;
drawColorCardOverlay();
invalidateTransformation();
refreshColorExtraction();
event.preventDefault();
});
}
// Extract colors from the color card image
function extractColorsFromImage(img) {
logMessage('Extracting colors from image...', 'info');
document.getElementById('colorcard-next').disabled = true;
invalidateTransformation();
try {
const tempCanvas = document.createElement('canvas');
const tempContext = tempCanvas.getContext('2d', { willReadFrequently: true });
tempCanvas.width = img.width;
tempCanvas.height = img.height;
tempContext.drawImage(img, 0, 0);
const imageData = tempContext.getImageData(0, 0, img.width, img.height);
state.capturedColors = LUTCore.extractGridColors(imageData, {
rows: state.rows,
columns: state.columns,
borderPercentage: state.cellBorderPercentage,
method: state.samplingMethod,
useAlignment: state.useChartAlignment,
corners: state.chartCorners
});
updateCapturedColorsGrid();
logMessage(
`Color extraction complete (${state.samplingMethod}${state.useChartAlignment ? ', aligned' : ''})`,
'success'
);
document.getElementById('colorcard-next').disabled = false;
} catch (error) {
state.capturedColors = [];
updateCapturedColorsGrid();
logMessage(`Color extraction failed: ${error.message}`, 'error');
}
}
// Load an image file
function loadImage(file, type) {
if (!file || !file.type.startsWith('image/')) {
logMessage('Please choose a supported image file', 'error');
return;
}
if (file.size > 50 * 1024 * 1024) {
logMessage('The selected image is larger than the 50 MB limit', 'error');
return;
}
const imageUrl = URL.createObjectURL(file);
const img = new Image();
img.onload = function() {
URL.revokeObjectURL(imageUrl);
if (!img.width || !img.height || img.width * img.height > 50_000_000) {
logMessage('The selected image dimensions are invalid or exceed the 50-megapixel limit', 'error');
return;
}
if (type === 'colorcard') {
state.colorCardImage = img;
displayColorCardImage(img);
} else if (type === 'test') {
state.testImage = img;
displayTestImage(img);
}
logMessage(`${type === 'colorcard' ? 'Color card' : 'Test'} image loaded successfully`, 'success');
};
img.onerror = function() {
URL.revokeObjectURL(imageUrl);
logMessage('The selected image could not be decoded', 'error');
};
img.src = imageUrl;
}
// Initialize the processing functionality
function initializeProcessing() {
// Process button
document.getElementById('process-button').addEventListener('click', function() {
processColorTransformation();
});
// Update selected color
document.getElementById('update-color').addEventListener('click', function() {
if (state.selectedCellIndex !== null) {
const r = parseInt(document.getElementById('red-input').value);
const g = parseInt(document.getElementById('green-input').value);
const b = parseInt(document.getElementById('blue-input').value);
state.referenceColors[state.selectedCellIndex] = [
isNaN(r) ? 0 : Math.min(255, Math.max(0, r)),
isNaN(g) ? 0 : Math.min(255, Math.max(0, g)),
isNaN(b) ? 0 : Math.min(255, Math.max(0, b))
];
// Update grid
const cell = document.querySelector(`.color-cell[data-index="${state.selectedCellIndex}"]`);
if (cell) {
cell.style.backgroundColor = rgbToHex(state.referenceColors[state.selectedCellIndex]);
cell.setAttribute(
'aria-label',
`Edit reference color ${state.selectedCellIndex + 1}: ${state.referenceColors[state.selectedCellIndex].join(', ')}`
);
}
// Update preview
const colorPreview = document.getElementById('selected-color-preview');
colorPreview.style.backgroundColor = rgbToHex(state.referenceColors[state.selectedCellIndex]);
updateCapturedColorsGrid();
invalidateTransformation();
}
});
// Reset colors
document.getElementById('reset-colors').addEventListener('click', function() {
state.referenceColors = Array(state.rows * state.columns).fill().map(() => [128, 128, 128]);
initializeReferenceGrid();
updateCapturedColorsGrid();
invalidateTransformation();
});
// Use example colors (color chart from the original code)
document.getElementById('use-example').addEventListener('click', function() {
const exampleColors = [
[147, 163, 96], [154, 64, 73], [0, 166, 153],
[61, 65, 93], [96, 102, 102], [247, 185, 48],
[62, 63, 64], [245, 243, 236], [138, 83, 129]
];
// Only use as many colors as there are cells
state.referenceColors = [];
for (let i = 0; i < state.rows * state.columns; i++) {
if (i < exampleColors.length) {
state.referenceColors.push(exampleColors[i]);
} else {
state.referenceColors.push([128, 128, 128]);
}
}
initializeReferenceGrid();
updateCapturedColorsGrid();
invalidateTransformation();
logMessage('Example colors loaded', 'success');
});
}
const colorPresets = {
demo3x3: {
name: "Demo 3×3",
rows: 3,
columns: 3,
cellBorderPercentage: 25,
colors: [
[147, 163, 96], [154, 64, 73], [0, 166, 153],
[61, 65, 93], [96, 102, 102], [247, 185, 48],
[62, 63, 64], [245, 243, 236], [138, 83, 129]
]
},
datacolor24: {
name: "Datacolor SpyderCHECKR 24",
rows: 4,
columns: 6,
cellBorderPercentage: 25,
colors: [
[ 98, 187, 166], [126, 125, 174], [ 82, 106, 60], [ 87, 120, 155], [197, 145, 125], [112, 76, 60],
[222, 118, 32], [ 58, 89, 160], [195 , 79, 95], [ 83, 58, 106], [157, 188, 54], [238, 158, 25],
[ 0, 127, 159], [192, 75, 145], [245, 205, 0], [186, 26, 51], [ 57, 146, 64], [ 25, 55, 135],
[249, 242, 238], [202, 198, 195], [161, 157, 154], [122, 118, 116], [ 80, 80, 78], [ 43, 41, 43]
]
},
datacolor48: {
name: "Datacolor SpyderCHECKR 48",
rows: 6,
columns: 8,
cellBorderPercentage: 25,
colors: [
/* sRGB values source: https://www.datacolor.com/spyder/downloads/SpyderCheckr_Color_Data_V2.pdf */
/* LEFT RIGHT */
/* A B C D E F G H */
/* 1 */ [210, 121, 117], [218, 203, 201], [237, 206, 186], [241, 233, 229], [249, 242, 238], [ 0, 127, 159], [222, 118, 32], [ 98, 187, 166],
/* 2 */ [216, 179, 90], [203, 205, 196], [211, 175, 133], [229, 222, 220], [202, 198, 195], [192, 75, 145], [ 58, 88, 159], [126, 125, 174],
/* 3 */ [127, 175, 120], [206, 203, 208], [193, 149, 91], [182, 178, 176], [161, 157, 154], [245, 205, 0], [195, 79, 95], [ 82, 106, 60],
/* 4 */ [ 66, 157, 179], [ 66, 57, 58], [139, 93, 61], [139, 136, 135], [122, 118, 116], [186, 26, 51], [ 83, 58, 106], [ 87, 120, 155],