サブエージェントがサブエージェント呼び出すのね。初めてかも。

CATIA V5 VBAマクロ開発向け VSCode拡張8
こちらの続きです。
CATIA V5 VBAマクロ開発向け VSCode拡張7 - C#ATIA
牛歩と言う訳ではないのですが、実際に使って気になる部分を即改修と言う事です。
一部の END xxx 部分が正しいにもかかわらず警告する状態だったため、修正しました。
Release v0.7.2 · kantoku-code/Cat5Dev · GitHub
但し、汚い書き方(僕が書くやつ)の場合に出てしまっていた警告でしたが・・・
CATIA V5 VBAマクロ開発向け VSCode拡張7
こちらの続きです。
CATIA V5 VBAマクロ開発向け VSCode拡張6 - C#ATIA
機能的には大きな変化はないのですが、Pull/Push機能を変更しました。
実はVBScriptを使用していたのですが、将来を考えVBScript依存を解消したかったため
変更に取り組みました。
[備忘録] VBScript廃止とVBAへの影響まとめ #Windows - Qiita
機能変更では無いものの自分的には結構大きな変更です。
色々と調べているうちにCATScriptやSystemService.ExecuteScriptでも
vbscript.dllを利用していることが分かりました。少し意外です。
ご興味あれば、最新のvsix v0.7.1はこちらです。
Release v0.7.1 · kantoku-code/Cat5Dev · GitHub
entityTokenDump
選択した要素のEntityTokenをDumpするもので、役には立たないです。
しかもテキスト部分でエラーで止まると思います。
import base64 import gzip import re import traceback import adsk import adsk.core as core import adsk.fusion as fusion _app: core.Application = None _ui: core.UserInterface = None _handlers = [] _selected = None # entity chosen in the dialog (set on OK) CMD_INFO = { "id": "kantoku_entityTokenDump", "name": "EntityToken Dump", "tooltip": "Dump entityToken of selected entities", } def dump(msg: str): _app.log(msg) print(msg) def _decodeToken(token: str) -> bytes: """entityToken: base64 -> find gzip header -> decompress""" data = base64.b64decode(token + "=" * (-len(token) % 4)) start = data.find(b"\x1f\x8b") if start < 0: raise ValueError("gzip header not found") return gzip.decompress(data[start:]) def _dumpEntity(entity): dump(f"--- {entity.objectType.split('::')[-1]} ---") token = getattr(entity, "entityToken", None) if not token: dump("token : (none)") return dump(f"token : {token}") try: dump(f"decoded: {_decodeToken(token)!r}") except Exception as e: dump(f"decoded: (failed: {e})") # Text commands that take the token / entity id res = _txt(f"Design.FindEntityByToken {token}") m = re.search(r"entityId\D*(\d+)", res, re.I) or re.search(r"\d+", res) if m: entityId = m.group(1) if m.groups() else m.group(0) _txt(f"Entity.Dump {entityId}") _txt(f"Entity.DumpReferencingEntities {entityId}") _txt(f"Fusion.printEntityMetaInfo {entityId}") # Text commands that work on the current selection _ui.activeSelections.clear() _ui.activeSelections.add(entity) _txt("EntityTracking.ReferenceKey") if entity.objectType == fusion.Profile.classType(): _txt("Sketch.dumpProfileCurves") _txt("Sketch.DumpProfileEdgesAttribs") else: _txt("Sketch.DumpEntityProgression") def _txt(command: str) -> str: """Run a text command and dump its result""" dump(f"> {command}") try: res = _app.executeTextCommand(command) except Exception as e: res = f"(failed: {e})" dump(res) return res class MyCommandCreatedHandler(core.CommandCreatedEventHandler): def __init__(self): super().__init__() def notify(self, args: core.CommandCreatedEventArgs): try: global _handlers cmd: core.Command = core.Command.cast(args.command) inputs: core.CommandInputs = cmd.commandInputs onDestroy = MyCommandDestroyHandler() cmd.destroy.add(onDestroy) _handlers.append(onDestroy) onExecute = MyExecuteHandler() cmd.execute.add(onExecute) _handlers.append(onExecute) selIpt: core.SelectionCommandInput = inputs.addSelectionInput( "selIpt", "Entity", "Select an entity" ) selIpt.setSelectionLimits(1, 1) except: _ui.messageBox("Failed:\n{}".format(traceback.format_exc())) class MyExecuteHandler(core.CommandEventHandler): def __init__(self): super().__init__() def notify(self, args: core.CommandEventArgs): global _selected selIpt = core.SelectionCommandInput.cast( args.command.commandInputs.itemById("selIpt") ) _selected = selIpt.selection(0).entity class MyCommandDestroyHandler(core.CommandEventHandler): def __init__(self): super().__init__() def notify(self, args: core.CommandEventArgs): # Dump after the command has ended, so changing activeSelections is safe try: if _selected: _dumpEntity(_selected) except: _ui.messageBox("Failed:\n{}".format(traceback.format_exc())) adsk.terminate() def run(context): try: global _app, _ui _app = core.Application.get() _ui = _app.userInterface cmdDef: core.CommandDefinition = _ui.commandDefinitions.itemById(CMD_INFO["id"]) if not cmdDef: cmdDef = _ui.commandDefinitions.addButtonDefinition( CMD_INFO["id"], CMD_INFO["name"], CMD_INFO["tooltip"] ) global _handlers onCommandCreated = MyCommandCreatedHandler() cmdDef.commandCreated.add(onCommandCreated) _handlers.append(onCommandCreated) cmdDef.execute() adsk.autoTerminate(False) except: if _ui: _ui.messageBox("Failed:\n{}".format(traceback.format_exc()))
紛失しそうなのでメモです。
見えている面のみを選択する
Fusionです。思うところあってのテスト的なスクリプトです。
今Fusionで選択している面でこちらから見えている面のみを選択したい時有りますよね?
こんなデータで事前に選択します。左上から右下にドラッグで選択すると面が選択状態となります。

