Hive Definition Diff

A Hive component’s data lives in several places which can drift apart. The definition diff library, zoo.libs.hive.definitiondebug, reads them all and shows where they differ. Use it to find out why a component builds differently from what you expect, why a value doesn’t survive a save and reopen, or what a build, mirror or script changed. The Hive Artist UI Definition Debugger is built on it.

The library is strictly read-only. It never creates Component instances, because loading a component, or calling Component.serializeFromScene, can write the definition back to the meta node. Everything is read from the meta nodes and the component registry only, so running it never changes the scene.

For every class and function see the API reference.

The Sources

Each component is read into a ComponentSnapshot holding these sources as plain dicts:

Source

Index

What it is

Base

BASE

The shipped .definition file for the component type.

Definition

DEFINITION

What Hive thinks the component is: the base merged with the definition cached on the component meta node, the same merge Hive does when it loads a component from the scene.

Scene

SCENE

What is built in the scene, serialized from the guides, settings nodes and constraints.

Frozen Definition

FROZEN_DEFINITION

The Definition kept by freeze().

Frozen Scene

FROZEN_SCENE

The Scene kept by freeze().

The source indices are constants of zoo.libs.hive.definitiondebug.session. The frozen sources are missing until you freeze. In raw mode the Definition source is the exact JSON stored in the zooDefCache* attributes of the meta node instead of the merged definition, see Normalized And Raw Mode.

Note

When a component has no guides built, Hive’s scene serializer returns the cache, so Scene equals the cached definition. snapshot.sceneIsCache is True for these components.

Quick Start

DiffSession is the entry point. It reads every component of a rig, builds and caches the diff trees, and exports the differences.

from zoo.libs.hive import api
from zoo.libs.hive.definitiondebug import session as diffsession

rig = api.rootByRigName("biped")
session = diffsession.DiffSession()
session.loadRig(rig.meta)

pairs = [(diffsession.DEFINITION, diffsession.SCENE)]
for snap in session.snapshots:
    print(snap.label(), session.differenceCount(snap, pairs))

# every difference of every component, as Markdown
report = session.report(compareMode=diffsession.COMPARE_MODES[1])
print(diffsession.reportToMarkdown(report))

A session only reads the scene in loadRig(). After changing the rig, call loadRig again to see the change. Changing the mode, tolerance or ignore rules doesn’t need a reload, the trees are cached per setting.

To find the rig of the selected nodes instead of using a rig name:

from zoo.libs.hive.definitiondebug import definitionsources

metas = definitionsources.selectedComponentMetas()
rigMeta = definitionsources.rigMetaForComponentMeta(metas[0])
session.loadRig(rigMeta)

# every hive rig in the scene, the label includes the namespace
for label, rigMeta in definitionsources.iterSceneRigs():
    print(label)

Load Errors

A source which fails to load doesn’t stop the others. The failure is added to snap.errors and that source is left as None, which compares as missing.

for snap in session.snapshots:
    for error in snap.errors:
        print(snap.label(), error)

Compare Modes

A CompareMode names the sources shown (columns) and the source pairs compared (pairs).

Mode

Use it to find

COMPARE_MODES[0] Base ↔ Definition ↔ Scene

Everything at once.

COMPARE_MODES[1] Definition ↔ Scene

Changes made in the scene which aren’t in the cached definition yet, or cached values the scene doesn’t match.

COMPARE_MODES[2] Base ↔ Definition

What this component changes from its component type’s defaults.

COMPARE_MODES[3] Base ↔ Scene

What the built component changes from the defaults.

FROZEN_COMPARE_MODES[0] Frozen ↔ Now

What changed in the Definition and the Scene since the freeze.

FROZEN_COMPARE_MODES[1] Frozen Scene ↔ Scene

What changed in the scene since the freeze.

FROZEN_COMPARE_MODES[2] Frozen Definition ↔ Definition

What changed in the cached definition since the freeze.

compareModes() returns the modes available right now, the frozen ones only after a freeze.

for mode in session.compareModes():
    print(mode.label, mode.columns, mode.pairs)

Reading The Differences

tree() returns the diff tree of a component, a DiffNode per key holding one value per source. Pass the compare mode’s columns so Hiding Rows Missing From A Source only checks the sources you look at.

iterDifferences() yields the nodes which explain the differences: an added or removed subtree once, and the changed values inside a changed dict or list rather than the container.

from zoo.libs.hive.definitiondebug import definitiondiff, formatting

mode = diffsession.COMPARE_MODES[1]
snap = session.snapshot("arm_L")
tree = session.tree(snap, mode.columns)
for node in definitiondiff.iterDifferences(tree, mode.pairs):
    values = [formatting.formatValue(node.values[s], node.kind) for s in mode.columns]
    print(node.pathString(), formatting.statusSymbols(node, mode.pairs), values)

Each node gives its DiffStatus between any two sources: same, changed, added (missing in the first source), removed (missing in the second) or absent (missing in both). Values missing from a source are the MISSING sentinel.

