openMaya contexts

hey im trying to figure out how to create contexts in maya via the python api

this is what i got this thus far.


import maya.OpenMaya as om
import maya.OpenMayaMPx as mpx
import sys


kPluginCtxName = 'myContext'
kPluginCmdName = 'myContextCmd'


class context(mpx.MPxContext):
    def __init__(self):
        mpx.MPxCommand.__init__(self)

    def doPress(self, event):
        sys.stderr.write('It works I hope!!!!!')


class contextCommand(mpx.MPxContextCommand):
    def __init__(self):
        mpx.MPxContextCommand.__init__(self)

    def makeObj(self):
        return mpx.asMPxPtr(context())

    @classmethod
    def creator(cls):
        return mpx.asMPxPtr(cls())


def initializePlugin(mobject):
    mplugin = mpx.MFnPlugin(mobject, "Passerby", "1.0", "Any")
    try:
        mplugin.registerContextCommand(kPluginCtxName, contextCommand.creator)
    except:
        sys.stderr.write("Failed to register context command: %s
" % kPluginCtxName)
        raise


# Uninitialize the script plug-in
def uninitializePlugin(mobject):
    mplugin = mpx.MFnPlugin(mobject)
    try:
        mplugin.deregisterContextCommand(kPluginCtxName, kPluginCmdName)
    except:
        sys.stderr.write("Failed to deregister context command: %s
" % kPluginCtxName)
        raise

the plugin loads without errors, but the problem is once i call maya.cmds.myContext() i get this error.

# Error: TypeError: file <string> line 2: Swig director type mismatch in output value of type 'MPxContext *' # 

my bad it was just a type on line 12 was calling the wrong init()

Hey Passerby,

Sorry to resurrect an old thread, but I am trying to create my own context and you seem to have had luck with it.

My goal is to create a python context that enables me to click and drag in a viewport to edit a voxel terrain, so ideally I need to click and drag across multiple meshes and “collect” the faces that are being touched. I haven’t really jumped into Python that much before so I am using this as a good learning lesson.

I am porting my Unity voxel terrain editor to Maya:

I tried testing your code above. I modified it so it loads the plugin correctly, and I can call maya.cmds.myContext() successfully, but when I click in the viewport I was hoping that ‘It works I hope!!!’ would print but it does not.

Any advice you could offer to point me in the right direction would be much appreciated! Thanks!

Ah finally got it to work. Took forever but I found out this context setup only works in Legacy Default Viewport (not viewport 2.0). Switching it to Legacy and all a sudden all my mouse events are firing! Yay!