예제 #1
0
// #### updateRegistry
//
//      Evaluates dirty flags and updates the effect registry if any
//      attributes have changed that require the shader to be rebuilt
//
void
OpenSubdivShader::updateRegistry()
{
    /* If adaptive flag has changed, update the effectRegistry accordingly */
    if (_adaptiveDirty) {
        g_effectRegistry.setIsAdaptive(_adaptive);
        _adaptiveDirty = false;
    }

    MHWRender::MRenderer *theRenderer = MHWRender::MRenderer::theRenderer();
    _theTextureManager = theRenderer->getTextureManager();

    /* If diffuse texture has changed, update the effectRegistry accordingly */
    if (_diffuseMapDirty) {
        GLuint diffMapId = bindTexture( _diffuseMapFile, DIFF_TEXTURE_UNIT );
        g_effectRegistry.setDiffuseId(diffMapId);
        _diffuseMapDirty = false;
    }

    /* If shader source has changed, update the effectRegistry accordingly */
    if (_shaderSourceDirty) {
        if ( _shaderSource.empty() ) {
            if ( g_effectRegistry.getShaderSource() != defaultShaderSource ) {
                g_effectRegistry.setShaderSource(defaultShaderSource);
            }
        } else {
            if ( g_effectRegistry.getShaderSource() != _shaderSource ) {
                g_effectRegistry.setShaderSource(_shaderSource);
            }
        }
        _shaderSourceDirty = false;
    }
}
//
// Update override for the current frame.
//
// Make sure we have a proper set of operations. If so then update
// shaders and light pruning information.
//
MStatus viewRenderOverrideShadows::setup(const MString& destination)
{
	// Firewall checks
	MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
	if (!renderer) return MStatus::kFailure;

	const MHWRender::MShaderManager* shaderMgr = renderer->getShaderManager();
	if (!shaderMgr) return MStatus::kFailure;

	// Update render operations
	//
	MStatus status = updateRenderOperations();
	if (status != MStatus::kSuccess)
		return status;

	// Update shaders
	status = updateShaders( shaderMgr );
	if (status != MStatus::kSuccess)
		return status;

	// Update light list
	status = updateLightList();

	return status;
}
예제 #3
0
MStatus initializePlugin(MObject obj)
{
	MStatus status = MStatus::kSuccess;
	MFnPlugin plugin(obj, PLUGIN_COMPANY, "1.0", "Any");
	status = MGlobal::startErrorLogging("c:/Temp/myLog.txt");
	if (!initialised)
	{
		Core::initClassFactorySingleton(new Maya::MayaClassFactory());
		Core::startup();
		dag = new Maya::DAG();
		dag->createGraph();
		MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(false);
		if (renderer)
		{
			rendererOverride = new Maya::RenderOverride();
			status = renderer->registerOverride(rendererOverride);
		}
		else
		{
			status = MStatus::kFailure;
		}
		initialised = true;
	}
	return status;
}
예제 #4
0
MStatus uninitializePlugin(MObject obj)
{
	if (dag != NULL)
	{
		delete dag;
		dag = NULL;
	}
	Core::shutdown();
	MStatus   status;
	MFnPlugin plugin(obj);

	// Degister and delete override
	//
	if (rendererOverride)
	{
		MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
		if (renderer)
		{
			status = renderer->deregisterOverride(rendererOverride);
		}
		delete rendererOverride;
		rendererOverride = NULL;
	}
	initialised = false;
	return MStatus::kSuccess;
}
예제 #5
0
/*!
	Register an override and associated command
*/
MStatus initializePlugin( MObject obj )
{
	MStatus   status;
	MFnPlugin plugin( obj, PLUGIN_COMPANY, "1.0", "Any");

	// Create and register an override.
	if (!viewRenderOverrideInstance)
	{
		// my_viewRenderOverride is the unique identifier string
		// for this override
		MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(false);
		if (renderer)
		{
			viewRenderOverrideInstance = new viewRenderOverride( "my_viewRenderOverride" );
			status = renderer->registerOverride(viewRenderOverrideInstance);
		}
	}

	if (!status)
	{
		status.perror("registerOverride");
	}

	return status;
}
LightMaterialOverride::LightMaterialOverride(const MObject& obj)
: MPxSurfaceShadingNodeOverride(obj)
{
	MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer();
	if (theRenderer)
	{
		MHWRender::MFragmentManager* fragmentMgr = theRenderer->getFragmentManager();
		if (fragmentMgr)
		{
			for (uint i = 0; i < MayaTo::getWorldPtr()->shaderSearchPath.length(); i++)
				fragmentMgr->addFragmentPath(MayaTo::getWorldPtr()->shaderSearchPath[i]);

			MString fragment = "CoronaLight";
			bool fragAdded = fragmentMgr->hasFragment(fragment);
			if (!fragAdded)
			{
				fragAdded = (fragment == fragmentMgr->addShadeFragmentFromFile(fragment + ".xml", false));
				if (fragAdded)
				{
					MGlobal::displayInfo(MString("Successfully loaded fragment ") + fragment + ".xml");
				}
				else{
					MGlobal::displayInfo(MString("Could not load fragment ") + fragment + ".xml");
				}
			}
		}
	}
}
예제 #7
0
void dx11ShaderOverride::terminateKey(MHWRender::MDrawContext& context, const MString& /*key*/)
{
    if (fShaderNode) {
        MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer();
        if (theRenderer)
        {
            dx11ShaderDX11Device* dxDevice = (dx11ShaderDX11Device*)theRenderer->GPUDeviceHandle();
            if (dxDevice)
            {
                ID3D11DeviceContext* dxContext = NULL;
                dxDevice->GetImmediateContext(&dxContext);
                if (dxContext)
                {
                    fShaderNode->restoreStates(dxContext, fStates);

                    dxContext->VSSetShader(NULL, NULL, 0);
                    dxContext->PSSetShader(NULL, NULL, 0);
                    dxContext->GSSetShader(NULL, NULL, 0);
                    dxContext->HSSetShader(NULL, NULL, 0);
                    dxContext->DSSetShader(NULL, NULL, 0);

                    dxContext->Release();
                }
            }
        }
    }
}
예제 #8
0
/*
	When uninitializing the plugin, make sure to deregister the
	override and then delete the instance which is being kept here.

	Also remove the command used to set options on the override
*/
MStatus uninitializePlugin( MObject obj)
{
	MStatus   status;
	MFnPlugin plugin( obj );

	// Degister and delete override
	//
	if (viewRenderOverrideInstance)
	{
		MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
		if (renderer)
		{
			status = renderer->deregisterOverride(viewRenderOverrideInstance);
		}

		delete viewRenderOverrideInstance;
		viewRenderOverrideInstance = NULL;
	}

	if (!status)
	{
		status.perror("deregisterOverride");
	}

	return status;
}
예제 #9
0
void ovalLocatorDrawOverride::draw (const MHWRender::MDrawContext &context, const MUserData *data) {
	MPointArray vertices =ovalLocator::vertices () ;
	// get cached data
	float color [3] ={ 0.0f, 1.0f, 0.0f } ;
	float multiplier =1.0f ;
	const ovalLocatorData *ovalData =dynamic_cast<const ovalLocatorData *>(data) ;
	if ( ovalData )
		multiplier =ovalData->multiplier ;	
	// get state data
	MStatus status ;
	const MMatrix transform =context.getMatrix (MHWRender::MDrawContext::kWorldViewMtx, &status) ;
	if ( status !=MStatus::kSuccess )
		return ;
	const MMatrix projection =context.getMatrix (MHWRender::MDrawContext::kProjectionMtx, &status) ;
	if ( status !=MStatus::kSuccess )
		return ;
	const int displayStyle =context.getDisplayStyle () ;
	// get renderer
	MHWRender::MRenderer *theRenderer =MHWRender::MRenderer::theRenderer () ;
	if ( !theRenderer )
		return ;

	// GL Draw
	if ( theRenderer->drawAPIIsOpenGL () ) {
		// set colour
		glColor3fv (color) ;
		// set world matrix
		glMatrixMode (GL_MODELVIEW) ;
		glPushMatrix () ;
		glLoadMatrixd (transform.matrix [0]) ;
		// set projection matrix
		glMatrixMode (GL_PROJECTION) ;
		glPushMatrix () ;
		glLoadMatrixd (projection.matrix [0]) ;
		if ( displayStyle & MHWRender::MDrawContext::kGouraudShaded ) {
			// See myShadedDraw
			glPushAttrib (GL_CURRENT_BIT) ;
			glBegin (GL_TRIANGLE_FAN) ;
			glVertex3f (0, 0, 0) ;
			for ( int i =0 ; i < vertices.length () ; ++i )
				glVertex3f (vertices [i].x * multiplier, vertices [i].y * multiplier, vertices [i].z * multiplier) ;
			glEnd () ;
			glPopAttrib () ;
		}
		if ( displayStyle & MHWRender::MDrawContext::kWireFrame ) {
			// See myWireFrameDraw
			glBegin (GL_LINES) ;
			for ( int i =0 ; i < vertices.length () - 1 ; ++i ) {
				glVertex3f (vertices [i].x * multiplier, vertices [i].y * multiplier, vertices [i].z * multiplier) ;
				glVertex3f (vertices [i + 1].x * multiplier, vertices [i + 1].y * multiplier, vertices [i + 1].z * multiplier) ;
			}
			glEnd () ;
		}
		glPopMatrix () ;
		glMatrixMode (GL_MODELVIEW) ;
		glPopMatrix () ;
	}
}
예제 #10
0
CheckerNodeOverride::CheckerNodeOverride(const MObject& obj)
: MPxShadingNodeOverride(obj)
, fFragmentName("")
{
	// Fragments are defined in separate XML files, add the checker node
	// directory to the search path and load from the files.
	static const MString sFragmentName("checkerNodePluginFragment");
	static const MString sFragmentOutputName("checkerNodePluginFragmentOutput");
	static const MString sFragmentGraphName("checkerNodePluginGraph");
	MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer();
	if (theRenderer)
	{
		MHWRender::MFragmentManager* fragmentMgr =
			theRenderer->getFragmentManager();
		if (fragmentMgr)
		{
			// Add search path (once only)
			static bool sAdded = false;
			if (!sAdded)
			{
				MString location;
				if( ! MGlobal::executeCommand(MString("getModulePath -moduleName \"devkit\""), location, false) ) {
					location = MString(getenv("MAYA_LOCATION")) + MString("/devkit");
				} 
				location += "/plug-ins/checkerShader";
				fragmentMgr->addFragmentPath(location);
				sAdded = true;
			}

			// Add fragments if needed
			bool fragAdded = fragmentMgr->hasFragment(sFragmentName);
			bool structAdded = fragmentMgr->hasFragment(sFragmentOutputName);
			bool graphAdded = fragmentMgr->hasFragment(sFragmentGraphName);
			if (!fragAdded)
			{
				fragAdded = (sFragmentName == fragmentMgr->addShadeFragmentFromFile(sFragmentName + ".xml", false));
			}
			if (!structAdded)
			{
				structAdded = (sFragmentOutputName == fragmentMgr->addShadeFragmentFromFile(sFragmentOutputName + ".xml", false));
			}
			if (!graphAdded)
			{
				graphAdded = (sFragmentGraphName == fragmentMgr->addFragmentGraphFromFile(sFragmentGraphName + ".xml"));
			}

			// If we have them all, use the final graph for the override
			if (fragAdded && structAdded && graphAdded)
			{
				fFragmentName = sFragmentGraphName;
			}
		}
	}
}
void arrowLocatorOverride::draw(
	const MHWRender::MDrawContext& context,
	const MUserData* data)
{
	MAngle rotationAngle;

	float color [3] ={ 0.0f, 1.0f, 0.0f } ;

	// data
	MStatus status;
	MHWRender::MStateManager* stateMgr = context.getStateManager();
	const arrowLocatorData* locatorData =
		dynamic_cast<const arrowLocatorData*>(data);
	if (!stateMgr || !locatorData) return;

	if ( locatorData )
		rotationAngle = locatorData->rotateAngle;

	// matrices
	const MMatrix transform =
		context.getMatrix(MHWRender::MFrameContext::kWorldViewMtx, &status);
	if (status != MStatus::kSuccess) return;
	const MMatrix projection =
		context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status);
	if (status != MStatus::kSuccess) return;

	// get renderer
	MHWRender::MRenderer *theRenderer =MHWRender::MRenderer::theRenderer () ;
	if ( !theRenderer )
		return ;
	if ( theRenderer->drawAPIIsOpenGL () ) {
		
		glPushAttrib(GL_CURRENT_BIT);
		glColor4fv(color);

		glPushMatrix();
		glRotated(-rotationAngle.asDegrees(), 0.0, 1.0, 0.0);
		glBegin( GL_LINE_STRIP);
		glVertex3f(arrow[0][0],arrow[0][1],arrow[0][2]);
		glVertex3f(arrow[1][0],arrow[1][1],arrow[1][2]);
		glVertex3f(arrow[2][0],arrow[2][1],arrow[2][2]);
		glEnd();

		glBegin( GL_LINE_STRIP );
		glVertex3f(arrow[2][0],arrow[2][1],arrow[2][2]);
		glVertex3f(arrow[3][0],arrow[3][1],arrow[3][2]);
		glVertex3f(arrow[0][0],arrow[0][1],arrow[0][2]);
		glEnd();
		glPopMatrix();

	}
}
예제 #12
0
// Override setup and cleanup for this override
//
MStatus ViewRenderOverride::setup(const MString & destination)
{
	MHWRender::MRenderer *theRenderer = MHWRender::MRenderer::theRenderer();
	unsigned int width, height;
	theRenderer->outputTargetSize(width, height);
	MString panelName;
	panelName.set(destination.asChar());
	for (int i = 0; i < renderOperations.size(); i++)
	{
		PluginTestOperationBase* base = dynamic_cast<PluginTestOperationBase*>(renderOperations[i]);
		base->panelName = panelName;
	}
	return MStatus::kSuccess;
}
MStatus initializePlugin(MObject obj)
{
	MStatus status;
	MFnPlugin plugin(obj, PLUGIN_COMPANY, "1.0", "Any");

	// ************************ MAYA-25818 PART 1 of 2 *************************
	// Workaround for avoiding dirtying the scene until there's a way to
	// register overrides without causing dirty.
	bool sceneDirty = true; // assume true since that's the safest
	try
	{
		// is the scene currently dirty?
		MCommandResult sceneDirtyResult(&status);
		if (status != MStatus::kSuccess) throw std::exception();
		status = MGlobal::executeCommand("file -query -modified", sceneDirtyResult);
		if (status != MStatus::kSuccess) throw std::exception();
		int commandResult;
		status = sceneDirtyResult.getResult(commandResult);
		if (status != MStatus::kSuccess) throw std::exception();
		sceneDirty = commandResult != 0;
	}
	catch (std::exception&)
	{
		// if we got here, assume the scene is dirty
		sceneDirty = true;
	}
	// ************************ MAYA-25818 PART 1 of 2 *********************

	MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
	if (renderer)
	{
		if (!viewImageBlitOverride::RenderOverride::sViewImageBlitOverrideInstance)
		{
			viewImageBlitOverride::RenderOverride::sViewImageBlitOverrideInstance = new viewImageBlitOverride::RenderOverride("my_viewImageBlitOverride");
			renderer->registerOverride(viewImageBlitOverride::RenderOverride::sViewImageBlitOverrideInstance);
		}
	}

	// ************************ MAYA-25818 PART 2 of 2 *************************
	// If the scene was previously unmodified, return it to that state since
	// we haven't done anything that needs to be saved.
	if (sceneDirty == false)
	{
		MGlobal::executeCommand("file -modified 0");
	}
	// ************************ END MAYA-25818 PART 2 of 2 *********************

	return status;
}
예제 #14
0
// Background color override. We get the current colors from the 
// renderer and use them
//
MHWRender::MClearOperation &
simpleViewRenderSceneRender::clearOperation()
{
	MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
	bool gradient = renderer->useGradient();
	MColor color1 = renderer->clearColor();
	MColor color2 = renderer->clearColor2();

	float c1[4] = { color1[0], color1[1], color1[2], 1.0f };
	float c2[4] = { color2[0], color2[1], color2[2], 1.0f };

	mClearOperation.setClearColor( c1 );
	mClearOperation.setClearColor2( c2 );
	mClearOperation.setClearGradient( gradient);
    return mClearOperation;
}
MStatus initializePlugin(MObject obj)
{
	MStatus status;
	MFnPlugin plugin(obj, PLUGIN_COMPANY, "1.0", "Any");

	MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
	if (renderer)
	{
		if (!viewRenderOverrideShadowsInstance)
		{
			viewRenderOverrideShadowsInstance = new viewRenderOverrideShadows("my_viewRenderOverrideShadows");
			renderer->registerOverride(viewRenderOverrideShadowsInstance);
		}
	}

	return status;
}
MStatus uninitializePlugin(MObject obj)
{
	MStatus status;
	MFnPlugin plugin(obj);

	MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
	if (renderer)
	{
		if (viewImageBlitOverride::RenderOverride::sViewImageBlitOverrideInstance)
		{
			renderer->deregisterOverride(viewImageBlitOverride::RenderOverride::sViewImageBlitOverrideInstance);
			delete viewImageBlitOverride::RenderOverride::sViewImageBlitOverrideInstance;
		}
		viewImageBlitOverride::RenderOverride::sViewImageBlitOverrideInstance = NULL;
	}

	return status;
}
예제 #17
0
파일: batchRenderer.cpp 프로젝트: JT-a/USD
void
UsdMayaGLBatchRenderer::Draw(
    const MHWRender::MDrawContext& context,
    const MUserData *userData)
{
    // VP 2.0 Implementation
    //
    MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer();
    if( !theRenderer || !theRenderer->drawAPIIsOpenGL() )
        return;

    const _BatchDrawUserData* batchData = static_cast<const _BatchDrawUserData*>(userData);
    if( !batchData )
        return;
    
    MStatus status;

    MMatrix projectionMat = context.getMatrix(MHWRender::MDrawContext::kProjectionMtx, &status);
    
    if( batchData->_bounds )
    {
        MMatrix worldViewMat = context.getMatrix(MHWRender::MDrawContext::kWorldViewMtx, &status);

        px_vp20Utils::RenderBoundingBox(*(batchData->_bounds),
                                        *(batchData->_wireframeColor),
                                        worldViewMat,
                                        projectionMat);
    }
    
    if( batchData->_drawShape && !_renderQueue.empty() )
    {
        MMatrix viewMat = context.getMatrix(MHWRender::MDrawContext::kViewMtx, &status);

        // Extract camera settings from maya view
        int viewX, viewY, viewWidth, viewHeight;
        context.getViewportDimensions(viewX, viewY, viewWidth, viewHeight);
        GfVec4d viewport(viewX, viewY, viewWidth, viewHeight);

        // Only the first call to this will do anything... After that the batch
        // queue is cleared.
        //
        _RenderBatches( &context, viewMat, projectionMat, viewport );
    }
}
simpleNoiseShaderOverride::~simpleNoiseShaderOverride()
{
	// Release texture
	MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
	if (renderer)
	{
		MHWRender::MTextureManager* textureMgr =
			renderer->getTextureManager();
		if (textureMgr)
		{
			textureMgr->releaseTexture(fNoiseTexture);
			fNoiseTexture = NULL;
		}
	}

	// Release sampler state
	MHWRender::MStateManager::releaseSamplerState(fNoiseSamplerState);
	fNoiseSamplerState = NULL;
}
/*
	Desctructor

	Make sure to release the operations and any shaders acquired
	via the shader manager
*/
viewRenderOverrideShadows::~viewRenderOverrideShadows()
{
	for (unsigned int i=0; i<kOperationCount; i++)
	{
		delete mRenderOperations[i];
		mRenderOperations[i] = NULL;
	}

    MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer();
	if (theRenderer)
	{
		// Release shaders
		const MHWRender::MShaderManager* shaderMgr = theRenderer->getShaderManager();
		if (shaderMgr && mLightShader)
		{
			shaderMgr->releaseShader(mLightShader);
			mLightShader = NULL;
		}
	}
}
예제 #20
0
void UsdMayaGLHdRenderer::RenderVp2(
    const RequestDataArray &requests,
    const MHWRender::MDrawContext& context,
    UsdImagingGLRenderParams params) const
{
    using namespace MHWRender;

    MStatus status;
    MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer();
    if (!theRenderer) return;

    MHWRender::MStateManager* stateMgr = context.getStateManager();
    if (!stateMgr) return;

    const int displayStyle = context.getDisplayStyle();
    if (displayStyle == 0) return;

    if (displayStyle & MDrawContext::kXray) {
        // Viewport 2.0 will call draw() twice when drawing transparent objects
        // (X-Ray mode). We skip the first draw() call.
        const MRasterizerState* rasterState = stateMgr->getRasterizerState();
        if (rasterState && rasterState->desc().cullMode == MRasterizerState::kCullFront) {
            return;
        }
    }

    if (!theRenderer->drawAPIIsOpenGL()) return;


    glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT);

    const MMatrix worldView =
        context.getMatrix(MHWRender::MDrawContext::kWorldViewMtx, &status);
    GfMatrix4d modelViewMatrix(worldView.matrix);

    const MMatrix projection =
        context.getMatrix(MHWRender::MDrawContext::kProjectionMtx, &status);
    GfMatrix4d projectionMatrix(projection.matrix);

    // get root matrix
    MMatrix root = context.getMatrix(MHWRender::MDrawContext::kWorldMtx, &status);
    GfMatrix4d rootMatrix(root.matrix);

    // Extract camera settings from maya view
    int viewX, viewY, viewWidth, viewHeight;
    context.getViewportDimensions(viewX, viewY, viewWidth, viewHeight);

    GfVec4d viewport(viewX, viewY, viewWidth, viewHeight);

    M3dView::DisplayStyle viewDisplayStyle = displayStyle & MDrawContext::kWireFrame ?
        M3dView::kWireFrame : M3dView::kGouraudShaded;

    if(viewDisplayStyle == M3dView::kGouraudShaded)
    {
        px_vp20Utils::setupLightingGL(context);
        glEnable(GL_LIGHTING);
    }

    _renderer->SetCameraState(modelViewMatrix, projectionMatrix, viewport);

    _renderer->SetLightingStateFromOpenGL();


    TF_FOR_ALL(it, requests) {
        RequestData request = *it;
        if(viewDisplayStyle == M3dView::kWireFrame && request.drawRequest.displayStyle() == M3dView::kGouraudShaded) {
            request.drawRequest.setDisplayStyle(viewDisplayStyle);
        }

        switch(request.drawRequest.token()) {
        case UsdMayaGLHdRenderer::DRAW_WIREFRAME:
        case UsdMayaGLHdRenderer::DRAW_POINTS: {

            params.drawMode = request.drawRequest.token() == 
                UsdMayaGLHdRenderer::DRAW_WIREFRAME ? 
                    UsdImagingGLDrawMode::DRAW_WIREFRAME :
                    UsdImagingGLDrawMode::DRAW_POINTS;
            params.enableLighting = false;
            params.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_NOTHING;

            params.overrideColor = request.fWireframeColor;

            // Get and render usdPrim
            _renderer->Render(_renderedPrim, params);

            break;
        }
        case UsdMayaGLHdRenderer::DRAW_SHADED_FLAT:
        case UsdMayaGLHdRenderer::DRAW_SHADED_SMOOTH: {


            params.drawMode = ((request.drawRequest.token() == 
                    UsdMayaGLHdRenderer::DRAW_SHADED_FLAT) ?
                        UsdImagingGLDrawMode::DRAW_GEOM_FLAT : 
                        UsdImagingGLDrawMode::DRAW_GEOM_SMOOTH);
            params.enableLighting = true;
            params.cullStyle = 
                UsdImagingGLCullStyle::CULL_STYLE_BACK_UNLESS_DOUBLE_SIDED;

            _renderer->Render(_renderedPrim, params);


            break;
        }
        case UsdMayaGLHdRenderer::DRAW_BOUNDING_BOX: {
            px_vp20Utils::RenderBoundingBox(request.bounds,
                                            request.fWireframeColor,
                                            worldView,
                                            projection);
            break;
        }
        }
    }
