# TenPix Cloth for 3ds Max: Guide for AI Assistants

TenPix Cloth 1.057235 for 3ds Max 2024, 2025, 2026 and 2027.

This guide is for an AI assistant connected to an artist's running 3ds Max through MCP. It covers reading a TenPix set-up, building and changing set-ups with MAXScript, simulating and caching, and talking with the artist. It is written to stand on its own for everyday jobs: dressing a character, materials, friction, layers, quality and caches. For the full detail, the TenPix Cloth Artist Manual (what each setting does to the cloth) and the TenPix Cloth MAXScript Guide (every property and function) come as PDFs in the folder this guide came in; they are not installed into 3ds Max. Everything here uses only their published names.

> **Read this first**
>
> - **You are working in the artist's live scene.** Look before you change anything. Change one thing at a time, show the result, and say what you changed.
> - **Never delete, Reset or overwrite caches or files without the artist's yes.**
> - **When the artist names a part of a garment** (collar, cuff, waistband, hem, sleeve, pocket, placket, belt, hood, shoulder pad), first find what is on that part now and work out what is happening to it. Then **ask which behaviour they want, and offer a default.** If the model uses a Tnpix Wrap, offer Tnpix Preserve and ask how strong it should be. Ask only questions whose answer changes what you will do. See section 5.

## Contents

1. Purpose and connection
2. Ground rules
3. Reading a scene
4. Recipes
5. Talking with the artist
6. Limits and what helps
7. Quick reference

---

## 1. Purpose and connection

### 1.1 What you can do

TenPix Cloth simulates cloth on an NVIDIA graphics card through a set of 3ds Max modifiers. Through MCP you can inspect a scene and explain its set-up (Solver groups, garments, colliders, forces, channels, pins, rigid pieces, Preserve, Wrap and caches), build and change set-ups with MAXScript, simulate and cache, and talk with the artist as section 5 describes.

### 1.2 The connection

Any MCP server that runs MAXScript inside the artist's running 3ds Max will work. Tool names differ from server to server, and not every server offers all three of these:

| Need | Typical tool |
|---|---|
| Run MAXScript | A tool that takes a MAXScript string, for example `max_execute_maxscript`. |
| Run Python | A tool that runs Python inside 3ds Max through pymxs, for example `max_execute_python_code`. |
| See the result | A viewport snapshot (width, height, image format, optional frame), for example `max_capture_viewport_snapshot`. Without one, save the viewport to a picture file with `tpaCapture` (3.6). |

Some servers show each script to the artist and run it only after they approve it. With such a server, gather your reading into one script, and say in one line what a script will change before you send it.

TenPix is scripted in MAXScript: through the modifier properties and the global interfaces `TnpixTool`, `TnpixPreset` and `TnpixGraph`. Write every TenPix call in MAXScript. If your server only runs Python, pass the same MAXScript text to 3ds Max's MAXScript evaluator from Python with `pymxs.runtime.execute("...")`.

### 1.3 Working through the connection

- **Calls share one session.** Every call runs in the same 3ds Max session, so functions and variables defined at the top level stay until 3ds Max closes. Wrap a multi-line script in `( ... )` to keep its `local`s inside it. Some servers add those brackets themselves and refuse a script that already starts with one; with such a server, send the script without its outer pair.
- **Return text as the script's value.** Build a string and make it the last expression. Lines printed to the Listener may not reach you.
- **Check every return value.** A TenPix call that refuses writes nothing and returns `false`, `-1`, or a string that begins with `***` or `refused:`. A refusal is never a silent success.
- **Make each change one undo step.** Wrap it as `undo "TenPix: <what>" on ( ... )` so the artist can take it back with Ctrl+Z. Functions that change something can be undone wherever the same change made on the panel can.
- **Work in chunks.** A call holds 3ds Max until it returns. Simulate a few dozen frames per call. Start long jobs only when the artist has said go: a cache save of a long range, a Batch Sim run.
- **Keep garments shown.** 3ds Max does not evaluate a hidden object, so keep every garment of a Solver group shown.
- **Capture what the artist sees.** Use their viewport and their camera. If you need to frame the cloth (`max tool zoomextents all`), say so first, because it changes their view.

### 1.4 First call

```maxscript
(
    local s = "TenPix loaded: " + ((TnpixTool != undefined) as string) + "\n"
    if TnpixTool != undefined do s += (TnpixTool.licInfo()) + "\n"
    s += "System unit: " + (units.SystemType as string) + " x " + (units.SystemScale as string) + "\n"
    s += "Range: " + ((animationRange.start.frame as integer) as string) + " to " + ((animationRange.end.frame as integer) as string) + " at " + (frameRate as string) + " fps"
    s
)
```

`TnpixTool.licInfo()` tells you whether this computer runs the demo or an activated licence. Tell the artist when a demo limit affects what they asked for:

- up to 25,000 cloth vertices simulate, counted over every simulating garment in the scene together, for the first 100 frames only (colliders, and garments playing from a Tnpix Cache, do not count);
- caches save as .tnc only (no Alembic);
- Live at frame 0 drapes the cloth but neither holds it nor keeps the shape;
- on a render farm or in batch mode, the demo simulates nothing.

Never handle a licence key. Activation is the artist's job, in the Licence window.

---

## 2. Ground rules

1. **Inspect before you change.** Run the scene report (3.3) and read it: units, frame range, Solver groups, every stack, channels and caches. Never ask the artist something the scene already tells you.
2. **Get the artist's yes first** before anything you cannot cleanly take back:
   - deleting an object, a modifier or a channel;
   - Reset Simulation (`TnpixTool.reset()`), or starting Live at frame 0, which clears the simulated frames the same way;
   - saving a cache over an existing file, deleting or moving cache files, or running Batch Sim (it replaces same-named files in its shot folders);
   - changing the start shape (Live `"keep"`, `"keepframe"`, `"clear"`);
   - changing the scene's units, or a Solver's World scale.

   Clearing a cache (`TnpixTool.cacheClear`) deletes nothing, but the garment then simulates again. Say so when you do it.
3. **Make one change at a time, then show it.** After each change, simulate the frames where it shows and capture them: one frame, or three or four frames of a short range. Use the same view and the same frames as before, so the artist can compare.
4. **Keep the scene's units.** TenPix works in the scene's own system unit. Never change System Unit Setup and never rescale the scene. Every length you write is a number in the system unit; section 3.1 lists the values TenPix keeps in real-world units instead.
5. **Save under a new name before a big change.** Big changes include a new Solver group, a replaced modifier, a Batch Sim run and a scene-wide quality change. Save the scene under a new file name, never over the artist's file, and tell the artist the name. If the scene has never been saved, ask where to save it.
6. **Report what you changed.** Give the object, the modifier and the setting, the old value and the new one, what you saw, and how to take it back.
7. **Change only what was asked.** If you notice another problem, report it with a suggestion. Do not fix it unasked.
8. **Find modifiers by class, not by name.** An artist may rename a modifier, for example "Tnpix Cache" to "Tnpix Cache_Walk". The helpers in 3.2 find modifiers by class.
9. **Set every value you rely on.** A Tnpix modifier you add starts from its default values (Section 7.8 lists them), not from the values last typed into another of the same kind. The artist may also have changed a value since. Set the ones the job depends on explicitly, as the recipes do.
10. **Check Play from cache before you tune.** A garment that plays from its Tnpix Cache ignores every change below the Cache.

---

## 3. Reading a scene

### 3.1 The set-up in brief

- **Modifiers.** Tnpix Solver is the only modifier that simulates. Every other Tnpix modifier contributes to it: gravity, fabric, colliders, painted regions and so on. A switched-off modifier behaves as if it had never been added, and nothing acts on the cloth unless it is on the stack. Without a Tnpix Gravity there is no gravity; an object collides only once it is in a Tnpix Collision list.
- **Solver group.** Every object that carries the same Tnpix Solver instance is simulated together, as one Solver group. Its garments collide with each other, stack in layers and can be stitched together. Two garments on two separate Solvers never touch. An object carries one Solver.
- **Group-wide and per-garment settings.** Group-wide settings have one value for the whole Solver group:
  - gravity;
  - the collider list (rows from every member are merged);
  - the Self Collision settings;
  - the Tear's trigger (Tear by), Ends and weakness range;
  - Accurate strain limit, Solve steps per iteration and Multi-res levels. For these three, the Solver runs the highest value that any garment's top Material Standard sets.

  Where two members carry different values for any other group-wide setting, the member created first wins.

  Each garment keeps its own: channels, Pin, Stitch and Tear regions, materials (each with its own friction and grip, 3.7), Preserve, Forces, Volume, Rigid, Soft Body, Garment and Threads. Share the group-wide modifiers as one instance across the group.
- **A shared Solver changes nothing for a garment.** A garment that shares a Solver with other garments behaves as it does on a Solver of its own: its weight and its self-collision sizes stay the same.
- **Each garment has its own space.** A garment is simulated in its own space, and every tool follows the cloth's own space. Moving or turning the whole set-up gives the same simulation; the whole set-up is the garment with its colliders, the objects its pins follow and its forces. Moving only one part of it (the garment alone, one collider, or the object a pin follows) does change the simulation. The Solver's Unlimited ground always stays at Z = 0.
- **Stack order.** Bottom to top:
  - Tnpix Garment at the bottom, because it changes the vertex count;
  - Tnpix Channel above it;
  - the modifiers that describe the cloth;
  - Tnpix Solver above them;
  - Tnpix Threads directly above the Solver, and Tnpix Cache above the Solver;
  - Tnpix Post Process above the Cache, and Tnpix Motion Brush above the Solver and its Cache;
  - render modifiers such as TurboSmooth or Shell on top.

  Where two materials paint the same points, the higher one wins. A Tnpix Soft Body or Tnpix Volume that has a Channel and sits above a Tnpix Pin or Tnpix Preserve lets go of the points it paints.

  A typical stack, top to bottom: `TurboSmooth > Tnpix Post Process > Tnpix Cache > Tnpix Solver > Tnpix Self Collision > Tnpix Collision > Tnpix Gravity > Tnpix Pin > Tnpix Material Standard > Tnpix Channel > Tnpix Garment > Editable Poly`.
- **Channels.** A channel is a named weight map painted with Tnpix Channel, from 0 (outside) to 1 (fully inside). Other modifiers bind a channel by its name, and a channel that nothing reads changes nothing.
  - A material acts only on its own garment's paint.
  - The channels of Pins, Stitches and Tears are merged by name across the Solver group, so give each garment's channels their own names, for example `shirt_collar`.
- **Playback and memory.** The simulation starts at the first frame of the animation range, and every simulated frame is held in memory.
  - Changing a simulation setting simulates again from the first frame, up to the frame shown.
  - Keyed settings are read frame by frame.
  - Editing a shape below the Solver, a collider's shape, or the shape of an object a pin follows starts the simulation again.
- **Caches.** A garment that plays from its Tnpix Cache file is read from disk. It is fast, identical every time and unaffected by changes below the Cache.
- **Units.** Lengths are numbers in the scene's system unit; Gravity is in units per second squared. These values use real-world units instead:

  | Value | Unit |
  |---|---|
  | TenPix Wind speeds and sizes | m/s and metres |
  | Fabric weight | g/m² |
  | Tnpix Rigid density | g/cm³ |
  | Soft Body stiffness and density | kPa and g/cm³ |
  | Tear threshold | not a length: a strength you set by reading the Tear's status line |

  A new modifier expresses its length defaults in the scene's unit. A new Gravity, for example, is −386.22 in an inch scene, −981 in centimetres and −9.81 in metres.
- **Repeatable.** The same scene with the same settings produces the same simulation every time.

### 3.2 Helpers

Load these once per 3ds Max session; they stay defined until 3ds Max closes. They find modifiers by class, and they place a new modifier where the stack order says it belongs. The other examples in this guide use them.

```maxscript
global tpaFirst, tpaIndex, tpaUsers, tpaAddBelowSolver, tpaAddAboveSolver, tpaGoldIndex, tpaMatIndex

-- the first modifier of class cls on o's stack, from the top (undefined if none)
fn tpaFirst o cls = (
    local r = undefined
    if isValidNode o do for m in o.modifiers where r == undefined and (classOf m) == cls do r = m
    r
)
-- the stack index of that modifier (1 = the top of the stack), 0 if none
fn tpaIndex o cls = (
    local k = 0
    for i = 1 to o.modifiers.count where k == 0 and (classOf o.modifiers[i]) == cls do k = i
    k
)
-- the objects that share modifier m; for a Tnpix Solver, its whole Solver group
fn tpaUsers m = ( makeUniqueArray (for n in (refs.dependentNodes m) where isValidNode n collect n) )
-- put m directly below o's Tnpix Solver, where the modifiers that describe the cloth go (on top if o has no Solver)
fn tpaAddBelowSolver o m = (
    local s = tpaIndex o Tnpix_Solver
    if s == 0 then addModifier o m else addModifier o m before:s
    m
)
-- put m directly above o's Tnpix Solver (Tnpix Cache, Tnpix Threads)
fn tpaAddAboveSolver o m = (
    local s = tpaIndex o Tnpix_Solver
    if s <= 1 then addModifier o m else addModifier o m before:(s - 1)
    m
)
-- the index that goldAt, goldSetAt and goldChanAt use for Material Standard m on o (0 = the top-most); -1 if not found
fn tpaGoldIndex o m = (
    local k = -1, n = 0
    for x in o.modifiers where (classOf x) == Tnpix_Material_Standard do ( if x == m do k = n; n += 1 )
    k
)
-- the same for a Material Advanced (matAt, matSetAt, matChanAt and the other mat functions)
fn tpaMatIndex o m = (
    local k = -1, n = 0
    for x in o.modifiers where (classOf x) == Tnpix_Material_Advanced do ( if x == m do k = n; n += 1 )
    k
)
```

`addModifier o m before:k` places `m` directly below the modifier at stack index `k`. Index 1 is the top of the stack.

### 3.3 The scene report

The report prints every Solver group, each garment's stack (top first) with what each TenPix modifier is set to, then the objects outside any Solver group, the TenPix Winds and the threads objects. Run `tpaReport()` and read the whole result before you suggest anything.

