Skip to content

Commit

Permalink
refactor: enhance loadAsciiFont function with promise support and err…
Browse files Browse the repository at this point in the history
…or handling
  • Loading branch information
humanbydefinition committed Dec 15, 2024
1 parent d2d6160 commit 643e6ea
Showing 1 changed file with 65 additions and 55 deletions.
120 changes: 65 additions & 55 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,69 +68,79 @@ p5.prototype.registerMethod("beforePreload", p5.prototype.preloadAsciiFont);
* loadAsciiFont('path/to/font.ttf');
*/
p5.prototype.loadAsciiFont = function (font) {
const setFont = async (loadedFont, fontPath) => {
p5asciify.font = loadedFont;

try { // Convert the font to Base64 for use in the text-based ASCII renderer
const response = await fetch(fontPath);
const arrayBuffer = await response.arrayBuffer();
const base64String = btoa(
new Uint8Array(arrayBuffer)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
);
return new Promise((resolve, reject) => {
const setFont = async (loadedFont, fontPath) => {
p5asciify.font = loadedFont;

// Determine the font type based on the file extension
let mimeType = '';
if (fontPath.toLowerCase().endsWith('.ttf')) {
mimeType = 'truetype';
} else if (fontPath.toLowerCase().endsWith('.otf')) {
mimeType = 'opentype';
} else {
mimeType = 'truetype';
try {
const response = await fetch(fontPath);
const arrayBuffer = await response.arrayBuffer();
const base64String = btoa(
new Uint8Array(arrayBuffer)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
);

let mimeType = '';
if (fontPath.toLowerCase().endsWith('.ttf')) {
mimeType = 'truetype';
} else if (fontPath.toLowerCase().endsWith('.otf')) {
mimeType = 'opentype';
} else {
mimeType = 'truetype';
}

p5asciify.fontBase64 = `data:font/${mimeType};charset=utf-8;base64,${base64String}`;
p5asciify.fontFileType = mimeType;
} catch (error) {
console.error('Error converting font to Base64:', error);
}

p5asciify.fontBase64 = `data:font/${mimeType};charset=utf-8;base64,${base64String}`;
p5asciify.fontFileType = mimeType;
} catch (error) {
console.error('Error converting font to Base64:', error);
}
// If the sketch is running, update font related components
if (p5asciify.p5Instance.frameCount > 0) {
try {
p5asciify.asciiFontTextureAtlas.setFontObject(loadedFont);

// This is where P5AsciifyError might be thrown if unsupported characters exist
p5asciify.asciiCharacterSet.setCharacterSet(p5asciify.asciiCharacterSet.characters);
p5asciify.edgeCharacterSet.setCharacterSet(p5asciify.edgeCharacterSet.characters);

p5asciify.grid.resizeCellPixelDimensions(
p5asciify.asciiFontTextureAtlas.maxGlyphDimensions.width,
p5asciify.asciiFontTextureAtlas.maxGlyphDimensions.height
);

p5asciify.brightnessRenderer.resizeFramebuffers();
p5asciify.edgeRenderer.resizeFramebuffers();
p5asciify.customAsciiRenderer.resizeFramebuffers();
p5asciify.accurateRenderer.resizeFramebuffers();
p5asciify.gradientRenderer.resizeFramebuffers();

p5asciify.edgeRenderer.resetShaders();
p5asciify.accurateRenderer.resetShaders();

p5asciify.textAsciiRenderer.updateFont(p5asciify.fontBase64, p5asciify.fontFileType);
} catch (e) {
// Catch any P5AsciifyError and reject the promise
return reject(e);
}
}

// If the sketch already runs, update the font texture atlas and grid dimensions, as well as the character sets
if (p5asciify.p5Instance.frameCount > 0) {
p5asciify.asciiFontTextureAtlas.setFontObject(loadedFont);
p5asciify.asciiCharacterSet.setCharacterSet(p5asciify.asciiCharacterSet.characters);
p5asciify.edgeCharacterSet.setCharacterSet(p5asciify.edgeCharacterSet.characters);
p5asciify.p5Instance._decrementPreload();
resolve();
};

p5asciify.grid.resizeCellPixelDimensions(
p5asciify.asciiFontTextureAtlas.maxGlyphDimensions.width,
p5asciify.asciiFontTextureAtlas.maxGlyphDimensions.height
if (typeof font === 'string') {
p5asciify.p5Instance.loadFont(
font,
(loadedFont) => { setFont(loadedFont, font); },
() => { reject(new P5AsciifyError(`loadAsciiFont() | Failed to load font from path: '${font}'`)); }
);

p5asciify.brightnessRenderer.resizeFramebuffers();
p5asciify.edgeRenderer.resizeFramebuffers();
p5asciify.customAsciiRenderer.resizeFramebuffers();
p5asciify.accurateRenderer.resizeFramebuffers();
p5asciify.gradientRenderer.resizeFramebuffers();

p5asciify.edgeRenderer.resetShaders();
p5asciify.accurateRenderer.resetShaders();

p5asciify.textAsciiRenderer.updateFont(p5asciify.fontBase64, p5asciify.fontFileType);
} else {
reject(new P5AsciifyError(`loadAsciiFont() | Invalid font parameter. Expected a string/path.`));
}

p5asciify.p5Instance._decrementPreload();
};

if (typeof font === 'string') {
p5asciify.p5Instance.loadFont(
font,
(loadedFont) => { setFont(loadedFont, font); },
() => { throw new P5AsciifyError(`loadAsciiFont() | Failed to load font from path: '${font}'`); }
);
} else {
throw new P5AsciifyError(`loadAsciiFont() | Invalid font parameter. Expected a string/path.`);
}
});
};

p5.prototype.registerPreloadMethod('loadAsciiFont', p5.prototype);

/**
Expand Down

0 comments on commit 643e6ea

Please sign in to comment.