node = tree.find("guideLayer", "dag", "root", "translate")
if node is not None:
    print(node.status(diffsession.DEFINITION, diffsession.SCENE))
    print(node.values[diffsession.DEFINITION], node.values[diffsession.SCENE])

# counts per pair: {(1, 2): {"changed": 3, "added": 0, "removed": 1}}
print(definitiondiff.summarize(tree, mode.pairs))

Paths are dotted keys from the definition root, e.g. guideLayer.dag.root.children.upr.translate. Lists of dicts are matched by identity rather than index, guides by id, drivers by label, attributes by name, so one inserted guide doesn’t show every guide after it as changed. Lists without a unique identity key are matched by index and show as [0], [1].

To jump from a guide path to the guide in the scene:

from zoo.libs.maya import zapi

guideId = diffsession.guideIdFromPath(node.path)
if guideId:
    guide = definitionsources.guideNodeFromId(snap.metaNode, guideId)
    if guide is not None:
        zapi.select([guide])

Where A Definition Value Came From

The Definition is a merge of the base and the meta node cache. origins() tells you which side each value came from: "base", "cache", "base + cache" (both hold it) or "merge/default" (neither, Hive’s merge or a hard coded default produced it).

origins = session.origins(snap)
print(origins.get(("guideLayer", "dag", "root", "translate")))
print(formatting.ORIGIN_DESCRIPTIONS["merge/default"])

Origins are only meaningful when the Definition is shown in normalized mode, see showsOrigins().

What A Key Means

docForPath() returns a short description of the last key of a path, useful for tooltips. Guide and node keys are read from the field comments in zoo.libs.hive.base.definition.definitionnodes.

from zoo.libs.hive.definitiondebug import keydocs

print(keydocs.docForPath(("guideLayer", "dag")))
# Node hierarchy of the layer, nested through 'children' and matched by 'id'.

Normalized And Raw Mode

By default the session is in normalized mode, definitionsources.MODE_NORMALIZED. Every source is put through ComponentDefinition and canonicalized, so differences which only come from how a source was written don’t show: keys left out against keys written with their default, attribute plug flags, locked/keyable/channelBox written as False against not written. Keys the scene serializers never write (the dg graphs and the rig layer dag) are taken from the Definition, and definitionsources.SERIALIZER_NOISE_RULES hides known serializer noise such as attribute min/max and resolved guide names.

Raw mode, definitionsources.MODE_RAW, compares the sources exactly as stored: the base file, the raw meta node cache and the raw scene serialization. Use it when you suspect the normalization itself hides the problem.

from zoo.libs.hive.definitiondebug import definitionsources

session.mode = definitionsources.MODE_RAW
session.tolerance = 0.001  # absolute tolerance for numbers, default 0.0001

Numbers, and lists of numbers such as vectors, matrices and curve cvs, compare within the tolerance. Bools never equal numbers.

Hiding Differences

Hidden differences compare as the same, so they leave the counts, the reports and iterDifferences. hiddenDifferenceCount() tells you how many are hidden, so nothing disappears silently.

Ignore Rules

An ignore rule is a (path pattern, mode) pair. Patterns are fnmatch patterns matched against the dotted path, * also matches dots, and *.key also covers a top level key.

Mode

Hides the node

definitiondiff.IGNORE_ALWAYS

Always.

definitiondiff.IGNORE_ONE_SIDED

When it’s missing from one side of the pair, a changed value still shows.

definitiondiff.ignoreMissingIn("Scene")

And everything below it, when it’s missing from any of the named sources, whatever the other sources hold.

User rules live in IgnoreRules. Adding a rule needs no reload.

rules = session.ignoreRules
rules.add("*.translate", definitiondiff.IGNORE_ONE_SIDED)
rules.add("guideLayer.dag*.shape", definitiondiff.IGNORE_ALWAYS)
rules.add("*.upr", definitiondiff.ignoreMissingIn("Scene"))
rules.add("*.upr", definitiondiff.ignoreMissingIn("Base"))  # merged into missingIn:Scene,Base

# a pattern matching one key anywhere, with special characters escaped
rules.add(definitiondiff.ignorePatternForKey("[2]"), definitiondiff.IGNORE_ALWAYS)

rules.remove("*.upr")  # every rule of the pattern, pass a mode to remove only that one
print(session.activeIgnoreRules())

A pattern holds at most one IGNORE_ALWAYS/IGNORE_ONE_SIDED rule, adding another replaces it, and one merged “missing in” rule. session.hideIgnored = False turns every ignore rule off, including the serializer noise rules, to see everything.

Saving The Rules

Rules are kept in memory unless you give IgnoreRules an IgnoreRulesStorage. The stored rules replace the initial ones, every change is saved and read or write failures are logged rather than raised.

import json
import os

from zoo.libs.hive.definitiondebug import ignorerules

class JsonFileStorage(ignorerules.IgnoreRulesStorage):
    def __init__(self, path):
        self.path = path

    def load(self):
        if not os.path.exists(self.path):
            return []
        with open(self.path) as f:
            return json.load(f)

    def save(self, rules):
        with open(self.path, "w") as f:
            json.dump(rules, f, indent=2)

