-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathimport.js
1378 lines (1125 loc) · 47.1 KB
/
import.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
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
import JSZip from 'jszip';
import xml2js from 'xml2js';
import importJson from '../../lib/import-json.js';
import CoarseChannel from '../../lib/model/CoarseChannel.js';
import { scaleDmxRangeIndividually, scaleDmxValue } from '../../lib/scale-dmx-values.js';
import gdtfAttributes, { gdtfUnits } from './gdtf-attributes.js';
import { followXmlNodeReference, getRgbColorFromGdtfColor } from './gdtf-helpers.js';
export const version = `0.2.0`;
/**
* @typedef {object} Relation
* @property {number} modeIndex The zero-based index of the mode this relation applies to.
* @property {object} masterGdtfChannel The GDTF channel that triggers switching.
* @property {string} switchingChannelName The name of the switching channel (containing multiple default channels).
* @property {object} followerGdtfChannel The GDTF channel that is switched by the master.
* @property {[number, Resolution]} dmxFrom The DMX value and DMX resolution of the start of the DMX range triggering this relation.
* @property {[number, Resolution]} dmxTo The DMX value and DMX resolution of the end of the DMX range triggering this relation.
*/
/**
* @param {Buffer} buffer The imported file.
* @param {string} filename The imported file's name.
* @param {string} authorName The importer's name.
* @returns {Promise<object, Error>} A Promise resolving to an out object
*/
export async function importFixtures(buffer, filename, authorName) {
const fixture = {
$schema: `https://raw.githubusercontent.com/OpenLightingProject/open-fixture-library/master/schemas/fixture.json`,
};
const warnings = [];
const xml = await getGdtfXml(buffer, filename);
const gdtfFixture = xml.GDTF.FixtureType[0];
fixture.name = gdtfFixture.$.Name;
fixture.shortName = gdtfFixture.$.ShortName;
const manufacturerKey = slugify(gdtfFixture.$.Manufacturer);
const fixtureKey = `${manufacturerKey}/${slugify(fixture.name)}`;
const manufacturers = await importJson(`../../fixtures/manufacturers.json`, import.meta.url);
let manufacturer;
if (manufacturerKey in manufacturers) {
manufacturer = manufacturers[manufacturerKey];
}
else {
manufacturer = {
name: gdtfFixture.$.Manufacturer,
};
warnings.push(`Please add manufacturer URL.`);
}
fixture.categories = [`Other`]; // TODO: can we find out categories?
warnings.push(`Please add fixture categories.`);
const timestamp = new Date().toISOString().replace(/T.*/, ``);
const [createDate, lastModifyDate] = getRevisionDates();
fixture.meta = {
authors: [authorName],
createDate: getIsoDateFromGdtfDate(createDate, timestamp),
lastModifyDate: getIsoDateFromGdtfDate(lastModifyDate, timestamp),
importPlugin: {
plugin: `gdtf`,
date: timestamp,
comment: `GDTF v${xml.GDTF.$.DataVersion} fixture type ID: ${gdtfFixture.$.FixtureTypeID}`,
},
};
fixture.comment = getFixtureComment();
warnings.push(`Please add relevant links to the fixture.`);
addRdmInfo();
warnings.push(`Please add physical data to the fixture.`);
fixture.matrix = {};
addWheels();
autoGenerateGdtfNameAttributes();
const switchingChannelRelations = splitSwitchingChannels();
addChannels();
addModes();
linkSwitchingChannels();
cleanUpFixture(fixture, warnings);
return {
manufacturers: {
[manufacturerKey]: manufacturer,
},
fixtures: {
[fixtureKey]: fixture,
},
warnings: {
[fixtureKey]: warnings,
},
};
/**
* @returns {[string | undefined, string | undefined]} An array with the earliest and latest revision dates of the GDTF fixture, if they are defined in <Revision> tag.
*/
function getRevisionDates() {
if (!gdtfFixture.Revisions?.[0]?.Revision) {
return [undefined, undefined];
}
const revisions = gdtfFixture.Revisions[0].Revision;
const earliestRevision = revisions[0];
const latestRevision = revisions.at(-1);
return [earliestRevision.$.Date, latestRevision.$.Date];
}
/**
* @returns {string | undefined} The comment to add to the fixture.
*/
function getFixtureComment() {
const { Name, LongName, Manufacturer, Description } = gdtfFixture.$;
const includeLongName = (LongName && LongName !== Name);
const includeDescription = (Description && Description !== `${Manufacturer} ${Name}`);
if (includeLongName && includeDescription) {
return `${LongName}: ${Description}`;
}
if (includeLongName) {
return LongName;
}
if (includeDescription) {
return Description;
}
return undefined;
}
/**
* Adds an RDM section to the OFL fixture and manufacturer if applicable.
*/
function addRdmInfo() {
if (!(`Protocols` in gdtfFixture) || gdtfFixture.Protocols[0] === `` || !(`FTRDM` in gdtfFixture.Protocols[0] || `RDM` in gdtfFixture.Protocols[0])) {
return;
}
const rdmData = (gdtfFixture.Protocols[0].FTRDM || gdtfFixture.Protocols[0].RDM)[0];
const softwareVersion = getLatestSoftwareVersion();
manufacturer.rdmId = Number.parseInt(rdmData.$.ManufacturerID, 16);
fixture.rdm = {
modelId: Number.parseInt(rdmData.$.DeviceModelID, 16),
softwareVersion: softwareVersion.name,
};
for (const personality of softwareVersion.personalities) {
const index = Number.parseInt(personality.$.Value.replace(`0x`, ``), 16);
const mode = followXmlNodeReference(gdtfFixture.DMXModes[0].DMXMode, personality.$.DMXMode);
mode._oflRdmPersonalityIndex = index;
}
/**
* @returns {object} Name and DMX personalities of the latest RDM software version (both may be undefined).
*/
function getLatestSoftwareVersion() {
let maxSoftwareVersion = undefined;
for (const rdmVersion of rdmData.SoftwareVersionID || []) {
if (!maxSoftwareVersion || rdmVersion.$.Value > maxSoftwareVersion.$.Value) {
maxSoftwareVersion = rdmVersion;
}
}
if (maxSoftwareVersion) {
return {
name: maxSoftwareVersion.$.Value,
personalities: maxSoftwareVersion.DMXPersonality,
};
}
return {
name: rdmData.$.SoftwareVersionID,
personalities: [],
};
}
}
/**
* Adds wheels to the OFL fixture (if there are any).
*/
function addWheels() {
if (!(`Wheels` in gdtfFixture)) {
return;
}
const gdtfWheels = (gdtfFixture.Wheels[0].Wheel || []).filter(
wheel => wheel.$.Name !== `ColorMacro`,
);
if (gdtfWheels.length === 0) {
return;
}
fixture.wheels = {};
for (const gdtfWheel of gdtfWheels) {
fixture.wheels[gdtfWheel.$.Name] = {
slots: (gdtfWheel.Slot || []).map(gdtfSlot => {
const name = gdtfSlot.$.Name;
const slot = {
type: `Unknown`,
};
if (name === `Open`) {
slot.type = `Open`;
}
else if (name === `Closed`) {
slot.type = `Closed`;
}
else if (`Color` in gdtfSlot.$) {
slot.type = `Color`;
slot.name = name;
slot.colors = [getRgbColorFromGdtfColor(gdtfSlot.$.Color)];
}
else if (`Facet` in gdtfSlot) {
slot.type = `Prism`;
slot.name = name;
slot.facets = gdtfSlot.Facet.length;
}
else if (name.startsWith(`Gobo`) || gdtfWheel.$.Name.startsWith(`Gobo`)) {
slot.type = `Gobo`;
slot.name = name;
}
else {
slot.name = name;
}
return slot;
}),
};
}
}
/**
* Autmatically generates `Name` attributes for GDTF's `<DMXChannel>`,
* `<LogicalChannel>` and `<ChannelFunction>` elements if they are not
* already defined.
*/
function autoGenerateGdtfNameAttributes() {
for (const gdtfMode of gdtfFixture.DMXModes[0].DMXMode) {
// add default Name attributes, so that the references work later
for (const gdtfChannel of gdtfMode.DMXChannels[0].DMXChannel) {
// auto-generate <DMXChannel> Name attribute
const geometry = gdtfChannel.$.Geometry.split(`.`).pop();
gdtfChannel.$.Name = `${geometry}_${gdtfChannel.LogicalChannel[0].$.Attribute}`;
for (const gdtfLogicalChannel of gdtfChannel.LogicalChannel) {
// auto-generate <LogicalChannel> Name attribute
gdtfLogicalChannel.$.Name = gdtfLogicalChannel.$.Attribute;
for (const [channelFunctionIndex, gdtfChannelFunction] of gdtfLogicalChannel.ChannelFunction.entries()) {
// auto-generate <ChannelFunction> Name attribute if not already defined
if (!(`Name` in gdtfChannelFunction.$)) {
gdtfChannelFunction.$.Name = `${gdtfChannelFunction.$.Attribute} ${channelFunctionIndex + 1}`;
}
}
}
}
}
}
/**
* @returns {Relation[]} An array of relations.
*/
function splitSwitchingChannels() {
let relations = getModeMasterRelations();
if (relations.length === 0) {
relations = getLegacyRelations();
}
for (const relation of relations) {
const followerChannel = relation.followerGdtfChannel;
// if channel was already split, skip splitting it again, else
// split channel such that followerChannelFunction is the only child
if (followerChannel.LogicalChannel[0].ChannelFunction.length > 1) {
const channelCopy = structuredClone(followerChannel);
channelCopy.$.Name += `_OflSplit`;
relation.followerGdtfChannel = channelCopy;
// remove followerChannelFunction from followerChannel and all others from the copy
const channelFunctionIndex = followerChannel.LogicalChannel[0].ChannelFunction.indexOf(relation.followerChannelFunction);
followerChannel.LogicalChannel[0].ChannelFunction.splice(channelFunctionIndex, 1);
channelCopy.LogicalChannel[0].ChannelFunction = [
channelCopy.LogicalChannel[0].ChannelFunction[channelFunctionIndex],
];
// insert channelCopy before the followerChannel
const gdtfMode = gdtfFixture.DMXModes[0].DMXMode[relation.modeIndex];
const channelIndex = gdtfMode.DMXChannels[0].DMXChannel.indexOf(followerChannel);
gdtfMode.DMXChannels[0].DMXChannel.splice(channelIndex, 0, channelCopy);
}
delete relation.followerChannelFunction;
}
return relations;
/**
* Parses <ChannelFunction ModeMaster="…">'s relation data.
* This way of specifying relations was added in GDTF v0.88.
* @returns {Relation[]} An array of relations, may be empty.
*/
function getModeMasterRelations() {
return gdtfFixture.DMXModes[0].DMXMode.flatMap((gdtfMode, modeIndex) => {
return gdtfMode.DMXChannels[0].DMXChannel.flatMap(gdtfDmxChannel => {
return gdtfDmxChannel.LogicalChannel.flatMap(gdtfLogicalChannel => {
return gdtfLogicalChannel.ChannelFunction.flatMap(gdtfChannelFunction => {
if (!(`ModeMaster` in gdtfChannelFunction.$)) {
return [];
}
const masterChannel = followXmlNodeReference(gdtfMode.DMXChannels[0], gdtfChannelFunction.$.ModeMaster.split(`.`)[0]);
const dmxFrom = getDmxValueWithResolutionFromGdtfDmxValue(gdtfChannelFunction.$.ModeFrom, 0);
const maxDmxValue = Math.pow(256, dmxFrom[1]) - 1;
const dmxTo = getDmxValueWithResolutionFromGdtfDmxValue(gdtfChannelFunction.$.ModeTo, maxDmxValue, dmxFrom[1]);
return [{
modeIndex,
masterGdtfChannel: masterChannel,
switchingChannelName: gdtfDmxChannel.$.Name,
followerGdtfChannel: gdtfDmxChannel,
followerChannelFunction: gdtfChannelFunction,
dmxFrom,
dmxTo,
}];
});
});
});
});
}
/**
* Parses <Relation Type="Mode">'s relation data.
* This behavior is deprecated since GDTF v0.88, but still supported as a fallback.
* @returns {Relation[]} An array of relations, may be empty.
*/
function getLegacyRelations() {
return gdtfFixture.DMXModes[0].DMXMode.flatMap((gdtfMode, modeIndex) => {
if (!(`Relations` in gdtfMode) || typeof gdtfMode.Relations[0] !== `object`) {
return [];
}
return gdtfMode.Relations[0].Relation.flatMap(gdtfRelation => {
if (gdtfRelation.$.Type !== `Mode`) {
return [];
}
const masterChannel = followXmlNodeReference(gdtfMode.DMXChannels[0], gdtfRelation.$.Master);
// Slave was renamed to Follower in GDTF v0.88
const followerChannelReference = gdtfRelation.$.Follower || gdtfRelation.$.Slave;
const followerChannel = followXmlNodeReference(gdtfMode.DMXChannels[0], followerChannelReference.split(`.`)[0]);
const followerChannelFunction = followXmlNodeReference(gdtfMode.DMXChannels[0], followerChannelReference);
const dmxFrom = getDmxValueWithResolutionFromGdtfDmxValue(gdtfRelation.$.DMXFrom, 0);
const maxDmxValue = Math.pow(256, dmxFrom[1]) - 1;
const dmxTo = getDmxValueWithResolutionFromGdtfDmxValue(gdtfRelation.$.DMXTo, maxDmxValue, dmxFrom[1]);
return [{
modeIndex,
masterGdtfChannel: masterChannel,
switchingChannelName: followerChannel.$.Name,
followerGdtfChannel: followerChannel,
followerChannelFunction,
dmxFrom,
dmxTo,
}];
});
});
}
}
/**
* @typedef {object} ChannelWrapper
* @property {string} key The channel key.
* @property {object} channel The OFL channel object.
* @property {number} maxResolution The highest used resolution of this channel.
* @property {number[]} modeIndices The indices of the modes that this channel is used in.
*/
/**
* Add availableChannels and templateChannels to the fixture.
*/
function addChannels() {
const availableChannels = [];
const templateChannels = [];
for (const gdtfMode of gdtfFixture.DMXModes[0].DMXMode) {
for (const gdtfChannel of gdtfMode.DMXChannels[0].DMXChannel) {
if (gdtfChannel.$.DMXBreak === `Overwrite`) {
addChannel(templateChannels, gdtfChannel);
}
else {
addChannel(availableChannels, gdtfChannel);
}
}
}
// append $pixelKey to templateChannels' keys and names
for (const channelWrapper of templateChannels) {
channelWrapper.key += ` $pixelKey`;
channelWrapper.channel.name += ` $pixelKey`;
}
cleanUpChannelWrappers([...availableChannels, ...templateChannels]);
// convert availableChannels array to object and add it to fixture
if (availableChannels.length > 0) {
fixture.availableChannels = Object.fromEntries(
availableChannels.map(channelWrapper => [channelWrapper.key, channelWrapper.channel]),
);
}
// convert templateChannels array to object and add it to fixture
if (templateChannels.length > 0) {
fixture.templateChannels = Object.fromEntries(
templateChannels.map(channelWrapper => [channelWrapper.key, channelWrapper.channel]),
);
}
}
/**
* @param {ChannelWrapper[]} channelWrappers The OFL availableChannels or templateChannels object.
* @param {object} gdtfChannel The GDTF <DMXChannel> XML object.
*/
function addChannel(channelWrappers, gdtfChannel) {
const name = getChannelName();
if (gdtfChannel.LogicalChannel.length > 1) {
warnings.push(`DMXChannel '${name}' has more than one LogicalChannel. This is not supported yet and could lead to undesired results.`);
}
const modeIndex = gdtfFixture.DMXModes[0].DMXMode.findIndex(
gdtfMode => gdtfMode.DMXChannels[0].DMXChannel.includes(gdtfChannel),
);
const channel = {
name,
fineChannelAliases: [],
dmxValueResolution: ``,
defaultValue: null,
};
if (`Default` in gdtfChannel.$) {
channel.defaultValue = getDmxValueWithResolutionFromGdtfDmxValue(gdtfChannel.$.Default);
}
if (`Highlight` in gdtfChannel.$ && gdtfChannel.$.Highlight !== `None`) {
channel.highlightValue = getDmxValueWithResolutionFromGdtfDmxValue(gdtfChannel.$.Highlight);
}
const capabilities = getCapabilities();
if (capabilities.length === 1) {
channel.capability = capabilities[0];
delete channel.capability.dmxRange;
}
else {
channel.capabilities = capabilities;
}
replaceGdtfDmxValuesWithNumbers();
// check if we already added the same channel in another mode
const sameChannel = channelWrappers.find(
channelWrapper => JSON.stringify(channelWrapper.channel) === JSON.stringify(channel) && !channelWrapper.modeIndices.includes(modeIndex),
);
if (sameChannel) {
gdtfChannel._oflChannelKey = sameChannel.key;
sameChannel.maxResolution = Math.max(sameChannel.maxResolution, getChannelResolution());
sameChannel.modeIndices.push(modeIndex);
return;
}
const channelKey = getChannelKey();
gdtfChannel._oflChannelKey = channelKey;
channelWrappers.push({
key: channelKey,
channel,
maxResolution: getChannelResolution(),
modeIndices: [modeIndex],
});
/**
* @returns {string} The channel name.
*/
function getChannelName() {
const channelAttribute = gdtfChannel.LogicalChannel[0].$.Attribute;
try {
return gdtfFixture.AttributeDefinitions[0].Attributes[0].Attribute.find(
attribute => attribute.$.Name === channelAttribute,
).$.Pretty || channelAttribute;
}
catch {
return channelAttribute;
}
}
/**
* @returns {object[]} Array of OFL capability objects (but with GDTF DMX values).
*/
function getCapabilities() {
let minPhysicalValue = Number.POSITIVE_INFINITY;
let maxPhysicalValue = Number.NEGATIVE_INFINITY;
// save all <ChannelSet> XML nodes in a flat list
const gdtfCapabilities = gdtfChannel.LogicalChannel.flatMap(gdtfLogicalChannel => {
if (!gdtfLogicalChannel.ChannelFunction) {
throw new Error(`LogicalChannel does not contain any ChannelFunction children in DMXChannel ${JSON.stringify(gdtfChannel, null, 2)}`);
}
return gdtfLogicalChannel.ChannelFunction.flatMap(gdtfChannelFunction => {
if (!gdtfChannelFunction.ChannelSet) {
// add an empty <ChannelSet />
gdtfChannelFunction.ChannelSet = [{ $: {} }];
}
// save GDTF attribute for later
gdtfChannelFunction._attribute = followXmlNodeReference(
gdtfFixture.AttributeDefinitions[0].Attributes[0],
gdtfChannelFunction.$.Attribute,
) || { $: { Name: `NoFeature` } };
return gdtfChannelFunction.ChannelSet.map(gdtfChannelSet => {
// save parent nodes for future use
gdtfChannelSet._logicalChannel = gdtfLogicalChannel;
gdtfChannelSet._channelFunction = gdtfChannelFunction;
gdtfChannelSet._fixture = gdtfFixture;
// do some preprocessing
if (!(`$` in gdtfChannelSet)) {
gdtfChannelSet.$ = {};
}
if (!(`Name` in gdtfChannelSet.$)) {
gdtfChannelSet.$.Name = ``;
}
gdtfChannelSet._dmxFrom = getDmxValueWithResolutionFromGdtfDmxValue(gdtfChannelSet.$.DMXFrom, 0);
const physicalFrom = parseFloatWithFallback(gdtfChannelSet.$.PhysicalFrom, 0);
const physicalTo = parseFloatWithFallback(gdtfChannelSet.$.PhysicalTo, 1);
gdtfChannelSet._physicalFrom = physicalFrom;
gdtfChannelSet._physicalTo = physicalTo;
minPhysicalValue = Math.min(minPhysicalValue, physicalFrom, physicalTo);
maxPhysicalValue = Math.max(maxPhysicalValue, physicalFrom, physicalTo);
return gdtfChannelSet;
});
});
});
return gdtfCapabilities.map((gdtfCapability, index) => {
const capability = {
dmxRange: [gdtfCapability._dmxFrom, getDmxRangeEnd(index)],
};
const gdtfAttribute = gdtfCapability._channelFunction._attribute;
const attributeName = gdtfAttribute.$.Name;
const capabilityTypeData = getCapabilityTypeData(attributeName);
capability.type = capabilityTypeData.oflType;
callHook(capabilityTypeData.beforePhysicalPropertyHook, capability, gdtfCapability, attributeName);
const oflProperty = getOflProperty(capabilityTypeData, gdtfCapability);
if (oflProperty !== null) {
const physicalUnit = getPhysicalUnit(gdtfCapability);
const physicalFrom = gdtfCapability._physicalFrom;
const physicalTo = gdtfCapability._physicalTo;
if (physicalFrom === physicalTo) {
capability[oflProperty] = physicalUnit(physicalFrom, null);
}
else {
capability[`${oflProperty}Start`] = physicalUnit(physicalFrom, physicalTo);
capability[`${oflProperty}End`] = physicalUnit(physicalTo, physicalFrom);
if (capability.brightnessStart === `0%` && capability.brightnessEnd === `100%`) {
delete capability.brightnessStart;
delete capability.brightnessEnd;
}
}
}
callHook(capabilityTypeData.afterPhysicalPropertyHook, capability, gdtfCapability, attributeName);
if (gdtfCapability.$.Name) {
capability.comment = gdtfCapability.$.Name;
}
return capability;
});
/**
* @param {number} index The index of the capability.
* @returns {[number, Resolution]} The GDTF DMX value for this capability's range end.
*/
function getDmxRangeEnd(index) {
const dmxFrom = gdtfCapabilities[index]._dmxFrom;
if (index === gdtfCapabilities.length - 1) {
// last capability
const resolution = dmxFrom[1];
return [Math.pow(256, resolution) - 1, resolution];
}
const [nextDmxFromValue, resolution] = gdtfCapabilities[index + 1]._dmxFrom;
return [nextDmxFromValue - 1, resolution];
}
/**
* @param {string} attributeName The GDTF attribute name.
* @returns {object} The capability type data from @file gdtf-attributes.js
*/
function getCapabilityTypeData(attributeName) {
let capabilityTypeData = gdtfAttributes[attributeName];
if (!capabilityTypeData) {
const enumeratedAttributeName = attributeName.replace(/\d+/, `(n)`).replace(/\d+/, `(m)`);
capabilityTypeData = gdtfAttributes[enumeratedAttributeName];
}
if (!capabilityTypeData) {
return {
oflType: `Unknown (${attributeName})`, // will trigger an error in the validation
oflProperty: `physical`, // will also trigger an error, but the information could be useful
};
}
if (!capabilityTypeData.inheritFrom) {
return capabilityTypeData;
}
// save the inherited result for later access
gdtfAttributes[attributeName] = {
...getCapabilityTypeData(capabilityTypeData.inheritFrom),
...capabilityTypeData,
};
delete gdtfAttributes[attributeName].inheritFrom;
return gdtfAttributes[attributeName];
}
/**
* @param {Function | null} hook The hook function, or a falsy value.
* @param {any[]} parameters The arguments to pass to the hook.
* @returns {any} The return value of the hook, or null if no hook was called.
*/
function callHook(hook, ...parameters) {
if (hook) {
return hook(...parameters);
}
return null;
}
/**
* @param {object} capabilityTypeData The capability type data from @file gdtf-attributes.js
* @param {object} gdtfCapability The enhanced <ChannelSet> XML object.
* @returns {string | null} The OFL property name, or null.
*/
function getOflProperty(capabilityTypeData, gdtfCapability) {
if (!(`oflProperty` in capabilityTypeData)) {
return null;
}
if (typeof capabilityTypeData.oflProperty === `function`) {
return capabilityTypeData.oflProperty(gdtfCapability);
}
return capabilityTypeData.oflProperty;
}
/**
* @param {object} gdtfCapability The enhanced <ChannelSet> XML object.
* @returns {Function} The function to turn a physical value into an entity string with the correct unit.
*/
function getPhysicalUnit(gdtfCapability) {
const gdtfAttribute = gdtfCapability._channelFunction._attribute;
const capabilityTypeData = getCapabilityTypeData(gdtfAttribute.$.Name);
if (capabilityTypeData.oflProperty === `index`) {
return gdtfUnits.None;
}
let physicalEntity = gdtfAttribute.$.PhysicalUnit;
if (!physicalEntity) {
physicalEntity = `None`;
if (minPhysicalValue === 0 && maxPhysicalValue === 1) {
physicalEntity = `Percent`;
}
else if (capabilityTypeData.defaultPhysicalEntity) {
physicalEntity = capabilityTypeData.defaultPhysicalEntity;
}
}
else if (!(physicalEntity in gdtfUnits)) {
// ignore case of PhysicalUnit attribute
physicalEntity = Object.keys(gdtfUnits).find(
entity => entity.toLowerCase() === physicalEntity.toLowerCase(),
);
}
return gdtfUnits[physicalEntity];
}
}
/**
* @returns {number} The resolution of this channel.
*/
function getChannelResolution() {
// The Offset attribute replaced the Coarse/Fine/Ultra/Uber attributes in GDTF v1.0
if (`Offset` in gdtfChannel.$) {
return gdtfChannel.$.Offset.split(`,`).length;
}
if (xmlNodeHasNotNoneAttribute(gdtfChannel, `Uber`)) {
return 4;
}
if (xmlNodeHasNotNoneAttribute(gdtfChannel, `Ultra`)) {
return 3;
}
if (xmlNodeHasNotNoneAttribute(gdtfChannel, `Fine`)) {
return 2;
}
return 1;
}
/**
* @returns {string} The channel key, derived from the name and made unique.
*/
function getChannelKey() {
let key = name;
// make unique by appending ' 2', ' 3', ... if necessary
let duplicates = 1;
const keyExists = () => channelWrappers.some(channelWrapper => channelWrapper.key === key);
while (keyExists()) {
duplicates++;
key = `${name} ${duplicates}`;
}
return key;
}
/**
* Look through all GDTF DMX values in this channel (consisting of DMX value
* and the resolution in which it is specified), make their resolution equal and
* replace them with a number. Then set the channel's dmxValueResolution to
* this resolution.
*/
function replaceGdtfDmxValuesWithNumbers() {
const maxDmxValueResolution = getMaxDmxValueResolution();
const scaleToResolution = Math.max(CoarseChannel.RESOLUTION_8BIT, maxDmxValueResolution);
if (channel.defaultValue) {
channel.defaultValue = scaleDmxValue(...channel.defaultValue, scaleToResolution);
}
if (channel.highlightValue) {
channel.highlightValue = scaleDmxValue(...channel.highlightValue, scaleToResolution);
}
if (channel.capabilities) {
for (const capability of channel.capabilities) {
const startValue = capability.dmxRange[0][0];
const startResolution = capability.dmxRange[0][1];
const endValue = capability.dmxRange[1][0];
const endResolution = capability.dmxRange[1][1];
try {
capability.dmxRange = scaleDmxRangeIndividually(startValue, startResolution, endValue, endResolution, scaleToResolution);
}
catch {
// will be caught by validation
capability.dmxRange = [startValue, endValue];
}
}
}
if (maxDmxValueResolution !== 0) {
channel.dmxValueResolution = `${maxDmxValueResolution * 8}bit`;
}
/**
* @returns {number} The highest DMX value resolution used in this channel, or 0 if no DMX value is used at all.
*/
function getMaxDmxValueResolution() {
const dmxValues = [];
if (channel.defaultValue && channel.defaultValue[0] !== 0) {
dmxValues.push(channel.defaultValue);
}
if (channel.highlightValue && channel.highlightValue[0] !== 0) {
dmxValues.push(channel.highlightValue);
}
if (channel.capabilities) {
for (const capability of channel.capabilities) {
dmxValues.push(capability.dmxRange[0], capability.dmxRange[1]);
}
}
return Math.max(0, ...dmxValues.map(
([value, resolution]) => resolution,
));
}
}
}
/**
* @typedef {object} DmxBreakWrapper Holds a list of OFL channel keys belonging to consecutive GDTF channels with the same DMXBreak attribute.
* @property {string | undefined} dmxBreak The DMXBreak attribute of consecutive DMXChannel nodes.
* @property {string} geometry The Geometry attribute of consecutive DMXChannel nodes.
* @property {string[]} channels The OFL channel keys in this DMX break.
*/
/**
* Add modes and matrix pixel keys (if needed) to the fixture.
*/
function addModes() {
// save all matrix pixels that are used in some mode
const matrixPixels = new Set();
fixture.modes = gdtfFixture.DMXModes[0].DMXMode.map(gdtfMode => {
/** @type {DmxBreakWrapper[]} */
const dmxBreakWrappers = [];
for (const gdtfChannel of gdtfMode.DMXChannels[0].DMXChannel) {
if (dmxBreakWrappers.length === 0 || dmxBreakWrappers.at(-1).dmxBreak !== gdtfChannel.$.DMXBreak) {
dmxBreakWrappers.push({
dmxBreak: gdtfChannel.$.DMXBreak,
geometry: gdtfChannel.$.Geometry,
channels: [],
});
}
addChannelKeyToDmxBreakWrapper(gdtfChannel, dmxBreakWrappers);
}
const channels = [];
for (const channelWrapper of dmxBreakWrappers) {
if (channelWrapper.dmxBreak !== `Overwrite`) {
// just append the channels
channels.push(...channelWrapper.channels);
continue;
}
// append a matrix channel insert block
const geometryReferences = findGeometryReferences(channelWrapper.geometry);
const usedMatrixPixels = geometryReferences.map(
(gdtfGeoRef, index) => gdtfGeoRef.$.Name || `${channelWrapper.geometry} ${index + 1}`,
);
for (const pixelKey of usedMatrixPixels) {
matrixPixels.add(pixelKey);
}
channels.push({
insert: `matrixChannels`,
repeatFor: usedMatrixPixels,
channelOrder: `perPixel`,
templateChannels: channelWrapper.channels.map(
channelKey => `${channelKey} $pixelKey`,
),
});
}
return {
name: gdtfMode.$.Name,
rdmPersonalityIndex: gdtfMode._oflRdmPersonalityIndex,
channels,
};
});
const matrixPixelList = [...matrixPixels];
fixture.matrix = {
pixelKeys: [
[
matrixPixelList,
],
],
};
// try to simplify matrix channel insert blocks
for (const mode of fixture.modes) {
for (const channel of mode.channels) {
if (typeof channel === `object` && channel.insert === `matrixChannels`
&& JSON.stringify(matrixPixelList) === JSON.stringify(channel.repeatFor)) {
channel.repeatFor = `eachPixelXYZ`;
}
}
}
/**
* Adds the OFL channel key (and fine channel keys) to dmxBreakWrappers'
* last entry's channels array.
* @param {object} gdtfChannel The GDTF channel object.
* @param {DmxBreakWrapper[]} dmxBreakWrappers The DMXBreak wrapper array.
*/
function addChannelKeyToDmxBreakWrapper(gdtfChannel, dmxBreakWrappers) {
const channelKey = gdtfChannel._oflChannelKey;
const oflChannel = fixture.availableChannels[channelKey];
const channels = dmxBreakWrappers.at(-1).channels;
const channelKeys = [channelKey, ...(oflChannel.fineChannelAliases ?? [])];
// The Offset attribute replaced the Coarse/Fine/Ultra/Uber attributes in GDTF v1.0
const channelOffsets = xmlNodeHasNotNoneAttribute(gdtfChannel, `Offset`)
? gdtfChannel.$.Offset.split(`,`)
: [
gdtfChannel.$.Coarse,
gdtfChannel.$.Fine,
gdtfChannel.$.Ultra,
gdtfChannel.$.Uber,
];
for (const [index, channelOffset] of channelOffsets.entries()) {
const dmxChannelNumber = Number.parseInt(channelOffset, 10);
if (!Number.isNaN(dmxChannelNumber)) {
channels[dmxChannelNumber - 1] = channelKeys[index];
}
}
}
/**
* Find all <GeometryReference> XML nodes with a given Geometry attribute.
* @param {string} geometryName The name of the geometry reference.
* @returns {object[]} An array of all geometry reference XML objects.
*/
function findGeometryReferences(geometryName) {
const geometryReferences = [];
traverseGeometries(gdtfFixture.Geometries[0]);
return geometryReferences;
/**
* Recursively go through the child nodes of a given XML node and add
* <GeometryReference> nodes with the correct Geometry attribute to the
* geometryReferences array.
* @param {object} xmlNode The XML node object to start traversing at.
*/
function traverseGeometries(xmlNode) {
// add all suitable GeometryReference child nodes
geometryReferences.push(
...(xmlNode.GeometryReference || []).filter(gdtfGeoRef => gdtfGeoRef.$.Geometry === geometryName),
);