-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
1448 lines (1220 loc) · 67.4 KB
/
Copy pathscript.js
File metadata and controls
1448 lines (1220 loc) · 67.4 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
document.addEventListener('DOMContentLoaded', function() {
// DOM Elements
const canvasScroll = document.getElementById('canvasScroll');
const circuitGrid = document.getElementById('circuitGrid');
const zoomInBtn = document.getElementById('zoomInBtn');
const zoomOutBtn = document.getElementById('zoomOutBtn');
const snapToGridBtn = document.getElementById('snapToGridBtn');
const deleteBtn = document.getElementById('deleteBtn');
const zoomLevel = document.getElementById('zoomLevel');
const paletteItems = document.querySelectorAll('.palette-item');
const simulateBtn = document.getElementById('simulateBtn');
const resultsModal = document.getElementById('resultsModal');
const closeModal = document.getElementById('closeModal');
const nodeTable = document.getElementById('nodeTable').querySelector('tbody');
const componentTable = document.getElementById('componentTable').querySelector('tbody');
const propertyEditor = document.getElementById('propertyEditor');
const propValue = document.getElementById('propValue');
const propUnit = document.getElementById('propUnit');
const applyProperties = document.getElementById('applyProperties');
const newBtn = document.getElementById('newBtn');
const saveBtn = document.getElementById('saveBtn');
const loadBtn = document.getElementById('loadBtn');
const showNodesBtn = document.getElementById('showNodesBtn');
const debugBtn = document.getElementById('debugBtn');
const debugPanel = document.getElementById('debugPanel');
const debugContent = document.getElementById('debugContent');
const componentCount = document.getElementById('componentCount');
const nodeCount = document.getElementById('nodeCount');
const simulationStatus = document.getElementById('simulationStatus');
// State variables
let scale = 1;
let isDragging = false;
let currentComponent = null;
let offsetX, offsetY;
let isSnapToGrid = true;
let selectedComponent = null;
let isCreatingWire = false;
let wireStartPoint = null;
let tempWireSegments = [];
let components = [];
let wires = [];
let nodes = {};
let nextNodeId = 1;
let nextComponentId = 1;
let componentCounters = {
resistor: 0,
capacitor: 0,
inductor: 0,
voltageSource: 0,
currentSource: 0,
ground: 0,
diode: 0,
led: 0
};
let showNodes = false;
let nodeIndicators = [];
let debugMode = false;
// Component SVG templates
const componentSVGs = {
resistor: `
<svg class="component-svg" viewBox="0 0 50 50">
<rect x="10" y="20" width="30" height="10" fill="none" stroke="black" stroke-width="2"/>
<line x1="5" y1="25" x2="10" y2="25" stroke="black" stroke-width="2"/>
<line x1="40" y1="25" x2="45" y2="25" stroke="black" stroke-width="2"/>
</svg>
`,
capacitor: `
<svg class="component-svg" viewBox="0 0 50 50">
<line x1="5" y1="25" x2="20" y2="25" stroke="black" stroke-width="2"/>
<line x1="20" y1="15" x2="20" y2="35" stroke="black" stroke-width="2"/>
<line x1="30" y1="15" x2="30" y2="35" stroke="black" stroke-width="2"/>
<line x1="30" y1="25" x2="45" y2="25" stroke="black" stroke-width="2"/>
</svg>
`,
inductor: `
<svg class="component-svg" viewBox="0 0 50 50">
<line x1="5" y1="25" x2="10" y2="25" stroke="black" stroke-width="2"/>
<path d="M 10 25 Q 15 15, 20 25 T 30 25 T 40 25" fill="none" stroke="black" stroke-width="2"/>
<line x1="40" y1="25" x2="45" y2="25" stroke="black" stroke-width="2"/>
</svg>
`,
voltageSource: `
<svg class="component-svg" viewBox="0 0 50 50">
<circle cx="25" cy="25" r="20" stroke="black" stroke-width="2" fill="none"/>
<text x="25" y="20" text-anchor="middle" font-size="16" font-weight="bold">+</text>
<text x="25" y="35" text-anchor="middle" font-size="16" font-weight="bold">-</text>
</svg>
`,
currentSource: `
<svg class="component-svg" viewBox="0 0 50 50">
<circle cx="25" cy="25" r="20" stroke="black" stroke-width="2" fill="none"/>
<line x1="15" y1="25" x2="35" y2="25" stroke="black" stroke-width="2" marker-end="url(#arrowhead)"/>
<defs>
<marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
<polygon points="0 0, 10 3.5, 0 7" fill="black"/>
</marker>
</defs>
</svg>
`,
ground: `
<svg class="component-svg" viewBox="0 0 50 50">
<line x1="25" y1="15" x2="25" y2="30" stroke="black" stroke-width="2"/>
<line x1="15" y1="30" x2="35" y2="30" stroke="black" stroke-width="2"/>
<line x1="18" y1="35" x2="32" y2="35" stroke="black" stroke-width="2"/>
<line x1="21" y1="40" x2="29" y2="40" stroke="black" stroke-width="2"/>
</svg>
`,
diode: `
<svg class="component-svg" viewBox="0 0 50 50">
<line x1="5" y1="25" x2="20" y2="25" stroke="black" stroke-width="2"/>
<polygon points="20,15 20,35 35,25" fill="black"/>
<line x1="35" y1="15" x2="35" y2="35" stroke="black" stroke-width="2"/>
<line x1="35" y1="25" x2="45" y2="25" stroke="black" stroke-width="2"/>
</svg>
`,
led: `
<svg class="component-svg" viewBox="0 0 50 50">
<line x1="5" y1="25" x2="20" y2="25" stroke="black" stroke-width="2"/>
<polygon points="20,15 20,35 35,25" fill="black"/>
<line x1="35" y1="15" x2="35" y2="35" stroke="black" stroke-width="2"/>
<line x1="35" y1="25" x2="45" y2="25" stroke="black" stroke-width="2"/>
<!-- Light rays -->
<line x1="25" y1="10" x2="25" y2="5" stroke="black" stroke-width="1.5"/>
<line x1="30" y1="12" x2="34" y2="8" stroke="black" stroke-width="1.5"/>
<line x1="20" y1="12" x2="16" y2="8" stroke="black" stroke-width="1.5"/>
</svg>
`
};
// Default component properties
const defaultProperties = {
resistor: { value: 1000, unit: 'Ω' },
capacitor: { value: 1, unit: 'μF' },
inductor: { value: 1, unit: 'mH' },
voltageSource: { value: 1, unit: 'V' },
currentSource: { value: 0.01, unit: 'A' },
ground: { value: 0, unit: 'V' },
diode: { value: 0.7, unit: 'V' },
led: { value: 2, unit: 'V' }
};
// Initialize grid
updateZoom();
updateStatusBar();
// Event Listeners
zoomInBtn.addEventListener('click', zoomIn);
zoomOutBtn.addEventListener('click', zoomOut);
snapToGridBtn.addEventListener('click', toggleSnapToGrid);
deleteBtn.addEventListener('click', deleteSelected);
simulateBtn.addEventListener('click', runSimulation);
closeModal.addEventListener('click', () => resultsModal.style.display = 'none');
applyProperties.addEventListener('click', updateComponentProperties);
newBtn.addEventListener('click', clearCircuit);
saveBtn.addEventListener('click', saveCircuit);
loadBtn.addEventListener('click', loadCircuit);
showNodesBtn.addEventListener('click', toggleNodeDisplay);
debugBtn.addEventListener('click', toggleDebug);
// Component palette drag
paletteItems.forEach(item => {
item.addEventListener('mousedown', function(e) {
const type = this.getAttribute('data-type');
createNewComponent(type, e);
});
});
// Canvas interaction
circuitGrid.addEventListener('mousedown', handleCanvasMouseDown);
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
// Double-click to edit properties
circuitGrid.addEventListener('dblclick', function(e) {
if (e.target.closest('.component')) {
const component = e.target.closest('.component');
showPropertyEditor(component, e);
}
});
// Prevent context menu on canvas
circuitGrid.addEventListener('contextmenu', (e) => e.preventDefault());
// Functions
function zoomIn() {
scale = Math.min(scale + 0.1, 2);
updateZoom();
}
function zoomOut() {
scale = Math.max(scale - 0.1, 0.5);
updateZoom();
}
function updateZoom() {
circuitGrid.style.transform = `scale(${scale})`;
zoomLevel.textContent = `${Math.round(scale * 100)}%`;
}
function toggleSnapToGrid() {
isSnapToGrid = !isSnapToGrid;
snapToGridBtn.classList.toggle('active', isSnapToGrid);
}
function toggleNodeDisplay() {
showNodes = !showNodes;
showNodesBtn.classList.toggle('active', showNodes);
if (showNodes) {
displayNodes();
} else {
hideNodes();
}
}
function toggleDebug() {
debugMode = !debugMode;
debugBtn.classList.toggle('active', debugMode);
debugPanel.style.display = debugMode ? 'block' : 'none';
}
function displayNodes() {
// Remove existing node indicators
hideNodes();
// Create new node indicators
const nodePositions = getNodePositions();
for (const nodeId in nodePositions) {
const pos = nodePositions[nodeId];
const indicator = document.createElement('div');
indicator.className = 'node-indicator';
indicator.textContent = nodeId;
indicator.style.left = `${pos.x - 10}px`;
indicator.style.top = `${pos.y - 10}px`;
circuitGrid.appendChild(indicator);
nodeIndicators.push(indicator);
}
}
function hideNodes() {
nodeIndicators.forEach(indicator => indicator.remove());
nodeIndicators = [];
}
function getNodePositions() {
const positions = {};
// Get positions of all connection points
components.forEach(comp => {
const leftPoint = comp.element.querySelector('.connection-point[data-terminal="left"]');
const rightPoint = comp.element.querySelector('.connection-point[data-terminal="right"]');
if (leftPoint) {
const leftTerminal = `${comp.id}:left`;
const nodeId = nodes[leftTerminal];
if (nodeId !== undefined) {
const pos = getPointPosition(leftPoint);
positions[nodeId] = pos;
}
}
if (rightPoint) {
const rightTerminal = `${comp.id}:right`;
const nodeId = nodes[rightTerminal];
if (nodeId !== undefined) {
const pos = getPointPosition(rightPoint);
positions[nodeId] = pos;
}
}
});
return positions;
}
function updateStatusBar() {
componentCount.textContent = `Components: ${components.length}`;
nodeCount.textContent = `Nodes: ${Object.keys(nodes).length > 0 ? new Set(Object.values(nodes)).size : 0}`;
}
function debugLog(message) {
if (debugMode) {
debugContent.textContent += message + '\n';
debugPanel.scrollTop = debugPanel.scrollHeight;
}
}
function deleteSelected() {
if (selectedComponent) {
// Remove associated wires
const componentId = selectedComponent.getAttribute('data-id');
wires = wires.filter(wire => {
if (wire.startComponentId === componentId || wire.endComponentId === componentId) {
wire.segments.forEach(segment => segment.element.remove());
return false;
}
return true;
});
// Remove component
selectedComponent.remove();
components = components.filter(comp => comp.id !== componentId);
selectedComponent = null;
updateStatusBar();
if (showNodes) {
displayNodes();
}
}
}
function createNewComponent(type, e) {
const componentId = `comp_${nextComponentId++}`;
componentCounters[type]++;
const component = document.createElement('div');
component.className = 'component';
component.setAttribute('data-type', type);
component.setAttribute('data-id', componentId);
// Set default properties
const defaultProps = defaultProperties[type];
component.setAttribute('data-value', defaultProps.value);
component.setAttribute('data-unit', defaultProps.unit);
// Position the component near the mouse
const rect = canvasScroll.getBoundingClientRect();
let x = e.clientX - rect.left - 40;
let y = e.clientY - rect.top - 40;
if (isSnapToGrid) {
const gridSize = 20 * scale;
x = Math.round(x / gridSize) * gridSize;
y = Math.round(y / gridSize) * gridSize;
}
component.style.left = `${x}px`;
component.style.top = `${y}px`;
// Generate component label
let label = '';
let labelPrefix = '';
switch (type) {
case 'resistor':
labelPrefix = 'R';
break;
case 'capacitor':
labelPrefix = 'C';
break;
case 'inductor':
labelPrefix = 'L';
break;
case 'voltageSource':
labelPrefix = 'Vs';
break;
case 'currentSource':
labelPrefix = 'Is';
break;
case 'ground':
labelPrefix = 'GND';
break;
case 'diode':
labelPrefix = 'D';
break;
case 'led':
labelPrefix = 'LED';
break;
}
label = `${labelPrefix}${componentCounters[type]} ${defaultProps.value}${defaultProps.unit}`;
// Add component content with SVG
component.innerHTML = `
<div class="component-svg-container">
${componentSVGs[type]}
</div>
<span class="component-label">${label}</span>
<div class="connection-point" data-terminal="left" style="left: -6px; top: 50%; transform: translateY(-50%);"></div>
<div class="connection-point" data-terminal="right" style="right: -6px; top: 50%; transform: translateY(-50%);"></div>
`;
circuitGrid.appendChild(component);
// Add to components array
components.push({
id: componentId,
type: type,
element: component,
value: defaultProps.value,
unit: defaultProps.unit,
label: label
});
// Select the new component
selectComponent(component);
currentComponent = component;
isDragging = true;
// Calculate offset for proper dragging
const componentRect = component.getBoundingClientRect();
offsetX = e.clientX - componentRect.left;
offsetY = e.clientY - componentRect.top;
updateStatusBar();
}
function handleCanvasMouseDown(e) {
if (e.target.classList.contains('connection-point')) {
// Start creating a wire
isCreatingWire = true;
wireStartPoint = e.target;
// Create temporary wire segments
const startPoint = getPointPosition(wireStartPoint);
createTempWireSegments(startPoint);
return;
}
// Only start dragging if clicking on the component SVG container
if (e.target.classList.contains('component-svg-container') ||
e.target.closest('.component-svg-container')) {
const component = e.target.closest('.component');
selectComponent(component);
currentComponent = component;
isDragging = true;
const rect = component.getBoundingClientRect();
offsetX = e.clientX - rect.left;
offsetY = e.clientY - rect.top;
} else if (e.target.classList.contains('component') || e.target.closest('.component')) {
// Clicked on component but not the SVG - just select it
const component = e.target.classList.contains('component') ? e.target : e.target.closest('.component');
selectComponent(component);
} else {
// Clicked on empty space - deselect
if (selectedComponent) {
selectedComponent.classList.remove('selected');
selectedComponent = null;
}
}
}
function handleMouseMove(e) {
if (isDragging && currentComponent) {
const rect = canvasScroll.getBoundingClientRect();
let x = e.clientX - rect.left - offsetX;
let y = e.clientY - rect.top - offsetY;
if (isSnapToGrid) {
const gridSize = 20 * scale;
x = Math.round(x / gridSize) * gridSize;
y = Math.round(y / gridSize) * gridSize;
}
currentComponent.style.left = `${x}px`;
currentComponent.style.top = `${y}px`;
// Update connected wires
updateComponentWires(currentComponent);
if (showNodes) {
displayNodes();
}
}
if (isCreatingWire && tempWireSegments.length > 0) {
const rect = canvasScroll.getBoundingClientRect();
const endX = e.clientX - rect.left;
const endY = e.clientY - rect.top;
// Update temporary wire segments
updateTempWireSegments(endX, endY);
}
}
function handleMouseUp(e) {
if (isCreatingWire && tempWireSegments.length > 0) {
// Check if we're over a connection point
const targetElement = document.elementFromPoint(e.clientX, e.clientY);
if (targetElement && targetElement.classList.contains('connection-point') && targetElement !== wireStartPoint) {
// Create a permanent wire
createWire(wireStartPoint, targetElement);
}
// Remove temporary wire segments
tempWireSegments.forEach(segment => segment.element.remove());
tempWireSegments = [];
}
isDragging = false;
currentComponent = null;
isCreatingWire = false;
wireStartPoint = null;
}
function createTempWireSegments(startPoint) {
// Clear any existing temp segments
tempWireSegments.forEach(segment => segment.element.remove());
tempWireSegments = [];
// Create initial horizontal segment
const hSegment = document.createElement('div');
hSegment.className = 'wire-segment horizontal';
hSegment.style.left = `${startPoint.x}px`;
hSegment.style.top = `${startPoint.y}px`;
hSegment.style.width = '0px';
circuitGrid.appendChild(hSegment);
tempWireSegments.push({ element: hSegment, type: 'horizontal' });
// Create initial vertical segment
const vSegment = document.createElement('div');
vSegment.className = 'wire-segment vertical';
vSegment.style.left = `${startPoint.x}px`;
vSegment.style.top = `${startPoint.y}px`;
vSegment.style.height = '0px';
circuitGrid.appendChild(vSegment);
tempWireSegments.push({ element: vSegment, type: 'vertical' });
}
function updateTempWireSegments(endX, endY) {
if (tempWireSegments.length < 2) return;
const startPoint = getPointPosition(wireStartPoint);
// Calculate orthogonal path (L-shaped)
// Option 1: Horizontal then vertical
const h1Length = endX - startPoint.x;
const v1Length = endY - startPoint.y;
// Option 2: Vertical then horizontal
const v2Length = endY - startPoint.y;
const h2Length = endX - startPoint.x;
// Choose the option with the shortest total length
const option1Length = Math.abs(h1Length) + Math.abs(v1Length);
const option2Length = Math.abs(v2Length) + Math.abs(h2Length);
if (option1Length <= option2Length) {
// Use horizontal then vertical
tempWireSegments[0].element.style.width = `${Math.abs(h1Length)}px`;
tempWireSegments[0].element.style.left = `${Math.min(startPoint.x, endX)}px`;
tempWireSegments[1].element.style.height = `${Math.abs(v1Length)}px`;
tempWireSegments[1].element.style.left = `${endX}px`;
tempWireSegments[1].element.style.top = `${Math.min(startPoint.y, endY)}px`;
} else {
// Use vertical then horizontal
tempWireSegments[0].element.style.height = `${Math.abs(v2Length)}px`;
tempWireSegments[0].element.style.top = `${Math.min(startPoint.y, endY)}px`;
tempWireSegments[1].element.style.width = `${Math.abs(h2Length)}px`;
tempWireSegments[1].element.style.left = `${Math.min(startPoint.x, endX)}px`;
tempWireSegments[1].element.style.top = `${endY}px`;
}
}
function createWire(startPoint, endPoint) {
const wireId = `wire_${Date.now()}`;
const startPos = getPointPosition(startPoint);
const endPos = getPointPosition(endPoint);
// Calculate orthogonal path (L-shaped)
// Option 1: Horizontal then vertical
const h1Length = endPos.x - startPos.x;
const v1Length = endPos.y - startPos.y;
// Option 2: Vertical then horizontal
const v2Length = endPos.y - startPos.y;
const h2Length = endPos.x - startPos.x;
// Choose the option with the shortest total length
const option1Length = Math.abs(h1Length) + Math.abs(v1Length);
const option2Length = Math.abs(v2Length) + Math.abs(h2Length);
const segments = [];
if (option1Length <= option2Length) {
// Use horizontal then vertical
const hSegment = document.createElement('div');
hSegment.className = 'wire-segment horizontal';
hSegment.setAttribute('data-wire-id', wireId);
hSegment.style.left = `${Math.min(startPos.x, endPos.x)}px`;
hSegment.style.top = `${startPos.y}px`;
hSegment.style.width = `${Math.abs(h1Length)}px`;
circuitGrid.appendChild(hSegment);
segments.push({ element: hSegment, type: 'horizontal' });
const vSegment = document.createElement('div');
vSegment.className = 'wire-segment vertical';
vSegment.setAttribute('data-wire-id', wireId);
vSegment.style.left = `${endPos.x}px`;
vSegment.style.top = `${Math.min(startPos.y, endPos.y)}px`;
vSegment.style.height = `${Math.abs(v1Length)}px`;
circuitGrid.appendChild(vSegment);
segments.push({ element: vSegment, type: 'vertical' });
} else {
// Use vertical then horizontal
const vSegment = document.createElement('div');
vSegment.className = 'wire-segment vertical';
vSegment.setAttribute('data-wire-id', wireId);
vSegment.style.left = `${startPos.x}px`;
vSegment.style.top = `${Math.min(startPos.y, endPos.y)}px`;
vSegment.style.height = `${Math.abs(v2Length)}px`;
circuitGrid.appendChild(vSegment);
segments.push({ element: vSegment, type: 'vertical' });
const hSegment = document.createElement('div');
hSegment.className = 'wire-segment horizontal';
hSegment.setAttribute('data-wire-id', wireId);
hSegment.style.left = `${Math.min(startPos.x, endPos.x)}px`;
hSegment.style.top = `${endPos.y}px`;
hSegment.style.width = `${Math.abs(h2Length)}px`;
circuitGrid.appendChild(hSegment);
segments.push({ element: hSegment, type: 'horizontal' });
}
// Get component IDs
const startComponent = startPoint.closest('.component');
const endComponent = endPoint.closest('.component');
const startComponentId = startComponent.getAttribute('data-id');
const endComponentId = endComponent.getAttribute('data-id');
const startTerminal = startPoint.getAttribute('data-terminal');
const endTerminal = endPoint.getAttribute('data-terminal');
// Add to wires array
wires.push({
id: wireId,
segments: segments,
startComponentId: startComponentId,
endComponentId: endComponentId,
startTerminal: startTerminal,
endTerminal: endTerminal
});
// Mark connection points as connected
startPoint.classList.add('connected');
endPoint.classList.add('connected');
updateStatusBar();
}
function getPointPosition(point) {
const rect = point.getBoundingClientRect();
const gridRect = circuitGrid.getBoundingClientRect();
return {
x: rect.left - gridRect.left + rect.width / 2,
y: rect.top - gridRect.top + rect.height / 2
};
}
function updateComponentWires(component) {
const componentId = component.getAttribute('data-id');
wires.forEach(wire => {
if (wire.startComponentId === componentId || wire.endComponentId === componentId) {
// Find the connection points
let startPoint, endPoint;
if (wire.startComponentId === componentId) {
startPoint = component.querySelector(`.connection-point[data-terminal="${wire.startTerminal}"]`);
const endComponent = components.find(c => c.id === wire.endComponentId).element;
endPoint = endComponent.querySelector(`.connection-point[data-terminal="${wire.endTerminal}"]`);
} else {
const startComponent = components.find(c => c.id === wire.startComponentId).element;
startPoint = startComponent.querySelector(`.connection-point[data-terminal="${wire.startTerminal}"]`);
endPoint = component.querySelector(`.connection-point[data-terminal="${wire.endTerminal}"]`);
}
// Update wire segments
const startPos = getPointPosition(startPoint);
const endPos = getPointPosition(endPoint);
// Calculate orthogonal path (L-shaped)
// Option 1: Horizontal then vertical
const h1Length = endPos.x - startPos.x;
const v1Length = endPos.y - startPos.y;
// Option 2: Vertical then horizontal
const v2Length = endPos.y - startPos.y;
const h2Length = endPos.x - startPos.x;
// Choose the option with the shortest total length
const option1Length = Math.abs(h1Length) + Math.abs(v1Length);
const option2Length = Math.abs(v2Length) + Math.abs(h2Length);
if (option1Length <= option2Length) {
// Use horizontal then vertical
wire.segments[0].element.style.width = `${Math.abs(h1Length)}px`;
wire.segments[0].element.style.left = `${Math.min(startPos.x, endPos.x)}px`;
wire.segments[0].element.style.top = `${startPos.y}px`;
wire.segments[1].element.style.height = `${Math.abs(v1Length)}px`;
wire.segments[1].element.style.left = `${endPos.x}px`;
wire.segments[1].element.style.top = `${Math.min(startPos.y, endPos.y)}px`;
} else {
// Use vertical then horizontal
wire.segments[0].element.style.height = `${Math.abs(v2Length)}px`;
wire.segments[0].element.style.left = `${startPos.x}px`;
wire.segments[0].element.style.top = `${Math.min(startPos.y, endPos.y)}px`;
wire.segments[1].element.style.width = `${Math.abs(h2Length)}px`;
wire.segments[1].element.style.left = `${Math.min(startPos.x, endPos.x)}px`;
wire.segments[1].element.style.top = `${endPos.y}px`;
}
}
});
if (showNodes) {
displayNodes();
}
}
function selectComponent(component) {
if (selectedComponent) {
selectedComponent.classList.remove('selected');
}
selectedComponent = component;
component.classList.add('selected');
component.style.zIndex = 10;
// Bring other components back to normal z-index
document.querySelectorAll('.component').forEach(comp => {
if (comp !== component) {
comp.style.zIndex = 2;
}
});
}
function showPropertyEditor(component, e) {
const type = component.getAttribute('data-type');
const value = component.getAttribute('data-value');
const unit = component.getAttribute('data-unit');
propValue.value = value;
propUnit.value = unit;
// Position the editor near the component
const rect = component.getBoundingClientRect();
const gridRect = circuitGrid.getBoundingClientRect();
propertyEditor.style.left = `${rect.left - gridRect.left + rect.width + 10}px`;
propertyEditor.style.top = `${rect.top - gridRect.top}px`;
propertyEditor.style.display = 'block';
// Store the component being edited
propertyEditor.setAttribute('data-component-id', component.getAttribute('data-id'));
}
function updateComponentProperties() {
const componentId = propertyEditor.getAttribute('data-component-id');
const component = components.find(c => c.id === componentId);
if (component) {
component.value = parseFloat(propValue.value) || 0;
component.unit = propUnit.value;
component.element.setAttribute('data-value', component.value);
component.element.setAttribute('data-unit', component.unit);
// Update label
const type = component.type;
let labelPrefix = '';
switch (type) {
case 'resistor':
labelPrefix = 'R';
break;
case 'capacitor':
labelPrefix = 'C';
break;
case 'inductor':
labelPrefix = 'L';
break;
case 'voltageSource':
labelPrefix = 'Vs';
break;
case 'currentSource':
labelPrefix = 'Is';
break;
case 'ground':
labelPrefix = 'GND';
break;
case 'diode':
labelPrefix = 'D';
break;
case 'led':
labelPrefix = 'LED';
break;
}
const compNum = componentCounters[type];
component.label = `${labelPrefix}${compNum} ${component.value}${component.unit}`;
component.element.querySelector('.component-label').textContent = component.label;
}
propertyEditor.style.display = 'none';
}
function runSimulation() {
// Clear debug log
if (debugMode) {
debugContent.textContent = '';
}
simulationStatus.textContent = 'Building circuit...';
simulationStatus.style.color = '#f59e0b';
// Build circuit graph
buildCircuitGraph();
simulationStatus.textContent = 'Solving circuit...';
// Solve circuit
const results = solveCircuit();
simulationStatus.textContent = 'Simulation complete';
simulationStatus.style.color = '#10b981';
// Display results
displayResults(results);
// Show modal
resultsModal.style.display = 'flex';
// Reset status after delay
setTimeout(() => {
simulationStatus.textContent = 'Ready';
simulationStatus.style.color = '';
}, 3000);
}
function buildCircuitGraph() {
// Reset nodes
nodes = {};
nextNodeId = 1;
// Create a map of all terminals
const terminals = {};
components.forEach(comp => {
terminals[`${comp.id}:left`] = null;
terminals[`${comp.id}:right`] = null;
});
// Create a union-find structure to merge connected terminals
const parent = {};
const rank = {};
// Initialize each terminal as its own set
Object.keys(terminals).forEach(terminal => {
parent[terminal] = terminal;
rank[terminal] = 0;
});
// Find function with path compression
function find(u) {
if (parent[u] !== u) {
parent[u] = find(parent[u]);
}
return parent[u];
}
// Union function by rank
function union(u, v) {
const rootU = find(u);
const rootV = find(v);
if (rootU === rootV) return;
if (rank[rootU] > rank[rootV]) {
parent[rootV] = rootU;
} else if (rank[rootU] < rank[rootV]) {
parent[rootU] = rootV;
} else {
parent[rootV] = rootU;
rank[rootU]++;
}
}
// Process wires to merge connected terminals
wires.forEach(wire => {
const terminal1 = `${wire.startComponentId}:${wire.startTerminal}`;
const terminal2 = `${wire.endComponentId}:${wire.endTerminal}`;
union(terminal1, terminal2);
});
// Assign node IDs to each set
const terminalToNodeId = {};
Object.keys(terminals).forEach(terminal => {
const root = find(terminal);
if (!terminalToNodeId[root]) {
terminalToNodeId[root] = nextNodeId++;
}
nodes[terminal] = terminalToNodeId[root];
});
// Find ground node and set it to 0
const groundComponent = components.find(c => c.type === 'ground');
if (groundComponent) {
const groundTerminal = `${groundComponent.id}:left`; // Ground only has one terminal
const groundNodeId = nodes[groundTerminal];
// Set ground node to 0
Object.keys(nodes).forEach(terminal => {
if (nodes[terminal] === groundNodeId) {
nodes[terminal] = 0;
}
});
}
updateStatusBar();
if (showNodes) {
displayNodes();
}
debugLog(`Node mapping:`);
for (const terminal in nodes) {
debugLog(` ${terminal} -> Node ${nodes[terminal]}`);
}
}
function solveCircuit() {
debugLog(`\n=== Circuit Analysis ===`);
// Get all unique nodes
const nodeIds = new Set();
Object.values(nodes).forEach(nodeId => {
nodeIds.add(nodeId);
});
const numNodes = nodeIds.size;
debugLog(`Total nodes: ${numNodes}`);
// Get voltage sources
const voltageSources = components.filter(c => c.type === 'voltageSource');
const numVoltageSources = voltageSources.length;
debugLog(`Voltage sources: ${numVoltageSources}`);
// Initialize MNA matrices
const G = math.zeros(numNodes, numNodes); // Conductance matrix
const B = math.zeros(numNodes, numVoltageSources); // Voltage source incidence matrix
const C = math.zeros(numVoltageSources, numNodes); // Transpose of B
const D = math.zeros(numVoltageSources, numVoltageSources); // For voltage sources, usually zero
const I = math.zeros(numNodes, 1); // Current source vector
const E = math.zeros(numVoltageSources, 1); // Voltage source vector
// Create a mapping from node ID to matrix index
const nodeToIndex = {};
let index = 0;
nodeIds.forEach(nodeId => {
nodeToIndex[nodeId] = index++;
debugLog(`Node ${nodeId} -> Index ${nodeToIndex[nodeId]}`);
});
// Create a mapping from voltage source ID to matrix index
const vsToIndex = {};
voltageSources.forEach((vs, i) => {
vsToIndex[vs.id] = i;
debugLog(`Voltage source ${vs.id} -> Index ${i}`);
});
// Process each component
components.forEach(comp => {
const leftTerminal = `${comp.id}:left`;
const rightTerminal = `${comp.id}:right`;
const node1 = nodes[leftTerminal];
const node2 = nodes[rightTerminal];
const idx1 = nodeToIndex[node1];
const idx2 = nodeToIndex[node2];
debugLog(`Processing ${comp.type} ${comp.id}: Node ${node1} (idx ${idx1}) to Node ${node2} (idx ${idx2})`);
switch (comp.type) {
case 'resistor':
const R = parseFloat(comp.value) || 1;
const conductance = 1 / R;
// Add to conductance matrix
if (idx1 !== undefined) {
G.set([idx1, idx1], G.get([idx1, idx1]) + conductance);
if (idx2 !== undefined && node1 !== node2) {
G.set([idx1, idx2], G.get([idx1, idx2]) - conductance);
G.set([idx2, idx1], G.get([idx2, idx1]) - conductance);
G.set([idx2, idx2], G.get([idx2, idx2]) + conductance);
}
}
debugLog(` Added resistor: R=${R}Ω, G=${conductance}S`);
break;
case 'voltageSource':
const V = parseFloat(comp.value) || 0;
const vsIdx = vsToIndex[comp.id];