Working With Definitions¶
A definition is a component described as data: its guides, settings, the nodes it connects with, its joints and its drivers. Hive creates most of the scene from it, so reading and changing a definition is how code changes what a component builds.
The examples on this page are real files in docs/source/examplecode/hivedefinition/, the unit tests run them.
Three Copies¶
Knowing which copy you hold is the whole trick.
Copy |
Where |
Use |
|---|---|---|
Original |
|
Never changed. What the component was designed as, and what a change is compared to. |
Working copy |
|
What code edits. It is in memory and is not live, the scene doesn’t change when it does. |
Saved copy |
The component meta node |
Written when a build stage finishes. Only what differs from the original is stored. |
Two rules follow:
Changing the working copy changes nothing in the scene until a stage is built. Edit, then build.
Changing the scene changes nothing in the working copy until it is read back, which every build stage does when it starts, and
component.serializeFromScene()does on demand.
What Is In A Definition¶
Key |
Holds |
|---|---|
|
Which component class, the name and side of the component and the version of the definition. |
|
The guides with their shapes and srts, and the guide settings. |
|
The nodes other components connect to and from. See Input And Output. |
|
The skinning joints. |
|
Settings per settings node, e.g. the |
|
Space switches, matrix, direct and parent space drivers. See Drivers And Space Switches. |
|
Which component this is a child of, and the constraints between the guides, stored by id. |
|
The naming preset and the marking menus of each stage. |
The json form of each node type is described in Definition Types.
Loading A Definition¶
The component registry loads a definition without a rig or a scene. Each call returns a new, independent working copy along with the original.
def loadDefinition(componentType="vchaincomponent"):
"""Loads a definition from the registry without a rig or a scene.
:return: A new working copy and the original it came from.
:rtype: tuple[:class:`api.ComponentDefinition`, :class:`api.ComponentDefinition`]
"""
registry = api.Configuration().componentRegistry()
definition, original = registry.initComponentDefinition(componentType)
return definition, original
def describe(definition):
"""A readable summary of a definition."""
guideLayer = definition.guideLayer
return {
"type": definition.type,
"guides": [guide.id for guide in guideLayer.iterGuides(includeRoot=False)],
"guideSettings": [setting.name for setting in guideLayer.iterGuideSettings()],
"inputs": [node.id for node in definition.inputLayer.iterInputs()],
"outputs": [node.id for node in definition.outputLayer.iterOutputs()],
"joints": [joint.id for joint in definition.deformLayer.iterDeformJoints()],
"controlPanel": [setting.name for setting in definition.rigLayer.nodeSettings(api.constants.CONTROL_PANEL_TYPE)],
"drivers": [(driver.type, driver.label) for driver in definition.drivers],
}
For a vchain describe returns the guides upr, mid, end and upVec, the guide settings hasStretch,
alignIkEndToWorld and ikfk_default, the inputs, outputs and joints, the controlPanel attributes and the drivers.
Reading Settings¶
Settings are definition attributes. .value is the value, .default the default.
def guideSettings(definition):
"""Reads guide settings, one at a time or many. Settings are AttributeDefinitions, ``.value`` is the value."""
guideLayer = definition.guideLayer
hasStretch = guideLayer.guideSetting("hasStretch").value
several = guideLayer.guideSettings("hasStretch", "alignIkEndToWorld")
return hasStretch, {name: setting.value for name, setting in several.items()}
The scene has the live values, reach them through the layer, see Examples.
Editing Before A Build¶
The simplest and safest change is to edit the working copy of a component which has no guides yet.
def setGuideSetting(component, name, value):
"""Changes a guide setting on the working copy of a built or unbuilt component.
The scene node isn't touched, the setting takes effect when the guides are built. ``saveDefinition``
must be called after editing the definition and before the build, otherwise the build ignores the change.
"""
component.definition.guideLayer.guideSetting(name).value = value
component.saveDefinition(component.definition)
def moveGuide(component, guideId, translate):
"""Places a guide by editing the definition, before the guides are built.
Editing the scene guide is the other way, use it once the guides exist. Guides are found by id.
``saveDefinition`` must be called before the build, otherwise the build ignores the change.
"""
guide = component.definition.guideLayer.guide(guideId)
guide.translate = tuple(translate)
component.saveDefinition(component.definition)
return guide
def addAnimSetting(component, name, value):
"""Adds an attribute to the control panel, it is created when the rig is built.
The rig layer holds settings per settings node. ``controlPanel`` is the node the animator sees.
``saveDefinition`` must be called before the build for the new attribute to be created.
"""
definition = component.definition
definition.rigLayer.addSetting(api.constants.CONTROL_PANEL_TYPE, name=name,
Type=zapi.attrtypes.kMFnNumericFloat, value=value, default=value,
min=0.0, max=10.0, keyable=True, channelBox=False)
component.saveDefinition(definition)
return definition.rigLayer.setting(api.constants.CONTROL_PANEL_TYPE, name)
Important
Editing component.definition only changes the in memory working copy. Call
component.saveDefinition(component.definition) after the edit and before running a build, it bakes the
definition into the component meta node which the build reads. Without it the build ignores your change. The
three functions above each end with the call.
Putting it together, edits made to an unbuilt component land in the scene when the guides are built:
def demo():
"""Edits a definition of an unbuilt component and builds it, returns facts for the tests."""
rig = api.commands.createRig(name="Robot")
arm = rig.createComponent("vchaincomponent", "arm", "L")
facts = {"rig": rig}
facts["describe"] = describe(arm.definition)
facts["settings"] = guideSettings(arm.definition)
moveGuide(arm, "end", (0.0, 0.0, 60.0))
setGuideSetting(arm, "hasStretch", False)
rig.buildGuides()
facts["endGuide"] = arm.guideLayer().guide("end").translation(zapi.kWorldSpace)
facts["stretchSetting"] = arm.guideLayer().guideSettings().hasStretch.value()
return facts
Note
Guides, inputs, outputs and joints are found by id in a definition, guideLayer.guide("end").
Ids never change, names follow the naming preset.
Editing After A Build¶
Once the guides exist a rigger may have moved them. The working copy doesn’t know, so read the scene back first, otherwise rebuilding puts the guides back where the working copy had them.
def sceneToDefinition(component):
"""Reads the scene back into the working copy, for when a rigger moved guides or changed settings by hand.
The definition in memory isn't live, nothing which happens in the scene reaches it until it is serialized.
``layerIds`` limits which layers are read.
:return: The definition of the component after the scene was read.
"""
component.serializeFromScene(layerIds=api.constants.GUIDE_LAYER_TYPE)
return component.definition
Then change the working copy, call saveDefinition and rebuild the stage:
def rebuild(rig, component):
"""Applies a change to the working copy. Guides and rig are rebuilt from the definition.
Deleting the guide first keeps a scene which was edited by hand, so read the scene into the definition
with :func:`sceneToDefinition` before you delete.
"""
component.deleteGuide()
rig.buildGuides([component])
Warning
component.deleteGuide() deletes the guide nodes. Anything a rigger did which isn’t in the definition is lost, so
always call sceneToDefinition before it.
What Is Saved¶
A saved definition only holds what differs from the original. A component which matches its original saves an empty list of drivers, the original supplies them when the component is loaded again. Extending a built in space switch stores the new choice in full and the protected, built in choices by label only, which keeps their order.
def serialize(component):
"""The dict which is stored in the scene, only the differences from the original definition are stored.
A definition which matches the original serializes drivers as an empty list, the original supplies them
when the component is loaded again.
"""
return component.definition.serialize(component.originalDefinition)
def customizeDrivers(component):
"""Drivers are diffed against the original when they are stored.
Extending a built in space switch stores the new choice in full and the protected built in choices by label only,
the label keeps the order, the original supplies everything else when the component is loaded.
:return: The choices the original has, and the choices the working copy has.
"""
space = component.definition.driver("ikSpace")
space.params.createDriver({"label": "prop", "driver": "@{prop:M.rigLayer.fk00}"})
original = [i.label for i in component.originalDefinition.driver("ikSpace").params.drivers]
working = [i.label for i in space.params.drivers]
return original, working
Important
This is why a definition which is created in code must be serialized against an empty definition, see below. Serializing against the original drops everything which matches it.
Writing A Definition To A File¶
ComponentDefinition.serialize(original) returns plain data. To keep everything, for a definition file or a template,
serialize against an empty definition.
def toJson(definition, original=None):
"""The definition as json text, drivers and layers included. Safe to write to a file."""
original = original if original is not None else api.ComponentDefinition.fromData({})
return json.dumps(definition.serialize(original), sort_keys=True, indent=4)
def roundTrip(definition):
"""Serializes a definition, then builds a new one from the data.
Serializing against an empty definition keeps everything, this is how a definition is written to a file.
"""
data = definition.serialize(api.ComponentDefinition.fromData({}))
return api.ComponentDefinition.fromData(json.loads(json.dumps(data)))
Creating A Definition From Scratch¶
Build a definition with the definition API, the layers have createGuide, createInput, createOutput,
createJoint, addGuideSetting, addSetting and createSpaceSwitch, then serialize it. The wheel component of
Writing A Custom Component does it from start to finish.
Common Mistakes¶
Mistake |
What happens |
|---|---|
Editing |
Nothing, the scene changes when a stage is built. |
Editing the scene and then rebuilding without reading it back. |
The change is lost, the working copy is used. |
Editing |
Every later comparison is wrong. Edit the working copy. |
Serializing a new definition against the original. |
Everything which matches the original is dropped. |
Finding nodes by name. |
Names change with the naming preset, use ids. |