裏面はこんな感じで選択されています。

で、選択した状態でこちらのスクリプトを実行です。
# Fusion360API Python script # 窓選択した面のうち、画面上で見えている面だけを残す import time import traceback import adsk import adsk.core as core import adsk.fusion as fusion EPS: float = 0.001 # cm 自己ヒット回避のオフセット def run(context: dict) -> None: """スクリプトのエントリーポイント。 選択中の面それぞれについて可視判定を行い、 画面上で見えている面だけを選択状態として残す。 Args: context: Fusion から渡される実行コンテキスト(未使用)。 """ ui: core.UserInterface = None try: app: core.Application = core.Application.get() ui = app.userInterface des: fusion.Design = app.activeProduct root: fusion.Component = des.rootComponent # 選択中の面を取得 faces: list[fusion.BRepFace] = get_selected_faces() if len(faces) < 1: ui.messageBox("先に面を窓選択してから実行してください") return # カメラ情報(視点・視線方向・投影方式)を取得 cam: core.Camera = app.activeViewport.camera viewDir: core.Vector3D = cam.eye.vectorTo(cam.target) viewDir.normalize() camInfo: dict = { "eye": cam.eye, "viewDir": viewDir, "isOrtho": cam.cameraType == core.CameraTypes.OrthographicCameraType, } # 各面の可視判定を行い、見えている面だけを集める t0: float = time.perf_counter() counts: dict[str, int] = {"visible": 0, "hidden": 0, "back": 0, "occluded": 0} keep: list[fusion.BRepFace] = [] for face in faces: res: str = is_visible_face(face, camInfo, root) counts[res] += 1 if res == "visible": keep.append(face) elapsed: float = time.perf_counter() - t0 # 選択を可視面だけに置き換える sels: core.Selections = ui.activeSelections sels.clear() for face in keep: sels.add(face) # 結果を表示 ui.messageBox( "選択面: {} → 残り: {}\n".format(len(faces), len(keep)) + "除外 非表示: {} / 裏面: {} / 遮蔽: {}\n".format( counts["hidden"], counts["back"], counts["occluded"] ) + "処理時間: {:.3f} 秒".format(elapsed) ) except Exception: if ui: ui.messageBox("Failed:\n{}".format(traceback.format_exc())) def get_selected_faces() -> list[fusion.BRepFace]: """現在の選択から BRepFace だけを抽出して返す。 Returns: 選択中の BRepFace のリスト。面以外の選択要素は除外される。 """ app: core.Application = core.Application.get() sels: core.Selections = app.userInterface.activeSelections faces: list[fusion.BRepFace] = [] for i in range(sels.count): ent = sels.item(i).entity # 面以外(エッジ・ボディ等)は無視 if isinstance(ent, fusion.BRepFace): faces.append(ent) return faces def is_visible_face( face: fusion.BRepFace, camInfo: dict, root: fusion.Component, ) -> str: """面が画面上で見えているかを判定する。 判定順: ボディ非表示 → 裏面(ソリッドのみ) → 他形状による遮蔽。 面上の代表点 1 点からカメラ方向へレイを飛ばして遮蔽を調べる簡易判定。 Args: face: 判定対象の面。 camInfo: カメラ情報。キーは "eye"(視点 Point3D)、 "viewDir"(視線方向の単位 Vector3D)、"isOrtho"(平行投影か)。 root: レイキャストに使うルートコンポーネント。 Returns: "visible"(見えている) / "hidden"(ボディ非表示) / "back"(裏面) / "occluded"(他の面に遮蔽) のいずれか。 """ # ボディ自体が非表示なら対象外 body: fusion.BRepBody = face.body if not body.isVisible: return "hidden" # 代表点(面内保証)とカメラ方向 p: core.Point3D = face.pointOnFace eye: core.Point3D = camInfo["eye"] maxDist: float | None if camInfo["isOrtho"]: # 平行投影: 全点共通で視線の逆方向、距離制限なし toCam: core.Vector3D = camInfo["viewDir"].copy() toCam.scaleBy(-1) maxDist = None else: # 透視投影: 代表点から視点への方向、視点までの距離を上限とする toCam = p.vectorTo(eye) maxDist = toCam.length toCam.normalize() # 裏面判定(ソリッドのみ。シートは両面見える) if body.isSolid: ok: bool normal: core.Vector3D ok, normal = face.evaluator.getNormalAtPoint(p) if ok and normal.dotProduct(toCam) <= 0: return "back" # 遮蔽判定: 代表点からカメラ方向へレイ # 自分自身にヒットしないよう、始点をカメラ方向へ少しずらす offset: core.Vector3D = toCam.copy() offset.scaleBy(EPS) origin: core.Point3D = p.copy() origin.translateBy(offset) hitPoints: core.ObjectCollection = core.ObjectCollection.create() hits: core.ObjectCollection = root.findBRepUsingRay( origin, toCam, fusion.BRepEntityTypes.BRepFaceEntityType, -1, # 近接判定距離(-1 でデフォルト) True, # 非表示要素は無視 hitPoints, ) for i in range(hits.count): hit: fusion.BRepFace = hits.item(i) # 自分自身のヒットは無視 if is_same_face(hit, face): continue # 透視投影では視点より奥のヒットは無視 if maxDist is not None: if origin.distanceTo(hitPoints.item(i)) > maxDist: continue # 視点より後ろ # それ以外のヒットがあれば遮蔽されている return "occluded" return "visible" def is_same_face(a: fusion.BRepFace, b: fusion.BRepFace) -> bool: """2 つの面が同一かを判定する。 オブジェクト比較で一致しない場合は entityToken で比較する。 Args: a: 比較する面 1。 b: 比較する面 2。 Returns: 同一の面なら True。比較に失敗した場合は False。 """ try: if a == b: return True return a.entityToken == b.entityToken except Exception: return False
実行後です。1秒かからないですね。