rules = ignorerules.IgnoreRules(storage=JsonFileStorage("C:/temp/hiveDiffIgnore.json"))
session = diffsession.DiffSession(ignoreRules=rules)

Hiding Rows Missing From A Source

hideMissing hides any row, and everything below it, that is missing from one of the given sources, for example keys the scene intentionally doesn’t have. It works like an ignoreMissingIn rule for every path, wins over the ignore rules and stays on when hideIgnored is off. Only sources shown by the compare mode are checked, so Scene doesn’t affect Base ↔ Definition.

session.hideMissing = {diffsession.SCENE}
mode = diffsession.COMPARE_MODES[0]
print(session.hiddenDifferenceCount(session.snapshots, mode.pairs,
                                    reason=definitiondiff.HIDDEN_MISSING))
print(session.hiddenDifferenceCount(session.snapshots, mode.pairs,
                                    reason=definitiondiff.HIDDEN_BY_RULE))

Freeze And Compare Later

freeze() keeps the current snapshots. Change the rig, reload, and compare the frozen state with now. This is the quickest way to see what a build, a mirror, a script, or a save and reopen changed.

from maya import cmds

session.loadRig(rig.meta)
session.freeze("before build")

rig.buildRigs()
session.loadRig(rig.meta)  # re-read, the freeze is kept

report = session.report(compareMode=diffsession.FROZEN_COMPARE_MODES[0])
print(diffsession.reportToMarkdown(report))

# components deleted since the freeze
print(session.frozen.missingFrom(session.snapshots))
session.clearFreeze()

Frozen components are matched to the current ones by meta node first, which follows renames, then by name and side, so a freeze survives reopening the scene. Reload the rig meta after reopening, the old one is gone:

session.freeze()
cmds.file(save=True)
cmds.file(cmds.file(query=True, sceneName=True), open=True, force=True)
session.loadRig(api.rootByRigName("biped").meta)
report = session.report(compareMode=diffsession.FROZEN_COMPARE_MODES[1])

Exporting A Report

report() returns the differences as a JSON compatible dict: the rig, scene, compare mode, settings, hidden counts and, per component, its errors and differences with the status per pair and the value per source. reportToMarkdown() turns it into Markdown tables, ready to paste in a bug report.

import json

from zoo.libs.hive.definitiondebug.definitiondiff import DiffStatus

report = session.report(
    snapshots=[session.snapshot("arm_L"), session.snapshot("arm_R")],  # defaults to every component
    compareMode=diffsession.COMPARE_MODES[1],
    statuses=(DiffStatus.CHANGED,),  # only changed values, not added or removed keys
    layer="guideLayer",  # one of diffsession.LAYER_FILTERS
)
with open("C:/temp/armDiff.json", "w") as f:
    json.dump(report, f, indent=2)
with open("C:/temp/armDiff.md", "w", encoding="utf-8") as f:
    f.write(diffsession.reportToMarkdown(report))

LAYER_FILTERS holds "All", each layer key, "drivers" and "Other" for the remaining top level keys.

Diffing Any Dicts

definitiondiff is pure python with no Maya imports. It diffs any number of JSON compatible dicts, for example two .definition files, or a definition against one from a template.

from zoo.libs.hive.definitiondebug import definitiondiff, formatting

base = {"name": "arm", "guideLayer": {"dag": [
    {"id": "root", "translate": [0, 0, 0], "children": [
        {"id": "shldr", "translate": [0, 14, 0], "children": []}]}]}}
scene = {"name": "arm", "guideLayer": {"dag": [
    {"id": "root", "translate": [0, 0, 0], "children": [
        {"id": "upr", "translate": [2, 14, 0], "children": []},
        {"id": "shldr", "translate": [0, 15, 0], "children": []}]}]}}

root = definitiondiff.buildDiffTree([base, scene], ("Base", "Scene"))
for node in definitiondiff.iterDifferences(root, [(0, 1)]):
    print(node.pathString(), node.status(0, 1),
          [formatting.formatValue(v, node.kind) for v in node.values])

Prints:

guideLayer.dag.root.children.shldr.translate changed ['[0, 14, 0]', '[0, 15, 0]']
guideLayer.dag.root.children.upr added ['‹missing›', '{…} 3 keys']

The inserted upr guide shows once as added and shldr keeps its identity. buildDiffTree also takes:

  • tolerance - the absolute tolerance for numbers.

  • ignore - ignore rules, as in Ignore Rules.

  • rules - (path pattern, identity key) pairs to choose how a list is matched, None forces index matching. The default matches connections.constraints by type.

  • suppressMissing and visibleSources - source indices for Hiding Rows Missing From A Source.

sourcePairs() gives the neighbour and end pairs for N sources, e.g. sourcePairs(3) is [(0, 1), (1, 2), (0, 2)].

To diff a raw definition dict the same way the session does in normalized mode, put it through normalize() first, this needs Maya.