Exemple #1
0
	void SkyLight::RenderLight(RenderManagerPtr pRenderer)
	{
		if(GetEnabled() == false)
		{
			return;
		}

		const math::Matrix44& view = pRenderer->GetViewMatrix();
		const math::Matrix44& proj = pRenderer->GetProjMatrix();

		pRenderer->SetMatrixBlock(m_pMaterial, math::MatrixIdentity());
		
		const math::Matrix44& tm = GetWorldTM();

		math::Vector3 d = tm.GetRow3(2);

		struct DirLightParam
		{
			math::Vector3 d;
			float i;
			math::Vector3 c;
		};

		DirLightParam l;
		l.d = d;
		l.i = GetIntensity();
		const math::Color4& diffClr = GetDiffuseColor();

		l.c = math::Vector3(diffClr.r, diffClr.g, diffClr.b);

		MaterialParameterPtr pParam = m_pMaterial->GetParameterByName("light");
		pParam->SetParameterBlock(&l, sizeof(DirLightParam));

		pRenderer->SetGBuffer(m_pMaterial);

		if(m_bCastShadow)
		{
			pParam = m_pMaterial->GetParameterByName("shadow_map");
		
			pParam->SetParameterTexture(m_pShadowMap->GetTexture(0));
			pParam = m_pMaterial->GetParameterByName("light_tm");
			pParam->SetParameterMatrix(m_lightTM);
		}

		pRenderer->DrawFullScreenQuad(m_pMaterial);
	}
Exemple #2
0
	void SkyLight::RenderLight(RenderSystemPtr pRenderer)
	{
		if(GetEnabled() == false)
		{
			return;
		}

		const math::Matrix44& view = pRenderer->GetViewMatrix();
		const math::Matrix44& proj = pRenderer->GetProjMatrix();


		m_pMaterial->SetWorldMatrix(math::MatrixIdentity());
		m_pMaterial->SetViewMatrix(view);
		m_pMaterial->SetProjMatrix(proj);


		const math::Matrix44& tm = GetWorldTM();

		math::Vector3 d = tm.GetRow3(2);

		struct DirLightParam
		{
			math::Vector3 d;
			float i;
			math::Vector3 c;
			float specularPow;
		};

		DirLightParam l;
		l.d = d;
		l.i = GetIntensity();
		const math::Color4& diffClr = GetDiffuseColor();

		l.c = math::Vector3(diffClr.r, diffClr.g, diffClr.b);
		l.specularPow = GetSpecularPow();

		m_pMaterial->SetCBByName("light", &l, sizeof(DirLightParam));
		m_pMaterial->SetGBuffer(pRenderer->GetGBuffer());
				
		pRenderer->DrawFullScreenQuad(m_pMaterial);
	}
Exemple #3
0
	//TODO: Z might have to be some standard value...
	//Has 100 right now, this should be in some global value..
	int cLight2DPoint::Render(iLowLevelGraphics* apLowLevel, int alFirstIndex)
	{
		//make the center vetrex:
		cVector3f vTex(0);
		cVector3f vPos;
		cVector3f vLightPos = GetWorldPosition();
		vLightPos.z = 100;
		float fRadius = GetFarAttenuation();

		cColor Col = GetDiffuseColor()*mfIntensity;
		Col.a =0;
		cVertex Vtx = cVertex(vLightPos,vTex,Col);
		apLowLevel->AddVertexToBatch(&Vtx); //index 0!

		Col = cColor(0,0);
		int idx=alFirstIndex+1;
		for(float fAngle=0;fAngle<=k2Pif;fAngle+=k2Pif/32)
		{
			vPos.x = vLightPos.x + fRadius * cos(fAngle);//*0.5;
			vPos.y = vLightPos.y + fRadius * sin(fAngle);//*0.5;
			vPos.z = 100;
			Vtx = cVertex(vPos,vTex,Col);
			apLowLevel->AddVertexToBatch(&Vtx);
			if(idx>0) {
				apLowLevel->AddIndexToBatch(alFirstIndex);     //The center
				apLowLevel->AddIndexToBatch(idx);   //The current point
				apLowLevel->AddIndexToBatch(idx-1); //The previous  point
			}
			idx++;
		}
		apLowLevel->AddIndexToBatch(alFirstIndex);     //The center
		apLowLevel->AddIndexToBatch(alFirstIndex+1);     //The current point
		apLowLevel->AddIndexToBatch(idx-1); //The previous  point

		return idx;
	}
