筆者早年涉獵三維動畫製作,後轉向 PHP 開發,發現 PHP 其實可以像 Macromedia Generator 動態生成 Flash 一樣,動態輸出 VRML (Virtual Reality Modeling Language) 場景描述檔案。VRML 規格雖然龐大複雜,但若能將各類 VRML 節點存入資料庫,便能構建出動態互動的虛擬實境網頁,極具發展潛力。
在伺服器端務必設定讓 PHP 解析 .wrl 副檔名,否則瀏覽器將無法正確識別 VRML 內容。本範例直接輸出 VRML 字串,瀏覽器需安裝相應外掛(如 Cortona3D Viewer)才能檢視。外掛可至筆者主頁下載:https://go.163.com/~sjtucaocao/
<?php
header("Content-type: application/x-vrml");
$txt = "#VRML V2.0 utf8
DEF leftBox Transform {
translation -5 0 0
children [
Shape {
appearance Appearance {
material Material { diffuseColor 1 0 0 }
}
geometry Box {}
}
DEF SphereChild Shape {
appearance Appearance {
material Material { diffuseColor 1 0 1 }
}
geometry Sphere { radius 1.2 }
}
]
}
DEF rightBox Transform {
translation 5 0 0
children [
Shape {
appearance Appearance {
material Material { diffuseColor 0 0 1 }
}
geometry Box {}
}
]
}
DEF onoff Transform {
translation 0 -1 0
children [
Shape {
appearance Appearance {
material Material { diffuseColor 0 1 0 }
}
geometry Box {}
DEF TS TouchSensor {}
}
]
}
DEF S Script {
eventIn SFBool isActive
eventOut MFNode child
field MFNode testNode USE SphereChild
url \"javascript:
function isActive(value) {
if (value) { child = testNode; }
}
\"
}
ROUTE TS.isActive TO S.isActive
ROUTE S.child TO leftBox.removeChildren
ROUTE S.child TO rightBox.addChildren\";
echo $txt;
?>
leftBox, rightBox) 分別包含紅色方塊與藍色方塊,左側另含一個洋紅色球體 (SphereChild)。onoff) 綁定 TouchSensor,點擊時產生 isActive 事件。value 為真,將 SphereChild 節點輸出至 child 欄位。leftBox.removeChildren (移除球體) 與 rightBox.addChildren (新增球體),實現球體在兩側箱子間「傳送」的視覺效果。若將材質、座標、幾何體參數等存入 MySQL/PostgreSQL,配合 PHP 動態組裝 VRML 字串,即可建構:
雖然 WebGL/X3D 已逐漸取代 VRML,但「伺服端動態生成場景描述」的架構思維在現代 WebXR、glTF 動態載入場景中依然適用。