Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2624 lines (2320 loc) · 92.7 KB
/
Copy pathscript.js
File metadata and controls
2624 lines (2320 loc) · 92.7 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
const byId = (id) => document.getElementById(id);
const materialData = {
copper: {
rho: 1.724e-8,
density: 8960
},
silver: {
rho: 1.626e-8,
density: 10490
},
aluminum: {
rho: 2.82e-8,
density: 2700
},
gold: {
rho: 2.428e-8,
density: 19320
},
brass: {
rho: 7.836e-8,
density: 8500
},
tin: {
rho: 1.149e-7,
density: 7310
},
nickel: {
rho: 7.836e-8,
density: 8908
}
};
const materialVisual = {
copper: 0xc6763a,
silver: 0xcdd4dd,
aluminum: 0xb2b9c5,
gold: 0xd5af37,
brass: 0xb68a47,
tin: 0xaeb4bf,
nickel: 0x8f979d
};
const ui = {
coilDiameter: byId("coilDiameter"),
coilLength: byId("coilLength"),
turns: byId("turns"),
pitch: byId("pitch"),
layers: byId("layers"),
layerSpacing: byId("layerSpacing"),
autoLength: byId("autoLength"),
wireDiameter: byId("wireDiameter"),
conductorDiameter: byId("conductorDiameter"),
insulationThickness: byId("insulationThickness"),
material: byId("material"),
wireType: byId("wireType"),
strands: byId("strands"),
strandDiameter: byId("strandDiameter"),
freq: byId("freq"),
freqMin: byId("freqMin"),
freqMax: byId("freqMax"),
parasiticExternal: byId("parasiticExternal"),
current: byId("current"),
cap: byId("cap"),
capMin: byId("capMin"),
capMax: byId("capMax"),
coreType: byId("coreType"),
coreDiameter: byId("coreDiameter"),
muR: byId("muR"),
coreLength: byId("coreLength"),
corePosition: byId("corePosition"),
holdRange: byId("holdRange"),
holdGeom: byId("holdGeom"),
holdWire: byId("holdWire"),
holdElec: byId("holdElec"),
holdCap: byId("holdCap"),
holdCore: byId("holdCore"),
openWireStandards: byId("openWireStandards"),
openCapStandards: byId("openCapStandards"),
exportPreset: byId("exportPreset"),
importPreset: byId("importPreset"),
importPresetFile: byId("importPresetFile"),
runOptimizer: byId("runOptimizer"),
optFreqMin: byId("optFreqMin"),
optFreqMax: byId("optFreqMax"),
optQMin: byId("optQMin"),
optTurnsMin: byId("optTurnsMin"),
optTurnsMax: byId("optTurnsMax"),
optPitchMin: byId("optPitchMin"),
optPitchMax: byId("optPitchMax"),
refModal: byId("refModal"),
refModalTitle: byId("refModalTitle"),
refModalBody: byId("refModalBody"),
refModalClose: byId("refModalClose"),
appNotice: byId("appNotice"),
languageSelect: byId("languageSelect"),
results: byId("results"),
coilViewer: byId("coilViewer"),
chartQ: byId("chartQ"),
chartRac: byId("chartRac"),
chartCap: byId("chartCap")
};
let currentLanguage = "en";
const i18n = {
en: {
pageTitle: "CoilCalc - Coil Calculator for Crystal Radio",
langLabel: "Language",
relatedProjectsLabel: "Related projects",
authorPanelTitle: "Author",
heroTitle: "Coil Calculator for Crystal Radio",
heroDesc: "Calculate inductance, resistance, Q factor, self-resonant frequency, LC tuning range, and physical winding parameters.",
sectionRange: "1. Desired Frequency Range",
sectionGeom: "2. Coil Geometry",
sectionWire: "3. Wire",
sectionElec: "4. Electrical Parameters",
sectionCap: "5. Tuning Capacitor",
sectionCore: "6. Former / Core",
sectionTools: "7. Presets & Optimizer",
section3d: "8. 3D LC Circuit Model",
sectionResults: "9. Results",
sectionCharts: "10. Analysis Charts",
presetTitle: "JSON Presets",
presetHint: "Save current project to JSON and load it later.",
exportPresetBtn: "Export preset",
importPresetBtn: "Import preset",
optimizerTitle: "Range Optimizer",
runOptimizerBtn: "Run optimizer",
chartQTitle: "Q(f)",
chartRacTitle: "Rac(f)",
chartCapTitle: "Coverage by C",
wireStandardsBtn: "Wire standards",
capStandardsBtn: "KPE standards",
modalClose: "Close",
wireModalTitle: "Standard Wire Sections (GOST / IEC / AWG)",
capModalTitle: "Standard Variable Capacitors (KPE)",
wireModalNote: "Reference table for common standardized conductor sizes. Verify insulation class and current density for your application.",
capModalNote: "Reference table for common radio tuning variable capacitor ranges used in USSR/RU and international practice.",
refSearchPlaceholder: "Search in standards...",
refApplyHint: "Click a row to apply values",
tableSystem: "System",
tableDesignation: "Designation",
tableCross: "Cross-section, mm2",
tableDiameter: "Equivalent diameter, mm",
tableUse: "Typical use",
tableCapRange: "Capacitance range",
tableGang: "Sections",
holdText: "Hold",
autoLengthText: "Auto-calculate coil length (l ≈ N · p / layers)",
litzHint: "Litz example: 20 × 0.05 mm",
viewerHint: "LMB: rotate, wheel: zoom, RMB/Shift+LMB: pan.",
threeLoadFail: "3D engine failed to load.",
holdValidationAll: "At least one block must stay editable.",
holdValidationResonance: "At least one of Desired Frequency Range, Coil Geometry, Electrical Parameters, or Tuning Capacitor must stay editable.",
holdBlockedWire: "Wire block is on Hold. Disable Hold to apply this standard.",
holdBlockedCap: "Tuning Capacitor block is on Hold. Disable Hold to apply this standard.",
presetExported: "Preset exported.",
presetImported: "Preset imported.",
presetImportError: "Invalid preset file.",
optimizerBlocked: "Disable Hold for Geometry and Tuning Capacitor to apply optimizer results.",
optimizerNoSolution: "No candidate matched target Q in current limits.",
optimizerDone: "Optimizer applied best candidate.",
legendTitle: "3D LC Legend",
legendMaterial: "Material",
legendCore: "Core",
legendInductance: "L",
legendCap: "C",
legendFreq: "f",
materialNames: {
copper: "Copper",
silver: "Silver",
aluminum: "Aluminum",
gold: "Gold",
brass: "Brass",
tin: "Tin",
nickel: "Nickel"
},
coreNames: {
air: "Air",
ferrite: "Ferrite",
powdered: "Powdered iron",
plastic: "PVC/Plastic"
},
modelLabelCoil: "Coil",
modelLabelCap: "Variable capacitor",
coverageInRange: "Within range",
coveragePartial: "Partially out of range",
labels: {
coilDiameter: "Coil diameter, mm",
coilLength: "Coil length, mm",
turns: "Number of turns",
pitch: "Winding pitch, mm",
layers: "Number of layers",
layerSpacing: "Layer spacing, mm",
wireDiameter: "Wire diameter (with insulation), mm",
conductorDiameter: "Conductor diameter (copper), mm",
insulationThickness: "Insulation thickness, mm",
material: "Material",
wireType: "Wire type",
strands: "Number of strands",
strandDiameter: "Strand diameter, mm",
freq: "Frequency, kHz",
freqMin: "Minimum frequency, kHz",
freqMax: "Maximum frequency, kHz",
parasiticExternal: "Parasitic capacitance ext., pF",
current: "Current for energy, mA",
cap: "Capacitance C, pF",
capMin: "Minimum capacitance, pF",
capMax: "Maximum capacitance, pF",
coreType: "Former/core type",
coreDiameter: "Core diameter, mm",
muR: "Relative permeability (μr)",
coreLength: "Core length, mm",
corePosition: "Core position, % inside coil"
,
optFreqMin: "Target f min, kHz",
optFreqMax: "Target f max, kHz",
optQMin: "Target Q min",
optTurnsMin: "N min",
optTurnsMax: "N max",
optPitchMin: "Pitch min, mm",
optPitchMax: "Pitch max, mm"
},
options: {
copper: "Copper (Cu) ~100%",
silver: "Silver (Ag) ~106%",
aluminum: "Aluminum (Al) ~61%",
gold: "Gold (Au) ~71%",
brass: "Brass ~15-30%",
tin: "Tin ~15%",
nickel: "Nickel (Ni) ~22%",
solid: "Solid wire",
stranded: "Stranded wire",
litz: "Litz wire",
air: "Air core",
ferrite: "Ferrite",
powdered: "Powdered iron",
plastic: "PVC/Plastic"
},
resultNames: {
inductance: "Inductance L",
rdc: "DC resistance Rdc",
rac: "AC resistance Rac",
q: "Q factor at f",
xl: "Reactance Xl",
srf: "Self-resonant frequency",
cpar: "Parasitic capacitance",
wireLen: "Wire length",
mass: "Conductor mass",
cross: "Wire cross-section",
density: "Winding density",
fill: "Fill factor",
outer: "Coil outer diameter",
depth: "Winding depth",
energy: "Magnetic energy",
fFixed: "f from fixed C",
tune: "Tuning range",
coverage: "Coverage check",
muEff: "Effective mu"
}
},
ru: {
pageTitle: "CoilCalc - Калькулятор катушек для детекторного приемника",
langLabel: "Язык",
relatedProjectsLabel: "Связанные проекты",
authorPanelTitle: "Автор",
heroTitle: "Калькулятор катушек для детекторного приемника",
heroDesc: "Расчет индуктивности, сопротивления, добротности, собственной резонансной частоты, диапазона настройки LC-контура и физических параметров намотки.",
sectionRange: "1. Желаемый диапазон частот",
sectionGeom: "2. Геометрия катушки",
sectionWire: "3. Провод",
sectionElec: "4. Электрические параметры",
sectionCap: "5. Конденсатор контура",
sectionCore: "6. Каркас / Сердечник",
sectionTools: "7. Пресеты и оптимизатор",
section3d: "8. 3D-модель LC-контура",
sectionResults: "9. Результаты",
sectionCharts: "10. Графики анализа",
presetTitle: "JSON пресеты",
presetHint: "Сохраните текущий проект в JSON и загрузите его позже.",
exportPresetBtn: "Экспорт пресета",
importPresetBtn: "Импорт пресета",
optimizerTitle: "Оптимизатор диапазона",
runOptimizerBtn: "Запустить оптимизатор",
chartQTitle: "Q(f)",
chartRacTitle: "Rac(f)",
chartCapTitle: "Покрытие по C",
wireStandardsBtn: "Стандарты провода",
capStandardsBtn: "Стандарты КПЕ",
modalClose: "Закрыть",
wireModalTitle: "Стандартные сечения проводов (ГОСТ / IEC / AWG)",
capModalTitle: "Стандартные КПЕ",
wireModalNote: "Справочная таблица типовых стандартизованных сечений проводников. Для практики учитывайте класс изоляции и допустимую плотность тока.",
capModalNote: "Справочная таблица типовых диапазонов переменных конденсаторов для радионастройки (СССР/РФ и международная практика).",
refSearchPlaceholder: "Поиск по стандартам...",
refApplyHint: "Кликните по строке для подстановки",
tableSystem: "Система",
tableDesignation: "Обозначение",
tableCross: "Сечение, mm2",
tableDiameter: "Эквив. диаметр, mm",
tableUse: "Типовое применение",
tableCapRange: "Диапазон емкости",
tableGang: "Секции",
holdText: "Фиксировать",
autoLengthText: "Авторасчет длины намотки (l ≈ N · p / layers)",
litzHint: "Пример литцендрата: 20 × 0.05 mm",
viewerHint: "ЛКМ: вращение, колесо: масштаб, ПКМ/Shift+ЛКМ: панорамирование.",
threeLoadFail: "3D-движок не загрузился.",
holdValidationAll: "Хотя бы один блок должен оставаться редактируемым.",
holdValidationResonance: "Хотя бы один из блоков Desired Frequency Range, Coil Geometry, Electrical Parameters или Tuning Capacitor должен оставаться редактируемым.",
holdBlockedWire: "Блок Провод зафиксирован Hold. Снимите Hold для применения стандарта.",
holdBlockedCap: "Блок Конденсатор контура зафиксирован Hold. Снимите Hold для применения стандарта.",
presetExported: "Пресет экспортирован.",
presetImported: "Пресет импортирован.",
presetImportError: "Некорректный файл пресета.",
optimizerBlocked: "Снимите Hold у Геометрии и Конденсатора контура для применения результата оптимизатора.",
optimizerNoSolution: "В текущих пределах не найден кандидат с целевой Q.",
optimizerDone: "Оптимизатор применил лучший вариант.",
legendTitle: "Легенда 3D LC",
legendMaterial: "Материал",
legendCore: "Сердечник",
legendInductance: "L",
legendCap: "C",
legendFreq: "f",
materialNames: {
copper: "Медь",
silver: "Серебро",
aluminum: "Алюминий",
gold: "Золото",
brass: "Латунь",
tin: "Олово",
nickel: "Никель"
},
coreNames: {
air: "Воздух",
ferrite: "Феррит",
powdered: "Порошковое железо",
plastic: "ПВХ/пластик"
},
modelLabelCoil: "Катушка",
modelLabelCap: "КПЕ",
coverageInRange: "Внутри диапазона",
coveragePartial: "Частично вне диапазона",
labels: {
coilDiameter: "Диаметр катушки, mm",
coilLength: "Длина катушки, mm",
turns: "Количество витков",
pitch: "Шаг намотки, mm",
layers: "Количество слоев",
layerSpacing: "Расстояние между слоями, mm",
wireDiameter: "Диаметр провода (с изоляцией), mm",
conductorDiameter: "Диаметр проводника (медь), mm",
insulationThickness: "Толщина изоляции, mm",
material: "Материал",
wireType: "Тип провода",
strands: "Количество жил",
strandDiameter: "Диаметр жилы, mm",
freq: "Частота, kHz",
freqMin: "Минимальная частота, kHz",
freqMax: "Максимальная частота, kHz",
parasiticExternal: "Внешняя паразитная емкость, pF",
current: "Ток для энергии, mA",
cap: "Емкость C, pF",
capMin: "Минимальная емкость, pF",
capMax: "Максимальная емкость, pF",
coreType: "Тип каркаса/сердечника",
coreDiameter: "Диаметр сердечника, mm",
muR: "Относительная проницаемость (μr)",
coreLength: "Длина сердечника, mm",
corePosition: "Положение сердечника, % внутри катушки"
,
optFreqMin: "Целевая f min, kHz",
optFreqMax: "Целевая f max, kHz",
optQMin: "Целевая Q min",
optTurnsMin: "N min",
optTurnsMax: "N max",
optPitchMin: "Шаг min, mm",
optPitchMax: "Шаг max, mm"
},
options: {
copper: "Медь (Cu) ~100%",
silver: "Серебро (Ag) ~106%",
aluminum: "Алюминий (Al) ~61%",
gold: "Золото (Au) ~71%",
brass: "Латунь ~15-30%",
tin: "Олово ~15%",
nickel: "Никель (Ni) ~22%",
solid: "Одножильный",
stranded: "Многожильный",
litz: "Литцендрат",
air: "Воздушный",
ferrite: "Феррит",
powdered: "Порошковое железо",
plastic: "ПВХ/Пластик"
},
resultNames: {
inductance: "Индуктивность L",
rdc: "Сопротивление DC Rdc",
rac: "Сопротивление AC Rac",
q: "Добротность Q на f",
xl: "Реактивное сопротивление Xl",
srf: "Собственная резонансная частота",
cpar: "Паразитная емкость",
wireLen: "Длина провода",
mass: "Масса проводника",
cross: "Сечение провода",
density: "Плотность намотки",
fill: "Коэффициент заполнения",
outer: "Наружный диаметр катушки",
depth: "Глубина намотки",
energy: "Магнитная энергия",
fFixed: "f при фиксированной C",
tune: "Диапазон настройки",
coverage: "Покрытие диапазона",
muEff: "Эффективная μ"
}
}
};
function setLabelText(controlId, text) {
const control = byId(controlId);
if (!control) {
return;
}
const label = control.closest("label");
if (!label) {
return;
}
const textNode = Array.from(label.childNodes).find((n) => n.nodeType === Node.TEXT_NODE);
if (textNode) {
textNode.textContent = `${text}\n `;
}
}
function applyLanguage(lang) {
currentLanguage = i18n[lang] ? lang : "en";
const t = i18n[currentLanguage];
document.documentElement.lang = currentLanguage;
document.title = t.pageTitle;
const staticMap = {
langLabel: t.langLabel,
projectLinksLabel: t.relatedProjectsLabel,
authorPanelTitle: t.authorPanelTitle,
heroTitle: t.heroTitle,
heroDesc: t.heroDesc,
sectionRange: t.sectionRange,
sectionGeom: t.sectionGeom,
sectionWire: t.sectionWire,
sectionElec: t.sectionElec,
sectionCap: t.sectionCap,
sectionCore: t.sectionCore,
sectionTools: t.sectionTools,
section3d: t.section3d,
sectionResults: t.sectionResults,
sectionCharts: t.sectionCharts,
presetTitle: t.presetTitle,
presetHint: t.presetHint,
optimizerTitle: t.optimizerTitle,
chartQTitle: t.chartQTitle,
chartRacTitle: t.chartRacTitle,
chartCapTitle: t.chartCapTitle,
autoLengthText: t.autoLengthText,
litzHint: t.litzHint,
viewerHint: t.viewerHint
};
for (const [id, text] of Object.entries(staticMap)) {
const el = byId(id);
if (el) {
if (el.children.length === 0) {
el.textContent = text;
}
}
}
for (const el of document.querySelectorAll(".hold-text")) {
el.textContent = t.holdText;
}
if (ui.openWireStandards) {
ui.openWireStandards.textContent = t.wireStandardsBtn;
}
if (ui.openCapStandards) {
ui.openCapStandards.textContent = t.capStandardsBtn;
}
if (ui.exportPreset) {
ui.exportPreset.textContent = t.exportPresetBtn;
}
if (ui.importPreset) {
ui.importPreset.textContent = t.importPresetBtn;
}
if (ui.runOptimizer) {
ui.runOptimizer.textContent = t.runOptimizerBtn;
}
if (ui.refModalClose) {
ui.refModalClose.setAttribute("aria-label", t.modalClose);
}
for (const [id, text] of Object.entries(t.labels)) {
setLabelText(id, text);
}
const optionMap = [
[ui.material, t.options],
[ui.wireType, t.options],
[ui.coreType, t.options]
];
for (const [select, dict] of optionMap) {
if (!select) {
continue;
}
for (const opt of select.options) {
if (dict[opt.value]) {
opt.textContent = dict[opt.value];
}
}
}
}
function equivalentDiameterFromArea(areaMm2) {
return Math.sqrt((4 * areaMm2) / Math.PI);
}
function areaFromDiameterMm(diameterMm) {
return Math.PI * Math.pow(diameterMm / 2, 2);
}
function awgDiameterMm(gauge) {
return 0.127 * Math.pow(92, (36 - gauge) / 39);
}
function buildWireReferenceItems() {
const items = [];
const gostWindingDiamMm = [
0.05, 0.056, 0.063, 0.071, 0.08, 0.09, 0.1, 0.112, 0.125, 0.14, 0.16, 0.18,
0.2, 0.224, 0.25, 0.28, 0.315, 0.355, 0.4, 0.45, 0.5, 0.56, 0.63, 0.71,
0.8, 0.9, 1.0, 1.12, 1.25, 1.4, 1.6, 1.8, 2.0
];
for (const d of gostWindingDiamMm) {
const area = areaFromDiameterMm(d);
items.push({
system: "GOST winding wire (PETV/PEV)",
designation: `d=${d.toFixed(3)} mm`,
area,
diameter: d,
useEn: d <= 0.2 ? "RF coils / IF / sensors" : "Power windings / chokes",
useRu: d <= 0.2 ? "ВЧ катушки / ПЧ / датчики" : "Силовые намотки / дроссели",
apply: { type: "wire", conductorDiameterMm: d }
});
}
const litzConstructions = [
["Litz 10x0.05", 10, 0.05, "Fine RF coils", "Малые ВЧ-катушки"],
["Litz 20x0.05", 20, 0.05, "Crystal radio / MW", "Детекторный приемник / СВ"],
["Litz 40x0.05", 40, 0.05, "High-Q LF/MW coils", "Высокодобротные ДВ/СВ катушки"],
["Litz 60x0.05", 60, 0.05, "High-Q MW coils", "Высокодобротные СВ катушки"],
["Litz 100x0.05", 100, 0.05, "Low-loss tuned circuits", "Малопотерные контуры"],
["Litz 120x0.07", 120, 0.07, "Antenna/RF transformers", "Антенные/ВЧ трансформаторы"],
["Litz 165x0.07", 165, 0.07, "Power RF inductors", "Силовые ВЧ-дроссели"]
];
for (const [name, strands, strandDiameter, useEn, useRu] of litzConstructions) {
const area = Math.max(1, strands) * areaFromDiameterMm(strandDiameter);
const equivDiameter = equivalentDiameterFromArea(area);
items.push({
system: "Litz constructions (reference)",
designation: name,
area,
diameter: equivDiameter,
useEn,
useRu,
apply: {
type: "wire",
wireType: "litz",
strands,
strandDiameterMm: strandDiameter,
conductorDiameterMm: equivDiameter
}
});
}
const iecAreas = [
0.5, 0.75, 1, 1.5, 2.5, 4, 6, 10, 16, 25, 35, 50, 70, 95, 120, 150, 185, 240
];
for (const area of iecAreas) {
items.push({
system: "IEC 60228 / GOST R 53769",
designation: `${area} mm2`,
area,
diameter: equivalentDiameterFromArea(area),
useEn: area < 4 ? "Low-power wiring" : "Power wiring",
useRu: area < 4 ? "Слаботочные цепи" : "Силовая проводка",
apply: { type: "wire", conductorDiameterMm: equivalentDiameterFromArea(area) }
});
}
const swgReference = [
[40, 0.122], [38, 0.152], [36, 0.193], [34, 0.234], [32, 0.274], [30, 0.315],
[28, 0.376], [26, 0.457], [24, 0.559], [22, 0.711], [20, 0.914], [18, 1.219],
[16, 1.626], [14, 2.032], [12, 2.642], [10, 3.251], [8, 4.064], [6, 4.877]
];
for (const [gauge, diameter] of swgReference) {
const area = areaFromDiameterMm(diameter);
items.push({
system: "SWG (reference)",
designation: `SWG ${gauge}`,
area,
diameter,
useEn: gauge >= 28 ? "Fine winding wire" : "General winding / leads",
useRu: gauge >= 28 ? "Тонкий намоточный провод" : "Общая намотка / выводы",
apply: { type: "wire", conductorDiameterMm: diameter }
});
}
for (let gauge = 46; gauge >= -3; gauge -= 1) {
const diameter = awgDiameterMm(gauge);
const area = areaFromDiameterMm(diameter);
let designation = `AWG ${gauge}`;
if (gauge === -1) {
designation = "AWG 00";
} else if (gauge === -2) {
designation = "AWG 000";
} else if (gauge === -3) {
designation = "AWG 0000";
}
items.push({
system: "AWG (ASTM B258)",
designation,
area,
diameter,
useEn: gauge >= 30 ? "Fine windings" : "Lead wires / power",
useRu: gauge >= 30 ? "Тонкие намотки" : "Выводы / питание",
apply: { type: "wire", conductorDiameterMm: diameter }
});
}
return items;
}
function buildCapReferenceItems() {
const rows = [
["USSR/RU radio practice", "Air KPE", 8, 250, "1x", "Short-wave coils", "КВ контуры"],
["USSR/RU radio practice", "Air KPE", 10, 365, "1x", "MW/LW tuning", "Настройка ДВ/СВ"],
["USSR/RU radio practice", "Air KPE", 12, 495, "1x", "Wide-band crystal sets", "Широкополосные детекторные приемники"],
["USSR/RU radio practice", "Air KPE", 15, 500, "1x", "General radio tuning", "Универсальная радионастройка"],
["USSR/RU radio practice", "Air KPE", 6, 270, "1x", "Compact MW receivers", "Компактные СВ приемники"],
["USSR/RU radio practice", "Air KPE", 10, 420, "1x", "Extended MW tuning", "Расширенная СВ настройка"],
["USSR/RU radio practice", "Dual-gang air KPE", 10, 365, "2x", "RF + LO", "ВЧ + гетеродин"],
["USSR/RU radio practice", "Dual-gang air KPE", 12, 495, "2x", "RF + antenna", "ВЧ + антенная секция"],
["USSR/RU radio practice", "Dual-gang air KPE", 8, 300, "2x", "AM receiver front-end", "Входной тракт AM"],
["USSR/RU radio practice", "Triple-gang air KPE", 10, 365, "3x", "Superhet RF stages", "Каскады супергетеродина"],
["USSR/RU radio practice", "Triple-gang air KPE", 8, 270, "3x", "Compact superhet", "Компактный супергетеродин"],
["IEC/JIS radio practice", "Polyvaricon", 10, 160, "2x", "Compact AM/FM front-ends", "Компактные AM/FM тракты"],
["IEC/JIS radio practice", "Polyvaricon", 12, 180, "2x", "Portable receivers", "Портативные приемники"],
["IEC/JIS radio practice", "Polyvaricon", 8, 140, "2x", "Pocket AM/FM radios", "Карманные AM/FM приемники"],
["IEC/JIS radio practice", "Polyvaricon", 15, 220, "2x", "Broader AM coverage", "Расширенный AM диапазон"],
["IEC/JIS radio practice", "Polyvaricon + trimmers", 5, 160, "2x + trim", "AM/FM alignment", "AM/FM подстройка"],
["IEC/JIS radio practice", "Polyvaricon + trimmers", 5, 210, "2x + trim", "Portable tuning blocks", "Портативные блоки настройки"],
["IEC trimmer practice", "Air/Ceramic trimmer", 3, 20, "1x", "Fine RF alignment", "Точная ВЧ подстройка"],
["IEC trimmer practice", "Air/Ceramic trimmer", 5, 60, "1x", "Alignment / fine tuning", "Подстройка и юстировка"],
["IEC trimmer practice", "Air/Ceramic trimmer", 10, 100, "1x", "Coarse tank adjustment", "Грубая подстройка контура"],
["IEC trimmer practice", "Ceramic trimmer", 2, 10, "1x", "Ultra-fine RF trimming", "Сверхточная ВЧ подстройка"],
["IEC trimmer practice", "Ceramic trimmer", 6, 40, "1x", "Receiver alignment", "Юстировка приемника"],
["HF transmitter practice", "Vacuum variable", 10, 500, "1x", "High voltage RF", "ВЧ при высоких напряжениях"],
["HF transmitter practice", "Vacuum variable", 20, 1000, "1x", "Antenna tuners", "Антенные тюнеры"],
["HF transmitter practice", "Vacuum variable", 15, 750, "1x", "Power RF stages", "Мощные ВЧ каскады"],
["HF transmitter practice", "Vacuum variable", 25, 1500, "1x", "High-power antenna match", "Согласование мощных антенн"]
];
return rows.map((r) => ({
system: r[0],
designation: r[1],
cMinPf: r[2],
cMaxPf: r[3],
gang: r[4],
useEn: r[5],
useRu: r[6],
apply: { type: "cap", cMinPf: r[2], cMaxPf: r[3] }
}));
}
function applyReferenceItem(item) {
if (!item || !item.apply) {
return;
}
if (item.apply.type === "wire") {
if (ui.holdWire && ui.holdWire.checked) {
showNoticeByKey("holdBlockedWire");
return;
}
const d = Math.max(0.01, item.apply.conductorDiameterMm);
ui.conductorDiameter.value = d.toFixed(3);
const insulation = Math.max(0, num(ui.insulationThickness, 0.025));
const wireD = Math.max(d + insulation * 2, d);
if (!isHeldField("wireDiameter")) {
ui.wireDiameter.value = wireD.toFixed(3);
}
if (item.apply.wireType && ui.wireType) {
ui.wireType.value = item.apply.wireType;
}
if (Number.isFinite(item.apply.strands) && ui.strands) {
ui.strands.value = Math.max(1, Math.round(item.apply.strands)).toFixed(0);
}
if (Number.isFinite(item.apply.strandDiameterMm) && ui.strandDiameter) {
ui.strandDiameter.value = Math.max(0.005, item.apply.strandDiameterMm).toFixed(3);
}
if (item.apply.materialKey && ui.material) {
ui.material.value = item.apply.materialKey;
}
closeReferenceModal();
calculate("conductorDiameter");
return;
}
if (item.apply.type === "cap") {
if (ui.holdCap && ui.holdCap.checked) {
showNoticeByKey("holdBlockedCap");
return;
}
const cMin = Math.max(1, item.apply.cMinPf);
const cMax = Math.max(cMin, item.apply.cMaxPf);
const cMid = Math.sqrt(cMin * cMax);
ui.capMin.value = cMin.toFixed(3);
ui.capMax.value = cMax.toFixed(3);
ui.cap.value = cMid.toFixed(3);
closeReferenceModal();
calculate("capMin");
}
}
function renderReferenceTable(headers, items) {
const table = document.createElement("table");
table.className = "ref-table";
const thead = document.createElement("thead");
const headRow = document.createElement("tr");
for (const header of headers) {
const th = document.createElement("th");
th.textContent = header;
headRow.appendChild(th);
}
thead.appendChild(headRow);
table.appendChild(thead);
const tbody = document.createElement("tbody");
for (const item of items) {
const row = item.cells;
const tr = document.createElement("tr");
tr.className = "ref-row";
tr.tabIndex = 0;
tr.setAttribute("role", "button");
tr.setAttribute("aria-label", row.join(" "));
tr.addEventListener("click", () => applyReferenceItem(item));
tr.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
applyReferenceItem(item);
}
});
for (const cell of row) {
const td = document.createElement("td");
td.textContent = cell;
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(tbody);
return table;
}
function renderSearchableReferenceTable(headers, items, placeholder, bodyContainer) {
const wrapper = document.createElement("div");
wrapper.className = "ref-search-wrap";
const searchable = items.length > 12;
let tableContainer = document.createElement("div");
wrapper.appendChild(tableContainer);
const draw = (list) => {
tableContainer.innerHTML = "";
tableContainer.appendChild(renderReferenceTable(headers, list));
};
if (searchable) {
const search = document.createElement("input");
search.className = "ref-search";
search.type = "search";
search.placeholder = placeholder;
wrapper.prepend(search);
search.addEventListener("input", () => {
const q = search.value.trim().toLowerCase();
if (!q) {
draw(items);
return;
}
const filtered = items.filter((item) => item.search.includes(q));
draw(filtered);
});
}
draw(items);
bodyContainer.appendChild(wrapper);
}
function openReferenceModal(type) {
if (!ui.refModal || !ui.refModalTitle || !ui.refModalBody) {
return;
}
const t = i18n[currentLanguage] || i18n.en;
ui.refModalBody.innerHTML = "";
const note = document.createElement("p");
note.className = "ref-note";
const hint = document.createElement("p");
hint.className = "ref-note";
hint.textContent = t.refApplyHint;
if (type === "wire") {
ui.refModalTitle.textContent = t.wireModalTitle;
note.textContent = t.wireModalNote;
ui.refModalBody.appendChild(note);
ui.refModalBody.appendChild(hint);
const items = buildWireReferenceItems().map((r) => ({
cells: [
r.system,
r.designation,
r.area.toFixed(4),
r.diameter.toFixed(3),
currentLanguage === "ru" ? r.useRu : r.useEn
],
search: `${r.system} ${r.designation} ${r.area.toFixed(4)} ${r.diameter.toFixed(3)} ${r.useEn} ${r.useRu}`.toLowerCase(),
apply: r.apply
}));
renderSearchableReferenceTable(
[t.tableSystem, t.tableDesignation, t.tableCross, t.tableDiameter, t.tableUse],
items,
t.refSearchPlaceholder,
ui.refModalBody
);
} else {
ui.refModalTitle.textContent = t.capModalTitle;
note.textContent = t.capModalNote;
ui.refModalBody.appendChild(note);
ui.refModalBody.appendChild(hint);
const items = buildCapReferenceItems().map((r) => ({
cells: [
r.system,
r.designation,
`${r.cMinPf}-${r.cMaxPf} pF`,
r.gang,
currentLanguage === "ru" ? r.useRu : r.useEn
],
search: `${r.system} ${r.designation} ${r.cMinPf} ${r.cMaxPf} ${r.gang} ${r.useEn} ${r.useRu}`.toLowerCase(),
apply: r.apply
}));
renderSearchableReferenceTable(
[t.tableSystem, t.tableDesignation, t.tableCapRange, t.tableGang, t.tableUse],
items,
t.refSearchPlaceholder,
ui.refModalBody
);
}
ui.refModal.classList.add("open");
ui.refModal.setAttribute("aria-hidden", "false");
}
function closeReferenceModal() {
if (!ui.refModal) {
return;
}
ui.refModal.classList.remove("open");
ui.refModal.setAttribute("aria-hidden", "true");
}
const scene3d = {
scene: null,
camera: null,
renderer: null,
controls: null,
root: null,
legendEl: null,
frameId: 0
};
function ensureViewerLegendElement() {
if (!ui.coilViewer) {
return null;
}
let legend = ui.coilViewer.querySelector(".viewer-legend");
if (!legend) {
legend = document.createElement("div");
legend.className = "viewer-legend";
ui.coilViewer.appendChild(legend);
}
return legend;
}
function formatLegendNumber(value, digits) {
if (!Number.isFinite(value)) {
return "-";
}
return Number(value).toFixed(digits);
}
function updateViewerLegend(params) {
if (!params) {
return;
}
const legend = scene3d.legendEl || ensureViewerLegendElement();
if (!legend) {
return;
}
scene3d.legendEl = legend;
const t = i18n[currentLanguage] || i18n.en;
const materialLabel = (t.materialNames && t.materialNames[params.materialKey]) || params.materialKey || "-";
const coreLabel = (t.coreNames && t.coreNames[params.coreType]) || params.coreType || "-";
legend.innerHTML = [
`<strong>${t.legendTitle}</strong>`,
`<span>${t.legendMaterial}: ${materialLabel}</span>`,
`<span>${t.legendCore}: ${coreLabel}</span>`,
`<span>${t.legendInductance}: ${formatLegendNumber(params.inductanceUh, 2)} uH</span>`,
`<span>${t.legendCap}: ${formatLegendNumber(params.capPf, 1)} pF (${formatLegendNumber(params.capMinPf, 1)}...${formatLegendNumber(params.capMaxPf, 1)} pF)</span>`,
`<span>${t.legendFreq}: ${formatLegendNumber(params.freqKHz, 1)} kHz</span>`
].join("");
}
function buildCoilCurve(params) {
const {
turns,
layers,
baseRadius,
pitch,
layerStep,
coilLength,
phase
} = params;
const turnsPerLayer = turns / layers;
const maxT = 2 * Math.PI * turns;
const points = [];
const totalSteps = Math.max(150, Math.round(turns * 36));
for (let i = 0; i <= totalSteps; i += 1) {
const t = (i / totalSteps) * maxT;
const angle = t + phase;
const turnsDone = t / (2 * Math.PI);
const layerIndex = Math.min(layers - 1, Math.floor(turnsDone / turnsPerLayer));
const localTurn = turnsDone - layerIndex * turnsPerLayer;
const radius = baseRadius + layerIndex * layerStep;
const x = -coilLength / 2 + localTurn * pitch;
points.push(new THREE.Vector3(
x,
Math.cos(angle) * radius,
Math.sin(angle) * radius
));
}
return new THREE.CatmullRomCurve3(points, false, "catmullrom", 0.05);
}
function init3D() {
if (!ui.coilViewer) {
return;
}