void Material::PrepareRenderState(InstanceMaterialState * instanceMaterialState)
{
    ///float32 timeElapsed = SystemTimer::Instance()->FrameDelta();

    if(MATERIAL_UNLIT_TEXTURE_LIGHTMAP == type)
	{
        if (!instanceMaterialState->lightmapTexture)
        {
            SetSetupLightmap(true);
        }
		else
        {
            SetSetupLightmap(false);
            renderStateBlock.SetTexture(instanceMaterialState->lightmapTexture, 1);
        }
    }
	else if (MATERIAL_UNLIT_TEXTURE_DECAL == type || MATERIAL_UNLIT_TEXTURE_DETAIL == type)
    {
        renderStateBlock.SetTexture(textures[Material::TEXTURE_DECAL], 1);
    }


    
	renderStateBlock.shader = shader;

	if (textures[Material::TEXTURE_DIFFUSE])
	{
		renderStateBlock.SetTexture(textures[Material::TEXTURE_DIFFUSE], 0);
	}


	if(MATERIAL_PIXEL_LIT_NORMAL_DIFFUSE == type || MATERIAL_PIXEL_LIT_NORMAL_DIFFUSE_SPECULAR == type || MATERIAL_PIXEL_LIT_NORMAL_DIFFUSE_SPECULAR_MAP == type)
	{
		if (textures[Material::TEXTURE_NORMALMAP])
		{
			renderStateBlock.SetTexture(textures[Material::TEXTURE_NORMALMAP], 1);
		}
	}
	else
	{
//		if (textures[Material::TEXTURE_DECAL])
//		{
//			renderStateBlock.SetTexture(textures[Material::TEXTURE_DECAL], 1);
//		}
	}

	if (isTranslucent || isTwoSided)
	{
		renderStateBlock.state &= ~RenderStateBlock::STATE_CULL;
	}
	else
	{
		renderStateBlock.state |= RenderStateBlock::STATE_CULL;
	}


	if(isAlphablend)
	{
		renderStateBlock.state |= RenderStateBlock::STATE_BLEND;
		//Dizz: temporary solution
		renderStateBlock.state &= ~RenderStateBlock::STATE_DEPTH_WRITE;

		renderStateBlock.SetBlendMode((eBlendMode)blendSrc, (eBlendMode)blendDst);
	}
	else
	{
		//Dizz: temporary solution
		renderStateBlock.state |= RenderStateBlock::STATE_DEPTH_WRITE;
		renderStateBlock.state &= ~RenderStateBlock::STATE_BLEND;
	}

	if(isWireframe)
	{
		renderStateBlock.SetFillMode(FILLMODE_WIREFRAME);
	}
	else
	{
		renderStateBlock.SetFillMode(FILLMODE_SOLID);
	}

	// render
	RenderManager::Instance()->FlushState(&renderStateBlock);
	RenderManager::Instance()->AttachRenderData();


    if(uniformTexture0 != -1)
    {
        shader->SetUniformValue(uniformTexture0, 0);
    }
    if(uniformTexture1 != -1)
    {
        shader->SetUniformValue(uniformTexture1, 1);
    }

	if(isSetupLightmap)
	{
		int32 lightmapSizePosition = shader->FindUniformLocationByName("lightmapSize");
		if (lightmapSizePosition != -1)
		{
			shader->SetUniformValue(lightmapSizePosition, (float32)setupLightmapSize); 
		}
	}
    

	if(MATERIAL_UNLIT_TEXTURE_LIGHTMAP == type)
	{
		if (uniformUvOffset != -1)
			shader->SetUniformValue(uniformUvOffset, instanceMaterialState->uvOffset);
		if (uniformUvScale != -1)
			shader->SetUniformValue(uniformUvScale, instanceMaterialState->uvScale);
	}

	if (isFogEnabled)
	{
		DVASSERT(uniformFogDensity != -1);
        shader->SetUniformValue(uniformFogDensity, fogDensity);
		
        DVASSERT(uniformFogColor != -1)
        shader->SetUniformColor3(uniformFogColor, fogColor);
	}
    
    if (instanceMaterialState)
    {
        if (isFlatColorEnabled)
        {
            DVASSERT(uniformFlatColor != -1);
            shader->SetUniformColor4(uniformFlatColor, instanceMaterialState->flatColor);
        }
        if (isTexture0ShiftEnabled)
        {
            DVASSERT(uniformTexture0Shift != -1);
            shader->SetUniformValue(uniformTexture0Shift, instanceMaterialState->texture0Shift);
        }

        Camera * camera = scene->GetCurrentCamera();
        Light * lightNode0 = instanceMaterialState->GetLight(0);
        if (lightNode0 && camera)
        {
            if (uniformLightPosition0 != -1)
            {
                const Matrix4 & matrix = camera->GetMatrix();
                Vector3 lightPosition0InCameraSpace = lightNode0->GetPosition() * matrix;
                
                shader->SetUniformValue(uniformLightPosition0, lightPosition0InCameraSpace);
            }
            if (uniformMaterialLightAmbientColor != -1)
            {
                shader->SetUniformColor3(uniformMaterialLightAmbientColor, lightNode0->GetAmbientColor() * GetAmbientColor());
            }
            if (uniformMaterialLightDiffuseColor != -1)
            {
                shader->SetUniformColor3(uniformMaterialLightDiffuseColor, lightNode0->GetDiffuseColor() * GetDiffuseColor());
            }
            if (uniformMaterialLightSpecularColor != -1)
            {
                shader->SetUniformColor3(uniformMaterialLightSpecularColor, lightNode0->GetSpecularColor() * GetSpecularColor());
            }
            if (uniformMaterialSpecularShininess != -1)
            {
                shader->SetUniformValue(uniformMaterialSpecularShininess, shininess);
            }
            
            if (uniformLightIntensity0 != -1)
            {
                shader->SetUniformValue(uniformLightIntensity0, lightNode0->GetIntensity());
            }
            if (uniformLightAttenuationQ != -1)
            {
                //shader->SetUniformValue(uniformLightAttenuationQ, lightNode0->GetAttenuation());
            }
        }
    }

}
Exemple #5
0
void Material::Draw(PolygonGroup * group, InstanceMaterialState * instanceMaterialState)
{
	if(!RenderManager::Instance()->GetOptions()->IsOptionEnabled(RenderOptions::MATERIAL_DRAW))
	{
		return;
	}

	if(isOpaque && !RenderManager::Instance()->GetOptions()->IsOptionEnabled(RenderOptions::OPAQUE_DRAW))
	{
		return;
	}

	//Dizz: uniformFogDensity != -1 is a check if fog is inabled in shader
	if(isFogEnabled && (uniformFogDensity != -1) && !RenderManager::Instance()->GetOptions()->IsOptionEnabled(RenderOptions::FOG_ENABLE))
	{
		RebuildShader();
	}

	if(isFogEnabled && (uniformFogDensity == -1) && RenderManager::Instance()->GetOptions()->IsOptionEnabled(RenderOptions::FOG_ENABLE))
	{
		RebuildShader();
	}

	RenderManager::Instance()->SetRenderData(group->renderDataObject);

	eBlendMode oldSrc;
	eBlendMode oldDst;
	if(isAlphablend)
	{
		oldSrc = RenderManager::Instance()->GetSrcBlend();
		oldDst = RenderManager::Instance()->GetDestBlend();
	}

	PrepareRenderState();

    if (instanceMaterialState)
    {
        Camera * camera = scene->GetCurrentCamera();
        LightNode * lightNode0 = instanceMaterialState->GetLight(0);
        if (lightNode0 && camera)
        {
            if (uniformLightPosition0 != -1)
            {
                const Matrix4 & matrix = camera->GetMatrix();
                Vector3 lightPosition0InCameraSpace = lightNode0->GetPosition() * matrix;
                
                shader->SetUniformValue(uniformLightPosition0, lightPosition0InCameraSpace); 
            }
            if (uniformMaterialLightAmbientColor != -1)
            {
                shader->SetUniformValue(uniformMaterialLightAmbientColor, lightNode0->GetAmbientColor() * GetAmbientColor());
            }
            if (uniformMaterialLightDiffuseColor != -1)
            {
                shader->SetUniformValue(uniformMaterialLightDiffuseColor, lightNode0->GetDiffuseColor() * GetDiffuseColor());
            }
            if (uniformMaterialLightSpecularColor != -1)
            {
                shader->SetUniformValue(uniformMaterialLightSpecularColor, lightNode0->GetSpecularColor() * GetSpecularColor());
            }
            if (uniformMaterialSpecularShininess != -1)
            {
                shader->SetUniformValue(uniformMaterialSpecularShininess, shininess);
            }
            
            if (uniformLightIntensity0 != -1)
            {
                shader->SetUniformValue(uniformLightIntensity0, lightNode0->GetIntensity());
            }
            if (uniformLightAttenuationQ != -1)
            {
                //shader->SetUniformValue(uniformLightAttenuationQ, lightNode0->GetAttenuation());
            }
        }
    }
    
    // TODO: rethink this code
    if (group->renderDataObject->GetIndexBufferID() != 0)
	{
		RenderManager::Instance()->HWDrawElements(PRIMITIVETYPE_TRIANGLELIST, group->indexCount, EIF_16, 0);
	}else
	{
		RenderManager::Instance()->HWDrawElements(PRIMITIVETYPE_TRIANGLELIST, group->indexCount, EIF_16, group->indexArray);
	}
    
	RenderManager::Instance()->SetTexture(0, 1); 
	RenderManager::Instance()->SetState(RenderStateBlock::DEFAULT_3D_STATE);
	if(isAlphablend)
	{
		RenderManager::Instance()->SetBlendMode(oldSrc, oldDst);
	}
}
Exemple #6
0
static int DoNextEditorDataChunk (T3dsLoaderPers *pers, long endofs)
{
    T3dsChunk *chunk;

#ifdef DEBUG_PM_3DS_EX
    printf("DoNextEditorDataChunk: endofs %d\n",endofs);
#endif
    while (pers->cofs < endofs)
    {
        long nextofs = pers->cofs;
        if ((chunk = GetChunk(pers)) == NULL) return 0;
        if (!chunk->len) return 0;
        nextofs += chunk->len;

#ifdef DEBUG_PM_3DS_EX
        printf("Chunk %04x (%s), len %d pers->cofs %x\n",chunk->id,DebugGetChunkName(chunk->id),chunk->len,pers->cofs);
#endif
        /*** meshes ***/
        if (chunk->id == CHUNK_OBJECT)
        {
            picoSurface_t *surface;
            char surfaceName[ 0xff ] = { 0 };

            /* read in surface name */
            if( !GetASCIIZ(pers,surfaceName,sizeof(surfaceName)) )
                return 0; /* this is bad */

//PicoGetSurfaceName
            /* ignore NULL name surfaces */
//            if( surfaceName

            /* allocate a pico surface */
            surface = PicoNewSurface( pers->model );
            if( surface == NULL )
            {
                pers->surface = NULL;
                return 0; /* this is bad too */
            }
            /* assign ptr to current surface */
            pers->surface = surface;

            /* 3ds models surfaces are all triangle meshes */
            PicoSetSurfaceType( pers->surface,PICO_TRIANGLES );

            /* set surface name */
            PicoSetSurfaceName( pers->surface,surfaceName );

            /* continue mess with object's sub chunks */
            DoNextEditorDataChunk(pers,nextofs);
            continue;
        }
        if (chunk->id == CHUNK_OBJECT_MESH)
        {
            /* continue mess with mesh's sub chunks */
            if (!DoNextEditorDataChunk(pers,nextofs)) return 0;
            continue;
        }
        if (chunk->id == CHUNK_OBJECT_VERTICES)
        {
            if (!GetMeshVertices(pers)) return 0;
            continue;
        }
        if (chunk->id == CHUNK_OBJECT_FACES)
        {
            if (!GetMeshFaces(pers)) return 0;
            continue;
        }
        if (chunk->id == CHUNK_OBJECT_UV)
        {
            if (!GetMeshTexCoords(pers)) return 0;
            continue;
        }
        if (chunk->id == CHUNK_OBJECT_MATERIAL)
        {
            if (!GetMeshShader(pers)) return 0;
            continue;
        }
        /*** materials ***/
        if (chunk->id == CHUNK_MATERIAL)
        {
            /* new shader specific things should be */
            /* initialized right here */
            picoShader_t *shader;

            /* allocate a pico shader */
            shader = PicoNewShader( pers->model );    /* ydnar */
            if( shader == NULL )
            {
                pers->shader = NULL;
                return 0; /* this is bad too */
            }
            
            /* assign ptr to current shader */
            pers->shader = shader;

            /* continue and process the material's sub chunks */
            DoNextEditorDataChunk(pers,nextofs);
            continue;
        }
        if (chunk->id == CHUNK_MATNAME)
        {
            /* new material's names should be stored here. note that */
            /* GetMeshMaterial returns the name of the material that */
            /* is used by the mesh. new material names are set HERE. */
            /* but for now we skip the new material's name ... */
            if (pers->shader)
            {
                char *name = (char*) (pers->bufptr + pers->cofs);
                char *cleanedName = _pico_clone_alloc( name );
                _pico_first_token( cleanedName );
                PicoSetShaderName( pers->shader, cleanedName );
#ifdef DEBUG_PM_3DS
                printf( "NewShader: '%s'\n", cleanedName );
#endif
                _pico_free( cleanedName );
            }
        }
        if (chunk->id == CHUNK_MATDIFFUSE)
        {
            /* todo: color for last inserted new material should be */
            /* stored somewhere by GetDiffuseColor */
            if (!GetDiffuseColor(pers)) return 0;

            /* rest of chunk is skipped here */
        }
        if (chunk->id == CHUNK_MATMAP)
        {
            /* continue and process the material map sub chunks */
            DoNextEditorDataChunk(pers,nextofs);
            continue;
        }
        if (chunk->id == CHUNK_MATMAPFILE)
        {
            /* map file name for last inserted new material should */
            /* be stored here. but for now we skip this too ... */
            if( pers->shader )
            {
                char *name = (char *)(pers->bufptr + pers->cofs);
                PicoSetShaderMapName( pers->shader,name );
#ifdef DEBUG_PM_3DS
                printf("NewShaderMapfile: '%s'\n",name);
#endif
            }
        }
        /*** keyframes ***/
        if (chunk->id == CHUNK_KEYFRAME_DATA)
        {
            /* well umm, this is a bit too much since we don't really */
            /* need model animation sequences right now. we skip this */
#ifdef DEBUG_PM_3DS
            printf("KeyframeData: len %d\n",chunk->len);
#endif
        }
        /* skip unknown chunk */
        pers->cofs = nextofs;
        if (pers->cofs >= pers->maxofs) break;
    }
    return 1;
}
Color basic_shader::Shade( const Scene &scene, const HitInfo &hit ) const
    {
    Ray ray;
	Ray reflectionRay;
	Ray refractedRay;
	Ray secondaryRefractedRay;

    HitInfo otherhit;
	HitInfo refractionHit;
    static const double epsilon = 1.0E-6;
    if( Emitter( hit.object ) ) return hit.object->material->emission;

    Material *mat   = hit.object->material;
    Color  diffuse  = mat->diffuse;
    Color  specular = mat->specular;
    Color  color    = mat->ambient * diffuse;
    Vec3   O = hit.ray.origin;
    Vec3   P = hit.point;
    Vec3   N = hit.normal;
    Vec3   E = Unit( O - P );
    Vec3   R = Unit( ( 2.0 * ( E * N ) ) * N - E );
    Color  r = mat->reflectivity;
    double e = mat->Phong_exp;
    double k = mat->ref_index;
	Color t = mat->translucency;

	if(hit.object->Inside(P)){
		P = P + epsilon*N;
	}

    if( E * N < 0.0 ) N = -N;  // Flip the normal if necessary.

	//get the attentuation
	
	double attenuation;
	double lightDistance;
	Vec3 lightVector;
	double diffuseFactor;
	double specularFactor;
	Color diffuseColor = Color();
	Color specularColor = Color();
	Color finalColor;
	Color colorWithLighting;
	Color reflectedColor;
	Color refractedColor;
	Vec3 currentR;
	double shadowFactor = 0;
	bool objectWasHit = false;

	int numGridVals = 30;
	float numSamples = 5;
	int totalNumGridVals = numGridVals*numGridVals*numSamples;
	int totalArrayValues = totalNumGridVals*2;
	float totalGridVals = numGridVals;
	float currentXvalue;
	float currentYvalue;
	float interval = 2.0f/totalGridVals;
	float currentDist;
	bool posZinHemisphere,negZinHemisphere;
	int currentInd1,currentInd2;
	float randomX,randomY;
	float currentPosZvalue,currentNegZvalue;
	//Vec3 currentNormal = Vec3(0.0f,0.0f,1.0f);
	Vec3 currentNormal = N;
	float dotProdPosZ,dotProdNegZ,dotProdXYpart;
	Vec3 positiveZvector;
	Vec3 negativeZvector;
	int numLightsHit = 0;
	
	/*
	Surface Area of sphere from each patch P is approximately area(P)*(1/z') where z' is taken at the center
	This comes from the fact that the surface area is integral_P (1/z)
	*/
	float minZvalue=sqrt(interval)*sqrt(2-interval);;
	
	//used to calculate surface area
	float centerXvalue,centerYvalue,centerZvalue,approxSurfaceArea;

	//temp variable. default emission of the light blocks
	Color defaultEmission = Color(1.0,1.0,1.0);
	double emissionFactor = 30.0;

	Color posZpatchValue = Color();
	Color negZpatchValue = Color();
	Color posZpatchSpecValue = Color();
	Color negZpatchSpecValue = Color();
	double radius,patchFormFactor;
	Vec3 otherNormal;
	float currentEnergy = 0;

	for(int xInd = 0; xInd < numGridVals; xInd++){
		for(int yInd = 0; yInd < numGridVals; yInd++){

			centerXvalue = -1 + interval*xInd + interval*0.5;
			centerYvalue = -1 + interval*yInd + interval*0.5;
			currentDist = centerXvalue*centerXvalue + centerYvalue*centerYvalue;
			centerZvalue = sqrt(1-currentDist);

			
			if(centerZvalue < minZvalue){
				centerZvalue = minZvalue;
			}

			approxSurfaceArea = interval*interval*(1.0f/centerZvalue);	
			

			posZpatchValue = Color();
			negZpatchValue = Color();

			for(int sampleInd = 0; sampleInd < numSamples; sampleInd++){

				randomX = (double)rand() / RAND_MAX;
				randomY = (double)rand() / RAND_MAX;

				currentXvalue = -1+interval*xInd + interval*randomX;
				currentYvalue = -1+interval*yInd + interval*randomY;
				
				currentDist = currentXvalue*currentXvalue + currentYvalue*currentYvalue;

				posZinHemisphere = false;
				negZinHemisphere = false;

				currentInd1 = (xInd*numGridVals + yInd)*numSamples + sampleInd;
				currentInd2 = currentInd1 + totalNumGridVals;

				//makes sure it is inside the unit disk
				if(currentDist <= 1){

					currentPosZvalue = sqrt(1-currentDist);
					currentNegZvalue = -currentPosZvalue;

					dotProdXYpart = currentNormal.x*currentXvalue + currentNormal.y*currentYvalue;
					dotProdPosZ = currentNormal.z*currentPosZvalue + dotProdXYpart;
					dotProdNegZ = currentNormal.z*currentNegZvalue + dotProdXYpart;

					posZinHemisphere = (dotProdPosZ >=0);
					negZinHemisphere = (dotProdNegZ >=0);

				}


				if(posZinHemisphere){

					positiveZvector = Vec3(currentXvalue,currentYvalue,currentPosZvalue);

					//light ray to case to determine occulsion
					ray.origin = P;
					ray.direction = positiveZvector;
					HitInfo objectHit;
					objectHit.distance = Infinity;

					shadowFactor = 1;
					if(scene.Cast(ray,objectHit) ){
						if(objectHit.object != NULL){
							Vec3 LightPos = objectHit.point;
							
							if(LightPos.z > 12.0){
								lightVector = LightPos - P;
								numLightsHit = numLightsHit + 1;
								radius = Length(lightVector);
								otherNormal = Unit(objectHit.normal);
								lightVector = Unit(lightVector);

								//this is the current patches approximation of F_ij
								//patchFormFactor = ((abs(lightVector*currentNormal))*(abs(-1*lightVector*otherNormal)))/(Pi*radius*radius);
								patchFormFactor = ((lightVector*currentNormal)*(-1*lightVector*otherNormal))/(Pi*radius*radius);
								patchFormFactor = max(0,patchFormFactor);
								//printf("radius: %f\n",radius);
								currentEnergy = currentEnergy + emissionFactor*patchFormFactor;
								diffuseColor = diffuseColor + GetDiffuseColor(lightVector,N,defaultEmission,diffuse);
							}
						}
					}

				}

				if(negZinHemisphere){
					negativeZvector = Vec3(currentXvalue,currentYvalue,currentNegZvalue);
					//printf("(x,y,z)=(%f,%f,%f)\n",gridXvalues[currentInd2],gridYvalues[currentInd2],gridZvalues[currentInd2]);

					//light ray to case to determine occulsion
					ray.origin = P;
					ray.direction = negativeZvector;
					HitInfo objectHit;
					objectHit.distance = Infinity;

					shadowFactor = 1;
					if(scene.Cast(ray,objectHit) ){
						if(objectHit.object != NULL){
							Vec3 LightPos = objectHit.point;
							
							if(LightPos.z > 12.0){
								lightVector = LightPos - P;
								numLightsHit = numLightsHit + 1;
								radius = Length(lightVector);
								
								otherNormal = Unit(objectHit.normal);
								lightVector = Unit(lightVector);

								//this is the current patches approximation of F_ij
								//patchFormFactor = ((abs(lightVector*currentNormal))*(abs(-1*lightVector*otherNormal)))/(Pi*radius*radius);
								patchFormFactor = ((lightVector*currentNormal)*(-1*lightVector*otherNormal))/(Pi*radius*radius);
								patchFormFactor = max(0,patchFormFactor);
								currentEnergy = currentEnergy + emissionFactor*patchFormFactor;
								diffuseColor = diffuseColor + GetDiffuseColor(lightVector,N,defaultEmission,diffuse);
								//negZpatchValue = negZpatchValue + GetDiffuseColor(lightVector,N,defaultEmission,diffuse);
							}
						}
					}
				}

			}

			//diffuseColor = diffuseColor + (posZpatchValue/numSamples)*approxSurfaceArea;
			//diffuseColor = diffuseColor + (negZpatchValue/numSamples)*approxSurfaceArea;
			//printf("Approx Surface Area:%f\n",approxSurfaceArea);

			//diffuseColor = diffuseColor + posZpatchValue;
			//diffuseColor = diffuseColor + negZpatchValue;

			if(diffuseColor.blue > 0.5 || diffuseColor.green > 0.5 || diffuseColor.red > 0.5){
				//printf("Current Diffuse Color: (%f,%f,%f)\n",diffuseColor.blue,diffuseColor.green,diffuseColor.red);
			}
			
			
		}
	}
	
	//makes sure to include the light vectors in the calculations
	for( unsigned i = 0; i < scene.NumLights(); i++ )
        {
        const Object *light = scene.GetLight(i);
        Color emission = light->material->emission;
        AABB box = GetBox( *light );
        Vec3 LightPos( Center( box ) ); 

		//gets the light Vector
		lightVector = LightPos - P;
		lightDistance = Length(lightVector);
		Vec3 unitLightVector = Unit(lightVector);
		
		//gets the attenuation factor
		attenuation = 1/(attenuation_a + attenuation_b*lightDistance + attenuation_c*lightDistance*lightDistance);

		float dotProd = currentNormal.x*unitLightVector.x + currentNormal.y*unitLightVector.y + currentNormal.z*unitLightVector.z;

		//light vector in unit hemipshere
		if(dotProd >= 0){

			//light ray to case to determine occulsion
			ray.origin = P;
			ray.direction = unitLightVector;
			HitInfo objectHit;
			objectHit.distance = Infinity;

			if(scene.Cast(ray,objectHit) ){
				if(objectHit.object != NULL){
					Vec3 LightPos = objectHit.point;
							
					if(LightPos.z > 12.0){
						numLightsHit = numLightsHit + 1;
						lightVector = LightPos - P;
						//diffuseColor = diffuseColor + GetDiffuseColor(lightVector,N,defaultEmission,diffuse);

						radius = Length(lightVector);
								
						otherNormal = Unit(objectHit.normal);
						lightVector = Unit(lightVector);

						//this is the current patches approximation of F_ij
						//patchFormFactor = ((abs(lightVector*currentNormal))*(abs(-1*lightVector*otherNormal)))/(Pi*radius*radius);
						patchFormFactor = ((lightVector*currentNormal)*(-1*lightVector*otherNormal))/(Pi*radius*radius);
						patchFormFactor = max(0,patchFormFactor);
						currentEnergy = currentEnergy + emissionFactor*patchFormFactor;
						diffuseColor = diffuseColor + GetDiffuseColor(lightVector,N,defaultEmission,diffuse);
					}
				}
			}

		}

		

		
    }

	diffuseColor = currentEnergy*defaultEmission;

	//diffuseColor = diffuseColor/12.0;

	float numLights = numLightsHit;
	//diffuseColor = diffuseColor/(numLights*Pi);
	if(numLightsHit > 1){
		//printf("Number of Lights Hit:%d\n",numLightsHit);
		//printf("Original Color: (%f,%f,%f)\n",diffuse.blue,diffuse.green,diffuse.red);
		//printf("Diffuse Color: (%f,%f,%f)\n\n",diffuseColor.blue,diffuseColor.green,diffuseColor.red);

	}

	//colorWithLighting = color + diffuseColor*diffuse + specularColor*specular;
	//colorWithLighting = diffuseColor*diffuse;
	colorWithLighting = diffuseColor*diffuse + diffuse*0.4;

	//set variables for reflection
	reflectionRay.origin = P;
	reflectionRay.direction = R;
	reflectionRay.generation = hit.ray.generation + 1;
	reflectedColor = Color();

	//set variables for refraction

	refractedRay.origin = P-epsilon*N;

	Vec3 refractionDir = RefractionDirection(1.0,k,E,N);
	refractedRay.direction = refractionDir; //for refraction
	refractedRay.generation = hit.ray.generation + 1;
	refractedColor = Color();
 	refractionHit.distance = Infinity;

	//only do refraction if the transluency is greater than zero
	//	this is an optimization so unnecessary refractions are not calculated
	if( (t.red + t.green + t.blue) > epsilon){
		if(scene.Cast(refractedRay,refractionHit)){

			bool insideMaterial = false;
			Vec3 currentNormal;
			Vec3 previousRefractedDirection;

			do{
				currentNormal = Unit(refractionHit.normal);
				previousRefractedDirection = refractedRay.direction;
				refractedRay.direction = RefractionDirection(k,1.0,-1*refractedRay.direction,-1*currentNormal);

				if(Length(refractedRay.direction) < epsilon){
					insideMaterial = true;
					refractionHit.distance = Infinity;
					refractedRay.origin = refractionHit.point - epsilon*currentNormal;
					refractedRay.direction = Unit( ( 2.0 * ( previousRefractedDirection * currentNormal ) ) * (-1*currentNormal) + previousRefractedDirection );


					if(!scene.Cast(refractedRay,refractionHit)){
						insideMaterial = false;
					}
				}else{

					refractedRay.origin = refractionHit.point + epsilon*currentNormal;
					insideMaterial = false;

				}

				

			}while(insideMaterial);

			refractedRay.generation = hit.ray.generation + 1;

			//now do refraction
			refractedColor = scene.Trace(refractedRay);

		}
	}


	//do the reflection
	//only do reflection if the reflectance is greater than zero
	//	this is an optimization so unnecessary reflections are not calculated
	if( (r.red + r.green + r.blue) > epsilon){
		reflectedColor = scene.Trace(reflectionRay);
	}
	
	//printf("diffuseColor: (%f,%f,%f)\n",colorWithLighting.red,colorWithLighting.green,colorWithLighting.blue);

	//now combine calculated color with reflected color
	//finalColor = (-1*t + Color(1.0,1.0,1.0))*(colorWithLighting + r*reflectedColor) + t*refractedColor;

	return colorWithLighting;
	//return finalColor; 
    }
