Esempio n. 1
0
def main():
    import sys
    import hou

    import soho
    import sohoglue
    import SOHOcommon

    import sys
    import ctypes
    if hasattr(sys, 'setdlopenflags'):
        sys.setdlopenflags(sys.getdlopenflags() | ctypes.RTLD_GLOBAL)

    import _vfh_ipr

    from soho import SohoParm

    LogLevel = type('Enum', (), {
        'Msg': 0,
        'Info': 1,
        'Progress': 2,
        'Warning': 3,
        'Error': 4,
        'Debug': 5
    })

    def logMessage(level, fmt, *args):
        _vfh_ipr.logMessage(level, fmt % args)

    def printDebug(fmt, *args):
        logMessage(LogLevel.Debug, fmt, *args)

    def dumpObjects(listName):
        printDebug("Checking \"%s\"" % listName)
        for obj in soho.objectList(listName):
            printDebug("   %s", obj.getName())

    def exportObjects(listName):
        for obj in soho.objectList(listName):
            _vfh_ipr.exportOpNode(opNode=obj.getName())

    def deleteObjects(listName):
        for obj in soho.objectList(listName):
            _vfh_ipr.deleteOpNode(opNode=obj.getName())

    def getViewParams(camera, sohoCam, t):
        camParms = {
            'space:world': SohoParm('space:world', 'real', [], False),
            'focal': SohoParm('focal', 'real', [0.050], False),
            'aperture': SohoParm('aperture', 'real', [0.0414214], False),
            'orthowidth': SohoParm('orthowidth', 'real', [2], False),
            'near': SohoParm('near', 'real', [0.001], False),
            'far': SohoParm('far', 'real', [1000], False),
            'res': SohoParm('res', 'int', [640, 480], False),
            'projection': SohoParm('projection', 'string', ["perspective"],
                                   False),
            'cropl': SohoParm('cropl', 'real', [-1], False),
            'cropr': SohoParm('cropr', 'real', [-1], False),
            'cropb': SohoParm('cropb', 'real', [-1], False),
            'cropt': SohoParm('cropt', 'real', [-1], False),
            'camera': SohoParm('camera', 'string', ['/obj/cam1'], False)
        }

        camParmsEval = sohoCam.evaluate(camParms, t)
        if not camParmsEval:
            return {}

        viewParams = {}
        for key in camParmsEval:
            viewParams[key] = camParmsEval[key].Value[0]

        viewParams['transform'] = camParmsEval['space:world'].Value
        viewParams['ortho'] = 1 if camParmsEval['projection'].Value[0] in {
            'ortho'
        } else 0
        viewParams['res'] = camParmsEval['res'].Value

        cropX = viewParams['res'][0] * viewParams['cropl']
        cropY = viewParams['res'][1] * (1.0 - viewParams['cropt'])
        cropW = viewParams['res'][0] * (viewParams['cropr'] -
                                        viewParams['cropl'])
        cropH = viewParams['res'][1] * (viewParams['cropt'] -
                                        viewParams['cropb'])

        printDebug("  Res: %s" % viewParams['res'])
        printDebug("  Crop: %i-%i %i x %i " % (cropX, cropY, cropW, cropH))

        return viewParams

    def exportView(rop, camera, sohoCam, t):
        printDebug("exportView()")

        _vfh_ipr.exportView(viewParams=getViewParams(camera, sohoCam, t))

    mode = soho.getDefaultedString('state:previewmode', ['default'])[0]

    # Evaluate an intrinsic parameter (see HDK_SOHO_API::evaluate())
    # The 'state:time' parameter evaluates the time from the ROP.
    now = soho.getDefaultedFloat('state:time', [0.0])[0]

    # Evaluate the 'camera' parameter as a string.
    # If the 'camera' parameter doesn't exist, use ['/obj/cam1'].
    # SOHO always returns lists of values.
    camera = soho.getDefaultedString('camera', ['/obj/cam1'])[0]

    # MPlay / Render View port.
    port = soho.getDefaultedInt("vm_image_mplay_socketport", [0])[0]

    # ROP node.
    ropPath = soho.getOutputDriver().getName()
    ropNode = hou.node(ropPath)

    printDebug("Initialize SOHO...")

    # Initialize SOHO with the camera.
    # XXX: This doesn't work for me, but it should according to the documentation...
    #   soho.initialize(now, camera)
    if not sohoglue.initialize(now, camera, None):
        soho.error("Unable to initialize rendering module with given camera")

    # Now, add objects to our scene
    soho.addObjects(now, "*", "*", "*", True)

    # Before we can evaluate the scene from SOHO, we need to lock the object lists.
    soho.lockObjects(now)

    for sohoCam in soho.objectList('objlist:camera'):
        break
    else:
        soho.error("Unable to find viewing camera for render")

    sohoOverride = soho.getDefaultedString('soho_overridefile', ['Unknown'])[0]

    printDebug("Processing Mode: \"%s\"" % mode)

    if mode in {"generate"}:
        # generate: Generation phase of IPR rendering
        # In generate mode, SOHO will keep the pipe (soho_pipecmd)
        # command open between invocations of the soho_program.
        #   objlist:all
        #   objlist:camera
        #   objlist:light
        #   objlist:instance
        #   objlist:fog
        #   objlist:space
        #   objlist:mat
        #
        printDebug("IPR Port: %s" % port)
        printDebug("Driver: %s" % ropPath)
        printDebug("Camera: %s" % camera)
        printDebug("Now: %.3f" % now)

        _vfh_ipr.init(rop=ropPath,
                      port=port,
                      now=now,
                      viewParams=getViewParams(camera, sohoCam, now))

    elif mode in {"update"}:
        # update: Send updated changes from previous generation
        #
        # In this rendering mode, the special object list parameters:
        #   objlist:dirtyinstance
        #   objlist:dirtylight
        #   objlist:dirtyspace
        #   objlist:dirtyfog
        # will contain the list of all objects modified since the last render
        # (whether a generate or update).
        #
        # As well, the parameters:
        #   objlist:deletedinstance
        #   objlist:deletedlight
        #   objlist:deletedspace
        #   objlist:deletedfog
        # will list all objects which have been deleted from the scene.
        #

        if not _vfh_ipr.isRopValid():
            _vfh_ipr.init(rop=ropPath,
                          port=port,
                          now=now,
                          viewParams=getViewParams(camera, sohoCam, now))
        else:
            if _vfh_ipr.setTime(now):
                # Have to handle "time" event manually here.
                exportObjects("objlist:dirtyinstance")
                exportObjects("objlist:dirtylight")

            # Update view.
            exportView(ropPath, camera, sohoCam, now)
