Skip to content

Programming Reference

CandidumDevTeam edited this page Jun 26, 2026 · 2 revisions

Programming Reference

This page covers the public API for importing PMX models, building Unity objects, and converting VMD motion. For the format and runtime mechanics behind these calls, read MMD Formats and Internals.

All runtime types live in the UMT namespace; editor types live in UMT.Editor. The runtime code never references UnityEditor, so the import and conversion pipeline is callable from play-mode and from builds, not only from the editor.

Assemblies

The package is split across three assemblies. UMT.Runtime holds the importer, the MMD runtime components, and the VMD converter. UMT.Editor holds the scripted importers and editor windows, and is editor-only. UMT.ThirdParty holds the romanisation and image-loading code. UMT.Runtime and UMT.ThirdParty both allow unsafe code, because the physics layer passes raw pointers into the native plugin.

UMT.Editor carries a version define: when lilToon 2.0.0 or newer is installed, LILTOON_AVAILABLE is defined. Material building keys off this to choose the lilToon shader.

Importing a PMX model

PMXImporter is the single entry point for turning a PMX file into Unity objects. It is synchronous, with no async variant, by design.

public static PMXImportResult Import(string pmxFilePath, PMXImportOptions options = null, CancellationToken cancellationToken = default)
public static PMXImportResult Import(byte[] pmxBytes, PMXImportOptions options = null, CancellationToken cancellationToken = default)
public static PMXImportResult BuildUnityObjects(PMXModel model, PMXImportOptions options = null)

Import parses the PMX, optionally applies renames, builds the Unity objects, builds metadata, and returns everything in a PMXImportResult. BuildUnityObjects runs only the object-building half against a PMXModel you already have in hand, which is useful when you have parsed or cached the model separately.

The build proceeds in a fixed order: compute morph-linked material groups, load textures, build materials, build bones and bind poses, optionally build the avatar, build meshes, build renderers, build the MMD transform and physics components, then refresh the transform manager's initial pose. Avatar building deliberately comes before mesh and component construction.

PMXImportResult

public sealed class PMXImportResult
{
    public GameObject root;
    public PMXModel model;
    public PMXRenameResult renameResult;
    public PMXMetadata metadata;
    public Transform[] bones;
    public Texture2D[] texturesByIndex;
    public PMXAvatarBuildResult avatarResult;
    public MMDTransformBuildResult mmdTransformResult;
    public readonly List<PMXImportedMesh> meshes;
    public readonly List<Material> materials;
    public readonly List<Texture2D> textures;
    public readonly List<string> warnings;
}

root is the assembled model GameObject. bones is the bone transform array indexed to match model.bones. texturesByIndex is the texture map indexed by PMX texture index. mmdTransformResult carries the runtime components (see below). Each PMXImportedMesh pairs a generated Mesh with the PMX material indices it covers. warnings collects non-fatal issues raised during import.

PMXImportOptions

public sealed class PMXImportOptions
{
    public string sourcePath;
    public string sourceName;
    public string textureBaseDirectory;
    public Transform parent;
    public bool applyRenames = true;
    public UMTResources umtResources;
    public PMXRenameLists renameLists;
    public Action<string, TimeSpan> timingCallback;
    public bool strictVersion = true;
    public bool createAvatar = true;
    public Func<PMXModel, PMXImportOptions, Texture2D[]> loadTextures;
    public Shader uvBlitShader;
    public ComputeShader alphaDetectorShader;
    public int alphaDetectionTextureSize = 1024;
    public float alphaDetectionThreshold = 0.99f;
    public float alphaCoverageZWriteThreshold = 0.90f;
}

A few of these matter more than the rest. umtResources must point at a populated UMTResources asset for renaming and avatar building to work. loadTextures is the hook that decides how textures are resolved: a runtime import decodes file bytes into Texture2D, whereas the editor import supplies project texture assets through PMXProjectTextures.Load and never decodes bytes itself. createAvatar toggles humanoid avatar construction. strictVersion controls whether an unexpected PMX version throws; the alpha-detection fields tune the GPU coverage pass that decides which materials are transparent.

There are no editor output paths here; keep editor-only concerns out of this type.

Parsing without building

PMXReader parses a PMX stream into a PMXModel and nothing else.

public static PMXModel Read(Stream stream, bool strictVersion = true)

The reader converts every spatial value into Unity space as it parses: a 180° rotation about Y plus a MMDConstants.k_MMDUnitToUnityUnit (0.08) scale on positions, with matching rotation on normals and quaternions. This is important: object building must not convert these again. See the internals page for the exact per-value rules.

Renaming and romanisation

PMX names are usually Japanese, sometimes Chinese, and Unity object names want to be ASCII. PMXRenameUtilities.Rename rewrites material, bone, morph, rigid-body and joint names in place on the model and reports what it changed.

public static PMXRenameResult Rename(PMXModel model, PMXRenameLists renameLists, UMTResources umtResources)