```maxscript
global tpaStack, tpaDetails, tpaReport

-- one line per modifier, top first: stack index, name, class, switches, sharing
fn tpaStack o = (
    local s = ""
    for j = 1 to o.modifiers.count do (
        local m = o.modifiers[j]
        local c = classOf m
        s += "      [" + (j as string) + "] " + m.name + " <" + (c as string) + ">"
        if not m.enabled do s += "  LIGHT BULB OFF"
        if isProperty m #tnEnabled do ( if not m.tnEnabled do s += "  tnEnabled OFF" )
        if c == Tnpix_Collision do ( if not m.active do s += "  active OFF" )
        local n = (tpaUsers m).count
        if n > 1 do s += "  (shared by " + (n as string) + " objects)"
        s += "\n"
    )
    s
)

-- what each TenPix modifier on o is set to
fn tpaDetails o = (
    local s = ""
    for m in o.modifiers do (
        local c = classOf m
        if c == Tnpix_Pin then s += "      Pin " + m.name + ": channel '" + m.channel + "', weight " + (m.weight as string) + ", follows " + (if isValidNode m.followObject then m.followObject.name else "nothing (holds in place)") + ", dynamic " + (m.dynamic as string) + (if m.activeTime then ", frames " + (m.activeFrom as string) + "-" + (m.activeTo as string) else "") + "\n"
        else if c == Tnpix_Preserve then s += "      Preserve " + m.name + ": channel '" + m.channel + "'\n"
        else if c == Tnpix_Stitch then s += "      Stitch " + m.name + ": channel '" + m.channel + "', to " + ((for x in m.stitchTo where isValidNode x collect x.name) as string) + ", to self " + (m.stitchToSelf as string) + ", tightness " + (m.tightness as string) + ", strength " + (m.strength as string) + "\n"
        else if c == Tnpix_Tear then s += "      Tear " + m.name + ": by " + (m.tearBy as string) + " (0 map, 1 stretch, 2 pressure), channel '" + m.channelName + "', threshold " + (m.threshold as string) + ", stretch ratio " + (m.stretchRatio as string) + "\n"
        else if c == Tnpix_Rigid then s += "      Rigid " + m.name + ": pieces from " + (m.piecesFrom as string) + " (0 channel, 1 mesh elements), channel '" + m.channel + "', rigidity " + (m.rigidity as string) + ", mass mode " + (m.massMode as string) + " | " + (TnpixTool.rigidInfo o) + "\n"
        else if c == Tnpix_Volume then s += "      Volume " + m.name + ": mode " + (m.mode as string) + " (0 keep volume, 1 pressure), channel '" + m.volumeChannel + "', ratio " + (m.volumeRatio as string) + ", pressure " + (m.pressure as string) + ", buoyancy " + (m.buoyancy as string) + "\n"
        else if c == Tnpix_Soft_Body then s += "      Soft Body " + m.name + ": material " + (m.material as string) + ", channel '" + m.softChannel + "'\n"
        else if c == Tnpix_Forces then s += "      Forces " + m.name + ": strength " + (m.strength as string) + ", channel '" + m.forceChannel + "', warps " + ((for x in m.forceNodes collect (if isValidNode x then x.name else "(deleted)")) as string) + ", muted " + (m.forceMuted as string) + "\n"
        else if c == Tnpix_Self_Collision then (
            s += "      Self Collision: thickness " + (m.thickness as string) + ", panel friction " + (m.friction as string)
            s += (if m.overrideMaterialFriction then " (Override material friction ON: the panel's friction, or a garment's own number below, on every point)" else " (Override material friction off: each garment's material friction acts; the panel's only where no material sets one)")
            s += ", mode " + (m.mode as string) + " (0 basic, 1 advanced, 2 optimized), relaxation passes " + (m.passes as string) + ", query diameter " + (m.queryDiameter as string) + ", layer ordering " + (m.layerOrdering as string) + ", hold strength " + (m.layerHoldStrength as string) + " | " + (TnpixTool.selfColLayers o) + "\n"
            for k = 1 to m.memberHandles.count do (
                local mo = maxOps.getNodeByHandle m.memberHandles[k]
                s += "        garment list " + (k as string) + ": " + (if isValidNode mo then mo.name else "(deleted)") + ", layer " + (if k <= m.memberLayers.count then (m.memberLayers[k] as string) else "-") + ", friction " + (if k <= m.memberFrictions.count then (m.memberFrictions[k] as string) else "-") + ", thickness " + (if k <= m.memberThicknesses.count then (m.memberThicknesses[k] as string) else "-") + " (-1 = not set)\n"
            )
        )
        else if c == Tnpix_Collision then s += "      Collision: " + ((TnpixTool.colCount o) as string) + " row(s); DynSlide is a row's Friction, and a row's Friction and Grip act only with its Override material at 1 or 2 (3.7)\n" + (TnpixTool.rows o) + "\n"
        else if c == Tnpix_Garment then s += "      Garment: mode " + (m.mode as string) + " (0 remesh, 1 OpenVDB), edge length " + (m.edgeLength as string) + "\n"
        else if c == Tnpix_Gravity then s += "      Gravity: magnitude " + (m.magnitude as string) + ", direction " + (m.direction as string) + "\n"
        else if c == Tnpix_Cache then s += "      Cache: " + (TnpixTool.cacheInfo o) + "\n"
        else if c == Tnpix_Wrap then s += "      Wrap: proxies " + ((for x in m.proxies where isValidNode x collect x.name) as string) + ", bind frame " + (m.bindFrame as string) + " | " + (TnpixTool.wrapInfo o) + "\n"
    )
    for k = 0 to (TnpixTool.goldCount o) - 1 do s += "      Material Standard " + (k as string) + ": " + (TnpixTool.goldAt o k)
    for k = 0 to (TnpixTool.matCount o) - 1 do s += "      Material Advanced " + (k as string) + ": " + (TnpixTool.matAt o k)
    if (tpaFirst o Tnpix_Channel) != undefined do s += (TnpixTool.chans o)
    s
)

fn tpaReport = (
    local s = "Scene " + maxFilePath + maxFileName + " | unit " + (units.SystemType as string) + " x " + (units.SystemScale as string)
    s += " | frames " + ((animationRange.start.frame as integer) as string) + " to " + ((animationRange.end.frame as integer) as string) + " at " + (frameRate as string) + " fps\n"
    if TnpixTool == undefined then s += "TenPix Cloth is not loaded.\n" else (
        s += "Licence: " + (TnpixTool.licInfo()) + "\n"
        -- the Solver groups: each Solver instance and the objects that carry it
        local svs = #(), grp = #()
        for o in objects do for m in o.modifiers where (classOf m) == Tnpix_Solver do (
            local k = findItem svs m
            if k == 0 then ( append svs m; append grp #(o) ) else append grp[k] o
        )
        for i = 1 to svs.count do (
            local sv = svs[i]
            s += "\n== SOLVER GROUP " + (i as string) + ": " + ((for o in grp[i] collect o.name) as string) + "\n"
            s += "   substeps " + (sv.substeps as string) + ", iterations " + (sv.iterations as string) + ", contact passes " + (sv.contactPasses as string) + ", stretch quality " + (sv.stretchQuality as string) + ", smoothing " + (sv.smoothingIterations as string) + ", post collision passes " + (sv.postCollisionPasses as string) + ", fast motion collision " + (sv.ccd as string) + ", deep rescue " + (sv.deepRescue as string) + "\n"
            s += "   collision system " + (sv.collisionSystem as string) + " (4 = Surface True Geometry), world scale " + (sv.worldScale as string) + ", weight mode " + (sv.weightMode as string) + " (1 = Real), unlimited ground " + (sv.unlimitedGround as string) + "\n"
            s += "   start shape: " + (TnpixTool.live grp[i][1] "shape" 0) + "\n"
            for o in grp[i] do s += "   -- " + o.name + "\n" + (tpaStack o) + (tpaDetails o)
        )
        s += "\n== OUTSIDE ANY SOLVER GROUP\n"
        for o in objects where (tpaFirst o Tnpix_Solver) == undefined do (
            local tn = for m in o.modifiers where matchPattern ((classOf m) as string) pattern:"Tnpix*" collect m.name
            if tn.count > 0 do s += "   -- " + o.name + ": " + (tn as string) + "\n" + (tpaDetails o)
            local c = classOf o.baseObject
            if c == TenPix_Wind do (
                local b = o.baseObject
                s += "   TenPix Wind " + o.name + ": mode " + (b.mode as string) + " (0 automatic, 1 map), type " + (b.windType as string) + ", speed " + (b.speed as string) + " m/s, map " + (b.map as string) + ", direction map " + (b.directionMap as string) + ", map size " + (b.mapSize as string) + " m, push across " + (b.pushAcross as string) + ", drag along " + (b.dragAlong as string) + "\n"
            )
            if c == Tnpix_Threads_Object do s += "   Threads object " + o.name + " shows " + (o.baseObject.threadsFrom as string) + "\n"
        )
    )
    s
)
```

What the report reads, and from where:

| What you want to know | Where it comes from |
|---|---|
| The Solver groups | `refs.dependentNodes` on a Solver, or the loop above |
| A garment's stack | `o.modifiers`; index 1 is the top of the stack |
| Colliders and their rows | `TnpixTool.colCount`, `TnpixTool.rows` (the row numbers that `colSet` takes) |
| Garment layers | `TnpixTool.selfColLayers` (each garment's layer, and whether it was typed or follows the Solver group's order) |
| Material values and their channel | `TnpixTool.goldAt` / `TnpixTool.matAt`; the text names the channel the material is bound to (`channel <name>`), and `goldAt` shows `matFriction` and `matGrip` (`auth 1` = switched on) |
| Friction | 3.7: the materials, the Self Collision panel and its garment list, the collider rows |
| Channels | `TnpixTool.chans`: the channel table, with the row selected on the panel |
| Caches | `TnpixTool.cacheInfo`: `file=`, `found=`, `playing=`, the frames (`frames 0-120 (121)`), and `stopped=1` for a recording that stopped early |
| Rigid pieces | `TnpixTool.rigidInfo`: the pieces and points, once a simulation has started |
| Wrap | `proxies` and `bindFrame`, plus `TnpixTool.wrapInfo` |
| Start shape | `TnpixTool.live node "shape" 0`: the modelled mesh, a kept shape, or the frame it was kept from |
| Wind | each TenPix Wind's properties on its base object; Tnpix Forces `forceNodes` and `forceMuted` |

### 3.4 What is on a garment part

When the artist names a part (section 5), find the channel that covers it with `TnpixTool.chans`, then list everything that reads that channel:

```maxscript
global tpaChannelUse
fn tpaChannelUse o ch = (
    local s = o.name + " / '" + ch + "': " + ((TnpixTool.chanCount o ch 0.5) as string) + " points at 0.5 or more, " + ((TnpixTool.chanCount o ch 0.001) as string) + " painted at all (-1 = no such channel)\n"
    for m in o.modifiers do (
        local c = classOf m
        local hit = false
        if c == Tnpix_Pin or c == Tnpix_Preserve or c == Tnpix_Stitch or c == Tnpix_Threads then hit = (m.channel == ch)
        else if c == Tnpix_Rigid then hit = (m.piecesFrom == 0 and m.channel == ch)
        else if c == Tnpix_Tear then hit = (m.channelName == ch)
        else if c == Tnpix_Volume then hit = (m.volumeChannel == ch)
        else if c == Tnpix_Soft_Body then hit = (m.softChannel == ch)
        else if c == Tnpix_Forces then hit = (m.forceChannel == ch)
        else if c == Tnpix_Post_Process then hit = (m.weightChannel == ch or m.detangleWeightChannel == ch)
        else if c == Tnpix_Wrap then hit = (m.weightChannel == ch)
        if hit do s += "  read by " + m.name + " <" + (c as string) + ">\n"
    )
    for k = 0 to (TnpixTool.goldCount o) - 1 do (
        local t = TnpixTool.goldAt o k
        if (findString t ("channel " + ch + " ")) != undefined do s += "  Material Standard " + (k as string) + ": " + t
    )
    for k = 0 to (TnpixTool.matCount o) - 1 do (
        local t = TnpixTool.matAt o k
        if (findString t ("channel " + ch + " ")) != undefined do s += "  Material Advanced " + (k as string) + ": " + t
    )
    s
)
```

Then check for a Tnpix Wrap, which rule 5b turns on. There are two cases:

```maxscript
-- the Tnpix Wrap on garment g itself (g follows its proxies), and the objects whose Tnpix Wrap uses g as a proxy (a detailed copy follows g)
(
    local g = $Shirt
    local own = tpaFirst g Tnpix_Wrap
    local driven = #()
    for o in objects do ( local w = tpaFirst o Tnpix_Wrap; if w != undefined and (findItem (w.proxies as array) g) > 0 do append driven o.name )
    "Wrap on " + g.name + ": " + (if own != undefined then ("yes, proxies " + ((for x in own.proxies where isValidNode x collect x.name) as string)) else "no") + "; Wraps that follow it: " + (driven as string)
)
```

Read the stack below the Solver as well (`tpaStack`). A Skin, Skin Wrap, Tnpix Wrap, Morpher, Point Cache or any other deformer below the Solver is animation that a Tnpix Preserve can follow.

### 3.5 A health check

These are the silent set-ups that the toolbar's Cloth Doctor looks for: nothing reports an error, but the cloth does not do what the artist expects.

```maxscript
global tpaCheck
fn tpaCheck = (
    local s = ""
    for o in objects where (tpaFirst o Tnpix_Solver) != undefined do (
        local sv = tpaFirst o Tnpix_Solver
        local g = tpaFirst o Tnpix_Gravity
        if g == undefined then s += o.name + ": no Tnpix Gravity - it hangs in the air\n"
        else if not g.tnEnabled or not g.enabled do s += o.name + ": its Tnpix Gravity is switched off\n"
        local iG = tpaIndex o Tnpix_Garment
        if iG > 0 and iG < (tpaIndex o Tnpix_Solver) do s += o.name + ": Tnpix Garment sits above the Solver\n"
        if (tpaFirst o Tnpix_Collision) != undefined and (TnpixTool.colCount o) == 0 do s += o.name + ": Tnpix Collision lists no collider\n"
        local sc = tpaFirst o Tnpix_Self_Collision
        if sc != undefined and not sc.tnEnabled do s += o.name + ": Tnpix Self Collision is present but switched off\n"
        local hi = amax sv.iterations sv.stretchQuality
        if (hi >= 8 and sv.contactPasses < 7) or (hi >= 4 and sv.contactPasses < 4) do s += o.name + ": contact passes " + (sv.contactPasses as string) + " are below the rule (4 for iterations or stretch quality of 4 or more, 7 for 8 or more)\n"
        local cm = tpaFirst o Tnpix_Cache
        if cm != undefined and cm.playFromCache do s += o.name + ": plays from its cache - changes below the cache do nothing\n"
    )
    if s == "" then "Nothing found." else s
)
```

The report also shows garments that sit on separate Solvers: they never collide with each other. Mention it only if the artist expects them to touch. To let the artist fix findings in a window, open Cloth Doctor (7.7).

### 3.6 Looking at it

- **Simulate, then capture.** Run `TnpixTool.sim node frame` up to the frame, move the slider there (`sliderTime = (f as time)`), and capture the viewport. Capturing a frame that has not been simulated yet simulates up to it.
- **Show End Result.** Before you capture, open the Solver in the Modify panel (`modPanel.setCurrentObject (tpaFirst g Tnpix_Solver)`). Opening a Tnpix panel turns 3ds Max's Show End Result on. With it off, and a modifier below the Solver selected, the cloth looks frozen.
- **Painted weights.** `(tpaFirst g Tnpix_Channel).showWeights = true` draws the channel selected on the Channel panel, from dark blue (0) through yellow (0.5) to red (1). Capture it, then set it back to `false`.
- **Stretch and contact.** `sv.stressHeatmap = true` colours every garment of the Solver group by how hard it is stretched or pressed. It is display only. Set it back afterwards.
- **The TenPix Graph.** `TnpixGraph.open()` shows the artist every Solver group with its objects and modifiers, in a window of its own. Opened from a script, it starts on the scene's first Solver group.

**Capture without a snapshot tool.** `tpaCapture` saves the active viewport, as it is drawn at that moment, to a PNG file. Read the file if your tools can open pictures; otherwise tell the artist where it is. Never judge a simulation from numbers alone: a garment can stay close to the body and still slide off it.