Exemple #8
0
//----------------------------------------------------------------------------
MtlLoader::MtlLoader (const string& path, const string& filename)
    :
    mCode(EC_SUCCESSFUL),
    mCurrent(-1)
{
    mLogFile = fopen("MtlLogFile.txt", "wt");
    if (!mLogFile)
    {
        assert(false);
        mCode = EC_LOGFILE_OPEN_FAILED;
        return;
    }

    string filePath = path + filename;
    ifstream inFile(filePath.c_str());
    if (!inFile)
    {
        assert(false);
        mCode = EC_FILE_OPEN_FAILED;
        fprintf(mLogFile, "%s: %s\n", msCodeString[mCode], filePath.c_str());
        fclose(mLogFile);
        return;
    }

    string line;
    vector<string> tokens;

    while (!inFile.eof())
    {
        getline(inFile, line);

        // Skip blank lines.
        if (line == "") { continue; }

        // Skip comments.
        if (line[0] == '#') { continue; }

        GetTokens(line, tokens);
        if (tokens.size() == 0)
        {
            assert(false);
            mCode = EC_NO_TOKENS;
            break;
        }

        // newmtl
        if (GetNewMaterial(tokens)) { continue; }
        if (mCode != EC_SUCCESSFUL) { break; }

        // illum
        if (GetIlluminationModel(tokens)) { continue; }
        if (mCode != EC_SUCCESSFUL) { break; }

        // Ka
        if (GetAmbientColor(tokens)) { continue; }
        if (mCode != EC_SUCCESSFUL) { break; }

        // Kd
        if (GetDiffuseColor(tokens)) { continue; }
        if (mCode != EC_SUCCESSFUL) { break; }

        // Ks
        if (GetSpecularColor(tokens)) { continue; }
        if (mCode != EC_SUCCESSFUL) { break; }

        // Tf
        if (GetTransmissionFilter(tokens)) { continue; }
        if (mCode != EC_SUCCESSFUL) { break; }

        // Ni
        if (GetOpticalDensity(tokens)) { continue; }
        if (mCode != EC_SUCCESSFUL) { break; }

        // Ni
        if (GetSpecularExponent(tokens)) { continue; }
        if (mCode != EC_SUCCESSFUL) { break; }

        // map_Kd
        if (GetDiffuseTexture(tokens)) { continue; }
        if (mCode != EC_SUCCESSFUL) { break; }

        assert(false);
        mCode = EC_UNEXPECTED_TOKEN;
        break;
    }

    if (mCode != EC_SUCCESSFUL)
    {
        fprintf(mLogFile, "%s: %s\n", msCodeString[mCode], line.c_str());
    }
    else
    {
        fprintf(mLogFile, "%s\n", msCodeString[EC_SUCCESSFUL]);
    }
    fclose(mLogFile);
    inFile.close();
}