Files
window-axis-innovators-box/vivid2DApi.md
tzdwindows 7 9cde0192fd feat(render): 添加光源与物理系统支持
- 新增 BufferBuilder 工具类用于简化顶点数据提交
- 实现 LightSource 和 LightSourceData 类以支持光源管理- 在 Model2D 中集成光源系统,支持序列化与反序列化
- 扩展 ModelData 以支持物理系统数据的完整序列化
- 重构 ModelRender以支持物理系统应用及碰撞箱渲染
- 添加粒子、弹簧、约束与碰撞体的数据结构与序列化逻辑
- 实现变形器的序列化接口以支持参数驱动动画的持久化
2025-10-11 20:21:11 +08:00

6.6 KiB

🎯 vivid2D 核心操作方法

1. 模型创建与基础设置

// 创建新模型
Model2D model = new Model2D("character_name");
model.setVersion("1.0.0");

// 设置元数据
ModelMetadata metadata = model.getMetadata();
metadata.setAuthor("Your Name");
metadata.setDescription("Character model");

2. 部件层级管理

// 创建部件
ModelPart body = model.createPart("body");
ModelPart head = model.createPart("head");
ModelPart leftArm = model.createPart("left_arm");
ModelPart rightArm = model.createPart("right_arm");

// 建立层级关系
body.addChild(head);
body.addChild(leftArm);
body.addChild(rightArm);

// 设置部件变换
body.setPosition(0, 0);
head.setPosition(0, -50); // 头部相对身体的位置
leftArm.setPosition(-30, 0);
rightArm.setPosition(30, 0);

// 设置旋转和缩放
head.setRotation(15.0f); // 角度制
body.setScale(1.2f, 1.0f);

3. 网格系统操作

// 创建基本形状网格
Mesh2D bodyMesh = Mesh2D.createQuad("body_mesh", 40, 80);
Mesh2D headMesh = Mesh2D.createQuad("head_mesh", 50, 50);
Mesh2D armMesh = Mesh2D.createQuad("arm_mesh", 20, 60);

// 添加网格到模型和部件
model.addMesh(bodyMesh);
model.addMesh(headMesh);
body.addMesh(bodyMesh);
head.addMesh(headMesh);
leftArm.addMesh(armMesh);
rightArm.addMesh(armMesh);

// 自定义网格数据
float[] vertices = { /* 顶点数据 */ };
float[] uvs = { /* UV坐标 */ };
int[] indices = { /* 索引数据 */ };
Mesh2D customMesh = model.createMesh("custom_mesh", vertices, uvs, indices);

4. 纹理管理系统

// 创建纹理
Texture bodyTexture = Texture.createSolidColor("body_tex", 64, 64, 0xFFFF0000); // 红色
Texture headTexture = Texture.createSolidColor("head_tex", 64, 64, 0xFF00FF00); // 绿色

// 创建棋盘格纹理
Texture checkerTexture = Texture.createCheckerboard(
    "checker_tex", 128, 128, 16, 0xFFFFFFFF, 0xFF0000FF
);

// 关键:确保纹理数据缓存(序列化必需)
bodyTexture.ensurePixelDataCached();
headTexture.ensurePixelDataCached();

// 添加纹理到模型
model.addTexture(bodyTexture);
model.addTexture(headTexture);
model.addTexture(checkerTexture);

// 为网格分配纹理
bodyMesh.setTexture(bodyTexture);
headMesh.setTexture(headTexture);

5. 动画参数驱动系统

// 创建动画参数
AnimationParameter smileParam = model.createParameter("smile", 0, 1, 0);
AnimationParameter blinkParam = model.createParameter("blink", 0, 1, 0);
AnimationParameter walkParam = model.createParameter("walk_cycle", 0, 1, 0);

// 设置参数值
model.setParameterValue("smile", 0.8f);
model.setParameterValue("blink", 1.0f);

// 获取参数值
float currentSmile = model.getParameterValue("smile");

