-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
522 lines (455 loc) · 15.7 KB
/
script.js
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
const canvas = document.getElementById('circuitCanvas');
const ctx = canvas.getContext('2d');
let isDragging = false;
let isConnecting = false;
let dragItem = null;
let startComponent = null;
let components = [];
let connections = [];
let tempConnection = null;
let connectionMode = false;
let lastTapTime = 0;
// Add styles for the value dialog
const style = document.createElement('style');
style.textContent = `
.value-dialog {
position: fixed;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
z-index: 1000;
}
.value-dialog input {
margin: 10px 0;
padding: 5px;
width: 150px;
}
.value-dialog button {
margin: 5px;
padding: 5px 10px;
background: #007BFF;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.value-dialog button:hover {
background: #0056b3;
}
.value-dialog select {
margin: 10px 0;
padding: 5px;
width: 150px;
}
`;
document.head.appendChild(style);
// Add a connection mode button to the toolbar
const connectionBtn = document.createElement('button');
connectionBtn.className = 'button';
connectionBtn.id = 'connectionBtn';
connectionBtn.textContent = 'Connection Mode: OFF';
document.querySelector('.toolbar').appendChild(connectionBtn);
// Create a simulate button and add it to the toolbar
const simulateBtn = document.createElement('button');
simulateBtn.className = 'button';
simulateBtn.id = 'simulateBtn';
simulateBtn.textContent = 'Simulate Circuit';
document.querySelector('.toolbar').appendChild(simulateBtn);
// Add event listener to the simulate button
simulateBtn.addEventListener('click', () => {
simulateCircuit();
});
// Toggle connection mode
connectionBtn.addEventListener('click', () => {
connectionMode = !connectionMode;
connectionBtn.textContent = `Connection Mode: ${connectionMode ? 'ON' : 'OFF'}`;
connectionBtn.style.backgroundColor = connectionMode ? '#ff4444' : '#007BFF';
});
function createValueDialog(component) {
const dialog = document.createElement('div');
dialog.className = 'value-dialog';
const valueInput = document.createElement('input');
valueInput.type = 'number';
valueInput.step = '0.1';
valueInput.value = component.value || '';
valueInput.placeholder = 'Enter value';
const unitSelect = document.createElement('select');
let units;
switch(component.type) {
case 'resistor':
units = ['Ω', 'kΩ', 'MΩ'];
break;
case 'capacitor':
units = ['pF', 'nF', 'µF', 'mF'];
break;
case 'inductor':
units = ['µH', 'mH', 'H'];
break;
case 'battery':
units = ['V'];
break;
}
units.forEach(unit => {
const option = document.createElement('option');
option.value = unit;
option.textContent = unit;
if (unit === component.unit) option.selected = true;
unitSelect.appendChild(option);
});
const saveBtn = document.createElement('button');
saveBtn.textContent = 'Save';
const cancelBtn = document.createElement('button');
cancelBtn.textContent = 'Cancel';
dialog.appendChild(valueInput);
dialog.appendChild(unitSelect);
dialog.appendChild(saveBtn);
dialog.appendChild(cancelBtn);
// Position dialog near the component
dialog.style.left = `${component.x + canvas.offsetLeft + component.width}px`;
dialog.style.top = `${component.y + canvas.offsetTop}px`;
saveBtn.onclick = () => {
component.value = valueInput.value;
component.unit = unitSelect.value;
document.body.removeChild(dialog);
draw();
};
cancelBtn.onclick = () => {
document.body.removeChild(dialog);
};
document.body.appendChild(dialog);
valueInput.focus();
}
function addComponent(type) {
const componentTypes = {
resistor: { color: 'blue', label: 'R', type: 'resistor' },
capacitor: { color: 'orange', label: 'C', type: 'capacitor' },
inductor: { color: 'green', label: 'L', type: 'inductor' },
battery: { color: 'yellow', label: 'B', type: 'battery' }
};
const component = {
x: Math.random() * (canvas.width - 50),
y: Math.random() * (canvas.height - 20),
width: 50,
height: 20,
value: '',
unit: '',
...componentTypes[type]
};
components.push(component);
draw();
}
// Mouse and Touch Event Handlers
canvas.addEventListener('mousedown', handleStart);
canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
handleStart(e.touches[0]);
});
canvas.addEventListener('mousemove', handleMove);
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
handleMove(e.touches[0]);
});
canvas.addEventListener('mouseup', handleEnd);
canvas.addEventListener('touchend', (e) => {
e.preventDefault();
handleEnd(e);
});
function handleStart(event) {
const pos = getEventPos(event);
const clickedComponent = findComponentUnderMouse(pos);
if (connectionMode && clickedComponent) {
if (!startComponent) {
isConnecting = true;
startComponent = clickedComponent;
tempConnection = {
start: {
x: clickedComponent.x + clickedComponent.width / 2,
y: clickedComponent.y + clickedComponent.height / 2
},
end: { x: pos.x, y: pos.y }
};
}
} else if (clickedComponent) {
isDragging = true;
dragItem = clickedComponent;
dragItem.offsetX = pos.x - clickedComponent.x;
dragItem.offsetY = pos.y - clickedComponent.y;
}
}
function handleMove(event) {
const pos = getEventPos(event);
if (isDragging && dragItem) {
dragItem.x = pos.x - dragItem.offsetX;
dragItem.y = pos.y - dragItem.offsetY;
// Update connected wires
connections.forEach(connection => {
if (connection.startComponent === dragItem) {
connection.start.x = dragItem.x + dragItem.width / 2;
connection.start.y = dragItem.y + dragItem.height / 2;
}
if (connection.endComponent === dragItem) {
connection.end.x = dragItem.x + dragItem.width / 2;
connection.end.y = dragItem.y + dragItem.height / 2;
}
});
}
if (isConnecting && tempConnection) {
tempConnection.end.x = pos.x;
tempConnection.end.y = pos.y;
}
draw();
}
function handleEnd(event) {
if (isConnecting && startComponent) {
const pos = getEventPos(event.changedTouches ? event.changedTouches[0] : event);
const endComponent = findComponentUnderMouse(pos);
if (endComponent && endComponent !== startComponent) {
connections.push({
start: {
x: startComponent.x + startComponent.width / 2,
y: startComponent.y + startComponent.height / 2
},
end: {
x: endComponent.x + endComponent.width / 2,
y: endComponent.y + endComponent.height / 2
},
startComponent: startComponent,
endComponent: endComponent
});
}
isConnecting = false;
startComponent = null;
tempConnection = null;
}
isDragging = false;
dragItem = null;
draw();
}
// Double-click handler
canvas.addEventListener('dblclick', handleDoubleClick);
canvas.addEventListener('touchend', (e) => {
const currentTime = new Date().getTime();
const tapLength = currentTime - lastTapTime;
if (tapLength < 500 && tapLength > 0) {
e.preventDefault();
handleDoubleClick(e.changedTouches[0]);
}
lastTapTime = currentTime;
});
function handleDoubleClick(event) {
const pos = getEventPos(event);
const clickedComponent = findComponentUnderMouse(pos);
if (clickedComponent) {
createValueDialog(clickedComponent);
}
}
function findComponentUnderMouse(pos) {
return components.find(component =>
pos.x >= component.x &&
pos.x <= component.x + component.width &&
pos.y >= component.y &&
pos.y <= component.y + component.height
);
}
function getEventPos(event) {
const rect = canvas.getBoundingClientRect();
const x = (event.clientX || event.pageX) - rect.left;
const y = (event.clientY || event.pageY) - rect.top;
return { x, y };
}
function drawConnection(connection, color) {
ctx.beginPath();
ctx.moveTo(connection.start.x, connection.start.y);
ctx.lineTo(connection.end.x, connection.end.y);
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.stroke();
}
function displaySimulationResults(data) {
const resultDiv = document.getElementById('simulationResults');
resultDiv.innerHTML = `
<p>Voltage at Node N001: ${data.output.voltage} V</p>
`;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw connections
connections.forEach(connection => {
drawConnection(connection, 'red');
});
if (tempConnection) {
drawConnection(tempConnection, 'blue');
}
// Draw components with symbols
components.forEach(component => {
switch (component.type) {
case 'resistor':
drawResistor(component);
break;
case 'capacitor':
drawCapacitor(component);
break;
case 'inductor':
drawInductor(component);
break;
case 'battery':
drawBattery(component);
break;
}
// Draw component value if it exists
if (component.value) {
ctx.fillStyle = 'black';
ctx.font = '12px Arial';
const valueText = `${component.value}${component.unit}`;
ctx.fillText(valueText,
component.x + component.width / 2 - ctx.measureText(valueText).width / 2,
component.y + component.height + 15
);
}
});
}
// Function to draw resistor symbol
function drawResistor(component) {
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.beginPath();
let x = component.x;
let y = component.y;
ctx.moveTo(x, y + component.height / 2);
for (let i = 0; i < 5; i++) {
x += component.width / 5;
y = (i % 2 === 0) ? component.y : component.y + component.height;
ctx.lineTo(x, y);
}
ctx.lineTo(component.x + component.width, component.y + component.height / 2);
ctx.stroke();
}
// Function to draw capacitor symbol
function drawCapacitor(component) {
ctx.strokeStyle = 'orange';
ctx.lineWidth = 2;
ctx.beginPath();
let x = component.x;
let y = component.y;
ctx.moveTo(x, y + component.height / 2);
ctx.lineTo(x + component.width / 3, y + component.height / 2);
ctx.moveTo(x + component.width * 2 / 3, y);
ctx.lineTo(x + component.width * 2 / 3, y + component.height);
ctx.moveTo(x + component.width * 2 / 3 + component.width / 6, y);
ctx.lineTo(x + component.width * 2 / 3 + component.width / 6, y + component.height);
ctx.stroke();
}
// Function to draw inductor symbol
function drawInductor(component) {
ctx.strokeStyle = 'green';
ctx.lineWidth = 2;
ctx.beginPath();
let x = component.x;
let y = component.y + component.height / 2;
ctx.moveTo(x, y);
for (let i = 0; i < 4; i++) {
x += component.width / 4;
ctx.arc(x, y, component.height / 4, Math.PI, 0, true);
}
ctx.stroke();
}
// Function to draw battery symbol
function drawBattery(component) {
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
let x = component.x;
let y = component.y;
ctx.beginPath();
ctx.moveTo(x, y + component.height / 2);
ctx.lineTo(x + component.width / 4, y + component.height / 2);
ctx.moveTo(x + component.width / 2 - 5, y);
ctx.lineTo(x + component.width / 2 - 5, y + component.height);
ctx.moveTo(x + component.width / 2 + 5, y + component.height / 4);
ctx.lineTo(x + component.width / 2 + 5, y + component.height * 3 / 4);
ctx.moveTo(x + component.width * 3 / 4, y + component.height / 2);
ctx.lineTo(x + component.width, y + component.height / 2);
ctx.stroke();
}
function generateLTSpiceFile() {
let ltspiceCircuit = ".title Circuit Simulation\n";
components.forEach(component => {
switch (component.type) {
case 'resistor':
ltspiceCircuit += `R${component.label} ${component.x} ${component.y} ${component.value}\n`;
break;
case 'capacitor':
ltspiceCircuit += `C${component.label} ${component.x} ${component.y} ${component.value}\n`;
break;
case 'battery':
ltspiceCircuit += `V${component.label} ${component.x} ${component.y} ${component.value}\n`;
break;
// Add more components as needed
}
});
// Include connections here (you would need to interpret the connections between components)
return ltspiceCircuit;
}
function simulateCircuit() {
const circuitFile = generateLTSpiceFile();
fetch('http://localhost:3000/simulate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ circuitFile })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Simulation Results:', data.output);
displaySimulationResults(data);
})
.catch(error => {
console.error('Error:', error);
});
}
// function draw() {
// ctx.clearRect(0, 0, canvas.width, canvas.height);
// // Draw connections
// connections.forEach(connection => {
// drawConnection(connection, 'red');
// });
// if (tempConnection) {
// drawConnection(tempConnection, 'blue');
// }
// // Draw components
// components.forEach(component => {
// // Draw component box
// ctx.fillStyle = component.color;
// ctx.fillRect(component.x, component.y, component.width, component.height);
// // Draw component label
// ctx.fillStyle = 'white';
// ctx.font = 'bold 14px Arial';
// ctx.fillText(component.label,
// component.x + component.width/2 - 5,
// component.y + component.height/2 + 5
// );
// // Draw component value if it exists
// if (component.value) {
// ctx.fillStyle = 'black';
// ctx.font = '12px Arial';
// const valueText = `${component.value}${component.unit}`;
// ctx.fillText(valueText,
// component.x + component.width/2 - ctx.measureText(valueText).width/2,
// component.y + component.height + 15
// );
// }
// });
// }
// Prevent context menu on right-click
canvas.addEventListener('contextmenu', (e) => e.preventDefault());
// Add component buttons
document.getElementById('addResistorBtn').addEventListener('click', () => addComponent('resistor'));
document.getElementById('addCapacitorBtn').addEventListener('click', () => addComponent('capacitor'));
document.getElementById('addInductorBtn').addEventListener('click', () => addComponent('inductor'));
document.getElementById('addBatteryBtn').addEventListener('click', () => addComponent('battery'));