It applies ordered token replacements from the rename lists, then romanises Japanese with Kawazu and Chinese with PinyinNet, then replaces any remaining non-ASCII characters with underscores. It is synchronous only. PMXRenameResult carries per-element original-to-renamed mappings and counts.

Renaming happens after parsing and before object construction and metadata, so generated objects and metadata both reflect the renamed names. If you call BuildUnityObjects against a model you want renamed, rename it first.

MMD runtime components

Object building attaches a small set of runtime components to the model root, assembled by MMDTransformBuilder.

public static MMDTransformBuildResult Build(PMXModel model, GameObject root, Transform[] bones)
public static void RefreshInitialTransforms(MMDTransformManager transformManager)

public struct MMDTransformBuildResult
{
    public MMDTransformManager transformManager;
    public MMDPhysicsManager physicsManager;
    public MMDRigidBody[] rigidBodies;
    public MMDJoint[] joints;
    public int boneComponentCount;
    public int ikControllerCount;
    public int constraintCount;
}

MMDTransformManager is the solver. It runs late (DefaultExecutionOrder 10000), runs in edit mode, and on each step samples the Unity transforms, resets bones to their initial pose, solves constraints and IK, optionally steps physics, and writes the solved transforms back. Its public surface:

public PMXModel model;
public MMDPhysicsManager physicsManager;
public bool transformEnabled = true;
public bool solveConstraints = true;
public bool solveIK = true;
public bool livePhysics = true;
public bool solveInEditMode = false;
public Animator animator;

public void SolveTransforms(bool accessTransforms);
public void SolveWithPhysics(bool accessTransforms, float physicsElapsedTime, bool runConstraintsAndIKSolver);
public void DisposeRuntimeData();

MMDPhysicsManager owns the native Bullet context: rigid-body, joint and ground construction, stepping, reset and disposal. It requires an MMDTransformManager on the same object.

public MMDRigidBody[] rigidBodies;
public MMDJoint[] joints;
public bool enableGroundCollision = true;
public uint physicsSeed = 0;
public void DisposePhysics();

Live physics only runs in play mode, only when livePhysics is set, and only when a physics manager and model are present. After changing the bind pose or rebuilding bones, call RefreshInitialTransforms so the solver's cached initial pose and native caches match the new state.

Converting VMD motion

VMDReader parses a .vmd into a VMDAnimation.

public static VMDAnimation Read(byte[] bytes)
public static VMDAnimation Read(Stream stream)

VMDAnimationClipConverter turns that into an AnimationClip. Motion conversion needs the target PMXModel, because curves are built against that model's exact bone and morph layout and against the imported hierarchy.

public static AnimationClip Convert(VMDAnimation animation, PMXModel model, VMDAnimationClipOptions options = null, ProgressCallback progress = null)
public static AnimationClip ConvertCamera(VMDAnimation animation, float frameRate = 30.0f, Action<string, TimeSpan> timingCallback = null, ProgressCallback progress = null)

public delegate void ProgressCallback(Stage stage, int frame, int totalFrames);
public enum Stage { Setup, BoneConversion, MorphConversion, CameraConversion, Finalization, Complete }

VMDAnimationClipOptions

public sealed class VMDAnimationClipOptions
{
    public float frameRate = 30.0f;
    public bool bakeIKToFK = true;
    public bool bakePhysicsToFK = true;
    public uint physicsSeed = 0;
    public float physicsWarmUpDuration = 5.0f;
    public Action<string, TimeSpan> timingCallback;
}

bakeIKToFK selects between two fundamentally different outputs. With it on (the default), the converter samples the fully solved pose every frame and writes dense FK rotation curves; if bakePhysicsToFK is also on and the model has physics, physics-driven bones are baked in too, after a warm-up of physicsWarmUpDuration seconds. With it off, the converter writes sparse local position and Euler-rotation curves plus stepped IK-toggle curves, and leaves IK to the runtime solver at playback.

Prefer baked output. Unity interpolates quaternion animation curves component-by-component and ignores tangent weighting, so it does not reproduce MMD's spherical rotation interpolation; baking removes the dependence on Unity's interpolation by putting the correct value on every frame. The internals page explains this in full.

Camera conversion produces a clip for a two-node rig: the root carries the centre position and orientation, and a child (named Camera by default, per k_DefaultCameraChildName) carries the signed distance on its local Z and the field-of-view curve.

Editor entry points

The editor wires the same runtime pipeline into Unity's asset import system. PMXScriptedImporter imports .pmx files directly and exposes the inspector options (create-avatar, debug data, and the VMD bake list). VMDScriptedImporter parses .vmd files into a single VMDAnimation main asset. PMXImportPipeline is the bridge that registers a finished PMXImportResult with the AssetImportContext, setting the root as the main object and adding meshes, materials and avatar as sub-assets, then returns a PMXImportPipelineResult summary of counts and warnings. VMDClipConverterWindow (Tools ▸ UMT ▸ VMD Clip Converter) is the one-off converter for motion and camera.

When you add or remove .cs files in this package, Unity has to regenerate its project and metadata files; let Unity do that by refreshing, rather than hand-editing the generated files.

Clone this wiki locally