if selection.count == 0 then return の行でエラーが出る原因は、恐らく gw オブジェクトが初期化されていない ためです。
3ds Max の gw (Graphics Window) オブジェクトは、redrawViewsCallback 関数内では自動的に有効化されますが、グローバルスコープで直接 gw を使おうとするとエラーになります。
正しくは、gw は 常に redrawViewsCallback 関数内 で使う必要があります。
以下が修正版です:
-- 既存のコールバックを解除
try (unregisterRedrawViewsCallback ::drawHalfCircleInViewport) catch()
global drawHalfCircleInViewport
-- パラメータ用のグローバル構造体インスタンス
global halfCircleParams
struct HalfCircleParamsStruct (
circleColor,
radius,
segments
)
halfCircleParams = HalfCircleParamsStruct circleColor:(color 255 0 0) radius:20 segments:32
rollout halfCircleFloater "半円ビューポート描画" width:220 height:90
(
colorPicker cp_color "色" pos:[10,10] color:(color 255 0 0)
spinner spn_radius "半径" range:[1,100,20] pos:[120,10] width:80
spinner spn_segments "分割数" range:[3,100,32] pos:[10,40] width:80
button btn_update "更新" pos:[120,40] width:80
on cp_color changed c do (
halfCircleParams.circleColor = c
redrawViews()
)
on spn_radius changed val do (
halfCircleParams.radius = val
redrawViews()
)
on spn_segments changed val do (
halfCircleParams.segments = val
redrawViews()
)
on btn_update pressed do redrawViews()
)
fn drawHalfCircleInViewport =
(
-- この中で初めて gw が有効になる
local theGW = gw
-- 選択オブジェクトがない場合は処理を中断
if selection.count == 0 then (
theGW.setColor #line (color 255 255 255)
theGW.text [0,0,0] "オブジェクトを選択してください"
theGW.updateScreen()
return
)
local obj = selection[1]
local center = obj.objecttransform.pos
local r = halfCircleParams.radius
local segs = halfCircleParams.segments
local col = halfCircleParams.circleColor
-- 半円の弧上の頂点
local arcVerts = #()
for i = 0 to segs do (
local angle = 180.0 * i / segs
local rad = degToRad angle
append arcVerts (center + [cos rad * r, sin rad * r, 0])
)
theGW.setTransform (matrix3 1)
-- 塗りつぶし描画
theGW.setColor #fill col
for i = 1 to arcVerts.count - 1 do (
theGW.polygon #(center, arcVerts[i], arcVerts[i+1]) #()
)
-- 半円の輪郭線を描画
theGW.setColor #line (color 0 0 0)
theGW.polyline arcVerts false -- 弧の部分(閉じない)
theGW.polyline #(center, arcVerts[1]) false -- 中心から開始点
theGW.polyline #(center, arcVerts[arcVerts.count]) false -- 中心から終了点
-- オブジェクト位置にテキスト表示(デバッグ用)
theGW.text center ("R:" + r as string) color:(color 255 255 255)
-- 画面更新
theGW.updateScreen()
)
-- コールバックの登録とフロータの作成
unregisterRedrawViewsCallback ::drawHalfCircleInViewport
registerRedrawViewsCallback ::drawHalfCircleInViewport
createDialog halfCircleFloater
変更点:
-
local theGW = gw を関数内で宣言: これにより gw が有効なコンテキストで使えるようになる。
-
選択がない場合の処理を theGW で描画: 「オブジェクトを選択してください」と表示するように変更。
-
すべての gw を theGW に置き換え: ローカル変数で管理することで安定化。
これでエラーなく動くはずです。
確認ポイント:
- スクリプトを実行後、3ds Max のビューポート上で 何かしらのオブジェクトを選択 する。
- UIから半径・色・分割数を変更するとリアルタイムでビューポートが更新される。
もしまだエラーが出る場合は:
- 3ds Max を再起動
- スクリプトを 新規の MAXScript ファイル に貼り付けて実行
してみてください。