```maxscript
global tpaCapture
-- save the active viewport to the PNG file f; returns the file's path, or why there is no picture
fn tpaCapture f = (
    local r = "No viewport picture here (" + f + " was not written)."
    try (
        completeRedraw()
        local img = gw.getViewportDib()
        if img != undefined do ( img.filename = f; save img; close img; r = f )
    ) catch ()
    r
)
-- tpaSimTo $Shirt 24 (4.15), then: tpaCapture ((getDir #temp) + "\\tenpix_frame24.png")
```

### 3.7 Friction and grip: which number acts

Friction is decided point by point, and every garment's material carries its own. Read the materials before you change friction anywhere else.

| Contact | The number that acts |
|---|---|
| Cloth on a collider | The material at that point: Material Standard `matFriction` and `matGrip`, Material Advanced `friction` and `grip`; on a Tnpix Rigid's pieces, the Rigid's own `friction`. The collider row's own Friction (field 6) and Grip (field 8) act only when the row's Override material (field 11) is 1, Unpainted cloth only (the points no material covers), or 2, Everything (the row decides wherever it touches). |
| Cloth on cloth (Self Collision) | Override material friction off: each point's material friction. A garment's own number in the garment list acts only where no material sets one, and the panel's Friction only where neither does. Override material friction on: the panel's Friction on every point, or the garment's own number in the list. |
| Two garments touching | The average of the two points' frictions. With Layer ordering on and the two garments on different layers, the outer garment's friction acts (the higher layer number). |

- **Defaults.** A new Material Standard or Material Advanced starts with Friction 0.35 and Grip 3, both switched on. A new collider row has Friction 0.35, Grip 3 and Override material 0, Off. A new Self Collision has Friction 0 and Override material friction off. So in a new set-up every garment slides with its material's 0.35, against the body and against the other garments: the panel's 0 does not make the garments frictionless. A point that no material covers takes 0.35 and 3.
- **Grip** multiplies Friction for holding cloth still on a collider; it does not act between garments. Raise Grip when cloth creeps slowly over a body, and Friction when it slides too freely.
- **Where to change it.** For one garment against everything: its material (`TnpixTool.goldSetAt g k "matFriction" 0.6`, `TnpixTool.matSetAt g k "friction" 0.6`). For one region of a garment, such as the shoulders: a material bound to that region's channel (4.3). For one collider, whatever the cloth: that row's Override material 2 with its own Friction and Grip (4.4). For all garment-to-garment contact at one number: Self Collision `overrideMaterialFriction = true` and its `friction`.
- **Reading it.** `goldAt` prints a Standard material's `matFriction` and `matGrip`, with `(auth 1)` when switched on. `matAt` does not print an Advanced material's friction and grip; `TnpixPreset.text m` does, as `matFriction = 0.6 on` and `matGrip = 4 on` (`on` = switched on). The report (3.3) shows the Self Collision panel, its Override switch and the garment list. In `TnpixTool.rows`, the column DynSlide is a row's Friction and `ovr 1` means Override material 2; the column shows 0 for both Off and Unpainted cloth only.

---

## 4. Recipes

The recipes use the helpers from 3.2, and the object names are examples. Wrap each change in an undo block and show the result before going on. Every value given here comes from the panels' defaults and the books' examples; change them to fit the shot.

### 4.1 Make a cloth

**Quick Cloth (toolbar).** With meshes selected, the artist sets Triangle size (the Tnpix Garment's Edge length, default 2.0), Rebuild the mesh (adds Tnpix Garment), Quick Cloth's own Quality (Draft: Substeps 2, Iterations 2; Preview: 4, 3; Final: 9, 4), Smoothing iterations (default 5), Add gravity, Add Standard material with the ceiling held on the body, and an optional collider. Make Selected Cloth then builds Garment > Gravity > Collision > Material Standard > Solver on every selected mesh. To open the window for the artist, run `tpaOpenTool "TenPix_01_QuickCloth.ms"` (7.7).

**By hand.** `addModifier` puts each new modifier on top of the stack, so add the modifiers bottom first. Measure the mesh before you rebuild it:

```maxscript
global tpaEdge
-- the mean edge length of o's mesh as it is now, in the scene's unit
fn tpaEdge o = (
    local m = snapshotAsMesh o
    local tot = 0.0, n = 0
    for f = 1 to m.numfaces do (
        local fc = getFace m f
        local a = getVert m fc.x, b = getVert m fc.y, c = getVert m fc.z
        tot += (distance a b) + (distance b c) + (distance c a)
        n += 3
    )
    delete m
    if n > 0 then tot / n else 0.0
)
```

```maxscript
undo "TenPix: make cloth" on (
    local g = $Sheet
    local e = tpaEdge g                                -- the modelled density, measured before any rebuild
    addModifier g (Tnpix_Garment())                    -- only on a mesh nothing else follows (see below)
    g.modifiers[#Tnpix_Garment].edgeLength = e         -- scene units; smaller = more detail and a slower solve
    addModifier g (Tnpix_Gravity())                    -- Earth gravity in the scene's unit
    addModifier g (Tnpix_Collision())
    addModifier g (Tnpix_Material_Standard())
    TnpixTool.goldPreset g 0                           -- Cotton (approx); the stock fabrics are listed in 7.5
    TnpixTool.goldSetAt g 0 "stretchBodyLimit" 1.0     -- "limit where it touches the body", as Quick Cloth sets it
    addModifier g (Tnpix_Solver())                     -- last, so on top
    TnpixTool.colAdd g $Body                           -- an object collides only once it is in the list
)
```

**Tnpix Garment rebuilds the mesh, and that changes its point count.**

- **Leave it out** when the mesh is already clean, even triangles, as most modelled garments are.
- **Never add it to a mesh that something else follows:** a Tnpix Wrap that uses the garment as a proxy (3.4), a Skin Wrap, or a Morpher target. They stop following until they are bound again, and the Wrap's status line then reads "proxy ... changed since the bind". Render meshes often follow simulation meshes this way.
- **Its Edge length is in the scene's unit**, and it decides the density and with it the time each frame takes. Start from the mesh's own mean edge (`tpaEdge`), never from a fixed number: 2.0 is 2 inches in an inch scene and 2 metres in a metre scene.

### 4.2 An outfit: several garments in one Solver group

Garments that must touch each other need the same Solver instance. Share Gravity, Collision and Self Collision across them as single instances too. Before you start, run the report (3.3) and the Wrap check (3.4): a garment that a render mesh follows through a Tnpix Wrap must keep its point count, so it gets no Tnpix Garment.

**Layers.** Take the garments in dressing order, innermost first. In the Self Collision's garment list, layer 0 lies against the body and higher numbers lie further out. With Layer ordering on, where two garments on different layers meet, the lower one holds and the upper one gives way, `layerHoldStrength` times harder (4 by default), and the outer garment's friction acts between them (3.7). The garment list stores four parallel arrays (handles, layers, frictions, thicknesses); `tpaGarmentEntry` adds a garment or changes its entry and keeps the four in step.

```maxscript
global tpaGarmentEntry, tpaInch
-- one inch in the scene's unit: 1.0 in an inch scene, 2.54 in a centimetre scene
fn tpaInch = (
    local m = case units.SystemType of (
        #inches: 0.0254
        #feet: 0.3048
        #miles: 1609.344
        #millimeters: 0.001
        #centimeters: 0.01
        #meters: 1.0
        #kilometers: 1000.0
        default: 0.0254
    )
    0.0254 / (m * units.SystemScale)
)
-- add garment g to Self Collision sc's garment list, or change its entry: its layer (0 = against the body),
-- its own friction and its own thickness (-1 = not set); returns its row in the list
fn tpaGarmentEntry sc g layer fric thick = (
    local h = g.inode.handle
    local k = findItem (sc.memberHandles as array) h
    if k == 0 do ( append sc.memberHandles h; k = sc.memberHandles.count )
    while sc.memberLayers.count < k do append sc.memberLayers 0
    while sc.memberFrictions.count < k do append sc.memberFrictions -1.0
    while sc.memberThicknesses.count < k do append sc.memberThicknesses -1.0
    sc.memberLayers[k] = layer
    sc.memberFrictions[k] = fric
    sc.memberThicknesses[k] = thick
    k
)
```

Each garment gets its own material, with its own friction and grip. Here the shirt and the coat take Material Standard and the jacket takes Material Advanced:

```maxscript
undo "TenPix: outfit" on (
    local order = #($Shirt, $Jacket, $Coat)            -- innermost first; no Tnpix Garment on a Wrap's proxy (3.4)
    local inch = tpaInch()                              -- one inch in the scene's unit
    for o in order do (
        if o == $Jacket then (
            local ma = Tnpix_Material_Advanced()
            addModifier o ma
            local k = tpaMatIndex o ma
            TnpixTool.matPresetAt o k 4                 -- Heavy Fabric; a preset resets every dial first
            TnpixTool.matSetAt o k "friction" 0.6       -- then its own friction and grip (3.7)
            TnpixTool.matSetAt o k "grip" 4.0
        ) else (
            addModifier o (Tnpix_Material_Standard())
            TnpixTool.goldPreset o 0                    -- Cotton (approx); friction 0.35 and grip 3, switched on
        )
    )
    local sc = Tnpix_Self_Collision()
    sc.tnEnabled = true
    sc.thickness = 0.15 * inch                          -- a radius, in scene units: layers settle about twice this apart
    sc.friction = 0.0                                   -- acts only where no material sets friction (3.7)
    sc.overrideMaterialFriction = false                 -- each garment's material friction acts
    sc.mode = 2                                         -- Optimized
    sc.layerOrdering = true                             -- the lower layer holds, the upper one gives way
    sc.layerHoldStrength = 4.0
    local grav = Tnpix_Gravity()
    local col = Tnpix_Collision()
    local s = Tnpix_Solver()
    for i = 1 to order.count do (
        local o = order[i]
        addModifier o sc
        addModifier o grav
        addModifier o col
        addModifier o s                                 -- the same instance: one Solver group
        tpaGarmentEntry sc o (i - 1) -1.0 -1.0          -- shirt layer 0, jacket 1, coat 2
    )
    TnpixTool.colAdd order[1] $Body                     -- the collider list is group-wide: the body, the boots ...
)
```

- **One garment's entry.** `tpaGarmentEntry (tpaFirst $Jacket Tnpix_Self_Collision) $Jacket 1 -1.0 0.3` gives the jacket a shell of its own, 0.3 in the scene's unit, and keeps its layer. A garment's own friction in the list acts only where no material sets friction, unless Override material friction is on (3.7).
- **Self-collision thickness.** It is a radius: two layers settle about twice this far apart. The panel suggests 0.05 to 0.30 inch, and a new modifier takes 0.15 inch in the scene's unit.
- **Adding an existing garment to a group.** Add the group's shared modifiers and its Solver instance to it, for example `addModifier $Pants (tpaFirst $Shirt Tnpix_Solver)`. An object carries one Solver, so a garment that has its own Solver must lose it first; ask before removing it. In the TenPix Graph, the artist can use + Add object instead.

### 4.3 Fabric: materials, regions and presets

**Standard or Advanced.** Material Standard has the everyday dials and 12 stock fabrics: start there. Material Advanced is the full model: Shape Memory keeps modelled folds and rolls, plus the Fabric Curve and the mass modes. Use it when a garment or a region must keep its modelled shape, or when the artist asks for it. Both kinds carry their own Friction and Grip (3.7), and one garment can mix them by region.

**Tnpix Material Standard** has no MAXScript properties for its dials. An assignment such as `mat.stretchBodyLimit = 1` does nothing at all, and does it silently. Read and write the dials by name, as listed in 7.6, and check that each call returns `true`. Index 0 is the top-most Standard material on the stack.

```maxscript
TnpixTool.goldPreset $Shirt 2                       -- Denim (approx); writes only the values that fabric carries
TnpixTool.goldSetAt  $Shirt 0 "weight" 400.0        -- g/m2, the number the panel shows
TnpixTool.goldSetAt  $Shirt 0 "bendGoldK" 120.0     -- K bend
TnpixTool.goldSetAt  $Shirt 0 "relDamp" 0.08        -- Relative Damp: about 0.08 for cotton, 0.2 leather, 0.02 silk
TnpixTool.goldSetAt  $Shirt 0 "matFriction" 0.5     -- this fabric's friction, on the body and on the other garments (3.7)
TnpixTool.goldSetAt  $Shirt 0 "matGrip" 3.0         -- its grip on colliders
TnpixTool.goldAt     $Shirt 0                       -- read it back
```

**Tnpix Material Advanced** takes the same approach with `matSetAt` and the other `mat...` functions; out-of-range values are refused, not clamped. A new Advanced material starts with the Medium Fabric values, and its default bend, Shape Memory, keeps the folds the garment was modelled with.

**A region of its own (several fabrics on one garment).** Bind an extra material to the region's channel. A material bound to a channel always keeps its region against a material without a channel, and where two channel-bound materials paint the same points, the higher one wins. Two examples for a collar painted in `shirt_collar`:

```maxscript
-- a) a stiffer Standard fabric on the collar
undo "TenPix: stiffer collar" on (
    local g = $Shirt
    local m = tpaAddBelowSolver g (Tnpix_Material_Standard())   -- directly below the Solver
    local k = tpaGoldIndex g m                                  -- its index for the gold functions
    TnpixTool.goldChanAt g k "shirt_collar"                      -- covers only the collar's paint
    if k == 0 do TnpixTool.goldPreset g 10                       -- Canvas; goldPreset writes the FIRST Standard material only
    TnpixTool.goldSetAt g k "bendGoldK" 500.0                    -- or any dial by name
)
-- b) a collar that keeps its modelled roll and the shirt's weight (Material Advanced)
undo "TenPix: collar keeps its roll" on (
    local g = $Shirt
    local m = tpaAddBelowSolver g (Tnpix_Material_Advanced())
    local k = tpaMatIndex g m
    TnpixTool.matChanAt g k "shirt_collar"
    TnpixTool.matSetBendModelAt g k 1          -- Shape Memory: every fold returns to its modelled angle
    TnpixTool.matSetPairAt g k "bend" 4.0 7    -- Bend Stiffness 4.0 x 1 000
    TnpixTool.matSetAt g k "massMode" 0        -- Unchanged: the collar keeps the weight of the material under it
)
```

Some values act per region and some do not:

- **Per region on a Standard material:** weight, velocity damping, Motion Damping, max strain, K bend, K stretch, K shear, Relative Damp, the damping ratios, damp bend, friction and grip.
- **Friction per region on both kinds:** a material bound to a channel brings its own friction and grip to the points it covers, so a jacket's shoulders can grip the body harder than its sleeves.
- **For the whole Solver:** Accurate strain limit, Solve steps per iteration and Multi-res levels.
- **Per region on an Advanced material:** Stretch Stiffness, Edge Stiffness, and Shear Stiffness under the Standard stretch type.
- **A garment with two materials and no channel:** only the higher one acts. Give a garment one material without a channel.

**Preset files.** `TnpixPreset` saves and loads the same files as the Presets rollout: `.tpstd` for Standard, `.tpadv` for Advanced, `.tpsoft` for Soft Body. A preset stores the fabric, not its channel binding.

```maxscript
m = tpaFirst $Shirt Tnpix_Material_Standard
f = TnpixPreset.folder() + "\\Heavy denim.tpstd"
-- saving writes a file: check doesFileExist f first and ask before replacing one
TnpixPreset.save m f
TnpixPreset.load (tpaFirst $Jacket Tnpix_Material_Standard) f    -- values applied, or -1 if refused
TnpixPreset.why()                                                  -- what the last save or load did
TnpixPreset.names m                                                -- the Standard presets in the folder
```

### 4.4 Colliders

```maxscript
TnpixTool.colAdd $Shirt $Body       -- as Pick Object: refuses duplicates, non-meshes and the cloth itself
TnpixTool.rows   $Shirt             -- every row with its number and settings
TnpixTool.colSet $Shirt 0 5 0.3     -- row 0, field 5: Thickness, in scene units
TnpixTool.colSet $Shirt 0 11 2      -- row 0, field 11: Override material (0 Off, the default; 1 Unpainted cloth only; 2 Everything)
TnpixTool.colSet $Shirt 0 6 0.5     -- row 0, field 6: Friction (the rows printout's DynSlide); acts only with Override material 1 or 2
TnpixTool.colSet $Shirt 0 8 3.0     -- row 0, field 8: Grip; the same
```

- **Friction against a body** is normally the garment's material (3.7). Use a row's Override material 2 only when this collider must decide whatever the cloth: ice, a sticky surface.
- **The list is group-wide:** rows picked on any member of a Solver group are merged.
- **The fields** are listed in 7.6. Values outside a setting's range are clamped.
- **Poke-through.** The first fix is the row's Thickness (default 0.15 inch in the scene's unit), then the Solver's Substeps.
- **Collision system.** The Solver's `collisionSystem` defaults to 4, Surface (True Geometry), which uses the collider's actual triangles. A Proxy value is greyed under this system.
- **Thin or open colliders.** Two-sided mesh (field 1) is for a thin sheet, and Open mesh (field 2) for an open mesh that still has an inside; a new row has both on.
- **Low-polygon facets** printing through the cloth: raise Mesh Smooth on the row (field 9) or Mesh contact smoothing on the Solver.
- **An endless floor.** Set `unlimitedGround = true` on the Solver: a floor at Z = 0 with no ground object.