// 动画循环示例
for (int frame = 0; frame < 60; frame++) {
    float walkValue = (float) Math.sin(frame * 0.1f) * 0.5f + 0.5f;
    model.setParameterValue("walk_cycle", walkValue);
    model.update(0.016f); // 60fps
}

6. 动画层系统

// 创建动画层
AnimationLayer baseLayer = model.createAnimationLayer("base_animation");
AnimationLayer facialLayer = model.createAnimationLayer("facial_animation");

// 设置动画层属性
baseLayer.setWeight(1.0f);
facialLayer.setWeight(0.8f);

7. 物理系统集成

// 获取物理系统
PhysicsSystem physics = model.getPhysics();

// 配置物理环境
physics.setGravity(new Vector2f(0, -9.8f));
physics.setAirResistance(0.1f);
physics.setTimeScale(1.0f);
physics.setEnabled(true);

// 初始化物理系统
physics.initialize();

// 添加物理粒子
PhysicsSystem.PhysicsParticle particle1 = physics.addParticle(
    "particle1", new Vector2f(0, 0), 1.0f
);
PhysicsSystem.PhysicsParticle particle2 = physics.addParticle(
    "particle2", new Vector2f(10, 0), 1.0f
);

// 添加弹簧连接
physics.addSpring("spring1", particle1, particle2, 15.0f, 0.5f, 0.1f);

8. 模型更新与状态管理

// 手动标记需要更新
model.markNeedsUpdate();

// 更新模型状态(通常在游戏循环中调用)
model.update(deltaTime);

// 控制可见性
model.setVisible(true);
boolean isVisible = model.isVisible();

// 获取当前姿势
ModelPose currentPose = model.getCurrentPose();

// 获取包围盒
BoundingBox bounds = model.getBounds();
if (bounds != null) {
    float width = bounds.getWidth();
    float height = bounds.getHeight();
}

9. 序列化与文件操作

// 保存到普通文件
model.saveToFile("character.model");

// 保存到压缩文件
model.saveToCompressedFile("character.model.gz");

// 从文件加载
Model2D loadedModel = Model2D.loadFromFile("character.model");

// 从压缩文件加载
Model2D compressedModel = Model2D.loadFromCompressedFile("character.model.gz");

10. 高级操作技巧

// 遍历部件层级
private void traverseHierarchy(ModelPart part, int depth) {
    String indent = "  ".repeat(depth);
    System.out.println(indent + part.getName());
    
    for (ModelPart child : part.getChildren()) {
        traverseHierarchy(child, depth + 1);
    }
}

// 查找特定部件
ModelPart findPartRecursive(ModelPart part, String name) {
    if (part.getName().equals(name)) {
        return part;
    }
    for (ModelPart child : part.getChildren()) {
        ModelPart found = findPartRecursive(child, name);
        if (found != null) {
            return found;
        }
    }
    return null;
}

// 批量设置参数
public void setMultipleParameters(Model2D model, Map<String, Float> paramValues) {
    for (Map.Entry<String, Float> entry : paramValues.entrySet()) {
        model.setParameterValue(entry.getKey(), entry.getValue());
    }
    model.markNeedsUpdate();
}

11. 性能优化建议

// 批量更新参数后再调用更新
public void efficientUpdate(Model2D model, float deltaTime) {
    if (!model.needsUpdate && !model.getPhysics().hasActivePhysics()) {
        return;
    }
    model.update(deltaTime);
}

// 重用模型实例
public class ModelManager {
    private Map<String, Model2D> modelCache = new HashMap<>();
    
    public Model2D getModel(String filePath) {
        return modelCache.computeIfAbsent(filePath, 
            path -> Model2D.loadFromFile(path));
    }
}

12. 错误处理最佳实践

try {
    // 模型操作
    Model2D model = Model2D.loadFromFile("character.model");
    model.setParameterValue("smile", 0.5f);
    model.update(0.016f);
    
} catch (Exception e) {
    System.err.println("模型操作失败: " + e.getMessage());
    e.printStackTrace();
}

这套操作方法涵盖了 vivid2D 的核心功能,从基础模型创建到高级动画和物理系统,帮助您快速上手并有效使用这个 2D 渲染引擎。