void simpleNoiseShaderOverride::updateShader(
	MHWRender::MShaderInstance& shader,
	const MHWRender::MAttributeParameterMappingList& mappings)
{
	// Handle resolved name caching
	if (fResolvedNoiseMapName.length() == 0)
	{
		const MHWRender::MAttributeParameterMapping* mapping =
			mappings.findByParameterName("noiseLookupMap");
		if (mapping)
		{
			fResolvedNoiseMapName = mapping->resolvedParameterName();
		}
	}
	if (fResolvedNoiseSamplerName.length() == 0)
	{
		const MHWRender::MAttributeParameterMapping* mapping =
			mappings.findByParameterName("noiseLookupMapSampler");
		if (mapping)
		{
			fResolvedNoiseSamplerName = mapping->resolvedParameterName();
		}
	}

	// Set the parameters on the shader
	if (fResolvedNoiseMapName.length() > 0 &&
		fResolvedNoiseSamplerName.length() > 0)
	{
		// Set a point-clamp sampler to the shader
		if (!fNoiseSamplerState)
		{
			MHWRender::MSamplerStateDesc desc;
			desc.filter = MHWRender::MSamplerState::kMinMagMipPoint;
			desc.addressU = desc.addressV = desc.addressW =
				MHWRender::MSamplerState::kTexClamp;
			desc.minLOD = 0;
			desc.maxLOD = 0;
			fNoiseSamplerState =
				MHWRender::MStateManager::acquireSamplerState(desc);
		}
		if (fNoiseSamplerState)
		{
			shader.setParameter(fResolvedNoiseSamplerName, *fNoiseSamplerState);
		}

		// Generate the noise lookup table texture if necessary
		if (!fNoiseTexture)
		{
			MHWRender::MRenderer* renderer =
				MHWRender::MRenderer::theRenderer();
			MHWRender::MTextureManager* textureMgr =
				renderer ? renderer->getTextureManager() : NULL;
			if (textureMgr)
			{
				// First, search the texture cache to see if another instance of
				// this override has already generated the texture. We can reuse
				// it to save GPU memory since the noise data is constant.
				fNoiseTexture =
					textureMgr->findTexture(sNoiseLookupTextureName);

				// Not in cache, so we need to actually build the texture
				if (!fNoiseTexture)
				{
					// Get Maya's noise table
					const std::vector<float>& noiseData = GetMayaNoiseTable();

					// Create a 3D texture containing the data
					MHWRender::MTextureDescription desc;
					desc.setToDefault2DTexture();
					desc.fWidth = desc.fHeight = desc.fDepth =
						MRenderUtil::noiseTableCubeSide();
					desc.fFormat = MHWRender::kR32_FLOAT;
					desc.fTextureType = MHWRender::kVolumeTexture;
					desc.fMipmaps = 1;
					fNoiseTexture = textureMgr->acquireTexture(
						sNoiseLookupTextureName,
						desc,
						(const void*)&(noiseData[0]),
						false);
				}
			}
		}

		// Set the texture to the shader instance
		if (fNoiseTexture)
		{
			MHWRender::MTextureAssignment textureAssignment;
			textureAssignment.texture = fNoiseTexture;
			shader.setParameter(fResolvedNoiseMapName, textureAssignment);
		}
	}
}
예제 #22
0
//
//      updateRegistry
//
//      When attributes change which affect the shader compilation the
//      effectRegistry needs to be updated with the new values
//
void
OpenSubdivPtexShader::updateRegistry()
{
    // adaptive toggle
    if (_adaptiveDirty) {
        effectRegistry.setIsAdaptive(_adaptive);
        _adaptiveDirty = false;
    }

    // ptex color file
    if (_ptexColorDirty) {
        bool ptexColorValid = bindPtexTexture(_colorFile, &_ptexColor, CLR_TEXTURE_UNIT);
        effectRegistry.setPtexColorValid(ptexColorValid);
        _ptexColorDirty = false;
    }

    // ptex displacement file
    if (_ptexDisplacementDirty) {
        bool ptexDisplacementValid = bindPtexTexture(_displacementFile, &_ptexDisplacement, DISP_TEXTURE_UNIT);
        effectRegistry.setPtexDisplacementValid(ptexDisplacementValid);
        _ptexDisplacementDirty = false;
    }

    // ptex occlusion file
    if (_ptexOcclusionDirty) {
        bool ptexOcclusionValid = bindPtexTexture(_occlusionFile, &_ptexOcclusion, OCC_TEXTURE_UNIT);
        effectRegistry.setPtexOcclusionValid(ptexOcclusionValid);
        _ptexOcclusionDirty = false;
    }


    MHWRender::MRenderer *theRenderer = MHWRender::MRenderer::theRenderer();
    _theTextureManager = theRenderer->getTextureManager();

    // diffuse environment map file
    if (_diffEnvMapDirty) {
        GLuint diffEnvMapId = bindTexture( _diffEnvMapFile, DIFF_TEXTURE_UNIT );
        effectRegistry.setDiffuseEnvironmentId(diffEnvMapId);
        _diffEnvMapDirty = false;
    }

    // specular environment map file
    if (_specEnvMapDirty) {
        GLuint specEnvMapId = bindTexture( _specEnvMapFile, ENV_TEXTURE_UNIT );
        effectRegistry.setSpecularEnvironmentId(specEnvMapId);
        _specEnvMapDirty = false;
    }

    // shader source
    if (_shaderSourceDirty) {
        if ( _shaderSource.empty() ) {
            if ( effectRegistry.getShaderSource() != defaultShaderSource ) {
                effectRegistry.setShaderSource(defaultShaderSource);
            }
        } else {
            if ( effectRegistry.getShaderSource() != _shaderSource ) {
                effectRegistry.setShaderSource(_shaderSource);
            }
        }
        _shaderSourceDirty = false;
    }
}
예제 #23
0
depthShaderOverride::depthShaderOverride(const MObject& obj)
: MPxSurfaceShadingNodeOverride(obj)
, fFragmentName("")
{
	// Define fragments needed for VP2 version of shader, this could also be
	// defined in a separate XML file
	//
	// Define the input and output parameter names to match the input and
	// output attribute names so that the values are automatically populated
	// on the shader.
	//
	// Define a separate fragment for computing the camera space position so
	// that the operation can be done in the vertex shader rather than the
	// pixel shader. Then connect the two fragments together in a graph.
	static const MString sFragmentName("depthShaderPluginFragment");
	static const char* sFragmentBody =
		"<fragment uiName=\"depthShaderPluginFragment\" name=\"depthShaderPluginFragment\" type=\"plumbing\" class=\"ShadeFragment\" version=\"1.0\">"
		"	<description><![CDATA[Depth shader fragment]]></description>"
		"	<properties>"
		"		<float name=\"depthValue\" />"
		"		<float3 name=\"color\" />"
		"		<float3 name=\"colorFar\" />"
		"		<float name=\"near\" />"
		"		<float name=\"far\" />"
		"	</properties>"
		"	<values>"
		"		<float name=\"depthValue\" value=\"0.0\" />"
		"		<float3 name=\"color\" value=\"0.0,1.0,0.0\" />"
		"		<float3 name=\"colorFar\" value=\"0.0,0.0,1.0\" />"
		"		<float name=\"near\" value=\"0.0\" />"
		"		<float name=\"far\" value=\"2.0\" />"
		"	</values>"
		"	<outputs>"
		"		<float3 name=\"outColor\" />"
		"	</outputs>"
		"	<implementation>"
		"	<implementation render=\"OGSRenderer\" language=\"Cg\" lang_version=\"2.1\">"
		"		<function_name val=\"depthShaderPluginFragment\" />"
		"		<source><![CDATA["
		"float3 depthShaderPluginFragment(float depthValue, float3 cNear, float3 cFar, float nearClip, float farClip) \n"
		"{ \n"
		"	float ratio = (farClip + depthValue)/(farClip - nearClip); \n"
		"	return cNear*ratio + cFar*(1.0f - ratio); \n"
		"} \n]]>"
		"		</source>"
		"	</implementation>"
		"	<implementation render=\"OGSRenderer\" language=\"HLSL\" lang_version=\"11.0\">"
		"		<function_name val=\"depthShaderPluginFragment\" />"
		"		<source><![CDATA["
		"float3 depthShaderPluginFragment(float depthValue, float3 cNear, float3 cFar, float nearClip, float farClip) \n"
		"{ \n"
		"	float ratio = (farClip + depthValue)/(farClip - nearClip); \n"
		"	return cNear*ratio + cFar*(1.0f - ratio); \n"
		"} \n]]>"
		"		</source>"
		"	</implementation>"
		"	<implementation render=\"OGSRenderer\" language=\"GLSL\" lang_version=\"3.0\">"
		"		<function_name val=\"depthShaderPluginFragment\" />"
		"		<source><![CDATA["
		"vec3 depthShaderPluginFragment(float depthValue, vec3 cNear, vec3 cFar, float nearClip, float farClip) \n"
		"{ \n"
		"	float ratio = (farClip + depthValue)/(farClip - nearClip); \n"
		"	return cNear*ratio + cFar*(1.0f - ratio); \n"
		"} \n]]>"
		"		</source>"
		"	</implementation>"
		"	</implementation>"
		"</fragment>";

	static const MString sVertexFragmentName("depthShaderPluginInterpolantFragment");
	static const char* sVertexFragmentBody =
		"<fragment uiName=\"depthShaderPluginInterpolantFragment\" name=\"depthShaderPluginInterpolantFragment\" type=\"interpolant\" class=\"ShadeFragment\" version=\"1.0\">"
		"	<description><![CDATA[Depth shader vertex fragment]]></description>"
		"	<properties>"
		"		<float3 name=\"Pm\" semantic=\"Pm\" flags=\"varyingInputParam\" />"
		"		<float4x4 name=\"worldViewProj\" semantic=\"worldviewprojection\" />"
		"	</properties>"
		"	<values>"
		"	</values>"
		"	<outputs>"
		"		<float name=\"outDepthValue\" ^1s/>"
		"	</outputs>"
		"	<implementation>"
		"	<implementation render=\"OGSRenderer\" language=\"Cg\" lang_version=\"2.1\">"
		"		<function_name val=\"depthShaderPluginInterpolantFragment\" />"
		"		<source><![CDATA["
		"float depthShaderPluginInterpolantFragment(float depthValue) \n"
		"{ \n"
		"	return depthValue; \n"
		"} \n]]>"
		"		</source>"
		"		<vertex_source><![CDATA["
		"float idepthShaderPluginInterpolantFragment(float3 Pm, float4x4 worldViewProj) \n"
		"{ \n"
		"	float4 pCamera = mul(worldViewProj, float4(Pm, 1.0f)); \n"
		"	return (pCamera.z - pCamera.w*2.0f); \n"
		"} \n]]>"
		"		</vertex_source>"
		"	</implementation>"
		"	<implementation render=\"OGSRenderer\" language=\"HLSL\" lang_version=\"11.0\">"
		"		<function_name val=\"depthShaderPluginInterpolantFragment\" />"
		"		<source><![CDATA["
		"float depthShaderPluginInterpolantFragment(float depthValue) \n"
		"{ \n"
		"	return depthValue; \n"
		"} \n]]>"
		"		</source>"
		"		<vertex_source><![CDATA["
		"float idepthShaderPluginInterpolantFragment(float3 Pm, float4x4 worldViewProj) \n"
		"{ \n"
		"	float4 pCamera = mul(float4(Pm, 1.0f), worldViewProj); \n"
		"	return (pCamera.z - pCamera.w*2.0f); \n"
		"} \n]]>"
		"		</vertex_source>"
		"	</implementation>"
		"	<implementation render=\"OGSRenderer\" language=\"GLSL\" lang_version=\"3.0\">"
		"		<function_name val=\"depthShaderPluginInterpolantFragment\" />"
		"		<source><![CDATA["
		"float depthShaderPluginInterpolantFragment(float depthValue) \n"
		"{ \n"
		"	return depthValue; \n"
		"} \n]]>"
		"		</source>"
		"		<vertex_source><![CDATA["
		"float idepthShaderPluginInterpolantFragment(vec3 Pm, mat4 worldViewProj) \n"
		"{ \n"
		"	vec4 pCamera = worldViewProj * vec4(Pm, 1.0f); \n"
		"	return (pCamera.z - pCamera.w*2.0f); \n"
		"} \n]]>"
		"		</vertex_source>"
		"	</implementation>"
		"	</implementation>"
		"</fragment>";

	static const MString sFragmentGraphName("depthShaderPluginGraph");
	static const char* sFragmentGraphBody =
		"<fragment_graph name=\"depthShaderPluginGraph\" ref=\"depthShaderPluginGraph\" class=\"FragmentGraph\" version=\"1.0\">"
		"	<fragments>"
		"			<fragment_ref name=\"depthShaderPluginFragment\" ref=\"depthShaderPluginFragment\" />"
		"			<fragment_ref name=\"depthShaderPluginInterpolantFragment\" ref=\"depthShaderPluginInterpolantFragment\" />"
		"	</fragments>"
		"	<connections>"
		"		<connect from=\"depthShaderPluginInterpolantFragment.outDepthValue\" to=\"depthShaderPluginFragment.depthValue\" />"
		"	</connections>"
		"	<properties>"
        "		<float3 name=\"Pm\" ref=\"depthShaderPluginInterpolantFragment.Pm\" semantic=\"Pm\" flags=\"varyingInputParam\" />"
        "		<float4x4 name=\"worldViewProj\" ref=\"depthShaderPluginInterpolantFragment.worldViewProj\" semantic=\"worldviewprojection\" />"
		"		<float3 name=\"color\" ref=\"depthShaderPluginFragment.color\" />"
		"		<float3 name=\"colorFar\" ref=\"depthShaderPluginFragment.colorFar\" />"
		"		<float name=\"near\" ref=\"depthShaderPluginFragment.near\" />"
		"		<float name=\"far\" ref=\"depthShaderPluginFragment.far\" />"
		"	</properties>"
		"	<values>"
		"		<float3 name=\"color\" value=\"0.0,1.0,0.0\" />"
		"		<float3 name=\"colorFar\" value=\"0.0,0.0,1.0\" />"
		"		<float name=\"near\" value=\"0.0\" />"
		"		<float name=\"far\" value=\"2.0\" />"
		"	</values>"
		"	<outputs>"
		"		<float3 name=\"outColor\" ref=\"depthShaderPluginFragment.outColor\" />"
		"	</outputs>"
		"</fragment_graph>";

	// Register fragments with the manager if needed
	MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer();
	if (theRenderer)
	{
		MHWRender::MFragmentManager* fragmentMgr =
			theRenderer->getFragmentManager();
		if (fragmentMgr)
		{
			// Add fragments if needed
			bool fragAdded = fragmentMgr->hasFragment(sFragmentName);
			bool vertFragAdded = fragmentMgr->hasFragment(sVertexFragmentName);
			bool graphAdded = fragmentMgr->hasFragment(sFragmentGraphName);
			if (!fragAdded)
			{
				fragAdded = (sFragmentName == fragmentMgr->addShadeFragmentFromBuffer(sFragmentBody, false));
			}
			if (!vertFragAdded)
			{
				// In DirectX, need to specify a semantic for the output of the vertex shader
				MString vertBody;
				if (theRenderer->drawAPI() == MHWRender::kDirectX11)
				{
					vertBody.format(MString(sVertexFragmentBody), MString("semantic=\"extraDepth\" "));
				}
				else
				{
					vertBody.format(MString(sVertexFragmentBody), MString(" "));
				}
				vertFragAdded = (sVertexFragmentName == fragmentMgr->addShadeFragmentFromBuffer(vertBody.asChar(), false));
			}
			if (!graphAdded)
			{
				graphAdded = (sFragmentGraphName == fragmentMgr->addFragmentGraphFromBuffer(sFragmentGraphBody));
			}

			// If we have them all, use the final graph for the override
			if (fragAdded && vertFragAdded && graphAdded)
			{
				fFragmentName = sFragmentGraphName;
			}
		}
	}
}
/*
	From the draw context, get the list of lights and queue the ones we are interested in
	into the "desired list"
*/
MStatus shadowPrepass::execute( const MHWRender::MDrawContext & context )
{
	MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer();
	if (!theRenderer)
		return MStatus::kSuccess;

	// Skip lighting modes where there are no lights which can
	// cast shadows
	MHWRender::MDrawContext::LightingMode lightingMode = context.getLightingMode();
	if (lightingMode != MHWRender::MDrawContext::kSelectedLights &&
		lightingMode != MHWRender::MDrawContext::kSceneLights)
	{
		return MStatus::kSuccess;
	}

	MHWRender::MDrawContext::LightFilter lightFilter = 
		MHWRender::MDrawContext::kFilteredIgnoreLightLimit;
	unsigned int nbSceneLights = context.numberOfActiveLights(lightFilter);

	for (unsigned int i=0; i<nbSceneLights; i++)
	{
		MHWRender::MLightParameterInformation* lightInfo = 
			context.getLightParameterInformation( i, lightFilter );
		if (!lightInfo)
			continue;

		// Get the actually Maya light node
		MStatus status = MStatus::kFailure;
		MDagPath lightPath = lightInfo->lightPath(&status);
		if (status != MStatus::kSuccess || !lightPath.isValid())
			continue;

		// Would be good to have an API method here to indicate if it
		// casts shadows
		MIntArray intVals;

		// Check if light is enabled, and emits any lighting
		MHWRender::MLightParameterInformation::StockParameterSemantic semantic =
			MHWRender::MLightParameterInformation::kLightEnabled;
		if (MStatus::kSuccess == lightInfo->getParameter( semantic, intVals ))
		{
			if (intVals.length())
			{
				if (intVals[0] == 0)
					continue;
			}
		}

		semantic = MHWRender::MLightParameterInformation::kEmitsDiffuse;
		if (MStatus::kSuccess == lightInfo->getParameter( semantic, intVals ))
		{
			if (intVals.length())
			{
				if (intVals[0] == 0)
					continue;
			}
		}

		semantic = MHWRender::MLightParameterInformation::kEmitsSpecular;
		if (MStatus::kSuccess == lightInfo->getParameter( semantic, intVals ))
		{
			if (intVals.length())
			{
				if (intVals[0] == 0)
					continue;
			}
		}

		// Check if local shadows are enabled.
		semantic = MHWRender::MLightParameterInformation::kShadowOn;
		if (MStatus::kSuccess == lightInfo->getParameter( semantic, intVals ))
		{
			if (intVals.length())
			{
				if (intVals[0] == 0)
					continue;
			}
		}

		// Check if the shadow is "dirty"
		bool shadowIsDirty = false;
		semantic = MHWRender::MLightParameterInformation::kShadowDirty;
		if (MStatus::kSuccess == lightInfo->getParameter( semantic, intVals ))
		{
			if (intVals.length())
			{
				if (intVals[0] == 0)
				//	continue;

				shadowIsDirty = intVals[0] != 0 ? true : false ;
			}
		}

		// Check the light list to prune, if not already pruned
		bool prune = false;
		if (lightingMode != MHWRender::MDrawContext::kSelectedLights)
		{
			if (mLightList && mLightList->length())
			{
				prune = !mLightList->hasItem(lightInfo->lightPath());
			}
		}

		static bool debugShadowRequests = false;
		// Set that we require shadows for this light
		if (!prune)
		{
			if (debugShadowRequests)
				fprintf(stderr, "QUEUE light shadows for %s, shadowDirty = %d\n", 
					lightPath.fullPathName().asChar(), shadowIsDirty);

			theRenderer->setLightRequiresShadows( lightPath.node(), true );
		}
		
		// Set that we DON'T require shadows for this light
		else
		{
			if (debugShadowRequests)
				fprintf(stderr, "DEQUEUE light shadows for %s, shadowDirty = %d\n", 
					lightPath.fullPathName().asChar(), shadowIsDirty);
			theRenderer->setLightRequiresShadows( lightPath.node(), false );
		}
	}

	return MStatus::kSuccess;
}
/*
	Utility method to update shader parameters based on available
	lighting information.
*/
static void updateLightShader( MHWRender::MShaderInstance *shaderInstance,
						const MHWRender::MDrawContext & context,
						const MSelectionList * lightList )
{
	if (!shaderInstance)
		return;

	// Check pass context information to see if we are in a shadow 
	// map update pass. If so do nothing.
	//
	const MHWRender::MPassContext & passCtx = context.getPassContext();
	const MStringArray & passSem = passCtx.passSemantics();
	bool handlePass = true;
	for (unsigned int i=0; i<passSem.length() && handlePass; i++)
	{
		// Handle special pass drawing.
		//
		if (passSem[i] == MHWRender::MPassContext::kShadowPassSemantic)
		{
			handlePass = false;
		}
	}
	if (!handlePass) return;

	//
	// Perform light shader update with lighting information
	// If the light list is not empty then use that light's information.
	// Otherwise choose the first appropriate light which can cast shadows.
	//

	// Defaults in case there are no lights
	//
	bool globalShadowsOn = false;
	bool localShadowsOn = false;
	bool shadowDirty = false;
	MFloatVector direction(0.0f, 0.0f, 1.0f);
	float lightIntensity = 0.0f; // If no lights then black out the light
	float lightColor[3] = { 0.0f, 0.0f, 0.0f };

	MStatus status;

	// Scan to find the first N lights that has a direction component in it
	// It's possible we find no lights.
	//
	MHWRender::MDrawContext::LightFilter considerAllSceneLights = MHWRender::MDrawContext::kFilteredIgnoreLightLimit;
	unsigned int lightCount = context.numberOfActiveLights(considerAllSceneLights);
	if (lightCount)
	{
		MFloatArray floatVals;
		MIntArray intVals;
		MHWRender::MTextureAssignment shadowResource;
		shadowResource.texture = NULL;
		MHWRender::MSamplerStateDesc samplerDesc;
		MMatrix shadowViewProj;
		float shadowColor[3] = { 0.0f, 0.0f, 0.0f };

		unsigned int i=0;
		bool foundDirectional = false;
		for (i=0; i<lightCount && !foundDirectional ; i++)
		{
			MHWRender::MLightParameterInformation *lightParam = context.getLightParameterInformation( i, considerAllSceneLights );
			if (lightParam)
			{
				// Prune against light list if any.
				if (lightList && lightList->length())
				{
					if (!lightList->hasItem(lightParam->lightPath()))
						continue;
				}

				MStringArray params;
				lightParam->parameterList(params);
				for (unsigned int p=0; p<params.length(); p++)
				{
					MString pname = params[p];

					MHWRender::MLightParameterInformation::StockParameterSemantic semantic = lightParam->parameterSemantic( pname );
					switch (semantic)
					{
						// Pick a few light parameters to pick up as an example
					case MHWRender::MLightParameterInformation::kWorldDirection:
						lightParam->getParameter( pname, floatVals );
						direction = MFloatVector( floatVals[0], floatVals[1], floatVals[2] );
						foundDirectional = true;
						break;
					case MHWRender::MLightParameterInformation::kIntensity:
						lightParam->getParameter( pname, floatVals );
						lightIntensity = floatVals[0];
						break;
					case MHWRender::MLightParameterInformation::kColor:
						lightParam->getParameter( pname, floatVals );
						lightColor[0] = floatVals[0];
						lightColor[1] = floatVals[1];
						lightColor[2] = floatVals[2];
						break;

						// Pick up shadowing parameters
					case MHWRender::MLightParameterInformation::kGlobalShadowOn:
						lightParam->getParameter( pname, intVals );
						if (intVals.length())
							globalShadowsOn = (intVals[0] != 0) ? true : false;
						break;
					case MHWRender::MLightParameterInformation::kShadowOn:
						lightParam->getParameter( pname, intVals );
						if (intVals.length())
							localShadowsOn = (intVals[0] != 0) ? true : false;
						break;
					case MHWRender::MLightParameterInformation::kShadowViewProj:
						lightParam->getParameter( pname, shadowViewProj);
						break;
					case MHWRender::MLightParameterInformation::kShadowMap:
						lightParam->getParameter( pname, shadowResource );
						break;
					case MHWRender::MLightParameterInformation::kShadowDirty:
						if (intVals.length())
							shadowDirty = (intVals[0] != 0) ? true : false;
						break;
					case MHWRender::MLightParameterInformation::kShadowSamp:
						lightParam->getParameter( pname, samplerDesc );
						break;
					case MHWRender::MLightParameterInformation::kShadowColor:
						lightParam->getParameter( pname, floatVals );
						shadowColor[0] = floatVals[0];
						shadowColor[1] = floatVals[1];
						shadowColor[2] = floatVals[2];
						break;
					default:
						break;
					}
				} /* for params */
			}

			if (foundDirectional && globalShadowsOn && localShadowsOn && shadowResource.texture)
			{
				void *resourceHandle = shadowResource.texture->resourceHandle();
				if (resourceHandle)
				{
					static bool debugShadowBindings = false;
					status  = shaderInstance->setParameter("mayaShadowPCF1_shadowMap", shadowResource );
					if (status == MStatus::kSuccess && debugShadowBindings)
						fprintf(stderr, "Bound shadow map to shader param mayaShadowPCF1_shadowMap\n");
					status  = shaderInstance->setParameter("mayaShadowPCF1_shadowViewProj", shadowViewProj );
					if (status == MStatus::kSuccess && debugShadowBindings)
						fprintf(stderr, "Bound shadow map transform to shader param mayaShadowPCF1_shadowViewProj\n");
					status  = shaderInstance->setParameter("mayaShadowPCF1_shadowColor", &shadowColor[0] );
					if (status == MStatus::kSuccess && debugShadowBindings)
						fprintf(stderr, "Bound shadow map color to shader param mayaShadowPCF1_shadowColor\n");
				}

				MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
				if (renderer)
				{
					MHWRender::MTextureManager* textureManager = renderer->getTextureManager();
					if (textureManager)
					{
						textureManager->releaseTexture(shadowResource.texture);
					}
				}
				shadowResource.texture = NULL;
			}
		}
	}

	// Set up parameters which should be set regardless of light existence.
	status = shaderInstance->setParameter("mayaDirectionalLight_direction", &( direction[0] ));
	status = shaderInstance->setParameter("mayaDirectionalLight_intensity", lightIntensity );
	status = shaderInstance->setParameter("mayaDirectionalLight_color", &( lightColor[0] ));
	status = shaderInstance->setParameter("mayaShadowPCF1_mayaGlobalShadowOn", globalShadowsOn);
	status = shaderInstance->setParameter("mayaShadowPCF1_mayaShadowOn", localShadowsOn);
}
예제 #26
0
GammaOverride::GammaOverride(const MObject& obj)
: MPxShadingNodeOverride(obj)
, fFragmentName("")
{
	// Define fragments needed for VP2 version of shader, this could also be
	// defined in a separate XML file
	//
	// Define the input and output parameter names to match the input and
	// output attribute names so that the values are automatically populated
	// on the shader.
	static const MString sFragmentName("gammaShaderPluginFragment");
	static const char* sFragmentBody =
		"<fragment uiName=\"gammaShaderPluginFragment\" name=\"gammaShaderPluginFragment\" type=\"plumbing\" class=\"ShadeFragment\" version=\"1.0\">"
		"	<description><![CDATA[Gamma utility fragment]]></description>"
		"	<properties>"
		"		<float3 name=\"color\" />"
		"		<float3 name=\"gamma\" />"
		"	</properties>"
		"	<values>"
		"		<float3 name=\"color\" value=\"0.5,0.5,0.5\" />"
		"		<float3 name=\"gamma\" value=\"1.0,1.0,1.0\" />"
		"	</values>"
		"	<outputs>"
		"		<float3 name=\"outColor\" />"
		"	</outputs>"
		"	<implementation>"
		"	<implementation render=\"OGSRenderer\" language=\"Cg\" lang_version=\"2.1\">"
		"		<function_name val=\"gammaShaderPluginFragment\" />"
		"		<source><![CDATA["
		"float3 gammaShaderPluginFragment(float3 icol, float3 igam) \n"
		"{ \n"
		"	float3 result; \n"
		"	result.r = pow(icol.r, 1.0f/igam.r); \n"
		"	result.g = pow(icol.g, 1.0f/igam.g); \n"
		"	result.b = pow(icol.b, 1.0f/igam.b); \n"
		"	return result; \n"
		"} \n]]>"
		"		</source>"
		"	</implementation>"
		"	<implementation render=\"OGSRenderer\" language=\"HLSL\" lang_version=\"11.0\">"
		"		<function_name val=\"gammaShaderPluginFragment\" />"
		"		<source><![CDATA["
		"float3 gammaShaderPluginFragment(float3 icol, float3 igam) \n"
		"{ \n"
		"	float3 result; \n"
		"	result.r = pow(icol.r, 1.0f/igam.r); \n"
		"	result.g = pow(icol.g, 1.0f/igam.g); \n"
		"	result.b = pow(icol.b, 1.0f/igam.b); \n"
		"	return result; \n"
		"} \n]]>"
		"		</source>"
		"	</implementation>"
		"	<implementation render=\"OGSRenderer\" language=\"GLSL\" lang_version=\"3.0\">"
		"		<function_name val=\"gammaShaderPluginFragment\" />"
		"		<source><![CDATA["
		"vec3 gammaShaderPluginFragment(vec3 icol, vec3 igam) \n"
		"{ \n"
		"	vec3 result; \n"
		"	result.r = pow(icol.r, 1.0f/igam.r); \n"
		"	result.g = pow(icol.g, 1.0f/igam.g); \n"
		"	result.b = pow(icol.b, 1.0f/igam.b); \n"
		"	return result; \n"
		"} \n]]>"
		"		</source>"
		"	</implementation>"
		"	</implementation>"
		"</fragment>";

	// Register fragments with the manager if needed
	MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer();
	if (theRenderer)
	{
		MHWRender::MFragmentManager* fragmentMgr =
			theRenderer->getFragmentManager();
		if (fragmentMgr)
		{
			// Add fragments if needed
			bool fragAdded = fragmentMgr->hasFragment(sFragmentName);
			if (!fragAdded)
			{
				fragAdded = (sFragmentName == fragmentMgr->addShadeFragmentFromBuffer(sFragmentBody, false));
			}

			// Use the fragment on successful add
			if (fragAdded)
			{
				fFragmentName = sFragmentName;
			}
		}
	}
}
MStatus viewRenderUserOperation::execute( const MHWRender::MDrawContext & drawContext )
{
	// Sample code to debug pass information
	static const bool debugPassInformation = false;
	if (debugPassInformation)
	{
		const MHWRender::MPassContext & passCtx = drawContext.getPassContext();
		const MString & passId = passCtx.passIdentifier();
		const MStringArray & passSem = passCtx.passSemantics();
		printf("viewRenderUserOperation: drawing in pass[%s], semantic[", passId.asChar());
		for (unsigned int i=0; i<passSem.length(); i++)
			printf(" %s", passSem[i].asChar());
		printf("\n");
	}

	// Example code to find the active override.
	// This is not necessary if the operations just keep a reference
	// to the override, but this demonstrates how this
	// contextual information can be extracted.
	//
	MHWRender::MRenderer *theRenderer = MHWRender::MRenderer::theRenderer();
	const MHWRender::MRenderOverride *overridePtr = NULL;
	if (theRenderer)
	{
		const MString & overrideName = theRenderer->activeRenderOverride();
		overridePtr = theRenderer->findRenderOverride( overrideName );
	}

	// Some sample code to debug lighting information in the MDrawContext
	//
	if (fDebugLightingInfo)
	{
		viewRenderOverrideUtilities::printDrawContextLightInfo( drawContext );
	}

	// Some sample code to debug other MDrawContext information
	//
	if (fDebugDrawContext)
	{
		MStatus status;
		MMatrix matrix = drawContext.getMatrix(MHWRender::MFrameContext::kWorldMtx, &status);
		double dest[4][4];
		status = matrix.get(dest);
		printf("World matrix is:\n");
		printf("\t%f, %f, %f, %f\n", dest[0][0], dest[0][1], dest[0][2], dest[0][3]);
		printf("\t%f, %f, %f, %f\n", dest[1][0], dest[1][1], dest[1][2], dest[1][3]);
		printf("\t%f, %f, %f, %f\n", dest[2][0], dest[2][1], dest[2][2], dest[2][3]);
		printf("\t%f, %f, %f, %f\n", dest[3][0], dest[3][1], dest[3][2], dest[3][3]);

		MDoubleArray viewDirection = drawContext.getTuple(MHWRender::MFrameContext::kViewDirection, &status);
		printf("Viewdirection is: %f, %f, %f\n", viewDirection[0], viewDirection[1], viewDirection[2]);

		MBoundingBox box = drawContext.getSceneBox(&status);
		printf("Screen box is:\n");
		printf("\twidth=%f, height=%f, depth=%f\n", box.width(), box.height(), box.depth());
		float center[4];
		box.center().get(center);
		printf("\tcenter=(%f, %f, %f, %f)\n", center[0], center[1], center[2], center[3]);


		int originX, originY, width, height;
		status = drawContext.getViewportDimensions(originX, originY, width, height);
		printf("Viewport dimension: center(%d, %d), width=%d, heigh=%d\n", originX, originY, width, height);
	}

	//  Draw some addition things for scene draw
	//
	M3dView mView;
	if (mPanelName.length() &&
		(M3dView::getM3dViewFromModelPanel(mPanelName, mView) == MStatus::kSuccess))
	{
		// Get the current viewport and scale it relative to that
		//
		int targetW, targetH;
		drawContext.getRenderTargetSize( targetW, targetH );

		if (fDrawLabel)
		{
			MString testString("Drawing with override: ");
			testString += overridePtr->name();
			MPoint pos(0.0,0.0,0.0);
			glColor3f( 1.0f, 1.0f, 1.0f );
			mView.drawText( testString, pos);
		}

		// Some user drawing of scene bounding boxes
		//
		if (fDrawBoundingBoxes)
		{
			MDagPath cameraPath;
			mView.getCamera( cameraPath);
			MCustomSceneDraw userDraw;
			userDraw.draw( cameraPath, targetW, targetH );
		}
	}
	return MStatus::kSuccess;
}