Skip to content

Commit

Permalink
Mod icon generator (#56)
Browse files Browse the repository at this point in the history
* mod icon generator

* cli: bundle the font

* cli: only generate icon if --unstable --allow-ffi

* cli: only upgrade with --unstable if it's already unstable

* include font license file

* remove workspace file

* figured out vscode settings to enable deno

* put the font face declaration to template page

* now without ffi

* bundle with esbuild

* inline constant

* make it actually configurable

* Remove unstable note

---------

Co-authored-by: modmuss50 <[email protected]>
  • Loading branch information
deirn and modmuss50 authored Feb 19, 2024
1 parent 40a247b commit 0e0b07c
Show file tree
Hide file tree
Showing 16 changed files with 356 additions and 44 deletions.
3 changes: 2 additions & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"vscode": {
"extensions": [
"svelte.svelte-vscode",
"shadowtime2000.eta-vscode"
"shadowtime2000.eta-vscode",
"denoland.vscode-deno"
]
}
}
Expand Down
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"editor.insertSpaces": false,
"deno.enablePaths": ["./cli"]
}
9 changes: 7 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
FROM node:18-bullseye
FROM node:18-bookworm

ENV DEBIAN_FRONTEND=noninteractive
ENV PATH="${PATH}:$HOME/gems/bin"
ENV GEM_HOME="$HOME/gems"

RUN apt update && apt install -y ruby-full build-essential zlib1g-dev
RUN gem install jekyll bundler
RUN gem install jekyll bundler

ENV DENO_INSTALL="$HOME/.deno"
ENV DENO_INSTALL_ROOT="$HOME/.deno"
RUN curl -fsSL https://deno.land/x/install/install.sh | sh
ENV PATH="${PATH}:$HOME/.deno/bin"
2 changes: 1 addition & 1 deletion Dockerfile.dev
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:18-bullseye AS BUILD
FROM node:18-bookworm AS BUILD

ENV DEBIAN_FRONTEND=noninteractive
ENV PATH="${PATH}:$HOME/gems/bin"
Expand Down
93 changes: 93 additions & 0 deletions assets/fonts/ComicRelief-Regular.license.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
Copyright 2013 Jeff Davis (https://github.com/loudifier/Comic-Relief)

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file added assets/fonts/ComicRelief-Regular.woff2
Binary file not shown.
1 change: 1 addition & 0 deletions cli/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@
!/commands
!Makefile
!bundle.ts
!fontgen.ts
!utils.ts
31 changes: 24 additions & 7 deletions cli/Makefile
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
ENTRYPOINT=main.ts
DENO_PERMISSIONS=--allow-net
DENO_PERMISSIONS=--allow-net --allow-env --allow-read --allow-write

run:
run: fontgen
cd ../scripts; \
npm install; \
npm run buildLib
deno run $(DENO_PERMISSIONS) $(ENTRYPOINT)

test:
deno test

check:
deno check $(ENTRYPOINT)

build: check
deno run --allow-env --allow-read --allow-net --allow-write bundle.ts
fontgen:
deno run --allow-read --allow-write fontgen.ts

build: fontgen check
deno run --allow-env --allow-read --allow-net --allow-write --allow-run bundle.ts

install: build
deno install $(DENO_PERMISSIONS) -f -n fabric bundled.ts

install-stable: build
deno install $(DENO_PERMISSIONS) -f -n fabric bundled.ts

init:
rm -rf ./test
deno run $(DENO_PERMISSIONS) $(ENTRYPOINT) init ./test

init-stable:
rm -rf ./test
deno run $(DENO_PERMISSIONS) $(ENTRYPOINT) init ./test
24 changes: 14 additions & 10 deletions cli/bundle.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
import { bundle } from "https://deno.land/x/[email protected]/mod.ts";
import * as esbuild from "https://deno.land/x/[email protected]/mod.js";
import { denoPlugins } from "https://deno.land/x/[email protected]/mod.ts";
import { format } from "https://deno.land/[email protected]/datetime/mod.ts";

const result = await bundle(
new URL("./main.ts", import.meta.url),
);

const header = `/**
* Fabric Command Line tools
* This file contains a bundled TypeScript file with the code and dependencies for the Fabric command line tools.
* It is expected to be ran using https://deno.com/runtime. The source code for this tool can be found at: https://github.com/FabricMC/fabricmc.net
*/
`;

const code = result.code.replace(
"%__VERSION__%",
format(new Date(), "yyyy-MM-dd HH:mm:ss"),
);
await esbuild.build({
plugins: [...denoPlugins()],
entryPoints: ["./main.ts"],
outfile: "./bundled.ts",
bundle: true,
format: "esm",
target: ["deno1"],
minify: true,
banner: { js: header },
define: { __VERSION__: JSON.stringify(format(new Date(), "yyyy-MM-dd HH:mm:ss")) },
});

await Deno.writeTextFile("bundled.ts", header + code);
esbuild.stop();
60 changes: 54 additions & 6 deletions cli/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,18 @@ import * as path from "https://deno.land/[email protected]/path/mod.ts";
import { colors } from "https://deno.land/x/[email protected]/ansi/mod.ts";
import * as utils from "../utils.ts";
import { ensureDir } from "https://deno.land/[email protected]/fs/ensure_dir.ts";
import fontData from "../font.ts";
import { decodeBase64 } from "https://deno.land/[email protected]/encoding/base64.ts";
import * as png from "https://deno.land/x/[email protected]/mod.ts";
import * as pureimage from "https://esm.sh/[email protected]";
// @deno-types="https://esm.sh/v135/@types/[email protected]/index.d.ts"
import * as opentype from "https://esm.sh/[email protected]";

const error = colors.bold.red;
const progress = colors.bold.yellow;
const success = colors.bold.green;

const ICON_ADVANCED_OPTION = "Generate Unique Mod Icon";
const KOTLIN_ADVANCED_OPTION = "Kotlin Programming Language";
const DATAGEN_ADVANCED_OPTION = "Data Generation";
const SPLIT_ADVANCED_OPTION = "Split client and common sources";
Expand Down Expand Up @@ -89,16 +96,54 @@ async function generate(
? defaultOptions(path.basename(outputDir))
: promptUser(path.basename(outputDir), cli));

const fontLoader = pureimage.registerFont("", generator.ICON_FONT);
fontLoader.font = opentype.parse(decodeBase64(fontData).buffer);
fontLoader.loaded = true;

const options: generator.Options = {
config,
writer: {
write: async (contentPath, content, options) => {
await writeFile(outputDir, contentPath, content, options);
},
},
canvas: {
create(width, height) {
const bitmap = pureimage.make(width, height);

return {
getContext: (id) => bitmap.getContext(id),
getPng: () => png.encode(bitmap.data, bitmap.width, bitmap.height),
measureText(ctx: pureimage.Context, text) {
const font = fontLoader.font;
const fontSize = ctx._font.size!;

let advance = 0;
let ascent = 0;
let descent = 0;

const glyphs = font.stringToGlyphs(text);

for (const glyph of glyphs) {
const metrics = glyph.getMetrics();
advance += glyph.advanceWidth!;
ascent = Math.max(ascent, metrics.yMax);
descent = Math.min(descent, metrics.yMin);
}

return {
width: (advance / font.unitsPerEm) * fontSize,
ascent: Math.abs((ascent / font.unitsPerEm) * fontSize),
descent: Math.abs((descent / font.unitsPerEm) * fontSize),
};
},
};
},
},
};

console.log(progress("Generating mod template..."));

await generator.generateTemplate(options);
console.log(success("Done!"));
}
Expand Down Expand Up @@ -203,7 +248,7 @@ async function promptUser(

const advancedOptions = cliOptions ?? await Checkbox.prompt({
message: "Advanced options",
options: getAdancedOptions(minecraftVersion),
options: getAdvancedOptions(minecraftVersion),
});

return {
Expand All @@ -214,6 +259,7 @@ async function promptUser(
useKotlin: advancedOptions.includes(KOTLIN_ADVANCED_OPTION),
dataGeneration: advancedOptions.includes(DATAGEN_ADVANCED_OPTION),
splitSources: advancedOptions.includes(SPLIT_ADVANCED_OPTION),
uniqueModIcon: advancedOptions.includes(ICON_ADVANCED_OPTION),
};
}

Expand Down Expand Up @@ -249,13 +295,15 @@ async function defaultOptions(
useKotlin: false,
dataGeneration: false,
splitSources: generator.minecraftSupportsSplitSources(minecraftVersion),
uniqueModIcon: true,
};
}