Esempio n. 2
0
def soho_render():
    control_parms = {
        # The time at which the scene is being rendered
        "now": SohoParm("state:time", "real", [0], False, key="now"),
        "camera": SohoParm("camera", "string", ["/obj/cam1"], False),
    }

    parms = soho.evaluate(control_parms)

    now = parms["now"].Value[0]
    camera = parms["camera"].Value[0]

    options = {}
    if not soho.initialize(now, camera, options):
        soho.error("Unable to initialize rendering module with given camera")

    object_selection = {
        # Candidate object selection
        "vobject": SohoParm("vobject", "string", ["*"], False),
        "alights": SohoParm("alights", "string", ["*"], False),
        "forceobject": SohoParm("forceobject", "string", [""], False),
        "forcelights": SohoParm("forcelights", "string", [""], False),
        "excludeobject": SohoParm("excludeobject", "string", [""], False),
        "excludelights": SohoParm("excludelights", "string", [""], False),
        "sololight": SohoParm("sololight", "string", [""], False),
    }

    for cam in soho.objectList("objlist:camera"):
        break
    else:
        soho.error("Unable to find viewing camera for render")

    objparms = cam.evaluate(object_selection, now)

    stdobject = objparms["vobject"].Value[0]
    stdlights = objparms["alights"].Value[0]
    forceobject = objparms["forceobject"].Value[0]
    forcelights = objparms["forcelights"].Value[0]
    excludeobject = objparms["excludeobject"].Value[0]
    excludelights = objparms["excludelights"].Value[0]
    sololight = objparms["sololight"].Value[0]
    forcelightsparm = "forcelights"

    if sololight:
        stdlights = excludelights = ""
        forcelights = sololight
        forcelightsparm = "sololight"

    # First, we add objects based on their display flags or dimmer values
    soho.addObjects(
        now,
        stdobject,
        stdlights,
        "",
        True,
        geo_parm="vobject",
        light_parm="alights",
        fog_parm="",
    )
    soho.addObjects(
        now,
        forceobject,
        forcelights,
        "",
        False,
        geo_parm="forceobject",
        light_parm=forcelightsparm,
        fog_parm="",
    )
    soho.removeObjects(
        now,
        excludeobject,
        excludelights,
        "",
        geo_parm="excludeobject",
        light_parm="excludelights",
        fog_parm="",
    )

    # Lock off the objects we've selected
    soho.lockObjects(now)

    with hou.undos.disabler(), scene_state:
        if "SOHO_PBRT_DEV" in os.environ:  # pragma: no coverage
            import cProfile

            pr = cProfile.Profile()
            pr.enable()
            try:
                PBRTscene.render(cam, now)
            finally:
                pr.disable()
                pr.dump_stats("hou-prbt.stats")
        else:
            PBRTscene.render(cam, now)
    return
