game-font-split 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js ADDED
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { createFontFile } = require('../src/utils/font');
6
+ const supportFont = require('../src/config/supportFont.json');
7
+
8
+ const args = process.argv.slice(2);
9
+
10
+ if (args.includes('--help') || args.includes('-h') || args.length === 0) {
11
+ console.log('game-font-split - 字体子集化工具\n');
12
+ console.log('用法:');
13
+ console.log(' game-font-split <字体文件名> <字符> [输出目录]\n');
14
+ console.log('示例:');
15
+ console.log(' game-font-split Microsoft_YaHei.woff "你好世界Hello"');
16
+ console.log(' game-font-split Microsoft_YaHei.woff "你好世界Hello" ./dist\n');
17
+ console.log('参数:');
18
+ console.log(' --list, -l 列出所有可用字体');
19
+ console.log(' --help, -h 显示帮助');
20
+ process.exit(0);
21
+ }
22
+
23
+ if (args.includes('--list') || args.includes('-l')) {
24
+ console.log('可用字体:\n');
25
+ const fontsDir = path.resolve(__dirname, '../fonts');
26
+ supportFont.forEach(f => {
27
+ const exists = fs.existsSync(path.join(fontsDir, f.fileName));
28
+ console.log(` ${f.fileName.padEnd(24)} ${f.label}${exists ? '' : ' (缺失)'}`);
29
+ });
30
+ process.exit(0);
31
+ }
32
+
33
+ const fontName = args[0];
34
+ const chars = args[1];
35
+ const outDir = path.resolve(args[2] || './output');
36
+
37
+ if (!chars) {
38
+ console.error('错误: 请提供字符参数');
39
+ console.error('用法: game-font-split <字体文件名> <字符>');
40
+ process.exit(1);
41
+ }
42
+
43
+ if (!fs.existsSync(outDir)) {
44
+ fs.mkdirSync(outDir, { recursive: true });
45
+ }
46
+
47
+ const result = createFontFile({
48
+ fontFamily: fontName,
49
+ content: chars,
50
+ fileName: fontName
51
+ });
52
+
53
+ if (!result) {
54
+ process.exit(1);
55
+ }
56
+
57
+ const outputFile = path.join(outDir, result.fileName);
58
+ fs.writeFileSync(outputFile, result.buffer);
59
+ console.log(`完成: ${outputFile}`);
60
+ console.log(` 字体: ${result.metadata.familyName}`);
61
+ console.log(` glyphs: ${result.metadata.numGlyphs}`);
62
+ console.log(` 原始: ${result.metadata.originalSize} bytes`);
63
+ console.log(` 输出: ${result.buffer.byteLength} bytes`);
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "game-font-split",
3
+ "version": "1.0.0",
4
+ "description": "游戏字体子集化工具 - 从 mainJson 收集文字信息并裁剪字体文件",
5
+ "main": "src/index.js",
6
+ "bin": {
7
+ "game-font-split": "bin/cli.js"
8
+ },
9
+ "files": [
10
+ "src",
11
+ "fonts",
12
+ "bin"
13
+ ],
14
+ "scripts": {
15
+ "test": "node test/test.js"
16
+ },
17
+ "keywords": [
18
+ "font",
19
+ "subset",
20
+ "game",
21
+ "opentype"
22
+ ],
23
+ "license": "MIT",
24
+ "dependencies": {
25
+ "opentype.js": "1.3.4"
26
+ }
27
+ }
@@ -0,0 +1,14 @@
1
+ [
2
+ {"label":"Arial","value":"Arial","fileName":"Arial.woff"},
3
+ {"label":"微软雅黑","value":"Microsoft Yahei","fileName":"Microsoft_YaHei.woff"},
4
+ {"label":"楷体","value":"KaiTi","fileName":"kaiti.woff"},
5
+ {"label":"宋体","value":"SimSun","fileName":"songti.woff"},
6
+ {"label":"droid sans mono","value":"Droid Sans Mono","fileName":"Droid_Sans_Mono.woff"},
7
+ {"value": "FZLTCHJW","label": "方正兰亭粗黑简体","fileName": "FZLTCHJW.woff"},
8
+ {"value": "fzltxhjt","label": "方正兰亭细黑简体","fileName": "FZLTXIHJW.woff"},
9
+ {"value": "fzltzhjt","label": "方正兰亭中黑简体","fileName": "FZLTZHJW.woff"},
10
+ {"value": "fzcsjt","label": "方正粗宋简体","fileName": "FZCSJW.woff"},
11
+ {"value": "fzdhjt","label": "方正大黑简体","fileName": "FZDHTJW.woff"},
12
+ {"value": "fzcyjt","label": "方正粗圆简体","fileName": "FZY4JW.woff"},
13
+ {"label":"字魂86号-杨任东楷书","value":"ZIHUN86","fileName":"ZIHUN86.woff"}
14
+ ]
package/src/index.js ADDED
@@ -0,0 +1,135 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { collectMainJsonFontInfo, createFontFile } = require('./utils/font');
4
+ const supportFont = require('./config/supportFont.json');
5
+
6
+ /**
7
+ * @param {object} mainJson - 游戏主配置 JSON
8
+ * @param {object} resourceJson - 资源列表 JSON(会被修改,追加字体资源)
9
+ * @param {object} [options]
10
+ * @param {string} [options.outDir='./static/'] - 输出目录
11
+ * @returns {{ resourceJson: object, fontInfo: object }}
12
+ */
13
+ const gameFontSplit = (mainJson, resourceJson, options = {}) => {
14
+ const { outDir = './static/' } = options;
15
+
16
+ if (!mainJson) {
17
+ throw new Error('mainJson 不能为空');
18
+ }
19
+ if (!resourceJson) {
20
+ throw new Error('resourceJson 不能为空');
21
+ }
22
+
23
+ const outputPath = path.resolve(outDir);
24
+ if (!fs.existsSync(outputPath)) {
25
+ fs.mkdirSync(outputPath, { recursive: true });
26
+ }
27
+
28
+ const fontInfo = collectMainJsonFontInfo(mainJson);
29
+ console.log('收集到的字体信息:', Object.keys(fontInfo));
30
+
31
+ if (!mainJson.props) {
32
+ mainJson.props = {};
33
+ }
34
+ var __fontList__ = mainJson.props.__fontList__ || [];
35
+
36
+ if (!__fontList__.length) {
37
+ var fontKeys = Object.keys(fontInfo);
38
+ __fontList__ = supportFont.filter(function (item) {
39
+ return fontKeys.some(function (key) {
40
+ return item.value && item.value.toLowerCase() === key.toLowerCase();
41
+ });
42
+ });
43
+ mainJson.props.__fontList__ = __fontList__;
44
+ console.log('已补充 __fontList__:', __fontList__.map(function (i) { return i.label; }));
45
+ }
46
+
47
+ var fontList = __fontList__;
48
+
49
+ const list = Object.keys(fontInfo).map(key => ({
50
+ fontFamily: key,
51
+ content: fontInfo[key],
52
+ fileName: (fontList.find(function (item) { return item.value && item.value.toLowerCase() === key.toLowerCase(); }) || {}).fileName
53
+ }));
54
+
55
+ const validItems = list.filter(item => item.content && item.fileName);
56
+ const skippedItems = list.filter(item => !item.content || !item.fileName);
57
+
58
+ if (skippedItems.length > 0) {
59
+ console.warn('跳过以下字体(缺少内容或文件名配置):', skippedItems.map(i => i.fontFamily));
60
+ }
61
+
62
+ if (validItems.length === 0) {
63
+ console.log('没有需要处理的字体');
64
+ return { resourceJson, fontInfo };
65
+ }
66
+
67
+ console.log(`准备处理 ${validItems.length} 个字体:`, validItems.map(i => i.fileName));
68
+
69
+ if (!resourceJson.list) {
70
+ resourceJson.list = [];
71
+ }
72
+ let resourceId = resourceJson.list.reduce((max, item) => Math.max(max, item.id || 0), 0) + 1;
73
+
74
+ for (const item of validItems) {
75
+ const result = createFontFile({
76
+ fontFamily: item.fontFamily,
77
+ content: item.content,
78
+ fileName: item.fileName
79
+ });
80
+
81
+ if (!result) continue;
82
+
83
+ const outputFile = path.join(outputPath, result.fileName);
84
+ fs.writeFileSync(outputFile, result.buffer);
85
+ console.log(`字体已写入: ${outputFile} (${result.metadata.numGlyphs} glyphs, ${result.buffer.byteLength} bytes)`);
86
+ var exists = resourceJson.list.some(function (r) { return r.name === result.fileName; });
87
+ if (exists) {
88
+ console.log('字体资源已存在,跳过: ' + result.fileName);
89
+ continue;
90
+ }
91
+ resourceJson.list.push({
92
+ id: resourceId++,
93
+ ext: 'woff',
94
+ name: result.fileName,
95
+ alias: result.fileName,
96
+ host: 'http://localhost:10087/resource',
97
+ src: `static/${result.fileName}`,
98
+ parameter: '',
99
+ xhrType: '',
100
+ noLoader: true
101
+ });
102
+ }
103
+
104
+ console.log('字体处理完成');
105
+ return { resourceJson, fontInfo };
106
+ };
107
+
108
+ var gameFontSplitByPath = function (mainJsonPath, resourceJsonPath) {
109
+ var resolvedMainPath = path.resolve(mainJsonPath);
110
+ var resolvedResPath = path.resolve(resourceJsonPath);
111
+
112
+ if (!fs.existsSync(resolvedMainPath)) {
113
+ throw new Error('mainJson 文件不存在: ' + resolvedMainPath);
114
+ }
115
+ if (!fs.existsSync(resolvedResPath)) {
116
+ throw new Error('resourceJson 文件不存在: ' + resolvedResPath);
117
+ }
118
+
119
+ var mainJson = JSON.parse(fs.readFileSync(resolvedMainPath, 'utf-8'));
120
+ var resourceJson = JSON.parse(fs.readFileSync(resolvedResPath, 'utf-8'));
121
+ var staticDir = path.join(path.dirname(resolvedResPath), 'static');
122
+
123
+ var result = gameFontSplit(mainJson, resourceJson, { outDir: staticDir });
124
+
125
+ fs.writeFileSync(resolvedMainPath, JSON.stringify(mainJson, null, 2), 'utf-8');
126
+ fs.writeFileSync(resolvedResPath, JSON.stringify(result.resourceJson, null, 2), 'utf-8');
127
+ console.log('文件已写回: ' + resolvedMainPath);
128
+ console.log('文件已写回: ' + resolvedResPath);
129
+
130
+ return { mainJson: mainJson, resourceJson: result.resourceJson };
131
+ };
132
+
133
+ module.exports = gameFontSplit;
134
+ module.exports.gameFontSplit = gameFontSplit;
135
+ module.exports.gameFontSplitByPath = gameFontSplitByPath;
@@ -0,0 +1,78 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { subsetFont } = require('./fontProcessor');
4
+
5
+ const collectMainJsonFontInfo = (mainJson) => {
6
+ const fontCollection = {};
7
+
8
+ const addText = (family, text) => {
9
+ if (!family || !text) return;
10
+ family = family.toLowerCase();
11
+ if (!fontCollection[family]) {
12
+ fontCollection[family] = new Set();
13
+ fontCollection[family].add('|ÉqM');
14
+ }
15
+ for (const char of text) {
16
+ fontCollection[family].add(char);
17
+ }
18
+ };
19
+
20
+ const traverse = (node) => {
21
+ if (!node) return;
22
+
23
+ if (node.conName === 'Text') {
24
+ const family = node.content && node.content.style && node.content.style._fontFamily;
25
+ const text = node.content && node.content.text;
26
+ addText(family, text);
27
+ } else if (['TextDom', 'ButtonDom'].includes(node.conName)) {
28
+ const family = node._style && node._style._fontFamily;
29
+ let text = node._innerHTML || '';
30
+ text = text.replace(/<[^>]+>/g, '');
31
+ addText(family, text);
32
+ }
33
+
34
+ if (node.children && Array.isArray(node.children)) {
35
+ node.children.forEach(traverse);
36
+ }
37
+ if (node.dom && Array.isArray(node.dom)) {
38
+ node.dom.forEach(traverse);
39
+ }
40
+ };
41
+
42
+ if (mainJson.pages && Array.isArray(mainJson.pages)) {
43
+ mainJson.pages.forEach(traverse);
44
+ mainJson.pages.forEach(page => {
45
+ (page.dom || []).forEach(traverse);
46
+ });
47
+ }
48
+
49
+ const result = {};
50
+ for (const key in fontCollection) {
51
+ result[key] = Array.from(fontCollection[key]).join('');
52
+ }
53
+ return result;
54
+ };
55
+
56
+ const FONT_DIR = path.resolve(__dirname, '../../fonts');
57
+
58
+ const createFontFile = ({ fontFamily, content, fileName }) => {
59
+ try {
60
+ const fontPath = path.join(FONT_DIR, fileName);
61
+ if (!fs.existsSync(fontPath)) {
62
+ console.warn(`字体文件不存在: ${fontPath}`);
63
+ return null;
64
+ }
65
+ console.log(`开始处理字体: ${fontFamily}, 文件: ${fileName}`);
66
+ const result = subsetFont(fontPath, content);
67
+ return {
68
+ fileName,
69
+ buffer: result.buffer,
70
+ metadata: result.metadata
71
+ };
72
+ } catch (error) {
73
+ console.error(`处理字体失败: ${fileName}`, error);
74
+ return null;
75
+ }
76
+ };
77
+
78
+ module.exports = { collectMainJsonFontInfo, createFontFile };
@@ -0,0 +1,40 @@
1
+ const opentype = require('opentype.js');
2
+ const fs = require('fs');
3
+ const subsetFont = (fontPath, characters) => {
4
+ const buffer = fs.readFileSync(fontPath);
5
+ const font = opentype.parse(buffer.buffer);
6
+
7
+ const charSet = Array.from(new Set(characters));
8
+ const glyphs = [font.glyphs.get(0)];
9
+
10
+ charSet.forEach(char => {
11
+ const index = font.charToGlyphIndex(char);
12
+ if (index > 0) {
13
+ glyphs.push(font.glyphs.get(index));
14
+ }
15
+ });
16
+
17
+ const subsetFont = new opentype.Font({
18
+ familyName: font.names.fontFamily.en,
19
+ styleName: font.names.fontSubfamily.en,
20
+ unitsPerEm: font.unitsPerEm,
21
+ ascender: font.ascender,
22
+ descender: font.descender,
23
+ glyphs: glyphs
24
+ });
25
+
26
+ const outputBuffer = subsetFont.toArrayBuffer();
27
+
28
+ return {
29
+ buffer: Buffer.from(outputBuffer),
30
+ metadata: {
31
+ familyName: font.names.fontFamily.en,
32
+ styleName: font.names.fontSubfamily.en,
33
+ unitsPerEm: font.unitsPerEm,
34
+ numGlyphs: glyphs.length,
35
+ originalSize: buffer.byteLength
36
+ }
37
+ };
38
+ };
39
+
40
+ module.exports = { subsetFont };