### 4.5 Painting a channel from script

Painting needs three things:

- the object selected, with its Tnpix Channel as the current object in the Modify panel;
- that Channel on exactly one object; an instanced Channel refuses;
- dab centres in the object's own space: the coordinates its vertices have before the node is moved.

A dab lands on the channel selected on the panel; after `chanAdd`, that is the new channel. Painting works reliably on a Tnpix Channel added through `modPanel.addModToSelection` while the object is selected in the Modify panel.

```maxscript
(
    local g = $Shirt
    max modify mode
    clearSelection()
    select g
    local ch = tpaFirst g Tnpix_Channel
    if ch != undefined then (
        modPanel.setCurrentObject ch                 -- paint into the garment's own Tnpix Channel
        completeRedraw()
    ) else (
        local below = tpaFirst g Tnpix_Garment       -- the new Channel goes directly above Tnpix Garment ...
        if below == undefined and g.modifiers.count > 0 do below = g.modifiers[g.modifiers.count]   -- ... or above the bottom modifier
        if below != undefined do modPanel.setCurrentObject below    -- 3ds Max adds a modifier above the current one
        modPanel.addModToSelection (Tnpix_Channel())
    )
    local ok = TnpixTool.chanAdd g "shirt_collar" 0.0      -- every point at 0; the new channel is selected
    if ok do (
        TnpixTool.chanStroke g true                         -- the dabs count as one stroke
        for p in #([0, -6, 58], [4, -5, 58], [8, -3, 58]) do TnpixTool.chanPaint g p 2.0 0 1.0   -- centre, radius, mode 0 Add, strength
        TnpixTool.chanStroke g false
    )
    "shirt_collar: " + ((TnpixTool.chanCount g "shirt_collar" 0.5) as string) + " points at 0.5 or more"
)
```

- **Approval.** Where a part lies is the artist's judgement. Show the weights (3.6) and get their OK before you bind anything to the channel. The artist can also paint the region themselves, which is often faster.
- **Modes and strength.** The modes are 0 Add, 1 Subtract, 2 Replace and 3 Smooth. The strength is how far one dab moves the weight toward the panel's Value.
- **Check the result** with `chanCount` at several levels (for example 0.99, 0.5 and 0.01).
- **One layer only.** `(tpaFirst g Tnpix_Channel).pick = 1` sets the paint brush's Picks to On the surface: it paints only the points the cloth reaches from the point pressed on, not a layer lying over or under it. Check script dabs with `chanCount` and the weights display.
- **Painting into an existing channel.** The documented interface has no call that selects an existing channel. Ask the artist to click it in the Channel list; `TnpixTool.chans` shows which row is selected.
- **Mirror.** `TnpixTool.chanMirror g 1 0.1` copies the selected channel's weights from the −X side to the +X side. Sides 0 to 5 are listed in 7.6.
- **A tear line.** `TnpixTool.tearCut g "tear_line" #([-40,0,0], [-20,4,0], [0,0,0]) [0,0,-1] 2.0` cuts a line into the mesh and marks it in the channel. It needs no Modify panel, and `TnpixTool.tearRemove g 0` removes the last cut.
- **Deleting a channel.** `TnpixTool.chanRemove` deletes a channel together with its tear-brush lines. Ask first.
- **Changing the mesh.** If the mesh below the Channel changes (another Edge length, for example), every channel carries its paint over by position.

### 4.6 Pins

A Pin holds a painted region in place, or makes it follow an object.

```maxscript
undo "TenPix: pin the waist" on (
    local p = tpaAddBelowSolver $Skirt (Tnpix_Pin())
    p.channel = "skirt_waist"        -- a channel on this stack
    p.weight = 1.0                   -- 1 follows fully; 0.5 follows half the motion and sags behind
    p.followObject = $Hips           -- undefined: the region holds in place
)
```

- **One Pin on the stack.** `TnpixTool.pinSet $Skirt "skirt_waist" 1.0 $Hips` sets channel, weight and object in one undoable call. With more than one Pin, set the properties on the Pin you mean.
- **Hard and soft pins.** For a hard pin, paint the region at 1 and use Weight 1. For a region that should hold almost firm, use a Weight of 0.9 to 0.99.
- **Dynamic.** `dynamic = true` keeps the pinned points' mass, so gravity, damping and collision still act on them, and a released point keeps its own velocity. Off, the object moves the points directly; use that for cloth pinned to a body.
- **Release at a frame.** `activeTime = true` with `activeFrom` and `activeTo` limits the pin to a frame range. At `activeFrom` the pin takes the points where they are; after `activeTo` it lets go.
- **Keep pinned points out of colliders.** A pinned point inside a body jitters.
- **A part that follows the character's own animation**, such as a cuff on a skinned arm, works better with Preserve (4.7). A Pin attaches each point to the nearest part of the object at the frame it takes hold, so with the arm close to the body, the armpit attaches to the body.

### 4.7 Preserve

A Preserve makes a painted region follow the animation of the mesh below the Tnpix Solver, instead of simulating it. That animation can come from a Skin, Skin Wrap, Tnpix Wrap, Morpher, Point Cache, or anything that moves the mesh.

```maxscript
undo "TenPix: preserve the cuffs" on (
    local pv = tpaAddBelowSolver $Shirt (Tnpix_Preserve())
    pv.channel = "shirt_cuffs"
)
```

- **It needs animation below the Solver.** Check that the garment is deformed below its Solver. Without such animation, a preserved region stays where it was modelled.
- **The paint is the strength:**

  | Painted | The point |
  |---|---|
  | 1 | Sits exactly on the animation, on every frame. It is ignored by every collision (colliders, ground, self collision, other garments) and pushes nothing. |
  | Between 0 and 1 | Follows that share of the animation: 0.5 follows half, 0.75 three quarters. It is still simulated, so it still collides. |
  | 0 | Is simulated, as without a Preserve. |

  Paint 1 where the part must ride exactly, falling to 0 over two or three rows into the simulated cloth. Keep the hard edge (paint 1) where no other cloth has to rest on it.
- **Stack position.** Its place in the stack does not change what it follows. On the same point it wins over a Tnpix Pin.
- **Frame by frame.** Play from the first frame with Real Time off, or simulate frame by frame (4.15), and every frame follows the animation exactly. Frames skipped by a jump ahead on the timeline are approximated.

### 4.8 Stitches

A Stitch sews the painted points of one garment to another garment in the same Solver group, or to the garment's own folded parts.

```maxscript
undo "TenPix: sew the pocket" on (
    local st = tpaAddBelowSolver $Pocket (Tnpix_Stitch())
    st.channel = "pocket_seam"       -- only painted points stitch
    append st.stitchTo $Jacket       -- must carry the same Tnpix Solver as $Pocket
    st.tightness = 1.0               -- 1 sewn shut; 0 a rigid tack that keeps the modelled gap
    st.strength = 1.0                -- about 0.5 holds; 0.8 and above is sewn shut
)
```

- **Stitch to self.** `stitchToSelf = true` stitches a rolled cuff or a tucked flap to the cloth's own folded parts.
- **Search distance.** `searchDistance` is how far a painted point looks for a surface. A new modifier takes 0.5 inch in the scene's unit. Raise it, or move the pieces closer, when the Stitch status line says the points are out of reach.
- **A seam that opens between stitch points** has sparse paint: paint more of the seam.

### 4.9 Tears

```maxscript
undo "TenPix: tear along the band" on (
    local t = tpaAddBelowSolver $Sheet (Tnpix_Tear())
    t.tearBy = 0                     -- 0 Map (inside the channel), 1 Stretch (anywhere), 2 Pressure (with a Tnpix Volume)
    t.channelName = "tear_band"
    t.threshold = 10.0               -- Map and Pressure: lower tears sooner
)
```

- **Order of work.** Settle the Solver's Substeps and Iterations first: a Threshold holds for the Substeps and Iterations it was typed at. Then play, read the Tear status line (it shows the strongest pull reached), and set the Threshold just below that value. The status line is on the panel, so ask the artist to read it, or step the Threshold and show the result.
- **Tearing by stretch.** `tearBy = 1` with `stretchRatio = 0.1` tears where an edge gets 10 percent longer. No paint is needed.
- **Tearing point by point.** With `weakMin` below `weakMax`, a painted region tears point by point instead of all at once.
- **An exact line.** Use the tear brush: `TnpixTool.tearCut` (4.5).
- **A Tearing Sample.** The toolbar's Tearing Sample builds a complete tearing scene to start from.

### 4.10 Volume

```maxscript
undo "TenPix: keep the shape" on (
    local v = tpaAddBelowSolver $Pillow (Tnpix_Volume())
    v.mode = 0                       -- 0 Keep volume, 1 Pressure
    v.volumeRatio = 1.0              -- 1.3 asks for 30 percent more, if the fabric can stretch that far
    v.softness = 0.0                 -- higher lets contact squash it and recover over time
)
```

- **Closed meshes.** On a whole object the mesh must be closed. Each object needs its own Volume.
- **A painted region.** `volumeChannel` makes the Volume hold only the painted area of a body, measured against a centre: `volumeCentre` is a bone or helper inside the region, or `undefined` for the middle of the painted points.
- **Float.** `buoyancy = true` with `buoyancyFill = 1` (Fill) and `fillInside` (0 Helium, 1 Hot air, 2 Air, 3 Water, 4 Custom) rises, floats or sinks as the real thing would.
- **The fabric's stretch limit caps the inflation.** The default fabric encloses about 1.15 times its rest volume at its limit.

### 4.11 Rigid pieces and the Rigidity mix

Tnpix Rigid makes painted regions, or separate mesh elements, solid pieces inside the cloth: buttons, buckles, a stiffened collar, an armour plate. **Rigidity is a mix:**

| Rigidity | The piece |
|---|---|
| 1 | Rigid: keeps its modelled shape and moves as one body. |
| 0.75 | A stiff leather patch. |
| 0.5 | Draped over a body, it bends about half as much as the cloth around it. |
| 0.25 | A soft patch. |
| 0 | Off: moves as the cloth around it. |

Below 1, a piece meets a collider partly as one body (Bounce, Friction) and partly as the cloth around it. Rigidity can be keyed.

```maxscript
undo "TenPix: rigid collar" on (
    local r = tpaAddBelowSolver $Shirt (Tnpix_Rigid())
    r.piecesFrom = 0                 -- 0 painted channel, 1 mesh elements
    r.channel = "shirt_collar"
    r.threshold = 0.5                -- paint at or above this is rigid
    r.eachRegion = true              -- every connected painted region is its own piece
    r.rigidity = 0.75                -- the mix the artist chose
    r.massMode = 0                   -- By density; an open patch has no inside and weighs its cloth
    r.density = 0.5                  -- g/cm3 for closed pieces: wood 0.5, plastic 1.0 to 1.4, steel 7.8
)
TnpixTool.rigidInfo $Shirt           -- after a simulation starts: the pieces and their points
```

The Rigid's own switch is named `enabled`, so from MAXScript the 3ds Max light bulb shadows it. Use the light bulb.

**Scenes from earlier versions.** A Tnpix Rigid from a scene of an earlier version keeps that version's Rigidity: any value above 0 holds its pieces fully rigid. Only a newly added Tnpix Rigid mixes. So if the artist wants a mix in such a scene, or a Rigidity between 0 and 1 still looks fully rigid, offer to replace that Rigid with a new one that has the same channel and settings. Replacing removes a modifier, so get their yes first.

```maxscript
global tpaRenewRigid
fn tpaRenewRigid o old = (
    local idx = 0
    for i = 1 to o.modifiers.count where idx == 0 and o.modifiers[i] == old do idx = i
    local r = undefined
    if idx > 0 do undo "TenPix: renew Tnpix Rigid" on (
        r = Tnpix_Rigid()
        addModifier o r before:idx           -- right below the old one ...
        r.piecesFrom = old.piecesFrom
        r.channel = old.channel
        r.threshold = old.threshold
        r.eachRegion = old.eachRegion
        r.rigidity = old.rigidity
        r.massMode = old.massMode
        r.density = old.density
        r.massKg = old.massKg
        r.massMul = old.massMul
        r.bounce = old.bounce
        r.friction = old.friction
        r.airResistance = old.airResistance
        r.spinResistance = old.spinResistance
        r.name = old.name
        deleteModifier o idx                 -- ... then the old one goes and the new one takes its place
    )
    r
)
-- tpaRenewRigid $Shirt (tpaFirst $Shirt Tnpix_Rigid)
```

The function copies a keyed Rigidity as its value at the current frame, so key the new Rigid again. A Rigid shared by several garments is replaced per garment, one call each.

### 4.12 Gravity

```maxscript
-- a Solver group needs one Tnpix Gravity, one instance shared by its garments: add it only where the group has none
(
    local sv = tpaFirst $Shirt Tnpix_Solver
    local has = for o in (tpaUsers sv) where (tpaFirst o Tnpix_Gravity) != undefined collect o.name
    if has.count > 0 then ("Gravity is already on: " + (has as string))
    else (
        undo "TenPix: gravity" on (
            local g = tpaAddBelowSolver $Shirt (Tnpix_Gravity())     -- a new one pulls with Earth gravity in the scene's unit
            for o in (tpaUsers sv) where o != $Shirt do tpaAddBelowSolver o g
        )
        "Gravity added to " + ((tpaUsers sv).count as string) + " garment(s)"
    )
)
```