Esempio n. 3
0
def soho_render():
    control_parms = {
        # The time at which the scene is being rendered
        'now': SohoParm('state:time', 'real', [0], False, key='now'),
        'fps': SohoParm('state:fps', 'real', [24], False, key='fps'),
        'camera': SohoParm('camera', 'string', ['/obj/cam1'], False),
    }

    parms = soho.evaluate(control_parms)

    now = parms['now'].Value[0]
    camera = parms['camera'].Value[0]
    fps = parms['fps'].Value[0]

    options = {'state:precision': 6}
    if not soho.initialize(now, camera, options):
        soho.error("Unable to initialize rendering module with given camera")

    object_selection = {
        # Candidate object selection
        'vobject': SohoParm('vobject', 'string', ['*'], False),
        'alights': SohoParm('alights', 'string', ['*'], False),
        'forceobject': SohoParm('forceobject', 'string', [''], False),
        'forcelights': SohoParm('forcelights', 'string', [''], False),
        'excludeobject': SohoParm('excludeobject', 'string', [''], False),
        'excludelights': SohoParm('excludelights', 'string', [''], False),
        'sololight': SohoParm('sololight', 'string', [''], False),
    }

    for cam in soho.objectList('objlist:camera'):
        break
    else:
        soho.error('Unable to find viewing camera for render')

    objparms = cam.evaluate(object_selection, now)

    stdobject = objparms['vobject'].Value[0]
    stdlights = objparms['alights'].Value[0]
    forceobject = objparms['forceobject'].Value[0]
    forcelights = objparms['forcelights'].Value[0]
    excludeobject = objparms['excludeobject'].Value[0]
    excludelights = objparms['excludelights'].Value[0]
    sololight = objparms['sololight'].Value[0]
    forcelightsparm = 'forcelights'

    if sololight:
        stdlights = excludelights = None
        forcelights = sololight
        forcelightsparm = 'sololight'

    # First, we add objects based on their display flags or dimmer values
    soho.addObjects(now, stdobject, stdlights, '', True)
    soho.addObjects(now, forceobject, forcelights, '', False)
    soho.removeObjects(now, excludeobject, excludelights, '')

    # Lock off the objects we've selected
    soho.lockObjects(now)

    with hou.undos.disabler(), scene_state:
        PBRTscene.render(cam, now)
    return
Esempio n. 4
0
File: APS.py Progetto: symek/haps
# Obtain the list of cameras through which we need to render. The main camera
# may specify a few sub-cameras, for example, in the stereo camera case.
camera_paths = objparms['vm_cameralist'].Value[0].split()
camera_list = []
for cam_path in camera_paths:
    camera_list.append(soho.getObject(cam_path))
if len(camera_list) == 0:
    cam.storeData('NoFileSuffix', True)
    camera_list.append(cam)

# First, we add objects based on their display flags or dimmer values
soho.addObjects(now,
                stdobject,
                stdlights,
                stdfog,
                True,
                geo_parm='vobject',
                light_parm='alights',
                fog_parm='vfog')
soho.addObjects(now,
                forceobject,
                forcelights,
                forcefog,
                False,
                geo_parm='forceobject',
                light_parm=forcelightsparm,
                fog_parm='forcefog')

