GfMatrix4d
Hdx_UnitTestGLDrawing::GetViewMatrix() const
{
    GfMatrix4d viewMatrix;
    viewMatrix.SetIdentity();
    // rotate from z-up to y-up
    viewMatrix *= GfMatrix4d().SetRotate(GfRotation(GfVec3d(1.0,0.0,0.0), -90.0));
    viewMatrix *= GfMatrix4d().SetRotate(GfRotation(GfVec3d(0, 1, 0), _rotate[1]));
    viewMatrix *= GfMatrix4d().SetRotate(GfRotation(GfVec3d(1, 0, 0), _rotate[0]));
    viewMatrix *= GfMatrix4d().SetTranslate(GfVec3d(_translate[0], _translate[1], _translate[2]));

    return viewMatrix;
}
Example #2
0
GfMatrix4d
UsdGeomConstraintTarget::ComputeInWorldSpace(
    UsdTimeCode time,
    UsdGeomXformCache *xfCache) const
{
    if (not IsDefined()) {
        TF_CODING_ERROR("Invalid constraint target.");
        return GfMatrix4d(1);
    }

    const UsdPrim &modelPrim = GetAttr().GetPrim();

    GfMatrix4d localToWorld(1);
    if (xfCache) {
        xfCache->SetTime(time);
        localToWorld = xfCache->GetLocalToWorldTransform(modelPrim);
    } else {
        UsdGeomXformCache cache;
        cache.SetTime(time);
        localToWorld = cache.GetLocalToWorldTransform(modelPrim);
    }

    GfMatrix4d localConstraintSpace(1.);
    if (not Get(&localConstraintSpace, time)) {
        TF_WARN("Failed to get value of constraint target '%s' at path <%s>.",
                GetIdentifier().GetText(), GetAttr().GetPath().GetText());
        return localConstraintSpace;
    }

    return localConstraintSpace * localToWorld;
}
Example #3
0
void
UsdMayaGLBatchRenderer::ShapeRenderer::PrepareForQueue(
    const MDagPath &objPath,
    UsdTimeCode time,
    uint8_t refineLevel,
    bool showGuides,
    bool showRenderGuides,
    bool tint,
    GfVec4f tintColor )
{
    // Initialization of default parameters go here. These parameters get used
    // in all viewports and for selection.
    //
    _baseParams.frame = time;
    _baseParams.refineLevel = refineLevel;

    // XXX Not yet adding ability to turn off display of proxy geometry, but
    // we should at some point, as in usdview
    _baseParams.renderTags.clear();
    _baseParams.renderTags.push_back(HdTokens->geometry);
    _baseParams.renderTags.push_back(HdTokens->proxy);
    if (showGuides) {
        _baseParams.renderTags.push_back(HdTokens->guide);
    } 
    if (showRenderGuides) {
        _baseParams.renderTags.push_back(_tokens->render);
    }
    
    if( tint )
        _baseParams.overrideColor = tintColor;

    if( _delegate )
    {
        MStatus status;
        MMatrix transform = objPath.inclusiveMatrix( &status );
        if( status )
        {
            _rootXform = GfMatrix4d( transform.matrix );
            _delegate->SetRootTransform(_rootXform);
        }

        _delegate->SetRefineLevelFallback(refineLevel);

        // Will only react if time actually changes.
        _delegate->SetTime(time);

        _delegate->SetRootCompensation(_rootPrim.GetPath());

        if( !_isPopulated )
            _batchRenderer->_populateQueue.insert(this);
    }
}
Example #4
0
UsdMayaGLBatchRenderer::TaskDelegate::TaskDelegate(
    HdRenderIndex *renderIndex, SdfPath const& delegateID)
    : HdSceneDelegate(renderIndex, delegateID)
{
    _lightingContext = GlfSimpleLightingContext::New();

    // populate tasks in renderindex

    // create an unique namespace
    _rootId = delegateID.AppendChild(
        TfToken(TfStringPrintf("_UsdImaging_%p", this)));

    _simpleLightTaskId          = _rootId.AppendChild(_tokens->simpleLightTask);
    _cameraId                   = _rootId.AppendChild(_tokens->camera);

    // camera
    {
        // Since we're hardcoded to use HdStRenderDelegate, we expect to
        // have camera Sprims.
        TF_VERIFY(renderIndex->IsSprimTypeSupported(HdPrimTypeTokens->camera));

        renderIndex->InsertSprim(HdPrimTypeTokens->camera, this, _cameraId);
        _ValueCache &cache = _valueCacheMap[_cameraId];
        cache[HdStCameraTokens->worldToViewMatrix] = VtValue(GfMatrix4d(1.0));
        cache[HdStCameraTokens->projectionMatrix] = VtValue(GfMatrix4d(1.0));
        cache[HdStCameraTokens->windowPolicy] = VtValue();  // no window policy.
    }

    // simple lighting task (for Hydra native)
    {
        renderIndex->InsertTask<HdxSimpleLightTask>(this, _simpleLightTaskId);
        _ValueCache &cache = _valueCacheMap[_simpleLightTaskId];
        HdxSimpleLightTaskParams taskParams;
        taskParams.cameraPath = _cameraId;
        cache[HdTokens->params] = VtValue(taskParams);
        cache[HdTokens->children] = VtValue(SdfPathVector());
    }
}
static void
_MatrixToVectorsWithPivotInvariant(
    const GfMatrix4d &m,
    const GfVec3d pivotPosition,
    const GfVec3d pivotOrientation,
    GfVec3d *translation, 
    GfVec3d *rotation, 
    GfVec3d *scale, 
    GfVec3d *scaleOrientation) 
{

    GfMatrix3d pivotOrientMat = _EulerXYZToMatrix3d(pivotOrientation);

    GfMatrix4d pp    = GfMatrix4d(1.0).SetTranslate( pivotPosition);
    GfMatrix4d ppInv = GfMatrix4d(1.0).SetTranslate(-pivotPosition);
    GfMatrix4d po    = GfMatrix4d(1.0).SetRotate(pivotOrientMat);
    GfMatrix4d poInv = GfMatrix4d(1.0).SetRotate(pivotOrientMat.GetInverse());

    GfMatrix4d factorMe = po * pp * m * ppInv;

    GfMatrix4d scaleOrientMat, factoredRotMat, perspMat;

    factorMe.Factor(&scaleOrientMat, scale, &factoredRotMat, 
                    translation, &perspMat);

    GfMatrix4d rotMat = factoredRotMat * poInv;

    if(not rotMat.Orthonormalize(/* issueWarning */ false))
        TF_WARN("Failed to orthonormalize rotMat.");

    _RotMatToRotTriplet(rotMat, rotation);

    if(not scaleOrientMat.Orthonormalize(/* issueWarning */ false))
        TF_WARN("Failed to orthonormalize scaleOrientMat.");

    _RotMatToRotTriplet(scaleOrientMat, scaleOrientation);
}
Example #6
0
bool
UsdSkelSkeletonQuery::ComputeJointRestRelativeTransforms(
    VtMatrix4dArray* xforms, UsdTimeCode time) const
{
    TRACE_FUNCTION();

    if (!xforms) {
        TF_CODING_ERROR("'xforms' pointer is null.");
        return false;
    }

    if(TF_VERIFY(IsValid(), "invalid skeleton query.")) {
        if (_HasMappableAnim()) {
            // jointLocalXf = restRelativeXf * restXf
            // restRelativeXf = jointLocalXf * inv(restXf)

            // Pull inverse rest transforms first
            // They are cached on the definition.
            VtMatrix4dArray invRestXforms;
            if (_definition->GetJointLocalInverseRestTransforms(
                    &invRestXforms)) {

                VtMatrix4dArray localXforms;
                if (_ComputeJointLocalTransforms(
                        &localXforms, time, /*atRest*/ false)) {
                    if (TF_VERIFY(localXforms.size() == invRestXforms.size())) {
                        
                        xforms->resize(localXforms.size());

                        _MultTransforms(localXforms.cdata(),
                                        invRestXforms.cdata(),
                                        xforms->data(), xforms->size());
                        return true;
                    }
                }
            } else {
                TF_WARN("%s -- Failed computing rest-relative transforms: "
                        "the 'restTransforms' of the Skeleton are either unset, "
                        "or do not have a matching number of joints.",
                        GetSkeleton().GetPrim().GetPath().GetText());
            }
        } else {
            // No bound animation, so rest relative transforms are identity.
            xforms->assign(GetTopology().GetNumJoints(), GfMatrix4d(1));
            return true;
        }
    }
    return false;
}
Example #7
0
void
Hd_TestDriver::_Init(HdReprSelector const &reprSelector)
{
    _renderIndex = HdRenderIndex::New(&_renderDelegate);
    TF_VERIFY(_renderIndex != nullptr);

    _sceneDelegate = new HdUnitTestDelegate(_renderIndex,
                                             SdfPath::AbsoluteRootPath());

    _reprSelector = reprSelector;

    GfMatrix4d viewMatrix = GfMatrix4d().SetIdentity();
    viewMatrix *= GfMatrix4d().SetTranslate(GfVec3d(0.0, 1000.0, 0.0));
    viewMatrix *= GfMatrix4d().SetRotate(GfRotation(GfVec3d(1.0, 0.0, 0.0), -90.0));

    GfFrustum frustum;
    frustum.SetPerspective(45, true, 1, 1.0, 10000.0);
    GfMatrix4d projMatrix = frustum.ComputeProjectionMatrix();

    SetCamera(viewMatrix, projMatrix, GfVec4d(0, 0, 512, 512));

    // set depthfunc to default
    _renderPassState->SetDepthFunc(HdCmpFuncLess);
}
Example #8
0
PXR_NAMESPACE_OPEN_SCOPE