- **Magnitude and direction.** The pull is `magnitude`, in scene units per second squared, along `direction`; only the direction of that vector counts, not its length. A new Gravity has direction [0,0,1] and a negative magnitude (−386.22 in an inch scene), so it pulls down. Do not change the direction to [0,0,−1] to correct it: with the negative magnitude, gravity would then pull up.
- **Lower magnitude** gives a slow-motion look; a tilted `direction` gives a steady sideways pull.
- **Off.** `tnEnabled = false` switches gravity off for a comparison without removing the modifier.

### 4.13 Wind

**TenPix Wind** is a wind made for cloth: it blows on every face as air, with gusts of real sizes and a wind shadow. It acts on a cloth only through that cloth's Tnpix Forces list. Speeds are in m/s and sizes in metres, whatever the scene's unit. Set its properties on its base object.

```maxscript
undo "TenPix: wind" on (
    local pos = [-150, 0, 100]                                -- scene units, upwind of the cloth
    local w = TenPixWind pos:pos name:"TPWind"
    w.transform = matrix3 [0, 1, 0] [0, 0, 1] [1, 0, 0] pos     -- rows: icon X, icon Y, arrow (icon Z), position: blows along +X
    local b = w.baseObject
    b.mode = 0                     -- 0 Automatic, 1 Map
    b.windType = 0                 -- 0 Planar, 1 Fan, 2 Point
    b.speed = 5.0                  -- m/s: 1 a light air, 5 a moderate breeze, 15 a near gale
    local fx = tpaFirst $Flag Tnpix_Forces
    if fx == undefined do fx = tpaAddBelowSolver $Flag (Tnpix_Forces())
    append fx.forceNodes w
    append fx.forceMuted 0         -- parallel to forceNodes: 0 acting, 1 muted
)
```

**Aiming.** The arrow is the icon's own Z axis, and the icon's X and Y are the direction map's "across" and "up". Set the transform with the rows X, Y, arrow and position. These rows keep the map's "up" pointing up in the world:

| Blows along | `w.transform = matrix3 X Y Z pos` |
|---|---|
| +X | `matrix3 [0,1,0] [0,0,1] [1,0,0] pos` |
| −X | `matrix3 [0,-1,0] [0,0,1] [-1,0,0] pos` |
| +Y | `matrix3 [-1,0,0] [0,0,1] [0,1,0] pos` |
| −Y | `matrix3 [1,0,0] [0,0,1] [0,-1,0] pos` |

Any right-handed set of rows works. For example, `matrix3 [0,0,-1] [0,1,0] [1,0,0] pos` also blows along +X; with it, the icon's X points down, so the map's "across" is vertical.

The other TenPix Wind settings:

- **Gusts.** `terrain` 0 Open land, 1 Suburb, 2 City; or set `gustStrength` and `biggestGust` yourself.
- **Direction drift.** `wander` is how far the direction drifts, in degrees.
- **Fade.** `falloff` fades the wind with distance.
- **Repeatability.** The gusts come from `seed`, and two bakes of the same scene are the same.
- **Shelter.** `shadow` is on by default: cloth behind a fold, another garment of the Solver, a collider, or an object in `shadowNodes` gets slower, gustier air.

**Map mode and direction maps.** In Map mode (`mode = 1`), `map` shapes where and how hard the wind blows: white is the full Speed, black none. With no map, the full Speed blows everywhere. `directionMap` turns the wind. Its colours are read in the picture's own frame:

| Colour | Turns the wind toward | 0 .. 1 means |
|---|---|---|
| Red | Across the map, left to right: the Wind icon's X | −1 .. +1 |
| Green | Up the map, bottom to top: the icon's Y | −1 .. +1 |
| Blue | Along the arrow | −1 .. +1 |

(0.5, 0.5, 1), or (128, 128, 255), blows straight along the arrow. The map's 0,0 is on the Wind's arrow, and one map (0..1) covers the Wind's `mapSize`, in metres.

- **Moving maps.** A map that changes over time, such as an animated map or an OSL map driven by its Time input, is read every frame and stays fast. The first frame after opening the scene, or after editing such a map, takes longer, because the map is read once along the timeline.
- **What shows the swirl.** Air running along the cloth's surface grips it through `dragAlong` (Drag along, default 0.02). Air meeting it face on pushes through `pushAcross` (Push across, default 1.2). A flat sheet facing the wind therefore shows a swirl only faintly, while folds, flags and garments show it.

**The samples.** The installer's `samples\Wind direction maps` folder sits beside the TenPix scripts folder. It holds 8 OSL shaders and 8 PNG pictures with the same names (`TenPix_WindDir_01_Straight` … `08_Turbulent`). Every OSL sample has a UVW input and a Time input in seconds that follows the time slider, plus its own settings, all of which can be animated. Leave UVW unconnected and the Wind provides it; connect a UVW Transform map to move, scale or turn the pattern. Anyone can copy a sample to write their own: keep its `tpWindColour` and `tpWindTurn` functions and change what the shader computes.

| Sample | The wind | Settings (MAXScript name = default) |
|---|---|---|
| 01 Straight | One direction everywhere; can sway | `Across`=0, `Up`=0 (deg), `Sway`=0 (deg), `SwayPeriod`=2 (s), `SwayWaves`=0 |
| 02 Swirl | Turns around a centre; the middle is calm | `CenterU`=0, `CenterV`=0, `Turn`=40, `Calm`=0.18, `Clockwise`=0, `DriftU`=0, `DriftV`=0 |
| 03 Spread | Blows outward from a centre, like a fan or a blast | `CenterU`, `CenterV`, `Turn`=35, `Calm`=0.25, `DriftU`, `DriftV` |
| 04 Gather | Blows in toward a centre, like a draught into an opening | `CenterU`, `CenterV`, `Turn`=35, `Calm`=0.25, `DriftU`, `DriftV` |
| 05 Rising | Lifts more toward the top, as over a slope | `Bottom`=0, `Top`=45 (deg), `DriftV`=0 |
| 06 Split | Parts left and right, as around something | `Position`=0, `Turn`=31, `Softness`=0.1, `DriftU`=0 |
| 07 Wave | Swings side to side in bands that travel up the map | `Waves`=2, `Swing`=29, `Speed`=0.5 (waves/s), `Phase`=0 |
| 08 Turbulent | Swirls that change over time and can drift | `Swirls`=4, `Turn`=37, `Speed`=0.25, `Phase`=0, `DriftU`, `DriftV` |

Centres and drifts are measured in maps from the Wind's arrow (drifts in maps per second); turns are in degrees.

```maxscript
-- the OSL Swirl in the Wind's Direction map
(
    local d = if TenPixCloth_Dir == undefined then "" else (getFilenamePath (trimRight TenPixCloth_Dir "\\")) + "samples\\Wind direction maps\\"
    local f = d + "TenPix_WindDir_02_Swirl.osl"
    if not (doesFileExist f) then ("No sample at " + f + ": ask the artist where the TenPix samples folder is.") else (
        local m = OSLMap()
        m.OSLPath = f
        try ( m.OSLAutoUpdate = true ) catch ()
        m.name = "Swirl"
        local b = $TPWind.baseObject
        undo "TenPix: wind direction map" on (
            b.mode = 1                 -- Map
            b.directionMap = m
            b.projection = 0           -- 0 along the wind (projected from the icon along its arrow), 1 3D around the icon
            b.mapSize = 1.0            -- metres: one map
            b.travel = false           -- the pattern stays where the Wind puts it
        )
        m.Turn = 40.0                  -- the shader's settings are properties of the OSL Map
        "Swirl set"
    )
)
-- a PNG sample instead: bt = Bitmaptexture filename:(d + "TenPix_WindDir_02_Swirl.png"); bt.filtering = 2; b.directionMap = bt
```

**A 3ds Max Wind** (or Drag, Vortex, Gravity, Motor, Push, PBomb) in a Tnpix Forces list acts with its own 3ds Max force; only a TenPix Wind is air. A Wind at Strength 1 pushes about as hard as gravity pulls. A Wind created from MAXScript starts with Decay, Turbulence and Frequency at 1.0, so pass `decay:0.0` or it dies off within a few units:

```maxscript
w = Wind pos:[0,-200,80] strength:1.0 decay:0.0 turbulence:0.3 frequency:2.0
w.rotation = eulerAngles 90 0 0
fx = tpaFirst $Flag Tnpix_Forces                     -- the garment's own Tnpix Forces, if it has one
if fx == undefined do fx = tpaAddBelowSolver $Flag (Tnpix_Forces())
append fx.forceNodes w
append fx.forceMuted 0
```

Tnpix Forces settings:

- **Each garment is pushed by its own Forces.** One instance shared across a Solver group pushes every garment alike.
- **Strength.** `strength` multiplies every warp in the list.
- **Mute.** `forceMuted[i] = 1` mutes one warp without removing it.
- **Push only part of a garment.** `forceChannel` limits the push to a painted channel, such as a sleeve or a hem.
- **Zones.** `zoneOn` with `zoneHelpers` (Influence Helpers) limits the push to a zone.

The toolbar's Forces window lists every Tnpix Forces in the scene with its warps' dials.

### 4.14 Quality presets

The Solver's Preset list sets six values together; Stretch quality is not part of a preset. Setting the same values from a script gives the same quality, and the panel then shows that preset.

```maxscript
global tpaPresetValues, tpaSetPreset
-- substeps, iterations, contact passes, smoothing, post collision passes, fast motion collision (ccd)
fn tpaPresetValues p = (
    if p == #draft then #(1, 1, 1, 5, 0, false)
    else if p == #tight then #(6, 2, 2, 10, 2, false)
    else if p == #fast then #(8, 2, 2, 10, 2, true)
    else if p == #high then #(8, 3, 3, 10, 3, true)
    else if p == #ultra then #(15, 8, 7, 10, 3, true)
    else #(4, 2, 1, 10, 0, false)                     -- #default: a new Solver's set
)
fn tpaSetPreset sv p = (
    local v = tpaPresetValues p
    undo "TenPix: Solver preset" on (
        sv.substeps = v[1]
        sv.iterations = v[2]
        sv.contactPasses = v[3]
        sv.smoothingIterations = v[4]
        sv.postCollisionPasses = v[5]
        sv.ccd = v[6]
        sv.deepRescue = false                          -- every preset sets it off
    )
)
-- tpaSetPreset (tpaFirst $Shirt Tnpix_Solver) #tight
```

| Preset | For |
|---|---|
| Draft | Blocking. |
| Tight clothes | Trousers and sleeves over bending joints. |
| Fast motion | Kicks and swinging hands. |
| High quality | The final. |
| Ultra quality | The finest result in one go, and the slowest; most shots do not need it. |

- **Substeps** divide each frame and evaluate everything again, collision included. They are the main fix for fast motion and the first thing to raise.
- **Iterations** only tighten a solve that is nearly right; they do not evaluate collision again.
- **Cost.** Substeps × Iterations is the first number to look at when a scene is slow.
- **Contact passes** follow a rule: Iterations or Stretch quality of 4 or more want at least 4 contact passes; 8 or more want at least 7.
- **Deep rescue** (`deepRescue`, Surface only) moves back outside any cloth a body has come through. It adds time.
- **Many Solvers at once.** The toolbar's Quality window applies the same presets to one Solver or many.

### 4.15 Simulate

```maxscript
-- simulate garment g up to frame f, one frame at a time from the first frame of the range, as playing does
global tpaSimTo
fn tpaSimTo g f = (
    local n = 0
    for t = (animationRange.start.frame as integer) to f do n = TnpixTool.sim g t
    sliderTime = (f as time)
    n                                  -- how many frames are stored
)
-- tpaSimTo $Shirt 30   then capture; tpaSimTo $Shirt 60, capture again
```

- **What `sim` does.** `TnpixTool.sim node frame` evaluates the cloth up to a frame, as scrubbing does, for the node's whole Solver group. Frames already stored are read back from memory.
- **Frame by frame for Preserve.** With a Tnpix Preserve, go frame by frame as above, so every frame follows the animation exactly.
- **No Reset needed after a change.** Any change to a simulation setting simulates again from the first frame. To simulate again without changing anything, `TnpixTool.reset()` clears the stored frames, as Reset Simulation does. Ask first: it throws away what is in memory.
- **The demo** simulates only the first 100 frames, and nothing at all while the simulating garments together have more than 25,000 vertices. Colliders do not count.

**The start shape.** A garment starts as modelled unless its Solver group has a start shape: a drape made with Live at frame 0, or a frame kept from a played simulation. A start shape never changes the fabric's pattern. Changing the start shape needs the artist's yes.

```maxscript
TnpixTool.live $Shirt "start" 8                      -- Live in Fast preview; clears the simulated frames
for i = 1 to 30 do TnpixTool.live $Shirt "step" 1    -- the garments drape at frame 0
TnpixTool.live $Shirt "info" 0                       -- show the drape: capture it
TnpixTool.live $Shirt "keep" 0                       -- with the artist's yes: the drape becomes the start (one undo step)
-- "stop" ends Live and keeps nothing; "keepframe" keeps the frame shown; "clear" goes back to the modelled mesh
```

### 4.16 Cache

**Tnpix Cache** saves the simulation to a file and plays it back:

- **Format.** The file's extension decides the format: `.tnc` (TenPix) or `.abc` (Alembic; the demo saves `.tnc` only).
- **What it keeps.** The cache holds the whole mesh: points, faces, every map channel, material IDs and smoothing groups.
- **One cache per garment.** Give each garment its own Tnpix Cache. One instanced across objects that depend on each other is refused by 3ds Max, so some garments would be skipped.
- **Shared Solver.** On a shared Solver, one save records the whole Solver group.
- **Shared Cache.** A Tnpix Cache shared by several garments writes one file per garment, named `<file>_<garment>`.

```maxscript
-- cache every garment of $Shirt's Solver group, each into its own file in one folder (the artist's folder)
(
    local folder = "D:\\Shots\\sh010\\cloth"
    local gs = tpaUsers (tpaFirst $Shirt Tnpix_Solver)
    local taken = for g in gs where doesFileExist (folder + "\\" + g.name + ".tnc") collect g.name
    local shared = for g in gs where (tpaFirst g Tnpix_Cache) != undefined and (tpaUsers (tpaFirst g Tnpix_Cache)).count > 1 collect g.name
    if taken.count > 0 then ("These files exist - ask before replacing them: " + (taken as string))
    else if shared.count > 0 then ("These garments share one Tnpix Cache - give each its own first (the Cache Manager does): " + (shared as string))
    else (
        makeDir folder all:true
        for g in gs do (
            local cm = tpaFirst g Tnpix_Cache
            if cm == undefined do cm = tpaAddAboveSolver g (Tnpix_Cache())
            cm.file = folder + "\\" + g.name + ".tnc"
            cm.specificRange = false          -- the whole animation range; or true with cm.start / cm.end
        )
        local n = TnpixTool.cacheSave gs[1]   -- frames written, or -1 (the reason is in cacheInfo)
        local s = "cacheSave: " + (n as string) + "\n"
        for g in gs do s += g.name + ": " + (TnpixTool.cacheInfo g) + "\n"
        s
    )
)
```

