-
Notifications
You must be signed in to change notification settings - Fork 22
/
samsa-core.js
3118 lines (2576 loc) · 101 KB
/
samsa-core.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
/*
samsa-core.js
Pre-GitHub version history
2019-10-18 glyf parsing in node & browser
2019-10-18 TVTs parsing in node & browser
2019-10-18 Tons of refactoring working nicely (tvts is much clearer structure than old gvd)
2019-10-19 avar seems to be working now
2019-10-20 Finally got gvar decompiling for all fonts I throw at it. Just need to do the fake glyph.points for composites and we’re done.
Minification:
- https://www.npmjs.com/package/uglify-es // this version of uglify is ES6 compatible, earlier versions were not
- uglifyjs samsa-core.js > samsa-core.min.js
*/
// TODO:
// - rename it SamsaCONFIG
// - pass the actual config object along with the font
let CONFIG = {
isNode: (typeof module !== 'undefined' && module.exports),
outFileDefault: "samsa-out.ttf",
instantiation: {
skipTables: ["gvar","fvar","cvar","avar","STAT","MVAR","HVAR","VVAR","DSIG"],
ignoreIUP: false,
},
defaultGlyph: [
"A", "a", "Alpha", "alpha", "afii10017", "A-cy", "afii10065", "a-cy", "zero", // PostScript names: Latin, Russian, Cyrillic (or should we use the cmap? because some fonts lack ps names)
],
sfnt: {
maxNumTables: 100,
maxSize: 10000000, // does not apply in node mode (i.e. we can create fonts of unlimited size on the command line)
},
glyf: {
overlapSimple: true,
bufferSize: 500000, // max data to accumulate before a write (ignored for in-memory instantiation)
compression: true, // toggles glyf data compression for output; default to true to minimize TTF file size; if false we generate instances faster; Bahnschrift-ship.ttf (2-axis) produces instances of ~109kb compressed, ~140kb uncompressed (note that woff2 compression generates identical woff2 files from compressed/uncompressed glyf data)
},
name: {
maxSize: 50000,
},
deltas: {
round: true,
},
postscriptNames: [".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"],
};
if (CONFIG.isNode) {
// mappings from DataView methods to Buffer methods
Buffer.prototype.getUint32 = Buffer.prototype.readUInt32BE;
Buffer.prototype.getInt32 = Buffer.prototype.readInt32BE;
Buffer.prototype.getUint16 = Buffer.prototype.readUInt16BE;
Buffer.prototype.getInt16 = Buffer.prototype.readInt16BE;
Buffer.prototype.getUint8 = Buffer.prototype.readUInt8;
Buffer.prototype.getInt8 = Buffer.prototype.readInt8;
Buffer.prototype.setUint32 = function (p,v) {this.writeUInt32BE(v,p);}
Buffer.prototype.setInt32 = function (p,v) {this.writeInt32BE(v,p);}
Buffer.prototype.setUint16 = function (p,v) {this.writeUInt16BE(v,p);}
Buffer.prototype.setInt16 = function (p,v) {this.writeInt16BE(v,p);}
Buffer.prototype.setUint8 = function (p,v) {this.writeUInt8(v,p);}
Buffer.prototype.setInt8 = function (p,v) {this.writeInt8(v,p);}
// add new Buffer methods
Buffer.prototype.getTag = function (p) {
var tag = "";
var p_end = p + 4; // global
var ch;
while (p < p_end) {
ch = this.readUInt8(p++);
if (ch >= 32 && ch < 126) // valid chars in tag data type https://www.microsoft.com/typography/otspec/otff.htm
tag += String.fromCharCode(ch);
}
return tag.length == 4 ? tag : false;
}
Buffer.prototype.getF2DOT14 = function (p) {
return this.getInt16(p) / 16384.0; /* signed */
}
}
function getStringFromData (data, p0, length)
{
// TODO: add a Pascal and C modes to use in parsing "post" table (use length = undefined for C, -1 for Pascal)
var str = "";
var p = p0;
while (p - p0 < length) {
str += String.fromCharCode(data.getUint8(p++));
}
return str;
}
// TODO: get rid of this!
function uint8ToBase64(buffer) {
var binary = '';
var len = buffer.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(buffer[i]);
}
return window.btoa( binary );
}
//////////////////////////////////
// fvsToCSS()
//////////////////////////////////
function fvsToCSS(fvs) {
// transforms an fvs object into a string suitable for font-variation-settings
// - simple transormation, it doesn’t perform any checks to see if the axes are in a font or if settings are beyond axis ranges
// - examples:
// {"wght": 655, "wdth": 77, "FOOB": 12345} => '"wght" 655,"wdth" 77,"FOOB" 12345'
// {} => 'normal'
let fvsCSS = [];
Object.keys(fvs).forEach(tag => {
fvsCSS.push(`"${tag}" ${fvs[tag]}`);
});
return fvsCSS.length ? fvsCSS.join() : "normal";
}
DataView.prototype.getTag = function (p) {
let ch, tag = "";
const p_end = p + 4;
while (p < p_end) {
ch = this.getUint8(p++);
if (ch >= 32 && ch < 126) // valid chars in tag data type https://www.microsoft.com/typography/otspec/otff.htm
tag += String.fromCharCode(ch);
}
return tag.length == 4 ? tag : false;
}
DataView.prototype.getF2DOT14 = function (p) {
return this.getInt16(p) / 16384.0; // signed
}
function copyBytes(source, target, zs, zt, n) {
// copies n bytes from source (starting at zs) to target (starting at zt)
// - source and target are typically DataView, but they can be any TypedArray
const src = new Uint8Array(source.buffer, source.byteOffset + zs, n);
const tgt = new Uint8Array(target.buffer, target.byteOffset + zt, n);
for (let i=0; i < n; i++)
tgt[i] = src[i]; // this seems to be the quickest way to copy between two ArrayBuffers, see benchmark at https://www.measurethat.net/Benchmarks/Show/7537/0/copy-arraybuffer-dataview-vs-uint8arrayset-vs-float64ar
}
// TODO make SamsaVFInstance a proper object
function SamsaVFInstance (init) {
}
function SamsaGlyph (init) {
this.id = init.id;
this.name = init.name;
this.font = init.font;
this.numPoints = 0;
this.numContours = 0; // -1 is the flag for composite
this.instructionLength = 0;
this.points = [];
this.components = [];
this.endPts = [];
this.tvts = [];
this.curveOrder = init.curveOrder || 2;
}
// SamsaGlyph methods are methods of SamsaGlyph.prototype, so that we don’t create a copy when we make each SamsaGlyph
// decompose()
// - decompose a composite glyph into a new simple glyph
SamsaGlyph.prototype.decompose = function (tuple, params) {
let simpleGlyph = new SamsaGlyph( {
id: this.id,
name: this.name,
font: this.font,
decompositionForGlyph: this,
} );
let iglyph = (tuple) ? this.instantiate(tuple) : this;
let offset, transform, flags;
if (params) {
offset = params.offset;
transform = params.transform;
flags = params.flags;
}
// simple case
if (this.numContours >= 0) {
if (!params && !tuple) // optimization for case when there’s no offset and no transform (we can make this return "this" itself: the decomposition of a simple glyph is itself)
return this;
// add the points
for (let pt=0; pt<iglyph.numPoints; pt++) {
// spec: https://docs.microsoft.com/en-us/typography/opentype/spec/glyf
let point = [ iglyph.points[pt][0], iglyph.points[pt][1], iglyph.points[pt][2] ];
// offset before transform
if (offset && (flags & 0x0800)) { // SCALED_COMPONENT_OFFSET
point[0] += offset[0];
point[1] += offset[1];
}
// transform matrix?
if (transform) {
let x = point[0], y = point[1];
point[0] = x * transform[0] + y * transform[1];
point[1] = x * transform[2] + y * transform[3];
}
// offset after transform
if (offset && !(flags & 0x0800)) { // SCALED_COMPONENT_OFFSET
point[0] += offset[0];
point[1] += offset[1];
}
simpleGlyph.points.push(point);
}
// fix up simpleGlyph
// TODO: can these point to the original objects?
for (endPt of this.endPts) {
simpleGlyph.endPts.push(endPt + simpleGlyph.numPoints);
}
simpleGlyph.numPoints += iglyph.numPoints;
simpleGlyph.numContours += iglyph.numContours;
}
else {
// step thru components, adding points to simpleGlyph
iglyph.components.forEach((component, c) => {
let gc = this.font.glyphs[component.glyphId];
let gci = gc.instantiate(tuple);
let newTransform = component.transform;
let newOffset = [ iglyph.points[c][0], iglyph.points[c][1] ];
if (offset) {
newOffset[0] += offset[0];
newOffset[1] += offset[1];
}
// decompse!
// - this is the recursive step
let decomp = gc.decompose(tuple, {
offset: newOffset,
transform: newTransform,
flags: component.flags,
});
// we now have the simple glyph "decomp": no offset or transform is needed
for (let p=0; p<decomp.numPoints; p++) {
simpleGlyph.points.push( [ decomp.points[p][0], decomp.points[p][1], decomp.points[p][2] ] );
}
// fix up simpleGlyph
for (endPt of decomp.endPts) {
simpleGlyph.endPts.push(endPt + simpleGlyph.numPoints);
}
simpleGlyph.numPoints += decomp.numPoints;
simpleGlyph.numContours += decomp.numContours;
});
}
// add the 4 phantom points
simpleGlyph.points.push([0,0,0], [iglyph.points[iglyph.points.length-3][0],0,0], [0,0,0], [0,0,0]);
// return the simple glyph
return simpleGlyph;
}
// instantiate()
// - take a default glyph and return the instantiation produced using the userTuple or instance settings
SamsaGlyph.prototype.instantiate = function (userTuple, instance, extra) {
// create newGlyph, a new glyph object which is the supplied glyph with the variations applied, as specified in instance (or if blank, userTuple)
// - TODO: can we move away from using userTuple and always require an instance?
// generate the glyph (e.g. if it’s needed by a composite)
if (this === undefined) {
console.log ("Samsaglyph.instantiate(): glyph is undefined");
}
//console.log("Instantiating using this.instantiate()");
const config = this.font.config;
const font = this.font;
let newGlyph = new SamsaGlyph({id:this.id, name:this.name, font:this.font});
newGlyph.default = this;
newGlyph.instance = instance; // this is still safe for tests that check for (!glyph.instance)
newGlyph.type = "instance";
newGlyph.points = [];
newGlyph.touched = [];
newGlyph.numContours = this.numContours;
newGlyph.components = this.components;
newGlyph.endPts = this.endPts;
newGlyph.numPoints = this.numPoints;
newGlyph.xMin = this.xMin;
newGlyph.yMin = this.yMin;
newGlyph.xMax = this.xMax;
newGlyph.yMax = this.yMax;
newGlyph.flags = this.flags; // do we need this?
let round = CONFIG.deltas.round;
if (extra && extra.roundDeltas === false)
round = false;
if (config.visualization)
newGlyph.tvtsVisualization = [];
// get a good userTuple (TODO: more validations than the array check)
// - it is recommended to use the ‘instance’ parameter, since then we preserve a connection between newGlyph and its instance
if (userTuple === null && instance)
userTuple = instance.tuple;
if (!Array.isArray(userTuple)) {
userTuple = font.fvsToTuple(userTuple); // userTuple was an fvs type object, but we transform it into a tuple array
}
// newGlyph starts off as a duplicate of the default glyph (at least, all of its points)
this.points.forEach((point, p) => {
newGlyph.points[p] = [point[0], point[1], point[2]];
});
// go through each tuple variation table for this glyph
newGlyph.sValues = [];
this.tvts.forEach((tvt, t) => {
let scaledDeltas = [];
let touched = [];
let S = 1;
this.points.forEach((point, p) => {
scaledDeltas[p] = [0,0];
});
// go thru each axis, multiply a scalar S from individual scalars AS
// based on pseudocode from https://www.microsoft.com/typography/otspec/otvaroverview.htm
font.axes.forEach((axis, a) => {
const ua = userTuple[a], peak = tvt.peak[a], start = tvt.start[a], end = tvt.end[a];
let AS;
if (start > peak || peak > end)
AS = 1;
else if (start < 0 && end > 0 && peak != 0)
AS = 1;
else if (peak == 0)
AS = 1;
else if (ua < start || ua > end)
AS = 0;
else {
if (ua == peak)
AS = 1;
else if (ua < peak)
AS = (ua - start) / (peak - start);
else
AS = (end - ua) / (end - peak);
}
S *= AS;
// TODO: optimize so that we quit the loop if AS == 0
// TODO: get rid of AS and use "S *= " in each of the branches (altho not ideal if we want to record each AS for visualization)
});
// now we can move the points by S * delta
if (S != 0) {
tvt.deltas.forEach((delta, pt) => {
if (delta !== null) {
newGlyph.touched[pt] = touched[pt] = true; // touched[] is just for this tvt; newGlyph.touched[] is for all tvts (in case we want to show in UI)
// btw, we don’t need to store touched array for composite or non-printing glyphs - probably a negligible optimization
scaledDeltas[pt] = [S * delta[0], S * delta[1]];
}
});
// IUP
// - TODO: ignore this step for composites (even though it is safe because numContours<0)
if (touched.length > 0 && !config.instantiation.ignoreIUP) { // it would be nice to check "touched.length < glyph.points.length" but that won’t work with sparse arrays, and must also think about phantom points
// for each contour
for (let c=0, startPt=0; c<this.numContours; c++) {
// OPTIMIZE: check here that the contour is actually touched
const numPointsInContour = this.endPts[c]-startPt+1;
let firstPrecPt = -1; // null value
let precPt, follPt;
for (let p=startPt; p!=firstPrecPt; ) {
let pNext = (p-startPt+1)%numPointsInContour+startPt;
if (touched[p] && !touched[pNext]) { // found a precPt
precPt = p;
follPt = pNext;
if (firstPrecPt == -1)
firstPrecPt = precPt;
do {
follPt = (follPt-startPt+1)%numPointsInContour+startPt;
} while (!touched[follPt]) // found the follPt
// now we have a good precPt and follPt
// perform IUP for x(0), then for y(1)
[0,1].forEach(xy => {
// IUP spec: https://www.microsoft.com/typography/otspec/gvar.htm#IDUP
const pA = this.points[precPt][xy];
const pB = this.points[follPt][xy];
const dA = scaledDeltas[precPt][xy];
const dB = scaledDeltas[follPt][xy];
for (let q=pNext, D, T, Q; q!=follPt; q=(q-startPt+1)%numPointsInContour+startPt) {
Q = this.points[q][xy];
if (pA == pB)
D = dA == dB ? dA : 0;
else {
if (Q <= pA && Q <= pB)
D = pA < pB ? dA : dB;
else if (Q >= pA && Q >= pB)
D = pA > pB ? dA : dB;
else {
T = (Q - pA) / (pB - pA); // safe for divide-by-zero
D = (1-T) * dA + T * dB;
}
}
scaledDeltas[q][xy] += D;
}
});
p = follPt;
}
else if (pNext == startPt && firstPrecPt == -1) // failed to find a precPt, so abandon this contour
break;
else
p = pNext;
}
startPt = this.endPts[c]+1;
}
} // if IUP
// add the net deltas to the glyph
// TODO: Try to avoid this step for points that were not moved
// TODO: Verify that we are rounding correctly. The spec implies we should maybe NOT round here, only at the end
// - https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview
let p;
const len = newGlyph.points.length; // includes phantoms
if (round) {
for (p=0; p<len; p++) {
newGlyph.points[p][0] += Math.round(scaledDeltas[p][0]);
newGlyph.points[p][1] += Math.round(scaledDeltas[p][1]);
}
}
else {
for (p=0; p<len; p++) {
newGlyph.points[p][0] += scaledDeltas[p][0];
newGlyph.points[p][1] += scaledDeltas[p][1];
}
}
} // if (S != 0)
// store S and scaledDeltas so we can use them in visualization
// - maybe we should recalculate multiple AS values and 1 S value in the GUI so we don’t add load to samsa-core
if (config.visualization) {
newGlyph.tvtsVisualization.push({
S: S,
scaledDeltas: scaledDeltas,
});
}
}); // end of processing the tvts
// new bbox extremes
// - TODO: fix for composites and non-printing glyphs (even though the latter don’t record a bbox)
/*
if (this.tvts.length) {
newGlyph.xMin = newGlyph.yMin = 32767;
newGlyph.xMax = newGlyph.yMax = -32768;
for (let pt=0; pt<newGlyph.numPoints; pt++) { // exclude the phantom points
let point = newGlyph.points[pt];
if (newGlyph.xMin > point[0])
newGlyph.xMin = point[0];
else if (newGlyph.xMax < point[0])
newGlyph.xMax = point[0];
if (newGlyph.yMin > point[1])
newGlyph.yMin = point[1];
else if (newGlyph.yMax < point[1])
newGlyph.yMax = point[1];
}
}*/
newGlyph.recalculateBounds();
return newGlyph;
}
// recalculateBounds()
// - recalculate the bounding box for this simple glyph
SamsaGlyph.prototype.recalculateBounds = function () {
if (this.numContours < 0) {
return false;
}
else if (this.numContours == 0) {
this.xMin = 0;
this.yMin = 0;
this.xMax = 0;
this.yMax = 0;
}
else {
let xMin = 32767, yMin = 32767, xMax = -32768, yMax = -32768;
for (let pt=0; pt<this.numPoints; pt++) { // exclude the phantom points
let point = this.points[pt];
if (xMin > point[0])
xMin = point[0];
else if (xMax < point[0])
xMax = point[0];
if (yMin > point[1])
yMin = point[1];
else if (yMax < point[1])
yMax = point[1];
}
this.xMin = xMin;
this.yMin = yMin;
this.xMax = xMax;
this.yMax = yMax;
}
return this.numPoints;
}
// featureVariationsGlyphId(tuple)
// - return a new glyphId for this glyph at the designspace location <tuple> according to FeatureVariations data
// - main function is in SamsaFont, so that, given a glyphId, we don’t need to create a SamsaGlyph in order to find FeatureVariations
SamsaGlyph.prototype.featureVariationsGlyphId = function (tuple) {
return this.font.featureVariationsGlyphId(this.id, tuple);
}
// svgPath()
// - export glyph as a string to be used in a SVG <path> "d" attribute
SamsaGlyph.prototype.svgPath = function () {
let contours = [];
let contour, pt, pt_, c, p;
// convert the glyph contours into an SVG-compatible contours array
let startPt = 0;
for (endPt of this.endPts) {
const numPoints = endPt-startPt+1; // number of points in this contour
contour = [];
// insert on-curve points between any two consecutive off-curve points
for (p=startPt; p<=endPt; p++) {
pt = this.points[p];
pt_ = this.points[(p-startPt+1)%numPoints+startPt];
contour.push (pt);
if (pt[2] == 0 && pt_[2] == 0) // if we have 2 consecutive off-curve points...
contour.push ( [ (pt[0]+pt_[0])/2, (pt[1]+pt_[1])/2, 1 ] ); // ...we insert the implied on-curve point
}
// ensure SVG contour starts with an on-curve point
if (contour[0][2] == 0) // is first point off-curve?
contour.unshift(contour.pop()); // OPTIMIZE: unshift is slow, so maybe build two arrays, "actual" and "toAppend", where "actual" starts with an on-curve
// append this contour
contours.push(contour);
startPt = endPt+1;
}
// convert contours array to an actual SVG path
// - we’ve already fixed things so there are never consecutive off-curve points
let path = "";
for (contour of contours) {
for (p=0; p<contour.length; p++) {
pt = contour[p];
if (p==0)
path += `M${pt[0]} ${pt[1]}`;
else {
if (pt[2] == 0) { // off-curve point (consumes 2 points)
pt_ = contour[(++p) % contour.length]; // increments loop variable p
path += `Q${pt[0]} ${pt[1]} ${pt_[0]} ${pt_[1]}`;
}
else // on-curve point
path += `L${pt[0]} ${pt[1]}`;
if (p == contour.length-1)
path += "Z";
}
}
}
return path;
};
// svg()
// - export glyph as a string, suitable for saving as a complete SVG file
SamsaGlyph.prototype.svg = function () {
let svg =
`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1000" height="1000" style="background-color: transparent;">
<g transform="translate(130,500) scale(0.5,-0.5)">
<path d="$_PATH_$" stroke="none" stroke-width="0" fill="#555"></path>
</g>
</svg>`;
svg = svg.replace("$_PATH_$", this.svgPath());
return svg;
}
// ttx()
// - export glyph as a string to be used as a complete XML <TTGlyph> within a TTX file
SamsaGlyph.prototype.ttx = function () {
let ttx = `<TTGlyph name="${this.name}" xMin="${this.xMin}" yMin="${this.yMin}" xMax="${this.xMax}" yMax="${this.yMax}">\n`;
let startPt = 0;
for (let endPt of this.endPts) {
ttx += ` <contour>\n`;
for (let pt=startPt; pt <= endPt; pt++) {
let point = this.points[pt];
ttx += ` <pt x="${point[0]}" y="${point[1]}" on="${point[2]}"/>\n`;
}
ttx += ` </contour>\n`;
startPt = endPt + 1;
}
ttx += `</TTGlyph>\n`;
return ttx;
};
// json()
// - export glyph as a JSON string but without the circular references of the internal object
SamsaGlyph.prototype.json = function () {
const replacer = ["id", "name", "curveOrder", "endPts", "numContours", "numComponents", "numPoints", "points", "components"];
return JSON.stringify(this, replacer, 4);
};
// ufo()
// - export glyph as a string to be used as a complete XML <glyph> structure as a standalone .glif file
SamsaGlyph.prototype.ufo = function () {
// - working for quadratic
// - assumes that UFO is cool with any number of off-curve points between on-curves, which is not clear from the spec
// - https://unifiedfontobject.org/versions/ufo3/glyphs/glif/
// - TODO: composites???
let glif = `<?xml version="1.0" encoding="UTF-8"?>\n`;
glif += `<glyph name="${this.name}" format="2">\n`;
glif += ` <advance width="${this.points[this.numPoints+1][0]}"/>\n`;
glif += ` <outline>\n`;
let startPt = 0;
for (let endPt of this.endPts) {
glif += ` <contour>\n`;
for (let pt=startPt; pt <= endPt; pt++) {
let point = this.points[pt];
let numContourPoints = endPt - startPt + 1;
let ptInContour = pt - startPt;
let prevPoint = this.points[startPt + (ptInContour-1+numContourPoints) % numContourPoints];
let typeString = "";
if (point[2] == 1) { // if point is on-curve
typeString = ` type="${ prevPoint[2] == 1 ? "line" : "qcurve" }"`; // decide if the current point is line or qcurve
}
glif += ` <point x="${point[0]}" y="${point[1]}"${typeString}/>\n`;
}
glif += ` </contour>\n`;
startPt = endPt + 1;
}
glif += ` </outline>\n`;
glif += `</glyph>\n`;
return glif;
};
function SamsaFont (init, config) {
// initialize config, and update it with updates passed to constructor
this.config = CONFIG;
if (config) {
Object.keys(config).forEach(k => this.config[k] = config[k] );
}
// general properties
this.dateCreated = new Date();
this.date = init.date;
this.arrayBuffer = init.arrayBuffer;
this.url = init.url; // for browser using a VF on a server
this.callback = init.callback;
this.data = undefined;
this.fontFamily = init.fontFamily;
this.instances = [];
this.axes = [];
this.instances = [];
this.errors = [];
this.glyphs = [];
this.glyphOffsets = [];
this.glyphSizes = [];
this.tupleOffsets = [];
this.tupleSizes = [];
this.avar = [];
// node-dependent properties
if (this.config.isNode) {
this.inFile = init.inFile;
if (!init.outFile)
this.outFile = this.config.outFileDefault;
}
this.path = init.inFile || this.url;
this.filename = init.filename || this.path.substr(this.path.lastIndexOf("/")+1); // works nicely even when there are no slashes in the name because of the -1 return :)
this.filesize = init.filesize;
// SamsaFont methods
//////////////////////////////////
// load()
//////////////////////////////////
this.load = () => {
if (this.config.isNode) {
// open the font file
try {
this.fd = config.fs.openSync (this.inFile, "r");
}
catch (error) {
this.errors.push(error);
quit(this);
}
this.stat = config.fs.fstatSync(this.fd);
this.filesize = this.stat.size;
this.date = this.stat.birthtimeMs;
this.parse();
}
else if (this.url) {
// fetch font binary from a url
// - works for http: and https: urls (including relative from the current file)
// - works for data: urls
// - note that in a browser frontend application, the font url normally needs to be on the same server as the application for same origin policy
fetch(this.url)
.then(response => {
return response.arrayBuffer();
})
.then(arrayBuffer => {
this.filesize = arrayBuffer.byteLength;
this.data = new DataView(arrayBuffer);
this.parse();
});
}
}
//////////////////////////////////
// parse()
//////////////////////////////////
this.parse = () => {
let font = this;
let data = this.data;
let config = this.config;
let table;
let p=p_=0; // data pointers
let node = this.config.isNode;
let fd = this.fd;
let read, write;
if (node) {
read = this.config.fs.readSync;
write = this.config.fs.writeSync;
}
/////////////////////////////////////////////////////////////////////////////////
// sfnt first 12 bytes
if (node) {
data = Buffer.alloc(12);
read (fd, data, 0, 12, 0);
}
font.fingerprint = data.getUint32(0);
switch (font.fingerprint) {
case 0x00010000: // normal TrueType
case 0x74727565: // 'true' (as in Skia.ttf)
font.flavor = "truetype";
break;
case 0x4f54544f: // 'OTTO' (as in OpenType OTF fonts)
font.flavor = "cff";
break;
default:
font.errors.push ("Invalid first 4 bytes of the file. Must be one of: 0x00010000, 0x74727565, 0x4f54544f");
break;
}
if (!font.errors.length)
{
font.numTables = data.getUint16(4);
if (font.numTables > config.sfnt.maxNumTables)
font.errors.push (`numTables (${font.numTables}) exceeds config.sfnt.maxNumTables (${config.sfnt.maxNumTables})`);
else {
/////////////////////////////////////////////////////////////////////////////////
// get sfnt table directory
font.tableDirectory = [];
font.tables = {};
if (node) {
p = 0;
data = Buffer.alloc(16 * font.numTables);
read (fd, data, 0, 16 * font.numTables, 12);
}
else
p = 12;
for (var t=0; t<font.numTables; t++) {
var tag = data.getTag (p);
if (!tag) {
font.errors.push ("Tag value is invalid");
break;
}
font.tables[tag] = font.tableDirectory[t] = {
id: t,
tag: tag,
checkSum: data.getUint32(p+4),
offset: data.getUint32(p+8),
length: data.getUint32(p+12),
};
p += 16;
}
}
}
// parse the short sfnt tables
// - maxp must be first
// - avar must precede fvar (because of normalizing code in fvar parsing)
// - name must precede fvar
// - name must precede STAT
// - gvar isn’t short, but we only parse its header here
["maxp", "hhea", "head", "hmtx", "OS/2", "post", "name", "avar", "fvar", "gvar", "STAT", "loca", "GSUB", "cmap"].forEach(tag => {
if (font.tables[tag])
font.parseSmallTable(tag);
});
// parse glyf table: all glyphs!
if (!node) {
for (let g=0; g < font.numGlyphs; g++) {
font.glyphs[g] = font.parseGlyph(g); // glyf data
font.glyphs[g].tvts = font.parseTvts(g); // gvar data
// delete glyph if this is a big file, to save memory
// - which of these is better?
// font.glyphs[g] = undefined;
// delete font.glyphs[g]
}
}
// glyf end
// we parsed the font, get a timestamp
font.dateParsed = new Date();
font.callback(font);
}
//////////////////////////////////
// parseSmallTable()
//////////////////////////////////
this.parseSmallTable = tag => {
let font = this;
let data;
let tableOffset, p=p_=0; // data pointers
let config = this.config;
let table = {};
let node = this.config.isNode;
let fd, read, write;
if (node) {
fd = this.fd;
read = this.config.fs.readSync;
write = this.config.fs.writeSync;
}
// set up data and pointers
if (node) {
data = Buffer.alloc(font.tables[tag].length);
read (fd, data, 0, font.tables[tag].length, font.tables[tag].offset);
p = tableOffset = 0;
}
else {
data = this.data;
p = tableOffset = font.tables[tag].offset;
}
// switch by tag to process each table
switch (tag) {
case "maxp":
table.version = data.getUint32(p), p+=4;
table.numGlyphs = data.getUint16(p), p+=2;
font.numGlyphs = table.numGlyphs;
break; // maxp end
case "hhea":
table.majorVersion = data.getUint16(p), p+=2;
table.minorVersion = data.getUint16(p), p+=2;
table.ascender = data.getInt16(p), p+=2;
table.descender = data.getInt16(p), p+=2;
table.lineGap = data.getInt16(p), p+=2;
table.advanceWidthMax = data.getUint16(p), p+=2;
table.minLeftSideBearing = data.getInt16(p), p+=2;
table.minRightSideBearing = data.getInt16(p), p+=2;
table.xMaxExtent = data.getInt16(p), p+=2;
table.caretSlopeRise = data.getInt16(p), p+=2;
table.caretSlopeRun = data.getInt16(p), p+=2;
table.caretOffset = data.getInt16(p), p+=2;
p+=8;
table.metricDataFormat = data.getInt16(p), p+=2;
table.numberOfHMetrics = data.getUint16(p), p+=2;
break; // hhea end
case "head":
table.majorVersion = data.getUint16(p), p+=2;
table.minorVersion = data.getUint16(p), p+=2;
table.fontRevision = data.getUint32(p), p+=4;
table.checkSumAdjustment = data.getUint32(p), p+=4;
table.magicNumber = data.getUint32(p), p+=4;
table.flags = data.getUint16(p), p+=2;
table.unitsPerEm = data.getUint16(p), p+=2;
p += 8;
p += 8;
table.xMin = data.getInt16(p), p+=2;
table.yMin = data.getInt16(p), p+=2;
table.xMax = data.getInt16(p), p+=2;
table.yMax = data.getInt16(p), p+=2;
table.macStyle = data.getUint16(p), p+=2;
table.lowestRecPPEM = data.getUint16(p), p+=2;
table.fontDirectionHint = data.getInt16(p), p+=2;
table.indexToLocFormat = data.getUint16(p), p+=2;
table.glyphDataFormat = data.getUint16(p), p+=2;
font.unitsPerEm = table.unitsPerEm;
break; // head end
case "hmtx":
font.widths = [];
if (font.tables['hhea'].data.numberOfHMetrics < 1)
font.errors.push ("hhea: numberOfHMetrics must be >=1.")
for (let m=0; m<font.numGlyphs; m++) {
if (m < font.tables['hhea'].data.numberOfHMetrics) {
font.widths[m] = data.getUint16(p), p+=2;
p+=2; // skip lsb
}
else
font.widths[m] = font.widths[m-1];
}
break; // hmtx end
case "OS/2":
table.version = data.getUint16(p), p+=2;
table.xAvgCharWidth = data.getInt16(p), p+=2;
table.usWeightClass = data.getUint16(p), p+=2;
table.usWidthClass = data.getUint16(p), p+=2;
table.fsType = data.getUint16(p), p+=2;
table.ySubscriptXSize = data.getInt16(p), p+=2;