[PR #6] feat: feat: experimental multithreading #6

Open
opened 2026-10-14 09:52:34 +00:00 by allankoech · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/pull/6
Author: @allankoechke
Created: 7/21/2026
Status: 🔄 Open

Base: master ← Head: 5-experimental-multithreading


📝 Commits (5)

  • 70992df feat: begin implementation for #5
  • b1c62cb feat: disable scene redraws during explode loop
  • 353ad28 feat: suppress per-face undo entries during explode loop
  • 5dad8b8 feat: throttle processEvents() to every 20 faces during explode loop
  • 4f267e6 feat: refactor MNMesh path to read-then-create pattern

📊 Changes

2 files changed (+154 additions, -110 deletions)

View changed files

📝 Bundle2/Contents/python/explode_geometry.py (+77 -55)
📝 Python/explode_geometry.py (+77 -55)

📄 Description

Closes #5

Explode Geometry Performance Optimization Implementation Plan

Overview

Research confirmed that pymxs.runtime calls cannot be made from background threads — 3ds Max is single-threaded for all scene graph operations. "Multithreading" is therefore implemented as a set of main-thread performance optimizations: disabling scene redraws during the face loop, suppressing per-face undo recording, throttling the Qt event-loop pump, and restructuring the MNMesh path to eliminate an inherent sequential index-shifting dependency. Both Python/explode_geometry.py and Bundle2/Contents/python/explode_geometry.py are identical and both require the same changes.

Current State Analysis

Key Discoveries:

  • Scene redraws are NOT suppressed during the inner face loop — each rt.mesh(), rt.addModifier(), and rt.maxOps.collapseNode() triggers a viewport update per face (Python/explode_geometry.py:261-296)
  • QApplication.processEvents() is called once per face via _prog(), adding Qt event-loop overhead on every iteration (Python/explode_geometry.py:257-259)
  • The outer with pymxs.undo(True, "Explode Geometry"): exists but individual per-face calls still record internal undo data, adding overhead (Python/explode_geometry.py:261)
  • The MNMesh path uses polyop.detachFaces which mutates the source mesh per call and shifts face indices, forcing a reverse-order sequential loop (Python/explode_geometry.py:360-362)
  • rt.redrawViews() is already called once after the loop (Python/explode_geometry.py:296) — viewport state is recoverable if redraws are suppressed during the loop
  • Bundle2/Contents/python/explode_geometry.py is identical to Python/explode_geometry.py and needs the same changes

Desired End State

The explode operation on large meshes (100+ faces) completes measurably faster. The viewport does not flicker per-face during the operation. A single Ctrl+Z reverts the entire explode. The progress bar updates at reasonable intervals (~every 20 faces). All existing functionality (Shell modifier, Edit Mesh, collapse stack, center pivot, delete original, TriMesh/MNMesh modes) is preserved and produces identical geometry output.

Verification: Run explode on a 500+ face mesh with Shell + Collapse Stack enabled. Record the elapsed time printed to the MAXScript Listener. Compare to the pre-patch baseline on the same mesh.

What We're NOT Doing

  • No threading.Thread, concurrent.futures.ThreadPoolExecutor, or multiprocessing for pymxs calls (confirmed impossible per Autodesk documentation)
  • No pymxs.mxstoken() usage (deprecated, non-functional)
  • No Qt worker threads that call back into pymxs (deadlock risk)
  • No changes to the UI layout or any feature set
  • No changes to Python/explode_geometry_classic.py (MaxPlus-based, legacy/unsupported since 3ds Max 2022)

Implementation Approach

Implement the four ranked optimizations from the research in priority order. Tasks 1 and 2 (redraw suppression + undo suppression) are the highest-impact changes. Task 3 (processEvents throttle) is a quick secondary improvement. Task 4 (MNMesh refactor) eliminates an algorithmic sequential dependency. All changes are applied to both script files.


IMPORTANT: Checkboxes are for implementation steps only. Steps requiring manual human verification are in the numbered "Manual Testing Steps" section at the bottom.

TASK 1: Disable Scene Redraws During the Explode Loop [HIGH PRIORITY]

Status: DONE
Milestone: The 3ds Max viewport no longer updates per-face during explode; a single rt.redrawViews() fires once at the end.

  • Confirm rt.disableSceneRedraw() and rt.enableSceneRedraw() are accessible via pymxs.runtime (test in MAXScript Listener: python.execute "import pymxs; pymxs.runtime.disableSceneRedraw()")
  • If direct pymxs access fails, use rt.execute("disableSceneRedraw()") and rt.execute("enableSceneRedraw()") as fallback
  • In do_explode() in Python/explode_geometry.py, add rt.disableSceneRedraw() immediately before the with pymxs.undo(True, "Explode Geometry"): block (before line 261)
  • Wrap the undo block in a try/finally that calls rt.enableSceneRedraw() then rt.redrawViews() in the finally clause
  • Remove the standalone rt.redrawViews() at line 296 since it is now inside the finally block
  • Apply the identical structural change to Bundle2/Contents/python/explode_geometry.py

Validation: Run explode on a 200+ face mesh. Viewport must not flicker per-face. rt.redrawViews() fires once at completion. MAXScript Listener shows lower elapsed time vs pre-patch baseline.

Requirements from spec:

  • All scene operations remain on the main thread
  • Viewport must be fully refreshed (redraws re-enabled + rt.redrawViews()) after explode completes

Files to Modify:

  • Python/explode_geometry.py — do_explode() method (~line 261)
  • Bundle2/Contents/python/explode_geometry.py — identical change

Implementation Details:

rt.disableSceneRedraw()
try:
    with pymxs.undo(True, "Explode Geometry"):
        if self.trimesh_option.isChecked():
            ...  # existing TriMesh loop
        if self.mnmesh_option.isChecked():
            ...  # existing MNMesh loop
finally:
    rt.enableSceneRedraw()
    rt.redrawViews()

TASK 2: Suppress Per-Face Undo Entries [HIGH PRIORITY]

Status: DONE
Milestone: The undo stack shows a single "Explode Geometry" entry; per-face undo recording overhead is eliminated.

  • In convert_to_triangle_faces() in Python/explode_geometry.py (lines 330-347), wrap the per-face block (rt.mesh(...) through applySettings(...)) in with pymxs.undo(False):
  • In convert_to_mnmesh_faces() in Python/explode_geometry.py (lines 360-372), wrap the per-face block (rt.polyop.detachFaces(...) through applySettings(...)) in with pymxs.undo(False):
  • Keep the outer with pymxs.undo(True, "Explode Geometry"): in do_explode() intact — it provides the single undo group entry
  • Apply the same changes to Bundle2/Contents/python/explode_geometry.py

Validation: Explode a 50+ face mesh. Press Ctrl+Z once. The entire explode operation (all created nodes removed, original restored) must be undone in a single step. The Edit menu undo history must show exactly one "Explode Geometry" entry.

Requirements from spec:

  • The whole explode must be reversible with a single undo
  • Nesting with pymxs.undo(False): inside with pymxs.undo(True, ...): must correctly scope undo to the outer block (test this before committing)

Files to Modify:

  • Python/explode_geometry.py — convert_to_triangle_faces() (~lines 330-347) and convert_to_mnmesh_faces() (~lines 360-372)
  • Bundle2/Contents/python/explode_geometry.py — same changes

Implementation Details:

In convert_to_triangle_faces:

for face_idx in range(1, num_faces + 1):
    face = rt.getFace(node, face_idx)
    v1 = rt.getVert(node, int(face.x))
    v2 = rt.getVert(node, int(face.y))
    v3 = rt.getVert(node, int(face.z))
    with pymxs.undo(False):
        new_node = rt.mesh(vertices=rt.Array(v1, v2, v3),
                           faces=rt.Array(rt.Point3(1, 2, 3)))
        rt.update(new_node)
        new_node.wireColor = _random_wire_color()
        applySettings(new_node, addShell, shell_amount, addEditMesh, collapseNode, centerPivot)
    if on_progress:
        on_progress(face_idx, num_faces)

TASK 3: Throttle processEvents() to Every N Faces [MEDIUM PRIORITY]

Status: DONE
Milestone: Qt event-loop pump overhead is reduced from O(faces) to O(faces/20) while the progress bar remains responsive.

  • In do_explode() in Python/explode_geometry.py, update the _prog() inner function (lines 257-259) to only call QtWidgets.QApplication.processEvents() when cur % 20 == 0 or cur == tot
  • Keep self.progress_bar.setValue(...) updating every call — it is cheap and ensures accurate display when processEvents() does fire
  • Keep the existing QtWidgets.QApplication.processEvents() at line 254 (after showing the progress panel) unchanged — that call is outside the hot path
  • Apply the same change to Bundle2/Contents/python/explode_geometry.py

Validation: On a 200-face mesh, the progress bar must advance in visible steps (~10% increments). The UI must remain responsive (window can be moved, not frozen). No single progress jump exceeds ~20% in one tick.

Requirements from spec:

  • Progress bar must remain visually responsive during long operations
  • Throttle interval of 20 faces is a starting point; adjust between 10-50 based on testing

Files to Modify:

  • Python/explode_geometry.py — _prog() inner function inside do_explode() (~lines 257-259)
  • Bundle2/Contents/python/explode_geometry.py — same change

Implementation Details:

def _prog(cur, tot):
    self.progress_bar.setValue(int(cur * 100 / tot) if tot else 0)
    if cur % 20 == 0 or cur == tot:
        QtWidgets.QApplication.processEvents()

TASK 4: Refactor MNMesh Path to Read-Then-Create Pattern [MEDIUM PRIORITY]

Status: DONE
Milestone: convert_to_mnmesh_faces() no longer uses polyop.detachFaces. All vertex data is read in Phase 1 before any node is created in Phase 2, removing the index-shifting sequential dependency.

  • Add a new helper function _create_poly_node_from_positions(positions) to Python/explode_geometry.py (after _random_wire_color). It must: create a new PolyMeshObject node via rt.newObjectNode(rt.PolyMeshObject()), call rt.polyop.setNumVerts, rt.polyop.setVert for each position, then rt.polyop.createFace with a 1-based index array
  • If rt.newObjectNode or rt.PolyMeshObject are not accessible in pymxs, use rt.execute("newObjectNode (PolyMeshObject())") and retrieve the node via rt.objects[-1]
  • Refactor convert_to_mnmesh_faces() in Python/explode_geometry.py (lines 351-373): Phase 1 iterates range(1, num_faces + 1) (forward order), calls rt.polyop.getFaceVerts and rt.polyop.getVert for each vertex, stores results as plain Python (x, y, z) tuples — retains no pymxs objects after this phase
  • Phase 2 iterates the plain Python list, calls _create_poly_node_from_positions(positions) per face, sets wireColor, calls applySettings
  • Remove the reverse iteration range(num_faces, 0, -1) from convert_to_mnmesh_faces — forward order is correct since Phase 1 does not mutate the source
  • Verify that rt.delete(node) (the deleteOriginal path in do_explode()) is called only after both phases complete, since Phase 1 reads from the source mesh
  • Apply the same changes to Bundle2/Contents/python/explode_geometry.py

Validation: Explode a quad-face plane in MNMesh mode. Each resulting node must be a single-face Editable Poly with correct vertex positions (check in modifier panel). Explode a pentagon (5-vert n-gon) to confirm n-gon topology is preserved, not triangulated.

Requirements from spec:

  • Polygon topology (quads, n-gons) must be preserved — do not triangulate faces
  • Vertex positions must match the source mesh exactly
  • Source mesh must not be mutated during Phase 1

Files to Modify:

  • Python/explode_geometry.py — add _create_poly_node_from_positions() helper; refactor convert_to_mnmesh_faces() (~lines 351-373)
  • Bundle2/Contents/python/explode_geometry.py — same changes

Implementation Details:

Phase 1 (read, no mutation):

rt.convertToPoly(node)
num_faces = rt.polyop.getNumFaces(node)
face_data = []
for face_idx in range(1, num_faces + 1):
    verts = rt.polyop.getFaceVerts(node, face_idx)
    positions = [(rt.polyop.getVert(node, int(v)).x,
                  rt.polyop.getVert(node, int(v)).y,
                  rt.polyop.getVert(node, int(v)).z) for v in verts]
    face_data.append(positions)

Phase 2 (create from plain Python data):

for i, positions in enumerate(face_data, 1):
    with pymxs.undo(False):
        new_node = _create_poly_node_from_positions(positions)
        new_node.wireColor = _random_wire_color()
        applySettings(new_node, addShell, shell_amount, addEditMesh, collapseNode, centerPivot)
    if on_progress:
        on_progress(i, num_faces)

Helper function:

def _create_poly_node_from_positions(positions):
    n = len(positions)
    node = rt.newObjectNode(rt.PolyMeshObject())
    rt.polyop.setNumVerts(node, n)
    for i, (x, y, z) in enumerate(positions, 1):
        rt.polyop.setVert(node, i, rt.Point3(x, y, z))
    rt.polyop.createFace(node, rt.Array(*range(1, n + 1)))
    return node

Assumption: rt.newObjectNode and rt.PolyMeshObject are available as pymxs runtime calls. If not, fall back to rt.execute(...) and rt.objects[-1].


Testing Strategy

Unit Tests:

  • No standalone unit test framework exists in this project (3ds Max plugin context)
  • Correctness is verified by comparing geometry output against the pre-patch baseline

Integration Tests:

  • Run TriMesh explode on a Box primitive (12 triangles) — verify exactly 12 TriMesh face nodes are created
  • Run MNMesh explode on a Plane primitive (quad faces) — verify N single-face Editable Poly nodes are created
  • Run MNMesh explode on an n-gon face — verify face topology is preserved (not triangulated)
  • Confirm single undo entry reverts entire operation

Manual Testing Steps:

  1. Open 3ds Max, load Python/explode_geometry.py, create a GeoSphere with 100+ faces
  2. Record baseline elapsed time from the MAXScript Listener before patching
  3. Apply Task 1 patch; repeat the same explode and compare elapsed time — viewport must not flicker
  4. Apply Task 2 patch; press Ctrl+Z once after explode — verify full operation is undone in a single step
  5. Apply Task 3 patch; run explode on a 200+ face mesh — verify progress bar advances in steps of ~20 faces
  6. Apply Task 4 patch; run MNMesh explode on a quad plane — open modifier panel on a resulting node and verify vertex coordinates match the original face
  7. Test the most expensive path end-to-end: Shell modifier enabled + Collapse Stack enabled on a 500+ face mesh — confirm elapsed time improvement and no crashes

Performance Considerations

  • Tasks 1 + 2 combined are estimated at 2–5x speedup on large meshes based on research; viewport redraw suppression is the single largest contributor
  • Task 3 impact is proportional to mesh size; most noticeable on 500+ face objects
  • Task 4 restructures the MNMesh algorithm but does not reduce O(n) complexity; gains come from eliminating the detachFaces per-call overhead and removing the reverse-iteration constraint

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/pull/6 **Author:** [@allankoechke](https://github.com/allankoechke) **Created:** 7/21/2026 **Status:** 🔄 Open **Base:** `master` ← **Head:** `5-experimental-multithreading` --- ### 📝 Commits (5) - [`70992df`](https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/commit/70992dfa56e93c82bb7feaba961a70982aa191e1) feat: begin implementation for #5 - [`b1c62cb`](https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/commit/b1c62cb28d1763e62999f72066b4d404230c5938) feat: disable scene redraws during explode loop - [`353ad28`](https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/commit/353ad28c15ce47bcecb41e3f415de720162fb5bc) feat: suppress per-face undo entries during explode loop - [`5dad8b8`](https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/commit/5dad8b8ddb1857814a5763e71f99b856ae354f84) feat: throttle processEvents() to every 20 faces during explode loop - [`4f267e6`](https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/commit/4f267e654ac05aedad23957a106fd2ef870f40e1) feat: refactor MNMesh path to read-then-create pattern ### 📊 Changes **2 files changed** (+154 additions, -110 deletions) <details> <summary>View changed files</summary> 📝 `Bundle2/Contents/python/explode_geometry.py` (+77 -55) 📝 `Python/explode_geometry.py` (+77 -55) </details> ### 📄 Description Closes #5 # Explode Geometry Performance Optimization Implementation Plan ## Overview Research confirmed that `pymxs.runtime` calls cannot be made from background threads — 3ds Max is single-threaded for all scene graph operations. "Multithreading" is therefore implemented as a set of main-thread performance optimizations: disabling scene redraws during the face loop, suppressing per-face undo recording, throttling the Qt event-loop pump, and restructuring the MNMesh path to eliminate an inherent sequential index-shifting dependency. Both `Python/explode_geometry.py` and `Bundle2/Contents/python/explode_geometry.py` are identical and both require the same changes. ## Current State Analysis ### Key Discoveries: - Scene redraws are NOT suppressed during the inner face loop — each `rt.mesh()`, `rt.addModifier()`, and `rt.maxOps.collapseNode()` triggers a viewport update per face (`Python/explode_geometry.py:261-296`) - `QApplication.processEvents()` is called once per face via `_prog()`, adding Qt event-loop overhead on every iteration (`Python/explode_geometry.py:257-259`) - The outer `with pymxs.undo(True, "Explode Geometry"):` exists but individual per-face calls still record internal undo data, adding overhead (`Python/explode_geometry.py:261`) - The MNMesh path uses `polyop.detachFaces` which mutates the source mesh per call and shifts face indices, forcing a reverse-order sequential loop (`Python/explode_geometry.py:360-362`) - `rt.redrawViews()` is already called once after the loop (`Python/explode_geometry.py:296`) — viewport state is recoverable if redraws are suppressed during the loop - `Bundle2/Contents/python/explode_geometry.py` is identical to `Python/explode_geometry.py` and needs the same changes ## Desired End State The explode operation on large meshes (100+ faces) completes measurably faster. The viewport does not flicker per-face during the operation. A single `Ctrl+Z` reverts the entire explode. The progress bar updates at reasonable intervals (~every 20 faces). All existing functionality (Shell modifier, Edit Mesh, collapse stack, center pivot, delete original, TriMesh/MNMesh modes) is preserved and produces identical geometry output. **Verification:** Run explode on a 500+ face mesh with Shell + Collapse Stack enabled. Record the `elapsed` time printed to the MAXScript Listener. Compare to the pre-patch baseline on the same mesh. ## What We're NOT Doing - No `threading.Thread`, `concurrent.futures.ThreadPoolExecutor`, or `multiprocessing` for `pymxs` calls (confirmed impossible per Autodesk documentation) - No `pymxs.mxstoken()` usage (deprecated, non-functional) - No Qt worker threads that call back into `pymxs` (deadlock risk) - No changes to the UI layout or any feature set - No changes to `Python/explode_geometry_classic.py` (MaxPlus-based, legacy/unsupported since 3ds Max 2022) ## Implementation Approach Implement the four ranked optimizations from the research in priority order. Tasks 1 and 2 (redraw suppression + undo suppression) are the highest-impact changes. Task 3 (processEvents throttle) is a quick secondary improvement. Task 4 (MNMesh refactor) eliminates an algorithmic sequential dependency. All changes are applied to both script files. --- **IMPORTANT: Checkboxes are for implementation steps only.** Steps requiring manual human verification are in the numbered "Manual Testing Steps" section at the bottom. ### TASK 1: Disable Scene Redraws During the Explode Loop [HIGH PRIORITY] **Status:** DONE **Milestone:** The 3ds Max viewport no longer updates per-face during explode; a single `rt.redrawViews()` fires once at the end. - [x] Confirm `rt.disableSceneRedraw()` and `rt.enableSceneRedraw()` are accessible via `pymxs.runtime` (test in MAXScript Listener: `python.execute "import pymxs; pymxs.runtime.disableSceneRedraw()"`) - [x] If direct pymxs access fails, use `rt.execute("disableSceneRedraw()")` and `rt.execute("enableSceneRedraw()")` as fallback - [x] In `do_explode()` in `Python/explode_geometry.py`, add `rt.disableSceneRedraw()` immediately before the `with pymxs.undo(True, "Explode Geometry"):` block (before line 261) - [x] Wrap the undo block in a `try/finally` that calls `rt.enableSceneRedraw()` then `rt.redrawViews()` in the `finally` clause - [x] Remove the standalone `rt.redrawViews()` at line 296 since it is now inside the `finally` block - [x] Apply the identical structural change to `Bundle2/Contents/python/explode_geometry.py` **Validation:** Run explode on a 200+ face mesh. Viewport must not flicker per-face. `rt.redrawViews()` fires once at completion. MAXScript Listener shows lower `elapsed` time vs pre-patch baseline. **Requirements from spec:** - All scene operations remain on the main thread - Viewport must be fully refreshed (redraws re-enabled + `rt.redrawViews()`) after explode completes **Files to Modify:** - `Python/explode_geometry.py` — `do_explode()` method (~line 261) - `Bundle2/Contents/python/explode_geometry.py` — identical change **Implementation Details:** ```python rt.disableSceneRedraw() try: with pymxs.undo(True, "Explode Geometry"): if self.trimesh_option.isChecked(): ... # existing TriMesh loop if self.mnmesh_option.isChecked(): ... # existing MNMesh loop finally: rt.enableSceneRedraw() rt.redrawViews() ``` --- ### TASK 2: Suppress Per-Face Undo Entries [HIGH PRIORITY] **Status:** DONE **Milestone:** The undo stack shows a single "Explode Geometry" entry; per-face undo recording overhead is eliminated. - [x] In `convert_to_triangle_faces()` in `Python/explode_geometry.py` (lines 330-347), wrap the per-face block (`rt.mesh(...)` through `applySettings(...)`) in `with pymxs.undo(False):` - [x] In `convert_to_mnmesh_faces()` in `Python/explode_geometry.py` (lines 360-372), wrap the per-face block (`rt.polyop.detachFaces(...)` through `applySettings(...)`) in `with pymxs.undo(False):` - [x] Keep the outer `with pymxs.undo(True, "Explode Geometry"):` in `do_explode()` intact — it provides the single undo group entry - [x] Apply the same changes to `Bundle2/Contents/python/explode_geometry.py` **Validation:** Explode a 50+ face mesh. Press `Ctrl+Z` once. The entire explode operation (all created nodes removed, original restored) must be undone in a single step. The Edit menu undo history must show exactly one "Explode Geometry" entry. **Requirements from spec:** - The whole explode must be reversible with a single undo - Nesting `with pymxs.undo(False):` inside `with pymxs.undo(True, ...):` must correctly scope undo to the outer block (test this before committing) **Files to Modify:** - `Python/explode_geometry.py` — `convert_to_triangle_faces()` (~lines 330-347) and `convert_to_mnmesh_faces()` (~lines 360-372) - `Bundle2/Contents/python/explode_geometry.py` — same changes **Implementation Details:** In `convert_to_triangle_faces`: ```python for face_idx in range(1, num_faces + 1): face = rt.getFace(node, face_idx) v1 = rt.getVert(node, int(face.x)) v2 = rt.getVert(node, int(face.y)) v3 = rt.getVert(node, int(face.z)) with pymxs.undo(False): new_node = rt.mesh(vertices=rt.Array(v1, v2, v3), faces=rt.Array(rt.Point3(1, 2, 3))) rt.update(new_node) new_node.wireColor = _random_wire_color() applySettings(new_node, addShell, shell_amount, addEditMesh, collapseNode, centerPivot) if on_progress: on_progress(face_idx, num_faces) ``` --- ### TASK 3: Throttle `processEvents()` to Every N Faces [MEDIUM PRIORITY] **Status:** DONE **Milestone:** Qt event-loop pump overhead is reduced from O(faces) to O(faces/20) while the progress bar remains responsive. - [x] In `do_explode()` in `Python/explode_geometry.py`, update the `_prog()` inner function (lines 257-259) to only call `QtWidgets.QApplication.processEvents()` when `cur % 20 == 0 or cur == tot` - [x] Keep `self.progress_bar.setValue(...)` updating every call — it is cheap and ensures accurate display when `processEvents()` does fire - [x] Keep the existing `QtWidgets.QApplication.processEvents()` at line 254 (after showing the progress panel) unchanged — that call is outside the hot path - [x] Apply the same change to `Bundle2/Contents/python/explode_geometry.py` **Validation:** On a 200-face mesh, the progress bar must advance in visible steps (~10% increments). The UI must remain responsive (window can be moved, not frozen). No single progress jump exceeds ~20% in one tick. **Requirements from spec:** - Progress bar must remain visually responsive during long operations - Throttle interval of 20 faces is a starting point; adjust between 10-50 based on testing **Files to Modify:** - `Python/explode_geometry.py` — `_prog()` inner function inside `do_explode()` (~lines 257-259) - `Bundle2/Contents/python/explode_geometry.py` — same change **Implementation Details:** ```python def _prog(cur, tot): self.progress_bar.setValue(int(cur * 100 / tot) if tot else 0) if cur % 20 == 0 or cur == tot: QtWidgets.QApplication.processEvents() ``` --- ### TASK 4: Refactor MNMesh Path to Read-Then-Create Pattern [MEDIUM PRIORITY] **Status:** DONE **Milestone:** `convert_to_mnmesh_faces()` no longer uses `polyop.detachFaces`. All vertex data is read in Phase 1 before any node is created in Phase 2, removing the index-shifting sequential dependency. - [x] Add a new helper function `_create_poly_node_from_positions(positions)` to `Python/explode_geometry.py` (after `_random_wire_color`). It must: create a new `PolyMeshObject` node via `rt.newObjectNode(rt.PolyMeshObject())`, call `rt.polyop.setNumVerts`, `rt.polyop.setVert` for each position, then `rt.polyop.createFace` with a 1-based index array - [x] If `rt.newObjectNode` or `rt.PolyMeshObject` are not accessible in pymxs, use `rt.execute("newObjectNode (PolyMeshObject())")` and retrieve the node via `rt.objects[-1]` - [x] Refactor `convert_to_mnmesh_faces()` in `Python/explode_geometry.py` (lines 351-373): Phase 1 iterates `range(1, num_faces + 1)` (forward order), calls `rt.polyop.getFaceVerts` and `rt.polyop.getVert` for each vertex, stores results as plain Python `(x, y, z)` tuples — retains no pymxs objects after this phase - [x] Phase 2 iterates the plain Python list, calls `_create_poly_node_from_positions(positions)` per face, sets `wireColor`, calls `applySettings` - [x] Remove the reverse iteration `range(num_faces, 0, -1)` from `convert_to_mnmesh_faces` — forward order is correct since Phase 1 does not mutate the source - [x] Verify that `rt.delete(node)` (the `deleteOriginal` path in `do_explode()`) is called only after both phases complete, since Phase 1 reads from the source mesh - [x] Apply the same changes to `Bundle2/Contents/python/explode_geometry.py` **Validation:** Explode a quad-face plane in MNMesh mode. Each resulting node must be a single-face Editable Poly with correct vertex positions (check in modifier panel). Explode a pentagon (5-vert n-gon) to confirm n-gon topology is preserved, not triangulated. **Requirements from spec:** - Polygon topology (quads, n-gons) must be preserved — do not triangulate faces - Vertex positions must match the source mesh exactly - Source mesh must not be mutated during Phase 1 **Files to Modify:** - `Python/explode_geometry.py` — add `_create_poly_node_from_positions()` helper; refactor `convert_to_mnmesh_faces()` (~lines 351-373) - `Bundle2/Contents/python/explode_geometry.py` — same changes **Implementation Details:** Phase 1 (read, no mutation): ```python rt.convertToPoly(node) num_faces = rt.polyop.getNumFaces(node) face_data = [] for face_idx in range(1, num_faces + 1): verts = rt.polyop.getFaceVerts(node, face_idx) positions = [(rt.polyop.getVert(node, int(v)).x, rt.polyop.getVert(node, int(v)).y, rt.polyop.getVert(node, int(v)).z) for v in verts] face_data.append(positions) ``` Phase 2 (create from plain Python data): ```python for i, positions in enumerate(face_data, 1): with pymxs.undo(False): new_node = _create_poly_node_from_positions(positions) new_node.wireColor = _random_wire_color() applySettings(new_node, addShell, shell_amount, addEditMesh, collapseNode, centerPivot) if on_progress: on_progress(i, num_faces) ``` Helper function: ```python def _create_poly_node_from_positions(positions): n = len(positions) node = rt.newObjectNode(rt.PolyMeshObject()) rt.polyop.setNumVerts(node, n) for i, (x, y, z) in enumerate(positions, 1): rt.polyop.setVert(node, i, rt.Point3(x, y, z)) rt.polyop.createFace(node, rt.Array(*range(1, n + 1))) return node ``` > **Assumption:** `rt.newObjectNode` and `rt.PolyMeshObject` are available as pymxs runtime calls. If not, fall back to `rt.execute(...)` and `rt.objects[-1]`. --- ## Testing Strategy ### Unit Tests: - No standalone unit test framework exists in this project (3ds Max plugin context) - Correctness is verified by comparing geometry output against the pre-patch baseline ### Integration Tests: - Run TriMesh explode on a Box primitive (12 triangles) — verify exactly 12 TriMesh face nodes are created - Run MNMesh explode on a Plane primitive (quad faces) — verify N single-face Editable Poly nodes are created - Run MNMesh explode on an n-gon face — verify face topology is preserved (not triangulated) - Confirm single undo entry reverts entire operation ### Manual Testing Steps: 1. Open 3ds Max, load `Python/explode_geometry.py`, create a GeoSphere with 100+ faces 2. Record baseline elapsed time from the MAXScript Listener before patching 3. Apply Task 1 patch; repeat the same explode and compare elapsed time — viewport must not flicker 4. Apply Task 2 patch; press `Ctrl+Z` once after explode — verify full operation is undone in a single step 5. Apply Task 3 patch; run explode on a 200+ face mesh — verify progress bar advances in steps of ~20 faces 6. Apply Task 4 patch; run MNMesh explode on a quad plane — open modifier panel on a resulting node and verify vertex coordinates match the original face 7. Test the most expensive path end-to-end: Shell modifier enabled + Collapse Stack enabled on a 500+ face mesh — confirm elapsed time improvement and no crashes ## Performance Considerations - Tasks 1 + 2 combined are estimated at 2–5x speedup on large meshes based on research; viewport redraw suppression is the single largest contributor - Task 3 impact is proportional to mesh size; most noticeable on 500+ face objects - Task 4 restructures the MNMesh algorithm but does not reduce O(n) complexity; gains come from eliminating the `detachFaces` per-call overhead and removing the reverse-iteration constraint --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
allankoech added the
pull-request
label 2026-10-14 09:52:34 +00:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: allankoech/ADN-3dsMax-Explode-Geometry#6
No description provided.