- **Save.** `cacheSave` records from the first frame of the range wherever the slider is, simulates any missing frames, and turns Play from cache on when it succeeds.
- **Load.** `cacheLoad` opens the Cache's `file` and plays it; `cacheClear` stops playing and forgets the file, deleting nothing.
- **Missing files.** If a garment's file was not written by the group's save, save that garment on its own and check `cacheInfo` again.
- **Progress.** Define a global `tnpixCacheProgressHook done total` function and the save calls it after every frame.
- **Retime and posterize** without simulating again: `retime` (animatable; 0 freezes), `posterizeStep`, `posterizeHold`, `frameOffset`.
- **Motion blur from Alembic.** `writeVelocities` (Alembic only) adds per-point velocities.
- **Order above the Cache.** Put Tnpix Post Process above the Cache. A threads object gets a Tnpix Cache of its own.

**The Cache Manager** (toolbar) is the artist's window for many garments at once:

- **Add** gives each highlighted garment its own Tnpix Cache.
- **Load** always asks. With one garment highlighted it asks for a file, opening at the garment's own file. With several it asks for a folder, in which each garment takes the file named after it, or the shot file a Batch Sim run wrote there (`<garment>_<shot>`). Cancel changes nothing; a garment with no file in the folder keeps what it plays.
- **Save** records into each garment's own file, or into a folder as `<object name>.tnc` / `.abc`. A garment on a shared Solver is saved with its whole Solver group.
- **Clear** stops playing and forgets the file. Nothing is deleted.

Open it for the artist with `tpaOpenTool "TenPix_03_CacheManager.ms"` (7.7).

**The Tnpix Cache panel's "..."** opens, on a Cache with no file yet, in the last folder any Tnpix Cache was given, with the garment's name ready. On a Cache that has a file, it opens at that file.

### 4.17 Batch Sim

Batch Sim (toolbar button **Batch Sim**, script `TenPix_12_BatchSim.ms`) runs the shots of a scene one after another and saves every garment's cache, shot by shot.

- **Garments.** Pick one garment, and every garment on its Tnpix Solver is simulated together.
- **Shots.** Each shot has a name, its first and last frame, and the Tnpix Collision and Tnpix Forces modifiers that are on in it. The modifiers another shot names are off; any other modifier is left as it is.
- **Output.** Files go to `<Folder>\<Shot>\<Garment>_<Shot>.tnc` or `.abc`, with optional velocities for Alembic, and a log of the run beside them. Test frames N runs only the first N frames of each shot, into `<Folder>\_TEST`.
- **Per shot.** For each shot, the run sets the timeline to the shot, switches on that shot's Collision and Forces, resets the simulation, simulates every garment frame by frame, and saves each garment's cache from memory.
- **The caches.** Every garment keeps its own Tnpix Cache: one is added where there is none, and a shared one becomes one per garment. After the run, each garment plays the last shot saved.
- **Afterwards.** The timeline, the slider and the shots' modifiers are put back as they were, and nothing is saved to the scene file. Esc stops the shot running, and that shot is not saved.

The same run is one script command, `TenPixBatchCore`:

```maxscript
TenPixBatch_NoDialog = true                          -- load the core without opening the window
fileIn (TenPixCloth_Dir + "TenPix_12_BatchSim.ms")   -- TenPixCloth_Dir undefined: the toolbar scripts are not loaded (7.7)

-- a shot: #(name, first frame, last frame, #(names of the Tnpix Collision / Tnpix Forces modifiers ON in it))
shots = #(#("Walk", 0, 120, #("Tnpix Collision_Floor")), #("Sit", 150, 300, #("Tnpix Collision_Chair")))

-- check changes nothing and returns #(problems, plan lines); an empty problem list means ready
chk = TenPixBatchCore.check $Robe shots folder:"D:\\Project\\PointCaches\\Cloth" ext:".tnc" testFrames:0 velocities:true

-- run, after the artist's yes; returns #(ok, message, log file)
res = TenPixBatchCore.run $Robe shots folder:"D:\\Project\\PointCaches\\Cloth" ext:".tnc"
```

- **The signatures:**
  - `check garment shots folder:"" ext:".tnc" testFrames:0 velocities:true`
  - `run garment shots folder:"" ext:".tnc" velocities:true preview:false testFrames:0 switched:undefined status:undefined`

  `ext:` is `".tnc"` or `".abc"`. `preview:true` makes a preview per shot. `status:` is a function given each progress line.
- **Modifier names.** A shot names modifiers exactly as their stack names (`m.name`), for example `"Tnpix Collision_Floor"`. Give each Collision and Forces that changes between shots its own name first; renaming is a change, so tell the artist.
- **`switched:`** lists the modifiers switched per shot; by default, every name the given shots use. When you run some of the artist's shots, pass `switched:` with every name the whole shot list uses, as the window does.
- **Run Check first and show its plan to the artist.** A run replaces same-named cache files in its shot folders and resets the simulation. Its changes (caches added, shared caches split) are not one undo step, so save the scene under a new name first. A long run holds 3ds Max until it ends: prefer letting the artist start it from the window, and try Test frames first.
- **Opening the window for the artist.** If you loaded the core, set `TenPixBatch_NoDialog = false`, then run the `fileIn` line again.
- **Loading a shot back.** In the Cache Manager: highlight the garments, Load, and pick the shot's folder.

### 4.18 Reading results

- **Look.** Capture the frames where the behaviour shows: the drape settled, the fastest move, the frame a tear opens. Use the same view and frames before and after a change. In fast, chaotic motion such as a flag in a gale, a small change can produce different folds, so judge the behaviour, not one fold.
- **Measure.** Read positions from the simulated mesh at the current frame:

```maxscript
(
    local m = snapshotAsMesh $Shirt                 -- world space, as simulated at the slider's frame
    local lo = undefined, sum = [0, 0, 0]
    for i = 1 to m.numverts do ( local p = getVert m i; sum += p; if lo == undefined or p.z < lo.z do lo = p )
    local mid = if m.numverts > 0 then sum / (m.numverts as float) else sum
    delete m
    "lowest point " + (lo as string) + ", middle " + (mid as string)
)
```

- **Is it staying on the body?** This is the usual outfit question. A garment can stay close to the body while it slides along it, so its distance to the body does not answer it. `tpaSlip` ties points of the garment to the nearest body points at one frame, and measures how far each has drifted from its body point at a later frame. Each tied point is compared with every body point: for a jacket of 8,000 points on a body of 14,000, `step` 200 takes about a second and `step` 20 about ten.

```maxscript
global tpaSlip
-- how far garment g drifted from where it sat on body b, from frame f0 to frame f1 (simulate up to f1 first, 4.15):
-- every step-th point of g within reach of b at f0 is tied to b's nearest point, and at f1 the distance between the two
-- is measured again. Returns the points tied, the mean and largest drift, and how many drifted further than reach.
fn tpaSlip g b f0 f1 reach step = (
    local g0 = at time f0 (snapshotAsMesh g), b0 = at time f0 (snapshotAsMesh b)
    local g1 = at time f1 (snapshotAsMesh g), b1 = at time f1 (snapshotAsMesh b)
    local s = ""
    if g0.numverts != g1.numverts or b0.numverts != b1.numverts then s = "A mesh changed its point count between the two frames."
    else (
        local tieG = #(), tieB = #(), tieD = #()
        for i = 1 to g0.numverts by step do (
            local p = getVert g0 i, best = 0, bd = reach
            for j = 1 to b0.numverts do ( local d = distance p (getVert b0 j); if d < bd do ( bd = d; best = j ) )
            if best > 0 do ( append tieG i; append tieB best; append tieD bd )
        )
        if tieG.count == 0 then s = "No point of " + g.name + " lies within " + (reach as string) + " of " + b.name + " at frame " + (f0 as string) + "."
        else (
            local sum = 0.0, mx = 0.0, far = 0
            for k = 1 to tieG.count do (
                local dr = abs ((distance (getVert g1 tieG[k]) (getVert b1 tieB[k])) - tieD[k])
                sum += dr
                if dr > mx do mx = dr
                if dr > reach do far += 1
            )
            s = g.name + " on " + b.name + ", frames " + (f0 as string) + " to " + (f1 as string) + ": " + (tieG.count as string) + " points tied, drift mean " + (formattedPrint (sum / tieG.count) format:".3f") + ", largest " + (formattedPrint mx format:".3f") + ", " + (far as string) + " drifted further than " + (reach as string)
        )
    )
    delete g0; delete b0; delete g1; delete b1
    s
)
-- tpaSimTo $Jacket 48 (4.15), then: tpaSlip $Jacket $Body 0 48 1.0 50    (lengths in scene units)
```

  A mean drift close to 0 with a large largest drift means one region slides: capture it, then look at that region's friction (3.7).

- **Read status.** These calls return what the panels show:

  | Call | Returns |
  |---|---|
  | `TnpixTool.cacheInfo` | Frames, file and whether it plays |
  | `TnpixTool.rigidInfo` | Pieces |
  | `TnpixTool.selfColLayers` | Layers |
  | `TnpixTool.wrapInfo` | Proxy memory and the last message |
  | `TnpixTool.threadsInfo` | The Threads status lines |
  | `TnpixTool.postInfo` | The Post Process settings and rest pose |
  | `TnpixTool.live node "info" 0` | Live's status line |
  | `TnpixTool.mbInfo` | Motion Brush layers |

  Other status lines are only on the panels: the Tear's strongest pull, the Stitch's count, a material's stretch. Ask the artist to read one when you need it.
- **The Listener.** Each TenPix line in the MAXScript Listener starts with `TenPix`: a note when a cache is saved, a warning when a demo limit holds the simulation or a collider is gone, an error when a cache cannot be saved or the graphics driver or card cannot run TenPix Cloth. A script relies on return values, not on these lines.

---

## 5. Talking with the artist

> **TenPix's rules for talking with the artist. Follow them every time.**
>
> **a. A named garment part: find, work out, then ask.** When the artist names a part of a garment (collar, cuff, waistband, hem, sleeve, pocket, placket, belt, hood, shoulder pad), first find what is on that part now: which channel and which material region cover it, and any Pin, Rigid, Preserve or Wrap. Work out what is happening to it. **Then ask which behaviour they want, before changing anything, and offer a sensible default with the question.**
>
> **b. With a Tnpix Wrap, offer Preserve.** If the model uses a Tnpix Wrap, it is usually better to keep a part's shape with Tnpix Preserve. **Ask whether to use Preserve, and how strong its effect should be, before adding it.**
>
> **c. Ask little, and ask well.** Ask only questions whose answer changes what you do. One short question with choices beats a long one. Never ask what the scene already tells you.

### 5.1 Find what is on the part

1. **Which garment and which channel.** Read the garment's channel table (`TnpixTool.chans`) and look for the part's name (collar, `shirt_collar`, neck and so on). If no channel covers the part, it is simulated like the rest of the garment.
2. **What reads that channel.** Run `tpaChannelUse g "<channel>"` (3.4). It finds materials, Pin, Preserve, Stitch, Tear, Rigid, Volume, Soft Body, Forces, Post Process, Wrap and Threads.
3. **What moves the garment below its Solver.** Run `tpaStack g`. A Skin, Skin Wrap, Tnpix Wrap or other deformer there is animation that a Preserve can follow. Also check whether a Tnpix Wrap drives this garment, or whether a detailed copy follows it (3.4).
4. **What it does now.** Simulate the frames that matter and capture them. Show the channel's weights if the region is in doubt.
5. **Say it in one line**, in the panels' own words. For example: "The collar is channel `shirt_collar` (412 points). Only the shirt's Cotton material covers it, and nothing pins, stiffens or preserves it, so it folds flat with the shirt (frame 24 attached)."

### 5.2 Ask: the collar example

Put the choices that change the result, mark your default, and say each choice's gain and cost in a few words:

> The collar (`shirt_collar`) is simulated like the rest of the shirt, so it folds flat by frame 24 (capture attached). How should it behave?
> 1. **Stiffer fabric** on the collar's channel. This is my default: a material that remembers the collar's modelled roll and keeps the shirt's weight. It is still cloth and still collides.
> 2. **Rigid**: Tnpix Rigid at Rigidity 1. The collar keeps its modelled shape exactly and moves as one piece.
> 3. **A mix of rigid and cloth**: Tnpix Rigid between 0 and 1. For example, 0.75 is a stiff leather patch, 0.5 bends half as much as the cloth, 0.25 is soft. How much?
> 4. **Keep its modelled shape on the body**: Tnpix Preserve. It rides the animation below the Solver instead of being simulated; where it is painted 1, it no longer collides.

Offer option 4 only when the garment is deformed below its Solver (a Skin, Skin Wrap, Tnpix Wrap and so on). Without that, a preserved collar stays where it was modelled. The artist may answer outside the list ("stiffer, but only at the back"); take that answer as given.

### 5.3 With a Tnpix Wrap: Preserve first, and how strong

Use this when the garment follows a body or proxy through a Tnpix Wrap below its Solver, or when its detailed mesh follows it through a Wrap:

> This shirt follows the body through a Tnpix Wrap. To keep the collar's shape I'd use **Tnpix Preserve** on `shirt_collar`: the collar then rides the wrapped shirt instead of being simulated. Shall I add it, and how strong should it be?
> - **Fully**: paint 1. The collar sits exactly on the wrapped shape and stops colliding there. This is my default at the collar's fold, fading to 0 over two or three rows into the shirt.
> - **Mostly**: 0.75. It follows three quarters of the way, and still simulates and collides.
> - **Half**: 0.5.

A Preserve has no strength dial of its own: its strength is the paint (4.7). Paint what the artist chose, show the weights, and simulate.

### 5.4 Parts and the tools for them

When the scene says nothing that points elsewhere, offer the first option in each row as the default. A Tnpix Wrap on the model puts Preserve first (rule b).

