关于 blockbench-plugins
这是一项面向 Blockbench 插件开发的技能,指导开发者使用宿主应用 API。内容涵盖界面组件、模型编辑、事件、导入导出、清理及版本适配验证。
主要功能
- 01创建操作、对话框和侧栏面板
- 02支持撤销的模型编辑
- 03事件订阅与清理
- 04自定义导入导出编解码器
- 05检查宿主版本与 API
适用场景
- 01在菜单或工具栏添加命令
- 02为插件创建侧栏面板
- 03实现模型格式的导入或导出
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jasonjgardner/ blockbench-mcp-project --skill blockbench-plugins安装后在 Claude Code 中输入/blockbench-plugins确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/format_plugin.jsplugin_template.jsreferences/api.mdelements.mdevents.md详细介绍
Blockbench 插件开发
概述
Blockbench 可在桌面端和 Web 上运行,并向插件提供宿主 API 以及内置的渲染/UI 库。选择 API 前,请确认目标宿主版本及其类型;插件变量隔离并不意味着可以不受限制地访问原生模块或文件系统。当较旧的 Wiki 示例与宿主不一致时,请优先参考最新的生成版 API 参考以及目标代码库。请将 variant 和 min_version 设为实际验证过的环境。
关于模型格式选择、UV 单位、绑定区别和导出交接,请参阅格式与交付指南。格式功能标志用于声明宿主行为;它不会为自定义编解码器实现缺失的验证或运行时序列化。
快速参考
| 任务 | 方法 |
|---|---|
| 创建可点击命令 | new Action() - 添加到菜单/工具栏 |
| 显示表单/对话框 | 使用表单字段创建 new Dialog() |
| 添加侧边栏面板 | 使用 Vue 组件创建 new Panel() |
| 修改模型元素 | 使用 Undo.initEdit() → 修改 → Undo.finishEdit() |
| 自定义导入/导出 | new Codec() + new ModelFormat() |
| 响应更改 | Blockbench.on('event_name', callback) |
插件文件结构
plugins/
└── my_plugin/
├── my_plugin.js # Main file (required, ID must match filename)
├── about.md # Extended docs (optional)
└── icon.png # 48x48 icon (optional)
插件注册模板
(function() {
// Store references for cleanup
let myAction, myPanel, myDialog, eventCallback;
Plugin.register('my_plugin', {
title: 'My Plugin',
author: 'Author Name',
description: 'Short description',
icon: 'extension', // Material icon name
version: '1.0.0',
variant: 'both', // 'desktop', 'web', or 'both'
min_version: '4.8.0',
tags: ['Utility'],
onload() {
// Initialize all components here
},
onunload() {
// CRITICAL: Delete ALL components here
},
oninstall() {
Blockbench.showQuickMessage('Installed!');
}
});
})();
操作
操作是可点击的命令,可用于菜单、工具栏和快捷键绑定。
myAction = new Action('my_action_id', {
name: 'Action Name',
description: 'Tooltip text',
icon: 'star',
category: 'edit', // For keybind settings
condition: () => Cube.selected.length > 0,
keybind: new Keybind({ key: 'k', ctrl: true }),
click(event) {
// Action logic
}
});
MenuBar.addAction(myAction, 'filter'); // Add to Filter menu
// Cleanup
myAction.delete();
菜单位置: 'file'、'edit'、'transform'、'filter'、'tools'、'view'、'help'
操作变体:
// Toggle (on/off state)
new Toggle('toggle_id', {
name: 'Feature',
default: false,
onChange(value) { /* handle */ }
});
// Tool (viewport interaction)
new Tool('tool_id', {
name: 'My Tool',
cursor: 'crosshair',
onCanvasClick(data) { /* handle */ },
onCanvasDrag(data) { /* handle */ }
});
对话框
myDialog = new Dialog({
id: 'my_dialog',
title: 'Dialog Title',
width: 540,
form: {
name: { label: 'Name', type: 'text', value: 'default' },
count: { label: 'Count', type: 'number', value: 10, min: 1, max: 100 },
enabled: { label: 'Enabled', type: 'checkbox', value: true },
mode: {
label: 'Mode',
type: 'select',
options: { a: 'Option A', b: 'Option B' },
value: 'a'
},
color: { label: 'Color', type: 'color', value: '#ff0000' },
// Conditional field
advanced: {
label: 'Advanced',
type: 'text',
condition: (form) => form.enabled
}
},
onConfirm(formData) {
console.log(formData.name, formData.count);
this.hide();
}
});
myDialog.show();
// Quick dialogs
Blockbench.textPrompt('Enter Value', 'default', (text) => { });
Blockbench.showMessageBox({ title: 'Alert', message: 'Text', buttons: ['OK'] });
面板
面板会显示在侧边栏中,并使用 Vue 组件。
myPanel = new Panel('my_panel', {
name: 'My Panel',
icon: 'dashboard',
condition: () => Format.animation_mode,
default_position: {
slot: 'left_bar', // 'left_bar', 'right_bar', 'bottom'
height: 300
},
component: {
template: `
<div>
<h3>{{ title }}</h3>
<ul><li v-for="item in items">{{ item.name }}</li></ul>
<button @click="refresh">Refresh</button>
</div>
`,
data() {
return { title: 'Items', items: [] };
},
methods: {
refresh() {
this.items = Cube.selected.map(c => ({ name: c.name }));
}
}
}
});
// Cleanup
myPanel.delete();
模型操作(带撤销)
使用原生撤销功能登记持久的项目编辑,并包含所有受影响的方面。在开始事务前验证目标并暂存异步输入;失败时取消/还原事务。原生操作或绘制 API 可能拥有自己的事务,因此不要再添加相互竞争的嵌套事务。只读检查、摄像机移动和文件写入不等同于可撤销的模型变更。请参阅撤销文档。
// Start tracking
Undo.initEdit({ elements: Cube.selected });
// Modify elements
Cube.selected.forEach(cube => {
cube.from[0] += 5;
cube.to[1] = 20;
cube.rotation[1] = 45;
});
// Update view
Canvas.updateView({
elements: Cube.selected,
element_aspects: { geometry: true, transform: true }
});
// Commit
Undo.finishEdit('Move cubes');
创建元素
创建操作必须在事务完成时记录新对象,而不只是记录一个空的初始列表:
Undo.initEdit({ elements: [], outliner: true });
const createdCube = new Cube({ name: 'body_geo', from: [-4, 0, -2], to: [4, 12, 2] }).init();
Undo.finishEdit('Add body cube', { elements: [createdCube], outliner: true });
Canvas.updateAll();
以下代码片段展示了各个宿主构造函数;修改现有项目时,请将它们放在适当的事务中。组的原点是枢轴;设置父级不会将该原点作为平移量加到立方体边界上。
// Cube
let cube = new Cube({
name: 'my_cube',
from: [0, 0, 0],
to: [16, 16, 16],
origin: [8, 8, 8],
rotation: [0, 45, 0]
}).init();
cube.addTo(Group.selected[0]); // Add to group
// Group (bone)
let group = new Group({
name: 'bone_arm',
origin: [0, 12, 0]
}).init();
group.addTo(); // Add to root
// Texture
let texture = new Texture({ name: 'my_texture' });
texture.fromPath('/path/to/file.png'); // or .fromDataURL()
texture.add(true); // true = add to undo
全局集合
| 集合 | 描述 |
|---|---|
Cube.all / Cube.selected | 所有立方体 / 已选立方体 |
Group.all / Group.selected | 所有组 / 已选组 |
Mesh.all / Mesh.selected | 所有网格 / 已选网格 |
Texture.all / Texture.selected | 所有纹理 / 已选纹理 |
Animation.all / Animation.selected | 所有动画 / 已选动画 |
Outliner.elements | 所有大纲元素 |
事件系统
// Subscribe
eventCallback = (data) => { /* handle */ };
Blockbench.on('update_selection', eventCallback);
// Unsubscribe (use SAME function reference)
Blockbench.removeListener('update_selection', eventCallback);
常见事件: update_selection、select_project、new_project、load_project、save_project、close_project、add_cube、add_group、add_texture、add_animation、select_animation、render_frame、undo、redo、finish_edit
完整列表请参阅 references/events.md。
自定义菜单
let menu = new Menu([
'existing_action_id',
myAction,
'_', // Separator
{
name: 'Custom Item',
icon: 'star',
click() { /* handle */ }
},
{
name: 'Submenu',
children: [ /* more items */ ]
}
]);
menu.open(event); // Open at mouse position
格式与编解码器(导入/导出)
const myCodec = new Codec('my_codec', {
name: 'My Format',
extension: 'mymodel',
compile(options) {
// Model → file content
let data = { bones: [] };
Group.all.forEach(g => {
data.bones.push({
name: g.name,
pivot: g.origin,
cubes: g.children.filter(c => c instanceof Cube).map(c => ({
from: c.from, to: c.to
}))
});
});
return JSON.stringify(data, null, 2);
},
parse(content, path) {
// File content → model
let data = JSON.parse(content);
newProject(myFormat);
data.bones.forEach(b => {
let group = new Group({ name: b.name, origin: b.pivot }).init();
b.cubes.forEach(c => {
new Cube({ from: c.from, to: c.to }).init().addTo(group);
});
});
Canvas.updateAll();
}
});
const myFormat = new ModelFormat('my_format', {
id: 'my_format',
name: 'My Format',
icon: 'icon_name',
codec: myCodec,
box_uv: true,
bone_rig: true,
animation_mode: true
});
// Cleanup
myFormat.delete();
myCodec.delete();
条件模式
// Function
condition: () => Format.id === 'bedrock' && Cube.selected.length > 0
// Object (combined with AND)
condition: {
formats: ['bedrock', 'java_block'],
modes: ['edit', 'paint'],
project: true,
selected: { cube: 1 },
method: () => customCheck()
}
代码风格约定
| 类型 | 约定 | 示例 |
|---|---|---|
| 类 | PascalCase | OutlinerElement、Animation |
| 方法 | camelCase | updateTransform、getSelectedFaces |
| 属性 | snake_case | data_points、uv_offset |
| 事件/操作 ID | snake_case | select_project、my_action |
关键清理模式
必须在 onunload() 中删除所有组件,以防止内存泄漏。
let action, panel, dialog, toolbar, format, codec, eventCallback, css;
Plugin.register('my_plugin', {
onload() {
action = new Action('id', { /* ... */ });
panel = new Panel('id', { /* ... */ });
format = new ModelFormat('id', { /* ... */ });
codec = new Codec('id', { /* ... */ });
eventCallback = (data) => { };
Blockbench.on('update_selection', eventCallback);
css = Blockbench.addCSS('.my-class { color: blue; }');
},
onunload() {
action.delete();
panel.delete();
format.delete();
codec.delete();
Blockbench.removeListener('update_selection', eventCallback);
css.delete();
}
});
反模式
// ❌ No stored reference = memory leak
onload() { new Action('leaked', { }); }
// ❌ No Undo = users can't reverse
Cube.selected.forEach(c => c.from[0] += 1);
// ❌ Bundling THREE.js (already global)
import * as THREE from 'three';
// ❌ Global pollution
window.myData = {};
内置库(请勿打包)
- THREE — Three.js 3D 渲染
- Vue — 宿主提供的响应式 UI;请匹配宿主支持的组件 API
- JSZip — ZIP 处理
- marked — Markdown 解析
- Molang — Molang 表达式解析器
图标
icon: 'star' // Material icon
icon: 'fa-bone' // Font Awesome
icon: 'icon-player' // Blockbench custom
icon: 'data:image/...' // Base64 image
TypeScript 设置
npm i --save-dev blockbench-types
/// <reference types="blockbench-types" />
模板文件
assets/plugin_template.js— 完整的插件起始模板assets/format_plugin.js— 自定义格式/编解码器示例
参考资料
- references/events.md — 事件参考;请在目标宿主中确认特定版本的事件
- references/api.md — 本地 API 示例
- references/elements.md — 元素类型和属性
- 创建插件 — 官方注册、生命周期和开发指南
- 生成的 API 参考 — 当前宿主类型和注释
请使用有代表性的项目验证插件修改:检查预期的数据/预览、撤销后重做,以及卸载/重新加载时的清理。对于格式/编解码器,请检查有代表性的导出和重新导入,包括 UV 尺寸、层级、名称、纹理引用,以及所支持的动画行为。编译通过并不能验证原生编辑器状态或序列化输出。