# Force matte & phantom objects to be visible too
if matte_objects:
    soho.addObjects(now,
Esempio n. 5
0
objectSelection = {
    'vobject': soho.SohoParm('vobject', 'string', ['*'], False),
    'forceobject': soho.SohoParm('forceobject', 'string', [''], False),
    'excludeobject': soho.SohoParm('excludeobject', 'string', [''], False),
}

objparms = soho.evaluate(objectSelection, now)

stdobject = objparms['vobject'].Value[0]
forceobject = objparms['forceobject'].Value[0]
excludeobject = objparms['excludeobject'].Value[0]

soho.addObjects(now=now,
                geometry=stdobject,
                lights="",
                fog="",
                do_culling=True,
                geo_parm='vobject')
soho.addObjects(now=now,
                geometry=forceobject,
                lights="",
                fog="",
                do_culling=False,
                geo_parm='forceobject')
soho.removeObjects(now=now,
                   geometry=excludeobject,
                   lights="*",
                   fog="*",
                   geo_parm='excludeobject',
                   light_parm='excludelights',
                   fog_parm='excludefog')
Esempio n. 6
0
def export():
    """Main export function."""

    is_last = False

    try:
        T = timer('FrameExport')

        ps = soho.evaluate({
            'now':
            SohoParm('state:time', 'real', [0], False, key='now'),
            'fps':
            SohoParm('state:fps', 'real', [24], False, key='fps'),
            'hver':
            SohoParm('state:houdiniversion', 'string', [''], False,
                     key='hver'),
            'objpath':
            SohoParm('objpath', 'string', [''], False),
            'abcoutput':
            SohoParm('abcoutput', 'string', [''], False),
            'camera':
            SohoParm('camera', 'string', [None], False),
            'trange':
            SohoParm('trange', 'int', [0], False),
            'f':
            SohoParm('f', 'int', None, False)
        })

        now = ps['now'].Value[0]
        fps = ps['fps'].Value[0]
        hver = ps['hver'].Value[0]
        camera = ps['camera'].Value[0]

        dbg("now=%.3f fps=%.3f" % (now, fps))

        if not soho.initialize(now, camera):
            soho.error("couldn't initialize soho (make sure camera is set)")
            abc_cleanup()
            return

        # NOTE: this is prone to float inaccuracies
        frame = now * fps + 1.0

        objpath = ps['objpath'].Value[0]
        abc_file = ps['abcoutput'].Value[0]
        trange = ps['trange'].Value[0]
        f = ps['f'].Value

        is_first = frame < f[0] + 0.5  # working around float funniness
        is_last = frame > f[1] - 0.5

        if trange == 0:
            is_first = is_last = True

        dbg("is_first=%d is_last=%d" % (is_first, is_last))
        dbg("now=%.3f fps=%.3f -> %f" % (now, fps, frame))

        dbg("objpath=%s camera=%s abcoutput=%s trange=%d f=%s" % \
         (objpath, camera, abc_file, trange, str(f)))

        T.lap('init')

        # collect hierarchy to be exported
        # (read from scene directly, ie. not containing instances, etc.)
        # results in array [ (parentname, objname) [, ...]  ] -- (full pathnames)
        #
        #dbg("COLLECTING ARCHY:")
        archy = collect_archy(objpath)
        archy_objs = [n[1] for n in archy]
        #dbg("DONE.")

        # collect geometry to be exported and their render SOPS
        # (including point- and other instances, etc)
        # (NOTE: the entire scene is to be searched, unfortunately)
        #
        soho.addObjects(now, '*', '*', '', do_culling=False)
        soho.lockObjects(now)

        soho_objs = {}  # {objname: soho_obj}
        soho_only = {
        }  # soho-only objects (can't be accessed directly with hdk)

        obj_list = []
        sop_dict = {}  # {objname: sopname}
        objs = soho.objectList('objlist:instance')

        #dbg("COLLECT soho instance/sop pairs ------------------")
        for obj in objs:
            n = obj.getName()  # full pathname
            obj_list.append(n)
            soho_objs[n] = obj
            path = obj.getDefaultedString('object:soppath', now, [None])[0]
            #dbg(" -- %s (sop:%s)" % (n, str(path)) )
            if path and path != "":
                sop_dict[n] = path

        T.lap('collect-objs')

        if False:
            dbg('-' * 40)
            dbg("sop_dict: %s" % str(sop_dict))

        # extend hierarchy with per-point instances
        #
        p1 = re.compile(":[^:]+:")
        for obj in obj_list:
            if re.search(p1, obj):
                m = obj.split(":")
                p = m[-2]  # parent: 2nd from right
                if p in archy_objs:
                    archy.append((p, obj, "%s__%s" % (m[-2], m[-1])))
                    soho_only[obj] = p
                    #dbg(" -+- %s %s" % (p, obj))

        # fill rest of the archy array
        # elem: (parentpath, objpath, exportname, soppath)
        #
        archy2 = []
        for a in archy:
            N = list(a)
            if len(N) < 3: N.append(N[1])  # N = [ N[0], N[1], N[1] ]
            if N[1] in sop_dict:
                N = [N[0], N[1], N[2], sop_dict[N[1]]]
            else:
                # empty xform (no sop)
                N = [N[0], N[1], N[1], None]

            N[2] = re.search("[^/]+$", N[2]).group(0)
            archy2.append(N)
        archy = archy2

        if False:
            dbg('-' * 40)
            dbg("COLLECTED ARCHY:")
            for a in archy:
                dbg("- %s: " % (a[1], ))

        dbg("COLLECTED ARCHY: %d elems" % len(archy))

        T.lap('got-archy')

        # we now have a list of all objects to be exported
        # (parentname, objname, exportname, soppath)
        #
        archy_objs = [n[1] for n in archy]
        skip_frame = False

        now_out = now + (1.0 / fps)

        # check for user abort
        #
        if False:  # TODO: check for user abort!
            skip_frame = True
            is_last = True
            warn("user abort")

        # first frame: init all internal stuff
        #
        if is_first:
            dbg("\n\n\n")
            dbg("IS_FIRST--INIT")
            G.archy = archy[:]
            G.archy_objs = archy_objs[:]

            s = abc_init(abc_file, tstep=1.0 / fps, tstart=now_out)
            if s:
                # build objects for oarchive
                #
                for E in archy:
                    objname = E[1]
                    parent = E[0]
                    outname = E[2]
                    soppath = E[3]
                    if parent is None: parent = "-"
                    if soppath is None: soppath = "-"

                    # TODO: if instance, objname should be the base obj name
                    obj_src = objname
                    if objname in soho_only:
                        obj_src = soho_only[objname]

                    #dbg("-- new xform\n\toutname= %s\n\tobj    = %s\n\tparent = %s\n\tsop    = %s" % (outname, objname, parent, soppath))

                    hou.hscript('%s newobject "%s" "%s" "%s" "%s" "%s"' % \
                     (CCMD, objname, obj_src, parent, outname, soppath))

                    # set object flags (static, etc.)
                    #
                    if objname in soho_objs:
                        ps = soho_objs[objname].evaluate(
                            {
                                'abc_staticgeo':
                                SohoParm('abc_staticgeo', 'int', [0], False)
                            }, now)

                        if ps['abc_staticgeo'].Value[0] != 0:
                            hou.hscript('%s objset "%s" static' %
                                        (CCMD, objname))

            else:
                warn("couldn't output to file %s--aborting" % abc_file)
                skip_frame = True
                is_last = True

        T.lap('frame-first')

        # frame export: collect xforms, geoms, and export them
        #
        if archy_objs == G.archy_objs and not skip_frame:

            dbg("\n")
            dbg(" -- EXPORTING frame %.1f" % frame)

            for E in archy:
                #dbg("\n-")
                #dbg("- OBJ: %s" % str(E))
                objname = E[1]
                soppath = E[3]
                #dbg("- OBJ: %s" % E[1])

                # get xform matrix (TODO: get pretransform too!)
                #
                xform = ''

                # TODO: use this only for instances!
                #if objname in soho_objs:
                if objname in soho_only:
                    # get matrix from soho
                    #dbg(" --- (mtx from soho)")
                    xform = []
                    soho_objs[objname].evalFloat('space:local', now, xform)
                    xform = hou.Matrix4(xform)
                    xform = ' '.join([str(n) for n in xform.asTuple()])

                # perform sample write
                # (c++ code decides if geom is to be written)
                #
                if True:
                    hou.hscript('%s writesample %f "%s" %s' % \
                     (CCMD, now_out, objname, xform))

        else:
            #soho.error("couldn't export frame %.1f--no. of objects changed" % frame)
            warn("couldn't export frame %.1f--no. of objects changed" % frame)

        T.lap('frame-export')

    except:
        dbg("INTERRUPTED BY EXCEPTION")
        is_last = True

    # last frame: cleanup all internal stuff,
    # finish export
    #
    if is_last:
        dbg("\n\n\n")
        dbg("IS_LAST--FINISHING...")
        abc_cleanup()

    T.lap('frame-last')

    T.stats()
Esempio n. 7
0
ropPath = soho.getOutputDriver().getName()
ropNode = hou.node(ropPath)

# Use callbacks or SOHO
render_rt_update_mode = hou.evalParm("render_rt_update_mode")

printDebug("Initialize SOHO...")

# Initialize SOHO with the camera.
# XXX: This doesn't work for me, but it should according to the documentation...
#   soho.initialize(now, camera)
if not sohoglue.initialize(now, camera, None):
    soho.error("Unable to initialize rendering module with given camera")

# Now, add objects to our scene
soho.addObjects(now, "*", "*", "*", True)

# Before we can evaluate the scene from SOHO, we need to lock the object lists.
soho.lockObjects(now)

for cam in soho.objectList('objlist:camera'):
    break
else:
    soho.error("Unable to find viewing camera for render")

sohoOverride = soho.getDefaultedString('soho_overridefile', ['Unknown'])[0]

# Check if there are any camera overrides.
camParmsEval = cam.evaluate(camParms, now)
if camParmsEval:
    printDebug("Camera overrides:")
Esempio n. 8
0
def soho_render():
    control_parms = {
        # The time at which the scene is being rendered
        "now": SohoParm("state:time", "real", [0], False, key="now")
    }

    parms = soho.evaluate(control_parms)

    now = parms["now"].Value[0]
    camera = None

    options = {}
    if not soho.initialize(now, camera, options):
        soho.error("Unable to initialize rendering module with given camera")

    object_selection = {
        # Candidate object selection
        "vobject": SohoParm("vobject", "string", ["*"], False),
        "forceobject": SohoParm("forceobject", "string", [""], False),
        "excludeobject": SohoParm("excludeobject", "string", [""], False),
    }

    objparms = soho.evaluate(object_selection, now)

    stdobject = objparms["vobject"].Value[0]
    forceobject = objparms["forceobject"].Value[0]
    excludeobject = objparms["excludeobject"].Value[0]

    # First, we add objects based on their display flags or dimmer values
    soho.addObjects(now,
                    stdobject,
                    "",
                    "",
                    True,
                    geo_parm="vobject",
                    light_parm="",
                    fog_parm="")
    soho.addObjects(
        now,
        forceobject,
        "",
        "",
        False,
        geo_parm="forceobject",
        light_parm="",
        fog_parm="",
    )
    soho.removeObjects(now,
                       excludeobject,
                       "",
                       "",
                       geo_parm="excludeobject",
                       light_parm="",
                       fog_parm="")

    # Lock off the objects we've selected
    soho.lockObjects(now)

    with hou.undos.disabler(), scene_state:
        if "SOHO_PBRT_DEV" in os.environ:  # pragma: no coverage
            import cProfile

            pr = cProfile.Profile()
            pr.enable()
            try:
                PBRTscene.archive(now)
            finally:
                pr.disable()
                pr.dump_stats("hou-prbtarchive.stats")
        else:
            PBRTscene.archive(now)
    return
def export():
	"""Main export function."""

	is_last = False

	try:
		T = timer('FrameExport')

		ps = soho.evaluate({
			'now':		SohoParm('state:time',			'real', [0],  False, key='now'),
			'fps':		SohoParm('state:fps',			'real', [24],  False, key='fps'),
			'hver':		SohoParm('state:houdiniversion',	'string', [''],  False, key='hver'),
			'objpath':	SohoParm('objpath',		'string',	[''], False),
			'abcoutput':	SohoParm('abcoutput',		'string',	[''], False),
			'camera':	SohoParm('camera',		'string',	[None], False),
			'trange':	SohoParm('trange',		'int',		[0], False),
			'f':		SohoParm('f',			'int',		None, False)
		})
		
		now = ps['now'].Value[0]
		fps = ps['fps'].Value[0]
		hver = ps['hver'].Value[0]
		camera = ps['camera'].Value[0]

		dbg("now=%.3f fps=%.3f" % (now, fps))

		if not soho.initialize(now, camera):
			soho.error("couldn't initialize soho (make sure camera is set)")
			abc_cleanup()
			return

		# NOTE: this is prone to float inaccuracies
		frame = now*fps + 1.0

		objpath   = ps['objpath'].Value[0]
		abc_file  = ps['abcoutput'].Value[0]
		trange    = ps['trange'].Value[0]
		f         = ps['f'].Value

		is_first  = frame < f[0]+0.5 # working around float funniness
		is_last   = frame > f[1]-0.5

		if trange==0:
			is_first= is_last= True

		dbg("is_first=%d is_last=%d" % (is_first, is_last))
		dbg("now=%.3f fps=%.3f -> %f" % (now, fps, frame))

		dbg("objpath=%s camera=%s abcoutput=%s trange=%d f=%s" % \
			(objpath, camera, abc_file, trange, str(f)))

		T.lap('init')

		# collect hierarchy to be exported
		# (read from scene directly, ie. not containing instances, etc.)
		# results in array [ (parentname, objname) [, ...]  ] -- (full pathnames)
		#
		#dbg("COLLECTING ARCHY:")
		archy = collect_archy(objpath)
		archy_objs = [ n[1] for n in archy ]
		#dbg("DONE.")


		# collect geometry to be exported and their render SOPS
		# (including point- and other instances, etc)
		# (NOTE: the entire scene is to be searched, unfortunately)
		#
		soho.addObjects(now, '*', '*', '', do_culling=False)
		soho.lockObjects(now)

		soho_objs = {} # {objname: soho_obj}
		soho_only = {} # soho-only objects (can't be accessed directly with hdk)

		obj_list = []
		sop_dict = {} # {objname: sopname}
		objs = soho.objectList('objlist:instance')

		#dbg("COLLECT soho instance/sop pairs ------------------")
		for obj in objs:
			n = obj.getName() # full pathname
			obj_list.append(n)
			soho_objs[n] = obj
			path = obj.getDefaultedString('object:soppath', now, [None])[0]
			#dbg(" -- %s (sop:%s)" % (n, str(path)) )
			if path and path!="":
				sop_dict[n] = path

		T.lap('collect-objs')

		if False:
			dbg( '-' * 40 )
			dbg("sop_dict: %s" % str(sop_dict))

		# extend hierarchy with per-point instances
		#
		p1 = re.compile(":[^:]+:")
		for obj in obj_list:
			if re.search(p1, obj):
				m = obj.split(":")
				p = m[-2] # parent: 2nd from right
				if p in archy_objs:
					archy.append( ( p, obj, "%s__%s" % (m[-2], m[-1]) )  )
					soho_only[obj]=p
					#dbg(" -+- %s %s" % (p, obj))


		# fill rest of the archy array
		# elem: (parentpath, objpath, exportname, soppath)
		#
		archy2 = []
		for a in archy:
			N = list(a)
			if len(N)<3: N.append(N[1]) # N = [ N[0], N[1], N[1] ]
			if N[1] in sop_dict:
				N = [ N[0], N[1], N[2], sop_dict[N[1]] ]
			else:
				# empty xform (no sop)
				N = [ N[0], N[1], N[1], None ]
			
			N[2] = re.search("[^/]+$", N[2]).group(0)
			archy2.append(N)
		archy = archy2

		if False:
			dbg( '-' * 40 )
			dbg("COLLECTED ARCHY:")
			for a in archy:
				dbg("- %s: " % (a[1], ))

		dbg("COLLECTED ARCHY: %d elems" % len(archy))

		T.lap('got-archy')

		# we now have a list of all objects to be exported
		# (parentname, objname, exportname, soppath)
		#
		archy_objs = [ n[1] for n in archy ]
		skip_frame = False

		now_out = now+(1.0/fps)

		# check for user abort
		#
		if False: # TODO: check for user abort!
			skip_frame = True
			is_last = True
			warn("user abort")


		# first frame: init all internal stuff
		#
		if is_first:
			dbg("\n\n\n")
			dbg("IS_FIRST--INIT")
			G.archy = archy[:]
			G.archy_objs = archy_objs[:]

			s = abc_init(abc_file, tstep=1.0/fps, tstart=now_out)
			if s:
				# build objects for oarchive
				#
				for E in archy:
					objname = E[1]
					parent  = E[0]
					outname = E[2]
					soppath = E[3]
					if parent is None: parent="-"
					if soppath is None: soppath="-"

					# TODO: if instance, objname should be the base obj name
					obj_src = objname
					if objname in soho_only:
						obj_src = soho_only[objname]

					#dbg("-- new xform\n\toutname= %s\n\tobj    = %s\n\tparent = %s\n\tsop    = %s" % (outname, objname, parent, soppath))

					hou.hscript('%s newobject "%s" "%s" "%s" "%s" "%s"' % \
						(CCMD, objname, obj_src, parent, outname, soppath))

					# set object flags (static, etc.)
					#
					if objname in soho_objs:
						ps = soho_objs[objname].evaluate({
							'abc_staticgeo': SohoParm('abc_staticgeo', 'int', [0], False)
						}, now)

						if ps['abc_staticgeo'].Value[0]!=0:
							hou.hscript('%s objset "%s" static' % (CCMD, objname))

			else:
				warn("couldn't output to file %s--aborting" % abc_file)
				skip_frame = True
				is_last = True

		T.lap('frame-first')


		# frame export: collect xforms, geoms, and export them
		#
		if archy_objs==G.archy_objs  and  not skip_frame:

			dbg("\n")
			dbg(" -- EXPORTING frame %.1f" % frame)

			for E in archy:
				#dbg("\n-")
				#dbg("- OBJ: %s" % str(E))
				objname = E[1]
				soppath = E[3]
				#dbg("- OBJ: %s" % E[1])

				# get xform matrix (TODO: get pretransform too!)
				#
				xform = ''

				# TODO: use this only for instances!
				#if objname in soho_objs:
				if objname in soho_only:
					# get matrix from soho
					#dbg(" --- (mtx from soho)")
					xform = []
					soho_objs[objname].evalFloat('space:local', now, xform)
					xform = hou.Matrix4(xform)
					xform = ' '.join([ str(n) for n in xform.asTuple() ])

				# perform sample write
				# (c++ code decides if geom is to be written)
				#
				if True:
					hou.hscript('%s writesample %f "%s" %s' % \
						(CCMD, now_out, objname, xform))

		else:
			#soho.error("couldn't export frame %.1f--no. of objects changed" % frame)
			warn("couldn't export frame %.1f--no. of objects changed" % frame)


		T.lap('frame-export')

	except:
		dbg("INTERRUPTED BY EXCEPTION")
		is_last=True


	# last frame: cleanup all internal stuff,
	# finish export
	#
	if is_last:
		dbg("\n\n\n")
		dbg("IS_LAST--FINISHING...")
		abc_cleanup()

	T.lap('frame-last')

	T.stats()
Esempio n. 10
0
forceobject = objparms['forceobject'].Value[0]
forcelights = objparms['forcelights'].Value[0]
forcefog = objparms['forcefog'].Value[0]
excludeobject = objparms['excludeobject'].Value[0]
excludelights = objparms['excludelights'].Value[0]
excludefog = objparms['excludefog'].Value[0]
sololight = objparms['sololight'].Value[0]
forcelightsparm = 'forcelights'

if sololight:
    stdlights = excludelights = ''
    forcelights = sololight
    forcelightsparm = 'sololight'

# First, we add objects based on their display flags or dimmer values
soho.addObjects(now, stdobject, stdlights, stdfog, True,
    geo_parm='vobject', light_parm='alights', fog_parm='vfog')
soho.addObjects(now, forceobject, forcelights, forcefog, False,
    geo_parm='forceobject', light_parm=forcelightsparm, fog_parm='forcefog')
soho.removeObjects(now, excludeobject, excludelights, excludefog,
    geo_parm='excludeobject', light_parm='excludelights', fog_parm='excludefog')

# Lock off the objects we've selected
soho.lockObjects(now)

############################## Camara stuff ###################
# Parameters we evaluate on the camera to determine the viewing
# frustum
camParms = {
    'space:world':SohoParm('space:world',       'real', [], False),
    'focal'      :SohoParm('focal',             'real', [0.050], False),
    'aperture'   :SohoParm('aperture',          'real', [0.0414214], False),
Esempio n. 11
0
forcelights = objparms['forcelights'].Value[0]
forcefog = objparms['forcefog'].Value[0]
excludeobject = objparms['excludeobject'].Value[0]
excludelights = objparms['excludelights'].Value[0]
excludefog = objparms['excludefog'].Value[0]
sololight = objparms['sololight'].Value[0]
matte_objects = objparms['matte_objects'].Value[0]
phantom_objects = objparms['phantom_objects'].Value[0]
forcelightsparm = 'forcelights'
if sololight:
    stdlights = excludelights = ''
    forcelights = sololight
    forcelightsparm = 'sololight'

# First, we add objects based on their display flags or dimmer values
soho.addObjects(now, stdobject, stdlights, stdfog, True,
    geo_parm='vobject', light_parm='alights', fog_parm='vfog')
soho.addObjects(now, forceobject, forcelights, forcefog, False,
    geo_parm='forceobject', light_parm=forcelightsparm, fog_parm='forcefog')

# Force matte & phantom objects to be visible too
if matte_objects:
    soho.addObjects(now, matte_objects, '', '', False,
	geo_parm='matte_objects', light_parm='', fog_parm='')
if phantom_objects:
    soho.addObjects(now, phantom_objects, '', '', False,
	geo_parm='phantom_objects', light_parm='', fog_parm='')
soho.removeObjects(now, excludeobject, excludelights, excludefog,
    geo_parm='excludeobject', light_parm='excludelights', fog_parm='excludefog')

    
# Lock off the objects we've selected
Esempio n. 12
0
# However, for our purposes, we don't actually need a camera, so...
camera = None

# Evaluate an intrinsic parameter (see HDK_SOHO_API::evaluate())
# The 'state:time' parameter evaluates the time from the ROP.
evaltime = soho.getDefaultedFloat('state:time', [0.0])[0]

# Initialize SOHO with the camera.
if not soho.initialize(evaltime, camera):
    soho.error('Unable to initialize rendering module with camera: %s' %
               repr(camera))

# Now, add objects to our scene
#   addObjects(time, geometry, light, fog, use_display_flags)
soho.addObjects(evaltime, "*", "*", "*", True)

# Before we can evaluate the scene from SOHO, we need to lock the object lists.
soho.lockObjects(evaltime)


# Now, traverse all the objects
def outputObjects(fp, prefix, list):
    fp.write('%s = {' % prefix)
    for obj in list:
        fp.write('"%s",' % obj.getName())
    fp.write('}\n')
    fp.flush()


fp = sys.stdout