PageRenderTime 139ms CodeModel.GetById 16ms app.highlight 109ms RepoModel.GetById 1ms app.codeStats 1ms

/indra/newview/lltexlayer.cpp

https://bitbucket.org/lindenlab/viewer-beta/
C++ | 2347 lines | 1810 code | 294 blank | 243 comment | 301 complexity | 018c418ac44468a479fe2dc343bd42b7 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/** 
   2 * @file lltexlayer.cpp
   3 * @brief A texture layer. Used for avatars.
   4 *
   5 * $LicenseInfo:firstyear=2002&license=viewerlgpl$
   6 * Second Life Viewer Source Code
   7 * Copyright (C) 2010, Linden Research, Inc.
   8 * 
   9 * This library is free software; you can redistribute it and/or
  10 * modify it under the terms of the GNU Lesser General Public
  11 * License as published by the Free Software Foundation;
  12 * version 2.1 of the License only.
  13 * 
  14 * This library is distributed in the hope that it will be useful,
  15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  17 * Lesser General Public License for more details.
  18 * 
  19 * You should have received a copy of the GNU Lesser General Public
  20 * License along with this library; if not, write to the Free Software
  21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
  22 * 
  23 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
  24 * $/LicenseInfo$
  25 */
  26
  27#include "llviewerprecompiledheaders.h"
  28
  29#include "lltexlayer.h"
  30
  31#include "llagent.h"
  32#include "llimagej2c.h"
  33#include "llimagetga.h"
  34#include "llnotificationsutil.h"
  35#include "llvfile.h"
  36#include "llvfs.h"
  37#include "llviewerstats.h"
  38#include "llviewerregion.h"
  39#include "llvoavatar.h"
  40#include "llvoavatarself.h"
  41#include "pipeline.h"
  42#include "llassetuploadresponders.h"
  43#include "lltexlayerparams.h"
  44#include "llui.h"
  45#include "llagentwearables.h"
  46#include "llwearable.h"
  47#include "llviewercontrol.h"
  48#include "llviewershadermgr.h"
  49#include "llviewervisualparam.h"
  50
  51//#include "../tools/imdebug/imdebug.h"
  52
  53using namespace LLVOAvatarDefines;
  54
  55static const S32 BAKE_UPLOAD_ATTEMPTS = 7;
  56static const F32 BAKE_UPLOAD_RETRY_DELAY = 2.f; // actual delay grows by power of 2 each attempt
  57
  58class LLTexLayerInfo
  59{
  60	friend class LLTexLayer;
  61	friend class LLTexLayerTemplate;
  62	friend class LLTexLayerInterface;
  63public:
  64	LLTexLayerInfo();
  65	~LLTexLayerInfo();
  66
  67	BOOL parseXml(LLXmlTreeNode* node);
  68	BOOL createVisualParams(LLVOAvatar *avatar);
  69	BOOL isUserSettable() { return mLocalTexture != -1;	}
  70	S32  getLocalTexture() const { return mLocalTexture; }
  71	BOOL getOnlyAlpha() const { return mUseLocalTextureAlphaOnly; }
  72	std::string getName() const { return mName;	}
  73
  74private:
  75	std::string				mName;
  76	
  77	BOOL					mWriteAllChannels; // Don't use masking.  Just write RGBA into buffer,
  78	LLTexLayerInterface::ERenderPass mRenderPass;
  79
  80	std::string				mGlobalColor;
  81	LLColor4				mFixedColor;
  82
  83	S32						mLocalTexture;
  84	std::string				mStaticImageFileName;
  85	BOOL					mStaticImageIsMask;
  86	BOOL					mUseLocalTextureAlphaOnly; // Ignore RGB channels from the input texture.  Use alpha as a mask
  87	BOOL					mIsVisibilityMask;
  88
  89	typedef std::vector< std::pair< std::string,BOOL > > morph_name_list_t;
  90	morph_name_list_t		    mMorphNameList;
  91	param_color_info_list_t		mParamColorInfoList;
  92	param_alpha_info_list_t		mParamAlphaInfoList;
  93};
  94
  95//-----------------------------------------------------------------------------
  96// LLBakedUploadData()
  97//-----------------------------------------------------------------------------
  98LLBakedUploadData::LLBakedUploadData(const LLVOAvatarSelf* avatar,
  99									 LLTexLayerSet* layerset,
 100									 const LLUUID& id,
 101									 bool highest_res) :
 102	mAvatar(avatar),
 103	mTexLayerSet(layerset),
 104	mID(id),
 105	mStartTime(LLFrameTimer::getTotalTime()),		// Record starting time
 106	mIsHighestRes(highest_res)
 107{ 
 108}
 109
 110//-----------------------------------------------------------------------------
 111// LLTexLayerSetBuffer
 112// The composite image that a LLTexLayerSet writes to.  Each LLTexLayerSet has one.
 113//-----------------------------------------------------------------------------
 114
 115// static
 116S32 LLTexLayerSetBuffer::sGLByteCount = 0;
 117
 118LLTexLayerSetBuffer::LLTexLayerSetBuffer(LLTexLayerSet* const owner, 
 119										 S32 width, S32 height) :
 120	// ORDER_LAST => must render these after the hints are created.
 121	LLViewerDynamicTexture( width, height, 4, LLViewerDynamicTexture::ORDER_LAST, TRUE ), 
 122	mUploadPending(FALSE), // Not used for any logic here, just to sync sending of updates
 123	mNeedsUpload(FALSE),
 124	mNumLowresUploads(0),
 125	mUploadFailCount(0),
 126	mNeedsUpdate(TRUE),
 127	mNumLowresUpdates(0),
 128	mTexLayerSet(owner)
 129{
 130	LLTexLayerSetBuffer::sGLByteCount += getSize();
 131	mNeedsUploadTimer.start();
 132	mNeedsUpdateTimer.start();
 133}
 134
 135LLTexLayerSetBuffer::~LLTexLayerSetBuffer()
 136{
 137	LLTexLayerSetBuffer::sGLByteCount -= getSize();
 138	destroyGLTexture();
 139	for( S32 order = 0; order < ORDER_COUNT; order++ )
 140	{
 141		LLViewerDynamicTexture::sInstances[order].erase(this);  // will fail in all but one case.
 142	}
 143}
 144
 145//virtual 
 146S8 LLTexLayerSetBuffer::getType() const 
 147{
 148	return LLViewerDynamicTexture::LL_TEX_LAYER_SET_BUFFER ;
 149}
 150
 151//virtual 
 152void LLTexLayerSetBuffer::restoreGLTexture() 
 153{	
 154	LLViewerDynamicTexture::restoreGLTexture() ;
 155}
 156
 157//virtual 
 158void LLTexLayerSetBuffer::destroyGLTexture() 
 159{
 160	LLViewerDynamicTexture::destroyGLTexture() ;
 161}
 162
 163// static
 164void LLTexLayerSetBuffer::dumpTotalByteCount()
 165{
 166	llinfos << "Composite System GL Buffers: " << (LLTexLayerSetBuffer::sGLByteCount/1024) << "KB" << llendl;
 167}
 168
 169void LLTexLayerSetBuffer::requestUpdate()
 170{
 171	restartUpdateTimer();
 172	mNeedsUpdate = TRUE;
 173	mNumLowresUpdates = 0;
 174	// If we're in the middle of uploading a baked texture, we don't care about it any more.
 175	// When it's downloaded, ignore it.
 176	mUploadID.setNull();
 177}
 178
 179void LLTexLayerSetBuffer::requestUpload()
 180{
 181	conditionalRestartUploadTimer();
 182	mNeedsUpload = TRUE;
 183	mNumLowresUploads = 0;
 184	mUploadPending = TRUE;
 185}
 186
 187void LLTexLayerSetBuffer::conditionalRestartUploadTimer()
 188{
 189	// If we requested a new upload but haven't even uploaded
 190	// a low res version of our last upload request, then
 191	// keep the timer ticking instead of resetting it.
 192	if (mNeedsUpload && (mNumLowresUploads == 0))
 193	{
 194		mNeedsUploadTimer.unpause();
 195	}
 196	else
 197	{
 198		mNeedsUploadTimer.reset();
 199		mNeedsUploadTimer.start();
 200	}
 201}
 202
 203void LLTexLayerSetBuffer::restartUpdateTimer()
 204{
 205	mNeedsUpdateTimer.reset();
 206	mNeedsUpdateTimer.start();
 207}
 208
 209void LLTexLayerSetBuffer::cancelUpload()
 210{
 211	mNeedsUpload = FALSE;
 212	mUploadPending = FALSE;
 213	mNeedsUploadTimer.pause();
 214	mUploadRetryTimer.reset();
 215}
 216
 217void LLTexLayerSetBuffer::pushProjection() const
 218{
 219	gGL.matrixMode(LLRender::MM_PROJECTION);
 220	gGL.pushMatrix();
 221	gGL.loadIdentity();
 222	gGL.ortho(0.0f, mFullWidth, 0.0f, mFullHeight, -1.0f, 1.0f);
 223
 224	gGL.matrixMode(LLRender::MM_MODELVIEW);
 225	gGL.pushMatrix();
 226	gGL.loadIdentity();
 227}
 228
 229void LLTexLayerSetBuffer::popProjection() const
 230{
 231	gGL.matrixMode(LLRender::MM_PROJECTION);
 232	gGL.popMatrix();
 233
 234	gGL.matrixMode(LLRender::MM_MODELVIEW);
 235	gGL.popMatrix();
 236}
 237
 238BOOL LLTexLayerSetBuffer::needsRender()
 239{
 240	llassert(mTexLayerSet->getAvatar() == gAgentAvatarp);
 241	if (!isAgentAvatarValid()) return FALSE;
 242
 243	const BOOL upload_now = mNeedsUpload && isReadyToUpload();
 244	const BOOL update_now = mNeedsUpdate && isReadyToUpdate();
 245
 246	// Don't render if we don't want to (or aren't ready to) upload or update.
 247	if (!(update_now || upload_now))
 248	{
 249		return FALSE;
 250	}
 251
 252	// Don't render if we're animating our appearance.
 253	if (gAgentAvatarp->getIsAppearanceAnimating())
 254	{
 255		return FALSE;
 256	}
 257
 258	// Don't render if we are trying to create a shirt texture but aren't wearing a skirt.
 259	if (gAgentAvatarp->getBakedTE(mTexLayerSet) == LLVOAvatarDefines::TEX_SKIRT_BAKED && 
 260		!gAgentAvatarp->isWearingWearableType(LLWearableType::WT_SKIRT))
 261	{
 262		cancelUpload();
 263		return FALSE;
 264	}
 265
 266	// Render if we have at least minimal level of detail for each local texture.
 267	return mTexLayerSet->isLocalTextureDataAvailable();
 268}
 269
 270void LLTexLayerSetBuffer::preRender(BOOL clear_depth)
 271{
 272	// Set up an ortho projection
 273	pushProjection();
 274	
 275	// keep depth buffer, we don't need to clear it
 276	LLViewerDynamicTexture::preRender(FALSE);
 277}
 278
 279void LLTexLayerSetBuffer::postRender(BOOL success)
 280{
 281	popProjection();
 282
 283	LLViewerDynamicTexture::postRender(success);
 284}
 285
 286BOOL LLTexLayerSetBuffer::render()
 287{
 288	// Default color mask for tex layer render
 289	gGL.setColorMask(true, true);
 290
 291	// do we need to upload, and do we have sufficient data to create an uploadable composite?
 292	// TODO: When do we upload the texture if gAgent.mNumPendingQueries is non-zero?
 293	const BOOL upload_now = mNeedsUpload && isReadyToUpload();
 294	const BOOL update_now = mNeedsUpdate && isReadyToUpdate();
 295	
 296	BOOL success = TRUE;
 297	
 298	bool use_shaders = LLGLSLShader::sNoFixedFunction;
 299
 300	if (use_shaders)
 301	{
 302		gAlphaMaskProgram.bind();
 303		gAlphaMaskProgram.setMinimumAlpha(0.004f);
 304	}
 305
 306	LLVertexBuffer::unbind();
 307
 308	// Composite the color data
 309	LLGLSUIDefault gls_ui;
 310	success &= mTexLayerSet->render( mOrigin.mX, mOrigin.mY, mFullWidth, mFullHeight );
 311	gGL.flush();
 312
 313	if(upload_now)
 314	{
 315		if (!success)
 316		{
 317			llinfos << "Failed attempt to bake " << mTexLayerSet->getBodyRegionName() << llendl;
 318			mUploadPending = FALSE;
 319		}
 320		else
 321		{
 322			if (mTexLayerSet->isVisible())
 323			{
 324				mTexLayerSet->getAvatar()->debugBakedTextureUpload(mTexLayerSet->getBakedTexIndex(), FALSE); // FALSE for start of upload, TRUE for finish.
 325				doUpload();
 326			}
 327			else
 328			{
 329				mUploadPending = FALSE;
 330				mNeedsUpload = FALSE;
 331				mNeedsUploadTimer.pause();
 332				mTexLayerSet->getAvatar()->setNewBakedTexture(mTexLayerSet->getBakedTexIndex(),IMG_INVISIBLE);
 333			}
 334		}
 335	}
 336	
 337	if (update_now)
 338	{
 339		doUpdate();
 340	}
 341
 342	if (use_shaders)
 343	{
 344		gAlphaMaskProgram.unbind();
 345	}
 346
 347	LLVertexBuffer::unbind();
 348	
 349	// reset GL state
 350	gGL.setColorMask(true, true);
 351	gGL.setSceneBlendType(LLRender::BT_ALPHA);
 352
 353	// we have valid texture data now
 354	mGLTexturep->setGLTextureCreated(true);
 355
 356	return success;
 357}
 358
 359BOOL LLTexLayerSetBuffer::isInitialized(void) const
 360{
 361	return mGLTexturep.notNull() && mGLTexturep->isGLTextureCreated();
 362}
 363
 364BOOL LLTexLayerSetBuffer::uploadPending() const
 365{
 366	return mUploadPending;
 367}
 368
 369BOOL LLTexLayerSetBuffer::uploadNeeded() const
 370{
 371	return mNeedsUpload;
 372}
 373
 374BOOL LLTexLayerSetBuffer::uploadInProgress() const
 375{
 376	return !mUploadID.isNull();
 377}
 378
 379BOOL LLTexLayerSetBuffer::isReadyToUpload() const
 380{
 381	if (!gAgentQueryManager.hasNoPendingQueries()) return FALSE; // Can't upload if there are pending queries.
 382	if (isAgentAvatarValid() && !gAgentAvatarp->isUsingBakedTextures()) return FALSE; // Don't upload if avatar is using composites.
 383
 384	BOOL ready = FALSE;
 385	if (mTexLayerSet->isLocalTextureDataFinal())
 386	{
 387		// If we requested an upload and have the final LOD ready, upload (or wait a while if this is a retry)
 388		if (mUploadFailCount == 0)
 389		{
 390			ready = TRUE;
 391		}
 392		else
 393		{
 394			ready = mUploadRetryTimer.getElapsedTimeF32() >= BAKE_UPLOAD_RETRY_DELAY * (1 << (mUploadFailCount - 1));
 395		}
 396	}
 397	else
 398	{
 399		// Upload if we've hit a timeout.  Upload is a pretty expensive process so we need to make sure
 400		// we aren't doing uploads too frequently.
 401		const U32 texture_timeout = gSavedSettings.getU32("AvatarBakedTextureUploadTimeout");
 402		if (texture_timeout != 0)
 403		{
 404			// The timeout period increases exponentially between every lowres upload in order to prevent
 405			// spamming the server with frequent uploads.
 406			const U32 texture_timeout_threshold = texture_timeout*(1 << mNumLowresUploads);
 407
 408			// If we hit our timeout and have textures available at even lower resolution, then upload.
 409			const BOOL is_upload_textures_timeout = mNeedsUploadTimer.getElapsedTimeF32() >= texture_timeout_threshold;
 410			const BOOL has_lower_lod = mTexLayerSet->isLocalTextureDataAvailable();
 411			ready = has_lower_lod && is_upload_textures_timeout;
 412		}
 413	}
 414
 415	return ready;
 416}
 417
 418BOOL LLTexLayerSetBuffer::isReadyToUpdate() const
 419{
 420	// If we requested an update and have the final LOD ready, then update.
 421	if (mTexLayerSet->isLocalTextureDataFinal()) return TRUE;
 422
 423	// If we haven't done an update yet, then just do one now regardless of state of textures.
 424	if (mNumLowresUpdates == 0) return TRUE;
 425
 426	// Update if we've hit a timeout.  Unlike for uploads, we can make this timeout fairly small
 427	// since render unnecessarily doesn't cost much.
 428	const U32 texture_timeout = gSavedSettings.getU32("AvatarBakedLocalTextureUpdateTimeout");
 429	if (texture_timeout != 0)
 430	{
 431		// If we hit our timeout and have textures available at even lower resolution, then update.
 432		const BOOL is_update_textures_timeout = mNeedsUpdateTimer.getElapsedTimeF32() >= texture_timeout;
 433		const BOOL has_lower_lod = mTexLayerSet->isLocalTextureDataAvailable();
 434		if (has_lower_lod && is_update_textures_timeout) return TRUE; 
 435	}
 436
 437	return FALSE;
 438}
 439
 440BOOL LLTexLayerSetBuffer::requestUpdateImmediate()
 441{
 442	mNeedsUpdate = TRUE;
 443	BOOL result = FALSE;
 444
 445	if (needsRender())
 446	{
 447		preRender(FALSE);
 448		result = render();
 449		postRender(result);
 450	}
 451
 452	return result;
 453}
 454
 455// Create the baked texture, send it out to the server, then wait for it to come
 456// back so we can switch to using it.
 457void LLTexLayerSetBuffer::doUpload()
 458{
 459	llinfos << "Uploading baked " << mTexLayerSet->getBodyRegionName() << llendl;
 460	LLViewerStats::getInstance()->incStat(LLViewerStats::ST_TEX_BAKES);
 461
 462	// Don't need caches since we're baked now.  (note: we won't *really* be baked 
 463	// until this image is sent to the server and the Avatar Appearance message is received.)
 464	mTexLayerSet->deleteCaches();
 465
 466	// Get the COLOR information from our texture
 467	U8* baked_color_data = new U8[ mFullWidth * mFullHeight * 4 ];
 468	glReadPixels(mOrigin.mX, mOrigin.mY, mFullWidth, mFullHeight, GL_RGBA, GL_UNSIGNED_BYTE, baked_color_data );
 469	stop_glerror();
 470
 471	// Get the MASK information from our texture
 472	LLGLSUIDefault gls_ui;
 473	LLPointer<LLImageRaw> baked_mask_image = new LLImageRaw(mFullWidth, mFullHeight, 1 );
 474	U8* baked_mask_data = baked_mask_image->getData(); 
 475	mTexLayerSet->gatherMorphMaskAlpha(baked_mask_data, mFullWidth, mFullHeight);
 476
 477
 478	// Create the baked image from our color and mask information
 479	const S32 baked_image_components = 5; // red green blue [bump] clothing
 480	LLPointer<LLImageRaw> baked_image = new LLImageRaw( mFullWidth, mFullHeight, baked_image_components );
 481	U8* baked_image_data = baked_image->getData();
 482	S32 i = 0;
 483	for (S32 u=0; u < mFullWidth; u++)
 484	{
 485		for (S32 v=0; v < mFullHeight; v++)
 486		{
 487			baked_image_data[5*i + 0] = baked_color_data[4*i + 0];
 488			baked_image_data[5*i + 1] = baked_color_data[4*i + 1];
 489			baked_image_data[5*i + 2] = baked_color_data[4*i + 2];
 490			baked_image_data[5*i + 3] = baked_color_data[4*i + 3]; // alpha should be correct for eyelashes.
 491			baked_image_data[5*i + 4] = baked_mask_data[i];
 492			i++;
 493		}
 494	}
 495	
 496	LLPointer<LLImageJ2C> compressedImage = new LLImageJ2C;
 497	compressedImage->setRate(0.f);
 498	const char* comment_text = LINDEN_J2C_COMMENT_PREFIX "RGBHM"; // writes into baked_color_data. 5 channels (rgb, heightfield/alpha, mask)
 499	if (compressedImage->encode(baked_image, comment_text))
 500	{
 501		LLTransactionID tid;
 502		tid.generate();
 503		const LLAssetID asset_id = tid.makeAssetID(gAgent.getSecureSessionID());
 504		if (LLVFile::writeFile(compressedImage->getData(), compressedImage->getDataSize(),
 505							   gVFS, asset_id, LLAssetType::AT_TEXTURE))
 506		{
 507			// Read back the file and validate.
 508			BOOL valid = FALSE;
 509			LLPointer<LLImageJ2C> integrity_test = new LLImageJ2C;
 510			S32 file_size = 0;
 511			U8* data = LLVFile::readFile(gVFS, asset_id, LLAssetType::AT_TEXTURE, &file_size);
 512			if (data)
 513			{
 514				valid = integrity_test->validate(data, file_size); // integrity_test will delete 'data'
 515			}
 516			else
 517			{
 518				integrity_test->setLastError("Unable to read entire file");
 519			}
 520			
 521			if (valid)
 522			{
 523				const bool highest_lod = mTexLayerSet->isLocalTextureDataFinal();
 524				// Baked_upload_data is owned by the responder and deleted after the request completes.
 525				LLBakedUploadData* baked_upload_data = new LLBakedUploadData(gAgentAvatarp, 
 526																			 this->mTexLayerSet, 
 527																			 asset_id,
 528																			 highest_lod);
 529				// upload ID is used to avoid overlaps, e.g. when the user rapidly makes two changes outside of Face Edit.
 530				mUploadID = asset_id;
 531
 532				// Upload the image
 533				const std::string url = gAgent.getRegion()->getCapability("UploadBakedTexture");
 534				if(!url.empty()
 535					&& !LLPipeline::sForceOldBakedUpload // toggle debug setting UploadBakedTexOld to change between the new caps method and old method
 536					&& (mUploadFailCount < (BAKE_UPLOAD_ATTEMPTS - 1))) // Try last ditch attempt via asset store if cap upload is failing.
 537				{
 538					LLSD body = LLSD::emptyMap();
 539					// The responder will call LLTexLayerSetBuffer::onTextureUploadComplete()
 540					LLHTTPClient::post(url, body, new LLSendTexLayerResponder(body, mUploadID, LLAssetType::AT_TEXTURE, baked_upload_data));
 541					llinfos << "Baked texture upload via capability of " << mUploadID << " to " << url << llendl;
 542				} 
 543				else
 544				{
 545					gAssetStorage->storeAssetData(tid,
 546												  LLAssetType::AT_TEXTURE,
 547												  LLTexLayerSetBuffer::onTextureUploadComplete,
 548												  baked_upload_data,
 549												  TRUE,		// temp_file
 550												  TRUE,		// is_priority
 551												  TRUE);	// store_local
 552					llinfos << "Baked texture upload via Asset Store." <<  llendl;
 553				}
 554
 555				if (highest_lod)
 556				{
 557					// Sending the final LOD for the baked texture.  All done, pause 
 558					// the upload timer so we know how long it took.
 559					mNeedsUpload = FALSE;
 560					mNeedsUploadTimer.pause();
 561				}
 562				else
 563				{
 564					// Sending a lower level LOD for the baked texture.  Restart the upload timer.
 565					mNumLowresUploads++;
 566					mNeedsUploadTimer.unpause();
 567					mNeedsUploadTimer.reset();
 568				}
 569
 570				// Print out notification that we uploaded this texture.
 571				if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
 572				{
 573					const std::string lod_str = highest_lod ? "HighRes" : "LowRes";
 574					LLSD args;
 575					args["EXISTENCE"] = llformat("%d",(U32)mTexLayerSet->getAvatar()->debugGetExistenceTimeElapsedF32());
 576					args["TIME"] = llformat("%d",(U32)mNeedsUploadTimer.getElapsedTimeF32());
 577					args["BODYREGION"] = mTexLayerSet->getBodyRegionName();
 578					args["RESOLUTION"] = lod_str;
 579					LLNotificationsUtil::add("AvatarRezSelfBakedTextureUploadNotification",args);
 580					llinfos << "Uploading [ name: " << mTexLayerSet->getBodyRegionName() << " res:" << lod_str << " time:" << (U32)mNeedsUploadTimer.getElapsedTimeF32() << " ]" << llendl;
 581				}
 582			}
 583			else
 584			{
 585				// The read back and validate operation failed.  Remove the uploaded file.
 586				mUploadPending = FALSE;
 587				LLVFile file(gVFS, asset_id, LLAssetType::AT_TEXTURE, LLVFile::WRITE);
 588				file.remove();
 589				llinfos << "Unable to create baked upload file (reason: corrupted)." << llendl;
 590			}
 591		}
 592	}
 593	else
 594	{
 595		// The VFS write file operation failed.
 596		mUploadPending = FALSE;
 597		llinfos << "Unable to create baked upload file (reason: failed to write file)" << llendl;
 598	}
 599
 600	delete [] baked_color_data;
 601}
 602
 603// Mostly bookkeeping; don't need to actually "do" anything since
 604// render() will actually do the update.
 605void LLTexLayerSetBuffer::doUpdate()
 606{
 607	const BOOL highest_lod = mTexLayerSet->isLocalTextureDataFinal();
 608	if (highest_lod)
 609	{
 610		mNeedsUpdate = FALSE;
 611	}
 612	else
 613	{
 614		mNumLowresUpdates++;
 615	}
 616
 617	restartUpdateTimer();
 618
 619	// need to swtich to using this layerset if this is the first update
 620	// after getting the lowest LOD
 621	mTexLayerSet->getAvatar()->updateMeshTextures();
 622	
 623	// Print out notification that we uploaded this texture.
 624	if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
 625	{
 626		const BOOL highest_lod = mTexLayerSet->isLocalTextureDataFinal();
 627		const std::string lod_str = highest_lod ? "HighRes" : "LowRes";
 628		LLSD args;
 629		args["EXISTENCE"] = llformat("%d",(U32)mTexLayerSet->getAvatar()->debugGetExistenceTimeElapsedF32());
 630		args["TIME"] = llformat("%d",(U32)mNeedsUpdateTimer.getElapsedTimeF32());
 631		args["BODYREGION"] = mTexLayerSet->getBodyRegionName();
 632		args["RESOLUTION"] = lod_str;
 633		LLNotificationsUtil::add("AvatarRezSelfBakedTextureUpdateNotification",args);
 634		llinfos << "Locally updating [ name: " << mTexLayerSet->getBodyRegionName() << " res:" << lod_str << " time:" << (U32)mNeedsUpdateTimer.getElapsedTimeF32() << " ]" << llendl;
 635	}
 636}
 637
 638// static
 639void LLTexLayerSetBuffer::onTextureUploadComplete(const LLUUID& uuid,
 640												  void* userdata,
 641												  S32 result,
 642												  LLExtStat ext_status) // StoreAssetData callback (not fixed)
 643{
 644	LLBakedUploadData* baked_upload_data = (LLBakedUploadData*)userdata;
 645
 646	if (isAgentAvatarValid() &&
 647		!gAgentAvatarp->isDead() &&
 648		(baked_upload_data->mAvatar == gAgentAvatarp) && // Sanity check: only the user's avatar should be uploading textures.
 649		(baked_upload_data->mTexLayerSet->hasComposite()))
 650	{
 651		LLTexLayerSetBuffer* layerset_buffer = baked_upload_data->mTexLayerSet->getComposite();
 652		S32 failures = layerset_buffer->mUploadFailCount;
 653		layerset_buffer->mUploadFailCount = 0;
 654
 655		if (layerset_buffer->mUploadID.isNull())
 656		{
 657			// The upload got canceled, we should be in the
 658			// process of baking a new texture so request an
 659			// upload with the new data
 660
 661			// BAP: does this really belong in this callback, as
 662			// opposed to where the cancellation takes place?
 663			// suspect this does nothing.
 664			layerset_buffer->requestUpload();
 665		}
 666		else if (baked_upload_data->mID == layerset_buffer->mUploadID)
 667		{
 668			// This is the upload we're currently waiting for.
 669			layerset_buffer->mUploadID.setNull();
 670			const std::string name(baked_upload_data->mTexLayerSet->getBodyRegionName());
 671			const std::string resolution = baked_upload_data->mIsHighestRes ? " full res " : " low res ";
 672			if (result >= 0)
 673			{
 674				layerset_buffer->mUploadPending = FALSE; // Allows sending of AgentSetAppearance later
 675				LLVOAvatarDefines::ETextureIndex baked_te = gAgentAvatarp->getBakedTE(layerset_buffer->mTexLayerSet);
 676				// Update baked texture info with the new UUID
 677				U64 now = LLFrameTimer::getTotalTime();		// Record starting time
 678				llinfos << "Baked" << resolution << "texture upload for " << name << " took " << (S32)((now - baked_upload_data->mStartTime) / 1000) << " ms" << llendl;
 679				gAgentAvatarp->setNewBakedTexture(baked_te, uuid);
 680			}
 681			else
 682			{	
 683				++failures;
 684				S32 max_attempts = baked_upload_data->mIsHighestRes ? BAKE_UPLOAD_ATTEMPTS : 1; // only retry final bakes
 685				llwarns << "Baked" << resolution << "texture upload for " << name << " failed (attempt " << failures << "/" << max_attempts << ")" << llendl;
 686				if (failures < max_attempts)
 687				{
 688					layerset_buffer->mUploadFailCount = failures;
 689					layerset_buffer->mUploadRetryTimer.start();
 690					layerset_buffer->requestUpload();
 691				}
 692			}
 693		}
 694		else
 695		{
 696			llinfos << "Received baked texture out of date, ignored." << llendl;
 697		}
 698
 699		gAgentAvatarp->dirtyMesh();
 700	}
 701	else
 702	{
 703		// Baked texture failed to upload (in which case since we
 704		// didn't set the new baked texture, it means that they'll try
 705		// and rebake it at some point in the future (after login?)),
 706		// or this response to upload is out of date, in which case a
 707		// current response should be on the way or already processed.
 708		llwarns << "Baked upload failed" << llendl;
 709	}
 710
 711	delete baked_upload_data;
 712}
 713
 714//-----------------------------------------------------------------------------
 715// LLTexLayerSet
 716// An ordered set of texture layers that get composited into a single texture.
 717//-----------------------------------------------------------------------------
 718
 719LLTexLayerSetInfo::LLTexLayerSetInfo() :
 720	mBodyRegion( "" ),
 721	mWidth( 512 ),
 722	mHeight( 512 ),
 723	mClearAlpha( TRUE )
 724{
 725}
 726
 727LLTexLayerSetInfo::~LLTexLayerSetInfo( )
 728{
 729	std::for_each(mLayerInfoList.begin(), mLayerInfoList.end(), DeletePointer());
 730}
 731
 732BOOL LLTexLayerSetInfo::parseXml(LLXmlTreeNode* node)
 733{
 734	llassert( node->hasName( "layer_set" ) );
 735	if( !node->hasName( "layer_set" ) )
 736	{
 737		return FALSE;
 738	}
 739
 740	// body_region
 741	static LLStdStringHandle body_region_string = LLXmlTree::addAttributeString("body_region");
 742	if( !node->getFastAttributeString( body_region_string, mBodyRegion ) )
 743	{
 744		llwarns << "<layer_set> is missing body_region attribute" << llendl;
 745		return FALSE;
 746	}
 747
 748	// width, height
 749	static LLStdStringHandle width_string = LLXmlTree::addAttributeString("width");
 750	if( !node->getFastAttributeS32( width_string, mWidth ) )
 751	{
 752		return FALSE;
 753	}
 754
 755	static LLStdStringHandle height_string = LLXmlTree::addAttributeString("height");
 756	if( !node->getFastAttributeS32( height_string, mHeight ) )
 757	{
 758		return FALSE;
 759	}
 760
 761	// Optional alpha component to apply after all compositing is complete.
 762	static LLStdStringHandle alpha_tga_file_string = LLXmlTree::addAttributeString("alpha_tga_file");
 763	node->getFastAttributeString( alpha_tga_file_string, mStaticAlphaFileName );
 764
 765	static LLStdStringHandle clear_alpha_string = LLXmlTree::addAttributeString("clear_alpha");
 766	node->getFastAttributeBOOL( clear_alpha_string, mClearAlpha );
 767
 768	// <layer>
 769	for (LLXmlTreeNode* child = node->getChildByName( "layer" );
 770		 child;
 771		 child = node->getNextNamedChild())
 772	{
 773		LLTexLayerInfo* info = new LLTexLayerInfo();
 774		if( !info->parseXml( child ))
 775		{
 776			delete info;
 777			return FALSE;
 778		}
 779		mLayerInfoList.push_back( info );		
 780	}
 781	return TRUE;
 782}
 783
 784// creates visual params without generating layersets or layers
 785void LLTexLayerSetInfo::createVisualParams(LLVOAvatar *avatar)
 786{
 787	//layer_info_list_t		mLayerInfoList;
 788	for (layer_info_list_t::iterator layer_iter = mLayerInfoList.begin();
 789		 layer_iter != mLayerInfoList.end();
 790		 layer_iter++)
 791	{
 792		LLTexLayerInfo *layer_info = *layer_iter;
 793		layer_info->createVisualParams(avatar);
 794	}
 795}
 796
 797//-----------------------------------------------------------------------------
 798// LLTexLayerSet
 799// An ordered set of texture layers that get composited into a single texture.
 800//-----------------------------------------------------------------------------
 801
 802BOOL LLTexLayerSet::sHasCaches = FALSE;
 803
 804LLTexLayerSet::LLTexLayerSet(LLVOAvatarSelf* const avatar) :
 805	mComposite( NULL ),
 806	mAvatar( avatar ),
 807	mUpdatesEnabled( FALSE ),
 808	mIsVisible( TRUE ),
 809	mBakedTexIndex(LLVOAvatarDefines::BAKED_HEAD),
 810	mInfo( NULL )
 811{
 812}
 813
 814LLTexLayerSet::~LLTexLayerSet()
 815{
 816	deleteCaches();
 817	std::for_each(mLayerList.begin(), mLayerList.end(), DeletePointer());
 818	std::for_each(mMaskLayerList.begin(), mMaskLayerList.end(), DeletePointer());
 819}
 820
 821//-----------------------------------------------------------------------------
 822// setInfo
 823//-----------------------------------------------------------------------------
 824
 825BOOL LLTexLayerSet::setInfo(const LLTexLayerSetInfo *info)
 826{
 827	llassert(mInfo == NULL);
 828	mInfo = info;
 829	//mID = info->mID; // No ID
 830
 831	mLayerList.reserve(info->mLayerInfoList.size());
 832	for (LLTexLayerSetInfo::layer_info_list_t::const_iterator iter = info->mLayerInfoList.begin(); 
 833		 iter != info->mLayerInfoList.end(); 
 834		 iter++)
 835	{
 836		LLTexLayerInterface *layer = NULL;
 837		if ( (*iter)->isUserSettable() )
 838		{
 839			layer = new LLTexLayerTemplate( this );
 840		}
 841		else
 842		{
 843			layer = new LLTexLayer(this);
 844		}
 845		// this is the first time this layer (of either type) is being created - make sure you add the parameters to the avatar
 846		if (!layer->setInfo(*iter, NULL))
 847		{
 848			mInfo = NULL;
 849			return FALSE;
 850		}
 851		if (!layer->isVisibilityMask())
 852		{
 853			mLayerList.push_back( layer );
 854		}
 855		else
 856		{
 857			mMaskLayerList.push_back(layer);
 858		}
 859	}
 860
 861	requestUpdate();
 862
 863	stop_glerror();
 864
 865	return TRUE;
 866}
 867
 868#if 0 // obsolete
 869//-----------------------------------------------------------------------------
 870// parseData
 871//-----------------------------------------------------------------------------
 872
 873BOOL LLTexLayerSet::parseData(LLXmlTreeNode* node)
 874{
 875	LLTexLayerSetInfo *info = new LLTexLayerSetInfo;
 876
 877	if (!info->parseXml(node))
 878	{
 879		delete info;
 880		return FALSE;
 881	}
 882	if (!setInfo(info))
 883	{
 884		delete info;
 885		return FALSE;
 886	}
 887	return TRUE;
 888}
 889#endif
 890
 891void LLTexLayerSet::deleteCaches()
 892{
 893	for( layer_list_t::iterator iter = mLayerList.begin(); iter != mLayerList.end(); iter++ )
 894	{
 895		LLTexLayerInterface* layer = *iter;
 896		layer->deleteCaches();
 897	}
 898	for (layer_list_t::iterator iter = mMaskLayerList.begin(); iter != mMaskLayerList.end(); iter++)
 899	{
 900		LLTexLayerInterface* layer = *iter;
 901		layer->deleteCaches();
 902	}
 903}
 904
 905// Returns TRUE if at least one packet of data has been received for each of the textures that this layerset depends on.
 906BOOL LLTexLayerSet::isLocalTextureDataAvailable() const
 907{
 908	if (!mAvatar->isSelf()) return FALSE;
 909	return ((LLVOAvatarSelf *)mAvatar)->isLocalTextureDataAvailable(this);
 910}
 911
 912
 913// Returns TRUE if all of the data for the textures that this layerset depends on have arrived.
 914BOOL LLTexLayerSet::isLocalTextureDataFinal() const
 915{
 916	if (!mAvatar->isSelf()) return FALSE;
 917	return ((LLVOAvatarSelf *)mAvatar)->isLocalTextureDataFinal(this);
 918}
 919
 920
 921BOOL LLTexLayerSet::render( S32 x, S32 y, S32 width, S32 height )
 922{
 923	BOOL success = TRUE;
 924	mIsVisible = TRUE;
 925
 926	if (mMaskLayerList.size() > 0)
 927	{
 928		for (layer_list_t::iterator iter = mMaskLayerList.begin(); iter != mMaskLayerList.end(); iter++)
 929		{
 930			LLTexLayerInterface* layer = *iter;
 931			if (layer->isInvisibleAlphaMask())
 932			{
 933				mIsVisible = FALSE;
 934			}
 935		}
 936	}
 937
 938	bool use_shaders = LLGLSLShader::sNoFixedFunction;
 939
 940	LLGLSUIDefault gls_ui;
 941	LLGLDepthTest gls_depth(GL_FALSE, GL_FALSE);
 942	gGL.setColorMask(true, true);
 943
 944	// clear buffer area to ensure we don't pick up UI elements
 945	{
 946		gGL.flush();
 947		LLGLDisable no_alpha(GL_ALPHA_TEST);
 948		if (use_shaders)
 949		{
 950			gAlphaMaskProgram.setMinimumAlpha(0.0f);
 951		}
 952		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
 953		gGL.color4f( 0.f, 0.f, 0.f, 1.f );
 954
 955		gl_rect_2d_simple( width, height );
 956
 957		gGL.flush();
 958		if (use_shaders)
 959		{
 960			gAlphaMaskProgram.setMinimumAlpha(0.004f);
 961		}
 962	}
 963
 964	if (mIsVisible)
 965	{
 966		// composite color layers
 967		for( layer_list_t::iterator iter = mLayerList.begin(); iter != mLayerList.end(); iter++ )
 968		{
 969			LLTexLayerInterface* layer = *iter;
 970			if (layer->getRenderPass() == LLTexLayer::RP_COLOR)
 971			{
 972				gGL.flush();
 973				success &= layer->render(x, y, width, height);
 974				gGL.flush();
 975			}
 976		}
 977		
 978		renderAlphaMaskTextures(x, y, width, height, false);
 979	
 980		stop_glerror();
 981	}
 982	else
 983	{
 984		gGL.flush();
 985
 986		gGL.setSceneBlendType(LLRender::BT_REPLACE);
 987		LLGLDisable no_alpha(GL_ALPHA_TEST);
 988		if (use_shaders)
 989		{
 990			gAlphaMaskProgram.setMinimumAlpha(0.f);
 991		}
 992
 993		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
 994		gGL.color4f( 0.f, 0.f, 0.f, 0.f );
 995
 996		gl_rect_2d_simple( width, height );
 997		gGL.setSceneBlendType(LLRender::BT_ALPHA);
 998
 999		gGL.flush();
1000		if (use_shaders)
1001		{
1002			gAlphaMaskProgram.setMinimumAlpha(0.004f);
1003		}
1004	}
1005
1006	return success;
1007}
1008
1009
1010BOOL LLTexLayerSet::isBodyRegion(const std::string& region) const 
1011{ 
1012	return mInfo->mBodyRegion == region; 
1013}
1014
1015const std::string LLTexLayerSet::getBodyRegionName() const 
1016{ 
1017	return mInfo->mBodyRegion; 
1018}
1019
1020void LLTexLayerSet::requestUpdate()
1021{
1022	if( mUpdatesEnabled )
1023	{
1024		createComposite();
1025		mComposite->requestUpdate(); 
1026	}
1027}
1028
1029void LLTexLayerSet::requestUpload()
1030{
1031	createComposite();
1032	mComposite->requestUpload();
1033}
1034
1035void LLTexLayerSet::cancelUpload()
1036{
1037	if(mComposite)
1038	{
1039		mComposite->cancelUpload();
1040	}
1041}
1042
1043void LLTexLayerSet::createComposite()
1044{
1045	if(!mComposite)
1046	{
1047		S32 width = mInfo->mWidth;
1048		S32 height = mInfo->mHeight;
1049		// Composite other avatars at reduced resolution
1050		if( !mAvatar->isSelf() )
1051		{
1052			llerrs << "composites should not be created for non-self avatars!" << llendl;
1053		}
1054		mComposite = new LLTexLayerSetBuffer( this, width, height );
1055	}
1056}
1057
1058void LLTexLayerSet::destroyComposite()
1059{
1060	if( mComposite )
1061	{
1062		mComposite = NULL;
1063	}
1064}
1065
1066void LLTexLayerSet::setUpdatesEnabled( BOOL b )
1067{
1068	mUpdatesEnabled = b; 
1069}
1070
1071
1072void LLTexLayerSet::updateComposite()
1073{
1074	createComposite();
1075	mComposite->requestUpdateImmediate();
1076}
1077
1078LLTexLayerSetBuffer* LLTexLayerSet::getComposite()
1079{
1080	if (!mComposite)
1081	{
1082		createComposite();
1083	}
1084	return mComposite;
1085}
1086
1087const LLTexLayerSetBuffer* LLTexLayerSet::getComposite() const
1088{
1089	return mComposite;
1090}
1091
1092void LLTexLayerSet::gatherMorphMaskAlpha(U8 *data, S32 width, S32 height)
1093{
1094	memset(data, 255, width * height);
1095
1096	for( layer_list_t::iterator iter = mLayerList.begin(); iter != mLayerList.end(); iter++ )
1097	{
1098		LLTexLayerInterface* layer = *iter;
1099		layer->gatherAlphaMasks(data, mComposite->getOriginX(),mComposite->getOriginY(), width, height);
1100	}
1101	
1102	// Set alpha back to that of our alpha masks.
1103	renderAlphaMaskTextures(mComposite->getOriginX(), mComposite->getOriginY(), width, height, true);
1104}
1105
1106void LLTexLayerSet::renderAlphaMaskTextures(S32 x, S32 y, S32 width, S32 height, bool forceClear)
1107{
1108	const LLTexLayerSetInfo *info = getInfo();
1109	
1110	bool use_shaders = LLGLSLShader::sNoFixedFunction;
1111
1112	gGL.setColorMask(false, true);
1113	gGL.setSceneBlendType(LLRender::BT_REPLACE);
1114	
1115	// (Optionally) replace alpha with a single component image from a tga file.
1116	if (!info->mStaticAlphaFileName.empty())
1117	{
1118		gGL.flush();
1119		{
1120			LLViewerTexture* tex = LLTexLayerStaticImageList::getInstance()->getTexture(info->mStaticAlphaFileName, TRUE);
1121			if( tex )
1122			{
1123				LLGLSUIDefault gls_ui;
1124				gGL.getTexUnit(0)->bind(tex);
1125				gGL.getTexUnit(0)->setTextureBlendType( LLTexUnit::TB_REPLACE );
1126				gl_rect_2d_simple_tex( width, height );
1127			}
1128		}
1129		gGL.flush();
1130	}
1131	else if (forceClear || info->mClearAlpha || (mMaskLayerList.size() > 0))
1132	{
1133		// Set the alpha channel to one (clean up after previous blending)
1134		gGL.flush();
1135		LLGLDisable no_alpha(GL_ALPHA_TEST);
1136		if (use_shaders)
1137		{
1138			gAlphaMaskProgram.setMinimumAlpha(0.f);
1139		}
1140		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
1141		gGL.color4f( 0.f, 0.f, 0.f, 1.f );
1142		
1143		gl_rect_2d_simple( width, height );
1144		
1145		gGL.flush();
1146		if (use_shaders)
1147		{
1148			gAlphaMaskProgram.setMinimumAlpha(0.004f);
1149		}
1150	}
1151	
1152	// (Optional) Mask out part of the baked texture with alpha masks
1153	// will still have an effect even if mClearAlpha is set or the alpha component was replaced
1154	if (mMaskLayerList.size() > 0)
1155	{
1156		gGL.setSceneBlendType(LLRender::BT_MULT_ALPHA);
1157		gGL.getTexUnit(0)->setTextureBlendType( LLTexUnit::TB_REPLACE );
1158		for (layer_list_t::iterator iter = mMaskLayerList.begin(); iter != mMaskLayerList.end(); iter++)
1159		{
1160			LLTexLayerInterface* layer = *iter;
1161			gGL.flush();
1162			layer->blendAlphaTexture(x,y,width, height);
1163			gGL.flush();
1164		}
1165		
1166	}
1167	
1168	gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
1169	
1170	gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
1171	gGL.setColorMask(true, true);
1172	gGL.setSceneBlendType(LLRender::BT_ALPHA);
1173}
1174
1175void LLTexLayerSet::applyMorphMask(U8* tex_data, S32 width, S32 height, S32 num_components)
1176{
1177	mAvatar->applyMorphMask(tex_data, width, height, num_components, mBakedTexIndex);
1178}
1179
1180BOOL LLTexLayerSet::isMorphValid() const
1181{
1182	for(layer_list_t::const_iterator iter = mLayerList.begin(); iter != mLayerList.end(); iter++ )
1183	{
1184		const LLTexLayerInterface* layer = *iter;
1185		if (layer && !layer->isMorphValid())
1186		{
1187			return FALSE;
1188		}
1189	}
1190	return TRUE;
1191}
1192
1193void LLTexLayerSet::invalidateMorphMasks()
1194{
1195	for( layer_list_t::iterator iter = mLayerList.begin(); iter != mLayerList.end(); iter++ )
1196	{
1197		LLTexLayerInterface* layer = *iter;
1198		if (layer)
1199		{
1200			layer->invalidateMorphMasks();
1201		}
1202	}
1203}
1204
1205
1206//-----------------------------------------------------------------------------
1207// LLTexLayerInfo
1208//-----------------------------------------------------------------------------
1209LLTexLayerInfo::LLTexLayerInfo() :
1210	mWriteAllChannels( FALSE ),
1211	mRenderPass(LLTexLayer::RP_COLOR),
1212	mFixedColor( 0.f, 0.f, 0.f, 0.f ),
1213	mLocalTexture( -1 ),
1214	mStaticImageIsMask( FALSE ),
1215	mUseLocalTextureAlphaOnly(FALSE),
1216	mIsVisibilityMask(FALSE)
1217{
1218}
1219
1220LLTexLayerInfo::~LLTexLayerInfo( )
1221{
1222	std::for_each(mParamColorInfoList.begin(), mParamColorInfoList.end(), DeletePointer());
1223	std::for_each(mParamAlphaInfoList.begin(), mParamAlphaInfoList.end(), DeletePointer());
1224}
1225
1226BOOL LLTexLayerInfo::parseXml(LLXmlTreeNode* node)
1227{
1228	llassert( node->hasName( "layer" ) );
1229
1230	// name attribute
1231	static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
1232	if( !node->getFastAttributeString( name_string, mName ) )
1233	{
1234		return FALSE;
1235	}
1236	
1237	static LLStdStringHandle write_all_channels_string = LLXmlTree::addAttributeString("write_all_channels");
1238	node->getFastAttributeBOOL( write_all_channels_string, mWriteAllChannels );
1239
1240	std::string render_pass_name;
1241	static LLStdStringHandle render_pass_string = LLXmlTree::addAttributeString("render_pass");
1242	if( node->getFastAttributeString( render_pass_string, render_pass_name ) )
1243	{
1244		if( render_pass_name == "bump" )
1245		{
1246			mRenderPass = LLTexLayer::RP_BUMP;
1247		}
1248	}
1249
1250	// Note: layers can have either a "global_color" attrib, a "fixed_color" attrib, or a <param_color> child.
1251	// global color attribute (optional)
1252	static LLStdStringHandle global_color_string = LLXmlTree::addAttributeString("global_color");
1253	node->getFastAttributeString( global_color_string, mGlobalColor );
1254
1255	// Visibility mask (optional)
1256	BOOL is_visibility;
1257	static LLStdStringHandle visibility_mask_string = LLXmlTree::addAttributeString("visibility_mask");
1258	if (node->getFastAttributeBOOL(visibility_mask_string, is_visibility))
1259	{
1260		mIsVisibilityMask = is_visibility;
1261	}
1262
1263	// color attribute (optional)
1264	LLColor4U color4u;
1265	static LLStdStringHandle fixed_color_string = LLXmlTree::addAttributeString("fixed_color");
1266	if( node->getFastAttributeColor4U( fixed_color_string, color4u ) )
1267	{
1268		mFixedColor.setVec( color4u );
1269	}
1270
1271		// <texture> optional sub-element
1272	for (LLXmlTreeNode* texture_node = node->getChildByName( "texture" );
1273		 texture_node;
1274		 texture_node = node->getNextNamedChild())
1275	{
1276		std::string local_texture_name;
1277		static LLStdStringHandle tga_file_string = LLXmlTree::addAttributeString("tga_file");
1278		static LLStdStringHandle local_texture_string = LLXmlTree::addAttributeString("local_texture");
1279		static LLStdStringHandle file_is_mask_string = LLXmlTree::addAttributeString("file_is_mask");
1280		static LLStdStringHandle local_texture_alpha_only_string = LLXmlTree::addAttributeString("local_texture_alpha_only");
1281		if( texture_node->getFastAttributeString( tga_file_string, mStaticImageFileName ) )
1282		{
1283			texture_node->getFastAttributeBOOL( file_is_mask_string, mStaticImageIsMask );
1284		}
1285		else if (texture_node->getFastAttributeString(local_texture_string, local_texture_name))
1286		{
1287			texture_node->getFastAttributeBOOL( local_texture_alpha_only_string, mUseLocalTextureAlphaOnly );
1288
1289			/* if ("upper_shirt" == local_texture_name)
1290				mLocalTexture = TEX_UPPER_SHIRT; */
1291			mLocalTexture = TEX_NUM_INDICES;
1292			for (LLVOAvatarDictionary::Textures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
1293				 iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
1294				 iter++)
1295			{
1296				const LLVOAvatarDictionary::TextureEntry *texture_dict = iter->second;
1297				if (local_texture_name == texture_dict->mName)
1298			{
1299					mLocalTexture = iter->first;
1300					break;
1301			}
1302			}
1303			if (mLocalTexture == TEX_NUM_INDICES)
1304			{
1305				llwarns << "<texture> element has invalid local_texture attribute: " << mName << " " << local_texture_name << llendl;
1306				return FALSE;
1307			}
1308		}
1309		else	
1310		{
1311			llwarns << "<texture> element is missing a required attribute. " << mName << llendl;
1312			return FALSE;
1313		}
1314	}
1315
1316	for (LLXmlTreeNode* maskNode = node->getChildByName( "morph_mask" );
1317		 maskNode;
1318		 maskNode = node->getNextNamedChild())
1319	{
1320		std::string morph_name;
1321		static LLStdStringHandle morph_name_string = LLXmlTree::addAttributeString("morph_name");
1322		if (maskNode->getFastAttributeString(morph_name_string, morph_name))
1323		{
1324			BOOL invert = FALSE;
1325			static LLStdStringHandle invert_string = LLXmlTree::addAttributeString("invert");
1326			maskNode->getFastAttributeBOOL(invert_string, invert);			
1327			mMorphNameList.push_back(std::pair<std::string,BOOL>(morph_name,invert));
1328		}
1329	}
1330
1331	// <param> optional sub-element (color or alpha params)
1332	for (LLXmlTreeNode* child = node->getChildByName( "param" );
1333		 child;
1334		 child = node->getNextNamedChild())
1335	{
1336		if( child->getChildByName( "param_color" ) )
1337		{
1338			// <param><param_color/></param>
1339			LLTexLayerParamColorInfo* info = new LLTexLayerParamColorInfo();
1340			if (!info->parseXml(child))
1341			{
1342				delete info;
1343				return FALSE;
1344			}
1345			mParamColorInfoList.push_back(info);
1346		}
1347		else if( child->getChildByName( "param_alpha" ) )
1348		{
1349			// <param><param_alpha/></param>
1350			LLTexLayerParamAlphaInfo* info = new LLTexLayerParamAlphaInfo( );
1351			if (!info->parseXml(child))
1352			{
1353				delete info;
1354				return FALSE;
1355			}
1356 			mParamAlphaInfoList.push_back(info);
1357		}
1358	}
1359	
1360	return TRUE;
1361}
1362
1363BOOL LLTexLayerInfo::createVisualParams(LLVOAvatar *avatar)
1364{
1365	BOOL success = TRUE;
1366	for (param_color_info_list_t::iterator color_info_iter = mParamColorInfoList.begin();
1367		 color_info_iter != mParamColorInfoList.end();
1368		 color_info_iter++)
1369	{
1370		LLTexLayerParamColorInfo * color_info = *color_info_iter;
1371		LLTexLayerParamColor* param_color = new LLTexLayerParamColor(avatar);
1372		if (!param_color->setInfo(color_info, TRUE))
1373		{
1374			llwarns << "NULL TexLayer Color Param could not be added to visual param list. Deleting." << llendl;
1375			delete param_color;
1376			success = FALSE;
1377		}
1378	}
1379
1380	for (param_alpha_info_list_t::iterator alpha_info_iter = mParamAlphaInfoList.begin();
1381		 alpha_info_iter != mParamAlphaInfoList.end();
1382		 alpha_info_iter++)
1383	{
1384		LLTexLayerParamAlphaInfo * alpha_info = *alpha_info_iter;
1385		LLTexLayerParamAlpha* param_alpha = new LLTexLayerParamAlpha(avatar);
1386		if (!param_alpha->setInfo(alpha_info, TRUE))
1387		{
1388			llwarns << "NULL TexLayer Alpha Param could not be added to visual param list. Deleting." << llendl;
1389			delete param_alpha;
1390			success = FALSE;
1391		}
1392	}
1393
1394	return success;
1395}
1396
1397LLTexLayerInterface::LLTexLayerInterface(LLTexLayerSet* const layer_set):
1398	mTexLayerSet( layer_set ),
1399	mMorphMasksValid( FALSE ),
1400	mInfo(NULL),
1401	mHasMorph(FALSE)
1402{
1403}
1404
1405LLTexLayerInterface::LLTexLayerInterface(const LLTexLayerInterface &layer, LLWearable *wearable):
1406	mTexLayerSet( layer.mTexLayerSet ),
1407	mInfo(NULL)
1408{
1409	// don't add visual params for cloned layers
1410	setInfo(layer.getInfo(), wearable);
1411
1412	mHasMorph = layer.mHasMorph;
1413}
1414
1415BOOL LLTexLayerInterface::setInfo(const LLTexLayerInfo *info, LLWearable* wearable  ) // This sets mInfo and calls initialization functions
1416{
1417	// setInfo should only be called once. Code is not robust enough to handle redefinition of a texlayer.
1418	// Not a critical warning, but could be useful for debugging later issues. -Nyx
1419	if (mInfo != NULL) 
1420	{
1421			llwarns << "mInfo != NULL" << llendl;
1422	}
1423	mInfo = info;
1424	//mID = info->mID; // No ID
1425
1426	mParamColorList.reserve(mInfo->mParamColorInfoList.size());
1427	for (param_color_info_list_t::const_iterator iter = mInfo->mParamColorInfoList.begin(); 
1428		 iter != mInfo->mParamColorInfoList.end(); 
1429		 iter++)
1430	{
1431		LLTexLayerParamColor* param_color;
1432		if (!wearable)
1433			{
1434				param_color = new LLTexLayerParamColor(this);
1435				if (!param_color->setInfo(*iter, TRUE))
1436				{
1437					mInfo = NULL;
1438					return FALSE;
1439				}
1440			}
1441			else
1442			{
1443				param_color = (LLTexLayerParamColor*)wearable->getVisualParam((*iter)->getID());
1444				if (!param_color)
1445				{
1446					mInfo = NULL;
1447					return FALSE;
1448				}
1449			}
1450			mParamColorList.push_back( param_color );
1451		}
1452
1453	mParamAlphaList.reserve(mInfo->mParamAlphaInfoList.size());
1454	for (param_alpha_info_list_t::const_iterator iter = mInfo->mParamAlphaInfoList.begin(); 
1455		 iter != mInfo->mParamAlphaInfoList.end(); 
1456		 iter++)
1457		{
1458			LLTexLayerParamAlpha* param_alpha;
1459			if (!wearable)
1460			{
1461				param_alpha = new LLTexLayerParamAlpha( this );
1462				if (!param_alpha->setInfo(*iter, TRUE))
1463				{
1464					mInfo = NULL;
1465					return FALSE;
1466				}
1467			}
1468			else
1469			{
1470				param_alpha = (LLTexLayerParamAlpha*) wearable->getVisualParam((*iter)->getID());
1471				if (!param_alpha)
1472				{
1473					mInfo = NULL;
1474					return FALSE;
1475				}
1476			}
1477			mParamAlphaList.push_back( param_alpha );
1478		}
1479
1480	return TRUE;
1481}
1482
1483/*virtual*/ void LLTexLayerInterface::requestUpdate()
1484{
1485	mTexLayerSet->requestUpdate();
1486}
1487
1488const std::string& LLTexLayerInterface::getName() const
1489{
1490	return mInfo->mName; 
1491}
1492
1493LLTexLayerInterface::ERenderPass LLTexLayerInterface::getRenderPass() const
1494{
1495	return mInfo->mRenderPass; 
1496}
1497
1498const std::string& LLTexLayerInterface::getGlobalColor() const
1499{
1500	return mInfo->mGlobalColor; 
1501}
1502
1503BOOL LLTexLayerInterface::isVisibilityMask() const
1504{
1505	return mInfo->mIsVisibilityMask;
1506}
1507
1508void LLTexLayerInterface::invalidateMorphMasks()
1509{
1510	mMorphMasksValid = FALSE;
1511}
1512
1513LLViewerVisualParam* LLTexLayerInterface::getVisualParamPtr(S32 index) const
1514{
1515	LLViewerVisualParam *result = NULL;
1516	for (param_color_list_t::const_iterator color_iter = mParamColorList.begin(); color_iter != mParamColorList.end() && !result; ++color_iter)
1517	{
1518		if ((*color_iter)->getID() == index)
1519		{
1520			result = *color_iter;
1521		}
1522	}
1523	for (param_alpha_list_t::const_iterator alpha_iter = mParamAlphaList.begin(); alpha_iter != mParamAlphaList.end() && !result; ++alpha_iter)
1524	{
1525		if ((*alpha_iter)->getID() == index)
1526		{
1527			result = *alpha_iter;
1528		}
1529	}
1530
1531	return result;
1532}
1533
1534//-----------------------------------------------------------------------------
1535// LLTexLayer
1536// A single texture layer, consisting of:
1537//		* color, consisting of either
1538//			* one or more color parameters (weighted colors)
1539//			* a reference to a global color
1540//			* a fixed color with non-zero alpha
1541//			* opaque white (the default)
1542//		* (optional) a texture defined by either
1543//			* a GUID
1544//			* a texture entry index (TE)
1545//		* (optional) one or more alpha parameters (weighted alpha textures)
1546//-----------------------------------------------------------------------------
1547LLTexLayer::LLTexLayer(LLTexLayerSet* const layer_set) :
1548	LLTexLayerInterface( layer_set ),
1549	mLocalTextureObject(NULL)
1550{
1551}
1552
1553LLTexLayer::LLTexLayer(const LLTexLayer &layer, LLWearable *wearable) :
1554	LLTexLayerInterface( layer, wearable ),
1555	mLocalTextureObject(NULL)
1556{
1557}
1558
1559LLTexLayer::LLTexLayer(const LLTexLayerTemplate &layer_template, LLLocalTextureObject *lto, LLWearable *wearable) :
1560	LLTexLayerInterface( layer_template, wearable ),
1561	mLocalTextureObject(lto)
1562{
1563}
1564
1565LLTexLayer::~LLTexLayer()
1566{
1567	// mParamAlphaList and mParamColorList are LLViewerVisualParam's and get
1568	// deleted with ~LLCharacter()
1569	//std::for_each(mParamAlphaList.begin(), mParamAlphaList.end(), DeletePointer());
1570	//std::for_each(mParamColorList.begin(), mParamColorList.end(), DeletePointer());
1571	
1572	for( alpha_cache_t::iterator iter = mAlphaCache.begin();
1573		 iter != mAlphaCache.end(); iter++ )
1574	{
1575		U8* alpha_data = iter->second;
1576		delete [] alpha_data;
1577	}
1578
1579}
1580
1581//-----------------------------------------------------------------------------
1582// setInfo
1583//-----------------------------------------------------------------------------
1584
1585BOOL LLTexLayer::setInfo(const LLTexLayerInfo* info, LLWearable* wearable  )
1586{
1587	return LLTexLayerInterface::setInfo(info, wearable);
1588}
1589
1590//static 
1591void LLTexLayer::calculateTexLayerColor(const param_color_list_t &param_list, LLColor4 &net_color)
1592{
1593	for (param_color_list_t::const_iterator iter = param_list.begin();
1594		 iter != param_list.end(); iter++)
1595	{
1596		const LLTexLayerParamColor* param = *iter;
1597		LLColor4 param_net = param->getNetColor();
1598		const LLTexLayerParamColorInfo *info = (LLTexLayerParamColorInfo *)param->getInfo();
1599		switch(info->getOperation())
1600		{
1601			case LLTexLayerParamColor::OP_ADD:
1602				net_color += param_net;
1603				break;
1604			case LLTexLayerParamColor::OP_MULTIPLY:
1605				net_color = net_color * param_net;
1606				break;
1607			case LLTexLayerParamColor::OP_BLEND:
1608				net_color = lerp(net_color, param_net, param->getWeight());
1609				break;
1610			default:
1611				llassert(0);
1612				break;
1613		}
1614	}
1615	net_color.clamp();
1616}
1617
1618/*virtual*/ void LLTexLayer::deleteCaches()
1619{
1620	// Only need to delete caches for alpha params. Color params don't hold extra memory
1621	for (param_alpha_list_t::iterator iter = mParamAlphaList.begin();
1622		 iter != mParamAlphaList.end(); iter++ )
1623	{
1624		LLTexLayerParamAlpha* param = *iter;
1625		param->deleteCaches();
1626	}
1627}
1628
1629BOOL LLTexLayer::render(S32 x, S32 y, S32 width, S32 height)
1630{
1631	LLGLEnable color_mat(GL_COLOR_MATERIAL);
1632	gPipeline.disableLights();
1633
1634	bool use_shaders = LLGLSLShader::sNoFixedFunction;
1635
1636	LLColor4 net_color;
1637	BOOL color_specified = findNetColor(&net_color);
1638	
1639	if (mTexLayerSet->getAvatar()->mIsDummy)
1640	{
1641		color_specified = true;
1642		net_color = LLVOAvatar::getDummyColor();
1643	}
1644
1645	BOOL success = TRUE;
1646	
1647	// If you can't see the layer, don't render it.
1648	if( is_approx_zero( net_color.mV[VW] ) )
1649	{
1650		return success;
1651	}
1652
1653	BOOL alpha_mask_specified = FALSE;
1654	param_alpha_list_t::const_iterator iter = mParamAlphaList.begin();
1655	if( iter != mParamAlphaList.end() )
1656	{
1657		// If we have alpha masks, but we're skipping all of them, skip the whole layer.
1658		// However, we can't do this optimization if we have morph masks that need updating.
1659/*		if (!mHasMorph)
1660		{
1661			BOOL skip_layer = TRUE;
1662
1663			while( iter != mParamAlphaList.end() )
1664			{
1665				const LLTexLayerParamAlpha* param = *iter;
1666		
1667				if( !param->getSkip() )
1668				{
1669					skip_layer = FALSE;
1670					break;
1671				}
1672
1673				iter++;
1674			} 
1675
1676			if( skip_layer )
1677			{
1678				return success;
1679			}
1680		}//*/
1681
1682		renderMorphMasks(x, y, width, height, net_color);
1683		alpha_mask_specified = TRUE;
1684		gGL.flush();
1685		gGL.blendFunc(LLRender::BF_DEST_ALPHA, LLRender::BF_ONE_MINUS_DEST_ALPHA);
1686	}
1687
1688	gGL.color4fv( net_color.mV);
1689
1690	if( getInfo()->mWriteAllChannels )
1691	{
1692		gGL.flush();
1693		gGL.setSceneBlendType(LLRender::BT_REPLACE);
1694	}
1695
1696	if( (getInfo()->mLocalTexture != -1) && !getInfo()->mUseLocalTextureAlphaOnly )
1697	{
1698		{
1699			LLViewerTexture* tex = NULL;
1700			if (mLocalTextureObject && mLocalTextureObject->getImage())
1701			{
1702				tex = mLocalTextureObject->getImage();
1703				if (mLocalTextureObject->getID() == IMG_DEFAULT_AVATAR)
1704				{
1705					tex = NULL;
1706				}
1707			}
1708			else
1709			{
1710				llinfos << "lto not defined or image not defined: " << getInfo()->getLocalTexture() << " lto: " << mLocalTextureObject << llendl;
1711			}
1712//			if( mTexLayerSet->getAvatar()->getLocalTextureGL((ETextureIndex)getInfo()->mLocalTexture, &image_gl ) )
1713			{
1714				if( tex )
1715				{
1716					bool no_alpha_test = getInfo()->mWriteAllChannels;
1717					LLGLDisable alpha_test(no_alpha_test ? GL_ALPHA_TEST : 0);
1718					if (use_shaders && no_alpha_test)
1719					{
1720						gAlphaMaskProgram.setMinimumAlpha(0.f);
1721					}
1722					
1723					LLTexUnit::eTextureAddressMode old_mode = tex->getAddressMode();
1724					
1725					gGL.getTexUnit(0)->bind(tex, TRUE);
1726					gGL.getTexUnit(0)->setTextureAddressMode(LLTexUnit::TAM_CLAMP);
1727
1728					gl_rect_2d_simple_tex( width, height );
1729
1730					gGL.getTexUnit(0)->setTextureAddressMode(o

Large files files are truncated, but you can click here to view the full file