Cult3D 是早期網頁 3D 互動技術(類似現代 WebGL/Three.js),透過 Java Applet 在瀏覽器渲染 3D 模型。本文展示如何撰寫 Cult3D 腳本(Cult3DScript 介面),動態替換材質貼圖顏色。
import com.cult3d.*;
import com.cult3d.world.*;
import java.awt.Color;
import java.awt.Image;
import java.awt.Graphics;
public class ColorSwap implements Cult3DScript, Runnable {
// 目標材質名稱(需與 3D 模型中的貼圖名稱一致)
private static final String TEXTURE_NAME = "MADAROSE";
// 顏色陣列(RGB 值 0-255)
private Color red = new Color(198, 58, 41);
private Color blue = new Color(99, 93, 163);
private Color green = new Color(138, 149, 78);
private Color grey = new Color(136, 136, 136);
private Color lightBlue = new Color(121, 130, 173);
private Color black = new Color(64, 64, 64);
private Color[] colors = { red, blue, green, grey, lightBlue, black };
// 材質相關物件
private Texture texture;
private TextureImage textureImage;
private int textureWidth, textureHeight;
private Graphics graphics;
// 狀態旗標
private volatile boolean loaded = false;
private int colorCounter = 0;
// 建構子:啟動背景載入執行緒
public ColorSwap() {
Thread thread = new Thread(this);
thread.start();
}
// 背景執行緒:預載材質資源(避免阻塞 UI 執行緒)
public void run() {
texture = new Texture(TEXTURE_NAME);
textureWidth = texture.getWidth();
textureHeight = texture.getHeight();
textureImage = (TextureImage) Cult.createImage(textureWidth, textureHeight);
graphics = textureImage.getGraphics();
loaded = true; // 標記載入完成
}
// 公開方法:供 Designer/外部呼叫切換顏色
public void changeColor(String s) {
if (!loaded) {
System.out.println("Java 代碼尚未載入完成");
return;
}
// 循環切換顏色
if (colorCounter >= colors.length) colorCounter = 0;
switchColor(colors[colorCounter]);
colorCounter++;
}
// 核心:填滿材質圖片並套用
private void switchColor(Color color) {
graphics.setColor(color);
graphics.fillRect(0, 0, textureWidth, textureHeight);
texture.setTexture(textureImage); // 更新至 3D 引擎
}
// 生命週期:場景卸載時清理
public void cult3dDestroy() {
// 釋放資源邏輯
}
}
run() 在背景執行緒建立 Texture、Graphics,避免卡住主執行緒導致瀏覽器假死loaded 跨執行緒可見性TextureImage → Graphics.fillRect() 填色 → texture.setTexture() 熱替換colorCounter 取模陣列長度,實現無限循環切換ColorSwap.classchangeColor("")| 技術 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| Cult3D (Java Applet) | 早期成熟、工具鏈完整 | 需 Java 插件、瀏覽器已全面棄用、安全風險 | 舊系統維護 |
| Three.js (WebGL) | 原生瀏覽器支援、無插件、生態豐富、效能強 | 學習曲線較陡 | 現代 3D 網頁首選 |
| Babylon.js | TypeScript 優先、編輯器完善、PBR 材質 | 體積較大 | 企業級 3D 應用 |
| Model Viewer | 零代碼、AR 支援、Web Component | 客製化有限 | 簡單模型展示 |
// Three.js 動態變更材質顏色
const loader = new THREE.TextureLoader();
const texture = loader.load('madarose.jpg');
const material = new THREE.MeshStandardMaterial({ map: texture });
// 動態變色:直接修改材質顏色屬性
material.color.set(0xc63a29); // 紅色
// 或替換貼圖
material.map = loader.load('new_texture.jpg');
material.needsUpdate = true;