裏面の見えていなかったところの選択は外れています。

もっと手間を省くのであれば、事前に面の選択をしないで
画面方向から見えているはずのすべての面を選択するバージョン
# Fusion360API Python script # 画面上で見えている面だけを選択する import time import traceback import adsk import adsk.core as core import adsk.fusion as fusion EPS: float = 0.001 # cm 自己ヒット回避のオフセット def run(context: dict) -> None: """スクリプトのエントリーポイント。 選択中の面それぞれについて可視判定を行い、 画面上で見えている面だけを選択状態として残す。 Args: context: Fusion から渡される実行コンテキスト(未使用)。 """ ui: core.UserInterface = None try: app: core.Application = core.Application.get() ui = app.userInterface des: fusion.Design = app.activeProduct root: fusion.Component = des.rootComponent # 表示されている全ての面を取得 faces: list[fusion.BRepFace] = get_all_faces(root) if len(faces) < 1: ui.messageBox("表示されている面がありません") return # カメラ情報(視点・視線方向・投影方式)を取得 cam: core.Camera = app.activeViewport.camera viewDir: core.Vector3D = cam.eye.vectorTo(cam.target) viewDir.normalize() camInfo: dict = { "eye": cam.eye, "viewDir": viewDir, "isOrtho": cam.cameraType == core.CameraTypes.OrthographicCameraType, } # 各面の可視判定を行い、見えている面だけを集める t0: float = time.perf_counter() counts: dict[str, int] = {"visible": 0, "hidden": 0, "back": 0, "occluded": 0} keep: list[fusion.BRepFace] = [] for face in faces: res: str = is_visible_face(face, camInfo, root) counts[res] += 1 if res == "visible": keep.append(face) elapsed: float = time.perf_counter() - t0 # 選択を可視面だけに置き換える sels: core.Selections = ui.activeSelections sels.clear() for face in keep: sels.add(face) # 結果を表示 ui.messageBox( "対象面: {} → 選択: {}\n".format(len(faces), len(keep)) + "除外 非表示: {} / 裏面: {} / 遮蔽: {}\n".format( counts["hidden"], counts["back"], counts["occluded"] ) + "処理時間: {:.3f} 秒".format(elapsed) ) except Exception: if ui: ui.messageBox("Failed:\n{}".format(traceback.format_exc())) def get_all_faces(root: fusion.Component) -> list[fusion.BRepFace]: """表示されている全ての面を取得して返す。 モデル全体のバウンディングボックスの中心から、対角線長を許容差として findBRepUsingPoint を実行し、全ての面を取得する。 Args: root: 検索に使うルートコンポーネント。 Returns: 表示されている BRepFace のリスト。 """ bb: core.BoundingBox3D = root.boundingBox minP: core.Point3D = bb.minPoint maxP: core.Point3D = bb.maxPoint center: core.Point3D = core.Point3D.create( (minP.x + maxP.x) * 0.5, (minP.y + maxP.y) * 0.5, (minP.z + maxP.z) * 0.5, ) tol: float = minP.distanceTo(maxP) # 対角線長(全体を包む) res: core.ObjectCollection = root.findBRepUsingPoint( center, fusion.BRepEntityTypes.BRepFaceEntityType, tol, True, # 表示されている要素のみ ) return [res.item(i) for i in range(res.count)] def is_visible_face( face: fusion.BRepFace, camInfo: dict, root: fusion.Component, ) -> str: """面が画面上で見えているかを判定する。 判定順: ボディ非表示 → 裏面(ソリッドのみ) → 他形状による遮蔽。 面上の代表点 1 点からカメラ方向へレイを飛ばして遮蔽を調べる簡易判定。 Args: face: 判定対象の面。 camInfo: カメラ情報。キーは "eye"(視点 Point3D)、 "viewDir"(視線方向の単位 Vector3D)、"isOrtho"(平行投影か)。 root: レイキャストに使うルートコンポーネント。 Returns: "visible"(見えている) / "hidden"(ボディ非表示) / "back"(裏面) / "occluded"(他の面に遮蔽) のいずれか。 """ # ボディ自体が非表示なら対象外 body: fusion.BRepBody = face.body if not body.isVisible: return "hidden" # 代表点(面内保証)とカメラ方向 p: core.Point3D = face.pointOnFace eye: core.Point3D = camInfo["eye"] maxDist: float | None if camInfo["isOrtho"]: # 平行投影: 全点共通で視線の逆方向、距離制限なし toCam: core.Vector3D = camInfo["viewDir"].copy() toCam.scaleBy(-1) maxDist = None else: # 透視投影: 代表点から視点への方向、視点までの距離を上限とする toCam = p.vectorTo(eye) maxDist = toCam.length toCam.normalize() # 裏面判定(ソリッドのみ。シートは両面見える) if body.isSolid: ok: bool normal: core.Vector3D ok, normal = face.evaluator.getNormalAtPoint(p) if ok and normal.dotProduct(toCam) <= 0: return "back" # 遮蔽判定: 代表点からカメラ方向へレイ # 自分自身にヒットしないよう、始点をカメラ方向へ少しずらす offset: core.Vector3D = toCam.copy() offset.scaleBy(EPS) origin: core.Point3D = p.copy() origin.translateBy(offset) hitPoints: core.ObjectCollection = core.ObjectCollection.create() hits: core.ObjectCollection = root.findBRepUsingRay( origin, toCam, fusion.BRepEntityTypes.BRepFaceEntityType, -1, # 近接判定距離(-1 でデフォルト) True, # 非表示要素は無視 hitPoints, ) for i in range(hits.count): hit: fusion.BRepFace = hits.item(i) # 自分自身のヒットは無視 if is_same_face(hit, face): continue # 透視投影では視点より奥のヒットは無視 if maxDist is not None: if origin.distanceTo(hitPoints.item(i)) > maxDist: continue # 視点より後ろ # それ以外のヒットがあれば遮蔽されている return "occluded" return "visible" def is_same_face(a: fusion.BRepFace, b: fusion.BRepFace) -> bool: """2 つの面が同一かを判定する。 オブジェクト比較で一致しない場合は entityToken で比較する。 Args: a: 比較する面 1。 b: 比較する面 2。 Returns: 同一の面なら True。比較に失敗した場合は False。 """ try: if a == b: return True return a.entityToken == b.entityToken except Exception: return False
早いんですよ・・・処理が・・・とても
CATIA V5 VBAマクロ開発向け VSCode拡張6
こちらの続きです。
CATIA V5 VBAマクロ開発向け VSCode拡張5 - C#ATIA
先日の日曜日は朝から晩までクソ忙しいものすごく忙しい予定だったのですが、
複数の予定がキャンセルとなり時間が出来たので、日頃使いにくい部分を思い切って
改修に取り組みました。
(前回の約半年前だったので、そこからのAIの進化が凄まじい事を実感しています。)
GitHub - kantoku-code/Cat5Dev: Cat5Dev is a VSCode extension that syncs VBA modules between VSCode and CATIA V5. · GitHub
長い間放置して申し訳なかったのですが、中国語サポートのPRが入っていたので、そちらを
取り込みました。v0.4.0 -> v0.6.7へ一気に上げてますが、一番不便だと感じていたインテリセンスの強化が
一番大きいと感じてます。VSCodeでの開発を目的にしていたにも関わらず、ここが
貧弱過ぎたので、実質開発出来ない状態でした。不便ないぐらいの性能にはなっているはず。
もう一つ不便に感じていたのが、パンくずリストの表示がソートされていなかった部分ですが、
こちらもソートした状態での表示に出来る設定を追加したので、関数が探しやすくなりました。
Lintやフォーマッタはまだ評価しきれていないものの、Push/Pullは問題無いです。
(Pushは開発当初から不安定で、出来れば変更したくない・・・)
Pushも以前に比べて送り込む量を減らしているので処理も早くなってます。
細かな部分では、ホバーするだけでちょっとした情報も表示するので、VBAエディタより
リッチな機能も付いているので、VSCodeでもある程度開発出来る可能性が見えてきました。

最新版の.vsixファイルのダウンロードはこちらから
Release v0.6.8 · kantoku-code/Cat5Dev · GitHub
CATPartパーサー
Githubを見ていたのですが、これ本当かな・・
GitHub - MadManJohnSmith/catpart-parser: Open-source parser for the CATIA V5 .CATPart/.CATProduct binary format - reads files without a CATIA installation · GitHub
始まったばかりの様ですし、試してもいないのですが、本当にこれが可能なのであれば
ファイル内の情報取得がCATIA無しで可能になる事を意味していますよね?
凄いのではないかな?
こちらもすごいですね。
GitHub - wind1022-cmd/catiarecon: Rebuild a history-less STEP solid in CATIA V5 as a part with history, driven by an LLM (experimental) · GitHub
実験とはなっているので継続的に取り組むか分からないのですが、
実現すれば面白そうです。
Fusionには既になりますが。