Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type: implement #7147 and minor refactors #7440

Merged
merged 2 commits into from
Dec 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 58 additions & 54 deletions src/type/p5.Font.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,6 @@
import Typr from './lib/Typr.js';
import { createFromCommands } from '@davepagurek/bezier-path';

function unquote(name) {
// Unquote name from CSS
if ((name.startsWith('"') || name.startsWith("'")) && name.at(0) === name.at(-1)) {
return name.slice(1, -1).replace(/\/(['"])/g, '$1');
}
return name;
}

function font(p5, fn) {

const pathArgCounts = { M: 2, L: 2, C: 6, Q: 4 };
Expand All @@ -62,53 +54,18 @@ function font(p5, fn) {
this.face = fontFace;
}

verticalAlign(size) {
const { sCapHeight } = this.data?.['OS/2'] || {};
const { unitsPerEm = 1000 } = this.data?.head || {};
const { ascender = 0, descender = 0 } = this.data?.hhea || {};
const current = ascender / 2;
const target = (sCapHeight || (ascender + descender)) / 2;
const offset = target - current;
return offset * size / unitsPerEm;
}

variations() {
let vars = {};
if (this.data) {
let axes = this.face?.axes;
if (axes) {
axes.forEach(ax => {
vars[ax.tag] = ax.value;
});
}
}
fontFaceVariations.forEach(v => {
let val = this.face[v];
if (val !== 'normal') {
vars[v] = vars[v] || val;
}
});
return vars;
}

metadata() {
let meta = this.data?.name || {};
for (let p in this.face) {
if (!/^load/.test(p)) {
meta[p] = meta[p] || this.face[p];
}
}
return meta;
}

fontBounds(...args) { // alias for p5.fontBounds
if (!this._pInst) throw Error('p5 required for fontBounds()');
return this._pInst.fontBounds(...args);
fontBounds(str, x, y, width, height, options) {
({ width, height, options } = this._parseArgs(width, height, options));
let renderer = options?.graphics?._renderer || this._pInst._renderer;
if (!renderer) throw Error('p5 or graphics required for fontBounds()');
return renderer.fontBounds(str, x, y, width, height);
}

textBounds(...args) { // alias for p5.textBounds
if (!this._pInst) throw Error('p5 required for textBounds()'); // TODO:
return this._pInst.textBounds(...args);
textBounds(str, x, y, width, height, options) {
({ width, height, options } = this._parseArgs(width, height, options));
let renderer = options?.graphics?._renderer || this._pInst._renderer;
if (!renderer) throw Error('p5 or graphics required for fontBounds()');
return renderer.textBounds(str, x, y, width, height);
}

textToPaths(str, x, y, width, height, options) {
Expand Down Expand Up @@ -208,6 +165,35 @@ function font(p5, fn) {
return geom;
}

variations() {
let vars = {};
if (this.data) {
let axes = this.face?.axes;
if (axes) {
axes.forEach(ax => {
vars[ax.tag] = ax.value;
});
}
}
fontFaceVariations.forEach(v => {
let val = this.face[v];
if (val !== 'normal') {
vars[v] = vars[v] || val;
}
});
return vars;
}

metadata() {
let meta = this.data?.name || {};
for (let p in this.face) {
if (!/^load/.test(p)) {
meta[p] = meta[p] || this.face[p];
}
}
return meta;
}

static async list(log = false) { // tmp
if (log) {
console.log('There are', document.fonts.size, 'font-faces\n');
Expand All @@ -228,6 +214,16 @@ function font(p5, fn) {
}

/////////////////////////////// HELPERS ////////////////////////////////

_verticalAlign(size) {
const { sCapHeight } = this.data?.['OS/2'] || {};
const { unitsPerEm = 1000 } = this.data?.head || {};
const { ascender = 0, descender = 0 } = this.data?.hhea || {};
const current = ascender / 2;
const target = (sCapHeight || (ascender + descender)) / 2;
const offset = target - current;
return offset * size / unitsPerEm;
}

/*
Returns an array of line objects, each containing { text, x, y, glyphs: [ {g, path} ] }
Expand Down Expand Up @@ -579,7 +575,7 @@ function font(p5, fn) {

// parse the font data
let fonts = Typr.parse(result);
console.log(fonts[0])

// TODO: generate descriptors from font in the future

if (fonts.length !== 1 || fonts[0].cmap === undefined) {
Expand Down Expand Up @@ -635,6 +631,14 @@ function font(p5, fn) {
return new p5.Font(pInst, face, name, path, rawFont);
}

function unquote(name) {
// Unquote name from CSS
if ((name.startsWith('"') || name.startsWith("'")) && name.at(0) === name.at(-1)) {
return name.slice(1, -1).replace(/\/(['"])/g, '$1');
}
return name;
}

function createFontFace(name, path, descriptors, rawFont) {
let fontArg = rawFont?._data;
if (!fontArg) {
Expand Down
14 changes: 6 additions & 8 deletions src/type/text2d.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ function text2d(p5, fn) {
}
return this._renderer[func](...args);
};
// TODO: is this necessary?
p5.Graphics.prototype[func] = function (...args) {
return this._renderer[func](...args);
};
Expand Down Expand Up @@ -160,8 +159,7 @@ function text2d(p5, fn) {
* @returns - a bounding box object for the text block: {x,y,w,h}
*/
Renderer.prototype.textBounds = function (str, x, y, width, height) {
//console.log('TEXT BOUNDS: ', str, x, y, width, height);
// delegate to _textBoundsSingle measure function
// delegate to _textBoundsSingle for measuring
return this._computeBounds(fn._TEXT_BOUNDS, str, x, y, width, height).bounds;
};

Expand All @@ -175,7 +173,7 @@ function text2d(p5, fn) {
* @returns - a bounding box object for the text block: {x,y,w,h}
*/
Renderer.prototype.fontBounds = function (str, x, y, width, height) {
// delegate to _fontBoundsSingle measure function
// delegate to _fontBoundsSingle for measuring
return this._computeBounds(fn._FONT_BOUNDS, str, x, y, width, height).bounds;
};

Expand Down Expand Up @@ -260,7 +258,7 @@ function text2d(p5, fn) {
};
};

Renderer.prototype._currentTextFont = function() {
Renderer.prototype._currentTextFont = function () {
return this.states.textFont.font || this.states.textFont.family;
}

Expand Down Expand Up @@ -1089,7 +1087,7 @@ function text2d(p5, fn) {
};

if (p5.Renderer2D) {
p5.Renderer2D.prototype.textDrawingContext = function() {
p5.Renderer2D.prototype.textDrawingContext = function () {
return this.drawingContext;
};
p5.Renderer2D.prototype._renderText = function (text, x, y, maxY, minY) {
Expand Down Expand Up @@ -1187,7 +1185,7 @@ function text2d(p5, fn) {
}
}
if (p5.RendererGL) {
p5.RendererGL.prototype.textDrawingContext = function() {
p5.RendererGL.prototype.textDrawingContext = function () {
if (!this._textDrawingContext) {
this._textCanvas = document.createElement('canvas');
this._textCanvas.width = 1;
Expand Down Expand Up @@ -1252,7 +1250,7 @@ function text2d(p5, fn) {
console.warn(`${textBaseline} is not supported in WebGL mode.`); // FES?
break;
}
yOff += this.states.textFont.font?.verticalAlign(textSize) || 0;
yOff += this.states.textFont.font?._verticalAlign(textSize) || 0;
dataArr.forEach(ele => ele.y += yOff);
return dataArr;
}
Expand Down
76 changes: 76 additions & 0 deletions test/manual-test-examples/type/text-to-points-buffer.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<html>

<!--
CSS-style font properties (preferred, but doesn't support custom axes):
font-weight: 650;
font-style: oblique 80deg; (must add deg)
font-stretch: 75%; (only accepts percentage with %)
font-optical-sizing: auto; (only allows for 'auto' or 'none')
Font-variation style properties:
font-variations-settings: 'wght' 650, 'slnt' 80, 'wdth' 75, 'opsz' 100;
-->

<head>
<meta charset='UTF-8'>
<!-- <script language="javascript" type="text/javascript" src="./lib/Typr.js"></script>
<script language="javascript" type="text/javascript" src="./lib/Typr.U.js"></script> -->

<style>
body {
padding: 0;
margin: 0;
}

canvas {
border: 1px solid #f0f0f0;
display: block;
}

img {
border: 1px solid #fff;
}

div {
margin: 100px 0px;
}
</style>
</head>



<body>
<script type='module'>
import p5 from '../../../src/app.js';
let sketch = async function (p) {
let f, g, pts;
p.setup = async function () {
p.createCanvas(400, 300);
f = await p.loadFont("https://fonts.gstatic.com/s/opensans/v40/memSYaGs126MiZpBA-UvWbX2vVnXBbObj2OVZyOOSr4dVJWUgsg-1y4nY1M2xLER.ttf");
g = p.createGraphics(p.width, p.height)
g.background(220);
g.textAlign(p.CENTER, p.CENTER)
g.textFont(f, 50);

g.text('Serendipity', g.width / 2, g.height / 2);
//let bb = g.textBounds('Serendipity', g.width / 2, g.height / 2);
let bb = f.textBounds('Serendipity', g.width / 2, g.height / 2, { graphics: g });
g.noFill();
g.stroke(0);
g.rect(bb.x, bb.y, bb.w, bb.h);

pts = f.textToPoints('Serendipity', g.width / 2, g.height / 2, { graphics: g });
pts.forEach((pt, i) => {
g.fill(0);
g.circle(pt.x, pt.y, 2);
});
p.image(g, 0, 0);
}
}

new p5(sketch);
</script>

</body>


</html>
Loading