// Sentinel value for prim restarts, so that multiple prims can be lumped into a
// single draw call, if the hardware supports it.
#define _PRIM_RESTART_INDEX 0xffffffff 

UsdImagingGLRefEngine::UsdImagingGLRefEngine(const SdfPathVector &excludedPrimPaths) :
    _ctm(GfMatrix4d(1.0)),
    _vertCount(0),
    _lineVertCount(0),
    _attribBuffer(0),
    _indexBuffer(0)
{
    // Build a TfHashSet of excluded prims for fast rejection.
    TF_FOR_ALL(pathIt, excludedPrimPaths) {
        _excludedSet.insert(*pathIt);
    }
void
My_TestGLDrawing::DrawTest(bool offscreen)
{
    std::cout << "My_TestGLDrawing::DrawTest()\n";

    HdPerfLog& perfLog = HdPerfLog::GetInstance();
    perfLog.Enable();
    
    // Reset all counters we care about.
    perfLog.ResetCache(HdTokens->extent);
    perfLog.ResetCache(HdTokens->points);
    perfLog.ResetCache(HdTokens->topology);
    perfLog.ResetCache(HdTokens->transform);
    perfLog.SetCounter(UsdImagingTokens->usdVaryingExtent, 0);
    perfLog.SetCounter(UsdImagingTokens->usdVaryingPrimvar, 0);
    perfLog.SetCounter(UsdImagingTokens->usdVaryingTopology, 0);
    perfLog.SetCounter(UsdImagingTokens->usdVaryingVisibility, 0);
    perfLog.SetCounter(UsdImagingTokens->usdVaryingXform, 0);

    int width = GetWidth(), height = GetHeight();

    double aspectRatio = double(width)/height;
    GfFrustum frustum;
    frustum.SetPerspective(60.0, aspectRatio, 1, 100000.0);

    GfMatrix4d viewMatrix;
    viewMatrix.SetIdentity();
    viewMatrix *= GfMatrix4d().SetRotate(GfRotation(GfVec3d(0, 1, 0), _rotate[0]));
    viewMatrix *= GfMatrix4d().SetRotate(GfRotation(GfVec3d(1, 0, 0), _rotate[1]));
    viewMatrix *= GfMatrix4d().SetTranslate(GfVec3d(_translate[0], _translate[1], _translate[2]));

    GfMatrix4d projMatrix = frustum.ComputeProjectionMatrix();

    GfMatrix4d modelViewMatrix = viewMatrix; 
    if (UsdGeomGetStageUpAxis(_stage) == UsdGeomTokens->z) {
        // rotate from z-up to y-up
        modelViewMatrix = 
            GfMatrix4d().SetRotate(GfRotation(GfVec3d(1.0,0.0,0.0), -90.0)) *
            modelViewMatrix;
    }

    GfVec4d viewport(0, 0, width, height);
    _engine->SetCameraState(modelViewMatrix, projMatrix, viewport);

    size_t i = 0;
    TF_FOR_ALL(timeIt, GetTimes()) {
        UsdTimeCode time = *timeIt;
        if (*timeIt == -999) {
            time = UsdTimeCode::Default();
        }
        UsdImagingGLRenderParams params;
        params.drawMode = GetDrawMode();
        params.enableLighting = IsEnabledTestLighting();
        params.enableIdRender = IsEnabledIdRender();
        params.frame = time;
        params.complexity = _GetComplexity();
        params.cullStyle = IsEnabledCullBackfaces() ?
                            UsdImagingGLCullStyle::CULL_STYLE_BACK :
                            UsdImagingGLCullStyle::CULL_STYLE_NOTHING;

        glViewport(0, 0, width, height);

        glEnable(GL_DEPTH_TEST);

        if(IsEnabledTestLighting()) {
            if(UsdImagingGLEngine::IsHydraEnabled()) {
                _engine->SetLightingState(_lightingContext);
            } else {
                _engine->SetLightingStateFromOpenGL();
            }
        }

        if (!GetClipPlanes().empty()) {
            params.clipPlanes = GetClipPlanes();
            for (size_t i=0; i<GetClipPlanes().size(); ++i) {
                glEnable(GL_CLIP_PLANE0 + i);
            }
        }

        GfVec4f const &clearColor = GetClearColor();
        GLfloat clearDepth[1] = { 1.0f };

        // Make sure we render to convergence.
        TfErrorMark mark;
        do {
            glClearBufferfv(GL_COLOR, 0, clearColor.data());
            glClearBufferfv(GL_DEPTH, 0, clearDepth);
            _engine->Render(_stage->GetPseudoRoot(), params);
        } while (!_engine->IsConverged());
        TF_VERIFY(mark.IsClean(), "Errors occurred while rendering!");

        std::cout << "itemsDrawn " << perfLog.GetCounter(HdTokens->itemsDrawn) << std::endl;
        std::cout << "totalItemCount " << perfLog.GetCounter(HdTokens->totalItemCount) << std::endl;

        std::string imageFilePath = GetOutputFilePath();
        if (!imageFilePath.empty()) {
            if (time != UsdTimeCode::Default()) {
                std::stringstream suffix;
                suffix << "_" << std::setw(3) << std::setfill('0') << params.frame << ".png";
                imageFilePath = TfStringReplace(imageFilePath, ".png", suffix.str());
            }
            std::cout << imageFilePath << "\n";
            WriteToFile("color", imageFilePath);
        }
        i++;
    }
Example #10
0
void
My_TestGLDrawing::InitTest()
{
    _renderIndex = HdRenderIndex::New(&_renderDelegate);
    TF_VERIFY(_renderIndex != nullptr);
    _delegate = new Hdx_UnitTestDelegate(_renderIndex);

    _delegate->SetRefineLevel(_refineLevel);

    // prepare render task
    SdfPath renderSetupTask("/renderSetupTask");
    SdfPath renderTask("/renderTask");
    _delegate->AddRenderSetupTask(renderSetupTask);
    _delegate->AddRenderTask(renderTask);

    // render task parameters.
    HdxRenderTaskParams param
        = _delegate->GetTaskParam(
            renderSetupTask, HdTokens->params).Get<HdxRenderTaskParams>();
    param.enableLighting = true; // use default lighting
    _delegate->SetTaskParam(renderSetupTask, HdTokens->params, VtValue(param));
    _delegate->SetTaskParam(renderTask, HdTokens->collection,
                           VtValue(HdRprimCollection(HdTokens->geometry,
                                   _reprName)));

    // prepare scene
    // To ensure that the non-aggregated element index returned via picking, 
    // we need to have at least two cubes with uniform colors.
    GfVec4f red(1,0,0,1), green(0,1,0,1), blue(0,0,1,1),
            yellow(1,1,0,1), magenta(1,0,1,1), cyan(0,1,1,1),
            white(1,1,1,1), black(0,0,0,1);

    GfVec4f faceColors[] = { red, green, blue, yellow, magenta, cyan};
    VtValue faceColor = VtValue(_BuildArray(&faceColors[0],
                                 sizeof(faceColors)/sizeof(faceColors[0])));

    GfVec4f vertColors[] = { white, blue, green, yellow,
                             black, blue, magenta, red};
    VtValue vertColor = VtValue(_BuildArray(&vertColors[0],
                                 sizeof(vertColors)/sizeof(vertColors[0])));

    _delegate->AddCube(SdfPath("/cube0"), _GetTranslate( 5, 0, 5),
                       /*guide=*/false, /*instancerId=*/SdfPath(),
                       /*scheme=*/PxOsdOpenSubdivTokens->catmark,
                       /*color=*/faceColor,
                       /*colorInterpolation=*/Hdx_UnitTestDelegate::UNIFORM);
    _delegate->AddCube(SdfPath("/cube1"), _GetTranslate(-5, 0, 5),
                       /*guide=*/false, /*instancerId=*/SdfPath(),
                       /*scheme=*/PxOsdOpenSubdivTokens->catmark,
                       /*color=*/faceColor,
                       /*colorInterpolation=*/Hdx_UnitTestDelegate::UNIFORM);
    _delegate->AddCube(SdfPath("/cube2"), _GetTranslate(-5, 0,-5));
    _delegate->AddCube(SdfPath("/cube3"), _GetTranslate( 5, 0,-5),
                        /*guide=*/false, /*instancerId=*/SdfPath(),
                       /*scheme=*/PxOsdOpenSubdivTokens->catmark,
                       /*color=*/vertColor,
                       /*colorInterpolation=*/Hdx_UnitTestDelegate::VERTEX);

    {
        _delegate->AddInstancer(SdfPath("/instancerTop"));
        _delegate->AddCube(SdfPath("/protoTop"),
                         GfMatrix4d(1), false, SdfPath("/instancerTop"));

        std::vector<SdfPath> prototypes;
        prototypes.push_back(SdfPath("/protoTop"));

        VtVec3fArray scale(3);
        VtVec4fArray rotate(3);
        VtVec3fArray translate(3);
        VtIntArray prototypeIndex(3);

        scale[0] = GfVec3f(1);
        rotate[0] = GfVec4f(0);
        translate[0] = GfVec3f(3, 0, 2);
        prototypeIndex[0] = 0;

        scale[1] = GfVec3f(1);
        rotate[1] = GfVec4f(0);
        translate[1] = GfVec3f(0, 0, 2);
        prototypeIndex[1] = 0;

        scale[2] = GfVec3f(1);
        rotate[2] = GfVec4f(0);
        translate[2] = GfVec3f(-3, 0, 2);
        prototypeIndex[2] = 0;

        _delegate->SetInstancerProperties(SdfPath("/instancerTop"),
                                        prototypeIndex,
                                        scale, rotate, translate);
    }

    {
        _delegate->AddInstancer(SdfPath("/instancerBottom"));
        _delegate->AddCube(SdfPath("/protoBottom"),
                         GfMatrix4d(1), false, SdfPath("/instancerBottom"));

        std::vector<SdfPath> prototypes;
        prototypes.push_back(SdfPath("/protoBottom"));

        VtVec3fArray scale(3);
        VtVec4fArray rotate(3);
        VtVec3fArray translate(3);
        VtIntArray prototypeIndex(3);

        scale[0] = GfVec3f(1);
        rotate[0] = GfVec4f(0);
        translate[0] = GfVec3f(3, 0, -2);
        prototypeIndex[0] = 0;

        scale[1] = GfVec3f(1);
        rotate[1] = GfVec4f(0);
        translate[1] = GfVec3f(0, 0, -2);
        prototypeIndex[1] = 0;

        scale[2] = GfVec3f(1);
        rotate[2] = GfVec4f(0);
        translate[2] = GfVec3f(-3, 0, -2);
        prototypeIndex[2] = 0;

        _delegate->SetInstancerProperties(SdfPath("/instancerBottom"),
                                        prototypeIndex,
                                        scale, rotate, translate);
    }

    SetCameraTranslate(GfVec3f(0, 0, -20));

    // XXX: Setup a VAO, the current drawing engine will not yet do this.
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glBindVertexArray(0);
}
Example #11
0
/*virtual*/
GfMatrix4d
HdSceneDelegate::GetInstancerTransform(SdfPath const &instancerId,
                                         SdfPath const &prototypeId)
{
    return GfMatrix4d();
}
Example #12
0
/*virtual*/
GfMatrix4d
HdSceneDelegate::GetTransform(SdfPath const & id)
{
    return GfMatrix4d();
}
Example #13
0
void
My_TestGLDrawing::InitTest()
{
    _renderIndex = HdRenderIndex::New(&_renderDelegate);
    TF_VERIFY(_renderIndex != nullptr);
    _delegate = new Hdx_UnitTestDelegate(_renderIndex);

    _delegate->SetRefineLevel(_refineLevel);

    // prepare render task
    SdfPath renderSetupTask("/renderSetupTask");
    SdfPath renderTask("/renderTask");
    _delegate->AddRenderSetupTask(renderSetupTask);
    _delegate->AddRenderTask(renderTask);

    // render task parameters.
    HdxRenderTaskParams param
        = _delegate->GetTaskParam(
            renderSetupTask, HdTokens->params).Get<HdxRenderTaskParams>();
    param.enableLighting = true; // use default lighting
    _delegate->SetTaskParam(renderSetupTask, HdTokens->params, VtValue(param));
    _delegate->SetTaskParam(renderTask, HdTokens->collection,
                           VtValue(HdRprimCollection(HdTokens->geometry,
                                   _reprName)));

    // prepare scene
    _delegate->AddCube(SdfPath("/cube0"), _GetTranslate( 5, 0, 5));
    _delegate->AddCube(SdfPath("/cube1"), _GetTranslate(-5, 0, 5));
    _delegate->AddCube(SdfPath("/cube2"), _GetTranslate(-5, 0,-5));
    _delegate->AddCube(SdfPath("/cube3"), _GetTranslate( 5, 0,-5));

    {
        _delegate->AddInstancer(SdfPath("/instancerTop"));
        _delegate->AddCube(SdfPath("/protoTop"),
                         GfMatrix4d(1), false, SdfPath("/instancerTop"));

        std::vector<SdfPath> prototypes;
        prototypes.push_back(SdfPath("/protoTop"));

        VtVec3fArray scale(3);
        VtVec4fArray rotate(3);
        VtVec3fArray translate(3);
        VtIntArray prototypeIndex(3);

        scale[0] = GfVec3f(1);
        rotate[0] = GfVec4f(0);
        translate[0] = GfVec3f(3, 0, 2);
        prototypeIndex[0] = 0;

        scale[1] = GfVec3f(1);
        rotate[1] = GfVec4f(0);
        translate[1] = GfVec3f(0, 0, 2);
        prototypeIndex[1] = 0;

        scale[2] = GfVec3f(1);
        rotate[2] = GfVec4f(0);
        translate[2] = GfVec3f(-3, 0, 2);
        prototypeIndex[2] = 0;

        _delegate->SetInstancerProperties(SdfPath("/instancerTop"),
                                        prototypeIndex,
                                        scale, rotate, translate);
    }

    {
        _delegate->AddInstancer(SdfPath("/instancerBottom"));
        _delegate->AddCube(SdfPath("/protoBottom"),
                         GfMatrix4d(1), false, SdfPath("/instancerBottom"));

        std::vector<SdfPath> prototypes;
        prototypes.push_back(SdfPath("/protoBottom"));

        VtVec3fArray scale(3);
        VtVec4fArray rotate(3);
        VtVec3fArray translate(3);
        VtIntArray prototypeIndex(3);

        scale[0] = GfVec3f(1);
        rotate[0] = GfVec4f(0);
        translate[0] = GfVec3f(3, 0, -2);
        prototypeIndex[0] = 0;

        scale[1] = GfVec3f(1);
        rotate[1] = GfVec4f(0);
        translate[1] = GfVec3f(0, 0, -2);
        prototypeIndex[1] = 0;

        scale[2] = GfVec3f(1);
        rotate[2] = GfVec4f(0);
        translate[2] = GfVec3f(-3, 0, -2);
        prototypeIndex[2] = 0;

        _delegate->SetInstancerProperties(SdfPath("/instancerBottom"),
                                        prototypeIndex,
                                        scale, rotate, translate);
    }

    SetCameraTranslate(GfVec3f(0, 0, -20));

    // XXX: Setup a VAO, the current drawing engine will not yet do this.
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glBindVertexArray(0);
}
Example #14
0
File: light.cpp Project: MWDD/USD
/* virtual */
void
HdxLight::Sync(HdSceneDelegate *sceneDelegate,
               HdRenderParam   *renderParam,
               HdDirtyBits     *dirtyBits)
{
    HD_TRACE_FUNCTION();
    HF_MALLOC_TAG_FUNCTION();

    TF_UNUSED(renderParam);

    SdfPath const &id = GetID();

    if (!TF_VERIFY(sceneDelegate != nullptr)) {
        return;
    }

    // HdxLight communicates to the scene graph and caches all interesting
    // values within this class.

    // later on Get() is called from TaskState (RenderPass) to perform
    // aggregation/pre-computation, in order to make the shader execution
    // efficient.

    HdDirtyBits bits = *dirtyBits;

    // Change tracking

    // Transform
    if (bits & DirtyTransform) {
        VtValue transform = sceneDelegate->Get(id, HdxLightTokens->transform);
        if (transform.IsHolding<GfMatrix4d>()) {
            _params[HdxLightTokens->transform] = transform;
        } else {
            _params[HdxLightTokens->transform] = GfMatrix4d(1);
        }
    }

    // Lighting Params
    if (bits & DirtyParams) {
        _params[HdxLightTokens->params] =
                sceneDelegate->Get(id, HdxLightTokens->params);
    }

    // Shadow Params
    if (bits & DirtyShadowParams) {
        _params[HdxLightTokens->shadowParams] =
                sceneDelegate->Get(id, HdxLightTokens->shadowParams);
    }

    // Shadow Collection
    if (bits & DirtyCollection) {
        VtValue vtShadowCollection =
                sceneDelegate->Get(id, HdxLightTokens->shadowCollection);

        // Optional
        if (vtShadowCollection.IsHolding<HdRprimCollection>()) {
            HdRprimCollection newCollection =
                vtShadowCollection.UncheckedGet<HdRprimCollection>();

            if (_params[HdxLightTokens->shadowCollection] != newCollection) {
                _params[HdxLightTokens->shadowCollection] = newCollection;

                HdChangeTracker& changeTracker =
                             sceneDelegate->GetRenderIndex().GetChangeTracker();

                changeTracker.MarkCollectionDirty(newCollection.GetName());
            }

        } else {
            _params[HdxLightTokens->shadowCollection] = HdRprimCollection();
        }
    }

    *dirtyBits = Clean;
}
Example #15
0
UsdImaging_DefaultTaskDelegate::UsdImaging_DefaultTaskDelegate(
    HdRenderIndexSharedPtr const& parentIndex,
    SdfPath const& delegateID)
    : UsdImagingTaskDelegate(parentIndex, delegateID)
    , _viewport(0,0,1,1)
    , _selectionColor(1,1,0,1)
{
    // create an unique namespace
    _rootId = delegateID.AppendChild(
        TfToken(TfStringPrintf("_UsdImaging_%p", this)));

    _renderTaskId               = _rootId.AppendChild(_tokens->renderTask);
    _idRenderTaskId             = _rootId.AppendChild(_tokens->idRenderTask);
    _selectionTaskId            = _rootId.AppendChild(_tokens->selectionTask);
    _simpleLightTaskId          = _rootId.AppendChild(_tokens->simpleLightTask);
    _simpleLightBypassTaskId    = _rootId.AppendChild(_tokens->simpleLightBypassTask);
    _cameraId                   = _rootId.AppendChild(_tokens->camera);
    _activeSimpleLightTaskId    = SdfPath();

    // TODO: tasks of shadow map generation, accumulation etc will be
    // prepared here.
    HdRenderIndex &renderIndex = GetRenderIndex();

    // camera
    {
        renderIndex.InsertCamera<HdCamera>(this, _cameraId);
        _ValueCache &cache = _valueCacheMap[_cameraId];
        cache[HdShaderTokens->worldToViewMatrix] = VtValue(GfMatrix4d(1));
        cache[HdShaderTokens->projectionMatrix]  = VtValue(GfMatrix4d(1));
        cache[HdTokens->cameraFrustum] = VtValue(); // we don't use GfFrustum.
        cache[HdTokens->windowPolicy] = VtValue();  // we don't use window policy.
    }

    // selection task
    {
        renderIndex.InsertTask<HdxSelectionTask>(this, _selectionTaskId);
        _ValueCache &cache = _valueCacheMap[_selectionTaskId];
        HdxSelectionTaskParams params;
        params.enableSelection = true;
        params.selectionColor = _selectionColor;
        params.locateColor = GfVec4f(0,0,1,1);
        cache[HdTokens->params] = VtValue(params);
        cache[HdTokens->children] = VtValue(SdfPathVector());
    }

    // simple lighting task (for Hydra native)
    {
        renderIndex.InsertTask<HdxSimpleLightTask>(this, _simpleLightTaskId);
        _ValueCache &cache = _valueCacheMap[_simpleLightTaskId];
        HdxSimpleLightTaskParams params;
        params.cameraPath = _cameraId;
        cache[HdTokens->params] = VtValue(params);
        cache[HdTokens->children] = VtValue(SdfPathVector());
    }

    // simple lighting task (for Presto UsdBaseIc compatible)
    {
        renderIndex.InsertTask<HdxSimpleLightBypassTask>(this,
                                                         _simpleLightBypassTaskId);
        _ValueCache &cache = _valueCacheMap[_simpleLightBypassTaskId];
        HdxSimpleLightBypassTaskParams params;
        params.cameraPath = _cameraId;
        cache[HdTokens->params] = VtValue(params);
        cache[HdTokens->children] = VtValue(SdfPathVector());
    }

    // render task
    _InsertRenderTask(_renderTaskId);
    _InsertRenderTask(_idRenderTaskId);

    // initialize HdxRenderTaskParams for render tasks
    _UpdateCollection(&_rprims, HdTokens->geometry, HdTokens->smoothHull,
                      SdfPathVector(1, SdfPath::AbsoluteRootPath()),
                      _renderTaskId,
                      _idRenderTaskId);
    _UpdateRenderParams(_renderParams,
                        _renderParams,
                        _renderTaskId);
    _UpdateRenderParams(_idRenderParams,
                        _idRenderParams,
                        _idRenderTaskId);
}
Example #16
0
bool
UsdGeomPointInstancer::ComputeInstanceTransformsAtTime(
    VtArray<GfMatrix4d>* xforms,
    const UsdTimeCode time,
    const UsdTimeCode baseTime,
    const ProtoXformInclusion doProtoXforms,
    const MaskApplication applyMask) const
{
    // XXX: Need to add handling of velocities/angularVelocities and baseTime.
    (void)baseTime;

    if (!xforms) {
        TF_WARN("%s -- null container passed to ComputeInstanceTransformsAtTime()",
                GetPrim().GetPath().GetText());
        return false;
    }

    VtIntArray protoIndices;
    if (!GetProtoIndicesAttr().Get(&protoIndices, time)) {
        TF_WARN("%s -- no prototype indices",
                GetPrim().GetPath().GetText());
        return false;
    }

    if (protoIndices.empty()) {
        xforms->clear();
        return true;
    }

    VtVec3fArray positions;
    if (!GetPositionsAttr().Get(&positions, time)) {
        TF_WARN("%s -- no positions",
                GetPrim().GetPath().GetText());
        return false;
    }

    if (positions.size() != protoIndices.size()) {
        TF_WARN("%s -- positions.size() [%zu] != protoIndices.size() [%zu]",
                GetPrim().GetPath().GetText(),
                positions.size(),
                protoIndices.size());
        return false;
    }

    VtVec3fArray scales;
    GetScalesAttr().Get(&scales, time);
    if (!scales.empty() && scales.size() != protoIndices.size()) {
        TF_WARN("%s -- scales.size() [%zu] != protoIndices.size() [%zu]",
                GetPrim().GetPath().GetText(),
                scales.size(),
                protoIndices.size());
        return false;
    }

    VtQuathArray orientations;
    GetOrientationsAttr().Get(&orientations, time);
    if (!orientations.empty() && orientations.size() != protoIndices.size()) {
        TF_WARN("%s -- orientations.size() [%zu] != protoIndices.size() [%zu]",
                GetPrim().GetPath().GetText(),
                orientations.size(),
                protoIndices.size());
        return false;
    }

    // If we're going to include the prototype transforms, verify that we have
    // prototypes and that all of the protoIndices are in bounds.
    SdfPathVector protoPaths;
    if (doProtoXforms == IncludeProtoXform) {
        const UsdRelationship prototypes = GetPrototypesRel();
        if (!prototypes.GetTargets(&protoPaths) || protoPaths.empty()) {
            TF_WARN("%s -- no prototypes",
                    GetPrim().GetPath().GetText());
            return false;
        }

        TF_FOR_ALL(iter, protoIndices) {
            const int protoIndex = *iter;
            if (protoIndex < 0 || static_cast<size_t>(protoIndex) >= protoPaths.size()) {
                TF_WARN("%s -- invalid prototype index: %d. Should be in [0, %zu)",
                        GetPrim().GetPath().GetText(),
                        protoIndex,
                        protoPaths.size());
                return false;
            }
        }
    }

    // Compute the mask only if applyMask says we should, otherwise we leave
    // mask empty so that its application below is a no-op.
    std::vector<bool> mask;
    if (applyMask == ApplyMask) {
        mask = ComputeMaskAtTime(time);
        if (!mask.empty() && mask.size() != protoIndices.size()) {
            TF_WARN("%s -- mask.size() [%zu] != protoIndices.size() [%zu]",
                    GetPrim().GetPath().GetText(),
                    mask.size(),
                    protoIndices.size());
            return false;
        }
    }

    UsdStageWeakPtr stage = GetPrim().GetStage();
    UsdGeomXformCache xformCache(time);

    xforms->assign(protoIndices.size(), GfMatrix4d(1.0));
    for (size_t instanceId = 0; instanceId < protoIndices.size(); ++instanceId) {
        if (!mask.empty() && !mask[instanceId]) {
            continue;
        }

        GfTransform instanceTransform;

        if (!scales.empty()) {
            instanceTransform.SetScale(scales[instanceId]);
        }

        if (!orientations.empty()) {
            instanceTransform.SetRotation(GfRotation(orientations[instanceId]));
        }

        instanceTransform.SetTranslation(positions[instanceId]);

        GfMatrix4d protoXform(1.0);
        if (doProtoXforms == IncludeProtoXform) {
            const int protoIndex = protoIndices[instanceId];
            const SdfPath& protoPath = protoPaths[protoIndex];
            const UsdPrim& protoPrim = stage->GetPrimAtPath(protoPath);
            if (protoPrim) {
                // Get the prototype's local transformation.
                bool resetsXformStack;
                protoXform = xformCache.GetLocalTransformation(protoPrim,
                                                               &resetsXformStack);
            }
        }

        (*xforms)[instanceId] = protoXform * instanceTransform.GetMatrix();
    }

    return ApplyMaskToArray(mask, xforms);
}
Example #17
0
static void CameraAndLightTest()
{
    HdStRenderDelegate renderDelegate;
    std::unique_ptr<HdRenderIndex> index(HdRenderIndex::New(&renderDelegate));
    TF_VERIFY(index);
    std::unique_ptr<Hdx_UnitTestDelegate> delegate(
                                         new Hdx_UnitTestDelegate(index.get()));

    HdChangeTracker& tracker = index->GetChangeTracker();
    HdPerfLog& perfLog = HdPerfLog::GetInstance();
    perfLog.Enable();
    HdRprimCollection collection(HdTokens->geometry, HdTokens->hull);
    HdRenderPassStateSharedPtr renderPassState(new HdRenderPassState());
    HdRenderPassSharedPtr renderPass(
        new HdSt_RenderPass(index.get(), collection));
    HdEngine engine;

    HdTaskSharedPtr drawTask = boost::make_shared<Hd_TestTask>(renderPass,
                                                               renderPassState);
    HdTaskSharedPtrVector tasks = { drawTask };

    GfMatrix4d tx(1.0f);
    tx.SetRow(3, GfVec4f(5, 0, 5, 1.0));
    SdfPath cube("geometry");
    delegate->AddCube(cube, tx);

    SdfPath camera("camera");
    SdfPath light("light");

    delegate->AddCamera(camera);
    delegate->AddLight(light, GlfSimpleLight());
    delegate->SetLight(light, HdStLightTokens->shadowCollection,
                      VtValue(HdRprimCollection(HdTokens->geometry,
                                                HdTokens->hull)));

    engine.Execute(*index, tasks);

    VERIFY_PERF_COUNT(HdPerfTokens->rebuildBatches, 1);

    // Update camera matrix
    delegate->SetCamera(camera, GfMatrix4d(2), GfMatrix4d(2));
    tracker.MarkSprimDirty(camera, HdStCamera::DirtyViewMatrix);
    tracker.MarkSprimDirty(camera, HdStCamera::DirtyProjMatrix);

    engine.Execute(*index, tasks);

    // batch should not be rebuilt
    VERIFY_PERF_COUNT(HdPerfTokens->rebuildBatches, 1);

    // Update shadow collection
    delegate->SetLight(light, HdStLightTokens->shadowCollection,
                      VtValue(HdRprimCollection(HdTokens->geometry,
                                                HdTokens->refined)));
    tracker.MarkSprimDirty(light, HdStLight::DirtyCollection);

    engine.Execute(*index, tasks);

    // batch rebuilt
    VERIFY_PERF_COUNT(HdPerfTokens->rebuildBatches, 2);

    // Update shadow collection again with the same data
    delegate->SetLight(light, HdStLightTokens->shadowCollection,
                      VtValue(HdRprimCollection(HdTokens->geometry,
                                                HdTokens->refined)));
    tracker.MarkSprimDirty(light, HdStLight::DirtyCollection);

    engine.Execute(*index, tasks);

    // batch should not be rebuilt
    VERIFY_PERF_COUNT(HdPerfTokens->rebuildBatches, 2);
}
Example #18
0
int
main(int argc, char *argv[])
{
    // GfVec2f
    {
        float vals[] = { 1.0f, 2.0f };
        GfVec2f v(vals);
        TF_AXIOM(v == GfVec2f(1,2));
        float const *f = v.GetArray();
        TF_AXIOM(f[0] == 1 and f[1] == 2);
    }

    // GfVec2i
    {
        int vals[] = { 1, 2 };
        GfVec2i v(vals);
        TF_AXIOM(v == GfVec2i(1,2));
        int const *i = v.GetArray();
        TF_AXIOM(i[0] == 1 and i[1] == 2);
        v.Set(0, 1);
        TF_AXIOM(v == GfVec2i(0,1));
    }

    // GfVec3i
    {
        int vals[] = { 1, 2, 3 };
        GfVec3i v(vals);
        TF_AXIOM(v == GfVec3i(1,2,3));
        int const *i = v.GetArray();
        TF_AXIOM(i[0] == 1 and i[1] == 2 and i[2] == 3);
        v.Set(0, 1, 2);
        TF_AXIOM(v == GfVec3i(0,1,2));
    }

    // GfVec4i
    {
        int vals[] = { 1, 2, 3, 4 };
        GfVec4i v(vals);
        TF_AXIOM(v == GfVec4i(1,2,3,4));
        int const *i = v.GetArray();
        TF_AXIOM(i[0] == 1 and i[1] == 2 and i[2] == 3 and i[3] == 4);
        v.Set(0, 1, 2, 3);
        TF_AXIOM(v == GfVec4i(0,1,2,3));
    }

    // GfVec3f
    {
        float vals[] = { 1.0f, 2.0f, 3.0f };
        GfVec3f v(vals);
        TF_AXIOM(v == GfVec3f(1,2,3));
        float const *f = v.GetArray();
        TF_AXIOM(f[0] == 1 and f[1] == 2 and f[2] == 3);
    }

    // GfVec4f
    {
        float vals[] = { 1.0f, 2.0f, 3.0f, 4.0f };
        GfVec4f v(vals);
        TF_AXIOM(v == GfVec4f(1,2,3,4));
        float const *f = v.GetArray();
        TF_AXIOM(f[0] == 1 and f[1] == 2 and f[2] == 3 and f[3] == 4);
    }

    // GfSize2, GfSize3
    {
        size_t vals[] = {1, 2, 3};
        TF_AXIOM(GfSize2(vals) == GfSize2(1,2));
        TF_AXIOM(GfSize3(vals) == GfSize3(1,2,3));
    }

    // GfMatrix2d
    {
        double vals[2][2] = {{1, 0},
                             {0, 1}};
        TF_AXIOM(GfMatrix2d(vals) == GfMatrix2d(1));
        GfMatrix2d m(vals);
        double const *d = m.GetArray();
        TF_AXIOM(d[0] == 1 and d[1] == 0 and
                 d[2] == 0 and d[3] == 1);
    }

    // GfMatrix2f
    {
        float vals[2][2] = {{1, 0},
                             {0, 1}};
        TF_AXIOM(GfMatrix2f(vals) == GfMatrix2f(1));
        GfMatrix2f m(vals);
        float const *f = m.GetArray();
        TF_AXIOM(f[0] == 1 and f[1] == 0 and
                 f[2] == 0 and f[3] == 1);
    }

    // GfMatrix3d
    {
        double vals[3][3] = {{1, 0, 0},
                             {0, 1, 0},
                             {0, 0, 1}};
        TF_AXIOM(GfMatrix3d(vals) == GfMatrix3d(1));
        GfMatrix3d m(vals);
        double const *d = m.GetArray();
        TF_AXIOM(d[0] == 1 and d[1] == 0 and d[2] == 0 and
                 d[3] == 0 and d[4] == 1 and d[5] == 0 and
                 d[6] == 0 and d[7] == 0 and d[8] == 1);
    }

    // GfMatrix4d
    {
        double vals[4][4] = {{1, 0, 0, 0},
                             {0, 1, 0, 0},
                             {0, 0, 1, 0},
                             {0, 0, 0, 1}};
        TF_AXIOM(GfMatrix4d(vals) == GfMatrix4d(1));
        GfMatrix4d m(vals);
        double const *d = m.GetArray();
        TF_AXIOM(d[ 0] == 1 and d[ 1] == 0 and d[ 2] == 0 and d[ 3] == 0 and
                 d[ 4] == 0 and d[ 5] == 1 and d[ 6] == 0 and d[ 7] == 0 and
                 d[ 8] == 0 and d[ 9] == 0 and d[10] == 1 and d[11] == 0 and
                 d[12] == 0 and d[13] == 0 and d[14] == 0 and d[15] == 1);
    }
    
    // half
    {
        float halfPosInf = half::posInf();
        TF_AXIOM(not std::isfinite(halfPosInf));
        TF_AXIOM(std::isinf(halfPosInf));

        float halfNegInf = half::negInf();
        TF_AXIOM(not std::isfinite(halfNegInf));
        TF_AXIOM(std::isinf(halfNegInf));

        float halfqNan = half::qNan();
        TF_AXIOM(std::isnan(halfqNan));

        float halfsNan = half::sNan();
        TF_AXIOM(std::isnan(halfsNan));
    }
    
    return 0;
}
Example #19
0
/* virtual */
void
HdStLight::Sync(HdSceneDelegate *sceneDelegate,
                HdRenderParam   *renderParam,
                HdDirtyBits     *dirtyBits)
{
    HD_TRACE_FUNCTION();
    HF_MALLOC_TAG_FUNCTION();

    TF_UNUSED(renderParam);

    SdfPath const &id = GetId();

    if (!TF_VERIFY(sceneDelegate != nullptr)) {
        return;
    }

    // HdStLight communicates to the scene graph and caches all interesting
    // values within this class. Later on Get() is called from 
    // TaskState (RenderPass) to perform aggregation/pre-computation, 
    // in order to make the shader execution efficient.

    // Change tracking
    HdDirtyBits bits = *dirtyBits;

    // Transform
    if (bits & DirtyTransform) {
        VtValue transform = sceneDelegate->Get(id, HdLightTokens->transform);
        if (transform.IsHolding<GfMatrix4d>()) {
            _params[HdLightTokens->transform] = transform;
        } else {
            _params[HdLightTokens->transform] = GfMatrix4d(1);
        }
    }

    // Lighting Params
    if (bits & DirtyParams) {
        // If it is an area light we will extract the parameters and convert
        // them to a gl friendly representation.
        if (_lightType == HdPrimTypeTokens->simpleLight) {
            _params[HdLightTokens->params] =
                sceneDelegate->Get(id, HdLightTokens->params);
        } else {
            _params[HdLightTokens->params] =
                _ApproximateAreaLight(id, sceneDelegate);
        }
    }

    // Shadow Params
    if (bits & DirtyShadowParams) {
        _params[HdLightTokens->shadowParams] =
                sceneDelegate->Get(id, HdLightTokens->shadowParams);
    }

    // Shadow Collection
    if (bits & DirtyCollection) {
        VtValue vtShadowCollection =
                sceneDelegate->Get(id, HdLightTokens->shadowCollection);

        // Optional
        if (vtShadowCollection.IsHolding<HdRprimCollection>()) {
            HdRprimCollection newCollection =
                vtShadowCollection.UncheckedGet<HdRprimCollection>();

            if (_params[HdLightTokens->shadowCollection] != newCollection) {
                _params[HdLightTokens->shadowCollection] = newCollection;

                HdChangeTracker& changeTracker =
                             sceneDelegate->GetRenderIndex().GetChangeTracker();

                changeTracker.MarkCollectionDirty(newCollection.GetName());
            }

        } else {
            _params[HdLightTokens->shadowCollection] = HdRprimCollection();
        }
    }

    *dirtyBits = Clean;
}
Example #20
0
File: camera.cpp Project: JT-a/USD
// Horizontal and vertical aperture is in mm whereas most stuff is in cm.
const double
GfCamera::APERTURE_UNIT = 0.1;

// Focal length is in mm whereas most stuff is in cm.
const double
GfCamera::FOCAL_LENGTH_UNIT = 0.1;

const bool GfCamera::ZUp = true;
const bool GfCamera::YUp = false;

// Matrix corresponding to Gf.Rotation(Gf.Vec3d.XAxis(), -90)
const GfMatrix4d
GfCamera::Y_UP_TO_Z_UP_MATRIX =
    GfMatrix4d( 1,  0 , 0,  0,
                0,  0, -1,  0,
                0,  1,  0,  0,
                0,  0,  0,  1);

// Matrix corresponding to Gf.Rotation(Gf.Vec3d.XAxis(), 90)
const GfMatrix4d
GfCamera::Z_UP_TO_Y_UP_MATRIX =
    GfMatrix4d( 1,  0 , 0,  0,
                0,  0,  1,  0,
                0, -1,  0,  0,
                0,  0,  0,  1);

// The default filmback size is based on a 35mm spherical
// projector aperture (0.825 x 0.602 inches, converted to
// mm). Note this is slightly different than SMPTE195-2000,
// which specifies 20.96mm (not 20.955mm) and 0.825"  Also
// note that 35mm spherical and anamorphic projector aperture
Example #21
0
File: xformOp.cpp Project: JT-a/USD
/* static */
GfMatrix4d 
UsdGeomXformOp::GetOpTransform(UsdGeomXformOp::Type const opType,
                               VtValue const &opVal,
                               bool isInverseOp)
{
    // This will be the most common case.
    if (opType == TypeTransform) {
        GfMatrix4d mat(1.);
        bool isMatrixVal = true;
        if (opVal.IsHolding<GfMatrix4d>()) {
            mat = opVal.UncheckedGet<GfMatrix4d>();
        } else if (opVal.IsHolding<GfMatrix4f>()) {
            mat = GfMatrix4d(opVal.UncheckedGet<GfMatrix4f>());
        } else {
            isMatrixVal = false;
            TF_CODING_ERROR("Invalid combination of opType (%s) "
                "and opVal (%s). Returning identity matrix.",
                TfEnum::GetName(opType).c_str(),
                TfStringify(opVal).c_str());
            return GfMatrix4d(1.);
        } 

        if (isMatrixVal && isInverseOp) {
            double determinant=0;
            mat = mat.GetInverse(&determinant);

            if (GfIsClose(determinant, 0.0, 1e-9)) {
                TF_CODING_ERROR("Cannot invert singular transform op with "
                    "value %s.", TfStringify(opVal).c_str());
            }
        }

        return mat;
    }

    double doubleVal = 0.;
    bool isScalarVal = true;
    if (opVal.IsHolding<double>()) {
        doubleVal  = opVal.UncheckedGet<double>();
    } else if (opVal.IsHolding<float>()) {
        doubleVal = opVal.UncheckedGet<float>();
    } else if (opVal.IsHolding<GfHalf>()) {
        doubleVal = opVal.UncheckedGet<GfHalf>();
    } else {
        isScalarVal = false;
    }

    if (isScalarVal) {
        if (isInverseOp) 
            doubleVal = -doubleVal;

        if (opType == TypeRotateX) {
            return GfMatrix4d(1.).SetRotate(GfRotation(GfVec3d::XAxis(), doubleVal));
        } else if (opType == TypeRotateY) {
            return GfMatrix4d(1.).SetRotate(GfRotation(GfVec3d::YAxis(), doubleVal));
        } else if (opType == TypeRotateZ) {
            return GfMatrix4d(1.).SetRotate(GfRotation(GfVec3d::ZAxis(), doubleVal));
        }
    }

    GfVec3d vec3dVal = GfVec3d(0.);
    bool isVecVal = true;
    if (opVal.IsHolding<GfVec3f>()) {
        vec3dVal = opVal.UncheckedGet<GfVec3f>();
    } else if (opVal.IsHolding<GfVec3d>()) {
        vec3dVal = opVal.UncheckedGet<GfVec3d>();
    } else if (opVal.IsHolding<GfVec3h>()) {
        vec3dVal = opVal.UncheckedGet<GfVec3h>();
    } else {
        isVecVal = false;
    }

    if (isVecVal) {
        switch(opType) {
            case TypeTranslate:
                if (isInverseOp) 
                    vec3dVal = -vec3dVal;
                return GfMatrix4d(1.).SetTranslate(vec3dVal);
            case TypeScale:
                if (isInverseOp) {
                    vec3dVal = GfVec3d(1/vec3dVal[0], 
                                       1/vec3dVal[1], 
                                       1/vec3dVal[2]);
                }
                return GfMatrix4d(1.).SetScale(vec3dVal);
            default: {
                if (isInverseOp) 
                    vec3dVal = -vec3dVal;
                // Must be one of the 3-axis rotates.
                GfMatrix3d xRot(GfRotation(GfVec3d::XAxis(), vec3dVal[0]));
                GfMatrix3d yRot(GfRotation(GfVec3d::YAxis(), vec3dVal[1]));
                GfMatrix3d zRot(GfRotation(GfVec3d::ZAxis(), vec3dVal[2]));
                GfMatrix3d rotationMat(1.);
                switch (opType) {
                    case TypeRotateXYZ: 
                        // Inv(ABC) = Inv(C) * Inv(B) * Inv(A)
                        rotationMat = !isInverseOp ? (xRot * yRot * zRot) 
                                                      : (zRot * yRot * xRot);
                        break;
                    case TypeRotateXZY: 
                        rotationMat = !isInverseOp ? (xRot * zRot * yRot)
                                                      : (yRot * zRot * xRot);
                        break;
                    case TypeRotateYXZ: 
                        rotationMat = !isInverseOp ? (yRot * xRot * zRot)
                                                      : (zRot * xRot * yRot);
                        break;
                    case TypeRotateYZX: 
                        rotationMat = !isInverseOp ? (yRot * zRot * xRot)
                                                      : (xRot * zRot * yRot);
                        break;
                    case TypeRotateZXY:
                        rotationMat = !isInverseOp ? (zRot * xRot * yRot)
                                                      : (yRot * xRot * zRot);
                        break;
                    case TypeRotateZYX: 
                        rotationMat = !isInverseOp ? (zRot * yRot * xRot)
                                                      : (xRot * yRot * zRot);
                        break;
                    default:
                        TF_CODING_ERROR("Invalid combination of opType (%s) "
                            "and opVal (%s). Returning identity matrix.",
                            TfEnum::GetName(opType).c_str(),
                            TfStringify(opVal).c_str());
                        return GfMatrix4d(1.);
                }
                return GfMatrix4d(1.).SetRotate(rotationMat);
            }
        }
    }

    if (opType == TypeOrient) {
        GfQuatd quatVal(0);
        if (opVal.IsHolding<GfQuatd>())
            quatVal = opVal.UncheckedGet<GfQuatd>();
        else if (opVal.IsHolding<GfQuatf>()) {
            const GfQuatf &quatf = opVal.UncheckedGet<GfQuatf>();
            quatVal = GfQuatd(quatf.GetReal(), quatf.GetImaginary());
        } else if (opVal.IsHolding<GfQuath>()) {
            const GfQuath &quath = opVal.UncheckedGet<GfQuath>();
            quatVal = GfQuatd(quath.GetReal(), quath.GetImaginary());
        }

        GfRotation quatRotation(quatVal);
        if (isInverseOp)
            quatRotation = quatRotation.GetInverse();

        return GfMatrix4d(quatRotation, GfVec3d(0.));
    }
    
    TF_CODING_ERROR("Invalid combination of opType (%s) and opVal (%s). "
        "Returning identity matrix.", TfEnum::GetName(opType).c_str(), 
        TfStringify(opVal).c_str());

    return GfMatrix4d(1.);
}
Example #22
0
bool
PxrUsdMayaWriteUtil::SetUsdAttr(
    const MPlug &plg,
    const UsdAttribute& usdAttr,
    const UsdTimeCode &usdTime)
{
    MStatus status;
    if (!usdAttr || plg.isNull() ) {
        return false;
    }

    bool isAnimated = plg.isDestination();
    if (usdTime.IsDefault() == isAnimated ) {
        return true;
    }

    // Set UsdAttr
    MObject attrObj = plg.attribute();
    if (attrObj.hasFn(MFn::kNumericAttribute)) {
        MFnNumericAttribute attrNumericFn(attrObj);
        switch (attrNumericFn.unitType())
        {
        case MFnNumericData::kBoolean:
            usdAttr.Set(plg.asBool(), usdTime);
            break;
        case MFnNumericData::kByte:
        case MFnNumericData::kChar:
            usdAttr.Set((int)plg.asChar(), usdTime);
            break;
        case MFnNumericData::kShort:
            usdAttr.Set(int(plg.asShort()), usdTime);
            break;
        case MFnNumericData::kInt:
            usdAttr.Set(int(plg.asInt()), usdTime);
            break;
        //case MFnNumericData::kLong:
        //case MFnNumericData::kAddr:
        //    usdAttr.Set(plg.asInt(), usdTime);
        //    break;
        case MFnNumericData::kFloat:
            usdAttr.Set(plg.asFloat(), usdTime);
            break;
        case MFnNumericData::kDouble:
            usdAttr.Set(plg.asDouble(), usdTime);
            break;
        case MFnNumericData::k2Short:
        {
            short tmp1, tmp2;
            MFnNumericData attrNumericDataFn(plg.asMObject());
            attrNumericDataFn.getData(tmp1, tmp2);
            usdAttr.Set(GfVec2i(tmp1, tmp2), usdTime);
            break;
        }
        case MFnNumericData::k2Int:
        {
            int tmp1, tmp2;
            MFnNumericData attrNumericDataFn(plg.asMObject());
            attrNumericDataFn.getData(tmp1, tmp2);
            usdAttr.Set(GfVec2i(tmp1, tmp2), usdTime);
            break;
        }
        //case MFnNumericData::k2Long:
        case MFnNumericData::k3Short:
        {
            short tmp1, tmp2, tmp3;
            MFnNumericData attrNumericDataFn(plg.asMObject());
            attrNumericDataFn.getData(tmp1, tmp2, tmp3);
            usdAttr.Set(GfVec3i(tmp1, tmp2, tmp3), usdTime);
            break;
        }
        case MFnNumericData::k3Int:
        {
            int tmp1, tmp2, tmp3;
            MFnNumericData attrNumericDataFn(plg.asMObject());
            attrNumericDataFn.getData(tmp1, tmp2, tmp3);
            usdAttr.Set(GfVec3i(tmp1, tmp2, tmp3), usdTime);
            break;
        }
        //case MFnNumericData::k3Long:
        case MFnNumericData::k2Float:
        {
            float tmp1, tmp2;
            MFnNumericData attrNumericDataFn(plg.asMObject());
            attrNumericDataFn.getData(tmp1, tmp2);
            usdAttr.Set(GfVec2f(tmp1, tmp2), usdTime);
            break;
        }
        case MFnNumericData::k3Float:
        {
            float tmp1, tmp2, tmp3;
            MFnNumericData attrNumericDataFn(plg.asMObject());
            attrNumericDataFn.getData(tmp1, tmp2, tmp3);
            _SetVec(usdAttr, GfVec3f(tmp1, tmp2, tmp3), usdTime);
            break;
        }
        case MFnNumericData::k2Double:
        {
            double tmp1, tmp2;
            MFnNumericData attrNumericDataFn(plg.asMObject());
            attrNumericDataFn.getData(tmp1, tmp2);
            usdAttr.Set(GfVec2d(tmp1, tmp2), usdTime);
            break;
        }
        case MFnNumericData::k3Double:
        {
            double tmp1, tmp2, tmp3;
            MFnNumericData attrNumericDataFn(plg.asMObject());
            attrNumericDataFn.getData(tmp1, tmp2, tmp3);
            _SetVec(usdAttr, GfVec3d(tmp1, tmp2, tmp3), usdTime);
            break;
        }
        case MFnNumericData::k4Double:
        {
            double tmp1, tmp2, tmp3, tmp4;
            MFnNumericData attrNumericDataFn(plg.asMObject());
            attrNumericDataFn.getData(tmp1, tmp2, tmp3, tmp4);
            _SetVec(usdAttr, GfVec4d(tmp1, tmp2, tmp3, tmp4), usdTime);
            break;
        }
        default:
            return false;
        }
    }
    else if (attrObj.hasFn(MFn::kTypedAttribute)) {
        MFnTypedAttribute attrTypedFn(attrObj);
        switch (attrTypedFn.attrType())
        {
        case MFnData::kString:
            usdAttr.Set(std::string(plg.asString().asChar()), usdTime);
            break;
        case MFnData::kMatrix:
        {
            MFnMatrixData attrMatrixDataFn(plg.asMObject());
            MMatrix mat1 = attrMatrixDataFn.matrix();
            usdAttr.Set(GfMatrix4d(mat1.matrix), usdTime);
            break;
        }
        case MFnData::kStringArray:
        {
            MFnStringArrayData attrDataFn(plg.asMObject());
            VtArray<std::string> usdVal(attrDataFn.length());
            for (unsigned int i=0; i < attrDataFn.length(); i++) {
                usdVal[i] = std::string(attrDataFn[i].asChar());
            }
            usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnData::kIntArray:
        {
            MFnIntArrayData attrDataFn(plg.asMObject());
            VtArray<int> usdVal(attrDataFn.length());
            for (unsigned int i=0; i < attrDataFn.length(); i++) {
                usdVal[i] = attrDataFn[i];
            }
            usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnData::kFloatArray:
        {
            MFnFloatArrayData attrDataFn(plg.asMObject());
            VtArray<float> usdVal(attrDataFn.length());
            for (unsigned int i=0; i < attrDataFn.length(); i++) {
                usdVal[i] = attrDataFn[i];
            }
            usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnData::kDoubleArray:
        {
            MFnDoubleArrayData attrDataFn(plg.asMObject());
            VtArray<double> usdVal(attrDataFn.length());
            for (unsigned int i=0; i < attrDataFn.length(); i++) {
                usdVal[i] = attrDataFn[i];
            }
            usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnData::kVectorArray:
        {
            MFnVectorArrayData attrDataFn(plg.asMObject());
            VtArray<GfVec3d> usdVal(attrDataFn.length());
            for (unsigned int i=0; i < attrDataFn.length(); i++) {
                MVector tmpMayaVal = attrDataFn[i];
                usdVal[i] = GfVec3d(tmpMayaVal[0], tmpMayaVal[1], tmpMayaVal[2]);
            }
            usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnData::kPointArray:
        {
            MFnPointArrayData attrDataFn(plg.asMObject());
            VtArray<GfVec4d> usdVal(attrDataFn.length());
            for (unsigned int i=0; i < attrDataFn.length(); i++) {
                MPoint tmpMayaVal = attrDataFn[i];
                usdVal[i] = GfVec4d(tmpMayaVal[0], tmpMayaVal[1], tmpMayaVal[2], tmpMayaVal[3]);
            }
            usdAttr.Set(usdVal, usdTime);
            break;
        }
        default:
            return false;
        }
    }
    else if (attrObj.hasFn(MFn::kUnitAttribute)) {
        //MFnUnitAttribute attrUnitFn(attrObj);
        return false;
    }
    else if (attrObj.hasFn(MFn::kEnumAttribute)) {
        MFnEnumAttribute attrEnumFn(attrObj);
        short enumIndex = plg.asShort();
        TfToken enumToken( std::string(attrEnumFn.fieldName(enumIndex, &status).asChar()) );
        usdAttr.Set(enumToken, usdTime);
        return false;
    }

    return true;
}