| Part | Options the tools give |
|---|---|
| Collar | Stiffer fabric on its channel (Material Advanced in Shape Memory keeps a rolled collar's roll) · Tnpix Rigid at 1 (a stiffened collar) · a Rigid mix · Preserve on a skinned or wrapped garment · a Pin to a neck object |
| Cuff | Preserve on a skinned or wrapped arm · Stitch to self for a rolled cuff · stiffer fabric on its channel · a Rigid mix |
| Waistband | Preserve on a skinned body, or a Pin that follows the hips · stiffer fabric on its channel |
| Hem | Heavier fabric on its channel (weight acts per region) · a hem that may stretch further (max strain per region) · a Threads fringe along painted edges · a Forces channel to push only the hem |
| Sleeve | Preserve for the top of the sleeve · the Tight clothes preset over a bending elbow · a Forces channel for wind on the sleeve only |
| Pocket, placket | Stiffer fabric on its channel · a Rigid mix (a stiff patch) · a Stitch where it is a separate piece |
| Belt, buckle | Tnpix Rigid: a buckle at 1, a leather belt as a mix (0.75) · the Leather stock fabric on its channel · a Pin or Preserve at the waist |
| Hood | Shape Memory fabric on its channel · Preserve on a skinned or wrapped garment · a Pin |
| Shoulder pad | A Rigid mix · stiffer, heavier fabric on its channel |
| Buttons | Tnpix Rigid, each painted region its own piece, with a density (plastic 1.0 to 1.4) |

### 5.5 Asking well

- **Ask only when the answer changes what you do.** Rigid or a mix, Preserve or not, overwriting a file: these change the result or cannot be undone, so ask. Which substep count to use is not a question: propose one with its reason and cost ("Substeps 4 to 8: the elbow stops passing through; each frame takes about twice as long"), then let the artist override.
- **Never ask what the scene tells you.** Do not ask about the units, the colliders, what is pinned or the frame range; read them.
- **One short question with choices**, a default and its reason. Expect answers outside the list.
- **Never ask the same question twice.** An answer given earlier in the conversation stands, even when it was given informally.
- **Answer a question first.** When the artist asks something, answer it, then offer to act.
- **Speak the artist's language.** Use panel names (Substeps, Contact give, Rigidity, Push across) and real units (g/m², m/s). Show captures rather than describing them.

### 5.6 After the answer

Make the change in one undo step, simulate, capture, and report. For example:

> Changed: Shirt > new Tnpix Rigid on `shirt_collar`, Rigidity 0.75. Frames 0, 24 and 48 attached: the collar keeps its roll and still bends with the neck. Undo: Edit > Undo "TenPix: rigid collar".

If it is not what the artist wanted, take it back and try the next option. Do not change anything else along the way.

---

## 6. Limits and what helps

### Set-up

| Situation | What helps |
|---|---|
| The garment floats | There is no Tnpix Gravity in the Solver group, or it is switched off. |
| The cloth falls through a collider | The object is not in the cloth's Collision list, its row is disabled, or the list's `active` is off. |
| The cloth falls through the floor | A floor object collides only once it is in the Collision list; or turn on the Solver's Unlimited ground (Z = 0). |
| Changes have no effect | A Tnpix Cache is playing from its file. Turn off Play from cache; nothing is lost. |
| The cloth looks frozen in the viewport | Show End Result is off while a modifier below the Solver is selected. Opening a Tnpix panel turns it back on. |
| A garment is not simulated | It is hidden: show it and play from the first frame. Or the demo's 25,000-vertex or 100-frame limit applies (`licInfo`). |
| Two garments do not interact | They are on two Solvers. Share one Solver instance and add Self Collision. |
| Violent first frames | The garment starts inside a collider or far from its rest shape. Model it clear of the body at the first frame. |
| The whole set-up was moved or turned | Same simulation: nothing to fix. Moving only part of it (one collider, the garment, or a pin's object) does change it. |
| A new modifier comes in with odd values | 3ds Max starts a new modifier from the values last typed into that kind of panel in this session. Set every value you rely on (7.8). |
| A render mesh stopped following its simulation mesh | The simulation mesh changed its point count (a Tnpix Garment, or a subdivision below its Solver), and the Tnpix Wrap that follows it says the proxy changed since the bind. Take the change back, or Reset the Wrap (`TnpixTool.wrapReset`, ask first) to bind it again. |
| The scene is slow | Look at Substeps × Iterations first. Then switch Self Collision off to see what it costs, and lower its Relaxation passes. Simulate at the density the shot needs, and add render detail above the Solver (TurboSmooth, or a Tnpix Wrap on a detailed copy). |

### Collision and self collision

| Situation | What helps |
|---|---|
| Poke-through in fast motion | Raise the row's Thickness and the Solver's Substeps; Iterations do not help. Then try the Tight clothes or Fast motion preset, Post collision passes 1 or 2, and Fast motion collision. |
| A body comes through the cloth during the shot | Deep rescue on the Solver (Surface only). It adds time. |
| A low-polygon collider prints its facets | Raise Mesh contact smoothing on the Solver, or Mesh Smooth on the row. |
| Small features blurred | Use Surface (True Geometry), the default, and keep Proxy at 0 on hero colliders. |
| Cloth cuts through itself in hard folds | Check Edge-edge, use Exclusion Mesh ring, raise Query diameter, then Relaxation passes. Then try Mode Advanced with Collision substeps 4, then 8. |
| Layers of a costume fight | Turn on Layer ordering with the inner garment on a lower layer; raise hold strength if needed. |
| The garment looks inflated | Self Collision Thickness or Query diameter is too large. Thickness is a radius. |
| A garment slides off the body (an open jacket off the shoulders) | Measure it (`tpaSlip`, 4.18) and capture it. Raise the garment's material Friction and Grip (3.7), on the whole garment or only on the shoulders through a channel-bound material. If a part must ride the animation, hold the collar and shoulders with Tnpix Preserve on a skinned or wrapped garment (4.7), or with a Pin. |
| A friction change does nothing | A collider row's Friction and Grip act only with its Override material at 1 or 2, and the Self Collision panel's Friction only with Override material friction on, or where no material sets friction. Change the garment's material instead (3.7). |
| Garments slide over each other too easily | Raise the materials' friction; with Layer ordering on, the outer garment's friction acts between the layers (3.7). Or turn on Override material friction and set the panel's Friction for every garment at once. |

### Pins, Preserve and stitches

| Situation | What helps |
|---|---|
| Jitter near a pinned region | The pinned points sit inside a collider. Move them clear at the first frame, or paint them lighter. |
| A sleeve's armpit stays on the body | A Pin binds to the nearest surface at the first frame. Use Tnpix Preserve, which follows the cloth's own animation. |
| Cloth resting on a preserved region falls through it | Points painted 1 take no part in collision. Give the region a soft edge, or keep its hard edge where nothing rests. |
| Preserve looks off after a jump on the timeline | Skipped frames are approximated. Play from the first frame with Real Time off, or simulate frame by frame. |
| A stitch target on another Solver | Stitches work only inside one Solver group. Share the Solver, or use a Pin. |
| A pinned point moves under a painted Soft Body or Volume | A Soft Body or Volume with a Channel above the Pin or Preserve lets go of its painted points. Put the Pin above it, or paint its region off those points. |

### Materials and rigid pieces

| Situation | What helps |
|---|---|
| A painted region behaves like the rest | Check that the material is bound to the region's channel by name, and that the value acts per region. |
| Two materials without a channel | Only the higher one acts. Bind the other to a channel. |
| The garment is stiff and lifeless | Lower the compress stiffness (Standard) or Compression Stiffness (Advanced): cloth has to buckle to wrinkle. |
| The cloth stretches too much | Raise K stretch or lower max strain on that region's material, then raise Stretch quality or Substeps. |
| Jitter or shimmer | Raise Relative Damp before Motion Damping. |
| A Standard dial did not change | Its dials are not properties: use `goldSetAt` and check that it returns `true`. |
| A rigid piece behaves like fabric | Its Rigidity is 0 (off), or Channel and Threshold do not cover the paint. |
| A Rigidity between 0 and 1 is still fully rigid | The Tnpix Rigid comes from a scene of an earlier version. Replace it with a new one with the same settings (4.11), with the artist's yes. |
| A Volume stops short of its ratio | The fabric's stretch limit holds it. Give the shell a fabric that stretches further. |

### Wind and forces

| Situation | What helps |
|---|---|
| A swirl or other direction map barely shows | A flat sheet facing the wind shows it only faintly: the push is face-on (Push across) and the grip along the surface is small (Drag along). Folds, flags and garments show it. |
| The first frame after opening the scene is slow | A map that changes over time is read once along the timeline on that frame, then every frame stays fast. |
| A TenPix Wind does nothing | It is not in the cloth's Tnpix Forces list, or it is muted there. A cloth whose Forces list has no TenPix Wind moves through no air. |
| A 3ds Max Wind does nothing, or blows the cloth away | Strength 1 is about one g. A Wind created by script needs Decay set (`decay:0.0`). The Forces Channel must be empty or a channel the cloth has. |

### Tears, threads and caches

| Situation | What helps |
|---|---|
| The cloth stretches but never tears | Map: bind a region, then lower the Threshold below the strongest pull on the status line. Stretch: lower the Stretch ratio. |
| A whole region tears on one frame | Set Weakness min below Weakness max. |
| No threads appear | Tnpix Threads needs a Solver directly below it, simulated frames and a Tear (or a painted fringe). A cloth playing from a cache file grows no threads: cache the threads object. |
| Adding one cache to a character skips garments | Give each garment its own Tnpix Cache (the Cache Manager's Add). |
| A save is refused | Read `cacheInfo`. In the demo, Alembic is refused. A file another program holds open, or a read-only file, is not written. |

### Licence and hardware

| Situation | What helps |
|---|---|
| The cloth does not move, and a window names the NVIDIA driver | TenPix Cloth needs NVIDIA driver 580 or newer. Until it is updated, the garment is shown as modelled. A garment playing from a cache file plays anywhere. |
| No supported NVIDIA graphics card | The garment is shown as modelled. Caches still play. |
| The demo | Up to 25,000 cloth vertices, counted over the simulating garments together; the first 100 frames; .tnc caches only. Activation is the artist's job. |

### From script

| Situation | What helps |
|---|---|
| A paint call refuses | The Channel must be the current object in the Modify panel, on exactly one object. A Channel added with `modPanel.addModToSelection` on the selected object paints. |
| Paint lands in the wrong channel | A dab lands on the channel selected on the panel. `chans` shows which row is selected. |
| `$x.modifiers[#Tnpix_Cache]` is undefined | The modifier was renamed. Find modifiers by class (3.2). |
| A Tnpix modifier switch does nothing | Use `tnEnabled`, not `enabled`. Collision uses `active`. Solver, Channel, Cache, Post Process, Motion Brush, Material Standard and Rigid use the light bulb (`enabled`). |
| `forceMuted` errors or mutes the wrong warp | Keep `forceNodes` and `forceMuted` the same length, and append to both together. |
| `TenPixCloth_Dir` is undefined | The TenPix toolbar's scripts did not start in this 3ds Max. The toolbar tools cannot be opened by script: ask the artist to open them from the toolbar, or to run the TenPix Cloth installer if there is no toolbar. Everything else in this guide works without them. |
| The garment list's arrays have different lengths | Change entries with `tpaGarmentEntry` (4.2), which keeps the four arrays in step. |

---

## 7. Quick reference

### 7.1 Classes

| Script class | Also | Role | Where | Its switch from script |
|---|---|---|---|---|
| `Tnpix_Solver` | `TnpixSolver` | Runs the simulation for its Solver group; quality, collision system, start shape | Above what describes the cloth | Light bulb `enabled` |
| `Tnpix_Garment` | `TnpixGarment` | Rebuilds the mesh as even triangles or from a volume | Bottom | `tnEnabled` |
| `Tnpix_Gravity` | `TnpixGravity` | Gravity; share one per Solver group | Anywhere | `tnEnabled` |
| `Tnpix_Forces` | `TnpixForces` | Space warps and TenPix Winds acting on this garment | Anywhere | `tnEnabled` |
| `Tnpix_Collision` | `TnpixCollision` | The collider list (group-wide), each row with its own settings | Anywhere; share | `active` |
| `Tnpix_Self_Collision` | `TnpixSelfCollision` | Cloth against itself and the other garments; layers | Anywhere; share | `tnEnabled` |
| `Tnpix_Material_Standard` | `TnpixGoldMaterial` | Fabric: everyday dials, 12 stock fabrics (dials through `gold...`) | Anywhere; one per fabric | Light bulb |
| `Tnpix_Material_Advanced` | `TnpixMaterial` | Fabric: the full model (dials through `mat...`) | Anywhere; one per fabric | `tnEnabled` |
| `Tnpix_Channel` | `TnpixChannel` | Painted, named weight maps; the tear brush | Above Garment | Light bulb |
| `Tnpix_Pin` | `TnpixPin` | Holds a painted region in place or on an object | Anywhere | `tnEnabled` |
| `Tnpix_Preserve` | `TnpixPreserve` | A painted region follows the animation below the Solver | Anywhere | `tnEnabled` |
| `Tnpix_Stitch` | `TnpixStitch` | Sews painted points to a garment of the same Solver, or to itself | Anywhere | `tnEnabled` |
| `Tnpix_Tear` | `TnpixTear` | Tears by painted region, stretch or pressure | Anywhere | `tnEnabled` |
| `Tnpix_Volume` | `TnpixVolume` | Keeps volume, inflates, floats; whole shell or painted region | Anywhere | `tnEnabled` |
| `Tnpix_Rigid` | `TnpixRigid` | Solid pieces in the cloth; Rigidity mixes rigid and cloth | Anywhere | Light bulb |
| `Tnpix_Soft_Body` | `TnpixSoftBody` | Soft flesh and simple muscles in a closed object (experimental) | Below the Solver | `tnEnabled` |
| `Tnpix_Cache` | `TnpixCache` | Saves and plays the simulation (.tnc / .abc); retime, posterize | Above the Solver | Light bulb |
| `Tnpix_Motion_Brush` | `TnpixMotionBrush` | Sculpts the simulated animation in layers; never re-simulates | Above the Solver and its Cache | Light bulb |
| `Tnpix_Post_Process` | `TnpixPostProcess` | Delta Mush and detangle after the solve | Above the Solver (and the Cache) | Light bulb; `deltaMush`, `detangle` |
| `Tnpix_Threads` | `TnpixThreads` | Warp and weft threads at tears and painted hems | Directly above the Solver | `tnEnabled` |
| `Tnpix_Wrap` | `TnpixWrap` | A detailed mesh follows simulated low-resolution proxies | On the detailed object | `tnEnabled` |
| `Tnpix_Threads_Object` | `TnpixThreadsObject` | Geometry object showing a cloth's thread tubes (`threadsFrom`) | Not a modifier | — |
| `TenPix_Wind` | `TenPixWind` | TenPix's own wind, a space warp; acts through Tnpix Forces | Not a modifier | — |

### 7.2 TnpixTool

`node` is the object that carries the modifier. Indexes count from 0 (materials from the top of the stack; collider rows as `rows` prints them), except the Threads functions, which count from 1.

| Function | Returns | Use |
|---|---|---|
| `reset()` | – | Reset Simulation: clears the stored frames (ask first) |
| `sim node frame` | integer | Simulate up to a frame, as scrubbing does; returns the frames stored |
| `live node op arg` | string | Live at frame 0: `"start"` (arg 0, or 2-64 Fast preview), `"step"`, `"keep"`, `"stop"`, `"release"`, `"info"`, `"shape"`, `"clear"`, `"keepframe"` |
| `liveGrab node vertex target radius` | string | While Live runs, hold a vertex (from 1) and the cloth around it toward a world position |
| `colAdd node collider` | boolean | Add a collider row, as Pick Object does |
| `colCount node` | integer | Number of collider rows |
| `rows node` | string | Every row and its settings |
| `colSet node index field value` | boolean | Set one setting of one row (fields in 7.6) |
| `selfColLayers node` | string | The garment list's layers |
| `chanAdd node name fill` | boolean | New channel at `fill`, and selected; make the Channel current in the Modify panel first, as for painting |
| `chanPaint node center radius mode strength` | boolean | One brush dab, object space; modes 0 Add, 1 Subtract, 2 Replace, 3 Smooth |
| `chanStroke node on` | boolean | Open (`true`) or close (`false`) a stroke |
| `chanKeys node shift ctrl` | boolean | Inside a stroke, hold Shift (smooth) or Ctrl (subtract) |
| `chanApplySel node` / `chanRemSel node` | boolean | Write the panel's Value into the selected vertices / set them to 0 |
| `chanClear node` | boolean | Set the selected channel to 0 (ask first) |
| `chans node` | string | The channel table |
| `chanCount node name atOrAbove` | integer | Points painted at or above a value; −1 = no such channel |
| `chanRemove node name` | boolean | Delete a channel and its tear lines (ask first) |
| `chanMirror node side tolerance` | string | Mirror the selected channel to the other side |
| `chanSelCount node edges` | integer | Size of the Channel's vertex or edge selection |
| `tearCut node channel points projDir spacing` | string | Cut a line into the mesh and mark it in the channel |
| `tearRemove node mode` | string | Remove the last cut (0) or every cut (1); undoable (ask first) |
| `pinSet node channel weight followObject` | boolean | Set the Pin's channel, weight and object in one call |
| `goldCount node` / `goldAt node index` | integer / string | Count / read Standard materials (the text names the channel) |
| `goldSetAt node index field value` | boolean | Set a Standard dial by name (7.6); `goldSet` acts on the first one |
| `goldClearAt node index field` | boolean | Untick `matFriction`, `matGrip` or `strainRateLimit`, keeping the number |
| `goldChanAt node index channel` | boolean | Bind a Standard material to a channel (`""` = whole garment); `goldChan` acts on the first one |
| `goldPreset node index` | boolean | Stock fabric 0-11 onto the first Standard material |
| `matCount node` / `matAt node index` | integer / string | Count / read Advanced materials |
| `matSetAt node index field value` | boolean | Set an Advanced value by name (7.6) and tick it |
| `matSetPairAt node index family coeff magIdx` | boolean | Stiffness as coefficient × Multiplier row; family `"stretch"` or `"bend"` |
| `matSetBendModelAt node index model` | boolean | Bend type: 0 Basic, 1 Shape Memory, 3 Shape Memory (Even) |
| `matPresetAt node index presetRow` | boolean | 1 Ultra Light, 2 Light, 3 Medium, 4 Heavy, 5 Leather (resets every dial first) |
| `matAuthoredAt node index on` | boolean | 0 runs pure defaults, 1 your values again |
| `matShearKClearAt node index` | boolean | Withdraw the shear stiffness, keeping the value |
| `matChanAt node index channel` | boolean | Bind an Advanced material to a channel |
| `cacheSave node` | integer | Save the Cache's range; frames written or −1. Ask the artist first if the file exists. |
| `cacheLoad node` / `cacheClear node` | boolean | Play the Cache's file / stop and forget it (deletes nothing) |
| `cacheInfo node` | string | File, found, frames, playing, last status |
| `postInfo node` / `postCaptureRest node` | string / boolean | Post Process settings and rest / take the rest pose now |
| `rigidInfo node` | string | Rigid pieces and points |
| `wrapFill node` / `wrapInfo node` / `wrapReset node` | integer / string / boolean | Fill the proxy memory / its state / forget the bind, rest shape and cuts, and bind again (ask first) |
| `threadsInfo node` / `threadsInfoAt node index` | string | Threads status lines |
| `threadsMakeObject node` / `threadsMakeObjectAt node index` | string | Make the threads object; returns its name |
| `mbLayer`, `mbStroke`, `mbKey` / `mbInfo` | integer / string | Motion Brush layers, strokes and keys / the layers as text |
| `licInfo()` / `licCap()` | string / integer | Licence state / the demo's vertex limit |
| `licActivate`, `licCheck`, `licDeactivate` | string | The artist's own licence actions: leave them to the artist, and never handle a key |

### 7.3 TnpixPreset and TnpixGraph

| Function | Use |
|---|---|
| `TnpixPreset.folder()` / `setFolder path` | The presets folder / choose it |
| `TnpixPreset.names material` | Presets of that kind in the folder |
| `TnpixPreset.save material path` / `load material path` | Save every dial / load one (values applied, or −1) |
| `TnpixPreset.text material` | The material's values in preset form |
| `TnpixPreset.recycle path` | Move a preset file to the Recycle Bin (ask first) |
| `TnpixPreset.why()` | What the last save, load, setFolder or recycle did |
| `TnpixGraph.open()` / `close()` | Open (on the first Solver group) or close the TenPix Graph |

### 7.4 Batch Sim core

| Call | Returns |
|---|---|
| `TenPixBatchCore.check garment shots folder:"" ext:".tnc" testFrames:0 velocities:true` | `#(problems, plan lines)`; changes nothing |
| `TenPixBatchCore.run garment shots folder:"" ext:".tnc" velocities:true preview:false testFrames:0 switched:undefined status:undefined` | `#(ok, message, log file)` |

A shot is `#(name, start, end, #(modifier names on))`. Load the core with `TenPixBatch_NoDialog = true` and then `fileIn (TenPixCloth_Dir + "TenPix_12_BatchSim.ms")`.

### 7.5 Solver presets and stock fabrics

| Preset | substeps | iterations | contactPasses | smoothingIterations | postCollisionPasses | ccd |
|---|---|---|---|---|---|---|
| Default | 4 | 2 | 1 | 10 | 0 | false |
| Draft | 1 | 1 | 1 | 5 | 0 | false |
| Tight clothes | 6 | 2 | 2 | 10 | 2 | false |
| Fast motion | 8 | 2 | 2 | 10 | 2 | true |
| High quality | 8 | 3 | 3 | 10 | 3 | true |
| Ultra quality | 15 | 8 | 7 | 10 | 3 | true |

Every preset also sets `deepRescue` to false; `stretchQuality` stays as set.

Stock fabrics for `goldPreset`: 0 Cotton (approx), 1 Silk (approx), 2 Denim (approx), 3 Leather (approx), 4 Wool, 5 Linen, 6 Chiffon (approx), 7 Satin, 8 Spandex, 9 Polyester, 10 Canvas, 11 Velvet.

Advanced presets for `matPresetAt`: 1 Ultra Light Fabric, 2 Light Fabric, 3 Medium Fabric, 4 Heavy Fabric, 5 Leather.

× Multiplier rows for `matSetPairAt`: 0 to 4 = 1e+10, 1e+9, 1e+8, 1e+7, 1e+6; 5 to 9 = 100 000, 10 000, 1 000, 100, 10; 10 = 1; 11 to 15 = 0.1 … 1e-5; 16 to 20 = 1e-6 … 1e-10; 21 = No Scaling.

### 7.6 Field names and codes

**Collider rows** (`colSet`): 0 Enabled · 1 Two-sided mesh · 2 Open mesh · 3 Voxel (0 = automatic) · 5 Thickness (scene units) · 6 Friction · 7 Proxy (0 = off) · 8 Grip (multiplier) · 9 Mesh Smooth (0 to 1) · 10 Override material as a switch (1 sets Everything, 0 sets Off) · 11 Override material (0 Off, 1 Unpainted cloth only, 2 Everything). Field 4 is not used. The `rows` printout calls field 6 DynSlide. A row's Friction and Grip act only with Override material 1 or 2 (3.7).

**Self Collision** (properties): `tnEnabled` · `thickness` (scene units, a radius) · `friction` · `overrideMaterialFriction` · `mode` · `passes` (Relaxation passes) · `queryDiameter` · `samePieceExclusion` · `exclusion` · `edgeEdge` · `inelasticContact` · `collisionSubsteps` (Mode Advanced only) · `layerOrdering` · `layerHoldStrength` · the garment list `memberHandles`, `memberLayers`, `memberFrictions`, `memberThicknesses` (−1 = not set; change them with `tpaGarmentEntry`, 4.2).

**Material Standard** (`goldSetAt`; names are case-sensitive, and an unknown name is refused):
`bendGoldK` K bend · `bendGoldDamp` damp bend · `dampRatioStretch`, `dampRatioBend` the damping ratios · `relDamp` Relative Damp · `stretchGoldK`, `shearGoldK` K stretch, K shear · `maxStrain` max strain (a fraction) · `damping` velocity damping · `motionDamp` Motion Damping · `weight` weight in g/m² (`densityAll` = weight / 200) · `warpStiff`, `weftStiff`, `shearStiff` warp, weft, shear · `membraneCompress` compress stiffness · `bendAnisoWarp`, `bendAnisoWeft` warp bend, weft bend · `bendQuadK` fold body k_b · `gammaK` collision damping · `matFriction`, `matGrip` friction, grip · `strainLimitOn` limit stretch · `stretchBodyLimit` limit where it touches the body · `strainRateLimit` strain-rate limit · `triStrainLimit` per-triangle limiter · `strainOptIters`, `strainOptCg` Accurate strain limit, Solve steps per iteration · `mrsLevels` multi-res levels.

**Material Advanced** (`matSetAt`; out-of-range values are refused):
`stretchGoldK`, `bendGoldK`, `shearGoldK` Stretch, Bend and Shear Stiffness · `edgeK` Edge Stiffness · `warpK`, `weftK` Stretch XX, Stretch YY · `relDamp` Relative Damp · `damping` Global Damping · `stretchDamp`, `dampRatioBend` the damping ratios · `membraneCompress` Compression Stiffness · `foldBody` Fold Body · `stretchDropoff`, `bendDropoff` Stiffness Dropoff · `restLengthScale`, `restAngleScale` Rest Length Scale, Rest Angle Scale · `normalDrag`, `tangentDrag` Normal Drag, Tangent Drag · `weight` (g/m²), `massKgM2` (kg/m²), `massKg` (whole mass, kg) · `massMode` 0 Unchanged, 1 By weight, 2 Override · `scaleMultiplier` Scale Multiplier · `stretchType` 0 Standard, 2 Fabric Curve · `nlWarpSoft`, `nlWeftSoft`, `nlBiasLock`, `nlLockMul`, `nlSmooth` the Fabric Curve rows · `strainLimitOn`, `maxStretch` Strain limit, Max stretch (percent) · `stretchHardness`, `stretchSweeps` Hardness, Sweeps · `stretchBodyLimit` Limit where it touches the body · `strainRateLimit` Strain-rate limit · `bendAnisoWarp`, `bendAnisoWeft`, `bendGrainAngle` Warp Bend, Weft Bend, Grain Angle · `friction`, `grip` Friction, Grip · `stretchMul`, `edgeMul`, `bendMul` the stiffness multipliers. The MAXScript Guide's Appendix A lists the remaining names: the clears, plasticity and the Scale Multiplier switch.

**Codes:**

| Where | Values |
|---|---|
| Solver `collisionSystem` | 1 Volume Only, 2 Volume + Proxy, 3 Surface + Volume, 4 Surface (True Geometry) |
| Solver `weightMode` | 0 Uniform, 1 Real (g/m²) |
| Self Collision `mode` / `exclusion` | 0 Basic, 1 Advanced, 2 Optimized / 0 Rest distance, 1 Mesh ring |
| Tear `tearBy` / `ends` | 0 Map, 1 Stretch, 2 Pressure / 0 Both marked, 1 Either |
| Volume `mode` / `fillInside` / `fillAround` | 0 Keep volume, 1 Pressure / 0 Helium, 1 Hot air, 2 Air, 3 Water, 4 Custom / 0 Air, 1 Water |
| Rigid `piecesFrom` / `massMode` | 0 Tnpix channel, 1 Mesh elements / 0 By density, 1 Override (kg), 2 Its cloth's |
| Soft Body `material` | 0 Fat, 1 Jelly, 2 Muscle, 3 Rubber, 4 Custom |
| Garment `mode` | 0 Garment (remesh), 1 OpenVDB (volume) |
| TenPix Wind `mode` / `windType` / `projection` / `terrain` | 0 Automatic, 1 Map / 0 Planar, 1 Fan, 2 Point / 0 along the wind, 1 3D around the icon / 0 Open land, 1 Suburb, 2 City, 3 Custom |
| `chanPaint` mode | 0 Add, 1 Subtract, 2 Replace, 3 Smooth |
| `chanMirror` side | 0 +X to −X, 1 −X to +X, 2 +Y to −Y, 3 −Y to +Y, 4 +Z to −Z, 5 −Z to +Z |
| Post Process and Wrap `weightFrom` | 0 Whole cloth / Everywhere, 1 Vertex color, 2 Tnpix channel |

### 7.7 The toolbar

The TenPix Cloth toolbar has nine tools; each opens a window. When 3ds Max starts, the toolbar's own start-up script sets `TenPixCloth_Dir` to the folder of these scripts. If TenPix Cloth was installed without its toolbar, `TenPixCloth_Dir` is undefined: the tools cannot be opened by script, and nothing else in this guide needs them. Open a tool for the artist with `tpaOpenTool`:

```maxscript
global tpaOpenTool
-- open a TenPix toolbar tool for the artist, by its script name (the table below); returns what happened
fn tpaOpenTool script = (
    if TenPixCloth_Dir == undefined or TenPixCloth_Dir == "" then "The TenPix toolbar's scripts are not loaded in this 3ds Max (TenPixCloth_Dir is undefined): ask the artist to open the tool from the toolbar, or to run the TenPix Cloth installer."
    else if not (doesFileExist (TenPixCloth_Dir + script)) then ("Not found: " + TenPixCloth_Dir + script)
    else ( fileIn (TenPixCloth_Dir + script); "Opened " + script )
)
-- tpaOpenTool "TenPix_03_CacheManager.ms"
```

| Tool | Script | What it does |
|---|---|---|
| Quick Cloth | `TenPix_01_QuickCloth.ms` | Makes the selected meshes simulation-ready cloth |
| Cache Manager | `TenPix_03_CacheManager.ms` | Adds, loads (always asks), saves and clears many garments' caches |
| Quality | `TenPix_08_Quality.ms` | Applies the Solver presets or values to one Solver or many |
| Cloth Doctor | `TenPix_07_ClothDoctor.ms` | Scans for silent set-up problems; fixes the ticked, safe ones |
| Tearing Sample | `TenPix_09_TearingSample.ms` | Builds a ready-made tearing scene |
| Forces | `TenPix_10_Forces.ms` | Lists every Tnpix Forces and the dials of its warps |
| Sim Profiler | `TenPix_SimProfiler.ms` | Shows where each simulated frame spends its time |
| Quick Soft Body | `TenPix_11_QuickSoftBody.ms` | Makes closed meshes into muscles or fats (experimental) |
| Batch Sim | `TenPix_12_BatchSim.ms` | Runs a list of shots and saves every garment's cache per shot |

### 7.8 Defaults of a new modifier

What a modifier added by script starts with when no panel of its kind has been used in the session (rule 9). Lengths marked * are inch values, written in the scene's unit.

| Modifier | Defaults |
|---|---|
| Tnpix Solver | `substeps` 4, `iterations` 2, `contactPasses` 1, `stretchQuality` 2, `smoothingIterations` 10, `postCollisionPasses` 0, `ccd` false, `deepRescue` false, `collisionSystem` 4 (Surface, True Geometry), `weightMode` 0 (Uniform), `worldScale` 1, `unlimitedGround` false |
| Tnpix Self Collision | `tnEnabled` true, `edgeEdge` true, `thickness` 0.15*, `friction` 0, `overrideMaterialFriction` false, `mode` 2 (Optimized), `passes` 10, `queryDiameter` 2.0, `samePieceExclusion` 2.5, `exclusion` 1 (Mesh ring), `inelasticContact` true, `collisionSubsteps` 4, `layerOrdering` false, `layerHoldStrength` 4, an empty garment list |
| A new collider row | Enabled, Two-sided mesh on, Open mesh on, Thickness 0.15*, Friction 0.35, Grip 3, Override material 0 (Off), Mesh Smooth 0, Proxy 0, Voxel 0 (automatic) |
| Material Standard, Material Advanced | Friction 0.35 and Grip 3, both switched on |
| Tnpix Gravity | `magnitude` −386.22* per second squared, `direction` [0,0,1] |
| Tnpix Garment | `edgeLength` 5.0* (Quick Cloth's Triangle size starts at 2.0) |
| Tnpix Stitch | `searchDistance` 0.5* |