function getAdancedOptions(minecraftVersion: string): CheckboxValueOptions {
const options: CheckboxValueOptions = [
{ value: KOTLIN_ADVANCED_OPTION },
];
function getAdvancedOptions(minecraftVersion: string): CheckboxValueOptions {
const options: CheckboxValueOptions = [];

options.push({ value: ICON_ADVANCED_OPTION, checked: true });
options.push({ value: KOTLIN_ADVANCED_OPTION });

if (generator.minecraftSupportsDataGen(minecraftVersion)) {
options.push({
Expand Down Expand Up @@ -287,7 +335,7 @@ async function writeFile(
};

// is there a cleaner way to do this?
if (content instanceof ArrayBuffer) {
if (content instanceof ArrayBuffer || content instanceof Uint8Array) {
const data = new Uint8Array(content);
await Deno.writeFile(output, data, writeOptions);
} else {
Expand Down
13 changes: 13 additions & 0 deletions cli/fontgen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { encodeBase64 } from "https://deno.land/[email protected]/encoding/base64.ts";

// @deno-types="npm:@types/wawoff2"
import * as wawoff2 from "npm:[email protected]";

const woff2 = await Deno.readFile("../assets/fonts/ComicRelief-Regular.woff2");
const woff = await wawoff2.decompress(woff2);
const base64 = encodeBase64(woff);

Deno.writeTextFileSync(
"./font.ts",
`export default ${JSON.stringify(base64)};`,
);
6 changes: 5 additions & 1 deletion cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import {
import { initCommand } from "./commands/init.ts";
import { upgradeCommand } from "./commands/upgrade.ts";

// Replaced by esbuild.
declare let __VERSION__: string;
const VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "dev";

// Set the XML parser as we do not have DomParser here.
generator.setXmlVersionParser((xml) => {
const document = parseXml(xml) as any;
Expand All @@ -19,7 +23,7 @@ generator.setXmlVersionParser((xml) => {
if (import.meta.main) {
const cmd = new Command()
.name("Fabric CLI tools")
.version("%__VERSION__%") // Replaced by bundle.ts
.version(VERSION)
.description("A set of command line tools to aid Fabric mod development")
.action(() => {
// Show the help in the default command with no args.
Expand Down
Loading

0 comments on commit 0e0b07c

Please sign in to comment.