summaryrefslogtreecommitdiff
path: root/indra/newview
diff options
context:
space:
mode:
Diffstat (limited to 'indra/newview')
-rw-r--r--indra/newview/CMakeLists.txt55
-rw-r--r--indra/newview/English.lproj/InfoPlist.strings4
-rw-r--r--indra/newview/Info-SecondLife.plist2
-rw-r--r--indra/newview/app_settings/high_graphics.xml2
-rw-r--r--indra/newview/app_settings/low_graphics.xml2
-rw-r--r--indra/newview/app_settings/mid_graphics.xml2
-rwxr-xr-x[-rw-r--r--]indra/newview/app_settings/settings.xml522
-rw-r--r--indra/newview/app_settings/settings_crash_behavior.xml2
-rw-r--r--indra/newview/app_settings/shaders/class1/avatar/avatarF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/avatar/avatarSkinV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/avatar/avatarV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/avatar/eyeballF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/avatar/eyeballV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/avatar/objectSkinV.glsl30
-rw-r--r--indra/newview/app_settings/shaders/class1/avatar/pickAvatarF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/avatar/pickAvatarV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/alphaF.glsl4
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/alphaSkinnedV.glsl83
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/alphaV.glsl4
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/attachmentShadowF.glsl18
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/attachmentShadowV.glsl27
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/avatarAlphaF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/avatarAlphaV.glsl16
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/avatarF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/avatarShadowF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/avatarShadowV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/avatarV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/blurLightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/blurLightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/bumpF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/bumpSkinnedV.glsl37
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/bumpV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/diffuseF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/diffuseSkinnedV.glsl33
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/diffuseV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/fullbrightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/fullbrightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/giF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/giV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/impostorF.glsl4
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/impostorV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/luminanceF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/luminanceV.glsl3
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/multiPointLightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/pointLightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/pointLightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/postDeferredF.glsl134
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/postDeferredV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/postgiF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/postgiV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/shadowF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/shadowV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/softenLightF.glsl12
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/softenLightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/sunLightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/sunLightSSAOF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/sunLightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/terrainF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/terrainV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/treeF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/treeV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/waterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/deferred/waterV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/effects/glowExtractF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/effects/glowExtractV.glsl1
-rw-r--r--indra/newview/app_settings/shaders/class1/effects/glowF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/effects/glowV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/environment/terrainF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/environment/terrainV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/environment/terrainWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/environment/underWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/environment/waterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/environment/waterFogF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/environment/waterV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/interface/highlightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/interface/highlightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightFullbrightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightFullbrightShinyF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightFullbrightShinyWaterF.glsl17
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightFullbrightWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightFuncSpecularV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightFuncV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightShinyF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightShinyWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightSpecularV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/lightWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/sumLightsSpecularV.glsl3
-rw-r--r--indra/newview/app_settings/shaders/class1/lighting/sumLightsV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/fullbrightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/fullbrightShinyF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/fullbrightShinySkinnedV.glsl39
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/fullbrightShinyV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/fullbrightShinyWaterF.glsl15
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/fullbrightSkinnedV.glsl37
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/fullbrightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/fullbrightWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/shinyF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/shinySimpleSkinnedV.glsl39
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/shinyV.glsl4
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/shinyWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/simpleF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/simpleSkinnedV.glsl39
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/simpleV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/objects/simpleWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/windlight/atmosphericsF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/windlight/atmosphericsHelpersV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/windlight/atmosphericsV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/windlight/atmosphericsVarsF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/windlight/atmosphericsVarsV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/windlight/gammaF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class1/windlight/transportF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/avatar/eyeballV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/alphaF.glsl4
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/alphaSkinnedV.glsl86
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/alphaV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/avatarAlphaF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/avatarAlphaV.glsl5
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/blurLightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/blurLightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/edgeF.glsl4
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/edgeV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/postDeferredF.glsl59
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/postDeferredV.glsl17
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/softenLightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/softenLightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/spotLightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/sunLightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/sunLightSSAOF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/deferred/sunLightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/effects/blurF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/effects/blurV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/effects/colorFilterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/effects/drawQuadV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/effects/extractF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/effects/nightVisionF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/effects/simpleF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/environment/terrainF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/environment/terrainV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/environment/terrainWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/environment/underWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/environment/waterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/environment/waterFogF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/lightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/lightFullbrightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/lightFullbrightShinyF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/lightFullbrightShinyWaterF.glsl31
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/lightFullbrightWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/lightShinyF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/lightShinyWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/lightSpecularV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/lightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/lightWaterF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/sumLightsSpecularV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/lighting/sumLightsV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/objects/shinyV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/atmosphericsF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/atmosphericsHelpersV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/atmosphericsV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/atmosphericsVarsF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/atmosphericsVarsV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/cloudsF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/cloudsV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/gammaF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/skyF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/skyV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class2/windlight/transportF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/avatar/avatarV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/giDownsampleF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/giDownsampleV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/giF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/giFinalF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/giFinalV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/giV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/luminanceF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/luminanceV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/postDeferredF.glsl4
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/postDeferredV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/postgiF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/postgiV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/softenLightF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/softenLightV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/deferred/treeF.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/lighting/sumLightsSpecularV.glsl2
-rw-r--r--indra/newview/app_settings/shaders/class3/lighting/sumLightsV.glsl2
-rw-r--r--indra/newview/app_settings/ultra_graphics.xml2
-rw-r--r--indra/newview/featuretable.txt1131
-rw-r--r--indra/newview/featuretable_linux.txt25
-rw-r--r--indra/newview/featuretable_mac.txt23
-rw-r--r--indra/newview/featuretable_xp.txt1131
-rw-r--r--indra/newview/gpu_table.txt44
-rwxr-xr-x[-rw-r--r--]indra/newview/installers/windows/installer_template.nsi20
-rwxr-xr-x[-rw-r--r--]indra/newview/installers/windows/lang_en-us.nsibin7162 -> 7542 bytes
-rw-r--r--indra/newview/licenses-win32.txt69
-rwxr-xr-x[-rw-r--r--]indra/newview/llagent.cpp10
-rw-r--r--indra/newview/llagentcamera.cpp10
-rwxr-xr-x[-rw-r--r--]indra/newview/llagentpilot.cpp195
-rwxr-xr-x[-rw-r--r--]indra/newview/llagentpilot.h47
-rw-r--r--indra/newview/llappearancemgr.cpp69
-rw-r--r--indra/newview/llappearancemgr.h9
-rwxr-xr-x[-rw-r--r--]indra/newview/llappviewer.cpp10334
-rw-r--r--indra/newview/llappviewerwin32.cpp6
-rw-r--r--indra/newview/llassetuploadresponders.cpp765
-rw-r--r--indra/newview/llassetuploadresponders.h53
-rw-r--r--[-rwxr-xr-x]indra/newview/llavataractions.cpp0
-rw-r--r--indra/newview/llbottomtray.cpp3700
-rw-r--r--indra/newview/llcallbacklist.cpp65
-rw-r--r--indra/newview/llcallbacklist.h9
-rw-r--r--[-rwxr-xr-x]indra/newview/llcommandhandler.cpp0
-rw-r--r--indra/newview/lldrawable.cpp220
-rw-r--r--indra/newview/lldrawable.h92
-rw-r--r--indra/newview/lldrawpool.cpp5
-rw-r--r--indra/newview/lldrawpool.h10
-rw-r--r--indra/newview/lldrawpoolalpha.cpp93
-rw-r--r--indra/newview/lldrawpoolavatar.cpp1004
-rw-r--r--indra/newview/lldrawpoolavatar.h109
-rw-r--r--indra/newview/lldrawpoolbump.cpp96
-rw-r--r--indra/newview/lldrawpoolbump.h11
-rw-r--r--indra/newview/lldrawpooltree.cpp15
-rw-r--r--indra/newview/lldrawpoolwlsky.cpp2
-rw-r--r--indra/newview/llface.cpp1161
-rw-r--r--indra/newview/llface.h51
-rwxr-xr-x[-rw-r--r--]indra/newview/llfasttimerview.cpp445
-rw-r--r--indra/newview/llfasttimerview.h1
-rw-r--r--indra/newview/llfeaturemanager.cpp8
-rw-r--r--indra/newview/llfilepicker.cpp70
-rw-r--r--indra/newview/llfilepicker.h6
-rw-r--r--indra/newview/llflexibleobject.cpp21
-rw-r--r--indra/newview/llflexibleobject.h2
-rw-r--r--indra/newview/llfloateranimpreview.cpp2
-rw-r--r--indra/newview/llfloaterhardwaresettings.cpp5
-rw-r--r--indra/newview/llfloaterimagepreview.cpp20
-rw-r--r--indra/newview/llfloaterimportcollada.cpp1112
-rw-r--r--indra/newview/llfloaterimportcollada.h136
-rwxr-xr-xindra/newview/llfloatermodelpreview.cpp4373
-rw-r--r--indra/newview/llfloatermodelpreview.h367
-rw-r--r--indra/newview/llfloatermodelwizard.cpp650
-rw-r--r--indra/newview/llfloatermodelwizard.h112
-rw-r--r--[-rwxr-xr-x]indra/newview/llfloaterpreference.cpp31
-rw-r--r--indra/newview/llfloatertools.cpp152
-rw-r--r--[-rwxr-xr-x]indra/newview/llfloaterworldmap.cpp0
-rw-r--r--indra/newview/llhudicon.cpp42
-rw-r--r--indra/newview/llhudnametag.cpp31
-rw-r--r--indra/newview/llinventorybridge.cpp78
-rw-r--r--indra/newview/llinventorybridge.h35
-rw-r--r--indra/newview/llinventoryfunctions.cpp1
-rw-r--r--indra/newview/llinventoryicon.cpp3
-rw-r--r--indra/newview/llinventoryicon.h1
-rw-r--r--indra/newview/llinventoryitemslist.h1
-rw-r--r--indra/newview/llmanipscale.cpp29
-rw-r--r--indra/newview/llmanipscale.h3
-rw-r--r--indra/newview/llmeshreduction.cpp272
-rw-r--r--indra/newview/llmeshreduction.h50
-rwxr-xr-xindra/newview/llmeshrepository.cpp3586
-rw-r--r--indra/newview/llmeshrepository.h553
-rw-r--r--indra/newview/llnamelistctrl.h18
-rw-r--r--indra/newview/llpanelface.cpp11
-rw-r--r--indra/newview/llpanelgroupnotices.cpp1
-rw-r--r--indra/newview/llpanelmaininventory.cpp9
-rw-r--r--indra/newview/llpanelnearbymedia.cpp2
-rw-r--r--indra/newview/llpanelobject.cpp158
-rw-r--r--indra/newview/llpanelobject.h14
-rw-r--r--indra/newview/llpanelobjectinventory.cpp116
-rw-r--r--[-rwxr-xr-x]indra/newview/llpanelpicks.cpp0
-rw-r--r--[-rwxr-xr-x]indra/newview/llpanelpicks.h0
-rw-r--r--indra/newview/llpanelprimmediacontrols.cpp5
-rw-r--r--[-rwxr-xr-x]indra/newview/llpanelprofile.cpp0
-rw-r--r--[-rwxr-xr-x]indra/newview/llpanelprofile.h0
-rw-r--r--indra/newview/llphysicsshapebuilderutil.cpp206
-rw-r--r--indra/newview/llphysicsshapebuilderutil.h134
-rw-r--r--indra/newview/llpolymesh.cpp52
-rw-r--r--indra/newview/llpolymesh.h12
-rw-r--r--indra/newview/llpolymorph.cpp13
-rw-r--r--indra/newview/llselectmgr.cpp504
-rw-r--r--indra/newview/llselectmgr.h18
-rw-r--r--indra/newview/llspatialpartition.cpp1671
-rw-r--r--indra/newview/llspatialpartition.h107
-rw-r--r--indra/newview/llsprite.cpp9
-rwxr-xr-x[-rw-r--r--]indra/newview/llstartup.cpp6463
-rw-r--r--indra/newview/llsurfacepatch.cpp6
-rw-r--r--indra/newview/lltexturectrl.cpp10
-rw-r--r--indra/newview/lltooldraganddrop.cpp295
-rw-r--r--indra/newview/lltooldraganddrop.h12
-rw-r--r--indra/newview/llviewerassetstats.cpp17
-rw-r--r--indra/newview/llviewerassettype.cpp2
-rw-r--r--indra/newview/llviewercamera.cpp17
-rw-r--r--indra/newview/llviewercontrol.cpp77
-rw-r--r--indra/newview/llviewerdisplay.cpp2995
-rw-r--r--indra/newview/llviewerfloaterreg.cpp31
-rw-r--r--indra/newview/llviewerfoldertype.cpp3
-rw-r--r--indra/newview/llviewerjointmesh.cpp295
-rw-r--r--indra/newview/llviewerjointmesh_sse.cpp6
-rw-r--r--indra/newview/llviewerjointmesh_sse2.cpp6
-rw-r--r--indra/newview/llviewerjointmesh_vec.cpp2
-rw-r--r--indra/newview/llviewerjoystick.cpp2
-rw-r--r--indra/newview/llviewermedia.cpp2
-rwxr-xr-x[-rw-r--r--]indra/newview/llviewermenu.cpp16365
-rw-r--r--indra/newview/llviewermenufile.cpp508
-rw-r--r--indra/newview/llviewermenufile.h135
-rw-r--r--indra/newview/llviewermessage.cpp2
-rw-r--r--indra/newview/llviewerobject.cpp289
-rw-r--r--indra/newview/llviewerobject.h54
-rw-r--r--indra/newview/llviewerobjectlist.cpp366
-rw-r--r--indra/newview/llviewerobjectlist.h24
-rw-r--r--indra/newview/llviewerpartsim.cpp4
-rw-r--r--indra/newview/llviewerregion.cpp48
-rw-r--r--indra/newview/llviewershadermgr.cpp336
-rw-r--r--indra/newview/llviewershadermgr.h16
-rw-r--r--indra/newview/llviewerstats.cpp2
-rwxr-xr-x[-rw-r--r--]indra/newview/llviewerstats.h31
-rw-r--r--indra/newview/llviewertexteditor.cpp24
-rwxr-xr-x[-rw-r--r--]indra/newview/llviewertexture.cpp20
-rw-r--r--indra/newview/llviewertexturelist.cpp2
-rw-r--r--indra/newview/llviewerwindow.cpp10215
-rw-r--r--indra/newview/llviewerwindow.h6
-rw-r--r--indra/newview/llvoavatar.cpp16617
-rw-r--r--indra/newview/llvoavatar.h2149
-rw-r--r--indra/newview/llvoavatarself.cpp14
-rw-r--r--indra/newview/llvoavatarself.h4
-rw-r--r--indra/newview/llvocache.cpp1512
-rw-r--r--indra/newview/llvograss.cpp15
-rw-r--r--indra/newview/llvoground.cpp9
-rw-r--r--indra/newview/llvoicevivox.cpp7
-rw-r--r--indra/newview/llvopartgroup.cpp14
-rw-r--r--indra/newview/llvopartgroup.h2
-rw-r--r--indra/newview/llvosky.cpp46
-rw-r--r--indra/newview/llvosurfacepatch.cpp97
-rw-r--r--indra/newview/llvosurfacepatch.h2
-rw-r--r--indra/newview/llvotextbubble.cpp33
-rw-r--r--indra/newview/llvotree.cpp43
-rw-r--r--indra/newview/llvotree.h2
-rw-r--r--indra/newview/llvovolume.cpp8688
-rw-r--r--indra/newview/llvovolume.h52
-rw-r--r--indra/newview/llvowater.cpp34
-rw-r--r--indra/newview/llvowater.h2
-rw-r--r--indra/newview/llvowlsky.cpp2
-rw-r--r--indra/newview/llwearableitemslist.h1
-rw-r--r--indra/newview/llworld.cpp2868
-rwxr-xr-x[-rw-r--r--]indra/newview/pipeline.cpp1908
-rw-r--r--indra/newview/pipeline.h38
-rw-r--r--indra/newview/skins/default/colors.xml6
-rw-r--r--indra/newview/skins/default/textures/icons/Inv_Mesh.pngbin0 -> 3263 bytes
-rw-r--r--indra/newview/skins/default/textures/icons/check_mark.pngbin0 -> 3166 bytes
-rw-r--r--indra/newview/skins/default/textures/model_wizard/divider_line.pngbin0 -> 2815 bytes
-rw-r--r--indra/newview/skins/default/textures/model_wizard/progress_bar_bg.pngbin0 -> 3180 bytes
-rw-r--r--indra/newview/skins/default/textures/model_wizard/progress_light.pngbin0 -> 2979 bytes
-rw-r--r--indra/newview/skins/default/textures/textures.xml25
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Disabled.pngbin0 -> 3576 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Off.pngbin0 -> 4309 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Over.pngbin0 -> 4272 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Press.pngbin0 -> 4278 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Disabled.pngbin0 -> 3425 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Off.pngbin0 -> 4151 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Over.pngbin0 -> 4137 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Press.pngbin0 -> 4200 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Disabled.pngbin0 -> 3169 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Off.pngbin0 -> 3845 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Over.pngbin0 -> 3867 bytes
-rw-r--r--indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Press.pngbin0 -> 3915 bytes
-rw-r--r--indra/newview/skins/default/xui/en/floater_about.xml7
-rw-r--r--indra/newview/skins/default/xui/en/floater_import_collada.xml42
-rw-r--r--indra/newview/skins/default/xui/en/floater_inventory_view_finder.xml29
-rw-r--r--indra/newview/skins/default/xui/en/floater_model_preview.xml544
-rw-r--r--indra/newview/skins/default/xui/en/floater_model_wizard.xml895
-rw-r--r--indra/newview/skins/default/xui/en/floater_price_for_listing.xml81
-rw-r--r--indra/newview/skins/default/xui/en/floater_tools.xml230
-rw-r--r--indra/newview/skins/default/xui/en/menu_inventory_add.xml14
-rw-r--r--indra/newview/skins/default/xui/en/menu_model_import_gear_default.xml79
-rw-r--r--indra/newview/skins/default/xui/en/menu_viewer.xml101
-rw-r--r--indra/newview/skins/default/xui/en/notifications.xml25
-rw-r--r--indra/newview/skins/default/xui/en/panel_place_profile.xml2
-rw-r--r--indra/newview/skins/default/xui/en/panel_preferences_graphics1.xml16
-rw-r--r--indra/newview/skins/default/xui/en/strings.xml2
-rw-r--r--indra/newview/tests/llcapabilitylistener_test.cpp1
-rw-r--r--indra/newview/viewer_manifest.py2007
376 files changed, 68837 insertions, 45656 deletions
diff --git a/indra/newview/CMakeLists.txt b/indra/newview/CMakeLists.txt
index 66869288b6..cb0f1c2907 100644
--- a/indra/newview/CMakeLists.txt
+++ b/indra/newview/CMakeLists.txt
@@ -17,6 +17,7 @@ include(JsonCpp)
include(LLAudio)
include(LLCharacter)
include(LLCommon)
+include(LLConvexDecomposition)
include(LLImage)
include(LLImageJ2COJ)
include(LLInventory)
@@ -40,15 +41,18 @@ include(UnixInstall)
include(LLKDU)
include(ViewerMiscLibs)
include(LLLogin)
+include(GLOD)
include(CMakeCopyIfDifferent)
include_directories(
${DBUSGLIB_INCLUDE_DIRS}
${ELFIO_INCLUDE_DIR}
${JSONCPP_INCLUDE_DIRS}
+ ${GLOD_INCLUDE_DIR}
${LLAUDIO_INCLUDE_DIRS}
${LLCHARACTER_INCLUDE_DIRS}
${LLCOMMON_INCLUDE_DIRS}
+ ${LLCONVEXDECOMP_INCLUDE_DIRS}
${LLIMAGE_INCLUDE_DIRS}
${LLKDU_INCLUDE_DIRS}
${LLINVENTORY_INCLUDE_DIRS}
@@ -66,6 +70,8 @@ include_directories(
${LSCRIPT_INCLUDE_DIRS}/lscript_compile
${LLLOGIN_INCLUDE_DIRS}
${UPDATER_INCLUDE_DIRS}
+ ${LIBS_PREBUILT_DIR}/include/collada
+ ${LIBS_PREBUILT_DIR}/include/collada/1.4
)
set(viewer_SOURCE_FILES
@@ -184,6 +190,7 @@ set(viewer_SOURCE_FILES
llfloaterhelpbrowser.cpp
llfloaterhud.cpp
llfloaterimagepreview.cpp
+ llfloaterimportcollada.cpp
llfloaterinspect.cpp
llfloaterinventory.cpp
llfloaterjoystick.cpp
@@ -194,6 +201,8 @@ set(viewer_SOURCE_FILES
llfloatermediabrowser.cpp
llfloatermediasettings.cpp
llfloatermemleak.cpp
+ llfloatermodelpreview.cpp
+ llfloatermodelwizard.cpp
llfloaternamedesc.cpp
llfloaternotificationsconsole.cpp
llfloateropenobject.cpp
@@ -297,6 +306,8 @@ set(viewer_SOURCE_FILES
llmediadataclient.cpp
llmemoryview.cpp
llmenucommands.cpp
+ llmeshrepository.cpp
+ llmeshreduction.cpp
llmimetypes.cpp
llmorphview.cpp
llmoveview.cpp
@@ -379,6 +390,7 @@ set(viewer_SOURCE_FILES
llparcelselection.cpp
llparticipantlist.cpp
llpatchvertexarray.cpp
+ llphysicsshapebuilderutil.cpp
llplacesinventorybridge.cpp
llplacesinventorypanel.cpp
llpopupview.cpp
@@ -725,6 +737,7 @@ set(viewer_HEADER_FILES
llfloaterhelpbrowser.h
llfloaterhud.h
llfloaterimagepreview.h
+ llfloaterimportcollada.h
llfloaterinspect.h
llfloaterinventory.h
llfloaterjoystick.h
@@ -735,6 +748,8 @@ set(viewer_HEADER_FILES
llfloatermediabrowser.h
llfloatermediasettings.h
llfloatermemleak.h
+ llfloatermodelpreview.h
+ llfloatermodelwizard.h
llfloaternamedesc.h
llfloaternotificationsconsole.h
llfloateropenobject.h
@@ -838,6 +853,8 @@ set(viewer_HEADER_FILES
llmediadataclient.h
llmemoryview.h
llmenucommands.h
+ llmeshrepository.h
+ llmeshreduction.h
llmimetypes.h
llmorphview.h
llmoveview.h
@@ -914,6 +931,7 @@ set(viewer_HEADER_FILES
llparcelselection.h
llparticipantlist.h
llpatchvertexarray.h
+ llphysicsshapebuilderutil.h
llplacesinventorybridge.h
llplacesinventorypanel.h
llpolymesh.h
@@ -1440,14 +1458,22 @@ if (WINDOWS)
set(release_flags "/MAP:Release/${VIEWER_BINARY_NAME}.map")
endif(MSVC71)
- set_target_properties(${VIEWER_BINARY_NAME}
- PROPERTIES
- # *TODO -reenable this once we get server usage sorted out
- #LINK_FLAGS "/debug /NODEFAULTLIB:LIBCMT /SUBSYSTEM:WINDOWS /INCLUDE:\"__tcmalloc\""
- LINK_FLAGS "/debug /NODEFAULTLIB:LIBCMT /SUBSYSTEM:WINDOWS"
- LINK_FLAGS_DEBUG "/NODEFAULTLIB:\"LIBCMT;LIBCMTD;MSVCRT\" /INCREMENTAL:NO"
- LINK_FLAGS_RELEASE ${release_flags}
- )
+ if (INCREMENTAL_LINK)
+ set_target_properties(${VIEWER_BINARY_NAME}
+ PROPERTIES
+ LINK_FLAGS "/debug /NODEFAULTLIB:LIBCMT /SUBSYSTEM:WINDOWS /INCREMENTAL /INCLUDE:__tcmalloc"
+ LINK_FLAGS_DEBUG "/NODEFAULTLIB:\"LIBCMT;LIBCMTD;MSVCRT\""
+ LINK_FLAGS_RELEASE ${release_flags}
+ )
+ else(INCREMENTAL_LINK)
+ set_target_properties(${VIEWER_BINARY_NAME}
+ PROPERTIES
+ LINK_FLAGS "/debug /NODEFAULTLIB:LIBCMT /SUBSYSTEM:WINDOWS /INCREMENTAL:NO /INCLUDE:__tcmalloc"
+ LINK_FLAGS_DEBUG "/NODEFAULTLIB:\"LIBCMT;LIBCMTD;MSVCRT\""
+ LINK_FLAGS_RELEASE ${release_flags}
+ )
+ endif(INCREMENTAL_LINK)
+
if(USE_PRECOMPILED_HEADERS)
set_target_properties(
${VIEWER_BINARY_NAME}
@@ -1483,6 +1509,12 @@ if (WINDOWS)
${SHARED_LIB_STAGING_DIR}/${CMAKE_CFG_INTDIR}/libapr-1.dll
${SHARED_LIB_STAGING_DIR}/${CMAKE_CFG_INTDIR}/libaprutil-1.dll
${SHARED_LIB_STAGING_DIR}/${CMAKE_CFG_INTDIR}/libapriconv-1.dll
+ ${SHARED_LIB_STAGING_DIR}/Release/glod.dll
+ ${SHARED_LIB_STAGING_DIR}/RelWithDebInfo/glod.dll
+ ${SHARED_LIB_STAGING_DIR}/Debug/glod.dll
+ ${SHARED_LIB_STAGING_DIR}/Release/libcollada14dom21.dll
+ ${SHARED_LIB_STAGING_DIR}/RelWithDebInfo/libcollada14dom21.dll
+ ${SHARED_LIB_STAGING_DIR}/Debug/libcollada14dom21-d.dll
${SHARED_LIB_STAGING_DIR}/Release/openjpeg.dll
${SHARED_LIB_STAGING_DIR}/RelWithDebInfo/openjpeg.dll
${SHARED_LIB_STAGING_DIR}/Debug/openjpegd.dll
@@ -1661,6 +1693,7 @@ endif (WINDOWS)
# that they depend upon. -brad
target_link_libraries(${VIEWER_BINARY_NAME}
${UPDATER_LIBRARIES}
+ ${GOOGLE_PERFTOOLS_LIBRARIES}
${LLAUDIO_LIBRARIES}
${LLCHARACTER_LIBRARIES}
${LLIMAGE_LIBRARIES}
@@ -1685,6 +1718,7 @@ target_link_libraries(${VIEWER_BINARY_NAME}
${DBUSGLIB_LIBRARIES}
${OPENGL_LIBRARIES}
${FMODWRAPPER_LIBRARY} # must come after LLAudio
+ ${GLOD_LIBRARIES}
${OPENGL_LIBRARIES}
${JSONCPP_LIBRARIES}
${SDL_LIBRARY}
@@ -1696,7 +1730,8 @@ target_link_libraries(${VIEWER_BINARY_NAME}
${OPENSSL_LIBRARIES}
${CRYPTO_LIBRARIES}
${LLLOGIN_LIBRARIES}
- ${GOOGLE_PERFTOOLS_LIBRARIES}
+ ${LLCONVEXDECOMP_LIBRARY}
+ ${TCMALLOC_LIBRARIES}
)
if (USE_KDU)
@@ -1752,6 +1787,8 @@ if (LINUX)
${COPY_INPUT_DEPENDENCIES}
)
+ if (PACKAGE)
+ endif (PACKAGE)
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/.${product}.copy_touched
COMMAND ${PYTHON_EXECUTABLE}
diff --git a/indra/newview/English.lproj/InfoPlist.strings b/indra/newview/English.lproj/InfoPlist.strings
index 4bf67b1367..5c7cacedec 100644
--- a/indra/newview/English.lproj/InfoPlist.strings
+++ b/indra/newview/English.lproj/InfoPlist.strings
@@ -2,6 +2,6 @@
CFBundleName = "Second Life";
-CFBundleShortVersionString = "Second Life version 2.1.1.0";
-CFBundleGetInfoString = "Second Life version 2.1.1.0, Copyright 2004-2010 Linden Research, Inc.";
+CFBundleShortVersionString = "Second Life version 2.1.0.13828";
+CFBundleGetInfoString = "Second Life version 2.1.0.13828, Copyright 2004-2009 Linden Research, Inc.";
diff --git a/indra/newview/Info-SecondLife.plist b/indra/newview/Info-SecondLife.plist
index 3cda7467dd..f7b11b217c 100644
--- a/indra/newview/Info-SecondLife.plist
+++ b/indra/newview/Info-SecondLife.plist
@@ -60,7 +60,7 @@
</dict>
</array>
<key>CFBundleVersion</key>
- <string>2.1.1.0</string>
+ <string>2.1.0.13828</string>
<key>CSResourcesFileMapped</key>
<true/>
</dict>
diff --git a/indra/newview/app_settings/high_graphics.xml b/indra/newview/app_settings/high_graphics.xml
index 4da2b0fd00..587b2f2a89 100644
--- a/indra/newview/app_settings/high_graphics.xml
+++ b/indra/newview/app_settings/high_graphics.xml
@@ -24,8 +24,6 @@
<RenderTerrainLODFactor value="2"/>
<!--Default for now-->
<RenderTreeLODFactor value="0.5"/>
- <!--Default for now-->
- <RenderUseFBO value="1"/>
<!--Try Impostors-->
<RenderUseImpostors value="TRUE"/>
<!--Default for now-->
diff --git a/indra/newview/app_settings/low_graphics.xml b/indra/newview/app_settings/low_graphics.xml
index 136087f69b..a5bbdfc1d0 100644
--- a/indra/newview/app_settings/low_graphics.xml
+++ b/indra/newview/app_settings/low_graphics.xml
@@ -26,8 +26,6 @@
<RenderTerrainLODFactor value="1.0"/>
<!--Default for now-->
<RenderTreeLODFactor value="0.5"/>
- <!--Default for now-->
- <RenderUseFBO value="0"/>
<!--Try Impostors-->
<RenderUseImpostors value="TRUE"/>
<!--Default for now-->
diff --git a/indra/newview/app_settings/mid_graphics.xml b/indra/newview/app_settings/mid_graphics.xml
index c150a87cdf..a1430a58f9 100644
--- a/indra/newview/app_settings/mid_graphics.xml
+++ b/indra/newview/app_settings/mid_graphics.xml
@@ -24,8 +24,6 @@
<RenderTerrainLODFactor value="1.0"/>
<!--Default for now-->
<RenderTreeLODFactor value="0.5"/>
- <!--Default for now-->
- <RenderUseFBO value="0"/>
<!--Try Impostors-->
<RenderUseImpostors value="TRUE"/>
<!--Default for now-->
diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml
index 6a89f5681d..92a3a0299a 100644..100755
--- a/indra/newview/app_settings/settings.xml
+++ b/indra/newview/app_settings/settings.xml
@@ -1322,7 +1322,68 @@
<key>Value</key>
<integer>0</integer>
</map>
- <key>CertStore</key>
+
+ <key>CameraFocusTransitionTime</key>
+ <map>
+ <key>Comment</key>
+ <string>How many seconds it takes the camera to transition between focal distances</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>F32</string>
+ <key>Value</key>
+ <real>0.5</real>
+ </map>
+
+ <key>CameraFNumber</key>
+ <map>
+ <key>Comment</key>
+ <string>Camera f-number value for DoF effect</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>F32</string>
+ <key>Value</key>
+ <real>9.0</real>
+ </map>
+
+ <key>CameraFocalLength</key>
+ <map>
+ <key>Comment</key>
+ <string>Camera focal length for DoF effect (in millimeters)</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>F32</string>
+ <key>Value</key>
+ <real>50</real>
+ </map>
+
+ <key>CameraFieldOfView</key>
+ <map>
+ <key>Comment</key>
+ <string>Vertical camera field of view for DoF effect (in degrees)</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>F32</string>
+ <key>Value</key>
+ <real>60.0</real>
+ </map>
+
+ <key>CameraAspectRatio</key>
+ <map>
+ <key>Comment</key>
+ <string>Camera aspect ratio for DoF effect</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>F32</string>
+ <key>Value</key>
+ <real>1.5</real>
+ </map>
+
+ <key>CertStore</key>
<map>
<key>Comment</key>
<string>Specifies the Certificate Store for certificate trust verification</string>
@@ -1844,7 +1905,7 @@
<key>DebugShowRenderInfo</key>
<map>
<key>Comment</key>
- <string>Show depth buffer contents</string>
+ <string>Show stats about current scene</string>
<key>Persist</key>
<integer>1</integer>
<key>Type</key>
@@ -1852,6 +1913,17 @@
<key>Value</key>
<integer>0</integer>
</map>
+ <key>DebugShowUploadCost</key>
+ <map>
+ <key>Comment</key>
+ <string>Show what it would cost to upload assets in current scene</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Boolean</string>
+ <key>Value</key>
+ <integer>0</integer>
+ </map>
<key>DebugShowRenderMatrices</key>
<map>
<key>Comment</key>
@@ -5429,7 +5501,18 @@
<key>Value</key>
<real>0</real>
</map>
- <key>MigrateCacheDirectory</key>
+ <key>MeshEnabled</key>
+ <map>
+ <key>Comment</key>
+ <string>Expose UI for mesh functionality (may require restart to take effect).</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Boolean</string>
+ <key>Value</key>
+ <real>1</real>
+ </map>
+ <key>MigrateCacheDirectory</key>
<map>
<key>Comment</key>
<string>Check for old version of disk cache to migrate to current location</string>
@@ -6092,6 +6175,66 @@
<key>Value</key>
<real>0.0</real>
</map>
+ <key>ObjectCostHighThreshold</key>
+ <map>
+ <key>Comment</key>
+ <string>Threshold at which object cost is considered high (displayed in red).</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>F32</string>
+ <key>Value</key>
+ <real>50.0</real>
+ </map>
+ <key>ObjectCostLowColor</key>
+ <map>
+ <key>Comment</key>
+ <string>Color for object with a low object cost.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Color4</string>
+ <key>Value</key>
+ <array>
+ <real>0.0</real>
+ <real>0.5</real>
+ <real>1.0</real>
+ <real>0.5</real>
+ </array>
+ </map>
+ <key>ObjectCostMidColor</key>
+ <map>
+ <key>Comment</key>
+ <string>Color for object with a medium object cost.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Color4</string>
+ <key>Value</key>
+ <array>
+ <real>1.0</real>
+ <real>0.75</real>
+ <real>0.0</real>
+ <real>0.65</real>
+ </array>
+ </map>
+ <key>ObjectCostHighColor</key>
+ <map>
+ <key>Comment</key>
+ <string>Color for object a high object cost.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Color4</string>
+ <key>Value</key>
+ <array>
+ <real>1.0</real>
+ <real>0.0</real>
+ <real>0.0</real>
+ <real>0.75</real>
+ </array>
+ </map>
+
<key>ParcelMediaAutoPlayEnable</key>
<map>
<key>Comment</key>
@@ -6327,7 +6470,177 @@
<key>Value</key>
<integer>13</integer>
</map>
- <key>PrimMediaMasterEnabled</key>
+
+ <key>PreviewAmbientColor</key>
+ <map>
+ <key>Comment</key>
+ <string>Ambient color of preview render.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Color4</string>
+ <key>Value</key>
+ <array>
+ <real>0.0</real>
+ <real>0.0</real>
+ <real>0.0</real>
+ <real>1.0</real>
+ </array>
+ </map>
+
+
+ <key>PreviewDiffuse0</key>
+ <map>
+ <key>Comment</key>
+ <string>Diffise color of preview light 0.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Color4</string>
+ <key>Value</key>
+ <array>
+ <real>1.0</real>
+ <real>1.0</real>
+ <real>1.0</real>
+ <real>1.0</real>
+ </array>
+ </map>
+
+ <key>PreviewDiffuse1</key>
+ <map>
+ <key>Comment</key>
+ <string>Diffise color of preview light 1.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Color4</string>
+ <key>Value</key>
+ <array>
+ <real>0.25</real>
+ <real>0.25</real>
+ <real>0.25</real>
+ <real>1.0</real>
+ </array>
+ </map>
+
+ <key>PreviewDiffuse2</key>
+ <map>
+ <key>Comment</key>
+ <string>Diffise color of preview light 2.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Color4</string>
+ <key>Value</key>
+ <array>
+ <real>1.0</real>
+ <real>1.0</real>
+ <real>1.0</real>
+ <real>1.0</real>
+ </array>
+ </map>
+
+ <key>PreviewSpecular0</key>
+ <map>
+ <key>Comment</key>
+ <string>Diffise color of preview light 0.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Color4</string>
+ <key>Value</key>
+ <array>
+ <real>1.0</real>
+ <real>1.0</real>
+ <real>1.0</real>
+ <real>1.0</real>
+ </array>
+ </map>
+
+ <key>PreviewSpecular1</key>
+ <map>
+ <key>Comment</key>
+ <string>Diffise color of preview light 1.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Color4</string>
+ <key>Value</key>
+ <array>
+ <real>1.0</real>
+ <real>1.0</real>
+ <real>1.0</real>
+ <real>1.0</real>
+ </array>
+ </map>
+
+ <key>PreviewSpecular2</key>
+ <map>
+ <key>Comment</key>
+ <string>Diffise color of preview light 2.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Color4</string>
+ <key>Value</key>
+ <array>
+ <real>1.0</real>
+ <real>1.0</real>
+ <real>1.0</real>
+ <real>1.0</real>
+ </array>
+ </map>
+
+
+ <key>PreviewDirection0</key>
+ <map>
+ <key>Comment</key>
+ <string>Direction of light 0 for preview render.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Vector3</string>
+ <key>Value</key>
+ <array>
+ <real>-0.75</real>
+ <real>1</real>
+ <real>1.0</real>
+ </array>
+ </map>
+
+ <key>PreviewDirection1</key>
+ <map>
+ <key>Comment</key>
+ <string>Direction of light 1 for preview render.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Vector3</string>
+ <key>Value</key>
+ <array>
+ <real>0.5</real>
+ <real>-0.6</real>
+ <real>0.4</real>
+ </array>
+ </map>
+
+ <key>PreviewDirection2</key>
+ <map>
+ <key>Comment</key>
+ <string>Direction of light 2 for preview render.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Vector3</string>
+ <key>Value</key>
+ <array>
+ <real>0.5</real>
+ <real>-0.8</real>
+ <real>0.3</real>
+ </array>
+ </map>
+
+ <key>PrimMediaMasterEnabled</key>
<map>
<key>Comment</key>
<string>Whether or not Media on a Prim is enabled.</string>
@@ -6800,7 +7113,31 @@
<key>Value</key>
<integer>1</integer>
</map>
-
+ <key>RenderPerformanceTest</key>
+ <map>
+ <key>Comment</key>
+ <string>Disable rendering of everything but in-world content for
+ performance testing</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Boolean</string>
+ <key>Value</key>
+ <integer>0</integer>
+ </map>
+
+ <key>RenderLocalLights</key>
+ <map>
+ <key>Comment</key>
+ <string>Whether or not to render local lights.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Boolean</string>
+ <key>Value</key>
+ <integer>1</integer>
+ </map>
+
<key>RenderShadowNearDist</key>
<map>
<key>Comment</key>
@@ -6997,7 +7334,18 @@
<key>Value</key>
<integer>0</integer>
</map>
- <key>RenderDebugPipeline</key>
+ <key>RenderDebugNormalScale</key>
+ <map>
+ <key>Comment</key>
+ <string>Scale of normals in debug display.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>F32</string>
+ <key>Value</key>
+ <real>0.03</real>
+ </map>
+ <key>RenderDebugPipeline</key>
<map>
<key>Comment</key>
<string>Enable strict pipeline debugging.</string>
@@ -7030,6 +7378,7 @@
<key>Value</key>
<integer>0</integer>
</map>
+
<key>RenderAnimateRes</key>
<map>
<key>Comment</key>
@@ -7041,7 +7390,31 @@
<key>Value</key>
<integer>0</integer>
</map>
-
+
+ <key>RenderBakeSunlight</key>
+ <map>
+ <key>Comment</key>
+ <string>Bake sunlight into vertex buffers for static objects.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Boolean</string>
+ <key>Value</key>
+ <integer>0</integer>
+ </map>
+
+ <key>RenderNoAlpha</key>
+ <map>
+ <key>Comment</key>
+ <string>Disable rendering of alpha objects (render all alpha objects as alpha masks).</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Boolean</string>
+ <key>Value</key>
+ <integer>0</integer>
+ </map>
+
<key>RenderAnimateTrees</key>
<map>
<key>Comment</key>
@@ -7198,6 +7571,18 @@
<real>16.0</real>
</map>
+ <key>RenderMinimumLODTriangleCount</key>
+ <map>
+ <key>Comment</key>
+ <string>Triangle count threshold at which automatic LOD generation stops</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>U32</string>
+ <key>Value</key>
+ <real>16</real>
+ </map>
+
<key>RenderEdgeDepthCutoff</key>
<map>
<key>Comment</key>
@@ -7288,7 +7673,6 @@
<key>Value</key>
<real>0.01</real>
</map>
-
<key>RenderShadowBiasError</key>
<map>
<key>Comment</key>
@@ -7333,7 +7717,7 @@
<key>Type</key>
<string>F32</string>
<key>Value</key>
- <real>0.0</real>
+ <real>-0.001</real>
</map>
<key>RenderSpotShadowOffset</key>
<map>
@@ -7555,30 +7939,6 @@
<integer>1</integer>
</map>
- <key>RenderDeferredLocalLights</key>
- <map>
- <key>Comment</key>
- <string>Execute local lighting shader in deferred renderer.</string>
- <key>Persist</key>
- <integer>1</integer>
- <key>Type</key>
- <string>Boolean</string>
- <key>Value</key>
- <integer>1</integer>
- </map>
-
- <key>RenderDeferredFullscreenLights</key>
- <map>
- <key>Comment</key>
- <string>Execute local lighting shader in deferred renderer.</string>
- <key>Persist</key>
- <integer>1</integer>
- <key>Type</key>
- <string>Boolean</string>
- <key>Value</key>
- <integer>1</integer>
- </map>
-
<key>RenderDeferredSunWash</key>
<map>
<key>Comment</key>
@@ -8030,7 +8390,7 @@
<key>Type</key>
<string>Boolean</string>
<key>Value</key>
- <integer>1</integer>
+ <integer>0</integer>
</map>
<key>RenderHideGroupTitle</key>
<map>
@@ -8396,17 +8756,17 @@
<key>Value</key>
<integer>0</integer>
</map>
- <key>RenderUseFBO</key>
- <map>
- <key>Comment</key>
- <string>Whether we want to use GL_EXT_framebuffer_objects.</string>
- <key>Persist</key>
- <integer>1</integer>
- <key>Type</key>
- <string>Boolean</string>
- <key>Value</key>
- <integer>1</integer>
- </map>
+ <key>RenderUseTriStrips</key>
+ <map>
+ <key>Comment</key>
+ <string>Use triangle strips for rendering prims.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Boolean</string>
+ <key>Value</key>
+ <integer>0</integer>
+ </map>
<key>RenderUseTriStrips</key>
<map>
<key>Comment</key>
@@ -8495,7 +8855,18 @@
<key>Value</key>
<integer>1</integer>
</map>
- <key>RenderVolumeLODFactor</key>
+ <key>RenderPreferStreamDraw</key>
+ <map>
+ <key>Comment</key>
+ <string>Use GL_STREAM_DRAW in place of GL_DYNAMIC_DRAW</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Boolean</string>
+ <key>Value</key>
+ <integer>0</integer>
+ </map>
+ <key>RenderVolumeLODFactor</key>
<map>
<key>Comment</key>
<string>Controls level of detail of primitives (multiplier for current screen area when calculated level of detail)</string>
@@ -8572,7 +8943,51 @@
<key>Value</key>
<real>1.0</real>
</map>
- <key>SafeMode</key>
+ <key>MeshStreamingCostScaler</key>
+ <map>
+ <key>Comment</key>
+ <string>DEBUG</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>F32</string>
+ <key>Value</key>
+ <real>2.0</real>
+ </map>
+ <key>MeshThreadCount</key>
+ <map>
+ <key>Comment</key>
+ <string>Number of threads to use for loading meshes.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>U32</string>
+ <key>Value</key>
+ <integer>8</integer>
+ </map>
+ <key>MeshMaxConcurrentRequests</key>
+ <map>
+ <key>Comment</key>
+ <string>Number of threads to use for loading meshes.</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>U32</string>
+ <key>Value</key>
+ <integer>32</integer>
+ </map>
+ <key>RunMultipleThreads</key>
+ <map>
+ <key>Comment</key>
+ <string>If TRUE keep background threads active during render</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Boolean</string>
+ <key>Value</key>
+ <integer>0</integer>
+ </map>
+ <key>SafeMode</key>
<map>
<key>Comment</key>
<string>Reset preferences, run in safe mode.</string>
@@ -9848,6 +10263,17 @@
<key>Value</key>
<string>pilot.txt</string>
</map>
+ <key>StatsPilotXMLFile</key>
+ <map>
+ <key>Comment</key>
+ <string>Filename for stats logging extended autopilot path</string>
+ <key>Persist</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>String</string>
+ <key>Value</key>
+ <string>pilot.xml</string>
+ </map>
<key>StatsQuitAfterRuns</key>
<map>
<key>Comment</key>
@@ -11331,7 +11757,7 @@
<key>Type</key>
<string>Boolean</string>
<key>Value</key>
- <integer>1</integer>
+ <integer>0</integer>
</map>
<key>SpeakerParticipantDefaultOrder</key>
<map>
diff --git a/indra/newview/app_settings/settings_crash_behavior.xml b/indra/newview/app_settings/settings_crash_behavior.xml
index cc7f5ac88b..97651ff4ca 100644
--- a/indra/newview/app_settings/settings_crash_behavior.xml
+++ b/indra/newview/app_settings/settings_crash_behavior.xml
@@ -9,7 +9,7 @@
<key>Type</key>
<string>S32</string>
<key>Value</key>
- <integer>0</integer>
+ <integer>1</integer>
</map>
</map>
</llsd>
diff --git a/indra/newview/app_settings/shaders/class1/avatar/avatarF.glsl b/indra/newview/app_settings/shaders/class1/avatar/avatarF.glsl
index 5de9cb0790..3f6b8b3323 100644
--- a/indra/newview/app_settings/shaders/class1/avatar/avatarF.glsl
+++ b/indra/newview/app_settings/shaders/class1/avatar/avatarF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void default_lighting();
diff --git a/indra/newview/app_settings/shaders/class1/avatar/avatarSkinV.glsl b/indra/newview/app_settings/shaders/class1/avatar/avatarSkinV.glsl
index 7e9818e54a..1ad87badfe 100644
--- a/indra/newview/app_settings/shaders/class1/avatar/avatarSkinV.glsl
+++ b/indra/newview/app_settings/shaders/class1/avatar/avatarSkinV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
attribute vec4 weight; //1
diff --git a/indra/newview/app_settings/shaders/class1/avatar/avatarV.glsl b/indra/newview/app_settings/shaders/class1/avatar/avatarV.glsl
index 9f06301cc7..a15846f192 100644
--- a/indra/newview/app_settings/shaders/class1/avatar/avatarV.glsl
+++ b/indra/newview/app_settings/shaders/class1/avatar/avatarV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
mat4 getSkinnedTransform();
diff --git a/indra/newview/app_settings/shaders/class1/avatar/eyeballF.glsl b/indra/newview/app_settings/shaders/class1/avatar/eyeballF.glsl
index 0feb88535a..05fe100372 100644
--- a/indra/newview/app_settings/shaders/class1/avatar/eyeballF.glsl
+++ b/indra/newview/app_settings/shaders/class1/avatar/eyeballF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void default_lighting();
diff --git a/indra/newview/app_settings/shaders/class1/avatar/eyeballV.glsl b/indra/newview/app_settings/shaders/class1/avatar/eyeballV.glsl
index 30a2f10f62..4b8a7604a1 100644
--- a/indra/newview/app_settings/shaders/class1/avatar/eyeballV.glsl
+++ b/indra/newview/app_settings/shaders/class1/avatar/eyeballV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 calcLightingSpecular(vec3 pos, vec3 norm, vec4 color, inout vec4 specularColor, vec4 baseCol);
void calcAtmospherics(vec3 inPositionEye);
diff --git a/indra/newview/app_settings/shaders/class1/avatar/objectSkinV.glsl b/indra/newview/app_settings/shaders/class1/avatar/objectSkinV.glsl
new file mode 100644
index 0000000000..ef823c28b1
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/avatar/objectSkinV.glsl
@@ -0,0 +1,30 @@
+/**
+ * @file objectSkinV.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+attribute vec4 object_weight;
+
+uniform mat4 matrixPalette[32];
+
+mat4 getObjectSkinnedTransform()
+{
+ int i;
+
+ vec4 w = fract(object_weight);
+ vec4 index = floor(object_weight);
+
+ float scale = 1.0/(w.x+w.y+w.z+w.w);
+ w *= scale;
+
+ mat4 mat = matrixPalette[int(index.x)]*w.x;
+ mat += matrixPalette[int(index.y)]*w.y;
+ mat += matrixPalette[int(index.z)]*w.z;
+ mat += matrixPalette[int(index.w)]*w.w;
+
+ return mat;
+}
diff --git a/indra/newview/app_settings/shaders/class1/avatar/pickAvatarF.glsl b/indra/newview/app_settings/shaders/class1/avatar/pickAvatarF.glsl
index bcd710dc57..27ac59a840 100644
--- a/indra/newview/app_settings/shaders/class1/avatar/pickAvatarF.glsl
+++ b/indra/newview/app_settings/shaders/class1/avatar/pickAvatarF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/avatar/pickAvatarV.glsl b/indra/newview/app_settings/shaders/class1/avatar/pickAvatarV.glsl
index 299def1927..f1aa549a47 100644
--- a/indra/newview/app_settings/shaders/class1/avatar/pickAvatarV.glsl
+++ b/indra/newview/app_settings/shaders/class1/avatar/pickAvatarV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
mat4 getSkinnedTransform();
diff --git a/indra/newview/app_settings/shaders/class1/deferred/alphaF.glsl b/indra/newview/app_settings/shaders/class1/deferred/alphaF.glsl
index 171a0e76f7..b08c5dd295 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/alphaF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/alphaF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
@@ -22,7 +24,6 @@ varying vec3 vary_ambient;
varying vec3 vary_directional;
varying vec3 vary_fragcoord;
varying vec3 vary_position;
-varying vec3 vary_light;
uniform mat4 inv_proj;
@@ -55,7 +56,6 @@ void main()
color.rgb = scaleSoftClip(color.rgb);
- //gl_FragColor = gl_Color;
gl_FragColor = color;
//gl_FragColor = vec4(1,0,1,1);
//gl_FragColor = vec4(1,0,1,1)*shadow;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/alphaSkinnedV.glsl b/indra/newview/app_settings/shaders/class1/deferred/alphaSkinnedV.glsl
new file mode 100644
index 0000000000..4261f943fb
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/deferred/alphaSkinnedV.glsl
@@ -0,0 +1,83 @@
+/**
+ * @file alphaSkinnedV.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
+mat4 getObjectSkinnedTransform();
+void calcAtmospherics(vec3 inPositionEye);
+
+float calcDirectionalLight(vec3 n, vec3 l);
+float calcPointLightOrSpotLight(vec3 v, vec3 n, vec4 lp, vec3 ln, float la, float is_pointlight);
+
+vec3 atmosAmbient(vec3 light);
+vec3 atmosAffectDirectionalLight(float lightIntensity);
+vec3 scaleDownLight(vec3 light);
+vec3 scaleUpLight(vec3 light);
+
+varying vec3 vary_position;
+varying vec3 vary_ambient;
+varying vec3 vary_directional;
+varying vec3 vary_normal;
+varying vec3 vary_light;
+varying vec3 vary_fragcoord;
+
+uniform float near_clip;
+
+void main()
+{
+ gl_TexCoord[0] = gl_MultiTexCoord0;
+
+ vec4 pos;
+ vec3 norm;
+
+ mat4 trans = getObjectSkinnedTransform();
+ trans = gl_ModelViewMatrix * trans;
+
+ pos = trans * gl_Vertex;
+
+ norm = gl_Vertex.xyz + gl_Normal.xyz;
+ norm = normalize(( trans*vec4(norm, 1.0) ).xyz-pos.xyz);
+
+ vec4 frag_pos = gl_ProjectionMatrix * pos;
+ gl_Position = frag_pos;
+
+ vary_position = pos.xyz;
+ vary_normal = norm;
+
+ calcAtmospherics(pos.xyz);
+
+ vec4 col = vec4(0.0, 0.0, 0.0, gl_Color.a);
+
+ // Collect normal lights (need to be divided by two, as we later multiply by 2)
+ col.rgb += gl_LightSource[2].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[2].position, gl_LightSource[2].spotDirection.xyz, gl_LightSource[2].linearAttenuation, gl_LightSource[2].specular.a);
+ col.rgb += gl_LightSource[3].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[3].position, gl_LightSource[3].spotDirection.xyz, gl_LightSource[3].linearAttenuation, gl_LightSource[3].specular.a);
+ col.rgb += gl_LightSource[4].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[4].position, gl_LightSource[4].spotDirection.xyz, gl_LightSource[4].linearAttenuation, gl_LightSource[4].specular.a);
+ col.rgb += gl_LightSource[5].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[5].position, gl_LightSource[5].spotDirection.xyz, gl_LightSource[5].linearAttenuation, gl_LightSource[5].specular.a);
+ col.rgb += gl_LightSource[6].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[6].position, gl_LightSource[6].spotDirection.xyz, gl_LightSource[6].linearAttenuation, gl_LightSource[6].specular.a);
+ col.rgb += gl_LightSource[7].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[7].position, gl_LightSource[7].spotDirection.xyz, gl_LightSource[7].linearAttenuation, gl_LightSource[7].specular.a);
+ col.rgb += gl_LightSource[1].diffuse.rgb*calcDirectionalLight(norm, gl_LightSource[1].position.xyz);
+ col.rgb = scaleDownLight(col.rgb);
+
+ // Add windlight lights
+ col.rgb += atmosAmbient(vec3(0.));
+
+ vary_light = gl_LightSource[0].position.xyz;
+
+ vary_ambient = col.rgb*gl_Color.rgb;
+ vary_directional = gl_Color.rgb*atmosAffectDirectionalLight(max(calcDirectionalLight(norm, gl_LightSource[0].position.xyz), (1.0-gl_Color.a)*(1.0-gl_Color.a)));
+
+ col.rgb = min(col.rgb*gl_Color.rgb, 1.0);
+
+ gl_FrontColor = col;
+
+ gl_FogFragCoord = pos.z;
+
+ vary_fragcoord.xyz = frag_pos.xyz + vec3(0,0,near_clip);
+}
+
+
diff --git a/indra/newview/app_settings/shaders/class1/deferred/alphaV.glsl b/indra/newview/app_settings/shaders/class1/deferred/alphaV.glsl
index fabbce0824..7ac410da95 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/alphaV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/alphaV.glsl
@@ -5,6 +5,8 @@
* $/LicenseInfo$
*/
+#version 120
+
vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
void calcAtmospherics(vec3 inPositionEye);
@@ -36,7 +38,7 @@ void main()
vec4 pos = (gl_ModelViewMatrix * gl_Vertex);
vec3 norm = normalize(gl_NormalMatrix * gl_Normal);
- vary_position = pos.xyz + norm.xyz * (-pos.z/64.0*shadow_offset+shadow_bias);
+ vary_position = pos.xyz;
calcAtmospherics(pos.xyz);
diff --git a/indra/newview/app_settings/shaders/class1/deferred/attachmentShadowF.glsl b/indra/newview/app_settings/shaders/class1/deferred/attachmentShadowF.glsl
new file mode 100644
index 0000000000..164322c3a7
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/deferred/attachmentShadowF.glsl
@@ -0,0 +1,18 @@
+/**
+ * @file avatarShadowF.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+uniform sampler2D diffuseMap;
+
+
+void main()
+{
+ //gl_FragColor = vec4(1,1,1,gl_Color.a * texture2D(diffuseMap, gl_TexCoord[0].xy).a);
+ gl_FragColor = vec4(1,1,1,1);
+}
+
diff --git a/indra/newview/app_settings/shaders/class1/deferred/attachmentShadowV.glsl b/indra/newview/app_settings/shaders/class1/deferred/attachmentShadowV.glsl
new file mode 100644
index 0000000000..5ae41cb730
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/deferred/attachmentShadowV.glsl
@@ -0,0 +1,27 @@
+/**
+ * @file attachmentShadowV.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+mat4 getObjectSkinnedTransform();
+
+void main()
+{
+ //transform vertex
+ gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
+
+ mat4 mat = getObjectSkinnedTransform();
+
+ mat = gl_ModelViewMatrix * mat;
+ vec3 pos = (mat*gl_Vertex).xyz;
+
+ gl_FrontColor = gl_Color;
+
+ vec4 p = gl_ProjectionMatrix * vec4(pos, 1.0);
+ p.z = max(p.z, -p.w+0.01);
+ gl_Position = p;
+}
diff --git a/indra/newview/app_settings/shaders/class1/deferred/avatarAlphaF.glsl b/indra/newview/app_settings/shaders/class1/deferred/avatarAlphaF.glsl
index 82ce6d7377..7d9d6cc0b2 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/avatarAlphaF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/avatarAlphaF.glsl
@@ -5,6 +5,8 @@
* $/LicenseInfo$
*/
+#version 120
+
uniform sampler2D diffuseMap;
uniform sampler2DShadow shadowMap0;
uniform sampler2DShadow shadowMap1;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/avatarAlphaV.glsl b/indra/newview/app_settings/shaders/class1/deferred/avatarAlphaV.glsl
index 21ddc2fad8..5dfbb91393 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/avatarAlphaV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/avatarAlphaV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
mat4 getSkinnedTransform();
@@ -17,10 +19,13 @@ vec3 atmosAffectDirectionalLight(float lightIntensity);
vec3 scaleDownLight(vec3 light);
vec3 scaleUpLight(vec3 light);
-varying vec4 vary_position;
+varying vec3 vary_position;
varying vec3 vary_ambient;
varying vec3 vary_directional;
varying vec3 vary_normal;
+varying vec3 vary_fragcoord;
+
+uniform float near_clip;
void main()
{
@@ -40,8 +45,10 @@ void main()
norm.z = dot(trans[2].xyz, gl_Normal);
norm = normalize(norm);
- gl_Position = gl_ProjectionMatrix * pos;
- vary_position = pos;
+ vec4 frag_pos = gl_ProjectionMatrix * pos;
+ gl_Position = frag_pos;
+
+ vary_position = pos.xyz;
vary_normal = norm;
calcAtmospherics(pos.xyz);
@@ -71,7 +78,8 @@ void main()
gl_FrontColor = col;
gl_FogFragCoord = pos.z;
-
+
+ vary_fragcoord.xyz = frag_pos.xyz + vec3(0,0,near_clip);
}
diff --git a/indra/newview/app_settings/shaders/class1/deferred/avatarF.glsl b/indra/newview/app_settings/shaders/class1/deferred/avatarF.glsl
index e376892e0a..9748727147 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/avatarF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/avatarF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/avatarShadowF.glsl b/indra/newview/app_settings/shaders/class1/deferred/avatarShadowF.glsl
index d88e3ecfd8..1b7ae06888 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/avatarShadowF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/avatarShadowF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/avatarShadowV.glsl b/indra/newview/app_settings/shaders/class1/deferred/avatarShadowV.glsl
index 2af8c8f5f7..cf6579a40d 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/avatarShadowV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/avatarShadowV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
mat4 getSkinnedTransform();
diff --git a/indra/newview/app_settings/shaders/class1/deferred/avatarV.glsl b/indra/newview/app_settings/shaders/class1/deferred/avatarV.glsl
index 988226fb7c..69c93799b5 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/avatarV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/avatarV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
mat4 getSkinnedTransform();
diff --git a/indra/newview/app_settings/shaders/class1/deferred/blurLightF.glsl b/indra/newview/app_settings/shaders/class1/deferred/blurLightF.glsl
index 258a9b7c40..ea2df4b51a 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/blurLightF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/blurLightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class1/deferred/blurLightV.glsl b/indra/newview/app_settings/shaders/class1/deferred/blurLightV.glsl
index b1b3f55f00..c2d05c601a 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/blurLightV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/blurLightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/bumpF.glsl b/indra/newview/app_settings/shaders/class1/deferred/bumpF.glsl
index 35f334d58e..37bfaac32c 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/bumpF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/bumpF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
uniform sampler2D bumpMap;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/bumpSkinnedV.glsl b/indra/newview/app_settings/shaders/class1/deferred/bumpSkinnedV.glsl
new file mode 100644
index 0000000000..d884f2e4a5
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/deferred/bumpSkinnedV.glsl
@@ -0,0 +1,37 @@
+/**
+ * @file bumpV.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+varying vec3 vary_mat0;
+varying vec3 vary_mat1;
+varying vec3 vary_mat2;
+
+mat4 getObjectSkinnedTransform();
+
+void main()
+{
+ gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
+
+ mat4 mat = getObjectSkinnedTransform();
+
+ mat = gl_ModelViewMatrix * mat;
+
+ vec3 pos = (mat*gl_Vertex).xyz;
+
+
+ vec3 n = normalize((mat * vec4(gl_Normal.xyz+gl_Vertex.xyz, 1.0)).xyz-pos.xyz);
+ vec3 b = normalize((mat * vec4(gl_MultiTexCoord2.xyz+gl_Vertex.xyz, 1.0)).xyz-pos.xyz);
+ vec3 t = cross(b, n);
+
+ vary_mat0 = vec3(t.x, b.x, n.x);
+ vary_mat1 = vec3(t.y, b.y, n.y);
+ vary_mat2 = vec3(t.z, b.z, n.z);
+
+ gl_Position = gl_ProjectionMatrix*vec4(pos, 1.0);
+ gl_FrontColor = gl_Color;
+}
diff --git a/indra/newview/app_settings/shaders/class1/deferred/bumpV.glsl b/indra/newview/app_settings/shaders/class1/deferred/bumpV.glsl
index 6c8550cb5b..9b109b2db6 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/bumpV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/bumpV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec3 vary_mat0;
varying vec3 vary_mat1;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/diffuseF.glsl b/indra/newview/app_settings/shaders/class1/deferred/diffuseF.glsl
index 9bd622a506..35cfb80c93 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/diffuseF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/diffuseF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/diffuseSkinnedV.glsl b/indra/newview/app_settings/shaders/class1/deferred/diffuseSkinnedV.glsl
new file mode 100644
index 0000000000..9a45c03237
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/deferred/diffuseSkinnedV.glsl
@@ -0,0 +1,33 @@
+/**
+ * @file diffuseSkinnedV.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+varying vec3 vary_normal;
+
+mat4 getObjectSkinnedTransform();
+
+void main()
+{
+ gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
+
+ mat4 mat = getObjectSkinnedTransform();
+
+ mat = gl_ModelViewMatrix * mat;
+ vec3 pos = (mat*gl_Vertex).xyz;
+
+ vec4 norm = gl_Vertex;
+ norm.xyz += gl_Normal.xyz;
+ norm.xyz = (mat*norm).xyz;
+ norm.xyz = normalize(norm.xyz-pos.xyz);
+
+ vary_normal = norm.xyz;
+
+ gl_FrontColor = gl_Color;
+
+ gl_Position = gl_ProjectionMatrix*vec4(pos, 1.0);
+}
diff --git a/indra/newview/app_settings/shaders/class1/deferred/diffuseV.glsl b/indra/newview/app_settings/shaders/class1/deferred/diffuseV.glsl
index bd58096317..03d3322cb6 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/diffuseV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/diffuseV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec3 vary_normal;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/fullbrightF.glsl b/indra/newview/app_settings/shaders/class1/deferred/fullbrightF.glsl
index f53e15c6cc..3429877397 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/fullbrightF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/fullbrightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class1/deferred/fullbrightV.glsl b/indra/newview/app_settings/shaders/class1/deferred/fullbrightV.glsl
index dc8b2c6be4..6c38d220e2 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/fullbrightV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/fullbrightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void calcAtmospherics(vec3 inPositionEye);
diff --git a/indra/newview/app_settings/shaders/class1/deferred/giF.glsl b/indra/newview/app_settings/shaders/class1/deferred/giF.glsl
index e64e29a0d2..75b555e8ae 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/giF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/giF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class1/deferred/giV.glsl b/indra/newview/app_settings/shaders/class1/deferred/giV.glsl
index 543527612e..8dc1410ea5 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/giV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/giV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/impostorF.glsl b/indra/newview/app_settings/shaders/class1/deferred/impostorF.glsl
index 7f365fedc8..e3c15a2ab2 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/impostorF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/impostorF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
uniform sampler2D normalMap;
@@ -12,7 +14,7 @@ uniform sampler2D specularMap;
void main()
{
vec4 col = texture2D(diffuseMap, gl_TexCoord[0].xy);
- gl_FragData[0] = vec4(col.rgb, col.a <= 0.5 ? 0.0 : 0.005);
+ gl_FragData[0] = vec4(col.rgb, col.a * 0.005);
gl_FragData[1] = texture2D(specularMap, gl_TexCoord[0].xy);
gl_FragData[2] = vec4(texture2D(normalMap, gl_TexCoord[0].xy).xyz, 0.0);
}
diff --git a/indra/newview/app_settings/shaders/class1/deferred/impostorV.glsl b/indra/newview/app_settings/shaders/class1/deferred/impostorV.glsl
index 4fc27d4412..37148b3f1a 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/impostorV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/impostorV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void main()
{
diff --git a/indra/newview/app_settings/shaders/class1/deferred/luminanceF.glsl b/indra/newview/app_settings/shaders/class1/deferred/luminanceF.glsl
index acb3014d18..78df54d5dc 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/luminanceF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/luminanceF.glsl
@@ -5,6 +5,8 @@
* $/LicenseInfo$
*/
+#version 120
+
uniform sampler2DRect diffuseMap;
varying vec2 vary_fragcoord;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/luminanceV.glsl b/indra/newview/app_settings/shaders/class1/deferred/luminanceV.glsl
index 6368def830..0c820bfc6c 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/luminanceV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/luminanceV.glsl
@@ -5,6 +5,9 @@
* $/LicenseInfo$
*/
+#version 120
+
+
varying vec2 vary_fragcoord;
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/multiPointLightF.glsl b/indra/newview/app_settings/shaders/class1/deferred/multiPointLightF.glsl
index 6fca08ae6a..c5ddf31ac0 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/multiPointLightF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/multiPointLightF.glsl
@@ -5,6 +5,8 @@
* $/LicenseInfo$
*/
+#version 120
+
#extension GL_ARB_texture_rectangle : enable
uniform sampler2DRect depthMap;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/pointLightF.glsl b/indra/newview/app_settings/shaders/class1/deferred/pointLightF.glsl
index 43da16436b..22ed9dcd40 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/pointLightF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/pointLightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+ #version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class1/deferred/pointLightV.glsl b/indra/newview/app_settings/shaders/class1/deferred/pointLightV.glsl
index e056c3e896..8e74feb615 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/pointLightV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/pointLightV.glsl
@@ -5,6 +5,8 @@
* $/LicenseInfo$
*/
+#version 120
+
varying vec4 vary_light;
varying vec4 vary_fragcoord;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/postDeferredF.glsl b/indra/newview/app_settings/shaders/class1/deferred/postDeferredF.glsl
index 650e1a91a8..7c89c01ea4 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/postDeferredF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/postDeferredF.glsl
@@ -4,54 +4,124 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
uniform sampler2DRect diffuseRect;
-uniform sampler2DRect localLightMap;
-uniform sampler2DRect sunLightMap;
-uniform sampler2DRect giLightMap;
-uniform sampler2D luminanceMap;
-uniform sampler2DRect lightMap;
+uniform sampler2DRect edgeMap;
+uniform sampler2DRect depthMap;
+uniform sampler2DRect normalMap;
+uniform sampler2D bloomMap;
-uniform vec3 lum_quad;
-uniform float lum_lod;
-uniform vec4 ambient;
-
-uniform vec3 gi_quad;
+uniform float depth_cutoff;
+uniform float norm_cutoff;
+uniform float focal_distance;
+uniform float blur_constant;
+uniform float tan_pixel_angle;
+uniform float magnification;
+uniform mat4 inv_proj;
uniform vec2 screen_res;
+
varying vec2 vary_fragcoord;
-void main()
+float getDepth(vec2 pos_screen)
{
- vec2 tc = vary_fragcoord.xy;
- vec3 lum = texture2DLod(luminanceMap, tc/screen_res, lum_lod).rgb;
- float luminance = lum.r;
- luminance = luminance*lum_quad.y+lum_quad.z;
+ float z = texture2DRect(depthMap, pos_screen.xy).a;
+ z = z*2.0-1.0;
+ vec4 ndc = vec4(0.0, 0.0, z, 1.0);
+ vec4 p = inv_proj*ndc;
+ return p.z/p.w;
+}
- vec4 diff = texture2DRect(diffuseRect, vary_fragcoord.xy);
+void dofSample(inout vec4 diff, inout float w, float fd, float x, float y)
+{
+ vec2 tc = vary_fragcoord.xy+vec2(x,y);
+ float d = getDepth(tc);
+
+ float wg = 1.0;
+ //if (d < fd)
+ //{
+ // diff += texture2DRect(diffuseRect, tc);
+ // w = 1.0;
+ //}
+ if (d > fd)
+ {
+ wg = max(d/fd, 0.1);
+ }
+
+ diff += texture2DRect(diffuseRect, tc+vec2(0.5,0.5))*wg*0.25;
+ diff += texture2DRect(diffuseRect, tc+vec2(-0.5,0.5))*wg*0.25;
+ diff += texture2DRect(diffuseRect, tc+vec2(0.5,-0.5))*wg*0.25;
+ diff += texture2DRect(diffuseRect, tc+vec2(-0.5,-0.5))*wg*0.25;
+ w += wg;
+}
- float ambocc = texture2DRect(lightMap, vary_fragcoord.xy).g;
-
- vec3 gi_col = texture2DRect(giLightMap, vary_fragcoord.xy).rgb;
- gi_col = gi_col*gi_col*gi_quad.x + gi_col*gi_quad.y+gi_quad.z*ambocc*ambient.rgb;
- gi_col *= diff;
+void dofSampleNear(inout vec4 diff, inout float w, float x, float y)
+{
+ vec2 tc = vary_fragcoord.xy+vec2(x,y);
+
+ diff += texture2DRect(diffuseRect, tc);
+ w += 1.0;
+}
+
+void main()
+{
+ vec3 norm = texture2DRect(normalMap, vary_fragcoord.xy).xyz;
+ norm = vec3((norm.xy-0.5)*2.0,norm.z); // unpack norm
- vec4 sun_col = texture2DRect(sunLightMap, vary_fragcoord.xy);
- vec3 local_col = texture2DRect(localLightMap, vary_fragcoord.xy).rgb;
+ vec2 tc = vary_fragcoord.xy;
+
+ float sc = 0.75;
+
+ float depth;
+ depth = getDepth(tc);
+ vec4 diff = texture2DRect(diffuseRect, vary_fragcoord.xy);
+
+ { //pixel is behind far focal plane
+ float w = 1.0;
- sun_col *= 1.0/min(luminance, 1.0);
- gi_col *= 1.0/luminance;
+ sc = (abs(depth-focal_distance)/-depth)*blur_constant;
- vec3 col = sun_col.rgb+gi_col+local_col;
-
- gl_FragColor.rgb = col.rgb;
- col.rgb = max(col.rgb-vec3(1.0,1.0,1.0), vec3(0.0, 0.0, 0.0));
-
- gl_FragColor.a = 0.0; // max(dot(col.rgb,col.rgb)*lum_quad.x, sun_col.a);
+ sc /= magnification;
+
+ // tan_pixel_angle = pixel_length/-depth;
+ float pixel_length = tan_pixel_angle*-focal_distance;
+
+ sc = sc/pixel_length;
+
+ //diff.r = sc;
+
+ sc = min(abs(sc), 8.0);
+
+ //sc = 4.0;
+
+ float fd = depth*0.5f;
+
+ while (sc > 1.0)
+ {
+ dofSample(diff,w, fd, sc,sc);
+ dofSample(diff,w, fd, -sc,sc);
+ dofSample(diff,w, fd, sc,-sc);
+ dofSample(diff,w, fd, -sc,-sc);
+
+ sc -= 0.5;
+ float sc2 = sc*1.414;
+ dofSample(diff,w, fd, 0,sc2);
+ dofSample(diff,w, fd, 0,-sc2);
+ dofSample(diff,w, fd, -sc2,0);
+ dofSample(diff,w, fd, sc2,0);
+ sc -= 0.5;
+ }
+
+ diff /= w;
+ }
+
+ vec4 bloom = texture2D(bloomMap, vary_fragcoord.xy/screen_res);
+ gl_FragColor = diff + bloom;
- //gl_FragColor.rgb = vec3(lum_lod);
}
diff --git a/indra/newview/app_settings/shaders/class1/deferred/postDeferredV.glsl b/indra/newview/app_settings/shaders/class1/deferred/postDeferredV.glsl
index 0ec81dcb02..12983baa94 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/postDeferredV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/postDeferredV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/postgiF.glsl b/indra/newview/app_settings/shaders/class1/deferred/postgiF.glsl
index e8e58f50e1..63b3c9f205 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/postgiF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/postgiF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2DRect depthMap;
uniform sampler2DRect normalMap;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/postgiV.glsl b/indra/newview/app_settings/shaders/class1/deferred/postgiV.glsl
index e5f6217644..ae57227fe5 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/postgiV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/postgiV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/shadowF.glsl b/indra/newview/app_settings/shaders/class1/deferred/shadowF.glsl
index 378a3295ec..6674c4a5aa 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/shadowF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/shadowF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/shadowV.glsl b/indra/newview/app_settings/shaders/class1/deferred/shadowV.glsl
index 666f909f01..db3bddc6be 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/shadowV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/shadowV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec4 post_pos;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/softenLightF.glsl b/indra/newview/app_settings/shaders/class1/deferred/softenLightF.glsl
index 5fbeceba81..29340c7e9f 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/softenLightF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/softenLightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
@@ -268,14 +270,10 @@ void main()
vec4 diffuse = texture2DRect(diffuseRect, tc);
vec4 spec = texture2DRect(specularRect, vary_fragcoord.xy);
- vec2 scol_ambocc = texture2DRect(lightMap, vary_fragcoord.xy).rg;
- float scol = max(scol_ambocc.r, diffuse.a);
- float ambocc = scol_ambocc.g;
-
- calcAtmospherics(pos.xyz, ambocc);
+ calcAtmospherics(pos.xyz, 1.0);
vec3 col = atmosAmbient(vec3(0));
- col += atmosAffectDirectionalLight(max(min(da, scol), diffuse.a));
+ col += atmosAffectDirectionalLight(max(min(da, 1.0), diffuse.a));
col *= diffuse.rgb;
@@ -285,7 +283,7 @@ void main()
//
vec3 refnormpersp = normalize(reflect(pos.xyz, norm.xyz));
float sa = dot(refnormpersp, vary_light.xyz);
- vec3 dumbshiny = vary_SunlitColor*scol_ambocc.r*texture2D(lightFunc, vec2(sa, spec.a)).a;
+ vec3 dumbshiny = vary_SunlitColor*texture2D(lightFunc, vec2(sa, spec.a)).a;
/*
// screen-space cheap fakey reflection map
diff --git a/indra/newview/app_settings/shaders/class1/deferred/softenLightV.glsl b/indra/newview/app_settings/shaders/class1/deferred/softenLightV.glsl
index 9d187b46e2..8f0bcca76b 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/softenLightV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/softenLightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/sunLightF.glsl b/indra/newview/app_settings/shaders/class1/deferred/sunLightF.glsl
index d4d686bbb7..00093836a2 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/sunLightF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/sunLightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
//class 1, no shadow, no SSAO, should never be called
diff --git a/indra/newview/app_settings/shaders/class1/deferred/sunLightSSAOF.glsl b/indra/newview/app_settings/shaders/class1/deferred/sunLightSSAOF.glsl
index cdbed4b791..1e0693d19f 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/sunLightSSAOF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/sunLightSSAOF.glsl
@@ -4,6 +4,8 @@
* Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
* $License$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class1/deferred/sunLightV.glsl b/indra/newview/app_settings/shaders/class1/deferred/sunLightV.glsl
index 9d092d9cea..9beb513ad8 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/sunLightV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/sunLightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec4 vary_light;
varying vec2 vary_fragcoord;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/terrainF.glsl b/indra/newview/app_settings/shaders/class1/deferred/terrainF.glsl
index 9ba508a30c..0edae47918 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/terrainF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/terrainF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D detail_0;
uniform sampler2D detail_1;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/terrainV.glsl b/indra/newview/app_settings/shaders/class1/deferred/terrainV.glsl
index 789e53b789..a6163063be 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/terrainV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/terrainV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec3 vary_normal;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/treeF.glsl b/indra/newview/app_settings/shaders/class1/deferred/treeF.glsl
index 1c1725a95c..c54d9a1e3e 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/treeF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/treeF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/treeV.glsl b/indra/newview/app_settings/shaders/class1/deferred/treeV.glsl
index 45832e350f..29689ecbaf 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/treeV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/treeV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec3 vary_normal;
diff --git a/indra/newview/app_settings/shaders/class1/deferred/waterF.glsl b/indra/newview/app_settings/shaders/class1/deferred/waterF.glsl
index ea531de24a..e76f598d09 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/waterF.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/waterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class1/deferred/waterV.glsl b/indra/newview/app_settings/shaders/class1/deferred/waterV.glsl
index e002d75ebe..649e392630 100644
--- a/indra/newview/app_settings/shaders/class1/deferred/waterV.glsl
+++ b/indra/newview/app_settings/shaders/class1/deferred/waterV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void calcAtmospherics(vec3 inPositionEye);
diff --git a/indra/newview/app_settings/shaders/class1/effects/glowExtractF.glsl b/indra/newview/app_settings/shaders/class1/effects/glowExtractF.glsl
index 2d40a19fa6..f2023fa5ea 100644
--- a/indra/newview/app_settings/shaders/class1/effects/glowExtractF.glsl
+++ b/indra/newview/app_settings/shaders/class1/effects/glowExtractF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class1/effects/glowExtractV.glsl b/indra/newview/app_settings/shaders/class1/effects/glowExtractV.glsl
index fe45898ed2..0ca0608b45 100644
--- a/indra/newview/app_settings/shaders/class1/effects/glowExtractV.glsl
+++ b/indra/newview/app_settings/shaders/class1/effects/glowExtractV.glsl
@@ -5,6 +5,7 @@
* $/LicenseInfo$
*/
+#version 120
void main()
{
diff --git a/indra/newview/app_settings/shaders/class1/effects/glowF.glsl b/indra/newview/app_settings/shaders/class1/effects/glowF.glsl
index 5b4e8b3ecc..65fc2e9f99 100644
--- a/indra/newview/app_settings/shaders/class1/effects/glowF.glsl
+++ b/indra/newview/app_settings/shaders/class1/effects/glowF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
uniform float glowStrength;
diff --git a/indra/newview/app_settings/shaders/class1/effects/glowV.glsl b/indra/newview/app_settings/shaders/class1/effects/glowV.glsl
index 97696e4719..0bd44cec90 100644
--- a/indra/newview/app_settings/shaders/class1/effects/glowV.glsl
+++ b/indra/newview/app_settings/shaders/class1/effects/glowV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform vec2 glowDelta;
diff --git a/indra/newview/app_settings/shaders/class1/environment/terrainF.glsl b/indra/newview/app_settings/shaders/class1/environment/terrainF.glsl
index 3a852239fb..ac00f15b35 100644
--- a/indra/newview/app_settings/shaders/class1/environment/terrainF.glsl
+++ b/indra/newview/app_settings/shaders/class1/environment/terrainF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D detail0;
uniform sampler2D detail1;
diff --git a/indra/newview/app_settings/shaders/class1/environment/terrainV.glsl b/indra/newview/app_settings/shaders/class1/environment/terrainV.glsl
index 0d781fd849..1e19ee7699 100644
--- a/indra/newview/app_settings/shaders/class1/environment/terrainV.glsl
+++ b/indra/newview/app_settings/shaders/class1/environment/terrainV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
diff --git a/indra/newview/app_settings/shaders/class1/environment/terrainWaterF.glsl b/indra/newview/app_settings/shaders/class1/environment/terrainWaterF.glsl
index 99c340d91a..34f78565a5 100644
--- a/indra/newview/app_settings/shaders/class1/environment/terrainWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class1/environment/terrainWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
// this class1 shader is just a copy of terrainF
diff --git a/indra/newview/app_settings/shaders/class1/environment/underWaterF.glsl b/indra/newview/app_settings/shaders/class1/environment/underWaterF.glsl
index 66458ec66d..0dfac84a6e 100644
--- a/indra/newview/app_settings/shaders/class1/environment/underWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class1/environment/underWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
uniform sampler2D bumpMap;
diff --git a/indra/newview/app_settings/shaders/class1/environment/waterF.glsl b/indra/newview/app_settings/shaders/class1/environment/waterF.glsl
index 5f1fbee1df..4e9c09b1ea 100644
--- a/indra/newview/app_settings/shaders/class1/environment/waterF.glsl
+++ b/indra/newview/app_settings/shaders/class1/environment/waterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec3 scaleSoftClip(vec3 inColor);
vec3 atmosTransport(vec3 inColor);
diff --git a/indra/newview/app_settings/shaders/class1/environment/waterFogF.glsl b/indra/newview/app_settings/shaders/class1/environment/waterFogF.glsl
index e5eb25f3fa..a34cf23790 100644
--- a/indra/newview/app_settings/shaders/class1/environment/waterFogF.glsl
+++ b/indra/newview/app_settings/shaders/class1/environment/waterFogF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 applyWaterFog(vec4 color)
{
diff --git a/indra/newview/app_settings/shaders/class1/environment/waterV.glsl b/indra/newview/app_settings/shaders/class1/environment/waterV.glsl
index 608a7a5807..161c794c68 100644
--- a/indra/newview/app_settings/shaders/class1/environment/waterV.glsl
+++ b/indra/newview/app_settings/shaders/class1/environment/waterV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void calcAtmospherics(vec3 inPositionEye);
diff --git a/indra/newview/app_settings/shaders/class1/interface/highlightF.glsl b/indra/newview/app_settings/shaders/class1/interface/highlightF.glsl
index 5ac9e96601..6f821f893d 100644
--- a/indra/newview/app_settings/shaders/class1/interface/highlightF.glsl
+++ b/indra/newview/app_settings/shaders/class1/interface/highlightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/interface/highlightV.glsl b/indra/newview/app_settings/shaders/class1/interface/highlightV.glsl
index c5f69c4ad4..d1c98bf70c 100644
--- a/indra/newview/app_settings/shaders/class1/interface/highlightV.glsl
+++ b/indra/newview/app_settings/shaders/class1/interface/highlightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void main()
{
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightF.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightF.glsl
index ad128dae8d..9c59e8c3ad 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightF.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightF.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightF.glsl
index 1742b9fc1c..1fee99c446 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightF.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightShinyF.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightShinyF.glsl
index 68b6603b4a..fb5da21c72 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightShinyF.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightShinyF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightShinyWaterF.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightShinyWaterF.glsl
new file mode 100644
index 0000000000..1bdaccf9b8
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightShinyWaterF.glsl
@@ -0,0 +1,17 @@
+/**
+ * @file lightFullbrightShinyWaterF.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+
+#version 120
+
+uniform sampler2D diffuseMap;
+uniform samplerCube environmentMap;
+
+void fullbright_shiny_lighting_water()
+{
+ gl_FragColor = texture2D(diffuseMap, gl_TexCoord[0].xy);
+}
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightWaterF.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightWaterF.glsl
index 693ed289f2..2e94d3bbf1 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightFullbrightWaterF.glsl
@@ -5,6 +5,8 @@
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightFuncSpecularV.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightFuncSpecularV.glsl
index b888e70325..714f9a2551 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightFuncSpecularV.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightFuncSpecularV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
float calcDirectionalLight(vec3 n, vec3 l)
{
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightFuncV.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightFuncV.glsl
index 4b6d95e177..65b45f8081 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightFuncV.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightFuncV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
float calcDirectionalLight(vec3 n, vec3 l)
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightShinyF.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightShinyF.glsl
index b127b1f8ea..7f65ea76f7 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightShinyF.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightShinyF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightShinyWaterF.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightShinyWaterF.glsl
index 05ad3256af..8f13e6dc04 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightShinyWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightShinyWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightSpecularV.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightSpecularV.glsl
index b1a7cb46ff..56f31f6a79 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightSpecularV.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightSpecularV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
float calcDirectionalLight(vec3 n, vec3 l);
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightV.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightV.glsl
index f6afa6a3ae..64d549ff52 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightV.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
float calcDirectionalLight(vec3 n, vec3 l);
diff --git a/indra/newview/app_settings/shaders/class1/lighting/lightWaterF.glsl b/indra/newview/app_settings/shaders/class1/lighting/lightWaterF.glsl
index e5e6ddc2d8..c5d084c132 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/lightWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/lightWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class1/lighting/sumLightsSpecularV.glsl b/indra/newview/app_settings/shaders/class1/lighting/sumLightsSpecularV.glsl
index a0649aea88..732d246471 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/sumLightsSpecularV.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/sumLightsSpecularV.glsl
@@ -4,6 +4,9 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
+
float calcDirectionalLightSpecular(inout vec4 specular, vec3 view, vec3 n, vec3 l, vec3 lightCol, float da);
vec3 atmosAmbient(vec3 light);
vec3 atmosAffectDirectionalLight(float lightIntensity);
diff --git a/indra/newview/app_settings/shaders/class1/lighting/sumLightsV.glsl b/indra/newview/app_settings/shaders/class1/lighting/sumLightsV.glsl
index c7d40d853f..73e1a1ec26 100644
--- a/indra/newview/app_settings/shaders/class1/lighting/sumLightsV.glsl
+++ b/indra/newview/app_settings/shaders/class1/lighting/sumLightsV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
float calcDirectionalLight(vec3 n, vec3 l);
diff --git a/indra/newview/app_settings/shaders/class1/objects/fullbrightF.glsl b/indra/newview/app_settings/shaders/class1/objects/fullbrightF.glsl
index 9da4c2c92b..afc3dc89bf 100644
--- a/indra/newview/app_settings/shaders/class1/objects/fullbrightF.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/fullbrightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void fullbright_lighting();
diff --git a/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyF.glsl b/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyF.glsl
index 1c8a9a1a30..3dc4294f67 100644
--- a/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyF.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void fullbright_shiny_lighting();
diff --git a/indra/newview/app_settings/shaders/class1/objects/fullbrightShinySkinnedV.glsl b/indra/newview/app_settings/shaders/class1/objects/fullbrightShinySkinnedV.glsl
new file mode 100644
index 0000000000..f0baeeeee5
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/objects/fullbrightShinySkinnedV.glsl
@@ -0,0 +1,39 @@
+/**
+ * @file shinySimpleSkinnedV.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+void calcAtmospherics(vec3 inPositionEye);
+mat4 getObjectSkinnedTransform();
+
+attribute vec4 object_weight;
+
+void main()
+{
+ mat4 mat = getObjectSkinnedTransform();
+
+ mat = gl_ModelViewMatrix * mat;
+ vec3 pos = (mat*gl_Vertex).xyz;
+
+ vec4 norm = gl_Vertex;
+ norm.xyz += gl_Normal.xyz;
+ norm.xyz = (mat*norm).xyz;
+ norm.xyz = normalize(norm.xyz-pos.xyz);
+
+ vec3 ref = reflect(pos.xyz, -norm.xyz);
+
+ gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
+ gl_TexCoord[1] = gl_TextureMatrix[1]*vec4(ref,1.0);
+
+ calcAtmospherics(pos.xyz);
+
+ gl_FrontColor = gl_Color;
+
+ gl_Position = gl_ProjectionMatrix*vec4(pos, 1.0);
+
+ gl_FogFragCoord = pos.z;
+}
diff --git a/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyV.glsl b/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyV.glsl
index 032def63b3..02367b9439 100644
--- a/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyV.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void calcAtmospherics(vec3 inPositionEye);
diff --git a/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyWaterF.glsl b/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyWaterF.glsl
new file mode 100644
index 0000000000..5daf66fb31
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/objects/fullbrightShinyWaterF.glsl
@@ -0,0 +1,15 @@
+/**
+ * @file fullbrightShinyWaterF.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+void fullbright_shiny_lighting_water();
+
+void main()
+{
+ fullbright_shiny_lighting_water();
+}
diff --git a/indra/newview/app_settings/shaders/class1/objects/fullbrightSkinnedV.glsl b/indra/newview/app_settings/shaders/class1/objects/fullbrightSkinnedV.glsl
new file mode 100644
index 0000000000..02ff3cc2a9
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/objects/fullbrightSkinnedV.glsl
@@ -0,0 +1,37 @@
+/**
+ * @file fullbrightSkinnedV.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+void calcAtmospherics(vec3 inPositionEye);
+mat4 getObjectSkinnedTransform();
+
+attribute vec4 object_weight;
+
+void main()
+{
+ //transform vertex
+ gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
+
+ mat4 mat = getObjectSkinnedTransform();
+
+ mat = gl_ModelViewMatrix * mat;
+ vec3 pos = (mat*gl_Vertex).xyz;
+
+ vec4 norm = gl_Vertex;
+ norm.xyz += gl_Normal.xyz;
+ norm.xyz = (mat*norm).xyz;
+ norm.xyz = normalize(norm.xyz-pos.xyz);
+
+ calcAtmospherics(pos.xyz);
+
+ gl_FrontColor = gl_Color;
+
+ gl_Position = gl_ProjectionMatrix*vec4(pos, 1.0);
+
+ gl_FogFragCoord = pos.z;
+}
diff --git a/indra/newview/app_settings/shaders/class1/objects/fullbrightV.glsl b/indra/newview/app_settings/shaders/class1/objects/fullbrightV.glsl
index 914e417ca0..38e07dbd80 100644
--- a/indra/newview/app_settings/shaders/class1/objects/fullbrightV.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/fullbrightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void calcAtmospherics(vec3 inPositionEye);
diff --git a/indra/newview/app_settings/shaders/class1/objects/fullbrightWaterF.glsl b/indra/newview/app_settings/shaders/class1/objects/fullbrightWaterF.glsl
index df76e9e1eb..afaac4f69c 100644
--- a/indra/newview/app_settings/shaders/class1/objects/fullbrightWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/fullbrightWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void fullbright_lighting_water();
diff --git a/indra/newview/app_settings/shaders/class1/objects/shinyF.glsl b/indra/newview/app_settings/shaders/class1/objects/shinyF.glsl
index 6bcd44506d..2cf7a69baa 100644
--- a/indra/newview/app_settings/shaders/class1/objects/shinyF.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/shinyF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void shiny_lighting();
diff --git a/indra/newview/app_settings/shaders/class1/objects/shinySimpleSkinnedV.glsl b/indra/newview/app_settings/shaders/class1/objects/shinySimpleSkinnedV.glsl
new file mode 100644
index 0000000000..4146646058
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/objects/shinySimpleSkinnedV.glsl
@@ -0,0 +1,39 @@
+/**
+ * @file shinySimpleSkinnedV.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
+void calcAtmospherics(vec3 inPositionEye);
+mat4 getObjectSkinnedTransform();
+
+attribute vec4 object_weight;
+
+void main()
+{
+ mat4 mat = getObjectSkinnedTransform();
+
+ mat = gl_ModelViewMatrix * mat;
+ vec3 pos = (mat*gl_Vertex).xyz;
+
+ vec4 norm = gl_Vertex;
+ norm.xyz += gl_Normal.xyz;
+ norm.xyz = (mat*norm).xyz;
+ norm.xyz = normalize(norm.xyz-pos.xyz);
+
+ vec3 ref = reflect(pos.xyz, -norm.xyz);
+
+ gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
+ gl_TexCoord[1] = gl_TextureMatrix[1]*vec4(ref,1.0);
+
+ calcAtmospherics(pos.xyz);
+
+ vec4 color = calcLighting(pos.xyz, norm.xyz, gl_Color, vec4(0.));
+ gl_FrontColor = color;
+
+ gl_Position = gl_ProjectionMatrix*vec4(pos, 1.0);
+}
diff --git a/indra/newview/app_settings/shaders/class1/objects/shinyV.glsl b/indra/newview/app_settings/shaders/class1/objects/shinyV.glsl
index 074892c98e..6ea83b721d 100644
--- a/indra/newview/app_settings/shaders/class1/objects/shinyV.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/shinyV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void calcAtmospherics(vec3 inPositionEye);
@@ -12,7 +14,7 @@ uniform vec4 origin;
void main()
{
//transform vertex
- gl_Position = ftransform(); //gl_ModelViewProjectionMatrix * gl_Vertex;
+ gl_Position = ftransform();
vec4 pos = (gl_ModelViewMatrix * gl_Vertex);
vec3 norm = normalize(gl_NormalMatrix * gl_Normal);
diff --git a/indra/newview/app_settings/shaders/class1/objects/shinyWaterF.glsl b/indra/newview/app_settings/shaders/class1/objects/shinyWaterF.glsl
index 54b30573e7..e3babe2210 100644
--- a/indra/newview/app_settings/shaders/class1/objects/shinyWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/shinyWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void shiny_lighting_water();
diff --git a/indra/newview/app_settings/shaders/class1/objects/simpleF.glsl b/indra/newview/app_settings/shaders/class1/objects/simpleF.glsl
index 61c2ce4272..d449d37c0c 100644
--- a/indra/newview/app_settings/shaders/class1/objects/simpleF.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/simpleF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void default_lighting();
diff --git a/indra/newview/app_settings/shaders/class1/objects/simpleSkinnedV.glsl b/indra/newview/app_settings/shaders/class1/objects/simpleSkinnedV.glsl
new file mode 100644
index 0000000000..be38a14d52
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class1/objects/simpleSkinnedV.glsl
@@ -0,0 +1,39 @@
+/**
+ * @file simpleSkinnedV.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
+void calcAtmospherics(vec3 inPositionEye);
+mat4 getObjectSkinnedTransform();
+
+attribute vec4 object_weight;
+
+void main()
+{
+ //transform vertex
+ gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
+
+ mat4 mat = getObjectSkinnedTransform();
+
+ mat = gl_ModelViewMatrix * mat;
+ vec3 pos = (mat*gl_Vertex).xyz;
+
+ vec4 norm = gl_Vertex;
+ norm.xyz += gl_Normal.xyz;
+ norm.xyz = (mat*norm).xyz;
+ norm.xyz = normalize(norm.xyz-pos.xyz);
+
+ calcAtmospherics(pos.xyz);
+
+ vec4 color = calcLighting(pos.xyz, norm.xyz, gl_Color, vec4(0.));
+ gl_FrontColor = color;
+
+ gl_Position = gl_ProjectionMatrix*vec4(pos, 1.0);
+
+ gl_FogFragCoord = pos.z;
+}
diff --git a/indra/newview/app_settings/shaders/class1/objects/simpleV.glsl b/indra/newview/app_settings/shaders/class1/objects/simpleV.glsl
index ced1a4be01..0d8e14e2e3 100644
--- a/indra/newview/app_settings/shaders/class1/objects/simpleV.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/simpleV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
void calcAtmospherics(vec3 inPositionEye);
diff --git a/indra/newview/app_settings/shaders/class1/objects/simpleWaterF.glsl b/indra/newview/app_settings/shaders/class1/objects/simpleWaterF.glsl
index 5e44212aed..68bd81e029 100644
--- a/indra/newview/app_settings/shaders/class1/objects/simpleWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class1/objects/simpleWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void default_lighting_water();
diff --git a/indra/newview/app_settings/shaders/class1/windlight/atmosphericsF.glsl b/indra/newview/app_settings/shaders/class1/windlight/atmosphericsF.glsl
index 7a05b8c8c6..f337bde329 100644
--- a/indra/newview/app_settings/shaders/class1/windlight/atmosphericsF.glsl
+++ b/indra/newview/app_settings/shaders/class1/windlight/atmosphericsF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec3 atmosLighting(vec3 light)
{
diff --git a/indra/newview/app_settings/shaders/class1/windlight/atmosphericsHelpersV.glsl b/indra/newview/app_settings/shaders/class1/windlight/atmosphericsHelpersV.glsl
index 874f2b4843..4b402a7028 100644
--- a/indra/newview/app_settings/shaders/class1/windlight/atmosphericsHelpersV.glsl
+++ b/indra/newview/app_settings/shaders/class1/windlight/atmosphericsHelpersV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec3 atmosAmbient(vec3 light)
{
diff --git a/indra/newview/app_settings/shaders/class1/windlight/atmosphericsV.glsl b/indra/newview/app_settings/shaders/class1/windlight/atmosphericsV.glsl
index 7ead9ddf26..20948b1e46 100644
--- a/indra/newview/app_settings/shaders/class1/windlight/atmosphericsV.glsl
+++ b/indra/newview/app_settings/shaders/class1/windlight/atmosphericsV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void setPositionEye(vec3 v);
diff --git a/indra/newview/app_settings/shaders/class1/windlight/atmosphericsVarsF.glsl b/indra/newview/app_settings/shaders/class1/windlight/atmosphericsVarsF.glsl
index f6032f8d41..8a2c2a7186 100644
--- a/indra/newview/app_settings/shaders/class1/windlight/atmosphericsVarsF.glsl
+++ b/indra/newview/app_settings/shaders/class1/windlight/atmosphericsVarsF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec3 vary_PositionEye;
diff --git a/indra/newview/app_settings/shaders/class1/windlight/atmosphericsVarsV.glsl b/indra/newview/app_settings/shaders/class1/windlight/atmosphericsVarsV.glsl
index a696ddf607..a1dd4ed5fe 100644
--- a/indra/newview/app_settings/shaders/class1/windlight/atmosphericsVarsV.glsl
+++ b/indra/newview/app_settings/shaders/class1/windlight/atmosphericsVarsV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec3 vary_PositionEye;
diff --git a/indra/newview/app_settings/shaders/class1/windlight/gammaF.glsl b/indra/newview/app_settings/shaders/class1/windlight/gammaF.glsl
index 4a1899798a..7aed1fd3b5 100644
--- a/indra/newview/app_settings/shaders/class1/windlight/gammaF.glsl
+++ b/indra/newview/app_settings/shaders/class1/windlight/gammaF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform vec4 gamma;
diff --git a/indra/newview/app_settings/shaders/class1/windlight/transportF.glsl b/indra/newview/app_settings/shaders/class1/windlight/transportF.glsl
index b78b90545e..6780dc4d3e 100644
--- a/indra/newview/app_settings/shaders/class1/windlight/transportF.glsl
+++ b/indra/newview/app_settings/shaders/class1/windlight/transportF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec3 atmosTransport(vec3 light)
{
diff --git a/indra/newview/app_settings/shaders/class2/avatar/eyeballV.glsl b/indra/newview/app_settings/shaders/class2/avatar/eyeballV.glsl
index 47300f0b39..172c2ca078 100644
--- a/indra/newview/app_settings/shaders/class2/avatar/eyeballV.glsl
+++ b/indra/newview/app_settings/shaders/class2/avatar/eyeballV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 calcLightingSpecular(vec3 pos, vec3 norm, vec4 color, inout vec4 specularColor, vec4 baseCol);
void calcAtmospherics(vec3 inPositionEye);
diff --git a/indra/newview/app_settings/shaders/class2/deferred/alphaF.glsl b/indra/newview/app_settings/shaders/class2/deferred/alphaF.glsl
index e2d7cd94da..32aab152a3 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/alphaF.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/alphaF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
@@ -115,7 +117,7 @@ void main()
//gl_FragColor = gl_Color;
gl_FragColor = color;
- //gl_FragColor = vec4(1,0,1,1)*shadow;
+ //gl_FragColor = vec4(1,shadow,1,1);
}
diff --git a/indra/newview/app_settings/shaders/class2/deferred/alphaSkinnedV.glsl b/indra/newview/app_settings/shaders/class2/deferred/alphaSkinnedV.glsl
new file mode 100644
index 0000000000..1da3d95069
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class2/deferred/alphaSkinnedV.glsl
@@ -0,0 +1,86 @@
+/**
+ * @file alphaSkinnedV.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
+void calcAtmospherics(vec3 inPositionEye);
+
+float calcDirectionalLight(vec3 n, vec3 l);
+float calcPointLightOrSpotLight(vec3 v, vec3 n, vec4 lp, vec3 ln, float la, float is_pointlight);
+mat4 getObjectSkinnedTransform();
+vec3 atmosAmbient(vec3 light);
+vec3 atmosAffectDirectionalLight(float lightIntensity);
+vec3 scaleDownLight(vec3 light);
+vec3 scaleUpLight(vec3 light);
+
+varying vec3 vary_ambient;
+varying vec3 vary_directional;
+varying vec3 vary_fragcoord;
+varying vec3 vary_position;
+varying vec3 vary_light;
+
+uniform float near_clip;
+uniform float shadow_offset;
+uniform float shadow_bias;
+
+void main()
+{
+ gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
+
+ mat4 mat = getObjectSkinnedTransform();
+
+ mat = gl_ModelViewMatrix * mat;
+
+ vec3 pos = (mat*gl_Vertex).xyz;
+
+ gl_Position = gl_ProjectionMatrix * vec4(pos, 1.0);
+
+ vec4 n = gl_Vertex;
+ n.xyz += gl_Normal.xyz;
+ n.xyz = (mat*n).xyz;
+ n.xyz = normalize(n.xyz-pos.xyz);
+
+ vec3 norm = n.xyz;
+
+ float dp_directional_light = max(0.0, dot(norm, gl_LightSource[0].position.xyz));
+ vary_position = pos.xyz + gl_LightSource[0].position.xyz * (1.0-dp_directional_light)*shadow_offset;
+
+ calcAtmospherics(pos.xyz);
+
+ //vec4 color = calcLighting(pos.xyz, norm, gl_Color, vec4(0.));
+ vec4 col = vec4(0.0, 0.0, 0.0, gl_Color.a);
+
+ // Collect normal lights (need to be divided by two, as we later multiply by 2)
+ col.rgb += gl_LightSource[2].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[2].position, gl_LightSource[2].spotDirection.xyz, gl_LightSource[2].linearAttenuation, gl_LightSource[2].specular.a);
+ col.rgb += gl_LightSource[3].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[3].position, gl_LightSource[3].spotDirection.xyz, gl_LightSource[3].linearAttenuation, gl_LightSource[3].specular.a);
+ col.rgb += gl_LightSource[4].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[4].position, gl_LightSource[4].spotDirection.xyz, gl_LightSource[4].linearAttenuation, gl_LightSource[4].specular.a);
+ col.rgb += gl_LightSource[5].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[5].position, gl_LightSource[5].spotDirection.xyz, gl_LightSource[5].linearAttenuation, gl_LightSource[5].specular.a);
+ col.rgb += gl_LightSource[6].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[6].position, gl_LightSource[6].spotDirection.xyz, gl_LightSource[6].linearAttenuation, gl_LightSource[6].specular.a);
+ col.rgb += gl_LightSource[7].diffuse.rgb*calcPointLightOrSpotLight(pos.xyz, norm, gl_LightSource[7].position, gl_LightSource[7].spotDirection.xyz, gl_LightSource[7].linearAttenuation, gl_LightSource[7].specular.a);
+ col.rgb += gl_LightSource[1].diffuse.rgb*calcDirectionalLight(norm, gl_LightSource[1].position.xyz);
+ col.rgb = scaleDownLight(col.rgb);
+
+ // Add windlight lights
+ col.rgb += atmosAmbient(vec3(0.));
+
+ vary_light = gl_LightSource[0].position.xyz;
+
+ vary_ambient = col.rgb*gl_Color.rgb;
+ vary_directional.rgb = gl_Color.rgb*atmosAffectDirectionalLight(max(calcDirectionalLight(norm, gl_LightSource[0].position.xyz), (1.0-gl_Color.a)*(1.0-gl_Color.a)));
+
+ col.rgb = min(col.rgb*gl_Color.rgb, 1.0);
+
+ gl_FrontColor = col;
+
+ gl_FogFragCoord = pos.z;
+
+ pos.xyz = (gl_ModelViewProjectionMatrix * gl_Vertex).xyz;
+ vary_fragcoord.xyz = pos.xyz + vec3(0,0,near_clip);
+
+}
+
diff --git a/indra/newview/app_settings/shaders/class2/deferred/alphaV.glsl b/indra/newview/app_settings/shaders/class2/deferred/alphaV.glsl
index 45f727951e..92f1cb22d6 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/alphaV.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/alphaV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
void calcAtmospherics(vec3 inPositionEye);
diff --git a/indra/newview/app_settings/shaders/class2/deferred/avatarAlphaF.glsl b/indra/newview/app_settings/shaders/class2/deferred/avatarAlphaF.glsl
index 5ecbbd2c4f..4671a54078 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/avatarAlphaF.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/avatarAlphaF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class2/deferred/avatarAlphaV.glsl b/indra/newview/app_settings/shaders/class2/deferred/avatarAlphaV.glsl
index d7d1111ba8..30954a8677 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/avatarAlphaV.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/avatarAlphaV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
mat4 getSkinnedTransform();
@@ -21,6 +23,7 @@ varying vec3 vary_position;
varying vec3 vary_ambient;
varying vec3 vary_directional;
varying vec3 vary_normal;
+varying vec3 vary_fragcoord;
uniform float near_clip;
uniform float shadow_offset;
@@ -77,7 +80,7 @@ void main()
gl_FrontColor = col;
gl_FogFragCoord = pos.z;
-
+ vary_fragcoord.xyz = pos.xyz + vec3(0,0,near_clip);
}
diff --git a/indra/newview/app_settings/shaders/class2/deferred/blurLightF.glsl b/indra/newview/app_settings/shaders/class2/deferred/blurLightF.glsl
index 258a9b7c40..ea2df4b51a 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/blurLightF.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/blurLightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class2/deferred/blurLightV.glsl b/indra/newview/app_settings/shaders/class2/deferred/blurLightV.glsl
index b1b3f55f00..c2d05c601a 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/blurLightV.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/blurLightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class2/deferred/edgeF.glsl b/indra/newview/app_settings/shaders/class2/deferred/edgeF.glsl
index ff32a15c54..3155f3f929 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/edgeF.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/edgeF.glsl
@@ -4,14 +4,14 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
uniform sampler2DRect depthMap;
uniform sampler2DRect normalMap;
-uniform float gi_dist_cutoff;
-
varying vec2 vary_fragcoord;
uniform float depth_cutoff;
diff --git a/indra/newview/app_settings/shaders/class2/deferred/edgeV.glsl b/indra/newview/app_settings/shaders/class2/deferred/edgeV.glsl
index 74f2bd9818..b3413c301f 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/edgeV.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/edgeV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class2/deferred/postDeferredF.glsl b/indra/newview/app_settings/shaders/class2/deferred/postDeferredF.glsl
deleted file mode 100644
index 757e3e7aab..0000000000
--- a/indra/newview/app_settings/shaders/class2/deferred/postDeferredF.glsl
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * @file postDeferredF.glsl
- *
- * $LicenseInfo:firstyear=2007&license=viewerlgpl$
- * $/LicenseInfo$
- */
-
-uniform sampler2DRect diffuseRect;
-uniform sampler2DRect localLightMap;
-uniform sampler2DRect sunLightMap;
-uniform sampler2DRect giLightMap;
-uniform sampler2D luminanceMap;
-uniform sampler2DRect lightMap;
-
-uniform vec3 gi_lum_quad;
-uniform vec3 sun_lum_quad;
-uniform vec3 lum_quad;
-uniform float lum_lod;
-uniform vec4 ambient;
-
-uniform vec3 gi_quad;
-
-uniform vec2 screen_res;
-varying vec2 vary_fragcoord;
-
-void main()
-{
- vec2 tc = vary_fragcoord.xy;
- vec3 lcol = texture2DLod(luminanceMap, tc/screen_res, lum_lod).rgb;
-
- float lum = sqrt(lcol.r)*lum_quad.x+lcol.r*lcol.r*lum_quad.y+lcol.r*lum_quad.z;
-
- vec4 diff = texture2DRect(diffuseRect, vary_fragcoord.xy);
-
- float ambocc = texture2DRect(lightMap, vary_fragcoord.xy).g;
-
- vec3 gi_col = texture2DRect(giLightMap, vary_fragcoord.xy).rgb;
- gi_col = gi_col*gi_col*gi_quad.x + gi_col*gi_quad.y+gi_quad.z*ambocc*ambient.rgb;
- gi_col *= diff;
-
- vec4 sun_col = texture2DRect(sunLightMap, vary_fragcoord.xy);
-
- vec3 local_col = texture2DRect(localLightMap, vary_fragcoord.xy).rgb;
-
-
- float sun_lum = 1.0-lum;
- sun_lum = sun_lum*sun_lum*sun_lum_quad.x + sun_lum*sun_lum_quad.y+sun_lum_quad.z;
-
- float gi_lum = lum;
- gi_lum = gi_lum*gi_lum*gi_lum_quad.x+gi_lum*gi_lum_quad.y+gi_lum_quad.z;
- gi_col *= 1.0/gi_lum;
-
- vec3 col = sun_col.rgb*(1.0+max(sun_lum,0.0))+gi_col+local_col;
-
- gl_FragColor.rgb = col.rgb;
- gl_FragColor.a = max(sun_lum*min(sun_col.r+sun_col.g+sun_col.b, 1.0), sun_col.a);
-
- //gl_FragColor.rgb = texture2DRect(giLightMap, vary_fragcoord.xy).rgb;
-}
diff --git a/indra/newview/app_settings/shaders/class2/deferred/postDeferredV.glsl b/indra/newview/app_settings/shaders/class2/deferred/postDeferredV.glsl
deleted file mode 100644
index 0ec81dcb02..0000000000
--- a/indra/newview/app_settings/shaders/class2/deferred/postDeferredV.glsl
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * @file postDeferredV.glsl
- *
- * $LicenseInfo:firstyear=2007&license=viewerlgpl$
- * $/LicenseInfo$
- */
-
-varying vec2 vary_fragcoord;
-uniform vec2 screen_res;
-
-void main()
-{
- //transform vertex
- gl_Position = ftransform();
- vec4 pos = gl_ModelViewProjectionMatrix * gl_Vertex;
- vary_fragcoord = (pos.xy*0.5+0.5)*screen_res;
-}
diff --git a/indra/newview/app_settings/shaders/class2/deferred/softenLightF.glsl b/indra/newview/app_settings/shaders/class2/deferred/softenLightF.glsl
index 1067be1e6e..0160e84278 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/softenLightF.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/softenLightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class2/deferred/softenLightV.glsl b/indra/newview/app_settings/shaders/class2/deferred/softenLightV.glsl
index 9d187b46e2..8f0bcca76b 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/softenLightV.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/softenLightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class2/deferred/spotLightF.glsl b/indra/newview/app_settings/shaders/class2/deferred/spotLightF.glsl
index d0e242c2d4..50b9ef276e 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/spotLightF.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/spotLightF.glsl
@@ -4,7 +4,7 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
-
+
#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class2/deferred/sunLightF.glsl b/indra/newview/app_settings/shaders/class2/deferred/sunLightF.glsl
index f565d3bdb9..26bc83e0d4 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/sunLightF.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/sunLightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class2/deferred/sunLightSSAOF.glsl b/indra/newview/app_settings/shaders/class2/deferred/sunLightSSAOF.glsl
index 4e33a1af45..cc921f23d7 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/sunLightSSAOF.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/sunLightSSAOF.glsl
@@ -4,6 +4,8 @@
* Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
* $License$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class2/deferred/sunLightV.glsl b/indra/newview/app_settings/shaders/class2/deferred/sunLightV.glsl
index 9d092d9cea..9beb513ad8 100644
--- a/indra/newview/app_settings/shaders/class2/deferred/sunLightV.glsl
+++ b/indra/newview/app_settings/shaders/class2/deferred/sunLightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec4 vary_light;
varying vec2 vary_fragcoord;
diff --git a/indra/newview/app_settings/shaders/class2/effects/blurF.glsl b/indra/newview/app_settings/shaders/class2/effects/blurF.glsl
index 4173709298..a4ad0bfa15 100644
--- a/indra/newview/app_settings/shaders/class2/effects/blurF.glsl
+++ b/indra/newview/app_settings/shaders/class2/effects/blurF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2DRect RenderTexture;
uniform float bloomStrength;
diff --git a/indra/newview/app_settings/shaders/class2/effects/blurV.glsl b/indra/newview/app_settings/shaders/class2/effects/blurV.glsl
index f66609527d..d471a6c5e5 100644
--- a/indra/newview/app_settings/shaders/class2/effects/blurV.glsl
+++ b/indra/newview/app_settings/shaders/class2/effects/blurV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform vec2 texelSize;
uniform vec2 blurDirection;
diff --git a/indra/newview/app_settings/shaders/class2/effects/colorFilterF.glsl b/indra/newview/app_settings/shaders/class2/effects/colorFilterF.glsl
index df41dae757..66880b958e 100644
--- a/indra/newview/app_settings/shaders/class2/effects/colorFilterF.glsl
+++ b/indra/newview/app_settings/shaders/class2/effects/colorFilterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2DRect RenderTexture;
uniform float brightness;
diff --git a/indra/newview/app_settings/shaders/class2/effects/drawQuadV.glsl b/indra/newview/app_settings/shaders/class2/effects/drawQuadV.glsl
index e836caf93f..c35c500d62 100644
--- a/indra/newview/app_settings/shaders/class2/effects/drawQuadV.glsl
+++ b/indra/newview/app_settings/shaders/class2/effects/drawQuadV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void main(void)
{
diff --git a/indra/newview/app_settings/shaders/class2/effects/extractF.glsl b/indra/newview/app_settings/shaders/class2/effects/extractF.glsl
index 06d5fc9797..e77baa5bee 100644
--- a/indra/newview/app_settings/shaders/class2/effects/extractF.glsl
+++ b/indra/newview/app_settings/shaders/class2/effects/extractF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2DRect RenderTexture;
uniform float extractLow;
diff --git a/indra/newview/app_settings/shaders/class2/effects/nightVisionF.glsl b/indra/newview/app_settings/shaders/class2/effects/nightVisionF.glsl
index 0a2767ad02..8e0eec6f5e 100644
--- a/indra/newview/app_settings/shaders/class2/effects/nightVisionF.glsl
+++ b/indra/newview/app_settings/shaders/class2/effects/nightVisionF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2DRect RenderTexture;
uniform sampler2D NoiseTexture;
diff --git a/indra/newview/app_settings/shaders/class2/effects/simpleF.glsl b/indra/newview/app_settings/shaders/class2/effects/simpleF.glsl
index 29ad9a995b..98a50e22fc 100644
--- a/indra/newview/app_settings/shaders/class2/effects/simpleF.glsl
+++ b/indra/newview/app_settings/shaders/class2/effects/simpleF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2DRect RenderTexture;
diff --git a/indra/newview/app_settings/shaders/class2/environment/terrainF.glsl b/indra/newview/app_settings/shaders/class2/environment/terrainF.glsl
index 32259acf1b..bbb8951f3a 100644
--- a/indra/newview/app_settings/shaders/class2/environment/terrainF.glsl
+++ b/indra/newview/app_settings/shaders/class2/environment/terrainF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D detail_0;
uniform sampler2D detail_1;
diff --git a/indra/newview/app_settings/shaders/class2/environment/terrainV.glsl b/indra/newview/app_settings/shaders/class2/environment/terrainV.glsl
index 2234f0bd89..84906c16bf 100644
--- a/indra/newview/app_settings/shaders/class2/environment/terrainV.glsl
+++ b/indra/newview/app_settings/shaders/class2/environment/terrainV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
void calcAtmospherics(vec3 inPositionEye);
diff --git a/indra/newview/app_settings/shaders/class2/environment/terrainWaterF.glsl b/indra/newview/app_settings/shaders/class2/environment/terrainWaterF.glsl
index 1650912fc8..7590c542ef 100644
--- a/indra/newview/app_settings/shaders/class2/environment/terrainWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class2/environment/terrainWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D detail_0;
uniform sampler2D detail_1;
diff --git a/indra/newview/app_settings/shaders/class2/environment/underWaterF.glsl b/indra/newview/app_settings/shaders/class2/environment/underWaterF.glsl
index 9e936a3790..900f1a6cb8 100644
--- a/indra/newview/app_settings/shaders/class2/environment/underWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class2/environment/underWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
uniform sampler2D bumpMap;
diff --git a/indra/newview/app_settings/shaders/class2/environment/waterF.glsl b/indra/newview/app_settings/shaders/class2/environment/waterF.glsl
index e477107c0b..f4f6b6e90f 100644
--- a/indra/newview/app_settings/shaders/class2/environment/waterF.glsl
+++ b/indra/newview/app_settings/shaders/class2/environment/waterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec3 scaleSoftClip(vec3 inColor);
vec3 atmosTransport(vec3 inColor);
diff --git a/indra/newview/app_settings/shaders/class2/environment/waterFogF.glsl b/indra/newview/app_settings/shaders/class2/environment/waterFogF.glsl
index 7bcdcf5d5b..9f3328cbf0 100644
--- a/indra/newview/app_settings/shaders/class2/environment/waterFogF.glsl
+++ b/indra/newview/app_settings/shaders/class2/environment/waterFogF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform vec4 lightnorm;
uniform vec4 waterPlane;
diff --git a/indra/newview/app_settings/shaders/class2/lighting/lightF.glsl b/indra/newview/app_settings/shaders/class2/lighting/lightF.glsl
index 269d11a085..342bc2ab66 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/lightF.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/lightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightF.glsl b/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightF.glsl
index 9ffe3c6f4a..dad18b5883 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightF.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightShinyF.glsl b/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightShinyF.glsl
index b7181dec3a..73ff81e03a 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightShinyF.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightShinyF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
uniform samplerCube environmentMap;
diff --git a/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightShinyWaterF.glsl b/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightShinyWaterF.glsl
new file mode 100644
index 0000000000..9b4b584369
--- /dev/null
+++ b/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightShinyWaterF.glsl
@@ -0,0 +1,31 @@
+/**
+ * @file lightFullbrightShinyWaterF.glsl
+ *
+ * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
+ * $License$
+ */
+
+#version 120
+
+uniform sampler2D diffuseMap;
+uniform samplerCube environmentMap;
+
+vec3 fullbrightShinyAtmosTransport(vec3 light);
+vec3 fullbrightScaleSoftClip(vec3 light);
+vec4 applyWaterFog(vec4 color);
+
+void fullbright_shiny_lighting_water()
+{
+ vec4 color = texture2D(diffuseMap, gl_TexCoord[0].xy);
+ color.rgb *= gl_Color.rgb;
+
+ vec3 envColor = textureCube(environmentMap, gl_TexCoord[1].xyz).rgb;
+ color.rgb = mix(color.rgb, envColor.rgb, gl_Color.a);
+
+ color.rgb = fullbrightShinyAtmosTransport(color.rgb);
+ color.rgb = fullbrightScaleSoftClip(color.rgb);
+ color.a = max(color.a, gl_Color.a);
+
+ gl_FragColor = applyWaterFog(color);
+}
+
diff --git a/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightWaterF.glsl b/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightWaterF.glsl
index ee38790cc4..3d46c8d874 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/lightFullbrightWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class2/lighting/lightShinyF.glsl b/indra/newview/app_settings/shaders/class2/lighting/lightShinyF.glsl
index b96b5d75bc..ebe21320b4 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/lightShinyF.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/lightShinyF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
uniform samplerCube environmentMap;
diff --git a/indra/newview/app_settings/shaders/class2/lighting/lightShinyWaterF.glsl b/indra/newview/app_settings/shaders/class2/lighting/lightShinyWaterF.glsl
index 0f5b2d6fcf..7f48e2cf1d 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/lightShinyWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/lightShinyWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class2/lighting/lightSpecularV.glsl b/indra/newview/app_settings/shaders/class2/lighting/lightSpecularV.glsl
index 6400b45d9e..ad1dc4da77 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/lightSpecularV.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/lightSpecularV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
// All lights, no specular highlights
diff --git a/indra/newview/app_settings/shaders/class2/lighting/lightV.glsl b/indra/newview/app_settings/shaders/class2/lighting/lightV.glsl
index 89ef510d7c..a0f6e019ef 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/lightV.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/lightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
// All lights, no specular highlights
diff --git a/indra/newview/app_settings/shaders/class2/lighting/lightWaterF.glsl b/indra/newview/app_settings/shaders/class2/lighting/lightWaterF.glsl
index 016258bd18..97eba92d7b 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/lightWaterF.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/lightWaterF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class2/lighting/sumLightsSpecularV.glsl b/indra/newview/app_settings/shaders/class2/lighting/sumLightsSpecularV.glsl
index 8cfeeb1cf9..fde32ed035 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/sumLightsSpecularV.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/sumLightsSpecularV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
float calcDirectionalLightSpecular(inout vec4 specular, vec3 view, vec3 n, vec3 l, vec3 lightCol, float da);
vec3 calcPointLightSpecular(inout vec4 specular, vec3 view, vec3 v, vec3 n, vec3 l, float r, float pw, vec3 lightCol);
diff --git a/indra/newview/app_settings/shaders/class2/lighting/sumLightsV.glsl b/indra/newview/app_settings/shaders/class2/lighting/sumLightsV.glsl
index a512b9d6fb..8fe49e3be0 100644
--- a/indra/newview/app_settings/shaders/class2/lighting/sumLightsV.glsl
+++ b/indra/newview/app_settings/shaders/class2/lighting/sumLightsV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
float calcDirectionalLight(vec3 n, vec3 l);
float calcPointLightOrSpotLight(vec3 v, vec3 n, vec4 lp, vec3 ln, float la, float is_pointlight);
diff --git a/indra/newview/app_settings/shaders/class2/objects/shinyV.glsl b/indra/newview/app_settings/shaders/class2/objects/shinyV.glsl
index c428bbb28e..4cebb06df0 100644
--- a/indra/newview/app_settings/shaders/class2/objects/shinyV.glsl
+++ b/indra/newview/app_settings/shaders/class2/objects/shinyV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
diff --git a/indra/newview/app_settings/shaders/class2/windlight/atmosphericsF.glsl b/indra/newview/app_settings/shaders/class2/windlight/atmosphericsF.glsl
index 8baff24dbd..77d15fba9a 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/atmosphericsF.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/atmosphericsF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
//////////////////////////////////////////////////////////
// The fragment shader for the terrain atmospherics
diff --git a/indra/newview/app_settings/shaders/class2/windlight/atmosphericsHelpersV.glsl b/indra/newview/app_settings/shaders/class2/windlight/atmosphericsHelpersV.glsl
index 6883edc1f1..8c5b864cbe 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/atmosphericsHelpersV.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/atmosphericsHelpersV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
// Output variables
vec3 getSunlitColor();
diff --git a/indra/newview/app_settings/shaders/class2/windlight/atmosphericsV.glsl b/indra/newview/app_settings/shaders/class2/windlight/atmosphericsV.glsl
index f5c513bbdd..8d365c15ca 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/atmosphericsV.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/atmosphericsV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
// varying param funcs
void setSunlitColor(vec3 v);
diff --git a/indra/newview/app_settings/shaders/class2/windlight/atmosphericsVarsF.glsl b/indra/newview/app_settings/shaders/class2/windlight/atmosphericsVarsF.glsl
index d0b60e918e..cf9ef30632 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/atmosphericsVarsF.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/atmosphericsVarsF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec3 vary_PositionEye;
diff --git a/indra/newview/app_settings/shaders/class2/windlight/atmosphericsVarsV.glsl b/indra/newview/app_settings/shaders/class2/windlight/atmosphericsVarsV.glsl
index 4b4baf50d0..398f1556a0 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/atmosphericsVarsV.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/atmosphericsVarsV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec3 vary_PositionEye;
diff --git a/indra/newview/app_settings/shaders/class2/windlight/cloudsF.glsl b/indra/newview/app_settings/shaders/class2/windlight/cloudsF.glsl
index 2a559440fc..13207997b2 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/cloudsF.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/cloudsF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
/////////////////////////////////////////////////////////////////////////
// The fragment shader for the sky
diff --git a/indra/newview/app_settings/shaders/class2/windlight/cloudsV.glsl b/indra/newview/app_settings/shaders/class2/windlight/cloudsV.glsl
index 865c0e9da8..267ef36d4d 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/cloudsV.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/cloudsV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
//////////////////////////////////////////////////////////////////////////
// The vertex shader for creating the atmospheric sky
diff --git a/indra/newview/app_settings/shaders/class2/windlight/gammaF.glsl b/indra/newview/app_settings/shaders/class2/windlight/gammaF.glsl
index ce4bd2358f..a658edd21f 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/gammaF.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/gammaF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform vec4 gamma;
diff --git a/indra/newview/app_settings/shaders/class2/windlight/skyF.glsl b/indra/newview/app_settings/shaders/class2/windlight/skyF.glsl
index b69a88a45f..77ca4868a6 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/skyF.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/skyF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
/////////////////////////////////////////////////////////////////////////
// The fragment shader for the sky
diff --git a/indra/newview/app_settings/shaders/class2/windlight/skyV.glsl b/indra/newview/app_settings/shaders/class2/windlight/skyV.glsl
index 397db01378..03bca8f27e 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/skyV.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/skyV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
// SKY ////////////////////////////////////////////////////////////////////////
// The vertex shader for creating the atmospheric sky
diff --git a/indra/newview/app_settings/shaders/class2/windlight/transportF.glsl b/indra/newview/app_settings/shaders/class2/windlight/transportF.glsl
index b30313bdc8..7f1ad4d5b4 100644
--- a/indra/newview/app_settings/shaders/class2/windlight/transportF.glsl
+++ b/indra/newview/app_settings/shaders/class2/windlight/transportF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
//////////////////////////////////////////////////////////
// The fragment shader for the terrain atmospherics
diff --git a/indra/newview/app_settings/shaders/class3/avatar/avatarV.glsl b/indra/newview/app_settings/shaders/class3/avatar/avatarV.glsl
index c85ba0c734..a003e2a1f1 100644
--- a/indra/newview/app_settings/shaders/class3/avatar/avatarV.glsl
+++ b/indra/newview/app_settings/shaders/class3/avatar/avatarV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
vec4 calcLighting(vec3 pos, vec3 norm, vec4 color, vec4 baseCol);
mat4 getSkinnedTransform();
diff --git a/indra/newview/app_settings/shaders/class3/deferred/giDownsampleF.glsl b/indra/newview/app_settings/shaders/class3/deferred/giDownsampleF.glsl
index d26b244fa3..fc370ef367 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/giDownsampleF.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/giDownsampleF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2DRect giLightMap;
diff --git a/indra/newview/app_settings/shaders/class3/deferred/giDownsampleV.glsl b/indra/newview/app_settings/shaders/class3/deferred/giDownsampleV.glsl
index e5f6217644..ae57227fe5 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/giDownsampleV.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/giDownsampleV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class3/deferred/giF.glsl b/indra/newview/app_settings/shaders/class3/deferred/giF.glsl
index 735150a78c..951e3e97ae 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/giF.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/giF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class3/deferred/giFinalF.glsl b/indra/newview/app_settings/shaders/class3/deferred/giFinalF.glsl
index e0f4a3e4f5..b2f8b2c633 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/giFinalF.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/giFinalF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class3/deferred/giFinalV.glsl b/indra/newview/app_settings/shaders/class3/deferred/giFinalV.glsl
index fbf2c17370..19c4e07b8b 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/giFinalV.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/giFinalV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class3/deferred/giV.glsl b/indra/newview/app_settings/shaders/class3/deferred/giV.glsl
index 543527612e..8dc1410ea5 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/giV.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/giV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
diff --git a/indra/newview/app_settings/shaders/class3/deferred/luminanceF.glsl b/indra/newview/app_settings/shaders/class3/deferred/luminanceF.glsl
index d9483bc6e4..5f3bf68b24 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/luminanceF.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/luminanceF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class3/deferred/luminanceV.glsl b/indra/newview/app_settings/shaders/class3/deferred/luminanceV.glsl
index 6368def830..a24eda35dc 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/luminanceV.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/luminanceV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
diff --git a/indra/newview/app_settings/shaders/class3/deferred/postDeferredF.glsl b/indra/newview/app_settings/shaders/class3/deferred/postDeferredF.glsl
index 51ab579e3c..ab99a88971 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/postDeferredF.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/postDeferredF.glsl
@@ -4,7 +4,9 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
-
+
+#version 120
+
#extension GL_ARB_texture_rectangle : enable
uniform sampler2DRect diffuseRect;
diff --git a/indra/newview/app_settings/shaders/class3/deferred/postDeferredV.glsl b/indra/newview/app_settings/shaders/class3/deferred/postDeferredV.glsl
index 0ec81dcb02..12983baa94 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/postDeferredV.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/postDeferredV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class3/deferred/postgiF.glsl b/indra/newview/app_settings/shaders/class3/deferred/postgiF.glsl
index 24fa07f251..f037754708 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/postgiF.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/postgiF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class3/deferred/postgiV.glsl b/indra/newview/app_settings/shaders/class3/deferred/postgiV.glsl
index e5f6217644..ae57227fe5 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/postgiV.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/postgiV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
varying vec2 vary_fragcoord;
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class3/deferred/softenLightF.glsl b/indra/newview/app_settings/shaders/class3/deferred/softenLightF.glsl
index a2db247331..ce32f66000 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/softenLightF.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/softenLightF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
#extension GL_ARB_texture_rectangle : enable
diff --git a/indra/newview/app_settings/shaders/class3/deferred/softenLightV.glsl b/indra/newview/app_settings/shaders/class3/deferred/softenLightV.glsl
index 9d187b46e2..8f0bcca76b 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/softenLightV.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/softenLightV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform vec2 screen_res;
diff --git a/indra/newview/app_settings/shaders/class3/deferred/treeF.glsl b/indra/newview/app_settings/shaders/class3/deferred/treeF.glsl
index 1c1725a95c..c54d9a1e3e 100644
--- a/indra/newview/app_settings/shaders/class3/deferred/treeF.glsl
+++ b/indra/newview/app_settings/shaders/class3/deferred/treeF.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
uniform sampler2D diffuseMap;
diff --git a/indra/newview/app_settings/shaders/class3/lighting/sumLightsSpecularV.glsl b/indra/newview/app_settings/shaders/class3/lighting/sumLightsSpecularV.glsl
index 2b44aedd5a..04533fdce1 100644
--- a/indra/newview/app_settings/shaders/class3/lighting/sumLightsSpecularV.glsl
+++ b/indra/newview/app_settings/shaders/class3/lighting/sumLightsSpecularV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
float calcDirectionalLightSpecular(inout vec4 specular, vec3 view, vec3 n, vec3 l, vec3 lightCol, float da);
vec3 calcPointLightSpecular(inout vec4 specular, vec3 view, vec3 v, vec3 n, vec3 l, float r, float pw, vec3 lightCol);
diff --git a/indra/newview/app_settings/shaders/class3/lighting/sumLightsV.glsl b/indra/newview/app_settings/shaders/class3/lighting/sumLightsV.glsl
index 329b0c4305..73bc18b866 100644
--- a/indra/newview/app_settings/shaders/class3/lighting/sumLightsV.glsl
+++ b/indra/newview/app_settings/shaders/class3/lighting/sumLightsV.glsl
@@ -4,6 +4,8 @@
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* $/LicenseInfo$
*/
+
+#version 120
float calcDirectionalLight(vec3 n, vec3 l);
float calcPointLightOrSpotLight(vec3 v, vec3 n, vec4 lp, vec3 ln, float la, float is_pointlight);
diff --git a/indra/newview/app_settings/ultra_graphics.xml b/indra/newview/app_settings/ultra_graphics.xml
index e7dce3b989..f741089ca2 100644
--- a/indra/newview/app_settings/ultra_graphics.xml
+++ b/indra/newview/app_settings/ultra_graphics.xml
@@ -24,8 +24,6 @@
<RenderTerrainLODFactor value="2.0"/>
<!--Default for now-->
<RenderTreeLODFactor value="1.0"/>
- <!--Default for now-->
- <RenderUseFBO value="1"/>
<!--Try Impostors-->
<RenderUseImpostors value="TRUE"/>
<!--Default for now-->
diff --git a/indra/newview/featuretable.txt b/indra/newview/featuretable.txt
index a82c3da4c5..6022153020 100644
--- a/indra/newview/featuretable.txt
+++ b/indra/newview/featuretable.txt
@@ -1,560 +1,571 @@
-version 25
-
-// NOTE: This is mostly identical to featuretable_mac.txt with a few differences
-// Should be combined into one table
-
-//
-// Generates lists of feature mask that can be applied on top of each other.
-//
-// // Begin comments
-// list <name>
-// Starts a feature list named <name>
-// <name> <available> <recommended>
-// <name> is the name of a feature
-// <available> is 0 or 1, whether the feature is available
-// <recommended> is an F32 which is the recommended value
-//
-// For now, the first list read sets up all of the default values
-//
-
-
-//
-// All contains everything at their default settings for high end machines
-// NOTE: All settings are set to the MIN of applied values, including 'all'!
-//
-list all
-RenderAnisotropic 1 1
-RenderAvatarCloth 1 1
-RenderAvatarLODFactor 1 1.0
-RenderAvatarMaxVisible 1 12
-RenderAvatarVP 1 1
-RenderCubeMap 1 1
-RenderDelayVBUpdate 1 0
-RenderFarClip 1 256
-RenderFlexTimeFactor 1 1.0
-RenderFogRatio 1 4.0
-RenderGamma 1 0
-RenderGlowResolutionPow 1 9
-RenderGround 1 1
-RenderMaxPartCount 1 8192
-RenderNightBrightness 1 1.0
-RenderObjectBump 1 1
-RenderReflectionDetail 1 4
-RenderTerrainDetail 1 1
-RenderTerrainLODFactor 1 2.0
-RenderTransparentWater 1 1
-RenderTreeLODFactor 1 1.0
-RenderUseImpostors 1 1
-RenderVBOEnable 1 1
-RenderVolumeLODFactor 1 2.0
-UseStartScreen 1 1
-UseOcclusion 1 1
-VertexShaderEnable 1 1
-WindLightUseAtmosShaders 1 1
-WLSkyDetail 1 128
-Disregard128DefaultDrawDistance 1 1
-Disregard96DefaultDrawDistance 1 1
-RenderTextureMemoryMultiple 1 1.0
-RenderShaderLightingMaxLevel 1 3
-SkyUseClassicClouds 1 1
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-WatchdogDisabled 1 1
-RenderUseStreamVBO 1 1
-RenderUseFBO 1 1
-
-//
-// Low Graphics Settings
-//
-list Low
-RenderAnisotropic 1 0
-RenderAvatarCloth 1 0
-RenderAvatarLODFactor 1 0
-RenderAvatarMaxVisible 1 3
-RenderAvatarVP 1 0
-RenderFarClip 1 64
-RenderFlexTimeFactor 1 0
-RenderGlowResolutionPow 1 8
-RenderMaxPartCount 1 0
-RenderObjectBump 1 0
-RenderReflectionDetail 1 0
-RenderTerrainDetail 1 0
-RenderTerrainLODFactor 1 1
-RenderTransparentWater 1 0
-RenderTreeLODFactor 1 0
-RenderUseImpostors 1 1
-RenderVolumeLODFactor 1 0.5
-VertexShaderEnable 1 0
-WindLightUseAtmosShaders 1 0
-WLSkyDetail 1 48
-SkyUseClassicClouds 1 0
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-RenderUseFBO 1 0
-
-//
-// Mid Graphics Settings
-//
-list Mid
-RenderAnisotropic 1 0
-RenderAvatarCloth 1 0
-RenderAvatarLODFactor 1 0.5
-RenderAvatarVP 1 1
-RenderFarClip 1 96
-RenderFlexTimeFactor 1 1.0
-RenderGlowResolutionPow 1 8
-RenderMaxPartCount 1 2048
-RenderObjectBump 1 1
-RenderReflectionDetail 1 0
-RenderTerrainDetail 1 1
-RenderTerrainLODFactor 1 1.0
-RenderTransparentWater 1 1
-RenderTreeLODFactor 1 0.5
-RenderUseImpostors 1 1
-RenderVolumeLODFactor 1 1.125
-VertexShaderEnable 1 1
-WindLightUseAtmosShaders 1 0
-WLSkyDetail 1 48
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-RenderUseFBO 1 0
-
-//
-// High Graphics Settings (purty)
-//
-list High
-RenderAnisotropic 1 1
-RenderAvatarCloth 1 0
-RenderAvatarLODFactor 1 1.0
-RenderAvatarVP 1 1
-RenderFarClip 1 128
-RenderFlexTimeFactor 1 1.0
-RenderGlowResolutionPow 1 9
-RenderMaxPartCount 1 4096
-RenderObjectBump 1 1
-RenderReflectionDetail 1 0
-RenderTerrainDetail 1 1
-RenderTerrainLODFactor 1 2.0
-RenderTransparentWater 1 1
-RenderTreeLODFactor 1 0.5
-RenderUseImpostors 1 1
-RenderVolumeLODFactor 1 1.125
-VertexShaderEnable 1 1
-WindLightUseAtmosShaders 1 1
-WLSkyDetail 1 48
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-RenderUseFBO 1 0
-
-//
-// Ultra graphics (REALLY PURTY!)
-//
-list Ultra
-RenderAnisotropic 1 1
-RenderAvatarCloth 1 1
-RenderAvatarLODFactor 1 1.0
-RenderAvatarVP 1 1
-RenderFarClip 1 256
-RenderFlexTimeFactor 1 1.0
-RenderGlowResolutionPow 1 9
-RenderMaxPartCount 1 8192
-RenderObjectBump 1 1
-RenderReflectionDetail 1 4
-RenderTerrainDetail 1 1
-RenderTerrainLODFactor 1 2.0
-RenderTransparentWater 1 1
-RenderTreeLODFactor 1 1.0
-RenderUseImpostors 1 1
-RenderVolumeLODFactor 1 2.0
-VertexShaderEnable 1 1
-WindLightUseAtmosShaders 1 1
-WLSkyDetail 1 128
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-RenderUseFBO 1 0
-
-//
-// Class Unknown Hardware (unknown)
-//
-list Unknown
-RenderVBOEnable 1 0
-
-//
-// Class 0 Hardware (just old)
-//
-list Class0
-RenderVBOEnable 1 1
-
-//
-// Class 1 Hardware
-//
-list Class1
-RenderVBOEnable 1 1
-
-//
-// Class 2 Hardware (make it purty)
-//
-list Class2
-RenderVBOEnable 1 1
-
-//
-// Class 3 Hardware (make it purty)
-//
-list Class3
-RenderVBOEnable 1 1
-
-//
-// No Pixel Shaders available
-//
-list NoPixelShaders
-RenderAvatarVP 0 0
-RenderAvatarCloth 0 0
-RenderReflectionDetail 0 0
-VertexShaderEnable 0 0
-WindLightUseAtmosShaders 0 0
-RenderDeferred 0 0
-RenderDeferredSSAO 0 0
-RenderShadowDetail 0 0
-
-//
-// No Vertex Shaders available
-//
-list NoVertexShaders
-RenderAvatarVP 0 0
-RenderAvatarCloth 0 0
-RenderReflectionDetail 0 0
-VertexShaderEnable 0 0
-WindLightUseAtmosShaders 0 0
-RenderDeferred 0 0
-RenderDeferredSSAO 0 0
-RenderShadowDetail 0 0
-
-//
-// "Default" setups for safe, low, medium, high
-//
-list safe
-RenderAnisotropic 1 0
-RenderAvatarCloth 0 0
-RenderAvatarVP 0 0
-RenderObjectBump 0 0
-RenderMaxPartCount 1 1024
-RenderTerrainDetail 1 0
-RenderUseImpostors 0 0
-RenderVBOEnable 1 0
-RenderReflectionDetail 0 0
-WindLightUseAtmosShaders 0 0
-RenderDeferred 0 0
-RenderDeferredSSAO 0 0
-RenderShadowDetail 0 0
-RenderUseFBO 1 0
-
-//
-// CPU based feature masks
-//
-
-// 1Ghz or less (equiv)
-list CPUSlow
-RenderMaxPartCount 1 1024
-
-//
-// RAM based feature masks
-//
-list RAM256MB
-RenderObjectBump 0 0
-
-//
-// Graphics card based feature masks
-//
-list OpenGLPre15
-RenderVBOEnable 1 0
-
-list Intel
-RenderAnisotropic 1 0
-
-list GeForce2
-RenderAnisotropic 1 0
-RenderMaxPartCount 1 2048
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 1
-
-list SiS
-UseOcclusion 0 0
-
-
-list Intel_830M
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_845G
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_855GM
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_865G
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_900
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_915GM
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_915G
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_945GM
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_945G
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_950
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_965
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-UseOcclusion 0 0
-
-list Intel_G33
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_G45
-WindLightUseAtmosShaders 0 0
-
-list Intel_Bear_Lake
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_Broadwater
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_Brookdale
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_Eaglelake
-WindLightUseAtmosShaders 0 0
-
-list Intel_Montara
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_Springdale
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-
-list ATI_FireGL_5200
-RenderVBOEnable 1 0
-WindLightUseAtmosShaders 0 0
-
-
-list ATI_Mobility_Radeon_7xxx
-RenderVBOEnable 0 0
-
-list ATI_Radeon_7xxx
-RenderVBOEnable 0 0
-
-list ATI_All-in-Wonder_Radeon
-RenderVBOEnable 0 0
-
-list ATI_All-in-Wonder_7500
-RenderVBOEnable 0 0
-
-list ATI_Mobility_Radeon_9600
-Disregard96DefaultDrawDistance 1 0
-
-
-/// tweaked ATI to 96 Draw distance
-
-list ATI_Radeon_9000
-Disregard96DefaultDrawDistance 1 0
-list ATI_Radeon_9200
-Disregard96DefaultDrawDistance 1 0
-list ATI_Radeon_9500
-Disregard96DefaultDrawDistance 1 0
-list ATI_Radeon_9600
-Disregard96DefaultDrawDistance 1 0
-
-/// tweaked ATI to 128 draw distance
-
-list ATI_Radeon_X300
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X400
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X500
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X600
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X700
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X1300
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-UseStartScreen 0 0
-list ATI_Radeon_X1400
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X1500
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-UseStartScreen 0 0
-list ATI_Radeon_X1600
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X1700
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Mobility_Radeon_X1xxx
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-
-list ATI_Radeon_HD_2300
-Disregard128DefaultDrawDistance 1 0
-list ATI_Radeon_HD_2400
-Disregard128DefaultDrawDistance 1 0
-list ATI_ASUS_AH24xx
-Disregard128DefaultDrawDistance 1 0
-
-
-// Avatar hardware skinning causes invisible avatars
-// on various ATI chipsets on drivers before 8.2
-
-list ATIOldDriver
-RenderAvatarVP 0 0
-RenderAvatarCloth 0 0
-
-// ATI cards generally perform better when not using VBOs for streaming data
-
-list ATI
-RenderUseStreamVBO 1 0
-
-/// Tweaked NVIDIA
-
-list NVIDIA_GeForce_FX_5100
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_5200
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_5500
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_5600
-Disregard96DefaultDrawDistance 1 0
-
-list NVIDIA_GeForce_FX_Go5100
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_Go5200
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_Go5300
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_Go5500
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_Go5600
-Disregard96DefaultDrawDistance 1 0
-
-list NVIDIA_GeForce_6100
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_6200
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_6500
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_6600
-Disregard128DefaultDrawDistance 1 0
-
-list NVIDIA_G73
-Disregard128DefaultDrawDistance 1 0
-
-list NVIDIA_GeForce_Go_6100
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6200
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6500
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6600
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6700
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6800
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-
-list NVIDIA_GeForce_7000
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7100
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7200
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7300
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7400
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7500
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7600
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7700
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7800
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7900
-RenderShaderLightingMaxLevel 1 2
-
-list NVIDIA_GeForce_Go_7200
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7300
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7300_LE
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7400
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7600
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7700
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7800
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7900
-RenderShaderLightingMaxLevel 1 2
+version 27
+
+// NOTE: This is mostly identical to featuretable_mac.txt with a few differences
+// Should be combined into one table
+
+//
+// Generates lists of feature mask that can be applied on top of each other.
+//
+// // Begin comments
+// list <name>
+// Starts a feature list named <name>
+// <name> <available> <recommended>
+// <name> is the name of a feature
+// <available> is 0 or 1, whether the feature is available
+// <recommended> is an F32 which is the recommended value
+//
+// For now, the first list read sets up all of the default values
+//
+
+
+//
+// All contains everything at their default settings for high end machines
+// NOTE: All settings are set to the MIN of applied values, including 'all'!
+//
+list all
+RenderAnisotropic 1 1
+RenderAvatarCloth 1 1
+RenderAvatarLODFactor 1 1.0
+RenderAvatarMaxVisible 1 12
+RenderAvatarVP 1 1
+RenderCubeMap 1 1
+RenderDelayVBUpdate 1 0
+RenderFarClip 1 256
+RenderFlexTimeFactor 1 1.0
+RenderFogRatio 1 4.0
+RenderGamma 1 0
+RenderGlowResolutionPow 1 9
+RenderGround 1 1
+RenderMaxPartCount 1 8192
+RenderNightBrightness 1 1.0
+RenderObjectBump 1 1
+RenderLocalLights 1 1
+RenderReflectionDetail 1 4
+RenderTerrainDetail 1 1
+RenderTerrainLODFactor 1 2.0
+RenderTransparentWater 1 1
+RenderTreeLODFactor 1 1.0
+RenderUseImpostors 1 1
+RenderVBOEnable 1 1
+RenderVolumeLODFactor 1 2.0
+UseStartScreen 1 1
+UseOcclusion 1 1
+VertexShaderEnable 1 1
+WindLightUseAtmosShaders 1 1
+WLSkyDetail 1 128
+Disregard128DefaultDrawDistance 1 1
+Disregard96DefaultDrawDistance 1 1
+RenderTextureMemoryMultiple 1 1.0
+RenderShaderLightingMaxLevel 1 3
+RenderDeferred 1 1
+SkyUseClassicClouds 1 1
+RenderDeferredSSAO 1 1
+RenderShadowDetail 1 2
+WatchdogDisabled 1 1
+RenderUseStreamVBO 1 1
+
+//
+// Low Graphics Settings
+//
+list Low
+RenderAnisotropic 1 0
+RenderAvatarCloth 1 0
+RenderAvatarLODFactor 1 0
+RenderAvatarMaxVisible 1 3
+RenderAvatarVP 1 0
+RenderFarClip 1 64
+RenderFlexTimeFactor 1 0
+RenderGlowResolutionPow 1 8
+RenderMaxPartCount 1 0
+RenderObjectBump 1 0
+RenderLocalLights 1 0
+RenderReflectionDetail 1 0
+RenderTerrainDetail 1 0
+RenderTerrainLODFactor 1 1
+RenderTransparentWater 1 0
+RenderTreeLODFactor 1 0
+RenderUseImpostors 1 1
+RenderVolumeLODFactor 1 0.5
+VertexShaderEnable 1 0
+WindLightUseAtmosShaders 1 0
+WLSkyDetail 1 48
+SkyUseClassicClouds 1 0
+RenderDeferred 1 0
+RenderDeferredSSAO 1 0
+RenderShadowDetail 1 0
+
+//
+// Mid Graphics Settings
+//
+list Mid
+RenderAnisotropic 1 0
+RenderAvatarCloth 1 0
+RenderAvatarLODFactor 1 0.5
+RenderAvatarVP 1 1
+RenderFarClip 1 96
+RenderFlexTimeFactor 1 1.0
+RenderGlowResolutionPow 1 8
+RenderMaxPartCount 1 2048
+RenderObjectBump 1 1
+RenderLocalLights 1 1
+RenderReflectionDetail 1 0
+RenderTerrainDetail 1 1
+RenderTerrainLODFactor 1 1.0
+RenderTransparentWater 1 1
+RenderTreeLODFactor 1 0.5
+RenderUseImpostors 1 1
+RenderVolumeLODFactor 1 1.125
+VertexShaderEnable 1 1
+WindLightUseAtmosShaders 1 0
+WLSkyDetail 1 48
+RenderDeferred 1 0
+RenderDeferredSSAO 1 0
+RenderShadowDetail 1 0
+
+//
+// High Graphics Settings (purty)
+//
+list High
+RenderAnisotropic 1 1
+RenderAvatarCloth 1 0
+RenderAvatarLODFactor 1 1.0
+RenderAvatarVP 1 1
+RenderFarClip 1 128
+RenderFlexTimeFactor 1 1.0
+RenderGlowResolutionPow 1 9
+RenderMaxPartCount 1 4096
+RenderObjectBump 1 1
+RenderLocalLights 1 1
+RenderReflectionDetail 1 0
+RenderTerrainDetail 1 1
+RenderTerrainLODFactor 1 2.0
+RenderTransparentWater 1 1
+RenderTreeLODFactor 1 0.5
+RenderUseImpostors 1 1
+RenderVolumeLODFactor 1 1.125
+VertexShaderEnable 1 1
+WindLightUseAtmosShaders 1 1
+WLSkyDetail 1 48
+RenderDeferred 1 0
+RenderDeferredSSAO 1 0
+RenderShadowDetail 1 0
+
+//
+// Ultra graphics (REALLY PURTY!)
+//
+list Ultra
+RenderAnisotropic 1 1
+RenderAvatarCloth 1 1
+RenderAvatarLODFactor 1 1.0
+RenderAvatarVP 1 1
+RenderFarClip 1 256
+RenderFlexTimeFactor 1 1.0
+RenderGlowResolutionPow 1 9
+RenderMaxPartCount 1 8192
+RenderObjectBump 1 1
+RenderLocalLights 1 1
+RenderReflectionDetail 1 4
+RenderTerrainDetail 1 1
+RenderTerrainLODFactor 1 2.0
+RenderTransparentWater 1 1
+RenderTreeLODFactor 1 1.0
+RenderUseImpostors 1 1
+RenderVolumeLODFactor 1 2.0
+VertexShaderEnable 1 1
+WindLightUseAtmosShaders 1 1
+WLSkyDetail 1 128
+RenderDeferred 1 1
+RenderDeferredSSAO 1 1
+RenderShadowDetail 1 2
+
+//
+// Class Unknown Hardware (unknown)
+//
+list Unknown
+RenderVBOEnable 1 0
+
+//
+// Class 0 Hardware (just old)
+//
+list Class0
+RenderVBOEnable 1 1
+
+//
+// Class 1 Hardware
+//
+list Class1
+RenderVBOEnable 1 1
+
+//
+// Class 2 Hardware (make it purty)
+//
+list Class2
+RenderVBOEnable 1 1
+
+//
+// Class 3 Hardware (make it purty)
+//
+list Class3
+RenderVBOEnable 1 1
+
+//
+// No Pixel Shaders available
+//
+list NoPixelShaders
+RenderAvatarVP 0 0
+RenderAvatarCloth 0 0
+RenderReflectionDetail 0 0
+VertexShaderEnable 0 0
+WindLightUseAtmosShaders 0 0
+RenderDeferred 0 0
+RenderDeferredSSAO 0 0
+RenderShadowDetail 0 0
+
+//
+// No Vertex Shaders available
+//
+list NoVertexShaders
+RenderAvatarVP 0 0
+RenderAvatarCloth 0 0
+RenderReflectionDetail 0 0
+VertexShaderEnable 0 0
+WindLightUseAtmosShaders 0 0
+RenderDeferred 0 0
+RenderDeferredSSAO 0 0
+RenderShadowDetail 0 0
+
+
+//
+// "Default" setups for safe, low, medium, high
+//
+list safe
+RenderAnisotropic 1 0
+RenderAvatarCloth 0 0
+RenderAvatarVP 0 0
+RenderObjectBump 0 0
+RenderLocalLights 1 0
+RenderMaxPartCount 1 1024
+RenderTerrainDetail 1 0
+RenderUseImpostors 0 0
+RenderVBOEnable 1 0
+RenderReflectionDetail 0 0
+WindLightUseAtmosShaders 0 0
+RenderDeferred 0 0
+RenderDeferredSSAO 0 0
+RenderShadowDetail 0 0
+
+
+//
+// CPU based feature masks
+//
+
+// 1Ghz or less (equiv)
+list CPUSlow
+RenderMaxPartCount 1 1024
+
+//
+// RAM based feature masks
+//
+list RAM256MB
+RenderObjectBump 0 0
+
+//
+// Graphics card based feature masks
+//
+list OpenGLPre15
+RenderVBOEnable 1 0
+
+list OpenGLPre30
+RenderDeferred 0 0
+
+list Intel
+RenderAnisotropic 1 0
+
+list GeForce2
+RenderAnisotropic 1 0
+RenderMaxPartCount 1 2048
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 1
+
+list SiS
+UseOcclusion 0 0
+
+
+list Intel_830M
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_845G
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_855GM
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_865G
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_900
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_915GM
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_915G
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_945GM
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_945G
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_950
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_965
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+UseOcclusion 0 0
+
+list Intel_G33
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_G45
+WindLightUseAtmosShaders 0 0
+
+list Intel_Bear_Lake
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_Broadwater
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_Brookdale
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_Eaglelake
+WindLightUseAtmosShaders 0 0
+
+list Intel_Montara
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_Springdale
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+
+list ATI_FireGL_5200
+RenderVBOEnable 1 0
+WindLightUseAtmosShaders 0 0
+
+
+list ATI_Mobility_Radeon_7xxx
+RenderVBOEnable 0 0
+
+list ATI_Radeon_7xxx
+RenderVBOEnable 0 0
+
+list ATI_All-in-Wonder_Radeon
+RenderVBOEnable 0 0
+
+list ATI_All-in-Wonder_7500
+RenderVBOEnable 0 0
+
+list ATI_Mobility_Radeon_9600
+Disregard96DefaultDrawDistance 1 0
+
+
+/// tweaked ATI to 96 Draw distance
+
+list ATI_Radeon_9000
+Disregard96DefaultDrawDistance 1 0
+list ATI_Radeon_9200
+Disregard96DefaultDrawDistance 1 0
+list ATI_Radeon_9500
+Disregard96DefaultDrawDistance 1 0
+list ATI_Radeon_9600
+Disregard96DefaultDrawDistance 1 0
+
+/// tweaked ATI to 128 draw distance
+
+list ATI_Radeon_X300
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X400
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X500
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X600
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X700
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X1300
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+UseStartScreen 0 0
+list ATI_Radeon_X1400
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X1500
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+UseStartScreen 0 0
+list ATI_Radeon_X1600
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X1700
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Mobility_Radeon_X1xxx
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+
+list ATI_Radeon_HD_2300
+Disregard128DefaultDrawDistance 1 0
+list ATI_Radeon_HD_2400
+Disregard128DefaultDrawDistance 1 0
+list ATI_ASUS_AH24xx
+Disregard128DefaultDrawDistance 1 0
+
+
+// Avatar hardware skinning causes invisible avatars
+// on various ATI chipsets on drivers before 8.2
+
+list ATIOldDriver
+RenderAvatarVP 0 0
+RenderAvatarCloth 0 0
+
+// ATI cards generally perform better when not using VBOs for streaming data
+
+list ATI
+RenderUseStreamVBO 1 0
+RenderAvatarVP 1 0
+
+// Disable vertex buffer objects by default for ATI cards with little video memory
+list ATIVramLT256
+RenderVBOEnable 1 0
+
+/// Tweaked NVIDIA
+
+list NVIDIA_GeForce_FX_5100
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_5200
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_5500
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_5600
+Disregard96DefaultDrawDistance 1 0
+
+list NVIDIA_GeForce_FX_Go5100
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_Go5200
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_Go5300
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_Go5500
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_Go5600
+Disregard96DefaultDrawDistance 1 0
+
+list NVIDIA_GeForce_6100
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_6200
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_6500
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_6600
+Disregard128DefaultDrawDistance 1 0
+
+list NVIDIA_G73
+Disregard128DefaultDrawDistance 1 0
+
+list NVIDIA_GeForce_Go_6100
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6200
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6500
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6600
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6700
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6800
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+
+list NVIDIA_GeForce_7000
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7100
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7200
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7300
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7400
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7500
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7600
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7700
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7800
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7900
+RenderShaderLightingMaxLevel 1 2
+
+list NVIDIA_GeForce_Go_7200
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7300
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7300_LE
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7400
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7600
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7700
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7800
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7900
+RenderShaderLightingMaxLevel 1 2
+
diff --git a/indra/newview/featuretable_linux.txt b/indra/newview/featuretable_linux.txt
index a2cd4b834c..c7ad0df50b 100644
--- a/indra/newview/featuretable_linux.txt
+++ b/indra/newview/featuretable_linux.txt
@@ -1,4 +1,4 @@
-version 22
+version 23
// NOTE: This is mostly identical to featuretable_mac.txt with a few differences
// Should be combined into one table
@@ -36,6 +36,7 @@ RenderFogRatio 1 4.0
RenderGamma 1 0
RenderGlowResolutionPow 1 9
RenderGround 1 1
+RenderLocalLights 1 1
RenderMaxPartCount 1 8192
RenderNightBrightness 1 1.0
RenderObjectBump 1 1
@@ -58,10 +59,9 @@ RenderTextureMemoryMultiple 1 1.0
SkyUseClassicClouds 1 1
RenderShaderLightingMaxLevel 1 3
RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-WatchdogDisabled 1 1
-RenderUseFBO 1 1
+RenderDeferred 1 1
+RenderDeferredSSAO 1 1
+RenderShadowDetail 1 2
//
// Low Graphics Settings
@@ -75,6 +75,7 @@ RenderAvatarVP 1 0
RenderFarClip 1 64
RenderFlexTimeFactor 1 0
RenderGlowResolutionPow 1 8
+RenderLocalLights 1 0
RenderMaxPartCount 1 0
RenderObjectBump 1 0
RenderReflectionDetail 1 0
@@ -91,7 +92,6 @@ SkyUseClassicClouds 1 0
RenderDeferred 1 0
RenderDeferredSSAO 1 0
RenderShadowDetail 1 0
-RenderUseFBO 1 0
//
// Mid Graphics Settings
@@ -104,6 +104,7 @@ RenderAvatarVP 1 1
RenderFarClip 1 96
RenderFlexTimeFactor 1 1.0
RenderGlowResolutionPow 1 8
+RenderLocalLights 1 1
RenderMaxPartCount 1 2048
RenderObjectBump 1 1
RenderReflectionDetail 1 0
@@ -119,7 +120,6 @@ WLSkyDetail 1 48
RenderDeferred 1 0
RenderDeferredSSAO 1 0
RenderShadowDetail 1 0
-RenderUseFBO 1 0
//
// High Graphics Settings (purty)
@@ -132,6 +132,7 @@ RenderAvatarVP 1 1
RenderFarClip 1 128
RenderFlexTimeFactor 1 1.0
RenderGlowResolutionPow 1 9
+RenderLocalLights 1 1
RenderMaxPartCount 1 4096
RenderObjectBump 1 1
RenderReflectionDetail 1 0
@@ -147,7 +148,6 @@ WLSkyDetail 1 48
RenderDeferred 1 0
RenderDeferredSSAO 1 0
RenderShadowDetail 1 0
-RenderUseFBO 1 0
//
// Ultra graphics (REALLY PURTY!)
@@ -160,6 +160,7 @@ RenderAvatarVP 1 1
RenderFarClip 1 256
RenderFlexTimeFactor 1 1.0
RenderGlowResolutionPow 1 9
+RenderLocalLights 1 1
RenderMaxPartCount 1 8192
RenderObjectBump 1 1
RenderReflectionDetail 1 4
@@ -172,10 +173,9 @@ RenderVolumeLODFactor 1 2.0
VertexShaderEnable 1 1
WindLightUseAtmosShaders 1 1
WLSkyDetail 1 128
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-RenderUseFBO 1 0
+RenderDeferred 1 1
+RenderDeferredSSAO 1 1
+RenderShadowDetail 1 2
//
// Class Unknown Hardware (unknown)
@@ -250,7 +250,6 @@ WindLightUseAtmosShaders 0 0
RenderDeferred 0 0
RenderDeferredSSAO 0 0
RenderShadowDetail 0 0
-RenderUseFBO 1 0
//
diff --git a/indra/newview/featuretable_mac.txt b/indra/newview/featuretable_mac.txt
index 3ad7f4e892..5cc9f44a5f 100644
--- a/indra/newview/featuretable_mac.txt
+++ b/indra/newview/featuretable_mac.txt
@@ -36,7 +36,7 @@ RenderFogRatio 1 4.0
RenderGamma 1 0
RenderGlowResolutionPow 1 9
RenderGround 1 1
-RenderLightingDetail 1 1
+RenderLocalLights 1 1
RenderMaxPartCount 1 8192
RenderNightBrightness 1 1.0
RenderObjectBump 1 1
@@ -61,7 +61,6 @@ Disregard128DefaultDrawDistance 1 1
Disregard96DefaultDrawDistance 1 1
SkyUseClassicClouds 1 1
WatchdogDisabled 1 1
-RenderUseFBO 1 1
//
// Low Graphics Settings
@@ -75,7 +74,7 @@ RenderAvatarVP 1 0
RenderFarClip 1 64
RenderFlexTimeFactor 1 0
RenderGlowResolutionPow 1 8
-RenderLightingDetail 1 0
+RenderLocalLights 1 0
RenderMaxPartCount 1 0
RenderObjectBump 1 0
RenderReflectionDetail 1 0
@@ -90,7 +89,6 @@ VertexShaderEnable 1 0
WindLightUseAtmosShaders 1 0
WLSkyDetail 1 48
SkyUseClassicClouds 1 0
-RenderUseFBO 1 0
//
// Mid Graphics Settings
@@ -103,7 +101,7 @@ RenderAvatarVP 1 1
RenderFarClip 1 96
RenderFlexTimeFactor 1 1.0
RenderGlowResolutionPow 1 8
-RenderLightingDetail 1 1
+RenderLocalLights 1 1
RenderMaxPartCount 1 2048
RenderObjectBump 1 1
RenderReflectionDetail 1 0
@@ -117,7 +115,6 @@ RenderWaterReflections 1 0
VertexShaderEnable 1 1
WindLightUseAtmosShaders 1 0
WLSkyDetail 1 48
-RenderUseFBO 1 0
//
// High Graphics Settings (purty)
@@ -130,7 +127,7 @@ RenderAvatarVP 1 1
RenderFarClip 1 128
RenderFlexTimeFactor 1 1.0
RenderGlowResolutionPow 1 9
-RenderLightingDetail 1 1
+RenderLocalLights 1 1
RenderMaxPartCount 1 4096
RenderObjectBump 1 1
RenderReflectionDetail 1 0
@@ -144,7 +141,6 @@ RenderWaterReflections 1 0
VertexShaderEnable 1 1
WindLightUseAtmosShaders 1 1
WLSkyDetail 1 48
-RenderUseFBO 1 0
//
// Ultra graphics (REALLY PURTY!)
@@ -157,7 +153,7 @@ RenderAvatarVP 1 1
RenderFarClip 1 256
RenderFlexTimeFactor 1 1.0
RenderGlowResolutionPow 1 9
-RenderLightingDetail 1 1
+RenderLocalLights 1 1
RenderMaxPartCount 1 8192
RenderObjectBump 1 1
RenderReflectionDetail 1 3
@@ -171,7 +167,6 @@ RenderWaterReflections 1 1
VertexShaderEnable 1 1
WindLightUseAtmosShaders 1 1
WLSkyDetail 1 128
-RenderUseFBO 1 0
//
// Class Unknown Hardware (unknown)
@@ -229,7 +224,7 @@ list safe
RenderAnisotropic 1 0
RenderAvatarCloth 0 0
RenderAvatarVP 0 0
-RenderLightingDetail 1 0
+RenderLocalLights 1 0
RenderObjectBump 0 0
RenderMaxPartCount 1 1024
RenderTerrainDetail 1 0
@@ -237,7 +232,6 @@ RenderUseImpostors 0 0
RenderVBOEnable 1 0
RenderWaterReflections 0 0
WindLightUseAtmosShaders 0 0
-RenderUseFBO 1 0
//
// CPU based feature masks
@@ -261,11 +255,11 @@ RenderVBOEnable 1 0
list Intel
RenderAnisotropic 1 0
-RenderLightingDetail 1 0
+RenderLocalLights 1 0
list GeForce2
RenderAnisotropic 1 0
-RenderLightingDetail 1 0
+RenderLocalLights 1 0
RenderMaxPartCount 1 2048
RenderTerrainDetail 1 0
RenderVBOEnable 1 1
@@ -382,7 +376,6 @@ list ATI_Radeon_X1500
Disregard128DefaultDrawDistance 1 0
list ATI_Radeon_X1600
Disregard128DefaultDrawDistance 1 0
-RenderUseFBO 0 0
list ATI_Radeon_X1700
Disregard128DefaultDrawDistance 1 0
list ATI_Mobility_Radeon_X1xxx
diff --git a/indra/newview/featuretable_xp.txt b/indra/newview/featuretable_xp.txt
index 38e6bb1e5e..10aeffef01 100644
--- a/indra/newview/featuretable_xp.txt
+++ b/indra/newview/featuretable_xp.txt
@@ -1,562 +1,569 @@
-version 25
-
-// NOTE: This is mostly identical to featuretable_mac.txt with a few differences
-// Should be combined into one table
-
-//
-// Generates lists of feature mask that can be applied on top of each other.
-//
-// // Begin comments
-// list <name>
-// Starts a feature list named <name>
-// <name> <available> <recommended>
-// <name> is the name of a feature
-// <available> is 0 or 1, whether the feature is available
-// <recommended> is an F32 which is the recommended value
-//
-// For now, the first list read sets up all of the default values
-//
-
-
-//
-// All contains everything at their default settings for high end machines
-// NOTE: All settings are set to the MIN of applied values, including 'all'!
-//
-list all
-RenderAnisotropic 1 1
-RenderAvatarCloth 1 1
-RenderAvatarLODFactor 1 1.0
-RenderAvatarMaxVisible 1 12
-RenderAvatarVP 1 1
-RenderCubeMap 1 1
-RenderDelayVBUpdate 1 0
-RenderFarClip 1 256
-RenderFlexTimeFactor 1 1.0
-RenderFogRatio 1 4.0
-RenderGamma 1 0
-RenderGlowResolutionPow 1 9
-RenderGround 1 1
-RenderMaxPartCount 1 8192
-RenderNightBrightness 1 1.0
-RenderObjectBump 1 1
-RenderReflectionDetail 1 4
-RenderTerrainDetail 1 1
-RenderTerrainLODFactor 1 2.0
-RenderTransparentWater 1 1
-RenderTreeLODFactor 1 1.0
-RenderUseImpostors 1 1
-RenderVBOEnable 1 1
-RenderVolumeLODFactor 1 2.0
-UseStartScreen 1 1
-UseOcclusion 1 1
-VertexShaderEnable 1 1
-WindLightUseAtmosShaders 1 1
-WLSkyDetail 1 128
-Disregard128DefaultDrawDistance 1 1
-Disregard96DefaultDrawDistance 1 1
-RenderTextureMemoryMultiple 1 1.0
-RenderShaderLightingMaxLevel 1 3
-SkyUseClassicClouds 1 1
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-RenderUseFBO 1 1
-WatchdogDisabled 1 1
-RenderUseStreamVBO 1 1
-
-//
-// Low Graphics Settings
-//
-list Low
-RenderAnisotropic 1 0
-RenderAvatarCloth 1 0
-RenderAvatarLODFactor 1 0
-RenderAvatarMaxVisible 1 3
-RenderAvatarVP 1 0
-RenderFarClip 1 64
-RenderFlexTimeFactor 1 0
-RenderGlowResolutionPow 1 8
-RenderMaxPartCount 1 0
-RenderObjectBump 1 0
-RenderReflectionDetail 1 0
-RenderTerrainDetail 1 0
-RenderTerrainLODFactor 1 1
-RenderTransparentWater 1 0
-RenderTreeLODFactor 1 0
-RenderUseImpostors 1 1
-RenderVolumeLODFactor 1 0.5
-VertexShaderEnable 1 0
-WindLightUseAtmosShaders 1 0
-WLSkyDetail 1 48
-SkyUseClassicClouds 1 0
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-RenderUseFBO 1 0
-
-//
-// Mid Graphics Settings
-//
-list Mid
-RenderAnisotropic 1 0
-RenderAvatarCloth 1 0
-RenderAvatarLODFactor 1 0.5
-RenderAvatarVP 1 1
-RenderFarClip 1 96
-RenderFlexTimeFactor 1 1.0
-RenderGlowResolutionPow 1 8
-RenderMaxPartCount 1 2048
-RenderObjectBump 1 1
-RenderReflectionDetail 1 0
-RenderTerrainDetail 1 1
-RenderTerrainLODFactor 1 1.0
-RenderTransparentWater 1 1
-RenderTreeLODFactor 1 0.5
-RenderUseImpostors 1 1
-RenderVolumeLODFactor 1 1.125
-VertexShaderEnable 1 1
-WindLightUseAtmosShaders 1 0
-WLSkyDetail 1 48
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-RenderUseFBO 1 0
-
-//
-// High Graphics Settings (purty)
-//
-list High
-RenderAnisotropic 1 1
-RenderAvatarCloth 1 0
-RenderAvatarLODFactor 1 1.0
-RenderAvatarVP 1 1
-RenderFarClip 1 128
-RenderFlexTimeFactor 1 1.0
-RenderGlowResolutionPow 1 9
-RenderMaxPartCount 1 4096
-RenderObjectBump 1 1
-RenderReflectionDetail 1 0
-RenderTerrainDetail 1 1
-RenderTerrainLODFactor 1 2.0
-RenderTransparentWater 1 1
-RenderTreeLODFactor 1 0.5
-RenderUseImpostors 1 1
-RenderVolumeLODFactor 1 1.125
-VertexShaderEnable 1 1
-WindLightUseAtmosShaders 1 1
-WLSkyDetail 1 48
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-RenderUseFBO 1 0
-
-//
-// Ultra graphics (REALLY PURTY!)
-//
-list Ultra
-RenderAnisotropic 1 1
-RenderAvatarCloth 1 1
-RenderAvatarLODFactor 1 1.0
-RenderAvatarVP 1 1
-RenderFarClip 1 256
-RenderFlexTimeFactor 1 1.0
-RenderGlowResolutionPow 1 9
-RenderMaxPartCount 1 8192
-RenderObjectBump 1 1
-RenderReflectionDetail 1 4
-RenderTerrainDetail 1 1
-RenderTerrainLODFactor 1 2.0
-RenderTransparentWater 1 1
-RenderTreeLODFactor 1 1.0
-RenderUseImpostors 1 1
-RenderVolumeLODFactor 1 2.0
-VertexShaderEnable 1 1
-WindLightUseAtmosShaders 1 1
-WLSkyDetail 1 128
-RenderDeferred 1 0
-RenderDeferredSSAO 1 0
-RenderShadowDetail 1 0
-RenderUseFBO 1 0
-
-//
-// Class Unknown Hardware (unknown)
-//
-list Unknown
-RenderVBOEnable 1 0
-
-//
-// Class 0 Hardware (just old)
-//
-list Class0
-RenderVBOEnable 1 1
-
-//
-// Class 1 Hardware
-//
-list Class1
-RenderVBOEnable 1 1
-
-//
-// Class 2 Hardware (make it purty)
-//
-list Class2
-RenderVBOEnable 1 1
-
-//
-// Class 3 Hardware (make it purty)
-//
-list Class3
-RenderVBOEnable 1 1
-
-//
-// No Pixel Shaders available
-//
-list NoPixelShaders
-RenderAvatarVP 0 0
-RenderAvatarCloth 0 0
-RenderReflectionDetail 0 0
-VertexShaderEnable 0 0
-WindLightUseAtmosShaders 0 0
-RenderDeferred 0 0
-RenderDeferredSSAO 0 0
-RenderShadowDetail 0 0
-
-//
-// No Vertex Shaders available
-//
-list NoVertexShaders
-RenderAvatarVP 0 0
-RenderAvatarCloth 0 0
-RenderReflectionDetail 0 0
-VertexShaderEnable 0 0
-WindLightUseAtmosShaders 0 0
-RenderDeferred 0 0
-RenderDeferredSSAO 0 0
-RenderShadowDetail 0 0
-
-//
-// "Default" setups for safe, low, medium, high
-//
-list safe
-RenderAnisotropic 1 0
-RenderAvatarCloth 0 0
-RenderAvatarVP 0 0
-RenderObjectBump 0 0
-RenderMaxPartCount 1 1024
-RenderTerrainDetail 1 0
-RenderUseImpostors 0 0
-RenderVBOEnable 1 0
-RenderReflectionDetail 0 0
-WindLightUseAtmosShaders 0 0
-RenderDeferred 0 0
-RenderDeferredSSAO 0 0
-RenderShadowDetail 0 0
-RenderUseFBO 1 0
-
-//
-// CPU based feature masks
-//
-
-// 1Ghz or less (equiv)
-list CPUSlow
-RenderMaxPartCount 1 1024
-
-//
-// RAM based feature masks
-//
-list RAM256MB
-RenderObjectBump 0 0
-
-//
-// Graphics card based feature masks
-//
-list OpenGLPre15
-RenderVBOEnable 1 0
-
-list Intel
-RenderAnisotropic 1 0
-
-list GeForce2
-RenderAnisotropic 1 0
-RenderMaxPartCount 1 2048
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 1
-
-list SiS
-UseOcclusion 0 0
-
-
-list Intel_830M
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_845G
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_855GM
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_865G
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_900
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_915GM
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_915G
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 0 0
-
-list Intel_945GM
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_945G
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_950
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_965
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-RenderUseImpostors 1 0
-UseOcclusion 0 0
-
-list Intel_G33
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_G45
-WindLightUseAtmosShaders 0 0
-
-list Intel_Bear_Lake
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_Broadwater
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_Brookdale
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_Eaglelake
-WindLightUseAtmosShaders 0 0
-
-list Intel_Montara
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-list Intel_Springdale
-RenderTerrainDetail 1 0
-RenderVBOEnable 1 0
-
-
-list ATI_FireGL_5200
-RenderVBOEnable 1 0
-WindLightUseAtmosShaders 0 0
-
-
-list ATI_Mobility_Radeon_7xxx
-RenderVBOEnable 0 0
-
-list ATI_Radeon_7xxx
-RenderVBOEnable 0 0
-
-list ATI_All-in-Wonder_Radeon
-RenderVBOEnable 0 0
-
-list ATI_All-in-Wonder_7500
-RenderVBOEnable 0 0
-
-list ATI_Mobility_Radeon_9600
-Disregard96DefaultDrawDistance 1 0
-
-
-/// tweaked ATI to 96 Draw distance
-
-list ATI_Radeon_9000
-Disregard96DefaultDrawDistance 1 0
-list ATI_Radeon_9200
-Disregard96DefaultDrawDistance 1 0
-list ATI_Radeon_9500
-Disregard96DefaultDrawDistance 1 0
-list ATI_Radeon_9600
-Disregard96DefaultDrawDistance 1 0
-
-/// tweaked ATI to 128 draw distance
-
-list ATI_Radeon_X300
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X400
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X500
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X600
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X700
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X1300
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-UseStartScreen 0 0
-list ATI_Radeon_X1400
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X1500
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-UseStartScreen 0 0
-list ATI_Radeon_X1600
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Radeon_X1700
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-list ATI_Mobility_Radeon_X1xxx
-Disregard128DefaultDrawDistance 1 0
-RenderVBOEnable 1 0
-
-list ATI_Radeon_HD_2300
-Disregard128DefaultDrawDistance 1 0
-list ATI_Radeon_HD_2400
-Disregard128DefaultDrawDistance 1 0
-list ATI_ASUS_AH24xx
-Disregard128DefaultDrawDistance 1 0
-
-
-// Avatar hardware skinning causes invisible avatars
-// on various ATI chipsets on drivers before 8.2
-
-list ATIOldDriver
-RenderAvatarVP 0 0
-RenderAvatarCloth 0 0
-
-// ATI cards generally perform better when not using VBOs for streaming data
-
-list ATI
-RenderUseStreamVBO 1 0
-
-/// Tweaked NVIDIA
-
-list NVIDIA_GeForce_FX_5100
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_5200
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_5500
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_5600
-Disregard96DefaultDrawDistance 1 0
-
-list NVIDIA_GeForce_FX_Go5100
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_Go5200
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_Go5300
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_Go5500
-Disregard96DefaultDrawDistance 1 0
-list NVIDIA_GeForce_FX_Go5600
-Disregard96DefaultDrawDistance 1 0
-
-list NVIDIA_GeForce_6100
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_6200
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_6500
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_6600
-Disregard128DefaultDrawDistance 1 0
-
-list NVIDIA_G73
-Disregard128DefaultDrawDistance 1 0
-
-list NVIDIA_GeForce_Go_6100
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6200
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6500
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6600
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6700
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6800
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-list NVIDIA_GeForce_Go_6
-RenderVBOEnable 1 0
-Disregard128DefaultDrawDistance 1 0
-
-list NVIDIA_GeForce_7000
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7100
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7200
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7300
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7400
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7500
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7600
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7700
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7800
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_7900
-RenderShaderLightingMaxLevel 1 2
-
-list NVIDIA_GeForce_Go_7200
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7300
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7300_LE
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7400
-Disregard128DefaultDrawDistance 1 0
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7600
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7700
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7800
-RenderShaderLightingMaxLevel 1 2
-list NVIDIA_GeForce_Go_7900
-RenderShaderLightingMaxLevel 1 2
-
+version 27
+
+// NOTE: This is mostly identical to featuretable_mac.txt with a few differences
+// Should be combined into one table
+
+//
+// Generates lists of feature mask that can be applied on top of each other.
+//
+// // Begin comments
+// list <name>
+// Starts a feature list named <name>
+// <name> <available> <recommended>
+// <name> is the name of a feature
+// <available> is 0 or 1, whether the feature is available
+// <recommended> is an F32 which is the recommended value
+//
+// For now, the first list read sets up all of the default values
+//
+
+
+//
+// All contains everything at their default settings for high end machines
+// NOTE: All settings are set to the MIN of applied values, including 'all'!
+//
+list all
+RenderAnisotropic 1 1
+RenderAvatarCloth 1 1
+RenderAvatarLODFactor 1 1.0
+RenderAvatarMaxVisible 1 12
+RenderAvatarVP 1 1
+RenderCubeMap 1 1
+RenderDelayVBUpdate 1 0
+RenderFarClip 1 256
+RenderFlexTimeFactor 1 1.0
+RenderFogRatio 1 4.0
+RenderGamma 1 0
+RenderGlowResolutionPow 1 9
+RenderGround 1 1
+RenderLocalLights 1 1
+RenderMaxPartCount 1 8192
+RenderNightBrightness 1 1.0
+RenderObjectBump 1 1
+RenderReflectionDetail 1 4
+RenderTerrainDetail 1 1
+RenderTerrainLODFactor 1 2.0
+RenderTransparentWater 1 1
+RenderTreeLODFactor 1 1.0
+RenderUseImpostors 1 1
+RenderVBOEnable 1 1
+RenderVolumeLODFactor 1 2.0
+UseStartScreen 1 1
+UseOcclusion 1 1
+VertexShaderEnable 1 1
+WindLightUseAtmosShaders 1 1
+WLSkyDetail 1 128
+Disregard128DefaultDrawDistance 1 1
+Disregard96DefaultDrawDistance 1 1
+RenderTextureMemoryMultiple 1 1.0
+RenderShaderLightingMaxLevel 1 3
+SkyUseClassicClouds 1 1
+RenderDeferred 1 0
+RenderDeferredSSAO 1 0
+RenderShadowDetail 1 0
+WatchdogDisabled 1 1
+RenderUseStreamVBO 1 1
+
+//
+// Low Graphics Settings
+//
+list Low
+RenderAnisotropic 1 0
+RenderAvatarCloth 1 0
+RenderAvatarLODFactor 1 0
+RenderAvatarMaxVisible 1 3
+RenderAvatarVP 1 0
+RenderFarClip 1 64
+RenderFlexTimeFactor 1 0
+RenderGlowResolutionPow 1 8
+RenderLocalLights 1 0
+RenderMaxPartCount 1 0
+RenderObjectBump 1 0
+RenderReflectionDetail 1 0
+RenderTerrainDetail 1 0
+RenderTerrainLODFactor 1 1
+RenderTransparentWater 1 0
+RenderTreeLODFactor 1 0
+RenderUseImpostors 1 1
+RenderVolumeLODFactor 1 0.5
+VertexShaderEnable 1 0
+WindLightUseAtmosShaders 1 0
+WLSkyDetail 1 48
+SkyUseClassicClouds 1 0
+RenderDeferred 1 0
+RenderDeferredSSAO 1 0
+RenderShadowDetail 1 0
+
+//
+// Mid Graphics Settings
+//
+list Mid
+RenderAnisotropic 1 0
+RenderAvatarCloth 1 0
+RenderAvatarLODFactor 1 0.5
+RenderAvatarVP 1 1
+RenderFarClip 1 96
+RenderFlexTimeFactor 1 1.0
+RenderGlowResolutionPow 1 8
+RenderLocalLights 1 1
+RenderMaxPartCount 1 2048
+RenderObjectBump 1 1
+RenderReflectionDetail 1 0
+RenderTerrainDetail 1 1
+RenderTerrainLODFactor 1 1.0
+RenderTransparentWater 1 1
+RenderTreeLODFactor 1 0.5
+RenderUseImpostors 1 1
+RenderVolumeLODFactor 1 1.125
+VertexShaderEnable 1 1
+WindLightUseAtmosShaders 1 0
+WLSkyDetail 1 48
+RenderDeferred 1 0
+RenderDeferredSSAO 1 0
+RenderShadowDetail 1 0
+
+//
+// High Graphics Settings (purty)
+//
+list High
+RenderAnisotropic 1 1
+RenderAvatarCloth 1 0
+RenderAvatarLODFactor 1 1.0
+RenderAvatarVP 1 1
+RenderFarClip 1 128
+RenderFlexTimeFactor 1 1.0
+RenderGlowResolutionPow 1 9
+RenderLocalLights 1 1
+RenderMaxPartCount 1 4096
+RenderObjectBump 1 1
+RenderReflectionDetail 1 0
+RenderTerrainDetail 1 1
+RenderTerrainLODFactor 1 2.0
+RenderTransparentWater 1 1
+RenderTreeLODFactor 1 0.5
+RenderUseImpostors 1 1
+RenderVolumeLODFactor 1 1.125
+VertexShaderEnable 1 1
+WindLightUseAtmosShaders 1 1
+WLSkyDetail 1 48
+RenderDeferred 1 0
+RenderDeferredSSAO 1 0
+RenderShadowDetail 1 0
+
+//
+// Ultra graphics (REALLY PURTY!)
+//
+list Ultra
+RenderAnisotropic 1 1
+RenderAvatarCloth 1 1
+RenderAvatarLODFactor 1 1.0
+RenderAvatarVP 1 1
+RenderFarClip 1 256
+RenderFlexTimeFactor 1 1.0
+RenderGlowResolutionPow 1 9
+RenderLocalLights 1 1
+RenderMaxPartCount 1 8192
+RenderObjectBump 1 1
+RenderReflectionDetail 1 4
+RenderTerrainDetail 1 1
+RenderTerrainLODFactor 1 2.0
+RenderTransparentWater 1 1
+RenderTreeLODFactor 1 1.0
+RenderUseImpostors 1 1
+RenderVolumeLODFactor 1 2.0
+VertexShaderEnable 1 1
+WindLightUseAtmosShaders 1 1
+WLSkyDetail 1 128
+RenderDeferred 1 0
+RenderDeferredSSAO 1 0
+RenderShadowDetail 1 0
+
+//
+// Class Unknown Hardware (unknown)
+//
+list Unknown
+RenderVBOEnable 1 0
+
+//
+// Class 0 Hardware (just old)
+//
+list Class0
+RenderVBOEnable 1 1
+
+//
+// Class 1 Hardware
+//
+list Class1
+RenderVBOEnable 1 1
+
+//
+// Class 2 Hardware (make it purty)
+//
+list Class2
+RenderVBOEnable 1 1
+
+//
+// Class 3 Hardware (make it purty)
+//
+list Class3
+RenderVBOEnable 1 1
+
+//
+// No Pixel Shaders available
+//
+list NoPixelShaders
+RenderAvatarVP 0 0
+RenderAvatarCloth 0 0
+RenderReflectionDetail 0 0
+VertexShaderEnable 0 0
+WindLightUseAtmosShaders 0 0
+RenderDeferred 0 0
+RenderDeferredSSAO 0 0
+RenderShadowDetail 0 0
+
+//
+// No Vertex Shaders available
+//
+list NoVertexShaders
+RenderAvatarVP 0 0
+RenderAvatarCloth 0 0
+RenderReflectionDetail 0 0
+VertexShaderEnable 0 0
+WindLightUseAtmosShaders 0 0
+RenderDeferred 0 0
+RenderDeferredSSAO 0 0
+RenderShadowDetail 0 0
+
+//
+// "Default" setups for safe, low, medium, high
+//
+list safe
+RenderAnisotropic 1 0
+RenderAvatarCloth 0 0
+RenderAvatarVP 0 0
+RenderObjectBump 0 0
+RenderMaxPartCount 1 1024
+RenderTerrainDetail 1 0
+RenderUseImpostors 0 0
+RenderVBOEnable 1 0
+RenderReflectionDetail 0 0
+WindLightUseAtmosShaders 0 0
+RenderDeferred 0 0
+RenderDeferredSSAO 0 0
+RenderShadowDetail 0 0
+
+//
+// CPU based feature masks
+//
+
+// 1Ghz or less (equiv)
+list CPUSlow
+RenderMaxPartCount 1 1024
+
+//
+// RAM based feature masks
+//
+list RAM256MB
+RenderObjectBump 0 0
+
+//
+// Graphics card based feature masks
+//
+list OpenGLPre15
+RenderVBOEnable 1 0
+
+list OpenGLPre30
+RenderDeferred 0 0
+
+list Intel
+RenderAnisotropic 1 0
+
+list GeForce2
+RenderAnisotropic 1 0
+RenderMaxPartCount 1 2048
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 1
+
+list SiS
+UseOcclusion 0 0
+
+
+list Intel_830M
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_845G
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_855GM
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_865G
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_900
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_915GM
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_915G
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 0 0
+
+list Intel_945GM
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_945G
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_950
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_965
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+RenderUseImpostors 1 0
+UseOcclusion 0 0
+
+list Intel_G33
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_G45
+WindLightUseAtmosShaders 0 0
+
+list Intel_Bear_Lake
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_Broadwater
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_Brookdale
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_Eaglelake
+WindLightUseAtmosShaders 0 0
+
+list Intel_Montara
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+list Intel_Springdale
+RenderTerrainDetail 1 0
+RenderVBOEnable 1 0
+
+
+list ATI_FireGL_5200
+RenderVBOEnable 1 0
+WindLightUseAtmosShaders 0 0
+
+
+list ATI_Mobility_Radeon_7xxx
+RenderVBOEnable 0 0
+
+list ATI_Radeon_7xxx
+RenderVBOEnable 0 0
+
+list ATI_All-in-Wonder_Radeon
+RenderVBOEnable 0 0
+
+list ATI_All-in-Wonder_7500
+RenderVBOEnable 0 0
+
+list ATI_Mobility_Radeon_9600
+Disregard96DefaultDrawDistance 1 0
+
+
+/// tweaked ATI to 96 Draw distance
+
+list ATI_Radeon_9000
+Disregard96DefaultDrawDistance 1 0
+list ATI_Radeon_9200
+Disregard96DefaultDrawDistance 1 0
+list ATI_Radeon_9500
+Disregard96DefaultDrawDistance 1 0
+list ATI_Radeon_9600
+Disregard96DefaultDrawDistance 1 0
+
+/// tweaked ATI to 128 draw distance
+
+list ATI_Radeon_X300
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X400
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X500
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X600
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X700
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X1300
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+UseStartScreen 0 0
+list ATI_Radeon_X1400
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X1500
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+UseStartScreen 0 0
+list ATI_Radeon_X1600
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Radeon_X1700
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+list ATI_Mobility_Radeon_X1xxx
+Disregard128DefaultDrawDistance 1 0
+RenderVBOEnable 1 0
+
+list ATI_Radeon_HD_2300
+Disregard128DefaultDrawDistance 1 0
+list ATI_Radeon_HD_2400
+Disregard128DefaultDrawDistance 1 0
+list ATI_ASUS_AH24xx
+Disregard128DefaultDrawDistance 1 0
+
+
+// Avatar hardware skinning causes invisible avatars
+// on various ATI chipsets on drivers before 8.2
+
+list ATIOldDriver
+RenderAvatarVP 0 0
+RenderAvatarCloth 0 0
+
+// ATI cards generally perform better when not using VBOs for streaming data
+
+list ATI
+RenderUseStreamVBO 1 0
+RenderAvatarVP 1 0
+
+// Disable vertex buffer objects by default for ATI cards with little video memory
+list ATIVramLT256
+RenderVBOEnable 1 0
+
+/// Tweaked NVIDIA
+
+list NVIDIA_GeForce_FX_5100
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_5200
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_5500
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_5600
+Disregard96DefaultDrawDistance 1 0
+
+list NVIDIA_GeForce_FX_Go5100
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_Go5200
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_Go5300
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_Go5500
+Disregard96DefaultDrawDistance 1 0
+list NVIDIA_GeForce_FX_Go5600
+Disregard96DefaultDrawDistance 1 0
+
+list NVIDIA_GeForce_6100
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_6200
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_6500
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_6600
+Disregard128DefaultDrawDistance 1 0
+
+list NVIDIA_G73
+Disregard128DefaultDrawDistance 1 0
+
+list NVIDIA_GeForce_Go_6100
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6200
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6500
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6600
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6700
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6800
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+list NVIDIA_GeForce_Go_6
+RenderVBOEnable 1 0
+Disregard128DefaultDrawDistance 1 0
+
+list NVIDIA_GeForce_7000
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7100
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7200
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7300
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7400
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7500
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7600
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7700
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7800
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_7900
+RenderShaderLightingMaxLevel 1 2
+
+list NVIDIA_GeForce_Go_7200
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7300
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7300_LE
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7400
+Disregard128DefaultDrawDistance 1 0
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7600
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7700
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7800
+RenderShaderLightingMaxLevel 1 2
+list NVIDIA_GeForce_Go_7900
+RenderShaderLightingMaxLevel 1 2
+
diff --git a/indra/newview/gpu_table.txt b/indra/newview/gpu_table.txt
index da888bc64d..66b3b97f00 100644
--- a/indra/newview/gpu_table.txt
+++ b/indra/newview/gpu_table.txt
@@ -207,6 +207,7 @@ NVIDIA GTX 280 .*NVIDIA.*GeForce GTX 28.* 3 1
NVIDIA GTX 290 .*NVIDIA.*GeForce GTX 29.* 3 1
NVIDIA GTX 470 .*NVIDIA.*GeForce GTX 47.* 3 1
NVIDIA GTX 480 .*NVIDIA.*GeForce GTX 48.* 3 1
+NVIDIA GTX 580 .*NVIDIA.*GeForce GTX 58.* 3 1
NVIDIA C51 .*NVIDIA.*C51.* 0 1
NVIDIA G72 .*NVIDIA.*G72.* 1 1
NVIDIA G73 .*NVIDIA.*G73.* 1 1
@@ -301,12 +302,43 @@ NVIDIA NV43 .*NVIDIA.*NV43.* 1 1
NVIDIA NV44 .*NVIDIA.*NV44.* 1 1
NVIDIA nForce .*NVIDIA.*nForce.* 0 0
NVIDIA MCP78 .*NVIDIA.*MCP78.* 1 1
-NVIDIA Quadro2 .*Quadro2.* 0 1
-NVIDIA Quadro4 .*Quadro4.* 0 1
-NVIDIA Quadro DCC .*Quadro DCC.* 0 1
-NVIDIA Quadro FX 4500 .*Quadro.*FX.*4500.* 3 1
-NVIDIA Quadro FX .*Quadro FX.* 1 1
-NVIDIA Quadro NVS .*Quadro NVS.* 0 1
+NVIDIA Quadro2 .*Quadro2.* 0 1
+NVIDIA Quadro4 .*Quadro4.* 0 1
+NVIDIA Quadro DCC .*Quadro DCC.* 0 1
+NVIDIA Quadro FX 1400 .*Quadro.*FX.*1400.* 1 1
+NVIDIA Quadro FX 1500 .*Quadro.*FX.*1500.* 1 1
+NVIDIA Quadro FX 1700 .*Quadro.*FX.*1700.* 2 1
+NVIDIA Quadro FX 1800 .*Quadro.*FX.*1800.* 2 1
+NVIDIA Quadro FX 3400 .*Quadro.*FX.*3400.* 1 1
+NVIDIA Quadro FX 3450 .*Quadro.*FX.*3450.* 1 1
+NVIDIA Quadro FX 3500 .*Quadro.*FX.*3500.* 1 1
+NVIDIA Quadro FX 3700 .*Quadro.*FX.*3700.* 2 1
+NVIDIA Quadro FX 3800 .*Quadro.*FX.*3800.* 2 1
+NVIDIA Quadro FX 370 .*Quadro.*FX.*370.* 2 1
+NVIDIA Quadro FX 380 .*Quadro.*FX.*380.* 2 1
+NVIDIA Quadro FX 4000 .*Quadro.*FX.*4000.* 1 1
+NVIDIA Quadro FX 4500 .*Quadro.*FX.*4500.* 1 1
+NVIDIA Quadro FX 4600 .*Quadro.*FX.*4600.* 2 1
+NVIDIA Quadro FX 4700 .*Quadro.*FX.*4700.* 2 1
+NVIDIA Quadro FX 4800 .*Quadro.*FX.*4800.* 2 1
+NVIDIA Quadro FX 470 .*Quadro.*FX.*470.* 2 1
+NVIDIA Quadro FX 5500 .*Quadro.*FX.*5500.* 1 1
+NVIDIA Quadro FX 5600 .*Quadro.*FX.*5600.* 2 1
+NVIDIA Quadro FX 5700 .*Quadro.*FX.*5700.* 2 1
+NVIDIA Quadro FX 5800 .*Quadro.*FX.*5800.* 2 1
+NVIDIA Quadro FX 540 .*Quadro.*FX.*540.* 1 1
+NVIDIA Quadro FX 550 .*Quadro.*FX.*550.* 1 1
+NVIDIA Quadro FX 560 .*Quadro.*FX.*560.* 1 1
+NVIDIA Quadro FX 570 .*Quadro.*FX.*570.* 2 1
+NVIDIA Quadro FX 580 .*Quadro.*FX.*580.* 2 1
+NVIDIA Quadro FX .*Quadro FX.* 0 1
+NVIDIA Quadro VX 200 .*Quadro VX.*200.* 2 1
+NVIDIA Quadro 2000 .*Quadro.*2000.* 2 1
+NVIDIA Quadro 4000 .*Quadro.*4000.* 2 1
+NVIDIA Quadro 5000 .*Quadro.*5000.* 2 1
+NVIDIA Quadro 6000 .*Quadro.*6000.* 2 1
+NVIDIA Quadro 600 .*Quadro.*600.* 2 1
+NVIDIA Quadro NVS .*Quadro NVS.* 0 1
NVIDIA RIVA TNT .*RIVA TNT.* 0 0
S3 .*S3 Graphics.* 0 0
SiS SiS.* 0 0
diff --git a/indra/newview/installers/windows/installer_template.nsi b/indra/newview/installers/windows/installer_template.nsi
index 4e8ed807ee..b5d43021ec 100644..100755
--- a/indra/newview/installers/windows/installer_template.nsi
+++ b/indra/newview/installers/windows/installer_template.nsi
@@ -211,6 +211,25 @@ continue_install:
FunctionEnd
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; Checks for CPU valid (must have SSE2 support)
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+Function CheckCPUFlags
+ Call GetWindowsVersion
+ Pop $R0
+ StrCmp $R0 "2000" OK_SSE ; sse check not available on win2k.
+
+ Push $1
+ System::Call 'kernel32::IsProcessorFeaturePresent(i) i(10) .r1'
+ IntCmp $1 1 OK_SSE
+ MessageBox MB_OKCANCEL $(MissingSSE2) /SD IDOK IDOK OK_SSE
+ Quit
+
+ OK_SSE:
+ Pop $1
+ Return
+FunctionEnd
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Close the program, if running. Modifies no variables.
; Allows user to bail out of install process.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@@ -744,6 +763,7 @@ StrCpy $INSTEXE "${INSTEXE}"
StrCpy $INSTSHORTCUT "${SHORTCUT}"
Call CheckWindowsVersion ; warn if on Windows 98/ME
+Call CheckCPUFlags ; Make sure we have SSE2 support
Call CheckIfAdministrator ; Make sure the user can install/uninstall
Call CheckIfAlreadyCurrent ; Make sure that we haven't already installed this version
Call CloseSecondLife ; Make sure we're not running
diff --git a/indra/newview/installers/windows/lang_en-us.nsi b/indra/newview/installers/windows/lang_en-us.nsi
index a01541377d..da0d7f54d2 100644..100755
--- a/indra/newview/installers/windows/lang_en-us.nsi
+++ b/indra/newview/installers/windows/lang_en-us.nsi
Binary files differ
diff --git a/indra/newview/licenses-win32.txt b/indra/newview/licenses-win32.txt
index 7e6d4b4561..8736626907 100644
--- a/indra/newview/licenses-win32.txt
+++ b/indra/newview/licenses-win32.txt
@@ -769,3 +769,72 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+=============
+GLOD license
+=============
+The GLOD Open-Source License Version 1.0 June 16, 2004
+
+Copyright (C) 2003-04 Jonathan Cohen, Nat Duca, Chris Niski, Johns
+Hopkins University and David Luebke, Brenden Schubert, University of
+Virginia. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, is permitted provided that the following conditions are
+met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer and
+ request.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer and
+ request in the documentation and/or other materials provided with
+ the distribution.
+
+3. The name "GLOD" must not be used to endorse or promote products
+ derived from this software without prior written permission.
+
+4. Redistributions of any modified version of this source, whether in
+ source or binary form , must include a form of the following
+ acknowledgment: "This product is derived from the GLOD library,
+ which is available from http://www.cs.jhu.edu/~graphics/GLOD."
+
+5. Redistributions of any modified version of this source in binary
+ form must provide, free of charge, access to the modified version
+ of the code.
+
+6. This license shall be governed by and construed and enforced in
+ accordance with the laws of the State of Maryland, without
+ reference to its conflicts of law provisions. The exclusive
+ jurisdiction and venue for all legal actions relating to this
+ license shall be in courts of competent subject matter jurisdiction
+ located in the State of Maryland.
+
+TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, GLOD IS PROVIDED
+UNDER THIS LICENSE ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY KIND,
+EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
+THAT GLOD IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
+PURPOSE OR NON-INFRINGING. ALL WARRANTIES ARE DISCLAIMED AND THE
+ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE CODE IS WITH
+YOU. SHOULD ANY CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
+COPYRIGHT HOLDER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
+NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
+CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY CODE IS
+AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
+
+TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
+THE COPYRIGHT HOLDER OR ANY OTHER CONTRIBUTOR BE LIABLE FOR ANY
+SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES FOR LOSS OF
+PROFITS, REVENUE, OR FOR LOSS OF INFORMATION OR ANY OTHER LOSS.
+
+YOU EXPRESSLY AGREE TO FOREVER INDEMNIFY, DEFEND AND HOLD HARMLESS THE
+COPYRIGHT HOLDERS AND CONTRIBUTORS OF GLOD AGAINST ALL CLAIMS,
+DEMANDS, SUITS OR OTHER ACTIONS ARISING DIRECTLY OR INDIRECTLY FROM
+YOUR ACCEPTANCE AND USE OF GLOD.
+
+Although NOT REQUIRED, we would appreciate it if active users of GLOD
+put a link on their web site to the GLOD web site when possible.
+
+
diff --git a/indra/newview/llagent.cpp b/indra/newview/llagent.cpp
index 7d908df5ce..3f1bf4c5c2 100644..100755
--- a/indra/newview/llagent.cpp
+++ b/indra/newview/llagent.cpp
@@ -1213,7 +1213,13 @@ BOOL LLAgent::getBusy() const
//-----------------------------------------------------------------------------
// startAutoPilotGlobal()
//-----------------------------------------------------------------------------
-void LLAgent::startAutoPilotGlobal(const LLVector3d &target_global, const std::string& behavior_name, const LLQuaternion *target_rotation, void (*finish_callback)(BOOL, void *), void *callback_data, F32 stop_distance, F32 rot_threshold)
+void LLAgent::startAutoPilotGlobal(
+ const LLVector3d &target_global,
+ const std::string& behavior_name,
+ const LLQuaternion *target_rotation,
+ void (*finish_callback)(BOOL, void *),
+ void *callback_data,
+ F32 stop_distance, F32 rot_threshold)
{
if (!isAgentAvatarValid())
{
@@ -1244,7 +1250,7 @@ void LLAgent::startAutoPilotGlobal(const LLVector3d &target_global, const std::s
else
{
// Guess at a reasonable stop distance.
- mAutoPilotStopDistance = fsqrtf( distance );
+ mAutoPilotStopDistance = (F32) sqrt( distance );
if (mAutoPilotStopDistance < 0.5f)
{
mAutoPilotStopDistance = 0.5f;
diff --git a/indra/newview/llagentcamera.cpp b/indra/newview/llagentcamera.cpp
index f01d5ff1f5..f5fd33d5e0 100644
--- a/indra/newview/llagentcamera.cpp
+++ b/indra/newview/llagentcamera.cpp
@@ -393,10 +393,12 @@ LLVector3 LLAgentCamera::calcFocusOffset(LLViewerObject *object, LLVector3 origi
{
return original_focus_point - obj_pos;
}
-
LLQuaternion inv_obj_rot = ~obj_rot; // get inverse of rotation
- LLVector3 object_extents = object->getScale();
+ LLVector3 object_extents;
+ const LLVector4a* oe4 = object->mDrawable->getSpatialExtents();
+ object_extents.set( oe4[1][0], oe4[1][1], oe4[1][2] );
+
// make sure they object extents are non-zero
object_extents.clamp(0.001f, F32_MAX);
@@ -554,7 +556,9 @@ BOOL LLAgentCamera::calcCameraMinDistance(F32 &obj_min_distance)
{
BOOL soft_limit = FALSE; // is the bounding box to be treated literally (volumes) or as an approximation (avatars)
- if (!mFocusObject || mFocusObject->isDead())
+ if (!mFocusObject || mFocusObject->isDead() ||
+ mFocusObject->isMesh() ||
+ gSavedSettings.getBOOL("DisableCameraConstraints"))
{
obj_min_distance = 0.f;
return TRUE;
diff --git a/indra/newview/llagentpilot.cpp b/indra/newview/llagentpilot.cpp
index 13e1023185..734c502fcf 100644..100755
--- a/indra/newview/llagentpilot.cpp
+++ b/indra/newview/llagentpilot.cpp
@@ -34,12 +34,12 @@
#include "llagent.h"
#include "llappviewer.h"
#include "llviewercontrol.h"
+#include "llviewercamera.h"
+#include "llsdserialize.h"
+#include "llsdutil_math.h"
LLAgentPilot gAgentPilot;
-BOOL LLAgentPilot::sLoop = TRUE;
-BOOL LLAgentPilot::sReplaySession = FALSE;
-
LLAgentPilot::LLAgentPilot() :
mNumRuns(-1),
mQuitAfterRuns(FALSE),
@@ -47,7 +47,10 @@ LLAgentPilot::LLAgentPilot() :
mLastRecordTime(0.f),
mStarted(FALSE),
mPlaying(FALSE),
- mCurrentAction(0)
+ mCurrentAction(0),
+ mOverrideCamera(FALSE),
+ mLoop(TRUE),
+ mReplaySession(FALSE)
{
}
@@ -55,7 +58,26 @@ LLAgentPilot::~LLAgentPilot()
{
}
-void LLAgentPilot::load(const std::string& filename)
+void LLAgentPilot::load()
+{
+ std::string txt_filename = gSavedSettings.getString("StatsPilotFile");
+ std::string xml_filename = gSavedSettings.getString("StatsPilotXMLFile");
+ if (LLFile::isfile(xml_filename))
+ {
+ loadXML(xml_filename);
+ }
+ else if (LLFile::isfile(txt_filename))
+ {
+ loadTxt(txt_filename);
+ }
+ else
+ {
+ lldebugs << "no autopilot file found" << llendl;
+ return;
+ }
+}
+
+void LLAgentPilot::loadTxt(const std::string& filename)
{
if(filename.empty())
{
@@ -75,6 +97,7 @@ void LLAgentPilot::load(const std::string& filename)
llinfos << "Opening pilot file " << filename << llendl;
}
+ mActions.reset();
S32 num_actions;
file >> num_actions;
@@ -89,10 +112,59 @@ void LLAgentPilot::load(const std::string& filename)
mActions.put(new_action);
}
+ mOverrideCamera = false;
+
+ file.close();
+}
+
+void LLAgentPilot::loadXML(const std::string& filename)
+{
+ if(filename.empty())
+ {
+ return;
+ }
+
+ llifstream file(filename);
+
+ if (!file)
+ {
+ lldebugs << "Couldn't open " << filename
+ << ", aborting agentpilot load!" << llendl;
+ return;
+ }
+ else
+ {
+ llinfos << "Opening pilot file " << filename << llendl;
+ }
+
+ mActions.reset();
+ LLSD record;
+ while (!file.eof() && LLSDSerialize::fromXML(record, file))
+ {
+ Action action;
+ action.mTime = record["time"].asReal();
+ action.mType = (EActionType)record["type"].asInteger();
+ action.mCameraView = record["camera_view"].asReal();
+ action.mTarget = ll_vector3d_from_sd(record["target"]);
+ action.mCameraOrigin = ll_vector3_from_sd(record["camera_origin"]);
+ action.mCameraXAxis = ll_vector3_from_sd(record["camera_xaxis"]);
+ action.mCameraYAxis = ll_vector3_from_sd(record["camera_yaxis"]);
+ action.mCameraZAxis = ll_vector3_from_sd(record["camera_zaxis"]);
+ mActions.put(action);
+ }
+ mOverrideCamera = true;
file.close();
}
-void LLAgentPilot::save(const std::string& filename)
+void LLAgentPilot::save()
+{
+ std::string txt_filename = gSavedSettings.getString("StatsPilotFile");
+ std::string xml_filename = gSavedSettings.getString("StatsPilotXMLFile");
+ saveTxt(txt_filename);
+ saveXML(xml_filename);
+}
+
+void LLAgentPilot::saveTxt(const std::string& filename)
{
llofstream file;
file.open(filename);
@@ -108,12 +180,41 @@ void LLAgentPilot::save(const std::string& filename)
for (i = 0; i < mActions.count(); i++)
{
file << mActions[i].mTime << "\t" << mActions[i].mType << "\t";
- file << std::setprecision(32) << mActions[i].mTarget.mdV[VX] << "\t" << mActions[i].mTarget.mdV[VY] << "\t" << mActions[i].mTarget.mdV[VZ] << '\n';
+ file << std::setprecision(32) << mActions[i].mTarget.mdV[VX] << "\t" << mActions[i].mTarget.mdV[VY] << "\t" << mActions[i].mTarget.mdV[VZ];
+ file << '\n';
}
file.close();
}
+void LLAgentPilot::saveXML(const std::string& filename)
+{
+ llofstream file;
+ file.open(filename);
+
+ if (!file)
+ {
+ llinfos << "Couldn't open " << filename << ", aborting agentpilot save!" << llendl;
+ }
+
+ S32 i;
+ for (i = 0; i < mActions.count(); i++)
+ {
+ Action& action = mActions[i];
+ LLSD record;
+ record["time"] = (LLSD::Real)action.mTime;
+ record["type"] = (LLSD::Integer)action.mType;
+ record["camera_view"] = (LLSD::Real)action.mCameraView;
+ record["target"] = ll_sd_from_vector3d(action.mTarget);
+ record["camera_origin"] = ll_sd_from_vector3(action.mCameraOrigin);
+ record["camera_xaxis"] = ll_sd_from_vector3(action.mCameraXAxis);
+ record["camera_yaxis"] = ll_sd_from_vector3(action.mCameraYAxis);
+ record["camera_zaxis"] = ll_sd_from_vector3(action.mCameraZAxis);
+ LLSDSerialize::toXML(record, file);
+ }
+ file.close();
+}
+
void LLAgentPilot::startRecord()
{
mActions.reset();
@@ -125,7 +226,7 @@ void LLAgentPilot::startRecord()
void LLAgentPilot::stopRecord()
{
gAgentPilot.addAction(STRAIGHT);
- gAgentPilot.save(gSavedSettings.getString("StatsPilotFile"));
+ gAgentPilot.save();
mRecording = FALSE;
}
@@ -136,6 +237,12 @@ void LLAgentPilot::addAction(enum EActionType action_type)
action.mType = action_type;
action.mTarget = gAgent.getPositionGlobal();
action.mTime = mTimer.getElapsedTimeF32();
+ LLViewerCamera *cam = LLViewerCamera::getInstance();
+ action.mCameraView = cam->getView();
+ action.mCameraOrigin = cam->getOrigin();
+ action.mCameraXAxis = cam->getXAxis();
+ action.mCameraYAxis = cam->getYAxis();
+ action.mCameraZAxis = cam->getZAxis();
mLastRecordTime = (F32)action.mTime;
mActions.put(action);
}
@@ -152,6 +259,7 @@ void LLAgentPilot::startPlayback()
{
llinfos << "Starting playback, moving to waypoint 0" << llendl;
gAgent.startAutoPilotGlobal(mActions[0].mTarget);
+ moveCamera();
mStarted = FALSE;
}
else
@@ -172,12 +280,53 @@ void LLAgentPilot::stopPlayback()
gAgent.stopAutoPilot();
}
- if (sReplaySession)
+ if (mReplaySession)
{
LLAppViewer::instance()->forceQuit();
}
}
+void LLAgentPilot::moveCamera()
+{
+ if (!getOverrideCamera())
+ return;
+
+ if (mCurrentAction<mActions.count())
+ {
+ S32 start_index = llmax(mCurrentAction-1,0);
+ S32 end_index = mCurrentAction;
+ F32 t = 0.0;
+ F32 timedelta = mActions[end_index].mTime - mActions[start_index].mTime;
+ F32 tickelapsed = mTimer.getElapsedTimeF32()-mActions[start_index].mTime;
+ if (timedelta > 0.0)
+ {
+ t = tickelapsed/timedelta;
+ }
+
+ if ((t<0.0)||(t>1.0))
+ {
+ llwarns << "mCurrentAction is invalid, t = " << t << llendl;
+ return;
+ }
+
+ Action& start = mActions[start_index];
+ Action& end = mActions[end_index];
+
+ F32 view = lerp(start.mCameraView, end.mCameraView, t);
+ LLVector3 origin = lerp(start.mCameraOrigin, end.mCameraOrigin, t);
+ LLQuaternion start_quat(start.mCameraXAxis, start.mCameraYAxis, start.mCameraZAxis);
+ LLQuaternion end_quat(end.mCameraXAxis, end.mCameraYAxis, end.mCameraZAxis);
+ LLQuaternion quat = nlerp(t, start_quat, end_quat);
+ LLMatrix3 mat(quat);
+
+ LLViewerCamera::getInstance()->setView(view);
+ LLViewerCamera::getInstance()->setOrigin(origin);
+ LLViewerCamera::getInstance()->mXAxis = LLVector3(mat.mMatrix[0]);
+ LLViewerCamera::getInstance()->mYAxis = LLVector3(mat.mMatrix[1]);
+ LLViewerCamera::getInstance()->mZAxis = LLVector3(mat.mMatrix[2]);
+ }
+}
+
void LLAgentPilot::updateTarget()
{
if (mPlaying)
@@ -209,12 +358,13 @@ void LLAgentPilot::updateTarget()
if (mCurrentAction < mActions.count())
{
gAgent.startAutoPilotGlobal(mActions[mCurrentAction].mTarget);
+ moveCamera();
}
else
{
stopPlayback();
mNumRuns--;
- if (sLoop)
+ if (mLoop)
{
if ((mNumRuns < 0) || (mNumRuns > 0))
{
@@ -249,29 +399,8 @@ void LLAgentPilot::updateTarget()
}
}
-// static
-void LLAgentPilot::startRecord(void *)
-{
- gAgentPilot.startRecord();
-}
-
-void LLAgentPilot::saveRecord(void *)
+void LLAgentPilot::addWaypoint()
{
- gAgentPilot.stopRecord();
-}
-
-void LLAgentPilot::addWaypoint(void *)
-{
- gAgentPilot.addAction(STRAIGHT);
-}
-
-void LLAgentPilot::startPlayback(void *)
-{
- gAgentPilot.mNumRuns = -1;
- gAgentPilot.startPlayback();
+ addAction(STRAIGHT);
}
-void LLAgentPilot::stopPlayback(void *)
-{
- gAgentPilot.stopPlayback();
-}
diff --git a/indra/newview/llagentpilot.h b/indra/newview/llagentpilot.h
index f3d34246ae..dd1709ec0c 100644..100755
--- a/indra/newview/llagentpilot.h
+++ b/indra/newview/llagentpilot.h
@@ -46,8 +46,12 @@ public:
LLAgentPilot();
virtual ~LLAgentPilot();
- void load(const std::string& filename);
- void save(const std::string& filename);
+ void load();
+ void loadTxt(const std::string& filename);
+ void loadXML(const std::string& filename);
+ void save();
+ void saveTxt(const std::string& filename);
+ void saveXML(const std::string& filename);
void startRecord();
void stopRecord();
@@ -56,19 +60,34 @@ public:
void startPlayback();
void stopPlayback();
+ bool isRecording() { return mRecording; }
+ bool isPlaying() { return mPlaying; }
+ bool getOverrideCamera() { return mOverrideCamera; }
+
void updateTarget();
- static void startRecord(void *);
- static void addWaypoint(void *);
- static void saveRecord(void *);
- static void startPlayback(void *);
- static void stopPlayback(void *);
- static BOOL sLoop;
- static BOOL sReplaySession;
+ void addWaypoint();
+ void moveCamera();
+
+ void setReplaySession(BOOL new_val) { mReplaySession = new_val; }
+ BOOL getReplaySession() { return mReplaySession; }
+
+ void setLoop(BOOL new_val) { mLoop = new_val; }
+ BOOL getLoop() { return mLoop; }
+
+ void setQuitAfterRuns(BOOL quit_val) { mQuitAfterRuns = quit_val; }
+ void setNumRuns(S32 num_runs) { mNumRuns = num_runs; }
+
+private:
+
+
+
+ BOOL mLoop;
+ BOOL mReplaySession;
S32 mNumRuns;
BOOL mQuitAfterRuns;
-private:
+
void setAutopilotTarget(const S32 id);
BOOL mRecording;
@@ -78,6 +97,8 @@ private:
BOOL mPlaying;
S32 mCurrentAction;
+ BOOL mOverrideCamera;
+
class Action
{
public:
@@ -85,10 +106,16 @@ private:
EActionType mType;
LLVector3d mTarget;
F64 mTime;
+ F32 mCameraView;
+ LLVector3 mCameraOrigin;
+ LLVector3 mCameraXAxis;
+ LLVector3 mCameraYAxis;
+ LLVector3 mCameraZAxis;
};
LLDynamicArray<Action> mActions;
LLTimer mTimer;
+
};
extern LLAgentPilot gAgentPilot;
diff --git a/indra/newview/llappearancemgr.cpp b/indra/newview/llappearancemgr.cpp
index 1cf552e42c..24c816d58d 100644
--- a/indra/newview/llappearancemgr.cpp
+++ b/indra/newview/llappearancemgr.cpp
@@ -2767,75 +2767,6 @@ BOOL LLAppearanceMgr::getIsProtectedCOFItem(const LLUUID& obj_id) const
*/
}
-// Shim class to allow arbitrary boost::bind
-// expressions to be run as one-time idle callbacks.
-//
-// TODO: rework idle function spec to take a boost::function in the first place.
-class OnIdleCallbackOneTime
-{
-public:
- OnIdleCallbackOneTime(nullary_func_t callable):
- mCallable(callable)
- {
- }
- static void onIdle(void *data)
- {
- gIdleCallbacks.deleteFunction(onIdle, data);
- OnIdleCallbackOneTime* self = reinterpret_cast<OnIdleCallbackOneTime*>(data);
- self->call();
- delete self;
- }
- void call()
- {
- mCallable();
- }
-private:
- nullary_func_t mCallable;
-};
-
-void doOnIdleOneTime(nullary_func_t callable)
-{
- OnIdleCallbackOneTime* cb_functor = new OnIdleCallbackOneTime(callable);
- gIdleCallbacks.addFunction(&OnIdleCallbackOneTime::onIdle,cb_functor);
-}
-
-// Shim class to allow generic boost functions to be run as
-// recurring idle callbacks. Callable should return true when done,
-// false to continue getting called.
-//
-// TODO: rework idle function spec to take a boost::function in the first place.
-class OnIdleCallbackRepeating
-{
-public:
- OnIdleCallbackRepeating(bool_func_t callable):
- mCallable(callable)
- {
- }
- // Will keep getting called until the callable returns true.
- static void onIdle(void *data)
- {
- OnIdleCallbackRepeating* self = reinterpret_cast<OnIdleCallbackRepeating*>(data);
- bool done = self->call();
- if (done)
- {
- gIdleCallbacks.deleteFunction(onIdle, data);
- delete self;
- }
- }
- bool call()
- {
- return mCallable();
- }
-private:
- bool_func_t mCallable;
-};
-
-void doOnIdleRepeating(bool_func_t callable)
-{
- OnIdleCallbackRepeating* cb_functor = new OnIdleCallbackRepeating(callable);
- gIdleCallbacks.addFunction(&OnIdleCallbackRepeating::onIdle,cb_functor);
-}
-
class CallAfterCategoryFetchStage2: public LLInventoryFetchItemsObserver
{
public:
diff --git a/indra/newview/llappearancemgr.h b/indra/newview/llappearancemgr.h
index c65d9dc9ee..4b1d95cf25 100644
--- a/indra/newview/llappearancemgr.h
+++ b/indra/newview/llappearancemgr.h
@@ -248,15 +248,6 @@ private:
LLUUID findDescendentCategoryIDByName(const LLUUID& parent_id,const std::string& name);
-typedef boost::function<void ()> nullary_func_t;
-typedef boost::function<bool ()> bool_func_t;
-
-// Call a given callable once in idle loop.
-void doOnIdleOneTime(nullary_func_t callable);
-
-// Repeatedly call a callable in idle loop until it returns true.
-void doOnIdleRepeating(bool_func_t callable);
-
// Invoke a given callable after category contents are fully fetched.
void callAfterCategoryFetch(const LLUUID& cat_id, nullary_func_t cb);
diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp
index 6d61be84ef..85447842e6 100644..100755
--- a/indra/newview/llappviewer.cpp
+++ b/indra/newview/llappviewer.cpp
@@ -1,5137 +1,5197 @@
- /**
- * @file llappviewer.cpp
- * @brief The LLAppViewer class definitions
- *
- * $LicenseInfo:firstyear=2007&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-#include "llviewerprecompiledheaders.h"
-
-#include "llappviewer.h"
-
-// Viewer includes
-#include "llversioninfo.h"
-#include "llversionviewer.h"
-#include "llfeaturemanager.h"
-#include "lluictrlfactory.h"
-#include "lltexteditor.h"
-#include "llerrorcontrol.h"
-#include "lleventtimer.h"
-#include "llviewertexturelist.h"
-#include "llgroupmgr.h"
-#include "llagent.h"
-#include "llagentcamera.h"
-#include "llagentlanguage.h"
-#include "llagentwearables.h"
-#include "llwindow.h"
-#include "llviewerstats.h"
-#include "llviewerstatsrecorder.h"
-#include "llmd5.h"
-#include "llpumpio.h"
-#include "llmimetypes.h"
-#include "llslurl.h"
-#include "llstartup.h"
-#include "llfocusmgr.h"
-#include "llviewerjoystick.h"
-#include "llallocator.h"
-#include "llares.h"
-#include "llcurl.h"
-#include "lltexturestats.h"
-#include "lltexturestats.h"
-#include "llviewerwindow.h"
-#include "llviewerdisplay.h"
-#include "llviewermedia.h"
-#include "llviewerparcelmedia.h"
-#include "llviewermediafocus.h"
-#include "llviewermessage.h"
-#include "llviewerobjectlist.h"
-#include "llworldmap.h"
-#include "llmutelist.h"
-#include "llviewerhelp.h"
-#include "lluicolortable.h"
-#include "llurldispatcher.h"
-#include "llurlhistory.h"
-//#include "llfirstuse.h"
-#include "llrender.h"
-#include "llteleporthistory.h"
-#include "lllocationhistory.h"
-#include "llfasttimerview.h"
-#include "llvoicechannel.h"
-#include "llvoavatarself.h"
-#include "llsidetray.h"
-#include "llfeaturemanager.h"
-#include "llurlmatch.h"
-#include "lltextutil.h"
-#include "lllogininstance.h"
-#include "llprogressview.h"
-
-#include "llweb.h"
-#include "llsecondlifeurls.h"
-#include "llupdaterservice.h"
-
-// Linden library includes
-#include "llavatarnamecache.h"
-#include "llimagej2c.h"
-#include "llmemory.h"
-#include "llprimitive.h"
-#include "llurlaction.h"
-#include "llurlentry.h"
-#include "llvfile.h"
-#include "llvfsthread.h"
-#include "llvolumemgr.h"
-#include "llxfermanager.h"
-
-#include "llnotificationmanager.h"
-#include "llnotifications.h"
-#include "llnotificationsutil.h"
-
-// Third party library includes
-#include <boost/bind.hpp>
-
-
-#if LL_WINDOWS
-# include <share.h> // For _SH_DENYWR in initMarkerFile
-#else
-# include <sys/file.h> // For initMarkerFile support
-#endif
-
-#include "llapr.h"
-#include "apr_dso.h"
-#include <boost/lexical_cast.hpp>
-
-#include "llviewerkeyboard.h"
-#include "lllfsthread.h"
-#include "llworkerthread.h"
-#include "lltexturecache.h"
-#include "lltexturefetch.h"
-#include "llimageworker.h"
-#include "llevents.h"
-
-// The files below handle dependencies from cleanup.
-#include "llkeyframemotion.h"
-#include "llworldmap.h"
-#include "llhudmanager.h"
-#include "lltoolmgr.h"
-#include "llassetstorage.h"
-#include "llpolymesh.h"
-#include "llcachename.h"
-#include "llaudioengine.h"
-#include "llstreamingaudio.h"
-#include "llviewermenu.h"
-#include "llselectmgr.h"
-#include "lltrans.h"
-#include "lltransutil.h"
-#include "lltracker.h"
-#include "llviewerparcelmgr.h"
-#include "llworldmapview.h"
-#include "llpostprocess.h"
-#include "llwlparammanager.h"
-#include "llwaterparammanager.h"
-
-#include "lldebugview.h"
-#include "llconsole.h"
-#include "llcontainerview.h"
-#include "lltooltip.h"
-
-#include "llsdserialize.h"
-
-#include "llworld.h"
-#include "llhudeffecttrail.h"
-#include "llvectorperfoptions.h"
-#include "llslurl.h"
-#include "llwatchdog.h"
-
-// Included so that constants/settings might be initialized
-// in save_settings_to_globals()
-#include "llbutton.h"
-#include "llstatusbar.h"
-#include "llsurface.h"
-#include "llvosky.h"
-#include "llvotree.h"
-#include "llvoavatar.h"
-#include "llfolderview.h"
-#include "llagentpilot.h"
-#include "llvovolume.h"
-#include "llflexibleobject.h"
-#include "llvosurfacepatch.h"
-#include "llviewerfloaterreg.h"
-#include "llcommandlineparser.h"
-#include "llfloatermemleak.h"
-#include "llfloaterreg.h"
-#include "llfloatersnapshot.h"
-#include "llfloaterinventory.h"
-
-// includes for idle() idleShutdown()
-#include "llviewercontrol.h"
-#include "lleventnotifier.h"
-#include "llcallbacklist.h"
-#include "pipeline.h"
-#include "llgesturemgr.h"
-#include "llsky.h"
-#include "llvlmanager.h"
-#include "llviewercamera.h"
-#include "lldrawpoolbump.h"
-#include "llvieweraudio.h"
-#include "llimview.h"
-#include "llviewerthrottle.h"
-#include "llparcel.h"
-#include "llavatariconctrl.h"
-#include "llgroupiconctrl.h"
-#include "llviewerassetstats.h"
-
-// Include for security api initialization
-#include "llsecapi.h"
-#include "llmachineid.h"
-
-#include "llmainlooprepeater.h"
-
-// *FIX: These extern globals should be cleaned up.
-// The globals either represent state/config/resource-storage of either
-// this app, or another 'component' of the viewer. App globals should be
-// moved into the app class, where as the other globals should be
-// moved out of here.
-// If a global symbol reference seems valid, it will be included
-// via header files above.
-
-//----------------------------------------------------------------------------
-// llviewernetwork.h
-#include "llviewernetwork.h"
-// define a self-registering event API object
-#include "llappviewerlistener.h"
-
-#if (LL_LINUX || LL_SOLARIS) && LL_GTK
-#include "glib.h"
-#endif // (LL_LINUX || LL_SOLARIS) && LL_GTK
-
-#if LL_MSVC
-// disable boost::lexical_cast warning
-#pragma warning (disable:4702)
-#endif
-
-static LLAppViewerListener sAppViewerListener(LLAppViewer::instance);
-
-////// Windows-specific includes to the bottom - nasty defines in these pollute the preprocessor
-//
-//----------------------------------------------------------------------------
-// viewer.cpp - these are only used in viewer, should be easily moved.
-
-#if LL_DARWIN
-extern void init_apple_menu(const char* product);
-#endif // LL_DARWIN
-
-extern BOOL gRandomizeFramerate;
-extern BOOL gPeriodicSlowFrame;
-extern BOOL gDebugGL;
-
-////////////////////////////////////////////////////////////
-// All from the last globals push...
-const F32 DEFAULT_AFK_TIMEOUT = 5.f * 60.f; // time with no input before user flagged as Away From Keyboard
-
-F32 gSimLastTime; // Used in LLAppViewer::init and send_stats()
-F32 gSimFrames;
-
-BOOL gShowObjectUpdates = FALSE;
-BOOL gUseQuickTime = TRUE;
-
-eLastExecEvent gLastExecEvent = LAST_EXEC_NORMAL;
-
-LLSD gDebugInfo;
-
-U32 gFrameCount = 0;
-U32 gForegroundFrameCount = 0; // number of frames that app window was in foreground
-LLPumpIO* gServicePump = NULL;
-
-U64 gFrameTime = 0;
-F32 gFrameTimeSeconds = 0.f;
-F32 gFrameIntervalSeconds = 0.f;
-F32 gFPSClamped = 10.f; // Pretend we start at target rate.
-F32 gFrameDTClamped = 0.f; // Time between adjacent checks to network for packets
-U64 gStartTime = 0; // gStartTime is "private", used only to calculate gFrameTimeSeconds
-U32 gFrameStalls = 0;
-const F64 FRAME_STALL_THRESHOLD = 1.0;
-
-LLTimer gRenderStartTime;
-LLFrameTimer gForegroundTime;
-LLFrameTimer gLoggedInTime;
-LLTimer gLogoutTimer;
-static const F32 LOGOUT_REQUEST_TIME = 6.f; // this will be cut short by the LogoutReply msg.
-F32 gLogoutMaxTime = LOGOUT_REQUEST_TIME;
-
-BOOL gDisconnected = FALSE;
-
-// used to restore texture state after a mode switch
-LLFrameTimer gRestoreGLTimer;
-BOOL gRestoreGL = FALSE;
-BOOL gUseWireframe = FALSE;
-
-// VFS globals - see llappviewer.h
-LLVFS* gStaticVFS = NULL;
-
-LLMemoryInfo gSysMemory;
-U64 gMemoryAllocated = 0; // updated in display_stats() in llviewerdisplay.cpp
-
-std::string gLastVersionChannel;
-
-LLVector3 gWindVec(3.0, 3.0, 0.0);
-LLVector3 gRelativeWindVec(0.0, 0.0, 0.0);
-
-U32 gPacketsIn = 0;
-
-BOOL gPrintMessagesThisFrame = FALSE;
-
-BOOL gRandomizeFramerate = FALSE;
-BOOL gPeriodicSlowFrame = FALSE;
-
-BOOL gCrashOnStartup = FALSE;
-BOOL gLLErrorActivated = FALSE;
-BOOL gLogoutInProgress = FALSE;
-
-////////////////////////////////////////////////////////////
-// Internal globals... that should be removed.
-static std::string gArgs;
-
-const std::string MARKER_FILE_NAME("SecondLife.exec_marker");
-const std::string ERROR_MARKER_FILE_NAME("SecondLife.error_marker");
-const std::string LLERROR_MARKER_FILE_NAME("SecondLife.llerror_marker");
-const std::string LOGOUT_MARKER_FILE_NAME("SecondLife.logout_marker");
-static BOOL gDoDisconnect = FALSE;
-static std::string gLaunchFileOnQuit;
-
-// Used on Win32 for other apps to identify our window (eg, win_setup)
-const char* const VIEWER_WINDOW_CLASSNAME = "Second Life";
-
-//----------------------------------------------------------------------------
-
-// List of entries from strings.xml to always replace
-static std::set<std::string> default_trans_args;
-void init_default_trans_args()
-{
- default_trans_args.insert("SECOND_LIFE"); // World
- default_trans_args.insert("APP_NAME");
- default_trans_args.insert("CAPITALIZED_APP_NAME");
- default_trans_args.insert("SECOND_LIFE_GRID");
- default_trans_args.insert("SUPPORT_SITE");
-}
-
-//----------------------------------------------------------------------------
-// File scope definitons
-const char *VFS_DATA_FILE_BASE = "data.db2.x.";
-const char *VFS_INDEX_FILE_BASE = "index.db2.x.";
-
-
-struct SettingsFile : public LLInitParam::Block<SettingsFile>
-{
- Mandatory<std::string> name;
- Optional<std::string> file_name;
- Optional<bool> required,
- persistent;
- Optional<std::string> file_name_setting;
-
- SettingsFile()
- : name("name"),
- file_name("file_name"),
- required("required", false),
- persistent("persistent", true),
- file_name_setting("file_name_setting")
- {}
-};
-
-struct SettingsGroup : public LLInitParam::Block<SettingsGroup>
-{
- Mandatory<std::string> name;
- Mandatory<S32> path_index;
- Multiple<SettingsFile> files;
-
- SettingsGroup()
- : name("name"),
- path_index("path_index"),
- files("file")
- {}
-};
-
-struct SettingsFiles : public LLInitParam::Block<SettingsFiles>
-{
- Multiple<SettingsGroup> groups;
-
- SettingsFiles()
- : groups("group")
- {}
-};
-
-static std::string gWindowTitle;
-
-LLAppViewer::LLUpdaterInfo *LLAppViewer::sUpdaterInfo = NULL ;
-
-//----------------------------------------------------------------------------
-// Metrics logging control constants
-//----------------------------------------------------------------------------
-static const F32 METRICS_INTERVAL_DEFAULT = 600.0;
-static const F32 METRICS_INTERVAL_QA = 30.0;
-static F32 app_metrics_interval = METRICS_INTERVAL_DEFAULT;
-static bool app_metrics_qa_mode = false;
-
-void idle_afk_check()
-{
- // check idle timers
- if (gSavedSettings.getS32("AFKTimeout") && (gAwayTriggerTimer.getElapsedTimeF32() > gSavedSettings.getS32("AFKTimeout")))
- {
- gAgent.setAFK();
- }
-}
-
-// A callback set in LLAppViewer::init()
-static void ui_audio_callback(const LLUUID& uuid)
-{
- if (gAudiop)
- {
- gAudiop->triggerSound(uuid, gAgent.getID(), 1.0f, LLAudioEngine::AUDIO_TYPE_UI);
- }
-}
-
-bool create_text_segment_icon_from_url_match(LLUrlMatch* match,LLTextBase* base)
-{
- if(!match || !base || base->getPlainText())
- return false;
-
- LLUUID match_id = match->getID();
-
- LLIconCtrl* icon;
-
- if(gAgent.isInGroup(match_id, TRUE))
- {
- LLGroupIconCtrl::Params icon_params;
- icon_params.group_id = match_id;
- icon_params.rect = LLRect(0, 16, 16, 0);
- icon_params.visible = true;
- icon = LLUICtrlFactory::instance().create<LLGroupIconCtrl>(icon_params);
- }
- else
- {
- LLAvatarIconCtrl::Params icon_params;
- icon_params.avatar_id = match_id;
- icon_params.rect = LLRect(0, 16, 16, 0);
- icon_params.visible = true;
- icon = LLUICtrlFactory::instance().create<LLAvatarIconCtrl>(icon_params);
- }
-
- LLInlineViewSegment::Params params;
- params.force_newline = false;
- params.view = icon;
- params.left_pad = 4;
- params.right_pad = 4;
- params.top_pad = -2;
- params.bottom_pad = 2;
-
- base->appendWidget(params," ",false);
-
- return true;
-}
-
-void request_initial_instant_messages()
-{
- static BOOL requested = FALSE;
- if (!requested
- && gMessageSystem
- && LLMuteList::getInstance()->isLoaded()
- && isAgentAvatarValid())
- {
- // Auto-accepted inventory items may require the avatar object
- // to build a correct name. Likewise, inventory offers from
- // muted avatars require the mute list to properly mute.
- LLMessageSystem* msg = gMessageSystem;
- msg->newMessageFast(_PREHASH_RetrieveInstantMessages);
- msg->nextBlockFast(_PREHASH_AgentData);
- msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
- msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- gAgent.sendReliableMessage();
- requested = TRUE;
- }
-}
-
-// A settings system callback for CrashSubmitBehavior
-bool handleCrashSubmitBehaviorChanged(const LLSD& newvalue)
-{
- S32 cb = newvalue.asInteger();
- const S32 NEVER_SUBMIT_REPORT = 2;
- if(cb == NEVER_SUBMIT_REPORT)
- {
- LLAppViewer::instance()->destroyMainloopTimeout();
- }
- return true;
-}
-
-// Use these strictly for things that are constructed at startup,
-// or for things that are performance critical. JC
-static void settings_to_globals()
-{
- LLBUTTON_H_PAD = gSavedSettings.getS32("ButtonHPad");
- BTN_HEIGHT_SMALL = gSavedSettings.getS32("ButtonHeightSmall");
- BTN_HEIGHT = gSavedSettings.getS32("ButtonHeight");
-
- MENU_BAR_HEIGHT = gSavedSettings.getS32("MenuBarHeight");
- MENU_BAR_WIDTH = gSavedSettings.getS32("MenuBarWidth");
-
- LLSurface::setTextureSize(gSavedSettings.getU32("RegionTextureSize"));
-
- LLImageGL::sGlobalUseAnisotropic = gSavedSettings.getBOOL("RenderAnisotropic");
- LLVOVolume::sLODFactor = gSavedSettings.getF32("RenderVolumeLODFactor");
- LLVOVolume::sDistanceFactor = 1.f-LLVOVolume::sLODFactor * 0.1f;
- LLVolumeImplFlexible::sUpdateFactor = gSavedSettings.getF32("RenderFlexTimeFactor");
- LLVOTree::sTreeFactor = gSavedSettings.getF32("RenderTreeLODFactor");
- LLVOAvatar::sLODFactor = gSavedSettings.getF32("RenderAvatarLODFactor");
- LLVOAvatar::sMaxVisible = (U32)gSavedSettings.getS32("RenderAvatarMaxVisible");
- LLVOAvatar::sVisibleInFirstPerson = gSavedSettings.getBOOL("FirstPersonAvatarVisible");
- // clamp auto-open time to some minimum usable value
- LLFolderView::sAutoOpenTime = llmax(0.25f, gSavedSettings.getF32("FolderAutoOpenDelay"));
- LLSelectMgr::sRectSelectInclusive = gSavedSettings.getBOOL("RectangleSelectInclusive");
- LLSelectMgr::sRenderHiddenSelections = gSavedSettings.getBOOL("RenderHiddenSelections");
- LLSelectMgr::sRenderLightRadius = gSavedSettings.getBOOL("RenderLightRadius");
-
- gAgentPilot.mNumRuns = gSavedSettings.getS32("StatsNumRuns");
- gAgentPilot.mQuitAfterRuns = gSavedSettings.getBOOL("StatsQuitAfterRuns");
- gAgent.setHideGroupTitle(gSavedSettings.getBOOL("RenderHideGroupTitle"));
-
- gDebugWindowProc = gSavedSettings.getBOOL("DebugWindowProc");
- gShowObjectUpdates = gSavedSettings.getBOOL("ShowObjectUpdates");
- LLWorldMapView::sMapScale = gSavedSettings.getF32("MapScale");
-}
-
-static void settings_modify()
-{
- LLRenderTarget::sUseFBO = gSavedSettings.getBOOL("RenderUseFBO");
- LLVOAvatar::sUseImpostors = gSavedSettings.getBOOL("RenderUseImpostors");
- LLVOSurfacePatch::sLODFactor = gSavedSettings.getF32("RenderTerrainLODFactor");
- LLVOSurfacePatch::sLODFactor *= LLVOSurfacePatch::sLODFactor; //square lod factor to get exponential range of [1,4]
- gDebugGL = gSavedSettings.getBOOL("RenderDebugGL") || gDebugSession;
- gDebugPipeline = gSavedSettings.getBOOL("RenderDebugPipeline");
- gAuditTexture = gSavedSettings.getBOOL("AuditTexture");
-#if LL_VECTORIZE
- if (gSysCPU.hasAltivec())
- {
- gSavedSettings.setBOOL("VectorizeEnable", TRUE );
- gSavedSettings.setU32("VectorizeProcessor", 0 );
- }
- else
- if (gSysCPU.hasSSE2())
- {
- gSavedSettings.setBOOL("VectorizeEnable", TRUE );
- gSavedSettings.setU32("VectorizeProcessor", 2 );
- }
- else
- if (gSysCPU.hasSSE())
- {
- gSavedSettings.setBOOL("VectorizeEnable", TRUE );
- gSavedSettings.setU32("VectorizeProcessor", 1 );
- }
- else
- {
- // Don't bother testing or running if CPU doesn't support it. JC
- gSavedSettings.setBOOL("VectorizePerfTest", FALSE );
- gSavedSettings.setBOOL("VectorizeEnable", FALSE );
- gSavedSettings.setU32("VectorizeProcessor", 0 );
- gSavedSettings.setBOOL("VectorizeSkin", FALSE);
- }
-#else
- // This build target doesn't support SSE, don't test/run.
- gSavedSettings.setBOOL("VectorizePerfTest", FALSE );
- gSavedSettings.setBOOL("VectorizeEnable", FALSE );
- gSavedSettings.setU32("VectorizeProcessor", 0 );
- gSavedSettings.setBOOL("VectorizeSkin", FALSE);
-
- // disable fullscreen mode, unsupported
- gSavedSettings.setBOOL("WindowFullScreen", FALSE);
-#endif
-}
-
-class LLFastTimerLogThread : public LLThread
-{
-public:
- std::string mFile;
-
- LLFastTimerLogThread(std::string& test_name) : LLThread("fast timer log")
- {
- std::string file_name = test_name + std::string(".slp");
- mFile = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, file_name);
- }
-
- void run()
- {
- std::ofstream os(mFile.c_str());
-
- while (!LLAppViewer::instance()->isQuitting())
- {
- LLFastTimer::writeLog(os);
- os.flush();
- ms_sleep(32);
- }
-
- os.close();
- }
-
-};
-
-//virtual
-bool LLAppViewer::initSLURLHandler()
-{
- // does nothing unless subclassed
- return false;
-}
-
-//virtual
-bool LLAppViewer::sendURLToOtherInstance(const std::string& url)
-{
- // does nothing unless subclassed
- return false;
-}
-
-//----------------------------------------------------------------------------
-// LLAppViewer definition
-
-// Static members.
-// The single viewer app.
-LLAppViewer* LLAppViewer::sInstance = NULL;
-
-const std::string LLAppViewer::sGlobalSettingsName = "Global";
-
-LLTextureCache* LLAppViewer::sTextureCache = NULL;
-LLImageDecodeThread* LLAppViewer::sImageDecodeThread = NULL;
-LLTextureFetch* LLAppViewer::sTextureFetch = NULL;
-
-LLAppViewer::LLAppViewer() :
- mMarkerFile(),
- mLogoutMarkerFile(NULL),
- mReportedCrash(false),
- mNumSessions(0),
- mPurgeCache(false),
- mPurgeOnExit(false),
- mSecondInstance(false),
- mSavedFinalSnapshot(false),
- mForceGraphicsDetail(false),
- mQuitRequested(false),
- mLogoutRequestSent(false),
- mYieldTime(-1),
- mMainloopTimeout(NULL),
- mAgentRegionLastAlive(false),
- mRandomizeFramerate(LLCachedControl<bool>(gSavedSettings,"Randomize Framerate", FALSE)),
- mPeriodicSlowFrame(LLCachedControl<bool>(gSavedSettings,"Periodic Slow Frame", FALSE)),
- mFastTimerLogThread(NULL),
- mUpdater(new LLUpdaterService()),
- mSettingsLocationList(NULL)
-{
- if(NULL != sInstance)
- {
- llerrs << "Oh no! An instance of LLAppViewer already exists! LLAppViewer is sort of like a singleton." << llendl;
- }
-
- setupErrorHandling();
- sInstance = this;
- gLoggedInTime.stop();
-
- LLLoginInstance::instance().setUpdaterService(mUpdater.get());
-}
-
-LLAppViewer::~LLAppViewer()
-{
- delete mSettingsLocationList;
-
- LLLoginInstance::instance().setUpdaterService(0);
-
- destroyMainloopTimeout();
-
- // If we got to this destructor somehow, the app didn't hang.
- removeMarkerFile();
-}
-
-bool LLAppViewer::init()
-{
- //
- // Start of the application
- //
- // IMPORTANT! Do NOT put anything that will write
- // into the log files during normal startup until AFTER
- // we run the "program crashed last time" error handler below.
- //
- LLFastTimer::reset();
-
- // Need to do this initialization before we do anything else, since anything
- // that touches files should really go through the lldir API
- gDirUtilp->initAppDirs("SecondLife");
- // set skin search path to default, will be overridden later
- // this allows simple skinned file lookups to work
- gDirUtilp->setSkinFolder("default");
-
- initLogging();
-
- //
- // OK to write stuff to logs now, we've now crash reported if necessary
- //
-
- init_default_trans_args();
-
- if (!initConfiguration())
- return false;
-
- // write Google Breakpad minidump files to our log directory
- std::string logdir = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "");
- logdir += gDirUtilp->getDirDelimiter();
- setMiniDumpDir(logdir);
-
- // Although initLogging() is the right place to mess with
- // setFatalFunction(), we can't query gSavedSettings until after
- // initConfiguration().
- S32 rc(gSavedSettings.getS32("QAModeTermCode"));
- if (rc >= 0)
- {
- // QAModeTermCode set, terminate with that rc on LL_ERRS. Use _exit()
- // rather than exit() because normal cleanup depends too much on
- // successful startup!
- LLError::setFatalFunction(boost::bind(_exit, rc));
- }
-
- mAlloc.setProfilingEnabled(gSavedSettings.getBOOL("MemProfiling"));
-
-#if LL_RECORD_VIEWER_STATS
- LLViewerStatsRecorder::initClass();
-#endif
-
- // *NOTE:Mani - LLCurl::initClass is not thread safe.
- // Called before threads are created.
- LLCurl::initClass();
- LLMachineID::init();
-
- {
- // Viewer metrics initialization
- static LLCachedControl<bool> metrics_submode(gSavedSettings,
- "QAModeMetrics",
- false,
- "Enables QA features (logging, faster cycling) for metrics collector");
-
- if (metrics_submode)
- {
- app_metrics_qa_mode = true;
- app_metrics_interval = METRICS_INTERVAL_QA;
- }
- LLViewerAssetStatsFF::init();
- }
-
- initThreads();
- writeSystemInfo();
-
- // Initialize updater service (now that we have an io pump)
- initUpdater();
- if(isQuitting())
- {
- // Early out here because updater set the quitting flag.
- return true;
- }
-
- //////////////////////////////////////////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////////////
- // *FIX: The following code isn't grouped into functions yet.
-
- // Statistics / debug timer initialization
- init_statistics();
-
- //
- // Various introspection concerning the libs we're using - particularly
- // the libs involved in getting to a full login screen.
- //
- LL_INFOS("InitInfo") << "J2C Engine is: " << LLImageJ2C::getEngineInfo() << LL_ENDL;
- LL_INFOS("InitInfo") << "libcurl version is: " << LLCurl::getVersionString() << LL_ENDL;
-
- // Get the single value from the crash settings file, if it exists
- std::string crash_settings_filename = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, CRASH_SETTINGS_FILE);
- gCrashSettings.loadFromFile(crash_settings_filename);
- if(gSavedSettings.getBOOL("IgnoreAllNotifications"))
- {
- gCrashSettings.setS32(CRASH_BEHAVIOR_SETTING, CRASH_BEHAVIOR_ALWAYS_SEND);
- gCrashSettings.saveToFile(crash_settings_filename, FALSE);
- }
-
- /////////////////////////////////////////////////
- // OS-specific login dialogs
- /////////////////////////////////////////////////
-
- //test_cached_control();
-
- // track number of times that app has run
- mNumSessions = gSavedSettings.getS32("NumSessions");
- mNumSessions++;
- gSavedSettings.setS32("NumSessions", mNumSessions);
-
- if (gSavedSettings.getBOOL("VerboseLogs"))
- {
- LLError::setPrintLocation(true);
- }
-
- // Widget construction depends on LLUI being initialized
- LLUI::settings_map_t settings_map;
- settings_map["config"] = &gSavedSettings;
- settings_map["ignores"] = &gWarningSettings;
- settings_map["floater"] = &gSavedSettings; // *TODO: New settings file
- settings_map["account"] = &gSavedPerAccountSettings;
-
- LLUI::initClass(settings_map,
- LLUIImageList::getInstance(),
- ui_audio_callback,
- &LLUI::sGLScaleFactor);
-
- // Setup paths and LLTrans after LLUI::initClass has been called
- LLUI::setupPaths();
- LLTransUtil::parseStrings("strings.xml", default_trans_args);
- LLTransUtil::parseLanguageStrings("language_settings.xml");
-
- // LLKeyboard relies on LLUI to know what some accelerator keys are called.
- LLKeyboard::setStringTranslatorFunc( LLTrans::getKeyboardString );
-
- LLWeb::initClass(); // do this after LLUI
-
- // Provide the text fields with callbacks for opening Urls
- LLUrlAction::setOpenURLCallback(&LLWeb::loadURL);
- LLUrlAction::setOpenURLInternalCallback(&LLWeb::loadURLInternal);
- LLUrlAction::setOpenURLExternalCallback(&LLWeb::loadURLExternal);
- LLUrlAction::setExecuteSLURLCallback(&LLURLDispatcher::dispatchFromTextEditor);
-
- // Let code in llui access the viewer help floater
- LLUI::sHelpImpl = LLViewerHelp::getInstance();
-
- // Load translations for tooltips
- LLFloater::initClass();
-
- /////////////////////////////////////////////////
-
- LLToolMgr::getInstance(); // Initialize tool manager if not already instantiated
-
- LLViewerFloaterReg::registerFloaters();
-
- /////////////////////////////////////////////////
- //
- // Load settings files
- //
- //
- LLGroupMgr::parseRoleActions("role_actions.xml");
-
- LLAgent::parseTeleportMessages("teleport_strings.xml");
-
- LLViewerJointMesh::updateVectorize();
-
- // load MIME type -> media impl mappings
- std::string mime_types_name;
-#if LL_DARWIN
- mime_types_name = "mime_types_mac.xml";
-#elif LL_LINUX
- mime_types_name = "mime_types_linux.xml";
-#else
- mime_types_name = "mime_types.xml";
-#endif
- LLMIMETypes::parseMIMETypes( mime_types_name );
-
- // Copy settings to globals. *TODO: Remove or move to appropriage class initializers
- settings_to_globals();
- // Setup settings listeners
- settings_setup_listeners();
- // Modify settings based on system configuration and compile options
- settings_modify();
-
- // Find partition serial number (Windows) or hardware serial (Mac)
- mSerialNumber = generateSerialNumber();
-
- // do any necessary set-up for accepting incoming SLURLs from apps
- initSLURLHandler();
-
- if(false == initHardwareTest())
- {
- // Early out from user choice.
- return false;
- }
-
- // Prepare for out-of-memory situations, during which we will crash on
- // purpose and save a dump.
-#if LL_WINDOWS && LL_RELEASE_FOR_DOWNLOAD && LL_USE_SMARTHEAP
- MemSetErrorHandler(first_mem_error_handler);
-#endif // LL_WINDOWS && LL_RELEASE_FOR_DOWNLOAD && LL_USE_SMARTHEAP
-
- // *Note: this is where gViewerStats used to be created.
-
- //
- // Initialize the VFS, and gracefully handle initialization errors
- //
-
- if (!initCache())
- {
- std::ostringstream msg;
- msg << LLTrans::getString("MBUnableToAccessFile");
- OSMessageBox(msg.str(),LLStringUtil::null,OSMB_OK);
- return 1;
- }
-
- // Initialize the repeater service.
- LLMainLoopRepeater::instance().start();
-
- //
- // Initialize the window
- //
- gGLActive = TRUE;
- initWindow();
-
- // initWindow also initializes the Feature List, so now we can initialize this global.
- LLCubeMap::sUseCubeMaps = LLFeatureManager::getInstance()->isFeatureAvailable("RenderCubeMap");
-
- // call all self-registered classes
- LLInitClassList::instance().fireCallbacks();
-
- LLFolderViewItem::initClass(); // SJB: Needs to happen after initWindow(), not sure why but related to fonts
-
- gGLManager.getGLInfo(gDebugInfo);
- gGLManager.printGLInfoString();
-
- // Load Default bindings
- std::string key_bindings_file = gDirUtilp->findFile("keys.xml",
- gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, ""),
- gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
-
-
- if (!gViewerKeyboard.loadBindingsXML(key_bindings_file))
- {
- std::string key_bindings_file = gDirUtilp->findFile("keys.ini",
- gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, ""),
- gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
- if (!gViewerKeyboard.loadBindings(key_bindings_file))
- {
- LL_ERRS("InitInfo") << "Unable to open keys.ini" << LL_ENDL;
- }
- }
-
- // If we don't have the right GL requirements, exit.
- if (!gGLManager.mHasRequirements && !gNoRender)
- {
- // can't use an alert here since we're exiting and
- // all hell breaks lose.
- OSMessageBox(
- LLNotifications::instance().getGlobalString("UnsupportedGLRequirements"),
- LLStringUtil::null,
- OSMB_OK);
- return 0;
- }
-
- // alert the user if they are using unsupported hardware
- if(!gSavedSettings.getBOOL("AlertedUnsupportedHardware"))
- {
- bool unsupported = false;
- LLSD args;
- std::string minSpecs;
-
- // get cpu data from xml
- std::stringstream minCPUString(LLNotifications::instance().getGlobalString("UnsupportedCPUAmount"));
- S32 minCPU = 0;
- minCPUString >> minCPU;
-
- // get RAM data from XML
- std::stringstream minRAMString(LLNotifications::instance().getGlobalString("UnsupportedRAMAmount"));
- U64 minRAM = 0;
- minRAMString >> minRAM;
- minRAM = minRAM * 1024 * 1024;
-
- if(!LLFeatureManager::getInstance()->isGPUSupported() && LLFeatureManager::getInstance()->getGPUClass() != GPU_CLASS_UNKNOWN)
- {
- minSpecs += LLNotifications::instance().getGlobalString("UnsupportedGPU");
- minSpecs += "\n";
- unsupported = true;
- }
- if(gSysCPU.getMHz() < minCPU)
- {
- minSpecs += LLNotifications::instance().getGlobalString("UnsupportedCPU");
- minSpecs += "\n";
- unsupported = true;
- }
- if(gSysMemory.getPhysicalMemoryClamped() < minRAM)
- {
- minSpecs += LLNotifications::instance().getGlobalString("UnsupportedRAM");
- minSpecs += "\n";
- unsupported = true;
- }
-
- if (LLFeatureManager::getInstance()->getGPUClass() == GPU_CLASS_UNKNOWN)
- {
- LLNotificationsUtil::add("UnknownGPU");
- }
-
- if(unsupported)
- {
- if(!gSavedSettings.controlExists("WarnUnsupportedHardware")
- || gSavedSettings.getBOOL("WarnUnsupportedHardware"))
- {
- args["MINSPECS"] = minSpecs;
- LLNotificationsUtil::add("UnsupportedHardware", args );
- }
-
- }
- }
-
-
- // save the graphics card
- gDebugInfo["GraphicsCard"] = LLFeatureManager::getInstance()->getGPUString();
-
- // Save the current version to the prefs file
- gSavedSettings.setString("LastRunVersion",
- LLVersionInfo::getChannelAndVersion());
-
- gSimLastTime = gRenderStartTime.getElapsedTimeF32();
- gSimFrames = (F32)gFrameCount;
-
- LLViewerJoystick::getInstance()->init(false);
-
- try {
- initializeSecHandler();
- }
- catch (LLProtectedDataException ex)
- {
- LLNotificationsUtil::add("CorruptedProtectedDataStore");
- }
- LLHTTPClient::setCertVerifyCallback(secapiSSLCertVerifyCallback);
-
-
- gGLActive = FALSE;
- if (gSavedSettings.getBOOL("QAMode") && gSavedSettings.getS32("QAModeEventHostPort") > 0)
- {
- loadEventHostModule(gSavedSettings.getS32("QAModeEventHostPort"));
- }
-
- LLViewerMedia::initClass();
- LLTextUtil::TextHelpers::iconCallbackCreationFunction = create_text_segment_icon_from_url_match;
-
- //EXT-7013 - On windows for some locale (Japanese) standard
- //datetime formatting functions didn't support some parameters such as "weekday".
- //Names for days and months localized in xml are also useful for Polish locale(STORM-107).
- std::string language = LLControlGroup::getInstance(sGlobalSettingsName)->getString("Language");
- if(language == "ja" || language == "pl")
- {
- LLStringOps::setupWeekDaysNames(LLTrans::getString("dateTimeWeekdaysNames"));
- LLStringOps::setupWeekDaysShortNames(LLTrans::getString("dateTimeWeekdaysShortNames"));
- LLStringOps::setupMonthNames(LLTrans::getString("dateTimeMonthNames"));
- LLStringOps::setupMonthShortNames(LLTrans::getString("dateTimeMonthShortNames"));
- LLStringOps::setupDayFormat(LLTrans::getString("dateTimeDayFormat"));
-
- LLStringOps::sAM = LLTrans::getString("dateTimeAM");
- LLStringOps::sPM = LLTrans::getString("dateTimePM");
- }
-
- LLAgentLanguage::init();
-
-
-
- return true;
-}
-
-static LLFastTimer::DeclareTimer FTM_MESSAGES("System Messages");
-static LLFastTimer::DeclareTimer FTM_SLEEP("Sleep");
-static LLFastTimer::DeclareTimer FTM_TEXTURE_CACHE("Texture Cache");
-static LLFastTimer::DeclareTimer FTM_DECODE("Image Decode");
-static LLFastTimer::DeclareTimer FTM_VFS("VFS Thread");
-static LLFastTimer::DeclareTimer FTM_LFS("LFS Thread");
-static LLFastTimer::DeclareTimer FTM_PAUSE_THREADS("Pause Threads");
-static LLFastTimer::DeclareTimer FTM_IDLE("Idle");
-static LLFastTimer::DeclareTimer FTM_PUMP("Pump");
-static LLFastTimer::DeclareTimer FTM_PUMP_ARES("Ares");
-static LLFastTimer::DeclareTimer FTM_PUMP_SERVICE("Service");
-static LLFastTimer::DeclareTimer FTM_SERVICE_CALLBACK("Callback");
-static LLFastTimer::DeclareTimer FTM_AGENT_AUTOPILOT("Autopilot");
-static LLFastTimer::DeclareTimer FTM_AGENT_UPDATE("Update");
-
-bool LLAppViewer::mainLoop()
-{
- LLMemType mt1(LLMemType::MTYPE_MAIN);
- mMainloopTimeout = new LLWatchdogTimeout();
-
- //-------------------------------------------
- // Run main loop until time to quit
- //-------------------------------------------
-
- // Create IO Pump to use for HTTP Requests.
- gServicePump = new LLPumpIO(gAPRPoolp);
- LLHTTPClient::setPump(*gServicePump);
- LLCurl::setCAFile(gDirUtilp->getCAFile());
-
- // Note: this is where gLocalSpeakerMgr and gActiveSpeakerMgr used to be instantiated.
-
- LLVoiceChannel::initClass();
- LLVoiceClient::getInstance()->init(gServicePump);
- LLTimer frameTimer,idleTimer;
- LLTimer debugTime;
- LLFrameTimer memCheckTimer;
- LLViewerJoystick* joystick(LLViewerJoystick::getInstance());
- joystick->setNeedsReset(true);
-
- LLEventPump& mainloop(LLEventPumps::instance().obtain("mainloop"));
- // As we do not (yet) send data on the mainloop LLEventPump that varies
- // with each frame, no need to instantiate a new LLSD event object each
- // time. Obviously, if that changes, just instantiate the LLSD at the
- // point of posting.
- LLSD newFrame;
-
- const F32 memory_check_interval = 1.0f ; //second
-
- // Handle messages
- while (!LLApp::isExiting())
- {
- LLFastTimer::nextFrame(); // Should be outside of any timer instances
-
- //clear call stack records
- llclearcallstacks;
-
- //check memory availability information
- {
- if(memory_check_interval < memCheckTimer.getElapsedTimeF32())
- {
- memCheckTimer.reset() ;
-
- //update the availability of memory
- LLMemoryInfo::getAvailableMemoryKB(mAvailPhysicalMemInKB, mAvailVirtualMemInKB) ;
- }
- llcallstacks << "Available physical mem(KB): " << mAvailPhysicalMemInKB << llcallstacksendl ;
- llcallstacks << "Available virtual mem(KB): " << mAvailVirtualMemInKB << llcallstacksendl ;
- }
-
- try
- {
- pingMainloopTimeout("Main:MiscNativeWindowEvents");
-
- if (gViewerWindow)
- {
- LLFastTimer t2(FTM_MESSAGES);
- gViewerWindow->mWindow->processMiscNativeEvents();
- }
-
- pingMainloopTimeout("Main:GatherInput");
-
- if (gViewerWindow)
- {
- LLFastTimer t2(FTM_MESSAGES);
- if (!restoreErrorTrap())
- {
- llwarns << " Someone took over my signal/exception handler (post messagehandling)!" << llendl;
- }
-
- gViewerWindow->mWindow->gatherInput();
- }
-
-#if 1 && !LL_RELEASE_FOR_DOWNLOAD
- // once per second debug info
- if (debugTime.getElapsedTimeF32() > 1.f)
- {
- debugTime.reset();
- }
-
-#endif
- //memory leaking simulation
- LLFloaterMemLeak* mem_leak_instance =
- LLFloaterReg::findTypedInstance<LLFloaterMemLeak>("mem_leaking");
- if(mem_leak_instance)
- {
- mem_leak_instance->idle() ;
- }
-
- // canonical per-frame event
- mainloop.post(newFrame);
-
- if (!LLApp::isExiting())
- {
- pingMainloopTimeout("Main:JoystickKeyboard");
-
- // Scan keyboard for movement keys. Command keys and typing
- // are handled by windows callbacks. Don't do this until we're
- // done initializing. JC
- if (gViewerWindow->mWindow->getVisible()
- && gViewerWindow->getActive()
- && !gViewerWindow->mWindow->getMinimized()
- && LLStartUp::getStartupState() == STATE_STARTED
- && !gViewerWindow->getShowProgress()
- && !gFocusMgr.focusLocked())
- {
- LLMemType mjk(LLMemType::MTYPE_JOY_KEY);
- joystick->scanJoystick();
- gKeyboard->scanKeyboard();
- }
-
- // Update state based on messages, user input, object idle.
- {
- pauseMainloopTimeout(); // *TODO: Remove. Messages shouldn't be stalling for 20+ seconds!
-
- LLFastTimer t3(FTM_IDLE);
- idle();
-
- if (gAres != NULL && gAres->isInitialized())
- {
- LLMemType mt_ip(LLMemType::MTYPE_IDLE_PUMP);
- pingMainloopTimeout("Main:ServicePump");
- LLFastTimer t4(FTM_PUMP);
- {
- LLFastTimer t(FTM_PUMP_ARES);
- gAres->process();
- }
- {
- LLFastTimer t(FTM_PUMP_SERVICE);
- // this pump is necessary to make the login screen show up
- gServicePump->pump();
-
- {
- LLFastTimer t(FTM_SERVICE_CALLBACK);
- gServicePump->callback();
- }
- }
- }
-
- resumeMainloopTimeout();
- }
-
- if (gDoDisconnect && (LLStartUp::getStartupState() == STATE_STARTED))
- {
- pauseMainloopTimeout();
- saveFinalSnapshot();
- disconnectViewer();
- resumeMainloopTimeout();
- }
-
- // Render scene.
- if (!LLApp::isExiting())
- {
- pingMainloopTimeout("Main:Display");
- gGLActive = TRUE;
- display();
- pingMainloopTimeout("Main:Snapshot");
- LLFloaterSnapshot::update(); // take snapshots
- gGLActive = FALSE;
- }
-
- }
-
- pingMainloopTimeout("Main:Sleep");
-
- pauseMainloopTimeout();
-
- // Sleep and run background threads
- {
- LLMemType mt_sleep(LLMemType::MTYPE_SLEEP);
- LLFastTimer t2(FTM_SLEEP);
-
- // yield some time to the os based on command line option
- if(mYieldTime >= 0)
- {
- ms_sleep(mYieldTime);
- }
-
- // yield cooperatively when not running as foreground window
- if ( gNoRender
- || (gViewerWindow && !gViewerWindow->mWindow->getVisible())
- || !gFocusMgr.getAppHasFocus())
- {
- // Sleep if we're not rendering, or the window is minimized.
- S32 milliseconds_to_sleep = llclamp(gSavedSettings.getS32("BackgroundYieldTime"), 0, 1000);
- // don't sleep when BackgroundYieldTime set to 0, since this will still yield to other threads
- // of equal priority on Windows
- if (milliseconds_to_sleep > 0)
- {
- ms_sleep(milliseconds_to_sleep);
- // also pause worker threads during this wait period
- LLAppViewer::getTextureCache()->pause();
- LLAppViewer::getImageDecodeThread()->pause();
- }
- }
-
- if (mRandomizeFramerate)
- {
- ms_sleep(rand() % 200);
- }
-
- if (mPeriodicSlowFrame
- && (gFrameCount % 10 == 0))
- {
- llinfos << "Periodic slow frame - sleeping 500 ms" << llendl;
- ms_sleep(500);
- }
-
- static const F64 FRAME_SLOW_THRESHOLD = 0.5; //2 frames per seconds
- const F64 max_idle_time = llmin(.005*10.0*gFrameTimeSeconds, 0.005); // 5 ms a second
- idleTimer.reset();
- bool is_slow = (frameTimer.getElapsedTimeF64() > FRAME_SLOW_THRESHOLD) ;
- S32 total_work_pending = 0;
- S32 total_io_pending = 0;
- while(!is_slow)//do not unpause threads if the frame rates are very low.
- {
- S32 work_pending = 0;
- S32 io_pending = 0;
- {
- LLFastTimer ftm(FTM_TEXTURE_CACHE);
- work_pending += LLAppViewer::getTextureCache()->update(1); // unpauses the texture cache thread
- }
- {
- LLFastTimer ftm(FTM_DECODE);
- work_pending += LLAppViewer::getImageDecodeThread()->update(1); // unpauses the image thread
- }
- {
- LLFastTimer ftm(FTM_DECODE);
- work_pending += LLAppViewer::getTextureFetch()->update(1); // unpauses the texture fetch thread
- }
-
- {
- LLFastTimer ftm(FTM_VFS);
- io_pending += LLVFSThread::updateClass(1);
- }
- {
- LLFastTimer ftm(FTM_LFS);
- io_pending += LLLFSThread::updateClass(1);
- }
-
- if (io_pending > 1000)
- {
- ms_sleep(llmin(io_pending/100,100)); // give the vfs some time to catch up
- }
-
- total_work_pending += work_pending ;
- total_io_pending += io_pending ;
-
- if (!work_pending || idleTimer.getElapsedTimeF64() >= max_idle_time)
- {
- break;
- }
- }
-
- if(!total_work_pending) //pause texture fetching threads if nothing to process.
- {
- LLAppViewer::getTextureCache()->pause();
- LLAppViewer::getImageDecodeThread()->pause();
- LLAppViewer::getTextureFetch()->pause();
- }
- if(!total_io_pending) //pause file threads if nothing to process.
- {
- LLVFSThread::sLocal->pause();
- LLLFSThread::sLocal->pause();
- }
-
- if ((LLStartUp::getStartupState() >= STATE_CLEANUP) &&
- (frameTimer.getElapsedTimeF64() > FRAME_STALL_THRESHOLD))
- {
- gFrameStalls++;
- }
- frameTimer.reset();
-
- resumeMainloopTimeout();
-
- pingMainloopTimeout("Main:End");
- }
- }
- catch(std::bad_alloc)
- {
- {
- llinfos << "Availabe physical memory(KB) at the beginning of the frame: " << mAvailPhysicalMemInKB << llendl ;
- llinfos << "Availabe virtual memory(KB) at the beginning of the frame: " << mAvailVirtualMemInKB << llendl ;
-
- LLMemoryInfo::getAvailableMemoryKB(mAvailPhysicalMemInKB, mAvailVirtualMemInKB) ;
-
- llinfos << "Current availabe physical memory(KB): " << mAvailPhysicalMemInKB << llendl ;
- llinfos << "Current availabe virtual memory(KB): " << mAvailVirtualMemInKB << llendl ;
- }
-
- //stop memory leaking simulation
- LLFloaterMemLeak* mem_leak_instance =
- LLFloaterReg::findTypedInstance<LLFloaterMemLeak>("mem_leaking");
- if(mem_leak_instance)
- {
- mem_leak_instance->stop() ;
- llwarns << "Bad memory allocation in LLAppViewer::mainLoop()!" << llendl ;
- }
- else
- {
- //output possible call stacks to log file.
- LLError::LLCallStacks::print() ;
-
- llerrs << "Bad memory allocation in LLAppViewer::mainLoop()!" << llendl ;
- }
- }
- }
-
- // Save snapshot for next time, if we made it through initialization
- if (STATE_STARTED == LLStartUp::getStartupState())
- {
- try
- {
- saveFinalSnapshot();
- }
- catch(std::bad_alloc)
- {
- llwarns << "Bad memory allocation when saveFinalSnapshot() is called!" << llendl ;
-
- //stop memory leaking simulation
- LLFloaterMemLeak* mem_leak_instance =
- LLFloaterReg::findTypedInstance<LLFloaterMemLeak>("mem_leaking");
- if(mem_leak_instance)
- {
- mem_leak_instance->stop() ;
- }
- }
- }
-
- delete gServicePump;
-
- destroyMainloopTimeout();
-
- llinfos << "Exiting main_loop" << llendflush;
-
- return true;
-}
-
-void LLAppViewer::flushVFSIO()
-{
- while (1)
- {
- S32 pending = LLVFSThread::updateClass(0);
- pending += LLLFSThread::updateClass(0);
- if (!pending)
- {
- break;
- }
- llinfos << "Waiting for pending IO to finish: " << pending << llendflush;
- ms_sleep(100);
- }
-}
-
-bool LLAppViewer::cleanup()
-{
- // workaround for DEV-35406 crash on shutdown
- LLEventPumps::instance().reset();
-
- // remove any old breakpad minidump files from the log directory
- if (! isError())
- {
- std::string logdir = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "");
- logdir += gDirUtilp->getDirDelimiter();
- gDirUtilp->deleteFilesInDir(logdir, "*-*-*-*-*.dmp");
- }
-
- // *TODO - generalize this and move DSO wrangling to a helper class -brad
- std::set<struct apr_dso_handle_t *>::const_iterator i;
- for(i = mPlugins.begin(); i != mPlugins.end(); ++i)
- {
- int (*ll_plugin_stop_func)(void) = NULL;
- apr_status_t rv = apr_dso_sym((apr_dso_handle_sym_t*)&ll_plugin_stop_func, *i, "ll_plugin_stop");
- ll_plugin_stop_func();
-
- rv = apr_dso_unload(*i);
- }
- mPlugins.clear();
-
- //flag all elements as needing to be destroyed immediately
- // to ensure shutdown order
- LLMortician::setZealous(TRUE);
-
- LLVoiceClient::getInstance()->terminate();
-
- disconnectViewer();
-
- llinfos << "Viewer disconnected" << llendflush;
-
- display_cleanup();
-
- release_start_screen(); // just in case
-
- LLError::logToFixedBuffer(NULL);
-
- llinfos << "Cleaning Up" << llendflush;
-
- // Must clean up texture references before viewer window is destroyed.
- if(LLHUDManager::instanceExists())
- {
- LLHUDManager::getInstance()->updateEffects();
- LLHUDObject::updateAll();
- LLHUDManager::getInstance()->cleanupEffects();
- LLHUDObject::cleanupHUDObjects();
- llinfos << "HUD Objects cleaned up" << llendflush;
- }
-
- LLKeyframeDataCache::clear();
-
- // End TransferManager before deleting systems it depends on (Audio, VFS, AssetStorage)
-#if 0 // this seems to get us stuck in an infinite loop...
- gTransferManager.cleanup();
-#endif
-
- // Note: this is where gWorldMap used to be deleted.
-
- // Note: this is where gHUDManager used to be deleted.
- if(LLHUDManager::instanceExists())
- {
- LLHUDManager::getInstance()->shutdownClass();
- }
-
- delete gAssetStorage;
- gAssetStorage = NULL;
-
- LLPolyMesh::freeAllMeshes();
-
- LLStartUp::cleanupNameCache();
-
- // Note: this is where gLocalSpeakerMgr and gActiveSpeakerMgr used to be deleted.
-
- LLWorldMap::getInstance()->reset(); // release any images
-
- llinfos << "Global stuff deleted" << llendflush;
-
- if (gAudiop)
- {
- // shut down the streaming audio sub-subsystem first, in case it relies on not outliving the general audio subsystem.
-
- LLStreamingAudioInterface *sai = gAudiop->getStreamingAudioImpl();
- delete sai;
- gAudiop->setStreamingAudioImpl(NULL);
-
- // shut down the audio subsystem
-
- bool want_longname = false;
- if (gAudiop->getDriverName(want_longname) == "FMOD")
- {
- // This hack exists because fmod likes to occasionally
- // crash or hang forever when shutting down, for no
- // apparent reason.
- llwarns << "Hack, skipping FMOD audio engine cleanup" << llendflush;
- }
- else
- {
- gAudiop->shutdown();
- }
-
- delete gAudiop;
- gAudiop = NULL;
- }
-
- // Note: this is where LLFeatureManager::getInstance()-> used to be deleted.
-
- // Patch up settings for next time
- // Must do this before we delete the viewer window,
- // such that we can suck rectangle information out of
- // it.
- cleanupSavedSettings();
- llinfos << "Settings patched up" << llendflush;
-
- // delete some of the files left around in the cache.
- removeCacheFiles("*.wav");
- removeCacheFiles("*.tmp");
- removeCacheFiles("*.lso");
- removeCacheFiles("*.out");
- removeCacheFiles("*.dsf");
- removeCacheFiles("*.bodypart");
- removeCacheFiles("*.clothing");
-
- llinfos << "Cache files removed" << llendflush;
-
- // Wait for any pending VFS IO
- flushVFSIO();
- llinfos << "Shutting down Views" << llendflush;
-
- // Destroy the UI
- if( gViewerWindow)
- gViewerWindow->shutdownViews();
-
- llinfos << "Cleaning up Inventory" << llendflush;
-
- // Cleanup Inventory after the UI since it will delete any remaining observers
- // (Deleted observers should have already removed themselves)
- gInventory.cleanupInventory();
-
- llinfos << "Cleaning up Selections" << llendflush;
-
- // Clean up selection managers after UI is destroyed, as UI may be observing them.
- // Clean up before GL is shut down because we might be holding on to objects with texture references
- LLSelectMgr::cleanupGlobals();
-
- llinfos << "Shutting down OpenGL" << llendflush;
-
- // Shut down OpenGL
- if( gViewerWindow)
- {
- gViewerWindow->shutdownGL();
-
- // Destroy window, and make sure we're not fullscreen
- // This may generate window reshape and activation events.
- // Therefore must do this before destroying the message system.
- delete gViewerWindow;
- gViewerWindow = NULL;
- llinfos << "ViewerWindow deleted" << llendflush;
- }
-
- llinfos << "Cleaning up Keyboard & Joystick" << llendflush;
-
- // viewer UI relies on keyboard so keep it aound until viewer UI isa gone
- delete gKeyboard;
- gKeyboard = NULL;
-
- // Turn off Space Navigator and similar devices
- LLViewerJoystick::getInstance()->terminate();
-
- llinfos << "Cleaning up Objects" << llendflush;
-
- LLViewerObject::cleanupVOClasses();
-
- LLWaterParamManager::cleanupClass();
- LLWLParamManager::cleanupClass();
- LLPostProcess::cleanupClass();
-
- LLTracker::cleanupInstance();
-
- // *FIX: This is handled in LLAppViewerWin32::cleanup().
- // I'm keeping the comment to remember its order in cleanup,
- // in case of unforseen dependency.
- //#if LL_WINDOWS
- // gDXHardware.cleanup();
- //#endif // LL_WINDOWS
-
- LLVolumeMgr* volume_manager = LLPrimitive::getVolumeManager();
- if (!volume_manager->cleanup())
- {
- llwarns << "Remaining references in the volume manager!" << llendflush;
- }
- LLPrimitive::cleanupVolumeManager();
-
- llinfos << "Additional Cleanup..." << llendflush;
-
- LLViewerParcelMgr::cleanupGlobals();
-
- // *Note: this is where gViewerStats used to be deleted.
-
- //end_messaging_system();
-
- LLFollowCamMgr::cleanupClass();
- //LLVolumeMgr::cleanupClass();
- LLPrimitive::cleanupVolumeManager();
- LLWorldMapView::cleanupClass();
- LLFolderViewItem::cleanupClass();
- LLUI::cleanupClass();
-
- //
- // Shut down the VFS's AFTER the decode manager cleans up (since it cleans up vfiles).
- // Also after viewerwindow is deleted, since it may have image pointers (which have vfiles)
- // Also after shutting down the messaging system since it has VFS dependencies
-
- //
- llinfos << "Cleaning up VFS" << llendflush;
- LLVFile::cleanupClass();
-
- llinfos << "Saving Data" << llendflush;
-
- // Store the time of our current logoff
- gSavedPerAccountSettings.setU32("LastLogoff", time_corrected());
-
- // Must do this after all panels have been deleted because panels that have persistent rects
- // save their rects on delete.
- gSavedSettings.saveToFile(gSavedSettings.getString("ClientSettingsFile"), TRUE);
-
- LLUIColorTable::instance().saveUserSettings();
-
- // PerAccountSettingsFile should be empty if no user has been logged on.
- // *FIX:Mani This should get really saved in a "logoff" mode.
- if (gSavedSettings.getString("PerAccountSettingsFile").empty())
- {
- llinfos << "Not saving per-account settings; don't know the account name yet." << llendl;
- }
- else
- {
- gSavedPerAccountSettings.saveToFile(gSavedSettings.getString("PerAccountSettingsFile"), TRUE);
- llinfos << "Saved settings" << llendflush;
- }
-
- std::string crash_settings_filename = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, CRASH_SETTINGS_FILE);
- // save all settings, even if equals defaults
- gCrashSettings.saveToFile(crash_settings_filename, FALSE);
-
- std::string warnings_settings_filename = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, getSettingsFilename("Default", "Warnings"));
- gWarningSettings.saveToFile(warnings_settings_filename, TRUE);
-
- // Save URL history file
- LLURLHistory::saveFile("url_history.xml");
-
- // save mute list. gMuteList used to also be deleted here too.
- LLMuteList::getInstance()->cache(gAgent.getID());
-
- if (mPurgeOnExit)
- {
- llinfos << "Purging all cache files on exit" << llendflush;
- std::string mask = gDirUtilp->getDirDelimiter() + "*.*";
- gDirUtilp->deleteFilesInDir(gDirUtilp->getExpandedFilename(LL_PATH_CACHE,""),mask);
- }
-
- removeMarkerFile(); // Any crashes from here on we'll just have to ignore
-
- writeDebugInfo();
-
- LLLocationHistory::getInstance()->save();
-
- LLAvatarIconIDCache::getInstance()->save();
-
- LLViewerMedia::saveCookieFile();
-
- // Stop the plugin read thread if it's running.
- LLPluginProcessParent::setUseReadThread(false);
-
- llinfos << "Shutting down Threads" << llendflush;
-
- // Let threads finish
- LLTimer idleTimer;
- idleTimer.reset();
- const F64 max_idle_time = 5.f; // 5 seconds
- while(1)
- {
- S32 pending = 0;
- pending += LLAppViewer::getTextureCache()->update(1); // unpauses the worker thread
- pending += LLAppViewer::getImageDecodeThread()->update(1); // unpauses the image thread
- pending += LLAppViewer::getTextureFetch()->update(1); // unpauses the texture fetch thread
- pending += LLVFSThread::updateClass(0);
- pending += LLLFSThread::updateClass(0);
- F64 idle_time = idleTimer.getElapsedTimeF64();
- if(!pending)
- {
- break ; //done
- }
- else if(idle_time >= max_idle_time)
- {
- llwarns << "Quitting with pending background tasks." << llendl;
- break;
- }
- }
-
- // Delete workers first
- // shotdown all worker threads before deleting them in case of co-dependencies
- sTextureFetch->shutdown();
- sTextureCache->shutdown();
- sImageDecodeThread->shutdown();
-
- sTextureFetch->shutDownTextureCacheThread() ;
- sTextureFetch->shutDownImageDecodeThread() ;
-
- delete sTextureCache;
- sTextureCache = NULL;
- delete sTextureFetch;
- sTextureFetch = NULL;
- delete sImageDecodeThread;
- sImageDecodeThread = NULL;
- delete mFastTimerLogThread;
- mFastTimerLogThread = NULL;
-
- if (LLFastTimerView::sAnalyzePerformance)
- {
- llinfos << "Analyzing performance" << llendl;
-
- std::string baseline_name = LLFastTimer::sLogName + "_baseline.slp";
- std::string current_name = LLFastTimer::sLogName + ".slp";
- std::string report_name = LLFastTimer::sLogName + "_report.csv";
-
- LLFastTimerView::doAnalysis(
- gDirUtilp->getExpandedFilename(LL_PATH_LOGS, baseline_name),
- gDirUtilp->getExpandedFilename(LL_PATH_LOGS, current_name),
- gDirUtilp->getExpandedFilename(LL_PATH_LOGS, report_name));
- }
- LLMetricPerformanceTesterBasic::cleanClass() ;
-
-#if LL_RECORD_VIEWER_STATS
- LLViewerStatsRecorder::cleanupClass();
-#endif
-
- llinfos << "Cleaning up Media and Textures" << llendflush;
-
- //Note:
- //LLViewerMedia::cleanupClass() has to be put before gTextureList.shutdown()
- //because some new image might be generated during cleaning up media. --bao
- LLViewerMedia::cleanupClass();
- LLViewerParcelMedia::cleanupClass();
- gTextureList.shutdown(); // shutdown again in case a callback added something
- LLUIImageList::getInstance()->cleanUp();
-
- // This should eventually be done in LLAppViewer
- LLImage::cleanupClass();
- LLVFSThread::cleanupClass();
- LLLFSThread::cleanupClass();
-
-#ifndef LL_RELEASE_FOR_DOWNLOAD
- llinfos << "Auditing VFS" << llendl;
- if(gVFS)
- {
- gVFS->audit();
- }
-#endif
-
- llinfos << "Misc Cleanup" << llendflush;
-
- // For safety, the LLVFS has to be deleted *after* LLVFSThread. This should be cleaned up.
- // (LLVFS doesn't know about LLVFSThread so can't kill pending requests) -Steve
- delete gStaticVFS;
- gStaticVFS = NULL;
- delete gVFS;
- gVFS = NULL;
-
- gSavedSettings.cleanup();
- LLUIColorTable::instance().clear();
- gCrashSettings.cleanup();
-
- LLWatchdog::getInstance()->cleanup();
-
- LLViewerAssetStatsFF::cleanup();
-
- llinfos << "Shutting down message system" << llendflush;
- end_messaging_system();
-
- // *NOTE:Mani - The following call is not thread safe.
- LLCurl::cleanupClass();
-
- // If we're exiting to launch an URL, do that here so the screen
- // is at the right resolution before we launch IE.
- if (!gLaunchFileOnQuit.empty())
- {
- llinfos << "Launch file on quit." << llendflush;
-#if LL_WINDOWS
- // Indicate an application is starting.
- SetCursor(LoadCursor(NULL, IDC_WAIT));
-#endif
-
- // HACK: Attempt to wait until the screen res. switch is complete.
- ms_sleep(1000);
-
- LLWeb::loadURLExternal( gLaunchFileOnQuit, false );
- llinfos << "File launched." << llendflush;
- }
-
- LLMainLoopRepeater::instance().stop();
-
- ll_close_fail_log();
-
- MEM_TRACK_RELEASE
-
- llinfos << "Goodbye!" << llendflush;
-
- // return 0;
- return true;
-}
-
-// A callback for llerrs to call during the watchdog error.
-void watchdog_llerrs_callback(const std::string &error_string)
-{
- gLLErrorActivated = true;
-
-#ifdef LL_WINDOWS
- RaiseException(0,0,0,0);
-#else
- raise(SIGQUIT);
-#endif
-}
-
-// A callback for the watchdog to call.
-void watchdog_killer_callback()
-{
- LLError::setFatalFunction(watchdog_llerrs_callback);
- llerrs << "Watchdog killer event" << llendl;
-}
-
-bool LLAppViewer::initThreads()
-{
-#if MEM_TRACK_MEM
- static const bool enable_threads = false;
-#else
- static const bool enable_threads = true;
-#endif
-
- LLVFSThread::initClass(enable_threads && false);
- LLLFSThread::initClass(enable_threads && false);
-
- // Image decoding
- LLAppViewer::sImageDecodeThread = new LLImageDecodeThread(enable_threads && true);
- LLAppViewer::sTextureCache = new LLTextureCache(enable_threads && true);
- LLAppViewer::sTextureFetch = new LLTextureFetch(LLAppViewer::getTextureCache(),
- sImageDecodeThread,
- enable_threads && true,
- app_metrics_qa_mode);
- LLImage::initClass();
-
- if (LLFastTimer::sLog || LLFastTimer::sMetricLog)
- {
- LLFastTimer::sLogLock = new LLMutex(NULL);
- mFastTimerLogThread = new LLFastTimerLogThread(LLFastTimer::sLogName);
- mFastTimerLogThread->start();
- }
-
- // *FIX: no error handling here!
- return true;
-}
-
-void errorCallback(const std::string &error_string)
-{
-#ifndef LL_RELEASE_FOR_DOWNLOAD
- OSMessageBox(error_string, LLTrans::getString("MBFatalError"), OSMB_OK);
-#endif
-
- //Set the ErrorActivated global so we know to create a marker file
- gLLErrorActivated = true;
-
- LLError::crashAndLoop(error_string);
-}
-
-bool LLAppViewer::initLogging()
-{
- //
- // Set up logging defaults for the viewer
- //
- LLError::initForApplication(
- gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
- LLError::setFatalFunction(errorCallback);
-
- // Remove the last ".old" log file.
- std::string old_log_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,
- "SecondLife.old");
- LLFile::remove(old_log_file);
-
- // Rename current log file to ".old"
- std::string log_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,
- "SecondLife.log");
- LLFile::rename(log_file, old_log_file);
-
- // Set the log file to SecondLife.log
-
- LLError::logToFile(log_file);
-
- // *FIX:Mani no error handling here!
- return true;
-}
-
-bool LLAppViewer::loadSettingsFromDirectory(const std::string& location_key,
- bool set_defaults)
-{
- if (!mSettingsLocationList)
- {
- llerrs << "Invalid settings location list" << llendl;
- }
-
- LLControlGroup* global_settings = LLControlGroup::getInstance(sGlobalSettingsName);
- for(LLInitParam::ParamIterator<SettingsGroup>::const_iterator it = mSettingsLocationList->groups.begin(), end_it = mSettingsLocationList->groups.end();
- it != end_it;
- ++it)
- {
- // skip settings groups that aren't the one we requested
- if (it->name() != location_key) continue;
-
- ELLPath path_index = (ELLPath)it->path_index();
- if(path_index <= LL_PATH_NONE || path_index >= LL_PATH_LAST)
- {
- llerrs << "Out of range path index in app_settings/settings_files.xml" << llendl;
- return false;
- }
-
- LLInitParam::ParamIterator<SettingsFile>::const_iterator file_it, end_file_it;
- for (file_it = it->files.begin(), end_file_it = it->files.end();
- file_it != end_file_it;
- ++file_it)
- {
- llinfos << "Attempting to load settings for the group " << file_it->name()
- << " - from location " << location_key << llendl;
-
- LLControlGroup* settings_group = LLControlGroup::getInstance(file_it->name);
- if(!settings_group)
- {
- llwarns << "No matching settings group for name " << file_it->name() << llendl;
- continue;
- }
-
- std::string full_settings_path;
-
- if (file_it->file_name_setting.isProvided()
- && global_settings->controlExists(file_it->file_name_setting))
- {
- // try to find filename stored in file_name_setting control
- full_settings_path = global_settings->getString(file_it->file_name_setting);
- if (!gDirUtilp->fileExists(full_settings_path))
- {
- // search in default path
- full_settings_path = gDirUtilp->getExpandedFilename((ELLPath)path_index, full_settings_path);
- }
- }
- else
- {
- // by default, use specified file name
- full_settings_path = gDirUtilp->getExpandedFilename((ELLPath)path_index, file_it->file_name());
- }
-
- if(settings_group->loadFromFile(full_settings_path, set_defaults, file_it->persistent))
- { // success!
- llinfos << "Loaded settings file " << full_settings_path << llendl;
- }
- else
- { // failed to load
- if(file_it->required)
- {
- llerrs << "Error: Cannot load required settings file from: " << full_settings_path << llendl;
- return false;
- }
- else
- {
- // only complain if we actually have a filename at this point
- if (!full_settings_path.empty())
- {
- llinfos << "Cannot load " << full_settings_path << " - No settings found." << llendl;
- }
- }
- }
- }
- }
-
- return true;
-}
-
-std::string LLAppViewer::getSettingsFilename(const std::string& location_key,
- const std::string& file)
-{
- for(LLInitParam::ParamIterator<SettingsGroup>::const_iterator it = mSettingsLocationList->groups.begin(), end_it = mSettingsLocationList->groups.end();
- it != end_it;
- ++it)
- {
- if (it->name() == location_key)
- {
- LLInitParam::ParamIterator<SettingsFile>::const_iterator file_it, end_file_it;
- for (file_it = it->files.begin(), end_file_it = it->files.end();
- file_it != end_file_it;
- ++file_it)
- {
- if (file_it->name() == file)
- {
- return file_it->file_name;
- }
- }
- }
- }
-
- return std::string();
-}
-
-void LLAppViewer::loadColorSettings()
-{
- LLUIColorTable::instance().loadFromSettings();
-}
-
-bool LLAppViewer::initConfiguration()
-{
- //Load settings files list
- std::string settings_file_list = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "settings_files.xml");
- //LLControlGroup settings_control("SettingsFiles");
- //llinfos << "Loading settings file list " << settings_file_list << llendl;
- //if (0 == settings_control.loadFromFile(settings_file_list))
- //{
- // llerrs << "Cannot load default configuration file " << settings_file_list << llendl;
- //}
-
- LLXMLNodePtr root;
- BOOL success = LLXMLNode::parseFile(settings_file_list, root, NULL);
- if (!success)
- {
- llerrs << "Cannot load default configuration file " << settings_file_list << llendl;
- }
-
- mSettingsLocationList = new SettingsFiles();
-
- LLXUIParser parser;
- parser.readXUI(root, *mSettingsLocationList, settings_file_list);
-
- if (!mSettingsLocationList->validateBlock())
- {
- llerrs << "Invalid settings file list " << settings_file_list << llendl;
- }
-
- // The settings and command line parsing have a fragile
- // order-of-operation:
- // - load defaults from app_settings
- // - set procedural settings values
- // - read command line settings
- // - selectively apply settings needed to load user settings.
- // - load overrides from user_settings
- // - apply command line settings (to override the overrides)
- // - load per account settings (happens in llstartup
-
- // - load defaults
- bool set_defaults = true;
- if(!loadSettingsFromDirectory("Default", set_defaults))
- {
- std::ostringstream msg;
- msg << "Unable to load default settings file. The installation may be corrupted.";
- OSMessageBox(msg.str(),LLStringUtil::null,OSMB_OK);
- return false;
- }
-
- LLUI::setupPaths(); // setup paths for LLTrans based on settings files only
- LLTransUtil::parseStrings("strings.xml", default_trans_args);
- LLTransUtil::parseLanguageStrings("language_settings.xml");
- // - set procedural settings
- // Note: can't use LL_PATH_PER_SL_ACCOUNT for any of these since we haven't logged in yet
- gSavedSettings.setString("ClientSettingsFile",
- gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, getSettingsFilename("Default", "Global")));
-
-#ifndef LL_RELEASE_FOR_DOWNLOAD
- // provide developer build only overrides for these control variables that are not
- // persisted to settings.xml
- LLControlVariable* c = gSavedSettings.getControl("ShowConsoleWindow");
- if (c)
- {
- c->setValue(true, false);
- }
- c = gSavedSettings.getControl("AllowMultipleViewers");
- if (c)
- {
- c->setValue(true, false);
- }
-#endif
-
-#ifndef LL_RELEASE_FOR_DOWNLOAD
- gSavedSettings.setBOOL("QAMode", TRUE );
- gSavedSettings.setS32("WatchdogEnabled", 0);
-#endif
-
- gCrashSettings.getControl(CRASH_BEHAVIOR_SETTING)->getSignal()->connect(boost::bind(&handleCrashSubmitBehaviorChanged, _2));
-
- // These are warnings that appear on the first experience of that condition.
- // They are already set in the settings_default.xml file, but still need to be added to LLFirstUse
- // for disable/reset ability
-// LLFirstUse::addConfigVariable("FirstBalanceIncrease");
-// LLFirstUse::addConfigVariable("FirstBalanceDecrease");
-// LLFirstUse::addConfigVariable("FirstSit");
-// LLFirstUse::addConfigVariable("FirstMap");
-// LLFirstUse::addConfigVariable("FirstGoTo");
-// LLFirstUse::addConfigVariable("FirstBuild");
-// LLFirstUse::addConfigVariable("FirstLeftClickNoHit");
-// LLFirstUse::addConfigVariable("FirstTeleport");
-// LLFirstUse::addConfigVariable("FirstOverrideKeys");
-// LLFirstUse::addConfigVariable("FirstAttach");
-// LLFirstUse::addConfigVariable("FirstAppearance");
-// LLFirstUse::addConfigVariable("FirstInventory");
-// LLFirstUse::addConfigVariable("FirstSandbox");
-// LLFirstUse::addConfigVariable("FirstFlexible");
-// LLFirstUse::addConfigVariable("FirstDebugMenus");
-// LLFirstUse::addConfigVariable("FirstSculptedPrim");
-// LLFirstUse::addConfigVariable("FirstVoice");
-// LLFirstUse::addConfigVariable("FirstMedia");
-
- // - read command line settings.
- LLControlGroupCLP clp;
- std::string cmd_line_config = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,
- "cmd_line.xml");
-
- clp.configure(cmd_line_config, &gSavedSettings);
-
- if(!initParseCommandLine(clp))
- {
- llwarns << "Error parsing command line options. Command Line options ignored." << llendl;
-
- llinfos << "Command line usage:\n" << clp << llendl;
-
- std::ostringstream msg;
- msg << LLTrans::getString("MBCmdLineError") << clp.getErrorMessage();
- OSMessageBox(msg.str(),LLStringUtil::null,OSMB_OK);
- return false;
- }
-
- // - selectively apply settings
-
- // If the user has specified a alternate settings file name.
- // Load it now before loading the user_settings/settings.xml
- if(clp.hasOption("settings"))
- {
- std::string user_settings_filename =
- gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS,
- clp.getOption("settings")[0]);
- gSavedSettings.setString("ClientSettingsFile", user_settings_filename);
- llinfos << "Using command line specified settings filename: "
- << user_settings_filename << llendl;
- }
-
- // - load overrides from user_settings
- loadSettingsFromDirectory("User");
-
- if (gSavedSettings.getBOOL("FirstRunThisInstall"))
- {
- gSavedSettings.setString("SessionSettingsFile", "settings_minimal.xml");
- }
-
- if (clp.hasOption("sessionsettings"))
- {
- std::string session_settings_filename = clp.getOption("sessionsettings")[0];
- gSavedSettings.setString("SessionSettingsFile", session_settings_filename);
- llinfos << "Using session settings filename: "
- << session_settings_filename << llendl;
- }
- loadSettingsFromDirectory("Session");
-
- if (clp.hasOption("usersessionsettings"))
- {
- std::string user_session_settings_filename = clp.getOption("usersessionsettings")[0];
- gSavedSettings.setString("UserSessionSettingsFile", user_session_settings_filename);
- llinfos << "Using user session settings filename: "
- << user_session_settings_filename << llendl;
-
- }
- loadSettingsFromDirectory("UserSession");
-
- // - apply command line settings
- clp.notify();
-
- // Register the core crash option as soon as we can
- // if we want gdb post-mortem on cores we need to be up and running
- // ASAP or we might miss init issue etc.
- if(clp.hasOption("disablecrashlogger"))
- {
- llwarns << "Crashes will be handled by system, stack trace logs and crash logger are both disabled" << llendl;
- LLAppViewer::instance()->disableCrashlogger();
- }
-
- // Handle initialization from settings.
- // Start up the debugging console before handling other options.
- if (gSavedSettings.getBOOL("ShowConsoleWindow"))
- {
- initConsole();
- }
-
- if(clp.hasOption("help"))
- {
- std::ostringstream msg;
- msg << LLTrans::getString("MBCmdLineUsg") << "\n" << clp;
- llinfos << msg.str() << llendl;
-
- OSMessageBox(
- msg.str().c_str(),
- LLStringUtil::null,
- OSMB_OK);
-
- return false;
- }
-
- if(clp.hasOption("set"))
- {
- const LLCommandLineParser::token_vector_t& set_values = clp.getOption("set");
- if(0x1 & set_values.size())
- {
- llwarns << "Invalid '--set' parameter count." << llendl;
- }
- else
- {
- LLCommandLineParser::token_vector_t::const_iterator itr = set_values.begin();
- for(; itr != set_values.end(); ++itr)
- {
- const std::string& name = *itr;
- const std::string& value = *(++itr);
- LLControlVariable* c = LLControlGroup::getInstance(sGlobalSettingsName)->getControl(name);
- if(c)
- {
- c->setValue(value, false);
- }
- else
- {
- llwarns << "'--set' specified with unknown setting: '"
- << name << "'." << llendl;
- }
- }
- }
- }
-
- if(clp.hasOption("channel"))
- {
- LLVersionInfo::resetChannel(clp.getOption("channel")[0]);
- }
-
-
- // If we have specified crash on startup, set the global so we'll trigger the crash at the right time
- if(clp.hasOption("crashonstartup"))
- {
- gCrashOnStartup = TRUE;
- }
-
- if (clp.hasOption("logperformance"))
- {
- LLFastTimer::sLog = TRUE;
- LLFastTimer::sLogName = std::string("performance");
- }
-
- if (clp.hasOption("logmetrics"))
- {
- LLFastTimer::sMetricLog = TRUE ;
- // '--logmetrics' can be specified with a named test metric argument so the data gathering is done only on that test
- // In the absence of argument, every metric is gathered (makes for a rather slow run and hard to decipher report...)
- std::string test_name = clp.getOption("logmetrics")[0];
- llinfos << "'--logmetrics' argument : " << test_name << llendl;
- if (test_name == "")
- {
- llwarns << "No '--logmetrics' argument given, will output all metrics to " << DEFAULT_METRIC_NAME << llendl;
- LLFastTimer::sLogName = DEFAULT_METRIC_NAME;
- }
- else
- {
- LLFastTimer::sLogName = test_name;
- }
- }
-
- if (clp.hasOption("graphicslevel"))
- {
- const LLCommandLineParser::token_vector_t& value = clp.getOption("graphicslevel");
- if(value.size() != 1)
- {
- llwarns << "Usage: -graphicslevel <0-3>" << llendl;
- }
- else
- {
- std::string detail = value.front();
- mForceGraphicsDetail = TRUE;
-
- switch (detail.c_str()[0])
- {
- case '0':
- gSavedSettings.setU32("RenderQualityPerformance", 0);
- break;
- case '1':
- gSavedSettings.setU32("RenderQualityPerformance", 1);
- break;
- case '2':
- gSavedSettings.setU32("RenderQualityPerformance", 2);
- break;
- case '3':
- gSavedSettings.setU32("RenderQualityPerformance", 3);
- break;
- default:
- mForceGraphicsDetail = FALSE;
- llwarns << "Usage: -graphicslevel <0-3>" << llendl;
- break;
- }
- }
- }
-
- if (clp.hasOption("analyzeperformance"))
- {
- LLFastTimerView::sAnalyzePerformance = TRUE;
- }
-
- if (clp.hasOption("replaysession"))
- {
- LLAgentPilot::sReplaySession = TRUE;
- }
-
- if (clp.hasOption("nonotifications"))
- {
- gSavedSettings.getControl("IgnoreAllNotifications")->setValue(true, false);
- }
-
- if (clp.hasOption("debugsession"))
- {
- gDebugSession = TRUE;
- gDebugGL = TRUE;
-
- ll_init_fail_log(gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "test_failures.log"));
- }
-
- // Handle slurl use. NOTE: Don't let SL-55321 reappear.
-
- // *FIX: This init code should be made more robust to prevent
- // the issue SL-55321 from returning. One thought is to allow
- // only select options to be set from command line when a slurl
- // is specified. More work on the settings system is needed to
- // achieve this. For now...
-
- // *NOTE:Mani The command line parser parses tokens and is
- // setup to bail after parsing the '--url' option or the
- // first option specified without a '--option' flag (or
- // any other option that uses the 'last_option' setting -
- // see LLControlGroupCLP::configure())
-
- // What can happen is that someone can use IE (or potentially
- // other browsers) and do the rough equivalent of command
- // injection and steal passwords. Phoenix. SL-55321
- if(clp.hasOption("url"))
- {
- LLStartUp::setStartSLURL(LLSLURL(clp.getOption("url")[0]));
- if(LLStartUp::getStartSLURL().getType() == LLSLURL::LOCATION)
- {
- LLGridManager::getInstance()->setGridChoice(LLStartUp::getStartSLURL().getGrid());
-
- }
- }
- else if(clp.hasOption("slurl"))
- {
- LLSLURL start_slurl(clp.getOption("slurl")[0]);
- LLStartUp::setStartSLURL(start_slurl);
- }
-
- const LLControlVariable* skinfolder = gSavedSettings.getControl("SkinCurrent");
- if(skinfolder && LLStringUtil::null != skinfolder->getValue().asString())
- {
- // hack to force the skin to default.
- gDirUtilp->setSkinFolder(skinfolder->getValue().asString());
- //gDirUtilp->setSkinFolder("default");
- }
-
- mYieldTime = gSavedSettings.getS32("YieldTime");
-
- // Read skin/branding settings if specified.
- //if (! gDirUtilp->getSkinDir().empty() )
- //{
- // std::string skin_def_file = gDirUtilp->findSkinnedFilename("skin.xml");
- // LLXmlTree skin_def_tree;
-
- // if (!skin_def_tree.parseFile(skin_def_file))
- // {
- // llerrs << "Failed to parse skin definition." << llendl;
- // }
-
- //}
-
-#if LL_DARWIN
- // Initialize apple menubar and various callbacks
- init_apple_menu(LLTrans::getString("APP_NAME").c_str());
-
-#if __ppc__
- // If the CPU doesn't have Altivec (i.e. it's not at least a G4), don't go any further.
- // Only test PowerPC - all Intel Macs have SSE.
- if(!gSysCPU.hasAltivec())
- {
- std::ostringstream msg;
- msg << LLTrans::getString("MBRequiresAltiVec");
- OSMessageBox(
- msg.str(),
- LLStringUtil::null,
- OSMB_OK);
- removeMarkerFile();
- return false;
- }
-#endif
-
-#endif // LL_DARWIN
-
- // Display splash screen. Must be after above check for previous
- // crash as this dialog is always frontmost.
- std::string splash_msg;
- LLStringUtil::format_map_t args;
- args["[APP_NAME]"] = LLTrans::getString("SECOND_LIFE");
- splash_msg = LLTrans::getString("StartupLoading", args);
- LLSplashScreen::show();
- LLSplashScreen::update(splash_msg);
-
- //LLVolumeMgr::initClass();
- LLVolumeMgr* volume_manager = new LLVolumeMgr();
- volume_manager->useMutex(); // LLApp and LLMutex magic must be manually enabled
- LLPrimitive::setVolumeManager(volume_manager);
-
- // Note: this is where we used to initialize gFeatureManagerp.
-
- gStartTime = totalTime();
-
- //
- // Set the name of the window
- //
- gWindowTitle = LLTrans::getString("APP_NAME");
-#if LL_DEBUG
- gWindowTitle += std::string(" [DEBUG] ") + gArgs;
-#else
- gWindowTitle += std::string(" ") + gArgs;
-#endif
- LLStringUtil::truncate(gWindowTitle, 255);
-
- //RN: if we received a URL, hand it off to the existing instance.
- // don't call anotherInstanceRunning() when doing URL handoff, as
- // it relies on checking a marker file which will not work when running
- // out of different directories
-
- if (LLStartUp::getStartSLURL().isValid())
- {
- if (sendURLToOtherInstance(LLStartUp::getStartSLURL().getSLURLString()))
- {
- // successfully handed off URL to existing instance, exit
- return false;
- }
- }
-
- if (!gSavedSettings.getBOOL("AllowMultipleViewers"))
- {
- //
- // Check for another instance of the app running
- //
-
- mSecondInstance = anotherInstanceRunning();
-
- if (mSecondInstance)
- {
- std::ostringstream msg;
- msg << LLTrans::getString("MBAlreadyRunning");
- OSMessageBox(
- msg.str(),
- LLStringUtil::null,
- OSMB_OK);
- return false;
- }
-
- initMarkerFile();
-
- checkForCrash();
- }
- else
- {
- mSecondInstance = anotherInstanceRunning();
-
- if (mSecondInstance)
- {
- // This is the second instance of SL. Turn off voice support,
- // but make sure the setting is *not* persisted.
- LLControlVariable* disable_voice = gSavedSettings.getControl("CmdLineDisableVoice");
- if(disable_voice)
- {
- const BOOL DO_NOT_PERSIST = FALSE;
- disable_voice->setValue(LLSD(TRUE), DO_NOT_PERSIST);
- }
- }
-
- initMarkerFile();
-
- if(!mSecondInstance)
- {
- checkForCrash();
- }
- }
-
- // need to do this here - need to have initialized global settings first
- std::string nextLoginLocation = gSavedSettings.getString( "NextLoginLocation" );
- if ( !nextLoginLocation.empty() )
- {
- LLStartUp::setStartSLURL(LLSLURL(nextLoginLocation));
- };
-
- gLastRunVersion = gSavedSettings.getString("LastRunVersion");
-
- loadColorSettings();
-
- return true; // Config was successful.
-}
-
-namespace {
- // *TODO - decide if there's a better place for these functions.
- // do we need a file llupdaterui.cpp or something? -brad
-
- void apply_update_callback(LLSD const & notification, LLSD const & response)
- {
- lldebugs << "LLUpdate user response: " << response << llendl;
- if(response["OK_okcancelbuttons"].asBoolean())
- {
- llinfos << "LLUpdate restarting viewer" << llendl;
- static const bool install_if_ready = true;
- // *HACK - this lets us launch the installer immediately for now
- LLUpdaterService().startChecking(install_if_ready);
- }
- }
-
- void apply_update_ok_callback(LLSD const & notification, LLSD const & response)
- {
- llinfos << "LLUpdate restarting viewer" << llendl;
- static const bool install_if_ready = true;
- // *HACK - this lets us launch the installer immediately for now
- LLUpdaterService().startChecking(install_if_ready);
- }
-
- void on_update_downloaded(LLSD const & data)
- {
- std::string notification_name;
- void (*apply_callback)(LLSD const &, LLSD const &) = NULL;
-
- if(data["required"].asBoolean())
- {
- if(LLStartUp::getStartupState() <= STATE_LOGIN_WAIT)
- {
- // The user never saw the progress bar.
- apply_callback = &apply_update_ok_callback;
- notification_name = "RequiredUpdateDownloadedVerboseDialog";
- }
- else if(LLStartUp::getStartupState() < STATE_WORLD_INIT)
- {
- // The user is logging in but blocked.
- apply_callback = &apply_update_ok_callback;
- notification_name = "RequiredUpdateDownloadedDialog";
- }
- else
- {
- // The user is already logged in; treat like an optional update.
- apply_callback = &apply_update_callback;
- notification_name = "DownloadBackgroundTip";
- }
- }
- else
- {
- apply_callback = &apply_update_callback;
- if(LLStartUp::getStartupState() < STATE_STARTED)
- {
- // CHOP-262 we need to use a different notification
- // method prior to login.
- notification_name = "DownloadBackgroundDialog";
- }
- else
- {
- notification_name = "DownloadBackgroundTip";
- }
- }
-
- LLSD substitutions;
- substitutions["VERSION"] = data["version"];
-
- // truncate version at the rightmost '.'
- std::string version_short(data["version"]);
- size_t short_length = version_short.rfind('.');
- if (short_length != std::string::npos)
- {
- version_short.resize(short_length);
- }
-
- LLUIString relnotes_url("[RELEASE_NOTES_BASE_URL][CHANNEL_URL]/[VERSION_SHORT]");
- relnotes_url.setArg("[VERSION_SHORT]", version_short);
-
- // *TODO thread the update service's response through to this point
- std::string const & channel = LLVersionInfo::getChannel();
- boost::shared_ptr<char> channel_escaped(curl_escape(channel.c_str(), channel.size()), &curl_free);
-
- relnotes_url.setArg("[CHANNEL_URL]", channel_escaped.get());
- relnotes_url.setArg("[RELEASE_NOTES_BASE_URL]", LLTrans::getString("RELEASE_NOTES_BASE_URL"));
- substitutions["RELEASE_NOTES_FULL_URL"] = relnotes_url.getString();
-
- LLNotificationsUtil::add(notification_name, substitutions, LLSD(), apply_callback);
- }
-
- void install_error_callback(LLSD const & notification, LLSD const & response)
- {
- LLAppViewer::instance()->forceQuit();
- }
-
- bool notify_update(LLSD const & evt)
- {
- std::string notification_name;
- switch (evt["type"].asInteger())
- {
- case LLUpdaterService::DOWNLOAD_COMPLETE:
- on_update_downloaded(evt);
- break;
- case LLUpdaterService::INSTALL_ERROR:
- if(evt["required"].asBoolean()) {
- LLNotificationsUtil::add("FailedRequiredUpdateInstall", LLSD(), LLSD(), &install_error_callback);
- } else {
- LLNotificationsUtil::add("FailedUpdateInstall");
- }
- break;
- default:
- break;
- }
-
- // let others also handle this event by default
- return false;
- }
-
- bool on_bandwidth_throttle(LLUpdaterService * updater, LLSD const & evt)
- {
- updater->setBandwidthLimit(evt.asInteger() * (1024/8));
- return false; // Let others receive this event.
- };
-};
-
-void LLAppViewer::initUpdater()
-{
- // Initialize the updater service.
- // Generate URL to the udpater service
- // Get Channel
- // Get Version
- std::string url = gSavedSettings.getString("UpdaterServiceURL");
- std::string channel = LLVersionInfo::getChannel();
- std::string version = LLVersionInfo::getVersion();
- std::string protocol_version = gSavedSettings.getString("UpdaterServiceProtocolVersion");
- std::string service_path = gSavedSettings.getString("UpdaterServicePath");
- U32 check_period = gSavedSettings.getU32("UpdaterServiceCheckPeriod");
-
- mUpdater->setAppExitCallback(boost::bind(&LLAppViewer::forceQuit, this));
- mUpdater->initialize(protocol_version,
- url,
- service_path,
- channel,
- version);
- mUpdater->setCheckPeriod(check_period);
- mUpdater->setBandwidthLimit((int)gSavedSettings.getF32("UpdaterMaximumBandwidth") * (1024/8));
- gSavedSettings.getControl("UpdaterMaximumBandwidth")->getSignal()->
- connect(boost::bind(&on_bandwidth_throttle, mUpdater.get(), _2));
- if(gSavedSettings.getU32("UpdaterServiceSetting"))
- {
- bool install_if_ready = true;
- mUpdater->startChecking(install_if_ready);
- }
-
- LLEventPump & updater_pump = LLEventPumps::instance().obtain(LLUpdaterService::pumpName());
- updater_pump.listen("notify_update", &notify_update);
-}
-
-void LLAppViewer::checkForCrash(void)
-{
-
-#if LL_SEND_CRASH_REPORTS
- if (gLastExecEvent == LAST_EXEC_FROZE)
- {
- llinfos << "Last execution froze, requesting to send crash report." << llendl;
- //
- // Pop up a freeze or crash warning dialog
- //
- S32 choice;
- if(gCrashSettings.getS32(CRASH_BEHAVIOR_SETTING) == CRASH_BEHAVIOR_ASK)
- {
- std::ostringstream msg;
- msg << LLTrans::getString("MBFrozenCrashed");
- std::string alert = LLTrans::getString("APP_NAME") + " " + LLTrans::getString("MBAlert");
- choice = OSMessageBox(msg.str(),
- alert,
- OSMB_YESNO);
- }
- else if(gCrashSettings.getS32(CRASH_BEHAVIOR_SETTING) == CRASH_BEHAVIOR_NEVER_SEND)
- {
- choice = OSBTN_NO;
- }
- else
- {
- choice = OSBTN_YES;
- }
-
- if (OSBTN_YES == choice)
- {
- llinfos << "Sending crash report." << llendl;
-
- bool report_freeze = true;
- handleCrashReporting(report_freeze);
- }
- else
- {
- llinfos << "Not sending crash report." << llendl;
- }
- }
-#endif // LL_SEND_CRASH_REPORTS
-
-}
-
-bool LLAppViewer::initWindow()
-{
- LL_INFOS("AppInit") << "Initializing window..." << LL_ENDL;
-
- // store setting in a global for easy access and modification
- gNoRender = gSavedSettings.getBOOL("DisableRendering");
-
- // always start windowed
- BOOL ignorePixelDepth = gSavedSettings.getBOOL("IgnorePixelDepth");
- gViewerWindow = new LLViewerWindow(gWindowTitle,
- VIEWER_WINDOW_CLASSNAME,
- gSavedSettings.getS32("WindowX"), gSavedSettings.getS32("WindowY"),
- gSavedSettings.getS32("WindowWidth"), gSavedSettings.getS32("WindowHeight"),
- gSavedSettings.getBOOL("WindowFullScreen"), ignorePixelDepth);
-
- // Need to load feature table before cheking to start watchdog.
- const S32 NEVER_SUBMIT_REPORT = 2;
- bool use_watchdog = false;
- int watchdog_enabled_setting = gSavedSettings.getS32("WatchdogEnabled");
- if(watchdog_enabled_setting == -1){
- use_watchdog = !LLFeatureManager::getInstance()->isFeatureAvailable("WatchdogDisabled");
- }
- else
- {
- // The user has explicitly set this setting; always use that value.
- use_watchdog = bool(watchdog_enabled_setting);
- }
-
- bool send_reports = gCrashSettings.getS32(CRASH_BEHAVIOR_SETTING) != NEVER_SUBMIT_REPORT;
- if(use_watchdog && send_reports)
- {
- LLWatchdog::getInstance()->init(watchdog_killer_callback);
- }
-
- LLNotificationsUI::LLNotificationManager::getInstance();
-
- if (gSavedSettings.getBOOL("WindowMaximized"))
- {
- gViewerWindow->mWindow->maximize();
- }
-
- if (!gNoRender)
- {
- //
- // Initialize GL stuff
- //
-
- if (mForceGraphicsDetail)
- {
- LLFeatureManager::getInstance()->setGraphicsLevel(gSavedSettings.getU32("RenderQualityPerformance"), false);
- }
-
- // Set this flag in case we crash while initializing GL
- gSavedSettings.setBOOL("RenderInitError", TRUE);
- gSavedSettings.saveToFile( gSavedSettings.getString("ClientSettingsFile"), TRUE );
-
- gPipeline.init();
- stop_glerror();
- gViewerWindow->initGLDefaults();
-
- gSavedSettings.setBOOL("RenderInitError", FALSE);
- gSavedSettings.saveToFile( gSavedSettings.getString("ClientSettingsFile"), TRUE );
- }
-
- //If we have a startup crash, it's usually near GL initialization, so simulate that.
- if(gCrashOnStartup)
- {
- LLAppViewer::instance()->forceErrorLLError();
- }
-
- LLUI::sWindow = gViewerWindow->getWindow();
-
- // Show watch cursor
- gViewerWindow->setCursor(UI_CURSOR_WAIT);
-
- // Finish view initialization
- gViewerWindow->initBase();
-
- // show viewer window
- //gViewerWindow->mWindow->show();
-
-
- return true;
-}
-
-void LLAppViewer::writeDebugInfo()
-{
- std::string debug_filename = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,"debug_info.log");
- llinfos << "Opening debug file " << debug_filename << llendl;
- llofstream out_file(debug_filename);
- LLSDSerialize::toPrettyXML(gDebugInfo, out_file);
- out_file.close();
-}
-
-void LLAppViewer::cleanupSavedSettings()
-{
- gSavedSettings.setBOOL("MouseSun", FALSE);
-
- gSavedSettings.setBOOL("UseEnergy", TRUE); // force toggle to turn off, since sends message to simulator
-
- gSavedSettings.setBOOL("DebugWindowProc", gDebugWindowProc);
-
- gSavedSettings.setBOOL("ShowObjectUpdates", gShowObjectUpdates);
-
- if (!gNoRender)
- {
- if (gDebugView)
- {
- gSavedSettings.setBOOL("ShowDebugConsole", gDebugView->mDebugConsolep->getVisible());
- }
- }
-
- // save window position if not maximized
- // as we don't track it in callbacks
- if(NULL != gViewerWindow)
- {
- BOOL maximized = gViewerWindow->mWindow->getMaximized();
- if (!maximized)
- {
- LLCoordScreen window_pos;
-
- if (gViewerWindow->mWindow->getPosition(&window_pos))
- {
- gSavedSettings.setS32("WindowX", window_pos.mX);
- gSavedSettings.setS32("WindowY", window_pos.mY);
- }
- }
- }
-
- gSavedSettings.setF32("MapScale", LLWorldMapView::sMapScale );
-
- // Some things are cached in LLAgent.
- if (gAgent.isInitialized())
- {
- gSavedSettings.setF32("RenderFarClip", gAgentCamera.mDrawDistance);
- }
-}
-
-void LLAppViewer::removeCacheFiles(const std::string& file_mask)
-{
- std::string mask = gDirUtilp->getDirDelimiter() + file_mask;
- gDirUtilp->deleteFilesInDir(gDirUtilp->getExpandedFilename(LL_PATH_CACHE, ""), mask);
-}
-
-void LLAppViewer::writeSystemInfo()
-{
- gDebugInfo["SLLog"] = LLError::logFileName();
-
- gDebugInfo["ClientInfo"]["Name"] = LLVersionInfo::getChannel();
- gDebugInfo["ClientInfo"]["MajorVersion"] = LLVersionInfo::getMajor();
- gDebugInfo["ClientInfo"]["MinorVersion"] = LLVersionInfo::getMinor();
- gDebugInfo["ClientInfo"]["PatchVersion"] = LLVersionInfo::getPatch();
- gDebugInfo["ClientInfo"]["BuildVersion"] = LLVersionInfo::getBuild();
-
- gDebugInfo["CAFilename"] = gDirUtilp->getCAFile();
-
- gDebugInfo["CPUInfo"]["CPUString"] = gSysCPU.getCPUString();
- gDebugInfo["CPUInfo"]["CPUFamily"] = gSysCPU.getFamily();
- gDebugInfo["CPUInfo"]["CPUMhz"] = (S32)gSysCPU.getMHz();
- gDebugInfo["CPUInfo"]["CPUAltivec"] = gSysCPU.hasAltivec();
- gDebugInfo["CPUInfo"]["CPUSSE"] = gSysCPU.hasSSE();
- gDebugInfo["CPUInfo"]["CPUSSE2"] = gSysCPU.hasSSE2();
-
- gDebugInfo["RAMInfo"]["Physical"] = (LLSD::Integer)(gSysMemory.getPhysicalMemoryKB());
- gDebugInfo["RAMInfo"]["Allocated"] = (LLSD::Integer)(gMemoryAllocated>>10); // MB -> KB
- gDebugInfo["OSInfo"] = getOSInfo().getOSStringSimple();
-
- // The user is not logged on yet, but record the current grid choice login url
- // which may have been the intended grid. This can b
- gDebugInfo["GridName"] = LLGridManager::getInstance()->getGridLabel();
-
- // *FIX:Mani - move this down in llappviewerwin32
-#ifdef LL_WINDOWS
- DWORD thread_id = GetCurrentThreadId();
- gDebugInfo["MainloopThreadID"] = (S32)thread_id;
-#endif
-
- // "CrashNotHandled" is set here, while things are running well,
- // in case of a freeze. If there is a freeze, the crash logger will be launched
- // and can read this value from the debug_info.log.
- // If the crash is handled by LLAppViewer::handleViewerCrash, ie not a freeze,
- // then the value of "CrashNotHandled" will be set to true.
- gDebugInfo["CrashNotHandled"] = (LLSD::Boolean)true;
-
- // Insert crash host url (url to post crash log to) if configured. This insures
- // that the crash report will go to the proper location in the case of a
- // prior freeze.
- std::string crashHostUrl = gSavedSettings.get<std::string>("CrashHostUrl");
- if(crashHostUrl != "")
- {
- gDebugInfo["CrashHostUrl"] = crashHostUrl;
- }
-
- // Dump some debugging info
- LL_INFOS("SystemInfo") << LLTrans::getString("APP_NAME")
- << " version " << LLVersionInfo::getShortVersion() << LL_ENDL;
-
- // Dump the local time and time zone
- time_t now;
- time(&now);
- char tbuffer[256]; /* Flawfinder: ignore */
- strftime(tbuffer, 256, "%Y-%m-%dT%H:%M:%S %Z", localtime(&now));
- LL_INFOS("SystemInfo") << "Local time: " << tbuffer << LL_ENDL;
-
- // query some system information
- LL_INFOS("SystemInfo") << "CPU info:\n" << gSysCPU << LL_ENDL;
- LL_INFOS("SystemInfo") << "Memory info:\n" << gSysMemory << LL_ENDL;
- LL_INFOS("SystemInfo") << "OS: " << getOSInfo().getOSStringSimple() << LL_ENDL;
- LL_INFOS("SystemInfo") << "OS info: " << getOSInfo() << LL_ENDL;
-
- writeDebugInfo(); // Save out debug_info.log early, in case of crash.
-}
-
-void LLAppViewer::handleViewerCrash()
-{
- llinfos << "Handle viewer crash entry." << llendl;
-
- llinfos << "Last render pool type: " << LLPipeline::sCurRenderPoolType << llendl ;
-
- //print out recorded call stacks if there are any.
- LLError::LLCallStacks::print();
-
- LLAppViewer* pApp = LLAppViewer::instance();
- if (pApp->beingDebugged())
- {
- // This will drop us into the debugger.
- abort();
- }
-
- if (LLApp::isCrashloggerDisabled())
- {
- abort();
- }
-
- // Returns whether a dialog was shown.
- // Only do the logic in here once
- if (pApp->mReportedCrash)
- {
- return;
- }
- pApp->mReportedCrash = TRUE;
-
- // Insert crash host url (url to post crash log to) if configured.
- std::string crashHostUrl = gSavedSettings.get<std::string>("CrashHostUrl");
- if(crashHostUrl != "")
- {
- gDebugInfo["CrashHostUrl"] = crashHostUrl;
- }
-
- //We already do this in writeSystemInfo(), but we do it again here to make /sure/ we have a version
- //to check against no matter what
- gDebugInfo["ClientInfo"]["Name"] = LLVersionInfo::getChannel();
-
- gDebugInfo["ClientInfo"]["MajorVersion"] = LLVersionInfo::getMajor();
- gDebugInfo["ClientInfo"]["MinorVersion"] = LLVersionInfo::getMinor();
- gDebugInfo["ClientInfo"]["PatchVersion"] = LLVersionInfo::getPatch();
- gDebugInfo["ClientInfo"]["BuildVersion"] = LLVersionInfo::getBuild();
-
- LLParcel* parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
- if ( parcel && parcel->getMusicURL()[0])
- {
- gDebugInfo["ParcelMusicURL"] = parcel->getMusicURL();
- }
- if ( parcel && parcel->getMediaURL()[0])
- {
- gDebugInfo["ParcelMediaURL"] = parcel->getMediaURL();
- }
-
-
- gDebugInfo["SettingsFilename"] = gSavedSettings.getString("ClientSettingsFile");
- gDebugInfo["CAFilename"] = gDirUtilp->getCAFile();
- gDebugInfo["ViewerExePath"] = gDirUtilp->getExecutablePathAndName();
- gDebugInfo["CurrentPath"] = gDirUtilp->getCurPath();
- gDebugInfo["SessionLength"] = F32(LLFrameTimer::getElapsedSeconds());
- gDebugInfo["StartupState"] = LLStartUp::getStartupStateString();
- gDebugInfo["RAMInfo"]["Allocated"] = (LLSD::Integer) LLMemory::getCurrentRSS() >> 10;
- gDebugInfo["FirstLogin"] = (LLSD::Boolean) gAgent.isFirstLogin();
- gDebugInfo["FirstRunThisInstall"] = gSavedSettings.getBOOL("FirstRunThisInstall");
-
- char *minidump_file = pApp->getMiniDumpFilename();
- if(minidump_file && minidump_file[0] != 0)
- {
- gDebugInfo["MinidumpPath"] = minidump_file;
- }
-
- if(gLogoutInProgress)
- {
- gDebugInfo["LastExecEvent"] = LAST_EXEC_LOGOUT_CRASH;
- }
- else
- {
- gDebugInfo["LastExecEvent"] = gLLErrorActivated ? LAST_EXEC_LLERROR_CRASH : LAST_EXEC_OTHER_CRASH;
- }
-
- if(gAgent.getRegion())
- {
- gDebugInfo["CurrentSimHost"] = gAgent.getRegionHost().getHostName();
- gDebugInfo["CurrentRegion"] = gAgent.getRegion()->getName();
-
- const LLVector3& loc = gAgent.getPositionAgent();
- gDebugInfo["CurrentLocationX"] = loc.mV[0];
- gDebugInfo["CurrentLocationY"] = loc.mV[1];
- gDebugInfo["CurrentLocationZ"] = loc.mV[2];
- }
-
- if(LLAppViewer::instance()->mMainloopTimeout)
- {
- gDebugInfo["MainloopTimeoutState"] = LLAppViewer::instance()->mMainloopTimeout->getState();
- }
-
- // The crash is being handled here so set this value to false.
- // Otherwise the crash logger will think this crash was a freeze.
- gDebugInfo["CrashNotHandled"] = (LLSD::Boolean)false;
-
- //Write out the crash status file
- //Use marker file style setup, as that's the simplest, especially since
- //we're already in a crash situation
- if (gDirUtilp)
- {
- std::string crash_file_name;
- if(gLLErrorActivated) crash_file_name = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,LLERROR_MARKER_FILE_NAME);
- else crash_file_name = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,ERROR_MARKER_FILE_NAME);
- llinfos << "Creating crash marker file " << crash_file_name << llendl;
-
- LLAPRFile crash_file ;
- crash_file.open(crash_file_name, LL_APR_W);
- if (crash_file.getFileHandle())
- {
- LL_INFOS("MarkerFile") << "Created crash marker file " << crash_file_name << LL_ENDL;
- }
- else
- {
- LL_WARNS("MarkerFile") << "Cannot create error marker file " << crash_file_name << LL_ENDL;
- }
- }
-
- if (gMessageSystem && gDirUtilp)
- {
- std::string filename;
- filename = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "stats.log");
- llofstream file(filename, llofstream::binary);
- if(file.good())
- {
- llinfos << "Handle viewer crash generating stats log." << llendl;
- gMessageSystem->summarizeLogs(file);
- file.close();
- }
- }
-
- if (gMessageSystem)
- {
- gMessageSystem->getCircuitInfo(gDebugInfo["CircuitInfo"]);
- gMessageSystem->stopLogging();
- }
-
- if (LLWorld::instanceExists()) LLWorld::getInstance()->getInfo(gDebugInfo);
-
- // Close the debug file
- pApp->writeDebugInfo();
-
- LLError::logToFile("");
-
- // Remove the marker file, since otherwise we'll spawn a process that'll keep it locked
- if(gDebugInfo["LastExecEvent"].asInteger() == LAST_EXEC_LOGOUT_CRASH)
- {
- pApp->removeMarkerFile(true);
- }
- else
- {
- pApp->removeMarkerFile(false);
- }
-
-#if LL_SEND_CRASH_REPORTS
- // Call to pure virtual, handled by platform specific llappviewer instance.
- pApp->handleCrashReporting();
-#endif
-
- return;
-}
-
-bool LLAppViewer::anotherInstanceRunning()
-{
- // We create a marker file when the program starts and remove the file when it finishes.
- // If the file is currently locked, that means another process is already running.
-
- std::string marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, MARKER_FILE_NAME);
- LL_DEBUGS("MarkerFile") << "Checking marker file for lock..." << LL_ENDL;
-
- //Freeze case checks
- if (LLAPRFile::isExist(marker_file, NULL, LL_APR_RB))
- {
- // File exists, try opening with write permissions
- LLAPRFile outfile ;
- outfile.open(marker_file, LL_APR_WB);
- apr_file_t* fMarker = outfile.getFileHandle() ;
- if (!fMarker)
- {
- // Another instance is running. Skip the rest of these operations.
- LL_INFOS("MarkerFile") << "Marker file is locked." << LL_ENDL;
- return true;
- }
- if (apr_file_lock(fMarker, APR_FLOCK_NONBLOCK | APR_FLOCK_EXCLUSIVE) != APR_SUCCESS) //flock(fileno(fMarker), LOCK_EX | LOCK_NB) == -1)
- {
- LL_INFOS("MarkerFile") << "Marker file is locked." << LL_ENDL;
- return true;
- }
- // No other instances; we'll lock this file now & delete on quit.
- }
- LL_DEBUGS("MarkerFile") << "Marker file isn't locked." << LL_ENDL;
- return false;
-}
-
-void LLAppViewer::initMarkerFile()
-{
- //First, check for the existence of other files.
- //There are marker files for two different types of crashes
-
- mMarkerFileName = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,MARKER_FILE_NAME);
- LL_DEBUGS("MarkerFile") << "Checking marker file for lock..." << LL_ENDL;
-
- //We've got 4 things to test for here
- // - Other Process Running (SecondLife.exec_marker present, locked)
- // - Freeze (SecondLife.exec_marker present, not locked)
- // - LLError Crash (SecondLife.llerror_marker present)
- // - Other Crash (SecondLife.error_marker present)
- // These checks should also remove these files for the last 2 cases if they currently exist
-
- //LLError/Error checks. Only one of these should ever happen at a time.
- std::string logout_marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, LOGOUT_MARKER_FILE_NAME);
- std::string llerror_marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, LLERROR_MARKER_FILE_NAME);
- std::string error_marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, ERROR_MARKER_FILE_NAME);
-
- if (LLAPRFile::isExist(mMarkerFileName, NULL, LL_APR_RB) && !anotherInstanceRunning())
- {
- gLastExecEvent = LAST_EXEC_FROZE;
- LL_INFOS("MarkerFile") << "Exec marker found: program froze on previous execution" << LL_ENDL;
- }
- if(LLAPRFile::isExist(logout_marker_file, NULL, LL_APR_RB))
- {
- gLastExecEvent = LAST_EXEC_LOGOUT_FROZE;
- LL_INFOS("MarkerFile") << "Last exec LLError crashed, setting LastExecEvent to " << gLastExecEvent << LL_ENDL;
- LLAPRFile::remove(logout_marker_file);
- }
- if(LLAPRFile::isExist(llerror_marker_file, NULL, LL_APR_RB))
- {
- if(gLastExecEvent == LAST_EXEC_LOGOUT_FROZE) gLastExecEvent = LAST_EXEC_LOGOUT_CRASH;
- else gLastExecEvent = LAST_EXEC_LLERROR_CRASH;
- LL_INFOS("MarkerFile") << "Last exec LLError crashed, setting LastExecEvent to " << gLastExecEvent << LL_ENDL;
- LLAPRFile::remove(llerror_marker_file);
- }
- if(LLAPRFile::isExist(error_marker_file, NULL, LL_APR_RB))
- {
- if(gLastExecEvent == LAST_EXEC_LOGOUT_FROZE) gLastExecEvent = LAST_EXEC_LOGOUT_CRASH;
- else gLastExecEvent = LAST_EXEC_OTHER_CRASH;
- LL_INFOS("MarkerFile") << "Last exec crashed, setting LastExecEvent to " << gLastExecEvent << LL_ENDL;
- LLAPRFile::remove(error_marker_file);
- }
-
- // No new markers if another instance is running.
- if(anotherInstanceRunning())
- {
- return;
- }
-
- // Create the marker file for this execution & lock it
- apr_status_t s;
- s = mMarkerFile.open(mMarkerFileName, LL_APR_W, TRUE);
-
- if (s == APR_SUCCESS && mMarkerFile.getFileHandle())
- {
- LL_DEBUGS("MarkerFile") << "Marker file created." << LL_ENDL;
- }
- else
- {
- LL_INFOS("MarkerFile") << "Failed to create marker file." << LL_ENDL;
- return;
- }
- if (apr_file_lock(mMarkerFile.getFileHandle(), APR_FLOCK_NONBLOCK | APR_FLOCK_EXCLUSIVE) != APR_SUCCESS)
- {
- mMarkerFile.close() ;
- LL_INFOS("MarkerFile") << "Marker file cannot be locked." << LL_ENDL;
- return;
- }
-
- LL_DEBUGS("MarkerFile") << "Marker file locked." << LL_ENDL;
-}
-
-void LLAppViewer::removeMarkerFile(bool leave_logout_marker)
-{
- LL_DEBUGS("MarkerFile") << "removeMarkerFile()" << LL_ENDL;
- if (mMarkerFile.getFileHandle())
- {
- mMarkerFile.close() ;
- LLAPRFile::remove( mMarkerFileName );
- }
- if (mLogoutMarkerFile != NULL && !leave_logout_marker)
- {
- LLAPRFile::remove( mLogoutMarkerFileName );
- mLogoutMarkerFile = NULL;
- }
-}
-
-void LLAppViewer::forceQuit()
-{
- LLApp::setQuitting();
-}
-
-//TODO: remove
-void LLAppViewer::fastQuit(S32 error_code)
-{
- // finish pending transfers
- flushVFSIO();
- // let sim know we're logging out
- sendLogoutRequest();
- // flush network buffers by shutting down messaging system
- end_messaging_system();
- // figure out the error code
- S32 final_error_code = error_code ? error_code : (S32)isError();
- // this isn't a crash
- removeMarkerFile();
- // get outta here
- _exit(final_error_code);
-}
-
-void LLAppViewer::requestQuit()
-{
- llinfos << "requestQuit" << llendl;
-
- LLViewerRegion* region = gAgent.getRegion();
-
- if( (LLStartUp::getStartupState() < STATE_STARTED) || !region )
- {
- // If we have a region, make some attempt to send a logout request first.
- // This prevents the halfway-logged-in avatar from hanging around inworld for a couple minutes.
- if(region)
- {
- sendLogoutRequest();
- }
-
- // Quit immediately
- forceQuit();
- return;
- }
-
- // Try to send metrics back to the grid
- metricsSend(!gDisconnected);
-
- LLHUDEffectSpiral *effectp = (LLHUDEffectSpiral*)LLHUDManager::getInstance()->createViewerEffect(LLHUDObject::LL_HUD_EFFECT_POINT, TRUE);
- effectp->setPositionGlobal(gAgent.getPositionGlobal());
- effectp->setColor(LLColor4U(gAgent.getEffectColor()));
- LLHUDManager::getInstance()->sendEffects();
- effectp->markDead() ;//remove it.
-
- // Attempt to close all floaters that might be
- // editing things.
- if (gFloaterView)
- {
- // application is quitting
- gFloaterView->closeAllChildren(true);
- }
-
- LLSideTray::getInstance()->notifyChildren(LLSD().with("request","quit"));
-
- send_stats();
-
- gLogoutTimer.reset();
- mQuitRequested = true;
-}
-
-static bool finish_quit(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
-
- if (option == 0)
- {
- LLAppViewer::instance()->requestQuit();
- }
- return false;
-}
-static LLNotificationFunctorRegistration finish_quit_reg("ConfirmQuit", finish_quit);
-
-static bool switch_standard_skin_and_quit(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
-
- if (option == 0)
- {
- gSavedSettings.setString("SessionSettingsFile", "");
- LLAppViewer::instance()->requestQuit();
- }
- return false;
-}
-
-static LLNotificationFunctorRegistration standard_skin_quit_reg("SwitchToStandardSkinAndQuit", switch_standard_skin_and_quit);
-
-void LLAppViewer::userQuit()
-{
- if (gDisconnected || gViewerWindow->getProgressView()->getVisible())
- {
- requestQuit();
- }
- else
- {
- LLNotificationsUtil::add("ConfirmQuit");
- }
-}
-
-static bool finish_early_exit(const LLSD& notification, const LLSD& response)
-{
- LLAppViewer::instance()->forceQuit();
- return false;
-}
-
-void LLAppViewer::earlyExit(const std::string& name, const LLSD& substitutions)
-{
- llwarns << "app_early_exit: " << name << llendl;
- gDoDisconnect = TRUE;
- LLNotificationsUtil::add(name, substitutions, LLSD(), finish_early_exit);
-}
-
-// case where we need the viewer to exit without any need for notifications
-void LLAppViewer::earlyExitNoNotify()
-{
- llwarns << "app_early_exit with no notification: " << llendl;
- gDoDisconnect = TRUE;
- finish_early_exit( LLSD(), LLSD() );
-}
-
-void LLAppViewer::abortQuit()
-{
- llinfos << "abortQuit()" << llendl;
- mQuitRequested = false;
-}
-
-void LLAppViewer::migrateCacheDirectory()
-{
-#if LL_WINDOWS || LL_DARWIN
- // NOTE: (Nyx) as of 1.21, cache for mac is moving to /library/caches/SecondLife from
- // /library/application support/SecondLife/cache This should clear/delete the old dir.
-
- // As of 1.23 the Windows cache moved from
- // C:\Documents and Settings\James\Application Support\SecondLife\cache
- // to
- // C:\Documents and Settings\James\Local Settings\Application Support\SecondLife
- //
- // The Windows Vista equivalent is from
- // C:\Users\James\AppData\Roaming\SecondLife\cache
- // to
- // C:\Users\James\AppData\Local\SecondLife
- //
- // Note the absence of \cache on the second path. James.
-
- // Only do this once per fresh install of this version.
- if (gSavedSettings.getBOOL("MigrateCacheDirectory"))
- {
- gSavedSettings.setBOOL("MigrateCacheDirectory", FALSE);
-
- std::string delimiter = gDirUtilp->getDirDelimiter();
- std::string old_cache_dir = gDirUtilp->getOSUserAppDir() + delimiter + "cache";
- std::string new_cache_dir = gDirUtilp->getCacheDir(true);
-
- if (gDirUtilp->fileExists(old_cache_dir))
- {
- llinfos << "Migrating cache from " << old_cache_dir << " to " << new_cache_dir << llendl;
-
- // Migrate inventory cache to avoid pain to inventory database after mass update
- S32 file_count = 0;
- std::string file_name;
- std::string mask = delimiter + "*.*";
- while (gDirUtilp->getNextFileInDir(old_cache_dir, mask, file_name))
- {
- if (file_name == "." || file_name == "..") continue;
- std::string source_path = old_cache_dir + delimiter + file_name;
- std::string dest_path = new_cache_dir + delimiter + file_name;
- if (!LLFile::rename(source_path, dest_path))
- {
- file_count++;
- }
- }
- llinfos << "Moved " << file_count << " files" << llendl;
-
- // Nuke the old cache
- gDirUtilp->setCacheDir(old_cache_dir);
- purgeCache();
- gDirUtilp->setCacheDir(new_cache_dir);
-
-#if LL_DARWIN
- // Clean up Mac files not deleted by removing *.*
- std::string ds_store = old_cache_dir + "/.DS_Store";
- if (gDirUtilp->fileExists(ds_store))
- {
- LLFile::remove(ds_store);
- }
-#endif
- if (LLFile::rmdir(old_cache_dir) != 0)
- {
- llwarns << "could not delete old cache directory " << old_cache_dir << llendl;
- }
- }
- }
-#endif // LL_WINDOWS || LL_DARWIN
-}
-
-void dumpVFSCaches()
-{
- llinfos << "======= Static VFS ========" << llendl;
- gStaticVFS->listFiles();
-#if LL_WINDOWS
- llinfos << "======= Dumping static VFS to StaticVFSDump ========" << llendl;
- WCHAR w_str[MAX_PATH];
- GetCurrentDirectory(MAX_PATH, w_str);
- S32 res = LLFile::mkdir("StaticVFSDump");
- if (res == -1)
- {
- if (errno != EEXIST)
- {
- llwarns << "Couldn't create dir StaticVFSDump" << llendl;
- }
- }
- SetCurrentDirectory(utf8str_to_utf16str("StaticVFSDump").c_str());
- gStaticVFS->dumpFiles();
- SetCurrentDirectory(w_str);
-#endif
-
- llinfos << "========= Dynamic VFS ====" << llendl;
- gVFS->listFiles();
-#if LL_WINDOWS
- llinfos << "========= Dumping dynamic VFS to VFSDump ====" << llendl;
- res = LLFile::mkdir("VFSDump");
- if (res == -1)
- {
- if (errno != EEXIST)
- {
- llwarns << "Couldn't create dir VFSDump" << llendl;
- }
- }
- SetCurrentDirectory(utf8str_to_utf16str("VFSDump").c_str());
- gVFS->dumpFiles();
- SetCurrentDirectory(w_str);
-#endif
-}
-
-//static
-U32 LLAppViewer::getTextureCacheVersion()
-{
- //viewer texture cache version, change if the texture cache format changes.
- const U32 TEXTURE_CACHE_VERSION = 7;
-
- return TEXTURE_CACHE_VERSION ;
-}
-
-//static
-U32 LLAppViewer::getObjectCacheVersion()
-{
- // Viewer object cache version, change if object update
- // format changes. JC
- const U32 INDRA_OBJECT_CACHE_VERSION = 14;
-
- return INDRA_OBJECT_CACHE_VERSION;
-}
-
-bool LLAppViewer::initCache()
-{
- mPurgeCache = false;
- BOOL read_only = mSecondInstance ? TRUE : FALSE;
- LLAppViewer::getTextureCache()->setReadOnly(read_only) ;
- LLVOCache::getInstance()->setReadOnly(read_only);
-
- BOOL texture_cache_mismatch = FALSE ;
- if (gSavedSettings.getS32("LocalCacheVersion") != LLAppViewer::getTextureCacheVersion())
- {
- texture_cache_mismatch = TRUE ;
- if(!read_only)
- {
- gSavedSettings.setS32("LocalCacheVersion", LLAppViewer::getTextureCacheVersion());
- }
- }
-
- if(!read_only)
- {
- // Purge cache if user requested it
- if (gSavedSettings.getBOOL("PurgeCacheOnStartup") ||
- gSavedSettings.getBOOL("PurgeCacheOnNextStartup"))
- {
- gSavedSettings.setBOOL("PurgeCacheOnNextStartup", false);
- mPurgeCache = true;
- }
-
- // We have moved the location of the cache directory over time.
- migrateCacheDirectory();
-
- // Setup and verify the cache location
- std::string cache_location = gSavedSettings.getString("CacheLocation");
- std::string new_cache_location = gSavedSettings.getString("NewCacheLocation");
- if (new_cache_location != cache_location)
- {
- gDirUtilp->setCacheDir(gSavedSettings.getString("CacheLocation"));
- purgeCache(); // purge old cache
- gSavedSettings.setString("CacheLocation", new_cache_location);
- gSavedSettings.setString("CacheLocationTopFolder", gDirUtilp->getBaseFileName(new_cache_location));
- }
- }
-
- if (!gDirUtilp->setCacheDir(gSavedSettings.getString("CacheLocation")))
- {
- LL_WARNS("AppCache") << "Unable to set cache location" << LL_ENDL;
- gSavedSettings.setString("CacheLocation", "");
- gSavedSettings.setString("CacheLocationTopFolder", "");
- }
-
- if (mPurgeCache && !read_only)
- {
- LLSplashScreen::update(LLTrans::getString("StartupClearingCache"));
- purgeCache();
- }
-
- LLSplashScreen::update(LLTrans::getString("StartupInitializingTextureCache"));
-
- // Init the texture cache
- // Allocate 80% of the cache size for textures
- const S32 MB = 1024*1024;
- S64 cache_size = (S64)(gSavedSettings.getU32("CacheSize")) * MB;
- const S64 MAX_CACHE_SIZE = 1024*MB;
- cache_size = llmin(cache_size, MAX_CACHE_SIZE);
- S64 texture_cache_size = ((cache_size * 8)/10);
- S64 extra = LLAppViewer::getTextureCache()->initCache(LL_PATH_CACHE, texture_cache_size, texture_cache_mismatch);
- texture_cache_size -= extra;
-
- LLVOCache::getInstance()->initCache(LL_PATH_CACHE, gSavedSettings.getU32("CacheNumberOfRegionsForObjects"), getObjectCacheVersion()) ;
-
- LLSplashScreen::update(LLTrans::getString("StartupInitializingVFS"));
-
- // Init the VFS
- S64 vfs_size = cache_size - texture_cache_size;
- const S64 MAX_VFS_SIZE = 1024 * MB; // 1 GB
- vfs_size = llmin(vfs_size, MAX_VFS_SIZE);
- vfs_size = (vfs_size / MB) * MB; // make sure it is MB aligned
- U32 vfs_size_u32 = (U32)vfs_size;
- U32 old_vfs_size = gSavedSettings.getU32("VFSOldSize") * MB;
- bool resize_vfs = (vfs_size_u32 != old_vfs_size);
- if (resize_vfs)
- {
- gSavedSettings.setU32("VFSOldSize", vfs_size_u32/MB);
- }
- LL_INFOS("AppCache") << "VFS CACHE SIZE: " << vfs_size/(1024*1024) << " MB" << LL_ENDL;
-
- // This has to happen BEFORE starting the vfs
- //time_t ltime;
- srand(time(NULL)); // Flawfinder: ignore
- U32 old_salt = gSavedSettings.getU32("VFSSalt");
- U32 new_salt;
- std::string old_vfs_data_file;
- std::string old_vfs_index_file;
- std::string new_vfs_data_file;
- std::string new_vfs_index_file;
- std::string static_vfs_index_file;
- std::string static_vfs_data_file;
-
- if (gSavedSettings.getBOOL("AllowMultipleViewers"))
- {
- // don't mess with renaming the VFS in this case
- new_salt = old_salt;
- }
- else
- {
- do
- {
- new_salt = rand();
- } while( new_salt == old_salt );
- }
-
- old_vfs_data_file = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,VFS_DATA_FILE_BASE) + llformat("%u",old_salt);
-
- // make sure this file exists
- llstat s;
- S32 stat_result = LLFile::stat(old_vfs_data_file, &s);
- if (stat_result)
- {
- // doesn't exist, look for a data file
- std::string mask;
- mask = gDirUtilp->getDirDelimiter();
- mask += VFS_DATA_FILE_BASE;
- mask += "*";
-
- std::string dir;
- dir = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,"");
-
- std::string found_file;
- if (gDirUtilp->getNextFileInDir(dir, mask, found_file))
- {
- old_vfs_data_file = dir + gDirUtilp->getDirDelimiter() + found_file;
-
- S32 start_pos = found_file.find_last_of('.');
- if (start_pos > 0)
- {
- sscanf(found_file.substr(start_pos+1).c_str(), "%d", &old_salt);
- }
- LL_DEBUGS("AppCache") << "Default vfs data file not present, found: " << old_vfs_data_file << " Old salt: " << old_salt << llendl;
- }
- }
-
- old_vfs_index_file = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,VFS_INDEX_FILE_BASE) + llformat("%u",old_salt);
-
- stat_result = LLFile::stat(old_vfs_index_file, &s);
- if (stat_result)
- {
- // We've got a bad/missing index file, nukem!
- LL_WARNS("AppCache") << "Bad or missing vfx index file " << old_vfs_index_file << LL_ENDL;
- LL_WARNS("AppCache") << "Removing old vfs data file " << old_vfs_data_file << LL_ENDL;
- LLFile::remove(old_vfs_data_file);
- LLFile::remove(old_vfs_index_file);
-
- // Just in case, nuke any other old cache files in the directory.
- std::string dir;
- dir = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,"");
-
- std::string mask;
- mask = gDirUtilp->getDirDelimiter();
- mask += VFS_DATA_FILE_BASE;
- mask += "*";
-
- gDirUtilp->deleteFilesInDir(dir, mask);
-
- mask = gDirUtilp->getDirDelimiter();
- mask += VFS_INDEX_FILE_BASE;
- mask += "*";
-
- gDirUtilp->deleteFilesInDir(dir, mask);
- }
-
- new_vfs_data_file = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,VFS_DATA_FILE_BASE) + llformat("%u",new_salt);
- new_vfs_index_file = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, VFS_INDEX_FILE_BASE) + llformat("%u",new_salt);
-
- static_vfs_data_file = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"static_data.db2");
- static_vfs_index_file = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"static_index.db2");
-
- if (resize_vfs)
- {
- LL_DEBUGS("AppCache") << "Removing old vfs and re-sizing" << LL_ENDL;
-
- LLFile::remove(old_vfs_data_file);
- LLFile::remove(old_vfs_index_file);
- }
- else if (old_salt != new_salt)
- {
- // move the vfs files to a new name before opening
- LL_DEBUGS("AppCache") << "Renaming " << old_vfs_data_file << " to " << new_vfs_data_file << LL_ENDL;
- LL_DEBUGS("AppCache") << "Renaming " << old_vfs_index_file << " to " << new_vfs_index_file << LL_ENDL;
- LLFile::rename(old_vfs_data_file, new_vfs_data_file);
- LLFile::rename(old_vfs_index_file, new_vfs_index_file);
- }
-
- // Startup the VFS...
- gSavedSettings.setU32("VFSSalt", new_salt);
-
- // Don't remove VFS after viewer crashes. If user has corrupt data, they can reinstall. JC
- gVFS = LLVFS::createLLVFS(new_vfs_index_file, new_vfs_data_file, false, vfs_size_u32, false);
- if( !gVFS )
- {
- return false;
- }
-
- gStaticVFS = LLVFS::createLLVFS(static_vfs_index_file, static_vfs_data_file, true, 0, false);
- if( !gStaticVFS )
- {
- return false;
- }
-
- BOOL success = gVFS->isValid() && gStaticVFS->isValid();
- if( !success )
- {
- return false;
- }
- else
- {
- LLVFile::initClass();
-
-#ifndef LL_RELEASE_FOR_DOWNLOAD
- if (gSavedSettings.getBOOL("DumpVFSCaches"))
- {
- dumpVFSCaches();
- }
-#endif
-
- return true;
- }
-}
-
-void LLAppViewer::purgeCache()
-{
- LL_INFOS("AppCache") << "Purging Cache and Texture Cache..." << llendl;
- LLAppViewer::getTextureCache()->purgeCache(LL_PATH_CACHE);
- LLVOCache::getInstance()->removeCache(LL_PATH_CACHE);
- std::string mask = gDirUtilp->getDirDelimiter() + "*.*";
- gDirUtilp->deleteFilesInDir(gDirUtilp->getExpandedFilename(LL_PATH_CACHE,""),mask);
-}
-
-std::string LLAppViewer::getSecondLifeTitle() const
-{
- return LLTrans::getString("APP_NAME");
-}
-
-std::string LLAppViewer::getWindowTitle() const
-{
- return gWindowTitle;
-}
-
-// Callback from a dialog indicating user was logged out.
-bool finish_disconnect(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
-
- if (1 == option)
- {
- LLAppViewer::instance()->forceQuit();
- }
- return false;
-}
-
-// Callback from an early disconnect dialog, force an exit
-bool finish_forced_disconnect(const LLSD& notification, const LLSD& response)
-{
- LLAppViewer::instance()->forceQuit();
- return false;
-}
-
-
-void LLAppViewer::forceDisconnect(const std::string& mesg)
-{
- if (gDoDisconnect)
- {
- // Already popped up one of these dialogs, don't
- // do this again.
- return;
- }
-
- // *TODO: Translate the message if possible
- std::string big_reason = LLAgent::sTeleportErrorMessages[mesg];
- if ( big_reason.size() == 0 )
- {
- big_reason = mesg;
- }
-
- LLSD args;
- gDoDisconnect = TRUE;
-
- if (LLStartUp::getStartupState() < STATE_STARTED)
- {
- // Tell users what happened
- args["ERROR_MESSAGE"] = big_reason;
- LLNotificationsUtil::add("ErrorMessage", args, LLSD(), &finish_forced_disconnect);
- }
- else
- {
- args["MESSAGE"] = big_reason;
- LLNotificationsUtil::add("YouHaveBeenLoggedOut", args, LLSD(), &finish_disconnect );
- }
-}
-
-void LLAppViewer::badNetworkHandler()
-{
- // Dump the packet
- gMessageSystem->dumpPacketToLog();
-
- // Flush all of our caches on exit in the case of disconnect due to
- // invalid packets.
-
- mPurgeOnExit = TRUE;
-
- std::ostringstream message;
- message <<
- "The viewer has detected mangled network data indicative\n"
- "of a bad upstream network connection or an incomplete\n"
- "local installation of " << LLAppViewer::instance()->getSecondLifeTitle() << ". \n"
- " \n"
- "Try uninstalling and reinstalling to see if this resolves \n"
- "the issue. \n"
- " \n"
- "If the problem continues, see the Tech Support FAQ at: \n"
- "www.secondlife.com/support";
- forceDisconnect(message.str());
-
- LLApp::instance()->writeMiniDump();
-}
-
-// This routine may get called more than once during the shutdown process.
-// This can happen because we need to get the screenshot before the window
-// is destroyed.
-void LLAppViewer::saveFinalSnapshot()
-{
- if (!mSavedFinalSnapshot && !gNoRender)
- {
- gSavedSettings.setVector3d("FocusPosOnLogout", gAgentCamera.calcFocusPositionTargetGlobal());
- gSavedSettings.setVector3d("CameraPosOnLogout", gAgentCamera.calcCameraPositionTargetGlobal());
- gViewerWindow->setCursor(UI_CURSOR_WAIT);
- gAgentCamera.changeCameraToThirdPerson( FALSE ); // don't animate, need immediate switch
- gSavedSettings.setBOOL("ShowParcelOwners", FALSE);
- idle();
-
- std::string snap_filename = gDirUtilp->getLindenUserDir();
- snap_filename += gDirUtilp->getDirDelimiter();
- snap_filename += SCREEN_LAST_FILENAME;
- // use full pixel dimensions of viewer window (not post-scale dimensions)
- gViewerWindow->saveSnapshot(snap_filename, gViewerWindow->getWindowWidthRaw(), gViewerWindow->getWindowHeightRaw(), FALSE, TRUE);
- mSavedFinalSnapshot = TRUE;
- }
-}
-
-void LLAppViewer::loadNameCache()
-{
- // display names cache
- std::string filename =
- gDirUtilp->getExpandedFilename(LL_PATH_CACHE, "avatar_name_cache.xml");
- LL_INFOS("AvNameCache") << filename << LL_ENDL;
- llifstream name_cache_stream(filename);
- if(name_cache_stream.is_open())
- {
- LLAvatarNameCache::importFile(name_cache_stream);
- }
-
- if (!gCacheName) return;
-
- std::string name_cache;
- name_cache = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, "name.cache");
- llifstream cache_file(name_cache);
- if(cache_file.is_open())
- {
- if(gCacheName->importFile(cache_file)) return;
- }
-}
-
-void LLAppViewer::saveNameCache()
- {
- // display names cache
- std::string filename =
- gDirUtilp->getExpandedFilename(LL_PATH_CACHE, "avatar_name_cache.xml");
- llofstream name_cache_stream(filename);
- if(name_cache_stream.is_open())
- {
- LLAvatarNameCache::exportFile(name_cache_stream);
-}
-
- if (!gCacheName) return;
-
- std::string name_cache;
- name_cache = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, "name.cache");
- llofstream cache_file(name_cache);
- if(cache_file.is_open())
- {
- gCacheName->exportFile(cache_file);
- }
-}
-
-/*! @brief This class is an LLFrameTimer that can be created with
- an elapsed time that starts counting up from the given value
- rather than 0.0.
-
- Otherwise it behaves the same way as LLFrameTimer.
-*/
-class LLFrameStatsTimer : public LLFrameTimer
-{
-public:
- LLFrameStatsTimer(F64 elapsed_already = 0.0)
- : LLFrameTimer()
- {
- mStartTime -= elapsed_already;
- }
-};
-
-static LLFastTimer::DeclareTimer FTM_AUDIO_UPDATE("Update Audio");
-static LLFastTimer::DeclareTimer FTM_CLEANUP("Cleanup");
-static LLFastTimer::DeclareTimer FTM_IDLE_CB("Idle Callbacks");
-static LLFastTimer::DeclareTimer FTM_LOD_UPDATE("Update LOD");
-static LLFastTimer::DeclareTimer FTM_OBJECTLIST_UPDATE("Update Objectlist");
-static LLFastTimer::DeclareTimer FTM_REGION_UPDATE("Update Region");
-static LLFastTimer::DeclareTimer FTM_WORLD_UPDATE("Update World");
-static LLFastTimer::DeclareTimer FTM_NETWORK("Network");
-
-///////////////////////////////////////////////////////
-// idle()
-//
-// Called every time the window is not doing anything.
-// Receive packets, update statistics, and schedule a redisplay.
-///////////////////////////////////////////////////////
-void LLAppViewer::idle()
-{
- LLMemType mt_idle(LLMemType::MTYPE_IDLE);
- pingMainloopTimeout("Main:Idle");
-
- // Update frame timers
- static LLTimer idle_timer;
-
- LLFrameTimer::updateFrameTime();
- LLFrameTimer::updateFrameCount();
- LLEventTimer::updateClass();
- LLCriticalDamp::updateInterpolants();
- LLMortician::updateClass();
- F32 dt_raw = idle_timer.getElapsedTimeAndResetF32();
-
- // Cap out-of-control frame times
- // Too low because in menus, swapping, debugger, etc.
- // Too high because idle called with no objects in view, etc.
- const F32 MIN_FRAME_RATE = 1.f;
- const F32 MAX_FRAME_RATE = 200.f;
-
- F32 frame_rate_clamped = 1.f / dt_raw;
- frame_rate_clamped = llclamp(frame_rate_clamped, MIN_FRAME_RATE, MAX_FRAME_RATE);
- gFrameDTClamped = 1.f / frame_rate_clamped;
-
- // Global frame timer
- // Smoothly weight toward current frame
- gFPSClamped = (frame_rate_clamped + (4.f * gFPSClamped)) / 5.f;
-
- F32 qas = gSavedSettings.getF32("QuitAfterSeconds");
- if (qas > 0.f)
- {
- if (gRenderStartTime.getElapsedTimeF32() > qas)
- {
- LLAppViewer::instance()->forceQuit();
- }
- }
-
- // debug setting to quit after N seconds of being AFK - 0 to never do this
- F32 qas_afk = gSavedSettings.getF32("QuitAfterSecondsOfAFK");
- if (qas_afk > 0.f)
- {
- // idle time is more than setting
- if ( gAwayTriggerTimer.getElapsedTimeF32() > qas_afk )
- {
- // go ahead and just quit gracefully
- LLAppViewer::instance()->requestQuit();
- }
- }
-
- // Must wait until both have avatar object and mute list, so poll
- // here.
- request_initial_instant_messages();
-
- ///////////////////////////////////
- //
- // Special case idle if still starting up
- //
- if (LLStartUp::getStartupState() < STATE_STARTED)
- {
- // Skip rest if idle startup returns false (essentially, no world yet)
- gGLActive = TRUE;
- if (!idle_startup())
- {
- gGLActive = FALSE;
- return;
- }
- gGLActive = FALSE;
- }
-
-
- F32 yaw = 0.f; // radians
-
- if (!gDisconnected)
- {
- LLFastTimer t(FTM_NETWORK);
- // Update spaceserver timeinfo
- LLWorld::getInstance()->setSpaceTimeUSec(LLWorld::getInstance()->getSpaceTimeUSec() + (U32)(dt_raw * SEC_TO_MICROSEC));
-
-
- //////////////////////////////////////
- //
- // Update simulator agent state
- //
-
- if (gSavedSettings.getBOOL("RotateRight"))
- {
- gAgent.moveYaw(-1.f);
- }
-
- {
- LLFastTimer t(FTM_AGENT_AUTOPILOT);
- // Handle automatic walking towards points
- gAgentPilot.updateTarget();
- gAgent.autoPilot(&yaw);
- }
-
- static LLFrameTimer agent_update_timer;
- static U32 last_control_flags;
-
- // When appropriate, update agent location to the simulator.
- F32 agent_update_time = agent_update_timer.getElapsedTimeF32();
- BOOL flags_changed = gAgent.controlFlagsDirty() || (last_control_flags != gAgent.getControlFlags());
-
- if (flags_changed || (agent_update_time > (1.0f / (F32) AGENT_UPDATES_PER_SECOND)))
- {
- LLFastTimer t(FTM_AGENT_UPDATE);
- // Send avatar and camera info
- last_control_flags = gAgent.getControlFlags();
- send_agent_update(TRUE);
- agent_update_timer.reset();
- }
- }
-
- //////////////////////////////////////
- //
- // Manage statistics
- //
- //
- {
- // Initialize the viewer_stats_timer with an already elapsed time
- // of SEND_STATS_PERIOD so that the initial stats report will
- // be sent immediately.
- static LLFrameStatsTimer viewer_stats_timer(SEND_STATS_PERIOD);
- reset_statistics();
-
- // Update session stats every large chunk of time
- // *FIX: (???) SAMANTHA
- if (viewer_stats_timer.getElapsedTimeF32() >= SEND_STATS_PERIOD && !gDisconnected)
- {
- llinfos << "Transmitting sessions stats" << llendl;
- send_stats();
- viewer_stats_timer.reset();
- }
-
- // Print the object debugging stats
- static LLFrameTimer object_debug_timer;
- if (object_debug_timer.getElapsedTimeF32() > 5.f)
- {
- object_debug_timer.reset();
- if (gObjectList.mNumDeadObjectUpdates)
- {
- llinfos << "Dead object updates: " << gObjectList.mNumDeadObjectUpdates << llendl;
- gObjectList.mNumDeadObjectUpdates = 0;
- }
- if (gObjectList.mNumUnknownKills)
- {
- llinfos << "Kills on unknown objects: " << gObjectList.mNumUnknownKills << llendl;
- gObjectList.mNumUnknownKills = 0;
- }
- if (gObjectList.mNumUnknownUpdates)
- {
- llinfos << "Unknown object updates: " << gObjectList.mNumUnknownUpdates << llendl;
- gObjectList.mNumUnknownUpdates = 0;
- }
-
- // ViewerMetrics FPS piggy-backing on the debug timer.
- // The 5-second interval is nice for this purpose. If the object debug
- // bit moves or is disabled, please give this a suitable home.
- LLViewerAssetStatsFF::record_fps_main(gFPSClamped);
- }
- }
-
- if (!gDisconnected)
- {
- LLFastTimer t(FTM_NETWORK);
-
- ////////////////////////////////////////////////
- //
- // Network processing
- //
- // NOTE: Starting at this point, we may still have pointers to "dead" objects
- // floating throughout the various object lists.
- //
- idleNameCache();
-
- idleNetwork();
-
-
- // Check for away from keyboard, kick idle agents.
- idle_afk_check();
-
- // Update statistics for this frame
- update_statistics(gFrameCount);
- }
-
- ////////////////////////////////////////
- //
- // Handle the regular UI idle callbacks as well as
- // hover callbacks
- //
-
- {
-// LLFastTimer t(FTM_IDLE_CB);
-
- // Do event notifications if necessary. Yes, we may want to move this elsewhere.
- gEventNotifier.update();
-
- gIdleCallbacks.callFunctions();
- gInventory.idleNotifyObservers();
- }
-
- // Metrics logging (LLViewerAssetStats, etc.)
- {
- static LLTimer report_interval;
-
- // *TODO: Add configuration controls for this
- if (report_interval.getElapsedTimeF32() >= app_metrics_interval)
- {
- metricsSend(! gDisconnected);
- report_interval.reset();
- }
- }
-
- if (gDisconnected)
- {
- return;
- }
-
- gViewerWindow->updateUI();
-
- ///////////////////////////////////////
- // Agent and camera movement
- //
- LLCoordGL current_mouse = gViewerWindow->getCurrentMouse();
-
- {
- // After agent and camera moved, figure out if we need to
- // deselect objects.
- LLSelectMgr::getInstance()->deselectAllIfTooFar();
-
- }
-
- {
- // Handle pending gesture processing
- static LLFastTimer::DeclareTimer ftm("Agent Position");
- LLFastTimer t(ftm);
- LLGestureMgr::instance().update();
-
- gAgent.updateAgentPosition(gFrameDTClamped, yaw, current_mouse.mX, current_mouse.mY);
- }
-
- {
- LLFastTimer t(FTM_OBJECTLIST_UPDATE);
-
- if (!(logoutRequestSent() && hasSavedFinalSnapshot()))
- {
- gObjectList.update(gAgent, *LLWorld::getInstance());
- }
- }
-
- //////////////////////////////////////
- //
- // Deletes objects...
- // Has to be done after doing idleUpdates (which can kill objects)
- //
-
- {
- LLFastTimer t(FTM_CLEANUP);
- gObjectList.cleanDeadObjects();
- LLDrawable::cleanupDeadDrawables();
- }
-
- //
- // After this point, in theory we should never see a dead object
- // in the various object/drawable lists.
- //
-
- //////////////////////////////////////
- //
- // Update/send HUD effects
- //
- // At this point, HUD effects may clean up some references to
- // dead objects.
- //
-
- {
- static LLFastTimer::DeclareTimer ftm("HUD Effects");
- LLFastTimer t(ftm);
- LLSelectMgr::getInstance()->updateEffects();
- LLHUDManager::getInstance()->cleanupEffects();
- LLHUDManager::getInstance()->sendEffects();
- }
-
- ////////////////////////////////////////
- //
- // Unpack layer data that we've received
- //
-
- {
- LLFastTimer t(FTM_NETWORK);
- gVLManager.unpackData();
- }
-
- /////////////////////////
- //
- // Update surfaces, and surface textures as well.
- //
-
- LLWorld::getInstance()->updateVisibilities();
- {
- const F32 max_region_update_time = .001f; // 1ms
- LLFastTimer t(FTM_REGION_UPDATE);
- LLWorld::getInstance()->updateRegions(max_region_update_time);
- }
-
- /////////////////////////
- //
- // Update weather effects
- //
- if (!gNoRender)
- {
- LLWorld::getInstance()->updateClouds(gFrameDTClamped);
- gSky.propagateHeavenlyBodies(gFrameDTClamped); // moves sun, moon, and planets
-
- // Update wind vector
- LLVector3 wind_position_region;
- static LLVector3 average_wind;
-
- LLViewerRegion *regionp;
- regionp = LLWorld::getInstance()->resolveRegionGlobal(wind_position_region, gAgent.getPositionGlobal()); // puts agent's local coords into wind_position
- if (regionp)
- {
- gWindVec = regionp->mWind.getVelocity(wind_position_region);
-
- // Compute average wind and use to drive motion of water
-
- average_wind = regionp->mWind.getAverage();
- F32 cloud_density = regionp->mCloudLayer.getDensityRegion(wind_position_region);
-
- gSky.setCloudDensityAtAgent(cloud_density);
- gSky.setWind(average_wind);
- //LLVOWater::setWind(average_wind);
- }
- else
- {
- gWindVec.setVec(0.0f, 0.0f, 0.0f);
- }
- }
-
- //////////////////////////////////////
- //
- // Sort and cull in the new renderer are moved to pipeline.cpp
- // Here, particles are updated and drawables are moved.
- //
-
- if (!gNoRender)
- {
- LLFastTimer t(FTM_WORLD_UPDATE);
- gPipeline.updateMove();
-
- LLWorld::getInstance()->updateParticles();
- }
-
- if (LLViewerJoystick::getInstance()->getOverrideCamera())
- {
- LLViewerJoystick::getInstance()->moveFlycam();
- }
- else
- {
- if (LLToolMgr::getInstance()->inBuildMode())
- {
- LLViewerJoystick::getInstance()->moveObjects();
- }
-
- gAgentCamera.updateCamera();
- }
-
- // update media focus
- LLViewerMediaFocus::getInstance()->update();
-
- // objects and camera should be in sync, do LOD calculations now
- {
- LLFastTimer t(FTM_LOD_UPDATE);
- gObjectList.updateApparentAngles(gAgent);
- }
-
- {
- LLFastTimer t(FTM_AUDIO_UPDATE);
-
- if (gAudiop)
- {
- audio_update_volume(false);
- audio_update_listener();
- audio_update_wind(false);
-
- // this line actually commits the changes we've made to source positions, etc.
- const F32 max_audio_decode_time = 0.002f; // 2 ms decode time
- gAudiop->idle(max_audio_decode_time);
- }
- }
-
- // Handle shutdown process, for example,
- // wait for floaters to close, send quit message,
- // forcibly quit if it has taken too long
- if (mQuitRequested)
- {
- gGLActive = TRUE;
- idleShutdown();
- }
-}
-
-void LLAppViewer::idleShutdown()
-{
- // Wait for all modal alerts to get resolved
- if (LLModalDialog::activeCount() > 0)
- {
- return;
- }
-
- // close IM interface
- if(gIMMgr)
- {
- gIMMgr->disconnectAllSessions();
- }
-
- // Wait for all floaters to get resolved
- if (gFloaterView
- && !gFloaterView->allChildrenClosed())
- {
- return;
- }
-
- if (LLSideTray::getInstance()->notifyChildren(LLSD().with("request","wait_quit")))
- {
- return;
- }
-
-
-
- // ProductEngine: Try moving this code to where we shut down sTextureCache in cleanup()
- // *TODO: ugly
- static bool saved_teleport_history = false;
- if (!saved_teleport_history)
- {
- saved_teleport_history = true;
- LLTeleportHistory::getInstance()->dump();
- LLLocationHistory::getInstance()->save(); // *TODO: find a better place for doing this
- return;
- }
-
- static bool saved_snapshot = false;
- if (!saved_snapshot)
- {
- saved_snapshot = true;
- saveFinalSnapshot();
- return;
- }
-
- const F32 SHUTDOWN_UPLOAD_SAVE_TIME = 5.f;
-
- S32 pending_uploads = gAssetStorage->getNumPendingUploads();
- if (pending_uploads > 0
- && gLogoutTimer.getElapsedTimeF32() < SHUTDOWN_UPLOAD_SAVE_TIME
- && !logoutRequestSent())
- {
- static S32 total_uploads = 0;
- // Sometimes total upload count can change during logout.
- total_uploads = llmax(total_uploads, pending_uploads);
- gViewerWindow->setShowProgress(TRUE);
- S32 finished_uploads = total_uploads - pending_uploads;
- F32 percent = 100.f * finished_uploads / total_uploads;
- gViewerWindow->setProgressPercent(percent);
- gViewerWindow->setProgressString(LLTrans::getString("SavingSettings"));
- return;
- }
-
- // All floaters are closed. Tell server we want to quit.
- if( !logoutRequestSent() )
- {
- sendLogoutRequest();
-
- // Wait for a LogoutReply message
- gViewerWindow->setShowProgress(TRUE);
- gViewerWindow->setProgressPercent(100.f);
- gViewerWindow->setProgressString(LLTrans::getString("LoggingOut"));
- return;
- }
-
- // Make sure that we quit if we haven't received a reply from the server.
- if( logoutRequestSent()
- && gLogoutTimer.getElapsedTimeF32() > gLogoutMaxTime )
- {
- forceQuit();
- return;
- }
-}
-
-void LLAppViewer::sendLogoutRequest()
-{
- if(!mLogoutRequestSent)
- {
- LLMessageSystem* msg = gMessageSystem;
- msg->newMessageFast(_PREHASH_LogoutRequest);
- msg->nextBlockFast(_PREHASH_AgentData);
- msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID() );
- msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- gAgent.sendReliableMessage();
-
- gLogoutTimer.reset();
- gLogoutMaxTime = LOGOUT_REQUEST_TIME;
- mLogoutRequestSent = TRUE;
-
- if(LLVoiceClient::instanceExists())
- {
- LLVoiceClient::getInstance()->leaveChannel();
- }
-
- //Set internal status variables and marker files
- gLogoutInProgress = TRUE;
- mLogoutMarkerFileName = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,LOGOUT_MARKER_FILE_NAME);
-
- LLAPRFile outfile ;
- outfile.open(mLogoutMarkerFileName, LL_APR_W);
- mLogoutMarkerFile = outfile.getFileHandle() ;
- if (mLogoutMarkerFile)
- {
- llinfos << "Created logout marker file " << mLogoutMarkerFileName << llendl;
- apr_file_close(mLogoutMarkerFile);
- }
- else
- {
- llwarns << "Cannot create logout marker file " << mLogoutMarkerFileName << llendl;
- }
- }
-}
-
-void LLAppViewer::idleNameCache()
-{
- // Neither old nor new name cache can function before agent has a region
- LLViewerRegion* region = gAgent.getRegion();
- if (!region) return;
-
- // deal with any queued name requests and replies.
- gCacheName->processPending();
-
- // Can't run the new cache until we have the list of capabilities
- // for the agent region, and can therefore decide whether to use
- // display names or fall back to the old name system.
- if (!region->capabilitiesReceived()) return;
-
- // Agent may have moved to a different region, so need to update cap URL
- // for name lookups. Can't do this in the cap grant code, as caps are
- // granted to neighbor regions before the main agent gets there. Can't
- // do it in the move-into-region code because cap not guaranteed to be
- // granted yet, for example on teleport.
- bool had_capability = LLAvatarNameCache::hasNameLookupURL();
- std::string name_lookup_url;
- name_lookup_url.reserve(128); // avoid a memory allocation below
- name_lookup_url = region->getCapability("GetDisplayNames");
- bool have_capability = !name_lookup_url.empty();
- if (have_capability)
- {
- // we have support for display names, use it
- U32 url_size = name_lookup_url.size();
- // capabilities require URLs with slashes before query params:
- // https://<host>:<port>/cap/<uuid>/?ids=<blah>
- // but the caps are granted like:
- // https://<host>:<port>/cap/<uuid>
- if (url_size > 0 && name_lookup_url[url_size-1] != '/')
- {
- name_lookup_url += '/';
- }
- LLAvatarNameCache::setNameLookupURL(name_lookup_url);
- }
- else
- {
- // Display names not available on this region
- LLAvatarNameCache::setNameLookupURL( std::string() );
- }
-
- // Error recovery - did we change state?
- if (had_capability != have_capability)
- {
- // name tags are persistant on screen, so make sure they refresh
- LLVOAvatar::invalidateNameTags();
- }
-
- LLAvatarNameCache::idle();
-}
-
-//
-// Handle messages, and all message related stuff
-//
-
-#define TIME_THROTTLE_MESSAGES
-
-#ifdef TIME_THROTTLE_MESSAGES
-#define CHECK_MESSAGES_DEFAULT_MAX_TIME .020f // 50 ms = 50 fps (just for messages!)
-static F32 CheckMessagesMaxTime = CHECK_MESSAGES_DEFAULT_MAX_TIME;
-#endif
-
-static LLFastTimer::DeclareTimer FTM_IDLE_NETWORK("Idle Network");
-
-void LLAppViewer::idleNetwork()
-{
- LLMemType mt_in(LLMemType::MTYPE_IDLE_NETWORK);
- pingMainloopTimeout("idleNetwork");
-
- gObjectList.mNumNewObjects = 0;
- S32 total_decoded = 0;
-
- if (!gSavedSettings.getBOOL("SpeedTest"))
- {
- LLFastTimer t(FTM_IDLE_NETWORK); // decode
-
- LLTimer check_message_timer;
- // Read all available packets from network
- const S64 frame_count = gFrameCount; // U32->S64
- F32 total_time = 0.0f;
-
- while (gMessageSystem->checkAllMessages(frame_count, gServicePump))
- {
- if (gDoDisconnect)
- {
- // We're disconnecting, don't process any more messages from the server
- // We're usually disconnecting due to either network corruption or a
- // server going down, so this is OK.
- break;
- }
-
- total_decoded++;
- gPacketsIn++;
-
- if (total_decoded > MESSAGE_MAX_PER_FRAME)
- {
- break;
- }
-
-#ifdef TIME_THROTTLE_MESSAGES
- // Prevent slow packets from completely destroying the frame rate.
- // This usually happens due to clumps of avatars taking huge amount
- // of network processing time (which needs to be fixed, but this is
- // a good limit anyway).
- total_time = check_message_timer.getElapsedTimeF32();
- if (total_time >= CheckMessagesMaxTime)
- break;
-#endif
- }
-
- // Handle per-frame message system processing.
- gMessageSystem->processAcks();
-
-#ifdef TIME_THROTTLE_MESSAGES
- if (total_time >= CheckMessagesMaxTime)
- {
- // Increase CheckMessagesMaxTime so that we will eventually catch up
- CheckMessagesMaxTime *= 1.035f; // 3.5% ~= x2 in 20 frames, ~8x in 60 frames
- }
- else
- {
- // Reset CheckMessagesMaxTime to default value
- CheckMessagesMaxTime = CHECK_MESSAGES_DEFAULT_MAX_TIME;
- }
-#endif
-
-
-
- // we want to clear the control after sending out all necessary agent updates
- gAgent.resetControlFlags();
-
- // Decode enqueued messages...
- S32 remaining_possible_decodes = MESSAGE_MAX_PER_FRAME - total_decoded;
-
- if( remaining_possible_decodes <= 0 )
- {
- llinfos << "Maxed out number of messages per frame at " << MESSAGE_MAX_PER_FRAME << llendl;
- }
-
- if (gPrintMessagesThisFrame)
- {
- llinfos << "Decoded " << total_decoded << " msgs this frame!" << llendl;
- gPrintMessagesThisFrame = FALSE;
- }
- }
- LLViewerStats::getInstance()->mNumNewObjectsStat.addValue(gObjectList.mNumNewObjects);
-
- // Retransmit unacknowledged packets.
- gXferManager->retransmitUnackedPackets();
- gAssetStorage->checkForTimeouts();
- gViewerThrottle.updateDynamicThrottle();
-
- // Check that the circuit between the viewer and the agent's current
- // region is still alive
- LLViewerRegion *agent_region = gAgent.getRegion();
- if (agent_region && (LLStartUp::getStartupState()==STATE_STARTED))
- {
- LLUUID this_region_id = agent_region->getRegionID();
- bool this_region_alive = agent_region->isAlive();
- if ((mAgentRegionLastAlive && !this_region_alive) // newly dead
- && (mAgentRegionLastID == this_region_id)) // same region
- {
- forceDisconnect(LLTrans::getString("AgentLostConnection"));
- }
- mAgentRegionLastID = this_region_id;
- mAgentRegionLastAlive = this_region_alive;
- }
-}
-
-void LLAppViewer::disconnectViewer()
-{
- if (gDisconnected)
- {
- return;
- }
- //
- // Cleanup after quitting.
- //
- // Save snapshot for next time, if we made it through initialization
-
- llinfos << "Disconnecting viewer!" << llendl;
-
- // Dump our frame statistics
-
- // Remember if we were flying
- gSavedSettings.setBOOL("FlyingAtExit", gAgent.getFlying() );
-
- // Un-minimize all windows so they don't get saved minimized
- if (!gNoRender)
- {
- if (gFloaterView)
- {
- gFloaterView->restoreAll();
- }
- }
-
- if (LLSelectMgr::getInstance())
- {
- LLSelectMgr::getInstance()->deselectAll();
- }
-
- // save inventory if appropriate
- gInventory.cache(gInventory.getRootFolderID(), gAgent.getID());
- if (gInventory.getLibraryRootFolderID().notNull()
- && gInventory.getLibraryOwnerID().notNull())
- {
- gInventory.cache(
- gInventory.getLibraryRootFolderID(),
- gInventory.getLibraryOwnerID());
- }
-
- saveNameCache();
-
- // close inventory interface, close all windows
- LLFloaterInventory::cleanup();
-
- gAgentWearables.cleanup();
- gAgentCamera.cleanup();
- // Also writes cached agent settings to gSavedSettings
- gAgent.cleanup();
-
- // This is where we used to call gObjectList.destroy() and then delete gWorldp.
- // Now we just ask the LLWorld singleton to cleanly shut down.
- if(LLWorld::instanceExists())
- {
- LLWorld::getInstance()->destroyClass();
- }
-
- // call all self-registered classes
- LLDestroyClassList::instance().fireCallbacks();
-
- cleanup_xfer_manager();
- gDisconnected = TRUE;
-
- // Pass the connection state to LLUrlEntryParcel not to attempt
- // parcel info requests while disconnected.
- LLUrlEntryParcel::setDisconnected(gDisconnected);
-}
-
-void LLAppViewer::forceErrorLLError()
-{
- llerrs << "This is an llerror" << llendl;
-}
-
-void LLAppViewer::forceErrorBreakpoint()
-{
-#ifdef LL_WINDOWS
- DebugBreak();
-#endif
- return;
-}
-
-void LLAppViewer::forceErrorBadMemoryAccess()
-{
- S32* crash = NULL;
- *crash = 0xDEADBEEF;
- return;
-}
-
-void LLAppViewer::forceErrorInfiniteLoop()
-{
- while(true)
- {
- ;
- }
- return;
-}
-
-void LLAppViewer::forceErrorSoftwareException()
-{
- // *FIX: Any way to insure it won't be handled?
- throw;
-}
-
-void LLAppViewer::forceErrorDriverCrash()
-{
- glDeleteTextures(1, NULL);
-}
-
-void LLAppViewer::initMainloopTimeout(const std::string& state, F32 secs)
-{
- if(!mMainloopTimeout)
- {
- mMainloopTimeout = new LLWatchdogTimeout();
- resumeMainloopTimeout(state, secs);
- }
-}
-
-void LLAppViewer::destroyMainloopTimeout()
-{
- if(mMainloopTimeout)
- {
- delete mMainloopTimeout;
- mMainloopTimeout = NULL;
- }
-}
-
-void LLAppViewer::resumeMainloopTimeout(const std::string& state, F32 secs)
-{
- if(mMainloopTimeout)
- {
- if(secs < 0.0f)
- {
- secs = gSavedSettings.getF32("MainloopTimeoutDefault");
- }
-
- mMainloopTimeout->setTimeout(secs);
- mMainloopTimeout->start(state);
- }
-}
-
-void LLAppViewer::pauseMainloopTimeout()
-{
- if(mMainloopTimeout)
- {
- mMainloopTimeout->stop();
- }
-}
-
-void LLAppViewer::pingMainloopTimeout(const std::string& state, F32 secs)
-{
-// if(!restoreErrorTrap())
-// {
-// llwarns << "!!!!!!!!!!!!! Its an error trap!!!!" << state << llendl;
-// }
-
- if(mMainloopTimeout)
- {
- if(secs < 0.0f)
- {
- secs = gSavedSettings.getF32("MainloopTimeoutDefault");
- }
-
- mMainloopTimeout->setTimeout(secs);
- mMainloopTimeout->ping(state);
- }
-}
-
-void LLAppViewer::handleLoginComplete()
-{
- gLoggedInTime.start();
- initMainloopTimeout("Mainloop Init");
-
- // Store some data to DebugInfo in case of a freeze.
- gDebugInfo["ClientInfo"]["Name"] = LLVersionInfo::getChannel();
-
- gDebugInfo["ClientInfo"]["MajorVersion"] = LLVersionInfo::getMajor();
- gDebugInfo["ClientInfo"]["MinorVersion"] = LLVersionInfo::getMinor();
- gDebugInfo["ClientInfo"]["PatchVersion"] = LLVersionInfo::getPatch();
- gDebugInfo["ClientInfo"]["BuildVersion"] = LLVersionInfo::getBuild();
-
- LLParcel* parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
- if ( parcel && parcel->getMusicURL()[0])
- {
- gDebugInfo["ParcelMusicURL"] = parcel->getMusicURL();
- }
- if ( parcel && parcel->getMediaURL()[0])
- {
- gDebugInfo["ParcelMediaURL"] = parcel->getMediaURL();
- }
-
- gDebugInfo["SettingsFilename"] = gSavedSettings.getString("ClientSettingsFile");
- gDebugInfo["CAFilename"] = gDirUtilp->getCAFile();
- gDebugInfo["ViewerExePath"] = gDirUtilp->getExecutablePathAndName();
- gDebugInfo["CurrentPath"] = gDirUtilp->getCurPath();
-
- if(gAgent.getRegion())
- {
- gDebugInfo["CurrentSimHost"] = gAgent.getRegionHost().getHostName();
- gDebugInfo["CurrentRegion"] = gAgent.getRegion()->getName();
- }
-
- if(LLAppViewer::instance()->mMainloopTimeout)
- {
- gDebugInfo["MainloopTimeoutState"] = LLAppViewer::instance()->mMainloopTimeout->getState();
- }
-
- mOnLoginCompleted();
-
- writeDebugInfo();
-}
-
-// *TODO - generalize this and move DSO wrangling to a helper class -brad
-void LLAppViewer::loadEventHostModule(S32 listen_port)
-{
- std::string dso_name =
-#if LL_WINDOWS
- "lleventhost.dll";
-#elif LL_DARWIN
- "liblleventhost.dylib";
-#else
- "liblleventhost.so";
-#endif
-
- std::string dso_path = gDirUtilp->findFile(dso_name,
- gDirUtilp->getAppRODataDir(),
- gDirUtilp->getExecutableDir());
-
- if(dso_path == "")
- {
- llerrs << "QAModeEventHost requested but module \"" << dso_name << "\" not found!" << llendl;
- return;
- }
-
- LL_INFOS("eventhost") << "Found lleventhost at '" << dso_path << "'" << LL_ENDL;
-#if ! defined(LL_WINDOWS)
- {
- std::string outfile("/tmp/lleventhost.file.out");
- std::string command("file '" + dso_path + "' > '" + outfile + "' 2>&1");
- int rc = system(command.c_str());
- if (rc != 0)
- {
- LL_WARNS("eventhost") << command << " ==> " << rc << ':' << LL_ENDL;
- }
- else
- {
- LL_INFOS("eventhost") << command << ':' << LL_ENDL;
- }
- {
- std::ifstream reader(outfile.c_str());
- std::string line;
- while (std::getline(reader, line))
- {
- size_t len = line.length();
- if (len && line[len-1] == '\n')
- line.erase(len-1);
- LL_INFOS("eventhost") << line << LL_ENDL;
- }
- }
- remove(outfile.c_str());
- }
-#endif // LL_WINDOWS
-
- apr_dso_handle_t * eventhost_dso_handle = NULL;
- apr_pool_t * eventhost_dso_memory_pool = NULL;
-
- //attempt to load the shared library
- apr_pool_create(&eventhost_dso_memory_pool, NULL);
- apr_status_t rv = apr_dso_load(&eventhost_dso_handle,
- dso_path.c_str(),
- eventhost_dso_memory_pool);
- llassert_always(! ll_apr_warn_status(rv, eventhost_dso_handle));
- llassert_always(eventhost_dso_handle != NULL);
-
- int (*ll_plugin_start_func)(LLSD const &) = NULL;
- rv = apr_dso_sym((apr_dso_handle_sym_t*)&ll_plugin_start_func, eventhost_dso_handle, "ll_plugin_start");
-
- llassert_always(! ll_apr_warn_status(rv, eventhost_dso_handle));
- llassert_always(ll_plugin_start_func != NULL);
-
- LLSD args;
- args["listen_port"] = listen_port;
-
- int status = ll_plugin_start_func(args);
-
- if(status != 0)
- {
- llerrs << "problem loading eventhost plugin, status: " << status << llendl;
- }
-
- mPlugins.insert(eventhost_dso_handle);
-}
-
-void LLAppViewer::launchUpdater()
-{
- LLSD query_map = LLSD::emptyMap();
- // *TODO place os string in a global constant
-#if LL_WINDOWS
- query_map["os"] = "win";
-#elif LL_DARWIN
- query_map["os"] = "mac";
-#elif LL_LINUX
- query_map["os"] = "lnx";
-#elif LL_SOLARIS
- query_map["os"] = "sol";
-#endif
- // *TODO change userserver to be grid on both viewer and sim, since
- // userserver no longer exists.
- query_map["userserver"] = LLGridManager::getInstance()->getGridLabel();
- query_map["channel"] = LLVersionInfo::getChannel();
- // *TODO constantize this guy
- // *NOTE: This URL is also used in win_setup/lldownloader.cpp
- LLURI update_url = LLURI::buildHTTP("secondlife.com", 80, "update.php", query_map);
-
- if(LLAppViewer::sUpdaterInfo)
- {
- delete LLAppViewer::sUpdaterInfo;
- }
- LLAppViewer::sUpdaterInfo = new LLAppViewer::LLUpdaterInfo() ;
-
- // if a sim name was passed in via command line parameter (typically through a SLURL)
- if ( LLStartUp::getStartSLURL().getType() == LLSLURL::LOCATION )
- {
- // record the location to start at next time
- gSavedSettings.setString( "NextLoginLocation", LLStartUp::getStartSLURL().getSLURLString());
- };
-
-#if LL_WINDOWS
- LLAppViewer::sUpdaterInfo->mUpdateExePath = gDirUtilp->getTempFilename();
- if (LLAppViewer::sUpdaterInfo->mUpdateExePath.empty())
- {
- delete LLAppViewer::sUpdaterInfo ;
- LLAppViewer::sUpdaterInfo = NULL ;
-
- // We're hosed, bail
- LL_WARNS("AppInit") << "LLDir::getTempFilename() failed" << LL_ENDL;
- return;
- }
-
- LLAppViewer::sUpdaterInfo->mUpdateExePath += ".exe";
-
- std::string updater_source = gDirUtilp->getAppRODataDir();
- updater_source += gDirUtilp->getDirDelimiter();
- updater_source += "updater.exe";
-
- LL_DEBUGS("AppInit") << "Calling CopyFile source: " << updater_source
- << " dest: " << LLAppViewer::sUpdaterInfo->mUpdateExePath
- << LL_ENDL;
-
-
- if (!CopyFileA(updater_source.c_str(), LLAppViewer::sUpdaterInfo->mUpdateExePath.c_str(), FALSE))
- {
- delete LLAppViewer::sUpdaterInfo ;
- LLAppViewer::sUpdaterInfo = NULL ;
-
- LL_WARNS("AppInit") << "Unable to copy the updater!" << LL_ENDL;
-
- return;
- }
-
- LLAppViewer::sUpdaterInfo->mParams << "-url \"" << update_url.asString() << "\"";
-
- LL_DEBUGS("AppInit") << "Calling updater: " << LLAppViewer::sUpdaterInfo->mUpdateExePath << " " << LLAppViewer::sUpdaterInfo->mParams.str() << LL_ENDL;
-
- //Explicitly remove the marker file, otherwise we pass the lock onto the child process and things get weird.
- LLAppViewer::instance()->removeMarkerFile(); // In case updater fails
-
- // *NOTE:Mani The updater is spawned as the last thing before the WinMain exit.
- // see LLAppViewerWin32.cpp
-
-#elif LL_DARWIN
- LLAppViewer::sUpdaterInfo->mUpdateExePath = "'";
- LLAppViewer::sUpdaterInfo->mUpdateExePath += gDirUtilp->getAppRODataDir();
- LLAppViewer::sUpdaterInfo->mUpdateExePath += "/mac-updater.app/Contents/MacOS/mac-updater' -url \"";
- LLAppViewer::sUpdaterInfo->mUpdateExePath += update_url.asString();
- LLAppViewer::sUpdaterInfo->mUpdateExePath += "\" -name \"";
- LLAppViewer::sUpdaterInfo->mUpdateExePath += LLAppViewer::instance()->getSecondLifeTitle();
- LLAppViewer::sUpdaterInfo->mUpdateExePath += "\" -bundleid \"";
- LLAppViewer::sUpdaterInfo->mUpdateExePath += LL_VERSION_BUNDLE_ID;
- LLAppViewer::sUpdaterInfo->mUpdateExePath += "\" &";
-
- LL_DEBUGS("AppInit") << "Calling updater: " << LLAppViewer::sUpdaterInfo->mUpdateExePath << LL_ENDL;
-
- // Run the auto-updater.
- system(LLAppViewer::sUpdaterInfo->mUpdateExePath.c_str()); /* Flawfinder: ignore */
-
-#elif (LL_LINUX || LL_SOLARIS) && LL_GTK
- // we tell the updater where to find the xml containing string
- // translations which it can use for its own UI
- std::string xml_strings_file = "strings.xml";
- std::vector<std::string> xui_path_vec = LLUI::getXUIPaths();
- std::string xml_search_paths;
- std::vector<std::string>::const_iterator iter;
- // build comma-delimited list of xml paths to pass to updater
- for (iter = xui_path_vec.begin(); iter != xui_path_vec.end(); )
- {
- std::string this_skin_dir = gDirUtilp->getDefaultSkinDir()
- + gDirUtilp->getDirDelimiter()
- + (*iter);
- llinfos << "Got a XUI path: " << this_skin_dir << llendl;
- xml_search_paths.append(this_skin_dir);
- ++iter;
- if (iter != xui_path_vec.end())
- xml_search_paths.append(","); // comma-delimit
- }
- // build the overall command-line to run the updater correctly
- LLAppViewer::sUpdaterInfo->mUpdateExePath =
- gDirUtilp->getExecutableDir() + "/" + "linux-updater.bin" +
- " --url \"" + update_url.asString() + "\"" +
- " --name \"" + LLAppViewer::instance()->getSecondLifeTitle() + "\"" +
- " --dest \"" + gDirUtilp->getAppRODataDir() + "\"" +
- " --stringsdir \"" + xml_search_paths + "\"" +
- " --stringsfile \"" + xml_strings_file + "\"";
-
- LL_INFOS("AppInit") << "Calling updater: "
- << LLAppViewer::sUpdaterInfo->mUpdateExePath << LL_ENDL;
-
- // *TODO: we could use the gdk equivalent to ensure the updater
- // gets started on the same screen.
- GError *error = NULL;
- if (!g_spawn_command_line_async(LLAppViewer::sUpdaterInfo->mUpdateExePath.c_str(), &error))
- {
- llerrs << "Failed to launch updater: "
- << error->message
- << llendl;
- }
- if (error) {
- g_error_free(error);
- }
-#else
- OSMessageBox(LLTrans::getString("MBNoAutoUpdate"), LLStringUtil::null, OSMB_OK);
-#endif
-
- // *REMOVE:Mani - Saving for reference...
- // LLAppViewer::instance()->forceQuit();
-}
-
-
-//virtual
-void LLAppViewer::setMasterSystemAudioMute(bool mute)
-{
- gSavedSettings.setBOOL("MuteAudio", mute);
-}
-
-//virtual
-bool LLAppViewer::getMasterSystemAudioMute()
-{
- return gSavedSettings.getBOOL("MuteAudio");
-}
-
-//----------------------------------------------------------------------------
-// Metrics-related methods (static and otherwise)
-//----------------------------------------------------------------------------
-
-/**
- * LLViewerAssetStats collects data on a per-region (as defined by the agent's
- * location) so we need to tell it about region changes which become a kind of
- * hidden variable/global state in the collectors. For collectors not running
- * on the main thread, we need to send a message to move the data over safely
- * and cheaply (amortized over a run).
- */
-void LLAppViewer::metricsUpdateRegion(U64 region_handle)
-{
- if (0 != region_handle)
- {
- LLViewerAssetStatsFF::set_region_main(region_handle);
- if (LLAppViewer::sTextureFetch)
- {
- // Send a region update message into 'thread1' to get the new region.
- LLAppViewer::sTextureFetch->commandSetRegion(region_handle);
- }
- else
- {
- // No 'thread1', a.k.a. TextureFetch, so update directly
- LLViewerAssetStatsFF::set_region_thread1(region_handle);
- }
- }
-}
-
-
-/**
- * Attempts to start a multi-threaded metrics report to be sent back to
- * the grid for consumption.
- */
-void LLAppViewer::metricsSend(bool enable_reporting)
-{
- if (! gViewerAssetStatsMain)
- return;
-
- if (LLAppViewer::sTextureFetch)
- {
- LLViewerRegion * regionp = gAgent.getRegion();
-
- if (enable_reporting && regionp)
- {
- std::string caps_url = regionp->getCapability("ViewerMetrics");
-
- // Make a copy of the main stats to send into another thread.
- // Receiving thread takes ownership.
- LLViewerAssetStats * main_stats(new LLViewerAssetStats(*gViewerAssetStatsMain));
-
- // Send a report request into 'thread1' to get the rest of the data
- // and provide some additional parameters while here.
- LLAppViewer::sTextureFetch->commandSendMetrics(caps_url,
- gAgentSessionID,
- gAgentID,
- main_stats);
- main_stats = 0; // Ownership transferred
- }
- else
- {
- LLAppViewer::sTextureFetch->commandDataBreak();
- }
- }
-
- // Reset even if we can't report. Rather than gather up a huge chunk of
- // data, we'll keep to our sampling interval and retain the data
- // resolution in time.
- gViewerAssetStatsMain->reset();
-}
-
+ /**
+ * @file llappviewer.cpp
+ * @brief The LLAppViewer class definitions
+ *
+ * $LicenseInfo:firstyear=2007&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h"
+
+#include "llappviewer.h"
+
+// Viewer includes
+#include "llversioninfo.h"
+#include "llversionviewer.h"
+#include "llfeaturemanager.h"
+#include "lluictrlfactory.h"
+#include "lltexteditor.h"
+#include "llerrorcontrol.h"
+#include "lleventtimer.h"
+#include "llviewertexturelist.h"
+#include "llgroupmgr.h"
+#include "llagent.h"
+#include "llagentcamera.h"
+#include "llagentlanguage.h"
+#include "llagentwearables.h"
+#include "llwindow.h"
+#include "llviewerstats.h"
+#include "llviewerstatsrecorder.h"
+#include "llmd5.h"
+#include "llmeshrepository.h"
+#include "llpumpio.h"
+#include "llmimetypes.h"
+#include "llslurl.h"
+#include "llstartup.h"
+#include "llfocusmgr.h"
+#include "llviewerjoystick.h"
+#include "llallocator.h"
+#include "llares.h"
+#include "llcurl.h"
+#include "lltexturestats.h"
+#include "lltexturestats.h"
+#include "llviewerwindow.h"
+#include "llviewerdisplay.h"
+#include "llviewermedia.h"
+#include "llviewerparcelmedia.h"
+#include "llviewermediafocus.h"
+#include "llviewermessage.h"
+#include "llviewerobjectlist.h"
+#include "llworldmap.h"
+#include "llmutelist.h"
+#include "llviewerhelp.h"
+#include "lluicolortable.h"
+#include "llurldispatcher.h"
+#include "llurlhistory.h"
+//#include "llfirstuse.h"
+#include "llrender.h"
+#include "llteleporthistory.h"
+#include "lllocationhistory.h"
+#include "llfasttimerview.h"
+#include "llvector4a.h"
+#include "llviewermenufile.h"
+#include "llvoicechannel.h"
+#include "llvoavatarself.h"
+#include "llsidetray.h"
+#include "llfeaturemanager.h"
+#include "llurlmatch.h"
+#include "lltextutil.h"
+#include "lllogininstance.h"
+#include "llprogressview.h"
+
+#include "llweb.h"
+#include "llsecondlifeurls.h"
+#include "llupdaterservice.h"
+
+// Linden library includes
+#include "llavatarnamecache.h"
+#include "llimagej2c.h"
+#include "llmemory.h"
+#include "llprimitive.h"
+#include "llurlaction.h"
+#include "llurlentry.h"
+#include "llvfile.h"
+#include "llvfsthread.h"
+#include "llvolumemgr.h"
+#include "llxfermanager.h"
+
+#include "llnotificationmanager.h"
+#include "llnotifications.h"
+#include "llnotificationsutil.h"
+
+// Third party library includes
+#include <boost/bind.hpp>
+
+
+#if LL_WINDOWS
+# include <share.h> // For _SH_DENYWR in initMarkerFile
+#else
+# include <sys/file.h> // For initMarkerFile support
+#endif
+
+#include "llapr.h"
+#include "apr_dso.h"
+#include <boost/lexical_cast.hpp>
+
+#include "llviewerkeyboard.h"
+#include "lllfsthread.h"
+#include "llworkerthread.h"
+#include "lltexturecache.h"
+#include "lltexturefetch.h"
+#include "llimageworker.h"
+#include "llevents.h"
+
+// The files below handle dependencies from cleanup.
+#include "llkeyframemotion.h"
+#include "llworldmap.h"
+#include "llhudmanager.h"
+#include "lltoolmgr.h"
+#include "llassetstorage.h"
+#include "llpolymesh.h"
+#include "llcachename.h"
+#include "llaudioengine.h"
+#include "llstreamingaudio.h"
+#include "llviewermenu.h"
+#include "llselectmgr.h"
+#include "lltrans.h"
+#include "lltransutil.h"
+#include "lltracker.h"
+#include "llviewerparcelmgr.h"
+#include "llworldmapview.h"
+#include "llpostprocess.h"
+#include "llwlparammanager.h"
+#include "llwaterparammanager.h"
+
+#include "lldebugview.h"
+#include "llconsole.h"
+#include "llcontainerview.h"
+#include "lltooltip.h"
+
+#include "llsdserialize.h"
+
+#include "llworld.h"
+#include "llhudeffecttrail.h"
+#include "llvectorperfoptions.h"
+#include "llslurl.h"
+#include "llwatchdog.h"
+
+// Included so that constants/settings might be initialized
+// in save_settings_to_globals()
+#include "llbutton.h"
+#include "llstatusbar.h"
+#include "llsurface.h"
+#include "llvosky.h"
+#include "llvotree.h"
+#include "llvoavatar.h"
+#include "llfolderview.h"
+#include "llagentpilot.h"
+#include "llvovolume.h"
+#include "llflexibleobject.h"
+#include "llvosurfacepatch.h"
+#include "llviewerfloaterreg.h"
+#include "llcommandlineparser.h"
+#include "llfloatermemleak.h"
+#include "llfloaterreg.h"
+#include "llfloatersnapshot.h"
+#include "llfloaterinventory.h"
+
+// includes for idle() idleShutdown()
+#include "llviewercontrol.h"
+#include "lleventnotifier.h"
+#include "llcallbacklist.h"
+#include "pipeline.h"
+#include "llgesturemgr.h"
+#include "llsky.h"
+#include "llvlmanager.h"
+#include "llviewercamera.h"
+#include "lldrawpoolbump.h"
+#include "llvieweraudio.h"
+#include "llimview.h"
+#include "llviewerthrottle.h"
+#include "llparcel.h"
+#include "llavatariconctrl.h"
+#include "llgroupiconctrl.h"
+#include "llviewerassetstats.h"
+
+// Include for security api initialization
+#include "llsecapi.h"
+#include "llmachineid.h"
+#include "llmainlooprepeater.h"
+
+// *FIX: These extern globals should be cleaned up.
+// The globals either represent state/config/resource-storage of either
+// this app, or another 'component' of the viewer. App globals should be
+// moved into the app class, where as the other globals should be
+// moved out of here.
+// If a global symbol reference seems valid, it will be included
+// via header files above.
+
+//----------------------------------------------------------------------------
+// llviewernetwork.h
+#include "llviewernetwork.h"
+// define a self-registering event API object
+#include "llappviewerlistener.h"
+
+#if (LL_LINUX || LL_SOLARIS) && LL_GTK
+#include "glib.h"
+#endif // (LL_LINUX || LL_SOLARIS) && LL_GTK
+
+#if LL_MSVC
+// disable boost::lexical_cast warning
+#pragma warning (disable:4702)
+#endif
+
+static LLAppViewerListener sAppViewerListener(LLAppViewer::instance);
+
+////// Windows-specific includes to the bottom - nasty defines in these pollute the preprocessor
+//
+//----------------------------------------------------------------------------
+// viewer.cpp - these are only used in viewer, should be easily moved.
+
+#if LL_DARWIN
+extern void init_apple_menu(const char* product);
+#endif // LL_DARWIN
+
+extern BOOL gRandomizeFramerate;
+extern BOOL gPeriodicSlowFrame;
+extern BOOL gDebugGL;
+
+////////////////////////////////////////////////////////////
+// All from the last globals push...
+const F32 DEFAULT_AFK_TIMEOUT = 5.f * 60.f; // time with no input before user flagged as Away From Keyboard
+
+F32 gSimLastTime; // Used in LLAppViewer::init and send_stats()
+F32 gSimFrames;
+
+BOOL gShowObjectUpdates = FALSE;
+BOOL gUseQuickTime = TRUE;
+
+eLastExecEvent gLastExecEvent = LAST_EXEC_NORMAL;
+
+LLSD gDebugInfo;
+
+U32 gFrameCount = 0;
+U32 gForegroundFrameCount = 0; // number of frames that app window was in foreground
+LLPumpIO* gServicePump = NULL;
+
+U64 gFrameTime = 0;
+F32 gFrameTimeSeconds = 0.f;
+F32 gFrameIntervalSeconds = 0.f;
+F32 gFPSClamped = 10.f; // Pretend we start at target rate.
+F32 gFrameDTClamped = 0.f; // Time between adjacent checks to network for packets
+U64 gStartTime = 0; // gStartTime is "private", used only to calculate gFrameTimeSeconds
+U32 gFrameStalls = 0;
+const F64 FRAME_STALL_THRESHOLD = 1.0;
+
+LLTimer gRenderStartTime;
+LLFrameTimer gForegroundTime;
+LLFrameTimer gLoggedInTime;
+LLTimer gLogoutTimer;
+static const F32 LOGOUT_REQUEST_TIME = 6.f; // this will be cut short by the LogoutReply msg.
+F32 gLogoutMaxTime = LOGOUT_REQUEST_TIME;
+
+BOOL gDisconnected = FALSE;
+
+// used to restore texture state after a mode switch
+LLFrameTimer gRestoreGLTimer;
+BOOL gRestoreGL = FALSE;
+BOOL gUseWireframe = FALSE;
+
+// VFS globals - see llappviewer.h
+LLVFS* gStaticVFS = NULL;
+
+LLMemoryInfo gSysMemory;
+U64 gMemoryAllocated = 0; // updated in display_stats() in llviewerdisplay.cpp
+
+std::string gLastVersionChannel;
+
+LLVector3 gWindVec(3.0, 3.0, 0.0);
+LLVector3 gRelativeWindVec(0.0, 0.0, 0.0);
+
+U32 gPacketsIn = 0;
+
+BOOL gPrintMessagesThisFrame = FALSE;
+
+BOOL gRandomizeFramerate = FALSE;
+BOOL gPeriodicSlowFrame = FALSE;
+
+BOOL gCrashOnStartup = FALSE;
+BOOL gLLErrorActivated = FALSE;
+BOOL gLogoutInProgress = FALSE;
+
+////////////////////////////////////////////////////////////
+// Internal globals... that should be removed.
+static std::string gArgs = "Mesh Beta";
+
+const std::string MARKER_FILE_NAME("SecondLife.exec_marker");
+const std::string ERROR_MARKER_FILE_NAME("SecondLife.error_marker");
+const std::string LLERROR_MARKER_FILE_NAME("SecondLife.llerror_marker");
+const std::string LOGOUT_MARKER_FILE_NAME("SecondLife.logout_marker");
+static BOOL gDoDisconnect = FALSE;
+static std::string gLaunchFileOnQuit;
+
+// Used on Win32 for other apps to identify our window (eg, win_setup)
+const char* const VIEWER_WINDOW_CLASSNAME = "Second Life";
+
+//----------------------------------------------------------------------------
+
+// List of entries from strings.xml to always replace
+static std::set<std::string> default_trans_args;
+void init_default_trans_args()
+{
+ default_trans_args.insert("SECOND_LIFE"); // World
+ default_trans_args.insert("APP_NAME");
+ default_trans_args.insert("CAPITALIZED_APP_NAME");
+ default_trans_args.insert("SECOND_LIFE_GRID");
+ default_trans_args.insert("SUPPORT_SITE");
+}
+
+//----------------------------------------------------------------------------
+// File scope definitons
+const char *VFS_DATA_FILE_BASE = "data.db2.x.";
+const char *VFS_INDEX_FILE_BASE = "index.db2.x.";
+
+
+struct SettingsFile : public LLInitParam::Block<SettingsFile>
+{
+ Mandatory<std::string> name;
+ Optional<std::string> file_name;
+ Optional<bool> required,
+ persistent;
+ Optional<std::string> file_name_setting;
+
+ SettingsFile()
+ : name("name"),
+ file_name("file_name"),
+ required("required", false),
+ persistent("persistent", true),
+ file_name_setting("file_name_setting")
+ {}
+};
+
+struct SettingsGroup : public LLInitParam::Block<SettingsGroup>
+{
+ Mandatory<std::string> name;
+ Mandatory<S32> path_index;
+ Multiple<SettingsFile> files;
+
+ SettingsGroup()
+ : name("name"),
+ path_index("path_index"),
+ files("file")
+ {}
+};
+
+struct SettingsFiles : public LLInitParam::Block<SettingsFiles>
+{
+ Multiple<SettingsGroup> groups;
+
+ SettingsFiles()
+ : groups("group")
+ {}
+};
+
+static std::string gWindowTitle;
+
+LLAppViewer::LLUpdaterInfo *LLAppViewer::sUpdaterInfo = NULL ;
+
+//----------------------------------------------------------------------------
+// Metrics logging control constants
+//----------------------------------------------------------------------------
+static const F32 METRICS_INTERVAL_DEFAULT = 600.0;
+static const F32 METRICS_INTERVAL_QA = 30.0;
+static F32 app_metrics_interval = METRICS_INTERVAL_DEFAULT;
+static bool app_metrics_qa_mode = false;
+
+void idle_afk_check()
+{
+ // check idle timers
+ if (gSavedSettings.getS32("AFKTimeout") && (gAwayTriggerTimer.getElapsedTimeF32() > gSavedSettings.getS32("AFKTimeout")))
+ {
+ gAgent.setAFK();
+ }
+}
+
+// A callback set in LLAppViewer::init()
+static void ui_audio_callback(const LLUUID& uuid)
+{
+ if (gAudiop)
+ {
+ gAudiop->triggerSound(uuid, gAgent.getID(), 1.0f, LLAudioEngine::AUDIO_TYPE_UI);
+ }
+}
+
+bool create_text_segment_icon_from_url_match(LLUrlMatch* match,LLTextBase* base)
+{
+ if(!match || !base || base->getPlainText())
+ return false;
+
+ LLUUID match_id = match->getID();
+
+ LLIconCtrl* icon;
+
+ if(gAgent.isInGroup(match_id, TRUE))
+ {
+ LLGroupIconCtrl::Params icon_params;
+ icon_params.group_id = match_id;
+ icon_params.rect = LLRect(0, 16, 16, 0);
+ icon_params.visible = true;
+ icon = LLUICtrlFactory::instance().create<LLGroupIconCtrl>(icon_params);
+ }
+ else
+ {
+ LLAvatarIconCtrl::Params icon_params;
+ icon_params.avatar_id = match_id;
+ icon_params.rect = LLRect(0, 16, 16, 0);
+ icon_params.visible = true;
+ icon = LLUICtrlFactory::instance().create<LLAvatarIconCtrl>(icon_params);
+ }
+
+ LLInlineViewSegment::Params params;
+ params.force_newline = false;
+ params.view = icon;
+ params.left_pad = 4;
+ params.right_pad = 4;
+ params.top_pad = -2;
+ params.bottom_pad = 2;
+
+ base->appendWidget(params," ",false);
+
+ return true;
+}
+
+void request_initial_instant_messages()
+{
+ static BOOL requested = FALSE;
+ if (!requested
+ && gMessageSystem
+ && LLMuteList::getInstance()->isLoaded()
+ && isAgentAvatarValid())
+ {
+ // Auto-accepted inventory items may require the avatar object
+ // to build a correct name. Likewise, inventory offers from
+ // muted avatars require the mute list to properly mute.
+ LLMessageSystem* msg = gMessageSystem;
+ msg->newMessageFast(_PREHASH_RetrieveInstantMessages);
+ msg->nextBlockFast(_PREHASH_AgentData);
+ msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
+ msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ gAgent.sendReliableMessage();
+ requested = TRUE;
+ }
+}
+
+// A settings system callback for CrashSubmitBehavior
+bool handleCrashSubmitBehaviorChanged(const LLSD& newvalue)
+{
+ S32 cb = newvalue.asInteger();
+ const S32 NEVER_SUBMIT_REPORT = 2;
+ if(cb == NEVER_SUBMIT_REPORT)
+ {
+ LLAppViewer::instance()->destroyMainloopTimeout();
+ }
+ return true;
+}
+
+// Use these strictly for things that are constructed at startup,
+// or for things that are performance critical. JC
+static void settings_to_globals()
+{
+ LLBUTTON_H_PAD = gSavedSettings.getS32("ButtonHPad");
+ BTN_HEIGHT_SMALL = gSavedSettings.getS32("ButtonHeightSmall");
+ BTN_HEIGHT = gSavedSettings.getS32("ButtonHeight");
+
+ MENU_BAR_HEIGHT = gSavedSettings.getS32("MenuBarHeight");
+ MENU_BAR_WIDTH = gSavedSettings.getS32("MenuBarWidth");
+
+ LLSurface::setTextureSize(gSavedSettings.getU32("RegionTextureSize"));
+
+ LLImageGL::sGlobalUseAnisotropic = gSavedSettings.getBOOL("RenderAnisotropic");
+ LLVOVolume::sLODFactor = gSavedSettings.getF32("RenderVolumeLODFactor");
+ LLVOVolume::sDistanceFactor = 1.f-LLVOVolume::sLODFactor * 0.1f;
+ LLVolumeImplFlexible::sUpdateFactor = gSavedSettings.getF32("RenderFlexTimeFactor");
+ LLVOTree::sTreeFactor = gSavedSettings.getF32("RenderTreeLODFactor");
+ LLVOAvatar::sLODFactor = gSavedSettings.getF32("RenderAvatarLODFactor");
+ LLVOAvatar::sMaxVisible = (U32)gSavedSettings.getS32("RenderAvatarMaxVisible");
+ LLVOAvatar::sVisibleInFirstPerson = gSavedSettings.getBOOL("FirstPersonAvatarVisible");
+ // clamp auto-open time to some minimum usable value
+ LLFolderView::sAutoOpenTime = llmax(0.25f, gSavedSettings.getF32("FolderAutoOpenDelay"));
+ LLSelectMgr::sRectSelectInclusive = gSavedSettings.getBOOL("RectangleSelectInclusive");
+ LLSelectMgr::sRenderHiddenSelections = gSavedSettings.getBOOL("RenderHiddenSelections");
+ LLSelectMgr::sRenderLightRadius = gSavedSettings.getBOOL("RenderLightRadius");
+
+ gAgentPilot.setNumRuns(gSavedSettings.getS32("StatsNumRuns"));
+ gAgentPilot.setQuitAfterRuns(gSavedSettings.getBOOL("StatsQuitAfterRuns"));
+ gAgent.setHideGroupTitle(gSavedSettings.getBOOL("RenderHideGroupTitle"));
+
+ gDebugWindowProc = gSavedSettings.getBOOL("DebugWindowProc");
+ gShowObjectUpdates = gSavedSettings.getBOOL("ShowObjectUpdates");
+ LLWorldMapView::sMapScale = gSavedSettings.getF32("MapScale");
+}
+
+static void settings_modify()
+{
+ LLRenderTarget::sUseFBO = gSavedSettings.getBOOL("RenderDeferred");
+ LLPipeline::sRenderDeferred = gSavedSettings.getBOOL("RenderDeferred");
+ LLVOAvatar::sUseImpostors = gSavedSettings.getBOOL("RenderUseImpostors");
+ LLVOSurfacePatch::sLODFactor = gSavedSettings.getF32("RenderTerrainLODFactor");
+ LLVOSurfacePatch::sLODFactor *= LLVOSurfacePatch::sLODFactor; //square lod factor to get exponential range of [1,4]
+ gDebugGL = gSavedSettings.getBOOL("RenderDebugGL") || gDebugSession;
+ gDebugPipeline = gSavedSettings.getBOOL("RenderDebugPipeline");
+ gAuditTexture = gSavedSettings.getBOOL("AuditTexture");
+#if LL_VECTORIZE
+ if (gSysCPU.hasAltivec())
+ {
+ gSavedSettings.setBOOL("VectorizeEnable", TRUE );
+ gSavedSettings.setU32("VectorizeProcessor", 0 );
+ }
+ else
+ if (gSysCPU.hasSSE2())
+ {
+ gSavedSettings.setBOOL("VectorizeEnable", TRUE );
+ gSavedSettings.setU32("VectorizeProcessor", 2 );
+ }
+ else
+ if (gSysCPU.hasSSE())
+ {
+ gSavedSettings.setBOOL("VectorizeEnable", TRUE );
+ gSavedSettings.setU32("VectorizeProcessor", 1 );
+ }
+ else
+ {
+ // Don't bother testing or running if CPU doesn't support it. JC
+ gSavedSettings.setBOOL("VectorizePerfTest", FALSE );
+ gSavedSettings.setBOOL("VectorizeEnable", FALSE );
+ gSavedSettings.setU32("VectorizeProcessor", 0 );
+ gSavedSettings.setBOOL("VectorizeSkin", FALSE);
+ }
+#else
+ // This build target doesn't support SSE, don't test/run.
+ gSavedSettings.setBOOL("VectorizePerfTest", FALSE );
+ gSavedSettings.setBOOL("VectorizeEnable", FALSE );
+ gSavedSettings.setU32("VectorizeProcessor", 0 );
+ gSavedSettings.setBOOL("VectorizeSkin", FALSE);
+
+ // disable fullscreen mode, unsupported
+ gSavedSettings.setBOOL("WindowFullScreen", FALSE);
+#endif
+}
+
+class LLFastTimerLogThread : public LLThread
+{
+public:
+ std::string mFile;
+
+ LLFastTimerLogThread(std::string& test_name) : LLThread("fast timer log")
+ {
+ std::string file_name = test_name + std::string(".slp");
+ mFile = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, file_name);
+ }
+
+ void run()
+ {
+ std::ofstream os(mFile.c_str());
+
+ while (!LLAppViewer::instance()->isQuitting())
+ {
+ LLFastTimer::writeLog(os);
+ os.flush();
+ ms_sleep(32);
+ }
+
+ os.close();
+ }
+};
+
+//virtual
+bool LLAppViewer::initSLURLHandler()
+{
+ // does nothing unless subclassed
+ return false;
+}
+
+//virtual
+bool LLAppViewer::sendURLToOtherInstance(const std::string& url)
+{
+ // does nothing unless subclassed
+ return false;
+}
+
+//----------------------------------------------------------------------------
+// LLAppViewer definition
+
+// Static members.
+// The single viewer app.
+LLAppViewer* LLAppViewer::sInstance = NULL;
+
+const std::string LLAppViewer::sGlobalSettingsName = "Global";
+
+LLTextureCache* LLAppViewer::sTextureCache = NULL;
+LLImageDecodeThread* LLAppViewer::sImageDecodeThread = NULL;
+LLTextureFetch* LLAppViewer::sTextureFetch = NULL;
+
+LLAppViewer::LLAppViewer() :
+ mMarkerFile(),
+ mLogoutMarkerFile(NULL),
+ mReportedCrash(false),
+ mNumSessions(0),
+ mPurgeCache(false),
+ mPurgeOnExit(false),
+ mSecondInstance(false),
+ mSavedFinalSnapshot(false),
+ mForceGraphicsDetail(false),
+ mQuitRequested(false),
+ mLogoutRequestSent(false),
+ mYieldTime(-1),
+ mMainloopTimeout(NULL),
+ mAgentRegionLastAlive(false),
+ mRandomizeFramerate(LLCachedControl<bool>(gSavedSettings,"Randomize Framerate", FALSE)),
+ mPeriodicSlowFrame(LLCachedControl<bool>(gSavedSettings,"Periodic Slow Frame", FALSE)),
+ mFastTimerLogThread(NULL),
+ mUpdater(new LLUpdaterService()),
+ mSettingsLocationList(NULL)
+{
+ if(NULL != sInstance)
+ {
+ llerrs << "Oh no! An instance of LLAppViewer already exists! LLAppViewer is sort of like a singleton." << llendl;
+ }
+
+ setupErrorHandling();
+ sInstance = this;
+ gLoggedInTime.stop();
+
+ LLLoginInstance::instance().setUpdaterService(mUpdater.get());
+}
+
+LLAppViewer::~LLAppViewer()
+{
+ delete mSettingsLocationList;
+
+ LLLoginInstance::instance().setUpdaterService(0);
+
+ destroyMainloopTimeout();
+
+ // If we got to this destructor somehow, the app didn't hang.
+ removeMarkerFile();
+}
+
+bool LLAppViewer::init()
+{
+ //
+ // Start of the application
+ //
+ // IMPORTANT! Do NOT put anything that will write
+ // into the log files during normal startup until AFTER
+ // we run the "program crashed last time" error handler below.
+ //
+ LLFastTimer::reset();
+
+ // initialize SSE options
+ LLVector4a::initClass();
+
+ // Need to do this initialization before we do anything else, since anything
+ // that touches files should really go through the lldir API
+ gDirUtilp->initAppDirs("SecondLife");
+ // set skin search path to default, will be overridden later
+ // this allows simple skinned file lookups to work
+ gDirUtilp->setSkinFolder("default");
+
+ initLogging();
+
+ //
+ // OK to write stuff to logs now, we've now crash reported if necessary
+ //
+
+ init_default_trans_args();
+
+ if (!initConfiguration())
+ return false;
+
+ // write Google Breakpad minidump files to our log directory
+ std::string logdir = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "");
+ logdir += gDirUtilp->getDirDelimiter();
+ setMiniDumpDir(logdir);
+
+ // Although initLogging() is the right place to mess with
+ // setFatalFunction(), we can't query gSavedSettings until after
+ // initConfiguration().
+ S32 rc(gSavedSettings.getS32("QAModeTermCode"));
+ if (rc >= 0)
+ {
+ // QAModeTermCode set, terminate with that rc on LL_ERRS. Use _exit()
+ // rather than exit() because normal cleanup depends too much on
+ // successful startup!
+ LLError::setFatalFunction(boost::bind(_exit, rc));
+ }
+
+ mAlloc.setProfilingEnabled(gSavedSettings.getBOOL("MemProfiling"));
+
+#if LL_RECORD_VIEWER_STATS
+ LLViewerStatsRecorder::initClass();
+#endif
+
+ // *NOTE:Mani - LLCurl::initClass is not thread safe.
+ // Called before threads are created.
+ LLCurl::initClass();
+ LLMachineID::init();
+
+ {
+ // Viewer metrics initialization
+ static LLCachedControl<bool> metrics_submode(gSavedSettings,
+ "QAModeMetrics",
+ false,
+ "Enables QA features (logging, faster cycling) for metrics collector");
+
+ if (metrics_submode)
+ {
+ app_metrics_qa_mode = true;
+ app_metrics_interval = METRICS_INTERVAL_QA;
+ }
+ LLViewerAssetStatsFF::init();
+ }
+
+ initThreads();
+ writeSystemInfo();
+
+ // Initialize updater service (now that we have an io pump)
+ initUpdater();
+ if(isQuitting())
+ {
+ // Early out here because updater set the quitting flag.
+ return true;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////
+ //////////////////////////////////////////////////////////////////////////////
+ //////////////////////////////////////////////////////////////////////////////
+ //////////////////////////////////////////////////////////////////////////////
+ // *FIX: The following code isn't grouped into functions yet.
+
+ // Statistics / debug timer initialization
+ init_statistics();
+
+ //
+ // Various introspection concerning the libs we're using - particularly
+ // the libs involved in getting to a full login screen.
+ //
+ LL_INFOS("InitInfo") << "J2C Engine is: " << LLImageJ2C::getEngineInfo() << LL_ENDL;
+ LL_INFOS("InitInfo") << "libcurl version is: " << LLCurl::getVersionString() << LL_ENDL;
+
+ // Get the single value from the crash settings file, if it exists
+ std::string crash_settings_filename = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, CRASH_SETTINGS_FILE);
+ gCrashSettings.loadFromFile(crash_settings_filename);
+ if(gSavedSettings.getBOOL("IgnoreAllNotifications"))
+ {
+ gCrashSettings.setS32(CRASH_BEHAVIOR_SETTING, CRASH_BEHAVIOR_ALWAYS_SEND);
+ gCrashSettings.saveToFile(crash_settings_filename, FALSE);
+ }
+
+ /////////////////////////////////////////////////
+ // OS-specific login dialogs
+ /////////////////////////////////////////////////
+
+ //test_cached_control();
+
+ // track number of times that app has run
+ mNumSessions = gSavedSettings.getS32("NumSessions");
+ mNumSessions++;
+ gSavedSettings.setS32("NumSessions", mNumSessions);
+
+ if (gSavedSettings.getBOOL("VerboseLogs"))
+ {
+ LLError::setPrintLocation(true);
+ }
+
+ // Widget construction depends on LLUI being initialized
+ LLUI::settings_map_t settings_map;
+ settings_map["config"] = &gSavedSettings;
+ settings_map["ignores"] = &gWarningSettings;
+ settings_map["floater"] = &gSavedSettings; // *TODO: New settings file
+ settings_map["account"] = &gSavedPerAccountSettings;
+
+ LLUI::initClass(settings_map,
+ LLUIImageList::getInstance(),
+ ui_audio_callback,
+ &LLUI::sGLScaleFactor);
+
+ // Setup paths and LLTrans after LLUI::initClass has been called
+ LLUI::setupPaths();
+ LLTransUtil::parseStrings("strings.xml", default_trans_args);
+ LLTransUtil::parseLanguageStrings("language_settings.xml");
+
+ // LLKeyboard relies on LLUI to know what some accelerator keys are called.
+ LLKeyboard::setStringTranslatorFunc( LLTrans::getKeyboardString );
+
+ LLWeb::initClass(); // do this after LLUI
+
+ // Provide the text fields with callbacks for opening Urls
+ LLUrlAction::setOpenURLCallback(&LLWeb::loadURL);
+ LLUrlAction::setOpenURLInternalCallback(&LLWeb::loadURLInternal);
+ LLUrlAction::setOpenURLExternalCallback(&LLWeb::loadURLExternal);
+ LLUrlAction::setExecuteSLURLCallback(&LLURLDispatcher::dispatchFromTextEditor);
+
+ // Let code in llui access the viewer help floater
+ LLUI::sHelpImpl = LLViewerHelp::getInstance();
+
+ // Load translations for tooltips
+ LLFloater::initClass();
+
+ /////////////////////////////////////////////////
+
+ LLToolMgr::getInstance(); // Initialize tool manager if not already instantiated
+
+ LLViewerFloaterReg::registerFloaters();
+
+ /////////////////////////////////////////////////
+ //
+ // Load settings files
+ //
+ //
+ LLGroupMgr::parseRoleActions("role_actions.xml");
+
+ LLAgent::parseTeleportMessages("teleport_strings.xml");
+
+ LLViewerJointMesh::updateVectorize();
+
+ // load MIME type -> media impl mappings
+ std::string mime_types_name;
+#if LL_DARWIN
+ mime_types_name = "mime_types_mac.xml";
+#elif LL_LINUX
+ mime_types_name = "mime_types_linux.xml";
+#else
+ mime_types_name = "mime_types.xml";
+#endif
+ LLMIMETypes::parseMIMETypes( mime_types_name );
+
+ // Copy settings to globals. *TODO: Remove or move to appropriage class initializers
+ settings_to_globals();
+ // Setup settings listeners
+ settings_setup_listeners();
+ // Modify settings based on system configuration and compile options
+ settings_modify();
+
+ // Find partition serial number (Windows) or hardware serial (Mac)
+ mSerialNumber = generateSerialNumber();
+
+ // do any necessary set-up for accepting incoming SLURLs from apps
+ initSLURLHandler();
+
+ if(false == initHardwareTest())
+ {
+ // Early out from user choice.
+ return false;
+ }
+
+ // Prepare for out-of-memory situations, during which we will crash on
+ // purpose and save a dump.
+#if LL_WINDOWS && LL_RELEASE_FOR_DOWNLOAD && LL_USE_SMARTHEAP
+ MemSetErrorHandler(first_mem_error_handler);
+#endif // LL_WINDOWS && LL_RELEASE_FOR_DOWNLOAD && LL_USE_SMARTHEAP
+
+ // *Note: this is where gViewerStats used to be created.
+
+ //
+ // Initialize the VFS, and gracefully handle initialization errors
+ //
+
+ if (!initCache())
+ {
+ std::ostringstream msg;
+ msg << LLTrans::getString("MBUnableToAccessFile");
+ OSMessageBox(msg.str(),LLStringUtil::null,OSMB_OK);
+ return 1;
+ }
+
+ // Initialize the repeater service.
+ LLMainLoopRepeater::instance().start();
+
+ //
+ // Initialize the window
+ //
+ gGLActive = TRUE;
+ initWindow();
+
+ // initWindow also initializes the Feature List, so now we can initialize this global.
+ LLCubeMap::sUseCubeMaps = LLFeatureManager::getInstance()->isFeatureAvailable("RenderCubeMap");
+
+ // call all self-registered classes
+ LLInitClassList::instance().fireCallbacks();
+
+ LLFolderViewItem::initClass(); // SJB: Needs to happen after initWindow(), not sure why but related to fonts
+
+ gGLManager.getGLInfo(gDebugInfo);
+ gGLManager.printGLInfoString();
+
+ // Load Default bindings
+ std::string key_bindings_file = gDirUtilp->findFile("keys.xml",
+ gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, ""),
+ gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
+
+
+ if (!gViewerKeyboard.loadBindingsXML(key_bindings_file))
+ {
+ std::string key_bindings_file = gDirUtilp->findFile("keys.ini",
+ gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, ""),
+ gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
+ if (!gViewerKeyboard.loadBindings(key_bindings_file))
+ {
+ LL_ERRS("InitInfo") << "Unable to open keys.ini" << LL_ENDL;
+ }
+ }
+
+ // If we don't have the right GL requirements, exit.
+ if (!gGLManager.mHasRequirements && !gNoRender)
+ {
+ // can't use an alert here since we're exiting and
+ // all hell breaks lose.
+ OSMessageBox(
+ LLNotifications::instance().getGlobalString("UnsupportedGLRequirements"),
+ LLStringUtil::null,
+ OSMB_OK);
+ return 0;
+ }
+
+ // Without SSE2 support we will crash almost immediately, warn here.
+ if (!gSysCPU.hasSSE2())
+ {
+ // can't use an alert here since we're exiting and
+ // all hell breaks lose.
+ OSMessageBox(
+ LLNotifications::instance().getGlobalString("UnsupportedCPUSSE2"),
+ LLStringUtil::null,
+ OSMB_OK);
+ return 0;
+ }
+
+ // alert the user if they are using unsupported hardware
+ if(!gSavedSettings.getBOOL("AlertedUnsupportedHardware"))
+ {
+ bool unsupported = false;
+ LLSD args;
+ std::string minSpecs;
+
+ // get cpu data from xml
+ std::stringstream minCPUString(LLNotifications::instance().getGlobalString("UnsupportedCPUAmount"));
+ S32 minCPU = 0;
+ minCPUString >> minCPU;
+
+ // get RAM data from XML
+ std::stringstream minRAMString(LLNotifications::instance().getGlobalString("UnsupportedRAMAmount"));
+ U64 minRAM = 0;
+ minRAMString >> minRAM;
+ minRAM = minRAM * 1024 * 1024;
+
+ if(!LLFeatureManager::getInstance()->isGPUSupported() && LLFeatureManager::getInstance()->getGPUClass() != GPU_CLASS_UNKNOWN)
+ {
+ minSpecs += LLNotifications::instance().getGlobalString("UnsupportedGPU");
+ minSpecs += "\n";
+ unsupported = true;
+ }
+ if(gSysCPU.getMHz() < minCPU)
+ {
+ minSpecs += LLNotifications::instance().getGlobalString("UnsupportedCPU");
+ minSpecs += "\n";
+ unsupported = true;
+ }
+ if(gSysMemory.getPhysicalMemoryClamped() < minRAM)
+ {
+ minSpecs += LLNotifications::instance().getGlobalString("UnsupportedRAM");
+ minSpecs += "\n";
+ unsupported = true;
+ }
+
+ if (LLFeatureManager::getInstance()->getGPUClass() == GPU_CLASS_UNKNOWN)
+ {
+ LLNotificationsUtil::add("UnknownGPU");
+ }
+
+ if(unsupported)
+ {
+ if(!gSavedSettings.controlExists("WarnUnsupportedHardware")
+ || gSavedSettings.getBOOL("WarnUnsupportedHardware"))
+ {
+ args["MINSPECS"] = minSpecs;
+ LLNotificationsUtil::add("UnsupportedHardware", args );
+ }
+
+ }
+ }
+
+
+ // save the graphics card
+ gDebugInfo["GraphicsCard"] = LLFeatureManager::getInstance()->getGPUString();
+
+ // Save the current version to the prefs file
+ gSavedSettings.setString("LastRunVersion",
+ LLVersionInfo::getChannelAndVersion());
+
+ gSimLastTime = gRenderStartTime.getElapsedTimeF32();
+ gSimFrames = (F32)gFrameCount;
+
+ LLViewerJoystick::getInstance()->init(false);
+
+ try {
+ initializeSecHandler();
+ }
+ catch (LLProtectedDataException ex)
+ {
+ LLNotificationsUtil::add("CorruptedProtectedDataStore");
+ }
+ LLHTTPClient::setCertVerifyCallback(secapiSSLCertVerifyCallback);
+
+
+ gGLActive = FALSE;
+ if (gSavedSettings.getBOOL("QAMode") && gSavedSettings.getS32("QAModeEventHostPort") > 0)
+ {
+ loadEventHostModule(gSavedSettings.getS32("QAModeEventHostPort"));
+ }
+
+ LLViewerMedia::initClass();
+ LLTextUtil::TextHelpers::iconCallbackCreationFunction = create_text_segment_icon_from_url_match;
+
+ //EXT-7013 - On windows for some locale (Japanese) standard
+ //datetime formatting functions didn't support some parameters such as "weekday".
+ //Names for days and months localized in xml are also useful for Polish locale(STORM-107).
+ std::string language = LLControlGroup::getInstance(sGlobalSettingsName)->getString("Language");
+ if(language == "ja" || language == "pl")
+ {
+ LLStringOps::setupWeekDaysNames(LLTrans::getString("dateTimeWeekdaysNames"));
+ LLStringOps::setupWeekDaysShortNames(LLTrans::getString("dateTimeWeekdaysShortNames"));
+ LLStringOps::setupMonthNames(LLTrans::getString("dateTimeMonthNames"));
+ LLStringOps::setupMonthShortNames(LLTrans::getString("dateTimeMonthShortNames"));
+ LLStringOps::setupDayFormat(LLTrans::getString("dateTimeDayFormat"));
+
+ LLStringOps::sAM = LLTrans::getString("dateTimeAM");
+ LLStringOps::sPM = LLTrans::getString("dateTimePM");
+ }
+
+ LLAgentLanguage::init();
+
+
+
+ return true;
+}
+
+static LLFastTimer::DeclareTimer FTM_MESSAGES("System Messages");
+static LLFastTimer::DeclareTimer FTM_SLEEP("Sleep");
+static LLFastTimer::DeclareTimer FTM_TEXTURE_CACHE("Texture Cache");
+static LLFastTimer::DeclareTimer FTM_DECODE("Image Decode");
+static LLFastTimer::DeclareTimer FTM_VFS("VFS Thread");
+static LLFastTimer::DeclareTimer FTM_LFS("LFS Thread");
+static LLFastTimer::DeclareTimer FTM_PAUSE_THREADS("Pause Threads");
+static LLFastTimer::DeclareTimer FTM_IDLE("Idle");
+static LLFastTimer::DeclareTimer FTM_PUMP("Pump");
+static LLFastTimer::DeclareTimer FTM_PUMP_ARES("Ares");
+static LLFastTimer::DeclareTimer FTM_PUMP_SERVICE("Service");
+static LLFastTimer::DeclareTimer FTM_SERVICE_CALLBACK("Callback");
+static LLFastTimer::DeclareTimer FTM_AGENT_AUTOPILOT("Autopilot");
+static LLFastTimer::DeclareTimer FTM_AGENT_UPDATE("Update");
+
+bool LLAppViewer::mainLoop()
+{
+ LLMemType mt1(LLMemType::MTYPE_MAIN);
+ mMainloopTimeout = new LLWatchdogTimeout();
+
+ //-------------------------------------------
+ // Run main loop until time to quit
+ //-------------------------------------------
+
+ // Create IO Pump to use for HTTP Requests.
+ gServicePump = new LLPumpIO(gAPRPoolp);
+ LLHTTPClient::setPump(*gServicePump);
+ LLCurl::setCAFile(gDirUtilp->getCAFile());
+
+ // Note: this is where gLocalSpeakerMgr and gActiveSpeakerMgr used to be instantiated.
+
+ LLVoiceChannel::initClass();
+ LLVoiceClient::getInstance()->init(gServicePump);
+ LLTimer frameTimer,idleTimer;
+ LLTimer debugTime;
+ LLFrameTimer memCheckTimer;
+ LLViewerJoystick* joystick(LLViewerJoystick::getInstance());
+ joystick->setNeedsReset(true);
+
+ LLEventPump& mainloop(LLEventPumps::instance().obtain("mainloop"));
+ // As we do not (yet) send data on the mainloop LLEventPump that varies
+ // with each frame, no need to instantiate a new LLSD event object each
+ // time. Obviously, if that changes, just instantiate the LLSD at the
+ // point of posting.
+ LLSD newFrame;
+
+ const F32 memory_check_interval = 1.0f ; //second
+
+ // Handle messages
+ while (!LLApp::isExiting())
+ {
+ LLFastTimer::nextFrame(); // Should be outside of any timer instances
+
+ //clear call stack records
+ llclearcallstacks;
+
+ //check memory availability information
+ {
+ if(memory_check_interval < memCheckTimer.getElapsedTimeF32())
+ {
+ memCheckTimer.reset() ;
+
+ //update the availability of memory
+ LLMemoryInfo::getAvailableMemoryKB(mAvailPhysicalMemInKB, mAvailVirtualMemInKB) ;
+ }
+ llcallstacks << "Available physical mem(KB): " << mAvailPhysicalMemInKB << llcallstacksendl ;
+ llcallstacks << "Available virtual mem(KB): " << mAvailVirtualMemInKB << llcallstacksendl ;
+ }
+
+ try
+ {
+ pingMainloopTimeout("Main:MiscNativeWindowEvents");
+
+ if (gViewerWindow)
+ {
+ LLFastTimer t2(FTM_MESSAGES);
+ gViewerWindow->mWindow->processMiscNativeEvents();
+ }
+
+ pingMainloopTimeout("Main:GatherInput");
+
+ if (gViewerWindow)
+ {
+ LLFastTimer t2(FTM_MESSAGES);
+ if (!restoreErrorTrap())
+ {
+ llwarns << " Someone took over my signal/exception handler (post messagehandling)!" << llendl;
+ }
+
+ gViewerWindow->mWindow->gatherInput();
+ }
+
+#if 1 && !LL_RELEASE_FOR_DOWNLOAD
+ // once per second debug info
+ if (debugTime.getElapsedTimeF32() > 1.f)
+ {
+ debugTime.reset();
+ }
+
+#endif
+ //memory leaking simulation
+ LLFloaterMemLeak* mem_leak_instance =
+ LLFloaterReg::findTypedInstance<LLFloaterMemLeak>("mem_leaking");
+ if(mem_leak_instance)
+ {
+ mem_leak_instance->idle() ;
+ }
+
+ // canonical per-frame event
+ mainloop.post(newFrame);
+
+ if (!LLApp::isExiting())
+ {
+ pingMainloopTimeout("Main:JoystickKeyboard");
+
+ // Scan keyboard for movement keys. Command keys and typing
+ // are handled by windows callbacks. Don't do this until we're
+ // done initializing. JC
+ if (gViewerWindow->mWindow->getVisible()
+ && gViewerWindow->getActive()
+ && !gViewerWindow->mWindow->getMinimized()
+ && LLStartUp::getStartupState() == STATE_STARTED
+ && !gViewerWindow->getShowProgress()
+ && !gFocusMgr.focusLocked())
+ {
+ LLMemType mjk(LLMemType::MTYPE_JOY_KEY);
+ joystick->scanJoystick();
+ gKeyboard->scanKeyboard();
+ }
+
+ // Update state based on messages, user input, object idle.
+ {
+ pauseMainloopTimeout(); // *TODO: Remove. Messages shouldn't be stalling for 20+ seconds!
+
+ LLFastTimer t3(FTM_IDLE);
+ idle();
+
+ if (gAres != NULL && gAres->isInitialized())
+ {
+ LLMemType mt_ip(LLMemType::MTYPE_IDLE_PUMP);
+ pingMainloopTimeout("Main:ServicePump");
+ LLFastTimer t4(FTM_PUMP);
+ {
+ LLFastTimer t(FTM_PUMP_ARES);
+ gAres->process();
+ }
+ {
+ LLFastTimer t(FTM_PUMP_SERVICE);
+ // this pump is necessary to make the login screen show up
+ gServicePump->pump();
+
+ {
+ LLFastTimer t(FTM_SERVICE_CALLBACK);
+ gServicePump->callback();
+ }
+ }
+ }
+
+ resumeMainloopTimeout();
+ }
+
+ if (gDoDisconnect && (LLStartUp::getStartupState() == STATE_STARTED))
+ {
+ pauseMainloopTimeout();
+ saveFinalSnapshot();
+ disconnectViewer();
+ resumeMainloopTimeout();
+ }
+
+ // Render scene.
+ if (!LLApp::isExiting())
+ {
+ pingMainloopTimeout("Main:Display");
+ gGLActive = TRUE;
+ display();
+ pingMainloopTimeout("Main:Snapshot");
+ LLFloaterSnapshot::update(); // take snapshots
+ gGLActive = FALSE;
+ }
+
+ }
+
+ pingMainloopTimeout("Main:Sleep");
+
+ pauseMainloopTimeout();
+
+ // Sleep and run background threads
+ {
+ LLMemType mt_sleep(LLMemType::MTYPE_SLEEP);
+ LLFastTimer t2(FTM_SLEEP);
+
+ // yield some time to the os based on command line option
+ if(mYieldTime >= 0)
+ {
+ ms_sleep(mYieldTime);
+ }
+
+ // yield cooperatively when not running as foreground window
+ if ( gNoRender
+ || (gViewerWindow && !gViewerWindow->mWindow->getVisible())
+ || !gFocusMgr.getAppHasFocus())
+ {
+ // Sleep if we're not rendering, or the window is minimized.
+ S32 milliseconds_to_sleep = llclamp(gSavedSettings.getS32("BackgroundYieldTime"), 0, 1000);
+ // don't sleep when BackgroundYieldTime set to 0, since this will still yield to other threads
+ // of equal priority on Windows
+ if (milliseconds_to_sleep > 0)
+ {
+ ms_sleep(milliseconds_to_sleep);
+ // also pause worker threads during this wait period
+ LLAppViewer::getTextureCache()->pause();
+ LLAppViewer::getImageDecodeThread()->pause();
+ }
+ }
+
+ if (mRandomizeFramerate)
+ {
+ ms_sleep(rand() % 200);
+ }
+
+ if (mPeriodicSlowFrame
+ && (gFrameCount % 10 == 0))
+ {
+ llinfos << "Periodic slow frame - sleeping 500 ms" << llendl;
+ ms_sleep(500);
+ }
+
+ static const F64 FRAME_SLOW_THRESHOLD = 0.5; //2 frames per seconds
+ const F64 max_idle_time = llmin(.005*10.0*gFrameTimeSeconds, 0.005); // 5 ms a second
+ idleTimer.reset();
+ bool is_slow = (frameTimer.getElapsedTimeF64() > FRAME_SLOW_THRESHOLD) ;
+ S32 total_work_pending = 0;
+ S32 total_io_pending = 0;
+ while(!is_slow)//do not unpause threads if the frame rates are very low.
+ {
+ S32 work_pending = 0;
+ S32 io_pending = 0;
+ {
+ LLFastTimer ftm(FTM_TEXTURE_CACHE);
+ work_pending += LLAppViewer::getTextureCache()->update(1); // unpauses the texture cache thread
+ }
+ {
+ LLFastTimer ftm(FTM_DECODE);
+ work_pending += LLAppViewer::getImageDecodeThread()->update(1); // unpauses the image thread
+ }
+ {
+ LLFastTimer ftm(FTM_DECODE);
+ work_pending += LLAppViewer::getTextureFetch()->update(1); // unpauses the texture fetch thread
+ }
+
+ {
+ LLFastTimer ftm(FTM_VFS);
+ io_pending += LLVFSThread::updateClass(1);
+ }
+ {
+ LLFastTimer ftm(FTM_LFS);
+ io_pending += LLLFSThread::updateClass(1);
+ }
+
+ if (io_pending > 1000)
+ {
+ ms_sleep(llmin(io_pending/100,100)); // give the vfs some time to catch up
+ }
+
+ total_work_pending += work_pending ;
+ total_io_pending += io_pending ;
+
+ if (!work_pending || idleTimer.getElapsedTimeF64() >= max_idle_time)
+ {
+ break;
+ }
+ }
+ gMeshRepo.update() ;
+
+ if(!total_work_pending) //pause texture fetching threads if nothing to process.
+ {
+ LLAppViewer::getTextureCache()->pause();
+ LLAppViewer::getImageDecodeThread()->pause();
+ LLAppViewer::getTextureFetch()->pause();
+ }
+ if(!total_io_pending) //pause file threads if nothing to process.
+ {
+ LLVFSThread::sLocal->pause();
+ LLLFSThread::sLocal->pause();
+ }
+
+ if ((LLStartUp::getStartupState() >= STATE_CLEANUP) &&
+ (frameTimer.getElapsedTimeF64() > FRAME_STALL_THRESHOLD))
+ {
+ gFrameStalls++;
+ }
+ frameTimer.reset();
+
+ resumeMainloopTimeout();
+
+ pingMainloopTimeout("Main:End");
+ }
+ }
+ catch(std::bad_alloc)
+ {
+ {
+ llinfos << "Availabe physical memory(KB) at the beginning of the frame: " << mAvailPhysicalMemInKB << llendl ;
+ llinfos << "Availabe virtual memory(KB) at the beginning of the frame: " << mAvailVirtualMemInKB << llendl ;
+
+ LLMemoryInfo::getAvailableMemoryKB(mAvailPhysicalMemInKB, mAvailVirtualMemInKB) ;
+
+ llinfos << "Current availabe physical memory(KB): " << mAvailPhysicalMemInKB << llendl ;
+ llinfos << "Current availabe virtual memory(KB): " << mAvailVirtualMemInKB << llendl ;
+ }
+
+ //stop memory leaking simulation
+ LLFloaterMemLeak* mem_leak_instance =
+ LLFloaterReg::findTypedInstance<LLFloaterMemLeak>("mem_leaking");
+ if(mem_leak_instance)
+ {
+ mem_leak_instance->stop() ;
+ llwarns << "Bad memory allocation in LLAppViewer::mainLoop()!" << llendl ;
+ }
+ else
+ {
+ //output possible call stacks to log file.
+ LLError::LLCallStacks::print() ;
+
+ llerrs << "Bad memory allocation in LLAppViewer::mainLoop()!" << llendl ;
+ }
+ }
+ }
+
+ // Save snapshot for next time, if we made it through initialization
+ if (STATE_STARTED == LLStartUp::getStartupState())
+ {
+ try
+ {
+ saveFinalSnapshot();
+ }
+ catch(std::bad_alloc)
+ {
+ llwarns << "Bad memory allocation when saveFinalSnapshot() is called!" << llendl ;
+
+ //stop memory leaking simulation
+ LLFloaterMemLeak* mem_leak_instance =
+ LLFloaterReg::findTypedInstance<LLFloaterMemLeak>("mem_leaking");
+ if(mem_leak_instance)
+ {
+ mem_leak_instance->stop() ;
+ }
+ }
+ }
+
+ delete gServicePump;
+
+ destroyMainloopTimeout();
+
+ llinfos << "Exiting main_loop" << llendflush;
+
+ return true;
+}
+
+void LLAppViewer::flushVFSIO()
+{
+ while (1)
+ {
+ S32 pending = LLVFSThread::updateClass(0);
+ pending += LLLFSThread::updateClass(0);
+ if (!pending)
+ {
+ break;
+ }
+ llinfos << "Waiting for pending IO to finish: " << pending << llendflush;
+ ms_sleep(100);
+ }
+}
+
+bool LLAppViewer::cleanup()
+{
+ // workaround for DEV-35406 crash on shutdown
+ LLEventPumps::instance().reset();
+
+ if (LLFastTimerView::sAnalyzePerformance)
+ {
+ llinfos << "Analyzing performance" << llendl;
+ std::string baseline_name = LLFastTimer::sLogName + "_baseline.slp";
+ std::string current_name = LLFastTimer::sLogName + ".slp";
+ std::string report_name = LLFastTimer::sLogName + "_report.csv";
+
+ LLFastTimerView::doAnalysis(
+ gDirUtilp->getExpandedFilename(LL_PATH_LOGS, baseline_name),
+ gDirUtilp->getExpandedFilename(LL_PATH_LOGS, current_name),
+ gDirUtilp->getExpandedFilename(LL_PATH_LOGS, report_name));
+ }
+ LLMetricPerformanceTesterBasic::cleanClass();
+
+ // remove any old breakpad minidump files from the log directory
+ if (! isError())
+ {
+ std::string logdir = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "");
+ logdir += gDirUtilp->getDirDelimiter();
+ gDirUtilp->deleteFilesInDir(logdir, "*-*-*-*-*.dmp");
+ }
+
+ // *TODO - generalize this and move DSO wrangling to a helper class -brad
+ std::set<struct apr_dso_handle_t *>::const_iterator i;
+ for(i = mPlugins.begin(); i != mPlugins.end(); ++i)
+ {
+ int (*ll_plugin_stop_func)(void) = NULL;
+ apr_status_t rv = apr_dso_sym((apr_dso_handle_sym_t*)&ll_plugin_stop_func, *i, "ll_plugin_stop");
+ ll_plugin_stop_func();
+
+ rv = apr_dso_unload(*i);
+ }
+ mPlugins.clear();
+
+ //flag all elements as needing to be destroyed immediately
+ // to ensure shutdown order
+ LLMortician::setZealous(TRUE);
+
+ LLVoiceClient::getInstance()->terminate();
+
+ disconnectViewer();
+
+ llinfos << "Viewer disconnected" << llendflush;
+
+ display_cleanup();
+
+ release_start_screen(); // just in case
+
+ LLError::logToFixedBuffer(NULL);
+
+ llinfos << "Cleaning Up" << llendflush;
+
+ // shut down mesh streamer
+ gMeshRepo.shutdown();
+
+ // Must clean up texture references before viewer window is destroyed.
+ if(LLHUDManager::instanceExists())
+ {
+ LLHUDManager::getInstance()->updateEffects();
+ LLHUDObject::updateAll();
+ LLHUDManager::getInstance()->cleanupEffects();
+ LLHUDObject::cleanupHUDObjects();
+ llinfos << "HUD Objects cleaned up" << llendflush;
+ }
+
+ LLKeyframeDataCache::clear();
+
+ // End TransferManager before deleting systems it depends on (Audio, VFS, AssetStorage)
+#if 0 // this seems to get us stuck in an infinite loop...
+ gTransferManager.cleanup();
+#endif
+
+ // Note: this is where gWorldMap used to be deleted.
+
+ // Note: this is where gHUDManager used to be deleted.
+ if(LLHUDManager::instanceExists())
+ {
+ LLHUDManager::getInstance()->shutdownClass();
+ }
+
+ delete gAssetStorage;
+ gAssetStorage = NULL;
+
+ LLPolyMesh::freeAllMeshes();
+
+ LLStartUp::cleanupNameCache();
+
+ // Note: this is where gLocalSpeakerMgr and gActiveSpeakerMgr used to be deleted.
+
+ LLWorldMap::getInstance()->reset(); // release any images
+
+ llinfos << "Global stuff deleted" << llendflush;
+
+ if (gAudiop)
+ {
+ // shut down the streaming audio sub-subsystem first, in case it relies on not outliving the general audio subsystem.
+
+ LLStreamingAudioInterface *sai = gAudiop->getStreamingAudioImpl();
+ delete sai;
+ gAudiop->setStreamingAudioImpl(NULL);
+
+ // shut down the audio subsystem
+
+ bool want_longname = false;
+ if (gAudiop->getDriverName(want_longname) == "FMOD")
+ {
+ // This hack exists because fmod likes to occasionally
+ // crash or hang forever when shutting down, for no
+ // apparent reason.
+ llwarns << "Hack, skipping FMOD audio engine cleanup" << llendflush;
+ }
+ else
+ {
+ gAudiop->shutdown();
+ }
+
+ delete gAudiop;
+ gAudiop = NULL;
+ }
+
+ // Note: this is where LLFeatureManager::getInstance()-> used to be deleted.
+
+ // Patch up settings for next time
+ // Must do this before we delete the viewer window,
+ // such that we can suck rectangle information out of
+ // it.
+ cleanupSavedSettings();
+ llinfos << "Settings patched up" << llendflush;
+
+ // delete some of the files left around in the cache.
+ removeCacheFiles("*.wav");
+ removeCacheFiles("*.tmp");
+ removeCacheFiles("*.lso");
+ removeCacheFiles("*.out");
+ removeCacheFiles("*.dsf");
+ removeCacheFiles("*.bodypart");
+ removeCacheFiles("*.clothing");
+
+ llinfos << "Cache files removed" << llendflush;
+
+ // Wait for any pending VFS IO
+ flushVFSIO();
+ llinfos << "Shutting down Views" << llendflush;
+
+ // Destroy the UI
+ if( gViewerWindow)
+ gViewerWindow->shutdownViews();
+
+ llinfos << "Cleaning up Inventory" << llendflush;
+
+ // Cleanup Inventory after the UI since it will delete any remaining observers
+ // (Deleted observers should have already removed themselves)
+ gInventory.cleanupInventory();
+
+ llinfos << "Cleaning up Selections" << llendflush;
+
+ // Clean up selection managers after UI is destroyed, as UI may be observing them.
+ // Clean up before GL is shut down because we might be holding on to objects with texture references
+ LLSelectMgr::cleanupGlobals();
+
+ llinfos << "Shutting down OpenGL" << llendflush;
+
+ // Shut down OpenGL
+ if( gViewerWindow)
+ {
+ gViewerWindow->shutdownGL();
+
+ // Destroy window, and make sure we're not fullscreen
+ // This may generate window reshape and activation events.
+ // Therefore must do this before destroying the message system.
+ delete gViewerWindow;
+ gViewerWindow = NULL;
+ llinfos << "ViewerWindow deleted" << llendflush;
+ }
+
+ llinfos << "Cleaning up Keyboard & Joystick" << llendflush;
+
+ // viewer UI relies on keyboard so keep it aound until viewer UI isa gone
+ delete gKeyboard;
+ gKeyboard = NULL;
+
+ // Turn off Space Navigator and similar devices
+ LLViewerJoystick::getInstance()->terminate();
+
+ llinfos << "Cleaning up Objects" << llendflush;
+
+ LLViewerObject::cleanupVOClasses();
+
+ LLWaterParamManager::cleanupClass();
+ LLWLParamManager::cleanupClass();
+ LLPostProcess::cleanupClass();
+
+ LLTracker::cleanupInstance();
+
+ // *FIX: This is handled in LLAppViewerWin32::cleanup().
+ // I'm keeping the comment to remember its order in cleanup,
+ // in case of unforseen dependency.
+ //#if LL_WINDOWS
+ // gDXHardware.cleanup();
+ //#endif // LL_WINDOWS
+
+ LLVolumeMgr* volume_manager = LLPrimitive::getVolumeManager();
+ if (!volume_manager->cleanup())
+ {
+ llwarns << "Remaining references in the volume manager!" << llendflush;
+ }
+ LLPrimitive::cleanupVolumeManager();
+
+ llinfos << "Additional Cleanup..." << llendflush;
+
+ LLViewerParcelMgr::cleanupGlobals();
+
+ // *Note: this is where gViewerStats used to be deleted.
+
+ //end_messaging_system();
+
+ LLFollowCamMgr::cleanupClass();
+ //LLVolumeMgr::cleanupClass();
+ LLPrimitive::cleanupVolumeManager();
+ LLWorldMapView::cleanupClass();
+ LLFolderViewItem::cleanupClass();
+ LLUI::cleanupClass();
+
+ //
+ // Shut down the VFS's AFTER the decode manager cleans up (since it cleans up vfiles).
+ // Also after viewerwindow is deleted, since it may have image pointers (which have vfiles)
+ // Also after shutting down the messaging system since it has VFS dependencies
+
+ //
+ llinfos << "Cleaning up VFS" << llendflush;
+ LLVFile::cleanupClass();
+
+ llinfos << "Saving Data" << llendflush;
+
+ // Store the time of our current logoff
+ gSavedPerAccountSettings.setU32("LastLogoff", time_corrected());
+
+ // Must do this after all panels have been deleted because panels that have persistent rects
+ // save their rects on delete.
+ gSavedSettings.saveToFile(gSavedSettings.getString("ClientSettingsFile"), TRUE);
+
+ LLUIColorTable::instance().saveUserSettings();
+
+ // PerAccountSettingsFile should be empty if no user has been logged on.
+ // *FIX:Mani This should get really saved in a "logoff" mode.
+ if (gSavedSettings.getString("PerAccountSettingsFile").empty())
+ {
+ llinfos << "Not saving per-account settings; don't know the account name yet." << llendl;
+ }
+ else
+ {
+ gSavedPerAccountSettings.saveToFile(gSavedSettings.getString("PerAccountSettingsFile"), TRUE);
+ llinfos << "Saved settings" << llendflush;
+ }
+
+ std::string crash_settings_filename = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, CRASH_SETTINGS_FILE);
+ // save all settings, even if equals defaults
+ gCrashSettings.saveToFile(crash_settings_filename, FALSE);
+
+ std::string warnings_settings_filename = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, getSettingsFilename("Default", "Warnings"));
+ gWarningSettings.saveToFile(warnings_settings_filename, TRUE);
+
+ // Save URL history file
+ LLURLHistory::saveFile("url_history.xml");
+
+ // save mute list. gMuteList used to also be deleted here too.
+ LLMuteList::getInstance()->cache(gAgent.getID());
+
+ if (mPurgeOnExit)
+ {
+ llinfos << "Purging all cache files on exit" << llendflush;
+ std::string mask = gDirUtilp->getDirDelimiter() + "*.*";
+ gDirUtilp->deleteFilesInDir(gDirUtilp->getExpandedFilename(LL_PATH_CACHE,""),mask);
+ }
+
+ removeMarkerFile(); // Any crashes from here on we'll just have to ignore
+
+ writeDebugInfo();
+
+ LLLocationHistory::getInstance()->save();
+
+ LLAvatarIconIDCache::getInstance()->save();
+
+ LLViewerMedia::saveCookieFile();
+
+ // Stop the plugin read thread if it's running.
+ LLPluginProcessParent::setUseReadThread(false);
+
+ llinfos << "Shutting down Threads" << llendflush;
+
+ // Let threads finish
+ LLTimer idleTimer;
+ idleTimer.reset();
+ const F64 max_idle_time = 5.f; // 5 seconds
+ while(1)
+ {
+ S32 pending = 0;
+ pending += LLAppViewer::getTextureCache()->update(1); // unpauses the worker thread
+ pending += LLAppViewer::getImageDecodeThread()->update(1); // unpauses the image thread
+ pending += LLAppViewer::getTextureFetch()->update(1); // unpauses the texture fetch thread
+ pending += LLVFSThread::updateClass(0);
+ pending += LLLFSThread::updateClass(0);
+ F64 idle_time = idleTimer.getElapsedTimeF64();
+ if(!pending)
+ {
+ break ; //done
+ }
+ else if(idle_time >= max_idle_time)
+ {
+ llwarns << "Quitting with pending background tasks." << llendl;
+ break;
+ }
+ }
+
+ // Delete workers first
+ // shotdown all worker threads before deleting them in case of co-dependencies
+ sTextureFetch->shutdown();
+ sTextureCache->shutdown();
+ sImageDecodeThread->shutdown();
+
+ sTextureFetch->shutDownTextureCacheThread() ;
+ sTextureFetch->shutDownImageDecodeThread() ;
+
+ LLFilePickerThread::cleanupClass();
+
+ delete sTextureCache;
+ sTextureCache = NULL;
+ delete sTextureFetch;
+ sTextureFetch = NULL;
+ delete sImageDecodeThread;
+ sImageDecodeThread = NULL;
+ delete mFastTimerLogThread;
+ mFastTimerLogThread = NULL;
+
+ if (LLFastTimerView::sAnalyzePerformance)
+ {
+ llinfos << "Analyzing performance" << llendl;
+
+ std::string baseline_name = LLFastTimer::sLogName + "_baseline.slp";
+ std::string current_name = LLFastTimer::sLogName + ".slp";
+ std::string report_name = LLFastTimer::sLogName + "_report.csv";
+
+ LLFastTimerView::doAnalysis(
+ gDirUtilp->getExpandedFilename(LL_PATH_LOGS, baseline_name),
+ gDirUtilp->getExpandedFilename(LL_PATH_LOGS, current_name),
+ gDirUtilp->getExpandedFilename(LL_PATH_LOGS, report_name));
+ }
+
+ LLMetricPerformanceTesterBasic::cleanClass() ;
+
+#if LL_RECORD_VIEWER_STATS
+ LLViewerStatsRecorder::cleanupClass();
+#endif
+
+ llinfos << "Cleaning up Media and Textures" << llendflush;
+
+ //Note:
+ //LLViewerMedia::cleanupClass() has to be put before gTextureList.shutdown()
+ //because some new image might be generated during cleaning up media. --bao
+ LLViewerMedia::cleanupClass();
+ LLViewerParcelMedia::cleanupClass();
+ gTextureList.shutdown(); // shutdown again in case a callback added something
+ LLUIImageList::getInstance()->cleanUp();
+
+ // This should eventually be done in LLAppViewer
+ LLImage::cleanupClass();
+ LLVFSThread::cleanupClass();
+ LLLFSThread::cleanupClass();
+
+#ifndef LL_RELEASE_FOR_DOWNLOAD
+ llinfos << "Auditing VFS" << llendl;
+ if(gVFS)
+ {
+ gVFS->audit();
+ }
+#endif
+
+ llinfos << "Misc Cleanup" << llendflush;
+
+ // For safety, the LLVFS has to be deleted *after* LLVFSThread. This should be cleaned up.
+ // (LLVFS doesn't know about LLVFSThread so can't kill pending requests) -Steve
+ delete gStaticVFS;
+ gStaticVFS = NULL;
+ delete gVFS;
+ gVFS = NULL;
+
+ gSavedSettings.cleanup();
+ LLUIColorTable::instance().clear();
+ gCrashSettings.cleanup();
+
+ LLWatchdog::getInstance()->cleanup();
+
+ LLViewerAssetStatsFF::cleanup();
+
+ llinfos << "Shutting down message system" << llendflush;
+ end_messaging_system();
+
+ // *NOTE:Mani - The following call is not thread safe.
+ LLCurl::cleanupClass();
+
+ // If we're exiting to launch an URL, do that here so the screen
+ // is at the right resolution before we launch IE.
+ if (!gLaunchFileOnQuit.empty())
+ {
+ llinfos << "Launch file on quit." << llendflush;
+#if LL_WINDOWS
+ // Indicate an application is starting.
+ SetCursor(LoadCursor(NULL, IDC_WAIT));
+#endif
+
+ // HACK: Attempt to wait until the screen res. switch is complete.
+ ms_sleep(1000);
+
+ LLWeb::loadURLExternal( gLaunchFileOnQuit, false );
+ llinfos << "File launched." << llendflush;
+ }
+
+ LLMainLoopRepeater::instance().stop();
+
+ ll_close_fail_log();
+
+ MEM_TRACK_RELEASE
+
+ llinfos << "Goodbye!" << llendflush;
+
+ // return 0;
+ return true;
+}
+
+// A callback for llerrs to call during the watchdog error.
+void watchdog_llerrs_callback(const std::string &error_string)
+{
+ gLLErrorActivated = true;
+
+#ifdef LL_WINDOWS
+ RaiseException(0,0,0,0);
+#else
+ raise(SIGQUIT);
+#endif
+}
+
+// A callback for the watchdog to call.
+void watchdog_killer_callback()
+{
+ LLError::setFatalFunction(watchdog_llerrs_callback);
+ llerrs << "Watchdog killer event" << llendl;
+}
+
+bool LLAppViewer::initThreads()
+{
+#if MEM_TRACK_MEM
+ static const bool enable_threads = false;
+#else
+ static const bool enable_threads = true;
+#endif
+
+ LLVFSThread::initClass(enable_threads && false);
+ LLLFSThread::initClass(enable_threads && false);
+
+ // Image decoding
+ LLAppViewer::sImageDecodeThread = new LLImageDecodeThread(enable_threads && true);
+ LLAppViewer::sTextureCache = new LLTextureCache(enable_threads && true);
+ LLAppViewer::sTextureFetch = new LLTextureFetch(LLAppViewer::getTextureCache(),
+ sImageDecodeThread,
+ enable_threads && true,
+ app_metrics_qa_mode);
+ LLImage::initClass();
+
+ if (LLFastTimer::sLog || LLFastTimer::sMetricLog)
+ {
+ LLFastTimer::sLogLock = new LLMutex(NULL);
+ mFastTimerLogThread = new LLFastTimerLogThread(LLFastTimer::sLogName);
+ mFastTimerLogThread->start();
+ }
+
+ // Mesh streaming and caching
+ gMeshRepo.init();
+
+ LLFilePickerThread::initClass();
+
+ // *FIX: no error handling here!
+ return true;
+}
+
+void errorCallback(const std::string &error_string)
+{
+#ifndef LL_RELEASE_FOR_DOWNLOAD
+ OSMessageBox(error_string, LLTrans::getString("MBFatalError"), OSMB_OK);
+#endif
+
+ //Set the ErrorActivated global so we know to create a marker file
+ gLLErrorActivated = true;
+
+ LLError::crashAndLoop(error_string);
+}
+
+bool LLAppViewer::initLogging()
+{
+ //
+ // Set up logging defaults for the viewer
+ //
+ LLError::initForApplication(
+ gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
+ LLError::setFatalFunction(errorCallback);
+
+ // Remove the last ".old" log file.
+ std::string old_log_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,
+ "SecondLife.old");
+ LLFile::remove(old_log_file);
+
+ // Rename current log file to ".old"
+ std::string log_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,
+ "SecondLife.log");
+ LLFile::rename(log_file, old_log_file);
+
+ // Set the log file to SecondLife.log
+
+ LLError::logToFile(log_file);
+
+ // *FIX:Mani no error handling here!
+ return true;
+}
+
+bool LLAppViewer::loadSettingsFromDirectory(const std::string& location_key,
+ bool set_defaults)
+{
+ if (!mSettingsLocationList)
+ {
+ llerrs << "Invalid settings location list" << llendl;
+ }
+
+ LLControlGroup* global_settings = LLControlGroup::getInstance(sGlobalSettingsName);
+ for(LLInitParam::ParamIterator<SettingsGroup>::const_iterator it = mSettingsLocationList->groups.begin(), end_it = mSettingsLocationList->groups.end();
+ it != end_it;
+ ++it)
+ {
+ // skip settings groups that aren't the one we requested
+ if (it->name() != location_key) continue;
+
+ ELLPath path_index = (ELLPath)it->path_index();
+ if(path_index <= LL_PATH_NONE || path_index >= LL_PATH_LAST)
+ {
+ llerrs << "Out of range path index in app_settings/settings_files.xml" << llendl;
+ return false;
+ }
+
+ LLInitParam::ParamIterator<SettingsFile>::const_iterator file_it, end_file_it;
+ for (file_it = it->files.begin(), end_file_it = it->files.end();
+ file_it != end_file_it;
+ ++file_it)
+ {
+ llinfos << "Attempting to load settings for the group " << file_it->name()
+ << " - from location " << location_key << llendl;
+
+ LLControlGroup* settings_group = LLControlGroup::getInstance(file_it->name);
+ if(!settings_group)
+ {
+ llwarns << "No matching settings group for name " << file_it->name() << llendl;
+ continue;
+ }
+
+ std::string full_settings_path;
+
+ if (file_it->file_name_setting.isProvided()
+ && global_settings->controlExists(file_it->file_name_setting))
+ {
+ // try to find filename stored in file_name_setting control
+ full_settings_path = global_settings->getString(file_it->file_name_setting);
+ if (!gDirUtilp->fileExists(full_settings_path))
+ {
+ // search in default path
+ full_settings_path = gDirUtilp->getExpandedFilename((ELLPath)path_index, full_settings_path);
+ }
+ }
+ else
+ {
+ // by default, use specified file name
+ full_settings_path = gDirUtilp->getExpandedFilename((ELLPath)path_index, file_it->file_name());
+ }
+
+ if(settings_group->loadFromFile(full_settings_path, set_defaults, file_it->persistent))
+ { // success!
+ llinfos << "Loaded settings file " << full_settings_path << llendl;
+ }
+ else
+ { // failed to load
+ if(file_it->required)
+ {
+ llerrs << "Error: Cannot load required settings file from: " << full_settings_path << llendl;
+ return false;
+ }
+ else
+ {
+ // only complain if we actually have a filename at this point
+ if (!full_settings_path.empty())
+ {
+ llinfos << "Cannot load " << full_settings_path << " - No settings found." << llendl;
+ }
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+std::string LLAppViewer::getSettingsFilename(const std::string& location_key,
+ const std::string& file)
+{
+ for(LLInitParam::ParamIterator<SettingsGroup>::const_iterator it = mSettingsLocationList->groups.begin(), end_it = mSettingsLocationList->groups.end();
+ it != end_it;
+ ++it)
+ {
+ if (it->name() == location_key)
+ {
+ LLInitParam::ParamIterator<SettingsFile>::const_iterator file_it, end_file_it;
+ for (file_it = it->files.begin(), end_file_it = it->files.end();
+ file_it != end_file_it;
+ ++file_it)
+ {
+ if (file_it->name() == file)
+ {
+ return file_it->file_name;
+ }
+ }
+ }
+ }
+
+ return std::string();
+}
+
+void LLAppViewer::loadColorSettings()
+{
+ LLUIColorTable::instance().loadFromSettings();
+}
+
+bool LLAppViewer::initConfiguration()
+{
+ //Load settings files list
+ std::string settings_file_list = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "settings_files.xml");
+ //LLControlGroup settings_control("SettingsFiles");
+ //llinfos << "Loading settings file list " << settings_file_list << llendl;
+ //if (0 == settings_control.loadFromFile(settings_file_list))
+ //{
+ // llerrs << "Cannot load default configuration file " << settings_file_list << llendl;
+ //}
+
+ LLXMLNodePtr root;
+ BOOL success = LLXMLNode::parseFile(settings_file_list, root, NULL);
+ if (!success)
+ {
+ llerrs << "Cannot load default configuration file " << settings_file_list << llendl;
+ }
+
+ mSettingsLocationList = new SettingsFiles();
+
+ LLXUIParser parser;
+ parser.readXUI(root, *mSettingsLocationList, settings_file_list);
+
+ if (!mSettingsLocationList->validateBlock())
+ {
+ llerrs << "Invalid settings file list " << settings_file_list << llendl;
+ }
+
+ // The settings and command line parsing have a fragile
+ // order-of-operation:
+ // - load defaults from app_settings
+ // - set procedural settings values
+ // - read command line settings
+ // - selectively apply settings needed to load user settings.
+ // - load overrides from user_settings
+ // - apply command line settings (to override the overrides)
+ // - load per account settings (happens in llstartup
+
+ // - load defaults
+ bool set_defaults = true;
+ if(!loadSettingsFromDirectory("Default", set_defaults))
+ {
+ std::ostringstream msg;
+ msg << "Unable to load default settings file. The installation may be corrupted.";
+ OSMessageBox(msg.str(),LLStringUtil::null,OSMB_OK);
+ return false;
+ }
+
+ LLUI::setupPaths(); // setup paths for LLTrans based on settings files only
+ LLTransUtil::parseStrings("strings.xml", default_trans_args);
+ LLTransUtil::parseLanguageStrings("language_settings.xml");
+ // - set procedural settings
+ // Note: can't use LL_PATH_PER_SL_ACCOUNT for any of these since we haven't logged in yet
+ gSavedSettings.setString("ClientSettingsFile",
+ gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, getSettingsFilename("Default", "Global")));
+
+ gSavedSettings.setString("VersionChannelName", LLVersionInfo::getChannel());
+
+#ifndef LL_RELEASE_FOR_DOWNLOAD
+ // provide developer build only overrides for these control variables that are not
+ // persisted to settings.xml
+ LLControlVariable* c = gSavedSettings.getControl("ShowConsoleWindow");
+ if (c)
+ {
+ c->setValue(true, false);
+ }
+ c = gSavedSettings.getControl("AllowMultipleViewers");
+ if (c)
+ {
+ c->setValue(true, false);
+ }
+#endif
+
+#ifndef LL_RELEASE_FOR_DOWNLOAD
+ gSavedSettings.setBOOL("QAMode", TRUE );
+ gSavedSettings.setS32("WatchdogEnabled", 0);
+#endif
+
+ gCrashSettings.getControl(CRASH_BEHAVIOR_SETTING)->getSignal()->connect(boost::bind(&handleCrashSubmitBehaviorChanged, _2));
+
+ // These are warnings that appear on the first experience of that condition.
+ // They are already set in the settings_default.xml file, but still need to be added to LLFirstUse
+ // for disable/reset ability
+// LLFirstUse::addConfigVariable("FirstBalanceIncrease");
+// LLFirstUse::addConfigVariable("FirstBalanceDecrease");
+// LLFirstUse::addConfigVariable("FirstSit");
+// LLFirstUse::addConfigVariable("FirstMap");
+// LLFirstUse::addConfigVariable("FirstGoTo");
+// LLFirstUse::addConfigVariable("FirstBuild");
+// LLFirstUse::addConfigVariable("FirstLeftClickNoHit");
+// LLFirstUse::addConfigVariable("FirstTeleport");
+// LLFirstUse::addConfigVariable("FirstOverrideKeys");
+// LLFirstUse::addConfigVariable("FirstAttach");
+// LLFirstUse::addConfigVariable("FirstAppearance");
+// LLFirstUse::addConfigVariable("FirstInventory");
+// LLFirstUse::addConfigVariable("FirstSandbox");
+// LLFirstUse::addConfigVariable("FirstFlexible");
+// LLFirstUse::addConfigVariable("FirstDebugMenus");
+// LLFirstUse::addConfigVariable("FirstSculptedPrim");
+// LLFirstUse::addConfigVariable("FirstVoice");
+// LLFirstUse::addConfigVariable("FirstMedia");
+
+ // - read command line settings.
+ LLControlGroupCLP clp;
+ std::string cmd_line_config = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,
+ "cmd_line.xml");
+
+ clp.configure(cmd_line_config, &gSavedSettings);
+
+ if(!initParseCommandLine(clp))
+ {
+ llwarns << "Error parsing command line options. Command Line options ignored." << llendl;
+
+ llinfos << "Command line usage:\n" << clp << llendl;
+
+ std::ostringstream msg;
+ msg << LLTrans::getString("MBCmdLineError") << clp.getErrorMessage();
+ OSMessageBox(msg.str(),LLStringUtil::null,OSMB_OK);
+ return false;
+ }
+
+ // - selectively apply settings
+
+ // If the user has specified a alternate settings file name.
+ // Load it now before loading the user_settings/settings.xml
+ if(clp.hasOption("settings"))
+ {
+ std::string user_settings_filename =
+ gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS,
+ clp.getOption("settings")[0]);
+ gSavedSettings.setString("ClientSettingsFile", user_settings_filename);
+ llinfos << "Using command line specified settings filename: "
+ << user_settings_filename << llendl;
+ }
+
+ // - load overrides from user_settings
+ loadSettingsFromDirectory("User");
+
+ if (gSavedSettings.getBOOL("FirstRunThisInstall"))
+ {
+ gSavedSettings.setString("SessionSettingsFile", "settings_minimal.xml");
+ }
+
+ if (clp.hasOption("sessionsettings"))
+ {
+ std::string session_settings_filename = clp.getOption("sessionsettings")[0];
+ gSavedSettings.setString("SessionSettingsFile", session_settings_filename);
+ llinfos << "Using session settings filename: "
+ << session_settings_filename << llendl;
+ }
+ loadSettingsFromDirectory("Session");
+
+ if (clp.hasOption("usersessionsettings"))
+ {
+ std::string user_session_settings_filename = clp.getOption("usersessionsettings")[0];
+ gSavedSettings.setString("UserSessionSettingsFile", user_session_settings_filename);
+ llinfos << "Using user session settings filename: "
+ << user_session_settings_filename << llendl;
+
+ }
+ loadSettingsFromDirectory("UserSession");
+
+ // - apply command line settings
+ clp.notify();
+
+ // Register the core crash option as soon as we can
+ // if we want gdb post-mortem on cores we need to be up and running
+ // ASAP or we might miss init issue etc.
+ if(clp.hasOption("disablecrashlogger"))
+ {
+ llwarns << "Crashes will be handled by system, stack trace logs and crash logger are both disabled" << llendl;
+ LLAppViewer::instance()->disableCrashlogger();
+ }
+
+ // Handle initialization from settings.
+ // Start up the debugging console before handling other options.
+ if (gSavedSettings.getBOOL("ShowConsoleWindow"))
+ {
+ initConsole();
+ }
+
+ if(clp.hasOption("help"))
+ {
+ std::ostringstream msg;
+ msg << LLTrans::getString("MBCmdLineUsg") << "\n" << clp;
+ llinfos << msg.str() << llendl;
+
+ OSMessageBox(
+ msg.str().c_str(),
+ LLStringUtil::null,
+ OSMB_OK);
+
+ return false;
+ }
+
+ if(clp.hasOption("set"))
+ {
+ const LLCommandLineParser::token_vector_t& set_values = clp.getOption("set");
+ if(0x1 & set_values.size())
+ {
+ llwarns << "Invalid '--set' parameter count." << llendl;
+ }
+ else
+ {
+ LLCommandLineParser::token_vector_t::const_iterator itr = set_values.begin();
+ for(; itr != set_values.end(); ++itr)
+ {
+ const std::string& name = *itr;
+ const std::string& value = *(++itr);
+ LLControlVariable* c = LLControlGroup::getInstance(sGlobalSettingsName)->getControl(name);
+ if(c)
+ {
+ c->setValue(value, false);
+ }
+ else
+ {
+ llwarns << "'--set' specified with unknown setting: '"
+ << name << "'." << llendl;
+ }
+ }
+ }
+ }
+
+ if(clp.hasOption("channel"))
+ {
+ LLVersionInfo::resetChannel(clp.getOption("channel")[0]);
+ }
+
+ // If we have specified crash on startup, set the global so we'll trigger the crash at the right time
+ if(clp.hasOption("crashonstartup"))
+ {
+ gCrashOnStartup = TRUE;
+ }
+
+ if (clp.hasOption("logperformance"))
+ {
+ LLFastTimer::sLog = TRUE;
+ LLFastTimer::sLogName = std::string("performance");
+ }
+
+ if (clp.hasOption("logmetrics"))
+ {
+ LLFastTimer::sMetricLog = TRUE ;
+ // '--logmetrics' can be specified with a named test metric argument so the data gathering is done only on that test
+ // In the absence of argument, every metric is gathered (makes for a rather slow run and hard to decipher report...)
+ std::string test_name = clp.getOption("logmetrics")[0];
+ llinfos << "'--logmetrics' argument : " << test_name << llendl;
+ if (test_name == "")
+ {
+ llwarns << "No '--logmetrics' argument given, will output all metrics to " << DEFAULT_METRIC_NAME << llendl;
+ LLFastTimer::sLogName = DEFAULT_METRIC_NAME;
+ }
+ else
+ {
+ LLFastTimer::sLogName = test_name;
+ }
+ }
+
+ if (clp.hasOption("graphicslevel"))
+ {
+ const LLCommandLineParser::token_vector_t& value = clp.getOption("graphicslevel");
+ if(value.size() != 1)
+ {
+ llwarns << "Usage: -graphicslevel <0-3>" << llendl;
+ }
+ else
+ {
+ std::string detail = value.front();
+ mForceGraphicsDetail = TRUE;
+
+ switch (detail.c_str()[0])
+ {
+ case '0':
+ gSavedSettings.setU32("RenderQualityPerformance", 0);
+ break;
+ case '1':
+ gSavedSettings.setU32("RenderQualityPerformance", 1);
+ break;
+ case '2':
+ gSavedSettings.setU32("RenderQualityPerformance", 2);
+ break;
+ case '3':
+ gSavedSettings.setU32("RenderQualityPerformance", 3);
+ break;
+ default:
+ mForceGraphicsDetail = FALSE;
+ llwarns << "Usage: -graphicslevel <0-3>" << llendl;
+ break;
+ }
+ }
+ }
+
+ if (clp.hasOption("analyzeperformance"))
+ {
+ LLFastTimerView::sAnalyzePerformance = TRUE;
+ }
+
+ if (clp.hasOption("replaysession"))
+ {
+ gAgentPilot.setReplaySession(TRUE);
+ }
+
+ if (clp.hasOption("nonotifications"))
+ {
+ gSavedSettings.getControl("IgnoreAllNotifications")->setValue(true, false);
+ }
+
+ if (clp.hasOption("debugsession"))
+ {
+ gDebugSession = TRUE;
+ gDebugGL = TRUE;
+
+ ll_init_fail_log(gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "test_failures.log"));
+ }
+
+ // Handle slurl use. NOTE: Don't let SL-55321 reappear.
+
+ // *FIX: This init code should be made more robust to prevent
+ // the issue SL-55321 from returning. One thought is to allow
+ // only select options to be set from command line when a slurl
+ // is specified. More work on the settings system is needed to
+ // achieve this. For now...
+
+ // *NOTE:Mani The command line parser parses tokens and is
+ // setup to bail after parsing the '--url' option or the
+ // first option specified without a '--option' flag (or
+ // any other option that uses the 'last_option' setting -
+ // see LLControlGroupCLP::configure())
+
+ // What can happen is that someone can use IE (or potentially
+ // other browsers) and do the rough equivalent of command
+ // injection and steal passwords. Phoenix. SL-55321
+ if(clp.hasOption("url"))
+ {
+ LLStartUp::setStartSLURL(LLSLURL(clp.getOption("url")[0]));
+ if(LLStartUp::getStartSLURL().getType() == LLSLURL::LOCATION)
+ {
+ LLGridManager::getInstance()->setGridChoice(LLStartUp::getStartSLURL().getGrid());
+
+ }
+ }
+ else if(clp.hasOption("slurl"))
+ {
+ LLSLURL start_slurl(clp.getOption("slurl")[0]);
+ LLStartUp::setStartSLURL(start_slurl);
+ }
+
+ const LLControlVariable* skinfolder = gSavedSettings.getControl("SkinCurrent");
+ if(skinfolder && LLStringUtil::null != skinfolder->getValue().asString())
+ {
+ // hack to force the skin to default.
+ gDirUtilp->setSkinFolder(skinfolder->getValue().asString());
+ //gDirUtilp->setSkinFolder("default");
+ }
+
+ mYieldTime = gSavedSettings.getS32("YieldTime");
+
+ // Read skin/branding settings if specified.
+ //if (! gDirUtilp->getSkinDir().empty() )
+ //{
+ // std::string skin_def_file = gDirUtilp->findSkinnedFilename("skin.xml");
+ // LLXmlTree skin_def_tree;
+
+ // if (!skin_def_tree.parseFile(skin_def_file))
+ // {
+ // llerrs << "Failed to parse skin definition." << llendl;
+ // }
+
+ //}
+
+#if LL_DARWIN
+ // Initialize apple menubar and various callbacks
+ init_apple_menu(LLTrans::getString("APP_NAME").c_str());
+
+#if __ppc__
+ // If the CPU doesn't have Altivec (i.e. it's not at least a G4), don't go any further.
+ // Only test PowerPC - all Intel Macs have SSE.
+ if(!gSysCPU.hasAltivec())
+ {
+ std::ostringstream msg;
+ msg << LLTrans::getString("MBRequiresAltiVec");
+ OSMessageBox(
+ msg.str(),
+ LLStringUtil::null,
+ OSMB_OK);
+ removeMarkerFile();
+ return false;
+ }
+#endif
+
+#endif // LL_DARWIN
+
+ // Display splash screen. Must be after above check for previous
+ // crash as this dialog is always frontmost.
+ std::string splash_msg;
+ LLStringUtil::format_map_t args;
+ args["[APP_NAME]"] = LLTrans::getString("SECOND_LIFE");
+ splash_msg = LLTrans::getString("StartupLoading", args);
+ LLSplashScreen::show();
+ LLSplashScreen::update(splash_msg);
+
+ //LLVolumeMgr::initClass();
+ LLVolumeMgr* volume_manager = new LLVolumeMgr();
+ volume_manager->useMutex(); // LLApp and LLMutex magic must be manually enabled
+ LLPrimitive::setVolumeManager(volume_manager);
+
+ // Note: this is where we used to initialize gFeatureManagerp.
+
+ gStartTime = totalTime();
+
+ //
+ // Set the name of the window
+ //
+ gWindowTitle = LLTrans::getString("APP_NAME");
+#if LL_DEBUG
+ gWindowTitle += std::string(" [DEBUG] ") + gArgs;
+#else
+ gWindowTitle += std::string(" ") + gArgs;
+#endif
+ LLStringUtil::truncate(gWindowTitle, 255);
+
+ //RN: if we received a URL, hand it off to the existing instance.
+ // don't call anotherInstanceRunning() when doing URL handoff, as
+ // it relies on checking a marker file which will not work when running
+ // out of different directories
+
+ if (LLStartUp::getStartSLURL().isValid())
+ {
+ if (sendURLToOtherInstance(LLStartUp::getStartSLURL().getSLURLString()))
+ {
+ // successfully handed off URL to existing instance, exit
+ return false;
+ }
+ }
+
+ if (!gSavedSettings.getBOOL("AllowMultipleViewers"))
+ {
+ //
+ // Check for another instance of the app running
+ //
+
+ mSecondInstance = anotherInstanceRunning();
+
+ if (mSecondInstance)
+ {
+ std::ostringstream msg;
+ msg << LLTrans::getString("MBAlreadyRunning");
+ OSMessageBox(
+ msg.str(),
+ LLStringUtil::null,
+ OSMB_OK);
+ return false;
+ }
+
+ initMarkerFile();
+
+ checkForCrash();
+ }
+ else
+ {
+ mSecondInstance = anotherInstanceRunning();
+
+ if (mSecondInstance)
+ {
+ // This is the second instance of SL. Turn off voice support,
+ // but make sure the setting is *not* persisted.
+ LLControlVariable* disable_voice = gSavedSettings.getControl("CmdLineDisableVoice");
+ if(disable_voice)
+ {
+ const BOOL DO_NOT_PERSIST = FALSE;
+ disable_voice->setValue(LLSD(TRUE), DO_NOT_PERSIST);
+ }
+ }
+
+ initMarkerFile();
+
+ if(!mSecondInstance)
+ {
+ checkForCrash();
+ }
+ }
+
+ // need to do this here - need to have initialized global settings first
+ std::string nextLoginLocation = gSavedSettings.getString( "NextLoginLocation" );
+ if ( !nextLoginLocation.empty() )
+ {
+ LLStartUp::setStartSLURL(LLSLURL(nextLoginLocation));
+ };
+
+ gLastRunVersion = gSavedSettings.getString("LastRunVersion");
+
+ loadColorSettings();
+
+ return true; // Config was successful.
+}
+
+namespace {
+ // *TODO - decide if there's a better place for these functions.
+ // do we need a file llupdaterui.cpp or something? -brad
+
+ void apply_update_callback(LLSD const & notification, LLSD const & response)
+ {
+ lldebugs << "LLUpdate user response: " << response << llendl;
+ if(response["OK_okcancelbuttons"].asBoolean())
+ {
+ llinfos << "LLUpdate restarting viewer" << llendl;
+ static const bool install_if_ready = true;
+ // *HACK - this lets us launch the installer immediately for now
+ LLUpdaterService().startChecking(install_if_ready);
+ }
+ }
+
+ void apply_update_ok_callback(LLSD const & notification, LLSD const & response)
+ {
+ llinfos << "LLUpdate restarting viewer" << llendl;
+ static const bool install_if_ready = true;
+ // *HACK - this lets us launch the installer immediately for now
+ LLUpdaterService().startChecking(install_if_ready);
+ }
+
+ void on_update_downloaded(LLSD const & data)
+ {
+ std::string notification_name;
+ void (*apply_callback)(LLSD const &, LLSD const &) = NULL;
+
+ if(data["required"].asBoolean())
+ {
+ if(LLStartUp::getStartupState() <= STATE_LOGIN_WAIT)
+ {
+ // The user never saw the progress bar.
+ apply_callback = &apply_update_ok_callback;
+ notification_name = "RequiredUpdateDownloadedVerboseDialog";
+ }
+ else if(LLStartUp::getStartupState() < STATE_WORLD_INIT)
+ {
+ // The user is logging in but blocked.
+ apply_callback = &apply_update_ok_callback;
+ notification_name = "RequiredUpdateDownloadedDialog";
+ }
+ else
+ {
+ // The user is already logged in; treat like an optional update.
+ apply_callback = &apply_update_callback;
+ notification_name = "DownloadBackgroundTip";
+ }
+ }
+ else
+ {
+ apply_callback = &apply_update_callback;
+ if(LLStartUp::getStartupState() < STATE_STARTED)
+ {
+ // CHOP-262 we need to use a different notification
+ // method prior to login.
+ notification_name = "DownloadBackgroundDialog";
+ }
+ else
+ {
+ notification_name = "DownloadBackgroundTip";
+ }
+ }
+
+ LLSD substitutions;
+ substitutions["VERSION"] = data["version"];
+
+ // truncate version at the rightmost '.'
+ std::string version_short(data["version"]);
+ size_t short_length = version_short.rfind('.');
+ if (short_length != std::string::npos)
+ {
+ version_short.resize(short_length);
+ }
+
+ LLUIString relnotes_url("[RELEASE_NOTES_BASE_URL][CHANNEL_URL]/[VERSION_SHORT]");
+ relnotes_url.setArg("[VERSION_SHORT]", version_short);
+
+ // *TODO thread the update service's response through to this point
+ std::string const & channel = LLVersionInfo::getChannel();
+ boost::shared_ptr<char> channel_escaped(curl_escape(channel.c_str(), channel.size()), &curl_free);
+
+ relnotes_url.setArg("[CHANNEL_URL]", channel_escaped.get());
+ relnotes_url.setArg("[RELEASE_NOTES_BASE_URL]", LLTrans::getString("RELEASE_NOTES_BASE_URL"));
+ substitutions["RELEASE_NOTES_FULL_URL"] = relnotes_url.getString();
+
+ LLNotificationsUtil::add(notification_name, substitutions, LLSD(), apply_callback);
+ }
+
+ void install_error_callback(LLSD const & notification, LLSD const & response)
+ {
+ LLAppViewer::instance()->forceQuit();
+ }
+
+ bool notify_update(LLSD const & evt)
+ {
+ std::string notification_name;
+ switch (evt["type"].asInteger())
+ {
+ case LLUpdaterService::DOWNLOAD_COMPLETE:
+ on_update_downloaded(evt);
+ break;
+ case LLUpdaterService::INSTALL_ERROR:
+ if(evt["required"].asBoolean()) {
+ LLNotificationsUtil::add("FailedRequiredUpdateInstall", LLSD(), LLSD(), &install_error_callback);
+ } else {
+ LLNotificationsUtil::add("FailedUpdateInstall");
+ }
+ break;
+ default:
+ break;
+ }
+
+ // let others also handle this event by default
+ return false;
+ }
+
+ bool on_bandwidth_throttle(LLUpdaterService * updater, LLSD const & evt)
+ {
+ updater->setBandwidthLimit(evt.asInteger() * (1024/8));
+ return false; // Let others receive this event.
+ };
+};
+
+void LLAppViewer::initUpdater()
+{
+ // Initialize the updater service.
+ // Generate URL to the udpater service
+ // Get Channel
+ // Get Version
+ std::string url = gSavedSettings.getString("UpdaterServiceURL");
+ std::string channel = LLVersionInfo::getChannel();
+ std::string version = LLVersionInfo::getVersion();
+ std::string protocol_version = gSavedSettings.getString("UpdaterServiceProtocolVersion");
+ std::string service_path = gSavedSettings.getString("UpdaterServicePath");
+ U32 check_period = gSavedSettings.getU32("UpdaterServiceCheckPeriod");
+
+ mUpdater->setAppExitCallback(boost::bind(&LLAppViewer::forceQuit, this));
+ mUpdater->initialize(protocol_version,
+ url,
+ service_path,
+ channel,
+ version);
+ mUpdater->setCheckPeriod(check_period);
+ mUpdater->setBandwidthLimit((int)gSavedSettings.getF32("UpdaterMaximumBandwidth") * (1024/8));
+ gSavedSettings.getControl("UpdaterMaximumBandwidth")->getSignal()->
+ connect(boost::bind(&on_bandwidth_throttle, mUpdater.get(), _2));
+ if(gSavedSettings.getU32("UpdaterServiceSetting"))
+ {
+ bool install_if_ready = true;
+ mUpdater->startChecking(install_if_ready);
+ }
+
+ LLEventPump & updater_pump = LLEventPumps::instance().obtain(LLUpdaterService::pumpName());
+ updater_pump.listen("notify_update", &notify_update);
+}
+
+void LLAppViewer::checkForCrash(void)
+{
+
+#if LL_SEND_CRASH_REPORTS
+ if (gLastExecEvent == LAST_EXEC_FROZE)
+ {
+ llinfos << "Last execution froze, requesting to send crash report." << llendl;
+ //
+ // Pop up a freeze or crash warning dialog
+ //
+ S32 choice;
+ if(gCrashSettings.getS32(CRASH_BEHAVIOR_SETTING) == CRASH_BEHAVIOR_ASK)
+ {
+ std::ostringstream msg;
+ msg << LLTrans::getString("MBFrozenCrashed");
+ std::string alert = LLTrans::getString("APP_NAME") + " " + LLTrans::getString("MBAlert");
+ choice = OSMessageBox(msg.str(),
+ alert,
+ OSMB_YESNO);
+ }
+ else if(gCrashSettings.getS32(CRASH_BEHAVIOR_SETTING) == CRASH_BEHAVIOR_NEVER_SEND)
+ {
+ choice = OSBTN_NO;
+ }
+ else
+ {
+ choice = OSBTN_YES;
+ }
+
+ if (OSBTN_YES == choice)
+ {
+ llinfos << "Sending crash report." << llendl;
+
+ bool report_freeze = true;
+ handleCrashReporting(report_freeze);
+ }
+ else
+ {
+ llinfos << "Not sending crash report." << llendl;
+ }
+ }
+#endif // LL_SEND_CRASH_REPORTS
+
+}
+
+bool LLAppViewer::initWindow()
+{
+ LL_INFOS("AppInit") << "Initializing window..." << LL_ENDL;
+
+ // store setting in a global for easy access and modification
+ gNoRender = gSavedSettings.getBOOL("DisableRendering");
+
+ // always start windowed
+ BOOL ignorePixelDepth = gSavedSettings.getBOOL("IgnorePixelDepth");
+ gViewerWindow = new LLViewerWindow(gWindowTitle,
+ VIEWER_WINDOW_CLASSNAME,
+ gSavedSettings.getS32("WindowX"), gSavedSettings.getS32("WindowY"),
+ gSavedSettings.getS32("WindowWidth"), gSavedSettings.getS32("WindowHeight"),
+ gSavedSettings.getBOOL("WindowFullScreen"), ignorePixelDepth);
+
+ // Need to load feature table before cheking to start watchdog.
+ const S32 NEVER_SUBMIT_REPORT = 2;
+ bool use_watchdog = false;
+ int watchdog_enabled_setting = gSavedSettings.getS32("WatchdogEnabled");
+ if(watchdog_enabled_setting == -1){
+ use_watchdog = !LLFeatureManager::getInstance()->isFeatureAvailable("WatchdogDisabled");
+ }
+ else
+ {
+ // The user has explicitly set this setting; always use that value.
+ use_watchdog = bool(watchdog_enabled_setting);
+ }
+
+ bool send_reports = gCrashSettings.getS32(CRASH_BEHAVIOR_SETTING) != NEVER_SUBMIT_REPORT;
+ if(use_watchdog && send_reports)
+ {
+ LLWatchdog::getInstance()->init(watchdog_killer_callback);
+ }
+
+ LLNotificationsUI::LLNotificationManager::getInstance();
+
+ if (gSavedSettings.getBOOL("WindowMaximized"))
+ {
+ gViewerWindow->mWindow->maximize();
+ }
+
+ if (!gNoRender)
+ {
+ //
+ // Initialize GL stuff
+ //
+
+ if (mForceGraphicsDetail)
+ {
+ LLFeatureManager::getInstance()->setGraphicsLevel(gSavedSettings.getU32("RenderQualityPerformance"), false);
+ }
+
+ // Set this flag in case we crash while initializing GL
+ gSavedSettings.setBOOL("RenderInitError", TRUE);
+ gSavedSettings.saveToFile( gSavedSettings.getString("ClientSettingsFile"), TRUE );
+
+ gPipeline.init();
+
+ stop_glerror();
+ gViewerWindow->initGLDefaults();
+
+ gSavedSettings.setBOOL("RenderInitError", FALSE);
+ gSavedSettings.saveToFile( gSavedSettings.getString("ClientSettingsFile"), TRUE );
+ }
+
+ //If we have a startup crash, it's usually near GL initialization, so simulate that.
+ if(gCrashOnStartup)
+ {
+ LLAppViewer::instance()->forceErrorLLError();
+ }
+
+ LLUI::sWindow = gViewerWindow->getWindow();
+
+ // Show watch cursor
+ gViewerWindow->setCursor(UI_CURSOR_WAIT);
+
+ // Finish view initialization
+ gViewerWindow->initBase();
+
+ // show viewer window
+ //gViewerWindow->mWindow->show();
+
+
+ return true;
+}
+
+void LLAppViewer::writeDebugInfo()
+{
+ std::string debug_filename = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,"debug_info.log");
+ llinfos << "Opening debug file " << debug_filename << llendl;
+ llofstream out_file(debug_filename);
+ LLSDSerialize::toPrettyXML(gDebugInfo, out_file);
+ out_file.close();
+}
+
+void LLAppViewer::cleanupSavedSettings()
+{
+ gSavedSettings.setBOOL("MouseSun", FALSE);
+
+ gSavedSettings.setBOOL("UseEnergy", TRUE); // force toggle to turn off, since sends message to simulator
+
+ gSavedSettings.setBOOL("DebugWindowProc", gDebugWindowProc);
+
+ gSavedSettings.setBOOL("ShowObjectUpdates", gShowObjectUpdates);
+
+ if (!gNoRender)
+ {
+ if (gDebugView)
+ {
+ gSavedSettings.setBOOL("ShowDebugConsole", gDebugView->mDebugConsolep->getVisible());
+ }
+ }
+
+ // save window position if not maximized
+ // as we don't track it in callbacks
+ if(NULL != gViewerWindow)
+ {
+ BOOL maximized = gViewerWindow->mWindow->getMaximized();
+ if (!maximized)
+ {
+ LLCoordScreen window_pos;
+
+ if (gViewerWindow->mWindow->getPosition(&window_pos))
+ {
+ gSavedSettings.setS32("WindowX", window_pos.mX);
+ gSavedSettings.setS32("WindowY", window_pos.mY);
+ }
+ }
+ }
+
+ gSavedSettings.setF32("MapScale", LLWorldMapView::sMapScale );
+
+ // Some things are cached in LLAgent.
+ if (gAgent.isInitialized())
+ {
+ gSavedSettings.setF32("RenderFarClip", gAgentCamera.mDrawDistance);
+ }
+}
+
+void LLAppViewer::removeCacheFiles(const std::string& file_mask)
+{
+ std::string mask = gDirUtilp->getDirDelimiter() + file_mask;
+ gDirUtilp->deleteFilesInDir(gDirUtilp->getExpandedFilename(LL_PATH_CACHE, ""), mask);
+}
+
+void LLAppViewer::writeSystemInfo()
+{
+ gDebugInfo["SLLog"] = LLError::logFileName();
+
+ gDebugInfo["ClientInfo"]["Name"] = LLVersionInfo::getChannel();
+ gDebugInfo["ClientInfo"]["MajorVersion"] = LLVersionInfo::getMajor();
+ gDebugInfo["ClientInfo"]["MinorVersion"] = LLVersionInfo::getMinor();
+ gDebugInfo["ClientInfo"]["PatchVersion"] = LLVersionInfo::getPatch();
+ gDebugInfo["ClientInfo"]["BuildVersion"] = LLVersionInfo::getBuild();
+
+ gDebugInfo["CAFilename"] = gDirUtilp->getCAFile();
+
+ gDebugInfo["CPUInfo"]["CPUString"] = gSysCPU.getCPUString();
+ gDebugInfo["CPUInfo"]["CPUFamily"] = gSysCPU.getFamily();
+ gDebugInfo["CPUInfo"]["CPUMhz"] = (S32)gSysCPU.getMHz();
+ gDebugInfo["CPUInfo"]["CPUAltivec"] = gSysCPU.hasAltivec();
+ gDebugInfo["CPUInfo"]["CPUSSE"] = gSysCPU.hasSSE();
+ gDebugInfo["CPUInfo"]["CPUSSE2"] = gSysCPU.hasSSE2();
+
+ gDebugInfo["RAMInfo"]["Physical"] = (LLSD::Integer)(gSysMemory.getPhysicalMemoryKB());
+ gDebugInfo["RAMInfo"]["Allocated"] = (LLSD::Integer)(gMemoryAllocated>>10); // MB -> KB
+ gDebugInfo["OSInfo"] = getOSInfo().getOSStringSimple();
+
+ // The user is not logged on yet, but record the current grid choice login url
+ // which may have been the intended grid. This can b
+ gDebugInfo["GridName"] = LLGridManager::getInstance()->getGridLabel();
+
+ // *FIX:Mani - move this down in llappviewerwin32
+#ifdef LL_WINDOWS
+ DWORD thread_id = GetCurrentThreadId();
+ gDebugInfo["MainloopThreadID"] = (S32)thread_id;
+#endif
+
+ // "CrashNotHandled" is set here, while things are running well,
+ // in case of a freeze. If there is a freeze, the crash logger will be launched
+ // and can read this value from the debug_info.log.
+ // If the crash is handled by LLAppViewer::handleViewerCrash, ie not a freeze,
+ // then the value of "CrashNotHandled" will be set to true.
+ gDebugInfo["CrashNotHandled"] = (LLSD::Boolean)true;
+
+ // Insert crash host url (url to post crash log to) if configured. This insures
+ // that the crash report will go to the proper location in the case of a
+ // prior freeze.
+ std::string crashHostUrl = gSavedSettings.get<std::string>("CrashHostUrl");
+ if(crashHostUrl != "")
+ {
+ gDebugInfo["CrashHostUrl"] = crashHostUrl;
+ }
+
+ // Dump some debugging info
+ LL_INFOS("SystemInfo") << LLTrans::getString("APP_NAME")
+ << " version " << LLVersionInfo::getShortVersion() << LL_ENDL;
+
+ // Dump the local time and time zone
+ time_t now;
+ time(&now);
+ char tbuffer[256]; /* Flawfinder: ignore */
+ strftime(tbuffer, 256, "%Y-%m-%dT%H:%M:%S %Z", localtime(&now));
+ LL_INFOS("SystemInfo") << "Local time: " << tbuffer << LL_ENDL;
+
+ // query some system information
+ LL_INFOS("SystemInfo") << "CPU info:\n" << gSysCPU << LL_ENDL;
+ LL_INFOS("SystemInfo") << "Memory info:\n" << gSysMemory << LL_ENDL;
+ LL_INFOS("SystemInfo") << "OS: " << getOSInfo().getOSStringSimple() << LL_ENDL;
+ LL_INFOS("SystemInfo") << "OS info: " << getOSInfo() << LL_ENDL;
+
+ LL_INFOS("SystemInfo") << "Timers: " << LLFastTimer::sClockType << LL_ENDL;
+
+ writeDebugInfo(); // Save out debug_info.log early, in case of crash.
+}
+
+void LLAppViewer::handleViewerCrash()
+{
+ llinfos << "Handle viewer crash entry." << llendl;
+
+ llinfos << "Last render pool type: " << LLPipeline::sCurRenderPoolType << llendl ;
+
+ //print out recorded call stacks if there are any.
+ LLError::LLCallStacks::print();
+
+ LLAppViewer* pApp = LLAppViewer::instance();
+ if (pApp->beingDebugged())
+ {
+ // This will drop us into the debugger.
+ abort();
+ }
+
+ if (LLApp::isCrashloggerDisabled())
+ {
+ abort();
+ }
+
+ // Returns whether a dialog was shown.
+ // Only do the logic in here once
+ if (pApp->mReportedCrash)
+ {
+ return;
+ }
+ pApp->mReportedCrash = TRUE;
+
+ // Insert crash host url (url to post crash log to) if configured.
+ std::string crashHostUrl = gSavedSettings.get<std::string>("CrashHostUrl");
+ if(crashHostUrl != "")
+ {
+ gDebugInfo["CrashHostUrl"] = crashHostUrl;
+ }
+
+ //We already do this in writeSystemInfo(), but we do it again here to make /sure/ we have a version
+ //to check against no matter what
+ gDebugInfo["ClientInfo"]["Name"] = LLVersionInfo::getChannel();
+
+ gDebugInfo["ClientInfo"]["MajorVersion"] = LLVersionInfo::getMajor();
+ gDebugInfo["ClientInfo"]["MinorVersion"] = LLVersionInfo::getMinor();
+ gDebugInfo["ClientInfo"]["PatchVersion"] = LLVersionInfo::getPatch();
+ gDebugInfo["ClientInfo"]["BuildVersion"] = LLVersionInfo::getBuild();
+
+ LLParcel* parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
+ if ( parcel && parcel->getMusicURL()[0])
+ {
+ gDebugInfo["ParcelMusicURL"] = parcel->getMusicURL();
+ }
+ if ( parcel && parcel->getMediaURL()[0])
+ {
+ gDebugInfo["ParcelMediaURL"] = parcel->getMediaURL();
+ }
+
+
+ gDebugInfo["SettingsFilename"] = gSavedSettings.getString("ClientSettingsFile");
+ gDebugInfo["CAFilename"] = gDirUtilp->getCAFile();
+ gDebugInfo["ViewerExePath"] = gDirUtilp->getExecutablePathAndName();
+ gDebugInfo["CurrentPath"] = gDirUtilp->getCurPath();
+ gDebugInfo["SessionLength"] = F32(LLFrameTimer::getElapsedSeconds());
+ gDebugInfo["StartupState"] = LLStartUp::getStartupStateString();
+ gDebugInfo["RAMInfo"]["Allocated"] = (LLSD::Integer) LLMemory::getCurrentRSS() >> 10;
+ gDebugInfo["FirstLogin"] = (LLSD::Boolean) gAgent.isFirstLogin();
+ gDebugInfo["FirstRunThisInstall"] = gSavedSettings.getBOOL("FirstRunThisInstall");
+
+ char *minidump_file = pApp->getMiniDumpFilename();
+ if(minidump_file && minidump_file[0] != 0)
+ {
+ gDebugInfo["MinidumpPath"] = minidump_file;
+ }
+
+ if(gLogoutInProgress)
+ {
+ gDebugInfo["LastExecEvent"] = LAST_EXEC_LOGOUT_CRASH;
+ }
+ else
+ {
+ gDebugInfo["LastExecEvent"] = gLLErrorActivated ? LAST_EXEC_LLERROR_CRASH : LAST_EXEC_OTHER_CRASH;
+ }
+
+ if(gAgent.getRegion())
+ {
+ gDebugInfo["CurrentSimHost"] = gAgent.getRegionHost().getHostName();
+ gDebugInfo["CurrentRegion"] = gAgent.getRegion()->getName();
+
+ const LLVector3& loc = gAgent.getPositionAgent();
+ gDebugInfo["CurrentLocationX"] = loc.mV[0];
+ gDebugInfo["CurrentLocationY"] = loc.mV[1];
+ gDebugInfo["CurrentLocationZ"] = loc.mV[2];
+ }
+
+ if(LLAppViewer::instance()->mMainloopTimeout)
+ {
+ gDebugInfo["MainloopTimeoutState"] = LLAppViewer::instance()->mMainloopTimeout->getState();
+ }
+
+ // The crash is being handled here so set this value to false.
+ // Otherwise the crash logger will think this crash was a freeze.
+ gDebugInfo["CrashNotHandled"] = (LLSD::Boolean)false;
+
+ //Write out the crash status file
+ //Use marker file style setup, as that's the simplest, especially since
+ //we're already in a crash situation
+ if (gDirUtilp)
+ {
+ std::string crash_file_name;
+ if(gLLErrorActivated) crash_file_name = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,LLERROR_MARKER_FILE_NAME);
+ else crash_file_name = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,ERROR_MARKER_FILE_NAME);
+ llinfos << "Creating crash marker file " << crash_file_name << llendl;
+
+ LLAPRFile crash_file ;
+ crash_file.open(crash_file_name, LL_APR_W);
+ if (crash_file.getFileHandle())
+ {
+ LL_INFOS("MarkerFile") << "Created crash marker file " << crash_file_name << LL_ENDL;
+ }
+ else
+ {
+ LL_WARNS("MarkerFile") << "Cannot create error marker file " << crash_file_name << LL_ENDL;
+ }
+ }
+
+ if (gMessageSystem && gDirUtilp)
+ {
+ std::string filename;
+ filename = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "stats.log");
+ llofstream file(filename, llofstream::binary);
+ if(file.good())
+ {
+ llinfos << "Handle viewer crash generating stats log." << llendl;
+ gMessageSystem->summarizeLogs(file);
+ file.close();
+ }
+ }
+
+ if (gMessageSystem)
+ {
+ gMessageSystem->getCircuitInfo(gDebugInfo["CircuitInfo"]);
+ gMessageSystem->stopLogging();
+ }
+
+ if (LLWorld::instanceExists()) LLWorld::getInstance()->getInfo(gDebugInfo);
+
+ // Close the debug file
+ pApp->writeDebugInfo();
+
+ LLError::logToFile("");
+
+ // Remove the marker file, since otherwise we'll spawn a process that'll keep it locked
+ if(gDebugInfo["LastExecEvent"].asInteger() == LAST_EXEC_LOGOUT_CRASH)
+ {
+ pApp->removeMarkerFile(true);
+ }
+ else
+ {
+ pApp->removeMarkerFile(false);
+ }
+
+#if LL_SEND_CRASH_REPORTS
+ // Call to pure virtual, handled by platform specific llappviewer instance.
+ pApp->handleCrashReporting();
+#endif
+
+ return;
+}
+
+bool LLAppViewer::anotherInstanceRunning()
+{
+ // We create a marker file when the program starts and remove the file when it finishes.
+ // If the file is currently locked, that means another process is already running.
+
+ std::string marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, MARKER_FILE_NAME);
+ LL_DEBUGS("MarkerFile") << "Checking marker file for lock..." << LL_ENDL;
+
+ //Freeze case checks
+ if (LLAPRFile::isExist(marker_file, NULL, LL_APR_RB))
+ {
+ // File exists, try opening with write permissions
+ LLAPRFile outfile ;
+ outfile.open(marker_file, LL_APR_WB);
+ apr_file_t* fMarker = outfile.getFileHandle() ;
+ if (!fMarker)
+ {
+ // Another instance is running. Skip the rest of these operations.
+ LL_INFOS("MarkerFile") << "Marker file is locked." << LL_ENDL;
+ return true;
+ }
+ if (apr_file_lock(fMarker, APR_FLOCK_NONBLOCK | APR_FLOCK_EXCLUSIVE) != APR_SUCCESS) //flock(fileno(fMarker), LOCK_EX | LOCK_NB) == -1)
+ {
+ LL_INFOS("MarkerFile") << "Marker file is locked." << LL_ENDL;
+ return true;
+ }
+ // No other instances; we'll lock this file now & delete on quit.
+ }
+ LL_DEBUGS("MarkerFile") << "Marker file isn't locked." << LL_ENDL;
+ return false;
+}
+
+void LLAppViewer::initMarkerFile()
+{
+ //First, check for the existence of other files.
+ //There are marker files for two different types of crashes
+
+ mMarkerFileName = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,MARKER_FILE_NAME);
+ LL_DEBUGS("MarkerFile") << "Checking marker file for lock..." << LL_ENDL;
+
+ //We've got 4 things to test for here
+ // - Other Process Running (SecondLife.exec_marker present, locked)
+ // - Freeze (SecondLife.exec_marker present, not locked)
+ // - LLError Crash (SecondLife.llerror_marker present)
+ // - Other Crash (SecondLife.error_marker present)
+ // These checks should also remove these files for the last 2 cases if they currently exist
+
+ //LLError/Error checks. Only one of these should ever happen at a time.
+ std::string logout_marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, LOGOUT_MARKER_FILE_NAME);
+ std::string llerror_marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, LLERROR_MARKER_FILE_NAME);
+ std::string error_marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, ERROR_MARKER_FILE_NAME);
+
+ if (LLAPRFile::isExist(mMarkerFileName, NULL, LL_APR_RB) && !anotherInstanceRunning())
+ {
+ gLastExecEvent = LAST_EXEC_FROZE;
+ LL_INFOS("MarkerFile") << "Exec marker found: program froze on previous execution" << LL_ENDL;
+ }
+ if(LLAPRFile::isExist(logout_marker_file, NULL, LL_APR_RB))
+ {
+ gLastExecEvent = LAST_EXEC_LOGOUT_FROZE;
+ LL_INFOS("MarkerFile") << "Last exec LLError crashed, setting LastExecEvent to " << gLastExecEvent << LL_ENDL;
+ LLAPRFile::remove(logout_marker_file);
+ }
+ if(LLAPRFile::isExist(llerror_marker_file, NULL, LL_APR_RB))
+ {
+ if(gLastExecEvent == LAST_EXEC_LOGOUT_FROZE) gLastExecEvent = LAST_EXEC_LOGOUT_CRASH;
+ else gLastExecEvent = LAST_EXEC_LLERROR_CRASH;
+ LL_INFOS("MarkerFile") << "Last exec LLError crashed, setting LastExecEvent to " << gLastExecEvent << LL_ENDL;
+ LLAPRFile::remove(llerror_marker_file);
+ }
+ if(LLAPRFile::isExist(error_marker_file, NULL, LL_APR_RB))
+ {
+ if(gLastExecEvent == LAST_EXEC_LOGOUT_FROZE) gLastExecEvent = LAST_EXEC_LOGOUT_CRASH;
+ else gLastExecEvent = LAST_EXEC_OTHER_CRASH;
+ LL_INFOS("MarkerFile") << "Last exec crashed, setting LastExecEvent to " << gLastExecEvent << LL_ENDL;
+ LLAPRFile::remove(error_marker_file);
+ }
+
+ // No new markers if another instance is running.
+ if(anotherInstanceRunning())
+ {
+ return;
+ }
+
+ // Create the marker file for this execution & lock it
+ apr_status_t s;
+ s = mMarkerFile.open(mMarkerFileName, LL_APR_W, TRUE);
+
+ if (s == APR_SUCCESS && mMarkerFile.getFileHandle())
+ {
+ LL_DEBUGS("MarkerFile") << "Marker file created." << LL_ENDL;
+ }
+ else
+ {
+ LL_INFOS("MarkerFile") << "Failed to create marker file." << LL_ENDL;
+ return;
+ }
+ if (apr_file_lock(mMarkerFile.getFileHandle(), APR_FLOCK_NONBLOCK | APR_FLOCK_EXCLUSIVE) != APR_SUCCESS)
+ {
+ mMarkerFile.close() ;
+ LL_INFOS("MarkerFile") << "Marker file cannot be locked." << LL_ENDL;
+ return;
+ }
+
+ LL_DEBUGS("MarkerFile") << "Marker file locked." << LL_ENDL;
+}
+
+void LLAppViewer::removeMarkerFile(bool leave_logout_marker)
+{
+ LL_DEBUGS("MarkerFile") << "removeMarkerFile()" << LL_ENDL;
+ if (mMarkerFile.getFileHandle())
+ {
+ mMarkerFile.close() ;
+ LLAPRFile::remove( mMarkerFileName );
+ }
+ if (mLogoutMarkerFile != NULL && !leave_logout_marker)
+ {
+ LLAPRFile::remove( mLogoutMarkerFileName );
+ mLogoutMarkerFile = NULL;
+ }
+}
+
+void LLAppViewer::forceQuit()
+{
+ LLApp::setQuitting();
+}
+
+//TODO: remove
+void LLAppViewer::fastQuit(S32 error_code)
+{
+ // finish pending transfers
+ flushVFSIO();
+ // let sim know we're logging out
+ sendLogoutRequest();
+ // flush network buffers by shutting down messaging system
+ end_messaging_system();
+ // figure out the error code
+ S32 final_error_code = error_code ? error_code : (S32)isError();
+ // this isn't a crash
+ removeMarkerFile();
+ // get outta here
+ _exit(final_error_code);
+}
+
+void LLAppViewer::requestQuit()
+{
+ llinfos << "requestQuit" << llendl;
+
+ LLViewerRegion* region = gAgent.getRegion();
+
+ if( (LLStartUp::getStartupState() < STATE_STARTED) || !region )
+ {
+ // If we have a region, make some attempt to send a logout request first.
+ // This prevents the halfway-logged-in avatar from hanging around inworld for a couple minutes.
+ if(region)
+ {
+ sendLogoutRequest();
+ }
+
+ // Quit immediately
+ forceQuit();
+ return;
+ }
+
+ // Try to send metrics back to the grid
+ metricsSend(!gDisconnected);
+
+ LLHUDEffectSpiral *effectp = (LLHUDEffectSpiral*)LLHUDManager::getInstance()->createViewerEffect(LLHUDObject::LL_HUD_EFFECT_POINT, TRUE);
+ effectp->setPositionGlobal(gAgent.getPositionGlobal());
+ effectp->setColor(LLColor4U(gAgent.getEffectColor()));
+ LLHUDManager::getInstance()->sendEffects();
+ effectp->markDead() ;//remove it.
+
+ // Attempt to close all floaters that might be
+ // editing things.
+ if (gFloaterView)
+ {
+ // application is quitting
+ gFloaterView->closeAllChildren(true);
+ }
+
+ LLSideTray::getInstance()->notifyChildren(LLSD().with("request","quit"));
+
+ send_stats();
+
+ gLogoutTimer.reset();
+ mQuitRequested = true;
+}
+
+static bool finish_quit(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+
+ if (option == 0)
+ {
+ LLAppViewer::instance()->requestQuit();
+ }
+ return false;
+}
+static LLNotificationFunctorRegistration finish_quit_reg("ConfirmQuit", finish_quit);
+
+static bool switch_standard_skin_and_quit(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+
+ if (option == 0)
+ {
+ gSavedSettings.setString("SessionSettingsFile", "");
+ LLAppViewer::instance()->requestQuit();
+ }
+ return false;
+}
+
+static LLNotificationFunctorRegistration standard_skin_quit_reg("SwitchToStandardSkinAndQuit", switch_standard_skin_and_quit);
+
+void LLAppViewer::userQuit()
+{
+ if (gDisconnected || gViewerWindow->getProgressView()->getVisible())
+ {
+ requestQuit();
+ }
+ else
+ {
+ LLNotificationsUtil::add("ConfirmQuit");
+ }
+}
+
+static bool finish_early_exit(const LLSD& notification, const LLSD& response)
+{
+ LLAppViewer::instance()->forceQuit();
+ return false;
+}
+
+void LLAppViewer::earlyExit(const std::string& name, const LLSD& substitutions)
+{
+ llwarns << "app_early_exit: " << name << llendl;
+ gDoDisconnect = TRUE;
+ LLNotificationsUtil::add(name, substitutions, LLSD(), finish_early_exit);
+}
+
+// case where we need the viewer to exit without any need for notifications
+void LLAppViewer::earlyExitNoNotify()
+{
+ llwarns << "app_early_exit with no notification: " << llendl;
+ gDoDisconnect = TRUE;
+ finish_early_exit( LLSD(), LLSD() );
+}
+
+void LLAppViewer::abortQuit()
+{
+ llinfos << "abortQuit()" << llendl;
+ mQuitRequested = false;
+}
+
+void LLAppViewer::migrateCacheDirectory()
+{
+#if LL_WINDOWS || LL_DARWIN
+ // NOTE: (Nyx) as of 1.21, cache for mac is moving to /library/caches/SecondLife from
+ // /library/application support/SecondLife/cache This should clear/delete the old dir.
+
+ // As of 1.23 the Windows cache moved from
+ // C:\Documents and Settings\James\Application Support\SecondLife\cache
+ // to
+ // C:\Documents and Settings\James\Local Settings\Application Support\SecondLife
+ //
+ // The Windows Vista equivalent is from
+ // C:\Users\James\AppData\Roaming\SecondLife\cache
+ // to
+ // C:\Users\James\AppData\Local\SecondLife
+ //
+ // Note the absence of \cache on the second path. James.
+
+ // Only do this once per fresh install of this version.
+ if (gSavedSettings.getBOOL("MigrateCacheDirectory"))
+ {
+ gSavedSettings.setBOOL("MigrateCacheDirectory", FALSE);
+
+ std::string delimiter = gDirUtilp->getDirDelimiter();
+ std::string old_cache_dir = gDirUtilp->getOSUserAppDir() + delimiter + "cache";
+ std::string new_cache_dir = gDirUtilp->getCacheDir(true);
+
+ if (gDirUtilp->fileExists(old_cache_dir))
+ {
+ llinfos << "Migrating cache from " << old_cache_dir << " to " << new_cache_dir << llendl;
+
+ // Migrate inventory cache to avoid pain to inventory database after mass update
+ S32 file_count = 0;
+ std::string file_name;
+ std::string mask = delimiter + "*.*";
+ while (gDirUtilp->getNextFileInDir(old_cache_dir, mask, file_name))
+ {
+ if (file_name == "." || file_name == "..") continue;
+ std::string source_path = old_cache_dir + delimiter + file_name;
+ std::string dest_path = new_cache_dir + delimiter + file_name;
+ if (!LLFile::rename(source_path, dest_path))
+ {
+ file_count++;
+ }
+ }
+ llinfos << "Moved " << file_count << " files" << llendl;
+
+ // Nuke the old cache
+ gDirUtilp->setCacheDir(old_cache_dir);
+ purgeCache();
+ gDirUtilp->setCacheDir(new_cache_dir);
+
+#if LL_DARWIN
+ // Clean up Mac files not deleted by removing *.*
+ std::string ds_store = old_cache_dir + "/.DS_Store";
+ if (gDirUtilp->fileExists(ds_store))
+ {
+ LLFile::remove(ds_store);
+ }
+#endif
+ if (LLFile::rmdir(old_cache_dir) != 0)
+ {
+ llwarns << "could not delete old cache directory " << old_cache_dir << llendl;
+ }
+ }
+ }
+#endif // LL_WINDOWS || LL_DARWIN
+}
+
+void dumpVFSCaches()
+{
+ llinfos << "======= Static VFS ========" << llendl;
+ gStaticVFS->listFiles();
+#if LL_WINDOWS
+ llinfos << "======= Dumping static VFS to StaticVFSDump ========" << llendl;
+ WCHAR w_str[MAX_PATH];
+ GetCurrentDirectory(MAX_PATH, w_str);
+ S32 res = LLFile::mkdir("StaticVFSDump");
+ if (res == -1)
+ {
+ if (errno != EEXIST)
+ {
+ llwarns << "Couldn't create dir StaticVFSDump" << llendl;
+ }
+ }
+ SetCurrentDirectory(utf8str_to_utf16str("StaticVFSDump").c_str());
+ gStaticVFS->dumpFiles();
+ SetCurrentDirectory(w_str);
+#endif
+
+ llinfos << "========= Dynamic VFS ====" << llendl;
+ gVFS->listFiles();
+#if LL_WINDOWS
+ llinfos << "========= Dumping dynamic VFS to VFSDump ====" << llendl;
+ res = LLFile::mkdir("VFSDump");
+ if (res == -1)
+ {
+ if (errno != EEXIST)
+ {
+ llwarns << "Couldn't create dir VFSDump" << llendl;
+ }
+ }
+ SetCurrentDirectory(utf8str_to_utf16str("VFSDump").c_str());
+ gVFS->dumpFiles();
+ SetCurrentDirectory(w_str);
+#endif
+}
+
+//static
+U32 LLAppViewer::getTextureCacheVersion()
+{
+ //viewer texture cache version, change if the texture cache format changes.
+ const U32 TEXTURE_CACHE_VERSION = 7;
+
+ return TEXTURE_CACHE_VERSION ;
+}
+
+//static
+U32 LLAppViewer::getObjectCacheVersion()
+{
+ // Viewer object cache version, change if object update
+ // format changes. JC
+ const U32 INDRA_OBJECT_CACHE_VERSION = 14;
+
+ return INDRA_OBJECT_CACHE_VERSION;
+}
+
+bool LLAppViewer::initCache()
+{
+ mPurgeCache = false;
+ BOOL read_only = mSecondInstance ? TRUE : FALSE;
+ LLAppViewer::getTextureCache()->setReadOnly(read_only) ;
+ LLVOCache::getInstance()->setReadOnly(read_only);
+
+ BOOL texture_cache_mismatch = FALSE ;
+ if (gSavedSettings.getS32("LocalCacheVersion") != LLAppViewer::getTextureCacheVersion())
+ {
+ texture_cache_mismatch = TRUE ;
+ if(!read_only)
+ {
+ gSavedSettings.setS32("LocalCacheVersion", LLAppViewer::getTextureCacheVersion());
+ }
+ }
+
+ if(!read_only)
+ {
+ // Purge cache if user requested it
+ if (gSavedSettings.getBOOL("PurgeCacheOnStartup") ||
+ gSavedSettings.getBOOL("PurgeCacheOnNextStartup"))
+ {
+ gSavedSettings.setBOOL("PurgeCacheOnNextStartup", false);
+ mPurgeCache = true;
+ }
+
+ // We have moved the location of the cache directory over time.
+ migrateCacheDirectory();
+
+ // Setup and verify the cache location
+ std::string cache_location = gSavedSettings.getString("CacheLocation");
+ std::string new_cache_location = gSavedSettings.getString("NewCacheLocation");
+ if (new_cache_location != cache_location)
+ {
+ gDirUtilp->setCacheDir(gSavedSettings.getString("CacheLocation"));
+ purgeCache(); // purge old cache
+ gSavedSettings.setString("CacheLocation", new_cache_location);
+ gSavedSettings.setString("CacheLocationTopFolder", gDirUtilp->getBaseFileName(new_cache_location));
+ }
+ }
+
+ if (!gDirUtilp->setCacheDir(gSavedSettings.getString("CacheLocation")))
+ {
+ LL_WARNS("AppCache") << "Unable to set cache location" << LL_ENDL;
+ gSavedSettings.setString("CacheLocation", "");
+ gSavedSettings.setString("CacheLocationTopFolder", "");
+ }
+
+ if (mPurgeCache && !read_only)
+ {
+ LLSplashScreen::update(LLTrans::getString("StartupClearingCache"));
+ purgeCache();
+ }
+
+ LLSplashScreen::update(LLTrans::getString("StartupInitializingTextureCache"));
+
+ // Init the texture cache
+ // Allocate 80% of the cache size for textures
+ const S32 MB = 1024*1024;
+ S64 cache_size = (S64)(gSavedSettings.getU32("CacheSize")) * MB;
+ const S64 MAX_CACHE_SIZE = 1024*MB;
+ cache_size = llmin(cache_size, MAX_CACHE_SIZE);
+ S64 texture_cache_size = ((cache_size * 8)/10);
+ S64 extra = LLAppViewer::getTextureCache()->initCache(LL_PATH_CACHE, texture_cache_size, texture_cache_mismatch);
+ texture_cache_size -= extra;
+
+ LLVOCache::getInstance()->initCache(LL_PATH_CACHE, gSavedSettings.getU32("CacheNumberOfRegionsForObjects"), getObjectCacheVersion()) ;
+
+ LLSplashScreen::update(LLTrans::getString("StartupInitializingVFS"));
+
+ // Init the VFS
+ S64 vfs_size = cache_size - texture_cache_size;
+ const S64 MAX_VFS_SIZE = 1024 * MB; // 1 GB
+ vfs_size = llmin(vfs_size, MAX_VFS_SIZE);
+ vfs_size = (vfs_size / MB) * MB; // make sure it is MB aligned
+ U32 vfs_size_u32 = (U32)vfs_size;
+ U32 old_vfs_size = gSavedSettings.getU32("VFSOldSize") * MB;
+ bool resize_vfs = (vfs_size_u32 != old_vfs_size);
+ if (resize_vfs)
+ {
+ gSavedSettings.setU32("VFSOldSize", vfs_size_u32/MB);
+ }
+ LL_INFOS("AppCache") << "VFS CACHE SIZE: " << vfs_size/(1024*1024) << " MB" << LL_ENDL;
+
+ // This has to happen BEFORE starting the vfs
+ //time_t ltime;
+ srand(time(NULL)); // Flawfinder: ignore
+ U32 old_salt = gSavedSettings.getU32("VFSSalt");
+ U32 new_salt;
+ std::string old_vfs_data_file;
+ std::string old_vfs_index_file;
+ std::string new_vfs_data_file;
+ std::string new_vfs_index_file;
+ std::string static_vfs_index_file;
+ std::string static_vfs_data_file;
+
+ if (gSavedSettings.getBOOL("AllowMultipleViewers"))
+ {
+ // don't mess with renaming the VFS in this case
+ new_salt = old_salt;
+ }
+ else
+ {
+ do
+ {
+ new_salt = rand();
+ } while( new_salt == old_salt );
+ }
+
+ old_vfs_data_file = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,VFS_DATA_FILE_BASE) + llformat("%u",old_salt);
+
+ // make sure this file exists
+ llstat s;
+ S32 stat_result = LLFile::stat(old_vfs_data_file, &s);
+ if (stat_result)
+ {
+ // doesn't exist, look for a data file
+ std::string mask;
+ mask = gDirUtilp->getDirDelimiter();
+ mask += VFS_DATA_FILE_BASE;
+ mask += "*";
+
+ std::string dir;
+ dir = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,"");
+
+ std::string found_file;
+ if (gDirUtilp->getNextFileInDir(dir, mask, found_file))
+ {
+ old_vfs_data_file = dir + gDirUtilp->getDirDelimiter() + found_file;
+
+ S32 start_pos = found_file.find_last_of('.');
+ if (start_pos > 0)
+ {
+ sscanf(found_file.substr(start_pos+1).c_str(), "%d", &old_salt);
+ }
+ LL_DEBUGS("AppCache") << "Default vfs data file not present, found: " << old_vfs_data_file << " Old salt: " << old_salt << llendl;
+ }
+ }
+
+ old_vfs_index_file = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,VFS_INDEX_FILE_BASE) + llformat("%u",old_salt);
+
+ stat_result = LLFile::stat(old_vfs_index_file, &s);
+ if (stat_result)
+ {
+ // We've got a bad/missing index file, nukem!
+ LL_WARNS("AppCache") << "Bad or missing vfx index file " << old_vfs_index_file << LL_ENDL;
+ LL_WARNS("AppCache") << "Removing old vfs data file " << old_vfs_data_file << LL_ENDL;
+ LLFile::remove(old_vfs_data_file);
+ LLFile::remove(old_vfs_index_file);
+
+ // Just in case, nuke any other old cache files in the directory.
+ std::string dir;
+ dir = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,"");
+
+ std::string mask;
+ mask = gDirUtilp->getDirDelimiter();
+ mask += VFS_DATA_FILE_BASE;
+ mask += "*";
+
+ gDirUtilp->deleteFilesInDir(dir, mask);
+
+ mask = gDirUtilp->getDirDelimiter();
+ mask += VFS_INDEX_FILE_BASE;
+ mask += "*";
+
+ gDirUtilp->deleteFilesInDir(dir, mask);
+ }
+
+ new_vfs_data_file = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,VFS_DATA_FILE_BASE) + llformat("%u",new_salt);
+ new_vfs_index_file = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, VFS_INDEX_FILE_BASE) + llformat("%u",new_salt);
+
+ static_vfs_data_file = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"static_data.db2");
+ static_vfs_index_file = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"static_index.db2");
+
+ if (resize_vfs)
+ {
+ LL_DEBUGS("AppCache") << "Removing old vfs and re-sizing" << LL_ENDL;
+
+ LLFile::remove(old_vfs_data_file);
+ LLFile::remove(old_vfs_index_file);
+ }
+ else if (old_salt != new_salt)
+ {
+ // move the vfs files to a new name before opening
+ LL_DEBUGS("AppCache") << "Renaming " << old_vfs_data_file << " to " << new_vfs_data_file << LL_ENDL;
+ LL_DEBUGS("AppCache") << "Renaming " << old_vfs_index_file << " to " << new_vfs_index_file << LL_ENDL;
+ LLFile::rename(old_vfs_data_file, new_vfs_data_file);
+ LLFile::rename(old_vfs_index_file, new_vfs_index_file);
+ }
+
+ // Startup the VFS...
+ gSavedSettings.setU32("VFSSalt", new_salt);
+
+ // Don't remove VFS after viewer crashes. If user has corrupt data, they can reinstall. JC
+ gVFS = LLVFS::createLLVFS(new_vfs_index_file, new_vfs_data_file, false, vfs_size_u32, false);
+ if( !gVFS )
+ {
+ return false;
+ }
+
+ gStaticVFS = LLVFS::createLLVFS(static_vfs_index_file, static_vfs_data_file, true, 0, false);
+ if( !gStaticVFS )
+ {
+ return false;
+ }
+
+ BOOL success = gVFS->isValid() && gStaticVFS->isValid();
+ if( !success )
+ {
+ return false;
+ }
+ else
+ {
+ LLVFile::initClass();
+
+#ifndef LL_RELEASE_FOR_DOWNLOAD
+ if (gSavedSettings.getBOOL("DumpVFSCaches"))
+ {
+ dumpVFSCaches();
+ }
+#endif
+
+ return true;
+ }
+}
+
+void LLAppViewer::purgeCache()
+{
+ LL_INFOS("AppCache") << "Purging Cache and Texture Cache..." << llendl;
+ LLAppViewer::getTextureCache()->purgeCache(LL_PATH_CACHE);
+ LLVOCache::getInstance()->removeCache(LL_PATH_CACHE);
+ std::string mask = gDirUtilp->getDirDelimiter() + "*.*";
+ gDirUtilp->deleteFilesInDir(gDirUtilp->getExpandedFilename(LL_PATH_CACHE,""),mask);
+}
+
+std::string LLAppViewer::getSecondLifeTitle() const
+{
+ return LLTrans::getString("APP_NAME");
+}
+
+std::string LLAppViewer::getWindowTitle() const
+{
+ return gWindowTitle;
+}
+
+// Callback from a dialog indicating user was logged out.
+bool finish_disconnect(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+
+ if (1 == option)
+ {
+ LLAppViewer::instance()->forceQuit();
+ }
+ return false;
+}
+
+// Callback from an early disconnect dialog, force an exit
+bool finish_forced_disconnect(const LLSD& notification, const LLSD& response)
+{
+ LLAppViewer::instance()->forceQuit();
+ return false;
+}
+
+
+void LLAppViewer::forceDisconnect(const std::string& mesg)
+{
+ if (gDoDisconnect)
+ {
+ // Already popped up one of these dialogs, don't
+ // do this again.
+ return;
+ }
+
+ // *TODO: Translate the message if possible
+ std::string big_reason = LLAgent::sTeleportErrorMessages[mesg];
+ if ( big_reason.size() == 0 )
+ {
+ big_reason = mesg;
+ }
+
+ LLSD args;
+ gDoDisconnect = TRUE;
+
+ if (LLStartUp::getStartupState() < STATE_STARTED)
+ {
+ // Tell users what happened
+ args["ERROR_MESSAGE"] = big_reason;
+ LLNotificationsUtil::add("ErrorMessage", args, LLSD(), &finish_forced_disconnect);
+ }
+ else
+ {
+ args["MESSAGE"] = big_reason;
+ LLNotificationsUtil::add("YouHaveBeenLoggedOut", args, LLSD(), &finish_disconnect );
+ }
+}
+
+void LLAppViewer::badNetworkHandler()
+{
+ // Dump the packet
+ gMessageSystem->dumpPacketToLog();
+
+ // Flush all of our caches on exit in the case of disconnect due to
+ // invalid packets.
+
+ mPurgeOnExit = TRUE;
+
+ std::ostringstream message;
+ message <<
+ "The viewer has detected mangled network data indicative\n"
+ "of a bad upstream network connection or an incomplete\n"
+ "local installation of " << LLAppViewer::instance()->getSecondLifeTitle() << ". \n"
+ " \n"
+ "Try uninstalling and reinstalling to see if this resolves \n"
+ "the issue. \n"
+ " \n"
+ "If the problem continues, see the Tech Support FAQ at: \n"
+ "www.secondlife.com/support";
+ forceDisconnect(message.str());
+
+ LLApp::instance()->writeMiniDump();
+}
+
+// This routine may get called more than once during the shutdown process.
+// This can happen because we need to get the screenshot before the window
+// is destroyed.
+void LLAppViewer::saveFinalSnapshot()
+{
+ if (!mSavedFinalSnapshot && !gNoRender)
+ {
+ gSavedSettings.setVector3d("FocusPosOnLogout", gAgentCamera.calcFocusPositionTargetGlobal());
+ gSavedSettings.setVector3d("CameraPosOnLogout", gAgentCamera.calcCameraPositionTargetGlobal());
+ gViewerWindow->setCursor(UI_CURSOR_WAIT);
+ gAgentCamera.changeCameraToThirdPerson( FALSE ); // don't animate, need immediate switch
+ gSavedSettings.setBOOL("ShowParcelOwners", FALSE);
+ idle();
+
+ std::string snap_filename = gDirUtilp->getLindenUserDir();
+ snap_filename += gDirUtilp->getDirDelimiter();
+ snap_filename += SCREEN_LAST_FILENAME;
+ // use full pixel dimensions of viewer window (not post-scale dimensions)
+ gViewerWindow->saveSnapshot(snap_filename, gViewerWindow->getWindowWidthRaw(), gViewerWindow->getWindowHeightRaw(), FALSE, TRUE);
+ mSavedFinalSnapshot = TRUE;
+ }
+}
+
+void LLAppViewer::loadNameCache()
+{
+ // display names cache
+ std::string filename =
+ gDirUtilp->getExpandedFilename(LL_PATH_CACHE, "avatar_name_cache.xml");
+ LL_INFOS("AvNameCache") << filename << LL_ENDL;
+ llifstream name_cache_stream(filename);
+ if(name_cache_stream.is_open())
+ {
+ LLAvatarNameCache::importFile(name_cache_stream);
+ }
+
+ if (!gCacheName) return;
+
+ std::string name_cache;
+ name_cache = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, "name.cache");
+ llifstream cache_file(name_cache);
+ if(cache_file.is_open())
+ {
+ if(gCacheName->importFile(cache_file)) return;
+ }
+}
+
+void LLAppViewer::saveNameCache()
+ {
+ // display names cache
+ std::string filename =
+ gDirUtilp->getExpandedFilename(LL_PATH_CACHE, "avatar_name_cache.xml");
+ llofstream name_cache_stream(filename);
+ if(name_cache_stream.is_open())
+ {
+ LLAvatarNameCache::exportFile(name_cache_stream);
+}
+
+ if (!gCacheName) return;
+
+ std::string name_cache;
+ name_cache = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, "name.cache");
+ llofstream cache_file(name_cache);
+ if(cache_file.is_open())
+ {
+ gCacheName->exportFile(cache_file);
+ }
+}
+
+/*! @brief This class is an LLFrameTimer that can be created with
+ an elapsed time that starts counting up from the given value
+ rather than 0.0.
+
+ Otherwise it behaves the same way as LLFrameTimer.
+*/
+class LLFrameStatsTimer : public LLFrameTimer
+{
+public:
+ LLFrameStatsTimer(F64 elapsed_already = 0.0)
+ : LLFrameTimer()
+ {
+ mStartTime -= elapsed_already;
+ }
+};
+
+static LLFastTimer::DeclareTimer FTM_AUDIO_UPDATE("Update Audio");
+static LLFastTimer::DeclareTimer FTM_CLEANUP("Cleanup");
+static LLFastTimer::DeclareTimer FTM_IDLE_CB("Idle Callbacks");
+static LLFastTimer::DeclareTimer FTM_LOD_UPDATE("Update LOD");
+static LLFastTimer::DeclareTimer FTM_OBJECTLIST_UPDATE("Update Objectlist");
+static LLFastTimer::DeclareTimer FTM_REGION_UPDATE("Update Region");
+static LLFastTimer::DeclareTimer FTM_WORLD_UPDATE("Update World");
+static LLFastTimer::DeclareTimer FTM_NETWORK("Network");
+static LLFastTimer::DeclareTimer FTM_AGENT_NETWORK("Agent Network");
+static LLFastTimer::DeclareTimer FTM_VLMANAGER("VL Manager");
+
+///////////////////////////////////////////////////////
+// idle()
+//
+// Called every time the window is not doing anything.
+// Receive packets, update statistics, and schedule a redisplay.
+///////////////////////////////////////////////////////
+void LLAppViewer::idle()
+{
+ LLMemType mt_idle(LLMemType::MTYPE_IDLE);
+ pingMainloopTimeout("Main:Idle");
+
+ // Update frame timers
+ static LLTimer idle_timer;
+
+ LLFrameTimer::updateFrameTime();
+ LLFrameTimer::updateFrameCount();
+ LLEventTimer::updateClass();
+ LLCriticalDamp::updateInterpolants();
+ LLMortician::updateClass();
+ LLFilePickerThread::clearDead(); //calls LLFilePickerThread::notify()
+
+ F32 dt_raw = idle_timer.getElapsedTimeAndResetF32();
+
+ // Cap out-of-control frame times
+ // Too low because in menus, swapping, debugger, etc.
+ // Too high because idle called with no objects in view, etc.
+ const F32 MIN_FRAME_RATE = 1.f;
+ const F32 MAX_FRAME_RATE = 200.f;
+
+ F32 frame_rate_clamped = 1.f / dt_raw;
+ frame_rate_clamped = llclamp(frame_rate_clamped, MIN_FRAME_RATE, MAX_FRAME_RATE);
+ gFrameDTClamped = 1.f / frame_rate_clamped;
+
+ // Global frame timer
+ // Smoothly weight toward current frame
+ gFPSClamped = (frame_rate_clamped + (4.f * gFPSClamped)) / 5.f;
+
+ F32 qas = gSavedSettings.getF32("QuitAfterSeconds");
+ if (qas > 0.f)
+ {
+ if (gRenderStartTime.getElapsedTimeF32() > qas)
+ {
+ LLAppViewer::instance()->forceQuit();
+ }
+ }
+
+ // debug setting to quit after N seconds of being AFK - 0 to never do this
+ F32 qas_afk = gSavedSettings.getF32("QuitAfterSecondsOfAFK");
+ if (qas_afk > 0.f)
+ {
+ // idle time is more than setting
+ if ( gAwayTriggerTimer.getElapsedTimeF32() > qas_afk )
+ {
+ // go ahead and just quit gracefully
+ LLAppViewer::instance()->requestQuit();
+ }
+ }
+
+ // Must wait until both have avatar object and mute list, so poll
+ // here.
+ request_initial_instant_messages();
+
+ ///////////////////////////////////
+ //
+ // Special case idle if still starting up
+ //
+ if (LLStartUp::getStartupState() < STATE_STARTED)
+ {
+ // Skip rest if idle startup returns false (essentially, no world yet)
+ gGLActive = TRUE;
+ if (!idle_startup())
+ {
+ gGLActive = FALSE;
+ return;
+ }
+ gGLActive = FALSE;
+ }
+
+
+ F32 yaw = 0.f; // radians
+
+ if (!gDisconnected)
+ {
+ LLFastTimer t(FTM_NETWORK);
+ // Update spaceserver timeinfo
+ LLWorld::getInstance()->setSpaceTimeUSec(LLWorld::getInstance()->getSpaceTimeUSec() + (U32)(dt_raw * SEC_TO_MICROSEC));
+
+
+ //////////////////////////////////////
+ //
+ // Update simulator agent state
+ //
+
+ if (gSavedSettings.getBOOL("RotateRight"))
+ {
+ gAgent.moveYaw(-1.f);
+ }
+
+ {
+ LLFastTimer t(FTM_AGENT_AUTOPILOT);
+ // Handle automatic walking towards points
+ gAgentPilot.updateTarget();
+ gAgent.autoPilot(&yaw);
+ }
+
+ static LLFrameTimer agent_update_timer;
+ static U32 last_control_flags;
+
+ // When appropriate, update agent location to the simulator.
+ F32 agent_update_time = agent_update_timer.getElapsedTimeF32();
+ BOOL flags_changed = gAgent.controlFlagsDirty() || (last_control_flags != gAgent.getControlFlags());
+
+ if (flags_changed || (agent_update_time > (1.0f / (F32) AGENT_UPDATES_PER_SECOND)))
+ {
+ LLFastTimer t(FTM_AGENT_UPDATE);
+ // Send avatar and camera info
+ last_control_flags = gAgent.getControlFlags();
+ send_agent_update(TRUE);
+ agent_update_timer.reset();
+ }
+ }
+
+ //////////////////////////////////////
+ //
+ // Manage statistics
+ //
+ //
+ {
+ // Initialize the viewer_stats_timer with an already elapsed time
+ // of SEND_STATS_PERIOD so that the initial stats report will
+ // be sent immediately.
+ static LLFrameStatsTimer viewer_stats_timer(SEND_STATS_PERIOD);
+ reset_statistics();
+
+ // Update session stats every large chunk of time
+ // *FIX: (???) SAMANTHA
+ if (viewer_stats_timer.getElapsedTimeF32() >= SEND_STATS_PERIOD && !gDisconnected)
+ {
+ llinfos << "Transmitting sessions stats" << llendl;
+ send_stats();
+ viewer_stats_timer.reset();
+ }
+
+ // Print the object debugging stats
+ static LLFrameTimer object_debug_timer;
+ if (object_debug_timer.getElapsedTimeF32() > 5.f)
+ {
+ object_debug_timer.reset();
+ if (gObjectList.mNumDeadObjectUpdates)
+ {
+ llinfos << "Dead object updates: " << gObjectList.mNumDeadObjectUpdates << llendl;
+ gObjectList.mNumDeadObjectUpdates = 0;
+ }
+ if (gObjectList.mNumUnknownKills)
+ {
+ llinfos << "Kills on unknown objects: " << gObjectList.mNumUnknownKills << llendl;
+ gObjectList.mNumUnknownKills = 0;
+ }
+ if (gObjectList.mNumUnknownUpdates)
+ {
+ llinfos << "Unknown object updates: " << gObjectList.mNumUnknownUpdates << llendl;
+ gObjectList.mNumUnknownUpdates = 0;
+ }
+
+ // ViewerMetrics FPS piggy-backing on the debug timer.
+ // The 5-second interval is nice for this purpose. If the object debug
+ // bit moves or is disabled, please give this a suitable home.
+ LLViewerAssetStatsFF::record_fps_main(gFPSClamped);
+ }
+ }
+
+ if (!gDisconnected)
+ {
+ LLFastTimer t(FTM_NETWORK);
+
+ ////////////////////////////////////////////////
+ //
+ // Network processing
+ //
+ // NOTE: Starting at this point, we may still have pointers to "dead" objects
+ // floating throughout the various object lists.
+ //
+ idleNameCache();
+
+ idleNetwork();
+
+
+ // Check for away from keyboard, kick idle agents.
+ idle_afk_check();
+
+ // Update statistics for this frame
+ update_statistics(gFrameCount);
+ }
+
+ ////////////////////////////////////////
+ //
+ // Handle the regular UI idle callbacks as well as
+ // hover callbacks
+ //
+
+ {
+// LLFastTimer t(FTM_IDLE_CB);
+
+ // Do event notifications if necessary. Yes, we may want to move this elsewhere.
+ gEventNotifier.update();
+
+ gIdleCallbacks.callFunctions();
+ gInventory.idleNotifyObservers();
+ }
+
+ // Metrics logging (LLViewerAssetStats, etc.)
+ {
+ static LLTimer report_interval;
+
+ // *TODO: Add configuration controls for this
+ if (report_interval.getElapsedTimeF32() >= app_metrics_interval)
+ {
+ metricsSend(! gDisconnected);
+ report_interval.reset();
+ }
+ }
+
+ if (gDisconnected)
+ {
+ return;
+ }
+
+ gViewerWindow->updateUI();
+
+ ///////////////////////////////////////
+ // Agent and camera movement
+ //
+ LLCoordGL current_mouse = gViewerWindow->getCurrentMouse();
+
+ {
+ // After agent and camera moved, figure out if we need to
+ // deselect objects.
+ LLSelectMgr::getInstance()->deselectAllIfTooFar();
+
+ }
+
+ {
+ // Handle pending gesture processing
+ static LLFastTimer::DeclareTimer ftm("Agent Position");
+ LLFastTimer t(ftm);
+ LLGestureMgr::instance().update();
+
+ gAgent.updateAgentPosition(gFrameDTClamped, yaw, current_mouse.mX, current_mouse.mY);
+ }
+
+ {
+ LLFastTimer t(FTM_OBJECTLIST_UPDATE);
+
+ if (!(logoutRequestSent() && hasSavedFinalSnapshot()))
+ {
+ gObjectList.update(gAgent, *LLWorld::getInstance());
+ }
+ }
+
+ //////////////////////////////////////
+ //
+ // Deletes objects...
+ // Has to be done after doing idleUpdates (which can kill objects)
+ //
+
+ {
+ LLFastTimer t(FTM_CLEANUP);
+ gObjectList.cleanDeadObjects();
+ LLDrawable::cleanupDeadDrawables();
+ }
+
+ //
+ // After this point, in theory we should never see a dead object
+ // in the various object/drawable lists.
+ //
+
+ //////////////////////////////////////
+ //
+ // Update/send HUD effects
+ //
+ // At this point, HUD effects may clean up some references to
+ // dead objects.
+ //
+
+ {
+ static LLFastTimer::DeclareTimer ftm("HUD Effects");
+ LLFastTimer t(ftm);
+ LLSelectMgr::getInstance()->updateEffects();
+ LLHUDManager::getInstance()->cleanupEffects();
+ LLHUDManager::getInstance()->sendEffects();
+ }
+
+ ////////////////////////////////////////
+ //
+ // Unpack layer data that we've received
+ //
+
+ {
+ LLFastTimer t(FTM_NETWORK);
+ gVLManager.unpackData();
+ }
+
+ /////////////////////////
+ //
+ // Update surfaces, and surface textures as well.
+ //
+
+ LLWorld::getInstance()->updateVisibilities();
+ {
+ const F32 max_region_update_time = .001f; // 1ms
+ LLFastTimer t(FTM_REGION_UPDATE);
+ LLWorld::getInstance()->updateRegions(max_region_update_time);
+ }
+
+ /////////////////////////
+ //
+ // Update weather effects
+ //
+ if (!gNoRender)
+ {
+ LLWorld::getInstance()->updateClouds(gFrameDTClamped);
+ gSky.propagateHeavenlyBodies(gFrameDTClamped); // moves sun, moon, and planets
+
+ // Update wind vector
+ LLVector3 wind_position_region;
+ static LLVector3 average_wind;
+
+ LLViewerRegion *regionp;
+ regionp = LLWorld::getInstance()->resolveRegionGlobal(wind_position_region, gAgent.getPositionGlobal()); // puts agent's local coords into wind_position
+ if (regionp)
+ {
+ gWindVec = regionp->mWind.getVelocity(wind_position_region);
+
+ // Compute average wind and use to drive motion of water
+
+ average_wind = regionp->mWind.getAverage();
+ F32 cloud_density = regionp->mCloudLayer.getDensityRegion(wind_position_region);
+
+ gSky.setCloudDensityAtAgent(cloud_density);
+ gSky.setWind(average_wind);
+ //LLVOWater::setWind(average_wind);
+ }
+ else
+ {
+ gWindVec.setVec(0.0f, 0.0f, 0.0f);
+ }
+ }
+
+ //////////////////////////////////////
+ //
+ // Sort and cull in the new renderer are moved to pipeline.cpp
+ // Here, particles are updated and drawables are moved.
+ //
+
+ if (!gNoRender)
+ {
+ LLFastTimer t(FTM_WORLD_UPDATE);
+ gPipeline.updateMove();
+
+ LLWorld::getInstance()->updateParticles();
+ }
+
+ if (gAgentPilot.isPlaying() && gAgentPilot.getOverrideCamera())
+ {
+ gAgentPilot.moveCamera();
+ }
+ else if (LLViewerJoystick::getInstance()->getOverrideCamera())
+ {
+ LLViewerJoystick::getInstance()->moveFlycam();
+ }
+ else
+ {
+ if (LLToolMgr::getInstance()->inBuildMode())
+ {
+ LLViewerJoystick::getInstance()->moveObjects();
+ }
+
+ gAgentCamera.updateCamera();
+ }
+
+ // update media focus
+ LLViewerMediaFocus::getInstance()->update();
+
+ // objects and camera should be in sync, do LOD calculations now
+ {
+ LLFastTimer t(FTM_LOD_UPDATE);
+ gObjectList.updateApparentAngles(gAgent);
+ }
+
+ {
+ LLFastTimer t(FTM_AUDIO_UPDATE);
+
+ if (gAudiop)
+ {
+ audio_update_volume(false);
+ audio_update_listener();
+ audio_update_wind(false);
+
+ // this line actually commits the changes we've made to source positions, etc.
+ const F32 max_audio_decode_time = 0.002f; // 2 ms decode time
+ gAudiop->idle(max_audio_decode_time);
+ }
+ }
+
+ // Handle shutdown process, for example,
+ // wait for floaters to close, send quit message,
+ // forcibly quit if it has taken too long
+ if (mQuitRequested)
+ {
+ gGLActive = TRUE;
+ idleShutdown();
+ }
+}
+
+void LLAppViewer::idleShutdown()
+{
+ // Wait for all modal alerts to get resolved
+ if (LLModalDialog::activeCount() > 0)
+ {
+ return;
+ }
+
+ // close IM interface
+ if(gIMMgr)
+ {
+ gIMMgr->disconnectAllSessions();
+ }
+
+ // Wait for all floaters to get resolved
+ if (gFloaterView
+ && !gFloaterView->allChildrenClosed())
+ {
+ return;
+ }
+
+ if (LLSideTray::getInstance()->notifyChildren(LLSD().with("request","wait_quit")))
+ {
+ return;
+ }
+
+
+
+ // ProductEngine: Try moving this code to where we shut down sTextureCache in cleanup()
+ // *TODO: ugly
+ static bool saved_teleport_history = false;
+ if (!saved_teleport_history)
+ {
+ saved_teleport_history = true;
+ LLTeleportHistory::getInstance()->dump();
+ LLLocationHistory::getInstance()->save(); // *TODO: find a better place for doing this
+ return;
+ }
+
+ static bool saved_snapshot = false;
+ if (!saved_snapshot)
+ {
+ saved_snapshot = true;
+ saveFinalSnapshot();
+ return;
+ }
+
+ const F32 SHUTDOWN_UPLOAD_SAVE_TIME = 5.f;
+
+ S32 pending_uploads = gAssetStorage->getNumPendingUploads();
+ if (pending_uploads > 0
+ && gLogoutTimer.getElapsedTimeF32() < SHUTDOWN_UPLOAD_SAVE_TIME
+ && !logoutRequestSent())
+ {
+ static S32 total_uploads = 0;
+ // Sometimes total upload count can change during logout.
+ total_uploads = llmax(total_uploads, pending_uploads);
+ gViewerWindow->setShowProgress(TRUE);
+ S32 finished_uploads = total_uploads - pending_uploads;
+ F32 percent = 100.f * finished_uploads / total_uploads;
+ gViewerWindow->setProgressPercent(percent);
+ gViewerWindow->setProgressString(LLTrans::getString("SavingSettings"));
+ return;
+ }
+
+ // All floaters are closed. Tell server we want to quit.
+ if( !logoutRequestSent() )
+ {
+ sendLogoutRequest();
+
+ // Wait for a LogoutReply message
+ gViewerWindow->setShowProgress(TRUE);
+ gViewerWindow->setProgressPercent(100.f);
+ gViewerWindow->setProgressString(LLTrans::getString("LoggingOut"));
+ return;
+ }
+
+ // Make sure that we quit if we haven't received a reply from the server.
+ if( logoutRequestSent()
+ && gLogoutTimer.getElapsedTimeF32() > gLogoutMaxTime )
+ {
+ forceQuit();
+ return;
+ }
+}
+
+void LLAppViewer::sendLogoutRequest()
+{
+ if(!mLogoutRequestSent)
+ {
+ LLMessageSystem* msg = gMessageSystem;
+ msg->newMessageFast(_PREHASH_LogoutRequest);
+ msg->nextBlockFast(_PREHASH_AgentData);
+ msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID() );
+ msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ gAgent.sendReliableMessage();
+
+ gLogoutTimer.reset();
+ gLogoutMaxTime = LOGOUT_REQUEST_TIME;
+ mLogoutRequestSent = TRUE;
+
+ if(LLVoiceClient::instanceExists())
+ {
+ LLVoiceClient::getInstance()->leaveChannel();
+ }
+
+ //Set internal status variables and marker files
+ gLogoutInProgress = TRUE;
+ mLogoutMarkerFileName = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,LOGOUT_MARKER_FILE_NAME);
+
+ LLAPRFile outfile ;
+ outfile.open(mLogoutMarkerFileName, LL_APR_W);
+ mLogoutMarkerFile = outfile.getFileHandle() ;
+ if (mLogoutMarkerFile)
+ {
+ llinfos << "Created logout marker file " << mLogoutMarkerFileName << llendl;
+ apr_file_close(mLogoutMarkerFile);
+ }
+ else
+ {
+ llwarns << "Cannot create logout marker file " << mLogoutMarkerFileName << llendl;
+ }
+ }
+}
+
+void LLAppViewer::idleNameCache()
+{
+ // Neither old nor new name cache can function before agent has a region
+ LLViewerRegion* region = gAgent.getRegion();
+ if (!region) return;
+
+ // deal with any queued name requests and replies.
+ gCacheName->processPending();
+
+ // Can't run the new cache until we have the list of capabilities
+ // for the agent region, and can therefore decide whether to use
+ // display names or fall back to the old name system.
+ if (!region->capabilitiesReceived()) return;
+
+ // Agent may have moved to a different region, so need to update cap URL
+ // for name lookups. Can't do this in the cap grant code, as caps are
+ // granted to neighbor regions before the main agent gets there. Can't
+ // do it in the move-into-region code because cap not guaranteed to be
+ // granted yet, for example on teleport.
+ bool had_capability = LLAvatarNameCache::hasNameLookupURL();
+ std::string name_lookup_url;
+ name_lookup_url.reserve(128); // avoid a memory allocation below
+ name_lookup_url = region->getCapability("GetDisplayNames");
+ bool have_capability = !name_lookup_url.empty();
+ if (have_capability)
+ {
+ // we have support for display names, use it
+ U32 url_size = name_lookup_url.size();
+ // capabilities require URLs with slashes before query params:
+ // https://<host>:<port>/cap/<uuid>/?ids=<blah>
+ // but the caps are granted like:
+ // https://<host>:<port>/cap/<uuid>
+ if (url_size > 0 && name_lookup_url[url_size-1] != '/')
+ {
+ name_lookup_url += '/';
+ }
+ LLAvatarNameCache::setNameLookupURL(name_lookup_url);
+ }
+ else
+ {
+ // Display names not available on this region
+ LLAvatarNameCache::setNameLookupURL( std::string() );
+ }
+
+ // Error recovery - did we change state?
+ if (had_capability != have_capability)
+ {
+ // name tags are persistant on screen, so make sure they refresh
+ LLVOAvatar::invalidateNameTags();
+ }
+
+ LLAvatarNameCache::idle();
+}
+
+//
+// Handle messages, and all message related stuff
+//
+
+#define TIME_THROTTLE_MESSAGES
+
+#ifdef TIME_THROTTLE_MESSAGES
+#define CHECK_MESSAGES_DEFAULT_MAX_TIME .020f // 50 ms = 50 fps (just for messages!)
+static F32 CheckMessagesMaxTime = CHECK_MESSAGES_DEFAULT_MAX_TIME;
+#endif
+
+static LLFastTimer::DeclareTimer FTM_IDLE_NETWORK("Idle Network");
+static LLFastTimer::DeclareTimer FTM_MESSAGE_ACKS("Message Acks");
+static LLFastTimer::DeclareTimer FTM_RETRANSMIT("Retransmit");
+static LLFastTimer::DeclareTimer FTM_TIMEOUT_CHECK("Timeout Check");
+static LLFastTimer::DeclareTimer FTM_DYNAMIC_THROTTLE("Dynamic Throttle");
+static LLFastTimer::DeclareTimer FTM_CHECK_REGION_CIRCUIT("Check Region Circuit");
+
+void LLAppViewer::idleNetwork()
+{
+ LLMemType mt_in(LLMemType::MTYPE_IDLE_NETWORK);
+ pingMainloopTimeout("idleNetwork");
+
+ gObjectList.mNumNewObjects = 0;
+ S32 total_decoded = 0;
+
+ if (!gSavedSettings.getBOOL("SpeedTest"))
+ {
+ LLFastTimer t(FTM_IDLE_NETWORK); // decode
+
+ LLTimer check_message_timer;
+ // Read all available packets from network
+ const S64 frame_count = gFrameCount; // U32->S64
+ F32 total_time = 0.0f;
+
+ while (gMessageSystem->checkAllMessages(frame_count, gServicePump))
+ {
+ if (gDoDisconnect)
+ {
+ // We're disconnecting, don't process any more messages from the server
+ // We're usually disconnecting due to either network corruption or a
+ // server going down, so this is OK.
+ break;
+ }
+
+ total_decoded++;
+ gPacketsIn++;
+
+ if (total_decoded > MESSAGE_MAX_PER_FRAME)
+ {
+ break;
+ }
+
+#ifdef TIME_THROTTLE_MESSAGES
+ // Prevent slow packets from completely destroying the frame rate.
+ // This usually happens due to clumps of avatars taking huge amount
+ // of network processing time (which needs to be fixed, but this is
+ // a good limit anyway).
+ total_time = check_message_timer.getElapsedTimeF32();
+ if (total_time >= CheckMessagesMaxTime)
+ break;
+#endif
+ }
+
+ // Handle per-frame message system processing.
+ gMessageSystem->processAcks();
+
+#ifdef TIME_THROTTLE_MESSAGES
+ if (total_time >= CheckMessagesMaxTime)
+ {
+ // Increase CheckMessagesMaxTime so that we will eventually catch up
+ CheckMessagesMaxTime *= 1.035f; // 3.5% ~= x2 in 20 frames, ~8x in 60 frames
+ }
+ else
+ {
+ // Reset CheckMessagesMaxTime to default value
+ CheckMessagesMaxTime = CHECK_MESSAGES_DEFAULT_MAX_TIME;
+ }
+#endif
+
+
+
+ // we want to clear the control after sending out all necessary agent updates
+ gAgent.resetControlFlags();
+
+ // Decode enqueued messages...
+ S32 remaining_possible_decodes = MESSAGE_MAX_PER_FRAME - total_decoded;
+
+ if( remaining_possible_decodes <= 0 )
+ {
+ llinfos << "Maxed out number of messages per frame at " << MESSAGE_MAX_PER_FRAME << llendl;
+ }
+
+ if (gPrintMessagesThisFrame)
+ {
+ llinfos << "Decoded " << total_decoded << " msgs this frame!" << llendl;
+ gPrintMessagesThisFrame = FALSE;
+ }
+ }
+ LLViewerStats::getInstance()->mNumNewObjectsStat.addValue(gObjectList.mNumNewObjects);
+
+ // Retransmit unacknowledged packets.
+ gXferManager->retransmitUnackedPackets();
+ gAssetStorage->checkForTimeouts();
+ gViewerThrottle.updateDynamicThrottle();
+
+ // Check that the circuit between the viewer and the agent's current
+ // region is still alive
+ LLViewerRegion *agent_region = gAgent.getRegion();
+ if (agent_region && (LLStartUp::getStartupState()==STATE_STARTED))
+ {
+ LLUUID this_region_id = agent_region->getRegionID();
+ bool this_region_alive = agent_region->isAlive();
+ if ((mAgentRegionLastAlive && !this_region_alive) // newly dead
+ && (mAgentRegionLastID == this_region_id)) // same region
+ {
+ forceDisconnect(LLTrans::getString("AgentLostConnection"));
+ }
+ mAgentRegionLastID = this_region_id;
+ mAgentRegionLastAlive = this_region_alive;
+ }
+}
+
+void LLAppViewer::disconnectViewer()
+{
+ if (gDisconnected)
+ {
+ return;
+ }
+ //
+ // Cleanup after quitting.
+ //
+ // Save snapshot for next time, if we made it through initialization
+
+ llinfos << "Disconnecting viewer!" << llendl;
+
+ // Dump our frame statistics
+
+ // Remember if we were flying
+ gSavedSettings.setBOOL("FlyingAtExit", gAgent.getFlying() );
+
+ // Un-minimize all windows so they don't get saved minimized
+ if (!gNoRender)
+ {
+ if (gFloaterView)
+ {
+ gFloaterView->restoreAll();
+ }
+ }
+
+ if (LLSelectMgr::getInstance())
+ {
+ LLSelectMgr::getInstance()->deselectAll();
+ }
+
+ // save inventory if appropriate
+ gInventory.cache(gInventory.getRootFolderID(), gAgent.getID());
+ if (gInventory.getLibraryRootFolderID().notNull()
+ && gInventory.getLibraryOwnerID().notNull())
+ {
+ gInventory.cache(
+ gInventory.getLibraryRootFolderID(),
+ gInventory.getLibraryOwnerID());
+ }
+
+ saveNameCache();
+
+ // close inventory interface, close all windows
+ LLFloaterInventory::cleanup();
+
+ gAgentWearables.cleanup();
+ gAgentCamera.cleanup();
+ // Also writes cached agent settings to gSavedSettings
+ gAgent.cleanup();
+
+ // This is where we used to call gObjectList.destroy() and then delete gWorldp.
+ // Now we just ask the LLWorld singleton to cleanly shut down.
+ if(LLWorld::instanceExists())
+ {
+ LLWorld::getInstance()->destroyClass();
+ }
+
+ // call all self-registered classes
+ LLDestroyClassList::instance().fireCallbacks();
+
+ cleanup_xfer_manager();
+ gDisconnected = TRUE;
+
+ // Pass the connection state to LLUrlEntryParcel not to attempt
+ // parcel info requests while disconnected.
+ LLUrlEntryParcel::setDisconnected(gDisconnected);
+}
+
+void LLAppViewer::forceErrorLLError()
+{
+ llerrs << "This is an llerror" << llendl;
+}
+
+void LLAppViewer::forceErrorBreakpoint()
+{
+#ifdef LL_WINDOWS
+ DebugBreak();
+#endif
+ return;
+}
+
+void LLAppViewer::forceErrorBadMemoryAccess()
+{
+ S32* crash = NULL;
+ *crash = 0xDEADBEEF;
+ return;
+}
+
+void LLAppViewer::forceErrorInfiniteLoop()
+{
+ while(true)
+ {
+ ;
+ }
+ return;
+}
+
+void LLAppViewer::forceErrorSoftwareException()
+{
+ // *FIX: Any way to insure it won't be handled?
+ throw;
+}
+
+void LLAppViewer::forceErrorDriverCrash()
+{
+ glDeleteTextures(1, NULL);
+}
+
+void LLAppViewer::initMainloopTimeout(const std::string& state, F32 secs)
+{
+ if(!mMainloopTimeout)
+ {
+ mMainloopTimeout = new LLWatchdogTimeout();
+ resumeMainloopTimeout(state, secs);
+ }
+}
+
+void LLAppViewer::destroyMainloopTimeout()
+{
+ if(mMainloopTimeout)
+ {
+ delete mMainloopTimeout;
+ mMainloopTimeout = NULL;
+ }
+}
+
+void LLAppViewer::resumeMainloopTimeout(const std::string& state, F32 secs)
+{
+ if(mMainloopTimeout)
+ {
+ if(secs < 0.0f)
+ {
+ secs = gSavedSettings.getF32("MainloopTimeoutDefault");
+ }
+
+ mMainloopTimeout->setTimeout(secs);
+ mMainloopTimeout->start(state);
+ }
+}
+
+void LLAppViewer::pauseMainloopTimeout()
+{
+ if(mMainloopTimeout)
+ {
+ mMainloopTimeout->stop();
+ }
+}
+
+void LLAppViewer::pingMainloopTimeout(const std::string& state, F32 secs)
+{
+// if(!restoreErrorTrap())
+// {
+// llwarns << "!!!!!!!!!!!!! Its an error trap!!!!" << state << llendl;
+// }
+
+ if(mMainloopTimeout)
+ {
+ if(secs < 0.0f)
+ {
+ secs = gSavedSettings.getF32("MainloopTimeoutDefault");
+ }
+
+ mMainloopTimeout->setTimeout(secs);
+ mMainloopTimeout->ping(state);
+ }
+}
+
+void LLAppViewer::handleLoginComplete()
+{
+ gLoggedInTime.start();
+ initMainloopTimeout("Mainloop Init");
+
+ // Store some data to DebugInfo in case of a freeze.
+ gDebugInfo["ClientInfo"]["Name"] = LLVersionInfo::getChannel();
+
+ gDebugInfo["ClientInfo"]["MajorVersion"] = LLVersionInfo::getMajor();
+ gDebugInfo["ClientInfo"]["MinorVersion"] = LLVersionInfo::getMinor();
+ gDebugInfo["ClientInfo"]["PatchVersion"] = LLVersionInfo::getPatch();
+ gDebugInfo["ClientInfo"]["BuildVersion"] = LLVersionInfo::getBuild();
+
+ LLParcel* parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
+ if ( parcel && parcel->getMusicURL()[0])
+ {
+ gDebugInfo["ParcelMusicURL"] = parcel->getMusicURL();
+ }
+ if ( parcel && parcel->getMediaURL()[0])
+ {
+ gDebugInfo["ParcelMediaURL"] = parcel->getMediaURL();
+ }
+
+ gDebugInfo["SettingsFilename"] = gSavedSettings.getString("ClientSettingsFile");
+ gDebugInfo["CAFilename"] = gDirUtilp->getCAFile();
+ gDebugInfo["ViewerExePath"] = gDirUtilp->getExecutablePathAndName();
+ gDebugInfo["CurrentPath"] = gDirUtilp->getCurPath();
+
+ if(gAgent.getRegion())
+ {
+ gDebugInfo["CurrentSimHost"] = gAgent.getRegionHost().getHostName();
+ gDebugInfo["CurrentRegion"] = gAgent.getRegion()->getName();
+ }
+
+ if(LLAppViewer::instance()->mMainloopTimeout)
+ {
+ gDebugInfo["MainloopTimeoutState"] = LLAppViewer::instance()->mMainloopTimeout->getState();
+ }
+
+ mOnLoginCompleted();
+
+ writeDebugInfo();
+}
+
+// *TODO - generalize this and move DSO wrangling to a helper class -brad
+void LLAppViewer::loadEventHostModule(S32 listen_port)
+{
+ std::string dso_name =
+#if LL_WINDOWS
+ "lleventhost.dll";
+#elif LL_DARWIN
+ "liblleventhost.dylib";
+#else
+ "liblleventhost.so";
+#endif
+
+ std::string dso_path = gDirUtilp->findFile(dso_name,
+ gDirUtilp->getAppRODataDir(),
+ gDirUtilp->getExecutableDir());
+
+ if(dso_path == "")
+ {
+ llerrs << "QAModeEventHost requested but module \"" << dso_name << "\" not found!" << llendl;
+ return;
+ }
+
+ LL_INFOS("eventhost") << "Found lleventhost at '" << dso_path << "'" << LL_ENDL;
+#if ! defined(LL_WINDOWS)
+ {
+ std::string outfile("/tmp/lleventhost.file.out");
+ std::string command("file '" + dso_path + "' > '" + outfile + "' 2>&1");
+ int rc = system(command.c_str());
+ if (rc != 0)
+ {
+ LL_WARNS("eventhost") << command << " ==> " << rc << ':' << LL_ENDL;
+ }
+ else
+ {
+ LL_INFOS("eventhost") << command << ':' << LL_ENDL;
+ }
+ {
+ std::ifstream reader(outfile.c_str());
+ std::string line;
+ while (std::getline(reader, line))
+ {
+ size_t len = line.length();
+ if (len && line[len-1] == '\n')
+ line.erase(len-1);
+ LL_INFOS("eventhost") << line << LL_ENDL;
+ }
+ }
+ remove(outfile.c_str());
+ }
+#endif // LL_WINDOWS
+
+ apr_dso_handle_t * eventhost_dso_handle = NULL;
+ apr_pool_t * eventhost_dso_memory_pool = NULL;
+
+ //attempt to load the shared library
+ apr_pool_create(&eventhost_dso_memory_pool, NULL);
+ apr_status_t rv = apr_dso_load(&eventhost_dso_handle,
+ dso_path.c_str(),
+ eventhost_dso_memory_pool);
+ llassert_always(! ll_apr_warn_status(rv, eventhost_dso_handle));
+ llassert_always(eventhost_dso_handle != NULL);
+
+ int (*ll_plugin_start_func)(LLSD const &) = NULL;
+ rv = apr_dso_sym((apr_dso_handle_sym_t*)&ll_plugin_start_func, eventhost_dso_handle, "ll_plugin_start");
+
+ llassert_always(! ll_apr_warn_status(rv, eventhost_dso_handle));
+ llassert_always(ll_plugin_start_func != NULL);
+
+ LLSD args;
+ args["listen_port"] = listen_port;
+
+ int status = ll_plugin_start_func(args);
+
+ if(status != 0)
+ {
+ llerrs << "problem loading eventhost plugin, status: " << status << llendl;
+ }
+
+ mPlugins.insert(eventhost_dso_handle);
+}
+
+void LLAppViewer::launchUpdater()
+{
+ LLSD query_map = LLSD::emptyMap();
+ // *TODO place os string in a global constant
+#if LL_WINDOWS
+ query_map["os"] = "win";
+#elif LL_DARWIN
+ query_map["os"] = "mac";
+#elif LL_LINUX
+ query_map["os"] = "lnx";
+#elif LL_SOLARIS
+ query_map["os"] = "sol";
+#endif
+ // *TODO change userserver to be grid on both viewer and sim, since
+ // userserver no longer exists.
+ query_map["userserver"] = LLGridManager::getInstance()->getGridLabel();
+ query_map["channel"] = LLVersionInfo::getChannel();
+ // *TODO constantize this guy
+ // *NOTE: This URL is also used in win_setup/lldownloader.cpp
+ LLURI update_url = LLURI::buildHTTP("secondlife.com", 80, "update.php", query_map);
+
+ if(LLAppViewer::sUpdaterInfo)
+ {
+ delete LLAppViewer::sUpdaterInfo;
+ }
+ LLAppViewer::sUpdaterInfo = new LLAppViewer::LLUpdaterInfo() ;
+
+ // if a sim name was passed in via command line parameter (typically through a SLURL)
+ if ( LLStartUp::getStartSLURL().getType() == LLSLURL::LOCATION )
+ {
+ // record the location to start at next time
+ gSavedSettings.setString( "NextLoginLocation", LLStartUp::getStartSLURL().getSLURLString());
+ };
+
+#if LL_WINDOWS
+ LLAppViewer::sUpdaterInfo->mUpdateExePath = gDirUtilp->getTempFilename();
+ if (LLAppViewer::sUpdaterInfo->mUpdateExePath.empty())
+ {
+ delete LLAppViewer::sUpdaterInfo ;
+ LLAppViewer::sUpdaterInfo = NULL ;
+
+ // We're hosed, bail
+ LL_WARNS("AppInit") << "LLDir::getTempFilename() failed" << LL_ENDL;
+ return;
+ }
+
+ LLAppViewer::sUpdaterInfo->mUpdateExePath += ".exe";
+
+ std::string updater_source = gDirUtilp->getAppRODataDir();
+ updater_source += gDirUtilp->getDirDelimiter();
+ updater_source += "updater.exe";
+
+ LL_DEBUGS("AppInit") << "Calling CopyFile source: " << updater_source
+ << " dest: " << LLAppViewer::sUpdaterInfo->mUpdateExePath
+ << LL_ENDL;
+
+
+ if (!CopyFileA(updater_source.c_str(), LLAppViewer::sUpdaterInfo->mUpdateExePath.c_str(), FALSE))
+ {
+ delete LLAppViewer::sUpdaterInfo ;
+ LLAppViewer::sUpdaterInfo = NULL ;
+
+ LL_WARNS("AppInit") << "Unable to copy the updater!" << LL_ENDL;
+
+ return;
+ }
+
+ LLAppViewer::sUpdaterInfo->mParams << "-url \"" << update_url.asString() << "\"";
+
+ LL_DEBUGS("AppInit") << "Calling updater: " << LLAppViewer::sUpdaterInfo->mUpdateExePath << " " << LLAppViewer::sUpdaterInfo->mParams.str() << LL_ENDL;
+
+ //Explicitly remove the marker file, otherwise we pass the lock onto the child process and things get weird.
+ LLAppViewer::instance()->removeMarkerFile(); // In case updater fails
+
+ // *NOTE:Mani The updater is spawned as the last thing before the WinMain exit.
+ // see LLAppViewerWin32.cpp
+
+#elif LL_DARWIN
+ LLAppViewer::sUpdaterInfo->mUpdateExePath = "'";
+ LLAppViewer::sUpdaterInfo->mUpdateExePath += gDirUtilp->getAppRODataDir();
+ LLAppViewer::sUpdaterInfo->mUpdateExePath += "/mac-updater.app/Contents/MacOS/mac-updater' -url \"";
+ LLAppViewer::sUpdaterInfo->mUpdateExePath += update_url.asString();
+ LLAppViewer::sUpdaterInfo->mUpdateExePath += "\" -name \"";
+ LLAppViewer::sUpdaterInfo->mUpdateExePath += LLAppViewer::instance()->getSecondLifeTitle();
+ LLAppViewer::sUpdaterInfo->mUpdateExePath += "\" -bundleid \"";
+ LLAppViewer::sUpdaterInfo->mUpdateExePath += LL_VERSION_BUNDLE_ID;
+ LLAppViewer::sUpdaterInfo->mUpdateExePath += "\" &";
+
+ LL_DEBUGS("AppInit") << "Calling updater: " << LLAppViewer::sUpdaterInfo->mUpdateExePath << LL_ENDL;
+
+ // Run the auto-updater.
+ system(LLAppViewer::sUpdaterInfo->mUpdateExePath.c_str()); /* Flawfinder: ignore */
+
+#elif (LL_LINUX || LL_SOLARIS) && LL_GTK
+ // we tell the updater where to find the xml containing string
+ // translations which it can use for its own UI
+ std::string xml_strings_file = "strings.xml";
+ std::vector<std::string> xui_path_vec = LLUI::getXUIPaths();
+ std::string xml_search_paths;
+ std::vector<std::string>::const_iterator iter;
+ // build comma-delimited list of xml paths to pass to updater
+ for (iter = xui_path_vec.begin(); iter != xui_path_vec.end(); )
+ {
+ std::string this_skin_dir = gDirUtilp->getDefaultSkinDir()
+ + gDirUtilp->getDirDelimiter()
+ + (*iter);
+ llinfos << "Got a XUI path: " << this_skin_dir << llendl;
+ xml_search_paths.append(this_skin_dir);
+ ++iter;
+ if (iter != xui_path_vec.end())
+ xml_search_paths.append(","); // comma-delimit
+ }
+ // build the overall command-line to run the updater correctly
+ LLAppViewer::sUpdaterInfo->mUpdateExePath =
+ gDirUtilp->getExecutableDir() + "/" + "linux-updater.bin" +
+ " --url \"" + update_url.asString() + "\"" +
+ " --name \"" + LLAppViewer::instance()->getSecondLifeTitle() + "\"" +
+ " --dest \"" + gDirUtilp->getAppRODataDir() + "\"" +
+ " --stringsdir \"" + xml_search_paths + "\"" +
+ " --stringsfile \"" + xml_strings_file + "\"";
+
+ LL_INFOS("AppInit") << "Calling updater: "
+ << LLAppViewer::sUpdaterInfo->mUpdateExePath << LL_ENDL;
+
+ // *TODO: we could use the gdk equivalent to ensure the updater
+ // gets started on the same screen.
+ GError *error = NULL;
+ if (!g_spawn_command_line_async(LLAppViewer::sUpdaterInfo->mUpdateExePath.c_str(), &error))
+ {
+ llerrs << "Failed to launch updater: "
+ << error->message
+ << llendl;
+ }
+ if (error) {
+ g_error_free(error);
+ }
+#else
+ OSMessageBox(LLTrans::getString("MBNoAutoUpdate"), LLStringUtil::null, OSMB_OK);
+#endif
+
+ // *REMOVE:Mani - Saving for reference...
+ // LLAppViewer::instance()->forceQuit();
+}
+
+
+//virtual
+void LLAppViewer::setMasterSystemAudioMute(bool mute)
+{
+ gSavedSettings.setBOOL("MuteAudio", mute);
+}
+
+//virtual
+bool LLAppViewer::getMasterSystemAudioMute()
+{
+ return gSavedSettings.getBOOL("MuteAudio");
+}
+
+//----------------------------------------------------------------------------
+// Metrics-related methods (static and otherwise)
+//----------------------------------------------------------------------------
+
+/**
+ * LLViewerAssetStats collects data on a per-region (as defined by the agent's
+ * location) so we need to tell it about region changes which become a kind of
+ * hidden variable/global state in the collectors. For collectors not running
+ * on the main thread, we need to send a message to move the data over safely
+ * and cheaply (amortized over a run).
+ */
+void LLAppViewer::metricsUpdateRegion(U64 region_handle)
+{
+ if (0 != region_handle)
+ {
+ LLViewerAssetStatsFF::set_region_main(region_handle);
+ if (LLAppViewer::sTextureFetch)
+ {
+ // Send a region update message into 'thread1' to get the new region.
+ LLAppViewer::sTextureFetch->commandSetRegion(region_handle);
+ }
+ else
+ {
+ // No 'thread1', a.k.a. TextureFetch, so update directly
+ LLViewerAssetStatsFF::set_region_thread1(region_handle);
+ }
+ }
+}
+
+
+/**
+ * Attempts to start a multi-threaded metrics report to be sent back to
+ * the grid for consumption.
+ */
+void LLAppViewer::metricsSend(bool enable_reporting)
+{
+ if (! gViewerAssetStatsMain)
+ return;
+
+ if (LLAppViewer::sTextureFetch)
+ {
+ LLViewerRegion * regionp = gAgent.getRegion();
+
+ if (enable_reporting && regionp)
+ {
+ std::string caps_url = regionp->getCapability("ViewerMetrics");
+
+ // Make a copy of the main stats to send into another thread.
+ // Receiving thread takes ownership.
+ LLViewerAssetStats * main_stats(new LLViewerAssetStats(*gViewerAssetStatsMain));
+
+ // Send a report request into 'thread1' to get the rest of the data
+ // and provide some additional parameters while here.
+ LLAppViewer::sTextureFetch->commandSendMetrics(caps_url,
+ gAgentSessionID,
+ gAgentID,
+ main_stats);
+ main_stats = 0; // Ownership transferred
+ }
+ else
+ {
+ LLAppViewer::sTextureFetch->commandDataBreak();
+ }
+ }
+
+ // Reset even if we can't report. Rather than gather up a huge chunk of
+ // data, we'll keep to our sampling interval and retain the data
+ // resolution in time.
+ gViewerAssetStatsMain->reset();
+}
+
diff --git a/indra/newview/llappviewerwin32.cpp b/indra/newview/llappviewerwin32.cpp
index d328567a0e..54689ea808 100644
--- a/indra/newview/llappviewerwin32.cpp
+++ b/indra/newview/llappviewerwin32.cpp
@@ -440,7 +440,11 @@ bool LLAppViewerWin32::initHardwareTest()
LL_WARNS("AppInit") << " Someone took over my exception handler (post hardware probe)!" << LL_ENDL;
}
- gGLManager.mVRAM = gDXHardware.getVRAM();
+ if (gGLManager.mVRAM == 0)
+ {
+ gGLManager.mVRAM = gDXHardware.getVRAM();
+ }
+
LL_INFOS("AppInit") << "Detected VRAM: " << gGLManager.mVRAM << LL_ENDL;
return true;
diff --git a/indra/newview/llassetuploadresponders.cpp b/indra/newview/llassetuploadresponders.cpp
index dd5bc74b2a..c08771c5e7 100644
--- a/indra/newview/llassetuploadresponders.cpp
+++ b/indra/newview/llassetuploadresponders.cpp
@@ -60,6 +60,7 @@
#include "llnotificationsutil.h"
#include "llscrolllistctrl.h"
#include "llsdserialize.h"
+#include "llsdutil.h"
#include "llvfs.h"
// When uploading multiple files, don't display any of them when uploading more than this number.
@@ -67,6 +68,106 @@ static const S32 FILE_COUNT_DISPLAY_THRESHOLD = 5;
void dialog_refresh_all();
+void on_new_single_inventory_upload_complete(
+ LLAssetType::EType asset_type,
+ LLInventoryType::EType inventory_type,
+ const std::string inventory_type_string,
+ const LLUUID& item_folder_id,
+ const std::string& item_name,
+ const std::string& item_description,
+ const LLSD& server_response,
+ S32 upload_price)
+{
+ if ( upload_price > 0 )
+ {
+ // this upload costed us L$, update our balance
+ // and display something saying that it cost L$
+ LLStatusBar::sendMoneyBalanceRequest();
+
+ LLSD args;
+ args["AMOUNT"] = llformat("%d", upload_price);
+ LLNotificationsUtil::add("UploadPayment", args);
+ }
+
+ if( item_folder_id.notNull() )
+ {
+ U32 everyone_perms = PERM_NONE;
+ U32 group_perms = PERM_NONE;
+ U32 next_owner_perms = PERM_ALL;
+ if( server_response.has("new_next_owner_mask") )
+ {
+ // The server provided creation perms so use them.
+ // Do not assume we got the perms we asked for in
+ // since the server may not have granted them all.
+ everyone_perms = server_response["new_everyone_mask"].asInteger();
+ group_perms = server_response["new_group_mask"].asInteger();
+ next_owner_perms = server_response["new_next_owner_mask"].asInteger();
+ }
+ else
+ {
+ // The server doesn't provide creation perms
+ // so use old assumption-based perms.
+ if( inventory_type_string != "snapshot")
+ {
+ next_owner_perms = PERM_MOVE | PERM_TRANSFER;
+ }
+ }
+
+ LLPermissions new_perms;
+ new_perms.init(
+ gAgent.getID(),
+ gAgent.getID(),
+ LLUUID::null,
+ LLUUID::null);
+
+ new_perms.initMasks(
+ PERM_ALL,
+ PERM_ALL,
+ everyone_perms,
+ group_perms,
+ next_owner_perms);
+
+ S32 creation_date_now = time_corrected();
+ LLPointer<LLViewerInventoryItem> item = new LLViewerInventoryItem(
+ server_response["new_inventory_item"].asUUID(),
+ item_folder_id,
+ new_perms,
+ server_response["new_asset"].asUUID(),
+ asset_type,
+ inventory_type,
+ item_name,
+ item_description,
+ LLSaleInfo::DEFAULT,
+ LLInventoryItemFlags::II_FLAGS_NONE,
+ creation_date_now);
+
+ gInventory.updateItem(item);
+ gInventory.notifyObservers();
+
+ // Show the preview panel for textures and sounds to let
+ // user know that the image (or snapshot) arrived intact.
+ LLInventoryPanel* panel = LLInventoryPanel::getActiveInventoryPanel();
+ if ( panel )
+ {
+ LLFocusableElement* focus = gFocusMgr.getKeyboardFocus();
+
+ panel->setSelection(
+ server_response["new_inventory_item"].asUUID(),
+ TAKE_FOCUS_NO);
+
+ // restore keyboard focus
+ gFocusMgr.setKeyboardFocus(focus);
+ }
+ }
+ else
+ {
+ llwarns << "Can't find a folder to put it in" << llendl;
+ }
+
+ // remove the "Uploading..." message
+ LLUploadDialog::modalUploadFinished();
+}
+
LLAssetUploadResponder::LLAssetUploadResponder(const LLSD &post_data,
const LLUUID& vfile_id,
LLAssetType::EType asset_type)
@@ -84,9 +185,10 @@ LLAssetUploadResponder::LLAssetUploadResponder(const LLSD &post_data,
}
}
-LLAssetUploadResponder::LLAssetUploadResponder(const LLSD &post_data,
- const std::string& file_name,
- LLAssetType::EType asset_type)
+LLAssetUploadResponder::LLAssetUploadResponder(
+ const LLSD &post_data,
+ const std::string& file_name,
+ LLAssetType::EType asset_type)
: LLHTTPClient::Responder(),
mPostData(post_data),
mFileName(file_name),
@@ -135,6 +237,7 @@ void LLAssetUploadResponder::result(const LLSD& content)
lldebugs << "LLAssetUploadResponder::result from capabilities" << llendl;
std::string state = content["state"];
+
if (state == "upload")
{
uploadUpload(content);
@@ -196,16 +299,36 @@ void LLAssetUploadResponder::uploadComplete(const LLSD& content)
{
}
-LLNewAgentInventoryResponder::LLNewAgentInventoryResponder(const LLSD& post_data,
- const LLUUID& vfile_id,
- LLAssetType::EType asset_type)
-: LLAssetUploadResponder(post_data, vfile_id, asset_type)
+LLNewAgentInventoryResponder::LLNewAgentInventoryResponder(
+ const LLSD& post_data,
+ const LLUUID& vfile_id,
+ LLAssetType::EType asset_type)
+ : LLAssetUploadResponder(post_data, vfile_id, asset_type)
{
}
-LLNewAgentInventoryResponder::LLNewAgentInventoryResponder(const LLSD& post_data, const std::string& file_name, LLAssetType::EType asset_type)
-: LLAssetUploadResponder(post_data, file_name, asset_type)
+LLNewAgentInventoryResponder::LLNewAgentInventoryResponder(
+ const LLSD& post_data,
+ const std::string& file_name,
+ LLAssetType::EType asset_type)
+ : LLAssetUploadResponder(post_data, file_name, asset_type)
+{
+}
+
+// virtual
+void LLNewAgentInventoryResponder::error(U32 statusNum, const std::string& reason)
{
+ LLAssetUploadResponder::error(statusNum, reason);
+ //LLImportColladaAssetCache::getInstance()->assetUploaded(mVFileID, LLUUID(), FALSE);
+}
+
+
+//virtual
+void LLNewAgentInventoryResponder::uploadFailure(const LLSD& content)
+{
+ LLAssetUploadResponder::uploadFailure(content);
+
+ //LLImportColladaAssetCache::getInstance()->assetUploaded(mVFileID, content["new_asset"], FALSE);
}
//virtual
@@ -219,95 +342,31 @@ void LLNewAgentInventoryResponder::uploadComplete(const LLSD& content)
LLAssetType::EType asset_type = LLAssetType::lookup(mPostData["asset_type"].asString());
LLInventoryType::EType inventory_type = LLInventoryType::lookup(mPostData["inventory_type"].asString());
- S32 expected_upload_cost = LLGlobalEconomy::Singleton::getInstance()->getPriceUpload();
+ S32 expected_upload_cost = 0;
// Update L$ and ownership credit information
// since it probably changed on the server
if (asset_type == LLAssetType::AT_TEXTURE ||
asset_type == LLAssetType::AT_SOUND ||
- asset_type == LLAssetType::AT_ANIMATION)
+ asset_type == LLAssetType::AT_ANIMATION ||
+ asset_type == LLAssetType::AT_MESH)
{
- LLStatusBar::sendMoneyBalanceRequest();
-
- LLSD args;
- args["AMOUNT"] = llformat("%d", expected_upload_cost);
- LLNotificationsUtil::add("UploadPayment", args);
+ expected_upload_cost =
+ LLGlobalEconomy::Singleton::getInstance()->getPriceUpload();
}
- // Actually add the upload to viewer inventory
- llinfos << "Adding " << content["new_inventory_item"].asUUID() << " "
- << content["new_asset"].asUUID() << " to inventory." << llendl;
- if(mPostData["folder_id"].asUUID().notNull())
- {
- //std::ostringstream out;
- //LLSDXMLFormatter *formatter = new LLSDXMLFormatter;
- //formatter->format(mPostData, out, LLSDFormatter::OPTIONS_PRETTY);
- //llinfos << "Post Data: " << out.str() << llendl;
+ on_new_single_inventory_upload_complete(
+ asset_type,
+ inventory_type,
+ mPostData["asset_type"].asString(),
+ mPostData["folder_id"].asUUID(),
+ mPostData["name"],
+ mPostData["description"],
+ content,
+ expected_upload_cost);
- U32 everyone_perms = PERM_NONE;
- U32 group_perms = PERM_NONE;
- U32 next_owner_perms = PERM_ALL;
- if(content.has("new_next_owner_mask"))
- {
- // This is a new sim that provides creation perms so use them.
- // Do not assume we got the perms we asked for in mPostData
- // since the sim may not have granted them all.
- everyone_perms = content["new_everyone_mask"].asInteger();
- group_perms = content["new_group_mask"].asInteger();
- next_owner_perms = content["new_next_owner_mask"].asInteger();
- }
- else
- {
- // This old sim doesn't provide creation perms so use old assumption-based perms.
- if(mPostData["inventory_type"].asString() != "snapshot")
- {
- next_owner_perms = PERM_MOVE | PERM_TRANSFER;
- }
- }
- LLPermissions new_perms;
- new_perms.init(gAgent.getID(), gAgent.getID(), LLUUID::null, LLUUID::null);
- new_perms.initMasks(PERM_ALL, PERM_ALL, everyone_perms, group_perms, next_owner_perms);
- S32 creation_date_now = time_corrected();
- LLPointer<LLViewerInventoryItem> item
- = new LLViewerInventoryItem(content["new_inventory_item"].asUUID(),
- mPostData["folder_id"].asUUID(),
- new_perms,
- content["new_asset"].asUUID(),
- asset_type,
- inventory_type,
- mPostData["name"].asString(),
- mPostData["description"].asString(),
- LLSaleInfo::DEFAULT,
- LLInventoryItemFlags::II_FLAGS_NONE,
- creation_date_now);
- gInventory.updateItem(item);
- gInventory.notifyObservers();
-
- // Show the preview panel for textures and sounds to let
- // user know that the image (or snapshot) arrived intact.
- LLInventoryPanel *active_panel = LLInventoryPanel::getActiveInventoryPanel();
- if (active_panel)
- {
- active_panel->setSelection(content["new_inventory_item"].asUUID(), TAKE_FOCUS_NO);
- if((LLAssetType::AT_TEXTURE == asset_type || LLAssetType::AT_SOUND == asset_type)
- && LLFilePicker::instance().getFileCount() <= FILE_COUNT_DISPLAY_THRESHOLD)
- {
- active_panel->openSelected();
- }
- //LLFloaterInventory::dumpSelectionInformation((void*)view);
- // restore keyboard focus
- LLFocusableElement* focus = gFocusMgr.getKeyboardFocus();
- gFocusMgr.setKeyboardFocus(focus);
- }
- }
- else
- {
- llwarns << "Can't find a folder to put it in" << llendl;
- }
+ // continue uploading for bulk uploads
- // remove the "Uploading..." message
- LLUploadDialog::modalUploadFinished();
-
// *FIX: This is a pretty big hack. What this does is check the
// file picker if there are any more pending uploads. If so,
// upload that file.
@@ -324,19 +383,42 @@ void LLNewAgentInventoryResponder::uploadComplete(const LLSD& content)
// Continuing the horrible hack above, we need to extract the originally requested permissions data, if any,
// and use them for each next file to be uploaded. Note the requested perms are not the same as the
- // granted ones found in the given "content" structure but can still be found in mPostData. -MG
- U32 everyone_perms = mPostData.has("everyone_mask") ? mPostData.get("everyone_mask" ).asInteger() : PERM_NONE;
- U32 group_perms = mPostData.has("group_mask") ? mPostData.get("group_mask" ).asInteger() : PERM_NONE;
- U32 next_owner_perms = mPostData.has("next_owner_mask") ? mPostData.get("next_owner_mask").asInteger() : PERM_NONE;
+ U32 everyone_perms =
+ content.has("everyone_mask") ?
+ content["everyone_mask"].asInteger() :
+ PERM_NONE;
+
+ U32 group_perms =
+ content.has("group_mask") ?
+ content["group_mask"].asInteger() :
+ PERM_NONE;
+
+ U32 next_owner_perms =
+ content.has("next_owner_mask") ?
+ content["next_owner_mask"].asInteger() :
+ PERM_NONE;
+
std::string display_name = LLStringUtil::null;
LLAssetStorage::LLStoreAssetCallback callback = NULL;
void *userdata = NULL;
- upload_new_resource(next_file, asset_name, asset_name,
- 0, LLFolderType::FT_NONE, LLInventoryType::IT_NONE,
- next_owner_perms, group_perms,
- everyone_perms, display_name,
- callback, expected_upload_cost, userdata);
+
+ upload_new_resource(
+ next_file,
+ asset_name,
+ asset_name,
+ 0,
+ LLFolderType::FT_NONE,
+ LLInventoryType::IT_NONE,
+ next_owner_perms,
+ group_perms,
+ everyone_perms,
+ display_name,
+ callback,
+ LLGlobalEconomy::Singleton::getInstance()->getPriceUpload(),
+ userdata);
}
+
+ //LLImportColladaAssetCache::getInstance()->assetUploaded(mVFileID, content["new_asset"], TRUE);
}
LLSendTexLayerResponder::LLSendTexLayerResponder(const LLSD& post_data,
@@ -390,17 +472,19 @@ void LLSendTexLayerResponder::error(U32 statusNum, const std::string& reason)
mBakedUploadData = NULL; // deleted in onTextureUploadComplete()
}
-LLUpdateAgentInventoryResponder::LLUpdateAgentInventoryResponder(const LLSD& post_data,
- const LLUUID& vfile_id,
- LLAssetType::EType asset_type)
-: LLAssetUploadResponder(post_data, vfile_id, asset_type)
+LLUpdateAgentInventoryResponder::LLUpdateAgentInventoryResponder(
+ const LLSD& post_data,
+ const LLUUID& vfile_id,
+ LLAssetType::EType asset_type)
+ : LLAssetUploadResponder(post_data, vfile_id, asset_type)
{
}
-LLUpdateAgentInventoryResponder::LLUpdateAgentInventoryResponder(const LLSD& post_data,
- const std::string& file_name,
- LLAssetType::EType asset_type)
-: LLAssetUploadResponder(post_data, file_name, asset_type)
+LLUpdateAgentInventoryResponder::LLUpdateAgentInventoryResponder(
+ const LLSD& post_data,
+ const std::string& file_name,
+ LLAssetType::EType asset_type)
+ : LLAssetUploadResponder(post_data, file_name, asset_type)
{
}
@@ -583,3 +667,474 @@ void LLUpdateTaskInventoryResponder::uploadComplete(const LLSD& content)
break;
}
}
+
+
+/////////////////////////////////////////////////////
+// LLNewAgentInventoryVariablePriceResponder::Impl //
+/////////////////////////////////////////////////////
+class LLNewAgentInventoryVariablePriceResponder::Impl
+{
+public:
+ Impl(
+ const LLUUID& vfile_id,
+ LLAssetType::EType asset_type,
+ const LLSD& inventory_data) :
+ mVFileID(vfile_id),
+ mAssetType(asset_type),
+ mInventoryData(inventory_data),
+ mFileName("")
+ {
+ if (!gVFS->getExists(vfile_id, asset_type))
+ {
+ llwarns
+ << "LLAssetUploadResponder called with nonexistant "
+ << "vfile_id " << vfile_id << llendl;
+ mVFileID.setNull();
+ mAssetType = LLAssetType::AT_NONE;
+ }
+ }
+
+ Impl(
+ const std::string& file_name,
+ LLAssetType::EType asset_type,
+ const LLSD& inventory_data) :
+ mFileName(file_name),
+ mAssetType(asset_type),
+ mInventoryData(inventory_data)
+ {
+ mVFileID.setNull();
+ }
+
+ std::string getFilenameOrIDString() const
+ {
+ return (mFileName.empty() ? mVFileID.asString() : mFileName);
+ }
+
+ LLUUID getVFileID() const
+ {
+ return mVFileID;
+ }
+
+ std::string getFilename() const
+ {
+ return mFileName;
+ }
+
+ LLAssetType::EType getAssetType() const
+ {
+ return mAssetType;
+ }
+
+ LLInventoryType::EType getInventoryType() const
+ {
+ return LLInventoryType::lookup(
+ mInventoryData["inventory_type"].asString());
+ }
+
+ std::string getInventoryTypeString() const
+ {
+ return mInventoryData["inventory_type"].asString();
+ }
+
+ LLUUID getFolderID() const
+ {
+ return mInventoryData["folder_id"].asUUID();
+ }
+
+ std::string getItemName() const
+ {
+ return mInventoryData["name"].asString();
+ }
+
+ std::string getItemDescription() const
+ {
+ return mInventoryData["description"].asString();
+ }
+
+ void displayCannotUploadReason(const std::string& reason)
+ {
+ LLSD args;
+ args["FILE"] = getFilenameOrIDString();
+ args["REASON"] = reason;
+
+
+ LLNotificationsUtil::add("CannotUploadReason", args);
+ LLUploadDialog::modalUploadFinished();
+ }
+
+ void onApplicationLevelError(const LLSD& error)
+ {
+ static const std::string _IDENTIFIER = "identifier";
+
+ static const std::string _INSUFFICIENT_FUNDS =
+ "NewAgentInventory_InsufficientLindenDollarBalance";
+ static const std::string _MISSING_REQUIRED_PARAMETER =
+ "NewAgentInventory_MissingRequiredParamater";
+ static const std::string _INVALID_REQUEST_BODY =
+ "NewAgentInventory_InvalidRequestBody";
+ static const std::string _RESOURCE_COST_DIFFERS =
+ "NewAgentInventory_ResourceCostDiffers";
+
+ static const std::string _MISSING_PARAMETER = "missing_parameter";
+ static const std::string _INVALID_PARAMETER = "invalid_parameter";
+ static const std::string _MISSING_RESOURCE = "missing_resource";
+ static const std::string _INVALID_RESOURCE = "invalid_resource";
+
+ // TODO* Add the other error_identifiers
+
+ std::string error_identifier = error[_IDENTIFIER].asString();
+
+ // TODO*: Pull these user visible strings from an xml file
+ // to be localized
+ if ( _INSUFFICIENT_FUNDS == error_identifier )
+ {
+ displayCannotUploadReason("You do not have a sufficient L$ balance to complete this upload.");
+ }
+ else if ( _MISSING_REQUIRED_PARAMETER == error_identifier )
+ {
+ // Missing parameters
+ if (error.has(_MISSING_PARAMETER) )
+ {
+ std::string message =
+ "Upload request was missing required parameter '[P]'";
+ LLStringUtil::replaceString(
+ message,
+ "[P]",
+ error[_MISSING_PARAMETER].asString());
+
+ displayCannotUploadReason(message);
+ }
+ else
+ {
+ std::string message =
+ "Upload request was missing a required parameter";
+ displayCannotUploadReason(message);
+ }
+ }
+ else if ( _INVALID_REQUEST_BODY == error_identifier )
+ {
+ // Invalid request body, check to see if
+ // a particular parameter was invalid
+ if ( error.has(_INVALID_PARAMETER) )
+ {
+ std::string message = "Upload parameter '[P]' is invalid.";
+ LLStringUtil::replaceString(
+ message,
+ "[P]",
+ error[_INVALID_PARAMETER].asString());
+
+ // See if the server also responds with what resource
+ // is missing.
+ if ( error.has(_MISSING_RESOURCE) )
+ {
+ message += "\nMissing resource '[R]'.";
+
+ LLStringUtil::replaceString(
+ message,
+ "[R]",
+ error[_MISSING_RESOURCE].asString());
+ }
+ else if ( error.has(_INVALID_RESOURCE) )
+ {
+ message += "\nInvalid resource '[R]'.";
+
+ LLStringUtil::replaceString(
+ message,
+ "[R]",
+ error[_INVALID_RESOURCE].asString());
+ }
+
+ displayCannotUploadReason(message);
+ }
+ else
+ {
+ std::string message = "Upload request was malformed";
+ displayCannotUploadReason(message);
+ }
+ }
+ else if ( _RESOURCE_COST_DIFFERS == error_identifier )
+ {
+ displayCannotUploadReason("The resource cost associated with this upload is not consistent with the server.");
+ }
+ else
+ {
+ displayCannotUploadReason("Unknown Error");
+ }
+ }
+
+ void onTransportError()
+ {
+ displayCannotUploadReason(
+ "The server is experiencing unexpected difficulties.");
+ }
+
+ void onTransportError(const LLSD& error)
+ {
+ static const std::string _IDENTIFIER = "identifier";
+
+ static const std::string _SERVER_ERROR_AFTER_CHARGE =
+ "NewAgentInventory_ServerErrorAfterCharge";
+
+ std::string error_identifier = error[_IDENTIFIER].asString();
+
+ // TODO*: Pull the user visible strings from an xml file
+ // to be localized
+
+ if ( _SERVER_ERROR_AFTER_CHARGE == error_identifier )
+ {
+ displayCannotUploadReason(
+ "The server is experiencing unexpected difficulties. You may have been charged for the upload.");
+ }
+ else
+ {
+ displayCannotUploadReason(
+ "The server is experiencing unexpected difficulties.");
+ }
+ }
+
+ bool uploadConfirmationCallback(
+ const LLSD& notification,
+ const LLSD& response,
+ boost::intrusive_ptr<LLNewAgentInventoryVariablePriceResponder> responder)
+ {
+ S32 option;
+ std::string confirmation_url;
+
+ option = LLNotificationsUtil::getSelectedOption(
+ notification,
+ response);
+
+ confirmation_url =
+ notification["payload"]["confirmation_url"].asString();
+
+ // Yay! We are confirming or cancelling our upload
+ switch(option)
+ {
+ case 0:
+ {
+ confirmUpload(confirmation_url, responder);
+ }
+ break;
+ case 1:
+ default:
+ break;
+ }
+
+ return false;
+ }
+
+ void confirmUpload(
+ const std::string& confirmation_url,
+ boost::intrusive_ptr<LLNewAgentInventoryVariablePriceResponder> responder)
+ {
+ if ( getFilename().empty() )
+ {
+ // we have no filename, use virtual file ID instead
+ LLHTTPClient::postFile(
+ confirmation_url,
+ getVFileID(),
+ getAssetType(),
+ responder);
+ }
+ else
+ {
+ LLHTTPClient::postFile(
+ confirmation_url,
+ getFilename(),
+ responder);
+ }
+ }
+
+
+private:
+ std::string mFileName;
+
+ LLSD mInventoryData;
+ LLAssetType::EType mAssetType;
+ LLUUID mVFileID;
+};
+
+///////////////////////////////////////////////
+// LLNewAgentInventoryVariablePriceResponder //
+///////////////////////////////////////////////
+LLNewAgentInventoryVariablePriceResponder::LLNewAgentInventoryVariablePriceResponder(
+ const LLUUID& vfile_id,
+ LLAssetType::EType asset_type,
+ const LLSD& inventory_info)
+{
+ mImpl = new Impl(
+ vfile_id,
+ asset_type,
+ inventory_info);
+}
+
+LLNewAgentInventoryVariablePriceResponder::LLNewAgentInventoryVariablePriceResponder(
+ const std::string& file_name,
+ LLAssetType::EType asset_type,
+ const LLSD& inventory_info)
+{
+ mImpl = new Impl(
+ file_name,
+ asset_type,
+ inventory_info);
+}
+
+LLNewAgentInventoryVariablePriceResponder::~LLNewAgentInventoryVariablePriceResponder()
+{
+ delete mImpl;
+}
+
+void LLNewAgentInventoryVariablePriceResponder::errorWithContent(
+ U32 statusNum,
+ const std::string& reason,
+ const LLSD& content)
+{
+ lldebugs
+ << "LLNewAgentInventoryVariablePrice::error " << statusNum
+ << " reason: " << reason << llendl;
+
+ if ( content.has("error") )
+ {
+ static const std::string _ERROR = "error";
+
+ mImpl->onTransportError(content[_ERROR]);
+ }
+ else
+ {
+ mImpl->onTransportError();
+ }
+}
+
+void LLNewAgentInventoryVariablePriceResponder::result(const LLSD& content)
+{
+ // Parse out application level errors and the appropriate
+ // responses for them
+ static const std::string _ERROR = "error";
+ static const std::string _STATE = "state";
+
+ static const std::string _COMPLETE = "complete";
+ static const std::string _CONFIRM_UPLOAD = "confirm_upload";
+
+ static const std::string _UPLOAD_PRICE = "upload_price";
+ static const std::string _RESOURCE_COST = "resource_cost";
+ static const std::string _RSVP = "rsvp";
+
+ // Check for application level errors
+ if ( content.has(_ERROR) )
+ {
+ onApplicationLevelError(content[_ERROR]);
+ return;
+ }
+
+ std::string state = content[_STATE];
+ LLAssetType::EType asset_type = mImpl->getAssetType();
+
+ if ( _COMPLETE == state )
+ {
+ // rename file in VFS with new asset id
+ if (mImpl->getFilename().empty())
+ {
+ // rename the file in the VFS to the actual asset id
+ // llinfos << "Changing uploaded asset UUID to " << content["new_asset"].asUUID() << llendl;
+ gVFS->renameFile(
+ mImpl->getVFileID(),
+ asset_type,
+ content["new_asset"].asUUID(),
+ asset_type);
+ }
+
+ on_new_single_inventory_upload_complete(
+ asset_type,
+ mImpl->getInventoryType(),
+ mImpl->getInventoryTypeString(),
+ mImpl->getFolderID(),
+ mImpl->getItemName(),
+ mImpl->getItemDescription(),
+ content,
+ content[_UPLOAD_PRICE].asInteger());
+
+ // TODO* Add bulk (serial) uploading or add
+ // a super class of this that does so
+ }
+ else if ( _CONFIRM_UPLOAD == state )
+ {
+ showConfirmationDialog(
+ content[_UPLOAD_PRICE].asInteger(),
+ content[_RESOURCE_COST].asInteger(),
+ content[_RSVP].asString());
+ }
+ else
+ {
+ onApplicationLevelError("");
+ }
+}
+
+void LLNewAgentInventoryVariablePriceResponder::onApplicationLevelError(
+ const LLSD& error)
+{
+ mImpl->onApplicationLevelError(error);
+}
+
+void LLNewAgentInventoryVariablePriceResponder::showConfirmationDialog(
+ S32 upload_price,
+ S32 resource_cost,
+ const std::string& confirmation_url)
+{
+ if ( 0 == upload_price )
+ {
+ // don't show confirmation dialog for free uploads, I mean,
+ // they're free!
+
+ // The creating of a new instrusive_ptr(this)
+ // creates a new boost::intrusive_ptr
+ // which is a copy of this. This code is required because
+ // 'this' is always of type Class* and not the intrusive_ptr,
+ // and thus, a reference to 'this' is not registered
+ // by using just plain 'this'.
+
+ // Since LLNewAgentInventoryVariablePriceResponder is a
+ // reference counted class, it is possible (since the
+ // reference to a plain 'this' would be missed here) that,
+ // when using plain ol' 'this', that this object
+ // would be deleted before the callback is triggered
+ // and cause sadness.
+ mImpl->confirmUpload(
+ confirmation_url,
+ boost::intrusive_ptr<LLNewAgentInventoryVariablePriceResponder>(this));
+ }
+ else
+ {
+ LLSD substitutions;
+ LLSD payload;
+
+ substitutions["PRICE"] = upload_price;
+
+ payload["confirmation_url"] = confirmation_url;
+
+ // The creating of a new instrusive_ptr(this)
+ // creates a new boost::intrusive_ptr
+ // which is a copy of this. This code is required because
+ // 'this' is always of type Class* and not the intrusive_ptr,
+ // and thus, a reference to 'this' is not registered
+ // by using just plain 'this'.
+
+ // Since LLNewAgentInventoryVariablePriceResponder is a
+ // reference counted class, it is possible (since the
+ // reference to a plain 'this' would be missed here) that,
+ // when using plain ol' 'this', that this object
+ // would be deleted before the callback is triggered
+ // and cause sadness.
+ LLNotificationsUtil::add(
+ "UploadCostConfirmation",
+ substitutions,
+ payload,
+ boost::bind(
+ &LLNewAgentInventoryVariablePriceResponder::Impl::uploadConfirmationCallback,
+ mImpl,
+ _1,
+ _2,
+ boost::intrusive_ptr<LLNewAgentInventoryVariablePriceResponder>(this)));
+ }
+}
+
+
diff --git a/indra/newview/llassetuploadresponders.h b/indra/newview/llassetuploadresponders.h
index 752c0dfe45..70871b62e2 100644
--- a/indra/newview/llassetuploadresponders.h
+++ b/indra/newview/llassetuploadresponders.h
@@ -55,15 +55,58 @@ protected:
std::string mFileName;
};
+// TODO*: Remove this once deprecated
class LLNewAgentInventoryResponder : public LLAssetUploadResponder
{
public:
- LLNewAgentInventoryResponder(const LLSD& post_data,
- const LLUUID& vfile_id,
- LLAssetType::EType asset_type);
- LLNewAgentInventoryResponder(const LLSD& post_data, const std::string& file_name,
- LLAssetType::EType asset_type);
+ LLNewAgentInventoryResponder(
+ const LLSD& post_data,
+ const LLUUID& vfile_id,
+ LLAssetType::EType asset_type);
+ LLNewAgentInventoryResponder(
+ const LLSD& post_data,
+ const std::string& file_name,
+ LLAssetType::EType asset_type);
+ virtual void error(U32 statusNum, const std::string& reason);
virtual void uploadComplete(const LLSD& content);
+ virtual void uploadFailure(const LLSD& content);
+};
+
+// A base class which goes through and performs some default
+// actions for variable price uploads. If more specific actions
+// are needed (such as different confirmation messages, etc.)
+// the functions onApplicationLevelError and showConfirmationDialog.
+class LLNewAgentInventoryVariablePriceResponder :
+ public LLHTTPClient::Responder
+{
+public:
+ LLNewAgentInventoryVariablePriceResponder(
+ const LLUUID& vfile_id,
+ LLAssetType::EType asset_type,
+ const LLSD& inventory_info);
+
+ LLNewAgentInventoryVariablePriceResponder(
+ const std::string& file_name,
+ LLAssetType::EType asset_type,
+ const LLSD& inventory_info);
+ virtual ~LLNewAgentInventoryVariablePriceResponder();
+
+ void errorWithContent(
+ U32 statusNum,
+ const std::string& reason,
+ const LLSD& content);
+ void result(const LLSD& content);
+
+ virtual void onApplicationLevelError(
+ const LLSD& error);
+ virtual void showConfirmationDialog(
+ S32 upload_price,
+ S32 resource_cost,
+ const std::string& confirmation_url);
+
+private:
+ class Impl;
+ Impl* mImpl;
};
struct LLBakedUploadData;
diff --git a/indra/newview/llavataractions.cpp b/indra/newview/llavataractions.cpp
index afa8b62c74..afa8b62c74 100755..100644
--- a/indra/newview/llavataractions.cpp
+++ b/indra/newview/llavataractions.cpp
diff --git a/indra/newview/llbottomtray.cpp b/indra/newview/llbottomtray.cpp
index 0c0df14ac1..1fb83fe567 100644
--- a/indra/newview/llbottomtray.cpp
+++ b/indra/newview/llbottomtray.cpp
@@ -1,1850 +1,1850 @@
-/**
- * @file llbottomtray.cpp
- * @brief LLBottomTray class implementation
- *
- * $LicenseInfo:firstyear=2009&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-#include "llviewerprecompiledheaders.h" // must be first include
-
-#define LLBOTTOMTRAY_CPP
-#include "llbottomtray.h"
-
-// library includes
-#include "llfloaterreg.h"
-#include "llflyoutbutton.h"
-#include "lllayoutstack.h"
-#include "llnotifications.h"
-#include "llnotificationsutil.h"
-#include "lltexteditor.h"
-
-// newview includes
-#include "llagent.h"
-#include "llagentcamera.h"
-#include "llavataractions.h"
-#include "llchiclet.h"
-#include "llfloatercamera.h"
-#include "llhints.h"
-#include "llimfloater.h" // for LLIMFloater
-#include "llnearbychatbar.h"
-#include "llsidetray.h"
-#include "llspeakbutton.h"
-#include "llsplitbutton.h"
-#include "llsyswellwindow.h"
-#include "lltoolmgr.h"
-#include "llviewerparcelmgr.h"
-
-#include "llviewerwindow.h"
-#include "llsdserialize.h"
-
-// Distance from mouse down on which drag'n'drop should be started.
-#define DRAG_START_DISTANCE 3
-
-static const std::string SORTING_DATA_FILE_NAME = "bottomtray_buttons_order.xml";
-
-LLDefaultChildRegistry::Register<LLBottomtrayButton> bottomtray_button("bottomtray_button");
-
-// LLBottomtrayButton methods
-
-// virtual
-BOOL LLBottomtrayButton::handleHover(S32 x, S32 y, MASK mask)
-{
- if (mCanDrag)
- {
- // pass hover to bottomtray
- S32 screenX, screenY;
- localPointToScreen(x, y, &screenX, &screenY);
- LLBottomTray::getInstance()->onDraggableButtonHover(screenX, screenY);
-
- return TRUE;
- }
- else
- {
- return LLButton::handleHover(x, y, mask);
- }
-}
-//virtual
-BOOL LLBottomtrayButton::handleMouseUp(S32 x, S32 y, MASK mask)
-{
- if (mCanDrag)
- {
- S32 screenX, screenY;
- localPointToScreen(x, y, &screenX, &screenY);
- // pass mouse up to bottomtray
- LLBottomTray::getInstance()->onDraggableButtonMouseUp(this, screenX, screenY);
- }
- return LLButton::handleMouseUp(x, y, mask);
-}
-//virtual
-BOOL LLBottomtrayButton::handleMouseDown(S32 x, S32 y, MASK mask)
-{
- if (mCanDrag)
- {
- S32 screenX, screenY;
- localPointToScreen(x, y, &screenX, &screenY);
- // pass mouse up to bottomtray
- LLBottomTray::getInstance()->onDraggableButtonMouseDown(this, screenX, screenY);
- }
- return LLButton::handleMouseDown(x, y, mask);
-}
-
-static void update_build_button_enable_state()
-{
- bool can_edit = LLToolMgr::getInstance()->canEdit();
-
- LLBottomTray::getInstance()->getChildView("build_btn")->setEnabled(can_edit);
-}
-
-// Build time optimization, generate extern template once in .cpp file
-template class LLBottomTray* LLSingleton<class LLBottomTray>::getInstance();
-
-namespace
-{
- const std::string& PANEL_CHICLET_NAME = "chiclet_list_panel";
-
- S32 get_panel_min_width(LLLayoutStack* stack, LLView* panel)
- {
- S32 minimal_width = 0;
- llassert(stack);
- if ( stack && panel && panel->getVisible() )
- {
- stack->getPanelMinSize(panel->getName(), &minimal_width);
- }
- return minimal_width;
- }
-
- S32 get_panel_max_width(LLLayoutStack* stack, LLPanel* panel)
- {
- S32 max_width = 0;
- llassert(stack);
- if ( stack && panel && panel->getVisible() )
- {
- stack->getPanelMaxSize(panel->getName(), &max_width);
- }
- return max_width;
- }
-
- S32 get_curr_width(LLUICtrl* ctrl)
- {
- S32 cur_width = 0;
- if ( ctrl && ctrl->getVisible() )
- {
- cur_width = ctrl->getRect().getWidth();
- }
- return cur_width;
- }
-}
-
-class LLBottomTrayLite
- : public LLPanel
-{
-public:
- LLBottomTrayLite()
- : mNearbyChatBar(NULL),
- mChatBarContainer(NULL),
- mGesturePanel(NULL)
- {
- mFactoryMap["chat_bar"] = LLCallbackMap(LLBottomTray::createNearbyChatBar, NULL);
- buildFromFile("panel_bottomtray_lite.xml");
- }
-
- BOOL postBuild()
- {
- mNearbyChatBar = findChild<LLNearbyChatBar>("chat_bar");
- mChatBarContainer = getChild<LLLayoutPanel>("chat_bar_layout_panel");
- mGesturePanel = getChild<LLPanel>("gesture_panel");
-
- // Hide "show_nearby_chat" button
- if (mNearbyChatBar)
- {
- LLLineEditor* chat_box = mNearbyChatBar->getChatBox();
- LLUICtrl* show_btn = mNearbyChatBar->getChild<LLUICtrl>("show_nearby_chat");
- S32 delta_width = show_btn->getRect().getWidth();
- show_btn->setVisible(FALSE);
- chat_box->reshape(chat_box->getRect().getWidth() + delta_width, chat_box->getRect().getHeight());
- }
- return TRUE;
- }
-
- void onFocusLost()
- {
- if (gAgentCamera.cameraMouselook())
- {
- LLBottomTray::getInstance()->setVisible(FALSE);
- }
- }
-
- LLNearbyChatBar* mNearbyChatBar;
- LLLayoutPanel* mChatBarContainer;
- LLPanel* mGesturePanel;
-};
-
-LLBottomTray::LLBottomTray(const LLSD&)
-: mChicletPanel(NULL),
- mSpeakPanel(NULL),
- mSpeakBtn(NULL),
- mNearbyChatBar(NULL),
- mChatBarContainer(NULL),
- mNearbyCharResizeHandlePanel(NULL),
- mToolbarStack(NULL),
- mMovementButton(NULL),
- mResizeState(RS_NORESIZE),
- mBottomTrayContextMenu(NULL),
- mCamButton(NULL),
- mBottomTrayLite(NULL),
- mIsInLiteMode(false),
- mDragStarted(false),
- mDraggedItem(NULL),
- mLandingTab(NULL),
- mCheckForDrag(false)
-{
- // Firstly add ourself to IMSession observers, so we catch session events
- // before chiclets do that.
- LLIMMgr::getInstance()->addSessionObserver(this);
-
- mFactoryMap["chat_bar"] = LLCallbackMap(LLBottomTray::createNearbyChatBar, NULL);
-
- buildFromFile("panel_bottomtray.xml");
-
- LLUICtrl::CommitCallbackRegistry::defaultRegistrar().add("CameraPresets.ChangeView", boost::bind(&LLFloaterCamera::onClickCameraItem, _2));
-
- //this is to fix a crash that occurs because LLBottomTray is a singleton
- //and thus is deleted at the end of the viewers lifetime, but to be cleanly
- //destroyed LLBottomTray requires some subsystems that are long gone
- //LLUI::getRootView()->addChild(this);
-
- {
- mBottomTrayLite = new LLBottomTrayLite();
- mBottomTrayLite->setFollowsAll();
- mBottomTrayLite->setVisible(FALSE);
- }
-
- mImageDragIndication = LLUI::getUIImage(getString("DragIndicationImageName"));
- mDesiredNearbyChatWidth = mNearbyChatBar ? mNearbyChatBar->getRect().getWidth() : 0;
-}
-
-LLBottomTray::~LLBottomTray()
-{
- if (!LLSingleton<LLIMMgr>::destroyed())
- {
- LLIMMgr::getInstance()->removeSessionObserver(this);
- }
-
- if (mNearbyChatBar)
- {
- // store custom width of chatbar panel.
- S32 custom_width = mChatBarContainer->getRect().getWidth();
- gSavedSettings.setS32("ChatBarCustomWidth", custom_width);
- }
-
- // emulate previous floater behavior to be hidden on startup.
- // override effect of save_visibility=true.
- // this attribute is necessary to button.initial_callback=Button.SetFloaterToggle works properly:
- // i.g when floater changes its visibility - button changes its toggle state.
- getChild<LLUICtrl>("build_btn")->setControlValue(false);
- getChild<LLUICtrl>("search_btn")->setControlValue(false);
- getChild<LLUICtrl>("world_map_btn")->setControlValue(false);
-}
-
-// *TODO Vadim: why void* ?
-void* LLBottomTray::createNearbyChatBar(void* userdata)
-{
- return new LLNearbyChatBar();
-}
-
-LLNearbyChatBar* LLBottomTray::getNearbyChatBar()
-{
- return mIsInLiteMode ? mBottomTrayLite->mNearbyChatBar : mNearbyChatBar;
-}
-
-LLIMChiclet* LLBottomTray::createIMChiclet(const LLUUID& session_id)
-{
- LLIMChiclet::EType im_chiclet_type = LLIMChiclet::getIMSessionType(session_id);
-
- switch (im_chiclet_type)
- {
- case LLIMChiclet::TYPE_IM:
- return getChicletPanel()->createChiclet<LLIMP2PChiclet>(session_id);
- case LLIMChiclet::TYPE_GROUP:
- return getChicletPanel()->createChiclet<LLIMGroupChiclet>(session_id);
- case LLIMChiclet::TYPE_AD_HOC:
- return getChicletPanel()->createChiclet<LLAdHocChiclet>(session_id);
- case LLIMChiclet::TYPE_UNKNOWN:
- break;
- }
-
- return NULL;
-}
-
-//virtual
-void LLBottomTray::sessionAdded(const LLUUID& session_id, const std::string& name, const LLUUID& other_participant_id)
-{
- if (!getChicletPanel()) return;
-
- LLIMModel::LLIMSession* session = LLIMModel::getInstance()->findIMSession(session_id);
- if (!session) return;
-
- // no need to spawn chiclets for participants in P2P calls called through Avaline
- if (session->isP2P() && session->isOtherParticipantAvaline()) return;
-
- if (getChicletPanel()->findChiclet<LLChiclet>(session_id)) return;
-
- LLIMChiclet* chiclet = createIMChiclet(session_id);
- if(chiclet)
- {
- chiclet->setIMSessionName(name);
- chiclet->setOtherParticipantId(other_participant_id);
-
- LLIMFloater::onIMChicletCreated(session_id);
-
- }
- else
- {
- llerrs << "Could not create chiclet" << llendl;
- }
-}
-
-//virtual
-void LLBottomTray::sessionRemoved(const LLUUID& session_id)
-{
- if(getChicletPanel())
- {
- // IM floater should be closed when session removed and associated chiclet closed
- LLIMFloater* iMfloater = LLFloaterReg::findTypedInstance<LLIMFloater>(
- "impanel", session_id);
- if (iMfloater != NULL)
- {
- iMfloater->closeFloater();
- }
-
- getChicletPanel()->removeChiclet(session_id);
- }
-}
-
-void LLBottomTray::sessionIDUpdated(const LLUUID& old_session_id, const LLUUID& new_session_id)
-{
- //this is only needed in case of outgoing ad-hoc/group chat sessions
- LLChicletPanel* chiclet_panel = getChicletPanel();
- if (chiclet_panel)
- {
- //it should be ad-hoc im chiclet or group im chiclet
- LLChiclet* chiclet = chiclet_panel->findChiclet<LLChiclet>(old_session_id);
- if (chiclet) chiclet->setSessionId(new_session_id);
- }
-}
-
-S32 LLBottomTray::getTotalUnreadIMCount()
-{
- return getChicletPanel()->getTotalUnreadIMCount();
-}
-
-// virtual
-void LLBottomTray::onChange(EStatusType status, const std::string &channelURI, bool proximal)
-{
- // Time it takes to connect to voice channel might be pretty long,
- // so don't expect user login or STATUS_VOICE_ENABLED to be followed by STATUS_JOINED.
- BOOL enable = FALSE;
-
- switch (status)
- {
- // Do not add STATUS_VOICE_ENABLED because voice chat is
- // inactive until STATUS_JOINED
- case STATUS_JOINED:
- enable = TRUE;
- break;
- default:
- enable = FALSE;
- break;
- }
-
- // We have to enable/disable right and left parts of speak button separately (EXT-4648)
- mSpeakBtn->setSpeakBtnEnabled(enable);
- // skipped to avoid button blinking
- if (status != STATUS_JOINING && status!= STATUS_LEFT_CHANNEL)
- {
- mSpeakBtn->setFlyoutBtnEnabled(LLVoiceClient::getInstance()->voiceEnabled() && LLVoiceClient::getInstance()->isVoiceWorking());
- }
-}
-
-void LLBottomTray::onMouselookModeOut()
-{
- mIsInLiteMode = false;
- mBottomTrayLite->setVisible(FALSE);
- mNearbyChatBar->getChatBox()->setText(mBottomTrayLite->mNearbyChatBar->getChatBox()->getText());
- setVisible(TRUE);
-}
-
-void LLBottomTray::onMouselookModeIn()
-{
- setVisible(FALSE);
-
- // Attach the lite bottom tray
- if (getParent() && mBottomTrayLite->getParent() != getParent())
- getParent()->addChild(mBottomTrayLite);
-
- mBottomTrayLite->setShape(getLocalRect());
- mBottomTrayLite->mNearbyChatBar->getChatBox()->setText(mNearbyChatBar->getChatBox()->getText());
- mBottomTrayLite->mGesturePanel->setVisible(gSavedSettings.getBOOL("ShowGestureButton"));
-
- mIsInLiteMode = true;
-}
-
-//virtual
-// setVisible used instead of onVisibilityChange, since LLAgent calls it on entering/leaving mouselook mode.
-// If bottom tray is already visible in mouselook mode, then onVisibilityChange will not be called from setVisible(true),
-void LLBottomTray::setVisible(BOOL visible)
-{
- if (mIsInLiteMode)
- {
- mBottomTrayLite->setVisible(visible);
- }
- else
- {
- LLPanel::setVisible(visible);
- }
-}
-
-S32 LLBottomTray::notifyParent(const LLSD& info)
-{
- if(info.has("well_empty")) // implementation of EXT-3397
- {
- const std::string chiclet_name = info["well_name"];
-
- // only "im_well" or "notification_well" names are expected.
- // They are set in panel_bottomtray.xml in <chiclet_im_well> & <chiclet_notification>
- llassert("im_well" == chiclet_name || "notification_well" == chiclet_name);
-
- BOOL should_be_visible = !info["well_empty"];
- showWellButton("im_well" == chiclet_name ? RS_IM_WELL : RS_NOTIFICATION_WELL, should_be_visible);
- return 1;
- }
-
- if (info.has("action") && info["action"] == "resize")
- {
- const std::string& name = info["view_name"];
-
- // expected only resize of nearby chatbar
- if (mChatBarContainer->getName() != name) return LLPanel::notifyParent(info);
-
- const S32 new_width = info["new_width"];
-
- processChatbarCustomization(new_width);
-
- return 2;
- }
- return LLPanel::notifyParent(info);
-}
-
-void LLBottomTray::showBottomTrayContextMenu(S32 x, S32 y, MASK mask)
-{
- // We should show BottomTrayContextMenu in last turn
- if (mBottomTrayContextMenu && !LLMenuGL::sMenuContainer->getVisibleMenu())
- {
- //there are no other context menu (IM chiclet etc ), so we can show BottomTrayContextMenu
-
- updateContextMenu(x, y, mask);
- mBottomTrayContextMenu->buildDrawLabels();
- mBottomTrayContextMenu->updateParent(LLMenuGL::sMenuContainer);
- LLMenuGL::showPopup(this, mBottomTrayContextMenu, x, y);
-
- }
-}
-
-void LLBottomTray::updateContextMenu(S32 x, S32 y, MASK mask)
-{
- LLUICtrl* edit_box = mNearbyChatBar->getChild<LLUICtrl>("chat_box");
-
- S32 local_x = x - mChatBarContainer->getRect().mLeft - edit_box->getRect().mLeft;
- S32 local_y = y - mChatBarContainer->getRect().mBottom - edit_box->getRect().mBottom;
-
- bool in_edit_box = edit_box->pointInView(local_x, local_y);
-
- mBottomTrayContextMenu->setItemVisible("Separator", in_edit_box);
- mBottomTrayContextMenu->setItemVisible("NearbyChatBar_Cut", in_edit_box);
- mBottomTrayContextMenu->setItemVisible("NearbyChatBar_Copy", in_edit_box);
- mBottomTrayContextMenu->setItemVisible("NearbyChatBar_Paste", in_edit_box);
- mBottomTrayContextMenu->setItemVisible("NearbyChatBar_Delete", in_edit_box);
- mBottomTrayContextMenu->setItemVisible("NearbyChatBar_Select_All", in_edit_box);
-}
-
-void LLBottomTray::showGestureButton(BOOL visible)
-{
- setTrayButtonVisibleIfPossible(RS_BUTTON_GESTURES, visible);
-}
-
-void LLBottomTray::showMoveButton(BOOL visible)
-{
- setTrayButtonVisibleIfPossible(RS_BUTTON_MOVEMENT, visible);
-}
-
-void LLBottomTray::showCameraButton(BOOL visible)
-{
- setTrayButtonVisibleIfPossible(RS_BUTTON_CAMERA, visible);
-}
-
-void LLBottomTray::showSnapshotButton(BOOL visible)
-{
- setTrayButtonVisibleIfPossible(RS_BUTTON_SNAPSHOT, visible);
-}
-
-void LLBottomTray::showSpeakButton(bool visible)
-{
- // Show/hide the button
- setTrayButtonVisible(RS_BUTTON_SPEAK, visible);
-
- // and adjust other panels according to the occupied/freed space.
- const S32 panel_width = mSpeakPanel->getRect().getWidth();
- if (visible)
- {
- processWidthDecreased(-panel_width);
- }
- else
- {
- processWidthIncreased(panel_width);
- }
-}
-
-void LLBottomTray::toggleMovementControls()
-{
- if (mMovementButton)
- mMovementButton->onCommit();
-}
-
-void LLBottomTray::toggleCameraControls()
-{
- if (mCamButton)
- mCamButton->onCommit();
-}
-
-BOOL LLBottomTray::postBuild()
-{
- LLHints::registerHintTarget("bottom_tray", LLView::getHandle());
- LLHints::registerHintTarget("dest_guide_btn", getChild<LLUICtrl>("destination_btn")->getHandle());
- LLHints::registerHintTarget("avatar_picker_btn", getChild<LLUICtrl>("avatar_btn")->getHandle());
-
- LLUICtrl::CommitCallbackRegistry::currentRegistrar().add("NearbyChatBar.Action", boost::bind(&LLBottomTray::onContextMenuItemClicked, this, _2));
- LLUICtrl::EnableCallbackRegistry::currentRegistrar().add("NearbyChatBar.EnableMenuItem", boost::bind(&LLBottomTray::onContextMenuItemEnabled, this, _2));
-
- mBottomTrayContextMenu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_bottomtray.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
- gMenuHolder->addChild(mBottomTrayContextMenu);
-
- mNearbyChatBar = findChild<LLNearbyChatBar>("chat_bar");
- LLHints::registerHintTarget("chat_bar", mNearbyChatBar->LLView::getHandle());
-
- mChatBarContainer = getChild<LLLayoutPanel>("chat_bar_layout_panel");
- mNearbyCharResizeHandlePanel = getChild<LLPanel>("chat_bar_resize_handle_panel");
-
- mToolbarStack = getChild<LLLayoutStack>("toolbar_stack");
- mMovementButton = getChild<LLButton>("movement_btn");
- LLHints::registerHintTarget("move_btn", mMovementButton->getHandle());
- mCamButton = getChild<LLButton>("camera_btn");
- setRightMouseDownCallback(boost::bind(&LLBottomTray::showBottomTrayContextMenu,this, _2, _3,_4));
-
- mSpeakPanel = getChild<LLPanel>("speak_panel");
- mSpeakBtn = getChild<LLSpeakButton>("talk");
-
- // Both parts of speak button should be initially disabled because
- // it takes some time between logging in to world and connecting to voice channel.
- mSpeakBtn->setSpeakBtnEnabled(false);
- mSpeakBtn->setFlyoutBtnEnabled(false);
-
- // Localization tool doesn't understand custom buttons like <talk_button>
- mSpeakBtn->setSpeakToolTip( getString("SpeakBtnToolTip") );
- mSpeakBtn->setShowToolTip( getString("VoiceControlBtnToolTip") );
-
- // Registering Chat Bar to receive Voice client status change notifications.
- LLVoiceClient::getInstance()->addObserver(this);
-
- mNearbyChatBar->getChatBox()->setContextMenu(NULL);
-
- mChicletPanel = getChild<LLChicletPanel>("chiclet_list");
-
- initResizeStateContainers();
-
- setButtonsControlsAndListeners();
-
- initButtonsVisibility();
-
- // update wells visibility:
- showWellButton(RS_IM_WELL, !LLIMWellWindow::getInstance()->isWindowEmpty());
- showWellButton(RS_NOTIFICATION_WELL, !LLNotificationWellWindow::getInstance()->isWindowEmpty());
-
- loadButtonsOrder();
-
- LLViewerParcelMgr::getInstance()->addAgentParcelChangedCallback(boost::bind(&update_build_button_enable_state));
-
- return TRUE;
-}
-
-//Drag-n-drop
-
-void LLBottomTray::onDraggableButtonMouseDown(LLUICtrl* ctrl, S32 x, S32 y)
-{
- if (ctrl == NULL) return;
- LLView* parent_view = ctrl->getParent();
- if(parent_view != NULL)
- {
- // we actually drag'n'drop panel (not button) in code, so have to find a parent
- // of button which called this method on mouse down.
- LLPanel* parent = dynamic_cast<LLPanel*>(parent_view);
- // It may happen that we clicked not usual button, but button inside widget(speak, gesture)
- // so we'll need to get a level higher to reach layout panel as a parent.
- if(parent == NULL) parent = dynamic_cast<LLPanel*>(parent_view->getParent());
- if (parent && parent->getVisible())
- {
- mDraggedItem = parent;
- mCheckForDrag = true;
- mStartX = x;
- mStartY = y;
- }
- }
-}
-
-LLPanel* LLBottomTray::findChildPanelByLocalCoords(S32 x, S32 y)
-{
- LLPanel* ctrl = 0;
- S32 screenX, screenY;
- const child_list_t* list = mToolbarStack->getChildList();
-
- localPointToScreen(x, y, &screenX, &screenY);
-
- // look for a child panel which contains the point (screenX, screenY) in it's rectangle
- for (child_list_const_iter_t i = list->begin(); i != list->end(); ++i)
- {
- LLRect rect;
- localRectToScreen((*i)->getRect(), &rect);
-
- if (rect.pointInRect(screenX, screenY))
- {
- ctrl = dynamic_cast<LLPanel*>(*i);
- break;
- }
- }
-
- return ctrl;
-}
-
-void LLBottomTray::onDraggableButtonHover(S32 x, S32 y)
-{
- // if mouse down on draggable item was done, check whether we should start DnD
- if (mCheckForDrag)
- {
- // Start drag'n'drop if mouse cursor was dragged away frome mouse down location enough
- if(sqrt((float)((mStartX-x)*(mStartX-x)+(mStartY-y)*(mStartY-y))) > DRAG_START_DISTANCE)
- {
- mDragStarted = true;
- mCheckForDrag = false;
- }
- }
- if (mDragStarted)
- {
- // Check whether the cursor is over draggable area, find which panel it is and set is as
- // landing tab for drag'n'drop
- if(isCursorOverDraggableArea(x, y))
- {
- LLPanel* panel = findChildPanelByLocalCoords(x,y);
- if (panel && panel != mDraggedItem) mLandingTab = panel;
- gViewerWindow->getWindow()->setCursor(UI_CURSOR_ARROWDRAG);
- }
- else
- {
- gViewerWindow->getWindow()->setCursor(UI_CURSOR_NO);
- }
- }
- else
- {
- // Reset cursor in case you move your mouse from the drag handle to a button.
- getWindow()->setCursor(UI_CURSOR_ARROW);
-
- }
-}
-
-bool LLBottomTray::isCursorOverDraggableArea(S32 x, S32 y)
-{
- // Draggable area lasts from the nearby chat input resize handle
- // to the chiclet area (exlusively).
- bool result = getRect().pointInRect(x, y);
- result = result && mNearbyCharResizeHandlePanel->calcScreenRect().mRight < x;
- result = result && mChicletPanel->calcScreenRect().mRight > x;
- return result;
-}
-
-void LLBottomTray::updateButtonsOrdersAfterDnD()
-{
- // *TODO: change implementation of this method to support simplify it
- // (and according to future possible changes in the way button order is saved between sessions).
- state_object_map_t::const_iterator it = mStateProcessedObjectMap.begin();
- state_object_map_t::const_iterator it_end = mStateProcessedObjectMap.end();
- EResizeState dragged_state = RS_NORESIZE;
- EResizeState landing_state = RS_NORESIZE;
- bool landing_state_found = false;
- // Find states for dragged item and landing tab
- for (; it != it_end; ++it)
- {
- if (it->second == mDraggedItem)
- {
- dragged_state = it->first;
- }
- else if (it->second == mLandingTab)
- {
- landing_state = it->first;
- landing_state_found = true;
- }
- }
-
- if (dragged_state == RS_NORESIZE)
- {
- llwarns << "Cannot determine what button is being dragged" << llendl;
- llassert(dragged_state != RS_NORESIZE);
- return;
- }
-
- lldebugs << "Will place " << resizeStateToString(dragged_state)
- << " before " << resizeStateToString(landing_state) << llendl;
-
- // Update order of buttons according to drag'n'drop
- mButtonsOrder.erase(std::find(mButtonsOrder.begin(), mButtonsOrder.end(), dragged_state));
- if (!landing_state_found && mLandingTab == getChild<LLPanel>(PANEL_CHICLET_NAME))
- {
- mButtonsOrder.push_back(dragged_state);
- }
- else
- {
- if (!landing_state_found) landing_state = RS_BUTTON_SPEAK; // just a random fallback
- mButtonsOrder.insert(std::find(mButtonsOrder.begin(), mButtonsOrder.end(), landing_state), dragged_state);
- }
-
- // Synchronize button process order with their order
- resize_state_vec_t::const_iterator it1 = mButtonsOrder.begin();
- const resize_state_vec_t::const_iterator it_end1 = mButtonsOrder.end();
- resize_state_vec_t::iterator it2 = mButtonsProcessOrder.begin();
- for (; it1 != it_end1; ++it1)
- {
- // Skip Speak because it is not in mButtonsProcessOrder(it's the reason why mButtonsOrder was introduced).
- // If any other draggable items will be added to bottomtray later, they should also be skipped here.
- if (*it1 != RS_BUTTON_SPEAK)
- {
- *it2 = *it1;
- ++it2;
- }
- }
-
- saveButtonsOrder();
-}
-
-void LLBottomTray::saveButtonsOrder()
-{
- std::string user_dir = gDirUtilp->getLindenUserDir();
- if (user_dir.empty()) return;
-
- std::string filename = gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT, SORTING_DATA_FILE_NAME);
- LLSD settings_llsd;
- int i = 0;
- const resize_state_vec_t::const_iterator it_end = mButtonsOrder.end();
- // we use numbers as keys for map which is saved in file and contains resize states as its values
- for (resize_state_vec_t::const_iterator it = mButtonsOrder.begin(); it != it_end; ++it, i++)
- {
- std::string str = llformat("%d", i);
- settings_llsd[str] = *it;
- }
- llofstream file;
- file.open(filename);
- LLSDSerialize::toPrettyXML(settings_llsd, file);
-}
-
-void LLBottomTray::loadButtonsOrder()
-{
- // load per-resident sorting information
- std::string filename = gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT, SORTING_DATA_FILE_NAME);
-
- LLSD settings_llsd;
- llifstream file;
- file.open(filename);
- if (!file.is_open()) return;
-
- LLSDSerialize::fromXML(settings_llsd, file);
-
-
- mButtonsOrder.clear();
- mButtonsProcessOrder.clear();
- int i = 0;
- // getting button order from file
- for (LLSD::map_const_iterator iter = settings_llsd.beginMap();
- iter != settings_llsd.endMap(); ++iter, ++i)
- {
- std::string str = llformat("%d", i);
- EResizeState state = (EResizeState)settings_llsd[str].asInteger();
- mButtonsOrder.push_back(state);
- // RS_BUTTON_SPEAK is skipped, because it shouldn't be in mButtonsProcessOrder (it does not hide or shrink).
- if (state != RS_BUTTON_SPEAK)
- {
- mButtonsProcessOrder.push_back(state);
- }
- }
-
- // There are other panels in layout stack order of which is not saved. Also, panels order of which is saved,
- // are already in layout stack but in wrong order. The most convenient way to place them is moving them
- // to front one by one (because in this case we don't have to pass the panel before which we want to insert our
- // panel to movePanel()). So panels are moved in order from the end of mButtonsOrder vector(reverse iterator is used).
- const resize_state_vec_t::const_reverse_iterator it_end = mButtonsOrder.rend();
- // placing panels in layout stack according to button order which we loaded in previous for
- for (resize_state_vec_t::const_reverse_iterator it = mButtonsOrder.rbegin(); it != it_end; ++it, ++i)
- {
- LLPanel* panel_to_move = getButtonPanel(*it);
- mToolbarStack->movePanel(panel_to_move, NULL, true); // prepend
- }
- // Nearbychat is not stored in order settings file, but it must be the first of the panels, so moving it
- // (along with its drag handle) manually here.
- mToolbarStack->movePanel(getChild<LLLayoutPanel>("chat_bar_resize_handle_panel"), NULL, true);
- mToolbarStack->movePanel(mChatBarContainer, NULL, true);
-}
-
-void LLBottomTray::onDraggableButtonMouseUp(LLUICtrl* ctrl, S32 x, S32 y)
-{
- //if mouse up happened over area where drop is possible, change order of buttons
- if (mLandingTab != NULL && mDraggedItem != NULL && mDragStarted)
- {
- if(isCursorOverDraggableArea(x, y))
- {
- // change order of panels in layout stack
- mToolbarStack->movePanel(mDraggedItem, (LLPanel*)mLandingTab);
- // change order of buttons in order vectors
- updateButtonsOrdersAfterDnD();
- }
- }
- gViewerWindow->getWindow()->setCursor(UI_CURSOR_ARROW);
- mDragStarted = false;
- mDraggedItem = NULL;
- mLandingTab = NULL;
- mCheckForDrag = false;
-}
-
-void LLBottomTray::draw()
-{
- LLPanel::draw();
- if (mLandingTab)
- {
- static S32 w = mImageDragIndication->getWidth();
- static S32 h = mImageDragIndication->getHeight();
- LLRect rect = mLandingTab->calcScreenRect();
- mImageDragIndication->draw(rect.mLeft - w/2, rect.getHeight(), w, h);
- }
- getChild<LLButton>("show_profile_btn")->setToggleState(LLAvatarActions::profileVisible(gAgent.getID()));
-
- LLPanel* panel = LLSideTray::getInstance()->getPanel("panel_people");
- if (panel && panel->isInVisibleChain())
- {
- getChild<LLButton>("show_people_button")->setToggleState(true);
- }
- else
- {
- getChild<LLButton>("show_people_button")->setToggleState(false);
- }
-
- LLFloater* help_browser = (LLFloaterReg::findInstance("help_browser"));
- bool help_floater_visible = (help_browser && help_browser->isInVisibleChain());
-
- getChild<LLButton>("show_help_btn")->setToggleState(help_floater_visible);
-
-
-}
-
-bool LLBottomTray::onContextMenuItemEnabled(const LLSD& userdata)
-{
- std::string item = userdata.asString();
- LLLineEditor* edit_box = mNearbyChatBar->findChild<LLLineEditor>("chat_box");
-
- if (item == "can_cut")
- {
- return edit_box->canCut();
- }
- else if (item == "can_copy")
- {
- return edit_box->canCopy();
- }
- else if (item == "can_paste")
- {
- return edit_box->canPaste();
- }
- else if (item == "can_delete")
- {
- return edit_box->canDoDelete();
- }
- else if (item == "can_select_all")
- {
- return edit_box->canSelectAll() && (edit_box->getLength()>0);
- }
- return true;
-}
-
-
-void LLBottomTray::onContextMenuItemClicked(const LLSD& userdata)
-{
- std::string item = userdata.asString();
- LLLineEditor* edit_box = mNearbyChatBar->findChild<LLLineEditor>("chat_box");
-
- if (item == "cut")
- {
- edit_box->cut();
- }
- else if (item == "copy")
- {
- edit_box->copy();
- }
- else if (item == "paste")
- {
- edit_box->paste();
- edit_box->setFocus(TRUE);
- }
- else if (item == "delete")
- {
- edit_box->doDelete();
- }
- else if (item == "select_all")
- {
- edit_box->selectAll();
- }
-}
-
-void LLBottomTray::log(LLView* panel, const std::string& descr)
-{
- if (NULL == panel) return;
- LLView* layout = panel->getParent();
- lldebugs << descr << ": "
- << "panel: " << panel->getName()
- << ", rect: " << panel->getRect()
-
-
- << "layout: " << layout->getName()
- << ", rect: " << layout->getRect()
- << llendl
- ;
-}
-
-void LLBottomTray::reshape(S32 width, S32 height, BOOL called_from_parent)
-{
- static S32 debug_calling_number = 0;
- lldebugs << "**************************************** " << ++debug_calling_number << llendl;
-
- S32 current_width = getRect().getWidth();
- S32 delta_width = width - current_width;
- lldebugs << "Reshaping: "
- << ", width: " << width
- << ", cur width: " << current_width
- << ", delta_width: " << delta_width
- << ", called_from_parent: " << called_from_parent
- << llendl;
-
- if (mNearbyChatBar) log(mNearbyChatBar, "before");
- if (mChicletPanel) log(mChicletPanel, "before");
-
- // stores width size on which bottom tray is less than width required by its children. EXT-991
- static S32 extra_shrink_width = 0;
- bool should_be_reshaped = true;
-
- if (mChicletPanel && mToolbarStack && mNearbyChatBar)
- {
- // Firstly, update layout stack to ensure we deal with correct panel sizes.
- {
- BOOL saved_anim = mToolbarStack->getAnimate();
- // Set chiclet panel to be autoresized by default.
- mToolbarStack->updatePanelAutoResize(PANEL_CHICLET_NAME, TRUE);
- // Disable animation to prevent layout updating in several frames.
- mToolbarStack->setAnimate(FALSE);
- // Force the updating of layout to reset panels collapse factor.
- mToolbarStack->updateLayout();
- // Restore animate state.
- mToolbarStack->setAnimate(saved_anim);
- }
-
- // bottom tray is narrowed
- if (delta_width < 0)
- {
- if (extra_shrink_width > 0)
- {
- // is world rect was extra shrunk and decreasing again only update this value
- // to delta_width negative
- extra_shrink_width -= delta_width; // use "-=" because delta_width is negative
- should_be_reshaped = false;
- }
- else
- {
- extra_shrink_width = processWidthDecreased(delta_width);
-
- // increase new width to extra_shrink_width value to not reshape less than bottom tray minimum
- width += extra_shrink_width;
- }
- }
- // bottom tray is widen
- else
- {
- if (extra_shrink_width > delta_width)
- {
- // Less than minimum width is more than increasing (delta_width)
- // only reduce it value and make no reshape
- extra_shrink_width -= delta_width;
- should_be_reshaped = false;
- }
- else
- {
- if (extra_shrink_width > 0)
- {
- // If we have some extra shrink width let's reduce delta_width & width
- delta_width -= extra_shrink_width;
- width -= extra_shrink_width;
- extra_shrink_width = 0;
- }
- processWidthIncreased(delta_width);
- }
- }
- }
-
- if (should_be_reshaped)
- {
- lldebugs << "Reshape all children with width: " << width << llendl;
- LLPanel::reshape(width, height, called_from_parent);
- }
-
- if (mNearbyChatBar) log(mNearbyChatBar, "after");
- if (mChicletPanel) log(mChicletPanel, "after");
-
-
- // Restore width of the chatbar on first reshape.
- // we can not to do this from postBuild because reshape is called from parent view on startup
- // creation after it and reset width according to resize logic.
- static bool needs_restore_custom_state = true;
- if (mChatBarContainer && needs_restore_custom_state)
- {
- // restore custom width of chatbar panel.
- S32 new_width = gSavedSettings.getS32("ChatBarCustomWidth");
- if (new_width > 0)
- {
- mDesiredNearbyChatWidth = new_width;
- processChatbarCustomization(new_width);
- mChatBarContainer->reshape(new_width, mChatBarContainer->getRect().getHeight());
- }
- needs_restore_custom_state = false;
- }
-
-}
-
-S32 LLBottomTray::processWidthDecreased(S32 delta_width)
-{
- bool still_should_be_processed = true;
-
- const S32 chiclet_panel_width = mChicletPanel->getParent()->getRect().getWidth();
- const S32 chiclet_panel_min_width = mChicletPanel->getMinWidth();
-
- // There are four steps of processing width decrease. If in one of them required width was reached,
- // further are not needed.
- // 1. Decreasing width of chiclet panel.
- if (chiclet_panel_width > chiclet_panel_min_width)
- {
- // we have some space to decrease chiclet panel
- S32 panel_delta_min = chiclet_panel_width - chiclet_panel_min_width;
-
- S32 delta_panel = llmin(-delta_width, panel_delta_min);
-
- lldebugs << "delta_width: " << delta_width
- << ", panel_delta_min: " << panel_delta_min
- << ", delta_panel: " << delta_panel
- << llendl;
-
- // is chiclet panel width enough to process resizing?
- delta_width += panel_delta_min;
-
- still_should_be_processed = delta_width < 0;
-
- mChicletPanel->getParent()->reshape(mChicletPanel->getParent()->getRect().getWidth() - delta_panel, mChicletPanel->getParent()->getRect().getHeight());
- log(mChicletPanel, "after processing panel decreasing via chiclet panel");
-
- lldebugs << "RS_CHICLET_PANEL"
- << ", delta_width: " << delta_width
- << llendl;
- }
-
- S32 buttons_freed_width = 0;
- // 2. Decreasing width of buttons.
- if (still_should_be_processed)
- {
- processShrinkButtons(delta_width, buttons_freed_width);
- }
- // 3. Decreasing width of nearby chat.
- const S32 chatbar_panel_min_width = get_panel_min_width(mToolbarStack, mChatBarContainer);
- const S32 chatbar_panel_width = mChatBarContainer->getRect().getWidth();
- if (still_should_be_processed && chatbar_panel_width > chatbar_panel_min_width)
- {
- // we have some space to decrease chatbar panel
- S32 panel_delta_min = chatbar_panel_width - chatbar_panel_min_width;
-
- S32 delta_panel = llmin(-delta_width, panel_delta_min);
-
- // whether chatbar panel width is enough to process resizing?
- delta_width += panel_delta_min;
-
- still_should_be_processed = delta_width < 0;
-
- // chatbar should only be shrunk here, not stretched
- if(delta_panel > 0)
- {
- mChatBarContainer->reshape(mNearbyChatBar->getRect().getWidth() - delta_panel, mChatBarContainer->getRect().getHeight());
- }
-
- log(mNearbyChatBar, "after processing panel decreasing via nearby chatbar panel");
-
- lldebugs << "RS_CHATBAR_INPUT"
- << ", delta_panel: " << delta_panel
- << ", delta_width: " << delta_width
- << llendl;
- }
-
- S32 extra_shrink_width = 0;
- // 4. Hiding buttons if needed.
- if (still_should_be_processed)
- {
- processHideButtons(delta_width, buttons_freed_width);
-
- if (delta_width < 0)
- {
- extra_shrink_width = -delta_width;
- llwarns << "There is no enough width to reshape all children: "
- << extra_shrink_width << llendl;
- }
-
- if (buttons_freed_width > 0)
- {
- S32 nearby_needed_width = mDesiredNearbyChatWidth - mNearbyChatBar->getRect().getWidth();
- if (nearby_needed_width > 0)
- {
- S32 compensative_width = nearby_needed_width > buttons_freed_width ? buttons_freed_width : nearby_needed_width;
- log(mNearbyChatBar, "before applying compensative width");
- mChatBarContainer->reshape(mChatBarContainer->getRect().getWidth() + compensative_width, mChatBarContainer->getRect().getHeight() );
- log(mNearbyChatBar, "after applying compensative width");
- lldebugs << buttons_freed_width << llendl;
- }
- }
- }
-
- return extra_shrink_width;
-}
-
-void LLBottomTray::processWidthIncreased(S32 delta_width)
-{
- if (delta_width <= 0) return;
-
- const S32 chiclet_panel_width = mChicletPanel->getParent()->getRect().getWidth();
- static const S32 chiclet_panel_min_width = mChicletPanel->getMinWidth();
-
- const S32 available_width_chiclet = chiclet_panel_width - chiclet_panel_min_width;
-
- // how many room we have to show hidden buttons
- S32 total_available_width = delta_width + available_width_chiclet;
-
- lldebugs << "Processing extending, available width:"
- << ", chiclets - " << available_width_chiclet
- << ", total - " << total_available_width
- << llendl;
-
- S32 available_width = total_available_width;
-
- processShowButtons(available_width);
-
- // if we have to show/extend some buttons but resized delta width is not enough...
- S32 processed_width = total_available_width - available_width;
- if (processed_width > delta_width)
- {
- // ... let's shrink nearby chat & chiclet panels
- S32 required_to_process_width = processed_width;
-
- // 1. use delta width of resizing
- required_to_process_width -= delta_width;
-
- // 2. use width available via decreasing of chiclet panel
- if (required_to_process_width > 0)
- {
- mChicletPanel->getParent()->reshape(mChicletPanel->getParent()->getRect().getWidth() - required_to_process_width, mChicletPanel->getParent()->getRect().getHeight());
- log(mChicletPanel, "after applying compensative width for chiclets: ");
- lldebugs << required_to_process_width << llendl;
- }
-
- }
-
- // shown buttons take some space, rest should be processed by nearby chatbar & chiclet panels
- delta_width -= processed_width;
-
-
- // how many space can nearby chatbar take?
- S32 chatbar_panel_width_ = mChatBarContainer->getRect().getWidth();
- if (delta_width > 0 && chatbar_panel_width_ < mDesiredNearbyChatWidth)
- {
- S32 delta_panel_max = mDesiredNearbyChatWidth - chatbar_panel_width_;
- S32 delta_panel = llmin(delta_width, delta_panel_max);
- lldebugs << "Unprocesed delta width: " << delta_width
- << ", can be applied to chatbar: " << delta_panel_max
- << ", will be applied: " << delta_panel
- << llendl;
-
- delta_width -= delta_panel_max;
- mChatBarContainer->reshape(chatbar_panel_width_ + delta_panel, mChatBarContainer->getRect().getHeight());
- log(mNearbyChatBar, "applied unprocessed delta width");
- }
- if (delta_width > 0)
- {
- processExtendButtons(delta_width);
- }
-}
-
-void LLBottomTray::processShowButtons(S32& available_width)
-{
- // process buttons from left to right
- resize_state_vec_t::const_iterator it = mButtonsProcessOrder.begin();
- const resize_state_vec_t::const_iterator it_end = mButtonsProcessOrder.end();
-
- for (; it != it_end; ++it)
- {
- // is there available space?
- if (available_width <= 0) break;
-
- // try to show next button
- processShowButton(*it, available_width);
- }
-}
-
-bool LLBottomTray::processShowButton(EResizeState shown_object_type, S32& available_width)
-{
- lldebugs << "Trying to show object type: " << shown_object_type << llendl;
-
- LLPanel* panel = getButtonPanel(shown_object_type);
- if (NULL == panel)
- {
- lldebugs << "There is no object to process for state: " << shown_object_type << llendl;
- return false;
- }
- bool can_be_shown = canButtonBeShown(shown_object_type);
- if (can_be_shown)
- {
- //validate if we have enough room to show this button
- const S32 required_width = panel->getRect().getWidth();
- can_be_shown = available_width >= required_width;
- if (can_be_shown)
- {
- available_width -= required_width;
-
- setTrayButtonVisible(shown_object_type, true);
-
- lldebugs << "processed object type: " << shown_object_type
- << ", rest available width: " << available_width
- << llendl;
- mResizeState &= ~shown_object_type;
- }
- }
- return can_be_shown;
-}
-
-void LLBottomTray::processHideButtons(S32& required_width, S32& buttons_freed_width)
-{
- // process buttons from right to left
- resize_state_vec_t::const_reverse_iterator it = mButtonsProcessOrder.rbegin();
- const resize_state_vec_t::const_reverse_iterator it_end = mButtonsProcessOrder.rend();
-
- for (; it != it_end; ++it)
- {
- // is it still necessary to hide a button?
- if (required_width >= 0) break;
-
- // try to hide next button
- processHideButton(*it, required_width, buttons_freed_width);
- }
-}
-
-void LLBottomTray::processHideButton(EResizeState processed_object_type, S32& required_width, S32& buttons_freed_width)
-{
- lldebugs << "Trying to hide object type: " << processed_object_type << llendl;
- LLPanel* panel = getButtonPanel(processed_object_type);
- if (NULL == panel)
- {
- lldebugs << "There is no object to process for state: " << processed_object_type << llendl;
- return;
- }
-
- if (panel->getVisible())
- {
- required_width += panel->getRect().getWidth();
-
- if (required_width > 0)
- {
- buttons_freed_width += required_width;
- }
-
- setTrayButtonVisible(processed_object_type, false);
-
- mResizeState |= processed_object_type;
-
- lldebugs << "processing object type: " << processed_object_type
- << ", buttons_freed_width: " << buttons_freed_width
- << llendl;
- }
-}
-
-void LLBottomTray::processShrinkButtons(S32& required_width, S32& buttons_freed_width)
-{
- // process buttons from right to left
- resize_state_vec_t::const_reverse_iterator it = mButtonsProcessOrder.rbegin();
- const resize_state_vec_t::const_reverse_iterator it_end = mButtonsProcessOrder.rend();
-
- // iterate through buttons in the mButtonsProcessOrder first
- for (; it != it_end; ++it)
- {
- // is it still necessary to hide a button?
- if (required_width >= 0) break;
-
- // try to shrink next button
- processShrinkButton(*it, required_width);
- }
-
- // then shrink Speak button
- if (required_width < 0)
- {
- S32 panel_min_width = 0;
- std::string panel_name = mSpeakPanel->getName();
- bool success = mToolbarStack->getPanelMinSize(panel_name, &panel_min_width);
- if (!success)
- {
- lldebugs << "Panel was not found to get its min width: " << panel_name << llendl;
- }
- else
- {
- S32 panel_width = mSpeakPanel->getRect().getWidth();
- S32 possible_shrink_width = panel_width - panel_min_width;
-
- if (possible_shrink_width > 0)
- {
- mSpeakBtn->setLabelVisible(false);
- mSpeakPanel->reshape(panel_width - possible_shrink_width, mSpeakPanel->getRect().getHeight());
-
- required_width += possible_shrink_width;
-
- if (required_width > 0)
- {
- buttons_freed_width += required_width;
- }
-
- lldebugs << "Shrunk Speak button panel: " << panel_name
- << ", shrunk width: " << possible_shrink_width
- << ", rest width to process: " << required_width
- << llendl;
- }
- }
- }
-}
-
-void LLBottomTray::processShrinkButton(EResizeState processed_object_type, S32& required_width)
-{
- LLPanel* panel = getButtonPanel(processed_object_type);
- if (NULL == panel)
- {
- lldebugs << "There is no object to process for type: " << processed_object_type << llendl;
- return;
- }
-
- if (panel->getVisible())
- {
- S32 panel_width = panel->getRect().getWidth();
- S32 panel_min_width = 0;
- std::string panel_name = panel->getName();
- bool success = mToolbarStack->getPanelMinSize(panel_name, &panel_min_width);
- S32 possible_shrink_width = panel_width - panel_min_width;
-
- if (!success)
- {
- lldebugs << "Panel was not found to get its min width: " << panel_name << llendl;
- }
- // we have some space to free by shrinking the button
- else if (possible_shrink_width > 0)
- {
- // let calculate real width to shrink
-
- // 1. apply all possible width
- required_width += possible_shrink_width;
-
- // 2. it it is too much...
- if (required_width > 0)
- {
- // reduce applied shrunk width to the excessive value.
- possible_shrink_width -= required_width;
- required_width = 0;
- }
- panel->reshape(panel_width - possible_shrink_width, panel->getRect().getHeight());
-
- lldebugs << "Shrunk panel: " << panel_name
- << ", shrunk width: " << possible_shrink_width
- << ", rest width to process: " << required_width
- << llendl;
- }
- }
-}
-
-
-void LLBottomTray::processExtendButtons(S32& available_width)
-{
- // do not allow extending any buttons if we have some buttons hidden via resize
- if (mResizeState & RS_BUTTONS_CAN_BE_HIDDEN) return;
-
- // process buttons from left to right
- resize_state_vec_t::const_iterator it = mButtonsProcessOrder.begin();
- const resize_state_vec_t::const_iterator it_end = mButtonsProcessOrder.end();
-
- // iterate through buttons in the mButtonsProcessOrder first
- for (; it != it_end; ++it)
- {
- // is there available space?
- if (available_width <= 0) break;
-
- // try to extend next button
- processExtendButton(*it, available_width);
- }
-
- const S32 chiclet_panel_width = mChicletPanel->getParent()->getRect().getWidth();
- static const S32 chiclet_panel_min_width = mChicletPanel->getMinWidth();
- const S32 available_width_chiclet = chiclet_panel_width - chiclet_panel_min_width;
-
- // then try to extend Speak button
- if (available_width > 0 || available_width_chiclet > 0)
- {
- S32 panel_max_width = mObjectDefaultWidthMap[RS_BUTTON_SPEAK];
- S32 panel_width = mSpeakPanel->getRect().getWidth();
- S32 possible_extend_width = panel_max_width - panel_width;
-
- if (possible_extend_width >= 0 && possible_extend_width <= available_width + available_width_chiclet) // HACK: this button doesn't change size so possible_extend_width will be 0
- {
- mSpeakBtn->setLabelVisible(true);
- mSpeakPanel->reshape(panel_max_width, mSpeakPanel->getRect().getHeight());
- log(mSpeakBtn, "speak button is extended");
-
- if( available_width > possible_extend_width)
- {
- available_width -= possible_extend_width;
- }
- else
- {
- S32 required_width = possible_extend_width - available_width;
- available_width = 0;
- mChicletPanel->getParent()->reshape(mChicletPanel->getParent()->getRect().getWidth() - required_width, mChicletPanel->getParent()->getRect().getHeight());
- }
- lldebugs << "Extending Speak button panel: " << mSpeakPanel->getName()
- << ", extended width: " << possible_extend_width
- << ", rest width to process: " << available_width
- << llendl;
- }
- }
-}
-
-void LLBottomTray::processExtendButton(EResizeState processed_object_type, S32& available_width)
-{
- LLPanel* panel = getButtonPanel(processed_object_type);
- if (NULL == panel)
- {
- lldebugs << "There is no object to process for type: " << processed_object_type << llendl;
- return;
- }
-
- if (!panel->getVisible()) return;
-
- S32 panel_max_width = mObjectDefaultWidthMap[processed_object_type];
- S32 panel_width = panel->getRect().getWidth();
- S32 possible_extend_width = panel_max_width - panel_width;
-
- if (possible_extend_width > 0)
- {
- // let calculate real width to extend
-
- // 1. apply all possible width
- available_width -= possible_extend_width;
-
- // 2. it it is too much...
- if (available_width < 0)
- {
- // reduce applied extended width to the excessive value.
- possible_extend_width += available_width;
- available_width = 0;
- }
- panel->reshape(panel_width + possible_extend_width, panel->getRect().getHeight());
-
- lldebugs << "Extending panel: " << panel->getName()
- << ", extended width: " << possible_extend_width
- << ", rest width to process: " << available_width
- << llendl;
- }
-}
-
-bool LLBottomTray::canButtonBeShown(EResizeState processed_object_type) const
-{
- // 0. Check if passed button was previously hidden on resize
- bool can_be_shown = mResizeState & processed_object_type;
- if (can_be_shown)
- {
- // Yes, it was. Lets now check that all buttons before it (that can be hidden on resize)
- // are already shown
-
- // process buttons in direct order (from left to right)
- resize_state_vec_t::const_iterator it = mButtonsProcessOrder.begin();
- const resize_state_vec_t::const_iterator it_end = mButtonsProcessOrder.end();
-
- // 1. Find and accumulate all buttons types before one passed into the method.
- MASK buttons_before_mask = RS_NORESIZE;
- for (; it != it_end; ++it)
- {
- const EResizeState button_type = *it;
- if (button_type == processed_object_type) break;
-
- buttons_before_mask |= button_type;
- }
-
- // 2. Check if some previous buttons are still hidden on resize
- can_be_shown = !(buttons_before_mask & mResizeState);
- }
- return can_be_shown;
-}
-
-void LLBottomTray::initResizeStateContainers()
-{
- // init map with objects should be processed for each type
- mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_SPEAK, getChild<LLPanel>("speak_panel")));
- mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_GESTURES, getChild<LLPanel>("gesture_panel")));
- mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_MOVEMENT, getChild<LLPanel>("movement_panel")));
- mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_CAMERA, getChild<LLPanel>("cam_panel")));
- mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_SNAPSHOT, getChild<LLPanel>("snapshot_panel")));
- mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_BUILD, getChild<LLPanel>("build_btn_panel")));
- mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_SEARCH, getChild<LLPanel>("search_btn_panel")));
- mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_WORLD_MAP, getChild<LLPanel>("world_map_btn_panel")));
- mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_MINI_MAP, getChild<LLPanel>("mini_map_btn_panel")));
-
- // init an order of processed buttons
- mButtonsProcessOrder.push_back(RS_BUTTON_GESTURES);
- mButtonsProcessOrder.push_back(RS_BUTTON_MOVEMENT);
- mButtonsProcessOrder.push_back(RS_BUTTON_CAMERA);
- mButtonsProcessOrder.push_back(RS_BUTTON_SNAPSHOT);
- mButtonsProcessOrder.push_back(RS_BUTTON_BUILD);
- mButtonsProcessOrder.push_back(RS_BUTTON_SEARCH);
- mButtonsProcessOrder.push_back(RS_BUTTON_WORLD_MAP);
- mButtonsProcessOrder.push_back(RS_BUTTON_MINI_MAP);
-
- mButtonsOrder.push_back(RS_BUTTON_SPEAK);
- mButtonsOrder.insert(mButtonsOrder.end(), mButtonsProcessOrder.begin(), mButtonsProcessOrder.end());
-
- // init default widths
-
- // process buttons that can be hidden on resize...
- resize_state_vec_t::const_iterator it = mButtonsProcessOrder.begin();
- const resize_state_vec_t::const_iterator it_end = mButtonsProcessOrder.end();
-
- for (; it != it_end; ++it)
- {
- const EResizeState button_type = *it;
- // is there an appropriate object?
- LLPanel* button_panel = getButtonPanel(button_type);
- if (!button_panel) continue;
-
- // set default width for it.
- mObjectDefaultWidthMap[button_type] = button_panel->getRect().getWidth();
- }
-
- // ... and add Speak button because it also can be shrunk.
- mObjectDefaultWidthMap[RS_BUTTON_SPEAK] = mSpeakPanel->getRect().getWidth();
-}
-
-// this method must be called before restoring of the chat entry field on startup
-// because it resets chatbar's width according to resize logic.
-void LLBottomTray::initButtonsVisibility()
-{
- setVisibleAndFitWidths(RS_BUTTON_SPEAK, gSavedSettings.getBOOL("EnableVoiceChat"));
- setVisibleAndFitWidths(RS_BUTTON_GESTURES, gSavedSettings.getBOOL("ShowGestureButton"));
- setVisibleAndFitWidths(RS_BUTTON_MOVEMENT, gSavedSettings.getBOOL("ShowMoveButton"));
- setVisibleAndFitWidths(RS_BUTTON_CAMERA, gSavedSettings.getBOOL("ShowCameraButton"));
- setVisibleAndFitWidths(RS_BUTTON_SNAPSHOT, gSavedSettings.getBOOL("ShowSnapshotButton"));
- setVisibleAndFitWidths(RS_BUTTON_BUILD, gSavedSettings.getBOOL("ShowBuildButton"));
- setVisibleAndFitWidths(RS_BUTTON_SEARCH, gSavedSettings.getBOOL("ShowSearchButton"));
- setVisibleAndFitWidths(RS_BUTTON_WORLD_MAP, gSavedSettings.getBOOL("ShowWorldMapButton"));
- setVisibleAndFitWidths(RS_BUTTON_MINI_MAP, gSavedSettings.getBOOL("ShowMiniMapButton"));
-}
-
-void LLBottomTray::setButtonsControlsAndListeners()
-{
- gSavedSettings.getControl("EnableVoiceChat")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_SPEAK, _2));
- gSavedSettings.getControl("ShowGestureButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_GESTURES, _2));
- gSavedSettings.getControl("ShowMoveButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_MOVEMENT, _2));
- gSavedSettings.getControl("ShowCameraButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_CAMERA, _2));
- gSavedSettings.getControl("ShowSnapshotButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_SNAPSHOT, _2));
- gSavedSettings.getControl("ShowBuildButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_BUILD, _2));
- gSavedSettings.getControl("ShowSearchButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_SEARCH, _2));
- gSavedSettings.getControl("ShowWorldMapButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_WORLD_MAP, _2));
- gSavedSettings.getControl("ShowMiniMapButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_MINI_MAP, _2));
-
-
- LLButton* build_btn = getChild<LLButton>("build_btn");
- // set control name for Build button. It is not enough to link it with Button.SetFloaterToggle in xml
- std::string vis_control_name = LLFloaterReg::declareVisibilityControl("build");
- // Set the button control value (toggle state) to the floater visibility control (Sets the value as well)
- build_btn->setControlVariable(LLFloater::getControlGroup()->getControl(vis_control_name));
-}
-
-bool LLBottomTray::toggleShowButton(LLBottomTray::EResizeState button_type, const LLSD& new_visibility)
-{
- if (LLBottomTray::instanceExists())
- {
- LLBottomTray::getInstance()->setTrayButtonVisibleIfPossible(button_type, new_visibility.asBoolean());
- }
- return true;
-}
-
-void LLBottomTray::setTrayButtonVisible(EResizeState shown_object_type, bool visible)
-{
- LLPanel* panel = getButtonPanel(shown_object_type);
- if (NULL == panel)
- {
- lldebugs << "There is no object to show for state: " << shown_object_type << llendl;
- return;
- }
-
- panel->setVisible(visible);
-}
-
-void LLBottomTray::setTrayButtonVisibleIfPossible(EResizeState shown_object_type, bool visible, bool raise_notification)
-{
- if (!setVisibleAndFitWidths(shown_object_type, visible) && visible && raise_notification)
- {
- LLNotificationsUtil::add("BottomTrayButtonCanNotBeShown",
- LLSD(),
- LLSD(),
- LLNotificationFunctorRegistry::instance().DONOTHING);
- }
-}
-
-bool LLBottomTray::setVisibleAndFitWidths(EResizeState object_type, bool visible)
-{
- // The Speak button is treated specially: if voice is enabled,
- // the button should be displayed no matter how much space we've got.
- if (object_type == RS_BUTTON_SPEAK)
- {
- showSpeakButton(visible);
- return true;
- }
-
- LLPanel* cur_panel = getButtonPanel(object_type);
- if (NULL == cur_panel)
- {
- lldebugs << "There is no object to process for state: " << object_type << llendl;
- return false;
- }
-
- bool is_set = true;
-
- if (visible)
- {
- // Assume that only chiclet panel can be auto-resized
- const S32 available_width =
- mChicletPanel->getParent()->getRect().getWidth() - mChicletPanel->getMinWidth();
-
- S32 preferred_width = mObjectDefaultWidthMap[object_type];
- S32 current_width = cur_panel->getRect().getWidth();
- S32 result_width = 0;
- bool decrease_width = false;
-
- // Mark this button to be shown
- mResizeState |= object_type;
-
- if (preferred_width > 0 && available_width >= preferred_width)
- {
- result_width = preferred_width;
- }
- else if (available_width >= current_width)
- {
- result_width = current_width;
- }
- else
- {
- // Calculate the possible shrunk width as difference between current and minimal widths
- const S32 chatbar_shrunk_width =
- mChatBarContainer->getRect().getWidth() - get_panel_min_width(mToolbarStack, mChatBarContainer);
-
- S32 sum_of_min_widths = get_panel_min_width(mToolbarStack, mSpeakPanel);
- S32 sum_of_curr_widths = get_curr_width(mSpeakPanel);
-
- resize_state_vec_t::const_iterator it = mButtonsProcessOrder.begin();
- const resize_state_vec_t::const_iterator it_end = mButtonsProcessOrder.end();
-
- for (; it != it_end; ++it)
- {
- LLPanel* cur_panel = getButtonPanel(*it);
- sum_of_min_widths += get_panel_min_width(mToolbarStack, cur_panel);
- sum_of_curr_widths += get_curr_width(cur_panel);
- }
-
- const S32 possible_shrunk_width =
- chatbar_shrunk_width + (sum_of_curr_widths - sum_of_min_widths);
-
- // Minimal width of current panel
- S32 minimal_width = 0;
- mToolbarStack->getPanelMinSize(cur_panel->getName(), &minimal_width);
-
- if ( (available_width + possible_shrunk_width) >= minimal_width)
- {
- // There is enough space for minimal width, but set the result_width
- // to preferred_width so buttons widths decreasing will be done in predefined order
- result_width = (preferred_width > 0) ? preferred_width : current_width;
- decrease_width = true;
- }
- else
- {
- // Nothing can be done, give up...
- return false;
- }
- }
-
- if (result_width != current_width)
- {
- cur_panel->reshape(result_width, cur_panel->getRect().getHeight());
- current_width = result_width;
- }
-
- is_set = processShowButton(object_type, current_width);
-
- // Shrink buttons if needed
- if (is_set && decrease_width)
- {
- processWidthDecreased( -result_width);
- }
- }
- else
- {
- const S32 delta_width = get_curr_width(cur_panel);
-
- setTrayButtonVisible(object_type, false);
-
- // Mark button NOT to show while future bottom tray extending
- mResizeState &= ~object_type;
-
- // Extend other buttons if need
- if (delta_width)
- {
- processWidthIncreased(delta_width);
- }
- }
- return is_set;
-}
-
-LLPanel* LLBottomTray::getButtonPanel(EResizeState button_type)
-{
- // Don't use the operator[] because it inserts a NULL value if the key is not found.
- if (mStateProcessedObjectMap.count(button_type) == 0)
- {
- llwarns << "Cannot find a panel for " << resizeStateToString(button_type) << llendl;
- llassert(mStateProcessedObjectMap.count(button_type) == 1);
- return NULL;
- }
-
- return mStateProcessedObjectMap[button_type];
-}
-
-void LLBottomTray::showWellButton(EResizeState object_type, bool visible)
-{
- llassert( ((RS_NOTIFICATION_WELL | RS_IM_WELL) & object_type) == object_type );
-
- const std::string panel_name = RS_IM_WELL == object_type ? "im_well_panel" : "notification_well_panel";
-
- LLView * panel = getChild<LLView>(panel_name);
-
- // if necessary visibility is set nothing to do here
- if (panel->getVisible() == (BOOL)visible) return;
-
- S32 panel_width = panel->getRect().getWidth();
- panel->setVisible(visible);
-
- if (visible)
- {
- // method assumes that input param is a negative value
- processWidthDecreased(-panel_width);
- }
- else
- {
- processWidthIncreased(panel_width);
- }
-}
-
-void LLBottomTray::processChatbarCustomization(S32 new_width)
-{
- if (NULL == mNearbyChatBar) return;
-
- const S32 delta_width = mChatBarContainer->getRect().getWidth() - new_width;
-
- if (delta_width == 0) return;
-
- mDesiredNearbyChatWidth = new_width;
-
- LLView * chiclet_layout_panel = mChicletPanel->getParent();
- const S32 chiclet_min_width = get_panel_min_width(mToolbarStack, chiclet_layout_panel);
- const S32 chiclet_panel_width = chiclet_layout_panel->getRect().getWidth();
- const S32 available_chiclet_shrink_width = chiclet_panel_width - chiclet_min_width;
- llassert(available_chiclet_shrink_width >= 0);
-
- if (delta_width > 0) // panel gets narrowly
- {
- S32 total_possible_width = delta_width + available_chiclet_shrink_width;
- processShowButtons(total_possible_width);
- processExtendButtons(total_possible_width);
- }
- // here (delta_width < 0) // panel gets wider
- else //if (-delta_width > available_chiclet_shrink_width)
- {
- S32 required_width = delta_width + available_chiclet_shrink_width;
- S32 buttons_freed_width = 0;
- processShrinkButtons(required_width, buttons_freed_width);
- processHideButtons(required_width, buttons_freed_width);
- }
-}
-
-// static
-std::string LLBottomTray::resizeStateToString(EResizeState state)
-{
- switch (state)
- {
- case RS_NORESIZE: return "RS_NORESIZE";
- case RS_CHICLET_PANEL: return "RS_CHICLET_PANEL";
- case RS_CHATBAR_INPUT: return "RS_CHATBAR_INPUT";
- case RS_BUTTON_SNAPSHOT: return "RS_BUTTON_SNAPSHOT";
- case RS_BUTTON_CAMERA: return "RS_BUTTON_CAMERA";
- case RS_BUTTON_MOVEMENT: return "RS_BUTTON_MOVEMENT";
- case RS_BUTTON_GESTURES: return "RS_BUTTON_GESTURES";
- case RS_BUTTON_SPEAK: return "RS_BUTTON_SPEAK";
- case RS_IM_WELL: return "RS_IM_WELL";
- case RS_NOTIFICATION_WELL: return "RS_NOTIFICATION_WELL";
- case RS_BUTTON_BUILD: return "RS_BUTTON_BUILD";
- case RS_BUTTON_SEARCH: return "RS_BUTTON_SEARCH";
- case RS_BUTTON_WORLD_MAP: return "RS_BUTTON_WORLD_MAP";
- case RS_BUTTON_MINI_MAP: return "RS_BUTTON_MINI_MAP";
- case RS_BUTTONS_CAN_BE_HIDDEN: return "RS_BUTTONS_CAN_BE_HIDDEN";
- // No default to track additions.
- }
- return "UNKNOWN_BUTTON";
-}
-
-//EOF
+/**
+ * @file llbottomtray.cpp
+ * @brief LLBottomTray class implementation
+ *
+ * $LicenseInfo:firstyear=2009&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h" // must be first include
+
+#define LLBOTTOMTRAY_CPP
+#include "llbottomtray.h"
+
+// library includes
+#include "llfloaterreg.h"
+#include "llflyoutbutton.h"
+#include "lllayoutstack.h"
+#include "llnotifications.h"
+#include "llnotificationsutil.h"
+#include "lltexteditor.h"
+
+// newview includes
+#include "llagent.h"
+#include "llagentcamera.h"
+#include "llavataractions.h"
+#include "llchiclet.h"
+#include "llfloatercamera.h"
+#include "llhints.h"
+#include "llimfloater.h" // for LLIMFloater
+#include "llnearbychatbar.h"
+#include "llsidetray.h"
+#include "llspeakbutton.h"
+#include "llsplitbutton.h"
+#include "llsyswellwindow.h"
+#include "lltoolmgr.h"
+#include "llviewerparcelmgr.h"
+
+#include "llviewerwindow.h"
+#include "llsdserialize.h"
+
+// Distance from mouse down on which drag'n'drop should be started.
+#define DRAG_START_DISTANCE 3
+
+static const std::string SORTING_DATA_FILE_NAME = "bottomtray_buttons_order.xml";
+
+LLDefaultChildRegistry::Register<LLBottomtrayButton> bottomtray_button("bottomtray_button");
+
+// LLBottomtrayButton methods
+
+// virtual
+BOOL LLBottomtrayButton::handleHover(S32 x, S32 y, MASK mask)
+{
+ if (mCanDrag)
+ {
+ // pass hover to bottomtray
+ S32 screenX, screenY;
+ localPointToScreen(x, y, &screenX, &screenY);
+ LLBottomTray::getInstance()->onDraggableButtonHover(screenX, screenY);
+
+ return TRUE;
+ }
+ else
+ {
+ return LLButton::handleHover(x, y, mask);
+ }
+}
+//virtual
+BOOL LLBottomtrayButton::handleMouseUp(S32 x, S32 y, MASK mask)
+{
+ if (mCanDrag)
+ {
+ S32 screenX, screenY;
+ localPointToScreen(x, y, &screenX, &screenY);
+ // pass mouse up to bottomtray
+ LLBottomTray::getInstance()->onDraggableButtonMouseUp(this, screenX, screenY);
+ }
+ return LLButton::handleMouseUp(x, y, mask);
+}
+//virtual
+BOOL LLBottomtrayButton::handleMouseDown(S32 x, S32 y, MASK mask)
+{
+ if (mCanDrag)
+ {
+ S32 screenX, screenY;
+ localPointToScreen(x, y, &screenX, &screenY);
+ // pass mouse up to bottomtray
+ LLBottomTray::getInstance()->onDraggableButtonMouseDown(this, screenX, screenY);
+ }
+ return LLButton::handleMouseDown(x, y, mask);
+}
+
+static void update_build_button_enable_state()
+{
+ bool can_edit = LLToolMgr::getInstance()->canEdit();
+
+ LLBottomTray::getInstance()->getChildView("build_btn")->setEnabled(can_edit);
+}
+
+// Build time optimization, generate extern template once in .cpp file
+template class LLBottomTray* LLSingleton<class LLBottomTray>::getInstance();
+
+namespace
+{
+ const std::string& PANEL_CHICLET_NAME = "chiclet_list_panel";
+
+ S32 get_panel_min_width(LLLayoutStack* stack, LLView* panel)
+ {
+ S32 minimal_width = 0;
+ llassert(stack);
+ if ( stack && panel && panel->getVisible() )
+ {
+ stack->getPanelMinSize(panel->getName(), &minimal_width);
+ }
+ return minimal_width;
+ }
+
+ S32 get_panel_max_width(LLLayoutStack* stack, LLPanel* panel)
+ {
+ S32 max_width = 0;
+ llassert(stack);
+ if ( stack && panel && panel->getVisible() )
+ {
+ stack->getPanelMaxSize(panel->getName(), &max_width);
+ }
+ return max_width;
+ }
+
+ S32 get_curr_width(LLUICtrl* ctrl)
+ {
+ S32 cur_width = 0;
+ if ( ctrl && ctrl->getVisible() )
+ {
+ cur_width = ctrl->getRect().getWidth();
+ }
+ return cur_width;
+ }
+}
+
+class LLBottomTrayLite
+ : public LLPanel
+{
+public:
+ LLBottomTrayLite()
+ : mNearbyChatBar(NULL),
+ mChatBarContainer(NULL),
+ mGesturePanel(NULL)
+ {
+ mFactoryMap["chat_bar"] = LLCallbackMap(LLBottomTray::createNearbyChatBar, NULL);
+ buildFromFile("panel_bottomtray_lite.xml");
+ }
+
+ BOOL postBuild()
+ {
+ mNearbyChatBar = findChild<LLNearbyChatBar>("chat_bar");
+ mChatBarContainer = getChild<LLLayoutPanel>("chat_bar_layout_panel");
+ mGesturePanel = getChild<LLPanel>("gesture_panel");
+
+ // Hide "show_nearby_chat" button
+ if (mNearbyChatBar)
+ {
+ LLLineEditor* chat_box = mNearbyChatBar->getChatBox();
+ LLUICtrl* show_btn = mNearbyChatBar->getChild<LLUICtrl>("show_nearby_chat");
+ S32 delta_width = show_btn->getRect().getWidth();
+ show_btn->setVisible(FALSE);
+ chat_box->reshape(chat_box->getRect().getWidth() + delta_width, chat_box->getRect().getHeight());
+ }
+ return TRUE;
+ }
+
+ void onFocusLost()
+ {
+ if (gAgentCamera.cameraMouselook())
+ {
+ LLBottomTray::getInstance()->setVisible(FALSE);
+ }
+ }
+
+ LLNearbyChatBar* mNearbyChatBar;
+ LLLayoutPanel* mChatBarContainer;
+ LLPanel* mGesturePanel;
+};
+
+LLBottomTray::LLBottomTray(const LLSD&)
+: mChicletPanel(NULL),
+ mSpeakPanel(NULL),
+ mSpeakBtn(NULL),
+ mNearbyChatBar(NULL),
+ mChatBarContainer(NULL),
+ mNearbyCharResizeHandlePanel(NULL),
+ mToolbarStack(NULL),
+ mMovementButton(NULL),
+ mResizeState(RS_NORESIZE),
+ mBottomTrayContextMenu(NULL),
+ mCamButton(NULL),
+ mBottomTrayLite(NULL),
+ mIsInLiteMode(false),
+ mDragStarted(false),
+ mDraggedItem(NULL),
+ mLandingTab(NULL),
+ mCheckForDrag(false)
+{
+ // Firstly add ourself to IMSession observers, so we catch session events
+ // before chiclets do that.
+ LLIMMgr::getInstance()->addSessionObserver(this);
+
+ mFactoryMap["chat_bar"] = LLCallbackMap(LLBottomTray::createNearbyChatBar, NULL);
+
+ buildFromFile("panel_bottomtray.xml");
+
+ LLUICtrl::CommitCallbackRegistry::defaultRegistrar().add("CameraPresets.ChangeView", boost::bind(&LLFloaterCamera::onClickCameraItem, _2));
+
+ //this is to fix a crash that occurs because LLBottomTray is a singleton
+ //and thus is deleted at the end of the viewers lifetime, but to be cleanly
+ //destroyed LLBottomTray requires some subsystems that are long gone
+ //LLUI::getRootView()->addChild(this);
+
+ {
+ mBottomTrayLite = new LLBottomTrayLite();
+ mBottomTrayLite->setFollowsAll();
+ mBottomTrayLite->setVisible(FALSE);
+ }
+
+ mImageDragIndication = LLUI::getUIImage(getString("DragIndicationImageName"));
+ mDesiredNearbyChatWidth = mNearbyChatBar ? mNearbyChatBar->getRect().getWidth() : 0;
+}
+
+LLBottomTray::~LLBottomTray()
+{
+ if (!LLSingleton<LLIMMgr>::destroyed())
+ {
+ LLIMMgr::getInstance()->removeSessionObserver(this);
+ }
+
+ if (mNearbyChatBar)
+ {
+ // store custom width of chatbar panel.
+ S32 custom_width = mChatBarContainer->getRect().getWidth();
+ gSavedSettings.setS32("ChatBarCustomWidth", custom_width);
+ }
+
+ // emulate previous floater behavior to be hidden on startup.
+ // override effect of save_visibility=true.
+ // this attribute is necessary to button.initial_callback=Button.SetFloaterToggle works properly:
+ // i.g when floater changes its visibility - button changes its toggle state.
+ getChild<LLUICtrl>("build_btn")->setControlValue(false);
+ getChild<LLUICtrl>("search_btn")->setControlValue(false);
+ getChild<LLUICtrl>("world_map_btn")->setControlValue(false);
+}
+
+// *TODO Vadim: why void* ?
+void* LLBottomTray::createNearbyChatBar(void* userdata)
+{
+ return new LLNearbyChatBar();
+}
+
+LLNearbyChatBar* LLBottomTray::getNearbyChatBar()
+{
+ return mIsInLiteMode ? mBottomTrayLite->mNearbyChatBar : mNearbyChatBar;
+}
+
+LLIMChiclet* LLBottomTray::createIMChiclet(const LLUUID& session_id)
+{
+ LLIMChiclet::EType im_chiclet_type = LLIMChiclet::getIMSessionType(session_id);
+
+ switch (im_chiclet_type)
+ {
+ case LLIMChiclet::TYPE_IM:
+ return getChicletPanel()->createChiclet<LLIMP2PChiclet>(session_id);
+ case LLIMChiclet::TYPE_GROUP:
+ return getChicletPanel()->createChiclet<LLIMGroupChiclet>(session_id);
+ case LLIMChiclet::TYPE_AD_HOC:
+ return getChicletPanel()->createChiclet<LLAdHocChiclet>(session_id);
+ case LLIMChiclet::TYPE_UNKNOWN:
+ break;
+ }
+
+ return NULL;
+}
+
+//virtual
+void LLBottomTray::sessionAdded(const LLUUID& session_id, const std::string& name, const LLUUID& other_participant_id)
+{
+ if (!getChicletPanel()) return;
+
+ LLIMModel::LLIMSession* session = LLIMModel::getInstance()->findIMSession(session_id);
+ if (!session) return;
+
+ // no need to spawn chiclets for participants in P2P calls called through Avaline
+ if (session->isP2P() && session->isOtherParticipantAvaline()) return;
+
+ if (getChicletPanel()->findChiclet<LLChiclet>(session_id)) return;
+
+ LLIMChiclet* chiclet = createIMChiclet(session_id);
+ if(chiclet)
+ {
+ chiclet->setIMSessionName(name);
+ chiclet->setOtherParticipantId(other_participant_id);
+
+ LLIMFloater::onIMChicletCreated(session_id);
+
+ }
+ else
+ {
+ llerrs << "Could not create chiclet" << llendl;
+ }
+}
+
+//virtual
+void LLBottomTray::sessionRemoved(const LLUUID& session_id)
+{
+ if(getChicletPanel())
+ {
+ // IM floater should be closed when session removed and associated chiclet closed
+ LLIMFloater* iMfloater = LLFloaterReg::findTypedInstance<LLIMFloater>(
+ "impanel", session_id);
+ if (iMfloater != NULL)
+ {
+ iMfloater->closeFloater();
+ }
+
+ getChicletPanel()->removeChiclet(session_id);
+ }
+}
+
+void LLBottomTray::sessionIDUpdated(const LLUUID& old_session_id, const LLUUID& new_session_id)
+{
+ //this is only needed in case of outgoing ad-hoc/group chat sessions
+ LLChicletPanel* chiclet_panel = getChicletPanel();
+ if (chiclet_panel)
+ {
+ //it should be ad-hoc im chiclet or group im chiclet
+ LLChiclet* chiclet = chiclet_panel->findChiclet<LLChiclet>(old_session_id);
+ if (chiclet) chiclet->setSessionId(new_session_id);
+ }
+}
+
+S32 LLBottomTray::getTotalUnreadIMCount()
+{
+ return getChicletPanel()->getTotalUnreadIMCount();
+}
+
+// virtual
+void LLBottomTray::onChange(EStatusType status, const std::string &channelURI, bool proximal)
+{
+ // Time it takes to connect to voice channel might be pretty long,
+ // so don't expect user login or STATUS_VOICE_ENABLED to be followed by STATUS_JOINED.
+ BOOL enable = FALSE;
+
+ switch (status)
+ {
+ // Do not add STATUS_VOICE_ENABLED because voice chat is
+ // inactive until STATUS_JOINED
+ case STATUS_JOINED:
+ enable = TRUE;
+ break;
+ default:
+ enable = FALSE;
+ break;
+ }
+
+ // We have to enable/disable right and left parts of speak button separately (EXT-4648)
+ mSpeakBtn->setSpeakBtnEnabled(enable);
+ // skipped to avoid button blinking
+ if (status != STATUS_JOINING && status!= STATUS_LEFT_CHANNEL)
+ {
+ mSpeakBtn->setFlyoutBtnEnabled(LLVoiceClient::getInstance()->voiceEnabled() && LLVoiceClient::getInstance()->isVoiceWorking());
+ }
+}
+
+void LLBottomTray::onMouselookModeOut()
+{
+ mIsInLiteMode = false;
+ mBottomTrayLite->setVisible(FALSE);
+ mNearbyChatBar->getChatBox()->setText(mBottomTrayLite->mNearbyChatBar->getChatBox()->getText());
+ setVisible(TRUE);
+}
+
+void LLBottomTray::onMouselookModeIn()
+{
+ setVisible(FALSE);
+
+ // Attach the lite bottom tray
+ if (getParent() && mBottomTrayLite->getParent() != getParent())
+ getParent()->addChild(mBottomTrayLite);
+
+ mBottomTrayLite->setShape(getLocalRect());
+ mBottomTrayLite->mNearbyChatBar->getChatBox()->setText(mNearbyChatBar->getChatBox()->getText());
+ mBottomTrayLite->mGesturePanel->setVisible(gSavedSettings.getBOOL("ShowGestureButton"));
+
+ mIsInLiteMode = true;
+}
+
+//virtual
+// setVisible used instead of onVisibilityChange, since LLAgent calls it on entering/leaving mouselook mode.
+// If bottom tray is already visible in mouselook mode, then onVisibilityChange will not be called from setVisible(true),
+void LLBottomTray::setVisible(BOOL visible)
+{
+ if (mIsInLiteMode)
+ {
+ mBottomTrayLite->setVisible(visible);
+ }
+ else
+ {
+ LLPanel::setVisible(visible);
+ }
+}
+
+S32 LLBottomTray::notifyParent(const LLSD& info)
+{
+ if(info.has("well_empty")) // implementation of EXT-3397
+ {
+ const std::string chiclet_name = info["well_name"];
+
+ // only "im_well" or "notification_well" names are expected.
+ // They are set in panel_bottomtray.xml in <chiclet_im_well> & <chiclet_notification>
+ llassert("im_well" == chiclet_name || "notification_well" == chiclet_name);
+
+ BOOL should_be_visible = !info["well_empty"];
+ showWellButton("im_well" == chiclet_name ? RS_IM_WELL : RS_NOTIFICATION_WELL, should_be_visible);
+ return 1;
+ }
+
+ if (info.has("action") && info["action"] == "resize")
+ {
+ const std::string& name = info["view_name"];
+
+ // expected only resize of nearby chatbar
+ if (mChatBarContainer->getName() != name) return LLPanel::notifyParent(info);
+
+ const S32 new_width = info["new_width"];
+
+ processChatbarCustomization(new_width);
+
+ return 2;
+ }
+ return LLPanel::notifyParent(info);
+}
+
+void LLBottomTray::showBottomTrayContextMenu(S32 x, S32 y, MASK mask)
+{
+ // We should show BottomTrayContextMenu in last turn
+ if (mBottomTrayContextMenu && !LLMenuGL::sMenuContainer->getVisibleMenu())
+ {
+ //there are no other context menu (IM chiclet etc ), so we can show BottomTrayContextMenu
+
+ updateContextMenu(x, y, mask);
+ mBottomTrayContextMenu->buildDrawLabels();
+ mBottomTrayContextMenu->updateParent(LLMenuGL::sMenuContainer);
+ LLMenuGL::showPopup(this, mBottomTrayContextMenu, x, y);
+
+ }
+}
+
+void LLBottomTray::updateContextMenu(S32 x, S32 y, MASK mask)
+{
+ LLUICtrl* edit_box = mNearbyChatBar->getChild<LLUICtrl>("chat_box");
+
+ S32 local_x = x - mChatBarContainer->getRect().mLeft - edit_box->getRect().mLeft;
+ S32 local_y = y - mChatBarContainer->getRect().mBottom - edit_box->getRect().mBottom;
+
+ bool in_edit_box = edit_box->pointInView(local_x, local_y);
+
+ mBottomTrayContextMenu->setItemVisible("Separator", in_edit_box);
+ mBottomTrayContextMenu->setItemVisible("NearbyChatBar_Cut", in_edit_box);
+ mBottomTrayContextMenu->setItemVisible("NearbyChatBar_Copy", in_edit_box);
+ mBottomTrayContextMenu->setItemVisible("NearbyChatBar_Paste", in_edit_box);
+ mBottomTrayContextMenu->setItemVisible("NearbyChatBar_Delete", in_edit_box);
+ mBottomTrayContextMenu->setItemVisible("NearbyChatBar_Select_All", in_edit_box);
+}
+
+void LLBottomTray::showGestureButton(BOOL visible)
+{
+ setTrayButtonVisibleIfPossible(RS_BUTTON_GESTURES, visible);
+}
+
+void LLBottomTray::showMoveButton(BOOL visible)
+{
+ setTrayButtonVisibleIfPossible(RS_BUTTON_MOVEMENT, visible);
+}
+
+void LLBottomTray::showCameraButton(BOOL visible)
+{
+ setTrayButtonVisibleIfPossible(RS_BUTTON_CAMERA, visible);
+}
+
+void LLBottomTray::showSnapshotButton(BOOL visible)
+{
+ setTrayButtonVisibleIfPossible(RS_BUTTON_SNAPSHOT, visible);
+}
+
+void LLBottomTray::showSpeakButton(bool visible)
+{
+ // Show/hide the button
+ setTrayButtonVisible(RS_BUTTON_SPEAK, visible);
+
+ // and adjust other panels according to the occupied/freed space.
+ const S32 panel_width = mSpeakPanel->getRect().getWidth();
+ if (visible)
+ {
+ processWidthDecreased(-panel_width);
+ }
+ else
+ {
+ processWidthIncreased(panel_width);
+ }
+}
+
+void LLBottomTray::toggleMovementControls()
+{
+ if (mMovementButton)
+ mMovementButton->onCommit();
+}
+
+void LLBottomTray::toggleCameraControls()
+{
+ if (mCamButton)
+ mCamButton->onCommit();
+}
+
+BOOL LLBottomTray::postBuild()
+{
+ LLHints::registerHintTarget("bottom_tray", LLView::getHandle());
+ LLHints::registerHintTarget("dest_guide_btn", getChild<LLUICtrl>("destination_btn")->getHandle());
+ LLHints::registerHintTarget("avatar_picker_btn", getChild<LLUICtrl>("avatar_btn")->getHandle());
+
+ LLUICtrl::CommitCallbackRegistry::currentRegistrar().add("NearbyChatBar.Action", boost::bind(&LLBottomTray::onContextMenuItemClicked, this, _2));
+ LLUICtrl::EnableCallbackRegistry::currentRegistrar().add("NearbyChatBar.EnableMenuItem", boost::bind(&LLBottomTray::onContextMenuItemEnabled, this, _2));
+
+ mBottomTrayContextMenu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_bottomtray.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
+ gMenuHolder->addChild(mBottomTrayContextMenu);
+
+ mNearbyChatBar = findChild<LLNearbyChatBar>("chat_bar");
+ LLHints::registerHintTarget("chat_bar", mNearbyChatBar->LLView::getHandle());
+
+ mChatBarContainer = getChild<LLLayoutPanel>("chat_bar_layout_panel");
+ mNearbyCharResizeHandlePanel = getChild<LLPanel>("chat_bar_resize_handle_panel");
+
+ mToolbarStack = getChild<LLLayoutStack>("toolbar_stack");
+ mMovementButton = getChild<LLButton>("movement_btn");
+ LLHints::registerHintTarget("move_btn", mMovementButton->getHandle());
+ mCamButton = getChild<LLButton>("camera_btn");
+ setRightMouseDownCallback(boost::bind(&LLBottomTray::showBottomTrayContextMenu,this, _2, _3,_4));
+
+ mSpeakPanel = getChild<LLPanel>("speak_panel");
+ mSpeakBtn = getChild<LLSpeakButton>("talk");
+
+ // Both parts of speak button should be initially disabled because
+ // it takes some time between logging in to world and connecting to voice channel.
+ mSpeakBtn->setSpeakBtnEnabled(false);
+ mSpeakBtn->setFlyoutBtnEnabled(false);
+
+ // Localization tool doesn't understand custom buttons like <talk_button>
+ mSpeakBtn->setSpeakToolTip( getString("SpeakBtnToolTip") );
+ mSpeakBtn->setShowToolTip( getString("VoiceControlBtnToolTip") );
+
+ // Registering Chat Bar to receive Voice client status change notifications.
+ LLVoiceClient::getInstance()->addObserver(this);
+
+ mNearbyChatBar->getChatBox()->setContextMenu(NULL);
+
+ mChicletPanel = getChild<LLChicletPanel>("chiclet_list");
+
+ initResizeStateContainers();
+
+ setButtonsControlsAndListeners();
+
+ initButtonsVisibility();
+
+ // update wells visibility:
+ showWellButton(RS_IM_WELL, !LLIMWellWindow::getInstance()->isWindowEmpty());
+ showWellButton(RS_NOTIFICATION_WELL, !LLNotificationWellWindow::getInstance()->isWindowEmpty());
+
+ loadButtonsOrder();
+
+ LLViewerParcelMgr::getInstance()->addAgentParcelChangedCallback(boost::bind(&update_build_button_enable_state));
+
+ return TRUE;
+}
+
+//Drag-n-drop
+
+void LLBottomTray::onDraggableButtonMouseDown(LLUICtrl* ctrl, S32 x, S32 y)
+{
+ if (ctrl == NULL) return;
+ LLView* parent_view = ctrl->getParent();
+ if(parent_view != NULL)
+ {
+ // we actually drag'n'drop panel (not button) in code, so have to find a parent
+ // of button which called this method on mouse down.
+ LLPanel* parent = dynamic_cast<LLPanel*>(parent_view);
+ // It may happen that we clicked not usual button, but button inside widget(speak, gesture)
+ // so we'll need to get a level higher to reach layout panel as a parent.
+ if(parent == NULL) parent = dynamic_cast<LLPanel*>(parent_view->getParent());
+ if (parent && parent->getVisible())
+ {
+ mDraggedItem = parent;
+ mCheckForDrag = true;
+ mStartX = x;
+ mStartY = y;
+ }
+ }
+}
+
+LLPanel* LLBottomTray::findChildPanelByLocalCoords(S32 x, S32 y)
+{
+ LLPanel* ctrl = 0;
+ S32 screenX, screenY;
+ const child_list_t* list = mToolbarStack->getChildList();
+
+ localPointToScreen(x, y, &screenX, &screenY);
+
+ // look for a child panel which contains the point (screenX, screenY) in it's rectangle
+ for (child_list_const_iter_t i = list->begin(); i != list->end(); ++i)
+ {
+ LLRect rect;
+ localRectToScreen((*i)->getRect(), &rect);
+
+ if (rect.pointInRect(screenX, screenY))
+ {
+ ctrl = dynamic_cast<LLPanel*>(*i);
+ break;
+ }
+ }
+
+ return ctrl;
+}
+
+void LLBottomTray::onDraggableButtonHover(S32 x, S32 y)
+{
+ // if mouse down on draggable item was done, check whether we should start DnD
+ if (mCheckForDrag)
+ {
+ // Start drag'n'drop if mouse cursor was dragged away frome mouse down location enough
+ if(sqrt((float)((mStartX-x)*(mStartX-x)+(mStartY-y)*(mStartY-y))) > DRAG_START_DISTANCE)
+ {
+ mDragStarted = true;
+ mCheckForDrag = false;
+ }
+ }
+ if (mDragStarted)
+ {
+ // Check whether the cursor is over draggable area, find which panel it is and set is as
+ // landing tab for drag'n'drop
+ if(isCursorOverDraggableArea(x, y))
+ {
+ LLPanel* panel = findChildPanelByLocalCoords(x,y);
+ if (panel && panel != mDraggedItem) mLandingTab = panel;
+ gViewerWindow->getWindow()->setCursor(UI_CURSOR_ARROWDRAG);
+ }
+ else
+ {
+ gViewerWindow->getWindow()->setCursor(UI_CURSOR_NO);
+ }
+ }
+ else
+ {
+ // Reset cursor in case you move your mouse from the drag handle to a button.
+ getWindow()->setCursor(UI_CURSOR_ARROW);
+
+ }
+}
+
+bool LLBottomTray::isCursorOverDraggableArea(S32 x, S32 y)
+{
+ // Draggable area lasts from the nearby chat input resize handle
+ // to the chiclet area (exlusively).
+ bool result = getRect().pointInRect(x, y);
+ result = result && mNearbyCharResizeHandlePanel->calcScreenRect().mRight < x;
+ result = result && mChicletPanel->calcScreenRect().mRight > x;
+ return result;
+}
+
+void LLBottomTray::updateButtonsOrdersAfterDnD()
+{
+ // *TODO: change implementation of this method to support simplify it
+ // (and according to future possible changes in the way button order is saved between sessions).
+ state_object_map_t::const_iterator it = mStateProcessedObjectMap.begin();
+ state_object_map_t::const_iterator it_end = mStateProcessedObjectMap.end();
+ EResizeState dragged_state = RS_NORESIZE;
+ EResizeState landing_state = RS_NORESIZE;
+ bool landing_state_found = false;
+ // Find states for dragged item and landing tab
+ for (; it != it_end; ++it)
+ {
+ if (it->second == mDraggedItem)
+ {
+ dragged_state = it->first;
+ }
+ else if (it->second == mLandingTab)
+ {
+ landing_state = it->first;
+ landing_state_found = true;
+ }
+ }
+
+ if (dragged_state == RS_NORESIZE)
+ {
+ llwarns << "Cannot determine what button is being dragged" << llendl;
+ llassert(dragged_state != RS_NORESIZE);
+ return;
+ }
+
+ lldebugs << "Will place " << resizeStateToString(dragged_state)
+ << " before " << resizeStateToString(landing_state) << llendl;
+
+ // Update order of buttons according to drag'n'drop
+ mButtonsOrder.erase(std::find(mButtonsOrder.begin(), mButtonsOrder.end(), dragged_state));
+ if (!landing_state_found && mLandingTab == getChild<LLPanel>(PANEL_CHICLET_NAME))
+ {
+ mButtonsOrder.push_back(dragged_state);
+ }
+ else
+ {
+ if (!landing_state_found) landing_state = RS_BUTTON_SPEAK; // just a random fallback
+ mButtonsOrder.insert(std::find(mButtonsOrder.begin(), mButtonsOrder.end(), landing_state), dragged_state);
+ }
+
+ // Synchronize button process order with their order
+ resize_state_vec_t::const_iterator it1 = mButtonsOrder.begin();
+ const resize_state_vec_t::const_iterator it_end1 = mButtonsOrder.end();
+ resize_state_vec_t::iterator it2 = mButtonsProcessOrder.begin();
+ for (; it1 != it_end1; ++it1)
+ {
+ // Skip Speak because it is not in mButtonsProcessOrder(it's the reason why mButtonsOrder was introduced).
+ // If any other draggable items will be added to bottomtray later, they should also be skipped here.
+ if (*it1 != RS_BUTTON_SPEAK)
+ {
+ *it2 = *it1;
+ ++it2;
+ }
+ }
+
+ saveButtonsOrder();
+}
+
+void LLBottomTray::saveButtonsOrder()
+{
+ std::string user_dir = gDirUtilp->getLindenUserDir();
+ if (user_dir.empty()) return;
+
+ std::string filename = gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT, SORTING_DATA_FILE_NAME);
+ LLSD settings_llsd;
+ int i = 0;
+ const resize_state_vec_t::const_iterator it_end = mButtonsOrder.end();
+ // we use numbers as keys for map which is saved in file and contains resize states as its values
+ for (resize_state_vec_t::const_iterator it = mButtonsOrder.begin(); it != it_end; ++it, i++)
+ {
+ std::string str = llformat("%d", i);
+ settings_llsd[str] = *it;
+ }
+ llofstream file;
+ file.open(filename);
+ LLSDSerialize::toPrettyXML(settings_llsd, file);
+}
+
+void LLBottomTray::loadButtonsOrder()
+{
+ // load per-resident sorting information
+ std::string filename = gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT, SORTING_DATA_FILE_NAME);
+
+ LLSD settings_llsd;
+ llifstream file;
+ file.open(filename);
+ if (!file.is_open()) return;
+
+ LLSDSerialize::fromXML(settings_llsd, file);
+
+
+ mButtonsOrder.clear();
+ mButtonsProcessOrder.clear();
+ int i = 0;
+ // getting button order from file
+ for (LLSD::map_const_iterator iter = settings_llsd.beginMap();
+ iter != settings_llsd.endMap(); ++iter, ++i)
+ {
+ std::string str = llformat("%d", i);
+ EResizeState state = (EResizeState)settings_llsd[str].asInteger();
+ mButtonsOrder.push_back(state);
+ // RS_BUTTON_SPEAK is skipped, because it shouldn't be in mButtonsProcessOrder (it does not hide or shrink).
+ if (state != RS_BUTTON_SPEAK)
+ {
+ mButtonsProcessOrder.push_back(state);
+ }
+ }
+
+ // There are other panels in layout stack order of which is not saved. Also, panels order of which is saved,
+ // are already in layout stack but in wrong order. The most convenient way to place them is moving them
+ // to front one by one (because in this case we don't have to pass the panel before which we want to insert our
+ // panel to movePanel()). So panels are moved in order from the end of mButtonsOrder vector(reverse iterator is used).
+ const resize_state_vec_t::const_reverse_iterator it_end = mButtonsOrder.rend();
+ // placing panels in layout stack according to button order which we loaded in previous for
+ for (resize_state_vec_t::const_reverse_iterator it = mButtonsOrder.rbegin(); it != it_end; ++it, ++i)
+ {
+ LLPanel* panel_to_move = getButtonPanel(*it);
+ mToolbarStack->movePanel(panel_to_move, NULL, true); // prepend
+ }
+ // Nearbychat is not stored in order settings file, but it must be the first of the panels, so moving it
+ // (along with its drag handle) manually here.
+ mToolbarStack->movePanel(getChild<LLLayoutPanel>("chat_bar_resize_handle_panel"), NULL, true);
+ mToolbarStack->movePanel(mChatBarContainer, NULL, true);
+}
+
+void LLBottomTray::onDraggableButtonMouseUp(LLUICtrl* ctrl, S32 x, S32 y)
+{
+ //if mouse up happened over area where drop is possible, change order of buttons
+ if (mLandingTab != NULL && mDraggedItem != NULL && mDragStarted)
+ {
+ if(isCursorOverDraggableArea(x, y))
+ {
+ // change order of panels in layout stack
+ mToolbarStack->movePanel(mDraggedItem, (LLPanel*)mLandingTab);
+ // change order of buttons in order vectors
+ updateButtonsOrdersAfterDnD();
+ }
+ }
+ gViewerWindow->getWindow()->setCursor(UI_CURSOR_ARROW);
+ mDragStarted = false;
+ mDraggedItem = NULL;
+ mLandingTab = NULL;
+ mCheckForDrag = false;
+}
+
+void LLBottomTray::draw()
+{
+ LLPanel::draw();
+ if (mLandingTab)
+ {
+ static S32 w = mImageDragIndication->getWidth();
+ static S32 h = mImageDragIndication->getHeight();
+ LLRect rect = mLandingTab->calcScreenRect();
+ mImageDragIndication->draw(rect.mLeft - w/2, rect.getHeight(), w, h);
+ }
+ getChild<LLButton>("show_profile_btn")->setToggleState(LLAvatarActions::profileVisible(gAgent.getID()));
+
+ LLPanel* panel = LLSideTray::getInstance()->getPanel("panel_people");
+ if (panel && panel->isInVisibleChain())
+ {
+ getChild<LLButton>("show_people_button")->setToggleState(true);
+ }
+ else
+ {
+ getChild<LLButton>("show_people_button")->setToggleState(false);
+ }
+
+ LLFloater* help_browser = (LLFloaterReg::findInstance("help_browser"));
+ bool help_floater_visible = (help_browser && help_browser->isInVisibleChain());
+
+ getChild<LLButton>("show_help_btn")->setToggleState(help_floater_visible);
+
+
+}
+
+bool LLBottomTray::onContextMenuItemEnabled(const LLSD& userdata)
+{
+ std::string item = userdata.asString();
+ LLLineEditor* edit_box = mNearbyChatBar->findChild<LLLineEditor>("chat_box");
+
+ if (item == "can_cut")
+ {
+ return edit_box->canCut();
+ }
+ else if (item == "can_copy")
+ {
+ return edit_box->canCopy();
+ }
+ else if (item == "can_paste")
+ {
+ return edit_box->canPaste();
+ }
+ else if (item == "can_delete")
+ {
+ return edit_box->canDoDelete();
+ }
+ else if (item == "can_select_all")
+ {
+ return edit_box->canSelectAll() && (edit_box->getLength()>0);
+ }
+ return true;
+}
+
+
+void LLBottomTray::onContextMenuItemClicked(const LLSD& userdata)
+{
+ std::string item = userdata.asString();
+ LLLineEditor* edit_box = mNearbyChatBar->findChild<LLLineEditor>("chat_box");
+
+ if (item == "cut")
+ {
+ edit_box->cut();
+ }
+ else if (item == "copy")
+ {
+ edit_box->copy();
+ }
+ else if (item == "paste")
+ {
+ edit_box->paste();
+ edit_box->setFocus(TRUE);
+ }
+ else if (item == "delete")
+ {
+ edit_box->doDelete();
+ }
+ else if (item == "select_all")
+ {
+ edit_box->selectAll();
+ }
+}
+
+void LLBottomTray::log(LLView* panel, const std::string& descr)
+{
+ if (NULL == panel) return;
+ LLView* layout = panel->getParent();
+ lldebugs << descr << ": "
+ << "panel: " << panel->getName()
+ << ", rect: " << panel->getRect()
+
+
+ << "layout: " << layout->getName()
+ << ", rect: " << layout->getRect()
+ << llendl
+ ;
+}
+
+void LLBottomTray::reshape(S32 width, S32 height, BOOL called_from_parent)
+{
+ static S32 debug_calling_number = 0;
+ lldebugs << "**************************************** " << ++debug_calling_number << llendl;
+
+ S32 current_width = getRect().getWidth();
+ S32 delta_width = width - current_width;
+ lldebugs << "Reshaping: "
+ << ", width: " << width
+ << ", cur width: " << current_width
+ << ", delta_width: " << delta_width
+ << ", called_from_parent: " << called_from_parent
+ << llendl;
+
+ if (mNearbyChatBar) log(mNearbyChatBar, "before");
+ if (mChicletPanel) log(mChicletPanel, "before");
+
+ // stores width size on which bottom tray is less than width required by its children. EXT-991
+ static S32 extra_shrink_width = 0;
+ bool should_be_reshaped = true;
+
+ if (mChicletPanel && mToolbarStack && mNearbyChatBar)
+ {
+ // Firstly, update layout stack to ensure we deal with correct panel sizes.
+ {
+ BOOL saved_anim = mToolbarStack->getAnimate();
+ // Set chiclet panel to be autoresized by default.
+ mToolbarStack->updatePanelAutoResize(PANEL_CHICLET_NAME, TRUE);
+ // Disable animation to prevent layout updating in several frames.
+ mToolbarStack->setAnimate(FALSE);
+ // Force the updating of layout to reset panels collapse factor.
+ mToolbarStack->updateLayout();
+ // Restore animate state.
+ mToolbarStack->setAnimate(saved_anim);
+ }
+
+ // bottom tray is narrowed
+ if (delta_width < 0)
+ {
+ if (extra_shrink_width > 0)
+ {
+ // is world rect was extra shrunk and decreasing again only update this value
+ // to delta_width negative
+ extra_shrink_width -= delta_width; // use "-=" because delta_width is negative
+ should_be_reshaped = false;
+ }
+ else
+ {
+ extra_shrink_width = processWidthDecreased(delta_width);
+
+ // increase new width to extra_shrink_width value to not reshape less than bottom tray minimum
+ width += extra_shrink_width;
+ }
+ }
+ // bottom tray is widen
+ else
+ {
+ if (extra_shrink_width > delta_width)
+ {
+ // Less than minimum width is more than increasing (delta_width)
+ // only reduce it value and make no reshape
+ extra_shrink_width -= delta_width;
+ should_be_reshaped = false;
+ }
+ else
+ {
+ if (extra_shrink_width > 0)
+ {
+ // If we have some extra shrink width let's reduce delta_width & width
+ delta_width -= extra_shrink_width;
+ width -= extra_shrink_width;
+ extra_shrink_width = 0;
+ }
+ processWidthIncreased(delta_width);
+ }
+ }
+ }
+
+ if (should_be_reshaped)
+ {
+ lldebugs << "Reshape all children with width: " << width << llendl;
+ LLPanel::reshape(width, height, called_from_parent);
+ }
+
+ if (mNearbyChatBar) log(mNearbyChatBar, "after");
+ if (mChicletPanel) log(mChicletPanel, "after");
+
+
+ // Restore width of the chatbar on first reshape.
+ // we can not to do this from postBuild because reshape is called from parent view on startup
+ // creation after it and reset width according to resize logic.
+ static bool needs_restore_custom_state = true;
+ if (mChatBarContainer && needs_restore_custom_state)
+ {
+ // restore custom width of chatbar panel.
+ S32 new_width = gSavedSettings.getS32("ChatBarCustomWidth");
+ if (new_width > 0)
+ {
+ mDesiredNearbyChatWidth = new_width;
+ processChatbarCustomization(new_width);
+ mChatBarContainer->reshape(new_width, mChatBarContainer->getRect().getHeight());
+ }
+ needs_restore_custom_state = false;
+ }
+
+}
+
+S32 LLBottomTray::processWidthDecreased(S32 delta_width)
+{
+ bool still_should_be_processed = true;
+
+ const S32 chiclet_panel_width = mChicletPanel->getParent()->getRect().getWidth();
+ const S32 chiclet_panel_min_width = mChicletPanel->getMinWidth();
+
+ // There are four steps of processing width decrease. If in one of them required width was reached,
+ // further are not needed.
+ // 1. Decreasing width of chiclet panel.
+ if (chiclet_panel_width > chiclet_panel_min_width)
+ {
+ // we have some space to decrease chiclet panel
+ S32 panel_delta_min = chiclet_panel_width - chiclet_panel_min_width;
+
+ S32 delta_panel = llmin(-delta_width, panel_delta_min);
+
+ lldebugs << "delta_width: " << delta_width
+ << ", panel_delta_min: " << panel_delta_min
+ << ", delta_panel: " << delta_panel
+ << llendl;
+
+ // is chiclet panel width enough to process resizing?
+ delta_width += panel_delta_min;
+
+ still_should_be_processed = delta_width < 0;
+
+ mChicletPanel->getParent()->reshape(mChicletPanel->getParent()->getRect().getWidth() - delta_panel, mChicletPanel->getParent()->getRect().getHeight());
+ log(mChicletPanel, "after processing panel decreasing via chiclet panel");
+
+ lldebugs << "RS_CHICLET_PANEL"
+ << ", delta_width: " << delta_width
+ << llendl;
+ }
+
+ S32 buttons_freed_width = 0;
+ // 2. Decreasing width of buttons.
+ if (still_should_be_processed)
+ {
+ processShrinkButtons(delta_width, buttons_freed_width);
+ }
+ // 3. Decreasing width of nearby chat.
+ const S32 chatbar_panel_min_width = get_panel_min_width(mToolbarStack, mChatBarContainer);
+ const S32 chatbar_panel_width = mChatBarContainer->getRect().getWidth();
+ if (still_should_be_processed && chatbar_panel_width > chatbar_panel_min_width)
+ {
+ // we have some space to decrease chatbar panel
+ S32 panel_delta_min = chatbar_panel_width - chatbar_panel_min_width;
+
+ S32 delta_panel = llmin(-delta_width, panel_delta_min);
+
+ // whether chatbar panel width is enough to process resizing?
+ delta_width += panel_delta_min;
+
+ still_should_be_processed = delta_width < 0;
+
+ // chatbar should only be shrunk here, not stretched
+ if(delta_panel > 0)
+ {
+ mChatBarContainer->reshape(mNearbyChatBar->getRect().getWidth() - delta_panel, mChatBarContainer->getRect().getHeight());
+ }
+
+ log(mNearbyChatBar, "after processing panel decreasing via nearby chatbar panel");
+
+ lldebugs << "RS_CHATBAR_INPUT"
+ << ", delta_panel: " << delta_panel
+ << ", delta_width: " << delta_width
+ << llendl;
+ }
+
+ S32 extra_shrink_width = 0;
+ // 4. Hiding buttons if needed.
+ if (still_should_be_processed)
+ {
+ processHideButtons(delta_width, buttons_freed_width);
+
+ if (delta_width < 0)
+ {
+ extra_shrink_width = -delta_width;
+ llwarns << "There is no enough width to reshape all children: "
+ << extra_shrink_width << llendl;
+ }
+
+ if (buttons_freed_width > 0)
+ {
+ S32 nearby_needed_width = mDesiredNearbyChatWidth - mNearbyChatBar->getRect().getWidth();
+ if (nearby_needed_width > 0)
+ {
+ S32 compensative_width = nearby_needed_width > buttons_freed_width ? buttons_freed_width : nearby_needed_width;
+ log(mNearbyChatBar, "before applying compensative width");
+ mChatBarContainer->reshape(mChatBarContainer->getRect().getWidth() + compensative_width, mChatBarContainer->getRect().getHeight() );
+ log(mNearbyChatBar, "after applying compensative width");
+ lldebugs << buttons_freed_width << llendl;
+ }
+ }
+ }
+
+ return extra_shrink_width;
+}
+
+void LLBottomTray::processWidthIncreased(S32 delta_width)
+{
+ if (delta_width <= 0) return;
+
+ const S32 chiclet_panel_width = mChicletPanel->getParent()->getRect().getWidth();
+ static const S32 chiclet_panel_min_width = mChicletPanel->getMinWidth();
+
+ const S32 available_width_chiclet = chiclet_panel_width - chiclet_panel_min_width;
+
+ // how many room we have to show hidden buttons
+ S32 total_available_width = delta_width + available_width_chiclet;
+
+ lldebugs << "Processing extending, available width:"
+ << ", chiclets - " << available_width_chiclet
+ << ", total - " << total_available_width
+ << llendl;
+
+ S32 available_width = total_available_width;
+
+ processShowButtons(available_width);
+
+ // if we have to show/extend some buttons but resized delta width is not enough...
+ S32 processed_width = total_available_width - available_width;
+ if (processed_width > delta_width)
+ {
+ // ... let's shrink nearby chat & chiclet panels
+ S32 required_to_process_width = processed_width;
+
+ // 1. use delta width of resizing
+ required_to_process_width -= delta_width;
+
+ // 2. use width available via decreasing of chiclet panel
+ if (required_to_process_width > 0)
+ {
+ mChicletPanel->getParent()->reshape(mChicletPanel->getParent()->getRect().getWidth() - required_to_process_width, mChicletPanel->getParent()->getRect().getHeight());
+ log(mChicletPanel, "after applying compensative width for chiclets: ");
+ lldebugs << required_to_process_width << llendl;
+ }
+
+ }
+
+ // shown buttons take some space, rest should be processed by nearby chatbar & chiclet panels
+ delta_width -= processed_width;
+
+
+ // how many space can nearby chatbar take?
+ S32 chatbar_panel_width_ = mChatBarContainer->getRect().getWidth();
+ if (delta_width > 0 && chatbar_panel_width_ < mDesiredNearbyChatWidth)
+ {
+ S32 delta_panel_max = mDesiredNearbyChatWidth - chatbar_panel_width_;
+ S32 delta_panel = llmin(delta_width, delta_panel_max);
+ lldebugs << "Unprocesed delta width: " << delta_width
+ << ", can be applied to chatbar: " << delta_panel_max
+ << ", will be applied: " << delta_panel
+ << llendl;
+
+ delta_width -= delta_panel_max;
+ mChatBarContainer->reshape(chatbar_panel_width_ + delta_panel, mChatBarContainer->getRect().getHeight());
+ log(mNearbyChatBar, "applied unprocessed delta width");
+ }
+ if (delta_width > 0)
+ {
+ processExtendButtons(delta_width);
+ }
+}
+
+void LLBottomTray::processShowButtons(S32& available_width)
+{
+ // process buttons from left to right
+ resize_state_vec_t::const_iterator it = mButtonsProcessOrder.begin();
+ const resize_state_vec_t::const_iterator it_end = mButtonsProcessOrder.end();
+
+ for (; it != it_end; ++it)
+ {
+ // is there available space?
+ if (available_width <= 0) break;
+
+ // try to show next button
+ processShowButton(*it, available_width);
+ }
+}
+
+bool LLBottomTray::processShowButton(EResizeState shown_object_type, S32& available_width)
+{
+ lldebugs << "Trying to show object type: " << shown_object_type << llendl;
+
+ LLPanel* panel = getButtonPanel(shown_object_type);
+ if (NULL == panel)
+ {
+ lldebugs << "There is no object to process for state: " << shown_object_type << llendl;
+ return false;
+ }
+ bool can_be_shown = canButtonBeShown(shown_object_type);
+ if (can_be_shown)
+ {
+ //validate if we have enough room to show this button
+ const S32 required_width = panel->getRect().getWidth();
+ can_be_shown = available_width >= required_width;
+ if (can_be_shown)
+ {
+ available_width -= required_width;
+
+ setTrayButtonVisible(shown_object_type, true);
+
+ lldebugs << "processed object type: " << shown_object_type
+ << ", rest available width: " << available_width
+ << llendl;
+ mResizeState &= ~shown_object_type;
+ }
+ }
+ return can_be_shown;
+}
+
+void LLBottomTray::processHideButtons(S32& required_width, S32& buttons_freed_width)
+{
+ // process buttons from right to left
+ resize_state_vec_t::const_reverse_iterator it = mButtonsProcessOrder.rbegin();
+ const resize_state_vec_t::const_reverse_iterator it_end = mButtonsProcessOrder.rend();
+
+ for (; it != it_end; ++it)
+ {
+ // is it still necessary to hide a button?
+ if (required_width >= 0) break;
+
+ // try to hide next button
+ processHideButton(*it, required_width, buttons_freed_width);
+ }
+}
+
+void LLBottomTray::processHideButton(EResizeState processed_object_type, S32& required_width, S32& buttons_freed_width)
+{
+ lldebugs << "Trying to hide object type: " << processed_object_type << llendl;
+ LLPanel* panel = getButtonPanel(processed_object_type);
+ if (NULL == panel)
+ {
+ lldebugs << "There is no object to process for state: " << processed_object_type << llendl;
+ return;
+ }
+
+ if (panel->getVisible())
+ {
+ required_width += panel->getRect().getWidth();
+
+ if (required_width > 0)
+ {
+ buttons_freed_width += required_width;
+ }
+
+ setTrayButtonVisible(processed_object_type, false);
+
+ mResizeState |= processed_object_type;
+
+ lldebugs << "processing object type: " << processed_object_type
+ << ", buttons_freed_width: " << buttons_freed_width
+ << llendl;
+ }
+}
+
+void LLBottomTray::processShrinkButtons(S32& required_width, S32& buttons_freed_width)
+{
+ // process buttons from right to left
+ resize_state_vec_t::const_reverse_iterator it = mButtonsProcessOrder.rbegin();
+ const resize_state_vec_t::const_reverse_iterator it_end = mButtonsProcessOrder.rend();
+
+ // iterate through buttons in the mButtonsProcessOrder first
+ for (; it != it_end; ++it)
+ {
+ // is it still necessary to hide a button?
+ if (required_width >= 0) break;
+
+ // try to shrink next button
+ processShrinkButton(*it, required_width);
+ }
+
+ // then shrink Speak button
+ if (required_width < 0)
+ {
+ S32 panel_min_width = 0;
+ std::string panel_name = mSpeakPanel->getName();
+ bool success = mToolbarStack->getPanelMinSize(panel_name, &panel_min_width);
+ if (!success)
+ {
+ lldebugs << "Panel was not found to get its min width: " << panel_name << llendl;
+ }
+ else
+ {
+ S32 panel_width = mSpeakPanel->getRect().getWidth();
+ S32 possible_shrink_width = panel_width - panel_min_width;
+
+ if (possible_shrink_width > 0)
+ {
+ mSpeakBtn->setLabelVisible(false);
+ mSpeakPanel->reshape(panel_width - possible_shrink_width, mSpeakPanel->getRect().getHeight());
+
+ required_width += possible_shrink_width;
+
+ if (required_width > 0)
+ {
+ buttons_freed_width += required_width;
+ }
+
+ lldebugs << "Shrunk Speak button panel: " << panel_name
+ << ", shrunk width: " << possible_shrink_width
+ << ", rest width to process: " << required_width
+ << llendl;
+ }
+ }
+ }
+}
+
+void LLBottomTray::processShrinkButton(EResizeState processed_object_type, S32& required_width)
+{
+ LLPanel* panel = getButtonPanel(processed_object_type);
+ if (NULL == panel)
+ {
+ lldebugs << "There is no object to process for type: " << processed_object_type << llendl;
+ return;
+ }
+
+ if (panel->getVisible())
+ {
+ S32 panel_width = panel->getRect().getWidth();
+ S32 panel_min_width = 0;
+ std::string panel_name = panel->getName();
+ bool success = mToolbarStack->getPanelMinSize(panel_name, &panel_min_width);
+ S32 possible_shrink_width = panel_width - panel_min_width;
+
+ if (!success)
+ {
+ lldebugs << "Panel was not found to get its min width: " << panel_name << llendl;
+ }
+ // we have some space to free by shrinking the button
+ else if (possible_shrink_width > 0)
+ {
+ // let calculate real width to shrink
+
+ // 1. apply all possible width
+ required_width += possible_shrink_width;
+
+ // 2. it it is too much...
+ if (required_width > 0)
+ {
+ // reduce applied shrunk width to the excessive value.
+ possible_shrink_width -= required_width;
+ required_width = 0;
+ }
+ panel->reshape(panel_width - possible_shrink_width, panel->getRect().getHeight());
+
+ lldebugs << "Shrunk panel: " << panel_name
+ << ", shrunk width: " << possible_shrink_width
+ << ", rest width to process: " << required_width
+ << llendl;
+ }
+ }
+}
+
+
+void LLBottomTray::processExtendButtons(S32& available_width)
+{
+ // do not allow extending any buttons if we have some buttons hidden via resize
+ if (mResizeState & RS_BUTTONS_CAN_BE_HIDDEN) return;
+
+ // process buttons from left to right
+ resize_state_vec_t::const_iterator it = mButtonsProcessOrder.begin();
+ const resize_state_vec_t::const_iterator it_end = mButtonsProcessOrder.end();
+
+ // iterate through buttons in the mButtonsProcessOrder first
+ for (; it != it_end; ++it)
+ {
+ // is there available space?
+ if (available_width <= 0) break;
+
+ // try to extend next button
+ processExtendButton(*it, available_width);
+ }
+
+ const S32 chiclet_panel_width = mChicletPanel->getParent()->getRect().getWidth();
+ static const S32 chiclet_panel_min_width = mChicletPanel->getMinWidth();
+ const S32 available_width_chiclet = chiclet_panel_width - chiclet_panel_min_width;
+
+ // then try to extend Speak button
+ if (available_width > 0 || available_width_chiclet > 0)
+ {
+ S32 panel_max_width = mObjectDefaultWidthMap[RS_BUTTON_SPEAK];
+ S32 panel_width = mSpeakPanel->getRect().getWidth();
+ S32 possible_extend_width = panel_max_width - panel_width;
+
+ if (possible_extend_width >= 0 && possible_extend_width <= available_width + available_width_chiclet) // HACK: this button doesn't change size so possible_extend_width will be 0
+ {
+ mSpeakBtn->setLabelVisible(true);
+ mSpeakPanel->reshape(panel_max_width, mSpeakPanel->getRect().getHeight());
+ log(mSpeakBtn, "speak button is extended");
+
+ if( available_width > possible_extend_width)
+ {
+ available_width -= possible_extend_width;
+ }
+ else
+ {
+ S32 required_width = possible_extend_width - available_width;
+ available_width = 0;
+ mChicletPanel->getParent()->reshape(mChicletPanel->getParent()->getRect().getWidth() - required_width, mChicletPanel->getParent()->getRect().getHeight());
+ }
+ lldebugs << "Extending Speak button panel: " << mSpeakPanel->getName()
+ << ", extended width: " << possible_extend_width
+ << ", rest width to process: " << available_width
+ << llendl;
+ }
+ }
+}
+
+void LLBottomTray::processExtendButton(EResizeState processed_object_type, S32& available_width)
+{
+ LLPanel* panel = getButtonPanel(processed_object_type);
+ if (NULL == panel)
+ {
+ lldebugs << "There is no object to process for type: " << processed_object_type << llendl;
+ return;
+ }
+
+ if (!panel->getVisible()) return;
+
+ S32 panel_max_width = mObjectDefaultWidthMap[processed_object_type];
+ S32 panel_width = panel->getRect().getWidth();
+ S32 possible_extend_width = panel_max_width - panel_width;
+
+ if (possible_extend_width > 0)
+ {
+ // let calculate real width to extend
+
+ // 1. apply all possible width
+ available_width -= possible_extend_width;
+
+ // 2. it it is too much...
+ if (available_width < 0)
+ {
+ // reduce applied extended width to the excessive value.
+ possible_extend_width += available_width;
+ available_width = 0;
+ }
+ panel->reshape(panel_width + possible_extend_width, panel->getRect().getHeight());
+
+ lldebugs << "Extending panel: " << panel->getName()
+ << ", extended width: " << possible_extend_width
+ << ", rest width to process: " << available_width
+ << llendl;
+ }
+}
+
+bool LLBottomTray::canButtonBeShown(EResizeState processed_object_type) const
+{
+ // 0. Check if passed button was previously hidden on resize
+ bool can_be_shown = mResizeState & processed_object_type;
+ if (can_be_shown)
+ {
+ // Yes, it was. Lets now check that all buttons before it (that can be hidden on resize)
+ // are already shown
+
+ // process buttons in direct order (from left to right)
+ resize_state_vec_t::const_iterator it = mButtonsProcessOrder.begin();
+ const resize_state_vec_t::const_iterator it_end = mButtonsProcessOrder.end();
+
+ // 1. Find and accumulate all buttons types before one passed into the method.
+ MASK buttons_before_mask = RS_NORESIZE;
+ for (; it != it_end; ++it)
+ {
+ const EResizeState button_type = *it;
+ if (button_type == processed_object_type) break;
+
+ buttons_before_mask |= button_type;
+ }
+
+ // 2. Check if some previous buttons are still hidden on resize
+ can_be_shown = !(buttons_before_mask & mResizeState);
+ }
+ return can_be_shown;
+}
+
+void LLBottomTray::initResizeStateContainers()
+{
+ // init map with objects should be processed for each type
+ mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_SPEAK, getChild<LLPanel>("speak_panel")));
+ mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_GESTURES, getChild<LLPanel>("gesture_panel")));
+ mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_MOVEMENT, getChild<LLPanel>("movement_panel")));
+ mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_CAMERA, getChild<LLPanel>("cam_panel")));
+ mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_SNAPSHOT, getChild<LLPanel>("snapshot_panel")));
+ mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_BUILD, getChild<LLPanel>("build_btn_panel")));
+ mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_SEARCH, getChild<LLPanel>("search_btn_panel")));
+ mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_WORLD_MAP, getChild<LLPanel>("world_map_btn_panel")));
+ mStateProcessedObjectMap.insert(std::make_pair(RS_BUTTON_MINI_MAP, getChild<LLPanel>("mini_map_btn_panel")));
+
+ // init an order of processed buttons
+ mButtonsProcessOrder.push_back(RS_BUTTON_GESTURES);
+ mButtonsProcessOrder.push_back(RS_BUTTON_MOVEMENT);
+ mButtonsProcessOrder.push_back(RS_BUTTON_CAMERA);
+ mButtonsProcessOrder.push_back(RS_BUTTON_SNAPSHOT);
+ mButtonsProcessOrder.push_back(RS_BUTTON_BUILD);
+ mButtonsProcessOrder.push_back(RS_BUTTON_SEARCH);
+ mButtonsProcessOrder.push_back(RS_BUTTON_WORLD_MAP);
+ mButtonsProcessOrder.push_back(RS_BUTTON_MINI_MAP);
+
+ mButtonsOrder.push_back(RS_BUTTON_SPEAK);
+ mButtonsOrder.insert(mButtonsOrder.end(), mButtonsProcessOrder.begin(), mButtonsProcessOrder.end());
+
+ // init default widths
+
+ // process buttons that can be hidden on resize...
+ resize_state_vec_t::const_iterator it = mButtonsProcessOrder.begin();
+ const resize_state_vec_t::const_iterator it_end = mButtonsProcessOrder.end();
+
+ for (; it != it_end; ++it)
+ {
+ const EResizeState button_type = *it;
+ // is there an appropriate object?
+ LLPanel* button_panel = getButtonPanel(button_type);
+ if (!button_panel) continue;
+
+ // set default width for it.
+ mObjectDefaultWidthMap[button_type] = button_panel->getRect().getWidth();
+ }
+
+ // ... and add Speak button because it also can be shrunk.
+ mObjectDefaultWidthMap[RS_BUTTON_SPEAK] = mSpeakPanel->getRect().getWidth();
+}
+
+// this method must be called before restoring of the chat entry field on startup
+// because it resets chatbar's width according to resize logic.
+void LLBottomTray::initButtonsVisibility()
+{
+ setVisibleAndFitWidths(RS_BUTTON_SPEAK, gSavedSettings.getBOOL("EnableVoiceChat"));
+ setVisibleAndFitWidths(RS_BUTTON_GESTURES, gSavedSettings.getBOOL("ShowGestureButton"));
+ setVisibleAndFitWidths(RS_BUTTON_MOVEMENT, gSavedSettings.getBOOL("ShowMoveButton"));
+ setVisibleAndFitWidths(RS_BUTTON_CAMERA, gSavedSettings.getBOOL("ShowCameraButton"));
+ setVisibleAndFitWidths(RS_BUTTON_SNAPSHOT, gSavedSettings.getBOOL("ShowSnapshotButton"));
+ setVisibleAndFitWidths(RS_BUTTON_BUILD, gSavedSettings.getBOOL("ShowBuildButton"));
+ setVisibleAndFitWidths(RS_BUTTON_SEARCH, gSavedSettings.getBOOL("ShowSearchButton"));
+ setVisibleAndFitWidths(RS_BUTTON_WORLD_MAP, gSavedSettings.getBOOL("ShowWorldMapButton"));
+ setVisibleAndFitWidths(RS_BUTTON_MINI_MAP, gSavedSettings.getBOOL("ShowMiniMapButton"));
+}
+
+void LLBottomTray::setButtonsControlsAndListeners()
+{
+ gSavedSettings.getControl("EnableVoiceChat")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_SPEAK, _2));
+ gSavedSettings.getControl("ShowGestureButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_GESTURES, _2));
+ gSavedSettings.getControl("ShowMoveButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_MOVEMENT, _2));
+ gSavedSettings.getControl("ShowCameraButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_CAMERA, _2));
+ gSavedSettings.getControl("ShowSnapshotButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_SNAPSHOT, _2));
+ gSavedSettings.getControl("ShowBuildButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_BUILD, _2));
+ gSavedSettings.getControl("ShowSearchButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_SEARCH, _2));
+ gSavedSettings.getControl("ShowWorldMapButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_WORLD_MAP, _2));
+ gSavedSettings.getControl("ShowMiniMapButton")->getSignal()->connect(boost::bind(&LLBottomTray::toggleShowButton, RS_BUTTON_MINI_MAP, _2));
+
+
+ LLButton* build_btn = getChild<LLButton>("build_btn");
+ // set control name for Build button. It is not enough to link it with Button.SetFloaterToggle in xml
+ std::string vis_control_name = LLFloaterReg::declareVisibilityControl("build");
+ // Set the button control value (toggle state) to the floater visibility control (Sets the value as well)
+ build_btn->setControlVariable(LLFloater::getControlGroup()->getControl(vis_control_name));
+}
+
+bool LLBottomTray::toggleShowButton(LLBottomTray::EResizeState button_type, const LLSD& new_visibility)
+{
+ if (LLBottomTray::instanceExists())
+ {
+ LLBottomTray::getInstance()->setTrayButtonVisibleIfPossible(button_type, new_visibility.asBoolean());
+ }
+ return true;
+}
+
+void LLBottomTray::setTrayButtonVisible(EResizeState shown_object_type, bool visible)
+{
+ LLPanel* panel = getButtonPanel(shown_object_type);
+ if (NULL == panel)
+ {
+ lldebugs << "There is no object to show for state: " << shown_object_type << llendl;
+ return;
+ }
+
+ panel->setVisible(visible);
+}
+
+void LLBottomTray::setTrayButtonVisibleIfPossible(EResizeState shown_object_type, bool visible, bool raise_notification)
+{
+ if (!setVisibleAndFitWidths(shown_object_type, visible) && visible && raise_notification)
+ {
+ LLNotificationsUtil::add("BottomTrayButtonCanNotBeShown",
+ LLSD(),
+ LLSD(),
+ LLNotificationFunctorRegistry::instance().DONOTHING);
+ }
+}
+
+bool LLBottomTray::setVisibleAndFitWidths(EResizeState object_type, bool visible)
+{
+ // The Speak button is treated specially: if voice is enabled,
+ // the button should be displayed no matter how much space we've got.
+ if (object_type == RS_BUTTON_SPEAK)
+ {
+ showSpeakButton(visible);
+ return true;
+ }
+
+ LLPanel* cur_panel = getButtonPanel(object_type);
+ if (NULL == cur_panel)
+ {
+ lldebugs << "There is no object to process for state: " << object_type << llendl;
+ return false;
+ }
+
+ bool is_set = true;
+
+ if (visible)
+ {
+ // Assume that only chiclet panel can be auto-resized
+ const S32 available_width =
+ mChicletPanel->getParent()->getRect().getWidth() - mChicletPanel->getMinWidth();
+
+ S32 preferred_width = mObjectDefaultWidthMap[object_type];
+ S32 current_width = cur_panel->getRect().getWidth();
+ S32 result_width = 0;
+ bool decrease_width = false;
+
+ // Mark this button to be shown
+ mResizeState |= object_type;
+
+ if (preferred_width > 0 && available_width >= preferred_width)
+ {
+ result_width = preferred_width;
+ }
+ else if (available_width >= current_width)
+ {
+ result_width = current_width;
+ }
+ else
+ {
+ // Calculate the possible shrunk width as difference between current and minimal widths
+ const S32 chatbar_shrunk_width =
+ mChatBarContainer->getRect().getWidth() - get_panel_min_width(mToolbarStack, mChatBarContainer);
+
+ S32 sum_of_min_widths = get_panel_min_width(mToolbarStack, mSpeakPanel);
+ S32 sum_of_curr_widths = get_curr_width(mSpeakPanel);
+
+ resize_state_vec_t::const_iterator it = mButtonsProcessOrder.begin();
+ const resize_state_vec_t::const_iterator it_end = mButtonsProcessOrder.end();
+
+ for (; it != it_end; ++it)
+ {
+ LLPanel* cur_panel = getButtonPanel(*it);
+ sum_of_min_widths += get_panel_min_width(mToolbarStack, cur_panel);
+ sum_of_curr_widths += get_curr_width(cur_panel);
+ }
+
+ const S32 possible_shrunk_width =
+ chatbar_shrunk_width + (sum_of_curr_widths - sum_of_min_widths);
+
+ // Minimal width of current panel
+ S32 minimal_width = 0;
+ mToolbarStack->getPanelMinSize(cur_panel->getName(), &minimal_width);
+
+ if ( (available_width + possible_shrunk_width) >= minimal_width)
+ {
+ // There is enough space for minimal width, but set the result_width
+ // to preferred_width so buttons widths decreasing will be done in predefined order
+ result_width = (preferred_width > 0) ? preferred_width : current_width;
+ decrease_width = true;
+ }
+ else
+ {
+ // Nothing can be done, give up...
+ return false;
+ }
+ }
+
+ if (result_width != current_width)
+ {
+ cur_panel->reshape(result_width, cur_panel->getRect().getHeight());
+ current_width = result_width;
+ }
+
+ is_set = processShowButton(object_type, current_width);
+
+ // Shrink buttons if needed
+ if (is_set && decrease_width)
+ {
+ processWidthDecreased( -result_width);
+ }
+ }
+ else
+ {
+ const S32 delta_width = get_curr_width(cur_panel);
+
+ setTrayButtonVisible(object_type, false);
+
+ // Mark button NOT to show while future bottom tray extending
+ mResizeState &= ~object_type;
+
+ // Extend other buttons if need
+ if (delta_width)
+ {
+ processWidthIncreased(delta_width);
+ }
+ }
+ return is_set;
+}
+
+LLPanel* LLBottomTray::getButtonPanel(EResizeState button_type)
+{
+ // Don't use the operator[] because it inserts a NULL value if the key is not found.
+ if (mStateProcessedObjectMap.count(button_type) == 0)
+ {
+ llwarns << "Cannot find a panel for " << resizeStateToString(button_type) << llendl;
+ llassert(mStateProcessedObjectMap.count(button_type) == 1);
+ return NULL;
+ }
+
+ return mStateProcessedObjectMap[button_type];
+}
+
+void LLBottomTray::showWellButton(EResizeState object_type, bool visible)
+{
+ llassert( ((RS_NOTIFICATION_WELL | RS_IM_WELL) & object_type) == object_type );
+
+ const std::string panel_name = RS_IM_WELL == object_type ? "im_well_panel" : "notification_well_panel";
+
+ LLView * panel = getChild<LLView>(panel_name);
+
+ // if necessary visibility is set nothing to do here
+ if (panel->getVisible() == (BOOL)visible) return;
+
+ S32 panel_width = panel->getRect().getWidth();
+ panel->setVisible(visible);
+
+ if (visible)
+ {
+ // method assumes that input param is a negative value
+ processWidthDecreased(-panel_width);
+ }
+ else
+ {
+ processWidthIncreased(panel_width);
+ }
+}
+
+void LLBottomTray::processChatbarCustomization(S32 new_width)
+{
+ if (NULL == mNearbyChatBar) return;
+
+ const S32 delta_width = mChatBarContainer->getRect().getWidth() - new_width;
+
+ if (delta_width == 0) return;
+
+ mDesiredNearbyChatWidth = new_width;
+
+ LLView * chiclet_layout_panel = mChicletPanel->getParent();
+ const S32 chiclet_min_width = get_panel_min_width(mToolbarStack, chiclet_layout_panel);
+ const S32 chiclet_panel_width = chiclet_layout_panel->getRect().getWidth();
+ const S32 available_chiclet_shrink_width = chiclet_panel_width - chiclet_min_width;
+ llassert(available_chiclet_shrink_width >= 0);
+
+ if (delta_width > 0) // panel gets narrowly
+ {
+ S32 total_possible_width = delta_width + available_chiclet_shrink_width;
+ processShowButtons(total_possible_width);
+ processExtendButtons(total_possible_width);
+ }
+ // here (delta_width < 0) // panel gets wider
+ else //if (-delta_width > available_chiclet_shrink_width)
+ {
+ S32 required_width = delta_width + available_chiclet_shrink_width;
+ S32 buttons_freed_width = 0;
+ processShrinkButtons(required_width, buttons_freed_width);
+ processHideButtons(required_width, buttons_freed_width);
+ }
+}
+
+// static
+std::string LLBottomTray::resizeStateToString(EResizeState state)
+{
+ switch (state)
+ {
+ case RS_NORESIZE: return "RS_NORESIZE";
+ case RS_CHICLET_PANEL: return "RS_CHICLET_PANEL";
+ case RS_CHATBAR_INPUT: return "RS_CHATBAR_INPUT";
+ case RS_BUTTON_SNAPSHOT: return "RS_BUTTON_SNAPSHOT";
+ case RS_BUTTON_CAMERA: return "RS_BUTTON_CAMERA";
+ case RS_BUTTON_MOVEMENT: return "RS_BUTTON_MOVEMENT";
+ case RS_BUTTON_GESTURES: return "RS_BUTTON_GESTURES";
+ case RS_BUTTON_SPEAK: return "RS_BUTTON_SPEAK";
+ case RS_IM_WELL: return "RS_IM_WELL";
+ case RS_NOTIFICATION_WELL: return "RS_NOTIFICATION_WELL";
+ case RS_BUTTON_BUILD: return "RS_BUTTON_BUILD";
+ case RS_BUTTON_SEARCH: return "RS_BUTTON_SEARCH";
+ case RS_BUTTON_WORLD_MAP: return "RS_BUTTON_WORLD_MAP";
+ case RS_BUTTON_MINI_MAP: return "RS_BUTTON_MINI_MAP";
+ case RS_BUTTONS_CAN_BE_HIDDEN: return "RS_BUTTONS_CAN_BE_HIDDEN";
+ // No default to track additions.
+ }
+ return "UNKNOWN_BUTTON";
+}
+
+//EOF
diff --git a/indra/newview/llcallbacklist.cpp b/indra/newview/llcallbacklist.cpp
index a54c77b4a0..357a6582d1 100644
--- a/indra/newview/llcallbacklist.cpp
+++ b/indra/newview/llcallbacklist.cpp
@@ -115,6 +115,71 @@ void LLCallbackList::callFunctions()
}
}
+// Shim class to allow arbitrary boost::bind
+// expressions to be run as one-time idle callbacks.
+class OnIdleCallbackOneTime
+{
+public:
+ OnIdleCallbackOneTime(nullary_func_t callable):
+ mCallable(callable)
+ {
+ }
+ static void onIdle(void *data)
+ {
+ gIdleCallbacks.deleteFunction(onIdle, data);
+ OnIdleCallbackOneTime* self = reinterpret_cast<OnIdleCallbackOneTime*>(data);
+ self->call();
+ delete self;
+ }
+ void call()
+ {
+ mCallable();
+ }
+private:
+ nullary_func_t mCallable;
+};
+
+void doOnIdleOneTime(nullary_func_t callable)
+{
+ OnIdleCallbackOneTime* cb_functor = new OnIdleCallbackOneTime(callable);
+ gIdleCallbacks.addFunction(&OnIdleCallbackOneTime::onIdle,cb_functor);
+}
+
+// Shim class to allow generic boost functions to be run as
+// recurring idle callbacks. Callable should return true when done,
+// false to continue getting called.
+class OnIdleCallbackRepeating
+{
+public:
+ OnIdleCallbackRepeating(bool_func_t callable):
+ mCallable(callable)
+ {
+ }
+ // Will keep getting called until the callable returns true.
+ static void onIdle(void *data)
+ {
+ OnIdleCallbackRepeating* self = reinterpret_cast<OnIdleCallbackRepeating*>(data);
+ bool done = self->call();
+ if (done)
+ {
+ gIdleCallbacks.deleteFunction(onIdle, data);
+ delete self;
+ }
+ }
+ bool call()
+ {
+ return mCallable();
+ }
+private:
+ bool_func_t mCallable;
+};
+
+void doOnIdleRepeating(bool_func_t callable)
+{
+ OnIdleCallbackRepeating* cb_functor = new OnIdleCallbackRepeating(callable);
+ gIdleCallbacks.addFunction(&OnIdleCallbackRepeating::onIdle,cb_functor);
+}
+
#ifdef _DEBUG
void test1(void *data)
diff --git a/indra/newview/llcallbacklist.h b/indra/newview/llcallbacklist.h
index 07ac21f5e9..97f3bfd9ee 100644
--- a/indra/newview/llcallbacklist.h
+++ b/indra/newview/llcallbacklist.h
@@ -52,6 +52,15 @@ protected:
callback_list_t mCallbackList;
};
+typedef boost::function<void ()> nullary_func_t;
+typedef boost::function<bool ()> bool_func_t;
+
+// Call a given callable once in idle loop.
+void doOnIdleOneTime(nullary_func_t callable);
+
+// Repeatedly call a callable in idle loop until it returns true.
+void doOnIdleRepeating(bool_func_t callable);
+
extern LLCallbackList gIdleCallbacks;
#endif
diff --git a/indra/newview/llcommandhandler.cpp b/indra/newview/llcommandhandler.cpp
index 1b6ba02aac..1b6ba02aac 100755..100644
--- a/indra/newview/llcommandhandler.cpp
+++ b/indra/newview/llcommandhandler.cpp
diff --git a/indra/newview/lldrawable.cpp b/indra/newview/lldrawable.cpp
index 8106fada11..bdc12ec0e3 100644
--- a/indra/newview/lldrawable.cpp
+++ b/indra/newview/lldrawable.cpp
@@ -35,6 +35,7 @@
#include "llcriticaldamp.h"
#include "llface.h"
#include "lllightconstants.h"
+#include "llmatrix4a.h"
#include "llsky.h"
#include "llsurfacepatch.h"
#include "llviewercamera.h"
@@ -85,6 +86,7 @@ void LLDrawable::incrementVisible()
sCurVisible++;
sCurPixelAngle = (F32) gViewerWindow->getWindowHeightRaw()/LLViewerCamera::getInstance()->getView();
}
+
void LLDrawable::init()
{
// mXform
@@ -115,6 +117,11 @@ void LLDrawable::initClass()
void LLDrawable::destroy()
{
+ if (gDebugGL)
+ {
+ gPipeline.checkReferences(this);
+ }
+
if (isDead())
{
sNumZombieDrawables--;
@@ -133,6 +140,7 @@ void LLDrawable::destroy()
{
llinfos << "- Zombie drawables: " << sNumZombieDrawables << llendl;
}*/
+
}
void LLDrawable::markDead()
@@ -170,6 +178,11 @@ LLVOVolume* LLDrawable::getVOVolume() const
}
}
+const LLMatrix4& LLDrawable::getRenderMatrix() const
+{
+ return isRoot() ? getWorldMatrix() : getParent()->getWorldMatrix();
+}
+
BOOL LLDrawable::isLight() const
{
LLViewerObject* objectp = mVObjp;
@@ -183,20 +196,30 @@ BOOL LLDrawable::isLight() const
}
}
+static LLFastTimer::DeclareTimer FTM_CLEANUP_DRAWABLE("Cleanup Drawable");
+static LLFastTimer::DeclareTimer FTM_DEREF_DRAWABLE("Deref");
+static LLFastTimer::DeclareTimer FTM_DELETE_FACES("Faces");
+
void LLDrawable::cleanupReferences()
{
- LLFastTimer t(FTM_PIPELINE);
+ LLFastTimer t(FTM_CLEANUP_DRAWABLE);
- std::for_each(mFaces.begin(), mFaces.end(), DeletePointer());
- mFaces.clear();
+ {
+ LLFastTimer t(FTM_DELETE_FACES);
+ std::for_each(mFaces.begin(), mFaces.end(), DeletePointer());
+ mFaces.clear();
+ }
gObjectList.removeDrawable(this);
gPipeline.unlinkDrawable(this);
- // Cleanup references to other objects
- mVObjp = NULL;
- mParent = NULL;
+ {
+ LLFastTimer t(FTM_DEREF_DRAWABLE);
+ // Cleanup references to other objects
+ mVObjp = NULL;
+ mParent = NULL;
+ }
}
void LLDrawable::cleanupDeadDrawables()
@@ -685,13 +708,15 @@ void LLDrawable::updateDistance(LLCamera& camera, bool force_update)
LLVOVolume* volume = getVOVolume();
if (volume)
{
- volume->updateRelativeXform();
- pos = volume->getRelativeXform().getTranslation();
- if (isStatic())
+ if (getSpatialGroup())
{
- pos += volume->getRegion()->getOriginAgent();
+ pos.set(getPositionGroup().getF32ptr());
}
-
+ else
+ {
+ pos = getPositionAgent();
+ }
+
if (isState(LLDrawable::HAS_ALPHA))
{
for (S32 i = 0; i < getNumFaces(); i++)
@@ -699,21 +724,23 @@ void LLDrawable::updateDistance(LLCamera& camera, bool force_update)
LLFace* facep = getFace(i);
if (force_update || facep->getPoolType() == LLDrawPool::POOL_ALPHA)
{
- LLVector3 box = (facep->mExtents[1] - facep->mExtents[0]) * 0.25f;
+ LLVector4a box;
+ box.setSub(facep->mExtents[1], facep->mExtents[0]);
+ box.mul(0.25f);
LLVector3 v = (facep->mCenterLocal-camera.getOrigin());
const LLVector3& at = camera.getAtAxis();
for (U32 j = 0; j < 3; j++)
{
- v.mV[j] -= box.mV[j] * at.mV[j];
+ v.mV[j] -= box[j] * at.mV[j];
}
facep->mDistance = v * camera.getAtAxis();
}
}
- }
+ }
}
else
{
- pos = LLVector3(getPositionGroup());
+ pos = LLVector3(getPositionGroup().getF32ptr());
}
pos -= camera.getOrigin();
@@ -739,7 +766,7 @@ void LLDrawable::updateTexture()
if (getVOVolume())
{
- if (isActive())
+ /*if (isActive())
{
if (isRoot())
{
@@ -749,7 +776,7 @@ void LLDrawable::updateTexture()
{
getParent()->mQuietCount = 0;
}
- }
+ }*/
gPipeline.markRebuild(this, LLDrawable::REBUILD_MATERIAL, TRUE);
}
@@ -762,7 +789,7 @@ BOOL LLDrawable::updateGeometry(BOOL priority)
return res;
}
-void LLDrawable::shiftPos(const LLVector3 &shift_vector)
+void LLDrawable::shiftPos(const LLVector4a &shift_vector)
{
if (isDead())
{
@@ -794,20 +821,19 @@ void LLDrawable::shiftPos(const LLVector3 &shift_vector)
for (S32 i = 0; i < getNumFaces(); i++)
{
LLFace *facep = getFace(i);
- facep->mCenterAgent += shift_vector;
- facep->mExtents[0] += shift_vector;
- facep->mExtents[1] += shift_vector;
+ facep->mCenterAgent += LLVector3(shift_vector.getF32ptr());
+ facep->mExtents[0].add(shift_vector);
+ facep->mExtents[1].add(shift_vector);
if (!volume && facep->hasGeometry())
{
- facep->mVertexBuffer = NULL;
- facep->mLastVertexBuffer = NULL;
+ facep->clearVertexBuffer();
}
}
- mExtents[0] += shift_vector;
- mExtents[1] += shift_vector;
- mPositionGroup += LLVector3d(shift_vector);
+ mExtents[0].add(shift_vector);
+ mExtents[1].add(shift_vector);
+ mPositionGroup.add(shift_vector);
}
else if (mSpatialBridge)
{
@@ -815,9 +841,9 @@ void LLDrawable::shiftPos(const LLVector3 &shift_vector)
}
else if (isAvatar())
{
- mExtents[0] += shift_vector;
- mExtents[1] += shift_vector;
- mPositionGroup += LLVector3d(shift_vector);
+ mExtents[0].add(shift_vector);
+ mExtents[1].add(shift_vector);
+ mPositionGroup.add(shift_vector);
}
mVObjp->onShift(shift_vector);
@@ -829,21 +855,26 @@ const LLVector3& LLDrawable::getBounds(LLVector3& min, LLVector3& max) const
return mXform.getPositionW();
}
-const LLVector3* LLDrawable::getSpatialExtents() const
+const LLVector4a* LLDrawable::getSpatialExtents() const
{
return mExtents;
}
-void LLDrawable::setSpatialExtents(LLVector3 min, LLVector3 max)
+void LLDrawable::setSpatialExtents(const LLVector3& min, const LLVector3& max)
+{
+ mExtents[0].load3(min.mV);
+ mExtents[1].load3(max.mV);
+}
+
+void LLDrawable::setSpatialExtents(const LLVector4a& min, const LLVector4a& max)
{
- LLVector3 size = max - min;
mExtents[0] = min;
- mExtents[1] = max;
+ mExtents[1] = max;
}
-void LLDrawable::setPositionGroup(const LLVector3d& pos)
+void LLDrawable::setPositionGroup(const LLVector4a& pos)
{
- mPositionGroup.setVec(pos);
+ mPositionGroup = pos;
}
void LLDrawable::updateSpatialExtents()
@@ -857,7 +888,7 @@ void LLDrawable::updateSpatialExtents()
if (mSpatialBridge.notNull())
{
- mPositionGroup.setVec(0,0,0);
+ mPositionGroup.splat(0.f);
}
}
@@ -910,6 +941,18 @@ void LLDrawable::setSpatialGroup(LLSpatialGroup *groupp)
{
mSpatialGroupp->setState(LLSpatialGroup::GEOM_DIRTY);
}*/
+
+ if (mSpatialGroupp != groupp && getVOVolume())
+ { //NULL out vertex buffer references for volumes on spatial group change to maintain
+ //requirement that every face vertex buffer is either NULL or points to a vertex buffer
+ //contained by its drawable's spatial group
+ for (S32 i = 0; i < getNumFaces(); ++i)
+ {
+ LLFace* facep = getFace(i);
+ facep->clearVertexBuffer();
+ }
+ }
+
mSpatialGroupp = groupp;
}
@@ -1027,7 +1070,7 @@ BOOL LLDrawable::isVisible() const
//=======================================
LLSpatialBridge::LLSpatialBridge(LLDrawable* root, BOOL render_by_group, U32 data_mask)
-: LLSpatialPartition(data_mask, render_by_group, FALSE)
+: LLSpatialPartition(data_mask, render_by_group, GL_STREAM_DRAW_ARB)
{
mDrawable = root;
root->setSpatialBridge(this);
@@ -1068,59 +1111,72 @@ void LLSpatialBridge::updateSpatialExtents()
root->rebound();
}
- LLXformMatrix* mat = mDrawable->getXform();
-
- LLVector3 offset = root->mBounds[0];
- LLVector3 size = root->mBounds[1];
+ LLVector4a offset;
+ LLVector4a size = root->mBounds[1];
- LLVector3 center = LLVector3(0,0,0) * mat->getWorldMatrix();
- LLQuaternion rotation = LLQuaternion(mat->getWorldMatrix());
+ //VECTORIZE THIS
+ LLMatrix4a mat;
+ mat.loadu(mDrawable->getXform()->getWorldMatrix());
+
+ LLVector4a t;
+ t.splat(0.f);
+
+ LLVector4a center;
+ mat.affineTransform(t, center);
- offset *= rotation;
- center += offset;
+ mat.rotate(root->mBounds[0], offset);
+ center.add(offset);
- LLVector3 v[4];
+ LLVector4a v[4];
+
//get 4 corners of bounding box
- v[0] = (size * rotation);
- v[1] = (LLVector3(-size.mV[0], -size.mV[1], size.mV[2]) * rotation);
- v[2] = (LLVector3(size.mV[0], -size.mV[1], -size.mV[2]) * rotation);
- v[3] = (LLVector3(-size.mV[0], size.mV[1], -size.mV[2]) * rotation);
+ mat.rotate(size,v[0]);
- LLVector3& newMin = mExtents[0];
- LLVector3& newMax = mExtents[1];
+ LLVector4a scale;
+
+ scale.set(-1.f, -1.f, 1.f);
+ scale.mul(size);
+ mat.rotate(scale, v[1]);
+
+ scale.set(1.f, -1.f, -1.f);
+ scale.mul(size);
+ mat.rotate(scale, v[2]);
+
+ scale.set(-1.f, 1.f, -1.f);
+ scale.mul(size);
+ mat.rotate(scale, v[3]);
+
+
+ LLVector4a& newMin = mExtents[0];
+ LLVector4a& newMax = mExtents[1];
newMin = newMax = center;
for (U32 i = 0; i < 4; i++)
{
- for (U32 j = 0; j < 3; j++)
- {
- F32 delta = fabsf(v[i].mV[j]);
- F32 min = center.mV[j] - delta;
- F32 max = center.mV[j] + delta;
-
- if (min < newMin.mV[j])
- {
- newMin.mV[j] = min;
- }
-
- if (max > newMax.mV[j])
- {
- newMax.mV[j] = max;
- }
- }
- }
+ LLVector4a delta;
+ delta.setAbs(v[i]);
+ LLVector4a min;
+ min.setSub(center, delta);
+ LLVector4a max;
+ max.setAdd(center, delta);
- LLVector3 diagonal = newMax - newMin;
- mRadius = diagonal.magVec() * 0.5f;
+ newMin.setMin(newMin, min);
+ newMax.setMax(newMax, max);
+ }
+
+ LLVector4a diagonal;
+ diagonal.setSub(newMax, newMin);
+ mRadius = diagonal.getLength3().getF32() * 0.5f;
- mPositionGroup.setVec((newMin + newMax) * 0.5f);
+ mPositionGroup.setAdd(newMin,newMax);
+ mPositionGroup.mul(0.5f);
updateBinRadius();
}
void LLSpatialBridge::updateBinRadius()
{
- mBinRadius = llmin((F32) mOctree->getSize().mdV[0]*0.5f, 256.f);
+ mBinRadius = llmin( mOctree->getSize()[0]*0.5f, 256.f);
}
LLCamera LLSpatialBridge::transformCamera(LLCamera& camera)
@@ -1261,8 +1317,12 @@ void LLSpatialBridge::setVisible(LLCamera& camera_in, std::vector<LLDrawable*>*
LLSpatialGroup* group = (LLSpatialGroup*) mOctree->getListener(0);
group->rebound();
- LLVector3 center = (mExtents[0] + mExtents[1]) * 0.5f;
- LLVector3 size = (mExtents[1]-mExtents[0]) * 0.5f;
+ LLVector4a center;
+ center.setAdd(mExtents[0], mExtents[1]);
+ center.mul(0.5f);
+ LLVector4a size;
+ size.setSub(mExtents[1], mExtents[0]);
+ size.mul(0.5f);
if ((LLPipeline::sShadowRender && camera_in.AABBInFrustum(center, size)) ||
LLPipeline::sImpostorRender ||
@@ -1375,11 +1435,11 @@ BOOL LLSpatialBridge::updateMove()
return TRUE;
}
-void LLSpatialBridge::shiftPos(const LLVector3& vec)
+void LLSpatialBridge::shiftPos(const LLVector4a& vec)
{
- mExtents[0] += vec;
- mExtents[1] += vec;
- mPositionGroup += LLVector3d(vec);
+ mExtents[0].add(vec);
+ mExtents[1].add(vec);
+ mPositionGroup.add(vec);
}
void LLSpatialBridge::cleanupReferences()
@@ -1497,7 +1557,7 @@ F32 LLHUDBridge::calcPixelArea(LLSpatialGroup* group, LLCamera& camera)
}
-void LLHUDBridge::shiftPos(const LLVector3& vec)
+void LLHUDBridge::shiftPos(const LLVector4a& vec)
{
//don't shift hud bridges on region crossing
}
diff --git a/indra/newview/lldrawable.h b/indra/newview/lldrawable.h
index 2cea41df0a..9ebe1a45b4 100644
--- a/indra/newview/lldrawable.h
+++ b/indra/newview/lldrawable.h
@@ -35,6 +35,7 @@
#include "v4math.h"
#include "m4math.h"
#include "v4coloru.h"
+#include "llvector4a.h"
#include "llquaternion.h"
#include "xform.h"
#include "llmemtype.h"
@@ -61,6 +62,17 @@ const U32 SILHOUETTE_HIGHLIGHT = 0;
class LLDrawable : public LLRefCount
{
public:
+ LLDrawable(const LLDrawable& rhs)
+ {
+ *this = rhs;
+ }
+
+ const LLDrawable& operator=(const LLDrawable& rhs)
+ {
+ llerrs << "Illegal operation!" << llendl;
+ return *this;
+ }
+
static void initClass();
LLDrawable() { init(); }
@@ -84,19 +96,19 @@ public:
LLVOVolume* getVOVolume() const; // cast mVObjp tp LLVOVolume if OK
const LLMatrix4& getWorldMatrix() const { return mXform.getWorldMatrix(); }
- const LLMatrix4& getRenderMatrix() const { return isRoot() ? getWorldMatrix() : getParent()->getWorldMatrix(); }
+ const LLMatrix4& getRenderMatrix() const;
void setPosition(LLVector3 v) const { }
const LLVector3& getPosition() const { return mXform.getPosition(); }
const LLVector3& getWorldPosition() const { return mXform.getPositionW(); }
const LLVector3 getPositionAgent() const;
- const LLVector3d& getPositionGroup() const { return mPositionGroup; }
+ const LLVector4a& getPositionGroup() const { return mPositionGroup; }
const LLVector3& getScale() const { return mCurrentScale; }
void setScale(const LLVector3& scale) { mCurrentScale = scale; }
const LLQuaternion& getWorldRotation() const { return mXform.getWorldRotation(); }
const LLQuaternion& getRotation() const { return mXform.getRotation(); }
F32 getIntensity() const { return llmin(mXform.getScale().mV[0], 4.f); }
S32 getLOD() const { return mVObjp ? mVObjp->getLOD() : 1; }
- F64 getBinRadius() const { return mBinRadius; }
+ F32 getBinRadius() const { return mBinRadius; }
void getMinMax(LLVector3& min,LLVector3& max) const { mXform.getMinMax(min,max); }
LLXformMatrix* getXform() { return &mXform; }
@@ -150,7 +162,7 @@ public:
void updateSpecialHoverCursor(BOOL enabled);
- virtual void shiftPos(const LLVector3 &shift_vector);
+ virtual void shiftPos(const LLVector4a &shift_vector);
S32 getGeneration() const { return mGeneration; }
@@ -168,11 +180,12 @@ public:
const LLVector3& getBounds(LLVector3& min, LLVector3& max) const;
virtual void updateSpatialExtents();
virtual void updateBinRadius();
- const LLVector3* getSpatialExtents() const;
- void setSpatialExtents(LLVector3 min, LLVector3 max);
- void setPositionGroup(const LLVector3d& pos);
- void setPositionGroup(const LLVector3& pos) { setPositionGroup(LLVector3d(pos)); }
+ const LLVector4a* getSpatialExtents() const;
+ void setSpatialExtents(const LLVector3& min, const LLVector3& max);
+ void setSpatialExtents(const LLVector4a& min, const LLVector4a& max);
+ void setPositionGroup(const LLVector4a& pos);
+
void setRenderType(S32 type) { mRenderType = type; }
BOOL isRenderType(S32 type) { return mRenderType == type; }
S32 getRenderType() { return mRenderType; }
@@ -232,37 +245,44 @@ public:
typedef enum e_drawable_flags
{
- IN_REBUILD_Q1 = 0x00000002,
- IN_REBUILD_Q2 = 0x00000004,
- IN_LIGHT_Q = 0x00000008,
- EARLY_MOVE = 0x00000010,
- MOVE_UNDAMPED = 0x00000020,
- ON_MOVE_LIST = 0x00000040,
- USE_BACKLIGHT = 0x00000080,
- UV = 0x00000100,
- UNLIT = 0x00000200,
- LIGHT = 0x00000400,
- LIGHTING_BUILT = 0x00000800,
- REBUILD_VOLUME = 0x00001000, //volume changed LOD or parameters, or vertex buffer changed
- REBUILD_TCOORD = 0x00002000, //texture coordinates changed
- REBUILD_COLOR = 0x00004000, //color changed
- REBUILD_POSITION= 0x00010000, //vertex positions/normals changed
+ IN_REBUILD_Q1 = 0x00000001,
+ IN_REBUILD_Q2 = 0x00000002,
+ IN_LIGHT_Q = 0x00000004,
+ EARLY_MOVE = 0x00000008,
+ MOVE_UNDAMPED = 0x00000010,
+ ON_MOVE_LIST = 0x00000020,
+ USE_BACKLIGHT = 0x00000040,
+ UV = 0x00000080,
+ UNLIT = 0x00000100,
+ LIGHT = 0x00000200,
+ LIGHTING_BUILT = 0x00000400,
+ REBUILD_VOLUME = 0x00000800, //volume changed LOD or parameters, or vertex buffer changed
+ REBUILD_TCOORD = 0x00001000, //texture coordinates changed
+ REBUILD_COLOR = 0x00002000, //color changed
+ REBUILD_POSITION= 0x00004000, //vertex positions/normals changed
REBUILD_GEOMETRY= REBUILD_POSITION|REBUILD_TCOORD|REBUILD_COLOR,
REBUILD_MATERIAL= REBUILD_TCOORD|REBUILD_COLOR,
REBUILD_ALL = REBUILD_GEOMETRY|REBUILD_VOLUME,
- ON_SHIFT_LIST = 0x00100000,
- BLOCKER = 0x00400000,
- ACTIVE = 0x00800000,
- DEAD = 0x01000000,
- INVISIBLE = 0x02000000, // stay invisible until flag is cleared
- NEARBY_LIGHT = 0x04000000, // In gPipeline.mNearbyLightSet
- BUILT = 0x08000000,
- FORCE_INVISIBLE = 0x10000000, // stay invis until CLEAR_INVISIBLE is set (set of orphaned)
- CLEAR_INVISIBLE = 0x20000000, // clear FORCE_INVISIBLE next draw frame
- REBUILD_SHADOW = 0x40000000,
- HAS_ALPHA = 0x80000000,
+ REBUILD_RIGGED = 0x00008000,
+ ON_SHIFT_LIST = 0x00010000,
+ BLOCKER = 0x00020000,
+ ACTIVE = 0x00040000,
+ DEAD = 0x00080000,
+ INVISIBLE = 0x00100000, // stay invisible until flag is cleared
+ NEARBY_LIGHT = 0x00200000, // In gPipeline.mNearbyLightSet
+ BUILT = 0x00400000,
+ FORCE_INVISIBLE = 0x00800000, // stay invis until CLEAR_INVISIBLE is set (set of orphaned)
+ CLEAR_INVISIBLE = 0x01000000, // clear FORCE_INVISIBLE next draw frame
+ REBUILD_SHADOW = 0x02000000,
+ HAS_ALPHA = 0x04000000,
+ RIGGED = 0x08000000,
} EDrawableFlags;
+private: //aligned members
+ LLVector4a mExtents[2];
+ LLVector4a mPositionGroup;
+
+public:
LLXformMatrix mXform;
// vis data
@@ -292,9 +312,7 @@ private:
mutable U32 mVisible;
F32 mRadius;
- LLVector3 mExtents[2];
- LLVector3d mPositionGroup;
- F64 mBinRadius;
+ F32 mBinRadius;
S32 mGeneration;
LLVector3 mCurrentScale;
diff --git a/indra/newview/lldrawpool.cpp b/indra/newview/lldrawpool.cpp
index ba576ff97f..25e4bc847c 100644
--- a/indra/newview/lldrawpool.cpp
+++ b/indra/newview/lldrawpool.cpp
@@ -243,11 +243,6 @@ void LLFacePool::dirtyTextures(const std::set<LLViewerFetchedTexture*>& textures
{
}
-BOOL LLFacePool::moveFace(LLFace *face, LLDrawPool *poolp, BOOL copy_data)
-{
- return TRUE;
-}
-
// static
S32 LLFacePool::drawLoop(face_array_t& face_list)
{
diff --git a/indra/newview/lldrawpool.h b/indra/newview/lldrawpool.h
index 1d6f99d346..d3fd9ead0d 100644
--- a/indra/newview/lldrawpool.h
+++ b/indra/newview/lldrawpool.h
@@ -47,14 +47,14 @@ public:
{
// Correspond to LLPipeline render type
POOL_SIMPLE = 1,
+ POOL_GROUND,
+ POOL_FULLBRIGHT,
+ POOL_BUMP,
POOL_TERRAIN,
- POOL_TREE,
POOL_SKY,
POOL_WL_SKY,
- POOL_GROUND,
+ POOL_TREE,
POOL_GRASS,
- POOL_FULLBRIGHT,
- POOL_BUMP,
POOL_INVISIBLE, // see below *
POOL_AVATAR,
POOL_VOIDWATER,
@@ -182,8 +182,6 @@ public:
virtual void resetDrawOrders();
void resetAll();
- BOOL moveFace(LLFace *face, LLDrawPool *poolp, BOOL copy_data = FALSE);
-
void destroy();
void buildEdges();
diff --git a/indra/newview/lldrawpoolalpha.cpp b/indra/newview/lldrawpoolalpha.cpp
index a2428d2de0..a2a109d5ee 100644
--- a/indra/newview/lldrawpoolalpha.cpp
+++ b/indra/newview/lldrawpoolalpha.cpp
@@ -103,16 +103,36 @@ void LLDrawPoolAlpha::renderDeferred(S32 pass)
S32 LLDrawPoolAlpha::getNumPostDeferredPasses()
{
- return 1;
+ if (LLPipeline::sImpostorRender)
+ { //skip depth buffer filling pass when rendering impostors
+ return 1;
+ }
+ else
+ {
+ return 2;
+ }
}
void LLDrawPoolAlpha::beginPostDeferredPass(S32 pass)
{
LLFastTimer t(FTM_RENDER_ALPHA);
- simple_shader = &gDeferredAlphaProgram;
- fullbright_shader = &gDeferredFullbrightProgram;
-
+ if (pass == 0)
+ {
+ simple_shader = &gDeferredAlphaProgram;
+ fullbright_shader = &gDeferredFullbrightProgram;
+ }
+ else
+ {
+ //update depth buffer sampler
+ gPipeline.mScreen.flush();
+ gPipeline.mDeferredDepth.copyContents(gPipeline.mDeferredScreen, 0, 0, gPipeline.mDeferredScreen.getWidth(), gPipeline.mDeferredScreen.getHeight(),
+ 0, 0, gPipeline.mDeferredDepth.getWidth(), gPipeline.mDeferredDepth.getHeight(), GL_DEPTH_BUFFER_BIT, GL_NEAREST);
+ gPipeline.mDeferredDepth.bindTarget();
+ simple_shader = NULL;
+ fullbright_shader = NULL;
+ }
+
deferred_render = TRUE;
if (mVertexShaderLevel > 0)
{
@@ -124,6 +144,13 @@ void LLDrawPoolAlpha::beginPostDeferredPass(S32 pass)
void LLDrawPoolAlpha::endPostDeferredPass(S32 pass)
{
+
+ if (pass == 1)
+ {
+ gPipeline.mDeferredDepth.flush();
+ gPipeline.mScreen.bindTarget();
+ }
+
deferred_render = FALSE;
endRenderPass(pass);
}
@@ -174,7 +201,14 @@ void LLDrawPoolAlpha::render(S32 pass)
LLGLSPipelineAlpha gls_pipeline_alpha;
- gGL.setColorMask(true, true);
+ if (deferred_render && pass == 1)
+ { //depth only
+ gGL.setColorMask(false, false);
+ }
+ else
+ {
+ gGL.setColorMask(true, true);
+ }
if (LLPipeline::sAutoMaskAlphaNonDeferred && !deferred_render)
{
@@ -206,18 +240,41 @@ void LLDrawPoolAlpha::render(S32 pass)
gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
}
- LLGLDepthTest depth(GL_TRUE, LLDrawPoolWater::sSkipScreenCopy ? GL_TRUE : GL_FALSE);
+ LLGLDepthTest depth(GL_TRUE, LLDrawPoolWater::sSkipScreenCopy ||
+ (deferred_render && pass == 1) ? GL_TRUE : GL_FALSE);
- mColorSFactor = LLRender::BF_SOURCE_ALPHA; // } regular alpha blend
- mColorDFactor = LLRender::BF_ONE_MINUS_SOURCE_ALPHA; // }
- mAlphaSFactor = LLRender::BF_ZERO; // } glow suppression
- mAlphaDFactor = LLRender::BF_ONE_MINUS_SOURCE_ALPHA; // }
- gGL.blendFunc(mColorSFactor, mColorDFactor, mAlphaSFactor, mAlphaDFactor);
+ if (deferred_render && pass == 1)
+ {
+ gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.33f);
+ gGL.blendFunc(LLRender::BF_SOURCE_ALPHA, LLRender::BF_ONE_MINUS_SOURCE_ALPHA);
+ }
+ else
+ {
+ mColorSFactor = LLRender::BF_SOURCE_ALPHA; // } regular alpha blend
+ mColorDFactor = LLRender::BF_ONE_MINUS_SOURCE_ALPHA; // }
+ mAlphaSFactor = LLRender::BF_ZERO; // } glow suppression
+ mAlphaDFactor = LLRender::BF_ONE_MINUS_SOURCE_ALPHA; // }
+ gGL.blendFunc(mColorSFactor, mColorDFactor, mAlphaSFactor, mAlphaDFactor);
+
+ if (LLPipeline::sImpostorRender)
+ {
+ gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);
+ }
+ else
+ {
+ gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
+ }
+ }
renderAlpha(getVertexDataMask());
gGL.setColorMask(true, false);
+ if (deferred_render && pass == 1)
+ {
+ gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
+ }
+
if (deferred_render && current_shader != NULL)
{
gPipeline.unbindDeferredShader(*current_shader);
@@ -276,22 +333,10 @@ void LLDrawPoolAlpha::renderAlpha(U32 mask)
BOOL light_enabled = TRUE;
S32 diffuse_channel = 0;
- //BOOL is_particle = FALSE;
BOOL use_shaders = (LLPipeline::sUnderWaterRender && gPipeline.canUseVertexShaders())
|| gPipeline.canUseWindLightShadersOnObjects();
- // check to see if it's a particle and if it's "close"
- {
- if (LLPipeline::sImpostorRender)
- {
- gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);
- }
- else
- {
- gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
- }
- }
-
+
for (LLCullResult::sg_list_t::iterator i = gPipeline.beginAlphaGroups(); i != gPipeline.endAlphaGroups(); ++i)
{
LLSpatialGroup* group = *i;
diff --git a/indra/newview/lldrawpoolavatar.cpp b/indra/newview/lldrawpoolavatar.cpp
index dbd5da31a6..645c7ebcae 100644
--- a/indra/newview/lldrawpoolavatar.cpp
+++ b/indra/newview/lldrawpoolavatar.cpp
@@ -31,15 +31,21 @@
#include "llvoavatar.h"
#include "m3math.h"
+#include "llmatrix4a.h"
+#include "llagent.h" //for gAgent.needsRenderAvatar()
#include "lldrawable.h"
+#include "lldrawpoolbump.h"
#include "llface.h"
+#include "llmeshrepository.h"
#include "llsky.h"
#include "llviewercamera.h"
#include "llviewerregion.h"
#include "noise.h"
#include "pipeline.h"
#include "llviewershadermgr.h"
+#include "llvovolume.h"
+#include "llvolume.h"
#include "llappviewer.h"
#include "llrendersphere.h"
#include "llviewerpartsim.h"
@@ -47,10 +53,15 @@
static U32 sDataMask = LLDrawPoolAvatar::VERTEX_DATA_MASK;
static U32 sBufferUsage = GL_STREAM_DRAW_ARB;
static U32 sShaderLevel = 0;
-static LLGLSLShader* sVertexProgram = NULL;
+
+LLGLSLShader* LLDrawPoolAvatar::sVertexProgram = NULL;
BOOL LLDrawPoolAvatar::sSkipOpaque = FALSE;
BOOL LLDrawPoolAvatar::sSkipTransparent = FALSE;
+S32 LLDrawPoolAvatar::sDiffuseChannel = 0;
+
+
+static bool is_deferred_render = false;
extern BOOL gUseGLPick;
@@ -86,7 +97,7 @@ BOOL gAvatarEmbossBumpMap = FALSE;
static BOOL sRenderingSkinned = FALSE;
S32 normal_channel = -1;
S32 specular_channel = -1;
-S32 diffuse_channel = -1;
+S32 cube_channel = -1;
static LLFastTimer::DeclareTimer FTM_SHADOW_AVATAR("Avatar Shadow");
@@ -142,21 +153,17 @@ LLMatrix4& LLDrawPoolAvatar::getModelView()
//-----------------------------------------------------------------------------
-S32 LLDrawPoolAvatar::getNumDeferredPasses()
-{
- return getNumPasses();
-}
void LLDrawPoolAvatar::beginDeferredPass(S32 pass)
{
LLFastTimer t(FTM_RENDER_CHARACTERS);
sSkipTransparent = TRUE;
-
+ is_deferred_render = true;
+
if (LLPipeline::sImpostorRender)
- {
- beginDeferredSkinned();
- return;
+ { //impostor pass does not have rigid or impostor rendering
+ pass += 2;
}
switch (pass)
@@ -170,6 +177,12 @@ void LLDrawPoolAvatar::beginDeferredPass(S32 pass)
case 2:
beginDeferredSkinned();
break;
+ case 3:
+ beginDeferredRiggedSimple();
+ break;
+ case 4:
+ beginDeferredRiggedBump();
+ break;
}
}
@@ -178,11 +191,11 @@ void LLDrawPoolAvatar::endDeferredPass(S32 pass)
LLFastTimer t(FTM_RENDER_CHARACTERS);
sSkipTransparent = FALSE;
+ is_deferred_render = false;
if (LLPipeline::sImpostorRender)
{
- endDeferredSkinned();
- return;
+ pass += 2;
}
switch (pass)
@@ -196,6 +209,12 @@ void LLDrawPoolAvatar::endDeferredPass(S32 pass)
case 2:
endDeferredSkinned();
break;
+ case 3:
+ endDeferredRiggedSimple();
+ break;
+ case 4:
+ endDeferredRiggedBump();
+ break;
}
}
@@ -206,11 +225,36 @@ void LLDrawPoolAvatar::renderDeferred(S32 pass)
S32 LLDrawPoolAvatar::getNumPostDeferredPasses()
{
- return 1;
+ return 6;
}
void LLDrawPoolAvatar::beginPostDeferredPass(S32 pass)
{
+ switch (pass)
+ {
+ case 0:
+ beginPostDeferredAlpha();
+ break;
+ case 1:
+ beginRiggedFullbright();
+ break;
+ case 2:
+ beginRiggedFullbrightShiny();
+ break;
+ case 3:
+ beginDeferredRiggedAlpha();
+ break;
+ case 4:
+ beginRiggedFullbrightAlpha();
+ break;
+ case 5:
+ beginRiggedGlow();
+ break;
+ }
+}
+
+void LLDrawPoolAvatar::beginPostDeferredAlpha()
+{
sSkipOpaque = TRUE;
sShaderLevel = mVertexShaderLevel;
sVertexProgram = &gDeferredAvatarAlphaProgram;
@@ -219,64 +263,143 @@ void LLDrawPoolAvatar::beginPostDeferredPass(S32 pass)
gPipeline.bindDeferredShader(*sVertexProgram);
+ sDiffuseChannel = sVertexProgram->enableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
enable_vertex_weighting(sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_WEIGHT]);
}
+void LLDrawPoolAvatar::beginDeferredRiggedAlpha()
+{
+ sVertexProgram = &gDeferredSkinnedAlphaProgram;
+ gPipeline.bindDeferredShader(*sVertexProgram);
+ sDiffuseChannel = sVertexProgram->enableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
+ LLVertexBuffer::sWeight4Loc = sVertexProgram->getAttribLocation(LLViewerShaderMgr::OBJECT_WEIGHT);
+ gPipeline.enableLightsDynamic();
+}
+
+void LLDrawPoolAvatar::endDeferredRiggedAlpha()
+{
+ LLVertexBuffer::unbind();
+ gPipeline.unbindDeferredShader(*sVertexProgram);
+ sDiffuseChannel = 0;
+ LLVertexBuffer::sWeight4Loc = -1;
+ sVertexProgram = NULL;
+}
+
void LLDrawPoolAvatar::endPostDeferredPass(S32 pass)
{
+ switch (pass)
+ {
+ case 0:
+ endPostDeferredAlpha();
+ break;
+ case 1:
+ endRiggedFullbright();
+ break;
+ case 2:
+ endRiggedFullbrightShiny();
+ break;
+ case 3:
+ endDeferredRiggedAlpha();
+ break;
+ case 4:
+ endRiggedFullbrightAlpha();
+ break;
+ case 5:
+ endRiggedGlow();
+ break;
+ }
+}
+
+void LLDrawPoolAvatar::endPostDeferredAlpha()
+{
// if we're in software-blending, remember to set the fence _after_ we draw so we wait till this rendering is done
sRenderingSkinned = FALSE;
sSkipOpaque = FALSE;
disable_vertex_weighting(sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_WEIGHT]);
gPipeline.unbindDeferredShader(*sVertexProgram);
-
+ sDiffuseChannel = 0;
sShaderLevel = mVertexShaderLevel;
}
void LLDrawPoolAvatar::renderPostDeferred(S32 pass)
{
- render(2); //pass 2 = skinned
+ const S32 actual_pass[] =
+ { //map post deferred pass numbers to what render() expects
+ 2, //skinned
+ 4, // rigged fullbright
+ 6, //rigged fullbright shiny
+ 7, //rigged alpha
+ 8, //rigged fullbright alpha
+ 9, //rigged glow
+ };
+
+ pass = actual_pass[pass];
+
+ if (LLPipeline::sImpostorRender)
+ { //HACK for impostors so actual pass ends up being proper pass
+ pass -= 2;
+ }
+
+ render(pass);
}
S32 LLDrawPoolAvatar::getNumShadowPasses()
{
- return 1;
+ return 2;
}
void LLDrawPoolAvatar::beginShadowPass(S32 pass)
{
LLFastTimer t(FTM_SHADOW_AVATAR);
- sVertexProgram = &gDeferredAvatarShadowProgram;
- if (sShaderLevel > 0)
+
+ if (pass == 0)
{
- gAvatarMatrixParam = sVertexProgram->mUniform[LLViewerShaderMgr::AVATAR_MATRIX];
- }
- gGL.setAlphaRejectSettings(LLRender::CF_GREATER_EQUAL, 0.2f);
-
- glColor4f(1,1,1,1);
+ sVertexProgram = &gDeferredAvatarShadowProgram;
+ if (sShaderLevel > 0)
+ {
+ gAvatarMatrixParam = sVertexProgram->mUniform[LLViewerShaderMgr::AVATAR_MATRIX];
+ }
+ gGL.setAlphaRejectSettings(LLRender::CF_GREATER_EQUAL, 0.2f);
+
+ glColor4f(1,1,1,1);
- if ((sShaderLevel > 0)) // for hardware blending
+ if ((sShaderLevel > 0)) // for hardware blending
+ {
+ sRenderingSkinned = TRUE;
+ sVertexProgram->bind();
+ enable_vertex_weighting(sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_WEIGHT]);
+ }
+ }
+ else
{
- sRenderingSkinned = TRUE;
+ sVertexProgram = &gDeferredAttachmentShadowProgram;
+ sDiffuseChannel = sVertexProgram->enableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
sVertexProgram->bind();
- enable_vertex_weighting(sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_WEIGHT]);
+ LLVertexBuffer::sWeight4Loc = sVertexProgram->getAttribLocation(LLViewerShaderMgr::OBJECT_WEIGHT);
}
-
}
void LLDrawPoolAvatar::endShadowPass(S32 pass)
{
LLFastTimer t(FTM_SHADOW_AVATAR);
- if (sShaderLevel > 0)
+ if (pass == 0)
{
- sRenderingSkinned = FALSE;
+ if (sShaderLevel > 0)
+ {
+ sRenderingSkinned = FALSE;
+ sVertexProgram->unbind();
+ disable_vertex_weighting(sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_WEIGHT]);
+ }
+ }
+ else
+ {
+ LLVertexBuffer::unbind();
sVertexProgram->unbind();
- disable_vertex_weighting(sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_WEIGHT]);
+ LLVertexBuffer::sWeight4Loc = -1;
+ sVertexProgram = NULL;
}
-
- gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
}
void LLDrawPoolAvatar::renderShadow(S32 pass)
@@ -306,26 +429,66 @@ void LLDrawPoolAvatar::renderShadow(S32 pass)
return;
}
- if (sShaderLevel > 0)
+ if (pass == 0)
{
- gAvatarMatrixParam = sVertexProgram->mUniform[LLViewerShaderMgr::AVATAR_MATRIX];
- }
-
- avatarp->renderSkinned(AVATAR_RENDER_PASS_SINGLE);
+ if (sShaderLevel > 0)
+ {
+ gAvatarMatrixParam = sVertexProgram->mUniform[LLViewerShaderMgr::AVATAR_MATRIX];
+ }
+ avatarp->renderSkinned(AVATAR_RENDER_PASS_SINGLE);
+ }
+ else
+ {
+ renderRigged(avatarp, RIGGED_SIMPLE);
+ renderRigged(avatarp, RIGGED_ALPHA);
+ renderRigged(avatarp, RIGGED_FULLBRIGHT);
+ renderRigged(avatarp, RIGGED_FULLBRIGHT_SHINY);
+ renderRigged(avatarp, RIGGED_SHINY);
+ renderRigged(avatarp, RIGGED_FULLBRIGHT_ALPHA);
+ }
}
S32 LLDrawPoolAvatar::getNumPasses()
{
- return LLPipeline::sImpostorRender ? 1 : 3;
+ if (LLPipeline::sImpostorRender)
+ {
+ return 8;
+ }
+ else
+ {
+ return 10;
+ }
+ if (LLPipeline::sImpostorRender)
+ {
+ return 1;
+ }
+ else
+ {
+ return 3;
+ }
+}
+
+
+S32 LLDrawPoolAvatar::getNumDeferredPasses()
+{
+ if (LLPipeline::sImpostorRender)
+ {
+ return 3;
+ }
+ else
+ {
+ return 5;
+ }
}
+
void LLDrawPoolAvatar::render(S32 pass)
{
LLFastTimer t(FTM_RENDER_CHARACTERS);
if (LLPipeline::sImpostorRender)
{
- renderAvatars(NULL, 2);
+ renderAvatars(NULL, pass+2);
return;
}
@@ -338,10 +501,14 @@ void LLDrawPoolAvatar::beginRenderPass(S32 pass)
//reset vertex buffer mappings
LLVertexBuffer::unbind();
+ if (pass == 0)
+ { //make sure no stale colors are left over from a previous render
+ glColor4f(1,1,1,1);
+ }
+
if (LLPipeline::sImpostorRender)
- {
- beginSkinned();
- return;
+ { //impostor render does not have impostors or rigid rendering
+ pass += 2;
}
switch (pass)
@@ -355,6 +522,27 @@ void LLDrawPoolAvatar::beginRenderPass(S32 pass)
case 2:
beginSkinned();
break;
+ case 3:
+ beginRiggedSimple();
+ break;
+ case 4:
+ beginRiggedFullbright();
+ break;
+ case 5:
+ beginRiggedShinySimple();
+ break;
+ case 6:
+ beginRiggedFullbrightShiny();
+ break;
+ case 7:
+ beginRiggedAlpha();
+ break;
+ case 8:
+ beginRiggedFullbrightAlpha();
+ break;
+ case 9:
+ beginRiggedGlow();
+ break;
}
}
@@ -364,8 +552,7 @@ void LLDrawPoolAvatar::endRenderPass(S32 pass)
if (LLPipeline::sImpostorRender)
{
- endSkinned();
- return;
+ pass += 2;
}
switch (pass)
@@ -378,6 +565,28 @@ void LLDrawPoolAvatar::endRenderPass(S32 pass)
break;
case 2:
endSkinned();
+ break;
+ case 3:
+ endRiggedSimple();
+ break;
+ case 4:
+ endRiggedFullbright();
+ break;
+ case 5:
+ endRiggedShinySimple();
+ break;
+ case 6:
+ endRiggedFullbrightShiny();
+ break;
+ case 7:
+ endRiggedAlpha();
+ break;
+ case 8:
+ endRiggedFullbrightAlpha();
+ break;
+ case 9:
+ endRiggedGlow();
+ break;
}
}
@@ -390,7 +599,7 @@ void LLDrawPoolAvatar::beginImpostor()
}
gPipeline.enableLightsFullbright(LLColor4(1,1,1,1));
- diffuse_channel = 0;
+ sDiffuseChannel = 0;
}
void LLDrawPoolAvatar::endImpostor()
@@ -441,9 +650,9 @@ void LLDrawPoolAvatar::beginDeferredImpostor()
sVertexProgram = &gDeferredImpostorProgram;
- normal_channel = sVertexProgram->enableTexture(LLViewerShaderMgr::DEFERRED_NORMAL);
specular_channel = sVertexProgram->enableTexture(LLViewerShaderMgr::SPECULAR_MAP);
- diffuse_channel = sVertexProgram->enableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
+ normal_channel = sVertexProgram->enableTexture(LLViewerShaderMgr::DEFERRED_NORMAL);
+ sDiffuseChannel = sVertexProgram->enableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
sVertexProgram->bind();
}
@@ -563,6 +772,254 @@ void LLDrawPoolAvatar::endSkinned()
gGL.getTexUnit(0)->activate();
}
+void LLDrawPoolAvatar::beginRiggedSimple()
+{
+ if (sShaderLevel > 0)
+ {
+ if (LLPipeline::sUnderWaterRender)
+ {
+ sVertexProgram = &gSkinnedObjectSimpleWaterProgram;
+ }
+ else
+ {
+ sVertexProgram = &gSkinnedObjectSimpleProgram;
+ }
+ }
+ else
+ {
+ if (LLPipeline::sUnderWaterRender)
+ {
+ sVertexProgram = &gObjectSimpleWaterProgram;
+ }
+ else
+ {
+ sVertexProgram = &gObjectSimpleProgram;
+ }
+ }
+
+ if (sShaderLevel > 0 || gPipeline.canUseVertexShaders())
+ {
+ sDiffuseChannel = 0;
+ sVertexProgram->bind();
+ LLVertexBuffer::sWeight4Loc = sVertexProgram->getAttribLocation(LLViewerShaderMgr::OBJECT_WEIGHT);
+ }
+}
+
+void LLDrawPoolAvatar::endRiggedSimple()
+{
+ LLVertexBuffer::unbind();
+ if (sShaderLevel > 0 || gPipeline.canUseVertexShaders())
+ {
+ sVertexProgram->unbind();
+ sVertexProgram = NULL;
+ LLVertexBuffer::sWeight4Loc = -1;
+ }
+}
+
+void LLDrawPoolAvatar::beginRiggedAlpha()
+{
+ beginRiggedSimple();
+}
+
+void LLDrawPoolAvatar::endRiggedAlpha()
+{
+ endRiggedSimple();
+}
+
+
+void LLDrawPoolAvatar::beginRiggedFullbrightAlpha()
+{
+ beginRiggedFullbright();
+}
+
+void LLDrawPoolAvatar::endRiggedFullbrightAlpha()
+{
+ endRiggedFullbright();
+}
+
+void LLDrawPoolAvatar::beginRiggedGlow()
+{
+ beginRiggedFullbright();
+}
+
+void LLDrawPoolAvatar::endRiggedGlow()
+{
+ endRiggedFullbright();
+}
+
+void LLDrawPoolAvatar::beginRiggedFullbright()
+{
+ if (sShaderLevel > 0)
+ {
+ if (LLPipeline::sUnderWaterRender)
+ {
+ sVertexProgram = &gSkinnedObjectFullbrightWaterProgram;
+ }
+ else
+ {
+ sVertexProgram = &gSkinnedObjectFullbrightProgram;
+ }
+ }
+ else
+ {
+ if (LLPipeline::sUnderWaterRender)
+ {
+ sVertexProgram = &gObjectFullbrightWaterProgram;
+ }
+ else
+ {
+ sVertexProgram = &gObjectFullbrightProgram;
+ }
+ }
+
+ if (sShaderLevel > 0 || gPipeline.canUseVertexShaders())
+ {
+ sDiffuseChannel = 0;
+ sVertexProgram->bind();
+ LLVertexBuffer::sWeight4Loc = sVertexProgram->getAttribLocation(LLViewerShaderMgr::OBJECT_WEIGHT);
+ }
+}
+
+void LLDrawPoolAvatar::endRiggedFullbright()
+{
+ LLVertexBuffer::unbind();
+ if (sShaderLevel > 0 || gPipeline.canUseVertexShaders())
+ {
+ sVertexProgram->unbind();
+ sVertexProgram = NULL;
+ LLVertexBuffer::sWeight4Loc = -1;
+ }
+}
+
+void LLDrawPoolAvatar::beginRiggedShinySimple()
+{
+ if (sShaderLevel > 0)
+ {
+ if (LLPipeline::sUnderWaterRender)
+ {
+ sVertexProgram = &gSkinnedObjectShinySimpleWaterProgram;
+ }
+ else
+ {
+ sVertexProgram = &gSkinnedObjectShinySimpleProgram;
+ }
+ }
+ else
+ {
+ if (LLPipeline::sUnderWaterRender)
+ {
+ sVertexProgram = &gObjectShinyWaterProgram;
+ }
+ else
+ {
+ sVertexProgram = &gObjectShinyProgram;
+ }
+ }
+
+ if (sShaderLevel > 0 || gPipeline.canUseVertexShaders())
+ {
+ sVertexProgram->bind();
+ LLDrawPoolBump::bindCubeMap(sVertexProgram, 2, sDiffuseChannel, cube_channel, false);
+ LLVertexBuffer::sWeight4Loc = sVertexProgram->getAttribLocation(LLViewerShaderMgr::OBJECT_WEIGHT);
+ }
+}
+
+void LLDrawPoolAvatar::endRiggedShinySimple()
+{
+ LLVertexBuffer::unbind();
+ if (sShaderLevel > 0 || gPipeline.canUseVertexShaders())
+ {
+ LLDrawPoolBump::unbindCubeMap(sVertexProgram, 2, sDiffuseChannel, cube_channel, false);
+ sVertexProgram->unbind();
+ sVertexProgram = NULL;
+ LLVertexBuffer::sWeight4Loc = -1;
+ }
+}
+
+void LLDrawPoolAvatar::beginRiggedFullbrightShiny()
+{
+ if (sShaderLevel > 0)
+ {
+ if (LLPipeline::sUnderWaterRender)
+ {
+ sVertexProgram = &gSkinnedObjectFullbrightShinyWaterProgram;
+ }
+ else
+ {
+ sVertexProgram = &gSkinnedObjectFullbrightShinyProgram;
+ }
+ }
+ else
+ {
+ if (LLPipeline::sUnderWaterRender)
+ {
+ sVertexProgram = &gObjectFullbrightShinyWaterProgram;
+ }
+ else
+ {
+ sVertexProgram = &gObjectFullbrightShinyProgram;
+ }
+ }
+
+
+ if (sShaderLevel > 0 || gPipeline.canUseVertexShaders())
+ {
+ sVertexProgram->bind();
+ LLDrawPoolBump::bindCubeMap(sVertexProgram, 2, sDiffuseChannel, cube_channel, false);
+ LLVertexBuffer::sWeight4Loc = sVertexProgram->getAttribLocation(LLViewerShaderMgr::OBJECT_WEIGHT);
+ }
+}
+
+void LLDrawPoolAvatar::endRiggedFullbrightShiny()
+{
+ LLVertexBuffer::unbind();
+ if (sShaderLevel > 0 || gPipeline.canUseVertexShaders())
+ {
+ LLDrawPoolBump::unbindCubeMap(sVertexProgram, 2, sDiffuseChannel, cube_channel, false);
+ sVertexProgram->unbind();
+ sVertexProgram = NULL;
+ LLVertexBuffer::sWeight4Loc = -1;
+ }
+}
+
+
+void LLDrawPoolAvatar::beginDeferredRiggedSimple()
+{
+ sVertexProgram = &gDeferredSkinnedDiffuseProgram;
+ sDiffuseChannel = 0;
+ sVertexProgram->bind();
+ LLVertexBuffer::sWeight4Loc = sVertexProgram->getAttribLocation(LLViewerShaderMgr::OBJECT_WEIGHT);
+}
+
+void LLDrawPoolAvatar::endDeferredRiggedSimple()
+{
+ LLVertexBuffer::unbind();
+ sVertexProgram->unbind();
+ LLVertexBuffer::sWeight4Loc = -1;
+ sVertexProgram = NULL;
+}
+
+void LLDrawPoolAvatar::beginDeferredRiggedBump()
+{
+ sVertexProgram = &gDeferredSkinnedBumpProgram;
+ sVertexProgram->bind();
+ normal_channel = sVertexProgram->enableTexture(LLViewerShaderMgr::BUMP_MAP);
+ sDiffuseChannel = sVertexProgram->enableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
+ LLVertexBuffer::sWeight4Loc = sVertexProgram->getAttribLocation(LLViewerShaderMgr::OBJECT_WEIGHT);
+}
+
+void LLDrawPoolAvatar::endDeferredRiggedBump()
+{
+ LLVertexBuffer::unbind();
+ sVertexProgram->disableTexture(LLViewerShaderMgr::BUMP_MAP);
+ sVertexProgram->disableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
+ sVertexProgram->unbind();
+ LLVertexBuffer::sWeight4Loc = -1;
+ normal_channel = -1;
+ sDiffuseChannel = 0;
+ sVertexProgram = NULL;
+}
+
void LLDrawPoolAvatar::beginDeferredSkinned()
{
sShaderLevel = mVertexShaderLevel;
@@ -572,6 +1029,7 @@ void LLDrawPoolAvatar::beginDeferredSkinned()
sVertexProgram->bind();
+ sDiffuseChannel = sVertexProgram->enableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
enable_vertex_weighting(sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_WEIGHT]);
gGL.getTexUnit(0)->activate();
@@ -584,6 +1042,8 @@ void LLDrawPoolAvatar::endDeferredSkinned()
disable_vertex_weighting(sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_WEIGHT]);
sVertexProgram->unbind();
+ sVertexProgram->disableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
+
sShaderLevel = mVertexShaderLevel;
gGL.getTexUnit(0)->activate();
@@ -668,8 +1128,6 @@ void LLDrawPoolAvatar::renderAvatars(LLVOAvatar* single_avatar, S32 pass)
return;
}
- LLOverrideFaceColor color(this, 1.0f, 1.0f, 1.0f, 1.0f);
-
if (pass == 0)
{
if (!LLPipeline::sReflectionRender)
@@ -679,7 +1137,7 @@ void LLDrawPoolAvatar::renderAvatars(LLVOAvatar* single_avatar, S32 pass)
if (impostor)
{
- if (LLPipeline::sRenderDeferred && avatarp->mImpostor.isComplete())
+ if (LLPipeline::sRenderDeferred && !LLPipeline::sReflectionRender && avatarp->mImpostor.isComplete())
{
if (normal_channel > -1)
{
@@ -690,7 +1148,7 @@ void LLDrawPoolAvatar::renderAvatars(LLVOAvatar* single_avatar, S32 pass)
avatarp->mImpostor.bindTexture(1, specular_channel);
}
}
- avatarp->renderImpostor(LLColor4U(255,255,255,255), diffuse_channel);
+ avatarp->renderImpostor(LLColor4U(255,255,255,255), sDiffuseChannel);
}
return;
}
@@ -706,6 +1164,88 @@ void LLDrawPoolAvatar::renderAvatars(LLVOAvatar* single_avatar, S32 pass)
avatarp->renderRigid();
return;
}
+
+ if (pass == 3)
+ {
+ if (is_deferred_render)
+ {
+ renderDeferredRiggedSimple(avatarp);
+ }
+ else
+ {
+ renderRiggedSimple(avatarp);
+ }
+ return;
+ }
+
+ if (pass == 4)
+ {
+ if (is_deferred_render)
+ {
+ renderDeferredRiggedBump(avatarp);
+ }
+ else
+ {
+ renderRiggedFullbright(avatarp);
+ }
+
+ return;
+ }
+
+ if (pass == 5)
+ {
+ renderRiggedShinySimple(avatarp);
+ return;
+ }
+
+ if (pass == 6)
+ {
+ renderRiggedFullbrightShiny(avatarp);
+ return;
+ }
+
+ if (pass >= 7 && pass < 9)
+ {
+ LLGLEnable blend(GL_BLEND);
+
+ gGL.setColorMask(true, true);
+ gGL.blendFunc(LLRender::BF_SOURCE_ALPHA,
+ LLRender::BF_ONE_MINUS_SOURCE_ALPHA,
+ LLRender::BF_ZERO,
+ LLRender::BF_ONE_MINUS_SOURCE_ALPHA);
+
+
+ if (pass == 7)
+ {
+ renderRiggedAlpha(avatarp);
+ return;
+ }
+
+ if (pass == 8)
+ {
+ renderRiggedFullbrightAlpha(avatarp);
+ return;
+ }
+ }
+
+ if (pass == 9)
+ {
+ LLGLEnable blend(GL_BLEND);
+ LLGLDisable test(GL_ALPHA_TEST);
+ gGL.flush();
+
+ LLGLEnable polyOffset(GL_POLYGON_OFFSET_FILL);
+ glPolygonOffset(-1.0f, -1.0f);
+ gGL.setSceneBlendType(LLRender::BT_ADD);
+
+ LLGLDepthTest depth(GL_TRUE, GL_FALSE);
+ gGL.setColorMask(false, true);
+
+ renderRiggedGlow(avatarp);
+ gGL.setColorMask(true, false);
+ gGL.setSceneBlendType(LLRender::BT_ALPHA);
+ return;
+ }
if (sShaderLevel > 0)
{
@@ -743,6 +1283,307 @@ void LLDrawPoolAvatar::renderAvatars(LLVOAvatar* single_avatar, S32 pass)
}
}
+void LLDrawPoolAvatar::updateRiggedFaceVertexBuffer(LLVOAvatar* avatar, LLFace* face, const LLMeshSkinInfo* skin, LLVolume* volume, const LLVolumeFace& vol_face)
+{
+ LLVector4a* weight = vol_face.mWeights;
+ if (!weight)
+ {
+ return;
+ }
+
+ LLVertexBuffer* buffer = face->getVertexBuffer();
+
+ U32 data_mask = face->getRiggedVertexBufferDataMask();
+
+ if (!buffer ||
+ buffer->getTypeMask() != data_mask ||
+ buffer->getRequestedVerts() != vol_face.mNumVertices)
+ {
+ face->setGeomIndex(0);
+ face->setIndicesIndex(0);
+ face->setSize(vol_face.mNumVertices, vol_face.mNumIndices, true);
+
+
+ if (sShaderLevel > 0)
+ {
+ buffer = new LLVertexBuffer(data_mask, GL_DYNAMIC_DRAW_ARB);
+ }
+ else
+ {
+ buffer = new LLVertexBuffer(data_mask, GL_STREAM_DRAW_ARB);
+ }
+
+ buffer->allocateBuffer(face->getGeomCount(), face->getIndicesCount(), true);
+
+ face->setVertexBuffer(buffer);
+
+ U16 offset = 0;
+
+ LLMatrix4 mat_vert = skin->mBindShapeMatrix;
+ glh::matrix4f m((F32*) mat_vert.mMatrix);
+ m = m.inverse().transpose();
+
+ F32 mat3[] =
+ { m.m[0], m.m[1], m.m[2],
+ m.m[4], m.m[5], m.m[6],
+ m.m[8], m.m[9], m.m[10] };
+
+ LLMatrix3 mat_normal(mat3);
+
+ face->getGeometryVolume(*volume, face->getTEOffset(), mat_vert, mat_normal, offset, true);
+ }
+
+ if (sShaderLevel <= 0 && face->mLastSkinTime < avatar->getLastSkinTime())
+ { //perform software vertex skinning for this face
+ LLStrider<LLVector3> position;
+ LLStrider<LLVector3> normal;
+
+ bool has_normal = buffer->hasDataType(LLVertexBuffer::TYPE_NORMAL);
+ buffer->getVertexStrider(position);
+
+ if (has_normal)
+ {
+ buffer->getNormalStrider(normal);
+ }
+
+ LLVector4a* pos = (LLVector4a*) position.get();
+
+ LLVector4a* norm = has_normal ? (LLVector4a*) normal.get() : NULL;
+
+ //build matrix palette
+ LLMatrix4a mp[64];
+ LLMatrix4* mat = (LLMatrix4*) mp;
+
+ for (U32 j = 0; j < skin->mJointNames.size(); ++j)
+ {
+ LLJoint* joint = avatar->getJoint(skin->mJointNames[j]);
+ if (joint)
+ {
+ mat[j] = skin->mInvBindMatrix[j];
+ mat[j] *= joint->getWorldMatrix();
+ }
+ }
+
+ LLMatrix4a bind_shape_matrix;
+ bind_shape_matrix.loadu(skin->mBindShapeMatrix);
+
+ for (U32 j = 0; j < buffer->getRequestedVerts(); ++j)
+ {
+ LLMatrix4a final_mat;
+ final_mat.clear();
+
+ S32 idx[4];
+
+ LLVector4 wght;
+
+ F32 scale = 0.f;
+ for (U32 k = 0; k < 4; k++)
+ {
+ F32 w = weight[j][k];
+
+ idx[k] = llclamp((S32) floorf(w), 0, 63);
+ wght[k] = w - floorf(w);
+ scale += wght[k];
+ }
+
+ wght *= 1.f/scale;
+
+ for (U32 k = 0; k < 4; k++)
+ {
+ F32 w = wght[k];
+
+ LLMatrix4a src;
+ src.setMul(mp[idx[k]], w);
+
+ final_mat.add(src);
+ }
+
+
+ LLVector4a& v = vol_face.mPositions[j];
+ LLVector4a t;
+ LLVector4a dst;
+ bind_shape_matrix.affineTransform(v, t);
+ final_mat.affineTransform(t, dst);
+ pos[j] = dst;
+
+ if (norm)
+ {
+ LLVector4a& n = vol_face.mNormals[j];
+ bind_shape_matrix.rotate(n, t);
+ final_mat.rotate(t, dst);
+ norm[j] = dst;
+ }
+ }
+ }
+}
+
+void LLDrawPoolAvatar::renderRigged(LLVOAvatar* avatar, U32 type, bool glow)
+{
+ if (avatar->isSelf() && !gAgent.needsRenderAvatar())
+ {
+ return;
+ }
+
+ stop_glerror();
+
+ for (U32 i = 0; i < mRiggedFace[type].size(); ++i)
+ {
+ LLFace* face = mRiggedFace[type][i];
+ LLDrawable* drawable = face->getDrawable();
+ if (!drawable)
+ {
+ continue;
+ }
+
+ LLVOVolume* vobj = drawable->getVOVolume();
+
+ if (!vobj)
+ {
+ continue;
+ }
+
+ LLVolume* volume = vobj->getVolume();
+ S32 te = face->getTEOffset();
+
+ if (!volume || volume->getNumVolumeFaces() <= te)
+ {
+ continue;
+ }
+
+ LLUUID mesh_id = volume->getParams().getSculptID();
+ if (mesh_id.isNull())
+ {
+ continue;
+ }
+
+ const LLMeshSkinInfo* skin = gMeshRepo.getSkinInfo(mesh_id);
+ if (!skin)
+ {
+ continue;
+ }
+
+ stop_glerror();
+
+ const LLVolumeFace& vol_face = volume->getVolumeFace(te);
+ updateRiggedFaceVertexBuffer(avatar, face, skin, volume, vol_face);
+
+ stop_glerror();
+
+ U32 data_mask = LLFace::getRiggedDataMask(type);
+
+ LLVertexBuffer* buff = face->getVertexBuffer();
+
+ if (buff)
+ {
+ if (sShaderLevel > 0)
+ { //upload matrix palette to shader
+ LLMatrix4 mat[64];
+
+ for (U32 i = 0; i < skin->mJointNames.size(); ++i)
+ {
+ LLJoint* joint = avatar->getJoint(skin->mJointNames[i]);
+ if (joint)
+ {
+ mat[i] = skin->mInvBindMatrix[i];
+ mat[i] *= joint->getWorldMatrix();
+ }
+ }
+
+ stop_glerror();
+
+ LLDrawPoolAvatar::sVertexProgram->uniformMatrix4fv("matrixPalette",
+ skin->mJointNames.size(),
+ FALSE,
+ (GLfloat*) mat[0].mMatrix);
+
+ stop_glerror();
+ }
+ else
+ {
+ data_mask &= ~LLVertexBuffer::MAP_WEIGHT4;
+ }
+
+ buff->setBuffer(data_mask);
+
+ U16 start = face->getGeomStart();
+ U16 end = start + face->getGeomCount()-1;
+ S32 offset = face->getIndicesStart();
+ U32 count = face->getIndicesCount();
+
+ if (glow)
+ {
+ glColor4f(0,0,0,face->getTextureEntry()->getGlow());
+ }
+
+ gGL.getTexUnit(sDiffuseChannel)->bind(face->getTexture());
+ if (normal_channel > -1)
+ {
+ LLDrawPoolBump::bindBumpMap(face, normal_channel);
+ }
+
+ if (face->mTextureMatrix)
+ {
+ glMatrixMode(GL_TEXTURE);
+ glLoadMatrixf((F32*) face->mTextureMatrix->mMatrix);
+ buff->drawRange(LLRender::TRIANGLES, start, end, count, offset);
+ glLoadIdentity();
+ glMatrixMode(GL_MODELVIEW);
+ }
+ else
+ {
+ buff->drawRange(LLRender::TRIANGLES, start, end, count, offset);
+ }
+ }
+ }
+}
+
+void LLDrawPoolAvatar::renderDeferredRiggedSimple(LLVOAvatar* avatar)
+{
+ renderRigged(avatar, RIGGED_DEFERRED_SIMPLE);
+}
+
+void LLDrawPoolAvatar::renderDeferredRiggedBump(LLVOAvatar* avatar)
+{
+ renderRigged(avatar, RIGGED_DEFERRED_BUMP);
+}
+
+void LLDrawPoolAvatar::renderRiggedSimple(LLVOAvatar* avatar)
+{
+ renderRigged(avatar, RIGGED_SIMPLE);
+}
+
+void LLDrawPoolAvatar::renderRiggedFullbright(LLVOAvatar* avatar)
+{
+ renderRigged(avatar, RIGGED_FULLBRIGHT);
+}
+
+
+void LLDrawPoolAvatar::renderRiggedShinySimple(LLVOAvatar* avatar)
+{
+ renderRigged(avatar, RIGGED_SHINY);
+}
+
+void LLDrawPoolAvatar::renderRiggedFullbrightShiny(LLVOAvatar* avatar)
+{
+ renderRigged(avatar, RIGGED_FULLBRIGHT_SHINY);
+}
+
+void LLDrawPoolAvatar::renderRiggedAlpha(LLVOAvatar* avatar)
+{
+ renderRigged(avatar, RIGGED_ALPHA);
+}
+
+void LLDrawPoolAvatar::renderRiggedFullbrightAlpha(LLVOAvatar* avatar)
+{
+ renderRigged(avatar, RIGGED_FULLBRIGHT_ALPHA);
+}
+
+void LLDrawPoolAvatar::renderRiggedGlow(LLVOAvatar* avatar)
+{
+ renderRigged(avatar, RIGGED_GLOW, true);
+}
+
+
//-----------------------------------------------------------------------------
// getDebugTexture()
@@ -770,6 +1611,50 @@ LLColor3 LLDrawPoolAvatar::getDebugColor() const
return LLColor3(0.f, 1.f, 0.f);
}
+void LLDrawPoolAvatar::addRiggedFace(LLFace* facep, U32 type)
+{
+ if (type >= NUM_RIGGED_PASSES)
+ {
+ llerrs << "Invalid rigged face type." << llendl;
+ }
+
+ if (facep->getRiggedIndex(type) != -1)
+ {
+ llerrs << "Tried to add a rigged face that's referenced elsewhere." << llendl;
+ }
+
+ facep->setRiggedIndex(type, mRiggedFace[type].size());
+ facep->setPool(this);
+ mRiggedFace[type].push_back(facep);
+}
+
+void LLDrawPoolAvatar::removeRiggedFace(LLFace* facep)
+{
+ facep->setPool(NULL);
+
+ for (U32 i = 0; i < NUM_RIGGED_PASSES; ++i)
+ {
+ S32 index = facep->getRiggedIndex(i);
+
+ if (index > -1)
+ {
+ if (mRiggedFace[i].size() > index && mRiggedFace[i][index] == facep)
+ {
+ facep->setRiggedIndex(i,-1);
+ mRiggedFace[i].erase(mRiggedFace[i].begin()+index);
+ for (U32 j = index; j < mRiggedFace[i].size(); ++j)
+ { //bump indexes down for faces referenced after erased face
+ mRiggedFace[i][j]->setRiggedIndex(i, j);
+ }
+ }
+ else
+ {
+ llerrs << "Face reference data corrupt for rigged type " << i << llendl;
+ }
+ }
+ }
+}
+
LLVertexBufferAvatar::LLVertexBufferAvatar()
: LLVertexBuffer(sDataMask,
GL_STREAM_DRAW_ARB) //avatars are always stream draw due to morph targets
@@ -782,22 +1667,25 @@ void LLVertexBufferAvatar::setupVertexBuffer(U32 data_mask) const
{
if (sRenderingSkinned)
{
- U8* base = useVBOs() ? NULL : mMappedData;
+ U8* base = useVBOs() ? (U8*) mAlignedOffset : mMappedData;
- glVertexPointer(3,GL_FLOAT, mStride, (void*)(base + 0));
- glNormalPointer(GL_FLOAT, mStride, (void*)(base + mOffsets[TYPE_NORMAL]));
- glTexCoordPointer(2,GL_FLOAT, mStride, (void*)(base + mOffsets[TYPE_TEXCOORD0]));
+ glVertexPointer(3,GL_FLOAT, LLVertexBuffer::sTypeSize[LLVertexBuffer::TYPE_VERTEX], (void*)(base + 0));
+ glNormalPointer(GL_FLOAT, LLVertexBuffer::sTypeSize[LLVertexBuffer::TYPE_NORMAL], (void*)(base + mOffsets[TYPE_NORMAL]));
+ glTexCoordPointer(2,GL_FLOAT, LLVertexBuffer::sTypeSize[LLVertexBuffer::TYPE_TEXCOORD0], (void*)(base + mOffsets[TYPE_TEXCOORD0]));
- set_vertex_weights(sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_WEIGHT], mStride, (F32*)(base + mOffsets[TYPE_WEIGHT]));
+ set_vertex_weights(LLDrawPoolAvatar::sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_WEIGHT],
+ LLVertexBuffer::sTypeSize[LLVertexBuffer::TYPE_WEIGHT], (F32*)(base + mOffsets[TYPE_WEIGHT]));
if (sShaderLevel >= LLDrawPoolAvatar::SHADER_LEVEL_BUMP)
{
- set_binormals(sVertexProgram->mAttribute[LLViewerShaderMgr::BINORMAL], mStride, (LLVector3*)(base + mOffsets[TYPE_BINORMAL]));
+ set_binormals(LLDrawPoolAvatar::sVertexProgram->mAttribute[LLViewerShaderMgr::BINORMAL],
+ LLVertexBuffer::sTypeSize[LLVertexBuffer::TYPE_BINORMAL], (LLVector3*)(base + mOffsets[TYPE_BINORMAL]));
}
if (sShaderLevel >= LLDrawPoolAvatar::SHADER_LEVEL_CLOTH)
{
- set_vertex_clothing_weights(sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_CLOTHING], mStride, (LLVector4*)(base + mOffsets[TYPE_CLOTHWEIGHT]));
+ set_vertex_clothing_weights(LLDrawPoolAvatar::sVertexProgram->mAttribute[LLViewerShaderMgr::AVATAR_CLOTHING],
+ LLVertexBuffer::sTypeSize[LLVertexBuffer::TYPE_CLOTHWEIGHT], (LLVector4*)(base + mOffsets[TYPE_CLOTHWEIGHT]));
}
}
else
diff --git a/indra/newview/lldrawpoolavatar.h b/indra/newview/lldrawpoolavatar.h
index f536d3c911..fcd8294af5 100644
--- a/indra/newview/lldrawpoolavatar.h
+++ b/indra/newview/lldrawpoolavatar.h
@@ -1,4 +1,4 @@
-/**
+ /**
* @file lldrawpoolavatar.h
* @brief LLDrawPoolAvatar class definition
*
@@ -30,6 +30,12 @@
#include "lldrawpool.h"
class LLVOAvatar;
+class LLGLSLShader;
+class LLFace;
+class LLMeshSkinInfo;
+class LLVolume;
+class LLVolumeFace;
+
class LLDrawPoolAvatar : public LLFacePool
{
@@ -83,7 +89,7 @@ public:
void beginRigid();
void beginImpostor();
void beginSkinned();
-
+
void endRigid();
void endImpostor();
void endSkinned();
@@ -95,14 +101,113 @@ public:
void endDeferredImpostor();
void endDeferredRigid();
void endDeferredSkinned();
+
+ void beginPostDeferredAlpha();
+ void endPostDeferredAlpha();
+
+ void beginRiggedSimple();
+ void beginRiggedFullbright();
+ void beginRiggedFullbrightShiny();
+ void beginRiggedShinySimple();
+ void beginRiggedAlpha();
+ void beginRiggedFullbrightAlpha();
+ void beginRiggedGlow();
+ void beginDeferredRiggedAlpha();
+
+ void endRiggedSimple();
+ void endRiggedFullbright();
+ void endRiggedFullbrightShiny();
+ void endRiggedShinySimple();
+ void endRiggedAlpha();
+ void endRiggedFullbrightAlpha();
+ void endRiggedGlow();
+ void endDeferredRiggedAlpha();
+
+ void beginDeferredRiggedSimple();
+ void beginDeferredRiggedBump();
+
+ void endDeferredRiggedSimple();
+ void endDeferredRiggedBump();
+ void updateRiggedFaceVertexBuffer(LLVOAvatar* avatar,
+ LLFace* facep,
+ const LLMeshSkinInfo* skin,
+ LLVolume* volume,
+ const LLVolumeFace& vol_face);
+
+ void renderRigged(LLVOAvatar* avatar, U32 type, bool glow = false);
+ void renderRiggedSimple(LLVOAvatar* avatar);
+ void renderRiggedAlpha(LLVOAvatar* avatar);
+ void renderRiggedFullbrightAlpha(LLVOAvatar* avatar);
+ void renderRiggedFullbright(LLVOAvatar* avatar);
+ void renderRiggedShinySimple(LLVOAvatar* avatar);
+ void renderRiggedFullbrightShiny(LLVOAvatar* avatar);
+ void renderRiggedGlow(LLVOAvatar* avatar);
+ void renderDeferredRiggedSimple(LLVOAvatar* avatar);
+ void renderDeferredRiggedBump(LLVOAvatar* avatar);
+
+ typedef enum
+ {
+ RIGGED_SIMPLE = 0,
+ RIGGED_FULLBRIGHT,
+ RIGGED_SHINY,
+ RIGGED_FULLBRIGHT_SHINY,
+ RIGGED_GLOW,
+ RIGGED_ALPHA,
+ RIGGED_FULLBRIGHT_ALPHA,
+ RIGGED_DEFERRED_BUMP,
+ RIGGED_DEFERRED_SIMPLE,
+ NUM_RIGGED_PASSES,
+ RIGGED_UNKNOWN,
+ } eRiggedPass;
+
+ typedef enum
+ {
+ RIGGED_SIMPLE_MASK = LLVertexBuffer::MAP_VERTEX |
+ LLVertexBuffer::MAP_NORMAL |
+ LLVertexBuffer::MAP_TEXCOORD0 |
+ LLVertexBuffer::MAP_COLOR |
+ LLVertexBuffer::MAP_WEIGHT4,
+ RIGGED_FULLBRIGHT_MASK = LLVertexBuffer::MAP_VERTEX |
+ LLVertexBuffer::MAP_TEXCOORD0 |
+ LLVertexBuffer::MAP_COLOR |
+ LLVertexBuffer::MAP_WEIGHT4,
+ RIGGED_SHINY_MASK = RIGGED_SIMPLE_MASK,
+ RIGGED_FULLBRIGHT_SHINY_MASK = RIGGED_SIMPLE_MASK,
+ RIGGED_GLOW_MASK = LLVertexBuffer::MAP_VERTEX |
+ LLVertexBuffer::MAP_TEXCOORD0 |
+ LLVertexBuffer::MAP_WEIGHT4,
+ RIGGED_ALPHA_MASK = RIGGED_SIMPLE_MASK,
+ RIGGED_FULLBRIGHT_ALPHA_MASK = RIGGED_FULLBRIGHT_MASK,
+ RIGGED_DEFERRED_BUMP_MASK = LLVertexBuffer::MAP_VERTEX |
+ LLVertexBuffer::MAP_NORMAL |
+ LLVertexBuffer::MAP_TEXCOORD0 |
+ LLVertexBuffer::MAP_BINORMAL |
+ LLVertexBuffer::MAP_COLOR |
+ LLVertexBuffer::MAP_WEIGHT4,
+ RIGGED_DEFERRED_SIMPLE_MASK = LLVertexBuffer::MAP_VERTEX |
+ LLVertexBuffer::MAP_NORMAL |
+ LLVertexBuffer::MAP_TEXCOORD0 |
+ LLVertexBuffer::MAP_COLOR |
+ LLVertexBuffer::MAP_WEIGHT4,
+ } eRiggedDataMask;
+
+ void addRiggedFace(LLFace* facep, U32 type);
+ void removeRiggedFace(LLFace* facep);
+
+ std::vector<LLFace*> mRiggedFace[NUM_RIGGED_PASSES];
+
/*virtual*/ LLViewerTexture *getDebugTexture();
/*virtual*/ LLColor3 getDebugColor() const; // For AGP debug display
void renderAvatars(LLVOAvatar *single_avatar, S32 pass = -1); // renders only one avatar if single_avatar is not null.
+
static BOOL sSkipOpaque;
static BOOL sSkipTransparent;
+ static S32 sDiffuseChannel;
+
+ static LLGLSLShader* sVertexProgram;
};
class LLVertexBufferAvatar : public LLVertexBuffer
diff --git a/indra/newview/lldrawpoolbump.cpp b/indra/newview/lldrawpoolbump.cpp
index 223e4a438c..38ff3083ce 100644
--- a/indra/newview/lldrawpoolbump.cpp
+++ b/indra/newview/lldrawpoolbump.cpp
@@ -145,12 +145,7 @@ void LLStandardBumpmap::addstandard()
// llinfos << "Loading bumpmap: " << bump_image_id << " from viewerart" << llendl;
gStandardBumpmapList[LLStandardBumpmap::sStandardBumpmapCount].mLabel = label;
gStandardBumpmapList[LLStandardBumpmap::sStandardBumpmapCount].mImage =
- LLViewerTextureManager::getFetchedTexture(LLUUID(bump_image_id),
- TRUE,
- LLViewerTexture::BOOST_NONE,
- LLViewerTexture::LOD_TEXTURE,
- 0,
- 0);
+ LLViewerTextureManager::getFetchedTexture(LLUUID(bump_image_id));
gStandardBumpmapList[LLStandardBumpmap::sStandardBumpmapCount].mImage->setBoostLevel(LLViewerTexture::BOOST_BUMP) ;
gStandardBumpmapList[LLStandardBumpmap::sStandardBumpmapCount].mImage->setLoadedCallback(LLBumpImageList::onSourceStandardLoaded, 0, TRUE, FALSE, NULL, NULL );
LLStandardBumpmap::sStandardBumpmapCount++;
@@ -334,30 +329,43 @@ void LLDrawPoolBump::beginShiny(bool invisible)
sVertexMask = VERTEX_MASK_SHINY | LLVertexBuffer::MAP_TEXCOORD0;
}
- if (LLPipeline::sUnderWaterRender)
+ if (getVertexShaderLevel() > 0)
{
- shader = &gObjectShinyWaterProgram;
+ if (LLPipeline::sUnderWaterRender)
+ {
+ shader = &gObjectShinyWaterProgram;
+ }
+ else
+ {
+ shader = &gObjectShinyProgram;
+ }
+ shader->bind();
}
else
{
- shader = &gObjectShinyProgram;
+ shader = NULL;
}
+ bindCubeMap(shader, mVertexShaderLevel, diffuse_channel, cube_channel, invisible);
+}
+
+//static
+void LLDrawPoolBump::bindCubeMap(LLGLSLShader* shader, S32 shader_level, S32& diffuse_channel, S32& cube_channel, bool invisible)
+{
LLCubeMap* cube_map = gSky.mVOSkyp ? gSky.mVOSkyp->getCubeMap() : NULL;
if( cube_map )
{
- if (!invisible && LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT) > 0 )
+ if (!invisible && shader )
{
LLMatrix4 mat;
mat.initRows(LLVector4(gGLModelView+0),
LLVector4(gGLModelView+4),
LLVector4(gGLModelView+8),
LLVector4(gGLModelView+12));
- shader->bind();
LLVector3 vec = LLVector3(gShinyOrigin) * mat;
LLVector4 vec4(vec, gShinyOrigin.mV[3]);
shader->uniform4fv(LLViewerShaderMgr::SHINY_ORIGIN, 1, vec4.mV);
- if (mVertexShaderLevel > 1)
+ if (shader_level > 1)
{
cube_map->setMatrix(1);
// Make sure that texture coord generation happens for tex unit 1, as that's the one we use for
@@ -419,22 +427,16 @@ void LLDrawPoolBump::renderShiny(bool invisible)
}
}
-void LLDrawPoolBump::endShiny(bool invisible)
+//static
+void LLDrawPoolBump::unbindCubeMap(LLGLSLShader* shader, S32 shader_level, S32& diffuse_channel, S32& cube_channel, bool invisible)
{
- LLFastTimer t(FTM_RENDER_SHINY);
- if ((!invisible && !gPipeline.hasRenderBatches(LLRenderPass::PASS_SHINY))||
- (invisible && !gPipeline.hasRenderBatches(LLRenderPass::PASS_INVISI_SHINY)))
- {
- return;
- }
-
LLCubeMap* cube_map = gSky.mVOSkyp ? gSky.mVOSkyp->getCubeMap() : NULL;
if( cube_map )
{
cube_map->disable();
cube_map->restoreMatrix();
- if (!invisible && mVertexShaderLevel > 1)
+ if (!invisible && shader_level > 1)
{
shader->disableTexture(LLViewerShaderMgr::ENVIRONMENT_MAP, LLTexUnit::TT_CUBE_MAP);
@@ -445,7 +447,6 @@ void LLDrawPoolBump::endShiny(bool invisible)
shader->disableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
}
}
- shader->unbind();
}
}
gGL.getTexUnit(diffuse_channel)->disable();
@@ -453,6 +454,22 @@ void LLDrawPoolBump::endShiny(bool invisible)
gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
+}
+
+void LLDrawPoolBump::endShiny(bool invisible)
+{
+ LLFastTimer t(FTM_RENDER_SHINY);
+ if ((!invisible && !gPipeline.hasRenderBatches(LLRenderPass::PASS_SHINY))||
+ (invisible && !gPipeline.hasRenderBatches(LLRenderPass::PASS_INVISI_SHINY)))
+ {
+ return;
+ }
+
+ unbindCubeMap(shader, mVertexShaderLevel, diffuse_channel, cube_channel, invisible);
+ if (shader)
+ {
+ shader->unbind();
+ }
diffuse_channel = -1;
cube_channel = 0;
@@ -473,7 +490,7 @@ void LLDrawPoolBump::beginFullbrightShiny()
if (LLPipeline::sUnderWaterRender)
{
- shader = &gObjectShinyWaterProgram;
+ shader = &gObjectFullbrightShinyWaterProgram;
}
else
{
@@ -580,18 +597,37 @@ void LLDrawPoolBump::renderGroup(LLSpatialGroup* group, U32 type, U32 mask, BOOL
// static
BOOL LLDrawPoolBump::bindBumpMap(LLDrawInfo& params, S32 channel)
{
- LLViewerTexture* bump = NULL;
-
U8 bump_code = params.mBump;
+ return bindBumpMap(bump_code, params.mTexture, params.mVSize, channel);
+}
+
+//static
+BOOL LLDrawPoolBump::bindBumpMap(LLFace* face, S32 channel)
+{
+ const LLTextureEntry* te = face->getTextureEntry();
+ if (te)
+ {
+ U8 bump_code = te->getBumpmap();
+ return bindBumpMap(bump_code, face->getTexture(), face->getVirtualSize(), channel);
+ }
+
+ return FALSE;
+}
+
+//static
+BOOL LLDrawPoolBump::bindBumpMap(U8 bump_code, LLViewerTexture* texture, F32 vsize, S32 channel)
+{
//Note: texture atlas does not support bump texture now.
- LLViewerFetchedTexture* tex = LLViewerTextureManager::staticCastToFetchedTexture(params.mTexture) ;
+ LLViewerFetchedTexture* tex = LLViewerTextureManager::staticCastToFetchedTexture(texture) ;
if(!tex)
{
//if the texture is not a fetched texture
return FALSE;
}
+ LLViewerTexture* bump = NULL;
+
switch( bump_code )
{
case BE_NO_BUMP:
@@ -605,7 +641,7 @@ BOOL LLDrawPoolBump::bindBumpMap(LLDrawInfo& params, S32 channel)
if( bump_code < LLStandardBumpmap::sStandardBumpmapCount )
{
bump = gStandardBumpmapList[bump_code].mImage;
- gBumpImageList.addTextureStats(bump_code, tex->getID(), params.mVSize);
+ gBumpImageList.addTextureStats(bump_code, tex->getID(), vsize);
}
break;
}
@@ -1085,7 +1121,11 @@ void LLBumpImageList::onSourceLoaded( BOOL success, LLViewerTexture *src_vi, LLI
{
bump_image_map_t& entries_list(bump_code == BE_BRIGHTNESS ? gBumpImageList.mBrightnessEntries : gBumpImageList.mDarknessEntries );
bump_image_map_t::iterator iter = entries_list.find(source_asset_id);
- if (iter != entries_list.end()) // bump not cached yet
+
+ if (iter != entries_list.end() ||
+ iter->second.isNull() ||
+ iter->second->getWidth() != src->getWidth() ||
+ iter->second->getHeight() != src->getHeight()) // bump not cached yet or has changed resolution
{
LLPointer<LLImageRaw> dst_image = new LLImageRaw(src->getWidth(), src->getHeight(), 1);
U8* dst_data = dst_image->getData();
diff --git a/indra/newview/lldrawpoolbump.h b/indra/newview/lldrawpoolbump.h
index 65a813ab94..f4702bf61d 100644
--- a/indra/newview/lldrawpoolbump.h
+++ b/indra/newview/lldrawpoolbump.h
@@ -35,6 +35,7 @@
class LLImageRaw;
class LLSpatialGroup;
class LLDrawInfo;
+class LLGLSLShader;
class LLViewerFetchedTexture;
class LLDrawPoolBump : public LLRenderPass
@@ -73,6 +74,9 @@ public:
void renderBump(U32 pass = LLRenderPass::PASS_BUMP);
void endBump(U32 pass = LLRenderPass::PASS_BUMP);
+ static void bindCubeMap(LLGLSLShader* shader, S32 shader_level, S32& diffuse_channel, S32& cube_channel, bool invisible);
+ static void unbindCubeMap(LLGLSLShader* shader, S32 shader_level, S32& diffuse_channel, S32& cube_channel, bool invisible);
+
virtual S32 getNumDeferredPasses();
/*virtual*/ void beginDeferredPass(S32 pass);
/*virtual*/ void endDeferredPass(S32 pass);
@@ -83,7 +87,12 @@ public:
/*virtual*/ void endPostDeferredPass(S32 pass);
/*virtual*/ void renderPostDeferred(S32 pass);
- BOOL bindBumpMap(LLDrawInfo& params, S32 channel = -2);
+ static BOOL bindBumpMap(LLDrawInfo& params, S32 channel = -2);
+ static BOOL bindBumpMap(LLFace* face, S32 channel = -2);
+
+private:
+ static BOOL bindBumpMap(U8 bump_code, LLViewerTexture* tex, F32 vsize, S32 channel);
+
};
enum EBumpEffect
diff --git a/indra/newview/lldrawpooltree.cpp b/indra/newview/lldrawpooltree.cpp
index f1198c9a8d..195ee60a2e 100644
--- a/indra/newview/lldrawpooltree.cpp
+++ b/indra/newview/lldrawpooltree.cpp
@@ -107,11 +107,12 @@ void LLDrawPoolTree::render(S32 pass)
iter != mDrawFace.end(); iter++)
{
LLFace *face = *iter;
- if(face->mVertexBuffer.notNull())
+ LLVertexBuffer* buff = face->getVertexBuffer();
+ if(buff)
{
- face->mVertexBuffer->setBuffer(LLDrawPoolTree::VERTEX_DATA_MASK);
- face->mVertexBuffer->drawRange(LLRender::TRIANGLES, 0, face->mVertexBuffer->getRequestedVerts()-1, face->mVertexBuffer->getRequestedIndices(), 0);
- gPipeline.addTrianglesDrawn(face->mVertexBuffer->getRequestedIndices());
+ buff->setBuffer(LLDrawPoolTree::VERTEX_DATA_MASK);
+ buff->drawRange(LLRender::TRIANGLES, 0, buff->getRequestedVerts()-1, buff->getRequestedIndices(), 0);
+ gPipeline.addTrianglesDrawn(buff->getRequestedIndices());
}
}
}
@@ -200,13 +201,13 @@ void LLDrawPoolTree::renderTree(BOOL selecting)
LLFace *face = *iter;
LLDrawable *drawablep = face->getDrawable();
- if (drawablep->isDead() || face->mVertexBuffer.isNull())
+ if (drawablep->isDead() || !face->getVertexBuffer())
{
continue;
}
- face->mVertexBuffer->setBuffer(LLDrawPoolTree::VERTEX_DATA_MASK);
- U16* indicesp = (U16*) face->mVertexBuffer->getIndicesPointer();
+ face->getVertexBuffer()->setBuffer(LLDrawPoolTree::VERTEX_DATA_MASK);
+ U16* indicesp = (U16*) face->getVertexBuffer()->getIndicesPointer();
// Render each of the trees
LLVOTree *treep = (LLVOTree *)drawablep->getVObj().get();
diff --git a/indra/newview/lldrawpoolwlsky.cpp b/indra/newview/lldrawpoolwlsky.cpp
index eaa6aa7e37..696c2d1abd 100644
--- a/indra/newview/lldrawpoolwlsky.cpp
+++ b/indra/newview/lldrawpoolwlsky.cpp
@@ -192,7 +192,7 @@ void LLDrawPoolWLSky::renderSkyClouds(F32 camHeightLocal) const
&gWLCloudProgram;
LLGLEnable blend(GL_BLEND);
- LLGLSBlendFunc blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ gGL.setSceneBlendType(LLRender::BT_ALPHA);
gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
gGL.getTexUnit(0)->bind(sCloudNoiseTexture);
diff --git a/indra/newview/llface.cpp b/indra/newview/llface.cpp
index fe201a6773..290115417f 100644
--- a/indra/newview/llface.cpp
+++ b/indra/newview/llface.cpp
@@ -33,8 +33,10 @@
#include "llviewercontrol.h"
#include "llvolume.h"
#include "m3math.h"
+#include "llmatrix4a.h"
#include "v3color.h"
+#include "lldrawpoolavatar.h"
#include "lldrawpoolbump.h"
#include "llgl.h"
#include "llrender.h"
@@ -67,35 +69,43 @@ The resulting texture coordinate <u,v> is:
u = 2(B dot P)
v = 2(T dot P)
*/
-void planarProjection(LLVector2 &tc, const LLVector3& normal,
- const LLVector3 &mCenter, const LLVector3& vec)
-{ //DONE!
- LLVector3 binormal;
- float d = normal * LLVector3(1,0,0);
+void planarProjection(LLVector2 &tc, const LLVector4a& normal,
+ const LLVector4a &center, const LLVector4a& vec)
+{
+ LLVector4a binormal;
+ F32 d = normal[0];
+
if (d >= 0.5f || d <= -0.5f)
{
- binormal = LLVector3(0,1,0);
- if (normal.mV[0] < 0)
+ if (d < 0)
+ {
+ binormal.set(0,-1,0);
+ }
+ else
{
- binormal = -binormal;
+ binormal.set(0, 1, 0);
}
}
else
{
- binormal = LLVector3(1,0,0);
- if (normal.mV[1] > 0)
+ if (normal[1] > 0)
{
- binormal = -binormal;
+ binormal.set(-1,0,0);
+ }
+ else
+ {
+ binormal.set(1,0,0);
}
}
- LLVector3 tangent = binormal % normal;
+ LLVector4a tangent;
+ tangent.setCross3(binormal,normal);
- tc.mV[1] = -((tangent*vec)*2 - 0.5f);
- tc.mV[0] = 1.0f+((binormal*vec)*2 - 0.5f);
+ tc.mV[1] = -((tangent.dot3(vec).getF32())*2 - 0.5f);
+ tc.mV[0] = 1.0f+((binormal.dot3(vec).getF32())*2 - 0.5f);
}
-void sphericalProjection(LLVector2 &tc, const LLVector3& normal,
- const LLVector3 &mCenter, const LLVector3& vec)
+void sphericalProjection(LLVector2 &tc, const LLVector4a& normal,
+ const LLVector4a &mCenter, const LLVector4a& vec)
{ //BROKEN
/*tc.mV[0] = acosf(vd.mNormal * LLVector3(1,0,0))/3.14159f;
@@ -106,7 +116,7 @@ void sphericalProjection(LLVector2 &tc, const LLVector3& normal,
}*/
}
-void cylindricalProjection(LLVector2 &tc, const LLVector3& normal, const LLVector3 &mCenter, const LLVector3& vec)
+void cylindricalProjection(LLVector2 &tc, const LLVector4a& normal, const LLVector4a &mCenter, const LLVector4a& vec)
{ //BROKEN
/*LLVector3 binormal;
float d = vd.mNormal * LLVector3(1,0,0);
@@ -138,6 +148,7 @@ void LLFace::init(LLDrawable* drawablep, LLViewerObject* objp)
{
mLastUpdateTime = gFrameTimeSeconds;
mLastMoveTime = 0.f;
+ mLastSkinTime = gFrameTimeSeconds;
mVSize = 0.f;
mPixelArea = 16.f;
mState = GLOBAL;
@@ -179,9 +190,13 @@ void LLFace::init(LLDrawable* drawablep, LLViewerObject* objp)
mHasMedia = FALSE ;
}
-
void LLFace::destroy()
{
+ if (gDebugGL)
+ {
+ gPipeline.checkReferences(this);
+ }
+
if(mTexture.notNull())
{
mTexture->removeFace(this) ;
@@ -189,7 +204,15 @@ void LLFace::destroy()
if (mDrawPoolp)
{
- mDrawPoolp->removeFace(this);
+ if (this->isState(LLFace::RIGGED) && mDrawPoolp->getType() == LLDrawPool::POOL_AVATAR)
+ {
+ ((LLDrawPoolAvatar*) mDrawPoolp)->removeRiggedFace(this);
+ }
+ else
+ {
+ mDrawPoolp->removeFace(this);
+ }
+
mDrawPoolp = NULL;
}
@@ -210,8 +233,8 @@ void LLFace::destroy()
}
setDrawInfo(NULL);
-
removeAtlas();
+
mDrawablep = NULL;
mVObjp = NULL;
}
@@ -227,6 +250,11 @@ void LLFace::setWorldMatrix(const LLMatrix4 &mat)
llerrs << "Faces on this drawable are not independently modifiable\n" << llendl;
}
+void LLFace::setPool(LLFacePool* pool)
+{
+ mDrawPoolp = pool;
+}
+
void LLFace::setPool(LLFacePool* new_pool, LLViewerTexture *texturep)
{
LLMemType mt1(LLMemType::MTYPE_DRAWABLE);
@@ -329,8 +357,21 @@ void LLFace::setDrawable(LLDrawable *drawable)
mXform = &drawable->mXform;
}
-void LLFace::setSize(const S32 num_vertices, const S32 num_indices)
+void LLFace::setSize(S32 num_vertices, S32 num_indices, bool align)
{
+ if (align)
+ {
+ //allocate vertices in blocks of 4 for alignment
+ num_vertices = (num_vertices + 0x3) & ~0x3;
+ }
+ else
+ {
+ if (mDrawablep->getVOVolume())
+ {
+ llerrs << "WTF?" << llendl;
+ }
+ }
+
if (mGeomCount != num_vertices ||
mIndicesCount != num_indices)
{
@@ -339,8 +380,28 @@ void LLFace::setSize(const S32 num_vertices, const S32 num_indices)
mVertexBuffer = NULL;
mLastVertexBuffer = NULL;
}
+
+ llassert(verify());
+}
+
+void LLFace::setGeomIndex(U16 idx)
+{
+ if (mGeomIndex != idx)
+ {
+ mGeomIndex = idx;
+ mVertexBuffer = NULL;
+ }
}
+void LLFace::setIndicesIndex(S32 idx)
+{
+ if (mIndicesIndex != idx)
+ {
+ mIndicesIndex = idx;
+ mVertexBuffer = NULL;
+ }
+}
+
//============================================================================
U16 LLFace::getGeometryAvatar(
@@ -429,8 +490,36 @@ void LLFace::renderSelected(LLViewerTexture *imagep, const LLColor4& color)
}
glColor4fv(color.mV);
- mVertexBuffer->setBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_TEXCOORD0);
- mVertexBuffer->draw(LLRender::TRIANGLES, mIndicesCount, mIndicesIndex);
+
+ if (mDrawablep->isState(LLDrawable::RIGGED))
+ {
+ LLVOVolume* volume = mDrawablep->getVOVolume();
+ if (volume)
+ {
+ LLRiggedVolume* rigged = volume->getRiggedVolume();
+ if (rigged)
+ {
+ LLGLEnable offset(GL_POLYGON_OFFSET_FILL);
+ glPolygonOffset(-1.f, -1.f);
+ glMultMatrixf((F32*) volume->getRelativeXform().mMatrix);
+ const LLVolumeFace& vol_face = rigged->getVolumeFace(getTEOffset());
+ LLVertexBuffer::unbind();
+ glVertexPointer(3, GL_FLOAT, 16, vol_face.mPositions);
+ if (vol_face.mTexCoords)
+ {
+ glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+ glTexCoordPointer(2, GL_FLOAT, 8, vol_face.mTexCoords);
+ }
+ glDrawElements(GL_TRIANGLES, vol_face.mNumIndices, GL_UNSIGNED_SHORT, vol_face.mIndices);
+ glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+ }
+ }
+ }
+ else
+ {
+ mVertexBuffer->setBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_TEXCOORD0);
+ mVertexBuffer->draw(LLRender::TRIANGLES, mIndicesCount, mIndicesIndex);
+ }
gGL.popMatrix();
}
@@ -515,23 +604,26 @@ void LLFace::printDebugInfo() const
llinfos << "II: " << mIndicesIndex << " Count:" << mIndicesCount << llendl;
llinfos << llendl;
- poolp->printDebugInfo();
-
- S32 pool_references = 0;
- for (std::vector<LLFace*>::iterator iter = poolp->mReferences.begin();
- iter != poolp->mReferences.end(); iter++)
+ if (poolp)
{
- LLFace *facep = *iter;
- if (facep == this)
+ poolp->printDebugInfo();
+
+ S32 pool_references = 0;
+ for (std::vector<LLFace*>::iterator iter = poolp->mReferences.begin();
+ iter != poolp->mReferences.end(); iter++)
{
- llinfos << "Pool reference: " << pool_references << llendl;
- pool_references++;
+ LLFace *facep = *iter;
+ if (facep == this)
+ {
+ llinfos << "Pool reference: " << pool_references << llendl;
+ pool_references++;
+ }
}
- }
- if (pool_references != 1)
- {
- llinfos << "Incorrect number of pool references!" << llendl;
+ if (pool_references != 1)
+ {
+ llinfos << "Incorrect number of pool references!" << llendl;
+ }
}
#if 0
@@ -588,95 +680,116 @@ static void xform(LLVector2 &tex_coord, F32 cosAng, F32 sinAng, F32 offS, F32 of
BOOL LLFace::genVolumeBBoxes(const LLVolume &volume, S32 f,
- const LLMatrix4& mat_vert, const LLMatrix3& mat_normal, BOOL global_volume)
+ const LLMatrix4& mat_vert_in, const LLMatrix3& mat_normal_in, BOOL global_volume)
{
LLMemType mt1(LLMemType::MTYPE_DRAWABLE);
//get bounding box
- if (mDrawablep->isState(LLDrawable::REBUILD_VOLUME | LLDrawable::REBUILD_POSITION))
+ if (mDrawablep->isState(LLDrawable::REBUILD_VOLUME | LLDrawable::REBUILD_POSITION | LLDrawable::REBUILD_RIGGED))
{
+ //VECTORIZE THIS
+ LLMatrix4a mat_vert;
+ mat_vert.loadu(mat_vert_in);
+
+ LLMatrix4a mat_normal;
+ mat_normal.loadu(mat_normal_in);
+
//if (mDrawablep->isState(LLDrawable::REBUILD_VOLUME))
//{ //vertex buffer no longer valid
// mVertexBuffer = NULL;
// mLastVertexBuffer = NULL;
//}
- LLVector3 min,max;
+ //VECTORIZE THIS
+ LLVector4a min,max;
if (f >= volume.getNumVolumeFaces())
{
- min = LLVector3(-1,-1,-1);
- max = LLVector3(1,1,1);
- }
- else
- {
- const LLVolumeFace &face = volume.getVolumeFace(f);
- min = face.mExtents[0];
- max = face.mExtents[1];
+ llwarns << "Generating bounding box for invalid face index!" << llendl;
+ f = 0;
}
+ const LLVolumeFace &face = volume.getVolumeFace(f);
+ min = face.mExtents[0];
+ max = face.mExtents[1];
+
+
//min, max are in volume space, convert to drawable render space
- LLVector3 center = ((min + max) * 0.5f)*mat_vert;
- LLVector3 size = ((max-min) * 0.5f);
+ LLVector4a center;
+ LLVector4a t;
+ t.setAdd(min, max);
+ t.mul(0.5f);
+ mat_vert.affineTransform(t, center);
+ LLVector4a size;
+ size.setSub(max, min);
+ size.mul(0.5f);
+
if (!global_volume)
{
- size.scaleVec(mDrawablep->getVObj()->getScale());
+ //VECTORIZE THIS
+ LLVector4a scale;
+ scale.load3(mDrawablep->getVObj()->getScale().mV);
+ size.mul(scale);
}
- LLMatrix3 mat = mat_normal;
- LLVector3 x = mat.getFwdRow();
- LLVector3 y = mat.getLeftRow();
- LLVector3 z = mat.getUpRow();
- x.normVec();
- y.normVec();
- z.normVec();
+ mat_normal.mMatrix[0].normalize3fast();
+ mat_normal.mMatrix[1].normalize3fast();
+ mat_normal.mMatrix[2].normalize3fast();
+
+ LLVector4a v[4];
- mat.setRows(x,y,z);
+ //get 4 corners of bounding box
+ mat_normal.rotate(size,v[0]);
- LLQuaternion rotation = LLQuaternion(mat);
+ //VECTORIZE THIS
+ LLVector4a scale;
- LLVector3 v[4];
- //get 4 corners of bounding box
- v[0] = (size * rotation);
- v[1] = (LLVector3(-size.mV[0], -size.mV[1], size.mV[2]) * rotation);
- v[2] = (LLVector3(size.mV[0], -size.mV[1], -size.mV[2]) * rotation);
- v[3] = (LLVector3(-size.mV[0], size.mV[1], -size.mV[2]) * rotation);
+ scale.set(-1.f, -1.f, 1.f);
+ scale.mul(size);
+ mat_normal.rotate(scale, v[1]);
+
+ scale.set(1.f, -1.f, -1.f);
+ scale.mul(size);
+ mat_normal.rotate(scale, v[2]);
+
+ scale.set(-1.f, 1.f, -1.f);
+ scale.mul(size);
+ mat_normal.rotate(scale, v[3]);
- LLVector3& newMin = mExtents[0];
- LLVector3& newMax = mExtents[1];
+ LLVector4a& newMin = mExtents[0];
+ LLVector4a& newMax = mExtents[1];
newMin = newMax = center;
for (U32 i = 0; i < 4; i++)
{
- for (U32 j = 0; j < 3; j++)
- {
- F32 delta = fabsf(v[i].mV[j]);
- F32 min = center.mV[j] - delta;
- F32 max = center.mV[j] + delta;
-
- if (min < newMin.mV[j])
- {
- newMin.mV[j] = min;
- }
-
- if (max > newMax.mV[j])
- {
- newMax.mV[j] = max;
- }
- }
+ LLVector4a delta;
+ delta.setAbs(v[i]);
+ LLVector4a min;
+ min.setSub(center, delta);
+ LLVector4a max;
+ max.setAdd(center, delta);
+
+ newMin.setMin(newMin,min);
+ newMax.setMax(newMax,max);
}
if (!mDrawablep->isActive())
{
- LLVector3 offset = mDrawablep->getRegion()->getOriginAgent();
- newMin += offset;
- newMax += offset;
+ LLVector4a offset;
+ offset.load3(mDrawablep->getRegion()->getOriginAgent().mV);
+ newMin.add(offset);
+ newMax.add(offset);
}
- mCenterLocal = (newMin+newMax)*0.5f;
- LLVector3 tmp = (newMin - newMax) ;
- mBoundingSphereRadius = tmp.length() * 0.5f ;
+ t.setAdd(newMin, newMax);
+ t.mul(0.5f);
+
+ //VECTORIZE THIS
+ mCenterLocal.set(t.getF32ptr());
+
+ t.setSub(newMax,newMin);
+ mBoundingSphereRadius = t.getLength3().getF32()*0.5f;
updateCenterAgent();
}
@@ -703,18 +816,26 @@ LLVector2 LLFace::surfaceToTexture(LLVector2 surface_coord, LLVector3 position,
return surface_coord;
}
+ //VECTORIZE THIS
// see if we have a non-default mapping
U8 texgen = getTextureEntry()->getTexGen();
if (texgen != LLTextureEntry::TEX_GEN_DEFAULT)
{
- LLVector3 center = mDrawablep->getVOVolume()->getVolume()->getVolumeFace(mTEOffset).mCenter;
+ LLVector4a& center = *(mDrawablep->getVOVolume()->getVolume()->getVolumeFace(mTEOffset).mCenter);
- LLVector3 scale = (mDrawablep->getVOVolume()->isVolumeGlobal()) ? LLVector3(1,1,1) : mVObjp->getScale();
- LLVector3 volume_position = mDrawablep->getVOVolume()->agentPositionToVolume(position);
- volume_position.scaleVec(scale);
+ LLVector4a volume_position;
+ volume_position.load3(mDrawablep->getVOVolume()->agentPositionToVolume(position).mV);
- LLVector3 volume_normal = mDrawablep->getVOVolume()->agentDirectionToVolume(normal);
- volume_normal.normalize();
+ if (!mDrawablep->getVOVolume()->isVolumeGlobal())
+ {
+ LLVector4a scale;
+ scale.load3(mVObjp->getScale().mV);
+ volume_position.mul(scale);
+ }
+
+ LLVector4a volume_normal;
+ volume_normal.load3(mDrawablep->getVOVolume()->agentDirectionToVolume(normal).mV);
+ volume_normal.normalize3fast();
switch (texgen)
{
@@ -755,10 +876,10 @@ void LLFace::getPlanarProjectedParams(LLQuaternion* face_rot, LLVector3* face_po
{
const LLMatrix4& vol_mat = getWorldMatrix();
const LLVolumeFace& vf = getViewerObject()->getVolume()->getVolumeFace(mTEOffset);
- LLVector3 normal = vf.mVertices[0].mNormal;
- LLVector3 binormal = vf.mVertices[0].mBinormal;
+ const LLVector4a& normal4a = vf.mNormals[0];
+ const LLVector4a& binormal4a = vf.mBinormals[0];
LLVector2 projected_binormal;
- planarProjection(projected_binormal, normal, vf.mCenter, binormal);
+ planarProjection(projected_binormal, normal4a, *vf.mCenter, binormal4a);
projected_binormal -= LLVector2(0.5f, 0.5f); // this normally happens in xform()
*scale = projected_binormal.length();
// rotate binormal to match what planarProjection() thinks it is,
@@ -766,6 +887,10 @@ void LLFace::getPlanarProjectedParams(LLQuaternion* face_rot, LLVector3* face_po
projected_binormal.normalize();
F32 ang = acos(projected_binormal.mV[VY]);
ang = (projected_binormal.mV[VX] < 0.f) ? -ang : ang;
+
+ //VECTORIZE THIS
+ LLVector3 binormal(binormal4a.getF32ptr());
+ LLVector3 normal(normal4a.getF32ptr());
binormal.rotVec(ang, normal);
LLQuaternion local_rot( binormal % normal, binormal, normal );
*face_rot = local_rot * vol_mat.quaternion();
@@ -848,6 +973,11 @@ void LLFace::updateRebuildFlags()
bool LLFace::canRenderAsMask()
{
+ if (LLPipeline::sNoAlpha)
+ {
+ return true;
+ }
+
const LLTextureEntry* te = getTextureEntry();
return (
(
@@ -869,13 +999,15 @@ static LLFastTimer::DeclareTimer FTM_FACE_GET_GEOM("Face Geom");
BOOL LLFace::getGeometryVolume(const LLVolume& volume,
const S32 &f,
- const LLMatrix4& mat_vert, const LLMatrix3& mat_normal,
- const U16 &index_offset)
+ const LLMatrix4& mat_vert_in, const LLMatrix3& mat_norm_in,
+ const U16 &index_offset,
+ bool force_rebuild)
{
LLFastTimer t(FTM_FACE_GET_GEOM);
+ llassert(verify());
const LLVolumeFace &vf = volume.getVolumeFace(f);
- S32 num_vertices = (S32)vf.mVertices.size();
- S32 num_indices = LLPipeline::sUseTriStrips ? (S32)vf.mTriStrip.size() : (S32) vf.mIndices.size();
+ S32 num_vertices = (S32)vf.mNumVertices;
+ S32 num_indices = (S32) vf.mNumIndices;
if (mVertexBuffer.notNull())
{
@@ -900,15 +1032,20 @@ BOOL LLFace::getGeometryVolume(const LLVolume& volume,
}
}
- LLStrider<LLVector3> vertices;
+ LLStrider<LLVector3> vert;
+ LLVector4a* vertices = NULL;
LLStrider<LLVector2> tex_coords;
LLStrider<LLVector2> tex_coords2;
- LLStrider<LLVector3> normals;
+ LLVector4a* normals = NULL;
+ LLStrider<LLVector3> norm;
LLStrider<LLColor4U> colors;
- LLStrider<LLVector3> binormals;
+ LLVector4a* binormals = NULL;
+ LLStrider<LLVector3> binorm;
LLStrider<U16> indicesp;
+ LLVector4a* weights = NULL;
+ LLStrider<LLVector4> wght;
- BOOL full_rebuild = mDrawablep->isState(LLDrawable::REBUILD_VOLUME);
+ BOOL full_rebuild = force_rebuild || mDrawablep->isState(LLDrawable::REBUILD_VOLUME);
BOOL global_volume = mDrawablep->getVOVolume()->isVolumeGlobal();
LLVector3 scale;
@@ -921,28 +1058,37 @@ BOOL LLFace::getGeometryVolume(const LLVolume& volume,
scale = mVObjp->getScale();
}
- BOOL rebuild_pos = full_rebuild || mDrawablep->isState(LLDrawable::REBUILD_POSITION);
- BOOL rebuild_color = full_rebuild || mDrawablep->isState(LLDrawable::REBUILD_COLOR);
- BOOL rebuild_tcoord = full_rebuild || mDrawablep->isState(LLDrawable::REBUILD_TCOORD);
- BOOL rebuild_normal = rebuild_pos && mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_NORMAL);
- BOOL rebuild_binormal = rebuild_pos && mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_BINORMAL);
+ bool rebuild_pos = full_rebuild || mDrawablep->isState(LLDrawable::REBUILD_POSITION);
+ bool rebuild_color = full_rebuild || mDrawablep->isState(LLDrawable::REBUILD_COLOR);
+ bool rebuild_tcoord = full_rebuild || mDrawablep->isState(LLDrawable::REBUILD_TCOORD);
+ bool rebuild_normal = rebuild_pos && mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_NORMAL);
+ bool rebuild_binormal = rebuild_pos && mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_BINORMAL);
+ bool rebuild_weights = rebuild_pos && mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_WEIGHT4);
const LLTextureEntry *tep = mVObjp->getTE(f);
- U8 bump_code = tep ? tep->getBumpmap() : 0;
+ const U8 bump_code = tep ? tep->getBumpmap() : 0;
if (rebuild_pos)
{
- mVertexBuffer->getVertexStrider(vertices, mGeomIndex);
+ mVertexBuffer->getVertexStrider(vert, mGeomIndex);
+ vertices = (LLVector4a*) vert.get();
}
if (rebuild_normal)
{
- mVertexBuffer->getNormalStrider(normals, mGeomIndex);
+ mVertexBuffer->getNormalStrider(norm, mGeomIndex);
+ normals = (LLVector4a*) norm.get();
}
if (rebuild_binormal)
{
- mVertexBuffer->getBinormalStrider(binormals, mGeomIndex);
+ mVertexBuffer->getBinormalStrider(binorm, mGeomIndex);
+ binormals = (LLVector4a*) binorm.get();
}
-
+ if (rebuild_weights)
+ {
+ mVertexBuffer->getWeight4Strider(wght, mGeomIndex);
+ weights = (LLVector4a*) wght.get();
+ }
+
F32 tcoord_xoffset = 0.f ;
F32 tcoord_yoffset = 0.f ;
F32 tcoord_xscale = 1.f ;
@@ -974,8 +1120,6 @@ BOOL LLFace::getGeometryVolume(const LLVolume& volume,
mVertexBuffer->getColorStrider(colors, mGeomIndex);
}
- F32 r = 0, os = 0, ot = 0, ms = 0, mt = 0, cos_ang = 0, sin_ang = 0;
-
BOOL is_static = mDrawablep->isStatic();
BOOL is_global = is_static;
@@ -990,59 +1134,6 @@ BOOL LLFace::getGeometryVolume(const LLVolume& volume,
clearState(GLOBAL);
}
- LLVector2 tmin, tmax;
-
-
-
- if (rebuild_tcoord)
- {
- if (tep)
- {
- r = tep->getRotation();
- os = tep->mOffsetS;
- ot = tep->mOffsetT;
- ms = tep->mScaleS;
- mt = tep->mScaleT;
- cos_ang = cos(r);
- sin_ang = sin(r);
- }
- else
- {
- cos_ang = 1.0f;
- sin_ang = 0.0f;
- os = 0.0f;
- ot = 0.0f;
- ms = 1.0f;
- mt = 1.0f;
- }
- }
-
- U8 tex_mode = 0;
-
- if (isState(TEXTURE_ANIM))
- {
- LLVOVolume* vobj = (LLVOVolume*) (LLViewerObject*) mVObjp;
- tex_mode = vobj->mTexAnimMode;
-
- if (!tex_mode)
- {
- clearState(TEXTURE_ANIM);
- }
- else
- {
- os = ot = 0.f;
- r = 0.f;
- cos_ang = 1.f;
- sin_ang = 0.f;
- ms = mt = 1.f;
- }
-
- if (getVirtualSize() >= MIN_TEX_ANIM_SIZE)
- { //don't override texture transform during tc bake
- tex_mode = 0;
- }
- }
-
LLColor4U color = tep->getColor();
if (rebuild_color)
@@ -1064,265 +1155,469 @@ BOOL LLFace::getGeometryVolume(const LLVolume& volume,
}
}
- // INDICES
+ // INDICES
if (full_rebuild)
{
mVertexBuffer->getIndexStrider(indicesp, mIndicesIndex);
- if (LLPipeline::sUseTriStrips)
+ __m128i* dst = (__m128i*) indicesp.get();
+ __m128i* src = (__m128i*) vf.mIndices;
+ __m128i offset = _mm_set1_epi16(index_offset);
+
+ S32 end = num_indices/8;
+
+ for (S32 i = 0; i < end; i++)
{
- for (U32 i = 0; i < (U32) num_indices; i++)
- {
- *indicesp++ = vf.mTriStrip[i] + index_offset;
- }
+ __m128i res = _mm_add_epi16(src[i], offset);
+ _mm_storeu_si128(dst+i, res);
}
- else
+
+ for (S32 i = end*8; i < num_indices; ++i)
{
- for (U32 i = 0; i < (U32) num_indices; i++)
- {
- *indicesp++ = vf.mIndices[i] + index_offset;
- }
+ indicesp[i] = vf.mIndices[i]+index_offset;
}
}
+ LLMatrix4a mat_normal;
+ mat_normal.loadu(mat_norm_in);
- //bump setup
- LLVector3 binormal_dir( -sin_ang, cos_ang, 0 );
- LLVector3 bump_s_primary_light_ray;
- LLVector3 bump_t_primary_light_ray;
+ //if it's not fullbright and has no normals, bake sunlight based on face normal
+ //bool bake_sunlight = !getTextureEntry()->getFullbright() &&
+ // !mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_NORMAL);
- LLQuaternion bump_quat;
- if (mDrawablep->isActive())
- {
- bump_quat = LLQuaternion(mDrawablep->getRenderMatrix());
- }
-
- if (bump_code)
+ F32 r = 0, os = 0, ot = 0, ms = 0, mt = 0, cos_ang = 0, sin_ang = 0;
+
+ if (rebuild_tcoord)
{
- mVObjp->getVolume()->genBinormals(f);
- F32 offset_multiple;
- switch( bump_code )
+ bool do_xform;
+
+ if (tep)
{
- case BE_NO_BUMP:
- offset_multiple = 0.f;
- break;
- case BE_BRIGHTNESS:
- case BE_DARKNESS:
- if( mTexture.notNull() && mTexture->hasGLTexture())
+ r = tep->getRotation();
+ os = tep->mOffsetS;
+ ot = tep->mOffsetT;
+ ms = tep->mScaleS;
+ mt = tep->mScaleT;
+ cos_ang = cos(r);
+ sin_ang = sin(r);
+
+ if (cos_ang != 1.f ||
+ sin_ang != 0.f ||
+ os != 0.f ||
+ ot != 0.f ||
+ ms != 1.f ||
+ mt != 1.f)
{
- // Offset by approximately one texel
- S32 cur_discard = mTexture->getDiscardLevel();
- S32 max_size = llmax( mTexture->getWidth(), mTexture->getHeight() );
- max_size <<= cur_discard;
- const F32 ARTIFICIAL_OFFSET = 2.f;
- offset_multiple = ARTIFICIAL_OFFSET / (F32)max_size;
+ do_xform = true;
}
else
{
- offset_multiple = 1.f/256;
- }
- break;
-
- default: // Standard bumpmap textures. Assumed to be 256x256
- offset_multiple = 1.f / 256;
- break;
+ do_xform = false;
+ }
}
-
- F32 s_scale = 1.f;
- F32 t_scale = 1.f;
- if( tep )
+ else
{
- tep->getScale( &s_scale, &t_scale );
+ do_xform = false;
}
- // Use the nudged south when coming from above sun angle, such
- // that emboss mapping always shows up on the upward faces of cubes when
- // it's noon (since a lot of builders build with the sun forced to noon).
- LLVector3 sun_ray = gSky.mVOSkyp->mBumpSunDir;
- LLVector3 moon_ray = gSky.getMoonDirection();
- LLVector3& primary_light_ray = (sun_ray.mV[VZ] > 0) ? sun_ray : moon_ray;
+
+ //bump setup
+ LLVector4a binormal_dir( -sin_ang, cos_ang, 0.f );
+ LLVector4a bump_s_primary_light_ray(0.f, 0.f, 0.f);
+ LLVector4a bump_t_primary_light_ray(0.f, 0.f, 0.f);
- bump_s_primary_light_ray = offset_multiple * s_scale * primary_light_ray;
- bump_t_primary_light_ray = offset_multiple * t_scale * primary_light_ray;
- }
+ LLQuaternion bump_quat;
+ if (mDrawablep->isActive())
+ {
+ bump_quat = LLQuaternion(mDrawablep->getRenderMatrix());
+ }
- U8 texgen = getTextureEntry()->getTexGen();
- if (rebuild_tcoord && texgen != LLTextureEntry::TEX_GEN_DEFAULT)
- { //planar texgen needs binormals
- mVObjp->getVolume()->genBinormals(f);
- }
-
- for (S32 i = 0; i < num_vertices; i++)
- {
- if (rebuild_tcoord)
+ if (bump_code)
{
- LLVector2 tc = vf.mVertices[i].mTexCoord;
-
- if (texgen != LLTextureEntry::TEX_GEN_DEFAULT)
+ mVObjp->getVolume()->genBinormals(f);
+ F32 offset_multiple;
+ switch( bump_code )
{
- LLVector3 vec = vf.mVertices[i].mPosition;
-
- vec.scaleVec(scale);
-
- switch (texgen)
+ case BE_NO_BUMP:
+ offset_multiple = 0.f;
+ break;
+ case BE_BRIGHTNESS:
+ case BE_DARKNESS:
+ if( mTexture.notNull() && mTexture->hasGLTexture())
{
- case LLTextureEntry::TEX_GEN_PLANAR:
- planarProjection(tc, vf.mVertices[i].mNormal, vf.mCenter, vec);
- break;
- case LLTextureEntry::TEX_GEN_SPHERICAL:
- sphericalProjection(tc, vf.mVertices[i].mNormal, vf.mCenter, vec);
- break;
- case LLTextureEntry::TEX_GEN_CYLINDRICAL:
- cylindricalProjection(tc, vf.mVertices[i].mNormal, vf.mCenter, vec);
- break;
- default:
- break;
- }
+ // Offset by approximately one texel
+ S32 cur_discard = mTexture->getDiscardLevel();
+ S32 max_size = llmax( mTexture->getWidth(), mTexture->getHeight() );
+ max_size <<= cur_discard;
+ const F32 ARTIFICIAL_OFFSET = 2.f;
+ offset_multiple = ARTIFICIAL_OFFSET / (F32)max_size;
+ }
+ else
+ {
+ offset_multiple = 1.f/256;
+ }
+ break;
+
+ default: // Standard bumpmap textures. Assumed to be 256x256
+ offset_multiple = 1.f / 256;
+ break;
+ }
+
+ F32 s_scale = 1.f;
+ F32 t_scale = 1.f;
+ if( tep )
+ {
+ tep->getScale( &s_scale, &t_scale );
}
+ // Use the nudged south when coming from above sun angle, such
+ // that emboss mapping always shows up on the upward faces of cubes when
+ // it's noon (since a lot of builders build with the sun forced to noon).
+ LLVector3 sun_ray = gSky.mVOSkyp->mBumpSunDir;
+ LLVector3 moon_ray = gSky.getMoonDirection();
+ LLVector3& primary_light_ray = (sun_ray.mV[VZ] > 0) ? sun_ray : moon_ray;
+
+ bump_s_primary_light_ray.load3((offset_multiple * s_scale * primary_light_ray).mV);
+ bump_t_primary_light_ray.load3((offset_multiple * t_scale * primary_light_ray).mV);
+ }
+
+ U8 texgen = getTextureEntry()->getTexGen();
+ if (rebuild_tcoord && texgen != LLTextureEntry::TEX_GEN_DEFAULT)
+ { //planar texgen needs binormals
+ mVObjp->getVolume()->genBinormals(f);
+ }
- if (tex_mode && mTextureMatrix)
+ U8 tex_mode = 0;
+
+ if (isState(TEXTURE_ANIM))
+ {
+ LLVOVolume* vobj = (LLVOVolume*) (LLViewerObject*) mVObjp;
+ tex_mode = vobj->mTexAnimMode;
+
+ if (!tex_mode)
{
- LLVector3 tmp(tc.mV[0], tc.mV[1], 0.f);
- tmp = tmp * *mTextureMatrix;
- tc.mV[0] = tmp.mV[0];
- tc.mV[1] = tmp.mV[1];
+ clearState(TEXTURE_ANIM);
}
else
{
- xform(tc, cos_ang, sin_ang, os, ot, ms, mt);
+ os = ot = 0.f;
+ r = 0.f;
+ cos_ang = 1.f;
+ sin_ang = 0.f;
+ ms = mt = 1.f;
+
+ do_xform = false;
}
- if(in_atlas)
- {
- //
- //manually calculate tex-coord per vertex for varying address modes.
- //should be removed if shader can handle this.
- //
+ if (getVirtualSize() >= MIN_TEX_ANIM_SIZE)
+ { //don't override texture transform during tc bake
+ tex_mode = 0;
+ }
+ }
- S32 int_part = 0 ;
- switch(mTexture->getAddressMode())
- {
- case LLTexUnit::TAM_CLAMP:
- if(tc.mV[0] < 0.f)
- {
- tc.mV[0] = 0.f ;
- }
- else if(tc.mV[0] > 1.f)
- {
- tc.mV[0] = 1.f;
- }
+ LLVector4a scalea;
+ scalea.load3(scale.mV);
- if(tc.mV[1] < 0.f)
- {
- tc.mV[1] = 0.f ;
- }
- else if(tc.mV[1] > 1.f)
- {
- tc.mV[1] = 1.f;
- }
- break;
- case LLTexUnit::TAM_MIRROR:
- if(tc.mV[0] < 0.f)
- {
- tc.mV[0] = -tc.mV[0] ;
- }
- int_part = (S32)tc.mV[0] ;
- if(int_part & 1) //odd number
- {
- tc.mV[0] = int_part + 1 - tc.mV[0] ;
- }
- else //even number
- {
- tc.mV[0] -= int_part ;
- }
+ bool do_bump = bump_code && mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_TEXCOORD1);
+ bool do_tex_mat = tex_mode && mTextureMatrix;
- if(tc.mV[1] < 0.f)
+ if (!in_atlas && !do_bump)
+ { //not in atlas or not bump mapped, might be able to do a cheap update
+ if (texgen != LLTextureEntry::TEX_GEN_PLANAR)
+ {
+ if (!do_tex_mat)
+ {
+ if (!do_xform)
{
- tc.mV[1] = -tc.mV[1] ;
+ LLVector4a::memcpyNonAliased16((F32*) tex_coords.get(), (F32*) vf.mTexCoords, num_vertices*2*sizeof(F32));
}
- int_part = (S32)tc.mV[1] ;
- if(int_part & 1) //odd number
+ else
{
- tc.mV[1] = int_part + 1 - tc.mV[1] ;
+ for (S32 i = 0; i < num_vertices; i++)
+ {
+ LLVector2 tc(vf.mTexCoords[i]);
+ xform(tc, cos_ang, sin_ang, os, ot, ms, mt);
+ *tex_coords++ = tc;
+ }
}
- else //even number
- {
- tc.mV[1] -= int_part ;
+ }
+ else
+ { //do tex mat, no texgen, no atlas, no bump
+ for (S32 i = 0; i < num_vertices; i++)
+ {
+ LLVector2 tc(vf.mTexCoords[i]);
+ //LLVector4a& norm = vf.mNormals[i];
+ //LLVector4a& center = *(vf.mCenter);
+
+ LLVector3 tmp(tc.mV[0], tc.mV[1], 0.f);
+ tmp = tmp * *mTextureMatrix;
+ tc.mV[0] = tmp.mV[0];
+ tc.mV[1] = tmp.mV[1];
+ *tex_coords++ = tc;
}
- break;
- case LLTexUnit::TAM_WRAP:
- if(tc.mV[0] > 1.f)
- tc.mV[0] -= (S32)(tc.mV[0] - 0.00001f) ;
- else if(tc.mV[0] < -1.f)
- tc.mV[0] -= (S32)(tc.mV[0] + 0.00001f) ;
-
- if(tc.mV[1] > 1.f)
- tc.mV[1] -= (S32)(tc.mV[1] - 0.00001f) ;
- else if(tc.mV[1] < -1.f)
- tc.mV[1] -= (S32)(tc.mV[1] + 0.00001f) ;
-
- if(tc.mV[0] < 0.f)
- {
- tc.mV[0] = 1.0f + tc.mV[0] ;
+ }
+ }
+ else
+ { //no bump, no atlas, tex gen planar
+ if (do_tex_mat)
+ {
+ for (S32 i = 0; i < num_vertices; i++)
+ {
+ LLVector2 tc(vf.mTexCoords[i]);
+ LLVector4a& norm = vf.mNormals[i];
+ LLVector4a& center = *(vf.mCenter);
+ LLVector4a vec = vf.mPositions[i];
+ vec.mul(scalea);
+ planarProjection(tc, norm, center, vec);
+
+ LLVector3 tmp(tc.mV[0], tc.mV[1], 0.f);
+ tmp = tmp * *mTextureMatrix;
+ tc.mV[0] = tmp.mV[0];
+ tc.mV[1] = tmp.mV[1];
+
+ *tex_coords++ = tc;
}
- if(tc.mV[1] < 0.f)
- {
- tc.mV[1] = 1.0f + tc.mV[1] ;
+ }
+ else
+ {
+ for (S32 i = 0; i < num_vertices; i++)
+ {
+ LLVector2 tc(vf.mTexCoords[i]);
+ LLVector4a& norm = vf.mNormals[i];
+ LLVector4a& center = *(vf.mCenter);
+ LLVector4a vec = vf.mPositions[i];
+ vec.mul(scalea);
+ planarProjection(tc, norm, center, vec);
+
+ xform(tc, cos_ang, sin_ang, os, ot, ms, mt);
+
+ *tex_coords++ = tc;
}
- break;
- default:
- break;
}
-
- tc.mV[0] = tcoord_xoffset + tcoord_xscale * tc.mV[0] ;
- tc.mV[1] = tcoord_yoffset + tcoord_yscale * tc.mV[1] ;
}
+ }
+ else
+ { //either bump mapped or in atlas, just do the whole expensive loop
+ for (S32 i = 0; i < num_vertices; i++)
+ {
+ LLVector2 tc(vf.mTexCoords[i]);
+ LLVector4a& norm = vf.mNormals[i];
+
+ LLVector4a& center = *(vf.mCenter);
+
+ if (texgen != LLTextureEntry::TEX_GEN_DEFAULT)
+ {
+ LLVector4a vec = vf.mPositions[i];
+
+ vec.mul(scalea);
- *tex_coords++ = tc;
-
- if (bump_code && mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_TEXCOORD1))
- {
- LLVector3 tangent = vf.mVertices[i].mBinormal % vf.mVertices[i].mNormal;
+ switch (texgen)
+ {
+ case LLTextureEntry::TEX_GEN_PLANAR:
+ planarProjection(tc, norm, center, vec);
+ break;
+ case LLTextureEntry::TEX_GEN_SPHERICAL:
+ sphericalProjection(tc, norm, center, vec);
+ break;
+ case LLTextureEntry::TEX_GEN_CYLINDRICAL:
+ cylindricalProjection(tc, norm, center, vec);
+ break;
+ default:
+ break;
+ }
+ }
- LLMatrix3 tangent_to_object;
- tangent_to_object.setRows(tangent, vf.mVertices[i].mBinormal, vf.mVertices[i].mNormal);
- LLVector3 binormal = binormal_dir * tangent_to_object;
- binormal = binormal * mat_normal;
-
- if (mDrawablep->isActive())
+ if (tex_mode && mTextureMatrix)
+ {
+ LLVector3 tmp(tc.mV[0], tc.mV[1], 0.f);
+ tmp = tmp * *mTextureMatrix;
+ tc.mV[0] = tmp.mV[0];
+ tc.mV[1] = tmp.mV[1];
+ }
+ else
{
- binormal *= bump_quat;
+ xform(tc, cos_ang, sin_ang, os, ot, ms, mt);
}
- binormal.normVec();
- tc += LLVector2( bump_s_primary_light_ray * tangent, bump_t_primary_light_ray * binormal );
+ if(in_atlas)
+ {
+ //
+ //manually calculate tex-coord per vertex for varying address modes.
+ //should be removed if shader can handle this.
+ //
+
+ S32 int_part = 0 ;
+ switch(mTexture->getAddressMode())
+ {
+ case LLTexUnit::TAM_CLAMP:
+ if(tc.mV[0] < 0.f)
+ {
+ tc.mV[0] = 0.f ;
+ }
+ else if(tc.mV[0] > 1.f)
+ {
+ tc.mV[0] = 1.f;
+ }
+
+ if(tc.mV[1] < 0.f)
+ {
+ tc.mV[1] = 0.f ;
+ }
+ else if(tc.mV[1] > 1.f)
+ {
+ tc.mV[1] = 1.f;
+ }
+ break;
+ case LLTexUnit::TAM_MIRROR:
+ if(tc.mV[0] < 0.f)
+ {
+ tc.mV[0] = -tc.mV[0] ;
+ }
+ int_part = (S32)tc.mV[0] ;
+ if(int_part & 1) //odd number
+ {
+ tc.mV[0] = int_part + 1 - tc.mV[0] ;
+ }
+ else //even number
+ {
+ tc.mV[0] -= int_part ;
+ }
+
+ if(tc.mV[1] < 0.f)
+ {
+ tc.mV[1] = -tc.mV[1] ;
+ }
+ int_part = (S32)tc.mV[1] ;
+ if(int_part & 1) //odd number
+ {
+ tc.mV[1] = int_part + 1 - tc.mV[1] ;
+ }
+ else //even number
+ {
+ tc.mV[1] -= int_part ;
+ }
+ break;
+ case LLTexUnit::TAM_WRAP:
+ if(tc.mV[0] > 1.f)
+ tc.mV[0] -= (S32)(tc.mV[0] - 0.00001f) ;
+ else if(tc.mV[0] < -1.f)
+ tc.mV[0] -= (S32)(tc.mV[0] + 0.00001f) ;
+
+ if(tc.mV[1] > 1.f)
+ tc.mV[1] -= (S32)(tc.mV[1] - 0.00001f) ;
+ else if(tc.mV[1] < -1.f)
+ tc.mV[1] -= (S32)(tc.mV[1] + 0.00001f) ;
+
+ if(tc.mV[0] < 0.f)
+ {
+ tc.mV[0] = 1.0f + tc.mV[0] ;
+ }
+ if(tc.mV[1] < 0.f)
+ {
+ tc.mV[1] = 1.0f + tc.mV[1] ;
+ }
+ break;
+ default:
+ break;
+ }
- *tex_coords2++ = tc;
- }
+ tc.mV[0] = tcoord_xoffset + tcoord_xscale * tc.mV[0] ;
+ tc.mV[1] = tcoord_yoffset + tcoord_yscale * tc.mV[1] ;
+ }
+
+
+ *tex_coords++ = tc;
+
+ if (bump_code && mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_TEXCOORD1))
+ {
+ LLVector4a tangent;
+ tangent.setCross3(vf.mBinormals[i], vf.mNormals[i]);
+
+ LLMatrix4a tangent_to_object;
+ tangent_to_object.setRows(tangent, vf.mBinormals[i], vf.mNormals[i]);
+ LLVector4a t;
+ tangent_to_object.rotate(binormal_dir, t);
+ LLVector4a binormal;
+ mat_normal.rotate(t, binormal);
+
+ //VECTORIZE THIS
+ if (mDrawablep->isActive())
+ {
+ LLVector3 t;
+ t.set(binormal.getF32ptr());
+ t *= bump_quat;
+ binormal.load3(t.mV);
+ }
+
+ binormal.normalize3fast();
+ tc += LLVector2( bump_s_primary_light_ray.dot3(tangent).getF32(), bump_t_primary_light_ray.dot3(binormal).getF32() );
+
+ *tex_coords2++ = tc;
+ }
+ }
}
-
- if (rebuild_pos)
- {
- *vertices++ = vf.mVertices[i].mPosition * mat_vert;
+ }
+
+ if (rebuild_pos)
+ {
+ LLMatrix4a mat_vert;
+ mat_vert.loadu(mat_vert_in);
+
+ LLVector4a* src = vf.mPositions;
+ LLVector4a* dst = vertices;
+
+ LLVector4a* end = dst+num_vertices;
+ do
+ {
+ mat_vert.affineTransform(*src++, *dst++);
}
+ while(dst < end);
+ }
- if (rebuild_normal)
- {
- LLVector3 normal = vf.mVertices[i].mNormal * mat_normal;
- normal.normVec();
-
- *normals++ = normal;
+ if (rebuild_normal)
+ {
+ for (S32 i = 0; i < num_vertices; i++)
+ {
+ LLVector4a normal;
+ mat_normal.rotate(vf.mNormals[i], normal);
+ normal.normalize3fast();
+ normals[i] = normal;
}
+ }
- if (rebuild_binormal)
- {
- LLVector3 binormal = vf.mVertices[i].mBinormal * mat_normal;
- binormal.normVec();
- *binormals++ = binormal;
+ if (rebuild_binormal)
+ {
+ for (S32 i = 0; i < num_vertices; i++)
+ {
+ LLVector4a binormal;
+ mat_normal.rotate(vf.mBinormals[i], binormal);
+ binormal.normalize3fast();
+ binormals[i] = binormal;
}
+ }
+
+ if (rebuild_weights && vf.mWeights)
+ {
+ LLVector4a::memcpyNonAliased16((F32*) weights, (F32*) vf.mWeights, num_vertices*4*sizeof(F32));
+ }
+
+ if (rebuild_color)
+ {
+ LLVector4a src;
+
+ U32 vec[4];
+ vec[0] = vec[1] = vec[2] = vec[3] = color.mAll;
- if (rebuild_color)
+ src.loadua((F32*) vec);
+
+ LLVector4a* dst = (LLVector4a*) colors.get();
+ S32 num_vecs = num_vertices/4;
+ if (num_vertices%4 > 0)
{
- *colors++ = color;
+ ++num_vecs;
+ }
+
+ for (S32 i = 0; i < num_vecs; i++)
+ {
+ dst[i] = src;
}
}
@@ -1418,20 +1713,31 @@ F32 LLFace::getTextureVirtualSize()
BOOL LLFace::calcPixelArea(F32& cos_angle_to_view_dir, F32& radius)
{
+ //VECTORIZE THIS
//get area of circle around face
- LLVector3 center = getPositionAgent();
- LLVector3 size = (mExtents[1] - mExtents[0]) * 0.5f;
+ LLVector4a center;
+ center.load3(getPositionAgent().mV);
+ LLVector4a size;
+ size.setSub(mExtents[1], mExtents[0]);
+ size.mul(0.5f);
+
LLViewerCamera* camera = LLViewerCamera::getInstance();
- F32 size_squared = size.lengthSquared() ;
- LLVector3 lookAt = center - camera->getOrigin();
- F32 dist = lookAt.normVec() ;
+ F32 size_squared = size.dot3(size).getF32();
+ LLVector4a lookAt;
+ LLVector4a t;
+ t.load3(camera->getOrigin().mV);
+ lookAt.setSub(center, t);
+ F32 dist = lookAt.getLength3().getF32();
+ lookAt.normalize3fast() ;
//get area of circle around node
- F32 app_angle = atanf(fsqrtf(size_squared) / dist);
+ F32 app_angle = atanf((F32) sqrt(size_squared) / dist);
radius = app_angle*LLDrawable::sCurPixelAngle;
mPixelArea = radius*radius * 3.14159f;
- cos_angle_to_view_dir = lookAt * camera->getXAxis() ;
+ LLVector4a x_axis;
+ x_axis.load3(camera->getXAxis().mV);
+ cos_angle_to_view_dir = lookAt.dot3(x_axis).getF32();
//if has media, check if the face is out of the view frustum.
if(hasMedia())
@@ -1447,7 +1753,10 @@ BOOL LLFace::calcPixelArea(F32& cos_angle_to_view_dir, F32& radius)
}
else
{
- if(dist * dist * (lookAt - camera->getXAxis()).lengthSquared() < size_squared)
+ LLVector4a d;
+ d.setSub(lookAt, x_axis);
+
+ if(dist * dist * d.dot3(d) < size_squared)
{
cos_angle_to_view_dir = 1.0f ;
}
@@ -1562,24 +1871,15 @@ BOOL LLFace::verify(const U32* indices_array) const
BOOL ok = TRUE;
if( mVertexBuffer.isNull() )
- {
- if( mGeomCount )
- {
- // This happens before teleports as faces are torn down.
- // Stop the crash in DEV-31893 with a null pointer check,
- // but present this info.
- // To clean up the log, the geometry could be cleared, or the
- // face could otherwise be marked for no ::verify.
- llinfos << "Face with no vertex buffer and " << mGeomCount << " mGeomCount" << llendl;
- }
+ { //no vertex buffer, face is implicitly valid
return TRUE;
}
// First, check whether the face data fits within the pool's range.
- if ((mGeomIndex + mGeomCount) > mVertexBuffer->getNumVerts())
+ if ((mGeomIndex + mGeomCount) > mVertexBuffer->getRequestedVerts())
{
ok = FALSE;
- llinfos << "Face not within pool range!" << llendl;
+ llinfos << "Face references invalid vertices!" << llendl;
}
S32 indices_count = (S32)getIndicesCount();
@@ -1595,6 +1895,12 @@ BOOL LLFace::verify(const U32* indices_array) const
llinfos << "Face has bogus indices count" << llendl;
}
+ if (mIndicesIndex + mIndicesCount > mVertexBuffer->getRequestedIndices())
+ {
+ ok = FALSE;
+ llinfos << "Face references invalid indices!" << llendl;
+ }
+
#if 0
S32 geom_start = getGeomStart();
S32 geom_count = mGeomCount;
@@ -1903,3 +2209,78 @@ BOOL LLFace::switchTexture()
return mUsingAtlas ;
}
+
+void LLFace::setVertexBuffer(LLVertexBuffer* buffer)
+{
+ mVertexBuffer = buffer;
+ llassert(verify());
+}
+
+void LLFace::clearVertexBuffer()
+{
+ mVertexBuffer = NULL;
+ mLastVertexBuffer = NULL;
+}
+
+//static
+U32 LLFace::getRiggedDataMask(U32 type)
+{
+ static const U32 rigged_data_mask[] = {
+ LLDrawPoolAvatar::RIGGED_SIMPLE_MASK,
+ LLDrawPoolAvatar::RIGGED_FULLBRIGHT_MASK,
+ LLDrawPoolAvatar::RIGGED_SHINY_MASK,
+ LLDrawPoolAvatar::RIGGED_FULLBRIGHT_SHINY_MASK,
+ LLDrawPoolAvatar::RIGGED_GLOW_MASK,
+ LLDrawPoolAvatar::RIGGED_ALPHA_MASK,
+ LLDrawPoolAvatar::RIGGED_FULLBRIGHT_ALPHA_MASK,
+ LLDrawPoolAvatar::RIGGED_DEFERRED_BUMP_MASK,
+ LLDrawPoolAvatar::RIGGED_DEFERRED_SIMPLE_MASK,
+ };
+
+ llassert(type < sizeof(rigged_data_mask)/sizeof(U32));
+
+ return rigged_data_mask[type];
+}
+
+U32 LLFace::getRiggedVertexBufferDataMask() const
+{
+ U32 data_mask = 0;
+ for (U32 i = 0; i < mRiggedIndex.size(); ++i)
+ {
+ if (mRiggedIndex[i] > -1)
+ {
+ data_mask |= LLFace::getRiggedDataMask(i);
+ }
+ }
+
+ return data_mask;
+}
+
+S32 LLFace::getRiggedIndex(U32 type) const
+{
+ if (mRiggedIndex.empty())
+ {
+ return -1;
+ }
+
+ llassert(type < mRiggedIndex.size());
+
+ return mRiggedIndex[type];
+}
+
+void LLFace::setRiggedIndex(U32 type, S32 index)
+{
+ if (mRiggedIndex.empty())
+ {
+ mRiggedIndex.resize(LLDrawPoolAvatar::NUM_RIGGED_PASSES);
+ for (U32 i = 0; i < mRiggedIndex.size(); ++i)
+ {
+ mRiggedIndex[i] = -1;
+ }
+ }
+
+ llassert(type < mRiggedIndex.size());
+
+ mRiggedIndex[type] = index;
+}
+
diff --git a/indra/newview/llface.h b/indra/newview/llface.h
index 6c941bd092..b2170c4cf3 100644
--- a/indra/newview/llface.h
+++ b/indra/newview/llface.h
@@ -59,6 +59,17 @@ class LLFace
{
public:
+ LLFace(const LLFace& rhs)
+ {
+ *this = rhs;
+ }
+
+ const LLFace& operator=(const LLFace& rhs)
+ {
+ llerrs << "Illegal operation!" << llendl;
+ return *this;
+ }
+
enum EMasks
{
LIGHT = 0x0001,
@@ -67,6 +78,7 @@ public:
HUD_RENDER = 0x0008,
USE_FACE_COLOR = 0x0010,
TEXTURE_ANIM = 0x0020,
+ RIGGED = 0x0040,
};
static void initClass();
@@ -119,14 +131,14 @@ public:
LLDrawable* getDrawable() const { return mDrawablep; }
LLViewerObject* getViewerObject() const { return mVObjp; }
S32 getLOD() const { return mVObjp.notNull() ? mVObjp->getLOD() : 0; }
- LLVertexBuffer* getVertexBuffer() const { return mVertexBuffer; }
void setPoolType(U32 type) { mPoolType = type; }
S32 getTEOffset() { return mTEOffset; }
LLViewerTexture* getTexture() const;
void setViewerObject(LLViewerObject* object);
void setPool(LLFacePool *pool, LLViewerTexture *texturep);
-
+ void setPool(LLFacePool* pool);
+
void setDrawable(LLDrawable *drawable);
void setTEOffset(const S32 te_offset);
@@ -142,7 +154,8 @@ public:
BOOL getGeometryVolume(const LLVolume& volume,
const S32 &f,
const LLMatrix4& mat_vert, const LLMatrix3& mat_normal,
- const U16 &index_offset);
+ const U16 &index_offset,
+ bool force_rebuild = false);
// For avatar
U16 getGeometryAvatar(
@@ -161,7 +174,7 @@ public:
S32 getColors(LLStrider<LLColor4U> &colors);
S32 getIndices(LLStrider<U16> &indices);
- void setSize(const S32 numVertices, const S32 num_indices = 0);
+ void setSize(S32 numVertices, S32 num_indices = 0, bool align = false);
BOOL genVolumeBBoxes(const LLVolume &volume, S32 f,
const LLMatrix4& mat, const LLMatrix3& inv_trans_mat, BOOL global_volume = FALSE);
@@ -183,8 +196,8 @@ public:
BOOL verify(const U32* indices_array = NULL) const;
void printDebugInfo() const;
- void setGeomIndex(U16 idx) { mGeomIndex = idx; }
- void setIndicesIndex(S32 idx) { mIndicesIndex = idx; }
+ void setGeomIndex(U16 idx);
+ void setIndicesIndex(S32 idx);
void setDrawInfo(LLDrawInfo* draw_info);
F32 getTextureVirtualSize() ;
@@ -205,6 +218,19 @@ public:
void removeAtlas() ;
BOOL switchTexture() ;
+ //vertex buffer tracking
+ void setVertexBuffer(LLVertexBuffer* buffer);
+ void clearVertexBuffer(); //sets mVertexBuffer and mLastVertexBuffer to NULL
+ LLVertexBuffer* getVertexBuffer() const { return mVertexBuffer; }
+ U32 getRiggedVertexBufferDataMask() const;
+ S32 getRiggedIndex(U32 type) const;
+ void setRiggedIndex(U32 type, S32 index);
+
+ static U32 getRiggedDataMask(U32 type);
+
+public: //aligned members
+ LLVector4a mExtents[2];
+
private:
F32 adjustPartialOverlapPixelArea(F32 cos_angle_to_view_dir, F32 radius );
BOOL calcPixelArea(F32& cos_angle_to_view_dir, F32& radius) ;
@@ -216,20 +242,19 @@ public:
LLVector3 mCenterLocal;
LLVector3 mCenterAgent;
- LLVector3 mExtents[2];
+
LLVector2 mTexExtents[2];
F32 mDistance;
- LLPointer<LLVertexBuffer> mVertexBuffer;
- LLPointer<LLVertexBuffer> mLastVertexBuffer;
F32 mLastUpdateTime;
+ F32 mLastSkinTime;
F32 mLastMoveTime;
LLMatrix4* mTextureMatrix;
LLDrawInfo* mDrawInfo;
private:
- friend class LLGeometryManager;
- friend class LLVolumeGeometryManager;
-
+ LLPointer<LLVertexBuffer> mVertexBuffer;
+ LLPointer<LLVertexBuffer> mLastVertexBuffer;
+
U32 mState;
LLFacePool* mDrawPoolp;
U32 mPoolType;
@@ -254,6 +279,8 @@ private:
S32 mTEOffset;
S32 mReferenceIndex;
+ std::vector<S32> mRiggedIndex;
+
F32 mVSize;
F32 mPixelArea;
diff --git a/indra/newview/llfasttimerview.cpp b/indra/newview/llfasttimerview.cpp
index 92a3b9b2f5..2bafb9a4a7 100644..100755
--- a/indra/newview/llfasttimerview.cpp
+++ b/indra/newview/llfasttimerview.cpp
@@ -32,7 +32,9 @@
#include "llrect.h"
#include "llerror.h"
#include "llgl.h"
+#include "llimagepng.h"
#include "llrender.h"
+#include "llrendertarget.h"
#include "lllocalcliprect.h"
#include "llmath.h"
#include "llfontgl.h"
@@ -49,6 +51,8 @@
#include "llfasttimer.h"
#include "lltreeiterators.h"
#include "llmetricperformancetester.h"
+#include "llviewerstats.h"
+
//////////////////////////////////////////////////////////////////////////////
static const S32 MAX_VISIBLE_HISTORY = 10;
@@ -1020,6 +1024,364 @@ F64 LLFastTimerView::getTime(const std::string& name)
return 0.0;
}
+void saveChart(const std::string& label, const char* suffix, LLImageRaw* scratch)
+{
+ //read result back into raw image
+ glReadPixels(0, 0, 1024, 512, GL_RGB, GL_UNSIGNED_BYTE, scratch->getData());
+
+ //write results to disk
+ LLPointer<LLImagePNG> result = new LLImagePNG();
+ result->encode(scratch, 0.f);
+
+ std::string ext = result->getExtension();
+ std::string filename = llformat("%s_%s.%s", label.c_str(), suffix, ext.c_str());
+
+ std::string out_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, filename);
+ result->save(out_file);
+}
+
+template <class VEC_TYPE>
+void removeOutliers(std::vector<VEC_TYPE>& data, F32 k)
+{
+ if (data.size() < 100)
+ { //not enough samples
+ return;
+ }
+
+ VEC_TYPE Q1 = data[data.size()/4];
+ VEC_TYPE Q3 = data[data.size()-data.size()/4-1];
+
+ VEC_TYPE min = Q1-k*(Q3-Q1);
+ VEC_TYPE max = Q3+k*(Q3-Q1);
+
+ U32 i = 0;
+ while (i < data.size() && data[i] < min)
+ {
+ i++;
+ }
+
+ S32 j = data.size()-1;
+ while (j > 0 && data[j] > max)
+ {
+ j--;
+ }
+
+ if (j < data.size()-1)
+ {
+ data.erase(data.begin()+j, data.end());
+ }
+
+ if (i > 0)
+ {
+ data.erase(data.begin(), data.begin()+i);
+ }
+}
+
+//static
+void LLFastTimerView::exportCharts(const std::string& base, const std::string& target)
+{
+ //allocate render target for drawing charts
+ LLRenderTarget buffer;
+ buffer.allocate(1024,512, GL_RGB, FALSE, FALSE);
+
+
+ LLSD cur;
+
+ LLSD base_data;
+
+ { //read base log into memory
+ S32 i = 0;
+ std::ifstream is(base.c_str());
+ while (!is.eof() && LLSDSerialize::fromXML(cur, is))
+ {
+ base_data[i++] = cur;
+ }
+ is.close();
+ }
+
+ LLSD cur_data;
+ std::set<std::string> chart_names;
+
+ { //read current log into memory
+ S32 i = 0;
+ std::ifstream is(target.c_str());
+ while (!is.eof() && LLSDSerialize::fromXML(cur, is))
+ {
+ cur_data[i++] = cur;
+
+ for (LLSD::map_iterator iter = cur.beginMap(); iter != cur.endMap(); ++iter)
+ {
+ std::string label = iter->first;
+ chart_names.insert(label);
+ }
+ }
+ is.close();
+ }
+
+ //get time domain
+ LLSD::Real cur_total_time = 0.0;
+
+ for (U32 i = 0; i < cur_data.size(); ++i)
+ {
+ cur_total_time += cur_data[i]["Total"]["Time"].asReal();
+ }
+
+ LLSD::Real base_total_time = 0.0;
+ for (U32 i = 0; i < base_data.size(); ++i)
+ {
+ base_total_time += base_data[i]["Total"]["Time"].asReal();
+ }
+
+ //allocate raw scratch space
+ LLPointer<LLImageRaw> scratch = new LLImageRaw(1024, 512, 3);
+
+ gGL.pushMatrix();
+ glLoadIdentity();
+ glMatrixMode(GL_PROJECTION);
+ glLoadIdentity();
+ glOrtho(-0.05, 1.05, -0.05, 1.05, -1.0, 1.0);
+
+ //render charts
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+
+ buffer.bindTarget();
+
+ for (std::set<std::string>::iterator iter = chart_names.begin(); iter != chart_names.end(); ++iter)
+ {
+ std::string label = *iter;
+
+ LLSD::Real max_time = 0.0;
+ LLSD::Integer max_calls = 0;
+ LLSD::Real max_execution = 0.0;
+
+ std::vector<LLSD::Real> cur_execution;
+ std::vector<LLSD::Real> cur_times;
+ std::vector<LLSD::Integer> cur_calls;
+
+ std::vector<LLSD::Real> base_execution;
+ std::vector<LLSD::Real> base_times;
+ std::vector<LLSD::Integer> base_calls;
+
+ for (U32 i = 0; i < cur_data.size(); ++i)
+ {
+ LLSD::Real time = cur_data[i][label]["Time"].asReal();
+ LLSD::Integer calls = cur_data[i][label]["Calls"].asInteger();
+
+ LLSD::Real execution = 0.0;
+ if (calls > 0)
+ {
+ execution = time/calls;
+ cur_execution.push_back(execution);
+ cur_times.push_back(time);
+ }
+
+ cur_calls.push_back(calls);
+ }
+
+ for (U32 i = 0; i < base_data.size(); ++i)
+ {
+ LLSD::Real time = base_data[i][label]["Time"].asReal();
+ LLSD::Integer calls = base_data[i][label]["Calls"].asInteger();
+
+ LLSD::Real execution = 0.0;
+ if (calls > 0)
+ {
+ execution = time/calls;
+ base_execution.push_back(execution);
+ base_times.push_back(time);
+ }
+
+ base_calls.push_back(calls);
+ }
+
+ std::sort(base_calls.begin(), base_calls.end());
+ std::sort(base_times.begin(), base_times.end());
+ std::sort(base_execution.begin(), base_execution.end());
+
+ std::sort(cur_calls.begin(), cur_calls.end());
+ std::sort(cur_times.begin(), cur_times.end());
+ std::sort(cur_execution.begin(), cur_execution.end());
+
+ //remove outliers
+ const U32 OUTLIER_CUTOFF = 512;
+ if (base_times.size() > OUTLIER_CUTOFF)
+ {
+ removeOutliers(base_times, 1.f);
+ }
+
+ if (base_execution.size() > OUTLIER_CUTOFF)
+ {
+ removeOutliers(base_execution, 1.f);
+ }
+
+ if (cur_times.size() > OUTLIER_CUTOFF)
+ {
+ removeOutliers(cur_times, 1.f);
+ }
+
+ if (cur_execution.size() > OUTLIER_CUTOFF)
+ {
+ removeOutliers(cur_execution, 1.f);
+ }
+
+
+ max_time = llmax(base_times.empty() ? 0.0 : *base_times.rbegin(), cur_times.empty() ? 0.0 : *cur_times.rbegin());
+ max_calls = llmax(base_calls.empty() ? 0 : *base_calls.rbegin(), cur_calls.empty() ? 0 : *cur_calls.rbegin());
+ max_execution = llmax(base_execution.empty() ? 0.0 : *base_execution.rbegin(), cur_execution.empty() ? 0.0 : *cur_execution.rbegin());
+
+
+ LLVector3 last_p;
+
+ //====================================
+ // basic
+ //====================================
+ buffer.clear();
+
+ last_p.clear();
+
+ LLGLDisable cull(GL_CULL_FACE);
+
+ LLVector3 base_col(0, 0.7f, 0.f);
+ LLVector3 cur_col(1.f, 0.f, 0.f);
+
+ gGL.setSceneBlendType(LLRender::BT_ADD);
+
+ gGL.color3fv(base_col.mV);
+ for (U32 i = 0; i < base_times.size(); ++i)
+ {
+ gGL.begin(LLRender::TRIANGLE_STRIP);
+ gGL.vertex3fv(last_p.mV);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ last_p.set((F32)i/(F32) base_times.size(), base_times[i]/max_time, 0.f);
+ gGL.vertex3fv(last_p.mV);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ gGL.end();
+ }
+
+ gGL.flush();
+
+
+ last_p.clear();
+ {
+ LLGLEnable blend(GL_BLEND);
+
+ gGL.color3fv(cur_col.mV);
+ for (U32 i = 0; i < cur_times.size(); ++i)
+ {
+ gGL.begin(LLRender::TRIANGLE_STRIP);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ gGL.vertex3fv(last_p.mV);
+ last_p.set((F32) i / (F32) cur_times.size(), cur_times[i]/max_time, 0.f);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ gGL.vertex3fv(last_p.mV);
+ gGL.end();
+ }
+
+ gGL.flush();
+ }
+
+ saveChart(label, "time", scratch);
+
+ //======================================
+ // calls
+ //======================================
+ buffer.clear();
+
+ last_p.clear();
+
+ gGL.color3fv(base_col.mV);
+ for (U32 i = 0; i < base_calls.size(); ++i)
+ {
+ gGL.begin(LLRender::TRIANGLE_STRIP);
+ gGL.vertex3fv(last_p.mV);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ last_p.set((F32) i / (F32) base_calls.size(), (F32)base_calls[i]/max_calls, 0.f);
+ gGL.vertex3fv(last_p.mV);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ gGL.end();
+ }
+
+ gGL.flush();
+
+ {
+ LLGLEnable blend(GL_BLEND);
+ gGL.color3fv(cur_col.mV);
+ last_p.clear();
+
+ for (U32 i = 0; i < cur_calls.size(); ++i)
+ {
+ gGL.begin(LLRender::TRIANGLE_STRIP);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ gGL.vertex3fv(last_p.mV);
+ last_p.set((F32) i / (F32) cur_calls.size(), (F32) cur_calls[i]/max_calls, 0.f);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ gGL.vertex3fv(last_p.mV);
+ gGL.end();
+
+ }
+
+ gGL.flush();
+ }
+
+ saveChart(label, "calls", scratch);
+
+ //======================================
+ // execution
+ //======================================
+ buffer.clear();
+
+
+ gGL.color3fv(base_col.mV);
+ U32 count = 0;
+ U32 total_count = base_execution.size();
+
+ last_p.clear();
+
+ for (std::vector<LLSD::Real>::iterator iter = base_execution.begin(); iter != base_execution.end(); ++iter)
+ {
+ gGL.begin(LLRender::TRIANGLE_STRIP);
+ gGL.vertex3fv(last_p.mV);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ last_p.set((F32)count/(F32)total_count, *iter/max_execution, 0.f);
+ gGL.vertex3fv(last_p.mV);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ gGL.end();
+ count++;
+ }
+
+ last_p.clear();
+
+ {
+ LLGLEnable blend(GL_BLEND);
+ gGL.color3fv(cur_col.mV);
+ count = 0;
+ total_count = cur_execution.size();
+
+ for (std::vector<LLSD::Real>::iterator iter = cur_execution.begin(); iter != cur_execution.end(); ++iter)
+ {
+ gGL.begin(LLRender::TRIANGLE_STRIP);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ gGL.vertex3fv(last_p.mV);
+ last_p.set((F32)count/(F32)total_count, *iter/max_execution, 0.f);
+ gGL.vertex3f(last_p.mV[0], 0.f, 0.f);
+ gGL.vertex3fv(last_p.mV);
+ gGL.end();
+ count++;
+ }
+
+ gGL.flush();
+ }
+
+ saveChart(label, "execution", scratch);
+ }
+
+ buffer.flush();
+
+ gGL.popMatrix();
+ glMatrixMode(GL_MODELVIEW);
+ gGL.popMatrix();
+}
+
//static
LLSD LLFastTimerView::analyzePerformanceLogDefault(std::istream& is)
{
@@ -1030,6 +1392,10 @@ LLSD LLFastTimerView::analyzePerformanceLogDefault(std::istream& is)
LLSD::Real total_time = 0.0;
LLSD::Integer total_frames = 0;
+ typedef std::map<std::string,LLViewerStats::StatsAccumulator> stats_map_t;
+ stats_map_t time_stats;
+ stats_map_t sample_stats;
+
while (!is.eof() && LLSDSerialize::fromXML(cur, is))
{
for (LLSD::map_iterator iter = cur.beginMap(); iter != cur.endMap(); ++iter)
@@ -1046,35 +1412,31 @@ LLSD LLFastTimerView::analyzePerformanceLogDefault(std::istream& is)
if (time > 0.0)
{
- ret[label]["TotalTime"] = ret[label]["TotalTime"].asReal() + time;
- ret[label]["MaxTime"] = llmax(time, ret[label]["MaxTime"].asReal());
-
- if (ret[label]["MinTime"].asReal() == 0)
- {
- ret[label]["MinTime"] = time;
- }
- else
- {
- ret[label]["MinTime"] = llmin(ret[label]["MinTime"].asReal(), time);
- }
-
LLSD::Integer samples = iter->second["Calls"].asInteger();
- ret[label]["Samples"] = ret[label]["Samples"].asInteger() + samples;
- ret[label]["MaxSamples"] = llmax(ret[label]["MaxSamples"].asInteger(), samples);
-
- if (ret[label]["MinSamples"].asInteger() == 0)
- {
- ret[label]["MinSamples"] = samples;
- }
- else
- {
- ret[label]["MinSamples"] = llmin(ret[label]["MinSamples"].asInteger(), samples);
- }
+ time_stats[label].push(time);
+ sample_stats[label].push(samples);
}
}
total_frames++;
}
+
+ for(stats_map_t::iterator it = time_stats.begin(); it != time_stats.end(); ++it)
+ {
+ std::string label = it->first;
+ ret[label]["TotalTime"] = time_stats[label].mSum;
+ ret[label]["MeanTime"] = time_stats[label].getMean();
+ ret[label]["MaxTime"] = time_stats[label].getMaxValue();
+ ret[label]["MinTime"] = time_stats[label].getMinValue();
+ ret[label]["StdDevTime"] = time_stats[label].getStdDev();
+
+ ret[label]["Samples"] = sample_stats[label].mSum;
+ ret[label]["MaxSamples"] = sample_stats[label].getMaxValue();
+ ret[label]["MinSamples"] = sample_stats[label].getMinValue();
+ ret[label]["StdDevSamples"] = sample_stats[label].getStdDev();
+
+ ret[label]["Frames"] = (LLSD::Integer)time_stats[label].getCount();
+ }
ret["SessionTime"] = total_time;
ret["FrameCount"] = total_frames;
@@ -1109,8 +1471,27 @@ void LLFastTimerView::doAnalysisDefault(std::string baseline, std::string target
std::ofstream os(output.c_str());
LLSD::Real session_time = current["SessionTime"].asReal();
-
- os << "Label, % Change, % of Session, Cur Min, Cur Max, Cur Mean, Cur Total, Cur Samples, Base Min, Base Max, Base Mean, Base Total, Base Samples\n";
+ os <<
+ "Label, "
+ "% Change, "
+ "% of Session, "
+ "Cur Min, "
+ "Cur Max, "
+ "Cur Mean/sample, "
+ "Cur Mean/frame, "
+ "Cur StdDev/frame, "
+ "Cur Total, "
+ "Cur Frames, "
+ "Cur Samples, "
+ "Base Min, "
+ "Base Max, "
+ "Base Mean/sample, "
+ "Base Mean/frame, "
+ "Base StdDev/frame, "
+ "Base Total, "
+ "Base Frames, "
+ "Base Samples\n";
+
for (LLSD::map_iterator iter = base.beginMap(); iter != base.endMap(); ++iter)
{
LLSD::String label = iter->first;
@@ -1122,29 +1503,37 @@ void LLFastTimerView::doAnalysisDefault(std::string baseline, std::string target
continue;
}
LLSD::Real a = base[label]["TotalTime"].asReal() / base[label]["Samples"].asReal();
- LLSD::Real b = current[label]["TotalTime"].asReal() / base[label]["Samples"].asReal();
+ LLSD::Real b = current[label]["TotalTime"].asReal() / current[label]["Samples"].asReal();
LLSD::Real diff = b-a;
LLSD::Real perc = diff/a * 100;
- os << llformat("%s, %.2f, %.4f, %.4f, %.4f, %.4f, %.4f, %d, %.4f, %.4f, %.4f, %.4f, %d\n",
+ os << llformat("%s, %.2f, %.4f, %.4f, %.4f, %.4f, %.4f, %.4f, %.4f, %d, %d, %.4f, %.4f, %.4f, %.4f, %.4f, %.4f, %d, %d\n",
label.c_str(),
(F32) perc,
(F32) (current[label]["TotalTime"].asReal()/session_time * 100.0),
+
(F32) current[label]["MinTime"].asReal(),
(F32) current[label]["MaxTime"].asReal(),
(F32) b,
+ (F32) current[label]["MeanTime"].asReal(),
+ (F32) current[label]["StdDevTime"].asReal(),
(F32) current[label]["TotalTime"].asReal(),
+ current[label]["Frames"].asInteger(),
current[label]["Samples"].asInteger(),
(F32) base[label]["MinTime"].asReal(),
(F32) base[label]["MaxTime"].asReal(),
(F32) a,
+ (F32) base[label]["MeanTime"].asReal(),
+ (F32) base[label]["StdDevTime"].asReal(),
(F32) base[label]["TotalTime"].asReal(),
+ base[label]["Frames"].asInteger(),
base[label]["Samples"].asInteger());
}
-
+ exportCharts(baseline, target);
+
os.flush();
os.close();
}
diff --git a/indra/newview/llfasttimerview.h b/indra/newview/llfasttimerview.h
index 1a54a53f09..c409445d86 100644
--- a/indra/newview/llfasttimerview.h
+++ b/indra/newview/llfasttimerview.h
@@ -45,6 +45,7 @@ private:
static void doAnalysisMetrics(std::string baseline, std::string target, std::string output) ;
static LLSD analyzeMetricPerformanceLog(std::istream& is) ;
static LLSD analyzePerformanceLogDefault(std::istream& is) ;
+ static void exportCharts(const std::string& base, const std::string& target);
public:
diff --git a/indra/newview/llfeaturemanager.cpp b/indra/newview/llfeaturemanager.cpp
index 4e16cc4217..9f0b34becc 100644
--- a/indra/newview/llfeaturemanager.cpp
+++ b/indra/newview/llfeaturemanager.cpp
@@ -729,6 +729,10 @@ void LLFeatureManager::applyBaseMasks()
{
maskFeatures("ATI");
}
+ if (gGLManager.mHasATIMemInfo && gGLManager.mVRAM < 256)
+ {
+ maskFeatures("ATIVramLT256");
+ }
if (gGLManager.mATIOldDriver)
{
maskFeatures("ATIOldDriver");
@@ -745,6 +749,10 @@ void LLFeatureManager::applyBaseMasks()
{
maskFeatures("OpenGLPre15");
}
+ if (gGLManager.mGLVersion < 3.f)
+ {
+ maskFeatures("OpenGLPre30");
+ }
// now mask by gpu string
// Replaces ' ' with '_' in mGPUString to deal with inability for parser to handle spaces
diff --git a/indra/newview/llfilepicker.cpp b/indra/newview/llfilepicker.cpp
index 51e76bcf9b..8c0ed29855 100644
--- a/indra/newview/llfilepicker.cpp
+++ b/indra/newview/llfilepicker.cpp
@@ -50,12 +50,14 @@ LLFilePicker LLFilePicker::sInstance;
#define SOUND_FILTER L"Sounds (*.wav)\0*.wav\0"
#define IMAGE_FILTER L"Images (*.tga; *.bmp; *.jpg; *.jpeg; *.png)\0*.tga;*.bmp;*.jpg;*.jpeg;*.png\0"
#define ANIM_FILTER L"Animations (*.bvh)\0*.bvh\0"
+#define COLLADA_FILTER L"Scene (*.dae)\0*.dae\0"
#ifdef _CORY_TESTING
#define GEOMETRY_FILTER L"SL Geometry (*.slg)\0*.slg\0"
#endif
#define XML_FILTER L"XML files (*.xml)\0*.xml\0"
#define SLOBJECT_FILTER L"Objects (*.slobject)\0*.slobject\0"
#define RAW_FILTER L"RAW files (*.raw)\0*.raw\0"
+#define MODEL_FILTER L"Model files (*.dae)\0*.dae\0"
#endif
//
@@ -185,6 +187,10 @@ BOOL LLFilePicker::setupFilter(ELoadFilter filter)
mOFN.lpstrFilter = ANIM_FILTER \
L"\0";
break;
+ case FFLOAD_COLLADA:
+ mOFN.lpstrFilter = COLLADA_FILTER \
+ L"\0";
+ break;
#ifdef _CORY_TESTING
case FFLOAD_GEOMETRY:
mOFN.lpstrFilter = GEOMETRY_FILTER \
@@ -203,6 +209,10 @@ BOOL LLFilePicker::setupFilter(ELoadFilter filter)
mOFN.lpstrFilter = RAW_FILTER \
L"\0";
break;
+ case FFLOAD_MODEL:
+ mOFN.lpstrFilter = MODEL_FILTER \
+ L"\0";
+ break;
default:
res = FALSE;
break;
@@ -210,7 +220,7 @@ BOOL LLFilePicker::setupFilter(ELoadFilter filter)
return res;
}
-BOOL LLFilePicker::getOpenFile(ELoadFilter filter)
+BOOL LLFilePicker::getOpenFile(ELoadFilter filter, bool blocking)
{
if( mLocked )
{
@@ -235,8 +245,11 @@ BOOL LLFilePicker::getOpenFile(ELoadFilter filter)
setupFilter(filter);
- // Modal, so pause agent
- send_agent_pause();
+ if (blocking)
+ {
+ // Modal, so pause agent
+ send_agent_pause();
+ }
reset();
@@ -247,10 +260,14 @@ BOOL LLFilePicker::getOpenFile(ELoadFilter filter)
std::string filename = utf16str_to_utf8str(llutf16string(mFilesW));
mFiles.push_back(filename);
}
- send_agent_resume();
- // Account for the fact that the app has been stalled.
- LLFrameTimer::updateFrameTime();
+ if (blocking)
+ {
+ send_agent_resume();
+ // Account for the fact that the app has been stalled.
+ LLFrameTimer::updateFrameTime();
+ }
+
return success;
}
@@ -570,6 +587,15 @@ Boolean LLFilePicker::navOpenFilterProc(AEDesc *theItem, void *info, void *callB
result = false;
}
}
+ else if (filter == FFLOAD_COLLADA)
+ {
+ if (fileInfo.filetype != 'DAE ' &&
+ (fileInfo.extension && (CFStringCompare(fileInfo.extension, CFSTR("dae"), kCFCompareCaseInsensitive) != kCFCompareEqualTo))
+ )
+ {
+ result = false;
+ }
+ }
#ifdef _CORY_TESTING
else if (filter == FFLOAD_GEOMETRY)
{
@@ -841,7 +867,7 @@ OSStatus LLFilePicker::doNavSaveDialog(ESaveFilter filter, const std::string& fi
return error;
}
-BOOL LLFilePicker::getOpenFile(ELoadFilter filter)
+BOOL LLFilePicker::getOpenFile(ELoadFilter filter, bool blocking)
{
if( mLocked )
return FALSE;
@@ -866,20 +892,29 @@ BOOL LLFilePicker::getOpenFile(ELoadFilter filter)
mNavOptions.optionFlags |= kNavSupportPackages;
}
- // Modal, so pause agent
- send_agent_pause();
+ if (blocking)
+ {
+ // Modal, so pause agent
+ send_agent_pause();
+ }
+
{
error = doNavChooseDialog(filter);
}
- send_agent_resume();
+
if (error == noErr)
{
if (getFileCount())
success = true;
}
- // Account for the fact that the app has been stalled.
- LLFrameTimer::updateFrameTime();
+ if (blocking)
+ {
+ send_agent_resume();
+ // Account for the fact that the app has been stalled.
+ LLFrameTimer::updateFrameTime();
+ }
+
return success;
}
@@ -1140,6 +1175,12 @@ static std::string add_bvh_filter_to_gtkchooser(GtkWindow *picker)
LLTrans::getString("animation_files") + " (*.bvh)");
}
+static std::string add_collada_filter_to_gtkchooser(GtkWindow *picker)
+{
+ return add_simple_pattern_filter_to_gtkchooser(picker, "*.dae",
+ LLTrans::getString("scene_files") + " (*.dae)");
+}
+
static std::string add_imageload_filter_to_gtkchooser(GtkWindow *picker)
{
GtkFileFilter *gfilter = gtk_file_filter_new();
@@ -1248,7 +1289,7 @@ BOOL LLFilePicker::getSaveFile( ESaveFilter filter, const std::string& filename
return rtn;
}
-BOOL LLFilePicker::getOpenFile( ELoadFilter filter )
+BOOL LLFilePicker::getOpenFile( ELoadFilter filter, bool blocking )
{
BOOL rtn = FALSE;
@@ -1276,6 +1317,9 @@ BOOL LLFilePicker::getOpenFile( ELoadFilter filter )
case FFLOAD_ANIM:
filtername = add_bvh_filter_to_gtkchooser(picker);
break;
+ case FFLOAD_COLLADA:
+ filtername = add_collada_filter_to_gtkchooser(picker);
+ break;
case FFLOAD_IMAGE:
filtername = add_imageload_filter_to_gtkchooser(picker);
break;
diff --git a/indra/newview/llfilepicker.h b/indra/newview/llfilepicker.h
index 596bfa3e69..cd843a8f33 100644
--- a/indra/newview/llfilepicker.h
+++ b/indra/newview/llfilepicker.h
@@ -82,6 +82,8 @@ public:
FFLOAD_XML = 6,
FFLOAD_SLOBJECT = 7,
FFLOAD_RAW = 8,
+ FFLOAD_MODEL = 9,
+ FFLOAD_COLLADA = 10,
};
enum ESaveFilter
@@ -105,7 +107,7 @@ public:
// open the dialog. This is a modal operation
BOOL getSaveFile( ESaveFilter filter = FFSAVE_ALL, const std::string& filename = LLStringUtil::null );
- BOOL getOpenFile( ELoadFilter filter = FFLOAD_ALL );
+ BOOL getOpenFile( ELoadFilter filter = FFLOAD_ALL, bool blocking = true );
BOOL getMultipleOpenFiles( ELoadFilter filter = FFLOAD_ALL );
// Get the filename(s) found. getFirstFile() sets the pointer to
@@ -190,4 +192,6 @@ public:
~LLFilePicker();
};
+const std::string upload_pick(void* data);
+
#endif
diff --git a/indra/newview/llflexibleobject.cpp b/indra/newview/llflexibleobject.cpp
index 8ab2229235..bd939d8636 100644
--- a/indra/newview/llflexibleobject.cpp
+++ b/indra/newview/llflexibleobject.cpp
@@ -91,11 +91,13 @@ void LLVolumeImplFlexible::onParameterChanged(U16 param_type, LLNetworkData *dat
}
}
-void LLVolumeImplFlexible::onShift(const LLVector3 &shift_vector)
+void LLVolumeImplFlexible::onShift(const LLVector4a &shift_vector)
{
+ //VECTORIZE THIS
+ LLVector3 shift(shift_vector.getF32ptr());
for (int section = 0; section < (1<<FLEXIBLE_OBJECT_MAX_SECTIONS)+1; ++section)
{
- mSection[section].mPosition += shift_vector;
+ mSection[section].mPosition += shift;
}
}
@@ -314,11 +316,13 @@ BOOL LLVolumeImplFlexible::doIdleUpdate(LLAgent &agent, LLWorld &world, const F6
return FALSE; // (we are not initialized or updated)
}
- if (force_update)
+ bool visible = mVO->mDrawable->isVisible();
+
+ if (force_update && visible)
{
gPipeline.markRebuild(mVO->mDrawable, LLDrawable::REBUILD_POSITION, FALSE);
}
- else if (mVO->mDrawable->isVisible() &&
+ else if (visible &&
!mVO->mDrawable->isState(LLDrawable::IN_REBUILD_Q1) &&
mVO->getPixelArea() > 256.f)
{
@@ -362,7 +366,7 @@ void LLVolumeImplFlexible::doFlexibleUpdate()
LLFastTimer ftm(FTM_DO_FLEXIBLE_UPDATE);
LLVolume* volume = mVO->getVolume();
LLPath *path = &volume->getPath();
- if (mSimulateRes == 0)
+ if ((mSimulateRes == 0 || !mInitialized) && mVO->mDrawable->isVisible())
{
mVO->markForUpdate(TRUE);
if (!doIdleUpdate(gAgent, *LLWorld::getInstance(), 0.0))
@@ -371,6 +375,11 @@ void LLVolumeImplFlexible::doFlexibleUpdate()
}
}
+ if (!mVO->mDrawable->isVisible())
+ {
+ return;
+ }
+
llassert_always(mInitialized);
S32 num_sections = 1 << mSimulateRes;
@@ -690,6 +699,8 @@ BOOL LLVolumeImplFlexible::doUpdateGeometry(LLDrawable *drawable)
}
volume->updateRelativeXform();
+
+ if (mRenderRes > -1)
{
LLFastTimer t(FTM_DO_FLEXIBLE_UPDATE);
doFlexibleUpdate();
diff --git a/indra/newview/llflexibleobject.h b/indra/newview/llflexibleobject.h
index 9b952f1985..fef43d464d 100644
--- a/indra/newview/llflexibleobject.h
+++ b/indra/newview/llflexibleobject.h
@@ -84,7 +84,7 @@ class LLVolumeImplFlexible : public LLVolumeInterface
void onSetVolume(const LLVolumeParams &volume_params, const S32 detail);
void onSetScale(const LLVector3 &scale, BOOL damped);
void onParameterChanged(U16 param_type, LLNetworkData *data, BOOL in_use, bool local_origin);
- void onShift(const LLVector3 &shift_vector);
+ void onShift(const LLVector4a &shift_vector);
bool isVolumeUnique() const { return true; }
bool isVolumeGlobal() const { return true; }
bool isActive() const { return true; }
diff --git a/indra/newview/llfloateranimpreview.cpp b/indra/newview/llfloateranimpreview.cpp
index deebd69ec1..1f334815d6 100644
--- a/indra/newview/llfloateranimpreview.cpp
+++ b/indra/newview/llfloateranimpreview.cpp
@@ -994,6 +994,7 @@ void LLFloaterAnimPreview::onBtnOK(void* userdata)
LLFloaterPerms::getNextOwnerPerms(), LLFloaterPerms::getGroupPerms(), LLFloaterPerms::getEveryonePerms(),
name,
callback, expected_upload_cost, userdata);
+
}
else
{
@@ -1032,7 +1033,6 @@ LLPreviewAnimation::LLPreviewAnimation(S32 width, S32 height) : LLViewerDynamicT
mDummyAvatar->updateGeometry(mDummyAvatar->mDrawable);
mDummyAvatar->startMotion(ANIM_AGENT_STAND, BASE_ANIM_TIME_OFFSET);
mDummyAvatar->hideSkirt();
- gPipeline.markVisible(mDummyAvatar->mDrawable, *LLViewerCamera::getInstance());
// stop extraneous animations
mDummyAvatar->stopMotion( ANIM_AGENT_HEAD_ROT, TRUE );
diff --git a/indra/newview/llfloaterhardwaresettings.cpp b/indra/newview/llfloaterhardwaresettings.cpp
index 1e91710552..42ec7d765b 100644
--- a/indra/newview/llfloaterhardwaresettings.cpp
+++ b/indra/newview/llfloaterhardwaresettings.cpp
@@ -50,7 +50,6 @@ LLFloaterHardwareSettings::LLFloaterHardwareSettings(const LLSD& key)
// but init them anyway
mUseVBO(0),
mUseAniso(0),
- mUseFBO(0),
mFSAASamples(0),
mGamma(0.0),
mVideoCardMem(0),
@@ -75,7 +74,6 @@ void LLFloaterHardwareSettings::refresh()
mUseVBO = gSavedSettings.getBOOL("RenderVBOEnable");
mUseAniso = gSavedSettings.getBOOL("RenderAnisotropic");
- mUseFBO = gSavedSettings.getBOOL("RenderUseFBO");
mFSAASamples = gSavedSettings.getU32("RenderFSAASamples");
mGamma = gSavedSettings.getF32("RenderGamma");
mVideoCardMem = gSavedSettings.getS32("TextureMemory");
@@ -104,7 +102,7 @@ void LLFloaterHardwareSettings::refreshEnabledState()
getChildView("(brightness, lower is brighter)")->setEnabled(!gPipeline.canUseWindLightShaders());
getChildView("fog")->setEnabled(!gPipeline.canUseWindLightShaders());
getChildView("fsaa")->setEnabled(gPipeline.canUseAntiAliasing());
- getChildView("antialiasing restart")->setVisible(!gSavedSettings.getBOOL("RenderUseFBO"));
+ getChildView("antialiasing restart")->setVisible(!gSavedSettings.getBOOL("RenderDeferred"));
/* Enable to reset fsaa value to disabled when feature is not available.
if (!gPipeline.canUseAntiAliasing())
@@ -139,7 +137,6 @@ void LLFloaterHardwareSettings::cancel()
{
gSavedSettings.setBOOL("RenderVBOEnable", mUseVBO);
gSavedSettings.setBOOL("RenderAnisotropic", mUseAniso);
- gSavedSettings.setBOOL("RenderUseFBO", mUseFBO);
gSavedSettings.setU32("RenderFSAASamples", mFSAASamples);
gSavedSettings.setF32("RenderGamma", mGamma);
gSavedSettings.setS32("TextureMemory", mVideoCardMem);
diff --git a/indra/newview/llfloaterimagepreview.cpp b/indra/newview/llfloaterimagepreview.cpp
index c7fbdd5745..d360d5db55 100644
--- a/indra/newview/llfloaterimagepreview.cpp
+++ b/indra/newview/llfloaterimagepreview.cpp
@@ -63,7 +63,7 @@ const S32 PREVIEW_BORDER_WIDTH = 2;
const S32 PREVIEW_RESIZE_HANDLE_SIZE = S32(RESIZE_HANDLE_WIDTH * OO_SQRT2) + PREVIEW_BORDER_WIDTH;
const S32 PREVIEW_HPAD = PREVIEW_RESIZE_HANDLE_SIZE;
const S32 PREF_BUTTON_HEIGHT = 16 + 7 + 16;
-const S32 PREVIEW_TEXTURE_HEIGHT = 300;
+const S32 PREVIEW_TEXTURE_HEIGHT = 320;
//-----------------------------------------------------------------------------
// LLFloaterImagePreview()
@@ -858,8 +858,8 @@ void LLImagePreviewSculpted::setPreviewTarget(LLImageRaw* imagep, F32 distance)
}
const LLVolumeFace &vf = mVolume->getVolumeFace(0);
- U32 num_indices = vf.mIndices.size();
- U32 num_vertices = vf.mVertices.size();
+ U32 num_indices = vf.mNumIndices;
+ U32 num_vertices = vf.mNumVertices;
mVertexBuffer = new LLVertexBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL, 0);
mVertexBuffer->allocateBuffer(num_vertices, num_indices, TRUE);
@@ -873,10 +873,16 @@ void LLImagePreviewSculpted::setPreviewTarget(LLImageRaw* imagep, F32 distance)
mVertexBuffer->getIndexStrider(index_strider);
// build vertices and normals
+ LLStrider<LLVector3> pos;
+ pos = (LLVector3*) vf.mPositions; pos.setStride(16);
+ LLStrider<LLVector3> norm;
+ norm = (LLVector3*) vf.mNormals; norm.setStride(16);
+
+
for (U32 i = 0; i < num_vertices; i++)
{
- *(vertex_strider++) = vf.mVertices[i].mPosition;
- LLVector3 normal = vf.mVertices[i].mNormal;
+ *(vertex_strider++) = *pos++;
+ LLVector3 normal = *norm++;
normal.normalize();
*(normal_strider++) = normal;
}
@@ -895,7 +901,6 @@ void LLImagePreviewSculpted::setPreviewTarget(LLImageRaw* imagep, F32 distance)
BOOL LLImagePreviewSculpted::render()
{
mNeedsUpdate = FALSE;
-
LLGLSUIDefault def;
LLGLDisable no_blend(GL_BLEND);
LLGLEnable cull(GL_CULL_FACE);
@@ -940,7 +945,7 @@ BOOL LLImagePreviewSculpted::render()
LLViewerCamera::getInstance()->setPerspective(FALSE, mOrigin.mX, mOrigin.mY, mFullWidth, mFullHeight, FALSE);
const LLVolumeFace &vf = mVolume->getVolumeFace(0);
- U32 num_indices = vf.mIndices.size();
+ U32 num_indices = vf.mNumIndices;
mVertexBuffer->setBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL);
@@ -953,7 +958,6 @@ BOOL LLImagePreviewSculpted::render()
mVertexBuffer->draw(LLRender::TRIANGLES, num_indices, 0);
gGL.popMatrix();
-
return TRUE;
}
diff --git a/indra/newview/llfloaterimportcollada.cpp b/indra/newview/llfloaterimportcollada.cpp
new file mode 100644
index 0000000000..20907e899e
--- /dev/null
+++ b/indra/newview/llfloaterimportcollada.cpp
@@ -0,0 +1,1112 @@
+/**
+ * @file llfloaterimportcollada.cpp
+ *
+ * $LicenseInfo:firstyear=2001&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+
+#include "llviewerprecompiledheaders.h"
+
+#if 0 //DEPRECATED
+
+#include "llfloaterimportcollada.h"
+
+#include "dae.h"
+//#include "dom.h"
+#include "dom/domAsset.h"
+#include "dom/domBind_material.h"
+#include "dom/domConstants.h"
+#include "dom/domEffect.h"
+#include "dom/domGeometry.h"
+#include "dom/domInstance_geometry.h"
+#include "dom/domInstance_material.h"
+#include "dom/domInstance_node.h"
+#include "dom/domInstance_effect.h"
+#include "dom/domMaterial.h"
+#include "dom/domMatrix.h"
+#include "dom/domNode.h"
+#include "dom/domProfile_COMMON.h"
+#include "dom/domRotate.h"
+#include "dom/domScale.h"
+#include "dom/domTranslate.h"
+#include "dom/domVisual_scene.h"
+
+#include "llagent.h"
+#include "llassetuploadresponders.h"
+#include "lleconomy.h"
+#include "llfloaterperms.h"
+#include "llfloaterreg.h"
+#include "llsdutil.h"
+#include "llsdutil_math.h"
+#include "llselectmgr.h"
+#include "llvfile.h"
+#include "llvfs.h"
+#include "llviewermenufile.h"
+#include "llviewerregion.h"
+#include "llvolumemessage.h"
+#include "llmodel.h"
+#include "llmeshreduction.h"
+#include "material_codes.h"
+
+//
+// floater
+//
+
+LLFloaterImportCollada::LLFloaterImportCollada(const LLSD& key)
+ : LLFloater(key)
+{
+}
+
+
+BOOL LLFloaterImportCollada::postBuild()
+{
+ if (!LLFloater::postBuild())
+ {
+ return FALSE;
+ }
+
+ childSetCommitCallback("ok", LLImportCollada::onCommitOK, this);
+ childSetCommitCallback("cancel", LLImportCollada::onCommitCancel, this);
+
+ setStatusIdle();
+ setAssetCount(0,0);
+ enableOK(TRUE);
+
+ return TRUE;
+}
+
+
+void LLFloaterImportCollada::setAssetCount(S32 mesh_count, S32 texture_count)
+{
+ childSetTextArg("mesh count", "[COUNT]", llformat("%d", mesh_count));
+ childSetTextArg("texture count", "[COUNT]", llformat("%d", texture_count));
+}
+
+void LLFloaterImportCollada::setStatusAssetUploading(std::string asset_name)
+{
+ LLUIString uploading = getString("status_uploading");
+ uploading.setArg("[NAME]", asset_name);
+ childSetTextArg("status", "[STATUS]", uploading.getString());
+}
+
+void LLFloaterImportCollada::setStatusCreatingPrim(std::string prim_name)
+{
+ LLUIString creating = getString("status_creating");
+ creating.setArg("[NAME]", prim_name);
+ childSetTextArg("status", "[STATUS]", creating.getString());
+}
+
+void LLFloaterImportCollada::setStatusIdle()
+{
+ childSetTextArg("status", "[STATUS]", getString("status_idle"));
+}
+
+void LLFloaterImportCollada::enableOK(BOOL enable)
+{
+ childSetEnabled("ok", enable);
+}
+
+
+//
+// misc helpers
+//
+
+
+// why oh why do forbid matrix multiplication in our llmath library?
+LLMatrix4 matrix_multiply(LLMatrix4 a, LLMatrix4 b)
+{
+ a *= b;
+
+ return a;
+}
+
+// why oh why does colladadom not provide such things?
+daeElement* getFirstChild(daeElement* parent)
+{
+ daeTArray< daeSmartRef<daeElement> > children = parent->getChildren();
+
+ if (children.getCount() > 0)
+ {
+ return children[0];
+ }
+ else
+ {
+ return NULL;
+ }
+}
+
+// why oh why does colladadom not provide such things?
+daeElement* getNextSibling(daeElement* child)
+{
+ daeElement* parent = child->getParent();
+
+ if (parent == NULL)
+ {
+ // must be root, root has no siblings
+ return NULL;
+ }
+
+ daeElement* sibling = NULL;
+
+ daeTArray< daeSmartRef<daeElement> > children = parent->getChildren();
+ for (S32 i = 0; i < children.getCount(); i++)
+ {
+ if (child == children[i])
+ {
+ if ((i+1) < children.getCount())
+ {
+ sibling = children[i+1];
+ }
+ }
+ }
+
+ return sibling;
+}
+
+// try to get a decent label for this element
+std::string getElementLabel(daeElement *element)
+{
+ // if we have a name attribute, use it
+ std::string name = element->getAttribute("name");
+ if (name.length())
+ {
+ return name;
+ }
+
+ // if we have an ID attribute, use it
+ if (element->getID())
+ {
+ return std::string(element->getID());
+ }
+
+ // if we have a parent, use it
+ daeElement* parent = element->getParent();
+ if (parent)
+ {
+ // if parent has a name, use it
+ std::string name = parent->getAttribute("name");
+ if (name.length())
+ {
+ return name;
+ }
+
+ // if parent has an ID, use it
+ if (parent->getID())
+ {
+ return std::string(parent->getID());
+ }
+ }
+
+ // try to use our type
+ daeString element_name = element->getElementName();
+ if (element_name)
+ {
+ return std::string(element_name);
+ }
+
+ // if all else fails, use "object"
+ return std::string("object");
+}
+
+LLColor4 getDaeColor(daeElement* element)
+{
+ LLColor4 value;
+ domCommon_color_or_texture_type_complexType::domColor* color =
+ daeSafeCast<domCommon_color_or_texture_type_complexType::domColor>(element->getDescendant("color"));
+ if (color)
+ {
+ domFx_color_common domfx_color = color->getValue();
+ value = LLColor4(domfx_color[0], domfx_color[1], domfx_color[2], domfx_color[3]);
+ }
+
+ return value;
+}
+
+LLTextureEntry profileToTextureEntry(domProfile_COMMON* material)
+{
+ LLTextureEntry te;
+
+ te.setID(LLUUID("5748decc-f629-461c-9a36-a35a221fe21f")); // blank texture
+ daeElement* diffuse = material->getDescendant("diffuse");
+ if (diffuse)
+ {
+ te.setColor(LLColor3(0.1f, 0.9f, 1.0f));
+
+ domCommon_color_or_texture_type_complexType::domTexture* texture =
+ daeSafeCast<domCommon_color_or_texture_type_complexType::domTexture>(diffuse->getDescendant("texture"));
+ if (texture)
+ {
+ domCommon_newparam_type_Array newparams = material->getNewparam_array();
+ for (S32 i = 0; i < newparams.getCount(); i++)
+ {
+ domFx_surface_common* surface = newparams[i]->getSurface();
+ if (surface)
+ {
+ domFx_surface_init_common* init = surface->getFx_surface_init_common();
+ if (init)
+ {
+ domFx_surface_init_from_common_Array init_from = init->getInit_from_array();
+
+ if (init_from.getCount() > 0)
+ {
+ daeElement* image = init_from[0]->getValue().getElement();
+ if (image)
+ {
+ LLUUID texture_asset = LLImportColladaAssetCache::getInstance()->getAssetForDaeElement(image);
+
+ if (texture_asset.notNull())
+ {
+ te.setID(texture_asset);
+ te.setColor(LLColor3(1,1,1));
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ domCommon_color_or_texture_type_complexType::domColor* color =
+ daeSafeCast<domCommon_color_or_texture_type_complexType::domColor>(diffuse->getDescendant("color"));
+ if (color)
+ {
+ domFx_color_common domfx_color = color->getValue();
+ LLColor4 value = LLColor4(domfx_color[0], domfx_color[1], domfx_color[2], domfx_color[3]);
+ te.setColor(value);
+ }
+ }
+
+ daeElement* emission = material->getDescendant("emission");
+ if (emission)
+ {
+ LLColor4 emission_color = getDaeColor(emission);
+ if (((emission_color[0] + emission_color[1] + emission_color[2]) / 3.0) > 0.25)
+ {
+ te.setFullbright(TRUE);
+ }
+ }
+
+ return te;
+}
+
+std::vector<LLTextureEntry> getMaterials(LLModel* model, domInstance_geometry* instance_geo)
+{
+ std::vector<LLTextureEntry> texture_entries;
+ for (int i = 0; i < model->mMaterialList.size(); i++)
+ {
+ LLTextureEntry texture_entry;
+
+ domInstance_material* instance_mat = NULL;
+
+ domBind_material::domTechnique_common* technique =
+ daeSafeCast<domBind_material::domTechnique_common>(instance_geo->getDescendant(daeElement::matchType(domBind_material::domTechnique_common::ID())));
+
+ if (technique)
+ {
+ daeTArray< daeSmartRef<domInstance_material> > inst_materials = technique->getChildrenByType<domInstance_material>();
+ for (int j = 0; j < inst_materials.getCount(); j++)
+ {
+ std::string symbol(inst_materials[j]->getSymbol());
+
+ if (symbol == model->mMaterialList[i]) // found the binding
+ {
+ instance_mat = inst_materials[j];
+ }
+ }
+ }
+
+ if (instance_mat)
+ {
+ domMaterial* material = daeSafeCast<domMaterial>(instance_mat->getTarget().getElement());
+ if (material)
+ {
+ domInstance_effect* instance_effect =
+ daeSafeCast<domInstance_effect>(material->getDescendant(daeElement::matchType(domInstance_effect::ID())));
+ if (instance_effect)
+ {
+ domEffect* effect = daeSafeCast<domEffect>(instance_effect->getUrl().getElement());
+ if (effect)
+ {
+ domProfile_COMMON* profile =
+ daeSafeCast<domProfile_COMMON>(effect->getDescendant(daeElement::matchType(domProfile_COMMON::ID())));
+ if (profile)
+ {
+ texture_entry = profileToTextureEntry(profile);
+ }
+ }
+ }
+ }
+ }
+
+ texture_entries.push_back(texture_entry);
+ }
+
+ return texture_entries;
+}
+
+LLTextureEntry instanceGeoToTextureEntry(domInstance_geometry* instance_geo)
+{
+ LLTextureEntry te;
+ domInstance_material* instance_mat =
+ daeSafeCast<domInstance_material>(instance_geo->getDescendant(daeElement::matchType(domInstance_material::ID())));
+ if (instance_mat)
+ {
+ }
+
+ return te;
+}
+
+
+
+// responder for asset uploads
+// does all the normal stuff followed by a notification to continue importing
+// WARNING - currently unused - TODO
+class LLColladaNewAgentInventoryResponder : public LLNewAgentInventoryResponder
+{
+ LLColladaNewAgentInventoryResponder(const LLSD& post_data,
+ const LLUUID& vfile_id,
+ LLAssetType::EType asset_type)
+ : LLNewAgentInventoryResponder(post_data, vfile_id, asset_type)
+ {
+ }
+ LLColladaNewAgentInventoryResponder(const LLSD& post_data,
+ const std::string& file_name,
+ LLAssetType::EType asset_type)
+ : LLNewAgentInventoryResponder(post_data, file_name, asset_type)
+ {
+ }
+
+ virtual void uploadComplete(const LLSD& content)
+ {
+ LLNewAgentInventoryResponder::uploadComplete(content);
+ }
+
+};
+
+BOOL LLImportColladaAssetCache::uploadImageAsset(domImage* image)
+{
+ // we only support init_from now - embedded data will come later
+ domImage::domInit_from* init = image->getInit_from();
+ if (!init)
+ {
+ return FALSE;
+ }
+
+ std::string filename = cdom::uriToNativePath(init->getValue().str());
+
+ std::string name = getElementLabel(image);
+
+ LLUUID transaction_id = upload_new_resource(filename, name, std::string(),
+ 0, LLFolderType::FT_TEXTURE, LLInventoryType::IT_TEXTURE,
+ LLFloaterPerms::getNextOwnerPerms(), LLFloaterPerms::getGroupPerms(),
+ LLFloaterPerms::getEveryonePerms(),
+ name, NULL,
+ LLGlobalEconomy::Singleton::getInstance()->getPriceUpload(), NULL);
+
+ if (transaction_id.isNull())
+ {
+ llwarns << "cannot upload " << filename << llendl;
+
+ return FALSE;
+ }
+
+ mTransactionMap[transaction_id] = image;
+
+ LLFloaterReg::findTypedInstance<LLFloaterImportCollada>("import_collada")->setStatusAssetUploading(name);
+
+ return TRUE;
+}
+
+
+
+//
+// asset cache -
+// uploads assets and provides a map from collada element to asset
+//
+
+
+
+BOOL LLImportColladaAssetCache::uploadMeshAsset(domMesh* mesh)
+{
+ LLPointer<LLModel> model = LLModel::loadModelFromDomMesh(mesh);
+
+ if (model->getNumVolumeFaces() == 0)
+ {
+ return FALSE;
+ }
+
+ // generate LODs
+
+
+ std::vector<LLPointer<LLModel> > lods;
+ lods.push_back(model);
+ S32 triangle_count = model->getNumTriangles();
+
+ for (S32 i = 0; i < 4; i++)
+ {
+ LLPointer<LLModel> last_model = lods.back();
+
+ S32 triangle_target = (S32)(triangle_count / pow(3.f, i + 1));
+ if (triangle_target > 16)
+ {
+ LLMeshReduction reduction;
+ LLPointer<LLModel> new_model = reduction.reduce(model, triangle_target, LLMeshReduction::TRIANGLE_BUDGET);
+ lods.push_back(new_model);
+ }
+ else
+ {
+ lods.push_back(last_model);
+ }
+ }
+
+ // write model to temp file
+
+ std::string filename = gDirUtilp->getTempFilename();
+ LLModel::writeModel(
+ filename,
+ lods[4],
+ lods[0],
+ lods[1],
+ lods[2],
+ lods[3],
+ lods[4]->mConvexHullDecomp);
+
+
+ // copy file to VFS
+
+ LLTransactionID tid;
+ tid.generate();
+ LLAssetID uuid = tid.makeAssetID(gAgent.getSecureSessionID()); // create asset uuid
+
+ S32 file_size;
+ LLAPRFile infile ;
+ infile.open(filename, LL_APR_RB, NULL, &file_size);
+
+ if (infile.getFileHandle())
+ {
+ LLVFile file(gVFS, uuid, LLAssetType::AT_MESH, LLVFile::WRITE);
+
+ file.setMaxSize(file_size);
+
+ const S32 buf_size = 65536;
+ U8 copy_buf[buf_size];
+ while ((file_size = infile.read(copy_buf, buf_size)))
+ {
+ file.write(copy_buf, file_size);
+ }
+ }
+
+
+ std::string name = getElementLabel(mesh);
+
+ upload_new_resource(tid, LLAssetType::AT_MESH, name, std::string(), 0,LLFolderType::FT_MESH, LLInventoryType::IT_MESH,
+ LLFloaterPerms::getNextOwnerPerms(), LLFloaterPerms::getGroupPerms(), LLFloaterPerms::getEveryonePerms(),
+ name, NULL,
+ LLGlobalEconomy::Singleton::getInstance()->getPriceUpload(), NULL);
+
+ LLFile::remove(filename);
+
+ mTransactionMap[uuid] = mesh;
+
+ LLFloaterReg::findTypedInstance<LLFloaterImportCollada>("import_collada")->setStatusAssetUploading(name);
+
+ return TRUE;
+}
+
+
+// called by the mesh asset upload responder to indicate the mesh asset has been uploaded
+void LLImportColladaAssetCache::assetUploaded(LLUUID transaction_uuid, LLUUID asset_uuid, BOOL success)
+{
+ std::map<LLUUID, daeElement*>::iterator i = mTransactionMap.find(transaction_uuid);
+
+ if (i != mTransactionMap.end())
+ {
+ daeElement* element = i->second;
+
+
+ if (success)
+ {
+ mAssetMap[element] = asset_uuid;
+ }
+ else // failure
+ {
+ // if failed, put back on end of queue
+ mUploadsPending.push_back(element);
+ }
+
+ mUploads--;
+ uploadNextAsset();
+ }
+}
+
+const S32 MAX_CONCURRENT_UPLOADS = 5;
+
+void LLImportColladaAssetCache::uploadNextAsset()
+{
+ while ((mUploadsPending.size() > 0) && (mUploads < MAX_CONCURRENT_UPLOADS))
+ {
+ BOOL upload_started = FALSE;
+
+ daeElement* element = mUploadsPending.back();
+ mUploadsPending.pop_back();
+
+ domImage* image = daeSafeCast<domImage>(element);
+ if (image)
+ {
+ upload_started = uploadImageAsset(image);
+ }
+
+ domMesh* mesh = daeSafeCast<domMesh>(element);
+ if (mesh)
+ {
+ upload_started = uploadMeshAsset(mesh);
+ }
+
+ if (upload_started)
+ {
+ mUploads++;
+ }
+
+ }
+
+ if ((mUploadsPending.size() == 0) && (mUploads == 0))
+ {
+ // we're done! notify the importer
+ LLImportCollada::getInstance()->assetsUploaded();
+ }
+
+ updateCount();
+}
+
+
+void LLImportColladaAssetCache::clear()
+{
+ mDAE = NULL;
+ mTransactionMap.clear();
+ mAssetMap.clear();
+ mUploadsPending.clear();
+ mUploads = 0;
+}
+
+void LLImportColladaAssetCache::endImport()
+{
+ clear();
+}
+
+void LLImportColladaAssetCache::updateCount()
+{
+ S32 mesh_count = 0;
+ S32 image_count = 0;
+
+ for (S32 i = 0; i < mUploadsPending.size(); i++)
+ {
+ daeElement* element = mUploadsPending[i];
+
+ if (daeSafeCast<domMesh>(element))
+ {
+ mesh_count++;
+ }
+
+ if (daeSafeCast<domImage>(element))
+ {
+ image_count++;
+ }
+ }
+
+ LLFloaterReg::findTypedInstance<LLFloaterImportCollada>("import_collada")->setAssetCount(mesh_count, image_count);
+}
+
+void LLImportColladaAssetCache::prepareForUpload(DAE* dae)
+{
+ clear();
+ mDAE = dae;
+
+ daeDatabase* db = mDAE->getDatabase();
+
+ S32 mesh_count = db->getElementCount(NULL, COLLADA_TYPE_MESH);
+ for (S32 i = 0; i < mesh_count; i++)
+ {
+ domMesh* mesh = NULL;
+
+ db->getElement((daeElement**) &mesh, i, NULL, COLLADA_TYPE_MESH);
+
+ mUploadsPending.push_back(mesh);
+ }
+
+
+ S32 image_count = db->getElementCount(NULL, COLLADA_TYPE_IMAGE);
+ for (S32 i = 0; i < image_count; i++)
+ {
+ domImage* image = NULL;
+ db->getElement((daeElement**) &image, i, NULL, COLLADA_TYPE_IMAGE);
+
+ mUploadsPending.push_back(image);
+ }
+
+ updateCount();
+}
+
+
+void LLImportColladaAssetCache::uploadAssets()
+{
+ uploadNextAsset();
+}
+
+
+LLUUID LLImportColladaAssetCache::getAssetForDaeElement(daeElement* element)
+{
+ LLUUID id;
+
+ std::map<daeElement*, LLUUID>::iterator i = mAssetMap.find(element);
+ if (i != mAssetMap.end())
+ {
+ id = i->second;
+ }
+
+ return id;
+}
+
+
+//
+// importer
+//
+
+
+
+LLImportCollada::LLImportCollada()
+{
+ mIsImporting = FALSE;
+}
+
+
+
+
+void LLImportCollada::appendObjectAsset(domInstance_geometry* instance_geo)
+{
+ domGeometry* geo = daeSafeCast<domGeometry>(instance_geo->getUrl().getElement());
+ if (!geo)
+ {
+ llwarns << "cannot find geometry" << llendl;
+ return;
+ }
+
+ domMesh* mesh = daeSafeCast<domMesh>(geo->getDescendant(daeElement::matchType(domMesh::ID())));
+ if (!mesh)
+ {
+ llwarns << "could not find mesh" << llendl;
+ return;
+ }
+
+ LLUUID mesh_asset = LLImportColladaAssetCache::getInstance()->getAssetForDaeElement(mesh);
+ if (mesh_asset.isNull())
+ {
+ llwarns << "no mesh asset, skipping" << llendl;
+ return;
+ }
+
+ // load the model
+ LLModel* model = LLModel::loadModelFromDomMesh(mesh);
+
+
+
+
+ // get our local transformation
+ LLMatrix4 transformation = mStack.front().transformation;
+
+ // adjust the transformation to compensate for mesh normalization
+ LLVector3 mesh_scale_vector;
+ LLVector3 mesh_translation_vector;
+ model->getNormalizedScaleTranslation(mesh_scale_vector, mesh_translation_vector);
+ LLMatrix4 mesh_translation;
+ mesh_translation.setTranslation(mesh_translation_vector);
+ transformation = matrix_multiply(mesh_translation, transformation);
+ LLMatrix4 mesh_scale;
+ mesh_scale.initScale(mesh_scale_vector);
+ transformation = matrix_multiply(mesh_scale, transformation);
+
+ // check for reflection
+ BOOL reflected = (transformation.determinant() < 0);
+
+ // compute position
+ LLVector3 position = LLVector3(0, 0, 0) * transformation;
+
+ // compute scale
+ LLVector3 x_transformed = LLVector3(1, 0, 0) * transformation - position;
+ LLVector3 y_transformed = LLVector3(0, 1, 0) * transformation - position;
+ LLVector3 z_transformed = LLVector3(0, 0, 1) * transformation - position;
+ F32 x_length = x_transformed.normalize();
+ F32 y_length = y_transformed.normalize();
+ F32 z_length = z_transformed.normalize();
+ LLVector3 scale = LLVector3(x_length, y_length, z_length);
+
+ // adjust for "reflected" geometry
+ LLVector3 x_transformed_reflected = x_transformed;
+ if (reflected)
+ {
+ x_transformed_reflected *= -1.0;
+ }
+
+ // compute rotation
+ LLMatrix3 rotation_matrix;
+ rotation_matrix.setRows(x_transformed_reflected, y_transformed, z_transformed);
+ LLQuaternion quat_rotation = rotation_matrix.quaternion();
+ quat_rotation.normalize(); // the rotation_matrix might not have been orthoginal. make it so here.
+ LLVector3 euler_rotation;
+ quat_rotation.getEulerAngles(&euler_rotation.mV[VX], &euler_rotation.mV[VY], &euler_rotation.mV[VZ]);
+
+
+ //
+ // build parameter block to construct this prim
+ //
+
+ LLSD object_params;
+
+ // create prim
+
+ // set volume params
+ LLVolumeParams volume_params;
+ volume_params.setType( LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE );
+ volume_params.setBeginAndEndS( 0.f, 1.f );
+ volume_params.setBeginAndEndT( 0.f, 1.f );
+ volume_params.setRatio ( 1, 1 );
+ volume_params.setShear ( 0, 0 );
+ U8 sculpt_type = LL_SCULPT_TYPE_MESH;
+ if (reflected)
+ {
+ sculpt_type |= LL_SCULPT_FLAG_MIRROR;
+ }
+ volume_params.setSculptID(mesh_asset, sculpt_type);
+ object_params["shape"] = volume_params.asLLSD();
+
+ object_params["material"] = LL_MCODE_WOOD;
+
+ object_params["group-id"] = gAgent.getGroupID();
+ object_params["pos"] = ll_sd_from_vector3(position);
+ object_params["rotation"] = ll_sd_from_quaternion(quat_rotation);
+ object_params["scale"] = ll_sd_from_vector3(scale);
+ object_params["name"] = mStack.front().name;
+
+ // load material from dae file
+ std::vector<LLTextureEntry> texture_entries = getMaterials(model, instance_geo);
+ object_params["facelist"] = LLSD::emptyArray();
+ for (int i = 0; i < texture_entries.size(); i++)
+ {
+ object_params["facelist"][i] = texture_entries[i].asLLSD();
+ }
+
+ // set extra parameters
+ LLSculptParams sculpt_params;
+ sculpt_params.setSculptTexture(mesh_asset);
+ sculpt_params.setSculptType(sculpt_type);
+ U8 buffer[MAX_OBJECT_PARAMS_SIZE+1];
+ LLDataPackerBinaryBuffer dp(buffer, MAX_OBJECT_PARAMS_SIZE);
+ sculpt_params.pack(dp);
+ std::vector<U8> v(dp.getCurrentSize());
+ memcpy(&v[0], buffer, dp.getCurrentSize());
+ LLSD extra_parameter;
+ extra_parameter["extra_parameter"] = sculpt_params.mType;
+ extra_parameter["param_data"] = v;
+ object_params["extra_parameters"].append(extra_parameter);
+
+ mObjectList.append(object_params);
+
+ delete model;
+
+ LLFloaterReg::findTypedInstance<LLFloaterImportCollada>("import_collada")->setStatusCreatingPrim(mStack.front().name);
+
+ return;
+}
+
+void LLImportCollada::uploadObjectAsset()
+{
+ LLSD request;
+ request["objects"] = mObjectList;
+
+ std::string url = gAgent.getRegion()->getCapability("UploadObjectAsset");
+ LLHTTPClient::post(url, request, new LLHTTPClient::Responder());
+}
+
+
+
+void LLImportCollada::importFile(std::string filename)
+{
+ if (mIsImporting)
+ {
+ llwarns << "Importer already running, import command for " << filename << " ignored" << llendl;
+ return;
+ }
+
+ LLFloaterReg::showInstance("import_collada");
+ LLFloaterReg::findTypedInstance<LLFloaterImportCollada>("import_collada")->enableOK(TRUE);
+
+
+ mIsImporting = TRUE;
+ mDAE = new DAE;
+ mImportOrigin = gAgent.getPositionAgent() + LLVector3(0, 0, 2);
+ mSceneTransformation = LLMatrix4(); // identity
+ mFilename = filename;
+ mCreates = 0;
+ mObjectList = LLSD::emptyArray();
+
+ if (mDAE->open(mFilename) == NULL)
+ {
+ llwarns << "cannot open file " << mFilename << llendl;
+ endImport();
+ return;
+ }
+
+ LLImportColladaAssetCache::getInstance()->prepareForUpload(mDAE);
+
+ return;
+}
+
+
+void LLImportCollada::assetsUploaded()
+{
+ if (!mIsImporting)
+ {
+ // weird, we got a callback while not importing.
+ return;
+ }
+
+ daeDocument* doc = mDAE->getDoc(mFilename);
+ if (!doc)
+ {
+ llwarns << "can't find internal doc" << llendl;
+ endImport();
+ }
+
+ daeElement* root = doc->getDomRoot();
+ if (!root)
+ {
+ llwarns << "document has no root" << llendl;
+ endImport();
+ }
+
+ domAsset::domUnit* unit = daeSafeCast<domAsset::domUnit>(root->getDescendant(daeElement::matchType(domAsset::domUnit::ID())));
+ if (unit)
+ {
+ mSceneTransformation *= unit->getMeter();
+ }
+
+ domUpAxisType up = UPAXISTYPE_Y_UP; // default is Y_UP
+ domAsset::domUp_axis* up_axis =
+ daeSafeCast<domAsset::domUp_axis>(root->getDescendant(daeElement::matchType(domAsset::domUp_axis::ID())));
+ if (up_axis)
+ {
+ up = up_axis->getValue();
+ }
+
+ if (up == UPAXISTYPE_X_UP)
+ {
+ LLMatrix4 rotation;
+ rotation.initRotation(0.0f, 90.0f * DEG_TO_RAD, 0.0f);
+
+ mSceneTransformation = matrix_multiply(rotation, mSceneTransformation);
+ }
+ else if (up == UPAXISTYPE_Y_UP)
+ {
+ LLMatrix4 rotation;
+ rotation.initRotation(90.0f * DEG_TO_RAD, 0.0f, 0.0f);
+
+ mSceneTransformation = matrix_multiply(rotation, mSceneTransformation);
+ }
+ // else Z_UP, which is our behavior
+
+
+
+ daeElement* scene = root->getDescendant("visual_scene");
+ if (!scene)
+ {
+ llwarns << "document has no visual_scene" << llendl;
+ endImport();
+ }
+
+ processElement(scene);
+ processNextElement();
+}
+
+void LLImportCollada::pushStack(daeElement* next_element, std::string name, LLMatrix4 transformation)
+{
+ struct StackState new_state;
+
+ new_state.next_element = next_element;
+ new_state.name = name;
+ new_state.transformation = transformation;
+
+ mStack.push_front(new_state);
+}
+
+
+
+void LLImportCollada::popStack()
+{
+ mStack.pop_front();
+}
+
+
+
+BOOL LLImportCollada::processElement(daeElement* element)
+{
+ if (mStack.size() > 0)
+ {
+ mStack.front().next_element = getNextSibling(element);
+ }
+
+ domTranslate* translate = daeSafeCast<domTranslate>(element);
+ if (translate)
+ {
+ domFloat3 dom_value = translate->getValue();
+
+ LLMatrix4 translation;
+ translation.setTranslation(LLVector3(dom_value[0], dom_value[1], dom_value[2]));
+
+ mStack.front().transformation = matrix_multiply(translation, mStack.front().transformation);
+ }
+
+ domRotate* rotate = daeSafeCast<domRotate>(element);
+ if (rotate)
+ {
+ domFloat4 dom_value = rotate->getValue();
+
+ LLMatrix4 rotation;
+ rotation.initRotTrans(dom_value[3] * DEG_TO_RAD, LLVector3(dom_value[0], dom_value[1], dom_value[2]), LLVector3(0, 0, 0));
+
+ mStack.front().transformation = matrix_multiply(rotation, mStack.front().transformation);
+ }
+
+ domScale* scale = daeSafeCast<domScale>(element);
+ if (scale)
+ {
+ domFloat3 dom_value = scale->getValue();
+
+ LLMatrix4 scaling;
+ scaling.initScale(LLVector3(dom_value[0], dom_value[1], dom_value[2]));
+
+ mStack.front().transformation = matrix_multiply(scaling, mStack.front().transformation);
+ }
+
+ domMatrix* matrix = daeSafeCast<domMatrix>(element);
+ if (matrix)
+ {
+ domFloat4x4 dom_value = matrix->getValue();
+
+ LLMatrix4 matrix_transform;
+
+ for (int i = 0; i < 4; i++)
+ for(int j = 0; j < 4; j++)
+ {
+ matrix_transform.mMatrix[i][j] = dom_value[i + j*4];
+ }
+
+ mStack.front().transformation = matrix_multiply(matrix_transform, mStack.front().transformation);
+ }
+
+ domInstance_geometry* instance_geo = daeSafeCast<domInstance_geometry>(element);
+ if (instance_geo)
+ {
+ appendObjectAsset(instance_geo);
+ }
+
+ domNode* node = daeSafeCast<domNode>(element);
+ if (node)
+ {
+ pushStack(getFirstChild(element), getElementLabel(element), mStack.front().transformation);
+ }
+
+ domInstance_node* instance_node = daeSafeCast<domInstance_node>(element);
+ if (instance_node)
+ {
+ daeElement* instance = instance_node->getUrl().getElement();
+ if (instance)
+ {
+ pushStack(getFirstChild(instance), getElementLabel(instance), mStack.front().transformation);
+ }
+ }
+
+ domVisual_scene* scene = daeSafeCast<domVisual_scene>(element);
+ if (scene)
+ {
+ pushStack(getFirstChild(element), std::string("scene"), mSceneTransformation);
+ }
+
+ return FALSE;
+}
+
+
+void LLImportCollada::processNextElement()
+{
+ while(1)
+ {
+ if (mStack.size() == 0)
+ {
+ uploadObjectAsset();
+ endImport();
+ return;
+ }
+
+ daeElement *element = mStack.front().next_element;
+
+ if (element == NULL)
+ {
+ popStack();
+ }
+ else
+ {
+ processElement(element);
+ }
+ }
+}
+
+
+void LLImportCollada::endImport()
+{
+ LLFloaterReg::hideInstance("import_collada");
+
+ LLImportColladaAssetCache::getInstance()->endImport();
+
+ if (mDAE)
+ {
+ delete mDAE;
+ mDAE = NULL;
+ }
+
+ mIsImporting = FALSE;
+}
+
+
+/* static */
+void LLImportCollada::onCommitOK(LLUICtrl*, void*)
+{
+ LLFloaterReg::findTypedInstance<LLFloaterImportCollada>("import_collada")->enableOK(FALSE);
+
+ LLImportColladaAssetCache::getInstance()->uploadAssets();
+}
+
+
+/* static */
+void LLImportCollada::onCommitCancel(LLUICtrl*, void*)
+{
+ getInstance()->endImport();
+}
+
+#endif
diff --git a/indra/newview/llfloaterimportcollada.h b/indra/newview/llfloaterimportcollada.h
new file mode 100644
index 0000000000..30c4a9a7db
--- /dev/null
+++ b/indra/newview/llfloaterimportcollada.h
@@ -0,0 +1,136 @@
+/**
+ * @file llfloaterimportcollada.h
+ * @brief The about box from Help -> About
+ *
+ * $LicenseInfo:firstyear=2001&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#if 0 //DEPRECATED
+
+#ifndef LL_LLFLOATERIMPORTCOLLADA_H
+#define LL_LLFLOATERIMPORTCOLLADA_H
+
+#include "llfloater.h"
+
+class LLFloaterImportCollada : public LLFloater
+{
+public:
+ LLFloaterImportCollada(const LLSD& key);
+ /* virtual */ BOOL postBuild();
+
+ void setAssetCount(S32 mesh_count, S32 texture_count);
+ void setStatusAssetUploading(std::string asset_name);
+ void setStatusCreatingPrim(std::string prim_name);
+ void setStatusIdle();
+ void enableOK(BOOL enable);
+};
+
+class LLViewerObject;
+class DAE;
+class daeElement;
+class domMesh;
+class domImage;
+class domInstance_geometry;
+class LLModel;
+class LLImportCollada;
+
+class LLImportColladaAssetCache : public LLSingleton<LLImportColladaAssetCache>
+{
+public:
+ // called first to initialize
+ void prepareForUpload(DAE* dae);
+
+ // upload the assets in this collada file
+ void uploadAssets();
+
+ // get the uploaded assets which corresponds to this element
+ LLUUID getAssetForDaeElement(daeElement* element);
+
+ // stop the upload
+ void endImport();
+
+ // reset
+ void clear();
+
+ // callback for notification when an asset has been uploaded
+ void assetUploaded(LLUUID transaction_uuid, LLUUID asset_uuid, BOOL success);
+
+private:
+ void uploadNextAsset();
+ BOOL uploadMeshAsset(domMesh* mesh);
+ BOOL uploadImageAsset(domImage* image);
+ void updateCount();
+
+ std::vector<daeElement*> mUploadsPending;
+ std::map<LLUUID, daeElement*> mTransactionMap;
+ std::map<daeElement*, LLUUID> mAssetMap;
+
+ DAE* mDAE;
+ S32 mUploads;
+};
+
+
+class LLImportCollada
+: public LLSingleton<LLImportCollada>
+{
+public:
+ LLImportCollada();
+ void importFile(std::string filename);
+
+ // callback when all assets have been uploaded
+ void assetsUploaded();
+
+ // callback when buttons pressed
+ static void onCommitOK(LLUICtrl*, void*);
+ static void onCommitCancel(LLUICtrl*, void*);
+
+
+private:
+ void endImport();
+ void processNextElement();
+ BOOL processElement(daeElement* element);
+ void pushStack(daeElement* next_element, std::string name, LLMatrix4 transformation);
+ void popStack();
+ void appendObjectAsset(domInstance_geometry* instance_geo);
+ void uploadObjectAsset();
+
+ struct StackState
+ {
+ daeElement* next_element;
+ std::string name;
+ LLMatrix4 transformation;
+ };
+
+ std::list<struct StackState> mStack;
+ S32 mCreates;
+ LLVector3 mImportOrigin;
+ std::string mFilename;
+ BOOL mIsImporting;
+ DAE *mDAE;
+ LLSD mObjectList;
+
+ LLMatrix4 mSceneTransformation;
+};
+
+#endif // LL_LLFLOATERIMPORTCOLLADA_H
+
+#endif //DEPRECATED
diff --git a/indra/newview/llfloatermodelpreview.cpp b/indra/newview/llfloatermodelpreview.cpp
new file mode 100755
index 0000000000..3a7732c7b3
--- /dev/null
+++ b/indra/newview/llfloatermodelpreview.cpp
@@ -0,0 +1,4373 @@
+/**
+ * @file llfloatermodelpreview.cpp
+ * @brief LLFloaterModelPreview class implementation
+ *
+ * $LicenseInfo:firstyear=2004&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h"
+
+#include "dae.h"
+//#include "dom.h"
+#include "dom/domAsset.h"
+#include "dom/domBind_material.h"
+#include "dom/domCOLLADA.h"
+#include "dom/domConstants.h"
+#include "dom/domController.h"
+#include "dom/domEffect.h"
+#include "dom/domGeometry.h"
+#include "dom/domInstance_geometry.h"
+#include "dom/domInstance_material.h"
+#include "dom/domInstance_node.h"
+#include "dom/domInstance_effect.h"
+#include "dom/domMaterial.h"
+#include "dom/domMatrix.h"
+#include "dom/domNode.h"
+#include "dom/domProfile_COMMON.h"
+#include "dom/domRotate.h"
+#include "dom/domScale.h"
+#include "dom/domTranslate.h"
+#include "dom/domVisual_scene.h"
+
+#include "llfloatermodelpreview.h"
+
+#include "llfilepicker.h"
+#include "llimagebmp.h"
+#include "llimagetga.h"
+#include "llimagejpeg.h"
+#include "llimagepng.h"
+
+#include "llagent.h"
+#include "llbutton.h"
+#include "llcombobox.h"
+#include "lldatapacker.h"
+#include "lldrawable.h"
+#include "lldrawpoolavatar.h"
+#include "llrender.h"
+#include "llface.h"
+#include "lleconomy.h"
+#include "llfocusmgr.h"
+#include "llfloaterperms.h"
+#include "lliconctrl.h"
+#include "llmatrix4a.h"
+#include "llmenubutton.h"
+#include "llmeshrepository.h"
+#include "llsdutil_math.h"
+#include "lltextbox.h"
+#include "lltoolmgr.h"
+#include "llui.h"
+#include "llvector4a.h"
+#include "llviewercamera.h"
+#include "llviewerwindow.h"
+#include "llvoavatar.h"
+#include "llvoavatarself.h"
+#include "pipeline.h"
+#include "lluictrlfactory.h"
+#include "llviewermenu.h"
+#include "llviewermenufile.h"
+#include "llviewerregion.h"
+#include "llviewertexturelist.h"
+#include "llstring.h"
+#include "llbutton.h"
+#include "llcheckboxctrl.h"
+#include "llradiogroup.h"
+#include "llsliderctrl.h"
+#include "llspinctrl.h"
+#include "lltoggleablemenu.h"
+#include "llvfile.h"
+#include "llvfs.h"
+#include "llcallbacklist.h"
+
+#include "glod/glod.h"
+
+//static
+S32 LLFloaterModelPreview::sUploadAmount = 10;
+LLFloaterModelPreview* LLFloaterModelPreview::sInstance = NULL;
+
+const S32 PREVIEW_BORDER_WIDTH = 2;
+const S32 PREVIEW_RESIZE_HANDLE_SIZE = S32(RESIZE_HANDLE_WIDTH * OO_SQRT2) + PREVIEW_BORDER_WIDTH;
+const S32 PREVIEW_HPAD = PREVIEW_RESIZE_HANDLE_SIZE;
+const S32 PREF_BUTTON_HEIGHT = 16 + 7 + 16;
+const S32 PREVIEW_TEXTURE_HEIGHT = 300;
+
+void drawBoxOutline(const LLVector3& pos, const LLVector3& size);
+
+
+std::string lod_name[NUM_LOD+1] =
+{
+ "lowest",
+ "low",
+ "medium",
+ "high",
+ "I went off the end of the lod_name array. Me so smart."
+};
+
+std::string lod_triangles_name[NUM_LOD+1] =
+{
+ "lowest_triangles",
+ "low_triangles",
+ "medium_triangles",
+ "high_triangles",
+ "I went off the end of the lod_triangles_name array. Me so smart."
+};
+
+std::string lod_vertices_name[NUM_LOD+1] =
+{
+ "lowest_vertices",
+ "low_vertices",
+ "medium_vertices",
+ "high_vertices",
+ "I went off the end of the lod_vertices_name array. Me so smart."
+};
+
+std::string lod_status_name[NUM_LOD+1] =
+{
+ "lowest_status",
+ "low_status",
+ "medium_status",
+ "high_status",
+ "I went off the end of the lod_status_name array. Me so smart."
+};
+
+std::string lod_icon_name[NUM_LOD+1] =
+{
+ "status_icon_lowest",
+ "status_icon_low",
+ "status_icon_medium",
+ "status_icon_high",
+ "I went off the end of the lod_status_name array. Me so smart."
+};
+
+std::string lod_status_image[NUM_LOD+1] =
+{
+ "ModelImport_Status_Good",
+ "ModelImport_Status_Warning",
+ "ModelImport_Status_Error",
+ "I went off the end of the lod_status_image array. Me so smart."
+};
+
+std::string lod_label_name[NUM_LOD+1] =
+{
+ "lowest_label",
+ "low_label",
+ "medium_label",
+ "high_label",
+ "I went off the end of the lod_label_name array. Me so smart."
+};
+
+bool validate_face(const LLVolumeFace& face)
+{
+ for (U32 i = 0; i < face.mNumIndices; ++i)
+ {
+ if (face.mIndices[i] >= face.mNumVertices)
+ {
+ llwarns << "Face has invalid index." << llendl;
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool validate_model(const LLModel* mdl)
+{
+ if (mdl->getNumVolumeFaces() == 0)
+ {
+ llwarns << "Model has no faces!" << llendl;
+ return false;
+ }
+
+ for (S32 i = 0; i < mdl->getNumVolumeFaces(); ++i)
+ {
+ if (mdl->getVolumeFace(i).mNumVertices == 0)
+ {
+ llwarns << "Face has no vertices." << llendl;
+ return false;
+ }
+
+ if (mdl->getVolumeFace(i).mNumIndices == 0)
+ {
+ llwarns << "Face has no indices." << llendl;
+ return false;
+ }
+
+ if (!validate_face(mdl->getVolumeFace(i)))
+ {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+BOOL stop_gloderror()
+{
+ GLuint error = glodGetError();
+
+ if (error != GLOD_NO_ERROR)
+ {
+ llwarns << "GLOD error detected, cannot generate LOD: " << std::hex << error << llendl;
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+
+LLMeshFilePicker::LLMeshFilePicker(LLModelPreview* mp, S32 lod)
+ : LLFilePickerThread(LLFilePicker::FFLOAD_COLLADA)
+ {
+ mMP = mp;
+ mLOD = lod;
+ }
+
+void LLMeshFilePicker::notify(const std::string& filename)
+{
+ mMP->loadModel(mFile, mLOD);
+}
+
+
+//-----------------------------------------------------------------------------
+// LLFloaterModelPreview()
+//-----------------------------------------------------------------------------
+LLFloaterModelPreview::LLFloaterModelPreview(const LLSD& key) :
+LLFloater(key)
+{
+ sInstance = this;
+ mLastMouseX = 0;
+ mLastMouseY = 0;
+ mGLName = 0;
+ mStatusLock = new LLMutex(NULL);
+
+ mLODMode[LLModel::LOD_HIGH] = 0;
+ for (U32 i = 0; i < LLModel::LOD_HIGH; i++)
+ {
+ mLODMode[i] = 1;
+ }
+}
+
+//-----------------------------------------------------------------------------
+// postBuild()
+//-----------------------------------------------------------------------------
+BOOL LLFloaterModelPreview::postBuild()
+{
+ if (!LLFloater::postBuild())
+ {
+ return FALSE;
+ }
+
+
+
+
+
+
+ childSetAction("lod_browse", onBrowseLOD, this);
+
+ childSetCommitCallback("cancel_btn", onCancel, this);
+ childSetCommitCallback("crease_angle", onGenerateNormalsCommit, this);
+ childSetCommitCallback("generate_normals", onGenerateNormalsCommit, this);
+
+ childSetCommitCallback("lod_generate", onAutoFillCommit, this);
+
+ childSetCommitCallback("lod_mode", onLODParamCommit, this);
+ childSetCommitCallback("lod_error_threshold", onLODParamCommit, this);
+ childSetCommitCallback("lod_triangle_limit", onLODParamCommitTriangleLimit, this);
+ childSetCommitCallback("build_operator", onLODParamCommit, this);
+ childSetCommitCallback("queue_mode", onLODParamCommit, this);
+ childSetCommitCallback("border_mode", onLODParamCommit, this);
+ childSetCommitCallback("share_tolerance", onLODParamCommit, this);
+
+ childSetTextArg("status", "[STATUS]", getString("status_idle"));
+
+ //childSetLabelArg("ok_btn", "[AMOUNT]", llformat("%d",sUploadAmount));
+ childSetAction("ok_btn", onUpload, this);
+ childDisable("ok_btn");
+
+ childSetAction("clear_materials", onClearMaterials, this);
+
+ childSetCommitCallback("preview_lod_combo", onPreviewLODCommit, this);
+
+ childSetCommitCallback("upload_skin", onUploadSkinCommit, this);
+ childSetCommitCallback("upload_joints", onUploadJointsCommit, this);
+
+ childSetCommitCallback("import_scale", onImportScaleCommit, this);
+ childSetCommitCallback("pelvis_offset", onPelvisOffsetCommit, this);
+
+ childSetCommitCallback("lod_file_or_limit", refresh, this);
+ childSetCommitCallback("physics_load_radio", refresh, this);
+ //childSetCommitCallback("physics_optimize", refresh, this);
+ //childSetCommitCallback("physics_use_hull", refresh, this);
+
+ childDisable("upload_skin");
+ childDisable("upload_joints");
+
+ childDisable("pelvis_offset");
+
+ childDisable("ok_btn");
+
+ mViewOptionMenuButton = getChild<LLMenuButton>("options_gear_btn");
+
+ mCommitCallbackRegistrar.add("ModelImport.ViewOption.Action", boost::bind(&LLFloaterModelPreview::onViewOptionChecked, this, _2));
+ mEnableCallbackRegistrar.add("ModelImport.ViewOption.Check", boost::bind(&LLFloaterModelPreview::isViewOptionChecked, this, _2));
+ mEnableCallbackRegistrar.add("ModelImport.ViewOption.Enabled", boost::bind(&LLFloaterModelPreview::isViewOptionEnabled, this, _2));
+
+
+
+ mViewOptionMenu = LLUICtrlFactory::getInstance()->createFromFile<LLToggleableMenu>("menu_model_import_gear_default.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
+ mViewOptionMenuButton->setMenu(mViewOptionMenu, LLMenuButton::MP_BOTTOM_LEFT);
+
+ initDecompControls();
+
+ LLView* preview_panel = getChild<LLView>("preview_panel");
+
+ mPreviewRect = preview_panel->getRect();
+
+ mModelPreview = new LLModelPreview(512, 512, this);
+ mModelPreview->setPreviewTarget(16.f);
+ mModelPreview->setDetailsCallback(boost::bind(&LLFloaterModelPreview::setDetails, this, _1, _2, _3, _4, _5));
+
+ //set callbacks for left click on line editor rows
+ for (U32 i = 0; i <= LLModel::LOD_HIGH; i++)
+ {
+ LLTextBox* text = getChild<LLTextBox>(lod_label_name[i]);
+ if (text)
+ {
+ text->setMouseDownCallback(boost::bind(&LLModelPreview::setPreviewLOD, mModelPreview, i));
+ }
+
+ text = getChild<LLTextBox>(lod_triangles_name[i]);
+ if (text)
+ {
+ text->setMouseDownCallback(boost::bind(&LLModelPreview::setPreviewLOD, mModelPreview, i));
+ }
+
+ text = getChild<LLTextBox>(lod_vertices_name[i]);
+ if (text)
+ {
+ text->setMouseDownCallback(boost::bind(&LLModelPreview::setPreviewLOD, mModelPreview, i));
+ }
+
+ text = getChild<LLTextBox>(lod_status_name[i]);
+ if (text)
+ {
+ text->setMouseDownCallback(boost::bind(&LLModelPreview::setPreviewLOD, mModelPreview, i));
+ }
+ }
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// LLFloaterModelPreview()
+//-----------------------------------------------------------------------------
+LLFloaterModelPreview::~LLFloaterModelPreview()
+{
+ sInstance = NULL;
+
+ const LLModelLoader *model_loader = mModelPreview->mModelLoader;
+ if (model_loader && model_loader->mResetJoints)
+ {
+ gAgentAvatarp->resetJointPositions();
+ }
+
+ delete mModelPreview;
+
+ if (mGLName)
+ {
+ LLImageGL::deleteTextures(1, &mGLName );
+ }
+
+ delete mStatusLock;
+ mStatusLock = NULL;
+}
+
+void LLFloaterModelPreview::onViewOptionChecked(const LLSD& userdata)
+{
+ if (mModelPreview)
+ {
+ mModelPreview->mViewOption[userdata.asString()] = !mModelPreview->mViewOption[userdata.asString()];
+
+ mModelPreview->refresh();
+ }
+}
+
+bool LLFloaterModelPreview::isViewOptionChecked(const LLSD& userdata)
+{
+ if (mModelPreview)
+ {
+ return mModelPreview->mViewOption[userdata.asString()];
+ }
+
+ return false;
+}
+
+bool LLFloaterModelPreview::isViewOptionEnabled(const LLSD& userdata)
+{
+ return !mViewOptionDisabled[userdata.asString()];
+}
+
+void LLFloaterModelPreview::setViewOptionEnabled(const std::string& option, bool enabled)
+{
+ mViewOptionDisabled[option] = !enabled;
+}
+
+void LLFloaterModelPreview::enableViewOption(const std::string& option)
+{
+ setViewOptionEnabled(option, true);
+}
+
+void LLFloaterModelPreview::disableViewOption(const std::string& option)
+{
+ setViewOptionEnabled(option, false);
+}
+
+void LLFloaterModelPreview::loadModel(S32 lod)
+{
+ mModelPreview->mLoading = true;
+
+ (new LLMeshFilePicker(mModelPreview, lod))->getFile();
+}
+
+//static
+void LLFloaterModelPreview::onImportScaleCommit(LLUICtrl*,void* userdata)
+{
+ LLFloaterModelPreview *fp =(LLFloaterModelPreview *)userdata;
+
+ if (!fp->mModelPreview)
+ {
+ return;
+ }
+
+ fp->mModelPreview->calcResourceCost();
+ fp->mModelPreview->refresh();
+}
+//static
+void LLFloaterModelPreview::onPelvisOffsetCommit( LLUICtrl*, void* userdata )
+{
+ LLFloaterModelPreview *fp =(LLFloaterModelPreview*)userdata;
+
+ if (!fp->mModelPreview)
+ {
+ return;
+ }
+ fp->mModelPreview->calcResourceCost();
+ fp->mModelPreview->refresh();
+}
+
+//static
+void LLFloaterModelPreview::onUploadJointsCommit(LLUICtrl*,void* userdata)
+{
+ LLFloaterModelPreview *fp =(LLFloaterModelPreview *)userdata;
+
+ if (!fp->mModelPreview)
+ {
+ return;
+ }
+
+ fp->mModelPreview->refresh();
+}
+
+//static
+void LLFloaterModelPreview::onUploadSkinCommit(LLUICtrl*,void* userdata)
+{
+ LLFloaterModelPreview *fp =(LLFloaterModelPreview *)userdata;
+
+ if (!fp->mModelPreview)
+ {
+ return;
+ }
+
+ fp->mModelPreview->refresh();
+ fp->mModelPreview->resetPreviewTarget();
+ fp->mModelPreview->clearBuffers();
+}
+
+//static
+void LLFloaterModelPreview::onPreviewLODCommit(LLUICtrl* ctrl, void* userdata)
+{
+ LLFloaterModelPreview *fp =(LLFloaterModelPreview *)userdata;
+
+ if (!fp->mModelPreview)
+ {
+ return;
+ }
+
+ S32 which_mode = 0;
+
+ LLComboBox* combo = (LLComboBox*) ctrl;
+
+ which_mode = (NUM_LOD-1)-combo->getFirstSelectedIndex(); // combo box list of lods is in reverse order
+
+ fp->mModelPreview->setPreviewLOD(which_mode);
+}
+
+//static
+void LLFloaterModelPreview::onGenerateNormalsCommit(LLUICtrl* ctrl, void* userdata)
+{
+ LLFloaterModelPreview* fp = (LLFloaterModelPreview*) userdata;
+
+ fp->mModelPreview->generateNormals();
+}
+
+//static
+void LLFloaterModelPreview::onExplodeCommit(LLUICtrl* ctrl, void* userdata)
+{
+ LLFloaterModelPreview* fp = LLFloaterModelPreview::sInstance;
+
+ fp->mModelPreview->refresh();
+}
+
+//static
+void LLFloaterModelPreview::onAutoFillCommit(LLUICtrl* ctrl, void* userdata)
+{
+ LLFloaterModelPreview* fp = (LLFloaterModelPreview*) userdata;
+
+ fp->mModelPreview->genLODs();
+}
+
+//static
+void LLFloaterModelPreview::onLODParamCommit(LLUICtrl* ctrl, void* userdata)
+{
+ LLFloaterModelPreview* fp = (LLFloaterModelPreview*) userdata;
+ fp->mModelPreview->onLODParamCommit(false);
+}
+
+//static
+void LLFloaterModelPreview::onLODParamCommitTriangleLimit(LLUICtrl* ctrl, void* userdata)
+{
+ LLFloaterModelPreview* fp = (LLFloaterModelPreview*) userdata;
+ fp->mModelPreview->onLODParamCommit(true);
+}
+
+
+//-----------------------------------------------------------------------------
+// draw()
+//-----------------------------------------------------------------------------
+void LLFloaterModelPreview::draw()
+{
+ LLFloater::draw();
+ LLRect r = getRect();
+
+ mModelPreview->update();
+
+ if (!mModelPreview->mLoading)
+ {
+ childSetTextArg("status", "[STATUS]", getString("status_idle"));
+ }
+
+ childSetTextArg("prim_cost", "[PRIM_COST]", llformat("%d", mModelPreview->mResourceCost));
+ childSetTextArg("description_label", "[TEXTURES]", llformat("%d", mModelPreview->mTextureSet.size()));
+
+ if (!mCurRequest.empty())
+ {
+ LLMutexLock lock(mStatusLock);
+ childSetTextArg("status", "[STATUS]", mStatusMessage);
+ }
+ else
+ {
+ childSetVisible("Simplify", true);
+ childSetVisible("simplify_cancel", false);
+ childSetVisible("Decompose", true);
+ childSetVisible("decompose_cancel", false);
+ }
+
+ U32 resource_cost = mModelPreview->mResourceCost*10;
+
+ if (childGetValue("upload_textures").asBoolean())
+ {
+ resource_cost += mModelPreview->mTextureSet.size()*10;
+ }
+
+ childSetLabelArg("ok_btn", "[AMOUNT]", llformat("%d", resource_cost));
+
+ if (mModelPreview)
+ {
+ gGL.color3f(1.f, 1.f, 1.f);
+
+ gGL.getTexUnit(0)->bind(mModelPreview);
+
+
+ LLView* preview_panel = getChild<LLView>("preview_panel");
+
+ LLRect rect = preview_panel->getRect();
+ if (rect != mPreviewRect)
+ {
+ mModelPreview->refresh();
+ mPreviewRect = preview_panel->getRect();
+ }
+
+ gGL.begin( LLRender::QUADS );
+ {
+ gGL.texCoord2f(0.f, 1.f);
+ gGL.vertex2i(mPreviewRect.mLeft, mPreviewRect.mTop-1);
+ gGL.texCoord2f(0.f, 0.f);
+ gGL.vertex2i(mPreviewRect.mLeft, mPreviewRect.mBottom);
+ gGL.texCoord2f(1.f, 0.f);
+ gGL.vertex2i(mPreviewRect.mRight-1, mPreviewRect.mBottom);
+ gGL.texCoord2f(1.f, 1.f);
+ gGL.vertex2i(mPreviewRect.mRight-1, mPreviewRect.mTop-1);
+ }
+ gGL.end();
+
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ }
+}
+
+//-----------------------------------------------------------------------------
+// handleMouseDown()
+//-----------------------------------------------------------------------------
+BOOL LLFloaterModelPreview::handleMouseDown(S32 x, S32 y, MASK mask)
+{
+ if (mPreviewRect.pointInRect(x, y))
+ {
+ bringToFront( x, y );
+ gFocusMgr.setMouseCapture(this);
+ gViewerWindow->hideCursor();
+ mLastMouseX = x;
+ mLastMouseY = y;
+ return TRUE;
+ }
+
+ return LLFloater::handleMouseDown(x, y, mask);
+}
+
+//-----------------------------------------------------------------------------
+// handleMouseUp()
+//-----------------------------------------------------------------------------
+BOOL LLFloaterModelPreview::handleMouseUp(S32 x, S32 y, MASK mask)
+{
+ gFocusMgr.setMouseCapture(FALSE);
+ gViewerWindow->showCursor();
+ return LLFloater::handleMouseUp(x, y, mask);
+}
+
+//-----------------------------------------------------------------------------
+// handleHover()
+//-----------------------------------------------------------------------------
+BOOL LLFloaterModelPreview::handleHover (S32 x, S32 y, MASK mask)
+{
+ MASK local_mask = mask & ~MASK_ALT;
+
+ if (mModelPreview && hasMouseCapture())
+ {
+ if (local_mask == MASK_PAN)
+ {
+ // pan here
+ mModelPreview->pan((F32)(x - mLastMouseX) * -0.005f, (F32)(y - mLastMouseY) * -0.005f);
+ }
+ else if (local_mask == MASK_ORBIT)
+ {
+ F32 yaw_radians = (F32)(x - mLastMouseX) * -0.01f;
+ F32 pitch_radians = (F32)(y - mLastMouseY) * 0.02f;
+
+ mModelPreview->rotate(yaw_radians, pitch_radians);
+ }
+ else
+ {
+
+ F32 yaw_radians = (F32)(x - mLastMouseX) * -0.01f;
+ F32 zoom_amt = (F32)(y - mLastMouseY) * 0.02f;
+
+ mModelPreview->rotate(yaw_radians, 0.f);
+ mModelPreview->zoom(zoom_amt);
+ }
+
+
+ mModelPreview->refresh();
+
+ LLUI::setMousePositionLocal(this, mLastMouseX, mLastMouseY);
+ }
+
+ if (!mPreviewRect.pointInRect(x, y) || !mModelPreview)
+ {
+ return LLFloater::handleHover(x, y, mask);
+ }
+ else if (local_mask == MASK_ORBIT)
+ {
+ gViewerWindow->setCursor(UI_CURSOR_TOOLCAMERA);
+ }
+ else if (local_mask == MASK_PAN)
+ {
+ gViewerWindow->setCursor(UI_CURSOR_TOOLPAN);
+ }
+ else
+ {
+ gViewerWindow->setCursor(UI_CURSOR_TOOLZOOMIN);
+ }
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// handleScrollWheel()
+//-----------------------------------------------------------------------------
+BOOL LLFloaterModelPreview::handleScrollWheel(S32 x, S32 y, S32 clicks)
+{
+ if (mPreviewRect.pointInRect(x, y) && mModelPreview)
+ {
+ mModelPreview->zoom((F32)clicks * -0.2f);
+ mModelPreview->refresh();
+ }
+
+ return TRUE;
+}
+
+//static
+void LLFloaterModelPreview::onPhysicsParamCommit(LLUICtrl* ctrl, void* data)
+{
+ if (LLConvexDecomposition::getInstance() == NULL)
+ {
+ llinfos << "convex decomposition tool is a stub on this platform. cannot get decomp." << llendl;
+ return;
+ }
+
+ if (sInstance)
+ {
+ LLCDParam* param = (LLCDParam*) data;
+ std::string name(param->mName);
+ sInstance->mDecompParams[name] = ctrl->getValue();
+
+ if (name == "Simplify Method")
+ {
+ if (ctrl->getValue().asInteger() == 0)
+ {
+ sInstance->childSetVisible("Retain%", true);
+ sInstance->childSetVisible("Detail Scale", false);
+ }
+ else
+ {
+ sInstance->childSetVisible("Retain%", false);
+ sInstance->childSetVisible("Detail Scale", true);
+ }
+ }
+ }
+}
+
+//static
+void LLFloaterModelPreview::onPhysicsStageExecute(LLUICtrl* ctrl, void* data)
+{
+ LLCDStageData* stage_data = (LLCDStageData*) data;
+ std::string stage = stage_data->mName;
+
+ if (sInstance)
+ {
+ if (!sInstance->mCurRequest.empty())
+ {
+ llinfos << "Decomposition request still pending." << llendl;
+ return;
+ }
+
+ if (sInstance->mModelPreview)
+ {
+ for (S32 i = 0; i < sInstance->mModelPreview->mModel[LLModel::LOD_PHYSICS].size(); ++i)
+ {
+ LLModel* mdl = sInstance->mModelPreview->mModel[LLModel::LOD_PHYSICS][i];
+ DecompRequest* request = new DecompRequest(stage, mdl);
+ sInstance->mCurRequest.insert(request);
+ gMeshRepo.mDecompThread->submitRequest(request);
+ }
+ }
+
+ if (stage == "Decompose")
+ {
+ sInstance->setStatusMessage(sInstance->getString("decomposing"));
+ sInstance->childSetVisible("Decompose", false);
+ sInstance->childSetVisible("decompose_cancel", true);
+ }
+ else if (stage == "Simplify")
+ {
+ sInstance->setStatusMessage(sInstance->getString("simplifying"));
+ sInstance->childSetVisible("Simplify", false);
+ sInstance->childSetVisible("simplify_cancel", true);
+ }
+ }
+}
+
+//static
+void LLFloaterModelPreview::onPhysicsBrowse(LLUICtrl* ctrl, void* userdata)
+{
+ sInstance->loadModel(LLModel::LOD_PHYSICS);
+}
+
+//static
+void LLFloaterModelPreview::onPhysicsUseLOD(LLUICtrl* ctrl, void* userdata)
+{
+ S32 which_mode = 3;
+ LLCtrlSelectionInterface* iface = sInstance->childGetSelectionInterface("physics_lod_combo");
+ if (iface)
+ {
+ which_mode = iface->getFirstSelectedIndex();
+ }
+
+ sInstance->mModelPreview->setPhysicsFromLOD(which_mode);
+}
+
+//static
+void LLFloaterModelPreview::onCancel(LLUICtrl* ctrl, void* data)
+{
+ if (sInstance)
+ {
+ sInstance->closeFloater(false);
+ }
+}
+
+//static
+void LLFloaterModelPreview::onPhysicsStageCancel(LLUICtrl* ctrl, void*data)
+{
+ if (sInstance)
+ {
+ for (std::set<LLPointer<DecompRequest> >::iterator iter = sInstance->mCurRequest.begin();
+ iter != sInstance->mCurRequest.end(); ++iter)
+ {
+ DecompRequest* req = *iter;
+ req->mContinue = 0;
+ }
+
+ sInstance->mCurRequest.clear();
+ }
+}
+
+void LLFloaterModelPreview::initDecompControls()
+{
+ LLSD key;
+
+ childSetCommitCallback("simplify_cancel", onPhysicsStageCancel, NULL);
+ childSetCommitCallback("decompose_cancel", onPhysicsStageCancel, NULL);
+
+ childSetCommitCallback("physics_lod_combo", onPhysicsUseLOD, NULL);
+ childSetCommitCallback("physics_browse", onPhysicsBrowse, NULL);
+
+ static const LLCDStageData* stage = NULL;
+ static S32 stage_count = 0;
+
+ if (!stage && LLConvexDecomposition::getInstance() != NULL)
+ {
+ stage_count = LLConvexDecomposition::getInstance()->getStages(&stage);
+ }
+
+ static const LLCDParam* param = NULL;
+ static S32 param_count = 0;
+ if (!param && LLConvexDecomposition::getInstance() != NULL)
+ {
+ param_count = LLConvexDecomposition::getInstance()->getParameters(&param);
+ }
+
+ for (S32 j = stage_count-1; j >= 0; --j)
+ {
+ LLButton* button = getChild<LLButton>(stage[j].mName);
+ if (button)
+ {
+ button->setCommitCallback(onPhysicsStageExecute, (void*) &stage[j]);
+ }
+
+ gMeshRepo.mDecompThread->mStageID[stage[j].mName] = j;
+ // protected against stub by stage_count being 0 for stub above
+ LLConvexDecomposition::getInstance()->registerCallback(j, LLPhysicsDecomp::llcdCallback);
+
+ //llinfos << "Physics decomp stage " << stage[j].mName << " (" << j << ") parameters:" << llendl;
+ //llinfos << "------------------------------------" << llendl;
+
+ for (S32 i = 0; i < param_count; ++i)
+ {
+ if (param[i].mStage != j)
+ {
+ continue;
+ }
+
+ std::string name(param[i].mName ? param[i].mName : "");
+ std::string description(param[i].mDescription ? param[i].mDescription : "");
+
+ std::string type = "unknown";
+
+ llinfos << name << " - " << description << llendl;
+
+ if (param[i].mType == LLCDParam::LLCD_FLOAT)
+ {
+ mDecompParams[param[i].mName] = LLSD(param[i].mDefault.mFloat);
+ //llinfos << "Type: float, Default: " << param[i].mDefault.mFloat << llendl;
+
+ LLSliderCtrl* slider = getChild<LLSliderCtrl>(name);
+ if (slider)
+ {
+ slider->setMinValue(param[i].mDetails.mRange.mLow.mFloat);
+ slider->setMaxValue(param[i].mDetails.mRange.mHigh.mFloat);
+ slider->setIncrement(param[i].mDetails.mRange.mDelta.mFloat);
+ slider->setValue(param[i].mDefault.mFloat);
+ slider->setCommitCallback(onPhysicsParamCommit, (void*) &param[i]);
+ }
+ }
+ else if (param[i].mType == LLCDParam::LLCD_INTEGER)
+ {
+ mDecompParams[param[i].mName] = LLSD(param[i].mDefault.mIntOrEnumValue);
+ //llinfos << "Type: integer, Default: " << param[i].mDefault.mIntOrEnumValue << llendl;
+
+ LLSliderCtrl* slider = getChild<LLSliderCtrl>(name);
+ if (slider)
+ {
+ slider->setMinValue(param[i].mDetails.mRange.mLow.mIntOrEnumValue);
+ slider->setMaxValue(param[i].mDetails.mRange.mHigh.mIntOrEnumValue);
+ slider->setIncrement(param[i].mDetails.mRange.mDelta.mIntOrEnumValue);
+ slider->setValue(param[i].mDefault.mIntOrEnumValue);
+ slider->setCommitCallback(onPhysicsParamCommit, (void*) &param[i]);
+ }
+ }
+ else if (param[i].mType == LLCDParam::LLCD_BOOLEAN)
+ {
+ mDecompParams[param[i].mName] = LLSD(param[i].mDefault.mBool);
+ //llinfos << "Type: boolean, Default: " << (param[i].mDefault.mBool ? "True" : "False") << llendl;
+
+ LLCheckBoxCtrl* check_box = getChild<LLCheckBoxCtrl>(name);
+ if (check_box)
+ {
+ check_box->setValue(param[i].mDefault.mBool);
+ check_box->setCommitCallback(onPhysicsParamCommit, (void*) &param[i]);
+ }
+ }
+ else if (param[i].mType == LLCDParam::LLCD_ENUM)
+ {
+ mDecompParams[param[i].mName] = LLSD(param[i].mDefault.mIntOrEnumValue);
+ //llinfos << "Type: enum, Default: " << param[i].mDefault.mIntOrEnumValue << llendl;
+
+ { //plug into combo box
+
+ //llinfos << "Accepted values: " << llendl;
+ LLComboBox* combo_box = getChild<LLComboBox>(name);
+ for (S32 k = 0; k < param[i].mDetails.mEnumValues.mNumEnums; ++k)
+ {
+ //llinfos << param[i].mDetails.mEnumValues.mEnumsArray[k].mValue
+ // << " - " << param[i].mDetails.mEnumValues.mEnumsArray[k].mName << llendl;
+
+ combo_box->add(param[i].mDetails.mEnumValues.mEnumsArray[k].mName,
+ LLSD::Integer(param[i].mDetails.mEnumValues.mEnumsArray[k].mValue));
+ }
+ combo_box->setValue(param[i].mDefault.mIntOrEnumValue);
+ combo_box->setCommitCallback(onPhysicsParamCommit, (void*) &param[i]);
+ }
+
+ //llinfos << "----" << llendl;
+ }
+ //llinfos << "-----------------------------" << llendl;
+ }
+ }
+
+ childSetCommitCallback("physics_explode", LLFloaterModelPreview::onExplodeCommit, this);
+}
+
+//-----------------------------------------------------------------------------
+// onMouseCaptureLost()
+//-----------------------------------------------------------------------------
+// static
+void LLFloaterModelPreview::onMouseCaptureLostModelPreview(LLMouseHandler* handler)
+{
+ gViewerWindow->showCursor();
+}
+
+//-----------------------------------------------------------------------------
+// LLModelLoader
+//-----------------------------------------------------------------------------
+LLModelLoader::LLModelLoader(std::string filename, S32 lod, LLModelPreview* preview)
+: LLThread("Model Loader"), mFilename(filename), mLod(lod), mPreview(preview), mState(STARTING), mFirstTransform(TRUE), mResetJoints( FALSE )
+{
+ mJointMap["mPelvis"] = "mPelvis";
+ mJointMap["mTorso"] = "mTorso";
+ mJointMap["mChest"] = "mChest";
+ mJointMap["mNeck"] = "mNeck";
+ mJointMap["mHead"] = "mHead";
+ mJointMap["mSkull"] = "mSkull";
+ mJointMap["mEyeRight"] = "mEyeRight";
+ mJointMap["mEyeLeft"] = "mEyeLeft";
+ mJointMap["mCollarLeft"] = "mCollarLeft";
+ mJointMap["mShoulderLeft"] = "mShoulderLeft";
+ mJointMap["mElbowLeft"] = "mElbowLeft";
+ mJointMap["mWristLeft"] = "mWristLeft";
+ mJointMap["mCollarRight"] = "mCollarRight";
+ mJointMap["mShoulderRight"] = "mShoulderRight";
+ mJointMap["mElbowRight"] = "mElbowRight";
+ mJointMap["mWristRight"] = "mWristRight";
+ mJointMap["mHipRight"] = "mHipRight";
+ mJointMap["mKneeRight"] = "mKneeRight";
+ mJointMap["mAnkleRight"] = "mAnkleRight";
+ mJointMap["mFootRight"] = "mFootRight";
+ mJointMap["mToeRight"] = "mToeRight";
+ mJointMap["mHipLeft"] = "mHipLeft";
+ mJointMap["mKneeLeft"] = "mKneeLeft";
+ mJointMap["mAnkleLeft"] = "mAnkleLeft";
+ mJointMap["mFootLeft"] = "mFootLeft";
+ mJointMap["mToeLeft"] = "mToeLeft";
+
+ mJointMap["avatar_mPelvis"] = "mPelvis";
+ mJointMap["avatar_mTorso"] = "mTorso";
+ mJointMap["avatar_mChest"] = "mChest";
+ mJointMap["avatar_mNeck"] = "mNeck";
+ mJointMap["avatar_mHead"] = "mHead";
+ mJointMap["avatar_mSkull"] = "mSkull";
+ mJointMap["avatar_mEyeRight"] = "mEyeRight";
+ mJointMap["avatar_mEyeLeft"] = "mEyeLeft";
+ mJointMap["avatar_mCollarLeft"] = "mCollarLeft";
+ mJointMap["avatar_mShoulderLeft"] = "mShoulderLeft";
+ mJointMap["avatar_mElbowLeft"] = "mElbowLeft";
+ mJointMap["avatar_mWristLeft"] = "mWristLeft";
+ mJointMap["avatar_mCollarRight"] = "mCollarRight";
+ mJointMap["avatar_mShoulderRight"] = "mShoulderRight";
+ mJointMap["avatar_mElbowRight"] = "mElbowRight";
+ mJointMap["avatar_mWristRight"] = "mWristRight";
+ mJointMap["avatar_mHipRight"] = "mHipRight";
+ mJointMap["avatar_mKneeRight"] = "mKneeRight";
+ mJointMap["avatar_mAnkleRight"] = "mAnkleRight";
+ mJointMap["avatar_mFootRight"] = "mFootRight";
+ mJointMap["avatar_mToeRight"] = "mToeRight";
+ mJointMap["avatar_mHipLeft"] = "mHipLeft";
+ mJointMap["avatar_mKneeLeft"] = "mKneeLeft";
+ mJointMap["avatar_mAnkleLeft"] = "mAnkleLeft";
+ mJointMap["avatar_mFootLeft"] = "mFootLeft";
+ mJointMap["avatar_mToeLeft"] = "mToeLeft";
+
+
+ mJointMap["hip"] = "mPelvis";
+ mJointMap["abdomen"] = "mTorso";
+ mJointMap["chest"] = "mChest";
+ mJointMap["neck"] = "mNeck";
+ mJointMap["head"] = "mHead";
+ mJointMap["figureHair"] = "mSkull";
+ mJointMap["lCollar"] = "mCollarLeft";
+ mJointMap["lShldr"] = "mShoulderLeft";
+ mJointMap["lForeArm"] = "mElbowLeft";
+ mJointMap["lHand"] = "mWristLeft";
+ mJointMap["rCollar"] = "mCollarRight";
+ mJointMap["rShldr"] = "mShoulderRight";
+ mJointMap["rForeArm"] = "mElbowRight";
+ mJointMap["rHand"] = "mWristRight";
+ mJointMap["rThigh"] = "mHipRight";
+ mJointMap["rShin"] = "mKneeRight";
+ mJointMap["rFoot"] = "mFootRight";
+ mJointMap["lThigh"] = "mHipLeft";
+ mJointMap["lShin"] = "mKneeLeft";
+ mJointMap["lFoot"] = "mFootLeft";
+
+ //move into joint mapper class
+ mMasterJointList.push_front("mPelvis");
+ mMasterJointList.push_front("mTorso");
+ mMasterJointList.push_front("mChest");
+ mMasterJointList.push_front("mNeck");
+ mMasterJointList.push_front("mHead");
+ mMasterJointList.push_front("mSkull");
+ mMasterJointList.push_front("mCollarLeft");
+ mMasterJointList.push_front("mShoulderLeft");
+ mMasterJointList.push_front("mElbowLeft");
+ mMasterJointList.push_front("mWristLeft");
+ mMasterJointList.push_front("mCollarRight");
+ mMasterJointList.push_front("mShoulderRight");
+ mMasterJointList.push_front("mElbowRight");
+ mMasterJointList.push_front("mWristRight");
+ mMasterJointList.push_front("mHipRight");
+ mMasterJointList.push_front("mKneeRight");
+ mMasterJointList.push_front("mFootRight");
+ mMasterJointList.push_front("mHipLeft");
+ mMasterJointList.push_front("mKneeLeft");
+ mMasterJointList.push_front("mFootLeft");
+}
+
+void stretch_extents(LLModel* model, LLMatrix4a& mat, LLVector4a& min, LLVector4a& max, BOOL& first_transform)
+{
+ LLVector4a box[] =
+ {
+ LLVector4a(-1, 1,-1),
+ LLVector4a(-1, 1, 1),
+ LLVector4a(-1,-1,-1),
+ LLVector4a(-1,-1, 1),
+ LLVector4a( 1, 1,-1),
+ LLVector4a( 1, 1, 1),
+ LLVector4a( 1,-1,-1),
+ LLVector4a( 1,-1, 1),
+ };
+
+ for (S32 j = 0; j < model->getNumVolumeFaces(); ++j)
+ {
+ const LLVolumeFace& face = model->getVolumeFace(j);
+
+ LLVector4a center;
+ center.setAdd(face.mExtents[0], face.mExtents[1]);
+ center.mul(0.5f);
+ LLVector4a size;
+ size.setSub(face.mExtents[1],face.mExtents[0]);
+ size.mul(0.5f);
+
+ for (U32 i = 0; i < 8; i++)
+ {
+ LLVector4a t;
+ t.setMul(size, box[i]);
+ t.add(center);
+
+ LLVector4a v;
+
+ mat.affineTransform(t, v);
+
+ if (first_transform)
+ {
+ first_transform = FALSE;
+ min = max = v;
+ }
+ else
+ {
+ update_min_max(min, max, v);
+ }
+ }
+ }
+}
+
+void stretch_extents(LLModel* model, LLMatrix4& mat, LLVector3& min, LLVector3& max, BOOL& first_transform)
+{
+ LLVector4a mina, maxa;
+ LLMatrix4a mata;
+
+ mata.loadu(mat);
+ mina.load3(min.mV);
+ maxa.load3(max.mV);
+
+ stretch_extents(model, mata, mina, maxa, first_transform);
+
+ min.set(mina.getF32ptr());
+ max.set(maxa.getF32ptr());
+}
+
+void LLModelLoader::run()
+{
+ DAE dae;
+ domCOLLADA* dom = dae.open(mFilename);
+
+ if (dom)
+ {
+ daeDatabase* db = dae.getDatabase();
+
+ daeInt count = db->getElementCount(NULL, COLLADA_TYPE_MESH);
+
+ daeDocument* doc = dae.getDoc(mFilename);
+ if (!doc)
+ {
+ llwarns << "can't find internal doc" << llendl;
+ return;
+ }
+
+ daeElement* root = doc->getDomRoot();
+ if (!root)
+ {
+ llwarns << "document has no root" << llendl;
+ return;
+ }
+
+ //get unit scale
+ mTransform.setIdentity();
+
+ domAsset::domUnit* unit = daeSafeCast<domAsset::domUnit>(root->getDescendant(daeElement::matchType(domAsset::domUnit::ID())));
+
+ if (unit)
+ {
+ F32 meter = unit->getMeter();
+ mTransform.mMatrix[0][0] = meter;
+ mTransform.mMatrix[1][1] = meter;
+ mTransform.mMatrix[2][2] = meter;
+ }
+
+ //get up axis rotation
+ LLMatrix4 rotation;
+
+ domUpAxisType up = UPAXISTYPE_Y_UP; // default is Y_UP
+ domAsset::domUp_axis* up_axis =
+ daeSafeCast<domAsset::domUp_axis>(root->getDescendant(daeElement::matchType(domAsset::domUp_axis::ID())));
+
+ if (up_axis)
+ {
+ up = up_axis->getValue();
+ }
+
+ if (up == UPAXISTYPE_X_UP)
+ {
+ rotation.initRotation(0.0f, 90.0f * DEG_TO_RAD, 0.0f);
+ }
+ else if (up == UPAXISTYPE_Y_UP)
+ {
+ rotation.initRotation(90.0f * DEG_TO_RAD, 0.0f, 0.0f);
+ }
+
+ rotation *= mTransform;
+ mTransform = rotation;
+
+
+ for (daeInt idx = 0; idx < count; ++idx)
+ { //build map of domEntities to LLModel
+ domMesh* mesh = NULL;
+ db->getElement((daeElement**) &mesh, idx, NULL, COLLADA_TYPE_MESH);
+
+ if (mesh)
+ {
+ LLPointer<LLModel> model = LLModel::loadModelFromDomMesh(mesh);
+
+ if (model.notNull() && validate_model(model))
+ {
+ mModelList.push_back(model);
+ mModel[mesh] = model;
+ }
+ }
+ }
+
+ count = db->getElementCount(NULL, COLLADA_TYPE_SKIN);
+ for (daeInt idx = 0; idx < count; ++idx)
+ { //add skinned meshes as instances
+ domSkin* skin = NULL;
+ db->getElement((daeElement**) &skin, idx, NULL, COLLADA_TYPE_SKIN);
+
+ if (skin)
+ {
+ domGeometry* geom = daeSafeCast<domGeometry>(skin->getSource().getElement());
+
+ if (geom)
+ {
+ domMesh* mesh = geom->getMesh();
+ if (mesh)
+ {
+ LLModel* model = mModel[mesh];
+ if (model)
+ {
+ LLVector3 mesh_scale_vector;
+ LLVector3 mesh_translation_vector;
+ model->getNormalizedScaleTranslation(mesh_scale_vector, mesh_translation_vector);
+
+ LLMatrix4 normalized_transformation;
+ normalized_transformation.setTranslation(mesh_translation_vector);
+
+ LLMatrix4 mesh_scale;
+ mesh_scale.initScale(mesh_scale_vector);
+ mesh_scale *= normalized_transformation;
+ normalized_transformation = mesh_scale;
+
+ glh::matrix4f inv_mat((F32*) normalized_transformation.mMatrix);
+ inv_mat = inv_mat.inverse();
+ LLMatrix4 inverse_normalized_transformation(inv_mat.m);
+
+ domSkin::domBind_shape_matrix* bind_mat = skin->getBind_shape_matrix();
+
+ if (bind_mat)
+ { //get bind shape matrix
+ domFloat4x4& dom_value = bind_mat->getValue();
+
+ for (int i = 0; i < 4; i++)
+ {
+ for(int j = 0; j < 4; j++)
+ {
+ model->mBindShapeMatrix.mMatrix[i][j] = dom_value[i + j*4];
+ }
+ }
+
+ LLMatrix4 trans = normalized_transformation;
+ trans *= model->mBindShapeMatrix;
+ model->mBindShapeMatrix = trans;
+
+ }
+
+
+ //The joint transfom map that we'll populate below
+ std::map<std::string,LLMatrix4> jointTransforms;
+ jointTransforms.clear();
+
+ //Some collada setup for accessing the skeleton
+ daeElement* pElement = 0;
+ dae.getDatabase()->getElement( &pElement, 0, 0, "skeleton" );
+
+ //Try to get at the skeletal instance controller
+ domInstance_controller::domSkeleton* pSkeleton = daeSafeCast<domInstance_controller::domSkeleton>( pElement );
+ bool missingSkeletonOrScene = false;
+
+ //If no skeleton, do a breadth-first search to get at specific joints
+ if ( !pSkeleton )
+ {
+ daeElement* pScene = root->getDescendant("visual_scene");
+ if ( !pScene )
+ {
+ llwarns<<"No visual scene - unable to parse bone offsets "<<llendl;
+ missingSkeletonOrScene = true;
+ }
+ else
+ {
+ //Get the children at this level
+ daeTArray< daeSmartRef<daeElement> > children = pScene->getChildren();
+ S32 childCount = children.getCount();
+
+ //Process any children that are joints
+ //Not all children are joints, some code be ambient lights, cameras, geometry etc..
+ for (S32 i = 0; i < childCount; ++i)
+ {
+ domNode* pNode = daeSafeCast<domNode>(children[i]);
+ if ( isNodeAJoint( pNode ) )
+ {
+ processJointNode( pNode, jointTransforms );
+ }
+ }
+ }
+ }
+ else
+ //Has Skeleton
+ {
+ //Get the root node of the skeleton
+ daeElement* pSkeletonRootNode = pSkeleton->getValue().getElement();
+ if ( pSkeletonRootNode )
+ {
+ //Once we have the root node - start acccessing it's joint components
+ const int jointCnt = mJointMap.size();
+ std::map<std::string, std::string> :: const_iterator jointIt = mJointMap.begin();
+
+ //Loop over all the possible joints within the .dae - using the allowed joint list in the ctor.
+ for ( int i=0; i<jointCnt; ++i, ++jointIt )
+ {
+ //Build a joint for the resolver to work with
+ char str[64]={0};
+ sprintf(str,"./%s",(*jointIt).second.c_str() );
+ //llwarns<<"Joint "<< str <<llendl;
+
+ //Setup the resolver
+ daeSIDResolver resolver( pSkeletonRootNode, str );
+
+ //Look for the joint
+ domNode* pJoint = daeSafeCast<domNode>( resolver.getElement() );
+ if ( pJoint )
+ {
+ //Pull out the translate id and store it in the jointTranslations map
+ daeSIDResolver jointResolver( pJoint, "./translate" );
+ domTranslate* pTranslate = daeSafeCast<domTranslate>( jointResolver.getElement() );
+
+ LLMatrix4 workingTransform;
+
+ //Translation via SID
+ if ( pTranslate )
+ {
+ extractTranslation( pTranslate, workingTransform );
+ }
+ else
+ {
+ //Translation via child from element
+ daeElement* pTranslateElement = getChildFromElement( pJoint, "translate" );
+ if ( pTranslateElement && pTranslateElement->typeID() != domTranslate::ID() )
+ {
+ llwarns<< "The found element is not a translate node" <<llendl;
+ missingSkeletonOrScene = true;
+ }
+ else
+ {
+ extractTranslationViaElement( pTranslateElement, workingTransform );
+ }
+ }
+
+ //Store the joint transform w/respect to it's name.
+ jointTransforms[(*jointIt).second.c_str()] = workingTransform;
+ }
+ }
+
+ //If anything failed in regards to extracting the skeleton, joints or translation id,
+ //mention it
+ if ( missingSkeletonOrScene )
+ {
+ llwarns<< "Partial jointmap found in asset - did you mean to just have a partial map?" << llendl;
+ }
+ }//got skeleton?
+ }
+
+
+ domSkin::domJoints* joints = skin->getJoints();
+
+ domInputLocal_Array& joint_input = joints->getInput_array();
+
+ for (size_t i = 0; i < joint_input.getCount(); ++i)
+ {
+ domInputLocal* input = joint_input.get(i);
+ xsNMTOKEN semantic = input->getSemantic();
+
+ if (strcmp(semantic, COMMON_PROFILE_INPUT_JOINT) == 0)
+ { //found joint source, fill model->mJointMap and model->mJointList
+ daeElement* elem = input->getSource().getElement();
+
+ domSource* source = daeSafeCast<domSource>(elem);
+ if (source)
+ {
+
+
+ domName_array* names_source = source->getName_array();
+
+ if (names_source)
+ {
+ domListOfNames &names = names_source->getValue();
+
+ for (size_t j = 0; j < names.getCount(); ++j)
+ {
+ std::string name(names.get(j));
+ if (mJointMap.find(name) != mJointMap.end())
+ {
+ name = mJointMap[name];
+ }
+ model->mJointList.push_back(name);
+ model->mJointMap[name] = j;
+ }
+ }
+ else
+ {
+ domIDREF_array* names_source = source->getIDREF_array();
+ if (names_source)
+ {
+ xsIDREFS& names = names_source->getValue();
+
+ for (size_t j = 0; j < names.getCount(); ++j)
+ {
+ std::string name(names.get(j).getID());
+ if (mJointMap.find(name) != mJointMap.end())
+ {
+ name = mJointMap[name];
+ }
+ model->mJointList.push_back(name);
+ model->mJointMap[name] = j;
+ }
+ }
+ }
+ }
+ }
+ else if (strcmp(semantic, COMMON_PROFILE_INPUT_INV_BIND_MATRIX) == 0)
+ { //found inv_bind_matrix array, fill model->mInvBindMatrix
+ domSource* source = daeSafeCast<domSource>(input->getSource().getElement());
+ if (source)
+ {
+ domFloat_array* t = source->getFloat_array();
+ if (t)
+ {
+ domListOfFloats& transform = t->getValue();
+ S32 count = transform.getCount()/16;
+
+ for (S32 k = 0; k < count; ++k)
+ {
+ LLMatrix4 mat;
+
+ for (int i = 0; i < 4; i++)
+ {
+ for(int j = 0; j < 4; j++)
+ {
+ mat.mMatrix[i][j] = transform[k*16 + i + j*4];
+ }
+ }
+
+ model->mInvBindMatrix.push_back(mat);
+ }
+ }
+ }
+ }
+ }
+
+ //Now that we've parsed the joint array, let's determine if we have a full rig
+ //(which means we have all the joints that are required for an avatar versus
+ //a skinned asset attached to a node in a file that contains an entire skeleton,
+ //but does not use the skeleton).
+
+ if ( !model->mJointList.empty() && doesJointArrayContainACompleteRig( model->mJointList ) )
+ {
+ mResetJoints = true;
+ }
+
+ if ( !missingSkeletonOrScene )
+ {
+ //Set the joint translations on the avatar - if it's a full mapping
+ //The joints are reset in the dtor
+ if ( mResetJoints )
+ {
+ std::map<std::string, std::string> :: const_iterator masterJointIt = mJointMap.begin();
+ std::map<std::string, std::string> :: const_iterator masterJointItEnd = mJointMap.end();
+ for (;masterJointIt!=masterJointItEnd;++masterJointIt )
+ {
+ std::string lookingForJoint = (*masterJointIt).first.c_str();
+
+ if ( jointTransforms.find( lookingForJoint ) != jointTransforms.end() )
+ {
+ //llinfos<<"joint "<<lookingForJoint.c_str()<<llendl;
+ LLMatrix4 jointTransform = jointTransforms[lookingForJoint];
+ LLJoint* pJoint = gAgentAvatarp->getJoint( lookingForJoint );
+ if ( pJoint )
+ {
+ pJoint->storeCurrentXform( jointTransform.getTranslation() );
+ }
+ else
+ {
+ //Most likely an error in the asset.
+ llwarns<<"Tried to apply joint position from .dae, but it did not exist in the avatar rig." << llendl;
+ }
+ }
+ }
+ }
+ } //missingSkeletonOrScene
+
+ //We need to construct the alternate bind matrix (which contains the new joint positions)
+ //in the same order as they were stored in the joint buffer. The joints associated
+ //with the skeleton are not stored in the same order as they are in the exported joint buffer.
+ //This remaps the skeletal joints to be in the same order as the joints stored in the model.
+ std::vector<std::string> :: const_iterator jointIt = model->mJointList.begin();
+ const int jointCnt = model->mJointList.size();
+ for ( int i=0; i<jointCnt; ++i, ++jointIt )
+ {
+ std::string lookingForJoint = (*jointIt).c_str();
+ //Look for the joint xform that we extracted from the skeleton, using the jointIt as the key
+ //and store it in the alternate bind matrix
+ if ( jointTransforms.find( lookingForJoint ) != jointTransforms.end() )
+ {
+ LLMatrix4 jointTransform = jointTransforms[lookingForJoint];
+ LLMatrix4 newInverse = model->mInvBindMatrix[i];
+ newInverse.setTranslation( jointTransforms[lookingForJoint].getTranslation() );
+ model->mAlternateBindMatrix.push_back( newInverse );
+ }
+ else
+ {
+ llwarns<<"Possibly misnamed/missing joint [" <<lookingForJoint.c_str()<<" ] "<<llendl;
+ }
+ }
+
+ //grab raw position array
+
+ domVertices* verts = mesh->getVertices();
+ if (verts)
+ {
+ domInputLocal_Array& inputs = verts->getInput_array();
+ for (size_t i = 0; i < inputs.getCount() && model->mPosition.empty(); ++i)
+ {
+ if (strcmp(inputs[i]->getSemantic(), COMMON_PROFILE_INPUT_POSITION) == 0)
+ {
+ domSource* pos_source = daeSafeCast<domSource>(inputs[i]->getSource().getElement());
+ if (pos_source)
+ {
+ domFloat_array* pos_array = pos_source->getFloat_array();
+ if (pos_array)
+ {
+ domListOfFloats& pos = pos_array->getValue();
+
+ for (size_t j = 0; j < pos.getCount(); j += 3)
+ {
+ if (pos.getCount() <= j+2)
+ {
+ llerrs << "WTF?" << llendl;
+ }
+
+ LLVector3 v(pos[j], pos[j+1], pos[j+2]);
+
+ //transform from COLLADA space to volume space
+ v = v * inverse_normalized_transformation;
+
+ model->mPosition.push_back(v);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ //grab skin weights array
+ domSkin::domVertex_weights* weights = skin->getVertex_weights();
+ if (weights)
+ {
+ domInputLocalOffset_Array& inputs = weights->getInput_array();
+ domFloat_array* vertex_weights = NULL;
+ for (size_t i = 0; i < inputs.getCount(); ++i)
+ {
+ if (strcmp(inputs[i]->getSemantic(), COMMON_PROFILE_INPUT_WEIGHT) == 0)
+ {
+ domSource* weight_source = daeSafeCast<domSource>(inputs[i]->getSource().getElement());
+ if (weight_source)
+ {
+ vertex_weights = weight_source->getFloat_array();
+ }
+ }
+ }
+
+ if (vertex_weights)
+ {
+ domListOfFloats& w = vertex_weights->getValue();
+ domListOfUInts& vcount = weights->getVcount()->getValue();
+ domListOfInts& v = weights->getV()->getValue();
+
+ U32 c_idx = 0;
+ for (size_t vc_idx = 0; vc_idx < vcount.getCount(); ++vc_idx)
+ { //for each vertex
+ daeUInt count = vcount[vc_idx];
+
+ //create list of weights that influence this vertex
+ LLModel::weight_list weight_list;
+
+ for (daeUInt i = 0; i < count; ++i)
+ { //for each weight
+ daeInt joint_idx = v[c_idx++];
+ daeInt weight_idx = v[c_idx++];
+
+ if (joint_idx == -1)
+ {
+ //ignore bindings to bind_shape_matrix
+ continue;
+ }
+
+ F32 weight_value = w[weight_idx];
+
+ weight_list.push_back(LLModel::JointWeight(joint_idx, weight_value));
+ }
+
+ //sort by joint weight
+ std::sort(weight_list.begin(), weight_list.end(), LLModel::CompareWeightGreater());
+
+ std::vector<LLModel::JointWeight> wght;
+
+ F32 total = 0.f;
+
+ for (U32 i = 0; i < llmin((U32) 4, (U32) weight_list.size()); ++i)
+ { //take up to 4 most significant weights
+ if (weight_list[i].mWeight > 0.f)
+ {
+ wght.push_back( weight_list[i] );
+ total += weight_list[i].mWeight;
+ }
+ }
+
+ F32 scale = 1.f/total;
+ if (scale != 1.f)
+ { //normalize weights
+ for (U32 i = 0; i < wght.size(); ++i)
+ {
+ wght[i].mWeight *= scale;
+ }
+ }
+
+ model->mSkinWeights[model->mPosition[vc_idx]] = wght;
+ }
+
+ //add instance to scene for this model
+
+ LLMatrix4 transformation = mTransform;
+ // adjust the transformation to compensate for mesh normalization
+
+ LLMatrix4 mesh_translation;
+ mesh_translation.setTranslation(mesh_translation_vector);
+ mesh_translation *= transformation;
+ transformation = mesh_translation;
+
+ LLMatrix4 mesh_scale;
+ mesh_scale.initScale(mesh_scale_vector);
+ mesh_scale *= transformation;
+ transformation = mesh_scale;
+
+ std::vector<LLImportMaterial> materials;
+ materials.resize(model->getNumVolumeFaces());
+ mScene[transformation].push_back(LLModelInstance(model, model->mLabel, transformation, materials));
+ stretch_extents(model, transformation, mExtents[0], mExtents[1], mFirstTransform);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ daeElement* scene = root->getDescendant("visual_scene");
+
+ if (!scene)
+ {
+ llwarns << "document has no visual_scene" << llendl;
+ setLoadState( ERROR_PARSING );
+ return;
+ }
+ setLoadState( DONE );
+
+ processElement(scene);
+
+ handlePivotPoint( root );
+
+ doOnIdleOneTime(boost::bind(&LLModelPreview::loadModelCallback,mPreview,mLod));
+ }
+}
+
+void LLModelLoader::handlePivotPoint( daeElement* pRoot )
+{
+ //Import an optional pivot point - a pivot point is just a node in the visual scene named "AssetPivot"
+ //If no assetpivot is found then the asset will use the SL default
+ daeElement* pScene = pRoot->getDescendant("visual_scene");
+ if ( pScene )
+ {
+ daeTArray< daeSmartRef<daeElement> > children = pScene->getChildren();
+ S32 childCount = children.getCount();
+ for (S32 i = 0; i < childCount; ++i)
+ {
+ domNode* pNode = daeSafeCast<domNode>(children[i]);
+ if ( pNode && isNodeAPivotPoint( pNode ) )
+ {
+ LLMatrix4 workingTransform;
+ daeSIDResolver nodeResolver( pNode, "./translate" );
+ domTranslate* pTranslate = daeSafeCast<domTranslate>( nodeResolver.getElement() );
+ //Translation via SID was successful
+ //todo#extract via element as well
+ if ( pTranslate )
+ {
+ extractTranslation( pTranslate, workingTransform );
+ mPreview->setModelPivot( workingTransform.getTranslation() );
+ mPreview->setHasPivot( true );
+ }
+ }
+ }
+ }
+}
+
+bool LLModelLoader::doesJointArrayContainACompleteRig( const std::vector<std::string> &jointListFromModel )
+{
+ std::deque<std::string> :: const_iterator masterJointIt = mMasterJointList.begin();
+ std::deque<std::string> :: const_iterator masterJointEndIt = mMasterJointList.end();
+
+ std::vector<std::string> :: const_iterator modelJointIt = jointListFromModel.begin();
+ std::vector<std::string> :: const_iterator modelJointItEnd = jointListFromModel.end();
+
+ bool found = false;
+ for ( ;masterJointIt!=masterJointEndIt;++masterJointIt )
+ {
+ found = false;
+ modelJointIt = jointListFromModel.begin();
+ for ( ;modelJointIt!=modelJointItEnd; ++modelJointIt )
+ {
+ if ( *masterJointIt == *modelJointIt )
+ {
+ found = true;
+ break;
+ }
+ }
+ if ( !found )
+ {
+ llinfos<<" Asset did not contain the joint (if you're u/l a fully rigged asset - it is required)." << *masterJointIt<< llendl;
+ break;
+ }
+ }
+
+ return found;
+}
+
+//called in the main thread
+void LLModelLoader::loadTextures()
+{
+ BOOL is_paused = isPaused() ;
+ pause() ; //pause the loader
+
+ for(scene::iterator iter = mScene.begin(); iter != mScene.end(); ++iter)
+ {
+ for(U32 i = 0 ; i < iter->second.size(); i++)
+ {
+ for(U32 j = 0 ; j < iter->second[i].mMaterial.size() ; j++)
+ {
+ if(!iter->second[i].mMaterial[j].mDiffuseMapFilename.empty())
+ {
+ iter->second[i].mMaterial[j].mDiffuseMap =
+ LLViewerTextureManager::getFetchedTextureFromUrl("file://" + iter->second[i].mMaterial[j].mDiffuseMapFilename, TRUE, LLViewerTexture::BOOST_PREVIEW);
+ iter->second[i].mMaterial[j].mDiffuseMap->setLoadedCallback(LLModelPreview::textureLoadedCallback, 0, TRUE, FALSE, mPreview, NULL, FALSE);
+ iter->second[i].mMaterial[j].mDiffuseMap->forceToSaveRawImage();
+ }
+ }
+ }
+ }
+
+ if(!is_paused)
+ {
+ unpause() ;
+ }
+}
+
+bool LLModelLoader::isNodeAJoint( domNode* pNode )
+{
+ if ( pNode->getName() == NULL)
+ {
+ return false;
+ }
+
+ if ( mJointMap.find( pNode->getName() ) != mJointMap.end() )
+ {
+ return true;
+ }
+
+ return false;
+}
+
+bool LLModelLoader::isNodeAPivotPoint( domNode* pNode )
+{
+ bool result = false;
+
+ if ( pNode && pNode->getName() )
+ {
+ std::string name = pNode->getName();
+ if ( name == "AssetPivot" )
+ {
+ result = true;
+ }
+ else
+ {
+ result = false;
+ }
+ }
+ return result;
+}
+
+void LLModelLoader::extractTranslation( domTranslate* pTranslate, LLMatrix4& transform )
+{
+ domFloat3 jointTrans = pTranslate->getValue();
+ LLVector3 singleJointTranslation( jointTrans[0], jointTrans[1], jointTrans[2] );
+ transform.setTranslation( singleJointTranslation );
+}
+
+void LLModelLoader::extractTranslationViaElement( daeElement* pTranslateElement, LLMatrix4& transform )
+{
+ domTranslate* pTranslateChild = dynamic_cast<domTranslate*>( pTranslateElement );
+ domFloat3 translateChild = pTranslateChild->getValue();
+ LLVector3 singleJointTranslation( translateChild[0], translateChild[1], translateChild[2] );
+ transform.setTranslation( singleJointTranslation );
+}
+
+void LLModelLoader::processJointNode( domNode* pNode, std::map<std::string,LLMatrix4>& jointTransforms )
+{
+ if (pNode->getName() == NULL)
+ {
+ llwarns << "nameless node, can't process" << llendl;
+ return;
+ }
+
+ //llwarns<<"ProcessJointNode# Node:" <<pNode->getName()<<llendl;
+
+ //1. handle the incoming node - extract out translation via SID or element
+
+ LLMatrix4 workingTransform;
+
+ //Pull out the translate id and store it in the jointTranslations map
+ daeSIDResolver jointResolver( pNode, "./translate" );
+ domTranslate* pTranslate = daeSafeCast<domTranslate>( jointResolver.getElement() );
+
+ //Translation via SID was successful
+ if ( pTranslate )
+ {
+ extractTranslation( pTranslate, workingTransform );
+ }
+ else
+ {
+ //Translation via child from element
+ daeElement* pTranslateElement = getChildFromElement( pNode, "translate" );
+ if ( !pTranslateElement || pTranslateElement->typeID() != domTranslate::ID() )
+ {
+ //llwarns<< "The found element is not a translate node" <<llendl;
+ daeSIDResolver jointResolver( pNode, "./matrix" );
+ domMatrix* pMatrix = daeSafeCast<domMatrix>( jointResolver.getElement() );
+ if ( pMatrix )
+ {
+ //llinfos<<"A matrix SID was however found!"<<llendl;
+ domFloat4x4 domArray = pMatrix->getValue();
+ for ( int i = 0; i < 4; i++ )
+ {
+ for( int j = 0; j < 4; j++ )
+ {
+ workingTransform.mMatrix[i][j] = domArray[i + j*4];
+ }
+ }
+ }
+ else
+ {
+ llwarns<< "The found element is not translate or matrix node - most likely a corrupt export!" <<llendl;
+ }
+ }
+ else
+ {
+ extractTranslationViaElement( pTranslateElement, workingTransform );
+ }
+ }
+
+ //Store the working transform relative to the nodes name.
+ jointTransforms[ pNode->getName() ] = workingTransform;
+
+ //2. handle the nodes children
+
+ //Gather and handle the incoming nodes children
+ daeTArray< daeSmartRef<daeElement> > childOfChild = pNode->getChildren();
+ S32 childOfChildCount = childOfChild.getCount();
+
+ for (S32 i = 0; i < childOfChildCount; ++i)
+ {
+ domNode* pChildNode = daeSafeCast<domNode>( childOfChild[i] );
+ if ( pChildNode )
+ {
+ processJointNode( pChildNode, jointTransforms );
+ }
+ }
+}
+
+daeElement* LLModelLoader::getChildFromElement( daeElement* pElement, std::string const & name )
+{
+ daeElement* pChildOfElement = pElement->getChild( name.c_str() );
+ if ( pChildOfElement )
+ {
+ return pChildOfElement;
+ }
+ llwarns<< "Could not find a child [" << name << "] for the element: \"" << pElement->getAttribute("id") << "\"" << llendl;
+ return NULL;
+}
+
+void LLModelLoader::processElement(daeElement* element)
+{
+ LLMatrix4 saved_transform = mTransform;
+
+ domTranslate* translate = daeSafeCast<domTranslate>(element);
+ if (translate)
+ {
+ domFloat3 dom_value = translate->getValue();
+
+ LLMatrix4 translation;
+ translation.setTranslation(LLVector3(dom_value[0], dom_value[1], dom_value[2]));
+
+ translation *= mTransform;
+ mTransform = translation;
+ }
+
+ domRotate* rotate = daeSafeCast<domRotate>(element);
+ if (rotate)
+ {
+ domFloat4 dom_value = rotate->getValue();
+
+ LLMatrix4 rotation;
+ rotation.initRotTrans(dom_value[3] * DEG_TO_RAD, LLVector3(dom_value[0], dom_value[1], dom_value[2]), LLVector3(0, 0, 0));
+
+ rotation *= mTransform;
+ mTransform = rotation;
+ }
+
+ domScale* scale = daeSafeCast<domScale>(element);
+ if (scale)
+ {
+ domFloat3 dom_value = scale->getValue();
+
+ LLMatrix4 scaling;
+ scaling.initScale(LLVector3(dom_value[0], dom_value[1], dom_value[2]));
+
+ scaling *= mTransform;
+ mTransform = scaling;
+ }
+
+ domMatrix* matrix = daeSafeCast<domMatrix>(element);
+ if (matrix)
+ {
+ domFloat4x4 dom_value = matrix->getValue();
+
+ LLMatrix4 matrix_transform;
+
+ for (int i = 0; i < 4; i++)
+ {
+ for(int j = 0; j < 4; j++)
+ {
+ matrix_transform.mMatrix[i][j] = dom_value[i + j*4];
+ }
+ }
+
+ matrix_transform *= mTransform;
+ mTransform = matrix_transform;
+ }
+
+ domInstance_geometry* instance_geo = daeSafeCast<domInstance_geometry>(element);
+ if (instance_geo)
+ {
+ domGeometry* geo = daeSafeCast<domGeometry>(instance_geo->getUrl().getElement());
+ if (geo)
+ {
+ domMesh* mesh = daeSafeCast<domMesh>(geo->getDescendant(daeElement::matchType(domMesh::ID())));
+ if (mesh)
+ {
+ LLModel* model = mModel[mesh];
+ if (model)
+ {
+ LLMatrix4 transformation = mTransform;
+
+ std::vector<LLImportMaterial> materials = getMaterials(model, instance_geo);
+
+ // adjust the transformation to compensate for mesh normalization
+ LLVector3 mesh_scale_vector;
+ LLVector3 mesh_translation_vector;
+ model->getNormalizedScaleTranslation(mesh_scale_vector, mesh_translation_vector);
+
+ LLMatrix4 mesh_translation;
+ mesh_translation.setTranslation(mesh_translation_vector);
+ mesh_translation *= transformation;
+ transformation = mesh_translation;
+
+ LLMatrix4 mesh_scale;
+ mesh_scale.initScale(mesh_scale_vector);
+ mesh_scale *= transformation;
+ transformation = mesh_scale;
+
+ std::string label = getElementLabel(instance_geo);
+ mScene[transformation].push_back(LLModelInstance(model, label, transformation, materials));
+
+ stretch_extents(model, transformation, mExtents[0], mExtents[1], mFirstTransform);
+ }
+ }
+ }
+ }
+
+ domInstance_node* instance_node = daeSafeCast<domInstance_node>(element);
+ if (instance_node)
+ {
+ daeElement* instance = instance_node->getUrl().getElement();
+ if (instance)
+ {
+ processElement(instance);
+ }
+ }
+
+ //process children
+ daeTArray< daeSmartRef<daeElement> > children = element->getChildren();
+ for (S32 i = 0; i < children.getCount(); i++)
+ {
+ processElement(children[i]);
+ }
+
+ domNode* node = daeSafeCast<domNode>(element);
+ if (node)
+ { //this element was a node, restore transform before processiing siblings
+ mTransform = saved_transform;
+ }
+}
+
+std::vector<LLImportMaterial> LLModelLoader::getMaterials(LLModel* model, domInstance_geometry* instance_geo)
+{
+ std::vector<LLImportMaterial> materials;
+ for (int i = 0; i < model->mMaterialList.size(); i++)
+ {
+ LLImportMaterial import_material;
+
+ domInstance_material* instance_mat = NULL;
+
+ domBind_material::domTechnique_common* technique =
+ daeSafeCast<domBind_material::domTechnique_common>(instance_geo->getDescendant(daeElement::matchType(domBind_material::domTechnique_common::ID())));
+
+ if (technique)
+ {
+ daeTArray< daeSmartRef<domInstance_material> > inst_materials = technique->getChildrenByType<domInstance_material>();
+ for (int j = 0; j < inst_materials.getCount(); j++)
+ {
+ std::string symbol(inst_materials[j]->getSymbol());
+
+ if (symbol == model->mMaterialList[i]) // found the binding
+ {
+ instance_mat = inst_materials[j];
+ }
+ }
+ }
+
+ if (instance_mat)
+ {
+ domMaterial* material = daeSafeCast<domMaterial>(instance_mat->getTarget().getElement());
+ if (material)
+ {
+ domInstance_effect* instance_effect =
+ daeSafeCast<domInstance_effect>(material->getDescendant(daeElement::matchType(domInstance_effect::ID())));
+ if (instance_effect)
+ {
+ domEffect* effect = daeSafeCast<domEffect>(instance_effect->getUrl().getElement());
+ if (effect)
+ {
+ domProfile_COMMON* profile =
+ daeSafeCast<domProfile_COMMON>(effect->getDescendant(daeElement::matchType(domProfile_COMMON::ID())));
+ if (profile)
+ {
+ import_material = profileToMaterial(profile);
+ }
+ }
+ }
+ }
+ }
+
+ materials.push_back(import_material);
+ }
+
+ return materials;
+}
+
+LLImportMaterial LLModelLoader::profileToMaterial(domProfile_COMMON* material)
+{
+ LLImportMaterial mat;
+ mat.mFullbright = FALSE;
+
+ daeElement* diffuse = material->getDescendant("diffuse");
+ if (diffuse)
+ {
+ domCommon_color_or_texture_type_complexType::domTexture* texture =
+ daeSafeCast<domCommon_color_or_texture_type_complexType::domTexture>(diffuse->getDescendant("texture"));
+ if (texture)
+ {
+ domCommon_newparam_type_Array newparams = material->getNewparam_array();
+ for (S32 i = 0; i < newparams.getCount(); i++)
+ {
+ domFx_surface_common* surface = newparams[i]->getSurface();
+ if (surface)
+ {
+ domFx_surface_init_common* init = surface->getFx_surface_init_common();
+ if (init)
+ {
+ domFx_surface_init_from_common_Array init_from = init->getInit_from_array();
+
+ if (init_from.getCount() > i)
+ {
+ domImage* image = daeSafeCast<domImage>(init_from[i]->getValue().getElement());
+ if (image)
+ {
+ // we only support init_from now - embedded data will come later
+ domImage::domInit_from* init = image->getInit_from();
+ if (init)
+ {
+ mat.mDiffuseMapFilename = cdom::uriToNativePath(init->getValue().str());
+ mat.mDiffuseMapLabel = getElementLabel(material);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ domCommon_color_or_texture_type_complexType::domColor* color =
+ daeSafeCast<domCommon_color_or_texture_type_complexType::domColor>(diffuse->getDescendant("color"));
+ if (color)
+ {
+ domFx_color_common domfx_color = color->getValue();
+ LLColor4 value = LLColor4(domfx_color[0], domfx_color[1], domfx_color[2], domfx_color[3]);
+ mat.mDiffuseColor = value;
+ }
+ }
+
+ daeElement* emission = material->getDescendant("emission");
+ if (emission)
+ {
+ LLColor4 emission_color = getDaeColor(emission);
+ if (((emission_color[0] + emission_color[1] + emission_color[2]) / 3.0) > 0.25)
+ {
+ mat.mFullbright = TRUE;
+ }
+ }
+
+ return mat;
+}
+
+// try to get a decent label for this element
+std::string LLModelLoader::getElementLabel(daeElement *element)
+{
+ // if we have a name attribute, use it
+ std::string name = element->getAttribute("name");
+ if (name.length())
+ {
+ return name;
+ }
+
+ // if we have an ID attribute, use it
+ if (element->getID())
+ {
+ return std::string(element->getID());
+ }
+
+ // if we have a parent, use it
+ daeElement* parent = element->getParent();
+ if (parent)
+ {
+ // if parent has a name, use it
+ std::string name = parent->getAttribute("name");
+ if (name.length())
+ {
+ return name;
+ }
+
+ // if parent has an ID, use it
+ if (parent->getID())
+ {
+ return std::string(parent->getID());
+ }
+ }
+
+ // try to use our type
+ daeString element_name = element->getElementName();
+ if (element_name)
+ {
+ return std::string(element_name);
+ }
+
+ // if all else fails, use "object"
+ return std::string("object");
+}
+
+LLColor4 LLModelLoader::getDaeColor(daeElement* element)
+{
+ LLColor4 value;
+ domCommon_color_or_texture_type_complexType::domColor* color =
+ daeSafeCast<domCommon_color_or_texture_type_complexType::domColor>(element->getDescendant("color"));
+ if (color)
+ {
+ domFx_color_common domfx_color = color->getValue();
+ value = LLColor4(domfx_color[0], domfx_color[1], domfx_color[2], domfx_color[3]);
+ }
+
+ return value;
+}
+
+//-----------------------------------------------------------------------------
+// LLModelPreview
+//-----------------------------------------------------------------------------
+
+LLModelPreview::LLModelPreview(S32 width, S32 height, LLFloater* fmp)
+: LLViewerDynamicTexture(width, height, 3, ORDER_MIDDLE, FALSE), LLMutex(NULL)
+, mPelvisZOffset( 0.0f )
+{
+ mNeedsUpdate = TRUE;
+ mCameraDistance = 0.f;
+ mCameraYaw = 0.f;
+ mCameraPitch = 0.f;
+ mCameraZoom = 1.f;
+ mTextureName = 0;
+ mPreviewLOD = 0;
+ mModelLoader = NULL;
+ mMaxTriangleLimit = 0;
+ mDirty = false;
+ mGenLOD = false;
+ mLoading = false;
+ mGroup = 0;
+ mBuildShareTolerance = 0.f;
+ mBuildQueueMode = GLOD_QUEUE_GREEDY;
+ mBuildBorderMode = GLOD_BORDER_UNLOCK;
+ mBuildOperator = GLOD_OPERATOR_EDGE_COLLAPSE;
+
+ for (U32 i = 0; i < LLModel::NUM_LODS; ++i)
+ {
+ mRequestedTriangleCount[i] = 0;
+ }
+
+ mViewOption["show_textures"] = false;
+
+ mFMP = fmp;
+
+ mHasPivot = false;
+ mModelPivot = LLVector3( 0.0f, 0.0f, 0.0f );
+
+ glodInit();
+}
+
+LLModelPreview::~LLModelPreview()
+{
+ if (mModelLoader)
+ {
+ delete mModelLoader;
+ mModelLoader = NULL;
+ }
+
+ //*HACK : *TODO : turn this back on when we understand why this crashes
+ //glodShutdown();
+}
+
+U32 LLModelPreview::calcResourceCost()
+{
+ assert_main_thread();
+
+ rebuildUploadData();
+
+ if (mFMP && mModelLoader)
+ {
+ if ( mModelLoader->getLoadState() != LLModelLoader::ERROR_PARSING )
+ {
+ mFMP->childEnable("ok_btn");
+ }
+ }
+
+ U32 cost = 0;
+ std::set<LLModel*> accounted;
+ U32 num_points = 0;
+ U32 num_hulls = 0;
+
+ F32 debug_scale = mFMP ? mFMP->childGetValue("import_scale").asReal() : 1.f;
+ mPelvisZOffset = mFMP ? mFMP->childGetValue("pelvis_offset").asReal() : 32.0f;
+
+ F32 streaming_cost = 0.f;
+ F32 physics_cost = 0.f;
+ for (U32 i = 0; i < mUploadData.size(); ++i)
+ {
+ LLModelInstance& instance = mUploadData[i];
+
+ if (accounted.find(instance.mModel) == accounted.end())
+ {
+ accounted.insert(instance.mModel);
+
+ LLModel::convex_hull_decomposition& decomp =
+ instance.mLOD[LLModel::LOD_PHYSICS] ?
+ instance.mLOD[LLModel::LOD_PHYSICS]->mConvexHullDecomp :
+ instance.mModel->mConvexHullDecomp;
+
+ LLSD ret = LLModel::writeModel(
+ "",
+ instance.mLOD[4],
+ instance.mLOD[3],
+ instance.mLOD[2],
+ instance.mLOD[1],
+ instance.mLOD[0],
+ decomp,
+ mFMP->childGetValue("upload_skin").asBoolean(),
+ mFMP->childGetValue("upload_joints").asBoolean(),
+ TRUE);
+ cost += gMeshRepo.calcResourceCost(ret);
+
+ num_hulls += decomp.size();
+ for (U32 i = 0; i < decomp.size(); ++i)
+ {
+ num_points += decomp[i].size();
+ }
+
+ //calculate streaming cost
+ LLMatrix4 transformation = instance.mTransform;
+
+ LLVector3 position = LLVector3(0, 0, 0) * transformation;
+
+ LLVector3 x_transformed = LLVector3(1, 0, 0) * transformation - position;
+ LLVector3 y_transformed = LLVector3(0, 1, 0) * transformation - position;
+ LLVector3 z_transformed = LLVector3(0, 0, 1) * transformation - position;
+ F32 x_length = x_transformed.normalize();
+ F32 y_length = y_transformed.normalize();
+ F32 z_length = z_transformed.normalize();
+ LLVector3 scale = LLVector3(x_length, y_length, z_length);
+
+ F32 radius = scale.length()*debug_scale;
+
+ streaming_cost += LLMeshRepository::getStreamingCost(ret, radius);
+ }
+ }
+
+ F32 scale = mFMP ? mFMP->childGetValue("import_scale").asReal()*2.f : 2.f;
+
+ mDetailsSignal(mPreviewScale[0]*scale, mPreviewScale[1]*scale, mPreviewScale[2]*scale, streaming_cost, physics_cost);
+
+ updateStatusMessages();
+
+ return cost;
+}
+
+void LLFloaterModelPreview::setDetails(F32 x, F32 y, F32 z, F32 streaming_cost, F32 physics_cost)
+{
+ childSetTextArg("import_dimensions", "[X]", llformat("%.3f", x));
+ childSetTextArg("import_dimensions", "[Y]", llformat("%.3f", y));
+ childSetTextArg("import_dimensions", "[Z]", llformat("%.3f", z));
+ childSetTextArg("streaming cost", "[COST]", llformat("%.3f", streaming_cost));
+ childSetTextArg("physics cost", "[COST]", llformat("%.3f", physics_cost));
+}
+
+void LLModelPreview::alterModelsPivot( void )
+{
+ for (LLModelLoader::model_list::iterator iter = mBaseModel.begin(); iter != mBaseModel.end(); ++iter)
+ {
+ if ( *iter )
+ {
+ (*iter)->offsetMesh( mModelPivot );
+ }
+ }
+
+ for ( int i=0;i<LLModel::NUM_LODS;++i )
+ {
+ for (LLModelLoader::model_list::iterator iter = mModel[i].begin(); iter != mModel[i].end(); ++iter)
+ {
+ if ( *iter )
+ {
+ (*iter)->offsetMesh( mModelPivot );
+ }
+ }
+ }
+}
+
+void LLModelPreview::rebuildUploadData()
+{
+ assert_main_thread();
+
+ mUploadData.clear();
+ mTextureSet.clear();
+
+ //fill uploaddata instance vectors from scene data
+
+ std::string requested_name = mFMP->getChild<LLUICtrl>("description_form")->getValue().asString();
+
+
+ LLSpinCtrl* scale_spinner = mFMP->getChild<LLSpinCtrl>("import_scale");
+
+ if (!scale_spinner)
+ {
+ llerrs << "floater_model_preview.xml MUST contain import_scale spinner." << llendl;
+ }
+
+ F32 scale = scale_spinner->getValue().asReal();
+
+ LLMatrix4 scale_mat;
+ scale_mat.initScale(LLVector3(scale, scale, scale));
+
+ F32 max_scale = 0.f;
+
+ if ( mBaseScene.size() > 0 )
+ {
+ mFMP->childEnable("ok_btn");
+ }
+
+ for (LLModelLoader::scene::iterator iter = mBaseScene.begin(); iter != mBaseScene.end(); ++iter)
+ { //for each transform in scene
+ LLMatrix4 mat = iter->first;
+
+ // compute position
+ LLVector3 position = LLVector3(0, 0, 0) * mat;
+
+ // compute scale
+ LLVector3 x_transformed = LLVector3(1, 0, 0) * mat - position;
+ LLVector3 y_transformed = LLVector3(0, 1, 0) * mat - position;
+ LLVector3 z_transformed = LLVector3(0, 0, 1) * mat - position;
+ F32 x_length = x_transformed.normalize();
+ F32 y_length = y_transformed.normalize();
+ F32 z_length = z_transformed.normalize();
+
+ max_scale = llmax(llmax(llmax(max_scale, x_length), y_length), z_length);
+
+ mat *= scale_mat;
+
+ for (LLModelLoader::model_instance_list::iterator model_iter = iter->second.begin(); model_iter != iter->second.end(); ++model_iter)
+ { //for each instance with said transform applied
+ LLModelInstance instance = *model_iter;
+
+ LLModel* base_model = instance.mModel;
+
+ if (base_model)
+ {
+ base_model->mRequestedLabel = requested_name;
+ }
+
+ S32 idx = 0;
+ for (idx = 0; idx < mBaseModel.size(); ++idx)
+ { //find reference instance for this model
+ if (mBaseModel[idx] == base_model)
+ {
+ break;
+ }
+ }
+
+ for (U32 i = 0; i < LLModel::NUM_LODS; i++)
+ { //fill LOD slots based on reference model index
+ if (!mModel[i].empty())
+ {
+ instance.mLOD[i] = mModel[i][idx];
+ }
+ else
+ {
+ instance.mLOD[i] = NULL;
+ }
+ }
+
+ instance.mTransform = mat;
+ mUploadData.push_back(instance);
+ }
+ }
+
+ F32 max_import_scale = DEFAULT_MAX_PRIM_SCALE/max_scale;
+
+ scale_spinner->setMaxValue(max_import_scale);
+
+ if (max_import_scale < scale)
+ {
+ scale_spinner->setValue(max_import_scale);
+ }
+
+}
+
+
+void LLModelPreview::clearModel(S32 lod)
+{
+ if (lod < 0 || lod > LLModel::LOD_PHYSICS)
+ {
+ return;
+ }
+
+ mVertexBuffer[lod].clear();
+ mModel[lod].clear();
+ mScene[lod].clear();
+}
+
+void LLModelPreview::loadModel(std::string filename, S32 lod)
+{
+ assert_main_thread();
+
+ LLMutexLock lock(this);
+
+ // This triggers if you bring up the file picker and then hit CANCEL.
+ // Just use the previous model (if any) and ignore that you brought up
+ // the file picker.
+
+ if (filename.empty())
+ {
+ if (mBaseModel.empty())
+ {
+ // this is the initial file picking. Close the whole floater
+ // if we don't have a base model to show for high LOD.
+ mFMP->closeFloater(false);
+ mLoading = false;
+ }
+ return;
+ }
+
+ if (mModelLoader)
+ {
+ delete mModelLoader;
+ mModelLoader = NULL;
+ }
+
+ mLODFile[lod] = filename;
+
+ if (lod == LLModel::LOD_HIGH)
+ {
+ clearGLODGroup();
+ }
+
+ mModelLoader = new LLModelLoader(filename, lod, this);
+
+ mModelLoader->start();
+
+ mFMP->childSetTextArg("status", "[STATUS]", mFMP->getString("status_reading_file"));
+
+ setPreviewLOD(lod);
+
+ if ( mModelLoader->getLoadState() == LLModelLoader::ERROR_PARSING )
+ {
+ mFMP->childDisable("ok_btn");
+ }
+
+ if (lod == mPreviewLOD)
+ {
+ mFMP->childSetText("lod_file", mLODFile[mPreviewLOD]);
+ }
+ else if (lod == LLModel::LOD_PHYSICS)
+ {
+ mFMP->childSetText("physics_file", mLODFile[lod]);
+ }
+
+ mFMP->openFloater();
+}
+
+void LLModelPreview::setPhysicsFromLOD(S32 lod)
+{
+ assert_main_thread();
+
+ if (lod >= 0 && lod <= 3)
+ {
+ mModel[LLModel::LOD_PHYSICS] = mModel[lod];
+ mScene[LLModel::LOD_PHYSICS] = mScene[lod];
+ mLODFile[LLModel::LOD_PHYSICS].clear();
+ mFMP->childSetText("physics_file", mLODFile[LLModel::LOD_PHYSICS]);
+ mVertexBuffer[LLModel::LOD_PHYSICS].clear();
+ rebuildUploadData();
+ refresh();
+ updateStatusMessages();
+ }
+}
+
+void LLModelPreview::clearIncompatible(S32 lod)
+{
+ for (U32 i = 0; i <= LLModel::LOD_HIGH; i++)
+ { //clear out any entries that aren't compatible with this model
+ if (i != lod)
+ {
+ if (mModel[i].size() != mModel[lod].size())
+ {
+ mModel[i].clear();
+ mScene[i].clear();
+ mVertexBuffer[i].clear();
+
+ if (i == LLModel::LOD_HIGH)
+ {
+ mBaseModel = mModel[lod];
+ clearGLODGroup();
+ mBaseScene = mScene[lod];
+ mVertexBuffer[5].clear();
+ }
+ }
+ }
+ }
+}
+
+void LLModelPreview::clearGLODGroup()
+{
+ if (mGroup)
+ {
+ for (std::map<LLPointer<LLModel>, U32>::iterator iter = mObject.begin(); iter != mObject.end(); ++iter)
+ {
+ glodDeleteObject(iter->second);
+ stop_gloderror();
+ }
+ mObject.clear();
+
+ glodDeleteGroup(mGroup);
+ stop_gloderror();
+ mGroup = 0;
+ }
+}
+
+void LLModelPreview::loadModelCallback(S32 lod)
+{
+ assert_main_thread();
+
+ LLMutexLock lock(this);
+ if (!mModelLoader)
+ {
+ return;
+ }
+
+ mModelLoader->loadTextures() ;
+ mModel[lod] = mModelLoader->mModelList;
+ mScene[lod] = mModelLoader->mScene;
+ mVertexBuffer[lod].clear();
+
+ if (lod == LLModel::LOD_PHYSICS)
+ {
+ mPhysicsMesh.clear();
+ }
+
+ setPreviewLOD(lod);
+
+
+ if (lod == LLModel::LOD_HIGH)
+ { //save a copy of the highest LOD for automatic LOD manipulation
+ if (mBaseModel.empty())
+ { //first time we've loaded a model, auto-gen LoD
+ mGenLOD = true;
+ }
+
+ mBaseModel = mModel[lod];
+ clearGLODGroup();
+
+ mBaseScene = mScene[lod];
+ mVertexBuffer[5].clear();
+ }
+
+ clearIncompatible(lod);
+
+ mDirty = true;
+
+ if (lod == LLModel::LOD_HIGH)
+ {
+ resetPreviewTarget();
+ }
+
+ mLoading = false;
+ refresh();
+
+ mModelLoadedSignal();
+}
+
+void LLModelPreview::resetPreviewTarget()
+{
+ mPreviewTarget = (mModelLoader->mExtents[0] + mModelLoader->mExtents[1]) * 0.5f;
+ mPreviewScale = (mModelLoader->mExtents[1] - mModelLoader->mExtents[0]) * 0.5f;
+ setPreviewTarget(mPreviewScale.magVec()*2.f);
+}
+
+void LLModelPreview::generateNormals()
+{
+ assert_main_thread();
+
+ S32 which_lod = mPreviewLOD;
+
+
+ if (which_lod > 4 || which_lod < 0 ||
+ mModel[which_lod].empty())
+ {
+ return;
+ }
+
+ F32 angle_cutoff = mFMP->childGetValue("crease_angle").asReal();
+
+ angle_cutoff *= DEG_TO_RAD;
+
+ if (which_lod == 3 && !mBaseModel.empty())
+ {
+ for (LLModelLoader::model_list::iterator iter = mBaseModel.begin(); iter != mBaseModel.end(); ++iter)
+ {
+ (*iter)->generateNormals(angle_cutoff);
+ }
+
+ mVertexBuffer[5].clear();
+ }
+
+ for (LLModelLoader::model_list::iterator iter = mModel[which_lod].begin(); iter != mModel[which_lod].end(); ++iter)
+ {
+ (*iter)->generateNormals(angle_cutoff);
+ }
+
+ mVertexBuffer[which_lod].clear();
+ refresh();
+
+}
+
+void LLModelPreview::clearMaterials()
+{
+ for (LLModelLoader::scene::iterator iter = mScene[mPreviewLOD].begin(); iter != mScene[mPreviewLOD].end(); ++iter)
+ { //for each transform in current scene
+ for (LLModelLoader::model_instance_list::iterator model_iter = iter->second.begin(); model_iter != iter->second.end(); ++model_iter)
+ { //for each instance with that transform
+ LLModelInstance& source_instance = *model_iter;
+ LLModel* source = source_instance.mModel;
+
+ for (S32 i = 0; i < source->getNumVolumeFaces(); ++i)
+ { //for each face in instance
+ LLImportMaterial& source_material = source_instance.mMaterial[i];
+
+ //clear material info
+ source_material.mDiffuseColor = LLColor4(1,1,1,1);
+ source_material.mDiffuseMap = NULL;
+ source_material.mDiffuseMapFilename.clear();
+ source_material.mDiffuseMapLabel.clear();
+ source_material.mFullbright = false;
+ }
+ }
+ }
+
+ mVertexBuffer[mPreviewLOD].clear();
+
+ if (mPreviewLOD == LLModel::LOD_HIGH)
+ {
+ mBaseScene = mScene[mPreviewLOD];
+ mBaseModel = mModel[mPreviewLOD];
+ clearGLODGroup();
+ mVertexBuffer[5].clear();
+ }
+
+ mResourceCost = calcResourceCost();
+ refresh();
+}
+
+void LLModelPreview::genLODs(S32 which_lod, U32 decimation, bool enforce_tri_limit)
+{
+ if (mBaseModel.empty())
+ {
+ return;
+ }
+
+ if (which_lod == LLModel::LOD_PHYSICS)
+ { //clear physics mesh map
+ mPhysicsMesh.clear();
+ }
+
+ LLVertexBuffer::unbind();
+
+ stop_gloderror();
+ static U32 cur_name = 1;
+
+ S32 limit = -1;
+
+ U32 triangle_count = 0;
+
+ for (LLModelLoader::model_list::iterator iter = mBaseModel.begin(); iter != mBaseModel.end(); ++iter)
+ {
+ LLModel* mdl = *iter;
+ for (S32 i = 0; i < mdl->getNumVolumeFaces(); ++i)
+ {
+ triangle_count += mdl->getVolumeFace(i).mNumIndices/3;
+ }
+ }
+
+ U32 base_triangle_count = triangle_count;
+
+ U32 type_mask = LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_TEXCOORD0;
+
+ U32 lod_mode = 0;
+
+ LLCtrlSelectionInterface* iface = mFMP->childGetSelectionInterface("lod_mode");
+ if (iface)
+ {
+ lod_mode = iface->getFirstSelectedIndex();
+ }
+
+ F32 lod_error_threshold = mFMP->childGetValue("lod_error_threshold").asReal();
+
+ if (lod_mode == 0)
+ {
+ lod_mode = GLOD_TRIANGLE_BUDGET;
+ if (which_lod != -1)
+ {
+ limit = mFMP->childGetValue("lod_triangle_limit").asInteger();
+ }
+ }
+ else
+ {
+ lod_mode = GLOD_ERROR_THRESHOLD;
+ }
+
+ U32 build_operator = 0;
+
+ iface = mFMP->childGetSelectionInterface("build_operator");
+ if (iface)
+ {
+ build_operator = iface->getFirstSelectedIndex();
+ }
+
+ if (build_operator == 0)
+ {
+ build_operator = GLOD_OPERATOR_EDGE_COLLAPSE;
+ }
+ else
+ {
+ build_operator = GLOD_OPERATOR_HALF_EDGE_COLLAPSE;
+ }
+
+ U32 queue_mode=0;
+ iface = mFMP->childGetSelectionInterface("queue_mode");
+ if (iface)
+ {
+ queue_mode = iface->getFirstSelectedIndex();
+ }
+
+ if (queue_mode == 0)
+ {
+ queue_mode = GLOD_QUEUE_GREEDY;
+ }
+ else if (queue_mode == 1)
+ {
+ queue_mode = GLOD_QUEUE_LAZY;
+ }
+ else
+ {
+ queue_mode = GLOD_QUEUE_INDEPENDENT;
+ }
+
+ U32 border_mode = 0;
+
+ iface = mFMP->childGetSelectionInterface("border_mode");
+ if (iface)
+ {
+ border_mode = iface->getFirstSelectedIndex();
+ }
+
+ if (border_mode == 0)
+ {
+ border_mode = GLOD_BORDER_UNLOCK;
+ }
+ else
+ {
+ border_mode = GLOD_BORDER_LOCK;
+ }
+
+ bool object_dirty = false;
+ if (border_mode != mBuildBorderMode)
+ {
+ mBuildBorderMode = border_mode;
+ object_dirty = true;
+ }
+
+ if (queue_mode != mBuildQueueMode)
+ {
+ mBuildQueueMode = queue_mode;
+ object_dirty = true;
+ }
+
+ if (build_operator != mBuildOperator)
+ {
+ mBuildOperator = build_operator;
+ object_dirty = true;
+ }
+
+ F32 share_tolerance = mFMP->childGetValue("share_tolerance").asReal();
+ if (share_tolerance != mBuildShareTolerance)
+ {
+ mBuildShareTolerance = share_tolerance;
+ object_dirty = true;
+ }
+
+ if (mGroup == 0)
+ {
+ object_dirty = true;
+ mGroup = cur_name++;
+ glodNewGroup(mGroup);
+ }
+
+ if (object_dirty)
+ {
+ for (LLModelLoader::model_list::iterator iter = mBaseModel.begin(); iter != mBaseModel.end(); ++iter)
+ { //build GLOD objects for each model in base model list
+ LLModel* mdl = *iter;
+
+ if (mObject[mdl] != 0)
+ {
+ glodDeleteObject(mObject[mdl]);
+ }
+
+ mObject[mdl] = cur_name++;
+
+ glodNewObject(mObject[mdl], mGroup, GLOD_DISCRETE);
+ stop_gloderror();
+
+ if (iter == mBaseModel.begin() && !mdl->mSkinWeights.empty())
+ { //regenerate vertex buffer for skinned models to prevent animation feedback during LOD generation
+ mVertexBuffer[5].clear();
+ }
+
+ if (mVertexBuffer[5].empty())
+ {
+ genBuffers(5, false);
+ }
+
+ U32 tri_count = 0;
+ for (U32 i = 0; i < mVertexBuffer[5][mdl].size(); ++i)
+ {
+ mVertexBuffer[5][mdl][i]->setBuffer(type_mask);
+ U32 num_indices = mVertexBuffer[5][mdl][i]->getNumIndices();
+ if (num_indices > 2)
+ {
+ glodInsertElements(mObject[mdl], i, GL_TRIANGLES, num_indices, GL_UNSIGNED_SHORT, mVertexBuffer[5][mdl][i]->getIndicesPointer(), 0, 0.f);
+ }
+ tri_count += num_indices/3;
+ stop_gloderror();
+ }
+
+ glodObjectParameteri(mObject[mdl], GLOD_BUILD_OPERATOR, build_operator);
+ stop_gloderror();
+
+ glodObjectParameteri(mObject[mdl], GLOD_BUILD_QUEUE_MODE, queue_mode);
+ stop_gloderror();
+
+ glodObjectParameteri(mObject[mdl], GLOD_BUILD_BORDER_MODE, border_mode);
+ stop_gloderror();
+
+ glodObjectParameterf(mObject[mdl], GLOD_BUILD_SHARE_TOLERANCE, share_tolerance);
+ stop_gloderror();
+
+ glodBuildObject(mObject[mdl]);
+ stop_gloderror();
+ }
+ }
+
+
+ S32 start = LLModel::LOD_HIGH;
+ S32 end = 0;
+
+ if (which_lod != -1)
+ {
+ start = end = which_lod;
+ }
+
+ mMaxTriangleLimit = base_triangle_count;
+
+ for (S32 lod = start; lod >= end; --lod)
+ {
+ if (which_lod == -1)
+ {
+ if (lod < start)
+ {
+ triangle_count /= decimation;
+ }
+ }
+ else
+ {
+ if (enforce_tri_limit)
+ {
+ triangle_count = limit;
+ }
+ else
+ {
+ for (S32 j=LLModel::LOD_HIGH; j>which_lod; --j)
+ {
+ triangle_count /= decimation;
+ }
+ }
+ }
+
+ mModel[lod].clear();
+ mModel[lod].resize(mBaseModel.size());
+ mVertexBuffer[lod].clear();
+
+ U32 actual_tris = 0;
+ U32 actual_verts = 0;
+ U32 submeshes = 0;
+
+ mRequestedTriangleCount[lod] = triangle_count;
+
+ glodGroupParameteri(mGroup, GLOD_ADAPT_MODE, lod_mode);
+ stop_gloderror();
+
+ glodGroupParameteri(mGroup, GLOD_ERROR_MODE, GLOD_OBJECT_SPACE_ERROR);
+ stop_gloderror();
+
+ glodGroupParameterf(mGroup, GLOD_OBJECT_SPACE_ERROR_THRESHOLD, lod_error_threshold);
+ stop_gloderror();
+
+ glodGroupParameteri(mGroup, GLOD_MAX_TRIANGLES, 0);
+ stop_gloderror();
+
+ glodAdaptGroup(mGroup);
+ stop_gloderror();
+
+ if (lod_mode == GLOD_TRIANGLE_BUDGET)
+ { //SH-632 Always adapt to 0 before adapting to actual desired amount, and always
+ //add 1 to desired amount to avoid decimating below desired amount
+ glodGroupParameteri(mGroup, GLOD_MAX_TRIANGLES, triangle_count+1);
+ stop_gloderror();
+
+ glodAdaptGroup(mGroup);
+ stop_gloderror();
+ }
+
+ for (U32 mdl_idx = 0; mdl_idx < mBaseModel.size(); ++mdl_idx)
+ {
+ LLModel* base = mBaseModel[mdl_idx];
+
+ GLint patch_count = 0;
+ glodGetObjectParameteriv(mObject[base], GLOD_NUM_PATCHES, &patch_count);
+ stop_gloderror();
+
+ LLVolumeParams volume_params;
+ volume_params.setType(LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE);
+ mModel[lod][mdl_idx] = new LLModel(volume_params, 0.f);
+
+ GLint* sizes = new GLint[patch_count*2];
+ glodGetObjectParameteriv(mObject[base], GLOD_PATCH_SIZES, sizes);
+ stop_gloderror();
+
+ GLint* names = new GLint[patch_count];
+ glodGetObjectParameteriv(mObject[base], GLOD_PATCH_NAMES, names);
+ stop_gloderror();
+
+ mModel[lod][mdl_idx]->setNumVolumeFaces(patch_count);
+
+ LLModel* target_model = mModel[lod][mdl_idx];
+
+ for (GLint i = 0; i < patch_count; ++i)
+ {
+ LLPointer<LLVertexBuffer> buff = new LLVertexBuffer(type_mask, 0);
+
+ if (sizes[i*2+1] > 0 && sizes[i*2] > 0)
+ {
+ buff->allocateBuffer(sizes[i*2+1], sizes[i*2], true);
+ buff->setBuffer(type_mask);
+ glodFillElements(mObject[base], names[i], GL_UNSIGNED_SHORT, buff->getIndicesPointer());
+ stop_gloderror();
+ }
+ else
+ { //this face was eliminated, create a dummy triangle (one vertex, 3 indices, all 0)
+ buff->allocateBuffer(1, 3, true);
+ memset(buff->getMappedData(), 0, buff->getSize());
+ memset(buff->getIndicesPointer(), 0, buff->getIndicesSize());
+ }
+
+ buff->validateRange(0, buff->getNumVerts()-1, buff->getNumIndices(), 0);
+
+ LLStrider<LLVector3> pos;
+ LLStrider<LLVector3> norm;
+ LLStrider<LLVector2> tc;
+ LLStrider<U16> index;
+
+ buff->getVertexStrider(pos);
+ buff->getNormalStrider(norm);
+ buff->getTexCoord0Strider(tc);
+ buff->getIndexStrider(index);
+
+ target_model->setVolumeFaceData(names[i], pos, norm, tc, index, buff->getNumVerts(), buff->getNumIndices());
+ actual_tris += buff->getNumIndices()/3;
+ actual_verts += buff->getNumVerts();
+ ++submeshes;
+
+ if (!validate_face(target_model->getVolumeFace(names[i])))
+ {
+ llerrs << "Invalid face generated during LOD generation." << llendl;
+ }
+ }
+
+ //blind copy skin weights and just take closest skin weight to point on
+ //decimated mesh for now (auto-generating LODs with skin weights is still a bit
+ //of an open problem).
+ target_model->mPosition = base->mPosition;
+ target_model->mSkinWeights = base->mSkinWeights;
+ target_model->mJointMap = base->mJointMap;
+ target_model->mJointList = base->mJointList;
+ target_model->mInvBindMatrix = base->mInvBindMatrix;
+ target_model->mBindShapeMatrix = base->mBindShapeMatrix;
+ target_model->mAlternateBindMatrix = base->mAlternateBindMatrix;
+ //copy material list
+ target_model->mMaterialList = base->mMaterialList;
+
+ if (!validate_model(target_model))
+ {
+ llerrs << "Invalid model generated when creating LODs" << llendl;
+ }
+
+ delete [] sizes;
+ delete [] names;
+ }
+
+ //rebuild scene based on mBaseScene
+ mScene[lod].clear();
+ mScene[lod] = mBaseScene;
+
+ for (U32 i = 0; i < mBaseModel.size(); ++i)
+ {
+ LLModel* mdl = mBaseModel[i];
+ LLModel* target = mModel[lod][i];
+ if (target)
+ {
+ for (LLModelLoader::scene::iterator iter = mScene[lod].begin(); iter != mScene[lod].end(); ++iter)
+ {
+ for (U32 j = 0; j < iter->second.size(); ++j)
+ {
+ if (iter->second[j].mModel == mdl)
+ {
+ iter->second[j].mModel = target;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ mResourceCost = calcResourceCost();
+
+ /*if (which_lod == -1 && mScene[LLModel::LOD_PHYSICS].empty())
+ { //build physics scene
+ mScene[LLModel::LOD_PHYSICS] = mScene[LLModel::LOD_LOW];
+ mModel[LLModel::LOD_PHYSICS] = mModel[LLModel::LOD_LOW];
+
+ for (U32 i = 1; i < mModel[LLModel::LOD_PHYSICS].size(); ++i)
+ {
+ mPhysicsQ.push(mModel[LLModel::LOD_PHYSICS][i]);
+ }
+ }*/
+}
+
+void LLModelPreview::updateStatusMessages()
+{
+ assert_main_thread();
+
+ //triangle/vertex/submesh count for each mesh asset for each lod
+ std::vector<S32> tris[LLModel::NUM_LODS];
+ std::vector<S32> verts[LLModel::NUM_LODS];
+ std::vector<S32> submeshes[LLModel::NUM_LODS];
+
+ //total triangle/vertex/submesh count for each lod
+ S32 total_tris[LLModel::NUM_LODS];
+ S32 total_verts[LLModel::NUM_LODS];
+ S32 total_submeshes[LLModel::NUM_LODS];
+
+ for (S32 lod = 0; lod < LLModel::NUM_LODS; ++lod)
+ {
+ //initialize total for this lod to 0
+ total_tris[lod] = total_verts[lod] = total_submeshes[lod] = 0;
+
+ for (U32 i = 0; i < mModel[lod].size(); ++i)
+ { //for each model in the lod
+ S32 cur_tris = 0;
+ S32 cur_verts = 0;
+ S32 cur_submeshes = mModel[lod][i]->getNumVolumeFaces();
+
+ for (S32 j = 0; j < cur_submeshes; ++j)
+ { //for each submesh (face), add triangles and vertices to current total
+ const LLVolumeFace& face = mModel[lod][i]->getVolumeFace(j);
+ cur_tris += face.mNumIndices/3;
+ cur_verts += face.mNumVertices;
+ }
+
+ //add this model to the lod total
+ total_tris[lod] += cur_tris;
+ total_verts[lod] += cur_verts;
+ total_submeshes[lod] += cur_submeshes;
+
+ //store this model's counts to asset data
+ tris[lod].push_back(cur_tris);
+ verts[lod].push_back(cur_verts);
+ submeshes[lod].push_back(cur_submeshes);
+ }
+ }
+
+ if (mMaxTriangleLimit == 0)
+ {
+ mMaxTriangleLimit = total_tris[LLModel::LOD_HIGH];
+ }
+
+
+ mFMP->childSetTextArg("submeshes_info", "[SUBMESHES]", llformat("%d", total_submeshes[LLModel::LOD_HIGH]));
+
+ std::string mesh_status_na = mFMP->getString("mesh_status_na");
+
+ S32 upload_status[LLModel::LOD_HIGH+1];
+
+ bool upload_ok = true;
+
+ for (S32 lod = 0; lod <= LLModel::LOD_HIGH; ++lod)
+ {
+ upload_status[lod] = 0;
+
+ std::string message = "mesh_status_good";
+
+ if (total_tris[lod] > 0)
+ {
+ mFMP->childSetText(lod_triangles_name[lod], llformat("%d", total_tris[lod]));
+ mFMP->childSetText(lod_vertices_name[lod], llformat("%d", total_verts[lod]));
+ }
+ else
+ {
+ if (lod == LLModel::LOD_HIGH)
+ {
+ upload_status[lod] = 2;
+ message = "mesh_status_missing_lod";
+ }
+ else
+ {
+ for (S32 i = lod-1; i >= 0; --i)
+ {
+ if (total_tris[i] > 0)
+ {
+ upload_status[lod] = 2;
+ message = "mesh_status_missing_lod";
+ }
+ }
+ }
+
+ mFMP->childSetText(lod_triangles_name[lod], mesh_status_na);
+ mFMP->childSetText(lod_vertices_name[lod], mesh_status_na);
+ }
+
+ const U32 lod_high = LLModel::LOD_HIGH;
+
+ if (lod != lod_high)
+ {
+ if (total_submeshes[lod] && total_submeshes[lod] != total_submeshes[lod_high])
+ { //number of submeshes is different
+ message = "mesh_status_submesh_mismatch";
+ upload_status[lod] = 2;
+ }
+ else if (!tris[lod].empty() && tris[lod].size() != tris[lod_high].size())
+ { //number of meshes is different
+ message = "mesh_status_mesh_mismatch";
+ upload_status[lod] = 2;
+ }
+ else if (!verts[lod].empty())
+ {
+ for (U32 i = 0; i < verts[lod].size(); ++i)
+ {
+ S32 max_verts = i < verts[lod+1].size() ? verts[lod+1][i] : 0;
+
+ if (max_verts > 0)
+ {
+ if (verts[lod][i] > max_verts)
+ { //too many vertices in this lod
+ message = "mesh_status_too_many_vertices";
+ upload_status[lod] = 2;
+ }
+ }
+ }
+ }
+ }
+
+ LLIconCtrl* icon = mFMP->getChild<LLIconCtrl>(lod_icon_name[lod]);
+ LLUIImagePtr img = LLUI::getUIImage(lod_status_image[upload_status[lod]]);
+ icon->setVisible(true);
+ icon->setImage(img);
+
+ if (upload_status[lod] >= 2)
+ {
+ upload_ok = false;
+ }
+
+ if (lod == mPreviewLOD)
+ {
+ mFMP->childSetText("lod_status_message_text", mFMP->getString(message));
+ icon = mFMP->getChild<LLIconCtrl>("lod_status_message_icon");
+ icon->setImage(img);
+ }
+ }
+
+ bool errorStateFromLoader = mModelLoader->getLoadState() == LLModelLoader::ERROR_PARSING ? true : false;
+
+ if ( upload_ok && !errorStateFromLoader )
+ {
+ mFMP->childEnable("ok_btn");
+ }
+ else
+ {
+ mFMP->childDisable("ok_btn");
+ }
+
+ //add up physics triangles etc
+ S32 start = 0;
+ S32 end = mModel[LLModel::LOD_PHYSICS].size();
+
+ S32 phys_tris = 0;
+ S32 phys_hulls = 0;
+ S32 phys_points = 0;
+
+ for (S32 i = start; i < end; ++i)
+ { //add up hulls and points and triangles for selected mesh(es)
+ LLModel* model = mModel[LLModel::LOD_PHYSICS][i];
+ S32 cur_submeshes = model->getNumVolumeFaces();
+
+ LLModel::convex_hull_decomposition& decomp = model->mConvexHullDecomp;
+
+ if (!decomp.empty())
+ {
+ phys_hulls += decomp.size();
+ for (U32 i = 0; i < decomp.size(); ++i)
+ {
+ phys_points += decomp[i].size();
+ }
+ }
+ else
+ { //choose physics shape OR decomposition, can't use both
+ for (S32 j = 0; j < cur_submeshes; ++j)
+ { //for each submesh (face), add triangles and vertices to current total
+ const LLVolumeFace& face = model->getVolumeFace(j);
+ phys_tris += face.mNumIndices/3;
+ }
+ }
+ }
+
+ if (phys_tris > 0)
+ {
+ mFMP->childSetTextArg("physics_triangles", "[TRIANGLES]", llformat("%d", phys_tris));
+ }
+ else
+ {
+ mFMP->childSetTextArg("physics_triangles", "[TRIANGLES]", mesh_status_na);
+ }
+
+ if (phys_hulls > 0)
+ {
+ mFMP->childSetTextArg("physics_hulls", "[HULLS]", llformat("%d", phys_hulls));
+ mFMP->childSetTextArg("physics_points", "[POINTS]", llformat("%d", phys_points));
+ }
+ else
+ {
+ mFMP->childSetTextArg("physics_hulls", "[HULLS]", mesh_status_na);
+ mFMP->childSetTextArg("physics_points", "[POINTS]", mesh_status_na);
+ }
+
+ LLFloaterModelPreview* fmp = LLFloaterModelPreview::sInstance;
+ if (fmp)
+ {
+ if (phys_tris > 0 || phys_hulls > 0)
+ {
+ if (!fmp->isViewOptionEnabled("show_physics"))
+ {
+ fmp->enableViewOption("show_physics");
+ mViewOption["show_physics"] = true;
+ }
+ }
+ else
+ {
+ fmp->disableViewOption("show_physics");
+ mViewOption["show_physics"] = false;
+
+ }
+
+ //bool use_hull = fmp->childGetValue("physics_use_hull").asBoolean();
+
+ //fmp->childSetEnabled("physics_optimize", !use_hull);
+
+ bool enable = phys_tris > 0 || phys_hulls > 0;
+ //enable = enable && !use_hull && fmp->childGetValue("physics_optimize").asBoolean();
+
+ //enable/disable "analysis" UI
+ LLPanel* panel = fmp->getChild<LLPanel>("physics analysis");
+ LLView* child = panel->getFirstChild();
+ while (child)
+ {
+ child->setEnabled(enable);
+ child = panel->findNextSibling(child);
+ }
+
+ enable = phys_hulls > 0;
+ //enable/disable "simplification" UI
+ panel = fmp->getChild<LLPanel>("physics simplification");
+ child = panel->getFirstChild();
+ while (child)
+ {
+ child->setEnabled(enable);
+ child = panel->findNextSibling(child);
+ }
+ }
+
+ const char* lod_controls[] =
+ {
+ "lod_mode",
+ "lod_triangle_limit",
+ "lod_error_tolerance",
+ "build_operator_text",
+ "queue_mode_text",
+ "border_mode_text",
+ "share_tolerance_text",
+ "build_operator",
+ "queue_mode",
+ "border_mode",
+ "share_tolerance"
+ };
+ const U32 num_lod_controls = sizeof(lod_controls)/sizeof(char*);
+
+ const char* file_controls[] =
+ {
+ "lod_browse",
+ "lod_file"
+ };
+ const U32 num_file_controls = sizeof(file_controls)/sizeof(char*);
+
+ if (fmp)
+ {
+ //enable/disable controls based on radio groups
+ if (mFMP->childGetValue("lod_from_file").asBoolean())
+ {
+ fmp->mLODMode[mPreviewLOD] = 0;
+ for (U32 i = 0; i < num_file_controls; ++i)
+ {
+ mFMP->childEnable(file_controls[i]);
+ }
+
+ for (U32 i = 0; i < num_lod_controls; ++i)
+ {
+ mFMP->childDisable(lod_controls[i]);
+ }
+ }
+ else if (mFMP->childGetValue("lod_none").asBoolean())
+ {
+ fmp->mLODMode[mPreviewLOD] = 2;
+ for (U32 i = 0; i < num_file_controls; ++i)
+ {
+ mFMP->childDisable(file_controls[i]);
+ }
+
+ for (U32 i = 0; i < num_lod_controls; ++i)
+ {
+ mFMP->childDisable(lod_controls[i]);
+ }
+
+ if (!mModel[mPreviewLOD].empty())
+ {
+ mModel[mPreviewLOD].clear();
+ mScene[mPreviewLOD].clear();
+ mVertexBuffer[mPreviewLOD].clear();
+
+ //this can cause phasing issues with the UI, so reenter this function and return
+ updateStatusMessages();
+ return;
+ }
+ }
+ else
+ { // auto generate, also the default case for wizard which has no radio selection
+ fmp->mLODMode[mPreviewLOD] = 1;
+
+ for (U32 i = 0; i < num_file_controls; ++i)
+ {
+ mFMP->childDisable(file_controls[i]);
+ }
+
+ for (U32 i = 0; i < num_lod_controls; ++i)
+ {
+ mFMP->childEnable(lod_controls[i]);
+ }
+
+ //if (threshold)
+ {
+ U32 lod_mode = 0;
+ LLCtrlSelectionInterface* iface = mFMP->childGetSelectionInterface("lod_mode");
+ if (iface)
+ {
+ lod_mode = iface->getFirstSelectedIndex();
+ }
+
+ LLSpinCtrl* threshold = mFMP->getChild<LLSpinCtrl>("lod_error_threshold");
+ LLSpinCtrl* limit = mFMP->getChild<LLSpinCtrl>("lod_triangle_limit");
+
+ limit->setMaxValue(mMaxTriangleLimit);
+ limit->setValue(mRequestedTriangleCount[mPreviewLOD]);
+
+ if (lod_mode == 0)
+ {
+ limit->setVisible(true);
+ threshold->setVisible(false);
+
+ limit->setMaxValue(mMaxTriangleLimit);
+ limit->setIncrement(mMaxTriangleLimit/32);
+ }
+ else
+ {
+ limit->setVisible(false);
+ threshold->setVisible(true);
+ }
+ }
+ }
+ }
+
+ if (mFMP->childGetValue("physics_load_from_file").asBoolean())
+ {
+ mFMP->childDisable("physics_lod_combo");
+ mFMP->childEnable("physics_file");
+ mFMP->childEnable("physics_browse");
+ }
+ else
+ {
+ mFMP->childEnable("physics_lod_combo");
+ mFMP->childDisable("physics_file");
+ mFMP->childDisable("physics_browse");
+ }
+}
+
+void LLModelPreview::setPreviewTarget(F32 distance)
+{
+ mCameraDistance = distance;
+ mCameraZoom = 1.f;
+ mCameraPitch = 0.f;
+ mCameraYaw = 0.f;
+ mCameraOffset.clearVec();
+}
+
+void LLModelPreview::clearBuffers()
+{
+ for (U32 i = 0; i < 6; i++)
+ {
+ mVertexBuffer[i].clear();
+ }
+}
+
+void LLModelPreview::genBuffers(S32 lod, bool include_skin_weights)
+{
+ U32 tri_count = 0;
+ U32 vertex_count = 0;
+ U32 mesh_count = 0;
+
+
+ LLModelLoader::model_list* model = NULL;
+
+ if (lod < 0 || lod > 4)
+ {
+ model = &mBaseModel;
+ lod = 5;
+ }
+ else
+ {
+ model = &(mModel[lod]);
+ }
+
+ if (!mVertexBuffer[lod].empty())
+ {
+ mVertexBuffer[lod].clear();
+ }
+
+ mVertexBuffer[lod].clear();
+
+ LLModelLoader::model_list::iterator base_iter = mBaseModel.begin();
+
+ for (LLModelLoader::model_list::iterator iter = model->begin(); iter != model->end(); ++iter)
+ {
+ LLModel* mdl = *iter;
+ if (!mdl)
+ {
+ continue;
+ }
+
+ LLModel* base_mdl = *base_iter;
+ base_iter++;
+
+ for (S32 i = 0; i < mdl->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace &vf = mdl->getVolumeFace(i);
+ U32 num_vertices = vf.mNumVertices;
+ U32 num_indices = vf.mNumIndices;
+
+ if (!num_vertices || ! num_indices)
+ {
+ continue;
+ }
+
+ LLVertexBuffer* vb = NULL;
+
+ bool skinned = include_skin_weights && !mdl->mSkinWeights.empty();
+
+ U32 mask = LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_TEXCOORD0;
+
+ if (skinned)
+ {
+ mask |= LLVertexBuffer::MAP_WEIGHT4;
+ }
+
+ vb = new LLVertexBuffer(mask, 0);
+
+ vb->allocateBuffer(num_vertices, num_indices, TRUE);
+
+ LLStrider<LLVector3> vertex_strider;
+ LLStrider<LLVector3> normal_strider;
+ LLStrider<LLVector2> tc_strider;
+ LLStrider<U16> index_strider;
+ LLStrider<LLVector4> weights_strider;
+
+ vb->getVertexStrider(vertex_strider);
+ vb->getNormalStrider(normal_strider);
+ vb->getTexCoord0Strider(tc_strider);
+ vb->getIndexStrider(index_strider);
+
+ if (skinned)
+ {
+ vb->getWeight4Strider(weights_strider);
+ }
+
+ LLVector4a::memcpyNonAliased16((F32*) vertex_strider.get(), (F32*) vf.mPositions, num_vertices*4*sizeof(F32));
+ LLVector4a::memcpyNonAliased16((F32*) tc_strider.get(), (F32*) vf.mTexCoords, num_vertices*2*sizeof(F32));
+ LLVector4a::memcpyNonAliased16((F32*) normal_strider.get(), (F32*) vf.mNormals, num_vertices*4*sizeof(F32));
+
+ if (skinned)
+ {
+ for (U32 i = 0; i < num_vertices; i++)
+ {
+ //find closest weight to vf.mVertices[i].mPosition
+ LLVector3 pos(vf.mPositions[i].getF32ptr());
+
+ const LLModel::weight_list& weight_list = base_mdl->getJointInfluences(pos);
+
+ LLVector4 w(0,0,0,0);
+ if (weight_list.size() > 4)
+ {
+ llerrs << "WTF?" << llendl;
+ }
+
+ for (U32 i = 0; i < weight_list.size(); ++i)
+ {
+ F32 wght = llmin(weight_list[i].mWeight, 0.999999f);
+ F32 joint = (F32) weight_list[i].mJointIdx;
+ w.mV[i] = joint + wght;
+ }
+
+ *(weights_strider++) = w;
+ }
+ }
+
+ // build indices
+ for (U32 i = 0; i < num_indices; i++)
+ {
+ *(index_strider++) = vf.mIndices[i];
+ }
+
+ mVertexBuffer[lod][mdl].push_back(vb);
+
+ vertex_count += num_vertices;
+ tri_count += num_indices/3;
+ ++mesh_count;
+
+ }
+ }
+}
+
+void LLModelPreview::update()
+{
+ if (mDirty)
+ {
+ mDirty = false;
+ mResourceCost = calcResourceCost();
+ refresh();
+ updateStatusMessages();
+ }
+
+ if (mGenLOD)
+ {
+ mGenLOD = false;
+ genLODs();
+ refresh();
+ updateStatusMessages();
+ }
+
+}
+
+//-----------------------------------------------------------------------------
+// render()
+//-----------------------------------------------------------------------------
+BOOL LLModelPreview::render()
+{
+ assert_main_thread();
+
+ LLMutexLock lock(this);
+ mNeedsUpdate = FALSE;
+
+ bool edges = mViewOption["show_edges"];
+ bool joint_positions = mViewOption["show_joint_positions"];
+ bool skin_weight = mViewOption["show_skin_weight"];
+ bool textures = mViewOption["show_textures"];
+ bool physics = mViewOption["show_physics"];
+
+ S32 width = getWidth();
+ S32 height = getHeight();
+
+ LLGLSUIDefault def;
+ LLGLDisable no_blend(GL_BLEND);
+ LLGLEnable cull(GL_CULL_FACE);
+ LLGLDepthTest depth(GL_TRUE);
+ LLGLDisable fog(GL_FOG);
+
+ {
+ //clear background to blue
+ glMatrixMode(GL_PROJECTION);
+ gGL.pushMatrix();
+ glLoadIdentity();
+ glOrtho(0.0f, width, 0.0f, height, -1.0f, 1.0f);
+
+ glMatrixMode(GL_MODELVIEW);
+ gGL.pushMatrix();
+ glLoadIdentity();
+
+ gGL.color4f(0.169f, 0.169f, 0.169f, 1.f);
+
+ gl_rect_2d_simple( width, height );
+
+ glMatrixMode(GL_PROJECTION);
+ gGL.popMatrix();
+
+ glMatrixMode(GL_MODELVIEW);
+ gGL.popMatrix();
+ }
+
+ LLFloaterModelPreview* fmp = LLFloaterModelPreview::sInstance;
+
+ bool has_skin_weights = false;
+ bool upload_skin = mFMP->childGetValue("upload_skin").asBoolean();
+ bool upload_joints = mFMP->childGetValue("upload_joints").asBoolean();
+
+ for (LLModelLoader::scene::iterator iter = mScene[mPreviewLOD].begin(); iter != mScene[mPreviewLOD].end(); ++iter)
+ {
+ for (LLModelLoader::model_instance_list::iterator model_iter = iter->second.begin(); model_iter != iter->second.end(); ++model_iter)
+ {
+ LLModelInstance& instance = *model_iter;
+ LLModel* model = instance.mModel;
+ model->mPelvisOffset = mPelvisZOffset;
+ if (!model->mSkinWeights.empty())
+ {
+ has_skin_weights = true;
+ }
+ }
+ }
+
+ if (has_skin_weights)
+ { //model has skin weights, enable view options for skin weights and joint positions
+ if (fmp)
+ {
+ fmp->enableViewOption("show_skin_weight");
+ fmp->setViewOptionEnabled("show_joint_positions", skin_weight);
+ }
+ mFMP->childEnable("upload_skin");
+ }
+ else
+ {
+ mFMP->childDisable("upload_skin");
+ if (fmp)
+ {
+ mViewOption["show_skin_weight"] = false;
+ fmp->disableViewOption("show_skin_weight");
+ fmp->disableViewOption("show_joint_positions");
+ }
+ skin_weight = false;
+ }
+
+ if (upload_skin && !has_skin_weights)
+ { //can't upload skin weights if model has no skin weights
+ mFMP->childSetValue("upload_skin", false);
+ upload_skin = false;
+ }
+
+ if (!upload_skin && upload_joints)
+ { //can't upload joints if not uploading skin weights
+ mFMP->childSetValue("upload_joints", false);
+ upload_joints = false;
+ }
+
+ mFMP->childSetEnabled("upload_joints", upload_skin);
+
+ F32 explode = mFMP->childGetValue("physics_explode").asReal();
+
+ glClear(GL_DEPTH_BUFFER_BIT);
+
+ LLRect preview_rect = mFMP->getChildView("preview_panel")->getRect();
+ F32 aspect = (F32) preview_rect.getWidth()/preview_rect.getHeight();
+
+ LLViewerCamera::getInstance()->setAspect(aspect);
+
+ LLViewerCamera::getInstance()->setView(LLViewerCamera::getInstance()->getDefaultFOV() / mCameraZoom);
+
+ LLVector3 offset = mCameraOffset;
+ LLVector3 target_pos = mPreviewTarget+offset;
+
+ F32 z_near = 0.001f;
+ F32 z_far = mCameraDistance+mPreviewScale.magVec()+mCameraOffset.magVec();
+
+ if (skin_weight)
+ {
+ target_pos = gAgentAvatarp->getPositionAgent();
+ z_near = 0.01f;
+ z_far = 1024.f;
+ mCameraDistance = 16.f;
+
+ //render avatar previews every frame
+ refresh();
+ }
+
+ glLoadIdentity();
+ gPipeline.enableLightsPreview();
+
+ LLQuaternion camera_rot = LLQuaternion(mCameraPitch, LLVector3::y_axis) *
+ LLQuaternion(mCameraYaw, LLVector3::z_axis);
+
+ LLQuaternion av_rot = camera_rot;
+ LLViewerCamera::getInstance()->setOriginAndLookAt(
+ target_pos + ((LLVector3(mCameraDistance, 0.f, 0.f) + offset) * av_rot), // camera
+ LLVector3::z_axis, // up
+ target_pos); // point of interest
+
+
+ LLViewerCamera::getInstance()->setPerspective(FALSE, mOrigin.mX, mOrigin.mY, width, height, FALSE, z_near, z_far);
+
+ stop_glerror();
+
+ gGL.pushMatrix();
+ const F32 BRIGHTNESS = 0.9f;
+ gGL.color3f(BRIGHTNESS, BRIGHTNESS, BRIGHTNESS);
+
+ LLGLEnable normalize(GL_NORMALIZE);
+
+ if (!mBaseModel.empty() && mVertexBuffer[5].empty())
+ {
+ genBuffers(-1, skin_weight);
+ //genBuffers(3);
+ //genLODs();
+ }
+
+ if (!mModel[mPreviewLOD].empty())
+ {
+ bool regen = mVertexBuffer[mPreviewLOD].empty();
+ if (!regen)
+ {
+ const std::vector<LLPointer<LLVertexBuffer> >& vb_vec = mVertexBuffer[mPreviewLOD].begin()->second;
+ if (!vb_vec.empty())
+ {
+ const LLVertexBuffer* buff = vb_vec[0];
+ regen = buff->hasDataType(LLVertexBuffer::TYPE_WEIGHT4) != skin_weight;
+ }
+ }
+
+ if (regen)
+ {
+ genBuffers(mPreviewLOD, skin_weight);
+ }
+
+ if (!skin_weight)
+ {
+ for (LLMeshUploadThread::instance_list::iterator iter = mUploadData.begin(); iter != mUploadData.end(); ++iter)
+ {
+ LLModelInstance& instance = *iter;
+
+ LLModel* model = instance.mLOD[mPreviewLOD];
+
+ if (!model)
+ {
+ continue;
+ }
+
+ gGL.pushMatrix();
+ LLMatrix4 mat = instance.mTransform;
+
+ glMultMatrixf((GLfloat*) mat.mMatrix);
+
+ for (U32 i = 0; i < mVertexBuffer[mPreviewLOD][model].size(); ++i)
+ {
+ LLVertexBuffer* buffer = mVertexBuffer[mPreviewLOD][model][i];
+
+ buffer->setBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_TEXCOORD0);
+
+ if (textures)
+ {
+ glColor4fv(instance.mMaterial[i].mDiffuseColor.mV);
+ if (i < instance.mMaterial.size() && instance.mMaterial[i].mDiffuseMap.notNull())
+ {
+ gGL.getTexUnit(0)->bind(instance.mMaterial[i].mDiffuseMap, true);
+ if (instance.mMaterial[i].mDiffuseMap->getDiscardLevel() > -1)
+ {
+ mTextureSet.insert(instance.mMaterial[i].mDiffuseMap.get());
+ }
+ }
+ }
+ else
+ {
+ glColor4f(1,1,1,1);
+ }
+
+ buffer->drawRange(LLRender::TRIANGLES, 0, buffer->getNumVerts()-1, buffer->getNumIndices(), 0);
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ glColor3f(0.4f, 0.4f, 0.4f);
+
+ if (edges)
+ {
+ glLineWidth(3.f);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ buffer->drawRange(LLRender::TRIANGLES, 0, buffer->getNumVerts()-1, buffer->getNumIndices(), 0);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ glLineWidth(1.f);
+ }
+ }
+ gGL.popMatrix();
+ }
+
+ if (physics)
+ {
+ glClear(GL_DEPTH_BUFFER_BIT);
+ LLGLEnable blend(GL_BLEND);
+ gGL.blendFunc(LLRender::BF_ONE, LLRender::BF_ZERO);
+
+ for (LLMeshUploadThread::instance_list::iterator iter = mUploadData.begin(); iter != mUploadData.end(); ++iter)
+ {
+ LLModelInstance& instance = *iter;
+
+ LLModel* model = instance.mLOD[LLModel::LOD_PHYSICS];
+
+ if (!model)
+ {
+ continue;
+ }
+
+ gGL.pushMatrix();
+ LLMatrix4 mat = instance.mTransform;
+
+ glMultMatrixf((GLfloat*) mat.mMatrix);
+
+
+ bool render_mesh = true;
+
+ LLPhysicsDecomp* decomp = gMeshRepo.mDecompThread;
+ if (decomp)
+ {
+ LLMutexLock(decomp->mMutex);
+
+ std::map<LLPointer<LLModel>, std::vector<LLPointer<LLVertexBuffer> > >::iterator iter =
+ mPhysicsMesh.find(model);
+ if (iter != mPhysicsMesh.end())
+ { //render hull instead of mesh
+ render_mesh = false;
+ for (U32 i = 0; i < iter->second.size(); ++i)
+ {
+ if (explode > 0.f)
+ {
+ gGL.pushMatrix();
+
+ LLVector3 offset = model->mHullCenter[i]-model->mCenterOfHullCenters;
+ offset *= explode;
+
+ gGL.translatef(offset.mV[0], offset.mV[1], offset.mV[2]);
+ }
+
+ static std::vector<LLColor4U> hull_colors;
+
+ if (i+1 >= hull_colors.size())
+ {
+ hull_colors.push_back(LLColor4U(rand()%128+127, rand()%128+127, rand()%128+127, 255));
+ }
+
+ LLVertexBuffer* buff = iter->second[i];
+ if (buff)
+ {
+ buff->setBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL);
+
+ glColor4ubv(hull_colors[i].mV);
+ buff->drawArrays(LLRender::TRIANGLES, 0, buff->getNumVerts());
+ }
+
+ if (explode > 0.f)
+ {
+ gGL.popMatrix();
+ }
+ }
+ }
+ }
+
+ if (render_mesh)
+ {
+ if (mVertexBuffer[LLModel::LOD_PHYSICS].empty())
+ {
+ genBuffers(LLModel::LOD_PHYSICS, false);
+ }
+ for (U32 i = 0; i < mVertexBuffer[LLModel::LOD_PHYSICS][model].size(); ++i)
+ {
+ LLVertexBuffer* buffer = mVertexBuffer[LLModel::LOD_PHYSICS][model][i];
+
+ buffer->setBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_TEXCOORD0);
+
+ buffer->drawRange(LLRender::TRIANGLES, 0, buffer->getNumVerts()-1, buffer->getNumIndices(), 0);
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ glColor4f(0.4f, 0.4f, 0.0f, 0.4f);
+
+ buffer->drawRange(LLRender::TRIANGLES, 0, buffer->getNumVerts()-1, buffer->getNumIndices(), 0);
+
+ glColor3f(1.f, 1.f, 0.f);
+
+ glLineWidth(3.f);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ buffer->drawRange(LLRender::TRIANGLES, 0, buffer->getNumVerts()-1, buffer->getNumIndices(), 0);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ glLineWidth(1.f);
+ }
+ }
+
+ gGL.popMatrix();
+ }
+
+ gGL.setSceneBlendType(LLRender::BT_ALPHA);
+ }
+ }
+ else
+ {
+ LLVOAvatarSelf* avatar = gAgentAvatarp;
+ target_pos = avatar->getPositionAgent();
+
+ LLViewerCamera::getInstance()->setOriginAndLookAt(
+ target_pos + ((LLVector3(mCameraDistance, 0.f, 0.f) + offset) * av_rot), // camera
+ LLVector3::z_axis, // up
+ target_pos); // point of interest
+
+ if (joint_positions)
+ {
+ avatar->renderCollisionVolumes();
+ }
+
+ for (LLModelLoader::scene::iterator iter = mScene[mPreviewLOD].begin(); iter != mScene[mPreviewLOD].end(); ++iter)
+ {
+ for (LLModelLoader::model_instance_list::iterator model_iter = iter->second.begin(); model_iter != iter->second.end(); ++model_iter)
+ {
+ LLModelInstance& instance = *model_iter;
+ LLModel* model = instance.mModel;
+
+ if (!model->mSkinWeights.empty())
+ {
+ for (U32 i = 0; i < mVertexBuffer[mPreviewLOD][model].size(); ++i)
+ {
+ LLVertexBuffer* buffer = mVertexBuffer[mPreviewLOD][model][i];
+
+ const LLVolumeFace& face = model->getVolumeFace(i);
+
+ LLStrider<LLVector3> position;
+ buffer->getVertexStrider(position);
+
+ LLStrider<LLVector4> weight;
+ buffer->getWeight4Strider(weight);
+
+ //quick 'n dirty software vertex skinning
+
+ //build matrix palette
+ LLMatrix4 mat[64];
+ for (U32 j = 0; j < model->mJointList.size(); ++j)
+ {
+ LLJoint* joint = avatar->getJoint(model->mJointList[j]);
+ if (joint)
+ {
+ mat[j] = model->mInvBindMatrix[j];
+ mat[j] *= joint->getWorldMatrix();
+ }
+ }
+
+ for (U32 j = 0; j < buffer->getRequestedVerts(); ++j)
+ {
+ LLMatrix4 final_mat;
+ final_mat.mMatrix[0][0] = final_mat.mMatrix[1][1] = final_mat.mMatrix[2][2] = final_mat.mMatrix[3][3] = 0.f;
+
+ LLVector4 wght;
+ S32 idx[4];
+
+ F32 scale = 0.f;
+ for (U32 k = 0; k < 4; k++)
+ {
+ F32 w = weight[j].mV[k];
+
+ idx[k] = (S32) floorf(w);
+ wght.mV[k] = w - floorf(w);
+ scale += wght.mV[k];
+ }
+
+ wght *= 1.f/scale;
+
+ for (U32 k = 0; k < 4; k++)
+ {
+ F32* src = (F32*) mat[idx[k]].mMatrix;
+ F32* dst = (F32*) final_mat.mMatrix;
+
+ F32 w = wght.mV[k];
+
+ for (U32 l = 0; l < 16; l++)
+ {
+ dst[l] += src[l]*w;
+ }
+ }
+
+ //VECTORIZE THIS
+ LLVector3 v(face.mPositions[j].getF32ptr());
+
+ v = v * model->mBindShapeMatrix;
+ v = v * final_mat;
+
+ position[j] = v;
+ }
+
+ buffer->setBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_TEXCOORD0);
+ glColor4fv(instance.mMaterial[i].mDiffuseColor.mV);
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ buffer->draw(LLRender::TRIANGLES, buffer->getNumIndices(), 0);
+ glColor3f(0.4f, 0.4f, 0.4f);
+
+ if (edges)
+ {
+ glLineWidth(3.f);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ buffer->draw(LLRender::TRIANGLES, buffer->getNumIndices(), 0);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ glLineWidth(1.f);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ gGL.popMatrix();
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// refresh()
+//-----------------------------------------------------------------------------
+void LLModelPreview::refresh()
+{
+ mNeedsUpdate = TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// rotate()
+//-----------------------------------------------------------------------------
+void LLModelPreview::rotate(F32 yaw_radians, F32 pitch_radians)
+{
+ mCameraYaw = mCameraYaw + yaw_radians;
+
+ mCameraPitch = llclamp(mCameraPitch + pitch_radians, F_PI_BY_TWO * -0.8f, F_PI_BY_TWO * 0.8f);
+}
+
+//-----------------------------------------------------------------------------
+// zoom()
+//-----------------------------------------------------------------------------
+void LLModelPreview::zoom(F32 zoom_amt)
+{
+ F32 new_zoom = mCameraZoom+zoom_amt;
+
+ mCameraZoom = llclamp(new_zoom, 1.f, 10.f);
+}
+
+void LLModelPreview::pan(F32 right, F32 up)
+{
+ mCameraOffset.mV[VY] = llclamp(mCameraOffset.mV[VY] + right * mCameraDistance / mCameraZoom, -1.f, 1.f);
+ mCameraOffset.mV[VZ] = llclamp(mCameraOffset.mV[VZ] + up * mCameraDistance / mCameraZoom, -1.f, 1.f);
+}
+
+void LLModelPreview::setPreviewLOD(S32 lod)
+{
+ lod = llclamp(lod, 0, (S32) LLModel::LOD_HIGH);
+
+ if (lod != mPreviewLOD)
+ {
+ mPreviewLOD = lod;
+
+ LLComboBox* combo_box = mFMP->getChild<LLComboBox>("preview_lod_combo");
+ combo_box->setCurrentByIndex((NUM_LOD-1)-mPreviewLOD); // combo box list of lods is in reverse order
+ mFMP->childSetTextArg("lod_table_footer", "[DETAIL]", mFMP->getString(lod_name[mPreviewLOD]));
+ mFMP->childSetText("lod_file", mLODFile[mPreviewLOD]);
+
+ // the wizard has two lod drop downs
+ LLComboBox* combo_box2 = mFMP->getChild<LLComboBox>("preview_lod_combo2");
+ combo_box2->setCurrentByIndex((NUM_LOD-1)-mPreviewLOD); // combo box list of lods is in reverse order
+
+ LLColor4 highlight_color = LLUIColorTable::instance().getColor("MeshImportTableHighlightColor");
+ LLColor4 normal_color = LLUIColorTable::instance().getColor("MeshImportTableNormalColor");
+
+ for (S32 i = 0; i <= LLModel::LOD_HIGH; ++i)
+ {
+ const LLColor4& color = (i == lod) ? highlight_color : normal_color;
+
+ mFMP->childSetColor(lod_status_name[i], color);
+ mFMP->childSetColor(lod_label_name[i], color);
+ mFMP->childSetColor(lod_triangles_name[i], color);
+ mFMP->childSetColor(lod_vertices_name[i], color);
+ }
+
+ LLFloaterModelPreview* fmp = LLFloaterModelPreview::sInstance;
+ if (fmp)
+ {
+ LLRadioGroup* radio = fmp->getChild<LLRadioGroup>("lod_file_or_limit");
+ radio->selectNthItem(fmp->mLODMode[mPreviewLOD]);
+ }
+ }
+ refresh();
+ updateStatusMessages();
+}
+
+//static
+void LLFloaterModelPreview::onBrowseLOD(void* data)
+{
+ assert_main_thread();
+
+ LLFloaterModelPreview* mp = (LLFloaterModelPreview*) data;
+ mp->loadModel(mp->mModelPreview->mPreviewLOD);
+}
+
+//static
+void LLFloaterModelPreview::onUpload(void* user_data)
+{
+ assert_main_thread();
+
+ LLFloaterModelPreview* mp = (LLFloaterModelPreview*) user_data;
+
+ if ( mp && mp->mModelPreview->mHasPivot )
+ {
+ mp->mModelPreview->alterModelsPivot();
+ }
+
+ mp->mModelPreview->rebuildUploadData();
+
+ gMeshRepo.uploadModel(mp->mModelPreview->mUploadData, mp->mModelPreview->mPreviewScale,
+ mp->childGetValue("upload_textures").asBoolean(), mp->childGetValue("upload_skin"), mp->childGetValue("upload_joints"));
+
+ mp->closeFloater(false);
+}
+
+
+//static
+void LLFloaterModelPreview::onClearMaterials(void* user_data)
+{
+ LLFloaterModelPreview* mp = (LLFloaterModelPreview*) user_data;
+ mp->mModelPreview->clearMaterials();
+}
+
+//static
+void LLFloaterModelPreview::refresh(LLUICtrl* ctrl, void* user_data)
+{
+ sInstance->mModelPreview->mDirty = true;
+}
+
+void LLFloaterModelPreview::updateResourceCost()
+{
+ U32 cost = mModelPreview->mResourceCost;
+ childSetLabelArg("ok_btn", "[AMOUNT]", llformat("%d",cost));
+}
+
+//static
+void LLModelPreview::textureLoadedCallback( BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* src_aux, S32 discard_level, BOOL final, void* userdata )
+{
+ LLModelPreview* preview = (LLModelPreview*) userdata;
+ preview->refresh();
+}
+
+void LLModelPreview::onLODParamCommit(bool enforce_tri_limit)
+{
+ genLODs(mPreviewLOD, 3, enforce_tri_limit);
+ updateStatusMessages();
+ refresh();
+}
+
+LLFloaterModelPreview::DecompRequest::DecompRequest(const std::string& stage, LLModel* mdl)
+{
+ mStage = stage;
+ mContinue = 1;
+ mModel = mdl;
+ mDecompID = &mdl->mDecompID;
+ mParams = sInstance->mDecompParams;
+
+ //copy out positions and indices
+ if (mdl)
+ {
+ U16 index_offset = 0;
+
+ mPositions.clear();
+ mIndices.clear();
+
+ //queue up vertex positions and indices
+ for (S32 i = 0; i < mdl->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = mdl->getVolumeFace(i);
+ if (mPositions.size() + face.mNumVertices > 65535)
+ {
+ continue;
+ }
+
+ for (U32 j = 0; j < face.mNumVertices; ++j)
+ {
+ mPositions.push_back(LLVector3(face.mPositions[j].getF32ptr()));
+ }
+
+ for (U32 j = 0; j < face.mNumIndices; ++j)
+ {
+ mIndices.push_back(face.mIndices[j]+index_offset);
+ }
+
+ index_offset += face.mNumVertices;
+ }
+ }
+}
+
+void LLFloaterModelPreview::setStatusMessage(const std::string& msg)
+{
+ LLMutexLock lock(mStatusLock);
+ mStatusMessage = msg;
+}
+
+S32 LLFloaterModelPreview::DecompRequest::statusCallback(const char* status, S32 p1, S32 p2)
+{
+ if (mContinue)
+ {
+ setStatusMessage(llformat("%s: %d/%d", status, p1, p2));
+ if (LLFloaterModelPreview::sInstance)
+ {
+ LLFloaterModelPreview::sInstance->setStatusMessage(mStatusMessage);
+ }
+ }
+
+ return mContinue;
+}
+
+void LLFloaterModelPreview::DecompRequest::completed()
+{ //called from the main thread
+ if (mContinue)
+ {
+ mModel->setConvexHullDecomposition(mHull);
+
+ if (sInstance)
+ {
+ if (mContinue)
+ {
+ if (sInstance->mModelPreview)
+ {
+ sInstance->mModelPreview->mPhysicsMesh[mModel] = mHullMesh;
+ sInstance->mModelPreview->mDirty = true;
+ LLFloaterModelPreview::sInstance->mModelPreview->refresh();
+ }
+ }
+
+ sInstance->mCurRequest.erase(this);
+ }
+ }
+ else if (sInstance)
+ {
+ llassert(sInstance->mCurRequest.find(this) == sInstance->mCurRequest.end());
+ }
+}
diff --git a/indra/newview/llfloatermodelpreview.h b/indra/newview/llfloatermodelpreview.h
new file mode 100644
index 0000000000..e3b0f7522e
--- /dev/null
+++ b/indra/newview/llfloatermodelpreview.h
@@ -0,0 +1,367 @@
+/**
+ * @file llfloatermodelpreview.h
+ * @brief LLFloaterModelPreview class definition
+ *
+ * $LicenseInfo:firstyear=2004&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#ifndef LL_LLFLOATERMODELPREVIEW_H
+#define LL_LLFLOATERMODELPREVIEW_H
+
+#include "llfloaternamedesc.h"
+
+#include "lldynamictexture.h"
+#include "llfloatermodelwizard.h"
+#include "llquaternion.h"
+#include "llmeshrepository.h"
+#include "llmodel.h"
+#include "llthread.h"
+#include "llviewermenufile.h"
+
+class LLComboBox;
+class LLJoint;
+class LLViewerJointMesh;
+class LLVOAvatar;
+class LLTextBox;
+class LLVertexBuffer;
+class LLModelPreview;
+class LLFloaterModelPreview;
+class daeElement;
+class domProfile_COMMON;
+class domInstance_geometry;
+class domNode;
+class domTranslate;
+class LLMenuButton;
+class LLToggleableMenu;
+
+const S32 NUM_LOD = 4;
+
+class LLModelLoader : public LLThread
+{
+public:
+ typedef enum
+ {
+ STARTING = 0,
+ READING_FILE,
+ CREATING_FACES,
+ GENERATING_VERTEX_BUFFERS,
+ GENERATING_LOD,
+ DONE,
+ ERROR_PARSING, //basically loading failed
+ } eLoadState;
+
+ U32 mState;
+ std::string mFilename;
+ S32 mLod;
+ LLModelPreview* mPreview;
+ LLMatrix4 mTransform;
+ BOOL mFirstTransform;
+ LLVector3 mExtents[2];
+
+ std::map<daeElement*, LLPointer<LLModel> > mModel;
+
+ typedef std::vector<LLPointer<LLModel> > model_list;
+ model_list mModelList;
+
+ typedef std::vector<LLModelInstance> model_instance_list;
+
+ typedef std::map<LLMatrix4, model_instance_list > scene;
+
+ scene mScene;
+
+ typedef std::queue<LLPointer<LLModel> > model_queue;
+
+ //queue of models that need a physics rep
+ model_queue mPhysicsQ;
+
+ LLModelLoader(std::string filename, S32 lod, LLModelPreview* preview);
+
+ virtual void run();
+
+ void loadTextures() ; //called in the main thread.
+ void processElement(daeElement* element);
+ std::vector<LLImportMaterial> getMaterials(LLModel* model, domInstance_geometry* instance_geo);
+ LLImportMaterial profileToMaterial(domProfile_COMMON* material);
+ std::string getElementLabel(daeElement *element);
+ LLColor4 getDaeColor(daeElement* element);
+
+ daeElement* getChildFromElement( daeElement* pElement, std::string const & name );
+
+ bool isNodeAJoint( domNode* pNode );
+ void processJointNode( domNode* pNode, std::map<std::string,LLMatrix4>& jointTransforms );
+ void extractTranslation( domTranslate* pTranslate, LLMatrix4& transform );
+ void extractTranslationViaElement( daeElement* pTranslateElement, LLMatrix4& transform );
+
+ bool doesJointArrayContainACompleteRig( const std::vector<std::string> &modelJointList );
+ bool checkForCompleteRig( const std::vector<std::string> &jointListFromModel );
+
+ void handlePivotPoint( daeElement* pRoot );
+ bool isNodeAPivotPoint( domNode* pNode );
+
+ void setLoadState( U32 state ) { mState = state; }
+ U32 getLoadState( void ) { return mState; }
+
+ //map of avatar joints as named in COLLADA assets to internal joint names
+ std::map<std::string, std::string> mJointMap;
+ std::deque<std::string> mMasterJointList;
+ bool mResetJoints;
+};
+
+class LLFloaterModelPreview : public LLFloater
+{
+public:
+
+ class DecompRequest : public LLPhysicsDecomp::Request
+ {
+ public:
+ S32 mContinue;
+ LLPointer<LLModel> mModel;
+
+ DecompRequest(const std::string& stage, LLModel* mdl);
+ virtual S32 statusCallback(const char* status, S32 p1, S32 p2);
+ virtual void completed();
+
+ };
+ static LLFloaterModelPreview* sInstance;
+
+ LLFloaterModelPreview(const LLSD& key);
+ virtual ~LLFloaterModelPreview();
+
+ virtual BOOL postBuild();
+
+ BOOL handleMouseDown(S32 x, S32 y, MASK mask);
+ BOOL handleMouseUp(S32 x, S32 y, MASK mask);
+ BOOL handleHover(S32 x, S32 y, MASK mask);
+ BOOL handleScrollWheel(S32 x, S32 y, S32 clicks);
+
+ static void onMouseCaptureLostModelPreview(LLMouseHandler*);
+ static void setUploadAmount(S32 amount) { sUploadAmount = amount; }
+
+ void setDetails(F32 x, F32 y, F32 z, F32 streaming_cost, F32 physics_cost);
+
+ static void onBrowseLOD(void* data);
+
+ static void onUpload(void* data);
+
+ static void onClearMaterials(void* data);
+
+ static void refresh(LLUICtrl* ctrl, void* data);
+
+ void updateResourceCost();
+
+ void loadModel(S32 lod);
+
+ void onViewOptionChecked(const LLSD& userdata);
+ bool isViewOptionChecked(const LLSD& userdata);
+ bool isViewOptionEnabled(const LLSD& userdata);
+ void setViewOptionEnabled(const std::string& option, bool enabled);
+ void enableViewOption(const std::string& option);
+ void disableViewOption(const std::string& option);
+
+protected:
+ friend class LLModelPreview;
+ friend class LLMeshFilePicker;
+ friend class LLPhysicsDecomp;
+
+ static void onImportScaleCommit(LLUICtrl*, void*);
+ static void onPelvisOffsetCommit(LLUICtrl*, void*);
+ static void onUploadJointsCommit(LLUICtrl*,void*);
+ static void onUploadSkinCommit(LLUICtrl*,void*);
+
+ static void onPreviewLODCommit(LLUICtrl*,void*);
+
+ static void onGenerateNormalsCommit(LLUICtrl*,void*);
+
+ static void onAutoFillCommit(LLUICtrl*,void*);
+ static void onLODParamCommit(LLUICtrl*,void*);
+ static void onLODParamCommitTriangleLimit(LLUICtrl*,void*);
+
+ static void onExplodeCommit(LLUICtrl*, void*);
+
+ static void onPhysicsParamCommit(LLUICtrl* ctrl, void* userdata);
+ static void onPhysicsStageExecute(LLUICtrl* ctrl, void* userdata);
+ static void onCancel(LLUICtrl* ctrl, void* userdata);
+ static void onPhysicsStageCancel(LLUICtrl* ctrl, void* userdata);
+
+ static void onPhysicsBrowse(LLUICtrl* ctrl, void* userdata);
+ static void onPhysicsUseLOD(LLUICtrl* ctrl, void* userdata);
+ static void onPhysicsOptimize(LLUICtrl* ctrl, void* userdata);
+ static void onPhysicsDecomposeBack(LLUICtrl* ctrl, void* userdata);
+ static void onPhysicsSimplifyBack(LLUICtrl* ctrl, void* userdata);
+
+ void draw();
+
+ void initDecompControls();
+
+ void setStatusMessage(const std::string& msg);
+
+ LLModelPreview* mModelPreview;
+
+ LLPhysicsDecomp::decomp_params mDecompParams;
+
+ S32 mLastMouseX;
+ S32 mLastMouseY;
+ LLRect mPreviewRect;
+ U32 mGLName;
+ static S32 sUploadAmount;
+
+ std::set<LLPointer<DecompRequest> > mCurRequest;
+ std::string mStatusMessage;
+
+ //use "disabled" as false by default
+ std::map<std::string, bool> mViewOptionDisabled;
+
+ //store which lod mode each LOD is using
+ // 0 - load from file
+ // 1 - auto generate
+ // 2 - None
+ S32 mLODMode[4];
+
+ LLMenuButton* mViewOptionMenuButton;
+ LLToggleableMenu* mViewOptionMenu;
+ LLMutex* mStatusLock;
+
+};
+
+class LLMeshFilePicker : public LLFilePickerThread
+{
+public:
+ LLMeshFilePicker(LLModelPreview* mp, S32 lod);
+ virtual void notify(const std::string& filename);
+
+private:
+ LLModelPreview* mMP;
+ S32 mLOD;
+};
+
+
+class LLModelPreview : public LLViewerDynamicTexture, public LLMutex
+{
+ typedef boost::signals2::signal<void (F32 x, F32 y, F32 z, F32 streaming_cost, F32 physics_cost)> details_signal_t;
+ typedef boost::signals2::signal<void (void)> model_loaded_signal_t;
+
+public:
+ LLModelPreview(S32 width, S32 height, LLFloater* fmp);
+ virtual ~LLModelPreview();
+
+ void resetPreviewTarget();
+ void setPreviewTarget(F32 distance);
+ void setTexture(U32 name) { mTextureName = name; }
+
+ void setPhysicsFromLOD(S32 lod);
+ BOOL render();
+ void update();
+ void genBuffers(S32 lod, bool skinned);
+ void clearBuffers();
+ void refresh();
+ void rotate(F32 yaw_radians, F32 pitch_radians);
+ void zoom(F32 zoom_amt);
+ void pan(F32 right, F32 up);
+ virtual BOOL needsRender() { return mNeedsUpdate; }
+ void setPreviewLOD(S32 lod);
+ void clearModel(S32 lod);
+ void loadModel(std::string filename, S32 lod);
+ void loadModelCallback(S32 lod);
+ void genLODs(S32 which_lod = -1, U32 decimation = 3, bool enforce_tri_limit = false);
+ void generateNormals();
+ void alterModelsPivot( void );
+ void clearMaterials();
+ U32 calcResourceCost();
+ void rebuildUploadData();
+ void clearIncompatible(S32 lod);
+ void updateStatusMessages();
+ void clearGLODGroup();
+ void onLODParamCommit(bool enforce_tri_limit);
+ const bool getModelPivot( void ) const { return mHasPivot; }
+ void setHasPivot( bool val ) { mHasPivot = val; }
+ void setModelPivot( const LLVector3& pivot ) { mModelPivot = pivot; }
+
+ static void textureLoadedCallback( BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* src_aux, S32 discard_level, BOOL final, void* userdata );
+
+ boost::signals2::connection setDetailsCallback( const details_signal_t::slot_type& cb ){ return mDetailsSignal.connect(cb); }
+ boost::signals2::connection setModelLoadedCallback( const model_loaded_signal_t::slot_type& cb ){ return mModelLoadedSignal.connect(cb); }
+
+ protected:
+ friend class LLFloaterModelPreview;
+ friend class LLFloaterModelWizard;
+ friend class LLFloaterModelPreview::DecompRequest;
+ friend class LLFloaterModelWizard::DecompRequest;
+ friend class LLPhysicsDecomp;
+
+ LLFloater* mFMP;
+
+ BOOL mNeedsUpdate;
+ bool mDirty;
+ bool mGenLOD;
+ U32 mTextureName;
+ F32 mCameraDistance;
+ F32 mCameraYaw;
+ F32 mCameraPitch;
+ F32 mCameraZoom;
+ LLVector3 mCameraOffset;
+ LLVector3 mPreviewTarget;
+ LLVector3 mPreviewScale;
+ S32 mPreviewLOD;
+ U32 mResourceCost;
+ std::string mLODFile[LLModel::NUM_LODS];
+ bool mLoading;
+
+ std::map<std::string, bool> mViewOption;
+
+ //GLOD object parameters (must rebuild object if these change)
+ F32 mBuildShareTolerance;
+ U32 mBuildQueueMode;
+ U32 mBuildOperator;
+ U32 mBuildBorderMode;
+ S32 mRequestedTriangleCount[LLModel::NUM_LODS];
+
+
+ LLModelLoader* mModelLoader;
+
+ LLModelLoader::scene mScene[LLModel::NUM_LODS];
+ LLModelLoader::scene mBaseScene;
+
+ LLModelLoader::model_list mModel[LLModel::NUM_LODS];
+ LLModelLoader::model_list mBaseModel;
+
+ U32 mGroup;
+ std::map<LLPointer<LLModel>, U32> mObject;
+ U32 mMaxTriangleLimit;
+ std::map<LLPointer<LLModel>, std::vector<LLPointer<LLVertexBuffer> > > mPhysicsMesh;
+
+ LLMeshUploadThread::instance_list mUploadData;
+ std::set<LLViewerFetchedTexture* > mTextureSet;
+
+ //map of vertex buffers to models (one vertex buffer in vector per face in model
+ std::map<LLModel*, std::vector<LLPointer<LLVertexBuffer> > > mVertexBuffer[LLModel::NUM_LODS+1];
+
+ details_signal_t mDetailsSignal;
+ model_loaded_signal_t mModelLoadedSignal;
+
+ LLVector3 mModelPivot;
+ bool mHasPivot;
+
+ float mPelvisZOffset;
+};
+
+
+#endif // LL_LLFLOATERMODELPREVIEW_H
diff --git a/indra/newview/llfloatermodelwizard.cpp b/indra/newview/llfloatermodelwizard.cpp
new file mode 100644
index 0000000000..be43216b0e
--- /dev/null
+++ b/indra/newview/llfloatermodelwizard.cpp
@@ -0,0 +1,650 @@
+/**
+ * @file llfloatermodelwizard.cpp
+ * @author Leyla Farazha
+ * @brief Implementation of the LLFloaterModelWizard class.
+ *
+ * $LicenseInfo:firstyear=2002&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+
+#include "llviewerprecompiledheaders.h"
+
+#include "llbutton.h"
+#include "lldrawable.h"
+#include "llcheckboxctrl.h"
+#include "llcombobox.h"
+#include "llfloater.h"
+#include "llfloatermodelwizard.h"
+#include "llfloatermodelpreview.h"
+#include "llfloaterreg.h"
+#include "llsliderctrl.h"
+#include "lltoolmgr.h"
+#include "llviewerwindow.h"
+
+LLFloaterModelWizard* LLFloaterModelWizard::sInstance = NULL;
+
+static const std::string stateNames[]={
+ "choose_file",
+ "optimize",
+ "physics",
+ "review",
+ "upload"};
+
+LLFloaterModelWizard::LLFloaterModelWizard(const LLSD& key)
+ : LLFloater(key)
+{
+ mLastEnabledState = CHOOSE_FILE;
+ sInstance = this;
+
+ mCommitCallbackRegistrar.add("Wizard.Choose", boost::bind(&LLFloaterModelWizard::setState, this, CHOOSE_FILE));
+ mCommitCallbackRegistrar.add("Wizard.Optimize", boost::bind(&LLFloaterModelWizard::setState, this, OPTIMIZE));
+ mCommitCallbackRegistrar.add("Wizard.Physics", boost::bind(&LLFloaterModelWizard::setState, this, PHYSICS));
+ mCommitCallbackRegistrar.add("Wizard.Review", boost::bind(&LLFloaterModelWizard::setState, this, REVIEW));
+ mCommitCallbackRegistrar.add("Wizard.Upload", boost::bind(&LLFloaterModelWizard::setState, this, UPLOAD));
+}
+LLFloaterModelWizard::~LLFloaterModelWizard()
+{
+ sInstance = NULL;
+}
+void LLFloaterModelWizard::setState(int state)
+{
+
+ mState = state;
+
+ for(size_t t=0; t<LL_ARRAY_SIZE(stateNames); ++t)
+ {
+ LLView *view = getChildView(stateNames[t]+"_panel");
+ if (view)
+ {
+ view->setVisible(state == (int) t ? TRUE : FALSE);
+ }
+ }
+
+ if (state == CHOOSE_FILE)
+ {
+ mModelPreview->mViewOption["show_physics"] = false;
+
+ getChildView("close")->setVisible(false);
+ getChildView("back")->setVisible(true);
+ getChildView("back")->setEnabled(false);
+ getChildView("next")->setVisible(true);
+ getChildView("upload")->setVisible(false);
+ getChildView("cancel")->setVisible(true);
+ }
+
+ if (state == OPTIMIZE)
+ {
+ if (mLastEnabledState < state)
+ {
+ mModelPreview->genLODs(-1);
+ }
+
+ mModelPreview->mViewOption["show_physics"] = false;
+
+ getChildView("back")->setVisible(true);
+ getChildView("back")->setEnabled(true);
+ getChildView("close")->setVisible(false);
+ getChildView("next")->setVisible(true);
+ getChildView("upload")->setVisible(false);
+ getChildView("cancel")->setVisible(true);
+ }
+
+ if (state == PHYSICS)
+ {
+ if (mLastEnabledState < state)
+ {
+ mModelPreview->setPhysicsFromLOD(1);
+ }
+
+ mModelPreview->mViewOption["show_physics"] = true;
+
+ getChildView("next")->setVisible(true);
+ getChildView("upload")->setVisible(false);
+ getChildView("close")->setVisible(false);
+ getChildView("back")->setVisible(true);
+ getChildView("back")->setEnabled(true);
+ getChildView("cancel")->setVisible(true);
+ }
+
+ if (state == REVIEW)
+ {
+ if (mLastEnabledState < state)
+ {
+ executePhysicsStage("Decompose");
+ }
+
+ mModelPreview->mViewOption["show_physics"] = true;
+
+ getChildView("close")->setVisible(false);
+ getChildView("next")->setVisible(false);
+ getChildView("back")->setVisible(true);
+ getChildView("back")->setEnabled(true);
+ getChildView("upload")->setVisible(true);
+ getChildView("cancel")->setVisible(true);
+ }
+
+ if (state == UPLOAD)
+ {
+ getChildView("close")->setVisible(true);
+ getChildView("next")->setVisible(false);
+ getChildView("back")->setVisible(false);
+ getChildView("upload")->setVisible(false);
+ getChildView("cancel")->setVisible(false);
+ }
+
+ updateButtons();
+}
+
+
+
+void LLFloaterModelWizard::updateButtons()
+{
+ if (mLastEnabledState < mState)
+ {
+ mLastEnabledState = mState;
+ }
+
+ for(size_t i=0; i<LL_ARRAY_SIZE(stateNames); ++i)
+ {
+ LLButton *button = getChild<LLButton>(stateNames[i]+"_btn");
+
+ if (i == mState)
+ {
+ button->setEnabled(TRUE);
+ button->setToggleState(TRUE);
+ }
+ else if (i <= mLastEnabledState)
+ {
+ button->setEnabled(TRUE);
+ button->setToggleState(FALSE);
+ }
+ else
+ {
+ button->setEnabled(FALSE);
+ }
+ }
+}
+
+void LLFloaterModelWizard::loadModel()
+{
+ mModelPreview->mLoading = TRUE;
+
+ (new LLMeshFilePicker(mModelPreview, 3))->getFile();
+}
+
+void LLFloaterModelWizard::onClickCancel()
+{
+ closeFloater();
+}
+
+void LLFloaterModelWizard::onClickBack()
+{
+ setState(llmax((int) CHOOSE_FILE, mState-1));
+}
+
+void LLFloaterModelWizard::onClickNext()
+{
+ setState(llmin((int) UPLOAD, mState+1));
+}
+
+bool LLFloaterModelWizard::onEnableNext()
+{
+ return true;
+}
+
+bool LLFloaterModelWizard::onEnableBack()
+{
+ return true;
+}
+
+
+//-----------------------------------------------------------------------------
+// handleMouseDown()
+//-----------------------------------------------------------------------------
+BOOL LLFloaterModelWizard::handleMouseDown(S32 x, S32 y, MASK mask)
+{
+ if (mPreviewRect.pointInRect(x, y))
+ {
+ bringToFront( x, y );
+ gFocusMgr.setMouseCapture(this);
+ gViewerWindow->hideCursor();
+ mLastMouseX = x;
+ mLastMouseY = y;
+ return TRUE;
+ }
+
+ return LLFloater::handleMouseDown(x, y, mask);
+}
+
+//-----------------------------------------------------------------------------
+// handleMouseUp()
+//-----------------------------------------------------------------------------
+BOOL LLFloaterModelWizard::handleMouseUp(S32 x, S32 y, MASK mask)
+{
+ gFocusMgr.setMouseCapture(FALSE);
+ gViewerWindow->showCursor();
+ return LLFloater::handleMouseUp(x, y, mask);
+}
+
+//-----------------------------------------------------------------------------
+// handleHover()
+//-----------------------------------------------------------------------------
+BOOL LLFloaterModelWizard::handleHover (S32 x, S32 y, MASK mask)
+{
+ MASK local_mask = mask & ~MASK_ALT;
+
+ if (mModelPreview && hasMouseCapture())
+ {
+ if (local_mask == MASK_PAN)
+ {
+ // pan here
+ mModelPreview->pan((F32)(x - mLastMouseX) * -0.005f, (F32)(y - mLastMouseY) * -0.005f);
+ }
+ else if (local_mask == MASK_ORBIT)
+ {
+ F32 yaw_radians = (F32)(x - mLastMouseX) * -0.01f;
+ F32 pitch_radians = (F32)(y - mLastMouseY) * 0.02f;
+
+ mModelPreview->rotate(yaw_radians, pitch_radians);
+ }
+ else
+ {
+
+ F32 yaw_radians = (F32)(x - mLastMouseX) * -0.01f;
+ F32 zoom_amt = (F32)(y - mLastMouseY) * 0.02f;
+
+ mModelPreview->rotate(yaw_radians, 0.f);
+ mModelPreview->zoom(zoom_amt);
+ }
+
+
+ mModelPreview->refresh();
+
+ LLUI::setMousePositionLocal(this, mLastMouseX, mLastMouseY);
+ }
+
+ if (!mPreviewRect.pointInRect(x, y) || !mModelPreview)
+ {
+ return LLFloater::handleHover(x, y, mask);
+ }
+ else if (local_mask == MASK_ORBIT)
+ {
+ gViewerWindow->setCursor(UI_CURSOR_TOOLCAMERA);
+ }
+ else if (local_mask == MASK_PAN)
+ {
+ gViewerWindow->setCursor(UI_CURSOR_TOOLPAN);
+ }
+ else
+ {
+ gViewerWindow->setCursor(UI_CURSOR_TOOLZOOMIN);
+ }
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// handleScrollWheel()
+//-----------------------------------------------------------------------------
+BOOL LLFloaterModelWizard::handleScrollWheel(S32 x, S32 y, S32 clicks)
+{
+ if (mPreviewRect.pointInRect(x, y) && mModelPreview)
+ {
+ mModelPreview->zoom((F32)clicks * -0.2f);
+ mModelPreview->refresh();
+ }
+
+ return TRUE;
+}
+
+void LLFloaterModelWizard::initDecompControls()
+{
+ LLSD key;
+
+ static const LLCDStageData* stage = NULL;
+ static S32 stage_count = 0;
+
+ if (!stage && LLConvexDecomposition::getInstance() != NULL)
+ {
+ stage_count = LLConvexDecomposition::getInstance()->getStages(&stage);
+ }
+
+ static const LLCDParam* param = NULL;
+ static S32 param_count = 0;
+ if (!param && LLConvexDecomposition::getInstance() != NULL)
+ {
+ param_count = LLConvexDecomposition::getInstance()->getParameters(&param);
+ }
+
+ for (S32 j = stage_count-1; j >= 0; --j)
+ {
+ gMeshRepo.mDecompThread->mStageID[stage[j].mName] = j;
+ // protected against stub by stage_count being 0 for stub above
+ LLConvexDecomposition::getInstance()->registerCallback(j, LLPhysicsDecomp::llcdCallback);
+
+ for (S32 i = 0; i < param_count; ++i)
+ {
+ if (param[i].mStage != j)
+ {
+ continue;
+ }
+
+ std::string name(param[i].mName ? param[i].mName : "");
+ std::string description(param[i].mDescription ? param[i].mDescription : "");
+
+ if (param[i].mType == LLCDParam::LLCD_FLOAT)
+ {
+ mDecompParams[param[i].mName] = LLSD(param[i].mDefault.mFloat);
+ }
+ else if (param[i].mType == LLCDParam::LLCD_INTEGER)
+ {
+ mDecompParams[param[i].mName] = LLSD(param[i].mDefault.mIntOrEnumValue);
+ }
+ else if (param[i].mType == LLCDParam::LLCD_BOOLEAN)
+ {
+ mDecompParams[param[i].mName] = LLSD(param[i].mDefault.mBool);
+ }
+ else if (param[i].mType == LLCDParam::LLCD_ENUM)
+ {
+ mDecompParams[param[i].mName] = LLSD(param[i].mDefault.mIntOrEnumValue);
+ }
+ }
+ }
+
+ mDecompParams["Simplify Method"] = 0; // set it to retain %
+}
+
+//static
+void LLFloaterModelWizard::executePhysicsStage(std::string stage_name)
+{
+ if (sInstance)
+ {
+ F64 physics_accuracy = sInstance->getChild<LLSliderCtrl>("physics_slider")->getValue().asReal();
+
+ sInstance->mDecompParams["Retain%"] = physics_accuracy;
+
+ if (!sInstance->mCurRequest.empty())
+ {
+ llinfos << "Decomposition request still pending." << llendl;
+ return;
+ }
+
+ if (sInstance->mModelPreview)
+ {
+ for (S32 i = 0; i < sInstance->mModelPreview->mModel[LLModel::LOD_PHYSICS].size(); ++i)
+ {
+ LLModel* mdl = sInstance->mModelPreview->mModel[LLModel::LOD_PHYSICS][i];
+ DecompRequest* request = new DecompRequest(stage_name, mdl);
+ sInstance->mCurRequest.insert(request);
+ gMeshRepo.mDecompThread->submitRequest(request);
+ }
+ }
+ }
+}
+
+LLFloaterModelWizard::DecompRequest::DecompRequest(const std::string& stage, LLModel* mdl)
+{
+ mStage = stage;
+ mContinue = 1;
+ mModel = mdl;
+ mDecompID = &mdl->mDecompID;
+ mParams = sInstance->mDecompParams;
+
+ //copy out positions and indices
+ if (mdl)
+ {
+ U16 index_offset = 0;
+
+ mPositions.clear();
+ mIndices.clear();
+
+ //queue up vertex positions and indices
+ for (S32 i = 0; i < mdl->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = mdl->getVolumeFace(i);
+ if (mPositions.size() + face.mNumVertices > 65535)
+ {
+ continue;
+ }
+
+ for (U32 j = 0; j < face.mNumVertices; ++j)
+ {
+ mPositions.push_back(LLVector3(face.mPositions[j].getF32ptr()));
+ }
+
+ for (U32 j = 0; j < face.mNumIndices; ++j)
+ {
+ mIndices.push_back(face.mIndices[j]+index_offset);
+ }
+
+ index_offset += face.mNumVertices;
+ }
+ }
+}
+
+
+S32 LLFloaterModelWizard::DecompRequest::statusCallback(const char* status, S32 p1, S32 p2)
+{
+ setStatusMessage(llformat("%s: %d/%d", status, p1, p2));
+
+ return mContinue;
+}
+
+void LLFloaterModelWizard::DecompRequest::completed()
+{ //called from the main thread
+ mModel->setConvexHullDecomposition(mHull);
+
+ if (sInstance)
+ {
+ if (sInstance->mModelPreview)
+ {
+ sInstance->mModelPreview->mPhysicsMesh[mModel] = mHullMesh;
+ sInstance->mModelPreview->mDirty = true;
+ LLFloaterModelWizard::sInstance->mModelPreview->refresh();
+ }
+
+ sInstance->mCurRequest.erase(this);
+ }
+
+ if (mStage == "Decompose")
+ {
+ executePhysicsStage("Simplify");
+ }
+}
+
+
+BOOL LLFloaterModelWizard::postBuild()
+{
+ LLView* preview_panel = getChildView("preview_panel");
+
+ childSetValue("import_scale", (F32) 0.67335826);
+
+ getChild<LLUICtrl>("browse")->setCommitCallback(boost::bind(&LLFloaterModelWizard::loadModel, this));
+ //getChild<LLUICtrl>("lod_file")->setCommitCallback(boost::bind(&LLFloaterModelWizard::loadModel, this));
+ getChild<LLUICtrl>("cancel")->setCommitCallback(boost::bind(&LLFloaterModelWizard::onClickCancel, this));
+ getChild<LLUICtrl>("close")->setCommitCallback(boost::bind(&LLFloaterModelWizard::onClickCancel, this));
+ getChild<LLUICtrl>("back")->setCommitCallback(boost::bind(&LLFloaterModelWizard::onClickBack, this));
+ getChild<LLUICtrl>("next")->setCommitCallback(boost::bind(&LLFloaterModelWizard::onClickNext, this));
+ getChild<LLUICtrl>("preview_lod_combo")->setCommitCallback(boost::bind(&LLFloaterModelWizard::onPreviewLODCommit, this, _1));
+ getChild<LLUICtrl>("preview_lod_combo2")->setCommitCallback(boost::bind(&LLFloaterModelWizard::onPreviewLODCommit, this, _1));
+ getChild<LLUICtrl>("accuracy_slider")->setCommitCallback(boost::bind(&LLFloaterModelWizard::onAccuracyPerformance, this, _2));
+ getChild<LLUICtrl>("upload")->setCommitCallback(boost::bind(&LLFloaterModelWizard::onUpload, this));
+ getChild<LLUICtrl>("physics_slider")->setCommitCallback(boost::bind(&LLFloaterModelWizard::onPhysicsChanged, this));
+
+ LLUICtrl::EnableCallbackRegistry::ScopedRegistrar enable_registrar;
+
+ enable_registrar.add("Next.OnEnable", boost::bind(&LLFloaterModelWizard::onEnableNext, this));
+ enable_registrar.add("Back.OnEnable", boost::bind(&LLFloaterModelWizard::onEnableBack, this));
+
+
+ mPreviewRect = preview_panel->getRect();
+
+ mModelPreview = new LLModelPreview(512, 512, this);
+ mModelPreview->setPreviewTarget(16.f);
+ mModelPreview->setDetailsCallback(boost::bind(&LLFloaterModelWizard::setDetails, this, _1, _2, _3, _4, _5));
+ mModelPreview->setModelLoadedCallback(boost::bind(&LLFloaterModelWizard::modelLoadedCallback, this));
+
+ center();
+
+ setState(CHOOSE_FILE);
+
+ childSetTextArg("import_dimensions", "[X]", LLStringUtil::null);
+ childSetTextArg("import_dimensions", "[Y]", LLStringUtil::null);
+ childSetTextArg("import_dimensions", "[Z]", LLStringUtil::null);
+
+ initDecompControls();
+
+ return TRUE;
+}
+
+
+void LLFloaterModelWizard::setDetails(F32 x, F32 y, F32 z, F32 streaming_cost, F32 physics_cost)
+{
+ // iterate through all the panels, setting the dimensions
+ for(size_t t=0; t<LL_ARRAY_SIZE(stateNames); ++t)
+ {
+ LLPanel *panel = getChild<LLPanel>(stateNames[t]+"_panel");
+ if (panel)
+ {
+ panel->childSetText("dimension_x", llformat("%.1f", x));
+ panel->childSetText("dimension_y", llformat("%.1f", y));
+ panel->childSetText("dimension_z", llformat("%.1f", z));
+ panel->childSetTextArg("streaming cost", "[COST]", llformat("%.3f", streaming_cost));
+ panel->childSetTextArg("physics cost", "[COST]", llformat("%.3f", physics_cost));
+ }
+ }
+}
+
+void LLFloaterModelWizard::modelLoadedCallback()
+{
+ mLastEnabledState = CHOOSE_FILE;
+ getChild<LLCheckBoxCtrl>("confirm_checkbox")->set(FALSE);
+ updateButtons();
+}
+
+void LLFloaterModelWizard::onPhysicsChanged()
+{
+ mLastEnabledState = PHYSICS;
+ updateButtons();
+}
+
+void LLFloaterModelWizard::onUpload()
+{
+ mModelPreview->rebuildUploadData();
+
+ gMeshRepo.uploadModel(mModelPreview->mUploadData, mModelPreview->mPreviewScale,
+ childGetValue("upload_textures").asBoolean(), childGetValue("upload_skin"), childGetValue("upload_joints"));
+
+ setState(UPLOAD);
+
+}
+
+void LLFloaterModelWizard::onAccuracyPerformance(const LLSD& data)
+{
+ int val = (int) data.asInteger();
+
+ mModelPreview->genLODs(-1, NUM_LOD-val);
+
+ mModelPreview->refresh();
+}
+
+
+void LLFloaterModelWizard::onPreviewLODCommit(LLUICtrl* ctrl)
+{
+ if (!mModelPreview)
+ {
+ return;
+ }
+
+ S32 which_mode = 0;
+
+ LLComboBox* combo = (LLComboBox*) ctrl;
+
+ which_mode = (NUM_LOD-1)-combo->getFirstSelectedIndex(); // combo box list of lods is in reverse order
+
+ mModelPreview->setPreviewLOD(which_mode);
+}
+
+void LLFloaterModelWizard::refresh()
+{
+ if (mState == CHOOSE_FILE)
+ {
+ bool model_loaded = false;
+
+ if (mModelPreview && mModelPreview->mModelLoader && mModelPreview->mModelLoader->getLoadState() == LLModelLoader::DONE)
+ {
+ model_loaded = true;
+ }
+
+ getChildView("next")->setEnabled(model_loaded);
+ }
+ if (mState == REVIEW)
+ {
+ getChildView("upload")->setEnabled(getChild<LLCheckBoxCtrl>("confirm_checkbox")->getValue().asBoolean());
+ }
+
+}
+
+void LLFloaterModelWizard::draw()
+{
+ refresh();
+
+ LLFloater::draw();
+ LLRect r = getRect();
+
+ mModelPreview->update();
+
+ if (mModelPreview)
+ {
+ gGL.color3f(1.f, 1.f, 1.f);
+
+ gGL.getTexUnit(0)->bind(mModelPreview);
+
+ LLView *view = getChildView(stateNames[mState]+"_panel");
+ LLView* preview_panel = view->getChildView("preview_panel");
+
+ LLRect rect = preview_panel->getRect();
+ if (rect != mPreviewRect)
+ {
+ mModelPreview->refresh();
+ mPreviewRect = preview_panel->getRect();
+ }
+
+ LLRect item_rect;
+ preview_panel->localRectToOtherView(preview_panel->getLocalRect(), &item_rect, this);
+
+ gGL.begin( LLRender::QUADS );
+ {
+ gGL.texCoord2f(0.f, 1.f);
+ gGL.vertex2i(item_rect.mLeft, item_rect.mTop-1);
+ gGL.texCoord2f(0.f, 0.f);
+ gGL.vertex2i(item_rect.mLeft, item_rect.mBottom);
+ gGL.texCoord2f(1.f, 0.f);
+ gGL.vertex2i(item_rect.mRight-1, item_rect.mBottom);
+ gGL.texCoord2f(1.f, 1.f);
+ gGL.vertex2i(item_rect.mRight-1, item_rect.mTop-1);
+ }
+ gGL.end();
+
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ }
+}
diff --git a/indra/newview/llfloatermodelwizard.h b/indra/newview/llfloatermodelwizard.h
new file mode 100644
index 0000000000..50e4ab1a96
--- /dev/null
+++ b/indra/newview/llfloatermodelwizard.h
@@ -0,0 +1,112 @@
+/**
+ * @file llfloatermodelwizard.h
+ *
+ * $LicenseInfo:firstyear=2009&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#ifndef LLFLOATERMODELWIZARD_H
+#define LLFLOATERMODELWIZARD_H
+
+
+#include "llmeshrepository.h"
+#include "llmodel.h"
+#include "llthread.h"
+
+
+class LLModelPreview;
+
+
+class LLFloaterModelWizard : public LLFloater
+{
+public:
+
+ class DecompRequest : public LLPhysicsDecomp::Request
+ {
+ public:
+ S32 mContinue;
+ LLPointer<LLModel> mModel;
+
+ DecompRequest(const std::string& stage, LLModel* mdl);
+ virtual S32 statusCallback(const char* status, S32 p1, S32 p2);
+ virtual void completed();
+
+ };
+
+ static LLFloaterModelWizard* sInstance;
+
+ LLFloaterModelWizard(const LLSD& key);
+ virtual ~LLFloaterModelWizard();
+ /*virtual*/ BOOL postBuild();
+ void draw();
+ void refresh();
+
+ BOOL handleMouseDown(S32 x, S32 y, MASK mask);
+ BOOL handleMouseUp(S32 x, S32 y, MASK mask);
+ BOOL handleHover(S32 x, S32 y, MASK mask);
+ BOOL handleScrollWheel(S32 x, S32 y, S32 clicks);
+
+ void setDetails(F32 x, F32 y, F32 z, F32 streaming_cost, F32 physics_cost);
+ void modelLoadedCallback();
+ void onPhysicsChanged();
+ void initDecompControls();
+
+ LLPhysicsDecomp::decomp_params mDecompParams;
+ std::set<LLPointer<DecompRequest> > mCurRequest;
+ std::string mStatusMessage;
+ static void executePhysicsStage(std::string stage_name);
+
+private:
+ enum EWizardState
+ {
+ CHOOSE_FILE = 0,
+ OPTIMIZE,
+ PHYSICS,
+ REVIEW,
+ UPLOAD
+ };
+
+ void setState(int state);
+ void updateButtons();
+ void onClickCancel();
+ void onClickBack();
+ void onClickNext();
+ bool onEnableNext();
+ bool onEnableBack();
+ void loadModel();
+ void onPreviewLODCommit(LLUICtrl*);
+ void onAccuracyPerformance(const LLSD& data);
+ void onUpload();
+
+ LLModelPreview* mModelPreview;
+ LLRect mPreviewRect;
+ int mState;
+
+ S32 mLastMouseX;
+ S32 mLastMouseY;
+
+ U32 mLastEnabledState;
+
+
+};
+
+
+#endif
diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp
index 724096b443..a90bacf41d 100755..100644
--- a/indra/newview/llfloaterpreference.cpp
+++ b/indra/newview/llfloaterpreference.cpp
@@ -1036,26 +1036,26 @@ void LLFloaterPreference::refreshEnabledState()
//Deferred/SSAO/Shadows
LLCheckBoxCtrl* ctrl_deferred = getChild<LLCheckBoxCtrl>("UseLightShaders");
- if (LLFeatureManager::getInstance()->isFeatureAvailable("RenderUseFBO") &&
- LLFeatureManager::getInstance()->isFeatureAvailable("RenderDeferred") &&
- shaders)
- {
- BOOL enabled = (ctrl_wind_light->get()) ? TRUE : FALSE;
+
+ BOOL enabled = LLFeatureManager::getInstance()->isFeatureAvailable("RenderDeferred") &&
+ shaders &&
+ gGLManager.mHasFramebufferObject &&
+ gSavedSettings.getBOOL("RenderAvatarVP") &&
+ (ctrl_wind_light->get()) ? TRUE : FALSE;
- ctrl_deferred->setEnabled(enabled);
+ ctrl_deferred->setEnabled(enabled);
- LLCheckBoxCtrl* ctrl_ssao = getChild<LLCheckBoxCtrl>("UseSSAO");
- LLComboBox* ctrl_shadow = getChild<LLComboBox>("ShadowDetail");
+ LLCheckBoxCtrl* ctrl_ssao = getChild<LLCheckBoxCtrl>("UseSSAO");
+ LLComboBox* ctrl_shadow = getChild<LLComboBox>("ShadowDetail");
- enabled = enabled && LLFeatureManager::getInstance()->isFeatureAvailable("RenderDeferredSSAO") && (ctrl_deferred->get() ? TRUE : FALSE);
+ enabled = enabled && LLFeatureManager::getInstance()->isFeatureAvailable("RenderDeferredSSAO") && (ctrl_deferred->get() ? TRUE : FALSE);
- ctrl_ssao->setEnabled(enabled);
+ ctrl_ssao->setEnabled(enabled);
- enabled = enabled && LLFeatureManager::getInstance()->isFeatureAvailable("RenderShadowDetail");
-
- ctrl_shadow->setEnabled(enabled);
- }
+ enabled = enabled && LLFeatureManager::getInstance()->isFeatureAvailable("RenderShadowDetail");
+ ctrl_shadow->setEnabled(enabled);
+
// now turn off any features that are unavailable
disableUnavailableSettings();
@@ -1121,7 +1121,8 @@ void LLFloaterPreference::disableUnavailableSettings()
}
// disabled deferred
- if(!LLFeatureManager::getInstance()->isFeatureAvailable("RenderDeferred"))
+ if (!LLFeatureManager::getInstance()->isFeatureAvailable("RenderDeferred") ||
+ !gGLManager.mHasFramebufferObject)
{
ctrl_shadows->setEnabled(FALSE);
ctrl_shadows->setValue(0);
diff --git a/indra/newview/llfloatertools.cpp b/indra/newview/llfloatertools.cpp
index 364fbad193..257970aaaf 100644
--- a/indra/newview/llfloatertools.cpp
+++ b/indra/newview/llfloatertools.cpp
@@ -32,6 +32,7 @@
#include "llcoord.h"
//#include "llgl.h"
+#include "llagent.h"
#include "llagentcamera.h"
#include "llbutton.h"
#include "llcheckboxctrl.h"
@@ -420,27 +421,83 @@ void LLFloaterTools::refresh()
// Refresh object and prim count labels
LLLocale locale(LLLocale::USER_LOCALE);
- std::string obj_count_string;
- LLResMgr::getInstance()->getIntegerString(obj_count_string, LLSelectMgr::getInstance()->getSelection()->getRootObjectCount());
- getChild<LLUICtrl>("obj_count")->setTextArg("[COUNT]", obj_count_string);
- std::string prim_count_string;
- LLResMgr::getInstance()->getIntegerString(prim_count_string, LLSelectMgr::getInstance()->getSelection()->getObjectCount());
- getChild<LLUICtrl>("prim_count")->setTextArg("[COUNT]", prim_count_string);
-
- // calculate selection rendering cost
- if (sShowObjectCost)
- {
- std::string prim_cost_string;
- LLResMgr::getInstance()->getIntegerString(prim_cost_string, calcRenderCost());
- getChild<LLUICtrl>("RenderingCost")->setTextArg("[COUNT]", prim_cost_string);
+
+ if ((gAgent.getRegion() && gAgent.getRegion()->getCapability("GetMesh").empty()) || !gSavedSettings.getBOOL("MeshEnabled"))
+ {
+ std::string obj_count_string;
+ LLResMgr::getInstance()->getIntegerString(obj_count_string, LLSelectMgr::getInstance()->getSelection()->getRootObjectCount());
+ getChild<LLUICtrl>("obj_count")->setTextArg("[COUNT]", obj_count_string);
+ std::string prim_count_string;
+ LLResMgr::getInstance()->getIntegerString(prim_count_string, LLSelectMgr::getInstance()->getSelection()->getObjectCount());
+ getChild<LLUICtrl>("prim_count")->setTextArg("[COUNT]", prim_count_string);
+
+ // calculate selection rendering cost
+ if (sShowObjectCost)
+ {
+ std::string prim_cost_string;
+ LLResMgr::getInstance()->getIntegerString(prim_cost_string, calcRenderCost());
+ getChild<LLUICtrl>("RenderingCost")->setTextArg("[COUNT]", prim_cost_string);
+ }
+
+ // disable the object and prim counts if nothing selected
+ bool have_selection = ! LLSelectMgr::getInstance()->getSelection()->isEmpty();
+ getChildView("obj_count")->setEnabled(have_selection);
+ getChildView("prim_count")->setEnabled(have_selection);
+ getChildView("RenderingCost")->setEnabled(have_selection && sShowObjectCost);
}
+ else
+ {
+ // Get the number of objects selected
+ std::string root_object_count_string;
+ std::string object_count_string;
+
+ LLResMgr::getInstance()->getIntegerString(
+ root_object_count_string,
+ LLSelectMgr::getInstance()->getSelection()->getRootObjectCount());
+ LLResMgr::getInstance()->getIntegerString(
+ object_count_string,
+ LLSelectMgr::getInstance()->getSelection()->getObjectCount());
+
+ F32 obj_cost =
+ LLSelectMgr::getInstance()->getSelection()->getSelectedObjectCost();
+ F32 link_cost =
+ LLSelectMgr::getInstance()->getSelection()->getSelectedLinksetCost();
+ F32 obj_physics_cost =
+ LLSelectMgr::getInstance()->getSelection()->getSelectedPhysicsCost();
+ F32 link_physics_cost =
+ LLSelectMgr::getInstance()->getSelection()->getSelectedLinksetPhysicsCost();
+
+ // Update the text for the counts
+ childSetTextArg(
+ "linked_set_count",
+ "[COUNT]",
+ root_object_count_string);
+ childSetTextArg("object_count", "[COUNT]", object_count_string);
+
+ // Update the text for the resource costs
+ childSetTextArg("linked_set_cost","[COST]",llformat("%.1f", link_cost));
+ childSetTextArg("object_cost", "[COST]", llformat("%.1f", obj_cost));
+ childSetTextArg("linked_set_cost","[PHYSICS]",llformat("%.1f", link_physics_cost));
+ childSetTextArg("object_cost", "[PHYSICS]", llformat("%.1f", obj_physics_cost));
+
+ // Display rendering cost if needed
+ if (sShowObjectCost)
+ {
+ std::string prim_cost_string;
+ LLResMgr::getInstance()->getIntegerString(prim_cost_string, calcRenderCost());
+ getChild<LLUICtrl>("RenderingCost")->setTextArg("[COUNT]", prim_cost_string);
+ }
- // disable the object and prim counts if nothing selected
- bool have_selection = ! LLSelectMgr::getInstance()->getSelection()->isEmpty();
- getChildView("obj_count")->setEnabled(have_selection);
- getChildView("prim_count")->setEnabled(have_selection);
- getChildView("RenderingCost")->setEnabled(have_selection && sShowObjectCost);
+ // disable the object and prim counts if nothing selected
+ bool have_selection = ! LLSelectMgr::getInstance()->getSelection()->isEmpty();
+ childSetEnabled("linked_set_count", have_selection);
+ childSetEnabled("object_count", have_selection);
+ childSetEnabled("linked_set_cost", have_selection);
+ childSetEnabled("object_cost", have_selection);
+ getChildView("RenderingCost")->setEnabled(have_selection && sShowObjectCost);
+ }
+
// Refresh child tabs
mPanelPermissions->refresh();
@@ -730,8 +787,16 @@ void LLFloaterTools::updatePopup(LLCoordGL center, MASK mask)
getChildView("Strength:")->setVisible( land_visible);
}
- getChildView("obj_count")->setVisible( !land_visible);
- getChildView("prim_count")->setVisible( !land_visible);
+ bool show_mesh_cost = !gAgent.getRegion()->getCapability("GetMesh").empty() && gSavedSettings.getBOOL("MeshEnabled");
+
+ getChildView("obj_count")->setVisible( !land_visible && !show_mesh_cost);
+ getChildView("prim_count")->setVisible( !land_visible && !show_mesh_cost);
+ getChildView("linked_set_count")->setVisible( !land_visible && show_mesh_cost);
+ getChildView("linked_set_cost")->setVisible( !land_visible && show_mesh_cost);
+ getChildView("object_count")->setVisible( !land_visible && show_mesh_cost);
+ getChildView("object_cost")->setVisible( !land_visible && show_mesh_cost);
+ getChildView("RenderingCost")->setVisible( !land_visible && sShowObjectCost);
+
mTab->setVisible(!land_visible);
mPanelLandInfo->setVisible(land_visible);
}
@@ -988,30 +1053,33 @@ void LLFloaterTools::onClickGridOptions()
S32 LLFloaterTools::calcRenderCost()
{
- S32 cost = 0;
- std::set<LLUUID> textures;
-
- for (LLObjectSelection::iterator selection_iter = LLSelectMgr::getInstance()->getSelection()->begin();
- selection_iter != LLSelectMgr::getInstance()->getSelection()->end();
- ++selection_iter)
- {
- LLSelectNode *select_node = *selection_iter;
- if (select_node)
- {
- LLVOVolume *viewer_volume = (LLVOVolume*)select_node->getObject();
- if (viewer_volume)
- {
- cost += viewer_volume->getRenderCost(textures);
- cost += textures.size() * LLVOVolume::ARC_TEXTURE_COST;
- textures.clear();
- }
- }
- }
-
-
- return cost;
+ S32 cost = 0;
+ std::set<LLUUID> textures;
+
+ for (LLObjectSelection::iterator selection_iter = LLSelectMgr::getInstance()->getSelection()->begin();
+ selection_iter != LLSelectMgr::getInstance()->getSelection()->end();
+ ++selection_iter)
+ {
+ LLSelectNode *select_node = *selection_iter;
+ if (select_node)
+ {
+ LLViewerObject *vobj = select_node->getObject();
+ if (vobj->getVolume())
+ {
+ LLVOVolume* volume = (LLVOVolume*) vobj;
+
+ cost += volume->getRenderCost(textures);
+ cost += textures.size() * LLVOVolume::ARC_TEXTURE_COST;
+ textures.clear();
+ }
+ }
+ }
+
+
+ return cost;
}
+
// static
void LLFloaterTools::setEditTool(void* tool_pointer)
{
diff --git a/indra/newview/llfloaterworldmap.cpp b/indra/newview/llfloaterworldmap.cpp
index 03cf0332a9..03cf0332a9 100755..100644
--- a/indra/newview/llfloaterworldmap.cpp
+++ b/indra/newview/llfloaterworldmap.cpp
diff --git a/indra/newview/llhudicon.cpp b/indra/newview/llhudicon.cpp
index 568b0ae585..7e1025c41b 100644
--- a/indra/newview/llhudicon.cpp
+++ b/indra/newview/llhudicon.cpp
@@ -33,6 +33,7 @@
#include "llviewerobject.h"
#include "lldrawable.h"
+#include "llvector4a.h"
#include "llviewercamera.h"
#include "llviewertexture.h"
#include "llviewerwindow.h"
@@ -255,21 +256,42 @@ BOOL LLHUDIcon::lineSegmentIntersect(const LLVector3& start, const LLVector3& en
LLVector3 x_scale = image_aspect * (F32)gViewerWindow->getWindowHeightScaled() * mScale * scale_factor * x_pixel_vec;
LLVector3 y_scale = (F32)gViewerWindow->getWindowHeightScaled() * mScale * scale_factor * y_pixel_vec;
- LLVector3 lower_left = icon_position - (x_scale * 0.5f);
- LLVector3 lower_right = icon_position + (x_scale * 0.5f);
- LLVector3 upper_left = icon_position - (x_scale * 0.5f) + y_scale;
- LLVector3 upper_right = icon_position + (x_scale * 0.5f) + y_scale;
+ LLVector4a x_scalea;
+ LLVector4a icon_positiona;
+ LLVector4a y_scalea;
-
- F32 t = 0.f;
- LLVector3 dir = end-start;
+ x_scalea.load3(x_scale.mV);
+ x_scalea.mul(0.5f);
+ y_scalea.load3(y_scale.mV);
+
+ icon_positiona.load3(icon_position.mV);
+
+ LLVector4a lower_left;
+ lower_left.setSub(icon_positiona, x_scalea);
+ LLVector4a lower_right;
+ lower_right.setAdd(icon_positiona, x_scalea);
+ LLVector4a upper_left;
+ upper_left.setAdd(lower_left, y_scalea);
+ LLVector4a upper_right;
+ upper_right.setAdd(lower_right, y_scalea);
+
+ LLVector4a enda;
+ enda.load3(end.mV);
+ LLVector4a starta;
+ starta.load3(start.mV);
+ LLVector4a dir;
+ dir.setSub(enda, starta);
+
+ F32 a,b,t;
- if (LLTriangleRayIntersect(upper_right, upper_left, lower_right, start, dir, NULL, NULL, &t, FALSE) ||
- LLTriangleRayIntersect(upper_left, lower_left, lower_right, start, dir, NULL, NULL, &t, FALSE))
+ if (LLTriangleRayIntersect(upper_right, upper_left, lower_right, starta, dir, a,b,t) ||
+ LLTriangleRayIntersect(upper_left, lower_left, lower_right, starta, dir, a,b,t))
{
if (intersection)
{
- *intersection = start + dir*t;
+ dir.mul(t);
+ starta.add(dir);
+ *intersection = LLVector3(starta.getF32ptr());
}
return TRUE;
}
diff --git a/indra/newview/llhudnametag.cpp b/indra/newview/llhudnametag.cpp
index fc758569e4..82e1f2dfb5 100644
--- a/indra/newview/llhudnametag.cpp
+++ b/indra/newview/llhudnametag.cpp
@@ -146,24 +146,43 @@ BOOL LLHUDNameTag::lineSegmentIntersect(const LLVector3& start, const LLVector3&
mOffsetY = lltrunc(mHeight * ((mVertAlignment == ALIGN_VERT_CENTER) ? 0.5f : 1.f));
+ LLVector3 position = mPositionAgent;
+
+ if (mSourceObject)
+ { //get intersection of eye through mPositionAgent to plane of source object
+ //using this position keeps the camera from focusing on some seemingly random
+ //point several meters in front of the nametag
+ const LLVector3& p = mSourceObject->getPositionAgent();
+ const LLVector3& n = LLViewerCamera::getInstance()->getAtAxis();
+ const LLVector3& eye = LLViewerCamera::getInstance()->getOrigin();
+
+ LLVector3 ray = position-eye;
+ ray.normalize();
+
+ LLVector3 delta = p-position;
+ F32 dist = delta*n;
+ F32 dt = dist/(ray*n);
+ position += ray*dt;
+ }
+
// scale screen size of borders down
//RN: for now, text on hud objects is never occluded
LLVector3 x_pixel_vec;
LLVector3 y_pixel_vec;
- LLViewerCamera::getInstance()->getPixelVectors(mPositionAgent, y_pixel_vec, x_pixel_vec);
+ LLViewerCamera::getInstance()->getPixelVectors(position, y_pixel_vec, x_pixel_vec);
LLVector3 width_vec = mWidth * x_pixel_vec;
LLVector3 height_vec = mHeight * y_pixel_vec;
LLCoordGL screen_pos;
- LLViewerCamera::getInstance()->projectPosAgentToScreen(mPositionAgent, screen_pos, FALSE);
+ LLViewerCamera::getInstance()->projectPosAgentToScreen(position, screen_pos, FALSE);
LLVector2 screen_offset;
screen_offset = updateScreenPos(mPositionOffset);
- LLVector3 render_position = mPositionAgent
+ LLVector3 render_position = position
+ (x_pixel_vec * screen_offset.mV[VX])
+ (y_pixel_vec * screen_offset.mV[VY]);
@@ -197,10 +216,10 @@ BOOL LLHUDNameTag::lineSegmentIntersect(const LLVector3& start, const LLVector3&
}
LLVector3 dir = end-start;
- F32 t = 0.f;
+ F32 a, b, t;
- if (LLTriangleRayIntersect(v[0], v[1], v[2], start, dir, NULL, NULL, &t, FALSE) ||
- LLTriangleRayIntersect(v[2], v[3], v[0], start, dir, NULL, NULL, &t, FALSE) )
+ if (LLTriangleRayIntersect(v[0], v[1], v[2], start, dir, a, b, t, FALSE) ||
+ LLTriangleRayIntersect(v[2], v[3], v[0], start, dir, a, b, t, FALSE) )
{
if (t <= 1.f)
{
diff --git a/indra/newview/llinventorybridge.cpp b/indra/newview/llinventorybridge.cpp
index 4c2e0fa709..21b1cc77ad 100644
--- a/indra/newview/llinventorybridge.cpp
+++ b/indra/newview/llinventorybridge.cpp
@@ -917,6 +917,14 @@ LLInvFVBridge* LLInvFVBridge::createBridge(LLAssetType::EType asset_type,
// Only should happen for broken links.
new_listener = new LLLinkItemBridge(inventory, root, uuid);
break;
+ case LLAssetType::AT_MESH:
+ if(!(inv_type == LLInventoryType::IT_MESH))
+ {
+ llwarns << LLAssetType::lookup(asset_type) << " asset has inventory type " << LLInventoryType::lookupHumanReadable(inv_type) << " on uuid " << uuid << llendl;
+ }
+ new_listener = new LLMeshBridge(inventory, root, uuid);
+ break;
+
default:
llinfos << "Unhandled asset type (llassetstorage.h): "
<< (S32)asset_type << llendl;
@@ -2266,6 +2274,9 @@ LLUIImagePtr LLFolderBridge::getIcon() const
LLUIImagePtr LLFolderBridge::getIcon(LLFolderType::EType preferred_type)
{
return LLUI::getUIImage(LLViewerFolderType::lookupIconName(preferred_type, FALSE));
+ /*case LLAssetType::AT_MESH:
+ control = "inv_folder_mesh.tga";
+ break;*/
}
LLUIImagePtr LLFolderBridge::getOpenIcon() const
@@ -2725,12 +2736,13 @@ BOOL LLFolderBridge::dragOrDrop(MASK mask, BOOL drop,
case DAD_CALLINGCARD:
case DAD_LANDMARK:
case DAD_SCRIPT:
+ case DAD_CLOTHING:
case DAD_OBJECT:
case DAD_NOTECARD:
- case DAD_CLOTHING:
case DAD_BODYPART:
case DAD_ANIMATION:
case DAD_GESTURE:
+ case DAD_MESH:
accept = dragItemIntoFolder(inv_item, drop);
break;
case DAD_LINK:
@@ -2760,7 +2772,11 @@ BOOL LLFolderBridge::dragOrDrop(MASK mask, BOOL drop,
accept = dragCategoryIntoFolder((LLInventoryCategory*)cargo_data, drop);
}
break;
+ case DAD_ROOT_CATEGORY:
+ case DAD_NONE:
+ break;
default:
+ llwarns << "Unhandled cargo type for drag&drop " << cargo_type << llendl;
break;
}
return accept;
@@ -3752,6 +3768,7 @@ BOOL LLCallingCardBridge::dragOrDrop(MASK mask, BOOL drop,
case DAD_BODYPART:
case DAD_ANIMATION:
case DAD_GESTURE:
+ case DAD_MESH:
{
LLInventoryItem* inv_item = (LLInventoryItem*)cargo_data;
const LLPermissions& perm = inv_item->getPermissions();
@@ -4920,6 +4937,7 @@ void LLWearableBridge::removeFromAvatar()
}
}
+
// +=================================================+
// | LLLinkItemBridge |
// +=================================================+
@@ -4950,6 +4968,63 @@ void LLLinkItemBridge::buildContextMenu(LLMenuGL& menu, U32 flags)
}
// +=================================================+
+// | LLMeshBridge |
+// +=================================================+
+
+LLUIImagePtr LLMeshBridge::getIcon() const
+{
+ return LLInventoryIcon::getIcon(LLAssetType::AT_MESH, LLInventoryType::IT_MESH, 0, FALSE);
+}
+
+void LLMeshBridge::openItem()
+{
+ LLViewerInventoryItem* item = getItem();
+
+ if (item)
+ {
+ // open mesh
+ }
+}
+
+void LLMeshBridge::previewItem()
+{
+ LLViewerInventoryItem* item = getItem();
+ if(item)
+ {
+ // preview mesh
+ }
+}
+
+
+void LLMeshBridge::buildContextMenu(LLMenuGL& menu, U32 flags)
+{
+ lldebugs << "LLMeshBridge::buildContextMenu()" << llendl;
+ std::vector<std::string> items;
+ std::vector<std::string> disabled_items;
+
+ if(isItemInTrash())
+ {
+ items.push_back(std::string("Purge Item"));
+ if (!isItemRemovable())
+ {
+ disabled_items.push_back(std::string("Purge Item"));
+ }
+
+ items.push_back(std::string("Restore Item"));
+ }
+ else
+ {
+ items.push_back(std::string("Properties"));
+
+ getClipboardEntries(true, items, disabled_items, flags);
+ }
+
+
+ hide_context_entries(menu, items, disabled_items);
+}
+
+
+// +=================================================+
// | LLLinkBridge |
// +=================================================+
// For broken folder links.
@@ -5255,6 +5330,7 @@ public:
{
wearOnAvatar();
}
+
virtual ~LLWearableBridgeAction(){}
protected:
LLWearableBridgeAction(const LLUUID& id,LLInventoryModel* model) : LLInvFVBridgeAction(id,model) {}
diff --git a/indra/newview/llinventorybridge.h b/indra/newview/llinventorybridge.h
index 5ac328dcef..1e849c8812 100644
--- a/indra/newview/llinventorybridge.h
+++ b/indra/newview/llinventorybridge.h
@@ -41,6 +41,7 @@ class LLMenuGL;
class LLCallingCardObserver;
class LLViewerJointAttachment;
+
typedef std::vector<std::string> menuentry_vec_t;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -523,6 +524,24 @@ protected:
static std::string sPrefix;
};
+
+class LLMeshBridge : public LLItemBridge
+{
+ friend class LLInvFVBridge;
+public:
+ virtual LLUIImagePtr getIcon() const;
+ virtual void openItem();
+ virtual void previewItem();
+ virtual void buildContextMenu(LLMenuGL& menu, U32 flags);
+
+protected:
+ LLMeshBridge(LLInventoryPanel* inventory,
+ LLFolderView* root,
+ const LLUUID& uuid) :
+ LLItemBridge(inventory, root, uuid) {}
+};
+
+
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Class LLInvFVBridgeAction
//
@@ -553,13 +572,23 @@ protected:
LLInventoryModel* mModel;
};
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Recent Inventory Panel related classes
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+class LLMeshBridgeAction: public LLInvFVBridgeAction
+{
+ friend class LLInvFVBridgeAction;
+public:
+ virtual void doIt() ;
+ virtual ~LLMeshBridgeAction(){}
+protected:
+ LLMeshBridgeAction(const LLUUID& id,LLInventoryModel* model):LLInvFVBridgeAction(id,model){}
+
+};
+
+
// Overridden version of the Inventory-Folder-View-Bridge for Folders
class LLRecentItemsFolderBridge : public LLFolderBridge
{
+ friend class LLInvFVBridgeAction;
public:
// Creates context menu for Folders related to Recent Inventory Panel.
// Uses base logic and than removes from visible items "New..." menu items.
diff --git a/indra/newview/llinventoryfunctions.cpp b/indra/newview/llinventoryfunctions.cpp
index ba9bea02b9..db3b968730 100644
--- a/indra/newview/llinventoryfunctions.cpp
+++ b/indra/newview/llinventoryfunctions.cpp
@@ -853,3 +853,4 @@ void LLOpenFoldersWithSelection::doFolder(LLFolderViewFolder* folder)
folder->getParentFolder()->setOpenArrangeRecursively(TRUE, LLFolderViewFolder::RECURSE_UP);
}
}
+
diff --git a/indra/newview/llinventoryicon.cpp b/indra/newview/llinventoryicon.cpp
index 3f4f33e88d..cf17647db9 100644
--- a/indra/newview/llinventoryicon.cpp
+++ b/indra/newview/llinventoryicon.cpp
@@ -84,6 +84,7 @@ LLIconDictionary::LLIconDictionary()
addEntry(LLInventoryIcon::ICONNAME_LINKITEM, new IconEntry("Inv_LinkItem"));
addEntry(LLInventoryIcon::ICONNAME_LINKFOLDER, new IconEntry("Inv_LinkFolder"));
+ addEntry(LLInventoryIcon::ICONNAME_MESH, new IconEntry("Inv_Mesh"));
addEntry(LLInventoryIcon::ICONNAME_INVALID, new IconEntry("Inv_Invalid"));
@@ -157,6 +158,8 @@ const std::string& LLInventoryIcon::getIconName(LLAssetType::EType asset_type,
case LLAssetType::AT_OBJECT:
idx = ICONNAME_OBJECT;
break;
+ case LLAssetType::AT_MESH:
+ idx = ICONNAME_MESH;
default:
break;
}
diff --git a/indra/newview/llinventoryicon.h b/indra/newview/llinventoryicon.h
index 9a2cc08095..521d973ce0 100644
--- a/indra/newview/llinventoryicon.h
+++ b/indra/newview/llinventoryicon.h
@@ -72,6 +72,7 @@ public:
ICONNAME_LINKITEM,
ICONNAME_LINKFOLDER,
+ ICONNAME_MESH,
ICONNAME_INVALID,
ICONNAME_COUNT,
diff --git a/indra/newview/llinventoryitemslist.h b/indra/newview/llinventoryitemslist.h
index 86e11dff17..b183a2052d 100644
--- a/indra/newview/llinventoryitemslist.h
+++ b/indra/newview/llinventoryitemslist.h
@@ -38,7 +38,6 @@ class LLViewerInventoryItem;
class LLInventoryItemsList : public LLFlatListViewEx
{
- LOG_CLASS(LLInventoryItemsList);
public:
struct Params : public LLInitParam::Block<Params, LLFlatListViewEx::Params>
{
diff --git a/indra/newview/llmanipscale.cpp b/indra/newview/llmanipscale.cpp
index 060677f9f3..dcbf17e31f 100644
--- a/indra/newview/llmanipscale.cpp
+++ b/indra/newview/llmanipscale.cpp
@@ -52,6 +52,7 @@
#include "llui.h"
#include "llviewercamera.h"
#include "llviewerobject.h"
+#include "llviewerregion.h"
#include "llviewerwindow.h"
#include "llhudrender.h"
#include "llworld.h"
@@ -85,6 +86,22 @@ const LLManip::EManipPart MANIPULATOR_IDS[NUM_MANIPULATORS] =
};
+F32 get_default_max_prim_scale(bool is_flora)
+{
+ // a bit of a hack, but if it's foilage, we don't want to use the
+ // new larger scale which would result in giant trees and grass
+ if (gSavedSettings.getBOOL("MeshEnabled") &&
+ gAgent.getRegion() &&
+ !gAgent.getRegion()->getCapability("GetMesh").empty() &&
+ !is_flora)
+ {
+ return DEFAULT_MAX_PRIM_SCALE;
+ }
+ else
+ {
+ return DEFAULT_MAX_PRIM_SCALE_NO_MESH;
+ }
+}
// static
void LLManipScale::setUniform(BOOL b)
@@ -950,8 +967,8 @@ void LLManipScale::dragCorner( S32 x, S32 y )
mInSnapRegime = FALSE;
}
- F32 max_scale_factor = DEFAULT_MAX_PRIM_SCALE / MIN_PRIM_SCALE;
- F32 min_scale_factor = MIN_PRIM_SCALE / DEFAULT_MAX_PRIM_SCALE;
+ F32 max_scale_factor = get_default_max_prim_scale() / MIN_PRIM_SCALE;
+ F32 min_scale_factor = MIN_PRIM_SCALE / get_default_max_prim_scale();
// find max and min scale factors that will make biggest object hit max absolute scale and smallest object hit min absolute scale
for (LLObjectSelection::iterator iter = mObjectSelection->begin();
@@ -963,7 +980,7 @@ void LLManipScale::dragCorner( S32 x, S32 y )
{
const LLVector3& scale = selectNode->mSavedScale;
- F32 cur_max_scale_factor = llmin( DEFAULT_MAX_PRIM_SCALE / scale.mV[VX], DEFAULT_MAX_PRIM_SCALE / scale.mV[VY], DEFAULT_MAX_PRIM_SCALE / scale.mV[VZ] );
+ F32 cur_max_scale_factor = llmin( get_default_max_prim_scale(LLPickInfo::isFlora(cur)) / scale.mV[VX], get_default_max_prim_scale(LLPickInfo::isFlora(cur)) / scale.mV[VY], get_default_max_prim_scale(LLPickInfo::isFlora(cur)) / scale.mV[VZ] );
max_scale_factor = llmin( max_scale_factor, cur_max_scale_factor );
F32 cur_min_scale_factor = llmax( MIN_PRIM_SCALE / scale.mV[VX], MIN_PRIM_SCALE / scale.mV[VY], MIN_PRIM_SCALE / scale.mV[VZ] );
@@ -1260,7 +1277,7 @@ void LLManipScale::stretchFace( const LLVector3& drag_start_agent, const LLVecto
F32 denom = axis * dir_local;
F32 desired_delta_size = is_approx_zero(denom) ? 0.f : (delta_local_mag / denom); // in meters
- F32 desired_scale = llclamp(selectNode->mSavedScale.mV[axis_index] + desired_delta_size, MIN_PRIM_SCALE, DEFAULT_MAX_PRIM_SCALE);
+ F32 desired_scale = llclamp(selectNode->mSavedScale.mV[axis_index] + desired_delta_size, MIN_PRIM_SCALE, get_default_max_prim_scale(LLPickInfo::isFlora(cur)));
// propagate scale constraint back to position offset
desired_delta_size = desired_scale - selectNode->mSavedScale.mV[axis_index]; // propagate constraint back to position
@@ -1960,7 +1977,7 @@ F32 LLManipScale::partToMaxScale( S32 part, const LLBBox &bbox ) const
max_extent = bbox_extents.mV[i];
}
}
- max_scale_factor = bbox_extents.magVec() * DEFAULT_MAX_PRIM_SCALE / max_extent;
+ max_scale_factor = bbox_extents.magVec() * get_default_max_prim_scale() / max_extent;
if (getUniform())
{
@@ -1975,7 +1992,7 @@ F32 LLManipScale::partToMinScale( S32 part, const LLBBox &bbox ) const
{
LLVector3 bbox_extents = unitVectorToLocalBBoxExtent( partToUnitVector( part ), bbox );
bbox_extents.abs();
- F32 min_extent = DEFAULT_MAX_PRIM_SCALE;
+ F32 min_extent = get_default_max_prim_scale();
for (U32 i = VX; i <= VZ; i++)
{
if (bbox_extents.mV[i] > 0.f && bbox_extents.mV[i] < min_extent)
diff --git a/indra/newview/llmanipscale.h b/indra/newview/llmanipscale.h
index 5559f557c0..5cb8898fd0 100644
--- a/indra/newview/llmanipscale.h
+++ b/indra/newview/llmanipscale.h
@@ -39,6 +39,9 @@
#include "llviewerobject.h"
#include "llbbox.h"
+
+F32 get_default_max_prim_scale(bool is_flora = false);
+
class LLToolComposite;
class LLColor4;
diff --git a/indra/newview/llmeshreduction.cpp b/indra/newview/llmeshreduction.cpp
new file mode 100644
index 0000000000..14e8dd37b4
--- /dev/null
+++ b/indra/newview/llmeshreduction.cpp
@@ -0,0 +1,272 @@
+/**
+ * @file llmeshreduction.cpp
+ * @brief LLMeshReduction class implementation
+ *
+ * $LicenseInfo:firstyear=2004&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h"
+
+#include "llmeshreduction.h"
+#include "llgl.h"
+#include "llvertexbuffer.h"
+
+#include "glod/glod.h"
+
+
+#if 0 //not used ?
+
+void create_vertex_buffers_from_model(LLModel* model, std::vector<LLPointer <LLVertexBuffer> >& vertex_buffers)
+{
+#if 0 //VECTORIZE THIS ?
+ vertex_buffers.clear();
+
+ for (S32 i = 0; i < model->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace &vf = model->getVolumeFace(i);
+ U32 num_vertices = vf.mNumVertices;
+ U32 num_indices = vf.mNumIndices;
+
+ if (!num_vertices || ! num_indices)
+ {
+ continue;
+ }
+
+ LLVertexBuffer* vb =
+ new LLVertexBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_TEXCOORD0, 0);
+
+ vb->allocateBuffer(num_vertices, num_indices, TRUE);
+
+ LLStrider<LLVector3> vertex_strider;
+ LLStrider<LLVector3> normal_strider;
+ LLStrider<LLVector2> tc_strider;
+ LLStrider<U16> index_strider;
+
+ vb->getVertexStrider(vertex_strider);
+ vb->getNormalStrider(normal_strider);
+ vb->getTexCoord0Strider(tc_strider);
+
+ vb->getIndexStrider(index_strider);
+
+ // build vertices and normals
+ for (U32 i = 0; (S32)i < num_vertices; i++)
+ {
+ *(vertex_strider++) = vf.mVertices[i].mPosition;
+ *(tc_strider++) = vf.mVertices[i].mTexCoord;
+ LLVector3 normal = vf.mVertices[i].mNormal;
+ normal.normalize();
+ *(normal_strider++) = normal;
+ }
+
+ // build indices
+ for (U32 i = 0; i < num_indices; i++)
+ {
+ *(index_strider++) = vf.mIndices[i];
+ }
+
+
+ vertex_buffers.push_back(vb);
+ }
+#endif
+}
+
+void create_glod_object_from_vertex_buffers(S32 object, S32 group, std::vector<LLPointer <LLVertexBuffer> >& vertex_buffers)
+{
+ glodNewGroup(group);
+ stop_gloderror();
+ glodNewObject(object, group, GLOD_DISCRETE);
+ stop_gloderror();
+
+ for (U32 i = 0; i < vertex_buffers.size(); ++i)
+ {
+ vertex_buffers[i]->setBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_TEXCOORD0);
+
+ U32 num_indices = vertex_buffers[i]->getNumIndices();
+
+ if (num_indices > 2)
+ {
+ glodInsertElements(object, i, GL_TRIANGLES, num_indices, GL_UNSIGNED_SHORT,
+ vertex_buffers[i]->getIndicesPointer(), 0, 0.f);
+ }
+ stop_gloderror();
+ }
+
+ glodBuildObject(object);
+ stop_gloderror();
+}
+
+// extract the GLOD data into vertex buffers
+void create_vertex_buffers_from_glod_object(S32 object, S32 group, std::vector<LLPointer <LLVertexBuffer> >& vertex_buffers)
+{
+ vertex_buffers.clear();
+
+ GLint patch_count = 0;
+ glodGetObjectParameteriv(object, GLOD_NUM_PATCHES, &patch_count);
+ stop_gloderror();
+
+ GLint* sizes = new GLint[patch_count*2];
+ glodGetObjectParameteriv(object, GLOD_PATCH_SIZES, sizes);
+ stop_gloderror();
+
+ GLint* names = new GLint[patch_count];
+ glodGetObjectParameteriv(object, GLOD_PATCH_NAMES, names);
+ stop_gloderror();
+
+ for (S32 i = 0; i < patch_count; i++)
+ {
+ LLPointer<LLVertexBuffer> buff =
+ new LLVertexBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_TEXCOORD0, 0);
+
+ if (sizes[i*2+1] > 0 && sizes[i*2] > 0)
+ {
+ buff->allocateBuffer(sizes[i*2+1], sizes[i*2], true);
+ buff->setBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_TEXCOORD0);
+ glodFillElements(object, names[i], GL_UNSIGNED_SHORT, buff->getIndicesPointer());
+ stop_gloderror();
+ }
+ else
+ {
+ // this face was eliminated, create a dummy triangle (one vertex, 3 indices, all 0)
+ buff->allocateBuffer(1, 3, true);
+ }
+
+ vertex_buffers.push_back(buff);
+ }
+
+ glodDeleteObject(object);
+ stop_gloderror();
+ glodDeleteGroup(group);
+ stop_gloderror();
+
+ delete [] sizes;
+ delete [] names;
+}
+
+
+LLPointer<LLModel> create_model_from_vertex_buffers(std::vector<LLPointer <LLVertexBuffer> >& vertex_buffers)
+{
+ // extract the newly reduced mesh
+
+ // create our output model
+ LLVolumeParams volume_params;
+ volume_params.setType(LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE);
+ LLPointer<LLModel> out_model = new LLModel(volume_params, 0.f);
+
+ out_model->setNumVolumeFaces(vertex_buffers.size());
+
+ // build new faces from each vertex buffer
+ for (GLint i = 0; i < vertex_buffers.size(); ++i)
+ {
+ LLStrider<LLVector3> pos;
+ LLStrider<LLVector3> norm;
+ LLStrider<LLVector2> tc;
+ LLStrider<U16> index;
+
+ vertex_buffers[i]->getVertexStrider(pos);
+ vertex_buffers[i]->getNormalStrider(norm);
+ vertex_buffers[i]->getTexCoord0Strider(tc);
+ vertex_buffers[i]->getIndexStrider(index);
+
+ out_model->setVolumeFaceData(i, pos, norm, tc, index,
+ vertex_buffers[i]->getNumVerts(), vertex_buffers[i]->getNumIndices());
+ }
+
+ return out_model;
+}
+
+
+
+LLMeshReduction::LLMeshReduction()
+{
+ mCounter = 1;
+
+ glodInit();
+}
+
+LLMeshReduction::~LLMeshReduction()
+{
+ glodShutdown();
+}
+
+
+LLPointer<LLModel> LLMeshReduction::reduce(LLModel* in_model, F32 limit, S32 mode)
+{
+ LLVertexBuffer::unbind();
+
+ // create vertex buffers from model
+ std::vector<LLPointer<LLVertexBuffer> > in_vertex_buffers;
+ create_vertex_buffers_from_model(in_model, in_vertex_buffers);
+
+ // create glod object from vertex buffers
+ stop_gloderror();
+ S32 glod_group = mCounter++;
+ S32 glod_object = mCounter++;
+ create_glod_object_from_vertex_buffers(glod_object, glod_group, in_vertex_buffers);
+
+
+ // set reduction parameters
+ stop_gloderror();
+
+ if (mode == TRIANGLE_BUDGET)
+ {
+ // triangle budget mode
+ glodGroupParameteri(glod_group, GLOD_ADAPT_MODE, GLOD_TRIANGLE_BUDGET);
+ stop_gloderror();
+ glodGroupParameteri(glod_group, GLOD_ERROR_MODE, GLOD_OBJECT_SPACE_ERROR);
+ stop_gloderror();
+ S32 triangle_count = (S32)limit;
+ glodGroupParameteri(glod_group, GLOD_MAX_TRIANGLES, triangle_count);
+ stop_gloderror();
+ }
+ else if (mode == ERROR_THRESHOLD)
+ {
+ // error threshold mode
+ glodGroupParameteri(glod_group, GLOD_ADAPT_MODE, GLOD_ERROR_THRESHOLD);
+ glodGroupParameteri(glod_group, GLOD_ERROR_MODE, GLOD_OBJECT_SPACE_ERROR);
+ F32 error_threshold = limit;
+ glodGroupParameterf(glod_group, GLOD_OBJECT_SPACE_ERROR_THRESHOLD, error_threshold);
+ stop_gloderror();
+ }
+
+ else
+ {
+ // not a legal mode
+ return NULL;
+ }
+
+
+ // do the reduction
+ glodAdaptGroup(glod_group);
+ stop_gloderror();
+
+ // convert glod object into vertex buffers
+ std::vector<LLPointer<LLVertexBuffer> > out_vertex_buffers;
+ create_vertex_buffers_from_glod_object(glod_object, glod_group, out_vertex_buffers);
+
+ // convert vertex buffers into a model
+ LLPointer<LLModel> out_model = create_model_from_vertex_buffers(out_vertex_buffers);
+
+
+ return out_model;
+}
+
+#endif
diff --git a/indra/newview/llmeshreduction.h b/indra/newview/llmeshreduction.h
new file mode 100644
index 0000000000..b518f6a650
--- /dev/null
+++ b/indra/newview/llmeshreduction.h
@@ -0,0 +1,50 @@
+/**
+ * @file llmeshreduction.h
+ * @brief LLMeshReduction class definition
+ *
+ * $LicenseInfo:firstyear=2004&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#ifndef LL_LLMESHREDUCTION_H
+#define LL_LLMESHREDUCTION_H
+
+#include "llmodel.h"
+
+class LLMeshReduction
+{
+ public:
+ enum EReductionMode
+ {
+ TRIANGLE_BUDGET,
+ ERROR_THRESHOLD
+ };
+
+ LLMeshReduction();
+ ~LLMeshReduction();
+
+ LLPointer<LLModel> reduce(LLModel* in_model, F32 limit, S32 mode);
+
+private:
+ U32 mCounter;
+};
+
+#endif // LL_LLMESHREDUCTION_H
diff --git a/indra/newview/llmeshrepository.cpp b/indra/newview/llmeshrepository.cpp
new file mode 100755
index 0000000000..93e773d33b
--- /dev/null
+++ b/indra/newview/llmeshrepository.cpp
@@ -0,0 +1,3586 @@
+/**
+ * @file llmeshrepository.cpp
+ * @brief Mesh repository implementation.
+ *
+ * $LicenseInfo:firstyear=2005&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h"
+
+#include "apr_pools.h"
+#include "apr_dso.h"
+
+#include "llmeshrepository.h"
+
+#include "llagent.h"
+#include "llappviewer.h"
+#include "llbufferstream.h"
+#include "llcurl.h"
+#include "llfasttimer.h"
+#include "llfloatermodelpreview.h"
+#include "llfloaterperms.h"
+#include "lleconomy.h"
+#include "llimagej2c.h"
+#include "llhost.h"
+#include "llnotificationsutil.h"
+#include "llsd.h"
+#include "llsdutil_math.h"
+#include "llsdserialize.h"
+#include "llthread.h"
+#include "llvfile.h"
+#include "llviewercontrol.h"
+#include "llviewermenufile.h"
+#include "llviewerobjectlist.h"
+#include "llviewerregion.h"
+#include "llviewertexturelist.h"
+#include "llvolume.h"
+#include "llvolumemgr.h"
+#include "llvovolume.h"
+#include "llworld.h"
+#include "material_codes.h"
+#include "pipeline.h"
+
+#ifndef LL_WINDOWS
+#include "netdb.h"
+#endif
+
+#include <queue>
+
+LLFastTimer::DeclareTimer FTM_MESH_UPDATE("Mesh Update");
+LLFastTimer::DeclareTimer FTM_LOAD_MESH("Load Mesh");
+
+LLMeshRepository gMeshRepo;
+
+const U32 MAX_MESH_REQUESTS_PER_SECOND = 100;
+
+U32 LLMeshRepository::sBytesReceived = 0;
+U32 LLMeshRepository::sHTTPRequestCount = 0;
+U32 LLMeshRepository::sHTTPRetryCount = 0;
+U32 LLMeshRepository::sCacheBytesRead = 0;
+U32 LLMeshRepository::sCacheBytesWritten = 0;
+U32 LLMeshRepository::sPeakKbps = 0;
+
+
+const U32 MAX_TEXTURE_UPLOAD_RETRIES = 5;
+
+std::string header_lod[] =
+{
+ "lowest_lod",
+ "low_lod",
+ "medium_lod",
+ "high_lod"
+};
+
+
+//get the number of bytes resident in memory for given volume
+U32 get_volume_memory_size(const LLVolume* volume)
+{
+ U32 indices = 0;
+ U32 vertices = 0;
+
+ for (U32 i = 0; i < volume->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = volume->getVolumeFace(i);
+ indices += face.mNumIndices;
+ vertices += face.mNumVertices;
+ }
+
+
+ return indices*2+vertices*11+sizeof(LLVolume)+sizeof(LLVolumeFace)*volume->getNumVolumeFaces();
+}
+
+LLVertexBuffer* get_vertex_buffer_from_mesh(LLCDMeshData& mesh, F32 scale = 1.f)
+{
+ LLVertexBuffer* buff = new LLVertexBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL, 0);
+ buff->allocateBuffer(mesh.mNumTriangles*3, 0, true);
+
+ LLStrider<LLVector3> pos;
+ LLStrider<LLVector3> norm;
+
+ buff->getVertexStrider(pos);
+ buff->getNormalStrider(norm);
+
+ const F32* v = mesh.mVertexBase;
+
+ if (mesh.mIndexType == LLCDMeshData::INT_16)
+ {
+ U16* idx = (U16*) mesh.mIndexBase;
+ for (S32 j = 0; j < mesh.mNumTriangles; ++j)
+ {
+ F32* mp0 = (F32*) ((U8*)v+idx[0]*mesh.mVertexStrideBytes);
+ F32* mp1 = (F32*) ((U8*)v+idx[1]*mesh.mVertexStrideBytes);
+ F32* mp2 = (F32*) ((U8*)v+idx[2]*mesh.mVertexStrideBytes);
+
+ idx = (U16*) (((U8*)idx)+mesh.mIndexStrideBytes);
+
+ LLVector3 v0(mp0);
+ LLVector3 v1(mp1);
+ LLVector3 v2(mp2);
+
+ LLVector3 n = (v1-v0)%(v2-v0);
+ n.normalize();
+
+ *pos++ = v0*scale;
+ *pos++ = v1*scale;
+ *pos++ = v2*scale;
+
+ *norm++ = n;
+ *norm++ = n;
+ *norm++ = n;
+ }
+ }
+ else
+ {
+ U32* idx = (U32*) mesh.mIndexBase;
+ for (S32 j = 0; j < mesh.mNumTriangles; ++j)
+ {
+ F32* mp0 = (F32*) ((U8*)v+idx[0]*mesh.mVertexStrideBytes);
+ F32* mp1 = (F32*) ((U8*)v+idx[1]*mesh.mVertexStrideBytes);
+ F32* mp2 = (F32*) ((U8*)v+idx[2]*mesh.mVertexStrideBytes);
+
+ idx = (U32*) (((U8*)idx)+mesh.mIndexStrideBytes);
+
+ LLVector3 v0(mp0);
+ LLVector3 v1(mp1);
+ LLVector3 v2(mp2);
+
+ LLVector3 n = (v1-v0)%(v2-v0);
+ n.normalize();
+
+ *(pos++) = v0*scale;
+ *(pos++) = v1*scale;
+ *(pos++) = v2*scale;
+
+ *(norm++) = n;
+ *(norm++) = n;
+ *(norm++) = n;
+ }
+ }
+
+ return buff;
+}
+
+S32 LLMeshRepoThread::sActiveHeaderRequests = 0;
+S32 LLMeshRepoThread::sActiveLODRequests = 0;
+U32 LLMeshRepoThread::sMaxConcurrentRequests = 1;
+
+
+class LLTextureCostResponder : public LLCurl::Responder
+{
+public:
+ LLTextureUploadData mData;
+ LLMeshUploadThread* mThread;
+
+ LLTextureCostResponder(LLTextureUploadData data, LLMeshUploadThread* thread)
+ : mData(data), mThread(thread)
+ {
+
+ }
+
+ virtual void completed(U32 status, const std::string& reason, const LLSD& content)
+ {
+ mThread->mPendingConfirmations--;
+ if (isGoodStatus(status))
+ {
+ mThread->priceResult(mData, content);
+ }
+ else
+ {
+ llwarns << status << ": " << reason << llendl;
+
+ if (mData.mRetries < MAX_TEXTURE_UPLOAD_RETRIES)
+ {
+ llwarns << "Retrying. (" << ++mData.mRetries << ")" << llendl;
+
+ if (status == 499 || status == 500)
+ {
+ mThread->uploadTexture(mData);
+ }
+ else
+ {
+ llerrs << "Unhandled status " << status << llendl;
+ }
+ }
+ else
+ {
+ llwarns << "Giving up after " << mData.mRetries << " retries." << llendl;
+ }
+ }
+ }
+};
+
+class LLTextureUploadResponder : public LLCurl::Responder
+{
+public:
+ LLTextureUploadData mData;
+ LLMeshUploadThread* mThread;
+
+ LLTextureUploadResponder(LLTextureUploadData data, LLMeshUploadThread* thread)
+ : mData(data), mThread(thread)
+ {
+ }
+
+ virtual void completed(U32 status, const std::string& reason, const LLSD& content)
+ {
+ mThread->mPendingUploads--;
+ if (isGoodStatus(status))
+ {
+ mData.mUUID = content["new_asset"].asUUID();
+ gMeshRepo.updateInventory(LLMeshRepository::inventory_data(mData.mPostData, content));
+ mThread->onTextureUploaded(mData);
+ }
+ else
+ {
+ llwarns << status << ": " << reason << llendl;
+ llwarns << "Retrying. (" << ++mData.mRetries << ")" << llendl;
+
+ if (status == 404)
+ {
+ mThread->uploadTexture(mData);
+ }
+ else if (status == 499)
+ {
+ mThread->mConfirmedTextureQ.push(mData);
+ }
+ else
+ {
+ llerrs << "Unhandled status " << status << llendl;
+ }
+ }
+ }
+};
+
+class LLMeshCostResponder : public LLCurl::Responder
+{
+public:
+ LLMeshUploadData mData;
+ LLMeshUploadThread* mThread;
+
+ LLMeshCostResponder(LLMeshUploadData data, LLMeshUploadThread* thread)
+ : mData(data), mThread(thread)
+ {
+
+ }
+
+ virtual void completed(U32 status, const std::string& reason, const LLSD& content)
+ {
+ mThread->mPendingConfirmations--;
+
+ if (isGoodStatus(status))
+ {
+ mThread->priceResult(mData, content);
+ }
+ else
+ {
+ llwarns << status << ": " << reason << llendl;
+ llwarns << "Retrying. (" << ++mData.mRetries << ")" << llendl;
+
+ if (status == 499)
+ {
+ mThread->uploadModel(mData);
+ }
+ else if (status == 400)
+ {
+ llwarns << "Status 400 received from server, giving up." << llendl;
+ }
+ else
+ {
+ llerrs << "Unhandled status " << status << llendl;
+ }
+ }
+ }
+};
+
+class LLMeshUploadResponder : public LLCurl::Responder
+{
+public:
+ LLMeshUploadData mData;
+ LLMeshUploadThread* mThread;
+
+ LLMeshUploadResponder(LLMeshUploadData data, LLMeshUploadThread* thread)
+ : mData(data), mThread(thread)
+ {
+ }
+
+ virtual void completed(U32 status, const std::string& reason, const LLSD& content)
+ {
+ mThread->mPendingUploads--;
+ if (isGoodStatus(status))
+ {
+ mData.mUUID = content["new_asset"].asUUID();
+ if (mData.mUUID.isNull())
+ {
+ LLSD args;
+ std::string message = content["error"]["message"];
+ std::string identifier = content["error"]["identifier"];
+ std::string invalidity_identifier = content["error"]["invalidity_identifier"];
+
+ args["MESSAGE"] = message;
+ args["IDENTIFIER"] = identifier;
+ args["INVALIDITY_IDENTIFIER"] = invalidity_identifier;
+ args["LABEL"] = mData.mBaseModel->mLabel;
+
+ gMeshRepo.uploadError(args);
+ }
+ else
+ {
+ gMeshRepo.updateInventory(LLMeshRepository::inventory_data(mData.mPostData, content));
+ mThread->onModelUploaded(mData);
+ }
+ }
+ else
+ {
+ llwarns << status << ": " << reason << llendl;
+ llwarns << "Retrying. (" << ++mData.mRetries << ")" << llendl;
+
+ if (status == 404)
+ {
+ mThread->uploadModel(mData);
+ }
+ else if (status == 499)
+ {
+ mThread->mConfirmedQ.push(mData);
+ }
+ else if (status != 500)
+ { //drop internal server errors on the floor, otherwise grab
+ llerrs << "Unhandled status " << status << llendl;
+ }
+ }
+ }
+};
+
+
+class LLMeshHeaderResponder : public LLCurl::Responder
+{
+public:
+ LLVolumeParams mMeshParams;
+
+ LLMeshHeaderResponder(const LLVolumeParams& mesh_params)
+ : mMeshParams(mesh_params)
+ {
+ }
+
+ virtual void completedRaw(U32 status, const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer);
+
+};
+
+class LLMeshLODResponder : public LLCurl::Responder
+{
+public:
+ LLVolumeParams mMeshParams;
+ S32 mLOD;
+ U32 mRequestedBytes;
+ U32 mOffset;
+
+ LLMeshLODResponder(const LLVolumeParams& mesh_params, S32 lod, U32 offset, U32 requested_bytes)
+ : mMeshParams(mesh_params), mLOD(lod), mOffset(offset), mRequestedBytes(requested_bytes)
+ {
+ }
+
+ virtual void completedRaw(U32 status, const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer);
+
+};
+
+class LLMeshSkinInfoResponder : public LLCurl::Responder
+{
+public:
+ LLUUID mMeshID;
+ U32 mRequestedBytes;
+ U32 mOffset;
+
+ LLMeshSkinInfoResponder(const LLUUID& id, U32 offset, U32 size)
+ : mMeshID(id), mRequestedBytes(size), mOffset(offset)
+ {
+ }
+
+ virtual void completedRaw(U32 status, const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer);
+
+};
+
+class LLMeshDecompositionResponder : public LLCurl::Responder
+{
+public:
+ LLUUID mMeshID;
+ U32 mRequestedBytes;
+ U32 mOffset;
+
+ LLMeshDecompositionResponder(const LLUUID& id, U32 offset, U32 size)
+ : mMeshID(id), mRequestedBytes(size), mOffset(offset)
+ {
+ }
+
+ virtual void completedRaw(U32 status, const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer);
+
+};
+
+class LLMeshPhysicsShapeResponder : public LLCurl::Responder
+{
+public:
+ LLUUID mMeshID;
+ U32 mRequestedBytes;
+ U32 mOffset;
+
+ LLMeshPhysicsShapeResponder(const LLUUID& id, U32 offset, U32 size)
+ : mMeshID(id), mRequestedBytes(size), mOffset(offset)
+ {
+ }
+
+ virtual void completedRaw(U32 status, const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer);
+
+};
+
+
+LLMeshRepoThread::LLMeshRepoThread()
+: LLThread("mesh repo", NULL)
+{
+ mWaiting = false;
+ mMutex = new LLMutex(NULL);
+ mHeaderMutex = new LLMutex(NULL);
+ mSignal = new LLCondition(NULL);
+}
+
+LLMeshRepoThread::~LLMeshRepoThread()
+{
+ delete mMutex;
+ mMutex = NULL;
+ delete mHeaderMutex;
+ mHeaderMutex = NULL;
+ delete mSignal;
+ mSignal = NULL;
+}
+
+void LLMeshRepoThread::run()
+{
+ mCurlRequest = new LLCurlRequest();
+ LLCDResult res = LLConvexDecomposition::initThread();
+ if (res != LLCD_OK)
+ {
+ llwarns << "convex decomposition unable to be loaded" << llendl;
+ }
+
+ while (!LLApp::isQuitting())
+ {
+ mWaiting = true;
+ mSignal->wait();
+ mWaiting = false;
+
+ if (!LLApp::isQuitting())
+ {
+ static U32 count = 0;
+
+ static F32 last_hundred = gFrameTimeSeconds;
+
+ if (gFrameTimeSeconds - last_hundred > 1.f)
+ { //a second has gone by, clear count
+ last_hundred = gFrameTimeSeconds;
+ count = 0;
+ }
+
+ // NOTE: throttling intentionally favors LOD requests over header requests
+
+ while (!mLODReqQ.empty() && count < MAX_MESH_REQUESTS_PER_SECOND && sActiveLODRequests < sMaxConcurrentRequests)
+ {
+ {
+ mMutex->lock();
+ LODRequest req = mLODReqQ.front();
+ mLODReqQ.pop();
+ mMutex->unlock();
+ if (fetchMeshLOD(req.mMeshParams, req.mLOD))
+ {
+ count++;
+ }
+ }
+ }
+
+ while (!mHeaderReqQ.empty() && count < MAX_MESH_REQUESTS_PER_SECOND && sActiveHeaderRequests < sMaxConcurrentRequests)
+ {
+ {
+ mMutex->lock();
+ HeaderRequest req = mHeaderReqQ.front();
+ mHeaderReqQ.pop();
+ mMutex->unlock();
+ if (fetchMeshHeader(req.mMeshParams))
+ {
+ count++;
+ }
+ }
+ }
+
+ { //mSkinRequests is protected by mSignal
+ std::set<LLUUID> incomplete;
+ for (std::set<LLUUID>::iterator iter = mSkinRequests.begin(); iter != mSkinRequests.end(); ++iter)
+ {
+ LLUUID mesh_id = *iter;
+ if (!fetchMeshSkinInfo(mesh_id))
+ {
+ incomplete.insert(mesh_id);
+ }
+ }
+ mSkinRequests = incomplete;
+ }
+
+ { //mDecompositionRequests is protected by mSignal
+ std::set<LLUUID> incomplete;
+ for (std::set<LLUUID>::iterator iter = mDecompositionRequests.begin(); iter != mDecompositionRequests.end(); ++iter)
+ {
+ LLUUID mesh_id = *iter;
+ if (!fetchMeshDecomposition(mesh_id))
+ {
+ incomplete.insert(mesh_id);
+ }
+ }
+ mDecompositionRequests = incomplete;
+ }
+
+ { //mPhysicsShapeRequests is protected by mSignal
+ std::set<LLUUID> incomplete;
+ for (std::set<LLUUID>::iterator iter = mPhysicsShapeRequests.begin(); iter != mPhysicsShapeRequests.end(); ++iter)
+ {
+ LLUUID mesh_id = *iter;
+ if (!fetchMeshPhysicsShape(mesh_id))
+ {
+ incomplete.insert(mesh_id);
+ }
+ }
+ mPhysicsShapeRequests = incomplete;
+ }
+
+ mCurlRequest->process();
+ }
+ }
+
+ if (mSignal->isLocked())
+ { //make sure to let go of the mutex associated with the given signal before shutting down
+ mSignal->unlock();
+ }
+
+ res = LLConvexDecomposition::quitThread();
+ if (res != LLCD_OK)
+ {
+ llwarns << "convex decomposition unable to be quit" << llendl;
+ }
+
+ delete mCurlRequest;
+ mCurlRequest = NULL;
+}
+
+void LLMeshRepoThread::loadMeshSkinInfo(const LLUUID& mesh_id)
+{ //protected by mSignal, no locking needed here
+ mSkinRequests.insert(mesh_id);
+}
+
+void LLMeshRepoThread::loadMeshDecomposition(const LLUUID& mesh_id)
+{ //protected by mSignal, no locking needed here
+ mDecompositionRequests.insert(mesh_id);
+}
+
+void LLMeshRepoThread::loadMeshPhysicsShape(const LLUUID& mesh_id)
+{ //protected by mSignal, no locking needed here
+ mPhysicsShapeRequests.insert(mesh_id);
+}
+
+
+void LLMeshRepoThread::loadMeshLOD(const LLVolumeParams& mesh_params, S32 lod)
+{ //protected by mSignal, no locking needed here
+
+ mesh_header_map::iterator iter = mMeshHeader.find(mesh_params.getSculptID());
+ if (iter != mMeshHeader.end())
+ { //if we have the header, request LOD byte range
+ LODRequest req(mesh_params, lod);
+ {
+ LLMutexLock lock(mMutex);
+ mLODReqQ.push(req);
+ }
+ }
+ else
+ {
+ HeaderRequest req(mesh_params);
+
+ pending_lod_map::iterator pending = mPendingLOD.find(mesh_params);
+
+ if (pending != mPendingLOD.end())
+ { //append this lod request to existing header request
+ pending->second.push_back(lod);
+ if (pending->second.size() > 4)
+ {
+ llerrs << "WTF?" << llendl;
+ }
+ }
+ else
+ { //if no header request is pending, fetch header
+ LLMutexLock lock(mMutex);
+ mHeaderReqQ.push(req);
+ mPendingLOD[mesh_params].push_back(lod);
+ }
+ }
+}
+
+//static
+std::string LLMeshRepoThread::constructUrl(LLUUID mesh_id)
+{
+ std::string http_url;
+
+ if (gAgent.getRegion())
+ {
+ http_url = gMeshRepo.mGetMeshCapability;
+ }
+
+ if (!http_url.empty())
+ {
+ http_url += "/?mesh_id=";
+ http_url += mesh_id.asString().c_str();
+ }
+ else
+ {
+ llwarns << "Current region does not have GetMesh capability! Cannot load " << mesh_id << ".mesh" << llendl;
+ }
+
+ return http_url;
+}
+
+bool LLMeshRepoThread::fetchMeshSkinInfo(const LLUUID& mesh_id)
+{ //protected by mMutex
+ mHeaderMutex->lock();
+
+ if (mMeshHeader.find(mesh_id) == mMeshHeader.end())
+ { //we have no header info for this mesh, do nothing
+ mHeaderMutex->unlock();
+ return false;
+ }
+
+ U32 header_size = mMeshHeaderSize[mesh_id];
+
+ if (header_size > 0)
+ {
+ S32 offset = header_size + mMeshHeader[mesh_id]["skin"]["offset"].asInteger();
+ S32 size = mMeshHeader[mesh_id]["skin"]["size"].asInteger();
+
+ mHeaderMutex->unlock();
+
+ if (offset >= 0 && size > 0)
+ {
+ //check VFS for mesh skin info
+ LLVFile file(gVFS, mesh_id, LLAssetType::AT_MESH);
+ if (file.getSize() >= offset+size)
+ {
+ LLMeshRepository::sCacheBytesRead += size;
+ file.seek(offset);
+ U8* buffer = new U8[size];
+ file.read(buffer, size);
+
+ //make sure buffer isn't all 0's (reserved block but not written)
+ bool zero = true;
+ for (S32 i = 0; i < llmin(size, 1024) && zero; ++i)
+ {
+ zero = buffer[i] > 0 ? false : true;
+ }
+
+ if (!zero)
+ { //attempt to parse
+ if (skinInfoReceived(mesh_id, buffer, size))
+ {
+ delete[] buffer;
+ return true;
+ }
+ }
+
+ delete[] buffer;
+ }
+
+ //reading from VFS failed for whatever reason, fetch from sim
+ std::vector<std::string> headers;
+ headers.push_back("Accept: application/octet-stream");
+
+ std::string http_url = constructUrl(mesh_id);
+ if (!http_url.empty())
+ {
+ ++sActiveLODRequests;
+ LLMeshRepository::sHTTPRequestCount++;
+ mCurlRequest->getByteRange(constructUrl(mesh_id), headers, offset, size,
+ new LLMeshSkinInfoResponder(mesh_id, offset, size));
+ }
+ }
+ }
+ else
+ {
+ mHeaderMutex->unlock();
+ }
+
+ //early out was not hit, effectively fetched
+ return true;
+}
+
+bool LLMeshRepoThread::fetchMeshDecomposition(const LLUUID& mesh_id)
+{ //protected by mMutex
+ mHeaderMutex->lock();
+
+ if (mMeshHeader.find(mesh_id) == mMeshHeader.end())
+ { //we have no header info for this mesh, do nothing
+ mHeaderMutex->unlock();
+ return false;
+ }
+
+ U32 header_size = mMeshHeaderSize[mesh_id];
+
+ if (header_size > 0)
+ {
+ S32 offset = header_size + mMeshHeader[mesh_id]["decomposition"]["offset"].asInteger();
+ S32 size = mMeshHeader[mesh_id]["decomposition"]["size"].asInteger();
+
+ mHeaderMutex->unlock();
+
+ if (offset >= 0 && size > 0)
+ {
+ //check VFS for mesh skin info
+ LLVFile file(gVFS, mesh_id, LLAssetType::AT_MESH);
+ if (file.getSize() >= offset+size)
+ {
+ LLMeshRepository::sCacheBytesRead += size;
+ file.seek(offset);
+ U8* buffer = new U8[size];
+ file.read(buffer, size);
+
+ //make sure buffer isn't all 0's (reserved block but not written)
+ bool zero = true;
+ for (S32 i = 0; i < llmin(size, 1024) && zero; ++i)
+ {
+ zero = buffer[i] > 0 ? false : true;
+ }
+
+ if (!zero)
+ { //attempt to parse
+ if (decompositionReceived(mesh_id, buffer, size))
+ {
+ delete[] buffer;
+ return true;
+ }
+ }
+
+ delete[] buffer;
+ }
+
+ //reading from VFS failed for whatever reason, fetch from sim
+ std::vector<std::string> headers;
+ headers.push_back("Accept: application/octet-stream");
+
+ std::string http_url = constructUrl(mesh_id);
+ if (!http_url.empty())
+ {
+ ++sActiveLODRequests;
+ LLMeshRepository::sHTTPRequestCount++;
+ mCurlRequest->getByteRange(http_url, headers, offset, size,
+ new LLMeshDecompositionResponder(mesh_id, offset, size));
+ }
+ }
+ }
+ else
+ {
+ mHeaderMutex->unlock();
+ }
+
+ //early out was not hit, effectively fetched
+ return true;
+}
+
+bool LLMeshRepoThread::fetchMeshPhysicsShape(const LLUUID& mesh_id)
+{ //protected by mMutex
+ mHeaderMutex->lock();
+
+ if (mMeshHeader.find(mesh_id) == mMeshHeader.end())
+ { //we have no header info for this mesh, do nothing
+ mHeaderMutex->unlock();
+ return false;
+ }
+
+ U32 header_size = mMeshHeaderSize[mesh_id];
+
+ if (header_size > 0)
+ {
+ S32 offset = header_size + mMeshHeader[mesh_id]["physics_shape"]["offset"].asInteger();
+ S32 size = mMeshHeader[mesh_id]["physics_shape"]["size"].asInteger();
+
+ mHeaderMutex->unlock();
+
+ if (offset >= 0 && size > 0)
+ {
+ //check VFS for mesh physics shape info
+ LLVFile file(gVFS, mesh_id, LLAssetType::AT_MESH);
+ if (file.getSize() >= offset+size)
+ {
+ LLMeshRepository::sCacheBytesRead += size;
+ file.seek(offset);
+ U8* buffer = new U8[size];
+ file.read(buffer, size);
+
+ //make sure buffer isn't all 0's (reserved block but not written)
+ bool zero = true;
+ for (S32 i = 0; i < llmin(size, 1024) && zero; ++i)
+ {
+ zero = buffer[i] > 0 ? false : true;
+ }
+
+ if (!zero)
+ { //attempt to parse
+ if (physicsShapeReceived(mesh_id, buffer, size))
+ {
+ delete[] buffer;
+ return true;
+ }
+ }
+
+ delete[] buffer;
+ }
+
+ //reading from VFS failed for whatever reason, fetch from sim
+ std::vector<std::string> headers;
+ headers.push_back("Accept: application/octet-stream");
+
+ std::string http_url = constructUrl(mesh_id);
+ if (!http_url.empty())
+ {
+ ++sActiveLODRequests;
+ LLMeshRepository::sHTTPRequestCount++;
+ mCurlRequest->getByteRange(http_url, headers, offset, size,
+ new LLMeshPhysicsShapeResponder(mesh_id, offset, size));
+ }
+ }
+ else
+ { //no physics shape whatsoever, report back NULL
+ physicsShapeReceived(mesh_id, NULL, 0);
+ }
+ }
+ else
+ {
+ mHeaderMutex->unlock();
+ }
+
+ //early out was not hit, effectively fetched
+ return true;
+}
+
+bool LLMeshRepoThread::fetchMeshHeader(const LLVolumeParams& mesh_params)
+{
+ bool retval = false;
+
+ {
+ //look for mesh in asset in vfs
+ LLVFile file(gVFS, mesh_params.getSculptID(), LLAssetType::AT_MESH);
+
+ S32 size = file.getSize();
+
+ if (size > 0)
+ {
+ U8 buffer[1024];
+ S32 bytes = llmin(size, 1024);
+ LLMeshRepository::sCacheBytesRead += bytes;
+ file.read(buffer, bytes);
+ if (headerReceived(mesh_params, buffer, bytes))
+ { //did not do an HTTP request, return false
+ return false;
+ }
+ }
+ }
+
+ //either cache entry doesn't exist or is corrupt, request header from simulator
+
+ std::vector<std::string> headers;
+ headers.push_back("Accept: application/octet-stream");
+
+ std::string http_url = constructUrl(mesh_params.getSculptID());
+ if (!http_url.empty())
+ {
+ ++sActiveHeaderRequests;
+ retval = true;
+ //grab first 4KB if we're going to bother with a fetch. Cache will prevent future fetches if a full mesh fits
+ //within the first 4KB
+ LLMeshRepository::sHTTPRequestCount++;
+ mCurlRequest->getByteRange(http_url, headers, 0, 4096, new LLMeshHeaderResponder(mesh_params));
+ }
+
+ return retval;
+}
+
+bool LLMeshRepoThread::fetchMeshLOD(const LLVolumeParams& mesh_params, S32 lod)
+{ //protected by mMutex
+ mHeaderMutex->lock();
+
+ bool retval = false;
+
+ LLUUID mesh_id = mesh_params.getSculptID();
+
+ U32 header_size = mMeshHeaderSize[mesh_id];
+
+ if (header_size > 0)
+ {
+ S32 offset = header_size + mMeshHeader[mesh_id][header_lod[lod]]["offset"].asInteger();
+ S32 size = mMeshHeader[mesh_id][header_lod[lod]]["size"].asInteger();
+ mHeaderMutex->unlock();
+ if (offset >= 0 && size > 0)
+ {
+
+ //check VFS for mesh asset
+ LLVFile file(gVFS, mesh_id, LLAssetType::AT_MESH);
+ if (file.getSize() >= offset+size)
+ {
+ LLMeshRepository::sCacheBytesRead += size;
+ file.seek(offset);
+ U8* buffer = new U8[size];
+ file.read(buffer, size);
+
+ //make sure buffer isn't all 0's (reserved block but not written)
+ bool zero = true;
+ for (S32 i = 0; i < llmin(size, 1024) && zero; ++i)
+ {
+ zero = buffer[i] > 0 ? false : true;
+ }
+
+ if (!zero)
+ { //attempt to parse
+ if (lodReceived(mesh_params, lod, buffer, size))
+ {
+ delete[] buffer;
+ return false;
+ }
+ }
+
+ delete[] buffer;
+ }
+
+ //reading from VFS failed for whatever reason, fetch from sim
+ std::vector<std::string> headers;
+ headers.push_back("Accept: application/octet-stream");
+
+ std::string http_url = constructUrl(mesh_id);
+ if (!http_url.empty())
+ {
+ ++sActiveLODRequests;
+ retval = true;
+ LLMeshRepository::sHTTPRequestCount++;
+ mCurlRequest->getByteRange(constructUrl(mesh_id), headers, offset, size,
+ new LLMeshLODResponder(mesh_params, lod, offset, size));
+ }
+ else
+ {
+ mUnavailableQ.push(LODRequest(mesh_params, lod));
+ }
+ }
+ else
+ {
+ mUnavailableQ.push(LODRequest(mesh_params, lod));
+ }
+ }
+ else
+ {
+ mHeaderMutex->unlock();
+ }
+
+ return retval;
+}
+
+bool LLMeshRepoThread::headerReceived(const LLVolumeParams& mesh_params, U8* data, S32 data_size)
+{
+ LLSD header;
+
+ U32 header_size = 0;
+ if (data_size > 0)
+ {
+ std::string res_str((char*) data, data_size);
+
+ std::string deprecated_header("<? LLSD/Binary ?>");
+
+ if (res_str.substr(0, deprecated_header.size()) == deprecated_header)
+ {
+ res_str = res_str.substr(deprecated_header.size()+1, data_size);
+ header_size = deprecated_header.size()+1;
+ }
+ data_size = res_str.size();
+
+ std::istringstream stream(res_str);
+
+ if (!LLSDSerialize::fromBinary(header, stream, data_size))
+ {
+ llwarns << "Mesh header parse error. Not a valid mesh asset!" << llendl;
+ return false;
+ }
+
+ header_size += stream.tellg();
+ }
+ else
+ {
+ llinfos
+ << "Marking header as non-existent, will not retry." << llendl;
+ header["404"] = 1;
+ }
+
+ {
+ U32 cost = gMeshRepo.calcResourceCost(header);
+
+ LLUUID mesh_id = mesh_params.getSculptID();
+
+ mHeaderMutex->lock();
+ mMeshHeaderSize[mesh_id] = header_size;
+ mMeshHeader[mesh_id] = header;
+ mMeshResourceCost[mesh_id] = cost;
+ mHeaderMutex->unlock();
+
+ //check for pending requests
+ pending_lod_map::iterator iter = mPendingLOD.find(mesh_params);
+ if (iter != mPendingLOD.end())
+ {
+ LLMutexLock lock(mMutex);
+ for (U32 i = 0; i < iter->second.size(); ++i)
+ {
+ LODRequest req(mesh_params, iter->second[i]);
+ mLODReqQ.push(req);
+ }
+ }
+ mPendingLOD.erase(iter);
+ }
+
+ return true;
+}
+
+bool LLMeshRepoThread::lodReceived(const LLVolumeParams& mesh_params, S32 lod, U8* data, S32 data_size)
+{
+ LLVolume* volume = new LLVolume(mesh_params, LLVolumeLODGroup::getVolumeScaleFromDetail(lod));
+ std::string mesh_string((char*) data, data_size);
+ std::istringstream stream(mesh_string);
+
+ if (volume->unpackVolumeFaces(stream, data_size))
+ {
+ LoadedMesh mesh(volume, mesh_params, lod);
+ if (volume->getNumFaces() > 0)
+ {
+ LLMutexLock lock(mMutex);
+ mLoadedQ.push(mesh);
+ return true;
+ }
+ }
+
+ return false;
+}
+
+bool LLMeshRepoThread::skinInfoReceived(const LLUUID& mesh_id, U8* data, S32 data_size)
+{
+ LLSD skin;
+
+ if (data_size > 0)
+ {
+ std::string res_str((char*) data, data_size);
+
+ std::istringstream stream(res_str);
+
+ if (!unzip_llsd(skin, stream, data_size))
+ {
+ llwarns << "Mesh skin info parse error. Not a valid mesh asset!" << llendl;
+ return false;
+ }
+ }
+
+ {
+ LLMeshSkinInfo info;
+ info.mMeshID = mesh_id;
+
+ if (skin.has("joint_names"))
+ {
+ for (U32 i = 0; i < skin["joint_names"].size(); ++i)
+ {
+ info.mJointNames.push_back(skin["joint_names"][i]);
+ }
+ }
+
+ if (skin.has("inverse_bind_matrix"))
+ {
+ for (U32 i = 0; i < skin["inverse_bind_matrix"].size(); ++i)
+ {
+ LLMatrix4 mat;
+ for (U32 j = 0; j < 4; j++)
+ {
+ for (U32 k = 0; k < 4; k++)
+ {
+ mat.mMatrix[j][k] = skin["inverse_bind_matrix"][i][j*4+k].asReal();
+ }
+ }
+
+ info.mInvBindMatrix.push_back(mat);
+ }
+ }
+
+ if (skin.has("bind_shape_matrix"))
+ {
+ for (U32 j = 0; j < 4; j++)
+ {
+ for (U32 k = 0; k < 4; k++)
+ {
+ info.mBindShapeMatrix.mMatrix[j][k] = skin["bind_shape_matrix"][j*4+k].asReal();
+ }
+ }
+ }
+
+ if (skin.has("alt_inverse_bind_matrix"))
+ {
+ for (U32 i = 0; i < skin["alt_inverse_bind_matrix"].size(); ++i)
+ {
+ LLMatrix4 mat;
+ for (U32 j = 0; j < 4; j++)
+ {
+ for (U32 k = 0; k < 4; k++)
+ {
+ mat.mMatrix[j][k] = skin["alt_inverse_bind_matrix"][i][j*4+k].asReal();
+ }
+ }
+
+ info.mAlternateBindMatrix.push_back(mat);
+ }
+ }
+
+ if (skin.has("pelvis_offset"))
+ {
+ info.mPelvisOffset = skin["pelvis_offset"].asReal();
+ }
+ //llinfos<<"info pelvis offset"<<info.mPelvisOffset<<llendl;
+ mSkinInfoQ.push(info);
+ }
+
+ return true;
+}
+
+bool LLMeshRepoThread::decompositionReceived(const LLUUID& mesh_id, U8* data, S32 data_size)
+{
+ LLSD decomp;
+
+ if (data_size > 0)
+ {
+ std::string res_str((char*) data, data_size);
+
+ std::istringstream stream(res_str);
+
+ if (!unzip_llsd(decomp, stream, data_size))
+ {
+ llwarns << "Mesh decomposition parse error. Not a valid mesh asset!" << llendl;
+ return false;
+ }
+ }
+
+ {
+ LLMeshDecomposition* d = new LLMeshDecomposition();
+ d->mMeshID = mesh_id;
+
+ if (decomp.has("HullList"))
+ {
+ // updated for const-correctness. gcc is picky about this type of thing - Nyx
+ const LLSD::Binary& hulls = decomp["HullList"].asBinary();
+ const LLSD::Binary& position = decomp["Position"].asBinary();
+
+ U16* p = (U16*) &position[0];
+
+ d->mHull.resize(hulls.size());
+
+ LLVector3 min;
+ LLVector3 max;
+ LLVector3 range;
+
+ min.setValue(decomp["Min"]);
+ max.setValue(decomp["Max"]);
+ range = max-min;
+
+ for (U32 i = 0; i < hulls.size(); ++i)
+ {
+ U16 count = (hulls[i] == 0) ? 256 : hulls[i];
+
+ for (U32 j = 0; j < count; ++j)
+ {
+ d->mHull[i].push_back(LLVector3(
+ (F32) p[0]/65535.f*range.mV[0]+min.mV[0],
+ (F32) p[1]/65535.f*range.mV[1]+min.mV[1],
+ (F32) p[2]/65535.f*range.mV[2]+min.mV[2]));
+ p += 3;
+ }
+
+ }
+
+ //get mesh for decomposition
+ for (U32 i = 0; i < d->mHull.size(); ++i)
+ {
+ LLCDHull hull;
+ hull.mNumVertices = d->mHull[i].size();
+ hull.mVertexBase = d->mHull[i][0].mV;
+ hull.mVertexStrideBytes = 12;
+
+ LLCDMeshData mesh;
+ LLCDResult res = LLCD_OK;
+ if (LLConvexDecomposition::getInstance() != NULL)
+ {
+ res = LLConvexDecomposition::getInstance()->getMeshFromHull(&hull, &mesh);
+ }
+ if (res != LLCD_OK)
+ {
+ llwarns << "could not get mesh from hull from convex decomposition lib." << llendl;
+ return false;
+ }
+
+
+ d->mMesh.push_back(get_vertex_buffer_from_mesh(mesh));
+ }
+ }
+
+ if (decomp.has("Hull"))
+ {
+ const LLSD::Binary& position = decomp["Hull"].asBinary();
+
+ U16* p = (U16*) &position[0];
+
+ LLVector3 min;
+ LLVector3 max;
+ LLVector3 range;
+
+ min.setValue(decomp["Min"]);
+ max.setValue(decomp["Max"]);
+ range = max-min;
+
+ U16 count = position.size()/6;
+
+ for (U32 j = 0; j < count; ++j)
+ {
+ d->mBaseHull.push_back(LLVector3(
+ (F32) p[0]/65535.f*range.mV[0]+min.mV[0],
+ (F32) p[1]/65535.f*range.mV[1]+min.mV[1],
+ (F32) p[2]/65535.f*range.mV[2]+min.mV[2]));
+ p += 3;
+ }
+
+ //get mesh for decomposition
+ LLCDHull hull;
+ hull.mNumVertices = d->mBaseHull.size();
+ hull.mVertexBase = d->mBaseHull[0].mV;
+ hull.mVertexStrideBytes = 12;
+
+ LLCDMeshData mesh;
+ LLCDResult res = LLCD_OK;
+ if (LLConvexDecomposition::getInstance() != NULL)
+ {
+ res = LLConvexDecomposition::getInstance()->getMeshFromHull(&hull, &mesh);
+ }
+ if (res != LLCD_OK)
+ {
+ llwarns << "could not get mesh from hull from convex decomposition lib." << llendl;
+ return false;
+ }
+
+ d->mBaseHullMesh = get_vertex_buffer_from_mesh(mesh);
+ }
+ else
+ {
+ //empty vertex buffer to indicate decomposition has been fetched
+ //but contains no base hull
+ d->mBaseHullMesh = new LLVertexBuffer(0, 0);
+ }
+
+ mDecompositionQ.push(d);
+ }
+
+ return true;
+}
+
+bool LLMeshRepoThread::physicsShapeReceived(const LLUUID& mesh_id, U8* data, S32 data_size)
+{
+ LLSD physics_shape;
+
+ LLMeshDecomposition* d = new LLMeshDecomposition();
+ d->mMeshID = mesh_id;
+
+ if (data == NULL)
+ { //no data, no physics shape exists
+ d->mPhysicsShapeMesh = new LLVertexBuffer(0,0);
+ }
+ else
+ {
+ LLVolumeParams volume_params;
+ volume_params.setType(LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE);
+ volume_params.setSculptID(mesh_id, LL_SCULPT_TYPE_MESH);
+ LLPointer<LLVolume> volume = new LLVolume(volume_params,0);
+ std::string mesh_string((char*) data, data_size);
+ std::istringstream stream(mesh_string);
+
+ if (volume->unpackVolumeFaces(stream, data_size))
+ {
+ //load volume faces into decomposition buffer
+ S32 vertex_count = 0;
+ S32 index_count = 0;
+
+ for (S32 i = 0; i < volume->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = volume->getVolumeFace(i);
+ vertex_count += face.mNumVertices;
+ index_count += face.mNumIndices;
+ }
+
+ d->mPhysicsShapeMesh = new LLVertexBuffer(LLVertexBuffer::MAP_VERTEX, 0);
+
+ d->mPhysicsShapeMesh->allocateBuffer(vertex_count, index_count, true);
+
+ LLStrider<LLVector3> pos;
+ LLStrider<U16> idx;
+
+ d->mPhysicsShapeMesh->getVertexStrider(pos);
+ d->mPhysicsShapeMesh->getIndexStrider(idx);
+
+ S32 idx_offset = 0;
+ for (S32 i = 0; i < volume->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = volume->getVolumeFace(i);
+ if (idx_offset + face.mNumIndices > 65535)
+ { //avoid 16-bit index overflow
+ continue;
+ }
+
+ LLVector4a::memcpyNonAliased16(pos[idx_offset].mV, face.mPositions[0].getF32ptr(), face.mNumVertices*sizeof(LLVector4a));
+
+ for (S32 i = 0; i < face.mNumIndices; ++i)
+ {
+ *idx++ = face.mIndices[i] + idx_offset;
+ }
+
+ idx_offset += face.mNumVertices;
+ }
+ }
+ }
+
+ mDecompositionQ.push(d);
+ return true;
+}
+
+LLMeshUploadThread::LLMeshUploadThread(LLMeshUploadThread::instance_list& data, LLVector3& scale, bool upload_textures,
+ bool upload_skin, bool upload_joints)
+: LLThread("mesh upload")
+{
+ mInstanceList = data;
+ mUploadTextures = upload_textures;
+ mUploadSkin = upload_skin;
+ mUploadJoints = upload_joints;
+ mMutex = new LLMutex(NULL);
+ mCurlRequest = NULL;
+ mPendingConfirmations = 0;
+ mPendingUploads = 0;
+ mPendingCost = 0;
+ mFinished = false;
+ mOrigin = gAgent.getPositionAgent();
+ mHost = gAgent.getRegionHost();
+
+ mUploadObjectAssetCapability = gAgent.getRegion()->getCapability("UploadObjectAsset");
+ mNewInventoryCapability = gAgent.getRegion()->getCapability("NewFileAgentInventoryVariablePrice");
+
+ mOrigin += gAgent.getAtAxis() * scale.magVec();
+}
+
+LLMeshUploadThread::~LLMeshUploadThread()
+{
+
+}
+
+LLMeshUploadThread::DecompRequest::DecompRequest(LLModel* mdl, LLModel* base_model, LLMeshUploadThread* thread)
+{
+ mStage = "single_hull";
+ mModel = mdl;
+ mDecompID = &mdl->mDecompID;
+ mBaseModel = base_model;
+ mThread = thread;
+
+ //copy out positions and indices
+ if (mdl)
+ {
+ U16 index_offset = 0;
+
+ mPositions.clear();
+ mIndices.clear();
+
+ //queue up vertex positions and indices
+ for (S32 i = 0; i < mdl->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = mdl->getVolumeFace(i);
+ if (mPositions.size() + face.mNumVertices > 65535)
+ {
+ continue;
+ }
+
+ for (U32 j = 0; j < face.mNumVertices; ++j)
+ {
+ mPositions.push_back(LLVector3(face.mPositions[j].getF32ptr()));
+ }
+
+ for (U32 j = 0; j < face.mNumIndices; ++j)
+ {
+ mIndices.push_back(face.mIndices[j]+index_offset);
+ }
+
+ index_offset += face.mNumVertices;
+ }
+ }
+
+ mThread->mFinalDecomp = this;
+ mThread->mPhysicsComplete = false;
+}
+
+void LLMeshUploadThread::DecompRequest::completed()
+{
+ if (mThread->mFinalDecomp == this)
+ {
+ mThread->mPhysicsComplete = true;
+ }
+
+ if (mHull.size() != 1)
+ {
+ llerrs << "WTF?" << llendl;
+ }
+
+ mThread->mHullMap[mBaseModel] = mHull[0];
+}
+
+//called in the main thread.
+void LLMeshUploadThread::preStart()
+{
+ //build map of LLModel refs to instances for callbacks
+ for (instance_list::iterator iter = mInstanceList.begin(); iter != mInstanceList.end(); ++iter)
+ {
+ mInstance[iter->mModel].push_back(*iter);
+ }
+}
+
+void LLMeshUploadThread::run()
+{
+ mCurlRequest = new LLCurlRequest();
+
+ std::set<LLViewerTexture* > textures;
+
+ //populate upload queue with relevant models
+ for (instance_map::iterator iter = mInstance.begin(); iter != mInstance.end(); ++iter)
+ {
+ LLMeshUploadData data;
+ data.mBaseModel = iter->first;
+
+ LLModelInstance& instance = *(iter->second.begin());
+
+ for (S32 i = 0; i < 5; i++)
+ {
+ data.mModel[i] = instance.mLOD[i];
+ }
+
+ uploadModel(data);
+
+ if (mUploadTextures)
+ {
+ for (std::vector<LLImportMaterial>::iterator material_iter = instance.mMaterial.begin();
+ material_iter != instance.mMaterial.end(); ++material_iter)
+ {
+
+ if (textures.find(material_iter->mDiffuseMap.get()) == textures.end())
+ {
+ textures.insert(material_iter->mDiffuseMap.get());
+
+ LLTextureUploadData data(material_iter->mDiffuseMap.get(), material_iter->mDiffuseMapLabel);
+ uploadTexture(data);
+ }
+ }
+ }
+
+ //queue up models for hull generation
+ LLModel* physics = NULL;
+
+ if (data.mModel[LLModel::LOD_PHYSICS].notNull())
+ {
+ physics = data.mModel[LLModel::LOD_PHYSICS];
+ }
+ else if (data.mModel[LLModel::LOD_MEDIUM].notNull())
+ {
+ physics = data.mModel[LLModel::LOD_MEDIUM];
+ }
+ else
+ {
+ physics = data.mModel[LLModel::LOD_HIGH];
+ }
+
+ if (!physics)
+ {
+ llerrs << "WTF?" << llendl;
+ }
+
+ DecompRequest* request = new DecompRequest(physics, data.mBaseModel, this);
+ gMeshRepo.mDecompThread->submitRequest(request);
+ }
+
+ while (!mPhysicsComplete)
+ {
+ apr_sleep(100);
+ }
+
+ //upload textures
+ bool done = false;
+ do
+ {
+ if (!mTextureQ.empty())
+ {
+ sendCostRequest(mTextureQ.front());
+ mTextureQ.pop();
+ }
+
+ if (!mConfirmedTextureQ.empty())
+ {
+ doUploadTexture(mConfirmedTextureQ.front());
+ mConfirmedTextureQ.pop();
+ }
+
+ mCurlRequest->process();
+
+ done = mTextureQ.empty() && mConfirmedTextureQ.empty();
+ }
+ while (!done || mCurlRequest->getQueued() > 0);
+
+ LLSD object_asset;
+ object_asset["objects"] = LLSD::emptyArray();
+
+ done = false;
+ do
+ {
+ static S32 count = 0;
+ static F32 last_hundred = gFrameTimeSeconds;
+ if (gFrameTimeSeconds - last_hundred > 1.f)
+ {
+ last_hundred = gFrameTimeSeconds;
+ count = 0;
+ }
+
+ //how many requests to push before calling process
+ const S32 PUSH_PER_PROCESS = 32;
+
+ S32 tcount = llmin(count+PUSH_PER_PROCESS, 100);
+
+ while (!mUploadQ.empty() && count < tcount)
+ { //send any pending upload requests
+ mMutex->lock();
+ LLMeshUploadData data = mUploadQ.front();
+ mUploadQ.pop();
+ mMutex->unlock();
+ sendCostRequest(data);
+ count++;
+ }
+
+ tcount = llmin(count+PUSH_PER_PROCESS, 100);
+
+ while (!mConfirmedQ.empty() && count < tcount)
+ { //process any meshes that have been confirmed for upload
+ LLMeshUploadData& data = mConfirmedQ.front();
+ doUploadModel(data);
+ mConfirmedQ.pop();
+ count++;
+ }
+
+ tcount = llmin(count+PUSH_PER_PROCESS, 100);
+
+ while (!mInstanceQ.empty() && count < tcount)
+ { //create any objects waiting for upload
+ count++;
+ object_asset["objects"].append(createObject(mInstanceQ.front()));
+ mInstanceQ.pop();
+ }
+
+ mCurlRequest->process();
+
+ done = mInstanceQ.empty() && mConfirmedQ.empty() && mUploadQ.empty();
+ }
+ while (!done || mCurlRequest->getQueued() > 0);
+
+ delete mCurlRequest;
+ mCurlRequest = NULL;
+
+ // now upload the object asset
+ std::string url = mUploadObjectAssetCapability;
+
+ if (object_asset["objects"][0].has("permissions"))
+ { //copy permissions from first available object to be used for coalesced object
+ object_asset["permissions"] = object_asset["objects"][0]["permissions"];
+ }
+
+ LLHTTPClient::post(url, object_asset, new LLHTTPClient::Responder());
+
+ mFinished = true;
+}
+
+void LLMeshUploadThread::uploadModel(LLMeshUploadData& data)
+{ //called from arbitrary thread
+ {
+ LLMutexLock lock(mMutex);
+ mUploadQ.push(data);
+ }
+}
+
+void LLMeshUploadThread::uploadTexture(LLTextureUploadData& data)
+{ //called from mesh upload thread
+ mTextureQ.push(data);
+}
+
+
+static LLFastTimer::DeclareTimer FTM_NOTIFY_MESH_LOADED("Notify Loaded");
+static LLFastTimer::DeclareTimer FTM_NOTIFY_MESH_UNAVAILABLE("Notify Unavailable");
+
+void LLMeshRepoThread::notifyLoadedMeshes()
+{
+ while (!mLoadedQ.empty())
+ {
+ mMutex->lock();
+ LoadedMesh mesh = mLoadedQ.front();
+ mLoadedQ.pop();
+ mMutex->unlock();
+
+ if (mesh.mVolume && mesh.mVolume->getNumVolumeFaces() > 0)
+ {
+ gMeshRepo.notifyMeshLoaded(mesh.mMeshParams, mesh.mVolume);
+ }
+ else
+ {
+ gMeshRepo.notifyMeshUnavailable(mesh.mMeshParams,
+ LLVolumeLODGroup::getVolumeDetailFromScale(mesh.mVolume->getDetail()));
+ }
+ }
+
+ while (!mUnavailableQ.empty())
+ {
+ mMutex->lock();
+ LODRequest req = mUnavailableQ.front();
+ mUnavailableQ.pop();
+ mMutex->unlock();
+
+ gMeshRepo.notifyMeshUnavailable(req.mMeshParams, req.mLOD);
+ }
+
+ while (!mSkinInfoQ.empty())
+ {
+ gMeshRepo.notifySkinInfoReceived(mSkinInfoQ.front());
+ mSkinInfoQ.pop();
+ }
+
+ while (!mDecompositionQ.empty())
+ {
+ gMeshRepo.notifyDecompositionReceived(mDecompositionQ.front());
+ mDecompositionQ.pop();
+ }
+}
+
+S32 LLMeshRepoThread::getActualMeshLOD(const LLVolumeParams& mesh_params, S32 lod)
+{ //only ever called from main thread
+ lod = llclamp(lod, 0, 3);
+
+ LLMutexLock lock(mHeaderMutex);
+ mesh_header_map::iterator iter = mMeshHeader.find(mesh_params.getSculptID());
+
+ if (iter != mMeshHeader.end())
+ {
+ LLSD& header = iter->second;
+
+ if (header.has("404"))
+ {
+ return -1;
+ }
+
+ if (header[header_lod[lod]]["size"].asInteger() > 0)
+ {
+ return lod;
+ }
+
+ //search down to find the next available lower lod
+ for (S32 i = lod-1; i >= 0; --i)
+ {
+ if (header[header_lod[i]]["size"].asInteger() > 0)
+ {
+ return i;
+ }
+ }
+
+ //search up to find then ext available higher lod
+ for (S32 i = lod+1; i < 4; ++i)
+ {
+ if (header[header_lod[i]]["size"].asInteger() > 0)
+ {
+ return i;
+ }
+ }
+
+ //header exists and no good lod found, treat as 404
+ header["404"] = 1;
+ return -1;
+ }
+
+ return lod;
+}
+
+U32 LLMeshRepoThread::getResourceCost(const LLUUID& mesh_id)
+{
+ LLMutexLock lock(mHeaderMutex);
+
+ std::map<LLUUID, U32>::iterator iter = mMeshResourceCost.find(mesh_id);
+ if (iter != mMeshResourceCost.end())
+ {
+ return iter->second;
+ }
+
+ return 0;
+}
+
+void LLMeshRepository::cacheOutgoingMesh(LLMeshUploadData& data, LLSD& header)
+{
+ mThread->mMeshHeader[data.mUUID] = header;
+
+ // we cache the mesh for default parameters
+ LLVolumeParams volume_params;
+ volume_params.setType(LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE);
+ volume_params.setSculptID(data.mUUID, LL_SCULPT_TYPE_MESH);
+
+ for (U32 i = 0; i < 4; i++)
+ {
+ if (data.mModel[i].notNull())
+ {
+ LLPointer<LLVolume> volume = new LLVolume(volume_params, LLVolumeLODGroup::getVolumeScaleFromDetail(i));
+ volume->copyVolumeFaces(data.mModel[i]);
+ }
+ }
+
+}
+
+void LLMeshLODResponder::completedRaw(U32 status, const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer)
+{
+
+ LLMeshRepoThread::sActiveLODRequests--;
+ S32 data_size = buffer->countAfter(channels.in(), NULL);
+
+ if (status < 200 || status > 400)
+ {
+ llwarns << status << ": " << reason << llendl;
+ }
+
+ if (data_size < mRequestedBytes)
+ {
+ if (status == 499 || status == 503)
+ { //timeout or service unavailable, try again
+ LLMeshRepository::sHTTPRetryCount++;
+ gMeshRepo.mThread->loadMeshLOD(mMeshParams, mLOD);
+ }
+ else
+ {
+ llwarns << "Unhandled status " << status << llendl;
+ }
+ return;
+ }
+
+ LLMeshRepository::sBytesReceived += mRequestedBytes;
+
+ U8* data = NULL;
+
+ if (data_size > 0)
+ {
+ data = new U8[data_size];
+ buffer->readAfter(channels.in(), NULL, data, data_size);
+ }
+
+ if (gMeshRepo.mThread->lodReceived(mMeshParams, mLOD, data, data_size))
+ {
+ //good fetch from sim, write to VFS for caching
+ LLVFile file(gVFS, mMeshParams.getSculptID(), LLAssetType::AT_MESH, LLVFile::WRITE);
+
+ S32 offset = mOffset;
+ S32 size = mRequestedBytes;
+
+ if (file.getSize() >= offset+size)
+ {
+ file.seek(offset);
+ file.write(data, size);
+ LLMeshRepository::sCacheBytesWritten += size;
+ }
+ }
+
+ delete [] data;
+}
+
+void LLMeshSkinInfoResponder::completedRaw(U32 status, const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer)
+{
+ S32 data_size = buffer->countAfter(channels.in(), NULL);
+
+ if (status < 200 || status > 400)
+ {
+ llwarns << status << ": " << reason << llendl;
+ }
+
+ if (data_size < mRequestedBytes)
+ {
+ if (status == 499 || status == 503)
+ { //timeout or service unavailable, try again
+ LLMeshRepository::sHTTPRetryCount++;
+ gMeshRepo.mThread->loadMeshSkinInfo(mMeshID);
+ }
+ else
+ {
+ llwarns << "Unhandled status " << status << llendl;
+ }
+ return;
+ }
+
+ LLMeshRepository::sBytesReceived += mRequestedBytes;
+
+ U8* data = NULL;
+
+ if (data_size > 0)
+ {
+ data = new U8[data_size];
+ buffer->readAfter(channels.in(), NULL, data, data_size);
+ }
+
+ if (gMeshRepo.mThread->skinInfoReceived(mMeshID, data, data_size))
+ {
+ //good fetch from sim, write to VFS for caching
+ LLVFile file(gVFS, mMeshID, LLAssetType::AT_MESH, LLVFile::WRITE);
+
+ S32 offset = mOffset;
+ S32 size = mRequestedBytes;
+
+ if (file.getSize() >= offset+size)
+ {
+ LLMeshRepository::sCacheBytesWritten += size;
+ file.seek(offset);
+ file.write(data, size);
+ }
+ }
+
+ delete [] data;
+}
+
+void LLMeshDecompositionResponder::completedRaw(U32 status, const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer)
+{
+ S32 data_size = buffer->countAfter(channels.in(), NULL);
+
+ if (status < 200 || status > 400)
+ {
+ llwarns << status << ": " << reason << llendl;
+ }
+
+ if (data_size < mRequestedBytes)
+ {
+ if (status == 499 || status == 503)
+ { //timeout or service unavailable, try again
+ LLMeshRepository::sHTTPRetryCount++;
+ gMeshRepo.mThread->loadMeshDecomposition(mMeshID);
+ }
+ else
+ {
+ llwarns << "Unhandled status " << status << llendl;
+ }
+ return;
+ }
+
+ LLMeshRepository::sBytesReceived += mRequestedBytes;
+
+ U8* data = NULL;
+
+ if (data_size > 0)
+ {
+ data = new U8[data_size];
+ buffer->readAfter(channels.in(), NULL, data, data_size);
+ }
+
+ if (gMeshRepo.mThread->decompositionReceived(mMeshID, data, data_size))
+ {
+ //good fetch from sim, write to VFS for caching
+ LLVFile file(gVFS, mMeshID, LLAssetType::AT_MESH, LLVFile::WRITE);
+
+ S32 offset = mOffset;
+ S32 size = mRequestedBytes;
+
+ if (file.getSize() >= offset+size)
+ {
+ LLMeshRepository::sCacheBytesWritten += size;
+ file.seek(offset);
+ file.write(data, size);
+ }
+ }
+
+ delete [] data;
+}
+
+void LLMeshPhysicsShapeResponder::completedRaw(U32 status, const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer)
+{
+ S32 data_size = buffer->countAfter(channels.in(), NULL);
+
+ if (status < 200 || status > 400)
+ {
+ llwarns << status << ": " << reason << llendl;
+ }
+
+ if (data_size < mRequestedBytes)
+ {
+ if (status == 499 || status == 503)
+ { //timeout or service unavailable, try again
+ LLMeshRepository::sHTTPRetryCount++;
+ gMeshRepo.mThread->loadMeshPhysicsShape(mMeshID);
+ }
+ else
+ {
+ llwarns << "Unhandled status " << status << llendl;
+ }
+ return;
+ }
+
+ LLMeshRepository::sBytesReceived += mRequestedBytes;
+
+ U8* data = NULL;
+
+ if (data_size > 0)
+ {
+ data = new U8[data_size];
+ buffer->readAfter(channels.in(), NULL, data, data_size);
+ }
+
+ if (gMeshRepo.mThread->physicsShapeReceived(mMeshID, data, data_size))
+ {
+ //good fetch from sim, write to VFS for caching
+ LLVFile file(gVFS, mMeshID, LLAssetType::AT_MESH, LLVFile::WRITE);
+
+ S32 offset = mOffset;
+ S32 size = mRequestedBytes;
+
+ if (file.getSize() >= offset+size)
+ {
+ LLMeshRepository::sCacheBytesWritten += size;
+ file.seek(offset);
+ file.write(data, size);
+ }
+ }
+
+ delete [] data;
+}
+
+void LLMeshHeaderResponder::completedRaw(U32 status, const std::string& reason,
+ const LLChannelDescriptors& channels,
+ const LLIOPipe::buffer_ptr_t& buffer)
+{
+ LLMeshRepoThread::sActiveHeaderRequests--;
+ if (status < 200 || status > 400)
+ {
+ //llwarns
+ // << "Header responder failed with status: "
+ // << status << ": " << reason << llendl;
+
+ // 503 (service unavailable) or 499 (timeout)
+ // can be due to server load and can be retried
+
+ // TODO*: Add maximum retry logic, exponential backoff
+ // and (somewhat more optional than the others) retries
+ // again after some set period of time
+ if (status == 503 || status == 499)
+ { //retry
+ LLMeshRepository::sHTTPRetryCount++;
+ LLMeshRepoThread::HeaderRequest req(mMeshParams);
+ LLMutexLock lock(gMeshRepo.mThread->mMutex);
+ gMeshRepo.mThread->mHeaderReqQ.push(req);
+
+ return;
+ }
+ }
+
+ S32 data_size = buffer->countAfter(channels.in(), NULL);
+
+ U8* data = NULL;
+
+ if (data_size > 0)
+ {
+ data = new U8[data_size];
+ buffer->readAfter(channels.in(), NULL, data, data_size);
+ }
+
+ LLMeshRepository::sBytesReceived += llmin(data_size, 4096);
+
+ if (!gMeshRepo.mThread->headerReceived(mMeshParams, data, data_size))
+ {
+ llwarns
+ << "Unable to parse mesh header: "
+ << status << ": " << reason << llendl;
+ }
+ else if (data && data_size > 0)
+ {
+ //header was successfully retrieved from sim, cache in vfs
+ LLUUID mesh_id = mMeshParams.getSculptID();
+ LLSD header = gMeshRepo.mThread->mMeshHeader[mesh_id];
+
+ std::stringstream str;
+
+ S32 lod_bytes = 0;
+
+ for (U32 i = 0; i < LLModel::LOD_PHYSICS; ++i)
+ { //figure out how many bytes we'll need to reserve in the file
+ std::string lod_name = header_lod[i];
+ lod_bytes = llmax(lod_bytes, header[lod_name]["offset"].asInteger()+header[lod_name]["size"].asInteger());
+ }
+
+ //just in case skin info or decomposition is at the end of the file (which it shouldn't be)
+ lod_bytes = llmax(lod_bytes, header["skin"]["offset"].asInteger() + header["skin"]["size"].asInteger());
+ lod_bytes = llmax(lod_bytes, header["decomposition"]["offset"].asInteger() + header["decomposition"]["size"].asInteger());
+
+ S32 header_bytes = (S32) gMeshRepo.mThread->mMeshHeaderSize[mesh_id];
+ S32 bytes = lod_bytes + header_bytes;
+
+
+ //it's possible for the remote asset to have more data than is needed for the local cache
+ //only allocate as much space in the VFS as is needed for the local cache
+ data_size = llmin(data_size, bytes);
+
+ LLVFile file(gVFS, mesh_id, LLAssetType::AT_MESH, LLVFile::WRITE);
+ if (file.getMaxSize() >= bytes || file.setMaxSize(bytes))
+ {
+ LLMeshRepository::sCacheBytesWritten += data_size;
+
+ file.write((const U8*) data, data_size);
+
+ //zero out the rest of the file
+ U8 block[4096];
+ memset(block, 0, 4096);
+
+ while (bytes-file.tell() > 4096)
+ {
+ file.write(block, 4096);
+ }
+
+ S32 remaining = bytes-file.tell();
+
+ if (remaining < 0 || remaining > 4096)
+ {
+ llerrs << "Bad padding of mesh asset cache entry." << llendl;
+ }
+
+ if (remaining > 0)
+ {
+ file.write(block, remaining);
+ }
+ }
+ }
+
+ delete [] data;
+}
+
+
+LLMeshRepository::LLMeshRepository()
+: mMeshMutex(NULL),
+ mMeshThreadCount(0),
+ mThread(NULL)
+{
+
+}
+
+void LLMeshRepository::init()
+{
+ mMeshMutex = new LLMutex(NULL);
+
+ LLConvexDecomposition::getInstance()->initSystem();
+
+ mDecompThread = new LLPhysicsDecomp();
+ mDecompThread->start();
+
+ while (!mDecompThread->mInited)
+ { //wait for physics decomp thread to init
+ apr_sleep(100);
+ }
+
+
+
+ mThread = new LLMeshRepoThread();
+ mThread->start();
+}
+
+void LLMeshRepository::shutdown()
+{
+ llinfos << "Shutting down mesh repository." << llendl;
+
+ mThread->mSignal->signal();
+
+ while (!mThread->isStopped())
+ {
+ apr_sleep(10);
+ }
+ delete mThread;
+ mThread = NULL;
+
+ for (U32 i = 0; i < mUploads.size(); ++i)
+ {
+ llinfos << "Waiting for pending mesh upload " << i << "/" << mUploads.size() << llendl;
+ while (!mUploads[i]->isStopped())
+ {
+ apr_sleep(10);
+ }
+ delete mUploads[i];
+ }
+
+ mUploads.clear();
+
+ delete mMeshMutex;
+ mMeshMutex = NULL;
+
+ llinfos << "Shutting down decomposition system." << llendl;
+
+ if (mDecompThread)
+ {
+ mDecompThread->shutdown();
+ delete mDecompThread;
+ mDecompThread = NULL;
+ }
+
+ LLConvexDecomposition::quitSystem();
+}
+
+//called in the main thread.
+S32 LLMeshRepository::update()
+{
+ if(mUploadWaitList.empty())
+ {
+ return 0 ;
+ }
+
+ S32 size = mUploadWaitList.size() ;
+ for (S32 i = 0; i < size; ++i)
+ {
+ mUploads.push_back(mUploadWaitList[i]);
+ mUploadWaitList[i]->preStart() ;
+ mUploadWaitList[i]->start() ;
+ }
+ mUploadWaitList.clear() ;
+
+ return size ;
+}
+
+S32 LLMeshRepository::loadMesh(LLVOVolume* vobj, const LLVolumeParams& mesh_params, S32 detail, S32 last_lod)
+{
+ if (detail < 0 || detail > 4)
+ {
+ return detail;
+ }
+
+ LLFastTimer t(FTM_LOAD_MESH);
+
+ {
+ LLMutexLock lock(mMeshMutex);
+ //add volume to list of loading meshes
+ mesh_load_map::iterator iter = mLoadingMeshes[detail].find(mesh_params);
+ if (iter != mLoadingMeshes[detail].end())
+ { //request pending for this mesh, append volume id to list
+ iter->second.insert(vobj->getID());
+ }
+ else
+ {
+ //first request for this mesh
+ mLoadingMeshes[detail][mesh_params].insert(vobj->getID());
+ mPendingRequests.push_back(LLMeshRepoThread::LODRequest(mesh_params, detail));
+ }
+ }
+
+ //do a quick search to see if we can't display something while we wait for this mesh to load
+ LLVolume* volume = vobj->getVolume();
+
+ if (volume)
+ {
+ if (volume->getNumVolumeFaces() == 0 && !volume->isTetrahedron())
+ {
+ volume->makeTetrahedron();
+ }
+
+ LLVolumeParams params = volume->getParams();
+
+ LLVolumeLODGroup* group = LLPrimitive::getVolumeManager()->getGroup(params);
+
+ if (group)
+ {
+ //first, see if last_lod is available (don't transition down to avoid funny popping a la SH-641)
+ if (last_lod >= 0)
+ {
+ LLVolume* lod = group->refLOD(last_lod);
+ if (lod && !lod->isTetrahedron() && lod->getNumVolumeFaces() > 0)
+ {
+ group->derefLOD(lod);
+ return last_lod;
+ }
+ group->derefLOD(lod);
+ }
+
+ //next, see what the next lowest LOD available might be
+ for (S32 i = detail-1; i >= 0; --i)
+ {
+ LLVolume* lod = group->refLOD(i);
+ if (lod && !lod->isTetrahedron() && lod->getNumVolumeFaces() > 0)
+ {
+ group->derefLOD(lod);
+ return i;
+ }
+
+ group->derefLOD(lod);
+ }
+
+ //no lower LOD is a available, is a higher lod available?
+ for (S32 i = detail+1; i < 4; ++i)
+ {
+ LLVolume* lod = group->refLOD(i);
+ if (lod && !lod->isTetrahedron() && lod->getNumVolumeFaces() > 0)
+ {
+ group->derefLOD(lod);
+ return i;
+ }
+
+ group->derefLOD(lod);
+ }
+ }
+ else
+ {
+ llerrs << "WTF?" << llendl;
+ }
+ }
+
+ return detail;
+}
+
+static LLFastTimer::DeclareTimer FTM_START_MESH_THREAD("Start Thread");
+static LLFastTimer::DeclareTimer FTM_LOAD_MESH_LOD("Load LOD");
+static LLFastTimer::DeclareTimer FTM_MESH_LOCK1("Lock 1");
+static LLFastTimer::DeclareTimer FTM_MESH_LOCK2("Lock 2");
+
+void LLMeshRepository::notifyLoadedMeshes()
+{ //called from main thread
+
+ LLMeshRepoThread::sMaxConcurrentRequests = gSavedSettings.getU32("MeshMaxConcurrentRequests");
+
+ //clean up completed upload threads
+ for (std::vector<LLMeshUploadThread*>::iterator iter = mUploads.begin(); iter != mUploads.end(); )
+ {
+ LLMeshUploadThread* thread = *iter;
+
+ if (thread->isStopped() && thread->finished())
+ {
+ iter = mUploads.erase(iter);
+ delete thread;
+ }
+ else
+ {
+ ++iter;
+ }
+ }
+
+ //update inventory
+ if (!mInventoryQ.empty())
+ {
+ LLMutexLock lock(mMeshMutex);
+ while (!mInventoryQ.empty())
+ {
+ inventory_data& data = mInventoryQ.front();
+
+ LLAssetType::EType asset_type = LLAssetType::lookup(data.mPostData["asset_type"].asString());
+ LLInventoryType::EType inventory_type = LLInventoryType::lookup(data.mPostData["inventory_type"].asString());
+
+ on_new_single_inventory_upload_complete(
+ asset_type,
+ inventory_type,
+ data.mPostData["asset_type"].asString(),
+ data.mPostData["folder_id"].asUUID(),
+ data.mPostData["name"],
+ data.mPostData["description"],
+ data.mResponse,
+ 0);
+
+ mInventoryQ.pop();
+ }
+ }
+
+ //call completed callbacks on finished decompositions
+ mDecompThread->notifyCompleted();
+
+ if (!mThread->mWaiting)
+ { //curl thread is churning, wait for it to go idle
+ return;
+ }
+
+ static std::string region_name("never name a region this");
+
+ if (gAgent.getRegion())
+ { //update capability url
+ if (gAgent.getRegion()->getName() != region_name && gAgent.getRegion()->capabilitiesReceived())
+ {
+ region_name = gAgent.getRegion()->getName();
+
+ mGetMeshCapability = gAgent.getRegion()->getCapability("GetMesh");
+ }
+ }
+
+ LLFastTimer t(FTM_MESH_UPDATE);
+
+ {
+ LLFastTimer t(FTM_MESH_LOCK1);
+ mMeshMutex->lock();
+ }
+
+ {
+ LLFastTimer t(FTM_MESH_LOCK2);
+ mThread->mMutex->lock();
+ }
+
+ //popup queued error messages from background threads
+ while (!mUploadErrorQ.empty())
+ {
+ LLNotificationsUtil::add("MeshUploadError", mUploadErrorQ.front());
+ mUploadErrorQ.pop();
+ }
+
+ S32 push_count = LLMeshRepoThread::sMaxConcurrentRequests-(LLMeshRepoThread::sActiveHeaderRequests+LLMeshRepoThread::sActiveLODRequests);
+
+ if (push_count > 0)
+ {
+ //calculate "score" for pending requests
+
+ //create score map
+ std::map<LLUUID, F32> score_map;
+
+ for (U32 i = 0; i < 4; ++i)
+ {
+ for (mesh_load_map::iterator iter = mLoadingMeshes[i].begin(); iter != mLoadingMeshes[i].end(); ++iter)
+ {
+ F32 max_score = 0.f;
+ for (std::set<LLUUID>::iterator obj_iter = iter->second.begin(); obj_iter != iter->second.end(); ++obj_iter)
+ {
+ LLViewerObject* object = gObjectList.findObject(*obj_iter);
+
+ if (object)
+ {
+ LLDrawable* drawable = object->mDrawable;
+ if (drawable)
+ {
+ F32 cur_score = drawable->getRadius()/llmax(drawable->mDistanceWRTCamera, 1.f);
+ max_score = llmax(max_score, cur_score);
+ }
+ }
+ }
+
+ score_map[iter->first.getSculptID()] = max_score;
+ }
+ }
+
+ //set "score" for pending requests
+ for (std::vector<LLMeshRepoThread::LODRequest>::iterator iter = mPendingRequests.begin(); iter != mPendingRequests.end(); ++iter)
+ {
+ iter->mScore = score_map[iter->mMeshParams.getSculptID()];
+ }
+
+ //sort by "score"
+ std::sort(mPendingRequests.begin(), mPendingRequests.end(), LLMeshRepoThread::CompareScoreGreater());
+
+ while (!mPendingRequests.empty() && push_count > 0)
+ {
+ LLFastTimer t(FTM_LOAD_MESH_LOD);
+ LLMeshRepoThread::LODRequest& request = mPendingRequests.front();
+ mThread->loadMeshLOD(request.mMeshParams, request.mLOD);
+ mPendingRequests.erase(mPendingRequests.begin());
+ push_count--;
+ }
+ }
+
+ //send skin info requests
+ while (!mPendingSkinRequests.empty())
+ {
+ mThread->loadMeshSkinInfo(mPendingSkinRequests.front());
+ mPendingSkinRequests.pop();
+ }
+
+ //send decomposition requests
+ while (!mPendingDecompositionRequests.empty())
+ {
+ mThread->loadMeshDecomposition(mPendingDecompositionRequests.front());
+ mPendingDecompositionRequests.pop();
+ }
+
+ //send physics shapes decomposition requests
+ while (!mPendingPhysicsShapeRequests.empty())
+ {
+ mThread->loadMeshPhysicsShape(mPendingPhysicsShapeRequests.front());
+ mPendingPhysicsShapeRequests.pop();
+ }
+
+ mThread->notifyLoadedMeshes();
+
+ mThread->mMutex->unlock();
+ mMeshMutex->unlock();
+
+ mThread->mSignal->signal();
+}
+
+void LLMeshRepository::notifySkinInfoReceived(LLMeshSkinInfo& info)
+{
+ mSkinMap[info.mMeshID] = info;
+ mLoadingSkins.erase(info.mMeshID);
+}
+
+void LLMeshDecomposition::merge(const LLMeshDecomposition* rhs)
+{
+ if (!rhs)
+ {
+ return;
+ }
+
+ if (mMeshID != rhs->mMeshID)
+ {
+ llerrs << "Attempted to merge with decomposition of some other mesh." << llendl;
+ }
+
+ if (mBaseHull.empty())
+ { //take base hull and decomposition from rhs
+ mHull = rhs->mHull;
+ mBaseHull = rhs->mBaseHull;
+ mMesh = rhs->mMesh;
+ mBaseHullMesh = rhs->mBaseHullMesh;
+ }
+
+ if (mPhysicsShapeMesh.isNull())
+ { //take physics shape mesh from rhs
+ mPhysicsShapeMesh = rhs->mPhysicsShapeMesh;
+ }
+}
+
+void LLMeshRepository::notifyDecompositionReceived(LLMeshDecomposition* decomp)
+{
+ decomposition_map::iterator iter = mDecompositionMap.find(decomp->mMeshID);
+ if (iter == mDecompositionMap.end())
+ { //just insert decomp into map
+ mDecompositionMap[decomp->mMeshID] = decomp;
+ }
+ else
+ { //merge decomp with existing entry
+ iter->second->merge(decomp);
+ delete decomp;
+ }
+
+ mLoadingDecompositions.erase(decomp->mMeshID);
+}
+
+void LLMeshRepository::notifyMeshLoaded(const LLVolumeParams& mesh_params, LLVolume* volume)
+{ //called from main thread
+ S32 detail = LLVolumeLODGroup::getVolumeDetailFromScale(volume->getDetail());
+
+ //get list of objects waiting to be notified this mesh is loaded
+ mesh_load_map::iterator obj_iter = mLoadingMeshes[detail].find(mesh_params);
+
+ if (volume && obj_iter != mLoadingMeshes[detail].end())
+ {
+ //make sure target volume is still valid
+ if (volume->getNumVolumeFaces() <= 0)
+ {
+ llwarns << "Mesh loading returned empty volume." << llendl;
+ volume->makeTetrahedron();
+ }
+
+ { //update system volume
+ LLVolume* sys_volume = LLPrimitive::getVolumeManager()->refVolume(mesh_params, detail);
+ if (sys_volume)
+ {
+ sys_volume->copyVolumeFaces(volume);
+ LLPrimitive::getVolumeManager()->unrefVolume(sys_volume);
+ }
+ else
+ {
+ llwarns << "Couldn't find system volume for given mesh." << llendl;
+ }
+ }
+
+ //notify waiting LLVOVolume instances that their requested mesh is available
+ for (std::set<LLUUID>::iterator vobj_iter = obj_iter->second.begin(); vobj_iter != obj_iter->second.end(); ++vobj_iter)
+ {
+ LLVOVolume* vobj = (LLVOVolume*) gObjectList.findObject(*vobj_iter);
+ if (vobj)
+ {
+ vobj->notifyMeshLoaded();
+ }
+ }
+
+ mLoadingMeshes[detail].erase(mesh_params);
+ }
+}
+
+void LLMeshRepository::notifyMeshUnavailable(const LLVolumeParams& mesh_params, S32 lod)
+{ //called from main thread
+ //get list of objects waiting to be notified this mesh is loaded
+ mesh_load_map::iterator obj_iter = mLoadingMeshes[lod].find(mesh_params);
+
+ F32 detail = LLVolumeLODGroup::getVolumeScaleFromDetail(lod);
+
+ if (obj_iter != mLoadingMeshes[lod].end())
+ {
+ for (std::set<LLUUID>::iterator vobj_iter = obj_iter->second.begin(); vobj_iter != obj_iter->second.end(); ++vobj_iter)
+ {
+ LLVOVolume* vobj = (LLVOVolume*) gObjectList.findObject(*vobj_iter);
+ if (vobj)
+ {
+ LLVolume* obj_volume = vobj->getVolume();
+
+ if (obj_volume &&
+ obj_volume->getDetail() == detail &&
+ obj_volume->getParams() == mesh_params)
+ { //should force volume to find most appropriate LOD
+ vobj->setVolume(obj_volume->getParams(), lod);
+ }
+ }
+ }
+
+ mLoadingMeshes[lod].erase(mesh_params);
+ }
+}
+
+S32 LLMeshRepository::getActualMeshLOD(const LLVolumeParams& mesh_params, S32 lod)
+{
+ return mThread->getActualMeshLOD(mesh_params, lod);
+}
+
+U32 LLMeshRepository::calcResourceCost(LLSD& header)
+{
+ U32 bytes = 0;
+
+ for (U32 i = 0; i < 4; i++)
+ {
+ bytes += header[header_lod[i]]["size"].asInteger();
+ }
+
+ bytes += header["skin"]["size"].asInteger();
+
+ return bytes/4096 + 1;
+}
+
+U32 LLMeshRepository::getResourceCost(const LLUUID& mesh_id)
+{
+ return mThread->getResourceCost(mesh_id);
+}
+
+const LLMeshSkinInfo* LLMeshRepository::getSkinInfo(const LLUUID& mesh_id)
+{
+ if (mesh_id.notNull())
+ {
+ skin_map::iterator iter = mSkinMap.find(mesh_id);
+ if (iter != mSkinMap.end())
+ {
+ return &(iter->second);
+ }
+
+ //no skin info known about given mesh, try to fetch it
+ {
+ LLMutexLock lock(mMeshMutex);
+ //add volume to list of loading meshes
+ std::set<LLUUID>::iterator iter = mLoadingSkins.find(mesh_id);
+ if (iter == mLoadingSkins.end())
+ { //no request pending for this skin info
+ mLoadingSkins.insert(mesh_id);
+ mPendingSkinRequests.push(mesh_id);
+ }
+ }
+ }
+
+ return NULL;
+}
+
+void LLMeshRepository::fetchPhysicsShape(const LLUUID& mesh_id)
+{
+ if (mesh_id.notNull())
+ {
+ LLMeshDecomposition* decomp = NULL;
+ decomposition_map::iterator iter = mDecompositionMap.find(mesh_id);
+ if (iter != mDecompositionMap.end())
+ {
+ decomp = iter->second;
+ }
+
+ //decomposition block hasn't been fetched yet
+ if (!decomp || decomp->mPhysicsShapeMesh.isNull())
+ {
+ LLMutexLock lock(mMeshMutex);
+ //add volume to list of loading meshes
+ std::set<LLUUID>::iterator iter = mLoadingPhysicsShapes.find(mesh_id);
+ if (iter == mLoadingPhysicsShapes.end())
+ { //no request pending for this skin info
+ mLoadingPhysicsShapes.insert(mesh_id);
+ mPendingPhysicsShapeRequests.push(mesh_id);
+ }
+ }
+ }
+
+}
+
+const LLMeshDecomposition* LLMeshRepository::getDecomposition(const LLUUID& mesh_id)
+{
+ LLMeshDecomposition* ret = NULL;
+
+ if (mesh_id.notNull())
+ {
+ decomposition_map::iterator iter = mDecompositionMap.find(mesh_id);
+ if (iter != mDecompositionMap.end())
+ {
+ ret = iter->second;
+ }
+
+ //decomposition block hasn't been fetched yet
+ if (!ret || ret->mBaseHullMesh.isNull())
+ {
+ LLMutexLock lock(mMeshMutex);
+ //add volume to list of loading meshes
+ std::set<LLUUID>::iterator iter = mLoadingDecompositions.find(mesh_id);
+ if (iter == mLoadingDecompositions.end())
+ { //no request pending for this skin info
+ mLoadingDecompositions.insert(mesh_id);
+ mPendingDecompositionRequests.push(mesh_id);
+ }
+ }
+ }
+
+ return ret;
+}
+
+void LLMeshRepository::buildHull(const LLVolumeParams& params, S32 detail)
+{
+ LLVolume* volume = LLPrimitive::sVolumeManager->refVolume(params, detail);
+
+ if (!volume->mHullPoints)
+ {
+ //all default params
+ //execute first stage
+ //set simplify mode to retain
+ //set retain percentage to zero
+ //run second stage
+ }
+
+ LLPrimitive::sVolumeManager->unrefVolume(volume);
+}
+
+bool LLMeshRepository::hasPhysicsShape(const LLUUID& mesh_id)
+{
+ LLSD mesh = mThread->getMeshHeader(mesh_id);
+ return mesh.has("physics_shape") && mesh["physics_shape"].has("size") && (mesh["physics_shape"]["size"].asInteger() > 0);
+}
+
+const LLSD& LLMeshRepository::getMeshHeader(const LLUUID& mesh_id)
+{
+ return mThread->getMeshHeader(mesh_id);
+}
+
+const LLSD& LLMeshRepoThread::getMeshHeader(const LLUUID& mesh_id)
+{
+ static LLSD dummy_ret;
+ if (mesh_id.notNull())
+ {
+ LLMutexLock lock(mHeaderMutex);
+ mesh_header_map::iterator iter = mMeshHeader.find(mesh_id);
+ if (iter != mMeshHeader.end())
+ {
+ return iter->second;
+ }
+ }
+
+ return dummy_ret;
+}
+
+
+void LLMeshRepository::uploadModel(std::vector<LLModelInstance>& data, LLVector3& scale, bool upload_textures,
+ bool upload_skin, bool upload_joints)
+{
+ LLMeshUploadThread* thread = new LLMeshUploadThread(data, scale, upload_textures, upload_skin, upload_joints);
+ mUploadWaitList.push_back(thread);
+}
+
+S32 LLMeshRepository::getMeshSize(const LLUUID& mesh_id, S32 lod)
+{
+ if (mThread)
+ {
+ LLMeshRepoThread::mesh_header_map::iterator iter = mThread->mMeshHeader.find(mesh_id);
+ if (iter != mThread->mMeshHeader.end())
+ {
+ LLSD& header = iter->second;
+
+ if (header.has("404"))
+ {
+ return -1;
+ }
+
+ S32 size = header[header_lod[lod]]["size"].asInteger();
+ return size;
+ }
+
+ }
+
+ return -1;
+
+}
+
+void LLMeshUploadThread::sendCostRequest(LLMeshUploadData& data)
+{
+ //write model file to memory buffer
+ std::stringstream ostr;
+
+ LLModel::convex_hull_decomposition& decomp =
+ data.mModel[LLModel::LOD_PHYSICS].notNull() ?
+ data.mModel[LLModel::LOD_PHYSICS]->mConvexHullDecomp :
+ data.mBaseModel->mConvexHullDecomp;
+
+ LLModel::hull dummy_hull;
+
+ LLSD header = LLModel::writeModel(
+ ostr,
+ data.mModel[LLModel::LOD_PHYSICS],
+ data.mModel[LLModel::LOD_HIGH],
+ data.mModel[LLModel::LOD_MEDIUM],
+ data.mModel[LLModel::LOD_LOW],
+ data.mModel[LLModel::LOD_IMPOSTOR],
+ decomp,
+ dummy_hull,
+ mUploadSkin,
+ mUploadJoints,
+ true);
+
+ std::string desc = data.mBaseModel->mLabel;
+
+ // Grab the total vertex count of the model
+ // along with other information for the "asset_resources" map
+ // to send to the server.
+ LLSD asset_resources = LLSD::emptyMap();
+
+
+ std::string url = mNewInventoryCapability;
+
+ if (!url.empty())
+ {
+ LLSD body = generate_new_resource_upload_capability_body(
+ LLAssetType::AT_MESH,
+ desc,
+ desc,
+ LLFolderType::FT_MESH,
+ LLInventoryType::IT_MESH,
+ LLFloaterPerms::getNextOwnerPerms(),
+ LLFloaterPerms::getGroupPerms(),
+ LLFloaterPerms::getEveryonePerms());
+
+ body["asset_resources"] = asset_resources;
+
+ mPendingConfirmations++;
+ LLCurlRequest::headers_t headers;
+
+ data.mPostData = body;
+
+ mCurlRequest->post(url, headers, body, new LLMeshCostResponder(data, this));
+ }
+}
+
+void LLMeshUploadThread::sendCostRequest(LLTextureUploadData& data)
+{
+ if (data.mTexture && data.mTexture->getDiscardLevel() >= 0)
+ {
+ LLSD asset_resources = LLSD::emptyMap();
+
+ std::string url = mNewInventoryCapability;
+
+ if (!url.empty())
+ {
+ LLSD body = generate_new_resource_upload_capability_body(
+ LLAssetType::AT_TEXTURE,
+ data.mLabel,
+ data.mLabel,
+ LLFolderType::FT_TEXTURE,
+ LLInventoryType::IT_TEXTURE,
+ LLFloaterPerms::getNextOwnerPerms(),
+ LLFloaterPerms::getGroupPerms(),
+ LLFloaterPerms::getEveryonePerms());
+
+ body["asset_resources"] = asset_resources;
+
+ mPendingConfirmations++;
+ LLCurlRequest::headers_t headers;
+
+ data.mPostData = body;
+ mCurlRequest->post(url, headers, body, new LLTextureCostResponder(data, this));
+ }
+ }
+}
+
+
+void LLMeshUploadThread::doUploadModel(LLMeshUploadData& data)
+{
+ if (!data.mRSVP.empty())
+ {
+ std::stringstream ostr;
+
+ LLModel::convex_hull_decomposition& decomp =
+ data.mModel[LLModel::LOD_PHYSICS].notNull() ?
+ data.mModel[LLModel::LOD_PHYSICS]->mConvexHullDecomp :
+ data.mBaseModel->mConvexHullDecomp;
+
+ LLModel::writeModel(
+ ostr,
+ data.mModel[LLModel::LOD_PHYSICS],
+ data.mModel[LLModel::LOD_HIGH],
+ data.mModel[LLModel::LOD_MEDIUM],
+ data.mModel[LLModel::LOD_LOW],
+ data.mModel[LLModel::LOD_IMPOSTOR],
+ decomp,
+ mHullMap[data.mBaseModel],
+ mUploadSkin,
+ mUploadJoints);
+
+ data.mAssetData = ostr.str();
+
+ LLCurlRequest::headers_t headers;
+ mPendingUploads++;
+
+ mCurlRequest->post(data.mRSVP, headers, data.mAssetData, new LLMeshUploadResponder(data, this));
+ }
+}
+
+void LLMeshUploadThread::doUploadTexture(LLTextureUploadData& data)
+{
+ if (!data.mRSVP.empty())
+ {
+ std::stringstream ostr;
+
+ if (!data.mTexture->isRawImageValid())
+ {
+ data.mTexture->reloadRawImage(data.mTexture->getDiscardLevel());
+ }
+
+ LLPointer<LLImageJ2C> upload_file = LLViewerTextureList::convertToUploadFile(data.mTexture->getRawImage());
+
+ ostr.write((const char*) upload_file->getData(), upload_file->getDataSize());
+
+ data.mAssetData = ostr.str();
+
+ LLCurlRequest::headers_t headers;
+ mPendingUploads++;
+
+ mCurlRequest->post(data.mRSVP, headers, data.mAssetData, new LLTextureUploadResponder(data, this));
+ }
+}
+
+
+void LLMeshUploadThread::onModelUploaded(LLMeshUploadData& data)
+{
+ createObjects(data);
+}
+
+void LLMeshUploadThread::onTextureUploaded(LLTextureUploadData& data)
+{
+ mTextureMap[data.mTexture] = data;
+}
+
+
+void LLMeshUploadThread::createObjects(LLMeshUploadData& data)
+{
+ instance_list& instances = mInstance[data.mBaseModel];
+
+ for (instance_list::iterator iter = instances.begin(); iter != instances.end(); ++iter)
+ { //create prims that reference given mesh
+ LLModelInstance& instance = *iter;
+ instance.mMeshID = data.mUUID;
+ mInstanceQ.push(instance);
+ }
+}
+
+LLSD LLMeshUploadThread::createObject(LLModelInstance& instance)
+{
+ LLMatrix4 transformation = instance.mTransform;
+
+ if (instance.mMeshID.isNull())
+ {
+ llerrs << "WTF?" << llendl;
+ }
+
+ // check for reflection
+ BOOL reflected = (transformation.determinant() < 0);
+
+ // compute position
+ LLVector3 position = LLVector3(0, 0, 0) * transformation;
+
+ // compute scale
+ LLVector3 x_transformed = LLVector3(1, 0, 0) * transformation - position;
+ LLVector3 y_transformed = LLVector3(0, 1, 0) * transformation - position;
+ LLVector3 z_transformed = LLVector3(0, 0, 1) * transformation - position;
+ F32 x_length = x_transformed.normalize();
+ F32 y_length = y_transformed.normalize();
+ F32 z_length = z_transformed.normalize();
+ LLVector3 scale = LLVector3(x_length, y_length, z_length);
+
+ // adjust for "reflected" geometry
+ LLVector3 x_transformed_reflected = x_transformed;
+ if (reflected)
+ {
+ x_transformed_reflected *= -1.0;
+ }
+
+ // compute rotation
+ LLMatrix3 rotation_matrix;
+ rotation_matrix.setRows(x_transformed_reflected, y_transformed, z_transformed);
+ LLQuaternion quat_rotation = rotation_matrix.quaternion();
+ quat_rotation.normalize(); // the rotation_matrix might not have been orthoginal. make it so here.
+ LLVector3 euler_rotation;
+ quat_rotation.getEulerAngles(&euler_rotation.mV[VX], &euler_rotation.mV[VY], &euler_rotation.mV[VZ]);
+
+ //
+ // build parameter block to construct this prim
+ //
+
+ LLSD object_params;
+
+ // create prim
+
+ // set volume params
+ U8 sculpt_type = LL_SCULPT_TYPE_MESH;
+ if (reflected)
+ {
+ sculpt_type |= LL_SCULPT_FLAG_MIRROR;
+ }
+ LLVolumeParams volume_params;
+ volume_params.setType( LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE );
+ volume_params.setBeginAndEndS( 0.f, 1.f );
+ volume_params.setBeginAndEndT( 0.f, 1.f );
+ volume_params.setRatio ( 1, 1 );
+ volume_params.setShear ( 0, 0 );
+ volume_params.setSculptID(instance.mMeshID, sculpt_type);
+ object_params["shape"] = volume_params.asLLSD();
+
+ object_params["material"] = LL_MCODE_WOOD;
+
+ object_params["group-id"] = gAgent.getGroupID();
+ object_params["pos"] = ll_sd_from_vector3(position + mOrigin);
+ object_params["rotation"] = ll_sd_from_quaternion(quat_rotation);
+ object_params["scale"] = ll_sd_from_vector3(scale);
+ object_params["name"] = instance.mLabel;
+
+ // load material from dae file
+ object_params["facelist"] = LLSD::emptyArray();
+ for (S32 i = 0; i < instance.mMaterial.size(); i++)
+ {
+ LLTextureEntry te;
+ LLImportMaterial& mat = instance.mMaterial[i];
+
+ te.setColor(mat.mDiffuseColor);
+
+ LLUUID diffuse_id = mTextureMap[mat.mDiffuseMap].mUUID;
+
+ if (diffuse_id.notNull())
+ {
+ te.setID(diffuse_id);
+ }
+ else
+ {
+ te.setID(LLUUID("5748decc-f629-461c-9a36-a35a221fe21f")); // blank texture
+ }
+
+ te.setFullbright(mat.mFullbright);
+
+ object_params["facelist"][i] = te.asLLSD();
+ }
+
+ // set extra parameters
+ LLSculptParams sculpt_params;
+ sculpt_params.setSculptTexture(instance.mMeshID);
+ sculpt_params.setSculptType(sculpt_type);
+ U8 buffer[MAX_OBJECT_PARAMS_SIZE+1];
+ LLDataPackerBinaryBuffer dp(buffer, MAX_OBJECT_PARAMS_SIZE);
+ sculpt_params.pack(dp);
+ std::vector<U8> v(dp.getCurrentSize());
+ memcpy(&v[0], buffer, dp.getCurrentSize());
+ LLSD extra_parameter;
+ extra_parameter["extra_parameter"] = sculpt_params.mType;
+ extra_parameter["param_data"] = v;
+ object_params["extra_parameters"].append(extra_parameter);
+
+ LLPermissions perm;
+ perm.setOwnerAndGroup(gAgent.getID(), gAgent.getID(), LLUUID::null, false);
+ perm.setCreator(gAgent.getID());
+
+ perm.initMasks(PERM_ITEM_UNRESTRICTED | PERM_MOVE, //base
+ PERM_ITEM_UNRESTRICTED | PERM_MOVE, //owner
+ LLFloaterPerms::getEveryonePerms(),
+ LLFloaterPerms::getGroupPerms(),
+ LLFloaterPerms::getNextOwnerPerms());
+
+ object_params["permissions"] = ll_create_sd_from_permissions(perm);
+
+ object_params["physics_shape_type"] = (U8)(LLViewerObject::PHYSICS_SHAPE_CONVEX_HULL);
+
+ return object_params;
+}
+
+void LLMeshUploadThread::priceResult(LLMeshUploadData& data, const LLSD& content)
+{
+ mPendingCost += content["upload_price"].asInteger();
+ data.mRSVP = content["rsvp"].asString();
+
+ mConfirmedQ.push(data);
+}
+
+void LLMeshUploadThread::priceResult(LLTextureUploadData& data, const LLSD& content)
+{
+ mPendingCost += content["upload_price"].asInteger();
+ data.mRSVP = content["rsvp"].asString();
+
+ mConfirmedTextureQ.push(data);
+}
+
+
+bool LLImportMaterial::operator<(const LLImportMaterial &rhs) const
+{
+ if (mDiffuseMap != rhs.mDiffuseMap)
+ {
+ return mDiffuseMap < rhs.mDiffuseMap;
+ }
+
+ if (mDiffuseMapFilename != rhs.mDiffuseMapFilename)
+ {
+ return mDiffuseMapFilename < rhs.mDiffuseMapFilename;
+ }
+
+ if (mDiffuseMapLabel != rhs.mDiffuseMapLabel)
+ {
+ return mDiffuseMapLabel < rhs.mDiffuseMapLabel;
+ }
+
+ if (mDiffuseColor != rhs.mDiffuseColor)
+ {
+ return mDiffuseColor < rhs.mDiffuseColor;
+ }
+
+ return mFullbright < rhs.mFullbright;
+}
+
+
+void LLMeshRepository::updateInventory(inventory_data data)
+{
+ LLMutexLock lock(mMeshMutex);
+ mInventoryQ.push(data);
+}
+
+void LLMeshRepository::uploadError(LLSD& args)
+{
+ LLMutexLock lock(mMeshMutex);
+ mUploadErrorQ.push(args);
+}
+
+//static
+F32 LLMeshRepository::getStreamingCost(const LLSD& header, F32 radius)
+{
+ F32 dlowest = llmin(radius/0.06f, 256.f);
+ F32 dlow = llmin(radius/0.24f, 256.f);
+ F32 dmid = llmin(radius/1.0f, 256.f);
+
+ F32 bytes_lowest = header["lowest_lod"]["size"].asReal()/1024.f;
+ F32 bytes_low = header["low_lod"]["size"].asReal()/1024.f;
+ F32 bytes_mid = header["medium_lod"]["size"].asReal()/1024.f;
+ F32 bytes_high = header["high_lod"]["size"].asReal()/1024.f;
+
+ if (bytes_high == 0.f)
+ {
+ return 0.f;
+ }
+
+ if (bytes_mid == 0.f)
+ {
+ bytes_mid = bytes_high;
+ }
+
+ if (bytes_low == 0.f)
+ {
+ bytes_low = bytes_mid;
+ }
+
+ if (bytes_lowest == 0.f)
+ {
+ bytes_lowest = bytes_low;
+ }
+
+ F32 max_area = 65536.f;
+ F32 min_area = 1.f;
+
+ F32 high_area = llmin(F_PI*dmid*dmid, max_area);
+ F32 mid_area = llmin(F_PI*dlow*dlow, max_area);
+ F32 low_area = llmin(F_PI*dlowest*dlowest, max_area);
+ F32 lowest_area = max_area;
+
+ lowest_area -= low_area;
+ low_area -= mid_area;
+ mid_area -= high_area;
+
+ high_area = llclamp(high_area, min_area, max_area);
+ mid_area = llclamp(mid_area, min_area, max_area);
+ low_area = llclamp(low_area, min_area, max_area);
+ lowest_area = llclamp(lowest_area, min_area, max_area);
+
+ F32 total_area = high_area + mid_area + low_area + lowest_area;
+ high_area /= total_area;
+ mid_area /= total_area;
+ low_area /= total_area;
+ lowest_area /= total_area;
+
+ F32 weighted_avg = bytes_high*high_area +
+ bytes_mid*mid_area +
+ bytes_low*low_area +
+ bytes_lowest*lowest_area;
+
+ return weighted_avg * gSavedSettings.getF32("MeshStreamingCostScaler");
+}
+
+
+LLPhysicsDecomp::LLPhysicsDecomp()
+: LLThread("Physics Decomp")
+{
+ mInited = false;
+ mQuitting = false;
+ mDone = false;
+
+ mSignal = new LLCondition(NULL);
+ mMutex = new LLMutex(NULL);
+}
+
+LLPhysicsDecomp::~LLPhysicsDecomp()
+{
+ shutdown();
+
+ delete mSignal;
+ mSignal = NULL;
+ delete mMutex;
+ mMutex = NULL;
+}
+
+void LLPhysicsDecomp::shutdown()
+{
+ if (mSignal)
+ {
+ mQuitting = true;
+ mSignal->signal();
+
+ while (!isStopped())
+ {
+ apr_sleep(10);
+ }
+ }
+}
+
+void LLPhysicsDecomp::submitRequest(LLPhysicsDecomp::Request* request)
+{
+ LLMutexLock lock(mMutex);
+ mRequestQ.push(request);
+ mSignal->signal();
+}
+
+//static
+S32 LLPhysicsDecomp::llcdCallback(const char* status, S32 p1, S32 p2)
+{
+ if (gMeshRepo.mDecompThread && gMeshRepo.mDecompThread->mCurRequest.notNull())
+ {
+ return gMeshRepo.mDecompThread->mCurRequest->statusCallback(status, p1, p2);
+ }
+
+ return 1;
+}
+
+void LLPhysicsDecomp::setMeshData(LLCDMeshData& mesh)
+{
+ mesh.mVertexBase = mCurRequest->mPositions[0].mV;
+ mesh.mVertexStrideBytes = 12;
+ mesh.mNumVertices = mCurRequest->mPositions.size();
+
+ mesh.mIndexType = LLCDMeshData::INT_16;
+ mesh.mIndexBase = &(mCurRequest->mIndices[0]);
+ mesh.mIndexStrideBytes = 6;
+
+ mesh.mNumTriangles = mCurRequest->mIndices.size()/3;
+
+ LLCDResult ret = LLCD_OK;
+ if (LLConvexDecomposition::getInstance() != NULL)
+ {
+ ret = LLConvexDecomposition::getInstance()->setMeshData(&mesh);
+ }
+
+ if (ret)
+ {
+ llerrs << "Convex Decomposition thread valid but could not set mesh data" << llendl;
+ }
+}
+
+void LLPhysicsDecomp::doDecomposition()
+{
+ LLCDMeshData mesh;
+ S32 stage = mStageID[mCurRequest->mStage];
+
+ //load data intoLLCD
+ if (stage == 0)
+ {
+ setMeshData(mesh);
+ }
+
+ //build parameter map
+ std::map<std::string, const LLCDParam*> param_map;
+
+ static const LLCDParam* params = NULL;
+ static S32 param_count = 0;
+ if (!params)
+ {
+ param_count = LLConvexDecomposition::getInstance()->getParameters(&params);
+ }
+
+ for (S32 i = 0; i < param_count; ++i)
+ {
+ param_map[params[i].mName] = params+i;
+ }
+
+ //set parameter values
+ for (decomp_params::iterator iter = mCurRequest->mParams.begin(); iter != mCurRequest->mParams.end(); ++iter)
+ {
+ const std::string& name = iter->first;
+ const LLSD& value = iter->second;
+
+ const LLCDParam* param = param_map[name];
+
+ if (param == NULL)
+ { //couldn't find valid parameter
+ continue;
+ }
+
+ U32 ret = LLCD_OK;
+
+ if (param->mType == LLCDParam::LLCD_FLOAT)
+ {
+ ret = LLConvexDecomposition::getInstance()->setParam(param->mName, (F32) value.asReal());
+ }
+ else if (param->mType == LLCDParam::LLCD_INTEGER ||
+ param->mType == LLCDParam::LLCD_ENUM)
+ {
+ ret = LLConvexDecomposition::getInstance()->setParam(param->mName, value.asInteger());
+ }
+ else if (param->mType == LLCDParam::LLCD_BOOLEAN)
+ {
+ ret = LLConvexDecomposition::getInstance()->setParam(param->mName, value.asBoolean());
+ }
+
+ if (ret)
+ {
+ llerrs << "WTF?" << llendl;
+ }
+ }
+
+ mCurRequest->setStatusMessage("Executing.");
+
+ LLCDResult ret = LLCD_OK;
+
+ if (LLConvexDecomposition::getInstance() != NULL)
+ {
+ ret = LLConvexDecomposition::getInstance()->executeStage(stage);
+ }
+
+ if (ret)
+ {
+ llwarns << "Convex Decomposition thread valid but could not execute stage " << stage << llendl;
+ LLMutexLock lock(mMutex);
+
+ mCurRequest->mHull.clear();
+ mCurRequest->mHullMesh.clear();
+
+ mCurRequest->setStatusMessage("FAIL");
+
+ completeCurrent();
+ }
+ else
+ {
+ mCurRequest->setStatusMessage("Reading results");
+
+ S32 num_hulls =0;
+ if (LLConvexDecomposition::getInstance() != NULL)
+ {
+ num_hulls = LLConvexDecomposition::getInstance()->getNumHullsFromStage(stage);
+ }
+
+ mMutex->lock();
+ mCurRequest->mHull.clear();
+ mCurRequest->mHull.resize(num_hulls);
+
+ mCurRequest->mHullMesh.clear();
+ mCurRequest->mHullMesh.resize(num_hulls);
+ mMutex->unlock();
+
+ for (S32 i = 0; i < num_hulls; ++i)
+ {
+ std::vector<LLVector3> p;
+ LLCDHull hull;
+ // if LLConvexDecomposition is a stub, num_hulls should have been set to 0 above, and we should not reach this code
+ LLConvexDecomposition::getInstance()->getHullFromStage(stage, i, &hull);
+
+ const F32* v = hull.mVertexBase;
+
+ for (S32 j = 0; j < hull.mNumVertices; ++j)
+ {
+ LLVector3 vert(v[0], v[1], v[2]);
+ p.push_back(vert);
+ v = (F32*) (((U8*) v) + hull.mVertexStrideBytes);
+ }
+
+ LLCDMeshData mesh;
+ // if LLConvexDecomposition is a stub, num_hulls should have been set to 0 above, and we should not reach this code
+ LLConvexDecomposition::getInstance()->getMeshFromStage(stage, i, &mesh);
+
+ mCurRequest->mHullMesh[i] = get_vertex_buffer_from_mesh(mesh);
+
+ mMutex->lock();
+ mCurRequest->mHull[i] = p;
+ mMutex->unlock();
+ }
+
+ {
+ LLMutexLock lock(mMutex);
+
+ mCurRequest->setStatusMessage("FAIL");
+ completeCurrent();
+ }
+ }
+}
+
+void LLPhysicsDecomp::completeCurrent()
+{
+ LLMutexLock lock(mMutex);
+ mCompletedQ.push(mCurRequest);
+ mCurRequest = NULL;
+}
+
+void LLPhysicsDecomp::notifyCompleted()
+{
+ if (!mCompletedQ.empty())
+ {
+ LLMutexLock lock(mMutex);
+ while (!mCompletedQ.empty())
+ {
+ Request* req = mCompletedQ.front();
+ req->completed();
+ mCompletedQ.pop();
+ }
+ }
+}
+
+
+void make_box(LLPhysicsDecomp::Request * request)
+{
+ LLVector3 min,max;
+ min = request->mPositions[0];
+ max = min;
+
+ for (U32 i = 0; i < request->mPositions.size(); ++i)
+ {
+ update_min_max(min, max, request->mPositions[i]);
+ }
+
+ request->mHull.clear();
+
+ LLModel::hull box;
+ box.push_back(LLVector3(min[0],min[1],min[2]));
+ box.push_back(LLVector3(max[0],min[1],min[2]));
+ box.push_back(LLVector3(min[0],max[1],min[2]));
+ box.push_back(LLVector3(max[0],max[1],min[2]));
+ box.push_back(LLVector3(min[0],min[1],max[2]));
+ box.push_back(LLVector3(max[0],min[1],max[2]));
+ box.push_back(LLVector3(min[0],max[1],max[2]));
+ box.push_back(LLVector3(max[0],max[1],max[2]));
+
+ request->mHull.push_back(box);
+}
+
+
+void LLPhysicsDecomp::doDecompositionSingleHull()
+{
+ LLCDMeshData mesh;
+
+ setMeshData(mesh);
+
+
+ //set all parameters to default
+ std::map<std::string, const LLCDParam*> param_map;
+
+ static const LLCDParam* params = NULL;
+ static S32 param_count = 0;
+
+ if (!params)
+ {
+ param_count = LLConvexDecomposition::getInstance()->getParameters(&params);
+ }
+
+ LLConvexDecomposition* decomp = LLConvexDecomposition::getInstance();
+
+ for (S32 i = 0; i < param_count; ++i)
+ {
+ decomp->setParam(params[i].mName, params[i].mDefault.mIntOrEnumValue);
+ }
+
+ const S32 STAGE_DECOMPOSE = mStageID["Decompose"];
+ const S32 STAGE_SIMPLIFY = mStageID["Simplify"];
+ const S32 DECOMP_PREVIEW = 0;
+ const S32 SIMPLIFY_RETAIN = 0;
+
+ decomp->setParam("Decompose Quality", DECOMP_PREVIEW);
+ decomp->setParam("Simplify Method", SIMPLIFY_RETAIN);
+ decomp->setParam("Retain%", 0.f);
+
+ LLCDResult ret = LLCD_OK;
+ ret = decomp->executeStage(STAGE_DECOMPOSE);
+
+ if (ret)
+ {
+ llwarns << "Could not execute decomposition stage when attempting to create single hull." << llendl;
+ make_box(mCurRequest);
+ }
+ else
+ {
+ ret = decomp->executeStage(STAGE_SIMPLIFY);
+
+ if (ret)
+ {
+ llwarns << "Could not execute simiplification stage when attempting to create single hull." << llendl;
+ make_box(mCurRequest);
+ }
+ else
+ {
+ S32 num_hulls =0;
+ if (LLConvexDecomposition::getInstance() != NULL)
+ {
+ num_hulls = LLConvexDecomposition::getInstance()->getNumHullsFromStage(STAGE_SIMPLIFY);
+ }
+
+ mMutex->lock();
+ mCurRequest->mHull.clear();
+ mCurRequest->mHull.resize(num_hulls);
+ mCurRequest->mHullMesh.clear();
+ mMutex->unlock();
+
+ for (S32 i = 0; i < num_hulls; ++i)
+ {
+ std::vector<LLVector3> p;
+ LLCDHull hull;
+ // if LLConvexDecomposition is a stub, num_hulls should have been set to 0 above, and we should not reach this code
+ LLConvexDecomposition::getInstance()->getHullFromStage(STAGE_SIMPLIFY, i, &hull);
+
+ const F32* v = hull.mVertexBase;
+
+ for (S32 j = 0; j < hull.mNumVertices; ++j)
+ {
+ LLVector3 vert(v[0], v[1], v[2]);
+ p.push_back(vert);
+ v = (F32*) (((U8*) v) + hull.mVertexStrideBytes);
+ }
+
+ mMutex->lock();
+ mCurRequest->mHull[i] = p;
+ mMutex->unlock();
+ }
+ }
+ }
+
+
+ {
+ completeCurrent();
+
+ }
+}
+
+
+void LLPhysicsDecomp::run()
+{
+ LLConvexDecomposition* decomp = LLConvexDecomposition::getInstance();
+ decomp->initThread();
+ mInited = true;
+
+ static const LLCDStageData* stages = NULL;
+ static S32 num_stages = 0;
+
+ if (!stages)
+ {
+ num_stages = decomp->getStages(&stages);
+ }
+
+ for (S32 i = 0; i < num_stages; i++)
+ {
+ mStageID[stages[i].mName] = i;
+ }
+
+ while (!mQuitting)
+ {
+ mSignal->wait();
+ while (!mQuitting && !mRequestQ.empty())
+ {
+ {
+ LLMutexLock lock(mMutex);
+ mCurRequest = mRequestQ.front();
+ mRequestQ.pop();
+ }
+
+ S32& id = *(mCurRequest->mDecompID);
+ if (id == -1)
+ {
+ decomp->genDecomposition(id);
+ }
+ decomp->bindDecomposition(id);
+
+ if (mCurRequest->mStage == "single_hull")
+ {
+ doDecompositionSingleHull();
+ }
+ else
+ {
+ doDecomposition();
+ }
+ }
+ }
+
+ decomp->quitThread();
+
+ if (mSignal->isLocked())
+ { //let go of mSignal's associated mutex
+ mSignal->unlock();
+ }
+
+ mDone = true;
+}
+
+void LLPhysicsDecomp::Request::setStatusMessage(const std::string& msg)
+{
+ mStatusMessage = msg;
+}
+
diff --git a/indra/newview/llmeshrepository.h b/indra/newview/llmeshrepository.h
new file mode 100644
index 0000000000..ccdcc03310
--- /dev/null
+++ b/indra/newview/llmeshrepository.h
@@ -0,0 +1,553 @@
+/**
+ * @file llmeshrepository.h
+ * @brief Client-side repository of mesh assets.
+ *
+ * $LicenseInfo:firstyear=2001&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#ifndef LL_MESH_REPOSITORY_H
+#define LL_MESH_REPOSITORY_H
+
+#include "llassettype.h"
+#include "llmodel.h"
+#include "lluuid.h"
+#include "llviewertexture.h"
+#include "llvolume.h"
+
+#define LLCONVEXDECOMPINTER_STATIC 1
+
+#include "llconvexdecomposition.h"
+
+class LLVOVolume;
+class LLMeshResponder;
+class LLCurlRequest;
+class LLMutex;
+class LLCondition;
+class LLVFS;
+class LLMeshRepository;
+
+class LLMeshUploadData
+{
+public:
+ LLPointer<LLModel> mBaseModel;
+ LLPointer<LLModel> mModel[5];
+ LLUUID mUUID;
+ U32 mRetries;
+ std::string mRSVP;
+ std::string mAssetData;
+ LLSD mPostData;
+
+ LLMeshUploadData()
+ {
+ mRetries = 0;
+ }
+};
+
+class LLTextureUploadData
+{
+public:
+ LLViewerFetchedTexture* mTexture;
+ LLUUID mUUID;
+ std::string mRSVP;
+ std::string mLabel;
+ U32 mRetries;
+ std::string mAssetData;
+ LLSD mPostData;
+
+ LLTextureUploadData()
+ {
+ mRetries = 0;
+ }
+
+ LLTextureUploadData(LLViewerFetchedTexture* texture, std::string& label)
+ : mTexture(texture), mLabel(label)
+ {
+ mRetries = 0;
+ }
+};
+
+class LLImportMaterial
+{
+public:
+ LLPointer<LLViewerFetchedTexture> mDiffuseMap;
+ std::string mDiffuseMapFilename;
+ std::string mDiffuseMapLabel;
+ LLColor4 mDiffuseColor;
+ bool mFullbright;
+
+ bool operator<(const LLImportMaterial &params) const;
+
+ LLImportMaterial()
+ : mFullbright(false)
+ {
+ mDiffuseColor.set(1,1,1,1);
+ }
+};
+
+class LLModelInstance
+{
+public:
+ LLPointer<LLModel> mModel;
+ LLPointer<LLModel> mLOD[5];
+
+ std::string mLabel;
+
+ LLUUID mMeshID;
+
+ LLMatrix4 mTransform;
+ std::vector<LLImportMaterial> mMaterial;
+
+ LLModelInstance(LLModel* model, const std::string& label, LLMatrix4& transform, std::vector<LLImportMaterial>& materials)
+ : mModel(model), mLabel(label), mTransform(transform), mMaterial(materials)
+ {
+ }
+};
+
+class LLMeshSkinInfo
+{
+public:
+ LLUUID mMeshID;
+ std::vector<std::string> mJointNames;
+ std::vector<LLMatrix4> mInvBindMatrix;
+ std::vector<LLMatrix4> mAlternateBindMatrix;
+
+ LLMatrix4 mBindShapeMatrix;
+ float mPelvisOffset;
+};
+
+class LLMeshDecomposition
+{
+public:
+ LLMeshDecomposition() { }
+
+ void merge(const LLMeshDecomposition* rhs);
+
+ LLUUID mMeshID;
+ LLModel::convex_hull_decomposition mHull;
+ LLModel::hull mBaseHull;
+
+ std::vector<LLPointer<LLVertexBuffer> > mMesh;
+ LLPointer<LLVertexBuffer> mBaseHullMesh;
+ LLPointer<LLVertexBuffer> mPhysicsShapeMesh;
+};
+
+class LLPhysicsDecomp : public LLThread
+{
+public:
+
+ typedef std::map<std::string, LLSD> decomp_params;
+
+ class Request : public LLRefCount
+ {
+ public:
+ //input params
+ S32* mDecompID;
+ std::string mStage;
+ std::vector<LLVector3> mPositions;
+ std::vector<U16> mIndices;
+ decomp_params mParams;
+
+ //output state
+ std::string mStatusMessage;
+ std::vector<LLPointer<LLVertexBuffer> > mHullMesh;
+ LLModel::convex_hull_decomposition mHull;
+
+ //status message callback, called from decomposition thread
+ virtual S32 statusCallback(const char* status, S32 p1, S32 p2) = 0;
+
+ //completed callback, called from the main thread
+ virtual void completed() = 0;
+
+ virtual void setStatusMessage(const std::string& msg);
+ };
+
+ LLCondition* mSignal;
+ LLMutex* mMutex;
+
+ bool mInited;
+ bool mQuitting;
+ bool mDone;
+
+ LLPhysicsDecomp();
+ ~LLPhysicsDecomp();
+
+ void shutdown();
+
+ void submitRequest(Request* request);
+ static S32 llcdCallback(const char*, S32, S32);
+ void cancel();
+
+ void setMeshData(LLCDMeshData& mesh);
+ void doDecomposition();
+ void doDecompositionSingleHull();
+
+ virtual void run();
+
+ void completeCurrent();
+ void notifyCompleted();
+
+ std::map<std::string, S32> mStageID;
+
+ typedef std::queue<LLPointer<Request> > request_queue;
+ request_queue mRequestQ;
+
+ LLPointer<Request> mCurRequest;
+
+ std::queue<LLPointer<Request> > mCompletedQ;
+
+};
+
+class LLMeshRepoThread : public LLThread
+{
+public:
+
+ static S32 sActiveHeaderRequests;
+ static S32 sActiveLODRequests;
+ static U32 sMaxConcurrentRequests;
+
+ LLCurlRequest* mCurlRequest;
+ LLMutex* mMutex;
+ LLMutex* mHeaderMutex;
+ LLCondition* mSignal;
+
+ bool mWaiting;
+
+ //map of known mesh headers
+ typedef std::map<LLUUID, LLSD> mesh_header_map;
+ mesh_header_map mMeshHeader;
+
+ std::map<LLUUID, U32> mMeshHeaderSize;
+ std::map<LLUUID, U32> mMeshResourceCost;
+
+ class HeaderRequest
+ {
+ public:
+ const LLVolumeParams mMeshParams;
+
+ HeaderRequest(const LLVolumeParams& mesh_params)
+ : mMeshParams(mesh_params)
+ {
+ }
+
+ bool operator<(const HeaderRequest& rhs) const
+ {
+ return mMeshParams < rhs.mMeshParams;
+ }
+ };
+
+ class LODRequest
+ {
+ public:
+ LLVolumeParams mMeshParams;
+ S32 mLOD;
+ F32 mScore;
+
+ LODRequest(const LLVolumeParams& mesh_params, S32 lod)
+ : mMeshParams(mesh_params), mLOD(lod), mScore(0.f)
+ {
+ }
+ };
+
+ struct CompareScoreGreater
+ {
+ bool operator()(const LODRequest& lhs, const LODRequest& rhs)
+ {
+ return lhs.mScore > rhs.mScore; // greatest = first
+ }
+ };
+
+
+ class LoadedMesh
+ {
+ public:
+ LLPointer<LLVolume> mVolume;
+ LLVolumeParams mMeshParams;
+ S32 mLOD;
+
+ LoadedMesh(LLVolume* volume, const LLVolumeParams& mesh_params, S32 lod)
+ : mVolume(volume), mMeshParams(mesh_params), mLOD(lod)
+ {
+ }
+
+ };
+
+ //set of requested skin info
+ std::set<LLUUID> mSkinRequests;
+
+ //queue of completed skin info requests
+ std::queue<LLMeshSkinInfo> mSkinInfoQ;
+
+ //set of requested decompositions
+ std::set<LLUUID> mDecompositionRequests;
+
+ //set of requested physics shapes
+ std::set<LLUUID> mPhysicsShapeRequests;
+
+ //queue of completed Decomposition info requests
+ std::queue<LLMeshDecomposition*> mDecompositionQ;
+
+ //queue of requested headers
+ std::queue<HeaderRequest> mHeaderReqQ;
+
+ //queue of requested LODs
+ std::queue<LODRequest> mLODReqQ;
+
+ //queue of unavailable LODs (either asset doesn't exist or asset doesn't have desired LOD)
+ std::queue<LODRequest> mUnavailableQ;
+
+ //queue of successfully loaded meshes
+ std::queue<LoadedMesh> mLoadedQ;
+
+ //map of pending header requests and currently desired LODs
+ typedef std::map<LLVolumeParams, std::vector<S32> > pending_lod_map;
+ pending_lod_map mPendingLOD;
+
+ static std::string constructUrl(LLUUID mesh_id);
+
+ LLMeshRepoThread();
+ ~LLMeshRepoThread();
+
+ virtual void run();
+
+ void loadMeshLOD(const LLVolumeParams& mesh_params, S32 lod);
+ bool fetchMeshHeader(const LLVolumeParams& mesh_params);
+ bool fetchMeshLOD(const LLVolumeParams& mesh_params, S32 lod);
+ bool headerReceived(const LLVolumeParams& mesh_params, U8* data, S32 data_size);
+ bool lodReceived(const LLVolumeParams& mesh_params, S32 lod, U8* data, S32 data_size);
+ bool skinInfoReceived(const LLUUID& mesh_id, U8* data, S32 data_size);
+ bool decompositionReceived(const LLUUID& mesh_id, U8* data, S32 data_size);
+ bool physicsShapeReceived(const LLUUID& mesh_id, U8* data, S32 data_size);
+ const LLSD& getMeshHeader(const LLUUID& mesh_id);
+
+ void notifyLoadedMeshes();
+ S32 getActualMeshLOD(const LLVolumeParams& mesh_params, S32 lod);
+ U32 getResourceCost(const LLUUID& mesh_params);
+
+ void loadMeshSkinInfo(const LLUUID& mesh_id);
+ void loadMeshDecomposition(const LLUUID& mesh_id);
+ void loadMeshPhysicsShape(const LLUUID& mesh_id);
+
+ //send request for skin info, returns true if header info exists
+ // (should hold onto mesh_id and try again later if header info does not exist)
+ bool fetchMeshSkinInfo(const LLUUID& mesh_id);
+
+ //send request for decomposition, returns true if header info exists
+ // (should hold onto mesh_id and try again later if header info does not exist)
+ bool fetchMeshDecomposition(const LLUUID& mesh_id);
+
+ //send request for PhysicsShape, returns true if header info exists
+ // (should hold onto mesh_id and try again later if header info does not exist)
+ bool fetchMeshPhysicsShape(const LLUUID& mesh_id);
+
+
+};
+
+class LLMeshUploadThread : public LLThread
+{
+public:
+ class DecompRequest : public LLPhysicsDecomp::Request
+ {
+ public:
+ LLPointer<LLModel> mModel;
+ LLPointer<LLModel> mBaseModel;
+
+ LLMeshUploadThread* mThread;
+
+ DecompRequest(LLModel* mdl, LLModel* base_model, LLMeshUploadThread* thread);
+
+ S32 statusCallback(const char* status, S32 p1, S32 p2) { return 1; }
+ void completed();
+ };
+
+ LLPointer<DecompRequest> mFinalDecomp;
+ bool mPhysicsComplete;
+
+ typedef std::map<LLPointer<LLModel>, std::vector<LLVector3> > hull_map;
+ hull_map mHullMap;
+
+ typedef std::vector<LLModelInstance> instance_list;
+ instance_list mInstanceList;
+
+ typedef std::map<LLPointer<LLModel>, instance_list> instance_map;
+ instance_map mInstance;
+
+ LLMutex* mMutex;
+ LLCurlRequest* mCurlRequest;
+ S32 mPendingConfirmations;
+ S32 mPendingUploads;
+ S32 mPendingCost;
+ bool mFinished;
+ LLVector3 mOrigin;
+ bool mUploadTextures;
+ bool mUploadSkin;
+ bool mUploadJoints;
+
+ LLHost mHost;
+ std::string mUploadObjectAssetCapability;
+ std::string mNewInventoryCapability;
+
+ std::queue<LLMeshUploadData> mUploadQ;
+ std::queue<LLMeshUploadData> mConfirmedQ;
+ std::queue<LLModelInstance> mInstanceQ;
+
+ std::queue<LLTextureUploadData> mTextureQ;
+ std::queue<LLTextureUploadData> mConfirmedTextureQ;
+
+ std::map<LLViewerFetchedTexture*, LLTextureUploadData> mTextureMap;
+
+ LLMeshUploadThread(instance_list& data, LLVector3& scale, bool upload_textures,
+ bool upload_skin, bool upload_joints);
+ ~LLMeshUploadThread();
+
+ void uploadTexture(LLTextureUploadData& data);
+ void doUploadTexture(LLTextureUploadData& data);
+ void sendCostRequest(LLTextureUploadData& data);
+ void priceResult(LLTextureUploadData& data, const LLSD& content);
+ void onTextureUploaded(LLTextureUploadData& data);
+
+ void uploadModel(LLMeshUploadData& data);
+ void sendCostRequest(LLMeshUploadData& data);
+ void doUploadModel(LLMeshUploadData& data);
+ void onModelUploaded(LLMeshUploadData& data);
+ void createObjects(LLMeshUploadData& data);
+ LLSD createObject(LLModelInstance& instance);
+ void priceResult(LLMeshUploadData& data, const LLSD& content);
+
+ bool finished() { return mFinished; }
+ virtual void run();
+ void preStart();
+
+};
+
+class LLMeshRepository
+{
+public:
+
+ //metrics
+ static U32 sBytesReceived;
+ static U32 sHTTPRequestCount;
+ static U32 sHTTPRetryCount;
+ static U32 sCacheBytesRead;
+ static U32 sCacheBytesWritten;
+ static U32 sPeakKbps;
+
+ static F32 getStreamingCost(const LLSD& header, F32 radius);
+
+ LLMeshRepository();
+
+ void init();
+ void shutdown();
+ S32 update() ;
+
+ //mesh management functions
+ S32 loadMesh(LLVOVolume* volume, const LLVolumeParams& mesh_params, S32 detail = 0, S32 last_lod = -1);
+
+ void notifyLoadedMeshes();
+ void notifyMeshLoaded(const LLVolumeParams& mesh_params, LLVolume* volume);
+ void notifyMeshUnavailable(const LLVolumeParams& mesh_params, S32 lod);
+ void notifySkinInfoReceived(LLMeshSkinInfo& info);
+ void notifyDecompositionReceived(LLMeshDecomposition* info);
+
+ S32 getActualMeshLOD(const LLVolumeParams& mesh_params, S32 lod);
+ U32 calcResourceCost(LLSD& header);
+ U32 getResourceCost(const LLUUID& mesh_params);
+ const LLMeshSkinInfo* getSkinInfo(const LLUUID& mesh_id);
+ const LLMeshDecomposition* getDecomposition(const LLUUID& mesh_id);
+ void fetchPhysicsShape(const LLUUID& mesh_id);
+ bool hasPhysicsShape(const LLUUID& mesh_id);
+
+ void buildHull(const LLVolumeParams& params, S32 detail);
+ const LLSD& getMeshHeader(const LLUUID& mesh_id);
+
+ void uploadModel(std::vector<LLModelInstance>& data, LLVector3& scale, bool upload_textures,
+ bool upload_skin, bool upload_joints);
+
+ S32 getMeshSize(const LLUUID& mesh_id, S32 lod);
+
+ typedef std::map<LLVolumeParams, std::set<LLUUID> > mesh_load_map;
+ mesh_load_map mLoadingMeshes[4];
+
+ typedef std::map<LLUUID, LLMeshSkinInfo> skin_map;
+ skin_map mSkinMap;
+
+ typedef std::map<LLUUID, LLMeshDecomposition*> decomposition_map;
+ decomposition_map mDecompositionMap;
+
+ LLMutex* mMeshMutex;
+
+ std::vector<LLMeshRepoThread::LODRequest> mPendingRequests;
+
+ //list of mesh ids awaiting skin info
+ std::set<LLUUID> mLoadingSkins;
+
+ //list of mesh ids that need to send skin info fetch requests
+ std::queue<LLUUID> mPendingSkinRequests;
+
+ //list of mesh ids awaiting decompositions
+ std::set<LLUUID> mLoadingDecompositions;
+
+ //list of mesh ids that need to send decomposition fetch requests
+ std::queue<LLUUID> mPendingDecompositionRequests;
+
+ //list of mesh ids awaiting physics shapes
+ std::set<LLUUID> mLoadingPhysicsShapes;
+
+ //list of mesh ids that need to send physics shape fetch requests
+ std::queue<LLUUID> mPendingPhysicsShapeRequests;
+
+ U32 mMeshThreadCount;
+
+ void cacheOutgoingMesh(LLMeshUploadData& data, LLSD& header);
+
+ LLMeshRepoThread* mThread;
+ std::vector<LLMeshUploadThread*> mUploads;
+ std::vector<LLMeshUploadThread*> mUploadWaitList;
+
+ LLPhysicsDecomp* mDecompThread;
+
+ class inventory_data
+ {
+ public:
+ LLSD mPostData;
+ LLSD mResponse;
+
+ inventory_data(const LLSD& data, const LLSD& content)
+ : mPostData(data), mResponse(content)
+ {
+ }
+ };
+
+ std::queue<inventory_data> mInventoryQ;
+
+ std::queue<LLSD> mUploadErrorQ;
+
+ void uploadError(LLSD& args);
+ void updateInventory(inventory_data data);
+
+ std::string mGetMeshCapability;
+
+};
+
+extern LLMeshRepository gMeshRepo;
+
+#endif
+
diff --git a/indra/newview/llnamelistctrl.h b/indra/newview/llnamelistctrl.h
index 6805630ef1..d64fdbe6a5 100644
--- a/indra/newview/llnamelistctrl.h
+++ b/indra/newview/llnamelistctrl.h
@@ -1,25 +1,25 @@
-/**
+/**
* @file llnamelistctrl.h
* @brief A list of names, automatically refreshing from the name cache.
*
* $LicenseInfo:firstyear=2003&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
- *
+ *
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
+ *
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
@@ -58,7 +58,7 @@ public:
NameItem()
: name("name"),
target("target", INDIVIDUAL)
- {}
+ {}
};
struct NameColumn : public LLInitParam::Choice<NameColumn>
@@ -83,7 +83,7 @@ protected:
LLNameListCtrl(const Params&);
friend class LLUICtrlFactory;
public:
- // Add a user to the list by name. It will be added, the name
+ // Add a user to the list by name. It will be added, the name
// requested from the cache, and updated as necessary.
void addNameItem(const LLUUID& agent_id, EAddPosition pos = ADD_BOTTOM,
BOOL enabled = TRUE, const std::string& suffix = LLStringUtil::null);
@@ -92,7 +92,7 @@ public:
/*virtual*/ LLScrollListItem* addElement(const LLSD& element, EAddPosition pos = ADD_BOTTOM, void* userdata = NULL);
LLScrollListItem* addNameItemRow(const NameItem& value, EAddPosition pos = ADD_BOTTOM, const std::string& suffix = LLStringUtil::null);
- // Add a user to the list by name. It will be added, the name
+ // Add a user to the list by name. It will be added, the name
// requested from the cache, and updated as necessary.
void addGroupNameItem(const LLUUID& group_id, EAddPosition pos = ADD_BOTTOM,
BOOL enabled = TRUE);
@@ -126,7 +126,7 @@ private:
/**
* LLNameListCtrl item
- *
+ *
* We don't use LLScrollListItem to be able to override getUUID(), which is needed
* because the name list item value is not simply an UUID but a map (uuid, is_group).
*/
diff --git a/indra/newview/llpanelface.cpp b/indra/newview/llpanelface.cpp
index bce496cbad..07c7f35989 100644
--- a/indra/newview/llpanelface.cpp
+++ b/indra/newview/llpanelface.cpp
@@ -376,6 +376,11 @@ struct LLPanelFaceSetAlignedTEFunctor : public LLSelectedTEFunctor
return true;
}
+ if (facep->getViewerObject()->getVolume()->getNumVolumeFaces() <= te)
+ {
+ return true;
+ }
+
bool set_aligned = true;
if (facep == mCenterFace)
{
@@ -418,6 +423,12 @@ struct LLPanelFaceGetIsAlignedTEFunctor : public LLSelectedTEFunctor
{
return false;
}
+
+ if (facep->getViewerObject()->getVolume()->getNumVolumeFaces() <= te)
+ { //volume face does not exist, can't be aligned
+ return false;
+ }
+
if (facep == mCenterFace)
{
return true;
diff --git a/indra/newview/llpanelgroupnotices.cpp b/indra/newview/llpanelgroupnotices.cpp
index cdf6e51bf8..e64192c2ae 100644
--- a/indra/newview/llpanelgroupnotices.cpp
+++ b/indra/newview/llpanelgroupnotices.cpp
@@ -154,6 +154,7 @@ BOOL LLGroupDropTarget::handleDragAndDrop(S32 x, S32 y, MASK mask, BOOL drop,
case DAD_ANIMATION:
case DAD_GESTURE:
case DAD_CALLINGCARD:
+ case DAD_MESH:
{
LLViewerInventoryItem* inv_item = (LLViewerInventoryItem*)cargo_data;
if(gInventory.getItem(inv_item->getUUID())
diff --git a/indra/newview/llpanelmaininventory.cpp b/indra/newview/llpanelmaininventory.cpp
index 0c3f2f3e31..d85ddcaa60 100644
--- a/indra/newview/llpanelmaininventory.cpp
+++ b/indra/newview/llpanelmaininventory.cpp
@@ -694,6 +694,7 @@ void LLFloaterInventoryFinder::updateElementsFromFilter()
getChild<LLUICtrl>("check_clothing")->setValue((S32) (filter_types & 0x1 << LLInventoryType::IT_WEARABLE));
getChild<LLUICtrl>("check_gesture")->setValue((S32) (filter_types & 0x1 << LLInventoryType::IT_GESTURE));
getChild<LLUICtrl>("check_landmark")->setValue((S32) (filter_types & 0x1 << LLInventoryType::IT_LANDMARK));
+ getChild<LLUICtrl>("check_mesh")->setValue((S32) (filter_types & 0x1 << LLInventoryType::IT_MESH));
getChild<LLUICtrl>("check_notecard")->setValue((S32) (filter_types & 0x1 << LLInventoryType::IT_NOTECARD));
getChild<LLUICtrl>("check_object")->setValue((S32) (filter_types & 0x1 << LLInventoryType::IT_OBJECT));
getChild<LLUICtrl>("check_script")->setValue((S32) (filter_types & 0x1 << LLInventoryType::IT_LSL));
@@ -745,6 +746,12 @@ void LLFloaterInventoryFinder::draw()
filtered_by_all_types = FALSE;
}
+ if (!getChild<LLUICtrl>("check_mesh")->getValue())
+ {
+ filter &= ~(0x1 << LLInventoryType::IT_MESH);
+ filtered_by_all_types = FALSE;
+ }
+
if (!getChild<LLUICtrl>("check_notecard")->getValue())
{
filter &= ~(0x1 << LLInventoryType::IT_NOTECARD);
@@ -841,6 +848,7 @@ void LLFloaterInventoryFinder::selectAllTypes(void* user_data)
self->getChild<LLUICtrl>("check_clothing")->setValue(TRUE);
self->getChild<LLUICtrl>("check_gesture")->setValue(TRUE);
self->getChild<LLUICtrl>("check_landmark")->setValue(TRUE);
+ self->getChild<LLUICtrl>("check_mesh")->setValue(TRUE);
self->getChild<LLUICtrl>("check_notecard")->setValue(TRUE);
self->getChild<LLUICtrl>("check_object")->setValue(TRUE);
self->getChild<LLUICtrl>("check_script")->setValue(TRUE);
@@ -860,6 +868,7 @@ void LLFloaterInventoryFinder::selectNoTypes(void* user_data)
self->getChild<LLUICtrl>("check_clothing")->setValue(FALSE);
self->getChild<LLUICtrl>("check_gesture")->setValue(FALSE);
self->getChild<LLUICtrl>("check_landmark")->setValue(FALSE);
+ self->getChild<LLUICtrl>("check_mesh")->setValue(FALSE);
self->getChild<LLUICtrl>("check_notecard")->setValue(FALSE);
self->getChild<LLUICtrl>("check_object")->setValue(FALSE);
self->getChild<LLUICtrl>("check_script")->setValue(FALSE);
diff --git a/indra/newview/llpanelnearbymedia.cpp b/indra/newview/llpanelnearbymedia.cpp
index a7f1ab28fd..2bbd15ae11 100644
--- a/indra/newview/llpanelnearbymedia.cpp
+++ b/indra/newview/llpanelnearbymedia.cpp
@@ -356,7 +356,7 @@ void LLPanelNearByMedia::updateListItem(LLScrollListItem* item, LLViewerMediaImp
debug_str += llformat("%g/", (float)impl->getInterest());
// proximity distance is actually distance squared -- display it as straight distance.
- debug_str += llformat("%g/", fsqrtf(impl->getProximityDistance()));
+ debug_str += llformat("%g/", (F32) sqrt(impl->getProximityDistance()));
// s += llformat("%g/", (float)impl->getCPUUsage());
// s += llformat("%g/", (float)impl->getApproximateTextureInterest());
diff --git a/indra/newview/llpanelobject.cpp b/indra/newview/llpanelobject.cpp
index a0c320ba19..0300ea0c92 100644
--- a/indra/newview/llpanelobject.cpp
+++ b/indra/newview/llpanelobject.cpp
@@ -67,6 +67,7 @@
#include "pipeline.h"
#include "llviewercontrol.h"
#include "lluictrlfactory.h"
+#include "llmeshrepository.h"
//#include "llfirstuse.h"
#include "lldrawpool.h"
@@ -132,6 +133,27 @@ BOOL LLPanelObject::postBuild()
mCheckPhantom = getChild<LLCheckBoxCtrl>("Phantom Checkbox Ctrl");
childSetCommitCallback("Phantom Checkbox Ctrl",onCommitPhantom,this);
+ // PhysicsShapeType combobox
+ mComboPhysicsShapeType = getChild<LLComboBox>("Physics Shape Type Combo Ctrl");
+ mComboPhysicsShapeType->setCommitCallback(boost::bind(&LLPanelObject::sendPhysicsShapeType, this, _1, mComboPhysicsShapeType));
+
+ // PhysicsGravity
+ mSpinPhysicsGravity = getChild<LLSpinCtrl>("Physics Gravity");
+ mSpinPhysicsGravity->setCommitCallback(boost::bind(&LLPanelObject::sendPhysicsGravity, this, _1, mSpinPhysicsGravity));
+
+ // PhysicsFriction
+ mSpinPhysicsFriction = getChild<LLSpinCtrl>("Physics Friction");
+ mSpinPhysicsFriction->setCommitCallback(boost::bind(&LLPanelObject::sendPhysicsFriction, this, _1, mSpinPhysicsFriction));
+
+ // PhysicsDensity
+ mSpinPhysicsDensity = getChild<LLSpinCtrl>("Physics Density");
+ mSpinPhysicsDensity->setCommitCallback(boost::bind(&LLPanelObject::sendPhysicsDensity, this, _1, mSpinPhysicsDensity));
+
+ // PhysicsRestitution
+ mSpinPhysicsRestitution = getChild<LLSpinCtrl>("Physics Restitution");
+ mSpinPhysicsRestitution->setCommitCallback(boost::bind(&LLPanelObject::sendPhysicsRestitution, this, _1, mSpinPhysicsRestitution));
+
+
// Position
mLabelPosition = getChild<LLTextBox>("label position");
mCtrlPosX = getChild<LLSpinCtrl>("Pos X");
@@ -519,6 +541,19 @@ void LLPanelObject::getState( )
mCheckPhantom->set( mIsPhantom );
mCheckPhantom->setEnabled( roots_selected>0 && editable && !is_flexible );
+
+ mSpinPhysicsGravity->set(objectp->getPhysicsGravity());
+ mSpinPhysicsGravity->setEnabled(editable);
+
+ mSpinPhysicsFriction->set(objectp->getPhysicsFriction());
+ mSpinPhysicsFriction->setEnabled(editable);
+
+ mSpinPhysicsDensity->set(objectp->getPhysicsDensity());
+ mSpinPhysicsDensity->setEnabled(editable);
+
+ mSpinPhysicsRestitution->set(objectp->getPhysicsRestitution());
+ mSpinPhysicsRestitution->setEnabled(editable);
+
#if 0 // 1.9.2
mCastShadows = root_objectp->flagCastShadows();
mCheckCastShadows->set( mCastShadows );
@@ -569,6 +604,7 @@ void LLPanelObject::getState( )
BOOL enabled = FALSE;
BOOL hole_enabled = FALSE;
F32 scale_x=1.f, scale_y=1.f;
+ BOOL isMesh = FALSE;
if( !objectp || !objectp->getVolume() || !editable || !single_volume)
{
@@ -599,10 +635,9 @@ void LLPanelObject::getState( )
// Only allowed to change these parameters for objects
// that you have permissions on AND are not attachments.
enabled = root_objectp->permModify();
-
- const LLVolumeParams &volume_params = objectp->getVolume()->getParams();
-
+
// Volume type
+ const LLVolumeParams &volume_params = objectp->getVolume()->getParams();
U8 path = volume_params.getPathParams().getCurveType();
U8 profile_and_hole = volume_params.getProfileParams().getCurveType();
U8 profile = profile_and_hole & LL_PCODE_PROFILE_MASK;
@@ -833,7 +868,7 @@ void LLPanelObject::getState( )
}
mSpinSkew->set( skew );
}
-
+
// Compute control visibility, label names, and twist range.
// Start with defaults.
BOOL cut_visible = TRUE;
@@ -1097,6 +1132,10 @@ void LLPanelObject::getState( )
mCtrlSculptInvert->setVisible(sculpt_texture_visible);
+ // update the physics shape combo to include allowed physics shapes
+ mComboPhysicsShapeType->removeall();
+ mComboPhysicsShapeType->add(getString("None"), LLSD(1));
+
// sculpt texture
if (selected_item == MI_SCULPT)
@@ -1128,6 +1167,7 @@ void LLPanelObject::getState( )
U8 sculpt_stitching = sculpt_type & LL_SCULPT_TYPE_MASK;
BOOL sculpt_invert = sculpt_type & LL_SCULPT_FLAG_INVERT;
BOOL sculpt_mirror = sculpt_type & LL_SCULPT_FLAG_MIRROR;
+ isMesh = (sculpt_stitching == LL_SCULPT_TYPE_MESH);
if (mCtrlSculptType)
{
@@ -1151,13 +1191,34 @@ void LLPanelObject::getState( )
{
mLabelSculptType->setEnabled(TRUE);
}
+
}
}
else
{
- mSculptTextureRevert = LLUUID::null;
+ mSculptTextureRevert = LLUUID::null;
}
+ if(isMesh && objectp)
+ {
+ const LLVolumeParams &volume_params = objectp->getVolume()->getParams();
+ LLUUID mesh_id = volume_params.getSculptID();
+ if(gMeshRepo.hasPhysicsShape(mesh_id))
+ {
+ // if a mesh contains an uploaded or decomposed physics mesh,
+ // allow 'Prim'
+ mComboPhysicsShapeType->add(getString("Prim"), LLSD(0));
+ }
+ }
+ else
+ {
+ // simple prims always allow physics shape prim
+ mComboPhysicsShapeType->add(getString("Prim"), LLSD(0));
+ }
+ mComboPhysicsShapeType->add(getString("Convex Hull"), LLSD(2));
+ mComboPhysicsShapeType->setValue(LLSD(objectp->getPhysicsShapeType()));
+ mComboPhysicsShapeType->setEnabled(editable);
+
//----------------------------------------------------------------------------
@@ -1221,6 +1282,48 @@ void LLPanelObject::sendIsPhantom()
}
}
+void LLPanelObject::sendPhysicsShapeType(LLUICtrl* ctrl, void* userdata)
+{
+ U8 type = ctrl->getValue().asInteger();
+ LLSelectMgr::getInstance()->selectionSetPhysicsType(type);
+
+ refreshCost();
+}
+
+void LLPanelObject::sendPhysicsGravity(LLUICtrl* ctrl, void* userdata)
+{
+ F32 val = ctrl->getValue().asReal();
+ LLSelectMgr::getInstance()->selectionSetGravity(val);
+}
+
+void LLPanelObject::sendPhysicsFriction(LLUICtrl* ctrl, void* userdata)
+{
+ F32 val = ctrl->getValue().asReal();
+ LLSelectMgr::getInstance()->selectionSetFriction(val);
+}
+
+void LLPanelObject::sendPhysicsRestitution(LLUICtrl* ctrl, void* userdata)
+{
+ F32 val = ctrl->getValue().asReal();
+ LLSelectMgr::getInstance()->selectionSetRestitution(val);
+}
+
+void LLPanelObject::sendPhysicsDensity(LLUICtrl* ctrl, void* userdata)
+{
+ F32 val = ctrl->getValue().asReal();
+ LLSelectMgr::getInstance()->selectionSetDensity(val);
+}
+
+void LLPanelObject::refreshCost()
+{
+ LLViewerObject* obj = LLSelectMgr::getInstance()->getSelection()->getFirstObject();
+
+ if (obj)
+ {
+ obj->getObjectCost();
+ }
+}
+
void LLPanelObject::sendCastShadows()
{
BOOL value = mCheckCastShadows->get();
@@ -1786,6 +1889,17 @@ void LLPanelObject::sendSculpt()
if (mCtrlSculptType)
sculpt_type |= mCtrlSculptType->getCurrentIndex();
+ bool enabled = sculpt_type != LL_SCULPT_TYPE_MESH;
+
+ if (mCtrlSculptMirror)
+ {
+ mCtrlSculptMirror->setEnabled(enabled ? TRUE : FALSE);
+ }
+ if (mCtrlSculptInvert)
+ {
+ mCtrlSculptInvert->setEnabled(enabled ? TRUE : FALSE);
+ }
+
if ((mCtrlSculptMirror) && (mCtrlSculptMirror->get()))
sculpt_type |= LL_SCULPT_FLAG_MIRROR;
@@ -1808,6 +1922,34 @@ void LLPanelObject::refresh()
{
mRootObject = NULL;
}
+
+ bool enable_mesh = gSavedSettings.getBOOL("MeshEnabled") &&
+ !gAgent.getRegion()->getCapability("GetMesh").empty();
+
+ getChildView("label physicsshapetype")->setVisible(enable_mesh);
+ getChildView("Physics Shape Type Combo Ctrl")->setVisible(enable_mesh);
+ getChildView("Physics Gravity")->setVisible(enable_mesh);
+ getChildView("Physics Material Override")->setVisible(enable_mesh);
+ getChildView("Physics Friction")->setVisible(enable_mesh);
+ getChildView("Physics Density")->setVisible(enable_mesh);
+ getChildView("Physics Restitution")->setVisible(enable_mesh);
+
+ F32 max_scale = get_default_max_prim_scale(LLPickInfo::isFlora(mObject));
+
+ getChild<LLSpinCtrl>("Scale X")->setMaxValue(max_scale);
+ getChild<LLSpinCtrl>("Scale Y")->setMaxValue(max_scale);
+ getChild<LLSpinCtrl>("Scale Z")->setMaxValue(max_scale);
+
+ LLComboBox* sculpt_combo = getChild<LLComboBox>("sculpt type control");
+ BOOL found = sculpt_combo->itemExists("Mesh");
+ if (enable_mesh && !found)
+ {
+ sculpt_combo->add("Mesh");
+ }
+ else if (!enable_mesh && found)
+ {
+ sculpt_combo->remove("Mesh");
+ }
}
@@ -1894,6 +2036,12 @@ void LLPanelObject::clearCtrls()
mCheckTemporary ->setEnabled( FALSE );
mCheckPhantom ->set(FALSE);
mCheckPhantom ->setEnabled( FALSE );
+
+ mSpinPhysicsGravity->setEnabled(FALSE);
+ mSpinPhysicsFriction->setEnabled(FALSE);
+ mSpinPhysicsDensity->setEnabled(FALSE);
+ mSpinPhysicsRestitution->setEnabled(FALSE);
+
#if 0 // 1.9.2
mCheckCastShadows->set(FALSE);
mCheckCastShadows->setEnabled( FALSE );
diff --git a/indra/newview/llpanelobject.h b/indra/newview/llpanelobject.h
index e07bf007ec..54bb5df8bf 100644
--- a/indra/newview/llpanelobject.h
+++ b/indra/newview/llpanelobject.h
@@ -65,6 +65,7 @@ public:
static void onCommitPhysics( LLUICtrl* ctrl, void* userdata);
static void onCommitTemporary( LLUICtrl* ctrl, void* userdata);
static void onCommitPhantom( LLUICtrl* ctrl, void* userdata);
+ static void onCommitPhysicsParam( LLUICtrl* ctrl, void* userdata);
static void onCommitCastShadows( LLUICtrl* ctrl, void* userdata);
static void onCommitParametric(LLUICtrl* ctrl, void* userdata);
@@ -80,6 +81,7 @@ public:
protected:
void getState();
+ void refreshCost();
void sendRotation(BOOL btn_down);
void sendScale(BOOL btn_down);
@@ -87,6 +89,12 @@ protected:
void sendIsPhysical();
void sendIsTemporary();
void sendIsPhantom();
+ void sendPhysicsShapeType(LLUICtrl* ctrl, void* userdata);
+ void sendPhysicsGravity(LLUICtrl* ctrl, void* userdata);
+ void sendPhysicsFriction(LLUICtrl* ctrl, void* userdata);
+ void sendPhysicsRestitution(LLUICtrl* ctrl, void* userdata);
+ void sendPhysicsDensity(LLUICtrl* ctrl, void* userdata);
+
void sendCastShadows();
void sendSculpt();
@@ -159,6 +167,12 @@ protected:
LLCheckBoxCtrl *mCheckPhantom;
LLCheckBoxCtrl *mCheckCastShadows;
+ LLComboBox* mComboPhysicsShapeType;
+ LLSpinCtrl* mSpinPhysicsGravity;
+ LLSpinCtrl* mSpinPhysicsFriction;
+ LLSpinCtrl* mSpinPhysicsDensity;
+ LLSpinCtrl* mSpinPhysicsRestitution;
+
LLTextureCtrl *mCtrlSculptTexture;
LLTextBox *mLabelSculptType;
LLComboBox *mCtrlSculptType;
diff --git a/indra/newview/llpanelobjectinventory.cpp b/indra/newview/llpanelobjectinventory.cpp
index 0b6267c9e6..bfe6cab52f 100644
--- a/indra/newview/llpanelobjectinventory.cpp
+++ b/indra/newview/llpanelobjectinventory.cpp
@@ -802,6 +802,7 @@ BOOL LLTaskCategoryBridge::dragOrDrop(MASK mask, BOOL drop,
case DAD_ANIMATION:
case DAD_GESTURE:
case DAD_CALLINGCARD:
+ case DAD_MESH:
accept = LLToolDragAndDrop::isInventoryDropAcceptable(object, (LLViewerInventoryItem*)cargo_data);
if(accept && drop)
{
@@ -1227,6 +1228,116 @@ LLUIImagePtr LLTaskWearableBridge::getIcon() const
return LLInventoryIcon::getIcon(mAssetType, mInventoryType, mFlags, FALSE );
}
+///----------------------------------------------------------------------------
+/// Class LLTaskMeshBridge
+///----------------------------------------------------------------------------
+
+class LLTaskMeshBridge : public LLTaskInvFVBridge
+{
+public:
+ LLTaskMeshBridge(
+ LLPanelObjectInventory* panel,
+ const LLUUID& uuid,
+ const std::string& name);
+
+ virtual LLUIImagePtr getIcon() const;
+ virtual void openItem();
+ virtual void performAction(LLInventoryModel* model, std::string action);
+ virtual void buildContextMenu(LLMenuGL& menu, U32 flags);
+};
+
+LLTaskMeshBridge::LLTaskMeshBridge(
+ LLPanelObjectInventory* panel,
+ const LLUUID& uuid,
+ const std::string& name) :
+ LLTaskInvFVBridge(panel, uuid, name)
+{
+}
+
+LLUIImagePtr LLTaskMeshBridge::getIcon() const
+{
+ return LLInventoryIcon::getIcon(LLAssetType::AT_MESH, LLInventoryType::IT_MESH, 0, FALSE);
+}
+
+void LLTaskMeshBridge::openItem()
+{
+ // open mesh
+}
+
+
+// virtual
+void LLTaskMeshBridge::performAction(LLInventoryModel* model, std::string action)
+{
+ if (action == "mesh action")
+ {
+ LLInventoryItem* item = findItem();
+ if(item)
+ {
+ // do action
+ }
+ }
+ LLTaskInvFVBridge::performAction(model, action);
+}
+
+void LLTaskMeshBridge::buildContextMenu(LLMenuGL& menu, U32 flags)
+{
+ LLInventoryItem* item = findItem();
+ if(!item) return;
+ std::vector<std::string> items;
+ std::vector<std::string> disabled_items;
+
+ if(item->getPermissions().getOwner() != gAgent.getID()
+ && item->getSaleInfo().isForSale())
+ {
+ items.push_back(std::string("Task Buy"));
+
+ std::string label= LLTrans::getString("Buy");
+ // Check the price of the item.
+ S32 price = getPrice();
+ if (-1 == price)
+ {
+ llwarns << "label_buy_task_bridged_item: Invalid price" << llendl;
+ }
+ else
+ {
+ std::ostringstream info;
+ info << LLTrans::getString("BuyforL$") << price;
+ label.assign(info.str());
+ }
+
+ const LLView::child_list_t *list = menu.getChildList();
+ LLView::child_list_t::const_iterator itor;
+ for (itor = list->begin(); itor != list->end(); ++itor)
+ {
+ std::string name = (*itor)->getName();
+ LLMenuItemCallGL* menu_itemp = dynamic_cast<LLMenuItemCallGL*>(*itor);
+ if (name == "Task Buy" && menu_itemp)
+ {
+ menu_itemp->setLabel(label);
+ }
+ }
+ }
+ else
+ {
+ items.push_back(std::string("Task Open"));
+ if (!isItemCopyable())
+ {
+ disabled_items.push_back(std::string("Task Open"));
+ }
+ }
+ items.push_back(std::string("Task Properties"));
+ if(isItemRenameable())
+ {
+ items.push_back(std::string("Task Rename"));
+ }
+ if(isItemRemovable())
+ {
+ items.push_back(std::string("Task Remove"));
+ }
+
+
+ hide_context_entries(menu, items, disabled_items);
+}
///----------------------------------------------------------------------------
/// LLTaskInvFVBridge impl
@@ -1307,6 +1418,11 @@ LLTaskInvFVBridge* LLTaskInvFVBridge::createObjectBridge(LLPanelObjectInventory*
object->getUUID(),
object->getName());
break;
+ case LLAssetType::AT_MESH:
+ new_bridge = new LLTaskMeshBridge(panel,
+ object->getUUID(),
+ object->getName());
+ break;
default:
llinfos << "Unhandled inventory type (llassetstorage.h): "
<< (S32)type << llendl;
diff --git a/indra/newview/llpanelpicks.cpp b/indra/newview/llpanelpicks.cpp
index ddce83c616..ddce83c616 100755..100644
--- a/indra/newview/llpanelpicks.cpp
+++ b/indra/newview/llpanelpicks.cpp
diff --git a/indra/newview/llpanelpicks.h b/indra/newview/llpanelpicks.h
index 29db110523..29db110523 100755..100644
--- a/indra/newview/llpanelpicks.h
+++ b/indra/newview/llpanelpicks.h
diff --git a/indra/newview/llpanelprimmediacontrols.cpp b/indra/newview/llpanelprimmediacontrols.cpp
index 82ff6c3487..933b40ec79 100644
--- a/indra/newview/llpanelprimmediacontrols.cpp
+++ b/indra/newview/llpanelprimmediacontrols.cpp
@@ -61,6 +61,7 @@
#include "llwindow.h"
#include "llwindowshade.h"
#include "llfloatertools.h" // to enable hide if build tools are up
+#include "llvector4a.h"
// Functions pulled from pipeline.cpp
glh::matrix4f glh_get_current_modelview();
@@ -577,7 +578,9 @@ void LLPanelPrimMediaControls::updateShape()
{
const LLVolumeFace& vf = volume->getVolumeFace(mTargetObjectFace);
- const LLVector3* ext = vf.mExtents;
+ LLVector3 ext[2];
+ ext[0].set(vf.mExtents[0].getF32ptr());
+ ext[1].set(vf.mExtents[1].getF32ptr());
LLVector3 center = (ext[0]+ext[1])*0.5f;
LLVector3 size = (ext[1]-ext[0])*0.5f;
diff --git a/indra/newview/llpanelprofile.cpp b/indra/newview/llpanelprofile.cpp
index fd5c3362bb..fd5c3362bb 100755..100644
--- a/indra/newview/llpanelprofile.cpp
+++ b/indra/newview/llpanelprofile.cpp
diff --git a/indra/newview/llpanelprofile.h b/indra/newview/llpanelprofile.h
index fca359f51e..fca359f51e 100755..100644
--- a/indra/newview/llpanelprofile.h
+++ b/indra/newview/llpanelprofile.h
diff --git a/indra/newview/llphysicsshapebuilderutil.cpp b/indra/newview/llphysicsshapebuilderutil.cpp
new file mode 100644
index 0000000000..54d54bfcb9
--- /dev/null
+++ b/indra/newview/llphysicsshapebuilderutil.cpp
@@ -0,0 +1,206 @@
+/**
+* @file llphysicsshapebuilder.cpp
+* @brief Generic system to convert LL(Physics)VolumeParams to physics shapes
+* @author falcon@lindenlab.com
+*
+* $LicenseInfo:firstyear=2010&license=internal$
+*
+* Copyright (c) 2010, Linden Research, Inc.
+*
+* The following source code is PROPRIETARY AND CONFIDENTIAL. Use of
+* this source code is governed by the Linden Lab Source Code Disclosure
+* Agreement ("Agreement") previously entered between you and Linden
+* Lab. By accessing, using, copying, modifying or distributing this
+* software, you acknowledge that you have been informed of your
+* obligations under the Agreement and agree to abide by those obligations.
+*
+* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
+* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
+* COMPLETENESS OR PERFORMANCE.
+* $/LicenseInfo$
+*/
+
+#include "llviewerprecompiledheaders.h"
+
+#include "llphysicsshapebuilderutil.h"
+
+/* static */
+void LLPhysicsShapeBuilderUtil::determinePhysicsShape( const LLPhysicsVolumeParams& volume_params, const LLVector3& scale, PhysicsShapeSpecification& specOut )
+{
+ const LLProfileParams& profile_params = volume_params.getProfileParams();
+ const LLPathParams& path_params = volume_params.getPathParams();
+
+ specOut.mScale = scale;
+
+ const F32 avgScale = ( scale[VX] + scale[VY] + scale[VZ] )/3.0f;
+
+ // count the scale elements that are small
+ S32 min_size_counts = 0;
+ for (S32 i = 0; i < 3; ++i)
+ {
+ if (scale[i] < SHAPE_BUILDER_CONVEXIFICATION_SIZE)
+ {
+ ++min_size_counts;
+ }
+ }
+
+ const bool profile_complete = ( profile_params.getBegin() <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_PATH_CUT/avgScale ) &&
+ ( profile_params.getEnd() >= (1.0f - SHAPE_BUILDER_IMPLICIT_THRESHOLD_PATH_CUT/avgScale) );
+
+ const bool path_complete = ( path_params.getBegin() <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_PATH_CUT/avgScale ) &&
+ ( path_params.getEnd() >= (1.0f - SHAPE_BUILDER_IMPLICIT_THRESHOLD_PATH_CUT/avgScale) );
+
+ const bool simple_params = ( volume_params.getHollow() <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_HOLLOW/avgScale )
+ && ( fabs(path_params.getShearX()) <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_SHEAR/avgScale )
+ && ( fabs(path_params.getShearY()) <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_SHEAR/avgScale )
+ && ( !volume_params.isMeshSculpt() && !volume_params.isSculpt() );
+
+ if (simple_params && profile_complete)
+ {
+ // Try to create an implicit shape or convexified
+ bool no_taper = ( fabs(path_params.getScaleX() - 1.0f) <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_TAPER/avgScale )
+ && ( fabs(path_params.getScaleY() - 1.0f) <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_TAPER/avgScale );
+
+ bool no_twist = ( fabs(path_params.getTwistBegin()) <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_TWIST/avgScale )
+ && ( fabs(path_params.getTwistEnd()) <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_TWIST/avgScale);
+
+ // Box
+ if(
+ ( profile_params.getCurveType() == LL_PCODE_PROFILE_SQUARE )
+ && ( path_params.getCurveType() == LL_PCODE_PATH_LINE )
+ && no_taper
+ && no_twist
+ )
+ {
+ specOut.mType = PhysicsShapeSpecification::BOX;
+ if ( path_complete )
+ {
+ return;
+ }
+ else
+ {
+ // Side lengths
+ specOut.mScale[VX] = llmax( scale[VX], SHAPE_BUILDER_MIN_GEOMETRY_SIZE );
+ specOut.mScale[VY] = llmax( scale[VY], SHAPE_BUILDER_MIN_GEOMETRY_SIZE );
+ specOut.mScale[VZ] = llmax( scale[VZ] * (path_params.getEnd() - path_params.getBegin()), SHAPE_BUILDER_MIN_GEOMETRY_SIZE );
+
+ specOut.mCenter.set( 0.f, 0.f, 0.5f * scale[VZ] * ( path_params.getEnd() + path_params.getBegin() - 1.0f ) );
+ return;
+ }
+ }
+
+ // Sphere
+ if( path_complete
+ && ( profile_params.getCurveType() == LL_PCODE_PROFILE_CIRCLE_HALF )
+ && ( path_params.getCurveType() == LL_PCODE_PATH_CIRCLE )
+ && ( fabs(volume_params.getTaper()) <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_TAPER/avgScale )
+ && no_twist
+ )
+ {
+ if ( ( scale[VX] == scale[VZ] )
+ && ( scale[VY] == scale[VZ] ) )
+ {
+ // perfect sphere
+ specOut.mType = PhysicsShapeSpecification::SPHERE;
+ specOut.mScale = scale;
+ return;
+ }
+ else if (min_size_counts > 1)
+ {
+ // small or narrow sphere -- we can boxify
+ for (S32 i=0; i<3; ++i)
+ {
+ if (specOut.mScale[i] < SHAPE_BUILDER_CONVEXIFICATION_SIZE)
+ {
+ // reduce each small dimension size to split the approximation errors
+ specOut.mScale[i] *= 0.75f;
+ }
+ }
+ specOut.mType = PhysicsShapeSpecification::BOX;
+ return;
+ }
+ }
+
+ // Cylinder
+ if( (scale[VX] == scale[VY])
+ && ( profile_params.getCurveType() == LL_PCODE_PROFILE_CIRCLE )
+ && ( path_params.getCurveType() == LL_PCODE_PATH_LINE )
+ && ( volume_params.getBeginS() <= SHAPE_BUILDER_IMPLICIT_THRESHOLD_PATH_CUT/avgScale )
+ && ( volume_params.getEndS() >= (1.0f - SHAPE_BUILDER_IMPLICIT_THRESHOLD_PATH_CUT/avgScale) )
+ && no_taper
+ )
+ {
+ if (min_size_counts > 1)
+ {
+ // small or narrow sphere -- we can boxify
+ for (S32 i=0; i<3; ++i)
+ {
+ if (specOut.mScale[i] < SHAPE_BUILDER_CONVEXIFICATION_SIZE)
+ {
+ // reduce each small dimension size to split the approximation errors
+ specOut.mScale[i] *= 0.75f;
+ }
+ }
+
+ specOut.mType = PhysicsShapeSpecification::BOX;
+ }
+ else
+ {
+ specOut.mType = PhysicsShapeSpecification::CYLINDER;
+ F32 length = (volume_params.getPathParams().getEnd() - volume_params.getPathParams().getBegin()) * scale[VZ];
+
+ specOut.mScale[VY] = specOut.mScale[VX];
+ specOut.mScale[VZ] = length;
+ // The minus one below fixes the fact that begin and end range from 0 to 1 not -1 to 1.
+ specOut.mCenter.set( 0.f, 0.f, 0.5f * (volume_params.getPathParams().getBegin() + volume_params.getPathParams().getEnd() - 1.f) * scale[VZ] );
+ }
+
+ return;
+ }
+ }
+
+ if ( (min_size_counts == 3 )
+ // Possible dead code here--who wants to take it out?
+ || (path_complete
+ && profile_complete
+ && ( path_params.getCurveType() == LL_PCODE_PATH_LINE )
+ && (min_size_counts > 1 ) )
+ )
+ {
+ // it isn't simple but
+ // we might be able to convexify this shape if the path and profile are complete
+ // or the path is linear and both path and profile are complete --> we can boxify it
+ specOut.mType = PhysicsShapeSpecification::BOX;
+ specOut.mScale = scale;
+ return;
+ }
+
+ // Special case for big, very thin objects - bump the small dimensions up to the COLLISION_TOLERANCE
+ if (min_size_counts == 1 // One dimension is small
+ && avgScale > 3.f) // ... but others are fairly large
+ {
+ for (S32 i = 0; i < 3; ++i)
+ {
+ specOut.mScale[i] = llmax( specOut.mScale[i], COLLISION_TOLERANCE );
+ }
+ }
+
+ if ( volume_params.shouldForceConvex() )
+ {
+ specOut.mType = PhysicsShapeSpecification::USER_CONVEX;
+ }
+ // Make a simpler convex shape if we can.
+ else if (volume_params.isConvex() // is convex
+ || min_size_counts > 1 ) // two or more small dimensions
+ {
+ specOut.mType = PhysicsShapeSpecification::PRIM_CONVEX;
+ }
+ else if ( volume_params.isSculpt() ) // Is a sculpt of any kind (mesh or legacy)
+ {
+ specOut.mType = volume_params.isMeshSculpt() ? PhysicsShapeSpecification::USER_MESH : PhysicsShapeSpecification::SCULPT;
+ }
+ else // Resort to mesh
+ {
+ specOut.mType = PhysicsShapeSpecification::PRIM_MESH;
+ }
+}
diff --git a/indra/newview/llphysicsshapebuilderutil.h b/indra/newview/llphysicsshapebuilderutil.h
new file mode 100644
index 0000000000..3de9afcb25
--- /dev/null
+++ b/indra/newview/llphysicsshapebuilderutil.h
@@ -0,0 +1,134 @@
+/**
+ * @file llphysicsshapebuilder.h
+ * @author falcon@lindenlab.com
+ * @brief Generic system to convert LL(Physics)VolumeParams to physics shapes
+ *
+ * $LicenseInfo:firstyear=2010&license=internal$
+ *
+ * Copyright (c) 2010, Linden Research, Inc.
+ *
+ * The following source code is PROPRIETARY AND CONFIDENTIAL. Use of
+ * this source code is governed by the Linden Lab Source Code Disclosure
+ * Agreement ("Agreement") previously entered between you and Linden
+ * Lab. By accessing, using, copying, modifying or distributing this
+ * software, you acknowledge that you have been informed of your
+ * obligations under the Agreement and agree to abide by those obligations.
+ *
+ * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
+ * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
+ * COMPLETENESS OR PERFORMANCE.
+ * $/LicenseInfo$
+ */
+
+#ifndef LL_PHYSICS_SHAPE_BUILDER_H
+#define LL_PHYSICS_SHAPE_BUILDER_H
+
+#include "indra_constants.h"
+#include "llvolume.h"
+
+#define USE_SHAPE_QUANTIZATION 0
+
+#define SHAPE_BUILDER_DEFAULT_VOLUME_DETAIL 1
+
+#define SHAPE_BUILDER_IMPLICIT_THRESHOLD_HOLLOW 0.10f
+#define SHAPE_BUILDER_IMPLICIT_THRESHOLD_HOLLOW_SPHERES 0.90f
+#define SHAPE_BUILDER_IMPLICIT_THRESHOLD_PATH_CUT 0.05f
+#define SHAPE_BUILDER_IMPLICIT_THRESHOLD_TAPER 0.05f
+#define SHAPE_BUILDER_IMPLICIT_THRESHOLD_TWIST 0.09f
+#define SHAPE_BUILDER_IMPLICIT_THRESHOLD_SHEAR 0.05f
+
+const F32 SHAPE_BUILDER_ENTRY_SNAP_SCALE_BIN_SIZE = 0.15f;
+const F32 SHAPE_BUILDER_ENTRY_SNAP_PARAMETER_BIN_SIZE = 0.010f;
+const F32 SHAPE_BUILDER_CONVEXIFICATION_SIZE = 2.f * COLLISION_TOLERANCE;
+const F32 SHAPE_BUILDER_MIN_GEOMETRY_SIZE = 0.5f * COLLISION_TOLERANCE;
+
+class LLPhysicsVolumeParams : public LLVolumeParams
+{
+public:
+
+ LLPhysicsVolumeParams( const LLVolumeParams& params, bool forceConvex ) :
+ LLVolumeParams( params ),
+ mForceConvex(forceConvex) {}
+
+ bool operator==(const LLPhysicsVolumeParams &params) const
+ {
+ return ( LLVolumeParams::operator==(params) && (mForceConvex == params.mForceConvex) );
+ }
+
+ bool operator!=(const LLPhysicsVolumeParams &params) const
+ {
+ return !operator==(params);
+ }
+
+ bool operator<(const LLPhysicsVolumeParams &params) const
+ {
+ if ( LLVolumeParams::operator!=(params) )
+ {
+ return LLVolumeParams::operator<(params);
+ }
+ return (params.mForceConvex == false) && (mForceConvex == true);
+ }
+
+ bool shouldForceConvex() const { return mForceConvex; }
+
+private:
+ bool mForceConvex;
+};
+
+
+class LLPhysicsShapeBuilderUtil
+{
+public:
+
+ class PhysicsShapeSpecification
+ {
+ public:
+ enum ShapeType
+ {
+ // Primitive types
+ BOX,
+ SPHERE,
+ CYLINDER,
+
+ USER_CONVEX, // User specified they wanted the convex hull of the volume
+
+ PRIM_CONVEX, // Either a volume that is inherently convex but not a primitive type, or a shape
+ // with dimensions such that will convexify it anyway.
+
+ SCULPT, // Special case for traditional sculpts--they are the convex hull of a single particular set of volume params
+
+ USER_MESH, // A user mesh. May or may not contain a convex decomposition.
+
+ PRIM_MESH, // A non-convex volume which we have to represent accurately
+
+ INVALID
+ };
+
+ PhysicsShapeSpecification() :
+ mType( INVALID ),
+ mScale( 0.f, 0.f, 0.f ),
+ mCenter( 0.f, 0.f, 0.f ) {}
+
+ bool isConvex() { return (mType != USER_MESH && mType != PRIM_MESH && mType != INVALID); }
+ bool isMesh() { return (mType == USER_MESH) || (mType == PRIM_MESH); }
+
+ ShapeType getType() { return mType; }
+ const LLVector3& getScale() { return mScale; }
+ const LLVector3& getCenter() { return mCenter; }
+
+ private:
+ friend class LLPhysicsShapeBuilderUtil;
+
+ ShapeType mType;
+
+ // Dimensions of an AABB around the shape
+ LLVector3 mScale;
+
+ // Offset of shape from origin of primitive's reference frame
+ LLVector3 mCenter;
+ };
+
+ static void determinePhysicsShape( const LLPhysicsVolumeParams& volume_params, const LLVector3& scale, PhysicsShapeSpecification& specOut );
+};
+
+#endif //LL_PHYSICS_SHAPE_BUILDER_H
diff --git a/indra/newview/llpolymesh.cpp b/indra/newview/llpolymesh.cpp
index 363b0b8e9d..c6425ed283 100644
--- a/indra/newview/llpolymesh.cpp
+++ b/indra/newview/llpolymesh.cpp
@@ -29,7 +29,8 @@
//-----------------------------------------------------------------------------
#include "llviewerprecompiledheaders.h"
-#include "llpolymesh.h"
+#include "llfasttimer.h"
+#include "llmemory.h"
#include "llviewercontrol.h"
#include "llxmltree.h"
@@ -39,7 +40,7 @@
#include "llvolume.h"
#include "llendianswizzle.h"
-#include "llfasttimer.h"
+#include "llpolymesh.h"
#define HEADER_ASCII "Linden Mesh 1.0"
#define HEADER_BINARY "Linden Binary Mesh 1.0"
@@ -134,7 +135,7 @@ void LLPolyMeshSharedData::freeMeshData()
delete [] mDetailTexCoords;
mDetailTexCoords = NULL;
- delete [] mWeights;
+ free(mWeights);
mWeights = NULL;
}
@@ -224,7 +225,7 @@ BOOL LLPolyMeshSharedData::allocateVertexData( U32 numVertices )
mBaseBinormals = new LLVector3[ numVertices ];
mTexCoords = new LLVector2[ numVertices ];
mDetailTexCoords = new LLVector2[ numVertices ];
- mWeights = new F32[ numVertices ];
+ mWeights = (F32*) malloc((numVertices*sizeof(F32)+0xF) & ~0xF);
for (i = 0; i < numVertices; i++)
{
mWeights[i] = 0.f;
@@ -702,20 +703,29 @@ LLPolyMesh::LLPolyMesh(LLPolyMeshSharedData *shared_data, LLPolyMesh *reference_
mClothingWeights = reference_mesh->mClothingWeights;
}
else
- {
+ {
#if 1 // Allocate memory without initializing every vector
// NOTE: This makes asusmptions about the size of LLVector[234]
int nverts = mSharedData->mNumVertices;
- int nfloats = nverts * (3*5 + 2 + 4);
- mVertexData = new F32[nfloats];
+ int nfloats = nverts * (2*4 + 3*3 + 2 + 4);
+
+ //use 16 byte aligned vertex data to make LLPolyMesh SSE friendly
+ mVertexData = (F32*) malloc(nfloats*4);
int offset = 0;
- mCoords = (LLVector3*)(mVertexData + offset); offset += 3*nverts;
- mNormals = (LLVector3*)(mVertexData + offset); offset += 3*nverts;
- mScaledNormals = (LLVector3*)(mVertexData + offset); offset += 3*nverts;
- mBinormals = (LLVector3*)(mVertexData + offset); offset += 3*nverts;
- mScaledBinormals = (LLVector3*)(mVertexData + offset); offset += 3*nverts;
- mTexCoords = (LLVector2*)(mVertexData + offset); offset += 2*nverts;
- mClothingWeights = (LLVector4*)(mVertexData + offset); offset += 4*nverts;
+
+ //all members must be 16-byte aligned except the last 3
+ mCoords = (LLVector4*)(mVertexData + offset); offset += 4*nverts;
+ mNormals = (LLVector4*)(mVertexData + offset); offset += 4*nverts;
+ mClothingWeights = (LLVector4*)(mVertexData + offset); offset += 4*nverts;
+ mTexCoords = (LLVector2*)(mVertexData + offset); offset += 2*nverts;
+
+ // these members don't need to be 16-byte aligned, but the first one might be
+ // read during an aligned memcpy of mTexCoords
+ mScaledNormals = (LLVector3*)(mVertexData + offset); offset += 3*nverts;
+ mBinormals = (LLVector3*)(mVertexData + offset); offset += 3*nverts;
+ mScaledBinormals = (LLVector3*)(mVertexData + offset); offset += 3*nverts;
+
+
#else
mCoords = new LLVector3[mSharedData->mNumVertices];
mNormals = new LLVector3[mSharedData->mNumVertices];
@@ -751,7 +761,7 @@ LLPolyMesh::~LLPolyMesh()
delete [] mClothingWeights;
delete [] mTexCoords;
#else
- delete [] mVertexData;
+ free(mVertexData);
#endif
}
@@ -858,7 +868,7 @@ void LLPolyMesh::dumpDiagInfo()
//-----------------------------------------------------------------------------
// getWritableCoords()
//-----------------------------------------------------------------------------
-LLVector3 *LLPolyMesh::getWritableCoords()
+LLVector4 *LLPolyMesh::getWritableCoords()
{
return mCoords;
}
@@ -866,7 +876,7 @@ LLVector3 *LLPolyMesh::getWritableCoords()
//-----------------------------------------------------------------------------
// getWritableNormals()
//-----------------------------------------------------------------------------
-LLVector3 *LLPolyMesh::getWritableNormals()
+LLVector4 *LLPolyMesh::getWritableNormals()
{
return mNormals;
}
@@ -921,8 +931,12 @@ void LLPolyMesh::initializeForMorph()
if (!mSharedData)
return;
- memcpy(mCoords, mSharedData->mBaseCoords, sizeof(LLVector3) * mSharedData->mNumVertices); /*Flawfinder: ignore*/
- memcpy(mNormals, mSharedData->mBaseNormals, sizeof(LLVector3) * mSharedData->mNumVertices); /*Flawfinder: ignore*/
+ for (U32 i = 0; i < mSharedData->mNumVertices; ++i)
+ {
+ mCoords[i] = LLVector4(mSharedData->mBaseCoords[i]);
+ mNormals[i] = LLVector4(mSharedData->mBaseNormals[i]);
+ }
+
memcpy(mScaledNormals, mSharedData->mBaseNormals, sizeof(LLVector3) * mSharedData->mNumVertices); /*Flawfinder: ignore*/
memcpy(mBinormals, mSharedData->mBaseBinormals, sizeof(LLVector3) * mSharedData->mNumVertices); /*Flawfinder: ignore*/
memcpy(mScaledBinormals, mSharedData->mBaseBinormals, sizeof(LLVector3) * mSharedData->mNumVertices); /*Flawfinder: ignore*/
diff --git a/indra/newview/llpolymesh.h b/indra/newview/llpolymesh.h
index 894cd307c4..ba2bf85570 100644
--- a/indra/newview/llpolymesh.h
+++ b/indra/newview/llpolymesh.h
@@ -217,15 +217,15 @@ public:
}
// Get coords
- const LLVector3 *getCoords() const{
+ const LLVector4 *getCoords() const{
return mCoords;
}
// non const version
- LLVector3 *getWritableCoords();
+ LLVector4 *getWritableCoords();
// Get normals
- const LLVector3 *getNormals() const{
+ const LLVector4 *getNormals() const{
return mNormals;
}
@@ -247,7 +247,7 @@ public:
}
// intermediate morphed normals and output normals
- LLVector3 *getWritableNormals();
+ LLVector4 *getWritableNormals();
LLVector3 *getScaledNormals();
LLVector3 *getWritableBinormals();
@@ -341,11 +341,11 @@ protected:
// Single array of floats for allocation / deletion
F32 *mVertexData;
// deformed vertices (resulting from application of morph targets)
- LLVector3 *mCoords;
+ LLVector4 *mCoords;
// deformed normals (resulting from application of morph targets)
LLVector3 *mScaledNormals;
// output normals (after normalization)
- LLVector3 *mNormals;
+ LLVector4 *mNormals;
// deformed binormals (resulting from application of morph targets)
LLVector3 *mScaledBinormals;
// output binormals (after normalization)
diff --git a/indra/newview/llpolymorph.cpp b/indra/newview/llpolymorph.cpp
index 0ffe1c635f..37e1d4e471 100644
--- a/indra/newview/llpolymorph.cpp
+++ b/indra/newview/llpolymorph.cpp
@@ -455,10 +455,10 @@ void LLPolyMorphTarget::apply( ESex avatar_sex )
if (delta_weight != 0.f)
{
llassert(!mMesh->isLOD());
- LLVector3 *coords = mMesh->getWritableCoords();
+ LLVector4 *coords = mMesh->getWritableCoords();
LLVector3 *scaled_normals = mMesh->getScaledNormals();
- LLVector3 *normals = mMesh->getWritableNormals();
+ LLVector4 *normals = mMesh->getWritableNormals();
LLVector3 *scaled_binormals = mMesh->getScaledBinormals();
LLVector3 *binormals = mMesh->getWritableBinormals();
@@ -478,7 +478,8 @@ void LLPolyMorphTarget::apply( ESex avatar_sex )
maskWeight = maskWeightArray[vert_index_morph];
}
- coords[vert_index_mesh] += mMorphData->mCoords[vert_index_morph] * delta_weight * maskWeight;
+ coords[vert_index_mesh] += LLVector4(mMorphData->mCoords[vert_index_morph] * delta_weight * maskWeight);
+
if (getInfo()->mIsClothingMorph && clothing_weights)
{
LLVector3 clothing_offset = mMorphData->mCoords[vert_index_morph] * delta_weight * maskWeight;
@@ -493,7 +494,7 @@ void LLPolyMorphTarget::apply( ESex avatar_sex )
scaled_normals[vert_index_mesh] += mMorphData->mNormals[vert_index_morph] * delta_weight * maskWeight * NORMAL_SOFTEN_FACTOR;
LLVector3 normalized_normal = scaled_normals[vert_index_mesh];
normalized_normal.normVec();
- normals[vert_index_mesh] = normalized_normal;
+ normals[vert_index_mesh] = LLVector4(normalized_normal);
// calculate new binormals
scaled_binormals[vert_index_mesh] += mMorphData->mBinormals[vert_index_morph] * delta_weight * maskWeight * NORMAL_SOFTEN_FACTOR;
@@ -542,7 +543,7 @@ void LLPolyMorphTarget::applyMask(U8 *maskTextureData, S32 width, S32 height, S3
if (maskWeights)
{
- LLVector3 *coords = mMesh->getWritableCoords();
+ LLVector4 *coords = mMesh->getWritableCoords();
LLVector3 *scaled_normals = mMesh->getScaledNormals();
LLVector3 *scaled_binormals = mMesh->getScaledBinormals();
LLVector2 *tex_coords = mMesh->getWritableTexCoords();
@@ -553,7 +554,7 @@ void LLPolyMorphTarget::applyMask(U8 *maskTextureData, S32 width, S32 height, S3
S32 out_vert = mMorphData->mVertexIndices[vert];
// remove effect of existing masked morph
- coords[out_vert] -= mMorphData->mCoords[vert] * lastMaskWeight;
+ coords[out_vert] -= LLVector4(mMorphData->mCoords[vert]) * lastMaskWeight;
scaled_normals[out_vert] -= mMorphData->mNormals[vert] * lastMaskWeight * NORMAL_SOFTEN_FACTOR;
scaled_binormals[out_vert] -= mMorphData->mBinormals[vert] * lastMaskWeight * NORMAL_SOFTEN_FACTOR;
tex_coords[out_vert] -= mMorphData->mTexCoords[vert] * lastMaskWeight;
diff --git a/indra/newview/llselectmgr.cpp b/indra/newview/llselectmgr.cpp
index 50bc0b4a98..b139ba361e 100644
--- a/indra/newview/llselectmgr.cpp
+++ b/indra/newview/llselectmgr.cpp
@@ -64,6 +64,7 @@
#include "llhudmanager.h"
#include "llinventorymodel.h"
#include "llmenugl.h"
+#include "llmeshrepository.h"
#include "llmutelist.h"
#include "llnotificationsutil.h"
#include "llsidepaneltaskinfo.h"
@@ -176,7 +177,6 @@ LLObjectSelection *get_null_object_selection()
// Build time optimization, generate this function once here
template class LLSelectMgr* LLSingleton<class LLSelectMgr>::getInstance();
-
//-----------------------------------------------------------------------------
// LLSelectMgr()
//-----------------------------------------------------------------------------
@@ -1193,8 +1193,8 @@ void LLSelectMgr::getGrid(LLVector3& origin, LLQuaternion &rotation, LLVector3 &
mGridRotation = first_grid_object->getRenderRotation();
LLVector3 first_grid_obj_pos = first_grid_object->getRenderPosition();
- LLVector3 min_extents(F32_MAX, F32_MAX, F32_MAX);
- LLVector3 max_extents(-F32_MAX, -F32_MAX, -F32_MAX);
+ LLVector4a min_extents(F32_MAX);
+ LLVector4a max_extents(-F32_MAX);
BOOL grid_changed = FALSE;
for (LLObjectSelection::iterator iter = mGridObjects.begin();
iter != mGridObjects.end(); ++iter)
@@ -1203,7 +1203,7 @@ void LLSelectMgr::getGrid(LLVector3& origin, LLQuaternion &rotation, LLVector3 &
LLDrawable* drawable = object->mDrawable;
if (drawable)
{
- const LLVector3* ext = drawable->getSpatialExtents();
+ const LLVector4a* ext = drawable->getSpatialExtents();
update_min_max(min_extents, max_extents, ext[0]);
update_min_max(min_extents, max_extents, ext[1]);
grid_changed = TRUE;
@@ -1211,13 +1211,19 @@ void LLSelectMgr::getGrid(LLVector3& origin, LLQuaternion &rotation, LLVector3 &
}
if (grid_changed)
{
- mGridOrigin = lerp(min_extents, max_extents, 0.5f);
+ LLVector4a center, size;
+ center.setAdd(min_extents, max_extents);
+ center.mul(0.5f);
+ size.setSub(max_extents, min_extents);
+ size.mul(0.5f);
+
+ mGridOrigin.set(center.getF32ptr());
LLDrawable* drawable = first_grid_object->mDrawable;
if (drawable && drawable->isActive())
{
mGridOrigin = mGridOrigin * first_grid_object->getRenderMatrix();
}
- mGridScale = (max_extents - min_extents) * 0.5f;
+ mGridScale.set(size.getF32ptr());
}
}
else // GRID_MODE_WORLD or just plain default
@@ -1981,6 +1987,103 @@ BOOL LLSelectMgr::selectionGetGlow(F32 *glow)
return identical;
}
+
+void LLSelectMgr::selectionSetPhysicsType(U8 type)
+{
+ struct f : public LLSelectedObjectFunctor
+ {
+ U8 mType;
+ f(const U8& t) : mType(t) {}
+ virtual bool apply(LLViewerObject* object)
+ {
+ if (object->permModify())
+ {
+ object->setPhysicsShapeType(mType);
+ object->updateFlags();
+ }
+ return true;
+ }
+ } sendfunc(type);
+ getSelection()->applyToObjects(&sendfunc);
+}
+
+void LLSelectMgr::selectionSetFriction(F32 friction)
+{
+ struct f : public LLSelectedObjectFunctor
+ {
+ F32 mFriction;
+ f(const F32& friction) : mFriction(friction) {}
+ virtual bool apply(LLViewerObject* object)
+ {
+ if (object->permModify())
+ {
+ object->setPhysicsFriction(mFriction);
+ object->updateFlags();
+ }
+ return true;
+ }
+ } sendfunc(friction);
+ getSelection()->applyToObjects(&sendfunc);
+}
+
+void LLSelectMgr::selectionSetGravity(F32 gravity )
+{
+ struct f : public LLSelectedObjectFunctor
+ {
+ F32 mGravity;
+ f(const F32& gravity) : mGravity(gravity) {}
+ virtual bool apply(LLViewerObject* object)
+ {
+ if (object->permModify())
+ {
+ object->setPhysicsGravity(mGravity);
+ object->updateFlags();
+ }
+ return true;
+ }
+ } sendfunc(gravity);
+ getSelection()->applyToObjects(&sendfunc);
+}
+
+void LLSelectMgr::selectionSetDensity(F32 density )
+{
+ struct f : public LLSelectedObjectFunctor
+ {
+ F32 mDensity;
+ f(const F32& density ) : mDensity(density) {}
+ virtual bool apply(LLViewerObject* object)
+ {
+ if (object->permModify())
+ {
+ object->setPhysicsDensity(mDensity);
+ object->updateFlags();
+ }
+ return true;
+ }
+ } sendfunc(density);
+ getSelection()->applyToObjects(&sendfunc);
+}
+
+void LLSelectMgr::selectionSetRestitution(F32 restitution)
+{
+ struct f : public LLSelectedObjectFunctor
+ {
+ F32 mRestitution;
+ f(const F32& restitution ) : mRestitution(restitution) {}
+ virtual bool apply(LLViewerObject* object)
+ {
+ if (object->permModify())
+ {
+ object->setPhysicsRestitution(mRestitution);
+ object->updateFlags();
+ }
+ return true;
+ }
+ } sendfunc(restitution);
+ getSelection()->applyToObjects(&sendfunc);
+}
+
+
//-----------------------------------------------------------------------------
// selectionSetMaterial()
//-----------------------------------------------------------------------------
@@ -3630,7 +3733,7 @@ void LLSelectMgr::deselectAllIfTooFar()
{
if (mDebugSelectMgr)
{
- llinfos << "Selection manager: auto-deselecting, select_dist = " << fsqrtf(select_dist_sq) << llendl;
+ llinfos << "Selection manager: auto-deselecting, select_dist = " << (F32) sqrt(select_dist_sq) << llendl;
llinfos << "agent pos global = " << gAgent.getPositionGlobal() << llendl;
llinfos << "selection pos global = " << selectionCenter << llendl;
}
@@ -3799,6 +3902,26 @@ void LLSelectMgr::sendDelink()
return;
}
+ struct f : public LLSelectedObjectFunctor
+ { //on delink, any modifyable object should
+ f() {}
+
+ virtual bool apply(LLViewerObject* object)
+ {
+ if (object->permModify())
+ {
+ if (object->getPhysicsShapeType() == LLViewerObject::PHYSICS_SHAPE_NONE)
+ {
+ object->setPhysicsShapeType(LLViewerObject::PHYSICS_SHAPE_CONVEX_HULL);
+ object->updateFlags();
+ }
+ }
+ return true;
+ }
+ } sendfunc;
+ getSelection()->applyToObjects(&sendfunc);
+
+
// Delink needs to send individuals so you can unlink a single object from
// a linked set.
sendListToRegions(
@@ -4028,7 +4151,6 @@ void LLSelectMgr::selectionUpdateCastShadows(BOOL cast_shadows)
getSelection()->applyToObjects(&func);
}
-
//----------------------------------------------------------------------
// Helpful packing functions for sendObjectMessage()
//----------------------------------------------------------------------
@@ -4717,7 +4839,6 @@ void LLSelectMgr::processForceObjectSelect(LLMessageSystem* msg, void**)
LLSelectMgr::getInstance()->highlightObjectAndFamily(objects);
}
-
extern LLGLdouble gGLModelView[16];
void LLSelectMgr::updateSilhouettes()
@@ -5201,7 +5322,6 @@ LLSelectNode::LLSelectNode(const LLSelectNode& nodep)
mSilhouetteVertices = nodep.mSilhouetteVertices;
mSilhouetteNormals = nodep.mSilhouetteNormals;
- mSilhouetteSegments = nodep.mSilhouetteSegments;
mSilhouetteExists = nodep.mSilhouetteExists;
mObject = nodep.mObject;
@@ -5435,6 +5555,111 @@ BOOL LLSelectNode::allowOperationOnNode(PermissionBit op, U64 group_proxy_power)
return (mPermissions->allowOperationBy(op, proxy_agent_id, group_id));
}
+
+//helper function for pushing relevant vertices from drawable to GL
+void pushWireframe(LLDrawable* drawable)
+{
+ if (drawable->isState(LLDrawable::RIGGED))
+ { //render straight from rigged volume if this is a rigged attachment
+ LLVOVolume* vobj = drawable->getVOVolume();
+ if (vobj)
+ {
+ vobj->updateRiggedVolume();
+ LLRiggedVolume* rigged_volume = vobj->getRiggedVolume();
+ if (rigged_volume)
+ {
+ LLVertexBuffer::unbind();
+ gGL.pushMatrix();
+ glMultMatrixf((F32*) vobj->getRelativeXform().mMatrix);
+ for (S32 i = 0; i < rigged_volume->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = rigged_volume->getVolumeFace(i);
+ glVertexPointer(3, GL_FLOAT, 16, face.mPositions);
+ glDrawElements(GL_TRIANGLES, face.mNumIndices, GL_UNSIGNED_SHORT, face.mIndices);
+ }
+ gGL.popMatrix();
+ }
+ }
+ }
+ else
+ {
+ for (S32 i = 0; i < drawable->getNumFaces(); ++i)
+ {
+ LLFace* face = drawable->getFace(i);
+ if (face->verify())
+ {
+ pushVerts(face, LLVertexBuffer::MAP_VERTEX);
+ }
+ }
+ }
+}
+
+void LLSelectNode::renderOneWireframe(const LLColor4& color)
+{
+ LLViewerObject* objectp = getObject();
+ if (!objectp)
+ {
+ return;
+ }
+
+ LLDrawable* drawable = objectp->mDrawable;
+ if(!drawable)
+ {
+ return;
+ }
+
+ glMatrixMode(GL_MODELVIEW);
+ gGL.pushMatrix();
+
+ BOOL is_hud_object = objectp->isHUDAttachment();
+
+ if (drawable->isActive())
+ {
+ glLoadMatrixd(gGLModelView);
+ glMultMatrixf((F32*) objectp->getRenderMatrix().mMatrix);
+ }
+ else if (!is_hud_object)
+ {
+ glLoadIdentity();
+ glMultMatrixd(gGLModelView);
+ LLVector3 trans = objectp->getRegion()->getOriginAgent();
+ glTranslatef(trans.mV[0], trans.mV[1], trans.mV[2]);
+ }
+
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+
+ if (LLSelectMgr::sRenderHiddenSelections) // && gFloaterTools && gFloaterTools->getVisible())
+ {
+ gGL.blendFunc(LLRender::BF_SOURCE_COLOR, LLRender::BF_ONE);
+ LLGLEnable fog(GL_FOG);
+ glFogi(GL_FOG_MODE, GL_LINEAR);
+ float d = (LLViewerCamera::getInstance()->getPointOfInterest()-LLViewerCamera::getInstance()->getOrigin()).magVec();
+ LLColor4 fogCol = color * (F32)llclamp((LLSelectMgr::getInstance()->getSelectionCenterGlobal()-gAgentCamera.getCameraPositionGlobal()).magVec()/(LLSelectMgr::getInstance()->getBBoxOfSelection().getExtentLocal().magVec()*4), 0.0, 1.0);
+ glFogf(GL_FOG_START, d);
+ glFogf(GL_FOG_END, d*(1 + (LLViewerCamera::getInstance()->getView() / LLViewerCamera::getInstance()->getDefaultFOV())));
+ glFogfv(GL_FOG_COLOR, fogCol.mV);
+
+ LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE, GL_GEQUAL);
+ gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
+ {
+ glColor4f(color.mV[VRED], color.mV[VGREEN], color.mV[VBLUE], 0.4f);
+ pushWireframe(drawable);
+ }
+ }
+
+ gGL.flush();
+ gGL.setSceneBlendType(LLRender::BT_ALPHA);
+
+ glColor4f(color.mV[VRED]*2, color.mV[VGREEN]*2, color.mV[VBLUE]*2, LLSelectMgr::sHighlightAlpha*2);
+ LLGLEnable offset(GL_POLYGON_OFFSET_LINE);
+ glPolygonOffset(3.f, 3.f);
+ glLineWidth(3.f);
+ pushWireframe(drawable);
+ glLineWidth(1.f);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ gGL.popMatrix();
+}
+
//-----------------------------------------------------------------------------
// renderOneSilhouette()
//-----------------------------------------------------------------------------
@@ -5452,6 +5677,13 @@ void LLSelectNode::renderOneSilhouette(const LLColor4 &color)
return;
}
+ LLVOVolume* vobj = drawable->getVOVolume();
+ if (vobj && vobj->isMesh())
+ {
+ renderOneWireframe(color);
+ return;
+ }
+
if (!mSilhouetteExists)
{
return;
@@ -5516,17 +5748,15 @@ void LLSelectNode::renderOneSilhouette(const LLColor4 &color)
gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
gGL.begin(LLRender::LINES);
{
- S32 i = 0;
- for (S32 seg_num = 0; seg_num < (S32)mSilhouetteSegments.size(); seg_num++)
+ for(S32 i = 0; i < mSilhouetteVertices.size(); i += 2)
{
- for(; i < mSilhouetteSegments[seg_num]; i++)
- {
- u_coord += u_divisor * LLSelectMgr::sHighlightUScale;
-
- gGL.color4f(color.mV[VRED], color.mV[VGREEN], color.mV[VBLUE], 0.4f);
- gGL.texCoord2f( u_coord, v_coord );
- gGL.vertex3fv( mSilhouetteVertices[i].mV );
- }
+ u_coord += u_divisor * LLSelectMgr::sHighlightUScale;
+ gGL.color4f(color.mV[VRED], color.mV[VGREEN], color.mV[VBLUE], 0.4f);
+ gGL.texCoord2f( u_coord, v_coord );
+ gGL.vertex3fv( mSilhouetteVertices[i].mV);
+ u_coord += u_divisor * LLSelectMgr::sHighlightUScale;
+ gGL.texCoord2f( u_coord, v_coord );
+ gGL.vertex3fv(mSilhouetteVertices[i+1].mV);
}
}
gGL.end();
@@ -5537,51 +5767,50 @@ void LLSelectNode::renderOneSilhouette(const LLColor4 &color)
gGL.setSceneBlendType(LLRender::BT_ALPHA);
gGL.begin(LLRender::TRIANGLES);
{
- S32 i = 0;
- for (S32 seg_num = 0; seg_num < (S32)mSilhouetteSegments.size(); seg_num++)
+ for(S32 i = 0; i < mSilhouetteVertices.size(); i+=2)
{
- S32 first_i = i;
- LLVector3 v;
- LLVector2 t;
+ if (!mSilhouetteNormals[i].isFinite() ||
+ !mSilhouetteNormals[i+1].isFinite())
+ { //skip skewed segments
+ continue;
+ }
- for(; i < mSilhouetteSegments[seg_num]; i++)
- {
+ LLVector3 v[4];
+ LLVector2 tc[4];
+ v[0] = mSilhouetteVertices[i] + (mSilhouetteNormals[i] * silhouette_thickness);
+ tc[0].set(u_coord, v_coord + LLSelectMgr::sHighlightVScale);
- if (i == first_i) {
- LLVector3 vert = (mSilhouetteNormals[i]) * silhouette_thickness;
- vert += mSilhouetteVertices[i];
+ v[1] = mSilhouetteVertices[i];
+ tc[1].set(u_coord, v_coord);
- gGL.color4f(color.mV[VRED], color.mV[VGREEN], color.mV[VBLUE], 0.0f); //LLSelectMgr::sHighlightAlpha);
- gGL.texCoord2f( u_coord, v_coord + LLSelectMgr::sHighlightVScale );
- gGL.vertex3fv( vert.mV );
-
- u_coord += u_divisor * LLSelectMgr::sHighlightUScale;
+ u_coord += u_divisor * LLSelectMgr::sHighlightUScale;
- gGL.color4f(color.mV[VRED]*2, color.mV[VGREEN]*2, color.mV[VBLUE]*2, LLSelectMgr::sHighlightAlpha*2);
- gGL.texCoord2f( u_coord, v_coord );
- gGL.vertex3fv( mSilhouetteVertices[i].mV );
+ v[2] = mSilhouetteVertices[i+1] + (mSilhouetteNormals[i+1] * silhouette_thickness);
+ tc[2].set(u_coord, v_coord + LLSelectMgr::sHighlightVScale);
+
+ v[3] = mSilhouetteVertices[i+1];
+ tc[3].set(u_coord,v_coord);
- v = mSilhouetteVertices[i];
- t = LLVector2(u_coord, v_coord);
- }
- else {
- LLVector3 vert = (mSilhouetteNormals[i]) * silhouette_thickness;
- vert += mSilhouetteVertices[i];
-
- gGL.color4f(color.mV[VRED], color.mV[VGREEN], color.mV[VBLUE], 0.0f); //LLSelectMgr::sHighlightAlpha);
- gGL.texCoord2f( u_coord, v_coord + LLSelectMgr::sHighlightVScale );
- gGL.vertex3fv( vert.mV );
- gGL.vertex3fv( vert.mV );
-
- gGL.texCoord2fv(t.mV);
- u_coord += u_divisor * LLSelectMgr::sHighlightUScale;
- gGL.color4f(color.mV[VRED]*2, color.mV[VGREEN]*2, color.mV[VBLUE]*2, LLSelectMgr::sHighlightAlpha*2);
- gGL.vertex3fv(v.mV);
- gGL.texCoord2f( u_coord, v_coord );
- gGL.vertex3fv( mSilhouetteVertices[i].mV );
+ gGL.color4f(color.mV[VRED], color.mV[VGREEN], color.mV[VBLUE], 0.0f); //LLSelectMgr::sHighlightAlpha);
+ gGL.texCoord2fv(tc[0].mV);
+ gGL.vertex3fv( v[0].mV );
+
+ gGL.color4f(color.mV[VRED]*2, color.mV[VGREEN]*2, color.mV[VBLUE]*2, LLSelectMgr::sHighlightAlpha*2);
+ gGL.texCoord2fv( tc[1].mV );
+ gGL.vertex3fv( v[1].mV );
- }
- }
+ gGL.color4f(color.mV[VRED], color.mV[VGREEN], color.mV[VBLUE], 0.0f); //LLSelectMgr::sHighlightAlpha);
+ gGL.texCoord2fv( tc[2].mV );
+ gGL.vertex3fv( v[2].mV );
+
+ gGL.vertex3fv( v[2].mV );
+
+ gGL.color4f(color.mV[VRED]*2, color.mV[VGREEN]*2, color.mV[VBLUE]*2, LLSelectMgr::sHighlightAlpha*2);
+ gGL.texCoord2fv( tc[1].mV );
+ gGL.vertex3fv( v[1].mV );
+
+ gGL.texCoord2fv( tc[3].mV );
+ gGL.vertex3fv( v[3].mV );
}
}
gGL.end();
@@ -6145,13 +6374,170 @@ BOOL LLObjectSelection::isEmpty() const
//-----------------------------------------------------------------------------
// getObjectCount() - returns number of non null objects
//-----------------------------------------------------------------------------
-S32 LLObjectSelection::getObjectCount()
+S32 LLObjectSelection::getObjectCount(BOOL mesh_adjust)
{
cleanupNodes();
S32 count = mList.size();
+
return count;
}
+F32 LLObjectSelection::getSelectedObjectCost()
+{
+ cleanupNodes();
+ F32 cost = 0.f;
+
+ for (list_t::iterator iter = mList.begin(); iter != mList.end(); ++iter)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* object = node->getObject();
+
+ if (object)
+ {
+ cost += object->getObjectCost();
+ }
+ }
+
+ return cost;
+}
+
+F32 LLObjectSelection::getSelectedLinksetCost()
+{
+ cleanupNodes();
+ F32 cost = 0.f;
+
+ std::set<LLViewerObject*> me_roots;
+
+ for (list_t::iterator iter = mList.begin(); iter != mList.end(); ++iter)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* object = node->getObject();
+
+ if (object)
+ {
+ LLViewerObject* root = static_cast<LLViewerObject*>(object->getRoot());
+ if (root)
+ {
+ if (me_roots.find(root) == me_roots.end())
+ {
+ me_roots.insert(root);
+ cost += root->getLinksetCost();
+ }
+ }
+ }
+ }
+
+ return cost;
+}
+
+F32 LLObjectSelection::getSelectedPhysicsCost()
+{
+ cleanupNodes();
+ F32 cost = 0.f;
+
+ for (list_t::iterator iter = mList.begin(); iter != mList.end(); ++iter)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* object = node->getObject();
+
+ if (object)
+ {
+ cost += object->getPhysicsCost();
+ }
+ }
+
+ return cost;
+}
+
+F32 LLObjectSelection::getSelectedLinksetPhysicsCost()
+{
+ cleanupNodes();
+ F32 cost = 0.f;
+
+ std::set<LLViewerObject*> me_roots;
+
+ for (list_t::iterator iter = mList.begin(); iter != mList.end(); ++iter)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* object = node->getObject();
+
+ if (object)
+ {
+ LLViewerObject* root = static_cast<LLViewerObject*>(object->getRoot());
+ if (root)
+ {
+ if (me_roots.find(root) == me_roots.end())
+ {
+ me_roots.insert(root);
+ cost += root->getLinksetPhysicsCost();
+ }
+ }
+ }
+ }
+
+ return cost;
+}
+
+F32 LLObjectSelection::getSelectedObjectStreamingCost()
+{
+ F32 cost = 0.f;
+ for (list_t::iterator iter = mList.begin(); iter != mList.end(); ++iter)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* object = node->getObject();
+
+ if (object)
+ {
+ cost += object->getStreamingCost();
+ }
+ }
+
+ return cost;
+}
+
+U32 LLObjectSelection::getSelectedObjectTriangleCount()
+{
+ U32 count = 0;
+ for (list_t::iterator iter = mList.begin(); iter != mList.end(); ++iter)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* object = node->getObject();
+
+ if (object)
+ {
+ count += object->getTriangleCount();
+ }
+ }
+
+ return count;
+}
+
+/*S32 LLObjectSelection::getSelectedObjectRenderCost()
+{
+ S32 cost = 0;
+ LLVOVolume::texture_cost_t textures;
+ for (list_t::iterator iter = mList.begin(); iter != mList.end(); ++iter)
+ {
+ LLSelectNode* node = *iter;
+ LLVOVolume* object = (LLVOVolume*)node->getObject();
+
+ if (object)
+ {
+ cost += object->getRenderCost(textures);
+ }
+
+ for (LLVOVolume::texture_cost_t::iterator iter = textures.begin(); iter != textures.end(); ++iter)
+ {
+ // add the cost of each individual texture in the linkset
+ cost += iter->second;
+ }
+ textures.clear();
+ }
+
+
+ return cost;
+}*/
+
//-----------------------------------------------------------------------------
// getTECount()
diff --git a/indra/newview/llselectmgr.h b/indra/newview/llselectmgr.h
index cb387f5c3c..031898d7c5 100644
--- a/indra/newview/llselectmgr.h
+++ b/indra/newview/llselectmgr.h
@@ -134,6 +134,7 @@ public:
BOOL isTESelected(S32 te_index);
S32 getLastSelectedTE();
S32 getTESelectMask() { return mTESelectMask; }
+ void renderOneWireframe(const LLColor4& color);
void renderOneSilhouette(const LLColor4 &color);
void setTransient(BOOL transient) { mTransient = transient; }
BOOL isTransient() { return mTransient; }
@@ -181,7 +182,6 @@ public:
std::vector<LLVector3> mTextureScaleRatios;
std::vector<LLVector3> mSilhouetteVertices; // array of vertices to render silhouette of object
std::vector<LLVector3> mSilhouetteNormals; // array of normals to render silhouette of object
- std::vector<S32> mSilhouetteSegments; // array of normals to render silhouette of object
BOOL mSilhouetteExists; // need to generate silhouette?
protected:
@@ -278,7 +278,16 @@ public:
LLSelectNode* findNode(LLViewerObject* objectp);
// count members
- S32 getObjectCount();
+ S32 getObjectCount(BOOL mesh_adjust = FALSE);
+ F32 getSelectedObjectCost();
+ F32 getSelectedLinksetCost();
+ F32 getSelectedPhysicsCost();
+ F32 getSelectedLinksetPhysicsCost();
+ S32 getSelectedObjectRenderCost();
+
+ F32 getSelectedObjectStreamingCost();
+ U32 getSelectedObjectTriangleCount();
+
S32 getTECount();
S32 getRootObjectCount();
@@ -500,6 +509,11 @@ public:
bool selectionGetIncludeInSearch(bool* include_in_search_out); // true if all selected objects have same
BOOL selectionGetGlow(F32 *glow);
+ void selectionSetPhysicsType(U8 type);
+ void selectionSetGravity(F32 gravity);
+ void selectionSetFriction(F32 friction);
+ void selectionSetDensity(F32 density);
+ void selectionSetRestitution(F32 restitution);
void selectionSetMaterial(U8 material);
void selectionSetImage(const LLUUID& imageid); // could be item or asset id
void selectionSetColor(const LLColor4 &color);
diff --git a/indra/newview/llspatialpartition.cpp b/indra/newview/llspatialpartition.cpp
index 8adb8c30e0..5e7af6bbb3 100644
--- a/indra/newview/llspatialpartition.cpp
+++ b/indra/newview/llspatialpartition.cpp
@@ -32,15 +32,19 @@
#include "llviewerobjectlist.h"
#include "llvovolume.h"
#include "llvolume.h"
+#include "llvolumeoctree.h"
#include "llviewercamera.h"
#include "llface.h"
#include "llviewercontrol.h"
#include "llviewerregion.h"
#include "llcamera.h"
#include "pipeline.h"
+#include "llmeshrepository.h"
#include "llrender.h"
#include "lloctree.h"
+#include "llphysicsshapebuilderutil.h"
#include "llvoavatar.h"
+#include "llvolumemgr.h"
#include "lltextureatlas.h"
static LLFastTimer::DeclareTimer FTM_FRUSTUM_CULL("Frustum Culling");
@@ -60,6 +64,12 @@ const F32 SG_OCCLUSION_FUDGE = 0.25f;
static U32 sZombieGroups = 0;
U32 LLSpatialGroup::sNodeCount = 0;
+
+#define LL_TRACK_PENDING_OCCLUSION_QUERIES 0
+
+std::set<GLuint> LLSpatialGroup::sPendingQueries;
+
+
BOOL LLSpatialGroup::sNoDelete = FALSE;
static F32 sLastMaxTexPriority = 1.f;
@@ -77,6 +87,9 @@ protected:
virtual void releaseName(GLuint name)
{
+#if LL_TRACK_PENDING_OCCLUSION_QUERIES
+ LLSpatialGroup::sPendingQueries.erase(name);
+#endif
glDeleteQueriesARB(1, &name);
}
};
@@ -95,23 +108,6 @@ void sg_assert(BOOL expr)
#endif
}
-#if LL_DEBUG
-void validate_drawable(LLDrawable* drawablep)
-{
- F64 rad = drawablep->getBinRadius();
- const LLVector3* ext = drawablep->getSpatialExtents();
-
- if (rad < 0 || rad > 4096 ||
- (ext[1]-ext[0]).magVec() > 4096)
- {
- llwarns << "Invalid drawable found in octree." << llendl;
- }
-}
-#else
-#define validate_drawable(x)
-#endif
-
-
S32 AABBSphereIntersect(const LLVector3& min, const LLVector3& max, const LLVector3 &origin, const F32 &rad)
{
return AABBSphereIntersectR2(min, max, origin, rad*rad);
@@ -151,6 +147,55 @@ S32 AABBSphereIntersectR2(const LLVector3& min, const LLVector3& max, const LLVe
}
+S32 AABBSphereIntersect(const LLVector4a& min, const LLVector4a& max, const LLVector3 &origin, const F32 &rad)
+{
+ return AABBSphereIntersectR2(min, max, origin, rad*rad);
+}
+
+S32 AABBSphereIntersectR2(const LLVector4a& min, const LLVector4a& max, const LLVector3 &origin, const F32 &r)
+{
+ F32 d = 0.f;
+ F32 t;
+
+ LLVector4a origina;
+ origina.load3(origin.mV);
+
+ LLVector4a v;
+ v.setSub(min, origina);
+
+ if (v.dot3(v) < r)
+ {
+ v.setSub(max, origina);
+ if (v.dot3(v) < r)
+ {
+ return 2;
+ }
+ }
+
+
+ for (U32 i = 0; i < 3; i++)
+ {
+ if (origin.mV[i] < min[i])
+ {
+ t = min[i] - origin.mV[i];
+ d += t*t;
+ }
+ else if (origin.mV[i] > max[i])
+ {
+ t = origin.mV[i] - max[i];
+ d += t*t;
+ }
+
+ if (d > r)
+ {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+
typedef enum
{
b000 = 0x00,
@@ -168,76 +213,113 @@ typedef enum
//gives you a triangle fan index array
static U8 sOcclusionIndices[] =
{
- // 000
+ //000
b111, b110, b010, b011, b001, b101, b100, b110,
- //001
- b110, b000, b010, b011, b111, b101, b100, b000,
+ //001
+ b011, b010, b000, b001, b101, b111, b110, b010,
//010
b101, b100, b110, b111, b011, b001, b000, b100,
//011
- b100, b010, b110, b111, b101, b001, b000, b010,
- //100
- b011, b010, b000, b001, b101, b111, b110, b010,
+ b001, b000, b100, b101, b111, b011, b010, b000,
+ //100
+ b110, b000, b010, b011, b111, b101, b100, b000,
//101
b010, b100, b000, b001, b011, b111, b110, b100,
//110
- b001, b000, b100, b101, b111, b011, b010, b000,
+ b100, b010, b110, b111, b101, b001, b000, b010,
//111
b000, b110, b100, b101, b001, b011, b010, b110,
};
-U8* get_box_fan_indices(LLCamera* camera, const LLVector3& center)
+U32 get_box_fan_indices(LLCamera* camera, const LLVector4a& center)
{
- LLVector3 d = center - camera->getOrigin();
+ LLVector4a origin;
+ origin.load3(camera->getOrigin().mV);
- U8 cypher = 0;
- if (d.mV[0] > 0)
- {
- cypher |= b100;
- }
- if (d.mV[1] > 0)
- {
- cypher |= b010;
- }
- if (d.mV[2] > 0)
- {
- cypher |= b001;
- }
+ S32 cypher = center.greaterThan(origin).getGatheredBits() & 0x7;
+
+ return cypher*8;
+}
+
+U8* get_box_fan_indices_ptr(LLCamera* camera, const LLVector4a& center)
+{
+ LLVector4a origin;
+ origin.load3(camera->getOrigin().mV);
+ S32 cypher = center.greaterThan(origin).getGatheredBits() & 0x7;
+
return sOcclusionIndices+cypher*8;
}
-
+
+
+static LLFastTimer::DeclareTimer FTM_BUILD_OCCLUSION("Build Occlusion");
+
void LLSpatialGroup::buildOcclusion()
{
- if (!mOcclusionVerts)
+ if (mOcclusionVerts.isNull())
{
- mOcclusionVerts = new F32[8*3];
+
+ mOcclusionVerts = new LLVertexBuffer(LLVertexBuffer::MAP_VERTEX,
+ LLVertexBuffer::sUseStreamDraw ? mBufferUsage : 0); //if GL has a hard time with VBOs, don't use them for occlusion culling.
+ mOcclusionVerts->allocateBuffer(8, 64, true);
+
+ LLStrider<U16> idx;
+ mOcclusionVerts->getIndexStrider(idx);
+ for (U32 i = 0; i < 64; i++)
+ {
+ *idx++ = sOcclusionIndices[i];
+ }
}
- LLVector3 r = mBounds[1] + LLVector3(SG_OCCLUSION_FUDGE, SG_OCCLUSION_FUDGE, SG_OCCLUSION_FUDGE);
+ LLVector4a fudge;
+ fudge.splat(SG_OCCLUSION_FUDGE);
- for (U32 k = 0; k < 3; k++)
+ LLVector4a r;
+ r.setAdd(mBounds[1], fudge);
+
+ LLStrider<LLVector3> pos;
+
{
- r.mV[k] = llmin(mBounds[1].mV[k]+0.25f, r.mV[k]);
+ LLFastTimer t(FTM_BUILD_OCCLUSION);
+ mOcclusionVerts->getVertexStrider(pos);
}
- F32* v = mOcclusionVerts;
- F32* c = mBounds[0].mV;
- F32* s = r.mV;
+ {
+ LLVector4a* v = (LLVector4a*) pos.get();
+
+ const LLVector4a& c = mBounds[0];
+ const LLVector4a& s = r;
+
+ static const LLVector4a octant[] =
+ {
+ LLVector4a(-1.f, -1.f, -1.f),
+ LLVector4a(-1.f, -1.f, 1.f),
+ LLVector4a(-1.f, 1.f, -1.f),
+ LLVector4a(-1.f, 1.f, 1.f),
+
+ LLVector4a(1.f, -1.f, -1.f),
+ LLVector4a(1.f, -1.f, 1.f),
+ LLVector4a(1.f, 1.f, -1.f),
+ LLVector4a(1.f, 1.f, 1.f),
+ };
+
+ //vertex positions are encoded so the 3 bits of their vertex index
+ //correspond to their axis facing, with bit position 3,2,1 matching
+ //axis facing x,y,z, bit set meaning positive facing, bit clear
+ //meaning negative facing
+
+ for (S32 i = 0; i < 8; ++i)
+ {
+ LLVector4a p;
+ p.setMul(s, octant[i]);
+ p.add(c);
+ v[i] = p;
+ }
+ }
- //vertex positions are encoded so the 3 bits of their vertex index
- //correspond to their axis facing, with bit position 3,2,1 matching
- //axis facing x,y,z, bit set meaning positive facing, bit clear
- //meaning negative facing
- v[0] = c[0]-s[0]; v[1] = c[1]-s[1]; v[2] = c[2]-s[2]; // 0 - 0000
- v[3] = c[0]-s[0]; v[4] = c[1]-s[1]; v[5] = c[2]+s[2]; // 1 - 0001
- v[6] = c[0]-s[0]; v[7] = c[1]+s[1]; v[8] = c[2]-s[2]; // 2 - 0010
- v[9] = c[0]-s[0]; v[10] = c[1]+s[1]; v[11] = c[2]+s[2]; // 3 - 0011
-
- v[12] = c[0]+s[0]; v[13] = c[1]-s[1]; v[14] = c[2]-s[2]; // 4 - 0100
- v[15] = c[0]+s[0]; v[16] = c[1]-s[1]; v[17] = c[2]+s[2]; // 5 - 0101
- v[18] = c[0]+s[0]; v[19] = c[1]+s[1]; v[20] = c[2]-s[2]; // 6 - 0110
- v[21] = c[0]+s[0]; v[22] = c[1]+s[1]; v[23] = c[2]+s[2]; // 7 - 0111
+ {
+ mOcclusionVerts->setBuffer(0);
+ }
clearState(LLSpatialGroup::OCCLUSION_DIRTY);
}
@@ -281,6 +363,11 @@ LLSpatialGroup::~LLSpatialGroup()
llerrs << "Illegal deletion of LLSpatialGroup!" << llendl;
}*/
+ if (gDebugGL)
+ {
+ gPipeline.checkReferences(this);
+ }
+
if (isState(DEAD))
{
sZombieGroups--;
@@ -288,12 +375,17 @@ LLSpatialGroup::~LLSpatialGroup()
sNodeCount--;
- if (gGLManager.mHasOcclusionQuery && mOcclusionQuery[LLViewerCamera::sCurCameraID])
+ if (gGLManager.mHasOcclusionQuery)
{
- sQueryPool.release(mOcclusionQuery[LLViewerCamera::sCurCameraID]);
+ for (U32 i = 0; i < LLViewerCamera::NUM_CAMERAS; ++i)
+ {
+ if (mOcclusionQuery[i])
+ {
+ sQueryPool.release(mOcclusionQuery[i]);
+ }
+ }
}
- delete [] mOcclusionVerts;
mOcclusionVerts = NULL;
LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION);
@@ -435,7 +527,7 @@ BOOL LLSpatialGroup::isRecentlyVisible() const
BOOL LLSpatialGroup::isVisible() const
{
- return mVisible[LLViewerCamera::sCurCameraID] == LLDrawable::getCurrentFrame() ? TRUE : FALSE;
+ return mVisible[LLViewerCamera::sCurCameraID] >= LLDrawable::getCurrentFrame() ? TRUE : FALSE;
}
void LLSpatialGroup::setVisible()
@@ -450,8 +542,10 @@ void LLSpatialGroup::validate()
sg_assert(!isState(DIRTY));
sg_assert(!isDead());
- LLVector3 myMin = mBounds[0] - mBounds[1];
- LLVector3 myMax = mBounds[0] + mBounds[1];
+ LLVector4a myMin;
+ myMin.setSub(mBounds[0], mBounds[1]);
+ LLVector4a myMax;
+ myMax.setAdd(mBounds[0], mBounds[1]);
validateDrawMap();
@@ -483,16 +577,18 @@ void LLSpatialGroup::validate()
group->validate();
//ensure all children are enclosed in this node
- LLVector3 center = group->mBounds[0];
- LLVector3 size = group->mBounds[1];
+ LLVector4a center = group->mBounds[0];
+ LLVector4a size = group->mBounds[1];
- LLVector3 min = center - size;
- LLVector3 max = center + size;
+ LLVector4a min;
+ min.setSub(center, size);
+ LLVector4a max;
+ max.setAdd(center, size);
for (U32 j = 0; j < 3; j++)
{
- sg_assert(min.mV[j] >= myMin.mV[j]-0.02f);
- sg_assert(max.mV[j] <= myMax.mV[j]+0.02f);
+ sg_assert(min[j] >= myMin[j]-0.02f);
+ sg_assert(max[j] <= myMax[j]+0.02f);
}
}
@@ -502,52 +598,8 @@ void LLSpatialGroup::validate()
void LLSpatialGroup::checkStates()
{
#if LL_OCTREE_PARANOIA_CHECK
- LLOctreeStateCheck checker;
- checker.traverse(mOctreeNode);
-#endif
-}
-
-void validate_draw_info(LLDrawInfo& params)
-{
-#if LL_OCTREE_PARANOIA_CHECK
- if (params.mVertexBuffer.isNull())
- {
- llerrs << "Draw batch has no vertex buffer." << llendl;
- }
-
- //bad range
- if (params.mStart >= params.mEnd)
- {
- llerrs << "Draw batch has invalid range." << llendl;
- }
-
- if (params.mEnd >= (U32) params.mVertexBuffer->getNumVerts())
- {
- llerrs << "Draw batch has buffer overrun error." << llendl;
- }
-
- if (params.mOffset + params.mCount > (U32) params.mVertexBuffer->getNumIndices())
- {
- llerrs << "Draw batch has index buffer ovverrun error." << llendl;
- }
-
- //bad indices
- U16* indicesp = (U16*) params.mVertexBuffer->getIndicesPointer();
- if (indicesp)
- {
- for (U32 i = params.mOffset; i < params.mOffset+params.mCount; i++)
- {
- if (indicesp[i] < (U16)params.mStart)
- {
- llerrs << "Draw batch has vertex buffer index out of range error (index too low)." << llendl;
- }
-
- if (indicesp[i] > (U16)params.mEnd)
- {
- llerrs << "Draw batch has vertex buffer index out of range error (index too high)." << llendl;
- }
- }
- }
+ //LLOctreeStateCheck checker;
+ //checker.traverse(mOctreeNode);
#endif
}
@@ -560,8 +612,8 @@ void LLSpatialGroup::validateDrawMap()
for (drawmap_elem_t::iterator j = draw_vec.begin(); j != draw_vec.end(); ++j)
{
LLDrawInfo& params = **j;
-
- validate_draw_info(params);
+
+ params.validate();
}
}
#endif
@@ -572,19 +624,17 @@ BOOL LLSpatialGroup::updateInGroup(LLDrawable *drawablep, BOOL immediate)
LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION);
drawablep->updateSpatialExtents();
- validate_drawable(drawablep);
OctreeNode* parent = mOctreeNode->getOctParent();
if (mOctreeNode->isInside(drawablep->getPositionGroup()) &&
(mOctreeNode->contains(drawablep) ||
- (drawablep->getBinRadius() > mOctreeNode->getSize().mdV[0] &&
+ (drawablep->getBinRadius() > mOctreeNode->getSize()[0] &&
parent && parent->getElementCount() >= LL_OCTREE_MAX_CAPACITY)))
{
unbound();
setState(OBJECT_DIRTY);
//setState(GEOM_DIRTY);
- validate_drawable(drawablep);
return TRUE;
}
@@ -602,7 +652,6 @@ BOOL LLSpatialGroup::addObject(LLDrawable *drawablep, BOOL add_all, BOOL from_oc
else
{
drawablep->setSpatialGroup(this);
- validate_drawable(drawablep);
setState(OBJECT_DIRTY | GEOM_DIRTY);
setOcclusionState(LLSpatialGroup::DISCARD_QUERY, LLSpatialGroup::STATE_MODE_ALL_CAMERAS);
gPipeline.markRebuild(this, TRUE);
@@ -703,7 +752,7 @@ void LLSpatialPartition::rebuildMesh(LLSpatialGroup* group)
}
-BOOL LLSpatialGroup::boundObjects(BOOL empty, LLVector3& minOut, LLVector3& maxOut)
+BOOL LLSpatialGroup::boundObjects(BOOL empty, LLVector4a& minOut, LLVector4a& maxOut)
{
const OctreeNode* node = mOctreeNode;
@@ -716,8 +765,8 @@ BOOL LLSpatialGroup::boundObjects(BOOL empty, LLVector3& minOut, LLVector3& maxO
return FALSE;
}
- LLVector3& newMin = mObjectExtents[0];
- LLVector3& newMax = mObjectExtents[1];
+ LLVector4a& newMin = mObjectExtents[0];
+ LLVector4a& newMax = mObjectExtents[1];
if (isState(OBJECT_DIRTY))
{ //calculate new bounding box
@@ -726,10 +775,10 @@ BOOL LLSpatialGroup::boundObjects(BOOL empty, LLVector3& minOut, LLVector3& maxO
//initialize bounding box to first element
OctreeNode::const_element_iter i = node->getData().begin();
LLDrawable* drawablep = *i;
- const LLVector3* minMax = drawablep->getSpatialExtents();
+ const LLVector4a* minMax = drawablep->getSpatialExtents();
- newMin.setVec(minMax[0]);
- newMax.setVec(minMax[1]);
+ newMin = minMax[0];
+ newMax = minMax[1];
for (++i; i != node->getData().end(); ++i)
{
@@ -753,8 +802,10 @@ BOOL LLSpatialGroup::boundObjects(BOOL empty, LLVector3& minOut, LLVector3& maxO
}*/
}
- mObjectBounds[0] = (newMin + newMax) * 0.5f;
- mObjectBounds[1] = (newMax - newMin) * 0.5f;
+ mObjectBounds[0].setAdd(newMin, newMax);
+ mObjectBounds[0].mul(0.5f);
+ mObjectBounds[1].setSub(newMax, newMin);
+ mObjectBounds[1].mul(0.5f);
}
if (empty)
@@ -764,17 +815,8 @@ BOOL LLSpatialGroup::boundObjects(BOOL empty, LLVector3& minOut, LLVector3& maxO
}
else
{
- for (U32 i = 0; i < 3; i++)
- {
- if (newMin.mV[i] < minOut.mV[i])
- {
- minOut.mV[i] = newMin.mV[i];
- }
- if (newMax.mV[i] > maxOut.mV[i])
- {
- maxOut.mV[i] = newMax.mV[i];
- }
- }
+ minOut.setMin(minOut, newMin);
+ maxOut.setMax(maxOut, newMax);
}
return TRUE;
@@ -865,18 +907,19 @@ BOOL LLSpatialGroup::removeObject(LLDrawable *drawablep, BOOL from_octree)
return TRUE;
}
-void LLSpatialGroup::shift(const LLVector3 &offset)
+void LLSpatialGroup::shift(const LLVector4a &offset)
{
LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION);
- LLVector3d offsetd(offset);
- mOctreeNode->setCenter(mOctreeNode->getCenter()+offsetd);
+ LLVector4a t = mOctreeNode->getCenter();
+ t.add(offset);
+ mOctreeNode->setCenter(t);
mOctreeNode->updateMinMax();
- mBounds[0] += offset;
- mExtents[0] += offset;
- mExtents[1] += offset;
- mObjectBounds[0] += offset;
- mObjectExtents[0] += offset;
- mObjectExtents[1] += offset;
+ mBounds[0].add(offset);
+ mExtents[0].add(offset);
+ mExtents[1].add(offset);
+ mObjectBounds[0].add(offset);
+ mObjectExtents[0].add(offset);
+ mObjectExtents[1].add(offset);
//if (!mSpatialPartition->mRenderByGroup)
{
@@ -884,15 +927,9 @@ void LLSpatialGroup::shift(const LLVector3 &offset)
gPipeline.markRebuild(this, TRUE);
}
- if (mOcclusionVerts)
+ if (mOcclusionVerts.notNull())
{
- for (U32 i = 0; i < 8; i++)
- {
- F32* v = mOcclusionVerts+i*3;
- v[0] += offset.mV[0];
- v[1] += offset.mV[1];
- v[2] += offset.mV[2];
- }
+ setState(OCCLUSION_DIRTY);
}
}
@@ -1079,12 +1116,23 @@ void LLSpatialGroup::setOcclusionState(U32 state, S32 mode)
for (U32 i = 0; i < LLViewerCamera::NUM_CAMERAS; i++)
{
mOcclusionState[i] |= state;
+
+ if ((state & DISCARD_QUERY) && mOcclusionQuery[i])
+ {
+ sQueryPool.release(mOcclusionQuery[i]);
+ mOcclusionQuery[i] = 0;
+ }
}
}
}
else
{
mOcclusionState[LLViewerCamera::sCurCameraID] |= state;
+ if ((state & DISCARD_QUERY) && mOcclusionQuery[LLViewerCamera::sCurCameraID])
+ {
+ sQueryPool.release(mOcclusionQuery[LLViewerCamera::sCurCameraID]);
+ mOcclusionQuery[LLViewerCamera::sCurCameraID] = 0;
+ }
}
}
@@ -1152,13 +1200,11 @@ LLSpatialGroup::LLSpatialGroup(OctreeNode* node, LLSpatialPartition* part) :
mOctreeNode(node),
mSpatialPartition(part),
mVertexBuffer(NULL),
- mBufferUsage(GL_STATIC_DRAW_ARB),
+ mBufferUsage(part->mBufferUsage),
mDistance(0.f),
mDepth(0.f),
mLastUpdateDistance(-1.f),
mLastUpdateTime(gFrameTimeSeconds),
- mViewAngle(0.f),
- mLastUpdateViewAngle(-1.f),
mAtlasList(4),
mCurUpdatingTime(0),
mCurUpdatingSlotp(NULL),
@@ -1167,13 +1213,18 @@ LLSpatialGroup::LLSpatialGroup(OctreeNode* node, LLSpatialPartition* part) :
sNodeCount++;
LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION);
+ mViewAngle.splat(0.f);
+ mLastUpdateViewAngle.splat(-1.f);
+ mExtents[0] = mExtents[1] = mObjectBounds[0] = mObjectBounds[0] = mObjectBounds[1] =
+ mObjectExtents[0] = mObjectExtents[1] = mViewAngle;
+
sg_assert(mOctreeNode->getListenerCount() == 0);
mOctreeNode->addListener(this);
setState(SG_INITIAL_STATE_MASK);
gPipeline.markRebuild(this, TRUE);
- mBounds[0] = LLVector3(node->getCenter());
- mBounds[1] = LLVector3(node->getSize());
+ mBounds[0] = node->getCenter();
+ mBounds[1] = node->getSize();
part->mLODSeed = (part->mLODSeed+1)%part->mLODPeriod;
mLODHash = part->mLODSeed;
@@ -1210,8 +1261,8 @@ void LLSpatialGroup::updateDistance(LLCamera &camera)
#endif
if (!getData().empty())
{
- mRadius = mSpatialPartition->mRenderByGroup ? mObjectBounds[1].magVec() :
- (F32) mOctreeNode->getSize().magVec();
+ mRadius = mSpatialPartition->mRenderByGroup ? mObjectBounds[1].getLength3().getF32() :
+ (F32) mOctreeNode->getSize().getLength3().getF32();
mDistance = mSpatialPartition->calcDistance(this, camera);
mPixelArea = mSpatialPartition->calcPixelArea(this, camera);
}
@@ -1219,24 +1270,31 @@ void LLSpatialGroup::updateDistance(LLCamera &camera)
F32 LLSpatialPartition::calcDistance(LLSpatialGroup* group, LLCamera& camera)
{
- LLVector3 eye = group->mObjectBounds[0] - camera.getOrigin();
+ LLVector4a eye;
+ LLVector4a origin;
+ origin.load3(camera.getOrigin().mV);
+
+ eye.setSub(group->mObjectBounds[0], origin);
F32 dist = 0.f;
if (group->mDrawMap.find(LLRenderPass::PASS_ALPHA) != group->mDrawMap.end())
{
- LLVector3 v = eye;
- dist = eye.normVec();
+ LLVector4a v = eye;
+
+ dist = eye.getLength3().getF32();
+ eye.normalize3fast();
if (!group->isState(LLSpatialGroup::ALPHA_DIRTY))
{
if (!group->mSpatialPartition->isBridge())
{
- LLVector3 view_angle = LLVector3(eye * LLVector3(1,0,0),
- eye * LLVector3(0,1,0),
- eye * LLVector3(0,0,1));
+ LLVector4a view_angle = eye;
+
+ LLVector4a diff;
+ diff.setSub(view_angle, group->mLastUpdateViewAngle);
- if ((view_angle-group->mLastUpdateViewAngle).magVec() > 0.64f)
+ if (diff.getLength3().getF32() > 0.64f)
{
group->mViewAngle = view_angle;
group->mLastUpdateViewAngle = view_angle;
@@ -1253,17 +1311,20 @@ F32 LLSpatialPartition::calcDistance(LLSpatialGroup* group, LLCamera& camera)
LLVector3 at = camera.getAtAxis();
- //front of bounding box
- for (U32 i = 0; i < 3; i++)
- {
- v.mV[i] -= group->mObjectBounds[1].mV[i]*0.25f * at.mV[i];
- }
+ LLVector4a ata;
+ ata.load3(at.mV);
- group->mDepth = v * at;
+ LLVector4a t = ata;
+ //front of bounding box
+ t.mul(0.25f);
+ t.mul(group->mObjectBounds[1]);
+ v.sub(t);
+
+ group->mDepth = v.dot3(ata).getF32();
}
else
{
- dist = eye.magVec();
+ dist = eye.getLength3().getF32();
}
if (dist < 16.f)
@@ -1289,7 +1350,8 @@ F32 LLSpatialGroup::getUpdateUrgency() const
}
else
{
- return (gFrameTimeSeconds - mLastUpdateTime+4.f)/mDistance;
+ F32 time = gFrameTimeSeconds-mLastUpdateTime+4.f;
+ return time + (mObjectBounds[1].dot3(mObjectBounds[1]).getF32()+1.f)/mDistance;
}
}
@@ -1300,8 +1362,8 @@ BOOL LLSpatialGroup::needsUpdate()
BOOL LLSpatialGroup::changeLOD()
{
- if (isState(ALPHA_DIRTY))
- { ///an alpha sort is going to happen, update distance and LOD
+ if (isState(ALPHA_DIRTY | OBJECT_DIRTY))
+ { ///a rebuild is going to happen, update distance and LoD
return TRUE;
}
@@ -1314,7 +1376,7 @@ BOOL LLSpatialGroup::changeLOD()
return TRUE;
}
- if (mDistance > mRadius)
+ if (mDistance > mRadius*2.f)
{
return FALSE;
}
@@ -1416,7 +1478,6 @@ void LLSpatialGroup::destroyGL()
}
}
- delete [] mOcclusionVerts;
mOcclusionVerts = NULL;
for (LLSpatialGroup::element_iter i = getData().begin(); i != getData().end(); ++i)
@@ -1425,8 +1486,7 @@ void LLSpatialGroup::destroyGL()
for (S32 j = 0; j < drawable->getNumFaces(); j++)
{
LLFace* facep = drawable->getFace(j);
- facep->mVertexBuffer = NULL;
- facep->mLastVertexBuffer = NULL;
+ facep->clearVertexBuffer();
}
}
}
@@ -1459,8 +1519,8 @@ BOOL LLSpatialGroup::rebound()
}
else
{
- LLVector3& newMin = mExtents[0];
- LLVector3& newMax = mExtents[1];
+ LLVector4a& newMin = mExtents[0];
+ LLVector4a& newMax = mExtents[1];
LLSpatialGroup* group = (LLSpatialGroup*) mOctreeNode->getChild(0)->getListener(0);
group->clearState(SKIP_FRUSTUM_CHECK);
group->rebound();
@@ -1474,26 +1534,19 @@ BOOL LLSpatialGroup::rebound()
group = (LLSpatialGroup*) mOctreeNode->getChild(i)->getListener(0);
group->clearState(SKIP_FRUSTUM_CHECK);
group->rebound();
- const LLVector3& max = group->mExtents[1];
- const LLVector3& min = group->mExtents[0];
+ const LLVector4a& max = group->mExtents[1];
+ const LLVector4a& min = group->mExtents[0];
- for (U32 j = 0; j < 3; j++)
- {
- if (max.mV[j] > newMax.mV[j])
- {
- newMax.mV[j] = max.mV[j];
- }
- if (min.mV[j] < newMin.mV[j])
- {
- newMin.mV[j] = min.mV[j];
- }
- }
+ newMax.setMax(newMax, max);
+ newMin.setMin(newMin, min);
}
boundObjects(FALSE, newMin, newMax);
- mBounds[0] = (newMin + newMax)*0.5f;
- mBounds[1] = (newMax - newMin)*0.5f;
+ mBounds[0].setAdd(newMin, newMax);
+ mBounds[0].mul(0.5f);
+ mBounds[1].setSub(newMax, newMin);
+ mBounds[1].mul(0.5f);
}
setState(OCCLUSION_DIRTY);
@@ -1516,31 +1569,53 @@ void LLSpatialGroup::checkOcclusion()
}
else if (isOcclusionState(QUERY_PENDING))
{ //otherwise, if a query is pending, read it back
- GLuint res = 1;
- if (!isOcclusionState(DISCARD_QUERY) && mOcclusionQuery[LLViewerCamera::sCurCameraID])
- {
- glGetQueryObjectuivARB(mOcclusionQuery[LLViewerCamera::sCurCameraID], GL_QUERY_RESULT_ARB, &res);
- }
-
- if (isOcclusionState(DISCARD_QUERY))
- {
- res = 2;
- }
- if (res > 0)
+ GLuint available = 0;
+ if (mOcclusionQuery[LLViewerCamera::sCurCameraID])
{
- assert_states_valid(this);
- clearOcclusionState(LLSpatialGroup::OCCLUDED, LLSpatialGroup::STATE_MODE_DIFF);
- assert_states_valid(this);
+ glGetQueryObjectuivARB(mOcclusionQuery[LLViewerCamera::sCurCameraID], GL_QUERY_RESULT_AVAILABLE_ARB, &available);
}
else
{
- assert_states_valid(this);
- setOcclusionState(LLSpatialGroup::OCCLUDED, LLSpatialGroup::STATE_MODE_DIFF);
- assert_states_valid(this);
+ available = 1;
}
- clearOcclusionState(QUERY_PENDING | DISCARD_QUERY);
+ if (available)
+ { //result is available, read it back, otherwise wait until next frame
+ GLuint res = 1;
+ if (!isOcclusionState(DISCARD_QUERY) && mOcclusionQuery[LLViewerCamera::sCurCameraID])
+ {
+ glGetQueryObjectuivARB(mOcclusionQuery[LLViewerCamera::sCurCameraID], GL_QUERY_RESULT_ARB, &res);
+#if LL_TRACK_PENDING_OCCLUSION_QUERIES
+ sPendingQueries.erase(mOcclusionQuery[LLViewerCamera::sCurCameraID]);
+#endif
+ }
+ else if (mOcclusionQuery[LLViewerCamera::sCurCameraID])
+ { //delete the query to avoid holding onto hundreds of pending queries
+ sQueryPool.release(mOcclusionQuery[LLViewerCamera::sCurCameraID]);
+ mOcclusionQuery[LLViewerCamera::sCurCameraID] = 0;
+ }
+
+ if (isOcclusionState(DISCARD_QUERY))
+ {
+ res = 2;
+ }
+
+ if (res > 0)
+ {
+ assert_states_valid(this);
+ clearOcclusionState(LLSpatialGroup::OCCLUDED, LLSpatialGroup::STATE_MODE_DIFF);
+ assert_states_valid(this);
+ }
+ else
+ {
+ assert_states_valid(this);
+ setOcclusionState(LLSpatialGroup::OCCLUDED, LLSpatialGroup::STATE_MODE_DIFF);
+ assert_states_valid(this);
+ }
+
+ clearOcclusionState(QUERY_PENDING | DISCARD_QUERY);
+ }
}
else if (mSpatialPartition->isOcclusionEnabled() && isOcclusionState(LLSpatialGroup::OCCLUDED))
{ //check occlusion has been issued for occluded node that has not had a query issued
@@ -1551,14 +1626,18 @@ void LLSpatialGroup::checkOcclusion()
}
}
+static LLFastTimer::DeclareTimer FTM_PUSH_OCCLUSION_VERTS("Push Occlusion");
+static LLFastTimer::DeclareTimer FTM_SET_OCCLUSION_STATE("Occlusion State");
+static LLFastTimer::DeclareTimer FTM_OCCLUSION_EARLY_FAIL("Occlusion Early Fail");
+
void LLSpatialGroup::doOcclusion(LLCamera* camera)
{
if (mSpatialPartition->isOcclusionEnabled() && LLPipeline::sUseOcclusion > 1)
{
// Don't cull hole/edge water, unless we have the GL_ARB_depth_clamp extension
- if ((mSpatialPartition->mDrawableType == LLDrawPool::POOL_VOIDWATER && !gGLManager.mHasDepthClamp) ||
- earlyFail(camera, this))
+ if (earlyFail(camera, this))
{
+ LLFastTimer t(FTM_OCCLUSION_EARLY_FAIL);
setOcclusionState(LLSpatialGroup::DISCARD_QUERY);
assert_states_valid(this);
clearOcclusionState(LLSpatialGroup::OCCLUDED, LLSpatialGroup::STATE_MODE_DIFF);
@@ -1566,54 +1645,82 @@ void LLSpatialGroup::doOcclusion(LLCamera* camera)
}
else
{
+ if (!isOcclusionState(QUERY_PENDING) || isOcclusionState(DISCARD_QUERY))
{
- LLFastTimer t(FTM_RENDER_OCCLUSION);
+ { //no query pending, or previous query to be discarded
+ LLFastTimer t(FTM_RENDER_OCCLUSION);
- if (!mOcclusionQuery[LLViewerCamera::sCurCameraID])
- {
- mOcclusionQuery[LLViewerCamera::sCurCameraID] = sQueryPool.allocate();
- }
+ if (!mOcclusionQuery[LLViewerCamera::sCurCameraID])
+ {
+ mOcclusionQuery[LLViewerCamera::sCurCameraID] = sQueryPool.allocate();
+ }
- if (!mOcclusionVerts || isState(LLSpatialGroup::OCCLUSION_DIRTY))
- {
- buildOcclusion();
- }
-
- // Depth clamp all water to avoid it being culled as a result of being
- // behind the far clip plane, and in the case of edge water to avoid
- // it being culled while still visible.
- bool const use_depth_clamp = gGLManager.mHasDepthClamp &&
- (mSpatialPartition->mDrawableType == LLDrawPool::POOL_WATER ||
- mSpatialPartition->mDrawableType == LLDrawPool::POOL_VOIDWATER);
- if (use_depth_clamp)
- {
- glEnable(GL_DEPTH_CLAMP);
- }
-
- glBeginQueryARB(GL_SAMPLES_PASSED_ARB, mOcclusionQuery[LLViewerCamera::sCurCameraID]);
- glVertexPointer(3, GL_FLOAT, 0, mOcclusionVerts);
- if (camera->getOrigin().isExactlyZero())
- { //origin is invalid, draw entire box
- glDrawRangeElements(GL_TRIANGLE_FAN, 0, 7, 8,
- GL_UNSIGNED_BYTE, sOcclusionIndices);
- glDrawRangeElements(GL_TRIANGLE_FAN, 0, 7, 8,
- GL_UNSIGNED_BYTE, sOcclusionIndices+b111*8);
- }
- else
- {
- glDrawRangeElements(GL_TRIANGLE_FAN, 0, 7, 8,
- GL_UNSIGNED_BYTE, get_box_fan_indices(camera, mBounds[0]));
+ if (mOcclusionVerts.isNull() || isState(LLSpatialGroup::OCCLUSION_DIRTY))
+ {
+ buildOcclusion();
+ }
+
+ // Depth clamp all water to avoid it being culled as a result of being
+ // behind the far clip plane, and in the case of edge water to avoid
+ // it being culled while still visible.
+ bool const use_depth_clamp = gGLManager.mHasDepthClamp &&
+ (mSpatialPartition->mDrawableType == LLDrawPool::POOL_WATER ||
+ mSpatialPartition->mDrawableType == LLDrawPool::POOL_VOIDWATER);
+
+ LLGLEnable clamp(use_depth_clamp ? GL_DEPTH_CLAMP : 0);
+
+#if !LL_DARWIN
+ U32 mode = gGLManager.mHasOcclusionQuery2 ? GL_ANY_SAMPLES_PASSED : GL_SAMPLES_PASSED_ARB;
+#else
+ U32 mode = GL_SAMPLES_PASSED_ARB;
+#endif
+
+#if LL_TRACK_PENDING_OCCLUSION_QUERIES
+ sPendingQueries.insert(mOcclusionQuery[LLViewerCamera::sCurCameraID]);
+#endif
+
+ {
+ LLFastTimer t(FTM_PUSH_OCCLUSION_VERTS);
+ glBeginQueryARB(mode, mOcclusionQuery[LLViewerCamera::sCurCameraID]);
+
+ mOcclusionVerts->setBuffer(LLVertexBuffer::MAP_VERTEX);
+
+ if (!use_depth_clamp && mSpatialPartition->mDrawableType == LLDrawPool::POOL_VOIDWATER)
+ {
+ LLGLSquashToFarClip squash(glh_get_current_projection(), 1);
+ if (camera->getOrigin().isExactlyZero())
+ { //origin is invalid, draw entire box
+ mOcclusionVerts->drawRange(LLRender::TRIANGLE_FAN, 0, 7, 8, 0);
+ mOcclusionVerts->drawRange(LLRender::TRIANGLE_FAN, 0, 7, 8, b111*8);
+ }
+ else
+ {
+ mOcclusionVerts->drawRange(LLRender::TRIANGLE_FAN, 0, 7, 8, get_box_fan_indices(camera, mBounds[0]));
+ }
+ }
+ else
+ {
+ if (camera->getOrigin().isExactlyZero())
+ { //origin is invalid, draw entire box
+ mOcclusionVerts->drawRange(LLRender::TRIANGLE_FAN, 0, 7, 8, 0);
+ mOcclusionVerts->drawRange(LLRender::TRIANGLE_FAN, 0, 7, 8, b111*8);
+ }
+ else
+ {
+ mOcclusionVerts->drawRange(LLRender::TRIANGLE_FAN, 0, 7, 8, get_box_fan_indices(camera, mBounds[0]));
+ }
+ }
+
+ glEndQueryARB(mode);
+ }
}
- glEndQueryARB(GL_SAMPLES_PASSED_ARB);
-
- if (use_depth_clamp)
+
{
- glDisable(GL_DEPTH_CLAMP);
+ LLFastTimer t(FTM_SET_OCCLUSION_STATE);
+ setOcclusionState(LLSpatialGroup::QUERY_PENDING);
+ clearOcclusionState(LLSpatialGroup::DISCARD_QUERY);
}
}
-
- setOcclusionState(LLSpatialGroup::QUERY_PENDING);
- clearOcclusionState(LLSpatialGroup::DISCARD_QUERY);
}
}
}
@@ -1637,8 +1744,11 @@ LLSpatialPartition::LLSpatialPartition(U32 data_mask, BOOL render_by_group, U32
LLGLNamePool::registerPool(&sQueryPool);
- mOctree = new LLSpatialGroup::OctreeRoot(LLVector3d(0,0,0),
- LLVector3d(1,1,1),
+ LLVector4a center, size;
+ center.splat(0.f);
+ size.splat(1.f);
+
+ mOctree = new LLSpatialGroup::OctreeRoot(center,size,
NULL);
new LLSpatialGroup(mOctree, this);
}
@@ -1658,7 +1768,6 @@ LLSpatialGroup *LLSpatialPartition::put(LLDrawable *drawablep, BOOL was_visible)
LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION);
drawablep->updateSpatialExtents();
- validate_drawable(drawablep);
//keep drawable from being garbage collected
LLPointer<LLDrawable> ptr = drawablep;
@@ -1742,16 +1851,16 @@ void LLSpatialPartition::move(LLDrawable *drawablep, LLSpatialGroup *curp, BOOL
class LLSpatialShift : public LLSpatialGroup::OctreeTraveler
{
public:
- LLSpatialShift(LLVector3 offset) : mOffset(offset) { }
+ const LLVector4a& mOffset;
+
+ LLSpatialShift(const LLVector4a& offset) : mOffset(offset) { }
virtual void visit(const LLSpatialGroup::OctreeNode* branch)
{
((LLSpatialGroup*) branch->getListener(0))->shift(mOffset);
}
-
- LLVector3 mOffset;
};
-void LLSpatialPartition::shift(const LLVector3 &offset)
+void LLSpatialPartition::shift(const LLVector4a &offset)
{ //shift octree node bounding boxes by offset
LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION);
LLSpatialShift shifter(offset);
@@ -1913,7 +2022,7 @@ public:
class LLOctreeCullVisExtents: public LLOctreeCullShadow
{
public:
- LLOctreeCullVisExtents(LLCamera* camera, LLVector3& min, LLVector3& max)
+ LLOctreeCullVisExtents(LLCamera* camera, LLVector4a& min, LLVector4a& max)
: LLOctreeCullShadow(camera), mMin(min), mMax(max), mEmpty(TRUE) { }
virtual bool earlyFail(LLSpatialGroup* group)
@@ -1980,8 +2089,8 @@ public:
}
BOOL mEmpty;
- LLVector3& mMin;
- LLVector3& mMax;
+ LLVector4a& mMin;
+ LLVector4a& mMax;
};
class LLOctreeCullDetectVisible: public LLOctreeCullShadow
@@ -2050,6 +2159,8 @@ public:
void drawBox(const LLVector3& c, const LLVector3& r)
{
+ LLVertexBuffer::unbind();
+
gGL.begin(LLRender::TRIANGLE_STRIP);
//left front
gGL.vertex3fv((c+r.scaledVec(LLVector3(-1,1,-1))).mV);
@@ -2085,6 +2196,11 @@ void drawBox(const LLVector3& c, const LLVector3& r)
gGL.end();
}
+void drawBox(const LLVector4a& c, const LLVector4a& r)
+{
+ drawBox(reinterpret_cast<const LLVector3&>(c), reinterpret_cast<const LLVector3&>(r));
+}
+
void drawBoxOutline(const LLVector3& pos, const LLVector3& size)
{
LLVector3 v1 = size.scaledVec(LLVector3( 1, 1,1));
@@ -2131,6 +2247,11 @@ void drawBoxOutline(const LLVector3& pos, const LLVector3& size)
gGL.end();
}
+void drawBoxOutline(const LLVector4a& pos, const LLVector4a& size)
+{
+ drawBoxOutline(reinterpret_cast<const LLVector3&>(pos), reinterpret_cast<const LLVector3&>(size));
+}
+
class LLOctreeDirty : public LLOctreeTraveler<LLDrawable>
{
public:
@@ -2174,14 +2295,21 @@ BOOL LLSpatialPartition::isOcclusionEnabled()
BOOL LLSpatialPartition::getVisibleExtents(LLCamera& camera, LLVector3& visMin, LLVector3& visMax)
{
+ LLVector4a visMina, visMaxa;
+ visMina.load3(visMin.mV);
+ visMaxa.load3(visMax.mV);
+
{
LLFastTimer ftm(FTM_CULL_REBOUND);
LLSpatialGroup* group = (LLSpatialGroup*) mOctree->getListener(0);
group->rebound();
}
- LLOctreeCullVisExtents vis(&camera, visMin, visMax);
+ LLOctreeCullVisExtents vis(&camera, visMina, visMaxa);
vis.traverse(mOctree);
+
+ visMin.set(visMina.getF32ptr());
+ visMax.set(visMaxa.getF32ptr());
return vis.mEmpty;
}
@@ -2244,25 +2372,36 @@ BOOL earlyFail(LLCamera* camera, LLSpatialGroup* group)
}
const F32 vel = SG_OCCLUSION_FUDGE*2.f;
- LLVector3 c = group->mBounds[0];
- LLVector3 r = group->mBounds[1] + LLVector3(vel,vel,vel);
-
+ LLVector4a fudge;
+ fudge.splat(vel);
+
+ const LLVector4a& c = group->mBounds[0];
+ LLVector4a r;
+ r.setAdd(group->mBounds[1], fudge);
+
/*if (r.magVecSquared() > 1024.0*1024.0)
{
return TRUE;
}*/
- LLVector3 e = camera->getOrigin();
+ LLVector4a e;
+ e.load3(camera->getOrigin().mV);
- LLVector3 min = c - r;
- LLVector3 max = c + r;
+ LLVector4a min;
+ min.setSub(c,r);
+ LLVector4a max;
+ max.setAdd(c,r);
- for (U32 j = 0; j < 3; j++)
+ S32 lt = e.lessThan(min).getGatheredBits() & 0x7;
+ if (lt)
{
- if (e.mV[j] < min.mV[j] || e.mV[j] > max.mV[j])
- {
- return FALSE;
- }
+ return FALSE;
+ }
+
+ S32 gt = e.greaterThan(max).getGatheredBits() & 0x7;
+ if (gt)
+ {
+ return FALSE;
}
return TRUE;
@@ -2293,7 +2432,9 @@ void pushVerts(LLSpatialGroup* group, U32 mask)
void pushVerts(LLFace* face, U32 mask)
{
- LLVertexBuffer* buffer = face->mVertexBuffer;
+ llassert(face->verify());
+
+ LLVertexBuffer* buffer = face->getVertexBuffer();
if (buffer)
{
@@ -2304,7 +2445,25 @@ void pushVerts(LLFace* face, U32 mask)
U16 offset = face->getIndicesStart();
buffer->drawRange(LLRender::TRIANGLES, start, end, count, offset);
}
+}
+void pushVerts(LLDrawable* drawable, U32 mask)
+{
+ for (S32 i = 0; i < drawable->getNumFaces(); ++i)
+ {
+ pushVerts(drawable->getFace(i), mask);
+ }
+}
+
+void pushVerts(LLVolume* volume)
+{
+ LLVertexBuffer::unbind();
+ for (S32 i = 0; i < volume->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = volume->getVolumeFace(i);
+ glVertexPointer(3, GL_FLOAT, 16, face.mPositions);
+ glDrawElements(GL_TRIANGLES, face.mNumIndices, GL_UNSIGNED_SHORT, face.mIndices);
+ }
}
void pushBufferVerts(LLVertexBuffer* buffer, U32 mask)
@@ -2382,7 +2541,6 @@ void renderOctree(LLSpatialGroup* group)
{
//render solid object bounding box, color
//coded by buffer usage and activity
- LLGLDepthTest depth(GL_TRUE, GL_FALSE);
gGL.setSceneBlendType(LLRender::BT_ADD_WITH_ALPHA);
LLVector4 col;
if (group->mBuilt > 0.f)
@@ -2423,7 +2581,7 @@ void renderOctree(LLSpatialGroup* group)
for (S32 j = 0; j < drawable->getNumFaces(); j++)
{
LLFace* face = drawable->getFace(j);
- if (face->mVertexBuffer.notNull())
+ if (face->getVertexBuffer())
{
if (gFrameTimeSeconds - face->mLastUpdateTime < 0.5f)
{
@@ -2438,10 +2596,10 @@ void renderOctree(LLSpatialGroup* group)
continue;
}
- face->mVertexBuffer->setBuffer(LLVertexBuffer::MAP_VERTEX);
+ face->getVertexBuffer()->setBuffer(LLVertexBuffer::MAP_VERTEX);
//drawBox((face->mExtents[0] + face->mExtents[1])*0.5f,
// (face->mExtents[1]-face->mExtents[0])*0.5f);
- face->mVertexBuffer->draw(LLRender::TRIANGLES, face->getIndicesCount(), face->getIndicesStart());
+ face->getVertexBuffer()->draw(LLRender::TRIANGLES, face->getIndicesCount(), face->getIndicesStart());
}
}
@@ -2468,7 +2626,16 @@ void renderOctree(LLSpatialGroup* group)
}
gGL.color4fv(col.mV);
- drawBox(group->mObjectBounds[0], group->mObjectBounds[1]*1.01f+LLVector3(0.001f, 0.001f, 0.001f));
+ LLVector4a fudge;
+ fudge.splat(0.001f);
+ LLVector4a size = group->mObjectBounds[1];
+ size.mul(1.01f);
+ size.add(fudge);
+
+ {
+ LLGLDepthTest depth(GL_TRUE, GL_FALSE);
+ drawBox(group->mObjectBounds[0], fudge);
+ }
gGL.setSceneBlendType(LLRender::BT_ALPHA);
@@ -2499,8 +2666,12 @@ void renderOctree(LLSpatialGroup* group)
for (LLSpatialGroup::drawmap_elem_t::iterator j = i->second.begin(); j != i->second.end(); ++j)
{
LLDrawInfo* draw_info = *j;
- LLVector3 center = (draw_info->mExtents[1] + draw_info->mExtents[0])*0.5f;
- LLVector3 size = (draw_info->mExtents[1] - draw_info->mExtents[0])*0.5f;
+ LLVector4a center;
+ center.setAdd(draw_info->mExtents[1], draw_info->mExtents[0]);
+ center.mul(0.5f);
+ LLVector4a size;
+ size.setSub(draw_info->mExtents[1], draw_info->mExtents[0]);
+ size.mul(0.5f);
drawBoxOutline(center, size);
}
}
@@ -2547,17 +2718,17 @@ void renderVisibility(LLSpatialGroup* group, LLCamera* camera)
gGL.color4f(0.f, 0.75f, 0.f, 0.5f);
pushBufferVerts(group, LLVertexBuffer::MAP_VERTEX);
}
- else if (camera && group->mOcclusionVerts)
+ else if (camera && group->mOcclusionVerts.notNull())
{
LLVertexBuffer::unbind();
- glVertexPointer(3, GL_FLOAT, 0, group->mOcclusionVerts);
-
+ group->mOcclusionVerts->setBuffer(LLVertexBuffer::MAP_VERTEX);
+
glColor4f(1.0f, 0.f, 0.f, 0.5f);
- glDrawRangeElements(GL_TRIANGLE_FAN, 0, 7, 8, GL_UNSIGNED_BYTE, get_box_fan_indices(camera, group->mBounds[0]));
+ group->mOcclusionVerts->drawRange(LLRender::TRIANGLE_FAN, 0, 7, 8, get_box_fan_indices(camera, group->mBounds[0]));
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glColor4f(1.0f, 1.f, 1.f, 1.0f);
- glDrawRangeElements(GL_TRIANGLE_FAN, 0, 7, 8, GL_UNSIGNED_BYTE, get_box_fan_indices(camera, group->mBounds[0]));
+ group->mOcclusionVerts->drawRange(LLRender::TRIANGLE_FAN, 0, 7, 8, get_box_fan_indices(camera, group->mBounds[0]));
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
}
@@ -2673,8 +2844,8 @@ void renderBoundingBox(LLDrawable* drawable, BOOL set_color = TRUE)
}
}
- const LLVector3* ext;
- LLVector3 pos, size;
+ const LLVector4a* ext;
+ LLVector4a pos, size;
//render face bounding boxes
for (S32 i = 0; i < drawable->getNumFaces(); i++)
@@ -2683,20 +2854,21 @@ void renderBoundingBox(LLDrawable* drawable, BOOL set_color = TRUE)
ext = facep->mExtents;
- if (ext[0].isExactlyZero() && ext[1].isExactlyZero())
- {
- continue;
- }
- pos = (ext[0] + ext[1]) * 0.5f;
- size = (ext[1] - ext[0]) * 0.5f;
+ pos.setAdd(ext[0], ext[1]);
+ pos.mul(0.5f);
+ size.setSub(ext[1], ext[0]);
+ size.mul(0.5f);
+
drawBoxOutline(pos,size);
}
//render drawable bounding box
ext = drawable->getSpatialExtents();
- pos = (ext[0] + ext[1]) * 0.5f;
- size = (ext[1] - ext[0]) * 0.5f;
+ pos.setAdd(ext[0], ext[1]);
+ pos.mul(0.5f);
+ size.setSub(ext[1], ext[0]);
+ size.mul(0.5f);
LLViewerObject* vobj = drawable->getVObj();
if (vobj && vobj->onActiveList())
@@ -2713,7 +2885,513 @@ void renderBoundingBox(LLDrawable* drawable, BOOL set_color = TRUE)
{
drawBoxOutline(pos,size);
}
+}
+
+void renderNormals(LLDrawable* drawablep)
+{
+ LLVertexBuffer::unbind();
+
+ LLVOVolume* vol = drawablep->getVOVolume();
+ if (vol)
+ {
+ LLVolume* volume = vol->getVolume();
+ gGL.pushMatrix();
+ glMultMatrixf((F32*) vol->getRelativeXform().mMatrix);
+
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+
+ LLVector4a scale(gSavedSettings.getF32("RenderDebugNormalScale"));
+
+ for (S32 i = 0; i < volume->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = volume->getVolumeFace(i);
+
+ gGL.begin(LLRender::LINES);
+
+ for (S32 j = 0; j < face.mNumVertices; ++j)
+ {
+ LLVector4a n,p;
+
+ n.setMul(face.mNormals[j], scale);
+ p.setAdd(face.mPositions[j], n);
+
+ gGL.color4f(1,1,1,1);
+ gGL.vertex3fv(face.mPositions[j].getF32ptr());
+ gGL.vertex3fv(p.getF32ptr());
+
+ if (face.mBinormals)
+ {
+ n.setMul(face.mBinormals[j], scale);
+ p.setAdd(face.mPositions[j], n);
+
+ gGL.color4f(0,1,1,1);
+ gGL.vertex3fv(face.mPositions[j].getF32ptr());
+ gGL.vertex3fv(p.getF32ptr());
+ }
+ }
+
+ gGL.end();
+ }
+
+ gGL.popMatrix();
+ }
+}
+
+S32 get_physics_detail(const LLVolumeParams& volume_params, const LLVector3& scale)
+{
+ const S32 DEFAULT_DETAIL = 1;
+ const F32 LARGE_THRESHOLD = 5.f;
+ const F32 MEGA_THRESHOLD = 25.f;
+
+ S32 detail = DEFAULT_DETAIL;
+ F32 avg_scale = (scale[0]+scale[1]+scale[2])/3.f;
+
+ if (avg_scale > LARGE_THRESHOLD)
+ {
+ detail += 1;
+ if (avg_scale > MEGA_THRESHOLD)
+ {
+ detail += 1;
+ }
+ }
+
+ return detail;
+}
+
+void renderMeshBaseHull(LLVOVolume* volume, U32 data_mask, LLColor4& color, LLColor4& line_color)
+{
+ LLUUID mesh_id = volume->getVolume()->getParams().getSculptID();
+ const LLMeshDecomposition* decomp = gMeshRepo.getDecomposition(mesh_id);
+
+ const LLVector3 center(0,0,0);
+ const LLVector3 size(0.25f,0.25f,0.25f);
+
+ if (decomp)
+ {
+ LLVertexBuffer* buff = decomp->mBaseHullMesh;
+
+ if (buff && buff->getNumVerts() > 0)
+ {
+ buff->setBuffer(data_mask);
+
+ /* glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glColor4fv(line_color.mV);
+ buff->drawArrays(LLRender::TRIANGLES, 0, buff->getNumVerts());
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);*/
+
+ {
+ glColor4fv(color.mV);
+ buff->drawArrays(LLRender::TRIANGLES, 0, buff->getNumVerts());
+ }
+ }
+ else
+ {
+ gGL.color3f(0,1,1);
+ drawBoxOutline(center, size);
+ }
+
+ }
+ else
+ {
+ gGL.color3f(1,0,1);
+ drawBoxOutline(center, size);
+ }
+}
+
+void render_hull(LLVertexBuffer* buff, U32 data_mask, const LLColor4& color, const LLColor4& line_color)
+{
+ buff->setBuffer(data_mask);
+
+ glColor4fv(color.mV);
+ buff->drawArrays(LLRender::TRIANGLES, 0, buff->getNumVerts());
+
+ LLGLEnable offset(GL_POLYGON_OFFSET_LINE);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glPolygonOffset(3.f, 3.f);
+ glLineWidth(3.f);
+ glColor4fv(line_color.mV);
+ buff->drawArrays(LLRender::TRIANGLES, 0, buff->getNumVerts());
+ glLineWidth(1.f);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+}
+
+void renderPhysicsShape(LLDrawable* drawable, LLVOVolume* volume)
+{
+ if (volume->isSelected())
+ {
+ LLVector3 construct_me(5,5,5);
+ construct_me.normalize();
+ }
+
+ U8 physics_type = volume->getPhysicsShapeType();
+
+ if (physics_type == LLViewerObject::PHYSICS_SHAPE_NONE || volume->isFlexible())
+ {
+ return;
+ }
+
+ //not allowed to return at this point without rendering *something*
+
+ F32 threshold = gSavedSettings.getF32("ObjectCostHighThreshold");
+ F32 cost = volume->getObjectCost();
+
+ LLColor4 low = gSavedSettings.getColor4("ObjectCostLowColor");
+ LLColor4 mid = gSavedSettings.getColor4("ObjectCostMidColor");
+ LLColor4 high = gSavedSettings.getColor4("ObjectCostHighColor");
+
+ F32 normalizedCost = 1.f - exp( -(cost / threshold) );
+
+ LLColor4 color;
+ if ( normalizedCost <= 0.5f )
+ {
+ color = lerp( low, mid, 2.f * normalizedCost );
+ }
+ else
+ {
+ color = lerp( mid, high, 2.f * ( normalizedCost - 0.5f ) );
+ }
+
+ LLColor4 line_color = color*0.5f;
+
+ U32 data_mask = LLVertexBuffer::MAP_VERTEX;
+
+ LLVolumeParams volume_params = volume->getVolume()->getParams();
+
+ LLPhysicsVolumeParams physics_params(volume_params,
+ physics_type == LLViewerObject::PHYSICS_SHAPE_CONVEX_HULL);
+
+ LLPhysicsShapeBuilderUtil::PhysicsShapeSpecification physics_spec;
+ LLPhysicsShapeBuilderUtil::determinePhysicsShape(physics_params, volume->getScale(), physics_spec);
+
+ U32 type = physics_spec.getType();
+
+ LLVector3 center(0,0,0);
+ LLVector3 size(0.25f,0.25f,0.25f);
+
+ gGL.pushMatrix();
+ glMultMatrixf((F32*) volume->getRelativeXform().mMatrix);
+
+ if (type == LLPhysicsShapeBuilderUtil::PhysicsShapeSpecification::USER_MESH)
+ {
+ LLUUID mesh_id = volume->getVolume()->getParams().getSculptID();
+ const LLMeshDecomposition* decomp = gMeshRepo.getDecomposition(mesh_id);
+
+ if (decomp)
+ { //render a physics based mesh
+
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+
+ if (!decomp->mHull.empty())
+ { //decomposition exists, use that
+ for (U32 i = 0; i < decomp->mHull.size(); ++i)
+ {
+ render_hull(decomp->mMesh[i], data_mask, color, line_color);
+ }
+ }
+ else if (decomp->mPhysicsShapeMesh.notNull() && decomp->mPhysicsShapeMesh->getNumVerts() > 0)
+ {
+ //decomp has physics mesh, render that mesh
+ glColor4fv(color.mV);
+ pushBufferVerts(decomp->mPhysicsShapeMesh, data_mask);
+
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glColor4fv(line_color.mV);
+ pushBufferVerts(decomp->mPhysicsShapeMesh, data_mask);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ }
+ else
+ { //no mesh or decomposition, render base hull
+ renderMeshBaseHull(volume, data_mask, color, line_color);
+
+ if (decomp->mPhysicsShapeMesh.isNull())
+ {
+ //attempt to fetch physics shape mesh if available
+ gMeshRepo.fetchPhysicsShape(mesh_id);
+ }
+ }
+ }
+ else
+ {
+ gGL.color3f(1,1,0);
+ drawBoxOutline(center, size);
+ }
+ }
+ else if (type == LLPhysicsShapeBuilderUtil::PhysicsShapeSpecification::USER_CONVEX ||
+ type == LLPhysicsShapeBuilderUtil::PhysicsShapeSpecification::PRIM_CONVEX)
+ {
+ if (volume->isMesh())
+ {
+ renderMeshBaseHull(volume, data_mask, color, line_color);
+ }
+#if LL_WINDOWS
+ else
+ {
+ LLVolumeParams volume_params = volume->getVolume()->getParams();
+ S32 detail = get_physics_detail(volume_params, volume->getScale());
+ LLVolume* phys_volume = LLPrimitive::sVolumeManager->refVolume(volume_params, detail);
+
+ if (!phys_volume->mHullPoints)
+ { //build convex hull
+ std::vector<LLVector3> pos;
+ std::vector<U16> index;
+
+ S32 index_offset = 0;
+
+ for (S32 i = 0; i < phys_volume->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = phys_volume->getVolumeFace(i);
+ if (index_offset + face.mNumVertices > 65535)
+ {
+ continue;
+ }
+
+ for (S32 j = 0; j < face.mNumVertices; ++j)
+ {
+ pos.push_back(LLVector3(face.mPositions[j].getF32ptr()));
+ }
+
+ for (S32 j = 0; j < face.mNumIndices; ++j)
+ {
+ index.push_back(face.mIndices[j]+index_offset);
+ }
+
+ index_offset += face.mNumVertices;
+ }
+
+ if (!pos.empty() && !index.empty())
+ {
+ LLCDMeshData mesh;
+ mesh.mIndexBase = &index[0];
+ mesh.mVertexBase = pos[0].mV;
+ mesh.mNumVertices = pos.size();
+ mesh.mVertexStrideBytes = 12;
+ mesh.mIndexStrideBytes = 6;
+ mesh.mIndexType = LLCDMeshData::INT_16;
+
+ mesh.mNumTriangles = index.size()/3;
+
+ LLCDMeshData res;
+
+ LLConvexDecomposition::getInstance()->generateSingleHullMeshFromMesh( &mesh, &res );
+
+ //copy res into phys_volume
+ phys_volume->mHullPoints = (LLVector4a*) malloc(sizeof(LLVector4a)*res.mNumVertices);
+ phys_volume->mNumHullPoints = res.mNumVertices;
+
+ S32 idx_size = (res.mNumTriangles*3*2+0xF) & ~0xF;
+ phys_volume->mHullIndices = (U16*) malloc(idx_size);
+ phys_volume->mNumHullIndices = res.mNumTriangles*3;
+
+ const F32* v = res.mVertexBase;
+
+ for (S32 i = 0; i < res.mNumVertices; ++i)
+ {
+ F32* p = (F32*) ((U8*)v+i*res.mVertexStrideBytes);
+ phys_volume->mHullPoints[i].load3(p);
+ }
+
+ if (res.mIndexType == LLCDMeshData::INT_16)
+ {
+ for (S32 i = 0; i < res.mNumTriangles; ++i)
+ {
+ U16* idx = (U16*) (((U8*)res.mIndexBase)+i*res.mIndexStrideBytes);
+
+ phys_volume->mHullIndices[i*3+0] = idx[0];
+ phys_volume->mHullIndices[i*3+1] = idx[1];
+ phys_volume->mHullIndices[i*3+2] = idx[2];
+ }
+ }
+ else
+ {
+ for (S32 i = 0; i < res.mNumTriangles; ++i)
+ {
+ U32* idx = (U32*) (((U8*)res.mIndexBase)+i*res.mIndexStrideBytes);
+
+ phys_volume->mHullIndices[i*3+0] = (U16) idx[0];
+ phys_volume->mHullIndices[i*3+1] = (U16) idx[1];
+ phys_volume->mHullIndices[i*3+2] = (U16) idx[2];
+ }
+ }
+ }
+ }
+
+ if (phys_volume->mHullPoints)
+ {
+ //render hull
+
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+
+ glColor4fv(line_color.mV);
+ LLVertexBuffer::unbind();
+
+ glVertexPointer(3, GL_FLOAT, 16, phys_volume->mHullPoints);
+ glDrawElements(GL_TRIANGLES, phys_volume->mNumHullIndices, GL_UNSIGNED_SHORT, phys_volume->mHullIndices);
+
+ glColor4fv(color.mV);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ glDrawElements(GL_TRIANGLES, phys_volume->mNumHullIndices, GL_UNSIGNED_SHORT, phys_volume->mHullIndices);
+ }
+ else
+ {
+ gGL.color3f(1,0,1);
+ drawBoxOutline(center, size);
+ }
+
+ LLPrimitive::sVolumeManager->unrefVolume(phys_volume);
+ }
+#endif //LL_WINDOWS
+ }
+ else if (type == LLPhysicsShapeBuilderUtil::PhysicsShapeSpecification::BOX)
+ {
+ LLVector3 center = physics_spec.getCenter();
+ LLVector3 scale = physics_spec.getScale();
+ LLVector3 vscale = volume->getScale()*2.f;
+ scale.set(scale[0]/vscale[0], scale[1]/vscale[1], scale[2]/vscale[2]);
+
+ gGL.color4fv(color.mV);
+ drawBox(center, scale);
+ }
+ else if (type == LLPhysicsShapeBuilderUtil::PhysicsShapeSpecification::SPHERE)
+ {
+ LLVolumeParams volume_params;
+ volume_params.setType( LL_PCODE_PROFILE_CIRCLE_HALF, LL_PCODE_PATH_CIRCLE );
+ volume_params.setBeginAndEndS( 0.f, 1.f );
+ volume_params.setBeginAndEndT( 0.f, 1.f );
+ volume_params.setRatio ( 1, 1 );
+ volume_params.setShear ( 0, 0 );
+ LLVolume* sphere = LLPrimitive::sVolumeManager->refVolume(volume_params, 3);
+
+ glColor4fv(color.mV);
+ pushVerts(sphere);
+ LLPrimitive::sVolumeManager->unrefVolume(sphere);
+ }
+ else if (type == LLPhysicsShapeBuilderUtil::PhysicsShapeSpecification::CYLINDER)
+ {
+ LLVolumeParams volume_params;
+ volume_params.setType( LL_PCODE_PROFILE_CIRCLE, LL_PCODE_PATH_LINE );
+ volume_params.setBeginAndEndS( 0.f, 1.f );
+ volume_params.setBeginAndEndT( 0.f, 1.f );
+ volume_params.setRatio ( 1, 1 );
+ volume_params.setShear ( 0, 0 );
+ LLVolume* cylinder = LLPrimitive::sVolumeManager->refVolume(volume_params, 3);
+
+ glColor4fv(color.mV);
+ pushVerts(cylinder);
+ LLPrimitive::sVolumeManager->unrefVolume(cylinder);
+ }
+ else if (type == LLPhysicsShapeBuilderUtil::PhysicsShapeSpecification::PRIM_MESH)
+ {
+ LLVolumeParams volume_params = volume->getVolume()->getParams();
+ S32 detail = get_physics_detail(volume_params, volume->getScale());
+
+ LLVolume* phys_volume = LLPrimitive::sVolumeManager->refVolume(volume_params, detail);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+
+ glColor4fv(line_color.mV);
+ pushVerts(phys_volume);
+
+ glColor4fv(color.mV);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ pushVerts(phys_volume);
+ LLPrimitive::sVolumeManager->unrefVolume(phys_volume);
+ }
+ else if (type == LLPhysicsShapeBuilderUtil::PhysicsShapeSpecification::PRIM_CONVEX)
+ {
+ LLVolumeParams volume_params = volume->getVolume()->getParams();
+ S32 detail = get_physics_detail(volume_params, volume->getScale());
+
+ LLVolume* phys_volume = LLPrimitive::sVolumeManager->refVolume(volume_params, detail);
+
+ if (phys_volume->mHullPoints && phys_volume->mHullIndices)
+ {
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+
+ LLVertexBuffer::unbind();
+ glVertexPointer(3, GL_FLOAT, 16, phys_volume->mHullPoints);
+ glColor4fv(line_color.mV);
+ glDrawElements(GL_TRIANGLES, phys_volume->mNumHullIndices, GL_UNSIGNED_SHORT, phys_volume->mHullIndices);
+
+ glColor4fv(color.mV);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ glDrawElements(GL_TRIANGLES, phys_volume->mNumHullIndices, GL_UNSIGNED_SHORT, phys_volume->mHullIndices);
+ }
+ else
+ {
+ gGL.color3f(1,0,1);
+ drawBoxOutline(center, size);
+ gMeshRepo.buildHull(volume_params, detail);
+ }
+ LLPrimitive::sVolumeManager->unrefVolume(phys_volume);
+ }
+ else if (type == LLPhysicsShapeBuilderUtil::PhysicsShapeSpecification::SCULPT)
+ {
+ //TODO: implement sculpted prim physics display
+ }
+ else
+ {
+ llerrs << "Unhandled type" << llendl;
+ }
+
+ gGL.popMatrix();
+
+ /*{ //analytical shape, just push visual rep.
+ glColor3fv(color.mV);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ pushVerts(drawable, data_mask);
+ glColor4fv(color.mV);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ pushVerts(drawable, data_mask);
+ }*/
+}
+
+void renderPhysicsShapes(LLSpatialGroup* group)
+{
+ for (LLSpatialGroup::OctreeNode::const_element_iter i = group->getData().begin(); i != group->getData().end(); ++i)
+ {
+ LLDrawable* drawable = *i;
+ LLVOVolume* volume = drawable->getVOVolume();
+ if (volume && !volume->isAttachment() && volume->getPhysicsShapeType() != LLViewerObject::PHYSICS_SHAPE_NONE )
+ {
+ if (!group->mSpatialPartition->isBridge())
+ {
+ gGL.pushMatrix();
+ LLVector3 trans = drawable->getRegion()->getOriginAgent();
+ glTranslatef(trans.mV[0], trans.mV[1], trans.mV[2]);
+ renderPhysicsShape(drawable, volume);
+ gGL.popMatrix();
+ }
+ else
+ {
+ renderPhysicsShape(drawable, volume);
+ }
+ }
+ else
+ {
+ LLViewerObject* object = drawable->getVObj();
+ if (object && object->getPCode() == LLViewerObject::LL_VO_SURFACE_PATCH)
+ {
+ //push face vertices for terrain
+ for (S32 i = 0; i < drawable->getNumFaces(); ++i)
+ {
+ LLFace* face = drawable->getFace(i);
+ LLVertexBuffer* buff = face->getVertexBuffer();
+ if (buff)
+ {
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+
+ buff->setBuffer(LLVertexBuffer::MAP_VERTEX);
+ glColor3f(0.2f, 0.5f, 0.3f);
+ buff->draw(LLRender::TRIANGLES, buff->getRequestedIndices(), 0);
+
+ glColor3f(0.2f, 1.f, 0.3f);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ buff->draw(LLRender::TRIANGLES, buff->getRequestedIndices(), 0);
+ }
+ }
+ }
+ }
+ }
}
void renderTexturePriority(LLDrawable* drawable)
@@ -2752,8 +3430,13 @@ void renderTexturePriority(LLDrawable* drawable)
// gGL.color4f(1,0,1,1);
//}
- LLVector3 center = (facep->mExtents[1]+facep->mExtents[0])*0.5f;
- LLVector3 size = (facep->mExtents[1]-facep->mExtents[0])*0.5f + LLVector3(0.01f, 0.01f, 0.01f);
+ LLVector4a center;
+ center.setAdd(facep->mExtents[1],facep->mExtents[0]);
+ center.mul(0.5f);
+ LLVector4a size;
+ size.setSub(facep->mExtents[1],facep->mExtents[0]);
+ size.mul(0.5f);
+ size.add(LLVector4a(0.01f));
drawBox(center, size);
/*S32 boost = imagep->getBoostLevel();
@@ -2777,7 +3460,6 @@ void renderPoints(LLDrawable* drawablep)
{
gGL.begin(LLRender::POINTS);
gGL.color3f(1,1,1);
- LLVector3 center(drawablep->getPositionGroup());
for (S32 i = 0; i < drawablep->getNumFaces(); i++)
{
gGL.vertex3fv(drawablep->getFace(i)->mCenterLocal.mV);
@@ -2809,8 +3491,12 @@ void renderShadowFrusta(LLDrawInfo* params)
LLGLEnable blend(GL_BLEND);
gGL.setSceneBlendType(LLRender::BT_ADD);
- LLVector3 center = (params->mExtents[1]+params->mExtents[0])*0.5f;
- LLVector3 size = (params->mExtents[1]-params->mExtents[0])*0.5f;
+ LLVector4a center;
+ center.setAdd(params->mExtents[1], params->mExtents[0]);
+ center.mul(0.5f);
+ LLVector4a size;
+ size.setSub(params->mExtents[1],params->mExtents[0]);
+ size.mul(0.5f);
if (gPipeline.mShadowCamera[4].AABBInFrustum(center, size))
{
@@ -2854,10 +3540,14 @@ void renderLights(LLDrawable* drawablep)
pushVerts(drawablep->getFace(i), LLVertexBuffer::MAP_VERTEX);
}
- const LLVector3* ext = drawablep->getSpatialExtents();
+ const LLVector4a* ext = drawablep->getSpatialExtents();
- LLVector3 pos = (ext[0] + ext[1]) * 0.5f;
- LLVector3 size = (ext[1] - ext[0]) * 0.5f;
+ LLVector4a pos;
+ pos.setAdd(ext[0], ext[1]);
+ pos.mul(0.5f);
+ LLVector4a size;
+ size.setSub(ext[1], ext[0]);
+ size.mul(0.5f);
{
LLGLDepthTest depth(GL_FALSE, GL_TRUE);
@@ -2867,65 +3557,206 @@ void renderLights(LLDrawable* drawablep)
gGL.color4f(1,1,0,1);
F32 rad = drawablep->getVOVolume()->getLightRadius();
- drawBoxOutline(pos, LLVector3(rad,rad,rad));
+ drawBoxOutline(pos, LLVector4a(rad));
}
}
-
-void renderRaycast(LLDrawable* drawablep)
+class LLRenderOctreeRaycast : public LLOctreeTriangleRayIntersect
{
- if (drawablep->getVObj() != gDebugRaycastObject)
+public:
+
+
+ LLRenderOctreeRaycast(const LLVector4a& start, const LLVector4a& dir, F32* closest_t)
+ : LLOctreeTriangleRayIntersect(start, dir, NULL, closest_t, NULL, NULL, NULL, NULL)
{
- return;
+
}
-
+
+ void visit(const LLOctreeNode<LLVolumeTriangle>* branch)
+ {
+ LLVolumeOctreeListener* vl = (LLVolumeOctreeListener*) branch->getListener(0);
+
+ LLVector3 center, size;
+
+ if (branch->getData().empty())
+ {
+ gGL.color3f(1.f,0.2f,0.f);
+ center.set(branch->getCenter().getF32ptr());
+ size.set(branch->getSize().getF32ptr());
+ }
+ else
+ {
+ gGL.color3f(0.75f, 1.f, 0.f);
+ center.set(vl->mBounds[0].getF32ptr());
+ size.set(vl->mBounds[1].getF32ptr());
+ }
+
+ drawBoxOutline(center, size);
+
+ for (U32 i = 0; i < 2; i++)
+ {
+ LLGLDepthTest depth(GL_TRUE, GL_FALSE, i == 1 ? GL_LEQUAL : GL_GREATER);
+
+ if (i == 1)
+ {
+ gGL.color4f(0,1,1,0.5f);
+ }
+ else
+ {
+ gGL.color4f(0,0.5f,0.5f, 0.25f);
+ drawBoxOutline(center, size);
+ }
+
+ if (i == 1)
+ {
+ gGL.flush();
+ glLineWidth(3.f);
+ }
+
+ gGL.begin(LLRender::TRIANGLES);
+ for (LLOctreeNode<LLVolumeTriangle>::const_element_iter iter = branch->getData().begin();
+ iter != branch->getData().end();
+ ++iter)
+ {
+ const LLVolumeTriangle* tri = *iter;
+
+ gGL.vertex3fv(tri->mV[0]->getF32ptr());
+ gGL.vertex3fv(tri->mV[1]->getF32ptr());
+ gGL.vertex3fv(tri->mV[2]->getF32ptr());
+ }
+ gGL.end();
+
+ if (i == 1)
+ {
+ gGL.flush();
+ glLineWidth(1.f);
+ }
+ }
+ }
+};
+
+void renderRaycast(LLDrawable* drawablep)
+{
if (drawablep->getNumFaces())
{
LLGLEnable blend(GL_BLEND);
gGL.color4f(0,1,1,0.5f);
- if (drawablep->getVOVolume() && gDebugRaycastFaceHit != -1)
+ if (drawablep->getVOVolume())
{
- glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
- pushVerts(drawablep->getFace(gDebugRaycastFaceHit), LLVertexBuffer::MAP_VERTEX);
- glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ //pushVerts(drawablep->getFace(gDebugRaycastFaceHit), LLVertexBuffer::MAP_VERTEX);
+ //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+
+ LLVOVolume* vobj = drawablep->getVOVolume();
+ LLVolume* volume = vobj->getVolume();
+
+ bool transform = true;
+ if (drawablep->isState(LLDrawable::RIGGED))
+ {
+ volume = vobj->getRiggedVolume();
+ transform = false;
+ }
+
+ if (volume)
+ {
+ LLVector3 trans = drawablep->getRegion()->getOriginAgent();
+
+ for (S32 i = 0; i < volume->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& face = volume->getVolumeFace(i);
+ if (!face.mOctree)
+ {
+ ((LLVolumeFace*) &face)->createOctree();
+ }
+
+ gGL.pushMatrix();
+ glTranslatef(trans.mV[0], trans.mV[1], trans.mV[2]);
+ glMultMatrixf((F32*) vobj->getRelativeXform().mMatrix);
+
+ LLVector3 start, end;
+ if (transform)
+ {
+ start = vobj->agentPositionToVolume(gDebugRaycastStart);
+ end = vobj->agentPositionToVolume(gDebugRaycastEnd);
+ }
+ else
+ {
+ start = gDebugRaycastStart;
+ end = gDebugRaycastEnd;
+ }
+
+ LLVector4a starta, enda;
+ starta.load3(start.mV);
+ enda.load3(end.mV);
+ LLVector4a dir;
+ dir.setSub(enda, starta);
+
+ F32 t = 1.f;
+
+ LLRenderOctreeRaycast render(starta, dir, &t);
+ gGL.flush();
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+
+ {
+ //render face positions
+ LLVertexBuffer::unbind();
+ glColor4f(0,1,1,0.5f);
+ glVertexPointer(3, GL_FLOAT, sizeof(LLVector4a), face.mPositions);
+ glDrawElements(GL_TRIANGLES, face.mNumIndices, GL_UNSIGNED_SHORT, face.mIndices);
+ }
+
+ render.traverse(face.mOctree);
+ gGL.popMatrix();
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ }
+ }
}
else if (drawablep->isAvatar())
{
- LLGLDepthTest depth(GL_FALSE);
- LLVOAvatar* av = (LLVOAvatar*) drawablep->getVObj().get();
- av->renderCollisionVolumes();
- }
-
- // draw intersection point
- glPushMatrix();
- glLoadMatrixd(gGLModelView);
- LLVector3 translate = gDebugRaycastIntersection;
- glTranslatef(translate.mV[0], translate.mV[1], translate.mV[2]);
- LLCoordFrame orient;
- orient.lookDir(gDebugRaycastNormal, gDebugRaycastBinormal);
- LLMatrix4 rotation;
- orient.getRotMatrixToParent(rotation);
- glMultMatrixf((float*)rotation.mMatrix);
-
- gGL.color4f(1,0,0,0.5f);
- drawBox(LLVector3(0, 0, 0), LLVector3(0.1f, 0.022f, 0.022f));
- gGL.color4f(0,1,0,0.5f);
- drawBox(LLVector3(0, 0, 0), LLVector3(0.021f, 0.1f, 0.021f));
- gGL.color4f(0,0,1,0.5f);
- drawBox(LLVector3(0, 0, 0), LLVector3(0.02f, 0.02f, 0.1f));
- glPopMatrix();
-
- // draw bounding box of prim
- const LLVector3* ext = drawablep->getSpatialExtents();
-
- LLVector3 pos = (ext[0] + ext[1]) * 0.5f;
- LLVector3 size = (ext[1] - ext[0]) * 0.5f;
+ if (drawablep->getVObj() == gDebugRaycastObject)
+ {
+ LLGLDepthTest depth(GL_FALSE);
+ LLVOAvatar* av = (LLVOAvatar*) drawablep->getVObj().get();
+ av->renderCollisionVolumes();
+ }
+ }
- LLGLDepthTest depth(GL_FALSE, GL_TRUE);
- gGL.color4f(0,0.5f,0.5f,1);
- drawBoxOutline(pos, size);
+ if (drawablep->getVObj() == gDebugRaycastObject)
+ {
+ // draw intersection point
+ glPushMatrix();
+ glLoadMatrixd(gGLModelView);
+ LLVector3 translate = gDebugRaycastIntersection;
+ glTranslatef(translate.mV[0], translate.mV[1], translate.mV[2]);
+ LLCoordFrame orient;
+ orient.lookDir(gDebugRaycastNormal, gDebugRaycastBinormal);
+ LLMatrix4 rotation;
+ orient.getRotMatrixToParent(rotation);
+ glMultMatrixf((float*)rotation.mMatrix);
+
+ gGL.color4f(1,0,0,0.5f);
+ drawBox(LLVector3(0, 0, 0), LLVector3(0.1f, 0.022f, 0.022f));
+ gGL.color4f(0,1,0,0.5f);
+ drawBox(LLVector3(0, 0, 0), LLVector3(0.021f, 0.1f, 0.021f));
+ gGL.color4f(0,0,1,0.5f);
+ drawBox(LLVector3(0, 0, 0), LLVector3(0.02f, 0.02f, 0.1f));
+ glPopMatrix();
+
+ // draw bounding box of prim
+ const LLVector4a* ext = drawablep->getSpatialExtents();
+
+ LLVector4a pos;
+ pos.setAdd(ext[0], ext[1]);
+ pos.mul(0.5f);
+ LLVector4a size;
+ size.setSub(ext[1], ext[0]);
+ size.mul(0.5f);
+ LLGLDepthTest depth(GL_FALSE, GL_TRUE);
+ gGL.color4f(0,0.5f,0.5f,1);
+ drawBoxOutline(pos, size);
+ }
}
}
@@ -2947,7 +3778,6 @@ void renderAgentTarget(LLVOAvatar* avatar)
}
}
-
class LLOctreeRenderNonOccluded : public LLOctreeTraveler<LLDrawable>
{
public:
@@ -3007,8 +3837,8 @@ public:
return;
}
- LLVector3 nodeCenter = group->mBounds[0];
- LLVector3 octCenter = LLVector3(group->mOctreeNode->getCenter());
+ LLVector4a nodeCenter = group->mBounds[0];
+ LLVector4a octCenter = group->mOctreeNode->getCenter();
group->rebuildGeom();
group->rebuildMesh();
@@ -3031,14 +3861,25 @@ public:
{
renderBoundingBox(drawable);
}
+
+ if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_NORMALS))
+ {
+ renderNormals(drawable);
+ }
if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_BUILD_QUEUE))
{
if (drawable->isState(LLDrawable::IN_REBUILD_Q2))
{
gGL.color4f(0.6f, 0.6f, 0.1f, 1.f);
- const LLVector3* ext = drawable->getSpatialExtents();
- drawBoxOutline((ext[0]+ext[1])*0.5f, (ext[1]-ext[0])*0.5f);
+ const LLVector4a* ext = drawable->getSpatialExtents();
+ LLVector4a center;
+ center.setAdd(ext[0], ext[1]);
+ center.mul(0.5f);
+ LLVector4a size;
+ size.setSub(ext[1], ext[0]);
+ size.mul(0.5f);
+ drawBoxOutline(center, size);
}
}
@@ -3103,6 +3944,41 @@ public:
}
};
+
+class LLOctreeRenderPhysicsShapes : public LLOctreeTraveler<LLDrawable>
+{
+public:
+ LLCamera* mCamera;
+ LLOctreeRenderPhysicsShapes(LLCamera* camera): mCamera(camera) {}
+
+ virtual void traverse(const LLSpatialGroup::OctreeNode* node)
+ {
+ LLSpatialGroup* group = (LLSpatialGroup*) node->getListener(0);
+
+ if (!mCamera || mCamera->AABBInFrustumNoFarClip(group->mBounds[0], group->mBounds[1]))
+ {
+ node->accept(this);
+ stop_glerror();
+
+ for (U32 i = 0; i < node->getChildCount(); i++)
+ {
+ traverse(node->getChild(i));
+ stop_glerror();
+ }
+
+ group->rebuildGeom();
+ group->rebuildMesh();
+
+ renderPhysicsShapes(group);
+ }
+ }
+
+ virtual void visit(const LLSpatialGroup::OctreeNode* branch)
+ {
+
+ }
+};
+
class LLOctreePushBBoxVerts : public LLOctreeTraveler<LLDrawable>
{
public:
@@ -3221,6 +4097,25 @@ public:
};
+void LLSpatialPartition::renderPhysicsShapes()
+{
+ LLSpatialBridge* bridge = asBridge();
+ LLCamera* camera = LLViewerCamera::getInstance();
+
+ if (bridge)
+ {
+ camera = NULL;
+ }
+
+ gGL.flush();
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ glLineWidth(3.f);
+ LLOctreeRenderPhysicsShapes render_physics(camera);
+ render_physics.traverse(mOctree);
+ gGL.flush();
+ glLineWidth(1.f);
+}
+
void LLSpatialPartition::renderDebug()
{
if (!gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_OCTREE |
@@ -3229,13 +4124,14 @@ void LLSpatialPartition::renderDebug()
LLPipeline::RENDER_DEBUG_BATCH_SIZE |
LLPipeline::RENDER_DEBUG_UPDATE_TYPE |
LLPipeline::RENDER_DEBUG_BBOXES |
+ LLPipeline::RENDER_DEBUG_NORMALS |
LLPipeline::RENDER_DEBUG_POINTS |
LLPipeline::RENDER_DEBUG_TEXTURE_PRIORITY |
LLPipeline::RENDER_DEBUG_TEXTURE_ANIM |
LLPipeline::RENDER_DEBUG_RAYCAST |
LLPipeline::RENDER_DEBUG_AVATAR_VOLUME |
LLPipeline::RENDER_DEBUG_AGENT_TARGET |
- LLPipeline::RENDER_DEBUG_BUILD_QUEUE |
+ //LLPipeline::RENDER_DEBUG_BUILD_QUEUE |
LLPipeline::RENDER_DEBUG_SHADOW_FRUSTA))
{
return;
@@ -3274,7 +4170,11 @@ void LLSpatialPartition::renderDebug()
void LLSpatialGroup::drawObjectBox(LLColor4 col)
{
gGL.color4fv(col.mV);
- drawBox(mObjectBounds[0], mObjectBounds[1]*1.01f+LLVector3(0.001f, 0.001f, 0.001f));
+ LLVector4a size;
+ size = mObjectBounds[1];
+ size.mul(1.01f);
+ size.add(LLVector4a(0.001f));
+ drawBox(mObjectBounds[0], size);
}
@@ -3334,8 +4234,8 @@ public:
LLSpatialGroup* group = (LLSpatialGroup*) child->getListener(0);
- LLVector3 size;
- LLVector3 center;
+ LLVector4a size;
+ LLVector4a center;
size = group->mBounds[1];
center = group->mBounds[0];
@@ -3352,7 +4252,11 @@ public:
local_end = mEnd * local_matrix;
}
- if (LLLineSegmentBoxIntersect(local_start, local_end, center, size))
+ LLVector4a start, end;
+ start.load3(local_start.mV);
+ end.load3(local_end.mV);
+
+ if (LLLineSegmentBoxIntersect(start, end, center, size))
{
check(child);
}
@@ -3442,18 +4346,9 @@ LLDrawInfo::LLDrawInfo(U16 start, U16 end, U32 count, U32 offset,
mDistance(0.f),
mDrawMode(LLRender::TRIANGLES)
{
+ mVertexBuffer->validateRange(mStart, mEnd, mCount, mOffset);
+
mDebugColor = (rand() << 16) + rand();
- if (mStart >= mVertexBuffer->getRequestedVerts() ||
- mEnd >= mVertexBuffer->getRequestedVerts())
- {
- llerrs << "Invalid draw info vertex range." << llendl;
- }
-
- if (mOffset >= (U32) mVertexBuffer->getRequestedIndices() ||
- mOffset + mCount > (U32) mVertexBuffer->getRequestedIndices())
- {
- llerrs << "Invalid draw info index range." << llendl;
- }
}
LLDrawInfo::~LLDrawInfo()
@@ -3467,6 +4362,16 @@ LLDrawInfo::~LLDrawInfo()
{
mFace->setDrawInfo(NULL);
}
+
+ if (gDebugGL)
+ {
+ gPipeline.checkReferences(this);
+ }
+}
+
+void LLDrawInfo::validate()
+{
+ mVertexBuffer->validateRange(mStart, mEnd, mCount, mOffset);
}
LLVertexBuffer* LLGeometryManager::createVertexBuffer(U32 type_mask, U32 usage)
diff --git a/indra/newview/llspatialpartition.h b/indra/newview/llspatialpartition.h
index 2b9cf6c630..0d9cad914a 100644
--- a/indra/newview/llspatialpartition.h
+++ b/indra/newview/llspatialpartition.h
@@ -39,7 +39,7 @@
#include "lldrawpool.h"
#include "llface.h"
#include "llviewercamera.h"
-
+#include "llvector4a.h"
#include <queue>
#define SG_STATE_INHERIT_MASK (OCCLUDED)
@@ -51,11 +51,16 @@ class LLSpatialGroup;
class LLTextureAtlas;
class LLTextureAtlasSlot;
+S32 AABBSphereIntersect(const LLVector4a& min, const LLVector4a& max, const LLVector3 &origin, const F32 &rad);
+S32 AABBSphereIntersectR2(const LLVector4a& min, const LLVector4a& max, const LLVector3 &origin, const F32 &radius_squared);
+
S32 AABBSphereIntersect(const LLVector3& min, const LLVector3& max, const LLVector3 &origin, const F32 &rad);
S32 AABBSphereIntersectR2(const LLVector3& min, const LLVector3& max, const LLVector3 &origin, const F32 &radius_squared);
+void pushVerts(LLFace* face, U32 mask);
// get index buffer for binary encoded axis vertex buffer given a box at center being viewed by given camera
-U8* get_box_fan_indices(LLCamera* camera, const LLVector3& center);
+U32 get_box_fan_indices(LLCamera* camera, const LLVector4a& center);
+U8* get_box_fan_indices_ptr(LLCamera* camera, const LLVector4a& center);
class LLDrawInfo : public LLRefCount
{
@@ -63,11 +68,27 @@ protected:
~LLDrawInfo();
public:
+
+ LLDrawInfo(const LLDrawInfo& rhs)
+ {
+ *this = rhs;
+ }
+
+ const LLDrawInfo& operator=(const LLDrawInfo& rhs)
+ {
+ llerrs << "Illegal operation!" << llendl;
+ return *this;
+ }
+
LLDrawInfo(U16 start, U16 end, U32 count, U32 offset,
LLViewerTexture* image, LLVertexBuffer* buffer,
BOOL fullbright = FALSE, U8 bump = 0, BOOL particle = FALSE, F32 part_size = 0);
+ void validate();
+
+ LLVector4a mExtents[2];
+
LLPointer<LLVertexBuffer> mVertexBuffer;
LLPointer<LLViewerTexture> mTexture;
LLColor4U mGlowColor;
@@ -86,7 +107,6 @@ public:
LLSpatialGroup* mGroup;
LLFace* mFace; //associated face
F32 mDistance;
- LLVector3 mExtents[2];
U32 mDrawMode;
struct CompareTexture
@@ -128,6 +148,17 @@ public:
};
+ struct CompareMatrixTexturePtr
+ {
+ bool operator()(const LLPointer<LLDrawInfo>& lhs, const LLPointer<LLDrawInfo>& rhs)
+ {
+ return lhs.get() != rhs.get()
+ && (lhs.isNull() || (rhs.notNull() && (lhs->mModelMatrix > rhs->mModelMatrix ||
+ (lhs->mModelMatrix == rhs->mModelMatrix && lhs->mTexture.get() > rhs->mTexture.get()))));
+ }
+
+ };
+
struct CompareBump
{
bool operator()(const LLPointer<LLDrawInfo>& lhs, const LLPointer<LLDrawInfo>& rhs)
@@ -149,11 +180,25 @@ public:
};
};
+LL_ALIGN_PREFIX(64)
class LLSpatialGroup : public LLOctreeListener<LLDrawable>
{
friend class LLSpatialPartition;
friend class LLOctreeStateCheck;
public:
+
+ LLSpatialGroup(const LLSpatialGroup& rhs)
+ {
+ *this = rhs;
+ }
+
+ const LLSpatialGroup& operator=(const LLSpatialGroup& rhs)
+ {
+ llerrs << "Illegal operation!" << llendl;
+ return *this;
+ }
+
+ static std::set<GLuint> sPendingQueries; //pending occlusion queries
static U32 sNodeCount;
static BOOL sNoDelete; //deletion of spatial groups and draw info not allowed if TRUE
@@ -262,8 +307,8 @@ public:
BOOL isVisible() const;
BOOL isRecentlyVisible() const;
void setVisible();
- void shift(const LLVector3 &offset);
- BOOL boundObjects(BOOL empty, LLVector3& newMin, LLVector3& newMax);
+ void shift(const LLVector4a &offset);
+ BOOL boundObjects(BOOL empty, LLVector4a& newMin, LLVector4a& newMax);
void unbound();
BOOL rebound();
void buildOcclusion(); //rebuild mOcclusionVerts
@@ -311,6 +356,27 @@ public:
void addAtlas(LLTextureAtlas* atlasp, S8 recursive_level = 3) ;
void removeAtlas(LLTextureAtlas* atlasp, BOOL remove_group = TRUE, S8 recursive_level = 3) ;
void clearAtlasList() ;
+
+public:
+
+ typedef enum
+ {
+ BOUNDS = 0,
+ EXTENTS = 2,
+ OBJECT_BOUNDS = 4,
+ OBJECT_EXTENTS = 6,
+ VIEW_ANGLE = 8,
+ LAST_VIEW_ANGLE = 9,
+ V4_COUNT = 10
+ } eV4Index;
+
+ LLVector4a mBounds[2]; // bounding box (center, size) of this node and all its children (tight fit to objects)
+ LLVector4a mExtents[2]; // extents (min, max) of this node and all its children
+ LLVector4a mObjectExtents[2]; // extents (min, max) of objects in this node
+ LLVector4a mObjectBounds[2]; // bounding box (center, size) of objects in this node
+ LLVector4a mViewAngle;
+ LLVector4a mLastUpdateViewAngle;
+
private:
U32 mCurUpdatingTime ;
//do not make the below two to use LLPointer
@@ -338,14 +404,9 @@ public:
F32 mBuilt;
OctreeNode* mOctreeNode;
LLSpatialPartition* mSpatialPartition;
- LLVector3 mBounds[2]; // bounding box (center, size) of this node and all its children (tight fit to objects)
- LLVector3 mExtents[2]; // extents (min, max) of this node and all its children
- LLVector3 mObjectExtents[2]; // extents (min, max) of objects in this node
- LLVector3 mObjectBounds[2]; // bounding box (center, size) of objects in this node
-
LLPointer<LLVertexBuffer> mVertexBuffer;
- F32* mOcclusionVerts;
+ LLPointer<LLVertexBuffer> mOcclusionVerts;
GLuint mOcclusionQuery[LLViewerCamera::NUM_CAMERAS];
U32 mBufferUsage;
@@ -356,13 +417,10 @@ public:
F32 mDepth;
F32 mLastUpdateDistance;
F32 mLastUpdateTime;
-
- LLVector3 mViewAngle;
- LLVector3 mLastUpdateViewAngle;
F32 mPixelArea;
F32 mRadius;
-};
+} LL_ALIGN_POSTFIX(64);
class LLGeometryManager
{
@@ -398,7 +456,7 @@ public:
// If the drawable moves, move it here.
virtual void move(LLDrawable *drawablep, LLSpatialGroup *curp, BOOL immediate = FALSE);
- virtual void shift(const LLVector3 &offset);
+ virtual void shift(const LLVector4a &offset);
virtual F32 calcDistance(LLSpatialGroup* group, LLCamera& camera);
virtual F32 calcPixelArea(LLSpatialGroup* group, LLCamera& camera);
@@ -414,6 +472,7 @@ public:
virtual LLSpatialBridge* asBridge() { return NULL; }
virtual BOOL isBridge() { return asBridge() != NULL; }
+ void renderPhysicsShapes();
void renderDebug();
void renderIntersectingBBoxes(LLCamera* camera);
void restoreGL();
@@ -456,7 +515,7 @@ public:
virtual void makeActive();
virtual void move(LLDrawable *drawablep, LLSpatialGroup *curp, BOOL immediate = FALSE);
virtual BOOL updateMove();
- virtual void shiftPos(const LLVector3& vec);
+ virtual void shiftPos(const LLVector4a& vec);
virtual void cleanupReferences();
virtual LLSpatialPartition* asPartition() { return this; }
virtual LLSpatialBridge* asBridge() { return this; }
@@ -484,6 +543,7 @@ public:
sg_list_t::iterator beginAlphaGroups();
sg_list_t::iterator endAlphaGroups();
+ bool hasOcclusionGroups() { return mOcclusionGroupsSize > 0; }
sg_list_t::iterator beginOcclusionGroups();
sg_list_t::iterator endOcclusionGroups();
@@ -613,6 +673,13 @@ public:
class LLVolumeGeometryManager: public LLGeometryManager
{
public:
+ typedef enum
+ {
+ NONE = 0,
+ BATCH_SORT,
+ DISTANCE_SORT
+ } eSortType;
+
virtual ~LLVolumeGeometryManager() { }
virtual void rebuildGeom(LLSpatialGroup* group);
virtual void rebuildMesh(LLSpatialGroup* group);
@@ -647,7 +714,7 @@ class LLHUDBridge : public LLVolumeBridge
{
public:
LLHUDBridge(LLDrawable* drawablep);
- virtual void shiftPos(const LLVector3& vec);
+ virtual void shiftPos(const LLVector4a& vec);
virtual F32 calcPixelArea(LLSpatialGroup* group, LLCamera& camera);
};
@@ -664,11 +731,9 @@ class LLHUDPartition : public LLBridgePartition
{
public:
LLHUDPartition();
- virtual void shift(const LLVector3 &offset);
+ virtual void shift(const LLVector4a &offset);
};
-void validate_draw_info(LLDrawInfo& params);
-
extern const F32 SG_BOX_SIDE;
extern const F32 SG_BOX_OFFSET;
extern const F32 SG_BOX_RAD;
diff --git a/indra/newview/llsprite.cpp b/indra/newview/llsprite.cpp
index a69592b61c..4bde2dfcab 100644
--- a/indra/newview/llsprite.cpp
+++ b/indra/newview/llsprite.cpp
@@ -186,14 +186,15 @@ void LLSprite::updateFace(LLFace &face)
U16 index_offset;
// Setup face
- if (face.mVertexBuffer.isNull())
+ if (!face.getVertexBuffer())
{
- face.mVertexBuffer = new LLVertexBuffer(LLVertexBuffer::MAP_VERTEX |
+ LLVertexBuffer* buff = new LLVertexBuffer(LLVertexBuffer::MAP_VERTEX |
LLVertexBuffer::MAP_TEXCOORD0,
GL_STREAM_DRAW_ARB);
- face.mVertexBuffer->allocateBuffer(4, 12, TRUE);
+ buff->allocateBuffer(4, 12, TRUE);
face.setGeomIndex(0);
face.setIndicesIndex(0);
+ face.setVertexBuffer(buff);
}
index_offset = face.getGeometry(verticesp,normalsp,tex_coordsp, indicesp);
@@ -242,7 +243,7 @@ void LLSprite::updateFace(LLFace &face)
*indicesp++ = 3 + index_offset;
}
- face.mVertexBuffer->setBuffer(0);
+ face.getVertexBuffer()->setBuffer(0);
face.mCenterAgent = mPosition;
}
diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp
index 45159de66e..86087ba0a1 100644..100755
--- a/indra/newview/llstartup.cpp
+++ b/indra/newview/llstartup.cpp
@@ -1,3229 +1,3234 @@
-/**
- * @file llstartup.cpp
- * @brief startup routines.
- *
- * $LicenseInfo:firstyear=2004&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-#include "llviewerprecompiledheaders.h"
-
-#include "llstartup.h"
-
-#if LL_WINDOWS
-# include <process.h> // _spawnl()
-#else
-# include <sys/stat.h> // mkdir()
-#endif
-
-#include "llviewermedia_streamingaudio.h"
-#include "llaudioengine.h"
-
-#ifdef LL_FMOD
-# include "llaudioengine_fmod.h"
-#endif
-
-#ifdef LL_OPENAL
-#include "llaudioengine_openal.h"
-#endif
-
-#include "llares.h"
-#include "llavatarnamecache.h"
-#include "lllandmark.h"
-#include "llcachename.h"
-#include "lldir.h"
-#include "llerrorcontrol.h"
-#include "llfloaterreg.h"
-#include "llfocusmgr.h"
-#include "llhttpsender.h"
-#include "llimfloater.h"
-#include "lllocationhistory.h"
-#include "llimageworker.h"
-
-#include "llloginflags.h"
-#include "llmd5.h"
-#include "llmemorystream.h"
-#include "llmessageconfig.h"
-#include "llmoveview.h"
-#include "llnearbychat.h"
-#include "llnotifications.h"
-#include "llnotificationsutil.h"
-#include "llteleporthistory.h"
-#include "llregionhandle.h"
-#include "llsd.h"
-#include "llsdserialize.h"
-#include "llsdutil_math.h"
-#include "llsecondlifeurls.h"
-#include "llstring.h"
-#include "lluserrelations.h"
-#include "llversioninfo.h"
-#include "llviewercontrol.h"
-#include "llvfs.h"
-#include "llxorcipher.h" // saved password, MAC address
-#include "llwindow.h"
-#include "imageids.h"
-#include "message.h"
-#include "v3math.h"
-
-#include "llagent.h"
-#include "llagentcamera.h"
-#include "llagentpicksinfo.h"
-#include "llagentwearables.h"
-#include "llagentpilot.h"
-#include "llfloateravatarpicker.h"
-#include "llcallbacklist.h"
-#include "llcallingcard.h"
-#include "llconsole.h"
-#include "llcontainerview.h"
-#include "lldebugview.h"
-#include "lldrawable.h"
-#include "lleventnotifier.h"
-#include "llface.h"
-#include "llfeaturemanager.h"
-//#include "llfirstuse.h"
-#include "llfloaterhud.h"
-#include "llfloaterland.h"
-#include "llfloaterpreference.h"
-#include "llfloatertopobjects.h"
-#include "llfloaterworldmap.h"
-#include "llgesturemgr.h"
-#include "llgroupmgr.h"
-#include "llhudeffecttrail.h"
-#include "llhudmanager.h"
-#include "llhttpclient.h"
-#include "llimagebmp.h"
-#include "llinventorybridge.h"
-#include "llinventorymodel.h"
-#include "llinventorymodelbackgroundfetch.h"
-#include "llkeyboard.h"
-#include "llloginhandler.h" // gLoginHandler, SLURL support
-#include "lllogininstance.h" // Host the login module.
-#include "llpanellogin.h"
-#include "llmutelist.h"
-#include "llavatarpropertiesprocessor.h"
-#include "llpanelclassified.h"
-#include "llpanelpick.h"
-#include "llpanelgrouplandmoney.h"
-#include "llpanelgroupnotices.h"
-#include "llpreview.h"
-#include "llpreviewscript.h"
-#include "llproductinforequest.h"
-#include "llsecondlifeurls.h"
-#include "llselectmgr.h"
-#include "llsky.h"
-#include "llsidetray.h"
-#include "llstatview.h"
-#include "llstatusbar.h" // sendMoneyBalanceRequest(), owns L$ balance
-#include "llsurface.h"
-#include "lltexturecache.h"
-#include "lltexturefetch.h"
-#include "lltoolmgr.h"
-#include "lltrans.h"
-#include "llui.h"
-#include "llurldispatcher.h"
-#include "llurlentry.h"
-#include "llslurl.h"
-#include "llurlhistory.h"
-#include "llurlwhitelist.h"
-#include "llvieweraudio.h"
-#include "llviewerassetstorage.h"
-#include "llviewercamera.h"
-#include "llviewerdisplay.h"
-#include "llviewergenericmessage.h"
-#include "llviewergesture.h"
-#include "llviewertexturelist.h"
-#include "llviewermedia.h"
-#include "llviewermenu.h"
-#include "llviewermessage.h"
-#include "llviewernetwork.h"
-#include "llviewerobjectlist.h"
-#include "llviewerparcelmedia.h"
-#include "llviewerparcelmgr.h"
-#include "llviewerregion.h"
-#include "llviewerstats.h"
-#include "llviewerthrottle.h"
-#include "llviewerwindow.h"
-#include "llvoavatar.h"
-#include "llvoavatarself.h"
-#include "llvoclouds.h"
-#include "llweb.h"
-#include "llworld.h"
-#include "llworldmapmessage.h"
-#include "llxfermanager.h"
-#include "pipeline.h"
-#include "llappviewer.h"
-#include "llfasttimerview.h"
-#include "llfloatermap.h"
-#include "llweb.h"
-#include "llvoiceclient.h"
-#include "llnamelistctrl.h"
-#include "llnamebox.h"
-#include "llnameeditor.h"
-#include "llpostprocess.h"
-#include "llwlparammanager.h"
-#include "llwaterparammanager.h"
-#include "llagentlanguage.h"
-#include "llwearable.h"
-#include "llinventorybridge.h"
-#include "llappearancemgr.h"
-#include "llavatariconctrl.h"
-#include "llvoicechannel.h"
-
-#include "lllogin.h"
-#include "llevents.h"
-#include "llstartuplistener.h"
-
-#if LL_WINDOWS
-#include "lldxhardware.h"
-#endif
-
-//
-// exported globals
-//
-bool gAgentMovementCompleted = false;
-S32 gMaxAgentGroups;
-
-std::string SCREEN_HOME_FILENAME = "screen_home.bmp";
-std::string SCREEN_LAST_FILENAME = "screen_last.bmp";
-
-LLPointer<LLViewerTexture> gStartTexture;
-
-//
-// Imported globals
-//
-extern S32 gStartImageWidth;
-extern S32 gStartImageHeight;
-
-//
-// local globals
-//
-static bool gGotUseCircuitCodeAck = false;
-static std::string sInitialOutfit;
-static std::string sInitialOutfitGender; // "male" or "female"
-static boost::signals2::connection sWearablesLoadedCon;
-
-static bool gUseCircuitCallbackCalled = false;
-
-EStartupState LLStartUp::gStartupState = STATE_FIRST;
-LLSLURL LLStartUp::sStartSLURL;
-
-static LLPointer<LLCredential> gUserCredential;
-static std::string gDisplayName;
-static BOOL gRememberPassword = TRUE;
-
-static U64 gFirstSimHandle = 0;
-static LLHost gFirstSim;
-static std::string gFirstSimSeedCap;
-static LLVector3 gAgentStartLookAt(1.0f, 0.f, 0.f);
-static std::string gAgentStartLocation = "safe";
-static bool mLoginStatePastUI = false;
-
-
-boost::scoped_ptr<LLEventPump> LLStartUp::sStateWatcher(new LLEventStream("StartupState"));
-boost::scoped_ptr<LLStartupListener> LLStartUp::sListener(new LLStartupListener());
-
-//
-// local function declaration
-//
-
-void login_show();
-void login_callback(S32 option, void* userdata);
-void show_first_run_dialog();
-bool first_run_dialog_callback(const LLSD& notification, const LLSD& response);
-void set_startup_status(const F32 frac, const std::string& string, const std::string& msg);
-bool login_alert_status(const LLSD& notification, const LLSD& response);
-void login_packet_failed(void**, S32 result);
-void use_circuit_callback(void**, S32 result);
-void register_viewer_callbacks(LLMessageSystem* msg);
-void asset_callback_nothing(LLVFS*, const LLUUID&, LLAssetType::EType, void*, S32);
-bool callback_choose_gender(const LLSD& notification, const LLSD& response);
-void init_start_screen(S32 location_id);
-void release_start_screen();
-void reset_login();
-LLSD transform_cert_args(LLPointer<LLCertificate> cert);
-void general_cert_done(const LLSD& notification, const LLSD& response);
-void trust_cert_done(const LLSD& notification, const LLSD& response);
-void apply_udp_blacklist(const std::string& csv);
-bool process_login_success_response();
-void transition_back_to_login_panel(const std::string& emsg);
-
-void callback_cache_name(const LLUUID& id, const std::string& full_name, bool is_group)
-{
- LLNameBox::refreshAll(id, full_name, is_group);
- LLNameEditor::refreshAll(id, full_name, is_group);
-
- // TODO: Actually be intelligent about the refresh.
- // For now, just brute force refresh the dialogs.
- dialog_refresh_all();
-}
-
-//
-// exported functionality
-//
-
-//
-// local classes
-//
-
-namespace
-{
- class LLNullHTTPSender : public LLHTTPSender
- {
- virtual void send(const LLHost& host,
- const std::string& message, const LLSD& body,
- LLHTTPClient::ResponderPtr response) const
- {
- LL_WARNS("AppInit") << " attemped to send " << message << " to " << host
- << " with null sender" << LL_ENDL;
- }
- };
-}
-
-void update_texture_fetch()
-{
- LLAppViewer::getTextureCache()->update(1); // unpauses the texture cache thread
- LLAppViewer::getImageDecodeThread()->update(1); // unpauses the image thread
- LLAppViewer::getTextureFetch()->update(1); // unpauses the texture fetch thread
- gTextureList.updateImages(0.10f);
-}
-
-// Returns false to skip other idle processing. Should only return
-// true when all initialization done.
-bool idle_startup()
-{
- LLMemType mt1(LLMemType::MTYPE_STARTUP);
-
- const F32 PRECACHING_DELAY = gSavedSettings.getF32("PrecachingDelay");
- static LLTimer timeout;
- static S32 timeout_count = 0;
-
- static LLTimer login_time;
-
- // until this is encapsulated, this little hack for the
- // auth/transform loop will do.
- static F32 progress = 0.10f;
-
- static std::string auth_desc;
- static std::string auth_message;
-
- static LLVector3 initial_sun_direction(1.f, 0.f, 0.f);
- static LLVector3 agent_start_position_region(10.f, 10.f, 10.f); // default for when no space server
-
- // last location by default
- static S32 agent_location_id = START_LOCATION_ID_LAST;
- static S32 location_which = START_LOCATION_ID_LAST;
-
- static bool show_connect_box = true;
-
- //static bool stipend_since_login = false;
-
- // HACK: These are things from the main loop that usually aren't done
- // until initialization is complete, but need to be done here for things
- // to work.
- gIdleCallbacks.callFunctions();
- gViewerWindow->updateUI();
- LLMortician::updateClass();
-
- const std::string delims (" ");
- std::string system;
- int begIdx, endIdx;
- std::string osString = LLAppViewer::instance()->getOSInfo().getOSStringSimple();
-
- begIdx = osString.find_first_not_of (delims);
- endIdx = osString.find_first_of (delims, begIdx);
- system = osString.substr (begIdx, endIdx - begIdx);
- system += "Locale";
-
- LLStringUtil::setLocale (LLTrans::getString(system));
-
- if (!gNoRender)
- {
- //note: Removing this line will cause incorrect button size in the login screen. -- bao.
- gTextureList.updateImages(0.01f) ;
- }
-
- if ( STATE_FIRST == LLStartUp::getStartupState() )
- {
- gViewerWindow->showCursor();
- gViewerWindow->getWindow()->setCursor(UI_CURSOR_WAIT);
-
- /////////////////////////////////////////////////
- //
- // Initialize stuff that doesn't need data from simulators
- //
-
- if (LLFeatureManager::getInstance()->isSafe())
- {
- LLNotificationsUtil::add("DisplaySetToSafe");
- }
- else if ((gSavedSettings.getS32("LastFeatureVersion") < LLFeatureManager::getInstance()->getVersion()) &&
- (gSavedSettings.getS32("LastFeatureVersion") != 0))
- {
- LLNotificationsUtil::add("DisplaySetToRecommended");
- }
- else if ((gSavedSettings.getS32("LastGPUClass") != LLFeatureManager::getInstance()->getGPUClass()) &&
- (gSavedSettings.getS32("LastGPUClass") != -1))
- {
- LLNotificationsUtil::add("DisplaySetToRecommended");
- }
- else if (!gViewerWindow->getInitAlert().empty())
- {
- LLNotificationsUtil::add(gViewerWindow->getInitAlert());
- }
-
- gSavedSettings.setS32("LastFeatureVersion", LLFeatureManager::getInstance()->getVersion());
- gSavedSettings.setS32("LastGPUClass", LLFeatureManager::getInstance()->getGPUClass());
-
- // load dynamic GPU/feature tables from website (S3)
- LLFeatureManager::getInstance()->fetchHTTPTables();
-
- std::string xml_file = LLUI::locateSkin("xui_version.xml");
- LLXMLNodePtr root;
- bool xml_ok = false;
- if (LLXMLNode::parseFile(xml_file, root, NULL))
- {
- if( (root->hasName("xui_version") ) )
- {
- std::string value = root->getValue();
- F32 version = 0.0f;
- LLStringUtil::convertToF32(value, version);
- if (version >= 1.0f)
- {
- xml_ok = true;
- }
- }
- }
- if (!xml_ok)
- {
- // If XML is bad, there's a good possibility that notifications.xml is ALSO bad.
- // If that's so, then we'll get a fatal error on attempting to load it,
- // which will display a nontranslatable error message that says so.
- // Otherwise, we'll display a reasonable error message that IS translatable.
- LLAppViewer::instance()->earlyExit("BadInstallation");
- }
- //
- // Statistics stuff
- //
-
- // Load autopilot and stats stuff
- gAgentPilot.load(gSavedSettings.getString("StatsPilotFile"));
-
- //gErrorStream.setTime(gSavedSettings.getBOOL("LogTimestamps"));
-
- // Load the throttle settings
- gViewerThrottle.load();
-
- if (ll_init_ares() == NULL || !gAres->isInitialized())
- {
- std::string diagnostic = "Could not start address resolution system";
- LL_WARNS("AppInit") << diagnostic << LL_ENDL;
- LLAppViewer::instance()->earlyExit("LoginFailedNoNetwork", LLSD().with("DIAGNOSTIC", diagnostic));
- }
-
- //
- // Initialize messaging system
- //
- LL_DEBUGS("AppInit") << "Initializing messaging system..." << LL_ENDL;
-
- std::string message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"message_template.msg");
-
- LLFILE* found_template = NULL;
- found_template = LLFile::fopen(message_template_path, "r"); /* Flawfinder: ignore */
-
- #if LL_WINDOWS
- // On the windows dev builds, unpackaged, the message_template.msg
- // file will be located in:
- // build-vc**/newview/<config>/app_settings
- if (!found_template)
- {
- message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_EXECUTABLE, "app_settings", "message_template.msg");
- found_template = LLFile::fopen(message_template_path.c_str(), "r"); /* Flawfinder: ignore */
- }
- #elif LL_DARWIN
- // On Mac dev builds, message_template.msg lives in:
- // indra/build-*/newview/<config>/Second Life/Contents/Resources/app_settings
- if (!found_template)
- {
- message_template_path =
- gDirUtilp->getExpandedFilename(LL_PATH_EXECUTABLE,
- "../Resources/app_settings",
- "message_template.msg");
- found_template = LLFile::fopen(message_template_path.c_str(), "r"); /* Flawfinder: ignore */
- }
- #endif
-
- if (found_template)
- {
- fclose(found_template);
-
- U32 port = gSavedSettings.getU32("UserConnectionPort");
-
- if ((NET_USE_OS_ASSIGNED_PORT == port) && // if nothing specified on command line (-port)
- (gSavedSettings.getBOOL("ConnectionPortEnabled")))
- {
- port = gSavedSettings.getU32("ConnectionPort");
- }
-
- LLHTTPSender::setDefaultSender(new LLNullHTTPSender());
-
- // TODO parameterize
- const F32 circuit_heartbeat_interval = 5;
- const F32 circuit_timeout = 100;
-
- const LLUseCircuitCodeResponder* responder = NULL;
- bool failure_is_fatal = true;
-
- if(!start_messaging_system(
- message_template_path,
- port,
- LLVersionInfo::getMajor(),
- LLVersionInfo::getMinor(),
- LLVersionInfo::getPatch(),
- FALSE,
- std::string(),
- responder,
- failure_is_fatal,
- circuit_heartbeat_interval,
- circuit_timeout))
- {
- std::string diagnostic = llformat(" Error: %d", gMessageSystem->getErrorCode());
- LL_WARNS("AppInit") << diagnostic << LL_ENDL;
- LLAppViewer::instance()->earlyExit("LoginFailedNoNetwork", LLSD().with("DIAGNOSTIC", diagnostic));
- }
-
- #if LL_WINDOWS
- // On the windows dev builds, unpackaged, the message.xml file will
- // be located in indra/build-vc**/newview/<config>/app_settings.
- std::string message_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"message.xml");
-
- if (!LLFile::isfile(message_path.c_str()))
- {
- LLMessageConfig::initClass("viewer", gDirUtilp->getExpandedFilename(LL_PATH_EXECUTABLE, "app_settings", ""));
- }
- else
- {
- LLMessageConfig::initClass("viewer", gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
- }
- #else
- LLMessageConfig::initClass("viewer", gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
- #endif
-
- }
- else
- {
- LLAppViewer::instance()->earlyExit("MessageTemplateNotFound", LLSD().with("PATH", message_template_path));
- }
-
- if(gMessageSystem && gMessageSystem->isOK())
- {
- // Initialize all of the callbacks in case of bad message
- // system data
- LLMessageSystem* msg = gMessageSystem;
- msg->setExceptionFunc(MX_UNREGISTERED_MESSAGE,
- invalid_message_callback,
- NULL);
- msg->setExceptionFunc(MX_PACKET_TOO_SHORT,
- invalid_message_callback,
- NULL);
-
- // running off end of a packet is now valid in the case
- // when a reader has a newer message template than
- // the sender
- /*msg->setExceptionFunc(MX_RAN_OFF_END_OF_PACKET,
- invalid_message_callback,
- NULL);*/
- msg->setExceptionFunc(MX_WROTE_PAST_BUFFER_SIZE,
- invalid_message_callback,
- NULL);
-
- if (gSavedSettings.getBOOL("LogMessages"))
- {
- LL_DEBUGS("AppInit") << "Message logging activated!" << LL_ENDL;
- msg->startLogging();
- }
-
- // start the xfer system. by default, choke the downloads
- // a lot...
- const S32 VIEWER_MAX_XFER = 3;
- start_xfer_manager(gVFS);
- gXferManager->setMaxIncomingXfers(VIEWER_MAX_XFER);
- F32 xfer_throttle_bps = gSavedSettings.getF32("XferThrottle");
- if (xfer_throttle_bps > 1.f)
- {
- gXferManager->setUseAckThrottling(TRUE);
- gXferManager->setAckThrottleBPS(xfer_throttle_bps);
- }
- gAssetStorage = new LLViewerAssetStorage(msg, gXferManager, gVFS, gStaticVFS);
-
-
- F32 dropPercent = gSavedSettings.getF32("PacketDropPercentage");
- msg->mPacketRing.setDropPercentage(dropPercent);
-
- F32 inBandwidth = gSavedSettings.getF32("InBandwidth");
- F32 outBandwidth = gSavedSettings.getF32("OutBandwidth");
- if (inBandwidth != 0.f)
- {
- LL_DEBUGS("AppInit") << "Setting packetring incoming bandwidth to " << inBandwidth << LL_ENDL;
- msg->mPacketRing.setUseInThrottle(TRUE);
- msg->mPacketRing.setInBandwidth(inBandwidth);
- }
- if (outBandwidth != 0.f)
- {
- LL_DEBUGS("AppInit") << "Setting packetring outgoing bandwidth to " << outBandwidth << LL_ENDL;
- msg->mPacketRing.setUseOutThrottle(TRUE);
- msg->mPacketRing.setOutBandwidth(outBandwidth);
- }
- }
-
- LL_INFOS("AppInit") << "Message System Initialized." << LL_ENDL;
-
- //-------------------------------------------------
- // Init audio, which may be needed for prefs dialog
- // or audio cues in connection UI.
- //-------------------------------------------------
-
- if (FALSE == gSavedSettings.getBOOL("NoAudio"))
- {
- gAudiop = NULL;
-
-#ifdef LL_OPENAL
- if (!gAudiop
-#if !LL_WINDOWS
- && NULL == getenv("LL_BAD_OPENAL_DRIVER")
-#endif // !LL_WINDOWS
- )
- {
- gAudiop = (LLAudioEngine *) new LLAudioEngine_OpenAL();
- }
-#endif
-
-#ifdef LL_FMOD
- if (!gAudiop
-#if !LL_WINDOWS
- && NULL == getenv("LL_BAD_FMOD_DRIVER")
-#endif // !LL_WINDOWS
- )
- {
- gAudiop = (LLAudioEngine *) new LLAudioEngine_FMOD();
- }
-#endif
-
- if (gAudiop)
- {
-#if LL_WINDOWS
- // FMOD on Windows needs the window handle to stop playing audio
- // when window is minimized. JC
- void* window_handle = (HWND)gViewerWindow->getPlatformWindow();
-#else
- void* window_handle = NULL;
-#endif
- bool init = gAudiop->init(kAUDIO_NUM_SOURCES, window_handle);
- if(init)
- {
- gAudiop->setMuted(TRUE);
- }
- else
- {
- LL_WARNS("AppInit") << "Unable to initialize audio engine" << LL_ENDL;
- delete gAudiop;
- gAudiop = NULL;
- }
-
- if (gAudiop)
- {
- // if the audio engine hasn't set up its own preferred handler for streaming audio then set up the generic streaming audio implementation which uses media plugins
- if (NULL == gAudiop->getStreamingAudioImpl())
- {
- LL_INFOS("AppInit") << "Using media plugins to render streaming audio" << LL_ENDL;
- gAudiop->setStreamingAudioImpl(new LLStreamingAudio_MediaPlugins());
- }
- }
- }
- }
-
- LL_INFOS("AppInit") << "Audio Engine Initialized." << LL_ENDL;
-
- if (LLTimer::knownBadTimer())
- {
- LL_WARNS("AppInit") << "Unreliable timers detected (may be bad PCI chipset)!!" << LL_ENDL;
- }
-
- //
- // Log on to system
- //
- if (gUserCredential.isNull())
- {
- gUserCredential = gLoginHandler.initializeLoginInfo();
- }
- if (gUserCredential.isNull())
- {
- show_connect_box = TRUE;
- }
- else if (gSavedSettings.getBOOL("AutoLogin"))
- {
- gRememberPassword = TRUE;
- gSavedSettings.setBOOL("RememberPassword", TRUE);
- show_connect_box = false;
- }
- else
- {
- gRememberPassword = gSavedSettings.getBOOL("RememberPassword");
- show_connect_box = TRUE;
- }
- // Go to the next startup state
- LLStartUp::setStartupState( STATE_BROWSER_INIT );
- return FALSE;
- }
-
-
- if (STATE_BROWSER_INIT == LLStartUp::getStartupState())
- {
- LL_DEBUGS("AppInit") << "STATE_BROWSER_INIT" << LL_ENDL;
- std::string msg = LLTrans::getString("LoginInitializingBrowser");
- set_startup_status(0.03f, msg.c_str(), gAgent.mMOTD.c_str());
- display_startup();
- // LLViewerMedia::initBrowser();
- LLStartUp::setStartupState( STATE_LOGIN_SHOW );
- return FALSE;
- }
-
-
- if (STATE_LOGIN_SHOW == LLStartUp::getStartupState())
- {
- LL_DEBUGS("AppInit") << "Initializing Window" << LL_ENDL;
-
- // if we've gone backwards in the login state machine, to this state where we show the UI
- // AND the debug setting to exit in this case is true, then go ahead and bail quickly
- if ( mLoginStatePastUI && gSavedSettings.getBOOL("QuitOnLoginActivated") )
- {
- // no requirement for notification here - just exit
- LLAppViewer::instance()->earlyExitNoNotify();
- }
-
- gViewerWindow->getWindow()->setCursor(UI_CURSOR_ARROW);
-
- timeout_count = 0;
-
- if (show_connect_box)
- {
- // Load all the name information out of the login view
- // NOTE: Hits "Attempted getFields with no login view shown" warning, since we don't
- // show the login view until login_show() is called below.
- if (gUserCredential.isNull())
- {
- gUserCredential = gLoginHandler.initializeLoginInfo();
- }
- if (gNoRender)
- {
- LL_ERRS("AppInit") << "Need to autologin or use command line with norender!" << LL_ENDL;
- }
- // Make sure the process dialog doesn't hide things
- gViewerWindow->setShowProgress(FALSE);
-
- initialize_edit_menu();
-
- // Show the login dialog
- login_show();
- // connect dialog is already shown, so fill in the names
- if (gUserCredential.notNull())
- {
- LLPanelLogin::setFields( gUserCredential, gRememberPassword);
- }
- LLPanelLogin::giveFocus();
-
- gSavedSettings.setBOOL("FirstRunThisInstall", FALSE);
-
- LLStartUp::setStartupState( STATE_LOGIN_WAIT ); // Wait for user input
- }
- else
- {
- // skip directly to message template verification
- LLStartUp::setStartupState( STATE_LOGIN_CLEANUP );
- }
-
- // *NOTE: This is where LLViewerParcelMgr::getInstance() used to get allocated before becoming LLViewerParcelMgr::getInstance().
-
- // *NOTE: This is where gHUDManager used to bet allocated before becoming LLHUDManager::getInstance().
-
- // *NOTE: This is where gMuteList used to get allocated before becoming LLMuteList::getInstance().
-
- // Login screen needs menus for preferences, but we can enter
- // this startup phase more than once.
- if (gLoginMenuBarView == NULL)
- {
- init_menus();
- }
-
- gViewerWindow->setNormalControlsVisible( FALSE );
- gLoginMenuBarView->setVisible( TRUE );
- gLoginMenuBarView->setEnabled( TRUE );
- show_debug_menus();
-
- // Hide the splash screen
- LLSplashScreen::hide();
-
- // Push our window frontmost
- gViewerWindow->getWindow()->show();
- display_startup();
-
- // DEV-16927. The following code removes errant keystrokes that happen while the window is being
- // first made visible.
-#ifdef _WIN32
- MSG msg;
- while( PeekMessage( &msg, /*All hWnds owned by this thread */ NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE ) );
-#endif
- timeout.reset();
- return FALSE;
- }
-
- if (STATE_LOGIN_WAIT == LLStartUp::getStartupState())
- {
- // when we get to this state, we've already been past the login UI
- // (possiblely automatically) - flag this so we can test in the
- // STATE_LOGIN_SHOW state if we've gone backwards
- mLoginStatePastUI = true;
-
- // Don't do anything. Wait for the login view to call the login_callback,
- // which will push us to the next state.
-
- // Sleep so we don't spin the CPU
- ms_sleep(1);
- return FALSE;
- }
-
- if (STATE_LOGIN_CLEANUP == LLStartUp::getStartupState())
- {
- //reset the values that could have come in from a slurl
- // DEV-42215: Make sure they're not empty -- gUserCredential
- // might already have been set from gSavedSettings, and it's too bad
- // to overwrite valid values with empty strings.
-
- if (show_connect_box)
- {
- // TODO if not use viewer auth
- // Load all the name information out of the login view
- LLPanelLogin::getFields(gUserCredential, gRememberPassword);
- // end TODO
-
- // HACK: Try to make not jump on login
- gKeyboard->resetKeys();
- }
-
- // when we get to this state, we've already been past the login UI
- // (possiblely automatically) - flag this so we can test in the
- // STATE_LOGIN_SHOW state if we've gone backwards
- mLoginStatePastUI = true;
-
- // save the credentials
- std::string userid = "unknown";
- if(gUserCredential.notNull())
- {
- userid = gUserCredential->userID();
- gSecAPIHandler->saveCredential(gUserCredential, gRememberPassword);
- }
- gSavedSettings.setBOOL("RememberPassword", gRememberPassword);
- LL_INFOS("AppInit") << "Attempting login as: " << userid << LL_ENDL;
- gDebugInfo["LoginName"] = userid;
-
- // create necessary directories
- // *FIX: these mkdir's should error check
- gDirUtilp->setLindenUserDir(userid);
- LLFile::mkdir(gDirUtilp->getLindenUserDir());
-
- // Set PerAccountSettingsFile to the default value.
- std::string per_account_settings_file = LLAppViewer::instance()->getSettingsFilename("Default", "PerAccount");
- gSavedSettings.setString("PerAccountSettingsFile",
- gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT,
- LLAppViewer::instance()->getSettingsFilename("Default", "PerAccount")));
-
- // Note: can't store warnings files per account because some come up before login
-
- // Overwrite default user settings with user settings
- LLAppViewer::instance()->loadSettingsFromDirectory("Account");
-
- // Need to set the LastLogoff time here if we don't have one. LastLogoff is used for "Recent Items" calculation
- // and startup time is close enough if we don't have a real value.
- if (gSavedPerAccountSettings.getU32("LastLogoff") == 0)
- {
- gSavedPerAccountSettings.setU32("LastLogoff", time_corrected());
- }
-
- //Default the path if one isn't set.
- // *NOTE: unable to check variable differ from "InstantMessageLogPath" because it was
- // provided in pre 2.0 viewer. See EXT-6661
- if (gSavedPerAccountSettings.getString("InstantMessageLogPath").empty())
- {
- gDirUtilp->setChatLogsDir(gDirUtilp->getOSUserAppDir());
- gSavedPerAccountSettings.setString("InstantMessageLogPath", gDirUtilp->getChatLogsDir());
- }
- else
- {
- gDirUtilp->setChatLogsDir(gSavedPerAccountSettings.getString("InstantMessageLogPath"));
- }
- gDirUtilp->setPerAccountChatLogsDir(userid);
-
- LLFile::mkdir(gDirUtilp->getChatLogsDir());
- LLFile::mkdir(gDirUtilp->getPerAccountChatLogsDir());
-
-
- //good a place as any to create user windlight directories
- std::string user_windlight_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight", ""));
- LLFile::mkdir(user_windlight_path_name.c_str());
-
- std::string user_windlight_skies_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/skies", ""));
- LLFile::mkdir(user_windlight_skies_path_name.c_str());
-
- std::string user_windlight_water_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/water", ""));
- LLFile::mkdir(user_windlight_water_path_name.c_str());
-
- std::string user_windlight_days_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/days", ""));
- LLFile::mkdir(user_windlight_days_path_name.c_str());
-
-
- if (show_connect_box)
- {
- LLSLURL slurl;
- LLPanelLogin::closePanel();
- }
-
-
- // Load URL History File
- LLURLHistory::loadFile("url_history.xml");
- // Load location history
- LLLocationHistory::getInstance()->load();
-
- // Load Avatars icons cache
- LLAvatarIconIDCache::getInstance()->load();
-
- // Load media plugin cookies
- LLViewerMedia::loadCookieFile();
-
- //-------------------------------------------------
- // Handle startup progress screen
- //-------------------------------------------------
-
- // on startup the user can request to go to their home,
- // their last location, or some URL "-url //sim/x/y[/z]"
- // All accounts have both a home and a last location, and we don't support
- // more locations than that. Choose the appropriate one. JC
- switch (LLStartUp::getStartSLURL().getType())
- {
- case LLSLURL::LOCATION:
- agent_location_id = START_LOCATION_ID_URL;
- location_which = START_LOCATION_ID_LAST;
- break;
- case LLSLURL::LAST_LOCATION:
- agent_location_id = START_LOCATION_ID_LAST;
- location_which = START_LOCATION_ID_LAST;
- break;
- default:
- agent_location_id = START_LOCATION_ID_HOME;
- location_which = START_LOCATION_ID_HOME;
- break;
- }
-
- gViewerWindow->getWindow()->setCursor(UI_CURSOR_WAIT);
-
- if (!gNoRender)
- {
- init_start_screen(agent_location_id);
- }
-
- // Display the startup progress bar.
- gViewerWindow->setShowProgress(TRUE);
- gViewerWindow->setProgressCancelButtonVisible(TRUE, LLTrans::getString("Quit"));
-
- // Poke the VFS, which could potentially block for a while if
- // Windows XP is acting up
- set_startup_status(0.07f, LLTrans::getString("LoginVerifyingCache"), LLStringUtil::null);
- display_startup();
-
- gVFS->pokeFiles();
-
- LLStartUp::setStartupState( STATE_LOGIN_AUTH_INIT );
-
- return FALSE;
- }
-
- if(STATE_LOGIN_AUTH_INIT == LLStartUp::getStartupState())
- {
- gDebugInfo["GridName"] = LLGridManager::getInstance()->getGridLabel();
-
- // Update progress status and the display loop.
- auth_desc = LLTrans::getString("LoginInProgress");
- set_startup_status(progress, auth_desc, auth_message);
- progress += 0.02f;
- display_startup();
-
- // Setting initial values...
- LLLoginInstance* login = LLLoginInstance::getInstance();
- login->setNotificationsInterface(LLNotifications::getInstance());
- if(gNoRender)
- {
- // HACK, skip optional updates if you're running drones
- login->setSkipOptionalUpdate(true);
- }
-
- login->setSerialNumber(LLAppViewer::instance()->getSerialNumber());
- login->setLastExecEvent(gLastExecEvent);
- login->setUpdaterLauncher(boost::bind(&LLAppViewer::launchUpdater, LLAppViewer::instance()));
-
- // This call to LLLoginInstance::connect() starts the
- // authentication process.
- login->connect(gUserCredential);
-
- LLStartUp::setStartupState( STATE_LOGIN_CURL_UNSTUCK );
- return FALSE;
- }
-
- if(STATE_LOGIN_CURL_UNSTUCK == LLStartUp::getStartupState())
- {
- // If we get here we have gotten past the potential stall
- // in curl, so take "may appear frozen" out of progress bar. JC
- auth_desc = LLTrans::getString("LoginInProgressNoFrozen");
- set_startup_status(progress, auth_desc, auth_message);
-
- LLStartUp::setStartupState( STATE_LOGIN_PROCESS_RESPONSE );
- return FALSE;
- }
-
- if(STATE_LOGIN_PROCESS_RESPONSE == LLStartUp::getStartupState())
- {
- std::ostringstream emsg;
- emsg << LLTrans::getString("LoginFailed") << "\n";
- if(LLLoginInstance::getInstance()->authFailure())
- {
- LL_INFOS("LLStartup") << "Login failed, LLLoginInstance::getResponse(): "
- << LLLoginInstance::getInstance()->getResponse() << LL_ENDL;
- LLSD response = LLLoginInstance::getInstance()->getResponse();
- // Still have error conditions that may need some
- // sort of handling.
- std::string reason_response = response["reason"];
- std::string message_response = response["message"];
-
- if(!message_response.empty())
- {
- // XUI: fix translation for strings returned during login
- // We need a generic table for translations
- std::string big_reason = LLAgent::sTeleportErrorMessages[ message_response ];
- if ( big_reason.size() == 0 )
- {
- emsg << message_response;
- }
- else
- {
- emsg << big_reason;
- }
- }
-
- if(reason_response == "key")
- {
- // Couldn't login because user/password is wrong
- // Clear the credential
- gUserCredential->clearAuthenticator();
- }
-
- if(reason_response == "update"
- || reason_response == "optional")
- {
- // In the case of a needed update, quit.
- // Its either downloading or declined.
- // If optional was skipped this case shouldn't
- // be reached.
- LLLoginInstance::getInstance()->disconnect();
- LLAppViewer::instance()->forceQuit();
- }
- else
- {
- if (reason_response != "tos")
- {
- // Don't pop up a notification in the TOS case because
- // LLFloaterTOS::onCancel() already scolded the user.
- std::string error_code;
- if(response.has("errorcode"))
- {
- error_code = response["errorcode"].asString();
- }
- if ((reason_response == "CURLError") &&
- (error_code == "SSL_CACERT" || error_code == "SSL_PEER_CERTIFICATE") &&
- response.has("certificate"))
- {
- // This was a certificate error, so grab the certificate
- // and throw up the appropriate dialog.
- LLPointer<LLCertificate> certificate = gSecAPIHandler->getCertificate(response["certificate"]);
- if(certificate)
- {
- LLSD args = transform_cert_args(certificate);
-
- if(error_code == "SSL_CACERT")
- {
- // if we are handling an untrusted CA, throw up the dialog
- // with the 'trust this CA' button.
- LLNotificationsUtil::add("TrustCertificateError", args, response,
- trust_cert_done);
-
- show_connect_box = true;
- }
- else
- {
- // the certificate exception returns a unique string for each type of exception.
- // we grab this string via the LLUserAuth object, and use that to grab the localized
- // string.
- args["REASON"] = LLTrans::getString(message_response);
-
- LLNotificationsUtil::add("GeneralCertificateError", args, response,
- general_cert_done);
-
- reset_login();
- gSavedSettings.setBOOL("AutoLogin", FALSE);
- show_connect_box = true;
-
- }
-
- }
- }
- else
- {
- // This wasn't a certificate error, so throw up the normal
- // notificatioin message.
- LLSD args;
- args["ERROR_MESSAGE"] = emsg.str();
- LL_INFOS("LLStartup") << "Notification: " << args << LL_ENDL;
- LLNotificationsUtil::add("ErrorMessage", args, LLSD(), login_alert_done);
- }
- }
- //setup map of datetime strings to codes and slt & local time offset from utc
- // *TODO: Does this need to be here?
- LLStringOps::setupDatetimeInfo (false);
- transition_back_to_login_panel(emsg.str());
- show_connect_box = true;
- }
- }
- else if(LLLoginInstance::getInstance()->authSuccess())
- {
- if(process_login_success_response())
- {
- // Pass the user information to the voice chat server interface.
- LLVoiceClient::getInstance()->userAuthorized(gUserCredential->userID(), gAgentID);
- // create the default proximal channel
- LLVoiceChannel::initClass();
- LLGridManager::getInstance()->setFavorite();
- LLStartUp::setStartupState( STATE_WORLD_INIT);
- }
- else
- {
- LLSD args;
- args["ERROR_MESSAGE"] = emsg.str();
- LL_INFOS("LLStartup") << "Notification: " << args << LL_ENDL;
- LLNotificationsUtil::add("ErrorMessage", args, LLSD(), login_alert_done);
- transition_back_to_login_panel(emsg.str());
- show_connect_box = true;
- return FALSE;
- }
- }
- return FALSE;
- }
-
- //---------------------------------------------------------------------
- // World Init
- //---------------------------------------------------------------------
- if (STATE_WORLD_INIT == LLStartUp::getStartupState())
- {
- set_startup_status(0.30f, LLTrans::getString("LoginInitializingWorld"), gAgent.mMOTD);
- display_startup();
- // We should have an agent id by this point.
- llassert(!(gAgentID == LLUUID::null));
-
- // Finish agent initialization. (Requires gSavedSettings, builds camera)
- gAgent.init();
- gAgentCamera.init();
- set_underclothes_menu_options();
-
- // Since we connected, save off the settings so the user doesn't have to
- // type the name/password again if we crash.
- gSavedSettings.saveToFile(gSavedSettings.getString("ClientSettingsFile"), TRUE);
- LLUIColorTable::instance().saveUserSettings();
-
- //
- // Initialize classes w/graphics stuff.
- //
- gTextureList.doPrefetchImages();
- LLSurface::initClasses();
-
- LLFace::initClass();
-
- LLDrawable::initClass();
-
- // init the shader managers
- LLPostProcess::initClass();
- LLWLParamManager::initClass();
- LLWaterParamManager::initClass();
-
- LLViewerObject::initVOClasses();
-
- // Initialize all our tools. Must be done after saved settings loaded.
- // NOTE: This also is where gToolMgr used to be instantiated before being turned into a singleton.
- LLToolMgr::getInstance()->initTools();
-
- // Pre-load floaters, like the world map, that are slow to spawn
- // due to XML complexity.
- gViewerWindow->initWorldUI();
-
- display_startup();
-
- // This is where we used to initialize gWorldp. Original comment said:
- // World initialization must be done after above window init
-
- // User might have overridden far clip
- LLWorld::getInstance()->setLandFarClip(gAgentCamera.mDrawDistance);
-
- // Before we create the first region, we need to set the agent's mOriginGlobal
- // This is necessary because creating objects before this is set will result in a
- // bad mPositionAgent cache.
-
- gAgent.initOriginGlobal(from_region_handle(gFirstSimHandle));
-
- LLWorld::getInstance()->addRegion(gFirstSimHandle, gFirstSim);
-
- LLViewerRegion *regionp = LLWorld::getInstance()->getRegionFromHandle(gFirstSimHandle);
- LL_INFOS("AppInit") << "Adding initial simulator " << regionp->getOriginGlobal() << LL_ENDL;
-
- regionp->setSeedCapability(gFirstSimSeedCap);
- LL_DEBUGS("AppInit") << "Waiting for seed grant ...." << LL_ENDL;
-
- // Set agent's initial region to be the one we just created.
- gAgent.setRegion(regionp);
-
- // Set agent's initial position, which will be read by LLVOAvatar when the avatar
- // object is created. I think this must be done after setting the region. JC
- gAgent.setPositionAgent(agent_start_position_region);
-
- display_startup();
- LLStartUp::setStartupState( STATE_MULTIMEDIA_INIT );
-
- return FALSE;
- }
-
-
- //---------------------------------------------------------------------
- // Load QuickTime/GStreamer and other multimedia engines, can be slow.
- // Do it while we're waiting on the network for our seed capability. JC
- //---------------------------------------------------------------------
- if (STATE_MULTIMEDIA_INIT == LLStartUp::getStartupState())
- {
- LLStartUp::multimediaInit();
- LLStartUp::setStartupState( STATE_FONT_INIT );
- return FALSE;
- }
-
- // Loading fonts takes several seconds
- if (STATE_FONT_INIT == LLStartUp::getStartupState())
- {
- LLStartUp::fontInit();
- LLStartUp::setStartupState( STATE_SEED_GRANTED_WAIT );
- return FALSE;
- }
-
- //---------------------------------------------------------------------
- // Wait for Seed Cap Grant
- //---------------------------------------------------------------------
- if(STATE_SEED_GRANTED_WAIT == LLStartUp::getStartupState())
- {
- return FALSE;
- }
-
-
- //---------------------------------------------------------------------
- // Seed Capability Granted
- // no newMessage calls should happen before this point
- //---------------------------------------------------------------------
- if (STATE_SEED_CAP_GRANTED == LLStartUp::getStartupState())
- {
- update_texture_fetch();
-
- if ( gViewerWindow != NULL)
- { // This isn't the first logon attempt, so show the UI
- gViewerWindow->setNormalControlsVisible( TRUE );
- }
- gLoginMenuBarView->setVisible( FALSE );
- gLoginMenuBarView->setEnabled( FALSE );
-
- if (!gNoRender)
- {
- // direct logging to the debug console's line buffer
- LLError::logToFixedBuffer(gDebugView->mDebugConsolep);
-
- // set initial visibility of debug console
- gDebugView->mDebugConsolep->setVisible(gSavedSettings.getBOOL("ShowDebugConsole"));
- }
-
- //
- // Set message handlers
- //
- LL_INFOS("AppInit") << "Initializing communications..." << LL_ENDL;
-
- // register callbacks for messages. . . do this after initial handshake to make sure that we don't catch any unwanted
- register_viewer_callbacks(gMessageSystem);
-
- // Debugging info parameters
- gMessageSystem->setMaxMessageTime( 0.5f ); // Spam if decoding all msgs takes more than 500 ms
-
- #ifndef LL_RELEASE_FOR_DOWNLOAD
- gMessageSystem->setTimeDecodes( TRUE ); // Time the decode of each msg
- gMessageSystem->setTimeDecodesSpamThreshold( 0.05f ); // Spam if a single msg takes over 50ms to decode
- #endif
-
- gXferManager->registerCallbacks(gMessageSystem);
-
- LLStartUp::initNameCache();
-
- // update the voice settings *after* gCacheName initialization
- // so that we can construct voice UI that relies on the name cache
- LLVoiceClient::getInstance()->updateSettings();
-
- //gCacheName is required for nearby chat history loading
- //so I just moved nearby history loading a few states further
- if (!gNoRender && gSavedPerAccountSettings.getBOOL("LogShowHistory"))
- {
- LLNearbyChat* nearby_chat = LLNearbyChat::getInstance();
- if (nearby_chat) nearby_chat->loadHistory();
- }
-
- // *Note: this is where gWorldMap used to be initialized.
-
- // register null callbacks for audio until the audio system is initialized
- gMessageSystem->setHandlerFuncFast(_PREHASH_SoundTrigger, null_message_callback, NULL);
- gMessageSystem->setHandlerFuncFast(_PREHASH_AttachedSound, null_message_callback, NULL);
-
- //reset statistics
- LLViewerStats::getInstance()->resetStats();
-
- display_startup();
- //
- // Set up region and surface defaults
- //
-
-
- // Sets up the parameters for the first simulator
-
- LL_DEBUGS("AppInit") << "Initializing camera..." << LL_ENDL;
- gFrameTime = totalTime();
- F32 last_time = gFrameTimeSeconds;
- gFrameTimeSeconds = (S64)(gFrameTime - gStartTime)/SEC_TO_MICROSEC;
-
- gFrameIntervalSeconds = gFrameTimeSeconds - last_time;
- if (gFrameIntervalSeconds < 0.f)
- {
- gFrameIntervalSeconds = 0.f;
- }
-
- // Make sure agent knows correct aspect ratio
- // FOV limits depend upon aspect ratio so this needs to happen before initializing the FOV below
- LLViewerCamera::getInstance()->setViewHeightInPixels(gViewerWindow->getWorldViewHeightRaw());
- LLViewerCamera::getInstance()->setAspect(gViewerWindow->getWorldViewAspectRatio());
- // Initialize FOV
- LLViewerCamera::getInstance()->setDefaultFOV(gSavedSettings.getF32("CameraAngle"));
-
- // Move agent to starting location. The position handed to us by
- // the space server is in global coordinates, but the agent frame
- // is in region local coordinates. Therefore, we need to adjust
- // the coordinates handed to us to fit in the local region.
-
- gAgent.setPositionAgent(agent_start_position_region);
- gAgent.resetAxes(gAgentStartLookAt);
- gAgentCamera.stopCameraAnimation();
- gAgentCamera.resetCamera();
-
- // Initialize global class data needed for surfaces (i.e. textures)
- if (!gNoRender)
- {
- LL_DEBUGS("AppInit") << "Initializing sky..." << LL_ENDL;
- // Initialize all of the viewer object classes for the first time (doing things like texture fetches.
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
-
- gSky.init(initial_sun_direction);
-
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
- }
-
- LL_DEBUGS("AppInit") << "Decoding images..." << LL_ENDL;
- // For all images pre-loaded into viewer cache, decode them.
- // Need to do this AFTER we init the sky
- const S32 DECODE_TIME_SEC = 2;
- for (int i = 0; i < DECODE_TIME_SEC; i++)
- {
- F32 frac = (F32)i / (F32)DECODE_TIME_SEC;
- set_startup_status(0.45f + frac*0.1f, LLTrans::getString("LoginDecodingImages"), gAgent.mMOTD);
- display_startup();
- gTextureList.decodeAllImages(1.f);
- }
- LLStartUp::setStartupState( STATE_WORLD_WAIT );
-
- // JC - Do this as late as possible to increase likelihood Purify
- // will run.
- LLMessageSystem* msg = gMessageSystem;
- if (!msg->mOurCircuitCode)
- {
- LL_WARNS("AppInit") << "Attempting to connect to simulator with a zero circuit code!" << LL_ENDL;
- }
-
- gUseCircuitCallbackCalled = false;
-
- msg->enableCircuit(gFirstSim, TRUE);
- // now, use the circuit info to tell simulator about us!
- LL_INFOS("AppInit") << "viewer: UserLoginLocationReply() Enabling " << gFirstSim << " with code " << msg->mOurCircuitCode << LL_ENDL;
- msg->newMessageFast(_PREHASH_UseCircuitCode);
- msg->nextBlockFast(_PREHASH_CircuitCode);
- msg->addU32Fast(_PREHASH_Code, msg->mOurCircuitCode);
- msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- msg->addUUIDFast(_PREHASH_ID, gAgent.getID());
- msg->sendReliable(
- gFirstSim,
- gSavedSettings.getS32("UseCircuitCodeMaxRetries"),
- FALSE,
- gSavedSettings.getF32("UseCircuitCodeTimeout"),
- use_circuit_callback,
- NULL);
-
- timeout.reset();
-
- return FALSE;
- }
-
- //---------------------------------------------------------------------
- // Agent Send
- //---------------------------------------------------------------------
- if(STATE_WORLD_WAIT == LLStartUp::getStartupState())
- {
- LL_DEBUGS("AppInit") << "Waiting for simulator ack...." << LL_ENDL;
- set_startup_status(0.59f, LLTrans::getString("LoginWaitingForRegionHandshake"), gAgent.mMOTD);
- if(gGotUseCircuitCodeAck)
- {
- LLStartUp::setStartupState( STATE_AGENT_SEND );
- }
- LLMessageSystem* msg = gMessageSystem;
- while (msg->checkAllMessages(gFrameCount, gServicePump))
- {
- }
- msg->processAcks();
- return FALSE;
- }
-
- //---------------------------------------------------------------------
- // Agent Send
- //---------------------------------------------------------------------
- if (STATE_AGENT_SEND == LLStartUp::getStartupState())
- {
- LL_DEBUGS("AppInit") << "Connecting to region..." << LL_ENDL;
- set_startup_status(0.60f, LLTrans::getString("LoginConnectingToRegion"), gAgent.mMOTD);
- // register with the message system so it knows we're
- // expecting this message
- LLMessageSystem* msg = gMessageSystem;
- msg->setHandlerFuncFast(
- _PREHASH_AgentMovementComplete,
- process_agent_movement_complete);
- LLViewerRegion* regionp = gAgent.getRegion();
- if(regionp)
- {
- send_complete_agent_movement(regionp->getHost());
- gAssetStorage->setUpstream(regionp->getHost());
- gCacheName->setUpstream(regionp->getHost());
- msg->newMessageFast(_PREHASH_EconomyDataRequest);
- gAgent.sendReliableMessage();
- }
-
- // Create login effect
- // But not on first login, because you can't see your avatar then
- if (!gAgent.isFirstLogin())
- {
- LLHUDEffectSpiral *effectp = (LLHUDEffectSpiral *)LLHUDManager::getInstance()->createViewerEffect(LLHUDObject::LL_HUD_EFFECT_POINT, TRUE);
- effectp->setPositionGlobal(gAgent.getPositionGlobal());
- effectp->setColor(LLColor4U(gAgent.getEffectColor()));
- LLHUDManager::getInstance()->sendEffects();
- }
-
- LLStartUp::setStartupState( STATE_AGENT_WAIT ); // Go to STATE_AGENT_WAIT
-
- timeout.reset();
- return FALSE;
- }
-
- //---------------------------------------------------------------------
- // Agent Wait
- //---------------------------------------------------------------------
- if (STATE_AGENT_WAIT == LLStartUp::getStartupState())
- {
- LLMessageSystem* msg = gMessageSystem;
- while (msg->checkAllMessages(gFrameCount, gServicePump))
- {
- if (gAgentMovementCompleted)
- {
- // Sometimes we have more than one message in the
- // queue. break out of this loop and continue
- // processing. If we don't, then this could skip one
- // or more login steps.
- break;
- }
- else
- {
- LL_DEBUGS("AppInit") << "Awaiting AvatarInitComplete, got "
- << msg->getMessageName() << LL_ENDL;
- }
- }
- msg->processAcks();
-
- if (gAgentMovementCompleted)
- {
- LLStartUp::setStartupState( STATE_INVENTORY_SEND );
- }
-
- return FALSE;
- }
-
- //---------------------------------------------------------------------
- // Inventory Send
- //---------------------------------------------------------------------
- if (STATE_INVENTORY_SEND == LLStartUp::getStartupState())
- {
- // Inform simulator of our language preference
- LLAgentLanguage::update();
-
- // unpack thin inventory
- LLSD response = LLLoginInstance::getInstance()->getResponse();
- //bool dump_buffer = false;
-
- LLSD inv_lib_root = response["inventory-lib-root"];
- if(inv_lib_root.isDefined())
- {
- // should only be one
- LLSD id = inv_lib_root[0]["folder_id"];
- if(id.isDefined())
- {
- gInventory.setLibraryRootFolderID(id.asUUID());
- }
- }
-
- LLSD inv_lib_owner = response["inventory-lib-owner"];
- if(inv_lib_owner.isDefined())
- {
- // should only be one
- LLSD id = inv_lib_owner[0]["agent_id"];
- if(id.isDefined())
- {
- gInventory.setLibraryOwnerID( LLUUID(id.asUUID()));
- }
- }
-
- LLSD inv_skel_lib = response["inventory-skel-lib"];
- if(inv_skel_lib.isDefined() && gInventory.getLibraryOwnerID().notNull())
- {
- if(!gInventory.loadSkeleton(inv_skel_lib, gInventory.getLibraryOwnerID()))
- {
- LL_WARNS("AppInit") << "Problem loading inventory-skel-lib" << LL_ENDL;
- }
- }
-
- LLSD inv_skeleton = response["inventory-skeleton"];
- if(inv_skeleton.isDefined())
- {
- if(!gInventory.loadSkeleton(inv_skeleton, gAgent.getID()))
- {
- LL_WARNS("AppInit") << "Problem loading inventory-skel-targets" << LL_ENDL;
- }
- }
-
- LLSD buddy_list = response["buddy-list"];
- if(buddy_list.isDefined())
- {
- LLAvatarTracker::buddy_map_t list;
- LLUUID agent_id;
- S32 has_rights = 0, given_rights = 0;
- for(LLSD::array_const_iterator it = buddy_list.beginArray(),
- end = buddy_list.endArray(); it != end; ++it)
- {
- LLSD buddy_id = (*it)["buddy_id"];
- if(buddy_id.isDefined())
- {
- agent_id = buddy_id.asUUID();
- }
-
- LLSD buddy_rights_has = (*it)["buddy_rights_has"];
- if(buddy_rights_has.isDefined())
- {
- has_rights = buddy_rights_has.asInteger();
- }
-
- LLSD buddy_rights_given = (*it)["buddy_rights_given"];
- if(buddy_rights_given.isDefined())
- {
- given_rights = buddy_rights_given.asInteger();
- }
-
- list[agent_id] = new LLRelationship(given_rights, has_rights, false);
- }
- LLAvatarTracker::instance().addBuddyList(list);
- }
-
- bool show_hud = false;
- LLSD tutorial_setting = response["tutorial_setting"];
- if(tutorial_setting.isDefined())
- {
- for(LLSD::array_const_iterator it = tutorial_setting.beginArray(),
- end = tutorial_setting.endArray(); it != end; ++it)
- {
- LLSD tutorial_url = (*it)["tutorial_url"];
- if(tutorial_url.isDefined())
- {
- // Tutorial floater will append language code
- gSavedSettings.setString("TutorialURL", tutorial_url.asString());
- }
-
- // For Viewer 2.0 we are not using the web-based tutorial
- // If we reverse that decision, put this code back and use
- // login.cgi to send a different URL with content that matches
- // the Viewer 2.0 UI.
- //LLSD use_tutorial = (*it)["use_tutorial"];
- //if(use_tutorial.asString() == "true")
- //{
- // show_hud = true;
- //}
- }
- }
- // Either we want to show tutorial because this is the first login
- // to a Linden Help Island or the user quit with the tutorial
- // visible. JC
- if (show_hud || gSavedSettings.getBOOL("ShowTutorial"))
- {
- LLFloaterReg::showInstance("hud", LLSD(), FALSE);
- }
-
- LLSD event_notifications = response["event_notifications"];
- if(event_notifications.isDefined())
- {
- gEventNotifier.load(event_notifications);
- }
-
- LLSD classified_categories = response["classified_categories"];
- if(classified_categories.isDefined())
- {
- LLClassifiedInfo::loadCategories(classified_categories);
- }
-
- // This method MUST be called before gInventory.findCategoryUUIDForType because of
- // gInventory.mIsAgentInvUsable is set to true in the gInventory.buildParentChildMap.
- gInventory.buildParentChildMap();
-
- //all categories loaded. lets create "My Favorites" category
- gInventory.findCategoryUUIDForType(LLFolderType::FT_FAVORITE,true);
-
- // set up callbacks
- llinfos << "Registering Callbacks" << llendl;
- LLMessageSystem* msg = gMessageSystem;
- llinfos << " Inventory" << llendl;
- LLInventoryModel::registerCallbacks(msg);
- llinfos << " AvatarTracker" << llendl;
- LLAvatarTracker::instance().registerCallbacks(msg);
- llinfos << " Landmark" << llendl;
- LLLandmark::registerCallbacks(msg);
-
- // request mute list
- llinfos << "Requesting Mute List" << llendl;
- LLMuteList::getInstance()->requestFromServer(gAgent.getID());
-
- // Get L$ and ownership credit information
- llinfos << "Requesting Money Balance" << llendl;
- LLStatusBar::sendMoneyBalanceRequest();
-
- // request all group information
- llinfos << "Requesting Agent Data" << llendl;
- gAgent.sendAgentDataUpdateRequest();
-
- // Create the inventory views
- llinfos << "Creating Inventory Views" << llendl;
- LLFloaterReg::getInstance("inventory");
-
- LLStartUp::setStartupState( STATE_MISC );
- return FALSE;
- }
-
-
- //---------------------------------------------------------------------
- // Misc
- //---------------------------------------------------------------------
- if (STATE_MISC == LLStartUp::getStartupState())
- {
- // We have a region, and just did a big inventory download.
- // We can estimate the user's connection speed, and set their
- // max bandwidth accordingly. JC
- if (gSavedSettings.getBOOL("FirstLoginThisInstall"))
- {
- // This is actually a pessimistic computation, because TCP may not have enough
- // time to ramp up on the (small) default inventory file to truly measure max
- // bandwidth. JC
- F64 rate_bps = LLLoginInstance::getInstance()->getLastTransferRateBPS();
- const F32 FAST_RATE_BPS = 600.f * 1024.f;
- const F32 FASTER_RATE_BPS = 750.f * 1024.f;
- F32 max_bandwidth = gViewerThrottle.getMaxBandwidth();
- if (rate_bps > FASTER_RATE_BPS
- && rate_bps > max_bandwidth)
- {
- LL_DEBUGS("AppInit") << "Fast network connection, increasing max bandwidth to "
- << FASTER_RATE_BPS/1024.f
- << " kbps" << LL_ENDL;
- gViewerThrottle.setMaxBandwidth(FASTER_RATE_BPS / 1024.f);
- }
- else if (rate_bps > FAST_RATE_BPS
- && rate_bps > max_bandwidth)
- {
- LL_DEBUGS("AppInit") << "Fast network connection, increasing max bandwidth to "
- << FAST_RATE_BPS/1024.f
- << " kbps" << LL_ENDL;
- gViewerThrottle.setMaxBandwidth(FAST_RATE_BPS / 1024.f);
- }
-
- // Set the show start location to true, now that the user has logged
- // on with this install.
- gSavedSettings.setBOOL("ShowStartLocation", TRUE);
- }
-
- // We're successfully logged in.
- gSavedSettings.setBOOL("FirstLoginThisInstall", FALSE);
-
- LLFloaterReg::showInitialVisibleInstances();
-
- // based on the comments, we've successfully logged in so we can delete the 'forced'
- // URL that the updater set in settings.ini (in a mostly paranoid fashion)
- std::string nextLoginLocation = gSavedSettings.getString( "NextLoginLocation" );
- if ( nextLoginLocation.length() )
- {
- // clear it
- gSavedSettings.setString( "NextLoginLocation", "" );
-
- // and make sure it's saved
- gSavedSettings.saveToFile( gSavedSettings.getString("ClientSettingsFile") , TRUE );
- LLUIColorTable::instance().saveUserSettings();
- };
-
- if (!gNoRender)
- {
- // JC: Initializing audio requests many sounds for download.
- init_audio();
-
- // JC: Initialize "active" gestures. This may also trigger
- // many gesture downloads, if this is the user's first
- // time on this machine or -purge has been run.
- LLSD gesture_options
- = LLLoginInstance::getInstance()->getResponse("gestures");
- if (gesture_options.isDefined())
- {
- LL_DEBUGS("AppInit") << "Gesture Manager loading " << gesture_options.size()
- << LL_ENDL;
- uuid_vec_t item_ids;
- for(LLSD::array_const_iterator resp_it = gesture_options.beginArray(),
- end = gesture_options.endArray(); resp_it != end; ++resp_it)
- {
- // If the id is not specifed in the LLSD,
- // the LLSD operator[]() will return a null LLUUID.
- LLUUID item_id = (*resp_it)["item_id"];
- LLUUID asset_id = (*resp_it)["asset_id"];
-
- if (item_id.notNull() && asset_id.notNull())
- {
- // Could schedule and delay these for later.
- const BOOL no_inform_server = FALSE;
- const BOOL no_deactivate_similar = FALSE;
- LLGestureMgr::instance().activateGestureWithAsset(item_id, asset_id,
- no_inform_server,
- no_deactivate_similar);
- // We need to fetch the inventory items for these gestures
- // so we have the names to populate the UI.
- item_ids.push_back(item_id);
- }
- }
- // no need to add gesture to inventory observer, it's already made in constructor
- LLGestureMgr::instance().setFetchIDs(item_ids);
- LLGestureMgr::instance().startFetch();
- }
- }
- gDisplaySwapBuffers = TRUE;
-
- LLMessageSystem* msg = gMessageSystem;
- msg->setHandlerFuncFast(_PREHASH_SoundTrigger, process_sound_trigger);
- msg->setHandlerFuncFast(_PREHASH_PreloadSound, process_preload_sound);
- msg->setHandlerFuncFast(_PREHASH_AttachedSound, process_attached_sound);
- msg->setHandlerFuncFast(_PREHASH_AttachedSoundGainChange, process_attached_sound_gain_change);
-
- LL_DEBUGS("AppInit") << "Initialization complete" << LL_ENDL;
-
- gRenderStartTime.reset();
- gForegroundTime.reset();
-
- // HACK: Inform simulator of window size.
- // Do this here so it's less likely to race with RegisterNewAgent.
- // TODO: Put this into RegisterNewAgent
- // JC - 7/20/2002
- gViewerWindow->sendShapeToSim();
-
-
- // Ignore stipend information for now. Money history is on the web site.
- // if needed, show the L$ history window
- //if (stipend_since_login && !gNoRender)
- //{
- //}
-
- // The reason we show the alert is because we want to
- // reduce confusion for when you log in and your provided
- // location is not your expected location. So, if this is
- // your first login, then you do not have an expectation,
- // thus, do not show this alert.
- if (!gAgent.isFirstLogin())
- {
- llinfos << "gAgentStartLocation : " << gAgentStartLocation << llendl;
- LLSLURL start_slurl = LLStartUp::getStartSLURL();
-
- if (((start_slurl.getType() == LLSLURL::LOCATION) && (gAgentStartLocation == "url")) ||
- ((start_slurl.getType() == LLSLURL::LAST_LOCATION) && (gAgentStartLocation == "last")) ||
- ((start_slurl.getType() == LLSLURL::HOME_LOCATION) && (gAgentStartLocation == "home")))
- {
- // Start location is OK
- // Disabled code to restore camera location and focus if logging in to default location
- static bool samename = false;
- if (samename)
- {
- // restore old camera pos
- gAgentCamera.setFocusOnAvatar(FALSE, FALSE);
- gAgentCamera.setCameraPosAndFocusGlobal(gSavedSettings.getVector3d("CameraPosOnLogout"), gSavedSettings.getVector3d("FocusPosOnLogout"), LLUUID::null);
- BOOL limit_hit = FALSE;
- gAgentCamera.calcCameraPositionTargetGlobal(&limit_hit);
- if (limit_hit)
- {
- gAgentCamera.setFocusOnAvatar(TRUE, FALSE);
- }
- gAgentCamera.stopCameraAnimation();
- }
- }
- else
- {
- std::string msg;
- switch(start_slurl.getType())
- {
- case LLSLURL::LOCATION:
- {
-
- msg = "AvatarMovedDesired";
- break;
- }
- case LLSLURL::HOME_LOCATION:
- {
- msg = "AvatarMovedHome";
- break;
- }
- default:
- {
- msg = "AvatarMovedLast";
- }
- }
- LLNotificationsUtil::add(msg);
- }
- }
-
- //DEV-17797. get null folder. Any items found here moved to Lost and Found
- LLInventoryModelBackgroundFetch::instance().findLostItems();
-
- LLStartUp::setStartupState( STATE_PRECACHE );
- timeout.reset();
- return FALSE;
- }
-
- if (STATE_PRECACHE == LLStartUp::getStartupState())
- {
- F32 timeout_frac = timeout.getElapsedTimeF32()/PRECACHING_DELAY;
-
- // We now have an inventory skeleton, so if this is a user's first
- // login, we can start setting up their clothing and avatar
- // appearance. This helps to avoid the generic "Ruth" avatar in
- // the orientation island tutorial experience. JC
- if (gAgent.isFirstLogin()
- && !sInitialOutfit.empty() // registration set up an outfit
- && !sInitialOutfitGender.empty() // and a gender
- && isAgentAvatarValid() // can't wear clothes without object
- && !gAgent.isGenderChosen() ) // nothing already loading
- {
- // Start loading the wearables, textures, gestures
- LLStartUp::loadInitialOutfit( sInitialOutfit, sInitialOutfitGender );
- }
-
- // wait precache-delay and for agent's avatar or a lot longer.
- if(((timeout_frac > 1.f) && isAgentAvatarValid())
- || (timeout_frac > 3.f))
- {
- LLStartUp::setStartupState( STATE_WEARABLES_WAIT );
- }
- else
- {
- update_texture_fetch();
- set_startup_status(0.60f + 0.30f * timeout_frac,
- LLTrans::getString("LoginPrecaching"),
- gAgent.mMOTD);
- display_startup();
- if (!LLViewerShaderMgr::sInitialized)
- {
- LLViewerShaderMgr::sInitialized = TRUE;
- LLViewerShaderMgr::instance()->setShaders();
- }
- }
-
- return TRUE;
- }
-
- if (STATE_WEARABLES_WAIT == LLStartUp::getStartupState())
- {
- static LLFrameTimer wearables_timer;
-
- const F32 wearables_time = wearables_timer.getElapsedTimeF32();
- const F32 MAX_WEARABLES_TIME = 10.f;
-
- if (!gAgent.isGenderChosen())
- {
- // No point in waiting for clothing, we don't even
- // know what gender we are. Pop a dialog to ask and
- // proceed to draw the world. JC
- //
- // *NOTE: We might hit this case even if we have an
- // initial outfit, but if the load hasn't started
- // already then something is wrong so fall back
- // to generic outfits. JC
- LLNotificationsUtil::add("WelcomeChooseSex", LLSD(), LLSD(),
- callback_choose_gender);
- LLStartUp::setStartupState( STATE_CLEANUP );
- return TRUE;
- }
-
- if (wearables_time > MAX_WEARABLES_TIME)
- {
- LLNotificationsUtil::add("ClothingLoading");
- LLViewerStats::getInstance()->incStat(LLViewerStats::ST_WEARABLES_TOO_LONG);
- LLStartUp::setStartupState( STATE_CLEANUP );
- return TRUE;
- }
-
- if (gAgent.isFirstLogin())
- {
- // wait for avatar to be completely loaded
- if (isAgentAvatarValid()
- && gAgentAvatarp->isFullyLoaded())
- {
- //llinfos << "avatar fully loaded" << llendl;
- LLStartUp::setStartupState( STATE_CLEANUP );
- return TRUE;
- }
- }
- else
- {
- // OK to just get the wearables
- if ( gAgentWearables.areWearablesLoaded() )
- {
- // We have our clothing, proceed.
- //llinfos << "wearables loaded" << llendl;
- LLStartUp::setStartupState( STATE_CLEANUP );
- return TRUE;
- }
- }
-
- update_texture_fetch();
- set_startup_status(0.9f + 0.1f * wearables_time / MAX_WEARABLES_TIME,
- LLTrans::getString("LoginDownloadingClothing").c_str(),
- gAgent.mMOTD.c_str());
- return TRUE;
- }
-
- if (STATE_CLEANUP == LLStartUp::getStartupState())
- {
- set_startup_status(1.0, "", "");
-
- // Let the map know about the inventory.
- LLFloaterWorldMap* floater_world_map = LLFloaterWorldMap::getInstance();
- if(floater_world_map)
- {
- floater_world_map->observeInventory(&gInventory);
- floater_world_map->observeFriends();
- }
- gViewerWindow->showCursor();
- gViewerWindow->getWindow()->resetBusyCount();
- gViewerWindow->getWindow()->setCursor(UI_CURSOR_ARROW);
- LL_DEBUGS("AppInit") << "Done releasing bitmap" << LL_ENDL;
- gViewerWindow->setShowProgress(FALSE);
- gViewerWindow->setProgressCancelButtonVisible(FALSE);
-
- // We're not away from keyboard, even though login might have taken
- // a while. JC
- gAgent.clearAFK();
-
- // Have the agent start watching the friends list so we can update proxies
- gAgent.observeFriends();
- if (gSavedSettings.getBOOL("LoginAsGod"))
- {
- gAgent.requestEnterGodMode();
- }
-
- // Start automatic replay if the flag is set.
- if (gSavedSettings.getBOOL("StatsAutoRun") || LLAgentPilot::sReplaySession)
- {
- LLUUID id;
- LL_DEBUGS("AppInit") << "Starting automatic playback" << LL_ENDL;
- gAgentPilot.startPlayback();
- }
-
- show_debug_menus(); // Debug menu visiblity and First Use trigger
-
- // If we've got a startup URL, dispatch it
- LLStartUp::dispatchURL();
-
- // Retrieve information about the land data
- // (just accessing this the first time will fetch it,
- // then the data is cached for the viewer's lifetime)
- LLProductInfoRequestManager::instance();
-
- // *FIX:Mani - What do I do here?
- // Need we really clear the Auth response data?
- // Clean up the userauth stuff.
- // LLUserAuth::getInstance()->reset();
-
- LLStartUp::setStartupState( STATE_STARTED );
-
- // Unmute audio if desired and setup volumes.
- // Unmute audio if desired and setup volumes.
- // This is a not-uncommon crash site, so surround it with
- // llinfos output to aid diagnosis.
- LL_INFOS("AppInit") << "Doing first audio_update_volume..." << LL_ENDL;
- audio_update_volume();
- LL_INFOS("AppInit") << "Done first audio_update_volume." << LL_ENDL;
-
- // reset keyboard focus to sane state of pointing at world
- gFocusMgr.setKeyboardFocus(NULL);
-
-#if 0 // sjb: enable for auto-enabling timer display
- gDebugView->mFastTimerView->setVisible(TRUE);
-#endif
-
- LLAppViewer::instance()->handleLoginComplete();
-
- // reset timers now that we are running "logged in" logic
- LLFastTimer::reset();
-
- LLAgentPicksInfo::getInstance()->requestNumberOfPicks();
-
- LLIMFloater::initIMFloater();
-
- return TRUE;
- }
-
- LL_WARNS("AppInit") << "Reached end of idle_startup for state " << LLStartUp::getStartupState() << LL_ENDL;
- return TRUE;
-}
-
-//
-// local function definition
-//
-
-void login_show()
-{
- LL_INFOS("AppInit") << "Initializing Login Screen" << LL_ENDL;
-
-#ifdef LL_RELEASE_FOR_DOWNLOAD
- BOOL bUseDebugLogin = gSavedSettings.getBOOL("UseDebugLogin");
-#else
- BOOL bUseDebugLogin = TRUE;
-#endif
-
- LLPanelLogin::show( gViewerWindow->getWindowRectScaled(),
- bUseDebugLogin || gSavedSettings.getBOOL("SecondLifeEnterprise"),
- login_callback, NULL );
-
-}
-
-// Callback for when login screen is closed. Option 0 = connect, option 1 = quit.
-void login_callback(S32 option, void *userdata)
-{
- const S32 CONNECT_OPTION = 0;
- const S32 QUIT_OPTION = 1;
-
- if (CONNECT_OPTION == option)
- {
- LLStartUp::setStartupState( STATE_LOGIN_CLEANUP );
- return;
- }
- else if (QUIT_OPTION == option) // *TODO: THIS CODE SEEMS TO BE UNREACHABLE!!!!! login_callback is never called with option equal to QUIT_OPTION
- {
- if (!gSavedSettings.getBOOL("RememberPassword"))
- {
- // turn off the setting and write out to disk
- gSavedSettings.saveToFile( gSavedSettings.getString("ClientSettingsFile") , TRUE );
- LLUIColorTable::instance().saveUserSettings();
- }
-
- // Next iteration through main loop should shut down the app cleanly.
- LLAppViewer::instance()->userQuit();
-
- if (LLAppViewer::instance()->quitRequested())
- {
- LLPanelLogin::closePanel();
- }
- return;
- }
- else
- {
- LL_WARNS("AppInit") << "Unknown login button clicked" << LL_ENDL;
- }
-}
-
-void show_first_run_dialog()
-{
- LLNotificationsUtil::add("FirstRun", LLSD(), LLSD(), first_run_dialog_callback);
-}
-
-bool first_run_dialog_callback(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- if (0 == option)
- {
- LL_DEBUGS("AppInit") << "First run dialog cancelling" << LL_ENDL;
- LLWeb::loadURLExternal(LLTrans::getString("create_account_url") );
- }
-
- LLPanelLogin::giveFocus();
- return false;
-}
-
-
-
-void set_startup_status(const F32 frac, const std::string& string, const std::string& msg)
-{
- gViewerWindow->setProgressPercent(frac*100);
- gViewerWindow->setProgressString(string);
-
- gViewerWindow->setProgressMessage(msg);
-}
-
-bool login_alert_status(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- // Buttons
- switch( option )
- {
- case 0: // OK
- break;
- // case 1: // Help
- // LLWeb::loadURL(LLNotifications::instance().getGlobalString("SUPPORT_URL") );
- // break;
- case 2: // Teleport
- // Restart the login process, starting at our home locaton
- LLStartUp::setStartSLURL(LLSLURL(LLSLURL::SIM_LOCATION_HOME));
- LLStartUp::setStartupState( STATE_LOGIN_CLEANUP );
- break;
- default:
- LL_WARNS("AppInit") << "Missing case in login_alert_status switch" << LL_ENDL;
- }
-
- LLPanelLogin::giveFocus();
- return false;
-}
-
-
-void use_circuit_callback(void**, S32 result)
-{
- // bail if we're quitting.
- if(LLApp::isExiting()) return;
- if( !gUseCircuitCallbackCalled )
- {
- gUseCircuitCallbackCalled = true;
- if (result)
- {
- // Make sure user knows something bad happened. JC
- LL_WARNS("AppInit") << "Backing up to login screen!" << LL_ENDL;
- LLNotificationsUtil::add("LoginPacketNeverReceived", LLSD(), LLSD(), login_alert_status);
- reset_login();
- }
- else
- {
- gGotUseCircuitCodeAck = true;
- }
- }
-}
-
-void register_viewer_callbacks(LLMessageSystem* msg)
-{
- msg->setHandlerFuncFast(_PREHASH_LayerData, process_layer_data );
- msg->setHandlerFuncFast(_PREHASH_ImageData, LLViewerTextureList::receiveImageHeader );
- msg->setHandlerFuncFast(_PREHASH_ImagePacket, LLViewerTextureList::receiveImagePacket );
- msg->setHandlerFuncFast(_PREHASH_ObjectUpdate, process_object_update );
- msg->setHandlerFunc("ObjectUpdateCompressed", process_compressed_object_update );
- msg->setHandlerFunc("ObjectUpdateCached", process_cached_object_update );
- msg->setHandlerFuncFast(_PREHASH_ImprovedTerseObjectUpdate, process_terse_object_update_improved );
- msg->setHandlerFunc("SimStats", process_sim_stats);
- msg->setHandlerFuncFast(_PREHASH_HealthMessage, process_health_message );
- msg->setHandlerFuncFast(_PREHASH_EconomyData, process_economy_data);
- msg->setHandlerFunc("RegionInfo", LLViewerRegion::processRegionInfo);
-
- msg->setHandlerFuncFast(_PREHASH_ChatFromSimulator, process_chat_from_simulator);
- msg->setHandlerFuncFast(_PREHASH_KillObject, process_kill_object, NULL);
- msg->setHandlerFuncFast(_PREHASH_SimulatorViewerTimeMessage, process_time_synch, NULL);
- msg->setHandlerFuncFast(_PREHASH_EnableSimulator, process_enable_simulator);
- msg->setHandlerFuncFast(_PREHASH_DisableSimulator, process_disable_simulator);
- msg->setHandlerFuncFast(_PREHASH_KickUser, process_kick_user, NULL);
-
- msg->setHandlerFunc("CrossedRegion", process_crossed_region);
- msg->setHandlerFuncFast(_PREHASH_TeleportFinish, process_teleport_finish);
-
- msg->setHandlerFuncFast(_PREHASH_AlertMessage, process_alert_message);
- msg->setHandlerFunc("AgentAlertMessage", process_agent_alert_message);
- msg->setHandlerFuncFast(_PREHASH_MeanCollisionAlert, process_mean_collision_alert_message, NULL);
- msg->setHandlerFunc("ViewerFrozenMessage", process_frozen_message);
-
- msg->setHandlerFuncFast(_PREHASH_NameValuePair, process_name_value);
- msg->setHandlerFuncFast(_PREHASH_RemoveNameValuePair, process_remove_name_value);
- msg->setHandlerFuncFast(_PREHASH_AvatarAnimation, process_avatar_animation);
- msg->setHandlerFuncFast(_PREHASH_AvatarAppearance, process_avatar_appearance);
- msg->setHandlerFunc("AgentCachedTextureResponse", LLAgent::processAgentCachedTextureResponse);
- msg->setHandlerFunc("RebakeAvatarTextures", LLVOAvatarSelf::processRebakeAvatarTextures);
- msg->setHandlerFuncFast(_PREHASH_CameraConstraint, process_camera_constraint);
- msg->setHandlerFuncFast(_PREHASH_AvatarSitResponse, process_avatar_sit_response);
- msg->setHandlerFunc("SetFollowCamProperties", process_set_follow_cam_properties);
- msg->setHandlerFunc("ClearFollowCamProperties", process_clear_follow_cam_properties);
-
- msg->setHandlerFuncFast(_PREHASH_ImprovedInstantMessage, process_improved_im);
- msg->setHandlerFuncFast(_PREHASH_ScriptQuestion, process_script_question);
- msg->setHandlerFuncFast(_PREHASH_ObjectProperties, LLSelectMgr::processObjectProperties, NULL);
- msg->setHandlerFuncFast(_PREHASH_ObjectPropertiesFamily, LLSelectMgr::processObjectPropertiesFamily, NULL);
- msg->setHandlerFunc("ForceObjectSelect", LLSelectMgr::processForceObjectSelect);
-
- msg->setHandlerFuncFast(_PREHASH_MoneyBalanceReply, process_money_balance_reply, NULL);
- msg->setHandlerFuncFast(_PREHASH_CoarseLocationUpdate, LLWorld::processCoarseUpdate, NULL);
- msg->setHandlerFuncFast(_PREHASH_ReplyTaskInventory, LLViewerObject::processTaskInv, NULL);
- msg->setHandlerFuncFast(_PREHASH_DerezContainer, process_derez_container, NULL);
- msg->setHandlerFuncFast(_PREHASH_ScriptRunningReply,
- &LLLiveLSLEditor::processScriptRunningReply);
-
- msg->setHandlerFuncFast(_PREHASH_DeRezAck, process_derez_ack);
-
- msg->setHandlerFunc("LogoutReply", process_logout_reply);
-
- //msg->setHandlerFuncFast(_PREHASH_AddModifyAbility,
- // &LLAgent::processAddModifyAbility);
- //msg->setHandlerFuncFast(_PREHASH_RemoveModifyAbility,
- // &LLAgent::processRemoveModifyAbility);
- msg->setHandlerFuncFast(_PREHASH_AgentDataUpdate,
- &LLAgent::processAgentDataUpdate);
- msg->setHandlerFuncFast(_PREHASH_AgentGroupDataUpdate,
- &LLAgent::processAgentGroupDataUpdate);
- msg->setHandlerFunc("AgentDropGroup",
- &LLAgent::processAgentDropGroup);
- // land ownership messages
- msg->setHandlerFuncFast(_PREHASH_ParcelOverlay,
- LLViewerParcelMgr::processParcelOverlay);
- msg->setHandlerFuncFast(_PREHASH_ParcelProperties,
- LLViewerParcelMgr::processParcelProperties);
- msg->setHandlerFunc("ParcelAccessListReply",
- LLViewerParcelMgr::processParcelAccessListReply);
- msg->setHandlerFunc("ParcelDwellReply",
- LLViewerParcelMgr::processParcelDwellReply);
-
- msg->setHandlerFunc("AvatarPropertiesReply",
- &LLAvatarPropertiesProcessor::processAvatarPropertiesReply);
- msg->setHandlerFunc("AvatarInterestsReply",
- &LLAvatarPropertiesProcessor::processAvatarInterestsReply);
- msg->setHandlerFunc("AvatarGroupsReply",
- &LLAvatarPropertiesProcessor::processAvatarGroupsReply);
- // ratings deprecated
- //msg->setHandlerFuncFast(_PREHASH_AvatarStatisticsReply,
- // LLPanelAvatar::processAvatarStatisticsReply);
- msg->setHandlerFunc("AvatarNotesReply",
- &LLAvatarPropertiesProcessor::processAvatarNotesReply);
- msg->setHandlerFunc("AvatarPicksReply",
- &LLAvatarPropertiesProcessor::processAvatarPicksReply);
- msg->setHandlerFunc("AvatarClassifiedReply",
- &LLAvatarPropertiesProcessor::processAvatarClassifiedsReply);
-
- msg->setHandlerFuncFast(_PREHASH_CreateGroupReply,
- LLGroupMgr::processCreateGroupReply);
- msg->setHandlerFuncFast(_PREHASH_JoinGroupReply,
- LLGroupMgr::processJoinGroupReply);
- msg->setHandlerFuncFast(_PREHASH_EjectGroupMemberReply,
- LLGroupMgr::processEjectGroupMemberReply);
- msg->setHandlerFuncFast(_PREHASH_LeaveGroupReply,
- LLGroupMgr::processLeaveGroupReply);
- msg->setHandlerFuncFast(_PREHASH_GroupProfileReply,
- LLGroupMgr::processGroupPropertiesReply);
-
- // ratings deprecated
- // msg->setHandlerFuncFast(_PREHASH_ReputationIndividualReply,
- // LLFloaterRate::processReputationIndividualReply);
-
- msg->setHandlerFuncFast(_PREHASH_AgentWearablesUpdate,
- LLAgentWearables::processAgentInitialWearablesUpdate );
-
- msg->setHandlerFunc("ScriptControlChange",
- LLAgent::processScriptControlChange );
-
- msg->setHandlerFuncFast(_PREHASH_ViewerEffect, LLHUDManager::processViewerEffect);
-
- msg->setHandlerFuncFast(_PREHASH_GrantGodlikePowers, process_grant_godlike_powers);
-
- msg->setHandlerFuncFast(_PREHASH_GroupAccountSummaryReply,
- LLPanelGroupLandMoney::processGroupAccountSummaryReply);
- msg->setHandlerFuncFast(_PREHASH_GroupAccountDetailsReply,
- LLPanelGroupLandMoney::processGroupAccountDetailsReply);
- msg->setHandlerFuncFast(_PREHASH_GroupAccountTransactionsReply,
- LLPanelGroupLandMoney::processGroupAccountTransactionsReply);
-
- msg->setHandlerFuncFast(_PREHASH_UserInfoReply,
- process_user_info_reply);
-
- msg->setHandlerFunc("RegionHandshake", process_region_handshake, NULL);
-
- msg->setHandlerFunc("TeleportStart", process_teleport_start );
- msg->setHandlerFunc("TeleportProgress", process_teleport_progress);
- msg->setHandlerFunc("TeleportFailed", process_teleport_failed, NULL);
- msg->setHandlerFunc("TeleportLocal", process_teleport_local, NULL);
-
- msg->setHandlerFunc("ImageNotInDatabase", LLViewerTextureList::processImageNotInDatabase, NULL);
-
- msg->setHandlerFuncFast(_PREHASH_GroupMembersReply,
- LLGroupMgr::processGroupMembersReply);
- msg->setHandlerFunc("GroupRoleDataReply",
- LLGroupMgr::processGroupRoleDataReply);
- msg->setHandlerFunc("GroupRoleMembersReply",
- LLGroupMgr::processGroupRoleMembersReply);
- msg->setHandlerFunc("GroupTitlesReply",
- LLGroupMgr::processGroupTitlesReply);
- // Special handler as this message is sometimes used for group land.
- msg->setHandlerFunc("PlacesReply", process_places_reply);
- msg->setHandlerFunc("GroupNoticesListReply", LLPanelGroupNotices::processGroupNoticesListReply);
-
- msg->setHandlerFunc("AvatarPickerReply", LLFloaterAvatarPicker::processAvatarPickerReply);
-
- msg->setHandlerFunc("MapBlockReply", LLWorldMapMessage::processMapBlockReply);
- msg->setHandlerFunc("MapItemReply", LLWorldMapMessage::processMapItemReply);
- msg->setHandlerFunc("EventInfoReply", LLEventNotifier::processEventInfoReply);
-
- msg->setHandlerFunc("PickInfoReply", &LLAvatarPropertiesProcessor::processPickInfoReply);
-// msg->setHandlerFunc("ClassifiedInfoReply", LLPanelClassified::processClassifiedInfoReply);
- msg->setHandlerFunc("ClassifiedInfoReply", LLAvatarPropertiesProcessor::processClassifiedInfoReply);
- msg->setHandlerFunc("ParcelInfoReply", LLRemoteParcelInfoProcessor::processParcelInfoReply);
- msg->setHandlerFunc("ScriptDialog", process_script_dialog);
- msg->setHandlerFunc("LoadURL", process_load_url);
- msg->setHandlerFunc("ScriptTeleportRequest", process_script_teleport_request);
- msg->setHandlerFunc("EstateCovenantReply", process_covenant_reply);
-
- // calling cards
- msg->setHandlerFunc("OfferCallingCard", process_offer_callingcard);
- msg->setHandlerFunc("AcceptCallingCard", process_accept_callingcard);
- msg->setHandlerFunc("DeclineCallingCard", process_decline_callingcard);
-
- msg->setHandlerFunc("ParcelObjectOwnersReply", LLPanelLandObjects::processParcelObjectOwnersReply);
-
- msg->setHandlerFunc("InitiateDownload", process_initiate_download);
- msg->setHandlerFunc("LandStatReply", LLFloaterTopObjects::handle_land_reply);
- msg->setHandlerFunc("GenericMessage", process_generic_message);
-
- msg->setHandlerFuncFast(_PREHASH_FeatureDisabled, process_feature_disabled_message);
-}
-
-void asset_callback_nothing(LLVFS*, const LLUUID&, LLAssetType::EType, void*, S32)
-{
- // nothing
-}
-
-// *HACK: Must match name in Library or agent inventory
-const std::string ROOT_GESTURES_FOLDER = "Gestures";
-const std::string COMMON_GESTURES_FOLDER = "Common Gestures";
-const std::string MALE_GESTURES_FOLDER = "Male Gestures";
-const std::string FEMALE_GESTURES_FOLDER = "Female Gestures";
-const std::string SPEECH_GESTURES_FOLDER = "Speech Gestures";
-const std::string OTHER_GESTURES_FOLDER = "Other Gestures";
-const S32 OPT_CLOSED_WINDOW = -1;
-const S32 OPT_MALE = 0;
-const S32 OPT_FEMALE = 1;
-const S32 OPT_TRUST_CERT = 0;
-const S32 OPT_CANCEL_TRUST = 1;
-
-bool callback_choose_gender(const LLSD& notification, const LLSD& response)
-{
-
- // These defaults are returned from the server on login. They are set in login.xml.
- // If no default is returned from the server, they are retrieved from settings.xml.
-
- S32 option = LLNotification::getSelectedOption(notification, response);
- switch(option)
- {
- case OPT_MALE:
- LLStartUp::loadInitialOutfit( gSavedSettings.getString("DefaultMaleAvatar"), "male" );
- break;
-
- case OPT_FEMALE:
- case OPT_CLOSED_WINDOW:
- default:
- LLStartUp::loadInitialOutfit( gSavedSettings.getString("DefaultFemaleAvatar"), "female" );
- break;
- }
- return false;
-}
-
-void LLStartUp::copyLibraryGestures(const std::string& same_gender_gestures)
-{
- llinfos << "Copying library gestures" << llendl;
-
- // Copy gestures
- LLUUID lib_gesture_cat_id =
- gInventory.findCategoryUUIDForType(LLFolderType::FT_GESTURE,false,true);
- if (lib_gesture_cat_id.isNull())
- {
- llwarns << "Unable to copy gestures, source category not found" << llendl;
- }
- LLUUID dst_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_GESTURE);
-
- std::vector<std::string> gesture_folders_to_copy;
- gesture_folders_to_copy.push_back(MALE_GESTURES_FOLDER);
- gesture_folders_to_copy.push_back(FEMALE_GESTURES_FOLDER);
- gesture_folders_to_copy.push_back(COMMON_GESTURES_FOLDER);
- gesture_folders_to_copy.push_back(SPEECH_GESTURES_FOLDER);
- gesture_folders_to_copy.push_back(OTHER_GESTURES_FOLDER);
-
- for(std::vector<std::string>::iterator it = gesture_folders_to_copy.begin();
- it != gesture_folders_to_copy.end();
- ++it)
- {
- std::string& folder_name = *it;
-
- LLPointer<LLInventoryCallback> cb(NULL);
-
- if (folder_name == same_gender_gestures ||
- folder_name == COMMON_GESTURES_FOLDER ||
- folder_name == OTHER_GESTURES_FOLDER)
- {
- cb = new ActivateGestureCallback;
- }
-
-
- LLUUID cat_id = findDescendentCategoryIDByName(lib_gesture_cat_id,folder_name);
- if (cat_id.isNull())
- {
- llwarns << "failed to find gesture folder for " << folder_name << llendl;
- }
- else
- {
- llinfos << "initiating fetch and copy for " << folder_name << " cat_id " << cat_id << llendl;
- LLAppearanceMgr* app_mgr = LLAppearanceMgr::getInstance();
- callAfterCategoryFetch(cat_id,
- boost::bind(&LLAppearanceMgr::shallowCopyCategory,
- app_mgr,
- cat_id,
- dst_id,
- cb));
- }
- }
-}
-
-void LLStartUp::loadInitialOutfit( const std::string& outfit_folder_name,
- const std::string& gender_name )
-{
- llinfos << "starting" << llendl;
-
- // Not going through the processAgentInitialWearables path, so need to set this here.
- LLAppearanceMgr::instance().setAttachmentInvLinkEnable(true);
- // Initiate creation of COF, since we're also bypassing that.
- gInventory.findCategoryUUIDForType(LLFolderType::FT_CURRENT_OUTFIT);
-
- S32 gender = 0;
- std::string same_gender_gestures;
- if (gender_name == "male")
- {
- gender = OPT_MALE;
- same_gender_gestures = MALE_GESTURES_FOLDER;
- }
- else
- {
- gender = OPT_FEMALE;
- same_gender_gestures = FEMALE_GESTURES_FOLDER;
- }
-
- // try to find the outfit - if not there, create some default
- // wearables.
- LLUUID cat_id = findDescendentCategoryIDByName(
- gInventory.getLibraryRootFolderID(),
- outfit_folder_name);
- if (cat_id.isNull())
- {
- gAgentWearables.createStandardWearables(gender);
- }
- else
- {
- sWearablesLoadedCon = gAgentWearables.addLoadedCallback(LLStartUp::saveInitialOutfit);
-
- bool do_copy = true;
- bool do_append = false;
- LLViewerInventoryCategory *cat = gInventory.getCategory(cat_id);
- LLAppearanceMgr::instance().wearInventoryCategory(cat, do_copy, do_append);
- }
-
- // Copy gestures
- copyLibraryGestures(same_gender_gestures);
-
- // This is really misnamed -- it means we have started loading
- // an outfit/shape that will give the avatar a gender eventually. JC
- gAgent.setGenderChosen(TRUE);
-
-}
-
-//static
-void LLStartUp::saveInitialOutfit()
-{
- if (sInitialOutfit.empty()) return;
-
- if (sWearablesLoadedCon.connected())
- {
- sWearablesLoadedCon.disconnect();
- }
- LLAppearanceMgr::getInstance()->makeNewOutfitLinks(sInitialOutfit,false);
-}
-
-std::string& LLStartUp::getInitialOutfitName()
-{
- return sInitialOutfit;
-}
-
-// Loads a bitmap to display during load
-void init_start_screen(S32 location_id)
-{
- if (gStartTexture.notNull())
- {
- gStartTexture = NULL;
- LL_INFOS("AppInit") << "re-initializing start screen" << LL_ENDL;
- }
-
- LL_DEBUGS("AppInit") << "Loading startup bitmap..." << LL_ENDL;
-
- std::string temp_str = gDirUtilp->getLindenUserDir() + gDirUtilp->getDirDelimiter();
-
- if ((S32)START_LOCATION_ID_LAST == location_id)
- {
- temp_str += SCREEN_LAST_FILENAME;
- }
- else
- {
- temp_str += SCREEN_HOME_FILENAME;
- }
-
- LLPointer<LLImageBMP> start_image_bmp = new LLImageBMP;
-
- // Turn off start screen to get around the occasional readback
- // driver bug
- if(!gSavedSettings.getBOOL("UseStartScreen"))
- {
- LL_INFOS("AppInit") << "Bitmap load disabled" << LL_ENDL;
- return;
- }
- else if(!start_image_bmp->load(temp_str) )
- {
- LL_WARNS("AppInit") << "Bitmap load failed" << LL_ENDL;
- return;
- }
-
- gStartImageWidth = start_image_bmp->getWidth();
- gStartImageHeight = start_image_bmp->getHeight();
-
- LLPointer<LLImageRaw> raw = new LLImageRaw;
- if (!start_image_bmp->decode(raw, 0.0f))
- {
- LL_WARNS("AppInit") << "Bitmap decode failed" << LL_ENDL;
- gStartTexture = NULL;
- return;
- }
-
- raw->expandToPowerOfTwo();
- gStartTexture = LLViewerTextureManager::getLocalTexture(raw.get(), FALSE) ;
-}
-
-
-// frees the bitmap
-void release_start_screen()
-{
- LL_DEBUGS("AppInit") << "Releasing bitmap..." << LL_ENDL;
- gStartTexture = NULL;
-}
-
-
-// static
-std::string LLStartUp::startupStateToString(EStartupState state)
-{
-#define RTNENUM(E) case E: return #E
- switch(state){
- RTNENUM( STATE_FIRST );
- RTNENUM( STATE_BROWSER_INIT );
- RTNENUM( STATE_LOGIN_SHOW );
- RTNENUM( STATE_LOGIN_WAIT );
- RTNENUM( STATE_LOGIN_CLEANUP );
- RTNENUM( STATE_LOGIN_AUTH_INIT );
- RTNENUM( STATE_LOGIN_CURL_UNSTUCK );
- RTNENUM( STATE_LOGIN_PROCESS_RESPONSE );
- RTNENUM( STATE_WORLD_INIT );
- RTNENUM( STATE_MULTIMEDIA_INIT );
- RTNENUM( STATE_FONT_INIT );
- RTNENUM( STATE_SEED_GRANTED_WAIT );
- RTNENUM( STATE_SEED_CAP_GRANTED );
- RTNENUM( STATE_WORLD_WAIT );
- RTNENUM( STATE_AGENT_SEND );
- RTNENUM( STATE_AGENT_WAIT );
- RTNENUM( STATE_INVENTORY_SEND );
- RTNENUM( STATE_MISC );
- RTNENUM( STATE_PRECACHE );
- RTNENUM( STATE_WEARABLES_WAIT );
- RTNENUM( STATE_CLEANUP );
- RTNENUM( STATE_STARTED );
- default:
- return llformat("(state #%d)", state);
- }
-#undef RTNENUM
-}
-
-// static
-void LLStartUp::setStartupState( EStartupState state )
-{
- LL_INFOS("AppInit") << "Startup state changing from " <<
- getStartupStateString() << " to " <<
- startupStateToString(state) << LL_ENDL;
- gStartupState = state;
- postStartupState();
-}
-
-void LLStartUp::postStartupState()
-{
- LLSD stateInfo;
- stateInfo["str"] = getStartupStateString();
- stateInfo["enum"] = gStartupState;
- sStateWatcher->post(stateInfo);
-}
-
-
-void reset_login()
-{
- gAgentWearables.cleanup();
- gAgentCamera.cleanup();
- gAgent.cleanup();
- LLWorld::getInstance()->destroyClass();
-
- LLStartUp::setStartupState( STATE_LOGIN_SHOW );
-
- if ( gViewerWindow )
- { // Hide menus and normal buttons
- gViewerWindow->setNormalControlsVisible( FALSE );
- gLoginMenuBarView->setVisible( TRUE );
- gLoginMenuBarView->setEnabled( TRUE );
- }
-
- // Hide any other stuff
- LLFloaterReg::hideVisibleInstances();
-}
-
-//---------------------------------------------------------------------------
-
-// Initialize all plug-ins except the web browser (which was initialized
-// early, before the login screen). JC
-void LLStartUp::multimediaInit()
-{
- LL_DEBUGS("AppInit") << "Initializing Multimedia...." << LL_ENDL;
- std::string msg = LLTrans::getString("LoginInitializingMultimedia");
- set_startup_status(0.42f, msg.c_str(), gAgent.mMOTD.c_str());
- display_startup();
-
- // LLViewerMedia::initClass();
- LLViewerParcelMedia::initClass();
-}
-
-void LLStartUp::fontInit()
-{
- LL_DEBUGS("AppInit") << "Initializing fonts...." << LL_ENDL;
- std::string msg = LLTrans::getString("LoginInitializingFonts");
- set_startup_status(0.45f, msg.c_str(), gAgent.mMOTD.c_str());
- display_startup();
-
- LLFontGL::loadDefaultFonts();
-}
-
-void LLStartUp::initNameCache()
-{
- // Can be called multiple times
- if ( gCacheName ) return;
-
- gCacheName = new LLCacheName(gMessageSystem);
- gCacheName->addObserver(&callback_cache_name);
- gCacheName->localizeCacheName("waiting", LLTrans::getString("AvatarNameWaiting"));
- gCacheName->localizeCacheName("nobody", LLTrans::getString("AvatarNameNobody"));
- gCacheName->localizeCacheName("none", LLTrans::getString("GroupNameNone"));
- // Load stored cache if possible
- LLAppViewer::instance()->loadNameCache();
-
- // Start cache in not-running state until we figure out if we have
- // capabilities for display name lookup
- LLAvatarNameCache::initClass(false);
- LLAvatarNameCache::setUseDisplayNames(gSavedSettings.getBOOL("UseDisplayNames"));
-}
-
-void LLStartUp::cleanupNameCache()
-{
- LLAvatarNameCache::cleanupClass();
-
- delete gCacheName;
- gCacheName = NULL;
-}
-
-bool LLStartUp::dispatchURL()
-{
- // ok, if we've gotten this far and have a startup URL
- if (!getStartSLURL().isValid())
- {
- return false;
- }
- if(getStartSLURL().getType() != LLSLURL::APP)
- {
-
- // If we started with a location, but we're already
- // at that location, don't pop dialogs open.
- LLVector3 pos = gAgent.getPositionAgent();
- LLVector3 slurlpos = getStartSLURL().getPosition();
- F32 dx = pos.mV[VX] - slurlpos.mV[VX];
- F32 dy = pos.mV[VY] - slurlpos.mV[VY];
- const F32 SLOP = 2.f; // meters
-
- if( getStartSLURL().getRegion() != gAgent.getRegion()->getName()
- || (dx*dx > SLOP*SLOP)
- || (dy*dy > SLOP*SLOP) )
- {
- LLURLDispatcher::dispatch(getStartSLURL().getSLURLString(),
- NULL, false);
- }
- return true;
- }
- return false;
-}
-
-void LLStartUp::setStartSLURL(const LLSLURL& slurl)
-{
- sStartSLURL = slurl;
- switch(slurl.getType())
- {
- case LLSLURL::HOME_LOCATION:
- {
- gSavedSettings.setString("LoginLocation", LLSLURL::SIM_LOCATION_HOME);
- break;
- }
- case LLSLURL::LAST_LOCATION:
- {
- gSavedSettings.setString("LoginLocation", LLSLURL::SIM_LOCATION_LAST);
- break;
- }
- default:
- LLGridManager::getInstance()->setGridChoice(slurl.getGrid());
- break;
- }
-}
-
-bool login_alert_done(const LLSD& notification, const LLSD& response)
-{
- LLPanelLogin::giveFocus();
- return false;
-}
-
-// parse the certificate information into args for the
-// certificate notifications
-LLSD transform_cert_args(LLPointer<LLCertificate> cert)
-{
- LLSD args = LLSD::emptyMap();
- std::string value;
- LLSD cert_info;
- cert->getLLSD(cert_info);
- // convert all of the elements in the cert into
- // args for the xml dialog, so we have flexability to
- // display various parts of the cert by only modifying
- // the cert alert dialog xml.
- for(LLSD::map_iterator iter = cert_info.beginMap();
- iter != cert_info.endMap();
- iter++)
- {
- // key usage and extended key usage
- // are actually arrays, and we want to format them as comma separated
- // strings, so special case those.
- LLSDSerialize::toXML(cert_info[iter->first], std::cout);
- if((iter->first== std::string(CERT_KEY_USAGE)) |
- (iter->first == std::string(CERT_EXTENDED_KEY_USAGE)))
- {
- value = "";
- LLSD usage = cert_info[iter->first];
- for (LLSD::array_iterator usage_iter = usage.beginArray();
- usage_iter != usage.endArray();
- usage_iter++)
- {
-
- if(usage_iter != usage.beginArray())
- {
- value += ", ";
- }
-
- value += (*usage_iter).asString();
- }
-
- }
- else
- {
- value = iter->second.asString();
- }
-
- std::string name = iter->first;
- std::transform(name.begin(), name.end(), name.begin(),
- (int(*)(int))toupper);
- args[name.c_str()] = value;
- }
- return args;
-}
-
-
-// when we handle a cert error, give focus back to the login panel
-void general_cert_done(const LLSD& notification, const LLSD& response)
-{
- LLStartUp::setStartupState( STATE_LOGIN_SHOW );
- LLPanelLogin::giveFocus();
-}
-
-// check to see if the user wants to trust the cert.
-// if they do, add it to the cert store and
-void trust_cert_done(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotification::getSelectedOption(notification, response);
- switch(option)
- {
- case OPT_TRUST_CERT:
- {
- LLPointer<LLCertificate> cert = gSecAPIHandler->getCertificate(notification["payload"]["certificate"]);
- LLPointer<LLCertificateStore> store = gSecAPIHandler->getCertificateStore(gSavedSettings.getString("CertStore"));
- store->add(cert);
- store->save();
- LLStartUp::setStartupState( STATE_LOGIN_CLEANUP );
- break;
- }
- case OPT_CANCEL_TRUST:
- reset_login();
- gSavedSettings.setBOOL("AutoLogin", FALSE);
- LLStartUp::setStartupState( STATE_LOGIN_SHOW );
- default:
- LLPanelLogin::giveFocus();
- break;
- }
-
-}
-
-void apply_udp_blacklist(const std::string& csv)
-{
-
- std::string::size_type start = 0;
- std::string::size_type comma = 0;
- do
- {
- comma = csv.find(",", start);
- if (comma == std::string::npos)
- {
- comma = csv.length();
- }
- std::string item(csv, start, comma-start);
-
- lldebugs << "udp_blacklist " << item << llendl;
- gMessageSystem->banUdpMessage(item);
-
- start = comma + 1;
-
- }
- while(comma < csv.length());
-
-}
-
-bool process_login_success_response()
-{
- LLSD response = LLLoginInstance::getInstance()->getResponse();
-
- std::string text(response["udp_blacklist"]);
- if(!text.empty())
- {
- apply_udp_blacklist(text);
- }
-
- // unpack login data needed by the application
- text = response["agent_id"].asString();
- if(!text.empty()) gAgentID.set(text);
- gDebugInfo["AgentID"] = text;
-
- // Agent id needed for parcel info request in LLUrlEntryParcel
- // to resolve parcel name.
- LLUrlEntryParcel::setAgentID(gAgentID);
-
- text = response["session_id"].asString();
- if(!text.empty()) gAgentSessionID.set(text);
- gDebugInfo["SessionID"] = text;
-
- // Session id needed for parcel info request in LLUrlEntryParcel
- // to resolve parcel name.
- LLUrlEntryParcel::setSessionID(gAgentSessionID);
-
- text = response["secure_session_id"].asString();
- if(!text.empty()) gAgent.mSecureSessionID.set(text);
-
- // if the response contains a display name, use that,
- // otherwise if the response contains a first and/or last name,
- // use those. Otherwise use the credential identifier
-
- gDisplayName = "";
- if (response.has("display_name"))
- {
- gDisplayName.assign(response["display_name"].asString());
- if(!gDisplayName.empty())
- {
- // Remove quotes from string. Login.cgi sends these to force
- // names that look like numbers into strings.
- LLStringUtil::replaceChar(gDisplayName, '"', ' ');
- LLStringUtil::trim(gDisplayName);
- }
- }
- if(gDisplayName.empty())
- {
- if(response.has("first_name"))
- {
- gDisplayName.assign(response["first_name"].asString());
- LLStringUtil::replaceChar(gDisplayName, '"', ' ');
- LLStringUtil::trim(gDisplayName);
- }
- if(response.has("last_name"))
- {
- text.assign(response["last_name"].asString());
- LLStringUtil::replaceChar(text, '"', ' ');
- LLStringUtil::trim(text);
- if(!gDisplayName.empty())
- {
- gDisplayName += " ";
- }
- gDisplayName += text;
- }
- }
- if(gDisplayName.empty())
- {
- gDisplayName.assign(gUserCredential->asString());
- }
-
- // this is their actual ability to access content
- text = response["agent_access_max"].asString();
- if (!text.empty())
- {
- // agent_access can be 'A', 'M', and 'PG'.
- gAgent.setMaturity(text[0]);
- }
-
- // this is the value of their preference setting for that content
- // which will always be <= agent_access_max
- text = response["agent_region_access"].asString();
- if (!text.empty())
- {
- U32 preferredMaturity = (U32)LLAgent::convertTextToMaturity(text[0]);
-
- gSavedSettings.setU32("PreferredMaturity", preferredMaturity);
- }
- // During the AO transition, this flag will be true. Then the flag will
- // go away. After the AO transition, this code and all the code that
- // uses it can be deleted.
- text = response["ao_transition"].asString();
- if (!text.empty())
- {
- if (text == "1")
- {
- gAgent.setAOTransition();
- }
- }
-
- text = response["start_location"].asString();
- if(!text.empty())
- {
- gAgentStartLocation.assign(text);
- }
-
- text = response["circuit_code"].asString();
- if(!text.empty())
- {
- gMessageSystem->mOurCircuitCode = strtoul(text.c_str(), NULL, 10);
- }
- std::string sim_ip_str = response["sim_ip"];
- std::string sim_port_str = response["sim_port"];
- if(!sim_ip_str.empty() && !sim_port_str.empty())
- {
- U32 sim_port = strtoul(sim_port_str.c_str(), NULL, 10);
- gFirstSim.set(sim_ip_str, sim_port);
- if (gFirstSim.isOk())
- {
- gMessageSystem->enableCircuit(gFirstSim, TRUE);
- }
- }
- std::string region_x_str = response["region_x"];
- std::string region_y_str = response["region_y"];
- if(!region_x_str.empty() && !region_y_str.empty())
- {
- U32 region_x = strtoul(region_x_str.c_str(), NULL, 10);
- U32 region_y = strtoul(region_y_str.c_str(), NULL, 10);
- gFirstSimHandle = to_region_handle(region_x, region_y);
- }
-
- const std::string look_at_str = response["look_at"];
- if (!look_at_str.empty())
- {
- size_t len = look_at_str.size();
- LLMemoryStream mstr((U8*)look_at_str.c_str(), len);
- LLSD sd = LLSDSerialize::fromNotation(mstr, len);
- gAgentStartLookAt = ll_vector3_from_sd(sd);
- }
-
- text = response["seed_capability"].asString();
- if (!text.empty()) gFirstSimSeedCap = text;
-
- text = response["seconds_since_epoch"].asString();
- if(!text.empty())
- {
- U32 server_utc_time = strtoul(text.c_str(), NULL, 10);
- if(server_utc_time)
- {
- time_t now = time(NULL);
- gUTCOffset = (server_utc_time - now);
- }
- }
-
- // this is the base used to construct help URLs
- text = response["help_url_format"].asString();
- if (!text.empty())
- {
- // replace the default help URL format
- gSavedSettings.setString("HelpURLFormat",text);
-
- // don't fall back to Standalone's pre-connection static help
- gSavedSettings.setBOOL("HelpUseLocal", false);
- }
-
- std::string home_location = response["home"];
- if(!home_location.empty())
- {
- size_t len = home_location.size();
- LLMemoryStream mstr((U8*)home_location.c_str(), len);
- LLSD sd = LLSDSerialize::fromNotation(mstr, len);
- S32 region_x = sd["region_handle"][0].asInteger();
- S32 region_y = sd["region_handle"][1].asInteger();
- U64 region_handle = to_region_handle(region_x, region_y);
- LLVector3 position = ll_vector3_from_sd(sd["position"]);
- gAgent.setHomePosRegion(region_handle, position);
- }
-
- gAgent.mMOTD.assign(response["message"]);
-
- // Options...
- // Each 'option' is an array of submaps.
- // It appears that we only ever use the first element of the array.
- LLUUID inv_root_folder_id = response["inventory-root"][0]["folder_id"];
- if(inv_root_folder_id.notNull())
- {
- gInventory.setRootFolderID(inv_root_folder_id);
- //gInventory.mock(gAgent.getInventoryRootID());
- }
-
- LLSD login_flags = response["login-flags"][0];
- if(login_flags.size())
- {
- std::string flag = login_flags["ever_logged_in"];
- if(!flag.empty())
- {
- gAgent.setFirstLogin((flag == "N") ? TRUE : FALSE);
- }
-
- /* Flag is currently ignored by the viewer.
- flag = login_flags["stipend_since_login"];
- if(flag == "Y")
- {
- stipend_since_login = true;
- }
- */
-
- flag = login_flags["gendered"].asString();
- if(flag == "Y")
- {
- gAgent.setGenderChosen(TRUE);
- }
-
- bool pacific_daylight_time = false;
- flag = login_flags["daylight_savings"].asString();
- if(flag == "Y")
- {
- pacific_daylight_time = (flag == "Y");
- }
-
- //setup map of datetime strings to codes and slt & local time offset from utc
- LLStringOps::setupDatetimeInfo(pacific_daylight_time);
- }
-
- // set up the voice configuration. Ultimately, we should pass this up as part of each voice
- // channel if we need to move to multiple voice servers per grid.
- LLSD voice_config_info = response["voice-config"];
- if(voice_config_info.has("VoiceServerType"))
- {
- gSavedSettings.setString("VoiceServerType", voice_config_info["VoiceServerType"].asString());
- }
-
- // Request the map server url
- std::string map_server_url = response["map-server-url"];
- if(!map_server_url.empty())
- {
- // We got an answer from the grid -> use that for map for the current session
- gSavedSettings.setString("CurrentMapServerURL", map_server_url);
- LL_INFOS("LLStartup") << "map-server-url : we got an answer from the grid : " << map_server_url << LL_ENDL;
- }
- else
- {
- // No answer from the grid -> use the default setting for current session
- map_server_url = gSavedSettings.getString("MapServerURL");
- gSavedSettings.setString("CurrentMapServerURL", map_server_url);
- LL_INFOS("LLStartup") << "map-server-url : no map-server-url answer, we use the default setting for the map : " << map_server_url << LL_ENDL;
- }
-
- // Default male and female avatars allowing the user to choose their avatar on first login.
- // These may be passed up by SLE to allow choice of enterprise avatars instead of the standard
- // "new ruth." Not to be confused with 'initial-outfit' below
- LLSD newuser_config = response["newuser-config"][0];
- if(newuser_config.has("DefaultFemaleAvatar"))
- {
- gSavedSettings.setString("DefaultFemaleAvatar", newuser_config["DefaultFemaleAvatar"].asString());
- }
- if(newuser_config.has("DefaultMaleAvatar"))
- {
- gSavedSettings.setString("DefaultMaleAvatar", newuser_config["DefaultMaleAvatar"].asString());
- }
-
- // Initial outfit for the user.
- // QUESTION: Why can't we simply simply set the users outfit directly
- // from a web page into the user info on the server? - Roxie
- LLSD initial_outfit = response["initial-outfit"][0];
- if(initial_outfit.size())
- {
- std::string flag = initial_outfit["folder_name"];
- if(!flag.empty())
- {
- // Initial outfit is a folder in your inventory,
- // must be an exact folder-name match.
- sInitialOutfit = flag;
- }
-
- flag = initial_outfit["gender"].asString();
- if(!flag.empty())
- {
- sInitialOutfitGender = flag;
- }
- }
-
- LLSD global_textures = response["global-textures"][0];
- if(global_textures.size())
- {
- // Extract sun and moon texture IDs. These are used
- // in the LLVOSky constructor, but I can't figure out
- // how to pass them in. JC
- LLUUID id = global_textures["sun_texture_id"];
- if(id.notNull())
- {
- gSunTextureID = id;
- }
-
- id = global_textures["moon_texture_id"];
- if(id.notNull())
- {
- gMoonTextureID = id;
- }
-
- id = global_textures["cloud_texture_id"];
- if(id.notNull())
- {
- gCloudTextureID = id;
- }
- }
-
- // Set the location of the snapshot sharing config endpoint
- std::string snapshot_config_url = response["snapshot_config_url"];
- if(!snapshot_config_url.empty())
- {
- gSavedSettings.setString("SnapshotConfigURL", snapshot_config_url);
- }
-
- // Start the process of fetching the OpenID session cookie for this user login
- std::string openid_url = response["openid_url"];
- if(!openid_url.empty())
- {
- std::string openid_token = response["openid_token"];
- LLViewerMedia::openIDSetup(openid_url, openid_token);
- }
-
- if(response.has("max-agent-groups")) {
- std::string max_agent_groups(response["max-agent-groups"]);
- gMaxAgentGroups = atoi(max_agent_groups.c_str());
- LL_INFOS("LLStartup") << "gMaxAgentGroups read from login.cgi: "
- << gMaxAgentGroups << LL_ENDL;
- }
- else {
- gMaxAgentGroups = DEFAULT_MAX_AGENT_GROUPS;
- LL_INFOS("LLStartup") << "using gMaxAgentGroups default: "
- << gMaxAgentGroups << LL_ENDL;
- }
-
- bool success = false;
- // JC: gesture loading done below, when we have an asset system
- // in place. Don't delete/clear gUserCredentials until then.
- if(gAgentID.notNull()
- && gAgentSessionID.notNull()
- && gMessageSystem->mOurCircuitCode
- && gFirstSim.isOk()
- && gInventory.getRootFolderID().notNull())
- {
- success = true;
- }
-
- return success;
-}
-
-void transition_back_to_login_panel(const std::string& emsg)
-{
- if (gNoRender)
- {
- LL_WARNS("AppInit") << "Failed to login!" << LL_ENDL;
- LL_WARNS("AppInit") << emsg << LL_ENDL;
- exit(0);
- }
-
- // Bounce back to the login screen.
- reset_login(); // calls LLStartUp::setStartupState( STATE_LOGIN_SHOW );
- gSavedSettings.setBOOL("AutoLogin", FALSE);
-}
+/**
+ * @file llstartup.cpp
+ * @brief startup routines.
+ *
+ * $LicenseInfo:firstyear=2004&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h"
+
+#include "llstartup.h"
+
+#if LL_WINDOWS
+# include <process.h> // _spawnl()
+#else
+# include <sys/stat.h> // mkdir()
+#endif
+
+#include "llviewermedia_streamingaudio.h"
+#include "llaudioengine.h"
+
+#ifdef LL_FMOD
+# include "llaudioengine_fmod.h"
+#endif
+
+#ifdef LL_OPENAL
+#include "llaudioengine_openal.h"
+#endif
+
+#include "llares.h"
+#include "llavatarnamecache.h"
+#include "lllandmark.h"
+#include "llcachename.h"
+#include "lldir.h"
+#include "llerrorcontrol.h"
+#include "llfloaterreg.h"
+#include "llfocusmgr.h"
+#include "llhttpsender.h"
+#include "llimfloater.h"
+#include "lllocationhistory.h"
+#include "llimageworker.h"
+
+#include "llloginflags.h"
+#include "llmd5.h"
+#include "llmemorystream.h"
+#include "llmessageconfig.h"
+#include "llmoveview.h"
+#include "llnearbychat.h"
+#include "llnotifications.h"
+#include "llnotificationsutil.h"
+#include "llteleporthistory.h"
+#include "llregionhandle.h"
+#include "llsd.h"
+#include "llsdserialize.h"
+#include "llsdutil_math.h"
+#include "llsecondlifeurls.h"
+#include "llstring.h"
+#include "lluserrelations.h"
+#include "llversioninfo.h"
+#include "llviewercontrol.h"
+#include "llvfs.h"
+#include "llxorcipher.h" // saved password, MAC address
+#include "llwindow.h"
+#include "imageids.h"
+#include "message.h"
+#include "v3math.h"
+
+#include "llagent.h"
+#include "llagentcamera.h"
+#include "llagentpicksinfo.h"
+#include "llagentwearables.h"
+#include "llagentpilot.h"
+#include "llfloateravatarpicker.h"
+#include "llcallbacklist.h"
+#include "llcallingcard.h"
+#include "llconsole.h"
+#include "llcontainerview.h"
+#include "lldebugview.h"
+#include "lldrawable.h"
+#include "lleventnotifier.h"
+#include "llface.h"
+#include "llfeaturemanager.h"
+//#include "llfirstuse.h"
+#include "llfloaterhud.h"
+#include "llfloaterland.h"
+#include "llfloaterpreference.h"
+#include "llfloatertopobjects.h"
+#include "llfloaterworldmap.h"
+#include "llgesturemgr.h"
+#include "llgroupmgr.h"
+#include "llhudeffecttrail.h"
+#include "llhudmanager.h"
+#include "llhttpclient.h"
+#include "llimagebmp.h"
+#include "llinventorybridge.h"
+#include "llinventorymodel.h"
+#include "llinventorymodelbackgroundfetch.h"
+#include "llkeyboard.h"
+#include "llloginhandler.h" // gLoginHandler, SLURL support
+#include "lllogininstance.h" // Host the login module.
+#include "llpanellogin.h"
+#include "llmutelist.h"
+#include "llavatarpropertiesprocessor.h"
+#include "llpanelclassified.h"
+#include "llpanelpick.h"
+#include "llpanelgrouplandmoney.h"
+#include "llpanelgroupnotices.h"
+#include "llpreview.h"
+#include "llpreviewscript.h"
+#include "llproductinforequest.h"
+#include "llsecondlifeurls.h"
+#include "llselectmgr.h"
+#include "llsky.h"
+#include "llsidetray.h"
+#include "llstatview.h"
+#include "llstatusbar.h" // sendMoneyBalanceRequest(), owns L$ balance
+#include "llsurface.h"
+#include "lltexturecache.h"
+#include "lltexturefetch.h"
+#include "lltoolmgr.h"
+#include "lltrans.h"
+#include "llui.h"
+#include "llurldispatcher.h"
+#include "llurlentry.h"
+#include "llslurl.h"
+#include "llurlhistory.h"
+#include "llurlwhitelist.h"
+#include "llvieweraudio.h"
+#include "llviewerassetstorage.h"
+#include "llviewercamera.h"
+#include "llviewerdisplay.h"
+#include "llviewergenericmessage.h"
+#include "llviewergesture.h"
+#include "llviewertexturelist.h"
+#include "llviewermedia.h"
+#include "llviewermenu.h"
+#include "llviewermessage.h"
+#include "llviewernetwork.h"
+#include "llviewerobjectlist.h"
+#include "llviewerparcelmedia.h"
+#include "llviewerparcelmgr.h"
+#include "llviewerregion.h"
+#include "llviewerstats.h"
+#include "llviewerthrottle.h"
+#include "llviewerwindow.h"
+#include "llvoavatar.h"
+#include "llvoavatarself.h"
+#include "llvoclouds.h"
+#include "llweb.h"
+#include "llworld.h"
+#include "llworldmapmessage.h"
+#include "llxfermanager.h"
+#include "pipeline.h"
+#include "llappviewer.h"
+#include "llfasttimerview.h"
+#include "llfloatermap.h"
+#include "llweb.h"
+#include "llvoiceclient.h"
+#include "llnamelistctrl.h"
+#include "llnamebox.h"
+#include "llnameeditor.h"
+#include "llpostprocess.h"
+#include "llwlparammanager.h"
+#include "llwaterparammanager.h"
+#include "llagentlanguage.h"
+#include "llwearable.h"
+#include "llinventorybridge.h"
+#include "llappearancemgr.h"
+#include "llavatariconctrl.h"
+#include "llvoicechannel.h"
+
+#include "lllogin.h"
+#include "llevents.h"
+#include "llstartuplistener.h"
+
+#if LL_WINDOWS
+#include "lldxhardware.h"
+#endif
+
+//
+// exported globals
+//
+bool gAgentMovementCompleted = false;
+S32 gMaxAgentGroups;
+
+std::string SCREEN_HOME_FILENAME = "screen_home.bmp";
+std::string SCREEN_LAST_FILENAME = "screen_last.bmp";
+
+LLPointer<LLViewerTexture> gStartTexture;
+
+//
+// Imported globals
+//
+extern S32 gStartImageWidth;
+extern S32 gStartImageHeight;
+
+//
+// local globals
+//
+static bool gGotUseCircuitCodeAck = false;
+static std::string sInitialOutfit;
+static std::string sInitialOutfitGender; // "male" or "female"
+static boost::signals2::connection sWearablesLoadedCon;
+
+static bool gUseCircuitCallbackCalled = false;
+
+EStartupState LLStartUp::gStartupState = STATE_FIRST;
+LLSLURL LLStartUp::sStartSLURL;
+
+static LLPointer<LLCredential> gUserCredential;
+static std::string gDisplayName;
+static BOOL gRememberPassword = TRUE;
+
+static U64 gFirstSimHandle = 0;
+static LLHost gFirstSim;
+static std::string gFirstSimSeedCap;
+static LLVector3 gAgentStartLookAt(1.0f, 0.f, 0.f);
+static std::string gAgentStartLocation = "safe";
+static bool mLoginStatePastUI = false;
+
+
+boost::scoped_ptr<LLEventPump> LLStartUp::sStateWatcher(new LLEventStream("StartupState"));
+boost::scoped_ptr<LLStartupListener> LLStartUp::sListener(new LLStartupListener());
+
+//
+// local function declaration
+//
+
+void login_show();
+void login_callback(S32 option, void* userdata);
+void show_first_run_dialog();
+bool first_run_dialog_callback(const LLSD& notification, const LLSD& response);
+void set_startup_status(const F32 frac, const std::string& string, const std::string& msg);
+bool login_alert_status(const LLSD& notification, const LLSD& response);
+void login_packet_failed(void**, S32 result);
+void use_circuit_callback(void**, S32 result);
+void register_viewer_callbacks(LLMessageSystem* msg);
+void asset_callback_nothing(LLVFS*, const LLUUID&, LLAssetType::EType, void*, S32);
+bool callback_choose_gender(const LLSD& notification, const LLSD& response);
+void init_start_screen(S32 location_id);
+void release_start_screen();
+void reset_login();
+LLSD transform_cert_args(LLPointer<LLCertificate> cert);
+void general_cert_done(const LLSD& notification, const LLSD& response);
+void trust_cert_done(const LLSD& notification, const LLSD& response);
+void apply_udp_blacklist(const std::string& csv);
+bool process_login_success_response();
+void transition_back_to_login_panel(const std::string& emsg);
+
+void callback_cache_name(const LLUUID& id, const std::string& full_name, bool is_group)
+{
+ LLNameBox::refreshAll(id, full_name, is_group);
+ LLNameEditor::refreshAll(id, full_name, is_group);
+
+ // TODO: Actually be intelligent about the refresh.
+ // For now, just brute force refresh the dialogs.
+ dialog_refresh_all();
+}
+
+//
+// exported functionality
+//
+
+//
+// local classes
+//
+
+namespace
+{
+ class LLNullHTTPSender : public LLHTTPSender
+ {
+ virtual void send(const LLHost& host,
+ const std::string& message, const LLSD& body,
+ LLHTTPClient::ResponderPtr response) const
+ {
+ LL_WARNS("AppInit") << " attemped to send " << message << " to " << host
+ << " with null sender" << LL_ENDL;
+ }
+ };
+}
+
+void update_texture_fetch()
+{
+ LLAppViewer::getTextureCache()->update(1); // unpauses the texture cache thread
+ LLAppViewer::getImageDecodeThread()->update(1); // unpauses the image thread
+ LLAppViewer::getTextureFetch()->update(1); // unpauses the texture fetch thread
+ gTextureList.updateImages(0.10f);
+}
+
+// Returns false to skip other idle processing. Should only return
+// true when all initialization done.
+bool idle_startup()
+{
+ LLMemType mt1(LLMemType::MTYPE_STARTUP);
+
+ const F32 PRECACHING_DELAY = gSavedSettings.getF32("PrecachingDelay");
+ static LLTimer timeout;
+ static S32 timeout_count = 0;
+
+ static LLTimer login_time;
+
+ // until this is encapsulated, this little hack for the
+ // auth/transform loop will do.
+ static F32 progress = 0.10f;
+
+ static std::string auth_desc;
+ static std::string auth_message;
+
+ static LLVector3 initial_sun_direction(1.f, 0.f, 0.f);
+ static LLVector3 agent_start_position_region(10.f, 10.f, 10.f); // default for when no space server
+
+ // last location by default
+ static S32 agent_location_id = START_LOCATION_ID_LAST;
+ static S32 location_which = START_LOCATION_ID_LAST;
+
+ static bool show_connect_box = true;
+
+ //static bool stipend_since_login = false;
+
+ // HACK: These are things from the main loop that usually aren't done
+ // until initialization is complete, but need to be done here for things
+ // to work.
+ gIdleCallbacks.callFunctions();
+ gViewerWindow->updateUI();
+ LLMortician::updateClass();
+
+ const std::string delims (" ");
+ std::string system;
+ int begIdx, endIdx;
+ std::string osString = LLAppViewer::instance()->getOSInfo().getOSStringSimple();
+
+ begIdx = osString.find_first_not_of (delims);
+ endIdx = osString.find_first_of (delims, begIdx);
+ system = osString.substr (begIdx, endIdx - begIdx);
+ system += "Locale";
+
+ LLStringUtil::setLocale (LLTrans::getString(system));
+
+ if (!gNoRender)
+ {
+ //note: Removing this line will cause incorrect button size in the login screen. -- bao.
+ gTextureList.updateImages(0.01f) ;
+ }
+
+ if ( STATE_FIRST == LLStartUp::getStartupState() )
+ {
+ gViewerWindow->showCursor();
+ gViewerWindow->getWindow()->setCursor(UI_CURSOR_WAIT);
+
+ /////////////////////////////////////////////////
+ //
+ // Initialize stuff that doesn't need data from simulators
+ //
+
+ if (LLFeatureManager::getInstance()->isSafe())
+ {
+ LLNotificationsUtil::add("DisplaySetToSafe");
+ }
+ else if ((gSavedSettings.getS32("LastFeatureVersion") < LLFeatureManager::getInstance()->getVersion()) &&
+ (gSavedSettings.getS32("LastFeatureVersion") != 0))
+ {
+ LLNotificationsUtil::add("DisplaySetToRecommended");
+ }
+ else if ((gSavedSettings.getS32("LastGPUClass") != LLFeatureManager::getInstance()->getGPUClass()) &&
+ (gSavedSettings.getS32("LastGPUClass") != -1))
+ {
+ LLNotificationsUtil::add("DisplaySetToRecommended");
+ }
+ else if (!gViewerWindow->getInitAlert().empty())
+ {
+ LLNotificationsUtil::add(gViewerWindow->getInitAlert());
+ }
+
+ gSavedSettings.setS32("LastFeatureVersion", LLFeatureManager::getInstance()->getVersion());
+ gSavedSettings.setS32("LastGPUClass", LLFeatureManager::getInstance()->getGPUClass());
+
+ // load dynamic GPU/feature tables from website (S3)
+ LLFeatureManager::getInstance()->fetchHTTPTables();
+
+ std::string xml_file = LLUI::locateSkin("xui_version.xml");
+ LLXMLNodePtr root;
+ bool xml_ok = false;
+ if (LLXMLNode::parseFile(xml_file, root, NULL))
+ {
+ if( (root->hasName("xui_version") ) )
+ {
+ std::string value = root->getValue();
+ F32 version = 0.0f;
+ LLStringUtil::convertToF32(value, version);
+ if (version >= 1.0f)
+ {
+ xml_ok = true;
+ }
+ }
+ }
+ if (!xml_ok)
+ {
+ // If XML is bad, there's a good possibility that notifications.xml is ALSO bad.
+ // If that's so, then we'll get a fatal error on attempting to load it,
+ // which will display a nontranslatable error message that says so.
+ // Otherwise, we'll display a reasonable error message that IS translatable.
+ LLAppViewer::instance()->earlyExit("BadInstallation");
+ }
+ //
+ // Statistics stuff
+ //
+
+ // Load autopilot and stats stuff
+ gAgentPilot.load();
+
+ //gErrorStream.setTime(gSavedSettings.getBOOL("LogTimestamps"));
+
+ // Load the throttle settings
+ gViewerThrottle.load();
+
+ if (ll_init_ares() == NULL || !gAres->isInitialized())
+ {
+ std::string diagnostic = "Could not start address resolution system";
+ LL_WARNS("AppInit") << diagnostic << LL_ENDL;
+ LLAppViewer::instance()->earlyExit("LoginFailedNoNetwork", LLSD().with("DIAGNOSTIC", diagnostic));
+ }
+
+ //
+ // Initialize messaging system
+ //
+ LL_DEBUGS("AppInit") << "Initializing messaging system..." << LL_ENDL;
+
+ std::string message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"message_template.msg");
+
+ LLFILE* found_template = NULL;
+ found_template = LLFile::fopen(message_template_path, "r"); /* Flawfinder: ignore */
+
+ #if LL_WINDOWS
+ // On the windows dev builds, unpackaged, the message_template.msg
+ // file will be located in:
+ // build-vc**/newview/<config>/app_settings
+ if (!found_template)
+ {
+ message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_EXECUTABLE, "app_settings", "message_template.msg");
+ found_template = LLFile::fopen(message_template_path.c_str(), "r"); /* Flawfinder: ignore */
+ }
+ #elif LL_DARWIN
+ // On Mac dev builds, message_template.msg lives in:
+ // indra/build-*/newview/<config>/Second Life/Contents/Resources/app_settings
+ if (!found_template)
+ {
+ message_template_path =
+ gDirUtilp->getExpandedFilename(LL_PATH_EXECUTABLE,
+ "../Resources/app_settings",
+ "message_template.msg");
+ found_template = LLFile::fopen(message_template_path.c_str(), "r"); /* Flawfinder: ignore */
+ }
+ #endif
+
+ if (found_template)
+ {
+ fclose(found_template);
+
+ U32 port = gSavedSettings.getU32("UserConnectionPort");
+
+ if ((NET_USE_OS_ASSIGNED_PORT == port) && // if nothing specified on command line (-port)
+ (gSavedSettings.getBOOL("ConnectionPortEnabled")))
+ {
+ port = gSavedSettings.getU32("ConnectionPort");
+ }
+
+ LLHTTPSender::setDefaultSender(new LLNullHTTPSender());
+
+ // TODO parameterize
+ const F32 circuit_heartbeat_interval = 5;
+ const F32 circuit_timeout = 100;
+
+ const LLUseCircuitCodeResponder* responder = NULL;
+ bool failure_is_fatal = true;
+
+ if(!start_messaging_system(
+ message_template_path,
+ port,
+ LLVersionInfo::getMajor(),
+ LLVersionInfo::getMinor(),
+ LLVersionInfo::getPatch(),
+ FALSE,
+ std::string(),
+ responder,
+ failure_is_fatal,
+ circuit_heartbeat_interval,
+ circuit_timeout))
+ {
+ std::string diagnostic = llformat(" Error: %d", gMessageSystem->getErrorCode());
+ LL_WARNS("AppInit") << diagnostic << LL_ENDL;
+ LLAppViewer::instance()->earlyExit("LoginFailedNoNetwork", LLSD().with("DIAGNOSTIC", diagnostic));
+ }
+
+ #if LL_WINDOWS
+ // On the windows dev builds, unpackaged, the message.xml file will
+ // be located in indra/build-vc**/newview/<config>/app_settings.
+ std::string message_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"message.xml");
+
+ if (!LLFile::isfile(message_path.c_str()))
+ {
+ LLMessageConfig::initClass("viewer", gDirUtilp->getExpandedFilename(LL_PATH_EXECUTABLE, "app_settings", ""));
+ }
+ else
+ {
+ LLMessageConfig::initClass("viewer", gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
+ }
+ #else
+ LLMessageConfig::initClass("viewer", gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
+ #endif
+
+ }
+ else
+ {
+ LLAppViewer::instance()->earlyExit("MessageTemplateNotFound", LLSD().with("PATH", message_template_path));
+ }
+
+ if(gMessageSystem && gMessageSystem->isOK())
+ {
+ // Initialize all of the callbacks in case of bad message
+ // system data
+ LLMessageSystem* msg = gMessageSystem;
+ msg->setExceptionFunc(MX_UNREGISTERED_MESSAGE,
+ invalid_message_callback,
+ NULL);
+ msg->setExceptionFunc(MX_PACKET_TOO_SHORT,
+ invalid_message_callback,
+ NULL);
+
+ // running off end of a packet is now valid in the case
+ // when a reader has a newer message template than
+ // the sender
+ /*msg->setExceptionFunc(MX_RAN_OFF_END_OF_PACKET,
+ invalid_message_callback,
+ NULL);*/
+ msg->setExceptionFunc(MX_WROTE_PAST_BUFFER_SIZE,
+ invalid_message_callback,
+ NULL);
+
+ if (gSavedSettings.getBOOL("LogMessages"))
+ {
+ LL_DEBUGS("AppInit") << "Message logging activated!" << LL_ENDL;
+ msg->startLogging();
+ }
+
+ // start the xfer system. by default, choke the downloads
+ // a lot...
+ const S32 VIEWER_MAX_XFER = 3;
+ start_xfer_manager(gVFS);
+ gXferManager->setMaxIncomingXfers(VIEWER_MAX_XFER);
+ F32 xfer_throttle_bps = gSavedSettings.getF32("XferThrottle");
+ if (xfer_throttle_bps > 1.f)
+ {
+ gXferManager->setUseAckThrottling(TRUE);
+ gXferManager->setAckThrottleBPS(xfer_throttle_bps);
+ }
+ gAssetStorage = new LLViewerAssetStorage(msg, gXferManager, gVFS, gStaticVFS);
+
+
+ F32 dropPercent = gSavedSettings.getF32("PacketDropPercentage");
+ msg->mPacketRing.setDropPercentage(dropPercent);
+
+ F32 inBandwidth = gSavedSettings.getF32("InBandwidth");
+ F32 outBandwidth = gSavedSettings.getF32("OutBandwidth");
+ if (inBandwidth != 0.f)
+ {
+ LL_DEBUGS("AppInit") << "Setting packetring incoming bandwidth to " << inBandwidth << LL_ENDL;
+ msg->mPacketRing.setUseInThrottle(TRUE);
+ msg->mPacketRing.setInBandwidth(inBandwidth);
+ }
+ if (outBandwidth != 0.f)
+ {
+ LL_DEBUGS("AppInit") << "Setting packetring outgoing bandwidth to " << outBandwidth << LL_ENDL;
+ msg->mPacketRing.setUseOutThrottle(TRUE);
+ msg->mPacketRing.setOutBandwidth(outBandwidth);
+ }
+ }
+
+ LL_INFOS("AppInit") << "Message System Initialized." << LL_ENDL;
+
+ //-------------------------------------------------
+ // Init audio, which may be needed for prefs dialog
+ // or audio cues in connection UI.
+ //-------------------------------------------------
+
+ if (FALSE == gSavedSettings.getBOOL("NoAudio"))
+ {
+ gAudiop = NULL;
+
+#ifdef LL_OPENAL
+ if (!gAudiop
+#if !LL_WINDOWS
+ && NULL == getenv("LL_BAD_OPENAL_DRIVER")
+#endif // !LL_WINDOWS
+ )
+ {
+ gAudiop = (LLAudioEngine *) new LLAudioEngine_OpenAL();
+ }
+#endif
+
+#ifdef LL_FMOD
+ if (!gAudiop
+#if !LL_WINDOWS
+ && NULL == getenv("LL_BAD_FMOD_DRIVER")
+#endif // !LL_WINDOWS
+ )
+ {
+ gAudiop = (LLAudioEngine *) new LLAudioEngine_FMOD();
+ }
+#endif
+
+ if (gAudiop)
+ {
+#if LL_WINDOWS
+ // FMOD on Windows needs the window handle to stop playing audio
+ // when window is minimized. JC
+ void* window_handle = (HWND)gViewerWindow->getPlatformWindow();
+#else
+ void* window_handle = NULL;
+#endif
+ bool init = gAudiop->init(kAUDIO_NUM_SOURCES, window_handle);
+ if(init)
+ {
+ gAudiop->setMuted(TRUE);
+ }
+ else
+ {
+ LL_WARNS("AppInit") << "Unable to initialize audio engine" << LL_ENDL;
+ delete gAudiop;
+ gAudiop = NULL;
+ }
+
+ if (gAudiop)
+ {
+ // if the audio engine hasn't set up its own preferred handler for streaming audio then set up the generic streaming audio implementation which uses media plugins
+ if (NULL == gAudiop->getStreamingAudioImpl())
+ {
+ LL_INFOS("AppInit") << "Using media plugins to render streaming audio" << LL_ENDL;
+ gAudiop->setStreamingAudioImpl(new LLStreamingAudio_MediaPlugins());
+ }
+ }
+ }
+ }
+
+ LL_INFOS("AppInit") << "Audio Engine Initialized." << LL_ENDL;
+
+ if (LLTimer::knownBadTimer())
+ {
+ LL_WARNS("AppInit") << "Unreliable timers detected (may be bad PCI chipset)!!" << LL_ENDL;
+ }
+
+ //
+ // Log on to system
+ //
+ if (gUserCredential.isNull())
+ {
+ gUserCredential = gLoginHandler.initializeLoginInfo();
+ }
+ if (gUserCredential.isNull())
+ {
+ show_connect_box = TRUE;
+ }
+ else if (gSavedSettings.getBOOL("AutoLogin"))
+ {
+ gRememberPassword = TRUE;
+ gSavedSettings.setBOOL("RememberPassword", TRUE);
+ show_connect_box = false;
+ }
+ else
+ {
+ gRememberPassword = gSavedSettings.getBOOL("RememberPassword");
+ show_connect_box = TRUE;
+ }
+ // Go to the next startup state
+ LLStartUp::setStartupState( STATE_BROWSER_INIT );
+ return FALSE;
+ }
+
+
+ if (STATE_BROWSER_INIT == LLStartUp::getStartupState())
+ {
+ LL_DEBUGS("AppInit") << "STATE_BROWSER_INIT" << LL_ENDL;
+ std::string msg = LLTrans::getString("LoginInitializingBrowser");
+ set_startup_status(0.03f, msg.c_str(), gAgent.mMOTD.c_str());
+ display_startup();
+ // LLViewerMedia::initBrowser();
+ LLStartUp::setStartupState( STATE_LOGIN_SHOW );
+ return FALSE;
+ }
+
+
+ if (STATE_LOGIN_SHOW == LLStartUp::getStartupState())
+ {
+ LL_DEBUGS("AppInit") << "Initializing Window" << LL_ENDL;
+
+ // if we've gone backwards in the login state machine, to this state where we show the UI
+ // AND the debug setting to exit in this case is true, then go ahead and bail quickly
+ if ( mLoginStatePastUI && gSavedSettings.getBOOL("QuitOnLoginActivated") )
+ {
+ // no requirement for notification here - just exit
+ LLAppViewer::instance()->earlyExitNoNotify();
+ }
+
+ gViewerWindow->getWindow()->setCursor(UI_CURSOR_ARROW);
+
+ timeout_count = 0;
+
+ if (show_connect_box)
+ {
+ // Load all the name information out of the login view
+ // NOTE: Hits "Attempted getFields with no login view shown" warning, since we don't
+ // show the login view until login_show() is called below.
+ if (gUserCredential.isNull())
+ {
+ gUserCredential = gLoginHandler.initializeLoginInfo();
+ }
+ if (gNoRender)
+ {
+ LL_ERRS("AppInit") << "Need to autologin or use command line with norender!" << LL_ENDL;
+ }
+ // Make sure the process dialog doesn't hide things
+ gViewerWindow->setShowProgress(FALSE);
+
+ initialize_edit_menu();
+
+ // Show the login dialog
+ login_show();
+ // connect dialog is already shown, so fill in the names
+ if (gUserCredential.notNull())
+ {
+ LLPanelLogin::setFields( gUserCredential, gRememberPassword);
+ }
+ LLPanelLogin::giveFocus();
+
+ gSavedSettings.setBOOL("FirstRunThisInstall", FALSE);
+
+ LLStartUp::setStartupState( STATE_LOGIN_WAIT ); // Wait for user input
+ }
+ else
+ {
+ // skip directly to message template verification
+ LLStartUp::setStartupState( STATE_LOGIN_CLEANUP );
+ }
+
+ // *NOTE: This is where LLViewerParcelMgr::getInstance() used to get allocated before becoming LLViewerParcelMgr::getInstance().
+
+ // *NOTE: This is where gHUDManager used to bet allocated before becoming LLHUDManager::getInstance().
+
+ // *NOTE: This is where gMuteList used to get allocated before becoming LLMuteList::getInstance().
+
+ // Login screen needs menus for preferences, but we can enter
+ // this startup phase more than once.
+ if (gLoginMenuBarView == NULL)
+ {
+ init_menus();
+ }
+
+ gViewerWindow->setNormalControlsVisible( FALSE );
+ gLoginMenuBarView->setVisible( TRUE );
+ gLoginMenuBarView->setEnabled( TRUE );
+ show_debug_menus();
+
+ // Hide the splash screen
+ LLSplashScreen::hide();
+
+ // Push our window frontmost
+ gViewerWindow->getWindow()->show();
+ display_startup();
+
+ // DEV-16927. The following code removes errant keystrokes that happen while the window is being
+ // first made visible.
+#ifdef _WIN32
+ MSG msg;
+ while( PeekMessage( &msg, /*All hWnds owned by this thread */ NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE ) );
+#endif
+ timeout.reset();
+ return FALSE;
+ }
+
+ if (STATE_LOGIN_WAIT == LLStartUp::getStartupState())
+ {
+ // when we get to this state, we've already been past the login UI
+ // (possiblely automatically) - flag this so we can test in the
+ // STATE_LOGIN_SHOW state if we've gone backwards
+ mLoginStatePastUI = true;
+
+ // Don't do anything. Wait for the login view to call the login_callback,
+ // which will push us to the next state.
+
+ // Sleep so we don't spin the CPU
+ ms_sleep(1);
+ return FALSE;
+ }
+
+ if (STATE_LOGIN_CLEANUP == LLStartUp::getStartupState())
+ {
+ //reset the values that could have come in from a slurl
+ // DEV-42215: Make sure they're not empty -- gUserCredential
+ // might already have been set from gSavedSettings, and it's too bad
+ // to overwrite valid values with empty strings.
+
+ if (show_connect_box)
+ {
+ // TODO if not use viewer auth
+ // Load all the name information out of the login view
+ LLPanelLogin::getFields(gUserCredential, gRememberPassword);
+ // end TODO
+
+ // HACK: Try to make not jump on login
+ gKeyboard->resetKeys();
+ }
+
+ // when we get to this state, we've already been past the login UI
+ // (possiblely automatically) - flag this so we can test in the
+ // STATE_LOGIN_SHOW state if we've gone backwards
+ mLoginStatePastUI = true;
+
+ // save the credentials
+ std::string userid = "unknown";
+ if(gUserCredential.notNull())
+ {
+ userid = gUserCredential->userID();
+ gSecAPIHandler->saveCredential(gUserCredential, gRememberPassword);
+ }
+ gSavedSettings.setBOOL("RememberPassword", gRememberPassword);
+ LL_INFOS("AppInit") << "Attempting login as: " << userid << LL_ENDL;
+ gDebugInfo["LoginName"] = userid;
+
+ // create necessary directories
+ // *FIX: these mkdir's should error check
+ gDirUtilp->setLindenUserDir(userid);
+ LLFile::mkdir(gDirUtilp->getLindenUserDir());
+
+ // Set PerAccountSettingsFile to the default value.
+ std::string per_account_settings_file = LLAppViewer::instance()->getSettingsFilename("Default", "PerAccount");
+ gSavedSettings.setString("PerAccountSettingsFile",
+ gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT,
+ LLAppViewer::instance()->getSettingsFilename("Default", "PerAccount")));
+
+ // Note: can't store warnings files per account because some come up before login
+
+ // Overwrite default user settings with user settings
+ LLAppViewer::instance()->loadSettingsFromDirectory("Account");
+
+ // Need to set the LastLogoff time here if we don't have one. LastLogoff is used for "Recent Items" calculation
+ // and startup time is close enough if we don't have a real value.
+ if (gSavedPerAccountSettings.getU32("LastLogoff") == 0)
+ {
+ gSavedPerAccountSettings.setU32("LastLogoff", time_corrected());
+ }
+
+ //Default the path if one isn't set.
+ // *NOTE: unable to check variable differ from "InstantMessageLogPath" because it was
+ // provided in pre 2.0 viewer. See EXT-6661
+ if (gSavedPerAccountSettings.getString("InstantMessageLogPath").empty())
+ {
+ gDirUtilp->setChatLogsDir(gDirUtilp->getOSUserAppDir());
+ gSavedPerAccountSettings.setString("InstantMessageLogPath", gDirUtilp->getChatLogsDir());
+ }
+ else
+ {
+ gDirUtilp->setChatLogsDir(gSavedPerAccountSettings.getString("InstantMessageLogPath"));
+ }
+ gDirUtilp->setPerAccountChatLogsDir(userid);
+
+ LLFile::mkdir(gDirUtilp->getChatLogsDir());
+ LLFile::mkdir(gDirUtilp->getPerAccountChatLogsDir());
+
+
+ //good a place as any to create user windlight directories
+ std::string user_windlight_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight", ""));
+ LLFile::mkdir(user_windlight_path_name.c_str());
+
+ std::string user_windlight_skies_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/skies", ""));
+ LLFile::mkdir(user_windlight_skies_path_name.c_str());
+
+ std::string user_windlight_water_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/water", ""));
+ LLFile::mkdir(user_windlight_water_path_name.c_str());
+
+ std::string user_windlight_days_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/days", ""));
+ LLFile::mkdir(user_windlight_days_path_name.c_str());
+
+
+ if (show_connect_box)
+ {
+ LLSLURL slurl;
+ LLPanelLogin::closePanel();
+ }
+
+
+ // Load URL History File
+ LLURLHistory::loadFile("url_history.xml");
+ // Load location history
+ LLLocationHistory::getInstance()->load();
+
+ // Load Avatars icons cache
+ LLAvatarIconIDCache::getInstance()->load();
+
+ // Load media plugin cookies
+ LLViewerMedia::loadCookieFile();
+
+ //-------------------------------------------------
+ // Handle startup progress screen
+ //-------------------------------------------------
+
+ // on startup the user can request to go to their home,
+ // their last location, or some URL "-url //sim/x/y[/z]"
+ // All accounts have both a home and a last location, and we don't support
+ // more locations than that. Choose the appropriate one. JC
+ switch (LLStartUp::getStartSLURL().getType())
+ {
+ case LLSLURL::LOCATION:
+ agent_location_id = START_LOCATION_ID_URL;
+ location_which = START_LOCATION_ID_LAST;
+ break;
+ case LLSLURL::LAST_LOCATION:
+ agent_location_id = START_LOCATION_ID_LAST;
+ location_which = START_LOCATION_ID_LAST;
+ break;
+ default:
+ agent_location_id = START_LOCATION_ID_HOME;
+ location_which = START_LOCATION_ID_HOME;
+ break;
+ }
+
+ gViewerWindow->getWindow()->setCursor(UI_CURSOR_WAIT);
+
+ if (!gNoRender)
+ {
+ init_start_screen(agent_location_id);
+ }
+
+ // Display the startup progress bar.
+ gViewerWindow->setShowProgress(TRUE);
+ gViewerWindow->setProgressCancelButtonVisible(TRUE, LLTrans::getString("Quit"));
+
+ // Poke the VFS, which could potentially block for a while if
+ // Windows XP is acting up
+ set_startup_status(0.07f, LLTrans::getString("LoginVerifyingCache"), LLStringUtil::null);
+ display_startup();
+
+ gVFS->pokeFiles();
+
+ LLStartUp::setStartupState( STATE_LOGIN_AUTH_INIT );
+
+ return FALSE;
+ }
+
+ if(STATE_LOGIN_AUTH_INIT == LLStartUp::getStartupState())
+ {
+ gDebugInfo["GridName"] = LLGridManager::getInstance()->getGridLabel();
+
+ // Update progress status and the display loop.
+ auth_desc = LLTrans::getString("LoginInProgress");
+ set_startup_status(progress, auth_desc, auth_message);
+ progress += 0.02f;
+ display_startup();
+
+ // Setting initial values...
+ LLLoginInstance* login = LLLoginInstance::getInstance();
+ login->setNotificationsInterface(LLNotifications::getInstance());
+ if(gNoRender)
+ {
+ // HACK, skip optional updates if you're running drones
+ login->setSkipOptionalUpdate(true);
+ }
+
+ login->setSerialNumber(LLAppViewer::instance()->getSerialNumber());
+ login->setLastExecEvent(gLastExecEvent);
+ login->setUpdaterLauncher(boost::bind(&LLAppViewer::launchUpdater, LLAppViewer::instance()));
+
+ // This call to LLLoginInstance::connect() starts the
+ // authentication process.
+ login->connect(gUserCredential);
+
+ LLStartUp::setStartupState( STATE_LOGIN_CURL_UNSTUCK );
+ return FALSE;
+ }
+
+ if(STATE_LOGIN_CURL_UNSTUCK == LLStartUp::getStartupState())
+ {
+ // If we get here we have gotten past the potential stall
+ // in curl, so take "may appear frozen" out of progress bar. JC
+ auth_desc = LLTrans::getString("LoginInProgressNoFrozen");
+ set_startup_status(progress, auth_desc, auth_message);
+
+ LLStartUp::setStartupState( STATE_LOGIN_PROCESS_RESPONSE );
+ return FALSE;
+ }
+
+ if(STATE_LOGIN_PROCESS_RESPONSE == LLStartUp::getStartupState())
+ {
+ std::ostringstream emsg;
+ emsg << LLTrans::getString("LoginFailed") << "\n";
+ if(LLLoginInstance::getInstance()->authFailure())
+ {
+ LL_INFOS("LLStartup") << "Login failed, LLLoginInstance::getResponse(): "
+ << LLLoginInstance::getInstance()->getResponse() << LL_ENDL;
+ LLSD response = LLLoginInstance::getInstance()->getResponse();
+ // Still have error conditions that may need some
+ // sort of handling.
+ std::string reason_response = response["reason"];
+ std::string message_response = response["message"];
+
+ if(!message_response.empty())
+ {
+ // XUI: fix translation for strings returned during login
+ // We need a generic table for translations
+ std::string big_reason = LLAgent::sTeleportErrorMessages[ message_response ];
+ if ( big_reason.size() == 0 )
+ {
+ emsg << message_response;
+ }
+ else
+ {
+ emsg << big_reason;
+ }
+ }
+
+ if(reason_response == "key")
+ {
+ // Couldn't login because user/password is wrong
+ // Clear the credential
+ gUserCredential->clearAuthenticator();
+ }
+
+ if(reason_response == "update"
+ || reason_response == "optional")
+ {
+ // In the case of a needed update, quit.
+ // Its either downloading or declined.
+ // If optional was skipped this case shouldn't
+ // be reached.
+ LLLoginInstance::getInstance()->disconnect();
+ LLAppViewer::instance()->forceQuit();
+ }
+ else
+ {
+ if (reason_response != "tos")
+ {
+ // Don't pop up a notification in the TOS case because
+ // LLFloaterTOS::onCancel() already scolded the user.
+ std::string error_code;
+ if(response.has("errorcode"))
+ {
+ error_code = response["errorcode"].asString();
+ }
+ if ((reason_response == "CURLError") &&
+ (error_code == "SSL_CACERT" || error_code == "SSL_PEER_CERTIFICATE") &&
+ response.has("certificate"))
+ {
+ // This was a certificate error, so grab the certificate
+ // and throw up the appropriate dialog.
+ LLPointer<LLCertificate> certificate = gSecAPIHandler->getCertificate(response["certificate"]);
+ if(certificate)
+ {
+ LLSD args = transform_cert_args(certificate);
+
+ if(error_code == "SSL_CACERT")
+ {
+ // if we are handling an untrusted CA, throw up the dialog
+ // with the 'trust this CA' button.
+ LLNotificationsUtil::add("TrustCertificateError", args, response,
+ trust_cert_done);
+
+ show_connect_box = true;
+ }
+ else
+ {
+ // the certificate exception returns a unique string for each type of exception.
+ // we grab this string via the LLUserAuth object, and use that to grab the localized
+ // string.
+ args["REASON"] = LLTrans::getString(message_response);
+
+ LLNotificationsUtil::add("GeneralCertificateError", args, response,
+ general_cert_done);
+
+ reset_login();
+ gSavedSettings.setBOOL("AutoLogin", FALSE);
+ show_connect_box = true;
+
+ }
+
+ }
+ }
+ else
+ {
+ // This wasn't a certificate error, so throw up the normal
+ // notificatioin message.
+ LLSD args;
+ args["ERROR_MESSAGE"] = emsg.str();
+ LL_INFOS("LLStartup") << "Notification: " << args << LL_ENDL;
+ LLNotificationsUtil::add("ErrorMessage", args, LLSD(), login_alert_done);
+ }
+ }
+ //setup map of datetime strings to codes and slt & local time offset from utc
+ // *TODO: Does this need to be here?
+ LLStringOps::setupDatetimeInfo (false);
+ transition_back_to_login_panel(emsg.str());
+ show_connect_box = true;
+ }
+ }
+ else if(LLLoginInstance::getInstance()->authSuccess())
+ {
+ if(process_login_success_response())
+ {
+ // Pass the user information to the voice chat server interface.
+ LLVoiceClient::getInstance()->userAuthorized(gUserCredential->userID(), gAgentID);
+ // create the default proximal channel
+ LLVoiceChannel::initClass();
+ LLGridManager::getInstance()->setFavorite();
+ LLStartUp::setStartupState( STATE_WORLD_INIT);
+ }
+ else
+ {
+ LLSD args;
+ args["ERROR_MESSAGE"] = emsg.str();
+ LL_INFOS("LLStartup") << "Notification: " << args << LL_ENDL;
+ LLNotificationsUtil::add("ErrorMessage", args, LLSD(), login_alert_done);
+ transition_back_to_login_panel(emsg.str());
+ show_connect_box = true;
+ return FALSE;
+ }
+ }
+ return FALSE;
+ }
+
+ //---------------------------------------------------------------------
+ // World Init
+ //---------------------------------------------------------------------
+ if (STATE_WORLD_INIT == LLStartUp::getStartupState())
+ {
+ set_startup_status(0.30f, LLTrans::getString("LoginInitializingWorld"), gAgent.mMOTD);
+ display_startup();
+ // We should have an agent id by this point.
+ llassert(!(gAgentID == LLUUID::null));
+
+ // Finish agent initialization. (Requires gSavedSettings, builds camera)
+ gAgent.init();
+ gAgentCamera.init();
+ set_underclothes_menu_options();
+
+ // Since we connected, save off the settings so the user doesn't have to
+ // type the name/password again if we crash.
+ gSavedSettings.saveToFile(gSavedSettings.getString("ClientSettingsFile"), TRUE);
+ LLUIColorTable::instance().saveUserSettings();
+
+ //
+ // Initialize classes w/graphics stuff.
+ //
+ gTextureList.doPrefetchImages();
+ LLSurface::initClasses();
+
+ LLFace::initClass();
+
+ LLDrawable::initClass();
+
+ // init the shader managers
+ LLPostProcess::initClass();
+ LLWLParamManager::initClass();
+ LLWaterParamManager::initClass();
+
+ LLViewerObject::initVOClasses();
+
+ // Initialize all our tools. Must be done after saved settings loaded.
+ // NOTE: This also is where gToolMgr used to be instantiated before being turned into a singleton.
+ LLToolMgr::getInstance()->initTools();
+
+ // Pre-load floaters, like the world map, that are slow to spawn
+ // due to XML complexity.
+ gViewerWindow->initWorldUI();
+
+ display_startup();
+
+ // This is where we used to initialize gWorldp. Original comment said:
+ // World initialization must be done after above window init
+
+ // User might have overridden far clip
+ LLWorld::getInstance()->setLandFarClip(gAgentCamera.mDrawDistance);
+
+ // Before we create the first region, we need to set the agent's mOriginGlobal
+ // This is necessary because creating objects before this is set will result in a
+ // bad mPositionAgent cache.
+
+ gAgent.initOriginGlobal(from_region_handle(gFirstSimHandle));
+
+ LLWorld::getInstance()->addRegion(gFirstSimHandle, gFirstSim);
+
+ LLViewerRegion *regionp = LLWorld::getInstance()->getRegionFromHandle(gFirstSimHandle);
+ LL_INFOS("AppInit") << "Adding initial simulator " << regionp->getOriginGlobal() << LL_ENDL;
+
+ regionp->setSeedCapability(gFirstSimSeedCap);
+ LL_DEBUGS("AppInit") << "Waiting for seed grant ...." << LL_ENDL;
+
+ // Set agent's initial region to be the one we just created.
+ gAgent.setRegion(regionp);
+
+ // Set agent's initial position, which will be read by LLVOAvatar when the avatar
+ // object is created. I think this must be done after setting the region. JC
+ gAgent.setPositionAgent(agent_start_position_region);
+
+ display_startup();
+ LLStartUp::setStartupState( STATE_MULTIMEDIA_INIT );
+
+ return FALSE;
+ }
+
+
+ //---------------------------------------------------------------------
+ // Load QuickTime/GStreamer and other multimedia engines, can be slow.
+ // Do it while we're waiting on the network for our seed capability. JC
+ //---------------------------------------------------------------------
+ if (STATE_MULTIMEDIA_INIT == LLStartUp::getStartupState())
+ {
+ LLStartUp::multimediaInit();
+ LLStartUp::setStartupState( STATE_FONT_INIT );
+ return FALSE;
+ }
+
+ // Loading fonts takes several seconds
+ if (STATE_FONT_INIT == LLStartUp::getStartupState())
+ {
+ LLStartUp::fontInit();
+ LLStartUp::setStartupState( STATE_SEED_GRANTED_WAIT );
+ return FALSE;
+ }
+
+ //---------------------------------------------------------------------
+ // Wait for Seed Cap Grant
+ //---------------------------------------------------------------------
+ if(STATE_SEED_GRANTED_WAIT == LLStartUp::getStartupState())
+ {
+ return FALSE;
+ }
+
+
+ //---------------------------------------------------------------------
+ // Seed Capability Granted
+ // no newMessage calls should happen before this point
+ //---------------------------------------------------------------------
+ if (STATE_SEED_CAP_GRANTED == LLStartUp::getStartupState())
+ {
+ update_texture_fetch();
+
+ if ( gViewerWindow != NULL)
+ { // This isn't the first logon attempt, so show the UI
+ gViewerWindow->setNormalControlsVisible( TRUE );
+ }
+ gLoginMenuBarView->setVisible( FALSE );
+ gLoginMenuBarView->setEnabled( FALSE );
+
+ if (!gNoRender)
+ {
+ // direct logging to the debug console's line buffer
+ LLError::logToFixedBuffer(gDebugView->mDebugConsolep);
+
+ // set initial visibility of debug console
+ gDebugView->mDebugConsolep->setVisible(gSavedSettings.getBOOL("ShowDebugConsole"));
+ }
+
+ //
+ // Set message handlers
+ //
+ LL_INFOS("AppInit") << "Initializing communications..." << LL_ENDL;
+
+ // register callbacks for messages. . . do this after initial handshake to make sure that we don't catch any unwanted
+ register_viewer_callbacks(gMessageSystem);
+
+ // Debugging info parameters
+ gMessageSystem->setMaxMessageTime( 0.5f ); // Spam if decoding all msgs takes more than 500 ms
+
+ #ifndef LL_RELEASE_FOR_DOWNLOAD
+ gMessageSystem->setTimeDecodes( TRUE ); // Time the decode of each msg
+ gMessageSystem->setTimeDecodesSpamThreshold( 0.05f ); // Spam if a single msg takes over 50ms to decode
+ #endif
+
+ gXferManager->registerCallbacks(gMessageSystem);
+
+ LLStartUp::initNameCache();
+
+ // update the voice settings *after* gCacheName initialization
+ // so that we can construct voice UI that relies on the name cache
+ LLVoiceClient::getInstance()->updateSettings();
+
+ //gCacheName is required for nearby chat history loading
+ //so I just moved nearby history loading a few states further
+ if (!gNoRender && gSavedPerAccountSettings.getBOOL("LogShowHistory"))
+ {
+ LLNearbyChat* nearby_chat = LLNearbyChat::getInstance();
+ if (nearby_chat) nearby_chat->loadHistory();
+ }
+
+ // *Note: this is where gWorldMap used to be initialized.
+
+ // register null callbacks for audio until the audio system is initialized
+ gMessageSystem->setHandlerFuncFast(_PREHASH_SoundTrigger, null_message_callback, NULL);
+ gMessageSystem->setHandlerFuncFast(_PREHASH_AttachedSound, null_message_callback, NULL);
+
+ //reset statistics
+ LLViewerStats::getInstance()->resetStats();
+
+ display_startup();
+ //
+ // Set up region and surface defaults
+ //
+
+
+ // Sets up the parameters for the first simulator
+
+ LL_DEBUGS("AppInit") << "Initializing camera..." << LL_ENDL;
+ gFrameTime = totalTime();
+ F32 last_time = gFrameTimeSeconds;
+ gFrameTimeSeconds = (S64)(gFrameTime - gStartTime)/SEC_TO_MICROSEC;
+
+ gFrameIntervalSeconds = gFrameTimeSeconds - last_time;
+ if (gFrameIntervalSeconds < 0.f)
+ {
+ gFrameIntervalSeconds = 0.f;
+ }
+
+ // Make sure agent knows correct aspect ratio
+ // FOV limits depend upon aspect ratio so this needs to happen before initializing the FOV below
+ LLViewerCamera::getInstance()->setViewHeightInPixels(gViewerWindow->getWorldViewHeightRaw());
+ LLViewerCamera::getInstance()->setAspect(gViewerWindow->getWorldViewAspectRatio());
+ // Initialize FOV
+ LLViewerCamera::getInstance()->setDefaultFOV(gSavedSettings.getF32("CameraAngle"));
+
+ // Move agent to starting location. The position handed to us by
+ // the space server is in global coordinates, but the agent frame
+ // is in region local coordinates. Therefore, we need to adjust
+ // the coordinates handed to us to fit in the local region.
+
+ gAgent.setPositionAgent(agent_start_position_region);
+ gAgent.resetAxes(gAgentStartLookAt);
+ gAgentCamera.stopCameraAnimation();
+ gAgentCamera.resetCamera();
+
+ // Initialize global class data needed for surfaces (i.e. textures)
+ if (!gNoRender)
+ {
+ LL_DEBUGS("AppInit") << "Initializing sky..." << LL_ENDL;
+ // Initialize all of the viewer object classes for the first time (doing things like texture fetches.
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+
+ gSky.init(initial_sun_direction);
+
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+ }
+
+ LL_DEBUGS("AppInit") << "Decoding images..." << LL_ENDL;
+ // For all images pre-loaded into viewer cache, decode them.
+ // Need to do this AFTER we init the sky
+ const S32 DECODE_TIME_SEC = 2;
+ for (int i = 0; i < DECODE_TIME_SEC; i++)
+ {
+ F32 frac = (F32)i / (F32)DECODE_TIME_SEC;
+ set_startup_status(0.45f + frac*0.1f, LLTrans::getString("LoginDecodingImages"), gAgent.mMOTD);
+ display_startup();
+ gTextureList.decodeAllImages(1.f);
+ }
+ LLStartUp::setStartupState( STATE_WORLD_WAIT );
+
+ // JC - Do this as late as possible to increase likelihood Purify
+ // will run.
+ LLMessageSystem* msg = gMessageSystem;
+ if (!msg->mOurCircuitCode)
+ {
+ LL_WARNS("AppInit") << "Attempting to connect to simulator with a zero circuit code!" << LL_ENDL;
+ }
+
+ gUseCircuitCallbackCalled = false;
+
+ msg->enableCircuit(gFirstSim, TRUE);
+ // now, use the circuit info to tell simulator about us!
+ LL_INFOS("AppInit") << "viewer: UserLoginLocationReply() Enabling " << gFirstSim << " with code " << msg->mOurCircuitCode << LL_ENDL;
+ msg->newMessageFast(_PREHASH_UseCircuitCode);
+ msg->nextBlockFast(_PREHASH_CircuitCode);
+ msg->addU32Fast(_PREHASH_Code, msg->mOurCircuitCode);
+ msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ msg->addUUIDFast(_PREHASH_ID, gAgent.getID());
+ msg->sendReliable(
+ gFirstSim,
+ gSavedSettings.getS32("UseCircuitCodeMaxRetries"),
+ FALSE,
+ gSavedSettings.getF32("UseCircuitCodeTimeout"),
+ use_circuit_callback,
+ NULL);
+
+ timeout.reset();
+
+ return FALSE;
+ }
+
+ //---------------------------------------------------------------------
+ // Agent Send
+ //---------------------------------------------------------------------
+ if(STATE_WORLD_WAIT == LLStartUp::getStartupState())
+ {
+ LL_DEBUGS("AppInit") << "Waiting for simulator ack...." << LL_ENDL;
+ set_startup_status(0.59f, LLTrans::getString("LoginWaitingForRegionHandshake"), gAgent.mMOTD);
+ if(gGotUseCircuitCodeAck)
+ {
+ LLStartUp::setStartupState( STATE_AGENT_SEND );
+ }
+ LLMessageSystem* msg = gMessageSystem;
+ while (msg->checkAllMessages(gFrameCount, gServicePump))
+ {
+ }
+ msg->processAcks();
+ return FALSE;
+ }
+
+ //---------------------------------------------------------------------
+ // Agent Send
+ //---------------------------------------------------------------------
+ if (STATE_AGENT_SEND == LLStartUp::getStartupState())
+ {
+ LL_DEBUGS("AppInit") << "Connecting to region..." << LL_ENDL;
+ set_startup_status(0.60f, LLTrans::getString("LoginConnectingToRegion"), gAgent.mMOTD);
+ // register with the message system so it knows we're
+ // expecting this message
+ LLMessageSystem* msg = gMessageSystem;
+ msg->setHandlerFuncFast(
+ _PREHASH_AgentMovementComplete,
+ process_agent_movement_complete);
+ LLViewerRegion* regionp = gAgent.getRegion();
+ if(regionp)
+ {
+ send_complete_agent_movement(regionp->getHost());
+ gAssetStorage->setUpstream(regionp->getHost());
+ gCacheName->setUpstream(regionp->getHost());
+ msg->newMessageFast(_PREHASH_EconomyDataRequest);
+ gAgent.sendReliableMessage();
+ }
+
+ // Create login effect
+ // But not on first login, because you can't see your avatar then
+ if (!gAgent.isFirstLogin())
+ {
+ LLHUDEffectSpiral *effectp = (LLHUDEffectSpiral *)LLHUDManager::getInstance()->createViewerEffect(LLHUDObject::LL_HUD_EFFECT_POINT, TRUE);
+ effectp->setPositionGlobal(gAgent.getPositionGlobal());
+ effectp->setColor(LLColor4U(gAgent.getEffectColor()));
+ LLHUDManager::getInstance()->sendEffects();
+ }
+
+ LLStartUp::setStartupState( STATE_AGENT_WAIT ); // Go to STATE_AGENT_WAIT
+
+ timeout.reset();
+ return FALSE;
+ }
+
+ //---------------------------------------------------------------------
+ // Agent Wait
+ //---------------------------------------------------------------------
+ if (STATE_AGENT_WAIT == LLStartUp::getStartupState())
+ {
+ LLMessageSystem* msg = gMessageSystem;
+ while (msg->checkAllMessages(gFrameCount, gServicePump))
+ {
+ if (gAgentMovementCompleted)
+ {
+ // Sometimes we have more than one message in the
+ // queue. break out of this loop and continue
+ // processing. If we don't, then this could skip one
+ // or more login steps.
+ break;
+ }
+ else
+ {
+ LL_DEBUGS("AppInit") << "Awaiting AvatarInitComplete, got "
+ << msg->getMessageName() << LL_ENDL;
+ }
+ }
+ msg->processAcks();
+
+ if (gAgentMovementCompleted)
+ {
+ LLStartUp::setStartupState( STATE_INVENTORY_SEND );
+ }
+
+ return FALSE;
+ }
+
+ //---------------------------------------------------------------------
+ // Inventory Send
+ //---------------------------------------------------------------------
+ if (STATE_INVENTORY_SEND == LLStartUp::getStartupState())
+ {
+ // Inform simulator of our language preference
+ LLAgentLanguage::update();
+
+ // unpack thin inventory
+ LLSD response = LLLoginInstance::getInstance()->getResponse();
+ //bool dump_buffer = false;
+
+ LLSD inv_lib_root = response["inventory-lib-root"];
+ if(inv_lib_root.isDefined())
+ {
+ // should only be one
+ LLSD id = inv_lib_root[0]["folder_id"];
+ if(id.isDefined())
+ {
+ gInventory.setLibraryRootFolderID(id.asUUID());
+ }
+ }
+
+ LLSD inv_lib_owner = response["inventory-lib-owner"];
+ if(inv_lib_owner.isDefined())
+ {
+ // should only be one
+ LLSD id = inv_lib_owner[0]["agent_id"];
+ if(id.isDefined())
+ {
+ gInventory.setLibraryOwnerID( LLUUID(id.asUUID()));
+ }
+ }
+
+ LLSD inv_skel_lib = response["inventory-skel-lib"];
+ if(inv_skel_lib.isDefined() && gInventory.getLibraryOwnerID().notNull())
+ {
+ if(!gInventory.loadSkeleton(inv_skel_lib, gInventory.getLibraryOwnerID()))
+ {
+ LL_WARNS("AppInit") << "Problem loading inventory-skel-lib" << LL_ENDL;
+ }
+ }
+
+ LLSD inv_skeleton = response["inventory-skeleton"];
+ if(inv_skeleton.isDefined())
+ {
+ if(!gInventory.loadSkeleton(inv_skeleton, gAgent.getID()))
+ {
+ LL_WARNS("AppInit") << "Problem loading inventory-skel-targets" << LL_ENDL;
+ }
+ }
+
+ LLSD buddy_list = response["buddy-list"];
+ if(buddy_list.isDefined())
+ {
+ LLAvatarTracker::buddy_map_t list;
+ LLUUID agent_id;
+ S32 has_rights = 0, given_rights = 0;
+ for(LLSD::array_const_iterator it = buddy_list.beginArray(),
+ end = buddy_list.endArray(); it != end; ++it)
+ {
+ LLSD buddy_id = (*it)["buddy_id"];
+ if(buddy_id.isDefined())
+ {
+ agent_id = buddy_id.asUUID();
+ }
+
+ LLSD buddy_rights_has = (*it)["buddy_rights_has"];
+ if(buddy_rights_has.isDefined())
+ {
+ has_rights = buddy_rights_has.asInteger();
+ }
+
+ LLSD buddy_rights_given = (*it)["buddy_rights_given"];
+ if(buddy_rights_given.isDefined())
+ {
+ given_rights = buddy_rights_given.asInteger();
+ }
+
+ list[agent_id] = new LLRelationship(given_rights, has_rights, false);
+ }
+ LLAvatarTracker::instance().addBuddyList(list);
+ }
+
+ bool show_hud = false;
+ LLSD tutorial_setting = response["tutorial_setting"];
+ if(tutorial_setting.isDefined())
+ {
+ for(LLSD::array_const_iterator it = tutorial_setting.beginArray(),
+ end = tutorial_setting.endArray(); it != end; ++it)
+ {
+ LLSD tutorial_url = (*it)["tutorial_url"];
+ if(tutorial_url.isDefined())
+ {
+ // Tutorial floater will append language code
+ gSavedSettings.setString("TutorialURL", tutorial_url.asString());
+ }
+
+ // For Viewer 2.0 we are not using the web-based tutorial
+ // If we reverse that decision, put this code back and use
+ // login.cgi to send a different URL with content that matches
+ // the Viewer 2.0 UI.
+ //LLSD use_tutorial = (*it)["use_tutorial"];
+ //if(use_tutorial.asString() == "true")
+ //{
+ // show_hud = true;
+ //}
+ }
+ }
+ // Either we want to show tutorial because this is the first login
+ // to a Linden Help Island or the user quit with the tutorial
+ // visible. JC
+ if (show_hud || gSavedSettings.getBOOL("ShowTutorial"))
+ {
+ LLFloaterReg::showInstance("hud", LLSD(), FALSE);
+ }
+
+ LLSD event_notifications = response["event_notifications"];
+ if(event_notifications.isDefined())
+ {
+ gEventNotifier.load(event_notifications);
+ }
+
+ LLSD classified_categories = response["classified_categories"];
+ if(classified_categories.isDefined())
+ {
+ LLClassifiedInfo::loadCategories(classified_categories);
+ }
+
+ // This method MUST be called before gInventory.findCategoryUUIDForType because of
+ // gInventory.mIsAgentInvUsable is set to true in the gInventory.buildParentChildMap.
+ gInventory.buildParentChildMap();
+
+ //all categories loaded. lets create "My Favorites" category
+ gInventory.findCategoryUUIDForType(LLFolderType::FT_FAVORITE,true);
+
+ // set up callbacks
+ llinfos << "Registering Callbacks" << llendl;
+ LLMessageSystem* msg = gMessageSystem;
+ llinfos << " Inventory" << llendl;
+ LLInventoryModel::registerCallbacks(msg);
+ llinfos << " AvatarTracker" << llendl;
+ LLAvatarTracker::instance().registerCallbacks(msg);
+ llinfos << " Landmark" << llendl;
+ LLLandmark::registerCallbacks(msg);
+
+ // request mute list
+ llinfos << "Requesting Mute List" << llendl;
+ LLMuteList::getInstance()->requestFromServer(gAgent.getID());
+
+ // Get L$ and ownership credit information
+ llinfos << "Requesting Money Balance" << llendl;
+ LLStatusBar::sendMoneyBalanceRequest();
+
+ // request all group information
+ llinfos << "Requesting Agent Data" << llendl;
+ gAgent.sendAgentDataUpdateRequest();
+
+ // Create the inventory views
+ llinfos << "Creating Inventory Views" << llendl;
+ LLFloaterReg::getInstance("inventory");
+
+ LLStartUp::setStartupState( STATE_MISC );
+ return FALSE;
+ }
+
+
+ //---------------------------------------------------------------------
+ // Misc
+ //---------------------------------------------------------------------
+ if (STATE_MISC == LLStartUp::getStartupState())
+ {
+ // We have a region, and just did a big inventory download.
+ // We can estimate the user's connection speed, and set their
+ // max bandwidth accordingly. JC
+ if (gSavedSettings.getBOOL("FirstLoginThisInstall"))
+ {
+ // This is actually a pessimistic computation, because TCP may not have enough
+ // time to ramp up on the (small) default inventory file to truly measure max
+ // bandwidth. JC
+ F64 rate_bps = LLLoginInstance::getInstance()->getLastTransferRateBPS();
+ const F32 FAST_RATE_BPS = 600.f * 1024.f;
+ const F32 FASTER_RATE_BPS = 750.f * 1024.f;
+ F32 max_bandwidth = gViewerThrottle.getMaxBandwidth();
+ if (rate_bps > FASTER_RATE_BPS
+ && rate_bps > max_bandwidth)
+ {
+ LL_DEBUGS("AppInit") << "Fast network connection, increasing max bandwidth to "
+ << FASTER_RATE_BPS/1024.f
+ << " kbps" << LL_ENDL;
+ gViewerThrottle.setMaxBandwidth(FASTER_RATE_BPS / 1024.f);
+ }
+ else if (rate_bps > FAST_RATE_BPS
+ && rate_bps > max_bandwidth)
+ {
+ LL_DEBUGS("AppInit") << "Fast network connection, increasing max bandwidth to "
+ << FAST_RATE_BPS/1024.f
+ << " kbps" << LL_ENDL;
+ gViewerThrottle.setMaxBandwidth(FAST_RATE_BPS / 1024.f);
+ }
+
+ // Set the show start location to true, now that the user has logged
+ // on with this install.
+ gSavedSettings.setBOOL("ShowStartLocation", TRUE);
+ }
+
+ // We're successfully logged in.
+ gSavedSettings.setBOOL("FirstLoginThisInstall", FALSE);
+
+ LLFloaterReg::showInitialVisibleInstances();
+
+ // based on the comments, we've successfully logged in so we can delete the 'forced'
+ // URL that the updater set in settings.ini (in a mostly paranoid fashion)
+ std::string nextLoginLocation = gSavedSettings.getString( "NextLoginLocation" );
+ if ( nextLoginLocation.length() )
+ {
+ // clear it
+ gSavedSettings.setString( "NextLoginLocation", "" );
+
+ // and make sure it's saved
+ gSavedSettings.saveToFile( gSavedSettings.getString("ClientSettingsFile") , TRUE );
+ LLUIColorTable::instance().saveUserSettings();
+ };
+
+ if (!gNoRender)
+ {
+ // JC: Initializing audio requests many sounds for download.
+ init_audio();
+
+ // JC: Initialize "active" gestures. This may also trigger
+ // many gesture downloads, if this is the user's first
+ // time on this machine or -purge has been run.
+ LLSD gesture_options
+ = LLLoginInstance::getInstance()->getResponse("gestures");
+ if (gesture_options.isDefined())
+ {
+ LL_DEBUGS("AppInit") << "Gesture Manager loading " << gesture_options.size()
+ << LL_ENDL;
+ uuid_vec_t item_ids;
+ for(LLSD::array_const_iterator resp_it = gesture_options.beginArray(),
+ end = gesture_options.endArray(); resp_it != end; ++resp_it)
+ {
+ // If the id is not specifed in the LLSD,
+ // the LLSD operator[]() will return a null LLUUID.
+ LLUUID item_id = (*resp_it)["item_id"];
+ LLUUID asset_id = (*resp_it)["asset_id"];
+
+ if (item_id.notNull() && asset_id.notNull())
+ {
+ // Could schedule and delay these for later.
+ const BOOL no_inform_server = FALSE;
+ const BOOL no_deactivate_similar = FALSE;
+ LLGestureMgr::instance().activateGestureWithAsset(item_id, asset_id,
+ no_inform_server,
+ no_deactivate_similar);
+ // We need to fetch the inventory items for these gestures
+ // so we have the names to populate the UI.
+ item_ids.push_back(item_id);
+ }
+ }
+ // no need to add gesture to inventory observer, it's already made in constructor
+ LLGestureMgr::instance().setFetchIDs(item_ids);
+ LLGestureMgr::instance().startFetch();
+ }
+ }
+ gDisplaySwapBuffers = TRUE;
+
+ LLMessageSystem* msg = gMessageSystem;
+ msg->setHandlerFuncFast(_PREHASH_SoundTrigger, process_sound_trigger);
+ msg->setHandlerFuncFast(_PREHASH_PreloadSound, process_preload_sound);
+ msg->setHandlerFuncFast(_PREHASH_AttachedSound, process_attached_sound);
+ msg->setHandlerFuncFast(_PREHASH_AttachedSoundGainChange, process_attached_sound_gain_change);
+
+ LL_DEBUGS("AppInit") << "Initialization complete" << LL_ENDL;
+
+ gRenderStartTime.reset();
+ gForegroundTime.reset();
+
+ // HACK: Inform simulator of window size.
+ // Do this here so it's less likely to race with RegisterNewAgent.
+ // TODO: Put this into RegisterNewAgent
+ // JC - 7/20/2002
+ gViewerWindow->sendShapeToSim();
+
+
+ // Ignore stipend information for now. Money history is on the web site.
+ // if needed, show the L$ history window
+ //if (stipend_since_login && !gNoRender)
+ //{
+ //}
+
+ // The reason we show the alert is because we want to
+ // reduce confusion for when you log in and your provided
+ // location is not your expected location. So, if this is
+ // your first login, then you do not have an expectation,
+ // thus, do not show this alert.
+ if (!gAgent.isFirstLogin())
+ {
+ llinfos << "gAgentStartLocation : " << gAgentStartLocation << llendl;
+ LLSLURL start_slurl = LLStartUp::getStartSLURL();
+
+ if (((start_slurl.getType() == LLSLURL::LOCATION) && (gAgentStartLocation == "url")) ||
+ ((start_slurl.getType() == LLSLURL::LAST_LOCATION) && (gAgentStartLocation == "last")) ||
+ ((start_slurl.getType() == LLSLURL::HOME_LOCATION) && (gAgentStartLocation == "home")))
+ {
+ // Start location is OK
+ // Disabled code to restore camera location and focus if logging in to default location
+ static bool samename = false;
+ if (samename)
+ {
+ // restore old camera pos
+ gAgentCamera.setFocusOnAvatar(FALSE, FALSE);
+ gAgentCamera.setCameraPosAndFocusGlobal(gSavedSettings.getVector3d("CameraPosOnLogout"), gSavedSettings.getVector3d("FocusPosOnLogout"), LLUUID::null);
+ BOOL limit_hit = FALSE;
+ gAgentCamera.calcCameraPositionTargetGlobal(&limit_hit);
+ if (limit_hit)
+ {
+ gAgentCamera.setFocusOnAvatar(TRUE, FALSE);
+ }
+ gAgentCamera.stopCameraAnimation();
+ }
+ }
+ else
+ {
+ std::string msg;
+ switch(start_slurl.getType())
+ {
+ case LLSLURL::LOCATION:
+ {
+
+ msg = "AvatarMovedDesired";
+ break;
+ }
+ case LLSLURL::HOME_LOCATION:
+ {
+ msg = "AvatarMovedHome";
+ break;
+ }
+ default:
+ {
+ msg = "AvatarMovedLast";
+ }
+ }
+ LLNotificationsUtil::add(msg);
+ }
+ }
+
+ //DEV-17797. get null folder. Any items found here moved to Lost and Found
+ LLInventoryModelBackgroundFetch::instance().findLostItems();
+
+ LLStartUp::setStartupState( STATE_PRECACHE );
+ timeout.reset();
+ return FALSE;
+ }
+
+ if (STATE_PRECACHE == LLStartUp::getStartupState())
+ {
+ F32 timeout_frac = timeout.getElapsedTimeF32()/PRECACHING_DELAY;
+
+ // We now have an inventory skeleton, so if this is a user's first
+ // login, we can start setting up their clothing and avatar
+ // appearance. This helps to avoid the generic "Ruth" avatar in
+ // the orientation island tutorial experience. JC
+ if (gAgent.isFirstLogin()
+ && !sInitialOutfit.empty() // registration set up an outfit
+ && !sInitialOutfitGender.empty() // and a gender
+ && isAgentAvatarValid() // can't wear clothes without object
+ && !gAgent.isGenderChosen() ) // nothing already loading
+ {
+ // Start loading the wearables, textures, gestures
+ LLStartUp::loadInitialOutfit( sInitialOutfit, sInitialOutfitGender );
+ }
+
+ // wait precache-delay and for agent's avatar or a lot longer.
+ if(((timeout_frac > 1.f) && isAgentAvatarValid())
+ || (timeout_frac > 3.f))
+ {
+ LLStartUp::setStartupState( STATE_WEARABLES_WAIT );
+ }
+ else
+ {
+ update_texture_fetch();
+ set_startup_status(0.60f + 0.30f * timeout_frac,
+ LLTrans::getString("LoginPrecaching"),
+ gAgent.mMOTD);
+ display_startup();
+ if (!LLViewerShaderMgr::sInitialized)
+ {
+ LLViewerShaderMgr::sInitialized = TRUE;
+ LLViewerShaderMgr::instance()->setShaders();
+ }
+ }
+
+ return TRUE;
+ }
+
+ if (STATE_WEARABLES_WAIT == LLStartUp::getStartupState())
+ {
+ static LLFrameTimer wearables_timer;
+
+ const F32 wearables_time = wearables_timer.getElapsedTimeF32();
+ const F32 MAX_WEARABLES_TIME = 10.f;
+
+ if (!gAgent.isGenderChosen())
+ {
+ // No point in waiting for clothing, we don't even
+ // know what gender we are. Pop a dialog to ask and
+ // proceed to draw the world. JC
+ //
+ // *NOTE: We might hit this case even if we have an
+ // initial outfit, but if the load hasn't started
+ // already then something is wrong so fall back
+ // to generic outfits. JC
+ LLNotificationsUtil::add("WelcomeChooseSex", LLSD(), LLSD(),
+ callback_choose_gender);
+ LLStartUp::setStartupState( STATE_CLEANUP );
+ return TRUE;
+ }
+
+ if (wearables_time > MAX_WEARABLES_TIME)
+ {
+ LLNotificationsUtil::add("ClothingLoading");
+ LLViewerStats::getInstance()->incStat(LLViewerStats::ST_WEARABLES_TOO_LONG);
+ LLStartUp::setStartupState( STATE_CLEANUP );
+ return TRUE;
+ }
+
+ if (gAgent.isFirstLogin())
+ {
+ // wait for avatar to be completely loaded
+ if (isAgentAvatarValid()
+ && gAgentAvatarp->isFullyLoaded())
+ {
+ //llinfos << "avatar fully loaded" << llendl;
+ LLStartUp::setStartupState( STATE_CLEANUP );
+ return TRUE;
+ }
+ }
+ else
+ {
+ // OK to just get the wearables
+ if ( gAgentWearables.areWearablesLoaded() )
+ {
+ // We have our clothing, proceed.
+ //llinfos << "wearables loaded" << llendl;
+ LLStartUp::setStartupState( STATE_CLEANUP );
+ return TRUE;
+ }
+ }
+
+ update_texture_fetch();
+ set_startup_status(0.9f + 0.1f * wearables_time / MAX_WEARABLES_TIME,
+ LLTrans::getString("LoginDownloadingClothing").c_str(),
+ gAgent.mMOTD.c_str());
+ return TRUE;
+ }
+
+ if (STATE_CLEANUP == LLStartUp::getStartupState())
+ {
+ set_startup_status(1.0, "", "");
+
+ // Let the map know about the inventory.
+ LLFloaterWorldMap* floater_world_map = LLFloaterWorldMap::getInstance();
+ if(floater_world_map)
+ {
+ floater_world_map->observeInventory(&gInventory);
+ floater_world_map->observeFriends();
+ }
+ gViewerWindow->showCursor();
+ gViewerWindow->getWindow()->resetBusyCount();
+ gViewerWindow->getWindow()->setCursor(UI_CURSOR_ARROW);
+ LL_DEBUGS("AppInit") << "Done releasing bitmap" << LL_ENDL;
+ gViewerWindow->setShowProgress(FALSE);
+ gViewerWindow->setProgressCancelButtonVisible(FALSE);
+
+ // We're not away from keyboard, even though login might have taken
+ // a while. JC
+ gAgent.clearAFK();
+
+ // Have the agent start watching the friends list so we can update proxies
+ gAgent.observeFriends();
+ if (gSavedSettings.getBOOL("LoginAsGod"))
+ {
+ gAgent.requestEnterGodMode();
+ }
+
+ // Start automatic replay if the flag is set.
+ if (gSavedSettings.getBOOL("StatsAutoRun") || gAgentPilot.getReplaySession())
+ {
+ LLUUID id;
+ LL_DEBUGS("AppInit") << "Starting automatic playback" << LL_ENDL;
+ gAgentPilot.startPlayback();
+ }
+
+ show_debug_menus(); // Debug menu visiblity and First Use trigger
+
+ // If we've got a startup URL, dispatch it
+ LLStartUp::dispatchURL();
+
+ // Retrieve information about the land data
+ // (just accessing this the first time will fetch it,
+ // then the data is cached for the viewer's lifetime)
+ LLProductInfoRequestManager::instance();
+
+ // *FIX:Mani - What do I do here?
+ // Need we really clear the Auth response data?
+ // Clean up the userauth stuff.
+ // LLUserAuth::getInstance()->reset();
+
+ LLStartUp::setStartupState( STATE_STARTED );
+
+ // Unmute audio if desired and setup volumes.
+ // Unmute audio if desired and setup volumes.
+ // This is a not-uncommon crash site, so surround it with
+ // llinfos output to aid diagnosis.
+ LL_INFOS("AppInit") << "Doing first audio_update_volume..." << LL_ENDL;
+ audio_update_volume();
+ LL_INFOS("AppInit") << "Done first audio_update_volume." << LL_ENDL;
+
+ // reset keyboard focus to sane state of pointing at world
+ gFocusMgr.setKeyboardFocus(NULL);
+
+#if 0 // sjb: enable for auto-enabling timer display
+ gDebugView->mFastTimerView->setVisible(TRUE);
+#endif
+
+ LLAppViewer::instance()->handleLoginComplete();
+
+ // reset timers now that we are running "logged in" logic
+ LLFastTimer::reset();
+
+ LLAgentPicksInfo::getInstance()->requestNumberOfPicks();
+
+ LLIMFloater::initIMFloater();
+
+ return TRUE;
+ }
+
+ LL_WARNS("AppInit") << "Reached end of idle_startup for state " << LLStartUp::getStartupState() << LL_ENDL;
+ return TRUE;
+}
+
+//
+// local function definition
+//
+
+void login_show()
+{
+ LL_INFOS("AppInit") << "Initializing Login Screen" << LL_ENDL;
+
+#ifdef LL_RELEASE_FOR_DOWNLOAD
+ BOOL bUseDebugLogin = gSavedSettings.getBOOL("UseDebugLogin");
+#else
+ BOOL bUseDebugLogin = TRUE;
+#endif
+
+ LLPanelLogin::show( gViewerWindow->getWindowRectScaled(),
+ bUseDebugLogin || gSavedSettings.getBOOL("SecondLifeEnterprise"),
+ login_callback, NULL );
+
+}
+
+// Callback for when login screen is closed. Option 0 = connect, option 1 = quit.
+void login_callback(S32 option, void *userdata)
+{
+ const S32 CONNECT_OPTION = 0;
+ const S32 QUIT_OPTION = 1;
+
+ if (CONNECT_OPTION == option)
+ {
+ LLStartUp::setStartupState( STATE_LOGIN_CLEANUP );
+ return;
+ }
+ else if (QUIT_OPTION == option) // *TODO: THIS CODE SEEMS TO BE UNREACHABLE!!!!! login_callback is never called with option equal to QUIT_OPTION
+ {
+ if (!gSavedSettings.getBOOL("RememberPassword"))
+ {
+ // turn off the setting and write out to disk
+ gSavedSettings.saveToFile( gSavedSettings.getString("ClientSettingsFile") , TRUE );
+ LLUIColorTable::instance().saveUserSettings();
+ }
+
+ // Next iteration through main loop should shut down the app cleanly.
+ LLAppViewer::instance()->userQuit();
+
+ if (LLAppViewer::instance()->quitRequested())
+ {
+ LLPanelLogin::closePanel();
+ }
+ return;
+ }
+ else
+ {
+ LL_WARNS("AppInit") << "Unknown login button clicked" << LL_ENDL;
+ }
+}
+
+void show_first_run_dialog()
+{
+ LLNotificationsUtil::add("FirstRun", LLSD(), LLSD(), first_run_dialog_callback);
+}
+
+bool first_run_dialog_callback(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ if (0 == option)
+ {
+ LL_DEBUGS("AppInit") << "First run dialog cancelling" << LL_ENDL;
+ LLWeb::loadURLExternal(LLTrans::getString("create_account_url") );
+ }
+
+ LLPanelLogin::giveFocus();
+ return false;
+}
+
+
+
+void set_startup_status(const F32 frac, const std::string& string, const std::string& msg)
+{
+ gViewerWindow->setProgressPercent(frac*100);
+ gViewerWindow->setProgressString(string);
+
+ gViewerWindow->setProgressMessage(msg);
+}
+
+bool login_alert_status(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ // Buttons
+ switch( option )
+ {
+ case 0: // OK
+ break;
+ // case 1: // Help
+ // LLWeb::loadURL(LLNotifications::instance().getGlobalString("SUPPORT_URL") );
+ // break;
+ case 2: // Teleport
+ // Restart the login process, starting at our home locaton
+ LLStartUp::setStartSLURL(LLSLURL(LLSLURL::SIM_LOCATION_HOME));
+ LLStartUp::setStartupState( STATE_LOGIN_CLEANUP );
+ break;
+ default:
+ LL_WARNS("AppInit") << "Missing case in login_alert_status switch" << LL_ENDL;
+ }
+
+ LLPanelLogin::giveFocus();
+ return false;
+}
+
+
+void use_circuit_callback(void**, S32 result)
+{
+ // bail if we're quitting.
+ if(LLApp::isExiting()) return;
+ if( !gUseCircuitCallbackCalled )
+ {
+ gUseCircuitCallbackCalled = true;
+ if (result)
+ {
+ // Make sure user knows something bad happened. JC
+ LL_WARNS("AppInit") << "Backing up to login screen!" << LL_ENDL;
+ LLNotificationsUtil::add("LoginPacketNeverReceived", LLSD(), LLSD(), login_alert_status);
+ reset_login();
+ }
+ else
+ {
+ gGotUseCircuitCodeAck = true;
+ }
+ }
+}
+
+void register_viewer_callbacks(LLMessageSystem* msg)
+{
+ msg->setHandlerFuncFast(_PREHASH_LayerData, process_layer_data );
+ msg->setHandlerFuncFast(_PREHASH_ImageData, LLViewerTextureList::receiveImageHeader );
+ msg->setHandlerFuncFast(_PREHASH_ImagePacket, LLViewerTextureList::receiveImagePacket );
+ msg->setHandlerFuncFast(_PREHASH_ObjectUpdate, process_object_update );
+ msg->setHandlerFunc("ObjectUpdateCompressed", process_compressed_object_update );
+ msg->setHandlerFunc("ObjectUpdateCached", process_cached_object_update );
+ msg->setHandlerFuncFast(_PREHASH_ImprovedTerseObjectUpdate, process_terse_object_update_improved );
+ msg->setHandlerFunc("SimStats", process_sim_stats);
+ msg->setHandlerFuncFast(_PREHASH_HealthMessage, process_health_message );
+ msg->setHandlerFuncFast(_PREHASH_EconomyData, process_economy_data);
+ msg->setHandlerFunc("RegionInfo", LLViewerRegion::processRegionInfo);
+
+ msg->setHandlerFuncFast(_PREHASH_ChatFromSimulator, process_chat_from_simulator);
+ msg->setHandlerFuncFast(_PREHASH_KillObject, process_kill_object, NULL);
+ msg->setHandlerFuncFast(_PREHASH_SimulatorViewerTimeMessage, process_time_synch, NULL);
+ msg->setHandlerFuncFast(_PREHASH_EnableSimulator, process_enable_simulator);
+ msg->setHandlerFuncFast(_PREHASH_DisableSimulator, process_disable_simulator);
+ msg->setHandlerFuncFast(_PREHASH_KickUser, process_kick_user, NULL);
+
+ msg->setHandlerFunc("CrossedRegion", process_crossed_region);
+ msg->setHandlerFuncFast(_PREHASH_TeleportFinish, process_teleport_finish);
+
+ msg->setHandlerFuncFast(_PREHASH_AlertMessage, process_alert_message);
+ msg->setHandlerFunc("AgentAlertMessage", process_agent_alert_message);
+ msg->setHandlerFuncFast(_PREHASH_MeanCollisionAlert, process_mean_collision_alert_message, NULL);
+ msg->setHandlerFunc("ViewerFrozenMessage", process_frozen_message);
+
+ msg->setHandlerFuncFast(_PREHASH_NameValuePair, process_name_value);
+ msg->setHandlerFuncFast(_PREHASH_RemoveNameValuePair, process_remove_name_value);
+ msg->setHandlerFuncFast(_PREHASH_AvatarAnimation, process_avatar_animation);
+ msg->setHandlerFuncFast(_PREHASH_AvatarAppearance, process_avatar_appearance);
+ msg->setHandlerFunc("AgentCachedTextureResponse", LLAgent::processAgentCachedTextureResponse);
+ msg->setHandlerFunc("RebakeAvatarTextures", LLVOAvatarSelf::processRebakeAvatarTextures);
+ msg->setHandlerFuncFast(_PREHASH_CameraConstraint, process_camera_constraint);
+ msg->setHandlerFuncFast(_PREHASH_AvatarSitResponse, process_avatar_sit_response);
+ msg->setHandlerFunc("SetFollowCamProperties", process_set_follow_cam_properties);
+ msg->setHandlerFunc("ClearFollowCamProperties", process_clear_follow_cam_properties);
+
+ msg->setHandlerFuncFast(_PREHASH_ImprovedInstantMessage, process_improved_im);
+ msg->setHandlerFuncFast(_PREHASH_ScriptQuestion, process_script_question);
+ msg->setHandlerFuncFast(_PREHASH_ObjectProperties, LLSelectMgr::processObjectProperties, NULL);
+ msg->setHandlerFuncFast(_PREHASH_ObjectPropertiesFamily, LLSelectMgr::processObjectPropertiesFamily, NULL);
+ msg->setHandlerFunc("ForceObjectSelect", LLSelectMgr::processForceObjectSelect);
+
+ msg->setHandlerFuncFast(_PREHASH_MoneyBalanceReply, process_money_balance_reply, NULL);
+ msg->setHandlerFuncFast(_PREHASH_CoarseLocationUpdate, LLWorld::processCoarseUpdate, NULL);
+ msg->setHandlerFuncFast(_PREHASH_ReplyTaskInventory, LLViewerObject::processTaskInv, NULL);
+ msg->setHandlerFuncFast(_PREHASH_DerezContainer, process_derez_container, NULL);
+ msg->setHandlerFuncFast(_PREHASH_ScriptRunningReply,
+ &LLLiveLSLEditor::processScriptRunningReply);
+
+ msg->setHandlerFuncFast(_PREHASH_DeRezAck, process_derez_ack);
+
+ msg->setHandlerFunc("LogoutReply", process_logout_reply);
+
+ //msg->setHandlerFuncFast(_PREHASH_AddModifyAbility,
+ // &LLAgent::processAddModifyAbility);
+ //msg->setHandlerFuncFast(_PREHASH_RemoveModifyAbility,
+ // &LLAgent::processRemoveModifyAbility);
+ msg->setHandlerFuncFast(_PREHASH_AgentDataUpdate,
+ &LLAgent::processAgentDataUpdate);
+ msg->setHandlerFuncFast(_PREHASH_AgentGroupDataUpdate,
+ &LLAgent::processAgentGroupDataUpdate);
+ msg->setHandlerFunc("AgentDropGroup",
+ &LLAgent::processAgentDropGroup);
+ // land ownership messages
+ msg->setHandlerFuncFast(_PREHASH_ParcelOverlay,
+ LLViewerParcelMgr::processParcelOverlay);
+ msg->setHandlerFuncFast(_PREHASH_ParcelProperties,
+ LLViewerParcelMgr::processParcelProperties);
+ msg->setHandlerFunc("ParcelAccessListReply",
+ LLViewerParcelMgr::processParcelAccessListReply);
+ msg->setHandlerFunc("ParcelDwellReply",
+ LLViewerParcelMgr::processParcelDwellReply);
+
+ msg->setHandlerFunc("AvatarPropertiesReply",
+ &LLAvatarPropertiesProcessor::processAvatarPropertiesReply);
+ msg->setHandlerFunc("AvatarInterestsReply",
+ &LLAvatarPropertiesProcessor::processAvatarInterestsReply);
+ msg->setHandlerFunc("AvatarGroupsReply",
+ &LLAvatarPropertiesProcessor::processAvatarGroupsReply);
+ // ratings deprecated
+ //msg->setHandlerFuncFast(_PREHASH_AvatarStatisticsReply,
+ // LLPanelAvatar::processAvatarStatisticsReply);
+ msg->setHandlerFunc("AvatarNotesReply",
+ &LLAvatarPropertiesProcessor::processAvatarNotesReply);
+ msg->setHandlerFunc("AvatarPicksReply",
+ &LLAvatarPropertiesProcessor::processAvatarPicksReply);
+ msg->setHandlerFunc("AvatarClassifiedReply",
+ &LLAvatarPropertiesProcessor::processAvatarClassifiedsReply);
+
+ msg->setHandlerFuncFast(_PREHASH_CreateGroupReply,
+ LLGroupMgr::processCreateGroupReply);
+ msg->setHandlerFuncFast(_PREHASH_JoinGroupReply,
+ LLGroupMgr::processJoinGroupReply);
+ msg->setHandlerFuncFast(_PREHASH_EjectGroupMemberReply,
+ LLGroupMgr::processEjectGroupMemberReply);
+ msg->setHandlerFuncFast(_PREHASH_LeaveGroupReply,
+ LLGroupMgr::processLeaveGroupReply);
+ msg->setHandlerFuncFast(_PREHASH_GroupProfileReply,
+ LLGroupMgr::processGroupPropertiesReply);
+
+ // ratings deprecated
+ // msg->setHandlerFuncFast(_PREHASH_ReputationIndividualReply,
+ // LLFloaterRate::processReputationIndividualReply);
+
+ msg->setHandlerFuncFast(_PREHASH_AgentWearablesUpdate,
+ LLAgentWearables::processAgentInitialWearablesUpdate );
+
+ msg->setHandlerFunc("ScriptControlChange",
+ LLAgent::processScriptControlChange );
+
+ msg->setHandlerFuncFast(_PREHASH_ViewerEffect, LLHUDManager::processViewerEffect);
+
+ msg->setHandlerFuncFast(_PREHASH_GrantGodlikePowers, process_grant_godlike_powers);
+
+ msg->setHandlerFuncFast(_PREHASH_GroupAccountSummaryReply,
+ LLPanelGroupLandMoney::processGroupAccountSummaryReply);
+ msg->setHandlerFuncFast(_PREHASH_GroupAccountDetailsReply,
+ LLPanelGroupLandMoney::processGroupAccountDetailsReply);
+ msg->setHandlerFuncFast(_PREHASH_GroupAccountTransactionsReply,
+ LLPanelGroupLandMoney::processGroupAccountTransactionsReply);
+
+ msg->setHandlerFuncFast(_PREHASH_UserInfoReply,
+ process_user_info_reply);
+
+ msg->setHandlerFunc("RegionHandshake", process_region_handshake, NULL);
+
+ msg->setHandlerFunc("TeleportStart", process_teleport_start );
+ msg->setHandlerFunc("TeleportProgress", process_teleport_progress);
+ msg->setHandlerFunc("TeleportFailed", process_teleport_failed, NULL);
+ msg->setHandlerFunc("TeleportLocal", process_teleport_local, NULL);
+
+ msg->setHandlerFunc("ImageNotInDatabase", LLViewerTextureList::processImageNotInDatabase, NULL);
+
+ msg->setHandlerFuncFast(_PREHASH_GroupMembersReply,
+ LLGroupMgr::processGroupMembersReply);
+ msg->setHandlerFunc("GroupRoleDataReply",
+ LLGroupMgr::processGroupRoleDataReply);
+ msg->setHandlerFunc("GroupRoleMembersReply",
+ LLGroupMgr::processGroupRoleMembersReply);
+ msg->setHandlerFunc("GroupTitlesReply",
+ LLGroupMgr::processGroupTitlesReply);
+ // Special handler as this message is sometimes used for group land.
+ msg->setHandlerFunc("PlacesReply", process_places_reply);
+ msg->setHandlerFunc("GroupNoticesListReply", LLPanelGroupNotices::processGroupNoticesListReply);
+
+ msg->setHandlerFunc("AvatarPickerReply", LLFloaterAvatarPicker::processAvatarPickerReply);
+
+ msg->setHandlerFunc("MapBlockReply", LLWorldMapMessage::processMapBlockReply);
+ msg->setHandlerFunc("MapItemReply", LLWorldMapMessage::processMapItemReply);
+ msg->setHandlerFunc("EventInfoReply", LLEventNotifier::processEventInfoReply);
+
+ msg->setHandlerFunc("PickInfoReply", &LLAvatarPropertiesProcessor::processPickInfoReply);
+// msg->setHandlerFunc("ClassifiedInfoReply", LLPanelClassified::processClassifiedInfoReply);
+ msg->setHandlerFunc("ClassifiedInfoReply", LLAvatarPropertiesProcessor::processClassifiedInfoReply);
+ msg->setHandlerFunc("ParcelInfoReply", LLRemoteParcelInfoProcessor::processParcelInfoReply);
+ msg->setHandlerFunc("ScriptDialog", process_script_dialog);
+ msg->setHandlerFunc("LoadURL", process_load_url);
+ msg->setHandlerFunc("ScriptTeleportRequest", process_script_teleport_request);
+ msg->setHandlerFunc("EstateCovenantReply", process_covenant_reply);
+
+ // calling cards
+ msg->setHandlerFunc("OfferCallingCard", process_offer_callingcard);
+ msg->setHandlerFunc("AcceptCallingCard", process_accept_callingcard);
+ msg->setHandlerFunc("DeclineCallingCard", process_decline_callingcard);
+
+ msg->setHandlerFunc("ParcelObjectOwnersReply", LLPanelLandObjects::processParcelObjectOwnersReply);
+
+ msg->setHandlerFunc("InitiateDownload", process_initiate_download);
+ msg->setHandlerFunc("LandStatReply", LLFloaterTopObjects::handle_land_reply);
+ msg->setHandlerFunc("GenericMessage", process_generic_message);
+
+ msg->setHandlerFuncFast(_PREHASH_FeatureDisabled, process_feature_disabled_message);
+}
+
+void asset_callback_nothing(LLVFS*, const LLUUID&, LLAssetType::EType, void*, S32)
+{
+ // nothing
+}
+
+// *HACK: Must match name in Library or agent inventory
+const std::string ROOT_GESTURES_FOLDER = "Gestures";
+const std::string COMMON_GESTURES_FOLDER = "Common Gestures";
+const std::string MALE_GESTURES_FOLDER = "Male Gestures";
+const std::string FEMALE_GESTURES_FOLDER = "Female Gestures";
+const std::string SPEECH_GESTURES_FOLDER = "Speech Gestures";
+const std::string OTHER_GESTURES_FOLDER = "Other Gestures";
+const S32 OPT_CLOSED_WINDOW = -1;
+const S32 OPT_MALE = 0;
+const S32 OPT_FEMALE = 1;
+const S32 OPT_TRUST_CERT = 0;
+const S32 OPT_CANCEL_TRUST = 1;
+
+bool callback_choose_gender(const LLSD& notification, const LLSD& response)
+{
+
+ // These defaults are returned from the server on login. They are set in login.xml.
+ // If no default is returned from the server, they are retrieved from settings.xml.
+
+ S32 option = LLNotification::getSelectedOption(notification, response);
+ switch(option)
+ {
+ case OPT_MALE:
+ LLStartUp::loadInitialOutfit( gSavedSettings.getString("DefaultMaleAvatar"), "male" );
+ break;
+
+ case OPT_FEMALE:
+ case OPT_CLOSED_WINDOW:
+ default:
+ LLStartUp::loadInitialOutfit( gSavedSettings.getString("DefaultFemaleAvatar"), "female" );
+ break;
+ }
+ return false;
+}
+
+void LLStartUp::copyLibraryGestures(const std::string& same_gender_gestures)
+{
+ llinfos << "Copying library gestures" << llendl;
+
+ // Copy gestures
+ LLUUID lib_gesture_cat_id =
+ gInventory.findCategoryUUIDForType(LLFolderType::FT_GESTURE,false,true);
+ if (lib_gesture_cat_id.isNull())
+ {
+ llwarns << "Unable to copy gestures, source category not found" << llendl;
+ }
+ LLUUID dst_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_GESTURE);
+
+ std::vector<std::string> gesture_folders_to_copy;
+ gesture_folders_to_copy.push_back(MALE_GESTURES_FOLDER);
+ gesture_folders_to_copy.push_back(FEMALE_GESTURES_FOLDER);
+ gesture_folders_to_copy.push_back(COMMON_GESTURES_FOLDER);
+ gesture_folders_to_copy.push_back(SPEECH_GESTURES_FOLDER);
+ gesture_folders_to_copy.push_back(OTHER_GESTURES_FOLDER);
+
+ for(std::vector<std::string>::iterator it = gesture_folders_to_copy.begin();
+ it != gesture_folders_to_copy.end();
+ ++it)
+ {
+ std::string& folder_name = *it;
+
+ LLPointer<LLInventoryCallback> cb(NULL);
+
+ if (folder_name == same_gender_gestures ||
+ folder_name == COMMON_GESTURES_FOLDER ||
+ folder_name == OTHER_GESTURES_FOLDER)
+ {
+ cb = new ActivateGestureCallback;
+ }
+
+
+ LLUUID cat_id = findDescendentCategoryIDByName(lib_gesture_cat_id,folder_name);
+ if (cat_id.isNull())
+ {
+ llwarns << "failed to find gesture folder for " << folder_name << llendl;
+ }
+ else
+ {
+ llinfos << "initiating fetch and copy for " << folder_name << " cat_id " << cat_id << llendl;
+ LLAppearanceMgr* app_mgr = LLAppearanceMgr::getInstance();
+ callAfterCategoryFetch(cat_id,
+ boost::bind(&LLAppearanceMgr::shallowCopyCategory,
+ app_mgr,
+ cat_id,
+ dst_id,
+ cb));
+ }
+ }
+}
+
+void LLStartUp::loadInitialOutfit( const std::string& outfit_folder_name,
+ const std::string& gender_name )
+{
+ llinfos << "starting" << llendl;
+
+ // Not going through the processAgentInitialWearables path, so need to set this here.
+ LLAppearanceMgr::instance().setAttachmentInvLinkEnable(true);
+ // Initiate creation of COF, since we're also bypassing that.
+ gInventory.findCategoryUUIDForType(LLFolderType::FT_CURRENT_OUTFIT);
+
+ S32 gender = 0;
+ std::string same_gender_gestures;
+ if (gender_name == "male")
+ {
+ gender = OPT_MALE;
+ same_gender_gestures = MALE_GESTURES_FOLDER;
+ }
+ else
+ {
+ gender = OPT_FEMALE;
+ same_gender_gestures = FEMALE_GESTURES_FOLDER;
+ }
+
+ // try to find the outfit - if not there, create some default
+ // wearables.
+ LLUUID cat_id = findDescendentCategoryIDByName(
+ gInventory.getLibraryRootFolderID(),
+ outfit_folder_name);
+ if (cat_id.isNull())
+ {
+ gAgentWearables.createStandardWearables(gender);
+ }
+ else
+ {
+ sWearablesLoadedCon = gAgentWearables.addLoadedCallback(LLStartUp::saveInitialOutfit);
+
+ bool do_copy = true;
+ bool do_append = false;
+ LLViewerInventoryCategory *cat = gInventory.getCategory(cat_id);
+ LLAppearanceMgr::instance().wearInventoryCategory(cat, do_copy, do_append);
+ }
+
+ // Copy gestures
+ copyLibraryGestures(same_gender_gestures);
+
+ // This is really misnamed -- it means we have started loading
+ // an outfit/shape that will give the avatar a gender eventually. JC
+ gAgent.setGenderChosen(TRUE);
+
+}
+
+//static
+void LLStartUp::saveInitialOutfit()
+{
+ if (sInitialOutfit.empty()) return;
+
+ if (sWearablesLoadedCon.connected())
+ {
+ sWearablesLoadedCon.disconnect();
+ }
+ LLAppearanceMgr::getInstance()->makeNewOutfitLinks(sInitialOutfit,false);
+}
+
+std::string& LLStartUp::getInitialOutfitName()
+{
+ return sInitialOutfit;
+}
+
+// Loads a bitmap to display during load
+void init_start_screen(S32 location_id)
+{
+ if (gStartTexture.notNull())
+ {
+ gStartTexture = NULL;
+ LL_INFOS("AppInit") << "re-initializing start screen" << LL_ENDL;
+ }
+
+ LL_DEBUGS("AppInit") << "Loading startup bitmap..." << LL_ENDL;
+
+ std::string temp_str = gDirUtilp->getLindenUserDir() + gDirUtilp->getDirDelimiter();
+
+ if ((S32)START_LOCATION_ID_LAST == location_id)
+ {
+ temp_str += SCREEN_LAST_FILENAME;
+ }
+ else
+ {
+ temp_str += SCREEN_HOME_FILENAME;
+ }
+
+ LLPointer<LLImageBMP> start_image_bmp = new LLImageBMP;
+
+ // Turn off start screen to get around the occasional readback
+ // driver bug
+ if(!gSavedSettings.getBOOL("UseStartScreen"))
+ {
+ LL_INFOS("AppInit") << "Bitmap load disabled" << LL_ENDL;
+ return;
+ }
+ else if(!start_image_bmp->load(temp_str) )
+ {
+ LL_WARNS("AppInit") << "Bitmap load failed" << LL_ENDL;
+ return;
+ }
+
+ gStartImageWidth = start_image_bmp->getWidth();
+ gStartImageHeight = start_image_bmp->getHeight();
+
+ LLPointer<LLImageRaw> raw = new LLImageRaw;
+ if (!start_image_bmp->decode(raw, 0.0f))
+ {
+ LL_WARNS("AppInit") << "Bitmap decode failed" << LL_ENDL;
+ gStartTexture = NULL;
+ return;
+ }
+
+ raw->expandToPowerOfTwo();
+ gStartTexture = LLViewerTextureManager::getLocalTexture(raw.get(), FALSE) ;
+}
+
+
+// frees the bitmap
+void release_start_screen()
+{
+ LL_DEBUGS("AppInit") << "Releasing bitmap..." << LL_ENDL;
+ gStartTexture = NULL;
+}
+
+
+// static
+std::string LLStartUp::startupStateToString(EStartupState state)
+{
+#define RTNENUM(E) case E: return #E
+ switch(state){
+ RTNENUM( STATE_FIRST );
+ RTNENUM( STATE_BROWSER_INIT );
+ RTNENUM( STATE_LOGIN_SHOW );
+ RTNENUM( STATE_LOGIN_WAIT );
+ RTNENUM( STATE_LOGIN_CLEANUP );
+ RTNENUM( STATE_LOGIN_AUTH_INIT );
+ RTNENUM( STATE_LOGIN_CURL_UNSTUCK );
+ RTNENUM( STATE_LOGIN_PROCESS_RESPONSE );
+ RTNENUM( STATE_WORLD_INIT );
+ RTNENUM( STATE_MULTIMEDIA_INIT );
+ RTNENUM( STATE_FONT_INIT );
+ RTNENUM( STATE_SEED_GRANTED_WAIT );
+ RTNENUM( STATE_SEED_CAP_GRANTED );
+ RTNENUM( STATE_WORLD_WAIT );
+ RTNENUM( STATE_AGENT_SEND );
+ RTNENUM( STATE_AGENT_WAIT );
+ RTNENUM( STATE_INVENTORY_SEND );
+ RTNENUM( STATE_MISC );
+ RTNENUM( STATE_PRECACHE );
+ RTNENUM( STATE_WEARABLES_WAIT );
+ RTNENUM( STATE_CLEANUP );
+ RTNENUM( STATE_STARTED );
+ default:
+ return llformat("(state #%d)", state);
+ }
+#undef RTNENUM
+}
+
+// static
+void LLStartUp::setStartupState( EStartupState state )
+{
+ LL_INFOS("AppInit") << "Startup state changing from " <<
+ getStartupStateString() << " to " <<
+ startupStateToString(state) << LL_ENDL;
+ gStartupState = state;
+ postStartupState();
+}
+
+void LLStartUp::postStartupState()
+{
+ LLSD stateInfo;
+ stateInfo["str"] = getStartupStateString();
+ stateInfo["enum"] = gStartupState;
+ sStateWatcher->post(stateInfo);
+}
+
+
+void reset_login()
+{
+ gAgentWearables.cleanup();
+ gAgentCamera.cleanup();
+ gAgent.cleanup();
+ LLWorld::getInstance()->destroyClass();
+
+ LLStartUp::setStartupState( STATE_LOGIN_SHOW );
+
+ if ( gViewerWindow )
+ { // Hide menus and normal buttons
+ gViewerWindow->setNormalControlsVisible( FALSE );
+ gLoginMenuBarView->setVisible( TRUE );
+ gLoginMenuBarView->setEnabled( TRUE );
+ }
+
+ // Hide any other stuff
+ LLFloaterReg::hideVisibleInstances();
+}
+
+//---------------------------------------------------------------------------
+
+// Initialize all plug-ins except the web browser (which was initialized
+// early, before the login screen). JC
+void LLStartUp::multimediaInit()
+{
+ LL_DEBUGS("AppInit") << "Initializing Multimedia...." << LL_ENDL;
+ std::string msg = LLTrans::getString("LoginInitializingMultimedia");
+ set_startup_status(0.42f, msg.c_str(), gAgent.mMOTD.c_str());
+ display_startup();
+
+ // LLViewerMedia::initClass();
+ LLViewerParcelMedia::initClass();
+}
+
+void LLStartUp::fontInit()
+{
+ LL_DEBUGS("AppInit") << "Initializing fonts...." << LL_ENDL;
+ std::string msg = LLTrans::getString("LoginInitializingFonts");
+ set_startup_status(0.45f, msg.c_str(), gAgent.mMOTD.c_str());
+ display_startup();
+
+ LLFontGL::loadDefaultFonts();
+}
+
+void LLStartUp::initNameCache()
+{
+ // Can be called multiple times
+ if ( gCacheName ) return;
+
+ gCacheName = new LLCacheName(gMessageSystem);
+ gCacheName->addObserver(&callback_cache_name);
+ gCacheName->localizeCacheName("waiting", LLTrans::getString("AvatarNameWaiting"));
+ gCacheName->localizeCacheName("nobody", LLTrans::getString("AvatarNameNobody"));
+ gCacheName->localizeCacheName("none", LLTrans::getString("GroupNameNone"));
+ // Load stored cache if possible
+ LLAppViewer::instance()->loadNameCache();
+
+ // Start cache in not-running state until we figure out if we have
+ // capabilities for display name lookup
+ LLAvatarNameCache::initClass(false);
+ LLAvatarNameCache::setUseDisplayNames(gSavedSettings.getBOOL("UseDisplayNames"));
+}
+
+void LLStartUp::cleanupNameCache()
+{
+ LLAvatarNameCache::cleanupClass();
+
+ delete gCacheName;
+ gCacheName = NULL;
+}
+
+bool LLStartUp::dispatchURL()
+{
+ // ok, if we've gotten this far and have a startup URL
+ if (!getStartSLURL().isValid())
+ {
+ return false;
+ }
+ if(getStartSLURL().getType() != LLSLURL::APP)
+ {
+
+ // If we started with a location, but we're already
+ // at that location, don't pop dialogs open.
+ LLVector3 pos = gAgent.getPositionAgent();
+ LLVector3 slurlpos = getStartSLURL().getPosition();
+ F32 dx = pos.mV[VX] - slurlpos.mV[VX];
+ F32 dy = pos.mV[VY] - slurlpos.mV[VY];
+ const F32 SLOP = 2.f; // meters
+
+ if( getStartSLURL().getRegion() != gAgent.getRegion()->getName()
+ || (dx*dx > SLOP*SLOP)
+ || (dy*dy > SLOP*SLOP) )
+ {
+ LLURLDispatcher::dispatch(getStartSLURL().getSLURLString(),
+ NULL, false);
+ }
+ return true;
+ }
+ return false;
+}
+
+void LLStartUp::setStartSLURL(const LLSLURL& slurl)
+{
+ sStartSLURL = slurl;
+ switch(slurl.getType())
+ {
+ case LLSLURL::HOME_LOCATION:
+ {
+ gSavedSettings.setString("LoginLocation", LLSLURL::SIM_LOCATION_HOME);
+ break;
+ }
+ case LLSLURL::LAST_LOCATION:
+ {
+ gSavedSettings.setString("LoginLocation", LLSLURL::SIM_LOCATION_LAST);
+ break;
+ }
+ default:
+ LLGridManager::getInstance()->setGridChoice(slurl.getGrid());
+ break;
+ }
+}
+
+bool login_alert_done(const LLSD& notification, const LLSD& response)
+{
+ LLPanelLogin::giveFocus();
+ return false;
+}
+
+// parse the certificate information into args for the
+// certificate notifications
+LLSD transform_cert_args(LLPointer<LLCertificate> cert)
+{
+ LLSD args = LLSD::emptyMap();
+ std::string value;
+ LLSD cert_info;
+ cert->getLLSD(cert_info);
+ // convert all of the elements in the cert into
+ // args for the xml dialog, so we have flexability to
+ // display various parts of the cert by only modifying
+ // the cert alert dialog xml.
+ for(LLSD::map_iterator iter = cert_info.beginMap();
+ iter != cert_info.endMap();
+ iter++)
+ {
+ // key usage and extended key usage
+ // are actually arrays, and we want to format them as comma separated
+ // strings, so special case those.
+ LLSDSerialize::toXML(cert_info[iter->first], std::cout);
+ if((iter->first== std::string(CERT_KEY_USAGE)) |
+ (iter->first == std::string(CERT_EXTENDED_KEY_USAGE)))
+ {
+ value = "";
+ LLSD usage = cert_info[iter->first];
+ for (LLSD::array_iterator usage_iter = usage.beginArray();
+ usage_iter != usage.endArray();
+ usage_iter++)
+ {
+
+ if(usage_iter != usage.beginArray())
+ {
+ value += ", ";
+ }
+
+ value += (*usage_iter).asString();
+ }
+
+ }
+ else
+ {
+ value = iter->second.asString();
+ }
+
+ std::string name = iter->first;
+ std::transform(name.begin(), name.end(), name.begin(),
+ (int(*)(int))toupper);
+ args[name.c_str()] = value;
+ }
+ return args;
+}
+
+
+// when we handle a cert error, give focus back to the login panel
+void general_cert_done(const LLSD& notification, const LLSD& response)
+{
+ LLStartUp::setStartupState( STATE_LOGIN_SHOW );
+ LLPanelLogin::giveFocus();
+}
+
+// check to see if the user wants to trust the cert.
+// if they do, add it to the cert store and
+void trust_cert_done(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotification::getSelectedOption(notification, response);
+ switch(option)
+ {
+ case OPT_TRUST_CERT:
+ {
+ LLPointer<LLCertificate> cert = gSecAPIHandler->getCertificate(notification["payload"]["certificate"]);
+ LLPointer<LLCertificateStore> store = gSecAPIHandler->getCertificateStore(gSavedSettings.getString("CertStore"));
+ store->add(cert);
+ store->save();
+ LLStartUp::setStartupState( STATE_LOGIN_CLEANUP );
+ break;
+ }
+ case OPT_CANCEL_TRUST:
+ reset_login();
+ gSavedSettings.setBOOL("AutoLogin", FALSE);
+ LLStartUp::setStartupState( STATE_LOGIN_SHOW );
+ default:
+ LLPanelLogin::giveFocus();
+ break;
+ }
+
+}
+
+void apply_udp_blacklist(const std::string& csv)
+{
+
+ std::string::size_type start = 0;
+ std::string::size_type comma = 0;
+ do
+ {
+ comma = csv.find(",", start);
+ if (comma == std::string::npos)
+ {
+ comma = csv.length();
+ }
+ std::string item(csv, start, comma-start);
+
+ lldebugs << "udp_blacklist " << item << llendl;
+ gMessageSystem->banUdpMessage(item);
+
+ start = comma + 1;
+
+ }
+ while(comma < csv.length());
+
+}
+
+bool process_login_success_response()
+{
+ LLSD response = LLLoginInstance::getInstance()->getResponse();
+
+ std::string text(response["udp_blacklist"]);
+ if(!text.empty())
+ {
+ apply_udp_blacklist(text);
+ }
+
+ // unpack login data needed by the application
+ text = response["agent_id"].asString();
+ if(!text.empty()) gAgentID.set(text);
+ gDebugInfo["AgentID"] = text;
+
+ // Agent id needed for parcel info request in LLUrlEntryParcel
+ // to resolve parcel name.
+ LLUrlEntryParcel::setAgentID(gAgentID);
+
+ text = response["session_id"].asString();
+ if(!text.empty()) gAgentSessionID.set(text);
+ gDebugInfo["SessionID"] = text;
+
+ // Session id needed for parcel info request in LLUrlEntryParcel
+ // to resolve parcel name.
+ LLUrlEntryParcel::setSessionID(gAgentSessionID);
+
+ text = response["secure_session_id"].asString();
+ if(!text.empty()) gAgent.mSecureSessionID.set(text);
+
+ // if the response contains a display name, use that,
+ // otherwise if the response contains a first and/or last name,
+ // use those. Otherwise use the credential identifier
+
+ gDisplayName = "";
+ if (response.has("display_name"))
+ {
+ gDisplayName.assign(response["display_name"].asString());
+ if(!gDisplayName.empty())
+ {
+ // Remove quotes from string. Login.cgi sends these to force
+ // names that look like numbers into strings.
+ LLStringUtil::replaceChar(gDisplayName, '"', ' ');
+ LLStringUtil::trim(gDisplayName);
+ }
+ }
+ if(gDisplayName.empty())
+ {
+ if(response.has("first_name"))
+ {
+ gDisplayName.assign(response["first_name"].asString());
+ LLStringUtil::replaceChar(gDisplayName, '"', ' ');
+ LLStringUtil::trim(gDisplayName);
+ }
+ if(response.has("last_name"))
+ {
+ text.assign(response["last_name"].asString());
+ LLStringUtil::replaceChar(text, '"', ' ');
+ LLStringUtil::trim(text);
+ if(!gDisplayName.empty())
+ {
+ gDisplayName += " ";
+ }
+ gDisplayName += text;
+ }
+ }
+ if(gDisplayName.empty())
+ {
+ gDisplayName.assign(gUserCredential->asString());
+ }
+
+ // this is their actual ability to access content
+ text = response["agent_access_max"].asString();
+ if (!text.empty())
+ {
+ // agent_access can be 'A', 'M', and 'PG'.
+ gAgent.setMaturity(text[0]);
+ }
+
+ // this is the value of their preference setting for that content
+ // which will always be <= agent_access_max
+ text = response["agent_region_access"].asString();
+ if (!text.empty())
+ {
+ U32 preferredMaturity = (U32)LLAgent::convertTextToMaturity(text[0]);
+
+ gSavedSettings.setU32("PreferredMaturity", preferredMaturity);
+ }
+ // During the AO transition, this flag will be true. Then the flag will
+ // go away. After the AO transition, this code and all the code that
+ // uses it can be deleted.
+ text = response["ao_transition"].asString();
+ if (!text.empty())
+ {
+ if (text == "1")
+ {
+ gAgent.setAOTransition();
+ }
+ }
+
+ text = response["start_location"].asString();
+ if(!text.empty())
+ {
+ gAgentStartLocation.assign(text);
+ }
+
+ text = response["circuit_code"].asString();
+ if(!text.empty())
+ {
+ gMessageSystem->mOurCircuitCode = strtoul(text.c_str(), NULL, 10);
+ }
+ std::string sim_ip_str = response["sim_ip"];
+ std::string sim_port_str = response["sim_port"];
+ if(!sim_ip_str.empty() && !sim_port_str.empty())
+ {
+ U32 sim_port = strtoul(sim_port_str.c_str(), NULL, 10);
+ gFirstSim.set(sim_ip_str, sim_port);
+ if (gFirstSim.isOk())
+ {
+ gMessageSystem->enableCircuit(gFirstSim, TRUE);
+ }
+ }
+ std::string region_x_str = response["region_x"];
+ std::string region_y_str = response["region_y"];
+ if(!region_x_str.empty() && !region_y_str.empty())
+ {
+ U32 region_x = strtoul(region_x_str.c_str(), NULL, 10);
+ U32 region_y = strtoul(region_y_str.c_str(), NULL, 10);
+ gFirstSimHandle = to_region_handle(region_x, region_y);
+ }
+
+ const std::string look_at_str = response["look_at"];
+ if (!look_at_str.empty())
+ {
+ size_t len = look_at_str.size();
+ LLMemoryStream mstr((U8*)look_at_str.c_str(), len);
+ LLSD sd = LLSDSerialize::fromNotation(mstr, len);
+ gAgentStartLookAt = ll_vector3_from_sd(sd);
+ }
+
+ text = response["seed_capability"].asString();
+ if (!text.empty()) gFirstSimSeedCap = text;
+
+ text = response["seconds_since_epoch"].asString();
+ if(!text.empty())
+ {
+ U32 server_utc_time = strtoul(text.c_str(), NULL, 10);
+ if(server_utc_time)
+ {
+ time_t now = time(NULL);
+ gUTCOffset = (server_utc_time - now);
+ }
+ }
+
+ // this is the base used to construct help URLs
+ text = response["help_url_format"].asString();
+ if (!text.empty())
+ {
+ // replace the default help URL format
+ gSavedSettings.setString("HelpURLFormat",text);
+
+ // don't fall back to Standalone's pre-connection static help
+ gSavedSettings.setBOOL("HelpUseLocal", false);
+ }
+
+ std::string home_location = response["home"];
+ if(!home_location.empty())
+ {
+ size_t len = home_location.size();
+ LLMemoryStream mstr((U8*)home_location.c_str(), len);
+ LLSD sd = LLSDSerialize::fromNotation(mstr, len);
+ S32 region_x = sd["region_handle"][0].asInteger();
+ S32 region_y = sd["region_handle"][1].asInteger();
+ U64 region_handle = to_region_handle(region_x, region_y);
+ LLVector3 position = ll_vector3_from_sd(sd["position"]);
+ gAgent.setHomePosRegion(region_handle, position);
+ }
+
+ gAgent.mMOTD.assign(response["message"]);
+
+ // Options...
+ // Each 'option' is an array of submaps.
+ // It appears that we only ever use the first element of the array.
+ LLUUID inv_root_folder_id = response["inventory-root"][0]["folder_id"];
+ if(inv_root_folder_id.notNull())
+ {
+ gInventory.setRootFolderID(inv_root_folder_id);
+ //gInventory.mock(gAgent.getInventoryRootID());
+ }
+
+ LLSD login_flags = response["login-flags"][0];
+ if(login_flags.size())
+ {
+ std::string flag = login_flags["ever_logged_in"];
+ if(!flag.empty())
+ {
+ gAgent.setFirstLogin((flag == "N") ? TRUE : FALSE);
+ }
+
+ /* Flag is currently ignored by the viewer.
+ flag = login_flags["stipend_since_login"];
+ if(flag == "Y")
+ {
+ stipend_since_login = true;
+ }
+ */
+
+ flag = login_flags["gendered"].asString();
+ if(flag == "Y")
+ {
+ gAgent.setGenderChosen(TRUE);
+ }
+
+ bool pacific_daylight_time = false;
+ flag = login_flags["daylight_savings"].asString();
+ if(flag == "Y")
+ {
+ pacific_daylight_time = (flag == "Y");
+ }
+
+ //setup map of datetime strings to codes and slt & local time offset from utc
+ LLStringOps::setupDatetimeInfo(pacific_daylight_time);
+ }
+
+ // set up the voice configuration. Ultimately, we should pass this up as part of each voice
+ // channel if we need to move to multiple voice servers per grid.
+ LLSD voice_config_info = response["voice-config"];
+ if(voice_config_info.has("VoiceServerType"))
+ {
+ gSavedSettings.setString("VoiceServerType", voice_config_info["VoiceServerType"].asString());
+ }
+
+ // Request the map server url
+ // Non-agni grids have a different default location.
+ if (!LLGridManager::getInstance()->isInProductionGrid())
+ {
+ gSavedSettings.setString("MapServerURL", "http://test.map.secondlife.com.s3.amazonaws.com/");
+ }
+ std::string map_server_url = response["map-server-url"];
+ if(!map_server_url.empty())
+ {
+ // We got an answer from the grid -> use that for map for the current session
+ gSavedSettings.setString("CurrentMapServerURL", map_server_url);
+ LL_INFOS("LLStartup") << "map-server-url : we got an answer from the grid : " << map_server_url << LL_ENDL;
+ }
+ else
+ {
+ // No answer from the grid -> use the default setting for current session
+ map_server_url = gSavedSettings.getString("MapServerURL");
+ gSavedSettings.setString("CurrentMapServerURL", map_server_url);
+ LL_INFOS("LLStartup") << "map-server-url : no map-server-url answer, we use the default setting for the map : " << map_server_url << LL_ENDL;
+ }
+
+ // Default male and female avatars allowing the user to choose their avatar on first login.
+ // These may be passed up by SLE to allow choice of enterprise avatars instead of the standard
+ // "new ruth." Not to be confused with 'initial-outfit' below
+ LLSD newuser_config = response["newuser-config"][0];
+ if(newuser_config.has("DefaultFemaleAvatar"))
+ {
+ gSavedSettings.setString("DefaultFemaleAvatar", newuser_config["DefaultFemaleAvatar"].asString());
+ }
+ if(newuser_config.has("DefaultMaleAvatar"))
+ {
+ gSavedSettings.setString("DefaultMaleAvatar", newuser_config["DefaultMaleAvatar"].asString());
+ }
+
+ // Initial outfit for the user.
+ // QUESTION: Why can't we simply simply set the users outfit directly
+ // from a web page into the user info on the server? - Roxie
+ LLSD initial_outfit = response["initial-outfit"][0];
+ if(initial_outfit.size())
+ {
+ std::string flag = initial_outfit["folder_name"];
+ if(!flag.empty())
+ {
+ // Initial outfit is a folder in your inventory,
+ // must be an exact folder-name match.
+ sInitialOutfit = flag;
+ }
+
+ flag = initial_outfit["gender"].asString();
+ if(!flag.empty())
+ {
+ sInitialOutfitGender = flag;
+ }
+ }
+
+ LLSD global_textures = response["global-textures"][0];
+ if(global_textures.size())
+ {
+ // Extract sun and moon texture IDs. These are used
+ // in the LLVOSky constructor, but I can't figure out
+ // how to pass them in. JC
+ LLUUID id = global_textures["sun_texture_id"];
+ if(id.notNull())
+ {
+ gSunTextureID = id;
+ }
+
+ id = global_textures["moon_texture_id"];
+ if(id.notNull())
+ {
+ gMoonTextureID = id;
+ }
+
+ id = global_textures["cloud_texture_id"];
+ if(id.notNull())
+ {
+ gCloudTextureID = id;
+ }
+ }
+
+ // Set the location of the snapshot sharing config endpoint
+ std::string snapshot_config_url = response["snapshot_config_url"];
+ if(!snapshot_config_url.empty())
+ {
+ gSavedSettings.setString("SnapshotConfigURL", snapshot_config_url);
+ }
+
+ // Start the process of fetching the OpenID session cookie for this user login
+ std::string openid_url = response["openid_url"];
+ if(!openid_url.empty())
+ {
+ std::string openid_token = response["openid_token"];
+ LLViewerMedia::openIDSetup(openid_url, openid_token);
+ }
+
+ if(response.has("max-agent-groups")) {
+ std::string max_agent_groups(response["max-agent-groups"]);
+ gMaxAgentGroups = atoi(max_agent_groups.c_str());
+ LL_INFOS("LLStartup") << "gMaxAgentGroups read from login.cgi: "
+ << gMaxAgentGroups << LL_ENDL;
+ }
+ else {
+ gMaxAgentGroups = DEFAULT_MAX_AGENT_GROUPS;
+ LL_INFOS("LLStartup") << "using gMaxAgentGroups default: "
+ << gMaxAgentGroups << LL_ENDL;
+ }
+
+ bool success = false;
+ // JC: gesture loading done below, when we have an asset system
+ // in place. Don't delete/clear gUserCredentials until then.
+ if(gAgentID.notNull()
+ && gAgentSessionID.notNull()
+ && gMessageSystem->mOurCircuitCode
+ && gFirstSim.isOk()
+ && gInventory.getRootFolderID().notNull())
+ {
+ success = true;
+ }
+
+ return success;
+}
+
+void transition_back_to_login_panel(const std::string& emsg)
+{
+ if (gNoRender)
+ {
+ LL_WARNS("AppInit") << "Failed to login!" << LL_ENDL;
+ LL_WARNS("AppInit") << emsg << LL_ENDL;
+ exit(0);
+ }
+
+ // Bounce back to the login screen.
+ reset_login(); // calls LLStartUp::setStartupState( STATE_LOGIN_SHOW );
+ gSavedSettings.setBOOL("AutoLogin", FALSE);
+}
diff --git a/indra/newview/llsurfacepatch.cpp b/indra/newview/llsurfacepatch.cpp
index 1d57e27616..5077c2c7e1 100644
--- a/indra/newview/llsurfacepatch.cpp
+++ b/indra/newview/llsurfacepatch.cpp
@@ -854,8 +854,10 @@ void LLSurfacePatch::updateVisibility()
F32 stride_per_distance = DEFAULT_DELTA_ANGLE / mSurfacep->getMetersPerGrid();
U32 grids_per_patch_edge = mSurfacep->getGridsPerPatchEdge();
- LLVector3 center = mCenterRegion + mSurfacep->getOriginAgent();
- LLVector3 radius = LLVector3(mRadius, mRadius, mRadius);
+ LLVector4a center;
+ center.load3( (mCenterRegion + mSurfacep->getOriginAgent()).mV);
+ LLVector4a radius;
+ radius.splat(mRadius);
// sphere in frustum on global coordinates
if (LLViewerCamera::getInstance()->AABBInFrustumNoFarClip(center, radius))
diff --git a/indra/newview/lltexturectrl.cpp b/indra/newview/lltexturectrl.cpp
index 56e9739350..1023a4339b 100644
--- a/indra/newview/lltexturectrl.cpp
+++ b/indra/newview/lltexturectrl.cpp
@@ -289,7 +289,9 @@ BOOL LLFloaterTexturePicker::handleDragAndDrop(
{
BOOL handled = FALSE;
- if (cargo_type == DAD_TEXTURE)
+ bool is_mesh = cargo_type == DAD_MESH;
+
+ if ((cargo_type == DAD_TEXTURE) || is_mesh)
{
LLInventoryItem *item = (LLInventoryItem *)cargo_data;
@@ -1206,7 +1208,11 @@ BOOL LLTextureCtrl::handleDragAndDrop(S32 x, S32 y, MASK mask,
// returns true, then the cast was valid, and we can perform
// the third test without problems.
LLInventoryItem* item = (LLInventoryItem*)cargo_data;
- if (getEnabled() && (cargo_type == DAD_TEXTURE) && allowDrop(item))
+ bool is_mesh = cargo_type == DAD_MESH;
+
+ if (getEnabled() &&
+ ((cargo_type == DAD_TEXTURE) || is_mesh) &&
+ allowDrop(item))
{
if (drop)
{
diff --git a/indra/newview/lltooldraganddrop.cpp b/indra/newview/lltooldraganddrop.cpp
index 1c745906aa..fbd6aad18f 100644
--- a/indra/newview/lltooldraganddrop.cpp
+++ b/indra/newview/lltooldraganddrop.cpp
@@ -308,23 +308,24 @@ LLToolDragAndDrop::dragOrDrop3dImpl LLToolDragAndDrop::LLDragAndDropDictionary::
LLToolDragAndDrop::LLDragAndDropDictionary::LLDragAndDropDictionary()
{
- // DT_NONE DT_SELF DT_AVATAR DT_OBJECT DT_LAND
- // |--------------|---------------------------|---------------------------|-------------------------------|--------------|
+ // DT_NONE DT_SELF DT_AVATAR DT_OBJECT DT_LAND
+ // |-------------------------------|----------------------------------------------|-----------------------------------------------|---------------------------------------------------|--------------------------------|
addEntry(DAD_NONE, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL));
- addEntry(DAD_TEXTURE, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dTextureObject, &LLToolDragAndDrop::dad3dNULL));
- addEntry(DAD_SOUND, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_TEXTURE, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dTextureObject, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_SOUND, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
addEntry(DAD_CALLINGCARD, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
- addEntry(DAD_LANDMARK, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
- addEntry(DAD_SCRIPT, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dRezScript, &LLToolDragAndDrop::dad3dNULL));
- addEntry(DAD_CLOTHING, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dWearItem, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
- addEntry(DAD_OBJECT, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dRezAttachmentFromInv, &LLToolDragAndDrop::dad3dGiveInventoryObject, &LLToolDragAndDrop::dad3dRezObjectOnObject, &LLToolDragAndDrop::dad3dRezObjectOnLand));
- addEntry(DAD_NOTECARD, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
- addEntry(DAD_CATEGORY, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dWearCategory, &LLToolDragAndDrop::dad3dGiveInventoryCategory,&LLToolDragAndDrop::dad3dUpdateInventoryCategory, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_LANDMARK, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_SCRIPT, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dRezScript, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_CLOTHING, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dWearItem, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_OBJECT, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dRezAttachmentFromInv, &LLToolDragAndDrop::dad3dGiveInventoryObject, &LLToolDragAndDrop::dad3dRezObjectOnObject, &LLToolDragAndDrop::dad3dRezObjectOnLand));
+ addEntry(DAD_NOTECARD, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_CATEGORY, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dWearCategory, &LLToolDragAndDrop::dad3dGiveInventoryCategory, &LLToolDragAndDrop::dad3dUpdateInventoryCategory, &LLToolDragAndDrop::dad3dNULL));
addEntry(DAD_ROOT_CATEGORY, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL));
- addEntry(DAD_BODYPART, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dWearItem, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
- addEntry(DAD_ANIMATION, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
- addEntry(DAD_GESTURE, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dActivateGesture, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_BODYPART, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dWearItem, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_ANIMATION, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_GESTURE, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dActivateGesture, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dUpdateInventory, &LLToolDragAndDrop::dad3dNULL));
addEntry(DAD_LINK, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL));
+ addEntry(DAD_MESH, new DragAndDropEntry(&LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dNULL, &LLToolDragAndDrop::dad3dGiveInventory, &LLToolDragAndDrop::dad3dMeshObject, &LLToolDragAndDrop::dad3dNULL));
// TODO: animation on self could play it? edit it?
// TODO: gesture on self could play it? edit it?
};
@@ -397,7 +398,7 @@ void LLToolDragAndDrop::beginDrag(EDragAndDropType type,
{
folder_ids.push_back(cargo_id);
}
- gInventory.collectDescendentsIf (
+ gInventory.collectDescendentsIf(
cargo_id,
cats,
items,
@@ -468,7 +469,7 @@ void LLToolDragAndDrop::beginMultiDrag(
{
cat_ids.insert(cat->getUUID());
}
- gInventory.collectDescendentsIf (
+ gInventory.collectDescendentsIf(
cat->getUUID(),
cats,
items,
@@ -1028,6 +1029,31 @@ void LLToolDragAndDrop::dropTextureAllFaces(LLViewerObject* hit_obj,
hit_obj->sendTEUpdate();
}
+void LLToolDragAndDrop::dropMesh(LLViewerObject* hit_obj,
+ LLInventoryItem* item,
+ LLToolDragAndDrop::ESource source,
+ const LLUUID& src_id)
+{
+ if (!item)
+ {
+ llwarns << "no inventory item." << llendl;
+ return;
+ }
+ LLUUID asset_id = item->getAssetUUID();
+ BOOL success = handleDropTextureProtections(hit_obj, item, source, src_id);
+ if(!success)
+ {
+ return;
+ }
+
+ LLSculptParams sculpt_params;
+ sculpt_params.setSculptTexture(asset_id);
+ sculpt_params.setSculptType(LL_SCULPT_TYPE_MESH);
+ hit_obj->setParameterEntry(LLNetworkData::PARAMS_SCULPT, sculpt_params, TRUE);
+
+ dialog_refresh_all();
+}
+
/*
void LLToolDragAndDrop::dropTextureOneFaceAvatar(LLVOAvatar* avatar, S32 hit_face, LLInventoryItem* item)
{
@@ -1124,9 +1150,9 @@ void LLToolDragAndDrop::dropScript(LLViewerObject* hit_obj,
}
void LLToolDragAndDrop::dropObject(LLViewerObject* raycast_target,
- BOOL bypass_sim_raycast,
- BOOL from_task_inventory,
- BOOL remove_from_inventory)
+ BOOL bypass_sim_raycast,
+ BOOL from_task_inventory,
+ BOOL remove_from_inventory)
{
LLViewerRegion* regionp = LLWorld::getInstance()->getRegionFromPosGlobal(mLastHitPos);
if (!regionp)
@@ -1362,7 +1388,7 @@ EAcceptance LLToolDragAndDrop::willObjectAcceptInventory(LLViewerObject* obj, LL
// help make sure that drops that are from an object to an object
// don't have to worry about order of evaluation. Think of this
// like check for self in assignment.
- if (obj->getID() == item->getParentUUID())
+ if(obj->getID() == item->getParentUUID())
{
return ACCEPT_NO;
}
@@ -1371,17 +1397,19 @@ EAcceptance LLToolDragAndDrop::willObjectAcceptInventory(LLViewerObject* obj, LL
// gAgent.getGroupID())
// && (obj->mPermModify || obj->mFlagAllowInventoryAdd));
BOOL worn = FALSE;
+ LLVOAvatarSelf* my_avatar = NULL;
switch(item->getType())
{
case LLAssetType::AT_OBJECT:
- if (isAgentAvatarValid() && gAgentAvatarp->isWearingAttachment(item->getUUID()))
+ my_avatar = gAgentAvatarp;
+ if(my_avatar && my_avatar->isWearingAttachment(item->getUUID()))
{
worn = TRUE;
}
break;
case LLAssetType::AT_BODYPART:
case LLAssetType::AT_CLOTHING:
- if (gAgentWearables.isWearingItem(item->getUUID()))
+ if(gAgentWearables.isWearingItem(item->getUUID()))
{
worn = TRUE;
}
@@ -1392,7 +1420,7 @@ EAcceptance LLToolDragAndDrop::willObjectAcceptInventory(LLViewerObject* obj, LL
const LLPermissions& perm = item->getPermissions();
BOOL modify = (obj->permModify() || obj->flagAllowInventoryAdd());
BOOL transfer = FALSE;
- if ((obj->permYouOwner() && (perm.getOwner() == gAgent.getID()))
+ if((obj->permYouOwner() && (perm.getOwner() == gAgent.getID()))
|| perm.allowOperationBy(PERM_TRANSFER, gAgent.getID()))
{
transfer = TRUE;
@@ -1400,15 +1428,15 @@ EAcceptance LLToolDragAndDrop::willObjectAcceptInventory(LLViewerObject* obj, LL
BOOL volume = (LL_PCODE_VOLUME == obj->getPCode());
BOOL attached = obj->isAttachment();
BOOL unrestricted = ((perm.getMaskBase() & PERM_ITEM_UNRESTRICTED) == PERM_ITEM_UNRESTRICTED) ? TRUE : FALSE;
- if (attached && !unrestricted)
+ if(attached && !unrestricted)
{
return ACCEPT_NO_LOCKED;
}
- else if (modify && transfer && volume && !worn)
+ else if(modify && transfer && volume && !worn)
{
return ACCEPT_YES_MULTI;
}
- else if (!modify)
+ else if(!modify)
{
return ACCEPT_NO_LOCKED;
}
@@ -1503,14 +1531,15 @@ bool LLToolDragAndDrop::handleGiveDragAndDrop(LLUUID dest_agent, LLUUID session_
case DAD_ANIMATION:
case DAD_GESTURE:
case DAD_CALLINGCARD:
+ case DAD_MESH:
{
LLViewerInventoryItem* inv_item = (LLViewerInventoryItem*)cargo_data;
- if (gInventory.getItem(inv_item->getUUID())
+ if(gInventory.getItem(inv_item->getUUID())
&& LLGiveInventory::isInventoryGiveAcceptable(inv_item))
{
// *TODO: get multiple object transfers working
*accept = ACCEPT_YES_COPY_SINGLE;
- if (drop)
+ if(drop)
{
LLIMModel::LLIMSession * session = LLIMModel::instance().findIMSession(session_id);
@@ -1550,11 +1579,11 @@ bool LLToolDragAndDrop::handleGiveDragAndDrop(LLUUID dest_agent, LLUUID session_
case DAD_CATEGORY:
{
LLViewerInventoryCategory* inv_cat = (LLViewerInventoryCategory*)cargo_data;
- if (gInventory.getCategory(inv_cat->getUUID()))
+ if( gInventory.getCategory( inv_cat->getUUID() ) )
{
// *TODO: get multiple object transfers working
*accept = ACCEPT_YES_COPY_SINGLE;
- if (drop)
+ if(drop)
{
LLGiveInventory::doGiveInventoryCategory(dest_agent, inv_cat, session_id);
}
@@ -1595,7 +1624,7 @@ EAcceptance LLToolDragAndDrop::dad3dRezAttachmentFromInv(
{
lldebugs << "LLToolDragAndDrop::dad3dRezAttachmentFromInv()" << llendl;
// must be in the user's inventory
- if (mSource != SOURCE_AGENT && mSource != SOURCE_LIBRARY)
+ if(mSource != SOURCE_AGENT && mSource != SOURCE_LIBRARY)
{
return ACCEPT_NO;
}
@@ -1607,20 +1636,21 @@ EAcceptance LLToolDragAndDrop::dad3dRezAttachmentFromInv(
// must not be in the trash
const LLUUID trash_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
- if (gInventory.isObjectDescendentOf(item->getUUID(), trash_id))
+ if( gInventory.isObjectDescendentOf( item->getUUID(), trash_id ) )
{
return ACCEPT_NO;
}
// must not be already wearing it
- if (!isAgentAvatarValid() || gAgentAvatarp->isWearingAttachment(item->getUUID()))
+ LLVOAvatarSelf* avatar = gAgentAvatarp;
+ if( !avatar || avatar->isWearingAttachment(item->getUUID()) )
{
return ACCEPT_NO;
}
- if (drop)
+ if( drop )
{
- if (mSource == SOURCE_LIBRARY)
+ if(mSource == SOURCE_LIBRARY)
{
LLPointer<LLInventoryCallback> cb = new RezAttachmentCallback(0);
copy_inventory_item(
@@ -1654,7 +1684,8 @@ EAcceptance LLToolDragAndDrop::dad3dRezObjectOnLand(
locateInventory(item, cat);
if (!item || !item->isFinished()) return ACCEPT_NO;
- if (!isAgentAvatarValid() || gAgentAvatarp->isWearingAttachment(item->getUUID()))
+ LLVOAvatarSelf* my_avatar = gAgentAvatarp;
+ if( !my_avatar || my_avatar->isWearingAttachment( item->getUUID() ) )
{
return ACCEPT_NO;
}
@@ -1679,7 +1710,7 @@ EAcceptance LLToolDragAndDrop::dad3dRezObjectOnLand(
// check if the item can be copied. If not, send that to the sim
// which will remove the inventory item.
- if (!item->getPermissions().allowCopyBy(gAgent.getID()))
+ if(!item->getPermissions().allowCopyBy(gAgent.getID()))
{
accept = ACCEPT_YES_SINGLE;
remove_inventory = TRUE;
@@ -1687,13 +1718,13 @@ EAcceptance LLToolDragAndDrop::dad3dRezObjectOnLand(
// Check if it's in the trash.
const LLUUID trash_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
- if (gInventory.isObjectDescendentOf(item->getUUID(), trash_id))
+ if(gInventory.isObjectDescendentOf(item->getUUID(), trash_id))
{
accept = ACCEPT_YES_SINGLE;
remove_inventory = TRUE;
}
- if (drop)
+ if(drop)
{
dropObject(obj, TRUE, FALSE, remove_inventory);
}
@@ -1715,22 +1746,23 @@ EAcceptance LLToolDragAndDrop::dad3dRezObjectOnObject(
LLViewerInventoryCategory* cat;
locateInventory(item, cat);
if (!item || !item->isFinished()) return ACCEPT_NO;
- if (!isAgentAvatarValid() || gAgentAvatarp->isWearingAttachment(item->getUUID()))
+ LLVOAvatarSelf* my_avatar = gAgentAvatarp;
+ if( !my_avatar || my_avatar->isWearingAttachment( item->getUUID() ) )
{
return ACCEPT_NO;
}
- if ((mask & MASK_CONTROL))
+ if((mask & MASK_CONTROL))
{
// *HACK: In order to resolve SL-22177, we need to block drags
// from notecards and objects onto other objects.
- if (mSource == SOURCE_NOTECARD)
+ if(mSource == SOURCE_NOTECARD)
{
return ACCEPT_NO;
}
EAcceptance rv = willObjectAcceptInventory(obj, item);
- if (drop && (ACCEPT_YES_SINGLE <= rv))
+ if(drop && (ACCEPT_YES_SINGLE <= rv))
{
dropInventory(obj, item, mSource, mSourceID);
}
@@ -1756,7 +1788,7 @@ EAcceptance LLToolDragAndDrop::dad3dRezObjectOnObject(
// check if the item can be copied. If not, send that to the sim
// which will remove the inventory item.
- if (!item->getPermissions().allowCopyBy(gAgent.getID()))
+ if(!item->getPermissions().allowCopyBy(gAgent.getID()))
{
accept = ACCEPT_YES_SINGLE;
remove_inventory = TRUE;
@@ -1764,13 +1796,13 @@ EAcceptance LLToolDragAndDrop::dad3dRezObjectOnObject(
// Check if it's in the trash.
const LLUUID trash_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
- if (gInventory.isObjectDescendentOf(item->getUUID(), trash_id))
+ if(gInventory.isObjectDescendentOf(item->getUUID(), trash_id))
{
accept = ACCEPT_YES_SINGLE;
remove_inventory = TRUE;
}
- if (drop)
+ if(drop)
{
dropObject(obj, FALSE, FALSE, remove_inventory);
}
@@ -1785,7 +1817,7 @@ EAcceptance LLToolDragAndDrop::dad3dRezScript(
// *HACK: In order to resolve SL-22177, we need to block drags
// from notecards and objects onto other objects.
- if ((SOURCE_WORLD == mSource) || (SOURCE_NOTECARD == mSource))
+ if((SOURCE_WORLD == mSource) || (SOURCE_NOTECARD == mSource))
{
return ACCEPT_NO;
}
@@ -1795,7 +1827,7 @@ EAcceptance LLToolDragAndDrop::dad3dRezScript(
locateInventory(item, cat);
if (!item || !item->isFinished()) return ACCEPT_NO;
EAcceptance rv = willObjectAcceptInventory(obj, item);
- if (drop && (ACCEPT_YES_SINGLE <= rv))
+ if(drop && (ACCEPT_YES_SINGLE <= rv))
{
// rez in the script active by default, rez in inactive if the
// control key is being held down.
@@ -1816,14 +1848,14 @@ EAcceptance LLToolDragAndDrop::dad3dRezScript(
return rv;
}
-EAcceptance LLToolDragAndDrop::dad3dTextureObject(
- LLViewerObject* obj, S32 face, MASK mask, BOOL drop)
+EAcceptance LLToolDragAndDrop::dad3dApplyToObject(
+ LLViewerObject* obj, S32 face, MASK mask, BOOL drop, EDragAndDropType cargo_type)
{
- lldebugs << "LLToolDragAndDrop::dad3dTextureObject()" << llendl;
+ lldebugs << "LLToolDragAndDrop::dad3dApplyToObject()" << llendl;
// *HACK: In order to resolve SL-22177, we need to block drags
// from notecards and objects onto other objects.
- if ((SOURCE_WORLD == mSource) || (SOURCE_NOTECARD == mSource))
+ if((SOURCE_WORLD == mSource) || (SOURCE_NOTECARD == mSource))
{
return ACCEPT_NO;
}
@@ -1833,33 +1865,44 @@ EAcceptance LLToolDragAndDrop::dad3dTextureObject(
locateInventory(item, cat);
if (!item || !item->isFinished()) return ACCEPT_NO;
EAcceptance rv = willObjectAcceptInventory(obj, item);
- if ((mask & MASK_CONTROL))
+ if((mask & MASK_CONTROL))
{
- if ((ACCEPT_YES_SINGLE <= rv) && drop)
+ if((ACCEPT_YES_SINGLE <= rv) && drop)
{
dropInventory(obj, item, mSource, mSourceID);
}
return rv;
}
- if (!obj->permModify())
+ if(!obj->permModify())
{
return ACCEPT_NO_LOCKED;
}
//If texture !copyable don't texture or you'll never get it back.
- if (!item->getPermissions().allowCopyBy(gAgent.getID()))
+ if(!item->getPermissions().allowCopyBy(gAgent.getID()))
{
return ACCEPT_NO;
}
- if (drop && (ACCEPT_YES_SINGLE <= rv))
+ if(drop && (ACCEPT_YES_SINGLE <= rv))
{
- if ((mask & MASK_SHIFT))
+ if (cargo_type == DAD_TEXTURE)
{
- dropTextureAllFaces(obj, item, mSource, mSourceID);
+ if((mask & MASK_SHIFT))
+ {
+ dropTextureAllFaces(obj, item, mSource, mSourceID);
+ }
+ else
+ {
+ dropTextureOneFace(obj, face, item, mSource, mSourceID);
+ }
+ }
+ else if (cargo_type == DAD_MESH)
+ {
+ dropMesh(obj, item, mSource, mSourceID);
}
else
{
- dropTextureOneFace(obj, face, item, mSource, mSourceID);
+ llwarns << "unsupported asset type" << llendl;
}
// VEFFECT: SetTexture
@@ -1873,14 +1916,29 @@ EAcceptance LLToolDragAndDrop::dad3dTextureObject(
// enable multi-drop, although last texture will win
return ACCEPT_YES_MULTI;
}
+
+
+EAcceptance LLToolDragAndDrop::dad3dTextureObject(
+ LLViewerObject* obj, S32 face, MASK mask, BOOL drop)
+{
+ return dad3dApplyToObject(obj, face, mask, drop, DAD_TEXTURE);
+}
+
+EAcceptance LLToolDragAndDrop::dad3dMeshObject(
+ LLViewerObject* obj, S32 face, MASK mask, BOOL drop)
+{
+ return dad3dApplyToObject(obj, face, mask, drop, DAD_MESH);
+}
+
+
/*
EAcceptance LLToolDragAndDrop::dad3dTextureSelf(
LLViewerObject* obj, S32 face, MASK mask, BOOL drop)
{
lldebugs << "LLToolDragAndDrop::dad3dTextureAvatar()" << llendl;
- if (drop)
+ if(drop)
{
- if (!(mask & MASK_SHIFT))
+ if( !(mask & MASK_SHIFT) )
{
dropTextureOneFaceAvatar( (LLVOAvatar*)obj, face, (LLInventoryItem*)mCargoData);
}
@@ -1898,16 +1956,16 @@ EAcceptance LLToolDragAndDrop::dad3dWearItem(
locateInventory(item, cat);
if (!item || !item->isFinished()) return ACCEPT_NO;
- if (mSource == SOURCE_AGENT || mSource == SOURCE_LIBRARY)
+ if(mSource == SOURCE_AGENT || mSource == SOURCE_LIBRARY)
{
// it's in the agent inventory
const LLUUID trash_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
- if (gInventory.isObjectDescendentOf(item->getUUID(), trash_id))
+ if( gInventory.isObjectDescendentOf( item->getUUID(), trash_id ) )
{
return ACCEPT_NO;
}
- if (drop)
+ if( drop )
{
// TODO: investigate wearables may not be loaded at this point EXT-8231
@@ -1931,19 +1989,19 @@ EAcceptance LLToolDragAndDrop::dad3dActivateGesture(
locateInventory(item, cat);
if (!item || !item->isFinished()) return ACCEPT_NO;
- if (mSource == SOURCE_AGENT || mSource == SOURCE_LIBRARY)
+ if(mSource == SOURCE_AGENT || mSource == SOURCE_LIBRARY)
{
// it's in the agent inventory
const LLUUID trash_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
- if (gInventory.isObjectDescendentOf(item->getUUID(), trash_id))
+ if( gInventory.isObjectDescendentOf( item->getUUID(), trash_id ) )
{
return ACCEPT_NO;
}
- if (drop)
+ if( drop )
{
LLUUID item_id;
- if (mSource == SOURCE_LIBRARY)
+ if(mSource == SOURCE_LIBRARY)
{
// create item based on that one, and put it on if that
// was a success.
@@ -1978,31 +2036,31 @@ EAcceptance LLToolDragAndDrop::dad3dWearCategory(
LLViewerInventoryItem* item;
LLViewerInventoryCategory* category;
locateInventory(item, category);
- if (!category) return ACCEPT_NO;
+ if(!category) return ACCEPT_NO;
if (drop)
{
// TODO: investigate wearables may not be loaded at this point EXT-8231
}
- if (mSource == SOURCE_AGENT)
+ if(mSource == SOURCE_AGENT)
{
const LLUUID trash_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
- if (gInventory.isObjectDescendentOf(category->getUUID(), trash_id))
+ if( gInventory.isObjectDescendentOf( category->getUUID(), trash_id ) )
{
return ACCEPT_NO;
}
- if (drop)
+ if(drop)
{
- BOOL append = ( (mask & MASK_SHIFT) ? TRUE : FALSE );
+ BOOL append = ( (mask & MASK_SHIFT) ? TRUE : FALSE );
LLAppearanceMgr::instance().wearInventoryCategory(category, false, append);
}
return ACCEPT_YES_MULTI;
}
- else if (mSource == SOURCE_LIBRARY)
+ else if(mSource == SOURCE_LIBRARY)
{
- if (drop)
+ if(drop)
{
LLAppearanceMgr::instance().wearInventoryCategory(category, true, false);
}
@@ -2023,7 +2081,7 @@ EAcceptance LLToolDragAndDrop::dad3dUpdateInventory(
// *HACK: In order to resolve SL-22177, we need to block drags
// from notecards and objects onto other objects.
- if ((SOURCE_WORLD == mSource) || (SOURCE_NOTECARD == mSource))
+ if((SOURCE_WORLD == mSource) || (SOURCE_NOTECARD == mSource))
{
return ACCEPT_NO;
}
@@ -2043,7 +2101,7 @@ EAcceptance LLToolDragAndDrop::dad3dUpdateInventory(
}
EAcceptance rv = willObjectAcceptInventory(root_object, item);
- if (root_object && drop && (ACCEPT_YES_COPY_SINGLE <= rv))
+ if(root_object && drop && (ACCEPT_YES_COPY_SINGLE <= rv))
{
dropInventory(root_object, item, mSource, mSourceID);
}
@@ -2087,7 +2145,7 @@ EAcceptance LLToolDragAndDrop::dad3dUpdateInventoryCategory(
LLDroppableItem droppable(!obj->permYouOwner());
LLInventoryModel::cat_array_t cats;
LLInventoryModel::item_array_t items;
- gInventory.collectDescendentsIf (cat->getUUID(),
+ gInventory.collectDescendentsIf(cat->getUUID(),
cats,
items,
LLInventoryModel::EXCLUDE_TRASH,
@@ -2116,7 +2174,7 @@ EAcceptance LLToolDragAndDrop::dad3dUpdateInventoryCategory(
{
const LLViewerInventoryCategory *cat = (*cat_iter);
rv = gInventory.isCategoryComplete(cat->getUUID()) ? ACCEPT_YES_MULTI : ACCEPT_NO;
- if (rv < ACCEPT_YES_SINGLE)
+ if(rv < ACCEPT_YES_SINGLE)
{
lldebugs << "Category " << cat->getUUID() << "is not complete." << llendl;
break;
@@ -2184,26 +2242,27 @@ EAcceptance LLToolDragAndDrop::dad3dGiveInventoryObject(
lldebugs << "LLToolDragAndDrop::dad3dGiveInventoryObject()" << llendl;
// item has to be in agent inventory.
- if (mSource != SOURCE_AGENT) return ACCEPT_NO;
+ if(mSource != SOURCE_AGENT) return ACCEPT_NO;
// find the item now.
LLViewerInventoryItem* item;
LLViewerInventoryCategory* cat;
locateInventory(item, cat);
if (!item || !item->isFinished()) return ACCEPT_NO;
- if (!item->getPermissions().allowOperationBy(PERM_TRANSFER, gAgent.getID()))
+ if(!item->getPermissions().allowOperationBy(PERM_TRANSFER, gAgent.getID()))
{
// cannot give away no-transfer objects
return ACCEPT_NO;
}
- if (isAgentAvatarValid() && gAgentAvatarp->isWearingAttachment(item->getUUID()))
+ LLVOAvatarSelf* avatar = gAgentAvatarp;
+ if(avatar && avatar->isWearingAttachment( item->getUUID() ) )
{
// You can't give objects that are attached to you
return ACCEPT_NO;
}
- if (obj && isAgentAvatarValid())
+ if( obj && avatar )
{
- if (drop)
+ if(drop)
{
LLGiveInventory::doGiveInventoryItem(obj->getID(), item );
}
@@ -2220,7 +2279,7 @@ EAcceptance LLToolDragAndDrop::dad3dGiveInventory(
{
lldebugs << "LLToolDragAndDrop::dad3dGiveInventory()" << llendl;
// item has to be in agent inventory.
- if (mSource != SOURCE_AGENT) return ACCEPT_NO;
+ if(mSource != SOURCE_AGENT) return ACCEPT_NO;
LLViewerInventoryItem* item;
LLViewerInventoryCategory* cat;
locateInventory(item, cat);
@@ -2242,12 +2301,12 @@ EAcceptance LLToolDragAndDrop::dad3dGiveInventoryCategory(
LLViewerObject* obj, S32 face, MASK mask, BOOL drop)
{
lldebugs << "LLToolDragAndDrop::dad3dGiveInventoryCategory()" << llendl;
- if (drop && obj)
+ if(drop && obj)
{
LLViewerInventoryItem* item;
LLViewerInventoryCategory* cat;
locateInventory(item, cat);
- if (!cat) return ACCEPT_NO;
+ if(!cat) return ACCEPT_NO;
LLGiveInventory::doGiveInventoryCategory(obj->getID(), cat);
}
// *TODO: deal with all the issues surrounding multi-object
@@ -2265,12 +2324,12 @@ EAcceptance LLToolDragAndDrop::dad3dRezFromObjectOnLand(
locateInventory(item, cat);
if (!item || !item->isFinished()) return ACCEPT_NO;
- if (!gAgent.allowOperation(PERM_COPY, item->getPermissions())
+ if(!gAgent.allowOperation(PERM_COPY, item->getPermissions())
|| !item->getPermissions().allowTransferTo(LLUUID::null))
{
return ACCEPT_NO_LOCKED;
}
- if (drop)
+ if(drop)
{
dropObject(obj, TRUE, TRUE, FALSE);
}
@@ -2285,7 +2344,7 @@ EAcceptance LLToolDragAndDrop::dad3dRezFromObjectOnObject(
LLViewerInventoryCategory* cat;
locateInventory(item, cat);
if (!item || !item->isFinished()) return ACCEPT_NO;
- if ((mask & MASK_CONTROL))
+ if((mask & MASK_CONTROL))
{
// *HACK: In order to resolve SL-22177, we need to block drags
// from notecards and objects onto other objects.
@@ -2293,19 +2352,19 @@ EAcceptance LLToolDragAndDrop::dad3dRezFromObjectOnObject(
// *HACK: uncomment this when appropriate
//EAcceptance rv = willObjectAcceptInventory(obj, item);
- //if (drop && (ACCEPT_YES_SINGLE <= rv))
+ //if(drop && (ACCEPT_YES_SINGLE <= rv))
//{
// dropInventory(obj, item, mSource, mSourceID);
//}
//return rv;
}
- if (!item->getPermissions().allowCopyBy(gAgent.getID(),
+ if(!item->getPermissions().allowCopyBy(gAgent.getID(),
gAgent.getGroupID())
|| !item->getPermissions().allowTransferTo(LLUUID::null))
{
return ACCEPT_NO_LOCKED;
}
- if (drop)
+ if(drop)
{
dropObject(obj, FALSE, TRUE, FALSE);
}
@@ -2321,23 +2380,23 @@ EAcceptance LLToolDragAndDrop::dad3dCategoryOnLand(
LLInventoryItem* item;
LLInventoryCategory* cat;
locateInventory(item, cat);
- if (!cat) return ACCEPT_NO;
+ if(!cat) return ACCEPT_NO;
EAcceptance rv = ACCEPT_NO;
// find all the items in the category
LLViewerInventoryCategory::cat_array_t cats;
LLViewerInventoryItem::item_array_t items;
LLDropCopyableItems droppable;
- gInventory.collectDescendentsIf (cat->getUUID(),
+ gInventory.collectDescendentsIf(cat->getUUID(),
cats,
items,
LLInventoryModel::EXCLUDE_TRASH,
droppable);
- if (items.count() > 0)
+ if(items.count() > 0)
{
rv = ACCEPT_YES_SINGLE;
}
- if ((rv >= ACCEPT_YES_COPY_SINGLE) && drop)
+ if((rv >= ACCEPT_YES_COPY_SINGLE) && drop)
{
createContainer(items, cat->getName());
return ACCEPT_NO;
@@ -2360,19 +2419,19 @@ EAcceptance LLToolDragAndDrop::dad3dAssetOnLand(
LLViewerInventoryItem::item_array_t items;
LLViewerInventoryItem::item_array_t copyable_items;
locateMultipleInventory(items, cats);
- if (!items.count()) return ACCEPT_NO;
+ if(!items.count()) return ACCEPT_NO;
EAcceptance rv = ACCEPT_NO;
for (S32 i = 0; i < items.count(); i++)
{
LLInventoryItem* item = items[i];
- if (item->getPermissions().allowCopyBy(gAgent.getID()))
+ if(item->getPermissions().allowCopyBy(gAgent.getID()))
{
copyable_items.put(item);
rv = ACCEPT_YES_SINGLE;
}
}
- if ((rv >= ACCEPT_YES_COPY_SINGLE) && drop)
+ if((rv >= ACCEPT_YES_COPY_SINGLE) && drop)
{
createContainer(copyable_items, NULL);
}
@@ -2387,20 +2446,20 @@ LLInventoryObject* LLToolDragAndDrop::locateInventory(
{
item = NULL;
cat = NULL;
- if (mCargoIDs.empty()) return NULL;
- if ((mSource == SOURCE_AGENT) || (mSource == SOURCE_LIBRARY))
+ if(mCargoIDs.empty()) return NULL;
+ if((mSource == SOURCE_AGENT) || (mSource == SOURCE_LIBRARY))
{
// The object should be in user inventory.
item = (LLViewerInventoryItem*)gInventory.getItem(mCargoIDs[mCurItemIndex]);
cat = (LLViewerInventoryCategory*)gInventory.getCategory(mCargoIDs[mCurItemIndex]);
}
- else if (mSource == SOURCE_WORLD)
+ else if(mSource == SOURCE_WORLD)
{
// This object is in some task inventory somewhere.
LLViewerObject* obj = gObjectList.findObject(mSourceID);
- if (obj)
+ if(obj)
{
- if ((mCargoTypes[mCurItemIndex] == DAD_CATEGORY)
+ if((mCargoTypes[mCurItemIndex] == DAD_CATEGORY)
|| (mCargoTypes[mCurItemIndex] == DAD_ROOT_CATEGORY))
{
cat = (LLViewerInventoryCategory*)obj->getInventoryObject(mCargoIDs[mCurItemIndex]);
@@ -2411,16 +2470,16 @@ LLInventoryObject* LLToolDragAndDrop::locateInventory(
}
}
}
- else if (mSource == SOURCE_NOTECARD)
+ else if(mSource == SOURCE_NOTECARD)
{
LLPreviewNotecard* preview = LLFloaterReg::findTypedInstance<LLPreviewNotecard>("preview_notecard", mSourceID);
- if (preview)
+ if(preview)
{
item = (LLViewerInventoryItem*)preview->getDragItem();
}
}
- if (item) return item;
- if (cat) return cat;
+ if(item) return item;
+ if(cat) return cat;
return NULL;
}
@@ -2428,8 +2487,8 @@ LLInventoryObject* LLToolDragAndDrop::locateInventory(
LLInventoryObject* LLToolDragAndDrop::locateMultipleInventory(LLViewerInventoryCategory::cat_array_t& cats,
LLViewerInventoryItem::item_array_t& items)
{
- if (mCargoIDs.count() == 0) return NULL;
- if ((mSource == SOURCE_AGENT) || (mSource == SOURCE_LIBRARY))
+ if(mCargoIDs.count() == 0) return NULL;
+ if((mSource == SOURCE_AGENT) || (mSource == SOURCE_LIBRARY))
{
// The object should be in user inventory.
for (S32 i = 0; i < mCargoIDs.count(); i++)
@@ -2446,13 +2505,13 @@ LLInventoryObject* LLToolDragAndDrop::locateMultipleInventory(LLViewerInventoryC
}
}
}
- else if (mSource == SOURCE_WORLD)
+ else if(mSource == SOURCE_WORLD)
{
// This object is in some task inventory somewhere.
LLViewerObject* obj = gObjectList.findObject(mSourceID);
- if (obj)
+ if(obj)
{
- if ((mCargoType == DAD_CATEGORY)
+ if((mCargoType == DAD_CATEGORY)
|| (mCargoType == DAD_ROOT_CATEGORY))
{
// The object should be in user inventory.
@@ -2478,17 +2537,17 @@ LLInventoryObject* LLToolDragAndDrop::locateMultipleInventory(LLViewerInventoryC
}
}
}
- else if (mSource == SOURCE_NOTECARD)
+ else if(mSource == SOURCE_NOTECARD)
{
LLPreviewNotecard* card;
card = (LLPreviewNotecard*)LLPreview::find(mSourceID);
- if (card)
+ if(card)
{
items.put((LLInventoryItem*)card->getDragItem());
}
}
- if (items.count()) return items[0];
- if (cats.count()) return cats[0];
+ if(items.count()) return items[0];
+ if(cats.count()) return cats[0];
return NULL;
}
*/
diff --git a/indra/newview/lltooldraganddrop.h b/indra/newview/lltooldraganddrop.h
index a13b775699..7b8cce3dc7 100644
--- a/indra/newview/lltooldraganddrop.h
+++ b/indra/newview/lltooldraganddrop.h
@@ -148,6 +148,8 @@ protected:
MASK mask, BOOL drop);
EAcceptance dad3dTextureObject(LLViewerObject* obj, S32 face,
MASK mask, BOOL drop);
+ EAcceptance dad3dMeshObject(LLViewerObject* obj, S32 face,
+ MASK mask, BOOL drop);
// EAcceptance dad3dTextureSelf(LLViewerObject* obj, S32 face,
// MASK mask, BOOL drop);
EAcceptance dad3dWearItem(LLViewerObject* obj, S32 face,
@@ -179,6 +181,11 @@ protected:
EAcceptance dad3dActivateGesture(LLViewerObject *obj, S32 face,
MASK mask, BOOL drop);
+ // helper called by methods above to handle "application" of an item
+ // to an object (texture applied to face, mesh applied to shape, etc.)
+ EAcceptance dad3dApplyToObject(LLViewerObject* obj, S32 face, MASK mask, BOOL drop, EDragAndDropType cargo_type);
+
+
// set the LLToolDragAndDrop's cursor based on the given acceptance
ECursorType acceptanceToCursor( EAcceptance acceptance );
@@ -229,6 +236,11 @@ public:
LLInventoryItem* item,
ESource source,
const LLUUID& src_id);
+ static void dropMesh(LLViewerObject* hit_obj,
+ LLInventoryItem* item,
+ ESource source,
+ const LLUUID& src_id);
+
//static void dropTextureOneFaceAvatar(LLVOAvatar* avatar,S32 hit_face,
// LLInventoryItem* item)
diff --git a/indra/newview/llviewerassetstats.cpp b/indra/newview/llviewerassetstats.cpp
index 7024b2c785..e621cf647e 100644
--- a/indra/newview/llviewerassetstats.cpp
+++ b/indra/newview/llviewerassetstats.cpp
@@ -525,7 +525,7 @@ asset_type_to_category(const LLViewerAssetType::EType at, bool with_http, bool i
// - gestures
// - everything else.
//
- llassert_always(26 == LLViewerAssetType::AT_COUNT);
+ llassert_always(50 == LLViewerAssetType::AT_COUNT);
// Multiple asset definitions are floating around so this requires some
// maintenance and attention.
@@ -557,9 +557,7 @@ asset_type_to_category(const LLViewerAssetType::EType at, bool with_http, bool i
LLViewerAssetStats::EVACOtherGet, // AT_FAVORITE
LLViewerAssetStats::EVACOtherGet, // AT_LINK
LLViewerAssetStats::EVACOtherGet, // AT_LINK_FOLDER
-#if 0
- // When LLViewerAssetType::AT_COUNT == 49
- LLViewerAssetStats::EVACOtherGet, // AT_FOLDER_ENSEMBLE_START
+ LLViewerAssetStats::EVACOtherGet, //
LLViewerAssetStats::EVACOtherGet, //
LLViewerAssetStats::EVACOtherGet, //
LLViewerAssetStats::EVACOtherGet, //
@@ -578,11 +576,12 @@ asset_type_to_category(const LLViewerAssetType::EType at, bool with_http, bool i
LLViewerAssetStats::EVACOtherGet, //
LLViewerAssetStats::EVACOtherGet, //
LLViewerAssetStats::EVACOtherGet, //
- LLViewerAssetStats::EVACOtherGet, // AT_FOLDER_ENSEMBLE_END
- LLViewerAssetStats::EVACOtherGet, // AT_CURRENT_OUTFIT
- LLViewerAssetStats::EVACOtherGet, // AT_OUTFIT
- LLViewerAssetStats::EVACOtherGet // AT_MY_OUTFITS
-#endif
+ LLViewerAssetStats::EVACOtherGet, //
+ LLViewerAssetStats::EVACOtherGet, //
+ LLViewerAssetStats::EVACOtherGet, //
+ LLViewerAssetStats::EVACOtherGet, //
+ LLViewerAssetStats::EVACOtherGet, // AT_MESH
+ // (50)
};
if (at < 0 || at >= LLViewerAssetType::AT_COUNT)
diff --git a/indra/newview/llviewerassettype.cpp b/indra/newview/llviewerassettype.cpp
index 9a52422641..b103f11597 100644
--- a/indra/newview/llviewerassettype.cpp
+++ b/indra/newview/llviewerassettype.cpp
@@ -79,6 +79,8 @@ LLViewerAssetDictionary::LLViewerAssetDictionary()
addEntry(LLViewerAssetType::AT_LINK, new ViewerAssetEntry(DAD_LINK));
addEntry(LLViewerAssetType::AT_LINK_FOLDER, new ViewerAssetEntry(DAD_LINK));
+ addEntry(LLViewerAssetType::AT_MESH, new ViewerAssetEntry(DAD_MESH));
+
addEntry(LLViewerAssetType::AT_NONE, new ViewerAssetEntry(DAD_NONE));
};
diff --git a/indra/newview/llviewercamera.cpp b/indra/newview/llviewercamera.cpp
index cbb1d25f78..23b0845f31 100644
--- a/indra/newview/llviewercamera.cpp
+++ b/indra/newview/llviewercamera.cpp
@@ -32,6 +32,7 @@
// Viewer includes
#include "llagent.h"
#include "llagentcamera.h"
+#include "llmatrix4a.h"
#include "llviewercontrol.h"
#include "llviewerobjectlist.h"
#include "llviewerregion.h"
@@ -781,21 +782,29 @@ BOOL LLViewerCamera::areVertsVisible(LLViewerObject* volumep, BOOL all_verts)
LLMatrix4 render_mat(vo_volume->getRenderRotation(), LLVector4(vo_volume->getRenderPosition()));
+ LLMatrix4a render_mata;
+ render_mata.loadu(render_mat);
+ LLMatrix4a mata;
+ mata.loadu(mat);
+
num_faces = volume->getNumVolumeFaces();
for (i = 0; i < num_faces; i++)
{
const LLVolumeFace& face = volume->getVolumeFace(i);
- for (U32 v = 0; v < face.mVertices.size(); v++)
+ for (U32 v = 0; v < face.mNumVertices; v++)
{
- LLVector4 vec = LLVector4(face.mVertices[v].mPosition) * mat;
+ const LLVector4a& src_vec = face.mPositions[v];
+ LLVector4a vec;
+ mata.affineTransform(src_vec, vec);
if (drawablep->isActive())
{
- vec = vec * render_mat;
+ LLVector4a t = vec;
+ render_mata.affineTransform(t, vec);
}
- BOOL in_frustum = pointInFrustum(LLVector3(vec)) > 0;
+ BOOL in_frustum = pointInFrustum(LLVector3(vec.getF32ptr())) > 0;
if (( !in_frustum && all_verts) ||
(in_frustum && !all_verts))
diff --git a/indra/newview/llviewercontrol.cpp b/indra/newview/llviewercontrol.cpp
index 3c53e54203..9385a6ae84 100644
--- a/indra/newview/llviewercontrol.cpp
+++ b/indra/newview/llviewercontrol.cpp
@@ -128,6 +128,45 @@ static bool handleSetShaderChanged(const LLSD& newvalue)
return true;
}
+static bool handleRenderPerfTestChanged(const LLSD& newvalue)
+{
+ bool status = !newvalue.asBoolean();
+ if (!status)
+ {
+ gPipeline.clearRenderTypeMask(LLPipeline::RENDER_TYPE_WL_SKY,
+ LLPipeline::RENDER_TYPE_GROUND,
+ LLPipeline::RENDER_TYPE_TERRAIN,
+ LLPipeline::RENDER_TYPE_GRASS,
+ LLPipeline::RENDER_TYPE_TREE,
+ LLPipeline::RENDER_TYPE_WATER,
+ LLPipeline::RENDER_TYPE_PASS_GRASS,
+ LLPipeline::RENDER_TYPE_HUD,
+ LLPipeline::RENDER_TYPE_PARTICLES,
+ LLPipeline::RENDER_TYPE_CLOUDS,
+ LLPipeline::RENDER_TYPE_HUD_PARTICLES,
+ LLPipeline::END_RENDER_TYPES);
+ gPipeline.setRenderDebugFeatureControl(LLPipeline::RENDER_DEBUG_FEATURE_UI, false);
+ }
+ else
+ {
+ gPipeline.setRenderTypeMask(LLPipeline::RENDER_TYPE_WL_SKY,
+ LLPipeline::RENDER_TYPE_GROUND,
+ LLPipeline::RENDER_TYPE_TERRAIN,
+ LLPipeline::RENDER_TYPE_GRASS,
+ LLPipeline::RENDER_TYPE_TREE,
+ LLPipeline::RENDER_TYPE_WATER,
+ LLPipeline::RENDER_TYPE_PASS_GRASS,
+ LLPipeline::RENDER_TYPE_HUD,
+ LLPipeline::RENDER_TYPE_PARTICLES,
+ LLPipeline::RENDER_TYPE_CLOUDS,
+ LLPipeline::RENDER_TYPE_HUD_PARTICLES,
+ LLPipeline::END_RENDER_TYPES);
+ gPipeline.setRenderDebugFeatureControl(LLPipeline::RENDER_DEBUG_FEATURE_UI, true);
+ }
+
+ return true;
+}
+
bool handleRenderTransparentWaterChanged(const LLSD& newvalue)
{
LLWorld::getInstance()->updateWaterObjects();
@@ -300,24 +339,6 @@ static bool handleNumpadControlChanged(const LLSD& newvalue)
return true;
}
-static bool handleRenderUseVBOChanged(const LLSD& newvalue)
-{
- if (gPipeline.isInit())
- {
- gPipeline.setUseVBO(newvalue.asBoolean());
- }
- return true;
-}
-
-static bool handleRenderUseVBOMappingChanged(const LLSD& newvalue)
-{
- if (gPipeline.isInit())
- {
- gPipeline.setDisableVBOMapping(newvalue.asBoolean());
- }
- return true;
-}
-
static bool handleWLSkyDetailChanged(const LLSD&)
{
if (gSky.mVOWLSkyp.notNull())
@@ -342,13 +363,21 @@ static bool handleRenderDynamicLODChanged(const LLSD& newvalue)
return true;
}
-static bool handleRenderUseFBOChanged(const LLSD& newvalue)
+static bool handleRenderLocalLightsChanged(const LLSD& newvalue)
+{
+ gPipeline.setLightingDetail(-1);
+ return true;
+}
+
+static bool handleRenderDeferredChanged(const LLSD& newvalue)
{
LLRenderTarget::sUseFBO = newvalue.asBoolean();
if (gPipeline.isInit())
{
+ gPipeline.updateRenderDeferred();
gPipeline.releaseGLBuffers();
gPipeline.createGLBuffers();
+ gPipeline.resetVertexBuffers();
if (LLPipeline::sRenderDeferred && LLRenderTarget::sUseFBO)
{
LLViewerShaderMgr::instance()->setShaders();
@@ -560,21 +589,22 @@ void settings_setup_listeners()
gSavedSettings.getControl("RenderFogRatio")->getSignal()->connect(boost::bind(&handleFogRatioChanged, _2));
gSavedSettings.getControl("RenderMaxPartCount")->getSignal()->connect(boost::bind(&handleMaxPartCountChanged, _2));
gSavedSettings.getControl("RenderDynamicLOD")->getSignal()->connect(boost::bind(&handleRenderDynamicLODChanged, _2));
+ gSavedSettings.getControl("RenderLocalLights")->getSignal()->connect(boost::bind(&handleRenderLocalLightsChanged, _2));
gSavedSettings.getControl("RenderDebugTextureBind")->getSignal()->connect(boost::bind(&handleResetVertexBuffersChanged, _2));
gSavedSettings.getControl("RenderAutoMaskAlphaDeferred")->getSignal()->connect(boost::bind(&handleResetVertexBuffersChanged, _2));
gSavedSettings.getControl("RenderAutoMaskAlphaNonDeferred")->getSignal()->connect(boost::bind(&handleResetVertexBuffersChanged, _2));
gSavedSettings.getControl("RenderObjectBump")->getSignal()->connect(boost::bind(&handleResetVertexBuffersChanged, _2));
gSavedSettings.getControl("RenderMaxVBOSize")->getSignal()->connect(boost::bind(&handleResetVertexBuffersChanged, _2));
- gSavedSettings.getControl("RenderUseFBO")->getSignal()->connect(boost::bind(&handleRenderUseFBOChanged, _2));
gSavedSettings.getControl("RenderDeferredNoise")->getSignal()->connect(boost::bind(&handleReleaseGLBufferChanged, _2));
gSavedSettings.getControl("RenderUseImpostors")->getSignal()->connect(boost::bind(&handleRenderUseImpostorsChanged, _2));
gSavedSettings.getControl("RenderDebugGL")->getSignal()->connect(boost::bind(&handleRenderDebugGLChanged, _2));
gSavedSettings.getControl("RenderDebugPipeline")->getSignal()->connect(boost::bind(&handleRenderDebugPipelineChanged, _2));
gSavedSettings.getControl("RenderResolutionDivisor")->getSignal()->connect(boost::bind(&handleRenderResolutionDivisorChanged, _2));
- gSavedSettings.getControl("RenderDeferred")->getSignal()->connect(boost::bind(&handleSetShaderChanged, _2));
+ gSavedSettings.getControl("RenderDeferred")->getSignal()->connect(boost::bind(&handleRenderDeferredChanged, _2));
gSavedSettings.getControl("RenderShadowDetail")->getSignal()->connect(boost::bind(&handleSetShaderChanged, _2));
gSavedSettings.getControl("RenderDeferredSSAO")->getSignal()->connect(boost::bind(&handleSetShaderChanged, _2));
gSavedSettings.getControl("RenderDeferredGI")->getSignal()->connect(boost::bind(&handleSetShaderChanged, _2));
+ gSavedSettings.getControl("RenderPerformanceTest")->getSignal()->connect(boost::bind(&handleRenderPerfTestChanged, _2));
gSavedSettings.getControl("TextureMemory")->getSignal()->connect(boost::bind(&handleVideoMemoryChanged, _2));
gSavedSettings.getControl("AuditTexture")->getSignal()->connect(boost::bind(&handleAuditTextureChanged, _2));
gSavedSettings.getControl("ChatFontSize")->getSignal()->connect(boost::bind(&handleChatFontSizeChanged, _2));
@@ -597,9 +627,10 @@ void settings_setup_listeners()
gSavedSettings.getControl("MuteVoice")->getSignal()->connect(boost::bind(&handleAudioVolumeChanged, _2));
gSavedSettings.getControl("MuteAmbient")->getSignal()->connect(boost::bind(&handleAudioVolumeChanged, _2));
gSavedSettings.getControl("MuteUI")->getSignal()->connect(boost::bind(&handleAudioVolumeChanged, _2));
- gSavedSettings.getControl("RenderVBOEnable")->getSignal()->connect(boost::bind(&handleRenderUseVBOChanged, _2));
- gSavedSettings.getControl("RenderVBOMappingDisable")->getSignal()->connect(boost::bind(&handleRenderUseVBOMappingChanged, _2));
+ gSavedSettings.getControl("RenderVBOEnable")->getSignal()->connect(boost::bind(&handleResetVertexBuffersChanged, _2));
+ gSavedSettings.getControl("RenderVBOMappingDisable")->getSignal()->connect(boost::bind(&handleResetVertexBuffersChanged, _2));
gSavedSettings.getControl("RenderUseStreamVBO")->getSignal()->connect(boost::bind(&handleResetVertexBuffersChanged, _2));
+ gSavedSettings.getControl("RenderPreferStreamDraw")->getSignal()->connect(boost::bind(&handleResetVertexBuffersChanged, _2));
gSavedSettings.getControl("WLSkyDetail")->getSignal()->connect(boost::bind(&handleWLSkyDetailChanged, _2));
gSavedSettings.getControl("NumpadControl")->getSignal()->connect(boost::bind(&handleNumpadControlChanged, _2));
gSavedSettings.getControl("JoystickAxis0")->getSignal()->connect(boost::bind(&handleJoystickChanged, _2));
diff --git a/indra/newview/llviewerdisplay.cpp b/indra/newview/llviewerdisplay.cpp
index 41b7c13826..b45d1aa3a6 100644
--- a/indra/newview/llviewerdisplay.cpp
+++ b/indra/newview/llviewerdisplay.cpp
@@ -1,1488 +1,1507 @@
-/**
- * @file llviewerdisplay.cpp
- * @brief LLViewerDisplay class implementation
- *
- * $LicenseInfo:firstyear=2004&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-#include "llviewerprecompiledheaders.h"
-
-#include "llviewerdisplay.h"
-
-#include "llgl.h"
-#include "llrender.h"
-#include "llglheaders.h"
-#include "llagent.h"
-#include "llagentcamera.h"
-#include "llviewercontrol.h"
-#include "llcoord.h"
-#include "llcriticaldamp.h"
-#include "lldir.h"
-#include "lldynamictexture.h"
-#include "lldrawpoolalpha.h"
-#include "llfeaturemanager.h"
-//#include "llfirstuse.h"
-#include "llhudmanager.h"
-#include "llimagebmp.h"
-#include "llmemory.h"
-#include "llselectmgr.h"
-#include "llsky.h"
-#include "llstartup.h"
-#include "lltoolfocus.h"
-#include "lltoolmgr.h"
-#include "lltooldraganddrop.h"
-#include "lltoolpie.h"
-#include "lltracker.h"
-#include "lltrans.h"
-#include "llui.h"
-#include "llviewercamera.h"
-#include "llviewerobjectlist.h"
-#include "llviewerparcelmgr.h"
-#include "llviewerwindow.h"
-#include "llvoavatarself.h"
-#include "llvograss.h"
-#include "llworld.h"
-#include "pipeline.h"
-#include "llspatialpartition.h"
-#include "llappviewer.h"
-#include "llstartup.h"
-#include "llviewershadermgr.h"
-#include "llfasttimer.h"
-#include "llfloatertools.h"
-#include "llviewertexturelist.h"
-#include "llfocusmgr.h"
-#include "llcubemap.h"
-#include "llviewerregion.h"
-#include "lldrawpoolwater.h"
-#include "lldrawpoolbump.h"
-#include "llwlparammanager.h"
-#include "llwaterparammanager.h"
-#include "llpostprocess.h"
-
-extern LLPointer<LLViewerTexture> gStartTexture;
-
-LLPointer<LLViewerTexture> gDisconnectedImagep = NULL;
-
-// used to toggle renderer back on after teleport
-const F32 TELEPORT_RENDER_DELAY = 20.f; // Max time a teleport is allowed to take before we raise the curtain
-const F32 TELEPORT_ARRIVAL_DELAY = 2.f; // Time to preload the world before raising the curtain after we've actually already arrived.
-const F32 TELEPORT_LOCAL_DELAY = 1.0f; // Delay to prevent teleports after starting an in-sim teleport.
-BOOL gTeleportDisplay = FALSE;
-LLFrameTimer gTeleportDisplayTimer;
-LLFrameTimer gTeleportArrivalTimer;
-const F32 RESTORE_GL_TIME = 5.f; // Wait this long while reloading textures before we raise the curtain
-
-BOOL gForceRenderLandFence = FALSE;
-BOOL gDisplaySwapBuffers = FALSE;
-BOOL gDepthDirty = FALSE;
-BOOL gResizeScreenTexture = FALSE;
-BOOL gWindowResized = FALSE;
-BOOL gSnapshot = FALSE;
-
-U32 gRecentFrameCount = 0; // number of 'recent' frames
-LLFrameTimer gRecentFPSTime;
-LLFrameTimer gRecentMemoryTime;
-
-// Rendering stuff
-void pre_show_depth_buffer();
-void post_show_depth_buffer();
-void render_ui(F32 zoom_factor = 1.f, int subfield = 0);
-void render_hud_attachments();
-void render_ui_3d();
-void render_ui_2d();
-void render_disconnected_background();
-
-void display_startup()
-{
- if ( !gViewerWindow->getActive()
- || !gViewerWindow->mWindow->getVisible()
- || gViewerWindow->mWindow->getMinimized()
- || gNoRender )
- {
- return;
- }
-
- gPipeline.updateGL();
-
- // Update images?
- //gImageList.updateImages(0.01f);
-
- LLGLSDefault gls_default;
-
- // Required for HTML update in login screen
- static S32 frame_count = 0;
-
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
-
- if (frame_count++ > 1) // make sure we have rendered a frame first
- {
- LLViewerDynamicTexture::updateAllInstances();
- }
-
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
-
- glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
- LLGLSUIDefault gls_ui;
- gPipeline.disableLights();
-
- gViewerWindow->setup2DRender();
- gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
-
- gGL.color4f(1,1,1,1);
- gViewerWindow->draw();
- gGL.flush();
-
- LLVertexBuffer::unbind();
-
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
-
- gViewerWindow->mWindow->swapBuffers();
- glClear(GL_DEPTH_BUFFER_BIT);
-}
-
-void display_update_camera()
-{
- LLMemType mt_uc(LLMemType::MTYPE_DISPLAY_UPDATE_CAMERA);
- // TODO: cut draw distance down if customizing avatar?
- // TODO: cut draw distance on per-parcel basis?
-
- // Cut draw distance in half when customizing avatar,
- // but on the viewer only.
- F32 final_far = gAgentCamera.mDrawDistance;
- if (CAMERA_MODE_CUSTOMIZE_AVATAR == gAgentCamera.getCameraMode())
- {
- final_far *= 0.5f;
- }
- LLViewerCamera::getInstance()->setFar(final_far);
- gViewerWindow->setup3DRender();
-
- // update all the sky/atmospheric/water settings
- LLWLParamManager::instance()->update(LLViewerCamera::getInstance());
- LLWaterParamManager::instance()->update(LLViewerCamera::getInstance());
-
- // Update land visibility too
- LLWorld::getInstance()->setLandFarClip(final_far);
-}
-
-// Write some stats to llinfos
-void display_stats()
-{
- F32 fps_log_freq = gSavedSettings.getF32("FPSLogFrequency");
- if (fps_log_freq > 0.f && gRecentFPSTime.getElapsedTimeF32() >= fps_log_freq)
- {
- F32 fps = gRecentFrameCount / fps_log_freq;
- llinfos << llformat("FPS: %.02f", fps) << llendl;
- gRecentFrameCount = 0;
- gRecentFPSTime.reset();
- }
- F32 mem_log_freq = gSavedSettings.getF32("MemoryLogFrequency");
- if (mem_log_freq > 0.f && gRecentMemoryTime.getElapsedTimeF32() >= mem_log_freq)
- {
- gMemoryAllocated = LLMemory::getCurrentRSS();
- U32 memory = (U32)(gMemoryAllocated / (1024*1024));
- llinfos << llformat("MEMORY: %d MB", memory) << llendl;
- gRecentMemoryTime.reset();
- }
-}
-
-static LLFastTimer::DeclareTimer FTM_PICK("Picking");
-static LLFastTimer::DeclareTimer FTM_RENDER("Render", true);
-static LLFastTimer::DeclareTimer FTM_UPDATE_SKY("Update Sky");
-static LLFastTimer::DeclareTimer FTM_UPDATE_TEXTURES("Update Textures");
-static LLFastTimer::DeclareTimer FTM_IMAGE_UPDATE("Update Images");
-
-// Paint the display!
-void display(BOOL rebuild, F32 zoom_factor, int subfield, BOOL for_snapshot)
-{
- LLMemType mt_render(LLMemType::MTYPE_RENDER);
- LLFastTimer t(FTM_RENDER);
-
- if (gWindowResized)
- { //skip render on frames where window has been resized
- gGL.flush();
- glClear(GL_COLOR_BUFFER_BIT);
- gViewerWindow->mWindow->swapBuffers();
- gPipeline.resizeScreenTexture();
- gResizeScreenTexture = FALSE;
- gWindowResized = FALSE;
- return;
- }
-
- if (LLPipeline::sRenderDeferred)
- { //hack to make sky show up in deferred snapshots
- for_snapshot = FALSE;
- }
-
- if (LLPipeline::sRenderFrameTest)
- {
- send_agent_pause();
- }
-
- gSnapshot = for_snapshot;
-
- LLGLSDefault gls_default;
- LLGLDepthTest gls_depth(GL_TRUE, GL_TRUE, GL_LEQUAL);
-
- LLVertexBuffer::unbind();
-
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
-
- stop_glerror();
-
- gPipeline.disableLights();
-
- stop_glerror();
-
- // Don't draw if the window is hidden or minimized.
- // In fact, must explicitly check the minimized state before drawing.
- // Attempting to draw into a minimized window causes a GL error. JC
- if ( !gViewerWindow->getActive()
- || !gViewerWindow->mWindow->getVisible()
- || gViewerWindow->mWindow->getMinimized() )
- {
- // Clean up memory the pools may have allocated
- if (rebuild)
- {
- stop_glerror();
- gPipeline.rebuildPools();
- stop_glerror();
- }
-
- stop_glerror();
- gViewerWindow->returnEmptyPicks();
- stop_glerror();
- return;
- }
-
- gViewerWindow->checkSettings();
-
- {
- LLFastTimer ftm(FTM_PICK);
- LLAppViewer::instance()->pingMainloopTimeout("Display:Pick");
- gViewerWindow->performPick();
- }
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:CheckStates");
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
-
- //////////////////////////////////////////////////////////
- //
- // Logic for forcing window updates if we're in drone mode.
- //
-
- if (gNoRender)
- {
-#if LL_WINDOWS
- static F32 last_update_time = 0.f;
- if ((gFrameTimeSeconds - last_update_time) > 1.f)
- {
- InvalidateRect((HWND)gViewerWindow->getPlatformWindow(), NULL, FALSE);
- last_update_time = gFrameTimeSeconds;
- }
-#elif LL_DARWIN
- // MBW -- Do something clever here.
-#endif
- // Not actually rendering, don't bother.
- return;
- }
-
-
- //
- // Bail out if we're in the startup state and don't want to try to
- // render the world.
- //
- if (LLStartUp::getStartupState() < STATE_STARTED)
- {
- LLAppViewer::instance()->pingMainloopTimeout("Display:Startup");
- display_startup();
- return;
- }
-
- //LLGLState::verify(FALSE);
-
- /////////////////////////////////////////////////
- //
- // Update GL Texture statistics (used for discard logic?)
- //
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:TextureStats");
- stop_glerror();
-
- LLImageGL::updateStats(gFrameTimeSeconds);
-
- LLVOAvatar::sRenderName = gSavedSettings.getS32("AvatarNameTagMode");
- LLVOAvatar::sRenderGroupTitles = (gSavedSettings.getBOOL("NameTagShowGroupTitles") && gSavedSettings.getS32("AvatarNameTagMode"));
-
- gPipeline.mBackfaceCull = TRUE;
- gFrameCount++;
- gRecentFrameCount++;
- if (gFocusMgr.getAppHasFocus())
- {
- gForegroundFrameCount++;
- }
-
- //////////////////////////////////////////////////////////
- //
- // Display start screen if we're teleporting, and skip render
- //
-
- if (gTeleportDisplay)
- {
- LLAppViewer::instance()->pingMainloopTimeout("Display:Teleport");
- const F32 TELEPORT_ARRIVAL_DELAY = 2.f; // Time to preload the world before raising the curtain after we've actually already arrived.
-
- S32 attach_count = 0;
- if (isAgentAvatarValid())
- {
- attach_count = gAgentAvatarp->getAttachmentCount();
- }
- F32 teleport_save_time = TELEPORT_EXPIRY + TELEPORT_EXPIRY_PER_ATTACHMENT * attach_count;
- F32 teleport_elapsed = gTeleportDisplayTimer.getElapsedTimeF32();
- F32 teleport_percent = teleport_elapsed * (100.f / teleport_save_time);
- if( (gAgent.getTeleportState() != LLAgent::TELEPORT_START) && (teleport_percent > 100.f) )
- {
- // Give up. Don't keep the UI locked forever.
- gAgent.setTeleportState( LLAgent::TELEPORT_NONE );
- gAgent.setTeleportMessage(std::string());
- }
-
- const std::string& message = gAgent.getTeleportMessage();
- switch( gAgent.getTeleportState() )
- {
- case LLAgent::TELEPORT_START:
- // Transition to REQUESTED. Viewer has sent some kind
- // of TeleportRequest to the source simulator
- gTeleportDisplayTimer.reset();
- gViewerWindow->setShowProgress(TRUE);
- gViewerWindow->setProgressPercent(0);
- gAgent.setTeleportState( LLAgent::TELEPORT_REQUESTED );
- gAgent.setTeleportMessage(
- LLAgent::sTeleportProgressMessages["requesting"]);
- break;
-
- case LLAgent::TELEPORT_REQUESTED:
- // Waiting for source simulator to respond
- gViewerWindow->setProgressPercent( llmin(teleport_percent, 37.5f) );
- gViewerWindow->setProgressString(message);
- break;
-
- case LLAgent::TELEPORT_MOVING:
- // Viewer has received destination location from source simulator
- gViewerWindow->setProgressPercent( llmin(teleport_percent, 75.f) );
- gViewerWindow->setProgressString(message);
- break;
-
- case LLAgent::TELEPORT_START_ARRIVAL:
- // Transition to ARRIVING. Viewer has received avatar update, etc., from destination simulator
- gTeleportArrivalTimer.reset();
- gViewerWindow->setProgressCancelButtonVisible(FALSE, LLTrans::getString("Cancel"));
- gViewerWindow->setProgressPercent(75.f);
- gAgent.setTeleportState( LLAgent::TELEPORT_ARRIVING );
- gAgent.setTeleportMessage(
- LLAgent::sTeleportProgressMessages["arriving"]);
- gTextureList.mForceResetTextureStats = TRUE;
- gAgentCamera.resetView(TRUE, TRUE);
- break;
-
- case LLAgent::TELEPORT_ARRIVING:
- // Make the user wait while content "pre-caches"
- {
- F32 arrival_fraction = (gTeleportArrivalTimer.getElapsedTimeF32() / TELEPORT_ARRIVAL_DELAY);
- if( arrival_fraction > 1.f )
- {
- arrival_fraction = 1.f;
- //LLFirstUse::useTeleport();
- gAgent.setTeleportState( LLAgent::TELEPORT_NONE );
- }
- gViewerWindow->setProgressCancelButtonVisible(FALSE, LLTrans::getString("Cancel"));
- gViewerWindow->setProgressPercent( arrival_fraction * 25.f + 75.f);
- gViewerWindow->setProgressString(message);
- }
- break;
-
- case LLAgent::TELEPORT_LOCAL:
- // Short delay when teleporting in the same sim (progress screen active but not shown - did not
- // fall-through from TELEPORT_START)
- {
- if( gTeleportDisplayTimer.getElapsedTimeF32() > TELEPORT_LOCAL_DELAY )
- {
- //LLFirstUse::useTeleport();
- gAgent.setTeleportState( LLAgent::TELEPORT_NONE );
- }
- }
- break;
-
- case LLAgent::TELEPORT_NONE:
- // No teleport in progress
- gViewerWindow->setShowProgress(FALSE);
- gTeleportDisplay = FALSE;
- break;
- }
- }
- else if(LLAppViewer::instance()->logoutRequestSent())
- {
- LLAppViewer::instance()->pingMainloopTimeout("Display:Logout");
- F32 percent_done = gLogoutTimer.getElapsedTimeF32() * 100.f / gLogoutMaxTime;
- if (percent_done > 100.f)
- {
- percent_done = 100.f;
- }
-
- if( LLApp::isExiting() )
- {
- percent_done = 100.f;
- }
-
- gViewerWindow->setProgressPercent( percent_done );
- }
- else
- if (gRestoreGL)
- {
- LLAppViewer::instance()->pingMainloopTimeout("Display:RestoreGL");
- F32 percent_done = gRestoreGLTimer.getElapsedTimeF32() * 100.f / RESTORE_GL_TIME;
- if( percent_done > 100.f )
- {
- gViewerWindow->setShowProgress(FALSE);
- gRestoreGL = FALSE;
- }
- else
- {
-
- if( LLApp::isExiting() )
- {
- percent_done = 100.f;
- }
-
- gViewerWindow->setProgressPercent( percent_done );
- }
- }
-
- //////////////////////////
- //
- // Prepare for the next frame
- //
-
- /////////////////////////////
- //
- // Update the camera
- //
- //
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:Camera");
- LLViewerCamera::getInstance()->setZoomParameters(zoom_factor, subfield);
- LLViewerCamera::getInstance()->setNear(MIN_NEAR_PLANE);
-
- //////////////////////////
- //
- // clear the next buffer
- // (must follow dynamic texture writing since that uses the frame buffer)
- //
-
- if (gDisconnected)
- {
- LLAppViewer::instance()->pingMainloopTimeout("Display:Disconnected");
- render_ui();
- }
-
- //////////////////////////
- //
- // Set rendering options
- //
- //
- LLAppViewer::instance()->pingMainloopTimeout("Display:RenderSetup");
- stop_glerror();
-
- ///////////////////////////////////////
- //
- // Slam lighting parameters back to our defaults.
- // Note that these are not the same as GL defaults...
-
- stop_glerror();
- F32 one[4] = {1.f, 1.f, 1.f, 1.f};
- glLightModelfv (GL_LIGHT_MODEL_AMBIENT,one);
- stop_glerror();
-
- /////////////////////////////////////
- //
- // Render
- //
- // Actually push all of our triangles to the screen.
- //
-
- // do render-to-texture stuff here
- if (gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_DYNAMIC_TEXTURES))
- {
- LLAppViewer::instance()->pingMainloopTimeout("Display:DynamicTextures");
- LLFastTimer t(FTM_UPDATE_TEXTURES);
- if (LLViewerDynamicTexture::updateAllInstances())
- {
- gGL.setColorMask(true, true);
- glClear(GL_DEPTH_BUFFER_BIT);
- }
- }
-
- gViewerWindow->setup3DViewport();
-
- gPipeline.resetFrameStats(); // Reset per-frame statistics.
-
- if (!gDisconnected)
- {
- LLMemType mt_du(LLMemType::MTYPE_DISPLAY_UPDATE);
- LLAppViewer::instance()->pingMainloopTimeout("Display:Update");
- if (gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_HUD))
- { //don't draw hud objects in this frame
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD);
- }
-
- if (gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_HUD_PARTICLES))
- { //don't draw hud particles in this frame
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD_PARTICLES);
- }
-
- //upkeep gl name pools
- LLGLNamePool::upkeepPools();
-
- stop_glerror();
- display_update_camera();
- stop_glerror();
-
- // *TODO: merge these two methods
- {
- LLMemType mt_uh(LLMemType::MTYPE_DISPLAY_UPDATE_HUD);
- LLHUDManager::getInstance()->updateEffects();
- LLHUDObject::updateAll();
- stop_glerror();
- }
-
- {
- LLMemType mt_ug(LLMemType::MTYPE_DISPLAY_UPDATE_GEOM);
- const F32 max_geom_update_time = 0.005f*10.f*gFrameIntervalSeconds; // 50 ms/second update time
- gPipeline.createObjects(max_geom_update_time);
- gPipeline.updateGeom(max_geom_update_time);
- stop_glerror();
- }
-
- gPipeline.updateGL();
- stop_glerror();
-
- S32 water_clip = 0;
- if ((LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_ENVIRONMENT) > 1) &&
- (gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_WATER) ||
- gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_VOIDWATER)))
- {
- if (LLViewerCamera::getInstance()->cameraUnderWater())
- {
- water_clip = -1;
- }
- else
- {
- water_clip = 1;
- }
- }
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:Cull");
-
- //Increment drawable frame counter
- LLDrawable::incrementVisible();
-
- LLSpatialGroup::sNoDelete = TRUE;
- LLPipeline::sUseOcclusion =
- (!gUseWireframe
- && LLFeatureManager::getInstance()->isFeatureAvailable("UseOcclusion")
- && gSavedSettings.getBOOL("UseOcclusion")
- && gGLManager.mHasOcclusionQuery) ? 2 : 0;
-
- if (LLPipeline::sUseOcclusion && LLPipeline::sRenderDeferred)
- { //force occlusion on for all render types if doing deferred render
- LLPipeline::sUseOcclusion = 3;
- }
-
- LLPipeline::sAutoMaskAlphaDeferred = gSavedSettings.getBOOL("RenderAutoMaskAlphaDeferred");
- LLPipeline::sAutoMaskAlphaNonDeferred = gSavedSettings.getBOOL("RenderAutoMaskAlphaNonDeferred");
- LLPipeline::sUseFarClip = gSavedSettings.getBOOL("RenderUseFarClip");
- LLVOAvatar::sMaxVisible = (U32)gSavedSettings.getS32("RenderAvatarMaxVisible");
- LLPipeline::sDelayVBUpdate = gSavedSettings.getBOOL("RenderDelayVBUpdate");
-
- S32 occlusion = LLPipeline::sUseOcclusion;
- if (gDepthDirty)
- { //depth buffer is invalid, don't overwrite occlusion state
- LLPipeline::sUseOcclusion = llmin(occlusion, 1);
- }
- gDepthDirty = FALSE;
-
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
- LLGLState::checkClientArrays();
-
- static LLCullResult result;
- LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WORLD;
- gPipeline.updateCull(*LLViewerCamera::getInstance(), result, water_clip);
- stop_glerror();
-
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
- LLGLState::checkClientArrays();
-
- BOOL to_texture = gPipeline.canUseVertexShaders() &&
- LLPipeline::sRenderGlow;
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:Swap");
-
- {
- LLMemType mt_ds(LLMemType::MTYPE_DISPLAY_SWAP);
- {
- LLFastTimer ftm(FTM_CLIENT_COPY);
- LLVertexBuffer::clientCopy(0.016);
- }
-
- if (gResizeScreenTexture)
- {
- gResizeScreenTexture = FALSE;
- gPipeline.resizeScreenTexture();
- }
-
- gGL.setColorMask(true, true);
- glClearColor(0,0,0,0);
-
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
- LLGLState::checkClientArrays();
-
- if (!for_snapshot)
- {
- if (gFrameCount > 1)
- { //for some reason, ATI 4800 series will error out if you
- //try to generate a shadow before the first frame is through
- gPipeline.generateSunShadow(*LLViewerCamera::getInstance());
- }
-
- LLVertexBuffer::unbind();
-
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
- LLGLState::checkClientArrays();
-
- glh::matrix4f proj = glh_get_current_projection();
- glh::matrix4f mod = glh_get_current_modelview();
- glViewport(0,0,512,512);
- LLVOAvatar::updateFreezeCounter() ;
- LLVOAvatar::updateImpostors();
-
- glh_set_current_projection(proj);
- glh_set_current_modelview(mod);
- glMatrixMode(GL_PROJECTION);
- glLoadMatrixf(proj.m);
- glMatrixMode(GL_MODELVIEW);
- glLoadMatrixf(mod.m);
- gViewerWindow->setup3DViewport();
-
- LLGLState::checkStates();
- LLGLState::checkTextureChannels();
- LLGLState::checkClientArrays();
-
- }
- glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
- }
-
- //if (!for_snapshot)
- {
- LLMemType mt_gw(LLMemType::MTYPE_DISPLAY_GEN_REFLECTION);
- LLAppViewer::instance()->pingMainloopTimeout("Display:Imagery");
- gPipeline.generateWaterReflection(*LLViewerCamera::getInstance());
- gPipeline.generateHighlight(*LLViewerCamera::getInstance());
- }
-
- //////////////////////////////////////
- //
- // Update images, using the image stats generated during object update/culling
- //
- // Can put objects onto the retextured list.
- //
- // Doing this here gives hardware occlusion queries extra time to complete
- LLAppViewer::instance()->pingMainloopTimeout("Display:UpdateImages");
-
- {
- LLMemType mt_iu(LLMemType::MTYPE_DISPLAY_IMAGE_UPDATE);
- LLFastTimer t(FTM_IMAGE_UPDATE);
-
- LLViewerTexture::updateClass(LLViewerCamera::getInstance()->getVelocityStat()->getMean(),
- LLViewerCamera::getInstance()->getAngularVelocityStat()->getMean());
-
- gBumpImageList.updateImages(); // must be called before gTextureList version so that it's textures are thrown out first.
-
- F32 max_image_decode_time = 0.050f*gFrameIntervalSeconds; // 50 ms/second decode time
- max_image_decode_time = llclamp(max_image_decode_time, 0.002f, 0.005f ); // min 2ms/frame, max 5ms/frame)
- gTextureList.updateImages(max_image_decode_time);
-
- //remove dead textures from GL
- LLImageGL::deleteDeadTextures();
- stop_glerror();
- }
- ///////////////////////////////////
- //
- // StateSort
- //
- // Responsible for taking visible objects, and adding them to the appropriate draw orders.
- // In the case of alpha objects, z-sorts them first.
- // Also creates special lists for outlines and selected face rendering.
- //
- LLAppViewer::instance()->pingMainloopTimeout("Display:StateSort");
- {
- LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WORLD;
- LLMemType mt_ss(LLMemType::MTYPE_DISPLAY_STATE_SORT);
- gPipeline.sAllowRebuildPriorityGroup = TRUE ;
- gPipeline.stateSort(*LLViewerCamera::getInstance(), result);
- stop_glerror();
-
- if (rebuild)
- {
- //////////////////////////////////////
- //
- // rebuildPools
- //
- //
- gPipeline.rebuildPools();
- stop_glerror();
- }
- }
-
- LLPipeline::sUseOcclusion = occlusion;
-
- {
- LLMemType mt_ds(LLMemType::MTYPE_DISPLAY_SKY);
- LLAppViewer::instance()->pingMainloopTimeout("Display:Sky");
- LLFastTimer t(FTM_UPDATE_SKY);
- gSky.updateSky();
- }
-
- if(gUseWireframe)
- {
- glClearColor(0.5f, 0.5f, 0.5f, 0.f);
- glClear(GL_COLOR_BUFFER_BIT);
- glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
- }
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:RenderStart");
-
- //// render frontmost floater opaque for occlusion culling purposes
- //LLFloater* frontmost_floaterp = gFloaterView->getFrontmost();
- //// assumes frontmost floater with focus is opaque
- //if (frontmost_floaterp && gFocusMgr.childHasKeyboardFocus(frontmost_floaterp))
- //{
- // glMatrixMode(GL_MODELVIEW);
- // glPushMatrix();
- // {
- // gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
-
- // glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE);
- // glLoadIdentity();
-
- // LLRect floater_rect = frontmost_floaterp->calcScreenRect();
- // // deflate by one pixel so rounding errors don't occlude outside of floater extents
- // floater_rect.stretch(-1);
- // LLRectf floater_3d_rect((F32)floater_rect.mLeft / (F32)gViewerWindow->getWindowWidthScaled(),
- // (F32)floater_rect.mTop / (F32)gViewerWindow->getWindowHeightScaled(),
- // (F32)floater_rect.mRight / (F32)gViewerWindow->getWindowWidthScaled(),
- // (F32)floater_rect.mBottom / (F32)gViewerWindow->getWindowHeightScaled());
- // floater_3d_rect.translate(-0.5f, -0.5f);
- // glTranslatef(0.f, 0.f, -LLViewerCamera::getInstance()->getNear());
- // glScalef(LLViewerCamera::getInstance()->getNear() * LLViewerCamera::getInstance()->getAspect() / sinf(LLViewerCamera::getInstance()->getView()), LLViewerCamera::getInstance()->getNear() / sinf(LLViewerCamera::getInstance()->getView()), 1.f);
- // gGL.color4fv(LLColor4::white.mV);
- // gGL.begin(LLVertexBuffer::QUADS);
- // {
- // gGL.vertex3f(floater_3d_rect.mLeft, floater_3d_rect.mBottom, 0.f);
- // gGL.vertex3f(floater_3d_rect.mLeft, floater_3d_rect.mTop, 0.f);
- // gGL.vertex3f(floater_3d_rect.mRight, floater_3d_rect.mTop, 0.f);
- // gGL.vertex3f(floater_3d_rect.mRight, floater_3d_rect.mBottom, 0.f);
- // }
- // gGL.end();
- // glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
- // }
- // glPopMatrix();
- //}
-
- LLPipeline::sUnderWaterRender = LLViewerCamera::getInstance()->cameraUnderWater() ? TRUE : FALSE;
- LLPipeline::updateRenderDeferred();
-
- stop_glerror();
-
- if (to_texture)
- {
- gGL.setColorMask(true, true);
- if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender)
- {
- gPipeline.mDeferredScreen.bindTarget();
- glClearColor(0,0,0,0);
- gPipeline.mDeferredScreen.clear();
- }
- else
- {
- gPipeline.mScreen.bindTarget();
- gPipeline.mScreen.clear();
- }
-
- gGL.setColorMask(true, false);
- }
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:RenderGeom");
-
- if (!(LLAppViewer::instance()->logoutRequestSent() && LLAppViewer::instance()->hasSavedFinalSnapshot())
- && !gRestoreGL)
- {
- LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WORLD;
- LLMemType mt_rg(LLMemType::MTYPE_DISPLAY_RENDER_GEOM);
- gGL.setColorMask(true, false);
- if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender)
- {
- gPipeline.renderGeomDeferred(*LLViewerCamera::getInstance());
- }
- else
- {
- gPipeline.renderGeom(*LLViewerCamera::getInstance(), TRUE);
- }
-
- gGL.setColorMask(true, true);
-
- //store this frame's modelview matrix for use
- //when rendering next frame's occlusion queries
- for (U32 i = 0; i < 16; i++)
- {
- gGLLastModelView[i] = gGLModelView[i];
- gGLLastProjection[i] = gGLProjection[i];
- }
- stop_glerror();
- }
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:RenderFlush");
-
- if (to_texture)
- {
- LLMemType mt_rf(LLMemType::MTYPE_DISPLAY_RENDER_FLUSH);
- if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender)
- {
- gPipeline.mDeferredScreen.flush();
- }
- else
- {
- gPipeline.mScreen.flush();
- }
- }
-
- if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender)
- {
- gPipeline.renderDeferredLighting();
- }
-
- LLPipeline::sUnderWaterRender = FALSE;
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:RenderUI");
- if (!for_snapshot)
- {
- LLFastTimer t(FTM_RENDER_UI);
- render_ui();
- }
-
- gPipeline.rebuildGroups();
-
- LLSpatialGroup::sNoDelete = FALSE;
- }
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:FrameStats");
-
- stop_glerror();
-
- if (LLPipeline::sRenderFrameTest)
- {
- send_agent_resume();
- LLPipeline::sRenderFrameTest = FALSE;
- }
-
- display_stats();
-
- LLAppViewer::instance()->pingMainloopTimeout("Display:Done");
-}
-
-void render_hud_attachments()
-{
- LLMemType mt_ra(LLMemType::MTYPE_DISPLAY_RENDER_ATTACHMENTS);
- glMatrixMode(GL_PROJECTION);
- glPushMatrix();
- glMatrixMode(GL_MODELVIEW);
- glPushMatrix();
-
- glh::matrix4f current_proj = glh_get_current_projection();
- glh::matrix4f current_mod = glh_get_current_modelview();
-
- // clamp target zoom level to reasonable values
- gAgentCamera.mHUDTargetZoom = llclamp(gAgentCamera.mHUDTargetZoom, 0.1f, 1.f);
- // smoothly interpolate current zoom level
- gAgentCamera.mHUDCurZoom = lerp(gAgentCamera.mHUDCurZoom, gAgentCamera.mHUDTargetZoom, LLCriticalDamp::getInterpolant(0.03f));
-
- if (LLPipeline::sShowHUDAttachments && !gDisconnected && setup_hud_matrices())
- {
- LLCamera hud_cam = *LLViewerCamera::getInstance();
- LLVector3 origin = hud_cam.getOrigin();
- hud_cam.setOrigin(-1.f,0,0);
- hud_cam.setAxes(LLVector3(1,0,0), LLVector3(0,1,0), LLVector3(0,0,1));
- LLViewerCamera::updateFrustumPlanes(hud_cam, TRUE);
-
- bool render_particles = gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_PARTICLES) && gSavedSettings.getBOOL("RenderHUDParticles");
-
- //only render hud objects
- gPipeline.pushRenderTypeMask();
-
- // turn off everything
- gPipeline.andRenderTypeMask(LLPipeline::END_RENDER_TYPES);
- // turn on HUD
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD);
- // turn on HUD particles
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD_PARTICLES);
-
- // if particles are off, turn off hud-particles as well
- if (!render_particles)
- {
- // turn back off HUD particles
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD_PARTICLES);
- }
-
- bool has_ui = gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI);
- if (has_ui)
- {
- gPipeline.toggleRenderDebugFeature((void*) LLPipeline::RENDER_DEBUG_FEATURE_UI);
- }
-
- S32 use_occlusion = LLPipeline::sUseOcclusion;
- LLPipeline::sUseOcclusion = 0;
- LLPipeline::sDisableShaders = TRUE;
-
- //cull, sort, and render hud objects
- static LLCullResult result;
- LLSpatialGroup::sNoDelete = TRUE;
-
- LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WORLD;
- gPipeline.updateCull(hud_cam, result);
-
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_BUMP);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_SIMPLE);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_VOLUME);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_ALPHA);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_FULLBRIGHT);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_ALPHA);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_ALPHA_MASK);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_BUMP);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_FULLBRIGHT);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_FULLBRIGHT_ALPHA_MASK);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_FULLBRIGHT_SHINY);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_SHINY);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_INVISIBLE);
- gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_INVISI_SHINY);
-
- gPipeline.stateSort(hud_cam, result);
-
- gPipeline.renderGeom(hud_cam);
-
- LLSpatialGroup::sNoDelete = FALSE;
-
- render_hud_elements();
-
- //restore type mask
- gPipeline.popRenderTypeMask();
-
- if (has_ui)
- {
- gPipeline.toggleRenderDebugFeature((void*) LLPipeline::RENDER_DEBUG_FEATURE_UI);
- }
- LLPipeline::sUseOcclusion = use_occlusion;
- LLPipeline::sDisableShaders = FALSE;
- }
- glMatrixMode(GL_PROJECTION);
- glPopMatrix();
- glMatrixMode(GL_MODELVIEW);
- glPopMatrix();
-
- glh_set_current_projection(current_proj);
- glh_set_current_modelview(current_mod);
-}
-
-LLRect get_whole_screen_region()
-{
- LLRect whole_screen = gViewerWindow->getWorldViewRectScaled();
-
- // apply camera zoom transform (for high res screenshots)
- F32 zoom_factor = LLViewerCamera::getInstance()->getZoomFactor();
- S16 sub_region = LLViewerCamera::getInstance()->getZoomSubRegion();
- if (zoom_factor > 1.f)
- {
- S32 num_horizontal_tiles = llceil(zoom_factor);
- S32 tile_width = llround((F32)gViewerWindow->getWorldViewWidthScaled() / zoom_factor);
- S32 tile_height = llround((F32)gViewerWindow->getWorldViewHeightScaled() / zoom_factor);
- int tile_y = sub_region / num_horizontal_tiles;
- int tile_x = sub_region - (tile_y * num_horizontal_tiles);
-
- whole_screen.setLeftTopAndSize(tile_x * tile_width, gViewerWindow->getWorldViewHeightScaled() - (tile_y * tile_height), tile_width, tile_height);
- }
- return whole_screen;
-}
-
-bool get_hud_matrices(const LLRect& screen_region, glh::matrix4f &proj, glh::matrix4f &model)
-{
- if (isAgentAvatarValid() && gAgentAvatarp->hasHUDAttachment())
- {
- F32 zoom_level = gAgentCamera.mHUDCurZoom;
- LLBBox hud_bbox = gAgentAvatarp->getHUDBBox();
-
- F32 hud_depth = llmax(1.f, hud_bbox.getExtentLocal().mV[VX] * 1.1f);
- proj = gl_ortho(-0.5f * LLViewerCamera::getInstance()->getAspect(), 0.5f * LLViewerCamera::getInstance()->getAspect(), -0.5f, 0.5f, 0.f, hud_depth);
- proj.element(2,2) = -0.01f;
-
- F32 aspect_ratio = LLViewerCamera::getInstance()->getAspect();
-
- glh::matrix4f mat;
- F32 scale_x = (F32)gViewerWindow->getWorldViewWidthScaled() / (F32)screen_region.getWidth();
- F32 scale_y = (F32)gViewerWindow->getWorldViewHeightScaled() / (F32)screen_region.getHeight();
- mat.set_scale(glh::vec3f(scale_x, scale_y, 1.f));
- mat.set_translate(
- glh::vec3f(clamp_rescale((F32)screen_region.getCenterX(), 0.f, (F32)gViewerWindow->getWorldViewWidthScaled(), 0.5f * scale_x * aspect_ratio, -0.5f * scale_x * aspect_ratio),
- clamp_rescale((F32)screen_region.getCenterY(), 0.f, (F32)gViewerWindow->getWorldViewHeightScaled(), 0.5f * scale_y, -0.5f * scale_y),
- 0.f));
- proj *= mat;
-
- glh::matrix4f tmp_model((GLfloat*) OGL_TO_CFR_ROTATION);
-
- mat.set_scale(glh::vec3f(zoom_level, zoom_level, zoom_level));
- mat.set_translate(glh::vec3f(-hud_bbox.getCenterLocal().mV[VX] + (hud_depth * 0.5f), 0.f, 0.f));
-
- tmp_model *= mat;
- model = tmp_model;
- return TRUE;
- }
- else
- {
- return FALSE;
- }
-}
-
-bool get_hud_matrices(glh::matrix4f &proj, glh::matrix4f &model)
-{
- LLRect whole_screen = get_whole_screen_region();
- return get_hud_matrices(whole_screen, proj, model);
-}
-
-BOOL setup_hud_matrices()
-{
- LLRect whole_screen = get_whole_screen_region();
- return setup_hud_matrices(whole_screen);
-}
-
-BOOL setup_hud_matrices(const LLRect& screen_region)
-{
- glh::matrix4f proj, model;
- bool result = get_hud_matrices(screen_region, proj, model);
- if (!result) return result;
-
- // set up transform to keep HUD objects in front of camera
- glMatrixMode(GL_PROJECTION);
- glLoadMatrixf(proj.m);
- glh_set_current_projection(proj);
-
- glMatrixMode(GL_MODELVIEW);
- glLoadMatrixf(model.m);
- glh_set_current_modelview(model);
- return TRUE;
-}
-
-static LLFastTimer::DeclareTimer FTM_SWAP("Swap");
-
-void render_ui(F32 zoom_factor, int subfield)
-{
- LLMemType mt_ru(LLMemType::MTYPE_DISPLAY_RENDER_UI);
- LLGLState::checkStates();
-
- glh::matrix4f saved_view = glh_get_current_modelview();
-
- if (!gSnapshot)
- {
- glPushMatrix();
- glLoadMatrixd(gGLLastModelView);
- glh_set_current_modelview(glh_copy_matrix(gGLLastModelView));
- }
-
- {
- BOOL to_texture = gPipeline.canUseVertexShaders() &&
- LLPipeline::sRenderGlow;
-
- if (to_texture)
- {
- gPipeline.renderBloom(gSnapshot, zoom_factor, subfield);
- }
-
- render_hud_elements();
- render_hud_attachments();
- }
-
- LLGLSDefault gls_default;
- LLGLSUIDefault gls_ui;
- {
- gPipeline.disableLights();
- }
-
- {
- gGL.color4f(1,1,1,1);
- if (gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
- {
- LLFastTimer t(FTM_RENDER_UI);
-
- if (!gDisconnected)
- {
- render_ui_3d();
- LLGLState::checkStates();
- }
- else
- {
- render_disconnected_background();
- }
-
- render_ui_2d();
- LLGLState::checkStates();
- }
- gGL.flush();
-
- {
- gViewerWindow->setup2DRender();
- gViewerWindow->updateDebugText();
- gViewerWindow->drawDebugText();
- }
-
- LLVertexBuffer::unbind();
- }
-
- if (!gSnapshot)
- {
- glh_set_current_modelview(saved_view);
- glPopMatrix();
- }
-
- if (gDisplaySwapBuffers)
- {
- LLFastTimer t(FTM_SWAP);
- gViewerWindow->mWindow->swapBuffers();
- }
- gDisplaySwapBuffers = TRUE;
-}
-
-void renderCoordinateAxes()
-{
- gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
- gGL.begin(LLRender::LINES);
- gGL.color3f(1.0f, 0.0f, 0.0f); // i direction = X-Axis = red
- gGL.vertex3f(0.0f, 0.0f, 0.0f);
- gGL.vertex3f(2.0f, 0.0f, 0.0f);
- gGL.vertex3f(3.0f, 0.0f, 0.0f);
- gGL.vertex3f(5.0f, 0.0f, 0.0f);
- gGL.vertex3f(6.0f, 0.0f, 0.0f);
- gGL.vertex3f(8.0f, 0.0f, 0.0f);
- // Make an X
- gGL.vertex3f(11.0f, 1.0f, 1.0f);
- gGL.vertex3f(11.0f, -1.0f, -1.0f);
- gGL.vertex3f(11.0f, 1.0f, -1.0f);
- gGL.vertex3f(11.0f, -1.0f, 1.0f);
-
- gGL.color3f(0.0f, 1.0f, 0.0f); // j direction = Y-Axis = green
- gGL.vertex3f(0.0f, 0.0f, 0.0f);
- gGL.vertex3f(0.0f, 2.0f, 0.0f);
- gGL.vertex3f(0.0f, 3.0f, 0.0f);
- gGL.vertex3f(0.0f, 5.0f, 0.0f);
- gGL.vertex3f(0.0f, 6.0f, 0.0f);
- gGL.vertex3f(0.0f, 8.0f, 0.0f);
- // Make a Y
- gGL.vertex3f(1.0f, 11.0f, 1.0f);
- gGL.vertex3f(0.0f, 11.0f, 0.0f);
- gGL.vertex3f(-1.0f, 11.0f, 1.0f);
- gGL.vertex3f(0.0f, 11.0f, 0.0f);
- gGL.vertex3f(0.0f, 11.0f, 0.0f);
- gGL.vertex3f(0.0f, 11.0f, -1.0f);
-
- gGL.color3f(0.0f, 0.0f, 1.0f); // Z-Axis = blue
- gGL.vertex3f(0.0f, 0.0f, 0.0f);
- gGL.vertex3f(0.0f, 0.0f, 2.0f);
- gGL.vertex3f(0.0f, 0.0f, 3.0f);
- gGL.vertex3f(0.0f, 0.0f, 5.0f);
- gGL.vertex3f(0.0f, 0.0f, 6.0f);
- gGL.vertex3f(0.0f, 0.0f, 8.0f);
- // Make a Z
- gGL.vertex3f(-1.0f, 1.0f, 11.0f);
- gGL.vertex3f(1.0f, 1.0f, 11.0f);
- gGL.vertex3f(1.0f, 1.0f, 11.0f);
- gGL.vertex3f(-1.0f, -1.0f, 11.0f);
- gGL.vertex3f(-1.0f, -1.0f, 11.0f);
- gGL.vertex3f(1.0f, -1.0f, 11.0f);
- gGL.end();
-}
-
-
-void draw_axes()
-{
- LLGLSUIDefault gls_ui;
- gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
- // A vertical white line at origin
- LLVector3 v = gAgent.getPositionAgent();
- gGL.begin(LLRender::LINES);
- gGL.color3f(1.0f, 1.0f, 1.0f);
- gGL.vertex3f(0.0f, 0.0f, 0.0f);
- gGL.vertex3f(0.0f, 0.0f, 40.0f);
- gGL.end();
- // Some coordinate axes
- glPushMatrix();
- glTranslatef( v.mV[VX], v.mV[VY], v.mV[VZ] );
- renderCoordinateAxes();
- glPopMatrix();
-}
-
-void render_ui_3d()
-{
- LLGLSPipeline gls_pipeline;
-
- //////////////////////////////////////
- //
- // Render 3D UI elements
- // NOTE: zbuffer is cleared before we get here by LLDrawPoolHUD,
- // so 3d elements requiring Z buffer are moved to LLDrawPoolHUD
- //
-
- /////////////////////////////////////////////////////////////
- //
- // Render 2.5D elements (2D elements in the world)
- // Stuff without z writes
- //
-
- // Debugging stuff goes before the UI.
-
- // Coordinate axes
- if (gSavedSettings.getBOOL("ShowAxes"))
- {
- draw_axes();
- }
-
- stop_glerror();
-
- gViewerWindow->renderSelections(FALSE, FALSE, TRUE); // Non HUD call in render_hud_elements
- stop_glerror();
-}
-
-void render_ui_2d()
-{
- LLGLSUIDefault gls_ui;
-
- /////////////////////////////////////////////////////////////
- //
- // Render 2D UI elements that overlay the world (no z compare)
-
- // Disable wireframe mode below here, as this is HUD/menus
- glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-
- // Menu overlays, HUD, etc
- gViewerWindow->setup2DRender();
-
- F32 zoom_factor = LLViewerCamera::getInstance()->getZoomFactor();
- S16 sub_region = LLViewerCamera::getInstance()->getZoomSubRegion();
-
- if (zoom_factor > 1.f)
- {
- //decompose subregion number to x and y values
- int pos_y = sub_region / llceil(zoom_factor);
- int pos_x = sub_region - (pos_y*llceil(zoom_factor));
- // offset for this tile
- LLFontGL::sCurOrigin.mX -= llround((F32)gViewerWindow->getWindowWidthScaled() * (F32)pos_x / zoom_factor);
- LLFontGL::sCurOrigin.mY -= llround((F32)gViewerWindow->getWindowHeightScaled() * (F32)pos_y / zoom_factor);
- }
-
- stop_glerror();
- gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
-
- // render outline for HUD
- if (isAgentAvatarValid() && gAgentCamera.mHUDCurZoom < 0.98f)
- {
- gGL.pushMatrix();
- S32 half_width = (gViewerWindow->getWorldViewWidthScaled() / 2);
- S32 half_height = (gViewerWindow->getWorldViewHeightScaled() / 2);
- glScalef(LLUI::sGLScaleFactor.mV[0], LLUI::sGLScaleFactor.mV[1], 1.f);
- glTranslatef((F32)half_width, (F32)half_height, 0.f);
- F32 zoom = gAgentCamera.mHUDCurZoom;
- glScalef(zoom,zoom,1.f);
- gGL.color4fv(LLColor4::white.mV);
- gl_rect_2d(-half_width, half_height, half_width, -half_height, FALSE);
- gGL.popMatrix();
- stop_glerror();
- }
-
-
- if (gSavedSettings.getBOOL("RenderUIBuffer"))
- {
- if (LLUI::sDirty)
- {
- LLUI::sDirty = FALSE;
- LLRect t_rect;
-
- gPipeline.mUIScreen.bindTarget();
- gGL.setColorMask(true, true);
- {
- static const S32 pad = 8;
-
- LLUI::sDirtyRect.mLeft -= pad;
- LLUI::sDirtyRect.mRight += pad;
- LLUI::sDirtyRect.mBottom -= pad;
- LLUI::sDirtyRect.mTop += pad;
-
- LLGLEnable scissor(GL_SCISSOR_TEST);
- static LLRect last_rect = LLUI::sDirtyRect;
-
- //union with last rect to avoid mouse poop
- last_rect.unionWith(LLUI::sDirtyRect);
-
- t_rect = LLUI::sDirtyRect;
- LLUI::sDirtyRect = last_rect;
- last_rect = t_rect;
-
- last_rect.mLeft = LLRect::tCoordType(last_rect.mLeft / LLUI::sGLScaleFactor.mV[0]);
- last_rect.mRight = LLRect::tCoordType(last_rect.mRight / LLUI::sGLScaleFactor.mV[0]);
- last_rect.mTop = LLRect::tCoordType(last_rect.mTop / LLUI::sGLScaleFactor.mV[1]);
- last_rect.mBottom = LLRect::tCoordType(last_rect.mBottom / LLUI::sGLScaleFactor.mV[1]);
-
- LLRect clip_rect(last_rect);
-
- glClear(GL_COLOR_BUFFER_BIT);
-
- gViewerWindow->draw();
- }
-
- gPipeline.mUIScreen.flush();
- gGL.setColorMask(true, false);
-
- LLUI::sDirtyRect = t_rect;
- }
-
- LLGLDisable cull(GL_CULL_FACE);
- LLGLDisable blend(GL_BLEND);
- S32 width = gViewerWindow->getWindowWidthScaled();
- S32 height = gViewerWindow->getWindowHeightScaled();
- gGL.getTexUnit(0)->bind(&gPipeline.mUIScreen);
- gGL.begin(LLRender::TRIANGLE_STRIP);
- gGL.color4f(1,1,1,1);
- gGL.texCoord2f(0, 0); gGL.vertex2i(0, 0);
- gGL.texCoord2f(width, 0); gGL.vertex2i(width, 0);
- gGL.texCoord2f(0, height); gGL.vertex2i(0, height);
- gGL.texCoord2f(width, height); gGL.vertex2i(width, height);
- gGL.end();
- }
- else
- {
- gViewerWindow->draw();
- }
-
-
-
- // reset current origin for font rendering, in case of tiling render
- LLFontGL::sCurOrigin.set(0, 0);
-}
-
-void render_disconnected_background()
-{
- gGL.color4f(1,1,1,1);
- if (!gDisconnectedImagep && gDisconnected)
- {
- llinfos << "Loading last bitmap..." << llendl;
-
- std::string temp_str;
- temp_str = gDirUtilp->getLindenUserDir() + gDirUtilp->getDirDelimiter() + SCREEN_LAST_FILENAME;
-
- LLPointer<LLImageBMP> image_bmp = new LLImageBMP;
- if( !image_bmp->load(temp_str) )
- {
- //llinfos << "Bitmap load failed" << llendl;
- return;
- }
-
- LLPointer<LLImageRaw> raw = new LLImageRaw;
- if (!image_bmp->decode(raw, 0.0f))
- {
- llinfos << "Bitmap decode failed" << llendl;
- gDisconnectedImagep = NULL;
- return;
- }
-
- U8 *rawp = raw->getData();
- S32 npixels = (S32)image_bmp->getWidth()*(S32)image_bmp->getHeight();
- for (S32 i = 0; i < npixels; i++)
- {
- S32 sum = 0;
- sum = *rawp + *(rawp+1) + *(rawp+2);
- sum /= 3;
- *rawp = ((S32)sum*6 + *rawp)/7;
- rawp++;
- *rawp = ((S32)sum*6 + *rawp)/7;
- rawp++;
- *rawp = ((S32)sum*6 + *rawp)/7;
- rawp++;
- }
-
-
- raw->expandToPowerOfTwo();
- gDisconnectedImagep = LLViewerTextureManager::getLocalTexture(raw.get(), FALSE );
- gStartTexture = gDisconnectedImagep;
- gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
- }
-
- // Make sure the progress view always fills the entire window.
- S32 width = gViewerWindow->getWindowWidthScaled();
- S32 height = gViewerWindow->getWindowHeightScaled();
-
- if (gDisconnectedImagep)
- {
- LLGLSUIDefault gls_ui;
- gViewerWindow->setup2DRender();
- glPushMatrix();
- {
- // scale ui to reflect UIScaleFactor
- // this can't be done in setup2DRender because it requires a
- // pushMatrix/popMatrix pair
- const LLVector2& display_scale = gViewerWindow->getDisplayScale();
- glScalef(display_scale.mV[VX], display_scale.mV[VY], 1.f);
-
- gGL.getTexUnit(0)->bind(gDisconnectedImagep);
- gGL.color4f(1.f, 1.f, 1.f, 1.f);
- gl_rect_2d_simple_tex(width, height);
- gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
- }
- glPopMatrix();
- }
- gGL.flush();
-}
-
-void display_cleanup()
-{
- gDisconnectedImagep = NULL;
-}
+/**
+ * @file llviewerdisplay.cpp
+ * @brief LLViewerDisplay class implementation
+ *
+ * $LicenseInfo:firstyear=2004&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h"
+
+#include "llviewerdisplay.h"
+
+#include "llgl.h"
+#include "llrender.h"
+#include "llglheaders.h"
+#include "llagent.h"
+#include "llagentcamera.h"
+#include "llviewercontrol.h"
+#include "llcoord.h"
+#include "llcriticaldamp.h"
+#include "lldir.h"
+#include "lldynamictexture.h"
+#include "lldrawpoolalpha.h"
+#include "llfeaturemanager.h"
+//#include "llfirstuse.h"
+#include "llhudmanager.h"
+#include "llimagebmp.h"
+#include "llmemory.h"
+#include "llselectmgr.h"
+#include "llsky.h"
+#include "llstartup.h"
+#include "lltoolfocus.h"
+#include "lltoolmgr.h"
+#include "lltooldraganddrop.h"
+#include "lltoolpie.h"
+#include "lltracker.h"
+#include "lltrans.h"
+#include "llui.h"
+#include "llviewercamera.h"
+#include "llviewerobjectlist.h"
+#include "llviewerparcelmgr.h"
+#include "llviewerwindow.h"
+#include "llvoavatarself.h"
+#include "llvograss.h"
+#include "llworld.h"
+#include "pipeline.h"
+#include "llspatialpartition.h"
+#include "llappviewer.h"
+#include "llstartup.h"
+#include "llviewershadermgr.h"
+#include "llfasttimer.h"
+#include "llfloatertools.h"
+#include "llviewertexturelist.h"
+#include "llfocusmgr.h"
+#include "llcubemap.h"
+#include "llviewerregion.h"
+#include "lldrawpoolwater.h"
+#include "lldrawpoolbump.h"
+#include "llwlparammanager.h"
+#include "llwaterparammanager.h"
+#include "llpostprocess.h"
+
+extern LLPointer<LLViewerTexture> gStartTexture;
+
+LLPointer<LLViewerTexture> gDisconnectedImagep = NULL;
+
+// used to toggle renderer back on after teleport
+const F32 TELEPORT_RENDER_DELAY = 20.f; // Max time a teleport is allowed to take before we raise the curtain
+const F32 TELEPORT_ARRIVAL_DELAY = 2.f; // Time to preload the world before raising the curtain after we've actually already arrived.
+const F32 TELEPORT_LOCAL_DELAY = 1.0f; // Delay to prevent teleports after starting an in-sim teleport.
+BOOL gTeleportDisplay = FALSE;
+LLFrameTimer gTeleportDisplayTimer;
+LLFrameTimer gTeleportArrivalTimer;
+const F32 RESTORE_GL_TIME = 5.f; // Wait this long while reloading textures before we raise the curtain
+
+BOOL gForceRenderLandFence = FALSE;
+BOOL gDisplaySwapBuffers = FALSE;
+BOOL gDepthDirty = FALSE;
+BOOL gResizeScreenTexture = FALSE;
+BOOL gWindowResized = FALSE;
+BOOL gSnapshot = FALSE;
+
+U32 gRecentFrameCount = 0; // number of 'recent' frames
+LLFrameTimer gRecentFPSTime;
+LLFrameTimer gRecentMemoryTime;
+
+// Rendering stuff
+void pre_show_depth_buffer();
+void post_show_depth_buffer();
+void render_ui(F32 zoom_factor = 1.f, int subfield = 0);
+void render_hud_attachments();
+void render_ui_3d();
+void render_ui_2d();
+void render_disconnected_background();
+
+void display_startup()
+{
+ if ( !gViewerWindow->getActive()
+ || !gViewerWindow->mWindow->getVisible()
+ || gViewerWindow->mWindow->getMinimized()
+ || gNoRender )
+ {
+ return;
+ }
+
+ gPipeline.updateGL();
+
+ // Update images?
+ //gImageList.updateImages(0.01f);
+
+ LLGLSDefault gls_default;
+
+ // Required for HTML update in login screen
+ static S32 frame_count = 0;
+
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+
+ if (frame_count++ > 1) // make sure we have rendered a frame first
+ {
+ LLViewerDynamicTexture::updateAllInstances();
+ }
+
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+
+ glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
+ LLGLSUIDefault gls_ui;
+ gPipeline.disableLights();
+
+ gViewerWindow->setup2DRender();
+ gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
+
+ gGL.color4f(1,1,1,1);
+ gViewerWindow->draw();
+ gGL.flush();
+
+ LLVertexBuffer::unbind();
+
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+
+ gViewerWindow->mWindow->swapBuffers();
+ glClear(GL_DEPTH_BUFFER_BIT);
+}
+
+void display_update_camera()
+{
+ LLMemType mt_uc(LLMemType::MTYPE_DISPLAY_UPDATE_CAMERA);
+ // TODO: cut draw distance down if customizing avatar?
+ // TODO: cut draw distance on per-parcel basis?
+
+ // Cut draw distance in half when customizing avatar,
+ // but on the viewer only.
+ F32 final_far = gAgentCamera.mDrawDistance;
+ if (CAMERA_MODE_CUSTOMIZE_AVATAR == gAgentCamera.getCameraMode())
+ {
+ final_far *= 0.5f;
+ }
+ LLViewerCamera::getInstance()->setFar(final_far);
+ gViewerWindow->setup3DRender();
+
+ // update all the sky/atmospheric/water settings
+ LLWLParamManager::instance()->update(LLViewerCamera::getInstance());
+ LLWaterParamManager::instance()->update(LLViewerCamera::getInstance());
+
+ // Update land visibility too
+ LLWorld::getInstance()->setLandFarClip(final_far);
+}
+
+// Write some stats to llinfos
+void display_stats()
+{
+ F32 fps_log_freq = gSavedSettings.getF32("FPSLogFrequency");
+ if (fps_log_freq > 0.f && gRecentFPSTime.getElapsedTimeF32() >= fps_log_freq)
+ {
+ F32 fps = gRecentFrameCount / fps_log_freq;
+ llinfos << llformat("FPS: %.02f", fps) << llendl;
+ gRecentFrameCount = 0;
+ gRecentFPSTime.reset();
+ }
+ F32 mem_log_freq = gSavedSettings.getF32("MemoryLogFrequency");
+ if (mem_log_freq > 0.f && gRecentMemoryTime.getElapsedTimeF32() >= mem_log_freq)
+ {
+ gMemoryAllocated = LLMemory::getCurrentRSS();
+ U32 memory = (U32)(gMemoryAllocated / (1024*1024));
+ llinfos << llformat("MEMORY: %d MB", memory) << llendl;
+ gRecentMemoryTime.reset();
+ }
+}
+
+static LLFastTimer::DeclareTimer FTM_PICK("Picking");
+static LLFastTimer::DeclareTimer FTM_RENDER("Render", true);
+static LLFastTimer::DeclareTimer FTM_UPDATE_SKY("Update Sky");
+static LLFastTimer::DeclareTimer FTM_UPDATE_TEXTURES("Update Textures");
+static LLFastTimer::DeclareTimer FTM_IMAGE_UPDATE("Update Images");
+
+// Paint the display!
+void display(BOOL rebuild, F32 zoom_factor, int subfield, BOOL for_snapshot)
+{
+ LLMemType mt_render(LLMemType::MTYPE_RENDER);
+ LLFastTimer t(FTM_RENDER);
+
+ if (gWindowResized)
+ { //skip render on frames where window has been resized
+ gGL.flush();
+ glClear(GL_COLOR_BUFFER_BIT);
+ gViewerWindow->mWindow->swapBuffers();
+ gPipeline.resizeScreenTexture();
+ gResizeScreenTexture = FALSE;
+ gWindowResized = FALSE;
+ return;
+ }
+
+ if (LLPipeline::sRenderDeferred)
+ { //hack to make sky show up in deferred snapshots
+ for_snapshot = FALSE;
+ }
+
+ if (LLPipeline::sRenderFrameTest)
+ {
+ send_agent_pause();
+ }
+
+ gSnapshot = for_snapshot;
+
+ LLGLSDefault gls_default;
+ LLGLDepthTest gls_depth(GL_TRUE, GL_TRUE, GL_LEQUAL);
+
+ LLVertexBuffer::unbind();
+
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+
+ stop_glerror();
+
+ gPipeline.disableLights();
+
+ stop_glerror();
+
+ // Don't draw if the window is hidden or minimized.
+ // In fact, must explicitly check the minimized state before drawing.
+ // Attempting to draw into a minimized window causes a GL error. JC
+ if ( !gViewerWindow->getActive()
+ || !gViewerWindow->mWindow->getVisible()
+ || gViewerWindow->mWindow->getMinimized() )
+ {
+ // Clean up memory the pools may have allocated
+ if (rebuild)
+ {
+ stop_glerror();
+ gPipeline.rebuildPools();
+ stop_glerror();
+ }
+
+ stop_glerror();
+ gViewerWindow->returnEmptyPicks();
+ stop_glerror();
+ return;
+ }
+
+ gViewerWindow->checkSettings();
+
+ {
+ LLFastTimer ftm(FTM_PICK);
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Pick");
+ gViewerWindow->performPick();
+ }
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:CheckStates");
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+
+ //////////////////////////////////////////////////////////
+ //
+ // Logic for forcing window updates if we're in drone mode.
+ //
+
+ if (gNoRender)
+ {
+#if LL_WINDOWS
+ static F32 last_update_time = 0.f;
+ if ((gFrameTimeSeconds - last_update_time) > 1.f)
+ {
+ InvalidateRect((HWND)gViewerWindow->getPlatformWindow(), NULL, FALSE);
+ last_update_time = gFrameTimeSeconds;
+ }
+#elif LL_DARWIN
+ // MBW -- Do something clever here.
+#endif
+ // Not actually rendering, don't bother.
+ return;
+ }
+
+
+ //
+ // Bail out if we're in the startup state and don't want to try to
+ // render the world.
+ //
+ if (LLStartUp::getStartupState() < STATE_STARTED)
+ {
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Startup");
+ display_startup();
+ return;
+ }
+
+ //LLGLState::verify(FALSE);
+
+ /////////////////////////////////////////////////
+ //
+ // Update GL Texture statistics (used for discard logic?)
+ //
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:TextureStats");
+ stop_glerror();
+
+ LLImageGL::updateStats(gFrameTimeSeconds);
+
+ LLVOAvatar::sRenderName = gSavedSettings.getS32("AvatarNameTagMode");
+ LLVOAvatar::sRenderGroupTitles = (gSavedSettings.getBOOL("NameTagShowGroupTitles") && gSavedSettings.getS32("AvatarNameTagMode"));
+
+ gPipeline.mBackfaceCull = TRUE;
+ gFrameCount++;
+ gRecentFrameCount++;
+ if (gFocusMgr.getAppHasFocus())
+ {
+ gForegroundFrameCount++;
+ }
+
+ //////////////////////////////////////////////////////////
+ //
+ // Display start screen if we're teleporting, and skip render
+ //
+
+ if (gTeleportDisplay)
+ {
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Teleport");
+ const F32 TELEPORT_ARRIVAL_DELAY = 2.f; // Time to preload the world before raising the curtain after we've actually already arrived.
+
+ S32 attach_count = 0;
+ if (isAgentAvatarValid())
+ {
+ attach_count = gAgentAvatarp->getAttachmentCount();
+ }
+ F32 teleport_save_time = TELEPORT_EXPIRY + TELEPORT_EXPIRY_PER_ATTACHMENT * attach_count;
+ F32 teleport_elapsed = gTeleportDisplayTimer.getElapsedTimeF32();
+ F32 teleport_percent = teleport_elapsed * (100.f / teleport_save_time);
+ if( (gAgent.getTeleportState() != LLAgent::TELEPORT_START) && (teleport_percent > 100.f) )
+ {
+ // Give up. Don't keep the UI locked forever.
+ gAgent.setTeleportState( LLAgent::TELEPORT_NONE );
+ gAgent.setTeleportMessage(std::string());
+ }
+
+ const std::string& message = gAgent.getTeleportMessage();
+ switch( gAgent.getTeleportState() )
+ {
+ case LLAgent::TELEPORT_START:
+ // Transition to REQUESTED. Viewer has sent some kind
+ // of TeleportRequest to the source simulator
+ gTeleportDisplayTimer.reset();
+ gViewerWindow->setShowProgress(TRUE);
+ gViewerWindow->setProgressPercent(0);
+ gAgent.setTeleportState( LLAgent::TELEPORT_REQUESTED );
+ gAgent.setTeleportMessage(
+ LLAgent::sTeleportProgressMessages["requesting"]);
+ break;
+
+ case LLAgent::TELEPORT_REQUESTED:
+ // Waiting for source simulator to respond
+ gViewerWindow->setProgressPercent( llmin(teleport_percent, 37.5f) );
+ gViewerWindow->setProgressString(message);
+ break;
+
+ case LLAgent::TELEPORT_MOVING:
+ // Viewer has received destination location from source simulator
+ gViewerWindow->setProgressPercent( llmin(teleport_percent, 75.f) );
+ gViewerWindow->setProgressString(message);
+ break;
+
+ case LLAgent::TELEPORT_START_ARRIVAL:
+ // Transition to ARRIVING. Viewer has received avatar update, etc., from destination simulator
+ gTeleportArrivalTimer.reset();
+ gViewerWindow->setProgressCancelButtonVisible(FALSE, LLTrans::getString("Cancel"));
+ gViewerWindow->setProgressPercent(75.f);
+ gAgent.setTeleportState( LLAgent::TELEPORT_ARRIVING );
+ gAgent.setTeleportMessage(
+ LLAgent::sTeleportProgressMessages["arriving"]);
+ gTextureList.mForceResetTextureStats = TRUE;
+ gAgentCamera.resetView(TRUE, TRUE);
+ break;
+
+ case LLAgent::TELEPORT_ARRIVING:
+ // Make the user wait while content "pre-caches"
+ {
+ F32 arrival_fraction = (gTeleportArrivalTimer.getElapsedTimeF32() / TELEPORT_ARRIVAL_DELAY);
+ if( arrival_fraction > 1.f )
+ {
+ arrival_fraction = 1.f;
+ //LLFirstUse::useTeleport();
+ gAgent.setTeleportState( LLAgent::TELEPORT_NONE );
+ }
+ gViewerWindow->setProgressCancelButtonVisible(FALSE, LLTrans::getString("Cancel"));
+ gViewerWindow->setProgressPercent( arrival_fraction * 25.f + 75.f);
+ gViewerWindow->setProgressString(message);
+ }
+ break;
+
+ case LLAgent::TELEPORT_LOCAL:
+ // Short delay when teleporting in the same sim (progress screen active but not shown - did not
+ // fall-through from TELEPORT_START)
+ {
+ if( gTeleportDisplayTimer.getElapsedTimeF32() > TELEPORT_LOCAL_DELAY )
+ {
+ //LLFirstUse::useTeleport();
+ gAgent.setTeleportState( LLAgent::TELEPORT_NONE );
+ }
+ }
+ break;
+
+ case LLAgent::TELEPORT_NONE:
+ // No teleport in progress
+ gViewerWindow->setShowProgress(FALSE);
+ gTeleportDisplay = FALSE;
+ break;
+ }
+ }
+ else if(LLAppViewer::instance()->logoutRequestSent())
+ {
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Logout");
+ F32 percent_done = gLogoutTimer.getElapsedTimeF32() * 100.f / gLogoutMaxTime;
+ if (percent_done > 100.f)
+ {
+ percent_done = 100.f;
+ }
+
+ if( LLApp::isExiting() )
+ {
+ percent_done = 100.f;
+ }
+
+ gViewerWindow->setProgressPercent( percent_done );
+ }
+ else
+ if (gRestoreGL)
+ {
+ LLAppViewer::instance()->pingMainloopTimeout("Display:RestoreGL");
+ F32 percent_done = gRestoreGLTimer.getElapsedTimeF32() * 100.f / RESTORE_GL_TIME;
+ if( percent_done > 100.f )
+ {
+ gViewerWindow->setShowProgress(FALSE);
+ gRestoreGL = FALSE;
+ }
+ else
+ {
+
+ if( LLApp::isExiting() )
+ {
+ percent_done = 100.f;
+ }
+
+ gViewerWindow->setProgressPercent( percent_done );
+ }
+ }
+
+ //////////////////////////
+ //
+ // Prepare for the next frame
+ //
+
+ /////////////////////////////
+ //
+ // Update the camera
+ //
+ //
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Camera");
+ LLViewerCamera::getInstance()->setZoomParameters(zoom_factor, subfield);
+ LLViewerCamera::getInstance()->setNear(MIN_NEAR_PLANE);
+
+ //////////////////////////
+ //
+ // clear the next buffer
+ // (must follow dynamic texture writing since that uses the frame buffer)
+ //
+
+ if (gDisconnected)
+ {
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Disconnected");
+ render_ui();
+ }
+
+ //////////////////////////
+ //
+ // Set rendering options
+ //
+ //
+ LLAppViewer::instance()->pingMainloopTimeout("Display:RenderSetup");
+ stop_glerror();
+
+ ///////////////////////////////////////
+ //
+ // Slam lighting parameters back to our defaults.
+ // Note that these are not the same as GL defaults...
+
+ stop_glerror();
+ F32 one[4] = {1.f, 1.f, 1.f, 1.f};
+ glLightModelfv (GL_LIGHT_MODEL_AMBIENT,one);
+ stop_glerror();
+
+ /////////////////////////////////////
+ //
+ // Render
+ //
+ // Actually push all of our triangles to the screen.
+ //
+
+ // do render-to-texture stuff here
+ if (gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_DYNAMIC_TEXTURES))
+ {
+ LLAppViewer::instance()->pingMainloopTimeout("Display:DynamicTextures");
+ LLFastTimer t(FTM_UPDATE_TEXTURES);
+ if (LLViewerDynamicTexture::updateAllInstances())
+ {
+ gGL.setColorMask(true, true);
+ glClear(GL_DEPTH_BUFFER_BIT);
+ }
+ }
+
+ gViewerWindow->setup3DViewport();
+
+ gPipeline.resetFrameStats(); // Reset per-frame statistics.
+
+ if (!gDisconnected)
+ {
+ LLMemType mt_du(LLMemType::MTYPE_DISPLAY_UPDATE);
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Update");
+ if (gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_HUD))
+ { //don't draw hud objects in this frame
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD);
+ }
+
+ if (gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_HUD_PARTICLES))
+ { //don't draw hud particles in this frame
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD_PARTICLES);
+ }
+
+ //upkeep gl name pools
+ LLGLNamePool::upkeepPools();
+
+ stop_glerror();
+ display_update_camera();
+ stop_glerror();
+
+ // *TODO: merge these two methods
+ {
+ LLMemType mt_uh(LLMemType::MTYPE_DISPLAY_UPDATE_HUD);
+ LLHUDManager::getInstance()->updateEffects();
+ LLHUDObject::updateAll();
+ stop_glerror();
+ }
+
+ {
+ LLMemType mt_ug(LLMemType::MTYPE_DISPLAY_UPDATE_GEOM);
+ const F32 max_geom_update_time = 0.005f*10.f*gFrameIntervalSeconds; // 50 ms/second update time
+ gPipeline.createObjects(max_geom_update_time);
+ gPipeline.updateGeom(max_geom_update_time);
+ stop_glerror();
+ }
+
+ gPipeline.updateGL();
+ stop_glerror();
+
+ S32 water_clip = 0;
+ if ((LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_ENVIRONMENT) > 1) &&
+ (gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_WATER) ||
+ gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_VOIDWATER)))
+ {
+ if (LLViewerCamera::getInstance()->cameraUnderWater())
+ {
+ water_clip = -1;
+ }
+ else
+ {
+ water_clip = 1;
+ }
+ }
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Cull");
+
+ //Increment drawable frame counter
+ LLDrawable::incrementVisible();
+
+ LLSpatialGroup::sNoDelete = TRUE;
+ LLPipeline::sUseOcclusion =
+ (!gUseWireframe
+ && LLFeatureManager::getInstance()->isFeatureAvailable("UseOcclusion")
+ && gSavedSettings.getBOOL("UseOcclusion")
+ && gGLManager.mHasOcclusionQuery) ? 2 : 0;
+
+ /*if (LLPipeline::sUseOcclusion && LLPipeline::sRenderDeferred)
+ { //force occlusion on for all render types if doing deferred render (tighter shadow frustum)
+ LLPipeline::sUseOcclusion = 3;
+ }*/
+
+ LLPipeline::sAutoMaskAlphaDeferred = gSavedSettings.getBOOL("RenderAutoMaskAlphaDeferred");
+ LLPipeline::sAutoMaskAlphaNonDeferred = gSavedSettings.getBOOL("RenderAutoMaskAlphaNonDeferred");
+ LLPipeline::sUseFarClip = gSavedSettings.getBOOL("RenderUseFarClip");
+ LLVOAvatar::sMaxVisible = (U32)gSavedSettings.getS32("RenderAvatarMaxVisible");
+ LLPipeline::sDelayVBUpdate = gSavedSettings.getBOOL("RenderDelayVBUpdate");
+
+ S32 occlusion = LLPipeline::sUseOcclusion;
+ if (gDepthDirty)
+ { //depth buffer is invalid, don't overwrite occlusion state
+ LLPipeline::sUseOcclusion = llmin(occlusion, 1);
+ }
+ gDepthDirty = FALSE;
+
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+ LLGLState::checkClientArrays();
+
+ static LLCullResult result;
+ LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WORLD;
+ gPipeline.updateCull(*LLViewerCamera::getInstance(), result, water_clip);
+ stop_glerror();
+
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+ LLGLState::checkClientArrays();
+
+ BOOL to_texture = gPipeline.canUseVertexShaders() &&
+ LLPipeline::sRenderGlow;
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Swap");
+
+ {
+ LLMemType mt_ds(LLMemType::MTYPE_DISPLAY_SWAP);
+ {
+ LLFastTimer ftm(FTM_CLIENT_COPY);
+ LLVertexBuffer::clientCopy(0.016);
+ }
+
+ if (gResizeScreenTexture)
+ {
+ gResizeScreenTexture = FALSE;
+ gPipeline.resizeScreenTexture();
+ }
+
+ gGL.setColorMask(true, true);
+ glClearColor(0,0,0,0);
+
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+ LLGLState::checkClientArrays();
+
+ if (!for_snapshot)
+ {
+ if (gFrameCount > 1)
+ { //for some reason, ATI 4800 series will error out if you
+ //try to generate a shadow before the first frame is through
+ gPipeline.generateSunShadow(*LLViewerCamera::getInstance());
+ }
+
+ LLVertexBuffer::unbind();
+
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+ LLGLState::checkClientArrays();
+
+ glh::matrix4f proj = glh_get_current_projection();
+ glh::matrix4f mod = glh_get_current_modelview();
+ glViewport(0,0,512,512);
+ LLVOAvatar::updateFreezeCounter() ;
+ LLVOAvatar::updateImpostors();
+
+ glh_set_current_projection(proj);
+ glh_set_current_modelview(mod);
+ glMatrixMode(GL_PROJECTION);
+ glLoadMatrixf(proj.m);
+ glMatrixMode(GL_MODELVIEW);
+ glLoadMatrixf(mod.m);
+ gViewerWindow->setup3DViewport();
+
+ LLGLState::checkStates();
+ LLGLState::checkTextureChannels();
+ LLGLState::checkClientArrays();
+
+ }
+ glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
+ }
+
+ //if (!for_snapshot)
+ {
+ LLMemType mt_gw(LLMemType::MTYPE_DISPLAY_GEN_REFLECTION);
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Imagery");
+ gPipeline.generateWaterReflection(*LLViewerCamera::getInstance());
+ gPipeline.generateHighlight(*LLViewerCamera::getInstance());
+ }
+
+ //////////////////////////////////////
+ //
+ // Update images, using the image stats generated during object update/culling
+ //
+ // Can put objects onto the retextured list.
+ //
+ // Doing this here gives hardware occlusion queries extra time to complete
+ LLAppViewer::instance()->pingMainloopTimeout("Display:UpdateImages");
+
+ {
+ LLMemType mt_iu(LLMemType::MTYPE_DISPLAY_IMAGE_UPDATE);
+ LLFastTimer t(FTM_IMAGE_UPDATE);
+
+ LLViewerTexture::updateClass(LLViewerCamera::getInstance()->getVelocityStat()->getMean(),
+ LLViewerCamera::getInstance()->getAngularVelocityStat()->getMean());
+
+ gBumpImageList.updateImages(); // must be called before gTextureList version so that it's textures are thrown out first.
+
+ F32 max_image_decode_time = 0.050f*gFrameIntervalSeconds; // 50 ms/second decode time
+ max_image_decode_time = llclamp(max_image_decode_time, 0.002f, 0.005f ); // min 2ms/frame, max 5ms/frame)
+ gTextureList.updateImages(max_image_decode_time);
+
+ //remove dead textures from GL
+ LLImageGL::deleteDeadTextures();
+ stop_glerror();
+ }
+ ///////////////////////////////////
+ //
+ // StateSort
+ //
+ // Responsible for taking visible objects, and adding them to the appropriate draw orders.
+ // In the case of alpha objects, z-sorts them first.
+ // Also creates special lists for outlines and selected face rendering.
+ //
+ LLAppViewer::instance()->pingMainloopTimeout("Display:StateSort");
+ {
+ LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WORLD;
+ LLMemType mt_ss(LLMemType::MTYPE_DISPLAY_STATE_SORT);
+ gPipeline.stateSort(*LLViewerCamera::getInstance(), result);
+ stop_glerror();
+
+ if (rebuild)
+ {
+ //////////////////////////////////////
+ //
+ // rebuildPools
+ //
+ //
+ gPipeline.rebuildPools();
+ stop_glerror();
+ }
+ }
+
+ LLPipeline::sUseOcclusion = occlusion;
+
+ {
+ LLMemType mt_ds(LLMemType::MTYPE_DISPLAY_SKY);
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Sky");
+ LLFastTimer t(FTM_UPDATE_SKY);
+ gSky.updateSky();
+ }
+
+ if(gUseWireframe)
+ {
+ glClearColor(0.5f, 0.5f, 0.5f, 0.f);
+ glClear(GL_COLOR_BUFFER_BIT);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ }
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:RenderStart");
+
+ //// render frontmost floater opaque for occlusion culling purposes
+ //LLFloater* frontmost_floaterp = gFloaterView->getFrontmost();
+ //// assumes frontmost floater with focus is opaque
+ //if (frontmost_floaterp && gFocusMgr.childHasKeyboardFocus(frontmost_floaterp))
+ //{
+ // glMatrixMode(GL_MODELVIEW);
+ // glPushMatrix();
+ // {
+ // gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+
+ // glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE);
+ // glLoadIdentity();
+
+ // LLRect floater_rect = frontmost_floaterp->calcScreenRect();
+ // // deflate by one pixel so rounding errors don't occlude outside of floater extents
+ // floater_rect.stretch(-1);
+ // LLRectf floater_3d_rect((F32)floater_rect.mLeft / (F32)gViewerWindow->getWindowWidthScaled(),
+ // (F32)floater_rect.mTop / (F32)gViewerWindow->getWindowHeightScaled(),
+ // (F32)floater_rect.mRight / (F32)gViewerWindow->getWindowWidthScaled(),
+ // (F32)floater_rect.mBottom / (F32)gViewerWindow->getWindowHeightScaled());
+ // floater_3d_rect.translate(-0.5f, -0.5f);
+ // glTranslatef(0.f, 0.f, -LLViewerCamera::getInstance()->getNear());
+ // glScalef(LLViewerCamera::getInstance()->getNear() * LLViewerCamera::getInstance()->getAspect() / sinf(LLViewerCamera::getInstance()->getView()), LLViewerCamera::getInstance()->getNear() / sinf(LLViewerCamera::getInstance()->getView()), 1.f);
+ // gGL.color4fv(LLColor4::white.mV);
+ // gGL.begin(LLVertexBuffer::QUADS);
+ // {
+ // gGL.vertex3f(floater_3d_rect.mLeft, floater_3d_rect.mBottom, 0.f);
+ // gGL.vertex3f(floater_3d_rect.mLeft, floater_3d_rect.mTop, 0.f);
+ // gGL.vertex3f(floater_3d_rect.mRight, floater_3d_rect.mTop, 0.f);
+ // gGL.vertex3f(floater_3d_rect.mRight, floater_3d_rect.mBottom, 0.f);
+ // }
+ // gGL.end();
+ // glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+ // }
+ // glPopMatrix();
+ //}
+
+ LLPipeline::sUnderWaterRender = LLViewerCamera::getInstance()->cameraUnderWater() ? TRUE : FALSE;
+ LLPipeline::updateRenderDeferred();
+
+ stop_glerror();
+
+ if (to_texture)
+ {
+ gGL.setColorMask(true, true);
+
+ if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender)
+ {
+ gPipeline.mDeferredScreen.bindTarget();
+ glClearColor(0,0,0,0);
+ gPipeline.mDeferredScreen.clear();
+ }
+ else
+ {
+ gPipeline.mScreen.bindTarget();
+ gPipeline.mScreen.clear();
+ }
+
+ gGL.setColorMask(true, false);
+ }
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:RenderGeom");
+
+ if (!(LLAppViewer::instance()->logoutRequestSent() && LLAppViewer::instance()->hasSavedFinalSnapshot())
+ && !gRestoreGL)
+ {
+ LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WORLD;
+ LLMemType mt_rg(LLMemType::MTYPE_DISPLAY_RENDER_GEOM);
+ gGL.setColorMask(true, false);
+ if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender)
+ {
+ gPipeline.renderGeomDeferred(*LLViewerCamera::getInstance());
+ }
+ else
+ {
+ gPipeline.renderGeom(*LLViewerCamera::getInstance(), TRUE);
+ }
+
+ gGL.setColorMask(true, true);
+
+ //store this frame's modelview matrix for use
+ //when rendering next frame's occlusion queries
+ for (U32 i = 0; i < 16; i++)
+ {
+ gGLLastModelView[i] = gGLModelView[i];
+ gGLLastProjection[i] = gGLProjection[i];
+ }
+ stop_glerror();
+ }
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:RenderFlush");
+
+ if (to_texture)
+ {
+ LLMemType mt_rf(LLMemType::MTYPE_DISPLAY_RENDER_FLUSH);
+ if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender)
+ {
+ gPipeline.mDeferredScreen.flush();
+ if(LLRenderTarget::sUseFBO)
+ {
+ LLRenderTarget::copyContentsToFramebuffer(gPipeline.mDeferredScreen, 0, 0, gPipeline.mDeferredScreen.getWidth(),
+ gPipeline.mDeferredScreen.getHeight(), 0, 0,
+ gPipeline.mDeferredScreen.getWidth(),
+ gPipeline.mDeferredScreen.getHeight(),
+ GL_DEPTH_BUFFER_BIT, GL_NEAREST);
+ }
+ }
+ else
+ {
+ gPipeline.mScreen.flush();
+ if(LLRenderTarget::sUseFBO)
+ {
+ LLRenderTarget::copyContentsToFramebuffer(gPipeline.mScreen, 0, 0, gPipeline.mScreen.getWidth(),
+ gPipeline.mScreen.getHeight(), 0, 0,
+ gPipeline.mScreen.getWidth(),
+ gPipeline.mScreen.getHeight(),
+ GL_DEPTH_BUFFER_BIT, GL_NEAREST);
+ }
+ }
+ }
+
+ if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender)
+ {
+ gPipeline.renderDeferredLighting();
+ }
+
+ LLPipeline::sUnderWaterRender = FALSE;
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:RenderUI");
+ if (!for_snapshot)
+ {
+ LLFastTimer t(FTM_RENDER_UI);
+ render_ui();
+ }
+
+
+ LLSpatialGroup::sNoDelete = FALSE;
+ gPipeline.clearReferences();
+
+ gPipeline.rebuildGroups();
+ }
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:FrameStats");
+
+ stop_glerror();
+
+ if (LLPipeline::sRenderFrameTest)
+ {
+ send_agent_resume();
+ LLPipeline::sRenderFrameTest = FALSE;
+ }
+
+ display_stats();
+
+ LLAppViewer::instance()->pingMainloopTimeout("Display:Done");
+}
+
+void render_hud_attachments()
+{
+ LLMemType mt_ra(LLMemType::MTYPE_DISPLAY_RENDER_ATTACHMENTS);
+ glMatrixMode(GL_PROJECTION);
+ glPushMatrix();
+ glMatrixMode(GL_MODELVIEW);
+ glPushMatrix();
+
+ glh::matrix4f current_proj = glh_get_current_projection();
+ glh::matrix4f current_mod = glh_get_current_modelview();
+
+ // clamp target zoom level to reasonable values
+ gAgentCamera.mHUDTargetZoom = llclamp(gAgentCamera.mHUDTargetZoom, 0.1f, 1.f);
+ // smoothly interpolate current zoom level
+ gAgentCamera.mHUDCurZoom = lerp(gAgentCamera.mHUDCurZoom, gAgentCamera.mHUDTargetZoom, LLCriticalDamp::getInterpolant(0.03f));
+
+ if (LLPipeline::sShowHUDAttachments && !gDisconnected && setup_hud_matrices())
+ {
+ LLCamera hud_cam = *LLViewerCamera::getInstance();
+ LLVector3 origin = hud_cam.getOrigin();
+ hud_cam.setOrigin(-1.f,0,0);
+ hud_cam.setAxes(LLVector3(1,0,0), LLVector3(0,1,0), LLVector3(0,0,1));
+ LLViewerCamera::updateFrustumPlanes(hud_cam, TRUE);
+
+ bool render_particles = gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_PARTICLES) && gSavedSettings.getBOOL("RenderHUDParticles");
+
+ //only render hud objects
+ gPipeline.pushRenderTypeMask();
+
+ // turn off everything
+ gPipeline.andRenderTypeMask(LLPipeline::END_RENDER_TYPES);
+ // turn on HUD
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD);
+ // turn on HUD particles
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD_PARTICLES);
+
+ // if particles are off, turn off hud-particles as well
+ if (!render_particles)
+ {
+ // turn back off HUD particles
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD_PARTICLES);
+ }
+
+ bool has_ui = gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI);
+ if (has_ui)
+ {
+ gPipeline.toggleRenderDebugFeature((void*) LLPipeline::RENDER_DEBUG_FEATURE_UI);
+ }
+
+ S32 use_occlusion = LLPipeline::sUseOcclusion;
+ LLPipeline::sUseOcclusion = 0;
+ LLPipeline::sDisableShaders = TRUE;
+
+ //cull, sort, and render hud objects
+ static LLCullResult result;
+ LLSpatialGroup::sNoDelete = TRUE;
+
+ LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WORLD;
+ gPipeline.updateCull(hud_cam, result);
+
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_BUMP);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_SIMPLE);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_VOLUME);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_ALPHA);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_FULLBRIGHT);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_ALPHA);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_ALPHA_MASK);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_BUMP);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_FULLBRIGHT);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_FULLBRIGHT_ALPHA_MASK);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_FULLBRIGHT_SHINY);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_SHINY);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_INVISIBLE);
+ gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_PASS_INVISI_SHINY);
+
+ gPipeline.stateSort(hud_cam, result);
+
+ gPipeline.renderGeom(hud_cam);
+
+ LLSpatialGroup::sNoDelete = FALSE;
+ gPipeline.clearReferences();
+
+ render_hud_elements();
+
+ //restore type mask
+ gPipeline.popRenderTypeMask();
+
+ if (has_ui)
+ {
+ gPipeline.toggleRenderDebugFeature((void*) LLPipeline::RENDER_DEBUG_FEATURE_UI);
+ }
+ LLPipeline::sUseOcclusion = use_occlusion;
+ LLPipeline::sDisableShaders = FALSE;
+ }
+ glMatrixMode(GL_PROJECTION);
+ glPopMatrix();
+ glMatrixMode(GL_MODELVIEW);
+ glPopMatrix();
+
+ glh_set_current_projection(current_proj);
+ glh_set_current_modelview(current_mod);
+}
+
+LLRect get_whole_screen_region()
+{
+ LLRect whole_screen = gViewerWindow->getWorldViewRectScaled();
+
+ // apply camera zoom transform (for high res screenshots)
+ F32 zoom_factor = LLViewerCamera::getInstance()->getZoomFactor();
+ S16 sub_region = LLViewerCamera::getInstance()->getZoomSubRegion();
+ if (zoom_factor > 1.f)
+ {
+ S32 num_horizontal_tiles = llceil(zoom_factor);
+ S32 tile_width = llround((F32)gViewerWindow->getWorldViewWidthScaled() / zoom_factor);
+ S32 tile_height = llround((F32)gViewerWindow->getWorldViewHeightScaled() / zoom_factor);
+ int tile_y = sub_region / num_horizontal_tiles;
+ int tile_x = sub_region - (tile_y * num_horizontal_tiles);
+
+ whole_screen.setLeftTopAndSize(tile_x * tile_width, gViewerWindow->getWorldViewHeightScaled() - (tile_y * tile_height), tile_width, tile_height);
+ }
+ return whole_screen;
+}
+
+bool get_hud_matrices(const LLRect& screen_region, glh::matrix4f &proj, glh::matrix4f &model)
+{
+ if (isAgentAvatarValid() && gAgentAvatarp->hasHUDAttachment())
+ {
+ F32 zoom_level = gAgentCamera.mHUDCurZoom;
+ LLBBox hud_bbox = gAgentAvatarp->getHUDBBox();
+
+ F32 hud_depth = llmax(1.f, hud_bbox.getExtentLocal().mV[VX] * 1.1f);
+ proj = gl_ortho(-0.5f * LLViewerCamera::getInstance()->getAspect(), 0.5f * LLViewerCamera::getInstance()->getAspect(), -0.5f, 0.5f, 0.f, hud_depth);
+ proj.element(2,2) = -0.01f;
+
+ F32 aspect_ratio = LLViewerCamera::getInstance()->getAspect();
+
+ glh::matrix4f mat;
+ F32 scale_x = (F32)gViewerWindow->getWorldViewWidthScaled() / (F32)screen_region.getWidth();
+ F32 scale_y = (F32)gViewerWindow->getWorldViewHeightScaled() / (F32)screen_region.getHeight();
+ mat.set_scale(glh::vec3f(scale_x, scale_y, 1.f));
+ mat.set_translate(
+ glh::vec3f(clamp_rescale((F32)screen_region.getCenterX(), 0.f, (F32)gViewerWindow->getWorldViewWidthScaled(), 0.5f * scale_x * aspect_ratio, -0.5f * scale_x * aspect_ratio),
+ clamp_rescale((F32)screen_region.getCenterY(), 0.f, (F32)gViewerWindow->getWorldViewHeightScaled(), 0.5f * scale_y, -0.5f * scale_y),
+ 0.f));
+ proj *= mat;
+
+ glh::matrix4f tmp_model((GLfloat*) OGL_TO_CFR_ROTATION);
+
+ mat.set_scale(glh::vec3f(zoom_level, zoom_level, zoom_level));
+ mat.set_translate(glh::vec3f(-hud_bbox.getCenterLocal().mV[VX] + (hud_depth * 0.5f), 0.f, 0.f));
+
+ tmp_model *= mat;
+ model = tmp_model;
+ return TRUE;
+ }
+ else
+ {
+ return FALSE;
+ }
+}
+
+bool get_hud_matrices(glh::matrix4f &proj, glh::matrix4f &model)
+{
+ LLRect whole_screen = get_whole_screen_region();
+ return get_hud_matrices(whole_screen, proj, model);
+}
+
+BOOL setup_hud_matrices()
+{
+ LLRect whole_screen = get_whole_screen_region();
+ return setup_hud_matrices(whole_screen);
+}
+
+BOOL setup_hud_matrices(const LLRect& screen_region)
+{
+ glh::matrix4f proj, model;
+ bool result = get_hud_matrices(screen_region, proj, model);
+ if (!result) return result;
+
+ // set up transform to keep HUD objects in front of camera
+ glMatrixMode(GL_PROJECTION);
+ glLoadMatrixf(proj.m);
+ glh_set_current_projection(proj);
+
+ glMatrixMode(GL_MODELVIEW);
+ glLoadMatrixf(model.m);
+ glh_set_current_modelview(model);
+ return TRUE;
+}
+
+static LLFastTimer::DeclareTimer FTM_SWAP("Swap");
+
+void render_ui(F32 zoom_factor, int subfield)
+{
+ LLMemType mt_ru(LLMemType::MTYPE_DISPLAY_RENDER_UI);
+ LLGLState::checkStates();
+
+ glh::matrix4f saved_view = glh_get_current_modelview();
+
+ if (!gSnapshot)
+ {
+ glPushMatrix();
+ glLoadMatrixd(gGLLastModelView);
+ glh_set_current_modelview(glh_copy_matrix(gGLLastModelView));
+ }
+
+ {
+ BOOL to_texture = gPipeline.canUseVertexShaders() &&
+ LLPipeline::sRenderGlow;
+
+ if (to_texture)
+ {
+ gPipeline.renderBloom(gSnapshot, zoom_factor, subfield);
+ }
+
+ render_hud_elements();
+ render_hud_attachments();
+ }
+
+ LLGLSDefault gls_default;
+ LLGLSUIDefault gls_ui;
+ {
+ gPipeline.disableLights();
+ }
+
+ {
+ gGL.color4f(1,1,1,1);
+ if (gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
+ {
+ LLFastTimer t(FTM_RENDER_UI);
+
+ if (!gDisconnected)
+ {
+ render_ui_3d();
+ LLGLState::checkStates();
+ }
+ else
+ {
+ render_disconnected_background();
+ }
+
+ render_ui_2d();
+ LLGLState::checkStates();
+ }
+ gGL.flush();
+
+ {
+ gViewerWindow->setup2DRender();
+ gViewerWindow->updateDebugText();
+ gViewerWindow->drawDebugText();
+ }
+
+ LLVertexBuffer::unbind();
+ }
+
+ if (!gSnapshot)
+ {
+ glh_set_current_modelview(saved_view);
+ glPopMatrix();
+ }
+
+ if (gDisplaySwapBuffers)
+ {
+ LLFastTimer t(FTM_SWAP);
+ gViewerWindow->mWindow->swapBuffers();
+ }
+ gDisplaySwapBuffers = TRUE;
+}
+
+void renderCoordinateAxes()
+{
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ gGL.begin(LLRender::LINES);
+ gGL.color3f(1.0f, 0.0f, 0.0f); // i direction = X-Axis = red
+ gGL.vertex3f(0.0f, 0.0f, 0.0f);
+ gGL.vertex3f(2.0f, 0.0f, 0.0f);
+ gGL.vertex3f(3.0f, 0.0f, 0.0f);
+ gGL.vertex3f(5.0f, 0.0f, 0.0f);
+ gGL.vertex3f(6.0f, 0.0f, 0.0f);
+ gGL.vertex3f(8.0f, 0.0f, 0.0f);
+ // Make an X
+ gGL.vertex3f(11.0f, 1.0f, 1.0f);
+ gGL.vertex3f(11.0f, -1.0f, -1.0f);
+ gGL.vertex3f(11.0f, 1.0f, -1.0f);
+ gGL.vertex3f(11.0f, -1.0f, 1.0f);
+
+ gGL.color3f(0.0f, 1.0f, 0.0f); // j direction = Y-Axis = green
+ gGL.vertex3f(0.0f, 0.0f, 0.0f);
+ gGL.vertex3f(0.0f, 2.0f, 0.0f);
+ gGL.vertex3f(0.0f, 3.0f, 0.0f);
+ gGL.vertex3f(0.0f, 5.0f, 0.0f);
+ gGL.vertex3f(0.0f, 6.0f, 0.0f);
+ gGL.vertex3f(0.0f, 8.0f, 0.0f);
+ // Make a Y
+ gGL.vertex3f(1.0f, 11.0f, 1.0f);
+ gGL.vertex3f(0.0f, 11.0f, 0.0f);
+ gGL.vertex3f(-1.0f, 11.0f, 1.0f);
+ gGL.vertex3f(0.0f, 11.0f, 0.0f);
+ gGL.vertex3f(0.0f, 11.0f, 0.0f);
+ gGL.vertex3f(0.0f, 11.0f, -1.0f);
+
+ gGL.color3f(0.0f, 0.0f, 1.0f); // Z-Axis = blue
+ gGL.vertex3f(0.0f, 0.0f, 0.0f);
+ gGL.vertex3f(0.0f, 0.0f, 2.0f);
+ gGL.vertex3f(0.0f, 0.0f, 3.0f);
+ gGL.vertex3f(0.0f, 0.0f, 5.0f);
+ gGL.vertex3f(0.0f, 0.0f, 6.0f);
+ gGL.vertex3f(0.0f, 0.0f, 8.0f);
+ // Make a Z
+ gGL.vertex3f(-1.0f, 1.0f, 11.0f);
+ gGL.vertex3f(1.0f, 1.0f, 11.0f);
+ gGL.vertex3f(1.0f, 1.0f, 11.0f);
+ gGL.vertex3f(-1.0f, -1.0f, 11.0f);
+ gGL.vertex3f(-1.0f, -1.0f, 11.0f);
+ gGL.vertex3f(1.0f, -1.0f, 11.0f);
+ gGL.end();
+}
+
+
+void draw_axes()
+{
+ LLGLSUIDefault gls_ui;
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ // A vertical white line at origin
+ LLVector3 v = gAgent.getPositionAgent();
+ gGL.begin(LLRender::LINES);
+ gGL.color3f(1.0f, 1.0f, 1.0f);
+ gGL.vertex3f(0.0f, 0.0f, 0.0f);
+ gGL.vertex3f(0.0f, 0.0f, 40.0f);
+ gGL.end();
+ // Some coordinate axes
+ glPushMatrix();
+ glTranslatef( v.mV[VX], v.mV[VY], v.mV[VZ] );
+ renderCoordinateAxes();
+ glPopMatrix();
+}
+
+void render_ui_3d()
+{
+ LLGLSPipeline gls_pipeline;
+
+ //////////////////////////////////////
+ //
+ // Render 3D UI elements
+ // NOTE: zbuffer is cleared before we get here by LLDrawPoolHUD,
+ // so 3d elements requiring Z buffer are moved to LLDrawPoolHUD
+ //
+
+ /////////////////////////////////////////////////////////////
+ //
+ // Render 2.5D elements (2D elements in the world)
+ // Stuff without z writes
+ //
+
+ // Debugging stuff goes before the UI.
+
+ // Coordinate axes
+ if (gSavedSettings.getBOOL("ShowAxes"))
+ {
+ draw_axes();
+ }
+
+ stop_glerror();
+
+ gViewerWindow->renderSelections(FALSE, FALSE, TRUE); // Non HUD call in render_hud_elements
+ stop_glerror();
+}
+
+void render_ui_2d()
+{
+ LLGLSUIDefault gls_ui;
+
+ /////////////////////////////////////////////////////////////
+ //
+ // Render 2D UI elements that overlay the world (no z compare)
+
+ // Disable wireframe mode below here, as this is HUD/menus
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+
+ // Menu overlays, HUD, etc
+ gViewerWindow->setup2DRender();
+
+ F32 zoom_factor = LLViewerCamera::getInstance()->getZoomFactor();
+ S16 sub_region = LLViewerCamera::getInstance()->getZoomSubRegion();
+
+ if (zoom_factor > 1.f)
+ {
+ //decompose subregion number to x and y values
+ int pos_y = sub_region / llceil(zoom_factor);
+ int pos_x = sub_region - (pos_y*llceil(zoom_factor));
+ // offset for this tile
+ LLFontGL::sCurOrigin.mX -= llround((F32)gViewerWindow->getWindowWidthScaled() * (F32)pos_x / zoom_factor);
+ LLFontGL::sCurOrigin.mY -= llround((F32)gViewerWindow->getWindowHeightScaled() * (F32)pos_y / zoom_factor);
+ }
+
+ stop_glerror();
+ gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
+
+ // render outline for HUD
+ if (isAgentAvatarValid() && gAgentCamera.mHUDCurZoom < 0.98f)
+ {
+ gGL.pushMatrix();
+ S32 half_width = (gViewerWindow->getWorldViewWidthScaled() / 2);
+ S32 half_height = (gViewerWindow->getWorldViewHeightScaled() / 2);
+ glScalef(LLUI::sGLScaleFactor.mV[0], LLUI::sGLScaleFactor.mV[1], 1.f);
+ glTranslatef((F32)half_width, (F32)half_height, 0.f);
+ F32 zoom = gAgentCamera.mHUDCurZoom;
+ glScalef(zoom,zoom,1.f);
+ gGL.color4fv(LLColor4::white.mV);
+ gl_rect_2d(-half_width, half_height, half_width, -half_height, FALSE);
+ gGL.popMatrix();
+ stop_glerror();
+ }
+
+
+ if (gSavedSettings.getBOOL("RenderUIBuffer"))
+ {
+ if (LLUI::sDirty)
+ {
+ LLUI::sDirty = FALSE;
+ LLRect t_rect;
+
+ gPipeline.mUIScreen.bindTarget();
+ gGL.setColorMask(true, true);
+ {
+ static const S32 pad = 8;
+
+ LLUI::sDirtyRect.mLeft -= pad;
+ LLUI::sDirtyRect.mRight += pad;
+ LLUI::sDirtyRect.mBottom -= pad;
+ LLUI::sDirtyRect.mTop += pad;
+
+ LLGLEnable scissor(GL_SCISSOR_TEST);
+ static LLRect last_rect = LLUI::sDirtyRect;
+
+ //union with last rect to avoid mouse poop
+ last_rect.unionWith(LLUI::sDirtyRect);
+
+ t_rect = LLUI::sDirtyRect;
+ LLUI::sDirtyRect = last_rect;
+ last_rect = t_rect;
+
+ last_rect.mLeft = LLRect::tCoordType(last_rect.mLeft / LLUI::sGLScaleFactor.mV[0]);
+ last_rect.mRight = LLRect::tCoordType(last_rect.mRight / LLUI::sGLScaleFactor.mV[0]);
+ last_rect.mTop = LLRect::tCoordType(last_rect.mTop / LLUI::sGLScaleFactor.mV[1]);
+ last_rect.mBottom = LLRect::tCoordType(last_rect.mBottom / LLUI::sGLScaleFactor.mV[1]);
+
+ LLRect clip_rect(last_rect);
+
+ glClear(GL_COLOR_BUFFER_BIT);
+
+ gViewerWindow->draw();
+ }
+
+ gPipeline.mUIScreen.flush();
+ gGL.setColorMask(true, false);
+
+ LLUI::sDirtyRect = t_rect;
+ }
+
+ LLGLDisable cull(GL_CULL_FACE);
+ LLGLDisable blend(GL_BLEND);
+ S32 width = gViewerWindow->getWindowWidthScaled();
+ S32 height = gViewerWindow->getWindowHeightScaled();
+ gGL.getTexUnit(0)->bind(&gPipeline.mUIScreen);
+ gGL.begin(LLRender::TRIANGLE_STRIP);
+ gGL.color4f(1,1,1,1);
+ gGL.texCoord2f(0, 0); gGL.vertex2i(0, 0);
+ gGL.texCoord2f(width, 0); gGL.vertex2i(width, 0);
+ gGL.texCoord2f(0, height); gGL.vertex2i(0, height);
+ gGL.texCoord2f(width, height); gGL.vertex2i(width, height);
+ gGL.end();
+ }
+ else
+ {
+ gViewerWindow->draw();
+ }
+
+
+
+ // reset current origin for font rendering, in case of tiling render
+ LLFontGL::sCurOrigin.set(0, 0);
+}
+
+void render_disconnected_background()
+{
+ gGL.color4f(1,1,1,1);
+ if (!gDisconnectedImagep && gDisconnected)
+ {
+ llinfos << "Loading last bitmap..." << llendl;
+
+ std::string temp_str;
+ temp_str = gDirUtilp->getLindenUserDir() + gDirUtilp->getDirDelimiter() + SCREEN_LAST_FILENAME;
+
+ LLPointer<LLImageBMP> image_bmp = new LLImageBMP;
+ if( !image_bmp->load(temp_str) )
+ {
+ //llinfos << "Bitmap load failed" << llendl;
+ return;
+ }
+
+ LLPointer<LLImageRaw> raw = new LLImageRaw;
+ if (!image_bmp->decode(raw, 0.0f))
+ {
+ llinfos << "Bitmap decode failed" << llendl;
+ gDisconnectedImagep = NULL;
+ return;
+ }
+
+ U8 *rawp = raw->getData();
+ S32 npixels = (S32)image_bmp->getWidth()*(S32)image_bmp->getHeight();
+ for (S32 i = 0; i < npixels; i++)
+ {
+ S32 sum = 0;
+ sum = *rawp + *(rawp+1) + *(rawp+2);
+ sum /= 3;
+ *rawp = ((S32)sum*6 + *rawp)/7;
+ rawp++;
+ *rawp = ((S32)sum*6 + *rawp)/7;
+ rawp++;
+ *rawp = ((S32)sum*6 + *rawp)/7;
+ rawp++;
+ }
+
+
+ raw->expandToPowerOfTwo();
+ gDisconnectedImagep = LLViewerTextureManager::getLocalTexture(raw.get(), FALSE );
+ gStartTexture = gDisconnectedImagep;
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ }
+
+ // Make sure the progress view always fills the entire window.
+ S32 width = gViewerWindow->getWindowWidthScaled();
+ S32 height = gViewerWindow->getWindowHeightScaled();
+
+ if (gDisconnectedImagep)
+ {
+ LLGLSUIDefault gls_ui;
+ gViewerWindow->setup2DRender();
+ glPushMatrix();
+ {
+ // scale ui to reflect UIScaleFactor
+ // this can't be done in setup2DRender because it requires a
+ // pushMatrix/popMatrix pair
+ const LLVector2& display_scale = gViewerWindow->getDisplayScale();
+ glScalef(display_scale.mV[VX], display_scale.mV[VY], 1.f);
+
+ gGL.getTexUnit(0)->bind(gDisconnectedImagep);
+ gGL.color4f(1.f, 1.f, 1.f, 1.f);
+ gl_rect_2d_simple_tex(width, height);
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ }
+ glPopMatrix();
+ }
+ gGL.flush();
+}
+
+void display_cleanup()
+{
+ gDisconnectedImagep = NULL;
+}
diff --git a/indra/newview/llviewerfloaterreg.cpp b/indra/newview/llviewerfloaterreg.cpp
index dca1e33e60..11686740f7 100644
--- a/indra/newview/llviewerfloaterreg.cpp
+++ b/indra/newview/llviewerfloaterreg.cpp
@@ -73,6 +73,7 @@
#include "llfloaterlandholdings.h"
#include "llfloatermap.h"
#include "llfloatermemleak.h"
+#include "llfloatermodelwizard.h"
#include "llfloaternamedesc.h"
#include "llfloaternotificationsconsole.h"
#include "llfloateropenobject.h"
@@ -122,8 +123,34 @@
#include "llpreviewtexture.h"
#include "llsyswellwindow.h"
#include "llscriptfloater.h"
+#include "llfloatermodelpreview.h"
+#include "llcommandhandler.h"
+
// *NOTE: Please add files in alphabetical order to keep merges easy.
+// handle secondlife:///app/floater/{NAME} URLs
+class LLFloaterOpenHandler : public LLCommandHandler
+{
+public:
+ // requires trusted browser to trigger
+ LLFloaterOpenHandler() : LLCommandHandler("floater", UNTRUSTED_THROTTLE) { }
+
+ bool handle(const LLSD& params, const LLSD& query_map,
+ LLMediaCtrl* web)
+ {
+ if (params.size() != 1)
+ {
+ return false;
+ }
+
+ const std::string floater_name = LLURI::unescape(params[0].asString());
+ LLFloaterReg::showInstance(floater_name);
+
+ return true;
+ }
+};
+
+LLFloaterOpenHandler gFloaterOpenHandler;
void LLViewerFloaterReg::registerFloaters()
{
@@ -249,7 +276,9 @@ void LLViewerFloaterReg::registerFloaters()
LLFloaterReg::add("upload_anim", "floater_animation_preview.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterAnimPreview>, "upload");
LLFloaterReg::add("upload_image", "floater_image_preview.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterImagePreview>, "upload");
LLFloaterReg::add("upload_sound", "floater_sound_preview.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterSoundPreview>, "upload");
-
+ LLFloaterReg::add("upload_model", "floater_model_preview.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterModelPreview>, "upload");
+ LLFloaterReg::add("upload_model_wizard", "floater_model_wizard.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterModelWizard>);
+
LLFloaterReg::add("voice_controls", "floater_voice_controls.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLCallFloater>);
LLFloaterReg::add("voice_effect", "floater_voice_effect.xml", (LLFloaterBuildFunc)&LLFloaterReg::build<LLFloaterVoiceEffect>);
diff --git a/indra/newview/llviewerfoldertype.cpp b/indra/newview/llviewerfoldertype.cpp
index de1c8d14a8..42f780a8a3 100644
--- a/indra/newview/llviewerfoldertype.cpp
+++ b/indra/newview/llviewerfoldertype.cpp
@@ -126,6 +126,9 @@ LLViewerFolderDictionary::LLViewerFolderDictionary()
addEntry(LLFolderType::FT_CURRENT_OUTFIT, new ViewerFolderEntry("Current Outfit", "Inv_SysOpen", "Inv_SysClosed", TRUE));
addEntry(LLFolderType::FT_OUTFIT, new ViewerFolderEntry("New Outfit", "Inv_LookFolderOpen", "Inv_LookFolderClosed", TRUE));
addEntry(LLFolderType::FT_MY_OUTFITS, new ViewerFolderEntry("My Outfits", "Inv_SysOpen", "Inv_SysClosed", TRUE));
+ addEntry(LLFolderType::FT_MESH, new ViewerFolderEntry("Meshes", "Inv_SysOpen", "Inv_SysClosed", FALSE));
+
+
addEntry(LLFolderType::FT_INBOX, new ViewerFolderEntry("Inbox", "Inv_SysOpen", "Inv_SysClosed", FALSE));
addEntry(LLFolderType::FT_NONE, new ViewerFolderEntry("New Folder", "Inv_FolderOpen", "Inv_FolderClosed", FALSE, "default"));
diff --git a/indra/newview/llviewerjointmesh.cpp b/indra/newview/llviewerjointmesh.cpp
index e59e685f53..77c8bb0329 100644
--- a/indra/newview/llviewerjointmesh.cpp
+++ b/indra/newview/llviewerjointmesh.cpp
@@ -55,6 +55,7 @@
#include "v4math.h"
#include "m3math.h"
#include "m4math.h"
+#include "llmatrix4a.h"
#if !LL_DARWIN && !LL_LINUX && !LL_SOLARIS
extern PFNGLWEIGHTPOINTERARBPROC glWeightPointerARB;
@@ -375,6 +376,7 @@ const S32 NUM_AXES = 3;
// pivot parent 0-n -- child = n+1
static LLMatrix4 gJointMatUnaligned[32];
+static LLMatrix4a gJointMatAligned[32];
static LLMatrix3 gJointRotUnaligned[32];
static LLVector4 gJointPivot[32];
@@ -460,6 +462,14 @@ void LLViewerJointMesh::uploadJointMatrices()
glUniform4fvARB(gAvatarMatrixParam, 45, mat);
stop_glerror();
}
+ else
+ {
+ //load gJointMatUnaligned into gJointMatAligned
+ for (joint_num = 0; joint_num < reference_mesh->mJointRenderData.count(); ++joint_num)
+ {
+ gJointMatAligned[joint_num].loadu(gJointMatUnaligned[joint_num]);
+ }
+ }
}
//--------------------------------------------------------------------
@@ -501,7 +511,7 @@ int compare_int(const void *a, const void *b)
U32 LLViewerJointMesh::drawShape( F32 pixelArea, BOOL first_pass, BOOL is_dummy)
{
if (!mValid || !mMesh || !mFace || !mVisible ||
- mFace->mVertexBuffer.isNull() ||
+ !mFace->getVertexBuffer() ||
mMesh->getNumFaces() == 0)
{
return 0;
@@ -509,6 +519,8 @@ U32 LLViewerJointMesh::drawShape( F32 pixelArea, BOOL first_pass, BOOL is_dummy)
U32 triangle_count = 0;
+ S32 diffuse_channel = LLDrawPoolAvatar::sDiffuseChannel;
+
stop_glerror();
//----------------------------------------------------------------
@@ -521,7 +533,7 @@ U32 LLViewerJointMesh::drawShape( F32 pixelArea, BOOL first_pass, BOOL is_dummy)
stop_glerror();
- LLGLSSpecular specular(LLColor4(1.f,1.f,1.f,1.f), mShiny && !(mFace->getPool()->getVertexShaderLevel() > 0));
+ LLGLSSpecular specular(LLColor4(1.f,1.f,1.f,1.f), mFace->getPool()->getVertexShaderLevel() > 0 ? 0.f : mShiny);
//----------------------------------------------------------------
// setup current texture
@@ -531,7 +543,7 @@ U32 LLViewerJointMesh::drawShape( F32 pixelArea, BOOL first_pass, BOOL is_dummy)
LLTexUnit::eTextureAddressMode old_mode = LLTexUnit::TAM_WRAP;
if (mTestImageName)
{
- gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, mTestImageName);
+ gGL.getTexUnit(diffuse_channel)->bindManual(LLTexUnit::TT_TEXTURE, mTestImageName);
if (mIsTransparent)
{
@@ -540,24 +552,18 @@ U32 LLViewerJointMesh::drawShape( F32 pixelArea, BOOL first_pass, BOOL is_dummy)
else
{
glColor4f(0.7f, 0.6f, 0.3f, 1.f);
- gGL.getTexUnit(0)->setTextureColorBlend(LLTexUnit::TBO_LERP_TEX_ALPHA, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_PREV_COLOR);
+ gGL.getTexUnit(diffuse_channel)->setTextureColorBlend(LLTexUnit::TBO_LERP_TEX_ALPHA, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_PREV_COLOR);
}
}
else if( !is_dummy && mLayerSet )
{
if( mLayerSet->hasComposite() )
{
- gGL.getTexUnit(0)->bind(mLayerSet->getComposite());
+ gGL.getTexUnit(diffuse_channel)->bind(mLayerSet->getComposite());
}
else
{
- // This warning will always trigger if you've hacked the avatar to show as incomplete.
- // Ignore the warning if that's the case.
- if (!gSavedSettings.getBOOL("RenderUnloadedAvatar"))
- {
- //llwarns << "Layerset without composite" << llendl;
- }
- gGL.getTexUnit(0)->bind(LLViewerTextureManager::getFetchedTexture(IMG_DEFAULT));
+ gGL.getTexUnit(diffuse_channel)->bind(LLViewerTextureManager::getFetchedTexture(IMG_DEFAULT));
}
}
else
@@ -567,16 +573,16 @@ U32 LLViewerJointMesh::drawShape( F32 pixelArea, BOOL first_pass, BOOL is_dummy)
{
old_mode = mTexture->getAddressMode();
}
- gGL.getTexUnit(0)->bind(mTexture.get());
- gGL.getTexUnit(0)->bind(mTexture);
- gGL.getTexUnit(0)->setTextureAddressMode(LLTexUnit::TAM_CLAMP);
+ gGL.getTexUnit(diffuse_channel)->bind(mTexture.get());
+ gGL.getTexUnit(diffuse_channel)->bind(mTexture);
+ gGL.getTexUnit(diffuse_channel)->setTextureAddressMode(LLTexUnit::TAM_CLAMP);
}
else
{
- gGL.getTexUnit(0)->bind(LLViewerTextureManager::getFetchedTexture(IMG_DEFAULT));
+ gGL.getTexUnit(diffuse_channel)->bind(LLViewerTextureManager::getFetchedTexture(IMG_DEFAULT));
}
- mFace->mVertexBuffer->setBuffer(sRenderMask);
+ mFace->getVertexBuffer()->setBuffer(sRenderMask);
U32 start = mMesh->mFaceVertexOffset;
U32 end = start + mMesh->mFaceVertexCount - 1;
@@ -593,14 +599,14 @@ U32 LLViewerJointMesh::drawShape( F32 pixelArea, BOOL first_pass, BOOL is_dummy)
}
}
- mFace->mVertexBuffer->drawRange(LLRender::TRIANGLES, start, end, count, offset);
+ mFace->getVertexBuffer()->drawRange(LLRender::TRIANGLES, start, end, count, offset);
}
else
{
glPushMatrix();
LLMatrix4 jointToWorld = getWorldMatrix();
glMultMatrixf((GLfloat*)jointToWorld.mMatrix);
- mFace->mVertexBuffer->drawRange(LLRender::TRIANGLES, start, end, count, offset);
+ mFace->getVertexBuffer()->drawRange(LLRender::TRIANGLES, start, end, count, offset);
glPopMatrix();
}
gPipeline.addTrianglesDrawn(count);
@@ -609,13 +615,13 @@ U32 LLViewerJointMesh::drawShape( F32 pixelArea, BOOL first_pass, BOOL is_dummy)
if (mTestImageName)
{
- gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
+ gGL.getTexUnit(diffuse_channel)->setTextureBlendType(LLTexUnit::TB_MULT);
}
if (mTexture.notNull() && !is_dummy)
{
- gGL.getTexUnit(0)->bind(mTexture);
- gGL.getTexUnit(0)->setTextureAddressMode(old_mode);
+ gGL.getTexUnit(diffuse_channel)->bind(mTexture);
+ gGL.getTexUnit(diffuse_channel)->setTextureAddressMode(old_mode);
}
return triangle_count;
@@ -626,6 +632,9 @@ U32 LLViewerJointMesh::drawShape( F32 pixelArea, BOOL first_pass, BOOL is_dummy)
//-----------------------------------------------------------------------------
void LLViewerJointMesh::updateFaceSizes(U32 &num_vertices, U32& num_indices, F32 pixel_area)
{
+ //bump num_vertices to next multiple of 4
+ num_vertices = (num_vertices + 0x3) & ~0x3;
+
// Do a pre-alloc pass to determine sizes of data.
if (mMesh && mValid)
{
@@ -648,13 +657,25 @@ static LLFastTimer::DeclareTimer FTM_AVATAR_FACE("Avatar Face");
void LLViewerJointMesh::updateFaceData(LLFace *face, F32 pixel_area, BOOL damp_wind, bool terse_update)
{
+ //IF THIS FUNCTION BREAKS, SEE LLPOLYMESH CONSTRUCTOR AND CHECK ALIGNMENT OF INPUT ARRAYS
+
mFace = face;
- if (mFace->mVertexBuffer.isNull())
+ if (!mFace->getVertexBuffer())
{
return;
}
+ LLDrawPool *poolp = mFace->getPool();
+ BOOL hardware_skinning = (poolp && poolp->getVertexShaderLevel() > 0) ? TRUE : FALSE;
+
+ if (!hardware_skinning && terse_update)
+ { //no need to do terse updates if we're doing software vertex skinning
+ // since mMesh is being copied into mVertexBuffer every frame
+ return;
+ }
+
+
LLFastTimer t(FTM_AVATAR_FACE);
LLStrider<LLVector3> verticesp;
@@ -667,111 +688,59 @@ void LLViewerJointMesh::updateFaceData(LLFace *face, F32 pixel_area, BOOL damp_w
// Copy data into the faces from the polymesh data.
if (mMesh && mValid)
{
- if (mMesh->getNumVertices())
+ const U32 num_verts = mMesh->getNumVertices();
+
+ if (num_verts)
{
- stop_glerror();
face->getGeometryAvatar(verticesp, normalsp, tex_coordsp, vertex_weightsp, clothing_weightsp);
- stop_glerror();
- face->mVertexBuffer->getIndexStrider(indicesp);
- stop_glerror();
+ face->getVertexBuffer()->getIndexStrider(indicesp);
verticesp += mMesh->mFaceVertexOffset;
- tex_coordsp += mMesh->mFaceVertexOffset;
normalsp += mMesh->mFaceVertexOffset;
- vertex_weightsp += mMesh->mFaceVertexOffset;
- clothing_weightsp += mMesh->mFaceVertexOffset;
-
- const U32* __restrict coords = (U32*) mMesh->getCoords();
- const U32* __restrict tex_coords = (U32*) mMesh->getTexCoords();
- const U32* __restrict normals = (U32*) mMesh->getNormals();
- const U32* __restrict weights = (U32*) mMesh->getWeights();
- const U32* __restrict cloth_weights = (U32*) mMesh->getClothingWeights();
-
- const U32 num_verts = mMesh->getNumVertices();
-
- U32 i = 0;
-
- const U32 skip = verticesp.getSkip()/sizeof(U32);
+
+ F32* v = (F32*) verticesp.get();
+ F32* n = (F32*) normalsp.get();
+
+ U32 words = num_verts*4;
- U32* __restrict v = (U32*) verticesp.get();
- U32* __restrict n = (U32*) normalsp.get();
+ LLVector4a::memcpyNonAliased16(v, (F32*) mMesh->getCoords(), words*sizeof(F32));
+ LLVector4a::memcpyNonAliased16(n, (F32*) mMesh->getNormals(), words*sizeof(F32));
+
- if (terse_update)
+ if (!terse_update)
{
- for (S32 i = num_verts; i > 0; --i)
- {
- //morph target application only, only update positions and normals
- v[0] = coords[0];
- v[1] = coords[1];
- v[2] = coords[2];
- coords += 3;
- v += skip;
- }
+ vertex_weightsp += mMesh->mFaceVertexOffset;
+ clothing_weightsp += mMesh->mFaceVertexOffset;
+ tex_coordsp += mMesh->mFaceVertexOffset;
+
+ F32* tc = (F32*) tex_coordsp.get();
+ F32* vw = (F32*) vertex_weightsp.get();
+ F32* cw = (F32*) clothing_weightsp.get();
- for (S32 i = num_verts; i > 0; --i)
- {
- n[0] = normals[0];
- n[1] = normals[1];
- n[2] = normals[2];
- normals += 3;
- n += skip;
- }
+ LLVector4a::memcpyNonAliased16(tc, (F32*) mMesh->getTexCoords(), num_verts*2*sizeof(F32));
+ LLVector4a::memcpyNonAliased16(vw, (F32*) mMesh->getWeights(), num_verts*sizeof(F32));
+ LLVector4a::memcpyNonAliased16(cw, (F32*) mMesh->getClothingWeights(), num_verts*4*sizeof(F32));
}
- else
- {
- U32* __restrict tc = (U32*) tex_coordsp.get();
- U32* __restrict vw = (U32*) vertex_weightsp.get();
- U32* __restrict cw = (U32*) clothing_weightsp.get();
-
- do
- {
- v[0] = *(coords++);
- v[1] = *(coords++);
- v[2] = *(coords++);
- v += skip;
-
- tc[0] = *(tex_coords++);
- tc[1] = *(tex_coords++);
- tc += skip;
-
- n[0] = *(normals++);
- n[1] = *(normals++);
- n[2] = *(normals++);
- n += skip;
-
- vw[0] = *(weights++);
- vw += skip;
-
- cw[0] = *(cloth_weights++);
- cw[1] = *(cloth_weights++);
- cw[2] = *(cloth_weights++);
- cw[3] = *(cloth_weights++);
- cw += skip;
- }
- while (++i < num_verts);
+ const U32 idx_count = mMesh->getNumFaces()*3;
- const U32 idx_count = mMesh->getNumFaces()*3;
+ indicesp += mMesh->mFaceIndexOffset;
- indicesp += mMesh->mFaceIndexOffset;
+ U16* __restrict idx = indicesp.get();
+ S32* __restrict src_idx = (S32*) mMesh->getFaces();
- U16* __restrict idx = indicesp.get();
- S32* __restrict src_idx = (S32*) mMesh->getFaces();
+ const S32 offset = (S32) mMesh->mFaceVertexOffset;
- i = 0;
-
- const S32 offset = (S32) mMesh->mFaceVertexOffset;
-
- do
- {
- *(idx++) = *(src_idx++)+offset;
- }
- while (++i < idx_count);
+ for (S32 i = 0; i < idx_count; ++i)
+ {
+ *(idx++) = *(src_idx++)+offset;
}
}
}
}
+
+
//-----------------------------------------------------------------------------
// updateLOD()
//-----------------------------------------------------------------------------
@@ -789,89 +758,49 @@ void LLViewerJointMesh::updateGeometryOriginal(LLFace *mFace, LLPolyMesh *mMesh)
LLStrider<LLVector3> o_normals;
//get vertex and normal striders
- LLVertexBuffer *buffer = mFace->mVertexBuffer;
+ LLVertexBuffer* buffer = mFace->getVertexBuffer();
buffer->getVertexStrider(o_vertices, 0);
buffer->getNormalStrider(o_normals, 0);
- F32 last_weight = F32_MAX;
- LLMatrix4 gBlendMat;
- LLMatrix3 gBlendRotMat;
+ F32* __restrict vert = o_vertices[0].mV;
+ F32* __restrict norm = o_normals[0].mV;
+
+ const F32* __restrict weights = mMesh->getWeights();
+ const LLVector4a* __restrict coords = (LLVector4a*) mMesh->getCoords();
+ const LLVector4a* __restrict normals = (LLVector4a*) mMesh->getNormals();
+
+ U32 offset = mMesh->mFaceVertexOffset*4;
+ vert += offset;
+ norm += offset;
- const F32* weights = mMesh->getWeights();
- const LLVector3* coords = mMesh->getCoords();
- const LLVector3* normals = mMesh->getNormals();
for (U32 index = 0; index < mMesh->getNumVertices(); index++)
{
- U32 bidx = index + mMesh->mFaceVertexOffset;
-
- // blend by first matrix
- F32 w = weights[index];
-
- // Maybe we don't have to change gBlendMat.
- // Profiles of a single-avatar scene on a Mac show this to be a very
- // common case. JC
- if (w == last_weight)
- {
- o_vertices[bidx] = coords[index] * gBlendMat;
- o_normals[bidx] = normals[index] * gBlendRotMat;
- continue;
- }
-
- last_weight = w;
+ // equivalent to joint = floorf(weights[index]);
+ S32 joint = _mm_cvtt_ss2si(_mm_load_ss(weights+index));
+ F32 w = weights[index] - joint;
- S32 joint = llfloor(w);
- w -= joint;
-
- // No lerp required in this case.
- if (w == 1.0f)
+ LLMatrix4a gBlendMat;
+
+ if (w != 0.f)
{
- gBlendMat = gJointMatUnaligned[joint+1];
- o_vertices[bidx] = coords[index] * gBlendMat;
- gBlendRotMat = gJointRotUnaligned[joint+1];
- o_normals[bidx] = normals[index] * gBlendRotMat;
- continue;
+ // blend between matrices and apply
+ gBlendMat.setLerp(gJointMatAligned[joint+0],
+ gJointMatAligned[joint+1], w);
+
+ LLVector4a res;
+ gBlendMat.affineTransform(coords[index], res);
+ res.store4a(vert+index*4);
+ gBlendMat.rotate(normals[index], res);
+ res.store4a(norm+index*4);
+ }
+ else
+ { // No lerp required in this case.
+ LLVector4a res;
+ gJointMatAligned[joint].affineTransform(coords[index], res);
+ res.store4a(vert+index*4);
+ gJointMatAligned[joint].rotate(normals[index], res);
+ res.store4a(norm+index*4);
}
-
- // Try to keep all the accesses to the matrix data as close
- // together as possible. This function is a hot spot on the
- // Mac. JC
- LLMatrix4 &m0 = gJointMatUnaligned[joint+1];
- LLMatrix4 &m1 = gJointMatUnaligned[joint+0];
-
- gBlendMat.mMatrix[VX][VX] = lerp(m1.mMatrix[VX][VX], m0.mMatrix[VX][VX], w);
- gBlendMat.mMatrix[VX][VY] = lerp(m1.mMatrix[VX][VY], m0.mMatrix[VX][VY], w);
- gBlendMat.mMatrix[VX][VZ] = lerp(m1.mMatrix[VX][VZ], m0.mMatrix[VX][VZ], w);
-
- gBlendMat.mMatrix[VY][VX] = lerp(m1.mMatrix[VY][VX], m0.mMatrix[VY][VX], w);
- gBlendMat.mMatrix[VY][VY] = lerp(m1.mMatrix[VY][VY], m0.mMatrix[VY][VY], w);
- gBlendMat.mMatrix[VY][VZ] = lerp(m1.mMatrix[VY][VZ], m0.mMatrix[VY][VZ], w);
-
- gBlendMat.mMatrix[VZ][VX] = lerp(m1.mMatrix[VZ][VX], m0.mMatrix[VZ][VX], w);
- gBlendMat.mMatrix[VZ][VY] = lerp(m1.mMatrix[VZ][VY], m0.mMatrix[VZ][VY], w);
- gBlendMat.mMatrix[VZ][VZ] = lerp(m1.mMatrix[VZ][VZ], m0.mMatrix[VZ][VZ], w);
-
- gBlendMat.mMatrix[VW][VX] = lerp(m1.mMatrix[VW][VX], m0.mMatrix[VW][VX], w);
- gBlendMat.mMatrix[VW][VY] = lerp(m1.mMatrix[VW][VY], m0.mMatrix[VW][VY], w);
- gBlendMat.mMatrix[VW][VZ] = lerp(m1.mMatrix[VW][VZ], m0.mMatrix[VW][VZ], w);
-
- o_vertices[bidx] = coords[index] * gBlendMat;
-
- LLMatrix3 &n0 = gJointRotUnaligned[joint+1];
- LLMatrix3 &n1 = gJointRotUnaligned[joint+0];
-
- gBlendRotMat.mMatrix[VX][VX] = lerp(n1.mMatrix[VX][VX], n0.mMatrix[VX][VX], w);
- gBlendRotMat.mMatrix[VX][VY] = lerp(n1.mMatrix[VX][VY], n0.mMatrix[VX][VY], w);
- gBlendRotMat.mMatrix[VX][VZ] = lerp(n1.mMatrix[VX][VZ], n0.mMatrix[VX][VZ], w);
-
- gBlendRotMat.mMatrix[VY][VX] = lerp(n1.mMatrix[VY][VX], n0.mMatrix[VY][VX], w);
- gBlendRotMat.mMatrix[VY][VY] = lerp(n1.mMatrix[VY][VY], n0.mMatrix[VY][VY], w);
- gBlendRotMat.mMatrix[VY][VZ] = lerp(n1.mMatrix[VY][VZ], n0.mMatrix[VY][VZ], w);
-
- gBlendRotMat.mMatrix[VZ][VX] = lerp(n1.mMatrix[VZ][VX], n0.mMatrix[VZ][VX], w);
- gBlendRotMat.mMatrix[VZ][VY] = lerp(n1.mMatrix[VZ][VY], n0.mMatrix[VZ][VY], w);
- gBlendRotMat.mMatrix[VZ][VZ] = lerp(n1.mMatrix[VZ][VZ], n0.mMatrix[VZ][VZ], w);
-
- o_normals[bidx] = normals[index] * gBlendRotMat;
}
buffer->setBuffer(0);
@@ -940,7 +869,7 @@ void LLViewerJointMesh::updateJointGeometry()
&& mMesh
&& mFace
&& mMesh->hasWeights()
- && mFace->mVertexBuffer.notNull()
+ && mFace->getVertexBuffer()
&& LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_AVATAR) == 0))
{
return;
diff --git a/indra/newview/llviewerjointmesh_sse.cpp b/indra/newview/llviewerjointmesh_sse.cpp
index 174b6eae29..400b49d046 100644
--- a/indra/newview/llviewerjointmesh_sse.cpp
+++ b/indra/newview/llviewerjointmesh_sse.cpp
@@ -83,13 +83,13 @@ void LLViewerJointMesh::updateGeometrySSE(LLFace *face, LLPolyMesh *mesh)
LLStrider<LLVector3> o_vertices;
LLStrider<LLVector3> o_normals;
- LLVertexBuffer *buffer = face->mVertexBuffer;
+ LLVertexBuffer *buffer = face->getVertexBuffer();
buffer->getVertexStrider(o_vertices, mesh->mFaceVertexOffset);
buffer->getNormalStrider(o_normals, mesh->mFaceVertexOffset);
const F32* weights = mesh->getWeights();
- const LLVector3* coords = mesh->getCoords();
- const LLVector3* normals = mesh->getNormals();
+ const LLVector3* coords = (const LLVector3*)mesh->getCoords();
+ const LLVector3* normals = (const LLVector3*)mesh->getNormals();
for (U32 index = 0, index_end = mesh->getNumVertices(); index < index_end; ++index)
{
if( weight != weights[index])
diff --git a/indra/newview/llviewerjointmesh_sse2.cpp b/indra/newview/llviewerjointmesh_sse2.cpp
index a374ba2471..c2296dd569 100644
--- a/indra/newview/llviewerjointmesh_sse2.cpp
+++ b/indra/newview/llviewerjointmesh_sse2.cpp
@@ -90,13 +90,13 @@ void LLViewerJointMesh::updateGeometrySSE2(LLFace *face, LLPolyMesh *mesh)
LLStrider<LLVector3> o_vertices;
LLStrider<LLVector3> o_normals;
- LLVertexBuffer *buffer = face->mVertexBuffer;
+ LLVertexBuffer *buffer = face->getVertexBuffer();
buffer->getVertexStrider(o_vertices, mesh->mFaceVertexOffset);
buffer->getNormalStrider(o_normals, mesh->mFaceVertexOffset);
const F32* weights = mesh->getWeights();
- const LLVector3* coords = mesh->getCoords();
- const LLVector3* normals = mesh->getNormals();
+ const LLVector3* coords = (const LLVector3*)mesh->getCoords();
+ const LLVector3* normals = (const LLVector3*)mesh->getNormals();
for (U32 index = 0, index_end = mesh->getNumVertices(); index < index_end; ++index)
{
if( weight != weights[index])
diff --git a/indra/newview/llviewerjointmesh_vec.cpp b/indra/newview/llviewerjointmesh_vec.cpp
index c9371030ad..6600d01d17 100644
--- a/indra/newview/llviewerjointmesh_vec.cpp
+++ b/indra/newview/llviewerjointmesh_vec.cpp
@@ -46,6 +46,7 @@
// static
void LLViewerJointMesh::updateGeometryVectorized(LLFace *face, LLPolyMesh *mesh)
{
+#if 0
static LLV4Matrix4 sJointMat[32];
LLDynamicArray<LLJointRenderData*>& joint_data = mesh->getReferenceMesh()->mJointRenderData;
S32 j, joint_num, joint_end = joint_data.count();
@@ -92,4 +93,5 @@ void LLViewerJointMesh::updateGeometryVectorized(LLFace *face, LLPolyMesh *mesh)
}
buffer->setBuffer(0);
+#endif
}
diff --git a/indra/newview/llviewerjoystick.cpp b/indra/newview/llviewerjoystick.cpp
index e1dd72dddc..fbf11f20db 100644
--- a/indra/newview/llviewerjoystick.cpp
+++ b/indra/newview/llviewerjoystick.cpp
@@ -758,7 +758,7 @@ void LLViewerJoystick::moveAvatar(bool reset)
sDelta[RX_I] += (cur_delta[RX_I] - sDelta[RX_I]) * time * feather;
sDelta[RY_I] += (cur_delta[RY_I] - sDelta[RY_I]) * time * feather;
- handleRun(fsqrtf(sDelta[Z_I]*sDelta[Z_I] + sDelta[X_I]*sDelta[X_I]));
+ handleRun((F32) sqrt(sDelta[Z_I]*sDelta[Z_I] + sDelta[X_I]*sDelta[X_I]));
// Allow forward/backward movement some priority
if (dom_axis == Z_I)
diff --git a/indra/newview/llviewermedia.cpp b/indra/newview/llviewermedia.cpp
index 499165135a..6d3316cf6a 100644
--- a/indra/newview/llviewermedia.cpp
+++ b/indra/newview/llviewermedia.cpp
@@ -913,7 +913,7 @@ void LLViewerMedia::updateMedia(void *dummy_arg)
// Set the low priority size for downsampling to approximately the size the texture is displayed at.
{
- F32 approximate_interest_dimension = fsqrtf(pimpl->getInterest());
+ F32 approximate_interest_dimension = (F32) sqrt(pimpl->getInterest());
pimpl->setLowPrioritySizeLimit(llround(approximate_interest_dimension));
}
diff --git a/indra/newview/llviewermenu.cpp b/indra/newview/llviewermenu.cpp
index add24e5216..26b6ffa19e 100644..100755
--- a/indra/newview/llviewermenu.cpp
+++ b/indra/newview/llviewermenu.cpp
@@ -1,8174 +1,8191 @@
-/**
- * @file llviewermenu.cpp
- * @brief Builds menus out of items.
- *
- * $LicenseInfo:firstyear=2002&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-#include "llviewerprecompiledheaders.h"
-#include "llviewermenu.h"
-
-// linden library includes
-#include "llavatarnamecache.h" // IDEVO
-#include "llfloaterreg.h"
-#include "llcombobox.h"
-#include "llinventorypanel.h"
-#include "llnotifications.h"
-#include "llnotificationsutil.h"
-
-// newview includes
-#include "llagent.h"
-#include "llagentcamera.h"
-#include "llagentwearables.h"
-#include "llagentpilot.h"
-#include "llbottomtray.h"
-#include "llcompilequeue.h"
-#include "llconsole.h"
-#include "lldebugview.h"
-#include "llfilepicker.h"
-#include "llfirstuse.h"
-#include "llfloaterbuy.h"
-#include "llfloaterbuycontents.h"
-#include "llbuycurrencyhtml.h"
-#include "llfloatergodtools.h"
-#include "llfloaterinventory.h"
-#include "llfloaterland.h"
-#include "llfloaterpay.h"
-#include "llfloaterreporter.h"
-#include "llfloatersearch.h"
-#include "llfloaterscriptdebug.h"
-#include "llfloatersnapshot.h"
-#include "llfloatertools.h"
-#include "llfloaterworldmap.h"
-#include "llavataractions.h"
-#include "lllandmarkactions.h"
-#include "llgroupmgr.h"
-#include "lltooltip.h"
-#include "llhints.h"
-#include "llhudeffecttrail.h"
-#include "llhudmanager.h"
-#include "llimview.h"
-#include "llinventorybridge.h"
-#include "llinventorydefines.h"
-#include "llinventoryfunctions.h"
-#include "llpanellogin.h"
-#include "llpanelblockedlist.h"
-#include "llmenucommands.h"
-#include "llmoveview.h"
-#include "llparcel.h"
-#include "llrootview.h"
-#include "llselectmgr.h"
-#include "llsidetray.h"
-#include "llstatusbar.h"
-#include "lltextureview.h"
-#include "lltoolcomp.h"
-#include "lltoolmgr.h"
-#include "lltoolpie.h"
-#include "lltoolselectland.h"
-#include "lltrans.h"
-#include "llviewergenericmessage.h"
-#include "llviewerhelp.h"
-#include "llviewermenufile.h" // init_menu_file()
-#include "llviewermessage.h"
-#include "llviewernetwork.h"
-#include "llviewerobjectlist.h"
-#include "llviewerparcelmgr.h"
-#include "llviewerstats.h"
-#include "llvoavatarself.h"
-#include "llworldmap.h"
-#include "pipeline.h"
-#include "llviewerjoystick.h"
-#include "llwlanimator.h"
-#include "llwlparammanager.h"
-#include "llfloatercamera.h"
-#include "lluilistener.h"
-#include "llappearancemgr.h"
-#include "lltrans.h"
-#include "lleconomy.h"
-#include "boost/unordered_map.hpp"
-
-using namespace LLVOAvatarDefines;
-
-static boost::unordered_map<std::string, LLStringExplicit> sDefaultItemLabels;
-
-BOOL enable_land_build(void*);
-BOOL enable_object_build(void*);
-
-LLVOAvatar* find_avatar_from_object( LLViewerObject* object );
-LLVOAvatar* find_avatar_from_object( const LLUUID& object_id );
-
-void handle_test_load_url(void*);
-
-//
-// Evil hackish imported globals
-
-//extern BOOL gHideSelectedObjects;
-//extern BOOL gAllowSelectAvatar;
-//extern BOOL gDebugAvatarRotation;
-extern BOOL gDebugClicks;
-extern BOOL gDebugWindowProc;
-//extern BOOL gDebugTextEditorTips;
-//extern BOOL gDebugSelectMgr;
-
-//
-// Globals
-//
-
-LLMenuBarGL *gMenuBarView = NULL;
-LLViewerMenuHolderGL *gMenuHolder = NULL;
-LLMenuGL *gPopupMenuView = NULL;
-LLMenuGL *gEditMenu = NULL;
-LLMenuBarGL *gLoginMenuBarView = NULL;
-
-// Pie menus
-LLContextMenu *gMenuAvatarSelf = NULL;
-LLContextMenu *gMenuAvatarOther = NULL;
-LLContextMenu *gMenuObject = NULL;
-LLContextMenu *gMenuAttachmentSelf = NULL;
-LLContextMenu *gMenuAttachmentOther = NULL;
-LLContextMenu *gMenuLand = NULL;
-
-const std::string SAVE_INTO_INVENTORY("Save Object Back to My Inventory");
-const std::string SAVE_INTO_TASK_INVENTORY("Save Object Back to Object Contents");
-
-LLMenuGL* gAttachSubMenu = NULL;
-LLMenuGL* gDetachSubMenu = NULL;
-LLMenuGL* gTakeOffClothes = NULL;
-LLContextMenu* gAttachScreenPieMenu = NULL;
-LLContextMenu* gAttachPieMenu = NULL;
-LLContextMenu* gAttachBodyPartPieMenus[8];
-LLContextMenu* gDetachPieMenu = NULL;
-LLContextMenu* gDetachScreenPieMenu = NULL;
-LLContextMenu* gDetachBodyPartPieMenus[8];
-
-LLMenuItemCallGL* gAFKMenu = NULL;
-LLMenuItemCallGL* gBusyMenu = NULL;
-
-//
-// Local prototypes
-
-// File Menu
-const char* upload_pick(void* data);
-void handle_compress_image(void*);
-
-
-// Edit menu
-void handle_dump_group_info(void *);
-void handle_dump_capabilities_info(void *);
-
-// Advanced->Consoles menu
-void handle_region_dump_settings(void*);
-void handle_region_dump_temp_asset_data(void*);
-void handle_region_clear_temp_asset_data(void*);
-
-// Object pie menu
-BOOL sitting_on_selection();
-
-void near_sit_object();
-//void label_sit_or_stand(std::string& label, void*);
-// buy and take alias into the same UI positions, so these
-// declarations handle this mess.
-BOOL is_selection_buy_not_take();
-S32 selection_price();
-BOOL enable_take();
-void handle_take();
-void handle_object_show_inspector();
-void handle_avatar_show_inspector();
-bool confirm_take(const LLSD& notification, const LLSD& response);
-
-void handle_buy_object(LLSaleInfo sale_info);
-void handle_buy_contents(LLSaleInfo sale_info);
-
-// Land pie menu
-void near_sit_down_point(BOOL success, void *);
-
-// Avatar pie menu
-
-// Debug menu
-
-
-void velocity_interpolate( void* );
-
-void handle_rebake_textures(void*);
-BOOL check_admin_override(void*);
-void handle_admin_override_toggle(void*);
-#ifdef TOGGLE_HACKED_GODLIKE_VIEWER
-void handle_toggle_hacked_godmode(void*);
-BOOL check_toggle_hacked_godmode(void*);
-bool enable_toggle_hacked_godmode(void*);
-#endif
-
-void toggle_show_xui_names(void *);
-BOOL check_show_xui_names(void *);
-
-// Debug UI
-
-void handle_buy_currency_test(void*);
-
-void handle_god_mode(void*);
-
-// God menu
-void handle_leave_god_mode(void*);
-
-
-void handle_reset_view();
-
-void handle_duplicate_in_place(void*);
-
-
-void handle_object_owner_self(void*);
-void handle_object_owner_permissive(void*);
-void handle_object_lock(void*);
-void handle_object_asset_ids(void*);
-void force_take_copy(void*);
-#ifdef _CORY_TESTING
-void force_export_copy(void*);
-void force_import_geometry(void*);
-#endif
-
-void handle_force_parcel_owner_to_me(void*);
-void handle_force_parcel_to_content(void*);
-void handle_claim_public_land(void*);
-
-void handle_god_request_avatar_geometry(void *); // Hack for easy testing of new avatar geometry
-void reload_vertex_shader(void *);
-void handle_disconnect_viewer(void *);
-
-void force_error_breakpoint(void *);
-void force_error_llerror(void *);
-void force_error_bad_memory_access(void *);
-void force_error_infinite_loop(void *);
-void force_error_software_exception(void *);
-void force_error_driver_crash(void *);
-
-void handle_force_delete(void*);
-void print_object_info(void*);
-void print_agent_nvpairs(void*);
-void toggle_debug_menus(void*);
-void upload_done_callback(const LLUUID& uuid, void* user_data, S32 result, LLExtStat ext_status);
-void dump_select_mgr(void*);
-
-void dump_inventory(void*);
-void toggle_visibility(void*);
-BOOL get_visibility(void*);
-
-// Avatar Pie menu
-void request_friendship(const LLUUID& agent_id);
-
-// Tools menu
-void handle_selected_texture_info(void*);
-
-void handle_dump_followcam(void*);
-void handle_viewer_enable_message_log(void*);
-void handle_viewer_disable_message_log(void*);
-
-BOOL enable_buy_land(void*);
-
-// Help menu
-
-void handle_test_male(void *);
-void handle_test_female(void *);
-void handle_toggle_pg(void*);
-void handle_dump_attachments(void *);
-void handle_dump_avatar_local_textures(void*);
-void handle_debug_avatar_textures(void*);
-void handle_grab_baked_texture(void*);
-BOOL enable_grab_baked_texture(void*);
-void handle_dump_region_object_cache(void*);
-
-BOOL enable_save_into_inventory(void*);
-BOOL enable_save_into_task_inventory(void*);
-
-BOOL enable_detach(const LLSD& = LLSD());
-void menu_toggle_attached_lights(void* user_data);
-void menu_toggle_attached_particles(void* user_data);
-
-class LLMenuParcelObserver : public LLParcelObserver
-{
-public:
- LLMenuParcelObserver();
- ~LLMenuParcelObserver();
- virtual void changed();
-};
-
-static LLMenuParcelObserver* gMenuParcelObserver = NULL;
-
-static LLUIListener sUIListener;
-
-LLMenuParcelObserver::LLMenuParcelObserver()
-{
- LLViewerParcelMgr::getInstance()->addObserver(this);
-}
-
-LLMenuParcelObserver::~LLMenuParcelObserver()
-{
- LLViewerParcelMgr::getInstance()->removeObserver(this);
-}
-
-void LLMenuParcelObserver::changed()
-{
- gMenuHolder->childSetEnabled("Land Buy Pass", LLPanelLandGeneral::enableBuyPass(NULL));
-
- BOOL buyable = enable_buy_land(NULL);
- gMenuHolder->childSetEnabled("Land Buy", buyable);
- gMenuHolder->childSetEnabled("Buy Land...", buyable);
-}
-
-
-void initialize_menus();
-
-//-----------------------------------------------------------------------------
-// Initialize main menus
-//
-// HOW TO NAME MENUS:
-//
-// First Letter Of Each Word Is Capitalized, Even At Or And
-//
-// Items that lead to dialog boxes end in "..."
-//
-// Break up groups of more than 6 items with separators
-//-----------------------------------------------------------------------------
-
-void set_underclothes_menu_options()
-{
- if (gMenuHolder && gAgent.isTeen())
- {
- gMenuHolder->getChild<LLView>("Self Underpants")->setVisible(FALSE);
- gMenuHolder->getChild<LLView>("Self Undershirt")->setVisible(FALSE);
- }
- if (gMenuBarView && gAgent.isTeen())
- {
- gMenuBarView->getChild<LLView>("Menu Underpants")->setVisible(FALSE);
- gMenuBarView->getChild<LLView>("Menu Undershirt")->setVisible(FALSE);
- }
-}
-
-void init_menus()
-{
- S32 top = gViewerWindow->getRootView()->getRect().getHeight();
-
- // Initialize actions
- initialize_menus();
-
- ///
- /// Popup menu
- ///
- /// The popup menu is now populated by the show_context_menu()
- /// method.
-
- LLMenuGL::Params menu_params;
- menu_params.name = "Popup";
- menu_params.visible = false;
- gPopupMenuView = LLUICtrlFactory::create<LLMenuGL>(menu_params);
- gMenuHolder->addChild( gPopupMenuView );
-
- ///
- /// Context menus
- ///
-
- const widget_registry_t& registry =
- LLViewerMenuHolderGL::child_registry_t::instance();
- gEditMenu = LLUICtrlFactory::createFromFile<LLMenuGL>("menu_edit.xml", gMenuHolder, registry);
- gMenuAvatarSelf = LLUICtrlFactory::createFromFile<LLContextMenu>(
- "menu_avatar_self.xml", gMenuHolder, registry);
- gMenuAvatarOther = LLUICtrlFactory::createFromFile<LLContextMenu>(
- "menu_avatar_other.xml", gMenuHolder, registry);
-
- gDetachScreenPieMenu = gMenuHolder->getChild<LLContextMenu>("Object Detach HUD", true);
- gDetachPieMenu = gMenuHolder->getChild<LLContextMenu>("Object Detach", true);
-
- gMenuObject = LLUICtrlFactory::createFromFile<LLContextMenu>(
- "menu_object.xml", gMenuHolder, registry);
-
- gAttachScreenPieMenu = gMenuHolder->getChild<LLContextMenu>("Object Attach HUD");
- gAttachPieMenu = gMenuHolder->getChild<LLContextMenu>("Object Attach");
-
- gMenuAttachmentSelf = LLUICtrlFactory::createFromFile<LLContextMenu>(
- "menu_attachment_self.xml", gMenuHolder, registry);
- gMenuAttachmentOther = LLUICtrlFactory::createFromFile<LLContextMenu>(
- "menu_attachment_other.xml", gMenuHolder, registry);
-
- gMenuLand = LLUICtrlFactory::createFromFile<LLContextMenu>(
- "menu_land.xml", gMenuHolder, registry);
-
- ///
- /// set up the colors
- ///
- LLColor4 color;
-
- LLColor4 context_menu_color = LLUIColorTable::instance().getColor("MenuPopupBgColor");
-
- gMenuAvatarSelf->setBackgroundColor( context_menu_color );
- gMenuAvatarOther->setBackgroundColor( context_menu_color );
- gMenuObject->setBackgroundColor( context_menu_color );
- gMenuAttachmentSelf->setBackgroundColor( context_menu_color );
- gMenuAttachmentOther->setBackgroundColor( context_menu_color );
-
- gMenuLand->setBackgroundColor( context_menu_color );
-
- color = LLUIColorTable::instance().getColor( "MenuPopupBgColor" );
- gPopupMenuView->setBackgroundColor( color );
-
- // If we are not in production, use a different color to make it apparent.
- if (LLGridManager::getInstance()->isInProductionGrid())
- {
- color = LLUIColorTable::instance().getColor( "MenuBarBgColor" );
- }
- else
- {
- color = LLUIColorTable::instance().getColor( "MenuNonProductionBgColor" );
- }
- gMenuBarView = LLUICtrlFactory::getInstance()->createFromFile<LLMenuBarGL>("menu_viewer.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
- gMenuBarView->setRect(LLRect(0, top, 0, top - MENU_BAR_HEIGHT));
- gMenuBarView->setBackgroundColor( color );
-
- LLView* menu_bar_holder = gViewerWindow->getRootView()->getChildView("menu_bar_holder");
- menu_bar_holder->addChild(gMenuBarView);
-
- gViewerWindow->setMenuBackgroundColor(false,
- LLGridManager::getInstance()->isInProductionGrid());
-
- // Assume L$10 for now, the server will tell us the real cost at login
- // *TODO:Also fix cost in llfolderview.cpp for Inventory menus
- const std::string upload_cost("10");
- gMenuHolder->childSetLabelArg("Upload Image", "[COST]", upload_cost);
- gMenuHolder->childSetLabelArg("Upload Sound", "[COST]", upload_cost);
- gMenuHolder->childSetLabelArg("Upload Animation", "[COST]", upload_cost);
- gMenuHolder->childSetLabelArg("Bulk Upload", "[COST]", upload_cost);
-
- gAFKMenu = gMenuBarView->getChild<LLMenuItemCallGL>("Set Away", TRUE);
- gBusyMenu = gMenuBarView->getChild<LLMenuItemCallGL>("Set Busy", TRUE);
- gAttachSubMenu = gMenuBarView->findChildMenuByName("Attach Object", TRUE);
- gDetachSubMenu = gMenuBarView->findChildMenuByName("Detach Object", TRUE);
-
-#if !MEM_TRACK_MEM
- // Don't display the Memory console menu if the feature is turned off
- LLMenuItemCheckGL *memoryMenu = gMenuBarView->getChild<LLMenuItemCheckGL>("Memory", TRUE);
- if (memoryMenu)
- {
- memoryMenu->setVisible(FALSE);
- }
-#endif
-
- gMenuBarView->createJumpKeys();
-
- // Let land based option enable when parcel changes
- gMenuParcelObserver = new LLMenuParcelObserver();
-
- gLoginMenuBarView = LLUICtrlFactory::getInstance()->createFromFile<LLMenuBarGL>("menu_login.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
- gLoginMenuBarView->arrangeAndClear();
- LLRect menuBarRect = gLoginMenuBarView->getRect();
- menuBarRect.setLeftTopAndSize(0, menu_bar_holder->getRect().getHeight(), menuBarRect.getWidth(), menuBarRect.getHeight());
- gLoginMenuBarView->setRect(menuBarRect);
- gLoginMenuBarView->setBackgroundColor( color );
- menu_bar_holder->addChild(gLoginMenuBarView);
-
- // tooltips are on top of EVERYTHING, including menus
- gViewerWindow->getRootView()->sendChildToFront(gToolTipView);
-}
-
-///////////////////
-// SHOW CONSOLES //
-///////////////////
-
-
-class LLAdvancedToggleConsole : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string console_type = userdata.asString();
- if ("texture" == console_type)
- {
- toggle_visibility( (void*)gTextureView );
- }
- else if ("debug" == console_type)
- {
- toggle_visibility( (void*)static_cast<LLUICtrl*>(gDebugView->mDebugConsolep));
- }
- else if (gTextureSizeView && "texture size" == console_type)
- {
- toggle_visibility( (void*)gTextureSizeView );
- }
- else if (gTextureCategoryView && "texture category" == console_type)
- {
- toggle_visibility( (void*)gTextureCategoryView );
- }
- else if ("fast timers" == console_type)
- {
- toggle_visibility( (void*)gDebugView->mFastTimerView );
- }
-#if MEM_TRACK_MEM
- else if ("memory view" == console_type)
- {
- toggle_visibility( (void*)gDebugView->mMemoryView );
- }
-#endif
- return true;
- }
-};
-class LLAdvancedCheckConsole : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string console_type = userdata.asString();
- bool new_value = false;
- if ("texture" == console_type)
- {
- new_value = get_visibility( (void*)gTextureView );
- }
- else if ("debug" == console_type)
- {
- new_value = get_visibility( (void*)((LLView*)gDebugView->mDebugConsolep) );
- }
- else if (gTextureSizeView && "texture size" == console_type)
- {
- new_value = get_visibility( (void*)gTextureSizeView );
- }
- else if (gTextureCategoryView && "texture category" == console_type)
- {
- new_value = get_visibility( (void*)gTextureCategoryView );
- }
- else if ("fast timers" == console_type)
- {
- new_value = get_visibility( (void*)gDebugView->mFastTimerView );
- }
-#if MEM_TRACK_MEM
- else if ("memory view" == console_type)
- {
- new_value = get_visibility( (void*)gDebugView->mMemoryView );
- }
-#endif
-
- return new_value;
- }
-};
-
-
-//////////////////////////
-// DUMP INFO TO CONSOLE //
-//////////////////////////
-
-
-class LLAdvancedDumpInfoToConsole : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string info_type = userdata.asString();
- if ("region" == info_type)
- {
- handle_region_dump_settings(NULL);
- }
- else if ("group" == info_type)
- {
- handle_dump_group_info(NULL);
- }
- else if ("capabilities" == info_type)
- {
- handle_dump_capabilities_info(NULL);
- }
- return true;
- }
-};
-
-
-//////////////
-// HUD INFO //
-//////////////
-
-
-class LLAdvancedToggleHUDInfo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string info_type = userdata.asString();
-
- if ("camera" == info_type)
- {
- gDisplayCameraPos = !(gDisplayCameraPos);
- }
- else if ("wind" == info_type)
- {
- gDisplayWindInfo = !(gDisplayWindInfo);
- }
- else if ("fov" == info_type)
- {
- gDisplayFOV = !(gDisplayFOV);
- }
- else if ("badge" == info_type)
- {
- gDisplayBadge = !(gDisplayBadge);
- }
- return true;
- }
-};
-
-class LLAdvancedCheckHUDInfo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string info_type = userdata.asString();
- bool new_value = false;
- if ("camera" == info_type)
- {
- new_value = gDisplayCameraPos;
- }
- else if ("wind" == info_type)
- {
- new_value = gDisplayWindInfo;
- }
- else if ("fov" == info_type)
- {
- new_value = gDisplayFOV;
- }
- else if ("badge" == info_type)
- {
- new_value = gDisplayBadge;
- }
- return new_value;
- }
-};
-
-
-//////////////
-// FLYING //
-//////////////
-
-class LLAdvancedAgentFlyingInfo : public view_listener_t
-{
- bool handleEvent(const LLSD&)
- {
- return gAgent.getFlying();
- }
-};
-
-
-///////////////////////
-// CLEAR GROUP CACHE //
-///////////////////////
-
-class LLAdvancedClearGroupCache : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLGroupMgr::debugClearAllGroups(NULL);
- return true;
- }
-};
-
-
-
-
-/////////////////
-// RENDER TYPE //
-/////////////////
-U32 render_type_from_string(std::string render_type)
-{
- if ("simple" == render_type)
- {
- return LLPipeline::RENDER_TYPE_SIMPLE;
- }
- else if ("alpha" == render_type)
- {
- return LLPipeline::RENDER_TYPE_ALPHA;
- }
- else if ("tree" == render_type)
- {
- return LLPipeline::RENDER_TYPE_TREE;
- }
- else if ("character" == render_type)
- {
- return LLPipeline::RENDER_TYPE_AVATAR;
- }
- else if ("surfacePath" == render_type)
- {
- return LLPipeline::RENDER_TYPE_TERRAIN;
- }
- else if ("sky" == render_type)
- {
- return LLPipeline::RENDER_TYPE_SKY;
- }
- else if ("water" == render_type)
- {
- return LLPipeline::RENDER_TYPE_WATER;
- }
- else if ("ground" == render_type)
- {
- return LLPipeline::RENDER_TYPE_GROUND;
- }
- else if ("volume" == render_type)
- {
- return LLPipeline::RENDER_TYPE_VOLUME;
- }
- else if ("grass" == render_type)
- {
- return LLPipeline::RENDER_TYPE_GRASS;
- }
- else if ("clouds" == render_type)
- {
- return LLPipeline::RENDER_TYPE_CLOUDS;
- }
- else if ("particles" == render_type)
- {
- return LLPipeline::RENDER_TYPE_PARTICLES;
- }
- else if ("bump" == render_type)
- {
- return LLPipeline::RENDER_TYPE_BUMP;
- }
- else
- {
- return 0;
- }
-}
-
-
-class LLAdvancedToggleRenderType : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- U32 render_type = render_type_from_string( userdata.asString() );
- if ( render_type != 0 )
- {
- LLPipeline::toggleRenderTypeControl( (void*)render_type );
- }
- return true;
- }
-};
-
-
-class LLAdvancedCheckRenderType : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- U32 render_type = render_type_from_string( userdata.asString() );
- bool new_value = false;
-
- if ( render_type != 0 )
- {
- new_value = LLPipeline::hasRenderTypeControl( (void*)render_type );
- }
-
- return new_value;
- }
-};
-
-
-/////////////
-// FEATURE //
-/////////////
-U32 feature_from_string(std::string feature)
-{
- if ("ui" == feature)
- {
- return LLPipeline::RENDER_DEBUG_FEATURE_UI;
- }
- else if ("selected" == feature)
- {
- return LLPipeline::RENDER_DEBUG_FEATURE_SELECTED;
- }
- else if ("highlighted" == feature)
- {
- return LLPipeline::RENDER_DEBUG_FEATURE_HIGHLIGHTED;
- }
- else if ("dynamic textures" == feature)
- {
- return LLPipeline::RENDER_DEBUG_FEATURE_DYNAMIC_TEXTURES;
- }
- else if ("foot shadows" == feature)
- {
- return LLPipeline::RENDER_DEBUG_FEATURE_FOOT_SHADOWS;
- }
- else if ("fog" == feature)
- {
- return LLPipeline::RENDER_DEBUG_FEATURE_FOG;
- }
- else if ("fr info" == feature)
- {
- return LLPipeline::RENDER_DEBUG_FEATURE_FR_INFO;
- }
- else if ("flexible" == feature)
- {
- return LLPipeline::RENDER_DEBUG_FEATURE_FLEXIBLE;
- }
- else
- {
- return 0;
- }
-};
-
-
-class LLAdvancedToggleFeature : public view_listener_t{
- bool handleEvent(const LLSD& userdata)
- {
- U32 feature = feature_from_string( userdata.asString() );
- if ( feature != 0 )
- {
- LLPipeline::toggleRenderDebugFeature( (void*)feature );
- }
- return true;
- }
-};
-
-class LLAdvancedCheckFeature : public view_listener_t
-{bool handleEvent(const LLSD& userdata)
-{
- U32 feature = feature_from_string( userdata.asString() );
- bool new_value = false;
-
- if ( feature != 0 )
- {
- new_value = LLPipeline::toggleRenderDebugFeatureControl( (void*)feature );
- }
-
- return new_value;
-}
-};
-
-void toggle_destination_and_avatar_picker(const LLSD& show)
-{
- S32 panel_idx = show.isDefined() ? show.asInteger() : -1;
- LLView* container = gViewerWindow->getRootView()->getChildView("avatar_picker_and_destination_guide_container");
- LLMediaCtrl* destinations = container->findChild<LLMediaCtrl>("destination_guide_contents");
- LLMediaCtrl* avatar_picker = container->findChild<LLMediaCtrl>("avatar_picker_contents");
- LLButton* avatar_btn = gViewerWindow->getRootView()->getChildView("bottom_tray")->getChild<LLButton>("avatar_btn");
- LLButton* destination_btn = gViewerWindow->getRootView()->getChildView("bottom_tray")->getChild<LLButton>("destination_btn");
-
- switch(panel_idx)
- {
- case 0:
- container->setVisible(true);
- destinations->setVisible(true);
- avatar_picker->setVisible(false);
- LLFirstUse::notUsingDestinationGuide(false);
- avatar_btn->setToggleState(false);
- destination_btn->setToggleState(true);
- break;
- case 1:
- container->setVisible(true);
- destinations->setVisible(false);
- avatar_picker->setVisible(true);
- avatar_btn->setToggleState(true);
- destination_btn->setToggleState(false);
- break;
- default:
- container->setVisible(false);
- destinations->setVisible(false);
- avatar_picker->setVisible(false);
- avatar_btn->setToggleState(false);
- destination_btn->setToggleState(false);
- break;
- }
-};
-
-
-//////////////////
-// INFO DISPLAY //
-//////////////////
-U32 info_display_from_string(std::string info_display)
-{
- if ("verify" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_VERIFY;
- }
- else if ("bboxes" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_BBOXES;
- }
- else if ("points" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_POINTS;
- }
- else if ("octree" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_OCTREE;
- }
- else if ("shadow frusta" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_SHADOW_FRUSTA;
- }
- else if ("occlusion" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_OCCLUSION;
- }
- else if ("render batches" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_BATCH_SIZE;
- }
- else if ("update type" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_UPDATE_TYPE;
- }
- else if ("texture anim" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_TEXTURE_ANIM;
- }
- else if ("texture priority" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_TEXTURE_PRIORITY;
- }
- else if ("shame" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_SHAME;
- }
- else if ("texture area" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_TEXTURE_AREA;
- }
- else if ("face area" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_FACE_AREA;
- }
- else if ("lights" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_LIGHTS;
- }
- else if ("particles" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_PARTICLES;
- }
- else if ("composition" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_COMPOSITION;
- }
- else if ("glow" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_GLOW;
- }
- else if ("collision skeleton" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_AVATAR_VOLUME;
- }
- else if ("raycast" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_RAYCAST;
- }
- else if ("agent target" == info_display)
- {
- return LLPipeline::RENDER_DEBUG_AGENT_TARGET;
- }
- else
- {
- return 0;
- }
-};
-
-class LLAdvancedToggleInfoDisplay : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- U32 info_display = info_display_from_string( userdata.asString() );
-
- if ( info_display != 0 )
- {
- LLPipeline::toggleRenderDebug( (void*)info_display );
- }
-
- return true;
- }
-};
-
-
-class LLAdvancedCheckInfoDisplay : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- U32 info_display = info_display_from_string( userdata.asString() );
- bool new_value = false;
-
- if ( info_display != 0 )
- {
- new_value = LLPipeline::toggleRenderDebugControl( (void*)info_display );
- }
-
- return new_value;
- }
-};
-
-
-///////////////////////////
-//// RANDOMIZE FRAMERATE //
-///////////////////////////
-
-
-class LLAdvancedToggleRandomizeFramerate : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gRandomizeFramerate = !(gRandomizeFramerate);
- return true;
- }
-};
-
-class LLAdvancedCheckRandomizeFramerate : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gRandomizeFramerate;
- return new_value;
- }
-};
-
-void run_vectorize_perf_test(void *)
-{
- gSavedSettings.setBOOL("VectorizePerfTest", TRUE);
-}
-
-
-////////////////////////////////
-// RUN Vectorized Perform Test//
-////////////////////////////////
-
-
-class LLAdvancedVectorizePerfTest : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- run_vectorize_perf_test(NULL);
- return true;
- }
-};
-
-///////////////////////////
-//// PERIODIC SLOW FRAME //
-///////////////////////////
-
-
-class LLAdvancedTogglePeriodicSlowFrame : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gPeriodicSlowFrame = !(gPeriodicSlowFrame);
- return true;
- }
-};
-
-class LLAdvancedCheckPeriodicSlowFrame : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gPeriodicSlowFrame;
- return new_value;
- }
-};
-
-
-
-////////////////
-// FRAME TEST //
-////////////////
-
-
-class LLAdvancedToggleFrameTest : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLPipeline::sRenderFrameTest = !(LLPipeline::sRenderFrameTest);
- return true;
- }
-};
-
-class LLAdvancedCheckFrameTest : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLPipeline::sRenderFrameTest;
- return new_value;
- }
-};
-
-
-///////////////////////////
-// SELECTED TEXTURE INFO //
-///////////////////////////
-
-
-class LLAdvancedSelectedTextureInfo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_selected_texture_info(NULL);
- return true;
- }
-};
-
-//////////////////////
-// TOGGLE WIREFRAME //
-//////////////////////
-
-class LLAdvancedToggleWireframe : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gUseWireframe = !(gUseWireframe);
- LLPipeline::updateRenderDeferred();
- gPipeline.resetVertexBuffers();
- return true;
- }
-};
-
-class LLAdvancedCheckWireframe : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gUseWireframe;
- return new_value;
- }
-};
-
-//////////////////////
-// TEXTURE ATLAS //
-//////////////////////
-
-class LLAdvancedToggleTextureAtlas : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLViewerTexture::sUseTextureAtlas = !LLViewerTexture::sUseTextureAtlas;
- gSavedSettings.setBOOL("EnableTextureAtlas", LLViewerTexture::sUseTextureAtlas) ;
- return true;
- }
-};
-
-class LLAdvancedCheckTextureAtlas : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLViewerTexture::sUseTextureAtlas; // <-- make this using LLCacheControl
- return new_value;
- }
-};
-
-//////////////////////////
-// DUMP SCRIPTED CAMERA //
-//////////////////////////
-
-class LLAdvancedDumpScriptedCamera : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_dump_followcam(NULL);
- return true;
-}
-};
-
-
-
-//////////////////////////////
-// DUMP REGION OBJECT CACHE //
-//////////////////////////////
-
-
-class LLAdvancedDumpRegionObjectCache : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
-{
- handle_dump_region_object_cache(NULL);
- return true;
- }
-};
-
-class LLAdvancedBuyCurrencyTest : public view_listener_t
- {
- bool handleEvent(const LLSD& userdata)
- {
- handle_buy_currency_test(NULL);
- return true;
- }
-};
-
-
-/////////////////////
-// DUMP SELECT MGR //
-/////////////////////
-
-
-class LLAdvancedDumpSelectMgr : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- dump_select_mgr(NULL);
- return true;
- }
-};
-
-
-
-////////////////////
-// DUMP INVENTORY //
-////////////////////
-
-
-class LLAdvancedDumpInventory : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- dump_inventory(NULL);
- return true;
- }
-};
-
-
-
-////////////////////////////////
-// PRINT SELECTED OBJECT INFO //
-////////////////////////////////
-
-
-class LLAdvancedPrintSelectedObjectInfo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- print_object_info(NULL);
- return true;
- }
-};
-
-
-
-//////////////////////
-// PRINT AGENT INFO //
-//////////////////////
-
-
-class LLAdvancedPrintAgentInfo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- print_agent_nvpairs(NULL);
- return true;
- }
-};
-
-
-
-////////////////////////////////
-// PRINT TEXTURE MEMORY STATS //
-////////////////////////////////
-
-
-class LLAdvancedPrintTextureMemoryStats : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- output_statistics(NULL);
- return true;
- }
-};
-
-//////////////////
-// DEBUG CLICKS //
-//////////////////
-
-
-class LLAdvancedToggleDebugClicks : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gDebugClicks = !(gDebugClicks);
- return true;
- }
-};
-
-class LLAdvancedCheckDebugClicks : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gDebugClicks;
- return new_value;
- }
-};
-
-
-
-/////////////////
-// DEBUG VIEWS //
-/////////////////
-
-
-class LLAdvancedToggleDebugViews : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLView::sDebugRects = !(LLView::sDebugRects);
- return true;
- }
-};
-
-class LLAdvancedCheckDebugViews : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLView::sDebugRects;
- return new_value;
- }
-};
-
-
-
-///////////////////////
-// XUI NAME TOOLTIPS //
-///////////////////////
-
-
-class LLAdvancedToggleXUINameTooltips : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- toggle_show_xui_names(NULL);
- return true;
- }
-};
-
-class LLAdvancedCheckXUINameTooltips : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = check_show_xui_names(NULL);
- return new_value;
- }
-};
-
-
-
-////////////////////////
-// DEBUG MOUSE EVENTS //
-////////////////////////
-
-
-class LLAdvancedToggleDebugMouseEvents : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLView::sDebugMouseHandling = !(LLView::sDebugMouseHandling);
- return true;
- }
-};
-
-class LLAdvancedCheckDebugMouseEvents : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLView::sDebugMouseHandling;
- return new_value;
- }
-};
-
-
-
-////////////////
-// DEBUG KEYS //
-////////////////
-
-
-class LLAdvancedToggleDebugKeys : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLView::sDebugKeys = !(LLView::sDebugKeys);
- return true;
- }
-};
-
-class LLAdvancedCheckDebugKeys : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLView::sDebugKeys;
- return new_value;
- }
-};
-
-
-
-///////////////////////
-// DEBUG WINDOW PROC //
-///////////////////////
-
-
-class LLAdvancedToggleDebugWindowProc : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gDebugWindowProc = !(gDebugWindowProc);
- return true;
- }
-};
-
-class LLAdvancedCheckDebugWindowProc : public view_listener_t
- {
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gDebugWindowProc;
- return new_value;
- }
-};
-
-// ------------------------------XUI MENU ---------------------------
-
-class LLAdvancedSendTestIms : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLIMModel::instance().testMessages();
- return true;
-}
-};
-
-
-///////////////
-// XUI NAMES //
-///////////////
-
-
-class LLAdvancedToggleXUINames : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- toggle_show_xui_names(NULL);
- return true;
- }
-};
-
-class LLAdvancedCheckXUINames : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = check_show_xui_names(NULL);
- return new_value;
- }
-};
-
-
-////////////////////////
-// GRAB BAKED TEXTURE //
-////////////////////////
-
-
-class LLAdvancedGrabBakedTexture : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string texture_type = userdata.asString();
- if ("iris" == texture_type)
- {
- handle_grab_baked_texture( (void*)BAKED_EYES );
- }
- else if ("head" == texture_type)
- {
- handle_grab_baked_texture( (void*)BAKED_HEAD );
- }
- else if ("upper" == texture_type)
- {
- handle_grab_baked_texture( (void*)BAKED_UPPER );
- }
- else if ("lower" == texture_type)
- {
- handle_grab_baked_texture( (void*)BAKED_LOWER );
- }
- else if ("skirt" == texture_type)
- {
- handle_grab_baked_texture( (void*)BAKED_SKIRT );
- }
- else if ("hair" == texture_type)
- {
- handle_grab_baked_texture( (void*)BAKED_HAIR );
- }
-
- return true;
- }
-};
-
-class LLAdvancedEnableGrabBakedTexture : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
-{
- std::string texture_type = userdata.asString();
- bool new_value = false;
-
- if ("iris" == texture_type)
- {
- new_value = enable_grab_baked_texture( (void*)BAKED_EYES );
- }
- else if ("head" == texture_type)
- {
- new_value = enable_grab_baked_texture( (void*)BAKED_HEAD );
- }
- else if ("upper" == texture_type)
- {
- new_value = enable_grab_baked_texture( (void*)BAKED_UPPER );
- }
- else if ("lower" == texture_type)
- {
- new_value = enable_grab_baked_texture( (void*)BAKED_LOWER );
- }
- else if ("skirt" == texture_type)
- {
- new_value = enable_grab_baked_texture( (void*)BAKED_SKIRT );
- }
- else if ("hair" == texture_type)
- {
- new_value = enable_grab_baked_texture( (void*)BAKED_HAIR );
- }
-
- return new_value;
-}
-};
-
-///////////////////////
-// APPEARANCE TO XML //
-///////////////////////
-
-
-class LLAdvancedAppearanceToXML : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar::dumpArchetypeXML(NULL);
- return true;
- }
-};
-
-
-
-///////////////////////////////
-// TOGGLE CHARACTER GEOMETRY //
-///////////////////////////////
-
-
-class LLAdvancedToggleCharacterGeometry : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_god_request_avatar_geometry(NULL);
- return true;
-}
-};
-
-
- /////////////////////////////
-// TEST MALE / TEST FEMALE //
-/////////////////////////////
-
-class LLAdvancedTestMale : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_test_male(NULL);
- return true;
- }
-};
-
-
-class LLAdvancedTestFemale : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_test_female(NULL);
- return true;
- }
-};
-
-
-
-///////////////
-// TOGGLE PG //
-///////////////
-
-
-class LLAdvancedTogglePG : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_toggle_pg(NULL);
- return true;
- }
-};
-
-
-class LLAdvancedForceParamsToDefault : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLAgent::clearVisualParams(NULL);
- return true;
- }
-};
-
-
-
-//////////////////////////
-// RELOAD VERTEX SHADER //
-//////////////////////////
-
-
-class LLAdvancedReloadVertexShader : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- reload_vertex_shader(NULL);
- return true;
- }
-};
-
-
-
-////////////////////
-// ANIMATION INFO //
-////////////////////
-
-
-class LLAdvancedToggleAnimationInfo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar::sShowAnimationDebug = !(LLVOAvatar::sShowAnimationDebug);
- return true;
- }
-};
-
-class LLAdvancedCheckAnimationInfo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLVOAvatar::sShowAnimationDebug;
- return new_value;
- }
-};
-
-
-//////////////////
-// SHOW LOOK AT //
-//////////////////
-
-
-class LLAdvancedToggleShowLookAt : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLHUDEffectLookAt::sDebugLookAt = !(LLHUDEffectLookAt::sDebugLookAt);
- return true;
- }
-};
-
-class LLAdvancedCheckShowLookAt : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLHUDEffectLookAt::sDebugLookAt;
- return new_value;
- }
-};
-
-
-
-///////////////////
-// SHOW POINT AT //
-///////////////////
-
-
-class LLAdvancedToggleShowPointAt : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLHUDEffectPointAt::sDebugPointAt = !(LLHUDEffectPointAt::sDebugPointAt);
- return true;
- }
-};
-
-class LLAdvancedCheckShowPointAt : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLHUDEffectPointAt::sDebugPointAt;
- return new_value;
- }
-};
-
-
-
-/////////////////////////
-// DEBUG JOINT UPDATES //
-/////////////////////////
-
-
-class LLAdvancedToggleDebugJointUpdates : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar::sJointDebug = !(LLVOAvatar::sJointDebug);
- return true;
- }
-};
-
-class LLAdvancedCheckDebugJointUpdates : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLVOAvatar::sJointDebug;
- return new_value;
- }
-};
-
-
-
-/////////////////
-// DISABLE LOD //
-/////////////////
-
-
-class LLAdvancedToggleDisableLOD : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLViewerJoint::sDisableLOD = !(LLViewerJoint::sDisableLOD);
- return true;
- }
-};
-
-class LLAdvancedCheckDisableLOD : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLViewerJoint::sDisableLOD;
- return new_value;
- }
-};
-
-
-
-/////////////////////////
-// DEBUG CHARACTER VIS //
-/////////////////////////
-
-
-class LLAdvancedToggleDebugCharacterVis : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar::sDebugInvisible = !(LLVOAvatar::sDebugInvisible);
- return true;
- }
-};
-
-class LLAdvancedCheckDebugCharacterVis : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLVOAvatar::sDebugInvisible;
- return new_value;
- }
-};
-
-
-//////////////////////
-// DUMP ATTACHMENTS //
-//////////////////////
-
-
-class LLAdvancedDumpAttachments : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_dump_attachments(NULL);
- return true;
- }
-};
-
-
-
-/////////////////////
-// REBAKE TEXTURES //
-/////////////////////
-
-
-class LLAdvancedRebakeTextures : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_rebake_textures(NULL);
- return true;
- }
-};
-
-
-#if 1 //ndef LL_RELEASE_FOR_DOWNLOAD
-///////////////////////////
-// DEBUG AVATAR TEXTURES //
-///////////////////////////
-
-
-class LLAdvancedDebugAvatarTextures : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if (gAgent.isGodlike())
- {
- handle_debug_avatar_textures(NULL);
- }
- return true;
- }
-};
-
-////////////////////////////////
-// DUMP AVATAR LOCAL TEXTURES //
-////////////////////////////////
-
-
-class LLAdvancedDumpAvatarLocalTextures : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
-#ifndef LL_RELEASE_FOR_DOWNLOAD
- handle_dump_avatar_local_textures(NULL);
-#endif
- return true;
- }
-};
-
-#endif
-
-/////////////////
-// MESSAGE LOG //
-/////////////////
-
-
-class LLAdvancedEnableMessageLog : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_viewer_enable_message_log(NULL);
- return true;
- }
-};
-
-class LLAdvancedDisableMessageLog : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_viewer_disable_message_log(NULL);
- return true;
- }
-};
-
-/////////////////
-// DROP PACKET //
-/////////////////
-
-
-class LLAdvancedDropPacket : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gMessageSystem->mPacketRing.dropPackets(1);
- return true;
- }
-};
-
-
-
-/////////////////
-// AGENT PILOT //
-/////////////////
-
-
-class LLAdvancedAgentPilot : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string command = userdata.asString();
- if ("start playback" == command)
- {
- LLAgentPilot::startPlayback(NULL);
- }
- else if ("stop playback" == command)
- {
- LLAgentPilot::stopPlayback(NULL);
- }
- else if ("start record" == command)
- {
- LLAgentPilot::startRecord(NULL);
- }
- else if ("stop record" == command)
- {
- LLAgentPilot::saveRecord(NULL);
- }
-
- return true;
- }
-};
-
-
-
-//////////////////////
-// AGENT PILOT LOOP //
-//////////////////////
-
-
-class LLAdvancedToggleAgentPilotLoop : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLAgentPilot::sLoop = !(LLAgentPilot::sLoop);
- return true;
- }
-};
-
-class LLAdvancedCheckAgentPilotLoop : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLAgentPilot::sLoop;
- return new_value;
- }
-};
-
-
-/////////////////////////
-// SHOW OBJECT UPDATES //
-/////////////////////////
-
-
-class LLAdvancedToggleShowObjectUpdates : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gShowObjectUpdates = !(gShowObjectUpdates);
- return true;
- }
-};
-
-class LLAdvancedCheckShowObjectUpdates : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gShowObjectUpdates;
- return new_value;
- }
-};
-
-
-
-////////////////////
-// COMPRESS IMAGE //
-////////////////////
-
-
-class LLAdvancedCompressImage : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_compress_image(NULL);
- return true;
- }
-};
-
-
-
-/////////////////////////
-// SHOW DEBUG SETTINGS //
-/////////////////////////
-
-
-class LLAdvancedShowDebugSettings : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLFloaterReg::showInstance("settings_debug",userdata);
- return true;
- }
-};
-
-
-
-////////////////////////
-// VIEW ADMIN OPTIONS //
-////////////////////////
-
-class LLAdvancedEnableViewAdminOptions : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- // Don't enable in god mode since the admin menu is shown anyway.
- // Only enable if the user has set the appropriate debug setting.
- bool new_value = !gAgent.getAgentAccess().isGodlikeWithoutAdminMenuFakery() && gSavedSettings.getBOOL("AdminMenu");
- return new_value;
- }
-};
-
-class LLAdvancedToggleViewAdminOptions : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_admin_override_toggle(NULL);
- return true;
- }
-};
-
-class LLAdvancedCheckViewAdminOptions : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = check_admin_override(NULL) || gAgent.isGodlike();
- return new_value;
- }
-};
-
-/////////////////////////////////////
-// Enable Object Object Occlusion ///
-/////////////////////////////////////
-class LLAdvancedEnableObjectObjectOcclusion: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
-
- bool new_value = gGLManager.mHasOcclusionQuery; // && LLFeatureManager::getInstance()->isFeatureAvailable(userdata.asString());
- return new_value;
-}
-};
-
-/////////////////////////////////////
-// Enable Framebuffer Objects ///
-/////////////////////////////////////
-class LLAdvancedEnableRenderFBO: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gGLManager.mHasFramebufferObject;
- return new_value;
- }
-};
-
-/////////////////////////////////////
-// Enable Deferred Rendering ///
-/////////////////////////////////////
-class LLAdvancedEnableRenderDeferred: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gSavedSettings.getBOOL("RenderUseFBO") && LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_WINDLIGHT > 0) &&
- LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_AVATAR) > 0;
- return new_value;
- }
-};
-
-/////////////////////////////////////
-// Enable Deferred Rendering sub-options
-/////////////////////////////////////
-class LLAdvancedEnableRenderDeferredOptions: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gSavedSettings.getBOOL("RenderUseFBO") && gSavedSettings.getBOOL("RenderDeferred");
- return new_value;
- }
-};
-
-
-
-//////////////////
-// ADMIN STATUS //
-//////////////////
-
-
-class LLAdvancedRequestAdminStatus : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_god_mode(NULL);
- return true;
- }
-};
-
-class LLAdvancedLeaveAdminStatus : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_leave_god_mode(NULL);
- return true;
- }
-};
-
-//////////////////////////
-// Advanced > Debugging //
-//////////////////////////
-
-
-class LLAdvancedForceErrorBreakpoint : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- force_error_breakpoint(NULL);
- return true;
- }
-};
-
-class LLAdvancedForceErrorLlerror : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- force_error_llerror(NULL);
- return true;
- }
-};
-class LLAdvancedForceErrorBadMemoryAccess : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- force_error_bad_memory_access(NULL);
- return true;
- }
-};
-
-class LLAdvancedForceErrorInfiniteLoop : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- force_error_infinite_loop(NULL);
- return true;
- }
-};
-
-class LLAdvancedForceErrorSoftwareException : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- force_error_software_exception(NULL);
- return true;
- }
-};
-
-class LLAdvancedForceErrorDriverCrash : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- force_error_driver_crash(NULL);
- return true;
- }
-};
-
-class LLAdvancedForceErrorDisconnectViewer : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_disconnect_viewer(NULL);
- return true;
-}
-};
-
-
-#ifdef TOGGLE_HACKED_GODLIKE_VIEWER
-
-class LLAdvancedHandleToggleHackedGodmode : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_toggle_hacked_godmode(NULL);
- return true;
- }
-};
-
-class LLAdvancedCheckToggleHackedGodmode : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- check_toggle_hacked_godmode(NULL);
- return true;
- }
-};
-
-class LLAdvancedEnableToggleHackedGodmode : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = enable_toggle_hacked_godmode(NULL);
- return new_value;
- }
-};
-#endif
-
-
-//
-////-------------------------------------------------------------------
-//// Advanced menu
-////-------------------------------------------------------------------
-
-//////////////////
-// ADMIN MENU //
-//////////////////
-
-// Admin > Object
-class LLAdminForceTakeCopy : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- force_take_copy(NULL);
- return true;
- }
-};
-
-class LLAdminHandleObjectOwnerSelf : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_object_owner_self(NULL);
- return true;
- }
-};
-class LLAdminHandleObjectOwnerPermissive : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_object_owner_permissive(NULL);
- return true;
- }
-};
-
-class LLAdminHandleForceDelete : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_force_delete(NULL);
- return true;
- }
-};
-
-class LLAdminHandleObjectLock : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_object_lock(NULL);
- return true;
- }
-};
-
-class LLAdminHandleObjectAssetIDs: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_object_asset_ids(NULL);
- return true;
- }
-};
-
-//Admin >Parcel
-class LLAdminHandleForceParcelOwnerToMe: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_force_parcel_owner_to_me(NULL);
- return true;
- }
-};
-class LLAdminHandleForceParcelToContent: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_force_parcel_to_content(NULL);
- return true;
- }
-};
-class LLAdminHandleClaimPublicLand: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_claim_public_land(NULL);
- return true;
- }
-};
-
-// Admin > Region
-class LLAdminHandleRegionDumpTempAssetData: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_region_dump_temp_asset_data(NULL);
- return true;
- }
-};
-//Admin (Top Level)
-
-class LLAdminOnSaveState: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLPanelRegionTools::onSaveState(NULL);
- return true;
-}
-};
-
-
-//-----------------------------------------------------------------------------
-// cleanup_menus()
-//-----------------------------------------------------------------------------
-void cleanup_menus()
-{
- delete gMenuParcelObserver;
- gMenuParcelObserver = NULL;
-
- delete gMenuAvatarSelf;
- gMenuAvatarSelf = NULL;
-
- delete gMenuAvatarOther;
- gMenuAvatarOther = NULL;
-
- delete gMenuObject;
- gMenuObject = NULL;
-
- delete gMenuAttachmentSelf;
- gMenuAttachmentSelf = NULL;
-
- delete gMenuAttachmentOther;
- gMenuAttachmentSelf = NULL;
-
- delete gMenuLand;
- gMenuLand = NULL;
-
- delete gMenuBarView;
- gMenuBarView = NULL;
-
- delete gPopupMenuView;
- gPopupMenuView = NULL;
-
- delete gMenuHolder;
- gMenuHolder = NULL;
-}
-
-//-----------------------------------------------------------------------------
-// Object pie menu
-//-----------------------------------------------------------------------------
-
-class LLObjectReportAbuse : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- if (objectp)
- {
- LLFloaterReporter::showFromObject(objectp->getID());
- }
- return true;
- }
-};
-
-// Enabled it you clicked an object
-class LLObjectEnableReportAbuse : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLSelectMgr::getInstance()->getSelection()->getObjectCount() != 0;
- return new_value;
- }
-};
-
-void handle_object_touch()
-{
- LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- if (!object) return;
-
- LLPickInfo pick = LLToolPie::getInstance()->getPick();
-
- LLMessageSystem *msg = gMessageSystem;
-
- msg->newMessageFast(_PREHASH_ObjectGrab);
- msg->nextBlockFast( _PREHASH_AgentData);
- msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
- msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- msg->nextBlockFast( _PREHASH_ObjectData);
- msg->addU32Fast( _PREHASH_LocalID, object->mLocalID);
- msg->addVector3Fast(_PREHASH_GrabOffset, LLVector3::zero );
- msg->nextBlock("SurfaceInfo");
- msg->addVector3("UVCoord", LLVector3(pick.mUVCoords));
- msg->addVector3("STCoord", LLVector3(pick.mSTCoords));
- msg->addS32Fast(_PREHASH_FaceIndex, pick.mObjectFace);
- msg->addVector3("Position", pick.mIntersection);
- msg->addVector3("Normal", pick.mNormal);
- msg->addVector3("Binormal", pick.mBinormal);
- msg->sendMessage( object->getRegion()->getHost());
-
- // *NOTE: Hope the packets arrive safely and in order or else
- // there will be some problems.
- // *TODO: Just fix this bad assumption.
- msg->newMessageFast(_PREHASH_ObjectDeGrab);
- msg->nextBlockFast(_PREHASH_AgentData);
- msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
- msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- msg->nextBlockFast(_PREHASH_ObjectData);
- msg->addU32Fast(_PREHASH_LocalID, object->mLocalID);
- msg->nextBlock("SurfaceInfo");
- msg->addVector3("UVCoord", LLVector3(pick.mUVCoords));
- msg->addVector3("STCoord", LLVector3(pick.mSTCoords));
- msg->addS32Fast(_PREHASH_FaceIndex, pick.mObjectFace);
- msg->addVector3("Position", pick.mIntersection);
- msg->addVector3("Normal", pick.mNormal);
- msg->addVector3("Binormal", pick.mBinormal);
- msg->sendMessage(object->getRegion()->getHost());
-}
-
-static void init_default_item_label(const std::string& item_name)
-{
- boost::unordered_map<std::string, LLStringExplicit>::iterator it = sDefaultItemLabels.find(item_name);
- if (it == sDefaultItemLabels.end())
- {
- // *NOTE: This will not work for items of type LLMenuItemCheckGL because they return boolean value
- // (doesn't seem to matter much ATM).
- LLStringExplicit default_label = gMenuHolder->childGetValue(item_name).asString();
- if (!default_label.empty())
- {
- sDefaultItemLabels.insert(std::pair<std::string, LLStringExplicit>(item_name, default_label));
- }
- }
-}
-
-static LLStringExplicit get_default_item_label(const std::string& item_name)
-{
- LLStringExplicit res("");
- boost::unordered_map<std::string, LLStringExplicit>::iterator it = sDefaultItemLabels.find(item_name);
- if (it != sDefaultItemLabels.end())
- {
- res = it->second;
- }
-
- return res;
-}
-
-
-bool enable_object_touch(LLUICtrl* ctrl)
-{
- LLViewerObject* obj = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
-
- bool new_value = obj && obj->flagHandleTouch();
-
- std::string item_name = ctrl->getName();
- init_default_item_label(item_name);
-
- // Update label based on the node touch name if available.
- LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
- if (node && node->mValid && !node->mTouchName.empty())
- {
- gMenuHolder->childSetText(item_name, node->mTouchName);
- }
- else
- {
- gMenuHolder->childSetText(item_name, get_default_item_label(item_name));
- }
-
- return new_value;
-};
-
-//void label_touch(std::string& label, void*)
-//{
-// LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
-// if (node && node->mValid && !node->mTouchName.empty())
-// {
-// label.assign(node->mTouchName);
-// }
-// else
-// {
-// label.assign("Touch");
-// }
-//}
-
-void handle_object_open()
-{
- LLFloaterReg::showInstance("openobject");
-}
-
-bool enable_object_open()
-{
- // Look for contents in root object, which is all the LLFloaterOpenObject
- // understands.
- LLViewerObject* obj = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- if (!obj) return false;
-
- LLViewerObject* root = obj->getRootEdit();
- if (!root) return false;
-
- return root->allowOpen();
-}
-
-
-class LLViewJoystickFlycam : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_toggle_flycam();
- return true;
- }
-};
-
-class LLViewCheckJoystickFlycam : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLViewerJoystick::getInstance()->getOverrideCamera();
- return new_value;
- }
-};
-
-void handle_toggle_flycam()
-{
- LLViewerJoystick::getInstance()->toggleFlycam();
-}
-
-class LLObjectBuild : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if (gAgentCamera.getFocusOnAvatar() && !LLToolMgr::getInstance()->inEdit() && gSavedSettings.getBOOL("EditCameraMovement") )
- {
- // zoom in if we're looking at the avatar
- gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
- gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
- gAgentCamera.cameraZoomIn(0.666f);
- gAgentCamera.cameraOrbitOver( 30.f * DEG_TO_RAD );
- gViewerWindow->moveCursorToCenter();
- }
- else if ( gSavedSettings.getBOOL("EditCameraMovement") )
- {
- gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
- gViewerWindow->moveCursorToCenter();
- }
-
- LLToolMgr::getInstance()->setCurrentToolset(gBasicToolset);
- LLToolMgr::getInstance()->getCurrentToolset()->selectTool( LLToolCompCreate::getInstance() );
-
- // Could be first use
- //LLFirstUse::useBuild();
- return true;
- }
-};
-
-
-void handle_object_edit()
-{
- LLViewerParcelMgr::getInstance()->deselectLand();
-
- if (gAgentCamera.getFocusOnAvatar() && !LLToolMgr::getInstance()->inEdit())
- {
- LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
-
- if (selection->getSelectType() == SELECT_TYPE_HUD || !gSavedSettings.getBOOL("EditCameraMovement"))
- {
- // always freeze camera in space, even if camera doesn't move
- // so, for example, follow cam scripts can't affect you when in build mode
- gAgentCamera.setFocusGlobal(gAgentCamera.calcFocusPositionTargetGlobal(), LLUUID::null);
- gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
- }
- else
- {
- gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
- LLViewerObject* selected_objectp = selection->getFirstRootObject();
- if (selected_objectp)
- {
- // zoom in on object center instead of where we clicked, as we need to see the manipulator handles
- gAgentCamera.setFocusGlobal(selected_objectp->getPositionGlobal(), selected_objectp->getID());
- gAgentCamera.cameraZoomIn(0.666f);
- gAgentCamera.cameraOrbitOver( 30.f * DEG_TO_RAD );
- gViewerWindow->moveCursorToCenter();
- }
- }
- }
-
- LLFloaterReg::showInstance("build");
-
- LLToolMgr::getInstance()->setCurrentToolset(gBasicToolset);
- gFloaterTools->setEditTool( LLToolCompTranslate::getInstance() );
-
- LLViewerJoystick::getInstance()->moveObjects(true);
- LLViewerJoystick::getInstance()->setNeedsReset(true);
-
- // Could be first use
- //LLFirstUse::useBuild();
- return;
-}
-
-void handle_object_inspect()
-{
- LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
- LLViewerObject* selected_objectp = selection->getFirstRootObject();
- if (selected_objectp)
- {
- LLSD key;
- key["task"] = "task";
- LLSideTray::getInstance()->showPanel("sidepanel_inventory", key);
- }
-
- /*
- // Old floater properties
- LLFloaterReg::showInstance("inspect", LLSD());
- */
-}
-
-//---------------------------------------------------------------------------
-// Land pie menu
-//---------------------------------------------------------------------------
-class LLLandBuild : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLViewerParcelMgr::getInstance()->deselectLand();
-
- if (gAgentCamera.getFocusOnAvatar() && !LLToolMgr::getInstance()->inEdit() && gSavedSettings.getBOOL("EditCameraMovement") )
- {
- // zoom in if we're looking at the avatar
- gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
- gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
- gAgentCamera.cameraZoomIn(0.666f);
- gAgentCamera.cameraOrbitOver( 30.f * DEG_TO_RAD );
- gViewerWindow->moveCursorToCenter();
- }
- else if ( gSavedSettings.getBOOL("EditCameraMovement") )
- {
- // otherwise just move focus
- gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
- gViewerWindow->moveCursorToCenter();
- }
-
-
- LLToolMgr::getInstance()->setCurrentToolset(gBasicToolset);
- LLToolMgr::getInstance()->getCurrentToolset()->selectTool( LLToolCompCreate::getInstance() );
-
- // Could be first use
- //LLFirstUse::useBuild();
- return true;
- }
-};
-
-class LLLandBuyPass : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLPanelLandGeneral::onClickBuyPass((void *)FALSE);
- return true;
- }
-};
-
-class LLLandEnableBuyPass : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLPanelLandGeneral::enableBuyPass(NULL);
- return new_value;
- }
-};
-
-// BUG: Should really check if CLICK POINT is in a parcel where you can build.
-BOOL enable_land_build(void*)
-{
- if (gAgent.isGodlike()) return TRUE;
- if (gAgent.inPrelude()) return FALSE;
-
- BOOL can_build = FALSE;
- LLParcel* agent_parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
- if (agent_parcel)
- {
- can_build = agent_parcel->getAllowModify();
- }
- return can_build;
-}
-
-// BUG: Should really check if OBJECT is in a parcel where you can build.
-BOOL enable_object_build(void*)
-{
- if (gAgent.isGodlike()) return TRUE;
- if (gAgent.inPrelude()) return FALSE;
-
- BOOL can_build = FALSE;
- LLParcel* agent_parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
- if (agent_parcel)
- {
- can_build = agent_parcel->getAllowModify();
- }
- return can_build;
-}
-
-bool enable_object_edit()
-{
- // *HACK: The new "prelude" Help Islands have a build sandbox area,
- // so users need the Edit and Create pie menu options when they are
- // there. Eventually this needs to be replaced with code that only
- // lets you edit objects if you have permission to do so (edit perms,
- // group edit, god). See also lltoolbar.cpp. JC
- bool enable = false;
- if (gAgent.inPrelude())
- {
- enable = LLViewerParcelMgr::getInstance()->allowAgentBuild()
- || LLSelectMgr::getInstance()->getSelection()->isAttachment();
- }
- else if (LLSelectMgr::getInstance()->selectGetAllValidAndObjectsFound())
- {
- enable = true;
- }
-
- return enable;
-}
-
-// mutually exclusive - show either edit option or build in menu
-bool enable_object_build()
-{
- return !enable_object_edit();
-}
-
-class LLSelfRemoveAllAttachments : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLAgentWearables::userRemoveAllAttachments();
- return true;
- }
-};
-
-class LLSelfEnableRemoveAllAttachments : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = false;
- if (isAgentAvatarValid())
- {
- for (LLVOAvatar::attachment_map_t::iterator iter = gAgentAvatarp->mAttachmentPoints.begin();
- iter != gAgentAvatarp->mAttachmentPoints.end(); )
- {
- LLVOAvatar::attachment_map_t::iterator curiter = iter++;
- LLViewerJointAttachment* attachment = curiter->second;
- if (attachment->getNumObjects() > 0)
- {
- new_value = true;
- break;
- }
- }
- }
- return new_value;
- }
-};
-
-BOOL enable_has_attachments(void*)
-{
-
- return FALSE;
-}
-
-//---------------------------------------------------------------------------
-// Avatar pie menu
-//---------------------------------------------------------------------------
-//void handle_follow(void *userdata)
-//{
-// // follow a given avatar by ID
-// LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
-// if (objectp)
-// {
-// gAgent.startFollowPilot(objectp->getID());
-// }
-//}
-
-bool enable_object_mute()
-{
- LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- if (!object) return false;
-
- LLVOAvatar* avatar = find_avatar_from_object(object);
- if (avatar)
- {
- // It's an avatar
- LLNameValue *lastname = avatar->getNVPair("LastName");
- bool is_linden =
- lastname && !LLStringUtil::compareStrings(lastname->getString(), "Linden");
- bool is_self = avatar->isSelf();
- return !is_linden && !is_self;
- }
- else
- {
- // Just a regular object
- return LLSelectMgr::getInstance()->getSelection()->
- contains( object, SELECT_ALL_TES );
- }
-}
-
-class LLObjectMute : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- if (!object) return true;
-
- LLUUID id;
- std::string name;
- LLMute::EType type;
- LLVOAvatar* avatar = find_avatar_from_object(object);
- if (avatar)
- {
- id = avatar->getID();
-
- LLNameValue *firstname = avatar->getNVPair("FirstName");
- LLNameValue *lastname = avatar->getNVPair("LastName");
- if (firstname && lastname)
- {
- name = LLCacheName::buildFullName(
- firstname->getString(), lastname->getString());
- }
-
- type = LLMute::AGENT;
- }
- else
- {
- // it's an object
- id = object->getID();
-
- LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
- if (node)
- {
- name = node->mName;
- }
-
- type = LLMute::OBJECT;
- }
-
- LLMute mute(id, name, type);
- if (LLMuteList::getInstance()->isMuted(mute.mID))
- {
- LLMuteList::getInstance()->remove(mute);
- }
- else
- {
- LLMuteList::getInstance()->add(mute);
- LLPanelBlockedList::showPanelAndSelect(mute.mID);
- }
-
- return true;
- }
-};
-
-bool handle_go_to()
-{
- // try simulator autopilot
- std::vector<std::string> strings;
- std::string val;
- LLVector3d pos = LLToolPie::getInstance()->getPick().mPosGlobal;
- val = llformat("%g", pos.mdV[VX]);
- strings.push_back(val);
- val = llformat("%g", pos.mdV[VY]);
- strings.push_back(val);
- val = llformat("%g", pos.mdV[VZ]);
- strings.push_back(val);
- send_generic_message("autopilot", strings);
-
- LLViewerParcelMgr::getInstance()->deselectLand();
-
- if (isAgentAvatarValid() && !gSavedSettings.getBOOL("AutoPilotLocksCamera"))
- {
- gAgentCamera.setFocusGlobal(gAgentCamera.getFocusTargetGlobal(), gAgentAvatarp->getID());
- }
- else
- {
- // Snap camera back to behind avatar
- gAgentCamera.setFocusOnAvatar(TRUE, ANIMATE);
- }
-
- // Could be first use
- //LLFirstUse::useGoTo();
- return true;
-}
-
-class LLGoToObject : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- return handle_go_to();
- }
-};
-
-class LLAvatarReportAbuse : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
- if(avatar)
- {
- LLFloaterReporter::showFromObject(avatar->getID());
- }
- return true;
- }
-};
-
-
-//---------------------------------------------------------------------------
-// Parcel freeze, eject, etc.
-//---------------------------------------------------------------------------
-bool callback_freeze(const LLSD& notification, const LLSD& response)
-{
- LLUUID avatar_id = notification["payload"]["avatar_id"].asUUID();
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
-
- if (0 == option || 1 == option)
- {
- U32 flags = 0x0;
- if (1 == option)
- {
- // unfreeze
- flags |= 0x1;
- }
-
- LLMessageSystem* msg = gMessageSystem;
- LLViewerObject* avatar = gObjectList.findObject(avatar_id);
-
- if (avatar)
- {
- msg->newMessage("FreezeUser");
- msg->nextBlock("AgentData");
- msg->addUUID("AgentID", gAgent.getID());
- msg->addUUID("SessionID", gAgent.getSessionID());
- msg->nextBlock("Data");
- msg->addUUID("TargetID", avatar_id );
- msg->addU32("Flags", flags );
- msg->sendReliable( avatar->getRegion()->getHost() );
- }
- }
- return false;
-}
-
-
-void handle_avatar_freeze(const LLSD& avatar_id)
-{
- // Use avatar_id if available, otherwise default to right-click avatar
- LLVOAvatar* avatar = NULL;
- if (avatar_id.asUUID().notNull())
- {
- avatar = find_avatar_from_object(avatar_id.asUUID());
- }
- else
- {
- avatar = find_avatar_from_object(
- LLSelectMgr::getInstance()->getSelection()->getPrimaryObject());
- }
-
- if( avatar )
- {
- std::string fullname = avatar->getFullname();
- LLSD payload;
- payload["avatar_id"] = avatar->getID();
-
- if (!fullname.empty())
- {
- LLSD args;
- args["AVATAR_NAME"] = fullname;
- LLNotificationsUtil::add("FreezeAvatarFullname",
- args,
- payload,
- callback_freeze);
- }
- else
- {
- LLNotificationsUtil::add("FreezeAvatar",
- LLSD(),
- payload,
- callback_freeze);
- }
- }
-}
-
-class LLAvatarVisibleDebug : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- return gAgent.isGodlike();
- }
-};
-
-class LLAvatarDebug : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
- if( avatar )
- {
- if (avatar->isSelf())
- {
- ((LLVOAvatarSelf *)avatar)->dumpLocalTextures();
- }
- llinfos << "Dumping temporary asset data to simulator logs for avatar " << avatar->getID() << llendl;
- std::vector<std::string> strings;
- strings.push_back(avatar->getID().asString());
- LLUUID invoice;
- send_generic_message("dumptempassetdata", strings, invoice);
- LLFloaterReg::showInstance( "avatar_textures", LLSD(avatar->getID()) );
- }
- return true;
- }
-};
-
-bool callback_eject(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- if (2 == option)
- {
- // Cancel button.
- return false;
- }
- LLUUID avatar_id = notification["payload"]["avatar_id"].asUUID();
- bool ban_enabled = notification["payload"]["ban_enabled"].asBoolean();
-
- if (0 == option)
- {
- // Eject button
- LLMessageSystem* msg = gMessageSystem;
- LLViewerObject* avatar = gObjectList.findObject(avatar_id);
-
- if (avatar)
- {
- U32 flags = 0x0;
- msg->newMessage("EjectUser");
- msg->nextBlock("AgentData");
- msg->addUUID("AgentID", gAgent.getID() );
- msg->addUUID("SessionID", gAgent.getSessionID() );
- msg->nextBlock("Data");
- msg->addUUID("TargetID", avatar_id );
- msg->addU32("Flags", flags );
- msg->sendReliable( avatar->getRegion()->getHost() );
- }
- }
- else if (ban_enabled)
- {
- // This is tricky. It is similar to say if it is not an 'Eject' button,
- // and it is also not an 'Cancle' button, and ban_enabled==ture,
- // it should be the 'Eject and Ban' button.
- LLMessageSystem* msg = gMessageSystem;
- LLViewerObject* avatar = gObjectList.findObject(avatar_id);
-
- if (avatar)
- {
- U32 flags = 0x1;
- msg->newMessage("EjectUser");
- msg->nextBlock("AgentData");
- msg->addUUID("AgentID", gAgent.getID() );
- msg->addUUID("SessionID", gAgent.getSessionID() );
- msg->nextBlock("Data");
- msg->addUUID("TargetID", avatar_id );
- msg->addU32("Flags", flags );
- msg->sendReliable( avatar->getRegion()->getHost() );
- }
- }
- return false;
-}
-
-void handle_avatar_eject(const LLSD& avatar_id)
-{
- // Use avatar_id if available, otherwise default to right-click avatar
- LLVOAvatar* avatar = NULL;
- if (avatar_id.asUUID().notNull())
- {
- avatar = find_avatar_from_object(avatar_id.asUUID());
- }
- else
- {
- avatar = find_avatar_from_object(
- LLSelectMgr::getInstance()->getSelection()->getPrimaryObject());
- }
-
- if( avatar )
- {
- LLSD payload;
- payload["avatar_id"] = avatar->getID();
- std::string fullname = avatar->getFullname();
-
- const LLVector3d& pos = avatar->getPositionGlobal();
- LLParcel* parcel = LLViewerParcelMgr::getInstance()->selectParcelAt(pos)->getParcel();
-
- if (LLViewerParcelMgr::getInstance()->isParcelOwnedByAgent(parcel,GP_LAND_MANAGE_BANNED))
- {
- payload["ban_enabled"] = true;
- if (!fullname.empty())
- {
- LLSD args;
- args["AVATAR_NAME"] = fullname;
- LLNotificationsUtil::add("EjectAvatarFullname",
- args,
- payload,
- callback_eject);
- }
- else
- {
- LLNotificationsUtil::add("EjectAvatarFullname",
- LLSD(),
- payload,
- callback_eject);
- }
- }
- else
- {
- payload["ban_enabled"] = false;
- if (!fullname.empty())
- {
- LLSD args;
- args["AVATAR_NAME"] = fullname;
- LLNotificationsUtil::add("EjectAvatarFullnameNoBan",
- args,
- payload,
- callback_eject);
- }
- else
- {
- LLNotificationsUtil::add("EjectAvatarNoBan",
- LLSD(),
- payload,
- callback_eject);
- }
- }
- }
-}
-
-bool enable_freeze_eject(const LLSD& avatar_id)
-{
- // Use avatar_id if available, otherwise default to right-click avatar
- LLVOAvatar* avatar = NULL;
- if (avatar_id.asUUID().notNull())
- {
- avatar = find_avatar_from_object(avatar_id.asUUID());
- }
- else
- {
- avatar = find_avatar_from_object(
- LLSelectMgr::getInstance()->getSelection()->getPrimaryObject());
- }
- if (!avatar) return false;
-
- // Gods can always freeze
- if (gAgent.isGodlike()) return true;
-
- // Estate owners / managers can freeze
- // Parcel owners can also freeze
- const LLVector3& pos = avatar->getPositionRegion();
- const LLVector3d& pos_global = avatar->getPositionGlobal();
- LLParcel* parcel = LLViewerParcelMgr::getInstance()->selectParcelAt(pos_global)->getParcel();
- LLViewerRegion* region = avatar->getRegion();
- if (!region) return false;
-
- bool new_value = region->isOwnedSelf(pos);
- if (!new_value || region->isOwnedGroup(pos))
- {
- new_value = LLViewerParcelMgr::getInstance()->isParcelOwnedByAgent(parcel,GP_LAND_ADMIN);
- }
- return new_value;
-}
-
-
-void login_done(S32 which, void *user)
-{
- llinfos << "Login done " << which << llendl;
-
- LLPanelLogin::closePanel();
-}
-
-
-bool callback_leave_group(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- if (option == 0)
- {
- LLMessageSystem *msg = gMessageSystem;
-
- msg->newMessageFast(_PREHASH_LeaveGroupRequest);
- msg->nextBlockFast(_PREHASH_AgentData);
- msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID() );
- msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- msg->nextBlockFast(_PREHASH_GroupData);
- msg->addUUIDFast(_PREHASH_GroupID, gAgent.getGroupID() );
- gAgent.sendReliableMessage();
- }
- return false;
-}
-
-void append_aggregate(std::string& string, const LLAggregatePermissions& ag_perm, PermissionBit bit, const char* txt)
-{
- LLAggregatePermissions::EValue val = ag_perm.getValue(bit);
- std::string buffer;
- switch(val)
- {
- case LLAggregatePermissions::AP_NONE:
- buffer = llformat( "* %s None\n", txt);
- break;
- case LLAggregatePermissions::AP_SOME:
- buffer = llformat( "* %s Some\n", txt);
- break;
- case LLAggregatePermissions::AP_ALL:
- buffer = llformat( "* %s All\n", txt);
- break;
- case LLAggregatePermissions::AP_EMPTY:
- default:
- break;
- }
- string.append(buffer);
-}
-
-bool enable_buy_object()
-{
- // In order to buy, there must only be 1 purchaseable object in
- // the selection manger.
- if(LLSelectMgr::getInstance()->getSelection()->getRootObjectCount() != 1) return false;
- LLViewerObject* obj = NULL;
- LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
- if(node)
- {
- obj = node->getObject();
- if(!obj) return false;
-
- if( for_sale_selection(node) )
- {
- // *NOTE: Is this needed? This checks to see if anyone owns the
- // object, dating back to when we had "public" objects owned by
- // no one. JC
- if(obj->permAnyOwner()) return true;
- }
- }
- return false;
-}
-
-// Note: This will only work if the selected object's data has been
-// received by the viewer and cached in the selection manager.
-void handle_buy_object(LLSaleInfo sale_info)
-{
- if(!LLSelectMgr::getInstance()->selectGetAllRootsValid())
- {
- LLNotificationsUtil::add("UnableToBuyWhileDownloading");
- return;
- }
-
- LLUUID owner_id;
- std::string owner_name;
- BOOL owners_identical = LLSelectMgr::getInstance()->selectGetOwner(owner_id, owner_name);
- if (!owners_identical)
- {
- LLNotificationsUtil::add("CannotBuyObjectsFromDifferentOwners");
- return;
- }
-
- LLPermissions perm;
- BOOL valid = LLSelectMgr::getInstance()->selectGetPermissions(perm);
- LLAggregatePermissions ag_perm;
- valid &= LLSelectMgr::getInstance()->selectGetAggregatePermissions(ag_perm);
- if(!valid || !sale_info.isForSale() || !perm.allowTransferTo(gAgent.getID()))
- {
- LLNotificationsUtil::add("ObjectNotForSale");
- return;
- }
-
- LLFloaterBuy::show(sale_info);
-}
-
-
-void handle_buy_contents(LLSaleInfo sale_info)
-{
- LLFloaterBuyContents::show(sale_info);
-}
-
-void handle_region_dump_temp_asset_data(void*)
-{
- llinfos << "Dumping temporary asset data to simulator logs" << llendl;
- std::vector<std::string> strings;
- LLUUID invoice;
- send_generic_message("dumptempassetdata", strings, invoice);
-}
-
-void handle_region_clear_temp_asset_data(void*)
-{
- llinfos << "Clearing temporary asset data" << llendl;
- std::vector<std::string> strings;
- LLUUID invoice;
- send_generic_message("cleartempassetdata", strings, invoice);
-}
-
-void handle_region_dump_settings(void*)
-{
- LLViewerRegion* regionp = gAgent.getRegion();
- if (regionp)
- {
- llinfos << "Damage: " << (regionp->getAllowDamage() ? "on" : "off") << llendl;
- llinfos << "Landmark: " << (regionp->getAllowLandmark() ? "on" : "off") << llendl;
- llinfos << "SetHome: " << (regionp->getAllowSetHome() ? "on" : "off") << llendl;
- llinfos << "ResetHome: " << (regionp->getResetHomeOnTeleport() ? "on" : "off") << llendl;
- llinfos << "SunFixed: " << (regionp->getSunFixed() ? "on" : "off") << llendl;
- llinfos << "BlockFly: " << (regionp->getBlockFly() ? "on" : "off") << llendl;
- llinfos << "AllowP2P: " << (regionp->getAllowDirectTeleport() ? "on" : "off") << llendl;
- llinfos << "Water: " << (regionp->getWaterHeight()) << llendl;
- }
-}
-
-void handle_dump_group_info(void *)
-{
- gAgent.dumpGroupInfo();
-}
-
-void handle_dump_capabilities_info(void *)
-{
- LLViewerRegion* regionp = gAgent.getRegion();
- if (regionp)
- {
- regionp->logActiveCapabilities();
- }
-}
-
-void handle_dump_region_object_cache(void*)
-{
- LLViewerRegion* regionp = gAgent.getRegion();
- if (regionp)
- {
- regionp->dumpCache();
- }
-}
-
-void handle_dump_focus()
-{
- LLUICtrl *ctrl = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
-
- llinfos << "Keyboard focus " << (ctrl ? ctrl->getName() : "(none)") << llendl;
-}
-
-class LLSelfStandUp : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gAgent.standUp();
- return true;
- }
-};
-
-bool enable_standup_self()
-{
- return isAgentAvatarValid() && gAgentAvatarp->isSitting();
-}
-
-class LLSelfSitDown : public view_listener_t
- {
- bool handleEvent(const LLSD& userdata)
- {
- gAgent.sitDown();
- return true;
- }
- };
-
-bool enable_sitdown_self()
-{
- return isAgentAvatarValid() && !gAgentAvatarp->isSitting() && !gAgent.getFlying();
-}
-
-// Used from the login screen to aid in UI work on side tray
-void handle_show_side_tray()
-{
- LLSideTray* side_tray = LLSideTray::getInstance();
- LLView* root = gViewerWindow->getRootView();
- // automatically removes and re-adds if there already
- root->addChild(side_tray);
-}
-
-// Toggle one of "People" panel tabs in side tray.
-class LLTogglePanelPeopleTab : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string panel_name = userdata.asString();
-
- LLSD param;
- param["people_panel_tab_name"] = panel_name;
-
- static LLPanel* friends_panel = NULL;
- static LLPanel* groups_panel = NULL;
- static LLPanel* nearby_panel = NULL;
-
- if (panel_name == "friends_panel")
- {
- return togglePeoplePanel(friends_panel, panel_name, param);
- }
- else if (panel_name == "groups_panel")
- {
- return togglePeoplePanel(groups_panel, panel_name, param);
- }
- else if (panel_name == "nearby_panel")
- {
- return togglePeoplePanel(nearby_panel, panel_name, param);
- }
- else
- {
- return false;
- }
- }
-
- static bool togglePeoplePanel(LLPanel* &panel, const std::string& panel_name, const LLSD& param)
- {
- if(!panel)
- {
- panel = LLSideTray::getInstance()->getPanel(panel_name);
- if(!panel)
- return false;
- }
-
- LLSideTray::getInstance()->togglePanel(panel, "panel_people", param);
-
- return true;
- }
-};
-
-BOOL check_admin_override(void*)
-{
- return gAgent.getAdminOverride();
-}
-
-void handle_admin_override_toggle(void*)
-{
- gAgent.setAdminOverride(!gAgent.getAdminOverride());
-
- // The above may have affected which debug menus are visible
- show_debug_menus();
-}
-
-void handle_god_mode(void*)
-{
- gAgent.requestEnterGodMode();
-}
-
-void handle_leave_god_mode(void*)
-{
- gAgent.requestLeaveGodMode();
-}
-
-void set_god_level(U8 god_level)
-{
- U8 old_god_level = gAgent.getGodLevel();
- gAgent.setGodLevel( god_level );
- LLViewerParcelMgr::getInstance()->notifyObservers();
-
- // God mode changes region visibility
- LLWorldMap::getInstance()->reloadItems(true);
-
- // inventory in items may change in god mode
- gObjectList.dirtyAllObjectInventory();
-
- if(gViewerWindow)
- {
- gViewerWindow->setMenuBackgroundColor(god_level > GOD_NOT,
- LLGridManager::getInstance()->isInProductionGrid());
- }
-
- LLSD args;
- if(god_level > GOD_NOT)
- {
- args["LEVEL"] = llformat("%d",(S32)god_level);
- LLNotificationsUtil::add("EnteringGodMode", args);
- }
- else
- {
- args["LEVEL"] = llformat("%d",(S32)old_god_level);
- LLNotificationsUtil::add("LeavingGodMode", args);
- }
-
- // changing god-level can affect which menus we see
- show_debug_menus();
-
- // changing god-level can invalidate search results
- LLFloaterSearch *search = dynamic_cast<LLFloaterSearch*>(LLFloaterReg::getInstance("search"));
- if (search)
- {
- search->godLevelChanged(god_level);
- }
-}
-
-#ifdef TOGGLE_HACKED_GODLIKE_VIEWER
-void handle_toggle_hacked_godmode(void*)
-{
- gHackGodmode = !gHackGodmode;
- set_god_level(gHackGodmode ? GOD_MAINTENANCE : GOD_NOT);
-}
-
-BOOL check_toggle_hacked_godmode(void*)
-{
- return gHackGodmode;
-}
-
-bool enable_toggle_hacked_godmode(void*)
-{
- return !LLGridManager::getInstance()->isInProductionGrid();
-}
-#endif
-
-void process_grant_godlike_powers(LLMessageSystem* msg, void**)
-{
- LLUUID agent_id;
- msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, agent_id);
- LLUUID session_id;
- msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_SessionID, session_id);
- if((agent_id == gAgent.getID()) && (session_id == gAgent.getSessionID()))
- {
- U8 god_level;
- msg->getU8Fast(_PREHASH_GrantData, _PREHASH_GodLevel, god_level);
- set_god_level(god_level);
- }
- else
- {
- llwarns << "Grant godlike for wrong agent " << agent_id << llendl;
- }
-}
-
-/*
-class LLHaveCallingcard : public LLInventoryCollectFunctor
-{
-public:
- LLHaveCallingcard(const LLUUID& agent_id);
- virtual ~LLHaveCallingcard() {}
- virtual bool operator()(LLInventoryCategory* cat,
- LLInventoryItem* item);
- BOOL isThere() const { return mIsThere;}
-protected:
- LLUUID mID;
- BOOL mIsThere;
-};
-
-LLHaveCallingcard::LLHaveCallingcard(const LLUUID& agent_id) :
- mID(agent_id),
- mIsThere(FALSE)
-{
-}
-
-bool LLHaveCallingcard::operator()(LLInventoryCategory* cat,
- LLInventoryItem* item)
-{
- if(item)
- {
- if((item->getType() == LLAssetType::AT_CALLINGCARD)
- && (item->getCreatorUUID() == mID))
- {
- mIsThere = TRUE;
- }
- }
- return FALSE;
-}
-*/
-
-BOOL is_agent_mappable(const LLUUID& agent_id)
-{
- const LLRelationship* buddy_info = NULL;
- bool is_friend = LLAvatarActions::isFriend(agent_id);
-
- if (is_friend)
- buddy_info = LLAvatarTracker::instance().getBuddyInfo(agent_id);
-
- return (buddy_info &&
- buddy_info->isOnline() &&
- buddy_info->isRightGrantedFrom(LLRelationship::GRANT_MAP_LOCATION)
- );
-}
-
-
-// Enable a menu item when you don't have someone's card.
-class LLAvatarEnableAddFriend : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar* avatar = find_avatar_from_object(LLSelectMgr::getInstance()->getSelection()->getPrimaryObject());
- bool new_value = avatar && !LLAvatarActions::isFriend(avatar->getID());
- return new_value;
- }
-};
-
-void request_friendship(const LLUUID& dest_id)
-{
- LLViewerObject* dest = gObjectList.findObject(dest_id);
- if(dest && dest->isAvatar())
- {
- std::string full_name;
- LLNameValue* nvfirst = dest->getNVPair("FirstName");
- LLNameValue* nvlast = dest->getNVPair("LastName");
- if(nvfirst && nvlast)
- {
- full_name = LLCacheName::buildFullName(
- nvfirst->getString(), nvlast->getString());
- }
- if (!full_name.empty())
- {
- LLAvatarActions::requestFriendshipDialog(dest_id, full_name);
- }
- else
- {
- LLNotificationsUtil::add("CantOfferFriendship");
- }
- }
-}
-
-
-class LLEditEnableCustomizeAvatar : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gAgentWearables.areWearablesLoaded();
- return new_value;
- }
-};
-
-class LLEnableEditShape : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- return gAgentWearables.isWearableModifiable(LLWearableType::WT_SHAPE, 0);
- }
-};
-
-bool is_object_sittable()
-{
- LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
-
- if (object && object->getPCode() == LL_PCODE_VOLUME)
- {
- return true;
- }
- else
- {
- return false;
- }
-}
-
-
-// only works on pie menu
-void handle_object_sit_or_stand()
-{
- LLPickInfo pick = LLToolPie::getInstance()->getPick();
- LLViewerObject *object = pick.getObject();;
- if (!object || pick.mPickType == LLPickInfo::PICK_FLORA)
- {
- return;
- }
-
- if (sitting_on_selection())
- {
- gAgent.standUp();
- return;
- }
-
- // get object selection offset
-
- if (object && object->getPCode() == LL_PCODE_VOLUME)
- {
-
- gMessageSystem->newMessageFast(_PREHASH_AgentRequestSit);
- gMessageSystem->nextBlockFast(_PREHASH_AgentData);
- gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
- gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- gMessageSystem->nextBlockFast(_PREHASH_TargetObject);
- gMessageSystem->addUUIDFast(_PREHASH_TargetID, object->mID);
- gMessageSystem->addVector3Fast(_PREHASH_Offset, pick.mObjectOffset);
-
- object->getRegion()->sendReliableMessage();
- }
-}
-
-void near_sit_down_point(BOOL success, void *)
-{
- if (success)
- {
- gAgent.setFlying(FALSE);
- gAgent.setControlFlags(AGENT_CONTROL_SIT_ON_GROUND);
-
- // Might be first sit
- //LLFirstUse::useSit();
- }
-}
-
-class LLLandSit : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gAgent.standUp();
- LLViewerParcelMgr::getInstance()->deselectLand();
-
- LLVector3d posGlobal = LLToolPie::getInstance()->getPick().mPosGlobal;
-
- LLQuaternion target_rot;
- if (isAgentAvatarValid())
- {
- target_rot = gAgentAvatarp->getRotation();
- }
- else
- {
- target_rot = gAgent.getFrameAgent().getQuaternion();
- }
- gAgent.startAutoPilotGlobal(posGlobal, "Sit", &target_rot, near_sit_down_point, NULL, 0.7f);
- return true;
- }
-};
-
-//-------------------------------------------------------------------
-// Help menu functions
-//-------------------------------------------------------------------
-
-//
-// Major mode switching
-//
-void reset_view_final( BOOL proceed );
-
-void handle_reset_view()
-{
- if (gAgentCamera.cameraCustomizeAvatar())
- {
- // switching to outfit selector should automagically save any currently edited wearable
- LLSideTray::getInstance()->showPanel("sidepanel_appearance", LLSD().with("type", "my_outfits"));
- }
-
- gAgentCamera.switchCameraPreset(CAMERA_PRESET_REAR_VIEW);
- reset_view_final( TRUE );
- LLFloaterCamera::resetCameraMode();
-}
-
-class LLViewResetView : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- handle_reset_view();
- return true;
- }
-};
-
-// Note: extra parameters allow this function to be called from dialog.
-void reset_view_final( BOOL proceed )
-{
- if( !proceed )
- {
- return;
- }
-
- gAgentCamera.resetView(TRUE, TRUE);
- gAgentCamera.setLookAt(LOOKAT_TARGET_CLEAR);
-}
-
-class LLViewLookAtLastChatter : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gAgentCamera.lookAtLastChat();
- return true;
- }
-};
-
-class LLViewMouselook : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if (!gAgentCamera.cameraMouselook())
- {
- gAgentCamera.changeCameraToMouselook();
- }
- else
- {
- gAgentCamera.changeCameraToDefault();
- }
- return true;
- }
-};
-
-class LLViewDefaultUISize : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gSavedSettings.setF32("UIScaleFactor", 1.0f);
- gSavedSettings.setBOOL("UIAutoScale", FALSE);
- gViewerWindow->reshape(gViewerWindow->getWindowWidthRaw(), gViewerWindow->getWindowHeightRaw());
- return true;
- }
-};
-
-class LLEditDuplicate : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if(LLEditMenuHandler::gEditMenuHandler)
- {
- LLEditMenuHandler::gEditMenuHandler->duplicate();
- }
- return true;
- }
-};
-
-class LLEditEnableDuplicate : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canDuplicate();
- return new_value;
- }
-};
-
-void handle_duplicate_in_place(void*)
-{
- llinfos << "handle_duplicate_in_place" << llendl;
-
- LLVector3 offset(0.f, 0.f, 0.f);
- LLSelectMgr::getInstance()->selectDuplicate(offset, TRUE);
-}
-
-/* dead code 30-apr-2008
-void handle_deed_object_to_group(void*)
-{
- LLUUID group_id;
-
- LLSelectMgr::getInstance()->selectGetGroup(group_id);
- LLSelectMgr::getInstance()->sendOwner(LLUUID::null, group_id, FALSE);
- LLViewerStats::getInstance()->incStat(LLViewerStats::ST_RELEASE_COUNT);
-}
-
-BOOL enable_deed_object_to_group(void*)
-{
- if(LLSelectMgr::getInstance()->getSelection()->isEmpty()) return FALSE;
- LLPermissions perm;
- LLUUID group_id;
-
- if (LLSelectMgr::getInstance()->selectGetGroup(group_id) &&
- gAgent.hasPowerInGroup(group_id, GP_OBJECT_DEED) &&
- LLSelectMgr::getInstance()->selectGetPermissions(perm) &&
- perm.deedToGroup(gAgent.getID(), group_id))
- {
- return TRUE;
- }
- return FALSE;
-}
-
-*/
-
-
-/*
- * No longer able to support viewer side manipulations in this way
- *
-void god_force_inv_owner_permissive(LLViewerObject* object,
- LLInventoryObject::object_list_t* inventory,
- S32 serial_num,
- void*)
-{
- typedef std::vector<LLPointer<LLViewerInventoryItem> > item_array_t;
- item_array_t items;
-
- LLInventoryObject::object_list_t::const_iterator inv_it = inventory->begin();
- LLInventoryObject::object_list_t::const_iterator inv_end = inventory->end();
- for ( ; inv_it != inv_end; ++inv_it)
- {
- if(((*inv_it)->getType() != LLAssetType::AT_CATEGORY))
- {
- LLInventoryObject* obj = *inv_it;
- LLPointer<LLViewerInventoryItem> new_item = new LLViewerInventoryItem((LLViewerInventoryItem*)obj);
- LLPermissions perm(new_item->getPermissions());
- perm.setMaskBase(PERM_ALL);
- perm.setMaskOwner(PERM_ALL);
- new_item->setPermissions(perm);
- items.push_back(new_item);
- }
- }
- item_array_t::iterator end = items.end();
- item_array_t::iterator it;
- for(it = items.begin(); it != end; ++it)
- {
- // since we have the inventory item in the callback, it should not
- // invalidate iteration through the selection manager.
- object->updateInventory((*it), TASK_INVENTORY_ITEM_KEY, false);
- }
-}
-*/
-
-void handle_object_owner_permissive(void*)
-{
- // only send this if they're a god.
- if(gAgent.isGodlike())
- {
- // do the objects.
- LLSelectMgr::getInstance()->selectionSetObjectPermissions(PERM_BASE, TRUE, PERM_ALL, TRUE);
- LLSelectMgr::getInstance()->selectionSetObjectPermissions(PERM_OWNER, TRUE, PERM_ALL, TRUE);
- }
-}
-
-void handle_object_owner_self(void*)
-{
- // only send this if they're a god.
- if(gAgent.isGodlike())
- {
- LLSelectMgr::getInstance()->sendOwner(gAgent.getID(), gAgent.getGroupID(), TRUE);
- }
-}
-
-// Shortcut to set owner permissions to not editable.
-void handle_object_lock(void*)
-{
- LLSelectMgr::getInstance()->selectionSetObjectPermissions(PERM_OWNER, FALSE, PERM_MODIFY);
-}
-
-void handle_object_asset_ids(void*)
-{
- // only send this if they're a god.
- if (gAgent.isGodlike())
- {
- LLSelectMgr::getInstance()->sendGodlikeRequest("objectinfo", "assetids");
- }
-}
-
-void handle_force_parcel_owner_to_me(void*)
-{
- LLViewerParcelMgr::getInstance()->sendParcelGodForceOwner( gAgent.getID() );
-}
-
-void handle_force_parcel_to_content(void*)
-{
- LLViewerParcelMgr::getInstance()->sendParcelGodForceToContent();
-}
-
-void handle_claim_public_land(void*)
-{
- if (LLViewerParcelMgr::getInstance()->getSelectionRegion() != gAgent.getRegion())
- {
- LLNotificationsUtil::add("ClaimPublicLand");
- return;
- }
-
- LLVector3d west_south_global;
- LLVector3d east_north_global;
- LLViewerParcelMgr::getInstance()->getSelection(west_south_global, east_north_global);
- LLVector3 west_south = gAgent.getPosAgentFromGlobal(west_south_global);
- LLVector3 east_north = gAgent.getPosAgentFromGlobal(east_north_global);
-
- LLMessageSystem* msg = gMessageSystem;
- msg->newMessage("GodlikeMessage");
- msg->nextBlock("AgentData");
- msg->addUUID("AgentID", gAgent.getID());
- msg->addUUID("SessionID", gAgent.getSessionID());
- msg->addUUIDFast(_PREHASH_TransactionID, LLUUID::null); //not used
- msg->nextBlock("MethodData");
- msg->addString("Method", "claimpublicland");
- msg->addUUID("Invoice", LLUUID::null);
- std::string buffer;
- buffer = llformat( "%f", west_south.mV[VX]);
- msg->nextBlock("ParamList");
- msg->addString("Parameter", buffer);
- buffer = llformat( "%f", west_south.mV[VY]);
- msg->nextBlock("ParamList");
- msg->addString("Parameter", buffer);
- buffer = llformat( "%f", east_north.mV[VX]);
- msg->nextBlock("ParamList");
- msg->addString("Parameter", buffer);
- buffer = llformat( "%f", east_north.mV[VY]);
- msg->nextBlock("ParamList");
- msg->addString("Parameter", buffer);
- gAgent.sendReliableMessage();
-}
-
-
-
-// HACK for easily testing new avatar geometry
-void handle_god_request_avatar_geometry(void *)
-{
- if (gAgent.isGodlike())
- {
- LLSelectMgr::getInstance()->sendGodlikeRequest("avatar toggle", "");
- }
-}
-
-
-void derez_objects(EDeRezDestination dest, const LLUUID& dest_id)
-{
- if(gAgentCamera.cameraMouselook())
- {
- gAgentCamera.changeCameraToDefault();
- }
- //gInventoryView->setPanelOpen(TRUE);
-
- std::string error;
- LLDynamicArray<LLViewerObject*> derez_objects;
-
- // Check conditions that we can't deal with, building a list of
- // everything that we'll actually be derezzing.
- LLViewerRegion* first_region = NULL;
- for (LLObjectSelection::valid_root_iterator iter = LLSelectMgr::getInstance()->getSelection()->valid_root_begin();
- iter != LLSelectMgr::getInstance()->getSelection()->valid_root_end(); iter++)
- {
- LLSelectNode* node = *iter;
- LLViewerObject* object = node->getObject();
- LLViewerRegion* region = object->getRegion();
- if (!first_region)
- {
- first_region = region;
- }
- else
- {
- if(region != first_region)
- {
- // Derez doesn't work at all if the some of the objects
- // are in regions besides the first object selected.
-
- // ...crosses region boundaries
- error = "AcquireErrorObjectSpan";
- break;
- }
- }
- if (object->isAvatar())
- {
- // ...don't acquire avatars
- continue;
- }
-
- // If AssetContainers are being sent back, they will appear as
- // boxes in the owner's inventory.
- if (object->getNVPair("AssetContainer")
- && dest != DRD_RETURN_TO_OWNER)
- {
- // this object is an asset container, derez its contents, not it
- llwarns << "Attempt to derez deprecated AssetContainer object type not supported." << llendl;
- /*
- object->requestInventory(container_inventory_arrived,
- (void *)(BOOL)(DRD_TAKE_INTO_AGENT_INVENTORY == dest));
- */
- continue;
- }
- BOOL can_derez_current = FALSE;
- switch(dest)
- {
- case DRD_TAKE_INTO_AGENT_INVENTORY:
- case DRD_TRASH:
- if( (node->mPermissions->allowTransferTo(gAgent.getID()) && object->permModify())
- || (node->allowOperationOnNode(PERM_OWNER, GP_OBJECT_MANIPULATE)) )
- {
- can_derez_current = TRUE;
- }
- break;
-
- case DRD_RETURN_TO_OWNER:
- can_derez_current = TRUE;
- break;
-
- default:
- if((node->mPermissions->allowTransferTo(gAgent.getID())
- && object->permCopy())
- || gAgent.isGodlike())
- {
- can_derez_current = TRUE;
- }
- break;
- }
- if(can_derez_current)
- {
- derez_objects.put(object);
- }
- }
-
- // This constant is based on (1200 - HEADER_SIZE) / 4 bytes per
- // root. I lopped off a few (33) to provide a bit
- // pad. HEADER_SIZE is currently 67 bytes, most of which is UUIDs.
- // This gives us a maximum of 63500 root objects - which should
- // satisfy anybody.
- const S32 MAX_ROOTS_PER_PACKET = 250;
- const S32 MAX_PACKET_COUNT = 254;
- F32 packets = ceil((F32)derez_objects.count() / (F32)MAX_ROOTS_PER_PACKET);
- if(packets > (F32)MAX_PACKET_COUNT)
- {
- error = "AcquireErrorTooManyObjects";
- }
-
- if(error.empty() && derez_objects.count() > 0)
- {
- U8 d = (U8)dest;
- LLUUID tid;
- tid.generate();
- U8 packet_count = (U8)packets;
- S32 object_index = 0;
- S32 objects_in_packet = 0;
- LLMessageSystem* msg = gMessageSystem;
- for(U8 packet_number = 0;
- packet_number < packet_count;
- ++packet_number)
- {
- msg->newMessageFast(_PREHASH_DeRezObject);
- msg->nextBlockFast(_PREHASH_AgentData);
- msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
- msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- msg->nextBlockFast(_PREHASH_AgentBlock);
- msg->addUUIDFast(_PREHASH_GroupID, gAgent.getGroupID());
- msg->addU8Fast(_PREHASH_Destination, d);
- msg->addUUIDFast(_PREHASH_DestinationID, dest_id);
- msg->addUUIDFast(_PREHASH_TransactionID, tid);
- msg->addU8Fast(_PREHASH_PacketCount, packet_count);
- msg->addU8Fast(_PREHASH_PacketNumber, packet_number);
- objects_in_packet = 0;
- while((object_index < derez_objects.count())
- && (objects_in_packet++ < MAX_ROOTS_PER_PACKET))
-
- {
- LLViewerObject* object = derez_objects.get(object_index++);
- msg->nextBlockFast(_PREHASH_ObjectData);
- msg->addU32Fast(_PREHASH_ObjectLocalID, object->getLocalID());
- // VEFFECT: DerezObject
- LLHUDEffectSpiral* effectp = (LLHUDEffectSpiral*)LLHUDManager::getInstance()->createViewerEffect(LLHUDObject::LL_HUD_EFFECT_POINT, TRUE);
- effectp->setPositionGlobal(object->getPositionGlobal());
- effectp->setColor(LLColor4U(gAgent.getEffectColor()));
- }
- msg->sendReliable(first_region->getHost());
- }
- make_ui_sound("UISndObjectRezOut");
-
- // Busy count decremented by inventory update, so only increment
- // if will be causing an update.
- if (dest != DRD_RETURN_TO_OWNER)
- {
- gViewerWindow->getWindow()->incBusyCount();
- }
- }
- else if(!error.empty())
- {
- LLNotificationsUtil::add(error);
- }
-}
-
-void handle_take_copy()
-{
- if (LLSelectMgr::getInstance()->getSelection()->isEmpty()) return;
-
- const LLUUID category_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_OBJECT);
- derez_objects(DRD_ACQUIRE_TO_AGENT_INVENTORY, category_id);
-}
-
-// You can return an object to its owner if it is on your land.
-class LLObjectReturn : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if (LLSelectMgr::getInstance()->getSelection()->isEmpty()) return true;
-
- mObjectSelection = LLSelectMgr::getInstance()->getEditSelection();
-
- LLNotificationsUtil::add("ReturnToOwner", LLSD(), LLSD(), boost::bind(&LLObjectReturn::onReturnToOwner, this, _1, _2));
- return true;
- }
-
- bool onReturnToOwner(const LLSD& notification, const LLSD& response)
- {
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- if (0 == option)
- {
- // Ignore category ID for this derez destination.
- derez_objects(DRD_RETURN_TO_OWNER, LLUUID::null);
- }
-
- // drop reference to current selection
- mObjectSelection = NULL;
- return false;
- }
-
-protected:
- LLObjectSelectionHandle mObjectSelection;
-};
-
-
-// Allow return to owner if one or more of the selected items is
-// over land you own.
-class LLObjectEnableReturn : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if (LLSelectMgr::getInstance()->getSelection()->isEmpty())
- {
- // Do not enable if nothing selected
- return false;
- }
-#ifdef HACKED_GODLIKE_VIEWER
- bool new_value = true;
-#else
- bool new_value = false;
- if (gAgent.isGodlike())
- {
- new_value = true;
- }
- else
- {
- LLViewerRegion* region = gAgent.getRegion();
- if (region)
- {
- // Estate owners and managers can always return objects.
- if (region->canManageEstate())
- {
- new_value = true;
- }
- else
- {
- struct f : public LLSelectedObjectFunctor
- {
- virtual bool apply(LLViewerObject* obj)
- {
- return
- obj->permModify() ||
- obj->isReturnable();
- }
- } func;
- const bool firstonly = true;
- new_value = LLSelectMgr::getInstance()->getSelection()->applyToRootObjects(&func, firstonly);
- }
- }
- }
-#endif
- return new_value;
- }
-};
-
-void force_take_copy(void*)
-{
- if (LLSelectMgr::getInstance()->getSelection()->isEmpty()) return;
- const LLUUID category_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_OBJECT);
- derez_objects(DRD_FORCE_TO_GOD_INVENTORY, category_id);
-}
-
-void handle_take()
-{
- // we want to use the folder this was derezzed from if it's
- // available. Otherwise, derez to the normal place.
- if(LLSelectMgr::getInstance()->getSelection()->isEmpty())
- {
- return;
- }
-
- BOOL you_own_everything = TRUE;
- BOOL locked_but_takeable_object = FALSE;
- LLUUID category_id;
-
- for (LLObjectSelection::root_iterator iter = LLSelectMgr::getInstance()->getSelection()->root_begin();
- iter != LLSelectMgr::getInstance()->getSelection()->root_end(); iter++)
- {
- LLSelectNode* node = *iter;
- LLViewerObject* object = node->getObject();
- if(object)
- {
- if(!object->permYouOwner())
- {
- you_own_everything = FALSE;
- }
-
- if(!object->permMove())
- {
- locked_but_takeable_object = TRUE;
- }
- }
- if(node->mFolderID.notNull())
- {
- if(category_id.isNull())
- {
- category_id = node->mFolderID;
- }
- else if(category_id != node->mFolderID)
- {
- // we have found two potential destinations. break out
- // now and send to the default location.
- category_id.setNull();
- break;
- }
- }
- }
- if(category_id.notNull())
- {
- // there is an unambiguous destination. See if this agent has
- // such a location and it is not in the trash or library
- if(!gInventory.getCategory(category_id))
- {
- // nope, set to NULL.
- category_id.setNull();
- }
- if(category_id.notNull())
- {
- // check trash
- const LLUUID trash = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
- if(category_id == trash || gInventory.isObjectDescendentOf(category_id, trash))
- {
- category_id.setNull();
- }
-
- // check library
- if(gInventory.isObjectDescendentOf(category_id, gInventory.getLibraryRootFolderID()))
- {
- category_id.setNull();
- }
-
- }
- }
- if(category_id.isNull())
- {
- category_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_OBJECT);
- }
- LLSD payload;
- payload["folder_id"] = category_id;
-
- LLNotification::Params params("ConfirmObjectTakeLock");
- params.payload(payload);
- params.functor.function(confirm_take);
-
- if(locked_but_takeable_object ||
- !you_own_everything)
- {
- if(locked_but_takeable_object && you_own_everything)
- {
- params.name("ConfirmObjectTakeLock");
- }
- else if(!locked_but_takeable_object && !you_own_everything)
- {
- params.name("ConfirmObjectTakeNoOwn");
- }
- else
- {
- params.name("ConfirmObjectTakeLockNoOwn");
- }
-
- LLNotifications::instance().add(params);
- }
- else
- {
- LLNotifications::instance().forceResponse(params, 0);
- }
-}
-
-void handle_object_show_inspector()
-{
- LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
- LLViewerObject* objectp = selection->getFirstRootObject(TRUE);
- if (!objectp)
- {
- return;
- }
-
- LLSD params;
- params["object_id"] = objectp->getID();
- LLFloaterReg::showInstance("inspect_object", params);
-}
-
-void handle_avatar_show_inspector()
-{
- LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
- if(avatar)
- {
- LLSD params;
- params["avatar_id"] = avatar->getID();
- LLFloaterReg::showInstance("inspect_avatar", params);
- }
-}
-
-
-
-bool confirm_take(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- if(enable_take() && (option == 0))
- {
- derez_objects(DRD_TAKE_INTO_AGENT_INVENTORY, notification["payload"]["folder_id"].asUUID());
- }
- return false;
-}
-
-// You can take an item when it is public and transferrable, or when
-// you own it. We err on the side of enabling the item when at least
-// one item selected can be copied to inventory.
-BOOL enable_take()
-{
- if (sitting_on_selection())
- {
- return FALSE;
- }
-
- for (LLObjectSelection::valid_root_iterator iter = LLSelectMgr::getInstance()->getSelection()->valid_root_begin();
- iter != LLSelectMgr::getInstance()->getSelection()->valid_root_end(); iter++)
- {
- LLSelectNode* node = *iter;
- LLViewerObject* object = node->getObject();
- if (object->isAvatar())
- {
- // ...don't acquire avatars
- continue;
- }
-
-#ifdef HACKED_GODLIKE_VIEWER
- return TRUE;
-#else
-# ifdef TOGGLE_HACKED_GODLIKE_VIEWER
- if (!LLGridManager::getInstance()->isInProductionGrid()
- && gAgent.isGodlike())
- {
- return TRUE;
- }
-# endif
- if((node->mPermissions->allowTransferTo(gAgent.getID())
- && object->permModify())
- || (node->mPermissions->getOwner() == gAgent.getID()))
- {
- return TRUE;
- }
-#endif
- }
- return FALSE;
-}
-
-
-void handle_buy_or_take()
-{
- if (LLSelectMgr::getInstance()->getSelection()->isEmpty())
- {
- return;
- }
-
- if (is_selection_buy_not_take())
- {
- S32 total_price = selection_price();
-
- if (total_price <= gStatusBar->getBalance() || total_price == 0)
- {
- handle_buy();
- }
- else
- {
- LLStringUtil::format_map_t args;
- args["AMOUNT"] = llformat("%d", total_price);
- LLBuyCurrencyHTML::openCurrencyFloater( LLTrans::getString( "BuyingCosts", args ), total_price );
- }
- }
- else
- {
- handle_take();
- }
-}
-
-bool visible_buy_object()
-{
- return is_selection_buy_not_take() && enable_buy_object();
-}
-
-bool visible_take_object()
-{
- return !is_selection_buy_not_take() && enable_take();
-}
-
-bool tools_visible_buy_object()
-{
- return is_selection_buy_not_take();
-}
-
-bool tools_visible_take_object()
-{
- return !is_selection_buy_not_take();
-}
-
-class LLToolsEnableBuyOrTake : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool is_buy = is_selection_buy_not_take();
- bool new_value = is_buy ? enable_buy_object() : enable_take();
- return new_value;
- }
-};
-
-// This is a small helper function to determine if we have a buy or a
-// take in the selection. This method is to help with the aliasing
-// problems of putting buy and take in the same pie menu space. After
-// a fair amont of discussion, it was determined to prefer buy over
-// take. The reasoning follows from the fact that when users walk up
-// to buy something, they will click on one or more items. Thus, if
-// anything is for sale, it becomes a buy operation, and the server
-// will group all of the buy items, and copyable/modifiable items into
-// one package and give the end user as much as the permissions will
-// allow. If the user wanted to take something, they will select fewer
-// and fewer items until only 'takeable' items are left. The one
-// exception is if you own everything in the selection that is for
-// sale, in this case, you can't buy stuff from yourself, so you can
-// take it.
-// return value = TRUE if selection is a 'buy'.
-// FALSE if selection is a 'take'
-BOOL is_selection_buy_not_take()
-{
- for (LLObjectSelection::root_iterator iter = LLSelectMgr::getInstance()->getSelection()->root_begin();
- iter != LLSelectMgr::getInstance()->getSelection()->root_end(); iter++)
- {
- LLSelectNode* node = *iter;
- LLViewerObject* obj = node->getObject();
- if(obj && !(obj->permYouOwner()) && (node->mSaleInfo.isForSale()))
- {
- // you do not own the object and it is for sale, thus,
- // it's a buy
- return TRUE;
- }
- }
- return FALSE;
-}
-
-S32 selection_price()
-{
- S32 total_price = 0;
- for (LLObjectSelection::root_iterator iter = LLSelectMgr::getInstance()->getSelection()->root_begin();
- iter != LLSelectMgr::getInstance()->getSelection()->root_end(); iter++)
- {
- LLSelectNode* node = *iter;
- LLViewerObject* obj = node->getObject();
- if(obj && !(obj->permYouOwner()) && (node->mSaleInfo.isForSale()))
- {
- // you do not own the object and it is for sale.
- // Add its price.
- total_price += node->mSaleInfo.getSalePrice();
- }
- }
-
- return total_price;
-}
-/*
-bool callback_show_buy_currency(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- if (0 == option)
- {
- llinfos << "Loading page " << LLNotifications::instance().getGlobalString("BUY_CURRENCY_URL") << llendl;
- LLWeb::loadURL(LLNotifications::instance().getGlobalString("BUY_CURRENCY_URL"));
- }
- return false;
-}
-*/
-
-void show_buy_currency(const char* extra)
-{
- // Don't show currency web page for branded clients.
-/*
- std::ostringstream mesg;
- if (extra != NULL)
- {
- mesg << extra << "\n \n";
- }
- mesg << "Go to " << LLNotifications::instance().getGlobalString("BUY_CURRENCY_URL")<< "\nfor information on purchasing currency?";
-*/
- LLSD args;
- if (extra != NULL)
- {
- args["EXTRA"] = extra;
- }
- LLNotificationsUtil::add("PromptGoToCurrencyPage", args);//, LLSD(), callback_show_buy_currency);
-}
-
-void handle_buy()
-{
- if (LLSelectMgr::getInstance()->getSelection()->isEmpty()) return;
-
- LLSaleInfo sale_info;
- BOOL valid = LLSelectMgr::getInstance()->selectGetSaleInfo(sale_info);
- if (!valid) return;
-
- S32 price = sale_info.getSalePrice();
-
- if (price > 0 && price > gStatusBar->getBalance())
- {
- LLStringUtil::format_map_t args;
- args["AMOUNT"] = llformat("%d", price);
- LLBuyCurrencyHTML::openCurrencyFloater( LLTrans::getString("this_object_costs", args), price );
- return;
- }
-
- if (sale_info.getSaleType() == LLSaleInfo::FS_CONTENTS)
- {
- handle_buy_contents(sale_info);
- }
- else
- {
- handle_buy_object(sale_info);
- }
-}
-
-bool anyone_copy_selection(LLSelectNode* nodep)
-{
- bool perm_copy = (bool)(nodep->getObject()->permCopy());
- bool all_copy = (bool)(nodep->mPermissions->getMaskEveryone() & PERM_COPY);
- return perm_copy && all_copy;
-}
-
-bool for_sale_selection(LLSelectNode* nodep)
-{
- return nodep->mSaleInfo.isForSale()
- && nodep->mPermissions->getMaskOwner() & PERM_TRANSFER
- && (nodep->mPermissions->getMaskOwner() & PERM_COPY
- || nodep->mSaleInfo.getSaleType() != LLSaleInfo::FS_COPY);
-}
-
-BOOL sitting_on_selection()
-{
- LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
- if (!node)
- {
- return FALSE;
- }
-
- if (!node->mValid)
- {
- return FALSE;
- }
-
- LLViewerObject* root_object = node->getObject();
- if (!root_object)
- {
- return FALSE;
- }
-
- // Need to determine if avatar is sitting on this object
- if (!isAgentAvatarValid()) return FALSE;
-
- return (gAgentAvatarp->isSitting() && gAgentAvatarp->getRoot() == root_object);
-}
-
-class LLToolsSaveToInventory : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if(enable_save_into_inventory(NULL))
- {
- derez_objects(DRD_SAVE_INTO_AGENT_INVENTORY, LLUUID::null);
- }
- return true;
- }
-};
-
-class LLToolsSaveToObjectInventory : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
- if(node && (node->mValid) && (!node->mFromTaskID.isNull()))
- {
- // *TODO: check to see if the fromtaskid object exists.
- derez_objects(DRD_SAVE_INTO_TASK_INVENTORY, node->mFromTaskID);
- }
- return true;
- }
-};
-
-// Round the position of all root objects to the grid
-class LLToolsSnapObjectXY : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- F64 snap_size = (F64)gSavedSettings.getF32("GridResolution");
-
- for (LLObjectSelection::root_iterator iter = LLSelectMgr::getInstance()->getSelection()->root_begin();
- iter != LLSelectMgr::getInstance()->getSelection()->root_end(); iter++)
- {
- LLSelectNode* node = *iter;
- LLViewerObject* obj = node->getObject();
- if (obj->permModify())
- {
- LLVector3d pos_global = obj->getPositionGlobal();
- F64 round_x = fmod(pos_global.mdV[VX], snap_size);
- if (round_x < snap_size * 0.5)
- {
- // closer to round down
- pos_global.mdV[VX] -= round_x;
- }
- else
- {
- // closer to round up
- pos_global.mdV[VX] -= round_x;
- pos_global.mdV[VX] += snap_size;
- }
-
- F64 round_y = fmod(pos_global.mdV[VY], snap_size);
- if (round_y < snap_size * 0.5)
- {
- pos_global.mdV[VY] -= round_y;
- }
- else
- {
- pos_global.mdV[VY] -= round_y;
- pos_global.mdV[VY] += snap_size;
- }
-
- obj->setPositionGlobal(pos_global, FALSE);
- }
- }
- LLSelectMgr::getInstance()->sendMultipleUpdate(UPD_POSITION);
- return true;
- }
-};
-
-// Determine if the option to cycle between linked prims is shown
-class LLToolsEnableSelectNextPart : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = (gSavedSettings.getBOOL("EditLinkedParts") &&
- !LLSelectMgr::getInstance()->getSelection()->isEmpty());
- return new_value;
- }
-};
-
-// Cycle selection through linked children in selected object.
-// FIXME: Order of children list is not always the same as sim's idea of link order. This may confuse
-// resis. Need link position added to sim messages to address this.
-class LLToolsSelectNextPart : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- S32 object_count = LLSelectMgr::getInstance()->getSelection()->getObjectCount();
- if (gSavedSettings.getBOOL("EditLinkedParts") && object_count)
- {
- LLViewerObject* selected = LLSelectMgr::getInstance()->getSelection()->getFirstObject();
- if (selected && selected->getRootEdit())
- {
- bool fwd = (userdata.asString() == "next");
- bool prev = (userdata.asString() == "previous");
- bool ifwd = (userdata.asString() == "includenext");
- bool iprev = (userdata.asString() == "includeprevious");
- LLViewerObject* to_select = NULL;
- LLViewerObject::child_list_t children = selected->getRootEdit()->getChildren();
- children.push_front(selected->getRootEdit()); // need root in the list too
-
- for (LLViewerObject::child_list_t::iterator iter = children.begin(); iter != children.end(); ++iter)
- {
- if ((*iter)->isSelected())
- {
- if (object_count > 1 && (fwd || prev)) // multiple selection, find first or last selected if not include
- {
- to_select = *iter;
- if (fwd)
- {
- // stop searching if going forward; repeat to get last hit if backward
- break;
- }
- }
- else if ((object_count == 1) || (ifwd || iprev)) // single selection or include
- {
- if (fwd || ifwd)
- {
- ++iter;
- while (iter != children.end() && ((*iter)->isAvatar() || (ifwd && (*iter)->isSelected())))
- {
- ++iter; // skip sitting avatars and selected if include
- }
- }
- else // backward
- {
- iter = (iter == children.begin() ? children.end() : iter);
- --iter;
- while (iter != children.begin() && ((*iter)->isAvatar() || (iprev && (*iter)->isSelected())))
- {
- --iter; // skip sitting avatars and selected if include
- }
- }
- iter = (iter == children.end() ? children.begin() : iter);
- to_select = *iter;
- break;
- }
- }
- }
-
- if (to_select)
- {
- if (gFocusMgr.childHasKeyboardFocus(gFloaterTools))
- {
- gFocusMgr.setKeyboardFocus(NULL); // force edit toolbox to commit any changes
- }
- if (fwd || prev)
- {
- LLSelectMgr::getInstance()->deselectAll();
- }
- LLSelectMgr::getInstance()->selectObjectOnly(to_select);
- return true;
- }
- }
- }
- return true;
- }
-};
-
-class LLToolsStopAllAnimations : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gAgent.stopCurrentAnimations();
- return true;
- }
-};
-
-class LLToolsReleaseKeys : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gAgent.forceReleaseControls();
-
- return true;
- }
-};
-
-class LLToolsEnableReleaseKeys : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- return gAgent.anyControlGrabbed();
- }
-};
-
-
-class LLEditEnableCut : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canCut();
- return new_value;
- }
-};
-
-class LLEditCut : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if( LLEditMenuHandler::gEditMenuHandler )
- {
- LLEditMenuHandler::gEditMenuHandler->cut();
- }
- return true;
- }
-};
-
-class LLEditEnableCopy : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canCopy();
- return new_value;
- }
-};
-
-class LLEditCopy : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if( LLEditMenuHandler::gEditMenuHandler )
- {
- LLEditMenuHandler::gEditMenuHandler->copy();
- }
- return true;
- }
-};
-
-class LLEditEnablePaste : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canPaste();
- return new_value;
- }
-};
-
-class LLEditPaste : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if( LLEditMenuHandler::gEditMenuHandler )
- {
- LLEditMenuHandler::gEditMenuHandler->paste();
- }
- return true;
- }
-};
-
-class LLEditEnableDelete : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canDoDelete();
- return new_value;
- }
-};
-
-class LLEditDelete : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- // If a text field can do a deletion, it gets precedence over deleting
- // an object in the world.
- if( LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canDoDelete())
- {
- LLEditMenuHandler::gEditMenuHandler->doDelete();
- }
-
- // and close any pie/context menus when done
- gMenuHolder->hideMenus();
-
- // When deleting an object we may not actually be done
- // Keep selection so we know what to delete when confirmation is needed about the delete
- gMenuObject->hide();
- return true;
- }
-};
-
-bool enable_object_delete()
-{
- bool new_value =
-#ifdef HACKED_GODLIKE_VIEWER
- TRUE;
-#else
-# ifdef TOGGLE_HACKED_GODLIKE_VIEWER
- (!LLGridManager::getInstance()->isInProductionGrid()
- && gAgent.isGodlike()) ||
-# endif
- LLSelectMgr::getInstance()->canDoDelete();
-#endif
- return new_value;
-}
-
-void handle_object_delete()
-{
-
- if (LLSelectMgr::getInstance())
- {
- LLSelectMgr::getInstance()->doDelete();
- }
-
- // and close any pie/context menus when done
- gMenuHolder->hideMenus();
-
- // When deleting an object we may not actually be done
- // Keep selection so we know what to delete when confirmation is needed about the delete
- gMenuObject->hide();
- return;
-}
-
-void handle_force_delete(void*)
-{
- LLSelectMgr::getInstance()->selectForceDelete();
-}
-
-class LLViewEnableJoystickFlycam : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = (gSavedSettings.getBOOL("JoystickEnabled") && gSavedSettings.getBOOL("JoystickFlycamEnabled"));
- return new_value;
- }
-};
-
-class LLViewEnableLastChatter : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- // *TODO: add check that last chatter is in range
- bool new_value = (gAgentCamera.cameraThirdPerson() && gAgent.getLastChatter().notNull());
- return new_value;
- }
-};
-
-class LLEditEnableDeselect : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canDeselect();
- return new_value;
- }
-};
-
-class LLEditDeselect : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if( LLEditMenuHandler::gEditMenuHandler )
- {
- LLEditMenuHandler::gEditMenuHandler->deselect();
- }
- return true;
- }
-};
-
-class LLEditEnableSelectAll : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canSelectAll();
- return new_value;
- }
-};
-
-
-class LLEditSelectAll : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if( LLEditMenuHandler::gEditMenuHandler )
- {
- LLEditMenuHandler::gEditMenuHandler->selectAll();
- }
- return true;
- }
-};
-
-
-class LLEditEnableUndo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canUndo();
- return new_value;
- }
-};
-
-class LLEditUndo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if( LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canUndo() )
- {
- LLEditMenuHandler::gEditMenuHandler->undo();
- }
- return true;
- }
-};
-
-class LLEditEnableRedo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canRedo();
- return new_value;
- }
-};
-
-class LLEditRedo : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if( LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canRedo() )
- {
- LLEditMenuHandler::gEditMenuHandler->redo();
- }
- return true;
- }
-};
-
-
-
-void print_object_info(void*)
-{
- LLSelectMgr::getInstance()->selectionDump();
-}
-
-void print_agent_nvpairs(void*)
-{
- LLViewerObject *objectp;
-
- llinfos << "Agent Name Value Pairs" << llendl;
-
- objectp = gObjectList.findObject(gAgentID);
- if (objectp)
- {
- objectp->printNameValuePairs();
- }
- else
- {
- llinfos << "Can't find agent object" << llendl;
- }
-
- llinfos << "Camera at " << gAgentCamera.getCameraPositionGlobal() << llendl;
-}
-
-void show_debug_menus()
-{
- // this might get called at login screen where there is no menu so only toggle it if one exists
- if ( gMenuBarView )
- {
- BOOL debug = gSavedSettings.getBOOL("UseDebugMenus");
- BOOL qamode = gSavedSettings.getBOOL("QAMode");
-
- gMenuBarView->setItemVisible("Advanced", debug);
-// gMenuBarView->setItemEnabled("Advanced", debug); // Don't disable Advanced keyboard shortcuts when hidden
-
- gMenuBarView->setItemVisible("Debug", qamode);
- gMenuBarView->setItemEnabled("Debug", qamode);
-
- gMenuBarView->setItemVisible("Develop", qamode);
- gMenuBarView->setItemEnabled("Develop", qamode);
-
- // Server ('Admin') menu hidden when not in godmode.
- const bool show_server_menu = (gAgent.getGodLevel() > GOD_NOT || (debug && gAgent.getAdminOverride()));
- gMenuBarView->setItemVisible("Admin", show_server_menu);
- gMenuBarView->setItemEnabled("Admin", show_server_menu);
- }
- if (gLoginMenuBarView)
- {
- BOOL debug = gSavedSettings.getBOOL("UseDebugMenus");
- gLoginMenuBarView->setItemVisible("Debug", debug);
- gLoginMenuBarView->setItemEnabled("Debug", debug);
- }
-}
-
-void toggle_debug_menus(void*)
-{
- BOOL visible = ! gSavedSettings.getBOOL("UseDebugMenus");
- gSavedSettings.setBOOL("UseDebugMenus", visible);
- show_debug_menus();
-}
-
-
-// LLUUID gExporterRequestID;
-// std::string gExportDirectory;
-
-// LLUploadDialog *gExportDialog = NULL;
-
-// void handle_export_selected( void * )
-// {
-// LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
-// if (selection->isEmpty())
-// {
-// return;
-// }
-// llinfos << "Exporting selected objects:" << llendl;
-
-// gExporterRequestID.generate();
-// gExportDirectory = "";
-
-// LLMessageSystem* msg = gMessageSystem;
-// msg->newMessageFast(_PREHASH_ObjectExportSelected);
-// msg->nextBlockFast(_PREHASH_AgentData);
-// msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
-// msg->addUUIDFast(_PREHASH_RequestID, gExporterRequestID);
-// msg->addS16Fast(_PREHASH_VolumeDetail, 4);
-
-// for (LLObjectSelection::root_iterator iter = selection->root_begin();
-// iter != selection->root_end(); iter++)
-// {
-// LLSelectNode* node = *iter;
-// LLViewerObject* object = node->getObject();
-// msg->nextBlockFast(_PREHASH_ObjectData);
-// msg->addUUIDFast(_PREHASH_ObjectID, object->getID());
-// llinfos << "Object: " << object->getID() << llendl;
-// }
-// msg->sendReliable(gAgent.getRegion()->getHost());
-
-// gExportDialog = LLUploadDialog::modalUploadDialog("Exporting selected objects...");
-// }
-//
-
-
-class LLWorldSetHomeLocation : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- // we just send the message and let the server check for failure cases
- // server will echo back a "Home position set." alert if it succeeds
- // and the home location screencapture happens when that alert is recieved
- gAgent.setStartPosition(START_LOCATION_ID_HOME);
- return true;
- }
-};
-
-class LLWorldTeleportHome : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gAgent.teleportHome();
- return true;
- }
-};
-
-class LLWorldAlwaysRun : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- // as well as altering the default walk-vs-run state,
- // we also change the *current* walk-vs-run state.
- if (gAgent.getAlwaysRun())
- {
- gAgent.clearAlwaysRun();
- gAgent.clearRunning();
- }
- else
- {
- gAgent.setAlwaysRun();
- gAgent.setRunning();
- }
-
- // tell the simulator.
- gAgent.sendWalkRun(gAgent.getAlwaysRun());
-
- // Update Movement Controls according to AlwaysRun mode
- LLFloaterMove::setAlwaysRunMode(gAgent.getAlwaysRun());
-
- return true;
- }
-};
-
-class LLWorldCheckAlwaysRun : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gAgent.getAlwaysRun();
- return new_value;
- }
-};
-
-class LLWorldSetAway : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if (gAgent.getAFK())
- {
- gAgent.clearAFK();
- }
- else
- {
- gAgent.setAFK();
- }
- return true;
- }
-};
-
-class LLWorldSetBusy : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if (gAgent.getBusy())
- {
- gAgent.clearBusy();
- }
- else
- {
- gAgent.setBusy();
- LLNotificationsUtil::add("BusyModeSet");
- }
- return true;
- }
-};
-
-class LLWorldCreateLandmark : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLSideTray::getInstance()->showPanel("panel_places", LLSD().with("type", "create_landmark"));
-
- return true;
- }
-};
-
-class LLWorldPlaceProfile : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLSideTray::getInstance()->showPanel("panel_places", LLSD().with("type", "agent"));
-
- return true;
- }
-};
-
-void handle_look_at_selection(const LLSD& param)
-{
- const F32 PADDING_FACTOR = 1.75f;
- BOOL zoom = (param.asString() == "zoom");
- if (!LLSelectMgr::getInstance()->getSelection()->isEmpty())
- {
- gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
-
- LLBBox selection_bbox = LLSelectMgr::getInstance()->getBBoxOfSelection();
- F32 angle_of_view = llmax(0.1f, LLViewerCamera::getInstance()->getAspect() > 1.f ? LLViewerCamera::getInstance()->getView() * LLViewerCamera::getInstance()->getAspect() : LLViewerCamera::getInstance()->getView());
- F32 distance = selection_bbox.getExtentLocal().magVec() * PADDING_FACTOR / atan(angle_of_view);
-
- LLVector3 obj_to_cam = LLViewerCamera::getInstance()->getOrigin() - selection_bbox.getCenterAgent();
- obj_to_cam.normVec();
-
- LLUUID object_id;
- if (LLSelectMgr::getInstance()->getSelection()->getPrimaryObject())
- {
- object_id = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject()->mID;
- }
- if (zoom)
- {
- // Make sure we are not increasing the distance between the camera and object
- LLVector3d orig_distance = gAgentCamera.getCameraPositionGlobal() - LLSelectMgr::getInstance()->getSelectionCenterGlobal();
- distance = llmin(distance, (F32) orig_distance.length());
-
- gAgentCamera.setCameraPosAndFocusGlobal(LLSelectMgr::getInstance()->getSelectionCenterGlobal() + LLVector3d(obj_to_cam * distance),
- LLSelectMgr::getInstance()->getSelectionCenterGlobal(),
- object_id );
-
- }
- else
- {
- gAgentCamera.setFocusGlobal( LLSelectMgr::getInstance()->getSelectionCenterGlobal(), object_id );
- }
- }
-}
-
-void handle_zoom_to_object(LLUUID object_id)
-{
- const F32 PADDING_FACTOR = 2.f;
-
- LLViewerObject* object = gObjectList.findObject(object_id);
-
- if (object)
- {
- gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
-
- LLBBox bbox = object->getBoundingBoxAgent() ;
- F32 angle_of_view = llmax(0.1f, LLViewerCamera::getInstance()->getAspect() > 1.f ? LLViewerCamera::getInstance()->getView() * LLViewerCamera::getInstance()->getAspect() : LLViewerCamera::getInstance()->getView());
- F32 distance = bbox.getExtentLocal().magVec() * PADDING_FACTOR / atan(angle_of_view);
-
- LLVector3 obj_to_cam = LLViewerCamera::getInstance()->getOrigin() - bbox.getCenterAgent();
- obj_to_cam.normVec();
-
-
- LLVector3d object_center_global = gAgent.getPosGlobalFromAgent(bbox.getCenterAgent());
-
- gAgentCamera.setCameraPosAndFocusGlobal(object_center_global + LLVector3d(obj_to_cam * distance),
- object_center_global,
- object_id );
- }
-}
-
-class LLAvatarInviteToGroup : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
- if(avatar)
- {
- LLAvatarActions::inviteToGroup(avatar->getID());
- }
- return true;
- }
-};
-
-class LLAvatarAddFriend : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
- if(avatar && !LLAvatarActions::isFriend(avatar->getID()))
- {
- request_friendship(avatar->getID());
- }
- return true;
- }
-};
-
-class LLAvatarAddContact : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
- if(avatar)
- {
- create_inventory_callingcard(avatar->getID());
- }
- return true;
- }
-};
-
-bool complete_give_money(const LLSD& notification, const LLSD& response, LLObjectSelectionHandle selection)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- if (option == 0)
- {
- gAgent.clearBusy();
- }
-
- LLViewerObject* objectp = selection->getPrimaryObject();
-
- // Show avatar's name if paying attachment
- if (objectp && objectp->isAttachment())
- {
- while (objectp && !objectp->isAvatar())
- {
- objectp = (LLViewerObject*)objectp->getParent();
- }
- }
-
- if (objectp)
- {
- if (objectp->isAvatar())
- {
- const bool is_group = false;
- LLFloaterPayUtil::payDirectly(&give_money,
- objectp->getID(),
- is_group);
- }
- else
- {
- LLFloaterPayUtil::payViaObject(&give_money, selection);
- }
- }
- return false;
-}
-
-void handle_give_money_dialog()
-{
- LLNotification::Params params("BusyModePay");
- params.functor.function(boost::bind(complete_give_money, _1, _2, LLSelectMgr::getInstance()->getSelection()));
-
- if (gAgent.getBusy())
- {
- // warn users of being in busy mode during a transaction
- LLNotifications::instance().add(params);
- }
- else
- {
- LLNotifications::instance().forceResponse(params, 1);
- }
-}
-
-bool enable_pay_avatar()
-{
- LLViewerObject* obj = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- LLVOAvatar* avatar = find_avatar_from_object(obj);
- return (avatar != NULL);
-}
-
-bool enable_pay_object()
-{
- LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- if( object )
- {
- LLViewerObject *parent = (LLViewerObject *)object->getParent();
- if((object->flagTakesMoney()) || (parent && parent->flagTakesMoney()))
- {
- return true;
- }
- }
- return false;
-}
-
-bool enable_object_stand_up()
-{
- // 'Object Stand Up' menu item is enabled when agent is sitting on selection
- return sitting_on_selection();
-}
-
-bool enable_object_sit(LLUICtrl* ctrl)
-{
- // 'Object Sit' menu item is enabled when agent is not sitting on selection
- bool sitting_on_sel = sitting_on_selection();
- if (!sitting_on_sel)
- {
- std::string item_name = ctrl->getName();
-
- // init default labels
- init_default_item_label(item_name);
-
- // Update label
- LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
- if (node && node->mValid && !node->mSitName.empty())
- {
- gMenuHolder->childSetText(item_name, node->mSitName);
- }
- else
- {
- gMenuHolder->childSetText(item_name, get_default_item_label(item_name));
- }
- }
- return !sitting_on_sel && is_object_sittable();
-}
-
-void dump_select_mgr(void*)
-{
- LLSelectMgr::getInstance()->dump();
-}
-
-void dump_inventory(void*)
-{
- gInventory.dumpInventory();
-}
-
-
-void handle_dump_followcam(void*)
-{
- LLFollowCamMgr::dump();
-}
-
-void handle_viewer_enable_message_log(void*)
-{
- gMessageSystem->startLogging();
-}
-
-void handle_viewer_disable_message_log(void*)
-{
- gMessageSystem->stopLogging();
-}
-
-void handle_customize_avatar()
-{
- LLSideTray::getInstance()->showPanel("sidepanel_appearance", LLSD().with("type", "my_outfits"));
-}
-
-void handle_edit_outfit()
-{
- LLSideTray::getInstance()->showPanel("sidepanel_appearance", LLSD().with("type", "edit_outfit"));
-}
-
-void handle_edit_shape()
-{
- LLSideTray::getInstance()->showPanel("sidepanel_appearance", LLSD().with("type", "edit_shape"));
-}
-
-void handle_report_abuse()
-{
- // Prevent menu from appearing in screen shot.
- gMenuHolder->hideMenus();
- LLFloaterReporter::showFromMenu(COMPLAINT_REPORT);
-}
-
-void handle_buy_currency()
-{
- LLBuyCurrencyHTML::openCurrencyFloater();
-}
-
-class LLFloaterVisible : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string floater_name = userdata.asString();
- bool new_value = false;
- {
- new_value = LLFloaterReg::instanceVisible(floater_name);
- }
- return new_value;
- }
-};
-
-class LLShowHelp : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string help_topic = userdata.asString();
- LLViewerHelp* vhelp = LLViewerHelp::getInstance();
- vhelp->showTopic(help_topic);
- return true;
- }
-};
-
-class LLToggleHelp : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLFloater* help_browser = (LLFloaterReg::findInstance("help_browser"));
- if (help_browser && help_browser->isInVisibleChain())
- {
- help_browser->closeFloater();
- }
- else
- {
- std::string help_topic = userdata.asString();
- LLViewerHelp* vhelp = LLViewerHelp::getInstance();
- vhelp->showTopic(help_topic);
- }
- return true;
- }
-};
-
-class LLShowSidetrayPanel : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string panel_name = userdata.asString();
-
- LLPanel* panel = LLSideTray::getInstance()->getPanel(panel_name);
- if (panel)
- {
- if (panel->isInVisibleChain())
- {
- LLSideTray::getInstance()->hidePanel(panel_name);
- }
- else
- {
- LLSideTray::getInstance()->showPanel(panel_name);
- }
- }
- return true;
- }
-};
-
-class LLSidetrayPanelVisible : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string panel_name = userdata.asString();
- // Toggle the panel
- if (LLSideTray::getInstance()->isPanelActive(panel_name))
- {
- return true;
- }
- else
- {
- return false;
- }
-
- }
-};
-
-
-bool callback_show_url(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- if (0 == option)
- {
- LLWeb::loadURL(notification["payload"]["url"].asString());
- }
- return false;
-}
-
-class LLPromptShowURL : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string param = userdata.asString();
- std::string::size_type offset = param.find(",");
- if (offset != param.npos)
- {
- std::string alert = param.substr(0, offset);
- std::string url = param.substr(offset+1);
-
- if(gSavedSettings.getBOOL("UseExternalBrowser"))
- {
- LLSD payload;
- payload["url"] = url;
- LLNotificationsUtil::add(alert, LLSD(), payload, callback_show_url);
- }
- else
- {
- LLWeb::loadURL(url);
- }
- }
- else
- {
- llinfos << "PromptShowURL invalid parameters! Expecting \"ALERT,URL\"." << llendl;
- }
- return true;
- }
-};
-
-bool callback_show_file(const LLSD& notification, const LLSD& response)
-{
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- if (0 == option)
- {
- LLWeb::loadURL(notification["payload"]["url"]);
- }
- return false;
-}
-
-class LLPromptShowFile : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string param = userdata.asString();
- std::string::size_type offset = param.find(",");
- if (offset != param.npos)
- {
- std::string alert = param.substr(0, offset);
- std::string file = param.substr(offset+1);
-
- LLSD payload;
- payload["url"] = file;
- LLNotificationsUtil::add(alert, LLSD(), payload, callback_show_file);
- }
- else
- {
- llinfos << "PromptShowFile invalid parameters! Expecting \"ALERT,FILE\"." << llendl;
- }
- return true;
- }
-};
-
-class LLShowAgentProfile : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLUUID agent_id;
- if (userdata.asString() == "agent")
- {
- agent_id = gAgent.getID();
- }
- else if (userdata.asString() == "hit object")
- {
- LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- if (objectp)
- {
- agent_id = objectp->getID();
- }
- }
- else
- {
- agent_id = userdata.asUUID();
- }
-
- LLVOAvatar* avatar = find_avatar_from_object(agent_id);
- if (avatar)
- {
- LLAvatarActions::showProfile(avatar->getID());
- }
- return true;
- }
-};
-
-class LLToggleAgentProfile : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLUUID agent_id;
- if (userdata.asString() == "agent")
- {
- agent_id = gAgent.getID();
- }
- else if (userdata.asString() == "hit object")
- {
- LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- if (objectp)
- {
- agent_id = objectp->getID();
- }
- }
- else
- {
- agent_id = userdata.asUUID();
- }
-
- LLVOAvatar* avatar = find_avatar_from_object(agent_id);
- if (avatar)
- {
- if (!LLAvatarActions::profileVisible(avatar->getID()))
- {
- LLAvatarActions::showProfile(avatar->getID());
- }
- else
- {
- LLAvatarActions::hideProfile(avatar->getID());
- }
- }
- return true;
- }
-};
-
-class LLLandEdit : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- if (gAgentCamera.getFocusOnAvatar() && gSavedSettings.getBOOL("EditCameraMovement") )
- {
- // zoom in if we're looking at the avatar
- gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
- gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
-
- gAgentCamera.cameraOrbitOver( F_PI * 0.25f );
- gViewerWindow->moveCursorToCenter();
- }
- else if ( gSavedSettings.getBOOL("EditCameraMovement") )
- {
- gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
- gViewerWindow->moveCursorToCenter();
- }
-
-
- LLViewerParcelMgr::getInstance()->selectParcelAt( LLToolPie::getInstance()->getPick().mPosGlobal );
-
- LLFloaterReg::showInstance("build");
-
- // Switch to land edit toolset
- LLToolMgr::getInstance()->getCurrentToolset()->selectTool( LLToolSelectLand::getInstance() );
- return true;
- }
-};
-
-class LLWorldEnableBuyLand : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLViewerParcelMgr::getInstance()->canAgentBuyParcel(
- LLViewerParcelMgr::getInstance()->selectionEmpty()
- ? LLViewerParcelMgr::getInstance()->getAgentParcel()
- : LLViewerParcelMgr::getInstance()->getParcelSelection()->getParcel(),
- false);
- return new_value;
- }
-};
-
-BOOL enable_buy_land(void*)
-{
- return LLViewerParcelMgr::getInstance()->canAgentBuyParcel(
- LLViewerParcelMgr::getInstance()->getParcelSelection()->getParcel(), false);
-}
-
-void handle_buy_land()
-{
- LLViewerParcelMgr* vpm = LLViewerParcelMgr::getInstance();
- if (vpm->selectionEmpty())
- {
- vpm->selectParcelAt(gAgent.getPositionGlobal());
- }
- vpm->startBuyLand();
-}
-
-class LLObjectAttachToAvatar : public view_listener_t
-{
-public:
- LLObjectAttachToAvatar(bool replace) : mReplace(replace) {}
- static void setObjectSelection(LLObjectSelectionHandle selection) { sObjectSelection = selection; }
-
-private:
- bool handleEvent(const LLSD& userdata)
- {
- setObjectSelection(LLSelectMgr::getInstance()->getSelection());
- LLViewerObject* selectedObject = sObjectSelection->getFirstRootObject();
- if (selectedObject)
- {
- S32 index = userdata.asInteger();
- LLViewerJointAttachment* attachment_point = NULL;
- if (index > 0)
- attachment_point = get_if_there(gAgentAvatarp->mAttachmentPoints, index, (LLViewerJointAttachment*)NULL);
- confirmReplaceAttachment(0, attachment_point);
- }
- return true;
- }
-
- static void onNearAttachObject(BOOL success, void *user_data);
- void confirmReplaceAttachment(S32 option, LLViewerJointAttachment* attachment_point);
-
- struct CallbackData
- {
- CallbackData(LLViewerJointAttachment* point, bool replace) : mAttachmentPoint(point), mReplace(replace) {}
-
- LLViewerJointAttachment* mAttachmentPoint;
- bool mReplace;
- };
-
-protected:
- static LLObjectSelectionHandle sObjectSelection;
- bool mReplace;
-};
-
-LLObjectSelectionHandle LLObjectAttachToAvatar::sObjectSelection;
-
-// static
-void LLObjectAttachToAvatar::onNearAttachObject(BOOL success, void *user_data)
-{
- if (!user_data) return;
- CallbackData* cb_data = static_cast<CallbackData*>(user_data);
-
- if (success)
- {
- const LLViewerJointAttachment *attachment = cb_data->mAttachmentPoint;
-
- U8 attachment_id = 0;
- if (attachment)
- {
- for (LLVOAvatar::attachment_map_t::const_iterator iter = gAgentAvatarp->mAttachmentPoints.begin();
- iter != gAgentAvatarp->mAttachmentPoints.end(); ++iter)
- {
- if (iter->second == attachment)
- {
- attachment_id = iter->first;
- break;
- }
- }
- }
- else
- {
- // interpret 0 as "default location"
- attachment_id = 0;
- }
- LLSelectMgr::getInstance()->sendAttach(attachment_id, cb_data->mReplace);
- }
- LLObjectAttachToAvatar::setObjectSelection(NULL);
-
- delete cb_data;
-}
-
-// static
-void LLObjectAttachToAvatar::confirmReplaceAttachment(S32 option, LLViewerJointAttachment* attachment_point)
-{
- if (option == 0/*YES*/)
- {
- LLViewerObject* selectedObject = LLSelectMgr::getInstance()->getSelection()->getFirstRootObject();
- if (selectedObject)
- {
- const F32 MIN_STOP_DISTANCE = 1.f; // meters
- const F32 ARM_LENGTH = 0.5f; // meters
- const F32 SCALE_FUDGE = 1.5f;
-
- F32 stop_distance = SCALE_FUDGE * selectedObject->getMaxScale() + ARM_LENGTH;
- if (stop_distance < MIN_STOP_DISTANCE)
- {
- stop_distance = MIN_STOP_DISTANCE;
- }
-
- LLVector3 walkToSpot = selectedObject->getPositionAgent();
-
- // make sure we stop in front of the object
- LLVector3 delta = walkToSpot - gAgent.getPositionAgent();
- delta.normVec();
- delta = delta * 0.5f;
- walkToSpot -= delta;
-
- // The callback will be called even if avatar fails to get close enough to the object, so we won't get a memory leak.
- CallbackData* user_data = new CallbackData(attachment_point, mReplace);
- gAgent.startAutoPilotGlobal(gAgent.getPosGlobalFromAgent(walkToSpot), "Attach", NULL, onNearAttachObject, user_data, stop_distance);
- gAgentCamera.clearFocusObject();
- }
- }
-}
-
-void callback_attachment_drop(const LLSD& notification, const LLSD& response)
-{
- // Ensure user confirmed the drop
- S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
- if (option != 0) return;
-
- // Called when the user clicked on an object attached to them
- // and selected "Drop".
- LLUUID object_id = notification["payload"]["object_id"].asUUID();
- LLViewerObject *object = gObjectList.findObject(object_id);
-
- if (!object)
- {
- llwarns << "handle_drop_attachment() - no object to drop" << llendl;
- return;
- }
-
- LLViewerObject *parent = (LLViewerObject*)object->getParent();
- while (parent)
- {
- if(parent->isAvatar())
- {
- break;
- }
- object = parent;
- parent = (LLViewerObject*)parent->getParent();
- }
-
- if (!object)
- {
- llwarns << "handle_detach() - no object to detach" << llendl;
- return;
- }
-
- if (object->isAvatar())
- {
- llwarns << "Trying to detach avatar from avatar." << llendl;
- return;
- }
-
- // reselect the object
- LLSelectMgr::getInstance()->selectObjectAndFamily(object);
-
- LLSelectMgr::getInstance()->sendDropAttachment();
-
- return;
-}
-
-class LLAttachmentDrop : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLSD payload;
- LLViewerObject *object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
-
- if (object)
- {
- payload["object_id"] = object->getID();
- }
- else
- {
- llwarns << "Drop object not found" << llendl;
- return true;
- }
-
- LLNotificationsUtil::add("AttachmentDrop", LLSD(), payload, &callback_attachment_drop);
- return true;
- }
-};
-
-// called from avatar pie menu
-class LLAttachmentDetachFromPoint : public view_listener_t
-{
- bool handleEvent(const LLSD& user_data)
- {
- const LLViewerJointAttachment *attachment = get_if_there(gAgentAvatarp->mAttachmentPoints, user_data.asInteger(), (LLViewerJointAttachment*)NULL);
- if (attachment->getNumObjects() > 0)
- {
- gMessageSystem->newMessage("ObjectDetach");
- gMessageSystem->nextBlockFast(_PREHASH_AgentData);
- gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgent.getID() );
- gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
-
- for (LLViewerJointAttachment::attachedobjs_vec_t::const_iterator iter = attachment->mAttachedObjects.begin();
- iter != attachment->mAttachedObjects.end();
- iter++)
- {
- LLViewerObject *attached_object = (*iter);
- gMessageSystem->nextBlockFast(_PREHASH_ObjectData);
- gMessageSystem->addU32Fast(_PREHASH_ObjectLocalID, attached_object->getLocalID());
- }
- gMessageSystem->sendReliable( gAgent.getRegionHost() );
- }
- return true;
- }
-};
-
-static bool onEnableAttachmentLabel(LLUICtrl* ctrl, const LLSD& data)
-{
- std::string label;
- LLMenuItemGL* menu = dynamic_cast<LLMenuItemGL*>(ctrl);
- if (menu)
- {
- const LLViewerJointAttachment *attachment = get_if_there(gAgentAvatarp->mAttachmentPoints, data["index"].asInteger(), (LLViewerJointAttachment*)NULL);
- if (attachment)
- {
- label = data["label"].asString();
- for (LLViewerJointAttachment::attachedobjs_vec_t::const_iterator attachment_iter = attachment->mAttachedObjects.begin();
- attachment_iter != attachment->mAttachedObjects.end();
- ++attachment_iter)
- {
- const LLViewerObject* attached_object = (*attachment_iter);
- if (attached_object)
- {
- LLViewerInventoryItem* itemp = gInventory.getItem(attached_object->getAttachmentItemID());
- if (itemp)
- {
- label += std::string(" (") + itemp->getName() + std::string(")");
- break;
- }
- }
- }
- }
- menu->setLabel(label);
- }
- return true;
-}
-
-class LLAttachmentDetach : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- // Called when the user clicked on an object attached to them
- // and selected "Detach".
- LLViewerObject *object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- if (!object)
- {
- llwarns << "handle_detach() - no object to detach" << llendl;
- return true;
- }
-
- LLViewerObject *parent = (LLViewerObject*)object->getParent();
- while (parent)
- {
- if(parent->isAvatar())
- {
- break;
- }
- object = parent;
- parent = (LLViewerObject*)parent->getParent();
- }
-
- if (!object)
- {
- llwarns << "handle_detach() - no object to detach" << llendl;
- return true;
- }
-
- if (object->isAvatar())
- {
- llwarns << "Trying to detach avatar from avatar." << llendl;
- return true;
- }
-
- // The sendDetach() method works on the list of selected
- // objects. Thus we need to clear the list, make sure it only
- // contains the object the user clicked, send the message,
- // then clear the list.
- // We use deselectAll to update the simulator's notion of what's
- // selected, and removeAll just to change things locally.
- //RN: I thought it was more useful to detach everything that was selected
- if (LLSelectMgr::getInstance()->getSelection()->isAttachment())
- {
- LLSelectMgr::getInstance()->sendDetach();
- }
- return true;
- }
-};
-
-//Adding an observer for a Jira 2422 and needs to be a fetch observer
-//for Jira 3119
-class LLWornItemFetchedObserver : public LLInventoryFetchItemsObserver
-{
-public:
- LLWornItemFetchedObserver(const LLUUID& worn_item_id) :
- LLInventoryFetchItemsObserver(worn_item_id)
- {}
- virtual ~LLWornItemFetchedObserver() {}
-
-protected:
- virtual void done()
- {
- gMenuAttachmentSelf->buildDrawLabels();
- gInventory.removeObserver(this);
- delete this;
- }
-};
-
-// You can only drop items on parcels where you can build.
-class LLAttachmentEnableDrop : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- BOOL can_build = gAgent.isGodlike() || (LLViewerParcelMgr::getInstance()->allowAgentBuild());
-
- //Add an inventory observer to only allow dropping the newly attached item
- //once it exists in your inventory. Look at Jira 2422.
- //-jwolk
-
- // A bug occurs when you wear/drop an item before it actively is added to your inventory
- // if this is the case (you're on a slow sim, etc.) a copy of the object,
- // well, a newly created object with the same properties, is placed
- // in your inventory. Therefore, we disable the drop option until the
- // item is in your inventory
-
- LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- LLViewerJointAttachment* attachment = NULL;
- LLInventoryItem* item = NULL;
-
- // Do not enable drop if all faces of object are not enabled
- if (object && LLSelectMgr::getInstance()->getSelection()->contains(object,SELECT_ALL_TES ))
- {
- S32 attachmentID = ATTACHMENT_ID_FROM_STATE(object->getState());
- attachment = get_if_there(gAgentAvatarp->mAttachmentPoints, attachmentID, (LLViewerJointAttachment*)NULL);
-
- if (attachment)
- {
- for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
- attachment_iter != attachment->mAttachedObjects.end();
- ++attachment_iter)
- {
- // make sure item is in your inventory (it could be a delayed attach message being sent from the sim)
- // so check to see if the item is in the inventory already
- item = gInventory.getItem((*attachment_iter)->getAttachmentItemID());
- if (!item)
- {
- // Item does not exist, make an observer to enable the pie menu
- // when the item finishes fetching worst case scenario
- // if a fetch is already out there (being sent from a slow sim)
- // we refetch and there are 2 fetches
- LLWornItemFetchedObserver* worn_item_fetched = new LLWornItemFetchedObserver((*attachment_iter)->getAttachmentItemID());
- worn_item_fetched->startFetch();
- gInventory.addObserver(worn_item_fetched);
- }
- }
- }
- }
-
- //now check to make sure that the item is actually in the inventory before we enable dropping it
- bool new_value = enable_detach() && can_build && item;
-
- return new_value;
- }
-};
-
-BOOL enable_detach(const LLSD&)
-{
- LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
-
- // Only enable detach if all faces of object are selected
- if (!object ||
- !object->isAttachment() ||
- !LLSelectMgr::getInstance()->getSelection()->contains(object,SELECT_ALL_TES ))
- {
- return FALSE;
- }
-
- // Find the avatar who owns this attachment
- LLViewerObject* avatar = object;
- while (avatar)
- {
- // ...if it's you, good to detach
- if (avatar->getID() == gAgent.getID())
- {
- return TRUE;
- }
-
- avatar = (LLViewerObject*)avatar->getParent();
- }
-
- return FALSE;
-}
-
-class LLAttachmentEnableDetach : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = enable_detach();
- return new_value;
- }
-};
-
-// Used to tell if the selected object can be attached to your avatar.
-BOOL object_selected_and_point_valid()
-{
- LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
- for (LLObjectSelection::root_iterator iter = selection->root_begin();
- iter != selection->root_end(); iter++)
- {
- LLSelectNode* node = *iter;
- LLViewerObject* object = node->getObject();
- LLViewerObject::const_child_list_t& child_list = object->getChildren();
- for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
- iter != child_list.end(); iter++)
- {
- LLViewerObject* child = *iter;
- if (child->isAvatar())
- {
- return FALSE;
- }
- }
- }
-
- return (selection->getRootObjectCount() == 1) &&
- (selection->getFirstRootObject()->getPCode() == LL_PCODE_VOLUME) &&
- selection->getFirstRootObject()->permYouOwner() &&
- selection->getFirstRootObject()->flagObjectMove() &&
- !((LLViewerObject*)selection->getFirstRootObject()->getRoot())->isAvatar() &&
- (selection->getFirstRootObject()->getNVPair("AssetContainer") == NULL);
-}
-
-
-BOOL object_is_wearable()
-{
- if (!object_selected_and_point_valid())
- {
- return FALSE;
- }
- if (sitting_on_selection())
- {
- return FALSE;
- }
- LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
- for (LLObjectSelection::valid_root_iterator iter = LLSelectMgr::getInstance()->getSelection()->valid_root_begin();
- iter != LLSelectMgr::getInstance()->getSelection()->valid_root_end(); iter++)
- {
- LLSelectNode* node = *iter;
- if (node->mPermissions->getOwner() == gAgent.getID())
- {
- return TRUE;
- }
- }
- return FALSE;
-}
-
-
-class LLAttachmentPointFilled : public view_listener_t
-{
- bool handleEvent(const LLSD& user_data)
- {
- bool enable = false;
- LLVOAvatar::attachment_map_t::iterator found_it = gAgentAvatarp->mAttachmentPoints.find(user_data.asInteger());
- if (found_it != gAgentAvatarp->mAttachmentPoints.end())
- {
- enable = found_it->second->getNumObjects() > 0;
- }
- return enable;
- }
-};
-
-class LLAvatarSendIM : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
- if(avatar)
- {
- LLAvatarActions::startIM(avatar->getID());
- }
- return true;
- }
-};
-
-class LLAvatarCall : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
- if(avatar)
- {
- LLAvatarActions::startCall(avatar->getID());
- }
- return true;
- }
-};
-
-namespace
-{
- struct QueueObjects : public LLSelectedObjectFunctor
- {
- BOOL scripted;
- BOOL modifiable;
- LLFloaterScriptQueue* mQueue;
- QueueObjects(LLFloaterScriptQueue* q) : mQueue(q), scripted(FALSE), modifiable(FALSE) {}
- virtual bool apply(LLViewerObject* obj)
- {
- scripted = obj->flagScripted();
- modifiable = obj->permModify();
-
- if( scripted && modifiable )
- {
- mQueue->addObject(obj->getID());
- return false;
- }
- else
- {
- return true; // fail: stop applying
- }
- }
- };
-}
-
-void queue_actions(LLFloaterScriptQueue* q, const std::string& msg)
-{
- QueueObjects func(q);
- LLSelectMgr *mgr = LLSelectMgr::getInstance();
- LLObjectSelectionHandle selectHandle = mgr->getSelection();
- bool fail = selectHandle->applyToObjects(&func);
- if(fail)
- {
- if ( !func.scripted )
- {
- std::string noscriptmsg = std::string("Cannot") + msg + "SelectObjectsNoScripts";
- LLNotificationsUtil::add(noscriptmsg);
- }
- else if ( !func.modifiable )
- {
- std::string nomodmsg = std::string("Cannot") + msg + "SelectObjectsNoPermission";
- LLNotificationsUtil::add(nomodmsg);
- }
- else
- {
- llerrs << "Bad logic." << llendl;
- }
- }
- else
- {
- if (!q->start())
- {
- llwarns << "Unexpected script compile failure." << llendl;
- }
- }
-}
-
-class LLToolsSelectedScriptAction : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string action = userdata.asString();
- bool mono = false;
- std::string msg, name;
- if (action == "compile mono")
- {
- name = "compile_queue";
- mono = true;
- msg = "Recompile";
- }
- if (action == "compile lsl")
- {
- name = "compile_queue";
- msg = "Recompile";
- }
- else if (action == "reset")
- {
- name = "reset_queue";
- msg = "Reset";
- }
- else if (action == "start")
- {
- name = "start_queue";
- msg = "Running";
- }
- else if (action == "stop")
- {
- name = "stop_queue";
- msg = "RunningNot";
- }
- LLUUID id; id.generate();
-
- LLFloaterScriptQueue* queue =LLFloaterReg::getTypedInstance<LLFloaterScriptQueue>(name, LLSD(id));
- if (queue)
- {
- queue->setMono(mono);
- queue_actions(queue, msg);
- }
- else
- {
- llwarns << "Failed to generate LLFloaterScriptQueue with action: " << action << llendl;
- }
- return true;
- }
-};
-
-void handle_selected_texture_info(void*)
-{
- for (LLObjectSelection::valid_iterator iter = LLSelectMgr::getInstance()->getSelection()->valid_begin();
- iter != LLSelectMgr::getInstance()->getSelection()->valid_end(); iter++)
- {
- LLSelectNode* node = *iter;
-
- std::string msg;
- msg.assign("Texture info for: ");
- msg.append(node->mName);
-
- LLSD args;
- args["MESSAGE"] = msg;
- LLNotificationsUtil::add("SystemMessage", args);
-
- U8 te_count = node->getObject()->getNumTEs();
- // map from texture ID to list of faces using it
- typedef std::map< LLUUID, std::vector<U8> > map_t;
- map_t faces_per_texture;
- for (U8 i = 0; i < te_count; i++)
- {
- if (!node->isTESelected(i)) continue;
-
- LLViewerTexture* img = node->getObject()->getTEImage(i);
- LLUUID image_id = img->getID();
- faces_per_texture[image_id].push_back(i);
- }
- // Per-texture, dump which faces are using it.
- map_t::iterator it;
- for (it = faces_per_texture.begin(); it != faces_per_texture.end(); ++it)
- {
- LLUUID image_id = it->first;
- U8 te = it->second[0];
- LLViewerTexture* img = node->getObject()->getTEImage(te);
- S32 height = img->getHeight();
- S32 width = img->getWidth();
- S32 components = img->getComponents();
- msg = llformat("%dx%d %s on face ",
- width,
- height,
- (components == 4 ? "alpha" : "opaque"));
- for (U8 i = 0; i < it->second.size(); ++i)
- {
- msg.append( llformat("%d ", (S32)(it->second[i])));
- }
-
- LLSD args;
- args["MESSAGE"] = msg;
- LLNotificationsUtil::add("SystemMessage", args);
- }
- }
-}
-
-void handle_test_male(void*)
-{
- LLAppearanceMgr::instance().wearOutfitByName("Male Shape & Outfit");
- //gGestureList.requestResetFromServer( TRUE );
-}
-
-void handle_test_female(void*)
-{
- LLAppearanceMgr::instance().wearOutfitByName("Female Shape & Outfit");
- //gGestureList.requestResetFromServer( FALSE );
-}
-
-void handle_toggle_pg(void*)
-{
- gAgent.setTeen( !gAgent.isTeen() );
-
- LLFloaterWorldMap::reloadIcons(NULL);
-
- llinfos << "PG status set to " << (S32)gAgent.isTeen() << llendl;
-}
-
-void handle_dump_attachments(void*)
-{
- if(!isAgentAvatarValid()) return;
-
- for (LLVOAvatar::attachment_map_t::iterator iter = gAgentAvatarp->mAttachmentPoints.begin();
- iter != gAgentAvatarp->mAttachmentPoints.end(); )
- {
- LLVOAvatar::attachment_map_t::iterator curiter = iter++;
- LLViewerJointAttachment* attachment = curiter->second;
- S32 key = curiter->first;
- for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
- attachment_iter != attachment->mAttachedObjects.end();
- ++attachment_iter)
- {
- LLViewerObject *attached_object = (*attachment_iter);
- BOOL visible = (attached_object != NULL &&
- attached_object->mDrawable.notNull() &&
- !attached_object->mDrawable->isRenderType(0));
- LLVector3 pos;
- if (visible) pos = attached_object->mDrawable->getPosition();
- llinfos << "ATTACHMENT " << key << ": item_id=" << attached_object->getAttachmentItemID()
- << (attached_object ? " present " : " absent ")
- << (visible ? "visible " : "invisible ")
- << " at " << pos
- << " and " << (visible ? attached_object->getPosition() : LLVector3::zero)
- << llendl;
- }
- }
-}
-
-
-// these are used in the gl menus to set control values, generically.
-class LLToggleControl : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string control_name = userdata.asString();
- BOOL checked = gSavedSettings.getBOOL( control_name );
- gSavedSettings.setBOOL( control_name, !checked );
- return true;
- }
-};
-
-class LLCheckControl : public view_listener_t
-{
- bool handleEvent( const LLSD& userdata)
- {
- std::string callback_data = userdata.asString();
- bool new_value = gSavedSettings.getBOOL(callback_data);
- return new_value;
- }
-};
-
-// not so generic
-
-class LLAdvancedCheckRenderShadowOption: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string control_name = userdata.asString();
- S32 current_shadow_level = gSavedSettings.getS32(control_name);
- if (current_shadow_level == 0) // is off
- {
- return false;
- }
- else // is on
- {
- return true;
- }
- }
-};
-
-class LLAdvancedClickRenderShadowOption: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string control_name = userdata.asString();
- S32 current_shadow_level = gSavedSettings.getS32(control_name);
- if (current_shadow_level == 0) // upgrade to level 2
- {
- gSavedSettings.setS32(control_name, 2);
- }
- else // downgrade to level 0
- {
- gSavedSettings.setS32(control_name, 0);
- }
- return true;
- }
-};
-
-void menu_toggle_attached_lights(void* user_data)
-{
- LLPipeline::sRenderAttachedLights = gSavedSettings.getBOOL("RenderAttachedLights");
-}
-
-void menu_toggle_attached_particles(void* user_data)
-{
- LLPipeline::sRenderAttachedParticles = gSavedSettings.getBOOL("RenderAttachedParticles");
-}
-
-class LLAdvancedHandleAttachedLightParticles: public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string control_name = userdata.asString();
-
- // toggle the control
- gSavedSettings.setBOOL(control_name,
- !gSavedSettings.getBOOL(control_name));
-
- // update internal flags
- if (control_name == "RenderAttachedLights")
- {
- menu_toggle_attached_lights(NULL);
- }
- else if (control_name == "RenderAttachedParticles")
- {
- menu_toggle_attached_particles(NULL);
- }
- return true;
- }
-};
-
-class LLSomethingSelected : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = !(LLSelectMgr::getInstance()->getSelection()->isEmpty());
- return new_value;
- }
-};
-
-class LLSomethingSelectedNoHUD : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
- bool new_value = !(selection->isEmpty()) && !(selection->getSelectType() == SELECT_TYPE_HUD);
- return new_value;
- }
-};
-
-static bool is_editable_selected()
-{
- return (LLSelectMgr::getInstance()->getSelection()->getFirstEditableObject() != NULL);
-}
-
-class LLEditableSelected : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- return is_editable_selected();
- }
-};
-
-class LLEditableSelectedMono : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = false;
- LLViewerRegion* region = gAgent.getRegion();
- if(region && gMenuHolder)
- {
- bool have_cap = (! region->getCapability("UpdateScriptTask").empty());
- new_value = is_editable_selected() && have_cap;
- }
- return new_value;
- }
-};
-
-bool enable_object_take_copy()
-{
- bool all_valid = false;
- if (LLSelectMgr::getInstance())
- {
- if (!LLSelectMgr::getInstance()->getSelection()->isEmpty())
- {
- all_valid = true;
-#ifndef HACKED_GODLIKE_VIEWER
-# ifdef TOGGLE_HACKED_GODLIKE_VIEWER
- if (LLGridManager::getInstance()->isInProductionGrid()
- || !gAgent.isGodlike())
-# endif
- {
- struct f : public LLSelectedObjectFunctor
- {
- virtual bool apply(LLViewerObject* obj)
- {
- return (!obj->permCopy() || obj->isAttachment());
- }
- } func;
- const bool firstonly = true;
- bool any_invalid = LLSelectMgr::getInstance()->getSelection()->applyToRootObjects(&func, firstonly);
- all_valid = !any_invalid;
- }
-#endif // HACKED_GODLIKE_VIEWER
- }
- }
-
- return all_valid;
-}
-
-
-class LLHasAsset : public LLInventoryCollectFunctor
-{
-public:
- LLHasAsset(const LLUUID& id) : mAssetID(id), mHasAsset(FALSE) {}
- virtual ~LLHasAsset() {}
- virtual bool operator()(LLInventoryCategory* cat,
- LLInventoryItem* item);
- BOOL hasAsset() const { return mHasAsset; }
-
-protected:
- LLUUID mAssetID;
- BOOL mHasAsset;
-};
-
-bool LLHasAsset::operator()(LLInventoryCategory* cat,
- LLInventoryItem* item)
-{
- if(item && item->getAssetUUID() == mAssetID)
- {
- mHasAsset = TRUE;
- }
- return FALSE;
-}
-
-BOOL enable_save_into_inventory(void*)
-{
- // *TODO: clean this up
- // find the last root
- LLSelectNode* last_node = NULL;
- for (LLObjectSelection::root_iterator iter = LLSelectMgr::getInstance()->getSelection()->root_begin();
- iter != LLSelectMgr::getInstance()->getSelection()->root_end(); iter++)
- {
- last_node = *iter;
- }
-
-#ifdef HACKED_GODLIKE_VIEWER
- return TRUE;
-#else
-# ifdef TOGGLE_HACKED_GODLIKE_VIEWER
- if (!LLGridManager::getInstance()->isInProductionGrid()
- && gAgent.isGodlike())
- {
- return TRUE;
- }
-# endif
- // check all pre-req's for save into inventory.
- if(last_node && last_node->mValid && !last_node->mItemID.isNull()
- && (last_node->mPermissions->getOwner() == gAgent.getID())
- && (gInventory.getItem(last_node->mItemID) != NULL))
- {
- LLViewerObject* obj = last_node->getObject();
- if( obj && !obj->isAttachment() )
- {
- return TRUE;
- }
- }
-#endif
- return FALSE;
-}
-
-class LLToolsEnableSaveToInventory : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = enable_save_into_inventory(NULL);
- return new_value;
- }
-};
-
-BOOL enable_save_into_task_inventory(void*)
-{
- LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
- if(node && (node->mValid) && (!node->mFromTaskID.isNull()))
- {
- // *TODO: check to see if the fromtaskid object exists.
- LLViewerObject* obj = node->getObject();
- if( obj && !obj->isAttachment() )
- {
- return TRUE;
- }
- }
- return FALSE;
-}
-
-class LLToolsEnableSaveToObjectInventory : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = enable_save_into_task_inventory(NULL);
- return new_value;
- }
-};
-
-
-class LLViewEnableMouselook : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- // You can't go directly from customize avatar to mouselook.
- // TODO: write code with appropriate dialogs to handle this transition.
- bool new_value = (CAMERA_MODE_CUSTOMIZE_AVATAR != gAgentCamera.getCameraMode() && !gSavedSettings.getBOOL("FreezeTime"));
- return new_value;
- }
-};
-
-class LLToolsEnableToolNotPie : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = ( LLToolMgr::getInstance()->getBaseTool() != LLToolPie::getInstance() );
- return new_value;
- }
-};
-
-class LLWorldEnableCreateLandmark : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- return !LLLandmarkActions::landmarkAlreadyExists();
- }
-};
-
-class LLWorldEnableSetHomeLocation : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gAgent.isGodlike() ||
- (gAgent.getRegion() && gAgent.getRegion()->getAllowSetHome());
- return new_value;
- }
-};
-
-class LLWorldEnableTeleportHome : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLViewerRegion* regionp = gAgent.getRegion();
- bool agent_on_prelude = (regionp && regionp->isPrelude());
- bool enable_teleport_home = gAgent.isGodlike() || !agent_on_prelude;
- return enable_teleport_home;
- }
-};
-
-BOOL enable_god_full(void*)
-{
- return gAgent.getGodLevel() >= GOD_FULL;
-}
-
-BOOL enable_god_liaison(void*)
-{
- return gAgent.getGodLevel() >= GOD_LIAISON;
-}
-
-bool is_god_customer_service()
-{
- return gAgent.getGodLevel() >= GOD_CUSTOMER_SERVICE;
-}
-
-BOOL enable_god_basic(void*)
-{
- return gAgent.getGodLevel() > GOD_NOT;
-}
-
-
-void toggle_show_xui_names(void *)
-{
- gSavedSettings.setBOOL("DebugShowXUINames", !gSavedSettings.getBOOL("DebugShowXUINames"));
-}
-
-BOOL check_show_xui_names(void *)
-{
- return gSavedSettings.getBOOL("DebugShowXUINames");
-}
-
-class LLToolsSelectOnlyMyObjects : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- BOOL cur_val = gSavedSettings.getBOOL("SelectOwnedOnly");
-
- gSavedSettings.setBOOL("SelectOwnedOnly", ! cur_val );
-
- return true;
- }
-};
-
-class LLToolsSelectOnlyMovableObjects : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- BOOL cur_val = gSavedSettings.getBOOL("SelectMovableOnly");
-
- gSavedSettings.setBOOL("SelectMovableOnly", ! cur_val );
-
- return true;
- }
-};
-
-class LLToolsSelectBySurrounding : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLSelectMgr::sRectSelectInclusive = !LLSelectMgr::sRectSelectInclusive;
-
- gSavedSettings.setBOOL("RectangleSelectInclusive", LLSelectMgr::sRectSelectInclusive);
- return true;
- }
-};
-
-class LLToolsShowHiddenSelection : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- // TomY TODO Merge these
- LLSelectMgr::sRenderHiddenSelections = !LLSelectMgr::sRenderHiddenSelections;
-
- gSavedSettings.setBOOL("RenderHiddenSelections", LLSelectMgr::sRenderHiddenSelections);
- return true;
- }
-};
-
-class LLToolsShowSelectionLightRadius : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- // TomY TODO merge these
- LLSelectMgr::sRenderLightRadius = !LLSelectMgr::sRenderLightRadius;
-
- gSavedSettings.setBOOL("RenderLightRadius", LLSelectMgr::sRenderLightRadius);
- return true;
- }
-};
-
-class LLToolsEditLinkedParts : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- BOOL select_individuals = !gSavedSettings.getBOOL("EditLinkedParts");
- gSavedSettings.setBOOL( "EditLinkedParts", select_individuals );
- if (select_individuals)
- {
- LLSelectMgr::getInstance()->demoteSelectionToIndividuals();
- }
- else
- {
- LLSelectMgr::getInstance()->promoteSelectionToRoot();
- }
- return true;
- }
-};
-
-void reload_vertex_shader(void *)
-{
- //THIS WOULD BE AN AWESOME PLACE TO RELOAD SHADERS... just a thought - DaveP
-}
-
-void handle_dump_avatar_local_textures(void*)
-{
- gAgentAvatarp->dumpLocalTextures();
-}
-
-void handle_dump_timers()
-{
- LLFastTimer::dumpCurTimes();
-}
-
-void handle_debug_avatar_textures(void*)
-{
- LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
- if (objectp)
- {
- LLFloaterReg::showInstance( "avatar_textures", LLSD(objectp->getID()) );
- }
-}
-
-void handle_grab_baked_texture(void* data)
-{
- EBakedTextureIndex baked_tex_index = (EBakedTextureIndex)((intptr_t)data);
- if (!isAgentAvatarValid()) return;
-
- const LLUUID& asset_id = gAgentAvatarp->grabBakedTexture(baked_tex_index);
- LL_INFOS("texture") << "Adding baked texture " << asset_id << " to inventory." << llendl;
- LLAssetType::EType asset_type = LLAssetType::AT_TEXTURE;
- LLInventoryType::EType inv_type = LLInventoryType::IT_TEXTURE;
- const LLUUID folder_id = gInventory.findCategoryUUIDForType(LLFolderType::assetTypeToFolderType(asset_type));
- if(folder_id.notNull())
- {
- std::string name;
- name = "Baked " + LLVOAvatarDictionary::getInstance()->getBakedTexture(baked_tex_index)->mNameCapitalized + " Texture";
-
- LLUUID item_id;
- item_id.generate();
- LLPermissions perm;
- perm.init(gAgentID,
- gAgentID,
- LLUUID::null,
- LLUUID::null);
- U32 next_owner_perm = PERM_MOVE | PERM_TRANSFER;
- perm.initMasks(PERM_ALL,
- PERM_ALL,
- PERM_NONE,
- PERM_NONE,
- next_owner_perm);
- time_t creation_date_now = time_corrected();
- LLPointer<LLViewerInventoryItem> item
- = new LLViewerInventoryItem(item_id,
- folder_id,
- perm,
- asset_id,
- asset_type,
- inv_type,
- name,
- LLStringUtil::null,
- LLSaleInfo::DEFAULT,
- LLInventoryItemFlags::II_FLAGS_NONE,
- creation_date_now);
-
- item->updateServer(TRUE);
- gInventory.updateItem(item);
- gInventory.notifyObservers();
-
- // Show the preview panel for textures to let
- // user know that the image is now in inventory.
- LLInventoryPanel *active_panel = LLInventoryPanel::getActiveInventoryPanel();
- if(active_panel)
- {
- LLFocusableElement* focus_ctrl = gFocusMgr.getKeyboardFocus();
-
- active_panel->setSelection(item_id, TAKE_FOCUS_NO);
- active_panel->openSelected();
- //LLFloaterInventory::dumpSelectionInformation((void*)view);
- // restore keyboard focus
- gFocusMgr.setKeyboardFocus(focus_ctrl);
- }
- }
- else
- {
- llwarns << "Can't find a folder to put it in" << llendl;
- }
-}
-
-BOOL enable_grab_baked_texture(void* data)
-{
- EBakedTextureIndex index = (EBakedTextureIndex)((intptr_t)data);
- if (isAgentAvatarValid())
- {
- return gAgentAvatarp->canGrabBakedTexture(index);
- }
- return FALSE;
-}
-
-// Returns a pointer to the avatar give the UUID of the avatar OR of an attachment the avatar is wearing.
-// Returns NULL on failure.
-LLVOAvatar* find_avatar_from_object( LLViewerObject* object )
-{
- if (object)
- {
- if( object->isAttachment() )
- {
- do
- {
- object = (LLViewerObject*) object->getParent();
- }
- while( object && !object->isAvatar() );
- }
- else if( !object->isAvatar() )
- {
- object = NULL;
- }
- }
-
- return (LLVOAvatar*) object;
-}
-
-
-// Returns a pointer to the avatar give the UUID of the avatar OR of an attachment the avatar is wearing.
-// Returns NULL on failure.
-LLVOAvatar* find_avatar_from_object( const LLUUID& object_id )
-{
- return find_avatar_from_object( gObjectList.findObject(object_id) );
-}
-
-
-void handle_disconnect_viewer(void *)
-{
- LLAppViewer::instance()->forceDisconnect(LLTrans::getString("TestingDisconnect"));
-}
-
-void force_error_breakpoint(void *)
-{
- LLAppViewer::instance()->forceErrorBreakpoint();
-}
-
-void force_error_llerror(void *)
-{
- LLAppViewer::instance()->forceErrorLLError();
-}
-
-void force_error_bad_memory_access(void *)
-{
- LLAppViewer::instance()->forceErrorBadMemoryAccess();
-}
-
-void force_error_infinite_loop(void *)
-{
- LLAppViewer::instance()->forceErrorInfiniteLoop();
-}
-
-void force_error_software_exception(void *)
-{
- LLAppViewer::instance()->forceErrorSoftwareException();
-}
-
-void force_error_driver_crash(void *)
-{
- LLAppViewer::instance()->forceErrorDriverCrash();
-}
-
-class LLToolsUseSelectionForGrid : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLSelectMgr::getInstance()->clearGridObjects();
- struct f : public LLSelectedObjectFunctor
- {
- virtual bool apply(LLViewerObject* objectp)
- {
- LLSelectMgr::getInstance()->addGridObject(objectp);
- return true;
- }
- } func;
- LLSelectMgr::getInstance()->getSelection()->applyToRootObjects(&func);
- LLSelectMgr::getInstance()->setGridMode(GRID_MODE_REF_OBJECT);
- if (gFloaterTools)
- {
- gFloaterTools->mComboGridMode->setCurrentByIndex((S32)GRID_MODE_REF_OBJECT);
- }
- return true;
- }
-};
-
-void handle_test_load_url(void*)
-{
- LLWeb::loadURL("");
- LLWeb::loadURL("hacker://www.google.com/");
- LLWeb::loadURL("http");
- LLWeb::loadURL("http://www.google.com/");
-}
-
-//
-// LLViewerMenuHolderGL
-//
-static LLDefaultChildRegistry::Register<LLViewerMenuHolderGL> r("menu_holder");
-
-LLViewerMenuHolderGL::LLViewerMenuHolderGL(const LLViewerMenuHolderGL::Params& p)
-: LLMenuHolderGL(p)
-{}
-
-BOOL LLViewerMenuHolderGL::hideMenus()
-{
- BOOL handled = LLMenuHolderGL::hideMenus();
-
- // drop pie menu selection
- mParcelSelection = NULL;
- mObjectSelection = NULL;
-
- if (gMenuBarView)
- {
- gMenuBarView->clearHoverItem();
- gMenuBarView->resetMenuTrigger();
- }
-
- return handled;
-}
-
-void LLViewerMenuHolderGL::setParcelSelection(LLSafeHandle<LLParcelSelection> selection)
-{
- mParcelSelection = selection;
-}
-
-void LLViewerMenuHolderGL::setObjectSelection(LLSafeHandle<LLObjectSelection> selection)
-{
- mObjectSelection = selection;
-}
-
-
-const LLRect LLViewerMenuHolderGL::getMenuRect() const
-{
- return LLRect(0, getRect().getHeight() - MENU_BAR_HEIGHT, getRect().getWidth(), STATUS_BAR_HEIGHT);
-}
-
-void handle_web_browser_test(const LLSD& param)
-{
- std::string url = param.asString();
- if (url.empty())
- {
- url = "about:blank";
- }
- LLWeb::loadURLInternal(url);
-}
-
-void handle_web_content_test(const LLSD& param)
-{
- std::string url = param.asString();
- LLWeb::loadWebURLInternal(url);
-}
-
-void handle_buy_currency_test(void*)
-{
- std::string url =
- "http://sarahd-sl-13041.webdev.lindenlab.com/app/lindex/index.php?agent_id=[AGENT_ID]&secure_session_id=[SESSION_ID]&lang=[LANGUAGE]";
-
- LLStringUtil::format_map_t replace;
- replace["[AGENT_ID]"] = gAgent.getID().asString();
- replace["[SESSION_ID]"] = gAgent.getSecureSessionID().asString();
- replace["[LANGUAGE]"] = LLUI::getLanguage();
- LLStringUtil::format(url, replace);
-
- llinfos << "buy currency url " << url << llendl;
-
- LLFloaterReg::showInstance("buy_currency_html", LLSD(url));
-}
-
-void handle_rebake_textures(void*)
-{
- if (!isAgentAvatarValid()) return;
-
- // Slam pending upload count to "unstick" things
- bool slam_for_debug = true;
- gAgentAvatarp->forceBakeAllTextures(slam_for_debug);
-}
-
-void toggle_visibility(void* user_data)
-{
- LLView* viewp = (LLView*)user_data;
- viewp->setVisible(!viewp->getVisible());
-}
-
-BOOL get_visibility(void* user_data)
-{
- LLView* viewp = (LLView*)user_data;
- return viewp->getVisible();
-}
-
-// TomY TODO: Get rid of these?
-class LLViewShowHoverTips : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- gSavedSettings.setBOOL("ShowHoverTips", !gSavedSettings.getBOOL("ShowHoverTips"));
- return true;
- }
-};
-
-class LLViewCheckShowHoverTips : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = gSavedSettings.getBOOL("ShowHoverTips");
- return new_value;
- }
-};
-
-// TomY TODO: Get rid of these?
-class LLViewHighlightTransparent : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLDrawPoolAlpha::sShowDebugAlpha = !LLDrawPoolAlpha::sShowDebugAlpha;
- return true;
- }
-};
-
-class LLViewCheckHighlightTransparent : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLDrawPoolAlpha::sShowDebugAlpha;
- return new_value;
- }
-};
-
-class LLViewBeaconWidth : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string width = userdata.asString();
- if(width == "1")
- {
- gSavedSettings.setS32("DebugBeaconLineWidth", 1);
- }
- else if(width == "4")
- {
- gSavedSettings.setS32("DebugBeaconLineWidth", 4);
- }
- else if(width == "16")
- {
- gSavedSettings.setS32("DebugBeaconLineWidth", 16);
- }
- else if(width == "32")
- {
- gSavedSettings.setS32("DebugBeaconLineWidth", 32);
- }
-
- return true;
- }
-};
-
-
-class LLViewToggleBeacon : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string beacon = userdata.asString();
- if (beacon == "scriptsbeacon")
- {
- LLPipeline::toggleRenderScriptedBeacons(NULL);
- gSavedSettings.setBOOL( "scriptsbeacon", LLPipeline::getRenderScriptedBeacons(NULL) );
- // toggle the other one off if it's on
- if (LLPipeline::getRenderScriptedBeacons(NULL) && LLPipeline::getRenderScriptedTouchBeacons(NULL))
- {
- LLPipeline::toggleRenderScriptedTouchBeacons(NULL);
- gSavedSettings.setBOOL( "scripttouchbeacon", LLPipeline::getRenderScriptedTouchBeacons(NULL) );
- }
- }
- else if (beacon == "physicalbeacon")
- {
- LLPipeline::toggleRenderPhysicalBeacons(NULL);
- gSavedSettings.setBOOL( "physicalbeacon", LLPipeline::getRenderPhysicalBeacons(NULL) );
- }
- else if (beacon == "soundsbeacon")
- {
- LLPipeline::toggleRenderSoundBeacons(NULL);
- gSavedSettings.setBOOL( "soundsbeacon", LLPipeline::getRenderSoundBeacons(NULL) );
- }
- else if (beacon == "particlesbeacon")
- {
- LLPipeline::toggleRenderParticleBeacons(NULL);
- gSavedSettings.setBOOL( "particlesbeacon", LLPipeline::getRenderParticleBeacons(NULL) );
- }
- else if (beacon == "scripttouchbeacon")
- {
- LLPipeline::toggleRenderScriptedTouchBeacons(NULL);
- gSavedSettings.setBOOL( "scripttouchbeacon", LLPipeline::getRenderScriptedTouchBeacons(NULL) );
- // toggle the other one off if it's on
- if (LLPipeline::getRenderScriptedBeacons(NULL) && LLPipeline::getRenderScriptedTouchBeacons(NULL))
- {
- LLPipeline::toggleRenderScriptedBeacons(NULL);
- gSavedSettings.setBOOL( "scriptsbeacon", LLPipeline::getRenderScriptedBeacons(NULL) );
- }
- }
- else if (beacon == "renderbeacons")
- {
- LLPipeline::toggleRenderBeacons(NULL);
- gSavedSettings.setBOOL( "renderbeacons", LLPipeline::getRenderBeacons(NULL) );
- // toggle the other one on if it's not
- if (!LLPipeline::getRenderBeacons(NULL) && !LLPipeline::getRenderHighlights(NULL))
- {
- LLPipeline::toggleRenderHighlights(NULL);
- gSavedSettings.setBOOL( "renderhighlights", LLPipeline::getRenderHighlights(NULL) );
- }
- }
- else if (beacon == "renderhighlights")
- {
- LLPipeline::toggleRenderHighlights(NULL);
- gSavedSettings.setBOOL( "renderhighlights", LLPipeline::getRenderHighlights(NULL) );
- // toggle the other one on if it's not
- if (!LLPipeline::getRenderBeacons(NULL) && !LLPipeline::getRenderHighlights(NULL))
- {
- LLPipeline::toggleRenderBeacons(NULL);
- gSavedSettings.setBOOL( "renderbeacons", LLPipeline::getRenderBeacons(NULL) );
- }
- }
-
- return true;
- }
-};
-
-class LLViewCheckBeaconEnabled : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string beacon = userdata.asString();
- bool new_value = false;
- if (beacon == "scriptsbeacon")
- {
- new_value = gSavedSettings.getBOOL( "scriptsbeacon");
- LLPipeline::setRenderScriptedBeacons(new_value);
- }
- else if (beacon == "physicalbeacon")
- {
- new_value = gSavedSettings.getBOOL( "physicalbeacon");
- LLPipeline::setRenderPhysicalBeacons(new_value);
- }
- else if (beacon == "soundsbeacon")
- {
- new_value = gSavedSettings.getBOOL( "soundsbeacon");
- LLPipeline::setRenderSoundBeacons(new_value);
- }
- else if (beacon == "particlesbeacon")
- {
- new_value = gSavedSettings.getBOOL( "particlesbeacon");
- LLPipeline::setRenderParticleBeacons(new_value);
- }
- else if (beacon == "scripttouchbeacon")
- {
- new_value = gSavedSettings.getBOOL( "scripttouchbeacon");
- LLPipeline::setRenderScriptedTouchBeacons(new_value);
- }
- else if (beacon == "renderbeacons")
- {
- new_value = gSavedSettings.getBOOL( "renderbeacons");
- LLPipeline::setRenderBeacons(new_value);
- }
- else if (beacon == "renderhighlights")
- {
- new_value = gSavedSettings.getBOOL( "renderhighlights");
- LLPipeline::setRenderHighlights(new_value);
- }
- return new_value;
- }
-};
-
-class LLViewToggleRenderType : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string type = userdata.asString();
- if (type == "hideparticles")
- {
- LLPipeline::toggleRenderType(LLPipeline::RENDER_TYPE_PARTICLES);
- }
- return true;
- }
-};
-
-class LLViewCheckRenderType : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string type = userdata.asString();
- bool new_value = false;
- if (type == "hideparticles")
- {
- new_value = LLPipeline::toggleRenderTypeControlNegated((void *)LLPipeline::RENDER_TYPE_PARTICLES);
- }
- return new_value;
- }
-};
-
-class LLViewShowHUDAttachments : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLPipeline::sShowHUDAttachments = !LLPipeline::sShowHUDAttachments;
- return true;
- }
-};
-
-class LLViewCheckHUDAttachments : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool new_value = LLPipeline::sShowHUDAttachments;
- return new_value;
- }
-};
-
-class LLEditEnableTakeOff : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string clothing = userdata.asString();
- LLWearableType::EType type = LLWearableType::typeNameToType(clothing);
- if (type >= LLWearableType::WT_SHAPE && type < LLWearableType::WT_COUNT)
- return LLAgentWearables::selfHasWearable(type);
- return false;
- }
-};
-
-class LLEditTakeOff : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string clothing = userdata.asString();
- if (clothing == "all")
- LLWearableBridge::removeAllClothesFromAvatar();
- else
- {
- LLWearableType::EType type = LLWearableType::typeNameToType(clothing);
- if (type >= LLWearableType::WT_SHAPE
- && type < LLWearableType::WT_COUNT
- && (gAgentWearables.getWearableCount(type) > 0))
- {
- // MULTI-WEARABLES: assuming user wanted to remove top shirt.
- U32 wearable_index = gAgentWearables.getWearableCount(type) - 1;
- LLViewerInventoryItem *item = dynamic_cast<LLViewerInventoryItem*>(gAgentWearables.getWearableInventoryItem(type,wearable_index));
- LLWearableBridge::removeItemFromAvatar(item);
- }
-
- }
- return true;
- }
-};
-
-class LLToolsSelectTool : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string tool_name = userdata.asString();
- if (tool_name == "focus")
- {
- LLToolMgr::getInstance()->getCurrentToolset()->selectToolByIndex(1);
- }
- else if (tool_name == "move")
- {
- LLToolMgr::getInstance()->getCurrentToolset()->selectToolByIndex(2);
- }
- else if (tool_name == "edit")
- {
- LLToolMgr::getInstance()->getCurrentToolset()->selectToolByIndex(3);
- }
- else if (tool_name == "create")
- {
- LLToolMgr::getInstance()->getCurrentToolset()->selectToolByIndex(4);
- }
- else if (tool_name == "land")
- {
- LLToolMgr::getInstance()->getCurrentToolset()->selectToolByIndex(5);
- }
- return true;
- }
-};
-
-/// WINDLIGHT callbacks
-class LLWorldEnvSettings : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- std::string tod = userdata.asString();
- LLVector3 sun_direction;
-
- if (tod == "editor")
- {
- // if not there or is hidden, show it
- LLFloaterReg::toggleInstance("env_settings");
- return true;
- }
-
- if (tod == "sunrise")
- {
- // set the value, turn off animation
- LLWLParamManager::instance()->mAnimator.setDayTime(0.25);
- LLWLParamManager::instance()->mAnimator.mIsRunning = false;
- LLWLParamManager::instance()->mAnimator.mUseLindenTime = false;
-
- // then call update once
- LLWLParamManager::instance()->mAnimator.update(
- LLWLParamManager::instance()->mCurParams);
- }
- else if (tod == "noon")
- {
- // set the value, turn off animation
- LLWLParamManager::instance()->mAnimator.setDayTime(0.567);
- LLWLParamManager::instance()->mAnimator.mIsRunning = false;
- LLWLParamManager::instance()->mAnimator.mUseLindenTime = false;
-
- // then call update once
- LLWLParamManager::instance()->mAnimator.update(
- LLWLParamManager::instance()->mCurParams);
- }
- else if (tod == "sunset")
- {
- // set the value, turn off animation
- LLWLParamManager::instance()->mAnimator.setDayTime(0.75);
- LLWLParamManager::instance()->mAnimator.mIsRunning = false;
- LLWLParamManager::instance()->mAnimator.mUseLindenTime = false;
-
- // then call update once
- LLWLParamManager::instance()->mAnimator.update(
- LLWLParamManager::instance()->mCurParams);
- }
- else if (tod == "midnight")
- {
- // set the value, turn off animation
- LLWLParamManager::instance()->mAnimator.setDayTime(0.0);
- LLWLParamManager::instance()->mAnimator.mIsRunning = false;
- LLWLParamManager::instance()->mAnimator.mUseLindenTime = false;
-
- // then call update once
- LLWLParamManager::instance()->mAnimator.update(
- LLWLParamManager::instance()->mCurParams);
- }
- else
- {
- LLWLParamManager::instance()->mAnimator.mIsRunning = true;
- LLWLParamManager::instance()->mAnimator.mUseLindenTime = true;
- }
- return true;
- }
-};
-
-/// Water Menu callbacks
-class LLWorldWaterSettings : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLFloaterReg::toggleInstance("env_water");
- return true;
- }
-};
-
-/// Post-Process callbacks
-class LLWorldPostProcess : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLFloaterReg::showInstance("env_post_process");
- return true;
- }
-};
-
-/// Day Cycle callbacks
-class LLWorldDayCycle : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLFloaterReg::showInstance("env_day_cycle");
- return true;
- }
-};
-
-class LLWorldToggleMovementControls : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLBottomTray::getInstance()->toggleMovementControls();
- return true;
- }
-};
-
-class LLWorldToggleCameraControls : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- LLBottomTray::getInstance()->toggleCameraControls();
- return true;
- }
-};
-
-void handle_flush_name_caches()
-{
- // Toggle display names on and off to flush
- bool use_display_names = LLAvatarNameCache::useDisplayNames();
- LLAvatarNameCache::setUseDisplayNames(!use_display_names);
- LLAvatarNameCache::setUseDisplayNames(use_display_names);
-
- if (gCacheName) gCacheName->clear();
-}
-
-class LLUploadCostCalculator : public view_listener_t
-{
- std::string mCostStr;
-
- bool handleEvent(const LLSD& userdata)
- {
- std::string menu_name = userdata.asString();
- gMenuHolder->childSetLabelArg(menu_name, "[COST]", mCostStr);
-
- return true;
- }
-
- void calculateCost();
-
-public:
- LLUploadCostCalculator()
- {
- calculateCost();
- }
-};
-
-class LLToggleUIHints : public view_listener_t
-{
- bool handleEvent(const LLSD& userdata)
- {
- bool ui_hints_enabled = gSavedSettings.getBOOL("EnableUIHints");
- // toggle
- ui_hints_enabled = !ui_hints_enabled;
- gSavedSettings.setBOOL("EnableUIHints", ui_hints_enabled);
- return true;
- }
-};
-
-void LLUploadCostCalculator::calculateCost()
-{
- S32 upload_cost = LLGlobalEconomy::Singleton::getInstance()->getPriceUpload();
-
- // getPriceUpload() returns -1 if no data available yet.
- if(upload_cost >= 0)
- {
- mCostStr = llformat("%d", upload_cost);
- }
- else
- {
- mCostStr = llformat("%d", gSavedSettings.getU32("DefaultUploadCost"));
- }
-}
-
-void show_navbar_context_menu(LLView* ctrl, S32 x, S32 y)
-{
- static LLMenuGL* show_navbar_context_menu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_hide_navbar.xml",
- gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
- if(gMenuHolder->hasVisibleMenu())
- {
- gMenuHolder->hideMenus();
- }
- show_navbar_context_menu->buildDrawLabels();
- show_navbar_context_menu->updateParent(LLMenuGL::sMenuContainer);
- LLMenuGL::showPopup(ctrl, show_navbar_context_menu, x, y);
-}
-
-void show_topinfobar_context_menu(LLView* ctrl, S32 x, S32 y)
-{
- static LLMenuGL* show_topbarinfo_context_menu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_topinfobar.xml",
- gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
-
- LLMenuItemGL* landmark_item = show_topbarinfo_context_menu->getChild<LLMenuItemGL>("Landmark");
- if (!LLLandmarkActions::landmarkAlreadyExists())
- {
- landmark_item->setLabel(LLTrans::getString("AddLandmarkNavBarMenu"));
- }
- else
- {
- landmark_item->setLabel(LLTrans::getString("EditLandmarkNavBarMenu"));
- }
-
- if(gMenuHolder->hasVisibleMenu())
- {
- gMenuHolder->hideMenus();
- }
-
- show_topbarinfo_context_menu->buildDrawLabels();
- show_topbarinfo_context_menu->updateParent(LLMenuGL::sMenuContainer);
- LLMenuGL::showPopup(ctrl, show_topbarinfo_context_menu, x, y);
-}
-
-void initialize_edit_menu()
-{
- view_listener_t::addMenu(new LLEditUndo(), "Edit.Undo");
- view_listener_t::addMenu(new LLEditRedo(), "Edit.Redo");
- view_listener_t::addMenu(new LLEditCut(), "Edit.Cut");
- view_listener_t::addMenu(new LLEditCopy(), "Edit.Copy");
- view_listener_t::addMenu(new LLEditPaste(), "Edit.Paste");
- view_listener_t::addMenu(new LLEditDelete(), "Edit.Delete");
- view_listener_t::addMenu(new LLEditSelectAll(), "Edit.SelectAll");
- view_listener_t::addMenu(new LLEditDeselect(), "Edit.Deselect");
- view_listener_t::addMenu(new LLEditDuplicate(), "Edit.Duplicate");
- view_listener_t::addMenu(new LLEditTakeOff(), "Edit.TakeOff");
- view_listener_t::addMenu(new LLEditEnableUndo(), "Edit.EnableUndo");
- view_listener_t::addMenu(new LLEditEnableRedo(), "Edit.EnableRedo");
- view_listener_t::addMenu(new LLEditEnableCut(), "Edit.EnableCut");
- view_listener_t::addMenu(new LLEditEnableCopy(), "Edit.EnableCopy");
- view_listener_t::addMenu(new LLEditEnablePaste(), "Edit.EnablePaste");
- view_listener_t::addMenu(new LLEditEnableDelete(), "Edit.EnableDelete");
- view_listener_t::addMenu(new LLEditEnableSelectAll(), "Edit.EnableSelectAll");
- view_listener_t::addMenu(new LLEditEnableDeselect(), "Edit.EnableDeselect");
- view_listener_t::addMenu(new LLEditEnableDuplicate(), "Edit.EnableDuplicate");
-
-}
-
-void initialize_menus()
-{
- // A parameterized event handler used as ctrl-8/9/0 zoom controls below.
- class LLZoomer : public view_listener_t
- {
- public:
- // The "mult" parameter says whether "val" is a multiplier or used to set the value.
- LLZoomer(F32 val, bool mult=true) : mVal(val), mMult(mult) {}
- bool handleEvent(const LLSD& userdata)
- {
- F32 new_fov_rad = mMult ? LLViewerCamera::getInstance()->getDefaultFOV() * mVal : mVal;
- LLViewerCamera::getInstance()->setDefaultFOV(new_fov_rad);
- gSavedSettings.setF32("CameraAngle", LLViewerCamera::getInstance()->getView()); // setView may have clamped it.
- return true;
- }
- private:
- F32 mVal;
- bool mMult;
- };
-
- LLUICtrl::EnableCallbackRegistry::Registrar& enable = LLUICtrl::EnableCallbackRegistry::currentRegistrar();
- LLUICtrl::CommitCallbackRegistry::Registrar& commit = LLUICtrl::CommitCallbackRegistry::currentRegistrar();
-
- // Generic enable and visible
- // Don't prepend MenuName.Foo because these can be used in any menu.
- enable.add("IsGodCustomerService", boost::bind(&is_god_customer_service));
-
- view_listener_t::addEnable(new LLUploadCostCalculator(), "Upload.CalculateCosts");
-
- // Agent
- commit.add("Agent.toggleFlying", boost::bind(&LLAgent::toggleFlying));
- enable.add("Agent.enableFlying", boost::bind(&LLAgent::enableFlying));
-
- // File menu
- init_menu_file();
-
- view_listener_t::addMenu(new LLEditEnableTakeOff(), "Edit.EnableTakeOff");
- view_listener_t::addMenu(new LLEditEnableCustomizeAvatar(), "Edit.EnableCustomizeAvatar");
- view_listener_t::addMenu(new LLEnableEditShape(), "Edit.EnableEditShape");
- commit.add("CustomizeAvatar", boost::bind(&handle_customize_avatar));
- commit.add("EditOutfit", boost::bind(&handle_edit_outfit));
- commit.add("EditShape", boost::bind(&handle_edit_shape));
-
- // View menu
- view_listener_t::addMenu(new LLViewMouselook(), "View.Mouselook");
- view_listener_t::addMenu(new LLViewJoystickFlycam(), "View.JoystickFlycam");
- view_listener_t::addMenu(new LLViewResetView(), "View.ResetView");
- view_listener_t::addMenu(new LLViewLookAtLastChatter(), "View.LookAtLastChatter");
- view_listener_t::addMenu(new LLViewShowHoverTips(), "View.ShowHoverTips");
- view_listener_t::addMenu(new LLViewHighlightTransparent(), "View.HighlightTransparent");
- view_listener_t::addMenu(new LLViewToggleRenderType(), "View.ToggleRenderType");
- view_listener_t::addMenu(new LLViewShowHUDAttachments(), "View.ShowHUDAttachments");
- view_listener_t::addMenu(new LLZoomer(1.2f), "View.ZoomOut");
- view_listener_t::addMenu(new LLZoomer(1/1.2f), "View.ZoomIn");
- view_listener_t::addMenu(new LLZoomer(DEFAULT_FIELD_OF_VIEW, false), "View.ZoomDefault");
- view_listener_t::addMenu(new LLViewDefaultUISize(), "View.DefaultUISize");
-
- view_listener_t::addMenu(new LLViewEnableMouselook(), "View.EnableMouselook");
- view_listener_t::addMenu(new LLViewEnableJoystickFlycam(), "View.EnableJoystickFlycam");
- view_listener_t::addMenu(new LLViewEnableLastChatter(), "View.EnableLastChatter");
-
- view_listener_t::addMenu(new LLViewCheckJoystickFlycam(), "View.CheckJoystickFlycam");
- view_listener_t::addMenu(new LLViewCheckShowHoverTips(), "View.CheckShowHoverTips");
- view_listener_t::addMenu(new LLViewCheckHighlightTransparent(), "View.CheckHighlightTransparent");
- view_listener_t::addMenu(new LLViewCheckRenderType(), "View.CheckRenderType");
- view_listener_t::addMenu(new LLViewCheckHUDAttachments(), "View.CheckHUDAttachments");
-
- // Me > Movement
- view_listener_t::addMenu(new LLAdvancedAgentFlyingInfo(), "Agent.getFlying");
-
- // World menu
- commit.add("World.Chat", boost::bind(&handle_chat, (void*)NULL));
- view_listener_t::addMenu(new LLWorldAlwaysRun(), "World.AlwaysRun");
- view_listener_t::addMenu(new LLWorldCreateLandmark(), "World.CreateLandmark");
- view_listener_t::addMenu(new LLWorldPlaceProfile(), "World.PlaceProfile");
- view_listener_t::addMenu(new LLWorldSetHomeLocation(), "World.SetHomeLocation");
- view_listener_t::addMenu(new LLWorldTeleportHome(), "World.TeleportHome");
- view_listener_t::addMenu(new LLWorldSetAway(), "World.SetAway");
- view_listener_t::addMenu(new LLWorldSetBusy(), "World.SetBusy");
-
- view_listener_t::addMenu(new LLWorldEnableCreateLandmark(), "World.EnableCreateLandmark");
- view_listener_t::addMenu(new LLWorldEnableSetHomeLocation(), "World.EnableSetHomeLocation");
- view_listener_t::addMenu(new LLWorldEnableTeleportHome(), "World.EnableTeleportHome");
- view_listener_t::addMenu(new LLWorldEnableBuyLand(), "World.EnableBuyLand");
-
- view_listener_t::addMenu(new LLWorldCheckAlwaysRun(), "World.CheckAlwaysRun");
-
- view_listener_t::addMenu(new LLWorldEnvSettings(), "World.EnvSettings");
- view_listener_t::addMenu(new LLWorldWaterSettings(), "World.WaterSettings");
- view_listener_t::addMenu(new LLWorldPostProcess(), "World.PostProcess");
- view_listener_t::addMenu(new LLWorldDayCycle(), "World.DayCycle");
-
- view_listener_t::addMenu(new LLWorldToggleMovementControls(), "World.Toggle.MovementControls");
- view_listener_t::addMenu(new LLWorldToggleCameraControls(), "World.Toggle.CameraControls");
-
- // Tools menu
- view_listener_t::addMenu(new LLToolsSelectTool(), "Tools.SelectTool");
- view_listener_t::addMenu(new LLToolsSelectOnlyMyObjects(), "Tools.SelectOnlyMyObjects");
- view_listener_t::addMenu(new LLToolsSelectOnlyMovableObjects(), "Tools.SelectOnlyMovableObjects");
- view_listener_t::addMenu(new LLToolsSelectBySurrounding(), "Tools.SelectBySurrounding");
- view_listener_t::addMenu(new LLToolsShowHiddenSelection(), "Tools.ShowHiddenSelection");
- view_listener_t::addMenu(new LLToolsShowSelectionLightRadius(), "Tools.ShowSelectionLightRadius");
- view_listener_t::addMenu(new LLToolsEditLinkedParts(), "Tools.EditLinkedParts");
- view_listener_t::addMenu(new LLToolsSnapObjectXY(), "Tools.SnapObjectXY");
- view_listener_t::addMenu(new LLToolsUseSelectionForGrid(), "Tools.UseSelectionForGrid");
- view_listener_t::addMenu(new LLToolsSelectNextPart(), "Tools.SelectNextPart");
- commit.add("Tools.Link", boost::bind(&LLSelectMgr::linkObjects, LLSelectMgr::getInstance()));
- commit.add("Tools.Unlink", boost::bind(&LLSelectMgr::unlinkObjects, LLSelectMgr::getInstance()));
- view_listener_t::addMenu(new LLToolsStopAllAnimations(), "Tools.StopAllAnimations");
- view_listener_t::addMenu(new LLToolsReleaseKeys(), "Tools.ReleaseKeys");
- view_listener_t::addMenu(new LLToolsEnableReleaseKeys(), "Tools.EnableReleaseKeys");
- commit.add("Tools.LookAtSelection", boost::bind(&handle_look_at_selection, _2));
- commit.add("Tools.BuyOrTake", boost::bind(&handle_buy_or_take));
- commit.add("Tools.TakeCopy", boost::bind(&handle_take_copy));
- view_listener_t::addMenu(new LLToolsSaveToInventory(), "Tools.SaveToInventory");
- view_listener_t::addMenu(new LLToolsSaveToObjectInventory(), "Tools.SaveToObjectInventory");
- view_listener_t::addMenu(new LLToolsSelectedScriptAction(), "Tools.SelectedScriptAction");
-
- view_listener_t::addMenu(new LLToolsEnableToolNotPie(), "Tools.EnableToolNotPie");
- view_listener_t::addMenu(new LLToolsEnableSelectNextPart(), "Tools.EnableSelectNextPart");
- enable.add("Tools.EnableLink", boost::bind(&LLSelectMgr::enableLinkObjects, LLSelectMgr::getInstance()));
- enable.add("Tools.EnableUnlink", boost::bind(&LLSelectMgr::enableUnlinkObjects, LLSelectMgr::getInstance()));
- view_listener_t::addMenu(new LLToolsEnableBuyOrTake(), "Tools.EnableBuyOrTake");
- enable.add("Tools.EnableTakeCopy", boost::bind(&enable_object_take_copy));
- enable.add("Tools.VisibleBuyObject", boost::bind(&tools_visible_buy_object));
- enable.add("Tools.VisibleTakeObject", boost::bind(&tools_visible_take_object));
- view_listener_t::addMenu(new LLToolsEnableSaveToInventory(), "Tools.EnableSaveToInventory");
- view_listener_t::addMenu(new LLToolsEnableSaveToObjectInventory(), "Tools.EnableSaveToObjectInventory");
-
- // Help menu
- // most items use the ShowFloater method
-
- // Advanced menu
- view_listener_t::addMenu(new LLAdvancedToggleConsole(), "Advanced.ToggleConsole");
- view_listener_t::addMenu(new LLAdvancedCheckConsole(), "Advanced.CheckConsole");
- view_listener_t::addMenu(new LLAdvancedDumpInfoToConsole(), "Advanced.DumpInfoToConsole");
-
- // Advanced > HUD Info
- view_listener_t::addMenu(new LLAdvancedToggleHUDInfo(), "Advanced.ToggleHUDInfo");
- view_listener_t::addMenu(new LLAdvancedCheckHUDInfo(), "Advanced.CheckHUDInfo");
-
- // Advanced Other Settings
- view_listener_t::addMenu(new LLAdvancedClearGroupCache(), "Advanced.ClearGroupCache");
-
- // Advanced > Render > Types
- view_listener_t::addMenu(new LLAdvancedToggleRenderType(), "Advanced.ToggleRenderType");
- view_listener_t::addMenu(new LLAdvancedCheckRenderType(), "Advanced.CheckRenderType");
-
- //// Advanced > Render > Features
- view_listener_t::addMenu(new LLAdvancedToggleFeature(), "Advanced.ToggleFeature");
- view_listener_t::addMenu(new LLAdvancedCheckFeature(), "Advanced.CheckFeature");
- // Advanced > Render > Info Displays
- view_listener_t::addMenu(new LLAdvancedToggleInfoDisplay(), "Advanced.ToggleInfoDisplay");
- view_listener_t::addMenu(new LLAdvancedCheckInfoDisplay(), "Advanced.CheckInfoDisplay");
- view_listener_t::addMenu(new LLAdvancedSelectedTextureInfo(), "Advanced.SelectedTextureInfo");
- view_listener_t::addMenu(new LLAdvancedToggleWireframe(), "Advanced.ToggleWireframe");
- view_listener_t::addMenu(new LLAdvancedCheckWireframe(), "Advanced.CheckWireframe");
- // Develop > Render
- view_listener_t::addMenu(new LLAdvancedToggleTextureAtlas(), "Advanced.ToggleTextureAtlas");
- view_listener_t::addMenu(new LLAdvancedCheckTextureAtlas(), "Advanced.CheckTextureAtlas");
- view_listener_t::addMenu(new LLAdvancedEnableObjectObjectOcclusion(), "Advanced.EnableObjectObjectOcclusion");
- view_listener_t::addMenu(new LLAdvancedEnableRenderFBO(), "Advanced.EnableRenderFBO");
- view_listener_t::addMenu(new LLAdvancedEnableRenderDeferred(), "Advanced.EnableRenderDeferred");
- view_listener_t::addMenu(new LLAdvancedEnableRenderDeferredOptions(), "Advanced.EnableRenderDeferredOptions");
- view_listener_t::addMenu(new LLAdvancedToggleRandomizeFramerate(), "Advanced.ToggleRandomizeFramerate");
- view_listener_t::addMenu(new LLAdvancedCheckRandomizeFramerate(), "Advanced.CheckRandomizeFramerate");
- view_listener_t::addMenu(new LLAdvancedTogglePeriodicSlowFrame(), "Advanced.TogglePeriodicSlowFrame");
- view_listener_t::addMenu(new LLAdvancedCheckPeriodicSlowFrame(), "Advanced.CheckPeriodicSlowFrame");
- view_listener_t::addMenu(new LLAdvancedVectorizePerfTest(), "Advanced.VectorizePerfTest");
- view_listener_t::addMenu(new LLAdvancedToggleFrameTest(), "Advanced.ToggleFrameTest");
- view_listener_t::addMenu(new LLAdvancedCheckFrameTest(), "Advanced.CheckFrameTest");
- view_listener_t::addMenu(new LLAdvancedHandleAttachedLightParticles(), "Advanced.HandleAttachedLightParticles");
- view_listener_t::addMenu(new LLAdvancedCheckRenderShadowOption(), "Advanced.CheckRenderShadowOption");
- view_listener_t::addMenu(new LLAdvancedClickRenderShadowOption(), "Advanced.ClickRenderShadowOption");
-
-
- #ifdef TOGGLE_HACKED_GODLIKE_VIEWER
- view_listener_t::addMenu(new LLAdvancedHandleToggleHackedGodmode(), "Advanced.HandleToggleHackedGodmode");
- view_listener_t::addMenu(new LLAdvancedCheckToggleHackedGodmode(), "Advanced.CheckToggleHackedGodmode");
- view_listener_t::addMenu(new LLAdvancedEnableToggleHackedGodmode(), "Advanced.EnableToggleHackedGodmode");
- #endif
-
- // Advanced > World
- view_listener_t::addMenu(new LLAdvancedDumpScriptedCamera(), "Advanced.DumpScriptedCamera");
- view_listener_t::addMenu(new LLAdvancedDumpRegionObjectCache(), "Advanced.DumpRegionObjectCache");
-
- // Advanced > UI
- commit.add("Advanced.WebBrowserTest", boost::bind(&handle_web_browser_test, _2)); // sigh! this one opens the MEDIA browser
- commit.add("Advanced.WebContentTest", boost::bind(&handle_web_content_test, _2)); // this one opens the Web Content floater
- view_listener_t::addMenu(new LLAdvancedBuyCurrencyTest(), "Advanced.BuyCurrencyTest");
- view_listener_t::addMenu(new LLAdvancedDumpSelectMgr(), "Advanced.DumpSelectMgr");
- view_listener_t::addMenu(new LLAdvancedDumpInventory(), "Advanced.DumpInventory");
- commit.add("Advanced.DumpTimers", boost::bind(&handle_dump_timers) );
- commit.add("Advanced.DumpFocusHolder", boost::bind(&handle_dump_focus) );
- view_listener_t::addMenu(new LLAdvancedPrintSelectedObjectInfo(), "Advanced.PrintSelectedObjectInfo");
- view_listener_t::addMenu(new LLAdvancedPrintAgentInfo(), "Advanced.PrintAgentInfo");
- view_listener_t::addMenu(new LLAdvancedPrintTextureMemoryStats(), "Advanced.PrintTextureMemoryStats");
- view_listener_t::addMenu(new LLAdvancedToggleDebugClicks(), "Advanced.ToggleDebugClicks");
- view_listener_t::addMenu(new LLAdvancedCheckDebugClicks(), "Advanced.CheckDebugClicks");
- view_listener_t::addMenu(new LLAdvancedCheckDebugViews(), "Advanced.CheckDebugViews");
- view_listener_t::addMenu(new LLAdvancedToggleDebugViews(), "Advanced.ToggleDebugViews");
- view_listener_t::addMenu(new LLAdvancedToggleXUINameTooltips(), "Advanced.ToggleXUINameTooltips");
- view_listener_t::addMenu(new LLAdvancedCheckXUINameTooltips(), "Advanced.CheckXUINameTooltips");
- view_listener_t::addMenu(new LLAdvancedToggleDebugMouseEvents(), "Advanced.ToggleDebugMouseEvents");
- view_listener_t::addMenu(new LLAdvancedCheckDebugMouseEvents(), "Advanced.CheckDebugMouseEvents");
- view_listener_t::addMenu(new LLAdvancedToggleDebugKeys(), "Advanced.ToggleDebugKeys");
- view_listener_t::addMenu(new LLAdvancedCheckDebugKeys(), "Advanced.CheckDebugKeys");
- view_listener_t::addMenu(new LLAdvancedToggleDebugWindowProc(), "Advanced.ToggleDebugWindowProc");
- view_listener_t::addMenu(new LLAdvancedCheckDebugWindowProc(), "Advanced.CheckDebugWindowProc");
- commit.add("Advanced.ShowSideTray", boost::bind(&handle_show_side_tray));
-
- // Advanced > XUI
- commit.add("Advanced.ReloadColorSettings", boost::bind(&LLUIColorTable::loadFromSettings, LLUIColorTable::getInstance()));
- view_listener_t::addMenu(new LLAdvancedToggleXUINames(), "Advanced.ToggleXUINames");
- view_listener_t::addMenu(new LLAdvancedCheckXUINames(), "Advanced.CheckXUINames");
- view_listener_t::addMenu(new LLAdvancedSendTestIms(), "Advanced.SendTestIMs");
- commit.add("Advanced.FlushNameCaches", boost::bind(&handle_flush_name_caches));
-
- // Advanced > Character > Grab Baked Texture
- view_listener_t::addMenu(new LLAdvancedGrabBakedTexture(), "Advanced.GrabBakedTexture");
- view_listener_t::addMenu(new LLAdvancedEnableGrabBakedTexture(), "Advanced.EnableGrabBakedTexture");
-
- // Advanced > Character > Character Tests
- view_listener_t::addMenu(new LLAdvancedAppearanceToXML(), "Advanced.AppearanceToXML");
- view_listener_t::addMenu(new LLAdvancedToggleCharacterGeometry(), "Advanced.ToggleCharacterGeometry");
-
- view_listener_t::addMenu(new LLAdvancedTestMale(), "Advanced.TestMale");
- view_listener_t::addMenu(new LLAdvancedTestFemale(), "Advanced.TestFemale");
- view_listener_t::addMenu(new LLAdvancedTogglePG(), "Advanced.TogglePG");
-
- // Advanced > Character (toplevel)
- view_listener_t::addMenu(new LLAdvancedForceParamsToDefault(), "Advanced.ForceParamsToDefault");
- view_listener_t::addMenu(new LLAdvancedReloadVertexShader(), "Advanced.ReloadVertexShader");
- view_listener_t::addMenu(new LLAdvancedToggleAnimationInfo(), "Advanced.ToggleAnimationInfo");
- view_listener_t::addMenu(new LLAdvancedCheckAnimationInfo(), "Advanced.CheckAnimationInfo");
- view_listener_t::addMenu(new LLAdvancedToggleShowLookAt(), "Advanced.ToggleShowLookAt");
- view_listener_t::addMenu(new LLAdvancedCheckShowLookAt(), "Advanced.CheckShowLookAt");
- view_listener_t::addMenu(new LLAdvancedToggleShowPointAt(), "Advanced.ToggleShowPointAt");
- view_listener_t::addMenu(new LLAdvancedCheckShowPointAt(), "Advanced.CheckShowPointAt");
- view_listener_t::addMenu(new LLAdvancedToggleDebugJointUpdates(), "Advanced.ToggleDebugJointUpdates");
- view_listener_t::addMenu(new LLAdvancedCheckDebugJointUpdates(), "Advanced.CheckDebugJointUpdates");
- view_listener_t::addMenu(new LLAdvancedToggleDisableLOD(), "Advanced.ToggleDisableLOD");
- view_listener_t::addMenu(new LLAdvancedCheckDisableLOD(), "Advanced.CheckDisableLOD");
- view_listener_t::addMenu(new LLAdvancedToggleDebugCharacterVis(), "Advanced.ToggleDebugCharacterVis");
- view_listener_t::addMenu(new LLAdvancedCheckDebugCharacterVis(), "Advanced.CheckDebugCharacterVis");
- view_listener_t::addMenu(new LLAdvancedDumpAttachments(), "Advanced.DumpAttachments");
- view_listener_t::addMenu(new LLAdvancedRebakeTextures(), "Advanced.RebakeTextures");
- view_listener_t::addMenu(new LLAdvancedDebugAvatarTextures(), "Advanced.DebugAvatarTextures");
- view_listener_t::addMenu(new LLAdvancedDumpAvatarLocalTextures(), "Advanced.DumpAvatarLocalTextures");
- // Advanced > Network
- view_listener_t::addMenu(new LLAdvancedEnableMessageLog(), "Advanced.EnableMessageLog");
- view_listener_t::addMenu(new LLAdvancedDisableMessageLog(), "Advanced.DisableMessageLog");
- view_listener_t::addMenu(new LLAdvancedDropPacket(), "Advanced.DropPacket");
-
- // Advanced > Recorder
- view_listener_t::addMenu(new LLAdvancedAgentPilot(), "Advanced.AgentPilot");
- view_listener_t::addMenu(new LLAdvancedToggleAgentPilotLoop(), "Advanced.ToggleAgentPilotLoop");
- view_listener_t::addMenu(new LLAdvancedCheckAgentPilotLoop(), "Advanced.CheckAgentPilotLoop");
-
- // Advanced > Debugging
- view_listener_t::addMenu(new LLAdvancedForceErrorBreakpoint(), "Advanced.ForceErrorBreakpoint");
- view_listener_t::addMenu(new LLAdvancedForceErrorLlerror(), "Advanced.ForceErrorLlerror");
- view_listener_t::addMenu(new LLAdvancedForceErrorBadMemoryAccess(), "Advanced.ForceErrorBadMemoryAccess");
- view_listener_t::addMenu(new LLAdvancedForceErrorInfiniteLoop(), "Advanced.ForceErrorInfiniteLoop");
- view_listener_t::addMenu(new LLAdvancedForceErrorSoftwareException(), "Advanced.ForceErrorSoftwareException");
- view_listener_t::addMenu(new LLAdvancedForceErrorDriverCrash(), "Advanced.ForceErrorDriverCrash");
- view_listener_t::addMenu(new LLAdvancedForceErrorDisconnectViewer(), "Advanced.ForceErrorDisconnectViewer");
-
- // Advanced (toplevel)
- view_listener_t::addMenu(new LLAdvancedToggleShowObjectUpdates(), "Advanced.ToggleShowObjectUpdates");
- view_listener_t::addMenu(new LLAdvancedCheckShowObjectUpdates(), "Advanced.CheckShowObjectUpdates");
- view_listener_t::addMenu(new LLAdvancedCompressImage(), "Advanced.CompressImage");
- view_listener_t::addMenu(new LLAdvancedShowDebugSettings(), "Advanced.ShowDebugSettings");
- view_listener_t::addMenu(new LLAdvancedEnableViewAdminOptions(), "Advanced.EnableViewAdminOptions");
- view_listener_t::addMenu(new LLAdvancedToggleViewAdminOptions(), "Advanced.ToggleViewAdminOptions");
- view_listener_t::addMenu(new LLAdvancedCheckViewAdminOptions(), "Advanced.CheckViewAdminOptions");
- view_listener_t::addMenu(new LLAdvancedRequestAdminStatus(), "Advanced.RequestAdminStatus");
- view_listener_t::addMenu(new LLAdvancedLeaveAdminStatus(), "Advanced.LeaveAdminStatus");
-
-
- // Admin >Object
- view_listener_t::addMenu(new LLAdminForceTakeCopy(), "Admin.ForceTakeCopy");
- view_listener_t::addMenu(new LLAdminHandleObjectOwnerSelf(), "Admin.HandleObjectOwnerSelf");
- view_listener_t::addMenu(new LLAdminHandleObjectOwnerPermissive(), "Admin.HandleObjectOwnerPermissive");
- view_listener_t::addMenu(new LLAdminHandleForceDelete(), "Admin.HandleForceDelete");
- view_listener_t::addMenu(new LLAdminHandleObjectLock(), "Admin.HandleObjectLock");
- view_listener_t::addMenu(new LLAdminHandleObjectAssetIDs(), "Admin.HandleObjectAssetIDs");
-
- // Admin >Parcel
- view_listener_t::addMenu(new LLAdminHandleForceParcelOwnerToMe(), "Admin.HandleForceParcelOwnerToMe");
- view_listener_t::addMenu(new LLAdminHandleForceParcelToContent(), "Admin.HandleForceParcelToContent");
- view_listener_t::addMenu(new LLAdminHandleClaimPublicLand(), "Admin.HandleClaimPublicLand");
-
- // Admin >Region
- view_listener_t::addMenu(new LLAdminHandleRegionDumpTempAssetData(), "Admin.HandleRegionDumpTempAssetData");
- // Admin top level
- view_listener_t::addMenu(new LLAdminOnSaveState(), "Admin.OnSaveState");
-
- // Self context menu
- view_listener_t::addMenu(new LLSelfStandUp(), "Self.StandUp");
- enable.add("Self.EnableStandUp", boost::bind(&enable_standup_self));
- view_listener_t::addMenu(new LLSelfSitDown(), "Self.SitDown");
- enable.add("Self.EnableSitDown", boost::bind(&enable_sitdown_self));
- view_listener_t::addMenu(new LLSelfRemoveAllAttachments(), "Self.RemoveAllAttachments");
-
- view_listener_t::addMenu(new LLSelfEnableRemoveAllAttachments(), "Self.EnableRemoveAllAttachments");
-
- // we don't use boost::bind directly to delay side tray construction
- view_listener_t::addMenu( new LLTogglePanelPeopleTab(), "SideTray.PanelPeopleTab");
-
- // Avatar pie menu
- view_listener_t::addMenu(new LLObjectMute(), "Avatar.Mute");
- view_listener_t::addMenu(new LLAvatarAddFriend(), "Avatar.AddFriend");
- view_listener_t::addMenu(new LLAvatarAddContact(), "Avatar.AddContact");
- commit.add("Avatar.Freeze", boost::bind(&handle_avatar_freeze, LLSD()));
- view_listener_t::addMenu(new LLAvatarDebug(), "Avatar.Debug");
- view_listener_t::addMenu(new LLAvatarVisibleDebug(), "Avatar.VisibleDebug");
- view_listener_t::addMenu(new LLAvatarInviteToGroup(), "Avatar.InviteToGroup");
- commit.add("Avatar.Eject", boost::bind(&handle_avatar_eject, LLSD()));
- commit.add("Avatar.ShowInspector", boost::bind(&handle_avatar_show_inspector));
- view_listener_t::addMenu(new LLAvatarSendIM(), "Avatar.SendIM");
- view_listener_t::addMenu(new LLAvatarCall(), "Avatar.Call");
- enable.add("Avatar.EnableCall", boost::bind(&LLAvatarActions::canCall));
- view_listener_t::addMenu(new LLAvatarReportAbuse(), "Avatar.ReportAbuse");
-
- view_listener_t::addMenu(new LLAvatarEnableAddFriend(), "Avatar.EnableAddFriend");
- enable.add("Avatar.EnableFreezeEject", boost::bind(&enable_freeze_eject, _2));
-
- // Object pie menu
- view_listener_t::addMenu(new LLObjectBuild(), "Object.Build");
- commit.add("Object.Touch", boost::bind(&handle_object_touch));
- commit.add("Object.SitOrStand", boost::bind(&handle_object_sit_or_stand));
- commit.add("Object.Delete", boost::bind(&handle_object_delete));
- view_listener_t::addMenu(new LLObjectAttachToAvatar(true), "Object.AttachToAvatar");
- view_listener_t::addMenu(new LLObjectAttachToAvatar(false), "Object.AttachAddToAvatar");
- view_listener_t::addMenu(new LLObjectReturn(), "Object.Return");
- view_listener_t::addMenu(new LLObjectReportAbuse(), "Object.ReportAbuse");
- view_listener_t::addMenu(new LLObjectMute(), "Object.Mute");
-
- enable.add("Object.VisibleTake", boost::bind(&visible_take_object));
- enable.add("Object.VisibleBuy", boost::bind(&visible_buy_object));
-
- commit.add("Object.Buy", boost::bind(&handle_buy));
- commit.add("Object.Edit", boost::bind(&handle_object_edit));
- commit.add("Object.Inspect", boost::bind(&handle_object_inspect));
- commit.add("Object.Open", boost::bind(&handle_object_open));
- commit.add("Object.Take", boost::bind(&handle_take));
- commit.add("Object.ShowInspector", boost::bind(&handle_object_show_inspector));
- enable.add("Object.EnableOpen", boost::bind(&enable_object_open));
- enable.add("Object.EnableTouch", boost::bind(&enable_object_touch, _1));
- enable.add("Object.EnableDelete", boost::bind(&enable_object_delete));
- enable.add("Object.EnableWear", boost::bind(&object_selected_and_point_valid));
-
- enable.add("Object.EnableStandUp", boost::bind(&enable_object_stand_up));
- enable.add("Object.EnableSit", boost::bind(&enable_object_sit, _1));
-
- view_listener_t::addMenu(new LLObjectEnableReturn(), "Object.EnableReturn");
- view_listener_t::addMenu(new LLObjectEnableReportAbuse(), "Object.EnableReportAbuse");
-
- enable.add("Avatar.EnableMute", boost::bind(&enable_object_mute));
- enable.add("Object.EnableMute", boost::bind(&enable_object_mute));
- enable.add("Object.EnableBuy", boost::bind(&enable_buy_object));
- commit.add("Object.ZoomIn", boost::bind(&handle_look_at_selection, "zoom"));
-
- // Attachment pie menu
- enable.add("Attachment.Label", boost::bind(&onEnableAttachmentLabel, _1, _2));
- view_listener_t::addMenu(new LLAttachmentDrop(), "Attachment.Drop");
- view_listener_t::addMenu(new LLAttachmentDetachFromPoint(), "Attachment.DetachFromPoint");
- view_listener_t::addMenu(new LLAttachmentDetach(), "Attachment.Detach");
- view_listener_t::addMenu(new LLAttachmentPointFilled(), "Attachment.PointFilled");
- view_listener_t::addMenu(new LLAttachmentEnableDrop(), "Attachment.EnableDrop");
- view_listener_t::addMenu(new LLAttachmentEnableDetach(), "Attachment.EnableDetach");
-
- // Land pie menu
- view_listener_t::addMenu(new LLLandBuild(), "Land.Build");
- view_listener_t::addMenu(new LLLandSit(), "Land.Sit");
- view_listener_t::addMenu(new LLLandBuyPass(), "Land.BuyPass");
- view_listener_t::addMenu(new LLLandEdit(), "Land.Edit");
-
- view_listener_t::addMenu(new LLLandEnableBuyPass(), "Land.EnableBuyPass");
- commit.add("Land.Buy", boost::bind(&handle_buy_land));
-
- // Generic actions
- commit.add("ReportAbuse", boost::bind(&handle_report_abuse));
- commit.add("BuyCurrency", boost::bind(&handle_buy_currency));
- view_listener_t::addMenu(new LLShowHelp(), "ShowHelp");
- view_listener_t::addMenu(new LLToggleHelp(), "ToggleHelp");
- view_listener_t::addMenu(new LLPromptShowURL(), "PromptShowURL");
- view_listener_t::addMenu(new LLShowAgentProfile(), "ShowAgentProfile");
- view_listener_t::addMenu(new LLToggleAgentProfile(), "ToggleAgentProfile");
- view_listener_t::addMenu(new LLToggleControl(), "ToggleControl");
- view_listener_t::addMenu(new LLCheckControl(), "CheckControl");
- view_listener_t::addMenu(new LLGoToObject(), "GoToObject");
- commit.add("PayObject", boost::bind(&handle_give_money_dialog));
-
- enable.add("EnablePayObject", boost::bind(&enable_pay_object));
- enable.add("EnablePayAvatar", boost::bind(&enable_pay_avatar));
- enable.add("EnableEdit", boost::bind(&enable_object_edit));
- enable.add("VisibleBuild", boost::bind(&enable_object_build));
-
- view_listener_t::addMenu(new LLFloaterVisible(), "FloaterVisible");
- view_listener_t::addMenu(new LLShowSidetrayPanel(), "ShowSidetrayPanel");
- view_listener_t::addMenu(new LLSidetrayPanelVisible(), "SidetrayPanelVisible");
- view_listener_t::addMenu(new LLSomethingSelected(), "SomethingSelected");
- view_listener_t::addMenu(new LLSomethingSelectedNoHUD(), "SomethingSelectedNoHUD");
- view_listener_t::addMenu(new LLEditableSelected(), "EditableSelected");
- view_listener_t::addMenu(new LLEditableSelectedMono(), "EditableSelectedMono");
-
- view_listener_t::addMenu(new LLToggleUIHints(), "ToggleUIHints");
-
- commit.add("Destination.show", boost::bind(&toggle_destination_and_avatar_picker, 0));
- commit.add("Avatar.show", boost::bind(&toggle_destination_and_avatar_picker, 1));
-}
+/**
+ * @file llviewermenu.cpp
+ * @brief Builds menus out of items.
+ *
+ * $LicenseInfo:firstyear=2002&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h"
+#include "llviewermenu.h"
+
+// linden library includes
+#include "llavatarnamecache.h" // IDEVO
+#include "llfloaterreg.h"
+#include "llcombobox.h"
+#include "llinventorypanel.h"
+#include "llnotifications.h"
+#include "llnotificationsutil.h"
+
+// newview includes
+#include "llagent.h"
+#include "llagentcamera.h"
+#include "llagentwearables.h"
+#include "llagentpilot.h"
+#include "llbottomtray.h"
+#include "llcompilequeue.h"
+#include "llconsole.h"
+#include "lldebugview.h"
+#include "llfilepicker.h"
+#include "llfirstuse.h"
+#include "llfloaterbuy.h"
+#include "llfloaterbuycontents.h"
+#include "llbuycurrencyhtml.h"
+#include "llfloatergodtools.h"
+#include "llfloaterinventory.h"
+#include "llfloaterland.h"
+#include "llfloaterpay.h"
+#include "llfloaterreporter.h"
+#include "llfloatersearch.h"
+#include "llfloaterscriptdebug.h"
+#include "llfloatersnapshot.h"
+#include "llfloatertools.h"
+#include "llfloaterworldmap.h"
+#include "llavataractions.h"
+#include "lllandmarkactions.h"
+#include "llgroupmgr.h"
+#include "lltooltip.h"
+#include "llhints.h"
+#include "llhudeffecttrail.h"
+#include "llhudmanager.h"
+#include "llimview.h"
+#include "llinventorybridge.h"
+#include "llinventorydefines.h"
+#include "llinventoryfunctions.h"
+#include "llpanellogin.h"
+#include "llpanelblockedlist.h"
+#include "llmenucommands.h"
+#include "llmoveview.h"
+#include "llparcel.h"
+#include "llrootview.h"
+#include "llselectmgr.h"
+#include "llsidetray.h"
+#include "llstatusbar.h"
+#include "lltextureview.h"
+#include "lltoolcomp.h"
+#include "lltoolmgr.h"
+#include "lltoolpie.h"
+#include "lltoolselectland.h"
+#include "lltrans.h"
+#include "llviewergenericmessage.h"
+#include "llviewerhelp.h"
+#include "llviewermenufile.h" // init_menu_file()
+#include "llviewermessage.h"
+#include "llviewernetwork.h"
+#include "llviewerobjectlist.h"
+#include "llviewerparcelmgr.h"
+#include "llviewerstats.h"
+#include "llvoavatarself.h"
+#include "llworldmap.h"
+#include "pipeline.h"
+#include "llviewerjoystick.h"
+#include "llwlanimator.h"
+#include "llwlparammanager.h"
+#include "llfloatercamera.h"
+#include "lluilistener.h"
+#include "llappearancemgr.h"
+#include "lltrans.h"
+#include "lleconomy.h"
+#include "boost/unordered_map.hpp"
+
+using namespace LLVOAvatarDefines;
+
+static boost::unordered_map<std::string, LLStringExplicit> sDefaultItemLabels;
+
+BOOL enable_land_build(void*);
+BOOL enable_object_build(void*);
+
+LLVOAvatar* find_avatar_from_object( LLViewerObject* object );
+LLVOAvatar* find_avatar_from_object( const LLUUID& object_id );
+
+void handle_test_load_url(void*);
+
+//
+// Evil hackish imported globals
+
+//extern BOOL gHideSelectedObjects;
+//extern BOOL gAllowSelectAvatar;
+//extern BOOL gDebugAvatarRotation;
+extern BOOL gDebugClicks;
+extern BOOL gDebugWindowProc;
+//extern BOOL gDebugTextEditorTips;
+//extern BOOL gDebugSelectMgr;
+
+//
+// Globals
+//
+
+LLMenuBarGL *gMenuBarView = NULL;
+LLViewerMenuHolderGL *gMenuHolder = NULL;
+LLMenuGL *gPopupMenuView = NULL;
+LLMenuGL *gEditMenu = NULL;
+LLMenuBarGL *gLoginMenuBarView = NULL;
+
+// Pie menus
+LLContextMenu *gMenuAvatarSelf = NULL;
+LLContextMenu *gMenuAvatarOther = NULL;
+LLContextMenu *gMenuObject = NULL;
+LLContextMenu *gMenuAttachmentSelf = NULL;
+LLContextMenu *gMenuAttachmentOther = NULL;
+LLContextMenu *gMenuLand = NULL;
+
+const std::string SAVE_INTO_INVENTORY("Save Object Back to My Inventory");
+const std::string SAVE_INTO_TASK_INVENTORY("Save Object Back to Object Contents");
+
+LLMenuGL* gAttachSubMenu = NULL;
+LLMenuGL* gDetachSubMenu = NULL;
+LLMenuGL* gTakeOffClothes = NULL;
+LLContextMenu* gAttachScreenPieMenu = NULL;
+LLContextMenu* gAttachPieMenu = NULL;
+LLContextMenu* gAttachBodyPartPieMenus[8];
+LLContextMenu* gDetachPieMenu = NULL;
+LLContextMenu* gDetachScreenPieMenu = NULL;
+LLContextMenu* gDetachBodyPartPieMenus[8];
+
+LLMenuItemCallGL* gAFKMenu = NULL;
+LLMenuItemCallGL* gBusyMenu = NULL;
+
+//
+// Local prototypes
+
+// File Menu
+void handle_compress_image(void*);
+
+
+// Edit menu
+void handle_dump_group_info(void *);
+void handle_dump_capabilities_info(void *);
+
+// Advanced->Consoles menu
+void handle_region_dump_settings(void*);
+void handle_region_dump_temp_asset_data(void*);
+void handle_region_clear_temp_asset_data(void*);
+
+// Object pie menu
+BOOL sitting_on_selection();
+
+void near_sit_object();
+//void label_sit_or_stand(std::string& label, void*);
+// buy and take alias into the same UI positions, so these
+// declarations handle this mess.
+BOOL is_selection_buy_not_take();
+S32 selection_price();
+BOOL enable_take();
+void handle_take();
+void handle_object_show_inspector();
+void handle_avatar_show_inspector();
+bool confirm_take(const LLSD& notification, const LLSD& response);
+
+void handle_buy_object(LLSaleInfo sale_info);
+void handle_buy_contents(LLSaleInfo sale_info);
+
+// Land pie menu
+void near_sit_down_point(BOOL success, void *);
+
+// Avatar pie menu
+
+// Debug menu
+
+
+void velocity_interpolate( void* );
+
+void handle_rebake_textures(void*);
+BOOL check_admin_override(void*);
+void handle_admin_override_toggle(void*);
+#ifdef TOGGLE_HACKED_GODLIKE_VIEWER
+void handle_toggle_hacked_godmode(void*);
+BOOL check_toggle_hacked_godmode(void*);
+bool enable_toggle_hacked_godmode(void*);
+#endif
+
+void toggle_show_xui_names(void *);
+BOOL check_show_xui_names(void *);
+
+// Debug UI
+
+void handle_buy_currency_test(void*);
+
+void handle_god_mode(void*);
+
+// God menu
+void handle_leave_god_mode(void*);
+
+
+void handle_reset_view();
+
+void handle_duplicate_in_place(void*);
+
+
+void handle_object_owner_self(void*);
+void handle_object_owner_permissive(void*);
+void handle_object_lock(void*);
+void handle_object_asset_ids(void*);
+void force_take_copy(void*);
+#ifdef _CORY_TESTING
+void force_export_copy(void*);
+void force_import_geometry(void*);
+#endif
+
+void handle_force_parcel_owner_to_me(void*);
+void handle_force_parcel_to_content(void*);
+void handle_claim_public_land(void*);
+
+void handle_god_request_avatar_geometry(void *); // Hack for easy testing of new avatar geometry
+void reload_vertex_shader(void *);
+void handle_disconnect_viewer(void *);
+
+void force_error_breakpoint(void *);
+void force_error_llerror(void *);
+void force_error_bad_memory_access(void *);
+void force_error_infinite_loop(void *);
+void force_error_software_exception(void *);
+void force_error_driver_crash(void *);
+
+void handle_force_delete(void*);
+void print_object_info(void*);
+void print_agent_nvpairs(void*);
+void toggle_debug_menus(void*);
+void upload_done_callback(const LLUUID& uuid, void* user_data, S32 result, LLExtStat ext_status);
+void dump_select_mgr(void*);
+
+void dump_inventory(void*);
+void toggle_visibility(void*);
+BOOL get_visibility(void*);
+
+// Avatar Pie menu
+void request_friendship(const LLUUID& agent_id);
+
+// Tools menu
+void handle_selected_texture_info(void*);
+
+void handle_dump_followcam(void*);
+void handle_viewer_enable_message_log(void*);
+void handle_viewer_disable_message_log(void*);
+
+BOOL enable_buy_land(void*);
+
+// Help menu
+
+void handle_test_male(void *);
+void handle_test_female(void *);
+void handle_toggle_pg(void*);
+void handle_dump_attachments(void *);
+void handle_dump_avatar_local_textures(void*);
+void handle_debug_avatar_textures(void*);
+void handle_grab_baked_texture(void*);
+BOOL enable_grab_baked_texture(void*);
+void handle_dump_region_object_cache(void*);
+
+BOOL enable_save_into_inventory(void*);
+BOOL enable_save_into_task_inventory(void*);
+
+BOOL enable_detach(const LLSD& = LLSD());
+void menu_toggle_attached_lights(void* user_data);
+void menu_toggle_attached_particles(void* user_data);
+
+class LLMenuParcelObserver : public LLParcelObserver
+{
+public:
+ LLMenuParcelObserver();
+ ~LLMenuParcelObserver();
+ virtual void changed();
+};
+
+static LLMenuParcelObserver* gMenuParcelObserver = NULL;
+
+static LLUIListener sUIListener;
+
+LLMenuParcelObserver::LLMenuParcelObserver()
+{
+ LLViewerParcelMgr::getInstance()->addObserver(this);
+}
+
+LLMenuParcelObserver::~LLMenuParcelObserver()
+{
+ LLViewerParcelMgr::getInstance()->removeObserver(this);
+}
+
+void LLMenuParcelObserver::changed()
+{
+ gMenuHolder->childSetEnabled("Land Buy Pass", LLPanelLandGeneral::enableBuyPass(NULL));
+
+ BOOL buyable = enable_buy_land(NULL);
+ gMenuHolder->childSetEnabled("Land Buy", buyable);
+ gMenuHolder->childSetEnabled("Buy Land...", buyable);
+}
+
+
+void initialize_menus();
+
+//-----------------------------------------------------------------------------
+// Initialize main menus
+//
+// HOW TO NAME MENUS:
+//
+// First Letter Of Each Word Is Capitalized, Even At Or And
+//
+// Items that lead to dialog boxes end in "..."
+//
+// Break up groups of more than 6 items with separators
+//-----------------------------------------------------------------------------
+
+void set_underclothes_menu_options()
+{
+ if (gMenuHolder && gAgent.isTeen())
+ {
+ gMenuHolder->getChild<LLView>("Self Underpants")->setVisible(FALSE);
+ gMenuHolder->getChild<LLView>("Self Undershirt")->setVisible(FALSE);
+ }
+ if (gMenuBarView && gAgent.isTeen())
+ {
+ gMenuBarView->getChild<LLView>("Menu Underpants")->setVisible(FALSE);
+ gMenuBarView->getChild<LLView>("Menu Undershirt")->setVisible(FALSE);
+ }
+}
+
+void init_menus()
+{
+ S32 top = gViewerWindow->getRootView()->getRect().getHeight();
+
+ // Initialize actions
+ initialize_menus();
+
+ ///
+ /// Popup menu
+ ///
+ /// The popup menu is now populated by the show_context_menu()
+ /// method.
+
+ LLMenuGL::Params menu_params;
+ menu_params.name = "Popup";
+ menu_params.visible = false;
+ gPopupMenuView = LLUICtrlFactory::create<LLMenuGL>(menu_params);
+ gMenuHolder->addChild( gPopupMenuView );
+
+ ///
+ /// Context menus
+ ///
+
+ const widget_registry_t& registry =
+ LLViewerMenuHolderGL::child_registry_t::instance();
+ gEditMenu = LLUICtrlFactory::createFromFile<LLMenuGL>("menu_edit.xml", gMenuHolder, registry);
+ gMenuAvatarSelf = LLUICtrlFactory::createFromFile<LLContextMenu>(
+ "menu_avatar_self.xml", gMenuHolder, registry);
+ gMenuAvatarOther = LLUICtrlFactory::createFromFile<LLContextMenu>(
+ "menu_avatar_other.xml", gMenuHolder, registry);
+
+ gDetachScreenPieMenu = gMenuHolder->getChild<LLContextMenu>("Object Detach HUD", true);
+ gDetachPieMenu = gMenuHolder->getChild<LLContextMenu>("Object Detach", true);
+
+ gMenuObject = LLUICtrlFactory::createFromFile<LLContextMenu>(
+ "menu_object.xml", gMenuHolder, registry);
+
+ gAttachScreenPieMenu = gMenuHolder->getChild<LLContextMenu>("Object Attach HUD");
+ gAttachPieMenu = gMenuHolder->getChild<LLContextMenu>("Object Attach");
+
+ gMenuAttachmentSelf = LLUICtrlFactory::createFromFile<LLContextMenu>(
+ "menu_attachment_self.xml", gMenuHolder, registry);
+ gMenuAttachmentOther = LLUICtrlFactory::createFromFile<LLContextMenu>(
+ "menu_attachment_other.xml", gMenuHolder, registry);
+
+ gMenuLand = LLUICtrlFactory::createFromFile<LLContextMenu>(
+ "menu_land.xml", gMenuHolder, registry);
+
+ ///
+ /// set up the colors
+ ///
+ LLColor4 color;
+
+ LLColor4 context_menu_color = LLUIColorTable::instance().getColor("MenuPopupBgColor");
+
+ gMenuAvatarSelf->setBackgroundColor( context_menu_color );
+ gMenuAvatarOther->setBackgroundColor( context_menu_color );
+ gMenuObject->setBackgroundColor( context_menu_color );
+ gMenuAttachmentSelf->setBackgroundColor( context_menu_color );
+ gMenuAttachmentOther->setBackgroundColor( context_menu_color );
+
+ gMenuLand->setBackgroundColor( context_menu_color );
+
+ color = LLUIColorTable::instance().getColor( "MenuPopupBgColor" );
+ gPopupMenuView->setBackgroundColor( color );
+
+ // If we are not in production, use a different color to make it apparent.
+ if (LLGridManager::getInstance()->isInProductionGrid())
+ {
+ color = LLUIColorTable::instance().getColor( "MenuBarBgColor" );
+ }
+ else
+ {
+ color = LLUIColorTable::instance().getColor( "MenuNonProductionBgColor" );
+ }
+ gMenuBarView = LLUICtrlFactory::getInstance()->createFromFile<LLMenuBarGL>("menu_viewer.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
+ gMenuBarView->setRect(LLRect(0, top, 0, top - MENU_BAR_HEIGHT));
+ gMenuBarView->setBackgroundColor( color );
+
+ LLView* menu_bar_holder = gViewerWindow->getRootView()->getChildView("menu_bar_holder");
+ menu_bar_holder->addChild(gMenuBarView);
+
+ gViewerWindow->setMenuBackgroundColor(false,
+ LLGridManager::getInstance()->isInProductionGrid());
+
+ // Assume L$10 for now, the server will tell us the real cost at login
+ // *TODO:Also fix cost in llfolderview.cpp for Inventory menus
+ const std::string upload_cost("10");
+ gMenuHolder->childSetLabelArg("Upload Image", "[COST]", upload_cost);
+ gMenuHolder->childSetLabelArg("Upload Sound", "[COST]", upload_cost);
+ gMenuHolder->childSetLabelArg("Upload Animation", "[COST]", upload_cost);
+ gMenuHolder->childSetLabelArg("Bulk Upload", "[COST]", upload_cost);
+
+ gAFKMenu = gMenuBarView->getChild<LLMenuItemCallGL>("Set Away", TRUE);
+ gBusyMenu = gMenuBarView->getChild<LLMenuItemCallGL>("Set Busy", TRUE);
+ gAttachSubMenu = gMenuBarView->findChildMenuByName("Attach Object", TRUE);
+ gDetachSubMenu = gMenuBarView->findChildMenuByName("Detach Object", TRUE);
+
+#if !MEM_TRACK_MEM
+ // Don't display the Memory console menu if the feature is turned off
+ LLMenuItemCheckGL *memoryMenu = gMenuBarView->getChild<LLMenuItemCheckGL>("Memory", TRUE);
+ if (memoryMenu)
+ {
+ memoryMenu->setVisible(FALSE);
+ }
+#endif
+
+ gMenuBarView->createJumpKeys();
+
+ // Let land based option enable when parcel changes
+ gMenuParcelObserver = new LLMenuParcelObserver();
+
+ gLoginMenuBarView = LLUICtrlFactory::getInstance()->createFromFile<LLMenuBarGL>("menu_login.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
+ gLoginMenuBarView->arrangeAndClear();
+ LLRect menuBarRect = gLoginMenuBarView->getRect();
+ menuBarRect.setLeftTopAndSize(0, menu_bar_holder->getRect().getHeight(), menuBarRect.getWidth(), menuBarRect.getHeight());
+ gLoginMenuBarView->setRect(menuBarRect);
+ gLoginMenuBarView->setBackgroundColor( color );
+ menu_bar_holder->addChild(gLoginMenuBarView);
+
+ // tooltips are on top of EVERYTHING, including menus
+ gViewerWindow->getRootView()->sendChildToFront(gToolTipView);
+}
+
+///////////////////
+// SHOW CONSOLES //
+///////////////////
+
+
+class LLAdvancedToggleConsole : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string console_type = userdata.asString();
+ if ("texture" == console_type)
+ {
+ toggle_visibility( (void*)gTextureView );
+ }
+ else if ("debug" == console_type)
+ {
+ toggle_visibility( (void*)static_cast<LLUICtrl*>(gDebugView->mDebugConsolep));
+ }
+ else if (gTextureSizeView && "texture size" == console_type)
+ {
+ toggle_visibility( (void*)gTextureSizeView );
+ }
+ else if (gTextureCategoryView && "texture category" == console_type)
+ {
+ toggle_visibility( (void*)gTextureCategoryView );
+ }
+ else if ("fast timers" == console_type)
+ {
+ toggle_visibility( (void*)gDebugView->mFastTimerView );
+ }
+#if MEM_TRACK_MEM
+ else if ("memory view" == console_type)
+ {
+ toggle_visibility( (void*)gDebugView->mMemoryView );
+ }
+#endif
+ return true;
+ }
+};
+class LLAdvancedCheckConsole : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string console_type = userdata.asString();
+ bool new_value = false;
+ if ("texture" == console_type)
+ {
+ new_value = get_visibility( (void*)gTextureView );
+ }
+ else if ("debug" == console_type)
+ {
+ new_value = get_visibility( (void*)((LLView*)gDebugView->mDebugConsolep) );
+ }
+ else if (gTextureSizeView && "texture size" == console_type)
+ {
+ new_value = get_visibility( (void*)gTextureSizeView );
+ }
+ else if (gTextureCategoryView && "texture category" == console_type)
+ {
+ new_value = get_visibility( (void*)gTextureCategoryView );
+ }
+ else if ("fast timers" == console_type)
+ {
+ new_value = get_visibility( (void*)gDebugView->mFastTimerView );
+ }
+#if MEM_TRACK_MEM
+ else if ("memory view" == console_type)
+ {
+ new_value = get_visibility( (void*)gDebugView->mMemoryView );
+ }
+#endif
+
+ return new_value;
+ }
+};
+
+
+//////////////////////////
+// DUMP INFO TO CONSOLE //
+//////////////////////////
+
+
+class LLAdvancedDumpInfoToConsole : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string info_type = userdata.asString();
+ if ("region" == info_type)
+ {
+ handle_region_dump_settings(NULL);
+ }
+ else if ("group" == info_type)
+ {
+ handle_dump_group_info(NULL);
+ }
+ else if ("capabilities" == info_type)
+ {
+ handle_dump_capabilities_info(NULL);
+ }
+ return true;
+ }
+};
+
+
+//////////////
+// HUD INFO //
+//////////////
+
+
+class LLAdvancedToggleHUDInfo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string info_type = userdata.asString();
+
+ if ("camera" == info_type)
+ {
+ gDisplayCameraPos = !(gDisplayCameraPos);
+ }
+ else if ("wind" == info_type)
+ {
+ gDisplayWindInfo = !(gDisplayWindInfo);
+ }
+ else if ("fov" == info_type)
+ {
+ gDisplayFOV = !(gDisplayFOV);
+ }
+ else if ("badge" == info_type)
+ {
+ gDisplayBadge = !(gDisplayBadge);
+ }
+ return true;
+ }
+};
+
+class LLAdvancedCheckHUDInfo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string info_type = userdata.asString();
+ bool new_value = false;
+ if ("camera" == info_type)
+ {
+ new_value = gDisplayCameraPos;
+ }
+ else if ("wind" == info_type)
+ {
+ new_value = gDisplayWindInfo;
+ }
+ else if ("fov" == info_type)
+ {
+ new_value = gDisplayFOV;
+ }
+ else if ("badge" == info_type)
+ {
+ new_value = gDisplayBadge;
+ }
+ return new_value;
+ }
+};
+
+
+//////////////
+// FLYING //
+//////////////
+
+class LLAdvancedAgentFlyingInfo : public view_listener_t
+{
+ bool handleEvent(const LLSD&)
+ {
+ return gAgent.getFlying();
+ }
+};
+
+
+///////////////////////
+// CLEAR GROUP CACHE //
+///////////////////////
+
+class LLAdvancedClearGroupCache : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLGroupMgr::debugClearAllGroups(NULL);
+ return true;
+ }
+};
+
+
+
+
+/////////////////
+// RENDER TYPE //
+/////////////////
+U32 render_type_from_string(std::string render_type)
+{
+ if ("simple" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_SIMPLE;
+ }
+ else if ("alpha" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_ALPHA;
+ }
+ else if ("tree" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_TREE;
+ }
+ else if ("character" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_AVATAR;
+ }
+ else if ("surfacePatch" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_TERRAIN;
+ }
+ else if ("sky" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_SKY;
+ }
+ else if ("water" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_WATER;
+ }
+ else if ("ground" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_GROUND;
+ }
+ else if ("volume" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_VOLUME;
+ }
+ else if ("grass" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_GRASS;
+ }
+ else if ("clouds" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_CLOUDS;
+ }
+ else if ("particles" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_PARTICLES;
+ }
+ else if ("bump" == render_type)
+ {
+ return LLPipeline::RENDER_TYPE_BUMP;
+ }
+ else
+ {
+ return 0;
+ }
+}
+
+
+class LLAdvancedToggleRenderType : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ U32 render_type = render_type_from_string( userdata.asString() );
+ if ( render_type != 0 )
+ {
+ LLPipeline::toggleRenderTypeControl( (void*)render_type );
+ }
+ return true;
+ }
+};
+
+
+class LLAdvancedCheckRenderType : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ U32 render_type = render_type_from_string( userdata.asString() );
+ bool new_value = false;
+
+ if ( render_type != 0 )
+ {
+ new_value = LLPipeline::hasRenderTypeControl( (void*)render_type );
+ }
+
+ return new_value;
+ }
+};
+
+
+/////////////
+// FEATURE //
+/////////////
+U32 feature_from_string(std::string feature)
+{
+ if ("ui" == feature)
+ {
+ return LLPipeline::RENDER_DEBUG_FEATURE_UI;
+ }
+ else if ("selected" == feature)
+ {
+ return LLPipeline::RENDER_DEBUG_FEATURE_SELECTED;
+ }
+ else if ("highlighted" == feature)
+ {
+ return LLPipeline::RENDER_DEBUG_FEATURE_HIGHLIGHTED;
+ }
+ else if ("dynamic textures" == feature)
+ {
+ return LLPipeline::RENDER_DEBUG_FEATURE_DYNAMIC_TEXTURES;
+ }
+ else if ("foot shadows" == feature)
+ {
+ return LLPipeline::RENDER_DEBUG_FEATURE_FOOT_SHADOWS;
+ }
+ else if ("fog" == feature)
+ {
+ return LLPipeline::RENDER_DEBUG_FEATURE_FOG;
+ }
+ else if ("fr info" == feature)
+ {
+ return LLPipeline::RENDER_DEBUG_FEATURE_FR_INFO;
+ }
+ else if ("flexible" == feature)
+ {
+ return LLPipeline::RENDER_DEBUG_FEATURE_FLEXIBLE;
+ }
+ else
+ {
+ return 0;
+ }
+};
+
+
+class LLAdvancedToggleFeature : public view_listener_t{
+ bool handleEvent(const LLSD& userdata)
+ {
+ U32 feature = feature_from_string( userdata.asString() );
+ if ( feature != 0 )
+ {
+ LLPipeline::toggleRenderDebugFeature( (void*)feature );
+ }
+ return true;
+ }
+};
+
+class LLAdvancedCheckFeature : public view_listener_t
+{bool handleEvent(const LLSD& userdata)
+{
+ U32 feature = feature_from_string( userdata.asString() );
+ bool new_value = false;
+
+ if ( feature != 0 )
+ {
+ new_value = LLPipeline::toggleRenderDebugFeatureControl( (void*)feature );
+ }
+
+ return new_value;
+}
+};
+
+void toggle_destination_and_avatar_picker(const LLSD& show)
+{
+ S32 panel_idx = show.isDefined() ? show.asInteger() : -1;
+ LLView* container = gViewerWindow->getRootView()->getChildView("avatar_picker_and_destination_guide_container");
+ LLMediaCtrl* destinations = container->findChild<LLMediaCtrl>("destination_guide_contents");
+ LLMediaCtrl* avatar_picker = container->findChild<LLMediaCtrl>("avatar_picker_contents");
+ LLButton* avatar_btn = gViewerWindow->getRootView()->getChildView("bottom_tray")->getChild<LLButton>("avatar_btn");
+ LLButton* destination_btn = gViewerWindow->getRootView()->getChildView("bottom_tray")->getChild<LLButton>("destination_btn");
+
+ switch(panel_idx)
+ {
+ case 0:
+ container->setVisible(true);
+ destinations->setVisible(true);
+ avatar_picker->setVisible(false);
+ LLFirstUse::notUsingDestinationGuide(false);
+ avatar_btn->setToggleState(false);
+ destination_btn->setToggleState(true);
+ break;
+ case 1:
+ container->setVisible(true);
+ destinations->setVisible(false);
+ avatar_picker->setVisible(true);
+ avatar_btn->setToggleState(true);
+ destination_btn->setToggleState(false);
+ break;
+ default:
+ container->setVisible(false);
+ destinations->setVisible(false);
+ avatar_picker->setVisible(false);
+ avatar_btn->setToggleState(false);
+ destination_btn->setToggleState(false);
+ break;
+ }
+};
+
+
+//////////////////
+// INFO DISPLAY //
+//////////////////
+U32 info_display_from_string(std::string info_display)
+{
+ if ("verify" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_VERIFY;
+ }
+ else if ("bboxes" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_BBOXES;
+ }
+ else if ("normals" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_NORMALS;
+ }
+ else if ("points" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_POINTS;
+ }
+ else if ("octree" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_OCTREE;
+ }
+ else if ("shadow frusta" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_SHADOW_FRUSTA;
+ }
+ else if ("physics shapes" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_PHYSICS_SHAPES;
+ }
+ else if ("occlusion" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_OCCLUSION;
+ }
+ else if ("render batches" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_BATCH_SIZE;
+ }
+ else if ("update type" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_UPDATE_TYPE;
+ }
+ else if ("texture anim" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_TEXTURE_ANIM;
+ }
+ else if ("texture priority" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_TEXTURE_PRIORITY;
+ }
+ else if ("shame" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_SHAME;
+ }
+ else if ("texture area" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_TEXTURE_AREA;
+ }
+ else if ("face area" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_FACE_AREA;
+ }
+ else if ("lod info" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_LOD_INFO;
+ }
+ else if ("build queue" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_BUILD_QUEUE;
+ }
+ else if ("lights" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_LIGHTS;
+ }
+ else if ("particles" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_PARTICLES;
+ }
+ else if ("composition" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_COMPOSITION;
+ }
+ else if ("glow" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_GLOW;
+ }
+ else if ("collision skeleton" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_AVATAR_VOLUME;
+ }
+ else if ("raycast" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_RAYCAST;
+ }
+ else if ("agent target" == info_display)
+ {
+ return LLPipeline::RENDER_DEBUG_AGENT_TARGET;
+ }
+ else
+ {
+ return 0;
+ }
+};
+
+class LLAdvancedToggleInfoDisplay : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ U32 info_display = info_display_from_string( userdata.asString() );
+
+ if ( info_display != 0 )
+ {
+ LLPipeline::toggleRenderDebug( (void*)info_display );
+ }
+
+ return true;
+ }
+};
+
+
+class LLAdvancedCheckInfoDisplay : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ U32 info_display = info_display_from_string( userdata.asString() );
+ bool new_value = false;
+
+ if ( info_display != 0 )
+ {
+ new_value = LLPipeline::toggleRenderDebugControl( (void*)info_display );
+ }
+
+ return new_value;
+ }
+};
+
+
+///////////////////////////
+//// RANDOMIZE FRAMERATE //
+///////////////////////////
+
+
+class LLAdvancedToggleRandomizeFramerate : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gRandomizeFramerate = !(gRandomizeFramerate);
+ return true;
+ }
+};
+
+class LLAdvancedCheckRandomizeFramerate : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gRandomizeFramerate;
+ return new_value;
+ }
+};
+
+void run_vectorize_perf_test(void *)
+{
+ gSavedSettings.setBOOL("VectorizePerfTest", TRUE);
+}
+
+
+////////////////////////////////
+// RUN Vectorized Perform Test//
+////////////////////////////////
+
+
+class LLAdvancedVectorizePerfTest : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ run_vectorize_perf_test(NULL);
+ return true;
+ }
+};
+
+///////////////////////////
+//// PERIODIC SLOW FRAME //
+///////////////////////////
+
+
+class LLAdvancedTogglePeriodicSlowFrame : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gPeriodicSlowFrame = !(gPeriodicSlowFrame);
+ return true;
+ }
+};
+
+class LLAdvancedCheckPeriodicSlowFrame : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gPeriodicSlowFrame;
+ return new_value;
+ }
+};
+
+
+
+////////////////
+// FRAME TEST //
+////////////////
+
+
+class LLAdvancedToggleFrameTest : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLPipeline::sRenderFrameTest = !(LLPipeline::sRenderFrameTest);
+ return true;
+ }
+};
+
+class LLAdvancedCheckFrameTest : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLPipeline::sRenderFrameTest;
+ return new_value;
+ }
+};
+
+
+///////////////////////////
+// SELECTED TEXTURE INFO //
+///////////////////////////
+
+
+class LLAdvancedSelectedTextureInfo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_selected_texture_info(NULL);
+ return true;
+ }
+};
+
+//////////////////////
+// TOGGLE WIREFRAME //
+//////////////////////
+
+class LLAdvancedToggleWireframe : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gUseWireframe = !(gUseWireframe);
+ LLPipeline::updateRenderDeferred();
+ gPipeline.resetVertexBuffers();
+ return true;
+ }
+};
+
+class LLAdvancedCheckWireframe : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gUseWireframe;
+ return new_value;
+ }
+};
+
+//////////////////////
+// TEXTURE ATLAS //
+//////////////////////
+
+class LLAdvancedToggleTextureAtlas : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLViewerTexture::sUseTextureAtlas = !LLViewerTexture::sUseTextureAtlas;
+ gSavedSettings.setBOOL("EnableTextureAtlas", LLViewerTexture::sUseTextureAtlas) ;
+ return true;
+ }
+};
+
+class LLAdvancedCheckTextureAtlas : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLViewerTexture::sUseTextureAtlas; // <-- make this using LLCacheControl
+ return new_value;
+ }
+};
+
+//////////////////////////
+// DUMP SCRIPTED CAMERA //
+//////////////////////////
+
+class LLAdvancedDumpScriptedCamera : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_dump_followcam(NULL);
+ return true;
+}
+};
+
+
+
+//////////////////////////////
+// DUMP REGION OBJECT CACHE //
+//////////////////////////////
+
+
+class LLAdvancedDumpRegionObjectCache : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+{
+ handle_dump_region_object_cache(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedBuyCurrencyTest : public view_listener_t
+ {
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_buy_currency_test(NULL);
+ return true;
+ }
+};
+
+
+/////////////////////
+// DUMP SELECT MGR //
+/////////////////////
+
+
+class LLAdvancedDumpSelectMgr : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ dump_select_mgr(NULL);
+ return true;
+ }
+};
+
+
+
+////////////////////
+// DUMP INVENTORY //
+////////////////////
+
+
+class LLAdvancedDumpInventory : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ dump_inventory(NULL);
+ return true;
+ }
+};
+
+
+
+////////////////////////////////
+// PRINT SELECTED OBJECT INFO //
+////////////////////////////////
+
+
+class LLAdvancedPrintSelectedObjectInfo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ print_object_info(NULL);
+ return true;
+ }
+};
+
+
+
+//////////////////////
+// PRINT AGENT INFO //
+//////////////////////
+
+
+class LLAdvancedPrintAgentInfo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ print_agent_nvpairs(NULL);
+ return true;
+ }
+};
+
+
+
+////////////////////////////////
+// PRINT TEXTURE MEMORY STATS //
+////////////////////////////////
+
+
+class LLAdvancedPrintTextureMemoryStats : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ output_statistics(NULL);
+ return true;
+ }
+};
+
+//////////////////
+// DEBUG CLICKS //
+//////////////////
+
+
+class LLAdvancedToggleDebugClicks : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gDebugClicks = !(gDebugClicks);
+ return true;
+ }
+};
+
+class LLAdvancedCheckDebugClicks : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gDebugClicks;
+ return new_value;
+ }
+};
+
+
+
+/////////////////
+// DEBUG VIEWS //
+/////////////////
+
+
+class LLAdvancedToggleDebugViews : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLView::sDebugRects = !(LLView::sDebugRects);
+ return true;
+ }
+};
+
+class LLAdvancedCheckDebugViews : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLView::sDebugRects;
+ return new_value;
+ }
+};
+
+
+
+///////////////////////
+// XUI NAME TOOLTIPS //
+///////////////////////
+
+
+class LLAdvancedToggleXUINameTooltips : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ toggle_show_xui_names(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedCheckXUINameTooltips : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = check_show_xui_names(NULL);
+ return new_value;
+ }
+};
+
+
+
+////////////////////////
+// DEBUG MOUSE EVENTS //
+////////////////////////
+
+
+class LLAdvancedToggleDebugMouseEvents : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLView::sDebugMouseHandling = !(LLView::sDebugMouseHandling);
+ return true;
+ }
+};
+
+class LLAdvancedCheckDebugMouseEvents : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLView::sDebugMouseHandling;
+ return new_value;
+ }
+};
+
+
+
+////////////////
+// DEBUG KEYS //
+////////////////
+
+
+class LLAdvancedToggleDebugKeys : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLView::sDebugKeys = !(LLView::sDebugKeys);
+ return true;
+ }
+};
+
+class LLAdvancedCheckDebugKeys : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLView::sDebugKeys;
+ return new_value;
+ }
+};
+
+
+
+///////////////////////
+// DEBUG WINDOW PROC //
+///////////////////////
+
+
+class LLAdvancedToggleDebugWindowProc : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gDebugWindowProc = !(gDebugWindowProc);
+ return true;
+ }
+};
+
+class LLAdvancedCheckDebugWindowProc : public view_listener_t
+ {
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gDebugWindowProc;
+ return new_value;
+ }
+};
+
+// ------------------------------XUI MENU ---------------------------
+
+class LLAdvancedSendTestIms : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLIMModel::instance().testMessages();
+ return true;
+}
+};
+
+
+///////////////
+// XUI NAMES //
+///////////////
+
+
+class LLAdvancedToggleXUINames : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ toggle_show_xui_names(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedCheckXUINames : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = check_show_xui_names(NULL);
+ return new_value;
+ }
+};
+
+
+////////////////////////
+// GRAB BAKED TEXTURE //
+////////////////////////
+
+
+class LLAdvancedGrabBakedTexture : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string texture_type = userdata.asString();
+ if ("iris" == texture_type)
+ {
+ handle_grab_baked_texture( (void*)BAKED_EYES );
+ }
+ else if ("head" == texture_type)
+ {
+ handle_grab_baked_texture( (void*)BAKED_HEAD );
+ }
+ else if ("upper" == texture_type)
+ {
+ handle_grab_baked_texture( (void*)BAKED_UPPER );
+ }
+ else if ("lower" == texture_type)
+ {
+ handle_grab_baked_texture( (void*)BAKED_LOWER );
+ }
+ else if ("skirt" == texture_type)
+ {
+ handle_grab_baked_texture( (void*)BAKED_SKIRT );
+ }
+ else if ("hair" == texture_type)
+ {
+ handle_grab_baked_texture( (void*)BAKED_HAIR );
+ }
+
+ return true;
+ }
+};
+
+class LLAdvancedEnableGrabBakedTexture : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+{
+ std::string texture_type = userdata.asString();
+ bool new_value = false;
+
+ if ("iris" == texture_type)
+ {
+ new_value = enable_grab_baked_texture( (void*)BAKED_EYES );
+ }
+ else if ("head" == texture_type)
+ {
+ new_value = enable_grab_baked_texture( (void*)BAKED_HEAD );
+ }
+ else if ("upper" == texture_type)
+ {
+ new_value = enable_grab_baked_texture( (void*)BAKED_UPPER );
+ }
+ else if ("lower" == texture_type)
+ {
+ new_value = enable_grab_baked_texture( (void*)BAKED_LOWER );
+ }
+ else if ("skirt" == texture_type)
+ {
+ new_value = enable_grab_baked_texture( (void*)BAKED_SKIRT );
+ }
+ else if ("hair" == texture_type)
+ {
+ new_value = enable_grab_baked_texture( (void*)BAKED_HAIR );
+ }
+
+ return new_value;
+}
+};
+
+///////////////////////
+// APPEARANCE TO XML //
+///////////////////////
+
+
+class LLAdvancedAppearanceToXML : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar::dumpArchetypeXML(NULL);
+ return true;
+ }
+};
+
+
+
+///////////////////////////////
+// TOGGLE CHARACTER GEOMETRY //
+///////////////////////////////
+
+
+class LLAdvancedToggleCharacterGeometry : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_god_request_avatar_geometry(NULL);
+ return true;
+}
+};
+
+
+ /////////////////////////////
+// TEST MALE / TEST FEMALE //
+/////////////////////////////
+
+class LLAdvancedTestMale : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_test_male(NULL);
+ return true;
+ }
+};
+
+
+class LLAdvancedTestFemale : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_test_female(NULL);
+ return true;
+ }
+};
+
+
+
+///////////////
+// TOGGLE PG //
+///////////////
+
+
+class LLAdvancedTogglePG : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_toggle_pg(NULL);
+ return true;
+ }
+};
+
+
+class LLAdvancedForceParamsToDefault : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLAgent::clearVisualParams(NULL);
+ return true;
+ }
+};
+
+
+
+//////////////////////////
+// RELOAD VERTEX SHADER //
+//////////////////////////
+
+
+class LLAdvancedReloadVertexShader : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ reload_vertex_shader(NULL);
+ return true;
+ }
+};
+
+
+
+////////////////////
+// ANIMATION INFO //
+////////////////////
+
+
+class LLAdvancedToggleAnimationInfo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar::sShowAnimationDebug = !(LLVOAvatar::sShowAnimationDebug);
+ return true;
+ }
+};
+
+class LLAdvancedCheckAnimationInfo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLVOAvatar::sShowAnimationDebug;
+ return new_value;
+ }
+};
+
+
+//////////////////
+// SHOW LOOK AT //
+//////////////////
+
+
+class LLAdvancedToggleShowLookAt : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLHUDEffectLookAt::sDebugLookAt = !(LLHUDEffectLookAt::sDebugLookAt);
+ return true;
+ }
+};
+
+class LLAdvancedCheckShowLookAt : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLHUDEffectLookAt::sDebugLookAt;
+ return new_value;
+ }
+};
+
+
+
+///////////////////
+// SHOW POINT AT //
+///////////////////
+
+
+class LLAdvancedToggleShowPointAt : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLHUDEffectPointAt::sDebugPointAt = !(LLHUDEffectPointAt::sDebugPointAt);
+ return true;
+ }
+};
+
+class LLAdvancedCheckShowPointAt : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLHUDEffectPointAt::sDebugPointAt;
+ return new_value;
+ }
+};
+
+
+
+/////////////////////////
+// DEBUG JOINT UPDATES //
+/////////////////////////
+
+
+class LLAdvancedToggleDebugJointUpdates : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar::sJointDebug = !(LLVOAvatar::sJointDebug);
+ return true;
+ }
+};
+
+class LLAdvancedCheckDebugJointUpdates : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLVOAvatar::sJointDebug;
+ return new_value;
+ }
+};
+
+
+
+/////////////////
+// DISABLE LOD //
+/////////////////
+
+
+class LLAdvancedToggleDisableLOD : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLViewerJoint::sDisableLOD = !(LLViewerJoint::sDisableLOD);
+ return true;
+ }
+};
+
+class LLAdvancedCheckDisableLOD : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLViewerJoint::sDisableLOD;
+ return new_value;
+ }
+};
+
+
+
+/////////////////////////
+// DEBUG CHARACTER VIS //
+/////////////////////////
+
+
+class LLAdvancedToggleDebugCharacterVis : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar::sDebugInvisible = !(LLVOAvatar::sDebugInvisible);
+ return true;
+ }
+};
+
+class LLAdvancedCheckDebugCharacterVis : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLVOAvatar::sDebugInvisible;
+ return new_value;
+ }
+};
+
+
+//////////////////////
+// DUMP ATTACHMENTS //
+//////////////////////
+
+
+class LLAdvancedDumpAttachments : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_dump_attachments(NULL);
+ return true;
+ }
+};
+
+
+
+/////////////////////
+// REBAKE TEXTURES //
+/////////////////////
+
+
+class LLAdvancedRebakeTextures : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_rebake_textures(NULL);
+ return true;
+ }
+};
+
+
+#if 1 //ndef LL_RELEASE_FOR_DOWNLOAD
+///////////////////////////
+// DEBUG AVATAR TEXTURES //
+///////////////////////////
+
+
+class LLAdvancedDebugAvatarTextures : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if (gAgent.isGodlike())
+ {
+ handle_debug_avatar_textures(NULL);
+ }
+ return true;
+ }
+};
+
+////////////////////////////////
+// DUMP AVATAR LOCAL TEXTURES //
+////////////////////////////////
+
+
+class LLAdvancedDumpAvatarLocalTextures : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+#ifndef LL_RELEASE_FOR_DOWNLOAD
+ handle_dump_avatar_local_textures(NULL);
+#endif
+ return true;
+ }
+};
+
+#endif
+
+/////////////////
+// MESSAGE LOG //
+/////////////////
+
+
+class LLAdvancedEnableMessageLog : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_viewer_enable_message_log(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedDisableMessageLog : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_viewer_disable_message_log(NULL);
+ return true;
+ }
+};
+
+/////////////////
+// DROP PACKET //
+/////////////////
+
+
+class LLAdvancedDropPacket : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gMessageSystem->mPacketRing.dropPackets(1);
+ return true;
+ }
+};
+
+
+
+/////////////////
+// AGENT PILOT //
+/////////////////
+
+
+class LLAdvancedAgentPilot : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string command = userdata.asString();
+ if ("start playback" == command)
+ {
+ gAgentPilot.setNumRuns(-1);
+ gAgentPilot.startPlayback();
+ }
+ else if ("stop playback" == command)
+ {
+ gAgentPilot.stopPlayback();
+ }
+ else if ("start record" == command)
+ {
+ gAgentPilot.startRecord();
+ }
+ else if ("stop record" == command)
+ {
+ gAgentPilot.stopRecord();
+ }
+
+ return true;
+ }
+};
+
+
+
+//////////////////////
+// AGENT PILOT LOOP //
+//////////////////////
+
+
+class LLAdvancedToggleAgentPilotLoop : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gAgentPilot.setLoop(!gAgentPilot.getLoop());
+ return true;
+ }
+};
+
+class LLAdvancedCheckAgentPilotLoop : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gAgentPilot.getLoop();
+ return new_value;
+ }
+};
+
+
+/////////////////////////
+// SHOW OBJECT UPDATES //
+/////////////////////////
+
+
+class LLAdvancedToggleShowObjectUpdates : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gShowObjectUpdates = !(gShowObjectUpdates);
+ return true;
+ }
+};
+
+class LLAdvancedCheckShowObjectUpdates : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gShowObjectUpdates;
+ return new_value;
+ }
+};
+
+
+
+////////////////////
+// COMPRESS IMAGE //
+////////////////////
+
+
+class LLAdvancedCompressImage : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_compress_image(NULL);
+ return true;
+ }
+};
+
+
+
+/////////////////////////
+// SHOW DEBUG SETTINGS //
+/////////////////////////
+
+
+class LLAdvancedShowDebugSettings : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLFloaterReg::showInstance("settings_debug",userdata);
+ return true;
+ }
+};
+
+
+
+////////////////////////
+// VIEW ADMIN OPTIONS //
+////////////////////////
+
+class LLAdvancedEnableViewAdminOptions : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ // Don't enable in god mode since the admin menu is shown anyway.
+ // Only enable if the user has set the appropriate debug setting.
+ bool new_value = !gAgent.getAgentAccess().isGodlikeWithoutAdminMenuFakery() && gSavedSettings.getBOOL("AdminMenu");
+ return new_value;
+ }
+};
+
+class LLAdvancedToggleViewAdminOptions : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_admin_override_toggle(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedCheckViewAdminOptions : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = check_admin_override(NULL) || gAgent.isGodlike();
+ return new_value;
+ }
+};
+
+/////////////////////////////////////
+// Enable Object Object Occlusion ///
+/////////////////////////////////////
+class LLAdvancedEnableObjectObjectOcclusion: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+
+ bool new_value = gGLManager.mHasOcclusionQuery; // && LLFeatureManager::getInstance()->isFeatureAvailable(userdata.asString());
+ return new_value;
+}
+};
+
+/////////////////////////////////////
+// Enable Framebuffer Objects ///
+/////////////////////////////////////
+class LLAdvancedEnableRenderFBO: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gGLManager.mHasFramebufferObject;
+ return new_value;
+ }
+};
+
+/////////////////////////////////////
+// Enable Deferred Rendering ///
+/////////////////////////////////////
+class LLAdvancedEnableRenderDeferred: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gGLManager.mHasFramebufferObject && LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_WINDLIGHT) > 1 &&
+ LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_AVATAR) > 0;
+ return new_value;
+ }
+};
+
+/////////////////////////////////////
+// Enable Deferred Rendering sub-options
+/////////////////////////////////////
+class LLAdvancedEnableRenderDeferredOptions: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gGLManager.mHasFramebufferObject && LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_WINDLIGHT) > 1 &&
+ LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_AVATAR) > 0 && gSavedSettings.getBOOL("RenderDeferred");
+ return new_value;
+ }
+};
+
+
+
+//////////////////
+// ADMIN STATUS //
+//////////////////
+
+
+class LLAdvancedRequestAdminStatus : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_god_mode(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedLeaveAdminStatus : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_leave_god_mode(NULL);
+ return true;
+ }
+};
+
+//////////////////////////
+// Advanced > Debugging //
+//////////////////////////
+
+
+class LLAdvancedForceErrorBreakpoint : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ force_error_breakpoint(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedForceErrorLlerror : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ force_error_llerror(NULL);
+ return true;
+ }
+};
+class LLAdvancedForceErrorBadMemoryAccess : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ force_error_bad_memory_access(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedForceErrorInfiniteLoop : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ force_error_infinite_loop(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedForceErrorSoftwareException : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ force_error_software_exception(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedForceErrorDriverCrash : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ force_error_driver_crash(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedForceErrorDisconnectViewer : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_disconnect_viewer(NULL);
+ return true;
+}
+};
+
+
+#ifdef TOGGLE_HACKED_GODLIKE_VIEWER
+
+class LLAdvancedHandleToggleHackedGodmode : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_toggle_hacked_godmode(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedCheckToggleHackedGodmode : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ check_toggle_hacked_godmode(NULL);
+ return true;
+ }
+};
+
+class LLAdvancedEnableToggleHackedGodmode : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = enable_toggle_hacked_godmode(NULL);
+ return new_value;
+ }
+};
+#endif
+
+
+//
+////-------------------------------------------------------------------
+//// Advanced menu
+////-------------------------------------------------------------------
+
+//////////////////
+// ADMIN MENU //
+//////////////////
+
+// Admin > Object
+class LLAdminForceTakeCopy : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ force_take_copy(NULL);
+ return true;
+ }
+};
+
+class LLAdminHandleObjectOwnerSelf : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_object_owner_self(NULL);
+ return true;
+ }
+};
+class LLAdminHandleObjectOwnerPermissive : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_object_owner_permissive(NULL);
+ return true;
+ }
+};
+
+class LLAdminHandleForceDelete : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_force_delete(NULL);
+ return true;
+ }
+};
+
+class LLAdminHandleObjectLock : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_object_lock(NULL);
+ return true;
+ }
+};
+
+class LLAdminHandleObjectAssetIDs: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_object_asset_ids(NULL);
+ return true;
+ }
+};
+
+//Admin >Parcel
+class LLAdminHandleForceParcelOwnerToMe: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_force_parcel_owner_to_me(NULL);
+ return true;
+ }
+};
+class LLAdminHandleForceParcelToContent: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_force_parcel_to_content(NULL);
+ return true;
+ }
+};
+class LLAdminHandleClaimPublicLand: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_claim_public_land(NULL);
+ return true;
+ }
+};
+
+// Admin > Region
+class LLAdminHandleRegionDumpTempAssetData: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_region_dump_temp_asset_data(NULL);
+ return true;
+ }
+};
+//Admin (Top Level)
+
+class LLAdminOnSaveState: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLPanelRegionTools::onSaveState(NULL);
+ return true;
+}
+};
+
+
+//-----------------------------------------------------------------------------
+// cleanup_menus()
+//-----------------------------------------------------------------------------
+void cleanup_menus()
+{
+ delete gMenuParcelObserver;
+ gMenuParcelObserver = NULL;
+
+ delete gMenuAvatarSelf;
+ gMenuAvatarSelf = NULL;
+
+ delete gMenuAvatarOther;
+ gMenuAvatarOther = NULL;
+
+ delete gMenuObject;
+ gMenuObject = NULL;
+
+ delete gMenuAttachmentSelf;
+ gMenuAttachmentSelf = NULL;
+
+ delete gMenuAttachmentOther;
+ gMenuAttachmentSelf = NULL;
+
+ delete gMenuLand;
+ gMenuLand = NULL;
+
+ delete gMenuBarView;
+ gMenuBarView = NULL;
+
+ delete gPopupMenuView;
+ gPopupMenuView = NULL;
+
+ delete gMenuHolder;
+ gMenuHolder = NULL;
+}
+
+//-----------------------------------------------------------------------------
+// Object pie menu
+//-----------------------------------------------------------------------------
+
+class LLObjectReportAbuse : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ if (objectp)
+ {
+ LLFloaterReporter::showFromObject(objectp->getID());
+ }
+ return true;
+ }
+};
+
+// Enabled it you clicked an object
+class LLObjectEnableReportAbuse : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLSelectMgr::getInstance()->getSelection()->getObjectCount() != 0;
+ return new_value;
+ }
+};
+
+void handle_object_touch()
+{
+ LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ if (!object) return;
+
+ LLPickInfo pick = LLToolPie::getInstance()->getPick();
+
+ LLMessageSystem *msg = gMessageSystem;
+
+ msg->newMessageFast(_PREHASH_ObjectGrab);
+ msg->nextBlockFast( _PREHASH_AgentData);
+ msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
+ msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ msg->nextBlockFast( _PREHASH_ObjectData);
+ msg->addU32Fast( _PREHASH_LocalID, object->mLocalID);
+ msg->addVector3Fast(_PREHASH_GrabOffset, LLVector3::zero );
+ msg->nextBlock("SurfaceInfo");
+ msg->addVector3("UVCoord", LLVector3(pick.mUVCoords));
+ msg->addVector3("STCoord", LLVector3(pick.mSTCoords));
+ msg->addS32Fast(_PREHASH_FaceIndex, pick.mObjectFace);
+ msg->addVector3("Position", pick.mIntersection);
+ msg->addVector3("Normal", pick.mNormal);
+ msg->addVector3("Binormal", pick.mBinormal);
+ msg->sendMessage( object->getRegion()->getHost());
+
+ // *NOTE: Hope the packets arrive safely and in order or else
+ // there will be some problems.
+ // *TODO: Just fix this bad assumption.
+ msg->newMessageFast(_PREHASH_ObjectDeGrab);
+ msg->nextBlockFast(_PREHASH_AgentData);
+ msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
+ msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ msg->nextBlockFast(_PREHASH_ObjectData);
+ msg->addU32Fast(_PREHASH_LocalID, object->mLocalID);
+ msg->nextBlock("SurfaceInfo");
+ msg->addVector3("UVCoord", LLVector3(pick.mUVCoords));
+ msg->addVector3("STCoord", LLVector3(pick.mSTCoords));
+ msg->addS32Fast(_PREHASH_FaceIndex, pick.mObjectFace);
+ msg->addVector3("Position", pick.mIntersection);
+ msg->addVector3("Normal", pick.mNormal);
+ msg->addVector3("Binormal", pick.mBinormal);
+ msg->sendMessage(object->getRegion()->getHost());
+}
+
+static void init_default_item_label(const std::string& item_name)
+{
+ boost::unordered_map<std::string, LLStringExplicit>::iterator it = sDefaultItemLabels.find(item_name);
+ if (it == sDefaultItemLabels.end())
+ {
+ // *NOTE: This will not work for items of type LLMenuItemCheckGL because they return boolean value
+ // (doesn't seem to matter much ATM).
+ LLStringExplicit default_label = gMenuHolder->childGetValue(item_name).asString();
+ if (!default_label.empty())
+ {
+ sDefaultItemLabels.insert(std::pair<std::string, LLStringExplicit>(item_name, default_label));
+ }
+ }
+}
+
+static LLStringExplicit get_default_item_label(const std::string& item_name)
+{
+ LLStringExplicit res("");
+ boost::unordered_map<std::string, LLStringExplicit>::iterator it = sDefaultItemLabels.find(item_name);
+ if (it != sDefaultItemLabels.end())
+ {
+ res = it->second;
+ }
+
+ return res;
+}
+
+
+bool enable_object_touch(LLUICtrl* ctrl)
+{
+ LLViewerObject* obj = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+
+ bool new_value = obj && obj->flagHandleTouch();
+
+ std::string item_name = ctrl->getName();
+ init_default_item_label(item_name);
+
+ // Update label based on the node touch name if available.
+ LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
+ if (node && node->mValid && !node->mTouchName.empty())
+ {
+ gMenuHolder->childSetText(item_name, node->mTouchName);
+ }
+ else
+ {
+ gMenuHolder->childSetText(item_name, get_default_item_label(item_name));
+ }
+
+ return new_value;
+};
+
+//void label_touch(std::string& label, void*)
+//{
+// LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
+// if (node && node->mValid && !node->mTouchName.empty())
+// {
+// label.assign(node->mTouchName);
+// }
+// else
+// {
+// label.assign("Touch");
+// }
+//}
+
+void handle_object_open()
+{
+ LLFloaterReg::showInstance("openobject");
+}
+
+bool enable_object_open()
+{
+ // Look for contents in root object, which is all the LLFloaterOpenObject
+ // understands.
+ LLViewerObject* obj = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ if (!obj) return false;
+
+ LLViewerObject* root = obj->getRootEdit();
+ if (!root) return false;
+
+ return root->allowOpen();
+}
+
+
+class LLViewJoystickFlycam : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_toggle_flycam();
+ return true;
+ }
+};
+
+class LLViewCheckJoystickFlycam : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLViewerJoystick::getInstance()->getOverrideCamera();
+ return new_value;
+ }
+};
+
+void handle_toggle_flycam()
+{
+ LLViewerJoystick::getInstance()->toggleFlycam();
+}
+
+class LLObjectBuild : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if (gAgentCamera.getFocusOnAvatar() && !LLToolMgr::getInstance()->inEdit() && gSavedSettings.getBOOL("EditCameraMovement") )
+ {
+ // zoom in if we're looking at the avatar
+ gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
+ gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
+ gAgentCamera.cameraZoomIn(0.666f);
+ gAgentCamera.cameraOrbitOver( 30.f * DEG_TO_RAD );
+ gViewerWindow->moveCursorToCenter();
+ }
+ else if ( gSavedSettings.getBOOL("EditCameraMovement") )
+ {
+ gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
+ gViewerWindow->moveCursorToCenter();
+ }
+
+ LLToolMgr::getInstance()->setCurrentToolset(gBasicToolset);
+ LLToolMgr::getInstance()->getCurrentToolset()->selectTool( LLToolCompCreate::getInstance() );
+
+ // Could be first use
+ //LLFirstUse::useBuild();
+ return true;
+ }
+};
+
+
+void handle_object_edit()
+{
+ LLViewerParcelMgr::getInstance()->deselectLand();
+
+ if (gAgentCamera.getFocusOnAvatar() && !LLToolMgr::getInstance()->inEdit())
+ {
+ LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
+
+ if (selection->getSelectType() == SELECT_TYPE_HUD || !gSavedSettings.getBOOL("EditCameraMovement"))
+ {
+ // always freeze camera in space, even if camera doesn't move
+ // so, for example, follow cam scripts can't affect you when in build mode
+ gAgentCamera.setFocusGlobal(gAgentCamera.calcFocusPositionTargetGlobal(), LLUUID::null);
+ gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
+ }
+ else
+ {
+ gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
+ LLViewerObject* selected_objectp = selection->getFirstRootObject();
+ if (selected_objectp)
+ {
+ // zoom in on object center instead of where we clicked, as we need to see the manipulator handles
+ gAgentCamera.setFocusGlobal(selected_objectp->getPositionGlobal(), selected_objectp->getID());
+ gAgentCamera.cameraZoomIn(0.666f);
+ gAgentCamera.cameraOrbitOver( 30.f * DEG_TO_RAD );
+ gViewerWindow->moveCursorToCenter();
+ }
+ }
+ }
+
+ LLFloaterReg::showInstance("build");
+
+ LLToolMgr::getInstance()->setCurrentToolset(gBasicToolset);
+ gFloaterTools->setEditTool( LLToolCompTranslate::getInstance() );
+
+ LLViewerJoystick::getInstance()->moveObjects(true);
+ LLViewerJoystick::getInstance()->setNeedsReset(true);
+
+ // Could be first use
+ //LLFirstUse::useBuild();
+ return;
+}
+
+void handle_object_inspect()
+{
+ LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
+ LLViewerObject* selected_objectp = selection->getFirstRootObject();
+ if (selected_objectp)
+ {
+ LLSD key;
+ key["task"] = "task";
+ LLSideTray::getInstance()->showPanel("sidepanel_inventory", key);
+ }
+
+ /*
+ // Old floater properties
+ LLFloaterReg::showInstance("inspect", LLSD());
+ */
+}
+
+//---------------------------------------------------------------------------
+// Land pie menu
+//---------------------------------------------------------------------------
+class LLLandBuild : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLViewerParcelMgr::getInstance()->deselectLand();
+
+ if (gAgentCamera.getFocusOnAvatar() && !LLToolMgr::getInstance()->inEdit() && gSavedSettings.getBOOL("EditCameraMovement") )
+ {
+ // zoom in if we're looking at the avatar
+ gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
+ gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
+ gAgentCamera.cameraZoomIn(0.666f);
+ gAgentCamera.cameraOrbitOver( 30.f * DEG_TO_RAD );
+ gViewerWindow->moveCursorToCenter();
+ }
+ else if ( gSavedSettings.getBOOL("EditCameraMovement") )
+ {
+ // otherwise just move focus
+ gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
+ gViewerWindow->moveCursorToCenter();
+ }
+
+
+ LLToolMgr::getInstance()->setCurrentToolset(gBasicToolset);
+ LLToolMgr::getInstance()->getCurrentToolset()->selectTool( LLToolCompCreate::getInstance() );
+
+ // Could be first use
+ //LLFirstUse::useBuild();
+ return true;
+ }
+};
+
+class LLLandBuyPass : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLPanelLandGeneral::onClickBuyPass((void *)FALSE);
+ return true;
+ }
+};
+
+class LLLandEnableBuyPass : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLPanelLandGeneral::enableBuyPass(NULL);
+ return new_value;
+ }
+};
+
+// BUG: Should really check if CLICK POINT is in a parcel where you can build.
+BOOL enable_land_build(void*)
+{
+ if (gAgent.isGodlike()) return TRUE;
+ if (gAgent.inPrelude()) return FALSE;
+
+ BOOL can_build = FALSE;
+ LLParcel* agent_parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
+ if (agent_parcel)
+ {
+ can_build = agent_parcel->getAllowModify();
+ }
+ return can_build;
+}
+
+// BUG: Should really check if OBJECT is in a parcel where you can build.
+BOOL enable_object_build(void*)
+{
+ if (gAgent.isGodlike()) return TRUE;
+ if (gAgent.inPrelude()) return FALSE;
+
+ BOOL can_build = FALSE;
+ LLParcel* agent_parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
+ if (agent_parcel)
+ {
+ can_build = agent_parcel->getAllowModify();
+ }
+ return can_build;
+}
+
+bool enable_object_edit()
+{
+ // *HACK: The new "prelude" Help Islands have a build sandbox area,
+ // so users need the Edit and Create pie menu options when they are
+ // there. Eventually this needs to be replaced with code that only
+ // lets you edit objects if you have permission to do so (edit perms,
+ // group edit, god). See also lltoolbar.cpp. JC
+ bool enable = false;
+ if (gAgent.inPrelude())
+ {
+ enable = LLViewerParcelMgr::getInstance()->allowAgentBuild()
+ || LLSelectMgr::getInstance()->getSelection()->isAttachment();
+ }
+ else if (LLSelectMgr::getInstance()->selectGetAllValidAndObjectsFound())
+ {
+ enable = true;
+ }
+
+ return enable;
+}
+
+// mutually exclusive - show either edit option or build in menu
+bool enable_object_build()
+{
+ return !enable_object_edit();
+}
+
+class LLSelfRemoveAllAttachments : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLAgentWearables::userRemoveAllAttachments();
+ return true;
+ }
+};
+
+class LLSelfEnableRemoveAllAttachments : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = false;
+ if (isAgentAvatarValid())
+ {
+ for (LLVOAvatar::attachment_map_t::iterator iter = gAgentAvatarp->mAttachmentPoints.begin();
+ iter != gAgentAvatarp->mAttachmentPoints.end(); )
+ {
+ LLVOAvatar::attachment_map_t::iterator curiter = iter++;
+ LLViewerJointAttachment* attachment = curiter->second;
+ if (attachment->getNumObjects() > 0)
+ {
+ new_value = true;
+ break;
+ }
+ }
+ }
+ return new_value;
+ }
+};
+
+BOOL enable_has_attachments(void*)
+{
+
+ return FALSE;
+}
+
+//---------------------------------------------------------------------------
+// Avatar pie menu
+//---------------------------------------------------------------------------
+//void handle_follow(void *userdata)
+//{
+// // follow a given avatar by ID
+// LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+// if (objectp)
+// {
+// gAgent.startFollowPilot(objectp->getID());
+// }
+//}
+
+bool enable_object_mute()
+{
+ LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ if (!object) return false;
+
+ LLVOAvatar* avatar = find_avatar_from_object(object);
+ if (avatar)
+ {
+ // It's an avatar
+ LLNameValue *lastname = avatar->getNVPair("LastName");
+ bool is_linden =
+ lastname && !LLStringUtil::compareStrings(lastname->getString(), "Linden");
+ bool is_self = avatar->isSelf();
+ return !is_linden && !is_self;
+ }
+ else
+ {
+ // Just a regular object
+ return LLSelectMgr::getInstance()->getSelection()->
+ contains( object, SELECT_ALL_TES );
+ }
+}
+
+class LLObjectMute : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ if (!object) return true;
+
+ LLUUID id;
+ std::string name;
+ LLMute::EType type;
+ LLVOAvatar* avatar = find_avatar_from_object(object);
+ if (avatar)
+ {
+ id = avatar->getID();
+
+ LLNameValue *firstname = avatar->getNVPair("FirstName");
+ LLNameValue *lastname = avatar->getNVPair("LastName");
+ if (firstname && lastname)
+ {
+ name = LLCacheName::buildFullName(
+ firstname->getString(), lastname->getString());
+ }
+
+ type = LLMute::AGENT;
+ }
+ else
+ {
+ // it's an object
+ id = object->getID();
+
+ LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
+ if (node)
+ {
+ name = node->mName;
+ }
+
+ type = LLMute::OBJECT;
+ }
+
+ LLMute mute(id, name, type);
+ if (LLMuteList::getInstance()->isMuted(mute.mID))
+ {
+ LLMuteList::getInstance()->remove(mute);
+ }
+ else
+ {
+ LLMuteList::getInstance()->add(mute);
+ LLPanelBlockedList::showPanelAndSelect(mute.mID);
+ }
+
+ return true;
+ }
+};
+
+bool handle_go_to()
+{
+ // try simulator autopilot
+ std::vector<std::string> strings;
+ std::string val;
+ LLVector3d pos = LLToolPie::getInstance()->getPick().mPosGlobal;
+ val = llformat("%g", pos.mdV[VX]);
+ strings.push_back(val);
+ val = llformat("%g", pos.mdV[VY]);
+ strings.push_back(val);
+ val = llformat("%g", pos.mdV[VZ]);
+ strings.push_back(val);
+ send_generic_message("autopilot", strings);
+
+ LLViewerParcelMgr::getInstance()->deselectLand();
+
+ if (isAgentAvatarValid() && !gSavedSettings.getBOOL("AutoPilotLocksCamera"))
+ {
+ gAgentCamera.setFocusGlobal(gAgentCamera.getFocusTargetGlobal(), gAgentAvatarp->getID());
+ }
+ else
+ {
+ // Snap camera back to behind avatar
+ gAgentCamera.setFocusOnAvatar(TRUE, ANIMATE);
+ }
+
+ // Could be first use
+ //LLFirstUse::useGoTo();
+ return true;
+}
+
+class LLGoToObject : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ return handle_go_to();
+ }
+};
+
+class LLAvatarReportAbuse : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
+ if(avatar)
+ {
+ LLFloaterReporter::showFromObject(avatar->getID());
+ }
+ return true;
+ }
+};
+
+
+//---------------------------------------------------------------------------
+// Parcel freeze, eject, etc.
+//---------------------------------------------------------------------------
+bool callback_freeze(const LLSD& notification, const LLSD& response)
+{
+ LLUUID avatar_id = notification["payload"]["avatar_id"].asUUID();
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+
+ if (0 == option || 1 == option)
+ {
+ U32 flags = 0x0;
+ if (1 == option)
+ {
+ // unfreeze
+ flags |= 0x1;
+ }
+
+ LLMessageSystem* msg = gMessageSystem;
+ LLViewerObject* avatar = gObjectList.findObject(avatar_id);
+
+ if (avatar)
+ {
+ msg->newMessage("FreezeUser");
+ msg->nextBlock("AgentData");
+ msg->addUUID("AgentID", gAgent.getID());
+ msg->addUUID("SessionID", gAgent.getSessionID());
+ msg->nextBlock("Data");
+ msg->addUUID("TargetID", avatar_id );
+ msg->addU32("Flags", flags );
+ msg->sendReliable( avatar->getRegion()->getHost() );
+ }
+ }
+ return false;
+}
+
+
+void handle_avatar_freeze(const LLSD& avatar_id)
+{
+ // Use avatar_id if available, otherwise default to right-click avatar
+ LLVOAvatar* avatar = NULL;
+ if (avatar_id.asUUID().notNull())
+ {
+ avatar = find_avatar_from_object(avatar_id.asUUID());
+ }
+ else
+ {
+ avatar = find_avatar_from_object(
+ LLSelectMgr::getInstance()->getSelection()->getPrimaryObject());
+ }
+
+ if( avatar )
+ {
+ std::string fullname = avatar->getFullname();
+ LLSD payload;
+ payload["avatar_id"] = avatar->getID();
+
+ if (!fullname.empty())
+ {
+ LLSD args;
+ args["AVATAR_NAME"] = fullname;
+ LLNotificationsUtil::add("FreezeAvatarFullname",
+ args,
+ payload,
+ callback_freeze);
+ }
+ else
+ {
+ LLNotificationsUtil::add("FreezeAvatar",
+ LLSD(),
+ payload,
+ callback_freeze);
+ }
+ }
+}
+
+class LLAvatarVisibleDebug : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ return gAgent.isGodlike();
+ }
+};
+
+class LLAvatarDebug : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
+ if( avatar )
+ {
+ if (avatar->isSelf())
+ {
+ ((LLVOAvatarSelf *)avatar)->dumpLocalTextures();
+ }
+ llinfos << "Dumping temporary asset data to simulator logs for avatar " << avatar->getID() << llendl;
+ std::vector<std::string> strings;
+ strings.push_back(avatar->getID().asString());
+ LLUUID invoice;
+ send_generic_message("dumptempassetdata", strings, invoice);
+ LLFloaterReg::showInstance( "avatar_textures", LLSD(avatar->getID()) );
+ }
+ return true;
+ }
+};
+
+bool callback_eject(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ if (2 == option)
+ {
+ // Cancel button.
+ return false;
+ }
+ LLUUID avatar_id = notification["payload"]["avatar_id"].asUUID();
+ bool ban_enabled = notification["payload"]["ban_enabled"].asBoolean();
+
+ if (0 == option)
+ {
+ // Eject button
+ LLMessageSystem* msg = gMessageSystem;
+ LLViewerObject* avatar = gObjectList.findObject(avatar_id);
+
+ if (avatar)
+ {
+ U32 flags = 0x0;
+ msg->newMessage("EjectUser");
+ msg->nextBlock("AgentData");
+ msg->addUUID("AgentID", gAgent.getID() );
+ msg->addUUID("SessionID", gAgent.getSessionID() );
+ msg->nextBlock("Data");
+ msg->addUUID("TargetID", avatar_id );
+ msg->addU32("Flags", flags );
+ msg->sendReliable( avatar->getRegion()->getHost() );
+ }
+ }
+ else if (ban_enabled)
+ {
+ // This is tricky. It is similar to say if it is not an 'Eject' button,
+ // and it is also not an 'Cancle' button, and ban_enabled==ture,
+ // it should be the 'Eject and Ban' button.
+ LLMessageSystem* msg = gMessageSystem;
+ LLViewerObject* avatar = gObjectList.findObject(avatar_id);
+
+ if (avatar)
+ {
+ U32 flags = 0x1;
+ msg->newMessage("EjectUser");
+ msg->nextBlock("AgentData");
+ msg->addUUID("AgentID", gAgent.getID() );
+ msg->addUUID("SessionID", gAgent.getSessionID() );
+ msg->nextBlock("Data");
+ msg->addUUID("TargetID", avatar_id );
+ msg->addU32("Flags", flags );
+ msg->sendReliable( avatar->getRegion()->getHost() );
+ }
+ }
+ return false;
+}
+
+void handle_avatar_eject(const LLSD& avatar_id)
+{
+ // Use avatar_id if available, otherwise default to right-click avatar
+ LLVOAvatar* avatar = NULL;
+ if (avatar_id.asUUID().notNull())
+ {
+ avatar = find_avatar_from_object(avatar_id.asUUID());
+ }
+ else
+ {
+ avatar = find_avatar_from_object(
+ LLSelectMgr::getInstance()->getSelection()->getPrimaryObject());
+ }
+
+ if( avatar )
+ {
+ LLSD payload;
+ payload["avatar_id"] = avatar->getID();
+ std::string fullname = avatar->getFullname();
+
+ const LLVector3d& pos = avatar->getPositionGlobal();
+ LLParcel* parcel = LLViewerParcelMgr::getInstance()->selectParcelAt(pos)->getParcel();
+
+ if (LLViewerParcelMgr::getInstance()->isParcelOwnedByAgent(parcel,GP_LAND_MANAGE_BANNED))
+ {
+ payload["ban_enabled"] = true;
+ if (!fullname.empty())
+ {
+ LLSD args;
+ args["AVATAR_NAME"] = fullname;
+ LLNotificationsUtil::add("EjectAvatarFullname",
+ args,
+ payload,
+ callback_eject);
+ }
+ else
+ {
+ LLNotificationsUtil::add("EjectAvatarFullname",
+ LLSD(),
+ payload,
+ callback_eject);
+ }
+ }
+ else
+ {
+ payload["ban_enabled"] = false;
+ if (!fullname.empty())
+ {
+ LLSD args;
+ args["AVATAR_NAME"] = fullname;
+ LLNotificationsUtil::add("EjectAvatarFullnameNoBan",
+ args,
+ payload,
+ callback_eject);
+ }
+ else
+ {
+ LLNotificationsUtil::add("EjectAvatarNoBan",
+ LLSD(),
+ payload,
+ callback_eject);
+ }
+ }
+ }
+}
+
+bool enable_freeze_eject(const LLSD& avatar_id)
+{
+ // Use avatar_id if available, otherwise default to right-click avatar
+ LLVOAvatar* avatar = NULL;
+ if (avatar_id.asUUID().notNull())
+ {
+ avatar = find_avatar_from_object(avatar_id.asUUID());
+ }
+ else
+ {
+ avatar = find_avatar_from_object(
+ LLSelectMgr::getInstance()->getSelection()->getPrimaryObject());
+ }
+ if (!avatar) return false;
+
+ // Gods can always freeze
+ if (gAgent.isGodlike()) return true;
+
+ // Estate owners / managers can freeze
+ // Parcel owners can also freeze
+ const LLVector3& pos = avatar->getPositionRegion();
+ const LLVector3d& pos_global = avatar->getPositionGlobal();
+ LLParcel* parcel = LLViewerParcelMgr::getInstance()->selectParcelAt(pos_global)->getParcel();
+ LLViewerRegion* region = avatar->getRegion();
+ if (!region) return false;
+
+ bool new_value = region->isOwnedSelf(pos);
+ if (!new_value || region->isOwnedGroup(pos))
+ {
+ new_value = LLViewerParcelMgr::getInstance()->isParcelOwnedByAgent(parcel,GP_LAND_ADMIN);
+ }
+ return new_value;
+}
+
+
+void login_done(S32 which, void *user)
+{
+ llinfos << "Login done " << which << llendl;
+
+ LLPanelLogin::closePanel();
+}
+
+
+bool callback_leave_group(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ if (option == 0)
+ {
+ LLMessageSystem *msg = gMessageSystem;
+
+ msg->newMessageFast(_PREHASH_LeaveGroupRequest);
+ msg->nextBlockFast(_PREHASH_AgentData);
+ msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID() );
+ msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ msg->nextBlockFast(_PREHASH_GroupData);
+ msg->addUUIDFast(_PREHASH_GroupID, gAgent.getGroupID() );
+ gAgent.sendReliableMessage();
+ }
+ return false;
+}
+
+void append_aggregate(std::string& string, const LLAggregatePermissions& ag_perm, PermissionBit bit, const char* txt)
+{
+ LLAggregatePermissions::EValue val = ag_perm.getValue(bit);
+ std::string buffer;
+ switch(val)
+ {
+ case LLAggregatePermissions::AP_NONE:
+ buffer = llformat( "* %s None\n", txt);
+ break;
+ case LLAggregatePermissions::AP_SOME:
+ buffer = llformat( "* %s Some\n", txt);
+ break;
+ case LLAggregatePermissions::AP_ALL:
+ buffer = llformat( "* %s All\n", txt);
+ break;
+ case LLAggregatePermissions::AP_EMPTY:
+ default:
+ break;
+ }
+ string.append(buffer);
+}
+
+bool enable_buy_object()
+{
+ // In order to buy, there must only be 1 purchaseable object in
+ // the selection manger.
+ if(LLSelectMgr::getInstance()->getSelection()->getRootObjectCount() != 1) return false;
+ LLViewerObject* obj = NULL;
+ LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
+ if(node)
+ {
+ obj = node->getObject();
+ if(!obj) return false;
+
+ if( for_sale_selection(node) )
+ {
+ // *NOTE: Is this needed? This checks to see if anyone owns the
+ // object, dating back to when we had "public" objects owned by
+ // no one. JC
+ if(obj->permAnyOwner()) return true;
+ }
+ }
+ return false;
+}
+
+// Note: This will only work if the selected object's data has been
+// received by the viewer and cached in the selection manager.
+void handle_buy_object(LLSaleInfo sale_info)
+{
+ if(!LLSelectMgr::getInstance()->selectGetAllRootsValid())
+ {
+ LLNotificationsUtil::add("UnableToBuyWhileDownloading");
+ return;
+ }
+
+ LLUUID owner_id;
+ std::string owner_name;
+ BOOL owners_identical = LLSelectMgr::getInstance()->selectGetOwner(owner_id, owner_name);
+ if (!owners_identical)
+ {
+ LLNotificationsUtil::add("CannotBuyObjectsFromDifferentOwners");
+ return;
+ }
+
+ LLPermissions perm;
+ BOOL valid = LLSelectMgr::getInstance()->selectGetPermissions(perm);
+ LLAggregatePermissions ag_perm;
+ valid &= LLSelectMgr::getInstance()->selectGetAggregatePermissions(ag_perm);
+ if(!valid || !sale_info.isForSale() || !perm.allowTransferTo(gAgent.getID()))
+ {
+ LLNotificationsUtil::add("ObjectNotForSale");
+ return;
+ }
+
+ LLFloaterBuy::show(sale_info);
+}
+
+
+void handle_buy_contents(LLSaleInfo sale_info)
+{
+ LLFloaterBuyContents::show(sale_info);
+}
+
+void handle_region_dump_temp_asset_data(void*)
+{
+ llinfos << "Dumping temporary asset data to simulator logs" << llendl;
+ std::vector<std::string> strings;
+ LLUUID invoice;
+ send_generic_message("dumptempassetdata", strings, invoice);
+}
+
+void handle_region_clear_temp_asset_data(void*)
+{
+ llinfos << "Clearing temporary asset data" << llendl;
+ std::vector<std::string> strings;
+ LLUUID invoice;
+ send_generic_message("cleartempassetdata", strings, invoice);
+}
+
+void handle_region_dump_settings(void*)
+{
+ LLViewerRegion* regionp = gAgent.getRegion();
+ if (regionp)
+ {
+ llinfos << "Damage: " << (regionp->getAllowDamage() ? "on" : "off") << llendl;
+ llinfos << "Landmark: " << (regionp->getAllowLandmark() ? "on" : "off") << llendl;
+ llinfos << "SetHome: " << (regionp->getAllowSetHome() ? "on" : "off") << llendl;
+ llinfos << "ResetHome: " << (regionp->getResetHomeOnTeleport() ? "on" : "off") << llendl;
+ llinfos << "SunFixed: " << (regionp->getSunFixed() ? "on" : "off") << llendl;
+ llinfos << "BlockFly: " << (regionp->getBlockFly() ? "on" : "off") << llendl;
+ llinfos << "AllowP2P: " << (regionp->getAllowDirectTeleport() ? "on" : "off") << llendl;
+ llinfos << "Water: " << (regionp->getWaterHeight()) << llendl;
+ }
+}
+
+void handle_dump_group_info(void *)
+{
+ gAgent.dumpGroupInfo();
+}
+
+void handle_dump_capabilities_info(void *)
+{
+ LLViewerRegion* regionp = gAgent.getRegion();
+ if (regionp)
+ {
+ regionp->logActiveCapabilities();
+ }
+}
+
+void handle_dump_region_object_cache(void*)
+{
+ LLViewerRegion* regionp = gAgent.getRegion();
+ if (regionp)
+ {
+ regionp->dumpCache();
+ }
+}
+
+void handle_dump_focus()
+{
+ LLUICtrl *ctrl = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
+
+ llinfos << "Keyboard focus " << (ctrl ? ctrl->getName() : "(none)") << llendl;
+}
+
+class LLSelfStandUp : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gAgent.standUp();
+ return true;
+ }
+};
+
+bool enable_standup_self()
+{
+ return isAgentAvatarValid() && gAgentAvatarp->isSitting();
+}
+
+class LLSelfSitDown : public view_listener_t
+ {
+ bool handleEvent(const LLSD& userdata)
+ {
+ gAgent.sitDown();
+ return true;
+ }
+ };
+
+bool enable_sitdown_self()
+{
+ return isAgentAvatarValid() && !gAgentAvatarp->isSitting() && !gAgent.getFlying();
+}
+
+// Used from the login screen to aid in UI work on side tray
+void handle_show_side_tray()
+{
+ LLSideTray* side_tray = LLSideTray::getInstance();
+ LLView* root = gViewerWindow->getRootView();
+ // automatically removes and re-adds if there already
+ root->addChild(side_tray);
+}
+
+// Toggle one of "People" panel tabs in side tray.
+class LLTogglePanelPeopleTab : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string panel_name = userdata.asString();
+
+ LLSD param;
+ param["people_panel_tab_name"] = panel_name;
+
+ static LLPanel* friends_panel = NULL;
+ static LLPanel* groups_panel = NULL;
+ static LLPanel* nearby_panel = NULL;
+
+ if (panel_name == "friends_panel")
+ {
+ return togglePeoplePanel(friends_panel, panel_name, param);
+ }
+ else if (panel_name == "groups_panel")
+ {
+ return togglePeoplePanel(groups_panel, panel_name, param);
+ }
+ else if (panel_name == "nearby_panel")
+ {
+ return togglePeoplePanel(nearby_panel, panel_name, param);
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ static bool togglePeoplePanel(LLPanel* &panel, const std::string& panel_name, const LLSD& param)
+ {
+ if(!panel)
+ {
+ panel = LLSideTray::getInstance()->getPanel(panel_name);
+ if(!panel)
+ return false;
+ }
+
+ LLSideTray::getInstance()->togglePanel(panel, "panel_people", param);
+
+ return true;
+ }
+};
+
+BOOL check_admin_override(void*)
+{
+ return gAgent.getAdminOverride();
+}
+
+void handle_admin_override_toggle(void*)
+{
+ gAgent.setAdminOverride(!gAgent.getAdminOverride());
+
+ // The above may have affected which debug menus are visible
+ show_debug_menus();
+}
+
+void handle_god_mode(void*)
+{
+ gAgent.requestEnterGodMode();
+}
+
+void handle_leave_god_mode(void*)
+{
+ gAgent.requestLeaveGodMode();
+}
+
+void set_god_level(U8 god_level)
+{
+ U8 old_god_level = gAgent.getGodLevel();
+ gAgent.setGodLevel( god_level );
+ LLViewerParcelMgr::getInstance()->notifyObservers();
+
+ // God mode changes region visibility
+ LLWorldMap::getInstance()->reloadItems(true);
+
+ // inventory in items may change in god mode
+ gObjectList.dirtyAllObjectInventory();
+
+ if(gViewerWindow)
+ {
+ gViewerWindow->setMenuBackgroundColor(god_level > GOD_NOT,
+ LLGridManager::getInstance()->isInProductionGrid());
+ }
+
+ LLSD args;
+ if(god_level > GOD_NOT)
+ {
+ args["LEVEL"] = llformat("%d",(S32)god_level);
+ LLNotificationsUtil::add("EnteringGodMode", args);
+ }
+ else
+ {
+ args["LEVEL"] = llformat("%d",(S32)old_god_level);
+ LLNotificationsUtil::add("LeavingGodMode", args);
+ }
+
+ // changing god-level can affect which menus we see
+ show_debug_menus();
+
+ // changing god-level can invalidate search results
+ LLFloaterSearch *search = dynamic_cast<LLFloaterSearch*>(LLFloaterReg::getInstance("search"));
+ if (search)
+ {
+ search->godLevelChanged(god_level);
+ }
+}
+
+#ifdef TOGGLE_HACKED_GODLIKE_VIEWER
+void handle_toggle_hacked_godmode(void*)
+{
+ gHackGodmode = !gHackGodmode;
+ set_god_level(gHackGodmode ? GOD_MAINTENANCE : GOD_NOT);
+}
+
+BOOL check_toggle_hacked_godmode(void*)
+{
+ return gHackGodmode;
+}
+
+bool enable_toggle_hacked_godmode(void*)
+{
+ return !LLGridManager::getInstance()->isInProductionGrid();
+}
+#endif
+
+void process_grant_godlike_powers(LLMessageSystem* msg, void**)
+{
+ LLUUID agent_id;
+ msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, agent_id);
+ LLUUID session_id;
+ msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_SessionID, session_id);
+ if((agent_id == gAgent.getID()) && (session_id == gAgent.getSessionID()))
+ {
+ U8 god_level;
+ msg->getU8Fast(_PREHASH_GrantData, _PREHASH_GodLevel, god_level);
+ set_god_level(god_level);
+ }
+ else
+ {
+ llwarns << "Grant godlike for wrong agent " << agent_id << llendl;
+ }
+}
+
+/*
+class LLHaveCallingcard : public LLInventoryCollectFunctor
+{
+public:
+ LLHaveCallingcard(const LLUUID& agent_id);
+ virtual ~LLHaveCallingcard() {}
+ virtual bool operator()(LLInventoryCategory* cat,
+ LLInventoryItem* item);
+ BOOL isThere() const { return mIsThere;}
+protected:
+ LLUUID mID;
+ BOOL mIsThere;
+};
+
+LLHaveCallingcard::LLHaveCallingcard(const LLUUID& agent_id) :
+ mID(agent_id),
+ mIsThere(FALSE)
+{
+}
+
+bool LLHaveCallingcard::operator()(LLInventoryCategory* cat,
+ LLInventoryItem* item)
+{
+ if(item)
+ {
+ if((item->getType() == LLAssetType::AT_CALLINGCARD)
+ && (item->getCreatorUUID() == mID))
+ {
+ mIsThere = TRUE;
+ }
+ }
+ return FALSE;
+}
+*/
+
+BOOL is_agent_mappable(const LLUUID& agent_id)
+{
+ const LLRelationship* buddy_info = NULL;
+ bool is_friend = LLAvatarActions::isFriend(agent_id);
+
+ if (is_friend)
+ buddy_info = LLAvatarTracker::instance().getBuddyInfo(agent_id);
+
+ return (buddy_info &&
+ buddy_info->isOnline() &&
+ buddy_info->isRightGrantedFrom(LLRelationship::GRANT_MAP_LOCATION)
+ );
+}
+
+
+// Enable a menu item when you don't have someone's card.
+class LLAvatarEnableAddFriend : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar* avatar = find_avatar_from_object(LLSelectMgr::getInstance()->getSelection()->getPrimaryObject());
+ bool new_value = avatar && !LLAvatarActions::isFriend(avatar->getID());
+ return new_value;
+ }
+};
+
+void request_friendship(const LLUUID& dest_id)
+{
+ LLViewerObject* dest = gObjectList.findObject(dest_id);
+ if(dest && dest->isAvatar())
+ {
+ std::string full_name;
+ LLNameValue* nvfirst = dest->getNVPair("FirstName");
+ LLNameValue* nvlast = dest->getNVPair("LastName");
+ if(nvfirst && nvlast)
+ {
+ full_name = LLCacheName::buildFullName(
+ nvfirst->getString(), nvlast->getString());
+ }
+ if (!full_name.empty())
+ {
+ LLAvatarActions::requestFriendshipDialog(dest_id, full_name);
+ }
+ else
+ {
+ LLNotificationsUtil::add("CantOfferFriendship");
+ }
+ }
+}
+
+
+class LLEditEnableCustomizeAvatar : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gAgentWearables.areWearablesLoaded();
+ return new_value;
+ }
+};
+
+class LLEnableEditShape : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ return gAgentWearables.isWearableModifiable(LLWearableType::WT_SHAPE, 0);
+ }
+};
+
+bool is_object_sittable()
+{
+ LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+
+ if (object && object->getPCode() == LL_PCODE_VOLUME)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+}
+
+
+// only works on pie menu
+void handle_object_sit_or_stand()
+{
+ LLPickInfo pick = LLToolPie::getInstance()->getPick();
+ LLViewerObject *object = pick.getObject();;
+ if (!object || pick.mPickType == LLPickInfo::PICK_FLORA)
+ {
+ return;
+ }
+
+ if (sitting_on_selection())
+ {
+ gAgent.standUp();
+ return;
+ }
+
+ // get object selection offset
+
+ if (object && object->getPCode() == LL_PCODE_VOLUME)
+ {
+
+ gMessageSystem->newMessageFast(_PREHASH_AgentRequestSit);
+ gMessageSystem->nextBlockFast(_PREHASH_AgentData);
+ gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
+ gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ gMessageSystem->nextBlockFast(_PREHASH_TargetObject);
+ gMessageSystem->addUUIDFast(_PREHASH_TargetID, object->mID);
+ gMessageSystem->addVector3Fast(_PREHASH_Offset, pick.mObjectOffset);
+
+ object->getRegion()->sendReliableMessage();
+ }
+}
+
+void near_sit_down_point(BOOL success, void *)
+{
+ if (success)
+ {
+ gAgent.setFlying(FALSE);
+ gAgent.setControlFlags(AGENT_CONTROL_SIT_ON_GROUND);
+
+ // Might be first sit
+ //LLFirstUse::useSit();
+ }
+}
+
+class LLLandSit : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gAgent.standUp();
+ LLViewerParcelMgr::getInstance()->deselectLand();
+
+ LLVector3d posGlobal = LLToolPie::getInstance()->getPick().mPosGlobal;
+
+ LLQuaternion target_rot;
+ if (isAgentAvatarValid())
+ {
+ target_rot = gAgentAvatarp->getRotation();
+ }
+ else
+ {
+ target_rot = gAgent.getFrameAgent().getQuaternion();
+ }
+ gAgent.startAutoPilotGlobal(posGlobal, "Sit", &target_rot, near_sit_down_point, NULL, 0.7f);
+ return true;
+ }
+};
+
+//-------------------------------------------------------------------
+// Help menu functions
+//-------------------------------------------------------------------
+
+//
+// Major mode switching
+//
+void reset_view_final( BOOL proceed );
+
+void handle_reset_view()
+{
+ if (gAgentCamera.cameraCustomizeAvatar())
+ {
+ // switching to outfit selector should automagically save any currently edited wearable
+ LLSideTray::getInstance()->showPanel("sidepanel_appearance", LLSD().with("type", "my_outfits"));
+ }
+
+ gAgentCamera.switchCameraPreset(CAMERA_PRESET_REAR_VIEW);
+ reset_view_final( TRUE );
+ LLFloaterCamera::resetCameraMode();
+}
+
+class LLViewResetView : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ handle_reset_view();
+ return true;
+ }
+};
+
+// Note: extra parameters allow this function to be called from dialog.
+void reset_view_final( BOOL proceed )
+{
+ if( !proceed )
+ {
+ return;
+ }
+
+ gAgentCamera.resetView(TRUE, TRUE);
+ gAgentCamera.setLookAt(LOOKAT_TARGET_CLEAR);
+}
+
+class LLViewLookAtLastChatter : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gAgentCamera.lookAtLastChat();
+ return true;
+ }
+};
+
+class LLViewMouselook : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if (!gAgentCamera.cameraMouselook())
+ {
+ gAgentCamera.changeCameraToMouselook();
+ }
+ else
+ {
+ gAgentCamera.changeCameraToDefault();
+ }
+ return true;
+ }
+};
+
+class LLViewDefaultUISize : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gSavedSettings.setF32("UIScaleFactor", 1.0f);
+ gSavedSettings.setBOOL("UIAutoScale", FALSE);
+ gViewerWindow->reshape(gViewerWindow->getWindowWidthRaw(), gViewerWindow->getWindowHeightRaw());
+ return true;
+ }
+};
+
+class LLEditDuplicate : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if(LLEditMenuHandler::gEditMenuHandler)
+ {
+ LLEditMenuHandler::gEditMenuHandler->duplicate();
+ }
+ return true;
+ }
+};
+
+class LLEditEnableDuplicate : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canDuplicate();
+ return new_value;
+ }
+};
+
+void handle_duplicate_in_place(void*)
+{
+ llinfos << "handle_duplicate_in_place" << llendl;
+
+ LLVector3 offset(0.f, 0.f, 0.f);
+ LLSelectMgr::getInstance()->selectDuplicate(offset, TRUE);
+}
+
+/* dead code 30-apr-2008
+void handle_deed_object_to_group(void*)
+{
+ LLUUID group_id;
+
+ LLSelectMgr::getInstance()->selectGetGroup(group_id);
+ LLSelectMgr::getInstance()->sendOwner(LLUUID::null, group_id, FALSE);
+ LLViewerStats::getInstance()->incStat(LLViewerStats::ST_RELEASE_COUNT);
+}
+
+BOOL enable_deed_object_to_group(void*)
+{
+ if(LLSelectMgr::getInstance()->getSelection()->isEmpty()) return FALSE;
+ LLPermissions perm;
+ LLUUID group_id;
+
+ if (LLSelectMgr::getInstance()->selectGetGroup(group_id) &&
+ gAgent.hasPowerInGroup(group_id, GP_OBJECT_DEED) &&
+ LLSelectMgr::getInstance()->selectGetPermissions(perm) &&
+ perm.deedToGroup(gAgent.getID(), group_id))
+ {
+ return TRUE;
+ }
+ return FALSE;
+}
+
+*/
+
+
+/*
+ * No longer able to support viewer side manipulations in this way
+ *
+void god_force_inv_owner_permissive(LLViewerObject* object,
+ LLInventoryObject::object_list_t* inventory,
+ S32 serial_num,
+ void*)
+{
+ typedef std::vector<LLPointer<LLViewerInventoryItem> > item_array_t;
+ item_array_t items;
+
+ LLInventoryObject::object_list_t::const_iterator inv_it = inventory->begin();
+ LLInventoryObject::object_list_t::const_iterator inv_end = inventory->end();
+ for ( ; inv_it != inv_end; ++inv_it)
+ {
+ if(((*inv_it)->getType() != LLAssetType::AT_CATEGORY))
+ {
+ LLInventoryObject* obj = *inv_it;
+ LLPointer<LLViewerInventoryItem> new_item = new LLViewerInventoryItem((LLViewerInventoryItem*)obj);
+ LLPermissions perm(new_item->getPermissions());
+ perm.setMaskBase(PERM_ALL);
+ perm.setMaskOwner(PERM_ALL);
+ new_item->setPermissions(perm);
+ items.push_back(new_item);
+ }
+ }
+ item_array_t::iterator end = items.end();
+ item_array_t::iterator it;
+ for(it = items.begin(); it != end; ++it)
+ {
+ // since we have the inventory item in the callback, it should not
+ // invalidate iteration through the selection manager.
+ object->updateInventory((*it), TASK_INVENTORY_ITEM_KEY, false);
+ }
+}
+*/
+
+void handle_object_owner_permissive(void*)
+{
+ // only send this if they're a god.
+ if(gAgent.isGodlike())
+ {
+ // do the objects.
+ LLSelectMgr::getInstance()->selectionSetObjectPermissions(PERM_BASE, TRUE, PERM_ALL, TRUE);
+ LLSelectMgr::getInstance()->selectionSetObjectPermissions(PERM_OWNER, TRUE, PERM_ALL, TRUE);
+ }
+}
+
+void handle_object_owner_self(void*)
+{
+ // only send this if they're a god.
+ if(gAgent.isGodlike())
+ {
+ LLSelectMgr::getInstance()->sendOwner(gAgent.getID(), gAgent.getGroupID(), TRUE);
+ }
+}
+
+// Shortcut to set owner permissions to not editable.
+void handle_object_lock(void*)
+{
+ LLSelectMgr::getInstance()->selectionSetObjectPermissions(PERM_OWNER, FALSE, PERM_MODIFY);
+}
+
+void handle_object_asset_ids(void*)
+{
+ // only send this if they're a god.
+ if (gAgent.isGodlike())
+ {
+ LLSelectMgr::getInstance()->sendGodlikeRequest("objectinfo", "assetids");
+ }
+}
+
+void handle_force_parcel_owner_to_me(void*)
+{
+ LLViewerParcelMgr::getInstance()->sendParcelGodForceOwner( gAgent.getID() );
+}
+
+void handle_force_parcel_to_content(void*)
+{
+ LLViewerParcelMgr::getInstance()->sendParcelGodForceToContent();
+}
+
+void handle_claim_public_land(void*)
+{
+ if (LLViewerParcelMgr::getInstance()->getSelectionRegion() != gAgent.getRegion())
+ {
+ LLNotificationsUtil::add("ClaimPublicLand");
+ return;
+ }
+
+ LLVector3d west_south_global;
+ LLVector3d east_north_global;
+ LLViewerParcelMgr::getInstance()->getSelection(west_south_global, east_north_global);
+ LLVector3 west_south = gAgent.getPosAgentFromGlobal(west_south_global);
+ LLVector3 east_north = gAgent.getPosAgentFromGlobal(east_north_global);
+
+ LLMessageSystem* msg = gMessageSystem;
+ msg->newMessage("GodlikeMessage");
+ msg->nextBlock("AgentData");
+ msg->addUUID("AgentID", gAgent.getID());
+ msg->addUUID("SessionID", gAgent.getSessionID());
+ msg->addUUIDFast(_PREHASH_TransactionID, LLUUID::null); //not used
+ msg->nextBlock("MethodData");
+ msg->addString("Method", "claimpublicland");
+ msg->addUUID("Invoice", LLUUID::null);
+ std::string buffer;
+ buffer = llformat( "%f", west_south.mV[VX]);
+ msg->nextBlock("ParamList");
+ msg->addString("Parameter", buffer);
+ buffer = llformat( "%f", west_south.mV[VY]);
+ msg->nextBlock("ParamList");
+ msg->addString("Parameter", buffer);
+ buffer = llformat( "%f", east_north.mV[VX]);
+ msg->nextBlock("ParamList");
+ msg->addString("Parameter", buffer);
+ buffer = llformat( "%f", east_north.mV[VY]);
+ msg->nextBlock("ParamList");
+ msg->addString("Parameter", buffer);
+ gAgent.sendReliableMessage();
+}
+
+
+
+// HACK for easily testing new avatar geometry
+void handle_god_request_avatar_geometry(void *)
+{
+ if (gAgent.isGodlike())
+ {
+ LLSelectMgr::getInstance()->sendGodlikeRequest("avatar toggle", "");
+ }
+}
+
+
+void derez_objects(EDeRezDestination dest, const LLUUID& dest_id)
+{
+ if(gAgentCamera.cameraMouselook())
+ {
+ gAgentCamera.changeCameraToDefault();
+ }
+ //gInventoryView->setPanelOpen(TRUE);
+
+ std::string error;
+ LLDynamicArray<LLViewerObject*> derez_objects;
+
+ // Check conditions that we can't deal with, building a list of
+ // everything that we'll actually be derezzing.
+ LLViewerRegion* first_region = NULL;
+ for (LLObjectSelection::valid_root_iterator iter = LLSelectMgr::getInstance()->getSelection()->valid_root_begin();
+ iter != LLSelectMgr::getInstance()->getSelection()->valid_root_end(); iter++)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* object = node->getObject();
+ LLViewerRegion* region = object->getRegion();
+ if (!first_region)
+ {
+ first_region = region;
+ }
+ else
+ {
+ if(region != first_region)
+ {
+ // Derez doesn't work at all if the some of the objects
+ // are in regions besides the first object selected.
+
+ // ...crosses region boundaries
+ error = "AcquireErrorObjectSpan";
+ break;
+ }
+ }
+ if (object->isAvatar())
+ {
+ // ...don't acquire avatars
+ continue;
+ }
+
+ // If AssetContainers are being sent back, they will appear as
+ // boxes in the owner's inventory.
+ if (object->getNVPair("AssetContainer")
+ && dest != DRD_RETURN_TO_OWNER)
+ {
+ // this object is an asset container, derez its contents, not it
+ llwarns << "Attempt to derez deprecated AssetContainer object type not supported." << llendl;
+ /*
+ object->requestInventory(container_inventory_arrived,
+ (void *)(BOOL)(DRD_TAKE_INTO_AGENT_INVENTORY == dest));
+ */
+ continue;
+ }
+ BOOL can_derez_current = FALSE;
+ switch(dest)
+ {
+ case DRD_TAKE_INTO_AGENT_INVENTORY:
+ case DRD_TRASH:
+ if( (node->mPermissions->allowTransferTo(gAgent.getID()) && object->permModify())
+ || (node->allowOperationOnNode(PERM_OWNER, GP_OBJECT_MANIPULATE)) )
+ {
+ can_derez_current = TRUE;
+ }
+ break;
+
+ case DRD_RETURN_TO_OWNER:
+ can_derez_current = TRUE;
+ break;
+
+ default:
+ if((node->mPermissions->allowTransferTo(gAgent.getID())
+ && object->permCopy())
+ || gAgent.isGodlike())
+ {
+ can_derez_current = TRUE;
+ }
+ break;
+ }
+ if(can_derez_current)
+ {
+ derez_objects.put(object);
+ }
+ }
+
+ // This constant is based on (1200 - HEADER_SIZE) / 4 bytes per
+ // root. I lopped off a few (33) to provide a bit
+ // pad. HEADER_SIZE is currently 67 bytes, most of which is UUIDs.
+ // This gives us a maximum of 63500 root objects - which should
+ // satisfy anybody.
+ const S32 MAX_ROOTS_PER_PACKET = 250;
+ const S32 MAX_PACKET_COUNT = 254;
+ F32 packets = ceil((F32)derez_objects.count() / (F32)MAX_ROOTS_PER_PACKET);
+ if(packets > (F32)MAX_PACKET_COUNT)
+ {
+ error = "AcquireErrorTooManyObjects";
+ }
+
+ if(error.empty() && derez_objects.count() > 0)
+ {
+ U8 d = (U8)dest;
+ LLUUID tid;
+ tid.generate();
+ U8 packet_count = (U8)packets;
+ S32 object_index = 0;
+ S32 objects_in_packet = 0;
+ LLMessageSystem* msg = gMessageSystem;
+ for(U8 packet_number = 0;
+ packet_number < packet_count;
+ ++packet_number)
+ {
+ msg->newMessageFast(_PREHASH_DeRezObject);
+ msg->nextBlockFast(_PREHASH_AgentData);
+ msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
+ msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ msg->nextBlockFast(_PREHASH_AgentBlock);
+ msg->addUUIDFast(_PREHASH_GroupID, gAgent.getGroupID());
+ msg->addU8Fast(_PREHASH_Destination, d);
+ msg->addUUIDFast(_PREHASH_DestinationID, dest_id);
+ msg->addUUIDFast(_PREHASH_TransactionID, tid);
+ msg->addU8Fast(_PREHASH_PacketCount, packet_count);
+ msg->addU8Fast(_PREHASH_PacketNumber, packet_number);
+ objects_in_packet = 0;
+ while((object_index < derez_objects.count())
+ && (objects_in_packet++ < MAX_ROOTS_PER_PACKET))
+
+ {
+ LLViewerObject* object = derez_objects.get(object_index++);
+ msg->nextBlockFast(_PREHASH_ObjectData);
+ msg->addU32Fast(_PREHASH_ObjectLocalID, object->getLocalID());
+ // VEFFECT: DerezObject
+ LLHUDEffectSpiral* effectp = (LLHUDEffectSpiral*)LLHUDManager::getInstance()->createViewerEffect(LLHUDObject::LL_HUD_EFFECT_POINT, TRUE);
+ effectp->setPositionGlobal(object->getPositionGlobal());
+ effectp->setColor(LLColor4U(gAgent.getEffectColor()));
+ }
+ msg->sendReliable(first_region->getHost());
+ }
+ make_ui_sound("UISndObjectRezOut");
+
+ // Busy count decremented by inventory update, so only increment
+ // if will be causing an update.
+ if (dest != DRD_RETURN_TO_OWNER)
+ {
+ gViewerWindow->getWindow()->incBusyCount();
+ }
+ }
+ else if(!error.empty())
+ {
+ LLNotificationsUtil::add(error);
+ }
+}
+
+void handle_take_copy()
+{
+ if (LLSelectMgr::getInstance()->getSelection()->isEmpty()) return;
+
+ const LLUUID category_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_OBJECT);
+ derez_objects(DRD_ACQUIRE_TO_AGENT_INVENTORY, category_id);
+}
+
+// You can return an object to its owner if it is on your land.
+class LLObjectReturn : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if (LLSelectMgr::getInstance()->getSelection()->isEmpty()) return true;
+
+ mObjectSelection = LLSelectMgr::getInstance()->getEditSelection();
+
+ LLNotificationsUtil::add("ReturnToOwner", LLSD(), LLSD(), boost::bind(&LLObjectReturn::onReturnToOwner, this, _1, _2));
+ return true;
+ }
+
+ bool onReturnToOwner(const LLSD& notification, const LLSD& response)
+ {
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ if (0 == option)
+ {
+ // Ignore category ID for this derez destination.
+ derez_objects(DRD_RETURN_TO_OWNER, LLUUID::null);
+ }
+
+ // drop reference to current selection
+ mObjectSelection = NULL;
+ return false;
+ }
+
+protected:
+ LLObjectSelectionHandle mObjectSelection;
+};
+
+
+// Allow return to owner if one or more of the selected items is
+// over land you own.
+class LLObjectEnableReturn : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if (LLSelectMgr::getInstance()->getSelection()->isEmpty())
+ {
+ // Do not enable if nothing selected
+ return false;
+ }
+#ifdef HACKED_GODLIKE_VIEWER
+ bool new_value = true;
+#else
+ bool new_value = false;
+ if (gAgent.isGodlike())
+ {
+ new_value = true;
+ }
+ else
+ {
+ LLViewerRegion* region = gAgent.getRegion();
+ if (region)
+ {
+ // Estate owners and managers can always return objects.
+ if (region->canManageEstate())
+ {
+ new_value = true;
+ }
+ else
+ {
+ struct f : public LLSelectedObjectFunctor
+ {
+ virtual bool apply(LLViewerObject* obj)
+ {
+ return
+ obj->permModify() ||
+ obj->isReturnable();
+ }
+ } func;
+ const bool firstonly = true;
+ new_value = LLSelectMgr::getInstance()->getSelection()->applyToRootObjects(&func, firstonly);
+ }
+ }
+ }
+#endif
+ return new_value;
+ }
+};
+
+void force_take_copy(void*)
+{
+ if (LLSelectMgr::getInstance()->getSelection()->isEmpty()) return;
+ const LLUUID category_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_OBJECT);
+ derez_objects(DRD_FORCE_TO_GOD_INVENTORY, category_id);
+}
+
+void handle_take()
+{
+ // we want to use the folder this was derezzed from if it's
+ // available. Otherwise, derez to the normal place.
+ if(LLSelectMgr::getInstance()->getSelection()->isEmpty())
+ {
+ return;
+ }
+
+ BOOL you_own_everything = TRUE;
+ BOOL locked_but_takeable_object = FALSE;
+ LLUUID category_id;
+
+ for (LLObjectSelection::root_iterator iter = LLSelectMgr::getInstance()->getSelection()->root_begin();
+ iter != LLSelectMgr::getInstance()->getSelection()->root_end(); iter++)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* object = node->getObject();
+ if(object)
+ {
+ if(!object->permYouOwner())
+ {
+ you_own_everything = FALSE;
+ }
+
+ if(!object->permMove())
+ {
+ locked_but_takeable_object = TRUE;
+ }
+ }
+ if(node->mFolderID.notNull())
+ {
+ if(category_id.isNull())
+ {
+ category_id = node->mFolderID;
+ }
+ else if(category_id != node->mFolderID)
+ {
+ // we have found two potential destinations. break out
+ // now and send to the default location.
+ category_id.setNull();
+ break;
+ }
+ }
+ }
+ if(category_id.notNull())
+ {
+ // there is an unambiguous destination. See if this agent has
+ // such a location and it is not in the trash or library
+ if(!gInventory.getCategory(category_id))
+ {
+ // nope, set to NULL.
+ category_id.setNull();
+ }
+ if(category_id.notNull())
+ {
+ // check trash
+ const LLUUID trash = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
+ if(category_id == trash || gInventory.isObjectDescendentOf(category_id, trash))
+ {
+ category_id.setNull();
+ }
+
+ // check library
+ if(gInventory.isObjectDescendentOf(category_id, gInventory.getLibraryRootFolderID()))
+ {
+ category_id.setNull();
+ }
+
+ }
+ }
+ if(category_id.isNull())
+ {
+ category_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_OBJECT);
+ }
+ LLSD payload;
+ payload["folder_id"] = category_id;
+
+ LLNotification::Params params("ConfirmObjectTakeLock");
+ params.payload(payload);
+ params.functor.function(confirm_take);
+
+ if(locked_but_takeable_object ||
+ !you_own_everything)
+ {
+ if(locked_but_takeable_object && you_own_everything)
+ {
+ params.name("ConfirmObjectTakeLock");
+ }
+ else if(!locked_but_takeable_object && !you_own_everything)
+ {
+ params.name("ConfirmObjectTakeNoOwn");
+ }
+ else
+ {
+ params.name("ConfirmObjectTakeLockNoOwn");
+ }
+
+ LLNotifications::instance().add(params);
+ }
+ else
+ {
+ LLNotifications::instance().forceResponse(params, 0);
+ }
+}
+
+void handle_object_show_inspector()
+{
+ LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
+ LLViewerObject* objectp = selection->getFirstRootObject(TRUE);
+ if (!objectp)
+ {
+ return;
+ }
+
+ LLSD params;
+ params["object_id"] = objectp->getID();
+ LLFloaterReg::showInstance("inspect_object", params);
+}
+
+void handle_avatar_show_inspector()
+{
+ LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
+ if(avatar)
+ {
+ LLSD params;
+ params["avatar_id"] = avatar->getID();
+ LLFloaterReg::showInstance("inspect_avatar", params);
+ }
+}
+
+
+
+bool confirm_take(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ if(enable_take() && (option == 0))
+ {
+ derez_objects(DRD_TAKE_INTO_AGENT_INVENTORY, notification["payload"]["folder_id"].asUUID());
+ }
+ return false;
+}
+
+// You can take an item when it is public and transferrable, or when
+// you own it. We err on the side of enabling the item when at least
+// one item selected can be copied to inventory.
+BOOL enable_take()
+{
+ if (sitting_on_selection())
+ {
+ return FALSE;
+ }
+
+ for (LLObjectSelection::valid_root_iterator iter = LLSelectMgr::getInstance()->getSelection()->valid_root_begin();
+ iter != LLSelectMgr::getInstance()->getSelection()->valid_root_end(); iter++)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* object = node->getObject();
+ if (object->isAvatar())
+ {
+ // ...don't acquire avatars
+ continue;
+ }
+
+#ifdef HACKED_GODLIKE_VIEWER
+ return TRUE;
+#else
+# ifdef TOGGLE_HACKED_GODLIKE_VIEWER
+ if (!LLGridManager::getInstance()->isInProductionGrid()
+ && gAgent.isGodlike())
+ {
+ return TRUE;
+ }
+# endif
+ if((node->mPermissions->allowTransferTo(gAgent.getID())
+ && object->permModify())
+ || (node->mPermissions->getOwner() == gAgent.getID()))
+ {
+ return TRUE;
+ }
+#endif
+ }
+ return FALSE;
+}
+
+
+void handle_buy_or_take()
+{
+ if (LLSelectMgr::getInstance()->getSelection()->isEmpty())
+ {
+ return;
+ }
+
+ if (is_selection_buy_not_take())
+ {
+ S32 total_price = selection_price();
+
+ if (total_price <= gStatusBar->getBalance() || total_price == 0)
+ {
+ handle_buy();
+ }
+ else
+ {
+ LLStringUtil::format_map_t args;
+ args["AMOUNT"] = llformat("%d", total_price);
+ LLBuyCurrencyHTML::openCurrencyFloater( LLTrans::getString( "BuyingCosts", args ), total_price );
+ }
+ }
+ else
+ {
+ handle_take();
+ }
+}
+
+bool visible_buy_object()
+{
+ return is_selection_buy_not_take() && enable_buy_object();
+}
+
+bool visible_take_object()
+{
+ return !is_selection_buy_not_take() && enable_take();
+}
+
+bool tools_visible_buy_object()
+{
+ return is_selection_buy_not_take();
+}
+
+bool tools_visible_take_object()
+{
+ return !is_selection_buy_not_take();
+}
+
+class LLToolsEnableBuyOrTake : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool is_buy = is_selection_buy_not_take();
+ bool new_value = is_buy ? enable_buy_object() : enable_take();
+ return new_value;
+ }
+};
+
+// This is a small helper function to determine if we have a buy or a
+// take in the selection. This method is to help with the aliasing
+// problems of putting buy and take in the same pie menu space. After
+// a fair amont of discussion, it was determined to prefer buy over
+// take. The reasoning follows from the fact that when users walk up
+// to buy something, they will click on one or more items. Thus, if
+// anything is for sale, it becomes a buy operation, and the server
+// will group all of the buy items, and copyable/modifiable items into
+// one package and give the end user as much as the permissions will
+// allow. If the user wanted to take something, they will select fewer
+// and fewer items until only 'takeable' items are left. The one
+// exception is if you own everything in the selection that is for
+// sale, in this case, you can't buy stuff from yourself, so you can
+// take it.
+// return value = TRUE if selection is a 'buy'.
+// FALSE if selection is a 'take'
+BOOL is_selection_buy_not_take()
+{
+ for (LLObjectSelection::root_iterator iter = LLSelectMgr::getInstance()->getSelection()->root_begin();
+ iter != LLSelectMgr::getInstance()->getSelection()->root_end(); iter++)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* obj = node->getObject();
+ if(obj && !(obj->permYouOwner()) && (node->mSaleInfo.isForSale()))
+ {
+ // you do not own the object and it is for sale, thus,
+ // it's a buy
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+S32 selection_price()
+{
+ S32 total_price = 0;
+ for (LLObjectSelection::root_iterator iter = LLSelectMgr::getInstance()->getSelection()->root_begin();
+ iter != LLSelectMgr::getInstance()->getSelection()->root_end(); iter++)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* obj = node->getObject();
+ if(obj && !(obj->permYouOwner()) && (node->mSaleInfo.isForSale()))
+ {
+ // you do not own the object and it is for sale.
+ // Add its price.
+ total_price += node->mSaleInfo.getSalePrice();
+ }
+ }
+
+ return total_price;
+}
+/*
+bool callback_show_buy_currency(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ if (0 == option)
+ {
+ llinfos << "Loading page " << LLNotifications::instance().getGlobalString("BUY_CURRENCY_URL") << llendl;
+ LLWeb::loadURL(LLNotifications::instance().getGlobalString("BUY_CURRENCY_URL"));
+ }
+ return false;
+}
+*/
+
+void show_buy_currency(const char* extra)
+{
+ // Don't show currency web page for branded clients.
+/*
+ std::ostringstream mesg;
+ if (extra != NULL)
+ {
+ mesg << extra << "\n \n";
+ }
+ mesg << "Go to " << LLNotifications::instance().getGlobalString("BUY_CURRENCY_URL")<< "\nfor information on purchasing currency?";
+*/
+ LLSD args;
+ if (extra != NULL)
+ {
+ args["EXTRA"] = extra;
+ }
+ LLNotificationsUtil::add("PromptGoToCurrencyPage", args);//, LLSD(), callback_show_buy_currency);
+}
+
+void handle_buy()
+{
+ if (LLSelectMgr::getInstance()->getSelection()->isEmpty()) return;
+
+ LLSaleInfo sale_info;
+ BOOL valid = LLSelectMgr::getInstance()->selectGetSaleInfo(sale_info);
+ if (!valid) return;
+
+ S32 price = sale_info.getSalePrice();
+
+ if (price > 0 && price > gStatusBar->getBalance())
+ {
+ LLStringUtil::format_map_t args;
+ args["AMOUNT"] = llformat("%d", price);
+ LLBuyCurrencyHTML::openCurrencyFloater( LLTrans::getString("this_object_costs", args), price );
+ return;
+ }
+
+ if (sale_info.getSaleType() == LLSaleInfo::FS_CONTENTS)
+ {
+ handle_buy_contents(sale_info);
+ }
+ else
+ {
+ handle_buy_object(sale_info);
+ }
+}
+
+bool anyone_copy_selection(LLSelectNode* nodep)
+{
+ bool perm_copy = (bool)(nodep->getObject()->permCopy());
+ bool all_copy = (bool)(nodep->mPermissions->getMaskEveryone() & PERM_COPY);
+ return perm_copy && all_copy;
+}
+
+bool for_sale_selection(LLSelectNode* nodep)
+{
+ return nodep->mSaleInfo.isForSale()
+ && nodep->mPermissions->getMaskOwner() & PERM_TRANSFER
+ && (nodep->mPermissions->getMaskOwner() & PERM_COPY
+ || nodep->mSaleInfo.getSaleType() != LLSaleInfo::FS_COPY);
+}
+
+BOOL sitting_on_selection()
+{
+ LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
+ if (!node)
+ {
+ return FALSE;
+ }
+
+ if (!node->mValid)
+ {
+ return FALSE;
+ }
+
+ LLViewerObject* root_object = node->getObject();
+ if (!root_object)
+ {
+ return FALSE;
+ }
+
+ // Need to determine if avatar is sitting on this object
+ if (!isAgentAvatarValid()) return FALSE;
+
+ return (gAgentAvatarp->isSitting() && gAgentAvatarp->getRoot() == root_object);
+}
+
+class LLToolsSaveToInventory : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if(enable_save_into_inventory(NULL))
+ {
+ derez_objects(DRD_SAVE_INTO_AGENT_INVENTORY, LLUUID::null);
+ }
+ return true;
+ }
+};
+
+class LLToolsSaveToObjectInventory : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
+ if(node && (node->mValid) && (!node->mFromTaskID.isNull()))
+ {
+ // *TODO: check to see if the fromtaskid object exists.
+ derez_objects(DRD_SAVE_INTO_TASK_INVENTORY, node->mFromTaskID);
+ }
+ return true;
+ }
+};
+
+// Round the position of all root objects to the grid
+class LLToolsSnapObjectXY : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ F64 snap_size = (F64)gSavedSettings.getF32("GridResolution");
+
+ for (LLObjectSelection::root_iterator iter = LLSelectMgr::getInstance()->getSelection()->root_begin();
+ iter != LLSelectMgr::getInstance()->getSelection()->root_end(); iter++)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* obj = node->getObject();
+ if (obj->permModify())
+ {
+ LLVector3d pos_global = obj->getPositionGlobal();
+ F64 round_x = fmod(pos_global.mdV[VX], snap_size);
+ if (round_x < snap_size * 0.5)
+ {
+ // closer to round down
+ pos_global.mdV[VX] -= round_x;
+ }
+ else
+ {
+ // closer to round up
+ pos_global.mdV[VX] -= round_x;
+ pos_global.mdV[VX] += snap_size;
+ }
+
+ F64 round_y = fmod(pos_global.mdV[VY], snap_size);
+ if (round_y < snap_size * 0.5)
+ {
+ pos_global.mdV[VY] -= round_y;
+ }
+ else
+ {
+ pos_global.mdV[VY] -= round_y;
+ pos_global.mdV[VY] += snap_size;
+ }
+
+ obj->setPositionGlobal(pos_global, FALSE);
+ }
+ }
+ LLSelectMgr::getInstance()->sendMultipleUpdate(UPD_POSITION);
+ return true;
+ }
+};
+
+// Determine if the option to cycle between linked prims is shown
+class LLToolsEnableSelectNextPart : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = (gSavedSettings.getBOOL("EditLinkedParts") &&
+ !LLSelectMgr::getInstance()->getSelection()->isEmpty());
+ return new_value;
+ }
+};
+
+// Cycle selection through linked children in selected object.
+// FIXME: Order of children list is not always the same as sim's idea of link order. This may confuse
+// resis. Need link position added to sim messages to address this.
+class LLToolsSelectNextPart : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ S32 object_count = LLSelectMgr::getInstance()->getSelection()->getObjectCount();
+ if (gSavedSettings.getBOOL("EditLinkedParts") && object_count)
+ {
+ LLViewerObject* selected = LLSelectMgr::getInstance()->getSelection()->getFirstObject();
+ if (selected && selected->getRootEdit())
+ {
+ bool fwd = (userdata.asString() == "next");
+ bool prev = (userdata.asString() == "previous");
+ bool ifwd = (userdata.asString() == "includenext");
+ bool iprev = (userdata.asString() == "includeprevious");
+ LLViewerObject* to_select = NULL;
+ LLViewerObject::child_list_t children = selected->getRootEdit()->getChildren();
+ children.push_front(selected->getRootEdit()); // need root in the list too
+
+ for (LLViewerObject::child_list_t::iterator iter = children.begin(); iter != children.end(); ++iter)
+ {
+ if ((*iter)->isSelected())
+ {
+ if (object_count > 1 && (fwd || prev)) // multiple selection, find first or last selected if not include
+ {
+ to_select = *iter;
+ if (fwd)
+ {
+ // stop searching if going forward; repeat to get last hit if backward
+ break;
+ }
+ }
+ else if ((object_count == 1) || (ifwd || iprev)) // single selection or include
+ {
+ if (fwd || ifwd)
+ {
+ ++iter;
+ while (iter != children.end() && ((*iter)->isAvatar() || (ifwd && (*iter)->isSelected())))
+ {
+ ++iter; // skip sitting avatars and selected if include
+ }
+ }
+ else // backward
+ {
+ iter = (iter == children.begin() ? children.end() : iter);
+ --iter;
+ while (iter != children.begin() && ((*iter)->isAvatar() || (iprev && (*iter)->isSelected())))
+ {
+ --iter; // skip sitting avatars and selected if include
+ }
+ }
+ iter = (iter == children.end() ? children.begin() : iter);
+ to_select = *iter;
+ break;
+ }
+ }
+ }
+
+ if (to_select)
+ {
+ if (gFocusMgr.childHasKeyboardFocus(gFloaterTools))
+ {
+ gFocusMgr.setKeyboardFocus(NULL); // force edit toolbox to commit any changes
+ }
+ if (fwd || prev)
+ {
+ LLSelectMgr::getInstance()->deselectAll();
+ }
+ LLSelectMgr::getInstance()->selectObjectOnly(to_select);
+ return true;
+ }
+ }
+ }
+ return true;
+ }
+};
+
+class LLToolsStopAllAnimations : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gAgent.stopCurrentAnimations();
+ return true;
+ }
+};
+
+class LLToolsReleaseKeys : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gAgent.forceReleaseControls();
+
+ return true;
+ }
+};
+
+class LLToolsEnableReleaseKeys : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ return gAgent.anyControlGrabbed();
+ }
+};
+
+
+class LLEditEnableCut : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canCut();
+ return new_value;
+ }
+};
+
+class LLEditCut : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if( LLEditMenuHandler::gEditMenuHandler )
+ {
+ LLEditMenuHandler::gEditMenuHandler->cut();
+ }
+ return true;
+ }
+};
+
+class LLEditEnableCopy : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canCopy();
+ return new_value;
+ }
+};
+
+class LLEditCopy : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if( LLEditMenuHandler::gEditMenuHandler )
+ {
+ LLEditMenuHandler::gEditMenuHandler->copy();
+ }
+ return true;
+ }
+};
+
+class LLEditEnablePaste : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canPaste();
+ return new_value;
+ }
+};
+
+class LLEditPaste : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if( LLEditMenuHandler::gEditMenuHandler )
+ {
+ LLEditMenuHandler::gEditMenuHandler->paste();
+ }
+ return true;
+ }
+};
+
+class LLEditEnableDelete : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canDoDelete();
+ return new_value;
+ }
+};
+
+class LLEditDelete : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ // If a text field can do a deletion, it gets precedence over deleting
+ // an object in the world.
+ if( LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canDoDelete())
+ {
+ LLEditMenuHandler::gEditMenuHandler->doDelete();
+ }
+
+ // and close any pie/context menus when done
+ gMenuHolder->hideMenus();
+
+ // When deleting an object we may not actually be done
+ // Keep selection so we know what to delete when confirmation is needed about the delete
+ gMenuObject->hide();
+ return true;
+ }
+};
+
+bool enable_object_delete()
+{
+ bool new_value =
+#ifdef HACKED_GODLIKE_VIEWER
+ TRUE;
+#else
+# ifdef TOGGLE_HACKED_GODLIKE_VIEWER
+ (!LLGridManager::getInstance()->isInProductionGrid()
+ && gAgent.isGodlike()) ||
+# endif
+ LLSelectMgr::getInstance()->canDoDelete();
+#endif
+ return new_value;
+}
+
+void handle_object_delete()
+{
+
+ if (LLSelectMgr::getInstance())
+ {
+ LLSelectMgr::getInstance()->doDelete();
+ }
+
+ // and close any pie/context menus when done
+ gMenuHolder->hideMenus();
+
+ // When deleting an object we may not actually be done
+ // Keep selection so we know what to delete when confirmation is needed about the delete
+ gMenuObject->hide();
+ return;
+}
+
+void handle_force_delete(void*)
+{
+ LLSelectMgr::getInstance()->selectForceDelete();
+}
+
+class LLViewEnableJoystickFlycam : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = (gSavedSettings.getBOOL("JoystickEnabled") && gSavedSettings.getBOOL("JoystickFlycamEnabled"));
+ return new_value;
+ }
+};
+
+class LLViewEnableLastChatter : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ // *TODO: add check that last chatter is in range
+ bool new_value = (gAgentCamera.cameraThirdPerson() && gAgent.getLastChatter().notNull());
+ return new_value;
+ }
+};
+
+class LLEditEnableDeselect : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canDeselect();
+ return new_value;
+ }
+};
+
+class LLEditDeselect : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if( LLEditMenuHandler::gEditMenuHandler )
+ {
+ LLEditMenuHandler::gEditMenuHandler->deselect();
+ }
+ return true;
+ }
+};
+
+class LLEditEnableSelectAll : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canSelectAll();
+ return new_value;
+ }
+};
+
+
+class LLEditSelectAll : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if( LLEditMenuHandler::gEditMenuHandler )
+ {
+ LLEditMenuHandler::gEditMenuHandler->selectAll();
+ }
+ return true;
+ }
+};
+
+
+class LLEditEnableUndo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canUndo();
+ return new_value;
+ }
+};
+
+class LLEditUndo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if( LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canUndo() )
+ {
+ LLEditMenuHandler::gEditMenuHandler->undo();
+ }
+ return true;
+ }
+};
+
+class LLEditEnableRedo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canRedo();
+ return new_value;
+ }
+};
+
+class LLEditRedo : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if( LLEditMenuHandler::gEditMenuHandler && LLEditMenuHandler::gEditMenuHandler->canRedo() )
+ {
+ LLEditMenuHandler::gEditMenuHandler->redo();
+ }
+ return true;
+ }
+};
+
+
+
+void print_object_info(void*)
+{
+ LLSelectMgr::getInstance()->selectionDump();
+}
+
+void print_agent_nvpairs(void*)
+{
+ LLViewerObject *objectp;
+
+ llinfos << "Agent Name Value Pairs" << llendl;
+
+ objectp = gObjectList.findObject(gAgentID);
+ if (objectp)
+ {
+ objectp->printNameValuePairs();
+ }
+ else
+ {
+ llinfos << "Can't find agent object" << llendl;
+ }
+
+ llinfos << "Camera at " << gAgentCamera.getCameraPositionGlobal() << llendl;
+}
+
+void show_debug_menus()
+{
+ // this might get called at login screen where there is no menu so only toggle it if one exists
+ if ( gMenuBarView )
+ {
+ BOOL debug = gSavedSettings.getBOOL("UseDebugMenus");
+ BOOL qamode = gSavedSettings.getBOOL("QAMode");
+
+ gMenuBarView->setItemVisible("Advanced", debug);
+// gMenuBarView->setItemEnabled("Advanced", debug); // Don't disable Advanced keyboard shortcuts when hidden
+
+ gMenuBarView->setItemVisible("Debug", qamode);
+ gMenuBarView->setItemEnabled("Debug", qamode);
+
+ gMenuBarView->setItemVisible("Develop", qamode);
+ gMenuBarView->setItemEnabled("Develop", qamode);
+
+ // Server ('Admin') menu hidden when not in godmode.
+ const bool show_server_menu = (gAgent.getGodLevel() > GOD_NOT || (debug && gAgent.getAdminOverride()));
+ gMenuBarView->setItemVisible("Admin", show_server_menu);
+ gMenuBarView->setItemEnabled("Admin", show_server_menu);
+ }
+ if (gLoginMenuBarView)
+ {
+ BOOL debug = gSavedSettings.getBOOL("UseDebugMenus");
+ gLoginMenuBarView->setItemVisible("Debug", debug);
+ gLoginMenuBarView->setItemEnabled("Debug", debug);
+ }
+}
+
+void toggle_debug_menus(void*)
+{
+ BOOL visible = ! gSavedSettings.getBOOL("UseDebugMenus");
+ gSavedSettings.setBOOL("UseDebugMenus", visible);
+ show_debug_menus();
+}
+
+
+// LLUUID gExporterRequestID;
+// std::string gExportDirectory;
+
+// LLUploadDialog *gExportDialog = NULL;
+
+// void handle_export_selected( void * )
+// {
+// LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
+// if (selection->isEmpty())
+// {
+// return;
+// }
+// llinfos << "Exporting selected objects:" << llendl;
+
+// gExporterRequestID.generate();
+// gExportDirectory = "";
+
+// LLMessageSystem* msg = gMessageSystem;
+// msg->newMessageFast(_PREHASH_ObjectExportSelected);
+// msg->nextBlockFast(_PREHASH_AgentData);
+// msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
+// msg->addUUIDFast(_PREHASH_RequestID, gExporterRequestID);
+// msg->addS16Fast(_PREHASH_VolumeDetail, 4);
+
+// for (LLObjectSelection::root_iterator iter = selection->root_begin();
+// iter != selection->root_end(); iter++)
+// {
+// LLSelectNode* node = *iter;
+// LLViewerObject* object = node->getObject();
+// msg->nextBlockFast(_PREHASH_ObjectData);
+// msg->addUUIDFast(_PREHASH_ObjectID, object->getID());
+// llinfos << "Object: " << object->getID() << llendl;
+// }
+// msg->sendReliable(gAgent.getRegion()->getHost());
+
+// gExportDialog = LLUploadDialog::modalUploadDialog("Exporting selected objects...");
+// }
+//
+
+
+class LLWorldSetHomeLocation : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ // we just send the message and let the server check for failure cases
+ // server will echo back a "Home position set." alert if it succeeds
+ // and the home location screencapture happens when that alert is recieved
+ gAgent.setStartPosition(START_LOCATION_ID_HOME);
+ return true;
+ }
+};
+
+class LLWorldTeleportHome : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gAgent.teleportHome();
+ return true;
+ }
+};
+
+class LLWorldAlwaysRun : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ // as well as altering the default walk-vs-run state,
+ // we also change the *current* walk-vs-run state.
+ if (gAgent.getAlwaysRun())
+ {
+ gAgent.clearAlwaysRun();
+ gAgent.clearRunning();
+ }
+ else
+ {
+ gAgent.setAlwaysRun();
+ gAgent.setRunning();
+ }
+
+ // tell the simulator.
+ gAgent.sendWalkRun(gAgent.getAlwaysRun());
+
+ // Update Movement Controls according to AlwaysRun mode
+ LLFloaterMove::setAlwaysRunMode(gAgent.getAlwaysRun());
+
+ return true;
+ }
+};
+
+class LLWorldCheckAlwaysRun : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gAgent.getAlwaysRun();
+ return new_value;
+ }
+};
+
+class LLWorldSetAway : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if (gAgent.getAFK())
+ {
+ gAgent.clearAFK();
+ }
+ else
+ {
+ gAgent.setAFK();
+ }
+ return true;
+ }
+};
+
+class LLWorldSetBusy : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if (gAgent.getBusy())
+ {
+ gAgent.clearBusy();
+ }
+ else
+ {
+ gAgent.setBusy();
+ LLNotificationsUtil::add("BusyModeSet");
+ }
+ return true;
+ }
+};
+
+class LLWorldCreateLandmark : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLSideTray::getInstance()->showPanel("panel_places", LLSD().with("type", "create_landmark"));
+
+ return true;
+ }
+};
+
+class LLWorldPlaceProfile : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLSideTray::getInstance()->showPanel("panel_places", LLSD().with("type", "agent"));
+
+ return true;
+ }
+};
+
+void handle_look_at_selection(const LLSD& param)
+{
+ const F32 PADDING_FACTOR = 1.75f;
+ BOOL zoom = (param.asString() == "zoom");
+ if (!LLSelectMgr::getInstance()->getSelection()->isEmpty())
+ {
+ gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
+
+ LLBBox selection_bbox = LLSelectMgr::getInstance()->getBBoxOfSelection();
+ F32 angle_of_view = llmax(0.1f, LLViewerCamera::getInstance()->getAspect() > 1.f ? LLViewerCamera::getInstance()->getView() * LLViewerCamera::getInstance()->getAspect() : LLViewerCamera::getInstance()->getView());
+ F32 distance = selection_bbox.getExtentLocal().magVec() * PADDING_FACTOR / atan(angle_of_view);
+
+ LLVector3 obj_to_cam = LLViewerCamera::getInstance()->getOrigin() - selection_bbox.getCenterAgent();
+ obj_to_cam.normVec();
+
+ LLUUID object_id;
+ if (LLSelectMgr::getInstance()->getSelection()->getPrimaryObject())
+ {
+ object_id = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject()->mID;
+ }
+ if (zoom)
+ {
+ // Make sure we are not increasing the distance between the camera and object
+ LLVector3d orig_distance = gAgentCamera.getCameraPositionGlobal() - LLSelectMgr::getInstance()->getSelectionCenterGlobal();
+ distance = llmin(distance, (F32) orig_distance.length());
+
+ gAgentCamera.setCameraPosAndFocusGlobal(LLSelectMgr::getInstance()->getSelectionCenterGlobal() + LLVector3d(obj_to_cam * distance),
+ LLSelectMgr::getInstance()->getSelectionCenterGlobal(),
+ object_id );
+
+ }
+ else
+ {
+ gAgentCamera.setFocusGlobal( LLSelectMgr::getInstance()->getSelectionCenterGlobal(), object_id );
+ }
+ }
+}
+
+void handle_zoom_to_object(LLUUID object_id)
+{
+ const F32 PADDING_FACTOR = 2.f;
+
+ LLViewerObject* object = gObjectList.findObject(object_id);
+
+ if (object)
+ {
+ gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
+
+ LLBBox bbox = object->getBoundingBoxAgent() ;
+ F32 angle_of_view = llmax(0.1f, LLViewerCamera::getInstance()->getAspect() > 1.f ? LLViewerCamera::getInstance()->getView() * LLViewerCamera::getInstance()->getAspect() : LLViewerCamera::getInstance()->getView());
+ F32 distance = bbox.getExtentLocal().magVec() * PADDING_FACTOR / atan(angle_of_view);
+
+ LLVector3 obj_to_cam = LLViewerCamera::getInstance()->getOrigin() - bbox.getCenterAgent();
+ obj_to_cam.normVec();
+
+
+ LLVector3d object_center_global = gAgent.getPosGlobalFromAgent(bbox.getCenterAgent());
+
+ gAgentCamera.setCameraPosAndFocusGlobal(object_center_global + LLVector3d(obj_to_cam * distance),
+ object_center_global,
+ object_id );
+ }
+}
+
+class LLAvatarInviteToGroup : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
+ if(avatar)
+ {
+ LLAvatarActions::inviteToGroup(avatar->getID());
+ }
+ return true;
+ }
+};
+
+class LLAvatarAddFriend : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
+ if(avatar && !LLAvatarActions::isFriend(avatar->getID()))
+ {
+ request_friendship(avatar->getID());
+ }
+ return true;
+ }
+};
+
+class LLAvatarAddContact : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
+ if(avatar)
+ {
+ create_inventory_callingcard(avatar->getID());
+ }
+ return true;
+ }
+};
+
+bool complete_give_money(const LLSD& notification, const LLSD& response, LLObjectSelectionHandle selection)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ if (option == 0)
+ {
+ gAgent.clearBusy();
+ }
+
+ LLViewerObject* objectp = selection->getPrimaryObject();
+
+ // Show avatar's name if paying attachment
+ if (objectp && objectp->isAttachment())
+ {
+ while (objectp && !objectp->isAvatar())
+ {
+ objectp = (LLViewerObject*)objectp->getParent();
+ }
+ }
+
+ if (objectp)
+ {
+ if (objectp->isAvatar())
+ {
+ const bool is_group = false;
+ LLFloaterPayUtil::payDirectly(&give_money,
+ objectp->getID(),
+ is_group);
+ }
+ else
+ {
+ LLFloaterPayUtil::payViaObject(&give_money, selection);
+ }
+ }
+ return false;
+}
+
+void handle_give_money_dialog()
+{
+ LLNotification::Params params("BusyModePay");
+ params.functor.function(boost::bind(complete_give_money, _1, _2, LLSelectMgr::getInstance()->getSelection()));
+
+ if (gAgent.getBusy())
+ {
+ // warn users of being in busy mode during a transaction
+ LLNotifications::instance().add(params);
+ }
+ else
+ {
+ LLNotifications::instance().forceResponse(params, 1);
+ }
+}
+
+bool enable_pay_avatar()
+{
+ LLViewerObject* obj = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ LLVOAvatar* avatar = find_avatar_from_object(obj);
+ return (avatar != NULL);
+}
+
+bool enable_pay_object()
+{
+ LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ if( object )
+ {
+ LLViewerObject *parent = (LLViewerObject *)object->getParent();
+ if((object->flagTakesMoney()) || (parent && parent->flagTakesMoney()))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool enable_object_stand_up()
+{
+ // 'Object Stand Up' menu item is enabled when agent is sitting on selection
+ return sitting_on_selection();
+}
+
+bool enable_object_sit(LLUICtrl* ctrl)
+{
+ // 'Object Sit' menu item is enabled when agent is not sitting on selection
+ bool sitting_on_sel = sitting_on_selection();
+ if (!sitting_on_sel)
+ {
+ std::string item_name = ctrl->getName();
+
+ // init default labels
+ init_default_item_label(item_name);
+
+ // Update label
+ LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
+ if (node && node->mValid && !node->mSitName.empty())
+ {
+ gMenuHolder->childSetText(item_name, node->mSitName);
+ }
+ else
+ {
+ gMenuHolder->childSetText(item_name, get_default_item_label(item_name));
+ }
+ }
+ return !sitting_on_sel && is_object_sittable();
+}
+
+void dump_select_mgr(void*)
+{
+ LLSelectMgr::getInstance()->dump();
+}
+
+void dump_inventory(void*)
+{
+ gInventory.dumpInventory();
+}
+
+
+void handle_dump_followcam(void*)
+{
+ LLFollowCamMgr::dump();
+}
+
+void handle_viewer_enable_message_log(void*)
+{
+ gMessageSystem->startLogging();
+}
+
+void handle_viewer_disable_message_log(void*)
+{
+ gMessageSystem->stopLogging();
+}
+
+void handle_customize_avatar()
+{
+ LLSideTray::getInstance()->showPanel("sidepanel_appearance", LLSD().with("type", "my_outfits"));
+}
+
+void handle_edit_outfit()
+{
+ LLSideTray::getInstance()->showPanel("sidepanel_appearance", LLSD().with("type", "edit_outfit"));
+}
+
+void handle_edit_shape()
+{
+ LLSideTray::getInstance()->showPanel("sidepanel_appearance", LLSD().with("type", "edit_shape"));
+}
+
+void handle_report_abuse()
+{
+ // Prevent menu from appearing in screen shot.
+ gMenuHolder->hideMenus();
+ LLFloaterReporter::showFromMenu(COMPLAINT_REPORT);
+}
+
+void handle_buy_currency()
+{
+ LLBuyCurrencyHTML::openCurrencyFloater();
+}
+
+class LLFloaterVisible : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string floater_name = userdata.asString();
+ bool new_value = false;
+ {
+ new_value = LLFloaterReg::instanceVisible(floater_name);
+ }
+ return new_value;
+ }
+};
+
+class LLShowHelp : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string help_topic = userdata.asString();
+ LLViewerHelp* vhelp = LLViewerHelp::getInstance();
+ vhelp->showTopic(help_topic);
+ return true;
+ }
+};
+
+class LLToggleHelp : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLFloater* help_browser = (LLFloaterReg::findInstance("help_browser"));
+ if (help_browser && help_browser->isInVisibleChain())
+ {
+ help_browser->closeFloater();
+ }
+ else
+ {
+ std::string help_topic = userdata.asString();
+ LLViewerHelp* vhelp = LLViewerHelp::getInstance();
+ vhelp->showTopic(help_topic);
+ }
+ return true;
+ }
+};
+
+class LLShowSidetrayPanel : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string panel_name = userdata.asString();
+
+ LLPanel* panel = LLSideTray::getInstance()->getPanel(panel_name);
+ if (panel)
+ {
+ if (panel->isInVisibleChain())
+ {
+ LLSideTray::getInstance()->hidePanel(panel_name);
+ }
+ else
+ {
+ LLSideTray::getInstance()->showPanel(panel_name);
+ }
+ }
+ return true;
+ }
+};
+
+class LLSidetrayPanelVisible : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string panel_name = userdata.asString();
+ // Toggle the panel
+ if (LLSideTray::getInstance()->isPanelActive(panel_name))
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+
+ }
+};
+
+
+bool callback_show_url(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ if (0 == option)
+ {
+ LLWeb::loadURL(notification["payload"]["url"].asString());
+ }
+ return false;
+}
+
+class LLPromptShowURL : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string param = userdata.asString();
+ std::string::size_type offset = param.find(",");
+ if (offset != param.npos)
+ {
+ std::string alert = param.substr(0, offset);
+ std::string url = param.substr(offset+1);
+
+ if(gSavedSettings.getBOOL("UseExternalBrowser"))
+ {
+ LLSD payload;
+ payload["url"] = url;
+ LLNotificationsUtil::add(alert, LLSD(), payload, callback_show_url);
+ }
+ else
+ {
+ LLWeb::loadURL(url);
+ }
+ }
+ else
+ {
+ llinfos << "PromptShowURL invalid parameters! Expecting \"ALERT,URL\"." << llendl;
+ }
+ return true;
+ }
+};
+
+bool callback_show_file(const LLSD& notification, const LLSD& response)
+{
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ if (0 == option)
+ {
+ LLWeb::loadURL(notification["payload"]["url"]);
+ }
+ return false;
+}
+
+class LLPromptShowFile : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string param = userdata.asString();
+ std::string::size_type offset = param.find(",");
+ if (offset != param.npos)
+ {
+ std::string alert = param.substr(0, offset);
+ std::string file = param.substr(offset+1);
+
+ LLSD payload;
+ payload["url"] = file;
+ LLNotificationsUtil::add(alert, LLSD(), payload, callback_show_file);
+ }
+ else
+ {
+ llinfos << "PromptShowFile invalid parameters! Expecting \"ALERT,FILE\"." << llendl;
+ }
+ return true;
+ }
+};
+
+class LLShowAgentProfile : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLUUID agent_id;
+ if (userdata.asString() == "agent")
+ {
+ agent_id = gAgent.getID();
+ }
+ else if (userdata.asString() == "hit object")
+ {
+ LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ if (objectp)
+ {
+ agent_id = objectp->getID();
+ }
+ }
+ else
+ {
+ agent_id = userdata.asUUID();
+ }
+
+ LLVOAvatar* avatar = find_avatar_from_object(agent_id);
+ if (avatar)
+ {
+ LLAvatarActions::showProfile(avatar->getID());
+ }
+ return true;
+ }
+};
+
+class LLToggleAgentProfile : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLUUID agent_id;
+ if (userdata.asString() == "agent")
+ {
+ agent_id = gAgent.getID();
+ }
+ else if (userdata.asString() == "hit object")
+ {
+ LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ if (objectp)
+ {
+ agent_id = objectp->getID();
+ }
+ }
+ else
+ {
+ agent_id = userdata.asUUID();
+ }
+
+ LLVOAvatar* avatar = find_avatar_from_object(agent_id);
+ if (avatar)
+ {
+ if (!LLAvatarActions::profileVisible(avatar->getID()))
+ {
+ LLAvatarActions::showProfile(avatar->getID());
+ }
+ else
+ {
+ LLAvatarActions::hideProfile(avatar->getID());
+ }
+ }
+ return true;
+ }
+};
+
+class LLLandEdit : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ if (gAgentCamera.getFocusOnAvatar() && gSavedSettings.getBOOL("EditCameraMovement") )
+ {
+ // zoom in if we're looking at the avatar
+ gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE);
+ gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
+
+ gAgentCamera.cameraOrbitOver( F_PI * 0.25f );
+ gViewerWindow->moveCursorToCenter();
+ }
+ else if ( gSavedSettings.getBOOL("EditCameraMovement") )
+ {
+ gAgentCamera.setFocusGlobal(LLToolPie::getInstance()->getPick());
+ gViewerWindow->moveCursorToCenter();
+ }
+
+
+ LLViewerParcelMgr::getInstance()->selectParcelAt( LLToolPie::getInstance()->getPick().mPosGlobal );
+
+ LLFloaterReg::showInstance("build");
+
+ // Switch to land edit toolset
+ LLToolMgr::getInstance()->getCurrentToolset()->selectTool( LLToolSelectLand::getInstance() );
+ return true;
+ }
+};
+
+class LLWorldEnableBuyLand : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLViewerParcelMgr::getInstance()->canAgentBuyParcel(
+ LLViewerParcelMgr::getInstance()->selectionEmpty()
+ ? LLViewerParcelMgr::getInstance()->getAgentParcel()
+ : LLViewerParcelMgr::getInstance()->getParcelSelection()->getParcel(),
+ false);
+ return new_value;
+ }
+};
+
+BOOL enable_buy_land(void*)
+{
+ return LLViewerParcelMgr::getInstance()->canAgentBuyParcel(
+ LLViewerParcelMgr::getInstance()->getParcelSelection()->getParcel(), false);
+}
+
+void handle_buy_land()
+{
+ LLViewerParcelMgr* vpm = LLViewerParcelMgr::getInstance();
+ if (vpm->selectionEmpty())
+ {
+ vpm->selectParcelAt(gAgent.getPositionGlobal());
+ }
+ vpm->startBuyLand();
+}
+
+class LLObjectAttachToAvatar : public view_listener_t
+{
+public:
+ LLObjectAttachToAvatar(bool replace) : mReplace(replace) {}
+ static void setObjectSelection(LLObjectSelectionHandle selection) { sObjectSelection = selection; }
+
+private:
+ bool handleEvent(const LLSD& userdata)
+ {
+ setObjectSelection(LLSelectMgr::getInstance()->getSelection());
+ LLViewerObject* selectedObject = sObjectSelection->getFirstRootObject();
+ if (selectedObject)
+ {
+ S32 index = userdata.asInteger();
+ LLViewerJointAttachment* attachment_point = NULL;
+ if (index > 0)
+ attachment_point = get_if_there(gAgentAvatarp->mAttachmentPoints, index, (LLViewerJointAttachment*)NULL);
+ confirmReplaceAttachment(0, attachment_point);
+ }
+ return true;
+ }
+
+ static void onNearAttachObject(BOOL success, void *user_data);
+ void confirmReplaceAttachment(S32 option, LLViewerJointAttachment* attachment_point);
+
+ struct CallbackData
+ {
+ CallbackData(LLViewerJointAttachment* point, bool replace) : mAttachmentPoint(point), mReplace(replace) {}
+
+ LLViewerJointAttachment* mAttachmentPoint;
+ bool mReplace;
+ };
+
+protected:
+ static LLObjectSelectionHandle sObjectSelection;
+ bool mReplace;
+};
+
+LLObjectSelectionHandle LLObjectAttachToAvatar::sObjectSelection;
+
+// static
+void LLObjectAttachToAvatar::onNearAttachObject(BOOL success, void *user_data)
+{
+ if (!user_data) return;
+ CallbackData* cb_data = static_cast<CallbackData*>(user_data);
+
+ if (success)
+ {
+ const LLViewerJointAttachment *attachment = cb_data->mAttachmentPoint;
+
+ U8 attachment_id = 0;
+ if (attachment)
+ {
+ for (LLVOAvatar::attachment_map_t::const_iterator iter = gAgentAvatarp->mAttachmentPoints.begin();
+ iter != gAgentAvatarp->mAttachmentPoints.end(); ++iter)
+ {
+ if (iter->second == attachment)
+ {
+ attachment_id = iter->first;
+ break;
+ }
+ }
+ }
+ else
+ {
+ // interpret 0 as "default location"
+ attachment_id = 0;
+ }
+ LLSelectMgr::getInstance()->sendAttach(attachment_id, cb_data->mReplace);
+ }
+ LLObjectAttachToAvatar::setObjectSelection(NULL);
+
+ delete cb_data;
+}
+
+// static
+void LLObjectAttachToAvatar::confirmReplaceAttachment(S32 option, LLViewerJointAttachment* attachment_point)
+{
+ if (option == 0/*YES*/)
+ {
+ LLViewerObject* selectedObject = LLSelectMgr::getInstance()->getSelection()->getFirstRootObject();
+ if (selectedObject)
+ {
+ const F32 MIN_STOP_DISTANCE = 1.f; // meters
+ const F32 ARM_LENGTH = 0.5f; // meters
+ const F32 SCALE_FUDGE = 1.5f;
+
+ F32 stop_distance = SCALE_FUDGE * selectedObject->getMaxScale() + ARM_LENGTH;
+ if (stop_distance < MIN_STOP_DISTANCE)
+ {
+ stop_distance = MIN_STOP_DISTANCE;
+ }
+
+ LLVector3 walkToSpot = selectedObject->getPositionAgent();
+
+ // make sure we stop in front of the object
+ LLVector3 delta = walkToSpot - gAgent.getPositionAgent();
+ delta.normVec();
+ delta = delta * 0.5f;
+ walkToSpot -= delta;
+
+ // The callback will be called even if avatar fails to get close enough to the object, so we won't get a memory leak.
+ CallbackData* user_data = new CallbackData(attachment_point, mReplace);
+ gAgent.startAutoPilotGlobal(gAgent.getPosGlobalFromAgent(walkToSpot), "Attach", NULL, onNearAttachObject, user_data, stop_distance);
+ gAgentCamera.clearFocusObject();
+ }
+ }
+}
+
+void callback_attachment_drop(const LLSD& notification, const LLSD& response)
+{
+ // Ensure user confirmed the drop
+ S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
+ if (option != 0) return;
+
+ // Called when the user clicked on an object attached to them
+ // and selected "Drop".
+ LLUUID object_id = notification["payload"]["object_id"].asUUID();
+ LLViewerObject *object = gObjectList.findObject(object_id);
+
+ if (!object)
+ {
+ llwarns << "handle_drop_attachment() - no object to drop" << llendl;
+ return;
+ }
+
+ LLViewerObject *parent = (LLViewerObject*)object->getParent();
+ while (parent)
+ {
+ if(parent->isAvatar())
+ {
+ break;
+ }
+ object = parent;
+ parent = (LLViewerObject*)parent->getParent();
+ }
+
+ if (!object)
+ {
+ llwarns << "handle_detach() - no object to detach" << llendl;
+ return;
+ }
+
+ if (object->isAvatar())
+ {
+ llwarns << "Trying to detach avatar from avatar." << llendl;
+ return;
+ }
+
+ // reselect the object
+ LLSelectMgr::getInstance()->selectObjectAndFamily(object);
+
+ LLSelectMgr::getInstance()->sendDropAttachment();
+
+ return;
+}
+
+class LLAttachmentDrop : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLSD payload;
+ LLViewerObject *object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+
+ if (object)
+ {
+ payload["object_id"] = object->getID();
+ }
+ else
+ {
+ llwarns << "Drop object not found" << llendl;
+ return true;
+ }
+
+ LLNotificationsUtil::add("AttachmentDrop", LLSD(), payload, &callback_attachment_drop);
+ return true;
+ }
+};
+
+// called from avatar pie menu
+class LLAttachmentDetachFromPoint : public view_listener_t
+{
+ bool handleEvent(const LLSD& user_data)
+ {
+ const LLViewerJointAttachment *attachment = get_if_there(gAgentAvatarp->mAttachmentPoints, user_data.asInteger(), (LLViewerJointAttachment*)NULL);
+ if (attachment->getNumObjects() > 0)
+ {
+ gMessageSystem->newMessage("ObjectDetach");
+ gMessageSystem->nextBlockFast(_PREHASH_AgentData);
+ gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgent.getID() );
+ gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+
+ for (LLViewerJointAttachment::attachedobjs_vec_t::const_iterator iter = attachment->mAttachedObjects.begin();
+ iter != attachment->mAttachedObjects.end();
+ iter++)
+ {
+ LLViewerObject *attached_object = (*iter);
+ gMessageSystem->nextBlockFast(_PREHASH_ObjectData);
+ gMessageSystem->addU32Fast(_PREHASH_ObjectLocalID, attached_object->getLocalID());
+ }
+ gMessageSystem->sendReliable( gAgent.getRegionHost() );
+ }
+ return true;
+ }
+};
+
+static bool onEnableAttachmentLabel(LLUICtrl* ctrl, const LLSD& data)
+{
+ std::string label;
+ LLMenuItemGL* menu = dynamic_cast<LLMenuItemGL*>(ctrl);
+ if (menu)
+ {
+ const LLViewerJointAttachment *attachment = get_if_there(gAgentAvatarp->mAttachmentPoints, data["index"].asInteger(), (LLViewerJointAttachment*)NULL);
+ if (attachment)
+ {
+ label = data["label"].asString();
+ for (LLViewerJointAttachment::attachedobjs_vec_t::const_iterator attachment_iter = attachment->mAttachedObjects.begin();
+ attachment_iter != attachment->mAttachedObjects.end();
+ ++attachment_iter)
+ {
+ const LLViewerObject* attached_object = (*attachment_iter);
+ if (attached_object)
+ {
+ LLViewerInventoryItem* itemp = gInventory.getItem(attached_object->getAttachmentItemID());
+ if (itemp)
+ {
+ label += std::string(" (") + itemp->getName() + std::string(")");
+ break;
+ }
+ }
+ }
+ }
+ menu->setLabel(label);
+ }
+ return true;
+}
+
+class LLAttachmentDetach : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ // Called when the user clicked on an object attached to them
+ // and selected "Detach".
+ LLViewerObject *object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ if (!object)
+ {
+ llwarns << "handle_detach() - no object to detach" << llendl;
+ return true;
+ }
+
+ LLViewerObject *parent = (LLViewerObject*)object->getParent();
+ while (parent)
+ {
+ if(parent->isAvatar())
+ {
+ break;
+ }
+ object = parent;
+ parent = (LLViewerObject*)parent->getParent();
+ }
+
+ if (!object)
+ {
+ llwarns << "handle_detach() - no object to detach" << llendl;
+ return true;
+ }
+
+ if (object->isAvatar())
+ {
+ llwarns << "Trying to detach avatar from avatar." << llendl;
+ return true;
+ }
+
+ // The sendDetach() method works on the list of selected
+ // objects. Thus we need to clear the list, make sure it only
+ // contains the object the user clicked, send the message,
+ // then clear the list.
+ // We use deselectAll to update the simulator's notion of what's
+ // selected, and removeAll just to change things locally.
+ //RN: I thought it was more useful to detach everything that was selected
+ if (LLSelectMgr::getInstance()->getSelection()->isAttachment())
+ {
+ LLSelectMgr::getInstance()->sendDetach();
+ }
+ return true;
+ }
+};
+
+//Adding an observer for a Jira 2422 and needs to be a fetch observer
+//for Jira 3119
+class LLWornItemFetchedObserver : public LLInventoryFetchItemsObserver
+{
+public:
+ LLWornItemFetchedObserver(const LLUUID& worn_item_id) :
+ LLInventoryFetchItemsObserver(worn_item_id)
+ {}
+ virtual ~LLWornItemFetchedObserver() {}
+
+protected:
+ virtual void done()
+ {
+ gMenuAttachmentSelf->buildDrawLabels();
+ gInventory.removeObserver(this);
+ delete this;
+ }
+};
+
+// You can only drop items on parcels where you can build.
+class LLAttachmentEnableDrop : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ BOOL can_build = gAgent.isGodlike() || (LLViewerParcelMgr::getInstance()->allowAgentBuild());
+
+ //Add an inventory observer to only allow dropping the newly attached item
+ //once it exists in your inventory. Look at Jira 2422.
+ //-jwolk
+
+ // A bug occurs when you wear/drop an item before it actively is added to your inventory
+ // if this is the case (you're on a slow sim, etc.) a copy of the object,
+ // well, a newly created object with the same properties, is placed
+ // in your inventory. Therefore, we disable the drop option until the
+ // item is in your inventory
+
+ LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ LLViewerJointAttachment* attachment = NULL;
+ LLInventoryItem* item = NULL;
+
+ // Do not enable drop if all faces of object are not enabled
+ if (object && LLSelectMgr::getInstance()->getSelection()->contains(object,SELECT_ALL_TES ))
+ {
+ S32 attachmentID = ATTACHMENT_ID_FROM_STATE(object->getState());
+ attachment = get_if_there(gAgentAvatarp->mAttachmentPoints, attachmentID, (LLViewerJointAttachment*)NULL);
+
+ if (attachment)
+ {
+ for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
+ attachment_iter != attachment->mAttachedObjects.end();
+ ++attachment_iter)
+ {
+ // make sure item is in your inventory (it could be a delayed attach message being sent from the sim)
+ // so check to see if the item is in the inventory already
+ item = gInventory.getItem((*attachment_iter)->getAttachmentItemID());
+ if (!item)
+ {
+ // Item does not exist, make an observer to enable the pie menu
+ // when the item finishes fetching worst case scenario
+ // if a fetch is already out there (being sent from a slow sim)
+ // we refetch and there are 2 fetches
+ LLWornItemFetchedObserver* worn_item_fetched = new LLWornItemFetchedObserver((*attachment_iter)->getAttachmentItemID());
+ worn_item_fetched->startFetch();
+ gInventory.addObserver(worn_item_fetched);
+ }
+ }
+ }
+ }
+
+ //now check to make sure that the item is actually in the inventory before we enable dropping it
+ bool new_value = enable_detach() && can_build && item;
+
+ return new_value;
+ }
+};
+
+BOOL enable_detach(const LLSD&)
+{
+ LLViewerObject* object = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+
+ // Only enable detach if all faces of object are selected
+ if (!object ||
+ !object->isAttachment() ||
+ !LLSelectMgr::getInstance()->getSelection()->contains(object,SELECT_ALL_TES ))
+ {
+ return FALSE;
+ }
+
+ // Find the avatar who owns this attachment
+ LLViewerObject* avatar = object;
+ while (avatar)
+ {
+ // ...if it's you, good to detach
+ if (avatar->getID() == gAgent.getID())
+ {
+ return TRUE;
+ }
+
+ avatar = (LLViewerObject*)avatar->getParent();
+ }
+
+ return FALSE;
+}
+
+class LLAttachmentEnableDetach : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = enable_detach();
+ return new_value;
+ }
+};
+
+// Used to tell if the selected object can be attached to your avatar.
+BOOL object_selected_and_point_valid()
+{
+ LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
+ for (LLObjectSelection::root_iterator iter = selection->root_begin();
+ iter != selection->root_end(); iter++)
+ {
+ LLSelectNode* node = *iter;
+ LLViewerObject* object = node->getObject();
+ LLViewerObject::const_child_list_t& child_list = object->getChildren();
+ for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
+ iter != child_list.end(); iter++)
+ {
+ LLViewerObject* child = *iter;
+ if (child->isAvatar())
+ {
+ return FALSE;
+ }
+ }
+ }
+
+ return (selection->getRootObjectCount() == 1) &&
+ (selection->getFirstRootObject()->getPCode() == LL_PCODE_VOLUME) &&
+ selection->getFirstRootObject()->permYouOwner() &&
+ selection->getFirstRootObject()->flagObjectMove() &&
+ !((LLViewerObject*)selection->getFirstRootObject()->getRoot())->isAvatar() &&
+ (selection->getFirstRootObject()->getNVPair("AssetContainer") == NULL);
+}
+
+
+BOOL object_is_wearable()
+{
+ if (!object_selected_and_point_valid())
+ {
+ return FALSE;
+ }
+ if (sitting_on_selection())
+ {
+ return FALSE;
+ }
+ LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
+ for (LLObjectSelection::valid_root_iterator iter = LLSelectMgr::getInstance()->getSelection()->valid_root_begin();
+ iter != LLSelectMgr::getInstance()->getSelection()->valid_root_end(); iter++)
+ {
+ LLSelectNode* node = *iter;
+ if (node->mPermissions->getOwner() == gAgent.getID())
+ {
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+
+class LLAttachmentPointFilled : public view_listener_t
+{
+ bool handleEvent(const LLSD& user_data)
+ {
+ bool enable = false;
+ LLVOAvatar::attachment_map_t::iterator found_it = gAgentAvatarp->mAttachmentPoints.find(user_data.asInteger());
+ if (found_it != gAgentAvatarp->mAttachmentPoints.end())
+ {
+ enable = found_it->second->getNumObjects() > 0;
+ }
+ return enable;
+ }
+};
+
+class LLAvatarSendIM : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
+ if(avatar)
+ {
+ LLAvatarActions::startIM(avatar->getID());
+ }
+ return true;
+ }
+};
+
+class LLAvatarCall : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLVOAvatar* avatar = find_avatar_from_object( LLSelectMgr::getInstance()->getSelection()->getPrimaryObject() );
+ if(avatar)
+ {
+ LLAvatarActions::startCall(avatar->getID());
+ }
+ return true;
+ }
+};
+
+namespace
+{
+ struct QueueObjects : public LLSelectedObjectFunctor
+ {
+ BOOL scripted;
+ BOOL modifiable;
+ LLFloaterScriptQueue* mQueue;
+ QueueObjects(LLFloaterScriptQueue* q) : mQueue(q), scripted(FALSE), modifiable(FALSE) {}
+ virtual bool apply(LLViewerObject* obj)
+ {
+ scripted = obj->flagScripted();
+ modifiable = obj->permModify();
+
+ if( scripted && modifiable )
+ {
+ mQueue->addObject(obj->getID());
+ return false;
+ }
+ else
+ {
+ return true; // fail: stop applying
+ }
+ }
+ };
+}
+
+void queue_actions(LLFloaterScriptQueue* q, const std::string& msg)
+{
+ QueueObjects func(q);
+ LLSelectMgr *mgr = LLSelectMgr::getInstance();
+ LLObjectSelectionHandle selectHandle = mgr->getSelection();
+ bool fail = selectHandle->applyToObjects(&func);
+ if(fail)
+ {
+ if ( !func.scripted )
+ {
+ std::string noscriptmsg = std::string("Cannot") + msg + "SelectObjectsNoScripts";
+ LLNotificationsUtil::add(noscriptmsg);
+ }
+ else if ( !func.modifiable )
+ {
+ std::string nomodmsg = std::string("Cannot") + msg + "SelectObjectsNoPermission";
+ LLNotificationsUtil::add(nomodmsg);
+ }
+ else
+ {
+ llerrs << "Bad logic." << llendl;
+ }
+ }
+ else
+ {
+ if (!q->start())
+ {
+ llwarns << "Unexpected script compile failure." << llendl;
+ }
+ }
+}
+
+class LLToolsSelectedScriptAction : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string action = userdata.asString();
+ bool mono = false;
+ std::string msg, name;
+ if (action == "compile mono")
+ {
+ name = "compile_queue";
+ mono = true;
+ msg = "Recompile";
+ }
+ if (action == "compile lsl")
+ {
+ name = "compile_queue";
+ msg = "Recompile";
+ }
+ else if (action == "reset")
+ {
+ name = "reset_queue";
+ msg = "Reset";
+ }
+ else if (action == "start")
+ {
+ name = "start_queue";
+ msg = "Running";
+ }
+ else if (action == "stop")
+ {
+ name = "stop_queue";
+ msg = "RunningNot";
+ }
+ LLUUID id; id.generate();
+
+ LLFloaterScriptQueue* queue =LLFloaterReg::getTypedInstance<LLFloaterScriptQueue>(name, LLSD(id));
+ if (queue)
+ {
+ queue->setMono(mono);
+ queue_actions(queue, msg);
+ }
+ else
+ {
+ llwarns << "Failed to generate LLFloaterScriptQueue with action: " << action << llendl;
+ }
+ return true;
+ }
+};
+
+void handle_selected_texture_info(void*)
+{
+ for (LLObjectSelection::valid_iterator iter = LLSelectMgr::getInstance()->getSelection()->valid_begin();
+ iter != LLSelectMgr::getInstance()->getSelection()->valid_end(); iter++)
+ {
+ LLSelectNode* node = *iter;
+
+ std::string msg;
+ msg.assign("Texture info for: ");
+ msg.append(node->mName);
+
+ LLSD args;
+ args["MESSAGE"] = msg;
+ LLNotificationsUtil::add("SystemMessage", args);
+
+ U8 te_count = node->getObject()->getNumTEs();
+ // map from texture ID to list of faces using it
+ typedef std::map< LLUUID, std::vector<U8> > map_t;
+ map_t faces_per_texture;
+ for (U8 i = 0; i < te_count; i++)
+ {
+ if (!node->isTESelected(i)) continue;
+
+ LLViewerTexture* img = node->getObject()->getTEImage(i);
+ LLUUID image_id = img->getID();
+ faces_per_texture[image_id].push_back(i);
+ }
+ // Per-texture, dump which faces are using it.
+ map_t::iterator it;
+ for (it = faces_per_texture.begin(); it != faces_per_texture.end(); ++it)
+ {
+ LLUUID image_id = it->first;
+ U8 te = it->second[0];
+ LLViewerTexture* img = node->getObject()->getTEImage(te);
+ S32 height = img->getHeight();
+ S32 width = img->getWidth();
+ S32 components = img->getComponents();
+ msg = llformat("%dx%d %s on face ",
+ width,
+ height,
+ (components == 4 ? "alpha" : "opaque"));
+ for (U8 i = 0; i < it->second.size(); ++i)
+ {
+ msg.append( llformat("%d ", (S32)(it->second[i])));
+ }
+
+ LLSD args;
+ args["MESSAGE"] = msg;
+ LLNotificationsUtil::add("SystemMessage", args);
+ }
+ }
+}
+
+void handle_test_male(void*)
+{
+ LLAppearanceMgr::instance().wearOutfitByName("Male Shape & Outfit");
+ //gGestureList.requestResetFromServer( TRUE );
+}
+
+void handle_test_female(void*)
+{
+ LLAppearanceMgr::instance().wearOutfitByName("Female Shape & Outfit");
+ //gGestureList.requestResetFromServer( FALSE );
+}
+
+void handle_toggle_pg(void*)
+{
+ gAgent.setTeen( !gAgent.isTeen() );
+
+ LLFloaterWorldMap::reloadIcons(NULL);
+
+ llinfos << "PG status set to " << (S32)gAgent.isTeen() << llendl;
+}
+
+void handle_dump_attachments(void*)
+{
+ if(!isAgentAvatarValid()) return;
+
+ for (LLVOAvatar::attachment_map_t::iterator iter = gAgentAvatarp->mAttachmentPoints.begin();
+ iter != gAgentAvatarp->mAttachmentPoints.end(); )
+ {
+ LLVOAvatar::attachment_map_t::iterator curiter = iter++;
+ LLViewerJointAttachment* attachment = curiter->second;
+ S32 key = curiter->first;
+ for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
+ attachment_iter != attachment->mAttachedObjects.end();
+ ++attachment_iter)
+ {
+ LLViewerObject *attached_object = (*attachment_iter);
+ BOOL visible = (attached_object != NULL &&
+ attached_object->mDrawable.notNull() &&
+ !attached_object->mDrawable->isRenderType(0));
+ LLVector3 pos;
+ if (visible) pos = attached_object->mDrawable->getPosition();
+ llinfos << "ATTACHMENT " << key << ": item_id=" << attached_object->getAttachmentItemID()
+ << (attached_object ? " present " : " absent ")
+ << (visible ? "visible " : "invisible ")
+ << " at " << pos
+ << " and " << (visible ? attached_object->getPosition() : LLVector3::zero)
+ << llendl;
+ }
+ }
+}
+
+
+// these are used in the gl menus to set control values, generically.
+class LLToggleControl : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string control_name = userdata.asString();
+ BOOL checked = gSavedSettings.getBOOL( control_name );
+ gSavedSettings.setBOOL( control_name, !checked );
+ return true;
+ }
+};
+
+class LLCheckControl : public view_listener_t
+{
+ bool handleEvent( const LLSD& userdata)
+ {
+ std::string callback_data = userdata.asString();
+ bool new_value = gSavedSettings.getBOOL(callback_data);
+ return new_value;
+ }
+};
+
+// not so generic
+
+class LLAdvancedCheckRenderShadowOption: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string control_name = userdata.asString();
+ S32 current_shadow_level = gSavedSettings.getS32(control_name);
+ if (current_shadow_level == 0) // is off
+ {
+ return false;
+ }
+ else // is on
+ {
+ return true;
+ }
+ }
+};
+
+class LLAdvancedClickRenderShadowOption: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string control_name = userdata.asString();
+ S32 current_shadow_level = gSavedSettings.getS32(control_name);
+ if (current_shadow_level == 0) // upgrade to level 2
+ {
+ gSavedSettings.setS32(control_name, 2);
+ }
+ else // downgrade to level 0
+ {
+ gSavedSettings.setS32(control_name, 0);
+ }
+ return true;
+ }
+};
+
+void menu_toggle_attached_lights(void* user_data)
+{
+ LLPipeline::sRenderAttachedLights = gSavedSettings.getBOOL("RenderAttachedLights");
+}
+
+void menu_toggle_attached_particles(void* user_data)
+{
+ LLPipeline::sRenderAttachedParticles = gSavedSettings.getBOOL("RenderAttachedParticles");
+}
+
+class LLAdvancedHandleAttachedLightParticles: public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string control_name = userdata.asString();
+
+ // toggle the control
+ gSavedSettings.setBOOL(control_name,
+ !gSavedSettings.getBOOL(control_name));
+
+ // update internal flags
+ if (control_name == "RenderAttachedLights")
+ {
+ menu_toggle_attached_lights(NULL);
+ }
+ else if (control_name == "RenderAttachedParticles")
+ {
+ menu_toggle_attached_particles(NULL);
+ }
+ return true;
+ }
+};
+
+class LLSomethingSelected : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = !(LLSelectMgr::getInstance()->getSelection()->isEmpty());
+ return new_value;
+ }
+};
+
+class LLSomethingSelectedNoHUD : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
+ bool new_value = !(selection->isEmpty()) && !(selection->getSelectType() == SELECT_TYPE_HUD);
+ return new_value;
+ }
+};
+
+static bool is_editable_selected()
+{
+ return (LLSelectMgr::getInstance()->getSelection()->getFirstEditableObject() != NULL);
+}
+
+class LLEditableSelected : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ return is_editable_selected();
+ }
+};
+
+class LLEditableSelectedMono : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = false;
+ LLViewerRegion* region = gAgent.getRegion();
+ if(region && gMenuHolder)
+ {
+ bool have_cap = (! region->getCapability("UpdateScriptTask").empty());
+ new_value = is_editable_selected() && have_cap;
+ }
+ return new_value;
+ }
+};
+
+bool enable_object_take_copy()
+{
+ bool all_valid = false;
+ if (LLSelectMgr::getInstance())
+ {
+ if (!LLSelectMgr::getInstance()->getSelection()->isEmpty())
+ {
+ all_valid = true;
+#ifndef HACKED_GODLIKE_VIEWER
+# ifdef TOGGLE_HACKED_GODLIKE_VIEWER
+ if (LLGridManager::getInstance()->isInProductionGrid()
+ || !gAgent.isGodlike())
+# endif
+ {
+ struct f : public LLSelectedObjectFunctor
+ {
+ virtual bool apply(LLViewerObject* obj)
+ {
+ return (!obj->permCopy() || obj->isAttachment());
+ }
+ } func;
+ const bool firstonly = true;
+ bool any_invalid = LLSelectMgr::getInstance()->getSelection()->applyToRootObjects(&func, firstonly);
+ all_valid = !any_invalid;
+ }
+#endif // HACKED_GODLIKE_VIEWER
+ }
+ }
+
+ return all_valid;
+}
+
+
+class LLHasAsset : public LLInventoryCollectFunctor
+{
+public:
+ LLHasAsset(const LLUUID& id) : mAssetID(id), mHasAsset(FALSE) {}
+ virtual ~LLHasAsset() {}
+ virtual bool operator()(LLInventoryCategory* cat,
+ LLInventoryItem* item);
+ BOOL hasAsset() const { return mHasAsset; }
+
+protected:
+ LLUUID mAssetID;
+ BOOL mHasAsset;
+};
+
+bool LLHasAsset::operator()(LLInventoryCategory* cat,
+ LLInventoryItem* item)
+{
+ if(item && item->getAssetUUID() == mAssetID)
+ {
+ mHasAsset = TRUE;
+ }
+ return FALSE;
+}
+
+BOOL enable_save_into_inventory(void*)
+{
+ // *TODO: clean this up
+ // find the last root
+ LLSelectNode* last_node = NULL;
+ for (LLObjectSelection::root_iterator iter = LLSelectMgr::getInstance()->getSelection()->root_begin();
+ iter != LLSelectMgr::getInstance()->getSelection()->root_end(); iter++)
+ {
+ last_node = *iter;
+ }
+
+#ifdef HACKED_GODLIKE_VIEWER
+ return TRUE;
+#else
+# ifdef TOGGLE_HACKED_GODLIKE_VIEWER
+ if (!LLGridManager::getInstance()->isInProductionGrid()
+ && gAgent.isGodlike())
+ {
+ return TRUE;
+ }
+# endif
+ // check all pre-req's for save into inventory.
+ if(last_node && last_node->mValid && !last_node->mItemID.isNull()
+ && (last_node->mPermissions->getOwner() == gAgent.getID())
+ && (gInventory.getItem(last_node->mItemID) != NULL))
+ {
+ LLViewerObject* obj = last_node->getObject();
+ if( obj && !obj->isAttachment() )
+ {
+ return TRUE;
+ }
+ }
+#endif
+ return FALSE;
+}
+
+class LLToolsEnableSaveToInventory : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = enable_save_into_inventory(NULL);
+ return new_value;
+ }
+};
+
+BOOL enable_save_into_task_inventory(void*)
+{
+ LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode();
+ if(node && (node->mValid) && (!node->mFromTaskID.isNull()))
+ {
+ // *TODO: check to see if the fromtaskid object exists.
+ LLViewerObject* obj = node->getObject();
+ if( obj && !obj->isAttachment() )
+ {
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+class LLToolsEnableSaveToObjectInventory : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = enable_save_into_task_inventory(NULL);
+ return new_value;
+ }
+};
+
+
+class LLViewEnableMouselook : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ // You can't go directly from customize avatar to mouselook.
+ // TODO: write code with appropriate dialogs to handle this transition.
+ bool new_value = (CAMERA_MODE_CUSTOMIZE_AVATAR != gAgentCamera.getCameraMode() && !gSavedSettings.getBOOL("FreezeTime"));
+ return new_value;
+ }
+};
+
+class LLToolsEnableToolNotPie : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = ( LLToolMgr::getInstance()->getBaseTool() != LLToolPie::getInstance() );
+ return new_value;
+ }
+};
+
+class LLWorldEnableCreateLandmark : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ return !LLLandmarkActions::landmarkAlreadyExists();
+ }
+};
+
+class LLWorldEnableSetHomeLocation : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gAgent.isGodlike() ||
+ (gAgent.getRegion() && gAgent.getRegion()->getAllowSetHome());
+ return new_value;
+ }
+};
+
+class LLWorldEnableTeleportHome : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLViewerRegion* regionp = gAgent.getRegion();
+ bool agent_on_prelude = (regionp && regionp->isPrelude());
+ bool enable_teleport_home = gAgent.isGodlike() || !agent_on_prelude;
+ return enable_teleport_home;
+ }
+};
+
+BOOL enable_god_full(void*)
+{
+ return gAgent.getGodLevel() >= GOD_FULL;
+}
+
+BOOL enable_god_liaison(void*)
+{
+ return gAgent.getGodLevel() >= GOD_LIAISON;
+}
+
+bool is_god_customer_service()
+{
+ return gAgent.getGodLevel() >= GOD_CUSTOMER_SERVICE;
+}
+
+BOOL enable_god_basic(void*)
+{
+ return gAgent.getGodLevel() > GOD_NOT;
+}
+
+
+void toggle_show_xui_names(void *)
+{
+ gSavedSettings.setBOOL("DebugShowXUINames", !gSavedSettings.getBOOL("DebugShowXUINames"));
+}
+
+BOOL check_show_xui_names(void *)
+{
+ return gSavedSettings.getBOOL("DebugShowXUINames");
+}
+
+class LLToolsSelectOnlyMyObjects : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ BOOL cur_val = gSavedSettings.getBOOL("SelectOwnedOnly");
+
+ gSavedSettings.setBOOL("SelectOwnedOnly", ! cur_val );
+
+ return true;
+ }
+};
+
+class LLToolsSelectOnlyMovableObjects : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ BOOL cur_val = gSavedSettings.getBOOL("SelectMovableOnly");
+
+ gSavedSettings.setBOOL("SelectMovableOnly", ! cur_val );
+
+ return true;
+ }
+};
+
+class LLToolsSelectBySurrounding : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLSelectMgr::sRectSelectInclusive = !LLSelectMgr::sRectSelectInclusive;
+
+ gSavedSettings.setBOOL("RectangleSelectInclusive", LLSelectMgr::sRectSelectInclusive);
+ return true;
+ }
+};
+
+class LLToolsShowHiddenSelection : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ // TomY TODO Merge these
+ LLSelectMgr::sRenderHiddenSelections = !LLSelectMgr::sRenderHiddenSelections;
+
+ gSavedSettings.setBOOL("RenderHiddenSelections", LLSelectMgr::sRenderHiddenSelections);
+ return true;
+ }
+};
+
+class LLToolsShowSelectionLightRadius : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ // TomY TODO merge these
+ LLSelectMgr::sRenderLightRadius = !LLSelectMgr::sRenderLightRadius;
+
+ gSavedSettings.setBOOL("RenderLightRadius", LLSelectMgr::sRenderLightRadius);
+ return true;
+ }
+};
+
+class LLToolsEditLinkedParts : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ BOOL select_individuals = !gSavedSettings.getBOOL("EditLinkedParts");
+ gSavedSettings.setBOOL( "EditLinkedParts", select_individuals );
+ if (select_individuals)
+ {
+ LLSelectMgr::getInstance()->demoteSelectionToIndividuals();
+ }
+ else
+ {
+ LLSelectMgr::getInstance()->promoteSelectionToRoot();
+ }
+ return true;
+ }
+};
+
+void reload_vertex_shader(void *)
+{
+ //THIS WOULD BE AN AWESOME PLACE TO RELOAD SHADERS... just a thought - DaveP
+}
+
+void handle_dump_avatar_local_textures(void*)
+{
+ gAgentAvatarp->dumpLocalTextures();
+}
+
+void handle_dump_timers()
+{
+ LLFastTimer::dumpCurTimes();
+}
+
+void handle_debug_avatar_textures(void*)
+{
+ LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getPrimaryObject();
+ if (objectp)
+ {
+ LLFloaterReg::showInstance( "avatar_textures", LLSD(objectp->getID()) );
+ }
+}
+
+void handle_grab_baked_texture(void* data)
+{
+ EBakedTextureIndex baked_tex_index = (EBakedTextureIndex)((intptr_t)data);
+ if (!isAgentAvatarValid()) return;
+
+ const LLUUID& asset_id = gAgentAvatarp->grabBakedTexture(baked_tex_index);
+ LL_INFOS("texture") << "Adding baked texture " << asset_id << " to inventory." << llendl;
+ LLAssetType::EType asset_type = LLAssetType::AT_TEXTURE;
+ LLInventoryType::EType inv_type = LLInventoryType::IT_TEXTURE;
+ const LLUUID folder_id = gInventory.findCategoryUUIDForType(LLFolderType::assetTypeToFolderType(asset_type));
+ if(folder_id.notNull())
+ {
+ std::string name;
+ name = "Baked " + LLVOAvatarDictionary::getInstance()->getBakedTexture(baked_tex_index)->mNameCapitalized + " Texture";
+
+ LLUUID item_id;
+ item_id.generate();
+ LLPermissions perm;
+ perm.init(gAgentID,
+ gAgentID,
+ LLUUID::null,
+ LLUUID::null);
+ U32 next_owner_perm = PERM_MOVE | PERM_TRANSFER;
+ perm.initMasks(PERM_ALL,
+ PERM_ALL,
+ PERM_NONE,
+ PERM_NONE,
+ next_owner_perm);
+ time_t creation_date_now = time_corrected();
+ LLPointer<LLViewerInventoryItem> item
+ = new LLViewerInventoryItem(item_id,
+ folder_id,
+ perm,
+ asset_id,
+ asset_type,
+ inv_type,
+ name,
+ LLStringUtil::null,
+ LLSaleInfo::DEFAULT,
+ LLInventoryItemFlags::II_FLAGS_NONE,
+ creation_date_now);
+
+ item->updateServer(TRUE);
+ gInventory.updateItem(item);
+ gInventory.notifyObservers();
+
+ // Show the preview panel for textures to let
+ // user know that the image is now in inventory.
+ LLInventoryPanel *active_panel = LLInventoryPanel::getActiveInventoryPanel();
+ if(active_panel)
+ {
+ LLFocusableElement* focus_ctrl = gFocusMgr.getKeyboardFocus();
+
+ active_panel->setSelection(item_id, TAKE_FOCUS_NO);
+ active_panel->openSelected();
+ //LLFloaterInventory::dumpSelectionInformation((void*)view);
+ // restore keyboard focus
+ gFocusMgr.setKeyboardFocus(focus_ctrl);
+ }
+ }
+ else
+ {
+ llwarns << "Can't find a folder to put it in" << llendl;
+ }
+}
+
+BOOL enable_grab_baked_texture(void* data)
+{
+ EBakedTextureIndex index = (EBakedTextureIndex)((intptr_t)data);
+ if (isAgentAvatarValid())
+ {
+ return gAgentAvatarp->canGrabBakedTexture(index);
+ }
+ return FALSE;
+}
+
+// Returns a pointer to the avatar give the UUID of the avatar OR of an attachment the avatar is wearing.
+// Returns NULL on failure.
+LLVOAvatar* find_avatar_from_object( LLViewerObject* object )
+{
+ if (object)
+ {
+ if( object->isAttachment() )
+ {
+ do
+ {
+ object = (LLViewerObject*) object->getParent();
+ }
+ while( object && !object->isAvatar() );
+ }
+ else if( !object->isAvatar() )
+ {
+ object = NULL;
+ }
+ }
+
+ return (LLVOAvatar*) object;
+}
+
+
+// Returns a pointer to the avatar give the UUID of the avatar OR of an attachment the avatar is wearing.
+// Returns NULL on failure.
+LLVOAvatar* find_avatar_from_object( const LLUUID& object_id )
+{
+ return find_avatar_from_object( gObjectList.findObject(object_id) );
+}
+
+
+void handle_disconnect_viewer(void *)
+{
+ LLAppViewer::instance()->forceDisconnect(LLTrans::getString("TestingDisconnect"));
+}
+
+void force_error_breakpoint(void *)
+{
+ LLAppViewer::instance()->forceErrorBreakpoint();
+}
+
+void force_error_llerror(void *)
+{
+ LLAppViewer::instance()->forceErrorLLError();
+}
+
+void force_error_bad_memory_access(void *)
+{
+ LLAppViewer::instance()->forceErrorBadMemoryAccess();
+}
+
+void force_error_infinite_loop(void *)
+{
+ LLAppViewer::instance()->forceErrorInfiniteLoop();
+}
+
+void force_error_software_exception(void *)
+{
+ LLAppViewer::instance()->forceErrorSoftwareException();
+}
+
+void force_error_driver_crash(void *)
+{
+ LLAppViewer::instance()->forceErrorDriverCrash();
+}
+
+class LLToolsUseSelectionForGrid : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLSelectMgr::getInstance()->clearGridObjects();
+ struct f : public LLSelectedObjectFunctor
+ {
+ virtual bool apply(LLViewerObject* objectp)
+ {
+ LLSelectMgr::getInstance()->addGridObject(objectp);
+ return true;
+ }
+ } func;
+ LLSelectMgr::getInstance()->getSelection()->applyToRootObjects(&func);
+ LLSelectMgr::getInstance()->setGridMode(GRID_MODE_REF_OBJECT);
+ if (gFloaterTools)
+ {
+ gFloaterTools->mComboGridMode->setCurrentByIndex((S32)GRID_MODE_REF_OBJECT);
+ }
+ return true;
+ }
+};
+
+void handle_test_load_url(void*)
+{
+ LLWeb::loadURL("");
+ LLWeb::loadURL("hacker://www.google.com/");
+ LLWeb::loadURL("http");
+ LLWeb::loadURL("http://www.google.com/");
+}
+
+//
+// LLViewerMenuHolderGL
+//
+static LLDefaultChildRegistry::Register<LLViewerMenuHolderGL> r("menu_holder");
+
+LLViewerMenuHolderGL::LLViewerMenuHolderGL(const LLViewerMenuHolderGL::Params& p)
+: LLMenuHolderGL(p)
+{}
+
+BOOL LLViewerMenuHolderGL::hideMenus()
+{
+ BOOL handled = LLMenuHolderGL::hideMenus();
+
+ // drop pie menu selection
+ mParcelSelection = NULL;
+ mObjectSelection = NULL;
+
+ if (gMenuBarView)
+ {
+ gMenuBarView->clearHoverItem();
+ gMenuBarView->resetMenuTrigger();
+ }
+
+ return handled;
+}
+
+void LLViewerMenuHolderGL::setParcelSelection(LLSafeHandle<LLParcelSelection> selection)
+{
+ mParcelSelection = selection;
+}
+
+void LLViewerMenuHolderGL::setObjectSelection(LLSafeHandle<LLObjectSelection> selection)
+{
+ mObjectSelection = selection;
+}
+
+
+const LLRect LLViewerMenuHolderGL::getMenuRect() const
+{
+ return LLRect(0, getRect().getHeight() - MENU_BAR_HEIGHT, getRect().getWidth(), STATUS_BAR_HEIGHT);
+}
+
+void handle_web_browser_test(const LLSD& param)
+{
+ std::string url = param.asString();
+ if (url.empty())
+ {
+ url = "about:blank";
+ }
+ LLWeb::loadURLInternal(url);
+}
+
+void handle_web_content_test(const LLSD& param)
+{
+ std::string url = param.asString();
+ LLWeb::loadWebURLInternal(url);
+}
+
+void handle_buy_currency_test(void*)
+{
+ std::string url =
+ "http://sarahd-sl-13041.webdev.lindenlab.com/app/lindex/index.php?agent_id=[AGENT_ID]&secure_session_id=[SESSION_ID]&lang=[LANGUAGE]";
+
+ LLStringUtil::format_map_t replace;
+ replace["[AGENT_ID]"] = gAgent.getID().asString();
+ replace["[SESSION_ID]"] = gAgent.getSecureSessionID().asString();
+ replace["[LANGUAGE]"] = LLUI::getLanguage();
+ LLStringUtil::format(url, replace);
+
+ llinfos << "buy currency url " << url << llendl;
+
+ LLFloaterReg::showInstance("buy_currency_html", LLSD(url));
+}
+
+void handle_rebake_textures(void*)
+{
+ if (!isAgentAvatarValid()) return;
+
+ // Slam pending upload count to "unstick" things
+ bool slam_for_debug = true;
+ gAgentAvatarp->forceBakeAllTextures(slam_for_debug);
+}
+
+void toggle_visibility(void* user_data)
+{
+ LLView* viewp = (LLView*)user_data;
+ viewp->setVisible(!viewp->getVisible());
+}
+
+BOOL get_visibility(void* user_data)
+{
+ LLView* viewp = (LLView*)user_data;
+ return viewp->getVisible();
+}
+
+// TomY TODO: Get rid of these?
+class LLViewShowHoverTips : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ gSavedSettings.setBOOL("ShowHoverTips", !gSavedSettings.getBOOL("ShowHoverTips"));
+ return true;
+ }
+};
+
+class LLViewCheckShowHoverTips : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = gSavedSettings.getBOOL("ShowHoverTips");
+ return new_value;
+ }
+};
+
+// TomY TODO: Get rid of these?
+class LLViewHighlightTransparent : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLDrawPoolAlpha::sShowDebugAlpha = !LLDrawPoolAlpha::sShowDebugAlpha;
+ return true;
+ }
+};
+
+class LLViewCheckHighlightTransparent : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLDrawPoolAlpha::sShowDebugAlpha;
+ return new_value;
+ }
+};
+
+class LLViewBeaconWidth : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string width = userdata.asString();
+ if(width == "1")
+ {
+ gSavedSettings.setS32("DebugBeaconLineWidth", 1);
+ }
+ else if(width == "4")
+ {
+ gSavedSettings.setS32("DebugBeaconLineWidth", 4);
+ }
+ else if(width == "16")
+ {
+ gSavedSettings.setS32("DebugBeaconLineWidth", 16);
+ }
+ else if(width == "32")
+ {
+ gSavedSettings.setS32("DebugBeaconLineWidth", 32);
+ }
+
+ return true;
+ }
+};
+
+
+class LLViewToggleBeacon : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string beacon = userdata.asString();
+ if (beacon == "scriptsbeacon")
+ {
+ LLPipeline::toggleRenderScriptedBeacons(NULL);
+ gSavedSettings.setBOOL( "scriptsbeacon", LLPipeline::getRenderScriptedBeacons(NULL) );
+ // toggle the other one off if it's on
+ if (LLPipeline::getRenderScriptedBeacons(NULL) && LLPipeline::getRenderScriptedTouchBeacons(NULL))
+ {
+ LLPipeline::toggleRenderScriptedTouchBeacons(NULL);
+ gSavedSettings.setBOOL( "scripttouchbeacon", LLPipeline::getRenderScriptedTouchBeacons(NULL) );
+ }
+ }
+ else if (beacon == "physicalbeacon")
+ {
+ LLPipeline::toggleRenderPhysicalBeacons(NULL);
+ gSavedSettings.setBOOL( "physicalbeacon", LLPipeline::getRenderPhysicalBeacons(NULL) );
+ }
+ else if (beacon == "soundsbeacon")
+ {
+ LLPipeline::toggleRenderSoundBeacons(NULL);
+ gSavedSettings.setBOOL( "soundsbeacon", LLPipeline::getRenderSoundBeacons(NULL) );
+ }
+ else if (beacon == "particlesbeacon")
+ {
+ LLPipeline::toggleRenderParticleBeacons(NULL);
+ gSavedSettings.setBOOL( "particlesbeacon", LLPipeline::getRenderParticleBeacons(NULL) );
+ }
+ else if (beacon == "scripttouchbeacon")
+ {
+ LLPipeline::toggleRenderScriptedTouchBeacons(NULL);
+ gSavedSettings.setBOOL( "scripttouchbeacon", LLPipeline::getRenderScriptedTouchBeacons(NULL) );
+ // toggle the other one off if it's on
+ if (LLPipeline::getRenderScriptedBeacons(NULL) && LLPipeline::getRenderScriptedTouchBeacons(NULL))
+ {
+ LLPipeline::toggleRenderScriptedBeacons(NULL);
+ gSavedSettings.setBOOL( "scriptsbeacon", LLPipeline::getRenderScriptedBeacons(NULL) );
+ }
+ }
+ else if (beacon == "renderbeacons")
+ {
+ LLPipeline::toggleRenderBeacons(NULL);
+ gSavedSettings.setBOOL( "renderbeacons", LLPipeline::getRenderBeacons(NULL) );
+ // toggle the other one on if it's not
+ if (!LLPipeline::getRenderBeacons(NULL) && !LLPipeline::getRenderHighlights(NULL))
+ {
+ LLPipeline::toggleRenderHighlights(NULL);
+ gSavedSettings.setBOOL( "renderhighlights", LLPipeline::getRenderHighlights(NULL) );
+ }
+ }
+ else if (beacon == "renderhighlights")
+ {
+ LLPipeline::toggleRenderHighlights(NULL);
+ gSavedSettings.setBOOL( "renderhighlights", LLPipeline::getRenderHighlights(NULL) );
+ // toggle the other one on if it's not
+ if (!LLPipeline::getRenderBeacons(NULL) && !LLPipeline::getRenderHighlights(NULL))
+ {
+ LLPipeline::toggleRenderBeacons(NULL);
+ gSavedSettings.setBOOL( "renderbeacons", LLPipeline::getRenderBeacons(NULL) );
+ }
+ }
+
+ return true;
+ }
+};
+
+class LLViewCheckBeaconEnabled : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string beacon = userdata.asString();
+ bool new_value = false;
+ if (beacon == "scriptsbeacon")
+ {
+ new_value = gSavedSettings.getBOOL( "scriptsbeacon");
+ LLPipeline::setRenderScriptedBeacons(new_value);
+ }
+ else if (beacon == "physicalbeacon")
+ {
+ new_value = gSavedSettings.getBOOL( "physicalbeacon");
+ LLPipeline::setRenderPhysicalBeacons(new_value);
+ }
+ else if (beacon == "soundsbeacon")
+ {
+ new_value = gSavedSettings.getBOOL( "soundsbeacon");
+ LLPipeline::setRenderSoundBeacons(new_value);
+ }
+ else if (beacon == "particlesbeacon")
+ {
+ new_value = gSavedSettings.getBOOL( "particlesbeacon");
+ LLPipeline::setRenderParticleBeacons(new_value);
+ }
+ else if (beacon == "scripttouchbeacon")
+ {
+ new_value = gSavedSettings.getBOOL( "scripttouchbeacon");
+ LLPipeline::setRenderScriptedTouchBeacons(new_value);
+ }
+ else if (beacon == "renderbeacons")
+ {
+ new_value = gSavedSettings.getBOOL( "renderbeacons");
+ LLPipeline::setRenderBeacons(new_value);
+ }
+ else if (beacon == "renderhighlights")
+ {
+ new_value = gSavedSettings.getBOOL( "renderhighlights");
+ LLPipeline::setRenderHighlights(new_value);
+ }
+ return new_value;
+ }
+};
+
+class LLViewToggleRenderType : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string type = userdata.asString();
+ if (type == "hideparticles")
+ {
+ LLPipeline::toggleRenderType(LLPipeline::RENDER_TYPE_PARTICLES);
+ }
+ return true;
+ }
+};
+
+class LLViewCheckRenderType : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string type = userdata.asString();
+ bool new_value = false;
+ if (type == "hideparticles")
+ {
+ new_value = LLPipeline::toggleRenderTypeControlNegated((void *)LLPipeline::RENDER_TYPE_PARTICLES);
+ }
+ return new_value;
+ }
+};
+
+class LLViewShowHUDAttachments : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLPipeline::sShowHUDAttachments = !LLPipeline::sShowHUDAttachments;
+ return true;
+ }
+};
+
+class LLViewCheckHUDAttachments : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool new_value = LLPipeline::sShowHUDAttachments;
+ return new_value;
+ }
+};
+
+class LLEditEnableTakeOff : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string clothing = userdata.asString();
+ LLWearableType::EType type = LLWearableType::typeNameToType(clothing);
+ if (type >= LLWearableType::WT_SHAPE && type < LLWearableType::WT_COUNT)
+ return LLAgentWearables::selfHasWearable(type);
+ return false;
+ }
+};
+
+class LLEditTakeOff : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string clothing = userdata.asString();
+ if (clothing == "all")
+ LLWearableBridge::removeAllClothesFromAvatar();
+ else
+ {
+ LLWearableType::EType type = LLWearableType::typeNameToType(clothing);
+ if (type >= LLWearableType::WT_SHAPE
+ && type < LLWearableType::WT_COUNT
+ && (gAgentWearables.getWearableCount(type) > 0))
+ {
+ // MULTI-WEARABLES: assuming user wanted to remove top shirt.
+ U32 wearable_index = gAgentWearables.getWearableCount(type) - 1;
+ LLViewerInventoryItem *item = dynamic_cast<LLViewerInventoryItem*>(gAgentWearables.getWearableInventoryItem(type,wearable_index));
+ LLWearableBridge::removeItemFromAvatar(item);
+ }
+
+ }
+ return true;
+ }
+};
+
+class LLToolsSelectTool : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string tool_name = userdata.asString();
+ if (tool_name == "focus")
+ {
+ LLToolMgr::getInstance()->getCurrentToolset()->selectToolByIndex(1);
+ }
+ else if (tool_name == "move")
+ {
+ LLToolMgr::getInstance()->getCurrentToolset()->selectToolByIndex(2);
+ }
+ else if (tool_name == "edit")
+ {
+ LLToolMgr::getInstance()->getCurrentToolset()->selectToolByIndex(3);
+ }
+ else if (tool_name == "create")
+ {
+ LLToolMgr::getInstance()->getCurrentToolset()->selectToolByIndex(4);
+ }
+ else if (tool_name == "land")
+ {
+ LLToolMgr::getInstance()->getCurrentToolset()->selectToolByIndex(5);
+ }
+ return true;
+ }
+};
+
+/// WINDLIGHT callbacks
+class LLWorldEnvSettings : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string tod = userdata.asString();
+ LLVector3 sun_direction;
+
+ if (tod == "editor")
+ {
+ // if not there or is hidden, show it
+ LLFloaterReg::toggleInstance("env_settings");
+ return true;
+ }
+
+ if (tod == "sunrise")
+ {
+ // set the value, turn off animation
+ LLWLParamManager::instance()->mAnimator.setDayTime(0.25);
+ LLWLParamManager::instance()->mAnimator.mIsRunning = false;
+ LLWLParamManager::instance()->mAnimator.mUseLindenTime = false;
+
+ // then call update once
+ LLWLParamManager::instance()->mAnimator.update(
+ LLWLParamManager::instance()->mCurParams);
+ }
+ else if (tod == "noon")
+ {
+ // set the value, turn off animation
+ LLWLParamManager::instance()->mAnimator.setDayTime(0.567);
+ LLWLParamManager::instance()->mAnimator.mIsRunning = false;
+ LLWLParamManager::instance()->mAnimator.mUseLindenTime = false;
+
+ // then call update once
+ LLWLParamManager::instance()->mAnimator.update(
+ LLWLParamManager::instance()->mCurParams);
+ }
+ else if (tod == "sunset")
+ {
+ // set the value, turn off animation
+ LLWLParamManager::instance()->mAnimator.setDayTime(0.75);
+ LLWLParamManager::instance()->mAnimator.mIsRunning = false;
+ LLWLParamManager::instance()->mAnimator.mUseLindenTime = false;
+
+ // then call update once
+ LLWLParamManager::instance()->mAnimator.update(
+ LLWLParamManager::instance()->mCurParams);
+ }
+ else if (tod == "midnight")
+ {
+ // set the value, turn off animation
+ LLWLParamManager::instance()->mAnimator.setDayTime(0.0);
+ LLWLParamManager::instance()->mAnimator.mIsRunning = false;
+ LLWLParamManager::instance()->mAnimator.mUseLindenTime = false;
+
+ // then call update once
+ LLWLParamManager::instance()->mAnimator.update(
+ LLWLParamManager::instance()->mCurParams);
+ }
+ else
+ {
+ LLWLParamManager::instance()->mAnimator.mIsRunning = true;
+ LLWLParamManager::instance()->mAnimator.mUseLindenTime = true;
+ }
+ return true;
+ }
+};
+
+/// Water Menu callbacks
+class LLWorldWaterSettings : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLFloaterReg::toggleInstance("env_water");
+ return true;
+ }
+};
+
+/// Post-Process callbacks
+class LLWorldPostProcess : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLFloaterReg::showInstance("env_post_process");
+ return true;
+ }
+};
+
+/// Day Cycle callbacks
+class LLWorldDayCycle : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLFloaterReg::showInstance("env_day_cycle");
+ return true;
+ }
+};
+
+class LLWorldToggleMovementControls : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLBottomTray::getInstance()->toggleMovementControls();
+ return true;
+ }
+};
+
+class LLWorldToggleCameraControls : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLBottomTray::getInstance()->toggleCameraControls();
+ return true;
+ }
+};
+
+void handle_flush_name_caches()
+{
+ // Toggle display names on and off to flush
+ bool use_display_names = LLAvatarNameCache::useDisplayNames();
+ LLAvatarNameCache::setUseDisplayNames(!use_display_names);
+ LLAvatarNameCache::setUseDisplayNames(use_display_names);
+
+ if (gCacheName) gCacheName->clear();
+}
+
+class LLUploadCostCalculator : public view_listener_t
+{
+ std::string mCostStr;
+
+ bool handleEvent(const LLSD& userdata)
+ {
+ std::string menu_name = userdata.asString();
+ gMenuHolder->childSetLabelArg(menu_name, "[COST]", mCostStr);
+
+ return true;
+ }
+
+ void calculateCost();
+
+public:
+ LLUploadCostCalculator()
+ {
+ calculateCost();
+ }
+};
+
+class LLToggleUIHints : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ bool ui_hints_enabled = gSavedSettings.getBOOL("EnableUIHints");
+ // toggle
+ ui_hints_enabled = !ui_hints_enabled;
+ gSavedSettings.setBOOL("EnableUIHints", ui_hints_enabled);
+ return true;
+ }
+};
+
+void LLUploadCostCalculator::calculateCost()
+{
+ S32 upload_cost = LLGlobalEconomy::Singleton::getInstance()->getPriceUpload();
+
+ // getPriceUpload() returns -1 if no data available yet.
+ if(upload_cost >= 0)
+ {
+ mCostStr = llformat("%d", upload_cost);
+ }
+ else
+ {
+ mCostStr = llformat("%d", gSavedSettings.getU32("DefaultUploadCost"));
+ }
+}
+
+void show_navbar_context_menu(LLView* ctrl, S32 x, S32 y)
+{
+ static LLMenuGL* show_navbar_context_menu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_hide_navbar.xml",
+ gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
+ if(gMenuHolder->hasVisibleMenu())
+ {
+ gMenuHolder->hideMenus();
+ }
+ show_navbar_context_menu->buildDrawLabels();
+ show_navbar_context_menu->updateParent(LLMenuGL::sMenuContainer);
+ LLMenuGL::showPopup(ctrl, show_navbar_context_menu, x, y);
+}
+
+void show_topinfobar_context_menu(LLView* ctrl, S32 x, S32 y)
+{
+ static LLMenuGL* show_topbarinfo_context_menu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_topinfobar.xml",
+ gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
+
+ LLMenuItemGL* landmark_item = show_topbarinfo_context_menu->getChild<LLMenuItemGL>("Landmark");
+ if (!LLLandmarkActions::landmarkAlreadyExists())
+ {
+ landmark_item->setLabel(LLTrans::getString("AddLandmarkNavBarMenu"));
+ }
+ else
+ {
+ landmark_item->setLabel(LLTrans::getString("EditLandmarkNavBarMenu"));
+ }
+
+ if(gMenuHolder->hasVisibleMenu())
+ {
+ gMenuHolder->hideMenus();
+ }
+
+ show_topbarinfo_context_menu->buildDrawLabels();
+ show_topbarinfo_context_menu->updateParent(LLMenuGL::sMenuContainer);
+ LLMenuGL::showPopup(ctrl, show_topbarinfo_context_menu, x, y);
+}
+
+void initialize_edit_menu()
+{
+ view_listener_t::addMenu(new LLEditUndo(), "Edit.Undo");
+ view_listener_t::addMenu(new LLEditRedo(), "Edit.Redo");
+ view_listener_t::addMenu(new LLEditCut(), "Edit.Cut");
+ view_listener_t::addMenu(new LLEditCopy(), "Edit.Copy");
+ view_listener_t::addMenu(new LLEditPaste(), "Edit.Paste");
+ view_listener_t::addMenu(new LLEditDelete(), "Edit.Delete");
+ view_listener_t::addMenu(new LLEditSelectAll(), "Edit.SelectAll");
+ view_listener_t::addMenu(new LLEditDeselect(), "Edit.Deselect");
+ view_listener_t::addMenu(new LLEditDuplicate(), "Edit.Duplicate");
+ view_listener_t::addMenu(new LLEditTakeOff(), "Edit.TakeOff");
+ view_listener_t::addMenu(new LLEditEnableUndo(), "Edit.EnableUndo");
+ view_listener_t::addMenu(new LLEditEnableRedo(), "Edit.EnableRedo");
+ view_listener_t::addMenu(new LLEditEnableCut(), "Edit.EnableCut");
+ view_listener_t::addMenu(new LLEditEnableCopy(), "Edit.EnableCopy");
+ view_listener_t::addMenu(new LLEditEnablePaste(), "Edit.EnablePaste");
+ view_listener_t::addMenu(new LLEditEnableDelete(), "Edit.EnableDelete");
+ view_listener_t::addMenu(new LLEditEnableSelectAll(), "Edit.EnableSelectAll");
+ view_listener_t::addMenu(new LLEditEnableDeselect(), "Edit.EnableDeselect");
+ view_listener_t::addMenu(new LLEditEnableDuplicate(), "Edit.EnableDuplicate");
+
+}
+
+void initialize_menus()
+{
+ // A parameterized event handler used as ctrl-8/9/0 zoom controls below.
+ class LLZoomer : public view_listener_t
+ {
+ public:
+ // The "mult" parameter says whether "val" is a multiplier or used to set the value.
+ LLZoomer(F32 val, bool mult=true) : mVal(val), mMult(mult) {}
+ bool handleEvent(const LLSD& userdata)
+ {
+ F32 new_fov_rad = mMult ? LLViewerCamera::getInstance()->getDefaultFOV() * mVal : mVal;
+ LLViewerCamera::getInstance()->setDefaultFOV(new_fov_rad);
+ gSavedSettings.setF32("CameraAngle", LLViewerCamera::getInstance()->getView()); // setView may have clamped it.
+ return true;
+ }
+ private:
+ F32 mVal;
+ bool mMult;
+ };
+
+ LLUICtrl::EnableCallbackRegistry::Registrar& enable = LLUICtrl::EnableCallbackRegistry::currentRegistrar();
+ LLUICtrl::CommitCallbackRegistry::Registrar& commit = LLUICtrl::CommitCallbackRegistry::currentRegistrar();
+
+ // Generic enable and visible
+ // Don't prepend MenuName.Foo because these can be used in any menu.
+ enable.add("IsGodCustomerService", boost::bind(&is_god_customer_service));
+
+ view_listener_t::addEnable(new LLUploadCostCalculator(), "Upload.CalculateCosts");
+
+ // Agent
+ commit.add("Agent.toggleFlying", boost::bind(&LLAgent::toggleFlying));
+ enable.add("Agent.enableFlying", boost::bind(&LLAgent::enableFlying));
+
+ // File menu
+ init_menu_file();
+
+ view_listener_t::addMenu(new LLEditEnableTakeOff(), "Edit.EnableTakeOff");
+ view_listener_t::addMenu(new LLEditEnableCustomizeAvatar(), "Edit.EnableCustomizeAvatar");
+ view_listener_t::addMenu(new LLEnableEditShape(), "Edit.EnableEditShape");
+ commit.add("CustomizeAvatar", boost::bind(&handle_customize_avatar));
+ commit.add("EditOutfit", boost::bind(&handle_edit_outfit));
+ commit.add("EditShape", boost::bind(&handle_edit_shape));
+
+ // View menu
+ view_listener_t::addMenu(new LLViewMouselook(), "View.Mouselook");
+ view_listener_t::addMenu(new LLViewJoystickFlycam(), "View.JoystickFlycam");
+ view_listener_t::addMenu(new LLViewResetView(), "View.ResetView");
+ view_listener_t::addMenu(new LLViewLookAtLastChatter(), "View.LookAtLastChatter");
+ view_listener_t::addMenu(new LLViewShowHoverTips(), "View.ShowHoverTips");
+ view_listener_t::addMenu(new LLViewHighlightTransparent(), "View.HighlightTransparent");
+ view_listener_t::addMenu(new LLViewToggleRenderType(), "View.ToggleRenderType");
+ view_listener_t::addMenu(new LLViewShowHUDAttachments(), "View.ShowHUDAttachments");
+ view_listener_t::addMenu(new LLZoomer(1.2f), "View.ZoomOut");
+ view_listener_t::addMenu(new LLZoomer(1/1.2f), "View.ZoomIn");
+ view_listener_t::addMenu(new LLZoomer(DEFAULT_FIELD_OF_VIEW, false), "View.ZoomDefault");
+ view_listener_t::addMenu(new LLViewDefaultUISize(), "View.DefaultUISize");
+
+ view_listener_t::addMenu(new LLViewEnableMouselook(), "View.EnableMouselook");
+ view_listener_t::addMenu(new LLViewEnableJoystickFlycam(), "View.EnableJoystickFlycam");
+ view_listener_t::addMenu(new LLViewEnableLastChatter(), "View.EnableLastChatter");
+
+ view_listener_t::addMenu(new LLViewCheckJoystickFlycam(), "View.CheckJoystickFlycam");
+ view_listener_t::addMenu(new LLViewCheckShowHoverTips(), "View.CheckShowHoverTips");
+ view_listener_t::addMenu(new LLViewCheckHighlightTransparent(), "View.CheckHighlightTransparent");
+ view_listener_t::addMenu(new LLViewCheckRenderType(), "View.CheckRenderType");
+ view_listener_t::addMenu(new LLViewCheckHUDAttachments(), "View.CheckHUDAttachments");
+
+ // Me > Movement
+ view_listener_t::addMenu(new LLAdvancedAgentFlyingInfo(), "Agent.getFlying");
+
+ // World menu
+ commit.add("World.Chat", boost::bind(&handle_chat, (void*)NULL));
+ view_listener_t::addMenu(new LLWorldAlwaysRun(), "World.AlwaysRun");
+ view_listener_t::addMenu(new LLWorldCreateLandmark(), "World.CreateLandmark");
+ view_listener_t::addMenu(new LLWorldPlaceProfile(), "World.PlaceProfile");
+ view_listener_t::addMenu(new LLWorldSetHomeLocation(), "World.SetHomeLocation");
+ view_listener_t::addMenu(new LLWorldTeleportHome(), "World.TeleportHome");
+ view_listener_t::addMenu(new LLWorldSetAway(), "World.SetAway");
+ view_listener_t::addMenu(new LLWorldSetBusy(), "World.SetBusy");
+
+ view_listener_t::addMenu(new LLWorldEnableCreateLandmark(), "World.EnableCreateLandmark");
+ view_listener_t::addMenu(new LLWorldEnableSetHomeLocation(), "World.EnableSetHomeLocation");
+ view_listener_t::addMenu(new LLWorldEnableTeleportHome(), "World.EnableTeleportHome");
+ view_listener_t::addMenu(new LLWorldEnableBuyLand(), "World.EnableBuyLand");
+
+ view_listener_t::addMenu(new LLWorldCheckAlwaysRun(), "World.CheckAlwaysRun");
+
+ view_listener_t::addMenu(new LLWorldEnvSettings(), "World.EnvSettings");
+ view_listener_t::addMenu(new LLWorldWaterSettings(), "World.WaterSettings");
+ view_listener_t::addMenu(new LLWorldPostProcess(), "World.PostProcess");
+ view_listener_t::addMenu(new LLWorldDayCycle(), "World.DayCycle");
+
+ view_listener_t::addMenu(new LLWorldToggleMovementControls(), "World.Toggle.MovementControls");
+ view_listener_t::addMenu(new LLWorldToggleCameraControls(), "World.Toggle.CameraControls");
+
+ // Tools menu
+ view_listener_t::addMenu(new LLToolsSelectTool(), "Tools.SelectTool");
+ view_listener_t::addMenu(new LLToolsSelectOnlyMyObjects(), "Tools.SelectOnlyMyObjects");
+ view_listener_t::addMenu(new LLToolsSelectOnlyMovableObjects(), "Tools.SelectOnlyMovableObjects");
+ view_listener_t::addMenu(new LLToolsSelectBySurrounding(), "Tools.SelectBySurrounding");
+ view_listener_t::addMenu(new LLToolsShowHiddenSelection(), "Tools.ShowHiddenSelection");
+ view_listener_t::addMenu(new LLToolsShowSelectionLightRadius(), "Tools.ShowSelectionLightRadius");
+ view_listener_t::addMenu(new LLToolsEditLinkedParts(), "Tools.EditLinkedParts");
+ view_listener_t::addMenu(new LLToolsSnapObjectXY(), "Tools.SnapObjectXY");
+ view_listener_t::addMenu(new LLToolsUseSelectionForGrid(), "Tools.UseSelectionForGrid");
+ view_listener_t::addMenu(new LLToolsSelectNextPart(), "Tools.SelectNextPart");
+ commit.add("Tools.Link", boost::bind(&LLSelectMgr::linkObjects, LLSelectMgr::getInstance()));
+ commit.add("Tools.Unlink", boost::bind(&LLSelectMgr::unlinkObjects, LLSelectMgr::getInstance()));
+ view_listener_t::addMenu(new LLToolsStopAllAnimations(), "Tools.StopAllAnimations");
+ view_listener_t::addMenu(new LLToolsReleaseKeys(), "Tools.ReleaseKeys");
+ view_listener_t::addMenu(new LLToolsEnableReleaseKeys(), "Tools.EnableReleaseKeys");
+ commit.add("Tools.LookAtSelection", boost::bind(&handle_look_at_selection, _2));
+ commit.add("Tools.BuyOrTake", boost::bind(&handle_buy_or_take));
+ commit.add("Tools.TakeCopy", boost::bind(&handle_take_copy));
+ view_listener_t::addMenu(new LLToolsSaveToInventory(), "Tools.SaveToInventory");
+ view_listener_t::addMenu(new LLToolsSaveToObjectInventory(), "Tools.SaveToObjectInventory");
+ view_listener_t::addMenu(new LLToolsSelectedScriptAction(), "Tools.SelectedScriptAction");
+
+ view_listener_t::addMenu(new LLToolsEnableToolNotPie(), "Tools.EnableToolNotPie");
+ view_listener_t::addMenu(new LLToolsEnableSelectNextPart(), "Tools.EnableSelectNextPart");
+ enable.add("Tools.EnableLink", boost::bind(&LLSelectMgr::enableLinkObjects, LLSelectMgr::getInstance()));
+ enable.add("Tools.EnableUnlink", boost::bind(&LLSelectMgr::enableUnlinkObjects, LLSelectMgr::getInstance()));
+ view_listener_t::addMenu(new LLToolsEnableBuyOrTake(), "Tools.EnableBuyOrTake");
+ enable.add("Tools.EnableTakeCopy", boost::bind(&enable_object_take_copy));
+ enable.add("Tools.VisibleBuyObject", boost::bind(&tools_visible_buy_object));
+ enable.add("Tools.VisibleTakeObject", boost::bind(&tools_visible_take_object));
+ view_listener_t::addMenu(new LLToolsEnableSaveToInventory(), "Tools.EnableSaveToInventory");
+ view_listener_t::addMenu(new LLToolsEnableSaveToObjectInventory(), "Tools.EnableSaveToObjectInventory");
+
+ // Help menu
+ // most items use the ShowFloater method
+
+ // Advanced menu
+ view_listener_t::addMenu(new LLAdvancedToggleConsole(), "Advanced.ToggleConsole");
+ view_listener_t::addMenu(new LLAdvancedCheckConsole(), "Advanced.CheckConsole");
+ view_listener_t::addMenu(new LLAdvancedDumpInfoToConsole(), "Advanced.DumpInfoToConsole");
+
+ // Advanced > HUD Info
+ view_listener_t::addMenu(new LLAdvancedToggleHUDInfo(), "Advanced.ToggleHUDInfo");
+ view_listener_t::addMenu(new LLAdvancedCheckHUDInfo(), "Advanced.CheckHUDInfo");
+
+ // Advanced Other Settings
+ view_listener_t::addMenu(new LLAdvancedClearGroupCache(), "Advanced.ClearGroupCache");
+
+ // Advanced > Render > Types
+ view_listener_t::addMenu(new LLAdvancedToggleRenderType(), "Advanced.ToggleRenderType");
+ view_listener_t::addMenu(new LLAdvancedCheckRenderType(), "Advanced.CheckRenderType");
+
+ //// Advanced > Render > Features
+ view_listener_t::addMenu(new LLAdvancedToggleFeature(), "Advanced.ToggleFeature");
+ view_listener_t::addMenu(new LLAdvancedCheckFeature(), "Advanced.CheckFeature");
+ // Advanced > Render > Info Displays
+ view_listener_t::addMenu(new LLAdvancedToggleInfoDisplay(), "Advanced.ToggleInfoDisplay");
+ view_listener_t::addMenu(new LLAdvancedCheckInfoDisplay(), "Advanced.CheckInfoDisplay");
+ view_listener_t::addMenu(new LLAdvancedSelectedTextureInfo(), "Advanced.SelectedTextureInfo");
+ view_listener_t::addMenu(new LLAdvancedToggleWireframe(), "Advanced.ToggleWireframe");
+ view_listener_t::addMenu(new LLAdvancedCheckWireframe(), "Advanced.CheckWireframe");
+ // Develop > Render
+ view_listener_t::addMenu(new LLAdvancedToggleTextureAtlas(), "Advanced.ToggleTextureAtlas");
+ view_listener_t::addMenu(new LLAdvancedCheckTextureAtlas(), "Advanced.CheckTextureAtlas");
+ view_listener_t::addMenu(new LLAdvancedEnableObjectObjectOcclusion(), "Advanced.EnableObjectObjectOcclusion");
+ view_listener_t::addMenu(new LLAdvancedEnableRenderFBO(), "Advanced.EnableRenderFBO");
+ view_listener_t::addMenu(new LLAdvancedEnableRenderDeferred(), "Advanced.EnableRenderDeferred");
+ view_listener_t::addMenu(new LLAdvancedEnableRenderDeferredOptions(), "Advanced.EnableRenderDeferredOptions");
+ view_listener_t::addMenu(new LLAdvancedToggleRandomizeFramerate(), "Advanced.ToggleRandomizeFramerate");
+ view_listener_t::addMenu(new LLAdvancedCheckRandomizeFramerate(), "Advanced.CheckRandomizeFramerate");
+ view_listener_t::addMenu(new LLAdvancedTogglePeriodicSlowFrame(), "Advanced.TogglePeriodicSlowFrame");
+ view_listener_t::addMenu(new LLAdvancedCheckPeriodicSlowFrame(), "Advanced.CheckPeriodicSlowFrame");
+ view_listener_t::addMenu(new LLAdvancedVectorizePerfTest(), "Advanced.VectorizePerfTest");
+ view_listener_t::addMenu(new LLAdvancedToggleFrameTest(), "Advanced.ToggleFrameTest");
+ view_listener_t::addMenu(new LLAdvancedCheckFrameTest(), "Advanced.CheckFrameTest");
+ view_listener_t::addMenu(new LLAdvancedHandleAttachedLightParticles(), "Advanced.HandleAttachedLightParticles");
+ view_listener_t::addMenu(new LLAdvancedCheckRenderShadowOption(), "Advanced.CheckRenderShadowOption");
+ view_listener_t::addMenu(new LLAdvancedClickRenderShadowOption(), "Advanced.ClickRenderShadowOption");
+
+
+ #ifdef TOGGLE_HACKED_GODLIKE_VIEWER
+ view_listener_t::addMenu(new LLAdvancedHandleToggleHackedGodmode(), "Advanced.HandleToggleHackedGodmode");
+ view_listener_t::addMenu(new LLAdvancedCheckToggleHackedGodmode(), "Advanced.CheckToggleHackedGodmode");
+ view_listener_t::addMenu(new LLAdvancedEnableToggleHackedGodmode(), "Advanced.EnableToggleHackedGodmode");
+ #endif
+
+ // Advanced > World
+ view_listener_t::addMenu(new LLAdvancedDumpScriptedCamera(), "Advanced.DumpScriptedCamera");
+ view_listener_t::addMenu(new LLAdvancedDumpRegionObjectCache(), "Advanced.DumpRegionObjectCache");
+
+ // Advanced > UI
+ commit.add("Advanced.WebBrowserTest", boost::bind(&handle_web_browser_test, _2)); // sigh! this one opens the MEDIA browser
+ commit.add("Advanced.WebContentTest", boost::bind(&handle_web_content_test, _2)); // this one opens the Web Content floater
+ view_listener_t::addMenu(new LLAdvancedBuyCurrencyTest(), "Advanced.BuyCurrencyTest");
+ view_listener_t::addMenu(new LLAdvancedDumpSelectMgr(), "Advanced.DumpSelectMgr");
+ view_listener_t::addMenu(new LLAdvancedDumpInventory(), "Advanced.DumpInventory");
+ commit.add("Advanced.DumpTimers", boost::bind(&handle_dump_timers) );
+ commit.add("Advanced.DumpFocusHolder", boost::bind(&handle_dump_focus) );
+ view_listener_t::addMenu(new LLAdvancedPrintSelectedObjectInfo(), "Advanced.PrintSelectedObjectInfo");
+ view_listener_t::addMenu(new LLAdvancedPrintAgentInfo(), "Advanced.PrintAgentInfo");
+ view_listener_t::addMenu(new LLAdvancedPrintTextureMemoryStats(), "Advanced.PrintTextureMemoryStats");
+ view_listener_t::addMenu(new LLAdvancedToggleDebugClicks(), "Advanced.ToggleDebugClicks");
+ view_listener_t::addMenu(new LLAdvancedCheckDebugClicks(), "Advanced.CheckDebugClicks");
+ view_listener_t::addMenu(new LLAdvancedCheckDebugViews(), "Advanced.CheckDebugViews");
+ view_listener_t::addMenu(new LLAdvancedToggleDebugViews(), "Advanced.ToggleDebugViews");
+ view_listener_t::addMenu(new LLAdvancedToggleXUINameTooltips(), "Advanced.ToggleXUINameTooltips");
+ view_listener_t::addMenu(new LLAdvancedCheckXUINameTooltips(), "Advanced.CheckXUINameTooltips");
+ view_listener_t::addMenu(new LLAdvancedToggleDebugMouseEvents(), "Advanced.ToggleDebugMouseEvents");
+ view_listener_t::addMenu(new LLAdvancedCheckDebugMouseEvents(), "Advanced.CheckDebugMouseEvents");
+ view_listener_t::addMenu(new LLAdvancedToggleDebugKeys(), "Advanced.ToggleDebugKeys");
+ view_listener_t::addMenu(new LLAdvancedCheckDebugKeys(), "Advanced.CheckDebugKeys");
+ view_listener_t::addMenu(new LLAdvancedToggleDebugWindowProc(), "Advanced.ToggleDebugWindowProc");
+ view_listener_t::addMenu(new LLAdvancedCheckDebugWindowProc(), "Advanced.CheckDebugWindowProc");
+ commit.add("Advanced.ShowSideTray", boost::bind(&handle_show_side_tray));
+
+ // Advanced > XUI
+ commit.add("Advanced.ReloadColorSettings", boost::bind(&LLUIColorTable::loadFromSettings, LLUIColorTable::getInstance()));
+ view_listener_t::addMenu(new LLAdvancedToggleXUINames(), "Advanced.ToggleXUINames");
+ view_listener_t::addMenu(new LLAdvancedCheckXUINames(), "Advanced.CheckXUINames");
+ view_listener_t::addMenu(new LLAdvancedSendTestIms(), "Advanced.SendTestIMs");
+ commit.add("Advanced.FlushNameCaches", boost::bind(&handle_flush_name_caches));
+
+ // Advanced > Character > Grab Baked Texture
+ view_listener_t::addMenu(new LLAdvancedGrabBakedTexture(), "Advanced.GrabBakedTexture");
+ view_listener_t::addMenu(new LLAdvancedEnableGrabBakedTexture(), "Advanced.EnableGrabBakedTexture");
+
+ // Advanced > Character > Character Tests
+ view_listener_t::addMenu(new LLAdvancedAppearanceToXML(), "Advanced.AppearanceToXML");
+ view_listener_t::addMenu(new LLAdvancedToggleCharacterGeometry(), "Advanced.ToggleCharacterGeometry");
+
+ view_listener_t::addMenu(new LLAdvancedTestMale(), "Advanced.TestMale");
+ view_listener_t::addMenu(new LLAdvancedTestFemale(), "Advanced.TestFemale");
+ view_listener_t::addMenu(new LLAdvancedTogglePG(), "Advanced.TogglePG");
+
+ // Advanced > Character (toplevel)
+ view_listener_t::addMenu(new LLAdvancedForceParamsToDefault(), "Advanced.ForceParamsToDefault");
+ view_listener_t::addMenu(new LLAdvancedReloadVertexShader(), "Advanced.ReloadVertexShader");
+ view_listener_t::addMenu(new LLAdvancedToggleAnimationInfo(), "Advanced.ToggleAnimationInfo");
+ view_listener_t::addMenu(new LLAdvancedCheckAnimationInfo(), "Advanced.CheckAnimationInfo");
+ view_listener_t::addMenu(new LLAdvancedToggleShowLookAt(), "Advanced.ToggleShowLookAt");
+ view_listener_t::addMenu(new LLAdvancedCheckShowLookAt(), "Advanced.CheckShowLookAt");
+ view_listener_t::addMenu(new LLAdvancedToggleShowPointAt(), "Advanced.ToggleShowPointAt");
+ view_listener_t::addMenu(new LLAdvancedCheckShowPointAt(), "Advanced.CheckShowPointAt");
+ view_listener_t::addMenu(new LLAdvancedToggleDebugJointUpdates(), "Advanced.ToggleDebugJointUpdates");
+ view_listener_t::addMenu(new LLAdvancedCheckDebugJointUpdates(), "Advanced.CheckDebugJointUpdates");
+ view_listener_t::addMenu(new LLAdvancedToggleDisableLOD(), "Advanced.ToggleDisableLOD");
+ view_listener_t::addMenu(new LLAdvancedCheckDisableLOD(), "Advanced.CheckDisableLOD");
+ view_listener_t::addMenu(new LLAdvancedToggleDebugCharacterVis(), "Advanced.ToggleDebugCharacterVis");
+ view_listener_t::addMenu(new LLAdvancedCheckDebugCharacterVis(), "Advanced.CheckDebugCharacterVis");
+ view_listener_t::addMenu(new LLAdvancedDumpAttachments(), "Advanced.DumpAttachments");
+ view_listener_t::addMenu(new LLAdvancedRebakeTextures(), "Advanced.RebakeTextures");
+ view_listener_t::addMenu(new LLAdvancedDebugAvatarTextures(), "Advanced.DebugAvatarTextures");
+ view_listener_t::addMenu(new LLAdvancedDumpAvatarLocalTextures(), "Advanced.DumpAvatarLocalTextures");
+ // Advanced > Network
+ view_listener_t::addMenu(new LLAdvancedEnableMessageLog(), "Advanced.EnableMessageLog");
+ view_listener_t::addMenu(new LLAdvancedDisableMessageLog(), "Advanced.DisableMessageLog");
+ view_listener_t::addMenu(new LLAdvancedDropPacket(), "Advanced.DropPacket");
+
+ // Advanced > Recorder
+ view_listener_t::addMenu(new LLAdvancedAgentPilot(), "Advanced.AgentPilot");
+ view_listener_t::addMenu(new LLAdvancedToggleAgentPilotLoop(), "Advanced.ToggleAgentPilotLoop");
+ view_listener_t::addMenu(new LLAdvancedCheckAgentPilotLoop(), "Advanced.CheckAgentPilotLoop");
+
+ // Advanced > Debugging
+ view_listener_t::addMenu(new LLAdvancedForceErrorBreakpoint(), "Advanced.ForceErrorBreakpoint");
+ view_listener_t::addMenu(new LLAdvancedForceErrorLlerror(), "Advanced.ForceErrorLlerror");
+ view_listener_t::addMenu(new LLAdvancedForceErrorBadMemoryAccess(), "Advanced.ForceErrorBadMemoryAccess");
+ view_listener_t::addMenu(new LLAdvancedForceErrorInfiniteLoop(), "Advanced.ForceErrorInfiniteLoop");
+ view_listener_t::addMenu(new LLAdvancedForceErrorSoftwareException(), "Advanced.ForceErrorSoftwareException");
+ view_listener_t::addMenu(new LLAdvancedForceErrorDriverCrash(), "Advanced.ForceErrorDriverCrash");
+ view_listener_t::addMenu(new LLAdvancedForceErrorDisconnectViewer(), "Advanced.ForceErrorDisconnectViewer");
+
+ // Advanced (toplevel)
+ view_listener_t::addMenu(new LLAdvancedToggleShowObjectUpdates(), "Advanced.ToggleShowObjectUpdates");
+ view_listener_t::addMenu(new LLAdvancedCheckShowObjectUpdates(), "Advanced.CheckShowObjectUpdates");
+ view_listener_t::addMenu(new LLAdvancedCompressImage(), "Advanced.CompressImage");
+ view_listener_t::addMenu(new LLAdvancedShowDebugSettings(), "Advanced.ShowDebugSettings");
+ view_listener_t::addMenu(new LLAdvancedEnableViewAdminOptions(), "Advanced.EnableViewAdminOptions");
+ view_listener_t::addMenu(new LLAdvancedToggleViewAdminOptions(), "Advanced.ToggleViewAdminOptions");
+ view_listener_t::addMenu(new LLAdvancedCheckViewAdminOptions(), "Advanced.CheckViewAdminOptions");
+ view_listener_t::addMenu(new LLAdvancedRequestAdminStatus(), "Advanced.RequestAdminStatus");
+ view_listener_t::addMenu(new LLAdvancedLeaveAdminStatus(), "Advanced.LeaveAdminStatus");
+
+
+ // Admin >Object
+ view_listener_t::addMenu(new LLAdminForceTakeCopy(), "Admin.ForceTakeCopy");
+ view_listener_t::addMenu(new LLAdminHandleObjectOwnerSelf(), "Admin.HandleObjectOwnerSelf");
+ view_listener_t::addMenu(new LLAdminHandleObjectOwnerPermissive(), "Admin.HandleObjectOwnerPermissive");
+ view_listener_t::addMenu(new LLAdminHandleForceDelete(), "Admin.HandleForceDelete");
+ view_listener_t::addMenu(new LLAdminHandleObjectLock(), "Admin.HandleObjectLock");
+ view_listener_t::addMenu(new LLAdminHandleObjectAssetIDs(), "Admin.HandleObjectAssetIDs");
+
+ // Admin >Parcel
+ view_listener_t::addMenu(new LLAdminHandleForceParcelOwnerToMe(), "Admin.HandleForceParcelOwnerToMe");
+ view_listener_t::addMenu(new LLAdminHandleForceParcelToContent(), "Admin.HandleForceParcelToContent");
+ view_listener_t::addMenu(new LLAdminHandleClaimPublicLand(), "Admin.HandleClaimPublicLand");
+
+ // Admin >Region
+ view_listener_t::addMenu(new LLAdminHandleRegionDumpTempAssetData(), "Admin.HandleRegionDumpTempAssetData");
+ // Admin top level
+ view_listener_t::addMenu(new LLAdminOnSaveState(), "Admin.OnSaveState");
+
+ // Self context menu
+ view_listener_t::addMenu(new LLSelfStandUp(), "Self.StandUp");
+ enable.add("Self.EnableStandUp", boost::bind(&enable_standup_self));
+ view_listener_t::addMenu(new LLSelfSitDown(), "Self.SitDown");
+ enable.add("Self.EnableSitDown", boost::bind(&enable_sitdown_self));
+ view_listener_t::addMenu(new LLSelfRemoveAllAttachments(), "Self.RemoveAllAttachments");
+
+ view_listener_t::addMenu(new LLSelfEnableRemoveAllAttachments(), "Self.EnableRemoveAllAttachments");
+
+ // we don't use boost::bind directly to delay side tray construction
+ view_listener_t::addMenu( new LLTogglePanelPeopleTab(), "SideTray.PanelPeopleTab");
+
+ // Avatar pie menu
+ view_listener_t::addMenu(new LLObjectMute(), "Avatar.Mute");
+ view_listener_t::addMenu(new LLAvatarAddFriend(), "Avatar.AddFriend");
+ view_listener_t::addMenu(new LLAvatarAddContact(), "Avatar.AddContact");
+ commit.add("Avatar.Freeze", boost::bind(&handle_avatar_freeze, LLSD()));
+ view_listener_t::addMenu(new LLAvatarDebug(), "Avatar.Debug");
+ view_listener_t::addMenu(new LLAvatarVisibleDebug(), "Avatar.VisibleDebug");
+ view_listener_t::addMenu(new LLAvatarInviteToGroup(), "Avatar.InviteToGroup");
+ commit.add("Avatar.Eject", boost::bind(&handle_avatar_eject, LLSD()));
+ commit.add("Avatar.ShowInspector", boost::bind(&handle_avatar_show_inspector));
+ view_listener_t::addMenu(new LLAvatarSendIM(), "Avatar.SendIM");
+ view_listener_t::addMenu(new LLAvatarCall(), "Avatar.Call");
+ enable.add("Avatar.EnableCall", boost::bind(&LLAvatarActions::canCall));
+ view_listener_t::addMenu(new LLAvatarReportAbuse(), "Avatar.ReportAbuse");
+
+ view_listener_t::addMenu(new LLAvatarEnableAddFriend(), "Avatar.EnableAddFriend");
+ enable.add("Avatar.EnableFreezeEject", boost::bind(&enable_freeze_eject, _2));
+
+ // Object pie menu
+ view_listener_t::addMenu(new LLObjectBuild(), "Object.Build");
+ commit.add("Object.Touch", boost::bind(&handle_object_touch));
+ commit.add("Object.SitOrStand", boost::bind(&handle_object_sit_or_stand));
+ commit.add("Object.Delete", boost::bind(&handle_object_delete));
+ view_listener_t::addMenu(new LLObjectAttachToAvatar(true), "Object.AttachToAvatar");
+ view_listener_t::addMenu(new LLObjectAttachToAvatar(false), "Object.AttachAddToAvatar");
+ view_listener_t::addMenu(new LLObjectReturn(), "Object.Return");
+ view_listener_t::addMenu(new LLObjectReportAbuse(), "Object.ReportAbuse");
+ view_listener_t::addMenu(new LLObjectMute(), "Object.Mute");
+
+ enable.add("Object.VisibleTake", boost::bind(&visible_take_object));
+ enable.add("Object.VisibleBuy", boost::bind(&visible_buy_object));
+
+ commit.add("Object.Buy", boost::bind(&handle_buy));
+ commit.add("Object.Edit", boost::bind(&handle_object_edit));
+ commit.add("Object.Inspect", boost::bind(&handle_object_inspect));
+ commit.add("Object.Open", boost::bind(&handle_object_open));
+ commit.add("Object.Take", boost::bind(&handle_take));
+ commit.add("Object.ShowInspector", boost::bind(&handle_object_show_inspector));
+ enable.add("Object.EnableOpen", boost::bind(&enable_object_open));
+ enable.add("Object.EnableTouch", boost::bind(&enable_object_touch, _1));
+ enable.add("Object.EnableDelete", boost::bind(&enable_object_delete));
+ enable.add("Object.EnableWear", boost::bind(&object_selected_and_point_valid));
+
+ enable.add("Object.EnableStandUp", boost::bind(&enable_object_stand_up));
+ enable.add("Object.EnableSit", boost::bind(&enable_object_sit, _1));
+
+ view_listener_t::addMenu(new LLObjectEnableReturn(), "Object.EnableReturn");
+ view_listener_t::addMenu(new LLObjectEnableReportAbuse(), "Object.EnableReportAbuse");
+
+ enable.add("Avatar.EnableMute", boost::bind(&enable_object_mute));
+ enable.add("Object.EnableMute", boost::bind(&enable_object_mute));
+ enable.add("Object.EnableBuy", boost::bind(&enable_buy_object));
+ commit.add("Object.ZoomIn", boost::bind(&handle_look_at_selection, "zoom"));
+
+ // Attachment pie menu
+ enable.add("Attachment.Label", boost::bind(&onEnableAttachmentLabel, _1, _2));
+ view_listener_t::addMenu(new LLAttachmentDrop(), "Attachment.Drop");
+ view_listener_t::addMenu(new LLAttachmentDetachFromPoint(), "Attachment.DetachFromPoint");
+ view_listener_t::addMenu(new LLAttachmentDetach(), "Attachment.Detach");
+ view_listener_t::addMenu(new LLAttachmentPointFilled(), "Attachment.PointFilled");
+ view_listener_t::addMenu(new LLAttachmentEnableDrop(), "Attachment.EnableDrop");
+ view_listener_t::addMenu(new LLAttachmentEnableDetach(), "Attachment.EnableDetach");
+
+ // Land pie menu
+ view_listener_t::addMenu(new LLLandBuild(), "Land.Build");
+ view_listener_t::addMenu(new LLLandSit(), "Land.Sit");
+ view_listener_t::addMenu(new LLLandBuyPass(), "Land.BuyPass");
+ view_listener_t::addMenu(new LLLandEdit(), "Land.Edit");
+
+ view_listener_t::addMenu(new LLLandEnableBuyPass(), "Land.EnableBuyPass");
+ commit.add("Land.Buy", boost::bind(&handle_buy_land));
+
+ // Generic actions
+ commit.add("ReportAbuse", boost::bind(&handle_report_abuse));
+ commit.add("BuyCurrency", boost::bind(&handle_buy_currency));
+ view_listener_t::addMenu(new LLShowHelp(), "ShowHelp");
+ view_listener_t::addMenu(new LLToggleHelp(), "ToggleHelp");
+ view_listener_t::addMenu(new LLPromptShowURL(), "PromptShowURL");
+ view_listener_t::addMenu(new LLShowAgentProfile(), "ShowAgentProfile");
+ view_listener_t::addMenu(new LLToggleAgentProfile(), "ToggleAgentProfile");
+ view_listener_t::addMenu(new LLToggleControl(), "ToggleControl");
+ view_listener_t::addMenu(new LLCheckControl(), "CheckControl");
+ view_listener_t::addMenu(new LLGoToObject(), "GoToObject");
+ commit.add("PayObject", boost::bind(&handle_give_money_dialog));
+
+ enable.add("EnablePayObject", boost::bind(&enable_pay_object));
+ enable.add("EnablePayAvatar", boost::bind(&enable_pay_avatar));
+ enable.add("EnableEdit", boost::bind(&enable_object_edit));
+ enable.add("VisibleBuild", boost::bind(&enable_object_build));
+
+ view_listener_t::addMenu(new LLFloaterVisible(), "FloaterVisible");
+ view_listener_t::addMenu(new LLShowSidetrayPanel(), "ShowSidetrayPanel");
+ view_listener_t::addMenu(new LLSidetrayPanelVisible(), "SidetrayPanelVisible");
+ view_listener_t::addMenu(new LLSomethingSelected(), "SomethingSelected");
+ view_listener_t::addMenu(new LLSomethingSelectedNoHUD(), "SomethingSelectedNoHUD");
+ view_listener_t::addMenu(new LLEditableSelected(), "EditableSelected");
+ view_listener_t::addMenu(new LLEditableSelectedMono(), "EditableSelectedMono");
+
+ view_listener_t::addMenu(new LLToggleUIHints(), "ToggleUIHints");
+
+ commit.add("Destination.show", boost::bind(&toggle_destination_and_avatar_picker, 0));
+ commit.add("Avatar.show", boost::bind(&toggle_destination_and_avatar_picker, 1));
+}
diff --git a/indra/newview/llviewermenufile.cpp b/indra/newview/llviewermenufile.cpp
index fda291f3c1..9ecb11d253 100644
--- a/indra/newview/llviewermenufile.cpp
+++ b/indra/newview/llviewermenufile.cpp
@@ -34,6 +34,7 @@
#include "llfilepicker.h"
#include "llfloaterreg.h"
#include "llbuycurrencyhtml.h"
+#include "llfloatermodelpreview.h"
#include "llfloatersnapshot.h"
#include "llimage.h"
#include "llimagebmp.h"
@@ -52,13 +53,14 @@
#include "llvfs.h"
#include "llviewerinventory.h"
#include "llviewermenu.h" // gMenuHolder
+#include "llviewerparcelmgr.h"
#include "llviewerregion.h"
#include "llviewerstats.h"
#include "llviewerwindow.h"
#include "llappviewer.h"
#include "lluploaddialog.h"
#include "lltrans.h"
-
+#include "llfloaterbuycurrency.h"
// linden libraries
#include "llassetuploadresponders.h"
@@ -66,6 +68,7 @@
#include "llhttpclient.h"
#include "llnotificationsutil.h"
#include "llsdserialize.h"
+#include "llsdutil.h"
#include "llstring.h"
#include "lltransactiontypes.h"
#include "lluuid.h"
@@ -84,6 +87,99 @@ class LLFileEnableUpload : public view_listener_t
}
};
+class LLFileEnableUploadModel : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ return true;
+ }
+};
+
+class LLMeshEnabled : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ return gSavedSettings.getBOOL("MeshEnabled");
+ }
+};
+
+class LLMeshUploadVisible : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ return gSavedSettings.getBOOL("MeshEnabled") &&
+ LLViewerParcelMgr::getInstance()->allowAgentBuild() &&
+ !gAgent.getRegion()->getCapability("ObjectAdd").empty();
+ }
+};
+
+LLMutex* LLFilePickerThread::sMutex = NULL;
+std::queue<LLFilePickerThread*> LLFilePickerThread::sDeadQ;
+
+void LLFilePickerThread::getFile()
+{
+#if LL_WINDOWS
+ start();
+#else
+ run();
+#endif
+}
+
+//virtual
+void LLFilePickerThread::run()
+{
+ LLFilePicker picker;
+#if LL_WINDOWS
+ if (picker.getOpenFile(mFilter, false))
+ {
+ mFile = picker.getFirstFile();
+ }
+#else
+ if (picker.getOpenFile(mFilter, true))
+ {
+ mFile = picker.getFirstFile();
+ }
+#endif
+
+ {
+ LLMutexLock lock(sMutex);
+ sDeadQ.push(this);
+ }
+
+}
+
+//static
+void LLFilePickerThread::initClass()
+{
+ sMutex = new LLMutex(NULL);
+}
+
+//static
+void LLFilePickerThread::cleanupClass()
+{
+ clearDead();
+
+ delete sMutex;
+ sMutex = NULL;
+}
+
+//static
+void LLFilePickerThread::clearDead()
+{
+ if (!sDeadQ.empty())
+ {
+ LLMutexLock lock(sMutex);
+ while (!sDeadQ.empty())
+ {
+ LLFilePickerThread* thread = sDeadQ.front();
+ thread->notify(thread->mFile);
+ delete thread;
+ sDeadQ.pop();
+ }
+ }
+}
+
+
//============================================================================
#if LL_WINDOWS
@@ -97,6 +193,7 @@ static std::string XML_EXTENSIONS = "xml";
static std::string SLOBJECT_EXTENSIONS = "slobject";
#endif
static std::string ALL_FILE_EXTENSIONS = "*.*";
+static std::string MODEL_EXTENSIONS = "dae";
std::string build_extensions_string(LLFilePicker::ELoadFilter filter)
{
@@ -111,6 +208,8 @@ std::string build_extensions_string(LLFilePicker::ELoadFilter filter)
return ANIM_EXTENSIONS;
case LLFilePicker::FFLOAD_SLOBJECT:
return SLOBJECT_EXTENSIONS;
+ case LLFilePicker::FFLOAD_MODEL:
+ return MODEL_EXTENSIONS;
#ifdef _CORY_TESTING
case LLFilePicker::FFLOAD_GEOMETRY:
return GEOMETRY_EXTENSIONS;
@@ -254,6 +353,20 @@ class LLFileUploadImage : public view_listener_t
}
};
+class LLFileUploadModel : public view_listener_t
+{
+ bool handleEvent(const LLSD& userdata)
+ {
+ LLFloaterModelPreview* fmp = (LLFloaterModelPreview*) LLFloaterReg::getInstance("upload_model");
+ if (fmp)
+ {
+ fmp->loadModel(3);
+ }
+
+ return TRUE;
+ }
+};
+
class LLFileUploadSound : public view_listener_t
{
bool handleEvent(const LLSD& userdata)
@@ -315,10 +428,21 @@ class LLFileUploadBulk : public view_listener_t
LLAssetStorage::LLStoreAssetCallback callback = NULL;
S32 expected_upload_cost = LLGlobalEconomy::Singleton::getInstance()->getPriceUpload();
void *userdata = NULL;
- upload_new_resource(filename, asset_name, asset_name, 0, LLFolderType::FT_NONE, LLInventoryType::IT_NONE,
- LLFloaterPerms::getNextOwnerPerms(), LLFloaterPerms::getGroupPerms(), LLFloaterPerms::getEveryonePerms(),
- display_name,
- callback, expected_upload_cost, userdata);
+
+ upload_new_resource(
+ filename,
+ asset_name,
+ asset_name,
+ 0,
+ LLFolderType::FT_NONE,
+ LLInventoryType::IT_NONE,
+ LLFloaterPerms::getNextOwnerPerms(),
+ LLFloaterPerms::getGroupPerms(),
+ LLFloaterPerms::getEveryonePerms(),
+ display_name,
+ callback,
+ expected_upload_cost,
+ userdata);
// *NOTE: Ew, we don't iterate over the file list here,
// we handle the next files in upload_done_callback()
@@ -473,17 +597,20 @@ void handle_compress_image(void*)
}
}
-void upload_new_resource(const std::string& src_filename, std::string name,
- std::string desc, S32 compression_info,
- LLFolderType::EType destination_folder_type,
- LLInventoryType::EType inv_type,
- U32 next_owner_perms,
- U32 group_perms,
- U32 everyone_perms,
- const std::string& display_name,
- LLAssetStorage::LLStoreAssetCallback callback,
- S32 expected_upload_cost,
- void *userdata)
+LLUUID upload_new_resource(
+ const std::string& src_filename,
+ std::string name,
+ std::string desc,
+ S32 compression_info,
+ LLFolderType::EType destination_folder_type,
+ LLInventoryType::EType inv_type,
+ U32 next_owner_perms,
+ U32 group_perms,
+ U32 everyone_perms,
+ const std::string& display_name,
+ LLAssetStorage::LLStoreAssetCallback callback,
+ S32 expected_upload_cost,
+ void *userdata)
{
// Generate the temporary UUID.
std::string filename = gDirUtilp->getTempFilename();
@@ -508,7 +635,7 @@ void upload_new_resource(const std::string& src_filename, std::string name,
short_name.c_str());
args["FILE"] = short_name;
upload_error(error_message, "NoFileExtension", filename, args);
- return;
+ return LLUUID();
}
else if( exten == "bmp")
{
@@ -522,7 +649,7 @@ void upload_new_resource(const std::string& src_filename, std::string name,
args["FILE"] = src_filename;
args["ERROR"] = LLImage::getLastError();
upload_error(error_message, "ProblemWithFile", filename, args);
- return;
+ return LLUUID();
}
}
else if( exten == "tga")
@@ -537,7 +664,7 @@ void upload_new_resource(const std::string& src_filename, std::string name,
args["FILE"] = src_filename;
args["ERROR"] = LLImage::getLastError();
upload_error(error_message, "ProblemWithFile", filename, args);
- return;
+ return LLUUID();
}
}
else if( exten == "jpg" || exten == "jpeg")
@@ -552,7 +679,7 @@ void upload_new_resource(const std::string& src_filename, std::string name,
args["FILE"] = src_filename;
args["ERROR"] = LLImage::getLastError();
upload_error(error_message, "ProblemWithFile", filename, args);
- return;
+ return LLUUID();
}
}
else if( exten == "png")
@@ -567,7 +694,7 @@ void upload_new_resource(const std::string& src_filename, std::string name,
args["FILE"] = src_filename;
args["ERROR"] = LLImage::getLastError();
upload_error(error_message, "ProblemWithFile", filename, args);
- return;
+ return LLUUID();
}
}
else if(exten == "wav")
@@ -595,7 +722,7 @@ void upload_new_resource(const std::string& src_filename, std::string name,
upload_error(error_message, "UnknownVorbisEncodeFailure", filename, args);
break;
}
- return;
+ return LLUUID();
}
}
else if(exten == "tmp")
@@ -635,7 +762,7 @@ void upload_new_resource(const std::string& src_filename, std::string name,
error_message = llformat("corrupt resource file: %s", src_filename.c_str());
args["FILE"] = src_filename;
upload_error(error_message, "CorruptResourceFile", filename, args);
- return;
+ return LLUUID();
}
if (2 == tokens_read)
@@ -663,7 +790,7 @@ void upload_new_resource(const std::string& src_filename, std::string name,
error_message = llformat("unknown linden resource file version in file: %s", src_filename.c_str());
args["FILE"] = src_filename;
upload_error(error_message, "UnknownResourceFileVersion", filename, args);
- return;
+ return LLUUID();
}
}
else
@@ -705,7 +832,7 @@ void upload_new_resource(const std::string& src_filename, std::string name,
error_message = llformat( "Unable to create output file: %s", filename.c_str());
args["FILE"] = filename;
upload_error(error_message, "UnableToCreateOutputFile", filename, args);
- return;
+ return LLUUID();
}
fclose(in);
@@ -719,7 +846,7 @@ void upload_new_resource(const std::string& src_filename, std::string name,
{
error_message = llformat("We do not currently support bulk upload of animation files\n");
upload_error(error_message, "DoNotSupportBulkAnimationUpload", filename, args);
- return;
+ return LLUUID();
}
else
{
@@ -765,9 +892,21 @@ void upload_new_resource(const std::string& src_filename, std::string name,
{
t_disp_name = src_filename;
}
- upload_new_resource(tid, asset_type, name, desc, compression_info, // tid
- destination_folder_type, inv_type, next_owner_perms, group_perms, everyone_perms,
- display_name, callback, expected_upload_cost, userdata);
+ upload_new_resource(
+ tid,
+ asset_type,
+ name,
+ desc,
+ compression_info, // tid
+ destination_folder_type,
+ inv_type,
+ next_owner_perms,
+ group_perms,
+ everyone_perms,
+ display_name,
+ callback,
+ expected_upload_cost,
+ userdata);
}
else
{
@@ -781,9 +920,15 @@ void upload_new_resource(const std::string& src_filename, std::string name,
}
LLFilePicker::instance().reset();
}
+
+ return uuid;
}
-void upload_done_callback(const LLUUID& uuid, void* user_data, S32 result, LLExtStat ext_status) // StoreAssetData callback (fixed)
+void upload_done_callback(
+ const LLUUID& uuid,
+ void* user_data,
+ S32 result,
+ LLExtStat ext_status) // StoreAssetData callback (fixed)
{
LLResourceData* data = (LLResourceData*)user_data;
S32 expected_upload_cost = data ? data->mExpectedUploadCost : 0;
@@ -888,35 +1033,102 @@ void upload_done_callback(const LLUUID& uuid, void* user_data, S32 result, LLExt
std::string display_name = LLStringUtil::null;
LLAssetStorage::LLStoreAssetCallback callback = NULL;
void *userdata = NULL;
- upload_new_resource(next_file, asset_name, asset_name, // file
- 0, LLFolderType::FT_NONE, LLInventoryType::IT_NONE,
- PERM_NONE, PERM_NONE, PERM_NONE,
- display_name,
- callback,
- expected_upload_cost, // assuming next in a group of uploads is of roughly the same type, i.e. same upload cost
- userdata);
+ upload_new_resource(
+ next_file,
+ asset_name,
+ asset_name, // file
+ 0,
+ LLFolderType::FT_NONE,
+ LLInventoryType::IT_NONE,
+ PERM_NONE,
+ PERM_NONE,
+ PERM_NONE,
+ display_name,
+ callback,
+ expected_upload_cost, // assuming next in a group of uploads is of roughly the same type, i.e. same upload cost
+ userdata);
}
}
-void upload_new_resource(const LLTransactionID &tid, LLAssetType::EType asset_type,
- std::string name,
- std::string desc, S32 compression_info,
- LLFolderType::EType destination_folder_type,
- LLInventoryType::EType inv_type,
- U32 next_owner_perms,
- U32 group_perms,
- U32 everyone_perms,
- const std::string& display_name,
- LLAssetStorage::LLStoreAssetCallback callback,
- S32 expected_upload_cost,
- void *userdata)
+static LLAssetID upload_new_resource_prep(
+ const LLTransactionID& tid,
+ LLAssetType::EType asset_type,
+ LLInventoryType::EType& inventory_type,
+ std::string& name,
+ const std::string& display_name,
+ std::string& description)
+{
+ LLAssetID uuid = generate_asset_id_for_new_upload(tid);
+
+ increase_new_upload_stats(asset_type);
+
+ assign_defaults_and_show_upload_message(
+ asset_type,
+ inventory_type,
+ name,
+ display_name,
+ description);
+
+ return uuid;
+}
+
+LLSD generate_new_resource_upload_capability_body(
+ LLAssetType::EType asset_type,
+ const std::string& name,
+ const std::string& desc,
+ LLFolderType::EType destination_folder_type,
+ LLInventoryType::EType inv_type,
+ U32 next_owner_perms,
+ U32 group_perms,
+ U32 everyone_perms)
+{
+ LLSD body;
+
+ body["folder_id"] = gInventory.findCategoryUUIDForType(
+ (destination_folder_type == LLFolderType::FT_NONE) ?
+ (LLFolderType::EType) asset_type :
+ destination_folder_type);
+
+ body["asset_type"] = LLAssetType::lookup(asset_type);
+ body["inventory_type"] = LLInventoryType::lookup(inv_type);
+ body["name"] = name;
+ body["description"] = desc;
+ body["next_owner_mask"] = LLSD::Integer(next_owner_perms);
+ body["group_mask"] = LLSD::Integer(group_perms);
+ body["everyone_mask"] = LLSD::Integer(everyone_perms);
+
+ return body;
+}
+
+void upload_new_resource(
+ const LLTransactionID &tid,
+ LLAssetType::EType asset_type,
+ std::string name,
+ std::string desc,
+ S32 compression_info,
+ LLFolderType::EType destination_folder_type,
+ LLInventoryType::EType inv_type,
+ U32 next_owner_perms,
+ U32 group_perms,
+ U32 everyone_perms,
+ const std::string& display_name,
+ LLAssetStorage::LLStoreAssetCallback callback,
+ S32 expected_upload_cost,
+ void *userdata)
{
if(gDisconnected)
{
return ;
}
-
- LLAssetID uuid = tid.makeAssetID(gAgent.getSecureSessionID());
+
+ LLAssetID uuid =
+ upload_new_resource_prep(
+ tid,
+ asset_type,
+ inv_type,
+ name,
+ display_name,
+ desc);
if( LLAssetType::AT_SOUND == asset_type )
{
@@ -961,26 +1173,32 @@ void upload_new_resource(const LLTransactionID &tid, LLAssetType::EType asset_ty
llinfos << "Expected Upload Cost: " << expected_upload_cost << llendl;
lldebugs << "Folder: " << gInventory.findCategoryUUIDForType((destination_folder_type == LLFolderType::FT_NONE) ? LLFolderType::assetTypeToFolderType(asset_type) : destination_folder_type) << llendl;
lldebugs << "Asset Type: " << LLAssetType::lookup(asset_type) << llendl;
- std::string url = gAgent.getRegion()->getCapability("NewFileAgentInventory");
- if (!url.empty())
+
+ std::string url = gAgent.getRegion()->getCapability(
+ "NewFileAgentInventory");
+
+ if ( !url.empty() )
{
llinfos << "New Agent Inventory via capability" << llendl;
- LLSD body;
- body["folder_id"] = gInventory.findCategoryUUIDForType((destination_folder_type == LLFolderType::FT_NONE) ? LLFolderType::assetTypeToFolderType(asset_type) : destination_folder_type);
- body["asset_type"] = LLAssetType::lookup(asset_type);
- body["inventory_type"] = LLInventoryType::lookup(inv_type);
- body["name"] = name;
- body["description"] = desc;
- body["next_owner_mask"] = LLSD::Integer(next_owner_perms);
- body["group_mask"] = LLSD::Integer(group_perms);
- body["everyone_mask"] = LLSD::Integer(everyone_perms);
- body["expected_upload_cost"] = LLSD::Integer(expected_upload_cost);
-
- //std::ostringstream llsdxml;
- //LLSDSerialize::toPrettyXML(body, llsdxml);
- //llinfos << "posting body to capability: " << llsdxml.str() << llendl;
- LLHTTPClient::post(url, body, new LLNewAgentInventoryResponder(body, uuid, asset_type));
+ LLSD body;
+ body = generate_new_resource_upload_capability_body(
+ asset_type,
+ name,
+ desc,
+ destination_folder_type,
+ inv_type,
+ next_owner_perms,
+ group_perms,
+ everyone_perms);
+
+ LLHTTPClient::post(
+ url,
+ body,
+ new LLNewAgentInventoryResponder(
+ body,
+ uuid,
+ asset_type));
}
else
{
@@ -994,10 +1212,10 @@ void upload_new_resource(const LLTransactionID &tid, LLAssetType::EType asset_ty
S32 balance = gStatusBar->getBalance();
if (balance < expected_upload_cost)
{
+ // insufficient funds, bail on this upload
LLStringUtil::format_map_t args;
args["NAME"] = name;
args["AMOUNT"] = llformat("%d", expected_upload_cost);
- // insufficient funds, bail on this upload
LLBuyCurrencyHTML::openCurrencyFloater( LLTrans::getString("UploadingCosts", args), expected_upload_cost );
return;
}
@@ -1021,18 +1239,157 @@ void upload_new_resource(const LLTransactionID &tid, LLAssetType::EType asset_ty
{
asset_callback = callback;
}
- gAssetStorage->storeAssetData(data->mAssetInfo.mTransactionID, data->mAssetInfo.mType,
- asset_callback,
- (void*)data,
- FALSE);
+ gAssetStorage->storeAssetData(
+ data->mAssetInfo.mTransactionID,
+ data->mAssetInfo.mType,
+ asset_callback,
+ (void*)data,
+ FALSE);
+ }
+}
+
+BOOL upload_new_variable_price_resource(
+ const LLTransactionID &tid,
+ LLAssetType::EType asset_type,
+ std::string name,
+ std::string desc,
+ LLFolderType::EType destination_folder_type,
+ LLInventoryType::EType inv_type,
+ U32 next_owner_perms,
+ U32 group_perms,
+ U32 everyone_perms,
+ const std::string& display_name,
+ const LLSD& asset_resources)
+{
+ LLAssetID uuid =
+ upload_new_resource_prep(
+ tid,
+ asset_type,
+ inv_type,
+ name,
+ display_name,
+ desc);
+
+ llinfos << "*** Uploading: " << llendl;
+ llinfos << "Type: " << LLAssetType::lookup(asset_type) << llendl;
+ llinfos << "UUID: " << uuid << llendl;
+ llinfos << "Name: " << name << llendl;
+ llinfos << "Desc: " << desc << llendl;
+ lldebugs << "Folder: "
+ << gInventory.findCategoryUUIDForType((destination_folder_type == LLFolderType::FT_NONE) ? (LLFolderType::EType)asset_type : destination_folder_type) << llendl;
+ lldebugs << "Asset Type: " << LLAssetType::lookup(asset_type) << llendl;
+
+ std::string url = gAgent.getRegion()->getCapability(
+ "NewFileAgentInventoryVariablePrice");
+
+ if ( !url.empty() )
+ {
+ lldebugs
+ << "New Agent Inventory variable price upload" << llendl;
+
+ // Each of the two capabilities has similar data, so
+ // let's reuse that code
+
+ LLSD body;
+
+ body = generate_new_resource_upload_capability_body(
+ asset_type,
+ name,
+ desc,
+ destination_folder_type,
+ inv_type,
+ next_owner_perms,
+ group_perms,
+ everyone_perms);
+
+ body["asset_resources"] = asset_resources;
+
+ LLHTTPClient::post(
+ url,
+ body,
+ new LLNewAgentInventoryVariablePriceResponder(
+ uuid,
+ asset_type,
+ body));
+
+ return TRUE;
+ }
+ else
+ {
+ return FALSE;
+ }
+}
+
+LLAssetID generate_asset_id_for_new_upload(const LLTransactionID& tid)
+{
+ if ( gDisconnected )
+ {
+ LLAssetID rv;
+
+ rv.setNull();
+ return rv;
+ }
+
+ LLAssetID uuid = tid.makeAssetID(gAgent.getSecureSessionID());
+
+ return uuid;
+}
+
+void increase_new_upload_stats(LLAssetType::EType asset_type)
+{
+ if ( LLAssetType::AT_SOUND == asset_type )
+ {
+ LLViewerStats::getInstance()->incStat(
+ LLViewerStats::ST_UPLOAD_SOUND_COUNT );
+ }
+ else if ( LLAssetType::AT_TEXTURE == asset_type )
+ {
+ LLViewerStats::getInstance()->incStat(
+ LLViewerStats::ST_UPLOAD_TEXTURE_COUNT );
+ }
+ else if ( LLAssetType::AT_ANIMATION == asset_type )
+ {
+ LLViewerStats::getInstance()->incStat(
+ LLViewerStats::ST_UPLOAD_ANIM_COUNT );
+ }
+}
+
+void assign_defaults_and_show_upload_message(
+ LLAssetType::EType asset_type,
+ LLInventoryType::EType& inventory_type,
+ std::string& name,
+ const std::string& display_name,
+ std::string& description)
+{
+ if ( LLInventoryType::IT_NONE == inventory_type )
+ {
+ inventory_type = LLInventoryType::defaultForAssetType(asset_type);
+ }
+ LLStringUtil::stripNonprintable(name);
+ LLStringUtil::stripNonprintable(description);
+
+ if ( name.empty() )
+ {
+ name = "(No Name)";
+ }
+ if ( description.empty() )
+ {
+ description = "(No Description)";
}
+
+ // At this point, we're ready for the upload.
+ std::string upload_message = "Uploading...\n\n";
+ upload_message.append(display_name);
+ LLUploadDialog::modalUploadDialog(upload_message);
}
+
void init_menu_file()
{
view_listener_t::addCommit(new LLFileUploadImage(), "File.UploadImage");
view_listener_t::addCommit(new LLFileUploadSound(), "File.UploadSound");
view_listener_t::addCommit(new LLFileUploadAnim(), "File.UploadAnim");
+ view_listener_t::addCommit(new LLFileUploadModel(), "File.UploadModel");
view_listener_t::addCommit(new LLFileUploadBulk(), "File.UploadBulk");
view_listener_t::addCommit(new LLFileCloseWindow(), "File.CloseWindow");
view_listener_t::addCommit(new LLFileCloseAllWindows(), "File.CloseAllWindows");
@@ -1042,6 +1399,9 @@ void init_menu_file()
view_listener_t::addCommit(new LLFileQuit(), "File.Quit");
view_listener_t::addEnable(new LLFileEnableUpload(), "File.EnableUpload");
-
+ view_listener_t::addEnable(new LLFileEnableUploadModel(), "File.EnableUploadModel");
+ view_listener_t::addMenu(new LLMeshEnabled(), "File.MeshEnabled");
+ view_listener_t::addMenu(new LLMeshUploadVisible(), "File.VisibleUploadModel");
+
// "File.SaveTexture" moved to llpanelmaininventory so that it can be properly handled.
}
diff --git a/indra/newview/llviewermenufile.h b/indra/newview/llviewermenufile.h
index 56b9e19049..1597821504 100644
--- a/indra/newview/llviewermenufile.h
+++ b/indra/newview/llviewermenufile.h
@@ -30,39 +30,118 @@
#include "llfoldertype.h"
#include "llassetstorage.h"
#include "llinventorytype.h"
+#include "llfilepicker.h"
class LLTransactionID;
void init_menu_file();
-void upload_new_resource(const std::string& src_filename,
- std::string name,
- std::string desc,
- S32 compression_info,
- LLFolderType::EType destination_folder_type,
- LLInventoryType::EType inv_type,
- U32 next_owner_perms,
- U32 group_perms,
- U32 everyone_perms,
- const std::string& display_name,
- LLAssetStorage::LLStoreAssetCallback callback,
- S32 expected_upload_cost,
- void *userdata);
-
-void upload_new_resource(const LLTransactionID &tid,
- LLAssetType::EType type,
- std::string name,
- std::string desc,
- S32 compression_info,
- LLFolderType::EType destination_folder_type,
- LLInventoryType::EType inv_type,
- U32 next_owner_perms,
- U32 group_perms,
- U32 everyone_perms,
- const std::string& display_name,
- LLAssetStorage::LLStoreAssetCallback callback,
- S32 expected_upload_cost,
- void *userdata);
+LLUUID upload_new_resource(
+ const std::string& src_filename,
+ std::string name,
+ std::string desc,
+ S32 compression_info,
+ LLFolderType::EType destination_folder_type,
+ LLInventoryType::EType inv_type,
+ U32 next_owner_perms,
+ U32 group_perms,
+ U32 everyone_perms,
+ const std::string& display_name,
+ LLAssetStorage::LLStoreAssetCallback callback,
+ S32 expected_upload_cost,
+ void *userdata);
+
+void upload_new_resource(
+ const LLTransactionID &tid,
+ LLAssetType::EType type,
+ std::string name,
+ std::string desc,
+ S32 compression_info,
+ LLFolderType::EType destination_folder_type,
+ LLInventoryType::EType inv_type,
+ U32 next_owner_perms,
+ U32 group_perms,
+ U32 everyone_perms,
+ const std::string& display_name,
+ LLAssetStorage::LLStoreAssetCallback callback,
+ S32 expected_upload_cost,
+ void *userdata);
+
+// TODO* : Move all uploads to use this new function
+// since at some point, that upload path will be deprecated and no longer
+// used
+
+// We make a new function here to ensure that previous code is not broken
+BOOL upload_new_variable_price_resource(
+ const LLTransactionID& tid,
+ LLAssetType::EType type,
+ std::string name,
+ std::string desc,
+ LLFolderType::EType destination_folder_type,
+ LLInventoryType::EType inv_type,
+ U32 next_owner_perms,
+ U32 group_perms,
+ U32 everyone_perms,
+ const std::string& display_name,
+ const LLSD& asset_resources);
+
+LLAssetID generate_asset_id_for_new_upload(const LLTransactionID& tid);
+void increase_new_upload_stats(LLAssetType::EType asset_type);
+void assign_defaults_and_show_upload_message(
+ LLAssetType::EType asset_type,
+ LLInventoryType::EType& inventory_type,
+ std::string& name,
+ const std::string& display_name,
+ std::string& description);
+
+LLSD generate_new_resource_upload_capability_body(
+ LLAssetType::EType asset_type,
+ const std::string& name,
+ const std::string& desc,
+ LLFolderType::EType destination_folder_type,
+ LLInventoryType::EType inv_type,
+ U32 next_owner_perms,
+ U32 group_perms,
+ U32 everyone_perms);
+
+void on_new_single_inventory_upload_complete(
+ LLAssetType::EType asset_type,
+ LLInventoryType::EType inventory_type,
+ const std::string inventory_type_string,
+ const LLUUID& item_folder_id,
+ const std::string& item_name,
+ const std::string& item_description,
+ const LLSD& server_response,
+ S32 upload_price);
+
+class LLFilePickerThread : public LLThread
+{ //multi-threaded file picker (runs system specific file picker in background and calls "notify" from main thread)
+public:
+
+ static std::queue<LLFilePickerThread*> sDeadQ;
+ static LLMutex* sMutex;
+
+ static void initClass();
+ static void cleanupClass();
+ static void clearDead();
+
+ std::string mFile;
+
+ LLFilePicker::ELoadFilter mFilter;
+
+ LLFilePickerThread(LLFilePicker::ELoadFilter filter)
+ : LLThread("file picker"), mFilter(filter)
+ {
+
+ }
+
+ void getFile();
+
+ virtual void run();
+
+ virtual void notify(const std::string& filename) = 0;
+};
+
#endif
diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp
index 8b52d478e6..bb7f6453bc 100644
--- a/indra/newview/llviewermessage.cpp
+++ b/indra/newview/llviewermessage.cpp
@@ -2804,7 +2804,7 @@ void process_improved_im(LLMessageSystem *msg, void **user_data)
{
LLVector3 pos, look_at;
U64 region_handle;
- U8 region_access = SIM_ACCESS_MIN;
+ U8 region_access;
std::string region_info = ll_safe_string((char*)binary_bucket, binary_bucket_size);
std::string region_access_str = LLStringUtil::null;
std::string region_access_icn = LLStringUtil::null;
diff --git a/indra/newview/llviewerobject.cpp b/indra/newview/llviewerobject.cpp
index 32cd8dbb39..bcdc774c5e 100644
--- a/indra/newview/llviewerobject.cpp
+++ b/indra/newview/llviewerobject.cpp
@@ -47,6 +47,7 @@
#include "llprimitive.h"
#include "llquantize.h"
#include "llregionhandle.h"
+#include "llsdserialize.h"
#include "lltree_common.h"
#include "llxfermanager.h"
#include "message.h"
@@ -62,6 +63,7 @@
#include "lldrawable.h"
#include "llface.h"
#include "llfloaterproperties.h"
+#include "llfloatertools.h"
#include "llfollowcam.h"
#include "llhudtext.h"
#include "llselectmgr.h"
@@ -202,6 +204,11 @@ LLViewerObject::LLViewerObject(const LLUUID &id, const LLPCode pcode, LLViewerRe
mGLName(0),
mbCanSelect(TRUE),
mFlags(0),
+ mPhysicsShapeType(0),
+ mPhysicsGravity(0),
+ mPhysicsFriction(0),
+ mPhysicsDensity(0),
+ mPhysicsRestitution(0),
mDrawable(),
mCreateSelected(FALSE),
mRenderMedia(FALSE),
@@ -233,6 +240,9 @@ LLViewerObject::LLViewerObject(const LLUUID &id, const LLPCode pcode, LLViewerRe
mState(0),
mMedia(NULL),
mClickAction(0),
+ mLinksetPhysicsCost(0.f),
+ mCostStale(true),
+ mPhysicsShapeUnknown(true),
mAttachmentItemID(LLUUID::null),
mLastUpdateType(OUT_UNKNOWN),
mLastUpdateCached(FALSE)
@@ -850,6 +860,13 @@ U32 LLViewerObject::processUpdateMessage(LLMessageSystem *mesgsys,
#ifdef DEBUG_UPDATE_TYPE
llinfos << "Full:" << getID() << llendl;
#endif
+ //clear cost and linkset cost
+ mCostStale = true;
+ if (isSelected())
+ {
+ gFloaterTools->dirty();
+ }
+
LLUUID audio_uuid;
LLUUID owner_id; // only valid if audio_uuid or particle system is not null
F32 gain;
@@ -1415,6 +1432,13 @@ U32 LLViewerObject::processUpdateMessage(LLMessageSystem *mesgsys,
#ifdef DEBUG_UPDATE_TYPE
llinfos << "CompFull:" << getID() << llendl;
#endif
+ mCostStale = true;
+
+ if (isSelected())
+ {
+ gFloaterTools->dirty();
+ }
+
dp->unpackU32(crc, "CRC");
mTotalCRC = crc;
dp->unpackU8(material, "Material");
@@ -3025,21 +3049,121 @@ void LLViewerObject::setScale(const LLVector3 &scale, BOOL damped)
}
}
-void LLViewerObject::updateSpatialExtents(LLVector3& newMin, LLVector3 &newMax)
+void LLViewerObject::setObjectCost(F32 cost)
+{
+ mObjectCost = cost;
+ mCostStale = false;
+
+ if (isSelected())
+ {
+ gFloaterTools->dirty();
+ }
+}
+
+void LLViewerObject::setLinksetCost(F32 cost)
+{
+ mLinksetCost = cost;
+ mCostStale = false;
+
+ if (isSelected())
+ {
+ gFloaterTools->dirty();
+ }
+}
+
+void LLViewerObject::setPhysicsCost(F32 cost)
+{
+ mPhysicsCost = cost;
+ mCostStale = false;
+
+ if (isSelected())
+ {
+ gFloaterTools->dirty();
+ }
+}
+
+void LLViewerObject::setLinksetPhysicsCost(F32 cost)
+{
+ mLinksetPhysicsCost = cost;
+ mCostStale = false;
+
+ if (isSelected())
+ {
+ gFloaterTools->dirty();
+ }
+}
+
+
+F32 LLViewerObject::getObjectCost()
+{
+ if (mCostStale)
+ {
+ gObjectList.updateObjectCost(this);
+ }
+
+ return mObjectCost;
+}
+
+F32 LLViewerObject::getLinksetCost()
+{
+ if (mCostStale)
+ {
+ gObjectList.updateObjectCost(this);
+ }
+
+ return mLinksetCost;
+}
+
+F32 LLViewerObject::getPhysicsCost()
+{
+ if (mCostStale)
+ {
+ gObjectList.updateObjectCost(this);
+ }
+
+ return mPhysicsCost;
+}
+
+F32 LLViewerObject::getLinksetPhysicsCost()
+{
+ if (mCostStale)
+ {
+ gObjectList.updateObjectCost(this);
+ }
+
+ return mLinksetPhysicsCost;
+}
+
+F32 LLViewerObject::getStreamingCost()
+{
+ return 0.f;
+}
+
+U32 LLViewerObject::getTriangleCount()
+{
+ return 0;
+}
+
+void LLViewerObject::updateSpatialExtents(LLVector4a& newMin, LLVector4a &newMax)
{
- LLVector3 center = getRenderPosition();
- LLVector3 size = getScale();
- newMin.setVec(center-size);
- newMax.setVec(center+size);
- mDrawable->setPositionGroup((newMin + newMax) * 0.5f);
+ LLVector4a center;
+ center.load3(getRenderPosition().mV);
+ LLVector4a size;
+ size.load3(getScale().mV);
+ newMin.setSub(center, size);
+ newMax.setAdd(center, size);
+
+ mDrawable->setPositionGroup(center);
}
F32 LLViewerObject::getBinRadius()
{
if (mDrawable.notNull())
{
- const LLVector3* ext = mDrawable->getSpatialExtents();
- return (ext[1]-ext[0]).magVec();
+ const LLVector4a* ext = mDrawable->getSpatialExtents();
+ LLVector4a diff;
+ diff.setSub(ext[1], ext[0]);
+ return diff.getLength3().getF32();
}
return getScale().magVec();
@@ -3105,7 +3229,7 @@ void LLViewerObject::boostTexturePriority(BOOL boost_children /* = TRUE */)
getTEImage(i)->setBoostLevel(LLViewerTexture::BOOST_SELECTED);
}
- if (isSculpted())
+ if (isSculpted() && !isMesh())
{
LLSculptParams *sculpt_params = (LLSculptParams *)getParameterEntry(LLNetworkData::PARAMS_SCULPT);
LLUUID sculpt_id = sculpt_params->getSculptTexture();
@@ -3345,6 +3469,15 @@ const LLVector3 LLViewerObject::getPositionEdit() const
const LLVector3 LLViewerObject::getRenderPosition() const
{
+ if (mDrawable.notNull() && mDrawable->isState(LLDrawable::RIGGED))
+ {
+ LLVOAvatar* avatar = getAvatar();
+ if (avatar)
+ {
+ return avatar->getPositionAgent();
+ }
+ }
+
if (mDrawable.isNull() || mDrawable->getGeneration() < 0)
{
return getPositionAgent();
@@ -3363,6 +3496,11 @@ const LLVector3 LLViewerObject::getPivotPositionAgent() const
const LLQuaternion LLViewerObject::getRenderRotation() const
{
LLQuaternion ret;
+ if (mDrawable.notNull() && mDrawable->isState(LLDrawable::RIGGED))
+ {
+ return ret;
+ }
+
if (mDrawable.isNull() || mDrawable->isStatic())
{
ret = getRotationEdit();
@@ -3631,12 +3769,21 @@ BOOL LLViewerObject::lineSegmentBoundingBox(const LLVector3& start, const LLVect
return FALSE;
}
- const LLVector3* ext = mDrawable->getSpatialExtents();
+ const LLVector4a* ext = mDrawable->getSpatialExtents();
+
+ //VECTORIZE THIS
+ LLVector4a center;
+ center.setAdd(ext[1], ext[0]);
+ center.mul(0.5f);
+ LLVector4a size;
+ size.setSub(ext[1], ext[0]);
+ size.mul(0.5f);
- LLVector3 center = (ext[1]+ext[0])*0.5f;
- LLVector3 size = (ext[1]-ext[0])*0.5f;
+ LLVector4a starta, enda;
+ starta.load3(start.mV);
+ enda.load3(end.mV);
- return LLLineSegmentBoxIntersect(start, end, center, size);
+ return LLLineSegmentBoxIntersect(starta, enda, center, size);
}
U8 LLViewerObject::getMediaType() const
@@ -5151,6 +5298,12 @@ void LLViewerObject::updateFlags()
gMessageSystem->addBOOL("IsTemporary", flagTemporaryOnRez() );
gMessageSystem->addBOOL("IsPhantom", flagPhantom() );
gMessageSystem->addBOOL("CastsShadows", flagCastShadows() );
+ gMessageSystem->nextBlock("ExtraPhysics");
+ gMessageSystem->addU8("PhysicsShapeType", getPhysicsShapeType() );
+ gMessageSystem->addF32("Density", getPhysicsDensity() );
+ gMessageSystem->addF32("Friction", getPhysicsFriction() );
+ gMessageSystem->addF32("Restitution", getPhysicsRestitution() );
+ gMessageSystem->addF32("GravityMultiplier", getPhysicsGravity() );
gMessageSystem->sendReliable( regionp->getHost() );
}
@@ -5183,6 +5336,44 @@ BOOL LLViewerObject::setFlags(U32 flags, BOOL state)
return setit;
}
+void LLViewerObject::setPhysicsShapeType(U8 type)
+{
+ mPhysicsShapeUnknown = false;
+ mPhysicsShapeType = type;
+ mCostStale = true;
+}
+
+void LLViewerObject::setPhysicsGravity(F32 gravity)
+{
+ mPhysicsGravity = gravity;
+}
+
+void LLViewerObject::setPhysicsFriction(F32 friction)
+{
+ mPhysicsFriction = friction;
+}
+
+void LLViewerObject::setPhysicsDensity(F32 density)
+{
+ mPhysicsDensity = density;
+}
+
+void LLViewerObject::setPhysicsRestitution(F32 restitution)
+{
+ mPhysicsRestitution = restitution;
+}
+
+U8 LLViewerObject::getPhysicsShapeType() const
+{
+ if (mPhysicsShapeUnknown)
+ {
+ mPhysicsShapeUnknown = false;
+ gObjectList.updatePhysicsFlags(this);
+ }
+
+ return mPhysicsShapeType;
+}
+
void LLViewerObject::applyAngularVelocity(F32 dt)
{
//do target omega here
@@ -5439,3 +5630,75 @@ const LLUUID &LLViewerObject::extractAttachmentItemID()
setAttachmentItemID(item_id);
return getAttachmentItemID();
}
+
+//virtual
+LLVOAvatar* LLViewerObject::getAvatar() const
+{
+ if (isAttachment())
+ {
+ LLViewerObject* vobj = (LLViewerObject*) getParent();
+
+ while (vobj && !vobj->asAvatar())
+ {
+ vobj = (LLViewerObject*) vobj->getParent();
+ }
+
+ return (LLVOAvatar*) vobj;
+ }
+
+ return NULL;
+}
+
+
+class ObjectPhysicsProperties : public LLHTTPNode
+{
+public:
+ virtual void post(
+ ResponsePtr responder,
+ const LLSD& context,
+ const LLSD& input) const
+ {
+ LLSD object_data = input["body"]["ObjectData"];
+ S32 num_entries = object_data.size();
+
+ for ( S32 i = 0; i < num_entries; i++ )
+ {
+ LLSD& curr_object_data = object_data[i];
+ U32 local_id = curr_object_data["LocalID"].asInteger();
+
+ // Iterate through nodes at end, since it can be on both the regular AND hover list
+ struct f : public LLSelectedNodeFunctor
+ {
+ U32 mID;
+ f(const U32& id) : mID(id) {}
+ virtual bool apply(LLSelectNode* node)
+ {
+ return (node->getObject() && node->getObject()->mLocalID == mID );
+ }
+ } func(local_id);
+
+ LLSelectNode* node = LLSelectMgr::getInstance()->getSelection()->getFirstNode(&func);
+
+ if (node)
+ {
+ // The LLSD message builder doesn't know how to handle U8, so we need to send as S8 and cast
+ U8 type = (U8)curr_object_data["PhysicsShapeType"].asInteger();
+ F32 density = (F32)curr_object_data["Density"].asReal();
+ F32 friction = (F32)curr_object_data["Friction"].asReal();
+ F32 restitution = (F32)curr_object_data["Restitution"].asReal();
+ F32 gravity = (F32)curr_object_data["GravityMultiplier"].asReal();
+
+ node->getObject()->setPhysicsShapeType(type);
+ node->getObject()->setPhysicsGravity(gravity);
+ node->getObject()->setPhysicsFriction(friction);
+ node->getObject()->setPhysicsDensity(density);
+ node->getObject()->setPhysicsRestitution(restitution);
+ }
+ }
+
+ dialog_refresh_all();
+ };
+};
+
+LLHTTPRegistration<ObjectPhysicsProperties>
+ gHTTPRegistrationObjectPhysicsProperties("/message/ObjectPhysicsProperties");
diff --git a/indra/newview/llviewerobject.h b/indra/newview/llviewerobject.h
index 7afb7f464b..2b2b7bd59d 100644
--- a/indra/newview/llviewerobject.h
+++ b/indra/newview/llviewerobject.h
@@ -176,6 +176,7 @@ public:
void setOnActiveList(BOOL on_active) { mOnActiveList = on_active; }
virtual BOOL isAttachment() const { return FALSE; }
+ virtual LLVOAvatar* getAvatar() const; //get the avatar this object is attached to, or NULL if object is not an attachment
virtual BOOL isHUDAttachment() const { return FALSE; }
virtual void updateRadius() {};
virtual F32 getVObjRadius() const; // default implemenation is mDrawable->getRadius()
@@ -224,6 +225,7 @@ public:
virtual BOOL isFlexible() const { return FALSE; }
virtual BOOL isSculpted() const { return FALSE; }
+ virtual BOOL isMesh() const { return FALSE; }
virtual BOOL hasLightTexture() const { return FALSE; }
// This method returns true if the object is over land owned by
@@ -324,6 +326,21 @@ public:
virtual void setScale(const LLVector3 &scale, BOOL damped = FALSE);
+ virtual F32 getStreamingCost();
+ virtual U32 getTriangleCount();
+
+ void setObjectCost(F32 cost);
+ F32 getObjectCost();
+
+ void setLinksetCost(F32 cost);
+ F32 getLinksetCost();
+
+ void setPhysicsCost(F32 cost);
+ F32 getPhysicsCost();
+
+ void setLinksetPhysicsCost(F32 cost);
+ F32 getLinksetPhysicsCost();
+
void sendShapeUpdate();
U8 getState() { return mState; }
@@ -363,7 +380,7 @@ public:
void markForUpdate(BOOL priority);
void updateVolume(const LLVolumeParams& volume_params);
- virtual void updateSpatialExtents(LLVector3& min, LLVector3& max);
+ virtual void updateSpatialExtents(LLVector4a& min, LLVector4a& max);
virtual F32 getBinRadius();
LLBBox getBoundingBoxAgent() const;
@@ -376,7 +393,7 @@ public:
void clearDrawableState(U32 state, BOOL recursive = TRUE);
// Called when the drawable shifts
- virtual void onShift(const LLVector3 &shift_vector) { }
+ virtual void onShift(const LLVector4a &shift_vector) { }
//////////////////////////////////////
//
@@ -451,6 +468,12 @@ public:
inline BOOL flagCameraDecoupled() const { return ((mFlags & FLAGS_CAMERA_DECOUPLED) != 0); }
inline BOOL flagObjectMove() const { return ((mFlags & FLAGS_OBJECT_MOVE) != 0); }
+ U8 getPhysicsShapeType() const;
+ inline F32 getPhysicsGravity() const { return mPhysicsGravity; }
+ inline F32 getPhysicsFriction() const { return mPhysicsFriction; }
+ inline F32 getPhysicsDensity() const { return mPhysicsDensity; }
+ inline F32 getPhysicsRestitution() const { return mPhysicsRestitution; }
+
bool getIncludeInSearch() const;
void setIncludeInSearch(bool include_in_search);
@@ -466,6 +489,11 @@ public:
void updateFlags();
BOOL setFlags(U32 flag, BOOL state);
+ void setPhysicsShapeType(U8 type);
+ void setPhysicsGravity(F32 gravity);
+ void setPhysicsFriction(F32 friction);
+ void setPhysicsDensity(F32 density);
+ void setPhysicsRestitution(F32 restitution);
virtual void dump() const;
static U32 getNumZombieObjects() { return sNumZombieObjects; }
@@ -530,6 +558,13 @@ public:
LL_VO_HUD_PART_GROUP = LL_PCODE_APP | 0xc0,
} EVOType;
+ typedef enum e_physics_shape_types
+ {
+ PHYSICS_SHAPE_PRIM = 0,
+ PHYSICS_SHAPE_NONE,
+ PHYSICS_SHAPE_CONVEX_HULL,
+ } EPhysicsShapeType;
+
LLUUID mID;
// unique within region, not unique across regions
@@ -548,6 +583,14 @@ public:
// Grabbed from UPDATE_FLAGS
U32 mFlags;
+ // Sent to sim in UPDATE_FLAGS, received in ObjectPhysicsProperties
+ U8 mPhysicsShapeType;
+ F32 mPhysicsGravity;
+ F32 mPhysicsFriction;
+ F32 mPhysicsDensity;
+ F32 mPhysicsRestitution;
+
+
// Pipeline classes
LLPointer<LLDrawable> mDrawable;
@@ -656,6 +699,13 @@ protected:
U8 mState; // legacy
LLViewerObjectMedia* mMedia; // NULL if no media associated
U8 mClickAction;
+ F32 mObjectCost; //resource cost of this object or -1 if unknown
+ F32 mLinksetCost;
+ F32 mPhysicsCost;
+ F32 mLinksetPhysicsCost;
+
+ bool mCostStale;
+ mutable bool mPhysicsShapeUnknown;
static U32 sNumZombieObjects; // Objects which are dead, but not deleted
diff --git a/indra/newview/llviewerobjectlist.cpp b/indra/newview/llviewerobjectlist.cpp
index 979d91cfcb..0071753831 100644
--- a/indra/newview/llviewerobjectlist.cpp
+++ b/indra/newview/llviewerobjectlist.cpp
@@ -54,6 +54,7 @@
#include "llviewercamera.h"
#include "llselectmgr.h"
#include "llresmgr.h"
+#include "llsdutil.h"
#include "llviewerregion.h"
#include "llviewerstats.h"
#include "llviewerstatsrecorder.h"
@@ -695,6 +696,189 @@ void LLViewerObjectList::updateApparentAngles(LLAgent &agent)
LLVOAvatar::cullAvatarsByPixelArea();
}
+class LLObjectCostResponder : public LLCurl::Responder
+{
+public:
+ LLObjectCostResponder(const LLSD& object_ids)
+ : mObjectIDs(object_ids)
+ {
+ }
+
+ // Clear's the global object list's pending
+ // request list for all objects requested
+ void clear_object_list_pending_requests()
+ {
+ // TODO*: No more hard coding
+ for (
+ LLSD::array_iterator iter = mObjectIDs.beginArray();
+ iter != mObjectIDs.endArray();
+ ++iter)
+ {
+ gObjectList.onObjectCostFetchFailure(iter->asUUID());
+ }
+ }
+
+ void error(U32 statusNum, const std::string& reason)
+ {
+ llwarns
+ << "Transport error requesting object cost "
+ << "HTTP status: " << statusNum << ", reason: "
+ << reason << "." << llendl;
+
+ // TODO*: Error message to user
+ // For now just clear the request from the pending list
+ clear_object_list_pending_requests();
+ }
+
+ void result(const LLSD& content)
+ {
+ if ( !content.isMap() || content.has("error") )
+ {
+ // Improper response or the request had an error,
+ // show an error to the user?
+ llwarns
+ << "Application level error when fetching object "
+ << "cost. Message: " << content["error"]["message"].asString()
+ << ", identifier: " << content["error"]["identifier"].asString()
+ << llendl;
+
+ // TODO*: Adaptively adjust request size if the
+ // service says we've requested too many and retry
+
+ // TODO*: Error message if not retrying
+ clear_object_list_pending_requests();
+ return;
+ }
+
+ // Success, grab the resource cost and linked set costs
+ // for an object if one was returned
+ for (
+ LLSD::array_iterator iter = mObjectIDs.beginArray();
+ iter != mObjectIDs.endArray();
+ ++iter)
+ {
+ LLUUID object_id = iter->asUUID();
+
+ // Check to see if the request contains data for the object
+ if ( content.has(iter->asString()) )
+ {
+ F32 link_cost =
+ content[iter->asString()]["linked_set_resource_cost"].asReal();
+ F32 object_cost =
+ content[iter->asString()]["resource_cost"].asReal();
+
+ F32 physics_cost = content[iter->asString()]["physics_cost"].asReal();
+ F32 link_physics_cost = content[iter->asString()]["linked_set_physics_cost"].asReal();
+
+ gObjectList.updateObjectCost(object_id, object_cost, link_cost, physics_cost, link_physics_cost);
+ }
+ else
+ {
+ // TODO*: Give user feedback about the missing data?
+ gObjectList.onObjectCostFetchFailure(object_id);
+ }
+ }
+ }
+
+private:
+ LLSD mObjectIDs;
+};
+
+
+class LLPhysicsFlagsResponder : public LLCurl::Responder
+{
+public:
+ LLPhysicsFlagsResponder(const LLSD& object_ids)
+ : mObjectIDs(object_ids)
+ {
+ }
+
+ // Clear's the global object list's pending
+ // request list for all objects requested
+ void clear_object_list_pending_requests()
+ {
+ // TODO*: No more hard coding
+ for (
+ LLSD::array_iterator iter = mObjectIDs.beginArray();
+ iter != mObjectIDs.endArray();
+ ++iter)
+ {
+ gObjectList.onPhysicsFlagsFetchFailure(iter->asUUID());
+ }
+ }
+
+ void error(U32 statusNum, const std::string& reason)
+ {
+ llwarns
+ << "Transport error requesting object physics flags "
+ << "HTTP status: " << statusNum << ", reason: "
+ << reason << "." << llendl;
+
+ // TODO*: Error message to user
+ // For now just clear the request from the pending list
+ clear_object_list_pending_requests();
+ }
+
+ void result(const LLSD& content)
+ {
+ if ( !content.isMap() || content.has("error") )
+ {
+ // Improper response or the request had an error,
+ // show an error to the user?
+ llwarns
+ << "Application level error when fetching object "
+ << "physics flags. Message: " << content["error"]["message"].asString()
+ << ", identifier: " << content["error"]["identifier"].asString()
+ << llendl;
+
+ // TODO*: Adaptively adjust request size if the
+ // service says we've requested too many and retry
+
+ // TODO*: Error message if not retrying
+ clear_object_list_pending_requests();
+ return;
+ }
+
+ // Success, grab the resource cost and linked set costs
+ // for an object if one was returned
+ for (
+ LLSD::array_iterator iter = mObjectIDs.beginArray();
+ iter != mObjectIDs.endArray();
+ ++iter)
+ {
+ LLUUID object_id = iter->asUUID();
+
+ // Check to see if the request contains data for the object
+ if ( content.has(iter->asString()) )
+ {
+ const LLSD& data = content[iter->asString()];
+
+ S32 shape_type = data["PhysicsShapeType"].asInteger();
+
+ gObjectList.updatePhysicsShapeType(object_id, shape_type);
+
+ if (data.has("Density"))
+ {
+ F32 density = data["Density"].asReal();
+ F32 friction = data["Friction"].asReal();
+ F32 restitution = data["Restitution"].asReal();
+ F32 gravity_multiplier = data["GravityMultiplier"].asReal();
+
+ gObjectList.updatePhysicsProperties(object_id,
+ density, friction, restitution, gravity_multiplier);
+ }
+ }
+ else
+ {
+ // TODO*: Give user feedback about the missing data?
+ gObjectList.onPhysicsFlagsFetchFailure(object_id);
+ }
+ }
+ }
+
+private:
+ LLSD mObjectIDs;
+};
void LLViewerObjectList::update(LLAgent &agent, LLWorld &world)
{
@@ -807,6 +991,9 @@ void LLViewerObjectList::update(LLAgent &agent, LLWorld &world)
}
}
+ fetchObjectCosts();
+ fetchPhysicsFlags();
+
mNumSizeCulled = 0;
mNumVisCulled = 0;
@@ -872,6 +1059,119 @@ void LLViewerObjectList::update(LLAgent &agent, LLWorld &world)
LLViewerStats::getInstance()->mNumVisCulledStat.addValue(mNumVisCulled);
}
+void LLViewerObjectList::fetchObjectCosts()
+{
+ // issue http request for stale object physics costs
+ if (!mStaleObjectCost.empty())
+ {
+ LLViewerRegion* regionp = gAgent.getRegion();
+
+ if (regionp)
+ {
+ std::string url = regionp->getCapability("GetObjectCost");
+
+ if (!url.empty())
+ {
+ LLSD id_list;
+ U32 object_index = 0;
+
+ for (
+ std::set<LLUUID>::iterator iter = mStaleObjectCost.begin();
+ iter != mStaleObjectCost.end();
+ ++iter)
+ {
+ // Check to see if a request for this object
+ // has already been made.
+ if ( mPendingObjectCost.find(*iter) ==
+ mPendingObjectCost.end() )
+ {
+ mPendingObjectCost.insert(*iter);
+ id_list[object_index++] = *iter;
+ }
+ }
+
+ // id_list should now contain all
+ // requests in mStaleObjectCost before, so clear
+ // it now
+ mStaleObjectCost.clear();
+
+ if ( id_list.size() > 0 )
+ {
+ LLSD post_data = LLSD::emptyMap();
+
+ post_data["object_ids"] = id_list;
+ LLHTTPClient::post(
+ url,
+ post_data,
+ new LLObjectCostResponder(id_list));
+ }
+ }
+ else
+ {
+ mStaleObjectCost.clear();
+ mPendingObjectCost.clear();
+ }
+ }
+ }
+}
+
+void LLViewerObjectList::fetchPhysicsFlags()
+{
+ // issue http request for stale object physics flags
+ if (!mStalePhysicsFlags.empty())
+ {
+ LLViewerRegion* regionp = gAgent.getRegion();
+
+ if (regionp)
+ {
+ std::string url = regionp->getCapability("GetObjectPhysicsData");
+
+ if (!url.empty())
+ {
+ LLSD id_list;
+ U32 object_index = 0;
+
+ for (
+ std::set<LLUUID>::iterator iter = mStalePhysicsFlags.begin();
+ iter != mStalePhysicsFlags.end();
+ ++iter)
+ {
+ // Check to see if a request for this object
+ // has already been made.
+ if ( mPendingPhysicsFlags.find(*iter) ==
+ mPendingPhysicsFlags.end() )
+ {
+ mPendingPhysicsFlags.insert(*iter);
+ id_list[object_index++] = *iter;
+ }
+ }
+
+ // id_list should now contain all
+ // requests in mStalePhysicsFlags before, so clear
+ // it now
+ mStalePhysicsFlags.clear();
+
+ if ( id_list.size() > 0 )
+ {
+ LLSD post_data = LLSD::emptyMap();
+
+ post_data["object_ids"] = id_list;
+ LLHTTPClient::post(
+ url,
+ post_data,
+ new LLPhysicsFlagsResponder(id_list));
+ }
+ }
+ else
+ {
+ mStalePhysicsFlags.clear();
+ mPendingPhysicsFlags.clear();
+ }
+ }
+ }
+}
+
+
void LLViewerObjectList::clearDebugText()
{
for (vobj_list_t::iterator iter = mObjects.begin(); iter != mObjects.end(); ++iter)
@@ -926,8 +1226,12 @@ void LLViewerObjectList::cleanupReferences(LLViewerObject *objectp)
mNumDeadObjects++;
}
+static LLFastTimer::DeclareTimer FTM_REMOVE_DRAWABLE("Remove Drawable");
+
void LLViewerObjectList::removeDrawable(LLDrawable* drawablep)
{
+ LLFastTimer t(FTM_REMOVE_DRAWABLE);
+
if (!drawablep)
{
return;
@@ -1092,7 +1396,69 @@ void LLViewerObjectList::updateActive(LLViewerObject *objectp)
}
}
+void LLViewerObjectList::updateObjectCost(LLViewerObject* object)
+{
+ mStaleObjectCost.insert(object->getID());
+}
+
+void LLViewerObjectList::updateObjectCost(const LLUUID& object_id, F32 object_cost, F32 link_cost, F32 physics_cost, F32 link_physics_cost)
+{
+ mPendingObjectCost.erase(object_id);
+ LLViewerObject* object = findObject(object_id);
+ if (object)
+ {
+ object->setObjectCost(object_cost);
+ object->setLinksetCost(link_cost);
+ object->setPhysicsCost(physics_cost);
+ object->setLinksetPhysicsCost(link_physics_cost);
+ }
+}
+
+void LLViewerObjectList::onObjectCostFetchFailure(const LLUUID& object_id)
+{
+ //llwarns << "Failed to fetch object cost for object: " << object_id << llendl;
+ mPendingObjectCost.erase(object_id);
+}
+
+void LLViewerObjectList::updatePhysicsFlags(const LLViewerObject* object)
+{
+ mStalePhysicsFlags.insert(object->getID());
+}
+
+void LLViewerObjectList::updatePhysicsShapeType(const LLUUID& object_id, S32 type)
+{
+ mPendingPhysicsFlags.erase(object_id);
+ LLViewerObject* object = findObject(object_id);
+ if (object)
+ {
+ object->setPhysicsShapeType(type);
+ }
+}
+
+void LLViewerObjectList::updatePhysicsProperties(const LLUUID& object_id,
+ F32 density,
+ F32 friction,
+ F32 restitution,
+ F32 gravity_multiplier)
+{
+ mPendingPhysicsFlags.erase(object_id);
+
+ LLViewerObject* object = findObject(object_id);
+ if (object)
+ {
+ object->setPhysicsDensity(density);
+ object->setPhysicsFriction(friction);
+ object->setPhysicsGravity(gravity_multiplier);
+ object->setPhysicsRestitution(restitution);
+ }
+}
+
+void LLViewerObjectList::onPhysicsFlagsFetchFailure(const LLUUID& object_id)
+{
+ //llwarns << "Failed to fetch physics flags for object: " << object_id << llendl;
+ mPendingPhysicsFlags.erase(object_id);
+}
void LLViewerObjectList::shiftObjects(const LLVector3 &offset)
{
diff --git a/indra/newview/llviewerobjectlist.h b/indra/newview/llviewerobjectlist.h
index 22a7f97c38..65374bca70 100644
--- a/indra/newview/llviewerobjectlist.h
+++ b/indra/newview/llviewerobjectlist.h
@@ -85,6 +85,22 @@ public:
void updateApparentAngles(LLAgent &agent);
void update(LLAgent &agent, LLWorld &world);
+ void fetchObjectCosts();
+ void fetchPhysicsFlags();
+
+ void updateObjectCost(LLViewerObject* object);
+ void updateObjectCost(const LLUUID& object_id, F32 object_cost, F32 link_cost, F32 physics_cost, F32 link_physics_cost);
+ void onObjectCostFetchFailure(const LLUUID& object_id);
+
+ void updatePhysicsFlags(const LLViewerObject* object);
+ void onPhysicsFlagsFetchFailure(const LLUUID& object_id);
+ void updatePhysicsShapeType(const LLUUID& object_id, S32 type);
+ void updatePhysicsProperties(const LLUUID& object_id,
+ F32 density,
+ F32 friction,
+ F32 restitution,
+ F32 gravity_multiplier);
+
void shiftObjects(const LLVector3 &offset);
bool hasMapObjectInRegion(LLViewerRegion* regionp) ;
@@ -186,6 +202,14 @@ protected:
std::map<LLUUID, LLPointer<LLViewerObject> > mUUIDObjectMap;
+ //set of objects that need to update their cost
+ std::set<LLUUID> mStaleObjectCost;
+ std::set<LLUUID> mPendingObjectCost;
+
+ //set of objects that need to update their physics flags
+ std::set<LLUUID> mStalePhysicsFlags;
+ std::set<LLUUID> mPendingPhysicsFlags;
+
std::vector<LLDebugBeacon> mDebugBeacons;
S32 mCurLazyUpdateIndex;
diff --git a/indra/newview/llviewerpartsim.cpp b/indra/newview/llviewerpartsim.cpp
index 4fee85e45c..6b3e04348a 100644
--- a/indra/newview/llviewerpartsim.cpp
+++ b/indra/newview/llviewerpartsim.cpp
@@ -155,8 +155,8 @@ LLViewerPartGroup::LLViewerPartGroup(const LLVector3 &center_agent, const F32 bo
if (group != NULL)
{
- LLVector3 center(group->mOctreeNode->getCenter());
- LLVector3 size(group->mOctreeNode->getSize());
+ LLVector3 center(group->mOctreeNode->getCenter().getF32ptr());
+ LLVector3 size(group->mOctreeNode->getSize().getF32ptr());
size += LLVector3(0.01f, 0.01f, 0.01f);
mMinObjPos = center - size;
mMaxObjPos = center + size;
diff --git a/indra/newview/llviewerregion.cpp b/indra/newview/llviewerregion.cpp
index e1d3e8a0b3..dc0ee88554 100644
--- a/indra/newview/llviewerregion.cpp
+++ b/indra/newview/llviewerregion.cpp
@@ -1085,32 +1085,35 @@ LLViewerRegion::eCacheUpdateResult LLViewerRegion::cacheFullUpdate(LLViewerObjec
// AND the CRC matches. JC
LLDataPacker *LLViewerRegion::getDP(U32 local_id, U32 crc, U8 &cache_miss_type)
{
- llassert(mCacheLoaded);
+ //llassert(mCacheLoaded); This assert failes often, changing to early-out -- davep, 2010/10/18
- LLVOCacheEntry* entry = get_if_there(mCacheMap, local_id, (LLVOCacheEntry*)NULL);
-
- if (entry)
+ if (mCacheLoaded)
{
- // we've seen this object before
- if (entry->getCRC() == crc)
+ LLVOCacheEntry* entry = get_if_there(mCacheMap, local_id, (LLVOCacheEntry*)NULL);
+
+ if (entry)
{
- // Record a hit
- entry->recordHit();
+ // we've seen this object before
+ if (entry->getCRC() == crc)
+ {
+ // Record a hit
+ entry->recordHit();
cache_miss_type = CACHE_MISS_TYPE_NONE;
- return entry->getDP(crc);
+ return entry->getDP(crc);
+ }
+ else
+ {
+ // llinfos << "CRC miss for " << local_id << llendl;
+ cache_miss_type = CACHE_MISS_TYPE_CRC;
+ mCacheMissCRC.put(local_id);
+ }
}
else
{
- // llinfos << "CRC miss for " << local_id << llendl;
- cache_miss_type = CACHE_MISS_TYPE_CRC;
- mCacheMissCRC.put(local_id);
- }
- }
- else
- {
- // llinfos << "Cache miss for " << local_id << llendl;
+ // llinfos << "Cache miss for " << local_id << llendl;
cache_miss_type = CACHE_MISS_TYPE_FULL;
- mCacheMissFull.put(local_id);
+ mCacheMissFull.put(local_id);
+ }
}
return NULL;
}
@@ -1399,12 +1402,17 @@ void LLViewerRegion::setSeedCapability(const std::string& url)
capabilityNames.append("GetDisplayNames");
capabilityNames.append("GetTexture");
+ capabilityNames.append("GetMesh");
+ capabilityNames.append("GetObjectCost");
+ capabilityNames.append("GetObjectPhysicsData");
capabilityNames.append("GroupProposalBallot");
capabilityNames.append("HomeLocation");
capabilityNames.append("LandResources");
capabilityNames.append("MapLayer");
capabilityNames.append("MapLayerGod");
capabilityNames.append("NewFileAgentInventory");
+ capabilityNames.append("NewFileAgentInventoryVariablePrice");
+ capabilityNames.append("ObjectAdd");
capabilityNames.append("ParcelPropertiesUpdate");
capabilityNames.append("ParcelMediaURLFilterList");
capabilityNames.append("ParcelNavigateMedia");
@@ -1419,6 +1427,8 @@ void LLViewerRegion::setSeedCapability(const std::string& url)
capabilityNames.append("SendUserReport");
capabilityNames.append("SendUserReportWithScreenshot");
capabilityNames.append("ServerReleaseNotes");
+ capabilityNames.append("SimConsole");
+ capabilityNames.append("SimulatorFeatures");
capabilityNames.append("SetDisplayName");
capabilityNames.append("SimConsoleAsync");
capabilityNames.append("StartGroupProposal");
@@ -1433,6 +1443,7 @@ void LLViewerRegion::setSeedCapability(const std::string& url)
capabilityNames.append("UpdateNotecardTaskInventory");
capabilityNames.append("UpdateScriptTask");
capabilityNames.append("UploadBakedTexture");
+ capabilityNames.append("UploadObjectAsset");
capabilityNames.append("ViewerMetrics");
capabilityNames.append("ViewerStartAuction");
capabilityNames.append("ViewerStats");
@@ -1479,6 +1490,7 @@ std::string LLViewerRegion::getCapability(const std::string& name) const
{
return "";
}
+
return iter->second;
}
diff --git a/indra/newview/llviewershadermgr.cpp b/indra/newview/llviewershadermgr.cpp
index c1abead36e..25cf63a367 100644
--- a/indra/newview/llviewershadermgr.cpp
+++ b/indra/newview/llviewershadermgr.cpp
@@ -68,9 +68,21 @@ LLGLSLShader gObjectFullbrightProgram;
LLGLSLShader gObjectFullbrightWaterProgram;
LLGLSLShader gObjectFullbrightShinyProgram;
+LLGLSLShader gObjectFullbrightShinyWaterProgram;
LLGLSLShader gObjectShinyProgram;
LLGLSLShader gObjectShinyWaterProgram;
+//object hardware skinning shaders
+LLGLSLShader gSkinnedObjectSimpleProgram;
+LLGLSLShader gSkinnedObjectFullbrightProgram;
+LLGLSLShader gSkinnedObjectFullbrightShinyProgram;
+LLGLSLShader gSkinnedObjectShinySimpleProgram;
+
+LLGLSLShader gSkinnedObjectSimpleWaterProgram;
+LLGLSLShader gSkinnedObjectFullbrightWaterProgram;
+LLGLSLShader gSkinnedObjectFullbrightShinyWaterProgram;
+LLGLSLShader gSkinnedObjectShinySimpleWaterProgram;
+
//environment shaders
LLGLSLShader gTerrainProgram;
LLGLSLShader gTerrainWaterProgram;
@@ -101,6 +113,9 @@ LLGLSLShader gDeferredImpostorProgram;
LLGLSLShader gDeferredEdgeProgram;
LLGLSLShader gDeferredWaterProgram;
LLGLSLShader gDeferredDiffuseProgram;
+LLGLSLShader gDeferredSkinnedDiffuseProgram;
+LLGLSLShader gDeferredSkinnedBumpProgram;
+LLGLSLShader gDeferredSkinnedAlphaProgram;
LLGLSLShader gDeferredBumpProgram;
LLGLSLShader gDeferredTerrainProgram;
LLGLSLShader gDeferredTreeProgram;
@@ -115,6 +130,7 @@ LLGLSLShader gDeferredBlurLightProgram;
LLGLSLShader gDeferredSoftenProgram;
LLGLSLShader gDeferredShadowProgram;
LLGLSLShader gDeferredAvatarShadowProgram;
+LLGLSLShader gDeferredAttachmentShadowProgram;
LLGLSLShader gDeferredAlphaProgram;
LLGLSLShader gDeferredFullbrightProgram;
LLGLSLShader gDeferredGIProgram;
@@ -142,6 +158,15 @@ LLViewerShaderMgr::LLViewerShaderMgr() :
mShaderList.push_back(&gObjectSimpleProgram);
mShaderList.push_back(&gObjectFullbrightProgram);
mShaderList.push_back(&gObjectFullbrightShinyProgram);
+ mShaderList.push_back(&gObjectFullbrightShinyWaterProgram);
+ mShaderList.push_back(&gSkinnedObjectSimpleProgram);
+ mShaderList.push_back(&gSkinnedObjectFullbrightProgram);
+ mShaderList.push_back(&gSkinnedObjectFullbrightShinyProgram);
+ mShaderList.push_back(&gSkinnedObjectShinySimpleProgram);
+ mShaderList.push_back(&gSkinnedObjectSimpleWaterProgram);
+ mShaderList.push_back(&gSkinnedObjectFullbrightWaterProgram);
+ mShaderList.push_back(&gSkinnedObjectFullbrightShinyWaterProgram);
+ mShaderList.push_back(&gSkinnedObjectShinySimpleWaterProgram);
mShaderList.push_back(&gTerrainProgram);
mShaderList.push_back(&gTerrainWaterProgram);
mShaderList.push_back(&gObjectSimpleWaterProgram);
@@ -155,6 +180,7 @@ LLViewerShaderMgr::LLViewerShaderMgr() :
mShaderList.push_back(&gDeferredLightProgram);
mShaderList.push_back(&gDeferredMultiLightProgram);
mShaderList.push_back(&gDeferredAlphaProgram);
+ mShaderList.push_back(&gDeferredSkinnedAlphaProgram);
mShaderList.push_back(&gDeferredFullbrightProgram);
mShaderList.push_back(&gDeferredPostGIProgram);
mShaderList.push_back(&gDeferredEdgeProgram);
@@ -189,6 +215,7 @@ void LLViewerShaderMgr::initAttribsAndUniforms(void)
mReservedAttribs.push_back("materialColor");
mReservedAttribs.push_back("specularColor");
mReservedAttribs.push_back("binormal");
+ mReservedAttribs.push_back("object_weight");
mAvatarAttribs.reserve(5);
mAvatarAttribs.push_back("weight");
@@ -370,7 +397,9 @@ void LLViewerShaderMgr::setShaders()
S32 deferred_class = 0;
if (LLFeatureManager::getInstance()->isFeatureAvailable("RenderDeferred") &&
- gSavedSettings.getBOOL("RenderDeferred"))
+ gSavedSettings.getBOOL("RenderDeferred") &&
+ gSavedSettings.getBOOL("RenderAvatarVP") &&
+ gSavedSettings.getBOOL("WindLightUseAtmosShaders"))
{
if (gSavedSettings.getS32("RenderShadowDetail") > 0)
{
@@ -388,14 +417,11 @@ void LLViewerShaderMgr::setShaders()
deferred_class = 1;
}
- //make sure framebuffer objects are enabled
- gSavedSettings.setBOOL("RenderUseFBO", TRUE);
-
//make sure hardware skinning is enabled
- gSavedSettings.setBOOL("RenderAvatarVP", TRUE);
+ //gSavedSettings.setBOOL("RenderAvatarVP", TRUE);
//make sure atmospheric shaders are enabled
- gSavedSettings.setBOOL("WindLightUseAtmosShaders", TRUE);
+ //gSavedSettings.setBOOL("WindLightUseAtmosShaders", TRUE);
}
@@ -438,7 +464,6 @@ void LLViewerShaderMgr::setShaders()
// Load all shaders to set max levels
loadShadersEnvironment();
loadShadersWater();
- loadShadersObject();
loadShadersWindLight();
loadShadersEffects();
loadShadersInterface();
@@ -446,14 +471,9 @@ void LLViewerShaderMgr::setShaders()
// Load max avatar shaders to set the max level
mVertexShaderLevel[SHADER_AVATAR] = 3;
mMaxAvatarShaderLevel = 3;
- loadShadersAvatar();
-
-#if 0 && LL_DARWIN // force avatar shaders off for mac
- mVertexShaderLevel[SHADER_AVATAR] = 0;
- sMaxAvatarShaderLevel = 0;
-#else
- if (gSavedSettings.getBOOL("RenderAvatarVP"))
- {
+
+ if (gSavedSettings.getBOOL("RenderAvatarVP") && loadShadersObject())
+ { //hardware skinning is enabled and rigged attachment shaders loaded correctly
BOOL avatar_cloth = gSavedSettings.getBOOL("RenderAvatarCloth");
S32 avatar_class = 1;
@@ -484,17 +504,28 @@ void LLViewerShaderMgr::setShaders()
}
}
else
- {
+ { //hardware skinning not possible, neither is deferred rendering
mVertexShaderLevel[SHADER_AVATAR] = 0;
- gSavedSettings.setBOOL("RenderAvatarCloth", FALSE);
+ mVertexShaderLevel[SHADER_DEFERRED] = 0;
+
+ if (gSavedSettings.getBOOL("RenderAvatarVP"))
+ {
+ gSavedSettings.setBOOL("RenderDeferred", FALSE);
+ gSavedSettings.setBOOL("RenderAvatarCloth", FALSE);
+ gSavedSettings.setBOOL("RenderAvatarVP", FALSE);
+ }
+
loadShadersAvatar(); // unloads
+ loadShadersObject();
}
if (!loadShadersDeferred())
{
gSavedSettings.setBOOL("RenderDeferred", FALSE);
+ reentrance = false;
+ setShaders();
+ return;
}
-#endif
}
else
{
@@ -542,7 +573,20 @@ void LLViewerShaderMgr::unloadShaders()
gObjectShinyProgram.unload();
gObjectFullbrightShinyProgram.unload();
+ gObjectFullbrightShinyWaterProgram.unload();
gObjectShinyWaterProgram.unload();
+
+ gSkinnedObjectSimpleProgram.unload();
+ gSkinnedObjectFullbrightProgram.unload();
+ gSkinnedObjectFullbrightShinyProgram.unload();
+ gSkinnedObjectShinySimpleProgram.unload();
+
+ gSkinnedObjectSimpleWaterProgram.unload();
+ gSkinnedObjectFullbrightWaterProgram.unload();
+ gSkinnedObjectFullbrightShinyWaterProgram.unload();
+ gSkinnedObjectShinySimpleWaterProgram.unload();
+
+
gWaterProgram.unload();
gUnderWaterProgram.unload();
gTerrainProgram.unload();
@@ -562,6 +606,9 @@ void LLViewerShaderMgr::unloadShaders()
gPostNightVisionProgram.unload();
gDeferredDiffuseProgram.unload();
+ gDeferredSkinnedDiffuseProgram.unload();
+ gDeferredSkinnedBumpProgram.unload();
+ gDeferredSkinnedAlphaProgram.unload();
mVertexShaderLevel[SHADER_LIGHTING] = 0;
mVertexShaderLevel[SHADER_OBJECT] = 0;
@@ -620,6 +667,7 @@ BOOL LLViewerShaderMgr::loadBasicShaders()
shaders.push_back( make_pair( "lighting/lightSpecularV.glsl", mVertexShaderLevel[SHADER_LIGHTING] ) );
shaders.push_back( make_pair( "windlight/atmosphericsV.glsl", mVertexShaderLevel[SHADER_WINDLIGHT] ) );
shaders.push_back( make_pair( "avatar/avatarSkinV.glsl", 1 ) );
+ shaders.push_back( make_pair( "avatar/objectSkinV.glsl", 1 ) );
// We no longer have to bind the shaders to global glhandles, they are automatically added to a map now.
for (U32 i = 0; i < shaders.size(); i++)
@@ -635,7 +683,7 @@ BOOL LLViewerShaderMgr::loadBasicShaders()
// (in order of shader function call depth for reference purposes, deepest level first)
shaders.clear();
- shaders.reserve(12);
+ shaders.reserve(13);
shaders.push_back( make_pair( "windlight/atmosphericsVarsF.glsl", mVertexShaderLevel[SHADER_WINDLIGHT] ) );
shaders.push_back( make_pair( "windlight/gammaF.glsl", mVertexShaderLevel[SHADER_WINDLIGHT]) );
shaders.push_back( make_pair( "windlight/atmosphericsF.glsl", mVertexShaderLevel[SHADER_WINDLIGHT] ) );
@@ -648,6 +696,7 @@ BOOL LLViewerShaderMgr::loadBasicShaders()
shaders.push_back( make_pair( "lighting/lightShinyF.glsl", mVertexShaderLevel[SHADER_LIGHTING] ) );
shaders.push_back( make_pair( "lighting/lightFullbrightShinyF.glsl", mVertexShaderLevel[SHADER_LIGHTING] ) );
shaders.push_back( make_pair( "lighting/lightShinyWaterF.glsl", mVertexShaderLevel[SHADER_LIGHTING] ) );
+ shaders.push_back( make_pair( "lighting/lightFullbrightShinyWaterF.glsl", mVertexShaderLevel[SHADER_LIGHTING] ) );
for (U32 i = 0; i < shaders.size(); i++)
{
@@ -875,6 +924,9 @@ BOOL LLViewerShaderMgr::loadShadersDeferred()
{
gDeferredTreeProgram.unload();
gDeferredDiffuseProgram.unload();
+ gDeferredSkinnedDiffuseProgram.unload();
+ gDeferredSkinnedBumpProgram.unload();
+ gDeferredSkinnedAlphaProgram.unload();
gDeferredBumpProgram.unload();
gDeferredImpostorProgram.unload();
gDeferredTerrainProgram.unload();
@@ -887,6 +939,7 @@ BOOL LLViewerShaderMgr::loadShadersDeferred()
gDeferredSoftenProgram.unload();
gDeferredShadowProgram.unload();
gDeferredAvatarShadowProgram.unload();
+ gDeferredAttachmentShadowProgram.unload();
gDeferredAvatarProgram.unload();
gDeferredAvatarAlphaProgram.unload();
gDeferredAlphaProgram.unload();
@@ -898,7 +951,7 @@ BOOL LLViewerShaderMgr::loadShadersDeferred()
gDeferredGIProgram.unload();
gDeferredGIFinalProgram.unload();
gDeferredWaterProgram.unload();
- return FALSE;
+ return TRUE;
}
mVertexShaderLevel[SHADER_AVATAR] = 1;
@@ -917,6 +970,44 @@ BOOL LLViewerShaderMgr::loadShadersDeferred()
if (success)
{
+ gDeferredSkinnedDiffuseProgram.mName = "Deferred Skinned Diffuse Shader";
+ gDeferredSkinnedDiffuseProgram.mFeatures.hasObjectSkinning = true;
+ gDeferredSkinnedDiffuseProgram.mShaderFiles.clear();
+ gDeferredSkinnedDiffuseProgram.mShaderFiles.push_back(make_pair("deferred/diffuseSkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gDeferredSkinnedDiffuseProgram.mShaderFiles.push_back(make_pair("deferred/diffuseF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gDeferredSkinnedDiffuseProgram.mShaderLevel = mVertexShaderLevel[SHADER_DEFERRED];
+ success = gDeferredSkinnedDiffuseProgram.createShader(NULL, NULL);
+ }
+
+ if (success)
+ {
+ gDeferredSkinnedBumpProgram.mName = "Deferred Skinned Bump Shader";
+ gDeferredSkinnedBumpProgram.mFeatures.hasObjectSkinning = true;
+ gDeferredSkinnedBumpProgram.mShaderFiles.clear();
+ gDeferredSkinnedBumpProgram.mShaderFiles.push_back(make_pair("deferred/bumpSkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gDeferredSkinnedBumpProgram.mShaderFiles.push_back(make_pair("deferred/bumpF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gDeferredSkinnedBumpProgram.mShaderLevel = mVertexShaderLevel[SHADER_DEFERRED];
+ success = gDeferredSkinnedBumpProgram.createShader(NULL, NULL);
+ }
+
+ if (success)
+ {
+ gDeferredSkinnedAlphaProgram.mName = "Deferred Skinned Alpha Shader";
+ gDeferredSkinnedAlphaProgram.mFeatures.hasObjectSkinning = true;
+ gDeferredSkinnedAlphaProgram.mFeatures.calculatesLighting = true;
+ gDeferredSkinnedAlphaProgram.mFeatures.calculatesAtmospherics = true;
+ gDeferredSkinnedAlphaProgram.mFeatures.hasGamma = true;
+ gDeferredSkinnedAlphaProgram.mFeatures.hasAtmospherics = true;
+ gDeferredSkinnedAlphaProgram.mFeatures.hasLighting = true;
+ gDeferredSkinnedAlphaProgram.mShaderFiles.clear();
+ gDeferredSkinnedAlphaProgram.mShaderFiles.push_back(make_pair("deferred/alphaSkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gDeferredSkinnedAlphaProgram.mShaderFiles.push_back(make_pair("deferred/alphaF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gDeferredSkinnedAlphaProgram.mShaderLevel = mVertexShaderLevel[SHADER_DEFERRED];
+ success = gDeferredSkinnedAlphaProgram.createShader(NULL, NULL);
+ }
+
+ if (success)
+ {
gDeferredBumpProgram.mName = "Deferred Bump Shader";
gDeferredBumpProgram.mShaderFiles.clear();
gDeferredBumpProgram.mShaderFiles.push_back(make_pair("deferred/bumpV.glsl", GL_VERTEX_SHADER_ARB));
@@ -1065,7 +1156,14 @@ BOOL LLViewerShaderMgr::loadShadersDeferred()
gDeferredSoftenProgram.mShaderFiles.clear();
gDeferredSoftenProgram.mShaderFiles.push_back(make_pair("deferred/softenLightV.glsl", GL_VERTEX_SHADER_ARB));
gDeferredSoftenProgram.mShaderFiles.push_back(make_pair("deferred/softenLightF.glsl", GL_FRAGMENT_SHADER_ARB));
+
gDeferredSoftenProgram.mShaderLevel = mVertexShaderLevel[SHADER_DEFERRED];
+
+ if (gSavedSettings.getBOOL("RenderDeferredSSAO"))
+ { //if using SSAO, take screen space light map into account as if shadows are enabled
+ gDeferredSoftenProgram.mShaderLevel = llmax(gDeferredSoftenProgram.mShaderLevel, 2);
+ }
+
success = gDeferredSoftenProgram.createShader(NULL, NULL);
}
@@ -1092,6 +1190,17 @@ BOOL LLViewerShaderMgr::loadShadersDeferred()
if (success)
{
+ gDeferredAttachmentShadowProgram.mName = "Deferred Attachment Shadow Shader";
+ gDeferredAttachmentShadowProgram.mFeatures.hasObjectSkinning = true;
+ gDeferredAttachmentShadowProgram.mShaderFiles.clear();
+ gDeferredAttachmentShadowProgram.mShaderFiles.push_back(make_pair("deferred/attachmentShadowV.glsl", GL_VERTEX_SHADER_ARB));
+ gDeferredAttachmentShadowProgram.mShaderFiles.push_back(make_pair("deferred/attachmentShadowF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gDeferredAttachmentShadowProgram.mShaderLevel = mVertexShaderLevel[SHADER_DEFERRED];
+ success = gDeferredAttachmentShadowProgram.createShader(NULL, NULL);
+ }
+
+ if (success)
+ {
gTerrainProgram.mName = "Deferred Terrain Shader";
gDeferredTerrainProgram.mShaderFiles.clear();
gDeferredTerrainProgram.mShaderFiles.push_back(make_pair("deferred/terrainV.glsl", GL_VERTEX_SHADER_ARB));
@@ -1122,11 +1231,21 @@ BOOL LLViewerShaderMgr::loadShadersDeferred()
gDeferredAvatarAlphaProgram.mFeatures.hasLighting = true;
gDeferredAvatarAlphaProgram.mShaderFiles.clear();
gDeferredAvatarAlphaProgram.mShaderFiles.push_back(make_pair("deferred/avatarAlphaV.glsl", GL_VERTEX_SHADER_ARB));
- gDeferredAvatarAlphaProgram.mShaderFiles.push_back(make_pair("deferred/avatarAlphaF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gDeferredAvatarAlphaProgram.mShaderFiles.push_back(make_pair("deferred/alphaF.glsl", GL_FRAGMENT_SHADER_ARB));
gDeferredAvatarAlphaProgram.mShaderLevel = mVertexShaderLevel[SHADER_DEFERRED];
success = gDeferredAvatarAlphaProgram.createShader(&mAvatarAttribs, &mAvatarUniforms);
}
+ if (success)
+ {
+ gDeferredPostProgram.mName = "Deferred Post Shader";
+ gDeferredPostProgram.mShaderFiles.clear();
+ gDeferredPostProgram.mShaderFiles.push_back(make_pair("deferred/postDeferredV.glsl", GL_VERTEX_SHADER_ARB));
+ gDeferredPostProgram.mShaderFiles.push_back(make_pair("deferred/postDeferredF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gDeferredPostProgram.mShaderLevel = mVertexShaderLevel[SHADER_DEFERRED];
+ success = gDeferredPostProgram.createShader(NULL, NULL);
+ }
+
if (mVertexShaderLevel[SHADER_DEFERRED] > 1)
{
if (success)
@@ -1142,15 +1261,7 @@ BOOL LLViewerShaderMgr::loadShadersDeferred()
if (mVertexShaderLevel[SHADER_DEFERRED] > 2)
{
- if (success)
- {
- gDeferredPostProgram.mName = "Deferred Post Shader";
- gDeferredPostProgram.mShaderFiles.clear();
- gDeferredPostProgram.mShaderFiles.push_back(make_pair("deferred/postDeferredV.glsl", GL_VERTEX_SHADER_ARB));
- gDeferredPostProgram.mShaderFiles.push_back(make_pair("deferred/postDeferredF.glsl", GL_FRAGMENT_SHADER_ARB));
- gDeferredPostProgram.mShaderLevel = mVertexShaderLevel[SHADER_DEFERRED];
- success = gDeferredPostProgram.createShader(NULL, NULL);
- }
+
if (success)
{
@@ -1204,12 +1315,22 @@ BOOL LLViewerShaderMgr::loadShadersObject()
{
gObjectShinyProgram.unload();
gObjectFullbrightShinyProgram.unload();
+ gObjectFullbrightShinyWaterProgram.unload();
gObjectShinyWaterProgram.unload();
gObjectSimpleProgram.unload();
gObjectSimpleWaterProgram.unload();
gObjectFullbrightProgram.unload();
gObjectFullbrightWaterProgram.unload();
- return FALSE;
+ gSkinnedObjectSimpleProgram.unload();
+ gSkinnedObjectFullbrightProgram.unload();
+ gSkinnedObjectFullbrightShinyProgram.unload();
+ gSkinnedObjectShinySimpleProgram.unload();
+ gSkinnedObjectSimpleWaterProgram.unload();
+ gSkinnedObjectFullbrightWaterProgram.unload();
+ gSkinnedObjectFullbrightShinyWaterProgram.unload();
+ gSkinnedObjectShinySimpleWaterProgram.unload();
+
+ return TRUE;
}
if (success)
@@ -1318,6 +1439,159 @@ BOOL LLViewerShaderMgr::loadShadersObject()
success = gObjectFullbrightShinyProgram.createShader(NULL, &mShinyUniforms);
}
+ if (success)
+ {
+ gObjectFullbrightShinyWaterProgram.mName = "Fullbright Shiny Water Shader";
+ gObjectFullbrightShinyWaterProgram.mFeatures.calculatesAtmospherics = true;
+ gObjectFullbrightShinyWaterProgram.mFeatures.isFullbright = true;
+ gObjectFullbrightShinyWaterProgram.mFeatures.isShiny = true;
+ gObjectFullbrightShinyWaterProgram.mFeatures.hasGamma = true;
+ gObjectFullbrightShinyWaterProgram.mFeatures.hasTransport = true;
+ gObjectFullbrightShinyWaterProgram.mFeatures.hasWaterFog = true;
+ gObjectFullbrightShinyWaterProgram.mShaderFiles.clear();
+ gObjectFullbrightShinyWaterProgram.mShaderFiles.push_back(make_pair("objects/fullbrightShinyV.glsl", GL_VERTEX_SHADER_ARB));
+ gObjectFullbrightShinyWaterProgram.mShaderFiles.push_back(make_pair("objects/fullbrightShinyWaterF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gObjectFullbrightShinyWaterProgram.mShaderLevel = mVertexShaderLevel[SHADER_OBJECT];
+ gObjectFullbrightShinyWaterProgram.mShaderGroup = LLGLSLShader::SG_WATER;
+ success = gObjectFullbrightShinyWaterProgram.createShader(NULL, &mShinyUniforms);
+ }
+
+ if (mVertexShaderLevel[SHADER_AVATAR] > 0)
+ { //load hardware skinned attachment shaders
+ if (success)
+ {
+ gSkinnedObjectSimpleProgram.mName = "Skinned Simple Shader";
+ gSkinnedObjectSimpleProgram.mFeatures.calculatesLighting = true;
+ gSkinnedObjectSimpleProgram.mFeatures.calculatesAtmospherics = true;
+ gSkinnedObjectSimpleProgram.mFeatures.hasGamma = true;
+ gSkinnedObjectSimpleProgram.mFeatures.hasAtmospherics = true;
+ gSkinnedObjectSimpleProgram.mFeatures.hasLighting = true;
+ gSkinnedObjectSimpleProgram.mFeatures.hasObjectSkinning = true;
+ gSkinnedObjectSimpleProgram.mShaderFiles.clear();
+ gSkinnedObjectSimpleProgram.mShaderFiles.push_back(make_pair("objects/simpleSkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gSkinnedObjectSimpleProgram.mShaderFiles.push_back(make_pair("objects/simpleF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gSkinnedObjectSimpleProgram.mShaderLevel = mVertexShaderLevel[SHADER_OBJECT];
+ success = gSkinnedObjectSimpleProgram.createShader(NULL, NULL);
+ }
+
+ if (success)
+ {
+ gSkinnedObjectFullbrightProgram.mName = "Skinned Fullbright Shader";
+ gSkinnedObjectFullbrightProgram.mFeatures.calculatesAtmospherics = true;
+ gSkinnedObjectFullbrightProgram.mFeatures.hasGamma = true;
+ gSkinnedObjectFullbrightProgram.mFeatures.hasTransport = true;
+ gSkinnedObjectFullbrightProgram.mFeatures.isFullbright = true;
+ gSkinnedObjectFullbrightProgram.mFeatures.hasObjectSkinning = true;
+ gSkinnedObjectFullbrightProgram.mShaderFiles.clear();
+ gSkinnedObjectFullbrightProgram.mShaderFiles.push_back(make_pair("objects/fullbrightSkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gSkinnedObjectFullbrightProgram.mShaderFiles.push_back(make_pair("objects/fullbrightF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gSkinnedObjectFullbrightProgram.mShaderLevel = mVertexShaderLevel[SHADER_OBJECT];
+ success = gSkinnedObjectFullbrightProgram.createShader(NULL, NULL);
+ }
+
+ if (success)
+ {
+ gSkinnedObjectFullbrightShinyProgram.mName = "Skinned Fullbright Shiny Shader";
+ gSkinnedObjectFullbrightShinyProgram.mFeatures.calculatesAtmospherics = true;
+ gSkinnedObjectFullbrightShinyProgram.mFeatures.hasGamma = true;
+ gSkinnedObjectFullbrightShinyProgram.mFeatures.hasTransport = true;
+ gSkinnedObjectFullbrightShinyProgram.mFeatures.isShiny = true;
+ gSkinnedObjectFullbrightShinyProgram.mFeatures.isFullbright = true;
+ gSkinnedObjectFullbrightShinyProgram.mFeatures.hasObjectSkinning = true;
+ gSkinnedObjectFullbrightShinyProgram.mShaderFiles.clear();
+ gSkinnedObjectFullbrightShinyProgram.mShaderFiles.push_back(make_pair("objects/fullbrightShinySkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gSkinnedObjectFullbrightShinyProgram.mShaderFiles.push_back(make_pair("objects/fullbrightShinyF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gSkinnedObjectFullbrightShinyProgram.mShaderLevel = mVertexShaderLevel[SHADER_OBJECT];
+ success = gSkinnedObjectFullbrightShinyProgram.createShader(NULL, &mShinyUniforms);
+ }
+
+ if (success)
+ {
+ gSkinnedObjectShinySimpleProgram.mName = "Skinned Shiny Simple Shader";
+ gSkinnedObjectShinySimpleProgram.mFeatures.calculatesLighting = true;
+ gSkinnedObjectShinySimpleProgram.mFeatures.calculatesAtmospherics = true;
+ gSkinnedObjectShinySimpleProgram.mFeatures.hasGamma = true;
+ gSkinnedObjectShinySimpleProgram.mFeatures.hasAtmospherics = true;
+ gSkinnedObjectShinySimpleProgram.mFeatures.hasObjectSkinning = true;
+ gSkinnedObjectShinySimpleProgram.mFeatures.isShiny = true;
+ gSkinnedObjectShinySimpleProgram.mShaderFiles.clear();
+ gSkinnedObjectShinySimpleProgram.mShaderFiles.push_back(make_pair("objects/shinySimpleSkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gSkinnedObjectShinySimpleProgram.mShaderFiles.push_back(make_pair("objects/shinyF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gSkinnedObjectShinySimpleProgram.mShaderLevel = mVertexShaderLevel[SHADER_OBJECT];
+ success = gSkinnedObjectShinySimpleProgram.createShader(NULL, &mShinyUniforms);
+ }
+
+ if (success)
+ {
+ gSkinnedObjectSimpleWaterProgram.mName = "Skinned Simple Water Shader";
+ gSkinnedObjectSimpleWaterProgram.mFeatures.calculatesLighting = true;
+ gSkinnedObjectSimpleWaterProgram.mFeatures.calculatesAtmospherics = true;
+ gSkinnedObjectSimpleWaterProgram.mFeatures.hasGamma = true;
+ gSkinnedObjectSimpleWaterProgram.mFeatures.hasAtmospherics = true;
+ gSkinnedObjectSimpleWaterProgram.mFeatures.hasLighting = true;
+ gSkinnedObjectSimpleWaterProgram.mFeatures.hasWaterFog = true;
+ gSkinnedObjectSimpleWaterProgram.mShaderGroup = LLGLSLShader::SG_WATER;
+ gSkinnedObjectSimpleWaterProgram.mFeatures.hasObjectSkinning = true;
+ gSkinnedObjectSimpleWaterProgram.mShaderFiles.clear();
+ gSkinnedObjectSimpleWaterProgram.mShaderFiles.push_back(make_pair("objects/simpleSkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gSkinnedObjectSimpleWaterProgram.mShaderFiles.push_back(make_pair("objects/simpleWaterF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gSkinnedObjectSimpleWaterProgram.mShaderLevel = mVertexShaderLevel[SHADER_OBJECT];
+ success = gSkinnedObjectSimpleWaterProgram.createShader(NULL, NULL);
+ }
+
+ if (success)
+ {
+ gSkinnedObjectFullbrightWaterProgram.mName = "Skinned Fullbright Water Shader";
+ gSkinnedObjectFullbrightWaterProgram.mFeatures.calculatesAtmospherics = true;
+ gSkinnedObjectFullbrightWaterProgram.mFeatures.hasGamma = true;
+ gSkinnedObjectFullbrightWaterProgram.mFeatures.hasTransport = true;
+ gSkinnedObjectFullbrightWaterProgram.mFeatures.isFullbright = true;
+ gSkinnedObjectFullbrightWaterProgram.mFeatures.hasObjectSkinning = true;
+ gSkinnedObjectFullbrightWaterProgram.mFeatures.hasWaterFog = true;
+ gSkinnedObjectFullbrightWaterProgram.mShaderGroup = LLGLSLShader::SG_WATER;
+ gSkinnedObjectFullbrightWaterProgram.mShaderFiles.clear();
+ gSkinnedObjectFullbrightWaterProgram.mShaderFiles.push_back(make_pair("objects/fullbrightSkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gSkinnedObjectFullbrightWaterProgram.mShaderFiles.push_back(make_pair("objects/fullbrightWaterF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gSkinnedObjectFullbrightWaterProgram.mShaderLevel = mVertexShaderLevel[SHADER_OBJECT];
+ success = gSkinnedObjectFullbrightWaterProgram.createShader(NULL, NULL);
+ }
+
+ if (success)
+ {
+ gSkinnedObjectFullbrightShinyWaterProgram.mName = "Skinned Fullbright Shiny Water Shader";
+ gSkinnedObjectFullbrightShinyWaterProgram.mFeatures.calculatesAtmospherics = true;
+ gSkinnedObjectFullbrightShinyWaterProgram.mFeatures.hasGamma = true;
+ gSkinnedObjectFullbrightShinyWaterProgram.mFeatures.hasTransport = true;
+ gSkinnedObjectFullbrightShinyWaterProgram.mFeatures.isShiny = true;
+ gSkinnedObjectFullbrightShinyWaterProgram.mFeatures.isFullbright = true;
+ gSkinnedObjectFullbrightShinyWaterProgram.mFeatures.hasObjectSkinning = true;
+ gSkinnedObjectFullbrightShinyWaterProgram.mFeatures.hasWaterFog = true;
+ gSkinnedObjectFullbrightShinyWaterProgram.mShaderGroup = LLGLSLShader::SG_WATER;
+ gSkinnedObjectFullbrightShinyWaterProgram.mShaderFiles.clear();
+ gSkinnedObjectFullbrightShinyWaterProgram.mShaderFiles.push_back(make_pair("objects/fullbrightShinySkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gSkinnedObjectFullbrightShinyWaterProgram.mShaderFiles.push_back(make_pair("objects/fullbrightShinyWaterF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gSkinnedObjectFullbrightShinyWaterProgram.mShaderLevel = mVertexShaderLevel[SHADER_OBJECT];
+ success = gSkinnedObjectFullbrightShinyWaterProgram.createShader(NULL, &mShinyUniforms);
+ }
+
+ if (success)
+ {
+ gSkinnedObjectShinySimpleWaterProgram.mName = "Skinned Shiny Simple Water Shader";
+ gSkinnedObjectShinySimpleWaterProgram.mFeatures.calculatesLighting = true;
+ gSkinnedObjectShinySimpleWaterProgram.mFeatures.calculatesAtmospherics = true;
+ gSkinnedObjectShinySimpleWaterProgram.mFeatures.hasGamma = true;
+ gSkinnedObjectShinySimpleWaterProgram.mFeatures.hasAtmospherics = true;
+ gSkinnedObjectShinySimpleWaterProgram.mFeatures.hasObjectSkinning = true;
+ gSkinnedObjectShinySimpleWaterProgram.mFeatures.isShiny = true;
+ gSkinnedObjectShinySimpleWaterProgram.mFeatures.hasWaterFog = true;
+ gSkinnedObjectShinySimpleWaterProgram.mShaderGroup = LLGLSLShader::SG_WATER;
+ gSkinnedObjectShinySimpleWaterProgram.mShaderFiles.clear();
+ gSkinnedObjectShinySimpleWaterProgram.mShaderFiles.push_back(make_pair("objects/shinySimpleSkinnedV.glsl", GL_VERTEX_SHADER_ARB));
+ gSkinnedObjectShinySimpleWaterProgram.mShaderFiles.push_back(make_pair("objects/shinyWaterF.glsl", GL_FRAGMENT_SHADER_ARB));
+ gSkinnedObjectShinySimpleWaterProgram.mShaderLevel = mVertexShaderLevel[SHADER_OBJECT];
+ success = gSkinnedObjectShinySimpleWaterProgram.createShader(NULL, &mShinyUniforms);
+ }
+ }
if( !success )
{
diff --git a/indra/newview/llviewershadermgr.h b/indra/newview/llviewershadermgr.h
index db880fded6..f31d2d1836 100644
--- a/indra/newview/llviewershadermgr.h
+++ b/indra/newview/llviewershadermgr.h
@@ -76,6 +76,7 @@ public:
MATERIAL_COLOR = 0,
SPECULAR_COLOR,
BINORMAL,
+ OBJECT_WEIGHT,
END_RESERVED_ATTRIBS
} eGLSLReservedAttribs;
@@ -304,9 +305,20 @@ extern LLGLSLShader gObjectSimpleLODProgram;
extern LLGLSLShader gObjectFullbrightLODProgram;
extern LLGLSLShader gObjectFullbrightShinyProgram;
+extern LLGLSLShader gObjectFullbrightShinyWaterProgram;
extern LLGLSLShader gObjectShinyProgram;
extern LLGLSLShader gObjectShinyWaterProgram;
+extern LLGLSLShader gSkinnedObjectSimpleProgram;
+extern LLGLSLShader gSkinnedObjectFullbrightProgram;
+extern LLGLSLShader gSkinnedObjectFullbrightShinyProgram;
+extern LLGLSLShader gSkinnedObjectShinySimpleProgram;
+
+extern LLGLSLShader gSkinnedObjectSimpleWaterProgram;
+extern LLGLSLShader gSkinnedObjectFullbrightWaterProgram;
+extern LLGLSLShader gSkinnedObjectFullbrightShinyWaterProgram;
+extern LLGLSLShader gSkinnedObjectShinySimpleWaterProgram;
+
//environment shaders
extern LLGLSLShader gTerrainProgram;
extern LLGLSLShader gTerrainWaterProgram;
@@ -337,6 +349,9 @@ extern LLGLSLShader gDeferredImpostorProgram;
extern LLGLSLShader gDeferredEdgeProgram;
extern LLGLSLShader gDeferredWaterProgram;
extern LLGLSLShader gDeferredDiffuseProgram;
+extern LLGLSLShader gDeferredSkinnedDiffuseProgram;
+extern LLGLSLShader gDeferredSkinnedBumpProgram;
+extern LLGLSLShader gDeferredSkinnedAlphaProgram;
extern LLGLSLShader gDeferredBumpProgram;
extern LLGLSLShader gDeferredTerrainProgram;
extern LLGLSLShader gDeferredTreeProgram;
@@ -354,6 +369,7 @@ extern LLGLSLShader gDeferredShadowProgram;
extern LLGLSLShader gDeferredPostGIProgram;
extern LLGLSLShader gDeferredPostProgram;
extern LLGLSLShader gDeferredAvatarShadowProgram;
+extern LLGLSLShader gDeferredAttachmentShadowProgram;
extern LLGLSLShader gDeferredAlphaProgram;
extern LLGLSLShader gDeferredFullbrightProgram;
extern LLGLSLShader gDeferredAvatarAlphaProgram;
diff --git a/indra/newview/llviewerstats.cpp b/indra/newview/llviewerstats.cpp
index 874519a59f..221d1114a7 100644
--- a/indra/newview/llviewerstats.cpp
+++ b/indra/newview/llviewerstats.cpp
@@ -59,6 +59,7 @@
#include "llworld.h"
#include "llfeaturemanager.h"
#include "llviewernetwork.h"
+#include "llmeshrepository.h" //for LLMeshRepository::sBytesReceived
class StatAttributes
@@ -794,6 +795,7 @@ void send_stats()
download["world_kbytes"] = gTotalWorldBytes / 1024.0;
download["object_kbytes"] = gTotalObjectBytes / 1024.0;
download["texture_kbytes"] = gTotalTextureBytes / 1024.0;
+ download["mesh_kbytes"] = LLMeshRepository::sBytesReceived/1024.0;
LLSD &in = body["stats"]["net"]["in"];
diff --git a/indra/newview/llviewerstats.h b/indra/newview/llviewerstats.h
index 3f9cfb9d9b..f91a1241fe 100644..100755
--- a/indra/newview/llviewerstats.h
+++ b/indra/newview/llviewerstats.h
@@ -196,8 +196,15 @@ public:
S32 mCount;
F32 mSum;
F32 mSumOfSquares;
+ F32 mMinValue;
+ F32 mMaxValue;
U32 mCountOfNextUpdatesToIgnore;
+ inline StatsAccumulator()
+ {
+ reset();
+ }
+
inline void push( F32 val )
{
if ( mCountOfNextUpdatesToIgnore > 0 )
@@ -209,13 +216,31 @@ public:
mCount++;
mSum += val;
mSumOfSquares += val * val;
+ if (mCount == 1 || val > mMaxValue)
+ {
+ mMaxValue = val;
+ }
+ if (mCount == 1 || val < mMinValue)
+ {
+ mMinValue = val;
+ }
}
inline F32 getMean() const
{
return (mCount == 0) ? 0.f : ((F32)mSum)/mCount;
}
-
+
+ inline F32 getMinValue() const
+ {
+ return mMinValue;
+ }
+
+ inline F32 getMaxValue() const
+ {
+ return mMaxValue;
+ }
+
inline F32 getStdDev() const
{
const F32 mean = getMean();
@@ -231,6 +256,8 @@ public:
{
mCount = 0;
mSum = mSumOfSquares = 0.f;
+ mMinValue = 0.0f;
+ mMaxValue = 0.0f;
mCountOfNextUpdatesToIgnore = 0;
}
@@ -240,6 +267,8 @@ public:
data["mean"] = getMean();
data["std_dev"] = getStdDev();
data["count"] = (S32)mCount;
+ data["min"] = getMinValue();
+ data["max"] = getMaxValue();
return data;
}
};
diff --git a/indra/newview/llviewertexteditor.cpp b/indra/newview/llviewertexteditor.cpp
index 0c36970878..4798bb536f 100644
--- a/indra/newview/llviewertexteditor.cpp
+++ b/indra/newview/llviewertexteditor.cpp
@@ -537,6 +537,7 @@ LLUIImagePtr LLEmbeddedItems::getItemImage(llwchar ext_char) const
case LLAssetType::AT_BODYPART: img_name = "Inv_Skin"; break;
case LLAssetType::AT_ANIMATION: img_name = "Inv_Animation"; break;
case LLAssetType::AT_GESTURE: img_name = "Inv_Gesture"; break;
+ case LLAssetType::AT_MESH: img_name = "Inv_Mesh"; break;
default: llassert(0);
}
@@ -846,17 +847,18 @@ BOOL LLViewerTextEditor::handleDragAndDrop(S32 x, S32 y, MASK mask,
{
switch( cargo_type )
{
- case DAD_CALLINGCARD:
- case DAD_TEXTURE:
- case DAD_SOUND:
- case DAD_LANDMARK:
- case DAD_SCRIPT:
- case DAD_CLOTHING:
- case DAD_OBJECT:
- case DAD_NOTECARD:
- case DAD_BODYPART:
- case DAD_ANIMATION:
- case DAD_GESTURE:
+ case DAD_CALLINGCARD:
+ case DAD_TEXTURE:
+ case DAD_SOUND:
+ case DAD_LANDMARK:
+ case DAD_SCRIPT:
+ case DAD_CLOTHING:
+ case DAD_OBJECT:
+ case DAD_NOTECARD:
+ case DAD_BODYPART:
+ case DAD_ANIMATION:
+ case DAD_GESTURE:
+ case DAD_MESH:
{
LLInventoryItem *item = (LLInventoryItem *)cargo_data;
if( item && allowsEmbeddedItems() )
diff --git a/indra/newview/llviewertexture.cpp b/indra/newview/llviewertexture.cpp
index cf7f3f80ad..5cd2881e2a 100644..100755
--- a/indra/newview/llviewertexture.cpp
+++ b/indra/newview/llviewertexture.cpp
@@ -835,7 +835,7 @@ BOOL LLViewerTexture::createGLTexture(S32 discard_level, const LLImageRaw* image
llassert(mGLTexturep.notNull()) ;
BOOL ret = mGLTexturep->createGLTexture(discard_level, imageraw, usename, to_create, category) ;
-
+
if(ret)
{
mFullWidth = mGLTexturep->getCurrentWidth() ;
@@ -1423,8 +1423,15 @@ BOOL LLViewerFetchedTexture::createTexture(S32 usename/*= 0*/)
mOrigWidth = mRawImage->getWidth();
mOrigHeight = mRawImage->getHeight();
- // leave black border, do not scale image content
- mRawImage->expandToPowerOfTwo(MAX_IMAGE_SIZE, FALSE);
+
+ if (mBoostLevel == BOOST_PREVIEW)
+ {
+ mRawImage->biasedScaleToPowerOfTwo(1024);
+ }
+ else
+ { // leave black border, do not scale image content
+ mRawImage->expandToPowerOfTwo(MAX_IMAGE_SIZE, FALSE);
+ }
mFullWidth = mRawImage->getWidth();
mFullHeight = mRawImage->getHeight();
@@ -1585,7 +1592,7 @@ F32 LLViewerFetchedTexture::calcDecodePriority()
S32 cur_discard = getCurrentDiscardLevelForFetching();
bool have_all_data = (cur_discard >= 0 && (cur_discard <= mDesiredDiscardLevel));
- F32 pixel_priority = fsqrtf(mMaxVirtualSize);
+ F32 pixel_priority = (F32) sqrt(mMaxVirtualSize);
F32 priority = 0.f;
@@ -2713,6 +2720,9 @@ void LLViewerFetchedTexture::forceToSaveRawImage(S32 desired_discard)
}
void LLViewerFetchedTexture::destroySavedRawImage()
{
+ mForceToSaveRawImage = FALSE ;
+ mSaveRawImage = FALSE ;
+
clearCallbackEntryList() ;
mSavedRawImage = NULL ;
@@ -2872,7 +2882,7 @@ BOOL LLViewerFetchedTexture::insertToAtlas()
}
//process the waiting_list
- for(ll_face_list_t::iterator iter = waiting_list.begin(); iter != waiting_list.end(); ++iter)
+ for(std::vector<LLFace*>::iterator iter = waiting_list.begin(); iter != waiting_list.end(); ++iter)
{
facep = (LLFace*)*iter ;
groupp = facep->getDrawable()->getSpatialGroup() ;
diff --git a/indra/newview/llviewertexturelist.cpp b/indra/newview/llviewertexturelist.cpp
index 10126219f8..b5eadb6d25 100644
--- a/indra/newview/llviewertexturelist.cpp
+++ b/indra/newview/llviewertexturelist.cpp
@@ -834,7 +834,7 @@ F32 LLViewerTextureList::updateImagesFetchTextures(F32 max_time)
for (entries_list_t::iterator iter3 = entries.begin();
iter3 != entries.end(); )
{
- LLPointer<LLViewerFetchedTexture> imagep = *iter3++;
+ LLViewerFetchedTexture* imagep = *iter3++;
bool fetching = imagep->updateFetch();
if (fetching)
diff --git a/indra/newview/llviewerwindow.cpp b/indra/newview/llviewerwindow.cpp
index 2843e4e9ae..f1acd34e11 100644
--- a/indra/newview/llviewerwindow.cpp
+++ b/indra/newview/llviewerwindow.cpp
@@ -1,5034 +1,5181 @@
-/**
- * @file llviewerwindow.cpp
- * @brief Implementation of the LLViewerWindow class.
- *
- * $LicenseInfo:firstyear=2001&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-#include "llviewerprecompiledheaders.h"
-
-#include "llviewerwindow.h"
-
-#if LL_WINDOWS
-#pragma warning (disable : 4355) // 'this' used in initializer list: yes, intentionally
-#endif
-
-// system library includes
-#include <stdio.h>
-#include <iostream>
-#include <fstream>
-#include <algorithm>
-
-#include "llagent.h"
-#include "llagentcamera.h"
-#include "llfloaterreg.h"
-#include "llpanellogin.h"
-#include "llviewerkeyboard.h"
-#include "llviewermenu.h"
-
-#include "llviewquery.h"
-#include "llxmltree.h"
-#include "llslurl.h"
-//#include "llviewercamera.h"
-#include "llrender.h"
-
-#include "llvoiceclient.h" // for push-to-talk button handling
-
-//
-// TODO: Many of these includes are unnecessary. Remove them.
-//
-
-// linden library includes
-#include "llaudioengine.h" // mute on minimize
-#include "indra_constants.h"
-#include "llassetstorage.h"
-#include "llerrorcontrol.h"
-#include "llfontgl.h"
-#include "llmousehandler.h"
-#include "llrect.h"
-#include "llsky.h"
-#include "llstring.h"
-#include "llui.h"
-#include "lluuid.h"
-#include "llview.h"
-#include "llxfermanager.h"
-#include "message.h"
-#include "object_flags.h"
-#include "lltimer.h"
-#include "timing.h"
-#include "llviewermenu.h"
-#include "lltooltip.h"
-#include "llmediaentry.h"
-#include "llurldispatcher.h"
-
-// newview includes
-#include "llagent.h"
-#include "llbox.h"
-#include "llconsole.h"
-#include "llviewercontrol.h"
-#include "llcylinder.h"
-#include "lldebugview.h"
-#include "lldir.h"
-#include "lldrawable.h"
-#include "lldrawpoolalpha.h"
-#include "lldrawpoolbump.h"
-#include "lldrawpoolwater.h"
-#include "llmaniptranslate.h"
-#include "llface.h"
-#include "llfeaturemanager.h"
-#include "llfilepicker.h"
-#include "llfirstuse.h"
-#include "llfloater.h"
-#include "llfloaterbuildoptions.h"
-#include "llfloaterbuyland.h"
-#include "llfloatercamera.h"
-#include "llfloaterland.h"
-#include "llfloaterinspect.h"
-#include "llfloatermap.h"
-#include "llfloaternamedesc.h"
-#include "llfloaterpreference.h"
-#include "llfloatersnapshot.h"
-#include "llfloatertools.h"
-#include "llfloaterworldmap.h"
-#include "llfocusmgr.h"
-#include "llfontfreetype.h"
-#include "llgesturemgr.h"
-#include "llglheaders.h"
-#include "lltooltip.h"
-#include "llhudmanager.h"
-#include "llhudobject.h"
-#include "llhudview.h"
-#include "llimagebmp.h"
-#include "llimagej2c.h"
-#include "llimageworker.h"
-#include "llkeyboard.h"
-#include "lllineeditor.h"
-#include "llmenugl.h"
-#include "llmodaldialog.h"
-#include "llmorphview.h"
-#include "llmoveview.h"
-#include "llnavigationbar.h"
-#include "llpopupview.h"
-#include "llpreviewtexture.h"
-#include "llprogressview.h"
-#include "llresmgr.h"
-#include "llsidetray.h"
-#include "llselectmgr.h"
-#include "llrootview.h"
-#include "llrendersphere.h"
-#include "llstartup.h"
-#include "llstatusbar.h"
-#include "llstatview.h"
-#include "llsurface.h"
-#include "llsurfacepatch.h"
-#include "lltexlayer.h"
-#include "lltextbox.h"
-#include "lltexturecache.h"
-#include "lltexturefetch.h"
-#include "lltextureview.h"
-#include "lltool.h"
-#include "lltoolcomp.h"
-#include "lltooldraganddrop.h"
-#include "lltoolface.h"
-#include "lltoolfocus.h"
-#include "lltoolgrab.h"
-#include "lltoolmgr.h"
-#include "lltoolmorph.h"
-#include "lltoolpie.h"
-#include "lltoolselectland.h"
-#include "lltrans.h"
-#include "lluictrlfactory.h"
-#include "llurldispatcher.h" // SLURL from other app instance
-#include "llversioninfo.h"
-#include "llvieweraudio.h"
-#include "llviewercamera.h"
-#include "llviewergesture.h"
-#include "llviewertexturelist.h"
-#include "llviewerinventory.h"
-#include "llviewerkeyboard.h"
-#include "llviewermedia.h"
-#include "llviewermediafocus.h"
-#include "llviewermenu.h"
-#include "llviewermessage.h"
-#include "llviewerobjectlist.h"
-#include "llviewerparcelmgr.h"
-#include "llviewerregion.h"
-#include "llviewershadermgr.h"
-#include "llviewerstats.h"
-#include "llvoavatarself.h"
-#include "llvovolume.h"
-#include "llworld.h"
-#include "llworldmapview.h"
-#include "pipeline.h"
-#include "llappviewer.h"
-#include "llviewerdisplay.h"
-#include "llspatialpartition.h"
-#include "llviewerjoystick.h"
-#include "llviewernetwork.h"
-#include "llpostprocess.h"
-#include "llbottomtray.h"
-#include "llnearbychatbar.h"
-#include "llagentui.h"
-#include "llwearablelist.h"
-
-#include "llnotifications.h"
-#include "llnotificationsutil.h"
-#include "llnotificationmanager.h"
-
-#include "llfloaternotificationsconsole.h"
-
-#include "llnearbychat.h"
-#include "llviewerwindowlistener.h"
-#include "llpaneltopinfobar.h"
-
-#if LL_WINDOWS
-#include <tchar.h> // For Unicode conversion methods
-#endif
-
-//
-// Globals
-//
-void render_ui(F32 zoom_factor = 1.f, int subfield = 0);
-
-extern BOOL gDebugClicks;
-extern BOOL gDisplaySwapBuffers;
-extern BOOL gDepthDirty;
-extern BOOL gResizeScreenTexture;
-
-LLViewerWindow *gViewerWindow = NULL;
-
-LLFrameTimer gAwayTimer;
-LLFrameTimer gAwayTriggerTimer;
-
-BOOL gShowOverlayTitle = FALSE;
-
-LLViewerObject* gDebugRaycastObject = NULL;
-LLVector3 gDebugRaycastIntersection;
-LLVector2 gDebugRaycastTexCoord;
-LLVector3 gDebugRaycastNormal;
-LLVector3 gDebugRaycastBinormal;
-S32 gDebugRaycastFaceHit;
-
-// HUD display lines in lower right
-BOOL gDisplayWindInfo = FALSE;
-BOOL gDisplayCameraPos = FALSE;
-BOOL gDisplayFOV = FALSE;
-BOOL gDisplayBadge = FALSE;
-
-S32 CHAT_BAR_HEIGHT = 28;
-S32 OVERLAY_BAR_HEIGHT = 20;
-
-const U8 NO_FACE = 255;
-BOOL gQuietSnapshot = FALSE;
-
-const F32 MIN_AFK_TIME = 2.f; // minimum time after setting away state before coming back
-const F32 MAX_FAST_FRAME_TIME = 0.5f;
-const F32 FAST_FRAME_INCREMENT = 0.1f;
-
-const F32 MIN_DISPLAY_SCALE = 0.75f;
-
-std::string LLViewerWindow::sSnapshotBaseName;
-std::string LLViewerWindow::sSnapshotDir;
-
-std::string LLViewerWindow::sMovieBaseName;
-
-class RecordToChatConsole : public LLError::Recorder, public LLSingleton<RecordToChatConsole>
-{
-public:
- virtual void recordMessage(LLError::ELevel level,
- const std::string& message)
- {
- //FIXME: this is NOT thread safe, and will do bad things when a warning is issued from a non-UI thread
-
- // only log warnings to chat console
- //if (level == LLError::LEVEL_WARN)
- //{
- //LLFloaterChat* chat_floater = LLFloaterReg::findTypedInstance<LLFloaterChat>("chat");
- //if (chat_floater && gSavedSettings.getBOOL("WarningsAsChat"))
- //{
- // LLChat chat;
- // chat.mText = message;
- // chat.mSourceType = CHAT_SOURCE_SYSTEM;
-
- // chat_floater->addChat(chat, FALSE, FALSE);
- //}
- //}
- }
-};
-
-////////////////////////////////////////////////////////////////////////////
-//
-// LLDebugText
-//
-
-class LLDebugText
-{
-private:
- struct Line
- {
- Line(const std::string& in_text, S32 in_x, S32 in_y) : text(in_text), x(in_x), y(in_y) {}
- std::string text;
- S32 x,y;
- };
-
- LLViewerWindow *mWindow;
-
- typedef std::vector<Line> line_list_t;
- line_list_t mLineList;
- LLColor4 mTextColor;
-
- void addText(S32 x, S32 y, const std::string &text)
- {
- mLineList.push_back(Line(text, x, y));
- }
-
- void clearText() { mLineList.clear(); }
-
-public:
- LLDebugText(LLViewerWindow* window) : mWindow(window) {}
-
- void update()
- {
- static LLCachedControl<bool> log_texture_traffic(gSavedSettings,"LogTextureNetworkTraffic") ;
-
- std::string wind_vel_text;
- std::string wind_vector_text;
- std::string rwind_vel_text;
- std::string rwind_vector_text;
- std::string audio_text;
-
- static const std::string beacon_particle = LLTrans::getString("BeaconParticle");
- static const std::string beacon_physical = LLTrans::getString("BeaconPhysical");
- static const std::string beacon_scripted = LLTrans::getString("BeaconScripted");
- static const std::string beacon_scripted_touch = LLTrans::getString("BeaconScriptedTouch");
- static const std::string beacon_sound = LLTrans::getString("BeaconSound");
- static const std::string beacon_media = LLTrans::getString("BeaconMedia");
- static const std::string particle_hiding = LLTrans::getString("ParticleHiding");
-
- // Draw the statistics in a light gray
- // and in a thin font
- mTextColor = LLColor4( 0.86f, 0.86f, 0.86f, 1.f );
-
- // Draw stuff growing up from right lower corner of screen
- U32 xpos = mWindow->getWindowWidthScaled() - 350;
- U32 ypos = 64;
- const U32 y_inc = 20;
-
- clearText();
-
- if (gSavedSettings.getBOOL("DebugShowTime"))
- {
- const U32 y_inc2 = 15;
- for (std::map<S32,LLFrameTimer>::reverse_iterator iter = gDebugTimers.rbegin();
- iter != gDebugTimers.rend(); ++iter)
- {
- S32 idx = iter->first;
- LLFrameTimer& timer = iter->second;
- F32 time = timer.getElapsedTimeF32();
- S32 hours = (S32)(time / (60*60));
- S32 mins = (S32)((time - hours*(60*60)) / 60);
- S32 secs = (S32)((time - hours*(60*60) - mins*60));
- std::string label = gDebugTimerLabel[idx];
- if (label.empty()) label = llformat("Debug: %d", idx);
- addText(xpos, ypos, llformat(" %s: %d:%02d:%02d", label.c_str(), hours,mins,secs)); ypos += y_inc2;
- }
-
- F32 time = gFrameTimeSeconds;
- S32 hours = (S32)(time / (60*60));
- S32 mins = (S32)((time - hours*(60*60)) / 60);
- S32 secs = (S32)((time - hours*(60*60) - mins*60));
- addText(xpos, ypos, llformat("Time: %d:%02d:%02d", hours,mins,secs)); ypos += y_inc;
- }
-
-#if LL_WINDOWS
- if (gSavedSettings.getBOOL("DebugShowMemory"))
- {
- addText(xpos, ypos, llformat("Memory: %d (KB)", LLMemory::getWorkingSetSize() / 1024));
- ypos += y_inc;
- }
-#endif
-
- if (gDisplayCameraPos)
- {
- std::string camera_view_text;
- std::string camera_center_text;
- std::string agent_view_text;
- std::string agent_left_text;
- std::string agent_center_text;
- std::string agent_root_center_text;
-
- LLVector3d tvector; // Temporary vector to hold data for printing.
-
- // Update camera center, camera view, wind info every other frame
- tvector = gAgent.getPositionGlobal();
- agent_center_text = llformat("AgentCenter %f %f %f",
- (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
-
- if (isAgentAvatarValid())
- {
- tvector = gAgent.getPosGlobalFromAgent(gAgentAvatarp->mRoot.getWorldPosition());
- agent_root_center_text = llformat("AgentRootCenter %f %f %f",
- (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
- }
- else
- {
- agent_root_center_text = "---";
- }
-
-
- tvector = LLVector4(gAgent.getFrameAgent().getAtAxis());
- agent_view_text = llformat("AgentAtAxis %f %f %f",
- (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
-
- tvector = LLVector4(gAgent.getFrameAgent().getLeftAxis());
- agent_left_text = llformat("AgentLeftAxis %f %f %f",
- (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
-
- tvector = gAgentCamera.getCameraPositionGlobal();
- camera_center_text = llformat("CameraCenter %f %f %f",
- (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
-
- tvector = LLVector4(LLViewerCamera::getInstance()->getAtAxis());
- camera_view_text = llformat("CameraAtAxis %f %f %f",
- (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
-
- addText(xpos, ypos, agent_center_text); ypos += y_inc;
- addText(xpos, ypos, agent_root_center_text); ypos += y_inc;
- addText(xpos, ypos, agent_view_text); ypos += y_inc;
- addText(xpos, ypos, agent_left_text); ypos += y_inc;
- addText(xpos, ypos, camera_center_text); ypos += y_inc;
- addText(xpos, ypos, camera_view_text); ypos += y_inc;
- }
-
- if (gDisplayWindInfo)
- {
- wind_vel_text = llformat("Wind velocity %.2f m/s", gWindVec.magVec());
- wind_vector_text = llformat("Wind vector %.2f %.2f %.2f", gWindVec.mV[0], gWindVec.mV[1], gWindVec.mV[2]);
- rwind_vel_text = llformat("RWind vel %.2f m/s", gRelativeWindVec.magVec());
- rwind_vector_text = llformat("RWind vec %.2f %.2f %.2f", gRelativeWindVec.mV[0], gRelativeWindVec.mV[1], gRelativeWindVec.mV[2]);
-
- addText(xpos, ypos, wind_vel_text); ypos += y_inc;
- addText(xpos, ypos, wind_vector_text); ypos += y_inc;
- addText(xpos, ypos, rwind_vel_text); ypos += y_inc;
- addText(xpos, ypos, rwind_vector_text); ypos += y_inc;
- }
- if (gDisplayWindInfo)
- {
- if (gAudiop)
- {
- audio_text= llformat("Audio for wind: %d", gAudiop->isWindEnabled());
- }
- addText(xpos, ypos, audio_text); ypos += y_inc;
- }
- if (gDisplayFOV)
- {
- addText(xpos, ypos, llformat("FOV: %2.1f deg", RAD_TO_DEG * LLViewerCamera::getInstance()->getView()));
- ypos += y_inc;
- }
- if (gDisplayBadge)
- {
- addText(xpos, ypos+(y_inc/2), llformat("Hippos!", RAD_TO_DEG * LLViewerCamera::getInstance()->getView()));
- ypos += y_inc * 2;
- }
-
- /*if (LLViewerJoystick::getInstance()->getOverrideCamera())
- {
- addText(xpos + 200, ypos, llformat("Flycam"));
- ypos += y_inc;
- }*/
-
- if (gSavedSettings.getBOOL("DebugShowRenderInfo"))
- {
- if (gPipeline.getUseVertexShaders() == 0)
- {
- addText(xpos, ypos, "Shaders Disabled");
- ypos += y_inc;
- }
- addText(xpos, ypos, llformat("%d MB Vertex Data", LLVertexBuffer::sAllocatedBytes/(1024*1024)));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%d Vertex Buffers", LLVertexBuffer::sGLCount));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%d Mapped Buffers", LLVertexBuffer::sMappedCount));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%d Vertex Buffer Binds", LLVertexBuffer::sBindCount));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%d Vertex Buffer Sets", LLVertexBuffer::sSetCount));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%d Texture Binds", LLImageGL::sBindCount));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%d Unique Textures", LLImageGL::sUniqueCount));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%d Render Calls", gPipeline.mBatchCount));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%d Matrix Ops", gPipeline.mMatrixOpCount));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%d Texture Matrix Ops", gPipeline.mTextureMatrixOps));
- ypos += y_inc;
-
- gPipeline.mTextureMatrixOps = 0;
- gPipeline.mMatrixOpCount = 0;
-
- if (gPipeline.mBatchCount > 0)
- {
- addText(xpos, ypos, llformat("Batch min/max/mean: %d/%d/%d", gPipeline.mMinBatchSize, gPipeline.mMaxBatchSize,
- gPipeline.mTrianglesDrawn/gPipeline.mBatchCount));
-
- gPipeline.mMinBatchSize = gPipeline.mMaxBatchSize;
- gPipeline.mMaxBatchSize = 0;
- gPipeline.mBatchCount = 0;
- }
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("UI Verts/Calls: %d/%d", LLRender::sUIVerts, LLRender::sUICalls));
- LLRender::sUICalls = LLRender::sUIVerts = 0;
- ypos += y_inc;
-
- addText(xpos,ypos, llformat("%d/%d Nodes visible", gPipeline.mNumVisibleNodes, LLSpatialGroup::sNodeCount));
-
- ypos += y_inc;
-
-
- addText(xpos,ypos, llformat("%d Avatars visible", LLVOAvatar::sNumVisibleAvatars));
-
- ypos += y_inc;
-
- addText(xpos,ypos, llformat("%d Lights visible", LLPipeline::sVisibleLightCount));
-
- ypos += y_inc;
-
- LLVertexBuffer::sBindCount = LLImageGL::sBindCount =
- LLVertexBuffer::sSetCount = LLImageGL::sUniqueCount =
- gPipeline.mNumVisibleNodes = LLPipeline::sVisibleLightCount = 0;
- }
- if (gSavedSettings.getBOOL("DebugShowRenderMatrices"))
- {
- addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLProjection[12], gGLProjection[13], gGLProjection[14], gGLProjection[15]));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLProjection[8], gGLProjection[9], gGLProjection[10], gGLProjection[11]));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLProjection[4], gGLProjection[5], gGLProjection[6], gGLProjection[7]));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLProjection[0], gGLProjection[1], gGLProjection[2], gGLProjection[3]));
- ypos += y_inc;
-
- addText(xpos, ypos, "Projection Matrix");
- ypos += y_inc;
-
-
- addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLModelView[12], gGLModelView[13], gGLModelView[14], gGLModelView[15]));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLModelView[8], gGLModelView[9], gGLModelView[10], gGLModelView[11]));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLModelView[4], gGLModelView[5], gGLModelView[6], gGLModelView[7]));
- ypos += y_inc;
-
- addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLModelView[0], gGLModelView[1], gGLModelView[2], gGLModelView[3]));
- ypos += y_inc;
-
- addText(xpos, ypos, "View Matrix");
- ypos += y_inc;
- }
- if (gSavedSettings.getBOOL("DebugShowColor"))
- {
- U8 color[4];
- LLCoordGL coord = gViewerWindow->getCurrentMouse();
- glReadPixels(coord.mX, coord.mY, 1,1,GL_RGBA, GL_UNSIGNED_BYTE, color);
- addText(xpos, ypos, llformat("%d %d %d %d", color[0], color[1], color[2], color[3]));
- ypos += y_inc;
- }
- // only display these messages if we are actually rendering beacons at this moment
- if (LLPipeline::getRenderBeacons(NULL) && LLFloaterReg::instanceVisible("beacons"))
- {
- if (LLPipeline::getRenderParticleBeacons(NULL))
- {
- addText(xpos, ypos, beacon_particle);
- ypos += y_inc;
- }
- if (LLPipeline::toggleRenderTypeControlNegated((void*)LLPipeline::RENDER_TYPE_PARTICLES))
- {
- addText(xpos, ypos, particle_hiding);
- ypos += y_inc;
- }
- if (LLPipeline::getRenderPhysicalBeacons(NULL))
- {
- addText(xpos, ypos, beacon_physical);
- ypos += y_inc;
- }
- if (LLPipeline::getRenderScriptedBeacons(NULL))
- {
- addText(xpos, ypos, beacon_scripted);
- ypos += y_inc;
- }
- else
- if (LLPipeline::getRenderScriptedTouchBeacons(NULL))
- {
- addText(xpos, ypos, beacon_scripted_touch);
- ypos += y_inc;
- }
- if (LLPipeline::getRenderSoundBeacons(NULL))
- {
- addText(xpos, ypos, beacon_sound);
- ypos += y_inc;
- }
- }
- if(log_texture_traffic)
- {
- U32 old_y = ypos ;
- for(S32 i = LLViewerTexture::BOOST_NONE; i < LLViewerTexture::MAX_GL_IMAGE_CATEGORY; i++)
- {
- if(gTotalTextureBytesPerBoostLevel[i] > 0)
- {
- addText(xpos, ypos, llformat("Boost_Level %d: %.3f MB", i, (F32)gTotalTextureBytesPerBoostLevel[i] / (1024 * 1024)));
- ypos += y_inc;
- }
- }
- if(ypos != old_y)
- {
- addText(xpos, ypos, "Network traffic for textures:");
- ypos += y_inc;
- }
- }
-
- if (gSavedSettings.getBOOL("DebugShowTextureInfo"))
- {
- LLViewerObject* objectp = NULL ;
- //objectp = = gAgentCamera.getFocusObject();
-
- LLSelectNode* nodep = LLSelectMgr::instance().getHoverNode();
- if (nodep)
- {
- objectp = nodep->getObject();
- }
- if (objectp && !objectp->isDead())
- {
- S32 num_faces = objectp->mDrawable->getNumFaces() ;
-
- for(S32 i = 0 ; i < num_faces; i++)
- {
- LLFace* facep = objectp->mDrawable->getFace(i) ;
- if(facep)
- {
- //addText(xpos, ypos, llformat("ts_min: %.3f ts_max: %.3f tt_min: %.3f tt_max: %.3f", facep->mTexExtents[0].mV[0], facep->mTexExtents[1].mV[0],
- // facep->mTexExtents[0].mV[1], facep->mTexExtents[1].mV[1]));
- //ypos += y_inc;
-
- addText(xpos, ypos, llformat("v_size: %.3f: p_size: %.3f", facep->getVirtualSize(), facep->getPixelArea()));
- ypos += y_inc;
-
- //const LLTextureEntry *tep = facep->getTextureEntry();
- //if(tep)
- //{
- // addText(xpos, ypos, llformat("scale_s: %.3f: scale_t: %.3f", tep->mScaleS, tep->mScaleT)) ;
- // ypos += y_inc;
- //}
-
- LLViewerTexture* tex = facep->getTexture() ;
- if(tex)
- {
- addText(xpos, ypos, llformat("ID: %s v_size: %.3f", tex->getID().asString().c_str(), tex->getMaxVirtualSize()));
- ypos += y_inc;
- }
- }
- }
- }
- }
- }
-
- void draw()
- {
- for (line_list_t::iterator iter = mLineList.begin();
- iter != mLineList.end(); ++iter)
- {
- const Line& line = *iter;
- LLFontGL::getFontMonospace()->renderUTF8(line.text, 0, (F32)line.x, (F32)line.y, mTextColor,
- LLFontGL::LEFT, LLFontGL::TOP,
- LLFontGL::NORMAL, LLFontGL::NO_SHADOW, S32_MAX, S32_MAX, NULL, FALSE);
- }
- mLineList.clear();
- }
-
-};
-
-void LLViewerWindow::updateDebugText()
-{
- mDebugText->update();
-}
-
-////////////////////////////////////////////////////////////////////////////
-//
-// LLViewerWindow
-//
-
-BOOL LLViewerWindow::handleAnyMouseClick(LLWindow *window, LLCoordGL pos, MASK mask, LLMouseHandler::EClickType clicktype, BOOL down)
-{
- const char* buttonname = "";
- const char* buttonstatestr = "";
- S32 x = pos.mX;
- S32 y = pos.mY;
- x = llround((F32)x / mDisplayScale.mV[VX]);
- y = llround((F32)y / mDisplayScale.mV[VY]);
-
- // only send mouse clicks to UI if UI is visible
- if(gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
- {
-
- if (down)
- {
- buttonstatestr = "down" ;
- }
- else
- {
- buttonstatestr = "up" ;
- }
-
- switch (clicktype)
- {
- case LLMouseHandler::CLICK_LEFT:
- mLeftMouseDown = down;
- buttonname = "Left";
- break;
- case LLMouseHandler::CLICK_RIGHT:
- mRightMouseDown = down;
- buttonname = "Right";
- break;
- case LLMouseHandler::CLICK_MIDDLE:
- mMiddleMouseDown = down;
- buttonname = "Middle";
- break;
- case LLMouseHandler::CLICK_DOUBLELEFT:
- mLeftMouseDown = down;
- buttonname = "Left Double Click";
- break;
- }
-
- LLView::sMouseHandlerMessage.clear();
-
- if (gMenuBarView)
- {
- // stop ALT-key access to menu
- gMenuBarView->resetMenuTrigger();
- }
-
- if (gDebugClicks)
- {
- llinfos << "ViewerWindow " << buttonname << " mouse " << buttonstatestr << " at " << x << "," << y << llendl;
- }
-
- // Make sure we get a corresponding mouseup event, even if the mouse leaves the window
- if (down)
- mWindow->captureMouse();
- else
- mWindow->releaseMouse();
-
- // Indicate mouse was active
- LLUI::resetMouseIdleTimer();
-
- // Don't let the user move the mouse out of the window until mouse up.
- if( LLToolMgr::getInstance()->getCurrentTool()->clipMouseWhenDown() )
- {
- mWindow->setMouseClipping(down);
- }
-
- LLMouseHandler* mouse_captor = gFocusMgr.getMouseCapture();
- if( mouse_captor )
- {
- S32 local_x;
- S32 local_y;
- mouse_captor->screenPointToLocal( x, y, &local_x, &local_y );
- if (LLView::sDebugMouseHandling)
- {
- llinfos << buttonname << " Mouse " << buttonstatestr << " handled by captor " << mouse_captor->getName() << llendl;
- }
- return mouse_captor->handleAnyMouseClick(local_x, local_y, mask, clicktype, down);
- }
-
- // Topmost view gets a chance before the hierarchy
- //LLUICtrl* top_ctrl = gFocusMgr.getTopCtrl();
- //if (top_ctrl)
- //{
- // S32 local_x, local_y;
- // top_ctrl->screenPointToLocal( x, y, &local_x, &local_y );
- // if (top_ctrl->pointInView(local_x, local_y))
- // {
- // return top_ctrl->handleAnyMouseClick(local_x, local_y, mask, clicktype, down) ;
- // }
- // else
- // {
- // if (down)
- // {
- // gFocusMgr.setTopCtrl(NULL);
- // }
- // }
- //}
-
- // Give the UI views a chance to process the click
- if( mRootView->handleAnyMouseClick(x, y, mask, clicktype, down) )
- {
- if (LLView::sDebugMouseHandling)
- {
- llinfos << buttonname << " Mouse " << buttonstatestr << " " << LLView::sMouseHandlerMessage << llendl;
- }
- return TRUE;
- }
- else if (LLView::sDebugMouseHandling)
- {
- llinfos << buttonname << " Mouse " << buttonstatestr << " not handled by view" << llendl;
- }
- }
-
- // Do not allow tool manager to handle mouseclicks if we have disconnected
- if(!gDisconnected && LLToolMgr::getInstance()->getCurrentTool()->handleAnyMouseClick( x, y, mask, clicktype, down ) )
- {
- return TRUE;
- }
-
-
- // If we got this far on a down-click, it wasn't handled.
- // Up-clicks, though, are always handled as far as the OS is concerned.
- BOOL default_rtn = !down;
- return default_rtn;
-}
-
-BOOL LLViewerWindow::handleMouseDown(LLWindow *window, LLCoordGL pos, MASK mask)
-{
- BOOL down = TRUE;
- return handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_LEFT,down);
-}
-
-BOOL LLViewerWindow::handleDoubleClick(LLWindow *window, LLCoordGL pos, MASK mask)
-{
- // try handling as a double-click first, then a single-click if that
- // wasn't handled.
- BOOL down = TRUE;
- if (handleAnyMouseClick(window, pos, mask,
- LLMouseHandler::CLICK_DOUBLELEFT, down))
- {
- return TRUE;
- }
- return handleMouseDown(window, pos, mask);
-}
-
-BOOL LLViewerWindow::handleMouseUp(LLWindow *window, LLCoordGL pos, MASK mask)
-{
- BOOL down = FALSE;
- return handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_LEFT,down);
-}
-
-
-BOOL LLViewerWindow::handleRightMouseDown(LLWindow *window, LLCoordGL pos, MASK mask)
-{
- S32 x = pos.mX;
- S32 y = pos.mY;
- x = llround((F32)x / mDisplayScale.mV[VX]);
- y = llround((F32)y / mDisplayScale.mV[VY]);
-
- BOOL down = TRUE;
- BOOL handle = handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_RIGHT,down);
- if (handle)
- return handle;
-
- // *HACK: this should be rolled into the composite tool logic, not
- // hardcoded at the top level.
- if (CAMERA_MODE_CUSTOMIZE_AVATAR != gAgentCamera.getCameraMode() && LLToolMgr::getInstance()->getCurrentTool() != LLToolPie::getInstance())
- {
- // If the current tool didn't process the click, we should show
- // the pie menu. This can be done by passing the event to the pie
- // menu tool.
- LLToolPie::getInstance()->handleRightMouseDown(x, y, mask);
- // show_context_menu( x, y, mask );
- }
-
- return TRUE;
-}
-
-BOOL LLViewerWindow::handleRightMouseUp(LLWindow *window, LLCoordGL pos, MASK mask)
-{
- BOOL down = FALSE;
- return handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_RIGHT,down);
-}
-
-BOOL LLViewerWindow::handleMiddleMouseDown(LLWindow *window, LLCoordGL pos, MASK mask)
-{
- BOOL down = TRUE;
- LLVoiceClient::getInstance()->middleMouseState(true);
- handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_MIDDLE,down);
-
- // Always handled as far as the OS is concerned.
- return TRUE;
-}
-
-LLWindowCallbacks::DragNDropResult LLViewerWindow::handleDragNDrop( LLWindow *window, LLCoordGL pos, MASK mask, LLWindowCallbacks::DragNDropAction action, std::string data)
-{
- LLWindowCallbacks::DragNDropResult result = LLWindowCallbacks::DND_NONE;
-
- const bool prim_media_dnd_enabled = gSavedSettings.getBOOL("PrimMediaDragNDrop");
- const bool slurl_dnd_enabled = gSavedSettings.getBOOL("SLURLDragNDrop");
-
- if ( prim_media_dnd_enabled || slurl_dnd_enabled )
- {
- switch(action)
- {
- // Much of the handling for these two cases is the same.
- case LLWindowCallbacks::DNDA_TRACK:
- case LLWindowCallbacks::DNDA_DROPPED:
- case LLWindowCallbacks::DNDA_START_TRACKING:
- {
- bool drop = (LLWindowCallbacks::DNDA_DROPPED == action);
-
- if (slurl_dnd_enabled)
- {
- LLSLURL dropped_slurl(data);
- if(dropped_slurl.isSpatial())
- {
- if (drop)
- {
- LLURLDispatcher::dispatch( dropped_slurl.getSLURLString(), NULL, true );
- return LLWindowCallbacks::DND_MOVE;
- }
- return LLWindowCallbacks::DND_COPY;
- }
- }
-
- if (prim_media_dnd_enabled)
- {
- LLPickInfo pick_info = pickImmediate( pos.mX, pos.mY, TRUE /*BOOL pick_transparent*/ );
-
- LLUUID object_id = pick_info.getObjectID();
- S32 object_face = pick_info.mObjectFace;
- std::string url = data;
-
- lldebugs << "Object: picked at " << pos.mX << ", " << pos.mY << " - face = " << object_face << " - URL = " << url << llendl;
-
- LLVOVolume *obj = dynamic_cast<LLVOVolume*>(static_cast<LLViewerObject*>(pick_info.getObject()));
-
- if (obj && !obj->getRegion()->getCapability("ObjectMedia").empty())
- {
- LLTextureEntry *te = obj->getTE(object_face);
-
- // can modify URL if we can modify the object or we have navigate permissions
- bool allow_modify_url = obj->permModify() || obj->hasMediaPermission( te->getMediaData(), LLVOVolume::MEDIA_PERM_INTERACT );
-
- if (te && allow_modify_url )
- {
- if (drop)
- {
- // object does NOT have media already
- if ( ! te->hasMedia() )
- {
- // we are allowed to modify the object
- if ( obj->permModify() )
- {
- // Create new media entry
- LLSD media_data;
- // XXX Should we really do Home URL too?
- media_data[LLMediaEntry::HOME_URL_KEY] = url;
- media_data[LLMediaEntry::CURRENT_URL_KEY] = url;
- media_data[LLMediaEntry::AUTO_PLAY_KEY] = true;
- obj->syncMediaData(object_face, media_data, true, true);
- // XXX This shouldn't be necessary, should it ?!?
- if (obj->getMediaImpl(object_face))
- obj->getMediaImpl(object_face)->navigateReload();
- obj->sendMediaDataUpdate();
-
- result = LLWindowCallbacks::DND_COPY;
- }
- }
- else
- // object HAS media already
- {
- // URL passes the whitelist
- if (te->getMediaData()->checkCandidateUrl( url ) )
- {
- // just navigate to the URL
- if (obj->getMediaImpl(object_face))
- {
- obj->getMediaImpl(object_face)->navigateTo(url);
- }
- else
- {
- // This is very strange. Navigation should
- // happen via the Impl, but we don't have one.
- // This sends it to the server, which /should/
- // trigger us getting it. Hopefully.
- LLSD media_data;
- media_data[LLMediaEntry::CURRENT_URL_KEY] = url;
- obj->syncMediaData(object_face, media_data, true, true);
- obj->sendMediaDataUpdate();
- }
- result = LLWindowCallbacks::DND_LINK;
-
- }
- }
- LLSelectMgr::getInstance()->unhighlightObjectOnly(mDragHoveredObject);
- mDragHoveredObject = NULL;
-
- }
- else
- {
- // Check the whitelist, if there's media (otherwise just show it)
- if (te->getMediaData() == NULL || te->getMediaData()->checkCandidateUrl(url))
- {
- if ( obj != mDragHoveredObject)
- {
- // Highlight the dragged object
- LLSelectMgr::getInstance()->unhighlightObjectOnly(mDragHoveredObject);
- mDragHoveredObject = obj;
- LLSelectMgr::getInstance()->highlightObjectOnly(mDragHoveredObject);
- }
- result = (! te->hasMedia()) ? LLWindowCallbacks::DND_COPY : LLWindowCallbacks::DND_LINK;
-
- }
- }
- }
- }
- }
- }
- break;
-
- case LLWindowCallbacks::DNDA_STOP_TRACKING:
- // The cleanup case below will make sure things are unhilighted if necessary.
- break;
- }
-
- if (prim_media_dnd_enabled &&
- result == LLWindowCallbacks::DND_NONE && !mDragHoveredObject.isNull())
- {
- LLSelectMgr::getInstance()->unhighlightObjectOnly(mDragHoveredObject);
- mDragHoveredObject = NULL;
- }
- }
-
- return result;
-}
-
-BOOL LLViewerWindow::handleMiddleMouseUp(LLWindow *window, LLCoordGL pos, MASK mask)
-{
- BOOL down = FALSE;
- LLVoiceClient::getInstance()->middleMouseState(false);
- handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_MIDDLE,down);
-
- // Always handled as far as the OS is concerned.
- return TRUE;
-}
-
-// WARNING: this is potentially called multiple times per frame
-void LLViewerWindow::handleMouseMove(LLWindow *window, LLCoordGL pos, MASK mask)
-{
- S32 x = pos.mX;
- S32 y = pos.mY;
-
- x = llround((F32)x / mDisplayScale.mV[VX]);
- y = llround((F32)y / mDisplayScale.mV[VY]);
-
- mMouseInWindow = TRUE;
-
- // Save mouse point for access during idle() and display()
-
- LLCoordGL mouse_point(x, y);
-
- if (mouse_point != mCurrentMousePoint)
- {
- LLUI::resetMouseIdleTimer();
- }
-
- saveLastMouse(mouse_point);
-
- mWindow->showCursorFromMouseMove();
-
- if (gAwayTimer.getElapsedTimeF32() > MIN_AFK_TIME)
- {
- gAgent.clearAFK();
- }
-}
-
-void LLViewerWindow::handleMouseLeave(LLWindow *window)
-{
- // Note: we won't get this if we have captured the mouse.
- llassert( gFocusMgr.getMouseCapture() == NULL );
- mMouseInWindow = FALSE;
- LLToolTipMgr::instance().blockToolTips();
-}
-
-BOOL LLViewerWindow::handleCloseRequest(LLWindow *window)
-{
- // User has indicated they want to close, but we may need to ask
- // about modified documents.
- LLAppViewer::instance()->userQuit();
- // Don't quit immediately
- return FALSE;
-}
-
-void LLViewerWindow::handleQuit(LLWindow *window)
-{
- LLAppViewer::instance()->forceQuit();
-}
-
-void LLViewerWindow::handleResize(LLWindow *window, S32 width, S32 height)
-{
- reshape(width, height);
- mResDirty = true;
-}
-
-// The top-level window has gained focus (e.g. via ALT-TAB)
-void LLViewerWindow::handleFocus(LLWindow *window)
-{
- gFocusMgr.setAppHasFocus(TRUE);
- LLModalDialog::onAppFocusGained();
-
- gAgent.onAppFocusGained();
- LLToolMgr::getInstance()->onAppFocusGained();
-
- // See if we're coming in with modifier keys held down
- if (gKeyboard)
- {
- gKeyboard->resetMaskKeys();
- }
-
- // resume foreground running timer
- // since we artifically limit framerate when not frontmost
- gForegroundTime.unpause();
-}
-
-// The top-level window has lost focus (e.g. via ALT-TAB)
-void LLViewerWindow::handleFocusLost(LLWindow *window)
-{
- gFocusMgr.setAppHasFocus(FALSE);
- //LLModalDialog::onAppFocusLost();
- LLToolMgr::getInstance()->onAppFocusLost();
- gFocusMgr.setMouseCapture( NULL );
-
- if (gMenuBarView)
- {
- // stop ALT-key access to menu
- gMenuBarView->resetMenuTrigger();
- }
-
- // restore mouse cursor
- showCursor();
- getWindow()->setMouseClipping(FALSE);
-
- // If losing focus while keys are down, reset them.
- if (gKeyboard)
- {
- gKeyboard->resetKeys();
- }
-
- // pause timer that tracks total foreground running time
- gForegroundTime.pause();
-}
-
-
-BOOL LLViewerWindow::handleTranslatedKeyDown(KEY key, MASK mask, BOOL repeated)
-{
- // Let the voice chat code check for its PTT key. Note that this never affects event processing.
- LLVoiceClient::getInstance()->keyDown(key, mask);
-
- if (gAwayTimer.getElapsedTimeF32() > MIN_AFK_TIME)
- {
- gAgent.clearAFK();
- }
-
- // *NOTE: We want to interpret KEY_RETURN later when it arrives as
- // a Unicode char, not as a keydown. Otherwise when client frame
- // rate is really low, hitting return sends your chat text before
- // it's all entered/processed.
- if (key == KEY_RETURN && mask == MASK_NONE)
- {
- return FALSE;
- }
-
- return gViewerKeyboard.handleKey(key, mask, repeated);
-}
-
-BOOL LLViewerWindow::handleTranslatedKeyUp(KEY key, MASK mask)
-{
- // Let the voice chat code check for its PTT key. Note that this never affects event processing.
- LLVoiceClient::getInstance()->keyUp(key, mask);
-
- return FALSE;
-}
-
-
-void LLViewerWindow::handleScanKey(KEY key, BOOL key_down, BOOL key_up, BOOL key_level)
-{
- LLViewerJoystick::getInstance()->setCameraNeedsUpdate(true);
- return gViewerKeyboard.scanKey(key, key_down, key_up, key_level);
-}
-
-
-
-
-BOOL LLViewerWindow::handleActivate(LLWindow *window, BOOL activated)
-{
- if (activated)
- {
- mActive = TRUE;
- send_agent_resume();
- gAgent.clearAFK();
-
- // Unmute audio
- audio_update_volume();
- }
- else
- {
- mActive = FALSE;
-
- if (gSavedSettings.getS32("AFKTimeout"))
- {
- gAgent.setAFK();
- }
-
- // SL-53351: Make sure we're not in mouselook when minimised, to prevent control issues
- if (gAgentCamera.getCameraMode() == CAMERA_MODE_MOUSELOOK)
- {
- gAgentCamera.changeCameraToDefault();
- }
-
- send_agent_pause();
-
- // Mute audio
- audio_update_volume();
- }
- return TRUE;
-}
-
-BOOL LLViewerWindow::handleActivateApp(LLWindow *window, BOOL activating)
-{
- //if (!activating) gAgentCamera.changeCameraToDefault();
-
- LLViewerJoystick::getInstance()->setNeedsReset(true);
- return FALSE;
-}
-
-
-void LLViewerWindow::handleMenuSelect(LLWindow *window, S32 menu_item)
-{
-}
-
-
-BOOL LLViewerWindow::handlePaint(LLWindow *window, S32 x, S32 y, S32 width, S32 height)
-{
-#if LL_WINDOWS
- if (gNoRender)
- {
- HWND window_handle = (HWND)window->getPlatformWindow();
- PAINTSTRUCT ps;
- HDC hdc;
-
- RECT wnd_rect;
- wnd_rect.left = 0;
- wnd_rect.top = 0;
- wnd_rect.bottom = 200;
- wnd_rect.right = 500;
-
- hdc = BeginPaint(window_handle, &ps);
- //SetBKColor(hdc, RGB(255, 255, 255));
- FillRect(hdc, &wnd_rect, CreateSolidBrush(RGB(255, 255, 255)));
-
- std::string temp_str;
- temp_str = llformat( "FPS %3.1f Phy FPS %2.1f Time Dil %1.3f", /* Flawfinder: ignore */
- LLViewerStats::getInstance()->mFPSStat.getMeanPerSec(),
- LLViewerStats::getInstance()->mSimPhysicsFPS.getPrev(0),
- LLViewerStats::getInstance()->mSimTimeDilation.getPrev(0));
- S32 len = temp_str.length();
- TextOutA(hdc, 0, 0, temp_str.c_str(), len);
-
-
- LLVector3d pos_global = gAgent.getPositionGlobal();
- temp_str = llformat( "Avatar pos %6.1lf %6.1lf %6.1lf", pos_global.mdV[0], pos_global.mdV[1], pos_global.mdV[2]);
- len = temp_str.length();
- TextOutA(hdc, 0, 25, temp_str.c_str(), len);
-
- TextOutA(hdc, 0, 50, "Set \"DisableRendering FALSE\" in settings.ini file to reenable", 61);
- EndPaint(window_handle, &ps);
- return TRUE;
- }
-#endif
- return FALSE;
-}
-
-
-void LLViewerWindow::handleScrollWheel(LLWindow *window, S32 clicks)
-{
- handleScrollWheel( clicks );
-}
-
-void LLViewerWindow::handleWindowBlock(LLWindow *window)
-{
- send_agent_pause();
-}
-
-void LLViewerWindow::handleWindowUnblock(LLWindow *window)
-{
- send_agent_resume();
-}
-
-void LLViewerWindow::handleDataCopy(LLWindow *window, S32 data_type, void *data)
-{
- const S32 SLURL_MESSAGE_TYPE = 0;
- switch (data_type)
- {
- case SLURL_MESSAGE_TYPE:
- // received URL
- std::string url = (const char*)data;
- LLMediaCtrl* web = NULL;
- const bool trusted_browser = false;
- if (LLURLDispatcher::dispatch(url, web, trusted_browser))
- {
- // bring window to foreground, as it has just been "launched" from a URL
- mWindow->bringToFront();
- }
- break;
- }
-}
-
-BOOL LLViewerWindow::handleTimerEvent(LLWindow *window)
-{
- if (LLViewerJoystick::getInstance()->getOverrideCamera())
- {
- LLViewerJoystick::getInstance()->updateStatus();
- return TRUE;
- }
- return FALSE;
-}
-
-BOOL LLViewerWindow::handleDeviceChange(LLWindow *window)
-{
- // give a chance to use a joystick after startup (hot-plugging)
- if (!LLViewerJoystick::getInstance()->isJoystickInitialized() )
- {
- LLViewerJoystick::getInstance()->init(true);
- return TRUE;
- }
- return FALSE;
-}
-
-void LLViewerWindow::handlePingWatchdog(LLWindow *window, const char * msg)
-{
- LLAppViewer::instance()->pingMainloopTimeout(msg);
-}
-
-
-void LLViewerWindow::handleResumeWatchdog(LLWindow *window)
-{
- LLAppViewer::instance()->resumeMainloopTimeout();
-}
-
-void LLViewerWindow::handlePauseWatchdog(LLWindow *window)
-{
- LLAppViewer::instance()->pauseMainloopTimeout();
-}
-
-//virtual
-std::string LLViewerWindow::translateString(const char* tag)
-{
- return LLTrans::getString( std::string(tag) );
-}
-
-//virtual
-std::string LLViewerWindow::translateString(const char* tag,
- const std::map<std::string, std::string>& args)
-{
- // LLTrans uses a special subclass of std::string for format maps,
- // but we must use std::map<> in these callbacks, otherwise we create
- // a dependency between LLWindow and LLFormatMapString. So copy the data.
- LLStringUtil::format_map_t args_copy;
- std::map<std::string,std::string>::const_iterator it = args.begin();
- for ( ; it != args.end(); ++it)
- {
- args_copy[it->first] = it->second;
- }
- return LLTrans::getString( std::string(tag), args_copy);
-}
-
-//
-// Classes
-//
-LLViewerWindow::LLViewerWindow(
- const std::string& title, const std::string& name,
- S32 x, S32 y,
- S32 width, S32 height,
- BOOL fullscreen, BOOL ignore_pixel_depth) // fullscreen is no longer used
- :
- mWindow(NULL),
- mActive(TRUE),
- mWindowRectRaw(0, height, width, 0),
- mWindowRectScaled(0, height, width, 0),
- mWorldViewRectRaw(0, height, width, 0),
- mLeftMouseDown(FALSE),
- mMiddleMouseDown(FALSE),
- mRightMouseDown(FALSE),
- mMouseInWindow( FALSE ),
- mLastMask( MASK_NONE ),
- mToolStored( NULL ),
- mHideCursorPermanent( FALSE ),
- mCursorHidden(FALSE),
- mIgnoreActivate( FALSE ),
- mResDirty(false),
- mStatesDirty(false),
- mCurrResolutionIndex(0),
- mViewerWindowListener(new LLViewerWindowListener(this)),
- mProgressView(NULL)
-{
- LLNotificationChannel::buildChannel("VW_alerts", "Visible", LLNotificationFilters::filterBy<std::string>(&LLNotification::getType, "alert"));
- LLNotificationChannel::buildChannel("VW_alertmodal", "Visible", LLNotificationFilters::filterBy<std::string>(&LLNotification::getType, "alertmodal"));
-
- LLNotifications::instance().getChannel("VW_alerts")->connectChanged(&LLViewerWindow::onAlert);
- LLNotifications::instance().getChannel("VW_alertmodal")->connectChanged(&LLViewerWindow::onAlert);
- LLNotifications::instance().setIgnoreAllNotifications(gSavedSettings.getBOOL("IgnoreAllNotifications"));
- llinfos << "NOTE: ALL NOTIFICATIONS THAT OCCUR WILL GET ADDED TO IGNORE LIST FOR LATER RUNS." << llendl;
-
- // Default to application directory.
- LLViewerWindow::sSnapshotBaseName = "Snapshot";
- LLViewerWindow::sMovieBaseName = "SLmovie";
- resetSnapshotLoc();
-
- // create window
- mWindow = LLWindowManager::createWindow(this,
- title, name, x, y, width, height, 0,
- fullscreen,
- gNoRender,
- gSavedSettings.getBOOL("DisableVerticalSync"),
- !gNoRender,
- ignore_pixel_depth,
- gSavedSettings.getBOOL("RenderUseFBO") ? 0 : gSavedSettings.getU32("RenderFSAASamples")); //don't use window level anti-aliasing if FBOs are enabled
-
- if (!LLAppViewer::instance()->restoreErrorTrap())
- {
- LL_WARNS("Window") << " Someone took over my signal/exception handler (post createWindow)!" << LL_ENDL;
- }
-
- LLCoordScreen scr;
- mWindow->getSize(&scr);
-
- if(fullscreen && ( scr.mX!=width || scr.mY!=height))
- {
- llwarns << "Fullscreen has forced us in to a different resolution now using "<<scr.mX<<" x "<<scr.mY<<llendl;
- gSavedSettings.setS32("FullScreenWidth",scr.mX);
- gSavedSettings.setS32("FullScreenHeight",scr.mY);
- }
-
- if (NULL == mWindow)
- {
- LLSplashScreen::update(LLTrans::getString("ShuttingDown"));
-#if LL_LINUX || LL_SOLARIS
- llwarns << "Unable to create window, be sure screen is set at 32-bit color and your graphics driver is configured correctly. See README-linux.txt or README-solaris.txt for further information."
- << llendl;
-#else
- LL_WARNS("Window") << "Unable to create window, be sure screen is set at 32-bit color in Control Panels->Display->Settings"
- << LL_ENDL;
-#endif
- LLAppViewer::instance()->fastQuit(1);
- }
-
- // Get the real window rect the window was created with (since there are various OS-dependent reasons why
- // the size of a window or fullscreen context may have been adjusted slightly...)
- F32 ui_scale_factor = gSavedSettings.getF32("UIScaleFactor");
-
- mDisplayScale.setVec(llmax(1.f / mWindow->getPixelAspectRatio(), 1.f), llmax(mWindow->getPixelAspectRatio(), 1.f));
- mDisplayScale *= ui_scale_factor;
- LLUI::setScaleFactor(mDisplayScale);
-
- {
- LLCoordWindow size;
- mWindow->getSize(&size);
- mWindowRectRaw.set(0, size.mY, size.mX, 0);
- mWindowRectScaled.set(0, llround((F32)size.mY / mDisplayScale.mV[VY]), llround((F32)size.mX / mDisplayScale.mV[VX]), 0);
- }
-
- LLFontManager::initClass();
-
- //
- // We want to set this stuff up BEFORE we initialize the pipeline, so we can turn off
- // stuff like AGP if we think that it'll crash the viewer.
- //
- LL_DEBUGS("Window") << "Loading feature tables." << LL_ENDL;
-
- LLFeatureManager::getInstance()->init();
-
- // Initialize OpenGL Renderer
- if (!LLFeatureManager::getInstance()->isFeatureAvailable("RenderVBOEnable") ||
- !gGLManager.mHasVertexBufferObject)
- {
- gSavedSettings.setBOOL("RenderVBOEnable", FALSE);
- }
- LLVertexBuffer::initClass(gSavedSettings.getBOOL("RenderVBOEnable"), gSavedSettings.getBOOL("RenderVBOMappingDisable"));
-
- if (LLFeatureManager::getInstance()->isSafe()
- || (gSavedSettings.getS32("LastFeatureVersion") != LLFeatureManager::getInstance()->getVersion())
- || (gSavedSettings.getS32("LastGPUClass") != LLFeatureManager::getInstance()->getGPUClass())
- || (gSavedSettings.getBOOL("ProbeHardwareOnStartup")))
- {
- LLFeatureManager::getInstance()->applyRecommendedSettings();
- gSavedSettings.setBOOL("ProbeHardwareOnStartup", FALSE);
- }
-
- if (!gGLManager.mHasDepthClamp)
- {
- LL_INFOS("RenderInit") << "Missing feature GL_ARB_depth_clamp. Void water might disappear in rare cases." << LL_ENDL;
- }
-
- // If we crashed while initializng GL stuff last time, disable certain features
- if (gSavedSettings.getBOOL("RenderInitError"))
- {
- mInitAlert = "DisplaySettingsNoShaders";
- LLFeatureManager::getInstance()->setGraphicsLevel(0, false);
- gSavedSettings.setU32("RenderQualityPerformance", 0);
- }
-
- // Init the image list. Must happen after GL is initialized and before the images that
- // LLViewerWindow needs are requested.
- LLImageGL::initClass(LLViewerTexture::MAX_GL_IMAGE_CATEGORY) ;
- gTextureList.init();
- LLViewerTextureManager::init() ;
- gBumpImageList.init();
-
- // Init font system, but don't actually load the fonts yet
- // because our window isn't onscreen and they take several
- // seconds to parse.
- LLFontGL::initClass( gSavedSettings.getF32("FontScreenDPI"),
- mDisplayScale.mV[VX],
- mDisplayScale.mV[VY],
- gDirUtilp->getAppRODataDir(),
- LLUI::getXUIPaths());
-
- // Create container for all sub-views
- LLView::Params rvp;
- rvp.name("root");
- rvp.rect(mWindowRectScaled);
- rvp.mouse_opaque(false);
- rvp.follows.flags(FOLLOWS_NONE);
- mRootView = LLUICtrlFactory::create<LLRootView>(rvp);
- LLUI::setRootView(mRootView);
-
- // Make avatar head look forward at start
- mCurrentMousePoint.mX = getWindowWidthScaled() / 2;
- mCurrentMousePoint.mY = getWindowHeightScaled() / 2;
-
- gShowOverlayTitle = gSavedSettings.getBOOL("ShowOverlayTitle");
- mOverlayTitle = gSavedSettings.getString("OverlayTitle");
- // Can't have spaces in settings.ini strings, so use underscores instead and convert them.
- LLStringUtil::replaceChar(mOverlayTitle, '_', ' ');
-
- // sync the keyboard's setting with the saved setting
- gSavedSettings.getControl("NumpadControl")->firePropertyChanged();
-
- mDebugText = new LLDebugText(this);
-
- mWorldViewRectScaled = calcScaledRect(mWorldViewRectRaw, mDisplayScale);
-}
-
-void LLViewerWindow::initGLDefaults()
-{
- gGL.setSceneBlendType(LLRender::BT_ALPHA);
- glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE );
-
- F32 ambient[4] = {0.f,0.f,0.f,0.f };
- F32 diffuse[4] = {1.f,1.f,1.f,1.f };
- glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,ambient);
- glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,diffuse);
-
- glPixelStorei(GL_PACK_ALIGNMENT,1);
- glPixelStorei(GL_UNPACK_ALIGNMENT,1);
-
- gGL.getTexUnit(0)->enable(LLTexUnit::TT_TEXTURE);
-
- // lights for objects
- glShadeModel( GL_SMOOTH );
-
- glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
-
- gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
-
- glCullFace(GL_BACK);
-
- // RN: Need this for translation and stretch manip.
- gCone.prerender();
- gBox.prerender();
- gSphere.prerender();
- gCylinder.prerender();
-}
-
-struct MainPanel : public LLPanel
-{
-};
-
-void LLViewerWindow::initBase()
-{
- S32 height = getWindowHeightScaled();
- S32 width = getWindowWidthScaled();
-
- LLRect full_window(0, height, width, 0);
-
- ////////////////////
- //
- // Set the gamma
- //
-
- F32 gamma = gSavedSettings.getF32("RenderGamma");
- if (gamma != 0.0f)
- {
- getWindow()->setGamma(gamma);
- }
-
- // Create global views
-
- // Create the floater view at the start so that other views can add children to it.
- // (But wait to add it as a child of the root view so that it will be in front of the
- // other views.)
- MainPanel* main_view = new MainPanel();
- main_view->buildFromFile("main_view.xml");
- main_view->setShape(full_window);
- getRootView()->addChild(main_view);
-
- // placeholder widget that controls where "world" is rendered
- mWorldViewPlaceholder = main_view->getChildView("world_view_rect")->getHandle();
- mNonSideTrayView = main_view->getChildView("non_side_tray_view")->getHandle();
- mFloaterViewHolder = main_view->getChildView("floater_view_holder")->getHandle();
- mPopupView = main_view->getChild<LLPopupView>("popup_holder");
- mHintHolder = main_view->getChild<LLView>("hint_holder")->getHandle();
- mLoginPanelHolder = main_view->getChild<LLView>("login_panel_holder")->getHandle();
-
- // Constrain floaters to inside the menu and status bar regions.
- gFloaterView = main_view->getChild<LLFloaterView>("Floater View");
- gFloaterView->setFloaterSnapView(main_view->getChild<LLView>("floater_snap_region")->getHandle());
- gSnapshotFloaterView = main_view->getChild<LLSnapshotFloaterView>("Snapshot Floater View");
-
-
- // Console
- llassert( !gConsole );
- LLConsole::Params cp;
- cp.name("console");
- cp.max_lines(gSavedSettings.getS32("ConsoleBufferSize"));
- cp.rect(getChatConsoleRect());
- cp.persist_time(gSavedSettings.getF32("ChatPersistTime"));
- cp.font_size_index(gSavedSettings.getS32("ChatFontSize"));
- cp.follows.flags(FOLLOWS_LEFT | FOLLOWS_RIGHT | FOLLOWS_BOTTOM);
- gConsole = LLUICtrlFactory::create<LLConsole>(cp);
- getRootView()->addChild(gConsole);
-
- // optionally forward warnings to chat console/chat floater
- // for qa runs and dev builds
-#if !LL_RELEASE_FOR_DOWNLOAD
- LLError::addRecorder(RecordToChatConsole::getInstance());
-#else
- if(gSavedSettings.getBOOL("QAMode"))
- {
- LLError::addRecorder(RecordToChatConsole::getInstance());
- }
-#endif
-
- gDebugView = getRootView()->getChild<LLDebugView>("DebugView");
- gDebugView->init();
- gToolTipView = getRootView()->getChild<LLToolTipView>("tooltip view");
-
- // Initialize busy response message when logged in
- LLAppViewer::instance()->setOnLoginCompletedCallback(boost::bind(&LLFloaterPreference::initBusyResponse));
-
- // Add the progress bar view (startup view), which overrides everything
- mProgressView = getRootView()->findChild<LLProgressView>("progress_view");
- setShowProgress(FALSE);
- setProgressCancelButtonVisible(FALSE);
-
- gMenuHolder = getRootView()->getChild<LLViewerMenuHolderGL>("Menu Holder");
-
- LLMenuGL::sMenuContainer = gMenuHolder;
-
-}
-
-void LLViewerWindow::initWorldUI()
-{
- S32 height = mRootView->getRect().getHeight();
- S32 width = mRootView->getRect().getWidth();
- LLRect full_window(0, height, width, 0);
-
-
- gIMMgr = LLIMMgr::getInstance();
-
- //getRootView()->sendChildToFront(gFloaterView);
- //getRootView()->sendChildToFront(gSnapshotFloaterView);
-
- // new bottom panel
- LLPanel* bottom_tray_container = getRootView()->getChild<LLPanel>("bottom_tray_container");
- LLBottomTray* bottom_tray = LLBottomTray::getInstance();
- bottom_tray->setShape(bottom_tray_container->getLocalRect());
- bottom_tray->setFollowsAll();
- bottom_tray_container->addChild(bottom_tray);
- bottom_tray_container->setVisible(TRUE);
-
- LLRect morph_view_rect = full_window;
- morph_view_rect.stretch( -STATUS_BAR_HEIGHT );
- morph_view_rect.mTop = full_window.mTop - 32;
- LLMorphView::Params mvp;
- mvp.name("MorphView");
- mvp.rect(morph_view_rect);
- mvp.visible(false);
- gMorphView = LLUICtrlFactory::create<LLMorphView>(mvp);
- getRootView()->addChild(gMorphView);
-
- LLWorldMapView::initClass();
-
- // Force gFloaterWorldMap to initialize
- LLFloaterReg::getInstance("world_map");
-
- // Force gFloaterTools to initialize
- LLFloaterReg::getInstance("build");
- LLFloaterReg::hideInstance("build");
-
- // Status bar
- LLPanel* status_bar_container = getRootView()->getChild<LLPanel>("status_bar_container");
- gStatusBar = new LLStatusBar(status_bar_container->getLocalRect());
- gStatusBar->setFollowsAll();
- gStatusBar->setShape(status_bar_container->getLocalRect());
- // sync bg color with menu bar
- gStatusBar->setBackgroundColor( gMenuBarView->getBackgroundColor().get() );
- status_bar_container->addChild(gStatusBar);
- status_bar_container->setVisible(TRUE);
-
- // Navigation bar
- LLPanel* nav_bar_container = getRootView()->getChild<LLPanel>("nav_bar_container");
-
- LLNavigationBar* navbar = LLNavigationBar::getInstance();
- navbar->setShape(nav_bar_container->getLocalRect());
- navbar->setBackgroundColor(gMenuBarView->getBackgroundColor().get());
- nav_bar_container->addChild(navbar);
- nav_bar_container->setVisible(TRUE);
-
- if (!gSavedSettings.getBOOL("ShowNavbarNavigationPanel"))
- {
- navbar->showNavigationPanel(FALSE);
- }
-
- if (!gSavedSettings.getBOOL("ShowNavbarFavoritesPanel"))
- {
- navbar->showFavoritesPanel(FALSE);
- }
-
- // Top Info bar
- LLPanel* topinfo_bar_container = getRootView()->getChild<LLPanel>("topinfo_bar_container");
- LLPanelTopInfoBar* topinfo_bar = LLPanelTopInfoBar::getInstance();
-
- topinfo_bar->setShape(topinfo_bar_container->getLocalRect());
-
- topinfo_bar_container->addChild(topinfo_bar);
- topinfo_bar_container->setVisible(TRUE);
-
- if (!gSavedSettings.getBOOL("ShowMiniLocationPanel"))
- {
- topinfo_bar->setVisible(FALSE);
- }
-
- if ( gHUDView == NULL )
- {
- LLRect hud_rect = full_window;
- hud_rect.mBottom += 50;
- if (gMenuBarView && gMenuBarView->isInVisibleChain())
- {
- hud_rect.mTop -= gMenuBarView->getRect().getHeight();
- }
- gHUDView = new LLHUDView(hud_rect);
- // put behind everything else in the UI
- getRootView()->addChildInBack(gHUDView);
- }
-
- LLPanel* panel_ssf_container = getRootView()->getChild<LLPanel>("stand_stop_flying_container");
- LLPanelStandStopFlying* panel_stand_stop_flying = LLPanelStandStopFlying::getInstance();
- panel_ssf_container->addChild(panel_stand_stop_flying);
- panel_ssf_container->setVisible(TRUE);
-
- // put sidetray in container
- LLPanel* side_tray_container = getRootView()->getChild<LLPanel>("side_tray_container");
- LLSideTray* sidetrayp = LLSideTray::getInstance();
- sidetrayp->setShape(side_tray_container->getLocalRect());
- // don't follow right edge to avoid spurious resizes, since we are using a fixed width layout
- sidetrayp->setFollows(FOLLOWS_LEFT|FOLLOWS_TOP|FOLLOWS_BOTTOM);
- side_tray_container->addChild(sidetrayp);
- side_tray_container->setVisible(FALSE);
-
- // put sidetray buttons in their own panel
- LLPanel* buttons_panel = sidetrayp->getButtonsPanel();
- LLPanel* buttons_panel_container = getRootView()->getChild<LLPanel>("side_bar_tabs");
- buttons_panel->setShape(buttons_panel_container->getLocalRect());
- buttons_panel->setFollowsAll();
- buttons_panel_container->addChild(buttons_panel);
-
- LLView* avatar_picker_destination_guide_container = gViewerWindow->getRootView()->getChild<LLView>("avatar_picker_and_destination_guide_container");
- avatar_picker_destination_guide_container->getChild<LLButton>("close")->setCommitCallback(boost::bind(toggle_destination_and_avatar_picker, LLSD()));
- LLMediaCtrl* destinations = avatar_picker_destination_guide_container->findChild<LLMediaCtrl>("destination_guide_contents");
- LLMediaCtrl* avatar_picker = avatar_picker_destination_guide_container->findChild<LLMediaCtrl>("avatar_picker_contents");
- if (destinations)
- {
- destinations->navigateTo(gSavedSettings.getString("DestinationGuideURL"), "text/html");
- }
-
- if (avatar_picker)
- {
- avatar_picker->navigateTo(gSavedSettings.getString("AvatarPickerURL"), "text/html");
- }
-
-}
-
-// Destroy the UI
-void LLViewerWindow::shutdownViews()
-{
- // clean up warning logger
- LLError::removeRecorder(RecordToChatConsole::getInstance());
-
- delete mDebugText;
- mDebugText = NULL;
-
- // Cleanup global views
- if (gMorphView)
- {
- gMorphView->setVisible(FALSE);
- }
-
- // DEV-40930: Clear sModalStack. Otherwise, any LLModalDialog left open
- // will crump with LL_ERRS.
- LLModalDialog::shutdownModals();
-
- // destroy the nav bar, not currently part of gViewerWindow
- // *TODO: Make LLNavigationBar part of gViewerWindow
- delete LLNavigationBar::getInstance();
-
- // destroy menus after instantiating navbar above, as it needs
- // access to gMenuHolder
- cleanup_menus();
-
- // Delete all child views.
- delete mRootView;
- mRootView = NULL;
-
- // Automatically deleted as children of mRootView. Fix the globals.
- gStatusBar = NULL;
- gIMMgr = NULL;
- gToolTipView = NULL;
-
- gFloaterView = NULL;
- gMorphView = NULL;
-
- gHUDView = NULL;
-}
-
-void LLViewerWindow::shutdownGL()
-{
- //--------------------------------------------------------
- // Shutdown GL cleanly. Order is very important here.
- //--------------------------------------------------------
- LLFontGL::destroyDefaultFonts();
- LLFontManager::cleanupClass();
- stop_glerror();
-
- gSky.cleanup();
- stop_glerror();
-
- LLWearableList::instance().cleanup() ;
-
- gTextureList.shutdown();
- stop_glerror();
-
- gBumpImageList.shutdown();
- stop_glerror();
-
- LLWorldMapView::cleanupTextures();
-
- llinfos << "Cleaning up pipeline" << llendl;
- gPipeline.cleanup();
- stop_glerror();
-
- LLViewerTextureManager::cleanup() ;
- LLImageGL::cleanupClass() ;
-
- llinfos << "All textures and llimagegl images are destroyed!" << llendl ;
-
- llinfos << "Cleaning up select manager" << llendl;
- LLSelectMgr::getInstance()->cleanup();
-
- LLVertexBuffer::cleanupClass();
-
- llinfos << "Stopping GL during shutdown" << llendl;
- if (!gNoRender)
- {
- stopGL(FALSE);
- stop_glerror();
- }
-
- gGL.shutdown();
-}
-
-// shutdownViews() and shutdownGL() need to be called first
-LLViewerWindow::~LLViewerWindow()
-{
- llinfos << "Destroying Window" << llendl;
- destroyWindow();
-
- delete mDebugText;
- mDebugText = NULL;
-}
-
-
-void LLViewerWindow::setCursor( ECursorType c )
-{
- mWindow->setCursor( c );
-}
-
-void LLViewerWindow::showCursor()
-{
- mWindow->showCursor();
-
- mCursorHidden = FALSE;
-}
-
-void LLViewerWindow::hideCursor()
-{
- // And hide the cursor
- mWindow->hideCursor();
-
- mCursorHidden = TRUE;
-}
-
-void LLViewerWindow::sendShapeToSim()
-{
- LLMessageSystem* msg = gMessageSystem;
- if(!msg) return;
- msg->newMessageFast(_PREHASH_AgentHeightWidth);
- msg->nextBlockFast(_PREHASH_AgentData);
- msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
- msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- msg->addU32Fast(_PREHASH_CircuitCode, gMessageSystem->mOurCircuitCode);
- msg->nextBlockFast(_PREHASH_HeightWidthBlock);
- msg->addU32Fast(_PREHASH_GenCounter, 0);
- U16 height16 = (U16) mWorldViewRectRaw.getHeight();
- U16 width16 = (U16) mWorldViewRectRaw.getWidth();
- msg->addU16Fast(_PREHASH_Height, height16);
- msg->addU16Fast(_PREHASH_Width, width16);
- gAgent.sendReliableMessage();
-}
-
-// Must be called after window is created to set up agent
-// camera variables and UI variables.
-void LLViewerWindow::reshape(S32 width, S32 height)
-{
- // Destroying the window at quit time generates spurious
- // reshape messages. We don't care about these, and we
- // don't want to send messages because the message system
- // may have been destructed.
- if (!LLApp::isExiting())
- {
- if (gNoRender)
- {
- return;
- }
-
- gWindowResized = TRUE;
-
- // update our window rectangle
- mWindowRectRaw.mRight = mWindowRectRaw.mLeft + width;
- mWindowRectRaw.mTop = mWindowRectRaw.mBottom + height;
-
- //glViewport(0, 0, width, height );
-
- if (height > 0)
- {
- LLViewerCamera::getInstance()->setViewHeightInPixels( mWorldViewRectRaw.getHeight() );
- LLViewerCamera::getInstance()->setAspect( getWorldViewAspectRatio() );
- }
-
- calcDisplayScale();
-
- BOOL display_scale_changed = mDisplayScale != LLUI::sGLScaleFactor;
- LLUI::setScaleFactor(mDisplayScale);
-
- // update our window rectangle
- mWindowRectScaled.mRight = mWindowRectScaled.mLeft + llround((F32)width / mDisplayScale.mV[VX]);
- mWindowRectScaled.mTop = mWindowRectScaled.mBottom + llround((F32)height / mDisplayScale.mV[VY]);
-
- setup2DViewport();
-
- // Inform lower views of the change
- // round up when converting coordinates to make sure there are no gaps at edge of window
- LLView::sForceReshape = display_scale_changed;
- mRootView->reshape(llceil((F32)width / mDisplayScale.mV[VX]), llceil((F32)height / mDisplayScale.mV[VY]));
- LLView::sForceReshape = FALSE;
-
- // clear font width caches
- if (display_scale_changed)
- {
- LLHUDObject::reshapeAll();
- }
-
- sendShapeToSim();
-
- // store new settings for the mode we are in, regardless
- // Only save size if not maximized
- BOOL maximized = mWindow->getMaximized();
- gSavedSettings.setBOOL("WindowMaximized", maximized);
-
- LLCoordScreen window_size;
- if (!maximized
- && mWindow->getSize(&window_size))
- {
- gSavedSettings.setS32("WindowWidth", window_size.mX);
- gSavedSettings.setS32("WindowHeight", window_size.mY);
- }
-
- LLViewerStats::getInstance()->setStat(LLViewerStats::ST_WINDOW_WIDTH, (F64)width);
- LLViewerStats::getInstance()->setStat(LLViewerStats::ST_WINDOW_HEIGHT, (F64)height);
- }
-}
-
-
-// Hide normal UI when a logon fails
-void LLViewerWindow::setNormalControlsVisible( BOOL visible )
-{
- if(LLBottomTray::instanceExists())
- {
- LLBottomTray::getInstance()->setVisible(visible);
- LLBottomTray::getInstance()->setEnabled(visible);
- }
-
- if ( gMenuBarView )
- {
- gMenuBarView->setVisible( visible );
- gMenuBarView->setEnabled( visible );
-
- // ...and set the menu color appropriately.
- setMenuBackgroundColor(gAgent.getGodLevel() > GOD_NOT,
- LLGridManager::getInstance()->isInProductionGrid());
- }
-
- if ( gStatusBar )
- {
- gStatusBar->setVisible( visible );
- gStatusBar->setEnabled( visible );
- }
-
- LLNavigationBar* navbarp = LLUI::getRootView()->findChild<LLNavigationBar>("navigation_bar");
- if (navbarp)
- {
- navbarp->setVisible( visible );
- }
-}
-
-void LLViewerWindow::setMenuBackgroundColor(bool god_mode, bool dev_grid)
-{
- LLSD args;
- LLColor4 new_bg_color;
-
- // no l10n problem because channel is always an english string
- std::string channel = LLVersionInfo::getChannel();
- bool isProject = (channel.find("Project") != std::string::npos);
-
- // god more important than project, proj more important than grid
- if(god_mode && LLGridManager::getInstance()->isInProductionGrid())
- {
- new_bg_color = LLUIColorTable::instance().getColor( "MenuBarGodBgColor" );
- }
- else if(god_mode && !LLGridManager::getInstance()->isInProductionGrid())
- {
- new_bg_color = LLUIColorTable::instance().getColor( "MenuNonProductionGodBgColor" );
- }
- else if (!god_mode && isProject)
- {
- new_bg_color = LLUIColorTable::instance().getColor( "MenuBarProjectBgColor" );
- }
- else if(!god_mode && !LLGridManager::getInstance()->isInProductionGrid())
- {
- new_bg_color = LLUIColorTable::instance().getColor( "MenuNonProductionBgColor" );
- }
- else
- {
- new_bg_color = LLUIColorTable::instance().getColor( "MenuBarBgColor" );
- }
-
- if(gMenuBarView)
- {
- gMenuBarView->setBackgroundColor( new_bg_color );
- }
-
- if(gStatusBar)
- {
- gStatusBar->setBackgroundColor( new_bg_color );
- }
-}
-
-void LLViewerWindow::drawDebugText()
-{
- gGL.color4f(1,1,1,1);
- gGL.pushMatrix();
- gGL.pushUIMatrix();
- {
- // scale view by UI global scale factor and aspect ratio correction factor
- gGL.scaleUI(mDisplayScale.mV[VX], mDisplayScale.mV[VY], 1.f);
- mDebugText->draw();
- }
- gGL.popUIMatrix();
- gGL.popMatrix();
-
- gGL.flush();
-}
-
-void LLViewerWindow::draw()
-{
-
-//#if LL_DEBUG
- LLView::sIsDrawing = TRUE;
-//#endif
- stop_glerror();
-
- LLUI::setLineWidth(1.f);
-
- LLUI::setLineWidth(1.f);
- // Reset any left-over transforms
- glMatrixMode(GL_MODELVIEW);
-
- glLoadIdentity();
-
- //S32 screen_x, screen_y;
-
- if (!gSavedSettings.getBOOL("RenderUIBuffer"))
- {
- LLUI::sDirtyRect = getWindowRectScaled();
- }
-
- // HACK for timecode debugging
- if (gSavedSettings.getBOOL("DisplayTimecode"))
- {
- // draw timecode block
- std::string text;
-
- glLoadIdentity();
-
- microsecondsToTimecodeString(gFrameTime,text);
- const LLFontGL* font = LLFontGL::getFontSansSerif();
- font->renderUTF8(text, 0,
- llround((getWindowWidthScaled()/2)-100.f),
- llround((getWindowHeightScaled()-60.f)),
- LLColor4( 1.f, 1.f, 1.f, 1.f ),
- LLFontGL::LEFT, LLFontGL::TOP);
- }
-
- // Draw all nested UI views.
- // No translation needed, this view is glued to 0,0
-
- gGL.pushMatrix();
- LLUI::pushMatrix();
- {
-
- // scale view by UI global scale factor and aspect ratio correction factor
- gGL.scaleUI(mDisplayScale.mV[VX], mDisplayScale.mV[VY], 1.f);
-
- LLVector2 old_scale_factor = LLUI::sGLScaleFactor;
- // apply camera zoom transform (for high res screenshots)
- F32 zoom_factor = LLViewerCamera::getInstance()->getZoomFactor();
- S16 sub_region = LLViewerCamera::getInstance()->getZoomSubRegion();
- if (zoom_factor > 1.f)
- {
- //decompose subregion number to x and y values
- int pos_y = sub_region / llceil(zoom_factor);
- int pos_x = sub_region - (pos_y*llceil(zoom_factor));
- // offset for this tile
- glTranslatef((F32)getWindowWidthScaled() * -(F32)pos_x,
- (F32)getWindowHeightScaled() * -(F32)pos_y,
- 0.f);
- glScalef(zoom_factor, zoom_factor, 1.f);
- LLUI::sGLScaleFactor *= zoom_factor;
- }
-
- // Draw tool specific overlay on world
- LLToolMgr::getInstance()->getCurrentTool()->draw();
-
- if( gAgentCamera.cameraMouselook() || LLFloaterCamera::inFreeCameraMode() )
- {
- drawMouselookInstructions();
- stop_glerror();
- }
-
- // Draw all nested UI views.
- // No translation needed, this view is glued to 0,0
- mRootView->draw();
-
- if (LLView::sDebugRects)
- {
- gToolTipView->drawStickyRect();
- }
-
- // Draw optional on-top-of-everyone view
- LLUICtrl* top_ctrl = gFocusMgr.getTopCtrl();
- if (top_ctrl && top_ctrl->getVisible())
- {
- S32 screen_x, screen_y;
- top_ctrl->localPointToScreen(0, 0, &screen_x, &screen_y);
-
- glMatrixMode(GL_MODELVIEW);
- LLUI::pushMatrix();
- LLUI::translate( (F32) screen_x, (F32) screen_y, 0.f);
- top_ctrl->draw();
- LLUI::popMatrix();
- }
-
-
- if( gShowOverlayTitle && !mOverlayTitle.empty() )
- {
- // Used for special titles such as "Second Life - Special E3 2003 Beta"
- const S32 DIST_FROM_TOP = 20;
- LLFontGL::getFontSansSerifBig()->renderUTF8(
- mOverlayTitle, 0,
- llround( getWindowWidthScaled() * 0.5f),
- getWindowHeightScaled() - DIST_FROM_TOP,
- LLColor4(1, 1, 1, 0.4f),
- LLFontGL::HCENTER, LLFontGL::TOP);
- }
-
- LLUI::sGLScaleFactor = old_scale_factor;
- }
- LLUI::popMatrix();
- gGL.popMatrix();
-
-//#if LL_DEBUG
- LLView::sIsDrawing = FALSE;
-//#endif
-}
-
-// Takes a single keydown event, usually when UI is visible
-BOOL LLViewerWindow::handleKey(KEY key, MASK mask)
-{
- // hide tooltips on keypress
- LLToolTipMgr::instance().blockToolTips();
-
- if (gFocusMgr.getKeyboardFocus()
- && !(mask & (MASK_CONTROL | MASK_ALT))
- && !gFocusMgr.getKeystrokesOnly())
- {
- // We have keyboard focus, and it's not an accelerator
- if (key < 0x80)
- {
- // Not a special key, so likely (we hope) to generate a character. Let it fall through to character handler first.
- return (gFocusMgr.getKeyboardFocus() != NULL);
- }
- }
-
- // let menus handle navigation keys for navigation
- if ((gMenuBarView && gMenuBarView->handleKey(key, mask, TRUE))
- ||(gLoginMenuBarView && gLoginMenuBarView->handleKey(key, mask, TRUE))
- ||(gMenuHolder && gMenuHolder->handleKey(key, mask, TRUE)))
- {
- return TRUE;
- }
-
- LLFocusableElement* keyboard_focus = gFocusMgr.getKeyboardFocus();
-
- // give menus a chance to handle modified (Ctrl, Alt) shortcut keys before current focus
- // as long as focus isn't locked
- if (mask & (MASK_CONTROL | MASK_ALT) && !gFocusMgr.focusLocked())
- {
- // Check the current floater's menu first, if it has one.
- if (gFocusMgr.keyboardFocusHasAccelerators()
- && keyboard_focus
- && keyboard_focus->handleKey(key,mask,FALSE))
- {
- return TRUE;
- }
-
- if ((gMenuBarView && gMenuBarView->handleAcceleratorKey(key, mask))
- ||(gLoginMenuBarView && gLoginMenuBarView->handleAcceleratorKey(key, mask)))
- {
- return TRUE;
- }
- }
-
- // give floaters first chance to handle TAB key
- // so frontmost floater gets focus
- // if nothing has focus, go to first or last UI element as appropriate
- if (key == KEY_TAB && (mask & MASK_CONTROL || gFocusMgr.getKeyboardFocus() == NULL))
- {
- if (gMenuHolder) gMenuHolder->hideMenus();
-
- // if CTRL-tabbing (and not just TAB with no focus), go into window cycle mode
- gFloaterView->setCycleMode((mask & MASK_CONTROL) != 0);
-
- // do CTRL-TAB and CTRL-SHIFT-TAB logic
- if (mask & MASK_SHIFT)
- {
- mRootView->focusPrevRoot();
- }
- else
- {
- mRootView->focusNextRoot();
- }
- return TRUE;
- }
- // hidden edit menu for cut/copy/paste
- if (gEditMenu && gEditMenu->handleAcceleratorKey(key, mask))
- {
- return TRUE;
- }
-
- // Traverses up the hierarchy
- if( keyboard_focus )
- {
- LLLineEditor* chat_editor = LLBottomTray::instanceExists() ? LLBottomTray::getInstance()->getNearbyChatBar()->getChatBox() : NULL;
- // arrow keys move avatar while chatting hack
- if (chat_editor && chat_editor->hasFocus())
- {
- // If text field is empty, there's no point in trying to move
- // cursor with arrow keys, so allow movement
- if (chat_editor->getText().empty()
- || gSavedSettings.getBOOL("ArrowKeysAlwaysMove"))
- {
- // let Control-Up and Control-Down through for chat line history,
- if (!(key == KEY_UP && mask == MASK_CONTROL)
- && !(key == KEY_DOWN && mask == MASK_CONTROL))
- {
- switch(key)
- {
- case KEY_LEFT:
- case KEY_RIGHT:
- case KEY_UP:
- case KEY_DOWN:
- case KEY_PAGE_UP:
- case KEY_PAGE_DOWN:
- case KEY_HOME:
- // when chatbar is empty or ArrowKeysAlwaysMove set,
- // pass arrow keys on to avatar...
- return FALSE;
- default:
- break;
- }
- }
- }
- }
-
- if (keyboard_focus->handleKey(key, mask, FALSE))
- {
- return TRUE;
- }
- }
-
- if( LLToolMgr::getInstance()->getCurrentTool()->handleKey(key, mask) )
- {
- return TRUE;
- }
-
- // Try for a new-format gesture
- if (LLGestureMgr::instance().triggerGesture(key, mask))
- {
- return TRUE;
- }
-
- // See if this is a gesture trigger. If so, eat the key and
- // don't pass it down to the menus.
- if (gGestureList.trigger(key, mask))
- {
- return TRUE;
- }
-
- // If "Pressing letter keys starts local chat" option is selected, we are not in mouselook,
- // no view has keyboard focus, this is a printable character key (and no modifier key is
- // pressed except shift), then give focus to nearby chat (STORM-560)
- if ( gSavedSettings.getS32("LetterKeysFocusChatBar") && !gAgentCamera.cameraMouselook() &&
- !keyboard_focus && key < 0x80 && (mask == MASK_NONE || mask == MASK_SHIFT) )
- {
- LLLineEditor* chat_editor = LLBottomTray::instanceExists() ? LLBottomTray::getInstance()->getNearbyChatBar()->getChatBox() : NULL;
- if (chat_editor)
- {
- // passing NULL here, character will be added later when it is handled by character handler.
- LLBottomTray::getInstance()->getNearbyChatBar()->startChat(NULL);
- return TRUE;
- }
- }
-
- // give menus a chance to handle unmodified accelerator keys
- if ((gMenuBarView && gMenuBarView->handleAcceleratorKey(key, mask))
- ||(gLoginMenuBarView && gLoginMenuBarView->handleAcceleratorKey(key, mask)))
- {
- return TRUE;
- }
-
- // don't pass keys on to world when something in ui has focus
- return gFocusMgr.childHasKeyboardFocus(mRootView)
- || LLMenuGL::getKeyboardMode()
- || (gMenuBarView && gMenuBarView->getHighlightedItem() && gMenuBarView->getHighlightedItem()->isActive());
-}
-
-
-BOOL LLViewerWindow::handleUnicodeChar(llwchar uni_char, MASK mask)
-{
- // HACK: We delay processing of return keys until they arrive as a Unicode char,
- // so that if you're typing chat text at low frame rate, we don't send the chat
- // until all keystrokes have been entered. JC
- // HACK: Numeric keypad <enter> on Mac is Unicode 3
- // HACK: Control-M on Windows is Unicode 13
- if ((uni_char == 13 && mask != MASK_CONTROL)
- || (uni_char == 3 && mask == MASK_NONE))
- {
- return gViewerKeyboard.handleKey(KEY_RETURN, mask, gKeyboard->getKeyRepeated(KEY_RETURN));
- }
-
- // let menus handle navigation (jump) keys
- if (gMenuBarView && gMenuBarView->handleUnicodeChar(uni_char, TRUE))
- {
- return TRUE;
- }
-
- // Traverses up the hierarchy
- LLFocusableElement* keyboard_focus = gFocusMgr.getKeyboardFocus();
- if( keyboard_focus )
- {
- if (keyboard_focus->handleUnicodeChar(uni_char, FALSE))
- {
- return TRUE;
- }
-
- //// Topmost view gets a chance before the hierarchy
- //LLUICtrl* top_ctrl = gFocusMgr.getTopCtrl();
- //if (top_ctrl && top_ctrl->handleUnicodeChar( uni_char, FALSE ) )
- //{
- // return TRUE;
- //}
-
- return TRUE;
- }
-
- return FALSE;
-}
-
-
-void LLViewerWindow::handleScrollWheel(S32 clicks)
-{
- LLView::sMouseHandlerMessage.clear();
-
- LLUI::resetMouseIdleTimer();
-
- LLMouseHandler* mouse_captor = gFocusMgr.getMouseCapture();
- if( mouse_captor )
- {
- S32 local_x;
- S32 local_y;
- mouse_captor->screenPointToLocal( mCurrentMousePoint.mX, mCurrentMousePoint.mY, &local_x, &local_y );
- mouse_captor->handleScrollWheel(local_x, local_y, clicks);
- if (LLView::sDebugMouseHandling)
- {
- llinfos << "Scroll Wheel handled by captor " << mouse_captor->getName() << llendl;
- }
- return;
- }
-
- LLUICtrl* top_ctrl = gFocusMgr.getTopCtrl();
- if (top_ctrl)
- {
- S32 local_x;
- S32 local_y;
- top_ctrl->screenPointToLocal( mCurrentMousePoint.mX, mCurrentMousePoint.mY, &local_x, &local_y );
- if (top_ctrl->handleScrollWheel(local_x, local_y, clicks)) return;
- }
-
- if (mRootView->handleScrollWheel(mCurrentMousePoint.mX, mCurrentMousePoint.mY, clicks) )
- {
- if (LLView::sDebugMouseHandling)
- {
- llinfos << "Scroll Wheel" << LLView::sMouseHandlerMessage << llendl;
- }
- return;
- }
- else if (LLView::sDebugMouseHandling)
- {
- llinfos << "Scroll Wheel not handled by view" << llendl;
- }
-
- // Zoom the camera in and out behavior
-
- if(top_ctrl == 0
- && getWorldViewRectScaled().pointInRect(mCurrentMousePoint.mX, mCurrentMousePoint.mY)
- && gAgentCamera.isInitialized())
- gAgentCamera.handleScrollWheel(clicks);
-
- return;
-}
-
-void LLViewerWindow::addPopup(LLView* popup)
-{
- if (mPopupView)
- {
- mPopupView->addPopup(popup);
- }
-}
-
-void LLViewerWindow::removePopup(LLView* popup)
-{
- if (mPopupView)
- {
- mPopupView->removePopup(popup);
- }
-}
-
-void LLViewerWindow::clearPopups()
-{
- if (mPopupView)
- {
- mPopupView->clearPopups();
- }
-}
-
-void LLViewerWindow::moveCursorToCenter()
-{
- if (! gSavedSettings.getBOOL("DisableMouseWarp"))
- {
- S32 x = getWorldViewWidthScaled() / 2;
- S32 y = getWorldViewHeightScaled() / 2;
-
- //on a forced move, all deltas get zeroed out to prevent jumping
- mCurrentMousePoint.set(x,y);
- mLastMousePoint.set(x,y);
- mCurrentMouseDelta.set(0,0);
-
- LLUI::setMousePositionScreen(x, y);
- }
-}
-
-
-//////////////////////////////////////////////////////////////////////
-//
-// Hover handlers
-//
-
-void append_xui_tooltip(LLView* viewp, LLToolTip::Params& params)
-{
- if (viewp)
- {
- if (!params.styled_message.empty())
- {
- params.styled_message.add().text("\n---------\n");
- }
- LLView::root_to_view_iterator_t end_tooltip_it = viewp->endRootToView();
- // NOTE: we skip "root" since it is assumed
- for (LLView::root_to_view_iterator_t tooltip_it = ++viewp->beginRootToView();
- tooltip_it != end_tooltip_it;
- ++tooltip_it)
- {
- LLView* viewp = *tooltip_it;
-
- params.styled_message.add().text(viewp->getName());
-
- LLPanel* panelp = dynamic_cast<LLPanel*>(viewp);
- if (panelp && !panelp->getXMLFilename().empty())
- {
- params.styled_message.add()
- .text("(" + panelp->getXMLFilename() + ")")
- .style.color(LLColor4(0.7f, 0.7f, 1.f, 1.f));
- }
- params.styled_message.add().text("/");
- }
- }
-}
-
-// Update UI based on stored mouse position from mouse-move
-// event processing.
-void LLViewerWindow::updateUI()
-{
- static LLFastTimer::DeclareTimer ftm("Update UI");
- LLFastTimer t(ftm);
-
- static std::string last_handle_msg;
-
- if (gLoggedInTime.getStarted())
- {
- if (gLoggedInTime.getElapsedTimeF32() > gSavedSettings.getF32("DestinationGuideHintTimeout"))
- {
- LLFirstUse::notUsingDestinationGuide();
- }
- if (gLoggedInTime.getElapsedTimeF32() > gSavedSettings.getF32("SidePanelHintTimeout"))
- {
- LLFirstUse::notUsingSidePanel();
- }
- }
-
- LLConsole::updateClass();
-
- // animate layout stacks so we have up to date rect for world view
- LLLayoutStack::updateClass();
-
- // use full window for world view when not rendering UI
- bool world_view_uses_full_window = gAgentCamera.cameraMouselook() || !gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI);
- updateWorldViewRect(world_view_uses_full_window);
-
- LLView::sMouseHandlerMessage.clear();
-
- S32 x = mCurrentMousePoint.mX;
- S32 y = mCurrentMousePoint.mY;
- MASK mask = gKeyboard->currentMask(TRUE);
-
- if (gNoRender)
- {
- return;
- }
-
- if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_RAYCAST))
- {
- gDebugRaycastFaceHit = -1;
- gDebugRaycastObject = cursorIntersect(-1, -1, 512.f, NULL, -1, FALSE,
- &gDebugRaycastFaceHit,
- &gDebugRaycastIntersection,
- &gDebugRaycastTexCoord,
- &gDebugRaycastNormal,
- &gDebugRaycastBinormal);
- }
-
- updateMouseDelta();
- updateKeyboardFocus();
-
- BOOL handled = FALSE;
-
- BOOL handled_by_top_ctrl = FALSE;
- LLUICtrl* top_ctrl = gFocusMgr.getTopCtrl();
- LLMouseHandler* mouse_captor = gFocusMgr.getMouseCapture();
- LLView* captor_view = dynamic_cast<LLView*>(mouse_captor);
-
- //FIXME: only include captor and captor's ancestors if mouse is truly over them --RN
-
- //build set of views containing mouse cursor by traversing UI hierarchy and testing
- //screen rect against mouse cursor
- view_handle_set_t mouse_hover_set;
-
- // constraint mouse enter events to children of mouse captor
- LLView* root_view = captor_view;
-
- // if mouse captor doesn't exist or isn't a LLView
- // then allow mouse enter events on entire UI hierarchy
- if (!root_view)
- {
- root_view = mRootView;
- }
-
- // only update mouse hover set when UI is visible (since we shouldn't send hover events to invisible UI
- if (gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
- {
- // include all ancestors of captor_view as automatically having mouse
- if (captor_view)
- {
- LLView* captor_parent_view = captor_view->getParent();
- while(captor_parent_view)
- {
- mouse_hover_set.insert(captor_parent_view->getHandle());
- captor_parent_view = captor_parent_view->getParent();
- }
- }
-
- // aggregate visible views that contain mouse cursor in display order
- LLPopupView::popup_list_t popups = mPopupView->getCurrentPopups();
-
- for(LLPopupView::popup_list_t::iterator popup_it = popups.begin(); popup_it != popups.end(); ++popup_it)
- {
- LLView* popup = popup_it->get();
- if (popup && popup->calcScreenBoundingRect().pointInRect(x, y))
- {
- // iterator over contents of top_ctrl, and throw into mouse_hover_set
- for (LLView::tree_iterator_t it = popup->beginTreeDFS();
- it != popup->endTreeDFS();
- ++it)
- {
- LLView* viewp = *it;
- if (viewp->getVisible()
- && viewp->calcScreenBoundingRect().pointInRect(x, y))
- {
- // we have a view that contains the mouse, add it to the set
- mouse_hover_set.insert(viewp->getHandle());
- }
- else
- {
- // skip this view and all of its children
- it.skipDescendants();
- }
- }
- }
- }
-
- // while the top_ctrl contains the mouse cursor, only it and its descendants will receive onMouseEnter events
- if (top_ctrl && top_ctrl->calcScreenBoundingRect().pointInRect(x, y))
- {
- // iterator over contents of top_ctrl, and throw into mouse_hover_set
- for (LLView::tree_iterator_t it = top_ctrl->beginTreeDFS();
- it != top_ctrl->endTreeDFS();
- ++it)
- {
- LLView* viewp = *it;
- if (viewp->getVisible()
- && viewp->calcScreenBoundingRect().pointInRect(x, y))
- {
- // we have a view that contains the mouse, add it to the set
- mouse_hover_set.insert(viewp->getHandle());
- }
- else
- {
- // skip this view and all of its children
- it.skipDescendants();
- }
- }
- }
- else
- {
- // walk UI tree in depth-first order
- for (LLView::tree_iterator_t it = root_view->beginTreeDFS();
- it != root_view->endTreeDFS();
- ++it)
- {
- LLView* viewp = *it;
- // calculating the screen rect involves traversing the parent, so this is less than optimal
- if (viewp->getVisible()
- && viewp->calcScreenBoundingRect().pointInRect(x, y))
- {
-
- // if this view is mouse opaque, nothing behind it should be in mouse_hover_set
- if (viewp->getMouseOpaque())
- {
- // constrain further iteration to children of this widget
- it = viewp->beginTreeDFS();
- }
-
- // we have a view that contains the mouse, add it to the set
- mouse_hover_set.insert(viewp->getHandle());
- }
- else
- {
- // skip this view and all of its children
- it.skipDescendants();
- }
- }
- }
- }
-
- typedef std::vector<LLHandle<LLView> > view_handle_list_t;
-
- // call onMouseEnter() on all views which contain the mouse cursor but did not before
- view_handle_list_t mouse_enter_views;
- std::set_difference(mouse_hover_set.begin(), mouse_hover_set.end(),
- mMouseHoverViews.begin(), mMouseHoverViews.end(),
- std::back_inserter(mouse_enter_views));
- for (view_handle_list_t::iterator it = mouse_enter_views.begin();
- it != mouse_enter_views.end();
- ++it)
- {
- LLView* viewp = it->get();
- if (viewp)
- {
- LLRect view_screen_rect = viewp->calcScreenRect();
- viewp->onMouseEnter(x - view_screen_rect.mLeft, y - view_screen_rect.mBottom, mask);
- }
- }
-
- // call onMouseLeave() on all views which no longer contain the mouse cursor
- view_handle_list_t mouse_leave_views;
- std::set_difference(mMouseHoverViews.begin(), mMouseHoverViews.end(),
- mouse_hover_set.begin(), mouse_hover_set.end(),
- std::back_inserter(mouse_leave_views));
- for (view_handle_list_t::iterator it = mouse_leave_views.begin();
- it != mouse_leave_views.end();
- ++it)
- {
- LLView* viewp = it->get();
- if (viewp)
- {
- LLRect view_screen_rect = viewp->calcScreenRect();
- viewp->onMouseLeave(x - view_screen_rect.mLeft, y - view_screen_rect.mBottom, mask);
- }
- }
-
- // store resulting hover set for next frame
- swap(mMouseHoverViews, mouse_hover_set);
-
- // only handle hover events when UI is enabled
- if (gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
- {
-
- if( mouse_captor )
- {
- // Pass hover events to object capturing mouse events.
- S32 local_x;
- S32 local_y;
- mouse_captor->screenPointToLocal( x, y, &local_x, &local_y );
- handled = mouse_captor->handleHover(local_x, local_y, mask);
- if (LLView::sDebugMouseHandling)
- {
- llinfos << "Hover handled by captor " << mouse_captor->getName() << llendl;
- }
-
- if( !handled )
- {
- lldebugst(LLERR_USER_INPUT) << "hover not handled by mouse captor" << llendl;
- }
- }
- else
- {
- if (top_ctrl)
- {
- S32 local_x, local_y;
- top_ctrl->screenPointToLocal( x, y, &local_x, &local_y );
- handled = top_ctrl->pointInView(local_x, local_y) && top_ctrl->handleHover(local_x, local_y, mask);
- handled_by_top_ctrl = TRUE;
- }
-
- if ( !handled )
- {
- // x and y are from last time mouse was in window
- // mMouseInWindow tracks *actual* mouse location
- if (mMouseInWindow && mRootView->handleHover(x, y, mask) )
- {
- if (LLView::sDebugMouseHandling && LLView::sMouseHandlerMessage != last_handle_msg)
- {
- last_handle_msg = LLView::sMouseHandlerMessage;
- llinfos << "Hover" << LLView::sMouseHandlerMessage << llendl;
- }
- handled = TRUE;
- }
- else if (LLView::sDebugMouseHandling)
- {
- if (last_handle_msg != LLStringUtil::null)
- {
- last_handle_msg.clear();
- llinfos << "Hover not handled by view" << llendl;
- }
- }
- }
-
- if (!handled)
- {
- LLTool *tool = LLToolMgr::getInstance()->getCurrentTool();
-
- if(mMouseInWindow && tool)
- {
- handled = tool->handleHover(x, y, mask);
- }
- }
- }
-
- // Show a new tool tip (or update one that is already shown)
- BOOL tool_tip_handled = FALSE;
- std::string tool_tip_msg;
- if( handled
- && !mWindow->isCursorHidden())
- {
- LLRect screen_sticky_rect = mRootView->getLocalRect();
- S32 local_x, local_y;
-
- if (gSavedSettings.getBOOL("DebugShowXUINames"))
- {
- LLToolTip::Params params;
-
- LLView* tooltip_view = mRootView;
- LLView::tree_iterator_t end_it = mRootView->endTreeDFS();
- for (LLView::tree_iterator_t it = mRootView->beginTreeDFS(); it != end_it; ++it)
- {
- LLView* viewp = *it;
- LLRect screen_rect;
- viewp->localRectToScreen(viewp->getLocalRect(), &screen_rect);
- if (!(viewp->getVisible()
- && screen_rect.pointInRect(x, y)))
- {
- it.skipDescendants();
- }
- // only report xui names for LLUICtrls,
- // and blacklist the various containers we don't care about
- else if (dynamic_cast<LLUICtrl*>(viewp)
- && viewp != gMenuHolder
- && viewp != gFloaterView
- && viewp != gConsole)
- {
- if (dynamic_cast<LLFloater*>(viewp))
- {
- // constrain search to descendants of this (frontmost) floater
- // by resetting iterator
- it = viewp->beginTreeDFS();
- }
-
- // if we are in a new part of the tree (not a descendent of current tooltip_view)
- // then push the results for tooltip_view and start with a new potential view
- // NOTE: this emulates visiting only the leaf nodes that meet our criteria
- if (!viewp->hasAncestor(tooltip_view))
- {
- append_xui_tooltip(tooltip_view, params);
- screen_sticky_rect.intersectWith(tooltip_view->calcScreenRect());
- }
- tooltip_view = viewp;
- }
- }
-
- append_xui_tooltip(tooltip_view, params);
- screen_sticky_rect.intersectWith(tooltip_view->calcScreenRect());
-
- params.sticky_rect = screen_sticky_rect;
- params.max_width = 400;
-
- LLToolTipMgr::instance().show(params);
- }
- // if there is a mouse captor, nothing else gets a tooltip
- else if (mouse_captor)
- {
- mouse_captor->screenPointToLocal(x, y, &local_x, &local_y);
- tool_tip_handled = mouse_captor->handleToolTip(local_x, local_y, mask);
- }
- else
- {
- // next is top_ctrl
- if (!tool_tip_handled && top_ctrl)
- {
- top_ctrl->screenPointToLocal(x, y, &local_x, &local_y);
- tool_tip_handled = top_ctrl->handleToolTip(local_x, local_y, mask );
- }
-
- if (!tool_tip_handled)
- {
- local_x = x; local_y = y;
- tool_tip_handled = mRootView->handleToolTip(local_x, local_y, mask );
- }
-
- LLTool* current_tool = LLToolMgr::getInstance()->getCurrentTool();
- if (!tool_tip_handled && current_tool)
- {
- current_tool->screenPointToLocal(x, y, &local_x, &local_y);
- tool_tip_handled = current_tool->handleToolTip(local_x, local_y, mask );
- }
- }
- }
- }
- else
- { // just have tools handle hover when UI is turned off
- LLTool *tool = LLToolMgr::getInstance()->getCurrentTool();
-
- if(mMouseInWindow && tool)
- {
- handled = tool->handleHover(x, y, mask);
- }
- }
-
- updateLayout();
-
- mLastMousePoint = mCurrentMousePoint;
-
- // cleanup unused selections when no modal dialogs are open
- if (LLModalDialog::activeCount() == 0)
- {
- LLViewerParcelMgr::getInstance()->deselectUnused();
- }
-
- if (LLModalDialog::activeCount() == 0)
- {
- LLSelectMgr::getInstance()->deselectUnused();
- }
-}
-
-
-void LLViewerWindow::updateLayout()
-{
- LLTool* tool = LLToolMgr::getInstance()->getCurrentTool();
- if (gFloaterTools != NULL
- && tool != NULL
- && tool != gToolNull
- && tool != LLToolCompInspect::getInstance()
- && tool != LLToolDragAndDrop::getInstance()
- && !gSavedSettings.getBOOL("FreezeTime"))
- {
- // Suppress the toolbox view if our source tool was the pie tool,
- // and we've overridden to something else.
- bool suppress_toolbox =
- (LLToolMgr::getInstance()->getBaseTool() == LLToolPie::getInstance()) &&
- (LLToolMgr::getInstance()->getCurrentTool() != LLToolPie::getInstance());
-
- LLMouseHandler *captor = gFocusMgr.getMouseCapture();
- // With the null, inspect, or drag and drop tool, don't muck
- // with visibility.
-
- if (gFloaterTools->isMinimized()
- || (tool != LLToolPie::getInstance() // not default tool
- && tool != LLToolCompGun::getInstance() // not coming out of mouselook
- && !suppress_toolbox // not override in third person
- && LLToolMgr::getInstance()->getCurrentToolset() != gFaceEditToolset // not special mode
- && LLToolMgr::getInstance()->getCurrentToolset() != gMouselookToolset
- && (!captor || dynamic_cast<LLView*>(captor) != NULL))) // not dragging
- {
- // Force floater tools to be visible (unless minimized)
- if (!gFloaterTools->getVisible())
- {
- gFloaterTools->openFloater();
- }
- // Update the location of the blue box tool popup
- LLCoordGL select_center_screen;
- gFloaterTools->updatePopup( select_center_screen, gKeyboard->currentMask(TRUE) );
- }
- else
- {
- gFloaterTools->setVisible(FALSE);
- }
- //gMenuBarView->setItemVisible("BuildTools", gFloaterTools->getVisible());
- }
-
- // Always update console
- if(gConsole)
- {
- LLRect console_rect = getChatConsoleRect();
- gConsole->reshape(console_rect.getWidth(), console_rect.getHeight());
- gConsole->setRect(console_rect);
- }
-}
-
-void LLViewerWindow::updateMouseDelta()
-{
- S32 dx = lltrunc((F32) (mCurrentMousePoint.mX - mLastMousePoint.mX) * LLUI::sGLScaleFactor.mV[VX]);
- S32 dy = lltrunc((F32) (mCurrentMousePoint.mY - mLastMousePoint.mY) * LLUI::sGLScaleFactor.mV[VY]);
-
- //RN: fix for asynchronous notification of mouse leaving window not working
- LLCoordWindow mouse_pos;
- mWindow->getCursorPosition(&mouse_pos);
- if (mouse_pos.mX < 0 ||
- mouse_pos.mY < 0 ||
- mouse_pos.mX > mWindowRectRaw.getWidth() ||
- mouse_pos.mY > mWindowRectRaw.getHeight())
- {
- mMouseInWindow = FALSE;
- }
- else
- {
- mMouseInWindow = TRUE;
- }
-
- LLVector2 mouse_vel;
-
- if (gSavedSettings.getBOOL("MouseSmooth"))
- {
- static F32 fdx = 0.f;
- static F32 fdy = 0.f;
-
- F32 amount = 16.f;
- fdx = fdx + ((F32) dx - fdx) * llmin(gFrameIntervalSeconds*amount,1.f);
- fdy = fdy + ((F32) dy - fdy) * llmin(gFrameIntervalSeconds*amount,1.f);
-
- mCurrentMouseDelta.set(llround(fdx), llround(fdy));
- mouse_vel.setVec(fdx,fdy);
- }
- else
- {
- mCurrentMouseDelta.set(dx, dy);
- mouse_vel.setVec((F32) dx, (F32) dy);
- }
-
- mMouseVelocityStat.addValue(mouse_vel.magVec());
-}
-
-void LLViewerWindow::updateKeyboardFocus()
-{
- if (!gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
- {
- gFocusMgr.setKeyboardFocus(NULL);
- }
-
- // clean up current focus
- LLUICtrl* cur_focus = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
- if (cur_focus)
- {
- if (!cur_focus->isInVisibleChain() || !cur_focus->isInEnabledChain())
- {
- // don't release focus, just reassign so that if being given
- // to a sibling won't call onFocusLost on all the ancestors
- // gFocusMgr.releaseFocusIfNeeded(cur_focus);
-
- LLUICtrl* parent = cur_focus->getParentUICtrl();
- const LLUICtrl* focus_root = cur_focus->findRootMostFocusRoot();
- bool new_focus_found = false;
- while(parent)
- {
- if (parent->isCtrl()
- && (parent->hasTabStop() || parent == focus_root)
- && !parent->getIsChrome()
- && parent->isInVisibleChain()
- && parent->isInEnabledChain())
- {
- if (!parent->focusFirstItem())
- {
- parent->setFocus(TRUE);
- }
- new_focus_found = true;
- break;
- }
- parent = parent->getParentUICtrl();
- }
-
- // if we didn't find a better place to put focus, just release it
- // hasFocus() will return true if and only if we didn't touch focus since we
- // are only moving focus higher in the hierarchy
- if (!new_focus_found)
- {
- cur_focus->setFocus(FALSE);
- }
- }
- else if (cur_focus->isFocusRoot())
- {
- // focus roots keep trying to delegate focus to their first valid descendant
- // this assumes that focus roots are not valid focus holders on their own
- cur_focus->focusFirstItem();
- }
- }
-
- // last ditch force of edit menu to selection manager
- if (LLEditMenuHandler::gEditMenuHandler == NULL && LLSelectMgr::getInstance()->getSelection()->getObjectCount())
- {
- LLEditMenuHandler::gEditMenuHandler = LLSelectMgr::getInstance();
- }
-
- if (gFloaterView->getCycleMode())
- {
- // sync all floaters with their focus state
- gFloaterView->highlightFocusedFloater();
- gSnapshotFloaterView->highlightFocusedFloater();
- if ((gKeyboard->currentMask(TRUE) & MASK_CONTROL) == 0)
- {
- // control key no longer held down, finish cycle mode
- gFloaterView->setCycleMode(FALSE);
-
- gFloaterView->syncFloaterTabOrder();
- }
- else
- {
- // user holding down CTRL, don't update tab order of floaters
- }
- }
- else
- {
- // update focused floater
- gFloaterView->highlightFocusedFloater();
- gSnapshotFloaterView->highlightFocusedFloater();
- // make sure floater visible order is in sync with tab order
- gFloaterView->syncFloaterTabOrder();
- }
-
- if(LLSideTray::instanceCreated())//just getInstance will create sidetray. we don't want this
- LLSideTray::getInstance()->highlightFocused();
-}
-
-static LLFastTimer::DeclareTimer FTM_UPDATE_WORLD_VIEW("Update World View");
-void LLViewerWindow::updateWorldViewRect(bool use_full_window)
-{
- LLFastTimer ft(FTM_UPDATE_WORLD_VIEW);
-
- // start off using whole window to render world
- LLRect new_world_rect = mWindowRectRaw;
-
- if (use_full_window == false && mWorldViewPlaceholder.get())
- {
- new_world_rect = mWorldViewPlaceholder.get()->calcScreenRect();
- // clamp to at least a 1x1 rect so we don't try to allocate zero width gl buffers
- new_world_rect.mTop = llmax(new_world_rect.mTop, new_world_rect.mBottom + 1);
- new_world_rect.mRight = llmax(new_world_rect.mRight, new_world_rect.mLeft + 1);
-
- new_world_rect.mLeft = llround((F32)new_world_rect.mLeft * mDisplayScale.mV[VX]);
- new_world_rect.mRight = llround((F32)new_world_rect.mRight * mDisplayScale.mV[VX]);
- new_world_rect.mBottom = llround((F32)new_world_rect.mBottom * mDisplayScale.mV[VY]);
- new_world_rect.mTop = llround((F32)new_world_rect.mTop * mDisplayScale.mV[VY]);
- }
-
- if (gSavedSettings.getBOOL("SidebarCameraMovement") == FALSE)
- {
- // use right edge of window, ignoring sidebar
- new_world_rect.mRight = mWindowRectRaw.mRight;
- }
-
- if (mWorldViewRectRaw != new_world_rect)
- {
- mWorldViewRectRaw = new_world_rect;
- gResizeScreenTexture = TRUE;
- LLViewerCamera::getInstance()->setViewHeightInPixels( mWorldViewRectRaw.getHeight() );
- LLViewerCamera::getInstance()->setAspect( getWorldViewAspectRatio() );
-
- LLRect old_world_rect_scaled = mWorldViewRectScaled;
- mWorldViewRectScaled = calcScaledRect(mWorldViewRectRaw, mDisplayScale);
-
- // sending a signal with a new WorldView rect
- mOnWorldViewRectUpdated(old_world_rect_scaled, mWorldViewRectScaled);
- }
-}
-
-void LLViewerWindow::saveLastMouse(const LLCoordGL &point)
-{
- // Store last mouse location.
- // If mouse leaves window, pretend last point was on edge of window
- if (point.mX < 0)
- {
- mCurrentMousePoint.mX = 0;
- }
- else if (point.mX > getWindowWidthScaled())
- {
- mCurrentMousePoint.mX = getWindowWidthScaled();
- }
- else
- {
- mCurrentMousePoint.mX = point.mX;
- }
-
- if (point.mY < 0)
- {
- mCurrentMousePoint.mY = 0;
- }
- else if (point.mY > getWindowHeightScaled() )
- {
- mCurrentMousePoint.mY = getWindowHeightScaled();
- }
- else
- {
- mCurrentMousePoint.mY = point.mY;
- }
-}
-
-
-// Draws the selection outlines for the currently selected objects
-// Must be called after displayObjects is called, which sets the mGLName parameter
-// NOTE: This function gets called 3 times:
-// render_ui_3d: FALSE, FALSE, TRUE
-// render_hud_elements: FALSE, FALSE, FALSE
-void LLViewerWindow::renderSelections( BOOL for_gl_pick, BOOL pick_parcel_walls, BOOL for_hud )
-{
- LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
-
- if (!for_hud && !for_gl_pick)
- {
- // Call this once and only once
- LLSelectMgr::getInstance()->updateSilhouettes();
- }
-
- // Draw fence around land selections
- if (for_gl_pick)
- {
- if (pick_parcel_walls)
- {
- LLViewerParcelMgr::getInstance()->renderParcelCollision();
- }
- }
- else if (( for_hud && selection->getSelectType() == SELECT_TYPE_HUD) ||
- (!for_hud && selection->getSelectType() != SELECT_TYPE_HUD))
- {
- LLSelectMgr::getInstance()->renderSilhouettes(for_hud);
-
- stop_glerror();
-
- // setup HUD render
- if (selection->getSelectType() == SELECT_TYPE_HUD && LLSelectMgr::getInstance()->getSelection()->getObjectCount())
- {
- LLBBox hud_bbox = gAgentAvatarp->getHUDBBox();
-
- // set up transform to encompass bounding box of HUD
- glMatrixMode(GL_PROJECTION);
- glPushMatrix();
- glLoadIdentity();
- F32 depth = llmax(1.f, hud_bbox.getExtentLocal().mV[VX] * 1.1f);
- glOrtho(-0.5f * LLViewerCamera::getInstance()->getAspect(), 0.5f * LLViewerCamera::getInstance()->getAspect(), -0.5f, 0.5f, 0.f, depth);
-
- glMatrixMode(GL_MODELVIEW);
- glPushMatrix();
- glLoadIdentity();
- glLoadMatrixf(OGL_TO_CFR_ROTATION); // Load Cory's favorite reference frame
- glTranslatef(-hud_bbox.getCenterLocal().mV[VX] + (depth *0.5f), 0.f, 0.f);
- }
-
- // Render light for editing
- if (LLSelectMgr::sRenderLightRadius && LLToolMgr::getInstance()->inEdit())
- {
- gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
- LLGLEnable gls_blend(GL_BLEND);
- LLGLEnable gls_cull(GL_CULL_FACE);
- LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE);
- glMatrixMode(GL_MODELVIEW);
- glPushMatrix();
- if (selection->getSelectType() == SELECT_TYPE_HUD)
- {
- F32 zoom = gAgentCamera.mHUDCurZoom;
- glScalef(zoom, zoom, zoom);
- }
-
- struct f : public LLSelectedObjectFunctor
- {
- virtual bool apply(LLViewerObject* object)
- {
- LLDrawable* drawable = object->mDrawable;
- if (drawable && drawable->isLight())
- {
- LLVOVolume* vovolume = drawable->getVOVolume();
- glPushMatrix();
-
- LLVector3 center = drawable->getPositionAgent();
- glTranslatef(center[0], center[1], center[2]);
- F32 scale = vovolume->getLightRadius();
- glScalef(scale, scale, scale);
-
- LLColor4 color(vovolume->getLightColor(), .5f);
- glColor4fv(color.mV);
-
- F32 pixel_area = 100000.f;
- // Render Outside
- gSphere.render(pixel_area);
-
- // Render Inside
- glCullFace(GL_FRONT);
- gSphere.render(pixel_area);
- glCullFace(GL_BACK);
-
- glPopMatrix();
- }
- return true;
- }
- } func;
- LLSelectMgr::getInstance()->getSelection()->applyToObjects(&func);
-
- glPopMatrix();
- }
-
- // NOTE: The average position for the axis arrows of the selected objects should
- // not be recalculated at this time. If they are, then group rotations will break.
-
- // Draw arrows at average center of all selected objects
- LLTool* tool = LLToolMgr::getInstance()->getCurrentTool();
- if (tool)
- {
- if(tool->isAlwaysRendered())
- {
- tool->render();
- }
- else
- {
- if( !LLSelectMgr::getInstance()->getSelection()->isEmpty() )
- {
- BOOL moveable_object_selected = FALSE;
- BOOL all_selected_objects_move = TRUE;
- BOOL all_selected_objects_modify = TRUE;
- BOOL selecting_linked_set = !gSavedSettings.getBOOL("EditLinkedParts");
-
- for (LLObjectSelection::iterator iter = LLSelectMgr::getInstance()->getSelection()->begin();
- iter != LLSelectMgr::getInstance()->getSelection()->end(); iter++)
- {
- LLSelectNode* nodep = *iter;
- LLViewerObject* object = nodep->getObject();
- BOOL this_object_movable = FALSE;
- if (object->permMove() && (object->permModify() || selecting_linked_set))
- {
- moveable_object_selected = TRUE;
- this_object_movable = TRUE;
- }
- all_selected_objects_move = all_selected_objects_move && this_object_movable;
- all_selected_objects_modify = all_selected_objects_modify && object->permModify();
- }
-
- BOOL draw_handles = TRUE;
-
- if (tool == LLToolCompTranslate::getInstance() && (!moveable_object_selected || !all_selected_objects_move))
- {
- draw_handles = FALSE;
- }
-
- if (tool == LLToolCompRotate::getInstance() && (!moveable_object_selected || !all_selected_objects_move))
- {
- draw_handles = FALSE;
- }
-
- if ( !all_selected_objects_modify && tool == LLToolCompScale::getInstance() )
- {
- draw_handles = FALSE;
- }
-
- if( draw_handles )
- {
- tool->render();
- }
- }
- }
- if (selection->getSelectType() == SELECT_TYPE_HUD && selection->getObjectCount())
- {
- glMatrixMode(GL_PROJECTION);
- glPopMatrix();
-
- glMatrixMode(GL_MODELVIEW);
- glPopMatrix();
- stop_glerror();
- }
- }
- }
-}
-
-// Return a point near the clicked object representative of the place the object was clicked.
-LLVector3d LLViewerWindow::clickPointInWorldGlobal(S32 x, S32 y_from_bot, LLViewerObject* clicked_object) const
-{
- // create a normalized vector pointing from the camera center into the
- // world at the location of the mouse click
- LLVector3 mouse_direction_global = mouseDirectionGlobal( x, y_from_bot );
-
- LLVector3d relative_object = clicked_object->getPositionGlobal() - gAgentCamera.getCameraPositionGlobal();
-
- // make mouse vector as long as object vector, so it touchs a point near
- // where the user clicked on the object
- mouse_direction_global *= (F32) relative_object.magVec();
-
- LLVector3d new_pos;
- new_pos.setVec(mouse_direction_global);
- // transform mouse vector back to world coords
- new_pos += gAgentCamera.getCameraPositionGlobal();
-
- return new_pos;
-}
-
-
-BOOL LLViewerWindow::clickPointOnSurfaceGlobal(const S32 x, const S32 y, LLViewerObject *objectp, LLVector3d &point_global) const
-{
- BOOL intersect = FALSE;
-
-// U8 shape = objectp->mPrimitiveCode & LL_PCODE_BASE_MASK;
- if (!intersect)
- {
- point_global = clickPointInWorldGlobal(x, y, objectp);
- llinfos << "approx intersection at " << (objectp->getPositionGlobal() - point_global) << llendl;
- }
- else
- {
- llinfos << "good intersection at " << (objectp->getPositionGlobal() - point_global) << llendl;
- }
-
- return intersect;
-}
-
-void LLViewerWindow::pickAsync(S32 x, S32 y_from_bot, MASK mask, void (*callback)(const LLPickInfo& info), BOOL pick_transparent)
-{
- if (gNoRender)
- {
- return;
- }
-
- BOOL in_build_mode = LLFloaterReg::instanceVisible("build");
- if (in_build_mode || LLDrawPoolAlpha::sShowDebugAlpha)
- {
- // build mode allows interaction with all transparent objects
- // "Show Debug Alpha" means no object actually transparent
- pick_transparent = TRUE;
- }
-
- LLPickInfo pick_info(LLCoordGL(x, y_from_bot), mask, pick_transparent, TRUE, callback);
- schedulePick(pick_info);
-}
-
-void LLViewerWindow::schedulePick(LLPickInfo& pick_info)
-{
- if (mPicks.size() >= 1024 || mWindow->getMinimized())
- { //something went wrong, picks are being scheduled but not processed
-
- if (pick_info.mPickCallback)
- {
- pick_info.mPickCallback(pick_info);
- }
-
- return;
- }
- mPicks.push_back(pick_info);
-
- // delay further event processing until we receive results of pick
- // only do this for async picks so that handleMouseUp won't be called
- // until the pick triggered in handleMouseDown has been processed, for example
- mWindow->delayInputProcessing();
-}
-
-
-void LLViewerWindow::performPick()
-{
- if (gNoRender)
- {
- return;
- }
-
- if (!mPicks.empty())
- {
- std::vector<LLPickInfo>::iterator pick_it;
- for (pick_it = mPicks.begin(); pick_it != mPicks.end(); ++pick_it)
- {
- pick_it->fetchResults();
- }
-
- mLastPick = mPicks.back();
- mPicks.clear();
- }
-}
-
-void LLViewerWindow::returnEmptyPicks()
-{
- std::vector<LLPickInfo>::iterator pick_it;
- for (pick_it = mPicks.begin(); pick_it != mPicks.end(); ++pick_it)
- {
- mLastPick = *pick_it;
- // just trigger callback with empty results
- if (pick_it->mPickCallback)
- {
- pick_it->mPickCallback(*pick_it);
- }
- }
- mPicks.clear();
-}
-
-// Performs the GL object/land pick.
-LLPickInfo LLViewerWindow::pickImmediate(S32 x, S32 y_from_bot, BOOL pick_transparent)
-{
- if (gNoRender)
- {
- return LLPickInfo();
- }
-
- BOOL in_build_mode = LLFloaterReg::instanceVisible("build");
- if (in_build_mode || LLDrawPoolAlpha::sShowDebugAlpha)
- {
- // build mode allows interaction with all transparent objects
- // "Show Debug Alpha" means no object actually transparent
- pick_transparent = TRUE;
- }
-
- // shortcut queueing in mPicks and just update mLastPick in place
- mLastPick = LLPickInfo(LLCoordGL(x, y_from_bot), gKeyboard->currentMask(TRUE), pick_transparent, TRUE, NULL);
- mLastPick.fetchResults();
-
- return mLastPick;
-}
-
-LLHUDIcon* LLViewerWindow::cursorIntersectIcon(S32 mouse_x, S32 mouse_y, F32 depth,
- LLVector3* intersection)
-{
- S32 x = mouse_x;
- S32 y = mouse_y;
-
- if ((mouse_x == -1) && (mouse_y == -1)) // use current mouse position
- {
- x = getCurrentMouseX();
- y = getCurrentMouseY();
- }
-
- // world coordinates of mouse
- LLVector3 mouse_direction_global = mouseDirectionGlobal(x,y);
- LLVector3 mouse_point_global = LLViewerCamera::getInstance()->getOrigin();
- LLVector3 mouse_world_start = mouse_point_global;
- LLVector3 mouse_world_end = mouse_point_global + mouse_direction_global * depth;
-
- return LLHUDIcon::lineSegmentIntersectAll(mouse_world_start, mouse_world_end, intersection);
-
-
-}
-
-LLViewerObject* LLViewerWindow::cursorIntersect(S32 mouse_x, S32 mouse_y, F32 depth,
- LLViewerObject *this_object,
- S32 this_face,
- BOOL pick_transparent,
- S32* face_hit,
- LLVector3 *intersection,
- LLVector2 *uv,
- LLVector3 *normal,
- LLVector3 *binormal)
-{
- S32 x = mouse_x;
- S32 y = mouse_y;
-
- if ((mouse_x == -1) && (mouse_y == -1)) // use current mouse position
- {
- x = getCurrentMouseX();
- y = getCurrentMouseY();
- }
-
- // HUD coordinates of mouse
- LLVector3 mouse_point_hud = mousePointHUD(x, y);
- LLVector3 mouse_hud_start = mouse_point_hud - LLVector3(depth, 0, 0);
- LLVector3 mouse_hud_end = mouse_point_hud + LLVector3(depth, 0, 0);
-
- // world coordinates of mouse
- LLVector3 mouse_direction_global = mouseDirectionGlobal(x,y);
- LLVector3 mouse_point_global = LLViewerCamera::getInstance()->getOrigin();
-
- //get near clip plane
- LLVector3 n = LLViewerCamera::getInstance()->getAtAxis();
- LLVector3 p = mouse_point_global + n * LLViewerCamera::getInstance()->getNear();
-
- //project mouse point onto plane
- LLVector3 pos;
- line_plane(mouse_point_global, mouse_direction_global, p, n, pos);
- mouse_point_global = pos;
-
- LLVector3 mouse_world_start = mouse_point_global;
- LLVector3 mouse_world_end = mouse_point_global + mouse_direction_global * depth;
-
-
- LLViewerObject* found = NULL;
-
- if (this_object) // check only this object
- {
- if (this_object->isHUDAttachment()) // is a HUD object?
- {
- if (this_object->lineSegmentIntersect(mouse_hud_start, mouse_hud_end, this_face, pick_transparent,
- face_hit, intersection, uv, normal, binormal))
- {
- found = this_object;
- }
- }
-
- else // is a world object
- {
- if (this_object->lineSegmentIntersect(mouse_world_start, mouse_world_end, this_face, pick_transparent,
- face_hit, intersection, uv, normal, binormal))
- {
- found = this_object;
- }
- }
- }
-
- else // check ALL objects
- {
- found = gPipeline.lineSegmentIntersectInHUD(mouse_hud_start, mouse_hud_end, pick_transparent,
- face_hit, intersection, uv, normal, binormal);
-
- if (!found) // if not found in HUD, look in world:
-
- {
- found = gPipeline.lineSegmentIntersectInWorld(mouse_world_start, mouse_world_end, pick_transparent,
- face_hit, intersection, uv, normal, binormal);
- }
-
- }
-
- return found;
-}
-
-// Returns unit vector relative to camera
-// indicating direction of point on screen x,y
-LLVector3 LLViewerWindow::mouseDirectionGlobal(const S32 x, const S32 y) const
-{
- // find vertical field of view
- F32 fov = LLViewerCamera::getInstance()->getView();
-
- // find world view center in scaled ui coordinates
- F32 center_x = getWorldViewRectScaled().getCenterX();
- F32 center_y = getWorldViewRectScaled().getCenterY();
-
- // calculate pixel distance to screen
- F32 distance = ((F32)getWorldViewHeightScaled() * 0.5f) / (tan(fov / 2.f));
-
- // calculate click point relative to middle of screen
- F32 click_x = x - center_x;
- F32 click_y = y - center_y;
-
- // compute mouse vector
- LLVector3 mouse_vector = distance * LLViewerCamera::getInstance()->getAtAxis()
- - click_x * LLViewerCamera::getInstance()->getLeftAxis()
- + click_y * LLViewerCamera::getInstance()->getUpAxis();
-
- mouse_vector.normVec();
-
- return mouse_vector;
-}
-
-LLVector3 LLViewerWindow::mousePointHUD(const S32 x, const S32 y) const
-{
- // find screen resolution
- S32 height = getWorldViewHeightScaled();
-
- // find world view center
- F32 center_x = getWorldViewRectScaled().getCenterX();
- F32 center_y = getWorldViewRectScaled().getCenterY();
-
- // remap with uniform scale (1/height) so that top is -0.5, bottom is +0.5
- F32 hud_x = -((F32)x - center_x) / height;
- F32 hud_y = ((F32)y - center_y) / height;
-
- return LLVector3(0.f, hud_x/gAgentCamera.mHUDCurZoom, hud_y/gAgentCamera.mHUDCurZoom);
-}
-
-// Returns unit vector relative to camera in camera space
-// indicating direction of point on screen x,y
-LLVector3 LLViewerWindow::mouseDirectionCamera(const S32 x, const S32 y) const
-{
- // find vertical field of view
- F32 fov_height = LLViewerCamera::getInstance()->getView();
- F32 fov_width = fov_height * LLViewerCamera::getInstance()->getAspect();
-
- // find screen resolution
- S32 height = getWorldViewHeightScaled();
- S32 width = getWorldViewWidthScaled();
-
- // find world view center
- F32 center_x = getWorldViewRectScaled().getCenterX();
- F32 center_y = getWorldViewRectScaled().getCenterY();
-
- // calculate click point relative to middle of screen
- F32 click_x = (((F32)x - center_x) / (F32)width) * fov_width * -1.f;
- F32 click_y = (((F32)y - center_y) / (F32)height) * fov_height;
-
- // compute mouse vector
- LLVector3 mouse_vector = LLVector3(0.f, 0.f, -1.f);
- LLQuaternion mouse_rotate;
- mouse_rotate.setQuat(click_y, click_x, 0.f);
-
- mouse_vector = mouse_vector * mouse_rotate;
- // project to z = -1 plane;
- mouse_vector = mouse_vector * (-1.f / mouse_vector.mV[VZ]);
-
- return mouse_vector;
-}
-
-
-
-BOOL LLViewerWindow::mousePointOnPlaneGlobal(LLVector3d& point, const S32 x, const S32 y,
- const LLVector3d &plane_point_global,
- const LLVector3 &plane_normal_global)
-{
- LLVector3d mouse_direction_global_d;
-
- mouse_direction_global_d.setVec(mouseDirectionGlobal(x,y));
- LLVector3d plane_normal_global_d;
- plane_normal_global_d.setVec(plane_normal_global);
- F64 plane_mouse_dot = (plane_normal_global_d * mouse_direction_global_d);
- LLVector3d plane_origin_camera_rel = plane_point_global - gAgentCamera.getCameraPositionGlobal();
- F64 mouse_look_at_scale = (plane_normal_global_d * plane_origin_camera_rel)
- / plane_mouse_dot;
- if (llabs(plane_mouse_dot) < 0.00001)
- {
- // if mouse is parallel to plane, return closest point on line through plane origin
- // that is parallel to camera plane by scaling mouse direction vector
- // by distance to plane origin, modulated by deviation of mouse direction from plane origin
- LLVector3d plane_origin_dir = plane_origin_camera_rel;
- plane_origin_dir.normVec();
-
- mouse_look_at_scale = plane_origin_camera_rel.magVec() / (plane_origin_dir * mouse_direction_global_d);
- }
-
- point = gAgentCamera.getCameraPositionGlobal() + mouse_look_at_scale * mouse_direction_global_d;
-
- return mouse_look_at_scale > 0.0;
-}
-
-
-// Returns global position
-BOOL LLViewerWindow::mousePointOnLandGlobal(const S32 x, const S32 y, LLVector3d *land_position_global)
-{
- LLVector3 mouse_direction_global = mouseDirectionGlobal(x,y);
- F32 mouse_dir_scale;
- BOOL hit_land = FALSE;
- LLViewerRegion *regionp;
- F32 land_z;
- const F32 FIRST_PASS_STEP = 1.0f; // meters
- const F32 SECOND_PASS_STEP = 0.1f; // meters
- LLVector3d camera_pos_global;
-
- camera_pos_global = gAgentCamera.getCameraPositionGlobal();
- LLVector3d probe_point_global;
- LLVector3 probe_point_region;
-
- // walk forwards to find the point
- for (mouse_dir_scale = FIRST_PASS_STEP; mouse_dir_scale < gAgentCamera.mDrawDistance; mouse_dir_scale += FIRST_PASS_STEP)
- {
- LLVector3d mouse_direction_global_d;
- mouse_direction_global_d.setVec(mouse_direction_global * mouse_dir_scale);
- probe_point_global = camera_pos_global + mouse_direction_global_d;
-
- regionp = LLWorld::getInstance()->resolveRegionGlobal(probe_point_region, probe_point_global);
-
- if (!regionp)
- {
- // ...we're outside the world somehow
- continue;
- }
-
- S32 i = (S32) (probe_point_region.mV[VX]/regionp->getLand().getMetersPerGrid());
- S32 j = (S32) (probe_point_region.mV[VY]/regionp->getLand().getMetersPerGrid());
- S32 grids_per_edge = (S32) regionp->getLand().mGridsPerEdge;
- if ((i >= grids_per_edge) || (j >= grids_per_edge))
- {
- //llinfos << "LLViewerWindow::mousePointOnLand probe_point is out of region" << llendl;
- continue;
- }
-
- land_z = regionp->getLand().resolveHeightRegion(probe_point_region);
-
- //llinfos << "mousePointOnLand initial z " << land_z << llendl;
-
- if (probe_point_region.mV[VZ] < land_z)
- {
- // ...just went under land
-
- // cout << "under land at " << probe_point << " scale " << mouse_vec_scale << endl;
-
- hit_land = TRUE;
- break;
- }
- }
-
-
- if (hit_land)
- {
- // Don't go more than one step beyond where we stopped above.
- // This can't just be "mouse_vec_scale" because floating point error
- // will stop the loop before the last increment.... X - 1.0 + 0.1 + 0.1 + ... + 0.1 != X
- F32 stop_mouse_dir_scale = mouse_dir_scale + FIRST_PASS_STEP;
-
- // take a step backwards, then walk forwards again to refine position
- for ( mouse_dir_scale -= FIRST_PASS_STEP; mouse_dir_scale <= stop_mouse_dir_scale; mouse_dir_scale += SECOND_PASS_STEP)
- {
- LLVector3d mouse_direction_global_d;
- mouse_direction_global_d.setVec(mouse_direction_global * mouse_dir_scale);
- probe_point_global = camera_pos_global + mouse_direction_global_d;
-
- regionp = LLWorld::getInstance()->resolveRegionGlobal(probe_point_region, probe_point_global);
-
- if (!regionp)
- {
- // ...we're outside the world somehow
- continue;
- }
-
- /*
- i = (S32) (local_probe_point.mV[VX]/regionp->getLand().getMetersPerGrid());
- j = (S32) (local_probe_point.mV[VY]/regionp->getLand().getMetersPerGrid());
- if ((i >= regionp->getLand().mGridsPerEdge) || (j >= regionp->getLand().mGridsPerEdge))
- {
- // llinfos << "LLViewerWindow::mousePointOnLand probe_point is out of region" << llendl;
- continue;
- }
- land_z = regionp->getLand().mSurfaceZ[ i + j * (regionp->getLand().mGridsPerEdge) ];
- */
-
- land_z = regionp->getLand().resolveHeightRegion(probe_point_region);
-
- //llinfos << "mousePointOnLand refine z " << land_z << llendl;
-
- if (probe_point_region.mV[VZ] < land_z)
- {
- // ...just went under land again
-
- *land_position_global = probe_point_global;
- return TRUE;
- }
- }
- }
-
- return FALSE;
-}
-
-// Saves an image to the harddrive as "SnapshotX" where X >= 1.
-BOOL LLViewerWindow::saveImageNumbered(LLImageFormatted *image)
-{
- if (!image)
- {
- return FALSE;
- }
-
- LLFilePicker::ESaveFilter pick_type;
- std::string extension("." + image->getExtension());
- if (extension == ".j2c")
- pick_type = LLFilePicker::FFSAVE_J2C;
- else if (extension == ".bmp")
- pick_type = LLFilePicker::FFSAVE_BMP;
- else if (extension == ".jpg")
- pick_type = LLFilePicker::FFSAVE_JPEG;
- else if (extension == ".png")
- pick_type = LLFilePicker::FFSAVE_PNG;
- else if (extension == ".tga")
- pick_type = LLFilePicker::FFSAVE_TGA;
- else
- pick_type = LLFilePicker::FFSAVE_ALL; // ???
-
- // Get a base file location if needed.
- if ( ! isSnapshotLocSet())
- {
- std::string proposed_name( sSnapshotBaseName );
-
- // getSaveFile will append an appropriate extension to the proposed name, based on the ESaveFilter constant passed in.
-
- // pick a directory in which to save
- LLFilePicker& picker = LLFilePicker::instance();
- if (!picker.getSaveFile(pick_type, proposed_name))
- {
- // Clicked cancel
- return FALSE;
- }
-
- // Copy the directory + file name
- std::string filepath = picker.getFirstFile();
-
- LLViewerWindow::sSnapshotBaseName = gDirUtilp->getBaseFileName(filepath, true);
- LLViewerWindow::sSnapshotDir = gDirUtilp->getDirName(filepath);
- }
-
- // Look for an unused file name
- std::string filepath;
- S32 i = 1;
- S32 err = 0;
-
- do
- {
- filepath = sSnapshotDir;
- filepath += gDirUtilp->getDirDelimiter();
- filepath += sSnapshotBaseName;
- filepath += llformat("_%.3d",i);
- filepath += extension;
-
- llstat stat_info;
- err = LLFile::stat( filepath, &stat_info );
- i++;
- }
- while( -1 != err ); // search until the file is not found (i.e., stat() gives an error).
-
- return image->save(filepath);
-}
-
-void LLViewerWindow::resetSnapshotLoc()
-{
- sSnapshotDir.clear();
-}
-
-static S32 BORDERHEIGHT = 0;
-static S32 BORDERWIDTH = 0;
-
-// static
-void LLViewerWindow::movieSize(S32 new_width, S32 new_height)
-{
- LLCoordScreen size;
- gViewerWindow->mWindow->getSize(&size);
- if ( (size.mX != new_width + BORDERWIDTH)
- ||(size.mY != new_height + BORDERHEIGHT))
- {
- // use actual display dimensions, not virtual UI dimensions
- S32 x = gViewerWindow->getWindowWidthRaw();
- S32 y = gViewerWindow->getWindowHeightRaw();
- BORDERWIDTH = size.mX - x;
- BORDERHEIGHT = size.mY- y;
- LLCoordScreen new_size(new_width + BORDERWIDTH,
- new_height + BORDERHEIGHT);
- gViewerWindow->mWindow->setSize(new_size);
- }
-}
-
-BOOL LLViewerWindow::saveSnapshot( const std::string& filepath, S32 image_width, S32 image_height, BOOL show_ui, BOOL do_rebuild, ESnapshotType type)
-{
- llinfos << "Saving snapshot to: " << filepath << llendl;
-
- LLPointer<LLImageRaw> raw = new LLImageRaw;
- BOOL success = rawSnapshot(raw, image_width, image_height, TRUE, FALSE, show_ui, do_rebuild);
-
- if (success)
- {
- LLPointer<LLImageBMP> bmp_image = new LLImageBMP;
- success = bmp_image->encode(raw, 0.0f);
- if( success )
- {
- success = bmp_image->save(filepath);
- }
- else
- {
- llwarns << "Unable to encode bmp snapshot" << llendl;
- }
- }
- else
- {
- llwarns << "Unable to capture raw snapshot" << llendl;
- }
-
- return success;
-}
-
-
-void LLViewerWindow::playSnapshotAnimAndSound()
-{
- if (gSavedSettings.getBOOL("QuietSnapshotsToDisk"))
- {
- return;
- }
- gAgent.sendAnimationRequest(ANIM_AGENT_SNAPSHOT, ANIM_REQUEST_START);
- send_sound_trigger(LLUUID(gSavedSettings.getString("UISndSnapshot")), 1.0f);
-}
-
-BOOL LLViewerWindow::thumbnailSnapshot(LLImageRaw *raw, S32 preview_width, S32 preview_height, BOOL show_ui, BOOL do_rebuild, ESnapshotType type)
-{
- return rawSnapshot(raw, preview_width, preview_height, FALSE, FALSE, show_ui, do_rebuild, type);
-}
-
-// Saves the image from the screen to the specified filename and path.
-BOOL LLViewerWindow::rawSnapshot(LLImageRaw *raw, S32 image_width, S32 image_height,
- BOOL keep_window_aspect, BOOL is_texture, BOOL show_ui, BOOL do_rebuild, ESnapshotType type, S32 max_size)
-{
- if (!raw)
- {
- return FALSE;
- }
-
- // PRE SNAPSHOT
- gDisplaySwapBuffers = FALSE;
-
- glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
- setCursor(UI_CURSOR_WAIT);
-
- // Hide all the UI widgets first and draw a frame
- BOOL prev_draw_ui = gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI) ? TRUE : FALSE;
-
- show_ui = show_ui ? TRUE : FALSE;
-
- if ( prev_draw_ui != show_ui)
- {
- LLPipeline::toggleRenderDebugFeature((void*)LLPipeline::RENDER_DEBUG_FEATURE_UI);
- }
-
- BOOL hide_hud = !gSavedSettings.getBOOL("RenderHUDInSnapshot") && LLPipeline::sShowHUDAttachments;
- if (hide_hud)
- {
- LLPipeline::sShowHUDAttachments = FALSE;
- }
-
- // if not showing ui, use full window to render world view
- updateWorldViewRect(!show_ui);
-
- // Copy screen to a buffer
- // crop sides or top and bottom, if taking a snapshot of different aspect ratio
- // from window
- LLRect window_rect = show_ui ? getWindowRectRaw() : getWorldViewRectRaw();
-
- S32 snapshot_width = window_rect.getWidth();
- S32 snapshot_height = window_rect.getHeight();
- // SNAPSHOT
- S32 window_width = snapshot_width;
- S32 window_height = snapshot_height;
-
- if (show_ui)
- {
- image_width = llmin(image_width, window_width);
- image_height = llmin(image_height, window_height);
- }
-
- F32 scale_factor = 1.0f ;
- if(!keep_window_aspect) //image cropping
- {
- F32 ratio = llmin( (F32)window_width / image_width , (F32)window_height / image_height) ;
- snapshot_width = (S32)(ratio * image_width) ;
- snapshot_height = (S32)(ratio * image_height) ;
- scale_factor = llmax(1.0f, 1.0f / ratio) ;
- }
- else //the scene(window) proportion needs to be maintained.
- {
- if(image_width > window_width || image_height > window_height) //need to enlarge the scene
- {
- F32 ratio = llmin( (F32)window_width / image_width , (F32)window_height / image_height) ;
- snapshot_width = (S32)(ratio * image_width) ;
- snapshot_height = (S32)(ratio * image_height) ;
- scale_factor = llmax(1.0f, 1.0f / ratio) ;
- }
- }
-
- if (show_ui && scale_factor > 1.f)
- {
- llwarns << "over scaling UI not supported." << llendl;
- }
-
- S32 buffer_x_offset = llfloor(((window_width - snapshot_width) * scale_factor) / 2.f);
- S32 buffer_y_offset = llfloor(((window_height - snapshot_height) * scale_factor) / 2.f);
-
- S32 image_buffer_x = llfloor(snapshot_width*scale_factor) ;
- S32 image_buffer_y = llfloor(snapshot_height *scale_factor) ;
-
- if(image_buffer_x > max_size || image_buffer_y > max_size) //boundary check to avoid memory overflow
- {
- scale_factor *= llmin((F32)max_size / image_buffer_x, (F32)max_size / image_buffer_y) ;
- image_buffer_x = llfloor(snapshot_width*scale_factor) ;
- image_buffer_y = llfloor(snapshot_height *scale_factor) ;
- }
- if(image_buffer_x > 0 && image_buffer_y > 0)
- {
- raw->resize(image_buffer_x, image_buffer_y, 3);
- }
- else
- {
- return FALSE ;
- }
- if(raw->isBufferInvalid())
- {
- return FALSE ;
- }
-
- BOOL high_res = scale_factor >= 2.f; // Font scaling is slow, only do so if rez is much higher
- if (high_res && show_ui)
- {
- llwarns << "High res UI snapshot not supported. " << llendl;
- /*send_agent_pause();
- //rescale fonts
- initFonts(scale_factor);
- LLHUDObject::reshapeAll();*/
- }
-
- S32 output_buffer_offset_y = 0;
-
- F32 depth_conversion_factor_1 = (LLViewerCamera::getInstance()->getFar() + LLViewerCamera::getInstance()->getNear()) / (2.f * LLViewerCamera::getInstance()->getFar() * LLViewerCamera::getInstance()->getNear());
- F32 depth_conversion_factor_2 = (LLViewerCamera::getInstance()->getFar() - LLViewerCamera::getInstance()->getNear()) / (2.f * LLViewerCamera::getInstance()->getFar() * LLViewerCamera::getInstance()->getNear());
-
- gObjectList.generatePickList(*LLViewerCamera::getInstance());
-
- for (int subimage_y = 0; subimage_y < scale_factor; ++subimage_y)
- {
- S32 subimage_y_offset = llclamp(buffer_y_offset - (subimage_y * window_height), 0, window_height);;
- // handle fractional columns
- U32 read_height = llmax(0, (window_height - subimage_y_offset) -
- llmax(0, (window_height * (subimage_y + 1)) - (buffer_y_offset + raw->getHeight())));
-
- S32 output_buffer_offset_x = 0;
- for (int subimage_x = 0; subimage_x < scale_factor; ++subimage_x)
- {
- gDisplaySwapBuffers = FALSE;
- gDepthDirty = TRUE;
-
- const U32 subfield = subimage_x+(subimage_y*llceil(scale_factor));
-
- if (LLPipeline::sRenderDeferred)
- {
- display(do_rebuild, scale_factor, subfield, TRUE);
- }
- else
- {
- display(do_rebuild, scale_factor, subfield, TRUE);
- // Required for showing the GUI in snapshots and performing bloom composite overlay
- // Call even if show_ui is FALSE
- render_ui(scale_factor, subfield);
- }
-
- S32 subimage_x_offset = llclamp(buffer_x_offset - (subimage_x * window_width), 0, window_width);
- // handle fractional rows
- U32 read_width = llmax(0, (window_width - subimage_x_offset) -
- llmax(0, (window_width * (subimage_x + 1)) - (buffer_x_offset + raw->getWidth())));
- for(U32 out_y = 0; out_y < read_height ; out_y++)
- {
- S32 output_buffer_offset = (
- (out_y * (raw->getWidth())) // ...plus iterated y...
- + (window_width * subimage_x) // ...plus subimage start in x...
- + (raw->getWidth() * window_height * subimage_y) // ...plus subimage start in y...
- - output_buffer_offset_x // ...minus buffer padding x...
- - (output_buffer_offset_y * (raw->getWidth())) // ...minus buffer padding y...
- ) * raw->getComponents();
-
- // Ping the wathdog thread every 100 lines to keep us alive (arbitrary number, feel free to change)
- if (out_y % 100 == 0)
- {
- LLAppViewer::instance()->pingMainloopTimeout("LLViewerWindow::rawSnapshot");
- }
-
- if (type == SNAPSHOT_TYPE_COLOR)
- {
- glReadPixels(
- subimage_x_offset, out_y + subimage_y_offset,
- read_width, 1,
- GL_RGB, GL_UNSIGNED_BYTE,
- raw->getData() + output_buffer_offset
- );
- }
- else // SNAPSHOT_TYPE_DEPTH
- {
- LLPointer<LLImageRaw> depth_line_buffer = new LLImageRaw(read_width, 1, sizeof(GL_FLOAT)); // need to store floating point values
- glReadPixels(
- subimage_x_offset, out_y + subimage_y_offset,
- read_width, 1,
- GL_DEPTH_COMPONENT, GL_FLOAT,
- depth_line_buffer->getData()// current output pixel is beginning of buffer...
- );
-
- for (S32 i = 0; i < (S32)read_width; i++)
- {
- F32 depth_float = *(F32*)(depth_line_buffer->getData() + (i * sizeof(F32)));
-
- F32 linear_depth_float = 1.f / (depth_conversion_factor_1 - (depth_float * depth_conversion_factor_2));
- U8 depth_byte = F32_to_U8(linear_depth_float, LLViewerCamera::getInstance()->getNear(), LLViewerCamera::getInstance()->getFar());
- //write converted scanline out to result image
- for(S32 j = 0; j < raw->getComponents(); j++)
- {
- *(raw->getData() + output_buffer_offset + (i * raw->getComponents()) + j) = depth_byte;
- }
- }
- }
- }
- output_buffer_offset_x += subimage_x_offset;
- stop_glerror();
- }
- output_buffer_offset_y += subimage_y_offset;
- }
-
- gDisplaySwapBuffers = FALSE;
- gDepthDirty = TRUE;
-
- // POST SNAPSHOT
- if (!gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
- {
- LLPipeline::toggleRenderDebugFeature((void*)LLPipeline::RENDER_DEBUG_FEATURE_UI);
- }
-
- if (hide_hud)
- {
- LLPipeline::sShowHUDAttachments = TRUE;
- }
-
- /*if (high_res)
- {
- initFonts(1.f);
- LLHUDObject::reshapeAll();
- }*/
-
- // Pre-pad image to number of pixels such that the line length is a multiple of 4 bytes (for BMP encoding)
- // Note: this formula depends on the number of components being 3. Not obvious, but it's correct.
- image_width += (image_width * 3) % 4;
-
- BOOL ret = TRUE ;
- // Resize image
- if(llabs(image_width - image_buffer_x) > 4 || llabs(image_height - image_buffer_y) > 4)
- {
- ret = raw->scale( image_width, image_height );
- }
- else if(image_width != image_buffer_x || image_height != image_buffer_y)
- {
- ret = raw->scale( image_width, image_height, FALSE );
- }
-
-
- setCursor(UI_CURSOR_ARROW);
-
- if (do_rebuild)
- {
- // If we had to do a rebuild, that means that the lists of drawables to be rendered
- // was empty before we started.
- // Need to reset these, otherwise we call state sort on it again when render gets called the next time
- // and we stand a good chance of crashing on rebuild because the render drawable arrays have multiple copies of
- // objects on them.
- gPipeline.resetDrawOrders();
- }
-
- if (high_res)
- {
- send_agent_resume();
- }
-
- return ret;
-}
-
-void LLViewerWindow::destroyWindow()
-{
- if (mWindow)
- {
- LLWindowManager::destroyWindow(mWindow);
- }
- mWindow = NULL;
-}
-
-
-void LLViewerWindow::drawMouselookInstructions()
-{
- // Draw instructions for mouselook ("Press ESC to return to World View" partially transparent at the bottom of the screen.)
- const std::string instructions = LLTrans::getString("LeaveMouselook");
- const LLFontGL* font = LLFontGL::getFont(LLFontDescriptor("SansSerif", "Large", LLFontGL::BOLD));
-
- //to be on top of Bottom bar when it is opened
- const S32 INSTRUCTIONS_PAD = 50;
-
- font->renderUTF8(
- instructions, 0,
- getWorldViewRectScaled().getCenterX(),
- getWorldViewRectScaled().mBottom + INSTRUCTIONS_PAD,
- LLColor4( 1.0f, 1.0f, 1.0f, 0.5f ),
- LLFontGL::HCENTER, LLFontGL::TOP,
- LLFontGL::NORMAL,LLFontGL::DROP_SHADOW);
-}
-
-void* LLViewerWindow::getPlatformWindow() const
-{
- return mWindow->getPlatformWindow();
-}
-
-void* LLViewerWindow::getMediaWindow() const
-{
- return mWindow->getMediaWindow();
-}
-
-void LLViewerWindow::focusClient() const
-{
- return mWindow->focusClient();
-}
-
-LLRootView* LLViewerWindow::getRootView() const
-{
- return mRootView;
-}
-
-LLRect LLViewerWindow::getWorldViewRectScaled() const
-{
- return mWorldViewRectScaled;
-}
-
-S32 LLViewerWindow::getWorldViewHeightScaled() const
-{
- return mWorldViewRectScaled.getHeight();
-}
-
-S32 LLViewerWindow::getWorldViewWidthScaled() const
-{
- return mWorldViewRectScaled.getWidth();
-}
-
-
-S32 LLViewerWindow::getWorldViewHeightRaw() const
-{
- return mWorldViewRectRaw.getHeight();
-}
-
-S32 LLViewerWindow::getWorldViewWidthRaw() const
-{
- return mWorldViewRectRaw.getWidth();
-}
-
-S32 LLViewerWindow::getWindowHeightScaled() const
-{
- return mWindowRectScaled.getHeight();
-}
-
-S32 LLViewerWindow::getWindowWidthScaled() const
-{
- return mWindowRectScaled.getWidth();
-}
-
-S32 LLViewerWindow::getWindowHeightRaw() const
-{
- return mWindowRectRaw.getHeight();
-}
-
-S32 LLViewerWindow::getWindowWidthRaw() const
-{
- return mWindowRectRaw.getWidth();
-}
-
-void LLViewerWindow::setup2DRender()
-{
- // setup ortho camera
- gl_state_for_2d(mWindowRectRaw.getWidth(), mWindowRectRaw.getHeight());
- setup2DViewport();
-}
-
-void LLViewerWindow::setup2DViewport(S32 x_offset, S32 y_offset)
-{
- gGLViewport[0] = mWindowRectRaw.mLeft + x_offset;
- gGLViewport[1] = mWindowRectRaw.mBottom + y_offset;
- gGLViewport[2] = mWindowRectRaw.getWidth();
- gGLViewport[3] = mWindowRectRaw.getHeight();
- glViewport(gGLViewport[0], gGLViewport[1], gGLViewport[2], gGLViewport[3]);
-}
-
-
-void LLViewerWindow::setup3DRender()
-{
- // setup perspective camera
- LLViewerCamera::getInstance()->setPerspective(NOT_FOR_SELECTION, mWorldViewRectRaw.mLeft, mWorldViewRectRaw.mBottom, mWorldViewRectRaw.getWidth(), mWorldViewRectRaw.getHeight(), FALSE, LLViewerCamera::getInstance()->getNear(), MAX_FAR_CLIP*2.f);
- setup3DViewport();
-}
-
-void LLViewerWindow::setup3DViewport(S32 x_offset, S32 y_offset)
-{
- gGLViewport[0] = mWorldViewRectRaw.mLeft + x_offset;
- gGLViewport[1] = mWorldViewRectRaw.mBottom + y_offset;
- gGLViewport[2] = mWorldViewRectRaw.getWidth();
- gGLViewport[3] = mWorldViewRectRaw.getHeight();
- glViewport(gGLViewport[0], gGLViewport[1], gGLViewport[2], gGLViewport[3]);
-}
-
-void LLViewerWindow::setShowProgress(const BOOL show)
-{
- if (mProgressView)
- {
- mProgressView->setVisible(show);
- }
-}
-
-BOOL LLViewerWindow::getShowProgress() const
-{
- return (mProgressView && mProgressView->getVisible());
-}
-
-void LLViewerWindow::setProgressString(const std::string& string)
-{
- if (mProgressView)
- {
- mProgressView->setText(string);
- }
-}
-
-void LLViewerWindow::setProgressMessage(const std::string& msg)
-{
- if(mProgressView)
- {
- mProgressView->setMessage(msg);
- }
-}
-
-void LLViewerWindow::setProgressPercent(const F32 percent)
-{
- if (mProgressView)
- {
- mProgressView->setPercent(percent);
- }
-}
-
-void LLViewerWindow::setProgressCancelButtonVisible( BOOL b, const std::string& label )
-{
- if (mProgressView)
- {
- mProgressView->setCancelButtonVisible( b, label );
- }
-}
-
-
-LLProgressView *LLViewerWindow::getProgressView() const
-{
- return mProgressView;
-}
-
-void LLViewerWindow::dumpState()
-{
- llinfos << "LLViewerWindow Active " << S32(mActive) << llendl;
- llinfos << "mWindow visible " << S32(mWindow->getVisible())
- << " minimized " << S32(mWindow->getMinimized())
- << llendl;
-}
-
-void LLViewerWindow::stopGL(BOOL save_state)
-{
- //Note: --bao
- //if not necessary, do not change the order of the function calls in this function.
- //if change something, make sure it will not break anything.
- //especially be careful to put anything behind gTextureList.destroyGL(save_state);
- if (!gGLManager.mIsDisabled)
- {
- llinfos << "Shutting down GL..." << llendl;
-
- // Pause texture decode threads (will get unpaused during main loop)
- LLAppViewer::getTextureCache()->pause();
- LLAppViewer::getImageDecodeThread()->pause();
- LLAppViewer::getTextureFetch()->pause();
-
- gSky.destroyGL();
- stop_glerror();
-
- LLManipTranslate::destroyGL() ;
- stop_glerror();
-
- gBumpImageList.destroyGL();
- stop_glerror();
-
- LLFontGL::destroyAllGL();
- stop_glerror();
-
- LLVOAvatar::destroyGL();
- stop_glerror();
-
- LLViewerDynamicTexture::destroyGL();
- stop_glerror();
-
- if (gPipeline.isInit())
- {
- gPipeline.destroyGL();
- }
-
- gCone.cleanupGL();
- gBox.cleanupGL();
- gSphere.cleanupGL();
- gCylinder.cleanupGL();
-
- if(gPostProcess)
- {
- gPostProcess->invalidate();
- }
-
- gTextureList.destroyGL(save_state);
- stop_glerror();
-
- gGLManager.mIsDisabled = TRUE;
- stop_glerror();
-
- llinfos << "Remaining allocated texture memory: " << LLImageGL::sGlobalTextureMemoryInBytes << " bytes" << llendl;
- }
-}
-
-void LLViewerWindow::restoreGL(const std::string& progress_message)
-{
- //Note: --bao
- //if not necessary, do not change the order of the function calls in this function.
- //if change something, make sure it will not break anything.
- //especially, be careful to put something before gTextureList.restoreGL();
- if (gGLManager.mIsDisabled)
- {
- llinfos << "Restoring GL..." << llendl;
- gGLManager.mIsDisabled = FALSE;
-
- initGLDefaults();
- LLGLState::restoreGL();
-
- gTextureList.restoreGL();
-
- // for future support of non-square pixels, and fonts that are properly stretched
- //LLFontGL::destroyDefaultFonts();
- initFonts();
-
- gSky.restoreGL();
- gPipeline.restoreGL();
- LLDrawPoolWater::restoreGL();
- LLManipTranslate::restoreGL();
-
- gBumpImageList.restoreGL();
- LLViewerDynamicTexture::restoreGL();
- LLVOAvatar::restoreGL();
-
- gResizeScreenTexture = TRUE;
- gWindowResized = TRUE;
-
- if (isAgentAvatarValid() && !gAgentAvatarp->isUsingBakedTextures())
- {
- LLVisualParamHint::requestHintUpdates();
- }
-
- if (!progress_message.empty())
- {
- gRestoreGLTimer.reset();
- gRestoreGL = TRUE;
- setShowProgress(TRUE);
- setProgressString(progress_message);
- }
- llinfos << "...Restoring GL done" << llendl;
- if(!LLAppViewer::instance()->restoreErrorTrap())
- {
- llwarns << " Someone took over my signal/exception handler (post restoreGL)!" << llendl;
- }
-
- }
-}
-
-void LLViewerWindow::initFonts(F32 zoom_factor)
-{
- LLFontGL::destroyAllGL();
- // Initialize with possibly different zoom factor
- LLFontGL::initClass( gSavedSettings.getF32("FontScreenDPI"),
- mDisplayScale.mV[VX] * zoom_factor,
- mDisplayScale.mV[VY] * zoom_factor,
- gDirUtilp->getAppRODataDir(),
- LLUI::getXUIPaths());
- // Force font reloads, which can be very slow
- LLFontGL::loadDefaultFonts();
-}
-
-void LLViewerWindow::requestResolutionUpdate()
-{
- mResDirty = true;
-}
-
-void LLViewerWindow::checkSettings()
-{
- if (mStatesDirty)
- {
- gGL.refreshState();
- LLViewerShaderMgr::instance()->setShaders();
- mStatesDirty = false;
- }
-
- // We want to update the resolution AFTER the states getting refreshed not before.
- if (mResDirty)
- {
- reshape(getWindowWidthRaw(), getWindowHeightRaw());
- mResDirty = false;
- }
-}
-
-void LLViewerWindow::restartDisplay(BOOL show_progress_bar)
-{
- llinfos << "Restaring GL" << llendl;
- stopGL();
- if (show_progress_bar)
- {
- restoreGL(LLTrans::getString("ProgressChangingResolution"));
- }
- else
- {
- restoreGL();
- }
-}
-
-BOOL LLViewerWindow::changeDisplaySettings(LLCoordScreen size, BOOL disable_vsync, BOOL show_progress_bar)
-{
- //BOOL was_maximized = gSavedSettings.getBOOL("WindowMaximized");
-
- //gResizeScreenTexture = TRUE;
-
- //U32 fsaa = gSavedSettings.getU32("RenderFSAASamples");
- //U32 old_fsaa = mWindow->getFSAASamples();
-
- // if not maximized, use the request size
- if (!mWindow->getMaximized())
- {
- mWindow->setSize(size);
- }
-
- //if (fsaa == old_fsaa)
- {
- return TRUE;
- }
-
-/*
-
- // Close floaters that don't handle settings change
- LLFloaterReg::hideInstance("snapshot");
-
- BOOL result_first_try = FALSE;
- BOOL result_second_try = FALSE;
-
- LLFocusableElement* keyboard_focus = gFocusMgr.getKeyboardFocus();
- send_agent_pause();
- llinfos << "Stopping GL during changeDisplaySettings" << llendl;
- stopGL();
- mIgnoreActivate = TRUE;
- LLCoordScreen old_size;
- LLCoordScreen old_pos;
- mWindow->getSize(&old_size);
-
- //mWindow->setFSAASamples(fsaa);
-
- result_first_try = mWindow->switchContext(false, size, disable_vsync);
- if (!result_first_try)
- {
- // try to switch back
- //mWindow->setFSAASamples(old_fsaa);
- result_second_try = mWindow->switchContext(false, old_size, disable_vsync);
-
- if (!result_second_try)
- {
- // we are stuck...try once again with a minimal resolution?
- send_agent_resume();
- mIgnoreActivate = FALSE;
- return FALSE;
- }
- }
- send_agent_resume();
-
- llinfos << "Restoring GL during resolution change" << llendl;
- if (show_progress_bar)
- {
- restoreGL(LLTrans::getString("ProgressChangingResolution"));
- }
- else
- {
- restoreGL();
- }
-
- if (!result_first_try)
- {
- LLSD args;
- args["RESX"] = llformat("%d",size.mX);
- args["RESY"] = llformat("%d",size.mY);
- LLNotificationsUtil::add("ResolutionSwitchFail", args);
- size = old_size; // for reshape below
- }
-
- BOOL success = result_first_try || result_second_try;
-
- if (success)
- {
- // maximize window if was maximized, else reposition
- if (was_maximized)
- {
- mWindow->maximize();
- }
- else
- {
- S32 windowX = gSavedSettings.getS32("WindowX");
- S32 windowY = gSavedSettings.getS32("WindowY");
-
- mWindow->setPosition(LLCoordScreen ( windowX, windowY ) );
- }
- }
-
- mIgnoreActivate = FALSE;
- gFocusMgr.setKeyboardFocus(keyboard_focus);
-
- return success;
-
- */
-}
-
-F32 LLViewerWindow::getWorldViewAspectRatio() const
-{
- F32 world_aspect = (F32)mWorldViewRectRaw.getWidth() / (F32)mWorldViewRectRaw.getHeight();
- return world_aspect;
-}
-
-void LLViewerWindow::calcDisplayScale()
-{
- F32 ui_scale_factor = gSavedSettings.getF32("UIScaleFactor");
- LLVector2 display_scale;
- display_scale.setVec(llmax(1.f / mWindow->getPixelAspectRatio(), 1.f), llmax(mWindow->getPixelAspectRatio(), 1.f));
- display_scale *= ui_scale_factor;
-
- // limit minimum display scale
- if (display_scale.mV[VX] < MIN_DISPLAY_SCALE || display_scale.mV[VY] < MIN_DISPLAY_SCALE)
- {
- display_scale *= MIN_DISPLAY_SCALE / llmin(display_scale.mV[VX], display_scale.mV[VY]);
- }
-
- if (display_scale != mDisplayScale)
- {
- llinfos << "Setting display scale to " << display_scale << llendl;
-
- mDisplayScale = display_scale;
- // Init default fonts
- initFonts();
- }
-}
-
-//static
-LLRect LLViewerWindow::calcScaledRect(const LLRect & rect, const LLVector2& display_scale)
-{
- LLRect res = rect;
- res.mLeft = llround((F32)res.mLeft / display_scale.mV[VX]);
- res.mRight = llround((F32)res.mRight / display_scale.mV[VX]);
- res.mBottom = llround((F32)res.mBottom / display_scale.mV[VY]);
- res.mTop = llround((F32)res.mTop / display_scale.mV[VY]);
-
- return res;
-}
-
-S32 LLViewerWindow::getChatConsoleBottomPad()
-{
- S32 offset = 0;
-
- if(LLBottomTray::instanceExists())
- offset += LLBottomTray::getInstance()->getRect().getHeight();
-
- return offset;
-}
-
-LLRect LLViewerWindow::getChatConsoleRect()
-{
- LLRect full_window(0, getWindowHeightScaled(), getWindowWidthScaled(), 0);
- LLRect console_rect = full_window;
-
- const S32 CONSOLE_PADDING_TOP = 24;
- const S32 CONSOLE_PADDING_LEFT = 24;
- const S32 CONSOLE_PADDING_RIGHT = 10;
-
- console_rect.mTop -= CONSOLE_PADDING_TOP;
- console_rect.mBottom += getChatConsoleBottomPad();
-
- console_rect.mLeft += CONSOLE_PADDING_LEFT;
-
- static const BOOL CHAT_FULL_WIDTH = gSavedSettings.getBOOL("ChatFullWidth");
-
- if (CHAT_FULL_WIDTH)
- {
- console_rect.mRight -= CONSOLE_PADDING_RIGHT;
- }
- else
- {
- // Make console rect somewhat narrow so having inventory open is
- // less of a problem.
- console_rect.mRight = console_rect.mLeft + 2 * getWindowWidthScaled() / 3;
- }
-
- return console_rect;
-}
-//----------------------------------------------------------------------------
-
-
-//static
-bool LLViewerWindow::onAlert(const LLSD& notify)
-{
- LLNotificationPtr notification = LLNotifications::instance().find(notify["id"].asUUID());
-
- if (gNoRender)
- {
- llinfos << "Alert: " << notification->getName() << llendl;
- notification->respond(LLSD::emptyMap());
- LLNotifications::instance().cancel(notification);
- return false;
- }
-
- // If we're in mouselook, the mouse is hidden and so the user can't click
- // the dialog buttons. In that case, change to First Person instead.
- if( gAgentCamera.cameraMouselook() )
- {
- gAgentCamera.changeCameraToDefault();
- }
- return false;
-}
-
-////////////////////////////////////////////////////////////////////////////
-//
-// LLPickInfo
-//
-LLPickInfo::LLPickInfo()
- : mKeyMask(MASK_NONE),
- mPickCallback(NULL),
- mPickType(PICK_INVALID),
- mWantSurfaceInfo(FALSE),
- mObjectFace(-1),
- mUVCoords(-1.f, -1.f),
- mSTCoords(-1.f, -1.f),
- mXYCoords(-1, -1),
- mIntersection(),
- mNormal(),
- mBinormal(),
- mHUDIcon(NULL),
- mPickTransparent(FALSE)
-{
-}
-
-LLPickInfo::LLPickInfo(const LLCoordGL& mouse_pos,
- MASK keyboard_mask,
- BOOL pick_transparent,
- BOOL pick_uv_coords,
- void (*pick_callback)(const LLPickInfo& pick_info))
- : mMousePt(mouse_pos),
- mKeyMask(keyboard_mask),
- mPickCallback(pick_callback),
- mPickType(PICK_INVALID),
- mWantSurfaceInfo(pick_uv_coords),
- mObjectFace(-1),
- mUVCoords(-1.f, -1.f),
- mSTCoords(-1.f, -1.f),
- mXYCoords(-1, -1),
- mNormal(),
- mBinormal(),
- mHUDIcon(NULL),
- mPickTransparent(pick_transparent)
-{
-}
-
-void LLPickInfo::fetchResults()
-{
-
- S32 face_hit = -1;
- LLVector3 intersection, normal, binormal;
- LLVector2 uv;
-
- LLHUDIcon* hit_icon = gViewerWindow->cursorIntersectIcon(mMousePt.mX, mMousePt.mY, 512.f, &intersection);
-
- F32 icon_dist = 0.f;
- if (hit_icon)
- {
- icon_dist = (LLViewerCamera::getInstance()->getOrigin()-intersection).magVec();
- }
- LLViewerObject* hit_object = gViewerWindow->cursorIntersect(mMousePt.mX, mMousePt.mY, 512.f,
- NULL, -1, mPickTransparent, &face_hit,
- &intersection, &uv, &normal, &binormal);
-
- mPickPt = mMousePt;
-
- U32 te_offset = face_hit > -1 ? face_hit : 0;
-
- //unproject relative clicked coordinate from window coordinate using GL
-
- LLViewerObject* objectp = hit_object;
-
- if (hit_icon &&
- (!objectp ||
- icon_dist < (LLViewerCamera::getInstance()->getOrigin()-intersection).magVec()))
- {
- // was this name referring to a hud icon?
- mHUDIcon = hit_icon;
- mPickType = PICK_ICON;
- mPosGlobal = mHUDIcon->getPositionGlobal();
- }
- else if (objectp)
- {
- if( objectp->getPCode() == LLViewerObject::LL_VO_SURFACE_PATCH )
- {
- // Hit land
- mPickType = PICK_LAND;
- mObjectID.setNull(); // land has no id
-
- // put global position into land_pos
- LLVector3d land_pos;
- if (!gViewerWindow->mousePointOnLandGlobal(mPickPt.mX, mPickPt.mY, &land_pos))
- {
- // The selected point is beyond the draw distance or is otherwise
- // not selectable. Return before calling mPickCallback().
- return;
- }
-
- // Fudge the land focus a little bit above ground.
- mPosGlobal = land_pos + LLVector3d::z_axis * 0.1f;
- }
- else
- {
- if(isFlora(objectp))
- {
- mPickType = PICK_FLORA;
- }
- else
- {
- mPickType = PICK_OBJECT;
- }
- mObjectOffset = gAgentCamera.calcFocusOffset(objectp, intersection, mPickPt.mX, mPickPt.mY);
- mObjectID = objectp->mID;
- mObjectFace = (te_offset == NO_FACE) ? -1 : (S32)te_offset;
-
- mPosGlobal = gAgent.getPosGlobalFromAgent(intersection);
-
- if (mWantSurfaceInfo)
- {
- getSurfaceInfo();
- }
- }
- }
-
- if (mPickCallback)
- {
- mPickCallback(*this);
- }
-}
-
-LLPointer<LLViewerObject> LLPickInfo::getObject() const
-{
- return gObjectList.findObject( mObjectID );
-}
-
-void LLPickInfo::updateXYCoords()
-{
- if (mObjectFace > -1)
- {
- const LLTextureEntry* tep = getObject()->getTE(mObjectFace);
- LLPointer<LLViewerTexture> imagep = LLViewerTextureManager::getFetchedTexture(tep->getID());
- if(mUVCoords.mV[VX] >= 0.f && mUVCoords.mV[VY] >= 0.f && imagep.notNull())
- {
- mXYCoords.mX = llround(mUVCoords.mV[VX] * (F32)imagep->getWidth());
- mXYCoords.mY = llround((1.f - mUVCoords.mV[VY]) * (F32)imagep->getHeight());
- }
- }
-}
-
-void LLPickInfo::getSurfaceInfo()
-{
- // set values to uninitialized - this is what we return if no intersection is found
- mObjectFace = -1;
- mUVCoords = LLVector2(-1, -1);
- mSTCoords = LLVector2(-1, -1);
- mXYCoords = LLCoordScreen(-1, -1);
- mIntersection = LLVector3(0,0,0);
- mNormal = LLVector3(0,0,0);
- mBinormal = LLVector3(0,0,0);
-
- LLViewerObject* objectp = getObject();
-
- if (objectp)
- {
- if (gViewerWindow->cursorIntersect(llround((F32)mMousePt.mX), llround((F32)mMousePt.mY), 1024.f,
- objectp, -1, mPickTransparent,
- &mObjectFace,
- &mIntersection,
- &mSTCoords,
- &mNormal,
- &mBinormal))
- {
- // if we succeeded with the intersect above, compute the texture coordinates:
-
- if (objectp->mDrawable.notNull() && mObjectFace > -1)
- {
- LLFace* facep = objectp->mDrawable->getFace(mObjectFace);
-
- mUVCoords = facep->surfaceToTexture(mSTCoords, mIntersection, mNormal);
- }
-
- // and XY coords:
- updateXYCoords();
-
- }
- }
-}
-
-
-/* code to get UV via a special UV render - removed in lieu of raycast method
-LLVector2 LLPickInfo::pickUV()
-{
- LLVector2 result(-1.f, -1.f);
-
- LLViewerObject* objectp = getObject();
- if (!objectp)
- {
- return result;
- }
-
- if (mObjectFace > -1 &&
- objectp->mDrawable.notNull() && objectp->getPCode() == LL_PCODE_VOLUME &&
- mObjectFace < objectp->mDrawable->getNumFaces())
- {
- S32 scaled_x = llround((F32)mPickPt.mX * gViewerWindow->getDisplayScale().mV[VX]);
- S32 scaled_y = llround((F32)mPickPt.mY * gViewerWindow->getDisplayScale().mV[VY]);
- const S32 UV_PICK_WIDTH = 5;
- const S32 UV_PICK_HALF_WIDTH = (UV_PICK_WIDTH - 1) / 2;
- U8 uv_pick_buffer[UV_PICK_WIDTH * UV_PICK_WIDTH * 4];
- LLFace* facep = objectp->mDrawable->getFace(mObjectFace);
- if (facep)
- {
- LLGLState scissor_state(GL_SCISSOR_TEST);
- scissor_state.enable();
- LLViewerCamera::getInstance()->setPerspective(FOR_SELECTION, scaled_x - UV_PICK_HALF_WIDTH, scaled_y - UV_PICK_HALF_WIDTH, UV_PICK_WIDTH, UV_PICK_WIDTH, FALSE);
- //glViewport(scaled_x - UV_PICK_HALF_WIDTH, scaled_y - UV_PICK_HALF_WIDTH, UV_PICK_WIDTH, UV_PICK_WIDTH);
- glScissor(scaled_x - UV_PICK_HALF_WIDTH, scaled_y - UV_PICK_HALF_WIDTH, UV_PICK_WIDTH, UV_PICK_WIDTH);
-
- glClear(GL_DEPTH_BUFFER_BIT);
-
- facep->renderSelectedUV();
-
- glReadPixels(scaled_x - UV_PICK_HALF_WIDTH, scaled_y - UV_PICK_HALF_WIDTH, UV_PICK_WIDTH, UV_PICK_WIDTH, GL_RGBA, GL_UNSIGNED_BYTE, uv_pick_buffer);
- U8* center_pixel = &uv_pick_buffer[4 * ((UV_PICK_WIDTH * UV_PICK_HALF_WIDTH) + UV_PICK_HALF_WIDTH + 1)];
-
- result.mV[VX] = (F32)((center_pixel[VGREEN] & 0xf) + (16.f * center_pixel[VRED])) / 4095.f;
- result.mV[VY] = (F32)((center_pixel[VGREEN] >> 4) + (16.f * center_pixel[VBLUE])) / 4095.f;
- }
- }
-
- return result;
-} */
-
-
-//static
-bool LLPickInfo::isFlora(LLViewerObject* object)
-{
- if (!object) return false;
-
- LLPCode pcode = object->getPCode();
-
- if( (LL_PCODE_LEGACY_GRASS == pcode)
- || (LL_PCODE_LEGACY_TREE == pcode)
- || (LL_PCODE_TREE_NEW == pcode))
- {
- return true;
- }
- return false;
-}
+/**
+ * @file llviewerwindow.cpp
+ * @brief Implementation of the LLViewerWindow class.
+ *
+ * $LicenseInfo:firstyear=2001&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h"
+#include "llviewerwindow.h"
+
+#if LL_WINDOWS
+#pragma warning (disable : 4355) // 'this' used in initializer list: yes, intentionally
+#endif
+
+// system library includes
+#include <stdio.h>
+#include <iostream>
+#include <fstream>
+#include <algorithm>
+
+#include "llagent.h"
+#include "llagentcamera.h"
+#include "llfloaterreg.h"
+#include "llmeshrepository.h"
+#include "llpanellogin.h"
+#include "llviewerkeyboard.h"
+#include "llviewermenu.h"
+
+#include "llviewquery.h"
+#include "llxmltree.h"
+#include "llslurl.h"
+//#include "llviewercamera.h"
+#include "llrender.h"
+
+#include "llvoiceclient.h" // for push-to-talk button handling
+
+//
+// TODO: Many of these includes are unnecessary. Remove them.
+//
+
+// linden library includes
+#include "llaudioengine.h" // mute on minimize
+#include "indra_constants.h"
+#include "llassetstorage.h"
+#include "llerrorcontrol.h"
+#include "llfontgl.h"
+#include "llmousehandler.h"
+#include "llrect.h"
+#include "llsky.h"
+#include "llstring.h"
+#include "llui.h"
+#include "lluuid.h"
+#include "llview.h"
+#include "llxfermanager.h"
+#include "message.h"
+#include "object_flags.h"
+#include "lltimer.h"
+#include "timing.h"
+#include "llviewermenu.h"
+#include "lltooltip.h"
+#include "llmediaentry.h"
+#include "llurldispatcher.h"
+
+// newview includes
+#include "llagent.h"
+#include "llbox.h"
+#include "llconsole.h"
+#include "llviewercontrol.h"
+#include "llcylinder.h"
+#include "lldebugview.h"
+#include "lldir.h"
+#include "lldrawable.h"
+#include "lldrawpoolalpha.h"
+#include "lldrawpoolbump.h"
+#include "lldrawpoolwater.h"
+#include "llmaniptranslate.h"
+#include "llface.h"
+#include "llfeaturemanager.h"
+#include "llfilepicker.h"
+#include "llfirstuse.h"
+#include "llfloater.h"
+#include "llfloaterbuildoptions.h"
+#include "llfloaterbuyland.h"
+#include "llfloatercamera.h"
+#include "llfloaterland.h"
+#include "llfloaterinspect.h"
+#include "llfloatermap.h"
+#include "llfloaternamedesc.h"
+#include "llfloaterpreference.h"
+#include "llfloatersnapshot.h"
+#include "llfloatertools.h"
+#include "llfloaterworldmap.h"
+#include "llfocusmgr.h"
+#include "llfontfreetype.h"
+#include "llgesturemgr.h"
+#include "llglheaders.h"
+#include "lltooltip.h"
+#include "llhudmanager.h"
+#include "llhudobject.h"
+#include "llhudview.h"
+#include "llimagebmp.h"
+#include "llimagej2c.h"
+#include "llimageworker.h"
+#include "llkeyboard.h"
+#include "lllineeditor.h"
+#include "llmenugl.h"
+#include "llmodaldialog.h"
+#include "llmorphview.h"
+#include "llmoveview.h"
+#include "llnavigationbar.h"
+#include "llpopupview.h"
+#include "llpreviewtexture.h"
+#include "llprogressview.h"
+#include "llresmgr.h"
+#include "llsidetray.h"
+#include "llselectmgr.h"
+#include "llrootview.h"
+#include "llrendersphere.h"
+#include "llstartup.h"
+#include "llstatusbar.h"
+#include "llstatview.h"
+#include "llsurface.h"
+#include "llsurfacepatch.h"
+#include "lltexlayer.h"
+#include "lltextbox.h"
+#include "lltexturecache.h"
+#include "lltexturefetch.h"
+#include "lltextureview.h"
+#include "lltool.h"
+#include "lltoolcomp.h"
+#include "lltooldraganddrop.h"
+#include "lltoolface.h"
+#include "lltoolfocus.h"
+#include "lltoolgrab.h"
+#include "lltoolmgr.h"
+#include "lltoolmorph.h"
+#include "lltoolpie.h"
+#include "lltoolselectland.h"
+#include "lltrans.h"
+#include "lluictrlfactory.h"
+#include "llurldispatcher.h" // SLURL from other app instance
+#include "llversioninfo.h"
+#include "llvieweraudio.h"
+#include "llviewercamera.h"
+#include "llviewergesture.h"
+#include "llviewertexturelist.h"
+#include "llviewerinventory.h"
+#include "llviewerkeyboard.h"
+#include "llviewermedia.h"
+#include "llviewermediafocus.h"
+#include "llviewermenu.h"
+#include "llviewermessage.h"
+#include "llviewerobjectlist.h"
+#include "llviewerparcelmgr.h"
+#include "llviewerregion.h"
+#include "llviewershadermgr.h"
+#include "llviewerstats.h"
+#include "llvoavatarself.h"
+#include "llvovolume.h"
+#include "llworld.h"
+#include "llworldmapview.h"
+#include "pipeline.h"
+#include "llappviewer.h"
+#include "llviewerdisplay.h"
+#include "llspatialpartition.h"
+#include "llviewerjoystick.h"
+#include "llviewernetwork.h"
+#include "llpostprocess.h"
+#include "llbottomtray.h"
+#include "llnearbychatbar.h"
+#include "llagentui.h"
+#include "llwearablelist.h"
+
+#include "llnotifications.h"
+#include "llnotificationsutil.h"
+#include "llnotificationmanager.h"
+
+#include "llfloaternotificationsconsole.h"
+
+#include "llnearbychat.h"
+#include "llviewerwindowlistener.h"
+#include "llpaneltopinfobar.h"
+
+#if LL_WINDOWS
+#include <tchar.h> // For Unicode conversion methods
+#endif
+
+//
+// Globals
+//
+void render_ui(F32 zoom_factor = 1.f, int subfield = 0);
+
+extern BOOL gDebugClicks;
+extern BOOL gDisplaySwapBuffers;
+extern BOOL gDepthDirty;
+extern BOOL gResizeScreenTexture;
+
+LLViewerWindow *gViewerWindow = NULL;
+
+LLFrameTimer gAwayTimer;
+LLFrameTimer gAwayTriggerTimer;
+
+BOOL gShowOverlayTitle = FALSE;
+
+LLViewerObject* gDebugRaycastObject = NULL;
+LLVector3 gDebugRaycastIntersection;
+LLVector2 gDebugRaycastTexCoord;
+LLVector3 gDebugRaycastNormal;
+LLVector3 gDebugRaycastBinormal;
+S32 gDebugRaycastFaceHit;
+LLVector3 gDebugRaycastStart;
+LLVector3 gDebugRaycastEnd;
+
+// HUD display lines in lower right
+BOOL gDisplayWindInfo = FALSE;
+BOOL gDisplayCameraPos = FALSE;
+BOOL gDisplayFOV = FALSE;
+BOOL gDisplayBadge = FALSE;
+
+S32 CHAT_BAR_HEIGHT = 28;
+S32 OVERLAY_BAR_HEIGHT = 20;
+
+const U8 NO_FACE = 255;
+BOOL gQuietSnapshot = FALSE;
+
+const F32 MIN_AFK_TIME = 2.f; // minimum time after setting away state before coming back
+const F32 MAX_FAST_FRAME_TIME = 0.5f;
+const F32 FAST_FRAME_INCREMENT = 0.1f;
+
+const F32 MIN_DISPLAY_SCALE = 0.75f;
+
+std::string LLViewerWindow::sSnapshotBaseName;
+std::string LLViewerWindow::sSnapshotDir;
+
+std::string LLViewerWindow::sMovieBaseName;
+
+class RecordToChatConsole : public LLError::Recorder, public LLSingleton<RecordToChatConsole>
+{
+public:
+ virtual void recordMessage(LLError::ELevel level,
+ const std::string& message)
+ {
+ //FIXME: this is NOT thread safe, and will do bad things when a warning is issued from a non-UI thread
+
+ // only log warnings to chat console
+ //if (level == LLError::LEVEL_WARN)
+ //{
+ //LLFloaterChat* chat_floater = LLFloaterReg::findTypedInstance<LLFloaterChat>("chat");
+ //if (chat_floater && gSavedSettings.getBOOL("WarningsAsChat"))
+ //{
+ // LLChat chat;
+ // chat.mText = message;
+ // chat.mSourceType = CHAT_SOURCE_SYSTEM;
+
+ // chat_floater->addChat(chat, FALSE, FALSE);
+ //}
+ //}
+ }
+};
+
+////////////////////////////////////////////////////////////////////////////
+//
+// LLDebugText
+//
+
+class LLDebugText
+{
+private:
+ struct Line
+ {
+ Line(const std::string& in_text, S32 in_x, S32 in_y) : text(in_text), x(in_x), y(in_y) {}
+ std::string text;
+ S32 x,y;
+ };
+
+ LLViewerWindow *mWindow;
+
+ typedef std::vector<Line> line_list_t;
+ line_list_t mLineList;
+ LLColor4 mTextColor;
+
+ void addText(S32 x, S32 y, const std::string &text)
+ {
+ mLineList.push_back(Line(text, x, y));
+ }
+
+ void clearText() { mLineList.clear(); }
+
+public:
+ LLDebugText(LLViewerWindow* window) : mWindow(window) {}
+
+ void update()
+ {
+ static LLCachedControl<bool> log_texture_traffic(gSavedSettings,"LogTextureNetworkTraffic") ;
+
+ std::string wind_vel_text;
+ std::string wind_vector_text;
+ std::string rwind_vel_text;
+ std::string rwind_vector_text;
+ std::string audio_text;
+
+ static const std::string beacon_particle = LLTrans::getString("BeaconParticle");
+ static const std::string beacon_physical = LLTrans::getString("BeaconPhysical");
+ static const std::string beacon_scripted = LLTrans::getString("BeaconScripted");
+ static const std::string beacon_scripted_touch = LLTrans::getString("BeaconScriptedTouch");
+ static const std::string beacon_sound = LLTrans::getString("BeaconSound");
+ static const std::string beacon_media = LLTrans::getString("BeaconMedia");
+ static const std::string particle_hiding = LLTrans::getString("ParticleHiding");
+
+ // Draw the statistics in a light gray
+ // and in a thin font
+ mTextColor = LLColor4( 0.86f, 0.86f, 0.86f, 1.f );
+
+ // Draw stuff growing up from right lower corner of screen
+ U32 xpos = mWindow->getWorldViewWidthScaled() - 350;
+ U32 ypos = 64;
+ const U32 y_inc = 20;
+
+ clearText();
+
+ if (gSavedSettings.getBOOL("DebugShowTime"))
+ {
+ const U32 y_inc2 = 15;
+ for (std::map<S32,LLFrameTimer>::reverse_iterator iter = gDebugTimers.rbegin();
+ iter != gDebugTimers.rend(); ++iter)
+ {
+ S32 idx = iter->first;
+ LLFrameTimer& timer = iter->second;
+ F32 time = timer.getElapsedTimeF32();
+ S32 hours = (S32)(time / (60*60));
+ S32 mins = (S32)((time - hours*(60*60)) / 60);
+ S32 secs = (S32)((time - hours*(60*60) - mins*60));
+ std::string label = gDebugTimerLabel[idx];
+ if (label.empty()) label = llformat("Debug: %d", idx);
+ addText(xpos, ypos, llformat(" %s: %d:%02d:%02d", label.c_str(), hours,mins,secs)); ypos += y_inc2;
+ }
+
+ F32 time = gFrameTimeSeconds;
+ S32 hours = (S32)(time / (60*60));
+ S32 mins = (S32)((time - hours*(60*60)) / 60);
+ S32 secs = (S32)((time - hours*(60*60) - mins*60));
+ addText(xpos, ypos, llformat("Time: %d:%02d:%02d", hours,mins,secs)); ypos += y_inc;
+ }
+
+#if LL_WINDOWS
+ if (gSavedSettings.getBOOL("DebugShowMemory"))
+ {
+ addText(xpos, ypos, llformat("Memory: %d (KB)", LLMemory::getWorkingSetSize() / 1024));
+ ypos += y_inc;
+ }
+#endif
+
+ if (gDisplayCameraPos)
+ {
+ std::string camera_view_text;
+ std::string camera_center_text;
+ std::string agent_view_text;
+ std::string agent_left_text;
+ std::string agent_center_text;
+ std::string agent_root_center_text;
+
+ LLVector3d tvector; // Temporary vector to hold data for printing.
+
+ // Update camera center, camera view, wind info every other frame
+ tvector = gAgent.getPositionGlobal();
+ agent_center_text = llformat("AgentCenter %f %f %f",
+ (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
+
+ if (isAgentAvatarValid())
+ {
+ tvector = gAgent.getPosGlobalFromAgent(gAgentAvatarp->mRoot.getWorldPosition());
+ agent_root_center_text = llformat("AgentRootCenter %f %f %f",
+ (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
+ }
+ else
+ {
+ agent_root_center_text = "---";
+ }
+
+
+ tvector = LLVector4(gAgent.getFrameAgent().getAtAxis());
+ agent_view_text = llformat("AgentAtAxis %f %f %f",
+ (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
+
+ tvector = LLVector4(gAgent.getFrameAgent().getLeftAxis());
+ agent_left_text = llformat("AgentLeftAxis %f %f %f",
+ (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
+
+ tvector = gAgentCamera.getCameraPositionGlobal();
+ camera_center_text = llformat("CameraCenter %f %f %f",
+ (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
+
+ tvector = LLVector4(LLViewerCamera::getInstance()->getAtAxis());
+ camera_view_text = llformat("CameraAtAxis %f %f %f",
+ (F32)(tvector.mdV[VX]), (F32)(tvector.mdV[VY]), (F32)(tvector.mdV[VZ]));
+
+ addText(xpos, ypos, agent_center_text); ypos += y_inc;
+ addText(xpos, ypos, agent_root_center_text); ypos += y_inc;
+ addText(xpos, ypos, agent_view_text); ypos += y_inc;
+ addText(xpos, ypos, agent_left_text); ypos += y_inc;
+ addText(xpos, ypos, camera_center_text); ypos += y_inc;
+ addText(xpos, ypos, camera_view_text); ypos += y_inc;
+ }
+
+ if (gDisplayWindInfo)
+ {
+ wind_vel_text = llformat("Wind velocity %.2f m/s", gWindVec.magVec());
+ wind_vector_text = llformat("Wind vector %.2f %.2f %.2f", gWindVec.mV[0], gWindVec.mV[1], gWindVec.mV[2]);
+ rwind_vel_text = llformat("RWind vel %.2f m/s", gRelativeWindVec.magVec());
+ rwind_vector_text = llformat("RWind vec %.2f %.2f %.2f", gRelativeWindVec.mV[0], gRelativeWindVec.mV[1], gRelativeWindVec.mV[2]);
+
+ addText(xpos, ypos, wind_vel_text); ypos += y_inc;
+ addText(xpos, ypos, wind_vector_text); ypos += y_inc;
+ addText(xpos, ypos, rwind_vel_text); ypos += y_inc;
+ addText(xpos, ypos, rwind_vector_text); ypos += y_inc;
+ }
+ if (gDisplayWindInfo)
+ {
+ if (gAudiop)
+ {
+ audio_text= llformat("Audio for wind: %d", gAudiop->isWindEnabled());
+ }
+ addText(xpos, ypos, audio_text); ypos += y_inc;
+ }
+ if (gDisplayFOV)
+ {
+ addText(xpos, ypos, llformat("FOV: %2.1f deg", RAD_TO_DEG * LLViewerCamera::getInstance()->getView()));
+ ypos += y_inc;
+ }
+ if (gDisplayBadge)
+ {
+ addText(xpos, ypos+(y_inc/2), llformat("Hippos!", RAD_TO_DEG * LLViewerCamera::getInstance()->getView()));
+ ypos += y_inc * 2;
+ }
+
+ /*if (LLViewerJoystick::getInstance()->getOverrideCamera())
+ {
+ addText(xpos + 200, ypos, llformat("Flycam"));
+ ypos += y_inc;
+ }*/
+
+ if (gSavedSettings.getBOOL("DebugShowRenderInfo"))
+ {
+ if (gPipeline.getUseVertexShaders() == 0)
+ {
+ addText(xpos, ypos, "Shaders Disabled");
+ ypos += y_inc;
+ }
+
+ if (gGLManager.mHasATIMemInfo)
+ {
+ S32 meminfo[4];
+ glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, meminfo);
+
+ addText(xpos, ypos, llformat("%.2f MB Texture Memory Free", meminfo[0]/1024.f));
+ ypos += y_inc;
+
+ if (gGLManager.mHasVertexBufferObject)
+ {
+ glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, meminfo);
+ addText(xpos, ypos, llformat("%.2f MB VBO Memory Free", meminfo[0]/1024.f));
+ ypos += y_inc;
+ }
+ }
+ else if (gGLManager.mHasNVXMemInfo)
+ {
+ S32 free_memory;
+ glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &free_memory);
+ addText(xpos, ypos, llformat("%.2f MB Video Memory Free", free_memory/1024.f));
+ ypos += y_inc;
+ }
+
+ //show streaming cost/triangle count of known prims in current region OR selection
+ {
+ F32 cost = 0.f;
+ S32 count = 0;
+ const char* label = "Region";
+ if (LLSelectMgr::getInstance()->getSelection()->getObjectCount() == 0)
+ { //region
+ LLViewerRegion* region = gAgent.getRegion();
+ if (region)
+ {
+ for (U32 i = 0; i < gObjectList.getNumObjects(); ++i)
+ {
+ LLViewerObject* object = gObjectList.getObject(i);
+ if (object &&
+ object->getRegion() == region &&
+ object->getVolume())
+ {
+ cost += object->getStreamingCost();
+ count += object->getTriangleCount();
+ }
+ }
+ }
+ }
+ else
+ {
+ label = "Selection";
+ cost = LLSelectMgr::getInstance()->getSelection()->getSelectedObjectStreamingCost();
+ count = LLSelectMgr::getInstance()->getSelection()->getSelectedObjectTriangleCount();
+ }
+
+ addText(xpos,ypos, llformat("%s streaming cost: %.1f (%.1f KTris)",
+ label, cost, count/1000.f));
+ ypos += y_inc;
+
+ }
+
+ addText(xpos, ypos, llformat("%d MB Vertex Data", LLVertexBuffer::sAllocatedBytes/(1024*1024)));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%d Vertex Buffers", LLVertexBuffer::sGLCount));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%d Mapped Buffers", LLVertexBuffer::sMappedCount));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%d Vertex Buffer Binds", LLVertexBuffer::sBindCount));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%d Vertex Buffer Sets", LLVertexBuffer::sSetCount));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%d Texture Binds", LLImageGL::sBindCount));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%d Unique Textures", LLImageGL::sUniqueCount));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%d Render Calls", gPipeline.mBatchCount));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%d Matrix Ops", gPipeline.mMatrixOpCount));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%d Texture Matrix Ops", gPipeline.mTextureMatrixOps));
+ ypos += y_inc;
+
+ gPipeline.mTextureMatrixOps = 0;
+ gPipeline.mMatrixOpCount = 0;
+
+ if (gPipeline.mBatchCount > 0)
+ {
+ addText(xpos, ypos, llformat("Batch min/max/mean: %d/%d/%d", gPipeline.mMinBatchSize, gPipeline.mMaxBatchSize,
+ gPipeline.mTrianglesDrawn/gPipeline.mBatchCount));
+
+ gPipeline.mMinBatchSize = gPipeline.mMaxBatchSize;
+ gPipeline.mMaxBatchSize = 0;
+ gPipeline.mBatchCount = 0;
+ }
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("UI Verts/Calls: %d/%d", LLRender::sUIVerts, LLRender::sUICalls));
+ LLRender::sUICalls = LLRender::sUIVerts = 0;
+ ypos += y_inc;
+
+ addText(xpos,ypos, llformat("%d/%d Nodes visible", gPipeline.mNumVisibleNodes, LLSpatialGroup::sNodeCount));
+
+ ypos += y_inc;
+
+ if (!LLSpatialGroup::sPendingQueries.empty())
+ {
+ addText(xpos,ypos, llformat("%d Queries pending", LLSpatialGroup::sPendingQueries.size()));
+ ypos += y_inc;
+ }
+
+
+ addText(xpos,ypos, llformat("%d Avatars visible", LLVOAvatar::sNumVisibleAvatars));
+
+ ypos += y_inc;
+
+ addText(xpos,ypos, llformat("%d Lights visible", LLPipeline::sVisibleLightCount));
+
+ ypos += y_inc;
+
+ if (gSavedSettings.getBOOL("MeshEnabled"))
+ {
+ addText(xpos, ypos, llformat("%.3f MB Mesh Data Received", LLMeshRepository::sBytesReceived/(1024.f*1024.f)));
+
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%d/%d Mesh HTTP Requests/Retries", LLMeshRepository::sHTTPRequestCount,
+ LLMeshRepository::sHTTPRetryCount));
+
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%.3f/%.3f MB Mesh Cache Read/Write ", LLMeshRepository::sCacheBytesRead/(1024.f*1024.f), LLMeshRepository::sCacheBytesWritten/(1024.f*1024.f)));
+
+ ypos += y_inc;
+ }
+
+ LLVertexBuffer::sBindCount = LLImageGL::sBindCount =
+ LLVertexBuffer::sSetCount = LLImageGL::sUniqueCount =
+ gPipeline.mNumVisibleNodes = LLPipeline::sVisibleLightCount = 0;
+ }
+ if (gSavedSettings.getBOOL("DebugShowRenderMatrices"))
+ {
+ addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLProjection[12], gGLProjection[13], gGLProjection[14], gGLProjection[15]));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLProjection[8], gGLProjection[9], gGLProjection[10], gGLProjection[11]));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLProjection[4], gGLProjection[5], gGLProjection[6], gGLProjection[7]));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLProjection[0], gGLProjection[1], gGLProjection[2], gGLProjection[3]));
+ ypos += y_inc;
+
+ addText(xpos, ypos, "Projection Matrix");
+ ypos += y_inc;
+
+
+ addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLModelView[12], gGLModelView[13], gGLModelView[14], gGLModelView[15]));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLModelView[8], gGLModelView[9], gGLModelView[10], gGLModelView[11]));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLModelView[4], gGLModelView[5], gGLModelView[6], gGLModelView[7]));
+ ypos += y_inc;
+
+ addText(xpos, ypos, llformat("%.4f .%4f %.4f %.4f", gGLModelView[0], gGLModelView[1], gGLModelView[2], gGLModelView[3]));
+ ypos += y_inc;
+
+ addText(xpos, ypos, "View Matrix");
+ ypos += y_inc;
+ }
+ if (gSavedSettings.getBOOL("DebugShowColor"))
+ {
+ U8 color[4];
+ LLCoordGL coord = gViewerWindow->getCurrentMouse();
+ glReadPixels(coord.mX, coord.mY, 1,1,GL_RGBA, GL_UNSIGNED_BYTE, color);
+ addText(xpos, ypos, llformat("%d %d %d %d", color[0], color[1], color[2], color[3]));
+ ypos += y_inc;
+ }
+ // only display these messages if we are actually rendering beacons at this moment
+ if (LLPipeline::getRenderBeacons(NULL) && LLFloaterReg::instanceVisible("beacons"))
+ {
+ if (LLPipeline::getRenderParticleBeacons(NULL))
+ {
+ addText(xpos, ypos, beacon_particle);
+ ypos += y_inc;
+ }
+ if (LLPipeline::toggleRenderTypeControlNegated((void*)LLPipeline::RENDER_TYPE_PARTICLES))
+ {
+ addText(xpos, ypos, particle_hiding);
+ ypos += y_inc;
+ }
+ if (LLPipeline::getRenderPhysicalBeacons(NULL))
+ {
+ addText(xpos, ypos, beacon_physical);
+ ypos += y_inc;
+ }
+ if (LLPipeline::getRenderScriptedBeacons(NULL))
+ {
+ addText(xpos, ypos, beacon_scripted);
+ ypos += y_inc;
+ }
+ else
+ if (LLPipeline::getRenderScriptedTouchBeacons(NULL))
+ {
+ addText(xpos, ypos, beacon_scripted_touch);
+ ypos += y_inc;
+ }
+ if (LLPipeline::getRenderSoundBeacons(NULL))
+ {
+ addText(xpos, ypos, beacon_sound);
+ ypos += y_inc;
+ }
+ }
+
+ if(log_texture_traffic)
+ {
+ U32 old_y = ypos ;
+ for(S32 i = LLViewerTexture::BOOST_NONE; i < LLViewerTexture::MAX_GL_IMAGE_CATEGORY; i++)
+ {
+ if(gTotalTextureBytesPerBoostLevel[i] > 0)
+ {
+ addText(xpos, ypos, llformat("Boost_Level %d: %.3f MB", i, (F32)gTotalTextureBytesPerBoostLevel[i] / (1024 * 1024)));
+ ypos += y_inc;
+ }
+ }
+ if(ypos != old_y)
+ {
+ addText(xpos, ypos, "Network traffic for textures:");
+ ypos += y_inc;
+ }
+ }
+
+ if (gSavedSettings.getBOOL("DebugShowUploadCost"))
+ {
+ addText(xpos, ypos, llformat(" Meshes: L$%d", gPipeline.mDebugMeshUploadCost));
+ ypos += y_inc/2;
+ addText(xpos, ypos, llformat(" Sculpties: L$%d", gPipeline.mDebugSculptUploadCost));
+ ypos += y_inc/2;
+ addText(xpos, ypos, llformat(" Textures: L$%d", gPipeline.mDebugTextureUploadCost));
+ ypos += y_inc/2;
+ addText(xpos, ypos, "Upload Cost: ");
+
+ ypos += y_inc;
+ }
+
+ //temporary hack to give feedback on mesh upload progress
+ if (!gMeshRepo.mUploads.empty())
+ {
+ for (std::vector<LLMeshUploadThread*>::iterator iter = gMeshRepo.mUploads.begin();
+ iter != gMeshRepo.mUploads.end(); ++iter)
+ {
+ LLMeshUploadThread* thread = *iter;
+
+ addText(xpos, ypos, llformat("Mesh Upload -- price quote: %d:%d | upload: %d:%d | create: %d",
+ thread->mPendingConfirmations, thread->mUploadQ.size()+thread->mTextureQ.size(),
+ thread->mPendingUploads, thread->mConfirmedQ.size()+thread->mConfirmedTextureQ.size(),
+ thread->mInstanceQ.size()));
+ ypos += y_inc;
+ }
+ }
+
+ if (!gMeshRepo.mPendingRequests.empty() ||
+ !gMeshRepo.mThread->mHeaderReqQ.empty() ||
+ !gMeshRepo.mThread->mLODReqQ.empty())
+ {
+ LLMutexLock lock(gMeshRepo.mThread->mMutex);
+ S32 pending = (S32) gMeshRepo.mPendingRequests.size();
+ S32 header = (S32) gMeshRepo.mThread->mHeaderReqQ.size();
+ S32 lod = (S32) gMeshRepo.mThread->mLODReqQ.size();
+
+ addText(xpos, ypos, llformat ("Mesh Queue - %d pending (%d:%d header | %d:%d LOD)",
+ pending,
+ LLMeshRepoThread::sActiveHeaderRequests, header,
+ LLMeshRepoThread::sActiveLODRequests, lod));
+
+ ypos += y_inc;
+ }
+
+ if (gSavedSettings.getBOOL("DebugShowTextureInfo"))
+ {
+ LLViewerObject* objectp = NULL ;
+ //objectp = = gAgentCamera.getFocusObject();
+
+ LLSelectNode* nodep = LLSelectMgr::instance().getHoverNode();
+ if (nodep)
+ {
+ objectp = nodep->getObject();
+ }
+ if (objectp && !objectp->isDead())
+ {
+ S32 num_faces = objectp->mDrawable->getNumFaces() ;
+
+ for(S32 i = 0 ; i < num_faces; i++)
+ {
+ LLFace* facep = objectp->mDrawable->getFace(i) ;
+ if(facep)
+ {
+ //addText(xpos, ypos, llformat("ts_min: %.3f ts_max: %.3f tt_min: %.3f tt_max: %.3f", facep->mTexExtents[0].mV[0], facep->mTexExtents[1].mV[0],
+ // facep->mTexExtents[0].mV[1], facep->mTexExtents[1].mV[1]));
+ //ypos += y_inc;
+
+ addText(xpos, ypos, llformat("v_size: %.3f: p_size: %.3f", facep->getVirtualSize(), facep->getPixelArea()));
+ ypos += y_inc;
+
+ //const LLTextureEntry *tep = facep->getTextureEntry();
+ //if(tep)
+ //{
+ // addText(xpos, ypos, llformat("scale_s: %.3f: scale_t: %.3f", tep->mScaleS, tep->mScaleT)) ;
+ // ypos += y_inc;
+ //}
+
+ LLViewerTexture* tex = facep->getTexture() ;
+ if(tex)
+ {
+ addText(xpos, ypos, llformat("ID: %s v_size: %.3f", tex->getID().asString().c_str(), tex->getMaxVirtualSize()));
+ ypos += y_inc;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ void draw()
+ {
+ for (line_list_t::iterator iter = mLineList.begin();
+ iter != mLineList.end(); ++iter)
+ {
+ const Line& line = *iter;
+ LLFontGL::getFontMonospace()->renderUTF8(line.text, 0, (F32)line.x, (F32)line.y, mTextColor,
+ LLFontGL::LEFT, LLFontGL::TOP,
+ LLFontGL::NORMAL, LLFontGL::NO_SHADOW, S32_MAX, S32_MAX, NULL, FALSE);
+ }
+ mLineList.clear();
+ }
+
+};
+
+void LLViewerWindow::updateDebugText()
+{
+ mDebugText->update();
+}
+
+////////////////////////////////////////////////////////////////////////////
+//
+// LLViewerWindow
+//
+
+BOOL LLViewerWindow::handleAnyMouseClick(LLWindow *window, LLCoordGL pos, MASK mask, LLMouseHandler::EClickType clicktype, BOOL down)
+{
+ const char* buttonname = "";
+ const char* buttonstatestr = "";
+ S32 x = pos.mX;
+ S32 y = pos.mY;
+ x = llround((F32)x / mDisplayScale.mV[VX]);
+ y = llround((F32)y / mDisplayScale.mV[VY]);
+
+ // only send mouse clicks to UI if UI is visible
+ if(gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
+ {
+
+ if (down)
+ {
+ buttonstatestr = "down" ;
+ }
+ else
+ {
+ buttonstatestr = "up" ;
+ }
+
+ switch (clicktype)
+ {
+ case LLMouseHandler::CLICK_LEFT:
+ mLeftMouseDown = down;
+ buttonname = "Left";
+ break;
+ case LLMouseHandler::CLICK_RIGHT:
+ mRightMouseDown = down;
+ buttonname = "Right";
+ break;
+ case LLMouseHandler::CLICK_MIDDLE:
+ mMiddleMouseDown = down;
+ buttonname = "Middle";
+ break;
+ case LLMouseHandler::CLICK_DOUBLELEFT:
+ mLeftMouseDown = down;
+ buttonname = "Left Double Click";
+ break;
+ }
+
+ LLView::sMouseHandlerMessage.clear();
+
+ if (gMenuBarView)
+ {
+ // stop ALT-key access to menu
+ gMenuBarView->resetMenuTrigger();
+ }
+
+ if (gDebugClicks)
+ {
+ llinfos << "ViewerWindow " << buttonname << " mouse " << buttonstatestr << " at " << x << "," << y << llendl;
+ }
+
+ // Make sure we get a corresponding mouseup event, even if the mouse leaves the window
+ if (down)
+ mWindow->captureMouse();
+ else
+ mWindow->releaseMouse();
+
+ // Indicate mouse was active
+ LLUI::resetMouseIdleTimer();
+
+ // Don't let the user move the mouse out of the window until mouse up.
+ if( LLToolMgr::getInstance()->getCurrentTool()->clipMouseWhenDown() )
+ {
+ mWindow->setMouseClipping(down);
+ }
+
+ LLMouseHandler* mouse_captor = gFocusMgr.getMouseCapture();
+ if( mouse_captor )
+ {
+ S32 local_x;
+ S32 local_y;
+ mouse_captor->screenPointToLocal( x, y, &local_x, &local_y );
+ if (LLView::sDebugMouseHandling)
+ {
+ llinfos << buttonname << " Mouse " << buttonstatestr << " handled by captor " << mouse_captor->getName() << llendl;
+ }
+ return mouse_captor->handleAnyMouseClick(local_x, local_y, mask, clicktype, down);
+ }
+
+ // Topmost view gets a chance before the hierarchy
+ //LLUICtrl* top_ctrl = gFocusMgr.getTopCtrl();
+ //if (top_ctrl)
+ //{
+ // S32 local_x, local_y;
+ // top_ctrl->screenPointToLocal( x, y, &local_x, &local_y );
+ // if (top_ctrl->pointInView(local_x, local_y))
+ // {
+ // return top_ctrl->handleAnyMouseClick(local_x, local_y, mask, clicktype, down) ;
+ // }
+ // else
+ // {
+ // if (down)
+ // {
+ // gFocusMgr.setTopCtrl(NULL);
+ // }
+ // }
+ //}
+
+ // Give the UI views a chance to process the click
+ if( mRootView->handleAnyMouseClick(x, y, mask, clicktype, down) )
+ {
+ if (LLView::sDebugMouseHandling)
+ {
+ llinfos << buttonname << " Mouse " << buttonstatestr << " " << LLView::sMouseHandlerMessage << llendl;
+ }
+ return TRUE;
+ }
+ else if (LLView::sDebugMouseHandling)
+ {
+ llinfos << buttonname << " Mouse " << buttonstatestr << " not handled by view" << llendl;
+ }
+ }
+
+ // Do not allow tool manager to handle mouseclicks if we have disconnected
+ if(!gDisconnected && LLToolMgr::getInstance()->getCurrentTool()->handleAnyMouseClick( x, y, mask, clicktype, down ) )
+ {
+ return TRUE;
+ }
+
+
+ // If we got this far on a down-click, it wasn't handled.
+ // Up-clicks, though, are always handled as far as the OS is concerned.
+ BOOL default_rtn = !down;
+ return default_rtn;
+}
+
+BOOL LLViewerWindow::handleMouseDown(LLWindow *window, LLCoordGL pos, MASK mask)
+{
+ BOOL down = TRUE;
+ return handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_LEFT,down);
+}
+
+BOOL LLViewerWindow::handleDoubleClick(LLWindow *window, LLCoordGL pos, MASK mask)
+{
+ // try handling as a double-click first, then a single-click if that
+ // wasn't handled.
+ BOOL down = TRUE;
+ if (handleAnyMouseClick(window, pos, mask,
+ LLMouseHandler::CLICK_DOUBLELEFT, down))
+ {
+ return TRUE;
+ }
+ return handleMouseDown(window, pos, mask);
+}
+
+BOOL LLViewerWindow::handleMouseUp(LLWindow *window, LLCoordGL pos, MASK mask)
+{
+ BOOL down = FALSE;
+ return handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_LEFT,down);
+}
+
+
+BOOL LLViewerWindow::handleRightMouseDown(LLWindow *window, LLCoordGL pos, MASK mask)
+{
+ S32 x = pos.mX;
+ S32 y = pos.mY;
+ x = llround((F32)x / mDisplayScale.mV[VX]);
+ y = llround((F32)y / mDisplayScale.mV[VY]);
+
+ BOOL down = TRUE;
+ BOOL handle = handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_RIGHT,down);
+ if (handle)
+ return handle;
+
+ // *HACK: this should be rolled into the composite tool logic, not
+ // hardcoded at the top level.
+ if (CAMERA_MODE_CUSTOMIZE_AVATAR != gAgentCamera.getCameraMode() && LLToolMgr::getInstance()->getCurrentTool() != LLToolPie::getInstance())
+ {
+ // If the current tool didn't process the click, we should show
+ // the pie menu. This can be done by passing the event to the pie
+ // menu tool.
+ LLToolPie::getInstance()->handleRightMouseDown(x, y, mask);
+ // show_context_menu( x, y, mask );
+ }
+
+ return TRUE;
+}
+
+BOOL LLViewerWindow::handleRightMouseUp(LLWindow *window, LLCoordGL pos, MASK mask)
+{
+ BOOL down = FALSE;
+ return handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_RIGHT,down);
+}
+
+BOOL LLViewerWindow::handleMiddleMouseDown(LLWindow *window, LLCoordGL pos, MASK mask)
+{
+ BOOL down = TRUE;
+ LLVoiceClient::getInstance()->middleMouseState(true);
+ handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_MIDDLE,down);
+
+ // Always handled as far as the OS is concerned.
+ return TRUE;
+}
+
+LLWindowCallbacks::DragNDropResult LLViewerWindow::handleDragNDrop( LLWindow *window, LLCoordGL pos, MASK mask, LLWindowCallbacks::DragNDropAction action, std::string data)
+{
+ LLWindowCallbacks::DragNDropResult result = LLWindowCallbacks::DND_NONE;
+
+ const bool prim_media_dnd_enabled = gSavedSettings.getBOOL("PrimMediaDragNDrop");
+ const bool slurl_dnd_enabled = gSavedSettings.getBOOL("SLURLDragNDrop");
+
+ if ( prim_media_dnd_enabled || slurl_dnd_enabled )
+ {
+ switch(action)
+ {
+ // Much of the handling for these two cases is the same.
+ case LLWindowCallbacks::DNDA_TRACK:
+ case LLWindowCallbacks::DNDA_DROPPED:
+ case LLWindowCallbacks::DNDA_START_TRACKING:
+ {
+ bool drop = (LLWindowCallbacks::DNDA_DROPPED == action);
+
+ if (slurl_dnd_enabled)
+ {
+ LLSLURL dropped_slurl(data);
+ if(dropped_slurl.isSpatial())
+ {
+ if (drop)
+ {
+ LLURLDispatcher::dispatch( dropped_slurl.getSLURLString(), NULL, true );
+ return LLWindowCallbacks::DND_MOVE;
+ }
+ return LLWindowCallbacks::DND_COPY;
+ }
+ }
+
+ if (prim_media_dnd_enabled)
+ {
+ LLPickInfo pick_info = pickImmediate( pos.mX, pos.mY, TRUE /*BOOL pick_transparent*/ );
+
+ LLUUID object_id = pick_info.getObjectID();
+ S32 object_face = pick_info.mObjectFace;
+ std::string url = data;
+
+ lldebugs << "Object: picked at " << pos.mX << ", " << pos.mY << " - face = " << object_face << " - URL = " << url << llendl;
+
+ LLVOVolume *obj = dynamic_cast<LLVOVolume*>(static_cast<LLViewerObject*>(pick_info.getObject()));
+
+ if (obj && !obj->getRegion()->getCapability("ObjectMedia").empty())
+ {
+ LLTextureEntry *te = obj->getTE(object_face);
+
+ // can modify URL if we can modify the object or we have navigate permissions
+ bool allow_modify_url = obj->permModify() || obj->hasMediaPermission( te->getMediaData(), LLVOVolume::MEDIA_PERM_INTERACT );
+
+ if (te && allow_modify_url )
+ {
+ if (drop)
+ {
+ // object does NOT have media already
+ if ( ! te->hasMedia() )
+ {
+ // we are allowed to modify the object
+ if ( obj->permModify() )
+ {
+ // Create new media entry
+ LLSD media_data;
+ // XXX Should we really do Home URL too?
+ media_data[LLMediaEntry::HOME_URL_KEY] = url;
+ media_data[LLMediaEntry::CURRENT_URL_KEY] = url;
+ media_data[LLMediaEntry::AUTO_PLAY_KEY] = true;
+ obj->syncMediaData(object_face, media_data, true, true);
+ // XXX This shouldn't be necessary, should it ?!?
+ if (obj->getMediaImpl(object_face))
+ obj->getMediaImpl(object_face)->navigateReload();
+ obj->sendMediaDataUpdate();
+
+ result = LLWindowCallbacks::DND_COPY;
+ }
+ }
+ else
+ // object HAS media already
+ {
+ // URL passes the whitelist
+ if (te->getMediaData()->checkCandidateUrl( url ) )
+ {
+ // just navigate to the URL
+ if (obj->getMediaImpl(object_face))
+ {
+ obj->getMediaImpl(object_face)->navigateTo(url);
+ }
+ else
+ {
+ // This is very strange. Navigation should
+ // happen via the Impl, but we don't have one.
+ // This sends it to the server, which /should/
+ // trigger us getting it. Hopefully.
+ LLSD media_data;
+ media_data[LLMediaEntry::CURRENT_URL_KEY] = url;
+ obj->syncMediaData(object_face, media_data, true, true);
+ obj->sendMediaDataUpdate();
+ }
+ result = LLWindowCallbacks::DND_LINK;
+
+ }
+ }
+ LLSelectMgr::getInstance()->unhighlightObjectOnly(mDragHoveredObject);
+ mDragHoveredObject = NULL;
+
+ }
+ else
+ {
+ // Check the whitelist, if there's media (otherwise just show it)
+ if (te->getMediaData() == NULL || te->getMediaData()->checkCandidateUrl(url))
+ {
+ if ( obj != mDragHoveredObject)
+ {
+ // Highlight the dragged object
+ LLSelectMgr::getInstance()->unhighlightObjectOnly(mDragHoveredObject);
+ mDragHoveredObject = obj;
+ LLSelectMgr::getInstance()->highlightObjectOnly(mDragHoveredObject);
+ }
+ result = (! te->hasMedia()) ? LLWindowCallbacks::DND_COPY : LLWindowCallbacks::DND_LINK;
+
+ }
+ }
+ }
+ }
+ }
+ }
+ break;
+
+ case LLWindowCallbacks::DNDA_STOP_TRACKING:
+ // The cleanup case below will make sure things are unhilighted if necessary.
+ break;
+ }
+
+ if (prim_media_dnd_enabled &&
+ result == LLWindowCallbacks::DND_NONE && !mDragHoveredObject.isNull())
+ {
+ LLSelectMgr::getInstance()->unhighlightObjectOnly(mDragHoveredObject);
+ mDragHoveredObject = NULL;
+ }
+ }
+
+ return result;
+}
+
+BOOL LLViewerWindow::handleMiddleMouseUp(LLWindow *window, LLCoordGL pos, MASK mask)
+{
+ BOOL down = FALSE;
+ LLVoiceClient::getInstance()->middleMouseState(false);
+ handleAnyMouseClick(window,pos,mask,LLMouseHandler::CLICK_MIDDLE,down);
+
+ // Always handled as far as the OS is concerned.
+ return TRUE;
+}
+
+// WARNING: this is potentially called multiple times per frame
+void LLViewerWindow::handleMouseMove(LLWindow *window, LLCoordGL pos, MASK mask)
+{
+ S32 x = pos.mX;
+ S32 y = pos.mY;
+
+ x = llround((F32)x / mDisplayScale.mV[VX]);
+ y = llround((F32)y / mDisplayScale.mV[VY]);
+
+ mMouseInWindow = TRUE;
+
+ // Save mouse point for access during idle() and display()
+
+ LLCoordGL mouse_point(x, y);
+
+ if (mouse_point != mCurrentMousePoint)
+ {
+ LLUI::resetMouseIdleTimer();
+ }
+
+ saveLastMouse(mouse_point);
+
+ mWindow->showCursorFromMouseMove();
+
+ if (gAwayTimer.getElapsedTimeF32() > MIN_AFK_TIME)
+ {
+ gAgent.clearAFK();
+ }
+}
+
+void LLViewerWindow::handleMouseLeave(LLWindow *window)
+{
+ // Note: we won't get this if we have captured the mouse.
+ llassert( gFocusMgr.getMouseCapture() == NULL );
+ mMouseInWindow = FALSE;
+ LLToolTipMgr::instance().blockToolTips();
+}
+
+BOOL LLViewerWindow::handleCloseRequest(LLWindow *window)
+{
+ // User has indicated they want to close, but we may need to ask
+ // about modified documents.
+ LLAppViewer::instance()->userQuit();
+ // Don't quit immediately
+ return FALSE;
+}
+
+void LLViewerWindow::handleQuit(LLWindow *window)
+{
+ LLAppViewer::instance()->forceQuit();
+}
+
+void LLViewerWindow::handleResize(LLWindow *window, S32 width, S32 height)
+{
+ reshape(width, height);
+ mResDirty = true;
+}
+
+// The top-level window has gained focus (e.g. via ALT-TAB)
+void LLViewerWindow::handleFocus(LLWindow *window)
+{
+ gFocusMgr.setAppHasFocus(TRUE);
+ LLModalDialog::onAppFocusGained();
+
+ gAgent.onAppFocusGained();
+ LLToolMgr::getInstance()->onAppFocusGained();
+
+ // See if we're coming in with modifier keys held down
+ if (gKeyboard)
+ {
+ gKeyboard->resetMaskKeys();
+ }
+
+ // resume foreground running timer
+ // since we artifically limit framerate when not frontmost
+ gForegroundTime.unpause();
+}
+
+// The top-level window has lost focus (e.g. via ALT-TAB)
+void LLViewerWindow::handleFocusLost(LLWindow *window)
+{
+ gFocusMgr.setAppHasFocus(FALSE);
+ //LLModalDialog::onAppFocusLost();
+ LLToolMgr::getInstance()->onAppFocusLost();
+ gFocusMgr.setMouseCapture( NULL );
+
+ if (gMenuBarView)
+ {
+ // stop ALT-key access to menu
+ gMenuBarView->resetMenuTrigger();
+ }
+
+ // restore mouse cursor
+ showCursor();
+ getWindow()->setMouseClipping(FALSE);
+
+ // If losing focus while keys are down, reset them.
+ if (gKeyboard)
+ {
+ gKeyboard->resetKeys();
+ }
+
+ // pause timer that tracks total foreground running time
+ gForegroundTime.pause();
+}
+
+
+BOOL LLViewerWindow::handleTranslatedKeyDown(KEY key, MASK mask, BOOL repeated)
+{
+ // Let the voice chat code check for its PTT key. Note that this never affects event processing.
+ LLVoiceClient::getInstance()->keyDown(key, mask);
+
+ if (gAwayTimer.getElapsedTimeF32() > MIN_AFK_TIME)
+ {
+ gAgent.clearAFK();
+ }
+
+ // *NOTE: We want to interpret KEY_RETURN later when it arrives as
+ // a Unicode char, not as a keydown. Otherwise when client frame
+ // rate is really low, hitting return sends your chat text before
+ // it's all entered/processed.
+ if (key == KEY_RETURN && mask == MASK_NONE)
+ {
+ return FALSE;
+ }
+
+ return gViewerKeyboard.handleKey(key, mask, repeated);
+}
+
+BOOL LLViewerWindow::handleTranslatedKeyUp(KEY key, MASK mask)
+{
+ // Let the voice chat code check for its PTT key. Note that this never affects event processing.
+ LLVoiceClient::getInstance()->keyUp(key, mask);
+
+ return FALSE;
+}
+
+
+void LLViewerWindow::handleScanKey(KEY key, BOOL key_down, BOOL key_up, BOOL key_level)
+{
+ LLViewerJoystick::getInstance()->setCameraNeedsUpdate(true);
+ return gViewerKeyboard.scanKey(key, key_down, key_up, key_level);
+}
+
+
+
+
+BOOL LLViewerWindow::handleActivate(LLWindow *window, BOOL activated)
+{
+ if (activated)
+ {
+ mActive = TRUE;
+ send_agent_resume();
+ gAgent.clearAFK();
+
+ // Unmute audio
+ audio_update_volume();
+ }
+ else
+ {
+ mActive = FALSE;
+
+ if (gSavedSettings.getS32("AFKTimeout"))
+ {
+ gAgent.setAFK();
+ }
+
+ // SL-53351: Make sure we're not in mouselook when minimised, to prevent control issues
+ if (gAgentCamera.getCameraMode() == CAMERA_MODE_MOUSELOOK)
+ {
+ gAgentCamera.changeCameraToDefault();
+ }
+
+ send_agent_pause();
+
+ // Mute audio
+ audio_update_volume();
+ }
+ return TRUE;
+}
+
+BOOL LLViewerWindow::handleActivateApp(LLWindow *window, BOOL activating)
+{
+ //if (!activating) gAgentCamera.changeCameraToDefault();
+
+ LLViewerJoystick::getInstance()->setNeedsReset(true);
+ return FALSE;
+}
+
+
+void LLViewerWindow::handleMenuSelect(LLWindow *window, S32 menu_item)
+{
+}
+
+
+BOOL LLViewerWindow::handlePaint(LLWindow *window, S32 x, S32 y, S32 width, S32 height)
+{
+#if LL_WINDOWS
+ if (gNoRender)
+ {
+ HWND window_handle = (HWND)window->getPlatformWindow();
+ PAINTSTRUCT ps;
+ HDC hdc;
+
+ RECT wnd_rect;
+ wnd_rect.left = 0;
+ wnd_rect.top = 0;
+ wnd_rect.bottom = 200;
+ wnd_rect.right = 500;
+
+ hdc = BeginPaint(window_handle, &ps);
+ //SetBKColor(hdc, RGB(255, 255, 255));
+ FillRect(hdc, &wnd_rect, CreateSolidBrush(RGB(255, 255, 255)));
+
+ std::string temp_str;
+ temp_str = llformat( "FPS %3.1f Phy FPS %2.1f Time Dil %1.3f", /* Flawfinder: ignore */
+ LLViewerStats::getInstance()->mFPSStat.getMeanPerSec(),
+ LLViewerStats::getInstance()->mSimPhysicsFPS.getPrev(0),
+ LLViewerStats::getInstance()->mSimTimeDilation.getPrev(0));
+ S32 len = temp_str.length();
+ TextOutA(hdc, 0, 0, temp_str.c_str(), len);
+
+
+ LLVector3d pos_global = gAgent.getPositionGlobal();
+ temp_str = llformat( "Avatar pos %6.1lf %6.1lf %6.1lf", pos_global.mdV[0], pos_global.mdV[1], pos_global.mdV[2]);
+ len = temp_str.length();
+ TextOutA(hdc, 0, 25, temp_str.c_str(), len);
+
+ TextOutA(hdc, 0, 50, "Set \"DisableRendering FALSE\" in settings.ini file to reenable", 61);
+ EndPaint(window_handle, &ps);
+ return TRUE;
+ }
+#endif
+ return FALSE;
+}
+
+
+void LLViewerWindow::handleScrollWheel(LLWindow *window, S32 clicks)
+{
+ handleScrollWheel( clicks );
+}
+
+void LLViewerWindow::handleWindowBlock(LLWindow *window)
+{
+ send_agent_pause();
+}
+
+void LLViewerWindow::handleWindowUnblock(LLWindow *window)
+{
+ send_agent_resume();
+}
+
+void LLViewerWindow::handleDataCopy(LLWindow *window, S32 data_type, void *data)
+{
+ const S32 SLURL_MESSAGE_TYPE = 0;
+ switch (data_type)
+ {
+ case SLURL_MESSAGE_TYPE:
+ // received URL
+ std::string url = (const char*)data;
+ LLMediaCtrl* web = NULL;
+ const bool trusted_browser = false;
+ if (LLURLDispatcher::dispatch(url, web, trusted_browser))
+ {
+ // bring window to foreground, as it has just been "launched" from a URL
+ mWindow->bringToFront();
+ }
+ break;
+ }
+}
+
+BOOL LLViewerWindow::handleTimerEvent(LLWindow *window)
+{
+ if (LLViewerJoystick::getInstance()->getOverrideCamera())
+ {
+ LLViewerJoystick::getInstance()->updateStatus();
+ return TRUE;
+ }
+ return FALSE;
+}
+
+BOOL LLViewerWindow::handleDeviceChange(LLWindow *window)
+{
+ // give a chance to use a joystick after startup (hot-plugging)
+ if (!LLViewerJoystick::getInstance()->isJoystickInitialized() )
+ {
+ LLViewerJoystick::getInstance()->init(true);
+ return TRUE;
+ }
+ return FALSE;
+}
+
+void LLViewerWindow::handlePingWatchdog(LLWindow *window, const char * msg)
+{
+ LLAppViewer::instance()->pingMainloopTimeout(msg);
+}
+
+
+void LLViewerWindow::handleResumeWatchdog(LLWindow *window)
+{
+ LLAppViewer::instance()->resumeMainloopTimeout();
+}
+
+void LLViewerWindow::handlePauseWatchdog(LLWindow *window)
+{
+ LLAppViewer::instance()->pauseMainloopTimeout();
+}
+
+//virtual
+std::string LLViewerWindow::translateString(const char* tag)
+{
+ return LLTrans::getString( std::string(tag) );
+}
+
+//virtual
+std::string LLViewerWindow::translateString(const char* tag,
+ const std::map<std::string, std::string>& args)
+{
+ // LLTrans uses a special subclass of std::string for format maps,
+ // but we must use std::map<> in these callbacks, otherwise we create
+ // a dependency between LLWindow and LLFormatMapString. So copy the data.
+ LLStringUtil::format_map_t args_copy;
+ std::map<std::string,std::string>::const_iterator it = args.begin();
+ for ( ; it != args.end(); ++it)
+ {
+ args_copy[it->first] = it->second;
+ }
+ return LLTrans::getString( std::string(tag), args_copy);
+}
+
+//
+// Classes
+//
+LLViewerWindow::LLViewerWindow(
+ const std::string& title, const std::string& name,
+ S32 x, S32 y,
+ S32 width, S32 height,
+ BOOL fullscreen, BOOL ignore_pixel_depth) // fullscreen is no longer used
+ :
+ mWindow(NULL),
+ mActive(TRUE),
+ mWindowRectRaw(0, height, width, 0),
+ mWindowRectScaled(0, height, width, 0),
+ mWorldViewRectRaw(0, height, width, 0),
+ mLeftMouseDown(FALSE),
+ mMiddleMouseDown(FALSE),
+ mRightMouseDown(FALSE),
+ mMouseInWindow( FALSE ),
+ mLastMask( MASK_NONE ),
+ mToolStored( NULL ),
+ mHideCursorPermanent( FALSE ),
+ mCursorHidden(FALSE),
+ mIgnoreActivate( FALSE ),
+ mResDirty(false),
+ mStatesDirty(false),
+ mCurrResolutionIndex(0),
+ mViewerWindowListener(new LLViewerWindowListener(this)),
+ mProgressView(NULL)
+{
+ LLNotificationChannel::buildChannel("VW_alerts", "Visible", LLNotificationFilters::filterBy<std::string>(&LLNotification::getType, "alert"));
+ LLNotificationChannel::buildChannel("VW_alertmodal", "Visible", LLNotificationFilters::filterBy<std::string>(&LLNotification::getType, "alertmodal"));
+
+ LLNotifications::instance().getChannel("VW_alerts")->connectChanged(&LLViewerWindow::onAlert);
+ LLNotifications::instance().getChannel("VW_alertmodal")->connectChanged(&LLViewerWindow::onAlert);
+ LLNotifications::instance().setIgnoreAllNotifications(gSavedSettings.getBOOL("IgnoreAllNotifications"));
+ llinfos << "NOTE: ALL NOTIFICATIONS THAT OCCUR WILL GET ADDED TO IGNORE LIST FOR LATER RUNS." << llendl;
+
+ // Default to application directory.
+ LLViewerWindow::sSnapshotBaseName = "Snapshot";
+ LLViewerWindow::sMovieBaseName = "SLmovie";
+ resetSnapshotLoc();
+
+ // create window
+ mWindow = LLWindowManager::createWindow(this,
+ title, name, x, y, width, height, 0,
+ fullscreen,
+ gNoRender,
+ gSavedSettings.getBOOL("DisableVerticalSync"),
+ !gNoRender,
+ ignore_pixel_depth,
+ gSavedSettings.getBOOL("RenderDeferred") ? 0 : gSavedSettings.getU32("RenderFSAASamples")); //don't use window level anti-aliasing if FBOs are enabled
+
+ if (!LLAppViewer::instance()->restoreErrorTrap())
+ {
+ LL_WARNS("Window") << " Someone took over my signal/exception handler (post createWindow)!" << LL_ENDL;
+ }
+
+ LLCoordScreen scr;
+ mWindow->getSize(&scr);
+
+ if(fullscreen && ( scr.mX!=width || scr.mY!=height))
+ {
+ llwarns << "Fullscreen has forced us in to a different resolution now using "<<scr.mX<<" x "<<scr.mY<<llendl;
+ gSavedSettings.setS32("FullScreenWidth",scr.mX);
+ gSavedSettings.setS32("FullScreenHeight",scr.mY);
+ }
+
+ if (NULL == mWindow)
+ {
+ LLSplashScreen::update(LLTrans::getString("ShuttingDown"));
+#if LL_LINUX || LL_SOLARIS
+ llwarns << "Unable to create window, be sure screen is set at 32-bit color and your graphics driver is configured correctly. See README-linux.txt or README-solaris.txt for further information."
+ << llendl;
+#else
+ LL_WARNS("Window") << "Unable to create window, be sure screen is set at 32-bit color in Control Panels->Display->Settings"
+ << LL_ENDL;
+#endif
+ LLAppViewer::instance()->fastQuit(1);
+ }
+
+ // Get the real window rect the window was created with (since there are various OS-dependent reasons why
+ // the size of a window or fullscreen context may have been adjusted slightly...)
+ F32 ui_scale_factor = gSavedSettings.getF32("UIScaleFactor");
+
+ mDisplayScale.setVec(llmax(1.f / mWindow->getPixelAspectRatio(), 1.f), llmax(mWindow->getPixelAspectRatio(), 1.f));
+ mDisplayScale *= ui_scale_factor;
+ LLUI::setScaleFactor(mDisplayScale);
+
+ {
+ LLCoordWindow size;
+ mWindow->getSize(&size);
+ mWindowRectRaw.set(0, size.mY, size.mX, 0);
+ mWindowRectScaled.set(0, llround((F32)size.mY / mDisplayScale.mV[VY]), llround((F32)size.mX / mDisplayScale.mV[VX]), 0);
+ }
+
+ LLFontManager::initClass();
+
+ //
+ // We want to set this stuff up BEFORE we initialize the pipeline, so we can turn off
+ // stuff like AGP if we think that it'll crash the viewer.
+ //
+ LL_DEBUGS("Window") << "Loading feature tables." << LL_ENDL;
+
+ LLFeatureManager::getInstance()->init();
+
+ // Initialize OpenGL Renderer
+ if (!LLFeatureManager::getInstance()->isFeatureAvailable("RenderVBOEnable") ||
+ !gGLManager.mHasVertexBufferObject)
+ {
+ gSavedSettings.setBOOL("RenderVBOEnable", FALSE);
+ }
+ LLVertexBuffer::initClass(gSavedSettings.getBOOL("RenderVBOEnable"), gSavedSettings.getBOOL("RenderVBOMappingDisable"));
+
+ if (LLFeatureManager::getInstance()->isSafe()
+ || (gSavedSettings.getS32("LastFeatureVersion") != LLFeatureManager::getInstance()->getVersion())
+ || (gSavedSettings.getS32("LastGPUClass") != LLFeatureManager::getInstance()->getGPUClass())
+ || (gSavedSettings.getBOOL("ProbeHardwareOnStartup")))
+ {
+ LLFeatureManager::getInstance()->applyRecommendedSettings();
+ gSavedSettings.setBOOL("ProbeHardwareOnStartup", FALSE);
+ }
+
+ if (!gGLManager.mHasDepthClamp)
+ {
+ LL_INFOS("RenderInit") << "Missing feature GL_ARB_depth_clamp. Void water might disappear in rare cases." << LL_ENDL;
+ }
+
+ // If we crashed while initializng GL stuff last time, disable certain features
+ if (gSavedSettings.getBOOL("RenderInitError"))
+ {
+ mInitAlert = "DisplaySettingsNoShaders";
+ LLFeatureManager::getInstance()->setGraphicsLevel(0, false);
+ gSavedSettings.setU32("RenderQualityPerformance", 0);
+ }
+
+ // Init the image list. Must happen after GL is initialized and before the images that
+ // LLViewerWindow needs are requested.
+ LLImageGL::initClass(LLViewerTexture::MAX_GL_IMAGE_CATEGORY) ;
+ gTextureList.init();
+ LLViewerTextureManager::init() ;
+ gBumpImageList.init();
+
+ // Init font system, but don't actually load the fonts yet
+ // because our window isn't onscreen and they take several
+ // seconds to parse.
+ LLFontGL::initClass( gSavedSettings.getF32("FontScreenDPI"),
+ mDisplayScale.mV[VX],
+ mDisplayScale.mV[VY],
+ gDirUtilp->getAppRODataDir(),
+ LLUI::getXUIPaths());
+
+ // Create container for all sub-views
+ LLView::Params rvp;
+ rvp.name("root");
+ rvp.rect(mWindowRectScaled);
+ rvp.mouse_opaque(false);
+ rvp.follows.flags(FOLLOWS_NONE);
+ mRootView = LLUICtrlFactory::create<LLRootView>(rvp);
+ LLUI::setRootView(mRootView);
+
+ // Make avatar head look forward at start
+ mCurrentMousePoint.mX = getWindowWidthScaled() / 2;
+ mCurrentMousePoint.mY = getWindowHeightScaled() / 2;
+
+ gShowOverlayTitle = gSavedSettings.getBOOL("ShowOverlayTitle");
+ mOverlayTitle = gSavedSettings.getString("OverlayTitle");
+ // Can't have spaces in settings.ini strings, so use underscores instead and convert them.
+ LLStringUtil::replaceChar(mOverlayTitle, '_', ' ');
+
+ // sync the keyboard's setting with the saved setting
+ gSavedSettings.getControl("NumpadControl")->firePropertyChanged();
+
+ mDebugText = new LLDebugText(this);
+
+ mWorldViewRectScaled = calcScaledRect(mWorldViewRectRaw, mDisplayScale);
+}
+
+void LLViewerWindow::initGLDefaults()
+{
+ gGL.setSceneBlendType(LLRender::BT_ALPHA);
+ glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE );
+
+ F32 ambient[4] = {0.f,0.f,0.f,0.f };
+ F32 diffuse[4] = {1.f,1.f,1.f,1.f };
+ glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,ambient);
+ glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,diffuse);
+
+ glPixelStorei(GL_PACK_ALIGNMENT,1);
+ glPixelStorei(GL_UNPACK_ALIGNMENT,1);
+
+ gGL.getTexUnit(0)->enable(LLTexUnit::TT_TEXTURE);
+
+ // lights for objects
+ glShadeModel( GL_SMOOTH );
+
+ glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
+
+ gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
+
+ glCullFace(GL_BACK);
+
+ // RN: Need this for translation and stretch manip.
+ gCone.prerender();
+ gBox.prerender();
+ gSphere.prerender();
+ gCylinder.prerender();
+}
+
+struct MainPanel : public LLPanel
+{
+};
+
+void LLViewerWindow::initBase()
+{
+ S32 height = getWindowHeightScaled();
+ S32 width = getWindowWidthScaled();
+
+ LLRect full_window(0, height, width, 0);
+
+ ////////////////////
+ //
+ // Set the gamma
+ //
+
+ F32 gamma = gSavedSettings.getF32("RenderGamma");
+ if (gamma != 0.0f)
+ {
+ getWindow()->setGamma(gamma);
+ }
+
+ // Create global views
+
+ // Create the floater view at the start so that other views can add children to it.
+ // (But wait to add it as a child of the root view so that it will be in front of the
+ // other views.)
+ MainPanel* main_view = new MainPanel();
+ main_view->buildFromFile("main_view.xml");
+ main_view->setShape(full_window);
+ getRootView()->addChild(main_view);
+
+ // placeholder widget that controls where "world" is rendered
+ mWorldViewPlaceholder = main_view->getChildView("world_view_rect")->getHandle();
+ mNonSideTrayView = main_view->getChildView("non_side_tray_view")->getHandle();
+ mFloaterViewHolder = main_view->getChildView("floater_view_holder")->getHandle();
+ mPopupView = main_view->getChild<LLPopupView>("popup_holder");
+ mHintHolder = main_view->getChild<LLView>("hint_holder")->getHandle();
+ mLoginPanelHolder = main_view->getChild<LLView>("login_panel_holder")->getHandle();
+
+ // Constrain floaters to inside the menu and status bar regions.
+ gFloaterView = main_view->getChild<LLFloaterView>("Floater View");
+ gFloaterView->setFloaterSnapView(main_view->getChild<LLView>("floater_snap_region")->getHandle());
+ gSnapshotFloaterView = main_view->getChild<LLSnapshotFloaterView>("Snapshot Floater View");
+
+
+ // Console
+ llassert( !gConsole );
+ LLConsole::Params cp;
+ cp.name("console");
+ cp.max_lines(gSavedSettings.getS32("ConsoleBufferSize"));
+ cp.rect(getChatConsoleRect());
+ cp.persist_time(gSavedSettings.getF32("ChatPersistTime"));
+ cp.font_size_index(gSavedSettings.getS32("ChatFontSize"));
+ cp.follows.flags(FOLLOWS_LEFT | FOLLOWS_RIGHT | FOLLOWS_BOTTOM);
+ gConsole = LLUICtrlFactory::create<LLConsole>(cp);
+ getRootView()->addChild(gConsole);
+
+ // optionally forward warnings to chat console/chat floater
+ // for qa runs and dev builds
+#if !LL_RELEASE_FOR_DOWNLOAD
+ LLError::addRecorder(RecordToChatConsole::getInstance());
+#else
+ if(gSavedSettings.getBOOL("QAMode"))
+ {
+ LLError::addRecorder(RecordToChatConsole::getInstance());
+ }
+#endif
+
+ gDebugView = getRootView()->getChild<LLDebugView>("DebugView");
+ gDebugView->init();
+ gToolTipView = getRootView()->getChild<LLToolTipView>("tooltip view");
+
+ // Initialize busy response message when logged in
+ LLAppViewer::instance()->setOnLoginCompletedCallback(boost::bind(&LLFloaterPreference::initBusyResponse));
+
+ // Add the progress bar view (startup view), which overrides everything
+ mProgressView = getRootView()->findChild<LLProgressView>("progress_view");
+ setShowProgress(FALSE);
+ setProgressCancelButtonVisible(FALSE);
+
+ gMenuHolder = getRootView()->getChild<LLViewerMenuHolderGL>("Menu Holder");
+
+ LLMenuGL::sMenuContainer = gMenuHolder;
+
+}
+
+void LLViewerWindow::initWorldUI()
+{
+ S32 height = mRootView->getRect().getHeight();
+ S32 width = mRootView->getRect().getWidth();
+ LLRect full_window(0, height, width, 0);
+
+
+ gIMMgr = LLIMMgr::getInstance();
+
+ //getRootView()->sendChildToFront(gFloaterView);
+ //getRootView()->sendChildToFront(gSnapshotFloaterView);
+
+ // new bottom panel
+ LLPanel* bottom_tray_container = getRootView()->getChild<LLPanel>("bottom_tray_container");
+ LLBottomTray* bottom_tray = LLBottomTray::getInstance();
+ bottom_tray->setShape(bottom_tray_container->getLocalRect());
+ bottom_tray->setFollowsAll();
+ bottom_tray_container->addChild(bottom_tray);
+ bottom_tray_container->setVisible(TRUE);
+
+ LLRect morph_view_rect = full_window;
+ morph_view_rect.stretch( -STATUS_BAR_HEIGHT );
+ morph_view_rect.mTop = full_window.mTop - 32;
+ LLMorphView::Params mvp;
+ mvp.name("MorphView");
+ mvp.rect(morph_view_rect);
+ mvp.visible(false);
+ gMorphView = LLUICtrlFactory::create<LLMorphView>(mvp);
+ getRootView()->addChild(gMorphView);
+
+ LLWorldMapView::initClass();
+
+ // Force gFloaterWorldMap to initialize
+ LLFloaterReg::getInstance("world_map");
+
+ // Force gFloaterTools to initialize
+ LLFloaterReg::getInstance("build");
+ LLFloaterReg::hideInstance("build");
+
+ // Status bar
+ LLPanel* status_bar_container = getRootView()->getChild<LLPanel>("status_bar_container");
+ gStatusBar = new LLStatusBar(status_bar_container->getLocalRect());
+ gStatusBar->setFollowsAll();
+ gStatusBar->setShape(status_bar_container->getLocalRect());
+ // sync bg color with menu bar
+ gStatusBar->setBackgroundColor( gMenuBarView->getBackgroundColor().get() );
+ status_bar_container->addChild(gStatusBar);
+ status_bar_container->setVisible(TRUE);
+
+ // Navigation bar
+ LLPanel* nav_bar_container = getRootView()->getChild<LLPanel>("nav_bar_container");
+
+ LLNavigationBar* navbar = LLNavigationBar::getInstance();
+ navbar->setShape(nav_bar_container->getLocalRect());
+ navbar->setBackgroundColor(gMenuBarView->getBackgroundColor().get());
+ nav_bar_container->addChild(navbar);
+ nav_bar_container->setVisible(TRUE);
+
+ if (!gSavedSettings.getBOOL("ShowNavbarNavigationPanel"))
+ {
+ navbar->showNavigationPanel(FALSE);
+ }
+
+ if (!gSavedSettings.getBOOL("ShowNavbarFavoritesPanel"))
+ {
+ navbar->showFavoritesPanel(FALSE);
+ }
+
+ // Top Info bar
+ LLPanel* topinfo_bar_container = getRootView()->getChild<LLPanel>("topinfo_bar_container");
+ LLPanelTopInfoBar* topinfo_bar = LLPanelTopInfoBar::getInstance();
+
+ topinfo_bar->setShape(topinfo_bar_container->getLocalRect());
+
+ topinfo_bar_container->addChild(topinfo_bar);
+ topinfo_bar_container->setVisible(TRUE);
+
+ if (!gSavedSettings.getBOOL("ShowMiniLocationPanel"))
+ {
+ topinfo_bar->setVisible(FALSE);
+ }
+
+ if ( gHUDView == NULL )
+ {
+ LLRect hud_rect = full_window;
+ hud_rect.mBottom += 50;
+ if (gMenuBarView && gMenuBarView->isInVisibleChain())
+ {
+ hud_rect.mTop -= gMenuBarView->getRect().getHeight();
+ }
+ gHUDView = new LLHUDView(hud_rect);
+ // put behind everything else in the UI
+ getRootView()->addChildInBack(gHUDView);
+ }
+
+ LLPanel* panel_ssf_container = getRootView()->getChild<LLPanel>("stand_stop_flying_container");
+ LLPanelStandStopFlying* panel_stand_stop_flying = LLPanelStandStopFlying::getInstance();
+ panel_ssf_container->addChild(panel_stand_stop_flying);
+ panel_ssf_container->setVisible(TRUE);
+
+ // put sidetray in container
+ LLPanel* side_tray_container = getRootView()->getChild<LLPanel>("side_tray_container");
+ LLSideTray* sidetrayp = LLSideTray::getInstance();
+ sidetrayp->setShape(side_tray_container->getLocalRect());
+ // don't follow right edge to avoid spurious resizes, since we are using a fixed width layout
+ sidetrayp->setFollows(FOLLOWS_LEFT|FOLLOWS_TOP|FOLLOWS_BOTTOM);
+ side_tray_container->addChild(sidetrayp);
+ side_tray_container->setVisible(FALSE);
+
+ // put sidetray buttons in their own panel
+ LLPanel* buttons_panel = sidetrayp->getButtonsPanel();
+ LLPanel* buttons_panel_container = getRootView()->getChild<LLPanel>("side_bar_tabs");
+ buttons_panel->setShape(buttons_panel_container->getLocalRect());
+ buttons_panel->setFollowsAll();
+ buttons_panel_container->addChild(buttons_panel);
+
+ LLView* avatar_picker_destination_guide_container = gViewerWindow->getRootView()->getChild<LLView>("avatar_picker_and_destination_guide_container");
+ avatar_picker_destination_guide_container->getChild<LLButton>("close")->setCommitCallback(boost::bind(toggle_destination_and_avatar_picker, LLSD()));
+ LLMediaCtrl* destinations = avatar_picker_destination_guide_container->findChild<LLMediaCtrl>("destination_guide_contents");
+ LLMediaCtrl* avatar_picker = avatar_picker_destination_guide_container->findChild<LLMediaCtrl>("avatar_picker_contents");
+ if (destinations)
+ {
+ destinations->navigateTo(gSavedSettings.getString("DestinationGuideURL"), "text/html");
+ }
+
+ if (avatar_picker)
+ {
+ avatar_picker->navigateTo(gSavedSettings.getString("AvatarPickerURL"), "text/html");
+ }
+
+}
+
+// Destroy the UI
+void LLViewerWindow::shutdownViews()
+{
+ // clean up warning logger
+ LLError::removeRecorder(RecordToChatConsole::getInstance());
+
+ delete mDebugText;
+ mDebugText = NULL;
+
+ // Cleanup global views
+ if (gMorphView)
+ {
+ gMorphView->setVisible(FALSE);
+ }
+
+ // DEV-40930: Clear sModalStack. Otherwise, any LLModalDialog left open
+ // will crump with LL_ERRS.
+ LLModalDialog::shutdownModals();
+
+ // destroy the nav bar, not currently part of gViewerWindow
+ // *TODO: Make LLNavigationBar part of gViewerWindow
+ delete LLNavigationBar::getInstance();
+
+ // destroy menus after instantiating navbar above, as it needs
+ // access to gMenuHolder
+ cleanup_menus();
+
+ // Delete all child views.
+ delete mRootView;
+ mRootView = NULL;
+
+ // Automatically deleted as children of mRootView. Fix the globals.
+ gStatusBar = NULL;
+ gIMMgr = NULL;
+ gToolTipView = NULL;
+
+ gFloaterView = NULL;
+ gMorphView = NULL;
+
+ gHUDView = NULL;
+}
+
+void LLViewerWindow::shutdownGL()
+{
+ //--------------------------------------------------------
+ // Shutdown GL cleanly. Order is very important here.
+ //--------------------------------------------------------
+ LLFontGL::destroyDefaultFonts();
+ LLFontManager::cleanupClass();
+ stop_glerror();
+
+ gSky.cleanup();
+ stop_glerror();
+
+ LLWearableList::instance().cleanup() ;
+
+ gTextureList.shutdown();
+ stop_glerror();
+
+ gBumpImageList.shutdown();
+ stop_glerror();
+
+ LLWorldMapView::cleanupTextures();
+
+ llinfos << "Cleaning up pipeline" << llendl;
+ gPipeline.cleanup();
+ stop_glerror();
+
+ LLViewerTextureManager::cleanup() ;
+ LLImageGL::cleanupClass() ;
+
+ llinfos << "All textures and llimagegl images are destroyed!" << llendl ;
+
+ llinfos << "Cleaning up select manager" << llendl;
+ LLSelectMgr::getInstance()->cleanup();
+
+ LLVertexBuffer::cleanupClass();
+
+ llinfos << "Stopping GL during shutdown" << llendl;
+ if (!gNoRender)
+ {
+ stopGL(FALSE);
+ stop_glerror();
+ }
+
+ gGL.shutdown();
+}
+
+// shutdownViews() and shutdownGL() need to be called first
+LLViewerWindow::~LLViewerWindow()
+{
+ llinfos << "Destroying Window" << llendl;
+ destroyWindow();
+
+ delete mDebugText;
+ mDebugText = NULL;
+}
+
+
+void LLViewerWindow::setCursor( ECursorType c )
+{
+ mWindow->setCursor( c );
+}
+
+void LLViewerWindow::showCursor()
+{
+ mWindow->showCursor();
+
+ mCursorHidden = FALSE;
+}
+
+void LLViewerWindow::hideCursor()
+{
+ // And hide the cursor
+ mWindow->hideCursor();
+
+ mCursorHidden = TRUE;
+}
+
+void LLViewerWindow::sendShapeToSim()
+{
+ LLMessageSystem* msg = gMessageSystem;
+ if(!msg) return;
+ msg->newMessageFast(_PREHASH_AgentHeightWidth);
+ msg->nextBlockFast(_PREHASH_AgentData);
+ msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
+ msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ msg->addU32Fast(_PREHASH_CircuitCode, gMessageSystem->mOurCircuitCode);
+ msg->nextBlockFast(_PREHASH_HeightWidthBlock);
+ msg->addU32Fast(_PREHASH_GenCounter, 0);
+ U16 height16 = (U16) mWorldViewRectRaw.getHeight();
+ U16 width16 = (U16) mWorldViewRectRaw.getWidth();
+ msg->addU16Fast(_PREHASH_Height, height16);
+ msg->addU16Fast(_PREHASH_Width, width16);
+ gAgent.sendReliableMessage();
+}
+
+// Must be called after window is created to set up agent
+// camera variables and UI variables.
+void LLViewerWindow::reshape(S32 width, S32 height)
+{
+ // Destroying the window at quit time generates spurious
+ // reshape messages. We don't care about these, and we
+ // don't want to send messages because the message system
+ // may have been destructed.
+ if (!LLApp::isExiting())
+ {
+ if (gNoRender)
+ {
+ return;
+ }
+
+ gWindowResized = TRUE;
+
+ // update our window rectangle
+ mWindowRectRaw.mRight = mWindowRectRaw.mLeft + width;
+ mWindowRectRaw.mTop = mWindowRectRaw.mBottom + height;
+
+ //glViewport(0, 0, width, height );
+
+ if (height > 0)
+ {
+ LLViewerCamera::getInstance()->setViewHeightInPixels( mWorldViewRectRaw.getHeight() );
+ LLViewerCamera::getInstance()->setAspect( getWorldViewAspectRatio() );
+ }
+
+ calcDisplayScale();
+
+ BOOL display_scale_changed = mDisplayScale != LLUI::sGLScaleFactor;
+ LLUI::setScaleFactor(mDisplayScale);
+
+ // update our window rectangle
+ mWindowRectScaled.mRight = mWindowRectScaled.mLeft + llround((F32)width / mDisplayScale.mV[VX]);
+ mWindowRectScaled.mTop = mWindowRectScaled.mBottom + llround((F32)height / mDisplayScale.mV[VY]);
+
+ setup2DViewport();
+
+ // Inform lower views of the change
+ // round up when converting coordinates to make sure there are no gaps at edge of window
+ LLView::sForceReshape = display_scale_changed;
+ mRootView->reshape(llceil((F32)width / mDisplayScale.mV[VX]), llceil((F32)height / mDisplayScale.mV[VY]));
+ LLView::sForceReshape = FALSE;
+
+ // clear font width caches
+ if (display_scale_changed)
+ {
+ LLHUDObject::reshapeAll();
+ }
+
+ sendShapeToSim();
+
+ // store new settings for the mode we are in, regardless
+ // Only save size if not maximized
+ BOOL maximized = mWindow->getMaximized();
+ gSavedSettings.setBOOL("WindowMaximized", maximized);
+
+ LLCoordScreen window_size;
+ if (!maximized
+ && mWindow->getSize(&window_size))
+ {
+ gSavedSettings.setS32("WindowWidth", window_size.mX);
+ gSavedSettings.setS32("WindowHeight", window_size.mY);
+ }
+
+ LLViewerStats::getInstance()->setStat(LLViewerStats::ST_WINDOW_WIDTH, (F64)width);
+ LLViewerStats::getInstance()->setStat(LLViewerStats::ST_WINDOW_HEIGHT, (F64)height);
+ }
+}
+
+
+// Hide normal UI when a logon fails
+void LLViewerWindow::setNormalControlsVisible( BOOL visible )
+{
+ if(LLBottomTray::instanceExists())
+ {
+ LLBottomTray::getInstance()->setVisible(visible);
+ LLBottomTray::getInstance()->setEnabled(visible);
+ }
+
+ if ( gMenuBarView )
+ {
+ gMenuBarView->setVisible( visible );
+ gMenuBarView->setEnabled( visible );
+
+ // ...and set the menu color appropriately.
+ setMenuBackgroundColor(gAgent.getGodLevel() > GOD_NOT,
+ LLGridManager::getInstance()->isInProductionGrid());
+ }
+
+ if ( gStatusBar )
+ {
+ gStatusBar->setVisible( visible );
+ gStatusBar->setEnabled( visible );
+ }
+
+ LLNavigationBar* navbarp = LLUI::getRootView()->findChild<LLNavigationBar>("navigation_bar");
+ if (navbarp)
+ {
+ navbarp->setVisible( visible );
+ }
+}
+
+void LLViewerWindow::setMenuBackgroundColor(bool god_mode, bool dev_grid)
+{
+ LLSD args;
+ LLColor4 new_bg_color;
+
+ // no l10n problem because channel is always an english string
+ std::string channel = LLVersionInfo::getChannel();
+ bool isProject = (channel.find("Project") != std::string::npos);
+
+ // god more important than project, proj more important than grid
+ if(god_mode && LLGridManager::getInstance()->isInProductionGrid())
+ {
+ new_bg_color = LLUIColorTable::instance().getColor( "MenuBarGodBgColor" );
+ }
+ else if(god_mode && !LLGridManager::getInstance()->isInProductionGrid())
+ {
+ new_bg_color = LLUIColorTable::instance().getColor( "MenuNonProductionGodBgColor" );
+ }
+ else if (!god_mode && isProject)
+ {
+ new_bg_color = LLUIColorTable::instance().getColor( "MenuBarProjectBgColor" );
+ }
+ else if(!god_mode && !LLGridManager::getInstance()->isInProductionGrid())
+ {
+ new_bg_color = LLUIColorTable::instance().getColor( "MenuNonProductionBgColor" );
+ }
+ else
+ {
+ new_bg_color = LLUIColorTable::instance().getColor( "MenuBarBgColor" );
+ }
+
+ if(gMenuBarView)
+ {
+ gMenuBarView->setBackgroundColor( new_bg_color );
+ }
+
+ if(gStatusBar)
+ {
+ gStatusBar->setBackgroundColor( new_bg_color );
+ }
+}
+
+void LLViewerWindow::drawDebugText()
+{
+ gGL.color4f(1,1,1,1);
+ gGL.pushMatrix();
+ gGL.pushUIMatrix();
+ {
+ // scale view by UI global scale factor and aspect ratio correction factor
+ gGL.scaleUI(mDisplayScale.mV[VX], mDisplayScale.mV[VY], 1.f);
+ mDebugText->draw();
+ }
+ gGL.popUIMatrix();
+ gGL.popMatrix();
+
+ gGL.flush();
+}
+
+void LLViewerWindow::draw()
+{
+
+//#if LL_DEBUG
+ LLView::sIsDrawing = TRUE;
+//#endif
+ stop_glerror();
+
+ LLUI::setLineWidth(1.f);
+
+ LLUI::setLineWidth(1.f);
+ // Reset any left-over transforms
+ glMatrixMode(GL_MODELVIEW);
+
+ glLoadIdentity();
+
+ //S32 screen_x, screen_y;
+
+ if (!gSavedSettings.getBOOL("RenderUIBuffer"))
+ {
+ LLUI::sDirtyRect = getWindowRectScaled();
+ }
+
+ // HACK for timecode debugging
+ if (gSavedSettings.getBOOL("DisplayTimecode"))
+ {
+ // draw timecode block
+ std::string text;
+
+ glLoadIdentity();
+
+ microsecondsToTimecodeString(gFrameTime,text);
+ const LLFontGL* font = LLFontGL::getFontSansSerif();
+ font->renderUTF8(text, 0,
+ llround((getWindowWidthScaled()/2)-100.f),
+ llround((getWindowHeightScaled()-60.f)),
+ LLColor4( 1.f, 1.f, 1.f, 1.f ),
+ LLFontGL::LEFT, LLFontGL::TOP);
+ }
+
+ // Draw all nested UI views.
+ // No translation needed, this view is glued to 0,0
+
+ gGL.pushMatrix();
+ LLUI::pushMatrix();
+ {
+
+ // scale view by UI global scale factor and aspect ratio correction factor
+ gGL.scaleUI(mDisplayScale.mV[VX], mDisplayScale.mV[VY], 1.f);
+
+ LLVector2 old_scale_factor = LLUI::sGLScaleFactor;
+ // apply camera zoom transform (for high res screenshots)
+ F32 zoom_factor = LLViewerCamera::getInstance()->getZoomFactor();
+ S16 sub_region = LLViewerCamera::getInstance()->getZoomSubRegion();
+ if (zoom_factor > 1.f)
+ {
+ //decompose subregion number to x and y values
+ int pos_y = sub_region / llceil(zoom_factor);
+ int pos_x = sub_region - (pos_y*llceil(zoom_factor));
+ // offset for this tile
+ glTranslatef((F32)getWindowWidthScaled() * -(F32)pos_x,
+ (F32)getWindowHeightScaled() * -(F32)pos_y,
+ 0.f);
+ glScalef(zoom_factor, zoom_factor, 1.f);
+ LLUI::sGLScaleFactor *= zoom_factor;
+ }
+
+ // Draw tool specific overlay on world
+ LLToolMgr::getInstance()->getCurrentTool()->draw();
+
+ if( gAgentCamera.cameraMouselook() || LLFloaterCamera::inFreeCameraMode() )
+ {
+ drawMouselookInstructions();
+ stop_glerror();
+ }
+
+ // Draw all nested UI views.
+ // No translation needed, this view is glued to 0,0
+ mRootView->draw();
+
+ if (LLView::sDebugRects)
+ {
+ gToolTipView->drawStickyRect();
+ }
+
+ // Draw optional on-top-of-everyone view
+ LLUICtrl* top_ctrl = gFocusMgr.getTopCtrl();
+ if (top_ctrl && top_ctrl->getVisible())
+ {
+ S32 screen_x, screen_y;
+ top_ctrl->localPointToScreen(0, 0, &screen_x, &screen_y);
+
+ glMatrixMode(GL_MODELVIEW);
+ LLUI::pushMatrix();
+ LLUI::translate( (F32) screen_x, (F32) screen_y, 0.f);
+ top_ctrl->draw();
+ LLUI::popMatrix();
+ }
+
+
+ if( gShowOverlayTitle && !mOverlayTitle.empty() )
+ {
+ // Used for special titles such as "Second Life - Special E3 2003 Beta"
+ const S32 DIST_FROM_TOP = 20;
+ LLFontGL::getFontSansSerifBig()->renderUTF8(
+ mOverlayTitle, 0,
+ llround( getWindowWidthScaled() * 0.5f),
+ getWindowHeightScaled() - DIST_FROM_TOP,
+ LLColor4(1, 1, 1, 0.4f),
+ LLFontGL::HCENTER, LLFontGL::TOP);
+ }
+
+ LLUI::sGLScaleFactor = old_scale_factor;
+ }
+ LLUI::popMatrix();
+ gGL.popMatrix();
+
+//#if LL_DEBUG
+ LLView::sIsDrawing = FALSE;
+//#endif
+}
+
+// Takes a single keydown event, usually when UI is visible
+BOOL LLViewerWindow::handleKey(KEY key, MASK mask)
+{
+ // hide tooltips on keypress
+ LLToolTipMgr::instance().blockToolTips();
+
+ if (gFocusMgr.getKeyboardFocus()
+ && !(mask & (MASK_CONTROL | MASK_ALT))
+ && !gFocusMgr.getKeystrokesOnly())
+ {
+ // We have keyboard focus, and it's not an accelerator
+ if (key < 0x80)
+ {
+ // Not a special key, so likely (we hope) to generate a character. Let it fall through to character handler first.
+ return (gFocusMgr.getKeyboardFocus() != NULL);
+ }
+ }
+
+ // let menus handle navigation keys for navigation
+ if ((gMenuBarView && gMenuBarView->handleKey(key, mask, TRUE))
+ ||(gLoginMenuBarView && gLoginMenuBarView->handleKey(key, mask, TRUE))
+ ||(gMenuHolder && gMenuHolder->handleKey(key, mask, TRUE)))
+ {
+ return TRUE;
+ }
+
+ LLFocusableElement* keyboard_focus = gFocusMgr.getKeyboardFocus();
+
+ // give menus a chance to handle modified (Ctrl, Alt) shortcut keys before current focus
+ // as long as focus isn't locked
+ if (mask & (MASK_CONTROL | MASK_ALT) && !gFocusMgr.focusLocked())
+ {
+ // Check the current floater's menu first, if it has one.
+ if (gFocusMgr.keyboardFocusHasAccelerators()
+ && keyboard_focus
+ && keyboard_focus->handleKey(key,mask,FALSE))
+ {
+ return TRUE;
+ }
+
+ if ((gMenuBarView && gMenuBarView->handleAcceleratorKey(key, mask))
+ ||(gLoginMenuBarView && gLoginMenuBarView->handleAcceleratorKey(key, mask)))
+ {
+ return TRUE;
+ }
+ }
+
+ // give floaters first chance to handle TAB key
+ // so frontmost floater gets focus
+ // if nothing has focus, go to first or last UI element as appropriate
+ if (key == KEY_TAB && (mask & MASK_CONTROL || gFocusMgr.getKeyboardFocus() == NULL))
+ {
+ if (gMenuHolder) gMenuHolder->hideMenus();
+
+ // if CTRL-tabbing (and not just TAB with no focus), go into window cycle mode
+ gFloaterView->setCycleMode((mask & MASK_CONTROL) != 0);
+
+ // do CTRL-TAB and CTRL-SHIFT-TAB logic
+ if (mask & MASK_SHIFT)
+ {
+ mRootView->focusPrevRoot();
+ }
+ else
+ {
+ mRootView->focusNextRoot();
+ }
+ return TRUE;
+ }
+ // hidden edit menu for cut/copy/paste
+ if (gEditMenu && gEditMenu->handleAcceleratorKey(key, mask))
+ {
+ return TRUE;
+ }
+
+ // Traverses up the hierarchy
+ if( keyboard_focus )
+ {
+ LLLineEditor* chat_editor = LLBottomTray::instanceExists() ? LLBottomTray::getInstance()->getNearbyChatBar()->getChatBox() : NULL;
+ // arrow keys move avatar while chatting hack
+ if (chat_editor && chat_editor->hasFocus())
+ {
+ // If text field is empty, there's no point in trying to move
+ // cursor with arrow keys, so allow movement
+ if (chat_editor->getText().empty()
+ || gSavedSettings.getBOOL("ArrowKeysAlwaysMove"))
+ {
+ // let Control-Up and Control-Down through for chat line history,
+ if (!(key == KEY_UP && mask == MASK_CONTROL)
+ && !(key == KEY_DOWN && mask == MASK_CONTROL))
+ {
+ switch(key)
+ {
+ case KEY_LEFT:
+ case KEY_RIGHT:
+ case KEY_UP:
+ case KEY_DOWN:
+ case KEY_PAGE_UP:
+ case KEY_PAGE_DOWN:
+ case KEY_HOME:
+ // when chatbar is empty or ArrowKeysAlwaysMove set,
+ // pass arrow keys on to avatar...
+ return FALSE;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+ if (keyboard_focus->handleKey(key, mask, FALSE))
+ {
+ return TRUE;
+ }
+ }
+
+ if( LLToolMgr::getInstance()->getCurrentTool()->handleKey(key, mask) )
+ {
+ return TRUE;
+ }
+
+ // Try for a new-format gesture
+ if (LLGestureMgr::instance().triggerGesture(key, mask))
+ {
+ return TRUE;
+ }
+
+ // See if this is a gesture trigger. If so, eat the key and
+ // don't pass it down to the menus.
+ if (gGestureList.trigger(key, mask))
+ {
+ return TRUE;
+ }
+
+ // If "Pressing letter keys starts local chat" option is selected, we are not in mouselook,
+ // no view has keyboard focus, this is a printable character key (and no modifier key is
+ // pressed except shift), then give focus to nearby chat (STORM-560)
+ if ( gSavedSettings.getS32("LetterKeysFocusChatBar") && !gAgentCamera.cameraMouselook() &&
+ !keyboard_focus && key < 0x80 && (mask == MASK_NONE || mask == MASK_SHIFT) )
+ {
+ LLLineEditor* chat_editor = LLBottomTray::instanceExists() ? LLBottomTray::getInstance()->getNearbyChatBar()->getChatBox() : NULL;
+ if (chat_editor)
+ {
+ // passing NULL here, character will be added later when it is handled by character handler.
+ LLBottomTray::getInstance()->getNearbyChatBar()->startChat(NULL);
+ return TRUE;
+ }
+ }
+
+ // give menus a chance to handle unmodified accelerator keys
+ if ((gMenuBarView && gMenuBarView->handleAcceleratorKey(key, mask))
+ ||(gLoginMenuBarView && gLoginMenuBarView->handleAcceleratorKey(key, mask)))
+ {
+ return TRUE;
+ }
+
+ // don't pass keys on to world when something in ui has focus
+ return gFocusMgr.childHasKeyboardFocus(mRootView)
+ || LLMenuGL::getKeyboardMode()
+ || (gMenuBarView && gMenuBarView->getHighlightedItem() && gMenuBarView->getHighlightedItem()->isActive());
+}
+
+
+BOOL LLViewerWindow::handleUnicodeChar(llwchar uni_char, MASK mask)
+{
+ // HACK: We delay processing of return keys until they arrive as a Unicode char,
+ // so that if you're typing chat text at low frame rate, we don't send the chat
+ // until all keystrokes have been entered. JC
+ // HACK: Numeric keypad <enter> on Mac is Unicode 3
+ // HACK: Control-M on Windows is Unicode 13
+ if ((uni_char == 13 && mask != MASK_CONTROL)
+ || (uni_char == 3 && mask == MASK_NONE))
+ {
+ return gViewerKeyboard.handleKey(KEY_RETURN, mask, gKeyboard->getKeyRepeated(KEY_RETURN));
+ }
+
+ // let menus handle navigation (jump) keys
+ if (gMenuBarView && gMenuBarView->handleUnicodeChar(uni_char, TRUE))
+ {
+ return TRUE;
+ }
+
+ // Traverses up the hierarchy
+ LLFocusableElement* keyboard_focus = gFocusMgr.getKeyboardFocus();
+ if( keyboard_focus )
+ {
+ if (keyboard_focus->handleUnicodeChar(uni_char, FALSE))
+ {
+ return TRUE;
+ }
+
+ //// Topmost view gets a chance before the hierarchy
+ //LLUICtrl* top_ctrl = gFocusMgr.getTopCtrl();
+ //if (top_ctrl && top_ctrl->handleUnicodeChar( uni_char, FALSE ) )
+ //{
+ // return TRUE;
+ //}
+
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+
+void LLViewerWindow::handleScrollWheel(S32 clicks)
+{
+ LLView::sMouseHandlerMessage.clear();
+
+ LLUI::resetMouseIdleTimer();
+
+ LLMouseHandler* mouse_captor = gFocusMgr.getMouseCapture();
+ if( mouse_captor )
+ {
+ S32 local_x;
+ S32 local_y;
+ mouse_captor->screenPointToLocal( mCurrentMousePoint.mX, mCurrentMousePoint.mY, &local_x, &local_y );
+ mouse_captor->handleScrollWheel(local_x, local_y, clicks);
+ if (LLView::sDebugMouseHandling)
+ {
+ llinfos << "Scroll Wheel handled by captor " << mouse_captor->getName() << llendl;
+ }
+ return;
+ }
+
+ LLUICtrl* top_ctrl = gFocusMgr.getTopCtrl();
+ if (top_ctrl)
+ {
+ S32 local_x;
+ S32 local_y;
+ top_ctrl->screenPointToLocal( mCurrentMousePoint.mX, mCurrentMousePoint.mY, &local_x, &local_y );
+ if (top_ctrl->handleScrollWheel(local_x, local_y, clicks)) return;
+ }
+
+ if (mRootView->handleScrollWheel(mCurrentMousePoint.mX, mCurrentMousePoint.mY, clicks) )
+ {
+ if (LLView::sDebugMouseHandling)
+ {
+ llinfos << "Scroll Wheel" << LLView::sMouseHandlerMessage << llendl;
+ }
+ return;
+ }
+ else if (LLView::sDebugMouseHandling)
+ {
+ llinfos << "Scroll Wheel not handled by view" << llendl;
+ }
+
+ // Zoom the camera in and out behavior
+
+ if(top_ctrl == 0
+ && getWorldViewRectScaled().pointInRect(mCurrentMousePoint.mX, mCurrentMousePoint.mY)
+ && gAgentCamera.isInitialized())
+ gAgentCamera.handleScrollWheel(clicks);
+
+ return;
+}
+
+void LLViewerWindow::addPopup(LLView* popup)
+{
+ if (mPopupView)
+ {
+ mPopupView->addPopup(popup);
+ }
+}
+
+void LLViewerWindow::removePopup(LLView* popup)
+{
+ if (mPopupView)
+ {
+ mPopupView->removePopup(popup);
+ }
+}
+
+void LLViewerWindow::clearPopups()
+{
+ if (mPopupView)
+ {
+ mPopupView->clearPopups();
+ }
+}
+
+void LLViewerWindow::moveCursorToCenter()
+{
+ if (! gSavedSettings.getBOOL("DisableMouseWarp"))
+ {
+ S32 x = getWorldViewWidthScaled() / 2;
+ S32 y = getWorldViewHeightScaled() / 2;
+
+ //on a forced move, all deltas get zeroed out to prevent jumping
+ mCurrentMousePoint.set(x,y);
+ mLastMousePoint.set(x,y);
+ mCurrentMouseDelta.set(0,0);
+
+ LLUI::setMousePositionScreen(x, y);
+ }
+}
+
+
+//////////////////////////////////////////////////////////////////////
+//
+// Hover handlers
+//
+
+void append_xui_tooltip(LLView* viewp, LLToolTip::Params& params)
+{
+ if (viewp)
+ {
+ if (!params.styled_message.empty())
+ {
+ params.styled_message.add().text("\n---------\n");
+ }
+ LLView::root_to_view_iterator_t end_tooltip_it = viewp->endRootToView();
+ // NOTE: we skip "root" since it is assumed
+ for (LLView::root_to_view_iterator_t tooltip_it = ++viewp->beginRootToView();
+ tooltip_it != end_tooltip_it;
+ ++tooltip_it)
+ {
+ LLView* viewp = *tooltip_it;
+
+ params.styled_message.add().text(viewp->getName());
+
+ LLPanel* panelp = dynamic_cast<LLPanel*>(viewp);
+ if (panelp && !panelp->getXMLFilename().empty())
+ {
+ params.styled_message.add()
+ .text("(" + panelp->getXMLFilename() + ")")
+ .style.color(LLColor4(0.7f, 0.7f, 1.f, 1.f));
+ }
+ params.styled_message.add().text("/");
+ }
+ }
+}
+
+// Update UI based on stored mouse position from mouse-move
+// event processing.
+void LLViewerWindow::updateUI()
+{
+ static LLFastTimer::DeclareTimer ftm("Update UI");
+ LLFastTimer t(ftm);
+
+ static std::string last_handle_msg;
+
+ if (gLoggedInTime.getStarted())
+ {
+ if (gLoggedInTime.getElapsedTimeF32() > gSavedSettings.getF32("DestinationGuideHintTimeout"))
+ {
+ LLFirstUse::notUsingDestinationGuide();
+ }
+ if (gLoggedInTime.getElapsedTimeF32() > gSavedSettings.getF32("SidePanelHintTimeout"))
+ {
+ LLFirstUse::notUsingSidePanel();
+ }
+ }
+
+ LLConsole::updateClass();
+
+ // animate layout stacks so we have up to date rect for world view
+ LLLayoutStack::updateClass();
+
+ // use full window for world view when not rendering UI
+ bool world_view_uses_full_window = gAgentCamera.cameraMouselook() || !gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI);
+ updateWorldViewRect(world_view_uses_full_window);
+
+ LLView::sMouseHandlerMessage.clear();
+
+ S32 x = mCurrentMousePoint.mX;
+ S32 y = mCurrentMousePoint.mY;
+ MASK mask = gKeyboard->currentMask(TRUE);
+
+ if (gNoRender)
+ {
+ return;
+ }
+
+ if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_RAYCAST))
+ {
+ gDebugRaycastFaceHit = -1;
+ gDebugRaycastObject = cursorIntersect(-1, -1, 512.f, NULL, -1, FALSE,
+ &gDebugRaycastFaceHit,
+ &gDebugRaycastIntersection,
+ &gDebugRaycastTexCoord,
+ &gDebugRaycastNormal,
+ &gDebugRaycastBinormal,
+ &gDebugRaycastStart,
+ &gDebugRaycastEnd);
+ }
+
+ updateMouseDelta();
+ updateKeyboardFocus();
+
+ BOOL handled = FALSE;
+
+ BOOL handled_by_top_ctrl = FALSE;
+ LLUICtrl* top_ctrl = gFocusMgr.getTopCtrl();
+ LLMouseHandler* mouse_captor = gFocusMgr.getMouseCapture();
+ LLView* captor_view = dynamic_cast<LLView*>(mouse_captor);
+
+ //FIXME: only include captor and captor's ancestors if mouse is truly over them --RN
+
+ //build set of views containing mouse cursor by traversing UI hierarchy and testing
+ //screen rect against mouse cursor
+ view_handle_set_t mouse_hover_set;
+
+ // constraint mouse enter events to children of mouse captor
+ LLView* root_view = captor_view;
+
+ // if mouse captor doesn't exist or isn't a LLView
+ // then allow mouse enter events on entire UI hierarchy
+ if (!root_view)
+ {
+ root_view = mRootView;
+ }
+
+ // only update mouse hover set when UI is visible (since we shouldn't send hover events to invisible UI
+ if (gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
+ {
+ // include all ancestors of captor_view as automatically having mouse
+ if (captor_view)
+ {
+ LLView* captor_parent_view = captor_view->getParent();
+ while(captor_parent_view)
+ {
+ mouse_hover_set.insert(captor_parent_view->getHandle());
+ captor_parent_view = captor_parent_view->getParent();
+ }
+ }
+
+ // aggregate visible views that contain mouse cursor in display order
+ LLPopupView::popup_list_t popups = mPopupView->getCurrentPopups();
+
+ for(LLPopupView::popup_list_t::iterator popup_it = popups.begin(); popup_it != popups.end(); ++popup_it)
+ {
+ LLView* popup = popup_it->get();
+ if (popup && popup->calcScreenBoundingRect().pointInRect(x, y))
+ {
+ // iterator over contents of top_ctrl, and throw into mouse_hover_set
+ for (LLView::tree_iterator_t it = popup->beginTreeDFS();
+ it != popup->endTreeDFS();
+ ++it)
+ {
+ LLView* viewp = *it;
+ if (viewp->getVisible()
+ && viewp->calcScreenBoundingRect().pointInRect(x, y))
+ {
+ // we have a view that contains the mouse, add it to the set
+ mouse_hover_set.insert(viewp->getHandle());
+ }
+ else
+ {
+ // skip this view and all of its children
+ it.skipDescendants();
+ }
+ }
+ }
+ }
+
+ // while the top_ctrl contains the mouse cursor, only it and its descendants will receive onMouseEnter events
+ if (top_ctrl && top_ctrl->calcScreenBoundingRect().pointInRect(x, y))
+ {
+ // iterator over contents of top_ctrl, and throw into mouse_hover_set
+ for (LLView::tree_iterator_t it = top_ctrl->beginTreeDFS();
+ it != top_ctrl->endTreeDFS();
+ ++it)
+ {
+ LLView* viewp = *it;
+ if (viewp->getVisible()
+ && viewp->calcScreenBoundingRect().pointInRect(x, y))
+ {
+ // we have a view that contains the mouse, add it to the set
+ mouse_hover_set.insert(viewp->getHandle());
+ }
+ else
+ {
+ // skip this view and all of its children
+ it.skipDescendants();
+ }
+ }
+ }
+ else
+ {
+ // walk UI tree in depth-first order
+ for (LLView::tree_iterator_t it = root_view->beginTreeDFS();
+ it != root_view->endTreeDFS();
+ ++it)
+ {
+ LLView* viewp = *it;
+ // calculating the screen rect involves traversing the parent, so this is less than optimal
+ if (viewp->getVisible()
+ && viewp->calcScreenBoundingRect().pointInRect(x, y))
+ {
+
+ // if this view is mouse opaque, nothing behind it should be in mouse_hover_set
+ if (viewp->getMouseOpaque())
+ {
+ // constrain further iteration to children of this widget
+ it = viewp->beginTreeDFS();
+ }
+
+ // we have a view that contains the mouse, add it to the set
+ mouse_hover_set.insert(viewp->getHandle());
+ }
+ else
+ {
+ // skip this view and all of its children
+ it.skipDescendants();
+ }
+ }
+ }
+ }
+
+ typedef std::vector<LLHandle<LLView> > view_handle_list_t;
+
+ // call onMouseEnter() on all views which contain the mouse cursor but did not before
+ view_handle_list_t mouse_enter_views;
+ std::set_difference(mouse_hover_set.begin(), mouse_hover_set.end(),
+ mMouseHoverViews.begin(), mMouseHoverViews.end(),
+ std::back_inserter(mouse_enter_views));
+ for (view_handle_list_t::iterator it = mouse_enter_views.begin();
+ it != mouse_enter_views.end();
+ ++it)
+ {
+ LLView* viewp = it->get();
+ if (viewp)
+ {
+ LLRect view_screen_rect = viewp->calcScreenRect();
+ viewp->onMouseEnter(x - view_screen_rect.mLeft, y - view_screen_rect.mBottom, mask);
+ }
+ }
+
+ // call onMouseLeave() on all views which no longer contain the mouse cursor
+ view_handle_list_t mouse_leave_views;
+ std::set_difference(mMouseHoverViews.begin(), mMouseHoverViews.end(),
+ mouse_hover_set.begin(), mouse_hover_set.end(),
+ std::back_inserter(mouse_leave_views));
+ for (view_handle_list_t::iterator it = mouse_leave_views.begin();
+ it != mouse_leave_views.end();
+ ++it)
+ {
+ LLView* viewp = it->get();
+ if (viewp)
+ {
+ LLRect view_screen_rect = viewp->calcScreenRect();
+ viewp->onMouseLeave(x - view_screen_rect.mLeft, y - view_screen_rect.mBottom, mask);
+ }
+ }
+
+ // store resulting hover set for next frame
+ swap(mMouseHoverViews, mouse_hover_set);
+
+ // only handle hover events when UI is enabled
+ if (gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
+ {
+
+ if( mouse_captor )
+ {
+ // Pass hover events to object capturing mouse events.
+ S32 local_x;
+ S32 local_y;
+ mouse_captor->screenPointToLocal( x, y, &local_x, &local_y );
+ handled = mouse_captor->handleHover(local_x, local_y, mask);
+ if (LLView::sDebugMouseHandling)
+ {
+ llinfos << "Hover handled by captor " << mouse_captor->getName() << llendl;
+ }
+
+ if( !handled )
+ {
+ lldebugst(LLERR_USER_INPUT) << "hover not handled by mouse captor" << llendl;
+ }
+ }
+ else
+ {
+ if (top_ctrl)
+ {
+ S32 local_x, local_y;
+ top_ctrl->screenPointToLocal( x, y, &local_x, &local_y );
+ handled = top_ctrl->pointInView(local_x, local_y) && top_ctrl->handleHover(local_x, local_y, mask);
+ handled_by_top_ctrl = TRUE;
+ }
+
+ if ( !handled )
+ {
+ // x and y are from last time mouse was in window
+ // mMouseInWindow tracks *actual* mouse location
+ if (mMouseInWindow && mRootView->handleHover(x, y, mask) )
+ {
+ if (LLView::sDebugMouseHandling && LLView::sMouseHandlerMessage != last_handle_msg)
+ {
+ last_handle_msg = LLView::sMouseHandlerMessage;
+ llinfos << "Hover" << LLView::sMouseHandlerMessage << llendl;
+ }
+ handled = TRUE;
+ }
+ else if (LLView::sDebugMouseHandling)
+ {
+ if (last_handle_msg != LLStringUtil::null)
+ {
+ last_handle_msg.clear();
+ llinfos << "Hover not handled by view" << llendl;
+ }
+ }
+ }
+
+ if (!handled)
+ {
+ LLTool *tool = LLToolMgr::getInstance()->getCurrentTool();
+
+ if(mMouseInWindow && tool)
+ {
+ handled = tool->handleHover(x, y, mask);
+ }
+ }
+ }
+
+ // Show a new tool tip (or update one that is already shown)
+ BOOL tool_tip_handled = FALSE;
+ std::string tool_tip_msg;
+ if( handled
+ && !mWindow->isCursorHidden())
+ {
+ LLRect screen_sticky_rect = mRootView->getLocalRect();
+ S32 local_x, local_y;
+
+ if (gSavedSettings.getBOOL("DebugShowXUINames"))
+ {
+ LLToolTip::Params params;
+
+ LLView* tooltip_view = mRootView;
+ LLView::tree_iterator_t end_it = mRootView->endTreeDFS();
+ for (LLView::tree_iterator_t it = mRootView->beginTreeDFS(); it != end_it; ++it)
+ {
+ LLView* viewp = *it;
+ LLRect screen_rect;
+ viewp->localRectToScreen(viewp->getLocalRect(), &screen_rect);
+ if (!(viewp->getVisible()
+ && screen_rect.pointInRect(x, y)))
+ {
+ it.skipDescendants();
+ }
+ // only report xui names for LLUICtrls,
+ // and blacklist the various containers we don't care about
+ else if (dynamic_cast<LLUICtrl*>(viewp)
+ && viewp != gMenuHolder
+ && viewp != gFloaterView
+ && viewp != gConsole)
+ {
+ if (dynamic_cast<LLFloater*>(viewp))
+ {
+ // constrain search to descendants of this (frontmost) floater
+ // by resetting iterator
+ it = viewp->beginTreeDFS();
+ }
+
+ // if we are in a new part of the tree (not a descendent of current tooltip_view)
+ // then push the results for tooltip_view and start with a new potential view
+ // NOTE: this emulates visiting only the leaf nodes that meet our criteria
+ if (!viewp->hasAncestor(tooltip_view))
+ {
+ append_xui_tooltip(tooltip_view, params);
+ screen_sticky_rect.intersectWith(tooltip_view->calcScreenRect());
+ }
+ tooltip_view = viewp;
+ }
+ }
+
+ append_xui_tooltip(tooltip_view, params);
+ screen_sticky_rect.intersectWith(tooltip_view->calcScreenRect());
+
+ params.sticky_rect = screen_sticky_rect;
+ params.max_width = 400;
+
+ LLToolTipMgr::instance().show(params);
+ }
+ // if there is a mouse captor, nothing else gets a tooltip
+ else if (mouse_captor)
+ {
+ mouse_captor->screenPointToLocal(x, y, &local_x, &local_y);
+ tool_tip_handled = mouse_captor->handleToolTip(local_x, local_y, mask);
+ }
+ else
+ {
+ // next is top_ctrl
+ if (!tool_tip_handled && top_ctrl)
+ {
+ top_ctrl->screenPointToLocal(x, y, &local_x, &local_y);
+ tool_tip_handled = top_ctrl->handleToolTip(local_x, local_y, mask );
+ }
+
+ if (!tool_tip_handled)
+ {
+ local_x = x; local_y = y;
+ tool_tip_handled = mRootView->handleToolTip(local_x, local_y, mask );
+ }
+
+ LLTool* current_tool = LLToolMgr::getInstance()->getCurrentTool();
+ if (!tool_tip_handled && current_tool)
+ {
+ current_tool->screenPointToLocal(x, y, &local_x, &local_y);
+ tool_tip_handled = current_tool->handleToolTip(local_x, local_y, mask );
+ }
+ }
+ }
+ }
+ else
+ { // just have tools handle hover when UI is turned off
+ LLTool *tool = LLToolMgr::getInstance()->getCurrentTool();
+
+ if(mMouseInWindow && tool)
+ {
+ handled = tool->handleHover(x, y, mask);
+ }
+ }
+
+ updateLayout();
+
+ mLastMousePoint = mCurrentMousePoint;
+
+ // cleanup unused selections when no modal dialogs are open
+ if (LLModalDialog::activeCount() == 0)
+ {
+ LLViewerParcelMgr::getInstance()->deselectUnused();
+ }
+
+ if (LLModalDialog::activeCount() == 0)
+ {
+ LLSelectMgr::getInstance()->deselectUnused();
+ }
+}
+
+
+void LLViewerWindow::updateLayout()
+{
+ LLTool* tool = LLToolMgr::getInstance()->getCurrentTool();
+ if (gFloaterTools != NULL
+ && tool != NULL
+ && tool != gToolNull
+ && tool != LLToolCompInspect::getInstance()
+ && tool != LLToolDragAndDrop::getInstance()
+ && !gSavedSettings.getBOOL("FreezeTime"))
+ {
+ // Suppress the toolbox view if our source tool was the pie tool,
+ // and we've overridden to something else.
+ bool suppress_toolbox =
+ (LLToolMgr::getInstance()->getBaseTool() == LLToolPie::getInstance()) &&
+ (LLToolMgr::getInstance()->getCurrentTool() != LLToolPie::getInstance());
+
+ LLMouseHandler *captor = gFocusMgr.getMouseCapture();
+ // With the null, inspect, or drag and drop tool, don't muck
+ // with visibility.
+
+ if (gFloaterTools->isMinimized()
+ || (tool != LLToolPie::getInstance() // not default tool
+ && tool != LLToolCompGun::getInstance() // not coming out of mouselook
+ && !suppress_toolbox // not override in third person
+ && LLToolMgr::getInstance()->getCurrentToolset() != gFaceEditToolset // not special mode
+ && LLToolMgr::getInstance()->getCurrentToolset() != gMouselookToolset
+ && (!captor || dynamic_cast<LLView*>(captor) != NULL))) // not dragging
+ {
+ // Force floater tools to be visible (unless minimized)
+ if (!gFloaterTools->getVisible())
+ {
+ gFloaterTools->openFloater();
+ }
+ // Update the location of the blue box tool popup
+ LLCoordGL select_center_screen;
+ gFloaterTools->updatePopup( select_center_screen, gKeyboard->currentMask(TRUE) );
+ }
+ else
+ {
+ gFloaterTools->setVisible(FALSE);
+ }
+ //gMenuBarView->setItemVisible("BuildTools", gFloaterTools->getVisible());
+ }
+
+ // Always update console
+ if(gConsole)
+ {
+ LLRect console_rect = getChatConsoleRect();
+ gConsole->reshape(console_rect.getWidth(), console_rect.getHeight());
+ gConsole->setRect(console_rect);
+ }
+}
+
+void LLViewerWindow::updateMouseDelta()
+{
+ S32 dx = lltrunc((F32) (mCurrentMousePoint.mX - mLastMousePoint.mX) * LLUI::sGLScaleFactor.mV[VX]);
+ S32 dy = lltrunc((F32) (mCurrentMousePoint.mY - mLastMousePoint.mY) * LLUI::sGLScaleFactor.mV[VY]);
+
+ //RN: fix for asynchronous notification of mouse leaving window not working
+ LLCoordWindow mouse_pos;
+ mWindow->getCursorPosition(&mouse_pos);
+ if (mouse_pos.mX < 0 ||
+ mouse_pos.mY < 0 ||
+ mouse_pos.mX > mWindowRectRaw.getWidth() ||
+ mouse_pos.mY > mWindowRectRaw.getHeight())
+ {
+ mMouseInWindow = FALSE;
+ }
+ else
+ {
+ mMouseInWindow = TRUE;
+ }
+
+ LLVector2 mouse_vel;
+
+ if (gSavedSettings.getBOOL("MouseSmooth"))
+ {
+ static F32 fdx = 0.f;
+ static F32 fdy = 0.f;
+
+ F32 amount = 16.f;
+ fdx = fdx + ((F32) dx - fdx) * llmin(gFrameIntervalSeconds*amount,1.f);
+ fdy = fdy + ((F32) dy - fdy) * llmin(gFrameIntervalSeconds*amount,1.f);
+
+ mCurrentMouseDelta.set(llround(fdx), llround(fdy));
+ mouse_vel.setVec(fdx,fdy);
+ }
+ else
+ {
+ mCurrentMouseDelta.set(dx, dy);
+ mouse_vel.setVec((F32) dx, (F32) dy);
+ }
+
+ mMouseVelocityStat.addValue(mouse_vel.magVec());
+}
+
+void LLViewerWindow::updateKeyboardFocus()
+{
+ if (!gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
+ {
+ gFocusMgr.setKeyboardFocus(NULL);
+ }
+
+ // clean up current focus
+ LLUICtrl* cur_focus = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
+ if (cur_focus)
+ {
+ if (!cur_focus->isInVisibleChain() || !cur_focus->isInEnabledChain())
+ {
+ // don't release focus, just reassign so that if being given
+ // to a sibling won't call onFocusLost on all the ancestors
+ // gFocusMgr.releaseFocusIfNeeded(cur_focus);
+
+ LLUICtrl* parent = cur_focus->getParentUICtrl();
+ const LLUICtrl* focus_root = cur_focus->findRootMostFocusRoot();
+ bool new_focus_found = false;
+ while(parent)
+ {
+ if (parent->isCtrl()
+ && (parent->hasTabStop() || parent == focus_root)
+ && !parent->getIsChrome()
+ && parent->isInVisibleChain()
+ && parent->isInEnabledChain())
+ {
+ if (!parent->focusFirstItem())
+ {
+ parent->setFocus(TRUE);
+ }
+ new_focus_found = true;
+ break;
+ }
+ parent = parent->getParentUICtrl();
+ }
+
+ // if we didn't find a better place to put focus, just release it
+ // hasFocus() will return true if and only if we didn't touch focus since we
+ // are only moving focus higher in the hierarchy
+ if (!new_focus_found)
+ {
+ cur_focus->setFocus(FALSE);
+ }
+ }
+ else if (cur_focus->isFocusRoot())
+ {
+ // focus roots keep trying to delegate focus to their first valid descendant
+ // this assumes that focus roots are not valid focus holders on their own
+ cur_focus->focusFirstItem();
+ }
+ }
+
+ // last ditch force of edit menu to selection manager
+ if (LLEditMenuHandler::gEditMenuHandler == NULL && LLSelectMgr::getInstance()->getSelection()->getObjectCount())
+ {
+ LLEditMenuHandler::gEditMenuHandler = LLSelectMgr::getInstance();
+ }
+
+ if (gFloaterView->getCycleMode())
+ {
+ // sync all floaters with their focus state
+ gFloaterView->highlightFocusedFloater();
+ gSnapshotFloaterView->highlightFocusedFloater();
+ if ((gKeyboard->currentMask(TRUE) & MASK_CONTROL) == 0)
+ {
+ // control key no longer held down, finish cycle mode
+ gFloaterView->setCycleMode(FALSE);
+
+ gFloaterView->syncFloaterTabOrder();
+ }
+ else
+ {
+ // user holding down CTRL, don't update tab order of floaters
+ }
+ }
+ else
+ {
+ // update focused floater
+ gFloaterView->highlightFocusedFloater();
+ gSnapshotFloaterView->highlightFocusedFloater();
+ // make sure floater visible order is in sync with tab order
+ gFloaterView->syncFloaterTabOrder();
+ }
+
+ if(LLSideTray::instanceCreated())//just getInstance will create sidetray. we don't want this
+ LLSideTray::getInstance()->highlightFocused();
+}
+
+static LLFastTimer::DeclareTimer FTM_UPDATE_WORLD_VIEW("Update World View");
+void LLViewerWindow::updateWorldViewRect(bool use_full_window)
+{
+ LLFastTimer ft(FTM_UPDATE_WORLD_VIEW);
+
+ // start off using whole window to render world
+ LLRect new_world_rect = mWindowRectRaw;
+
+ if (use_full_window == false && mWorldViewPlaceholder.get())
+ {
+ new_world_rect = mWorldViewPlaceholder.get()->calcScreenRect();
+ // clamp to at least a 1x1 rect so we don't try to allocate zero width gl buffers
+ new_world_rect.mTop = llmax(new_world_rect.mTop, new_world_rect.mBottom + 1);
+ new_world_rect.mRight = llmax(new_world_rect.mRight, new_world_rect.mLeft + 1);
+
+ new_world_rect.mLeft = llround((F32)new_world_rect.mLeft * mDisplayScale.mV[VX]);
+ new_world_rect.mRight = llround((F32)new_world_rect.mRight * mDisplayScale.mV[VX]);
+ new_world_rect.mBottom = llround((F32)new_world_rect.mBottom * mDisplayScale.mV[VY]);
+ new_world_rect.mTop = llround((F32)new_world_rect.mTop * mDisplayScale.mV[VY]);
+ }
+
+ if (gSavedSettings.getBOOL("SidebarCameraMovement") == FALSE)
+ {
+ // use right edge of window, ignoring sidebar
+ new_world_rect.mRight = mWindowRectRaw.mRight;
+ }
+
+ if (mWorldViewRectRaw != new_world_rect)
+ {
+ mWorldViewRectRaw = new_world_rect;
+ gResizeScreenTexture = TRUE;
+ LLViewerCamera::getInstance()->setViewHeightInPixels( mWorldViewRectRaw.getHeight() );
+ LLViewerCamera::getInstance()->setAspect( getWorldViewAspectRatio() );
+
+ LLRect old_world_rect_scaled = mWorldViewRectScaled;
+ mWorldViewRectScaled = calcScaledRect(mWorldViewRectRaw, mDisplayScale);
+
+ // sending a signal with a new WorldView rect
+ mOnWorldViewRectUpdated(old_world_rect_scaled, mWorldViewRectScaled);
+ }
+}
+
+void LLViewerWindow::saveLastMouse(const LLCoordGL &point)
+{
+ // Store last mouse location.
+ // If mouse leaves window, pretend last point was on edge of window
+ if (point.mX < 0)
+ {
+ mCurrentMousePoint.mX = 0;
+ }
+ else if (point.mX > getWindowWidthScaled())
+ {
+ mCurrentMousePoint.mX = getWindowWidthScaled();
+ }
+ else
+ {
+ mCurrentMousePoint.mX = point.mX;
+ }
+
+ if (point.mY < 0)
+ {
+ mCurrentMousePoint.mY = 0;
+ }
+ else if (point.mY > getWindowHeightScaled() )
+ {
+ mCurrentMousePoint.mY = getWindowHeightScaled();
+ }
+ else
+ {
+ mCurrentMousePoint.mY = point.mY;
+ }
+}
+
+
+// Draws the selection outlines for the currently selected objects
+// Must be called after displayObjects is called, which sets the mGLName parameter
+// NOTE: This function gets called 3 times:
+// render_ui_3d: FALSE, FALSE, TRUE
+// render_hud_elements: FALSE, FALSE, FALSE
+void LLViewerWindow::renderSelections( BOOL for_gl_pick, BOOL pick_parcel_walls, BOOL for_hud )
+{
+ LLObjectSelectionHandle selection = LLSelectMgr::getInstance()->getSelection();
+
+ if (!for_hud && !for_gl_pick)
+ {
+ // Call this once and only once
+ LLSelectMgr::getInstance()->updateSilhouettes();
+ }
+
+ // Draw fence around land selections
+ if (for_gl_pick)
+ {
+ if (pick_parcel_walls)
+ {
+ LLViewerParcelMgr::getInstance()->renderParcelCollision();
+ }
+ }
+ else if (( for_hud && selection->getSelectType() == SELECT_TYPE_HUD) ||
+ (!for_hud && selection->getSelectType() != SELECT_TYPE_HUD))
+ {
+ LLSelectMgr::getInstance()->renderSilhouettes(for_hud);
+
+ stop_glerror();
+
+ // setup HUD render
+ if (selection->getSelectType() == SELECT_TYPE_HUD && LLSelectMgr::getInstance()->getSelection()->getObjectCount())
+ {
+ LLBBox hud_bbox = gAgentAvatarp->getHUDBBox();
+
+ // set up transform to encompass bounding box of HUD
+ glMatrixMode(GL_PROJECTION);
+ glPushMatrix();
+ glLoadIdentity();
+ F32 depth = llmax(1.f, hud_bbox.getExtentLocal().mV[VX] * 1.1f);
+ glOrtho(-0.5f * LLViewerCamera::getInstance()->getAspect(), 0.5f * LLViewerCamera::getInstance()->getAspect(), -0.5f, 0.5f, 0.f, depth);
+
+ glMatrixMode(GL_MODELVIEW);
+ glPushMatrix();
+ glLoadIdentity();
+ glLoadMatrixf(OGL_TO_CFR_ROTATION); // Load Cory's favorite reference frame
+ glTranslatef(-hud_bbox.getCenterLocal().mV[VX] + (depth *0.5f), 0.f, 0.f);
+ }
+
+ // Render light for editing
+ if (LLSelectMgr::sRenderLightRadius && LLToolMgr::getInstance()->inEdit())
+ {
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ LLGLEnable gls_blend(GL_BLEND);
+ LLGLEnable gls_cull(GL_CULL_FACE);
+ LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE);
+ glMatrixMode(GL_MODELVIEW);
+ glPushMatrix();
+ if (selection->getSelectType() == SELECT_TYPE_HUD)
+ {
+ F32 zoom = gAgentCamera.mHUDCurZoom;
+ glScalef(zoom, zoom, zoom);
+ }
+
+ struct f : public LLSelectedObjectFunctor
+ {
+ virtual bool apply(LLViewerObject* object)
+ {
+ LLDrawable* drawable = object->mDrawable;
+ if (drawable && drawable->isLight())
+ {
+ LLVOVolume* vovolume = drawable->getVOVolume();
+ glPushMatrix();
+
+ LLVector3 center = drawable->getPositionAgent();
+ glTranslatef(center[0], center[1], center[2]);
+ F32 scale = vovolume->getLightRadius();
+ glScalef(scale, scale, scale);
+
+ LLColor4 color(vovolume->getLightColor(), .5f);
+ glColor4fv(color.mV);
+
+ F32 pixel_area = 100000.f;
+ // Render Outside
+ gSphere.render(pixel_area);
+
+ // Render Inside
+ glCullFace(GL_FRONT);
+ gSphere.render(pixel_area);
+ glCullFace(GL_BACK);
+
+ glPopMatrix();
+ }
+ return true;
+ }
+ } func;
+ LLSelectMgr::getInstance()->getSelection()->applyToObjects(&func);
+
+ glPopMatrix();
+ }
+
+ // NOTE: The average position for the axis arrows of the selected objects should
+ // not be recalculated at this time. If they are, then group rotations will break.
+
+ // Draw arrows at average center of all selected objects
+ LLTool* tool = LLToolMgr::getInstance()->getCurrentTool();
+ if (tool)
+ {
+ if(tool->isAlwaysRendered())
+ {
+ tool->render();
+ }
+ else
+ {
+ if( !LLSelectMgr::getInstance()->getSelection()->isEmpty() )
+ {
+ BOOL moveable_object_selected = FALSE;
+ BOOL all_selected_objects_move = TRUE;
+ BOOL all_selected_objects_modify = TRUE;
+ BOOL selecting_linked_set = !gSavedSettings.getBOOL("EditLinkedParts");
+
+ for (LLObjectSelection::iterator iter = LLSelectMgr::getInstance()->getSelection()->begin();
+ iter != LLSelectMgr::getInstance()->getSelection()->end(); iter++)
+ {
+ LLSelectNode* nodep = *iter;
+ LLViewerObject* object = nodep->getObject();
+ BOOL this_object_movable = FALSE;
+ if (object->permMove() && (object->permModify() || selecting_linked_set))
+ {
+ moveable_object_selected = TRUE;
+ this_object_movable = TRUE;
+ }
+ all_selected_objects_move = all_selected_objects_move && this_object_movable;
+ all_selected_objects_modify = all_selected_objects_modify && object->permModify();
+ }
+
+ BOOL draw_handles = TRUE;
+
+ if (tool == LLToolCompTranslate::getInstance() && (!moveable_object_selected || !all_selected_objects_move))
+ {
+ draw_handles = FALSE;
+ }
+
+ if (tool == LLToolCompRotate::getInstance() && (!moveable_object_selected || !all_selected_objects_move))
+ {
+ draw_handles = FALSE;
+ }
+
+ if ( !all_selected_objects_modify && tool == LLToolCompScale::getInstance() )
+ {
+ draw_handles = FALSE;
+ }
+
+ if( draw_handles )
+ {
+ tool->render();
+ }
+ }
+ }
+ if (selection->getSelectType() == SELECT_TYPE_HUD && selection->getObjectCount())
+ {
+ glMatrixMode(GL_PROJECTION);
+ glPopMatrix();
+
+ glMatrixMode(GL_MODELVIEW);
+ glPopMatrix();
+ stop_glerror();
+ }
+ }
+ }
+}
+
+// Return a point near the clicked object representative of the place the object was clicked.
+LLVector3d LLViewerWindow::clickPointInWorldGlobal(S32 x, S32 y_from_bot, LLViewerObject* clicked_object) const
+{
+ // create a normalized vector pointing from the camera center into the
+ // world at the location of the mouse click
+ LLVector3 mouse_direction_global = mouseDirectionGlobal( x, y_from_bot );
+
+ LLVector3d relative_object = clicked_object->getPositionGlobal() - gAgentCamera.getCameraPositionGlobal();
+
+ // make mouse vector as long as object vector, so it touchs a point near
+ // where the user clicked on the object
+ mouse_direction_global *= (F32) relative_object.magVec();
+
+ LLVector3d new_pos;
+ new_pos.setVec(mouse_direction_global);
+ // transform mouse vector back to world coords
+ new_pos += gAgentCamera.getCameraPositionGlobal();
+
+ return new_pos;
+}
+
+
+BOOL LLViewerWindow::clickPointOnSurfaceGlobal(const S32 x, const S32 y, LLViewerObject *objectp, LLVector3d &point_global) const
+{
+ BOOL intersect = FALSE;
+
+// U8 shape = objectp->mPrimitiveCode & LL_PCODE_BASE_MASK;
+ if (!intersect)
+ {
+ point_global = clickPointInWorldGlobal(x, y, objectp);
+ llinfos << "approx intersection at " << (objectp->getPositionGlobal() - point_global) << llendl;
+ }
+ else
+ {
+ llinfos << "good intersection at " << (objectp->getPositionGlobal() - point_global) << llendl;
+ }
+
+ return intersect;
+}
+
+void LLViewerWindow::pickAsync(S32 x, S32 y_from_bot, MASK mask, void (*callback)(const LLPickInfo& info), BOOL pick_transparent)
+{
+ if (gNoRender)
+ {
+ return;
+ }
+
+ BOOL in_build_mode = LLFloaterReg::instanceVisible("build");
+ if (in_build_mode || LLDrawPoolAlpha::sShowDebugAlpha)
+ {
+ // build mode allows interaction with all transparent objects
+ // "Show Debug Alpha" means no object actually transparent
+ pick_transparent = TRUE;
+ }
+
+ LLPickInfo pick_info(LLCoordGL(x, y_from_bot), mask, pick_transparent, TRUE, callback);
+ schedulePick(pick_info);
+}
+
+void LLViewerWindow::schedulePick(LLPickInfo& pick_info)
+{
+ if (mPicks.size() >= 1024 || mWindow->getMinimized())
+ { //something went wrong, picks are being scheduled but not processed
+
+ if (pick_info.mPickCallback)
+ {
+ pick_info.mPickCallback(pick_info);
+ }
+
+ return;
+ }
+ mPicks.push_back(pick_info);
+
+ // delay further event processing until we receive results of pick
+ // only do this for async picks so that handleMouseUp won't be called
+ // until the pick triggered in handleMouseDown has been processed, for example
+ mWindow->delayInputProcessing();
+}
+
+
+void LLViewerWindow::performPick()
+{
+ if (gNoRender)
+ {
+ return;
+ }
+
+ if (!mPicks.empty())
+ {
+ std::vector<LLPickInfo>::iterator pick_it;
+ for (pick_it = mPicks.begin(); pick_it != mPicks.end(); ++pick_it)
+ {
+ pick_it->fetchResults();
+ }
+
+ mLastPick = mPicks.back();
+ mPicks.clear();
+ }
+}
+
+void LLViewerWindow::returnEmptyPicks()
+{
+ std::vector<LLPickInfo>::iterator pick_it;
+ for (pick_it = mPicks.begin(); pick_it != mPicks.end(); ++pick_it)
+ {
+ mLastPick = *pick_it;
+ // just trigger callback with empty results
+ if (pick_it->mPickCallback)
+ {
+ pick_it->mPickCallback(*pick_it);
+ }
+ }
+ mPicks.clear();
+}
+
+// Performs the GL object/land pick.
+LLPickInfo LLViewerWindow::pickImmediate(S32 x, S32 y_from_bot, BOOL pick_transparent)
+{
+ if (gNoRender)
+ {
+ return LLPickInfo();
+ }
+
+ BOOL in_build_mode = LLFloaterReg::instanceVisible("build");
+ if (in_build_mode || LLDrawPoolAlpha::sShowDebugAlpha)
+ {
+ // build mode allows interaction with all transparent objects
+ // "Show Debug Alpha" means no object actually transparent
+ pick_transparent = TRUE;
+ }
+
+ // shortcut queueing in mPicks and just update mLastPick in place
+ mLastPick = LLPickInfo(LLCoordGL(x, y_from_bot), gKeyboard->currentMask(TRUE), pick_transparent, TRUE, NULL);
+ mLastPick.fetchResults();
+
+ return mLastPick;
+}
+
+LLHUDIcon* LLViewerWindow::cursorIntersectIcon(S32 mouse_x, S32 mouse_y, F32 depth,
+ LLVector3* intersection)
+{
+ S32 x = mouse_x;
+ S32 y = mouse_y;
+
+ if ((mouse_x == -1) && (mouse_y == -1)) // use current mouse position
+ {
+ x = getCurrentMouseX();
+ y = getCurrentMouseY();
+ }
+
+ // world coordinates of mouse
+ LLVector3 mouse_direction_global = mouseDirectionGlobal(x,y);
+ LLVector3 mouse_point_global = LLViewerCamera::getInstance()->getOrigin();
+ LLVector3 mouse_world_start = mouse_point_global;
+ LLVector3 mouse_world_end = mouse_point_global + mouse_direction_global * depth;
+
+ return LLHUDIcon::lineSegmentIntersectAll(mouse_world_start, mouse_world_end, intersection);
+
+
+}
+
+LLViewerObject* LLViewerWindow::cursorIntersect(S32 mouse_x, S32 mouse_y, F32 depth,
+ LLViewerObject *this_object,
+ S32 this_face,
+ BOOL pick_transparent,
+ S32* face_hit,
+ LLVector3 *intersection,
+ LLVector2 *uv,
+ LLVector3 *normal,
+ LLVector3 *binormal,
+ LLVector3* start,
+ LLVector3* end)
+{
+ S32 x = mouse_x;
+ S32 y = mouse_y;
+
+ if ((mouse_x == -1) && (mouse_y == -1)) // use current mouse position
+ {
+ x = getCurrentMouseX();
+ y = getCurrentMouseY();
+ }
+
+ // HUD coordinates of mouse
+ LLVector3 mouse_point_hud = mousePointHUD(x, y);
+ LLVector3 mouse_hud_start = mouse_point_hud - LLVector3(depth, 0, 0);
+ LLVector3 mouse_hud_end = mouse_point_hud + LLVector3(depth, 0, 0);
+
+ // world coordinates of mouse
+ LLVector3 mouse_direction_global = mouseDirectionGlobal(x,y);
+ LLVector3 mouse_point_global = LLViewerCamera::getInstance()->getOrigin();
+
+ //get near clip plane
+ LLVector3 n = LLViewerCamera::getInstance()->getAtAxis();
+ LLVector3 p = mouse_point_global + n * LLViewerCamera::getInstance()->getNear();
+
+ //project mouse point onto plane
+ LLVector3 pos;
+ line_plane(mouse_point_global, mouse_direction_global, p, n, pos);
+ mouse_point_global = pos;
+
+ LLVector3 mouse_world_start = mouse_point_global;
+ LLVector3 mouse_world_end = mouse_point_global + mouse_direction_global * depth;
+
+ //gDebugRaycastIntersection = mouse_world_end;
+
+ if (start)
+ {
+ *start = mouse_world_start;
+ }
+
+ if (end)
+ {
+ *end = mouse_world_end;
+ }
+
+ LLViewerObject* found = NULL;
+
+ if (this_object) // check only this object
+ {
+ if (this_object->isHUDAttachment()) // is a HUD object?
+ {
+ if (this_object->lineSegmentIntersect(mouse_hud_start, mouse_hud_end, this_face, pick_transparent,
+ face_hit, intersection, uv, normal, binormal))
+ {
+ found = this_object;
+ }
+ }
+ else // is a world object
+ {
+ if (this_object->lineSegmentIntersect(mouse_world_start, mouse_world_end, this_face, pick_transparent,
+ face_hit, intersection, uv, normal, binormal))
+ {
+ found = this_object;
+ }
+ }
+ }
+ else // check ALL objects
+ {
+ found = gPipeline.lineSegmentIntersectInHUD(mouse_hud_start, mouse_hud_end, pick_transparent,
+ face_hit, intersection, uv, normal, binormal);
+
+ if (!found) // if not found in HUD, look in world:
+ {
+ found = gPipeline.lineSegmentIntersectInWorld(mouse_world_start, mouse_world_end, pick_transparent,
+ face_hit, intersection, uv, normal, binormal);
+ if (found && !pick_transparent)
+ {
+ gDebugRaycastIntersection = *intersection;
+ }
+ }
+ }
+
+ return found;
+}
+
+// Returns unit vector relative to camera
+// indicating direction of point on screen x,y
+LLVector3 LLViewerWindow::mouseDirectionGlobal(const S32 x, const S32 y) const
+{
+ // find vertical field of view
+ F32 fov = LLViewerCamera::getInstance()->getView();
+
+ // find world view center in scaled ui coordinates
+ F32 center_x = getWorldViewRectScaled().getCenterX();
+ F32 center_y = getWorldViewRectScaled().getCenterY();
+
+ // calculate pixel distance to screen
+ F32 distance = ((F32)getWorldViewHeightScaled() * 0.5f) / (tan(fov / 2.f));
+
+ // calculate click point relative to middle of screen
+ F32 click_x = x - center_x;
+ F32 click_y = y - center_y;
+
+ // compute mouse vector
+ LLVector3 mouse_vector = distance * LLViewerCamera::getInstance()->getAtAxis()
+ - click_x * LLViewerCamera::getInstance()->getLeftAxis()
+ + click_y * LLViewerCamera::getInstance()->getUpAxis();
+
+ mouse_vector.normVec();
+
+ return mouse_vector;
+}
+
+LLVector3 LLViewerWindow::mousePointHUD(const S32 x, const S32 y) const
+{
+ // find screen resolution
+ S32 height = getWorldViewHeightScaled();
+
+ // find world view center
+ F32 center_x = getWorldViewRectScaled().getCenterX();
+ F32 center_y = getWorldViewRectScaled().getCenterY();
+
+ // remap with uniform scale (1/height) so that top is -0.5, bottom is +0.5
+ F32 hud_x = -((F32)x - center_x) / height;
+ F32 hud_y = ((F32)y - center_y) / height;
+
+ return LLVector3(0.f, hud_x/gAgentCamera.mHUDCurZoom, hud_y/gAgentCamera.mHUDCurZoom);
+}
+
+// Returns unit vector relative to camera in camera space
+// indicating direction of point on screen x,y
+LLVector3 LLViewerWindow::mouseDirectionCamera(const S32 x, const S32 y) const
+{
+ // find vertical field of view
+ F32 fov_height = LLViewerCamera::getInstance()->getView();
+ F32 fov_width = fov_height * LLViewerCamera::getInstance()->getAspect();
+
+ // find screen resolution
+ S32 height = getWorldViewHeightScaled();
+ S32 width = getWorldViewWidthScaled();
+
+ // find world view center
+ F32 center_x = getWorldViewRectScaled().getCenterX();
+ F32 center_y = getWorldViewRectScaled().getCenterY();
+
+ // calculate click point relative to middle of screen
+ F32 click_x = (((F32)x - center_x) / (F32)width) * fov_width * -1.f;
+ F32 click_y = (((F32)y - center_y) / (F32)height) * fov_height;
+
+ // compute mouse vector
+ LLVector3 mouse_vector = LLVector3(0.f, 0.f, -1.f);
+ LLQuaternion mouse_rotate;
+ mouse_rotate.setQuat(click_y, click_x, 0.f);
+
+ mouse_vector = mouse_vector * mouse_rotate;
+ // project to z = -1 plane;
+ mouse_vector = mouse_vector * (-1.f / mouse_vector.mV[VZ]);
+
+ return mouse_vector;
+}
+
+
+
+BOOL LLViewerWindow::mousePointOnPlaneGlobal(LLVector3d& point, const S32 x, const S32 y,
+ const LLVector3d &plane_point_global,
+ const LLVector3 &plane_normal_global)
+{
+ LLVector3d mouse_direction_global_d;
+
+ mouse_direction_global_d.setVec(mouseDirectionGlobal(x,y));
+ LLVector3d plane_normal_global_d;
+ plane_normal_global_d.setVec(plane_normal_global);
+ F64 plane_mouse_dot = (plane_normal_global_d * mouse_direction_global_d);
+ LLVector3d plane_origin_camera_rel = plane_point_global - gAgentCamera.getCameraPositionGlobal();
+ F64 mouse_look_at_scale = (plane_normal_global_d * plane_origin_camera_rel)
+ / plane_mouse_dot;
+ if (llabs(plane_mouse_dot) < 0.00001)
+ {
+ // if mouse is parallel to plane, return closest point on line through plane origin
+ // that is parallel to camera plane by scaling mouse direction vector
+ // by distance to plane origin, modulated by deviation of mouse direction from plane origin
+ LLVector3d plane_origin_dir = plane_origin_camera_rel;
+ plane_origin_dir.normVec();
+
+ mouse_look_at_scale = plane_origin_camera_rel.magVec() / (plane_origin_dir * mouse_direction_global_d);
+ }
+
+ point = gAgentCamera.getCameraPositionGlobal() + mouse_look_at_scale * mouse_direction_global_d;
+
+ return mouse_look_at_scale > 0.0;
+}
+
+
+// Returns global position
+BOOL LLViewerWindow::mousePointOnLandGlobal(const S32 x, const S32 y, LLVector3d *land_position_global)
+{
+ LLVector3 mouse_direction_global = mouseDirectionGlobal(x,y);
+ F32 mouse_dir_scale;
+ BOOL hit_land = FALSE;
+ LLViewerRegion *regionp;
+ F32 land_z;
+ const F32 FIRST_PASS_STEP = 1.0f; // meters
+ const F32 SECOND_PASS_STEP = 0.1f; // meters
+ LLVector3d camera_pos_global;
+
+ camera_pos_global = gAgentCamera.getCameraPositionGlobal();
+ LLVector3d probe_point_global;
+ LLVector3 probe_point_region;
+
+ // walk forwards to find the point
+ for (mouse_dir_scale = FIRST_PASS_STEP; mouse_dir_scale < gAgentCamera.mDrawDistance; mouse_dir_scale += FIRST_PASS_STEP)
+ {
+ LLVector3d mouse_direction_global_d;
+ mouse_direction_global_d.setVec(mouse_direction_global * mouse_dir_scale);
+ probe_point_global = camera_pos_global + mouse_direction_global_d;
+
+ regionp = LLWorld::getInstance()->resolveRegionGlobal(probe_point_region, probe_point_global);
+
+ if (!regionp)
+ {
+ // ...we're outside the world somehow
+ continue;
+ }
+
+ S32 i = (S32) (probe_point_region.mV[VX]/regionp->getLand().getMetersPerGrid());
+ S32 j = (S32) (probe_point_region.mV[VY]/regionp->getLand().getMetersPerGrid());
+ S32 grids_per_edge = (S32) regionp->getLand().mGridsPerEdge;
+ if ((i >= grids_per_edge) || (j >= grids_per_edge))
+ {
+ //llinfos << "LLViewerWindow::mousePointOnLand probe_point is out of region" << llendl;
+ continue;
+ }
+
+ land_z = regionp->getLand().resolveHeightRegion(probe_point_region);
+
+ //llinfos << "mousePointOnLand initial z " << land_z << llendl;
+
+ if (probe_point_region.mV[VZ] < land_z)
+ {
+ // ...just went under land
+
+ // cout << "under land at " << probe_point << " scale " << mouse_vec_scale << endl;
+
+ hit_land = TRUE;
+ break;
+ }
+ }
+
+
+ if (hit_land)
+ {
+ // Don't go more than one step beyond where we stopped above.
+ // This can't just be "mouse_vec_scale" because floating point error
+ // will stop the loop before the last increment.... X - 1.0 + 0.1 + 0.1 + ... + 0.1 != X
+ F32 stop_mouse_dir_scale = mouse_dir_scale + FIRST_PASS_STEP;
+
+ // take a step backwards, then walk forwards again to refine position
+ for ( mouse_dir_scale -= FIRST_PASS_STEP; mouse_dir_scale <= stop_mouse_dir_scale; mouse_dir_scale += SECOND_PASS_STEP)
+ {
+ LLVector3d mouse_direction_global_d;
+ mouse_direction_global_d.setVec(mouse_direction_global * mouse_dir_scale);
+ probe_point_global = camera_pos_global + mouse_direction_global_d;
+
+ regionp = LLWorld::getInstance()->resolveRegionGlobal(probe_point_region, probe_point_global);
+
+ if (!regionp)
+ {
+ // ...we're outside the world somehow
+ continue;
+ }
+
+ /*
+ i = (S32) (local_probe_point.mV[VX]/regionp->getLand().getMetersPerGrid());
+ j = (S32) (local_probe_point.mV[VY]/regionp->getLand().getMetersPerGrid());
+ if ((i >= regionp->getLand().mGridsPerEdge) || (j >= regionp->getLand().mGridsPerEdge))
+ {
+ // llinfos << "LLViewerWindow::mousePointOnLand probe_point is out of region" << llendl;
+ continue;
+ }
+ land_z = regionp->getLand().mSurfaceZ[ i + j * (regionp->getLand().mGridsPerEdge) ];
+ */
+
+ land_z = regionp->getLand().resolveHeightRegion(probe_point_region);
+
+ //llinfos << "mousePointOnLand refine z " << land_z << llendl;
+
+ if (probe_point_region.mV[VZ] < land_z)
+ {
+ // ...just went under land again
+
+ *land_position_global = probe_point_global;
+ return TRUE;
+ }
+ }
+ }
+
+ return FALSE;
+}
+
+// Saves an image to the harddrive as "SnapshotX" where X >= 1.
+BOOL LLViewerWindow::saveImageNumbered(LLImageFormatted *image)
+{
+ if (!image)
+ {
+ return FALSE;
+ }
+
+ LLFilePicker::ESaveFilter pick_type;
+ std::string extension("." + image->getExtension());
+ if (extension == ".j2c")
+ pick_type = LLFilePicker::FFSAVE_J2C;
+ else if (extension == ".bmp")
+ pick_type = LLFilePicker::FFSAVE_BMP;
+ else if (extension == ".jpg")
+ pick_type = LLFilePicker::FFSAVE_JPEG;
+ else if (extension == ".png")
+ pick_type = LLFilePicker::FFSAVE_PNG;
+ else if (extension == ".tga")
+ pick_type = LLFilePicker::FFSAVE_TGA;
+ else
+ pick_type = LLFilePicker::FFSAVE_ALL; // ???
+
+ // Get a base file location if needed.
+ if ( ! isSnapshotLocSet())
+ {
+ std::string proposed_name( sSnapshotBaseName );
+
+ // getSaveFile will append an appropriate extension to the proposed name, based on the ESaveFilter constant passed in.
+
+ // pick a directory in which to save
+ LLFilePicker& picker = LLFilePicker::instance();
+ if (!picker.getSaveFile(pick_type, proposed_name))
+ {
+ // Clicked cancel
+ return FALSE;
+ }
+
+ // Copy the directory + file name
+ std::string filepath = picker.getFirstFile();
+
+ LLViewerWindow::sSnapshotBaseName = gDirUtilp->getBaseFileName(filepath, true);
+ LLViewerWindow::sSnapshotDir = gDirUtilp->getDirName(filepath);
+ }
+
+ // Look for an unused file name
+ std::string filepath;
+ S32 i = 1;
+ S32 err = 0;
+
+ do
+ {
+ filepath = sSnapshotDir;
+ filepath += gDirUtilp->getDirDelimiter();
+ filepath += sSnapshotBaseName;
+ filepath += llformat("_%.3d",i);
+ filepath += extension;
+
+ llstat stat_info;
+ err = LLFile::stat( filepath, &stat_info );
+ i++;
+ }
+ while( -1 != err ); // search until the file is not found (i.e., stat() gives an error).
+
+ return image->save(filepath);
+}
+
+void LLViewerWindow::resetSnapshotLoc()
+{
+ sSnapshotDir.clear();
+}
+
+static S32 BORDERHEIGHT = 0;
+static S32 BORDERWIDTH = 0;
+
+// static
+void LLViewerWindow::movieSize(S32 new_width, S32 new_height)
+{
+ LLCoordScreen size;
+ gViewerWindow->mWindow->getSize(&size);
+ if ( (size.mX != new_width + BORDERWIDTH)
+ ||(size.mY != new_height + BORDERHEIGHT))
+ {
+ // use actual display dimensions, not virtual UI dimensions
+ S32 x = gViewerWindow->getWindowWidthRaw();
+ S32 y = gViewerWindow->getWindowHeightRaw();
+ BORDERWIDTH = size.mX - x;
+ BORDERHEIGHT = size.mY- y;
+ LLCoordScreen new_size(new_width + BORDERWIDTH,
+ new_height + BORDERHEIGHT);
+ gViewerWindow->mWindow->setSize(new_size);
+ }
+}
+
+BOOL LLViewerWindow::saveSnapshot( const std::string& filepath, S32 image_width, S32 image_height, BOOL show_ui, BOOL do_rebuild, ESnapshotType type)
+{
+ llinfos << "Saving snapshot to: " << filepath << llendl;
+
+ LLPointer<LLImageRaw> raw = new LLImageRaw;
+ BOOL success = rawSnapshot(raw, image_width, image_height, TRUE, FALSE, show_ui, do_rebuild);
+
+ if (success)
+ {
+ LLPointer<LLImageBMP> bmp_image = new LLImageBMP;
+ success = bmp_image->encode(raw, 0.0f);
+ if( success )
+ {
+ success = bmp_image->save(filepath);
+ }
+ else
+ {
+ llwarns << "Unable to encode bmp snapshot" << llendl;
+ }
+ }
+ else
+ {
+ llwarns << "Unable to capture raw snapshot" << llendl;
+ }
+
+ return success;
+}
+
+
+void LLViewerWindow::playSnapshotAnimAndSound()
+{
+ if (gSavedSettings.getBOOL("QuietSnapshotsToDisk"))
+ {
+ return;
+ }
+ gAgent.sendAnimationRequest(ANIM_AGENT_SNAPSHOT, ANIM_REQUEST_START);
+ send_sound_trigger(LLUUID(gSavedSettings.getString("UISndSnapshot")), 1.0f);
+}
+
+BOOL LLViewerWindow::thumbnailSnapshot(LLImageRaw *raw, S32 preview_width, S32 preview_height, BOOL show_ui, BOOL do_rebuild, ESnapshotType type)
+{
+ return rawSnapshot(raw, preview_width, preview_height, FALSE, FALSE, show_ui, do_rebuild, type);
+}
+
+// Saves the image from the screen to the specified filename and path.
+BOOL LLViewerWindow::rawSnapshot(LLImageRaw *raw, S32 image_width, S32 image_height,
+ BOOL keep_window_aspect, BOOL is_texture, BOOL show_ui, BOOL do_rebuild, ESnapshotType type, S32 max_size)
+{
+ if (!raw)
+ {
+ return FALSE;
+ }
+
+ // PRE SNAPSHOT
+ gDisplaySwapBuffers = FALSE;
+
+ glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
+ setCursor(UI_CURSOR_WAIT);
+
+ // Hide all the UI widgets first and draw a frame
+ BOOL prev_draw_ui = gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI) ? TRUE : FALSE;
+
+ show_ui = show_ui ? TRUE : FALSE;
+
+ if ( prev_draw_ui != show_ui)
+ {
+ LLPipeline::toggleRenderDebugFeature((void*)LLPipeline::RENDER_DEBUG_FEATURE_UI);
+ }
+
+ BOOL hide_hud = !gSavedSettings.getBOOL("RenderHUDInSnapshot") && LLPipeline::sShowHUDAttachments;
+ if (hide_hud)
+ {
+ LLPipeline::sShowHUDAttachments = FALSE;
+ }
+
+ // if not showing ui, use full window to render world view
+ updateWorldViewRect(!show_ui);
+
+ // Copy screen to a buffer
+ // crop sides or top and bottom, if taking a snapshot of different aspect ratio
+ // from window
+ LLRect window_rect = show_ui ? getWindowRectRaw() : getWorldViewRectRaw();
+
+ S32 snapshot_width = window_rect.getWidth();
+ S32 snapshot_height = window_rect.getHeight();
+ // SNAPSHOT
+ S32 window_width = snapshot_width;
+ S32 window_height = snapshot_height;
+
+ if (show_ui)
+ {
+ image_width = llmin(image_width, window_width);
+ image_height = llmin(image_height, window_height);
+ }
+
+ F32 scale_factor = 1.0f ;
+ if(!keep_window_aspect) //image cropping
+ {
+ F32 ratio = llmin( (F32)window_width / image_width , (F32)window_height / image_height) ;
+ snapshot_width = (S32)(ratio * image_width) ;
+ snapshot_height = (S32)(ratio * image_height) ;
+ scale_factor = llmax(1.0f, 1.0f / ratio) ;
+ }
+ else //the scene(window) proportion needs to be maintained.
+ {
+ if(image_width > window_width || image_height > window_height) //need to enlarge the scene
+ {
+ F32 ratio = llmin( (F32)window_width / image_width , (F32)window_height / image_height) ;
+ snapshot_width = (S32)(ratio * image_width) ;
+ snapshot_height = (S32)(ratio * image_height) ;
+ scale_factor = llmax(1.0f, 1.0f / ratio) ;
+ }
+ }
+
+ if (show_ui && scale_factor > 1.f)
+ {
+ llwarns << "over scaling UI not supported." << llendl;
+ }
+
+ S32 buffer_x_offset = llfloor(((window_width - snapshot_width) * scale_factor) / 2.f);
+ S32 buffer_y_offset = llfloor(((window_height - snapshot_height) * scale_factor) / 2.f);
+
+ S32 image_buffer_x = llfloor(snapshot_width*scale_factor) ;
+ S32 image_buffer_y = llfloor(snapshot_height *scale_factor) ;
+
+ if(image_buffer_x > max_size || image_buffer_y > max_size) //boundary check to avoid memory overflow
+ {
+ scale_factor *= llmin((F32)max_size / image_buffer_x, (F32)max_size / image_buffer_y) ;
+ image_buffer_x = llfloor(snapshot_width*scale_factor) ;
+ image_buffer_y = llfloor(snapshot_height *scale_factor) ;
+ }
+ if(image_buffer_x > 0 && image_buffer_y > 0)
+ {
+ raw->resize(image_buffer_x, image_buffer_y, 3);
+ }
+ else
+ {
+ return FALSE ;
+ }
+ if(raw->isBufferInvalid())
+ {
+ return FALSE ;
+ }
+
+ BOOL high_res = scale_factor >= 2.f; // Font scaling is slow, only do so if rez is much higher
+ if (high_res && show_ui)
+ {
+ llwarns << "High res UI snapshot not supported. " << llendl;
+ /*send_agent_pause();
+ //rescale fonts
+ initFonts(scale_factor);
+ LLHUDObject::reshapeAll();*/
+ }
+
+ S32 output_buffer_offset_y = 0;
+
+ F32 depth_conversion_factor_1 = (LLViewerCamera::getInstance()->getFar() + LLViewerCamera::getInstance()->getNear()) / (2.f * LLViewerCamera::getInstance()->getFar() * LLViewerCamera::getInstance()->getNear());
+ F32 depth_conversion_factor_2 = (LLViewerCamera::getInstance()->getFar() - LLViewerCamera::getInstance()->getNear()) / (2.f * LLViewerCamera::getInstance()->getFar() * LLViewerCamera::getInstance()->getNear());
+
+ gObjectList.generatePickList(*LLViewerCamera::getInstance());
+
+ for (int subimage_y = 0; subimage_y < scale_factor; ++subimage_y)
+ {
+ S32 subimage_y_offset = llclamp(buffer_y_offset - (subimage_y * window_height), 0, window_height);;
+ // handle fractional columns
+ U32 read_height = llmax(0, (window_height - subimage_y_offset) -
+ llmax(0, (window_height * (subimage_y + 1)) - (buffer_y_offset + raw->getHeight())));
+
+ S32 output_buffer_offset_x = 0;
+ for (int subimage_x = 0; subimage_x < scale_factor; ++subimage_x)
+ {
+ gDisplaySwapBuffers = FALSE;
+ gDepthDirty = TRUE;
+
+ const U32 subfield = subimage_x+(subimage_y*llceil(scale_factor));
+
+ if (LLPipeline::sRenderDeferred)
+ {
+ display(do_rebuild, scale_factor, subfield, TRUE);
+ }
+ else
+ {
+ display(do_rebuild, scale_factor, subfield, TRUE);
+ // Required for showing the GUI in snapshots and performing bloom composite overlay
+ // Call even if show_ui is FALSE
+ render_ui(scale_factor, subfield);
+ }
+
+ S32 subimage_x_offset = llclamp(buffer_x_offset - (subimage_x * window_width), 0, window_width);
+ // handle fractional rows
+ U32 read_width = llmax(0, (window_width - subimage_x_offset) -
+ llmax(0, (window_width * (subimage_x + 1)) - (buffer_x_offset + raw->getWidth())));
+ for(U32 out_y = 0; out_y < read_height ; out_y++)
+ {
+ S32 output_buffer_offset = (
+ (out_y * (raw->getWidth())) // ...plus iterated y...
+ + (window_width * subimage_x) // ...plus subimage start in x...
+ + (raw->getWidth() * window_height * subimage_y) // ...plus subimage start in y...
+ - output_buffer_offset_x // ...minus buffer padding x...
+ - (output_buffer_offset_y * (raw->getWidth())) // ...minus buffer padding y...
+ ) * raw->getComponents();
+
+ // Ping the wathdog thread every 100 lines to keep us alive (arbitrary number, feel free to change)
+ if (out_y % 100 == 0)
+ {
+ LLAppViewer::instance()->pingMainloopTimeout("LLViewerWindow::rawSnapshot");
+ }
+
+ if (type == SNAPSHOT_TYPE_COLOR)
+ {
+ glReadPixels(
+ subimage_x_offset, out_y + subimage_y_offset,
+ read_width, 1,
+ GL_RGB, GL_UNSIGNED_BYTE,
+ raw->getData() + output_buffer_offset
+ );
+ }
+ else // SNAPSHOT_TYPE_DEPTH
+ {
+ LLPointer<LLImageRaw> depth_line_buffer = new LLImageRaw(read_width, 1, sizeof(GL_FLOAT)); // need to store floating point values
+ glReadPixels(
+ subimage_x_offset, out_y + subimage_y_offset,
+ read_width, 1,
+ GL_DEPTH_COMPONENT, GL_FLOAT,
+ depth_line_buffer->getData()// current output pixel is beginning of buffer...
+ );
+
+ for (S32 i = 0; i < (S32)read_width; i++)
+ {
+ F32 depth_float = *(F32*)(depth_line_buffer->getData() + (i * sizeof(F32)));
+
+ F32 linear_depth_float = 1.f / (depth_conversion_factor_1 - (depth_float * depth_conversion_factor_2));
+ U8 depth_byte = F32_to_U8(linear_depth_float, LLViewerCamera::getInstance()->getNear(), LLViewerCamera::getInstance()->getFar());
+ //write converted scanline out to result image
+ for(S32 j = 0; j < raw->getComponents(); j++)
+ {
+ *(raw->getData() + output_buffer_offset + (i * raw->getComponents()) + j) = depth_byte;
+ }
+ }
+ }
+ }
+ output_buffer_offset_x += subimage_x_offset;
+ stop_glerror();
+ }
+ output_buffer_offset_y += subimage_y_offset;
+ }
+
+ gDisplaySwapBuffers = FALSE;
+ gDepthDirty = TRUE;
+
+ // POST SNAPSHOT
+ if (!gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
+ {
+ LLPipeline::toggleRenderDebugFeature((void*)LLPipeline::RENDER_DEBUG_FEATURE_UI);
+ }
+
+ if (hide_hud)
+ {
+ LLPipeline::sShowHUDAttachments = TRUE;
+ }
+
+ /*if (high_res)
+ {
+ initFonts(1.f);
+ LLHUDObject::reshapeAll();
+ }*/
+
+ // Pre-pad image to number of pixels such that the line length is a multiple of 4 bytes (for BMP encoding)
+ // Note: this formula depends on the number of components being 3. Not obvious, but it's correct.
+ image_width += (image_width * 3) % 4;
+
+ BOOL ret = TRUE ;
+ // Resize image
+ if(llabs(image_width - image_buffer_x) > 4 || llabs(image_height - image_buffer_y) > 4)
+ {
+ ret = raw->scale( image_width, image_height );
+ }
+ else if(image_width != image_buffer_x || image_height != image_buffer_y)
+ {
+ ret = raw->scale( image_width, image_height, FALSE );
+ }
+
+
+ setCursor(UI_CURSOR_ARROW);
+
+ if (do_rebuild)
+ {
+ // If we had to do a rebuild, that means that the lists of drawables to be rendered
+ // was empty before we started.
+ // Need to reset these, otherwise we call state sort on it again when render gets called the next time
+ // and we stand a good chance of crashing on rebuild because the render drawable arrays have multiple copies of
+ // objects on them.
+ gPipeline.resetDrawOrders();
+ }
+
+ if (high_res)
+ {
+ send_agent_resume();
+ }
+
+ return ret;
+}
+
+void LLViewerWindow::destroyWindow()
+{
+ if (mWindow)
+ {
+ LLWindowManager::destroyWindow(mWindow);
+ }
+ mWindow = NULL;
+}
+
+
+void LLViewerWindow::drawMouselookInstructions()
+{
+ // Draw instructions for mouselook ("Press ESC to return to World View" partially transparent at the bottom of the screen.)
+ const std::string instructions = LLTrans::getString("LeaveMouselook");
+ const LLFontGL* font = LLFontGL::getFont(LLFontDescriptor("SansSerif", "Large", LLFontGL::BOLD));
+
+ //to be on top of Bottom bar when it is opened
+ const S32 INSTRUCTIONS_PAD = 50;
+
+ font->renderUTF8(
+ instructions, 0,
+ getWorldViewRectScaled().getCenterX(),
+ getWorldViewRectScaled().mBottom + INSTRUCTIONS_PAD,
+ LLColor4( 1.0f, 1.0f, 1.0f, 0.5f ),
+ LLFontGL::HCENTER, LLFontGL::TOP,
+ LLFontGL::NORMAL,LLFontGL::DROP_SHADOW);
+}
+
+void* LLViewerWindow::getPlatformWindow() const
+{
+ return mWindow->getPlatformWindow();
+}
+
+void* LLViewerWindow::getMediaWindow() const
+{
+ return mWindow->getMediaWindow();
+}
+
+void LLViewerWindow::focusClient() const
+{
+ return mWindow->focusClient();
+}
+
+LLRootView* LLViewerWindow::getRootView() const
+{
+ return mRootView;
+}
+
+LLRect LLViewerWindow::getWorldViewRectScaled() const
+{
+ return mWorldViewRectScaled;
+}
+
+S32 LLViewerWindow::getWorldViewHeightScaled() const
+{
+ return mWorldViewRectScaled.getHeight();
+}
+
+S32 LLViewerWindow::getWorldViewWidthScaled() const
+{
+ return mWorldViewRectScaled.getWidth();
+}
+
+
+S32 LLViewerWindow::getWorldViewHeightRaw() const
+{
+ return mWorldViewRectRaw.getHeight();
+}
+
+S32 LLViewerWindow::getWorldViewWidthRaw() const
+{
+ return mWorldViewRectRaw.getWidth();
+}
+
+S32 LLViewerWindow::getWindowHeightScaled() const
+{
+ return mWindowRectScaled.getHeight();
+}
+
+S32 LLViewerWindow::getWindowWidthScaled() const
+{
+ return mWindowRectScaled.getWidth();
+}
+
+S32 LLViewerWindow::getWindowHeightRaw() const
+{
+ return mWindowRectRaw.getHeight();
+}
+
+S32 LLViewerWindow::getWindowWidthRaw() const
+{
+ return mWindowRectRaw.getWidth();
+}
+
+void LLViewerWindow::setup2DRender()
+{
+ // setup ortho camera
+ gl_state_for_2d(mWindowRectRaw.getWidth(), mWindowRectRaw.getHeight());
+ setup2DViewport();
+}
+
+void LLViewerWindow::setup2DViewport(S32 x_offset, S32 y_offset)
+{
+ gGLViewport[0] = mWindowRectRaw.mLeft + x_offset;
+ gGLViewport[1] = mWindowRectRaw.mBottom + y_offset;
+ gGLViewport[2] = mWindowRectRaw.getWidth();
+ gGLViewport[3] = mWindowRectRaw.getHeight();
+ glViewport(gGLViewport[0], gGLViewport[1], gGLViewport[2], gGLViewport[3]);
+}
+
+
+void LLViewerWindow::setup3DRender()
+{
+ // setup perspective camera
+ LLViewerCamera::getInstance()->setPerspective(NOT_FOR_SELECTION, mWorldViewRectRaw.mLeft, mWorldViewRectRaw.mBottom, mWorldViewRectRaw.getWidth(), mWorldViewRectRaw.getHeight(), FALSE, LLViewerCamera::getInstance()->getNear(), MAX_FAR_CLIP*2.f);
+ setup3DViewport();
+}
+
+void LLViewerWindow::setup3DViewport(S32 x_offset, S32 y_offset)
+{
+ gGLViewport[0] = mWorldViewRectRaw.mLeft + x_offset;
+ gGLViewport[1] = mWorldViewRectRaw.mBottom + y_offset;
+ gGLViewport[2] = mWorldViewRectRaw.getWidth();
+ gGLViewport[3] = mWorldViewRectRaw.getHeight();
+ glViewport(gGLViewport[0], gGLViewport[1], gGLViewport[2], gGLViewport[3]);
+}
+
+void LLViewerWindow::setShowProgress(const BOOL show)
+{
+ if (mProgressView)
+ {
+ mProgressView->setVisible(show);
+ }
+}
+
+BOOL LLViewerWindow::getShowProgress() const
+{
+ return (mProgressView && mProgressView->getVisible());
+}
+
+void LLViewerWindow::setProgressString(const std::string& string)
+{
+ if (mProgressView)
+ {
+ mProgressView->setText(string);
+ }
+}
+
+void LLViewerWindow::setProgressMessage(const std::string& msg)
+{
+ if(mProgressView)
+ {
+ mProgressView->setMessage(msg);
+ }
+}
+
+void LLViewerWindow::setProgressPercent(const F32 percent)
+{
+ if (mProgressView)
+ {
+ mProgressView->setPercent(percent);
+ }
+}
+
+void LLViewerWindow::setProgressCancelButtonVisible( BOOL b, const std::string& label )
+{
+ if (mProgressView)
+ {
+ mProgressView->setCancelButtonVisible( b, label );
+ }
+}
+
+
+LLProgressView *LLViewerWindow::getProgressView() const
+{
+ return mProgressView;
+}
+
+void LLViewerWindow::dumpState()
+{
+ llinfos << "LLViewerWindow Active " << S32(mActive) << llendl;
+ llinfos << "mWindow visible " << S32(mWindow->getVisible())
+ << " minimized " << S32(mWindow->getMinimized())
+ << llendl;
+}
+
+void LLViewerWindow::stopGL(BOOL save_state)
+{
+ //Note: --bao
+ //if not necessary, do not change the order of the function calls in this function.
+ //if change something, make sure it will not break anything.
+ //especially be careful to put anything behind gTextureList.destroyGL(save_state);
+ if (!gGLManager.mIsDisabled)
+ {
+ llinfos << "Shutting down GL..." << llendl;
+
+ // Pause texture decode threads (will get unpaused during main loop)
+ LLAppViewer::getTextureCache()->pause();
+ LLAppViewer::getImageDecodeThread()->pause();
+ LLAppViewer::getTextureFetch()->pause();
+
+ gSky.destroyGL();
+ stop_glerror();
+
+ LLManipTranslate::destroyGL() ;
+ stop_glerror();
+
+ gBumpImageList.destroyGL();
+ stop_glerror();
+
+ LLFontGL::destroyAllGL();
+ stop_glerror();
+
+ LLVOAvatar::destroyGL();
+ stop_glerror();
+
+ LLViewerDynamicTexture::destroyGL();
+ stop_glerror();
+
+ if (gPipeline.isInit())
+ {
+ gPipeline.destroyGL();
+ }
+
+ gCone.cleanupGL();
+ gBox.cleanupGL();
+ gSphere.cleanupGL();
+ gCylinder.cleanupGL();
+
+ if(gPostProcess)
+ {
+ gPostProcess->invalidate();
+ }
+
+ gTextureList.destroyGL(save_state);
+ stop_glerror();
+
+ gGLManager.mIsDisabled = TRUE;
+ stop_glerror();
+
+ llinfos << "Remaining allocated texture memory: " << LLImageGL::sGlobalTextureMemoryInBytes << " bytes" << llendl;
+ }
+}
+
+void LLViewerWindow::restoreGL(const std::string& progress_message)
+{
+ //Note: --bao
+ //if not necessary, do not change the order of the function calls in this function.
+ //if change something, make sure it will not break anything.
+ //especially, be careful to put something before gTextureList.restoreGL();
+ if (gGLManager.mIsDisabled)
+ {
+ llinfos << "Restoring GL..." << llendl;
+ gGLManager.mIsDisabled = FALSE;
+
+ initGLDefaults();
+ LLGLState::restoreGL();
+
+ gTextureList.restoreGL();
+
+ // for future support of non-square pixels, and fonts that are properly stretched
+ //LLFontGL::destroyDefaultFonts();
+ initFonts();
+
+ gSky.restoreGL();
+ gPipeline.restoreGL();
+ LLDrawPoolWater::restoreGL();
+ LLManipTranslate::restoreGL();
+
+ gBumpImageList.restoreGL();
+ LLViewerDynamicTexture::restoreGL();
+ LLVOAvatar::restoreGL();
+
+ gResizeScreenTexture = TRUE;
+ gWindowResized = TRUE;
+
+ if (isAgentAvatarValid() && !gAgentAvatarp->isUsingBakedTextures())
+ {
+ LLVisualParamHint::requestHintUpdates();
+ }
+
+ if (!progress_message.empty())
+ {
+ gRestoreGLTimer.reset();
+ gRestoreGL = TRUE;
+ setShowProgress(TRUE);
+ setProgressString(progress_message);
+ }
+ llinfos << "...Restoring GL done" << llendl;
+ if(!LLAppViewer::instance()->restoreErrorTrap())
+ {
+ llwarns << " Someone took over my signal/exception handler (post restoreGL)!" << llendl;
+ }
+
+ }
+}
+
+void LLViewerWindow::initFonts(F32 zoom_factor)
+{
+ LLFontGL::destroyAllGL();
+ // Initialize with possibly different zoom factor
+ LLFontGL::initClass( gSavedSettings.getF32("FontScreenDPI"),
+ mDisplayScale.mV[VX] * zoom_factor,
+ mDisplayScale.mV[VY] * zoom_factor,
+ gDirUtilp->getAppRODataDir(),
+ LLUI::getXUIPaths());
+ // Force font reloads, which can be very slow
+ LLFontGL::loadDefaultFonts();
+}
+
+void LLViewerWindow::requestResolutionUpdate()
+{
+ mResDirty = true;
+}
+
+void LLViewerWindow::checkSettings()
+{
+ if (mStatesDirty)
+ {
+ gGL.refreshState();
+ LLViewerShaderMgr::instance()->setShaders();
+ mStatesDirty = false;
+ }
+
+ // We want to update the resolution AFTER the states getting refreshed not before.
+ if (mResDirty)
+ {
+ reshape(getWindowWidthRaw(), getWindowHeightRaw());
+ mResDirty = false;
+ }
+}
+
+void LLViewerWindow::restartDisplay(BOOL show_progress_bar)
+{
+ llinfos << "Restaring GL" << llendl;
+ stopGL();
+ if (show_progress_bar)
+ {
+ restoreGL(LLTrans::getString("ProgressChangingResolution"));
+ }
+ else
+ {
+ restoreGL();
+ }
+}
+
+BOOL LLViewerWindow::changeDisplaySettings(LLCoordScreen size, BOOL disable_vsync, BOOL show_progress_bar)
+{
+ //BOOL was_maximized = gSavedSettings.getBOOL("WindowMaximized");
+
+ //gResizeScreenTexture = TRUE;
+
+
+ //U32 fsaa = gSavedSettings.getU32("RenderFSAASamples");
+ //U32 old_fsaa = mWindow->getFSAASamples();
+
+ // if not maximized, use the request size
+ if (!mWindow->getMaximized())
+ {
+ mWindow->setSize(size);
+ }
+
+ //if (fsaa == old_fsaa)
+ {
+ return TRUE;
+ }
+
+/*
+
+ // Close floaters that don't handle settings change
+ LLFloaterReg::hideInstance("snapshot");
+
+ BOOL result_first_try = FALSE;
+ BOOL result_second_try = FALSE;
+
+ LLFocusableElement* keyboard_focus = gFocusMgr.getKeyboardFocus();
+ send_agent_pause();
+ llinfos << "Stopping GL during changeDisplaySettings" << llendl;
+ stopGL();
+ mIgnoreActivate = TRUE;
+ LLCoordScreen old_size;
+ LLCoordScreen old_pos;
+ mWindow->getSize(&old_size);
+
+ //mWindow->setFSAASamples(fsaa);
+
+ result_first_try = mWindow->switchContext(false, size, disable_vsync);
+ if (!result_first_try)
+ {
+ // try to switch back
+ //mWindow->setFSAASamples(old_fsaa);
+ result_second_try = mWindow->switchContext(false, old_size, disable_vsync);
+
+ if (!result_second_try)
+ {
+ // we are stuck...try once again with a minimal resolution?
+ send_agent_resume();
+ mIgnoreActivate = FALSE;
+ return FALSE;
+ }
+ }
+ send_agent_resume();
+
+ llinfos << "Restoring GL during resolution change" << llendl;
+ if (show_progress_bar)
+ {
+ restoreGL(LLTrans::getString("ProgressChangingResolution"));
+ }
+ else
+ {
+ restoreGL();
+ }
+
+ if (!result_first_try)
+ {
+ LLSD args;
+ args["RESX"] = llformat("%d",size.mX);
+ args["RESY"] = llformat("%d",size.mY);
+ LLNotificationsUtil::add("ResolutionSwitchFail", args);
+ size = old_size; // for reshape below
+ }
+
+ BOOL success = result_first_try || result_second_try;
+
+ if (success)
+ {
+ // maximize window if was maximized, else reposition
+ if (was_maximized)
+ {
+ mWindow->maximize();
+ }
+ else
+ {
+ S32 windowX = gSavedSettings.getS32("WindowX");
+ S32 windowY = gSavedSettings.getS32("WindowY");
+
+ mWindow->setPosition(LLCoordScreen ( windowX, windowY ) );
+ }
+ }
+
+ mIgnoreActivate = FALSE;
+ gFocusMgr.setKeyboardFocus(keyboard_focus);
+
+ return success;
+
+ */
+}
+
+F32 LLViewerWindow::getWorldViewAspectRatio() const
+{
+ F32 world_aspect = (F32)mWorldViewRectRaw.getWidth() / (F32)mWorldViewRectRaw.getHeight();
+ return world_aspect;
+}
+
+void LLViewerWindow::calcDisplayScale()
+{
+ F32 ui_scale_factor = gSavedSettings.getF32("UIScaleFactor");
+ LLVector2 display_scale;
+ display_scale.setVec(llmax(1.f / mWindow->getPixelAspectRatio(), 1.f), llmax(mWindow->getPixelAspectRatio(), 1.f));
+ display_scale *= ui_scale_factor;
+
+ // limit minimum display scale
+ if (display_scale.mV[VX] < MIN_DISPLAY_SCALE || display_scale.mV[VY] < MIN_DISPLAY_SCALE)
+ {
+ display_scale *= MIN_DISPLAY_SCALE / llmin(display_scale.mV[VX], display_scale.mV[VY]);
+ }
+
+ if (display_scale != mDisplayScale)
+ {
+ llinfos << "Setting display scale to " << display_scale << llendl;
+
+ mDisplayScale = display_scale;
+ // Init default fonts
+ initFonts();
+ }
+}
+
+//static
+LLRect LLViewerWindow::calcScaledRect(const LLRect & rect, const LLVector2& display_scale)
+{
+ LLRect res = rect;
+ res.mLeft = llround((F32)res.mLeft / display_scale.mV[VX]);
+ res.mRight = llround((F32)res.mRight / display_scale.mV[VX]);
+ res.mBottom = llround((F32)res.mBottom / display_scale.mV[VY]);
+ res.mTop = llround((F32)res.mTop / display_scale.mV[VY]);
+
+ return res;
+}
+
+S32 LLViewerWindow::getChatConsoleBottomPad()
+{
+ S32 offset = 0;
+
+ if(LLBottomTray::instanceExists())
+ offset += LLBottomTray::getInstance()->getRect().getHeight();
+
+ return offset;
+}
+
+LLRect LLViewerWindow::getChatConsoleRect()
+{
+ LLRect full_window(0, getWindowHeightScaled(), getWindowWidthScaled(), 0);
+ LLRect console_rect = full_window;
+
+ const S32 CONSOLE_PADDING_TOP = 24;
+ const S32 CONSOLE_PADDING_LEFT = 24;
+ const S32 CONSOLE_PADDING_RIGHT = 10;
+
+ console_rect.mTop -= CONSOLE_PADDING_TOP;
+ console_rect.mBottom += getChatConsoleBottomPad();
+
+ console_rect.mLeft += CONSOLE_PADDING_LEFT;
+
+ static const BOOL CHAT_FULL_WIDTH = gSavedSettings.getBOOL("ChatFullWidth");
+
+ if (CHAT_FULL_WIDTH)
+ {
+ console_rect.mRight -= CONSOLE_PADDING_RIGHT;
+ }
+ else
+ {
+ // Make console rect somewhat narrow so having inventory open is
+ // less of a problem.
+ console_rect.mRight = console_rect.mLeft + 2 * getWindowWidthScaled() / 3;
+ }
+
+ return console_rect;
+}
+//----------------------------------------------------------------------------
+
+
+//static
+bool LLViewerWindow::onAlert(const LLSD& notify)
+{
+ LLNotificationPtr notification = LLNotifications::instance().find(notify["id"].asUUID());
+
+ if (gNoRender)
+ {
+ llinfos << "Alert: " << notification->getName() << llendl;
+ notification->respond(LLSD::emptyMap());
+ LLNotifications::instance().cancel(notification);
+ return false;
+ }
+
+ // If we're in mouselook, the mouse is hidden and so the user can't click
+ // the dialog buttons. In that case, change to First Person instead.
+ if( gAgentCamera.cameraMouselook() )
+ {
+ gAgentCamera.changeCameraToDefault();
+ }
+ return false;
+}
+
+////////////////////////////////////////////////////////////////////////////
+//
+// LLPickInfo
+//
+LLPickInfo::LLPickInfo()
+ : mKeyMask(MASK_NONE),
+ mPickCallback(NULL),
+ mPickType(PICK_INVALID),
+ mWantSurfaceInfo(FALSE),
+ mObjectFace(-1),
+ mUVCoords(-1.f, -1.f),
+ mSTCoords(-1.f, -1.f),
+ mXYCoords(-1, -1),
+ mIntersection(),
+ mNormal(),
+ mBinormal(),
+ mHUDIcon(NULL),
+ mPickTransparent(FALSE)
+{
+}
+
+LLPickInfo::LLPickInfo(const LLCoordGL& mouse_pos,
+ MASK keyboard_mask,
+ BOOL pick_transparent,
+ BOOL pick_uv_coords,
+ void (*pick_callback)(const LLPickInfo& pick_info))
+ : mMousePt(mouse_pos),
+ mKeyMask(keyboard_mask),
+ mPickCallback(pick_callback),
+ mPickType(PICK_INVALID),
+ mWantSurfaceInfo(pick_uv_coords),
+ mObjectFace(-1),
+ mUVCoords(-1.f, -1.f),
+ mSTCoords(-1.f, -1.f),
+ mXYCoords(-1, -1),
+ mNormal(),
+ mBinormal(),
+ mHUDIcon(NULL),
+ mPickTransparent(pick_transparent)
+{
+}
+
+void LLPickInfo::fetchResults()
+{
+
+ S32 face_hit = -1;
+ LLVector3 intersection, normal, binormal;
+ LLVector2 uv;
+
+ LLHUDIcon* hit_icon = gViewerWindow->cursorIntersectIcon(mMousePt.mX, mMousePt.mY, 512.f, &intersection);
+
+ F32 icon_dist = 0.f;
+ if (hit_icon)
+ {
+ icon_dist = (LLViewerCamera::getInstance()->getOrigin()-intersection).magVec();
+ }
+ LLViewerObject* hit_object = gViewerWindow->cursorIntersect(mMousePt.mX, mMousePt.mY, 512.f,
+ NULL, -1, mPickTransparent, &face_hit,
+ &intersection, &uv, &normal, &binormal);
+
+ mPickPt = mMousePt;
+
+ U32 te_offset = face_hit > -1 ? face_hit : 0;
+
+ //unproject relative clicked coordinate from window coordinate using GL
+
+ LLViewerObject* objectp = hit_object;
+
+ if (hit_icon &&
+ (!objectp ||
+ icon_dist < (LLViewerCamera::getInstance()->getOrigin()-intersection).magVec()))
+ {
+ // was this name referring to a hud icon?
+ mHUDIcon = hit_icon;
+ mPickType = PICK_ICON;
+ mPosGlobal = mHUDIcon->getPositionGlobal();
+ }
+ else if (objectp)
+ {
+ if( objectp->getPCode() == LLViewerObject::LL_VO_SURFACE_PATCH )
+ {
+ // Hit land
+ mPickType = PICK_LAND;
+ mObjectID.setNull(); // land has no id
+
+ // put global position into land_pos
+ LLVector3d land_pos;
+ if (!gViewerWindow->mousePointOnLandGlobal(mPickPt.mX, mPickPt.mY, &land_pos))
+ {
+ // The selected point is beyond the draw distance or is otherwise
+ // not selectable. Return before calling mPickCallback().
+ return;
+ }
+
+ // Fudge the land focus a little bit above ground.
+ mPosGlobal = land_pos + LLVector3d::z_axis * 0.1f;
+ }
+ else
+ {
+ if(isFlora(objectp))
+ {
+ mPickType = PICK_FLORA;
+ }
+ else
+ {
+ mPickType = PICK_OBJECT;
+ }
+ mObjectOffset = gAgentCamera.calcFocusOffset(objectp, intersection, mPickPt.mX, mPickPt.mY);
+ mObjectID = objectp->mID;
+ mObjectFace = (te_offset == NO_FACE) ? -1 : (S32)te_offset;
+
+ mPosGlobal = gAgent.getPosGlobalFromAgent(intersection);
+
+ if (mWantSurfaceInfo)
+ {
+ getSurfaceInfo();
+ }
+ }
+ }
+
+ if (mPickCallback)
+ {
+ mPickCallback(*this);
+ }
+}
+
+LLPointer<LLViewerObject> LLPickInfo::getObject() const
+{
+ return gObjectList.findObject( mObjectID );
+}
+
+void LLPickInfo::updateXYCoords()
+{
+ if (mObjectFace > -1)
+ {
+ const LLTextureEntry* tep = getObject()->getTE(mObjectFace);
+ LLPointer<LLViewerTexture> imagep = LLViewerTextureManager::getFetchedTexture(tep->getID());
+ if(mUVCoords.mV[VX] >= 0.f && mUVCoords.mV[VY] >= 0.f && imagep.notNull())
+ {
+ mXYCoords.mX = llround(mUVCoords.mV[VX] * (F32)imagep->getWidth());
+ mXYCoords.mY = llround((1.f - mUVCoords.mV[VY]) * (F32)imagep->getHeight());
+ }
+ }
+}
+
+void LLPickInfo::getSurfaceInfo()
+{
+ // set values to uninitialized - this is what we return if no intersection is found
+ mObjectFace = -1;
+ mUVCoords = LLVector2(-1, -1);
+ mSTCoords = LLVector2(-1, -1);
+ mXYCoords = LLCoordScreen(-1, -1);
+ mIntersection = LLVector3(0,0,0);
+ mNormal = LLVector3(0,0,0);
+ mBinormal = LLVector3(0,0,0);
+
+ LLViewerObject* objectp = getObject();
+
+ if (objectp)
+ {
+ if (gViewerWindow->cursorIntersect(llround((F32)mMousePt.mX), llround((F32)mMousePt.mY), 1024.f,
+ objectp, -1, mPickTransparent,
+ &mObjectFace,
+ &mIntersection,
+ &mSTCoords,
+ &mNormal,
+ &mBinormal))
+ {
+ // if we succeeded with the intersect above, compute the texture coordinates:
+
+ if (objectp->mDrawable.notNull() && mObjectFace > -1)
+ {
+ LLFace* facep = objectp->mDrawable->getFace(mObjectFace);
+
+ mUVCoords = facep->surfaceToTexture(mSTCoords, mIntersection, mNormal);
+ }
+
+ // and XY coords:
+ updateXYCoords();
+
+ }
+ }
+}
+
+
+/* code to get UV via a special UV render - removed in lieu of raycast method
+LLVector2 LLPickInfo::pickUV()
+{
+ LLVector2 result(-1.f, -1.f);
+
+ LLViewerObject* objectp = getObject();
+ if (!objectp)
+ {
+ return result;
+ }
+
+ if (mObjectFace > -1 &&
+ objectp->mDrawable.notNull() && objectp->getPCode() == LL_PCODE_VOLUME &&
+ mObjectFace < objectp->mDrawable->getNumFaces())
+ {
+ S32 scaled_x = llround((F32)mPickPt.mX * gViewerWindow->getDisplayScale().mV[VX]);
+ S32 scaled_y = llround((F32)mPickPt.mY * gViewerWindow->getDisplayScale().mV[VY]);
+ const S32 UV_PICK_WIDTH = 5;
+ const S32 UV_PICK_HALF_WIDTH = (UV_PICK_WIDTH - 1) / 2;
+ U8 uv_pick_buffer[UV_PICK_WIDTH * UV_PICK_WIDTH * 4];
+ LLFace* facep = objectp->mDrawable->getFace(mObjectFace);
+ if (facep)
+ {
+ LLGLState scissor_state(GL_SCISSOR_TEST);
+ scissor_state.enable();
+ LLViewerCamera::getInstance()->setPerspective(FOR_SELECTION, scaled_x - UV_PICK_HALF_WIDTH, scaled_y - UV_PICK_HALF_WIDTH, UV_PICK_WIDTH, UV_PICK_WIDTH, FALSE);
+ //glViewport(scaled_x - UV_PICK_HALF_WIDTH, scaled_y - UV_PICK_HALF_WIDTH, UV_PICK_WIDTH, UV_PICK_WIDTH);
+ glScissor(scaled_x - UV_PICK_HALF_WIDTH, scaled_y - UV_PICK_HALF_WIDTH, UV_PICK_WIDTH, UV_PICK_WIDTH);
+
+ glClear(GL_DEPTH_BUFFER_BIT);
+
+ facep->renderSelectedUV();
+
+ glReadPixels(scaled_x - UV_PICK_HALF_WIDTH, scaled_y - UV_PICK_HALF_WIDTH, UV_PICK_WIDTH, UV_PICK_WIDTH, GL_RGBA, GL_UNSIGNED_BYTE, uv_pick_buffer);
+ U8* center_pixel = &uv_pick_buffer[4 * ((UV_PICK_WIDTH * UV_PICK_HALF_WIDTH) + UV_PICK_HALF_WIDTH + 1)];
+
+ result.mV[VX] = (F32)((center_pixel[VGREEN] & 0xf) + (16.f * center_pixel[VRED])) / 4095.f;
+ result.mV[VY] = (F32)((center_pixel[VGREEN] >> 4) + (16.f * center_pixel[VBLUE])) / 4095.f;
+ }
+ }
+
+ return result;
+} */
+
+
+//static
+bool LLPickInfo::isFlora(LLViewerObject* object)
+{
+ if (!object) return false;
+
+ LLPCode pcode = object->getPCode();
+
+ if( (LL_PCODE_LEGACY_GRASS == pcode)
+ || (LL_PCODE_LEGACY_TREE == pcode)
+ || (LL_PCODE_TREE_NEW == pcode))
+ {
+ return true;
+ }
+ return false;
+}
diff --git a/indra/newview/llviewerwindow.h b/indra/newview/llviewerwindow.h
index 5eeb02b080..62822c0b34 100644
--- a/indra/newview/llviewerwindow.h
+++ b/indra/newview/llviewerwindow.h
@@ -346,7 +346,9 @@ public:
LLVector3 *intersection = NULL,
LLVector2 *uv = NULL,
LLVector3 *normal = NULL,
- LLVector3 *binormal = NULL);
+ LLVector3 *binormal = NULL,
+ LLVector3* start = NULL,
+ LLVector3* end = NULL);
// Returns a pointer to the last object hit
@@ -486,6 +488,8 @@ extern LLVector2 gDebugRaycastTexCoord;
extern LLVector3 gDebugRaycastNormal;
extern LLVector3 gDebugRaycastBinormal;
extern S32 gDebugRaycastFaceHit;
+extern LLVector3 gDebugRaycastStart;
+extern LLVector3 gDebugRaycastEnd;
extern S32 CHAT_BAR_HEIGHT;
diff --git a/indra/newview/llvoavatar.cpp b/indra/newview/llvoavatar.cpp
index 2e376e8568..5f0e4bcded 100644
--- a/indra/newview/llvoavatar.cpp
+++ b/indra/newview/llvoavatar.cpp
@@ -1,8180 +1,8437 @@
-/**
- * @File llvoavatar.cpp
- * @brief Implementation of LLVOAvatar class which is a derivation of LLViewerObject
- *
- * $LicenseInfo:firstyear=2001&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-#if LL_MSVC
-// disable warning about boost::lexical_cast returning uninitialized data
-// when it fails to parse the string
-#pragma warning (disable:4701)
-#endif
-
-#include "llviewerprecompiledheaders.h"
-
-#include "llvoavatar.h"
-
-#include <stdio.h>
-#include <ctype.h>
-
-#include "llaudioengine.h"
-#include "llcachename.h"
-#include "noise.h"
-#include "sound_ids.h"
-
-#include "llagent.h" // Get state values from here
-#include "llagentcamera.h"
-#include "llagentwearables.h"
-#include "llanimationstates.h"
-#include "llavatarnamecache.h"
-#include "llavatarpropertiesprocessor.h"
-#include "llviewercontrol.h"
-#include "llcallingcard.h" // IDEVO for LLAvatarTracker
-#include "lldrawpoolavatar.h"
-#include "lldriverparam.h"
-#include "lleditingmotion.h"
-#include "llemote.h"
-//#include "llfirstuse.h"
-#include "llheadrotmotion.h"
-#include "llhudeffecttrail.h"
-#include "llhudmanager.h"
-#include "llhudnametag.h"
-#include "llhudtext.h" // for mText/mDebugText
-#include "llkeyframefallmotion.h"
-#include "llkeyframestandmotion.h"
-#include "llkeyframewalkmotion.h"
-#include "llmutelist.h"
-#include "llmoveview.h"
-#include "llnotificationsutil.h"
-#include "llquantize.h"
-#include "llrand.h"
-#include "llregionhandle.h"
-#include "llresmgr.h"
-#include "llselectmgr.h"
-#include "llsprite.h"
-#include "lltargetingmotion.h"
-#include "lltexlayer.h"
-#include "lltoolmorph.h"
-#include "llviewercamera.h"
-#include "llviewertexturelist.h"
-#include "llviewermenu.h"
-#include "llviewerobjectlist.h"
-#include "llviewerparcelmgr.h"
-#include "llviewerstats.h"
-#include "llvoavatarself.h"
-#include "llvovolume.h"
-#include "llworld.h"
-#include "pipeline.h"
-#include "llviewershadermgr.h"
-#include "llsky.h"
-#include "llanimstatelabels.h"
-#include "lltrans.h"
-#include "llappearancemgr.h"
-
-#include "llgesturemgr.h" //needed to trigger the voice gesticulations
-#include "llvoiceclient.h"
-#include "llvoicevisualizer.h" // Ventrella
-
-#include "lldebugmessagebox.h"
-extern F32 SPEED_ADJUST_MAX;
-extern F32 SPEED_ADJUST_MAX_SEC;
-extern F32 ANIM_SPEED_MAX;
-extern F32 ANIM_SPEED_MIN;
-
-#if LL_MSVC
-// disable boost::lexical_cast warning
-#pragma warning (disable:4702)
-#endif
-
-#include <boost/lexical_cast.hpp>
-
-using namespace LLVOAvatarDefines;
-
-//-----------------------------------------------------------------------------
-// Global constants
-//-----------------------------------------------------------------------------
-const LLUUID ANIM_AGENT_BODY_NOISE = LLUUID("9aa8b0a6-0c6f-9518-c7c3-4f41f2c001ad"); //"body_noise"
-const LLUUID ANIM_AGENT_BREATHE_ROT = LLUUID("4c5a103e-b830-2f1c-16bc-224aa0ad5bc8"); //"breathe_rot"
-const LLUUID ANIM_AGENT_EDITING = LLUUID("2a8eba1d-a7f8-5596-d44a-b4977bf8c8bb"); //"editing"
-const LLUUID ANIM_AGENT_EYE = LLUUID("5c780ea8-1cd1-c463-a128-48c023f6fbea"); //"eye"
-const LLUUID ANIM_AGENT_FLY_ADJUST = LLUUID("db95561f-f1b0-9f9a-7224-b12f71af126e"); //"fly_adjust"
-const LLUUID ANIM_AGENT_HAND_MOTION = LLUUID("ce986325-0ba7-6e6e-cc24-b17c4b795578"); //"hand_motion"
-const LLUUID ANIM_AGENT_HEAD_ROT = LLUUID("e6e8d1dd-e643-fff7-b238-c6b4b056a68d"); //"head_rot"
-const LLUUID ANIM_AGENT_PELVIS_FIX = LLUUID("0c5dd2a2-514d-8893-d44d-05beffad208b"); //"pelvis_fix"
-const LLUUID ANIM_AGENT_TARGET = LLUUID("0e4896cb-fba4-926c-f355-8720189d5b55"); //"target"
-const LLUUID ANIM_AGENT_WALK_ADJUST = LLUUID("829bc85b-02fc-ec41-be2e-74cc6dd7215d"); //"walk_adjust"
-
-
-//-----------------------------------------------------------------------------
-// Constants
-//-----------------------------------------------------------------------------
-const std::string AVATAR_DEFAULT_CHAR = "avatar";
-
-const S32 MIN_PIXEL_AREA_FOR_COMPOSITE = 1024;
-const F32 SHADOW_OFFSET_AMT = 0.03f;
-
-const F32 DELTA_TIME_MIN = 0.01f; // we clamp measured deltaTime to this
-const F32 DELTA_TIME_MAX = 0.2f; // range to insure stability of computations.
-
-const F32 PELVIS_LAG_FLYING = 0.22f;// pelvis follow half life while flying
-const F32 PELVIS_LAG_WALKING = 0.4f; // ...while walking
-const F32 PELVIS_LAG_MOUSELOOK = 0.15f;
-const F32 MOUSELOOK_PELVIS_FOLLOW_FACTOR = 0.5f;
-const F32 PELVIS_LAG_WHEN_FOLLOW_CAM_IS_ON = 0.0001f; // not zero! - something gets divided by this!
-
-const F32 PELVIS_ROT_THRESHOLD_SLOW = 60.0f; // amount of deviation allowed between
-const F32 PELVIS_ROT_THRESHOLD_FAST = 2.0f; // the pelvis and the view direction
- // when moving fast & slow
-const F32 TORSO_NOISE_AMOUNT = 1.0f; // Amount of deviation from up-axis, in degrees
-const F32 TORSO_NOISE_SPEED = 0.2f; // Time scale factor on torso noise.
-
-const F32 BREATHE_ROT_MOTION_STRENGTH = 0.05f;
-const F32 BREATHE_SCALE_MOTION_STRENGTH = 0.005f;
-
-const F32 MIN_SHADOW_HEIGHT = 0.f;
-const F32 MAX_SHADOW_HEIGHT = 0.3f;
-
-const S32 MIN_REQUIRED_PIXEL_AREA_BODY_NOISE = 10000;
-const S32 MIN_REQUIRED_PIXEL_AREA_BREATHE = 10000;
-const S32 MIN_REQUIRED_PIXEL_AREA_PELVIS_FIX = 40;
-
-const S32 TEX_IMAGE_SIZE_SELF = 512;
-const S32 TEX_IMAGE_AREA_SELF = TEX_IMAGE_SIZE_SELF * TEX_IMAGE_SIZE_SELF;
-const S32 TEX_IMAGE_SIZE_OTHER = 512 / 4; // The size of local textures for other (!isSelf()) avatars
-
-const F32 HEAD_MOVEMENT_AVG_TIME = 0.9f;
-
-const S32 MORPH_MASK_REQUESTED_DISCARD = 0;
-
-// Discard level at which to switch to baked textures
-// Should probably be 4 or 3, but didn't want to change it while change other logic - SJB
-const S32 SWITCH_TO_BAKED_DISCARD = 5;
-
-const F32 FOOT_COLLIDE_FUDGE = 0.04f;
-
-const F32 HOVER_EFFECT_MAX_SPEED = 3.f;
-const F32 HOVER_EFFECT_STRENGTH = 0.f;
-const F32 UNDERWATER_EFFECT_STRENGTH = 0.1f;
-const F32 UNDERWATER_FREQUENCY_DAMP = 0.33f;
-const F32 APPEARANCE_MORPH_TIME = 0.65f;
-const F32 TIME_BEFORE_MESH_CLEANUP = 5.f; // seconds
-const S32 AVATAR_RELEASE_THRESHOLD = 10; // number of avatar instances before releasing memory
-const F32 FOOT_GROUND_COLLISION_TOLERANCE = 0.25f;
-const F32 AVATAR_LOD_TWEAK_RANGE = 0.7f;
-const S32 MAX_BUBBLE_CHAT_LENGTH = DB_CHAT_MSG_STR_LEN;
-const S32 MAX_BUBBLE_CHAT_UTTERANCES = 12;
-const F32 CHAT_FADE_TIME = 8.0;
-const F32 BUBBLE_CHAT_TIME = CHAT_FADE_TIME * 3.f;
-
-const LLColor4 DUMMY_COLOR = LLColor4(0.5,0.5,0.5,1.0);
-
-enum ERenderName
-{
- RENDER_NAME_NEVER,
- RENDER_NAME_ALWAYS,
- RENDER_NAME_FADE
-};
-
-//-----------------------------------------------------------------------------
-// Callback data
-//-----------------------------------------------------------------------------
-
-struct LLTextureMaskData
-{
- LLTextureMaskData( const LLUUID& id ) :
- mAvatarID(id),
- mLastDiscardLevel(S32_MAX)
- {}
- LLUUID mAvatarID;
- S32 mLastDiscardLevel;
-};
-
-/*********************************************************************************
- ** **
- ** Begin private LLVOAvatar Support classes
- **
- **/
-
-//------------------------------------------------------------------------
-// LLVOBoneInfo
-// Trans/Scale/Rot etc. info about each avatar bone. Used by LLVOAvatarSkeleton.
-//------------------------------------------------------------------------
-class LLVOAvatarBoneInfo
-{
- friend class LLVOAvatar;
- friend class LLVOAvatarSkeletonInfo;
-public:
- LLVOAvatarBoneInfo() : mIsJoint(FALSE) {}
- ~LLVOAvatarBoneInfo()
- {
- std::for_each(mChildList.begin(), mChildList.end(), DeletePointer());
- }
- BOOL parseXml(LLXmlTreeNode* node);
-
-private:
- std::string mName;
- BOOL mIsJoint;
- LLVector3 mPos;
- LLVector3 mRot;
- LLVector3 mScale;
- LLVector3 mPivot;
- typedef std::vector<LLVOAvatarBoneInfo*> child_list_t;
- child_list_t mChildList;
-};
-
-//------------------------------------------------------------------------
-// LLVOAvatarSkeletonInfo
-// Overall avatar skeleton
-//------------------------------------------------------------------------
-class LLVOAvatarSkeletonInfo
-{
- friend class LLVOAvatar;
-public:
- LLVOAvatarSkeletonInfo() :
- mNumBones(0), mNumCollisionVolumes(0) {}
- ~LLVOAvatarSkeletonInfo()
- {
- std::for_each(mBoneInfoList.begin(), mBoneInfoList.end(), DeletePointer());
- }
- BOOL parseXml(LLXmlTreeNode* node);
- S32 getNumBones() const { return mNumBones; }
- S32 getNumCollisionVolumes() const { return mNumCollisionVolumes; }
-
-private:
- S32 mNumBones;
- S32 mNumCollisionVolumes;
- typedef std::vector<LLVOAvatarBoneInfo*> bone_info_list_t;
- bone_info_list_t mBoneInfoList;
-};
-
-//-----------------------------------------------------------------------------
-// class LLBodyNoiseMotion
-//-----------------------------------------------------------------------------
-class LLBodyNoiseMotion :
- public LLMotion
-{
-public:
- // Constructor
- LLBodyNoiseMotion(const LLUUID &id)
- : LLMotion(id)
- {
- mName = "body_noise";
- mTorsoState = new LLJointState;
- }
-
- // Destructor
- virtual ~LLBodyNoiseMotion() { }
-
-public:
- //-------------------------------------------------------------------------
- // functions to support MotionController and MotionRegistry
- //-------------------------------------------------------------------------
- // static constructor
- // all subclasses must implement such a function and register it
- static LLMotion *create(const LLUUID &id) { return new LLBodyNoiseMotion(id); }
-
-public:
- //-------------------------------------------------------------------------
- // animation callbacks to be implemented by subclasses
- //-------------------------------------------------------------------------
-
- // motions must specify whether or not they loop
- virtual BOOL getLoop() { return TRUE; }
-
- // motions must report their total duration
- virtual F32 getDuration() { return 0.0; }
-
- // motions must report their "ease in" duration
- virtual F32 getEaseInDuration() { return 0.0; }
-
- // motions must report their "ease out" duration.
- virtual F32 getEaseOutDuration() { return 0.0; }
-
- // motions must report their priority
- virtual LLJoint::JointPriority getPriority() { return LLJoint::HIGH_PRIORITY; }
-
- virtual LLMotionBlendType getBlendType() { return ADDITIVE_BLEND; }
-
- // called to determine when a motion should be activated/deactivated based on avatar pixel coverage
- virtual F32 getMinPixelArea() { return MIN_REQUIRED_PIXEL_AREA_BODY_NOISE; }
-
- // run-time (post constructor) initialization,
- // called after parameters have been set
- // must return true to indicate success and be available for activation
- virtual LLMotionInitStatus onInitialize(LLCharacter *character)
- {
- if( !mTorsoState->setJoint( character->getJoint("mTorso") ))
- {
- return STATUS_FAILURE;
- }
-
- mTorsoState->setUsage(LLJointState::ROT);
-
- addJointState( mTorsoState );
- return STATUS_SUCCESS;
- }
-
- // called when a motion is activated
- // must return TRUE to indicate success, or else
- // it will be deactivated
- virtual BOOL onActivate() { return TRUE; }
-
- // called per time step
- // must return TRUE while it is active, and
- // must return FALSE when the motion is completed.
- virtual BOOL onUpdate(F32 time, U8* joint_mask)
- {
- F32 nx[2];
- nx[0]=time*TORSO_NOISE_SPEED;
- nx[1]=0.0f;
- F32 ny[2];
- ny[0]=0.0f;
- ny[1]=time*TORSO_NOISE_SPEED;
- F32 noiseX = noise2(nx);
- F32 noiseY = noise2(ny);
-
- F32 rx = TORSO_NOISE_AMOUNT * DEG_TO_RAD * noiseX / 0.42f;
- F32 ry = TORSO_NOISE_AMOUNT * DEG_TO_RAD * noiseY / 0.42f;
- LLQuaternion tQn;
- tQn.setQuat( rx, ry, 0.0f );
- mTorsoState->setRotation( tQn );
-
- return TRUE;
- }
-
- // called when a motion is deactivated
- virtual void onDeactivate() {}
-
-private:
- //-------------------------------------------------------------------------
- // joint states to be animated
- //-------------------------------------------------------------------------
- LLPointer<LLJointState> mTorsoState;
-};
-
-//-----------------------------------------------------------------------------
-// class LLBreatheMotionRot
-//-----------------------------------------------------------------------------
-class LLBreatheMotionRot :
- public LLMotion
-{
-public:
- // Constructor
- LLBreatheMotionRot(const LLUUID &id) :
- LLMotion(id),
- mBreatheRate(1.f),
- mCharacter(NULL)
- {
- mName = "breathe_rot";
- mChestState = new LLJointState;
- }
-
- // Destructor
- virtual ~LLBreatheMotionRot() {}
-
-public:
- //-------------------------------------------------------------------------
- // functions to support MotionController and MotionRegistry
- //-------------------------------------------------------------------------
- // static constructor
- // all subclasses must implement such a function and register it
- static LLMotion *create(const LLUUID &id) { return new LLBreatheMotionRot(id); }
-
-public:
- //-------------------------------------------------------------------------
- // animation callbacks to be implemented by subclasses
- //-------------------------------------------------------------------------
-
- // motions must specify whether or not they loop
- virtual BOOL getLoop() { return TRUE; }
-
- // motions must report their total duration
- virtual F32 getDuration() { return 0.0; }
-
- // motions must report their "ease in" duration
- virtual F32 getEaseInDuration() { return 0.0; }
-
- // motions must report their "ease out" duration.
- virtual F32 getEaseOutDuration() { return 0.0; }
-
- // motions must report their priority
- virtual LLJoint::JointPriority getPriority() { return LLJoint::MEDIUM_PRIORITY; }
-
- virtual LLMotionBlendType getBlendType() { return NORMAL_BLEND; }
-
- // called to determine when a motion should be activated/deactivated based on avatar pixel coverage
- virtual F32 getMinPixelArea() { return MIN_REQUIRED_PIXEL_AREA_BREATHE; }
-
- // run-time (post constructor) initialization,
- // called after parameters have been set
- // must return true to indicate success and be available for activation
- virtual LLMotionInitStatus onInitialize(LLCharacter *character)
- {
- mCharacter = character;
- BOOL success = true;
-
- if ( !mChestState->setJoint( character->getJoint( "mChest" ) ) ) { success = false; }
-
- if ( success )
- {
- mChestState->setUsage(LLJointState::ROT);
- addJointState( mChestState );
- }
-
- if ( success )
- {
- return STATUS_SUCCESS;
- }
- else
- {
- return STATUS_FAILURE;
- }
- }
-
- // called when a motion is activated
- // must return TRUE to indicate success, or else
- // it will be deactivated
- virtual BOOL onActivate() { return TRUE; }
-
- // called per time step
- // must return TRUE while it is active, and
- // must return FALSE when the motion is completed.
- virtual BOOL onUpdate(F32 time, U8* joint_mask)
- {
- mBreatheRate = 1.f;
-
- F32 breathe_amt = (sinf(mBreatheRate * time) * BREATHE_ROT_MOTION_STRENGTH);
-
- mChestState->setRotation(LLQuaternion(breathe_amt, LLVector3(0.f, 1.f, 0.f)));
-
- return TRUE;
- }
-
- // called when a motion is deactivated
- virtual void onDeactivate() {}
-
-private:
- //-------------------------------------------------------------------------
- // joint states to be animated
- //-------------------------------------------------------------------------
- LLPointer<LLJointState> mChestState;
- F32 mBreatheRate;
- LLCharacter* mCharacter;
-};
-
-//-----------------------------------------------------------------------------
-// class LLPelvisFixMotion
-//-----------------------------------------------------------------------------
-class LLPelvisFixMotion :
- public LLMotion
-{
-public:
- // Constructor
- LLPelvisFixMotion(const LLUUID &id)
- : LLMotion(id), mCharacter(NULL)
- {
- mName = "pelvis_fix";
-
- mPelvisState = new LLJointState;
- }
-
- // Destructor
- virtual ~LLPelvisFixMotion() { }
-
-public:
- //-------------------------------------------------------------------------
- // functions to support MotionController and MotionRegistry
- //-------------------------------------------------------------------------
- // static constructor
- // all subclasses must implement such a function and register it
- static LLMotion *create(const LLUUID& id) { return new LLPelvisFixMotion(id); }
-
-public:
- //-------------------------------------------------------------------------
- // animation callbacks to be implemented by subclasses
- //-------------------------------------------------------------------------
-
- // motions must specify whether or not they loop
- virtual BOOL getLoop() { return TRUE; }
-
- // motions must report their total duration
- virtual F32 getDuration() { return 0.0; }
-
- // motions must report their "ease in" duration
- virtual F32 getEaseInDuration() { return 0.5f; }
-
- // motions must report their "ease out" duration.
- virtual F32 getEaseOutDuration() { return 0.5f; }
-
- // motions must report their priority
- virtual LLJoint::JointPriority getPriority() { return LLJoint::LOW_PRIORITY; }
-
- virtual LLMotionBlendType getBlendType() { return NORMAL_BLEND; }
-
- // called to determine when a motion should be activated/deactivated based on avatar pixel coverage
- virtual F32 getMinPixelArea() { return MIN_REQUIRED_PIXEL_AREA_PELVIS_FIX; }
-
- // run-time (post constructor) initialization,
- // called after parameters have been set
- // must return true to indicate success and be available for activation
- virtual LLMotionInitStatus onInitialize(LLCharacter *character)
- {
- mCharacter = character;
-
- if (!mPelvisState->setJoint( character->getJoint("mPelvis")))
- {
- return STATUS_FAILURE;
- }
-
- mPelvisState->setUsage(LLJointState::POS);
-
- addJointState( mPelvisState );
- return STATUS_SUCCESS;
- }
-
- // called when a motion is activated
- // must return TRUE to indicate success, or else
- // it will be deactivated
- virtual BOOL onActivate() { return TRUE; }
-
- // called per time step
- // must return TRUE while it is active, and
- // must return FALSE when the motion is completed.
- virtual BOOL onUpdate(F32 time, U8* joint_mask)
- {
- mPelvisState->setPosition(LLVector3::zero);
-
- return TRUE;
- }
-
- // called when a motion is deactivated
- virtual void onDeactivate() {}
-
-private:
- //-------------------------------------------------------------------------
- // joint states to be animated
- //-------------------------------------------------------------------------
- LLPointer<LLJointState> mPelvisState;
- LLCharacter* mCharacter;
-};
-
-/**
- **
- ** End LLVOAvatar Support classes
- ** **
- *********************************************************************************/
-
-
-//-----------------------------------------------------------------------------
-// Static Data
-//-----------------------------------------------------------------------------
-LLXmlTree LLVOAvatar::sXMLTree;
-LLXmlTree LLVOAvatar::sSkeletonXMLTree;
-LLVOAvatarSkeletonInfo* LLVOAvatar::sAvatarSkeletonInfo = NULL;
-LLVOAvatar::LLVOAvatarXmlInfo* LLVOAvatar::sAvatarXmlInfo = NULL;
-LLVOAvatarDictionary *LLVOAvatar::sAvatarDictionary = NULL;
-S32 LLVOAvatar::sFreezeCounter = 0;
-U32 LLVOAvatar::sMaxVisible = 12;
-F32 LLVOAvatar::sRenderDistance = 256.f;
-S32 LLVOAvatar::sNumVisibleAvatars = 0;
-S32 LLVOAvatar::sNumLODChangesThisFrame = 0;
-
-const LLUUID LLVOAvatar::sStepSoundOnLand("e8af4a28-aa83-4310-a7c4-c047e15ea0df");
-const LLUUID LLVOAvatar::sStepSounds[LL_MCODE_END] =
-{
- SND_STONE_RUBBER,
- SND_METAL_RUBBER,
- SND_GLASS_RUBBER,
- SND_WOOD_RUBBER,
- SND_FLESH_RUBBER,
- SND_RUBBER_PLASTIC,
- SND_RUBBER_RUBBER
-};
-
-S32 LLVOAvatar::sRenderName = RENDER_NAME_ALWAYS;
-BOOL LLVOAvatar::sRenderGroupTitles = TRUE;
-S32 LLVOAvatar::sNumVisibleChatBubbles = 0;
-BOOL LLVOAvatar::sDebugInvisible = FALSE;
-BOOL LLVOAvatar::sShowAttachmentPoints = FALSE;
-BOOL LLVOAvatar::sShowAnimationDebug = FALSE;
-BOOL LLVOAvatar::sShowFootPlane = FALSE;
-BOOL LLVOAvatar::sVisibleInFirstPerson = FALSE;
-F32 LLVOAvatar::sLODFactor = 1.f;
-BOOL LLVOAvatar::sUseImpostors = FALSE;
-BOOL LLVOAvatar::sJointDebug = FALSE;
-
-F32 LLVOAvatar::sUnbakedTime = 0.f;
-F32 LLVOAvatar::sUnbakedUpdateTime = 0.f;
-F32 LLVOAvatar::sGreyTime = 0.f;
-F32 LLVOAvatar::sGreyUpdateTime = 0.f;
-
-//-----------------------------------------------------------------------------
-// Helper functions
-//-----------------------------------------------------------------------------
-static F32 calc_bouncy_animation(F32 x);
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar()
-//-----------------------------------------------------------------------------
-LLVOAvatar::LLVOAvatar(const LLUUID& id,
- const LLPCode pcode,
- LLViewerRegion* regionp) :
- LLViewerObject(id, pcode, regionp),
- mIsDummy(FALSE),
- mSpecialRenderMode(0),
- mTurning(FALSE),
- mPelvisToFoot(0.f),
- mLastSkeletonSerialNum( 0 ),
- mHeadOffset(),
- mIsSitting(FALSE),
- mTimeVisible(),
- mTyping(FALSE),
- mMeshValid(FALSE),
- mVisible(FALSE),
- mWindFreq(0.f),
- mRipplePhase( 0.f ),
- mBelowWater(FALSE),
- mLastAppearanceBlendTime(0.f),
- mAppearanceAnimating(FALSE),
- mNameString(),
- mTitle(),
- mNameAway(false),
- mNameBusy(false),
- mNameMute(false),
- mNameAppearance(false),
- mNameFriend(false),
- mNameAlpha(0.f),
- mRenderGroupTitles(sRenderGroupTitles),
- mNameCloud(false),
- mFirstTEMessageReceived( FALSE ),
- mFirstAppearanceMessageReceived( FALSE ),
- mCulled( FALSE ),
- mVisibilityRank(0),
- mTexSkinColor( NULL ),
- mTexHairColor( NULL ),
- mTexEyeColor( NULL ),
- mNeedsSkin(FALSE),
- mUpdatePeriod(1),
- mFullyLoaded(FALSE),
- mPreviousFullyLoaded(FALSE),
- mFullyLoadedInitialized(FALSE),
- mSupportsAlphaLayers(FALSE),
- mLoadedCallbacksPaused(FALSE)
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
- //VTResume(); // VTune
-
- // mVoiceVisualizer is created by the hud effects manager and uses the HUD Effects pipeline
- const BOOL needsSendToSim = false; // currently, this HUD effect doesn't need to pack and unpack data to do its job
- mVoiceVisualizer = ( LLVoiceVisualizer *)LLHUDManager::getInstance()->createViewerEffect( LLHUDObject::LL_HUD_EFFECT_VOICE_VISUALIZER, needsSendToSim );
-
- lldebugs << "LLVOAvatar Constructor (0x" << this << ") id:" << mID << llendl;
-
- mPelvisp = NULL;
-
- mBakedTextureDatas.resize(BAKED_NUM_INDICES);
- for (U32 i = 0; i < mBakedTextureDatas.size(); i++ )
- {
- mBakedTextureDatas[i].mLastTextureIndex = IMG_DEFAULT_AVATAR;
- mBakedTextureDatas[i].mTexLayerSet = NULL;
- mBakedTextureDatas[i].mIsLoaded = false;
- mBakedTextureDatas[i].mIsUsed = false;
- mBakedTextureDatas[i].mMaskTexName = 0;
- mBakedTextureDatas[i].mTextureIndex = LLVOAvatarDictionary::bakedToLocalTextureIndex((EBakedTextureIndex)i);
- }
-
- mDirtyMesh = 2; // Dirty geometry, need to regenerate.
- mMeshTexturesDirty = FALSE;
- mHeadp = NULL;
-
- mIsBuilt = FALSE;
-
- mNumJoints = 0;
- mSkeleton = NULL;
-
- mNumCollisionVolumes = 0;
- mCollisionVolumes = NULL;
-
- // set up animation variables
- mSpeed = 0.f;
- setAnimationData("Speed", &mSpeed);
-
- mNeedsImpostorUpdate = TRUE;
- mNeedsAnimUpdate = TRUE;
-
- mImpostorDistance = 0;
- mImpostorPixelArea = 0;
-
- setNumTEs(TEX_NUM_INDICES);
-
- mbCanSelect = TRUE;
-
- mSignaledAnimations.clear();
- mPlayingAnimations.clear();
-
- mWasOnGroundLeft = FALSE;
- mWasOnGroundRight = FALSE;
-
- mTimeLast = 0.0f;
- mSpeedAccum = 0.0f;
-
- mRippleTimeLast = 0.f;
-
- mInAir = FALSE;
-
- mStepOnLand = TRUE;
- mStepMaterial = 0;
-
- mLipSyncActive = false;
- mOohMorph = NULL;
- mAahMorph = NULL;
-
- mCurrentGesticulationLevel = 0;
-
- mRuthTimer.reset();
- mRuthDebugTimer.reset();
- mDebugExistenceTimer.reset();
-}
-
-//------------------------------------------------------------------------
-// LLVOAvatar::~LLVOAvatar()
-//------------------------------------------------------------------------
-LLVOAvatar::~LLVOAvatar()
-{
- if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
- {
- if (!mFullyLoaded)
- {
- llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' left after " << (U32)mRuthDebugTimer.getElapsedTimeF32() << " seconds as cloud." << llendl;
- LLSD args;
- args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
- args["TIME"] = llformat("%d",(U32)mRuthDebugTimer.getElapsedTimeF32());
- args["NAME"] = getFullname();
- LLNotificationsUtil::add("AvatarRezLeftCloudNotification",args);
- }
- else
- {
- llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' left." << llendl;
- LLSD args;
- args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
- args["NAME"] = getFullname();
- LLNotificationsUtil::add("AvatarRezLeftNotification",args);
- }
-
- }
- lldebugs << "LLVOAvatar Destructor (0x" << this << ") id:" << mID << llendl;
-
- mRoot.removeAllChildren();
-
- deleteAndClearArray(mSkeleton);
- deleteAndClearArray(mCollisionVolumes);
-
- mNumJoints = 0;
-
- for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
- {
- deleteAndClear(mBakedTextureDatas[i].mTexLayerSet);
- mBakedTextureDatas[i].mMeshes.clear();
-
- for (morph_list_t::iterator iter2 = mBakedTextureDatas[i].mMaskedMorphs.begin();
- iter2 != mBakedTextureDatas[i].mMaskedMorphs.end(); iter2++)
- {
- LLMaskedMorph* masked_morph = (*iter2);
- delete masked_morph;
- }
- }
-
- std::for_each(mAttachmentPoints.begin(), mAttachmentPoints.end(), DeletePairedPointer());
- mAttachmentPoints.clear();
-
- deleteAndClear(mTexSkinColor);
- deleteAndClear(mTexHairColor);
- deleteAndClear(mTexEyeColor);
-
- std::for_each(mMeshes.begin(), mMeshes.end(), DeletePairedPointer());
- mMeshes.clear();
-
- for (std::vector<LLViewerJoint*>::iterator jointIter = mMeshLOD.begin();
- jointIter != mMeshLOD.end();
- ++jointIter)
- {
- LLViewerJoint* joint = (LLViewerJoint *) *jointIter;
- std::for_each(joint->mMeshParts.begin(), joint->mMeshParts.end(), DeletePointer());
- joint->mMeshParts.clear();
- }
- std::for_each(mMeshLOD.begin(), mMeshLOD.end(), DeletePointer());
- mMeshLOD.clear();
-
- mDead = TRUE;
-
- mAnimationSources.clear();
- LLLoadedCallbackEntry::cleanUpCallbackList(&mCallbackTextureList) ;
-
- lldebugs << "LLVOAvatar Destructor end" << llendl;
-}
-
-void LLVOAvatar::markDead()
-{
- if (mNameText)
- {
- mNameText->markDead();
- mNameText = NULL;
- sNumVisibleChatBubbles--;
- }
- mVoiceVisualizer->markDead();
- LLLoadedCallbackEntry::cleanUpCallbackList(&mCallbackTextureList) ;
- LLViewerObject::markDead();
-}
-
-
-BOOL LLVOAvatar::isFullyBaked()
-{
- if (mIsDummy) return TRUE;
- if (getNumTEs() == 0) return FALSE;
-
- for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
- {
- if (!isTextureDefined(mBakedTextureDatas[i].mTextureIndex)
- && ( (i != BAKED_SKIRT) || isWearingWearableType(LLWearableType::WT_SKIRT) ) )
- {
- return FALSE;
- }
- }
- return TRUE;
-}
-
-void LLVOAvatar::deleteLayerSetCaches(bool clearAll)
-{
- for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
- {
- if (mBakedTextureDatas[i].mTexLayerSet)
- {
- // ! BACKWARDS COMPATIBILITY !
- // Can be removed after hair baking is mandatory on the grid
- if ((i != BAKED_HAIR || isSelf()) && !clearAll)
- {
- mBakedTextureDatas[i].mTexLayerSet->deleteCaches();
- }
- }
- if (mBakedTextureDatas[i].mMaskTexName)
- {
- glDeleteTextures(1, (GLuint*)&(mBakedTextureDatas[i].mMaskTexName));
- mBakedTextureDatas[i].mMaskTexName = 0 ;
- }
- }
-}
-
-// static
-BOOL LLVOAvatar::areAllNearbyInstancesBaked(S32& grey_avatars)
-{
- BOOL res = TRUE;
- grey_avatars = 0;
- for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
- iter != LLCharacter::sInstances.end(); ++iter)
- {
- LLVOAvatar* inst = (LLVOAvatar*) *iter;
- if( inst->isDead() )
- {
- continue;
- }
- else if( !inst->isFullyBaked() )
- {
- res = FALSE;
- if (inst->mHasGrey)
- {
- ++grey_avatars;
- }
- }
- }
- return res;
-}
-
-// static
-void LLVOAvatar::dumpBakedStatus()
-{
- LLVector3d camera_pos_global = gAgentCamera.getCameraPositionGlobal();
-
- for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
- iter != LLCharacter::sInstances.end(); ++iter)
- {
- LLVOAvatar* inst = (LLVOAvatar*) *iter;
- llinfos << "Avatar ";
-
- LLNameValue* firstname = inst->getNVPair("FirstName");
- LLNameValue* lastname = inst->getNVPair("LastName");
-
- if( firstname )
- {
- llcont << firstname->getString();
- }
- if( lastname )
- {
- llcont << " " << lastname->getString();
- }
-
- llcont << " " << inst->mID;
-
- if( inst->isDead() )
- {
- llcont << " DEAD ("<< inst->getNumRefs() << " refs)";
- }
-
- if( inst->isSelf() )
- {
- llcont << " (self)";
- }
-
-
- F64 dist_to_camera = (inst->getPositionGlobal() - camera_pos_global).length();
- llcont << " " << dist_to_camera << "m ";
-
- llcont << " " << inst->mPixelArea << " pixels";
-
- if( inst->isVisible() )
- {
- llcont << " (visible)";
- }
- else
- {
- llcont << " (not visible)";
- }
-
- if( inst->isFullyBaked() )
- {
- llcont << " Baked";
- }
- else
- {
- llcont << " Unbaked (";
-
- for (LLVOAvatarDictionary::BakedTextures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getBakedTextures().begin();
- iter != LLVOAvatarDictionary::getInstance()->getBakedTextures().end();
- ++iter)
- {
- const LLVOAvatarDictionary::BakedEntry *baked_dict = iter->second;
- const ETextureIndex index = baked_dict->mTextureIndex;
- if (!inst->isTextureDefined(index))
- {
- llcont << " " << LLVOAvatarDictionary::getInstance()->getTexture(index)->mName;
- }
- }
- llcont << " ) " << inst->getUnbakedPixelAreaRank();
- if( inst->isCulled() )
- {
- llcont << " culled";
- }
- }
- llcont << llendl;
- }
-}
-
-//static
-void LLVOAvatar::restoreGL()
-{
- if (!isAgentAvatarValid()) return;
-
- gAgentAvatarp->setCompositeUpdatesEnabled(TRUE);
- for (U32 i = 0; i < gAgentAvatarp->mBakedTextureDatas.size(); i++)
- {
- gAgentAvatarp->invalidateComposite(gAgentAvatarp->mBakedTextureDatas[i].mTexLayerSet, FALSE);
- }
- gAgentAvatarp->updateMeshTextures();
-}
-
-//static
-void LLVOAvatar::destroyGL()
-{
- deleteCachedImages();
-
- resetImpostors();
-}
-
-//static
-void LLVOAvatar::resetImpostors()
-{
- for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
- iter != LLCharacter::sInstances.end(); ++iter)
- {
- LLVOAvatar* avatar = (LLVOAvatar*) *iter;
- avatar->mImpostor.release();
- }
-}
-
-// static
-void LLVOAvatar::deleteCachedImages(bool clearAll)
-{
- if (LLTexLayerSet::sHasCaches)
- {
- lldebugs << "Deleting layer set caches" << llendl;
- for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
- iter != LLCharacter::sInstances.end(); ++iter)
- {
- LLVOAvatar* inst = (LLVOAvatar*) *iter;
- inst->deleteLayerSetCaches(clearAll);
- }
- LLTexLayerSet::sHasCaches = FALSE;
- }
- LLVOAvatarSelf::deleteScratchTextures();
- LLTexLayerStaticImageList::getInstance()->deleteCachedImages();
-}
-
-
-//------------------------------------------------------------------------
-// static
-// LLVOAvatar::initClass()
-//------------------------------------------------------------------------
-void LLVOAvatar::initClass()
-{
- std::string xmlFile;
-
- xmlFile = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,AVATAR_DEFAULT_CHAR) + "_lad.xml";
- BOOL success = sXMLTree.parseFile( xmlFile, FALSE );
- if (!success)
- {
- llerrs << "Problem reading avatar configuration file:" << xmlFile << llendl;
- }
-
- // now sanity check xml file
- LLXmlTreeNode* root = sXMLTree.getRoot();
- if (!root)
- {
- llerrs << "No root node found in avatar configuration file: " << xmlFile << llendl;
- return;
- }
-
- //-------------------------------------------------------------------------
- // <linden_avatar version="1.0"> (root)
- //-------------------------------------------------------------------------
- if( !root->hasName( "linden_avatar" ) )
- {
- llerrs << "Invalid avatar file header: " << xmlFile << llendl;
- }
-
- std::string version;
- static LLStdStringHandle version_string = LLXmlTree::addAttributeString("version");
- if( !root->getFastAttributeString( version_string, version ) || (version != "1.0") )
- {
- llerrs << "Invalid avatar file version: " << version << " in file: " << xmlFile << llendl;
- }
-
- S32 wearable_def_version = 1;
- static LLStdStringHandle wearable_definition_version_string = LLXmlTree::addAttributeString("wearable_definition_version");
- root->getFastAttributeS32( wearable_definition_version_string, wearable_def_version );
- LLWearable::setCurrentDefinitionVersion( wearable_def_version );
-
- std::string mesh_file_name;
-
- LLXmlTreeNode* skeleton_node = root->getChildByName( "skeleton" );
- if (!skeleton_node)
- {
- llerrs << "No skeleton in avatar configuration file: " << xmlFile << llendl;
- return;
- }
-
- std::string skeleton_file_name;
- static LLStdStringHandle file_name_string = LLXmlTree::addAttributeString("file_name");
- if (!skeleton_node->getFastAttributeString(file_name_string, skeleton_file_name))
- {
- llerrs << "No file name in skeleton node in avatar config file: " << xmlFile << llendl;
- }
-
- std::string skeleton_path;
- skeleton_path = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,skeleton_file_name);
- if (!parseSkeletonFile(skeleton_path))
- {
- llerrs << "Error parsing skeleton file: " << skeleton_path << llendl;
- }
-
- // Process XML data
-
- // avatar_skeleton.xml
- llassert(!sAvatarSkeletonInfo);
- sAvatarSkeletonInfo = new LLVOAvatarSkeletonInfo;
- if (!sAvatarSkeletonInfo->parseXml(sSkeletonXMLTree.getRoot()))
- {
- llerrs << "Error parsing skeleton XML file: " << skeleton_path << llendl;
- }
- // parse avatar_lad.xml
- llassert(!sAvatarXmlInfo);
- sAvatarXmlInfo = new LLVOAvatarXmlInfo;
- if (!sAvatarXmlInfo->parseXmlSkeletonNode(root))
- {
- llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
- }
- if (!sAvatarXmlInfo->parseXmlMeshNodes(root))
- {
- llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
- }
- if (!sAvatarXmlInfo->parseXmlColorNodes(root))
- {
- llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
- }
- if (!sAvatarXmlInfo->parseXmlLayerNodes(root))
- {
- llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
- }
- if (!sAvatarXmlInfo->parseXmlDriverNodes(root))
- {
- llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
- }
- if (!sAvatarXmlInfo->parseXmlMorphNodes(root))
- {
- llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
- }
-
- gAnimLibrary.animStateSetString(ANIM_AGENT_BODY_NOISE,"body_noise");
- gAnimLibrary.animStateSetString(ANIM_AGENT_BREATHE_ROT,"breathe_rot");
- gAnimLibrary.animStateSetString(ANIM_AGENT_EDITING,"editing");
- gAnimLibrary.animStateSetString(ANIM_AGENT_EYE,"eye");
- gAnimLibrary.animStateSetString(ANIM_AGENT_FLY_ADJUST,"fly_adjust");
- gAnimLibrary.animStateSetString(ANIM_AGENT_HAND_MOTION,"hand_motion");
- gAnimLibrary.animStateSetString(ANIM_AGENT_HEAD_ROT,"head_rot");
- gAnimLibrary.animStateSetString(ANIM_AGENT_PELVIS_FIX,"pelvis_fix");
- gAnimLibrary.animStateSetString(ANIM_AGENT_TARGET,"target");
- gAnimLibrary.animStateSetString(ANIM_AGENT_WALK_ADJUST,"walk_adjust");
-}
-
-
-void LLVOAvatar::cleanupClass()
-{
- deleteAndClear(sAvatarXmlInfo);
- sSkeletonXMLTree.cleanup();
- sXMLTree.cleanup();
-}
-
-void LLVOAvatar::initInstance(void)
-{
- //-------------------------------------------------------------------------
- // initialize joint, mesh and shape members
- //-------------------------------------------------------------------------
- mRoot.setName( "mRoot" );
-
- for (LLVOAvatarDictionary::Meshes::const_iterator iter = LLVOAvatarDictionary::getInstance()->getMeshes().begin();
- iter != LLVOAvatarDictionary::getInstance()->getMeshes().end();
- ++iter)
- {
- const EMeshIndex mesh_index = iter->first;
- const LLVOAvatarDictionary::MeshEntry *mesh_dict = iter->second;
- LLViewerJoint* joint = new LLViewerJoint();
- joint->setName(mesh_dict->mName);
- joint->setMeshID(mesh_index);
- mMeshLOD.push_back(joint);
-
- /* mHairLOD.setName("mHairLOD");
- mHairMesh0.setName("mHairMesh0");
- mHairMesh0.setMeshID(MESH_ID_HAIR);
- mHairMesh1.setName("mHairMesh1"); */
- for (U32 lod = 0; lod < mesh_dict->mLOD; lod++)
- {
- LLViewerJointMesh* mesh = new LLViewerJointMesh();
- std::string mesh_name = "m" + mesh_dict->mName + boost::lexical_cast<std::string>(lod);
- // We pre-pended an m - need to capitalize first character for camelCase
- mesh_name[1] = toupper(mesh_name[1]);
- mesh->setName(mesh_name);
- mesh->setMeshID(mesh_index);
- mesh->setPickName(mesh_dict->mPickName);
- mesh->setIsTransparent(FALSE);
- switch((int)mesh_index)
- {
- case MESH_ID_HAIR:
- mesh->setIsTransparent(TRUE);
- break;
- case MESH_ID_SKIRT:
- mesh->setIsTransparent(TRUE);
- break;
- case MESH_ID_EYEBALL_LEFT:
- case MESH_ID_EYEBALL_RIGHT:
- mesh->setSpecular( LLColor4( 1.0f, 1.0f, 1.0f, 1.0f ), 1.f );
- break;
- }
-
- joint->mMeshParts.push_back(mesh);
- }
- }
-
- //-------------------------------------------------------------------------
- // associate baked textures with meshes
- //-------------------------------------------------------------------------
- for (LLVOAvatarDictionary::Meshes::const_iterator iter = LLVOAvatarDictionary::getInstance()->getMeshes().begin();
- iter != LLVOAvatarDictionary::getInstance()->getMeshes().end();
- ++iter)
- {
- const EMeshIndex mesh_index = iter->first;
- const LLVOAvatarDictionary::MeshEntry *mesh_dict = iter->second;
- const EBakedTextureIndex baked_texture_index = mesh_dict->mBakedID;
- // Skip it if there's no associated baked texture.
- if (baked_texture_index == BAKED_NUM_INDICES) continue;
-
- for (std::vector<LLViewerJointMesh* >::iterator iter = mMeshLOD[mesh_index]->mMeshParts.begin();
- iter != mMeshLOD[mesh_index]->mMeshParts.end();
- ++iter)
- {
- LLViewerJointMesh* mesh = (LLViewerJointMesh*) *iter;
- mBakedTextureDatas[(int)baked_texture_index].mMeshes.push_back(mesh);
- }
- }
-
-
- //-------------------------------------------------------------------------
- // register motions
- //-------------------------------------------------------------------------
- if (LLCharacter::sInstances.size() == 1)
- {
- LLKeyframeMotion::setVFS(gStaticVFS);
- registerMotion( ANIM_AGENT_BUSY, LLNullMotion::create );
- registerMotion( ANIM_AGENT_CROUCH, LLKeyframeStandMotion::create );
- registerMotion( ANIM_AGENT_CROUCHWALK, LLKeyframeWalkMotion::create );
- registerMotion( ANIM_AGENT_EXPRESS_AFRAID, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_ANGER, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_BORED, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_CRY, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_DISDAIN, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_EMBARRASSED, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_FROWN, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_KISS, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_LAUGH, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_OPEN_MOUTH, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_REPULSED, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_SAD, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_SHRUG, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_SMILE, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_SURPRISE, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_TONGUE_OUT, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_TOOTHSMILE, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_WINK, LLEmote::create );
- registerMotion( ANIM_AGENT_EXPRESS_WORRY, LLEmote::create );
- registerMotion( ANIM_AGENT_FEMALE_RUN_NEW, LLKeyframeWalkMotion::create );
- registerMotion( ANIM_AGENT_FEMALE_WALK, LLKeyframeWalkMotion::create );
- registerMotion( ANIM_AGENT_FEMALE_WALK_NEW, LLKeyframeWalkMotion::create );
- registerMotion( ANIM_AGENT_RUN, LLKeyframeWalkMotion::create );
- registerMotion( ANIM_AGENT_RUN_NEW, LLKeyframeWalkMotion::create );
- registerMotion( ANIM_AGENT_STAND, LLKeyframeStandMotion::create );
- registerMotion( ANIM_AGENT_STAND_1, LLKeyframeStandMotion::create );
- registerMotion( ANIM_AGENT_STAND_2, LLKeyframeStandMotion::create );
- registerMotion( ANIM_AGENT_STAND_3, LLKeyframeStandMotion::create );
- registerMotion( ANIM_AGENT_STAND_4, LLKeyframeStandMotion::create );
- registerMotion( ANIM_AGENT_STANDUP, LLKeyframeFallMotion::create );
- registerMotion( ANIM_AGENT_TURNLEFT, LLKeyframeWalkMotion::create );
- registerMotion( ANIM_AGENT_TURNRIGHT, LLKeyframeWalkMotion::create );
- registerMotion( ANIM_AGENT_WALK, LLKeyframeWalkMotion::create );
- registerMotion( ANIM_AGENT_WALK_NEW, LLKeyframeWalkMotion::create );
-
- // motions without a start/stop bit
- registerMotion( ANIM_AGENT_BODY_NOISE, LLBodyNoiseMotion::create );
- registerMotion( ANIM_AGENT_BREATHE_ROT, LLBreatheMotionRot::create );
- registerMotion( ANIM_AGENT_EDITING, LLEditingMotion::create );
- registerMotion( ANIM_AGENT_EYE, LLEyeMotion::create );
- registerMotion( ANIM_AGENT_FEMALE_WALK, LLKeyframeWalkMotion::create );
- registerMotion( ANIM_AGENT_FLY_ADJUST, LLFlyAdjustMotion::create );
- registerMotion( ANIM_AGENT_HAND_MOTION, LLHandMotion::create );
- registerMotion( ANIM_AGENT_HEAD_ROT, LLHeadRotMotion::create );
- registerMotion( ANIM_AGENT_PELVIS_FIX, LLPelvisFixMotion::create );
- registerMotion( ANIM_AGENT_SIT_FEMALE, LLKeyframeMotion::create );
- registerMotion( ANIM_AGENT_TARGET, LLTargetingMotion::create );
- registerMotion( ANIM_AGENT_WALK_ADJUST, LLWalkAdjustMotion::create );
-
- }
-
- if (gNoRender)
- {
- return;
- }
-
- buildCharacter();
-
- if (gNoRender)
- {
- return;
- }
-
- // preload specific motions here
- createMotion( ANIM_AGENT_CUSTOMIZE);
- createMotion( ANIM_AGENT_CUSTOMIZE_DONE);
-
- //VTPause(); // VTune
-
- mVoiceVisualizer->setVoiceEnabled( LLVoiceClient::getInstance()->getVoiceEnabled( mID ) );
-
-}
-
-const LLVector3 LLVOAvatar::getRenderPosition() const
-{
- if (mDrawable.isNull() || mDrawable->getGeneration() < 0)
- {
- return getPositionAgent();
- }
- else if (isRoot())
- {
- return mDrawable->getPositionAgent();
- }
- else
- {
- return getPosition() * mDrawable->getParent()->getRenderMatrix();
- }
-}
-
-void LLVOAvatar::updateDrawable(BOOL force_damped)
-{
- clearChanged(SHIFTED);
-}
-
-void LLVOAvatar::onShift(const LLVector3& shift_vector)
-{
- mLastAnimExtents[0] += shift_vector;
- mLastAnimExtents[1] += shift_vector;
- mNeedsImpostorUpdate = TRUE;
- mNeedsAnimUpdate = TRUE;
-}
-
-void LLVOAvatar::updateSpatialExtents(LLVector3& newMin, LLVector3 &newMax)
-{
- if (isImpostor() && !needsImpostorUpdate())
- {
- LLVector3 delta = getRenderPosition() -
- ((LLVector3(mDrawable->getPositionGroup())-mImpostorOffset));
-
- newMin = mLastAnimExtents[0] + delta;
- newMax = mLastAnimExtents[1] + delta;
- }
- else
- {
- getSpatialExtents(newMin,newMax);
- mLastAnimExtents[0] = newMin;
- mLastAnimExtents[1] = newMax;
- LLVector3 pos_group = (newMin+newMax)*0.5f;
- mImpostorOffset = pos_group-getRenderPosition();
- mDrawable->setPositionGroup(pos_group);
- }
-}
-
-void LLVOAvatar::getSpatialExtents(LLVector3& newMin, LLVector3& newMax)
-{
- LLVector3 buffer(0.25f, 0.25f, 0.25f);
- LLVector3 pos = getRenderPosition();
- newMin = pos - buffer;
- newMax = pos + buffer;
- float max_attachment_span = DEFAULT_MAX_PRIM_SCALE * 5.0f;
-
- //stretch bounding box by joint positions
- for (polymesh_map_t::iterator i = mMeshes.begin(); i != mMeshes.end(); ++i)
- {
- LLPolyMesh* mesh = i->second;
- for (S32 joint_num = 0; joint_num < mesh->mJointRenderData.count(); joint_num++)
- {
- update_min_max(newMin, newMax,
- mesh->mJointRenderData[joint_num]->mWorldMatrix->getTranslation());
- }
- }
-
- mPixelArea = LLPipeline::calcPixelArea((newMin+newMax)*0.5f, (newMax-newMin)*0.5f, *LLViewerCamera::getInstance());
-
- //stretch bounding box by attachments
- for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
-
- if (!attachment->getValid())
- {
- continue ;
- }
-
- for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
- attachment_iter != attachment->mAttachedObjects.end();
- ++attachment_iter)
- {
- const LLViewerObject* attached_object = (*attachment_iter);
- if (attached_object && !attached_object->isHUDAttachment())
- {
- LLDrawable* drawable = attached_object->mDrawable;
- if (drawable)
- {
- LLSpatialBridge* bridge = drawable->getSpatialBridge();
- if (bridge)
- {
- const LLVector3* ext = bridge->getSpatialExtents();
- LLVector3 distance = (ext[1] - ext[0]);
-
- // Only add the prim to spatial extents calculations if it isn't a megaprim.
- // max_attachment_span calculated at the start of the function
- // (currently 5 times our max prim size)
- if (distance.mV[0] < max_attachment_span
- && distance.mV[1] < max_attachment_span
- && distance.mV[2] < max_attachment_span)
- {
- update_min_max(newMin,newMax,ext[0]);
- update_min_max(newMin,newMax,ext[1]);
- }
- }
- }
- }
- }
- }
-
- //pad bounding box
- newMin -= buffer;
- newMax += buffer;
-}
-
-//-----------------------------------------------------------------------------
-// renderCollisionVolumes()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::renderCollisionVolumes()
-{
- for (S32 i = 0; i < mNumCollisionVolumes; i++)
- {
- mCollisionVolumes[i].renderCollision();
- }
-
- if (mNameText.notNull())
- {
- LLVector3 unused;
- mNameText->lineSegmentIntersect(LLVector3(0,0,0), LLVector3(0,0,1), unused, TRUE);
- }
-}
-
-BOOL LLVOAvatar::lineSegmentIntersect(const LLVector3& start, const LLVector3& end,
- S32 face,
- BOOL pick_transparent,
- S32* face_hit,
- LLVector3* intersection,
- LLVector2* tex_coord,
- LLVector3* normal,
- LLVector3* bi_normal)
-{
- if ((isSelf() && !gAgent.needsRenderAvatar()) || !LLPipeline::sPickAvatar)
- {
- return FALSE;
- }
-
- if (lineSegmentBoundingBox(start, end))
- {
- for (S32 i = 0; i < mNumCollisionVolumes; ++i)
- {
- mCollisionVolumes[i].updateWorldMatrix();
-
- glh::matrix4f mat((F32*) mCollisionVolumes[i].getXform()->getWorldMatrix().mMatrix);
- glh::matrix4f inverse = mat.inverse();
- glh::matrix4f norm_mat = inverse.transpose();
-
- glh::vec3f p1(start.mV);
- glh::vec3f p2(end.mV);
-
- inverse.mult_matrix_vec(p1);
- inverse.mult_matrix_vec(p2);
-
- LLVector3 position;
- LLVector3 norm;
-
- if (linesegment_sphere(LLVector3(p1.v), LLVector3(p2.v), LLVector3(0,0,0), 1.f, position, norm))
- {
- glh::vec3f res_pos(position.mV);
- mat.mult_matrix_vec(res_pos);
-
- norm.normalize();
- glh::vec3f res_norm(norm.mV);
- norm_mat.mult_matrix_dir(res_norm);
-
- if (intersection)
- {
- *intersection = LLVector3(res_pos.v);
- }
-
- if (normal)
- {
- *normal = LLVector3(res_norm.v);
- }
-
- return TRUE;
- }
- }
- }
-
- LLVector3 position;
- if (mNameText.notNull() && mNameText->lineSegmentIntersect(start, end, position))
- {
- if (intersection)
- {
- *intersection = position;
- }
-
- return TRUE;
- }
-
- return FALSE;
-}
-
-//-----------------------------------------------------------------------------
-// parseSkeletonFile()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::parseSkeletonFile(const std::string& filename)
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- //-------------------------------------------------------------------------
- // parse the file
- //-------------------------------------------------------------------------
- BOOL parsesuccess = sSkeletonXMLTree.parseFile( filename, FALSE );
-
- if (!parsesuccess)
- {
- llerrs << "Can't parse skeleton file: " << filename << llendl;
- return FALSE;
- }
-
- // now sanity check xml file
- LLXmlTreeNode* root = sSkeletonXMLTree.getRoot();
- if (!root)
- {
- llerrs << "No root node found in avatar skeleton file: " << filename << llendl;
- return FALSE;
- }
-
- if( !root->hasName( "linden_skeleton" ) )
- {
- llerrs << "Invalid avatar skeleton file header: " << filename << llendl;
- return FALSE;
- }
-
- std::string version;
- static LLStdStringHandle version_string = LLXmlTree::addAttributeString("version");
- if( !root->getFastAttributeString( version_string, version ) || (version != "1.0") )
- {
- llerrs << "Invalid avatar skeleton file version: " << version << " in file: " << filename << llendl;
- return FALSE;
- }
-
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// setupBone()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::setupBone(const LLVOAvatarBoneInfo* info, LLViewerJoint* parent, S32 &volume_num, S32 &joint_num)
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- LLViewerJoint* joint = NULL;
-
- if (info->mIsJoint)
- {
- joint = (LLViewerJoint*)getCharacterJoint(joint_num);
- if (!joint)
- {
- llwarns << "Too many bones" << llendl;
- return FALSE;
- }
- joint->setName( info->mName );
- }
- else // collision volume
- {
- if (volume_num >= (S32)mNumCollisionVolumes)
- {
- llwarns << "Too many bones" << llendl;
- return FALSE;
- }
- joint = (LLViewerJoint*)(&mCollisionVolumes[volume_num]);
- joint->setName( info->mName );
- }
-
- // add to parent
- if (parent)
- {
- parent->addChild( joint );
- }
-
- joint->setPosition(info->mPos);
- joint->setRotation(mayaQ(info->mRot.mV[VX], info->mRot.mV[VY],
- info->mRot.mV[VZ], LLQuaternion::XYZ));
- joint->setScale(info->mScale);
-
-
- if (info->mIsJoint)
- {
- joint->setSkinOffset( info->mPivot );
- joint_num++;
- }
- else // collision volume
- {
- volume_num++;
- }
-
- // setup children
- LLVOAvatarBoneInfo::child_list_t::const_iterator iter;
- for (iter = info->mChildList.begin(); iter != info->mChildList.end(); ++iter)
- {
- LLVOAvatarBoneInfo *child_info = *iter;
- if (!setupBone(child_info, joint, volume_num, joint_num))
- {
- return FALSE;
- }
- }
-
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// buildSkeleton()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::buildSkeleton(const LLVOAvatarSkeletonInfo *info)
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- //-------------------------------------------------------------------------
- // allocate joints
- //-------------------------------------------------------------------------
- if (!allocateCharacterJoints(info->mNumBones))
- {
- llerrs << "Can't allocate " << info->mNumBones << " joints" << llendl;
- return FALSE;
- }
-
- //-------------------------------------------------------------------------
- // allocate volumes
- //-------------------------------------------------------------------------
- if (info->mNumCollisionVolumes)
- {
- if (!allocateCollisionVolumes(info->mNumCollisionVolumes))
- {
- llerrs << "Can't allocate " << info->mNumCollisionVolumes << " collision volumes" << llendl;
- return FALSE;
- }
- }
-
- S32 current_joint_num = 0;
- S32 current_volume_num = 0;
- LLVOAvatarSkeletonInfo::bone_info_list_t::const_iterator iter;
- for (iter = info->mBoneInfoList.begin(); iter != info->mBoneInfoList.end(); ++iter)
- {
- LLVOAvatarBoneInfo *info = *iter;
- if (!setupBone(info, NULL, current_volume_num, current_joint_num))
- {
- llerrs << "Error parsing bone in skeleton file" << llendl;
- return FALSE;
- }
- }
-
- return TRUE;
-}
-
-LLVOAvatar* LLVOAvatar::asAvatar()
-{
- return this;
-}
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::startDefaultMotions()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::startDefaultMotions()
-{
- //-------------------------------------------------------------------------
- // start default motions
- //-------------------------------------------------------------------------
- startMotion( ANIM_AGENT_HEAD_ROT );
- startMotion( ANIM_AGENT_EYE );
- startMotion( ANIM_AGENT_BODY_NOISE );
- startMotion( ANIM_AGENT_BREATHE_ROT );
- startMotion( ANIM_AGENT_HAND_MOTION );
- startMotion( ANIM_AGENT_PELVIS_FIX );
-
- //-------------------------------------------------------------------------
- // restart any currently active motions
- //-------------------------------------------------------------------------
- processAnimationStateChanges();
-}
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::buildCharacter()
-// Deferred initialization and rebuild of the avatar.
-//-----------------------------------------------------------------------------
-void LLVOAvatar::buildCharacter()
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- //-------------------------------------------------------------------------
- // remove all references to our existing skeleton
- // so we can rebuild it
- //-------------------------------------------------------------------------
- flushAllMotions();
-
- //-------------------------------------------------------------------------
- // remove all of mRoot's children
- //-------------------------------------------------------------------------
- mRoot.removeAllChildren();
- mIsBuilt = FALSE;
-
- //-------------------------------------------------------------------------
- // clear mesh data
- //-------------------------------------------------------------------------
- for (std::vector<LLViewerJoint*>::iterator jointIter = mMeshLOD.begin();
- jointIter != mMeshLOD.end(); ++jointIter)
- {
- LLViewerJoint* joint = (LLViewerJoint*) *jointIter;
- for (std::vector<LLViewerJointMesh*>::iterator meshIter = joint->mMeshParts.begin();
- meshIter != joint->mMeshParts.end(); ++meshIter)
- {
- LLViewerJointMesh * mesh = (LLViewerJointMesh *) *meshIter;
- mesh->setMesh(NULL);
- }
- }
-
- //-------------------------------------------------------------------------
- // (re)load our skeleton and meshes
- //-------------------------------------------------------------------------
- LLTimer timer;
-
- BOOL status = loadAvatar();
- stop_glerror();
-
- if (gNoRender)
- {
- // Still want to load the avatar skeleton so visual parameters work.
- return;
- }
-
-// gPrintMessagesThisFrame = TRUE;
- lldebugs << "Avatar load took " << timer.getElapsedTimeF32() << " seconds." << llendl;
-
- if (!status)
- {
- if (isSelf())
- {
- llerrs << "Unable to load user's avatar" << llendl;
- }
- else
- {
- llwarns << "Unable to load other's avatar" << llendl;
- }
- return;
- }
-
- //-------------------------------------------------------------------------
- // initialize "well known" joint pointers
- //-------------------------------------------------------------------------
- mPelvisp = (LLViewerJoint*)mRoot.findJoint("mPelvis");
- mTorsop = (LLViewerJoint*)mRoot.findJoint("mTorso");
- mChestp = (LLViewerJoint*)mRoot.findJoint("mChest");
- mNeckp = (LLViewerJoint*)mRoot.findJoint("mNeck");
- mHeadp = (LLViewerJoint*)mRoot.findJoint("mHead");
- mSkullp = (LLViewerJoint*)mRoot.findJoint("mSkull");
- mHipLeftp = (LLViewerJoint*)mRoot.findJoint("mHipLeft");
- mHipRightp = (LLViewerJoint*)mRoot.findJoint("mHipRight");
- mKneeLeftp = (LLViewerJoint*)mRoot.findJoint("mKneeLeft");
- mKneeRightp = (LLViewerJoint*)mRoot.findJoint("mKneeRight");
- mAnkleLeftp = (LLViewerJoint*)mRoot.findJoint("mAnkleLeft");
- mAnkleRightp = (LLViewerJoint*)mRoot.findJoint("mAnkleRight");
- mFootLeftp = (LLViewerJoint*)mRoot.findJoint("mFootLeft");
- mFootRightp = (LLViewerJoint*)mRoot.findJoint("mFootRight");
- mWristLeftp = (LLViewerJoint*)mRoot.findJoint("mWristLeft");
- mWristRightp = (LLViewerJoint*)mRoot.findJoint("mWristRight");
- mEyeLeftp = (LLViewerJoint*)mRoot.findJoint("mEyeLeft");
- mEyeRightp = (LLViewerJoint*)mRoot.findJoint("mEyeRight");
-
- //-------------------------------------------------------------------------
- // Make sure "well known" pointers exist
- //-------------------------------------------------------------------------
- if (!(mPelvisp &&
- mTorsop &&
- mChestp &&
- mNeckp &&
- mHeadp &&
- mSkullp &&
- mHipLeftp &&
- mHipRightp &&
- mKneeLeftp &&
- mKneeRightp &&
- mAnkleLeftp &&
- mAnkleRightp &&
- mFootLeftp &&
- mFootRightp &&
- mWristLeftp &&
- mWristRightp &&
- mEyeLeftp &&
- mEyeRightp))
- {
- llerrs << "Failed to create avatar." << llendl;
- return;
- }
-
- //-------------------------------------------------------------------------
- // initialize the pelvis
- //-------------------------------------------------------------------------
- mPelvisp->setPosition( LLVector3(0.0f, 0.0f, 0.0f) );
-
- //-------------------------------------------------------------------------
- // set head offset from pelvis
- //-------------------------------------------------------------------------
- updateHeadOffset();
-
- //-------------------------------------------------------------------------
- // initialize lip sync morph pointers
- //-------------------------------------------------------------------------
- mOohMorph = getVisualParam( "Lipsync_Ooh" );
- mAahMorph = getVisualParam( "Lipsync_Aah" );
-
- // If we don't have the Ooh morph, use the Kiss morph
- if (!mOohMorph)
- {
- llwarns << "Missing 'Ooh' morph for lipsync, using fallback." << llendl;
- mOohMorph = getVisualParam( "Express_Kiss" );
- }
-
- // If we don't have the Aah morph, use the Open Mouth morph
- if (!mAahMorph)
- {
- llwarns << "Missing 'Aah' morph for lipsync, using fallback." << llendl;
- mAahMorph = getVisualParam( "Express_Open_Mouth" );
- }
-
- startDefaultMotions();
-
- //-------------------------------------------------------------------------
- // restart any currently active motions
- //-------------------------------------------------------------------------
- processAnimationStateChanges();
-
- mIsBuilt = TRUE;
- stop_glerror();
-
- mMeshValid = TRUE;
-}
-
-
-//-----------------------------------------------------------------------------
-// releaseMeshData()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::releaseMeshData()
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- if (sInstances.size() < AVATAR_RELEASE_THRESHOLD || mIsDummy)
- {
- return;
- }
-
- //llinfos << "Releasing" << llendl;
-
- // cleanup mesh data
- for (std::vector<LLViewerJoint*>::iterator iter = mMeshLOD.begin();
- iter != mMeshLOD.end();
- ++iter)
- {
- LLViewerJoint* joint = (LLViewerJoint*) *iter;
- joint->setValid(FALSE, TRUE);
- }
-
- //cleanup data
- if (mDrawable.notNull())
- {
- LLFace* facep = mDrawable->getFace(0);
- facep->setSize(0, 0);
- for(S32 i = mNumInitFaces ; i < mDrawable->getNumFaces(); i++)
- {
- facep = mDrawable->getFace(i);
- facep->setSize(0, 0);
- }
- }
-
- for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
- if (!attachment->getIsHUDAttachment())
- {
- attachment->setAttachmentVisibility(FALSE);
- }
- }
- mMeshValid = FALSE;
-}
-
-//-----------------------------------------------------------------------------
-// restoreMeshData()
-//-----------------------------------------------------------------------------
-// virtual
-void LLVOAvatar::restoreMeshData()
-{
- llassert(!isSelf());
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- //llinfos << "Restoring" << llendl;
- mMeshValid = TRUE;
- updateJointLODs();
-
- for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
- if (!attachment->getIsHUDAttachment())
- {
- attachment->setAttachmentVisibility(TRUE);
- }
- }
-
- // force mesh update as LOD might not have changed to trigger this
- gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_GEOMETRY, TRUE);
-}
-
-//-----------------------------------------------------------------------------
-// updateMeshData()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::updateMeshData()
-{
- if (mDrawable.notNull())
- {
- stop_glerror();
-
- S32 f_num = 0 ;
- const U32 VERTEX_NUMBER_THRESHOLD = 128 ;//small number of this means each part of an avatar has its own vertex buffer.
- const S32 num_parts = mMeshLOD.size();
-
- // this order is determined by number of LODS
- // if a mesh earlier in this list changed LODs while a later mesh doesn't,
- // the later mesh's index offset will be inaccurate
- for(S32 part_index = 0 ; part_index < num_parts ;)
- {
- S32 j = part_index ;
- U32 last_v_num = 0, num_vertices = 0 ;
- U32 last_i_num = 0, num_indices = 0 ;
-
- while(part_index < num_parts && num_vertices < VERTEX_NUMBER_THRESHOLD)
- {
- last_v_num = num_vertices ;
- last_i_num = num_indices ;
-
- mMeshLOD[part_index++]->updateFaceSizes(num_vertices, num_indices, mAdjustedPixelArea);
- }
- if(num_vertices < 1)//skip empty meshes
- {
- continue ;
- }
- if(last_v_num > 0)//put the last inserted part into next vertex buffer.
- {
- num_vertices = last_v_num ;
- num_indices = last_i_num ;
- part_index-- ;
- }
-
- LLFace* facep ;
- if(f_num < mDrawable->getNumFaces())
- {
- facep = mDrawable->getFace(f_num);
- }
- else
- {
- facep = mDrawable->addFace(mDrawable->getFace(0)->getPool(), mDrawable->getFace(0)->getTexture()) ;
- }
-
- // resize immediately
- facep->setSize(num_vertices, num_indices);
-
- bool terse_update = false;
-
- if(facep->mVertexBuffer.isNull())
- {
- facep->mVertexBuffer = new LLVertexBufferAvatar();
- facep->mVertexBuffer->allocateBuffer(num_vertices, num_indices, TRUE);
- }
- else
- {
- if (facep->mVertexBuffer->getRequestedIndices() == num_indices &&
- facep->mVertexBuffer->getRequestedVerts() == num_vertices)
- {
- terse_update = true;
- }
- else
- {
- facep->mVertexBuffer->resizeBuffer(num_vertices, num_indices) ;
- }
- }
-
- facep->setGeomIndex(0);
- facep->setIndicesIndex(0);
-
- // This is a hack! Avatars have their own pool, so we are detecting
- // the case of more than one avatar in the pool (thus > 0 instead of >= 0)
- if (facep->getGeomIndex() > 0)
- {
- llerrs << "non-zero geom index: " << facep->getGeomIndex() << " in LLVOAvatar::restoreMeshData" << llendl;
- }
-
- for(S32 k = j ; k < part_index ; k++)
- {
- mMeshLOD[k]->updateFaceData(facep, mAdjustedPixelArea, k == MESH_ID_HAIR, terse_update);
- }
-
- stop_glerror();
- facep->mVertexBuffer->setBuffer(0);
-
- if(!f_num)
- {
- f_num += mNumInitFaces ;
- }
- else
- {
- f_num++ ;
- }
- }
- }
-}
-
-//------------------------------------------------------------------------
-
-//------------------------------------------------------------------------
-// The viewer can only suggest a good size for the agent,
-// the simulator will keep it inside a reasonable range.
-void LLVOAvatar::computeBodySize()
-{
- LLVector3 pelvis_scale = mPelvisp->getScale();
-
- // some of the joints have not been cached
- LLVector3 skull = mSkullp->getPosition();
- LLVector3 skull_scale = mSkullp->getScale();
-
- LLVector3 neck = mNeckp->getPosition();
- LLVector3 neck_scale = mNeckp->getScale();
-
- LLVector3 chest = mChestp->getPosition();
- LLVector3 chest_scale = mChestp->getScale();
-
- // the rest of the joints have been cached
- LLVector3 head = mHeadp->getPosition();
- LLVector3 head_scale = mHeadp->getScale();
-
- LLVector3 torso = mTorsop->getPosition();
- LLVector3 torso_scale = mTorsop->getScale();
-
- LLVector3 hip = mHipLeftp->getPosition();
- LLVector3 hip_scale = mHipLeftp->getScale();
-
- LLVector3 knee = mKneeLeftp->getPosition();
- LLVector3 knee_scale = mKneeLeftp->getScale();
-
- LLVector3 ankle = mAnkleLeftp->getPosition();
- LLVector3 ankle_scale = mAnkleLeftp->getScale();
-
- LLVector3 foot = mFootLeftp->getPosition();
-
- mPelvisToFoot = hip.mV[VZ] * pelvis_scale.mV[VZ] -
- knee.mV[VZ] * hip_scale.mV[VZ] -
- ankle.mV[VZ] * knee_scale.mV[VZ] -
- foot.mV[VZ] * ankle_scale.mV[VZ];
-
- LLVector3 new_body_size;
- new_body_size.mV[VZ] = mPelvisToFoot +
- // the sqrt(2) correction below is an approximate
- // correction to get to the top of the head
- F_SQRT2 * (skull.mV[VZ] * head_scale.mV[VZ]) +
- head.mV[VZ] * neck_scale.mV[VZ] +
- neck.mV[VZ] * chest_scale.mV[VZ] +
- chest.mV[VZ] * torso_scale.mV[VZ] +
- torso.mV[VZ] * pelvis_scale.mV[VZ];
-
- // TODO -- measure the real depth and width
- new_body_size.mV[VX] = DEFAULT_AGENT_DEPTH;
- new_body_size.mV[VY] = DEFAULT_AGENT_WIDTH;
-
- if (new_body_size != mBodySize)
- {
- mBodySize = new_body_size;
-
- if (isSelf() && !LLAppearanceMgr::instance().isInUpdateAppearanceFromCOF())
- { // notify simulator of change in size
- // but not if we are in the middle of updating appearance
- gAgent.sendAgentSetAppearance();
- }
- }
-}
-
-//------------------------------------------------------------------------
-// LLVOAvatar::processUpdateMessage()
-//------------------------------------------------------------------------
-U32 LLVOAvatar::processUpdateMessage(LLMessageSystem *mesgsys,
- void **user_data,
- U32 block_num, const EObjectUpdateType update_type,
- LLDataPacker *dp)
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- LLVector3 old_vel = getVelocity();
- const BOOL has_name = !getNVPair("FirstName");
-
- // Do base class updates...
- U32 retval = LLViewerObject::processUpdateMessage(mesgsys, user_data, block_num, update_type, dp);
-
- // Print out arrival information once we have name of avatar.
- if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
- {
- if (has_name && getNVPair("FirstName"))
- {
- mDebugExistenceTimer.reset();
- LLSD args;
- args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
- args["NAME"] = getFullname();
- LLNotificationsUtil::add("AvatarRezArrivedNotification",args);
- llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' arrived." << llendl;
- }
- }
- if(retval & LLViewerObject::INVALID_UPDATE)
- {
- if (isSelf())
- {
- //tell sim to cancel this update
- gAgent.teleportViaLocation(gAgent.getPositionGlobal());
- }
- }
-
- //llinfos << getRotation() << llendl;
- //llinfos << getPosition() << llendl;
-
- return retval;
-}
-
-// virtual
-S32 LLVOAvatar::setTETexture(const U8 te, const LLUUID& uuid)
-{
- // The core setTETexture() method requests images, so we need
- // to redirect certain avatar texture requests to different sims.
- if (isIndexBakedTexture((ETextureIndex)te))
- {
- LLHost target_host = getObjectHost();
- return setTETextureCore(te, uuid, target_host);
- }
- else
- {
- return setTETextureCore(te, uuid, LLHost::invalid);
- }
-}
-
-static LLFastTimer::DeclareTimer FTM_AVATAR_UPDATE("Update Avatar");
-static LLFastTimer::DeclareTimer FTM_JOINT_UPDATE("Update Joints");
-
-//------------------------------------------------------------------------
-// LLVOAvatar::dumpAnimationState()
-//------------------------------------------------------------------------
-void LLVOAvatar::dumpAnimationState()
-{
- llinfos << "==============================================" << llendl;
- for (LLVOAvatar::AnimIterator it = mSignaledAnimations.begin(); it != mSignaledAnimations.end(); ++it)
- {
- LLUUID id = it->first;
- std::string playtag = "";
- if (mPlayingAnimations.find(id) != mPlayingAnimations.end())
- {
- playtag = "*";
- }
- llinfos << gAnimLibrary.animationName(id) << playtag << llendl;
- }
- for (LLVOAvatar::AnimIterator it = mPlayingAnimations.begin(); it != mPlayingAnimations.end(); ++it)
- {
- LLUUID id = it->first;
- bool is_signaled = mSignaledAnimations.find(id) != mSignaledAnimations.end();
- if (!is_signaled)
- {
- llinfos << gAnimLibrary.animationName(id) << "!S" << llendl;
- }
- }
-}
-
-//------------------------------------------------------------------------
-// idleUpdate()
-//------------------------------------------------------------------------
-BOOL LLVOAvatar::idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time)
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
- LLFastTimer t(FTM_AVATAR_UPDATE);
-
- if (isDead())
- {
- llinfos << "Warning! Idle on dead avatar" << llendl;
- return TRUE;
- }
-
- if (!(gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_AVATAR)))
- {
- return TRUE;
- }
-
- checkTextureLoading() ;
-
- // force immediate pixel area update on avatars using last frames data (before drawable or camera updates)
- setPixelAreaAndAngle(gAgent);
-
- // force asynchronous drawable update
- if(mDrawable.notNull() && !gNoRender)
- {
- LLFastTimer t(FTM_JOINT_UPDATE);
-
- if (mIsSitting && getParent())
- {
- LLViewerObject *root_object = (LLViewerObject*)getRoot();
- LLDrawable* drawablep = root_object->mDrawable;
- // if this object hasn't already been updated by another avatar...
- if (drawablep) // && !drawablep->isState(LLDrawable::EARLY_MOVE))
- {
- if (root_object->isSelected())
- {
- gPipeline.updateMoveNormalAsync(drawablep);
- }
- else
- {
- gPipeline.updateMoveDampedAsync(drawablep);
- }
- }
- }
- else
- {
- gPipeline.updateMoveDampedAsync(mDrawable);
- }
- }
-
- //--------------------------------------------------------------------
- // set alpha flag depending on state
- //--------------------------------------------------------------------
-
- if (isSelf())
- {
- LLViewerObject::idleUpdate(agent, world, time);
-
- // trigger fidget anims
- if (isAnyAnimationSignaled(AGENT_STAND_ANIMS, NUM_AGENT_STAND_ANIMS))
- {
- agent.fidget();
- }
- }
- else
- {
- // Should override the idleUpdate stuff and leave out the angular update part.
- LLQuaternion rotation = getRotation();
- LLViewerObject::idleUpdate(agent, world, time);
- setRotation(rotation);
- }
-
- // attach objects that were waiting for a drawable
- lazyAttach();
-
- // animate the character
- // store off last frame's root position to be consistent with camera position
- LLVector3 root_pos_last = mRoot.getWorldPosition();
- BOOL detailed_update = updateCharacter(agent);
-
- if (gNoRender)
- {
- return TRUE;
- }
-
- static LLUICachedControl<bool> visualizers_in_calls("ShowVoiceVisualizersInCalls", false);
- bool voice_enabled = (visualizers_in_calls || LLVoiceClient::getInstance()->inProximalChannel()) &&
- LLVoiceClient::getInstance()->getVoiceEnabled(mID);
-
- idleUpdateVoiceVisualizer( voice_enabled );
- idleUpdateMisc( detailed_update );
- idleUpdateAppearanceAnimation();
- if (detailed_update)
- {
- idleUpdateLipSync( voice_enabled );
- idleUpdateLoadingEffect();
- idleUpdateBelowWater(); // wind effect uses this
- idleUpdateWindEffect();
- }
-
- idleUpdateNameTag( root_pos_last );
- idleUpdateRenderCost();
-
- return TRUE;
-}
-
-void LLVOAvatar::idleUpdateVoiceVisualizer(bool voice_enabled)
-{
- bool render_visualizer = voice_enabled;
-
- // Don't render the user's own voice visualizer when in mouselook, or when opening the mic is disabled.
- if(isSelf())
- {
- if(gAgentCamera.cameraMouselook() || gSavedSettings.getBOOL("VoiceDisableMic"))
- {
- render_visualizer = false;
- }
- }
-
- mVoiceVisualizer->setVoiceEnabled(render_visualizer);
-
- if ( voice_enabled )
- {
- //----------------------------------------------------------------
- // Only do gesture triggering for your own avatar, and only when you're in a proximal channel.
- //----------------------------------------------------------------
- if( isSelf() )
- {
- //----------------------------------------------------------------------------------------
- // The following takes the voice signal and uses that to trigger gesticulations.
- //----------------------------------------------------------------------------------------
- int lastGesticulationLevel = mCurrentGesticulationLevel;
- mCurrentGesticulationLevel = mVoiceVisualizer->getCurrentGesticulationLevel();
-
- //---------------------------------------------------------------------------------------------------
- // If "current gesticulation level" changes, we catch this, and trigger the new gesture
- //---------------------------------------------------------------------------------------------------
- if ( lastGesticulationLevel != mCurrentGesticulationLevel )
- {
- if ( mCurrentGesticulationLevel != VOICE_GESTICULATION_LEVEL_OFF )
- {
- std::string gestureString = "unInitialized";
- if ( mCurrentGesticulationLevel == 0 ) { gestureString = "/voicelevel1"; }
- else if ( mCurrentGesticulationLevel == 1 ) { gestureString = "/voicelevel2"; }
- else if ( mCurrentGesticulationLevel == 2 ) { gestureString = "/voicelevel3"; }
- else { llinfos << "oops - CurrentGesticulationLevel can be only 0, 1, or 2" << llendl; }
-
- // this is the call that Karl S. created for triggering gestures from within the code.
- LLGestureMgr::instance().triggerAndReviseString( gestureString );
- }
- }
-
- } //if( isSelf() )
-
- //-----------------------------------------------------------------------------------------------------------------
- // If the avatar is speaking, then the voice amplitude signal is passed to the voice visualizer.
- // Also, here we trigger voice visualizer start and stop speaking, so it can animate the voice symbol.
- //
- // Notice the calls to "gAwayTimer.reset()". This resets the timer that determines how long the avatar has been
- // "away", so that the avatar doesn't lapse into away-mode (and slump over) while the user is still talking.
- //-----------------------------------------------------------------------------------------------------------------
- if (LLVoiceClient::getInstance()->getIsSpeaking( mID ))
- {
- if (!mVoiceVisualizer->getCurrentlySpeaking())
- {
- mVoiceVisualizer->setStartSpeaking();
-
- //printf( "gAwayTimer.reset();\n" );
- }
-
- mVoiceVisualizer->setSpeakingAmplitude( LLVoiceClient::getInstance()->getCurrentPower( mID ) );
-
- if( isSelf() )
- {
- gAgent.clearAFK();
- }
- }
- else
- {
- if ( mVoiceVisualizer->getCurrentlySpeaking() )
- {
- mVoiceVisualizer->setStopSpeaking();
-
- if ( mLipSyncActive )
- {
- if( mOohMorph ) mOohMorph->setWeight(mOohMorph->getMinWeight(), FALSE);
- if( mAahMorph ) mAahMorph->setWeight(mAahMorph->getMinWeight(), FALSE);
-
- mLipSyncActive = false;
- LLCharacter::updateVisualParams();
- dirtyMesh();
- }
- }
- }
-
- //--------------------------------------------------------------------------------------------
- // here we get the approximate head position and set as sound source for the voice symbol
- // (the following version uses a tweak of "mHeadOffset" which handle sitting vs. standing)
- //--------------------------------------------------------------------------------------------
- LLVector3 headOffset = LLVector3( 0.0f, 0.0f, mHeadOffset.mV[2] );
- mVoiceVisualizer->setVoiceSourceWorldPosition( mRoot.getWorldPosition() + headOffset );
-
- }//if ( voiceEnabled )
-}
-
-static LLFastTimer::DeclareTimer FTM_ATTACHMENT_UPDATE("Update Attachments");
-
-void LLVOAvatar::idleUpdateMisc(bool detailed_update)
-{
- if (LLVOAvatar::sJointDebug)
- {
- llinfos << getFullname() << ": joint touches: " << LLJoint::sNumTouches << " updates: " << LLJoint::sNumUpdates << llendl;
- }
-
- LLJoint::sNumUpdates = 0;
- LLJoint::sNumTouches = 0;
-
- BOOL visible = isVisible() || mNeedsAnimUpdate;
-
- // update attachments positions
- if (detailed_update || !sUseImpostors)
- {
- LLFastTimer t(FTM_ATTACHMENT_UPDATE);
- for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
-
- for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
- attachment_iter != attachment->mAttachedObjects.end();
- ++attachment_iter)
- {
- LLViewerObject* attached_object = (*attachment_iter);
- BOOL visibleAttachment = visible || (attached_object &&
- !(attached_object->mDrawable->getSpatialBridge() &&
- attached_object->mDrawable->getSpatialBridge()->getRadius() < 2.0));
-
- if (visibleAttachment && attached_object && !attached_object->isDead() && attachment->getValid())
- {
- // if selecting any attachments, update all of them as non-damped
- if (LLSelectMgr::getInstance()->getSelection()->getObjectCount() && LLSelectMgr::getInstance()->getSelection()->isAttachment())
- {
- gPipeline.updateMoveNormalAsync(attached_object->mDrawable);
- }
- else
- {
- gPipeline.updateMoveDampedAsync(attached_object->mDrawable);
- }
-
- LLSpatialBridge* bridge = attached_object->mDrawable->getSpatialBridge();
- if (bridge)
- {
- gPipeline.updateMoveNormalAsync(bridge);
- }
- attached_object->updateText();
- }
- }
- }
- }
-
- mNeedsAnimUpdate = FALSE;
-
- if (isImpostor() && !mNeedsImpostorUpdate)
- {
- LLVector3 ext[2];
- F32 distance;
- LLVector3 angle;
-
- getImpostorValues(ext, angle, distance);
-
- for (U32 i = 0; i < 3 && !mNeedsImpostorUpdate; i++)
- {
- F32 cur_angle = angle.mV[i];
- F32 old_angle = mImpostorAngle.mV[i];
- F32 angle_diff = fabsf(cur_angle-old_angle);
-
- if (angle_diff > F_PI/512.f*distance*mUpdatePeriod)
- {
- mNeedsImpostorUpdate = TRUE;
- }
- }
-
- if (detailed_update && !mNeedsImpostorUpdate)
- { //update impostor if view angle, distance, or bounding box change
- //significantly
-
- F32 dist_diff = fabsf(distance-mImpostorDistance);
- if (dist_diff/mImpostorDistance > 0.1f)
- {
- mNeedsImpostorUpdate = TRUE;
- }
- else
- {
- getSpatialExtents(ext[0], ext[1]);
- if ((ext[1]-mImpostorExtents[1]).length() > 0.05f ||
- (ext[0]-mImpostorExtents[0]).length() > 0.05f)
- {
- mNeedsImpostorUpdate = TRUE;
- }
- }
- }
- }
-
- mDrawable->movePartition();
-
- //force a move if sitting on an active object
- if (getParent() && ((LLViewerObject*) getParent())->mDrawable->isActive())
- {
- gPipeline.markMoved(mDrawable, TRUE);
- }
-}
-
-void LLVOAvatar::idleUpdateAppearanceAnimation()
-{
- // update morphing params
- if (mAppearanceAnimating)
- {
- ESex avatar_sex = getSex();
- F32 appearance_anim_time = mAppearanceMorphTimer.getElapsedTimeF32();
- if (appearance_anim_time >= APPEARANCE_MORPH_TIME)
- {
- mAppearanceAnimating = FALSE;
- for (LLVisualParam *param = getFirstVisualParam();
- param;
- param = getNextVisualParam())
- {
- if (param->isTweakable())
- {
- param->stopAnimating(FALSE);
- }
- }
- updateVisualParams();
- if (isSelf())
- {
- gAgent.sendAgentSetAppearance();
- }
- }
- else
- {
- F32 morph_amt = calcMorphAmount();
- LLVisualParam *param;
-
- if (!isSelf())
- {
- // animate only top level params for non-self avatars
- for (param = getFirstVisualParam();
- param;
- param = getNextVisualParam())
- {
- if (param->isTweakable())
- {
- param->animate(morph_amt, FALSE);
- }
- }
- }
-
- // apply all params
- for (param = getFirstVisualParam();
- param;
- param = getNextVisualParam())
- {
- param->apply(avatar_sex);
- }
-
- mLastAppearanceBlendTime = appearance_anim_time;
- }
- dirtyMesh();
- }
-}
-
-F32 LLVOAvatar::calcMorphAmount()
-{
- F32 appearance_anim_time = mAppearanceMorphTimer.getElapsedTimeF32();
- F32 blend_frac = calc_bouncy_animation(appearance_anim_time / APPEARANCE_MORPH_TIME);
- F32 last_blend_frac = calc_bouncy_animation(mLastAppearanceBlendTime / APPEARANCE_MORPH_TIME);
-
- F32 morph_amt;
- if (last_blend_frac == 1.f)
- {
- morph_amt = 1.f;
- }
- else
- {
- morph_amt = (blend_frac - last_blend_frac) / (1.f - last_blend_frac);
- }
-
- return morph_amt;
-}
-
-void LLVOAvatar::idleUpdateLipSync(bool voice_enabled)
-{
- // Use the Lipsync_Ooh and Lipsync_Aah morphs for lip sync
- if ( voice_enabled && (LLVoiceClient::getInstance()->lipSyncEnabled()) && LLVoiceClient::getInstance()->getIsSpeaking( mID ) )
- {
- F32 ooh_morph_amount = 0.0f;
- F32 aah_morph_amount = 0.0f;
-
- mVoiceVisualizer->lipSyncOohAah( ooh_morph_amount, aah_morph_amount );
-
- if( mOohMorph )
- {
- F32 ooh_weight = mOohMorph->getMinWeight()
- + ooh_morph_amount * (mOohMorph->getMaxWeight() - mOohMorph->getMinWeight());
-
- mOohMorph->setWeight( ooh_weight, FALSE );
- }
-
- if( mAahMorph )
- {
- F32 aah_weight = mAahMorph->getMinWeight()
- + aah_morph_amount * (mAahMorph->getMaxWeight() - mAahMorph->getMinWeight());
-
- mAahMorph->setWeight( aah_weight, FALSE );
- }
-
- mLipSyncActive = true;
- LLCharacter::updateVisualParams();
- dirtyMesh();
- }
-}
-
-void LLVOAvatar::idleUpdateLoadingEffect()
-{
- // update visibility when avatar is partially loaded
- if (updateIsFullyLoaded()) // changed?
- {
- if (isFullyLoaded() && isSelf())
- {
- static bool first_fully_visible = true;
- if (first_fully_visible)
- {
- llinfos << "self isFullyLoaded, first_fully_visible" << llendl;
-
- first_fully_visible = false;
- LLAppearanceMgr::instance().onFirstFullyVisible();
- }
- }
- if (isFullyLoaded())
- {
- deleteParticleSource();
- updateLOD();
- }
- else
- {
- LLPartSysData particle_parameters;
-
- // fancy particle cloud designed by Brent
- particle_parameters.mPartData.mMaxAge = 4.f;
- particle_parameters.mPartData.mStartScale.mV[VX] = 0.8f;
- particle_parameters.mPartData.mStartScale.mV[VX] = 0.8f;
- particle_parameters.mPartData.mStartScale.mV[VY] = 1.0f;
- particle_parameters.mPartData.mEndScale.mV[VX] = 0.02f;
- particle_parameters.mPartData.mEndScale.mV[VY] = 0.02f;
- particle_parameters.mPartData.mStartColor = LLColor4(1, 1, 1, 0.5f);
- particle_parameters.mPartData.mEndColor = LLColor4(1, 1, 1, 0.0f);
- particle_parameters.mPartData.mStartScale.mV[VX] = 0.8f;
- LLViewerTexture* cloud = LLViewerTextureManager::getFetchedTextureFromFile("cloud-particle.j2c");
- particle_parameters.mPartImageID = cloud->getID();
- particle_parameters.mMaxAge = 0.f;
- particle_parameters.mPattern = LLPartSysData::LL_PART_SRC_PATTERN_ANGLE_CONE;
- particle_parameters.mInnerAngle = F_PI;
- particle_parameters.mOuterAngle = 0.f;
- particle_parameters.mBurstRate = 0.02f;
- particle_parameters.mBurstRadius = 0.0f;
- particle_parameters.mBurstPartCount = 1;
- particle_parameters.mBurstSpeedMin = 0.1f;
- particle_parameters.mBurstSpeedMax = 1.f;
- particle_parameters.mPartData.mFlags = ( LLPartData::LL_PART_INTERP_COLOR_MASK | LLPartData::LL_PART_INTERP_SCALE_MASK |
- LLPartData::LL_PART_EMISSIVE_MASK | // LLPartData::LL_PART_FOLLOW_SRC_MASK |
- LLPartData::LL_PART_TARGET_POS_MASK );
-
- setParticleSource(particle_parameters, getID());
- }
- }
-}
-
-void LLVOAvatar::idleUpdateWindEffect()
-{
- // update wind effect
- if ((LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_AVATAR) >= LLDrawPoolAvatar::SHADER_LEVEL_CLOTH))
- {
- F32 hover_strength = 0.f;
- F32 time_delta = mRippleTimer.getElapsedTimeF32() - mRippleTimeLast;
- mRippleTimeLast = mRippleTimer.getElapsedTimeF32();
- LLVector3 velocity = getVelocity();
- F32 speed = velocity.length();
- //RN: velocity varies too much frame to frame for this to work
- mRippleAccel.clearVec();//lerp(mRippleAccel, (velocity - mLastVel) * time_delta, LLCriticalDamp::getInterpolant(0.02f));
- mLastVel = velocity;
- LLVector4 wind;
- wind.setVec(getRegion()->mWind.getVelocityNoisy(getPositionAgent(), 4.f) - velocity);
-
- if (mInAir)
- {
- hover_strength = HOVER_EFFECT_STRENGTH * llmax(0.f, HOVER_EFFECT_MAX_SPEED - speed);
- }
-
- if (mBelowWater)
- {
- // TODO: make cloth flow more gracefully when underwater
- hover_strength += UNDERWATER_EFFECT_STRENGTH;
- }
-
- wind.mV[VZ] += hover_strength;
- wind.normalize();
-
- wind.mV[VW] = llmin(0.025f + (speed * 0.015f) + hover_strength, 0.5f);
- F32 interp;
- if (wind.mV[VW] > mWindVec.mV[VW])
- {
- interp = LLCriticalDamp::getInterpolant(0.2f);
- }
- else
- {
- interp = LLCriticalDamp::getInterpolant(0.4f);
- }
- mWindVec = lerp(mWindVec, wind, interp);
-
- F32 wind_freq = hover_strength + llclamp(8.f + (speed * 0.7f) + (noise1(mRipplePhase) * 4.f), 8.f, 25.f);
- mWindFreq = lerp(mWindFreq, wind_freq, interp);
-
- if (mBelowWater)
- {
- mWindFreq *= UNDERWATER_FREQUENCY_DAMP;
- }
-
- mRipplePhase += (time_delta * mWindFreq);
- if (mRipplePhase > F_TWO_PI)
- {
- mRipplePhase = fmodf(mRipplePhase, F_TWO_PI);
- }
- }
-}
-
-void LLVOAvatar::idleUpdateNameTag(const LLVector3& root_pos_last)
-{
- // update chat bubble
- //--------------------------------------------------------------------
- // draw text label over character's head
- //--------------------------------------------------------------------
- if (mChatTimer.getElapsedTimeF32() > BUBBLE_CHAT_TIME)
- {
- mChats.clear();
- }
-
- const F32 time_visible = mTimeVisible.getElapsedTimeF32();
- const F32 NAME_SHOW_TIME = gSavedSettings.getF32("RenderNameShowTime"); // seconds
- const F32 FADE_DURATION = gSavedSettings.getF32("RenderNameFadeDuration"); // seconds
- BOOL visible_avatar = isVisible() || mNeedsAnimUpdate;
- BOOL visible_chat = gSavedSettings.getBOOL("UseChatBubbles") && (mChats.size() || mTyping);
- BOOL render_name = visible_chat ||
- (visible_avatar &&
- ((sRenderName == RENDER_NAME_ALWAYS) ||
- (sRenderName == RENDER_NAME_FADE && time_visible < NAME_SHOW_TIME)));
- // If it's your own avatar, don't draw in mouselook, and don't
- // draw if we're specifically hiding our own name.
- if (isSelf())
- {
- render_name = render_name
- && !gAgentCamera.cameraMouselook()
- && (visible_chat || (gSavedSettings.getBOOL("RenderNameShowSelf")
- && gSavedSettings.getS32("AvatarNameTagMode") ));
- }
-
- if ( !render_name )
- {
- if (mNameText)
- {
- // ...clean up old name tag
- mNameText->markDead();
- mNameText = NULL;
- sNumVisibleChatBubbles--;
- }
- return;
- }
-
- BOOL new_name = FALSE;
- if (visible_chat != mVisibleChat)
- {
- mVisibleChat = visible_chat;
- new_name = TRUE;
- }
-
- if (sRenderGroupTitles != mRenderGroupTitles)
- {
- mRenderGroupTitles = sRenderGroupTitles;
- new_name = TRUE;
- }
-
- // First Calculate Alpha
- // If alpha > 0, create mNameText if necessary, otherwise delete it
- F32 alpha = 0.f;
- if (mAppAngle > 5.f)
- {
- const F32 START_FADE_TIME = NAME_SHOW_TIME - FADE_DURATION;
- if (!visible_chat && sRenderName == RENDER_NAME_FADE && time_visible > START_FADE_TIME)
- {
- alpha = 1.f - (time_visible - START_FADE_TIME) / FADE_DURATION;
- }
- else
- {
- // ...not fading, full alpha
- alpha = 1.f;
- }
- }
- else if (mAppAngle > 2.f)
- {
- // far away is faded out also
- alpha = (mAppAngle-2.f)/3.f;
- }
-
- if (alpha <= 0.f)
- {
- if (mNameText)
- {
- mNameText->markDead();
- mNameText = NULL;
- sNumVisibleChatBubbles--;
- }
- return;
- }
-
- if (!mNameText)
- {
- mNameText = static_cast<LLHUDNameTag*>( LLHUDObject::addHUDObject(
- LLHUDObject::LL_HUD_NAME_TAG) );
- //mNameText->setMass(10.f);
- mNameText->setSourceObject(this);
- mNameText->setVertAlignment(LLHUDNameTag::ALIGN_VERT_TOP);
- mNameText->setVisibleOffScreen(TRUE);
- mNameText->setMaxLines(11);
- mNameText->setFadeDistance(CHAT_NORMAL_RADIUS, 5.f);
- sNumVisibleChatBubbles++;
- new_name = TRUE;
- }
-
- LLVector3 name_position = idleUpdateNameTagPosition(root_pos_last);
- mNameText->setPositionAgent(name_position);
-
- idleUpdateNameTagText(new_name);
-
- idleUpdateNameTagAlpha(new_name, alpha);
-}
-
-void LLVOAvatar::idleUpdateNameTagText(BOOL new_name)
- {
- LLNameValue *title = getNVPair("Title");
- LLNameValue* firstname = getNVPair("FirstName");
- LLNameValue* lastname = getNVPair("LastName");
-
- // Avatars must have a first and last name
- if (!firstname || !lastname) return;
-
- bool is_away = mSignaledAnimations.find(ANIM_AGENT_AWAY) != mSignaledAnimations.end();
- bool is_busy = mSignaledAnimations.find(ANIM_AGENT_BUSY) != mSignaledAnimations.end();
- bool is_appearance = mSignaledAnimations.find(ANIM_AGENT_CUSTOMIZE) != mSignaledAnimations.end();
- bool is_muted;
- if (isSelf())
- {
- is_muted = false;
- }
- else
- {
- is_muted = LLMuteList::getInstance()->isMuted(getID());
- }
- bool is_friend = LLAvatarTracker::instance().isBuddy(getID());
- bool is_cloud = getIsCloud();
-
- if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
- {
- if (is_appearance != mNameAppearance)
- {
- if (is_appearance)
- {
- LLSD args;
- args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
- args["NAME"] = getFullname();
- LLNotificationsUtil::add("AvatarRezEnteredAppearanceNotification",args);
- llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' entered appearance mode." << llendl;
- }
- else
- {
- LLSD args;
- args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
- args["NAME"] = getFullname();
- LLNotificationsUtil::add("AvatarRezLeftAppearanceNotification",args);
- llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' left appearance mode." << llendl;
- }
- }
- }
-
- // Rebuild name tag if state change detected
- if (mNameString.empty()
- || new_name
- || (!title && !mTitle.empty())
- || (title && mTitle != title->getString())
- || is_away != mNameAway
- || is_busy != mNameBusy
- || is_muted != mNameMute
- || is_appearance != mNameAppearance
- || is_friend != mNameFriend
- || is_cloud != mNameCloud)
- {
- LLColor4 name_tag_color = getNameTagColor(is_friend);
-
- clearNameTag();
-
- if (is_away || is_muted || is_busy || is_appearance)
- {
- std::string line;
- if (is_away)
- {
- line += LLTrans::getString("AvatarAway");
- line += ", ";
- }
- if (is_busy)
- {
- line += LLTrans::getString("AvatarBusy");
- line += ", ";
- }
- if (is_muted)
- {
- line += LLTrans::getString("AvatarMuted");
- line += ", ";
- }
- if (is_appearance)
- {
- line += LLTrans::getString("AvatarEditingAppearance");
- line += ", ";
- }
- if (is_cloud)
- {
- line += LLTrans::getString("LoadingData");
- line += ", ";
- }
- // trim last ", "
- line.resize( line.length() - 2 );
- addNameTagLine(line, name_tag_color, LLFontGL::NORMAL,
- LLFontGL::getFontSansSerifSmall());
- }
-
- if (sRenderGroupTitles
- && title && title->getString() && title->getString()[0] != '\0')
- {
- std::string title_str = title->getString();
- LLStringFn::replace_ascii_controlchars(title_str,LL_UNKNOWN_CHAR);
- addNameTagLine(title_str, name_tag_color, LLFontGL::NORMAL,
- LLFontGL::getFontSansSerifSmall());
- }
-
- static LLUICachedControl<bool> show_display_names("NameTagShowDisplayNames");
- static LLUICachedControl<bool> show_usernames("NameTagShowUsernames");
-
- if (LLAvatarNameCache::useDisplayNames())
- {
- LLAvatarName av_name;
- if (!LLAvatarNameCache::get(getID(), &av_name))
- {
- // ...call this function back when the name arrives
- // and force a rebuild
- LLAvatarNameCache::get(getID(),
- boost::bind(&LLVOAvatar::clearNameTag, this));
- }
-
- // Might be blank if name not available yet, that's OK
- if (show_display_names)
- {
- addNameTagLine(av_name.mDisplayName, name_tag_color, LLFontGL::NORMAL,
- LLFontGL::getFontSansSerif());
- }
- // Suppress SLID display if display name matches exactly (ugh)
- if (show_usernames && !av_name.mIsDisplayNameDefault)
- {
- // *HACK: Desaturate the color
- LLColor4 username_color = name_tag_color * 0.83f;
- addNameTagLine(av_name.mUsername, username_color, LLFontGL::NORMAL,
- LLFontGL::getFontSansSerifSmall());
- }
- }
- else
- {
- const LLFontGL* font = LLFontGL::getFontSansSerif();
- std::string full_name =
- LLCacheName::buildFullName( firstname->getString(), lastname->getString() );
- addNameTagLine(full_name, name_tag_color, LLFontGL::NORMAL, font);
- }
-
- mNameAway = is_away;
- mNameBusy = is_busy;
- mNameMute = is_muted;
- mNameAppearance = is_appearance;
- mNameFriend = is_friend;
- mNameCloud = is_cloud;
- mTitle = title ? title->getString() : "";
- LLStringFn::replace_ascii_controlchars(mTitle,LL_UNKNOWN_CHAR);
- new_name = TRUE;
- }
-
- if (mVisibleChat)
- {
- mNameText->setFont(LLFontGL::getFontSansSerif());
- mNameText->setTextAlignment(LLHUDNameTag::ALIGN_TEXT_LEFT);
- mNameText->setFadeDistance(CHAT_NORMAL_RADIUS * 2.f, 5.f);
-
- char line[MAX_STRING]; /* Flawfinder: ignore */
- line[0] = '\0';
- std::deque<LLChat>::iterator chat_iter = mChats.begin();
- mNameText->clearString();
-
- LLColor4 new_chat = LLUIColorTable::instance().getColor( isSelf() ? "UserChatColor" : "AgentChatColor" );
- LLColor4 normal_chat = lerp(new_chat, LLColor4(0.8f, 0.8f, 0.8f, 1.f), 0.7f);
- LLColor4 old_chat = lerp(normal_chat, LLColor4(0.6f, 0.6f, 0.6f, 1.f), 0.7f);
- if (mTyping && mChats.size() >= MAX_BUBBLE_CHAT_UTTERANCES)
- {
- ++chat_iter;
- }
-
- for(; chat_iter != mChats.end(); ++chat_iter)
- {
- F32 chat_fade_amt = llclamp((F32)((LLFrameTimer::getElapsedSeconds() - chat_iter->mTime) / CHAT_FADE_TIME), 0.f, 4.f);
- LLFontGL::StyleFlags style;
- switch(chat_iter->mChatType)
- {
- case CHAT_TYPE_WHISPER:
- style = LLFontGL::ITALIC;
- break;
- case CHAT_TYPE_SHOUT:
- style = LLFontGL::BOLD;
- break;
- default:
- style = LLFontGL::NORMAL;
- break;
- }
- if (chat_fade_amt < 1.f)
- {
- F32 u = clamp_rescale(chat_fade_amt, 0.9f, 1.f, 0.f, 1.f);
- mNameText->addLine(chat_iter->mText, lerp(new_chat, normal_chat, u), style);
- }
- else if (chat_fade_amt < 2.f)
- {
- F32 u = clamp_rescale(chat_fade_amt, 1.9f, 2.f, 0.f, 1.f);
- mNameText->addLine(chat_iter->mText, lerp(normal_chat, old_chat, u), style);
- }
- else if (chat_fade_amt < 3.f)
- {
- // *NOTE: only remove lines down to minimum number
- mNameText->addLine(chat_iter->mText, old_chat, style);
- }
- }
- mNameText->setVisibleOffScreen(TRUE);
-
- if (mTyping)
- {
- S32 dot_count = (llfloor(mTypingTimer.getElapsedTimeF32() * 3.f) + 2) % 3 + 1;
- switch(dot_count)
- {
- case 1:
- mNameText->addLine(".", new_chat);
- break;
- case 2:
- mNameText->addLine("..", new_chat);
- break;
- case 3:
- mNameText->addLine("...", new_chat);
- break;
- }
-
- }
- }
- else
- {
- // ...not using chat bubbles, just names
- mNameText->setTextAlignment(LLHUDNameTag::ALIGN_TEXT_CENTER);
- mNameText->setFadeDistance(CHAT_NORMAL_RADIUS, 5.f);
- mNameText->setVisibleOffScreen(FALSE);
- }
-}
-
-void LLVOAvatar::addNameTagLine(const std::string& line, const LLColor4& color, S32 style, const LLFontGL* font)
-{
- llassert(mNameText);
- if (mVisibleChat)
- {
- mNameText->addLabel(line);
- }
- else
- {
- mNameText->addLine(line, color, (LLFontGL::StyleFlags)style, font);
- }
- mNameString += line;
- mNameString += '\n';
-}
-
-void LLVOAvatar::clearNameTag()
-{
- mNameString.clear();
- if (mNameText)
- {
- mNameText->setLabel("");
- mNameText->setString( "" );
- }
-}
-
-//static
-void LLVOAvatar::invalidateNameTag(const LLUUID& agent_id)
-{
- LLViewerObject* obj = gObjectList.findObject(agent_id);
- if (!obj) return;
-
- LLVOAvatar* avatar = dynamic_cast<LLVOAvatar*>(obj);
- if (!avatar) return;
-
- avatar->clearNameTag();
-}
-
-//static
-void LLVOAvatar::invalidateNameTags()
-{
- std::vector<LLCharacter*>::iterator it = LLCharacter::sInstances.begin();
- for ( ; it != LLCharacter::sInstances.end(); ++it)
- {
- LLVOAvatar* avatar = dynamic_cast<LLVOAvatar*>(*it);
- if (!avatar) continue;
- if (avatar->isDead()) continue;
-
- avatar->clearNameTag();
- }
- }
-
-// Compute name tag position during idle update
-LLVector3 LLVOAvatar::idleUpdateNameTagPosition(const LLVector3& root_pos_last)
-{
- LLQuaternion root_rot = mRoot.getWorldRotation();
- LLVector3 pixel_right_vec;
- LLVector3 pixel_up_vec;
- LLViewerCamera::getInstance()->getPixelVectors(root_pos_last, pixel_up_vec, pixel_right_vec);
- LLVector3 camera_to_av = root_pos_last - LLViewerCamera::getInstance()->getOrigin();
- camera_to_av.normalize();
- LLVector3 local_camera_at = camera_to_av * ~root_rot;
- LLVector3 local_camera_up = camera_to_av % LLViewerCamera::getInstance()->getLeftAxis();
- local_camera_up.normalize();
- local_camera_up = local_camera_up * ~root_rot;
-
- local_camera_up.scaleVec(mBodySize * 0.5f);
- local_camera_at.scaleVec(mBodySize * 0.5f);
-
- LLVector3 name_position = mRoot.getWorldPosition() +
- (local_camera_up * root_rot) -
- (projected_vec(local_camera_at * root_rot, camera_to_av));
- name_position += pixel_up_vec * 15.f;
- return name_position;
- }
-
-void LLVOAvatar::idleUpdateNameTagAlpha(BOOL new_name, F32 alpha)
-{
- llassert(mNameText);
-
- if (new_name
- || alpha != mNameAlpha)
- {
- mNameText->setAlpha(alpha);
- mNameAlpha = alpha;
- }
-}
-
-LLColor4 LLVOAvatar::getNameTagColor(bool is_friend)
-{
- static LLUICachedControl<bool> show_friends("NameTagShowFriends");
- const char* color_name;
- if (show_friends && is_friend)
- {
- color_name = "NameTagFriend";
- }
- else if (LLAvatarNameCache::useDisplayNames())
- {
- // ...color based on whether username "matches" a computed display
- // name
- LLAvatarName av_name;
- if (LLAvatarNameCache::get(getID(), &av_name)
- && av_name.mIsDisplayNameDefault)
- {
- color_name = "NameTagMatch";
- }
- else
- {
- color_name = "NameTagMismatch";
- }
- }
- else
- {
- // ...not using display names
- color_name = "NameTagLegacy";
- }
- return LLUIColorTable::getInstance()->getColor( color_name );
-}
-
-void LLVOAvatar::idleUpdateBelowWater()
-{
- F32 avatar_height = (F32)(getPositionGlobal().mdV[VZ]);
-
- F32 water_height;
- water_height = getRegion()->getWaterHeight();
-
- mBelowWater = avatar_height < water_height;
-}
-
-void LLVOAvatar::slamPosition()
-{
- gAgent.setPositionAgent(getPositionAgent());
- mRoot.setWorldPosition(getPositionAgent()); // teleport
- setChanged(TRANSLATED);
- if (mDrawable.notNull())
- {
- gPipeline.updateMoveNormalAsync(mDrawable);
- }
- mRoot.updateWorldMatrixChildren();
-}
-
-//------------------------------------------------------------------------
-// updateCharacter()
-// called on both your avatar and other avatars
-//------------------------------------------------------------------------
-BOOL LLVOAvatar::updateCharacter(LLAgent &agent)
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- // clear debug text
- mDebugText.clear();
- if (LLVOAvatar::sShowAnimationDebug)
- {
- for (LLMotionController::motion_list_t::iterator iter = mMotionController.getActiveMotions().begin();
- iter != mMotionController.getActiveMotions().end(); ++iter)
- {
- LLMotion* motionp = *iter;
- if (motionp->getMinPixelArea() < getPixelArea())
- {
- std::string output;
- if (motionp->getName().empty())
- {
- output = llformat("%s - %d",
- gAgent.isGodlikeWithoutAdminMenuFakery() ?
- motionp->getID().asString().c_str() :
- LLUUID::null.asString().c_str(),
- (U32)motionp->getPriority());
- }
- else
- {
- output = llformat("%s - %d",
- motionp->getName().c_str(),
- (U32)motionp->getPriority());
- }
- addDebugText(output);
- }
- }
- }
-
- if (gNoRender)
- {
- // Hack if we're running drones...
- if (isSelf())
- {
- gAgent.setPositionAgent(getPositionAgent());
- }
- return FALSE;
- }
-
-
- LLVector3d root_pos_global;
-
- if (!mIsBuilt)
- {
- return FALSE;
- }
-
- BOOL visible = isVisible();
-
- // For fading out the names above heads, only let the timer
- // run if we're visible.
- if (mDrawable.notNull() && !visible)
- {
- mTimeVisible.reset();
- }
-
-
- //--------------------------------------------------------------------
- // the rest should only be done occasionally for far away avatars
- //--------------------------------------------------------------------
-
- if (visible && !isSelf() && !mIsDummy && sUseImpostors && !mNeedsAnimUpdate && !sFreezeCounter)
- {
- F32 impostor_area = 256.f*512.f*(8.125f - LLVOAvatar::sLODFactor*8.f);
- if (LLMuteList::getInstance()->isMuted(getID()))
- { // muted avatars update at 16 hz
- mUpdatePeriod = 16;
- }
- else if (mVisibilityRank <= LLVOAvatar::sMaxVisible)
- { //first 25% of max visible avatars are not impostored
- mUpdatePeriod = 1;
- }
- else if (mVisibilityRank > LLVOAvatar::sMaxVisible * 4)
- { //background avatars are REALLY slow updating impostors
- mUpdatePeriod = 16;
- }
- else if (mVisibilityRank > LLVOAvatar::sMaxVisible * 3)
- { //back 25% of max visible avatars are slow updating impostors
- mUpdatePeriod = 8;
- }
- else if (mImpostorPixelArea <= impostor_area)
- { // stuff in between gets an update period based on pixel area
- mUpdatePeriod = llclamp((S32) sqrtf(impostor_area*4.f/mImpostorPixelArea), 2, 8);
- }
- else
- {
- //nearby avatars, update the impostors more frequently.
- mUpdatePeriod = 4;
- }
-
- visible = (LLDrawable::getCurrentFrame()+mID.mData[0])%mUpdatePeriod == 0 ? TRUE : FALSE;
- }
-
- // don't early out for your own avatar, as we rely on your animations playing reliably
- // for example, the "turn around" animation when entering customize avatar needs to trigger
- // even when your avatar is offscreen
- if (!visible && !isSelf())
- {
- updateMotions(LLCharacter::HIDDEN_UPDATE);
- return FALSE;
- }
-
- // change animation time quanta based on avatar render load
- if (!isSelf() && !mIsDummy)
- {
- F32 time_quantum = clamp_rescale((F32)sInstances.size(), 10.f, 35.f, 0.f, 0.25f);
- F32 pixel_area_scale = clamp_rescale(mPixelArea, 100, 5000, 1.f, 0.f);
- F32 time_step = time_quantum * pixel_area_scale;
- if (time_step != 0.f)
- {
- // disable walk motion servo controller as it doesn't work with motion timesteps
- stopMotion(ANIM_AGENT_WALK_ADJUST);
- removeAnimationData("Walk Speed");
- }
- mMotionController.setTimeStep(time_step);
-// llinfos << "Setting timestep to " << time_quantum * pixel_area_scale << llendl;
- }
-
- if (getParent() && !mIsSitting)
- {
- sitOnObject((LLViewerObject*)getParent());
- }
- else if (!getParent() && mIsSitting && !isMotionActive(ANIM_AGENT_SIT_GROUND_CONSTRAINED))
- {
- getOffObject();
- }
-
- //--------------------------------------------------------------------
- // create local variables in world coords for region position values
- //--------------------------------------------------------------------
- F32 speed;
- LLVector3 normal;
-
- LLVector3 xyVel = getVelocity();
- xyVel.mV[VZ] = 0.0f;
- speed = xyVel.length();
-
- BOOL throttle = TRUE;
-
- if (!(mIsSitting && getParent()))
- {
- //--------------------------------------------------------------------
- // get timing info
- // handle initial condition case
- //--------------------------------------------------------------------
- F32 animation_time = mAnimTimer.getElapsedTimeF32();
- if (mTimeLast == 0.0f)
- {
- mTimeLast = animation_time;
- throttle = FALSE;
-
- // put the pelvis at slaved position/mRotation
- mRoot.setWorldPosition( getPositionAgent() ); // first frame
- mRoot.setWorldRotation( getRotation() );
- }
-
- //--------------------------------------------------------------------
- // dont' let dT get larger than 1/5th of a second
- //--------------------------------------------------------------------
- F32 deltaTime = animation_time - mTimeLast;
-
- deltaTime = llclamp( deltaTime, DELTA_TIME_MIN, DELTA_TIME_MAX );
- mTimeLast = animation_time;
-
- mSpeedAccum = (mSpeedAccum * 0.95f) + (speed * 0.05f);
-
- //--------------------------------------------------------------------
- // compute the position of the avatar's root
- //--------------------------------------------------------------------
- LLVector3d root_pos;
- LLVector3d ground_under_pelvis;
-
- if (isSelf())
- {
- gAgent.setPositionAgent(getRenderPosition());
- }
-
- root_pos = gAgent.getPosGlobalFromAgent(getRenderPosition());
-
- resolveHeightGlobal(root_pos, ground_under_pelvis, normal);
- F32 foot_to_ground = (F32) (root_pos.mdV[VZ] - mPelvisToFoot - ground_under_pelvis.mdV[VZ]);
- BOOL in_air = ((!LLWorld::getInstance()->getRegionFromPosGlobal(ground_under_pelvis)) ||
- foot_to_ground > FOOT_GROUND_COLLISION_TOLERANCE);
-
- if (in_air && !mInAir)
- {
- mTimeInAir.reset();
- }
- mInAir = in_air;
-
- // correct for the fact that the pelvis is not necessarily the center
- // of the agent's physical representation
- root_pos.mdV[VZ] -= (0.5f * mBodySize.mV[VZ]) - mPelvisToFoot;
-
-
- LLVector3 newPosition = gAgent.getPosAgentFromGlobal(root_pos);
-
- if (newPosition != mRoot.getXform()->getWorldPosition())
- {
- mRoot.touch();
- mRoot.setWorldPosition(newPosition ); // regular update
- }
-
-
- //--------------------------------------------------------------------
- // Propagate viewer object rotation to root of avatar
- //--------------------------------------------------------------------
- if (!isAnyAnimationSignaled(AGENT_NO_ROTATE_ANIMS, NUM_AGENT_NO_ROTATE_ANIMS))
- {
- LLQuaternion iQ;
- LLVector3 upDir( 0.0f, 0.0f, 1.0f );
-
- // Compute a forward direction vector derived from the primitive rotation
- // and the velocity vector. When walking or jumping, don't let body deviate
- // more than 90 from the view, if necessary, flip the velocity vector.
-
- LLVector3 primDir;
- if (isSelf())
- {
- primDir = agent.getAtAxis() - projected_vec(agent.getAtAxis(), agent.getReferenceUpVector());
- primDir.normalize();
- }
- else
- {
- primDir = getRotation().getMatrix3().getFwdRow();
- }
- LLVector3 velDir = getVelocity();
- velDir.normalize();
- if ( mSignaledAnimations.find(ANIM_AGENT_WALK) != mSignaledAnimations.end())
- {
- F32 vpD = velDir * primDir;
- if (vpD < -0.5f)
- {
- velDir *= -1.0f;
- }
- }
- LLVector3 fwdDir = lerp(primDir, velDir, clamp_rescale(speed, 0.5f, 2.0f, 0.0f, 1.0f));
- if (isSelf() && gAgentCamera.cameraMouselook())
- {
- // make sure fwdDir stays in same general direction as primdir
- if (gAgent.getFlying())
- {
- fwdDir = LLViewerCamera::getInstance()->getAtAxis();
- }
- else
- {
- LLVector3 at_axis = LLViewerCamera::getInstance()->getAtAxis();
- LLVector3 up_vector = gAgent.getReferenceUpVector();
- at_axis -= up_vector * (at_axis * up_vector);
- at_axis.normalize();
-
- F32 dot = fwdDir * at_axis;
- if (dot < 0.f)
- {
- fwdDir -= 2.f * at_axis * dot;
- fwdDir.normalize();
- }
- }
-
- }
-
- LLQuaternion root_rotation = mRoot.getWorldMatrix().quaternion();
- F32 root_roll, root_pitch, root_yaw;
- root_rotation.getEulerAngles(&root_roll, &root_pitch, &root_yaw);
-
- // When moving very slow, the pelvis is allowed to deviate from the
- // forward direction to allow it to hold it's position while the torso
- // and head turn. Once in motion, it must conform however.
- BOOL self_in_mouselook = isSelf() && gAgentCamera.cameraMouselook();
-
- LLVector3 pelvisDir( mRoot.getWorldMatrix().getFwdRow4().mV );
- F32 pelvis_rot_threshold = clamp_rescale(speed, 0.1f, 1.0f, PELVIS_ROT_THRESHOLD_SLOW, PELVIS_ROT_THRESHOLD_FAST);
-
- if (self_in_mouselook)
- {
- pelvis_rot_threshold *= MOUSELOOK_PELVIS_FOLLOW_FACTOR;
- }
- pelvis_rot_threshold *= DEG_TO_RAD;
-
- F32 angle = angle_between( pelvisDir, fwdDir );
-
- // The avatar's root is allowed to have a yaw that deviates widely
- // from the forward direction, but if roll or pitch are off even
- // a little bit we need to correct the rotation.
- if(root_roll < 1.f * DEG_TO_RAD
- && root_pitch < 5.f * DEG_TO_RAD)
- {
- // smaller correction vector means pelvis follows prim direction more closely
- if (!mTurning && angle > pelvis_rot_threshold*0.75f)
- {
- mTurning = TRUE;
- }
-
- // use tighter threshold when turning
- if (mTurning)
- {
- pelvis_rot_threshold *= 0.4f;
- }
-
- // am I done turning?
- if (angle < pelvis_rot_threshold)
- {
- mTurning = FALSE;
- }
-
- LLVector3 correction_vector = (pelvisDir - fwdDir) * clamp_rescale(angle, pelvis_rot_threshold*0.75f, pelvis_rot_threshold, 1.0f, 0.0f);
- fwdDir += correction_vector;
- }
- else
- {
- mTurning = FALSE;
- }
-
- // Now compute the full world space rotation for the whole body (wQv)
- LLVector3 leftDir = upDir % fwdDir;
- leftDir.normalize();
- fwdDir = leftDir % upDir;
- LLQuaternion wQv( fwdDir, leftDir, upDir );
-
- if (isSelf() && mTurning)
- {
- if ((fwdDir % pelvisDir) * upDir > 0.f)
- {
- gAgent.setControlFlags(AGENT_CONTROL_TURN_RIGHT);
- }
- else
- {
- gAgent.setControlFlags(AGENT_CONTROL_TURN_LEFT);
- }
- }
-
- // Set the root rotation, but do so incrementally so that it
- // lags in time by some fixed amount.
- //F32 u = LLCriticalDamp::getInterpolant(PELVIS_LAG);
- F32 pelvis_lag_time = 0.f;
- if (self_in_mouselook)
- {
- pelvis_lag_time = PELVIS_LAG_MOUSELOOK;
- }
- else if (mInAir)
- {
- pelvis_lag_time = PELVIS_LAG_FLYING;
- // increase pelvis lag time when moving slowly
- pelvis_lag_time *= clamp_rescale(mSpeedAccum, 0.f, 15.f, 3.f, 1.f);
- }
- else
- {
- pelvis_lag_time = PELVIS_LAG_WALKING;
- }
-
- F32 u = llclamp((deltaTime / pelvis_lag_time), 0.0f, 1.0f);
-
- mRoot.setWorldRotation( slerp(u, mRoot.getWorldRotation(), wQv) );
-
- }
- }
- else if (mDrawable.notNull())
- {
- mRoot.setPosition(mDrawable->getPosition());
- mRoot.setRotation(mDrawable->getRotation());
- }
-
- //-------------------------------------------------------------------------
- // Update character motions
- //-------------------------------------------------------------------------
- // store data relevant to motions
- mSpeed = speed;
-
- // update animations
- if (mSpecialRenderMode == 1) // Animation Preview
- updateMotions(LLCharacter::FORCE_UPDATE);
- else
- updateMotions(LLCharacter::NORMAL_UPDATE);
-
- // update head position
- updateHeadOffset();
-
- //-------------------------------------------------------------------------
- // Find the ground under each foot, these are used for a variety
- // of things that follow
- //-------------------------------------------------------------------------
- LLVector3 ankle_left_pos_agent = mFootLeftp->getWorldPosition();
- LLVector3 ankle_right_pos_agent = mFootRightp->getWorldPosition();
-
- LLVector3 ankle_left_ground_agent = ankle_left_pos_agent;
- LLVector3 ankle_right_ground_agent = ankle_right_pos_agent;
- resolveHeightAgent(ankle_left_pos_agent, ankle_left_ground_agent, normal);
- resolveHeightAgent(ankle_right_pos_agent, ankle_right_ground_agent, normal);
-
- F32 leftElev = llmax(-0.2f, ankle_left_pos_agent.mV[VZ] - ankle_left_ground_agent.mV[VZ]);
- F32 rightElev = llmax(-0.2f, ankle_right_pos_agent.mV[VZ] - ankle_right_ground_agent.mV[VZ]);
-
- if (!mIsSitting)
- {
- //-------------------------------------------------------------------------
- // Figure out which foot is on ground
- //-------------------------------------------------------------------------
- if (!mInAir)
- {
- if ((leftElev < 0.0f) || (rightElev < 0.0f))
- {
- ankle_left_pos_agent = mFootLeftp->getWorldPosition();
- ankle_right_pos_agent = mFootRightp->getWorldPosition();
- leftElev = ankle_left_pos_agent.mV[VZ] - ankle_left_ground_agent.mV[VZ];
- rightElev = ankle_right_pos_agent.mV[VZ] - ankle_right_ground_agent.mV[VZ];
- }
- }
- }
-
- //-------------------------------------------------------------------------
- // Generate footstep sounds when feet hit the ground
- //-------------------------------------------------------------------------
- const LLUUID AGENT_FOOTSTEP_ANIMS[] = {ANIM_AGENT_WALK, ANIM_AGENT_RUN, ANIM_AGENT_LAND};
- const S32 NUM_AGENT_FOOTSTEP_ANIMS = LL_ARRAY_SIZE(AGENT_FOOTSTEP_ANIMS);
-
- if ( gAudiop && isAnyAnimationSignaled(AGENT_FOOTSTEP_ANIMS, NUM_AGENT_FOOTSTEP_ANIMS) )
- {
- BOOL playSound = FALSE;
- LLVector3 foot_pos_agent;
-
- BOOL onGroundLeft = (leftElev <= 0.05f);
- BOOL onGroundRight = (rightElev <= 0.05f);
-
- // did left foot hit the ground?
- if ( onGroundLeft && !mWasOnGroundLeft )
- {
- foot_pos_agent = ankle_left_pos_agent;
- playSound = TRUE;
- }
-
- // did right foot hit the ground?
- if ( onGroundRight && !mWasOnGroundRight )
- {
- foot_pos_agent = ankle_right_pos_agent;
- playSound = TRUE;
- }
-
- mWasOnGroundLeft = onGroundLeft;
- mWasOnGroundRight = onGroundRight;
-
- if ( playSound )
- {
-// F32 gain = clamp_rescale( mSpeedAccum,
-// AUDIO_STEP_LO_SPEED, AUDIO_STEP_HI_SPEED,
-// AUDIO_STEP_LO_GAIN, AUDIO_STEP_HI_GAIN );
-
- const F32 STEP_VOLUME = 0.1f;
- const LLUUID& step_sound_id = getStepSound();
-
- LLVector3d foot_pos_global = gAgent.getPosGlobalFromAgent(foot_pos_agent);
-
- if (LLViewerParcelMgr::getInstance()->canHearSound(foot_pos_global)
- && !LLMuteList::getInstance()->isMuted(getID(), LLMute::flagObjectSounds))
- {
- gAudiop->triggerSound(step_sound_id, getID(), STEP_VOLUME, LLAudioEngine::AUDIO_TYPE_AMBIENT, foot_pos_global);
- }
- }
- }
-
- mRoot.updateWorldMatrixChildren();
-
- if (!mDebugText.size() && mText.notNull())
- {
- mText->markDead();
- mText = NULL;
- }
- else if (mDebugText.size())
- {
- setDebugText(mDebugText);
- }
-
- //mesh vertices need to be reskinned
- mNeedsSkin = TRUE;
-
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// updateHeadOffset()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::updateHeadOffset()
-{
- // since we only care about Z, just grab one of the eyes
- LLVector3 midEyePt = mEyeLeftp->getWorldPosition();
- midEyePt -= mDrawable.notNull() ? mDrawable->getWorldPosition() : mRoot.getWorldPosition();
- midEyePt.mV[VZ] = llmax(-mPelvisToFoot + LLViewerCamera::getInstance()->getNear(), midEyePt.mV[VZ]);
-
- if (mDrawable.notNull())
- {
- midEyePt = midEyePt * ~mDrawable->getWorldRotation();
- }
- if (mIsSitting)
- {
- mHeadOffset = midEyePt;
- }
- else
- {
- F32 u = llmax(0.f, HEAD_MOVEMENT_AVG_TIME - (1.f / gFPSClamped));
- mHeadOffset = lerp(midEyePt, mHeadOffset, u);
- }
-}
-
-//------------------------------------------------------------------------
-// updateVisibility()
-//------------------------------------------------------------------------
-void LLVOAvatar::updateVisibility()
-{
- BOOL visible = FALSE;
-
- if (mIsDummy)
- {
- visible = TRUE;
- }
- else if (mDrawable.isNull())
- {
- visible = FALSE;
- }
- else
- {
- if (!mDrawable->getSpatialGroup() || mDrawable->getSpatialGroup()->isVisible())
- {
- visible = TRUE;
- }
- else
- {
- visible = FALSE;
- }
-
- if(isSelf())
- {
- if (!gAgentWearables.areWearablesLoaded())
- {
- visible = FALSE;
- }
- }
- else if( !mFirstAppearanceMessageReceived )
- {
- visible = FALSE;
- }
-
- if (sDebugInvisible)
- {
- LLNameValue* firstname = getNVPair("FirstName");
- if (firstname)
- {
- llinfos << "Avatar " << firstname->getString() << " updating visiblity" << llendl;
- }
- else
- {
- llinfos << "Avatar " << this << " updating visiblity" << llendl;
- }
-
- if (visible)
- {
- llinfos << "Visible" << llendl;
- }
- else
- {
- llinfos << "Not visible" << llendl;
- }
-
- /*if (avatar_in_frustum)
- {
- llinfos << "Avatar in frustum" << llendl;
- }
- else
- {
- llinfos << "Avatar not in frustum" << llendl;
- }*/
-
- /*if (LLViewerCamera::getInstance()->sphereInFrustum(sel_pos_agent, 2.0f))
- {
- llinfos << "Sel pos visible" << llendl;
- }
- if (LLViewerCamera::getInstance()->sphereInFrustum(wrist_right_pos_agent, 0.2f))
- {
- llinfos << "Wrist pos visible" << llendl;
- }
- if (LLViewerCamera::getInstance()->sphereInFrustum(getPositionAgent(), getMaxScale()*2.f))
- {
- llinfos << "Agent visible" << llendl;
- }*/
- llinfos << "PA: " << getPositionAgent() << llendl;
- /*llinfos << "SPA: " << sel_pos_agent << llendl;
- llinfos << "WPA: " << wrist_right_pos_agent << llendl;*/
- for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
-
- for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
- attachment_iter != attachment->mAttachedObjects.end();
- ++attachment_iter)
- {
- if (LLViewerObject *attached_object = (*attachment_iter))
- {
- if(attached_object->mDrawable->isVisible())
- {
- llinfos << attachment->getName() << " visible" << llendl;
- }
- else
- {
- llinfos << attachment->getName() << " not visible at " << mDrawable->getWorldPosition() << " and radius " << mDrawable->getRadius() << llendl;
- }
- }
- }
- }
- }
- }
-
- if (!visible && mVisible)
- {
- mMeshInvisibleTime.reset();
- }
-
- if (visible)
- {
- if (!mMeshValid)
- {
- restoreMeshData();
- }
- }
- else
- {
- if (mMeshValid && mMeshInvisibleTime.getElapsedTimeF32() > TIME_BEFORE_MESH_CLEANUP)
- {
- releaseMeshData();
- }
- // this breaks off-screen chat bubbles
- //if (mNameText)
- //{
- // mNameText->markDead();
- // mNameText = NULL;
- // sNumVisibleChatBubbles--;
- //}
- }
-
- mVisible = visible;
-}
-
-// private
-bool LLVOAvatar::shouldAlphaMask()
-{
- const bool should_alpha_mask = mSupportsAlphaLayers && !LLDrawPoolAlpha::sShowDebugAlpha // Don't alpha mask if "Highlight Transparent" checked
- && !LLDrawPoolAvatar::sSkipTransparent;
-
- return should_alpha_mask;
-
-}
-
-//-----------------------------------------------------------------------------
-// renderSkinned()
-//-----------------------------------------------------------------------------
-U32 LLVOAvatar::renderSkinned(EAvatarRenderPass pass)
-{
- U32 num_indices = 0;
-
- if (!mIsBuilt)
- {
- return num_indices;
- }
-
- LLFace* face = mDrawable->getFace(0);
-
- bool needs_rebuild = !face || face->mVertexBuffer.isNull() || mDrawable->isState(LLDrawable::REBUILD_GEOMETRY);
-
- if (needs_rebuild || mDirtyMesh)
- { //LOD changed or new mesh created, allocate new vertex buffer if needed
- if (needs_rebuild || mDirtyMesh >= 2 || mVisibilityRank <= 4)
- {
- updateMeshData();
- mDirtyMesh = 0;
- mNeedsSkin = TRUE;
- mDrawable->clearState(LLDrawable::REBUILD_GEOMETRY);
- }
- }
-
- if (LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_AVATAR) <= 0)
- {
- if (mNeedsSkin)
- {
- //generate animated mesh
- mMeshLOD[MESH_ID_LOWER_BODY]->updateJointGeometry();
- mMeshLOD[MESH_ID_UPPER_BODY]->updateJointGeometry();
-
- if( isWearingWearableType( LLWearableType::WT_SKIRT ) )
- {
- mMeshLOD[MESH_ID_SKIRT]->updateJointGeometry();
- }
-
- if (!isSelf() || gAgent.needsRenderHead() || LLPipeline::sShadowRender)
- {
- mMeshLOD[MESH_ID_EYELASH]->updateJointGeometry();
- mMeshLOD[MESH_ID_HEAD]->updateJointGeometry();
- mMeshLOD[MESH_ID_HAIR]->updateJointGeometry();
- }
- mNeedsSkin = FALSE;
-
- LLVertexBuffer* vb = mDrawable->getFace(0)->mVertexBuffer;
- if (vb)
- {
- vb->setBuffer(0);
- }
- }
- }
- else
- {
- mNeedsSkin = FALSE;
- }
-
- if (sDebugInvisible)
- {
- LLNameValue* firstname = getNVPair("FirstName");
- if (firstname)
- {
- llinfos << "Avatar " << firstname->getString() << " in render" << llendl;
- }
- else
- {
- llinfos << "Avatar " << this << " in render" << llendl;
- }
- if (!mIsBuilt)
- {
- llinfos << "Not built!" << llendl;
- }
- else if (!gAgent.needsRenderAvatar())
- {
- llinfos << "Doesn't need avatar render!" << llendl;
- }
- else
- {
- llinfos << "Rendering!" << llendl;
- }
- }
-
- if (!mIsBuilt)
- {
- return num_indices;
- }
-
- if (isSelf() && !gAgent.needsRenderAvatar())
- {
- return num_indices;
- }
-
- // render collision normal
- // *NOTE: this is disabled (there is no UI for enabling sShowFootPlane) due
- // to DEV-14477. the code is left here to aid in tracking down the cause
- // of the crash in the future. -brad
- if (sShowFootPlane && mDrawable.notNull())
- {
- LLVector3 slaved_pos = mDrawable->getPositionAgent();
- LLVector3 foot_plane_normal(mFootPlane.mV[VX], mFootPlane.mV[VY], mFootPlane.mV[VZ]);
- F32 dist_from_plane = (slaved_pos * foot_plane_normal) - mFootPlane.mV[VW];
- LLVector3 collide_point = slaved_pos;
- collide_point.mV[VZ] -= foot_plane_normal.mV[VZ] * (dist_from_plane + COLLISION_TOLERANCE - FOOT_COLLIDE_FUDGE);
-
- gGL.begin(LLRender::LINES);
- {
- F32 SQUARE_SIZE = 0.2f;
- gGL.color4f(1.f, 0.f, 0.f, 1.f);
-
- gGL.vertex3f(collide_point.mV[VX] - SQUARE_SIZE, collide_point.mV[VY] - SQUARE_SIZE, collide_point.mV[VZ]);
- gGL.vertex3f(collide_point.mV[VX] + SQUARE_SIZE, collide_point.mV[VY] - SQUARE_SIZE, collide_point.mV[VZ]);
-
- gGL.vertex3f(collide_point.mV[VX] + SQUARE_SIZE, collide_point.mV[VY] - SQUARE_SIZE, collide_point.mV[VZ]);
- gGL.vertex3f(collide_point.mV[VX] + SQUARE_SIZE, collide_point.mV[VY] + SQUARE_SIZE, collide_point.mV[VZ]);
-
- gGL.vertex3f(collide_point.mV[VX] + SQUARE_SIZE, collide_point.mV[VY] + SQUARE_SIZE, collide_point.mV[VZ]);
- gGL.vertex3f(collide_point.mV[VX] - SQUARE_SIZE, collide_point.mV[VY] + SQUARE_SIZE, collide_point.mV[VZ]);
-
- gGL.vertex3f(collide_point.mV[VX] - SQUARE_SIZE, collide_point.mV[VY] + SQUARE_SIZE, collide_point.mV[VZ]);
- gGL.vertex3f(collide_point.mV[VX] - SQUARE_SIZE, collide_point.mV[VY] - SQUARE_SIZE, collide_point.mV[VZ]);
-
- gGL.vertex3f(collide_point.mV[VX], collide_point.mV[VY], collide_point.mV[VZ]);
- gGL.vertex3f(collide_point.mV[VX] + mFootPlane.mV[VX], collide_point.mV[VY] + mFootPlane.mV[VY], collide_point.mV[VZ] + mFootPlane.mV[VZ]);
-
- }
- gGL.end();
- gGL.flush();
- }
- //--------------------------------------------------------------------
- // render all geometry attached to the skeleton
- //--------------------------------------------------------------------
- static LLStat render_stat;
-
- LLViewerJointMesh::sRenderPass = pass;
-
- if (pass == AVATAR_RENDER_PASS_SINGLE)
- {
-
- bool should_alpha_mask = shouldAlphaMask();
- LLGLState test(GL_ALPHA_TEST, should_alpha_mask);
-
- if (should_alpha_mask)
- {
- gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);
- }
-
- BOOL first_pass = TRUE;
- if (!LLDrawPoolAvatar::sSkipOpaque)
- {
- if (!isSelf() || gAgent.needsRenderHead() || LLPipeline::sShadowRender)
- {
- if (isTextureVisible(TEX_HEAD_BAKED) || mIsDummy)
- {
- num_indices += mMeshLOD[MESH_ID_HEAD]->render(mAdjustedPixelArea, TRUE, mIsDummy);
- first_pass = FALSE;
- }
- }
- if (isTextureVisible(TEX_UPPER_BAKED) || mIsDummy)
- {
- num_indices += mMeshLOD[MESH_ID_UPPER_BODY]->render(mAdjustedPixelArea, first_pass, mIsDummy);
- first_pass = FALSE;
- }
-
- if (isTextureVisible(TEX_LOWER_BAKED) || mIsDummy)
- {
- num_indices += mMeshLOD[MESH_ID_LOWER_BODY]->render(mAdjustedPixelArea, first_pass, mIsDummy);
- first_pass = FALSE;
- }
- }
-
- gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
-
- if (!LLDrawPoolAvatar::sSkipTransparent || LLPipeline::sImpostorRender)
- {
- LLGLState blend(GL_BLEND, !mIsDummy);
- LLGLState test(GL_ALPHA_TEST, !mIsDummy);
- num_indices += renderTransparent(first_pass);
- }
- }
-
- LLViewerJointMesh::sRenderPass = AVATAR_RENDER_PASS_SINGLE;
-
- //llinfos << "Avatar render: " << render_timer.getElapsedTimeF32() << llendl;
-
- //render_stat.addValue(render_timer.getElapsedTimeF32()*1000.f);
-
- return num_indices;
-}
-
-U32 LLVOAvatar::renderTransparent(BOOL first_pass)
-{
- U32 num_indices = 0;
- if( isWearingWearableType( LLWearableType::WT_SKIRT ) && (mIsDummy || isTextureVisible(TEX_SKIRT_BAKED)) )
- {
- gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.25f);
- num_indices += mMeshLOD[MESH_ID_SKIRT]->render(mAdjustedPixelArea, FALSE);
- first_pass = FALSE;
- gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
- }
-
- if (!isSelf() || gAgent.needsRenderHead() || LLPipeline::sShadowRender)
- {
- if (LLPipeline::sImpostorRender)
- {
- gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);
- }
-
- if (isTextureVisible(TEX_HEAD_BAKED))
- {
- num_indices += mMeshLOD[MESH_ID_EYELASH]->render(mAdjustedPixelArea, first_pass, mIsDummy);
- first_pass = FALSE;
- }
- // Can't test for baked hair being defined, since that won't always be the case (not all viewers send baked hair)
- // TODO: 1.25 will be able to switch this logic back to calling isTextureVisible();
- if (getImage(TEX_HAIR_BAKED, 0)->getID() != IMG_INVISIBLE || LLDrawPoolAlpha::sShowDebugAlpha)
- {
- num_indices += mMeshLOD[MESH_ID_HAIR]->render(mAdjustedPixelArea, first_pass, mIsDummy);
- first_pass = FALSE;
- }
- if (LLPipeline::sImpostorRender)
- {
- gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
- }
- }
-
- return num_indices;
-}
-
-//-----------------------------------------------------------------------------
-// renderRigid()
-//-----------------------------------------------------------------------------
-U32 LLVOAvatar::renderRigid()
-{
- U32 num_indices = 0;
-
- if (!mIsBuilt)
- {
- return 0;
- }
-
- if (isSelf() && (!gAgent.needsRenderAvatar() || !gAgent.needsRenderHead()))
- {
- return 0;
- }
-
- if (!mIsBuilt)
- {
- return 0;
- }
-
- bool should_alpha_mask = shouldAlphaMask();
- LLGLState test(GL_ALPHA_TEST, should_alpha_mask);
-
- if (should_alpha_mask)
- {
- gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);
- }
-
- if (isTextureVisible(TEX_EYES_BAKED) || mIsDummy)
- {
- num_indices += mMeshLOD[MESH_ID_EYEBALL_LEFT]->render(mAdjustedPixelArea, TRUE, mIsDummy);
- num_indices += mMeshLOD[MESH_ID_EYEBALL_RIGHT]->render(mAdjustedPixelArea, TRUE, mIsDummy);
- }
-
- gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
-
- return num_indices;
-}
-
-U32 LLVOAvatar::renderImpostor(LLColor4U color, S32 diffuse_channel)
-{
- if (!mImpostor.isComplete())
- {
- return 0;
- }
-
- LLVector3 pos(getRenderPosition()+mImpostorOffset);
- LLVector3 at = (pos - LLViewerCamera::getInstance()->getOrigin());
- at.normalize();
- LLVector3 left = LLViewerCamera::getInstance()->getUpAxis() % at;
- LLVector3 up = at%left;
-
- left *= mImpostorDim.mV[0];
- up *= mImpostorDim.mV[1];
-
- LLGLEnable test(GL_ALPHA_TEST);
- gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.f);
-
- gGL.color4ubv(color.mV);
- gGL.getTexUnit(diffuse_channel)->bind(&mImpostor);
- gGL.begin(LLRender::QUADS);
- gGL.texCoord2f(0,0);
- gGL.vertex3fv((pos+left-up).mV);
- gGL.texCoord2f(1,0);
- gGL.vertex3fv((pos-left-up).mV);
- gGL.texCoord2f(1,1);
- gGL.vertex3fv((pos-left+up).mV);
- gGL.texCoord2f(0,1);
- gGL.vertex3fv((pos+left+up).mV);
- gGL.end();
- gGL.flush();
-
- return 6;
-}
-
-//------------------------------------------------------------------------
-// LLVOAvatar::updateTextures()
-//------------------------------------------------------------------------
-void LLVOAvatar::updateTextures()
-{
- BOOL render_avatar = TRUE;
-
- if (mIsDummy || gNoRender)
- {
- return;
- }
-
- if( isSelf() )
- {
- render_avatar = TRUE;
- }
- else
- {
- if(!isVisible())
- {
- return ;//do not update for invisible avatar.
- }
-
- render_avatar = !mCulled; //visible and not culled.
- }
-
- std::vector<BOOL> layer_baked;
- // GL NOT ACTIVE HERE - *TODO
- for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
- {
- layer_baked.push_back(isTextureDefined(mBakedTextureDatas[i].mTextureIndex));
- // bind the texture so that they'll be decoded slightly
- // inefficient, we can short-circuit this if we have to
- if (render_avatar && !gGLManager.mIsDisabled)
- {
- if (layer_baked[i] && !mBakedTextureDatas[i].mIsLoaded)
- {
- gGL.getTexUnit(0)->bind(getImage( mBakedTextureDatas[i].mTextureIndex, 0 ));
- }
- }
- }
-
- mMaxPixelArea = 0.f;
- mMinPixelArea = 99999999.f;
- mHasGrey = FALSE; // debug
- for (U32 texture_index = 0; texture_index < getNumTEs(); texture_index++)
- {
- LLWearableType::EType wearable_type = LLVOAvatarDictionary::getTEWearableType((ETextureIndex)texture_index);
- U32 num_wearables = gAgentWearables.getWearableCount(wearable_type);
- const LLTextureEntry *te = getTE(texture_index);
- const F32 texel_area_ratio = fabs(te->mScaleS * te->mScaleT);
- LLViewerFetchedTexture *imagep = NULL;
- for (U32 wearable_index = 0; wearable_index < num_wearables; wearable_index++)
- {
- imagep = LLViewerTextureManager::staticCastToFetchedTexture(getImage(texture_index, wearable_index), TRUE);
- if (imagep)
- {
- const LLVOAvatarDictionary::TextureEntry *texture_dict = LLVOAvatarDictionary::getInstance()->getTexture((ETextureIndex)texture_index);
- const EBakedTextureIndex baked_index = texture_dict->mBakedTextureIndex;
- if (texture_dict->mIsLocalTexture)
- {
- addLocalTextureStats((ETextureIndex)texture_index, imagep, texel_area_ratio, render_avatar, layer_baked[baked_index]);
- }
- }
- }
- if (isIndexBakedTexture((ETextureIndex) texture_index) && render_avatar)
- {
- const S32 boost_level = getAvatarBakedBoostLevel();
- imagep = LLViewerTextureManager::staticCastToFetchedTexture(getImage(texture_index,0), TRUE);
- // Spam if this is a baked texture, not set to default image, without valid host info
- if (isIndexBakedTexture((ETextureIndex)texture_index)
- && imagep->getID() != IMG_DEFAULT_AVATAR
- && imagep->getID() != IMG_INVISIBLE
- && !imagep->getTargetHost().isOk())
- {
- LL_WARNS_ONCE("Texture") << "LLVOAvatar::updateTextures No host for texture "
- << imagep->getID() << " for avatar "
- << (isSelf() ? "<myself>" : getID().asString())
- << " on host " << getRegion()->getHost() << llendl;
- }
-
- addBakedTextureStats( imagep, mPixelArea, texel_area_ratio, boost_level );
- }
- }
-
- if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_AREA))
- {
- setDebugText(llformat("%4.0f:%4.0f", fsqrtf(mMinPixelArea),fsqrtf(mMaxPixelArea)));
- }
-}
-
-
-void LLVOAvatar::addLocalTextureStats( ETextureIndex idx, LLViewerFetchedTexture* imagep,
- F32 texel_area_ratio, BOOL render_avatar, BOOL covered_by_baked, U32 index )
-{
- // No local texture stats for non-self avatars
- return;
-}
-
-const S32 MAX_TEXTURE_UPDATE_INTERVAL = 64 ; //need to call updateTextures() at least every 32 frames.
-const S32 MAX_TEXTURE_VIRTURE_SIZE_RESET_INTERVAL = S32_MAX ; //frames
-void LLVOAvatar::checkTextureLoading()
-{
- static const F32 MAX_INVISIBLE_WAITING_TIME = 15.f ; //seconds
-
- BOOL pause = !isVisible() ;
- if(!pause)
- {
- mInvisibleTimer.reset() ;
- }
- if(mLoadedCallbacksPaused == pause)
- {
- return ;
- }
-
- if(mCallbackTextureList.empty()) //when is self or no callbacks. Note: this list for self is always empty.
- {
- mLoadedCallbacksPaused = pause ;
- return ; //nothing to check.
- }
-
- if(pause && mInvisibleTimer.getElapsedTimeF32() < MAX_INVISIBLE_WAITING_TIME)
- {
- return ; //have not been invisible for enough time.
- }
-
- for(LLLoadedCallbackEntry::source_callback_list_t::iterator iter = mCallbackTextureList.begin();
- iter != mCallbackTextureList.end(); ++iter)
- {
- LLViewerFetchedTexture* tex = gTextureList.findImage(*iter) ;
- if(tex)
- {
- if(pause)//pause texture fetching.
- {
- tex->pauseLoadedCallbacks(&mCallbackTextureList) ;
-
- //set to terminate texture fetching after MAX_TEXTURE_UPDATE_INTERVAL frames.
- tex->setMaxVirtualSizeResetInterval(MAX_TEXTURE_UPDATE_INTERVAL);
- tex->resetMaxVirtualSizeResetCounter() ;
- }
- else//unpause
- {
- static const F32 START_AREA = 100.f ;
-
- tex->unpauseLoadedCallbacks(&mCallbackTextureList) ;
- tex->addTextureStats(START_AREA); //jump start the fetching again
- }
- }
- }
-
- if(!pause)
- {
- updateTextures() ; //refresh texture stats.
- }
- mLoadedCallbacksPaused = pause ;
- return ;
-}
-
-const F32 SELF_ADDITIONAL_PRI = 0.75f ;
-const F32 ADDITIONAL_PRI = 0.5f;
-void LLVOAvatar::addBakedTextureStats( LLViewerFetchedTexture* imagep, F32 pixel_area, F32 texel_area_ratio, S32 boost_level)
-{
- //Note:
- //if this function is not called for the last MAX_TEXTURE_VIRTURE_SIZE_RESET_INTERVAL frames,
- //the texture pipeline will stop fetching this texture.
-
- imagep->resetTextureStats();
- imagep->setCanUseHTTP(false) ; //turn off http fetching for baked textures.
- imagep->setMaxVirtualSizeResetInterval(MAX_TEXTURE_VIRTURE_SIZE_RESET_INTERVAL);
- imagep->resetMaxVirtualSizeResetCounter() ;
-
- mMaxPixelArea = llmax(pixel_area, mMaxPixelArea);
- mMinPixelArea = llmin(pixel_area, mMinPixelArea);
- imagep->addTextureStats(pixel_area / texel_area_ratio);
- imagep->setBoostLevel(boost_level);
-
- if(boost_level != LLViewerTexture::BOOST_AVATAR_BAKED_SELF)
- {
- imagep->setAdditionalDecodePriority(ADDITIONAL_PRI) ;
- }
- else
- {
- imagep->setAdditionalDecodePriority(SELF_ADDITIONAL_PRI) ;
- }
-}
-
-//virtual
-void LLVOAvatar::setImage(const U8 te, LLViewerTexture *imagep, const U32 index)
-{
- setTEImage(te, imagep);
-}
-
-//virtual
-LLViewerTexture* LLVOAvatar::getImage(const U8 te, const U32 index) const
-{
- return getTEImage(te);
-}
-//virtual
-const LLTextureEntry* LLVOAvatar::getTexEntry(const U8 te_num) const
-{
- return getTE(te_num);
-}
-
-//virtual
-void LLVOAvatar::setTexEntry(const U8 index, const LLTextureEntry &te)
-{
- setTE(index, te);
-}
-
-//-----------------------------------------------------------------------------
-// resolveHeight()
-//-----------------------------------------------------------------------------
-
-void LLVOAvatar::resolveHeightAgent(const LLVector3 &in_pos_agent, LLVector3 &out_pos_agent, LLVector3 &out_norm)
-{
- LLVector3d in_pos_global, out_pos_global;
-
- in_pos_global = gAgent.getPosGlobalFromAgent(in_pos_agent);
- resolveHeightGlobal(in_pos_global, out_pos_global, out_norm);
- out_pos_agent = gAgent.getPosAgentFromGlobal(out_pos_global);
-}
-
-
-void LLVOAvatar::resolveRayCollisionAgent(const LLVector3d start_pt, const LLVector3d end_pt, LLVector3d &out_pos, LLVector3 &out_norm)
-{
- LLViewerObject *obj;
- LLWorld::getInstance()->resolveStepHeightGlobal(this, start_pt, end_pt, out_pos, out_norm, &obj);
-}
-
-
-void LLVOAvatar::resolveHeightGlobal(const LLVector3d &inPos, LLVector3d &outPos, LLVector3 &outNorm)
-{
- LLVector3d zVec(0.0f, 0.0f, 0.5f);
- LLVector3d p0 = inPos + zVec;
- LLVector3d p1 = inPos - zVec;
- LLViewerObject *obj;
- LLWorld::getInstance()->resolveStepHeightGlobal(this, p0, p1, outPos, outNorm, &obj);
- if (!obj)
- {
- mStepOnLand = TRUE;
- mStepMaterial = 0;
- mStepObjectVelocity.setVec(0.0f, 0.0f, 0.0f);
- }
- else
- {
- mStepOnLand = FALSE;
- mStepMaterial = obj->getMaterial();
-
- // We want the primitive velocity, not our velocity... (which actually subtracts the
- // step object velocity)
- LLVector3 angularVelocity = obj->getAngularVelocity();
- LLVector3 relativePos = gAgent.getPosAgentFromGlobal(outPos) - obj->getPositionAgent();
-
- LLVector3 linearComponent = angularVelocity % relativePos;
-// llinfos << "Linear Component of Rotation Velocity " << linearComponent << llendl;
- mStepObjectVelocity = obj->getVelocity() + linearComponent;
- }
-}
-
-
-//-----------------------------------------------------------------------------
-// getStepSound()
-//-----------------------------------------------------------------------------
-const LLUUID& LLVOAvatar::getStepSound() const
-{
- if ( mStepOnLand )
- {
- return sStepSoundOnLand;
- }
-
- return sStepSounds[mStepMaterial];
-}
-
-
-//-----------------------------------------------------------------------------
-// processAnimationStateChanges()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::processAnimationStateChanges()
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- if (gNoRender)
- {
- return;
- }
-
- if ( isAnyAnimationSignaled(AGENT_WALK_ANIMS, NUM_AGENT_WALK_ANIMS) )
- {
- startMotion(ANIM_AGENT_WALK_ADJUST);
- stopMotion(ANIM_AGENT_FLY_ADJUST);
- }
- else if (mInAir && !mIsSitting)
- {
- stopMotion(ANIM_AGENT_WALK_ADJUST);
- startMotion(ANIM_AGENT_FLY_ADJUST);
- }
- else
- {
- stopMotion(ANIM_AGENT_WALK_ADJUST);
- stopMotion(ANIM_AGENT_FLY_ADJUST);
- }
-
- if ( isAnyAnimationSignaled(AGENT_GUN_AIM_ANIMS, NUM_AGENT_GUN_AIM_ANIMS) )
- {
- startMotion(ANIM_AGENT_TARGET);
- stopMotion(ANIM_AGENT_BODY_NOISE);
- }
- else
- {
- stopMotion(ANIM_AGENT_TARGET);
- startMotion(ANIM_AGENT_BODY_NOISE);
- }
-
- // clear all current animations
- AnimIterator anim_it;
- for (anim_it = mPlayingAnimations.begin(); anim_it != mPlayingAnimations.end();)
- {
- AnimIterator found_anim = mSignaledAnimations.find(anim_it->first);
-
- // playing, but not signaled, so stop
- if (found_anim == mSignaledAnimations.end())
- {
- processSingleAnimationStateChange(anim_it->first, FALSE);
- mPlayingAnimations.erase(anim_it++);
- continue;
- }
-
- ++anim_it;
- }
-
- // start up all new anims
- for (anim_it = mSignaledAnimations.begin(); anim_it != mSignaledAnimations.end();)
- {
- AnimIterator found_anim = mPlayingAnimations.find(anim_it->first);
-
- // signaled but not playing, or different sequence id, start motion
- if (found_anim == mPlayingAnimations.end() || found_anim->second != anim_it->second)
- {
- if (processSingleAnimationStateChange(anim_it->first, TRUE))
- {
- mPlayingAnimations[anim_it->first] = anim_it->second;
- ++anim_it;
- continue;
- }
- }
-
- ++anim_it;
- }
-
- // clear source information for animations which have been stopped
- if (isSelf())
- {
- AnimSourceIterator source_it = mAnimationSources.begin();
-
- for (source_it = mAnimationSources.begin(); source_it != mAnimationSources.end();)
- {
- if (mSignaledAnimations.find(source_it->second) == mSignaledAnimations.end())
- {
- mAnimationSources.erase(source_it++);
- }
- else
- {
- ++source_it;
- }
- }
- }
-
- stop_glerror();
-}
-
-
-//-----------------------------------------------------------------------------
-// processSingleAnimationStateChange();
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::processSingleAnimationStateChange( const LLUUID& anim_id, BOOL start )
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- BOOL result = FALSE;
-
- if ( start ) // start animation
- {
- if (anim_id == ANIM_AGENT_TYPE)
- {
- if (gAudiop)
- {
- LLVector3d char_pos_global = gAgent.getPosGlobalFromAgent(getCharacterPosition());
- if (LLViewerParcelMgr::getInstance()->canHearSound(char_pos_global)
- && !LLMuteList::getInstance()->isMuted(getID(), LLMute::flagObjectSounds))
- {
- // RN: uncomment this to play on typing sound at fixed volume once sound engine is fixed
- // to support both spatialized and non-spatialized instances of the same sound
- //if (isSelf())
- //{
- // gAudiop->triggerSound(LLUUID(gSavedSettings.getString("UISndTyping")), 1.0f, LLAudioEngine::AUDIO_TYPE_UI);
- //}
- //else
- {
- LLUUID sound_id = LLUUID(gSavedSettings.getString("UISndTyping"));
- gAudiop->triggerSound(sound_id, getID(), 1.0f, LLAudioEngine::AUDIO_TYPE_SFX, char_pos_global);
- }
- }
- }
- }
- else if (anim_id == ANIM_AGENT_SIT_GROUND_CONSTRAINED)
- {
- sitDown(TRUE);
- }
-
-
- if (startMotion(anim_id))
- {
- result = TRUE;
- }
- else
- {
- llwarns << "Failed to start motion!" << llendl;
- }
- }
- else //stop animation
- {
- if (anim_id == ANIM_AGENT_SIT_GROUND_CONSTRAINED)
- {
- sitDown(FALSE);
- }
- stopMotion(anim_id);
- result = TRUE;
- }
-
- return result;
-}
-
-//-----------------------------------------------------------------------------
-// isAnyAnimationSignaled()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::isAnyAnimationSignaled(const LLUUID *anim_array, const S32 num_anims) const
-{
- for (S32 i = 0; i < num_anims; i++)
- {
- if(mSignaledAnimations.find(anim_array[i]) != mSignaledAnimations.end())
- {
- return TRUE;
- }
- }
- return FALSE;
-}
-
-//-----------------------------------------------------------------------------
-// resetAnimations()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::resetAnimations()
-{
- LLKeyframeMotion::flushKeyframeCache();
- flushAllMotions();
-}
-
-// Override selectively based on avatar sex and whether we're using new
-// animations.
-LLUUID LLVOAvatar::remapMotionID(const LLUUID& id)
-{
- BOOL use_new_walk_run = gSavedSettings.getBOOL("UseNewWalkRun");
- LLUUID result = id;
-
- // start special case female walk for female avatars
- if (getSex() == SEX_FEMALE)
- {
- if (id == ANIM_AGENT_WALK)
- {
- if (use_new_walk_run)
- result = ANIM_AGENT_FEMALE_WALK_NEW;
- else
- result = ANIM_AGENT_FEMALE_WALK;
- }
- else if (id == ANIM_AGENT_RUN)
- {
- // There is no old female run animation, so only override
- // in one case.
- if (use_new_walk_run)
- result = ANIM_AGENT_FEMALE_RUN_NEW;
- }
- else if (id == ANIM_AGENT_SIT)
- {
- result = ANIM_AGENT_SIT_FEMALE;
- }
- }
- else
- {
- // Male avatar.
- if (id == ANIM_AGENT_WALK)
- {
- if (use_new_walk_run)
- result = ANIM_AGENT_WALK_NEW;
- }
- else if (id == ANIM_AGENT_RUN)
- {
- if (use_new_walk_run)
- result = ANIM_AGENT_RUN_NEW;
- }
-
- }
-
- return result;
-
-}
-
-//-----------------------------------------------------------------------------
-// startMotion()
-// id is the asset if of the animation to start
-// time_offset is the offset into the animation at which to start playing
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::startMotion(const LLUUID& id, F32 time_offset)
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- lldebugs << "motion requested " << id.asString() << " " << gAnimLibrary.animationName(id) << llendl;
-
- LLUUID remap_id = remapMotionID(id);
-
- if (remap_id != id)
- {
- lldebugs << "motion resultant " << remap_id.asString() << " " << gAnimLibrary.animationName(remap_id) << llendl;
- }
-
- if (isSelf() && remap_id == ANIM_AGENT_AWAY)
- {
- gAgent.setAFK();
- }
-
- return LLCharacter::startMotion(remap_id, time_offset);
-}
-
-//-----------------------------------------------------------------------------
-// stopMotion()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::stopMotion(const LLUUID& id, BOOL stop_immediate)
-{
- lldebugs << "motion requested " << id.asString() << " " << gAnimLibrary.animationName(id) << llendl;
-
- LLUUID remap_id = remapMotionID(id);
-
- if (remap_id != id)
- {
- lldebugs << "motion resultant " << remap_id.asString() << " " << gAnimLibrary.animationName(remap_id) << llendl;
- }
-
- if (isSelf())
- {
- gAgent.onAnimStop(remap_id);
- }
-
- return LLCharacter::stopMotion(remap_id, stop_immediate);
-}
-
-//-----------------------------------------------------------------------------
-// stopMotionFromSource()
-//-----------------------------------------------------------------------------
-// virtual
-void LLVOAvatar::stopMotionFromSource(const LLUUID& source_id)
-{
-}
-
-//-----------------------------------------------------------------------------
-// getVolumePos()
-//-----------------------------------------------------------------------------
-LLVector3 LLVOAvatar::getVolumePos(S32 joint_index, LLVector3& volume_offset)
-{
- if (joint_index > mNumCollisionVolumes)
- {
- return LLVector3::zero;
- }
-
- return mCollisionVolumes[joint_index].getVolumePos(volume_offset);
-}
-
-//-----------------------------------------------------------------------------
-// findCollisionVolume()
-//-----------------------------------------------------------------------------
-LLJoint* LLVOAvatar::findCollisionVolume(U32 volume_id)
-{
- if ((S32)volume_id > mNumCollisionVolumes)
- {
- return NULL;
- }
-
- return &mCollisionVolumes[volume_id];
-}
-
-//-----------------------------------------------------------------------------
-// findCollisionVolume()
-//-----------------------------------------------------------------------------
-S32 LLVOAvatar::getCollisionVolumeID(std::string &name)
-{
- for (S32 i = 0; i < mNumCollisionVolumes; i++)
- {
- if (mCollisionVolumes[i].getName() == name)
- {
- return i;
- }
- }
-
- return -1;
-}
-
-//-----------------------------------------------------------------------------
-// addDebugText()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::addDebugText(const std::string& text)
-{
- mDebugText.append(1, '\n');
- mDebugText.append(text);
-}
-
-//-----------------------------------------------------------------------------
-// getID()
-//-----------------------------------------------------------------------------
-const LLUUID& LLVOAvatar::getID()
-{
- return mID;
-}
-
-//-----------------------------------------------------------------------------
-// getJoint()
-//-----------------------------------------------------------------------------
-// RN: avatar joints are multi-rooted to include screen-based attachments
-LLJoint *LLVOAvatar::getJoint( const std::string &name )
-{
- LLJoint* jointp = mRoot.findJoint(name);
- return jointp;
-}
-
-//-----------------------------------------------------------------------------
-// getCharacterPosition()
-//-----------------------------------------------------------------------------
-LLVector3 LLVOAvatar::getCharacterPosition()
-{
- if (mDrawable.notNull())
- {
- return mDrawable->getPositionAgent();
- }
- else
- {
- return getPositionAgent();
- }
-}
-
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::getCharacterRotation()
-//-----------------------------------------------------------------------------
-LLQuaternion LLVOAvatar::getCharacterRotation()
-{
- return getRotation();
-}
-
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::getCharacterVelocity()
-//-----------------------------------------------------------------------------
-LLVector3 LLVOAvatar::getCharacterVelocity()
-{
- return getVelocity() - mStepObjectVelocity;
-}
-
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::getCharacterAngularVelocity()
-//-----------------------------------------------------------------------------
-LLVector3 LLVOAvatar::getCharacterAngularVelocity()
-{
- return getAngularVelocity();
-}
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::getGround()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::getGround(const LLVector3 &in_pos_agent, LLVector3 &out_pos_agent, LLVector3 &outNorm)
-{
- LLVector3d z_vec(0.0f, 0.0f, 1.0f);
- LLVector3d p0_global, p1_global;
-
- if (gNoRender || mIsDummy)
- {
- outNorm.setVec(z_vec);
- out_pos_agent = in_pos_agent;
- return;
- }
-
- p0_global = gAgent.getPosGlobalFromAgent(in_pos_agent) + z_vec;
- p1_global = gAgent.getPosGlobalFromAgent(in_pos_agent) - z_vec;
- LLViewerObject *obj;
- LLVector3d out_pos_global;
- LLWorld::getInstance()->resolveStepHeightGlobal(this, p0_global, p1_global, out_pos_global, outNorm, &obj);
- out_pos_agent = gAgent.getPosAgentFromGlobal(out_pos_global);
-}
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::getTimeDilation()
-//-----------------------------------------------------------------------------
-F32 LLVOAvatar::getTimeDilation()
-{
- return mTimeDilation;
-}
-
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::getPixelArea()
-//-----------------------------------------------------------------------------
-F32 LLVOAvatar::getPixelArea() const
-{
- if (mIsDummy)
- {
- return 100000.f;
- }
- return mPixelArea;
-}
-
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::getHeadMesh()
-//-----------------------------------------------------------------------------
-LLPolyMesh* LLVOAvatar::getHeadMesh()
-{
- return mMeshLOD[MESH_ID_HEAD]->mMeshParts[0]->getMesh();
-}
-
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::getUpperBodyMesh()
-//-----------------------------------------------------------------------------
-LLPolyMesh* LLVOAvatar::getUpperBodyMesh()
-{
- return mMeshLOD[MESH_ID_UPPER_BODY]->mMeshParts[0]->getMesh();
-}
-
-
-//-----------------------------------------------------------------------------
-// LLVOAvatar::getPosGlobalFromAgent()
-//-----------------------------------------------------------------------------
-LLVector3d LLVOAvatar::getPosGlobalFromAgent(const LLVector3 &position)
-{
- return gAgent.getPosGlobalFromAgent(position);
-}
-
-//-----------------------------------------------------------------------------
-// getPosAgentFromGlobal()
-//-----------------------------------------------------------------------------
-LLVector3 LLVOAvatar::getPosAgentFromGlobal(const LLVector3d &position)
-{
- return gAgent.getPosAgentFromGlobal(position);
-}
-
-//-----------------------------------------------------------------------------
-// allocateCharacterJoints()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::allocateCharacterJoints( U32 num )
-{
- deleteAndClearArray(mSkeleton);
- mNumJoints = 0;
-
- mSkeleton = new LLViewerJoint[num];
-
- for(S32 joint_num = 0; joint_num < (S32)num; joint_num++)
- {
- mSkeleton[joint_num].setJointNum(joint_num);
- }
-
- if (!mSkeleton)
- {
- return FALSE;
- }
-
- mNumJoints = num;
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// allocateCollisionVolumes()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::allocateCollisionVolumes( U32 num )
-{
- deleteAndClearArray(mCollisionVolumes);
- mNumCollisionVolumes = 0;
-
- mCollisionVolumes = new LLViewerJointCollisionVolume[num];
- if (!mCollisionVolumes)
- {
- return FALSE;
- }
-
- mNumCollisionVolumes = num;
- return TRUE;
-}
-
-
-//-----------------------------------------------------------------------------
-// getCharacterJoint()
-//-----------------------------------------------------------------------------
-LLJoint *LLVOAvatar::getCharacterJoint( U32 num )
-{
- if ((S32)num >= mNumJoints
- || (S32)num < 0)
- {
- return NULL;
- }
- return (LLJoint*)&mSkeleton[num];
-}
-
-//-----------------------------------------------------------------------------
-// requestStopMotion()
-//-----------------------------------------------------------------------------
-// virtual
-void LLVOAvatar::requestStopMotion( LLMotion* motion )
-{
- // Only agent avatars should handle the stop motion notifications.
-}
-
-//-----------------------------------------------------------------------------
-// loadAvatar()
-//-----------------------------------------------------------------------------
-static LLFastTimer::DeclareTimer FTM_LOAD_AVATAR("Load Avatar");
-
-BOOL LLVOAvatar::loadAvatar()
-{
-// LLFastTimer t(FTM_LOAD_AVATAR);
-
- // avatar_skeleton.xml
- if( !buildSkeleton(sAvatarSkeletonInfo) )
- {
- llwarns << "avatar file: buildSkeleton() failed" << llendl;
- return FALSE;
- }
-
- // avatar_lad.xml : <skeleton>
- if( !loadSkeletonNode() )
- {
- llwarns << "avatar file: loadNodeSkeleton() failed" << llendl;
- return FALSE;
- }
-
- // avatar_lad.xml : <mesh>
- if( !loadMeshNodes() )
- {
- llwarns << "avatar file: loadNodeMesh() failed" << llendl;
- return FALSE;
- }
-
- // avatar_lad.xml : <global_color>
- if( sAvatarXmlInfo->mTexSkinColorInfo )
- {
- mTexSkinColor = new LLTexGlobalColor( this );
- if( !mTexSkinColor->setInfo( sAvatarXmlInfo->mTexSkinColorInfo ) )
- {
- llwarns << "avatar file: mTexSkinColor->setInfo() failed" << llendl;
- return FALSE;
- }
- }
- else
- {
- llwarns << "<global_color> name=\"skin_color\" not found" << llendl;
- return FALSE;
- }
- if( sAvatarXmlInfo->mTexHairColorInfo )
- {
- mTexHairColor = new LLTexGlobalColor( this );
- if( !mTexHairColor->setInfo( sAvatarXmlInfo->mTexHairColorInfo ) )
- {
- llwarns << "avatar file: mTexHairColor->setInfo() failed" << llendl;
- return FALSE;
- }
- }
- else
- {
- llwarns << "<global_color> name=\"hair_color\" not found" << llendl;
- return FALSE;
- }
- if( sAvatarXmlInfo->mTexEyeColorInfo )
- {
- mTexEyeColor = new LLTexGlobalColor( this );
- if( !mTexEyeColor->setInfo( sAvatarXmlInfo->mTexEyeColorInfo ) )
- {
- llwarns << "avatar file: mTexEyeColor->setInfo() failed" << llendl;
- return FALSE;
- }
- }
- else
- {
- llwarns << "<global_color> name=\"eye_color\" not found" << llendl;
- return FALSE;
- }
-
- // avatar_lad.xml : <layer_set>
- if (sAvatarXmlInfo->mLayerInfoList.empty())
- {
- llwarns << "avatar file: missing <layer_set> node" << llendl;
- return FALSE;
- }
-
- if (sAvatarXmlInfo->mMorphMaskInfoList.empty())
- {
- llwarns << "avatar file: missing <morph_masks> node" << llendl;
- return FALSE;
- }
-
- // avatar_lad.xml : <morph_masks>
- for (LLVOAvatarXmlInfo::morph_info_list_t::iterator iter = sAvatarXmlInfo->mMorphMaskInfoList.begin();
- iter != sAvatarXmlInfo->mMorphMaskInfoList.end();
- ++iter)
- {
- LLVOAvatarXmlInfo::LLVOAvatarMorphInfo *info = *iter;
-
- EBakedTextureIndex baked = LLVOAvatarDictionary::findBakedByRegionName(info->mRegion);
- if (baked != BAKED_NUM_INDICES)
- {
- LLPolyMorphTarget *morph_param;
- const std::string *name = &info->mName;
- morph_param = (LLPolyMorphTarget *)(getVisualParam(name->c_str()));
- if (morph_param)
- {
- BOOL invert = info->mInvert;
- addMaskedMorph(baked, morph_param, invert, info->mLayer);
- }
- }
-
- }
-
- loadLayersets();
-
- // avatar_lad.xml : <driver_parameters>
- for (LLVOAvatarXmlInfo::driver_info_list_t::iterator iter = sAvatarXmlInfo->mDriverInfoList.begin();
- iter != sAvatarXmlInfo->mDriverInfoList.end();
- ++iter)
- {
- LLDriverParamInfo *info = *iter;
- LLDriverParam* driver_param = new LLDriverParam( this );
- if (driver_param->setInfo(info))
- {
- addVisualParam( driver_param );
- LLVisualParam*(LLVOAvatar::*avatar_function)(S32)const = &LLVOAvatar::getVisualParam;
- if( !driver_param->linkDrivenParams(boost::bind(avatar_function,(LLVOAvatar*)this,_1 ), false))
- {
- llwarns << "could not link driven params for avatar " << this->getFullname() << " id: " << driver_param->getID() << llendl;
- continue;
- }
- }
- else
- {
- delete driver_param;
- llwarns << "avatar file: driver_param->parseData() failed" << llendl;
- return FALSE;
- }
- }
-
- // Uncomment to enable avatar_lad.xml debugging.
- std::ofstream file;
- file.open("avatar_lad.log");
- for( LLViewerVisualParam* param = (LLViewerVisualParam*) getFirstVisualParam();
- param;
- param = (LLViewerVisualParam*) getNextVisualParam() )
- {
- param->getInfo()->toStream(file);
- file << std::endl;
- }
-
- file.close();
-
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// loadSkeletonNode(): loads <skeleton> node from XML tree
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::loadSkeletonNode ()
-{
- mRoot.addChild( &mSkeleton[0] );
-
- for (std::vector<LLViewerJoint *>::iterator iter = mMeshLOD.begin();
- iter != mMeshLOD.end();
- ++iter)
- {
- LLViewerJoint *joint = (LLViewerJoint *) *iter;
- joint->mUpdateXform = FALSE;
- joint->setMeshesToChildren();
- }
-
- mRoot.addChild(mMeshLOD[MESH_ID_HEAD]);
- mRoot.addChild(mMeshLOD[MESH_ID_EYELASH]);
- mRoot.addChild(mMeshLOD[MESH_ID_UPPER_BODY]);
- mRoot.addChild(mMeshLOD[MESH_ID_LOWER_BODY]);
- mRoot.addChild(mMeshLOD[MESH_ID_SKIRT]);
- mRoot.addChild(mMeshLOD[MESH_ID_HEAD]);
-
- LLViewerJoint *skull = (LLViewerJoint*)mRoot.findJoint("mSkull");
- if (skull)
- {
- skull->addChild(mMeshLOD[MESH_ID_HAIR] );
- }
-
- LLViewerJoint *eyeL = (LLViewerJoint*)mRoot.findJoint("mEyeLeft");
- if (eyeL)
- {
- eyeL->addChild( mMeshLOD[MESH_ID_EYEBALL_LEFT] );
- }
-
- LLViewerJoint *eyeR = (LLViewerJoint*)mRoot.findJoint("mEyeRight");
- if (eyeR)
- {
- eyeR->addChild( mMeshLOD[MESH_ID_EYEBALL_RIGHT] );
- }
-
- // SKELETAL DISTORTIONS
- {
- LLVOAvatarXmlInfo::skeletal_distortion_info_list_t::iterator iter;
- for (iter = sAvatarXmlInfo->mSkeletalDistortionInfoList.begin();
- iter != sAvatarXmlInfo->mSkeletalDistortionInfoList.end();
- ++iter)
- {
- LLPolySkeletalDistortionInfo *info = *iter;
- LLPolySkeletalDistortion *param = new LLPolySkeletalDistortion(this);
- if (!param->setInfo(info))
- {
- delete param;
- return FALSE;
- }
- else
- {
- addVisualParam(param);
- }
- }
- }
-
- // ATTACHMENTS
- {
- LLVOAvatarXmlInfo::attachment_info_list_t::iterator iter;
- for (iter = sAvatarXmlInfo->mAttachmentInfoList.begin();
- iter != sAvatarXmlInfo->mAttachmentInfoList.end();
- ++iter)
- {
- LLVOAvatarXmlInfo::LLVOAvatarAttachmentInfo *info = *iter;
- if (!isSelf() && info->mJointName == "mScreen")
- { //don't process screen joint for other avatars
- continue;
- }
-
- LLViewerJointAttachment* attachment = new LLViewerJointAttachment();
-
- attachment->setName(info->mName);
- LLJoint *parentJoint = getJoint(info->mJointName);
- if (!parentJoint)
- {
- llwarns << "No parent joint by name " << info->mJointName << " found for attachment point " << info->mName << llendl;
- delete attachment;
- continue;
- }
-
- if (info->mHasPosition)
- {
- attachment->setOriginalPosition(info->mPosition);
- }
-
- if (info->mHasRotation)
- {
- LLQuaternion rotation;
- rotation.setQuat(info->mRotationEuler.mV[VX] * DEG_TO_RAD,
- info->mRotationEuler.mV[VY] * DEG_TO_RAD,
- info->mRotationEuler.mV[VZ] * DEG_TO_RAD);
- attachment->setRotation(rotation);
- }
-
- int group = info->mGroup;
- if (group >= 0)
- {
- if (group < 0 || group >= 9)
- {
- llwarns << "Invalid group number (" << group << ") for attachment point " << info->mName << llendl;
- }
- else
- {
- attachment->setGroup(group);
- }
- }
-
- S32 attachmentID = info->mAttachmentID;
- if (attachmentID < 1 || attachmentID > 255)
- {
- llwarns << "Attachment point out of range [1-255]: " << attachmentID << " on attachment point " << info->mName << llendl;
- delete attachment;
- continue;
- }
- if (mAttachmentPoints.find(attachmentID) != mAttachmentPoints.end())
- {
- llwarns << "Attachment point redefined with id " << attachmentID << " on attachment point " << info->mName << llendl;
- delete attachment;
- continue;
- }
-
- attachment->setPieSlice(info->mPieMenuSlice);
- attachment->setVisibleInFirstPerson(info->mVisibleFirstPerson);
- attachment->setIsHUDAttachment(info->mIsHUDAttachment);
-
- mAttachmentPoints[attachmentID] = attachment;
-
- // now add attachment joint
- parentJoint->addChild(attachment);
- }
- }
-
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// loadMeshNodes(): loads <mesh> nodes from XML tree
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::loadMeshNodes()
-{
- for (LLVOAvatarXmlInfo::mesh_info_list_t::const_iterator meshinfo_iter = sAvatarXmlInfo->mMeshInfoList.begin();
- meshinfo_iter != sAvatarXmlInfo->mMeshInfoList.end();
- ++meshinfo_iter)
- {
- const LLVOAvatarXmlInfo::LLVOAvatarMeshInfo *info = *meshinfo_iter;
- const std::string &type = info->mType;
- S32 lod = info->mLOD;
-
- LLViewerJointMesh* mesh = NULL;
- U8 mesh_id = 0;
- BOOL found_mesh_id = FALSE;
-
- /* if (type == "hairMesh")
- switch(lod)
- case 0:
- mesh = &mHairMesh0; */
- for (LLVOAvatarDictionary::Meshes::const_iterator mesh_iter = LLVOAvatarDictionary::getInstance()->getMeshes().begin();
- mesh_iter != LLVOAvatarDictionary::getInstance()->getMeshes().end();
- ++mesh_iter)
- {
- const EMeshIndex mesh_index = mesh_iter->first;
- const LLVOAvatarDictionary::MeshEntry *mesh_dict = mesh_iter->second;
- if (type.compare(mesh_dict->mName) == 0)
- {
- mesh_id = mesh_index;
- found_mesh_id = TRUE;
- break;
- }
- }
-
- if (found_mesh_id)
- {
- if (lod < (S32)mMeshLOD[mesh_id]->mMeshParts.size())
- {
- mesh = mMeshLOD[mesh_id]->mMeshParts[lod];
- }
- else
- {
- llwarns << "Avatar file: <mesh> has invalid lod setting " << lod << llendl;
- return FALSE;
- }
- }
- else
- {
- llwarns << "Ignoring unrecognized mesh type: " << type << llendl;
- return FALSE;
- }
-
- // llinfos << "Parsing mesh data for " << type << "..." << llendl;
-
- // If this isn't set to white (1.0), avatars will *ALWAYS* be darker than their surroundings.
- // Do not touch!!!
- mesh->setColor( 1.0f, 1.0f, 1.0f, 1.0f );
-
- LLPolyMesh *poly_mesh = NULL;
-
- if (!info->mReferenceMeshName.empty())
- {
- polymesh_map_t::const_iterator polymesh_iter = mMeshes.find(info->mReferenceMeshName);
- if (polymesh_iter != mMeshes.end())
- {
- poly_mesh = LLPolyMesh::getMesh(info->mMeshFileName, polymesh_iter->second);
- poly_mesh->setAvatar(this);
- }
- else
- {
- // This should never happen
- LL_WARNS("Avatar") << "Could not find avatar mesh: " << info->mReferenceMeshName << LL_ENDL;
- }
- }
- else
- {
- poly_mesh = LLPolyMesh::getMesh(info->mMeshFileName);
- poly_mesh->setAvatar(this);
- }
-
- if( !poly_mesh )
- {
- llwarns << "Failed to load mesh of type " << type << llendl;
- return FALSE;
- }
-
- // Multimap insert
- mMeshes.insert(std::make_pair(info->mMeshFileName, poly_mesh));
-
- mesh->setMesh( poly_mesh );
- mesh->setLOD( info->mMinPixelArea );
-
- for (LLVOAvatarXmlInfo::LLVOAvatarMeshInfo::morph_info_list_t::const_iterator xmlinfo_iter = info->mPolyMorphTargetInfoList.begin();
- xmlinfo_iter != info->mPolyMorphTargetInfoList.end();
- ++xmlinfo_iter)
- {
- const LLVOAvatarXmlInfo::LLVOAvatarMeshInfo::morph_info_pair_t *info_pair = &(*xmlinfo_iter);
- LLPolyMorphTarget *param = new LLPolyMorphTarget(mesh->getMesh());
- if (!param->setInfo(info_pair->first))
- {
- delete param;
- return FALSE;
- }
- else
- {
- if (info_pair->second)
- {
- addSharedVisualParam(param);
- }
- else
- {
- addVisualParam(param);
- }
- }
- }
- }
-
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// loadLayerSets()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::loadLayersets()
-{
- BOOL success = TRUE;
- for (LLVOAvatarXmlInfo::layer_info_list_t::const_iterator layerset_iter = sAvatarXmlInfo->mLayerInfoList.begin();
- layerset_iter != sAvatarXmlInfo->mLayerInfoList.end();
- ++layerset_iter)
- {
- // Construct a layerset for each one specified in avatar_lad.xml and initialize it as such.
- LLTexLayerSetInfo *layerset_info = *layerset_iter;
- layerset_info->createVisualParams(this);
- }
- return success;
-}
-
-//-----------------------------------------------------------------------------
-// updateVisualParams()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::updateVisualParams()
-{
- if (gNoRender)
- {
- return;
- }
-
- setSex( (getVisualParamWeight( "male" ) > 0.5f) ? SEX_MALE : SEX_FEMALE );
-
- LLCharacter::updateVisualParams();
-
- if (mLastSkeletonSerialNum != mSkeletonSerialNum)
- {
- computeBodySize();
- mLastSkeletonSerialNum = mSkeletonSerialNum;
- mRoot.updateWorldMatrixChildren();
- }
-
- dirtyMesh();
- updateHeadOffset();
-}
-
-//-----------------------------------------------------------------------------
-// isActive()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::isActive() const
-{
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// setPixelAreaAndAngle()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::setPixelAreaAndAngle(LLAgent &agent)
-{
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
- if (mDrawable.isNull())
- {
- return;
- }
-
- const LLVector3* ext = mDrawable->getSpatialExtents();
- LLVector3 center = (ext[1] + ext[0]) * 0.5f;
- LLVector3 size = (ext[1]-ext[0])*0.5f;
-
- mImpostorPixelArea = LLPipeline::calcPixelArea(center, size, *LLViewerCamera::getInstance());
-
- F32 range = mDrawable->mDistanceWRTCamera;
-
- if (range < 0.001f) // range == zero
- {
- mAppAngle = 180.f;
- }
- else
- {
- F32 radius = size.length();
- mAppAngle = (F32) atan2( radius, range) * RAD_TO_DEG;
- }
-
- // We always want to look good to ourselves
- if( isSelf() )
- {
- mPixelArea = llmax( mPixelArea, F32(getTexImageSize() / 16) );
- }
-}
-
-//-----------------------------------------------------------------------------
-// updateJointLODs()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::updateJointLODs()
-{
- const F32 MAX_PIXEL_AREA = 100000000.f;
- F32 lod_factor = (sLODFactor * AVATAR_LOD_TWEAK_RANGE + (1.f - AVATAR_LOD_TWEAK_RANGE));
- F32 avatar_num_min_factor = clamp_rescale(sLODFactor, 0.f, 1.f, 0.25f, 0.6f);
- F32 avatar_num_factor = clamp_rescale((F32)sNumVisibleAvatars, 8, 25, 1.f, avatar_num_min_factor);
- F32 area_scale = 0.16f;
-
- {
- if (isSelf())
- {
- if(gAgentCamera.cameraCustomizeAvatar() || gAgentCamera.cameraMouselook())
- {
- mAdjustedPixelArea = MAX_PIXEL_AREA;
- }
- else
- {
- mAdjustedPixelArea = mPixelArea*area_scale;
- }
- }
- else if (mIsDummy)
- {
- mAdjustedPixelArea = MAX_PIXEL_AREA;
- }
- else
- {
- // reported avatar pixel area is dependent on avatar render load, based on number of visible avatars
- mAdjustedPixelArea = (F32)mPixelArea * area_scale * lod_factor * lod_factor * avatar_num_factor * avatar_num_factor;
- }
-
- // now select meshes to render based on adjusted pixel area
- BOOL res = mRoot.updateLOD(mAdjustedPixelArea, TRUE);
- if (res)
- {
- sNumLODChangesThisFrame++;
- dirtyMesh(2);
- return TRUE;
- }
- }
-
- return FALSE;
-}
-
-//-----------------------------------------------------------------------------
-// createDrawable()
-//-----------------------------------------------------------------------------
-LLDrawable *LLVOAvatar::createDrawable(LLPipeline *pipeline)
-{
- pipeline->allocDrawable(this);
- mDrawable->setLit(FALSE);
-
- LLDrawPoolAvatar *poolp = (LLDrawPoolAvatar*) gPipeline.getPool(LLDrawPool::POOL_AVATAR);
-
- // Only a single face (one per avatar)
- //this face will be splitted into several if its vertex buffer is too long.
- mDrawable->setState(LLDrawable::ACTIVE);
- mDrawable->addFace(poolp, NULL);
- mDrawable->setRenderType(LLPipeline::RENDER_TYPE_AVATAR);
-
- mNumInitFaces = mDrawable->getNumFaces() ;
-
- dirtyMesh(2);
- return mDrawable;
-}
-
-
-void LLVOAvatar::updateGL()
-{
- if (mMeshTexturesDirty)
- {
- updateMeshTextures();
- mMeshTexturesDirty = FALSE;
- }
-}
-
-//-----------------------------------------------------------------------------
-// updateGeometry()
-//-----------------------------------------------------------------------------
-static LLFastTimer::DeclareTimer FTM_UPDATE_AVATAR("Update Avatar");
-BOOL LLVOAvatar::updateGeometry(LLDrawable *drawable)
-{
- LLFastTimer ftm(FTM_UPDATE_AVATAR);
- if (!(gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_AVATAR)))
- {
- return TRUE;
- }
-
- if (!mMeshValid)
- {
- return TRUE;
- }
-
- if (!drawable)
- {
- llerrs << "LLVOAvatar::updateGeometry() called with NULL drawable" << llendl;
- }
-
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// updateSexDependentLayerSets()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::updateSexDependentLayerSets( BOOL upload_bake )
-{
- invalidateComposite( mBakedTextureDatas[BAKED_HEAD].mTexLayerSet, upload_bake );
- invalidateComposite( mBakedTextureDatas[BAKED_UPPER].mTexLayerSet, upload_bake );
- invalidateComposite( mBakedTextureDatas[BAKED_LOWER].mTexLayerSet, upload_bake );
-}
-
-//-----------------------------------------------------------------------------
-// dirtyMesh()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::dirtyMesh()
-{
- dirtyMesh(1);
-}
-void LLVOAvatar::dirtyMesh(S32 priority)
-{
- mDirtyMesh = llmax(mDirtyMesh, priority);
-}
-//-----------------------------------------------------------------------------
-// hideSkirt()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::hideSkirt()
-{
- mMeshLOD[MESH_ID_SKIRT]->setVisible(FALSE, TRUE);
-}
-
-BOOL LLVOAvatar::setParent(LLViewerObject* parent)
-{
- BOOL ret ;
- if (parent == NULL)
- {
- getOffObject();
- ret = LLViewerObject::setParent(parent);
- if (isSelf())
- {
- gAgentCamera.resetCamera();
- }
- }
- else
- {
- ret = LLViewerObject::setParent(parent);
- if(ret)
- {
- sitOnObject(parent);
- }
- }
- return ret ;
-}
-
-void LLVOAvatar::addChild(LLViewerObject *childp)
-{
- childp->extractAttachmentItemID(); // find the inventory item this object is associated with.
- LLViewerObject::addChild(childp);
- if (childp->mDrawable)
- {
- attachObject(childp);
- }
- else
- {
- mPendingAttachment.push_back(childp);
- }
-}
-
-void LLVOAvatar::removeChild(LLViewerObject *childp)
-{
- LLViewerObject::removeChild(childp);
- if (!detachObject(childp))
- {
- llwarns << "Calling detach on non-attached object " << llendl;
- }
-}
-
-LLViewerJointAttachment* LLVOAvatar::getTargetAttachmentPoint(LLViewerObject* viewer_object)
-{
- S32 attachmentID = ATTACHMENT_ID_FROM_STATE(viewer_object->getState());
-
- // This should never happen unless the server didn't process the attachment point
- // correctly, but putting this check in here to be safe.
- if (attachmentID & ATTACHMENT_ADD)
- {
- llwarns << "Got an attachment with ATTACHMENT_ADD mask, removing ( attach pt:" << attachmentID << " )" << llendl;
- attachmentID &= ~ATTACHMENT_ADD;
- }
-
- LLViewerJointAttachment* attachment = get_if_there(mAttachmentPoints, attachmentID, (LLViewerJointAttachment*)NULL);
-
- if (!attachment)
- {
- llwarns << "Object attachment point invalid: " << attachmentID << llendl;
- attachment = get_if_there(mAttachmentPoints, 1, (LLViewerJointAttachment*)NULL); // Arbitrary using 1 (chest)
- }
-
- return attachment;
-}
-
-//-----------------------------------------------------------------------------
-// attachObject()
-//-----------------------------------------------------------------------------
-const LLViewerJointAttachment *LLVOAvatar::attachObject(LLViewerObject *viewer_object)
-{
- LLViewerJointAttachment* attachment = getTargetAttachmentPoint(viewer_object);
-
- if (!attachment || !attachment->addObject(viewer_object))
- {
- return 0;
- }
-
- if (viewer_object->isSelected())
- {
- LLSelectMgr::getInstance()->updateSelectionCenter();
- LLSelectMgr::getInstance()->updatePointAt();
- }
-
- return attachment;
-}
-
-//-----------------------------------------------------------------------------
-// attachObject()
-//-----------------------------------------------------------------------------
-U32 LLVOAvatar::getNumAttachments() const
-{
- U32 num_attachments = 0;
- for (attachment_map_t::const_iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- const LLViewerJointAttachment *attachment_pt = (*iter).second;
- num_attachments += attachment_pt->getNumObjects();
- }
- return num_attachments;
-}
-
-//-----------------------------------------------------------------------------
-// canAttachMoreObjects()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::canAttachMoreObjects() const
-{
- return (getNumAttachments() < MAX_AGENT_ATTACHMENTS);
-}
-
-//-----------------------------------------------------------------------------
-// canAttachMoreObjects()
-// Returns true if we can attach <n> more objects.
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::canAttachMoreObjects(U32 n) const
-{
- return (getNumAttachments() + n) <= MAX_AGENT_ATTACHMENTS;
-}
-
-//-----------------------------------------------------------------------------
-// lazyAttach()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::lazyAttach()
-{
- std::vector<LLPointer<LLViewerObject> > still_pending;
-
- for (U32 i = 0; i < mPendingAttachment.size(); i++)
- {
- if (mPendingAttachment[i]->mDrawable)
- {
- attachObject(mPendingAttachment[i]);
- }
- else
- {
- still_pending.push_back(mPendingAttachment[i]);
- }
- }
-
- mPendingAttachment = still_pending;
-}
-
-void LLVOAvatar::resetHUDAttachments()
-{
- for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
- if (attachment->getIsHUDAttachment())
- {
- for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
- attachment_iter != attachment->mAttachedObjects.end();
- ++attachment_iter)
- {
- const LLViewerObject* attached_object = (*attachment_iter);
- if (attached_object && attached_object->mDrawable.notNull())
- {
- gPipeline.markMoved(attached_object->mDrawable);
- }
- }
- }
- }
-}
-
-//-----------------------------------------------------------------------------
-// detachObject()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::detachObject(LLViewerObject *viewer_object)
-{
- for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
-
- if (attachment->isObjectAttached(viewer_object))
- {
- attachment->removeObject(viewer_object);
- lldebugs << "Detaching object " << viewer_object->mID << " from " << attachment->getName() << llendl;
- return TRUE;
- }
- }
- return FALSE;
-}
-
-//-----------------------------------------------------------------------------
-// sitDown()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::sitDown(BOOL bSitting)
-{
- mIsSitting = bSitting;
- if (isSelf())
- {
- // Update Movement Controls according to own Sitting mode
- LLFloaterMove::setSittingMode(bSitting);
- }
-}
-
-//-----------------------------------------------------------------------------
-// sitOnObject()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::sitOnObject(LLViewerObject *sit_object)
-{
- if (isSelf())
- {
- // Might be first sit
- //LLFirstUse::useSit();
-
- gAgent.setFlying(FALSE);
- gAgentCamera.setThirdPersonHeadOffset(LLVector3::zero);
- //interpolate to new camera position
- gAgentCamera.startCameraAnimation();
- // make sure we are not trying to autopilot
- gAgent.stopAutoPilot();
- gAgentCamera.setupSitCamera();
- if (gAgentCamera.getForceMouselook())
- {
- gAgentCamera.changeCameraToMouselook();
- }
- }
-
- if (mDrawable.isNull())
- {
- return;
- }
- LLQuaternion inv_obj_rot = ~sit_object->getRenderRotation();
- LLVector3 obj_pos = sit_object->getRenderPosition();
-
- LLVector3 rel_pos = getRenderPosition() - obj_pos;
- rel_pos.rotVec(inv_obj_rot);
-
- mDrawable->mXform.setPosition(rel_pos);
- mDrawable->mXform.setRotation(mDrawable->getWorldRotation() * inv_obj_rot);
-
- gPipeline.markMoved(mDrawable, TRUE);
- // Notice that removing sitDown() from here causes avatars sitting on
- // objects to be not rendered for new arrivals. See EXT-6835 and EXT-1655.
- sitDown(TRUE);
- mRoot.getXform()->setParent(&sit_object->mDrawable->mXform); // LLVOAvatar::sitOnObject
- mRoot.setPosition(getPosition());
- mRoot.updateWorldMatrixChildren();
-
- stopMotion(ANIM_AGENT_BODY_NOISE);
-
-}
-
-//-----------------------------------------------------------------------------
-// getOffObject()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::getOffObject()
-{
- if (mDrawable.isNull())
- {
- return;
- }
-
- LLViewerObject* sit_object = (LLViewerObject*)getParent();
-
- if (sit_object)
- {
- stopMotionFromSource(sit_object->getID());
- LLFollowCamMgr::setCameraActive(sit_object->getID(), FALSE);
-
- LLViewerObject::const_child_list_t& child_list = sit_object->getChildren();
- for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
- iter != child_list.end(); ++iter)
- {
- LLViewerObject* child_objectp = *iter;
-
- stopMotionFromSource(child_objectp->getID());
- LLFollowCamMgr::setCameraActive(child_objectp->getID(), FALSE);
- }
- }
-
- // assumes that transform will not be updated with drawable still having a parent
- LLVector3 cur_position_world = mDrawable->getWorldPosition();
- LLQuaternion cur_rotation_world = mDrawable->getWorldRotation();
-
- // set *local* position based on last *world* position, since we're unparenting the avatar
- mDrawable->mXform.setPosition(cur_position_world);
- mDrawable->mXform.setRotation(cur_rotation_world);
-
- gPipeline.markMoved(mDrawable, TRUE);
-
- sitDown(FALSE);
-
- mRoot.getXform()->setParent(NULL); // LLVOAvatar::getOffObject
- mRoot.setPosition(cur_position_world);
- mRoot.setRotation(cur_rotation_world);
- mRoot.getXform()->update();
-
- startMotion(ANIM_AGENT_BODY_NOISE);
-
- if (isSelf())
- {
- LLQuaternion av_rot = gAgent.getFrameAgent().getQuaternion();
- LLQuaternion obj_rot = sit_object ? sit_object->getRenderRotation() : LLQuaternion::DEFAULT;
- av_rot = av_rot * obj_rot;
- LLVector3 at_axis = LLVector3::x_axis;
- at_axis = at_axis * av_rot;
- at_axis.mV[VZ] = 0.f;
- at_axis.normalize();
- gAgent.resetAxes(at_axis);
-
- //reset orientation
-// mRoot.setRotation(avWorldRot);
- gAgentCamera.setThirdPersonHeadOffset(LLVector3(0.f, 0.f, 1.f));
-
- gAgentCamera.setSitCamera(LLUUID::null);
- }
-}
-
-//-----------------------------------------------------------------------------
-// findAvatarFromAttachment()
-//-----------------------------------------------------------------------------
-// static
-LLVOAvatar* LLVOAvatar::findAvatarFromAttachment( LLViewerObject* obj )
-{
- if( obj->isAttachment() )
- {
- do
- {
- obj = (LLViewerObject*) obj->getParent();
- }
- while( obj && !obj->isAvatar() );
-
- if( obj && !obj->isDead() )
- {
- return (LLVOAvatar*)obj;
- }
- }
- return NULL;
-}
-
-// warning: order(N) not order(1)
-S32 LLVOAvatar::getAttachmentCount()
-{
- S32 count = mAttachmentPoints.size();
- return count;
-}
-
-LLColor4 LLVOAvatar::getGlobalColor( const std::string& color_name ) const
-{
- if (color_name=="skin_color" && mTexSkinColor)
- {
- return mTexSkinColor->getColor();
- }
- else if(color_name=="hair_color" && mTexHairColor)
- {
- return mTexHairColor->getColor();
- }
- if(color_name=="eye_color" && mTexEyeColor)
- {
- return mTexEyeColor->getColor();
- }
- else
- {
-// return LLColor4( .5f, .5f, .5f, .5f );
- return LLColor4( 0.f, 1.f, 1.f, 1.f ); // good debugging color
- }
-}
-
-// virtual
-void LLVOAvatar::invalidateComposite( LLTexLayerSet* layerset, BOOL upload_result )
-{
-}
-
-void LLVOAvatar::invalidateAll()
-{
-}
-
-void LLVOAvatar::onGlobalColorChanged(const LLTexGlobalColor* global_color, BOOL upload_bake )
-{
- if (global_color == mTexSkinColor)
- {
- invalidateComposite( mBakedTextureDatas[BAKED_HEAD].mTexLayerSet, upload_bake );
- invalidateComposite( mBakedTextureDatas[BAKED_UPPER].mTexLayerSet, upload_bake );
- invalidateComposite( mBakedTextureDatas[BAKED_LOWER].mTexLayerSet, upload_bake );
- }
- else if (global_color == mTexHairColor)
- {
- invalidateComposite( mBakedTextureDatas[BAKED_HEAD].mTexLayerSet, upload_bake );
- invalidateComposite( mBakedTextureDatas[BAKED_HAIR].mTexLayerSet, upload_bake );
-
- // ! BACKWARDS COMPATIBILITY !
- // Fix for dealing with avatars from viewers that don't bake hair.
- if (!isTextureDefined(mBakedTextureDatas[BAKED_HAIR].mTextureIndex))
- {
- LLColor4 color = mTexHairColor->getColor();
- for (U32 i = 0; i < mBakedTextureDatas[BAKED_HAIR].mMeshes.size(); i++)
- {
- mBakedTextureDatas[BAKED_HAIR].mMeshes[i]->setColor( color.mV[VX], color.mV[VY], color.mV[VZ], color.mV[VW] );
- }
- }
- }
- else if (global_color == mTexEyeColor)
- {
-// llinfos << "invalidateComposite cause: onGlobalColorChanged( eyecolor )" << llendl;
- invalidateComposite( mBakedTextureDatas[BAKED_EYES].mTexLayerSet, upload_bake );
- }
- updateMeshTextures();
-}
-
-BOOL LLVOAvatar::isVisible() const
-{
- return mDrawable.notNull()
- && (mDrawable->isVisible() || mIsDummy);
-}
-
-// Determine if we have enough avatar data to render
-BOOL LLVOAvatar::getIsCloud()
-{
- // Do we have a shape?
- if (visualParamWeightsAreDefault())
- {
- return TRUE;
- }
-
- if (!isTextureDefined(TEX_LOWER_BAKED) ||
- !isTextureDefined(TEX_UPPER_BAKED) ||
- !isTextureDefined(TEX_HEAD_BAKED))
- {
- return TRUE;
- }
- return FALSE;
-}
-
-// call periodically to keep isFullyLoaded up to date.
-// returns true if the value has changed.
-BOOL LLVOAvatar::updateIsFullyLoaded()
-{
- const BOOL loading = getIsCloud();
- updateRuthTimer(loading);
- return processFullyLoadedChange(loading);
-}
-
-void LLVOAvatar::updateRuthTimer(bool loading)
-{
- if (isSelf() || !loading)
- {
- return;
- }
-
- if (mPreviousFullyLoaded)
- {
- mRuthTimer.reset();
- if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
- {
- llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' became cloud." << llendl;
- LLSD args;
- args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
- args["TIME"] = llformat("%d",(U32)mRuthDebugTimer.getElapsedTimeF32());
- args["NAME"] = getFullname();
- LLNotificationsUtil::add("AvatarRezCloudNotification",args);
- }
- mRuthDebugTimer.reset();
- }
-
- const F32 LOADING_TIMEOUT__SECONDS = 120.f;
- if (mRuthTimer.getElapsedTimeF32() > LOADING_TIMEOUT__SECONDS)
- {
- llinfos << "Ruth Timer timeout: Missing texture data for '" << getFullname() << "' "
- << "( Params loaded : " << !visualParamWeightsAreDefault() << " ) "
- << "( Lower : " << isTextureDefined(TEX_LOWER_BAKED) << " ) "
- << "( Upper : " << isTextureDefined(TEX_UPPER_BAKED) << " ) "
- << "( Head : " << isTextureDefined(TEX_HEAD_BAKED) << " )."
- << llendl;
-
- LLAvatarPropertiesProcessor::getInstance()->sendAvatarTexturesRequest(getID());
- mRuthTimer.reset();
- }
-}
-
-BOOL LLVOAvatar::processFullyLoadedChange(bool loading)
-{
- // we wait a little bit before giving the all clear,
- // to let textures settle down
- const F32 PAUSE = 1.f;
- if (loading)
- mFullyLoadedTimer.reset();
-
- mFullyLoaded = (mFullyLoadedTimer.getElapsedTimeF32() > PAUSE);
-
- if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
- {
- if (!mPreviousFullyLoaded && !loading && mFullyLoaded)
- {
- llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' resolved in " << (U32)mRuthDebugTimer.getElapsedTimeF32() << " seconds." << llendl;
- LLSD args;
- args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
- args["TIME"] = llformat("%d",(U32)mRuthDebugTimer.getElapsedTimeF32());
- args["NAME"] = getFullname();
- LLNotificationsUtil::add("AvatarRezNotification",args);
- }
- }
-
- // did our loading state "change" from last call?
- const S32 UPDATE_RATE = 30;
- BOOL changed =
- ((mFullyLoaded != mPreviousFullyLoaded) || // if the value is different from the previous call
- (!mFullyLoadedInitialized) || // if we've never been called before
- (mFullyLoadedFrameCounter % UPDATE_RATE == 0)); // every now and then issue a change
-
- mPreviousFullyLoaded = mFullyLoaded;
- mFullyLoadedInitialized = TRUE;
- mFullyLoadedFrameCounter++;
-
- return changed;
-}
-
-BOOL LLVOAvatar::isFullyLoaded() const
-{
- if (gSavedSettings.getBOOL("RenderUnloadedAvatar"))
- return TRUE;
- else
- return mFullyLoaded;
-}
-
-
-//-----------------------------------------------------------------------------
-// findMotion()
-//-----------------------------------------------------------------------------
-LLMotion* LLVOAvatar::findMotion(const LLUUID& id) const
-{
- return mMotionController.findMotion(id);
-}
-
-//-----------------------------------------------------------------------------
-// updateMeshTextures()
-// Uses the current TE values to set the meshes' and layersets' textures.
-//-----------------------------------------------------------------------------
-void LLVOAvatar::updateMeshTextures()
-{
- // llinfos << "updateMeshTextures" << llendl;
- if (gNoRender) return;
-
- // if user has never specified a texture, assign the default
- for (U32 i=0; i < getNumTEs(); i++)
- {
- const LLViewerTexture* te_image = getImage(i, 0);
- if(!te_image || te_image->getID().isNull() || (te_image->getID() == IMG_DEFAULT))
- {
- setImage(i, LLViewerTextureManager::getFetchedTexture(i == TEX_HAIR ? IMG_DEFAULT : IMG_DEFAULT_AVATAR), 0); // IMG_DEFAULT_AVATAR = a special texture that's never rendered.
- }
- }
-
- const BOOL self_customizing = isSelf() && gAgentCamera.cameraCustomizeAvatar(); // During face edit mode, we don't use baked textures
- const BOOL other_culled = !isSelf() && mCulled;
- LLLoadedCallbackEntry::source_callback_list_t* src_callback_list = NULL ;
- BOOL paused = FALSE;
- if(!isSelf())
- {
- src_callback_list = &mCallbackTextureList ;
- paused = mLoadedCallbacksPaused ;
- }
-
- std::vector<BOOL> is_layer_baked;
- is_layer_baked.resize(mBakedTextureDatas.size(), false);
-
- std::vector<BOOL> use_lkg_baked_layer; // lkg = "last known good"
- use_lkg_baked_layer.resize(mBakedTextureDatas.size(), false);
-
- for (U32 i=0; i < mBakedTextureDatas.size(); i++)
- {
- is_layer_baked[i] = isTextureDefined(mBakedTextureDatas[i].mTextureIndex);
-
- if (!other_culled)
- {
- // When an avatar is changing clothes and not in Appearance mode,
- // use the last-known good baked texture until it finish the first
- // render of the new layerset.
-
- const BOOL layerset_invalid = mBakedTextureDatas[i].mTexLayerSet
- && ( !mBakedTextureDatas[i].mTexLayerSet->getComposite()->isInitialized()
- || !mBakedTextureDatas[i].mTexLayerSet->isLocalTextureDataAvailable() );
-
- use_lkg_baked_layer[i] = (!is_layer_baked[i]
- && (mBakedTextureDatas[i].mLastTextureIndex != IMG_DEFAULT_AVATAR)
- && layerset_invalid);
- if (use_lkg_baked_layer[i])
- {
- mBakedTextureDatas[i].mTexLayerSet->setUpdatesEnabled(TRUE);
- }
- }
- else
- {
- use_lkg_baked_layer[i] = (!is_layer_baked[i]
- && mBakedTextureDatas[i].mLastTextureIndex != IMG_DEFAULT_AVATAR);
- if (mBakedTextureDatas[i].mTexLayerSet)
- {
- mBakedTextureDatas[i].mTexLayerSet->destroyComposite();
- }
- }
-
- }
-
- // Turn on alpha masking correctly for yourself and other avatars on 1.23+
- mSupportsAlphaLayers = isSelf() || is_layer_baked[BAKED_HAIR];
-
- // Baked textures should be requested from the sim this avatar is on. JC
- const LLHost target_host = getObjectHost();
- if (!target_host.isOk())
- {
- llwarns << "updateMeshTextures: invalid host for object: " << getID() << llendl;
- }
-
- for (U32 i=0; i < mBakedTextureDatas.size(); i++)
- {
- if (use_lkg_baked_layer[i] && !self_customizing )
- {
- LLViewerFetchedTexture* baked_img = LLViewerTextureManager::getFetchedTextureFromHost( mBakedTextureDatas[i].mLastTextureIndex, target_host );
- mBakedTextureDatas[i].mIsUsed = TRUE;
- for (U32 k=0; k < mBakedTextureDatas[i].mMeshes.size(); k++)
- {
- mBakedTextureDatas[i].mMeshes[k]->setTexture( baked_img );
- }
- }
- else if (!self_customizing && is_layer_baked[i])
- {
- LLViewerFetchedTexture* baked_img = LLViewerTextureManager::staticCastToFetchedTexture(getImage( mBakedTextureDatas[i].mTextureIndex, 0 ), TRUE) ;
- if( baked_img->getID() == mBakedTextureDatas[i].mLastTextureIndex )
- {
- // Even though the file may not be finished loading, we'll consider it loaded and use it (rather than doing compositing).
- useBakedTexture( baked_img->getID() );
- }
- else
- {
- mBakedTextureDatas[i].mIsLoaded = FALSE;
- if ( (baked_img->getID() != IMG_INVISIBLE) && ((i == BAKED_HEAD) || (i == BAKED_UPPER) || (i == BAKED_LOWER)) )
- {
- baked_img->setLoadedCallback(onBakedTextureMasksLoaded, MORPH_MASK_REQUESTED_DISCARD, TRUE, TRUE, new LLTextureMaskData( mID ),
- src_callback_list, paused);
- }
- baked_img->setLoadedCallback(onBakedTextureLoaded, SWITCH_TO_BAKED_DISCARD, FALSE, FALSE, new LLUUID( mID ),
- src_callback_list, paused );
- }
- }
- else if (mBakedTextureDatas[i].mTexLayerSet
- && !other_culled)
- {
- mBakedTextureDatas[i].mTexLayerSet->createComposite();
- mBakedTextureDatas[i].mTexLayerSet->setUpdatesEnabled( TRUE );
- mBakedTextureDatas[i].mIsUsed = FALSE;
- for (U32 k=0; k < mBakedTextureDatas[i].mMeshes.size(); k++)
- {
- mBakedTextureDatas[i].mMeshes[k]->setLayerSet( mBakedTextureDatas[i].mTexLayerSet );
- }
- }
- }
-
- // set texture and color of hair manually if we are not using a baked image.
- // This can happen while loading hair for yourself, or for clients that did not
- // bake a hair texture. Still needed for yourself after 1.22 is depricated.
- if (!is_layer_baked[BAKED_HAIR] || self_customizing)
- {
- const LLColor4 color = mTexHairColor ? mTexHairColor->getColor() : LLColor4(1,1,1,1);
- LLViewerTexture* hair_img = getImage( TEX_HAIR, 0 );
- for (U32 i = 0; i < mBakedTextureDatas[BAKED_HAIR].mMeshes.size(); i++)
- {
- mBakedTextureDatas[BAKED_HAIR].mMeshes[i]->setColor( color.mV[VX], color.mV[VY], color.mV[VZ], color.mV[VW] );
- mBakedTextureDatas[BAKED_HAIR].mMeshes[i]->setTexture( hair_img );
- }
- }
-
-
- for (LLVOAvatarDictionary::BakedTextures::const_iterator baked_iter = LLVOAvatarDictionary::getInstance()->getBakedTextures().begin();
- baked_iter != LLVOAvatarDictionary::getInstance()->getBakedTextures().end();
- ++baked_iter)
- {
- const EBakedTextureIndex baked_index = baked_iter->first;
- const LLVOAvatarDictionary::BakedEntry *baked_dict = baked_iter->second;
-
- for (texture_vec_t::const_iterator local_tex_iter = baked_dict->mLocalTextures.begin();
- local_tex_iter != baked_dict->mLocalTextures.end();
- ++local_tex_iter)
- {
- const ETextureIndex texture_index = *local_tex_iter;
- const BOOL is_baked_ready = (is_layer_baked[baked_index] && mBakedTextureDatas[baked_index].mIsLoaded) || other_culled;
- if (isSelf())
- {
- setBakedReady(texture_index, is_baked_ready);
- }
- }
- }
- removeMissingBakedTextures();
-}
-
-// virtual
-//-----------------------------------------------------------------------------
-// setLocalTexture()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::setLocalTexture( ETextureIndex type, LLViewerTexture* in_tex, BOOL baked_version_ready, U32 index )
-{
- // invalid for anyone but self
- llassert(0);
-}
-
-//virtual
-void LLVOAvatar::setBakedReady(LLVOAvatarDefines::ETextureIndex type, BOOL baked_version_exists, U32 index)
-{
- // invalid for anyone but self
- llassert(0);
-}
-
-void LLVOAvatar::addChat(const LLChat& chat)
-{
- std::deque<LLChat>::iterator chat_iter;
-
- mChats.push_back(chat);
-
- S32 chat_length = 0;
- for( chat_iter = mChats.begin(); chat_iter != mChats.end(); ++chat_iter)
- {
- chat_length += chat_iter->mText.size();
- }
-
- // remove any excess chat
- chat_iter = mChats.begin();
- while ((chat_length > MAX_BUBBLE_CHAT_LENGTH || mChats.size() > MAX_BUBBLE_CHAT_UTTERANCES) && chat_iter != mChats.end())
- {
- chat_length -= chat_iter->mText.size();
- mChats.pop_front();
- chat_iter = mChats.begin();
- }
-
- mChatTimer.reset();
-}
-
-void LLVOAvatar::clearChat()
-{
- mChats.clear();
-}
-
-// adds a morph mask to the appropriate baked texture structure
-void LLVOAvatar::addMaskedMorph(EBakedTextureIndex index, LLPolyMorphTarget* morph_target, BOOL invert, std::string layer)
-{
- if (index < BAKED_NUM_INDICES)
- {
- LLMaskedMorph *morph = new LLMaskedMorph(morph_target, invert, layer);
- mBakedTextureDatas[index].mMaskedMorphs.push_front(morph);
- }
-}
-
-// returns TRUE if morph masks are present and not valid for a given baked texture, FALSE otherwise
-BOOL LLVOAvatar::morphMaskNeedsUpdate(LLVOAvatarDefines::EBakedTextureIndex index)
-{
- if (index >= BAKED_NUM_INDICES)
- {
- return FALSE;
- }
-
- if (!mBakedTextureDatas[index].mMaskedMorphs.empty())
- {
- if (isSelf())
- {
- LLTexLayerSet *layer_set = mBakedTextureDatas[index].mTexLayerSet;
- if (layer_set)
- {
- return !layer_set->isMorphValid();
- }
- }
- else
- {
- return FALSE;
- }
- }
-
- return FALSE;
-}
-
-void LLVOAvatar::applyMorphMask(U8* tex_data, S32 width, S32 height, S32 num_components, LLVOAvatarDefines::EBakedTextureIndex index)
-{
- if (index >= BAKED_NUM_INDICES)
- {
- llwarns << "invalid baked texture index passed to applyMorphMask" << llendl;
- return;
- }
-
- for (morph_list_t::const_iterator iter = mBakedTextureDatas[index].mMaskedMorphs.begin();
- iter != mBakedTextureDatas[index].mMaskedMorphs.end(); ++iter)
- {
- const LLMaskedMorph* maskedMorph = (*iter);
- maskedMorph->mMorphTarget->applyMask(tex_data, width, height, num_components, maskedMorph->mInvert);
- }
-}
-
-
-//-----------------------------------------------------------------------------
-// releaseComponentTextures()
-// release any component texture UUIDs for which we have a baked texture
-// ! BACKWARDS COMPATIBILITY !
-// This is only called for non-self avatars, it can be taken out once component
-// textures aren't communicated by non-self avatars.
-//-----------------------------------------------------------------------------
-void LLVOAvatar::releaseComponentTextures()
-{
- // ! BACKWARDS COMPATIBILITY !
- // Detect if the baked hair texture actually wasn't sent, and if so set to default
- if (isTextureDefined(TEX_HAIR_BAKED) && getImage(TEX_HAIR_BAKED,0)->getID() == getImage(TEX_SKIRT_BAKED,0)->getID())
- {
- if (getImage(TEX_HAIR_BAKED,0)->getID() != IMG_INVISIBLE)
- {
- // Regression case of messaging system. Expected 21 textures, received 20. last texture is not valid so set to default
- setTETexture(TEX_HAIR_BAKED, IMG_DEFAULT_AVATAR);
- }
- }
-
- for (U8 baked_index = 0; baked_index < BAKED_NUM_INDICES; baked_index++)
- {
- const LLVOAvatarDictionary::BakedEntry * bakedDicEntry = LLVOAvatarDictionary::getInstance()->getBakedTexture((EBakedTextureIndex)baked_index);
- // skip if this is a skirt and av is not wearing one, or if we don't have a baked texture UUID
- if (!isTextureDefined(bakedDicEntry->mTextureIndex)
- && ( (baked_index != BAKED_SKIRT) || isWearingWearableType(LLWearableType::WT_SKIRT) ))
- {
- continue;
- }
-
- for (U8 texture = 0; texture < bakedDicEntry->mLocalTextures.size(); texture++)
- {
- const U8 te = (ETextureIndex)bakedDicEntry->mLocalTextures[texture];
- setTETexture(te, IMG_DEFAULT_AVATAR);
- }
- }
-}
-
-//static
-BOOL LLVOAvatar::teToColorParams( ETextureIndex te, U32 *param_name )
-{
- switch( te )
- {
- case TEX_UPPER_SHIRT:
- param_name[0] = 803; //"shirt_red";
- param_name[1] = 804; //"shirt_green";
- param_name[2] = 805; //"shirt_blue";
- break;
-
- case TEX_LOWER_PANTS:
- param_name[0] = 806; //"pants_red";
- param_name[1] = 807; //"pants_green";
- param_name[2] = 808; //"pants_blue";
- break;
-
- case TEX_LOWER_SHOES:
- param_name[0] = 812; //"shoes_red";
- param_name[1] = 813; //"shoes_green";
- param_name[2] = 817; //"shoes_blue";
- break;
-
- case TEX_LOWER_SOCKS:
- param_name[0] = 818; //"socks_red";
- param_name[1] = 819; //"socks_green";
- param_name[2] = 820; //"socks_blue";
- break;
-
- case TEX_UPPER_JACKET:
- case TEX_LOWER_JACKET:
- param_name[0] = 834; //"jacket_red";
- param_name[1] = 835; //"jacket_green";
- param_name[2] = 836; //"jacket_blue";
- break;
-
- case TEX_UPPER_GLOVES:
- param_name[0] = 827; //"gloves_red";
- param_name[1] = 829; //"gloves_green";
- param_name[2] = 830; //"gloves_blue";
- break;
-
- case TEX_UPPER_UNDERSHIRT:
- param_name[0] = 821; //"undershirt_red";
- param_name[1] = 822; //"undershirt_green";
- param_name[2] = 823; //"undershirt_blue";
- break;
-
- case TEX_LOWER_UNDERPANTS:
- param_name[0] = 824; //"underpants_red";
- param_name[1] = 825; //"underpants_green";
- param_name[2] = 826; //"underpants_blue";
- break;
-
- case TEX_SKIRT:
- param_name[0] = 921; //"skirt_red";
- param_name[1] = 922; //"skirt_green";
- param_name[2] = 923; //"skirt_blue";
- break;
-
- case TEX_HEAD_TATTOO:
- case TEX_LOWER_TATTOO:
- case TEX_UPPER_TATTOO:
- param_name[0] = 1071; //"tattoo_red";
- param_name[1] = 1072; //"tattoo_green";
- param_name[2] = 1073; //"tattoo_blue";
- break;
-
- default:
- llassert(0);
- return FALSE;
- }
-
- return TRUE;
-}
-
-void LLVOAvatar::setClothesColor( ETextureIndex te, const LLColor4& new_color, BOOL upload_bake )
-{
- U32 param_name[3];
- if( teToColorParams( te, param_name ) )
- {
- setVisualParamWeight( param_name[0], new_color.mV[VX], upload_bake );
- setVisualParamWeight( param_name[1], new_color.mV[VY], upload_bake );
- setVisualParamWeight( param_name[2], new_color.mV[VZ], upload_bake );
- }
-}
-
-LLColor4 LLVOAvatar::getClothesColor( ETextureIndex te )
-{
- LLColor4 color;
- U32 param_name[3];
- if( teToColorParams( te, param_name ) )
- {
- color.mV[VX] = getVisualParamWeight( param_name[0] );
- color.mV[VY] = getVisualParamWeight( param_name[1] );
- color.mV[VZ] = getVisualParamWeight( param_name[2] );
- }
- return color;
-}
-
-// static
-LLColor4 LLVOAvatar::getDummyColor()
-{
- return DUMMY_COLOR;
-}
-
-void LLVOAvatar::dumpAvatarTEs( const std::string& context ) const
-{
- llinfos << (isSelf() ? "Self: " : "Other: ") << context << llendl;
- for (LLVOAvatarDictionary::Textures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
- iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
- ++iter)
- {
- const LLVOAvatarDictionary::TextureEntry *texture_dict = iter->second;
- // TODO: MULTI-WEARABLE: handle multiple textures for self
- const LLViewerTexture* te_image = getImage(iter->first,0);
- if( !te_image )
- {
- llinfos << " " << texture_dict->mName << ": null ptr" << llendl;
- }
- else if( te_image->getID().isNull() )
- {
- llinfos << " " << texture_dict->mName << ": null UUID" << llendl;
- }
- else if( te_image->getID() == IMG_DEFAULT )
- {
- llinfos << " " << texture_dict->mName << ": IMG_DEFAULT" << llendl;
- }
- else if( te_image->getID() == IMG_DEFAULT_AVATAR )
- {
- llinfos << " " << texture_dict->mName << ": IMG_DEFAULT_AVATAR" << llendl;
- }
- else
- {
- llinfos << " " << texture_dict->mName << ": " << te_image->getID() << llendl;
- }
- }
-}
-
-// Unlike most wearable functions, this works for both self and other.
-BOOL LLVOAvatar::isWearingWearableType(LLWearableType::EType type) const
-{
- if (mIsDummy) return TRUE;
-
- switch(type)
- {
- case LLWearableType::WT_SHAPE:
- case LLWearableType::WT_SKIN:
- case LLWearableType::WT_HAIR:
- case LLWearableType::WT_EYES:
- return TRUE; // everyone has all bodyparts
- default:
- break; // Do nothing
- }
-
- /* switch(type)
- case LLWearableType::WT_SHIRT:
- indicator_te = TEX_UPPER_SHIRT; */
- for (LLVOAvatarDictionary::Textures::const_iterator tex_iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
- tex_iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
- ++tex_iter)
- {
- const LLVOAvatarDictionary::TextureEntry *texture_dict = tex_iter->second;
- if (texture_dict->mWearableType == type)
- {
- // If you're checking another avatar's clothing, you don't have component textures.
- // Thus, you must check to see if the corresponding baked texture is defined.
- // NOTE: this is a poor substitute if you actually want to know about individual pieces of clothing
- // this works for detecting a skirt (most important), but is ineffective at any piece of clothing that
- // gets baked into a texture that always exists (upper or lower).
- if (texture_dict->mIsUsedByBakedTexture)
- {
- const EBakedTextureIndex baked_index = texture_dict->mBakedTextureIndex;
- return isTextureDefined(LLVOAvatarDictionary::getInstance()->getBakedTexture(baked_index)->mTextureIndex);
- }
- return FALSE;
- }
- }
- return FALSE;
-}
-
-//-----------------------------------------------------------------------------
-// clampAttachmentPositions()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::clampAttachmentPositions()
-{
- if (isDead())
- {
- return;
- }
- for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
- if (attachment)
- {
- attachment->clampObjectPosition();
- }
- }
-}
-
-BOOL LLVOAvatar::hasHUDAttachment() const
-{
- for (attachment_map_t::const_iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
- if (attachment->getIsHUDAttachment() && attachment->getNumObjects() > 0)
- {
- return TRUE;
- }
- }
- return FALSE;
-}
-
-LLBBox LLVOAvatar::getHUDBBox() const
-{
- LLBBox bbox;
- for (attachment_map_t::const_iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
- if (attachment->getIsHUDAttachment())
- {
- for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
- attachment_iter != attachment->mAttachedObjects.end();
- ++attachment_iter)
- {
- const LLViewerObject* attached_object = (*attachment_iter);
- if (attached_object == NULL)
- {
- llwarns << "HUD attached object is NULL!" << llendl;
- continue;
- }
- // initialize bounding box to contain identity orientation and center point for attached object
- bbox.addPointLocal(attached_object->getPosition());
- // add rotated bounding box for attached object
- bbox.addBBoxAgent(attached_object->getBoundingBoxAgent());
- LLViewerObject::const_child_list_t& child_list = attached_object->getChildren();
- for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
- iter != child_list.end();
- ++iter)
- {
- const LLViewerObject* child_objectp = *iter;
- bbox.addBBoxAgent(child_objectp->getBoundingBoxAgent());
- }
- }
- }
- }
-
- return bbox;
-}
-
-void LLVOAvatar::rebuildHUD()
-{
-}
-
-//-----------------------------------------------------------------------------
-// onFirstTEMessageReceived()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::onFirstTEMessageReceived()
-{
- if( !mFirstTEMessageReceived )
- {
- mFirstTEMessageReceived = TRUE;
-
- LLLoadedCallbackEntry::source_callback_list_t* src_callback_list = NULL ;
- BOOL paused = FALSE ;
- if(!isSelf())
- {
- src_callback_list = &mCallbackTextureList ;
- paused = mLoadedCallbacksPaused ;
- }
-
- for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
- {
- const BOOL layer_baked = isTextureDefined(mBakedTextureDatas[i].mTextureIndex);
-
- // Use any baked textures that we have even if they haven't downloaded yet.
- // (That is, don't do a transition from unbaked to baked.)
- if (layer_baked)
- {
- LLViewerFetchedTexture* image = LLViewerTextureManager::staticCastToFetchedTexture(getImage( mBakedTextureDatas[i].mTextureIndex, 0 ), TRUE) ;
- mBakedTextureDatas[i].mLastTextureIndex = image->getID();
- // If we have more than one texture for the other baked layers, we'll want to call this for them too.
- if ( (image->getID() != IMG_INVISIBLE) && ((i == BAKED_HEAD) || (i == BAKED_UPPER) || (i == BAKED_LOWER)) )
- {
- image->setLoadedCallback( onBakedTextureMasksLoaded, MORPH_MASK_REQUESTED_DISCARD, TRUE, TRUE, new LLTextureMaskData( mID ),
- src_callback_list, paused);
- }
- image->setLoadedCallback( onInitialBakedTextureLoaded, MAX_DISCARD_LEVEL, FALSE, FALSE, new LLUUID( mID ),
- src_callback_list, paused );
- }
- }
-
- mMeshTexturesDirty = TRUE;
- gPipeline.markGLRebuild(this);
- }
-}
-
-//-----------------------------------------------------------------------------
-// bool visualParamWeightsAreDefault()
-//-----------------------------------------------------------------------------
-bool LLVOAvatar::visualParamWeightsAreDefault()
-{
- bool rtn = true;
-
- bool is_wearing_skirt = isWearingWearableType(LLWearableType::WT_SKIRT);
- for (LLVisualParam *param = getFirstVisualParam();
- param;
- param = getNextVisualParam())
- {
- if (param->isTweakable())
- {
- LLViewerVisualParam* vparam = dynamic_cast<LLViewerVisualParam*>(param);
- llassert(vparam);
- bool is_skirt_param = vparam &&
- LLWearableType::WT_SKIRT == vparam->getWearableType();
- if (param->getWeight() != param->getDefaultWeight() &&
- // we have to not care whether skirt weights are default, if we're not actually wearing a skirt
- (is_wearing_skirt || !is_skirt_param))
- {
- //llinfos << "param '" << param->getName() << "'=" << param->getWeight() << " which differs from default=" << param->getDefaultWeight() << llendl;
- rtn = false;
- break;
- }
- }
- }
-
- //llinfos << "params are default ? " << int(rtn) << llendl;
-
- return rtn;
-}
-
-
-//-----------------------------------------------------------------------------
-// processAvatarAppearance()
-//-----------------------------------------------------------------------------
-void LLVOAvatar::processAvatarAppearance( LLMessageSystem* mesgsys )
-{
- if (gSavedSettings.getBOOL("BlockAvatarAppearanceMessages"))
- {
- llwarns << "Blocking AvatarAppearance message" << llendl;
- return;
- }
-
- LLMemType mt(LLMemType::MTYPE_AVATAR);
-
-// llinfos << "processAvatarAppearance start " << mID << llendl;
- BOOL is_first_appearance_message = !mFirstAppearanceMessageReceived;
-
- mFirstAppearanceMessageReceived = TRUE;
-
- if( isSelf() )
- {
- llwarns << "Received AvatarAppearance for self" << llendl;
- if( mFirstTEMessageReceived )
- {
-// llinfos << "processAvatarAppearance end " << mID << llendl;
- return;
- }
- }
-
- if (gNoRender)
- {
- return;
- }
-
- ESex old_sex = getSex();
-
-// llinfos << "LLVOAvatar::processAvatarAppearance()" << llendl;
-// dumpAvatarTEs( "PRE processAvatarAppearance()" );
- unpackTEMessage(mesgsys, _PREHASH_ObjectData);
-// dumpAvatarTEs( "POST processAvatarAppearance()" );
-
- // prevent the overwriting of valid baked textures with invalid baked textures
- for (U8 baked_index = 0; baked_index < mBakedTextureDatas.size(); baked_index++)
- {
- if (!isTextureDefined(mBakedTextureDatas[baked_index].mTextureIndex)
- && mBakedTextureDatas[baked_index].mLastTextureIndex != IMG_DEFAULT
- && baked_index != BAKED_SKIRT)
- {
- setTEImage(mBakedTextureDatas[baked_index].mTextureIndex,
- LLViewerTextureManager::getFetchedTexture(mBakedTextureDatas[baked_index].mLastTextureIndex, TRUE, LLViewerTexture::BOOST_NONE, LLViewerTexture::LOD_TEXTURE));
- }
- }
-
-
- if( !is_first_appearance_message )
- {
- onFirstTEMessageReceived();
- }
-
- setCompositeUpdatesEnabled( FALSE );
- mMeshTexturesDirty = TRUE;
- gPipeline.markGLRebuild(this);
-
- // ! BACKWARDS COMPATIBILITY !
- // Non-self avatars will no longer have component textures
- if (!isSelf())
- {
- releaseComponentTextures();
- }
-
- // parse visual params
- S32 num_blocks = mesgsys->getNumberOfBlocksFast(_PREHASH_VisualParam);
- bool drop_visual_params_debug = gSavedSettings.getBOOL("BlockSomeAvatarAppearanceVisualParams") && (ll_rand(2) == 0); // pretend that ~12% of AvatarAppearance messages arrived without a VisualParam block, for testing
- if( num_blocks > 1 && !drop_visual_params_debug)
- {
- BOOL params_changed = FALSE;
- BOOL interp_params = FALSE;
-
- LLVisualParam* param = getFirstVisualParam();
- llassert(param); // if this ever fires, we should do the same as when num_blocks<=1
- if (!param)
- {
- llwarns << "No visual params!" << llendl;
- }
- else
- {
- for( S32 i = 0; i < num_blocks; i++ )
- {
- while( param && (param->getGroup() != VISUAL_PARAM_GROUP_TWEAKABLE) ) // should not be any of group VISUAL_PARAM_GROUP_TWEAKABLE_NO_TRANSMIT
- {
- param = getNextVisualParam();
- }
-
- if( !param )
- {
- // more visual params supplied than expected - just process what we know about
- break;
- }
-
- U8 value;
- mesgsys->getU8Fast(_PREHASH_VisualParam, _PREHASH_ParamValue, value, i);
- F32 newWeight = U8_to_F32(value, param->getMinWeight(), param->getMaxWeight());
-
- if (is_first_appearance_message || (param->getWeight() != newWeight))
- {
- //llinfos << "Received update for param " << param->getDisplayName() << " at value " << newWeight << llendl;
- params_changed = TRUE;
- if(is_first_appearance_message)
- {
- param->setWeight(newWeight, FALSE);
- }
- else
- {
- interp_params = TRUE;
- param->setAnimationTarget(newWeight, FALSE);
- }
- }
- param = getNextVisualParam();
- }
- }
-
- const S32 expected_tweakable_count = getVisualParamCountInGroup(VISUAL_PARAM_GROUP_TWEAKABLE); // don't worry about VISUAL_PARAM_GROUP_TWEAKABLE_NO_TRANSMIT
- if (num_blocks != expected_tweakable_count)
- {
- llinfos << "Number of params in AvatarAppearance msg (" << num_blocks << ") does not match number of tweakable params in avatar xml file (" << expected_tweakable_count << "). Processing what we can. object: " << getID() << llendl;
- }
-
- if (params_changed)
- {
- if (interp_params)
- {
- startAppearanceAnimation();
- }
- updateVisualParams();
-
- ESex new_sex = getSex();
- if( old_sex != new_sex )
- {
- updateSexDependentLayerSets( FALSE );
- }
- }
-
- llassert( getSex() == ((getVisualParamWeight( "male" ) > 0.5f) ? SEX_MALE : SEX_FEMALE) );
- }
- else
- {
- // AvatarAppearance message arrived without visual params
- if (drop_visual_params_debug)
- {
- llinfos << "Debug-faked lack of parameters on AvatarAppearance for object: " << getID() << llendl;
- }
- else
- {
- llinfos << "AvatarAppearance msg received without any parameters, object: " << getID() << llendl;
- }
-
- const F32 LOADING_TIMEOUT_SECONDS = 60.f;
- // this isn't really a problem if we already have a non-default shape
- if (visualParamWeightsAreDefault() && mRuthTimer.getElapsedTimeF32() > LOADING_TIMEOUT_SECONDS)
- {
- // re-request appearance, hoping that it comes back with a shape next time
- llinfos << "Re-requesting AvatarAppearance for object: " << getID() << llendl;
- LLAvatarPropertiesProcessor::getInstance()->sendAvatarTexturesRequest(getID());
- mRuthTimer.reset();
- }
- else
- {
- llinfos << "That's okay, we already have a non-default shape for object: " << getID() << llendl;
- // we don't really care.
- }
- }
-
- setCompositeUpdatesEnabled( TRUE );
-
- // If all of the avatars are completely baked, release the global image caches to conserve memory.
- LLVOAvatar::cullAvatarsByPixelArea();
-
-// llinfos << "processAvatarAppearance end " << mID << llendl;
-}
-
-// static
-void LLVOAvatar::getAnimLabels( LLDynamicArray<std::string>* labels )
-{
- S32 i;
- for( i = 0; i < gUserAnimStatesCount; i++ )
- {
- labels->put( LLAnimStateLabels::getStateLabel( gUserAnimStates[i].mName ) );
- }
-
- // Special case to trigger away (AFK) state
- labels->put( "Away From Keyboard" );
-}
-
-// static
-void LLVOAvatar::getAnimNames( LLDynamicArray<std::string>* names )
-{
- S32 i;
-
- for( i = 0; i < gUserAnimStatesCount; i++ )
- {
- names->put( std::string(gUserAnimStates[i].mName) );
- }
-
- // Special case to trigger away (AFK) state
- names->put( "enter_away_from_keyboard_state" );
-}
-
-void LLVOAvatar::onBakedTextureMasksLoaded( BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata )
-{
- if (!userdata) return;
-
- //llinfos << "onBakedTextureMasksLoaded: " << src_vi->getID() << llendl;
- const LLMemType mt(LLMemType::MTYPE_AVATAR);
- const LLUUID id = src_vi->getID();
-
- LLTextureMaskData* maskData = (LLTextureMaskData*) userdata;
- LLVOAvatar* self = (LLVOAvatar*) gObjectList.findObject( maskData->mAvatarID );
-
- // if discard level is 2 less than last discard level we processed, or we hit 0,
- // then generate morph masks
- if(self && success && (discard_level < maskData->mLastDiscardLevel - 2 || discard_level == 0))
- {
- if(aux_src && aux_src->getComponents() == 1)
- {
- if (!aux_src->getData())
- {
- llerrs << "No auxiliary source data for onBakedTextureMasksLoaded" << llendl;
- return;
- }
-
- U32 gl_name;
- LLImageGL::generateTextures(1, &gl_name );
- stop_glerror();
-
- gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, gl_name);
- stop_glerror();
-
- LLImageGL::setManualImage(
- GL_TEXTURE_2D, 0, GL_ALPHA8,
- aux_src->getWidth(), aux_src->getHeight(),
- GL_ALPHA, GL_UNSIGNED_BYTE, aux_src->getData());
- stop_glerror();
-
- gGL.getTexUnit(0)->setTextureFilteringOption(LLTexUnit::TFO_BILINEAR);
-
- /* if( id == head_baked->getID() )
- if (self->mBakedTextureDatas[BAKED_HEAD].mTexLayerSet)
- //llinfos << "onBakedTextureMasksLoaded for head " << id << " discard = " << discard_level << llendl;
- self->mBakedTextureDatas[BAKED_HEAD].mTexLayerSet->applyMorphMask(aux_src->getData(), aux_src->getWidth(), aux_src->getHeight(), 1);
- maskData->mLastDiscardLevel = discard_level; */
- BOOL found_texture_id = false;
- for (LLVOAvatarDictionary::Textures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
- iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
- ++iter)
- {
-
- const LLVOAvatarDictionary::TextureEntry *texture_dict = iter->second;
- if (texture_dict->mIsUsedByBakedTexture)
- {
- const ETextureIndex texture_index = iter->first;
- const LLViewerTexture *baked_img = self->getImage(texture_index, 0);
- if (baked_img && id == baked_img->getID())
- {
- const EBakedTextureIndex baked_index = texture_dict->mBakedTextureIndex;
- self->applyMorphMask(aux_src->getData(), aux_src->getWidth(), aux_src->getHeight(), 1, baked_index);
- maskData->mLastDiscardLevel = discard_level;
- if (self->mBakedTextureDatas[baked_index].mMaskTexName)
- {
- LLImageGL::deleteTextures(1, &(self->mBakedTextureDatas[baked_index].mMaskTexName));
- }
- self->mBakedTextureDatas[baked_index].mMaskTexName = gl_name;
- found_texture_id = true;
- break;
- }
- }
- }
- if (!found_texture_id)
- {
- llinfos << "onBakedTextureMasksLoaded(): unexpected image id: " << id << llendl;
- }
- self->dirtyMesh();
- }
- else
- {
- // this can happen when someone uses an old baked texture possibly provided by
- // viewer-side baked texture caching
- llwarns << "Masks loaded callback but NO aux source!" << llendl;
- }
- }
-
- if (final || !success)
- {
- delete maskData;
- }
-}
-
-// static
-void LLVOAvatar::onInitialBakedTextureLoaded( BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata )
-{
- LLUUID *avatar_idp = (LLUUID *)userdata;
- LLVOAvatar *selfp = (LLVOAvatar *)gObjectList.findObject(*avatar_idp);
-
- if (!success && selfp)
- {
- selfp->removeMissingBakedTextures();
- }
- if (final || !success )
- {
- delete avatar_idp;
- }
-}
-
-void LLVOAvatar::onBakedTextureLoaded(BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata)
-{
- //llinfos << "onBakedTextureLoaded: " << src_vi->getID() << llendl;
-
- LLUUID id = src_vi->getID();
- LLUUID *avatar_idp = (LLUUID *)userdata;
- LLVOAvatar *selfp = (LLVOAvatar *)gObjectList.findObject(*avatar_idp);
-
- if (selfp && !success)
- {
- selfp->removeMissingBakedTextures();
- }
-
- if( final || !success )
- {
- delete avatar_idp;
- }
-
- if( selfp && success && final )
- {
- selfp->useBakedTexture( id );
- }
-}
-
-
-// Called when baked texture is loaded and also when we start up with a baked texture
-void LLVOAvatar::useBakedTexture( const LLUUID& id )
-{
- /* if(id == head_baked->getID())
- mHeadBakedLoaded = TRUE;
- mLastHeadBakedID = id;
- mHeadMesh0.setTexture( head_baked );
- mHeadMesh1.setTexture( head_baked ); */
- for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
- {
- LLViewerTexture* image_baked = getImage( mBakedTextureDatas[i].mTextureIndex, 0 );
- if (id == image_baked->getID())
- {
- mBakedTextureDatas[i].mIsLoaded = true;
- mBakedTextureDatas[i].mLastTextureIndex = id;
- mBakedTextureDatas[i].mIsUsed = true;
- for (U32 k = 0; k < mBakedTextureDatas[i].mMeshes.size(); k++)
- {
- mBakedTextureDatas[i].mMeshes[k]->setTexture( image_baked );
- }
- if (mBakedTextureDatas[i].mTexLayerSet)
- {
- //mBakedTextureDatas[i].mTexLayerSet->destroyComposite();
- }
- const LLVOAvatarDictionary::BakedEntry *baked_dict = LLVOAvatarDictionary::getInstance()->getBakedTexture((EBakedTextureIndex)i);
- for (texture_vec_t::const_iterator local_tex_iter = baked_dict->mLocalTextures.begin();
- local_tex_iter != baked_dict->mLocalTextures.end();
- ++local_tex_iter)
- {
- if (isSelf()) setBakedReady(*local_tex_iter, TRUE);
- }
-
- // ! BACKWARDS COMPATIBILITY !
- // Workaround for viewing avatars from old viewers that haven't baked hair textures.
- // This is paired with similar code in updateMeshTextures that sets hair mesh color.
- if (i == BAKED_HAIR)
- {
- for (U32 i = 0; i < mBakedTextureDatas[BAKED_HAIR].mMeshes.size(); i++)
- {
- mBakedTextureDatas[BAKED_HAIR].mMeshes[i]->setColor( 1.f, 1.f, 1.f, 1.f );
- }
- }
- }
- }
-
- dirtyMesh();
-}
-
-// static
-void LLVOAvatar::dumpArchetypeXML( void* )
-{
- LLAPRFile outfile;
- outfile.open(gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,"new archetype.xml"), LL_APR_WB );
- apr_file_t* file = outfile.getFileHandle() ;
- if (!file)
- {
- return;
- }
-
- apr_file_printf( file, "<?xml version=\"1.0\" encoding=\"US-ASCII\" standalone=\"yes\"?>\n" );
- apr_file_printf( file, "<linden_genepool version=\"1.0\">\n" );
- apr_file_printf( file, "\n\t<archetype name=\"???\">\n" );
-
- // only body parts, not clothing.
- for (S32 type = LLWearableType::WT_SHAPE; type <= LLWearableType::WT_EYES; type++)
- {
- const std::string& wearable_name = LLWearableType::getTypeName((LLWearableType::EType)type);
- apr_file_printf( file, "\n\t\t<!-- wearable: %s -->\n", wearable_name.c_str() );
-
- for (LLVisualParam* param = gAgentAvatarp->getFirstVisualParam(); param; param = gAgentAvatarp->getNextVisualParam())
- {
- LLViewerVisualParam* viewer_param = (LLViewerVisualParam*)param;
- if( (viewer_param->getWearableType() == type) &&
- (viewer_param->isTweakable() ) )
- {
- apr_file_printf(file, "\t\t<param id=\"%d\" name=\"%s\" value=\"%.3f\"/>\n",
- viewer_param->getID(), viewer_param->getName().c_str(), viewer_param->getWeight());
- }
- }
-
- for (U8 te = 0; te < TEX_NUM_INDICES; te++)
- {
- if (LLVOAvatarDictionary::getTEWearableType((ETextureIndex)te) == type)
- {
- // MULTIPLE_WEARABLES: extend to multiple wearables?
- LLViewerTexture* te_image = ((LLVOAvatar *)(gAgentAvatarp))->getImage((ETextureIndex)te, 0);
- if( te_image )
- {
- std::string uuid_str;
- te_image->getID().toString( uuid_str );
- apr_file_printf( file, "\t\t<texture te=\"%i\" uuid=\"%s\"/>\n", te, uuid_str.c_str());
- }
- }
- }
- }
- apr_file_printf( file, "\t</archetype>\n" );
- apr_file_printf( file, "\n</linden_genepool>\n" );
-}
-
-
-void LLVOAvatar::setVisibilityRank(U32 rank)
-{
- if (mDrawable.isNull() || mDrawable->isDead())
- {
- // do nothing
- return;
- }
- mVisibilityRank = rank;
-}
-
-// Assumes LLVOAvatar::sInstances has already been sorted.
-S32 LLVOAvatar::getUnbakedPixelAreaRank()
-{
- S32 rank = 1;
- for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
- iter != LLCharacter::sInstances.end(); ++iter)
- {
- LLVOAvatar* inst = (LLVOAvatar*) *iter;
- if (inst == this)
- {
- return rank;
- }
- else if (!inst->isDead() && !inst->isFullyBaked())
- {
- rank++;
- }
- }
-
- llassert(0);
- return 0;
-}
-
-struct CompareScreenAreaGreater
-{
- BOOL operator()(const LLCharacter* const& lhs, const LLCharacter* const& rhs)
- {
- return lhs->getPixelArea() > rhs->getPixelArea();
- }
-};
-
-// static
-void LLVOAvatar::cullAvatarsByPixelArea()
-{
- std::sort(LLCharacter::sInstances.begin(), LLCharacter::sInstances.end(), CompareScreenAreaGreater());
-
- // Update the avatars that have changed status
- U32 rank = 2; //1 is reserved for self.
- for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
- iter != LLCharacter::sInstances.end(); ++iter)
- {
- LLVOAvatar* inst = (LLVOAvatar*) *iter;
- BOOL culled;
- if (inst->isSelf() || inst->isFullyBaked())
- {
- culled = FALSE;
- }
- else
- {
- culled = TRUE;
- }
-
- if (inst->mCulled != culled)
- {
- inst->mCulled = culled;
- lldebugs << "avatar " << inst->getID() << (culled ? " start culled" : " start not culled" ) << llendl;
- inst->updateMeshTextures();
- }
-
- if (inst->isSelf())
- {
- inst->setVisibilityRank(1);
- }
- else if (inst->mDrawable.notNull() && inst->mDrawable->isVisible())
- {
- inst->setVisibilityRank(rank++);
- }
- }
-
- S32 grey_avatars = 0;
- if (LLVOAvatar::areAllNearbyInstancesBaked(grey_avatars))
- {
- LLVOAvatar::deleteCachedImages(false);
- }
- else
- {
- if (gFrameTimeSeconds != sUnbakedUpdateTime) // only update once per frame
- {
- sUnbakedUpdateTime = gFrameTimeSeconds;
- sUnbakedTime += gFrameIntervalSeconds;
- }
- if (grey_avatars > 0)
- {
- if (gFrameTimeSeconds != sGreyUpdateTime) // only update once per frame
- {
- sGreyUpdateTime = gFrameTimeSeconds;
- sGreyTime += gFrameIntervalSeconds;
- }
- }
- }
-}
-
-void LLVOAvatar::startAppearanceAnimation()
-{
- if(!mAppearanceAnimating)
- {
- mAppearanceAnimating = TRUE;
- mAppearanceMorphTimer.reset();
- mLastAppearanceBlendTime = 0.f;
- }
-}
-
-// virtual
-void LLVOAvatar::removeMissingBakedTextures()
-{
-}
-
-//-----------------------------------------------------------------------------
-// LLVOAvatarXmlInfo
-//-----------------------------------------------------------------------------
-
-LLVOAvatar::LLVOAvatarXmlInfo::LLVOAvatarXmlInfo()
- : mTexSkinColorInfo(0), mTexHairColorInfo(0), mTexEyeColorInfo(0)
-{
-}
-
-LLVOAvatar::LLVOAvatarXmlInfo::~LLVOAvatarXmlInfo()
-{
- std::for_each(mMeshInfoList.begin(), mMeshInfoList.end(), DeletePointer());
- std::for_each(mSkeletalDistortionInfoList.begin(), mSkeletalDistortionInfoList.end(), DeletePointer());
- std::for_each(mAttachmentInfoList.begin(), mAttachmentInfoList.end(), DeletePointer());
- deleteAndClear(mTexSkinColorInfo);
- deleteAndClear(mTexHairColorInfo);
- deleteAndClear(mTexEyeColorInfo);
- std::for_each(mLayerInfoList.begin(), mLayerInfoList.end(), DeletePointer());
- std::for_each(mDriverInfoList.begin(), mDriverInfoList.end(), DeletePointer());
- std::for_each(mMorphMaskInfoList.begin(), mMorphMaskInfoList.end(), DeletePointer());
-}
-
-//-----------------------------------------------------------------------------
-// LLVOAvatarBoneInfo::parseXml()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatarBoneInfo::parseXml(LLXmlTreeNode* node)
-{
- if (node->hasName("bone"))
- {
- mIsJoint = TRUE;
- static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
- if (!node->getFastAttributeString(name_string, mName))
- {
- llwarns << "Bone without name" << llendl;
- return FALSE;
- }
- }
- else if (node->hasName("collision_volume"))
- {
- mIsJoint = FALSE;
- static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
- if (!node->getFastAttributeString(name_string, mName))
- {
- mName = "Collision Volume";
- }
- }
- else
- {
- llwarns << "Invalid node " << node->getName() << llendl;
- return FALSE;
- }
-
- static LLStdStringHandle pos_string = LLXmlTree::addAttributeString("pos");
- if (!node->getFastAttributeVector3(pos_string, mPos))
- {
- llwarns << "Bone without position" << llendl;
- return FALSE;
- }
-
- static LLStdStringHandle rot_string = LLXmlTree::addAttributeString("rot");
- if (!node->getFastAttributeVector3(rot_string, mRot))
- {
- llwarns << "Bone without rotation" << llendl;
- return FALSE;
- }
-
- static LLStdStringHandle scale_string = LLXmlTree::addAttributeString("scale");
- if (!node->getFastAttributeVector3(scale_string, mScale))
- {
- llwarns << "Bone without scale" << llendl;
- return FALSE;
- }
-
- if (mIsJoint)
- {
- static LLStdStringHandle pivot_string = LLXmlTree::addAttributeString("pivot");
- if (!node->getFastAttributeVector3(pivot_string, mPivot))
- {
- llwarns << "Bone without pivot" << llendl;
- return FALSE;
- }
- }
-
- // parse children
- LLXmlTreeNode* child;
- for( child = node->getFirstChild(); child; child = node->getNextChild() )
- {
- LLVOAvatarBoneInfo *child_info = new LLVOAvatarBoneInfo;
- if (!child_info->parseXml(child))
- {
- delete child_info;
- return FALSE;
- }
- mChildList.push_back(child_info);
- }
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// LLVOAvatarSkeletonInfo::parseXml()
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatarSkeletonInfo::parseXml(LLXmlTreeNode* node)
-{
- static LLStdStringHandle num_bones_string = LLXmlTree::addAttributeString("num_bones");
- if (!node->getFastAttributeS32(num_bones_string, mNumBones))
- {
- llwarns << "Couldn't find number of bones." << llendl;
- return FALSE;
- }
-
- static LLStdStringHandle num_collision_volumes_string = LLXmlTree::addAttributeString("num_collision_volumes");
- node->getFastAttributeS32(num_collision_volumes_string, mNumCollisionVolumes);
-
- LLXmlTreeNode* child;
- for( child = node->getFirstChild(); child; child = node->getNextChild() )
- {
- LLVOAvatarBoneInfo *info = new LLVOAvatarBoneInfo;
- if (!info->parseXml(child))
- {
- delete info;
- llwarns << "Error parsing bone in skeleton file" << llendl;
- return FALSE;
- }
- mBoneInfoList.push_back(info);
- }
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// parseXmlSkeletonNode(): parses <skeleton> nodes from XML tree
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlSkeletonNode(LLXmlTreeNode* root)
-{
- LLXmlTreeNode* node = root->getChildByName( "skeleton" );
- if( !node )
- {
- llwarns << "avatar file: missing <skeleton>" << llendl;
- return FALSE;
- }
-
- LLXmlTreeNode* child;
-
- // SKELETON DISTORTIONS
- for (child = node->getChildByName( "param" );
- child;
- child = node->getNextNamedChild())
- {
- if (!child->getChildByName("param_skeleton"))
- {
- if (child->getChildByName("param_morph"))
- {
- llwarns << "Can't specify morph param in skeleton definition." << llendl;
- }
- else
- {
- llwarns << "Unknown param type." << llendl;
- }
- continue;
- }
-
- LLPolySkeletalDistortionInfo *info = new LLPolySkeletalDistortionInfo;
- if (!info->parseXml(child))
- {
- delete info;
- return FALSE;
- }
-
- mSkeletalDistortionInfoList.push_back(info);
- }
-
- // ATTACHMENT POINTS
- for (child = node->getChildByName( "attachment_point" );
- child;
- child = node->getNextNamedChild())
- {
- LLVOAvatarAttachmentInfo* info = new LLVOAvatarAttachmentInfo();
-
- static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
- if (!child->getFastAttributeString(name_string, info->mName))
- {
- llwarns << "No name supplied for attachment point." << llendl;
- delete info;
- continue;
- }
-
- static LLStdStringHandle joint_string = LLXmlTree::addAttributeString("joint");
- if (!child->getFastAttributeString(joint_string, info->mJointName))
- {
- llwarns << "No bone declared in attachment point " << info->mName << llendl;
- delete info;
- continue;
- }
-
- static LLStdStringHandle position_string = LLXmlTree::addAttributeString("position");
- if (child->getFastAttributeVector3(position_string, info->mPosition))
- {
- info->mHasPosition = TRUE;
- }
-
- static LLStdStringHandle rotation_string = LLXmlTree::addAttributeString("rotation");
- if (child->getFastAttributeVector3(rotation_string, info->mRotationEuler))
- {
- info->mHasRotation = TRUE;
- }
- static LLStdStringHandle group_string = LLXmlTree::addAttributeString("group");
- if (child->getFastAttributeS32(group_string, info->mGroup))
- {
- if (info->mGroup == -1)
- info->mGroup = -1111; // -1 = none parsed, < -1 = bad value
- }
-
- static LLStdStringHandle id_string = LLXmlTree::addAttributeString("id");
- if (!child->getFastAttributeS32(id_string, info->mAttachmentID))
- {
- llwarns << "No id supplied for attachment point " << info->mName << llendl;
- delete info;
- continue;
- }
-
- static LLStdStringHandle slot_string = LLXmlTree::addAttributeString("pie_slice");
- child->getFastAttributeS32(slot_string, info->mPieMenuSlice);
-
- static LLStdStringHandle visible_in_first_person_string = LLXmlTree::addAttributeString("visible_in_first_person");
- child->getFastAttributeBOOL(visible_in_first_person_string, info->mVisibleFirstPerson);
-
- static LLStdStringHandle hud_attachment_string = LLXmlTree::addAttributeString("hud");
- child->getFastAttributeBOOL(hud_attachment_string, info->mIsHUDAttachment);
-
- mAttachmentInfoList.push_back(info);
- }
-
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// parseXmlMeshNodes(): parses <mesh> nodes from XML tree
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlMeshNodes(LLXmlTreeNode* root)
-{
- for (LLXmlTreeNode* node = root->getChildByName( "mesh" );
- node;
- node = root->getNextNamedChild())
- {
- LLVOAvatarMeshInfo *info = new LLVOAvatarMeshInfo;
-
- // attribute: type
- static LLStdStringHandle type_string = LLXmlTree::addAttributeString("type");
- if( !node->getFastAttributeString( type_string, info->mType ) )
- {
- llwarns << "Avatar file: <mesh> is missing type attribute. Ignoring element. " << llendl;
- delete info;
- return FALSE; // Ignore this element
- }
-
- static LLStdStringHandle lod_string = LLXmlTree::addAttributeString("lod");
- if (!node->getFastAttributeS32( lod_string, info->mLOD ))
- {
- llwarns << "Avatar file: <mesh> is missing lod attribute. Ignoring element. " << llendl;
- delete info;
- return FALSE; // Ignore this element
- }
-
- static LLStdStringHandle file_name_string = LLXmlTree::addAttributeString("file_name");
- if( !node->getFastAttributeString( file_name_string, info->mMeshFileName ) )
- {
- llwarns << "Avatar file: <mesh> is missing file_name attribute. Ignoring: " << info->mType << llendl;
- delete info;
- return FALSE; // Ignore this element
- }
-
- static LLStdStringHandle reference_string = LLXmlTree::addAttributeString("reference");
- node->getFastAttributeString( reference_string, info->mReferenceMeshName );
-
- // attribute: min_pixel_area
- static LLStdStringHandle min_pixel_area_string = LLXmlTree::addAttributeString("min_pixel_area");
- static LLStdStringHandle min_pixel_width_string = LLXmlTree::addAttributeString("min_pixel_width");
- if (!node->getFastAttributeF32( min_pixel_area_string, info->mMinPixelArea ))
- {
- F32 min_pixel_area = 0.1f;
- if (node->getFastAttributeF32( min_pixel_width_string, min_pixel_area ))
- {
- // this is square root of pixel area (sensible to use linear space in defining lods)
- min_pixel_area = min_pixel_area * min_pixel_area;
- }
- info->mMinPixelArea = min_pixel_area;
- }
-
- // Parse visual params for this node only if we haven't already
- for (LLXmlTreeNode* child = node->getChildByName( "param" );
- child;
- child = node->getNextNamedChild())
- {
- if (!child->getChildByName("param_morph"))
- {
- if (child->getChildByName("param_skeleton"))
- {
- llwarns << "Can't specify skeleton param in a mesh definition." << llendl;
- }
- else
- {
- llwarns << "Unknown param type." << llendl;
- }
- continue;
- }
-
- LLPolyMorphTargetInfo *morphinfo = new LLPolyMorphTargetInfo();
- if (!morphinfo->parseXml(child))
- {
- delete morphinfo;
- delete info;
- return -1;
- }
- BOOL shared = FALSE;
- static LLStdStringHandle shared_string = LLXmlTree::addAttributeString("shared");
- child->getFastAttributeBOOL(shared_string, shared);
-
- info->mPolyMorphTargetInfoList.push_back(LLVOAvatarMeshInfo::morph_info_pair_t(morphinfo, shared));
- }
-
- mMeshInfoList.push_back(info);
- }
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// parseXmlColorNodes(): parses <global_color> nodes from XML tree
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlColorNodes(LLXmlTreeNode* root)
-{
- for (LLXmlTreeNode* color_node = root->getChildByName( "global_color" );
- color_node;
- color_node = root->getNextNamedChild())
- {
- std::string global_color_name;
- static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
- if (color_node->getFastAttributeString( name_string, global_color_name ) )
- {
- if( global_color_name == "skin_color" )
- {
- if (mTexSkinColorInfo)
- {
- llwarns << "avatar file: multiple instances of skin_color" << llendl;
- return FALSE;
- }
- mTexSkinColorInfo = new LLTexGlobalColorInfo;
- if( !mTexSkinColorInfo->parseXml( color_node ) )
- {
- deleteAndClear(mTexSkinColorInfo);
- llwarns << "avatar file: mTexSkinColor->parseXml() failed" << llendl;
- return FALSE;
- }
- }
- else if( global_color_name == "hair_color" )
- {
- if (mTexHairColorInfo)
- {
- llwarns << "avatar file: multiple instances of hair_color" << llendl;
- return FALSE;
- }
- mTexHairColorInfo = new LLTexGlobalColorInfo;
- if( !mTexHairColorInfo->parseXml( color_node ) )
- {
- deleteAndClear(mTexHairColorInfo);
- llwarns << "avatar file: mTexHairColor->parseXml() failed" << llendl;
- return FALSE;
- }
- }
- else if( global_color_name == "eye_color" )
- {
- if (mTexEyeColorInfo)
- {
- llwarns << "avatar file: multiple instances of eye_color" << llendl;
- return FALSE;
- }
- mTexEyeColorInfo = new LLTexGlobalColorInfo;
- if( !mTexEyeColorInfo->parseXml( color_node ) )
- {
- llwarns << "avatar file: mTexEyeColor->parseXml() failed" << llendl;
- return FALSE;
- }
- }
- }
- }
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// parseXmlLayerNodes(): parses <layer_set> nodes from XML tree
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlLayerNodes(LLXmlTreeNode* root)
-{
- for (LLXmlTreeNode* layer_node = root->getChildByName( "layer_set" );
- layer_node;
- layer_node = root->getNextNamedChild())
- {
- LLTexLayerSetInfo* layer_info = new LLTexLayerSetInfo();
- if( layer_info->parseXml( layer_node ) )
- {
- mLayerInfoList.push_back(layer_info);
- }
- else
- {
- delete layer_info;
- llwarns << "avatar file: layer_set->parseXml() failed" << llendl;
- return FALSE;
- }
- }
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// parseXmlDriverNodes(): parses <driver_parameters> nodes from XML tree
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlDriverNodes(LLXmlTreeNode* root)
-{
- LLXmlTreeNode* driver = root->getChildByName( "driver_parameters" );
- if( driver )
- {
- for (LLXmlTreeNode* grand_child = driver->getChildByName( "param" );
- grand_child;
- grand_child = driver->getNextNamedChild())
- {
- if( grand_child->getChildByName( "param_driver" ) )
- {
- LLDriverParamInfo* driver_info = new LLDriverParamInfo();
- if( driver_info->parseXml( grand_child ) )
- {
- mDriverInfoList.push_back(driver_info);
- }
- else
- {
- delete driver_info;
- llwarns << "avatar file: driver_param->parseXml() failed" << llendl;
- return FALSE;
- }
- }
- }
- }
- return TRUE;
-}
-
-//-----------------------------------------------------------------------------
-// parseXmlDriverNodes(): parses <driver_parameters> nodes from XML tree
-//-----------------------------------------------------------------------------
-BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlMorphNodes(LLXmlTreeNode* root)
-{
- LLXmlTreeNode* masks = root->getChildByName( "morph_masks" );
- if( !masks )
- {
- return FALSE;
- }
-
- for (LLXmlTreeNode* grand_child = masks->getChildByName( "mask" );
- grand_child;
- grand_child = masks->getNextNamedChild())
- {
- LLVOAvatarMorphInfo* info = new LLVOAvatarMorphInfo();
-
- static LLStdStringHandle name_string = LLXmlTree::addAttributeString("morph_name");
- if (!grand_child->getFastAttributeString(name_string, info->mName))
- {
- llwarns << "No name supplied for morph mask." << llendl;
- delete info;
- continue;
- }
-
- static LLStdStringHandle region_string = LLXmlTree::addAttributeString("body_region");
- if (!grand_child->getFastAttributeString(region_string, info->mRegion))
- {
- llwarns << "No region supplied for morph mask." << llendl;
- delete info;
- continue;
- }
-
- static LLStdStringHandle layer_string = LLXmlTree::addAttributeString("layer");
- if (!grand_child->getFastAttributeString(layer_string, info->mLayer))
- {
- llwarns << "No layer supplied for morph mask." << llendl;
- delete info;
- continue;
- }
-
- // optional parameter. don't throw a warning if not present.
- static LLStdStringHandle invert_string = LLXmlTree::addAttributeString("invert");
- grand_child->getFastAttributeBOOL(invert_string, info->mInvert);
-
- mMorphMaskInfoList.push_back(info);
- }
-
- return TRUE;
-}
-
-//virtual
-void LLVOAvatar::updateRegion(LLViewerRegion *regionp)
-{
- LLViewerObject::updateRegion(regionp);
-}
-
-std::string LLVOAvatar::getFullname() const
-{
- std::string name;
-
- LLNameValue* first = getNVPair("FirstName");
- LLNameValue* last = getNVPair("LastName");
- if (first && last)
- {
- name = LLCacheName::buildFullName( first->getString(), last->getString() );
- }
-
- return name;
-}
-
-LLHost LLVOAvatar::getObjectHost() const
-{
- LLViewerRegion* region = getRegion();
- if (region && !isDead())
- {
- return region->getHost();
- }
- else
- {
- return LLHost::invalid;
- }
-}
-
-//static
-void LLVOAvatar::updateFreezeCounter(S32 counter)
-{
- if(counter)
- {
- sFreezeCounter = counter;
- }
- else if(sFreezeCounter > 0)
- {
- sFreezeCounter--;
- }
- else
- {
- sFreezeCounter = 0;
- }
-}
-
-BOOL LLVOAvatar::updateLOD()
-{
- if (isImpostor())
- {
- return TRUE;
- }
-
- BOOL res = updateJointLODs();
-
- LLFace* facep = mDrawable->getFace(0);
- if (facep->mVertexBuffer.isNull())
- {
- dirtyMesh(2);
- }
-
- if (mDirtyMesh >= 2 || mDrawable->isState(LLDrawable::REBUILD_GEOMETRY))
- { //LOD changed or new mesh created, allocate new vertex buffer if needed
- updateMeshData();
- mDirtyMesh = 0;
- mNeedsSkin = TRUE;
- mDrawable->clearState(LLDrawable::REBUILD_GEOMETRY);
- }
-
- updateVisibility();
-
- return res;
-}
-
-U32 LLVOAvatar::getPartitionType() const
-{
- // Avatars merely exist as drawables in the bridge partition
- return LLViewerRegion::PARTITION_BRIDGE;
-}
-
-//static
-void LLVOAvatar::updateImpostors()
-{
- for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
- iter != LLCharacter::sInstances.end(); ++iter)
- {
- LLVOAvatar* avatar = (LLVOAvatar*) *iter;
- if (!avatar->isDead() && avatar->needsImpostorUpdate() && avatar->isVisible() && avatar->isImpostor())
- {
- gPipeline.generateImpostor(avatar);
- }
- }
-}
-
-BOOL LLVOAvatar::isImpostor() const
-{
- return (sUseImpostors && mUpdatePeriod >= IMPOSTOR_PERIOD) ? TRUE : FALSE;
-}
-
-
-BOOL LLVOAvatar::needsImpostorUpdate() const
-{
- return mNeedsImpostorUpdate;
-}
-
-const LLVector3& LLVOAvatar::getImpostorOffset() const
-{
- return mImpostorOffset;
-}
-
-const LLVector2& LLVOAvatar::getImpostorDim() const
-{
- return mImpostorDim;
-}
-
-void LLVOAvatar::setImpostorDim(const LLVector2& dim)
-{
- mImpostorDim = dim;
-}
-
-void LLVOAvatar::cacheImpostorValues()
-{
- getImpostorValues(mImpostorExtents, mImpostorAngle, mImpostorDistance);
-}
-
-void LLVOAvatar::getImpostorValues(LLVector3* extents, LLVector3& angle, F32& distance) const
-{
- const LLVector3* ext = mDrawable->getSpatialExtents();
- extents[0] = ext[0];
- extents[1] = ext[1];
-
- LLVector3 at = LLViewerCamera::getInstance()->getOrigin()-(getRenderPosition()+mImpostorOffset);
- distance = at.normalize();
- F32 da = 1.f - (at*LLViewerCamera::getInstance()->getAtAxis());
- angle.mV[0] = LLViewerCamera::getInstance()->getYaw()*da;
- angle.mV[1] = LLViewerCamera::getInstance()->getPitch()*da;
- angle.mV[2] = da;
-}
-
-void LLVOAvatar::idleUpdateRenderCost()
-{
- static const U32 ARC_BODY_PART_COST = 20;
- static const U32 ARC_LIMIT = 2048;
-
- static std::set<LLUUID> all_textures;
-
- if (!gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_SHAME))
- {
- return;
- }
-
- U32 cost = 0;
- std::set<LLUUID> textures;
-
- for (U8 baked_index = 0; baked_index < BAKED_NUM_INDICES; baked_index++)
- {
- const LLVOAvatarDictionary::BakedEntry *baked_dict = LLVOAvatarDictionary::getInstance()->getBakedTexture((EBakedTextureIndex)baked_index);
- ETextureIndex tex_index = baked_dict->mTextureIndex;
- if ((tex_index != TEX_SKIRT_BAKED) || (isWearingWearableType(LLWearableType::WT_SKIRT)))
- {
- if (isTextureVisible(tex_index))
- {
- cost +=ARC_BODY_PART_COST;
- }
- }
- }
-
- for (attachment_map_t::const_iterator iter = mAttachmentPoints.begin();
- iter != mAttachmentPoints.end();
- ++iter)
- {
- LLViewerJointAttachment* attachment = iter->second;
- for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
- attachment_iter != attachment->mAttachedObjects.end();
- ++attachment_iter)
- {
- const LLViewerObject* attached_object = (*attachment_iter);
- if (attached_object && !attached_object->isHUDAttachment())
- {
- const LLDrawable* drawable = attached_object->mDrawable;
- if (drawable)
- {
- const LLVOVolume* volume = drawable->getVOVolume();
- if (volume)
- {
- cost += volume->getRenderCost(textures);
- }
- }
- }
- }
- }
- // Diagnostic output to identify all avatar-related textures.
- // Does not affect rendering cost calculation.
- // Could be wrapped in a debug option if output becomes problematic.
- if (isSelf())
- {
- // print any attachment textures we didn't already know about.
- for (std::set<LLUUID>::iterator it = textures.begin(); it != textures.end(); ++it)
- {
- LLUUID image_id = *it;
- if( image_id.isNull() || image_id == IMG_DEFAULT || image_id == IMG_DEFAULT_AVATAR)
- continue;
- if (all_textures.find(image_id) == all_textures.end())
- {
- // attachment texture not previously seen.
- llinfos << "attachment_texture: " << image_id.asString() << llendl;
- all_textures.insert(image_id);
- }
- }
-
- // print any avatar textures we didn't already know about
- for (LLVOAvatarDictionary::Textures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
- iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
- ++iter)
- {
- const LLVOAvatarDictionary::TextureEntry *texture_dict = iter->second;
- // TODO: MULTI-WEARABLE: handle multiple textures for self
- const LLViewerTexture* te_image = getImage(iter->first,0);
- if (!te_image)
- continue;
- LLUUID image_id = te_image->getID();
- if( image_id.isNull() || image_id == IMG_DEFAULT || image_id == IMG_DEFAULT_AVATAR)
- continue;
- if (all_textures.find(image_id) == all_textures.end())
- {
- llinfos << "local_texture: " << texture_dict->mName << ": " << image_id << llendl;
- all_textures.insert(image_id);
- }
- }
- }
- cost += textures.size() * LLVOVolume::ARC_TEXTURE_COST;
-
- setDebugText(llformat("%d", cost));
- F32 green = 1.f-llclamp(((F32) cost-(F32)ARC_LIMIT)/(F32)ARC_LIMIT, 0.f, 1.f);
- F32 red = llmin((F32) cost/(F32)ARC_LIMIT, 1.f);
- mText->setColor(LLColor4(red,green,0,1));
-}
-
-// static
-BOOL LLVOAvatar::isIndexLocalTexture(ETextureIndex index)
-{
- if (index < 0 || index >= TEX_NUM_INDICES) return false;
- return LLVOAvatarDictionary::getInstance()->getTexture(index)->mIsLocalTexture;
-}
-
-// static
-BOOL LLVOAvatar::isIndexBakedTexture(ETextureIndex index)
-{
- if (index < 0 || index >= TEX_NUM_INDICES) return false;
- return LLVOAvatarDictionary::getInstance()->getTexture(index)->mIsBakedTexture;
-}
-
-const std::string LLVOAvatar::getBakedStatusForPrintout() const
-{
- std::string line;
-
- for (LLVOAvatarDictionary::Textures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
- iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
- ++iter)
- {
- const ETextureIndex index = iter->first;
- const LLVOAvatarDictionary::TextureEntry *texture_dict = iter->second;
- if (texture_dict->mIsBakedTexture)
- {
- line += texture_dict->mName;
- if (isTextureDefined(index))
- {
- line += "_baked";
- }
- line += " ";
- }
- }
- return line;
-}
-
-
-
-//virtual
-S32 LLVOAvatar::getTexImageSize() const
-{
- return TEX_IMAGE_SIZE_OTHER;
-}
-
-//-----------------------------------------------------------------------------
-// Utility functions
-//-----------------------------------------------------------------------------
-
-F32 calc_bouncy_animation(F32 x)
-{
- return -(cosf(x * F_PI * 2.5f - F_PI_BY_TWO))*(0.4f + x * -0.1f) + x * 1.3f;
-}
-
-//virtual
-BOOL LLVOAvatar::isTextureDefined(LLVOAvatarDefines::ETextureIndex te, U32 index ) const
-{
- if (isIndexLocalTexture(te))
- {
- return FALSE;
- }
-
- return (getImage(te, index)->getID() != IMG_DEFAULT_AVATAR &&
- getImage(te, index)->getID() != IMG_DEFAULT);
-}
-
-//virtual
-BOOL LLVOAvatar::isTextureVisible(LLVOAvatarDefines::ETextureIndex type, U32 index) const
-{
- if (isIndexLocalTexture(type))
- {
- return isTextureDefined(type, index);
- }
- else
- {
- // baked textures can use TE images directly
- return ((isTextureDefined(type) || isSelf())
- && (getTEImage(type)->getID() != IMG_INVISIBLE
- || LLDrawPoolAlpha::sShowDebugAlpha));
- }
-}
-
-//virtual
-BOOL LLVOAvatar::isTextureVisible(LLVOAvatarDefines::ETextureIndex type, LLWearable *wearable) const
-{
- // non-self avatars don't have wearables
- return FALSE;
-}
-
+/**
+ * @File llvoavatar.cpp
+ * @brief Implementation of LLVOAvatar class which is a derivation of LLViewerObject
+ *
+ * $LicenseInfo:firstyear=2001&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#if LL_MSVC
+// disable warning about boost::lexical_cast returning uninitialized data
+// when it fails to parse the string
+#pragma warning (disable:4701)
+#endif
+
+#include "llviewerprecompiledheaders.h"
+
+#include "llvoavatar.h"
+
+#include <stdio.h>
+#include <ctype.h>
+
+#include "llaudioengine.h"
+#include "llcachename.h"
+#include "noise.h"
+#include "sound_ids.h"
+
+#include "llagent.h" // Get state values from here
+#include "llagentcamera.h"
+#include "llagentwearables.h"
+#include "llanimationstates.h"
+#include "llavatarnamecache.h"
+#include "llavatarpropertiesprocessor.h"
+#include "llviewercontrol.h"
+#include "llcallingcard.h" // IDEVO for LLAvatarTracker
+#include "lldrawpoolavatar.h"
+#include "lldriverparam.h"
+#include "lleditingmotion.h"
+#include "llemote.h"
+//#include "llfirstuse.h"
+#include "llheadrotmotion.h"
+#include "llhudeffecttrail.h"
+#include "llhudmanager.h"
+#include "llhudnametag.h"
+#include "llhudtext.h" // for mText/mDebugText
+#include "llkeyframefallmotion.h"
+#include "llkeyframestandmotion.h"
+#include "llkeyframewalkmotion.h"
+#include "llmanipscale.h" // for get_default_max_prim_scale()
+#include "llmeshrepository.h"
+#include "llmutelist.h"
+#include "llmoveview.h"
+#include "llnotificationsutil.h"
+#include "llquantize.h"
+#include "llrand.h"
+#include "llregionhandle.h"
+#include "llresmgr.h"
+#include "llselectmgr.h"
+#include "llsprite.h"
+#include "lltargetingmotion.h"
+#include "lltexlayer.h"
+#include "lltoolmorph.h"
+#include "llviewercamera.h"
+#include "llviewertexturelist.h"
+#include "llviewermenu.h"
+#include "llviewerobjectlist.h"
+#include "llviewerparcelmgr.h"
+#include "llviewershadermgr.h"
+#include "llviewerstats.h"
+#include "llvoavatarself.h"
+#include "llvovolume.h"
+#include "llworld.h"
+#include "pipeline.h"
+#include "llviewershadermgr.h"
+#include "llsky.h"
+#include "llanimstatelabels.h"
+#include "lltrans.h"
+#include "llappearancemgr.h"
+
+#include "llgesturemgr.h" //needed to trigger the voice gesticulations
+#include "llvoiceclient.h"
+#include "llvoicevisualizer.h" // Ventrella
+
+#include "lldebugmessagebox.h"
+extern F32 SPEED_ADJUST_MAX;
+extern F32 SPEED_ADJUST_MAX_SEC;
+extern F32 ANIM_SPEED_MAX;
+extern F32 ANIM_SPEED_MIN;
+
+#if LL_MSVC
+// disable boost::lexical_cast warning
+#pragma warning (disable:4702)
+#endif
+
+#include <boost/lexical_cast.hpp>
+
+using namespace LLVOAvatarDefines;
+
+//-----------------------------------------------------------------------------
+// Global constants
+//-----------------------------------------------------------------------------
+const LLUUID ANIM_AGENT_BODY_NOISE = LLUUID("9aa8b0a6-0c6f-9518-c7c3-4f41f2c001ad"); //"body_noise"
+const LLUUID ANIM_AGENT_BREATHE_ROT = LLUUID("4c5a103e-b830-2f1c-16bc-224aa0ad5bc8"); //"breathe_rot"
+const LLUUID ANIM_AGENT_EDITING = LLUUID("2a8eba1d-a7f8-5596-d44a-b4977bf8c8bb"); //"editing"
+const LLUUID ANIM_AGENT_EYE = LLUUID("5c780ea8-1cd1-c463-a128-48c023f6fbea"); //"eye"
+const LLUUID ANIM_AGENT_FLY_ADJUST = LLUUID("db95561f-f1b0-9f9a-7224-b12f71af126e"); //"fly_adjust"
+const LLUUID ANIM_AGENT_HAND_MOTION = LLUUID("ce986325-0ba7-6e6e-cc24-b17c4b795578"); //"hand_motion"
+const LLUUID ANIM_AGENT_HEAD_ROT = LLUUID("e6e8d1dd-e643-fff7-b238-c6b4b056a68d"); //"head_rot"
+const LLUUID ANIM_AGENT_PELVIS_FIX = LLUUID("0c5dd2a2-514d-8893-d44d-05beffad208b"); //"pelvis_fix"
+const LLUUID ANIM_AGENT_TARGET = LLUUID("0e4896cb-fba4-926c-f355-8720189d5b55"); //"target"
+const LLUUID ANIM_AGENT_WALK_ADJUST = LLUUID("829bc85b-02fc-ec41-be2e-74cc6dd7215d"); //"walk_adjust"
+
+
+//-----------------------------------------------------------------------------
+// Constants
+//-----------------------------------------------------------------------------
+const std::string AVATAR_DEFAULT_CHAR = "avatar";
+
+const S32 MIN_PIXEL_AREA_FOR_COMPOSITE = 1024;
+const F32 SHADOW_OFFSET_AMT = 0.03f;
+
+const F32 DELTA_TIME_MIN = 0.01f; // we clamp measured deltaTime to this
+const F32 DELTA_TIME_MAX = 0.2f; // range to insure stability of computations.
+
+const F32 PELVIS_LAG_FLYING = 0.22f;// pelvis follow half life while flying
+const F32 PELVIS_LAG_WALKING = 0.4f; // ...while walking
+const F32 PELVIS_LAG_MOUSELOOK = 0.15f;
+const F32 MOUSELOOK_PELVIS_FOLLOW_FACTOR = 0.5f;
+const F32 PELVIS_LAG_WHEN_FOLLOW_CAM_IS_ON = 0.0001f; // not zero! - something gets divided by this!
+
+const F32 PELVIS_ROT_THRESHOLD_SLOW = 60.0f; // amount of deviation allowed between
+const F32 PELVIS_ROT_THRESHOLD_FAST = 2.0f; // the pelvis and the view direction
+ // when moving fast & slow
+const F32 TORSO_NOISE_AMOUNT = 1.0f; // Amount of deviation from up-axis, in degrees
+const F32 TORSO_NOISE_SPEED = 0.2f; // Time scale factor on torso noise.
+
+const F32 BREATHE_ROT_MOTION_STRENGTH = 0.05f;
+const F32 BREATHE_SCALE_MOTION_STRENGTH = 0.005f;
+
+const F32 MIN_SHADOW_HEIGHT = 0.f;
+const F32 MAX_SHADOW_HEIGHT = 0.3f;
+
+const S32 MIN_REQUIRED_PIXEL_AREA_BODY_NOISE = 10000;
+const S32 MIN_REQUIRED_PIXEL_AREA_BREATHE = 10000;
+const S32 MIN_REQUIRED_PIXEL_AREA_PELVIS_FIX = 40;
+
+const S32 TEX_IMAGE_SIZE_SELF = 512;
+const S32 TEX_IMAGE_AREA_SELF = TEX_IMAGE_SIZE_SELF * TEX_IMAGE_SIZE_SELF;
+const S32 TEX_IMAGE_SIZE_OTHER = 512 / 4; // The size of local textures for other (!isSelf()) avatars
+
+const F32 HEAD_MOVEMENT_AVG_TIME = 0.9f;
+
+const S32 MORPH_MASK_REQUESTED_DISCARD = 0;
+
+// Discard level at which to switch to baked textures
+// Should probably be 4 or 3, but didn't want to change it while change other logic - SJB
+const S32 SWITCH_TO_BAKED_DISCARD = 5;
+
+const F32 FOOT_COLLIDE_FUDGE = 0.04f;
+
+const F32 HOVER_EFFECT_MAX_SPEED = 3.f;
+const F32 HOVER_EFFECT_STRENGTH = 0.f;
+const F32 UNDERWATER_EFFECT_STRENGTH = 0.1f;
+const F32 UNDERWATER_FREQUENCY_DAMP = 0.33f;
+const F32 APPEARANCE_MORPH_TIME = 0.65f;
+const F32 TIME_BEFORE_MESH_CLEANUP = 5.f; // seconds
+const S32 AVATAR_RELEASE_THRESHOLD = 10; // number of avatar instances before releasing memory
+const F32 FOOT_GROUND_COLLISION_TOLERANCE = 0.25f;
+const F32 AVATAR_LOD_TWEAK_RANGE = 0.7f;
+const S32 MAX_BUBBLE_CHAT_LENGTH = DB_CHAT_MSG_STR_LEN;
+const S32 MAX_BUBBLE_CHAT_UTTERANCES = 12;
+const F32 CHAT_FADE_TIME = 8.0;
+const F32 BUBBLE_CHAT_TIME = CHAT_FADE_TIME * 3.f;
+
+const LLColor4 DUMMY_COLOR = LLColor4(0.5,0.5,0.5,1.0);
+
+enum ERenderName
+{
+ RENDER_NAME_NEVER,
+ RENDER_NAME_ALWAYS,
+ RENDER_NAME_FADE
+};
+
+//-----------------------------------------------------------------------------
+// Callback data
+//-----------------------------------------------------------------------------
+
+struct LLTextureMaskData
+{
+ LLTextureMaskData( const LLUUID& id ) :
+ mAvatarID(id),
+ mLastDiscardLevel(S32_MAX)
+ {}
+ LLUUID mAvatarID;
+ S32 mLastDiscardLevel;
+};
+
+/*********************************************************************************
+ ** **
+ ** Begin private LLVOAvatar Support classes
+ **
+ **/
+
+//------------------------------------------------------------------------
+// LLVOBoneInfo
+// Trans/Scale/Rot etc. info about each avatar bone. Used by LLVOAvatarSkeleton.
+//------------------------------------------------------------------------
+class LLVOAvatarBoneInfo
+{
+ friend class LLVOAvatar;
+ friend class LLVOAvatarSkeletonInfo;
+public:
+ LLVOAvatarBoneInfo() : mIsJoint(FALSE) {}
+ ~LLVOAvatarBoneInfo()
+ {
+ std::for_each(mChildList.begin(), mChildList.end(), DeletePointer());
+ }
+ BOOL parseXml(LLXmlTreeNode* node);
+
+private:
+ std::string mName;
+ BOOL mIsJoint;
+ LLVector3 mPos;
+ LLVector3 mRot;
+ LLVector3 mScale;
+ LLVector3 mPivot;
+ typedef std::vector<LLVOAvatarBoneInfo*> child_list_t;
+ child_list_t mChildList;
+};
+
+//------------------------------------------------------------------------
+// LLVOAvatarSkeletonInfo
+// Overall avatar skeleton
+//------------------------------------------------------------------------
+class LLVOAvatarSkeletonInfo
+{
+ friend class LLVOAvatar;
+public:
+ LLVOAvatarSkeletonInfo() :
+ mNumBones(0), mNumCollisionVolumes(0) {}
+ ~LLVOAvatarSkeletonInfo()
+ {
+ std::for_each(mBoneInfoList.begin(), mBoneInfoList.end(), DeletePointer());
+ }
+ BOOL parseXml(LLXmlTreeNode* node);
+ S32 getNumBones() const { return mNumBones; }
+ S32 getNumCollisionVolumes() const { return mNumCollisionVolumes; }
+
+private:
+ S32 mNumBones;
+ S32 mNumCollisionVolumes;
+ typedef std::vector<LLVOAvatarBoneInfo*> bone_info_list_t;
+ bone_info_list_t mBoneInfoList;
+};
+
+//-----------------------------------------------------------------------------
+// class LLBodyNoiseMotion
+//-----------------------------------------------------------------------------
+class LLBodyNoiseMotion :
+ public LLMotion
+{
+public:
+ // Constructor
+ LLBodyNoiseMotion(const LLUUID &id)
+ : LLMotion(id)
+ {
+ mName = "body_noise";
+ mTorsoState = new LLJointState;
+ }
+
+ // Destructor
+ virtual ~LLBodyNoiseMotion() { }
+
+public:
+ //-------------------------------------------------------------------------
+ // functions to support MotionController and MotionRegistry
+ //-------------------------------------------------------------------------
+ // static constructor
+ // all subclasses must implement such a function and register it
+ static LLMotion *create(const LLUUID &id) { return new LLBodyNoiseMotion(id); }
+
+public:
+ //-------------------------------------------------------------------------
+ // animation callbacks to be implemented by subclasses
+ //-------------------------------------------------------------------------
+
+ // motions must specify whether or not they loop
+ virtual BOOL getLoop() { return TRUE; }
+
+ // motions must report their total duration
+ virtual F32 getDuration() { return 0.0; }
+
+ // motions must report their "ease in" duration
+ virtual F32 getEaseInDuration() { return 0.0; }
+
+ // motions must report their "ease out" duration.
+ virtual F32 getEaseOutDuration() { return 0.0; }
+
+ // motions must report their priority
+ virtual LLJoint::JointPriority getPriority() { return LLJoint::HIGH_PRIORITY; }
+
+ virtual LLMotionBlendType getBlendType() { return ADDITIVE_BLEND; }
+
+ // called to determine when a motion should be activated/deactivated based on avatar pixel coverage
+ virtual F32 getMinPixelArea() { return MIN_REQUIRED_PIXEL_AREA_BODY_NOISE; }
+
+ // run-time (post constructor) initialization,
+ // called after parameters have been set
+ // must return true to indicate success and be available for activation
+ virtual LLMotionInitStatus onInitialize(LLCharacter *character)
+ {
+ if( !mTorsoState->setJoint( character->getJoint("mTorso") ))
+ {
+ return STATUS_FAILURE;
+ }
+
+ mTorsoState->setUsage(LLJointState::ROT);
+
+ addJointState( mTorsoState );
+ return STATUS_SUCCESS;
+ }
+
+ // called when a motion is activated
+ // must return TRUE to indicate success, or else
+ // it will be deactivated
+ virtual BOOL onActivate() { return TRUE; }
+
+ // called per time step
+ // must return TRUE while it is active, and
+ // must return FALSE when the motion is completed.
+ virtual BOOL onUpdate(F32 time, U8* joint_mask)
+ {
+ F32 nx[2];
+ nx[0]=time*TORSO_NOISE_SPEED;
+ nx[1]=0.0f;
+ F32 ny[2];
+ ny[0]=0.0f;
+ ny[1]=time*TORSO_NOISE_SPEED;
+ F32 noiseX = noise2(nx);
+ F32 noiseY = noise2(ny);
+
+ F32 rx = TORSO_NOISE_AMOUNT * DEG_TO_RAD * noiseX / 0.42f;
+ F32 ry = TORSO_NOISE_AMOUNT * DEG_TO_RAD * noiseY / 0.42f;
+ LLQuaternion tQn;
+ tQn.setQuat( rx, ry, 0.0f );
+ mTorsoState->setRotation( tQn );
+
+ return TRUE;
+ }
+
+ // called when a motion is deactivated
+ virtual void onDeactivate() {}
+
+private:
+ //-------------------------------------------------------------------------
+ // joint states to be animated
+ //-------------------------------------------------------------------------
+ LLPointer<LLJointState> mTorsoState;
+};
+
+//-----------------------------------------------------------------------------
+// class LLBreatheMotionRot
+//-----------------------------------------------------------------------------
+class LLBreatheMotionRot :
+ public LLMotion
+{
+public:
+ // Constructor
+ LLBreatheMotionRot(const LLUUID &id) :
+ LLMotion(id),
+ mBreatheRate(1.f),
+ mCharacter(NULL)
+ {
+ mName = "breathe_rot";
+ mChestState = new LLJointState;
+ }
+
+ // Destructor
+ virtual ~LLBreatheMotionRot() {}
+
+public:
+ //-------------------------------------------------------------------------
+ // functions to support MotionController and MotionRegistry
+ //-------------------------------------------------------------------------
+ // static constructor
+ // all subclasses must implement such a function and register it
+ static LLMotion *create(const LLUUID &id) { return new LLBreatheMotionRot(id); }
+
+public:
+ //-------------------------------------------------------------------------
+ // animation callbacks to be implemented by subclasses
+ //-------------------------------------------------------------------------
+
+ // motions must specify whether or not they loop
+ virtual BOOL getLoop() { return TRUE; }
+
+ // motions must report their total duration
+ virtual F32 getDuration() { return 0.0; }
+
+ // motions must report their "ease in" duration
+ virtual F32 getEaseInDuration() { return 0.0; }
+
+ // motions must report their "ease out" duration.
+ virtual F32 getEaseOutDuration() { return 0.0; }
+
+ // motions must report their priority
+ virtual LLJoint::JointPriority getPriority() { return LLJoint::MEDIUM_PRIORITY; }
+
+ virtual LLMotionBlendType getBlendType() { return NORMAL_BLEND; }
+
+ // called to determine when a motion should be activated/deactivated based on avatar pixel coverage
+ virtual F32 getMinPixelArea() { return MIN_REQUIRED_PIXEL_AREA_BREATHE; }
+
+ // run-time (post constructor) initialization,
+ // called after parameters have been set
+ // must return true to indicate success and be available for activation
+ virtual LLMotionInitStatus onInitialize(LLCharacter *character)
+ {
+ mCharacter = character;
+ BOOL success = true;
+
+ if ( !mChestState->setJoint( character->getJoint( "mChest" ) ) ) { success = false; }
+
+ if ( success )
+ {
+ mChestState->setUsage(LLJointState::ROT);
+ addJointState( mChestState );
+ }
+
+ if ( success )
+ {
+ return STATUS_SUCCESS;
+ }
+ else
+ {
+ return STATUS_FAILURE;
+ }
+ }
+
+ // called when a motion is activated
+ // must return TRUE to indicate success, or else
+ // it will be deactivated
+ virtual BOOL onActivate() { return TRUE; }
+
+ // called per time step
+ // must return TRUE while it is active, and
+ // must return FALSE when the motion is completed.
+ virtual BOOL onUpdate(F32 time, U8* joint_mask)
+ {
+ mBreatheRate = 1.f;
+
+ F32 breathe_amt = (sinf(mBreatheRate * time) * BREATHE_ROT_MOTION_STRENGTH);
+
+ mChestState->setRotation(LLQuaternion(breathe_amt, LLVector3(0.f, 1.f, 0.f)));
+
+ return TRUE;
+ }
+
+ // called when a motion is deactivated
+ virtual void onDeactivate() {}
+
+private:
+ //-------------------------------------------------------------------------
+ // joint states to be animated
+ //-------------------------------------------------------------------------
+ LLPointer<LLJointState> mChestState;
+ F32 mBreatheRate;
+ LLCharacter* mCharacter;
+};
+
+//-----------------------------------------------------------------------------
+// class LLPelvisFixMotion
+//-----------------------------------------------------------------------------
+class LLPelvisFixMotion :
+ public LLMotion
+{
+public:
+ // Constructor
+ LLPelvisFixMotion(const LLUUID &id)
+ : LLMotion(id), mCharacter(NULL)
+ {
+ mName = "pelvis_fix";
+
+ mPelvisState = new LLJointState;
+ }
+
+ // Destructor
+ virtual ~LLPelvisFixMotion() { }
+
+public:
+ //-------------------------------------------------------------------------
+ // functions to support MotionController and MotionRegistry
+ //-------------------------------------------------------------------------
+ // static constructor
+ // all subclasses must implement such a function and register it
+ static LLMotion *create(const LLUUID& id) { return new LLPelvisFixMotion(id); }
+
+public:
+ //-------------------------------------------------------------------------
+ // animation callbacks to be implemented by subclasses
+ //-------------------------------------------------------------------------
+
+ // motions must specify whether or not they loop
+ virtual BOOL getLoop() { return TRUE; }
+
+ // motions must report their total duration
+ virtual F32 getDuration() { return 0.0; }
+
+ // motions must report their "ease in" duration
+ virtual F32 getEaseInDuration() { return 0.5f; }
+
+ // motions must report their "ease out" duration.
+ virtual F32 getEaseOutDuration() { return 0.5f; }
+
+ // motions must report their priority
+ virtual LLJoint::JointPriority getPriority() { return LLJoint::LOW_PRIORITY; }
+
+ virtual LLMotionBlendType getBlendType() { return NORMAL_BLEND; }
+
+ // called to determine when a motion should be activated/deactivated based on avatar pixel coverage
+ virtual F32 getMinPixelArea() { return MIN_REQUIRED_PIXEL_AREA_PELVIS_FIX; }
+
+ // run-time (post constructor) initialization,
+ // called after parameters have been set
+ // must return true to indicate success and be available for activation
+ virtual LLMotionInitStatus onInitialize(LLCharacter *character)
+ {
+ mCharacter = character;
+
+ if (!mPelvisState->setJoint( character->getJoint("mPelvis")))
+ {
+ return STATUS_FAILURE;
+ }
+
+ mPelvisState->setUsage(LLJointState::POS);
+
+ addJointState( mPelvisState );
+ return STATUS_SUCCESS;
+ }
+
+ // called when a motion is activated
+ // must return TRUE to indicate success, or else
+ // it will be deactivated
+ virtual BOOL onActivate() { return TRUE; }
+
+ // called per time step
+ // must return TRUE while it is active, and
+ // must return FALSE when the motion is completed.
+ virtual BOOL onUpdate(F32 time, U8* joint_mask)
+ {
+ mPelvisState->setPosition(LLVector3::zero);
+
+ return TRUE;
+ }
+
+ // called when a motion is deactivated
+ virtual void onDeactivate() {}
+
+private:
+ //-------------------------------------------------------------------------
+ // joint states to be animated
+ //-------------------------------------------------------------------------
+ LLPointer<LLJointState> mPelvisState;
+ LLCharacter* mCharacter;
+};
+
+/**
+ **
+ ** End LLVOAvatar Support classes
+ ** **
+ *********************************************************************************/
+
+
+//-----------------------------------------------------------------------------
+// Static Data
+//-----------------------------------------------------------------------------
+LLXmlTree LLVOAvatar::sXMLTree;
+LLXmlTree LLVOAvatar::sSkeletonXMLTree;
+LLVOAvatarSkeletonInfo* LLVOAvatar::sAvatarSkeletonInfo = NULL;
+LLVOAvatar::LLVOAvatarXmlInfo* LLVOAvatar::sAvatarXmlInfo = NULL;
+LLVOAvatarDictionary *LLVOAvatar::sAvatarDictionary = NULL;
+S32 LLVOAvatar::sFreezeCounter = 0;
+U32 LLVOAvatar::sMaxVisible = 12;
+F32 LLVOAvatar::sRenderDistance = 256.f;
+S32 LLVOAvatar::sNumVisibleAvatars = 0;
+S32 LLVOAvatar::sNumLODChangesThisFrame = 0;
+
+const LLUUID LLVOAvatar::sStepSoundOnLand("e8af4a28-aa83-4310-a7c4-c047e15ea0df");
+const LLUUID LLVOAvatar::sStepSounds[LL_MCODE_END] =
+{
+ SND_STONE_RUBBER,
+ SND_METAL_RUBBER,
+ SND_GLASS_RUBBER,
+ SND_WOOD_RUBBER,
+ SND_FLESH_RUBBER,
+ SND_RUBBER_PLASTIC,
+ SND_RUBBER_RUBBER
+};
+
+S32 LLVOAvatar::sRenderName = RENDER_NAME_ALWAYS;
+BOOL LLVOAvatar::sRenderGroupTitles = TRUE;
+S32 LLVOAvatar::sNumVisibleChatBubbles = 0;
+BOOL LLVOAvatar::sDebugInvisible = FALSE;
+BOOL LLVOAvatar::sShowAttachmentPoints = FALSE;
+BOOL LLVOAvatar::sShowAnimationDebug = FALSE;
+BOOL LLVOAvatar::sShowFootPlane = FALSE;
+BOOL LLVOAvatar::sVisibleInFirstPerson = FALSE;
+F32 LLVOAvatar::sLODFactor = 1.f;
+BOOL LLVOAvatar::sUseImpostors = FALSE;
+BOOL LLVOAvatar::sJointDebug = FALSE;
+
+F32 LLVOAvatar::sUnbakedTime = 0.f;
+F32 LLVOAvatar::sUnbakedUpdateTime = 0.f;
+F32 LLVOAvatar::sGreyTime = 0.f;
+F32 LLVOAvatar::sGreyUpdateTime = 0.f;
+
+//-----------------------------------------------------------------------------
+// Helper functions
+//-----------------------------------------------------------------------------
+static F32 calc_bouncy_animation(F32 x);
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar()
+//-----------------------------------------------------------------------------
+LLVOAvatar::LLVOAvatar(const LLUUID& id,
+ const LLPCode pcode,
+ LLViewerRegion* regionp) :
+ LLViewerObject(id, pcode, regionp),
+ mIsDummy(FALSE),
+ mSpecialRenderMode(0),
+ mTurning(FALSE),
+ mPelvisToFoot(0.f),
+ mLastSkeletonSerialNum( 0 ),
+ mHeadOffset(),
+ mIsSitting(FALSE),
+ mTimeVisible(),
+ mTyping(FALSE),
+ mMeshValid(FALSE),
+ mVisible(FALSE),
+ mWindFreq(0.f),
+ mRipplePhase( 0.f ),
+ mBelowWater(FALSE),
+ mLastAppearanceBlendTime(0.f),
+ mAppearanceAnimating(FALSE),
+ mNameString(),
+ mTitle(),
+ mNameAway(false),
+ mNameBusy(false),
+ mNameMute(false),
+ mNameAppearance(false),
+ mNameFriend(false),
+ mNameAlpha(0.f),
+ mRenderGroupTitles(sRenderGroupTitles),
+ mNameCloud(false),
+ mFirstTEMessageReceived( FALSE ),
+ mFirstAppearanceMessageReceived( FALSE ),
+ mCulled( FALSE ),
+ mVisibilityRank(0),
+ mTexSkinColor( NULL ),
+ mTexHairColor( NULL ),
+ mTexEyeColor( NULL ),
+ mNeedsSkin(FALSE),
+ mLastSkinTime(0.f),
+ mUpdatePeriod(1),
+ mFullyLoaded(FALSE),
+ mPreviousFullyLoaded(FALSE),
+ mFullyLoadedInitialized(FALSE),
+ mSupportsAlphaLayers(FALSE),
+ mLoadedCallbacksPaused(FALSE),
+ mHasPelvisOffset( FALSE )
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+ //VTResume(); // VTune
+
+ // mVoiceVisualizer is created by the hud effects manager and uses the HUD Effects pipeline
+ const BOOL needsSendToSim = false; // currently, this HUD effect doesn't need to pack and unpack data to do its job
+ mVoiceVisualizer = ( LLVoiceVisualizer *)LLHUDManager::getInstance()->createViewerEffect( LLHUDObject::LL_HUD_EFFECT_VOICE_VISUALIZER, needsSendToSim );
+
+ lldebugs << "LLVOAvatar Constructor (0x" << this << ") id:" << mID << llendl;
+
+ mPelvisp = NULL;
+
+ mBakedTextureDatas.resize(BAKED_NUM_INDICES);
+ for (U32 i = 0; i < mBakedTextureDatas.size(); i++ )
+ {
+ mBakedTextureDatas[i].mLastTextureIndex = IMG_DEFAULT_AVATAR;
+ mBakedTextureDatas[i].mTexLayerSet = NULL;
+ mBakedTextureDatas[i].mIsLoaded = false;
+ mBakedTextureDatas[i].mIsUsed = false;
+ mBakedTextureDatas[i].mMaskTexName = 0;
+ mBakedTextureDatas[i].mTextureIndex = LLVOAvatarDictionary::bakedToLocalTextureIndex((EBakedTextureIndex)i);
+ }
+
+ mDirtyMesh = 2; // Dirty geometry, need to regenerate.
+ mMeshTexturesDirty = FALSE;
+ mHeadp = NULL;
+
+ mIsBuilt = FALSE;
+
+ mNumJoints = 0;
+ mSkeleton = NULL;
+
+ mNumCollisionVolumes = 0;
+ mCollisionVolumes = NULL;
+
+ // set up animation variables
+ mSpeed = 0.f;
+ setAnimationData("Speed", &mSpeed);
+
+ mNeedsImpostorUpdate = TRUE;
+ mNeedsAnimUpdate = TRUE;
+
+ mImpostorDistance = 0;
+ mImpostorPixelArea = 0;
+
+ setNumTEs(TEX_NUM_INDICES);
+
+ mbCanSelect = TRUE;
+
+ mSignaledAnimations.clear();
+ mPlayingAnimations.clear();
+
+ mWasOnGroundLeft = FALSE;
+ mWasOnGroundRight = FALSE;
+
+ mTimeLast = 0.0f;
+ mSpeedAccum = 0.0f;
+
+ mRippleTimeLast = 0.f;
+
+ mInAir = FALSE;
+
+ mStepOnLand = TRUE;
+ mStepMaterial = 0;
+
+ mLipSyncActive = false;
+ mOohMorph = NULL;
+ mAahMorph = NULL;
+
+ mCurrentGesticulationLevel = 0;
+
+ mRuthTimer.reset();
+ mRuthDebugTimer.reset();
+ mDebugExistenceTimer.reset();
+ mPelvisOffset = LLVector3(0.0f,0.0f,0.0f);
+ mLastPelvisToFoot = 0.0f;
+ mPelvisFixup = 0.0f;
+}
+
+//------------------------------------------------------------------------
+// LLVOAvatar::~LLVOAvatar()
+//------------------------------------------------------------------------
+LLVOAvatar::~LLVOAvatar()
+{
+ if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
+ {
+ if (!mFullyLoaded)
+ {
+ llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' left after " << (U32)mRuthDebugTimer.getElapsedTimeF32() << " seconds as cloud." << llendl;
+ LLSD args;
+ args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
+ args["TIME"] = llformat("%d",(U32)mRuthDebugTimer.getElapsedTimeF32());
+ args["NAME"] = getFullname();
+ LLNotificationsUtil::add("AvatarRezLeftCloudNotification",args);
+ }
+ else
+ {
+ llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' left." << llendl;
+ LLSD args;
+ args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
+ args["NAME"] = getFullname();
+ LLNotificationsUtil::add("AvatarRezLeftNotification",args);
+ }
+
+ }
+ lldebugs << "LLVOAvatar Destructor (0x" << this << ") id:" << mID << llendl;
+
+ mRoot.removeAllChildren();
+
+ deleteAndClearArray(mSkeleton);
+ deleteAndClearArray(mCollisionVolumes);
+
+ mNumJoints = 0;
+
+ for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
+ {
+ deleteAndClear(mBakedTextureDatas[i].mTexLayerSet);
+ mBakedTextureDatas[i].mMeshes.clear();
+
+ for (morph_list_t::iterator iter2 = mBakedTextureDatas[i].mMaskedMorphs.begin();
+ iter2 != mBakedTextureDatas[i].mMaskedMorphs.end(); iter2++)
+ {
+ LLMaskedMorph* masked_morph = (*iter2);
+ delete masked_morph;
+ }
+ }
+
+ std::for_each(mAttachmentPoints.begin(), mAttachmentPoints.end(), DeletePairedPointer());
+ mAttachmentPoints.clear();
+
+ deleteAndClear(mTexSkinColor);
+ deleteAndClear(mTexHairColor);
+ deleteAndClear(mTexEyeColor);
+
+ std::for_each(mMeshes.begin(), mMeshes.end(), DeletePairedPointer());
+ mMeshes.clear();
+
+ for (std::vector<LLViewerJoint*>::iterator jointIter = mMeshLOD.begin();
+ jointIter != mMeshLOD.end();
+ ++jointIter)
+ {
+ LLViewerJoint* joint = (LLViewerJoint *) *jointIter;
+ std::for_each(joint->mMeshParts.begin(), joint->mMeshParts.end(), DeletePointer());
+ joint->mMeshParts.clear();
+ }
+ std::for_each(mMeshLOD.begin(), mMeshLOD.end(), DeletePointer());
+ mMeshLOD.clear();
+
+ mDead = TRUE;
+
+ mAnimationSources.clear();
+ LLLoadedCallbackEntry::cleanUpCallbackList(&mCallbackTextureList) ;
+
+ lldebugs << "LLVOAvatar Destructor end" << llendl;
+}
+
+void LLVOAvatar::markDead()
+{
+ if (mNameText)
+ {
+ mNameText->markDead();
+ mNameText = NULL;
+ sNumVisibleChatBubbles--;
+ }
+ mVoiceVisualizer->markDead();
+ LLLoadedCallbackEntry::cleanUpCallbackList(&mCallbackTextureList) ;
+ LLViewerObject::markDead();
+}
+
+
+BOOL LLVOAvatar::isFullyBaked()
+{
+ if (mIsDummy) return TRUE;
+ if (getNumTEs() == 0) return FALSE;
+
+ for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
+ {
+ if (!isTextureDefined(mBakedTextureDatas[i].mTextureIndex)
+ && ( (i != BAKED_SKIRT) || isWearingWearableType(LLWearableType::WT_SKIRT) ) )
+ {
+ return FALSE;
+ }
+ }
+ return TRUE;
+}
+
+void LLVOAvatar::deleteLayerSetCaches(bool clearAll)
+{
+ for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
+ {
+ if (mBakedTextureDatas[i].mTexLayerSet)
+ {
+ // ! BACKWARDS COMPATIBILITY !
+ // Can be removed after hair baking is mandatory on the grid
+ if ((i != BAKED_HAIR || isSelf()) && !clearAll)
+ {
+ mBakedTextureDatas[i].mTexLayerSet->deleteCaches();
+ }
+ }
+ if (mBakedTextureDatas[i].mMaskTexName)
+ {
+ glDeleteTextures(1, (GLuint*)&(mBakedTextureDatas[i].mMaskTexName));
+ mBakedTextureDatas[i].mMaskTexName = 0 ;
+ }
+ }
+}
+
+// static
+BOOL LLVOAvatar::areAllNearbyInstancesBaked(S32& grey_avatars)
+{
+ BOOL res = TRUE;
+ grey_avatars = 0;
+ for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
+ iter != LLCharacter::sInstances.end(); ++iter)
+ {
+ LLVOAvatar* inst = (LLVOAvatar*) *iter;
+ if( inst->isDead() )
+ {
+ continue;
+ }
+ else if( !inst->isFullyBaked() )
+ {
+ res = FALSE;
+ if (inst->mHasGrey)
+ {
+ ++grey_avatars;
+ }
+ }
+ }
+ return res;
+}
+
+// static
+void LLVOAvatar::dumpBakedStatus()
+{
+ LLVector3d camera_pos_global = gAgentCamera.getCameraPositionGlobal();
+
+ for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
+ iter != LLCharacter::sInstances.end(); ++iter)
+ {
+ LLVOAvatar* inst = (LLVOAvatar*) *iter;
+ llinfos << "Avatar ";
+
+ LLNameValue* firstname = inst->getNVPair("FirstName");
+ LLNameValue* lastname = inst->getNVPair("LastName");
+
+ if( firstname )
+ {
+ llcont << firstname->getString();
+ }
+ if( lastname )
+ {
+ llcont << " " << lastname->getString();
+ }
+
+ llcont << " " << inst->mID;
+
+ if( inst->isDead() )
+ {
+ llcont << " DEAD ("<< inst->getNumRefs() << " refs)";
+ }
+
+ if( inst->isSelf() )
+ {
+ llcont << " (self)";
+ }
+
+
+ F64 dist_to_camera = (inst->getPositionGlobal() - camera_pos_global).length();
+ llcont << " " << dist_to_camera << "m ";
+
+ llcont << " " << inst->mPixelArea << " pixels";
+
+ if( inst->isVisible() )
+ {
+ llcont << " (visible)";
+ }
+ else
+ {
+ llcont << " (not visible)";
+ }
+
+ if( inst->isFullyBaked() )
+ {
+ llcont << " Baked";
+ }
+ else
+ {
+ llcont << " Unbaked (";
+
+ for (LLVOAvatarDictionary::BakedTextures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getBakedTextures().begin();
+ iter != LLVOAvatarDictionary::getInstance()->getBakedTextures().end();
+ ++iter)
+ {
+ const LLVOAvatarDictionary::BakedEntry *baked_dict = iter->second;
+ const ETextureIndex index = baked_dict->mTextureIndex;
+ if (!inst->isTextureDefined(index))
+ {
+ llcont << " " << LLVOAvatarDictionary::getInstance()->getTexture(index)->mName;
+ }
+ }
+ llcont << " ) " << inst->getUnbakedPixelAreaRank();
+ if( inst->isCulled() )
+ {
+ llcont << " culled";
+ }
+ }
+ llcont << llendl;
+ }
+}
+
+//static
+void LLVOAvatar::restoreGL()
+{
+ if (!isAgentAvatarValid()) return;
+
+ gAgentAvatarp->setCompositeUpdatesEnabled(TRUE);
+ for (U32 i = 0; i < gAgentAvatarp->mBakedTextureDatas.size(); i++)
+ {
+ gAgentAvatarp->invalidateComposite(gAgentAvatarp->mBakedTextureDatas[i].mTexLayerSet, FALSE);
+ }
+ gAgentAvatarp->updateMeshTextures();
+}
+
+//static
+void LLVOAvatar::destroyGL()
+{
+ deleteCachedImages();
+
+ resetImpostors();
+}
+
+//static
+void LLVOAvatar::resetImpostors()
+{
+ for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
+ iter != LLCharacter::sInstances.end(); ++iter)
+ {
+ LLVOAvatar* avatar = (LLVOAvatar*) *iter;
+ avatar->mImpostor.release();
+ }
+}
+
+// static
+void LLVOAvatar::deleteCachedImages(bool clearAll)
+{
+ if (LLTexLayerSet::sHasCaches)
+ {
+ lldebugs << "Deleting layer set caches" << llendl;
+ for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
+ iter != LLCharacter::sInstances.end(); ++iter)
+ {
+ LLVOAvatar* inst = (LLVOAvatar*) *iter;
+ inst->deleteLayerSetCaches(clearAll);
+ }
+ LLTexLayerSet::sHasCaches = FALSE;
+ }
+ LLVOAvatarSelf::deleteScratchTextures();
+ LLTexLayerStaticImageList::getInstance()->deleteCachedImages();
+}
+
+
+//------------------------------------------------------------------------
+// static
+// LLVOAvatar::initClass()
+//------------------------------------------------------------------------
+void LLVOAvatar::initClass()
+{
+ std::string xmlFile;
+
+ xmlFile = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,AVATAR_DEFAULT_CHAR) + "_lad.xml";
+ BOOL success = sXMLTree.parseFile( xmlFile, FALSE );
+ if (!success)
+ {
+ llerrs << "Problem reading avatar configuration file:" << xmlFile << llendl;
+ }
+
+ // now sanity check xml file
+ LLXmlTreeNode* root = sXMLTree.getRoot();
+ if (!root)
+ {
+ llerrs << "No root node found in avatar configuration file: " << xmlFile << llendl;
+ return;
+ }
+
+ //-------------------------------------------------------------------------
+ // <linden_avatar version="1.0"> (root)
+ //-------------------------------------------------------------------------
+ if( !root->hasName( "linden_avatar" ) )
+ {
+ llerrs << "Invalid avatar file header: " << xmlFile << llendl;
+ }
+
+ std::string version;
+ static LLStdStringHandle version_string = LLXmlTree::addAttributeString("version");
+ if( !root->getFastAttributeString( version_string, version ) || (version != "1.0") )
+ {
+ llerrs << "Invalid avatar file version: " << version << " in file: " << xmlFile << llendl;
+ }
+
+ S32 wearable_def_version = 1;
+ static LLStdStringHandle wearable_definition_version_string = LLXmlTree::addAttributeString("wearable_definition_version");
+ root->getFastAttributeS32( wearable_definition_version_string, wearable_def_version );
+ LLWearable::setCurrentDefinitionVersion( wearable_def_version );
+
+ std::string mesh_file_name;
+
+ LLXmlTreeNode* skeleton_node = root->getChildByName( "skeleton" );
+ if (!skeleton_node)
+ {
+ llerrs << "No skeleton in avatar configuration file: " << xmlFile << llendl;
+ return;
+ }
+
+ std::string skeleton_file_name;
+ static LLStdStringHandle file_name_string = LLXmlTree::addAttributeString("file_name");
+ if (!skeleton_node->getFastAttributeString(file_name_string, skeleton_file_name))
+ {
+ llerrs << "No file name in skeleton node in avatar config file: " << xmlFile << llendl;
+ }
+
+ std::string skeleton_path;
+ skeleton_path = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,skeleton_file_name);
+ if (!parseSkeletonFile(skeleton_path))
+ {
+ llerrs << "Error parsing skeleton file: " << skeleton_path << llendl;
+ }
+
+ // Process XML data
+
+ // avatar_skeleton.xml
+ llassert(!sAvatarSkeletonInfo);
+ sAvatarSkeletonInfo = new LLVOAvatarSkeletonInfo;
+ if (!sAvatarSkeletonInfo->parseXml(sSkeletonXMLTree.getRoot()))
+ {
+ llerrs << "Error parsing skeleton XML file: " << skeleton_path << llendl;
+ }
+ // parse avatar_lad.xml
+ llassert(!sAvatarXmlInfo);
+ sAvatarXmlInfo = new LLVOAvatarXmlInfo;
+ if (!sAvatarXmlInfo->parseXmlSkeletonNode(root))
+ {
+ llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
+ }
+ if (!sAvatarXmlInfo->parseXmlMeshNodes(root))
+ {
+ llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
+ }
+ if (!sAvatarXmlInfo->parseXmlColorNodes(root))
+ {
+ llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
+ }
+ if (!sAvatarXmlInfo->parseXmlLayerNodes(root))
+ {
+ llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
+ }
+ if (!sAvatarXmlInfo->parseXmlDriverNodes(root))
+ {
+ llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
+ }
+ if (!sAvatarXmlInfo->parseXmlMorphNodes(root))
+ {
+ llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
+ }
+
+ gAnimLibrary.animStateSetString(ANIM_AGENT_BODY_NOISE,"body_noise");
+ gAnimLibrary.animStateSetString(ANIM_AGENT_BREATHE_ROT,"breathe_rot");
+ gAnimLibrary.animStateSetString(ANIM_AGENT_EDITING,"editing");
+ gAnimLibrary.animStateSetString(ANIM_AGENT_EYE,"eye");
+ gAnimLibrary.animStateSetString(ANIM_AGENT_FLY_ADJUST,"fly_adjust");
+ gAnimLibrary.animStateSetString(ANIM_AGENT_HAND_MOTION,"hand_motion");
+ gAnimLibrary.animStateSetString(ANIM_AGENT_HEAD_ROT,"head_rot");
+ gAnimLibrary.animStateSetString(ANIM_AGENT_PELVIS_FIX,"pelvis_fix");
+ gAnimLibrary.animStateSetString(ANIM_AGENT_TARGET,"target");
+ gAnimLibrary.animStateSetString(ANIM_AGENT_WALK_ADJUST,"walk_adjust");
+}
+
+
+void LLVOAvatar::cleanupClass()
+{
+ deleteAndClear(sAvatarXmlInfo);
+ sSkeletonXMLTree.cleanup();
+ sXMLTree.cleanup();
+}
+
+void LLVOAvatar::initInstance(void)
+{
+ //-------------------------------------------------------------------------
+ // initialize joint, mesh and shape members
+ //-------------------------------------------------------------------------
+ mRoot.setName( "mRoot" );
+
+ for (LLVOAvatarDictionary::Meshes::const_iterator iter = LLVOAvatarDictionary::getInstance()->getMeshes().begin();
+ iter != LLVOAvatarDictionary::getInstance()->getMeshes().end();
+ ++iter)
+ {
+ const EMeshIndex mesh_index = iter->first;
+ const LLVOAvatarDictionary::MeshEntry *mesh_dict = iter->second;
+ LLViewerJoint* joint = new LLViewerJoint();
+ joint->setName(mesh_dict->mName);
+ joint->setMeshID(mesh_index);
+ mMeshLOD.push_back(joint);
+
+ /* mHairLOD.setName("mHairLOD");
+ mHairMesh0.setName("mHairMesh0");
+ mHairMesh0.setMeshID(MESH_ID_HAIR);
+ mHairMesh1.setName("mHairMesh1"); */
+ for (U32 lod = 0; lod < mesh_dict->mLOD; lod++)
+ {
+ LLViewerJointMesh* mesh = new LLViewerJointMesh();
+ std::string mesh_name = "m" + mesh_dict->mName + boost::lexical_cast<std::string>(lod);
+ // We pre-pended an m - need to capitalize first character for camelCase
+ mesh_name[1] = toupper(mesh_name[1]);
+ mesh->setName(mesh_name);
+ mesh->setMeshID(mesh_index);
+ mesh->setPickName(mesh_dict->mPickName);
+ mesh->setIsTransparent(FALSE);
+ switch((int)mesh_index)
+ {
+ case MESH_ID_HAIR:
+ mesh->setIsTransparent(TRUE);
+ break;
+ case MESH_ID_SKIRT:
+ mesh->setIsTransparent(TRUE);
+ break;
+ case MESH_ID_EYEBALL_LEFT:
+ case MESH_ID_EYEBALL_RIGHT:
+ mesh->setSpecular( LLColor4( 1.0f, 1.0f, 1.0f, 1.0f ), 1.f );
+ break;
+ }
+
+ joint->mMeshParts.push_back(mesh);
+ }
+ }
+
+ //-------------------------------------------------------------------------
+ // associate baked textures with meshes
+ //-------------------------------------------------------------------------
+ for (LLVOAvatarDictionary::Meshes::const_iterator iter = LLVOAvatarDictionary::getInstance()->getMeshes().begin();
+ iter != LLVOAvatarDictionary::getInstance()->getMeshes().end();
+ ++iter)
+ {
+ const EMeshIndex mesh_index = iter->first;
+ const LLVOAvatarDictionary::MeshEntry *mesh_dict = iter->second;
+ const EBakedTextureIndex baked_texture_index = mesh_dict->mBakedID;
+ // Skip it if there's no associated baked texture.
+ if (baked_texture_index == BAKED_NUM_INDICES) continue;
+
+ for (std::vector<LLViewerJointMesh* >::iterator iter = mMeshLOD[mesh_index]->mMeshParts.begin();
+ iter != mMeshLOD[mesh_index]->mMeshParts.end();
+ ++iter)
+ {
+ LLViewerJointMesh* mesh = (LLViewerJointMesh*) *iter;
+ mBakedTextureDatas[(int)baked_texture_index].mMeshes.push_back(mesh);
+ }
+ }
+
+
+ //-------------------------------------------------------------------------
+ // register motions
+ //-------------------------------------------------------------------------
+ if (LLCharacter::sInstances.size() == 1)
+ {
+ LLKeyframeMotion::setVFS(gStaticVFS);
+ registerMotion( ANIM_AGENT_BUSY, LLNullMotion::create );
+ registerMotion( ANIM_AGENT_CROUCH, LLKeyframeStandMotion::create );
+ registerMotion( ANIM_AGENT_CROUCHWALK, LLKeyframeWalkMotion::create );
+ registerMotion( ANIM_AGENT_EXPRESS_AFRAID, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_ANGER, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_BORED, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_CRY, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_DISDAIN, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_EMBARRASSED, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_FROWN, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_KISS, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_LAUGH, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_OPEN_MOUTH, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_REPULSED, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_SAD, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_SHRUG, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_SMILE, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_SURPRISE, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_TONGUE_OUT, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_TOOTHSMILE, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_WINK, LLEmote::create );
+ registerMotion( ANIM_AGENT_EXPRESS_WORRY, LLEmote::create );
+ registerMotion( ANIM_AGENT_FEMALE_RUN_NEW, LLKeyframeWalkMotion::create );
+ registerMotion( ANIM_AGENT_FEMALE_WALK, LLKeyframeWalkMotion::create );
+ registerMotion( ANIM_AGENT_FEMALE_WALK_NEW, LLKeyframeWalkMotion::create );
+ registerMotion( ANIM_AGENT_RUN, LLKeyframeWalkMotion::create );
+ registerMotion( ANIM_AGENT_RUN_NEW, LLKeyframeWalkMotion::create );
+ registerMotion( ANIM_AGENT_STAND, LLKeyframeStandMotion::create );
+ registerMotion( ANIM_AGENT_STAND_1, LLKeyframeStandMotion::create );
+ registerMotion( ANIM_AGENT_STAND_2, LLKeyframeStandMotion::create );
+ registerMotion( ANIM_AGENT_STAND_3, LLKeyframeStandMotion::create );
+ registerMotion( ANIM_AGENT_STAND_4, LLKeyframeStandMotion::create );
+ registerMotion( ANIM_AGENT_STANDUP, LLKeyframeFallMotion::create );
+ registerMotion( ANIM_AGENT_TURNLEFT, LLKeyframeWalkMotion::create );
+ registerMotion( ANIM_AGENT_TURNRIGHT, LLKeyframeWalkMotion::create );
+ registerMotion( ANIM_AGENT_WALK, LLKeyframeWalkMotion::create );
+ registerMotion( ANIM_AGENT_WALK_NEW, LLKeyframeWalkMotion::create );
+
+ // motions without a start/stop bit
+ registerMotion( ANIM_AGENT_BODY_NOISE, LLBodyNoiseMotion::create );
+ registerMotion( ANIM_AGENT_BREATHE_ROT, LLBreatheMotionRot::create );
+ registerMotion( ANIM_AGENT_EDITING, LLEditingMotion::create );
+ registerMotion( ANIM_AGENT_EYE, LLEyeMotion::create );
+ registerMotion( ANIM_AGENT_FEMALE_WALK, LLKeyframeWalkMotion::create );
+ registerMotion( ANIM_AGENT_FLY_ADJUST, LLFlyAdjustMotion::create );
+ registerMotion( ANIM_AGENT_HAND_MOTION, LLHandMotion::create );
+ registerMotion( ANIM_AGENT_HEAD_ROT, LLHeadRotMotion::create );
+ registerMotion( ANIM_AGENT_PELVIS_FIX, LLPelvisFixMotion::create );
+ registerMotion( ANIM_AGENT_SIT_FEMALE, LLKeyframeMotion::create );
+ registerMotion( ANIM_AGENT_TARGET, LLTargetingMotion::create );
+ registerMotion( ANIM_AGENT_WALK_ADJUST, LLWalkAdjustMotion::create );
+
+ }
+
+ if (gNoRender)
+ {
+ return;
+ }
+
+ buildCharacter();
+
+ if (gNoRender)
+ {
+ return;
+ }
+
+ // preload specific motions here
+ createMotion( ANIM_AGENT_CUSTOMIZE);
+ createMotion( ANIM_AGENT_CUSTOMIZE_DONE);
+
+ //VTPause(); // VTune
+
+ mVoiceVisualizer->setVoiceEnabled( LLVoiceClient::getInstance()->getVoiceEnabled( mID ) );
+
+}
+
+const LLVector3 LLVOAvatar::getRenderPosition() const
+{
+ if (mDrawable.isNull() || mDrawable->getGeneration() < 0)
+ {
+ return getPositionAgent();
+ }
+ else if (isRoot())
+ {
+ return mDrawable->getPositionAgent();
+ }
+ else
+ {
+ return getPosition() * mDrawable->getParent()->getRenderMatrix();
+ }
+}
+
+void LLVOAvatar::updateDrawable(BOOL force_damped)
+{
+ clearChanged(SHIFTED);
+}
+
+void LLVOAvatar::onShift(const LLVector4a& shift_vector)
+{
+ const LLVector3& shift = reinterpret_cast<const LLVector3&>(shift_vector);
+ mLastAnimExtents[0] += shift;
+ mLastAnimExtents[1] += shift;
+ mNeedsImpostorUpdate = TRUE;
+ mNeedsAnimUpdate = TRUE;
+}
+
+void LLVOAvatar::updateSpatialExtents(LLVector4a& newMin, LLVector4a &newMax)
+{
+ if (isImpostor() && !needsImpostorUpdate())
+ {
+ LLVector3 delta = getRenderPosition() -
+ ((LLVector3(mDrawable->getPositionGroup().getF32ptr())-mImpostorOffset));
+
+ newMin.load3( (mLastAnimExtents[0] + delta).mV);
+ newMax.load3( (mLastAnimExtents[1] + delta).mV);
+ }
+ else
+ {
+ getSpatialExtents(newMin,newMax);
+ mLastAnimExtents[0].set(newMin.getF32ptr());
+ mLastAnimExtents[1].set(newMax.getF32ptr());
+ LLVector4a pos_group;
+ pos_group.setAdd(newMin,newMax);
+ pos_group.mul(0.5f);
+ mImpostorOffset = LLVector3(pos_group.getF32ptr())-getRenderPosition();
+ mDrawable->setPositionGroup(pos_group);
+ }
+}
+
+void LLVOAvatar::getSpatialExtents(LLVector4a& newMin, LLVector4a& newMax)
+{
+ LLVector4a buffer(0.25f);
+ LLVector4a pos;
+ pos.load3(getRenderPosition().mV);
+ newMin.setSub(pos, buffer);
+ newMax.setAdd(pos, buffer);
+
+ float max_attachment_span = get_default_max_prim_scale() * 5.0f;
+
+ //stretch bounding box by joint positions
+ for (polymesh_map_t::iterator i = mMeshes.begin(); i != mMeshes.end(); ++i)
+ {
+ LLPolyMesh* mesh = i->second;
+ for (S32 joint_num = 0; joint_num < mesh->mJointRenderData.count(); joint_num++)
+ {
+ LLVector4a trans;
+ trans.load3( mesh->mJointRenderData[joint_num]->mWorldMatrix->getTranslation().mV);
+ update_min_max(newMin, newMax, trans);
+ }
+ }
+
+ LLVector4a center, size;
+ center.setAdd(newMin, newMax);
+ center.mul(0.5f);
+
+ size.setSub(newMax,newMin);
+ size.mul(0.5f);
+
+ mPixelArea = LLPipeline::calcPixelArea(center, size, *LLViewerCamera::getInstance());
+
+ //stretch bounding box by attachments
+ for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+
+ if (!attachment->getValid())
+ {
+ continue ;
+ }
+
+ for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
+ attachment_iter != attachment->mAttachedObjects.end();
+ ++attachment_iter)
+ {
+ const LLViewerObject* attached_object = (*attachment_iter);
+ if (attached_object && !attached_object->isHUDAttachment())
+ {
+ LLDrawable* drawable = attached_object->mDrawable;
+ if (drawable && !drawable->isState(LLDrawable::RIGGED))
+ {
+ LLSpatialBridge* bridge = drawable->getSpatialBridge();
+ if (bridge)
+ {
+ const LLVector4a* ext = bridge->getSpatialExtents();
+ LLVector4a distance;
+ distance.setSub(ext[1], ext[0]);
+ LLVector4a max_span(max_attachment_span);
+
+ S32 lt = distance.lessThan(max_span).getGatheredBits() & 0x7;
+
+ // Only add the prim to spatial extents calculations if it isn't a megaprim.
+ // max_attachment_span calculated at the start of the function
+ // (currently 5 times our max prim size)
+ if (lt == 0x7)
+ {
+ update_min_max(newMin,newMax,ext[0]);
+ update_min_max(newMin,newMax,ext[1]);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ //pad bounding box
+
+ newMin.sub(buffer);
+ newMax.add(buffer);
+}
+
+//-----------------------------------------------------------------------------
+// renderCollisionVolumes()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::renderCollisionVolumes()
+{
+ for (S32 i = 0; i < mNumCollisionVolumes; i++)
+ {
+ mCollisionVolumes[i].renderCollision();
+ }
+
+ if (mNameText.notNull())
+ {
+ LLVector3 unused;
+ mNameText->lineSegmentIntersect(LLVector3(0,0,0), LLVector3(0,0,1), unused, TRUE);
+ }
+}
+
+BOOL LLVOAvatar::lineSegmentIntersect(const LLVector3& start, const LLVector3& end,
+ S32 face,
+ BOOL pick_transparent,
+ S32* face_hit,
+ LLVector3* intersection,
+ LLVector2* tex_coord,
+ LLVector3* normal,
+ LLVector3* bi_normal)
+{
+ if ((isSelf() && !gAgent.needsRenderAvatar()) || !LLPipeline::sPickAvatar)
+ {
+ return FALSE;
+ }
+
+ if (lineSegmentBoundingBox(start, end))
+ {
+ for (S32 i = 0; i < mNumCollisionVolumes; ++i)
+ {
+ mCollisionVolumes[i].updateWorldMatrix();
+
+ glh::matrix4f mat((F32*) mCollisionVolumes[i].getXform()->getWorldMatrix().mMatrix);
+ glh::matrix4f inverse = mat.inverse();
+ glh::matrix4f norm_mat = inverse.transpose();
+
+ glh::vec3f p1(start.mV);
+ glh::vec3f p2(end.mV);
+
+ inverse.mult_matrix_vec(p1);
+ inverse.mult_matrix_vec(p2);
+
+ LLVector3 position;
+ LLVector3 norm;
+
+ if (linesegment_sphere(LLVector3(p1.v), LLVector3(p2.v), LLVector3(0,0,0), 1.f, position, norm))
+ {
+ glh::vec3f res_pos(position.mV);
+ mat.mult_matrix_vec(res_pos);
+
+ norm.normalize();
+ glh::vec3f res_norm(norm.mV);
+ norm_mat.mult_matrix_dir(res_norm);
+
+ if (intersection)
+ {
+ *intersection = LLVector3(res_pos.v);
+ }
+
+ if (normal)
+ {
+ *normal = LLVector3(res_norm.v);
+ }
+
+ return TRUE;
+ }
+ }
+ }
+
+ LLVector3 position;
+ if (mNameText.notNull() && mNameText->lineSegmentIntersect(start, end, position))
+ {
+ if (intersection)
+ {
+ *intersection = position;
+ }
+
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+//-----------------------------------------------------------------------------
+// parseSkeletonFile()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::parseSkeletonFile(const std::string& filename)
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ //-------------------------------------------------------------------------
+ // parse the file
+ //-------------------------------------------------------------------------
+ BOOL parsesuccess = sSkeletonXMLTree.parseFile( filename, FALSE );
+
+ if (!parsesuccess)
+ {
+ llerrs << "Can't parse skeleton file: " << filename << llendl;
+ return FALSE;
+ }
+
+ // now sanity check xml file
+ LLXmlTreeNode* root = sSkeletonXMLTree.getRoot();
+ if (!root)
+ {
+ llerrs << "No root node found in avatar skeleton file: " << filename << llendl;
+ return FALSE;
+ }
+
+ if( !root->hasName( "linden_skeleton" ) )
+ {
+ llerrs << "Invalid avatar skeleton file header: " << filename << llendl;
+ return FALSE;
+ }
+
+ std::string version;
+ static LLStdStringHandle version_string = LLXmlTree::addAttributeString("version");
+ if( !root->getFastAttributeString( version_string, version ) || (version != "1.0") )
+ {
+ llerrs << "Invalid avatar skeleton file version: " << version << " in file: " << filename << llendl;
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// setupBone()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::setupBone(const LLVOAvatarBoneInfo* info, LLViewerJoint* parent, S32 &volume_num, S32 &joint_num)
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ LLViewerJoint* joint = NULL;
+
+ if (info->mIsJoint)
+ {
+ joint = (LLViewerJoint*)getCharacterJoint(joint_num);
+ if (!joint)
+ {
+ llwarns << "Too many bones" << llendl;
+ return FALSE;
+ }
+ joint->setName( info->mName );
+ }
+ else // collision volume
+ {
+ if (volume_num >= (S32)mNumCollisionVolumes)
+ {
+ llwarns << "Too many bones" << llendl;
+ return FALSE;
+ }
+ joint = (LLViewerJoint*)(&mCollisionVolumes[volume_num]);
+ joint->setName( info->mName );
+ }
+
+ // add to parent
+ if (parent)
+ {
+ parent->addChild( joint );
+ }
+
+ joint->setPosition(info->mPos);
+ joint->setRotation(mayaQ(info->mRot.mV[VX], info->mRot.mV[VY],
+ info->mRot.mV[VZ], LLQuaternion::XYZ));
+ joint->setScale(info->mScale);
+
+ joint->setDefaultFromCurrentXform();
+
+ if (info->mIsJoint)
+ {
+ joint->setSkinOffset( info->mPivot );
+ joint_num++;
+ }
+ else // collision volume
+ {
+ volume_num++;
+ }
+
+ // setup children
+ LLVOAvatarBoneInfo::child_list_t::const_iterator iter;
+ for (iter = info->mChildList.begin(); iter != info->mChildList.end(); ++iter)
+ {
+ LLVOAvatarBoneInfo *child_info = *iter;
+ if (!setupBone(child_info, joint, volume_num, joint_num))
+ {
+ return FALSE;
+ }
+ }
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// buildSkeleton()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::buildSkeleton(const LLVOAvatarSkeletonInfo *info)
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ //-------------------------------------------------------------------------
+ // allocate joints
+ //-------------------------------------------------------------------------
+ if (!allocateCharacterJoints(info->mNumBones))
+ {
+ llerrs << "Can't allocate " << info->mNumBones << " joints" << llendl;
+ return FALSE;
+ }
+
+ //-------------------------------------------------------------------------
+ // allocate volumes
+ //-------------------------------------------------------------------------
+ if (info->mNumCollisionVolumes)
+ {
+ if (!allocateCollisionVolumes(info->mNumCollisionVolumes))
+ {
+ llerrs << "Can't allocate " << info->mNumCollisionVolumes << " collision volumes" << llendl;
+ return FALSE;
+ }
+ }
+
+ S32 current_joint_num = 0;
+ S32 current_volume_num = 0;
+ LLVOAvatarSkeletonInfo::bone_info_list_t::const_iterator iter;
+ for (iter = info->mBoneInfoList.begin(); iter != info->mBoneInfoList.end(); ++iter)
+ {
+ LLVOAvatarBoneInfo *info = *iter;
+ if (!setupBone(info, NULL, current_volume_num, current_joint_num))
+ {
+ llerrs << "Error parsing bone in skeleton file" << llendl;
+ return FALSE;
+ }
+ }
+
+ return TRUE;
+}
+
+LLVOAvatar* LLVOAvatar::asAvatar()
+{
+ return this;
+}
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::startDefaultMotions()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::startDefaultMotions()
+{
+ //-------------------------------------------------------------------------
+ // start default motions
+ //-------------------------------------------------------------------------
+ startMotion( ANIM_AGENT_HEAD_ROT );
+ startMotion( ANIM_AGENT_EYE );
+ startMotion( ANIM_AGENT_BODY_NOISE );
+ startMotion( ANIM_AGENT_BREATHE_ROT );
+ startMotion( ANIM_AGENT_HAND_MOTION );
+ startMotion( ANIM_AGENT_PELVIS_FIX );
+
+ //-------------------------------------------------------------------------
+ // restart any currently active motions
+ //-------------------------------------------------------------------------
+ processAnimationStateChanges();
+}
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::buildCharacter()
+// Deferred initialization and rebuild of the avatar.
+//-----------------------------------------------------------------------------
+void LLVOAvatar::buildCharacter()
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ //-------------------------------------------------------------------------
+ // remove all references to our existing skeleton
+ // so we can rebuild it
+ //-------------------------------------------------------------------------
+ flushAllMotions();
+
+ //-------------------------------------------------------------------------
+ // remove all of mRoot's children
+ //-------------------------------------------------------------------------
+ mRoot.removeAllChildren();
+ mIsBuilt = FALSE;
+
+ //-------------------------------------------------------------------------
+ // clear mesh data
+ //-------------------------------------------------------------------------
+ for (std::vector<LLViewerJoint*>::iterator jointIter = mMeshLOD.begin();
+ jointIter != mMeshLOD.end(); ++jointIter)
+ {
+ LLViewerJoint* joint = (LLViewerJoint*) *jointIter;
+ for (std::vector<LLViewerJointMesh*>::iterator meshIter = joint->mMeshParts.begin();
+ meshIter != joint->mMeshParts.end(); ++meshIter)
+ {
+ LLViewerJointMesh * mesh = (LLViewerJointMesh *) *meshIter;
+ mesh->setMesh(NULL);
+ }
+ }
+
+ //-------------------------------------------------------------------------
+ // (re)load our skeleton and meshes
+ //-------------------------------------------------------------------------
+ LLTimer timer;
+
+ BOOL status = loadAvatar();
+ stop_glerror();
+
+ if (gNoRender)
+ {
+ // Still want to load the avatar skeleton so visual parameters work.
+ return;
+ }
+
+// gPrintMessagesThisFrame = TRUE;
+ lldebugs << "Avatar load took " << timer.getElapsedTimeF32() << " seconds." << llendl;
+
+ if (!status)
+ {
+ if (isSelf())
+ {
+ llerrs << "Unable to load user's avatar" << llendl;
+ }
+ else
+ {
+ llwarns << "Unable to load other's avatar" << llendl;
+ }
+ return;
+ }
+
+ //-------------------------------------------------------------------------
+ // initialize "well known" joint pointers
+ //-------------------------------------------------------------------------
+ mPelvisp = (LLViewerJoint*)mRoot.findJoint("mPelvis");
+ mTorsop = (LLViewerJoint*)mRoot.findJoint("mTorso");
+ mChestp = (LLViewerJoint*)mRoot.findJoint("mChest");
+ mNeckp = (LLViewerJoint*)mRoot.findJoint("mNeck");
+ mHeadp = (LLViewerJoint*)mRoot.findJoint("mHead");
+ mSkullp = (LLViewerJoint*)mRoot.findJoint("mSkull");
+ mHipLeftp = (LLViewerJoint*)mRoot.findJoint("mHipLeft");
+ mHipRightp = (LLViewerJoint*)mRoot.findJoint("mHipRight");
+ mKneeLeftp = (LLViewerJoint*)mRoot.findJoint("mKneeLeft");
+ mKneeRightp = (LLViewerJoint*)mRoot.findJoint("mKneeRight");
+ mAnkleLeftp = (LLViewerJoint*)mRoot.findJoint("mAnkleLeft");
+ mAnkleRightp = (LLViewerJoint*)mRoot.findJoint("mAnkleRight");
+ mFootLeftp = (LLViewerJoint*)mRoot.findJoint("mFootLeft");
+ mFootRightp = (LLViewerJoint*)mRoot.findJoint("mFootRight");
+ mWristLeftp = (LLViewerJoint*)mRoot.findJoint("mWristLeft");
+ mWristRightp = (LLViewerJoint*)mRoot.findJoint("mWristRight");
+ mEyeLeftp = (LLViewerJoint*)mRoot.findJoint("mEyeLeft");
+ mEyeRightp = (LLViewerJoint*)mRoot.findJoint("mEyeRight");
+
+ //-------------------------------------------------------------------------
+ // Make sure "well known" pointers exist
+ //-------------------------------------------------------------------------
+ if (!(mPelvisp &&
+ mTorsop &&
+ mChestp &&
+ mNeckp &&
+ mHeadp &&
+ mSkullp &&
+ mHipLeftp &&
+ mHipRightp &&
+ mKneeLeftp &&
+ mKneeRightp &&
+ mAnkleLeftp &&
+ mAnkleRightp &&
+ mFootLeftp &&
+ mFootRightp &&
+ mWristLeftp &&
+ mWristRightp &&
+ mEyeLeftp &&
+ mEyeRightp))
+ {
+ llerrs << "Failed to create avatar." << llendl;
+ return;
+ }
+
+ //-------------------------------------------------------------------------
+ // initialize the pelvis
+ //-------------------------------------------------------------------------
+ mPelvisp->setPosition( LLVector3(0.0f, 0.0f, 0.0f) );
+
+ //-------------------------------------------------------------------------
+ // set head offset from pelvis
+ //-------------------------------------------------------------------------
+ updateHeadOffset();
+
+ //-------------------------------------------------------------------------
+ // initialize lip sync morph pointers
+ //-------------------------------------------------------------------------
+ mOohMorph = getVisualParam( "Lipsync_Ooh" );
+ mAahMorph = getVisualParam( "Lipsync_Aah" );
+
+ // If we don't have the Ooh morph, use the Kiss morph
+ if (!mOohMorph)
+ {
+ llwarns << "Missing 'Ooh' morph for lipsync, using fallback." << llendl;
+ mOohMorph = getVisualParam( "Express_Kiss" );
+ }
+
+ // If we don't have the Aah morph, use the Open Mouth morph
+ if (!mAahMorph)
+ {
+ llwarns << "Missing 'Aah' morph for lipsync, using fallback." << llendl;
+ mAahMorph = getVisualParam( "Express_Open_Mouth" );
+ }
+
+ startDefaultMotions();
+
+ //-------------------------------------------------------------------------
+ // restart any currently active motions
+ //-------------------------------------------------------------------------
+ processAnimationStateChanges();
+
+ mIsBuilt = TRUE;
+ stop_glerror();
+
+ mMeshValid = TRUE;
+}
+
+
+//-----------------------------------------------------------------------------
+// releaseMeshData()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::releaseMeshData()
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ if (sInstances.size() < AVATAR_RELEASE_THRESHOLD || mIsDummy)
+ {
+ return;
+ }
+
+ //llinfos << "Releasing" << llendl;
+
+ // cleanup mesh data
+ for (std::vector<LLViewerJoint*>::iterator iter = mMeshLOD.begin();
+ iter != mMeshLOD.end();
+ ++iter)
+ {
+ LLViewerJoint* joint = (LLViewerJoint*) *iter;
+ joint->setValid(FALSE, TRUE);
+ }
+
+ //cleanup data
+ if (mDrawable.notNull())
+ {
+ LLFace* facep = mDrawable->getFace(0);
+ facep->setSize(0, 0);
+ for(S32 i = mNumInitFaces ; i < mDrawable->getNumFaces(); i++)
+ {
+ facep = mDrawable->getFace(i);
+ facep->setSize(0, 0);
+ }
+ }
+
+ for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+ if (!attachment->getIsHUDAttachment())
+ {
+ attachment->setAttachmentVisibility(FALSE);
+ }
+ }
+ mMeshValid = FALSE;
+}
+
+//-----------------------------------------------------------------------------
+// restoreMeshData()
+//-----------------------------------------------------------------------------
+// virtual
+void LLVOAvatar::restoreMeshData()
+{
+ llassert(!isSelf());
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ //llinfos << "Restoring" << llendl;
+ mMeshValid = TRUE;
+ updateJointLODs();
+
+ for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+ if (!attachment->getIsHUDAttachment())
+ {
+ attachment->setAttachmentVisibility(TRUE);
+ }
+ }
+
+ // force mesh update as LOD might not have changed to trigger this
+ gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_GEOMETRY, TRUE);
+}
+
+//-----------------------------------------------------------------------------
+// updateMeshData()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::updateMeshData()
+{
+ if (mDrawable.notNull())
+ {
+ stop_glerror();
+
+ S32 f_num = 0 ;
+ const U32 VERTEX_NUMBER_THRESHOLD = 128 ;//small number of this means each part of an avatar has its own vertex buffer.
+ const S32 num_parts = mMeshLOD.size();
+
+ // this order is determined by number of LODS
+ // if a mesh earlier in this list changed LODs while a later mesh doesn't,
+ // the later mesh's index offset will be inaccurate
+ for(S32 part_index = 0 ; part_index < num_parts ;)
+ {
+ S32 j = part_index ;
+ U32 last_v_num = 0, num_vertices = 0 ;
+ U32 last_i_num = 0, num_indices = 0 ;
+
+ while(part_index < num_parts && num_vertices < VERTEX_NUMBER_THRESHOLD)
+ {
+ last_v_num = num_vertices ;
+ last_i_num = num_indices ;
+
+ mMeshLOD[part_index++]->updateFaceSizes(num_vertices, num_indices, mAdjustedPixelArea);
+ }
+ if(num_vertices < 1)//skip empty meshes
+ {
+ continue ;
+ }
+ if(last_v_num > 0)//put the last inserted part into next vertex buffer.
+ {
+ num_vertices = last_v_num ;
+ num_indices = last_i_num ;
+ part_index-- ;
+ }
+
+ LLFace* facep ;
+ if(f_num < mDrawable->getNumFaces())
+ {
+ facep = mDrawable->getFace(f_num);
+ }
+ else
+ {
+ facep = mDrawable->addFace(mDrawable->getFace(0)->getPool(), mDrawable->getFace(0)->getTexture()) ;
+ }
+
+ // resize immediately
+ facep->setSize(num_vertices, num_indices);
+
+ bool terse_update = false;
+
+ facep->setGeomIndex(0);
+ facep->setIndicesIndex(0);
+
+ LLVertexBuffer* buff = facep->getVertexBuffer();
+ if(!facep->getVertexBuffer())
+ {
+ buff = new LLVertexBufferAvatar();
+ buff->allocateBuffer(num_vertices, num_indices, TRUE);
+ facep->setVertexBuffer(buff);
+ }
+ else
+ {
+ if (buff->getRequestedIndices() == num_indices &&
+ buff->getRequestedVerts() == num_vertices)
+ {
+ terse_update = true;
+ }
+ else
+ {
+ buff->resizeBuffer(num_vertices, num_indices);
+ }
+ }
+
+
+ // This is a hack! Avatars have their own pool, so we are detecting
+ // the case of more than one avatar in the pool (thus > 0 instead of >= 0)
+ if (facep->getGeomIndex() > 0)
+ {
+ llerrs << "non-zero geom index: " << facep->getGeomIndex() << " in LLVOAvatar::restoreMeshData" << llendl;
+ }
+
+ for(S32 k = j ; k < part_index ; k++)
+ {
+ mMeshLOD[k]->updateFaceData(facep, mAdjustedPixelArea, k == MESH_ID_HAIR, terse_update);
+ }
+
+ stop_glerror();
+ buff->setBuffer(0);
+
+ if(!f_num)
+ {
+ f_num += mNumInitFaces ;
+ }
+ else
+ {
+ f_num++ ;
+ }
+ }
+ }
+}
+
+//------------------------------------------------------------------------
+
+//------------------------------------------------------------------------
+// The viewer can only suggest a good size for the agent,
+// the simulator will keep it inside a reasonable range.
+void LLVOAvatar::computeBodySize()
+{
+ LLVector3 pelvis_scale = mPelvisp->getScale();
+
+ // some of the joints have not been cached
+ LLVector3 skull = mSkullp->getPosition();
+ LLVector3 skull_scale = mSkullp->getScale();
+
+ LLVector3 neck = mNeckp->getPosition();
+ LLVector3 neck_scale = mNeckp->getScale();
+
+ LLVector3 chest = mChestp->getPosition();
+ LLVector3 chest_scale = mChestp->getScale();
+
+ // the rest of the joints have been cached
+ LLVector3 head = mHeadp->getPosition();
+ LLVector3 head_scale = mHeadp->getScale();
+
+ LLVector3 torso = mTorsop->getPosition();
+ LLVector3 torso_scale = mTorsop->getScale();
+
+ LLVector3 hip = mHipLeftp->getPosition();
+ LLVector3 hip_scale = mHipLeftp->getScale();
+
+ LLVector3 knee = mKneeLeftp->getPosition();
+ LLVector3 knee_scale = mKneeLeftp->getScale();
+
+ LLVector3 ankle = mAnkleLeftp->getPosition();
+ LLVector3 ankle_scale = mAnkleLeftp->getScale();
+
+ LLVector3 foot = mFootLeftp->getPosition();
+
+ mPelvisToFoot = hip.mV[VZ] * pelvis_scale.mV[VZ] -
+ knee.mV[VZ] * hip_scale.mV[VZ] -
+ ankle.mV[VZ] * knee_scale.mV[VZ] -
+ foot.mV[VZ] * ankle_scale.mV[VZ];
+
+ LLVector3 new_body_size;
+ new_body_size.mV[VZ] = mPelvisToFoot +
+ // the sqrt(2) correction below is an approximate
+ // correction to get to the top of the head
+ F_SQRT2 * (skull.mV[VZ] * head_scale.mV[VZ]) +
+ head.mV[VZ] * neck_scale.mV[VZ] +
+ neck.mV[VZ] * chest_scale.mV[VZ] +
+ chest.mV[VZ] * torso_scale.mV[VZ] +
+ torso.mV[VZ] * pelvis_scale.mV[VZ];
+
+ // TODO -- measure the real depth and width
+ new_body_size.mV[VX] = DEFAULT_AGENT_DEPTH;
+ new_body_size.mV[VY] = DEFAULT_AGENT_WIDTH;
+
+ if (new_body_size != mBodySize)
+ {
+ mBodySize = new_body_size;
+
+ if (isSelf() && !LLAppearanceMgr::instance().isInUpdateAppearanceFromCOF())
+ { // notify simulator of change in size
+ // but not if we are in the middle of updating appearance
+ gAgent.sendAgentSetAppearance();
+ }
+ }
+}
+
+//------------------------------------------------------------------------
+// LLVOAvatar::processUpdateMessage()
+//------------------------------------------------------------------------
+U32 LLVOAvatar::processUpdateMessage(LLMessageSystem *mesgsys,
+ void **user_data,
+ U32 block_num, const EObjectUpdateType update_type,
+ LLDataPacker *dp)
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ LLVector3 old_vel = getVelocity();
+ const BOOL has_name = !getNVPair("FirstName");
+
+ // Do base class updates...
+ U32 retval = LLViewerObject::processUpdateMessage(mesgsys, user_data, block_num, update_type, dp);
+
+ // Print out arrival information once we have name of avatar.
+ if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
+ {
+ if (has_name && getNVPair("FirstName"))
+ {
+ mDebugExistenceTimer.reset();
+ LLSD args;
+ args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
+ args["NAME"] = getFullname();
+ LLNotificationsUtil::add("AvatarRezArrivedNotification",args);
+ llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' arrived." << llendl;
+ }
+ }
+ if(retval & LLViewerObject::INVALID_UPDATE)
+ {
+ if (isSelf())
+ {
+ //tell sim to cancel this update
+ gAgent.teleportViaLocation(gAgent.getPositionGlobal());
+ }
+ }
+
+ //llinfos << getRotation() << llendl;
+ //llinfos << getPosition() << llendl;
+
+ return retval;
+}
+
+// virtual
+S32 LLVOAvatar::setTETexture(const U8 te, const LLUUID& uuid)
+{
+ // The core setTETexture() method requests images, so we need
+ // to redirect certain avatar texture requests to different sims.
+ if (isIndexBakedTexture((ETextureIndex)te))
+ {
+ LLHost target_host = getObjectHost();
+ return setTETextureCore(te, uuid, target_host);
+ }
+ else
+ {
+ return setTETextureCore(te, uuid, LLHost::invalid);
+ }
+}
+
+static LLFastTimer::DeclareTimer FTM_AVATAR_UPDATE("Update Avatar");
+static LLFastTimer::DeclareTimer FTM_JOINT_UPDATE("Update Joints");
+
+//------------------------------------------------------------------------
+// LLVOAvatar::dumpAnimationState()
+//------------------------------------------------------------------------
+void LLVOAvatar::dumpAnimationState()
+{
+ llinfos << "==============================================" << llendl;
+ for (LLVOAvatar::AnimIterator it = mSignaledAnimations.begin(); it != mSignaledAnimations.end(); ++it)
+ {
+ LLUUID id = it->first;
+ std::string playtag = "";
+ if (mPlayingAnimations.find(id) != mPlayingAnimations.end())
+ {
+ playtag = "*";
+ }
+ llinfos << gAnimLibrary.animationName(id) << playtag << llendl;
+ }
+ for (LLVOAvatar::AnimIterator it = mPlayingAnimations.begin(); it != mPlayingAnimations.end(); ++it)
+ {
+ LLUUID id = it->first;
+ bool is_signaled = mSignaledAnimations.find(id) != mSignaledAnimations.end();
+ if (!is_signaled)
+ {
+ llinfos << gAnimLibrary.animationName(id) << "!S" << llendl;
+ }
+ }
+}
+
+//------------------------------------------------------------------------
+// idleUpdate()
+//------------------------------------------------------------------------
+BOOL LLVOAvatar::idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time)
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+ LLFastTimer t(FTM_AVATAR_UPDATE);
+
+ if (isDead())
+ {
+ llinfos << "Warning! Idle on dead avatar" << llendl;
+ return TRUE;
+ }
+
+ if (!(gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_AVATAR)))
+ {
+ return TRUE;
+ }
+
+ checkTextureLoading() ;
+
+ // force immediate pixel area update on avatars using last frames data (before drawable or camera updates)
+ setPixelAreaAndAngle(gAgent);
+
+ // force asynchronous drawable update
+ if(mDrawable.notNull() && !gNoRender)
+ {
+ LLFastTimer t(FTM_JOINT_UPDATE);
+
+ if (mIsSitting && getParent())
+ {
+ LLViewerObject *root_object = (LLViewerObject*)getRoot();
+ LLDrawable* drawablep = root_object->mDrawable;
+ // if this object hasn't already been updated by another avatar...
+ if (drawablep) // && !drawablep->isState(LLDrawable::EARLY_MOVE))
+ {
+ if (root_object->isSelected())
+ {
+ gPipeline.updateMoveNormalAsync(drawablep);
+ }
+ else
+ {
+ gPipeline.updateMoveDampedAsync(drawablep);
+ }
+ }
+ }
+ else
+ {
+ gPipeline.updateMoveDampedAsync(mDrawable);
+ }
+ }
+
+ //--------------------------------------------------------------------
+ // set alpha flag depending on state
+ //--------------------------------------------------------------------
+
+ if (isSelf())
+ {
+ LLViewerObject::idleUpdate(agent, world, time);
+
+ // trigger fidget anims
+ if (isAnyAnimationSignaled(AGENT_STAND_ANIMS, NUM_AGENT_STAND_ANIMS))
+ {
+ agent.fidget();
+ }
+ }
+ else
+ {
+ // Should override the idleUpdate stuff and leave out the angular update part.
+ LLQuaternion rotation = getRotation();
+ LLViewerObject::idleUpdate(agent, world, time);
+ setRotation(rotation);
+ }
+
+ // attach objects that were waiting for a drawable
+ lazyAttach();
+
+ // animate the character
+ // store off last frame's root position to be consistent with camera position
+ LLVector3 root_pos_last = mRoot.getWorldPosition();
+ BOOL detailed_update = updateCharacter(agent);
+
+ if (gNoRender)
+ {
+ return TRUE;
+ }
+
+ static LLUICachedControl<bool> visualizers_in_calls("ShowVoiceVisualizersInCalls", false);
+ bool voice_enabled = (visualizers_in_calls || LLVoiceClient::getInstance()->inProximalChannel()) &&
+ LLVoiceClient::getInstance()->getVoiceEnabled(mID);
+
+ idleUpdateVoiceVisualizer( voice_enabled );
+ idleUpdateMisc( detailed_update );
+ idleUpdateAppearanceAnimation();
+ if (detailed_update)
+ {
+ idleUpdateLipSync( voice_enabled );
+ idleUpdateLoadingEffect();
+ idleUpdateBelowWater(); // wind effect uses this
+ idleUpdateWindEffect();
+ }
+
+ idleUpdateNameTag( root_pos_last );
+ idleUpdateRenderCost();
+
+ return TRUE;
+}
+
+void LLVOAvatar::idleUpdateVoiceVisualizer(bool voice_enabled)
+{
+ bool render_visualizer = voice_enabled;
+
+ // Don't render the user's own voice visualizer when in mouselook, or when opening the mic is disabled.
+ if(isSelf())
+ {
+ if(gAgentCamera.cameraMouselook() || gSavedSettings.getBOOL("VoiceDisableMic"))
+ {
+ render_visualizer = false;
+ }
+ }
+
+ mVoiceVisualizer->setVoiceEnabled(render_visualizer);
+
+ if ( voice_enabled )
+ {
+ //----------------------------------------------------------------
+ // Only do gesture triggering for your own avatar, and only when you're in a proximal channel.
+ //----------------------------------------------------------------
+ if( isSelf() )
+ {
+ //----------------------------------------------------------------------------------------
+ // The following takes the voice signal and uses that to trigger gesticulations.
+ //----------------------------------------------------------------------------------------
+ int lastGesticulationLevel = mCurrentGesticulationLevel;
+ mCurrentGesticulationLevel = mVoiceVisualizer->getCurrentGesticulationLevel();
+
+ //---------------------------------------------------------------------------------------------------
+ // If "current gesticulation level" changes, we catch this, and trigger the new gesture
+ //---------------------------------------------------------------------------------------------------
+ if ( lastGesticulationLevel != mCurrentGesticulationLevel )
+ {
+ if ( mCurrentGesticulationLevel != VOICE_GESTICULATION_LEVEL_OFF )
+ {
+ std::string gestureString = "unInitialized";
+ if ( mCurrentGesticulationLevel == 0 ) { gestureString = "/voicelevel1"; }
+ else if ( mCurrentGesticulationLevel == 1 ) { gestureString = "/voicelevel2"; }
+ else if ( mCurrentGesticulationLevel == 2 ) { gestureString = "/voicelevel3"; }
+ else { llinfos << "oops - CurrentGesticulationLevel can be only 0, 1, or 2" << llendl; }
+
+ // this is the call that Karl S. created for triggering gestures from within the code.
+ LLGestureMgr::instance().triggerAndReviseString( gestureString );
+ }
+ }
+
+ } //if( isSelf() )
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // If the avatar is speaking, then the voice amplitude signal is passed to the voice visualizer.
+ // Also, here we trigger voice visualizer start and stop speaking, so it can animate the voice symbol.
+ //
+ // Notice the calls to "gAwayTimer.reset()". This resets the timer that determines how long the avatar has been
+ // "away", so that the avatar doesn't lapse into away-mode (and slump over) while the user is still talking.
+ //-----------------------------------------------------------------------------------------------------------------
+ if (LLVoiceClient::getInstance()->getIsSpeaking( mID ))
+ {
+ if (!mVoiceVisualizer->getCurrentlySpeaking())
+ {
+ mVoiceVisualizer->setStartSpeaking();
+
+ //printf( "gAwayTimer.reset();\n" );
+ }
+
+ mVoiceVisualizer->setSpeakingAmplitude( LLVoiceClient::getInstance()->getCurrentPower( mID ) );
+
+ if( isSelf() )
+ {
+ gAgent.clearAFK();
+ }
+ }
+ else
+ {
+ if ( mVoiceVisualizer->getCurrentlySpeaking() )
+ {
+ mVoiceVisualizer->setStopSpeaking();
+
+ if ( mLipSyncActive )
+ {
+ if( mOohMorph ) mOohMorph->setWeight(mOohMorph->getMinWeight(), FALSE);
+ if( mAahMorph ) mAahMorph->setWeight(mAahMorph->getMinWeight(), FALSE);
+
+ mLipSyncActive = false;
+ LLCharacter::updateVisualParams();
+ dirtyMesh();
+ }
+ }
+ }
+
+ //--------------------------------------------------------------------------------------------
+ // here we get the approximate head position and set as sound source for the voice symbol
+ // (the following version uses a tweak of "mHeadOffset" which handle sitting vs. standing)
+ //--------------------------------------------------------------------------------------------
+
+ if ( mIsSitting )
+ {
+ LLVector3 headOffset = LLVector3( 0.0f, 0.0f, mHeadOffset.mV[2] );
+ mVoiceVisualizer->setVoiceSourceWorldPosition( mRoot.getWorldPosition() + headOffset );
+ }
+ else
+ {
+ LLVector3 tagPos = mRoot.getWorldPosition();
+ tagPos[VZ] -= mPelvisToFoot;
+ tagPos[VZ] += ( mBodySize[VZ] + 0.125f );
+ mVoiceVisualizer->setVoiceSourceWorldPosition( tagPos );
+ }
+ }//if ( voiceEnabled )
+}
+
+static LLFastTimer::DeclareTimer FTM_ATTACHMENT_UPDATE("Update Attachments");
+
+void LLVOAvatar::idleUpdateMisc(bool detailed_update)
+{
+ if (LLVOAvatar::sJointDebug)
+ {
+ llinfos << getFullname() << ": joint touches: " << LLJoint::sNumTouches << " updates: " << LLJoint::sNumUpdates << llendl;
+ }
+
+ LLJoint::sNumUpdates = 0;
+ LLJoint::sNumTouches = 0;
+
+ BOOL visible = isVisible() || mNeedsAnimUpdate;
+
+ // update attachments positions
+ if (detailed_update || !sUseImpostors)
+ {
+ LLFastTimer t(FTM_ATTACHMENT_UPDATE);
+ for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+
+ for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
+ attachment_iter != attachment->mAttachedObjects.end();
+ ++attachment_iter)
+ {
+ LLViewerObject* attached_object = (*attachment_iter);
+ BOOL visibleAttachment = visible || (attached_object &&
+ !(attached_object->mDrawable->getSpatialBridge() &&
+ attached_object->mDrawable->getSpatialBridge()->getRadius() < 2.0));
+
+ if (visibleAttachment && attached_object && !attached_object->isDead() && attachment->getValid())
+ {
+ // if selecting any attachments, update all of them as non-damped
+ if (LLSelectMgr::getInstance()->getSelection()->getObjectCount() && LLSelectMgr::getInstance()->getSelection()->isAttachment())
+ {
+ gPipeline.updateMoveNormalAsync(attached_object->mDrawable);
+ }
+ else
+ {
+ gPipeline.updateMoveDampedAsync(attached_object->mDrawable);
+ }
+
+ LLSpatialBridge* bridge = attached_object->mDrawable->getSpatialBridge();
+ if (bridge)
+ {
+ gPipeline.updateMoveNormalAsync(bridge);
+ }
+ attached_object->updateText();
+ }
+ }
+ }
+ }
+
+ mNeedsAnimUpdate = FALSE;
+
+ if (isImpostor() && !mNeedsImpostorUpdate)
+ {
+ LLVector4a ext[2];
+ F32 distance;
+ LLVector3 angle;
+
+ getImpostorValues(ext, angle, distance);
+
+ for (U32 i = 0; i < 3 && !mNeedsImpostorUpdate; i++)
+ {
+ F32 cur_angle = angle.mV[i];
+ F32 old_angle = mImpostorAngle.mV[i];
+ F32 angle_diff = fabsf(cur_angle-old_angle);
+
+ if (angle_diff > F_PI/512.f*distance*mUpdatePeriod)
+ {
+ mNeedsImpostorUpdate = TRUE;
+ }
+ }
+
+ if (detailed_update && !mNeedsImpostorUpdate)
+ { //update impostor if view angle, distance, or bounding box change
+ //significantly
+
+ F32 dist_diff = fabsf(distance-mImpostorDistance);
+ if (dist_diff/mImpostorDistance > 0.1f)
+ {
+ mNeedsImpostorUpdate = TRUE;
+ }
+ else
+ {
+ //VECTORIZE THIS
+ getSpatialExtents(ext[0], ext[1]);
+ LLVector4a diff;
+ diff.setSub(ext[1], mImpostorExtents[1]);
+ if (diff.getLength3().getF32() > 0.05f)
+ {
+ mNeedsImpostorUpdate = TRUE;
+ }
+ else
+ {
+ diff.setSub(ext[0], mImpostorExtents[0]);
+ if (diff.getLength3().getF32() > 0.05f)
+ {
+ mNeedsImpostorUpdate = TRUE;
+ }
+ }
+ }
+ }
+ }
+
+ mDrawable->movePartition();
+
+ //force a move if sitting on an active object
+ if (getParent() && ((LLViewerObject*) getParent())->mDrawable->isActive())
+ {
+ gPipeline.markMoved(mDrawable, TRUE);
+ }
+}
+
+void LLVOAvatar::idleUpdateAppearanceAnimation()
+{
+ // update morphing params
+ if (mAppearanceAnimating)
+ {
+ ESex avatar_sex = getSex();
+ F32 appearance_anim_time = mAppearanceMorphTimer.getElapsedTimeF32();
+ if (appearance_anim_time >= APPEARANCE_MORPH_TIME)
+ {
+ mAppearanceAnimating = FALSE;
+ for (LLVisualParam *param = getFirstVisualParam();
+ param;
+ param = getNextVisualParam())
+ {
+ if (param->isTweakable())
+ {
+ param->stopAnimating(FALSE);
+ }
+ }
+ updateVisualParams();
+ if (isSelf())
+ {
+ gAgent.sendAgentSetAppearance();
+ }
+ }
+ else
+ {
+ F32 morph_amt = calcMorphAmount();
+ LLVisualParam *param;
+
+ if (!isSelf())
+ {
+ // animate only top level params for non-self avatars
+ for (param = getFirstVisualParam();
+ param;
+ param = getNextVisualParam())
+ {
+ if (param->isTweakable())
+ {
+ param->animate(morph_amt, FALSE);
+ }
+ }
+ }
+
+ // apply all params
+ for (param = getFirstVisualParam();
+ param;
+ param = getNextVisualParam())
+ {
+ param->apply(avatar_sex);
+ }
+
+ mLastAppearanceBlendTime = appearance_anim_time;
+ }
+ dirtyMesh();
+ }
+}
+
+F32 LLVOAvatar::calcMorphAmount()
+{
+ F32 appearance_anim_time = mAppearanceMorphTimer.getElapsedTimeF32();
+ F32 blend_frac = calc_bouncy_animation(appearance_anim_time / APPEARANCE_MORPH_TIME);
+ F32 last_blend_frac = calc_bouncy_animation(mLastAppearanceBlendTime / APPEARANCE_MORPH_TIME);
+
+ F32 morph_amt;
+ if (last_blend_frac == 1.f)
+ {
+ morph_amt = 1.f;
+ }
+ else
+ {
+ morph_amt = (blend_frac - last_blend_frac) / (1.f - last_blend_frac);
+ }
+
+ return morph_amt;
+}
+
+void LLVOAvatar::idleUpdateLipSync(bool voice_enabled)
+{
+ // Use the Lipsync_Ooh and Lipsync_Aah morphs for lip sync
+ if ( voice_enabled && (LLVoiceClient::getInstance()->lipSyncEnabled()) && LLVoiceClient::getInstance()->getIsSpeaking( mID ) )
+ {
+ F32 ooh_morph_amount = 0.0f;
+ F32 aah_morph_amount = 0.0f;
+
+ mVoiceVisualizer->lipSyncOohAah( ooh_morph_amount, aah_morph_amount );
+
+ if( mOohMorph )
+ {
+ F32 ooh_weight = mOohMorph->getMinWeight()
+ + ooh_morph_amount * (mOohMorph->getMaxWeight() - mOohMorph->getMinWeight());
+
+ mOohMorph->setWeight( ooh_weight, FALSE );
+ }
+
+ if( mAahMorph )
+ {
+ F32 aah_weight = mAahMorph->getMinWeight()
+ + aah_morph_amount * (mAahMorph->getMaxWeight() - mAahMorph->getMinWeight());
+
+ mAahMorph->setWeight( aah_weight, FALSE );
+ }
+
+ mLipSyncActive = true;
+ LLCharacter::updateVisualParams();
+ dirtyMesh();
+ }
+}
+
+void LLVOAvatar::idleUpdateLoadingEffect()
+{
+ // update visibility when avatar is partially loaded
+ if (updateIsFullyLoaded()) // changed?
+ {
+ if (isFullyLoaded() && isSelf())
+ {
+ static bool first_fully_visible = true;
+ if (first_fully_visible)
+ {
+ llinfos << "self isFullyLoaded, first_fully_visible" << llendl;
+
+ first_fully_visible = false;
+ LLAppearanceMgr::instance().onFirstFullyVisible();
+ }
+ }
+ if (isFullyLoaded())
+ {
+ deleteParticleSource();
+ updateLOD();
+ }
+ else
+ {
+ LLPartSysData particle_parameters;
+
+ // fancy particle cloud designed by Brent
+ particle_parameters.mPartData.mMaxAge = 4.f;
+ particle_parameters.mPartData.mStartScale.mV[VX] = 0.8f;
+ particle_parameters.mPartData.mStartScale.mV[VX] = 0.8f;
+ particle_parameters.mPartData.mStartScale.mV[VY] = 1.0f;
+ particle_parameters.mPartData.mEndScale.mV[VX] = 0.02f;
+ particle_parameters.mPartData.mEndScale.mV[VY] = 0.02f;
+ particle_parameters.mPartData.mStartColor = LLColor4(1, 1, 1, 0.5f);
+ particle_parameters.mPartData.mEndColor = LLColor4(1, 1, 1, 0.0f);
+ particle_parameters.mPartData.mStartScale.mV[VX] = 0.8f;
+ LLViewerTexture* cloud = LLViewerTextureManager::getFetchedTextureFromFile("cloud-particle.j2c");
+ particle_parameters.mPartImageID = cloud->getID();
+ particle_parameters.mMaxAge = 0.f;
+ particle_parameters.mPattern = LLPartSysData::LL_PART_SRC_PATTERN_ANGLE_CONE;
+ particle_parameters.mInnerAngle = F_PI;
+ particle_parameters.mOuterAngle = 0.f;
+ particle_parameters.mBurstRate = 0.02f;
+ particle_parameters.mBurstRadius = 0.0f;
+ particle_parameters.mBurstPartCount = 1;
+ particle_parameters.mBurstSpeedMin = 0.1f;
+ particle_parameters.mBurstSpeedMax = 1.f;
+ particle_parameters.mPartData.mFlags = ( LLPartData::LL_PART_INTERP_COLOR_MASK | LLPartData::LL_PART_INTERP_SCALE_MASK |
+ LLPartData::LL_PART_EMISSIVE_MASK | // LLPartData::LL_PART_FOLLOW_SRC_MASK |
+ LLPartData::LL_PART_TARGET_POS_MASK );
+
+ setParticleSource(particle_parameters, getID());
+ }
+ }
+}
+
+void LLVOAvatar::idleUpdateWindEffect()
+{
+ // update wind effect
+ if ((LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_AVATAR) >= LLDrawPoolAvatar::SHADER_LEVEL_CLOTH))
+ {
+ F32 hover_strength = 0.f;
+ F32 time_delta = mRippleTimer.getElapsedTimeF32() - mRippleTimeLast;
+ mRippleTimeLast = mRippleTimer.getElapsedTimeF32();
+ LLVector3 velocity = getVelocity();
+ F32 speed = velocity.length();
+ //RN: velocity varies too much frame to frame for this to work
+ mRippleAccel.clearVec();//lerp(mRippleAccel, (velocity - mLastVel) * time_delta, LLCriticalDamp::getInterpolant(0.02f));
+ mLastVel = velocity;
+ LLVector4 wind;
+ wind.setVec(getRegion()->mWind.getVelocityNoisy(getPositionAgent(), 4.f) - velocity);
+
+ if (mInAir)
+ {
+ hover_strength = HOVER_EFFECT_STRENGTH * llmax(0.f, HOVER_EFFECT_MAX_SPEED - speed);
+ }
+
+ if (mBelowWater)
+ {
+ // TODO: make cloth flow more gracefully when underwater
+ hover_strength += UNDERWATER_EFFECT_STRENGTH;
+ }
+
+ wind.mV[VZ] += hover_strength;
+ wind.normalize();
+
+ wind.mV[VW] = llmin(0.025f + (speed * 0.015f) + hover_strength, 0.5f);
+ F32 interp;
+ if (wind.mV[VW] > mWindVec.mV[VW])
+ {
+ interp = LLCriticalDamp::getInterpolant(0.2f);
+ }
+ else
+ {
+ interp = LLCriticalDamp::getInterpolant(0.4f);
+ }
+ mWindVec = lerp(mWindVec, wind, interp);
+
+ F32 wind_freq = hover_strength + llclamp(8.f + (speed * 0.7f) + (noise1(mRipplePhase) * 4.f), 8.f, 25.f);
+ mWindFreq = lerp(mWindFreq, wind_freq, interp);
+
+ if (mBelowWater)
+ {
+ mWindFreq *= UNDERWATER_FREQUENCY_DAMP;
+ }
+
+ mRipplePhase += (time_delta * mWindFreq);
+ if (mRipplePhase > F_TWO_PI)
+ {
+ mRipplePhase = fmodf(mRipplePhase, F_TWO_PI);
+ }
+ }
+}
+
+void LLVOAvatar::idleUpdateNameTag(const LLVector3& root_pos_last)
+{
+ // update chat bubble
+ //--------------------------------------------------------------------
+ // draw text label over character's head
+ //--------------------------------------------------------------------
+ if (mChatTimer.getElapsedTimeF32() > BUBBLE_CHAT_TIME)
+ {
+ mChats.clear();
+ }
+
+ const F32 time_visible = mTimeVisible.getElapsedTimeF32();
+ const F32 NAME_SHOW_TIME = gSavedSettings.getF32("RenderNameShowTime"); // seconds
+ const F32 FADE_DURATION = gSavedSettings.getF32("RenderNameFadeDuration"); // seconds
+ BOOL visible_avatar = isVisible() || mNeedsAnimUpdate;
+ BOOL visible_chat = gSavedSettings.getBOOL("UseChatBubbles") && (mChats.size() || mTyping);
+ BOOL render_name = visible_chat ||
+ (visible_avatar &&
+ ((sRenderName == RENDER_NAME_ALWAYS) ||
+ (sRenderName == RENDER_NAME_FADE && time_visible < NAME_SHOW_TIME)));
+ // If it's your own avatar, don't draw in mouselook, and don't
+ // draw if we're specifically hiding our own name.
+ if (isSelf())
+ {
+ render_name = render_name
+ && !gAgentCamera.cameraMouselook()
+ && (visible_chat || (gSavedSettings.getBOOL("RenderNameShowSelf")
+ && gSavedSettings.getS32("AvatarNameTagMode") ));
+ }
+
+ if ( !render_name )
+ {
+ if (mNameText)
+ {
+ // ...clean up old name tag
+ mNameText->markDead();
+ mNameText = NULL;
+ sNumVisibleChatBubbles--;
+ }
+ return;
+ }
+
+ BOOL new_name = FALSE;
+ if (visible_chat != mVisibleChat)
+ {
+ mVisibleChat = visible_chat;
+ new_name = TRUE;
+ }
+
+ if (sRenderGroupTitles != mRenderGroupTitles)
+ {
+ mRenderGroupTitles = sRenderGroupTitles;
+ new_name = TRUE;
+ }
+
+ // First Calculate Alpha
+ // If alpha > 0, create mNameText if necessary, otherwise delete it
+ F32 alpha = 0.f;
+ if (mAppAngle > 5.f)
+ {
+ const F32 START_FADE_TIME = NAME_SHOW_TIME - FADE_DURATION;
+ if (!visible_chat && sRenderName == RENDER_NAME_FADE && time_visible > START_FADE_TIME)
+ {
+ alpha = 1.f - (time_visible - START_FADE_TIME) / FADE_DURATION;
+ }
+ else
+ {
+ // ...not fading, full alpha
+ alpha = 1.f;
+ }
+ }
+ else if (mAppAngle > 2.f)
+ {
+ // far away is faded out also
+ alpha = (mAppAngle-2.f)/3.f;
+ }
+
+ if (alpha <= 0.f)
+ {
+ if (mNameText)
+ {
+ mNameText->markDead();
+ mNameText = NULL;
+ sNumVisibleChatBubbles--;
+ }
+ return;
+ }
+
+ if (!mNameText)
+ {
+ mNameText = static_cast<LLHUDNameTag*>( LLHUDObject::addHUDObject(
+ LLHUDObject::LL_HUD_NAME_TAG) );
+ //mNameText->setMass(10.f);
+ mNameText->setSourceObject(this);
+ mNameText->setVertAlignment(LLHUDNameTag::ALIGN_VERT_TOP);
+ mNameText->setVisibleOffScreen(TRUE);
+ mNameText->setMaxLines(11);
+ mNameText->setFadeDistance(CHAT_NORMAL_RADIUS, 5.f);
+ sNumVisibleChatBubbles++;
+ new_name = TRUE;
+ }
+
+ LLVector3 name_position = idleUpdateNameTagPosition(root_pos_last);
+ mNameText->setPositionAgent(name_position);
+ idleUpdateNameTagText(new_name);
+ idleUpdateNameTagAlpha(new_name, alpha);
+}
+
+void LLVOAvatar::idleUpdateNameTagText(BOOL new_name)
+ {
+ LLNameValue *title = getNVPair("Title");
+ LLNameValue* firstname = getNVPair("FirstName");
+ LLNameValue* lastname = getNVPair("LastName");
+
+ // Avatars must have a first and last name
+ if (!firstname || !lastname) return;
+
+ bool is_away = mSignaledAnimations.find(ANIM_AGENT_AWAY) != mSignaledAnimations.end();
+ bool is_busy = mSignaledAnimations.find(ANIM_AGENT_BUSY) != mSignaledAnimations.end();
+ bool is_appearance = mSignaledAnimations.find(ANIM_AGENT_CUSTOMIZE) != mSignaledAnimations.end();
+ bool is_muted;
+ if (isSelf())
+ {
+ is_muted = false;
+ }
+ else
+ {
+ is_muted = LLMuteList::getInstance()->isMuted(getID());
+ }
+ bool is_friend = LLAvatarTracker::instance().isBuddy(getID());
+ bool is_cloud = getIsCloud();
+
+ if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
+ {
+ if (is_appearance != mNameAppearance)
+ {
+ if (is_appearance)
+ {
+ LLSD args;
+ args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
+ args["NAME"] = getFullname();
+ LLNotificationsUtil::add("AvatarRezEnteredAppearanceNotification",args);
+ llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' entered appearance mode." << llendl;
+ }
+ else
+ {
+ LLSD args;
+ args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
+ args["NAME"] = getFullname();
+ LLNotificationsUtil::add("AvatarRezLeftAppearanceNotification",args);
+ llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' left appearance mode." << llendl;
+ }
+ }
+ }
+
+ // Rebuild name tag if state change detected
+ if (mNameString.empty()
+ || new_name
+ || (!title && !mTitle.empty())
+ || (title && mTitle != title->getString())
+ || is_away != mNameAway
+ || is_busy != mNameBusy
+ || is_muted != mNameMute
+ || is_appearance != mNameAppearance
+ || is_friend != mNameFriend
+ || is_cloud != mNameCloud)
+ {
+ LLColor4 name_tag_color = getNameTagColor(is_friend);
+
+ clearNameTag();
+
+ if (is_away || is_muted || is_busy || is_appearance)
+ {
+ std::string line;
+ if (is_away)
+ {
+ line += LLTrans::getString("AvatarAway");
+ line += ", ";
+ }
+ if (is_busy)
+ {
+ line += LLTrans::getString("AvatarBusy");
+ line += ", ";
+ }
+ if (is_muted)
+ {
+ line += LLTrans::getString("AvatarMuted");
+ line += ", ";
+ }
+ if (is_appearance)
+ {
+ line += LLTrans::getString("AvatarEditingAppearance");
+ line += ", ";
+ }
+ if (is_cloud)
+ {
+ line += LLTrans::getString("LoadingData");
+ line += ", ";
+ }
+ // trim last ", "
+ line.resize( line.length() - 2 );
+ addNameTagLine(line, name_tag_color, LLFontGL::NORMAL,
+ LLFontGL::getFontSansSerifSmall());
+ }
+
+ if (sRenderGroupTitles
+ && title && title->getString() && title->getString()[0] != '\0')
+ {
+ std::string title_str = title->getString();
+ LLStringFn::replace_ascii_controlchars(title_str,LL_UNKNOWN_CHAR);
+ addNameTagLine(title_str, name_tag_color, LLFontGL::NORMAL,
+ LLFontGL::getFontSansSerifSmall());
+ }
+
+ static LLUICachedControl<bool> show_display_names("NameTagShowDisplayNames");
+ static LLUICachedControl<bool> show_usernames("NameTagShowUsernames");
+
+ if (LLAvatarNameCache::useDisplayNames())
+ {
+ LLAvatarName av_name;
+ if (!LLAvatarNameCache::get(getID(), &av_name))
+ {
+ // ...call this function back when the name arrives
+ // and force a rebuild
+ LLAvatarNameCache::get(getID(),
+ boost::bind(&LLVOAvatar::clearNameTag, this));
+ }
+
+ // Might be blank if name not available yet, that's OK
+ if (show_display_names)
+ {
+ addNameTagLine(av_name.mDisplayName, name_tag_color, LLFontGL::NORMAL,
+ LLFontGL::getFontSansSerif());
+ }
+ // Suppress SLID display if display name matches exactly (ugh)
+ if (show_usernames && !av_name.mIsDisplayNameDefault)
+ {
+ // *HACK: Desaturate the color
+ LLColor4 username_color = name_tag_color * 0.83f;
+ addNameTagLine(av_name.mUsername, username_color, LLFontGL::NORMAL,
+ LLFontGL::getFontSansSerifSmall());
+ }
+ }
+ else
+ {
+ const LLFontGL* font = LLFontGL::getFontSansSerif();
+ std::string full_name =
+ LLCacheName::buildFullName( firstname->getString(), lastname->getString() );
+ addNameTagLine(full_name, name_tag_color, LLFontGL::NORMAL, font);
+ }
+
+ mNameAway = is_away;
+ mNameBusy = is_busy;
+ mNameMute = is_muted;
+ mNameAppearance = is_appearance;
+ mNameFriend = is_friend;
+ mNameCloud = is_cloud;
+ mTitle = title ? title->getString() : "";
+ LLStringFn::replace_ascii_controlchars(mTitle,LL_UNKNOWN_CHAR);
+ new_name = TRUE;
+ }
+
+ if (mVisibleChat)
+ {
+ mNameText->setFont(LLFontGL::getFontSansSerif());
+ mNameText->setTextAlignment(LLHUDNameTag::ALIGN_TEXT_LEFT);
+ mNameText->setFadeDistance(CHAT_NORMAL_RADIUS * 2.f, 5.f);
+
+ char line[MAX_STRING]; /* Flawfinder: ignore */
+ line[0] = '\0';
+ std::deque<LLChat>::iterator chat_iter = mChats.begin();
+ mNameText->clearString();
+
+ LLColor4 new_chat = LLUIColorTable::instance().getColor( isSelf() ? "UserChatColor" : "AgentChatColor" );
+ LLColor4 normal_chat = lerp(new_chat, LLColor4(0.8f, 0.8f, 0.8f, 1.f), 0.7f);
+ LLColor4 old_chat = lerp(normal_chat, LLColor4(0.6f, 0.6f, 0.6f, 1.f), 0.7f);
+ if (mTyping && mChats.size() >= MAX_BUBBLE_CHAT_UTTERANCES)
+ {
+ ++chat_iter;
+ }
+
+ for(; chat_iter != mChats.end(); ++chat_iter)
+ {
+ F32 chat_fade_amt = llclamp((F32)((LLFrameTimer::getElapsedSeconds() - chat_iter->mTime) / CHAT_FADE_TIME), 0.f, 4.f);
+ LLFontGL::StyleFlags style;
+ switch(chat_iter->mChatType)
+ {
+ case CHAT_TYPE_WHISPER:
+ style = LLFontGL::ITALIC;
+ break;
+ case CHAT_TYPE_SHOUT:
+ style = LLFontGL::BOLD;
+ break;
+ default:
+ style = LLFontGL::NORMAL;
+ break;
+ }
+ if (chat_fade_amt < 1.f)
+ {
+ F32 u = clamp_rescale(chat_fade_amt, 0.9f, 1.f, 0.f, 1.f);
+ mNameText->addLine(chat_iter->mText, lerp(new_chat, normal_chat, u), style);
+ }
+ else if (chat_fade_amt < 2.f)
+ {
+ F32 u = clamp_rescale(chat_fade_amt, 1.9f, 2.f, 0.f, 1.f);
+ mNameText->addLine(chat_iter->mText, lerp(normal_chat, old_chat, u), style);
+ }
+ else if (chat_fade_amt < 3.f)
+ {
+ // *NOTE: only remove lines down to minimum number
+ mNameText->addLine(chat_iter->mText, old_chat, style);
+ }
+ }
+ mNameText->setVisibleOffScreen(TRUE);
+
+ if (mTyping)
+ {
+ S32 dot_count = (llfloor(mTypingTimer.getElapsedTimeF32() * 3.f) + 2) % 3 + 1;
+ switch(dot_count)
+ {
+ case 1:
+ mNameText->addLine(".", new_chat);
+ break;
+ case 2:
+ mNameText->addLine("..", new_chat);
+ break;
+ case 3:
+ mNameText->addLine("...", new_chat);
+ break;
+ }
+
+ }
+ }
+ else
+ {
+ // ...not using chat bubbles, just names
+ mNameText->setTextAlignment(LLHUDNameTag::ALIGN_TEXT_CENTER);
+ mNameText->setFadeDistance(CHAT_NORMAL_RADIUS, 5.f);
+ mNameText->setVisibleOffScreen(FALSE);
+ }
+}
+
+void LLVOAvatar::addNameTagLine(const std::string& line, const LLColor4& color, S32 style, const LLFontGL* font)
+{
+ llassert(mNameText);
+ if (mVisibleChat)
+ {
+ mNameText->addLabel(line);
+ }
+ else
+ {
+ mNameText->addLine(line, color, (LLFontGL::StyleFlags)style, font);
+ }
+ mNameString += line;
+ mNameString += '\n';
+}
+
+void LLVOAvatar::clearNameTag()
+{
+ mNameString.clear();
+ if (mNameText)
+ {
+ mNameText->setLabel("");
+ mNameText->setString( "" );
+ }
+}
+
+//static
+void LLVOAvatar::invalidateNameTag(const LLUUID& agent_id)
+{
+ LLViewerObject* obj = gObjectList.findObject(agent_id);
+ if (!obj) return;
+
+ LLVOAvatar* avatar = dynamic_cast<LLVOAvatar*>(obj);
+ if (!avatar) return;
+
+ avatar->clearNameTag();
+}
+
+//static
+void LLVOAvatar::invalidateNameTags()
+{
+ std::vector<LLCharacter*>::iterator it = LLCharacter::sInstances.begin();
+ for ( ; it != LLCharacter::sInstances.end(); ++it)
+ {
+ LLVOAvatar* avatar = dynamic_cast<LLVOAvatar*>(*it);
+ if (!avatar) continue;
+ if (avatar->isDead()) continue;
+
+ avatar->clearNameTag();
+
+ }
+}
+
+// Compute name tag position during idle update
+LLVector3 LLVOAvatar::idleUpdateNameTagPosition(const LLVector3& root_pos_last)
+{
+ LLQuaternion root_rot = mRoot.getWorldRotation();
+ LLVector3 pixel_right_vec;
+ LLVector3 pixel_up_vec;
+ LLViewerCamera::getInstance()->getPixelVectors(root_pos_last, pixel_up_vec, pixel_right_vec);
+ LLVector3 camera_to_av = root_pos_last - LLViewerCamera::getInstance()->getOrigin();
+ camera_to_av.normalize();
+ LLVector3 local_camera_at = camera_to_av * ~root_rot;
+ LLVector3 local_camera_up = camera_to_av % LLViewerCamera::getInstance()->getLeftAxis();
+ local_camera_up.normalize();
+ local_camera_up = local_camera_up * ~root_rot;
+
+ local_camera_up.scaleVec(mBodySize * 0.5f);
+ local_camera_at.scaleVec(mBodySize * 0.5f);
+
+ LLVector3 name_position = mRoot.getWorldPosition();
+ name_position[VZ] -= mPelvisToFoot;
+ name_position[VZ] += (mBodySize[VZ]* 0.55f);
+ name_position += (local_camera_up * root_rot) - (projected_vec(local_camera_at * root_rot, camera_to_av));
+ name_position += pixel_up_vec * 15.f;
+
+ return name_position;
+}
+
+void LLVOAvatar::idleUpdateNameTagAlpha(BOOL new_name, F32 alpha)
+{
+ llassert(mNameText);
+
+ if (new_name
+ || alpha != mNameAlpha)
+ {
+ mNameText->setAlpha(alpha);
+ mNameAlpha = alpha;
+ }
+}
+
+LLColor4 LLVOAvatar::getNameTagColor(bool is_friend)
+{
+ static LLUICachedControl<bool> show_friends("NameTagShowFriends");
+ const char* color_name;
+ if (show_friends && is_friend)
+ {
+ color_name = "NameTagFriend";
+ }
+ else if (LLAvatarNameCache::useDisplayNames())
+ {
+ // ...color based on whether username "matches" a computed display
+ // name
+ LLAvatarName av_name;
+ if (LLAvatarNameCache::get(getID(), &av_name)
+ && av_name.mIsDisplayNameDefault)
+ {
+ color_name = "NameTagMatch";
+ }
+ else
+ {
+ color_name = "NameTagMismatch";
+ }
+ }
+ else
+ {
+ // ...not using display names
+ color_name = "NameTagLegacy";
+ }
+ return LLUIColorTable::getInstance()->getColor( color_name );
+}
+
+void LLVOAvatar::idleUpdateBelowWater()
+{
+ F32 avatar_height = (F32)(getPositionGlobal().mdV[VZ]);
+
+ F32 water_height;
+ water_height = getRegion()->getWaterHeight();
+
+ mBelowWater = avatar_height < water_height;
+}
+
+void LLVOAvatar::slamPosition()
+{
+ gAgent.setPositionAgent(getPositionAgent());
+ mRoot.setWorldPosition(getPositionAgent()); // teleport
+ setChanged(TRANSLATED);
+ if (mDrawable.notNull())
+ {
+ gPipeline.updateMoveNormalAsync(mDrawable);
+ }
+ mRoot.updateWorldMatrixChildren();
+}
+
+//------------------------------------------------------------------------
+// updateCharacter()
+// called on both your avatar and other avatars
+//------------------------------------------------------------------------
+BOOL LLVOAvatar::updateCharacter(LLAgent &agent)
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ // clear debug text
+ mDebugText.clear();
+ if (LLVOAvatar::sShowAnimationDebug)
+ {
+ for (LLMotionController::motion_list_t::iterator iter = mMotionController.getActiveMotions().begin();
+ iter != mMotionController.getActiveMotions().end(); ++iter)
+ {
+ LLMotion* motionp = *iter;
+ if (motionp->getMinPixelArea() < getPixelArea())
+ {
+ std::string output;
+ if (motionp->getName().empty())
+ {
+ output = llformat("%s - %d",
+ gAgent.isGodlikeWithoutAdminMenuFakery() ?
+ motionp->getID().asString().c_str() :
+ LLUUID::null.asString().c_str(),
+ (U32)motionp->getPriority());
+ }
+ else
+ {
+ output = llformat("%s - %d",
+ motionp->getName().c_str(),
+ (U32)motionp->getPriority());
+ }
+ addDebugText(output);
+ }
+ }
+ }
+
+ if (gNoRender)
+ {
+ // Hack if we're running drones...
+ if (isSelf())
+ {
+ gAgent.setPositionAgent(getPositionAgent());
+ }
+ return FALSE;
+ }
+
+
+ LLVector3d root_pos_global;
+
+ if (!mIsBuilt)
+ {
+ return FALSE;
+ }
+
+ BOOL visible = isVisible();
+
+ // For fading out the names above heads, only let the timer
+ // run if we're visible.
+ if (mDrawable.notNull() && !visible)
+ {
+ mTimeVisible.reset();
+ }
+
+
+ //--------------------------------------------------------------------
+ // the rest should only be done occasionally for far away avatars
+ //--------------------------------------------------------------------
+
+ if (visible && !isSelf() && !mIsDummy && sUseImpostors && !mNeedsAnimUpdate && !sFreezeCounter)
+ {
+ const LLVector4a* ext = mDrawable->getSpatialExtents();
+ LLVector4a size;
+ size.setSub(ext[1],ext[0]);
+ F32 mag = size.getLength3().getF32()*0.5f;
+
+ F32 impostor_area = 256.f*512.f*(8.125f - LLVOAvatar::sLODFactor*8.f);
+ if (LLMuteList::getInstance()->isMuted(getID()))
+ { // muted avatars update at 16 hz
+ mUpdatePeriod = 16;
+ }
+ else if (mVisibilityRank <= LLVOAvatar::sMaxVisible ||
+ mDrawable->mDistanceWRTCamera < 1.f + mag)
+ { //first 25% of max visible avatars are not impostored
+ //also, don't impostor avatars whose bounding box may be penetrating the
+ //impostor camera near clip plane
+ mUpdatePeriod = 1;
+ }
+ else if (mVisibilityRank > LLVOAvatar::sMaxVisible * 4)
+ { //background avatars are REALLY slow updating impostors
+ mUpdatePeriod = 16;
+ }
+ else if (mVisibilityRank > LLVOAvatar::sMaxVisible * 3)
+ { //back 25% of max visible avatars are slow updating impostors
+ mUpdatePeriod = 8;
+ }
+ else if (mImpostorPixelArea <= impostor_area)
+ { // stuff in between gets an update period based on pixel area
+ mUpdatePeriod = llclamp((S32) sqrtf(impostor_area*4.f/mImpostorPixelArea), 2, 8);
+ }
+ else
+ {
+ //nearby avatars, update the impostors more frequently.
+ mUpdatePeriod = 4;
+ }
+
+ visible = (LLDrawable::getCurrentFrame()+mID.mData[0])%mUpdatePeriod == 0 ? TRUE : FALSE;
+ }
+
+ // don't early out for your own avatar, as we rely on your animations playing reliably
+ // for example, the "turn around" animation when entering customize avatar needs to trigger
+ // even when your avatar is offscreen
+ if (!visible && !isSelf())
+ {
+ updateMotions(LLCharacter::HIDDEN_UPDATE);
+ return FALSE;
+ }
+
+ // change animation time quanta based on avatar render load
+ if (!isSelf() && !mIsDummy)
+ {
+ F32 time_quantum = clamp_rescale((F32)sInstances.size(), 10.f, 35.f, 0.f, 0.25f);
+ F32 pixel_area_scale = clamp_rescale(mPixelArea, 100, 5000, 1.f, 0.f);
+ F32 time_step = time_quantum * pixel_area_scale;
+ if (time_step != 0.f)
+ {
+ // disable walk motion servo controller as it doesn't work with motion timesteps
+ stopMotion(ANIM_AGENT_WALK_ADJUST);
+ removeAnimationData("Walk Speed");
+ }
+ mMotionController.setTimeStep(time_step);
+// llinfos << "Setting timestep to " << time_quantum * pixel_area_scale << llendl;
+ }
+
+ if (getParent() && !mIsSitting)
+ {
+ sitOnObject((LLViewerObject*)getParent());
+ }
+ else if (!getParent() && mIsSitting && !isMotionActive(ANIM_AGENT_SIT_GROUND_CONSTRAINED))
+ {
+ getOffObject();
+ }
+
+ //--------------------------------------------------------------------
+ // create local variables in world coords for region position values
+ //--------------------------------------------------------------------
+ F32 speed;
+ LLVector3 normal;
+
+ LLVector3 xyVel = getVelocity();
+ xyVel.mV[VZ] = 0.0f;
+ speed = xyVel.length();
+
+ BOOL throttle = TRUE;
+
+ if (!(mIsSitting && getParent()))
+ {
+ //--------------------------------------------------------------------
+ // get timing info
+ // handle initial condition case
+ //--------------------------------------------------------------------
+ F32 animation_time = mAnimTimer.getElapsedTimeF32();
+ if (mTimeLast == 0.0f)
+ {
+ mTimeLast = animation_time;
+ throttle = FALSE;
+
+ // put the pelvis at slaved position/mRotation
+ mRoot.setWorldPosition( getPositionAgent() ); // first frame
+ mRoot.setWorldRotation( getRotation() );
+ }
+
+ //--------------------------------------------------------------------
+ // dont' let dT get larger than 1/5th of a second
+ //--------------------------------------------------------------------
+ F32 deltaTime = animation_time - mTimeLast;
+
+ deltaTime = llclamp( deltaTime, DELTA_TIME_MIN, DELTA_TIME_MAX );
+ mTimeLast = animation_time;
+
+ mSpeedAccum = (mSpeedAccum * 0.95f) + (speed * 0.05f);
+
+ //--------------------------------------------------------------------
+ // compute the position of the avatar's root
+ //--------------------------------------------------------------------
+ LLVector3d root_pos;
+ LLVector3d ground_under_pelvis;
+
+ if (isSelf())
+ {
+ gAgent.setPositionAgent(getRenderPosition());
+ }
+
+ root_pos = gAgent.getPosGlobalFromAgent(getRenderPosition());
+
+ resolveHeightGlobal(root_pos, ground_under_pelvis, normal);
+ F32 foot_to_ground = (F32) (root_pos.mdV[VZ] - mPelvisToFoot - ground_under_pelvis.mdV[VZ]);
+ BOOL in_air = ((!LLWorld::getInstance()->getRegionFromPosGlobal(ground_under_pelvis)) ||
+ foot_to_ground > FOOT_GROUND_COLLISION_TOLERANCE);
+
+ if (in_air && !mInAir)
+ {
+ mTimeInAir.reset();
+ }
+ mInAir = in_air;
+
+ // correct for the fact that the pelvis is not necessarily the center
+ // of the agent's physical representation
+ root_pos.mdV[VZ] -= (0.5f * mBodySize.mV[VZ]) - mPelvisToFoot;
+
+ LLVector3 newPosition = gAgent.getPosAgentFromGlobal(root_pos);
+
+ if (newPosition != mRoot.getXform()->getWorldPosition())
+ {
+ mRoot.touch();
+ mRoot.setWorldPosition( newPosition ); // regular update
+ }
+
+
+ //--------------------------------------------------------------------
+ // Propagate viewer object rotation to root of avatar
+ //--------------------------------------------------------------------
+ if (!isAnyAnimationSignaled(AGENT_NO_ROTATE_ANIMS, NUM_AGENT_NO_ROTATE_ANIMS))
+ {
+ LLQuaternion iQ;
+ LLVector3 upDir( 0.0f, 0.0f, 1.0f );
+
+ // Compute a forward direction vector derived from the primitive rotation
+ // and the velocity vector. When walking or jumping, don't let body deviate
+ // more than 90 from the view, if necessary, flip the velocity vector.
+
+ LLVector3 primDir;
+ if (isSelf())
+ {
+ primDir = agent.getAtAxis() - projected_vec(agent.getAtAxis(), agent.getReferenceUpVector());
+ primDir.normalize();
+ }
+ else
+ {
+ primDir = getRotation().getMatrix3().getFwdRow();
+ }
+ LLVector3 velDir = getVelocity();
+ velDir.normalize();
+ if ( mSignaledAnimations.find(ANIM_AGENT_WALK) != mSignaledAnimations.end())
+ {
+ F32 vpD = velDir * primDir;
+ if (vpD < -0.5f)
+ {
+ velDir *= -1.0f;
+ }
+ }
+ LLVector3 fwdDir = lerp(primDir, velDir, clamp_rescale(speed, 0.5f, 2.0f, 0.0f, 1.0f));
+ if (isSelf() && gAgentCamera.cameraMouselook())
+ {
+ // make sure fwdDir stays in same general direction as primdir
+ if (gAgent.getFlying())
+ {
+ fwdDir = LLViewerCamera::getInstance()->getAtAxis();
+ }
+ else
+ {
+ LLVector3 at_axis = LLViewerCamera::getInstance()->getAtAxis();
+ LLVector3 up_vector = gAgent.getReferenceUpVector();
+ at_axis -= up_vector * (at_axis * up_vector);
+ at_axis.normalize();
+
+ F32 dot = fwdDir * at_axis;
+ if (dot < 0.f)
+ {
+ fwdDir -= 2.f * at_axis * dot;
+ fwdDir.normalize();
+ }
+ }
+
+ }
+
+ LLQuaternion root_rotation = mRoot.getWorldMatrix().quaternion();
+ F32 root_roll, root_pitch, root_yaw;
+ root_rotation.getEulerAngles(&root_roll, &root_pitch, &root_yaw);
+
+ // When moving very slow, the pelvis is allowed to deviate from the
+ // forward direction to allow it to hold it's position while the torso
+ // and head turn. Once in motion, it must conform however.
+ BOOL self_in_mouselook = isSelf() && gAgentCamera.cameraMouselook();
+
+ LLVector3 pelvisDir( mRoot.getWorldMatrix().getFwdRow4().mV );
+ F32 pelvis_rot_threshold = clamp_rescale(speed, 0.1f, 1.0f, PELVIS_ROT_THRESHOLD_SLOW, PELVIS_ROT_THRESHOLD_FAST);
+
+ if (self_in_mouselook)
+ {
+ pelvis_rot_threshold *= MOUSELOOK_PELVIS_FOLLOW_FACTOR;
+ }
+ pelvis_rot_threshold *= DEG_TO_RAD;
+
+ F32 angle = angle_between( pelvisDir, fwdDir );
+
+ // The avatar's root is allowed to have a yaw that deviates widely
+ // from the forward direction, but if roll or pitch are off even
+ // a little bit we need to correct the rotation.
+ if(root_roll < 1.f * DEG_TO_RAD
+ && root_pitch < 5.f * DEG_TO_RAD)
+ {
+ // smaller correction vector means pelvis follows prim direction more closely
+ if (!mTurning && angle > pelvis_rot_threshold*0.75f)
+ {
+ mTurning = TRUE;
+ }
+
+ // use tighter threshold when turning
+ if (mTurning)
+ {
+ pelvis_rot_threshold *= 0.4f;
+ }
+
+ // am I done turning?
+ if (angle < pelvis_rot_threshold)
+ {
+ mTurning = FALSE;
+ }
+
+ LLVector3 correction_vector = (pelvisDir - fwdDir) * clamp_rescale(angle, pelvis_rot_threshold*0.75f, pelvis_rot_threshold, 1.0f, 0.0f);
+ fwdDir += correction_vector;
+ }
+ else
+ {
+ mTurning = FALSE;
+ }
+
+ // Now compute the full world space rotation for the whole body (wQv)
+ LLVector3 leftDir = upDir % fwdDir;
+ leftDir.normalize();
+ fwdDir = leftDir % upDir;
+ LLQuaternion wQv( fwdDir, leftDir, upDir );
+
+ if (isSelf() && mTurning)
+ {
+ if ((fwdDir % pelvisDir) * upDir > 0.f)
+ {
+ gAgent.setControlFlags(AGENT_CONTROL_TURN_RIGHT);
+ }
+ else
+ {
+ gAgent.setControlFlags(AGENT_CONTROL_TURN_LEFT);
+ }
+ }
+
+ // Set the root rotation, but do so incrementally so that it
+ // lags in time by some fixed amount.
+ //F32 u = LLCriticalDamp::getInterpolant(PELVIS_LAG);
+ F32 pelvis_lag_time = 0.f;
+ if (self_in_mouselook)
+ {
+ pelvis_lag_time = PELVIS_LAG_MOUSELOOK;
+ }
+ else if (mInAir)
+ {
+ pelvis_lag_time = PELVIS_LAG_FLYING;
+ // increase pelvis lag time when moving slowly
+ pelvis_lag_time *= clamp_rescale(mSpeedAccum, 0.f, 15.f, 3.f, 1.f);
+ }
+ else
+ {
+ pelvis_lag_time = PELVIS_LAG_WALKING;
+ }
+
+ F32 u = llclamp((deltaTime / pelvis_lag_time), 0.0f, 1.0f);
+
+ mRoot.setWorldRotation( slerp(u, mRoot.getWorldRotation(), wQv) );
+
+ }
+ }
+ else if (mDrawable.notNull())
+ {
+ mRoot.setPosition(mDrawable->getPosition());
+ mRoot.setRotation(mDrawable->getRotation());
+ }
+
+ //-------------------------------------------------------------------------
+ // Update character motions
+ //-------------------------------------------------------------------------
+ // store data relevant to motions
+ mSpeed = speed;
+
+ // update animations
+ if (mSpecialRenderMode == 1) // Animation Preview
+ updateMotions(LLCharacter::FORCE_UPDATE);
+ else
+ updateMotions(LLCharacter::NORMAL_UPDATE);
+
+ // update head position
+ updateHeadOffset();
+
+ //-------------------------------------------------------------------------
+ // Find the ground under each foot, these are used for a variety
+ // of things that follow
+ //-------------------------------------------------------------------------
+ LLVector3 ankle_left_pos_agent = mFootLeftp->getWorldPosition();
+ LLVector3 ankle_right_pos_agent = mFootRightp->getWorldPosition();
+
+ LLVector3 ankle_left_ground_agent = ankle_left_pos_agent;
+ LLVector3 ankle_right_ground_agent = ankle_right_pos_agent;
+ resolveHeightAgent(ankle_left_pos_agent, ankle_left_ground_agent, normal);
+ resolveHeightAgent(ankle_right_pos_agent, ankle_right_ground_agent, normal);
+
+ F32 leftElev = llmax(-0.2f, ankle_left_pos_agent.mV[VZ] - ankle_left_ground_agent.mV[VZ]);
+ F32 rightElev = llmax(-0.2f, ankle_right_pos_agent.mV[VZ] - ankle_right_ground_agent.mV[VZ]);
+
+ if (!mIsSitting)
+ {
+ //-------------------------------------------------------------------------
+ // Figure out which foot is on ground
+ //-------------------------------------------------------------------------
+ if (!mInAir)
+ {
+ if ((leftElev < 0.0f) || (rightElev < 0.0f))
+ {
+ ankle_left_pos_agent = mFootLeftp->getWorldPosition();
+ ankle_right_pos_agent = mFootRightp->getWorldPosition();
+ leftElev = ankle_left_pos_agent.mV[VZ] - ankle_left_ground_agent.mV[VZ];
+ rightElev = ankle_right_pos_agent.mV[VZ] - ankle_right_ground_agent.mV[VZ];
+ }
+ }
+ }
+
+ //-------------------------------------------------------------------------
+ // Generate footstep sounds when feet hit the ground
+ //-------------------------------------------------------------------------
+ const LLUUID AGENT_FOOTSTEP_ANIMS[] = {ANIM_AGENT_WALK, ANIM_AGENT_RUN, ANIM_AGENT_LAND};
+ const S32 NUM_AGENT_FOOTSTEP_ANIMS = LL_ARRAY_SIZE(AGENT_FOOTSTEP_ANIMS);
+
+ if ( gAudiop && isAnyAnimationSignaled(AGENT_FOOTSTEP_ANIMS, NUM_AGENT_FOOTSTEP_ANIMS) )
+ {
+ BOOL playSound = FALSE;
+ LLVector3 foot_pos_agent;
+
+ BOOL onGroundLeft = (leftElev <= 0.05f);
+ BOOL onGroundRight = (rightElev <= 0.05f);
+
+ // did left foot hit the ground?
+ if ( onGroundLeft && !mWasOnGroundLeft )
+ {
+ foot_pos_agent = ankle_left_pos_agent;
+ playSound = TRUE;
+ }
+
+ // did right foot hit the ground?
+ if ( onGroundRight && !mWasOnGroundRight )
+ {
+ foot_pos_agent = ankle_right_pos_agent;
+ playSound = TRUE;
+ }
+
+ mWasOnGroundLeft = onGroundLeft;
+ mWasOnGroundRight = onGroundRight;
+
+ if ( playSound )
+ {
+// F32 gain = clamp_rescale( mSpeedAccum,
+// AUDIO_STEP_LO_SPEED, AUDIO_STEP_HI_SPEED,
+// AUDIO_STEP_LO_GAIN, AUDIO_STEP_HI_GAIN );
+
+ const F32 STEP_VOLUME = 0.1f;
+ const LLUUID& step_sound_id = getStepSound();
+
+ LLVector3d foot_pos_global = gAgent.getPosGlobalFromAgent(foot_pos_agent);
+
+ if (LLViewerParcelMgr::getInstance()->canHearSound(foot_pos_global)
+ && !LLMuteList::getInstance()->isMuted(getID(), LLMute::flagObjectSounds))
+ {
+ gAudiop->triggerSound(step_sound_id, getID(), STEP_VOLUME, LLAudioEngine::AUDIO_TYPE_AMBIENT, foot_pos_global);
+ }
+ }
+ }
+
+ mRoot.updateWorldMatrixChildren();
+
+ if (!mDebugText.size() && mText.notNull())
+ {
+ mText->markDead();
+ mText = NULL;
+ }
+ else if (mDebugText.size())
+ {
+ setDebugText(mDebugText);
+ }
+
+ //mesh vertices need to be reskinned
+ mNeedsSkin = TRUE;
+
+ return TRUE;
+}
+//-----------------------------------------------------------------------------
+// updateHeadOffset()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::updateHeadOffset()
+{
+ // since we only care about Z, just grab one of the eyes
+ LLVector3 midEyePt = mEyeLeftp->getWorldPosition();
+ midEyePt -= mDrawable.notNull() ? mDrawable->getWorldPosition() : mRoot.getWorldPosition();
+ midEyePt.mV[VZ] = llmax(-mPelvisToFoot + LLViewerCamera::getInstance()->getNear(), midEyePt.mV[VZ]);
+
+ if (mDrawable.notNull())
+ {
+ midEyePt = midEyePt * ~mDrawable->getWorldRotation();
+ }
+ if (mIsSitting)
+ {
+ mHeadOffset = midEyePt;
+ }
+ else
+ {
+ F32 u = llmax(0.f, HEAD_MOVEMENT_AVG_TIME - (1.f / gFPSClamped));
+ mHeadOffset = lerp(midEyePt, mHeadOffset, u);
+ }
+}
+//------------------------------------------------------------------------
+// setPelvisOffset
+//------------------------------------------------------------------------
+void LLVOAvatar::setPelvisOffset( bool hasOffset, const LLVector3& offsetAmount, F32 pelvisFixup )
+{
+ mHasPelvisOffset = hasOffset;
+ if ( mHasPelvisOffset )
+ {
+ //Store off last pelvis to foot value
+ mLastPelvisToFoot = mPelvisToFoot;
+ mPelvisOffset = offsetAmount;
+ mPelvisFixup = pelvisFixup;
+ }
+}
+//------------------------------------------------------------------------
+// postPelvisSetRecalc
+//------------------------------------------------------------------------
+void LLVOAvatar::postPelvisSetRecalc( void )
+{
+ computeBodySize();
+ mRoot.touch();
+ mRoot.updateWorldMatrixChildren();
+ dirtyMesh();
+ updateHeadOffset();
+}
+//------------------------------------------------------------------------
+// updateVisibility()
+//------------------------------------------------------------------------
+void LLVOAvatar::updateVisibility()
+{
+ BOOL visible = FALSE;
+
+ if (mIsDummy)
+ {
+ visible = TRUE;
+ }
+ else if (mDrawable.isNull())
+ {
+ visible = FALSE;
+ }
+ else
+ {
+ if (!mDrawable->getSpatialGroup() || mDrawable->getSpatialGroup()->isVisible())
+ {
+ visible = TRUE;
+ }
+ else
+ {
+ visible = FALSE;
+ }
+
+ if(isSelf())
+ {
+ if (!gAgentWearables.areWearablesLoaded())
+ {
+ visible = FALSE;
+ }
+ }
+ else if( !mFirstAppearanceMessageReceived )
+ {
+ visible = FALSE;
+ }
+
+ if (sDebugInvisible)
+ {
+ LLNameValue* firstname = getNVPair("FirstName");
+ if (firstname)
+ {
+ llinfos << "Avatar " << firstname->getString() << " updating visiblity" << llendl;
+ }
+ else
+ {
+ llinfos << "Avatar " << this << " updating visiblity" << llendl;
+ }
+
+ if (visible)
+ {
+ llinfos << "Visible" << llendl;
+ }
+ else
+ {
+ llinfos << "Not visible" << llendl;
+ }
+
+ /*if (avatar_in_frustum)
+ {
+ llinfos << "Avatar in frustum" << llendl;
+ }
+ else
+ {
+ llinfos << "Avatar not in frustum" << llendl;
+ }*/
+
+ /*if (LLViewerCamera::getInstance()->sphereInFrustum(sel_pos_agent, 2.0f))
+ {
+ llinfos << "Sel pos visible" << llendl;
+ }
+ if (LLViewerCamera::getInstance()->sphereInFrustum(wrist_right_pos_agent, 0.2f))
+ {
+ llinfos << "Wrist pos visible" << llendl;
+ }
+ if (LLViewerCamera::getInstance()->sphereInFrustum(getPositionAgent(), getMaxScale()*2.f))
+ {
+ llinfos << "Agent visible" << llendl;
+ }*/
+ llinfos << "PA: " << getPositionAgent() << llendl;
+ /*llinfos << "SPA: " << sel_pos_agent << llendl;
+ llinfos << "WPA: " << wrist_right_pos_agent << llendl;*/
+ for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+
+ for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
+ attachment_iter != attachment->mAttachedObjects.end();
+ ++attachment_iter)
+ {
+ if (LLViewerObject *attached_object = (*attachment_iter))
+ {
+ if(attached_object->mDrawable->isVisible())
+ {
+ llinfos << attachment->getName() << " visible" << llendl;
+ }
+ else
+ {
+ llinfos << attachment->getName() << " not visible at " << mDrawable->getWorldPosition() << " and radius " << mDrawable->getRadius() << llendl;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (!visible && mVisible)
+ {
+ mMeshInvisibleTime.reset();
+ }
+
+ if (visible)
+ {
+ if (!mMeshValid)
+ {
+ restoreMeshData();
+ }
+ }
+ else
+ {
+ if (mMeshValid && mMeshInvisibleTime.getElapsedTimeF32() > TIME_BEFORE_MESH_CLEANUP)
+ {
+ releaseMeshData();
+ }
+ // this breaks off-screen chat bubbles
+ //if (mNameText)
+ //{
+ // mNameText->markDead();
+ // mNameText = NULL;
+ // sNumVisibleChatBubbles--;
+ //}
+ }
+
+ mVisible = visible;
+}
+
+// private
+bool LLVOAvatar::shouldAlphaMask()
+{
+ const bool should_alpha_mask = mSupportsAlphaLayers && !LLDrawPoolAlpha::sShowDebugAlpha // Don't alpha mask if "Highlight Transparent" checked
+ && !LLDrawPoolAvatar::sSkipTransparent;
+
+ return should_alpha_mask;
+
+}
+
+U32 LLVOAvatar::renderSkinnedAttachments()
+{
+ /*U32 num_indices = 0;
+
+ const U32 data_mask = LLVertexBuffer::MAP_VERTEX |
+ LLVertexBuffer::MAP_NORMAL |
+ LLVertexBuffer::MAP_TEXCOORD0 |
+ LLVertexBuffer::MAP_COLOR |
+ LLVertexBuffer::MAP_WEIGHT4;
+
+ for (attachment_map_t::const_iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+ for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
+ attachment_iter != attachment->mAttachedObjects.end();
+ ++attachment_iter)
+ {
+ const LLViewerObject* attached_object = (*attachment_iter);
+ if (attached_object && !attached_object->isHUDAttachment())
+ {
+ const LLDrawable* drawable = attached_object->mDrawable;
+ if (drawable)
+ {
+ for (S32 i = 0; i < drawable->getNumFaces(); ++i)
+ {
+ LLFace* face = drawable->getFace(i);
+ if (face->isState(LLFace::RIGGED))
+ {
+
+ }
+ }
+ }
+ }
+
+ return num_indices;*/
+ return 0;
+}
+
+//-----------------------------------------------------------------------------
+// renderSkinned()
+//-----------------------------------------------------------------------------
+U32 LLVOAvatar::renderSkinned(EAvatarRenderPass pass)
+{
+ U32 num_indices = 0;
+
+ if (!mIsBuilt)
+ {
+ return num_indices;
+ }
+
+ LLFace* face = mDrawable->getFace(0);
+
+ bool needs_rebuild = !face || !face->getVertexBuffer() || mDrawable->isState(LLDrawable::REBUILD_GEOMETRY);
+
+ if (needs_rebuild || mDirtyMesh)
+ { //LOD changed or new mesh created, allocate new vertex buffer if needed
+ if (needs_rebuild || mDirtyMesh >= 2 || mVisibilityRank <= 4)
+ {
+ updateMeshData();
+ mDirtyMesh = 0;
+ mNeedsSkin = TRUE;
+ mDrawable->clearState(LLDrawable::REBUILD_GEOMETRY);
+ }
+ }
+
+ if (LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_AVATAR) <= 0)
+ {
+ if (mNeedsSkin)
+ {
+ //generate animated mesh
+ mMeshLOD[MESH_ID_LOWER_BODY]->updateJointGeometry();
+ mMeshLOD[MESH_ID_UPPER_BODY]->updateJointGeometry();
+
+ if( isWearingWearableType( LLWearableType::WT_SKIRT ) )
+ {
+ mMeshLOD[MESH_ID_SKIRT]->updateJointGeometry();
+ }
+
+ if (!isSelf() || gAgent.needsRenderHead() || LLPipeline::sShadowRender)
+ {
+ mMeshLOD[MESH_ID_EYELASH]->updateJointGeometry();
+ mMeshLOD[MESH_ID_HEAD]->updateJointGeometry();
+ mMeshLOD[MESH_ID_HAIR]->updateJointGeometry();
+ }
+ mNeedsSkin = FALSE;
+ mLastSkinTime = gFrameTimeSeconds;
+
+ LLVertexBuffer* vb = mDrawable->getFace(0)->getVertexBuffer();
+ if (vb)
+ {
+ vb->setBuffer(0);
+ }
+ }
+ }
+ else
+ {
+ mNeedsSkin = FALSE;
+ }
+
+ if (sDebugInvisible)
+ {
+ LLNameValue* firstname = getNVPair("FirstName");
+ if (firstname)
+ {
+ llinfos << "Avatar " << firstname->getString() << " in render" << llendl;
+ }
+ else
+ {
+ llinfos << "Avatar " << this << " in render" << llendl;
+ }
+ if (!mIsBuilt)
+ {
+ llinfos << "Not built!" << llendl;
+ }
+ else if (!gAgent.needsRenderAvatar())
+ {
+ llinfos << "Doesn't need avatar render!" << llendl;
+ }
+ else
+ {
+ llinfos << "Rendering!" << llendl;
+ }
+ }
+
+ if (!mIsBuilt)
+ {
+ return num_indices;
+ }
+
+ if (isSelf() && !gAgent.needsRenderAvatar())
+ {
+ return num_indices;
+ }
+
+ // render collision normal
+ // *NOTE: this is disabled (there is no UI for enabling sShowFootPlane) due
+ // to DEV-14477. the code is left here to aid in tracking down the cause
+ // of the crash in the future. -brad
+ if (sShowFootPlane && mDrawable.notNull())
+ {
+ LLVector3 slaved_pos = mDrawable->getPositionAgent();
+ LLVector3 foot_plane_normal(mFootPlane.mV[VX], mFootPlane.mV[VY], mFootPlane.mV[VZ]);
+ F32 dist_from_plane = (slaved_pos * foot_plane_normal) - mFootPlane.mV[VW];
+ LLVector3 collide_point = slaved_pos;
+ collide_point.mV[VZ] -= foot_plane_normal.mV[VZ] * (dist_from_plane + COLLISION_TOLERANCE - FOOT_COLLIDE_FUDGE);
+
+ gGL.begin(LLRender::LINES);
+ {
+ F32 SQUARE_SIZE = 0.2f;
+ gGL.color4f(1.f, 0.f, 0.f, 1.f);
+
+ gGL.vertex3f(collide_point.mV[VX] - SQUARE_SIZE, collide_point.mV[VY] - SQUARE_SIZE, collide_point.mV[VZ]);
+ gGL.vertex3f(collide_point.mV[VX] + SQUARE_SIZE, collide_point.mV[VY] - SQUARE_SIZE, collide_point.mV[VZ]);
+
+ gGL.vertex3f(collide_point.mV[VX] + SQUARE_SIZE, collide_point.mV[VY] - SQUARE_SIZE, collide_point.mV[VZ]);
+ gGL.vertex3f(collide_point.mV[VX] + SQUARE_SIZE, collide_point.mV[VY] + SQUARE_SIZE, collide_point.mV[VZ]);
+
+ gGL.vertex3f(collide_point.mV[VX] + SQUARE_SIZE, collide_point.mV[VY] + SQUARE_SIZE, collide_point.mV[VZ]);
+ gGL.vertex3f(collide_point.mV[VX] - SQUARE_SIZE, collide_point.mV[VY] + SQUARE_SIZE, collide_point.mV[VZ]);
+
+ gGL.vertex3f(collide_point.mV[VX] - SQUARE_SIZE, collide_point.mV[VY] + SQUARE_SIZE, collide_point.mV[VZ]);
+ gGL.vertex3f(collide_point.mV[VX] - SQUARE_SIZE, collide_point.mV[VY] - SQUARE_SIZE, collide_point.mV[VZ]);
+
+ gGL.vertex3f(collide_point.mV[VX], collide_point.mV[VY], collide_point.mV[VZ]);
+ gGL.vertex3f(collide_point.mV[VX] + mFootPlane.mV[VX], collide_point.mV[VY] + mFootPlane.mV[VY], collide_point.mV[VZ] + mFootPlane.mV[VZ]);
+
+ }
+ gGL.end();
+ gGL.flush();
+ }
+ //--------------------------------------------------------------------
+ // render all geometry attached to the skeleton
+ //--------------------------------------------------------------------
+ static LLStat render_stat;
+
+ LLViewerJointMesh::sRenderPass = pass;
+
+ if (pass == AVATAR_RENDER_PASS_SINGLE)
+ {
+
+ bool should_alpha_mask = shouldAlphaMask();
+ LLGLState test(GL_ALPHA_TEST, should_alpha_mask);
+
+ if (should_alpha_mask)
+ {
+ gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);
+ }
+
+ BOOL first_pass = TRUE;
+ if (!LLDrawPoolAvatar::sSkipOpaque)
+ {
+ if (!isSelf() || gAgent.needsRenderHead() || LLPipeline::sShadowRender)
+ {
+ if (isTextureVisible(TEX_HEAD_BAKED) || mIsDummy)
+ {
+ num_indices += mMeshLOD[MESH_ID_HEAD]->render(mAdjustedPixelArea, TRUE, mIsDummy);
+ first_pass = FALSE;
+ }
+ }
+ if (isTextureVisible(TEX_UPPER_BAKED) || mIsDummy)
+ {
+ num_indices += mMeshLOD[MESH_ID_UPPER_BODY]->render(mAdjustedPixelArea, first_pass, mIsDummy);
+ first_pass = FALSE;
+ }
+
+ if (isTextureVisible(TEX_LOWER_BAKED) || mIsDummy)
+ {
+ num_indices += mMeshLOD[MESH_ID_LOWER_BODY]->render(mAdjustedPixelArea, first_pass, mIsDummy);
+ first_pass = FALSE;
+ }
+ }
+
+ gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
+
+ if (!LLDrawPoolAvatar::sSkipTransparent || LLPipeline::sImpostorRender)
+ {
+ LLGLState blend(GL_BLEND, !mIsDummy);
+ LLGLState test(GL_ALPHA_TEST, !mIsDummy);
+ num_indices += renderTransparent(first_pass);
+ }
+ }
+
+ LLViewerJointMesh::sRenderPass = AVATAR_RENDER_PASS_SINGLE;
+
+ //llinfos << "Avatar render: " << render_timer.getElapsedTimeF32() << llendl;
+
+ //render_stat.addValue(render_timer.getElapsedTimeF32()*1000.f);
+
+ return num_indices;
+}
+
+U32 LLVOAvatar::renderTransparent(BOOL first_pass)
+{
+ U32 num_indices = 0;
+ if( isWearingWearableType( LLWearableType::WT_SKIRT ) && (mIsDummy || isTextureVisible(TEX_SKIRT_BAKED)) )
+ {
+ gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.25f);
+ num_indices += mMeshLOD[MESH_ID_SKIRT]->render(mAdjustedPixelArea, FALSE);
+ first_pass = FALSE;
+ gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
+ }
+
+ if (!isSelf() || gAgent.needsRenderHead() || LLPipeline::sShadowRender)
+ {
+ if (LLPipeline::sImpostorRender)
+ {
+ gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);
+ }
+
+ if (isTextureVisible(TEX_HEAD_BAKED))
+ {
+ num_indices += mMeshLOD[MESH_ID_EYELASH]->render(mAdjustedPixelArea, first_pass, mIsDummy);
+ first_pass = FALSE;
+ }
+ // Can't test for baked hair being defined, since that won't always be the case (not all viewers send baked hair)
+ // TODO: 1.25 will be able to switch this logic back to calling isTextureVisible();
+ if (getImage(TEX_HAIR_BAKED, 0)->getID() != IMG_INVISIBLE || LLDrawPoolAlpha::sShowDebugAlpha)
+ {
+ num_indices += mMeshLOD[MESH_ID_HAIR]->render(mAdjustedPixelArea, first_pass, mIsDummy);
+ first_pass = FALSE;
+ }
+ if (LLPipeline::sImpostorRender)
+ {
+ gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
+ }
+ }
+
+ return num_indices;
+}
+
+//-----------------------------------------------------------------------------
+// renderRigid()
+//-----------------------------------------------------------------------------
+U32 LLVOAvatar::renderRigid()
+{
+ U32 num_indices = 0;
+
+ if (!mIsBuilt)
+ {
+ return 0;
+ }
+
+ if (isSelf() && (!gAgent.needsRenderAvatar() || !gAgent.needsRenderHead()))
+ {
+ return 0;
+ }
+
+ if (!mIsBuilt)
+ {
+ return 0;
+ }
+
+ bool should_alpha_mask = shouldAlphaMask();
+ LLGLState test(GL_ALPHA_TEST, should_alpha_mask);
+
+ if (should_alpha_mask)
+ {
+ gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);
+ }
+
+ if (isTextureVisible(TEX_EYES_BAKED) || mIsDummy)
+ {
+ num_indices += mMeshLOD[MESH_ID_EYEBALL_LEFT]->render(mAdjustedPixelArea, TRUE, mIsDummy);
+ num_indices += mMeshLOD[MESH_ID_EYEBALL_RIGHT]->render(mAdjustedPixelArea, TRUE, mIsDummy);
+ }
+
+ gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
+
+ return num_indices;
+}
+
+U32 LLVOAvatar::renderImpostor(LLColor4U color, S32 diffuse_channel)
+{
+ if (!mImpostor.isComplete())
+ {
+ return 0;
+ }
+
+ LLVector3 pos(getRenderPosition()+mImpostorOffset);
+ LLVector3 at = (pos - LLViewerCamera::getInstance()->getOrigin());
+ at.normalize();
+ LLVector3 left = LLViewerCamera::getInstance()->getUpAxis() % at;
+ LLVector3 up = at%left;
+
+ left *= mImpostorDim.mV[0];
+ up *= mImpostorDim.mV[1];
+
+ LLGLEnable test(GL_ALPHA_TEST);
+ gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.f);
+
+ gGL.color4ubv(color.mV);
+ gGL.getTexUnit(diffuse_channel)->bind(&mImpostor);
+ gGL.begin(LLRender::QUADS);
+ gGL.texCoord2f(0,0);
+ gGL.vertex3fv((pos+left-up).mV);
+ gGL.texCoord2f(1,0);
+ gGL.vertex3fv((pos-left-up).mV);
+ gGL.texCoord2f(1,1);
+ gGL.vertex3fv((pos-left+up).mV);
+ gGL.texCoord2f(0,1);
+ gGL.vertex3fv((pos+left+up).mV);
+ gGL.end();
+ gGL.flush();
+
+ return 6;
+}
+
+//------------------------------------------------------------------------
+// LLVOAvatar::updateTextures()
+//------------------------------------------------------------------------
+void LLVOAvatar::updateTextures()
+{
+ BOOL render_avatar = TRUE;
+
+ if (mIsDummy || gNoRender)
+ {
+ return;
+ }
+
+ if( isSelf() )
+ {
+ render_avatar = TRUE;
+ }
+ else
+ {
+ if(!isVisible())
+ {
+ return ;//do not update for invisible avatar.
+ }
+
+ render_avatar = !mCulled; //visible and not culled.
+ }
+
+ std::vector<BOOL> layer_baked;
+ // GL NOT ACTIVE HERE - *TODO
+ for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
+ {
+ layer_baked.push_back(isTextureDefined(mBakedTextureDatas[i].mTextureIndex));
+ // bind the texture so that they'll be decoded slightly
+ // inefficient, we can short-circuit this if we have to
+ if (render_avatar && !gGLManager.mIsDisabled)
+ {
+ if (layer_baked[i] && !mBakedTextureDatas[i].mIsLoaded)
+ {
+ gGL.getTexUnit(0)->bind(getImage( mBakedTextureDatas[i].mTextureIndex, 0 ));
+ }
+ }
+ }
+
+ mMaxPixelArea = 0.f;
+ mMinPixelArea = 99999999.f;
+ mHasGrey = FALSE; // debug
+ for (U32 texture_index = 0; texture_index < getNumTEs(); texture_index++)
+ {
+ LLWearableType::EType wearable_type = LLVOAvatarDictionary::getTEWearableType((ETextureIndex)texture_index);
+ U32 num_wearables = gAgentWearables.getWearableCount(wearable_type);
+ const LLTextureEntry *te = getTE(texture_index);
+ const F32 texel_area_ratio = fabs(te->mScaleS * te->mScaleT);
+ LLViewerFetchedTexture *imagep = NULL;
+ for (U32 wearable_index = 0; wearable_index < num_wearables; wearable_index++)
+ {
+ imagep = LLViewerTextureManager::staticCastToFetchedTexture(getImage(texture_index, wearable_index), TRUE);
+ if (imagep)
+ {
+ const LLVOAvatarDictionary::TextureEntry *texture_dict = LLVOAvatarDictionary::getInstance()->getTexture((ETextureIndex)texture_index);
+ const EBakedTextureIndex baked_index = texture_dict->mBakedTextureIndex;
+ if (texture_dict->mIsLocalTexture)
+ {
+ addLocalTextureStats((ETextureIndex)texture_index, imagep, texel_area_ratio, render_avatar, layer_baked[baked_index]);
+ }
+ }
+ }
+ if (isIndexBakedTexture((ETextureIndex) texture_index) && render_avatar)
+ {
+ const S32 boost_level = getAvatarBakedBoostLevel();
+ imagep = LLViewerTextureManager::staticCastToFetchedTexture(getImage(texture_index,0), TRUE);
+ // Spam if this is a baked texture, not set to default image, without valid host info
+ if (isIndexBakedTexture((ETextureIndex)texture_index)
+ && imagep->getID() != IMG_DEFAULT_AVATAR
+ && imagep->getID() != IMG_INVISIBLE
+ && !imagep->getTargetHost().isOk())
+ {
+ LL_WARNS_ONCE("Texture") << "LLVOAvatar::updateTextures No host for texture "
+ << imagep->getID() << " for avatar "
+ << (isSelf() ? "<myself>" : getID().asString())
+ << " on host " << getRegion()->getHost() << llendl;
+ }
+
+ addBakedTextureStats( imagep, mPixelArea, texel_area_ratio, boost_level );
+ }
+ }
+
+ if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_AREA))
+ {
+ setDebugText(llformat("%4.0f:%4.0f", (F32) sqrt(mMinPixelArea),(F32) sqrt(mMaxPixelArea)));
+ }
+}
+
+
+void LLVOAvatar::addLocalTextureStats( ETextureIndex idx, LLViewerFetchedTexture* imagep,
+ F32 texel_area_ratio, BOOL render_avatar, BOOL covered_by_baked, U32 index )
+{
+ // No local texture stats for non-self avatars
+ return;
+}
+
+const S32 MAX_TEXTURE_UPDATE_INTERVAL = 64 ; //need to call updateTextures() at least every 32 frames.
+const S32 MAX_TEXTURE_VIRTURE_SIZE_RESET_INTERVAL = S32_MAX ; //frames
+void LLVOAvatar::checkTextureLoading()
+{
+ static const F32 MAX_INVISIBLE_WAITING_TIME = 15.f ; //seconds
+
+ BOOL pause = !isVisible() ;
+ if(!pause)
+ {
+ mInvisibleTimer.reset() ;
+ }
+ if(mLoadedCallbacksPaused == pause)
+ {
+ return ;
+ }
+
+ if(mCallbackTextureList.empty()) //when is self or no callbacks. Note: this list for self is always empty.
+ {
+ mLoadedCallbacksPaused = pause ;
+ return ; //nothing to check.
+ }
+
+ if(pause && mInvisibleTimer.getElapsedTimeF32() < MAX_INVISIBLE_WAITING_TIME)
+ {
+ return ; //have not been invisible for enough time.
+ }
+
+ for(LLLoadedCallbackEntry::source_callback_list_t::iterator iter = mCallbackTextureList.begin();
+ iter != mCallbackTextureList.end(); ++iter)
+ {
+ LLViewerFetchedTexture* tex = gTextureList.findImage(*iter) ;
+ if(tex)
+ {
+ if(pause)//pause texture fetching.
+ {
+ tex->pauseLoadedCallbacks(&mCallbackTextureList) ;
+
+ //set to terminate texture fetching after MAX_TEXTURE_UPDATE_INTERVAL frames.
+ tex->setMaxVirtualSizeResetInterval(MAX_TEXTURE_UPDATE_INTERVAL);
+ tex->resetMaxVirtualSizeResetCounter() ;
+ }
+ else//unpause
+ {
+ static const F32 START_AREA = 100.f ;
+
+ tex->unpauseLoadedCallbacks(&mCallbackTextureList) ;
+ tex->addTextureStats(START_AREA); //jump start the fetching again
+ }
+ }
+ }
+
+ if(!pause)
+ {
+ updateTextures() ; //refresh texture stats.
+ }
+ mLoadedCallbacksPaused = pause ;
+ return ;
+}
+
+const F32 SELF_ADDITIONAL_PRI = 0.75f ;
+const F32 ADDITIONAL_PRI = 0.5f;
+void LLVOAvatar::addBakedTextureStats( LLViewerFetchedTexture* imagep, F32 pixel_area, F32 texel_area_ratio, S32 boost_level)
+{
+ //Note:
+ //if this function is not called for the last MAX_TEXTURE_VIRTURE_SIZE_RESET_INTERVAL frames,
+ //the texture pipeline will stop fetching this texture.
+
+ imagep->resetTextureStats();
+ imagep->setCanUseHTTP(false) ; //turn off http fetching for baked textures.
+ imagep->setMaxVirtualSizeResetInterval(MAX_TEXTURE_VIRTURE_SIZE_RESET_INTERVAL);
+ imagep->resetMaxVirtualSizeResetCounter() ;
+
+ mMaxPixelArea = llmax(pixel_area, mMaxPixelArea);
+ mMinPixelArea = llmin(pixel_area, mMinPixelArea);
+ imagep->addTextureStats(pixel_area / texel_area_ratio);
+ imagep->setBoostLevel(boost_level);
+
+ if(boost_level != LLViewerTexture::BOOST_AVATAR_BAKED_SELF)
+ {
+ imagep->setAdditionalDecodePriority(ADDITIONAL_PRI) ;
+ }
+ else
+ {
+ imagep->setAdditionalDecodePriority(SELF_ADDITIONAL_PRI) ;
+ }
+}
+
+//virtual
+void LLVOAvatar::setImage(const U8 te, LLViewerTexture *imagep, const U32 index)
+{
+ setTEImage(te, imagep);
+}
+
+//virtual
+LLViewerTexture* LLVOAvatar::getImage(const U8 te, const U32 index) const
+{
+ return getTEImage(te);
+}
+//virtual
+const LLTextureEntry* LLVOAvatar::getTexEntry(const U8 te_num) const
+{
+ return getTE(te_num);
+}
+
+//virtual
+void LLVOAvatar::setTexEntry(const U8 index, const LLTextureEntry &te)
+{
+ setTE(index, te);
+}
+
+//-----------------------------------------------------------------------------
+// resolveHeight()
+//-----------------------------------------------------------------------------
+
+void LLVOAvatar::resolveHeightAgent(const LLVector3 &in_pos_agent, LLVector3 &out_pos_agent, LLVector3 &out_norm)
+{
+ LLVector3d in_pos_global, out_pos_global;
+
+ in_pos_global = gAgent.getPosGlobalFromAgent(in_pos_agent);
+ resolveHeightGlobal(in_pos_global, out_pos_global, out_norm);
+ out_pos_agent = gAgent.getPosAgentFromGlobal(out_pos_global);
+}
+
+
+void LLVOAvatar::resolveRayCollisionAgent(const LLVector3d start_pt, const LLVector3d end_pt, LLVector3d &out_pos, LLVector3 &out_norm)
+{
+ LLViewerObject *obj;
+ LLWorld::getInstance()->resolveStepHeightGlobal(this, start_pt, end_pt, out_pos, out_norm, &obj);
+}
+
+void LLVOAvatar::resolveHeightGlobal(const LLVector3d &inPos, LLVector3d &outPos, LLVector3 &outNorm)
+{
+ LLVector3d zVec(0.0f, 0.0f, 0.5f);
+ LLVector3d p0 = inPos + zVec;
+ LLVector3d p1 = inPos - zVec;
+ LLViewerObject *obj;
+ LLWorld::getInstance()->resolveStepHeightGlobal(this, p0, p1, outPos, outNorm, &obj);
+ if (!obj)
+ {
+ mStepOnLand = TRUE;
+ mStepMaterial = 0;
+ mStepObjectVelocity.setVec(0.0f, 0.0f, 0.0f);
+ }
+ else
+ {
+ mStepOnLand = FALSE;
+ mStepMaterial = obj->getMaterial();
+
+ // We want the primitive velocity, not our velocity... (which actually subtracts the
+ // step object velocity)
+ LLVector3 angularVelocity = obj->getAngularVelocity();
+ LLVector3 relativePos = gAgent.getPosAgentFromGlobal(outPos) - obj->getPositionAgent();
+
+ LLVector3 linearComponent = angularVelocity % relativePos;
+// llinfos << "Linear Component of Rotation Velocity " << linearComponent << llendl;
+ mStepObjectVelocity = obj->getVelocity() + linearComponent;
+ }
+}
+
+
+//-----------------------------------------------------------------------------
+// getStepSound()
+//-----------------------------------------------------------------------------
+const LLUUID& LLVOAvatar::getStepSound() const
+{
+ if ( mStepOnLand )
+ {
+ return sStepSoundOnLand;
+ }
+
+ return sStepSounds[mStepMaterial];
+}
+
+
+//-----------------------------------------------------------------------------
+// processAnimationStateChanges()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::processAnimationStateChanges()
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ if (gNoRender)
+ {
+ return;
+ }
+
+ if ( isAnyAnimationSignaled(AGENT_WALK_ANIMS, NUM_AGENT_WALK_ANIMS) )
+ {
+ startMotion(ANIM_AGENT_WALK_ADJUST);
+ stopMotion(ANIM_AGENT_FLY_ADJUST);
+ }
+ else if (mInAir && !mIsSitting)
+ {
+ stopMotion(ANIM_AGENT_WALK_ADJUST);
+ startMotion(ANIM_AGENT_FLY_ADJUST);
+ }
+ else
+ {
+ stopMotion(ANIM_AGENT_WALK_ADJUST);
+ stopMotion(ANIM_AGENT_FLY_ADJUST);
+ }
+
+ if ( isAnyAnimationSignaled(AGENT_GUN_AIM_ANIMS, NUM_AGENT_GUN_AIM_ANIMS) )
+ {
+ startMotion(ANIM_AGENT_TARGET);
+ stopMotion(ANIM_AGENT_BODY_NOISE);
+ }
+ else
+ {
+ stopMotion(ANIM_AGENT_TARGET);
+ startMotion(ANIM_AGENT_BODY_NOISE);
+ }
+
+ // clear all current animations
+ AnimIterator anim_it;
+ for (anim_it = mPlayingAnimations.begin(); anim_it != mPlayingAnimations.end();)
+ {
+ AnimIterator found_anim = mSignaledAnimations.find(anim_it->first);
+
+ // playing, but not signaled, so stop
+ if (found_anim == mSignaledAnimations.end())
+ {
+ processSingleAnimationStateChange(anim_it->first, FALSE);
+ mPlayingAnimations.erase(anim_it++);
+ continue;
+ }
+
+ ++anim_it;
+ }
+
+ // start up all new anims
+ for (anim_it = mSignaledAnimations.begin(); anim_it != mSignaledAnimations.end();)
+ {
+ AnimIterator found_anim = mPlayingAnimations.find(anim_it->first);
+
+ // signaled but not playing, or different sequence id, start motion
+ if (found_anim == mPlayingAnimations.end() || found_anim->second != anim_it->second)
+ {
+ if (processSingleAnimationStateChange(anim_it->first, TRUE))
+ {
+ mPlayingAnimations[anim_it->first] = anim_it->second;
+ ++anim_it;
+ continue;
+ }
+ }
+
+ ++anim_it;
+ }
+
+ // clear source information for animations which have been stopped
+ if (isSelf())
+ {
+ AnimSourceIterator source_it = mAnimationSources.begin();
+
+ for (source_it = mAnimationSources.begin(); source_it != mAnimationSources.end();)
+ {
+ if (mSignaledAnimations.find(source_it->second) == mSignaledAnimations.end())
+ {
+ mAnimationSources.erase(source_it++);
+ }
+ else
+ {
+ ++source_it;
+ }
+ }
+ }
+
+ stop_glerror();
+}
+
+
+//-----------------------------------------------------------------------------
+// processSingleAnimationStateChange();
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::processSingleAnimationStateChange( const LLUUID& anim_id, BOOL start )
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ BOOL result = FALSE;
+
+ if ( start ) // start animation
+ {
+ if (anim_id == ANIM_AGENT_TYPE)
+ {
+ if (gAudiop)
+ {
+ LLVector3d char_pos_global = gAgent.getPosGlobalFromAgent(getCharacterPosition());
+ if (LLViewerParcelMgr::getInstance()->canHearSound(char_pos_global)
+ && !LLMuteList::getInstance()->isMuted(getID(), LLMute::flagObjectSounds))
+ {
+ // RN: uncomment this to play on typing sound at fixed volume once sound engine is fixed
+ // to support both spatialized and non-spatialized instances of the same sound
+ //if (isSelf())
+ //{
+ // gAudiop->triggerSound(LLUUID(gSavedSettings.getString("UISndTyping")), 1.0f, LLAudioEngine::AUDIO_TYPE_UI);
+ //}
+ //else
+ {
+ LLUUID sound_id = LLUUID(gSavedSettings.getString("UISndTyping"));
+ gAudiop->triggerSound(sound_id, getID(), 1.0f, LLAudioEngine::AUDIO_TYPE_SFX, char_pos_global);
+ }
+ }
+ }
+ }
+ else if (anim_id == ANIM_AGENT_SIT_GROUND_CONSTRAINED)
+ {
+ sitDown(TRUE);
+ }
+
+
+ if (startMotion(anim_id))
+ {
+ result = TRUE;
+ }
+ else
+ {
+ llwarns << "Failed to start motion!" << llendl;
+ }
+ }
+ else //stop animation
+ {
+ if (anim_id == ANIM_AGENT_SIT_GROUND_CONSTRAINED)
+ {
+ sitDown(FALSE);
+ }
+ stopMotion(anim_id);
+ result = TRUE;
+ }
+
+ return result;
+}
+
+//-----------------------------------------------------------------------------
+// isAnyAnimationSignaled()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::isAnyAnimationSignaled(const LLUUID *anim_array, const S32 num_anims) const
+{
+ for (S32 i = 0; i < num_anims; i++)
+ {
+ if(mSignaledAnimations.find(anim_array[i]) != mSignaledAnimations.end())
+ {
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+//-----------------------------------------------------------------------------
+// resetAnimations()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::resetAnimations()
+{
+ LLKeyframeMotion::flushKeyframeCache();
+ flushAllMotions();
+}
+
+// Override selectively based on avatar sex and whether we're using new
+// animations.
+LLUUID LLVOAvatar::remapMotionID(const LLUUID& id)
+{
+ BOOL use_new_walk_run = gSavedSettings.getBOOL("UseNewWalkRun");
+ LLUUID result = id;
+
+ // start special case female walk for female avatars
+ if (getSex() == SEX_FEMALE)
+ {
+ if (id == ANIM_AGENT_WALK)
+ {
+ if (use_new_walk_run)
+ result = ANIM_AGENT_FEMALE_WALK_NEW;
+ else
+ result = ANIM_AGENT_FEMALE_WALK;
+ }
+ else if (id == ANIM_AGENT_RUN)
+ {
+ // There is no old female run animation, so only override
+ // in one case.
+ if (use_new_walk_run)
+ result = ANIM_AGENT_FEMALE_RUN_NEW;
+ }
+ else if (id == ANIM_AGENT_SIT)
+ {
+ result = ANIM_AGENT_SIT_FEMALE;
+ }
+ }
+ else
+ {
+ // Male avatar.
+ if (id == ANIM_AGENT_WALK)
+ {
+ if (use_new_walk_run)
+ result = ANIM_AGENT_WALK_NEW;
+ }
+ else if (id == ANIM_AGENT_RUN)
+ {
+ if (use_new_walk_run)
+ result = ANIM_AGENT_RUN_NEW;
+ }
+
+ }
+
+ return result;
+
+}
+
+//-----------------------------------------------------------------------------
+// startMotion()
+// id is the asset if of the animation to start
+// time_offset is the offset into the animation at which to start playing
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::startMotion(const LLUUID& id, F32 time_offset)
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ lldebugs << "motion requested " << id.asString() << " " << gAnimLibrary.animationName(id) << llendl;
+
+ LLUUID remap_id = remapMotionID(id);
+
+ if (remap_id != id)
+ {
+ lldebugs << "motion resultant " << remap_id.asString() << " " << gAnimLibrary.animationName(remap_id) << llendl;
+ }
+
+ if (isSelf() && remap_id == ANIM_AGENT_AWAY)
+ {
+ gAgent.setAFK();
+ }
+
+ return LLCharacter::startMotion(remap_id, time_offset);
+}
+
+//-----------------------------------------------------------------------------
+// stopMotion()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::stopMotion(const LLUUID& id, BOOL stop_immediate)
+{
+ lldebugs << "motion requested " << id.asString() << " " << gAnimLibrary.animationName(id) << llendl;
+
+ LLUUID remap_id = remapMotionID(id);
+
+ if (remap_id != id)
+ {
+ lldebugs << "motion resultant " << remap_id.asString() << " " << gAnimLibrary.animationName(remap_id) << llendl;
+ }
+
+ if (isSelf())
+ {
+ gAgent.onAnimStop(remap_id);
+ }
+
+ return LLCharacter::stopMotion(remap_id, stop_immediate);
+}
+
+//-----------------------------------------------------------------------------
+// stopMotionFromSource()
+//-----------------------------------------------------------------------------
+// virtual
+void LLVOAvatar::stopMotionFromSource(const LLUUID& source_id)
+{
+}
+
+//-----------------------------------------------------------------------------
+// getVolumePos()
+//-----------------------------------------------------------------------------
+LLVector3 LLVOAvatar::getVolumePos(S32 joint_index, LLVector3& volume_offset)
+{
+ if (joint_index > mNumCollisionVolumes)
+ {
+ return LLVector3::zero;
+ }
+
+ return mCollisionVolumes[joint_index].getVolumePos(volume_offset);
+}
+
+//-----------------------------------------------------------------------------
+// findCollisionVolume()
+//-----------------------------------------------------------------------------
+LLJoint* LLVOAvatar::findCollisionVolume(U32 volume_id)
+{
+ if ((S32)volume_id > mNumCollisionVolumes)
+ {
+ return NULL;
+ }
+
+ return &mCollisionVolumes[volume_id];
+}
+
+//-----------------------------------------------------------------------------
+// findCollisionVolume()
+//-----------------------------------------------------------------------------
+S32 LLVOAvatar::getCollisionVolumeID(std::string &name)
+{
+ for (S32 i = 0; i < mNumCollisionVolumes; i++)
+ {
+ if (mCollisionVolumes[i].getName() == name)
+ {
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+//-----------------------------------------------------------------------------
+// addDebugText()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::addDebugText(const std::string& text)
+{
+ mDebugText.append(1, '\n');
+ mDebugText.append(text);
+}
+
+//-----------------------------------------------------------------------------
+// getID()
+//-----------------------------------------------------------------------------
+const LLUUID& LLVOAvatar::getID()
+{
+ return mID;
+}
+
+//-----------------------------------------------------------------------------
+// getJoint()
+//-----------------------------------------------------------------------------
+// RN: avatar joints are multi-rooted to include screen-based attachments
+LLJoint *LLVOAvatar::getJoint( const std::string &name )
+{
+ LLJoint* jointp = mRoot.findJoint(name);
+ return jointp;
+}
+
+//-----------------------------------------------------------------------------
+// resetJointPositions
+//-----------------------------------------------------------------------------
+void LLVOAvatar::resetJointPositions( void )
+{
+ for(S32 i = 0; i < (S32)mNumJoints; ++i)
+ {
+ mSkeleton[i].restoreOldXform();
+ mSkeleton[i].setId( LLUUID::null );
+ }
+ mHasPelvisOffset = false;
+}
+//-----------------------------------------------------------------------------
+// resetSpecificJointPosition
+//-----------------------------------------------------------------------------
+void LLVOAvatar::resetSpecificJointPosition( const std::string& name )
+{
+ LLJoint* pJoint = mRoot.findJoint( name );
+
+ if ( pJoint && pJoint->doesJointNeedToBeReset() )
+ {
+ pJoint->restoreOldXform();
+ pJoint->setId( LLUUID::null );
+ //If we're reseting the pelvis position make sure not to apply offset
+ if ( name == "mPelvis" )
+ {
+ mHasPelvisOffset = false;
+ }
+ }
+ else
+ {
+ llinfos<<"Did not find "<< name.c_str()<<llendl;
+ }
+}
+//-----------------------------------------------------------------------------
+// resetJointPositionsToDefault
+//-----------------------------------------------------------------------------
+void LLVOAvatar::resetJointPositionsToDefault( void )
+{
+ const LLVector3& avPos = getCharacterPosition();
+
+ //Reposition the pelvis
+ LLJoint* pPelvis = mRoot.findJoint("mPelvis");
+ if ( pPelvis )
+ {
+ pPelvis->setPosition( avPos + pPelvis->getPosition() );
+ }
+ else
+ {
+ llwarns<<"Can't get pelvis joint."<<llendl;
+ return;
+ }
+
+ //Subsequent joints are relative to pelvis
+ for( S32 i = 0; i < (S32)mNumJoints; ++i )
+ {
+ LLJoint* pJoint = (LLJoint*)&mSkeleton[i];
+ if ( pJoint->doesJointNeedToBeReset() )
+ {
+
+ pJoint->setId( LLUUID::null );
+ //restore joints to default positions, however skip over the pelvis
+ if ( pJoint && pPelvis != pJoint )
+ {
+ pJoint->restoreOldXform();
+ }
+ }
+ }
+ //make sure we don't apply the joint offset
+ mHasPelvisOffset = false;
+ postPelvisSetRecalc();
+}
+//-----------------------------------------------------------------------------
+// getCharacterPosition()
+//-----------------------------------------------------------------------------
+LLVector3 LLVOAvatar::getCharacterPosition()
+{
+ if (mDrawable.notNull())
+ {
+ return mDrawable->getPositionAgent();
+ }
+ else
+ {
+ return getPositionAgent();
+ }
+}
+
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::getCharacterRotation()
+//-----------------------------------------------------------------------------
+LLQuaternion LLVOAvatar::getCharacterRotation()
+{
+ return getRotation();
+}
+
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::getCharacterVelocity()
+//-----------------------------------------------------------------------------
+LLVector3 LLVOAvatar::getCharacterVelocity()
+{
+ return getVelocity() - mStepObjectVelocity;
+}
+
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::getCharacterAngularVelocity()
+//-----------------------------------------------------------------------------
+LLVector3 LLVOAvatar::getCharacterAngularVelocity()
+{
+ return getAngularVelocity();
+}
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::getGround()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::getGround(const LLVector3 &in_pos_agent, LLVector3 &out_pos_agent, LLVector3 &outNorm)
+{
+ LLVector3d z_vec(0.0f, 0.0f, 1.0f);
+ LLVector3d p0_global, p1_global;
+
+ if (gNoRender || mIsDummy)
+ {
+ outNorm.setVec(z_vec);
+ out_pos_agent = in_pos_agent;
+ return;
+ }
+
+ p0_global = gAgent.getPosGlobalFromAgent(in_pos_agent) + z_vec;
+ p1_global = gAgent.getPosGlobalFromAgent(in_pos_agent) - z_vec;
+ LLViewerObject *obj;
+ LLVector3d out_pos_global;
+ LLWorld::getInstance()->resolveStepHeightGlobal(this, p0_global, p1_global, out_pos_global, outNorm, &obj);
+ out_pos_agent = gAgent.getPosAgentFromGlobal(out_pos_global);
+}
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::getTimeDilation()
+//-----------------------------------------------------------------------------
+F32 LLVOAvatar::getTimeDilation()
+{
+ return mTimeDilation;
+}
+
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::getPixelArea()
+//-----------------------------------------------------------------------------
+F32 LLVOAvatar::getPixelArea() const
+{
+ if (mIsDummy)
+ {
+ return 100000.f;
+ }
+ return mPixelArea;
+}
+
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::getHeadMesh()
+//-----------------------------------------------------------------------------
+LLPolyMesh* LLVOAvatar::getHeadMesh()
+{
+ return mMeshLOD[MESH_ID_HEAD]->mMeshParts[0]->getMesh();
+}
+
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::getUpperBodyMesh()
+//-----------------------------------------------------------------------------
+LLPolyMesh* LLVOAvatar::getUpperBodyMesh()
+{
+ return mMeshLOD[MESH_ID_UPPER_BODY]->mMeshParts[0]->getMesh();
+}
+
+
+//-----------------------------------------------------------------------------
+// LLVOAvatar::getPosGlobalFromAgent()
+//-----------------------------------------------------------------------------
+LLVector3d LLVOAvatar::getPosGlobalFromAgent(const LLVector3 &position)
+{
+ return gAgent.getPosGlobalFromAgent(position);
+}
+
+//-----------------------------------------------------------------------------
+// getPosAgentFromGlobal()
+//-----------------------------------------------------------------------------
+LLVector3 LLVOAvatar::getPosAgentFromGlobal(const LLVector3d &position)
+{
+ return gAgent.getPosAgentFromGlobal(position);
+}
+
+//-----------------------------------------------------------------------------
+// allocateCharacterJoints()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::allocateCharacterJoints( U32 num )
+{
+ deleteAndClearArray(mSkeleton);
+ mNumJoints = 0;
+
+ mSkeleton = new LLViewerJoint[num];
+
+ for(S32 joint_num = 0; joint_num < (S32)num; joint_num++)
+ {
+ mSkeleton[joint_num].setJointNum(joint_num);
+ }
+
+ if (!mSkeleton)
+ {
+ return FALSE;
+ }
+
+ mNumJoints = num;
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// allocateCollisionVolumes()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::allocateCollisionVolumes( U32 num )
+{
+ deleteAndClearArray(mCollisionVolumes);
+ mNumCollisionVolumes = 0;
+
+ mCollisionVolumes = new LLViewerJointCollisionVolume[num];
+ if (!mCollisionVolumes)
+ {
+ return FALSE;
+ }
+
+ mNumCollisionVolumes = num;
+ return TRUE;
+}
+
+
+//-----------------------------------------------------------------------------
+// getCharacterJoint()
+//-----------------------------------------------------------------------------
+LLJoint *LLVOAvatar::getCharacterJoint( U32 num )
+{
+ if ((S32)num >= mNumJoints
+ || (S32)num < 0)
+ {
+ return NULL;
+ }
+ return (LLJoint*)&mSkeleton[num];
+}
+
+//-----------------------------------------------------------------------------
+// requestStopMotion()
+//-----------------------------------------------------------------------------
+// virtual
+void LLVOAvatar::requestStopMotion( LLMotion* motion )
+{
+ // Only agent avatars should handle the stop motion notifications.
+}
+
+//-----------------------------------------------------------------------------
+// loadAvatar()
+//-----------------------------------------------------------------------------
+static LLFastTimer::DeclareTimer FTM_LOAD_AVATAR("Load Avatar");
+
+BOOL LLVOAvatar::loadAvatar()
+{
+// LLFastTimer t(FTM_LOAD_AVATAR);
+
+ // avatar_skeleton.xml
+ if( !buildSkeleton(sAvatarSkeletonInfo) )
+ {
+ llwarns << "avatar file: buildSkeleton() failed" << llendl;
+ return FALSE;
+ }
+
+ // avatar_lad.xml : <skeleton>
+ if( !loadSkeletonNode() )
+ {
+ llwarns << "avatar file: loadNodeSkeleton() failed" << llendl;
+ return FALSE;
+ }
+
+ // avatar_lad.xml : <mesh>
+ if( !loadMeshNodes() )
+ {
+ llwarns << "avatar file: loadNodeMesh() failed" << llendl;
+ return FALSE;
+ }
+
+ // avatar_lad.xml : <global_color>
+ if( sAvatarXmlInfo->mTexSkinColorInfo )
+ {
+ mTexSkinColor = new LLTexGlobalColor( this );
+ if( !mTexSkinColor->setInfo( sAvatarXmlInfo->mTexSkinColorInfo ) )
+ {
+ llwarns << "avatar file: mTexSkinColor->setInfo() failed" << llendl;
+ return FALSE;
+ }
+ }
+ else
+ {
+ llwarns << "<global_color> name=\"skin_color\" not found" << llendl;
+ return FALSE;
+ }
+ if( sAvatarXmlInfo->mTexHairColorInfo )
+ {
+ mTexHairColor = new LLTexGlobalColor( this );
+ if( !mTexHairColor->setInfo( sAvatarXmlInfo->mTexHairColorInfo ) )
+ {
+ llwarns << "avatar file: mTexHairColor->setInfo() failed" << llendl;
+ return FALSE;
+ }
+ }
+ else
+ {
+ llwarns << "<global_color> name=\"hair_color\" not found" << llendl;
+ return FALSE;
+ }
+ if( sAvatarXmlInfo->mTexEyeColorInfo )
+ {
+ mTexEyeColor = new LLTexGlobalColor( this );
+ if( !mTexEyeColor->setInfo( sAvatarXmlInfo->mTexEyeColorInfo ) )
+ {
+ llwarns << "avatar file: mTexEyeColor->setInfo() failed" << llendl;
+ return FALSE;
+ }
+ }
+ else
+ {
+ llwarns << "<global_color> name=\"eye_color\" not found" << llendl;
+ return FALSE;
+ }
+
+ // avatar_lad.xml : <layer_set>
+ if (sAvatarXmlInfo->mLayerInfoList.empty())
+ {
+ llwarns << "avatar file: missing <layer_set> node" << llendl;
+ return FALSE;
+ }
+
+ if (sAvatarXmlInfo->mMorphMaskInfoList.empty())
+ {
+ llwarns << "avatar file: missing <morph_masks> node" << llendl;
+ return FALSE;
+ }
+
+ // avatar_lad.xml : <morph_masks>
+ for (LLVOAvatarXmlInfo::morph_info_list_t::iterator iter = sAvatarXmlInfo->mMorphMaskInfoList.begin();
+ iter != sAvatarXmlInfo->mMorphMaskInfoList.end();
+ ++iter)
+ {
+ LLVOAvatarXmlInfo::LLVOAvatarMorphInfo *info = *iter;
+
+ EBakedTextureIndex baked = LLVOAvatarDictionary::findBakedByRegionName(info->mRegion);
+ if (baked != BAKED_NUM_INDICES)
+ {
+ LLPolyMorphTarget *morph_param;
+ const std::string *name = &info->mName;
+ morph_param = (LLPolyMorphTarget *)(getVisualParam(name->c_str()));
+ if (morph_param)
+ {
+ BOOL invert = info->mInvert;
+ addMaskedMorph(baked, morph_param, invert, info->mLayer);
+ }
+ }
+
+ }
+
+ loadLayersets();
+
+ // avatar_lad.xml : <driver_parameters>
+ for (LLVOAvatarXmlInfo::driver_info_list_t::iterator iter = sAvatarXmlInfo->mDriverInfoList.begin();
+ iter != sAvatarXmlInfo->mDriverInfoList.end();
+ ++iter)
+ {
+ LLDriverParamInfo *info = *iter;
+ LLDriverParam* driver_param = new LLDriverParam( this );
+ if (driver_param->setInfo(info))
+ {
+ addVisualParam( driver_param );
+ LLVisualParam*(LLVOAvatar::*avatar_function)(S32)const = &LLVOAvatar::getVisualParam;
+ if( !driver_param->linkDrivenParams(boost::bind(avatar_function,(LLVOAvatar*)this,_1 ), false))
+ {
+ llwarns << "could not link driven params for avatar " << this->getFullname() << " id: " << driver_param->getID() << llendl;
+ continue;
+ }
+ }
+ else
+ {
+ delete driver_param;
+ llwarns << "avatar file: driver_param->parseData() failed" << llendl;
+ return FALSE;
+ }
+ }
+
+ // Uncomment to enable avatar_lad.xml debugging.
+ std::ofstream file;
+ file.open("avatar_lad.log");
+ for( LLViewerVisualParam* param = (LLViewerVisualParam*) getFirstVisualParam();
+ param;
+ param = (LLViewerVisualParam*) getNextVisualParam() )
+ {
+ param->getInfo()->toStream(file);
+ file << std::endl;
+ }
+
+ file.close();
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// loadSkeletonNode(): loads <skeleton> node from XML tree
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::loadSkeletonNode ()
+{
+ mRoot.addChild( &mSkeleton[0] );
+
+ for (std::vector<LLViewerJoint *>::iterator iter = mMeshLOD.begin();
+ iter != mMeshLOD.end();
+ ++iter)
+ {
+ LLViewerJoint *joint = (LLViewerJoint *) *iter;
+ joint->mUpdateXform = FALSE;
+ joint->setMeshesToChildren();
+ }
+
+ mRoot.addChild(mMeshLOD[MESH_ID_HEAD]);
+ mRoot.addChild(mMeshLOD[MESH_ID_EYELASH]);
+ mRoot.addChild(mMeshLOD[MESH_ID_UPPER_BODY]);
+ mRoot.addChild(mMeshLOD[MESH_ID_LOWER_BODY]);
+ mRoot.addChild(mMeshLOD[MESH_ID_SKIRT]);
+ mRoot.addChild(mMeshLOD[MESH_ID_HEAD]);
+
+ LLViewerJoint *skull = (LLViewerJoint*)mRoot.findJoint("mSkull");
+ if (skull)
+ {
+ skull->addChild(mMeshLOD[MESH_ID_HAIR] );
+ }
+
+ LLViewerJoint *eyeL = (LLViewerJoint*)mRoot.findJoint("mEyeLeft");
+ if (eyeL)
+ {
+ eyeL->addChild( mMeshLOD[MESH_ID_EYEBALL_LEFT] );
+ }
+
+ LLViewerJoint *eyeR = (LLViewerJoint*)mRoot.findJoint("mEyeRight");
+ if (eyeR)
+ {
+ eyeR->addChild( mMeshLOD[MESH_ID_EYEBALL_RIGHT] );
+ }
+
+ // SKELETAL DISTORTIONS
+ {
+ LLVOAvatarXmlInfo::skeletal_distortion_info_list_t::iterator iter;
+ for (iter = sAvatarXmlInfo->mSkeletalDistortionInfoList.begin();
+ iter != sAvatarXmlInfo->mSkeletalDistortionInfoList.end();
+ ++iter)
+ {
+ LLPolySkeletalDistortionInfo *info = *iter;
+ LLPolySkeletalDistortion *param = new LLPolySkeletalDistortion(this);
+ if (!param->setInfo(info))
+ {
+ delete param;
+ return FALSE;
+ }
+ else
+ {
+ addVisualParam(param);
+ }
+ }
+ }
+
+ // ATTACHMENTS
+ {
+ LLVOAvatarXmlInfo::attachment_info_list_t::iterator iter;
+ for (iter = sAvatarXmlInfo->mAttachmentInfoList.begin();
+ iter != sAvatarXmlInfo->mAttachmentInfoList.end();
+ ++iter)
+ {
+ LLVOAvatarXmlInfo::LLVOAvatarAttachmentInfo *info = *iter;
+ if (!isSelf() && info->mJointName == "mScreen")
+ { //don't process screen joint for other avatars
+ continue;
+ }
+
+ LLViewerJointAttachment* attachment = new LLViewerJointAttachment();
+
+ attachment->setName(info->mName);
+ LLJoint *parentJoint = getJoint(info->mJointName);
+ if (!parentJoint)
+ {
+ llwarns << "No parent joint by name " << info->mJointName << " found for attachment point " << info->mName << llendl;
+ delete attachment;
+ continue;
+ }
+
+ if (info->mHasPosition)
+ {
+ attachment->setOriginalPosition(info->mPosition);
+ }
+
+ if (info->mHasRotation)
+ {
+ LLQuaternion rotation;
+ rotation.setQuat(info->mRotationEuler.mV[VX] * DEG_TO_RAD,
+ info->mRotationEuler.mV[VY] * DEG_TO_RAD,
+ info->mRotationEuler.mV[VZ] * DEG_TO_RAD);
+ attachment->setRotation(rotation);
+ }
+
+ int group = info->mGroup;
+ if (group >= 0)
+ {
+ if (group < 0 || group >= 9)
+ {
+ llwarns << "Invalid group number (" << group << ") for attachment point " << info->mName << llendl;
+ }
+ else
+ {
+ attachment->setGroup(group);
+ }
+ }
+
+ S32 attachmentID = info->mAttachmentID;
+ if (attachmentID < 1 || attachmentID > 255)
+ {
+ llwarns << "Attachment point out of range [1-255]: " << attachmentID << " on attachment point " << info->mName << llendl;
+ delete attachment;
+ continue;
+ }
+ if (mAttachmentPoints.find(attachmentID) != mAttachmentPoints.end())
+ {
+ llwarns << "Attachment point redefined with id " << attachmentID << " on attachment point " << info->mName << llendl;
+ delete attachment;
+ continue;
+ }
+
+ attachment->setPieSlice(info->mPieMenuSlice);
+ attachment->setVisibleInFirstPerson(info->mVisibleFirstPerson);
+ attachment->setIsHUDAttachment(info->mIsHUDAttachment);
+
+ mAttachmentPoints[attachmentID] = attachment;
+
+ // now add attachment joint
+ parentJoint->addChild(attachment);
+ }
+ }
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// loadMeshNodes(): loads <mesh> nodes from XML tree
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::loadMeshNodes()
+{
+ for (LLVOAvatarXmlInfo::mesh_info_list_t::const_iterator meshinfo_iter = sAvatarXmlInfo->mMeshInfoList.begin();
+ meshinfo_iter != sAvatarXmlInfo->mMeshInfoList.end();
+ ++meshinfo_iter)
+ {
+ const LLVOAvatarXmlInfo::LLVOAvatarMeshInfo *info = *meshinfo_iter;
+ const std::string &type = info->mType;
+ S32 lod = info->mLOD;
+
+ LLViewerJointMesh* mesh = NULL;
+ U8 mesh_id = 0;
+ BOOL found_mesh_id = FALSE;
+
+ /* if (type == "hairMesh")
+ switch(lod)
+ case 0:
+ mesh = &mHairMesh0; */
+ for (LLVOAvatarDictionary::Meshes::const_iterator mesh_iter = LLVOAvatarDictionary::getInstance()->getMeshes().begin();
+ mesh_iter != LLVOAvatarDictionary::getInstance()->getMeshes().end();
+ ++mesh_iter)
+ {
+ const EMeshIndex mesh_index = mesh_iter->first;
+ const LLVOAvatarDictionary::MeshEntry *mesh_dict = mesh_iter->second;
+ if (type.compare(mesh_dict->mName) == 0)
+ {
+ mesh_id = mesh_index;
+ found_mesh_id = TRUE;
+ break;
+ }
+ }
+
+ if (found_mesh_id)
+ {
+ if (lod < (S32)mMeshLOD[mesh_id]->mMeshParts.size())
+ {
+ mesh = mMeshLOD[mesh_id]->mMeshParts[lod];
+ }
+ else
+ {
+ llwarns << "Avatar file: <mesh> has invalid lod setting " << lod << llendl;
+ return FALSE;
+ }
+ }
+ else
+ {
+ llwarns << "Ignoring unrecognized mesh type: " << type << llendl;
+ return FALSE;
+ }
+
+ // llinfos << "Parsing mesh data for " << type << "..." << llendl;
+
+ // If this isn't set to white (1.0), avatars will *ALWAYS* be darker than their surroundings.
+ // Do not touch!!!
+ mesh->setColor( 1.0f, 1.0f, 1.0f, 1.0f );
+
+ LLPolyMesh *poly_mesh = NULL;
+
+ if (!info->mReferenceMeshName.empty())
+ {
+ polymesh_map_t::const_iterator polymesh_iter = mMeshes.find(info->mReferenceMeshName);
+ if (polymesh_iter != mMeshes.end())
+ {
+ poly_mesh = LLPolyMesh::getMesh(info->mMeshFileName, polymesh_iter->second);
+ poly_mesh->setAvatar(this);
+ }
+ else
+ {
+ // This should never happen
+ LL_WARNS("Avatar") << "Could not find avatar mesh: " << info->mReferenceMeshName << LL_ENDL;
+ }
+ }
+ else
+ {
+ poly_mesh = LLPolyMesh::getMesh(info->mMeshFileName);
+ poly_mesh->setAvatar(this);
+ }
+
+ if( !poly_mesh )
+ {
+ llwarns << "Failed to load mesh of type " << type << llendl;
+ return FALSE;
+ }
+
+ // Multimap insert
+ mMeshes.insert(std::make_pair(info->mMeshFileName, poly_mesh));
+
+ mesh->setMesh( poly_mesh );
+ mesh->setLOD( info->mMinPixelArea );
+
+ for (LLVOAvatarXmlInfo::LLVOAvatarMeshInfo::morph_info_list_t::const_iterator xmlinfo_iter = info->mPolyMorphTargetInfoList.begin();
+ xmlinfo_iter != info->mPolyMorphTargetInfoList.end();
+ ++xmlinfo_iter)
+ {
+ const LLVOAvatarXmlInfo::LLVOAvatarMeshInfo::morph_info_pair_t *info_pair = &(*xmlinfo_iter);
+ LLPolyMorphTarget *param = new LLPolyMorphTarget(mesh->getMesh());
+ if (!param->setInfo(info_pair->first))
+ {
+ delete param;
+ return FALSE;
+ }
+ else
+ {
+ if (info_pair->second)
+ {
+ addSharedVisualParam(param);
+ }
+ else
+ {
+ addVisualParam(param);
+ }
+ }
+ }
+ }
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// loadLayerSets()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::loadLayersets()
+{
+ BOOL success = TRUE;
+ for (LLVOAvatarXmlInfo::layer_info_list_t::const_iterator layerset_iter = sAvatarXmlInfo->mLayerInfoList.begin();
+ layerset_iter != sAvatarXmlInfo->mLayerInfoList.end();
+ ++layerset_iter)
+ {
+ // Construct a layerset for each one specified in avatar_lad.xml and initialize it as such.
+ LLTexLayerSetInfo *layerset_info = *layerset_iter;
+ layerset_info->createVisualParams(this);
+ }
+ return success;
+}
+
+//-----------------------------------------------------------------------------
+// updateVisualParams()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::updateVisualParams()
+{
+ if (gNoRender)
+ {
+ return;
+ }
+
+ setSex( (getVisualParamWeight( "male" ) > 0.5f) ? SEX_MALE : SEX_FEMALE );
+
+ LLCharacter::updateVisualParams();
+
+ if (mLastSkeletonSerialNum != mSkeletonSerialNum)
+ {
+ computeBodySize();
+ mLastSkeletonSerialNum = mSkeletonSerialNum;
+ mRoot.updateWorldMatrixChildren();
+ }
+
+ dirtyMesh();
+ updateHeadOffset();
+}
+
+//-----------------------------------------------------------------------------
+// isActive()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::isActive() const
+{
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// setPixelAreaAndAngle()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::setPixelAreaAndAngle(LLAgent &agent)
+{
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+ if (mDrawable.isNull())
+ {
+ return;
+ }
+
+ const LLVector4a* ext = mDrawable->getSpatialExtents();
+ LLVector4a center;
+ center.setAdd(ext[1], ext[0]);
+ center.mul(0.5f);
+ LLVector4a size;
+ size.setSub(ext[1], ext[0]);
+ size.mul(0.5f);
+
+ mImpostorPixelArea = LLPipeline::calcPixelArea(center, size, *LLViewerCamera::getInstance());
+
+ F32 range = mDrawable->mDistanceWRTCamera;
+
+ if (range < 0.001f) // range == zero
+ {
+ mAppAngle = 180.f;
+ }
+ else
+ {
+ F32 radius = size.getLength3().getF32();
+ mAppAngle = (F32) atan2( radius, range) * RAD_TO_DEG;
+ }
+
+ // We always want to look good to ourselves
+ if( isSelf() )
+ {
+ mPixelArea = llmax( mPixelArea, F32(getTexImageSize() / 16) );
+ }
+}
+
+//-----------------------------------------------------------------------------
+// updateJointLODs()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::updateJointLODs()
+{
+ const F32 MAX_PIXEL_AREA = 100000000.f;
+ F32 lod_factor = (sLODFactor * AVATAR_LOD_TWEAK_RANGE + (1.f - AVATAR_LOD_TWEAK_RANGE));
+ F32 avatar_num_min_factor = clamp_rescale(sLODFactor, 0.f, 1.f, 0.25f, 0.6f);
+ F32 avatar_num_factor = clamp_rescale((F32)sNumVisibleAvatars, 8, 25, 1.f, avatar_num_min_factor);
+ F32 area_scale = 0.16f;
+
+ {
+ if (isSelf())
+ {
+ if(gAgentCamera.cameraCustomizeAvatar() || gAgentCamera.cameraMouselook())
+ {
+ mAdjustedPixelArea = MAX_PIXEL_AREA;
+ }
+ else
+ {
+ mAdjustedPixelArea = mPixelArea*area_scale;
+ }
+ }
+ else if (mIsDummy)
+ {
+ mAdjustedPixelArea = MAX_PIXEL_AREA;
+ }
+ else
+ {
+ // reported avatar pixel area is dependent on avatar render load, based on number of visible avatars
+ mAdjustedPixelArea = (F32)mPixelArea * area_scale * lod_factor * lod_factor * avatar_num_factor * avatar_num_factor;
+ }
+
+ // now select meshes to render based on adjusted pixel area
+ BOOL res = mRoot.updateLOD(mAdjustedPixelArea, TRUE);
+ if (res)
+ {
+ sNumLODChangesThisFrame++;
+ dirtyMesh(2);
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+}
+
+//-----------------------------------------------------------------------------
+// createDrawable()
+//-----------------------------------------------------------------------------
+LLDrawable *LLVOAvatar::createDrawable(LLPipeline *pipeline)
+{
+ pipeline->allocDrawable(this);
+ mDrawable->setLit(FALSE);
+
+ LLDrawPoolAvatar *poolp = (LLDrawPoolAvatar*) gPipeline.getPool(LLDrawPool::POOL_AVATAR);
+
+ // Only a single face (one per avatar)
+ //this face will be splitted into several if its vertex buffer is too long.
+ mDrawable->setState(LLDrawable::ACTIVE);
+ mDrawable->addFace(poolp, NULL);
+ mDrawable->setRenderType(LLPipeline::RENDER_TYPE_AVATAR);
+
+ mNumInitFaces = mDrawable->getNumFaces() ;
+
+ dirtyMesh(2);
+ return mDrawable;
+}
+
+
+void LLVOAvatar::updateGL()
+{
+ if (mMeshTexturesDirty)
+ {
+ updateMeshTextures();
+ mMeshTexturesDirty = FALSE;
+ }
+}
+
+//-----------------------------------------------------------------------------
+// updateGeometry()
+//-----------------------------------------------------------------------------
+static LLFastTimer::DeclareTimer FTM_UPDATE_AVATAR("Update Avatar");
+BOOL LLVOAvatar::updateGeometry(LLDrawable *drawable)
+{
+ LLFastTimer ftm(FTM_UPDATE_AVATAR);
+ if (!(gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_AVATAR)))
+ {
+ return TRUE;
+ }
+
+ if (!mMeshValid)
+ {
+ return TRUE;
+ }
+
+ if (!drawable)
+ {
+ llerrs << "LLVOAvatar::updateGeometry() called with NULL drawable" << llendl;
+ }
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// updateSexDependentLayerSets()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::updateSexDependentLayerSets( BOOL upload_bake )
+{
+ invalidateComposite( mBakedTextureDatas[BAKED_HEAD].mTexLayerSet, upload_bake );
+ invalidateComposite( mBakedTextureDatas[BAKED_UPPER].mTexLayerSet, upload_bake );
+ invalidateComposite( mBakedTextureDatas[BAKED_LOWER].mTexLayerSet, upload_bake );
+}
+
+//-----------------------------------------------------------------------------
+// dirtyMesh()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::dirtyMesh()
+{
+ dirtyMesh(1);
+}
+void LLVOAvatar::dirtyMesh(S32 priority)
+{
+ mDirtyMesh = llmax(mDirtyMesh, priority);
+}
+//-----------------------------------------------------------------------------
+// hideSkirt()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::hideSkirt()
+{
+ mMeshLOD[MESH_ID_SKIRT]->setVisible(FALSE, TRUE);
+}
+
+BOOL LLVOAvatar::setParent(LLViewerObject* parent)
+{
+ BOOL ret ;
+ if (parent == NULL)
+ {
+ getOffObject();
+ ret = LLViewerObject::setParent(parent);
+ if (isSelf())
+ {
+ gAgentCamera.resetCamera();
+ }
+ }
+ else
+ {
+ ret = LLViewerObject::setParent(parent);
+ if(ret)
+ {
+ sitOnObject(parent);
+ }
+ }
+ return ret ;
+}
+
+void LLVOAvatar::addChild(LLViewerObject *childp)
+{
+ childp->extractAttachmentItemID(); // find the inventory item this object is associated with.
+ LLViewerObject::addChild(childp);
+ if (childp->mDrawable)
+ {
+ attachObject(childp);
+ }
+ else
+ {
+ mPendingAttachment.push_back(childp);
+ }
+}
+
+void LLVOAvatar::removeChild(LLViewerObject *childp)
+{
+ LLViewerObject::removeChild(childp);
+ if (!detachObject(childp))
+ {
+ llwarns << "Calling detach on non-attached object " << llendl;
+ }
+}
+
+LLViewerJointAttachment* LLVOAvatar::getTargetAttachmentPoint(LLViewerObject* viewer_object)
+{
+ S32 attachmentID = ATTACHMENT_ID_FROM_STATE(viewer_object->getState());
+
+ // This should never happen unless the server didn't process the attachment point
+ // correctly, but putting this check in here to be safe.
+ if (attachmentID & ATTACHMENT_ADD)
+ {
+ llwarns << "Got an attachment with ATTACHMENT_ADD mask, removing ( attach pt:" << attachmentID << " )" << llendl;
+ attachmentID &= ~ATTACHMENT_ADD;
+ }
+
+ LLViewerJointAttachment* attachment = get_if_there(mAttachmentPoints, attachmentID, (LLViewerJointAttachment*)NULL);
+
+ if (!attachment)
+ {
+ llwarns << "Object attachment point invalid: " << attachmentID << llendl;
+ attachment = get_if_there(mAttachmentPoints, 1, (LLViewerJointAttachment*)NULL); // Arbitrary using 1 (chest)
+ }
+
+ return attachment;
+}
+
+//-----------------------------------------------------------------------------
+// attachObject()
+//-----------------------------------------------------------------------------
+const LLViewerJointAttachment *LLVOAvatar::attachObject(LLViewerObject *viewer_object)
+{
+ LLViewerJointAttachment* attachment = getTargetAttachmentPoint(viewer_object);
+
+ if (!attachment || !attachment->addObject(viewer_object))
+ {
+ return 0;
+ }
+
+ if (viewer_object->isSelected())
+ {
+ LLSelectMgr::getInstance()->updateSelectionCenter();
+ LLSelectMgr::getInstance()->updatePointAt();
+ }
+
+ return attachment;
+}
+
+//-----------------------------------------------------------------------------
+// attachObject()
+//-----------------------------------------------------------------------------
+U32 LLVOAvatar::getNumAttachments() const
+{
+ U32 num_attachments = 0;
+ for (attachment_map_t::const_iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ const LLViewerJointAttachment *attachment_pt = (*iter).second;
+ num_attachments += attachment_pt->getNumObjects();
+ }
+ return num_attachments;
+}
+
+//-----------------------------------------------------------------------------
+// canAttachMoreObjects()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::canAttachMoreObjects() const
+{
+ return (getNumAttachments() < MAX_AGENT_ATTACHMENTS);
+}
+
+//-----------------------------------------------------------------------------
+// canAttachMoreObjects()
+// Returns true if we can attach <n> more objects.
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::canAttachMoreObjects(U32 n) const
+{
+ return (getNumAttachments() + n) <= MAX_AGENT_ATTACHMENTS;
+}
+
+//-----------------------------------------------------------------------------
+// lazyAttach()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::lazyAttach()
+{
+ std::vector<LLPointer<LLViewerObject> > still_pending;
+
+ for (U32 i = 0; i < mPendingAttachment.size(); i++)
+ {
+ if (mPendingAttachment[i]->mDrawable)
+ {
+ attachObject(mPendingAttachment[i]);
+ }
+ else
+ {
+ still_pending.push_back(mPendingAttachment[i]);
+ }
+ }
+
+ mPendingAttachment = still_pending;
+}
+
+void LLVOAvatar::resetHUDAttachments()
+{
+ for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+ if (attachment->getIsHUDAttachment())
+ {
+ for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
+ attachment_iter != attachment->mAttachedObjects.end();
+ ++attachment_iter)
+ {
+ const LLViewerObject* attached_object = (*attachment_iter);
+ if (attached_object && attached_object->mDrawable.notNull())
+ {
+ gPipeline.markMoved(attached_object->mDrawable);
+ }
+ }
+ }
+ }
+}
+
+void LLVOAvatar::rebuildRiggedAttachments( void )
+{
+ for ( attachment_map_t::iterator iter = mAttachmentPoints.begin(); iter != mAttachmentPoints.end(); ++iter )
+ {
+ LLViewerJointAttachment* pAttachment = iter->second;
+ LLViewerJointAttachment::attachedobjs_vec_t::iterator attachmentIterEnd = pAttachment->mAttachedObjects.end();
+
+ for ( LLViewerJointAttachment::attachedobjs_vec_t::iterator attachmentIter = pAttachment->mAttachedObjects.begin();
+ attachmentIter != attachmentIterEnd; ++attachmentIter)
+ {
+ const LLViewerObject* pAttachedObject = *attachmentIter;
+ if ( pAttachment && pAttachedObject->mDrawable.notNull() )
+ {
+ gPipeline.markRebuild(pAttachedObject->mDrawable);
+ }
+ }
+ }
+}
+//-----------------------------------------------------------------------------
+// cleanupAttachedMesh()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::cleanupAttachedMesh( LLViewerObject* pVO )
+{
+ //If a VO has a skin that we'll reset the joint positions to their default
+ if ( pVO && pVO->mDrawable )
+ {
+ LLVOVolume* pVObj = pVO->mDrawable->getVOVolume();
+ if ( pVObj )
+ {
+ const LLMeshSkinInfo* pSkinData = gMeshRepo.getSkinInfo( pVObj->getVolume()->getParams().getSculptID() );
+ if ( pSkinData )
+ {
+ const int jointCnt = pSkinData->mJointNames.size();
+ bool fullRig = ( jointCnt>=20 ) ? true : false;
+ if ( fullRig )
+ {
+ const int bindCnt = pSkinData->mAlternateBindMatrix.size();
+ if ( bindCnt > 0 )
+ {
+ LLVOAvatar::resetJointPositionsToDefault();
+ }
+ }
+ }
+ }
+ }
+}
+//-----------------------------------------------------------------------------
+// detachObject()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::detachObject(LLViewerObject *viewer_object)
+{
+ for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+
+ if (attachment->isObjectAttached(viewer_object))
+ {
+ cleanupAttachedMesh( viewer_object );
+ attachment->removeObject(viewer_object);
+ lldebugs << "Detaching object " << viewer_object->mID << " from " << attachment->getName() << llendl;
+ return TRUE;
+ }
+ }
+
+ std::vector<LLPointer<LLViewerObject> >::iterator iter = std::find(mPendingAttachment.begin(), mPendingAttachment.end(), viewer_object);
+ if (iter != mPendingAttachment.end())
+ {
+ mPendingAttachment.erase(iter);
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+//-----------------------------------------------------------------------------
+// sitDown()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::sitDown(BOOL bSitting)
+{
+ mIsSitting = bSitting;
+ if (isSelf())
+ {
+ // Update Movement Controls according to own Sitting mode
+ LLFloaterMove::setSittingMode(bSitting);
+ }
+}
+
+//-----------------------------------------------------------------------------
+// sitOnObject()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::sitOnObject(LLViewerObject *sit_object)
+{
+ if (isSelf())
+ {
+ // Might be first sit
+ //LLFirstUse::useSit();
+
+ gAgent.setFlying(FALSE);
+ gAgentCamera.setThirdPersonHeadOffset(LLVector3::zero);
+ //interpolate to new camera position
+ gAgentCamera.startCameraAnimation();
+ // make sure we are not trying to autopilot
+ gAgent.stopAutoPilot();
+ gAgentCamera.setupSitCamera();
+ if (gAgentCamera.getForceMouselook())
+ {
+ gAgentCamera.changeCameraToMouselook();
+ }
+ }
+
+ if (mDrawable.isNull())
+ {
+ return;
+ }
+ LLQuaternion inv_obj_rot = ~sit_object->getRenderRotation();
+ LLVector3 obj_pos = sit_object->getRenderPosition();
+
+ LLVector3 rel_pos = getRenderPosition() - obj_pos;
+ rel_pos.rotVec(inv_obj_rot);
+
+ mDrawable->mXform.setPosition(rel_pos);
+ mDrawable->mXform.setRotation(mDrawable->getWorldRotation() * inv_obj_rot);
+
+ gPipeline.markMoved(mDrawable, TRUE);
+ // Notice that removing sitDown() from here causes avatars sitting on
+ // objects to be not rendered for new arrivals. See EXT-6835 and EXT-1655.
+ sitDown(TRUE);
+ mRoot.getXform()->setParent(&sit_object->mDrawable->mXform); // LLVOAvatar::sitOnObject
+ mRoot.setPosition(getPosition());
+ mRoot.updateWorldMatrixChildren();
+
+ stopMotion(ANIM_AGENT_BODY_NOISE);
+
+}
+
+//-----------------------------------------------------------------------------
+// getOffObject()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::getOffObject()
+{
+ if (mDrawable.isNull())
+ {
+ return;
+ }
+
+ LLViewerObject* sit_object = (LLViewerObject*)getParent();
+
+ if (sit_object)
+ {
+ stopMotionFromSource(sit_object->getID());
+ LLFollowCamMgr::setCameraActive(sit_object->getID(), FALSE);
+
+ LLViewerObject::const_child_list_t& child_list = sit_object->getChildren();
+ for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
+ iter != child_list.end(); ++iter)
+ {
+ LLViewerObject* child_objectp = *iter;
+
+ stopMotionFromSource(child_objectp->getID());
+ LLFollowCamMgr::setCameraActive(child_objectp->getID(), FALSE);
+ }
+ }
+
+ // assumes that transform will not be updated with drawable still having a parent
+ LLVector3 cur_position_world = mDrawable->getWorldPosition();
+ LLQuaternion cur_rotation_world = mDrawable->getWorldRotation();
+
+ // set *local* position based on last *world* position, since we're unparenting the avatar
+ mDrawable->mXform.setPosition(cur_position_world);
+ mDrawable->mXform.setRotation(cur_rotation_world);
+
+ gPipeline.markMoved(mDrawable, TRUE);
+
+ sitDown(FALSE);
+
+ mRoot.getXform()->setParent(NULL); // LLVOAvatar::getOffObject
+ mRoot.setPosition(cur_position_world);
+ mRoot.setRotation(cur_rotation_world);
+ mRoot.getXform()->update();
+
+ startMotion(ANIM_AGENT_BODY_NOISE);
+
+ if (isSelf())
+ {
+ LLQuaternion av_rot = gAgent.getFrameAgent().getQuaternion();
+ LLQuaternion obj_rot = sit_object ? sit_object->getRenderRotation() : LLQuaternion::DEFAULT;
+ av_rot = av_rot * obj_rot;
+ LLVector3 at_axis = LLVector3::x_axis;
+ at_axis = at_axis * av_rot;
+ at_axis.mV[VZ] = 0.f;
+ at_axis.normalize();
+ gAgent.resetAxes(at_axis);
+
+ //reset orientation
+// mRoot.setRotation(avWorldRot);
+ gAgentCamera.setThirdPersonHeadOffset(LLVector3(0.f, 0.f, 1.f));
+
+ gAgentCamera.setSitCamera(LLUUID::null);
+ }
+}
+
+//-----------------------------------------------------------------------------
+// findAvatarFromAttachment()
+//-----------------------------------------------------------------------------
+// static
+LLVOAvatar* LLVOAvatar::findAvatarFromAttachment( LLViewerObject* obj )
+{
+ if( obj->isAttachment() )
+ {
+ do
+ {
+ obj = (LLViewerObject*) obj->getParent();
+ }
+ while( obj && !obj->isAvatar() );
+
+ if( obj && !obj->isDead() )
+ {
+ return (LLVOAvatar*)obj;
+ }
+ }
+ return NULL;
+}
+
+// warning: order(N) not order(1)
+S32 LLVOAvatar::getAttachmentCount()
+{
+ S32 count = mAttachmentPoints.size();
+ return count;
+}
+
+LLColor4 LLVOAvatar::getGlobalColor( const std::string& color_name ) const
+{
+ if (color_name=="skin_color" && mTexSkinColor)
+ {
+ return mTexSkinColor->getColor();
+ }
+ else if(color_name=="hair_color" && mTexHairColor)
+ {
+ return mTexHairColor->getColor();
+ }
+ if(color_name=="eye_color" && mTexEyeColor)
+ {
+ return mTexEyeColor->getColor();
+ }
+ else
+ {
+// return LLColor4( .5f, .5f, .5f, .5f );
+ return LLColor4( 0.f, 1.f, 1.f, 1.f ); // good debugging color
+ }
+}
+
+// virtual
+void LLVOAvatar::invalidateComposite( LLTexLayerSet* layerset, BOOL upload_result )
+{
+}
+
+void LLVOAvatar::invalidateAll()
+{
+}
+
+void LLVOAvatar::onGlobalColorChanged(const LLTexGlobalColor* global_color, BOOL upload_bake )
+{
+ if (global_color == mTexSkinColor)
+ {
+ invalidateComposite( mBakedTextureDatas[BAKED_HEAD].mTexLayerSet, upload_bake );
+ invalidateComposite( mBakedTextureDatas[BAKED_UPPER].mTexLayerSet, upload_bake );
+ invalidateComposite( mBakedTextureDatas[BAKED_LOWER].mTexLayerSet, upload_bake );
+ }
+ else if (global_color == mTexHairColor)
+ {
+ invalidateComposite( mBakedTextureDatas[BAKED_HEAD].mTexLayerSet, upload_bake );
+ invalidateComposite( mBakedTextureDatas[BAKED_HAIR].mTexLayerSet, upload_bake );
+
+ // ! BACKWARDS COMPATIBILITY !
+ // Fix for dealing with avatars from viewers that don't bake hair.
+ if (!isTextureDefined(mBakedTextureDatas[BAKED_HAIR].mTextureIndex))
+ {
+ LLColor4 color = mTexHairColor->getColor();
+ for (U32 i = 0; i < mBakedTextureDatas[BAKED_HAIR].mMeshes.size(); i++)
+ {
+ mBakedTextureDatas[BAKED_HAIR].mMeshes[i]->setColor( color.mV[VX], color.mV[VY], color.mV[VZ], color.mV[VW] );
+ }
+ }
+ }
+ else if (global_color == mTexEyeColor)
+ {
+// llinfos << "invalidateComposite cause: onGlobalColorChanged( eyecolor )" << llendl;
+ invalidateComposite( mBakedTextureDatas[BAKED_EYES].mTexLayerSet, upload_bake );
+ }
+ updateMeshTextures();
+}
+
+BOOL LLVOAvatar::isVisible() const
+{
+ return mDrawable.notNull()
+ && (mDrawable->isVisible() || mIsDummy);
+}
+
+// Determine if we have enough avatar data to render
+BOOL LLVOAvatar::getIsCloud()
+{
+ // Do we have a shape?
+ if (visualParamWeightsAreDefault())
+ {
+ return TRUE;
+ }
+
+ if (!isTextureDefined(TEX_LOWER_BAKED) ||
+ !isTextureDefined(TEX_UPPER_BAKED) ||
+ !isTextureDefined(TEX_HEAD_BAKED))
+ {
+ return TRUE;
+ }
+ return FALSE;
+}
+
+// call periodically to keep isFullyLoaded up to date.
+// returns true if the value has changed.
+BOOL LLVOAvatar::updateIsFullyLoaded()
+{
+ const BOOL loading = getIsCloud();
+ updateRuthTimer(loading);
+ return processFullyLoadedChange(loading);
+}
+
+void LLVOAvatar::updateRuthTimer(bool loading)
+{
+ if (isSelf() || !loading)
+ {
+ return;
+ }
+
+ if (mPreviousFullyLoaded)
+ {
+ mRuthTimer.reset();
+ if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
+ {
+ llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' became cloud." << llendl;
+ LLSD args;
+ args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
+ args["TIME"] = llformat("%d",(U32)mRuthDebugTimer.getElapsedTimeF32());
+ args["NAME"] = getFullname();
+ LLNotificationsUtil::add("AvatarRezCloudNotification",args);
+ }
+ mRuthDebugTimer.reset();
+ }
+
+ const F32 LOADING_TIMEOUT__SECONDS = 120.f;
+ if (mRuthTimer.getElapsedTimeF32() > LOADING_TIMEOUT__SECONDS)
+ {
+ llinfos << "Ruth Timer timeout: Missing texture data for '" << getFullname() << "' "
+ << "( Params loaded : " << !visualParamWeightsAreDefault() << " ) "
+ << "( Lower : " << isTextureDefined(TEX_LOWER_BAKED) << " ) "
+ << "( Upper : " << isTextureDefined(TEX_UPPER_BAKED) << " ) "
+ << "( Head : " << isTextureDefined(TEX_HEAD_BAKED) << " )."
+ << llendl;
+
+ LLAvatarPropertiesProcessor::getInstance()->sendAvatarTexturesRequest(getID());
+ mRuthTimer.reset();
+ }
+}
+
+BOOL LLVOAvatar::processFullyLoadedChange(bool loading)
+{
+ // we wait a little bit before giving the all clear,
+ // to let textures settle down
+ const F32 PAUSE = 1.f;
+ if (loading)
+ mFullyLoadedTimer.reset();
+
+ mFullyLoaded = (mFullyLoadedTimer.getElapsedTimeF32() > PAUSE);
+
+ if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
+ {
+ if (!mPreviousFullyLoaded && !loading && mFullyLoaded)
+ {
+ llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' resolved in " << (U32)mRuthDebugTimer.getElapsedTimeF32() << " seconds." << llendl;
+ LLSD args;
+ args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
+ args["TIME"] = llformat("%d",(U32)mRuthDebugTimer.getElapsedTimeF32());
+ args["NAME"] = getFullname();
+ LLNotificationsUtil::add("AvatarRezNotification",args);
+ }
+ }
+
+ // did our loading state "change" from last call?
+ const S32 UPDATE_RATE = 30;
+ BOOL changed =
+ ((mFullyLoaded != mPreviousFullyLoaded) || // if the value is different from the previous call
+ (!mFullyLoadedInitialized) || // if we've never been called before
+ (mFullyLoadedFrameCounter % UPDATE_RATE == 0)); // every now and then issue a change
+
+ mPreviousFullyLoaded = mFullyLoaded;
+ mFullyLoadedInitialized = TRUE;
+ mFullyLoadedFrameCounter++;
+
+ return changed;
+}
+
+BOOL LLVOAvatar::isFullyLoaded() const
+{
+ if (gSavedSettings.getBOOL("RenderUnloadedAvatar"))
+ return TRUE;
+ else
+ return mFullyLoaded;
+}
+
+
+//-----------------------------------------------------------------------------
+// findMotion()
+//-----------------------------------------------------------------------------
+LLMotion* LLVOAvatar::findMotion(const LLUUID& id) const
+{
+ return mMotionController.findMotion(id);
+}
+
+//-----------------------------------------------------------------------------
+// updateMeshTextures()
+// Uses the current TE values to set the meshes' and layersets' textures.
+//-----------------------------------------------------------------------------
+void LLVOAvatar::updateMeshTextures()
+{
+ // llinfos << "updateMeshTextures" << llendl;
+ if (gNoRender) return;
+
+ // if user has never specified a texture, assign the default
+ for (U32 i=0; i < getNumTEs(); i++)
+ {
+ const LLViewerTexture* te_image = getImage(i, 0);
+ if(!te_image || te_image->getID().isNull() || (te_image->getID() == IMG_DEFAULT))
+ {
+ setImage(i, LLViewerTextureManager::getFetchedTexture(i == TEX_HAIR ? IMG_DEFAULT : IMG_DEFAULT_AVATAR), 0); // IMG_DEFAULT_AVATAR = a special texture that's never rendered.
+ }
+ }
+
+ const BOOL self_customizing = isSelf() && gAgentCamera.cameraCustomizeAvatar(); // During face edit mode, we don't use baked textures
+ const BOOL other_culled = !isSelf() && mCulled;
+ LLLoadedCallbackEntry::source_callback_list_t* src_callback_list = NULL ;
+ BOOL paused = FALSE;
+ if(!isSelf())
+ {
+ src_callback_list = &mCallbackTextureList ;
+ paused = mLoadedCallbacksPaused ;
+ }
+
+ std::vector<BOOL> is_layer_baked;
+ is_layer_baked.resize(mBakedTextureDatas.size(), false);
+
+ std::vector<BOOL> use_lkg_baked_layer; // lkg = "last known good"
+ use_lkg_baked_layer.resize(mBakedTextureDatas.size(), false);
+
+ for (U32 i=0; i < mBakedTextureDatas.size(); i++)
+ {
+ is_layer_baked[i] = isTextureDefined(mBakedTextureDatas[i].mTextureIndex);
+
+ if (!other_culled)
+ {
+ // When an avatar is changing clothes and not in Appearance mode,
+ // use the last-known good baked texture until it finish the first
+ // render of the new layerset.
+
+ const BOOL layerset_invalid = mBakedTextureDatas[i].mTexLayerSet
+ && ( !mBakedTextureDatas[i].mTexLayerSet->getComposite()->isInitialized()
+ || !mBakedTextureDatas[i].mTexLayerSet->isLocalTextureDataAvailable() );
+
+ use_lkg_baked_layer[i] = (!is_layer_baked[i]
+ && (mBakedTextureDatas[i].mLastTextureIndex != IMG_DEFAULT_AVATAR)
+ && layerset_invalid);
+ if (use_lkg_baked_layer[i])
+ {
+ mBakedTextureDatas[i].mTexLayerSet->setUpdatesEnabled(TRUE);
+ }
+ }
+ else
+ {
+ use_lkg_baked_layer[i] = (!is_layer_baked[i]
+ && mBakedTextureDatas[i].mLastTextureIndex != IMG_DEFAULT_AVATAR);
+ if (mBakedTextureDatas[i].mTexLayerSet)
+ {
+ mBakedTextureDatas[i].mTexLayerSet->destroyComposite();
+ }
+ }
+
+ }
+
+ // Turn on alpha masking correctly for yourself and other avatars on 1.23+
+ mSupportsAlphaLayers = isSelf() || is_layer_baked[BAKED_HAIR];
+
+ // Baked textures should be requested from the sim this avatar is on. JC
+ const LLHost target_host = getObjectHost();
+ if (!target_host.isOk())
+ {
+ llwarns << "updateMeshTextures: invalid host for object: " << getID() << llendl;
+ }
+
+ for (U32 i=0; i < mBakedTextureDatas.size(); i++)
+ {
+ if (use_lkg_baked_layer[i] && !self_customizing )
+ {
+ LLViewerFetchedTexture* baked_img = LLViewerTextureManager::getFetchedTextureFromHost( mBakedTextureDatas[i].mLastTextureIndex, target_host );
+ mBakedTextureDatas[i].mIsUsed = TRUE;
+ for (U32 k=0; k < mBakedTextureDatas[i].mMeshes.size(); k++)
+ {
+ mBakedTextureDatas[i].mMeshes[k]->setTexture( baked_img );
+ }
+ }
+ else if (!self_customizing && is_layer_baked[i])
+ {
+ LLViewerFetchedTexture* baked_img = LLViewerTextureManager::staticCastToFetchedTexture(getImage( mBakedTextureDatas[i].mTextureIndex, 0 ), TRUE) ;
+ if( baked_img->getID() == mBakedTextureDatas[i].mLastTextureIndex )
+ {
+ // Even though the file may not be finished loading, we'll consider it loaded and use it (rather than doing compositing).
+ useBakedTexture( baked_img->getID() );
+ }
+ else
+ {
+ mBakedTextureDatas[i].mIsLoaded = FALSE;
+ if ( (baked_img->getID() != IMG_INVISIBLE) && ((i == BAKED_HEAD) || (i == BAKED_UPPER) || (i == BAKED_LOWER)) )
+ {
+ baked_img->setLoadedCallback(onBakedTextureMasksLoaded, MORPH_MASK_REQUESTED_DISCARD, TRUE, TRUE, new LLTextureMaskData( mID ),
+ src_callback_list, paused);
+ }
+ baked_img->setLoadedCallback(onBakedTextureLoaded, SWITCH_TO_BAKED_DISCARD, FALSE, FALSE, new LLUUID( mID ),
+ src_callback_list, paused );
+ }
+ }
+ else if (mBakedTextureDatas[i].mTexLayerSet
+ && !other_culled)
+ {
+ mBakedTextureDatas[i].mTexLayerSet->createComposite();
+ mBakedTextureDatas[i].mTexLayerSet->setUpdatesEnabled( TRUE );
+ mBakedTextureDatas[i].mIsUsed = FALSE;
+ for (U32 k=0; k < mBakedTextureDatas[i].mMeshes.size(); k++)
+ {
+ mBakedTextureDatas[i].mMeshes[k]->setLayerSet( mBakedTextureDatas[i].mTexLayerSet );
+ }
+ }
+ }
+
+ // set texture and color of hair manually if we are not using a baked image.
+ // This can happen while loading hair for yourself, or for clients that did not
+ // bake a hair texture. Still needed for yourself after 1.22 is depricated.
+ if (!is_layer_baked[BAKED_HAIR] || self_customizing)
+ {
+ const LLColor4 color = mTexHairColor ? mTexHairColor->getColor() : LLColor4(1,1,1,1);
+ LLViewerTexture* hair_img = getImage( TEX_HAIR, 0 );
+ for (U32 i = 0; i < mBakedTextureDatas[BAKED_HAIR].mMeshes.size(); i++)
+ {
+ mBakedTextureDatas[BAKED_HAIR].mMeshes[i]->setColor( color.mV[VX], color.mV[VY], color.mV[VZ], color.mV[VW] );
+ mBakedTextureDatas[BAKED_HAIR].mMeshes[i]->setTexture( hair_img );
+ }
+ }
+
+
+ for (LLVOAvatarDictionary::BakedTextures::const_iterator baked_iter = LLVOAvatarDictionary::getInstance()->getBakedTextures().begin();
+ baked_iter != LLVOAvatarDictionary::getInstance()->getBakedTextures().end();
+ ++baked_iter)
+ {
+ const EBakedTextureIndex baked_index = baked_iter->first;
+ const LLVOAvatarDictionary::BakedEntry *baked_dict = baked_iter->second;
+
+ for (texture_vec_t::const_iterator local_tex_iter = baked_dict->mLocalTextures.begin();
+ local_tex_iter != baked_dict->mLocalTextures.end();
+ ++local_tex_iter)
+ {
+ const ETextureIndex texture_index = *local_tex_iter;
+ const BOOL is_baked_ready = (is_layer_baked[baked_index] && mBakedTextureDatas[baked_index].mIsLoaded) || other_culled;
+ if (isSelf())
+ {
+ setBakedReady(texture_index, is_baked_ready);
+ }
+ }
+ }
+ removeMissingBakedTextures();
+}
+
+// virtual
+//-----------------------------------------------------------------------------
+// setLocalTexture()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::setLocalTexture( ETextureIndex type, LLViewerTexture* in_tex, BOOL baked_version_ready, U32 index )
+{
+ // invalid for anyone but self
+ llassert(0);
+}
+
+//virtual
+void LLVOAvatar::setBakedReady(LLVOAvatarDefines::ETextureIndex type, BOOL baked_version_exists, U32 index)
+{
+ // invalid for anyone but self
+ llassert(0);
+}
+
+void LLVOAvatar::addChat(const LLChat& chat)
+{
+ std::deque<LLChat>::iterator chat_iter;
+
+ mChats.push_back(chat);
+
+ S32 chat_length = 0;
+ for( chat_iter = mChats.begin(); chat_iter != mChats.end(); ++chat_iter)
+ {
+ chat_length += chat_iter->mText.size();
+ }
+
+ // remove any excess chat
+ chat_iter = mChats.begin();
+ while ((chat_length > MAX_BUBBLE_CHAT_LENGTH || mChats.size() > MAX_BUBBLE_CHAT_UTTERANCES) && chat_iter != mChats.end())
+ {
+ chat_length -= chat_iter->mText.size();
+ mChats.pop_front();
+ chat_iter = mChats.begin();
+ }
+
+ mChatTimer.reset();
+}
+
+void LLVOAvatar::clearChat()
+{
+ mChats.clear();
+}
+
+// adds a morph mask to the appropriate baked texture structure
+void LLVOAvatar::addMaskedMorph(EBakedTextureIndex index, LLPolyMorphTarget* morph_target, BOOL invert, std::string layer)
+{
+ if (index < BAKED_NUM_INDICES)
+ {
+ LLMaskedMorph *morph = new LLMaskedMorph(morph_target, invert, layer);
+ mBakedTextureDatas[index].mMaskedMorphs.push_front(morph);
+ }
+}
+
+// returns TRUE if morph masks are present and not valid for a given baked texture, FALSE otherwise
+BOOL LLVOAvatar::morphMaskNeedsUpdate(LLVOAvatarDefines::EBakedTextureIndex index)
+{
+ if (index >= BAKED_NUM_INDICES)
+ {
+ return FALSE;
+ }
+
+ if (!mBakedTextureDatas[index].mMaskedMorphs.empty())
+ {
+ if (isSelf())
+ {
+ LLTexLayerSet *layer_set = mBakedTextureDatas[index].mTexLayerSet;
+ if (layer_set)
+ {
+ return !layer_set->isMorphValid();
+ }
+ }
+ else
+ {
+ return FALSE;
+ }
+ }
+
+ return FALSE;
+}
+
+void LLVOAvatar::applyMorphMask(U8* tex_data, S32 width, S32 height, S32 num_components, LLVOAvatarDefines::EBakedTextureIndex index)
+{
+ if (index >= BAKED_NUM_INDICES)
+ {
+ llwarns << "invalid baked texture index passed to applyMorphMask" << llendl;
+ return;
+ }
+
+ for (morph_list_t::const_iterator iter = mBakedTextureDatas[index].mMaskedMorphs.begin();
+ iter != mBakedTextureDatas[index].mMaskedMorphs.end(); ++iter)
+ {
+ const LLMaskedMorph* maskedMorph = (*iter);
+ maskedMorph->mMorphTarget->applyMask(tex_data, width, height, num_components, maskedMorph->mInvert);
+ }
+}
+
+
+//-----------------------------------------------------------------------------
+// releaseComponentTextures()
+// release any component texture UUIDs for which we have a baked texture
+// ! BACKWARDS COMPATIBILITY !
+// This is only called for non-self avatars, it can be taken out once component
+// textures aren't communicated by non-self avatars.
+//-----------------------------------------------------------------------------
+void LLVOAvatar::releaseComponentTextures()
+{
+ // ! BACKWARDS COMPATIBILITY !
+ // Detect if the baked hair texture actually wasn't sent, and if so set to default
+ if (isTextureDefined(TEX_HAIR_BAKED) && getImage(TEX_HAIR_BAKED,0)->getID() == getImage(TEX_SKIRT_BAKED,0)->getID())
+ {
+ if (getImage(TEX_HAIR_BAKED,0)->getID() != IMG_INVISIBLE)
+ {
+ // Regression case of messaging system. Expected 21 textures, received 20. last texture is not valid so set to default
+ setTETexture(TEX_HAIR_BAKED, IMG_DEFAULT_AVATAR);
+ }
+ }
+
+ for (U8 baked_index = 0; baked_index < BAKED_NUM_INDICES; baked_index++)
+ {
+ const LLVOAvatarDictionary::BakedEntry * bakedDicEntry = LLVOAvatarDictionary::getInstance()->getBakedTexture((EBakedTextureIndex)baked_index);
+ // skip if this is a skirt and av is not wearing one, or if we don't have a baked texture UUID
+ if (!isTextureDefined(bakedDicEntry->mTextureIndex)
+ && ( (baked_index != BAKED_SKIRT) || isWearingWearableType(LLWearableType::WT_SKIRT) ))
+ {
+ continue;
+ }
+
+ for (U8 texture = 0; texture < bakedDicEntry->mLocalTextures.size(); texture++)
+ {
+ const U8 te = (ETextureIndex)bakedDicEntry->mLocalTextures[texture];
+ setTETexture(te, IMG_DEFAULT_AVATAR);
+ }
+ }
+}
+
+//static
+BOOL LLVOAvatar::teToColorParams( ETextureIndex te, U32 *param_name )
+{
+ switch( te )
+ {
+ case TEX_UPPER_SHIRT:
+ param_name[0] = 803; //"shirt_red";
+ param_name[1] = 804; //"shirt_green";
+ param_name[2] = 805; //"shirt_blue";
+ break;
+
+ case TEX_LOWER_PANTS:
+ param_name[0] = 806; //"pants_red";
+ param_name[1] = 807; //"pants_green";
+ param_name[2] = 808; //"pants_blue";
+ break;
+
+ case TEX_LOWER_SHOES:
+ param_name[0] = 812; //"shoes_red";
+ param_name[1] = 813; //"shoes_green";
+ param_name[2] = 817; //"shoes_blue";
+ break;
+
+ case TEX_LOWER_SOCKS:
+ param_name[0] = 818; //"socks_red";
+ param_name[1] = 819; //"socks_green";
+ param_name[2] = 820; //"socks_blue";
+ break;
+
+ case TEX_UPPER_JACKET:
+ case TEX_LOWER_JACKET:
+ param_name[0] = 834; //"jacket_red";
+ param_name[1] = 835; //"jacket_green";
+ param_name[2] = 836; //"jacket_blue";
+ break;
+
+ case TEX_UPPER_GLOVES:
+ param_name[0] = 827; //"gloves_red";
+ param_name[1] = 829; //"gloves_green";
+ param_name[2] = 830; //"gloves_blue";
+ break;
+
+ case TEX_UPPER_UNDERSHIRT:
+ param_name[0] = 821; //"undershirt_red";
+ param_name[1] = 822; //"undershirt_green";
+ param_name[2] = 823; //"undershirt_blue";
+ break;
+
+ case TEX_LOWER_UNDERPANTS:
+ param_name[0] = 824; //"underpants_red";
+ param_name[1] = 825; //"underpants_green";
+ param_name[2] = 826; //"underpants_blue";
+ break;
+
+ case TEX_SKIRT:
+ param_name[0] = 921; //"skirt_red";
+ param_name[1] = 922; //"skirt_green";
+ param_name[2] = 923; //"skirt_blue";
+ break;
+
+ case TEX_HEAD_TATTOO:
+ case TEX_LOWER_TATTOO:
+ case TEX_UPPER_TATTOO:
+ param_name[0] = 1071; //"tattoo_red";
+ param_name[1] = 1072; //"tattoo_green";
+ param_name[2] = 1073; //"tattoo_blue";
+ break;
+
+ default:
+ llassert(0);
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+void LLVOAvatar::setClothesColor( ETextureIndex te, const LLColor4& new_color, BOOL upload_bake )
+{
+ U32 param_name[3];
+ if( teToColorParams( te, param_name ) )
+ {
+ setVisualParamWeight( param_name[0], new_color.mV[VX], upload_bake );
+ setVisualParamWeight( param_name[1], new_color.mV[VY], upload_bake );
+ setVisualParamWeight( param_name[2], new_color.mV[VZ], upload_bake );
+ }
+}
+
+LLColor4 LLVOAvatar::getClothesColor( ETextureIndex te )
+{
+ LLColor4 color;
+ U32 param_name[3];
+ if( teToColorParams( te, param_name ) )
+ {
+ color.mV[VX] = getVisualParamWeight( param_name[0] );
+ color.mV[VY] = getVisualParamWeight( param_name[1] );
+ color.mV[VZ] = getVisualParamWeight( param_name[2] );
+ }
+ return color;
+}
+
+// static
+LLColor4 LLVOAvatar::getDummyColor()
+{
+ return DUMMY_COLOR;
+}
+
+void LLVOAvatar::dumpAvatarTEs( const std::string& context ) const
+{
+ llinfos << (isSelf() ? "Self: " : "Other: ") << context << llendl;
+ for (LLVOAvatarDictionary::Textures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
+ iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
+ ++iter)
+ {
+ const LLVOAvatarDictionary::TextureEntry *texture_dict = iter->second;
+ // TODO: MULTI-WEARABLE: handle multiple textures for self
+ const LLViewerTexture* te_image = getImage(iter->first,0);
+ if( !te_image )
+ {
+ llinfos << " " << texture_dict->mName << ": null ptr" << llendl;
+ }
+ else if( te_image->getID().isNull() )
+ {
+ llinfos << " " << texture_dict->mName << ": null UUID" << llendl;
+ }
+ else if( te_image->getID() == IMG_DEFAULT )
+ {
+ llinfos << " " << texture_dict->mName << ": IMG_DEFAULT" << llendl;
+ }
+ else if( te_image->getID() == IMG_DEFAULT_AVATAR )
+ {
+ llinfos << " " << texture_dict->mName << ": IMG_DEFAULT_AVATAR" << llendl;
+ }
+ else
+ {
+ llinfos << " " << texture_dict->mName << ": " << te_image->getID() << llendl;
+ }
+ }
+}
+
+// Unlike most wearable functions, this works for both self and other.
+BOOL LLVOAvatar::isWearingWearableType(LLWearableType::EType type) const
+{
+ if (mIsDummy) return TRUE;
+
+ switch(type)
+ {
+ case LLWearableType::WT_SHAPE:
+ case LLWearableType::WT_SKIN:
+ case LLWearableType::WT_HAIR:
+ case LLWearableType::WT_EYES:
+ return TRUE; // everyone has all bodyparts
+ default:
+ break; // Do nothing
+ }
+
+ /* switch(type)
+ case LLWearableType::WT_SHIRT:
+ indicator_te = TEX_UPPER_SHIRT; */
+ for (LLVOAvatarDictionary::Textures::const_iterator tex_iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
+ tex_iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
+ ++tex_iter)
+ {
+ const LLVOAvatarDictionary::TextureEntry *texture_dict = tex_iter->second;
+ if (texture_dict->mWearableType == type)
+ {
+ // If you're checking another avatar's clothing, you don't have component textures.
+ // Thus, you must check to see if the corresponding baked texture is defined.
+ // NOTE: this is a poor substitute if you actually want to know about individual pieces of clothing
+ // this works for detecting a skirt (most important), but is ineffective at any piece of clothing that
+ // gets baked into a texture that always exists (upper or lower).
+ if (texture_dict->mIsUsedByBakedTexture)
+ {
+ const EBakedTextureIndex baked_index = texture_dict->mBakedTextureIndex;
+ return isTextureDefined(LLVOAvatarDictionary::getInstance()->getBakedTexture(baked_index)->mTextureIndex);
+ }
+ return FALSE;
+ }
+ }
+ return FALSE;
+}
+
+//-----------------------------------------------------------------------------
+// clampAttachmentPositions()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::clampAttachmentPositions()
+{
+ if (isDead())
+ {
+ return;
+ }
+ for (attachment_map_t::iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+ if (attachment)
+ {
+ attachment->clampObjectPosition();
+ }
+ }
+}
+
+BOOL LLVOAvatar::hasHUDAttachment() const
+{
+ for (attachment_map_t::const_iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+ if (attachment->getIsHUDAttachment() && attachment->getNumObjects() > 0)
+ {
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+LLBBox LLVOAvatar::getHUDBBox() const
+{
+ LLBBox bbox;
+ for (attachment_map_t::const_iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+ if (attachment->getIsHUDAttachment())
+ {
+ for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
+ attachment_iter != attachment->mAttachedObjects.end();
+ ++attachment_iter)
+ {
+ const LLViewerObject* attached_object = (*attachment_iter);
+ if (attached_object == NULL)
+ {
+ llwarns << "HUD attached object is NULL!" << llendl;
+ continue;
+ }
+ // initialize bounding box to contain identity orientation and center point for attached object
+ bbox.addPointLocal(attached_object->getPosition());
+ // add rotated bounding box for attached object
+ bbox.addBBoxAgent(attached_object->getBoundingBoxAgent());
+ LLViewerObject::const_child_list_t& child_list = attached_object->getChildren();
+ for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
+ iter != child_list.end();
+ ++iter)
+ {
+ const LLViewerObject* child_objectp = *iter;
+ bbox.addBBoxAgent(child_objectp->getBoundingBoxAgent());
+ }
+ }
+ }
+ }
+
+ return bbox;
+}
+
+void LLVOAvatar::rebuildHUD()
+{
+}
+
+//-----------------------------------------------------------------------------
+// onFirstTEMessageReceived()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::onFirstTEMessageReceived()
+{
+ if( !mFirstTEMessageReceived )
+ {
+ mFirstTEMessageReceived = TRUE;
+
+ LLLoadedCallbackEntry::source_callback_list_t* src_callback_list = NULL ;
+ BOOL paused = FALSE ;
+ if(!isSelf())
+ {
+ src_callback_list = &mCallbackTextureList ;
+ paused = mLoadedCallbacksPaused ;
+ }
+
+ for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
+ {
+ const BOOL layer_baked = isTextureDefined(mBakedTextureDatas[i].mTextureIndex);
+
+ // Use any baked textures that we have even if they haven't downloaded yet.
+ // (That is, don't do a transition from unbaked to baked.)
+ if (layer_baked)
+ {
+ LLViewerFetchedTexture* image = LLViewerTextureManager::staticCastToFetchedTexture(getImage( mBakedTextureDatas[i].mTextureIndex, 0 ), TRUE) ;
+ mBakedTextureDatas[i].mLastTextureIndex = image->getID();
+ // If we have more than one texture for the other baked layers, we'll want to call this for them too.
+ if ( (image->getID() != IMG_INVISIBLE) && ((i == BAKED_HEAD) || (i == BAKED_UPPER) || (i == BAKED_LOWER)) )
+ {
+ image->setLoadedCallback( onBakedTextureMasksLoaded, MORPH_MASK_REQUESTED_DISCARD, TRUE, TRUE, new LLTextureMaskData( mID ),
+ src_callback_list, paused);
+ }
+ image->setLoadedCallback( onInitialBakedTextureLoaded, MAX_DISCARD_LEVEL, FALSE, FALSE, new LLUUID( mID ),
+ src_callback_list, paused );
+ }
+ }
+
+ mMeshTexturesDirty = TRUE;
+ gPipeline.markGLRebuild(this);
+ }
+}
+
+//-----------------------------------------------------------------------------
+// bool visualParamWeightsAreDefault()
+//-----------------------------------------------------------------------------
+bool LLVOAvatar::visualParamWeightsAreDefault()
+{
+ bool rtn = true;
+
+ bool is_wearing_skirt = isWearingWearableType(LLWearableType::WT_SKIRT);
+ for (LLVisualParam *param = getFirstVisualParam();
+ param;
+ param = getNextVisualParam())
+ {
+ if (param->isTweakable())
+ {
+ LLViewerVisualParam* vparam = dynamic_cast<LLViewerVisualParam*>(param);
+ llassert(vparam);
+ bool is_skirt_param = vparam &&
+ LLWearableType::WT_SKIRT == vparam->getWearableType();
+ if (param->getWeight() != param->getDefaultWeight() &&
+ // we have to not care whether skirt weights are default, if we're not actually wearing a skirt
+ (is_wearing_skirt || !is_skirt_param))
+ {
+ //llinfos << "param '" << param->getName() << "'=" << param->getWeight() << " which differs from default=" << param->getDefaultWeight() << llendl;
+ rtn = false;
+ break;
+ }
+ }
+ }
+
+ //llinfos << "params are default ? " << int(rtn) << llendl;
+
+ return rtn;
+}
+
+
+//-----------------------------------------------------------------------------
+// processAvatarAppearance()
+//-----------------------------------------------------------------------------
+void LLVOAvatar::processAvatarAppearance( LLMessageSystem* mesgsys )
+{
+ if (gSavedSettings.getBOOL("BlockAvatarAppearanceMessages"))
+ {
+ llwarns << "Blocking AvatarAppearance message" << llendl;
+ return;
+ }
+
+ LLMemType mt(LLMemType::MTYPE_AVATAR);
+
+// llinfos << "processAvatarAppearance start " << mID << llendl;
+ BOOL is_first_appearance_message = !mFirstAppearanceMessageReceived;
+
+ mFirstAppearanceMessageReceived = TRUE;
+
+ if( isSelf() )
+ {
+ llwarns << "Received AvatarAppearance for self" << llendl;
+ if( mFirstTEMessageReceived )
+ {
+// llinfos << "processAvatarAppearance end " << mID << llendl;
+ return;
+ }
+ }
+
+ if (gNoRender)
+ {
+ return;
+ }
+
+ ESex old_sex = getSex();
+
+// llinfos << "LLVOAvatar::processAvatarAppearance()" << llendl;
+// dumpAvatarTEs( "PRE processAvatarAppearance()" );
+ unpackTEMessage(mesgsys, _PREHASH_ObjectData);
+// dumpAvatarTEs( "POST processAvatarAppearance()" );
+
+ // prevent the overwriting of valid baked textures with invalid baked textures
+ for (U8 baked_index = 0; baked_index < mBakedTextureDatas.size(); baked_index++)
+ {
+ if (!isTextureDefined(mBakedTextureDatas[baked_index].mTextureIndex)
+ && mBakedTextureDatas[baked_index].mLastTextureIndex != IMG_DEFAULT
+ && baked_index != BAKED_SKIRT)
+ {
+ setTEImage(mBakedTextureDatas[baked_index].mTextureIndex,
+ LLViewerTextureManager::getFetchedTexture(mBakedTextureDatas[baked_index].mLastTextureIndex, TRUE, LLViewerTexture::BOOST_NONE, LLViewerTexture::LOD_TEXTURE));
+ }
+ }
+
+
+ if( !is_first_appearance_message )
+ {
+ onFirstTEMessageReceived();
+ }
+
+ setCompositeUpdatesEnabled( FALSE );
+ mMeshTexturesDirty = TRUE;
+ gPipeline.markGLRebuild(this);
+
+ // ! BACKWARDS COMPATIBILITY !
+ // Non-self avatars will no longer have component textures
+ if (!isSelf())
+ {
+ releaseComponentTextures();
+ }
+
+ // parse visual params
+ S32 num_blocks = mesgsys->getNumberOfBlocksFast(_PREHASH_VisualParam);
+ bool drop_visual_params_debug = gSavedSettings.getBOOL("BlockSomeAvatarAppearanceVisualParams") && (ll_rand(2) == 0); // pretend that ~12% of AvatarAppearance messages arrived without a VisualParam block, for testing
+ if( num_blocks > 1 && !drop_visual_params_debug)
+ {
+ BOOL params_changed = FALSE;
+ BOOL interp_params = FALSE;
+
+ LLVisualParam* param = getFirstVisualParam();
+ llassert(param); // if this ever fires, we should do the same as when num_blocks<=1
+ if (!param)
+ {
+ llwarns << "No visual params!" << llendl;
+ }
+ else
+ {
+ for( S32 i = 0; i < num_blocks; i++ )
+ {
+ while( param && (param->getGroup() != VISUAL_PARAM_GROUP_TWEAKABLE) ) // should not be any of group VISUAL_PARAM_GROUP_TWEAKABLE_NO_TRANSMIT
+ {
+ param = getNextVisualParam();
+ }
+
+ if( !param )
+ {
+ // more visual params supplied than expected - just process what we know about
+ break;
+ }
+
+ U8 value;
+ mesgsys->getU8Fast(_PREHASH_VisualParam, _PREHASH_ParamValue, value, i);
+ F32 newWeight = U8_to_F32(value, param->getMinWeight(), param->getMaxWeight());
+
+ if (is_first_appearance_message || (param->getWeight() != newWeight))
+ {
+ //llinfos << "Received update for param " << param->getDisplayName() << " at value " << newWeight << llendl;
+ params_changed = TRUE;
+ if(is_first_appearance_message)
+ {
+ param->setWeight(newWeight, FALSE);
+ }
+ else
+ {
+ interp_params = TRUE;
+ param->setAnimationTarget(newWeight, FALSE);
+ }
+ }
+ param = getNextVisualParam();
+ }
+ }
+
+ const S32 expected_tweakable_count = getVisualParamCountInGroup(VISUAL_PARAM_GROUP_TWEAKABLE); // don't worry about VISUAL_PARAM_GROUP_TWEAKABLE_NO_TRANSMIT
+ if (num_blocks != expected_tweakable_count)
+ {
+ llinfos << "Number of params in AvatarAppearance msg (" << num_blocks << ") does not match number of tweakable params in avatar xml file (" << expected_tweakable_count << "). Processing what we can. object: " << getID() << llendl;
+ }
+
+ if (params_changed)
+ {
+ if (interp_params)
+ {
+ startAppearanceAnimation();
+ }
+ updateVisualParams();
+
+ ESex new_sex = getSex();
+ if( old_sex != new_sex )
+ {
+ updateSexDependentLayerSets( FALSE );
+ }
+ }
+
+ llassert( getSex() == ((getVisualParamWeight( "male" ) > 0.5f) ? SEX_MALE : SEX_FEMALE) );
+ }
+ else
+ {
+ // AvatarAppearance message arrived without visual params
+ if (drop_visual_params_debug)
+ {
+ llinfos << "Debug-faked lack of parameters on AvatarAppearance for object: " << getID() << llendl;
+ }
+ else
+ {
+ llinfos << "AvatarAppearance msg received without any parameters, object: " << getID() << llendl;
+ }
+
+ const F32 LOADING_TIMEOUT_SECONDS = 60.f;
+ // this isn't really a problem if we already have a non-default shape
+ if (visualParamWeightsAreDefault() && mRuthTimer.getElapsedTimeF32() > LOADING_TIMEOUT_SECONDS)
+ {
+ // re-request appearance, hoping that it comes back with a shape next time
+ llinfos << "Re-requesting AvatarAppearance for object: " << getID() << llendl;
+ LLAvatarPropertiesProcessor::getInstance()->sendAvatarTexturesRequest(getID());
+ mRuthTimer.reset();
+ }
+ else
+ {
+ llinfos << "That's okay, we already have a non-default shape for object: " << getID() << llendl;
+ // we don't really care.
+ }
+ }
+
+ setCompositeUpdatesEnabled( TRUE );
+
+ // If all of the avatars are completely baked, release the global image caches to conserve memory.
+ LLVOAvatar::cullAvatarsByPixelArea();
+
+// llinfos << "processAvatarAppearance end " << mID << llendl;
+}
+
+// static
+void LLVOAvatar::getAnimLabels( LLDynamicArray<std::string>* labels )
+{
+ S32 i;
+ for( i = 0; i < gUserAnimStatesCount; i++ )
+ {
+ labels->put( LLAnimStateLabels::getStateLabel( gUserAnimStates[i].mName ) );
+ }
+
+ // Special case to trigger away (AFK) state
+ labels->put( "Away From Keyboard" );
+}
+
+// static
+void LLVOAvatar::getAnimNames( LLDynamicArray<std::string>* names )
+{
+ S32 i;
+
+ for( i = 0; i < gUserAnimStatesCount; i++ )
+ {
+ names->put( std::string(gUserAnimStates[i].mName) );
+ }
+
+ // Special case to trigger away (AFK) state
+ names->put( "enter_away_from_keyboard_state" );
+}
+
+void LLVOAvatar::onBakedTextureMasksLoaded( BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata )
+{
+ if (!userdata) return;
+
+ //llinfos << "onBakedTextureMasksLoaded: " << src_vi->getID() << llendl;
+ const LLMemType mt(LLMemType::MTYPE_AVATAR);
+ const LLUUID id = src_vi->getID();
+
+ LLTextureMaskData* maskData = (LLTextureMaskData*) userdata;
+ LLVOAvatar* self = (LLVOAvatar*) gObjectList.findObject( maskData->mAvatarID );
+
+ // if discard level is 2 less than last discard level we processed, or we hit 0,
+ // then generate morph masks
+ if(self && success && (discard_level < maskData->mLastDiscardLevel - 2 || discard_level == 0))
+ {
+ if(aux_src && aux_src->getComponents() == 1)
+ {
+ if (!aux_src->getData())
+ {
+ llerrs << "No auxiliary source data for onBakedTextureMasksLoaded" << llendl;
+ return;
+ }
+
+ U32 gl_name;
+ LLImageGL::generateTextures(1, &gl_name );
+ stop_glerror();
+
+ gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, gl_name);
+ stop_glerror();
+
+ LLImageGL::setManualImage(
+ GL_TEXTURE_2D, 0, GL_ALPHA8,
+ aux_src->getWidth(), aux_src->getHeight(),
+ GL_ALPHA, GL_UNSIGNED_BYTE, aux_src->getData());
+ stop_glerror();
+
+ gGL.getTexUnit(0)->setTextureFilteringOption(LLTexUnit::TFO_BILINEAR);
+
+ /* if( id == head_baked->getID() )
+ if (self->mBakedTextureDatas[BAKED_HEAD].mTexLayerSet)
+ //llinfos << "onBakedTextureMasksLoaded for head " << id << " discard = " << discard_level << llendl;
+ self->mBakedTextureDatas[BAKED_HEAD].mTexLayerSet->applyMorphMask(aux_src->getData(), aux_src->getWidth(), aux_src->getHeight(), 1);
+ maskData->mLastDiscardLevel = discard_level; */
+ BOOL found_texture_id = false;
+ for (LLVOAvatarDictionary::Textures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
+ iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
+ ++iter)
+ {
+
+ const LLVOAvatarDictionary::TextureEntry *texture_dict = iter->second;
+ if (texture_dict->mIsUsedByBakedTexture)
+ {
+ const ETextureIndex texture_index = iter->first;
+ const LLViewerTexture *baked_img = self->getImage(texture_index, 0);
+ if (baked_img && id == baked_img->getID())
+ {
+ const EBakedTextureIndex baked_index = texture_dict->mBakedTextureIndex;
+ self->applyMorphMask(aux_src->getData(), aux_src->getWidth(), aux_src->getHeight(), 1, baked_index);
+ maskData->mLastDiscardLevel = discard_level;
+ if (self->mBakedTextureDatas[baked_index].mMaskTexName)
+ {
+ LLImageGL::deleteTextures(1, &(self->mBakedTextureDatas[baked_index].mMaskTexName));
+ }
+ self->mBakedTextureDatas[baked_index].mMaskTexName = gl_name;
+ found_texture_id = true;
+ break;
+ }
+ }
+ }
+ if (!found_texture_id)
+ {
+ llinfos << "onBakedTextureMasksLoaded(): unexpected image id: " << id << llendl;
+ }
+ self->dirtyMesh();
+ }
+ else
+ {
+ // this can happen when someone uses an old baked texture possibly provided by
+ // viewer-side baked texture caching
+ llwarns << "Masks loaded callback but NO aux source!" << llendl;
+ }
+ }
+
+ if (final || !success)
+ {
+ delete maskData;
+ }
+}
+
+// static
+void LLVOAvatar::onInitialBakedTextureLoaded( BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata )
+{
+ LLUUID *avatar_idp = (LLUUID *)userdata;
+ LLVOAvatar *selfp = (LLVOAvatar *)gObjectList.findObject(*avatar_idp);
+
+ if (!success && selfp)
+ {
+ selfp->removeMissingBakedTextures();
+ }
+ if (final || !success )
+ {
+ delete avatar_idp;
+ }
+}
+
+void LLVOAvatar::onBakedTextureLoaded(BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata)
+{
+ //llinfos << "onBakedTextureLoaded: " << src_vi->getID() << llendl;
+
+ LLUUID id = src_vi->getID();
+ LLUUID *avatar_idp = (LLUUID *)userdata;
+ LLVOAvatar *selfp = (LLVOAvatar *)gObjectList.findObject(*avatar_idp);
+
+ if (selfp && !success)
+ {
+ selfp->removeMissingBakedTextures();
+ }
+
+ if( final || !success )
+ {
+ delete avatar_idp;
+ }
+
+ if( selfp && success && final )
+ {
+ selfp->useBakedTexture( id );
+ }
+}
+
+
+// Called when baked texture is loaded and also when we start up with a baked texture
+void LLVOAvatar::useBakedTexture( const LLUUID& id )
+{
+ /* if(id == head_baked->getID())
+ mHeadBakedLoaded = TRUE;
+ mLastHeadBakedID = id;
+ mHeadMesh0.setTexture( head_baked );
+ mHeadMesh1.setTexture( head_baked ); */
+ for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
+ {
+ LLViewerTexture* image_baked = getImage( mBakedTextureDatas[i].mTextureIndex, 0 );
+ if (id == image_baked->getID())
+ {
+ mBakedTextureDatas[i].mIsLoaded = true;
+ mBakedTextureDatas[i].mLastTextureIndex = id;
+ mBakedTextureDatas[i].mIsUsed = true;
+ for (U32 k = 0; k < mBakedTextureDatas[i].mMeshes.size(); k++)
+ {
+ mBakedTextureDatas[i].mMeshes[k]->setTexture( image_baked );
+ }
+ if (mBakedTextureDatas[i].mTexLayerSet)
+ {
+ //mBakedTextureDatas[i].mTexLayerSet->destroyComposite();
+ }
+ const LLVOAvatarDictionary::BakedEntry *baked_dict = LLVOAvatarDictionary::getInstance()->getBakedTexture((EBakedTextureIndex)i);
+ for (texture_vec_t::const_iterator local_tex_iter = baked_dict->mLocalTextures.begin();
+ local_tex_iter != baked_dict->mLocalTextures.end();
+ ++local_tex_iter)
+ {
+ if (isSelf()) setBakedReady(*local_tex_iter, TRUE);
+ }
+
+ // ! BACKWARDS COMPATIBILITY !
+ // Workaround for viewing avatars from old viewers that haven't baked hair textures.
+ // This is paired with similar code in updateMeshTextures that sets hair mesh color.
+ if (i == BAKED_HAIR)
+ {
+ for (U32 i = 0; i < mBakedTextureDatas[BAKED_HAIR].mMeshes.size(); i++)
+ {
+ mBakedTextureDatas[BAKED_HAIR].mMeshes[i]->setColor( 1.f, 1.f, 1.f, 1.f );
+ }
+ }
+ }
+ }
+
+ dirtyMesh();
+}
+
+// static
+void LLVOAvatar::dumpArchetypeXML( void* )
+{
+ LLAPRFile outfile;
+ outfile.open(gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,"new archetype.xml"), LL_APR_WB );
+ apr_file_t* file = outfile.getFileHandle() ;
+ if (!file)
+ {
+ return;
+ }
+
+ apr_file_printf( file, "<?xml version=\"1.0\" encoding=\"US-ASCII\" standalone=\"yes\"?>\n" );
+ apr_file_printf( file, "<linden_genepool version=\"1.0\">\n" );
+ apr_file_printf( file, "\n\t<archetype name=\"???\">\n" );
+
+ // only body parts, not clothing.
+ for (S32 type = LLWearableType::WT_SHAPE; type <= LLWearableType::WT_EYES; type++)
+ {
+ const std::string& wearable_name = LLWearableType::getTypeName((LLWearableType::EType)type);
+ apr_file_printf( file, "\n\t\t<!-- wearable: %s -->\n", wearable_name.c_str() );
+
+ for (LLVisualParam* param = gAgentAvatarp->getFirstVisualParam(); param; param = gAgentAvatarp->getNextVisualParam())
+ {
+ LLViewerVisualParam* viewer_param = (LLViewerVisualParam*)param;
+ if( (viewer_param->getWearableType() == type) &&
+ (viewer_param->isTweakable() ) )
+ {
+ apr_file_printf(file, "\t\t<param id=\"%d\" name=\"%s\" value=\"%.3f\"/>\n",
+ viewer_param->getID(), viewer_param->getName().c_str(), viewer_param->getWeight());
+ }
+ }
+
+ for (U8 te = 0; te < TEX_NUM_INDICES; te++)
+ {
+ if (LLVOAvatarDictionary::getTEWearableType((ETextureIndex)te) == type)
+ {
+ // MULTIPLE_WEARABLES: extend to multiple wearables?
+ LLViewerTexture* te_image = ((LLVOAvatar *)(gAgentAvatarp))->getImage((ETextureIndex)te, 0);
+ if( te_image )
+ {
+ std::string uuid_str;
+ te_image->getID().toString( uuid_str );
+ apr_file_printf( file, "\t\t<texture te=\"%i\" uuid=\"%s\"/>\n", te, uuid_str.c_str());
+ }
+ }
+ }
+ }
+ apr_file_printf( file, "\t</archetype>\n" );
+ apr_file_printf( file, "\n</linden_genepool>\n" );
+}
+
+
+void LLVOAvatar::setVisibilityRank(U32 rank)
+{
+ if (mDrawable.isNull() || mDrawable->isDead())
+ {
+ // do nothing
+ return;
+ }
+ mVisibilityRank = rank;
+}
+
+// Assumes LLVOAvatar::sInstances has already been sorted.
+S32 LLVOAvatar::getUnbakedPixelAreaRank()
+{
+ S32 rank = 1;
+ for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
+ iter != LLCharacter::sInstances.end(); ++iter)
+ {
+ LLVOAvatar* inst = (LLVOAvatar*) *iter;
+ if (inst == this)
+ {
+ return rank;
+ }
+ else if (!inst->isDead() && !inst->isFullyBaked())
+ {
+ rank++;
+ }
+ }
+
+ llassert(0);
+ return 0;
+}
+
+struct CompareScreenAreaGreater
+{
+ BOOL operator()(const LLCharacter* const& lhs, const LLCharacter* const& rhs)
+ {
+ return lhs->getPixelArea() > rhs->getPixelArea();
+ }
+};
+
+// static
+void LLVOAvatar::cullAvatarsByPixelArea()
+{
+ std::sort(LLCharacter::sInstances.begin(), LLCharacter::sInstances.end(), CompareScreenAreaGreater());
+
+ // Update the avatars that have changed status
+ U32 rank = 2; //1 is reserved for self.
+ for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
+ iter != LLCharacter::sInstances.end(); ++iter)
+ {
+ LLVOAvatar* inst = (LLVOAvatar*) *iter;
+ BOOL culled;
+ if (inst->isSelf() || inst->isFullyBaked())
+ {
+ culled = FALSE;
+ }
+ else
+ {
+ culled = TRUE;
+ }
+
+ if (inst->mCulled != culled)
+ {
+ inst->mCulled = culled;
+ lldebugs << "avatar " << inst->getID() << (culled ? " start culled" : " start not culled" ) << llendl;
+ inst->updateMeshTextures();
+ }
+
+ if (inst->isSelf())
+ {
+ inst->setVisibilityRank(1);
+ }
+ else if (inst->mDrawable.notNull() && inst->mDrawable->isVisible())
+ {
+ inst->setVisibilityRank(rank++);
+ }
+ }
+
+ S32 grey_avatars = 0;
+ if (LLVOAvatar::areAllNearbyInstancesBaked(grey_avatars))
+ {
+ LLVOAvatar::deleteCachedImages(false);
+ }
+ else
+ {
+ if (gFrameTimeSeconds != sUnbakedUpdateTime) // only update once per frame
+ {
+ sUnbakedUpdateTime = gFrameTimeSeconds;
+ sUnbakedTime += gFrameIntervalSeconds;
+ }
+ if (grey_avatars > 0)
+ {
+ if (gFrameTimeSeconds != sGreyUpdateTime) // only update once per frame
+ {
+ sGreyUpdateTime = gFrameTimeSeconds;
+ sGreyTime += gFrameIntervalSeconds;
+ }
+ }
+ }
+}
+
+void LLVOAvatar::startAppearanceAnimation()
+{
+ if(!mAppearanceAnimating)
+ {
+ mAppearanceAnimating = TRUE;
+ mAppearanceMorphTimer.reset();
+ mLastAppearanceBlendTime = 0.f;
+ }
+}
+
+// virtual
+void LLVOAvatar::removeMissingBakedTextures()
+{
+}
+
+//-----------------------------------------------------------------------------
+// LLVOAvatarXmlInfo
+//-----------------------------------------------------------------------------
+
+LLVOAvatar::LLVOAvatarXmlInfo::LLVOAvatarXmlInfo()
+ : mTexSkinColorInfo(0), mTexHairColorInfo(0), mTexEyeColorInfo(0)
+{
+}
+
+LLVOAvatar::LLVOAvatarXmlInfo::~LLVOAvatarXmlInfo()
+{
+ std::for_each(mMeshInfoList.begin(), mMeshInfoList.end(), DeletePointer());
+ std::for_each(mSkeletalDistortionInfoList.begin(), mSkeletalDistortionInfoList.end(), DeletePointer());
+ std::for_each(mAttachmentInfoList.begin(), mAttachmentInfoList.end(), DeletePointer());
+ deleteAndClear(mTexSkinColorInfo);
+ deleteAndClear(mTexHairColorInfo);
+ deleteAndClear(mTexEyeColorInfo);
+ std::for_each(mLayerInfoList.begin(), mLayerInfoList.end(), DeletePointer());
+ std::for_each(mDriverInfoList.begin(), mDriverInfoList.end(), DeletePointer());
+ std::for_each(mMorphMaskInfoList.begin(), mMorphMaskInfoList.end(), DeletePointer());
+}
+
+//-----------------------------------------------------------------------------
+// LLVOAvatarBoneInfo::parseXml()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatarBoneInfo::parseXml(LLXmlTreeNode* node)
+{
+ if (node->hasName("bone"))
+ {
+ mIsJoint = TRUE;
+ static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
+ if (!node->getFastAttributeString(name_string, mName))
+ {
+ llwarns << "Bone without name" << llendl;
+ return FALSE;
+ }
+ }
+ else if (node->hasName("collision_volume"))
+ {
+ mIsJoint = FALSE;
+ static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
+ if (!node->getFastAttributeString(name_string, mName))
+ {
+ mName = "Collision Volume";
+ }
+ }
+ else
+ {
+ llwarns << "Invalid node " << node->getName() << llendl;
+ return FALSE;
+ }
+
+ static LLStdStringHandle pos_string = LLXmlTree::addAttributeString("pos");
+ if (!node->getFastAttributeVector3(pos_string, mPos))
+ {
+ llwarns << "Bone without position" << llendl;
+ return FALSE;
+ }
+
+ static LLStdStringHandle rot_string = LLXmlTree::addAttributeString("rot");
+ if (!node->getFastAttributeVector3(rot_string, mRot))
+ {
+ llwarns << "Bone without rotation" << llendl;
+ return FALSE;
+ }
+
+ static LLStdStringHandle scale_string = LLXmlTree::addAttributeString("scale");
+ if (!node->getFastAttributeVector3(scale_string, mScale))
+ {
+ llwarns << "Bone without scale" << llendl;
+ return FALSE;
+ }
+
+ if (mIsJoint)
+ {
+ static LLStdStringHandle pivot_string = LLXmlTree::addAttributeString("pivot");
+ if (!node->getFastAttributeVector3(pivot_string, mPivot))
+ {
+ llwarns << "Bone without pivot" << llendl;
+ return FALSE;
+ }
+ }
+
+ // parse children
+ LLXmlTreeNode* child;
+ for( child = node->getFirstChild(); child; child = node->getNextChild() )
+ {
+ LLVOAvatarBoneInfo *child_info = new LLVOAvatarBoneInfo;
+ if (!child_info->parseXml(child))
+ {
+ delete child_info;
+ return FALSE;
+ }
+ mChildList.push_back(child_info);
+ }
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// LLVOAvatarSkeletonInfo::parseXml()
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatarSkeletonInfo::parseXml(LLXmlTreeNode* node)
+{
+ static LLStdStringHandle num_bones_string = LLXmlTree::addAttributeString("num_bones");
+ if (!node->getFastAttributeS32(num_bones_string, mNumBones))
+ {
+ llwarns << "Couldn't find number of bones." << llendl;
+ return FALSE;
+ }
+
+ static LLStdStringHandle num_collision_volumes_string = LLXmlTree::addAttributeString("num_collision_volumes");
+ node->getFastAttributeS32(num_collision_volumes_string, mNumCollisionVolumes);
+
+ LLXmlTreeNode* child;
+ for( child = node->getFirstChild(); child; child = node->getNextChild() )
+ {
+ LLVOAvatarBoneInfo *info = new LLVOAvatarBoneInfo;
+ if (!info->parseXml(child))
+ {
+ delete info;
+ llwarns << "Error parsing bone in skeleton file" << llendl;
+ return FALSE;
+ }
+ mBoneInfoList.push_back(info);
+ }
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// parseXmlSkeletonNode(): parses <skeleton> nodes from XML tree
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlSkeletonNode(LLXmlTreeNode* root)
+{
+ LLXmlTreeNode* node = root->getChildByName( "skeleton" );
+ if( !node )
+ {
+ llwarns << "avatar file: missing <skeleton>" << llendl;
+ return FALSE;
+ }
+
+ LLXmlTreeNode* child;
+
+ // SKELETON DISTORTIONS
+ for (child = node->getChildByName( "param" );
+ child;
+ child = node->getNextNamedChild())
+ {
+ if (!child->getChildByName("param_skeleton"))
+ {
+ if (child->getChildByName("param_morph"))
+ {
+ llwarns << "Can't specify morph param in skeleton definition." << llendl;
+ }
+ else
+ {
+ llwarns << "Unknown param type." << llendl;
+ }
+ continue;
+ }
+
+ LLPolySkeletalDistortionInfo *info = new LLPolySkeletalDistortionInfo;
+ if (!info->parseXml(child))
+ {
+ delete info;
+ return FALSE;
+ }
+
+ mSkeletalDistortionInfoList.push_back(info);
+ }
+
+ // ATTACHMENT POINTS
+ for (child = node->getChildByName( "attachment_point" );
+ child;
+ child = node->getNextNamedChild())
+ {
+ LLVOAvatarAttachmentInfo* info = new LLVOAvatarAttachmentInfo();
+
+ static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
+ if (!child->getFastAttributeString(name_string, info->mName))
+ {
+ llwarns << "No name supplied for attachment point." << llendl;
+ delete info;
+ continue;
+ }
+
+ static LLStdStringHandle joint_string = LLXmlTree::addAttributeString("joint");
+ if (!child->getFastAttributeString(joint_string, info->mJointName))
+ {
+ llwarns << "No bone declared in attachment point " << info->mName << llendl;
+ delete info;
+ continue;
+ }
+
+ static LLStdStringHandle position_string = LLXmlTree::addAttributeString("position");
+ if (child->getFastAttributeVector3(position_string, info->mPosition))
+ {
+ info->mHasPosition = TRUE;
+ }
+
+ static LLStdStringHandle rotation_string = LLXmlTree::addAttributeString("rotation");
+ if (child->getFastAttributeVector3(rotation_string, info->mRotationEuler))
+ {
+ info->mHasRotation = TRUE;
+ }
+ static LLStdStringHandle group_string = LLXmlTree::addAttributeString("group");
+ if (child->getFastAttributeS32(group_string, info->mGroup))
+ {
+ if (info->mGroup == -1)
+ info->mGroup = -1111; // -1 = none parsed, < -1 = bad value
+ }
+
+ static LLStdStringHandle id_string = LLXmlTree::addAttributeString("id");
+ if (!child->getFastAttributeS32(id_string, info->mAttachmentID))
+ {
+ llwarns << "No id supplied for attachment point " << info->mName << llendl;
+ delete info;
+ continue;
+ }
+
+ static LLStdStringHandle slot_string = LLXmlTree::addAttributeString("pie_slice");
+ child->getFastAttributeS32(slot_string, info->mPieMenuSlice);
+
+ static LLStdStringHandle visible_in_first_person_string = LLXmlTree::addAttributeString("visible_in_first_person");
+ child->getFastAttributeBOOL(visible_in_first_person_string, info->mVisibleFirstPerson);
+
+ static LLStdStringHandle hud_attachment_string = LLXmlTree::addAttributeString("hud");
+ child->getFastAttributeBOOL(hud_attachment_string, info->mIsHUDAttachment);
+
+ mAttachmentInfoList.push_back(info);
+ }
+
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// parseXmlMeshNodes(): parses <mesh> nodes from XML tree
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlMeshNodes(LLXmlTreeNode* root)
+{
+ for (LLXmlTreeNode* node = root->getChildByName( "mesh" );
+ node;
+ node = root->getNextNamedChild())
+ {
+ LLVOAvatarMeshInfo *info = new LLVOAvatarMeshInfo;
+
+ // attribute: type
+ static LLStdStringHandle type_string = LLXmlTree::addAttributeString("type");
+ if( !node->getFastAttributeString( type_string, info->mType ) )
+ {
+ llwarns << "Avatar file: <mesh> is missing type attribute. Ignoring element. " << llendl;
+ delete info;
+ return FALSE; // Ignore this element
+ }
+
+ static LLStdStringHandle lod_string = LLXmlTree::addAttributeString("lod");
+ if (!node->getFastAttributeS32( lod_string, info->mLOD ))
+ {
+ llwarns << "Avatar file: <mesh> is missing lod attribute. Ignoring element. " << llendl;
+ delete info;
+ return FALSE; // Ignore this element
+ }
+
+ static LLStdStringHandle file_name_string = LLXmlTree::addAttributeString("file_name");
+ if( !node->getFastAttributeString( file_name_string, info->mMeshFileName ) )
+ {
+ llwarns << "Avatar file: <mesh> is missing file_name attribute. Ignoring: " << info->mType << llendl;
+ delete info;
+ return FALSE; // Ignore this element
+ }
+
+ static LLStdStringHandle reference_string = LLXmlTree::addAttributeString("reference");
+ node->getFastAttributeString( reference_string, info->mReferenceMeshName );
+
+ // attribute: min_pixel_area
+ static LLStdStringHandle min_pixel_area_string = LLXmlTree::addAttributeString("min_pixel_area");
+ static LLStdStringHandle min_pixel_width_string = LLXmlTree::addAttributeString("min_pixel_width");
+ if (!node->getFastAttributeF32( min_pixel_area_string, info->mMinPixelArea ))
+ {
+ F32 min_pixel_area = 0.1f;
+ if (node->getFastAttributeF32( min_pixel_width_string, min_pixel_area ))
+ {
+ // this is square root of pixel area (sensible to use linear space in defining lods)
+ min_pixel_area = min_pixel_area * min_pixel_area;
+ }
+ info->mMinPixelArea = min_pixel_area;
+ }
+
+ // Parse visual params for this node only if we haven't already
+ for (LLXmlTreeNode* child = node->getChildByName( "param" );
+ child;
+ child = node->getNextNamedChild())
+ {
+ if (!child->getChildByName("param_morph"))
+ {
+ if (child->getChildByName("param_skeleton"))
+ {
+ llwarns << "Can't specify skeleton param in a mesh definition." << llendl;
+ }
+ else
+ {
+ llwarns << "Unknown param type." << llendl;
+ }
+ continue;
+ }
+
+ LLPolyMorphTargetInfo *morphinfo = new LLPolyMorphTargetInfo();
+ if (!morphinfo->parseXml(child))
+ {
+ delete morphinfo;
+ delete info;
+ return -1;
+ }
+ BOOL shared = FALSE;
+ static LLStdStringHandle shared_string = LLXmlTree::addAttributeString("shared");
+ child->getFastAttributeBOOL(shared_string, shared);
+
+ info->mPolyMorphTargetInfoList.push_back(LLVOAvatarMeshInfo::morph_info_pair_t(morphinfo, shared));
+ }
+
+ mMeshInfoList.push_back(info);
+ }
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// parseXmlColorNodes(): parses <global_color> nodes from XML tree
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlColorNodes(LLXmlTreeNode* root)
+{
+ for (LLXmlTreeNode* color_node = root->getChildByName( "global_color" );
+ color_node;
+ color_node = root->getNextNamedChild())
+ {
+ std::string global_color_name;
+ static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
+ if (color_node->getFastAttributeString( name_string, global_color_name ) )
+ {
+ if( global_color_name == "skin_color" )
+ {
+ if (mTexSkinColorInfo)
+ {
+ llwarns << "avatar file: multiple instances of skin_color" << llendl;
+ return FALSE;
+ }
+ mTexSkinColorInfo = new LLTexGlobalColorInfo;
+ if( !mTexSkinColorInfo->parseXml( color_node ) )
+ {
+ deleteAndClear(mTexSkinColorInfo);
+ llwarns << "avatar file: mTexSkinColor->parseXml() failed" << llendl;
+ return FALSE;
+ }
+ }
+ else if( global_color_name == "hair_color" )
+ {
+ if (mTexHairColorInfo)
+ {
+ llwarns << "avatar file: multiple instances of hair_color" << llendl;
+ return FALSE;
+ }
+ mTexHairColorInfo = new LLTexGlobalColorInfo;
+ if( !mTexHairColorInfo->parseXml( color_node ) )
+ {
+ deleteAndClear(mTexHairColorInfo);
+ llwarns << "avatar file: mTexHairColor->parseXml() failed" << llendl;
+ return FALSE;
+ }
+ }
+ else if( global_color_name == "eye_color" )
+ {
+ if (mTexEyeColorInfo)
+ {
+ llwarns << "avatar file: multiple instances of eye_color" << llendl;
+ return FALSE;
+ }
+ mTexEyeColorInfo = new LLTexGlobalColorInfo;
+ if( !mTexEyeColorInfo->parseXml( color_node ) )
+ {
+ llwarns << "avatar file: mTexEyeColor->parseXml() failed" << llendl;
+ return FALSE;
+ }
+ }
+ }
+ }
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// parseXmlLayerNodes(): parses <layer_set> nodes from XML tree
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlLayerNodes(LLXmlTreeNode* root)
+{
+ for (LLXmlTreeNode* layer_node = root->getChildByName( "layer_set" );
+ layer_node;
+ layer_node = root->getNextNamedChild())
+ {
+ LLTexLayerSetInfo* layer_info = new LLTexLayerSetInfo();
+ if( layer_info->parseXml( layer_node ) )
+ {
+ mLayerInfoList.push_back(layer_info);
+ }
+ else
+ {
+ delete layer_info;
+ llwarns << "avatar file: layer_set->parseXml() failed" << llendl;
+ return FALSE;
+ }
+ }
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// parseXmlDriverNodes(): parses <driver_parameters> nodes from XML tree
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlDriverNodes(LLXmlTreeNode* root)
+{
+ LLXmlTreeNode* driver = root->getChildByName( "driver_parameters" );
+ if( driver )
+ {
+ for (LLXmlTreeNode* grand_child = driver->getChildByName( "param" );
+ grand_child;
+ grand_child = driver->getNextNamedChild())
+ {
+ if( grand_child->getChildByName( "param_driver" ) )
+ {
+ LLDriverParamInfo* driver_info = new LLDriverParamInfo();
+ if( driver_info->parseXml( grand_child ) )
+ {
+ mDriverInfoList.push_back(driver_info);
+ }
+ else
+ {
+ delete driver_info;
+ llwarns << "avatar file: driver_param->parseXml() failed" << llendl;
+ return FALSE;
+ }
+ }
+ }
+ }
+ return TRUE;
+}
+
+//-----------------------------------------------------------------------------
+// parseXmlDriverNodes(): parses <driver_parameters> nodes from XML tree
+//-----------------------------------------------------------------------------
+BOOL LLVOAvatar::LLVOAvatarXmlInfo::parseXmlMorphNodes(LLXmlTreeNode* root)
+{
+ LLXmlTreeNode* masks = root->getChildByName( "morph_masks" );
+ if( !masks )
+ {
+ return FALSE;
+ }
+
+ for (LLXmlTreeNode* grand_child = masks->getChildByName( "mask" );
+ grand_child;
+ grand_child = masks->getNextNamedChild())
+ {
+ LLVOAvatarMorphInfo* info = new LLVOAvatarMorphInfo();
+
+ static LLStdStringHandle name_string = LLXmlTree::addAttributeString("morph_name");
+ if (!grand_child->getFastAttributeString(name_string, info->mName))
+ {
+ llwarns << "No name supplied for morph mask." << llendl;
+ delete info;
+ continue;
+ }
+
+ static LLStdStringHandle region_string = LLXmlTree::addAttributeString("body_region");
+ if (!grand_child->getFastAttributeString(region_string, info->mRegion))
+ {
+ llwarns << "No region supplied for morph mask." << llendl;
+ delete info;
+ continue;
+ }
+
+ static LLStdStringHandle layer_string = LLXmlTree::addAttributeString("layer");
+ if (!grand_child->getFastAttributeString(layer_string, info->mLayer))
+ {
+ llwarns << "No layer supplied for morph mask." << llendl;
+ delete info;
+ continue;
+ }
+
+ // optional parameter. don't throw a warning if not present.
+ static LLStdStringHandle invert_string = LLXmlTree::addAttributeString("invert");
+ grand_child->getFastAttributeBOOL(invert_string, info->mInvert);
+
+ mMorphMaskInfoList.push_back(info);
+ }
+
+ return TRUE;
+}
+
+//virtual
+void LLVOAvatar::updateRegion(LLViewerRegion *regionp)
+{
+ LLViewerObject::updateRegion(regionp);
+}
+
+std::string LLVOAvatar::getFullname() const
+{
+ std::string name;
+
+ LLNameValue* first = getNVPair("FirstName");
+ LLNameValue* last = getNVPair("LastName");
+ if (first && last)
+ {
+ name = LLCacheName::buildFullName( first->getString(), last->getString() );
+ }
+
+ return name;
+}
+
+LLHost LLVOAvatar::getObjectHost() const
+{
+ LLViewerRegion* region = getRegion();
+ if (region && !isDead())
+ {
+ return region->getHost();
+ }
+ else
+ {
+ return LLHost::invalid;
+ }
+}
+
+//static
+void LLVOAvatar::updateFreezeCounter(S32 counter)
+{
+ if(counter)
+ {
+ sFreezeCounter = counter;
+ }
+ else if(sFreezeCounter > 0)
+ {
+ sFreezeCounter--;
+ }
+ else
+ {
+ sFreezeCounter = 0;
+ }
+}
+
+BOOL LLVOAvatar::updateLOD()
+{
+ if (isImpostor())
+ {
+ return TRUE;
+ }
+
+ BOOL res = updateJointLODs();
+
+ LLFace* facep = mDrawable->getFace(0);
+ if (!facep->getVertexBuffer())
+ {
+ dirtyMesh(2);
+ }
+
+ if (mDirtyMesh >= 2 || mDrawable->isState(LLDrawable::REBUILD_GEOMETRY))
+ { //LOD changed or new mesh created, allocate new vertex buffer if needed
+ updateMeshData();
+ mDirtyMesh = 0;
+ mNeedsSkin = TRUE;
+ mDrawable->clearState(LLDrawable::REBUILD_GEOMETRY);
+ }
+ updateVisibility();
+
+ return res;
+}
+
+void LLVOAvatar::updateLODRiggedAttachments( void )
+{
+ updateLOD();
+ rebuildRiggedAttachments();
+}
+U32 LLVOAvatar::getPartitionType() const
+{
+ // Avatars merely exist as drawables in the bridge partition
+ return LLViewerRegion::PARTITION_BRIDGE;
+}
+
+//static
+void LLVOAvatar::updateImpostors()
+{
+ for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
+ iter != LLCharacter::sInstances.end(); ++iter)
+ {
+ LLVOAvatar* avatar = (LLVOAvatar*) *iter;
+ if (!avatar->isDead() && avatar->needsImpostorUpdate() && avatar->isVisible() && avatar->isImpostor())
+ {
+ gPipeline.generateImpostor(avatar);
+ }
+ }
+}
+
+BOOL LLVOAvatar::isImpostor() const
+{
+ return (sUseImpostors && mUpdatePeriod >= IMPOSTOR_PERIOD) ? TRUE : FALSE;
+}
+
+
+BOOL LLVOAvatar::needsImpostorUpdate() const
+{
+ return mNeedsImpostorUpdate;
+}
+
+const LLVector3& LLVOAvatar::getImpostorOffset() const
+{
+ return mImpostorOffset;
+}
+
+const LLVector2& LLVOAvatar::getImpostorDim() const
+{
+ return mImpostorDim;
+}
+
+void LLVOAvatar::setImpostorDim(const LLVector2& dim)
+{
+ mImpostorDim = dim;
+}
+
+void LLVOAvatar::cacheImpostorValues()
+{
+ getImpostorValues(mImpostorExtents, mImpostorAngle, mImpostorDistance);
+}
+
+void LLVOAvatar::getImpostorValues(LLVector4a* extents, LLVector3& angle, F32& distance) const
+{
+ const LLVector4a* ext = mDrawable->getSpatialExtents();
+ extents[0] = ext[0];
+ extents[1] = ext[1];
+
+ LLVector3 at = LLViewerCamera::getInstance()->getOrigin()-(getRenderPosition()+mImpostorOffset);
+ distance = at.normalize();
+ F32 da = 1.f - (at*LLViewerCamera::getInstance()->getAtAxis());
+ angle.mV[0] = LLViewerCamera::getInstance()->getYaw()*da;
+ angle.mV[1] = LLViewerCamera::getInstance()->getPitch()*da;
+ angle.mV[2] = da;
+}
+
+void LLVOAvatar::idleUpdateRenderCost()
+{
+ static const U32 ARC_BODY_PART_COST = 20;
+ static const U32 ARC_LIMIT = 2048;
+
+ static std::set<LLUUID> all_textures;
+
+ if (!gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_SHAME))
+ {
+ return;
+ }
+
+ U32 cost = 0;
+ std::set<LLUUID> textures;
+
+ for (U8 baked_index = 0; baked_index < BAKED_NUM_INDICES; baked_index++)
+ {
+ const LLVOAvatarDictionary::BakedEntry *baked_dict = LLVOAvatarDictionary::getInstance()->getBakedTexture((EBakedTextureIndex)baked_index);
+ ETextureIndex tex_index = baked_dict->mTextureIndex;
+ if ((tex_index != TEX_SKIRT_BAKED) || (isWearingWearableType(LLWearableType::WT_SKIRT)))
+ {
+ if (isTextureVisible(tex_index))
+ {
+ cost +=ARC_BODY_PART_COST;
+ }
+ }
+ }
+
+ for (attachment_map_t::const_iterator iter = mAttachmentPoints.begin();
+ iter != mAttachmentPoints.end();
+ ++iter)
+ {
+ LLViewerJointAttachment* attachment = iter->second;
+ for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
+ attachment_iter != attachment->mAttachedObjects.end();
+ ++attachment_iter)
+ {
+ const LLViewerObject* attached_object = (*attachment_iter);
+ if (attached_object && !attached_object->isHUDAttachment())
+ {
+ const LLDrawable* drawable = attached_object->mDrawable;
+ if (drawable)
+ {
+ const LLVOVolume* volume = drawable->getVOVolume();
+ if (volume)
+ {
+ cost += volume->getRenderCost(textures);
+ }
+ }
+ }
+ }
+
+ }
+
+ // Diagnostic output to identify all avatar-related textures.
+ // Does not affect rendering cost calculation.
+ // Could be wrapped in a debug option if output becomes problematic.
+ if (isSelf())
+ {
+ // print any attachment textures we didn't already know about.
+ for (std::set<LLUUID>::iterator it = textures.begin(); it != textures.end(); ++it)
+ {
+ LLUUID image_id = *it;
+ if( image_id.isNull() || image_id == IMG_DEFAULT || image_id == IMG_DEFAULT_AVATAR)
+ continue;
+ if (all_textures.find(image_id) == all_textures.end())
+ {
+ // attachment texture not previously seen.
+ llinfos << "attachment_texture: " << image_id.asString() << llendl;
+ all_textures.insert(image_id);
+ }
+ }
+
+ // print any avatar textures we didn't already know about
+ for (LLVOAvatarDictionary::Textures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
+ iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
+ ++iter)
+ {
+ const LLVOAvatarDictionary::TextureEntry *texture_dict = iter->second;
+ // TODO: MULTI-WEARABLE: handle multiple textures for self
+ const LLViewerTexture* te_image = getImage(iter->first,0);
+ if (!te_image)
+ continue;
+ LLUUID image_id = te_image->getID();
+ if( image_id.isNull() || image_id == IMG_DEFAULT || image_id == IMG_DEFAULT_AVATAR)
+ continue;
+ if (all_textures.find(image_id) == all_textures.end())
+ {
+ llinfos << "local_texture: " << texture_dict->mName << ": " << image_id << llendl;
+ all_textures.insert(image_id);
+ }
+ }
+ }
+
+ cost += textures.size() * LLVOVolume::ARC_TEXTURE_COST;
+
+ setDebugText(llformat("%d", cost));
+ F32 green = 1.f-llclamp(((F32) cost-(F32)ARC_LIMIT)/(F32)ARC_LIMIT, 0.f, 1.f);
+ F32 red = llmin((F32) cost/(F32)ARC_LIMIT, 1.f);
+ mText->setColor(LLColor4(red,green,0,1));
+}
+
+// static
+BOOL LLVOAvatar::isIndexLocalTexture(ETextureIndex index)
+{
+ if (index < 0 || index >= TEX_NUM_INDICES) return false;
+ return LLVOAvatarDictionary::getInstance()->getTexture(index)->mIsLocalTexture;
+}
+
+// static
+BOOL LLVOAvatar::isIndexBakedTexture(ETextureIndex index)
+{
+ if (index < 0 || index >= TEX_NUM_INDICES) return false;
+ return LLVOAvatarDictionary::getInstance()->getTexture(index)->mIsBakedTexture;
+}
+
+const std::string LLVOAvatar::getBakedStatusForPrintout() const
+{
+ std::string line;
+
+ for (LLVOAvatarDictionary::Textures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getTextures().begin();
+ iter != LLVOAvatarDictionary::getInstance()->getTextures().end();
+ ++iter)
+ {
+ const ETextureIndex index = iter->first;
+ const LLVOAvatarDictionary::TextureEntry *texture_dict = iter->second;
+ if (texture_dict->mIsBakedTexture)
+ {
+ line += texture_dict->mName;
+ if (isTextureDefined(index))
+ {
+ line += "_baked";
+ }
+ line += " ";
+ }
+ }
+ return line;
+}
+
+
+
+//virtual
+S32 LLVOAvatar::getTexImageSize() const
+{
+ return TEX_IMAGE_SIZE_OTHER;
+}
+
+//-----------------------------------------------------------------------------
+// Utility functions
+//-----------------------------------------------------------------------------
+
+F32 calc_bouncy_animation(F32 x)
+{
+ return -(cosf(x * F_PI * 2.5f - F_PI_BY_TWO))*(0.4f + x * -0.1f) + x * 1.3f;
+}
+
+//virtual
+BOOL LLVOAvatar::isTextureDefined(LLVOAvatarDefines::ETextureIndex te, U32 index ) const
+{
+ if (isIndexLocalTexture(te))
+ {
+ return FALSE;
+ }
+
+ return (getImage(te, index)->getID() != IMG_DEFAULT_AVATAR &&
+ getImage(te, index)->getID() != IMG_DEFAULT);
+}
+
+//virtual
+BOOL LLVOAvatar::isTextureVisible(LLVOAvatarDefines::ETextureIndex type, U32 index) const
+{
+ if (isIndexLocalTexture(type))
+ {
+ return isTextureDefined(type, index);
+ }
+ else
+ {
+ // baked textures can use TE images directly
+ return ((isTextureDefined(type) || isSelf())
+ && (getTEImage(type)->getID() != IMG_INVISIBLE
+ || LLDrawPoolAlpha::sShowDebugAlpha));
+ }
+}
+
+//virtual
+BOOL LLVOAvatar::isTextureVisible(LLVOAvatarDefines::ETextureIndex type, LLWearable *wearable) const
+{
+ // non-self avatars don't have wearables
+ return FALSE;
+}
+
diff --git a/indra/newview/llvoavatar.h b/indra/newview/llvoavatar.h
index a779a1735c..7209b9f1e5 100644
--- a/indra/newview/llvoavatar.h
+++ b/indra/newview/llvoavatar.h
@@ -1,1063 +1,1086 @@
-/**
- * @file llvoavatar.h
- * @brief Declaration of LLVOAvatar class which is a derivation of
- * LLViewerObject
- *
- * $LicenseInfo:firstyear=2001&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-#ifndef LL_LLVOAVATAR_H
-#define LL_LLVOAVATAR_H
-
-#include <map>
-#include <deque>
-#include <string>
-#include <vector>
-
-#include <boost/signals2.hpp>
-
-#include "imageids.h" // IMG_INVISIBLE
-#include "llchat.h"
-#include "lldrawpoolalpha.h"
-#include "llviewerobject.h"
-#include "llcharacter.h"
-#include "llviewerjointmesh.h"
-#include "llviewerjointattachment.h"
-#include "llrendertarget.h"
-#include "llvoavatardefines.h"
-#include "lltexglobalcolor.h"
-#include "lldriverparam.h"
-#include "material_codes.h" // LL_MCODE_END
-
-extern const LLUUID ANIM_AGENT_BODY_NOISE;
-extern const LLUUID ANIM_AGENT_BREATHE_ROT;
-extern const LLUUID ANIM_AGENT_EDITING;
-extern const LLUUID ANIM_AGENT_EYE;
-extern const LLUUID ANIM_AGENT_FLY_ADJUST;
-extern const LLUUID ANIM_AGENT_HAND_MOTION;
-extern const LLUUID ANIM_AGENT_HEAD_ROT;
-extern const LLUUID ANIM_AGENT_PELVIS_FIX;
-extern const LLUUID ANIM_AGENT_TARGET;
-extern const LLUUID ANIM_AGENT_WALK_ADJUST;
-
-class LLTexLayerSet;
-class LLVoiceVisualizer;
-class LLHUDNameTag;
-class LLHUDEffectSpiral;
-class LLTexGlobalColor;
-class LLVOAvatarBoneInfo;
-class LLVOAvatarSkeletonInfo;
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// LLVOAvatar
-//
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class LLVOAvatar :
- public LLViewerObject,
- public LLCharacter,
- public boost::signals2::trackable
-{
-public:
- friend class LLVOAvatarSelf;
-protected:
- struct LLVOAvatarXmlInfo;
- struct LLMaskedMorph;
-
-/********************************************************************************
- ** **
- ** INITIALIZATION
- **/
-
-public:
- LLVOAvatar(const LLUUID &id, const LLPCode pcode, LLViewerRegion *regionp);
- virtual void markDead();
- static void initClass(); // Initialize data that's only init'd once per class.
- static void cleanupClass(); // Cleanup data that's only init'd once per class.
- virtual void initInstance(); // Called after construction to initialize the class.
-protected:
- virtual ~LLVOAvatar();
- BOOL loadSkeletonNode();
- BOOL loadMeshNodes();
- virtual BOOL loadLayersets();
-
-/** Initialization
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** INHERITED
- **/
-
- //--------------------------------------------------------------------
- // LLViewerObject interface and related
- //--------------------------------------------------------------------
-public:
- virtual void updateGL();
- virtual LLVOAvatar* asAvatar();
- virtual U32 processUpdateMessage(LLMessageSystem *mesgsys,
- void **user_data,
- U32 block_num,
- const EObjectUpdateType update_type,
- LLDataPacker *dp);
- virtual BOOL idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time);
- virtual BOOL updateLOD();
- BOOL updateJointLODs();
- virtual BOOL isActive() const; // Whether this object needs to do an idleUpdate.
- virtual void updateTextures();
- virtual S32 setTETexture(const U8 te, const LLUUID& uuid); // If setting a baked texture, need to request it from a non-local sim.
- virtual void onShift(const LLVector3& shift_vector);
- virtual U32 getPartitionType() const;
- virtual const LLVector3 getRenderPosition() const;
- virtual void updateDrawable(BOOL force_damped);
- virtual LLDrawable* createDrawable(LLPipeline *pipeline);
- virtual BOOL updateGeometry(LLDrawable *drawable);
- virtual void setPixelAreaAndAngle(LLAgent &agent);
- virtual void updateRegion(LLViewerRegion *regionp);
- virtual void updateSpatialExtents(LLVector3& newMin, LLVector3 &newMax);
- virtual void getSpatialExtents(LLVector3& newMin, LLVector3& newMax);
- virtual BOOL lineSegmentIntersect(const LLVector3& start, const LLVector3& end,
- S32 face = -1, // which face to check, -1 = ALL_SIDES
- BOOL pick_transparent = FALSE,
- S32* face_hit = NULL, // which face was hit
- LLVector3* intersection = NULL, // return the intersection point
- LLVector2* tex_coord = NULL, // return the texture coordinates of the intersection point
- LLVector3* normal = NULL, // return the surface normal at the intersection point
- LLVector3* bi_normal = NULL); // return the surface bi-normal at the intersection point
-
- //--------------------------------------------------------------------
- // LLCharacter interface and related
- //--------------------------------------------------------------------
-public:
- virtual LLVector3 getCharacterPosition();
- virtual LLQuaternion getCharacterRotation();
- virtual LLVector3 getCharacterVelocity();
- virtual LLVector3 getCharacterAngularVelocity();
- virtual LLJoint* getCharacterJoint(U32 num);
- virtual BOOL allocateCharacterJoints(U32 num);
-
- virtual LLUUID remapMotionID(const LLUUID& id);
- virtual BOOL startMotion(const LLUUID& id, F32 time_offset = 0.f);
- virtual BOOL stopMotion(const LLUUID& id, BOOL stop_immediate = FALSE);
- virtual void stopMotionFromSource(const LLUUID& source_id);
- virtual void requestStopMotion(LLMotion* motion);
- LLMotion* findMotion(const LLUUID& id) const;
- void startDefaultMotions();
- void dumpAnimationState();
-
- virtual LLJoint* getJoint(const std::string &name);
- virtual LLJoint* getRootJoint() { return &mRoot; }
-
- virtual const char* getAnimationPrefix() { return "avatar"; }
- virtual const LLUUID& getID();
- virtual LLVector3 getVolumePos(S32 joint_index, LLVector3& volume_offset);
- virtual LLJoint* findCollisionVolume(U32 volume_id);
- virtual S32 getCollisionVolumeID(std::string &name);
- virtual void addDebugText(const std::string& text);
- virtual F32 getTimeDilation();
- virtual void getGround(const LLVector3 &inPos, LLVector3 &outPos, LLVector3 &outNorm);
- virtual F32 getPixelArea() const;
- virtual LLPolyMesh* getHeadMesh();
- virtual LLPolyMesh* getUpperBodyMesh();
- virtual LLVector3d getPosGlobalFromAgent(const LLVector3 &position);
- virtual LLVector3 getPosAgentFromGlobal(const LLVector3d &position);
- virtual void updateVisualParams();
-
-
-/** Inherited
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** STATE
- **/
-
-public:
- virtual bool isSelf() const { return false; } // True if this avatar is for this viewer's agent
- bool isBuilt() const { return mIsBuilt; }
-private:
- BOOL mSupportsAlphaLayers; // For backwards compatibility, TRUE for 1.23+ clients
-
- //--------------------------------------------------------------------
- // Updates
- //--------------------------------------------------------------------
-public:
- virtual BOOL updateCharacter(LLAgent &agent);
- void idleUpdateVoiceVisualizer(bool voice_enabled);
- void idleUpdateMisc(bool detailed_update);
- virtual void idleUpdateAppearanceAnimation();
- void idleUpdateLipSync(bool voice_enabled);
- void idleUpdateLoadingEffect();
- void idleUpdateWindEffect();
- void idleUpdateNameTag(const LLVector3& root_pos_last);
- void idleUpdateNameTagText(BOOL new_name);
- LLVector3 idleUpdateNameTagPosition(const LLVector3& root_pos_last);
- void idleUpdateNameTagAlpha(BOOL new_name, F32 alpha);
- LLColor4 getNameTagColor(bool is_friend);
- void clearNameTag();
- static void invalidateNameTag(const LLUUID& agent_id);
- // force all name tags to rebuild, useful when display names turned on/off
- static void invalidateNameTags();
- void addNameTagLine(const std::string& line, const LLColor4& color, S32 style, const LLFontGL* font);
- void idleUpdateRenderCost();
- void idleUpdateBelowWater();
-
- //--------------------------------------------------------------------
- // Static preferences (controlled by user settings/menus)
- //--------------------------------------------------------------------
-public:
- static S32 sRenderName;
- static BOOL sRenderGroupTitles;
- static U32 sMaxVisible; //(affected by control "RenderAvatarMaxVisible")
- static F32 sRenderDistance; //distance at which avatars will render.
- static BOOL sShowAnimationDebug; // show animation debug info
- static BOOL sUseImpostors; //use impostors for far away avatars
- static BOOL sShowFootPlane; // show foot collision plane reported by server
- static BOOL sShowCollisionVolumes; // show skeletal collision volumes
- static BOOL sVisibleInFirstPerson;
- static S32 sNumLODChangesThisFrame;
- static S32 sNumVisibleChatBubbles;
- static BOOL sDebugInvisible;
- static BOOL sShowAttachmentPoints;
- static F32 sLODFactor; // user-settable LOD factor
- static BOOL sJointDebug; // output total number of joints being touched for each avatar
- static BOOL sDebugAvatarRotation;
-
- //--------------------------------------------------------------------
- // Region state
- //--------------------------------------------------------------------
-public:
- LLHost getObjectHost() const;
-
- //--------------------------------------------------------------------
- // Loading state
- //--------------------------------------------------------------------
-public:
- BOOL isFullyLoaded() const;
- bool visualParamWeightsAreDefault();
-protected:
- virtual BOOL getIsCloud();
- BOOL updateIsFullyLoaded();
- BOOL processFullyLoadedChange(bool loading);
- void updateRuthTimer(bool loading);
- F32 calcMorphAmount();
-private:
- BOOL mFullyLoaded;
- BOOL mPreviousFullyLoaded;
- BOOL mFullyLoadedInitialized;
- S32 mFullyLoadedFrameCounter;
- LLFrameTimer mFullyLoadedTimer;
- LLFrameTimer mRuthTimer;
-protected:
- LLFrameTimer mInvisibleTimer;
-
-/** State
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** SKELETON
- **/
-
-public:
- void updateHeadOffset();
- F32 getPelvisToFoot() const { return mPelvisToFoot; }
-
- LLVector3 mHeadOffset; // current head position
- LLViewerJoint mRoot;
-protected:
- static BOOL parseSkeletonFile(const std::string& filename);
- void buildCharacter();
- virtual BOOL loadAvatar();
-
- BOOL setupBone(const LLVOAvatarBoneInfo* info, LLViewerJoint* parent, S32 &current_volume_num, S32 &current_joint_num);
- BOOL buildSkeleton(const LLVOAvatarSkeletonInfo *info);
-private:
- BOOL mIsBuilt; // state of deferred character building
- S32 mNumJoints;
- LLViewerJoint* mSkeleton;
-
- //--------------------------------------------------------------------
- // Pelvis height adjustment members.
- //--------------------------------------------------------------------
-public:
- LLVector3 mBodySize;
- S32 mLastSkeletonSerialNum;
-private:
- F32 mPelvisToFoot;
-
- //--------------------------------------------------------------------
- // Cached pointers to well known joints
- //--------------------------------------------------------------------
-public:
- LLViewerJoint* mPelvisp;
- LLViewerJoint* mTorsop;
- LLViewerJoint* mChestp;
- LLViewerJoint* mNeckp;
- LLViewerJoint* mHeadp;
- LLViewerJoint* mSkullp;
- LLViewerJoint* mEyeLeftp;
- LLViewerJoint* mEyeRightp;
- LLViewerJoint* mHipLeftp;
- LLViewerJoint* mHipRightp;
- LLViewerJoint* mKneeLeftp;
- LLViewerJoint* mKneeRightp;
- LLViewerJoint* mAnkleLeftp;
- LLViewerJoint* mAnkleRightp;
- LLViewerJoint* mFootLeftp;
- LLViewerJoint* mFootRightp;
- LLViewerJoint* mWristLeftp;
- LLViewerJoint* mWristRightp;
-
- //--------------------------------------------------------------------
- // XML parse tree
- //--------------------------------------------------------------------
-private:
- static LLXmlTree sXMLTree; // avatar config file
- static LLXmlTree sSkeletonXMLTree; // avatar skeleton file
-
-/** Skeleton
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** RENDERING
- **/
-
-public:
- U32 renderImpostor(LLColor4U color = LLColor4U(255,255,255,255), S32 diffuse_channel = 0);
- U32 renderRigid();
- U32 renderSkinned(EAvatarRenderPass pass);
- U32 renderTransparent(BOOL first_pass);
- void renderCollisionVolumes();
- static void deleteCachedImages(bool clearAll=true);
- static void destroyGL();
- static void restoreGL();
- BOOL mIsDummy; // for special views
- S32 mSpecialRenderMode; // special lighting
-private:
- bool shouldAlphaMask();
-
- BOOL mNeedsSkin; // avatar has been animated and verts have not been updated
- S32 mUpdatePeriod;
- S32 mNumInitFaces; //number of faces generated when creating the avatar drawable, does not inculde splitted faces due to long vertex buffer.
-
- //--------------------------------------------------------------------
- // Morph masks
- //--------------------------------------------------------------------
-public:
- BOOL morphMaskNeedsUpdate(LLVOAvatarDefines::EBakedTextureIndex index = LLVOAvatarDefines::BAKED_NUM_INDICES);
- void addMaskedMorph(LLVOAvatarDefines::EBakedTextureIndex index, LLPolyMorphTarget* morph_target, BOOL invert, std::string layer);
- void applyMorphMask(U8* tex_data, S32 width, S32 height, S32 num_components, LLVOAvatarDefines::EBakedTextureIndex index = LLVOAvatarDefines::BAKED_NUM_INDICES);
-
- //--------------------------------------------------------------------
- // Visibility
- //--------------------------------------------------------------------
-protected:
- void updateVisibility();
-private:
- U32 mVisibilityRank;
- BOOL mVisible;
-
- //--------------------------------------------------------------------
- // Shadowing
- //--------------------------------------------------------------------
-public:
- void updateShadowFaces();
- LLDrawable* mShadow;
-private:
- LLFace* mShadow0Facep;
- LLFace* mShadow1Facep;
- LLPointer<LLViewerTexture> mShadowImagep;
-
- //--------------------------------------------------------------------
- // Impostors
- //--------------------------------------------------------------------
-public:
- BOOL isImpostor() const;
- BOOL needsImpostorUpdate() const;
- const LLVector3& getImpostorOffset() const;
- const LLVector2& getImpostorDim() const;
- void getImpostorValues(LLVector3* extents, LLVector3& angle, F32& distance) const;
- void cacheImpostorValues();
- void setImpostorDim(const LLVector2& dim);
- static void resetImpostors();
- static void updateImpostors();
- LLRenderTarget mImpostor;
- BOOL mNeedsImpostorUpdate;
-private:
- LLVector3 mImpostorOffset;
- LLVector2 mImpostorDim;
- BOOL mNeedsAnimUpdate;
- LLVector3 mImpostorExtents[2];
- LLVector3 mImpostorAngle;
- F32 mImpostorDistance;
- F32 mImpostorPixelArea;
- LLVector3 mLastAnimExtents[2];
-
- //--------------------------------------------------------------------
- // Wind rippling in clothes
- //--------------------------------------------------------------------
-public:
- LLVector4 mWindVec;
- F32 mRipplePhase;
- BOOL mBelowWater;
-private:
- F32 mWindFreq;
- LLFrameTimer mRippleTimer;
- F32 mRippleTimeLast;
- LLVector3 mRippleAccel;
- LLVector3 mLastVel;
-
- //--------------------------------------------------------------------
- // Culling
- //--------------------------------------------------------------------
-public:
- static void cullAvatarsByPixelArea();
- BOOL isCulled() const { return mCulled; }
-private:
- BOOL mCulled;
-
- //--------------------------------------------------------------------
- // Freeze counter
- //--------------------------------------------------------------------
-public:
- static void updateFreezeCounter(S32 counter = 0);
-private:
- static S32 sFreezeCounter;
-
- //--------------------------------------------------------------------
- // Constants
- //--------------------------------------------------------------------
-public:
- virtual LLViewerTexture::EBoostLevel getAvatarBoostLevel() const { return LLViewerTexture::BOOST_AVATAR; }
- virtual LLViewerTexture::EBoostLevel getAvatarBakedBoostLevel() const { return LLViewerTexture::BOOST_AVATAR_BAKED; }
- virtual S32 getTexImageSize() const;
- virtual S32 getTexImageArea() const { return getTexImageSize()*getTexImageSize(); }
-
-/** Rendering
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** TEXTURES
- **/
-
- //--------------------------------------------------------------------
- // Loading status
- //--------------------------------------------------------------------
-public:
- virtual BOOL isTextureDefined(LLVOAvatarDefines::ETextureIndex type, U32 index = 0) const;
- virtual BOOL isTextureVisible(LLVOAvatarDefines::ETextureIndex type, U32 index = 0) const;
- virtual BOOL isTextureVisible(LLVOAvatarDefines::ETextureIndex type, LLWearable *wearable) const;
-
-protected:
- BOOL isFullyBaked();
- static BOOL areAllNearbyInstancesBaked(S32& grey_avatars);
-
- //--------------------------------------------------------------------
- // Baked textures
- //--------------------------------------------------------------------
-public:
- void releaseComponentTextures(); // ! BACKWARDS COMPATIBILITY !
-protected:
- static void onBakedTextureMasksLoaded(BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata);
- static void onInitialBakedTextureLoaded(BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata);
- static void onBakedTextureLoaded(BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata);
- virtual void removeMissingBakedTextures();
- void useBakedTexture(const LLUUID& id);
-
- typedef std::deque<LLMaskedMorph *> morph_list_t;
- struct BakedTextureData
- {
- LLUUID mLastTextureIndex;
- LLTexLayerSet* mTexLayerSet; // Only exists for self
- bool mIsLoaded;
- bool mIsUsed;
- LLVOAvatarDefines::ETextureIndex mTextureIndex;
- U32 mMaskTexName;
- // Stores pointers to the joint meshes that this baked texture deals with
- std::vector< LLViewerJointMesh * > mMeshes; // std::vector<LLViewerJointMesh> mJoints[i]->mMeshParts
- morph_list_t mMaskedMorphs;
- };
- typedef std::vector<BakedTextureData> bakedtexturedata_vec_t;
- bakedtexturedata_vec_t mBakedTextureDatas;
- LLLoadedCallbackEntry::source_callback_list_t mCallbackTextureList ;
- BOOL mLoadedCallbacksPaused;
- //--------------------------------------------------------------------
- // Local Textures
- //--------------------------------------------------------------------
-protected:
- virtual void setLocalTexture(LLVOAvatarDefines::ETextureIndex type, LLViewerTexture* tex, BOOL baked_version_exits, U32 index = 0);
- virtual void addLocalTextureStats(LLVOAvatarDefines::ETextureIndex type, LLViewerFetchedTexture* imagep, F32 texel_area_ratio, BOOL rendered, BOOL covered_by_baked, U32 index = 0);
- // MULTI-WEARABLE: make self-only?
- virtual void setBakedReady(LLVOAvatarDefines::ETextureIndex type, BOOL baked_version_exists, U32 index = 0);
-
- //--------------------------------------------------------------------
- // Texture accessors
- //--------------------------------------------------------------------
-private:
- virtual void setImage(const U8 te, LLViewerTexture *imagep, const U32 index);
- virtual LLViewerTexture* getImage(const U8 te, const U32 index) const;
-
- virtual const LLTextureEntry* getTexEntry(const U8 te_num) const;
- virtual void setTexEntry(const U8 index, const LLTextureEntry &te);
-
- void checkTextureLoading() ;
- //--------------------------------------------------------------------
- // Layers
- //--------------------------------------------------------------------
-protected:
- void deleteLayerSetCaches(bool clearAll = true);
- void addBakedTextureStats(LLViewerFetchedTexture* imagep, F32 pixel_area, F32 texel_area_ratio, S32 boost_level);
-
- //--------------------------------------------------------------------
- // Composites
- //--------------------------------------------------------------------
-public:
- virtual void invalidateComposite(LLTexLayerSet* layerset, BOOL upload_result);
- virtual void invalidateAll();
- virtual void setCompositeUpdatesEnabled(bool b) {}
- virtual void setCompositeUpdatesEnabled(U32 index, bool b) {}
- virtual bool isCompositeUpdateEnabled(U32 index) { return false; }
-
- //--------------------------------------------------------------------
- // Static texture/mesh/baked dictionary
- //--------------------------------------------------------------------
-public:
- static BOOL isIndexLocalTexture(LLVOAvatarDefines::ETextureIndex i);
- static BOOL isIndexBakedTexture(LLVOAvatarDefines::ETextureIndex i);
-private:
- static const LLVOAvatarDefines::LLVOAvatarDictionary *getDictionary() { return sAvatarDictionary; }
- static LLVOAvatarDefines::LLVOAvatarDictionary* sAvatarDictionary;
- static LLVOAvatarSkeletonInfo* sAvatarSkeletonInfo;
- static LLVOAvatarXmlInfo* sAvatarXmlInfo;
-
- //--------------------------------------------------------------------
- // Messaging
- //--------------------------------------------------------------------
-public:
- void onFirstTEMessageReceived();
-private:
- BOOL mFirstTEMessageReceived;
- BOOL mFirstAppearanceMessageReceived;
-
-/** Textures
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** MESHES
- **/
-
-public:
- void updateMeshTextures();
- void updateSexDependentLayerSets(BOOL upload_bake);
- void dirtyMesh(); // Dirty the avatar mesh
- void updateMeshData();
-protected:
- void releaseMeshData();
- virtual void restoreMeshData();
-private:
- void dirtyMesh(S32 priority); // Dirty the avatar mesh, with priority
- S32 mDirtyMesh; // 0 -- not dirty, 1 -- morphed, 2 -- LOD
- BOOL mMeshTexturesDirty;
-
- typedef std::multimap<std::string, LLPolyMesh*> polymesh_map_t;
- polymesh_map_t mMeshes;
- std::vector<LLViewerJoint *> mMeshLOD;
-
- //--------------------------------------------------------------------
- // Destroy invisible mesh
- //--------------------------------------------------------------------
-protected:
- BOOL mMeshValid;
- LLFrameTimer mMeshInvisibleTime;
-
-/** Meshes
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** APPEARANCE
- **/
-
-public:
- void processAvatarAppearance(LLMessageSystem* mesgsys);
- void hideSkirt();
- void startAppearanceAnimation();
-
- //--------------------------------------------------------------------
- // Appearance morphing
- //--------------------------------------------------------------------
-public:
- BOOL getIsAppearanceAnimating() const { return mAppearanceAnimating; }
-private:
- BOOL mAppearanceAnimating;
- LLFrameTimer mAppearanceMorphTimer;
- F32 mLastAppearanceBlendTime;
-
- //--------------------------------------------------------------------
- // Clothing colors (convenience functions to access visual parameters)
- //--------------------------------------------------------------------
-public:
- void setClothesColor(LLVOAvatarDefines::ETextureIndex te, const LLColor4& new_color, BOOL upload_bake);
- LLColor4 getClothesColor(LLVOAvatarDefines::ETextureIndex te);
- static BOOL teToColorParams(LLVOAvatarDefines::ETextureIndex te, U32 *param_name);
-
- //--------------------------------------------------------------------
- // Global colors
- //--------------------------------------------------------------------
-public:
- LLColor4 getGlobalColor(const std::string& color_name ) const;
- void onGlobalColorChanged(const LLTexGlobalColor* global_color, BOOL upload_bake);
-private:
- LLTexGlobalColor* mTexSkinColor;
- LLTexGlobalColor* mTexHairColor;
- LLTexGlobalColor* mTexEyeColor;
-
- //--------------------------------------------------------------------
- // Visibility
- //--------------------------------------------------------------------
-public:
- BOOL isVisible() const;
- void setVisibilityRank(U32 rank);
- U32 getVisibilityRank() const { return mVisibilityRank; } // unused
- static S32 sNumVisibleAvatars; // Number of instances of this class
- static LLColor4 getDummyColor();
-/** Appearance
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** WEARABLES
- **/
-
-public:
- virtual BOOL isWearingWearableType(LLWearableType::EType type ) const;
-
- //--------------------------------------------------------------------
- // Attachments
- //--------------------------------------------------------------------
-public:
- void clampAttachmentPositions();
- virtual const LLViewerJointAttachment* attachObject(LLViewerObject *viewer_object);
- virtual BOOL detachObject(LLViewerObject *viewer_object);
- static LLVOAvatar* findAvatarFromAttachment(LLViewerObject* obj);
-protected:
- LLViewerJointAttachment* getTargetAttachmentPoint(LLViewerObject* viewer_object);
- void lazyAttach();
-
- //--------------------------------------------------------------------
- // Map of attachment points, by ID
- //--------------------------------------------------------------------
-public:
- S32 getAttachmentCount(); // Warning: order(N) not order(1) // currently used only by -self
- typedef std::map<S32, LLViewerJointAttachment*> attachment_map_t;
- attachment_map_t mAttachmentPoints;
- std::vector<LLPointer<LLViewerObject> > mPendingAttachment;
-
- //--------------------------------------------------------------------
- // HUD functions
- //--------------------------------------------------------------------
-public:
- BOOL hasHUDAttachment() const;
- LLBBox getHUDBBox() const;
- void rebuildHUD();
- void resetHUDAttachments();
- BOOL canAttachMoreObjects() const;
- BOOL canAttachMoreObjects(U32 n) const;
-protected:
- U32 getNumAttachments() const; // O(N), not O(1)
-
-/** Wearables
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** ACTIONS
- **/
-
- //--------------------------------------------------------------------
- // Animations
- //--------------------------------------------------------------------
-public:
- BOOL isAnyAnimationSignaled(const LLUUID *anim_array, const S32 num_anims) const;
- void processAnimationStateChanges();
-protected:
- BOOL processSingleAnimationStateChange(const LLUUID &anim_id, BOOL start);
- void resetAnimations();
-private:
- LLTimer mAnimTimer;
- F32 mTimeLast;
-
- //--------------------------------------------------------------------
- // Animation state data
- //--------------------------------------------------------------------
-public:
- typedef std::map<LLUUID, S32>::iterator AnimIterator;
- std::map<LLUUID, S32> mSignaledAnimations; // requested state of Animation name/value
- std::map<LLUUID, S32> mPlayingAnimations; // current state of Animation name/value
-
- typedef std::multimap<LLUUID, LLUUID> AnimationSourceMap;
- typedef AnimationSourceMap::iterator AnimSourceIterator;
- AnimationSourceMap mAnimationSources; // object ids that triggered anim ids
-
- //--------------------------------------------------------------------
- // Chat
- //--------------------------------------------------------------------
-public:
- void addChat(const LLChat& chat);
- void clearChat();
- void startTyping() { mTyping = TRUE; mTypingTimer.reset(); }
- void stopTyping() { mTyping = FALSE; }
-private:
- BOOL mVisibleChat;
-
- //--------------------------------------------------------------------
- // Lip synch morphs
- //--------------------------------------------------------------------
-private:
- bool mLipSyncActive; // we're morphing for lip sync
- LLVisualParam* mOohMorph; // cached pointers morphs for lip sync
- LLVisualParam* mAahMorph; // cached pointers morphs for lip sync
-
- //--------------------------------------------------------------------
- // Flight
- //--------------------------------------------------------------------
-public:
- BOOL mInAir;
- LLFrameTimer mTimeInAir;
-
-/** Actions
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** PHYSICS
- **/
-
-private:
- F32 mSpeedAccum; // measures speed (for diagnostics mostly).
- BOOL mTurning; // controls hysteresis on avatar rotation
- F32 mSpeed; // misc. animation repeated state
-
- //--------------------------------------------------------------------
- // Collision volumes
- //--------------------------------------------------------------------
-public:
- S32 mNumCollisionVolumes;
- LLViewerJointCollisionVolume* mCollisionVolumes;
-protected:
- BOOL allocateCollisionVolumes(U32 num);
-
- //--------------------------------------------------------------------
- // Dimensions
- //--------------------------------------------------------------------
-public:
- void resolveHeightGlobal(const LLVector3d &inPos, LLVector3d &outPos, LLVector3 &outNorm);
- void resolveHeightAgent(const LLVector3 &inPos, LLVector3 &outPos, LLVector3 &outNorm);
- void resolveRayCollisionAgent(const LLVector3d start_pt, const LLVector3d end_pt, LLVector3d &out_pos, LLVector3 &out_norm);
- void slamPosition(); // Slam position to transmitted position (for teleport);
-protected:
- void computeBodySize();
-
- //--------------------------------------------------------------------
- // Material being stepped on
- //--------------------------------------------------------------------
-private:
- BOOL mStepOnLand;
- U8 mStepMaterial;
- LLVector3 mStepObjectVelocity;
-
-/** Physics
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** HIERARCHY
- **/
-
-public:
- virtual BOOL setParent(LLViewerObject* parent);
- virtual void addChild(LLViewerObject *childp);
- virtual void removeChild(LLViewerObject *childp);
-
- //--------------------------------------------------------------------
- // Sitting
- //--------------------------------------------------------------------
-public:
- void sitDown(BOOL bSitting);
- BOOL isSitting(){return mIsSitting;}
- void sitOnObject(LLViewerObject *sit_object);
- void getOffObject();
-private:
- // set this property only with LLVOAvatar::sitDown method
- BOOL mIsSitting;
-
-/** Hierarchy
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** NAME
- **/
-
-public:
- std::string getFullname() const; // Returns "FirstName LastName"
-protected:
- static void getAnimLabels(LLDynamicArray<std::string>* labels);
- static void getAnimNames(LLDynamicArray<std::string>* names);
-private:
- std::string mNameString; // UTF-8 title + name + status
- std::string mTitle;
- bool mNameAway;
- bool mNameBusy;
- bool mNameMute;
- bool mNameAppearance;
- bool mNameFriend;
- bool mNameCloud;
- F32 mNameAlpha;
- BOOL mRenderGroupTitles;
-
- //--------------------------------------------------------------------
- // Display the name (then optionally fade it out)
- //--------------------------------------------------------------------
-public:
- LLFrameTimer mChatTimer;
- LLPointer<LLHUDNameTag> mNameText;
-private:
- LLFrameTimer mTimeVisible;
- std::deque<LLChat> mChats;
- BOOL mTyping;
- LLFrameTimer mTypingTimer;
-
-/** Name
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** SOUNDS
- **/
-
- //--------------------------------------------------------------------
- // Voice visualizer
- //--------------------------------------------------------------------
-public:
- // Responsible for detecting the user's voice signal (and when the
- // user speaks, it puts a voice symbol over the avatar's head) and gesticulations
- LLPointer<LLVoiceVisualizer> mVoiceVisualizer;
- int mCurrentGesticulationLevel;
-
- //--------------------------------------------------------------------
- // Step sound
- //--------------------------------------------------------------------
-protected:
- const LLUUID& getStepSound() const;
-private:
- // Global table of sound ids per material, and the ground
- const static LLUUID sStepSounds[LL_MCODE_END];
- const static LLUUID sStepSoundOnLand;
-
- //--------------------------------------------------------------------
- // Foot step state (for generating sounds)
- //--------------------------------------------------------------------
-public:
- void setFootPlane(const LLVector4 &plane) { mFootPlane = plane; }
- LLVector4 mFootPlane;
-private:
- BOOL mWasOnGroundLeft;
- BOOL mWasOnGroundRight;
-
-/** Sounds
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** DIAGNOSTICS
- **/
-
- //--------------------------------------------------------------------
- // General
- //--------------------------------------------------------------------
-public:
- static void dumpArchetypeXML(void*);
- static void dumpBakedStatus();
- const std::string getBakedStatusForPrintout() const;
- void dumpAvatarTEs(const std::string& context) const;
-
- static F32 sUnbakedTime; // Total seconds with >=1 unbaked avatars
- static F32 sUnbakedUpdateTime; // Last time stats were updated (to prevent multiple updates per frame)
- static F32 sGreyTime; // Total seconds with >=1 grey avatars
- static F32 sGreyUpdateTime; // Last time stats were updated (to prevent multiple updates per frame)
-protected:
- S32 getUnbakedPixelAreaRank();
- BOOL mHasGrey;
-private:
- F32 mMinPixelArea;
- F32 mMaxPixelArea;
- F32 mAdjustedPixelArea;
- std::string mDebugText;
-
-
- //--------------------------------------------------------------------
- // Avatar Rez Metrics
- //--------------------------------------------------------------------
-public:
- F32 debugGetExistenceTimeElapsedF32() const { return mDebugExistenceTimer.getElapsedTimeF32(); }
-protected:
- LLFrameTimer mRuthDebugTimer; // For tracking how long it takes for av to rez
- LLFrameTimer mDebugExistenceTimer; // Debugging for how long the avatar has been in memory.
-
-/** Diagnostics
- ** **
- *******************************************************************************/
-
-/********************************************************************************
- ** **
- ** SUPPORT CLASSES
- **/
-
-protected: // Shared with LLVOAvatarSelf
-
- struct LLVOAvatarXmlInfo
- {
- LLVOAvatarXmlInfo();
- ~LLVOAvatarXmlInfo();
-
- BOOL parseXmlSkeletonNode(LLXmlTreeNode* root);
- BOOL parseXmlMeshNodes(LLXmlTreeNode* root);
- BOOL parseXmlColorNodes(LLXmlTreeNode* root);
- BOOL parseXmlLayerNodes(LLXmlTreeNode* root);
- BOOL parseXmlDriverNodes(LLXmlTreeNode* root);
- BOOL parseXmlMorphNodes(LLXmlTreeNode* root);
-
- struct LLVOAvatarMeshInfo
- {
- typedef std::pair<LLPolyMorphTargetInfo*,BOOL> morph_info_pair_t;
- typedef std::vector<morph_info_pair_t> morph_info_list_t;
-
- LLVOAvatarMeshInfo() : mLOD(0), mMinPixelArea(.1f) {}
- ~LLVOAvatarMeshInfo()
- {
- morph_info_list_t::iterator iter;
- for (iter = mPolyMorphTargetInfoList.begin(); iter != mPolyMorphTargetInfoList.end(); iter++)
- {
- delete iter->first;
- }
- mPolyMorphTargetInfoList.clear();
- }
-
- std::string mType;
- S32 mLOD;
- std::string mMeshFileName;
- std::string mReferenceMeshName;
- F32 mMinPixelArea;
- morph_info_list_t mPolyMorphTargetInfoList;
- };
- typedef std::vector<LLVOAvatarMeshInfo*> mesh_info_list_t;
- mesh_info_list_t mMeshInfoList;
-
- typedef std::vector<LLPolySkeletalDistortionInfo*> skeletal_distortion_info_list_t;
- skeletal_distortion_info_list_t mSkeletalDistortionInfoList;
-
- struct LLVOAvatarAttachmentInfo
- {
- LLVOAvatarAttachmentInfo()
- : mGroup(-1), mAttachmentID(-1), mPieMenuSlice(-1), mVisibleFirstPerson(FALSE),
- mIsHUDAttachment(FALSE), mHasPosition(FALSE), mHasRotation(FALSE) {}
- std::string mName;
- std::string mJointName;
- LLVector3 mPosition;
- LLVector3 mRotationEuler;
- S32 mGroup;
- S32 mAttachmentID;
- S32 mPieMenuSlice;
- BOOL mVisibleFirstPerson;
- BOOL mIsHUDAttachment;
- BOOL mHasPosition;
- BOOL mHasRotation;
- };
- typedef std::vector<LLVOAvatarAttachmentInfo*> attachment_info_list_t;
- attachment_info_list_t mAttachmentInfoList;
-
- LLTexGlobalColorInfo *mTexSkinColorInfo;
- LLTexGlobalColorInfo *mTexHairColorInfo;
- LLTexGlobalColorInfo *mTexEyeColorInfo;
-
- typedef std::vector<LLTexLayerSetInfo*> layer_info_list_t;
- layer_info_list_t mLayerInfoList;
-
- typedef std::vector<LLDriverParamInfo*> driver_info_list_t;
- driver_info_list_t mDriverInfoList;
-
- struct LLVOAvatarMorphInfo
- {
- LLVOAvatarMorphInfo()
- : mInvert(FALSE) {}
- std::string mName;
- std::string mRegion;
- std::string mLayer;
- BOOL mInvert;
- };
-
- typedef std::vector<LLVOAvatarMorphInfo*> morph_info_list_t;
- morph_info_list_t mMorphMaskInfoList;
- };
-
- struct LLMaskedMorph
- {
- LLMaskedMorph(LLPolyMorphTarget *morph_target, BOOL invert, std::string layer) :
- mMorphTarget(morph_target),
- mInvert(invert),
- mLayer(layer)
- {
- morph_target->addPendingMorphMask();
- }
-
- LLPolyMorphTarget *mMorphTarget;
- BOOL mInvert;
- std::string mLayer;
- };
-
-/** Support classes
- ** **
- *******************************************************************************/
-
-}; // LLVOAvatar
-extern const F32 SELF_ADDITIONAL_PRI;
-extern const S32 MAX_TEXTURE_VIRTURE_SIZE_RESET_INTERVAL;
-
-#endif // LL_VO_AVATAR_H
+/**
+ * @file llvoavatar.h
+ * @brief Declaration of LLVOAvatar class which is a derivation of
+ * LLViewerObject
+ *
+ * $LicenseInfo:firstyear=2001&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#ifndef LL_LLVOAVATAR_H
+#define LL_LLVOAVATAR_H
+
+#include <map>
+#include <deque>
+#include <string>
+#include <vector>
+
+#include <boost/signals2.hpp>
+
+#include "imageids.h" // IMG_INVISIBLE
+#include "llchat.h"
+#include "lldrawpoolalpha.h"
+#include "llviewerobject.h"
+#include "llcharacter.h"
+#include "llviewerjointmesh.h"
+#include "llviewerjointattachment.h"
+#include "llrendertarget.h"
+#include "llvoavatardefines.h"
+#include "lltexglobalcolor.h"
+#include "lldriverparam.h"
+#include "material_codes.h" // LL_MCODE_END
+
+extern const LLUUID ANIM_AGENT_BODY_NOISE;
+extern const LLUUID ANIM_AGENT_BREATHE_ROT;
+extern const LLUUID ANIM_AGENT_EDITING;
+extern const LLUUID ANIM_AGENT_EYE;
+extern const LLUUID ANIM_AGENT_FLY_ADJUST;
+extern const LLUUID ANIM_AGENT_HAND_MOTION;
+extern const LLUUID ANIM_AGENT_HEAD_ROT;
+extern const LLUUID ANIM_AGENT_PELVIS_FIX;
+extern const LLUUID ANIM_AGENT_TARGET;
+extern const LLUUID ANIM_AGENT_WALK_ADJUST;
+
+class LLTexLayerSet;
+class LLVoiceVisualizer;
+class LLHUDNameTag;
+class LLHUDEffectSpiral;
+class LLTexGlobalColor;
+class LLVOAvatarBoneInfo;
+class LLVOAvatarSkeletonInfo;
+
+//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+// LLVOAvatar
+//
+//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+class LLVOAvatar :
+ public LLViewerObject,
+ public LLCharacter,
+ public boost::signals2::trackable
+{
+public:
+ friend class LLVOAvatarSelf;
+protected:
+ struct LLVOAvatarXmlInfo;
+ struct LLMaskedMorph;
+
+/********************************************************************************
+ ** **
+ ** INITIALIZATION
+ **/
+
+public:
+ LLVOAvatar(const LLUUID &id, const LLPCode pcode, LLViewerRegion *regionp);
+ virtual void markDead();
+ static void initClass(); // Initialize data that's only init'd once per class.
+ static void cleanupClass(); // Cleanup data that's only init'd once per class.
+ virtual void initInstance(); // Called after construction to initialize the class.
+protected:
+ virtual ~LLVOAvatar();
+ BOOL loadSkeletonNode();
+ BOOL loadMeshNodes();
+ virtual BOOL loadLayersets();
+
+/** Initialization
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** INHERITED
+ **/
+
+ //--------------------------------------------------------------------
+ // LLViewerObject interface and related
+ //--------------------------------------------------------------------
+public:
+ virtual void updateGL();
+ virtual LLVOAvatar* asAvatar();
+ virtual U32 processUpdateMessage(LLMessageSystem *mesgsys,
+ void **user_data,
+ U32 block_num,
+ const EObjectUpdateType update_type,
+ LLDataPacker *dp);
+ virtual BOOL idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time);
+ virtual BOOL updateLOD();
+ BOOL updateJointLODs();
+ void updateLODRiggedAttachments( void );
+ virtual BOOL isActive() const; // Whether this object needs to do an idleUpdate.
+ virtual void updateTextures();
+ virtual S32 setTETexture(const U8 te, const LLUUID& uuid); // If setting a baked texture, need to request it from a non-local sim.
+ virtual void onShift(const LLVector4a& shift_vector);
+ virtual U32 getPartitionType() const;
+ virtual const LLVector3 getRenderPosition() const;
+ virtual void updateDrawable(BOOL force_damped);
+ virtual LLDrawable* createDrawable(LLPipeline *pipeline);
+ virtual BOOL updateGeometry(LLDrawable *drawable);
+ virtual void setPixelAreaAndAngle(LLAgent &agent);
+ virtual void updateRegion(LLViewerRegion *regionp);
+ virtual void updateSpatialExtents(LLVector4a& newMin, LLVector4a &newMax);
+ virtual void getSpatialExtents(LLVector4a& newMin, LLVector4a& newMax);
+ virtual BOOL lineSegmentIntersect(const LLVector3& start, const LLVector3& end,
+ S32 face = -1, // which face to check, -1 = ALL_SIDES
+ BOOL pick_transparent = FALSE,
+ S32* face_hit = NULL, // which face was hit
+ LLVector3* intersection = NULL, // return the intersection point
+ LLVector2* tex_coord = NULL, // return the texture coordinates of the intersection point
+ LLVector3* normal = NULL, // return the surface normal at the intersection point
+ LLVector3* bi_normal = NULL); // return the surface bi-normal at the intersection point
+
+ //--------------------------------------------------------------------
+ // LLCharacter interface and related
+ //--------------------------------------------------------------------
+public:
+ virtual LLVector3 getCharacterPosition();
+ virtual LLQuaternion getCharacterRotation();
+ virtual LLVector3 getCharacterVelocity();
+ virtual LLVector3 getCharacterAngularVelocity();
+ virtual LLJoint* getCharacterJoint(U32 num);
+ virtual BOOL allocateCharacterJoints(U32 num);
+
+ virtual LLUUID remapMotionID(const LLUUID& id);
+ virtual BOOL startMotion(const LLUUID& id, F32 time_offset = 0.f);
+ virtual BOOL stopMotion(const LLUUID& id, BOOL stop_immediate = FALSE);
+ virtual void stopMotionFromSource(const LLUUID& source_id);
+ virtual void requestStopMotion(LLMotion* motion);
+ LLMotion* findMotion(const LLUUID& id) const;
+ void startDefaultMotions();
+ void dumpAnimationState();
+
+ virtual LLJoint* getJoint(const std::string &name);
+ virtual LLJoint* getRootJoint() { return &mRoot; }
+
+ void resetJointPositions( void );
+ void resetJointPositionsToDefault( void );
+ void resetSpecificJointPosition( const std::string& name );
+
+ virtual const char* getAnimationPrefix() { return "avatar"; }
+ virtual const LLUUID& getID();
+ virtual LLVector3 getVolumePos(S32 joint_index, LLVector3& volume_offset);
+ virtual LLJoint* findCollisionVolume(U32 volume_id);
+ virtual S32 getCollisionVolumeID(std::string &name);
+ virtual void addDebugText(const std::string& text);
+ virtual F32 getTimeDilation();
+ virtual void getGround(const LLVector3 &inPos, LLVector3 &outPos, LLVector3 &outNorm);
+ virtual F32 getPixelArea() const;
+ virtual LLPolyMesh* getHeadMesh();
+ virtual LLPolyMesh* getUpperBodyMesh();
+ virtual LLVector3d getPosGlobalFromAgent(const LLVector3 &position);
+ virtual LLVector3 getPosAgentFromGlobal(const LLVector3d &position);
+ virtual void updateVisualParams();
+
+
+/** Inherited
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** STATE
+ **/
+
+public:
+ virtual bool isSelf() const { return false; } // True if this avatar is for this viewer's agent
+ bool isBuilt() const { return mIsBuilt; }
+
+private: //aligned members
+ LLVector4a mImpostorExtents[2];
+
+private:
+ BOOL mSupportsAlphaLayers; // For backwards compatibility, TRUE for 1.23+ clients
+
+ //--------------------------------------------------------------------
+ // Updates
+ //--------------------------------------------------------------------
+public:
+ virtual BOOL updateCharacter(LLAgent &agent);
+ void idleUpdateVoiceVisualizer(bool voice_enabled);
+ void idleUpdateMisc(bool detailed_update);
+ virtual void idleUpdateAppearanceAnimation();
+ void idleUpdateLipSync(bool voice_enabled);
+ void idleUpdateLoadingEffect();
+ void idleUpdateWindEffect();
+ void idleUpdateNameTag(const LLVector3& root_pos_last);
+ void idleUpdateNameTagText(BOOL new_name);
+ LLVector3 idleUpdateNameTagPosition(const LLVector3& root_pos_last);
+ void idleUpdateNameTagAlpha(BOOL new_name, F32 alpha);
+ LLColor4 getNameTagColor(bool is_friend);
+ void clearNameTag();
+ static void invalidateNameTag(const LLUUID& agent_id);
+ // force all name tags to rebuild, useful when display names turned on/off
+ static void invalidateNameTags();
+ void addNameTagLine(const std::string& line, const LLColor4& color, S32 style, const LLFontGL* font);
+ void idleUpdateRenderCost();
+ void idleUpdateBelowWater();
+
+ //--------------------------------------------------------------------
+ // Static preferences (controlled by user settings/menus)
+ //--------------------------------------------------------------------
+public:
+ static S32 sRenderName;
+ static BOOL sRenderGroupTitles;
+ static U32 sMaxVisible; //(affected by control "RenderAvatarMaxVisible")
+ static F32 sRenderDistance; //distance at which avatars will render.
+ static BOOL sShowAnimationDebug; // show animation debug info
+ static BOOL sUseImpostors; //use impostors for far away avatars
+ static BOOL sShowFootPlane; // show foot collision plane reported by server
+ static BOOL sShowCollisionVolumes; // show skeletal collision volumes
+ static BOOL sVisibleInFirstPerson;
+ static S32 sNumLODChangesThisFrame;
+ static S32 sNumVisibleChatBubbles;
+ static BOOL sDebugInvisible;
+ static BOOL sShowAttachmentPoints;
+ static F32 sLODFactor; // user-settable LOD factor
+ static BOOL sJointDebug; // output total number of joints being touched for each avatar
+ static BOOL sDebugAvatarRotation;
+
+ //--------------------------------------------------------------------
+ // Region state
+ //--------------------------------------------------------------------
+public:
+ LLHost getObjectHost() const;
+
+ //--------------------------------------------------------------------
+ // Loading state
+ //--------------------------------------------------------------------
+public:
+ BOOL isFullyLoaded() const;
+ bool visualParamWeightsAreDefault();
+protected:
+ virtual BOOL getIsCloud();
+ BOOL updateIsFullyLoaded();
+ BOOL processFullyLoadedChange(bool loading);
+ void updateRuthTimer(bool loading);
+ F32 calcMorphAmount();
+private:
+ BOOL mFullyLoaded;
+ BOOL mPreviousFullyLoaded;
+ BOOL mFullyLoadedInitialized;
+ S32 mFullyLoadedFrameCounter;
+ LLFrameTimer mFullyLoadedTimer;
+ LLFrameTimer mRuthTimer;
+protected:
+ LLFrameTimer mInvisibleTimer;
+
+/** State
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** SKELETON
+ **/
+
+public:
+ void updateHeadOffset();
+ F32 getPelvisToFoot() const { return mPelvisToFoot; }
+ void setPelvisOffset( bool hasOffset, const LLVector3& translation, F32 offset ) ;
+ bool hasPelvisOffset( void ) { return mHasPelvisOffset; }
+ void postPelvisSetRecalc( void );
+
+ bool mHasPelvisOffset;
+ LLVector3 mPelvisOffset;
+ F32 mLastPelvisToFoot;
+ F32 mPelvisFixup;
+
+ LLVector3 mHeadOffset; // current head position
+ LLViewerJoint mRoot;
+protected:
+ static BOOL parseSkeletonFile(const std::string& filename);
+ void buildCharacter();
+ virtual BOOL loadAvatar();
+
+ BOOL setupBone(const LLVOAvatarBoneInfo* info, LLViewerJoint* parent, S32 &current_volume_num, S32 &current_joint_num);
+ BOOL buildSkeleton(const LLVOAvatarSkeletonInfo *info);
+private:
+ BOOL mIsBuilt; // state of deferred character building
+ S32 mNumJoints;
+ LLViewerJoint* mSkeleton;
+
+ //--------------------------------------------------------------------
+ // Pelvis height adjustment members.
+ //--------------------------------------------------------------------
+public:
+ LLVector3 mBodySize;
+ S32 mLastSkeletonSerialNum;
+private:
+ F32 mPelvisToFoot;
+
+ //--------------------------------------------------------------------
+ // Cached pointers to well known joints
+ //--------------------------------------------------------------------
+public:
+ LLViewerJoint* mPelvisp;
+ LLViewerJoint* mTorsop;
+ LLViewerJoint* mChestp;
+ LLViewerJoint* mNeckp;
+ LLViewerJoint* mHeadp;
+ LLViewerJoint* mSkullp;
+ LLViewerJoint* mEyeLeftp;
+ LLViewerJoint* mEyeRightp;
+ LLViewerJoint* mHipLeftp;
+ LLViewerJoint* mHipRightp;
+ LLViewerJoint* mKneeLeftp;
+ LLViewerJoint* mKneeRightp;
+ LLViewerJoint* mAnkleLeftp;
+ LLViewerJoint* mAnkleRightp;
+ LLViewerJoint* mFootLeftp;
+ LLViewerJoint* mFootRightp;
+ LLViewerJoint* mWristLeftp;
+ LLViewerJoint* mWristRightp;
+
+ //--------------------------------------------------------------------
+ // XML parse tree
+ //--------------------------------------------------------------------
+private:
+ static LLXmlTree sXMLTree; // avatar config file
+ static LLXmlTree sSkeletonXMLTree; // avatar skeleton file
+
+/** Skeleton
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** RENDERING
+ **/
+
+public:
+ U32 renderImpostor(LLColor4U color = LLColor4U(255,255,255,255), S32 diffuse_channel = 0);
+ U32 renderRigid();
+ U32 renderSkinned(EAvatarRenderPass pass);
+ F32 getLastSkinTime() { return mLastSkinTime; }
+ U32 renderSkinnedAttachments();
+ U32 renderTransparent(BOOL first_pass);
+ void renderCollisionVolumes();
+ static void deleteCachedImages(bool clearAll=true);
+ static void destroyGL();
+ static void restoreGL();
+ BOOL mIsDummy; // for special views
+ S32 mSpecialRenderMode; // special lighting
+private:
+ bool shouldAlphaMask();
+
+ BOOL mNeedsSkin; // avatar has been animated and verts have not been updated
+ F32 mLastSkinTime; //value of gFrameTimeSeconds at last skin update
+
+ S32 mUpdatePeriod;
+ S32 mNumInitFaces; //number of faces generated when creating the avatar drawable, does not inculde splitted faces due to long vertex buffer.
+
+ //--------------------------------------------------------------------
+ // Morph masks
+ //--------------------------------------------------------------------
+public:
+ BOOL morphMaskNeedsUpdate(LLVOAvatarDefines::EBakedTextureIndex index = LLVOAvatarDefines::BAKED_NUM_INDICES);
+ void addMaskedMorph(LLVOAvatarDefines::EBakedTextureIndex index, LLPolyMorphTarget* morph_target, BOOL invert, std::string layer);
+ void applyMorphMask(U8* tex_data, S32 width, S32 height, S32 num_components, LLVOAvatarDefines::EBakedTextureIndex index = LLVOAvatarDefines::BAKED_NUM_INDICES);
+
+ //--------------------------------------------------------------------
+ // Visibility
+ //--------------------------------------------------------------------
+protected:
+ void updateVisibility();
+private:
+ U32 mVisibilityRank;
+ BOOL mVisible;
+
+ //--------------------------------------------------------------------
+ // Shadowing
+ //--------------------------------------------------------------------
+public:
+ void updateShadowFaces();
+ LLDrawable* mShadow;
+private:
+ LLFace* mShadow0Facep;
+ LLFace* mShadow1Facep;
+ LLPointer<LLViewerTexture> mShadowImagep;
+
+ //--------------------------------------------------------------------
+ // Impostors
+ //--------------------------------------------------------------------
+public:
+ BOOL isImpostor() const;
+ BOOL needsImpostorUpdate() const;
+ const LLVector3& getImpostorOffset() const;
+ const LLVector2& getImpostorDim() const;
+ void getImpostorValues(LLVector4a* extents, LLVector3& angle, F32& distance) const;
+ void cacheImpostorValues();
+ void setImpostorDim(const LLVector2& dim);
+ static void resetImpostors();
+ static void updateImpostors();
+ LLRenderTarget mImpostor;
+ BOOL mNeedsImpostorUpdate;
+private:
+ LLVector3 mImpostorOffset;
+ LLVector2 mImpostorDim;
+ BOOL mNeedsAnimUpdate;
+ LLVector3 mImpostorAngle;
+ F32 mImpostorDistance;
+ F32 mImpostorPixelArea;
+ LLVector3 mLastAnimExtents[2];
+
+ //--------------------------------------------------------------------
+ // Wind rippling in clothes
+ //--------------------------------------------------------------------
+public:
+ LLVector4 mWindVec;
+ F32 mRipplePhase;
+ BOOL mBelowWater;
+private:
+ F32 mWindFreq;
+ LLFrameTimer mRippleTimer;
+ F32 mRippleTimeLast;
+ LLVector3 mRippleAccel;
+ LLVector3 mLastVel;
+
+ //--------------------------------------------------------------------
+ // Culling
+ //--------------------------------------------------------------------
+public:
+ static void cullAvatarsByPixelArea();
+ BOOL isCulled() const { return mCulled; }
+private:
+ BOOL mCulled;
+
+ //--------------------------------------------------------------------
+ // Freeze counter
+ //--------------------------------------------------------------------
+public:
+ static void updateFreezeCounter(S32 counter = 0);
+private:
+ static S32 sFreezeCounter;
+
+ //--------------------------------------------------------------------
+ // Constants
+ //--------------------------------------------------------------------
+public:
+ virtual LLViewerTexture::EBoostLevel getAvatarBoostLevel() const { return LLViewerTexture::BOOST_AVATAR; }
+ virtual LLViewerTexture::EBoostLevel getAvatarBakedBoostLevel() const { return LLViewerTexture::BOOST_AVATAR_BAKED; }
+ virtual S32 getTexImageSize() const;
+ virtual S32 getTexImageArea() const { return getTexImageSize()*getTexImageSize(); }
+
+/** Rendering
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** TEXTURES
+ **/
+
+ //--------------------------------------------------------------------
+ // Loading status
+ //--------------------------------------------------------------------
+public:
+ virtual BOOL isTextureDefined(LLVOAvatarDefines::ETextureIndex type, U32 index = 0) const;
+ virtual BOOL isTextureVisible(LLVOAvatarDefines::ETextureIndex type, U32 index = 0) const;
+ virtual BOOL isTextureVisible(LLVOAvatarDefines::ETextureIndex type, LLWearable *wearable) const;
+
+protected:
+ BOOL isFullyBaked();
+ static BOOL areAllNearbyInstancesBaked(S32& grey_avatars);
+
+ //--------------------------------------------------------------------
+ // Baked textures
+ //--------------------------------------------------------------------
+public:
+ void releaseComponentTextures(); // ! BACKWARDS COMPATIBILITY !
+protected:
+ static void onBakedTextureMasksLoaded(BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata);
+ static void onInitialBakedTextureLoaded(BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata);
+ static void onBakedTextureLoaded(BOOL success, LLViewerFetchedTexture *src_vi, LLImageRaw* src, LLImageRaw* aux_src, S32 discard_level, BOOL final, void* userdata);
+ virtual void removeMissingBakedTextures();
+ void useBakedTexture(const LLUUID& id);
+
+ typedef std::deque<LLMaskedMorph *> morph_list_t;
+ struct BakedTextureData
+ {
+ LLUUID mLastTextureIndex;
+ LLTexLayerSet* mTexLayerSet; // Only exists for self
+ bool mIsLoaded;
+ bool mIsUsed;
+ LLVOAvatarDefines::ETextureIndex mTextureIndex;
+ U32 mMaskTexName;
+ // Stores pointers to the joint meshes that this baked texture deals with
+ std::vector< LLViewerJointMesh * > mMeshes; // std::vector<LLViewerJointMesh> mJoints[i]->mMeshParts
+ morph_list_t mMaskedMorphs;
+ };
+ typedef std::vector<BakedTextureData> bakedtexturedata_vec_t;
+ bakedtexturedata_vec_t mBakedTextureDatas;
+ LLLoadedCallbackEntry::source_callback_list_t mCallbackTextureList ;
+ BOOL mLoadedCallbacksPaused;
+ //--------------------------------------------------------------------
+ // Local Textures
+ //--------------------------------------------------------------------
+protected:
+ virtual void setLocalTexture(LLVOAvatarDefines::ETextureIndex type, LLViewerTexture* tex, BOOL baked_version_exits, U32 index = 0);
+ virtual void addLocalTextureStats(LLVOAvatarDefines::ETextureIndex type, LLViewerFetchedTexture* imagep, F32 texel_area_ratio, BOOL rendered, BOOL covered_by_baked, U32 index = 0);
+ // MULTI-WEARABLE: make self-only?
+ virtual void setBakedReady(LLVOAvatarDefines::ETextureIndex type, BOOL baked_version_exists, U32 index = 0);
+
+ //--------------------------------------------------------------------
+ // Texture accessors
+ //--------------------------------------------------------------------
+private:
+ virtual void setImage(const U8 te, LLViewerTexture *imagep, const U32 index);
+ virtual LLViewerTexture* getImage(const U8 te, const U32 index) const;
+
+ virtual const LLTextureEntry* getTexEntry(const U8 te_num) const;
+ virtual void setTexEntry(const U8 index, const LLTextureEntry &te);
+
+ void checkTextureLoading() ;
+ //--------------------------------------------------------------------
+ // Layers
+ //--------------------------------------------------------------------
+protected:
+ void deleteLayerSetCaches(bool clearAll = true);
+ void addBakedTextureStats(LLViewerFetchedTexture* imagep, F32 pixel_area, F32 texel_area_ratio, S32 boost_level);
+
+ //--------------------------------------------------------------------
+ // Composites
+ //--------------------------------------------------------------------
+public:
+ virtual void invalidateComposite(LLTexLayerSet* layerset, BOOL upload_result);
+ virtual void invalidateAll();
+ virtual void setCompositeUpdatesEnabled(bool b) {}
+ virtual void setCompositeUpdatesEnabled(U32 index, bool b) {}
+ virtual bool isCompositeUpdateEnabled(U32 index) { return false; }
+
+ //--------------------------------------------------------------------
+ // Static texture/mesh/baked dictionary
+ //--------------------------------------------------------------------
+public:
+ static BOOL isIndexLocalTexture(LLVOAvatarDefines::ETextureIndex i);
+ static BOOL isIndexBakedTexture(LLVOAvatarDefines::ETextureIndex i);
+private:
+ static const LLVOAvatarDefines::LLVOAvatarDictionary *getDictionary() { return sAvatarDictionary; }
+ static LLVOAvatarDefines::LLVOAvatarDictionary* sAvatarDictionary;
+ static LLVOAvatarSkeletonInfo* sAvatarSkeletonInfo;
+ static LLVOAvatarXmlInfo* sAvatarXmlInfo;
+
+ //--------------------------------------------------------------------
+ // Messaging
+ //--------------------------------------------------------------------
+public:
+ void onFirstTEMessageReceived();
+private:
+ BOOL mFirstTEMessageReceived;
+ BOOL mFirstAppearanceMessageReceived;
+
+/** Textures
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** MESHES
+ **/
+
+public:
+ void updateMeshTextures();
+ void updateSexDependentLayerSets(BOOL upload_bake);
+ void dirtyMesh(); // Dirty the avatar mesh
+ void updateMeshData();
+protected:
+ void releaseMeshData();
+ virtual void restoreMeshData();
+private:
+ void dirtyMesh(S32 priority); // Dirty the avatar mesh, with priority
+ S32 mDirtyMesh; // 0 -- not dirty, 1 -- morphed, 2 -- LOD
+ BOOL mMeshTexturesDirty;
+
+ typedef std::multimap<std::string, LLPolyMesh*> polymesh_map_t;
+ polymesh_map_t mMeshes;
+ std::vector<LLViewerJoint *> mMeshLOD;
+
+ //--------------------------------------------------------------------
+ // Destroy invisible mesh
+ //--------------------------------------------------------------------
+protected:
+ BOOL mMeshValid;
+ LLFrameTimer mMeshInvisibleTime;
+
+/** Meshes
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** APPEARANCE
+ **/
+
+public:
+ void processAvatarAppearance(LLMessageSystem* mesgsys);
+ void hideSkirt();
+ void startAppearanceAnimation();
+
+ //--------------------------------------------------------------------
+ // Appearance morphing
+ //--------------------------------------------------------------------
+public:
+ BOOL getIsAppearanceAnimating() const { return mAppearanceAnimating; }
+private:
+ BOOL mAppearanceAnimating;
+ LLFrameTimer mAppearanceMorphTimer;
+ F32 mLastAppearanceBlendTime;
+
+ //--------------------------------------------------------------------
+ // Clothing colors (convenience functions to access visual parameters)
+ //--------------------------------------------------------------------
+public:
+ void setClothesColor(LLVOAvatarDefines::ETextureIndex te, const LLColor4& new_color, BOOL upload_bake);
+ LLColor4 getClothesColor(LLVOAvatarDefines::ETextureIndex te);
+ static BOOL teToColorParams(LLVOAvatarDefines::ETextureIndex te, U32 *param_name);
+
+ //--------------------------------------------------------------------
+ // Global colors
+ //--------------------------------------------------------------------
+public:
+ LLColor4 getGlobalColor(const std::string& color_name ) const;
+ void onGlobalColorChanged(const LLTexGlobalColor* global_color, BOOL upload_bake);
+private:
+ LLTexGlobalColor* mTexSkinColor;
+ LLTexGlobalColor* mTexHairColor;
+ LLTexGlobalColor* mTexEyeColor;
+
+ //--------------------------------------------------------------------
+ // Visibility
+ //--------------------------------------------------------------------
+public:
+ BOOL isVisible() const;
+ void setVisibilityRank(U32 rank);
+ U32 getVisibilityRank() const { return mVisibilityRank; } // unused
+ static S32 sNumVisibleAvatars; // Number of instances of this class
+ static LLColor4 getDummyColor();
+/** Appearance
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** WEARABLES
+ **/
+
+public:
+ virtual BOOL isWearingWearableType(LLWearableType::EType type ) const;
+
+ //--------------------------------------------------------------------
+ // Attachments
+ //--------------------------------------------------------------------
+public:
+ void clampAttachmentPositions();
+ virtual const LLViewerJointAttachment* attachObject(LLViewerObject *viewer_object);
+ virtual BOOL detachObject(LLViewerObject *viewer_object);
+ void cleanupAttachedMesh( LLViewerObject* pVO );
+ static LLVOAvatar* findAvatarFromAttachment(LLViewerObject* obj);
+protected:
+ LLViewerJointAttachment* getTargetAttachmentPoint(LLViewerObject* viewer_object);
+ void lazyAttach();
+ void rebuildRiggedAttachments( void );
+
+ //--------------------------------------------------------------------
+ // Map of attachment points, by ID
+ //--------------------------------------------------------------------
+public:
+ S32 getAttachmentCount(); // Warning: order(N) not order(1) // currently used only by -self
+ typedef std::map<S32, LLViewerJointAttachment*> attachment_map_t;
+ attachment_map_t mAttachmentPoints;
+ std::vector<LLPointer<LLViewerObject> > mPendingAttachment;
+
+ //--------------------------------------------------------------------
+ // HUD functions
+ //--------------------------------------------------------------------
+public:
+ BOOL hasHUDAttachment() const;
+ LLBBox getHUDBBox() const;
+ void rebuildHUD();
+ void resetHUDAttachments();
+ BOOL canAttachMoreObjects() const;
+ BOOL canAttachMoreObjects(U32 n) const;
+protected:
+ U32 getNumAttachments() const; // O(N), not O(1)
+
+/** Wearables
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** ACTIONS
+ **/
+
+ //--------------------------------------------------------------------
+ // Animations
+ //--------------------------------------------------------------------
+public:
+ BOOL isAnyAnimationSignaled(const LLUUID *anim_array, const S32 num_anims) const;
+ void processAnimationStateChanges();
+protected:
+ BOOL processSingleAnimationStateChange(const LLUUID &anim_id, BOOL start);
+ void resetAnimations();
+private:
+ LLTimer mAnimTimer;
+ F32 mTimeLast;
+
+ //--------------------------------------------------------------------
+ // Animation state data
+ //--------------------------------------------------------------------
+public:
+ typedef std::map<LLUUID, S32>::iterator AnimIterator;
+ std::map<LLUUID, S32> mSignaledAnimations; // requested state of Animation name/value
+ std::map<LLUUID, S32> mPlayingAnimations; // current state of Animation name/value
+
+ typedef std::multimap<LLUUID, LLUUID> AnimationSourceMap;
+ typedef AnimationSourceMap::iterator AnimSourceIterator;
+ AnimationSourceMap mAnimationSources; // object ids that triggered anim ids
+
+ //--------------------------------------------------------------------
+ // Chat
+ //--------------------------------------------------------------------
+public:
+ void addChat(const LLChat& chat);
+ void clearChat();
+ void startTyping() { mTyping = TRUE; mTypingTimer.reset(); }
+ void stopTyping() { mTyping = FALSE; }
+private:
+ BOOL mVisibleChat;
+
+ //--------------------------------------------------------------------
+ // Lip synch morphs
+ //--------------------------------------------------------------------
+private:
+ bool mLipSyncActive; // we're morphing for lip sync
+ LLVisualParam* mOohMorph; // cached pointers morphs for lip sync
+ LLVisualParam* mAahMorph; // cached pointers morphs for lip sync
+
+ //--------------------------------------------------------------------
+ // Flight
+ //--------------------------------------------------------------------
+public:
+ BOOL mInAir;
+ LLFrameTimer mTimeInAir;
+
+/** Actions
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** PHYSICS
+ **/
+
+private:
+ F32 mSpeedAccum; // measures speed (for diagnostics mostly).
+ BOOL mTurning; // controls hysteresis on avatar rotation
+ F32 mSpeed; // misc. animation repeated state
+
+ //--------------------------------------------------------------------
+ // Collision volumes
+ //--------------------------------------------------------------------
+public:
+ S32 mNumCollisionVolumes;
+ LLViewerJointCollisionVolume* mCollisionVolumes;
+protected:
+ BOOL allocateCollisionVolumes(U32 num);
+
+ //--------------------------------------------------------------------
+ // Dimensions
+ //--------------------------------------------------------------------
+public:
+ void resolveHeightGlobal(const LLVector3d &inPos, LLVector3d &outPos, LLVector3 &outNorm);
+ bool distanceToGround( const LLVector3d &startPoint, LLVector3d &collisionPoint, F32 distToIntersectionAlongRay );
+ void resolveHeightAgent(const LLVector3 &inPos, LLVector3 &outPos, LLVector3 &outNorm);
+ void resolveRayCollisionAgent(const LLVector3d start_pt, const LLVector3d end_pt, LLVector3d &out_pos, LLVector3 &out_norm);
+ void slamPosition(); // Slam position to transmitted position (for teleport);
+protected:
+ void computeBodySize();
+
+ //--------------------------------------------------------------------
+ // Material being stepped on
+ //--------------------------------------------------------------------
+private:
+ BOOL mStepOnLand;
+ U8 mStepMaterial;
+ LLVector3 mStepObjectVelocity;
+
+/** Physics
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** HIERARCHY
+ **/
+
+public:
+ virtual BOOL setParent(LLViewerObject* parent);
+ virtual void addChild(LLViewerObject *childp);
+ virtual void removeChild(LLViewerObject *childp);
+
+ //--------------------------------------------------------------------
+ // Sitting
+ //--------------------------------------------------------------------
+public:
+ void sitDown(BOOL bSitting);
+ BOOL isSitting(){return mIsSitting;}
+ void sitOnObject(LLViewerObject *sit_object);
+ void getOffObject();
+private:
+ // set this property only with LLVOAvatar::sitDown method
+ BOOL mIsSitting;
+
+/** Hierarchy
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** NAME
+ **/
+
+public:
+ std::string getFullname() const; // Returns "FirstName LastName"
+protected:
+ static void getAnimLabels(LLDynamicArray<std::string>* labels);
+ static void getAnimNames(LLDynamicArray<std::string>* names);
+private:
+ std::string mNameString; // UTF-8 title + name + status
+ std::string mTitle;
+ bool mNameAway;
+ bool mNameBusy;
+ bool mNameMute;
+ bool mNameAppearance;
+ bool mNameFriend;
+ bool mNameCloud;
+ F32 mNameAlpha;
+ BOOL mRenderGroupTitles;
+
+ //--------------------------------------------------------------------
+ // Display the name (then optionally fade it out)
+ //--------------------------------------------------------------------
+public:
+ LLFrameTimer mChatTimer;
+ LLPointer<LLHUDNameTag> mNameText;
+private:
+ LLFrameTimer mTimeVisible;
+ std::deque<LLChat> mChats;
+ BOOL mTyping;
+ LLFrameTimer mTypingTimer;
+
+/** Name
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** SOUNDS
+ **/
+
+ //--------------------------------------------------------------------
+ // Voice visualizer
+ //--------------------------------------------------------------------
+public:
+ // Responsible for detecting the user's voice signal (and when the
+ // user speaks, it puts a voice symbol over the avatar's head) and gesticulations
+ LLPointer<LLVoiceVisualizer> mVoiceVisualizer;
+ int mCurrentGesticulationLevel;
+
+ //--------------------------------------------------------------------
+ // Step sound
+ //--------------------------------------------------------------------
+protected:
+ const LLUUID& getStepSound() const;
+private:
+ // Global table of sound ids per material, and the ground
+ const static LLUUID sStepSounds[LL_MCODE_END];
+ const static LLUUID sStepSoundOnLand;
+
+ //--------------------------------------------------------------------
+ // Foot step state (for generating sounds)
+ //--------------------------------------------------------------------
+public:
+ void setFootPlane(const LLVector4 &plane) { mFootPlane = plane; }
+ LLVector4 mFootPlane;
+private:
+ BOOL mWasOnGroundLeft;
+ BOOL mWasOnGroundRight;
+
+/** Sounds
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** DIAGNOSTICS
+ **/
+
+ //--------------------------------------------------------------------
+ // General
+ //--------------------------------------------------------------------
+public:
+ static void dumpArchetypeXML(void*);
+ static void dumpBakedStatus();
+ const std::string getBakedStatusForPrintout() const;
+ void dumpAvatarTEs(const std::string& context) const;
+
+ static F32 sUnbakedTime; // Total seconds with >=1 unbaked avatars
+ static F32 sUnbakedUpdateTime; // Last time stats were updated (to prevent multiple updates per frame)
+ static F32 sGreyTime; // Total seconds with >=1 grey avatars
+ static F32 sGreyUpdateTime; // Last time stats were updated (to prevent multiple updates per frame)
+protected:
+ S32 getUnbakedPixelAreaRank();
+ BOOL mHasGrey;
+private:
+ F32 mMinPixelArea;
+ F32 mMaxPixelArea;
+ F32 mAdjustedPixelArea;
+ std::string mDebugText;
+
+
+ //--------------------------------------------------------------------
+ // Avatar Rez Metrics
+ //--------------------------------------------------------------------
+public:
+ F32 debugGetExistenceTimeElapsedF32() const { return mDebugExistenceTimer.getElapsedTimeF32(); }
+protected:
+ LLFrameTimer mRuthDebugTimer; // For tracking how long it takes for av to rez
+ LLFrameTimer mDebugExistenceTimer; // Debugging for how long the avatar has been in memory.
+
+/** Diagnostics
+ ** **
+ *******************************************************************************/
+
+/********************************************************************************
+ ** **
+ ** SUPPORT CLASSES
+ **/
+
+protected: // Shared with LLVOAvatarSelf
+
+ struct LLVOAvatarXmlInfo
+ {
+ LLVOAvatarXmlInfo();
+ ~LLVOAvatarXmlInfo();
+
+ BOOL parseXmlSkeletonNode(LLXmlTreeNode* root);
+ BOOL parseXmlMeshNodes(LLXmlTreeNode* root);
+ BOOL parseXmlColorNodes(LLXmlTreeNode* root);
+ BOOL parseXmlLayerNodes(LLXmlTreeNode* root);
+ BOOL parseXmlDriverNodes(LLXmlTreeNode* root);
+ BOOL parseXmlMorphNodes(LLXmlTreeNode* root);
+
+ struct LLVOAvatarMeshInfo
+ {
+ typedef std::pair<LLPolyMorphTargetInfo*,BOOL> morph_info_pair_t;
+ typedef std::vector<morph_info_pair_t> morph_info_list_t;
+
+ LLVOAvatarMeshInfo() : mLOD(0), mMinPixelArea(.1f) {}
+ ~LLVOAvatarMeshInfo()
+ {
+ morph_info_list_t::iterator iter;
+ for (iter = mPolyMorphTargetInfoList.begin(); iter != mPolyMorphTargetInfoList.end(); iter++)
+ {
+ delete iter->first;
+ }
+ mPolyMorphTargetInfoList.clear();
+ }
+
+ std::string mType;
+ S32 mLOD;
+ std::string mMeshFileName;
+ std::string mReferenceMeshName;
+ F32 mMinPixelArea;
+ morph_info_list_t mPolyMorphTargetInfoList;
+ };
+ typedef std::vector<LLVOAvatarMeshInfo*> mesh_info_list_t;
+ mesh_info_list_t mMeshInfoList;
+
+ typedef std::vector<LLPolySkeletalDistortionInfo*> skeletal_distortion_info_list_t;
+ skeletal_distortion_info_list_t mSkeletalDistortionInfoList;
+
+ struct LLVOAvatarAttachmentInfo
+ {
+ LLVOAvatarAttachmentInfo()
+ : mGroup(-1), mAttachmentID(-1), mPieMenuSlice(-1), mVisibleFirstPerson(FALSE),
+ mIsHUDAttachment(FALSE), mHasPosition(FALSE), mHasRotation(FALSE) {}
+ std::string mName;
+ std::string mJointName;
+ LLVector3 mPosition;
+ LLVector3 mRotationEuler;
+ S32 mGroup;
+ S32 mAttachmentID;
+ S32 mPieMenuSlice;
+ BOOL mVisibleFirstPerson;
+ BOOL mIsHUDAttachment;
+ BOOL mHasPosition;
+ BOOL mHasRotation;
+ };
+ typedef std::vector<LLVOAvatarAttachmentInfo*> attachment_info_list_t;
+ attachment_info_list_t mAttachmentInfoList;
+
+ LLTexGlobalColorInfo *mTexSkinColorInfo;
+ LLTexGlobalColorInfo *mTexHairColorInfo;
+ LLTexGlobalColorInfo *mTexEyeColorInfo;
+
+ typedef std::vector<LLTexLayerSetInfo*> layer_info_list_t;
+ layer_info_list_t mLayerInfoList;
+
+ typedef std::vector<LLDriverParamInfo*> driver_info_list_t;
+ driver_info_list_t mDriverInfoList;
+
+ struct LLVOAvatarMorphInfo
+ {
+ LLVOAvatarMorphInfo()
+ : mInvert(FALSE) {}
+ std::string mName;
+ std::string mRegion;
+ std::string mLayer;
+ BOOL mInvert;
+ };
+
+ typedef std::vector<LLVOAvatarMorphInfo*> morph_info_list_t;
+ morph_info_list_t mMorphMaskInfoList;
+ };
+
+ struct LLMaskedMorph
+ {
+ LLMaskedMorph(LLPolyMorphTarget *morph_target, BOOL invert, std::string layer) :
+ mMorphTarget(morph_target),
+ mInvert(invert),
+ mLayer(layer)
+ {
+ morph_target->addPendingMorphMask();
+ }
+
+ LLPolyMorphTarget *mMorphTarget;
+ BOOL mInvert;
+ std::string mLayer;
+ };
+
+/** Support classes
+ ** **
+ *******************************************************************************/
+
+}; // LLVOAvatar
+extern const F32 SELF_ADDITIONAL_PRI;
+extern const S32 MAX_TEXTURE_VIRTURE_SIZE_RESET_INTERVAL;
+
+#endif // LL_VO_AVATAR_H
diff --git a/indra/newview/llvoavatarself.cpp b/indra/newview/llvoavatarself.cpp
index 5f9e343907..75966a0f96 100644
--- a/indra/newview/llvoavatarself.cpp
+++ b/indra/newview/llvoavatarself.cpp
@@ -56,6 +56,8 @@
#include "llviewerstats.h"
#include "llviewerregion.h"
#include "llappearancemgr.h"
+#include "llmeshrepository.h"
+#include "llvovolume.h"
#if LL_MSVC
// disable boost::lexical_cast warning
@@ -623,6 +625,7 @@ BOOL LLVOAvatarSelf::updateCharacter(LLAgent &agent)
mScreenp->updateWorldMatrixChildren();
resetHUDAttachments();
}
+
return LLVOAvatar::updateCharacter(agent);
}
@@ -648,7 +651,11 @@ LLJoint *LLVOAvatarSelf::getJoint(const std::string &name)
}
return LLVOAvatar::getJoint(name);
}
-
+//virtual
+void LLVOAvatarSelf::resetJointPositions( void )
+{
+ return LLVOAvatar::resetJointPositions();
+}
// virtual
BOOL LLVOAvatarSelf::setVisualParamWeight(LLVisualParam *which_param, F32 weight, BOOL upload_bake )
{
@@ -1132,6 +1139,7 @@ const LLViewerJointAttachment *LLVOAvatarSelf::attachObject(LLViewerObject *view
LLAppearanceMgr::instance().registerAttachment(attachment_id);
// Clear any pending requests once the attachment arrives.
removeAttachmentRequest(attachment_id);
+ updateLODRiggedAttachments();
}
return attachment;
@@ -1141,8 +1149,10 @@ const LLViewerJointAttachment *LLVOAvatarSelf::attachObject(LLViewerObject *view
BOOL LLVOAvatarSelf::detachObject(LLViewerObject *viewer_object)
{
const LLUUID attachment_id = viewer_object->getAttachmentItemID();
- if (LLVOAvatar::detachObject(viewer_object))
+ if ( LLVOAvatar::detachObject(viewer_object) )
{
+ LLVOAvatar::cleanupAttachedMesh( viewer_object );
+
// the simulator should automatically handle permission revocation
stopMotionFromSource(attachment_id);
diff --git a/indra/newview/llvoavatarself.h b/indra/newview/llvoavatarself.h
index d13cf5ba38..51f06dee5f 100644
--- a/indra/newview/llvoavatarself.h
+++ b/indra/newview/llvoavatarself.h
@@ -83,7 +83,9 @@ public:
/*virtual*/ void stopMotionFromSource(const LLUUID& source_id);
/*virtual*/ void requestStopMotion(LLMotion* motion);
/*virtual*/ LLJoint* getJoint(const std::string &name);
-
+
+ void resetJointPositions( void );
+
/*virtual*/ BOOL setVisualParamWeight(LLVisualParam *which_param, F32 weight, BOOL upload_bake = FALSE );
/*virtual*/ BOOL setVisualParamWeight(const char* param_name, F32 weight, BOOL upload_bake = FALSE );
/*virtual*/ BOOL setVisualParamWeight(S32 index, F32 weight, BOOL upload_bake = FALSE );
diff --git a/indra/newview/llvocache.cpp b/indra/newview/llvocache.cpp
index b888a263d0..1f9be20c75 100644
--- a/indra/newview/llvocache.cpp
+++ b/indra/newview/llvocache.cpp
@@ -1,756 +1,756 @@
-/**
- * @file llvocache.cpp
- * @brief Cache of objects on the viewer.
- *
- * $LicenseInfo:firstyear=2003&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-#include "llviewerprecompiledheaders.h"
-#include "llvocache.h"
-#include "llerror.h"
-#include "llregionhandle.h"
-#include "llviewercontrol.h"
-
-BOOL check_read(LLAPRFile* apr_file, void* src, S32 n_bytes)
-{
- return apr_file->read(src, n_bytes) == n_bytes ;
-}
-
-BOOL check_write(LLAPRFile* apr_file, void* src, S32 n_bytes)
-{
- return apr_file->write(src, n_bytes) == n_bytes ;
-}
-
-
-//---------------------------------------------------------------------------
-// LLVOCacheEntry
-//---------------------------------------------------------------------------
-
-LLVOCacheEntry::LLVOCacheEntry(U32 local_id, U32 crc, LLDataPackerBinaryBuffer &dp)
- :
- mLocalID(local_id),
- mCRC(crc),
- mHitCount(0),
- mDupeCount(0),
- mCRCChangeCount(0)
-{
- mBuffer = new U8[dp.getBufferSize()];
- mDP.assignBuffer(mBuffer, dp.getBufferSize());
- mDP = dp;
-}
-
-LLVOCacheEntry::LLVOCacheEntry()
- :
- mLocalID(0),
- mCRC(0),
- mHitCount(0),
- mDupeCount(0),
- mCRCChangeCount(0),
- mBuffer(NULL)
-{
- mDP.assignBuffer(mBuffer, 0);
-}
-
-LLVOCacheEntry::LLVOCacheEntry(LLAPRFile* apr_file)
- : mBuffer(NULL)
-{
- S32 size = -1;
- BOOL success;
-
- success = check_read(apr_file, &mLocalID, sizeof(U32));
- if(success)
- {
- success = check_read(apr_file, &mCRC, sizeof(U32));
- }
- if(success)
- {
- success = check_read(apr_file, &mHitCount, sizeof(S32));
- }
- if(success)
- {
- success = check_read(apr_file, &mDupeCount, sizeof(S32));
- }
- if(success)
- {
- success = check_read(apr_file, &mCRCChangeCount, sizeof(S32));
- }
- if(success)
- {
- success = check_read(apr_file, &size, sizeof(S32));
-
- // Corruption in the cache entries
- if ((size > 10000) || (size < 1))
- {
- // We've got a bogus size, skip reading it.
- // We won't bother seeking, because the rest of this file
- // is likely bogus, and will be tossed anyway.
- llwarns << "Bogus cache entry, size " << size << ", aborting!" << llendl;
- success = FALSE;
- }
- }
- if(success && size > 0)
- {
- mBuffer = new U8[size];
- success = check_read(apr_file, mBuffer, size);
-
- if(success)
- {
- mDP.assignBuffer(mBuffer, size);
- }
- else
- {
- delete[] mBuffer ;
- mBuffer = NULL ;
- }
- }
-
- if(!success)
- {
- mLocalID = 0;
- mCRC = 0;
- mHitCount = 0;
- mDupeCount = 0;
- mCRCChangeCount = 0;
- mBuffer = NULL;
- }
-}
-
-LLVOCacheEntry::~LLVOCacheEntry()
-{
- if(mBuffer)
- {
- delete[] mBuffer;
- }
-}
-
-
-// New CRC means the object has changed.
-void LLVOCacheEntry::assignCRC(U32 crc, LLDataPackerBinaryBuffer &dp)
-{
- if ( (mCRC != crc)
- ||(mDP.getBufferSize() == 0))
- {
- mCRC = crc;
- mHitCount = 0;
- mCRCChangeCount++;
-
- mDP.freeBuffer();
- mBuffer = new U8[dp.getBufferSize()];
- mDP.assignBuffer(mBuffer, dp.getBufferSize());
- mDP = dp;
- }
-}
-
-LLDataPackerBinaryBuffer *LLVOCacheEntry::getDP(U32 crc)
-{
- if ( (mCRC != crc)
- ||(mDP.getBufferSize() == 0))
- {
- //llinfos << "Not getting cache entry, invalid!" << llendl;
- return NULL;
- }
- mHitCount++;
- return &mDP;
-}
-
-
-void LLVOCacheEntry::recordHit()
-{
- mHitCount++;
-}
-
-
-void LLVOCacheEntry::dump() const
-{
- llinfos << "local " << mLocalID
- << " crc " << mCRC
- << " hits " << mHitCount
- << " dupes " << mDupeCount
- << " change " << mCRCChangeCount
- << llendl;
-}
-
-BOOL LLVOCacheEntry::writeToFile(LLAPRFile* apr_file) const
-{
- BOOL success;
- success = check_write(apr_file, (void*)&mLocalID, sizeof(U32));
- if(success)
- {
- success = check_write(apr_file, (void*)&mCRC, sizeof(U32));
- }
- if(success)
- {
- success = check_write(apr_file, (void*)&mHitCount, sizeof(S32));
- }
- if(success)
- {
- success = check_write(apr_file, (void*)&mDupeCount, sizeof(S32));
- }
- if(success)
- {
- success = check_write(apr_file, (void*)&mCRCChangeCount, sizeof(S32));
- }
- if(success)
- {
- S32 size = mDP.getBufferSize();
- success = check_write(apr_file, (void*)&size, sizeof(S32));
-
- if(success)
- {
- success = check_write(apr_file, (void*)mBuffer, size);
- }
- }
-
- return success ;
-}
-
-//-------------------------------------------------------------------
-//LLVOCache
-//-------------------------------------------------------------------
-// Format string used to construct filename for the object cache
-static const char OBJECT_CACHE_FILENAME[] = "objects_%d_%d.slc";
-
-const U32 MAX_NUM_OBJECT_ENTRIES = 128 ;
-const U32 MIN_ENTRIES_TO_PURGE = 16 ;
-const U32 INVALID_TIME = 0 ;
-const char* object_cache_dirname = "objectcache";
-const char* header_filename = "object.cache";
-
-LLVOCache* LLVOCache::sInstance = NULL;
-
-//static
-LLVOCache* LLVOCache::getInstance()
-{
- if(!sInstance)
- {
- sInstance = new LLVOCache() ;
- }
- return sInstance ;
-}
-
-//static
-BOOL LLVOCache::hasInstance()
-{
- return sInstance != NULL ;
-}
-
-//static
-void LLVOCache::destroyClass()
-{
- if(sInstance)
- {
- delete sInstance ;
- sInstance = NULL ;
- }
-}
-
-LLVOCache::LLVOCache():
- mInitialized(FALSE),
- mReadOnly(TRUE),
- mNumEntries(0),
- mCacheSize(1)
-{
- mEnabled = gSavedSettings.getBOOL("ObjectCacheEnabled");
- mLocalAPRFilePoolp = new LLVolatileAPRPool() ;
-}
-
-LLVOCache::~LLVOCache()
-{
- if(mEnabled)
- {
- writeCacheHeader();
- clearCacheInMemory();
- }
- delete mLocalAPRFilePoolp;
-}
-
-void LLVOCache::setDirNames(ELLPath location)
-{
- std::string delem = gDirUtilp->getDirDelimiter();
-
- mHeaderFileName = gDirUtilp->getExpandedFilename(location, object_cache_dirname, header_filename);
- mObjectCacheDirName = gDirUtilp->getExpandedFilename(location, object_cache_dirname);
-}
-
-void LLVOCache::initCache(ELLPath location, U32 size, U32 cache_version)
-{
- if(!mEnabled)
- {
- llwarns << "Not initializing cache: Cache is currently disabled." << llendl;
- return ;
- }
-
- if(mInitialized)
- {
- llwarns << "Cache already initialized." << llendl;
- return ;
- }
- mInitialized = TRUE ;
-
- setDirNames(location);
- if (!mReadOnly)
- {
- LLFile::mkdir(mObjectCacheDirName);
- }
- mCacheSize = llclamp(size, MIN_ENTRIES_TO_PURGE, MAX_NUM_OBJECT_ENTRIES);
- mMetaInfo.mVersion = cache_version;
- readCacheHeader();
-
- if(mMetaInfo.mVersion != cache_version)
- {
- mMetaInfo.mVersion = cache_version ;
- if(mReadOnly) //disable cache
- {
- clearCacheInMemory();
- }
- else //delete the current cache if the format does not match.
- {
- removeCache();
- }
- }
-}
-
-void LLVOCache::removeCache(ELLPath location)
-{
- if(mReadOnly)
- {
- llwarns << "Not removing cache at " << location << ": Cache is currently in read-only mode." << llendl;
- return ;
- }
-
- llinfos << "about to remove the object cache due to settings." << llendl ;
-
- std::string delem = gDirUtilp->getDirDelimiter();
- std::string mask = delem + "*";
- std::string cache_dir = gDirUtilp->getExpandedFilename(location, object_cache_dirname);
- llinfos << "Removing cache at " << cache_dir << llendl;
- gDirUtilp->deleteFilesInDir(cache_dir, mask); //delete all files
- LLFile::rmdir(cache_dir);
-
- clearCacheInMemory();
- mInitialized = FALSE ;
-}
-
-void LLVOCache::removeCache()
-{
- llassert_always(mInitialized) ;
- if(mReadOnly)
- {
- llwarns << "Not clearing object cache: Cache is currently in read-only mode." << llendl;
- return ;
- }
-
- llinfos << "about to remove the object cache due to some error." << llendl ;
-
- std::string delem = gDirUtilp->getDirDelimiter();
- std::string mask = delem + "*";
- llinfos << "Removing cache at " << mObjectCacheDirName << llendl;
- gDirUtilp->deleteFilesInDir(mObjectCacheDirName, mask);
-
- clearCacheInMemory() ;
- writeCacheHeader();
-}
-
-void LLVOCache::removeEntry(HeaderEntryInfo* entry)
-{
- llassert_always(mInitialized) ;
- if(mReadOnly)
- {
- return ;
- }
- if(!entry)
- {
- return ;
- }
-
- header_entry_queue_t::iterator iter = mHeaderEntryQueue.find(entry) ;
- if(iter != mHeaderEntryQueue.end())
- {
- mHandleEntryMap.erase(entry->mHandle) ;
- mHeaderEntryQueue.erase(iter) ;
- removeFromCache(entry) ;
- delete entry ;
-
- mNumEntries = mHandleEntryMap.size() ;
- }
-}
-
-void LLVOCache::removeEntry(U64 handle)
-{
- handle_entry_map_t::iterator iter = mHandleEntryMap.find(handle) ;
- if(iter == mHandleEntryMap.end()) //no cache
- {
- return ;
- }
- HeaderEntryInfo* entry = iter->second ;
- removeEntry(entry) ;
-}
-
-void LLVOCache::clearCacheInMemory()
-{
- if(!mHeaderEntryQueue.empty())
- {
- for(header_entry_queue_t::iterator iter = mHeaderEntryQueue.begin(); iter != mHeaderEntryQueue.end(); ++iter)
- {
- delete *iter ;
- }
- mHeaderEntryQueue.clear();
- mHandleEntryMap.clear();
- mNumEntries = 0 ;
- }
-
-}
-
-void LLVOCache::getObjectCacheFilename(U64 handle, std::string& filename)
-{
- U32 region_x, region_y;
-
- grid_from_region_handle(handle, &region_x, &region_y);
- filename = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, object_cache_dirname,
- llformat(OBJECT_CACHE_FILENAME, region_x, region_y));
-
- return ;
-}
-
-void LLVOCache::removeFromCache(HeaderEntryInfo* entry)
-{
- if(mReadOnly)
- {
- llwarns << "Not removing cache for handle " << entry->mHandle << ": Cache is currently in read-only mode." << llendl;
- return ;
- }
-
- std::string filename;
- getObjectCacheFilename(entry->mHandle, filename);
- LLAPRFile::remove(filename, mLocalAPRFilePoolp);
- entry->mTime = INVALID_TIME ;
- updateEntry(entry) ; //update the head file.
-}
-
-void LLVOCache::readCacheHeader()
-{
- if(!mEnabled)
- {
- llwarns << "Not reading cache header: Cache is currently disabled." << llendl;
- return;
- }
-
- //clear stale info.
- clearCacheInMemory();
-
- bool success = true ;
- if (LLAPRFile::isExist(mHeaderFileName, mLocalAPRFilePoolp))
- {
- LLAPRFile apr_file(mHeaderFileName, APR_READ|APR_BINARY, mLocalAPRFilePoolp);
-
- //read the meta element
- success = check_read(&apr_file, &mMetaInfo, sizeof(HeaderMetaInfo)) ;
-
- if(success)
- {
- HeaderEntryInfo* entry = NULL ;
- mNumEntries = 0 ;
- U32 num_read = 0 ;
- while(num_read++ < MAX_NUM_OBJECT_ENTRIES)
- {
- if(!entry)
- {
- entry = new HeaderEntryInfo() ;
- }
- success = check_read(&apr_file, entry, sizeof(HeaderEntryInfo));
-
- if(!success) //failed
- {
- llwarns << "Error reading cache header entry. (entry_index=" << mNumEntries << ")" << llendl;
- delete entry ;
- entry = NULL ;
- break ;
- }
- else if(entry->mTime == INVALID_TIME)
- {
- continue ; //an empty entry
- }
-
- entry->mIndex = mNumEntries++ ;
- mHeaderEntryQueue.insert(entry) ;
- mHandleEntryMap[entry->mHandle] = entry ;
- entry = NULL ;
- }
- if(entry)
- {
- delete entry ;
- }
- }
-
- //---------
- //debug code
- //----------
- //std::string name ;
- //for(header_entry_queue_t::iterator iter = mHeaderEntryQueue.begin() ; success && iter != mHeaderEntryQueue.end(); ++iter)
- //{
- // getObjectCacheFilename((*iter)->mHandle, name) ;
- // llinfos << name << llendl ;
- //}
- //-----------
- }
- else
- {
- writeCacheHeader() ;
- }
-
- if(!success)
- {
- removeCache() ; //failed to read header, clear the cache
- }
- else if(mNumEntries >= mCacheSize)
- {
- purgeEntries(mCacheSize) ;
- }
-
- return ;
-}
-
-void LLVOCache::writeCacheHeader()
-{
- if (!mEnabled)
- {
- llwarns << "Not writing cache header: Cache is currently disabled." << llendl;
- return;
- }
-
- if(mReadOnly)
- {
- llwarns << "Not writing cache header: Cache is currently in read-only mode." << llendl;
- return;
- }
-
- bool success = true ;
- {
- LLAPRFile apr_file(mHeaderFileName, APR_CREATE|APR_WRITE|APR_BINARY, mLocalAPRFilePoolp);
-
- //write the meta element
- success = check_write(&apr_file, &mMetaInfo, sizeof(HeaderMetaInfo)) ;
-
-
- mNumEntries = 0 ;
- for(header_entry_queue_t::iterator iter = mHeaderEntryQueue.begin() ; success && iter != mHeaderEntryQueue.end(); ++iter)
- {
- (*iter)->mIndex = mNumEntries++ ;
- success = check_write(&apr_file, (void*)*iter, sizeof(HeaderEntryInfo));
- }
-
- mNumEntries = mHeaderEntryQueue.size() ;
- if(success && mNumEntries < MAX_NUM_OBJECT_ENTRIES)
- {
- HeaderEntryInfo* entry = new HeaderEntryInfo() ;
- entry->mTime = INVALID_TIME ;
- for(S32 i = mNumEntries ; success && i < MAX_NUM_OBJECT_ENTRIES ; i++)
- {
- //fill the cache with the default entry.
- success = check_write(&apr_file, entry, sizeof(HeaderEntryInfo)) ;
-
- }
- delete entry ;
- }
- }
-
- if(!success)
- {
- clearCacheInMemory() ;
- mReadOnly = TRUE ; //disable the cache.
- }
- return ;
-}
-
-BOOL LLVOCache::updateEntry(const HeaderEntryInfo* entry)
-{
- LLAPRFile apr_file(mHeaderFileName, APR_WRITE|APR_BINARY, mLocalAPRFilePoolp);
- apr_file.seek(APR_SET, entry->mIndex * sizeof(HeaderEntryInfo) + sizeof(HeaderMetaInfo)) ;
-
- return check_write(&apr_file, (void*)entry, sizeof(HeaderEntryInfo)) ;
-}
-
-void LLVOCache::readFromCache(U64 handle, const LLUUID& id, LLVOCacheEntry::vocache_entry_map_t& cache_entry_map)
-{
- if(!mEnabled)
- {
- llwarns << "Not reading cache for handle " << handle << "): Cache is currently disabled." << llendl;
- return ;
- }
- llassert_always(mInitialized);
-
- handle_entry_map_t::iterator iter = mHandleEntryMap.find(handle) ;
- if(iter == mHandleEntryMap.end()) //no cache
- {
- llwarns << "No handle map entry for " << handle << llendl;
- return ;
- }
-
- bool success = true ;
- {
- std::string filename;
- getObjectCacheFilename(handle, filename);
- LLAPRFile apr_file(filename, APR_READ|APR_BINARY, mLocalAPRFilePoolp);
-
- LLUUID cache_id ;
- success = check_read(&apr_file, cache_id.mData, UUID_BYTES) ;
-
- if(success)
- {
- if(cache_id != id)
- {
- llinfos << "Cache ID doesn't match for this region, discarding"<< llendl;
- success = false ;
- }
-
- if(success)
- {
- S32 num_entries;
- success = check_read(&apr_file, &num_entries, sizeof(S32)) ;
-
- for (S32 i = 0; success && i < num_entries; i++)
- {
- LLVOCacheEntry* entry = new LLVOCacheEntry(&apr_file);
- if (!entry->getLocalID())
- {
- llwarns << "Aborting cache file load for " << filename << ", cache file corruption!" << llendl;
- delete entry ;
- success = false ;
- }
- cache_entry_map[entry->getLocalID()] = entry;
- }
- }
- }
- }
-
- if(!success)
- {
- if(cache_entry_map.empty())
- {
- removeEntry(iter->second) ;
- }
- }
-
- return ;
-}
-
-void LLVOCache::purgeEntries(U32 size)
-{
- while(mHeaderEntryQueue.size() > size)
- {
- header_entry_queue_t::iterator iter = mHeaderEntryQueue.begin() ;
- HeaderEntryInfo* entry = *iter ;
- mHandleEntryMap.erase(entry->mHandle);
- mHeaderEntryQueue.erase(iter) ;
- removeFromCache(entry) ;
- delete entry;
- }
- mNumEntries = mHandleEntryMap.size() ;
-}
-
-void LLVOCache::writeToCache(U64 handle, const LLUUID& id, const LLVOCacheEntry::vocache_entry_map_t& cache_entry_map, BOOL dirty_cache)
-{
- if(!mEnabled)
- {
- llwarns << "Not writing cache for handle " << handle << "): Cache is currently disabled." << llendl;
- return ;
- }
- llassert_always(mInitialized);
-
- if(mReadOnly)
- {
- llwarns << "Not writing cache for handle " << handle << "): Cache is currently in read-only mode." << llendl;
- return ;
- }
-
- HeaderEntryInfo* entry;
- handle_entry_map_t::iterator iter = mHandleEntryMap.find(handle) ;
- if(iter == mHandleEntryMap.end()) //new entry
- {
- if(mNumEntries >= mCacheSize - 1)
- {
- purgeEntries(mCacheSize - 1) ;
- }
-
- entry = new HeaderEntryInfo();
- entry->mHandle = handle ;
- entry->mTime = time(NULL) ;
- entry->mIndex = mNumEntries++;
- mHeaderEntryQueue.insert(entry) ;
- mHandleEntryMap[handle] = entry ;
- }
- else
- {
- // Update access time.
- entry = iter->second ;
-
- //resort
- mHeaderEntryQueue.erase(entry) ;
-
- entry->mTime = time(NULL) ;
- mHeaderEntryQueue.insert(entry) ;
- }
-
- //update cache header
- if(!updateEntry(entry))
- {
- llwarns << "Failed to update cache header index " << entry->mIndex << ". handle = " << handle << llendl;
- return ; //update failed.
- }
-
- if(!dirty_cache)
- {
- llwarns << "Skipping write to cache for handle " << handle << ": cache not dirty" << llendl;
- return ; //nothing changed, no need to update.
- }
-
- //write to cache file
- bool success = true ;
- {
- std::string filename;
- getObjectCacheFilename(handle, filename);
- LLAPRFile apr_file(filename, APR_CREATE|APR_WRITE|APR_BINARY, mLocalAPRFilePoolp);
-
- success = check_write(&apr_file, (void*)id.mData, UUID_BYTES) ;
-
-
- if(success)
- {
- S32 num_entries = cache_entry_map.size() ;
- success = check_write(&apr_file, &num_entries, sizeof(S32));
-
- for (LLVOCacheEntry::vocache_entry_map_t::const_iterator iter = cache_entry_map.begin(); success && iter != cache_entry_map.end(); ++iter)
- {
- success = iter->second->writeToFile(&apr_file) ;
- }
- }
- }
-
- if(!success)
- {
- removeEntry(entry) ;
-
- }
-
- return ;
-}
-
+/**
+ * @file llvocache.cpp
+ * @brief Cache of objects on the viewer.
+ *
+ * $LicenseInfo:firstyear=2003&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h"
+#include "llvocache.h"
+#include "llerror.h"
+#include "llregionhandle.h"
+#include "llviewercontrol.h"
+
+BOOL check_read(LLAPRFile* apr_file, void* src, S32 n_bytes)
+{
+ return apr_file->read(src, n_bytes) == n_bytes ;
+}
+
+BOOL check_write(LLAPRFile* apr_file, void* src, S32 n_bytes)
+{
+ return apr_file->write(src, n_bytes) == n_bytes ;
+}
+
+
+//---------------------------------------------------------------------------
+// LLVOCacheEntry
+//---------------------------------------------------------------------------
+
+LLVOCacheEntry::LLVOCacheEntry(U32 local_id, U32 crc, LLDataPackerBinaryBuffer &dp)
+ :
+ mLocalID(local_id),
+ mCRC(crc),
+ mHitCount(0),
+ mDupeCount(0),
+ mCRCChangeCount(0)
+{
+ mBuffer = new U8[dp.getBufferSize()];
+ mDP.assignBuffer(mBuffer, dp.getBufferSize());
+ mDP = dp;
+}
+
+LLVOCacheEntry::LLVOCacheEntry()
+ :
+ mLocalID(0),
+ mCRC(0),
+ mHitCount(0),
+ mDupeCount(0),
+ mCRCChangeCount(0),
+ mBuffer(NULL)
+{
+ mDP.assignBuffer(mBuffer, 0);
+}
+
+LLVOCacheEntry::LLVOCacheEntry(LLAPRFile* apr_file)
+ : mBuffer(NULL)
+{
+ S32 size = -1;
+ BOOL success;
+
+ success = check_read(apr_file, &mLocalID, sizeof(U32));
+ if(success)
+ {
+ success = check_read(apr_file, &mCRC, sizeof(U32));
+ }
+ if(success)
+ {
+ success = check_read(apr_file, &mHitCount, sizeof(S32));
+ }
+ if(success)
+ {
+ success = check_read(apr_file, &mDupeCount, sizeof(S32));
+ }
+ if(success)
+ {
+ success = check_read(apr_file, &mCRCChangeCount, sizeof(S32));
+ }
+ if(success)
+ {
+ success = check_read(apr_file, &size, sizeof(S32));
+
+ // Corruption in the cache entries
+ if ((size > 10000) || (size < 1))
+ {
+ // We've got a bogus size, skip reading it.
+ // We won't bother seeking, because the rest of this file
+ // is likely bogus, and will be tossed anyway.
+ llwarns << "Bogus cache entry, size " << size << ", aborting!" << llendl;
+ success = FALSE;
+ }
+ }
+ if(success && size > 0)
+ {
+ mBuffer = new U8[size];
+ success = check_read(apr_file, mBuffer, size);
+
+ if(success)
+ {
+ mDP.assignBuffer(mBuffer, size);
+ }
+ else
+ {
+ delete[] mBuffer ;
+ mBuffer = NULL ;
+ }
+ }
+
+ if(!success)
+ {
+ mLocalID = 0;
+ mCRC = 0;
+ mHitCount = 0;
+ mDupeCount = 0;
+ mCRCChangeCount = 0;
+ mBuffer = NULL;
+ }
+}
+
+LLVOCacheEntry::~LLVOCacheEntry()
+{
+ if(mBuffer)
+ {
+ delete[] mBuffer;
+ }
+}
+
+
+// New CRC means the object has changed.
+void LLVOCacheEntry::assignCRC(U32 crc, LLDataPackerBinaryBuffer &dp)
+{
+ if ( (mCRC != crc)
+ ||(mDP.getBufferSize() == 0))
+ {
+ mCRC = crc;
+ mHitCount = 0;
+ mCRCChangeCount++;
+
+ mDP.freeBuffer();
+ mBuffer = new U8[dp.getBufferSize()];
+ mDP.assignBuffer(mBuffer, dp.getBufferSize());
+ mDP = dp;
+ }
+}
+
+LLDataPackerBinaryBuffer *LLVOCacheEntry::getDP(U32 crc)
+{
+ if ( (mCRC != crc)
+ ||(mDP.getBufferSize() == 0))
+ {
+ //llinfos << "Not getting cache entry, invalid!" << llendl;
+ return NULL;
+ }
+ mHitCount++;
+ return &mDP;
+}
+
+
+void LLVOCacheEntry::recordHit()
+{
+ mHitCount++;
+}
+
+
+void LLVOCacheEntry::dump() const
+{
+ llinfos << "local " << mLocalID
+ << " crc " << mCRC
+ << " hits " << mHitCount
+ << " dupes " << mDupeCount
+ << " change " << mCRCChangeCount
+ << llendl;
+}
+
+BOOL LLVOCacheEntry::writeToFile(LLAPRFile* apr_file) const
+{
+ BOOL success;
+ success = check_write(apr_file, (void*)&mLocalID, sizeof(U32));
+ if(success)
+ {
+ success = check_write(apr_file, (void*)&mCRC, sizeof(U32));
+ }
+ if(success)
+ {
+ success = check_write(apr_file, (void*)&mHitCount, sizeof(S32));
+ }
+ if(success)
+ {
+ success = check_write(apr_file, (void*)&mDupeCount, sizeof(S32));
+ }
+ if(success)
+ {
+ success = check_write(apr_file, (void*)&mCRCChangeCount, sizeof(S32));
+ }
+ if(success)
+ {
+ S32 size = mDP.getBufferSize();
+ success = check_write(apr_file, (void*)&size, sizeof(S32));
+
+ if(success)
+ {
+ success = check_write(apr_file, (void*)mBuffer, size);
+ }
+ }
+
+ return success ;
+}
+
+//-------------------------------------------------------------------
+//LLVOCache
+//-------------------------------------------------------------------
+// Format string used to construct filename for the object cache
+static const char OBJECT_CACHE_FILENAME[] = "objects_%d_%d.slc";
+
+const U32 MAX_NUM_OBJECT_ENTRIES = 128 ;
+const U32 MIN_ENTRIES_TO_PURGE = 16 ;
+const U32 INVALID_TIME = 0 ;
+const char* object_cache_dirname = "objectcache";
+const char* header_filename = "object.cache";
+
+LLVOCache* LLVOCache::sInstance = NULL;
+
+//static
+LLVOCache* LLVOCache::getInstance()
+{
+ if(!sInstance)
+ {
+ sInstance = new LLVOCache() ;
+ }
+ return sInstance ;
+}
+
+//static
+BOOL LLVOCache::hasInstance()
+{
+ return sInstance != NULL ;
+}
+
+//static
+void LLVOCache::destroyClass()
+{
+ if(sInstance)
+ {
+ delete sInstance ;
+ sInstance = NULL ;
+ }
+}
+
+LLVOCache::LLVOCache():
+ mInitialized(FALSE),
+ mReadOnly(TRUE),
+ mNumEntries(0),
+ mCacheSize(1)
+{
+ mEnabled = gSavedSettings.getBOOL("ObjectCacheEnabled");
+ mLocalAPRFilePoolp = new LLVolatileAPRPool() ;
+}
+
+LLVOCache::~LLVOCache()
+{
+ if(mEnabled)
+ {
+ writeCacheHeader();
+ clearCacheInMemory();
+ }
+ delete mLocalAPRFilePoolp;
+}
+
+void LLVOCache::setDirNames(ELLPath location)
+{
+ std::string delem = gDirUtilp->getDirDelimiter();
+
+ mHeaderFileName = gDirUtilp->getExpandedFilename(location, object_cache_dirname, header_filename);
+ mObjectCacheDirName = gDirUtilp->getExpandedFilename(location, object_cache_dirname);
+}
+
+void LLVOCache::initCache(ELLPath location, U32 size, U32 cache_version)
+{
+ if(!mEnabled)
+ {
+ llwarns << "Not initializing cache: Cache is currently disabled." << llendl;
+ return ;
+ }
+
+ if(mInitialized)
+ {
+ llwarns << "Cache already initialized." << llendl;
+ return ;
+ }
+ mInitialized = TRUE ;
+
+ setDirNames(location);
+ if (!mReadOnly)
+ {
+ LLFile::mkdir(mObjectCacheDirName);
+ }
+ mCacheSize = llclamp(size, MIN_ENTRIES_TO_PURGE, MAX_NUM_OBJECT_ENTRIES);
+ mMetaInfo.mVersion = cache_version;
+ readCacheHeader();
+
+ if(mMetaInfo.mVersion != cache_version)
+ {
+ mMetaInfo.mVersion = cache_version ;
+ if(mReadOnly) //disable cache
+ {
+ clearCacheInMemory();
+ }
+ else //delete the current cache if the format does not match.
+ {
+ removeCache();
+ }
+ }
+}
+
+void LLVOCache::removeCache(ELLPath location)
+{
+ if(mReadOnly)
+ {
+ llwarns << "Not removing cache at " << location << ": Cache is currently in read-only mode." << llendl;
+ return ;
+ }
+
+ llinfos << "about to remove the object cache due to settings." << llendl ;
+
+ std::string delem = gDirUtilp->getDirDelimiter();
+ std::string mask = delem + "*";
+ std::string cache_dir = gDirUtilp->getExpandedFilename(location, object_cache_dirname);
+ llinfos << "Removing cache at " << cache_dir << llendl;
+ gDirUtilp->deleteFilesInDir(cache_dir, mask); //delete all files
+ LLFile::rmdir(cache_dir);
+
+ clearCacheInMemory();
+ mInitialized = FALSE ;
+}
+
+void LLVOCache::removeCache()
+{
+ llassert_always(mInitialized) ;
+ if(mReadOnly)
+ {
+ llwarns << "Not clearing object cache: Cache is currently in read-only mode." << llendl;
+ return ;
+ }
+
+ llinfos << "about to remove the object cache due to some error." << llendl ;
+
+ std::string delem = gDirUtilp->getDirDelimiter();
+ std::string mask = delem + "*";
+ llinfos << "Removing cache at " << mObjectCacheDirName << llendl;
+ gDirUtilp->deleteFilesInDir(mObjectCacheDirName, mask);
+
+ clearCacheInMemory() ;
+ writeCacheHeader();
+}
+
+void LLVOCache::removeEntry(HeaderEntryInfo* entry)
+{
+ llassert_always(mInitialized) ;
+ if(mReadOnly)
+ {
+ return ;
+ }
+ if(!entry)
+ {
+ return ;
+ }
+
+ header_entry_queue_t::iterator iter = mHeaderEntryQueue.find(entry) ;
+ if(iter != mHeaderEntryQueue.end())
+ {
+ mHandleEntryMap.erase(entry->mHandle) ;
+ mHeaderEntryQueue.erase(iter) ;
+ removeFromCache(entry) ;
+ delete entry ;
+
+ mNumEntries = mHandleEntryMap.size() ;
+ }
+}
+
+void LLVOCache::removeEntry(U64 handle)
+{
+ handle_entry_map_t::iterator iter = mHandleEntryMap.find(handle) ;
+ if(iter == mHandleEntryMap.end()) //no cache
+ {
+ return ;
+ }
+ HeaderEntryInfo* entry = iter->second ;
+ removeEntry(entry) ;
+}
+
+void LLVOCache::clearCacheInMemory()
+{
+ if(!mHeaderEntryQueue.empty())
+ {
+ for(header_entry_queue_t::iterator iter = mHeaderEntryQueue.begin(); iter != mHeaderEntryQueue.end(); ++iter)
+ {
+ delete *iter ;
+ }
+ mHeaderEntryQueue.clear();
+ mHandleEntryMap.clear();
+ mNumEntries = 0 ;
+ }
+
+}
+
+void LLVOCache::getObjectCacheFilename(U64 handle, std::string& filename)
+{
+ U32 region_x, region_y;
+
+ grid_from_region_handle(handle, &region_x, &region_y);
+ filename = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, object_cache_dirname,
+ llformat(OBJECT_CACHE_FILENAME, region_x, region_y));
+
+ return ;
+}
+
+void LLVOCache::removeFromCache(HeaderEntryInfo* entry)
+{
+ if(mReadOnly)
+ {
+ llwarns << "Not removing cache for handle " << entry->mHandle << ": Cache is currently in read-only mode." << llendl;
+ return ;
+ }
+
+ std::string filename;
+ getObjectCacheFilename(entry->mHandle, filename);
+ LLAPRFile::remove(filename, mLocalAPRFilePoolp);
+ entry->mTime = INVALID_TIME ;
+ updateEntry(entry) ; //update the head file.
+}
+
+void LLVOCache::readCacheHeader()
+{
+ if(!mEnabled)
+ {
+ llwarns << "Not reading cache header: Cache is currently disabled." << llendl;
+ return;
+ }
+
+ //clear stale info.
+ clearCacheInMemory();
+
+ bool success = true ;
+ if (LLAPRFile::isExist(mHeaderFileName, mLocalAPRFilePoolp))
+ {
+ LLAPRFile apr_file(mHeaderFileName, APR_READ|APR_BINARY, mLocalAPRFilePoolp);
+
+ //read the meta element
+ success = check_read(&apr_file, &mMetaInfo, sizeof(HeaderMetaInfo)) ;
+
+ if(success)
+ {
+ HeaderEntryInfo* entry = NULL ;
+ mNumEntries = 0 ;
+ U32 num_read = 0 ;
+ while(num_read++ < MAX_NUM_OBJECT_ENTRIES)
+ {
+ if(!entry)
+ {
+ entry = new HeaderEntryInfo() ;
+ }
+ success = check_read(&apr_file, entry, sizeof(HeaderEntryInfo));
+
+ if(!success) //failed
+ {
+ llwarns << "Error reading cache header entry. (entry_index=" << mNumEntries << ")" << llendl;
+ delete entry ;
+ entry = NULL ;
+ break ;
+ }
+ else if(entry->mTime == INVALID_TIME)
+ {
+ continue ; //an empty entry
+ }
+
+ entry->mIndex = mNumEntries++ ;
+ mHeaderEntryQueue.insert(entry) ;
+ mHandleEntryMap[entry->mHandle] = entry ;
+ entry = NULL ;
+ }
+ if(entry)
+ {
+ delete entry ;
+ }
+ }
+
+ //---------
+ //debug code
+ //----------
+ //std::string name ;
+ //for(header_entry_queue_t::iterator iter = mHeaderEntryQueue.begin() ; success && iter != mHeaderEntryQueue.end(); ++iter)
+ //{
+ // getObjectCacheFilename((*iter)->mHandle, name) ;
+ // llinfos << name << llendl ;
+ //}
+ //-----------
+ }
+ else
+ {
+ writeCacheHeader() ;
+ }
+
+ if(!success)
+ {
+ removeCache() ; //failed to read header, clear the cache
+ }
+ else if(mNumEntries >= mCacheSize)
+ {
+ purgeEntries(mCacheSize) ;
+ }
+
+ return ;
+}
+
+void LLVOCache::writeCacheHeader()
+{
+ if (!mEnabled)
+ {
+ llwarns << "Not writing cache header: Cache is currently disabled." << llendl;
+ return;
+ }
+
+ if(mReadOnly)
+ {
+ llwarns << "Not writing cache header: Cache is currently in read-only mode." << llendl;
+ return;
+ }
+
+ bool success = true ;
+ {
+ LLAPRFile apr_file(mHeaderFileName, APR_CREATE|APR_WRITE|APR_BINARY, mLocalAPRFilePoolp);
+
+ //write the meta element
+ success = check_write(&apr_file, &mMetaInfo, sizeof(HeaderMetaInfo)) ;
+
+
+ mNumEntries = 0 ;
+ for(header_entry_queue_t::iterator iter = mHeaderEntryQueue.begin() ; success && iter != mHeaderEntryQueue.end(); ++iter)
+ {
+ (*iter)->mIndex = mNumEntries++ ;
+ success = check_write(&apr_file, (void*)*iter, sizeof(HeaderEntryInfo));
+ }
+
+ mNumEntries = mHeaderEntryQueue.size() ;
+ if(success && mNumEntries < MAX_NUM_OBJECT_ENTRIES)
+ {
+ HeaderEntryInfo* entry = new HeaderEntryInfo() ;
+ entry->mTime = INVALID_TIME ;
+ for(S32 i = mNumEntries ; success && i < MAX_NUM_OBJECT_ENTRIES ; i++)
+ {
+ //fill the cache with the default entry.
+ success = check_write(&apr_file, entry, sizeof(HeaderEntryInfo)) ;
+
+ }
+ delete entry ;
+ }
+ }
+
+ if(!success)
+ {
+ clearCacheInMemory() ;
+ mReadOnly = TRUE ; //disable the cache.
+ }
+ return ;
+}
+
+BOOL LLVOCache::updateEntry(const HeaderEntryInfo* entry)
+{
+ LLAPRFile apr_file(mHeaderFileName, APR_WRITE|APR_BINARY, mLocalAPRFilePoolp);
+ apr_file.seek(APR_SET, entry->mIndex * sizeof(HeaderEntryInfo) + sizeof(HeaderMetaInfo)) ;
+
+ return check_write(&apr_file, (void*)entry, sizeof(HeaderEntryInfo)) ;
+}
+
+void LLVOCache::readFromCache(U64 handle, const LLUUID& id, LLVOCacheEntry::vocache_entry_map_t& cache_entry_map)
+{
+ if(!mEnabled)
+ {
+ llwarns << "Not reading cache for handle " << handle << "): Cache is currently disabled." << llendl;
+ return ;
+ }
+ llassert_always(mInitialized);
+
+ handle_entry_map_t::iterator iter = mHandleEntryMap.find(handle) ;
+ if(iter == mHandleEntryMap.end()) //no cache
+ {
+ llwarns << "No handle map entry for " << handle << llendl;
+ return ;
+ }
+
+ bool success = true ;
+ {
+ std::string filename;
+ getObjectCacheFilename(handle, filename);
+ LLAPRFile apr_file(filename, APR_READ|APR_BINARY, mLocalAPRFilePoolp);
+
+ LLUUID cache_id ;
+ success = check_read(&apr_file, cache_id.mData, UUID_BYTES) ;
+
+ if(success)
+ {
+ if(cache_id != id)
+ {
+ llinfos << "Cache ID doesn't match for this region, discarding"<< llendl;
+ success = false ;
+ }
+
+ if(success)
+ {
+ S32 num_entries;
+ success = check_read(&apr_file, &num_entries, sizeof(S32)) ;
+
+ for (S32 i = 0; success && i < num_entries; i++)
+ {
+ LLVOCacheEntry* entry = new LLVOCacheEntry(&apr_file);
+ if (!entry->getLocalID())
+ {
+ llwarns << "Aborting cache file load for " << filename << ", cache file corruption!" << llendl;
+ delete entry ;
+ success = false ;
+ }
+ cache_entry_map[entry->getLocalID()] = entry;
+ }
+ }
+ }
+ }
+
+ if(!success)
+ {
+ if(cache_entry_map.empty())
+ {
+ removeEntry(iter->second) ;
+ }
+ }
+
+ return ;
+}
+
+void LLVOCache::purgeEntries(U32 size)
+{
+ while(mHeaderEntryQueue.size() > size)
+ {
+ header_entry_queue_t::iterator iter = mHeaderEntryQueue.begin() ;
+ HeaderEntryInfo* entry = *iter ;
+ mHandleEntryMap.erase(entry->mHandle);
+ mHeaderEntryQueue.erase(iter) ;
+ removeFromCache(entry) ;
+ delete entry;
+ }
+ mNumEntries = mHandleEntryMap.size() ;
+}
+
+void LLVOCache::writeToCache(U64 handle, const LLUUID& id, const LLVOCacheEntry::vocache_entry_map_t& cache_entry_map, BOOL dirty_cache)
+{
+ if(!mEnabled)
+ {
+ llwarns << "Not writing cache for handle " << handle << "): Cache is currently disabled." << llendl;
+ return ;
+ }
+ llassert_always(mInitialized);
+
+ if(mReadOnly)
+ {
+ llwarns << "Not writing cache for handle " << handle << "): Cache is currently in read-only mode." << llendl;
+ return ;
+ }
+
+ HeaderEntryInfo* entry;
+ handle_entry_map_t::iterator iter = mHandleEntryMap.find(handle) ;
+ if(iter == mHandleEntryMap.end()) //new entry
+ {
+ if(mNumEntries >= mCacheSize - 1)
+ {
+ purgeEntries(mCacheSize - 1) ;
+ }
+
+ entry = new HeaderEntryInfo();
+ entry->mHandle = handle ;
+ entry->mTime = time(NULL) ;
+ entry->mIndex = mNumEntries++;
+ mHeaderEntryQueue.insert(entry) ;
+ mHandleEntryMap[handle] = entry ;
+ }
+ else
+ {
+ // Update access time.
+ entry = iter->second ;
+
+ //resort
+ mHeaderEntryQueue.erase(entry) ;
+
+ entry->mTime = time(NULL) ;
+ mHeaderEntryQueue.insert(entry) ;
+ }
+
+ //update cache header
+ if(!updateEntry(entry))
+ {
+ llwarns << "Failed to update cache header index " << entry->mIndex << ". handle = " << handle << llendl;
+ return ; //update failed.
+ }
+
+ if(!dirty_cache)
+ {
+ llwarns << "Skipping write to cache for handle " << handle << ": cache not dirty" << llendl;
+ return ; //nothing changed, no need to update.
+ }
+
+ //write to cache file
+ bool success = true ;
+ {
+ std::string filename;
+ getObjectCacheFilename(handle, filename);
+ LLAPRFile apr_file(filename, APR_CREATE|APR_WRITE|APR_BINARY, mLocalAPRFilePoolp);
+
+ success = check_write(&apr_file, (void*)id.mData, UUID_BYTES) ;
+
+
+ if(success)
+ {
+ S32 num_entries = cache_entry_map.size() ;
+ success = check_write(&apr_file, &num_entries, sizeof(S32));
+
+ for (LLVOCacheEntry::vocache_entry_map_t::const_iterator iter = cache_entry_map.begin(); success && iter != cache_entry_map.end(); ++iter)
+ {
+ success = iter->second->writeToFile(&apr_file) ;
+ }
+ }
+ }
+
+ if(!success)
+ {
+ removeEntry(entry) ;
+
+ }
+
+ return ;
+}
+
diff --git a/indra/newview/llvograss.cpp b/indra/newview/llvograss.cpp
index f57f7b67ea..32822e1181 100644
--- a/indra/newview/llvograss.cpp
+++ b/indra/newview/llvograss.cpp
@@ -340,7 +340,7 @@ void LLVOGrass::updateTextures()
{
if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_AREA))
{
- setDebugText(llformat("%4.0f", fsqrtf(mPixelArea)));
+ setDebugText(llformat("%4.0f", (F32) sqrt(mPixelArea)));
}
getTEImage(0)->addTextureStats(mPixelArea);
}
@@ -453,7 +453,7 @@ void LLVOGrass::plantBlades()
face->setTexture(getTEImage(0));
face->setState(LLFace::GLOBAL);
face->setSize(mNumBlades * 8, mNumBlades * 12);
- face->mVertexBuffer = NULL;
+ face->setVertexBuffer(NULL);
face->setTEOffset(0);
face->mCenterLocal = mPosition + mRegionp->getOriginAgent();
@@ -640,7 +640,7 @@ BOOL LLVOGrass::lineSegmentIntersect(const LLVector3& start, const LLVector3& en
LLVector2 tc[4];
LLVector3 v[4];
- // LLVector3 n[4]; // unused!
+ //LLVector3 n[4];
F32 closest_t = 1.f;
@@ -686,7 +686,6 @@ BOOL LLVOGrass::lineSegmentIntersect(const LLVector3& start, const LLVector3& en
position.mV[2] += blade_height;
v[3] = v1 = position + mRegionp->getOriginAgent();
-
F32 a,b,t;
BOOL hit = FALSE;
@@ -694,23 +693,23 @@ BOOL LLVOGrass::lineSegmentIntersect(const LLVector3& start, const LLVector3& en
U32 idx0 = 0,idx1 = 0,idx2 = 0;
- if (LLTriangleRayIntersect(v[0], v[1], v[2], start, dir, &a, &b, &t, FALSE))
+ if (LLTriangleRayIntersect(v[0], v[1], v[2], start, dir, a, b, t, FALSE))
{
hit = TRUE;
idx0 = 0; idx1 = 1; idx2 = 2;
}
- else if (LLTriangleRayIntersect(v[1], v[3], v[2], start, dir, &a, &b, &t, FALSE))
+ else if (LLTriangleRayIntersect(v[1], v[3], v[2], start, dir, a, b, t, FALSE))
{
hit = TRUE;
idx0 = 1; idx1 = 3; idx2 = 2;
}
- else if (LLTriangleRayIntersect(v[2], v[1], v[0], start, dir, &a, &b, &t, FALSE))
+ else if (LLTriangleRayIntersect(v[2], v[1], v[0], start, dir, a, b, t, FALSE))
{
normal1 = -normal1;
hit = TRUE;
idx0 = 2; idx1 = 1; idx2 = 0;
}
- else if (LLTriangleRayIntersect(v[2], v[3], v[1], start, dir, &a, &b, &t, FALSE))
+ else if (LLTriangleRayIntersect(v[2], v[3], v[1], start, dir, a, b, t, FALSE))
{
normal1 = -normal1;
hit = TRUE;
diff --git a/indra/newview/llvoground.cpp b/indra/newview/llvoground.cpp
index f032ae8780..ce256fdedf 100644
--- a/indra/newview/llvoground.cpp
+++ b/indra/newview/llvoground.cpp
@@ -97,13 +97,14 @@ BOOL LLVOGround::updateGeometry(LLDrawable *drawable)
drawable->addFace(poolp, NULL);
face = drawable->getFace(0);
- if (face->mVertexBuffer.isNull())
+ if (!face->getVertexBuffer())
{
face->setSize(5, 12);
- face->mVertexBuffer = new LLVertexBuffer(LLDrawPoolGround::VERTEX_DATA_MASK, GL_STREAM_DRAW_ARB);
- face->mVertexBuffer->allocateBuffer(face->getGeomCount(), face->getIndicesCount(), TRUE);
+ LLVertexBuffer* buff = new LLVertexBuffer(LLDrawPoolGround::VERTEX_DATA_MASK, GL_STREAM_DRAW_ARB);
+ buff->allocateBuffer(face->getGeomCount(), face->getIndicesCount(), TRUE);
face->setGeomIndex(0);
face->setIndicesIndex(0);
+ face->setVertexBuffer(buff);
}
index_offset = face->getGeometry(verticesp,normalsp,texCoordsp, indicesp);
@@ -161,7 +162,7 @@ BOOL LLVOGround::updateGeometry(LLDrawable *drawable)
*(texCoordsp++) = LLVector2(0.f, 1.f);
*(texCoordsp++) = LLVector2(0.5f, 0.5f);
- face->mVertexBuffer->setBuffer(0);
+ face->getVertexBuffer()->setBuffer(0);
LLPipeline::sCompiles++;
return TRUE;
}
diff --git a/indra/newview/llvoicevivox.cpp b/indra/newview/llvoicevivox.cpp
index 08e242af8e..daaf2a4e96 100644
--- a/indra/newview/llvoicevivox.cpp
+++ b/indra/newview/llvoicevivox.cpp
@@ -6979,13 +6979,6 @@ void LLVivoxProtocolParser::reset()
alias.clear();
numberOfAliases = 0;
applicationString.clear();
- id = 0;
- nameString.clear();
- descriptionString.clear();
- expirationDate = LLDate();
- hasExpired = false;
- fontType = 0;
- fontStatus = 0;
}
//virtual
diff --git a/indra/newview/llvopartgroup.cpp b/indra/newview/llvopartgroup.cpp
index 40833ad259..6f354b78b1 100644
--- a/indra/newview/llvopartgroup.cpp
+++ b/indra/newview/llvopartgroup.cpp
@@ -73,12 +73,14 @@ F32 LLVOPartGroup::getBinRadius()
return mScale.mV[0]*2.f;
}
-void LLVOPartGroup::updateSpatialExtents(LLVector3& newMin, LLVector3& newMax)
+void LLVOPartGroup::updateSpatialExtents(LLVector4a& newMin, LLVector4a& newMax)
{
const LLVector3& pos_agent = getPositionAgent();
- newMin = pos_agent - mScale;
- newMax = pos_agent + mScale;
- mDrawable->setPositionGroup(pos_agent);
+ newMin.load3( (pos_agent - mScale).mV);
+ newMax.load3( (pos_agent + mScale).mV);
+ LLVector4a pos;
+ pos.load3(pos_agent.mV);
+ mDrawable->setPositionGroup(pos);
}
BOOL LLVOPartGroup::idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time)
@@ -358,7 +360,7 @@ U32 LLVOPartGroup::getPartitionType() const
}
LLParticlePartition::LLParticlePartition()
-: LLSpatialPartition(LLDrawPoolAlpha::VERTEX_DATA_MASK, TRUE, GL_DYNAMIC_DRAW_ARB)
+: LLSpatialPartition(LLDrawPoolAlpha::VERTEX_DATA_MASK, TRUE, GL_STREAM_DRAW_ARB)
{
mRenderPass = LLRenderPass::PASS_ALPHA;
mDrawableType = LLPipeline::RENDER_TYPE_PARTICLES;
@@ -461,7 +463,7 @@ void LLParticlePartition::getGeometry(LLSpatialGroup* group)
LLAlphaObject* object = (LLAlphaObject*) facep->getViewerObject();
facep->setGeomIndex(vertex_count);
facep->setIndicesIndex(index_count);
- facep->mVertexBuffer = buffer;
+ facep->setVertexBuffer(buffer);
facep->setPoolType(LLDrawPool::POOL_ALPHA);
object->getGeometry(facep->getTEOffset(), verticesp, normalsp, texcoordsp, colorsp, indicesp);
diff --git a/indra/newview/llvopartgroup.h b/indra/newview/llvopartgroup.h
index b136f2cbfa..4db893b4ef 100644
--- a/indra/newview/llvopartgroup.h
+++ b/indra/newview/llvopartgroup.h
@@ -51,7 +51,7 @@ public:
BOOL idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time);
virtual F32 getBinRadius();
- virtual void updateSpatialExtents(LLVector3& newMin, LLVector3& newMax);
+ virtual void updateSpatialExtents(LLVector4a& newMin, LLVector4a& newMax);
virtual U32 getPartitionType() const;
/*virtual*/ void setPixelAreaAndAngle(LLAgent &agent);
diff --git a/indra/newview/llvosky.cpp b/indra/newview/llvosky.cpp
index 80f43e51d2..288d335e1d 100644
--- a/indra/newview/llvosky.cpp
+++ b/indra/newview/llvosky.cpp
@@ -1182,7 +1182,7 @@ BOOL LLVOSky::updateSky()
}
}
- if (mDrawable.notNull() && mDrawable->getFace(0) && mDrawable->getFace(0)->mVertexBuffer.isNull())
+ if (mDrawable.notNull() && mDrawable->getFace(0) && !mDrawable->getFace(0)->getVertexBuffer())
{
gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, TRUE);
}
@@ -1233,10 +1233,11 @@ void LLVOSky::createDummyVertexBuffer()
mFace[FACE_DUMMY] = mDrawable->addFace(poolp, NULL);
}
- if(mFace[FACE_DUMMY]->mVertexBuffer.isNull())
+ if(!mFace[FACE_DUMMY]->getVertexBuffer())
{
- mFace[FACE_DUMMY]->mVertexBuffer = new LLVertexBuffer(LLDrawPoolSky::VERTEX_DATA_MASK, GL_DYNAMIC_DRAW_ARB);
- mFace[FACE_DUMMY]->mVertexBuffer->allocateBuffer(1, 1, TRUE);
+ LLVertexBuffer* buff = new LLVertexBuffer(LLDrawPoolSky::VERTEX_DATA_MASK, GL_DYNAMIC_DRAW_ARB);
+ buff->allocateBuffer(1, 1, TRUE);
+ mFace[FACE_DUMMY]->setVertexBuffer(buff);
}
}
@@ -1255,13 +1256,13 @@ void LLVOSky::updateDummyVertexBuffer()
LLFastTimer t(FTM_RENDER_FAKE_VBO_UPDATE) ;
- if(!mFace[FACE_DUMMY] || mFace[FACE_DUMMY]->mVertexBuffer.isNull())
+ if(!mFace[FACE_DUMMY] || !mFace[FACE_DUMMY]->getVertexBuffer())
createDummyVertexBuffer() ;
LLStrider<LLVector3> vertices ;
- mFace[FACE_DUMMY]->mVertexBuffer->getVertexStrider(vertices, 0);
+ mFace[FACE_DUMMY]->getVertexBuffer()->getVertexStrider(vertices, 0);
*vertices = mCameraPosAgent ;
- mFace[FACE_DUMMY]->mVertexBuffer->setBuffer(0) ;
+ mFace[FACE_DUMMY]->getVertexBuffer()->setBuffer(0) ;
}
//----------------------------------
//end of fake vertex buffer updating
@@ -1304,14 +1305,15 @@ BOOL LLVOSky::updateGeometry(LLDrawable *drawable)
{
face = mFace[FACE_SIDE0 + side];
- if (face->mVertexBuffer.isNull())
+ if (!face->getVertexBuffer())
{
face->setSize(4, 6);
face->setGeomIndex(0);
face->setIndicesIndex(0);
- face->mVertexBuffer = new LLVertexBuffer(LLDrawPoolSky::VERTEX_DATA_MASK, GL_STREAM_DRAW_ARB);
- face->mVertexBuffer->allocateBuffer(4, 6, TRUE);
-
+ LLVertexBuffer* buff = new LLVertexBuffer(LLDrawPoolSky::VERTEX_DATA_MASK, GL_STREAM_DRAW_ARB);
+ buff->allocateBuffer(4, 6, TRUE);
+ face->setVertexBuffer(buff);
+
index_offset = face->getGeometry(verticesp,normalsp,texCoordsp, indicesp);
S32 vtx = 0;
@@ -1344,7 +1346,7 @@ BOOL LLVOSky::updateGeometry(LLDrawable *drawable)
*indicesp++ = index_offset + 3;
*indicesp++ = index_offset + 2;
- face->mVertexBuffer->setBuffer(0);
+ buff->setBuffer(0);
}
}
@@ -1471,13 +1473,14 @@ BOOL LLVOSky::updateHeavenlyBodyGeometry(LLDrawable *drawable, const S32 f, cons
facep = mFace[f];
- if (facep->mVertexBuffer.isNull())
+ if (!facep->getVertexBuffer())
{
- facep->setSize(4, 6);
- facep->mVertexBuffer = new LLVertexBuffer(LLDrawPoolSky::VERTEX_DATA_MASK, GL_STREAM_DRAW_ARB);
- facep->mVertexBuffer->allocateBuffer(facep->getGeomCount(), facep->getIndicesCount(), TRUE);
+ facep->setSize(4, 6);
+ LLVertexBuffer* buff = new LLVertexBuffer(LLDrawPoolSky::VERTEX_DATA_MASK, GL_STREAM_DRAW_ARB);
+ buff->allocateBuffer(facep->getGeomCount(), facep->getIndicesCount(), TRUE);
facep->setGeomIndex(0);
facep->setIndicesIndex(0);
+ facep->setVertexBuffer(buff);
}
index_offset = facep->getGeometry(verticesp,normalsp,texCoordsp, indicesp);
@@ -1506,7 +1509,7 @@ BOOL LLVOSky::updateHeavenlyBodyGeometry(LLDrawable *drawable, const S32 f, cons
*indicesp++ = index_offset + 2;
*indicesp++ = index_offset + 3;
- facep->mVertexBuffer->setBuffer(0);
+ facep->getVertexBuffer()->setBuffer(0);
if (is_sun)
{
@@ -1875,13 +1878,14 @@ void LLVOSky::updateReflectionGeometry(LLDrawable *drawable, F32 H,
LLFace *face = mFace[FACE_REFLECTION];
- if (face->mVertexBuffer.isNull() || quads*4 != face->getGeomCount())
+ if (!face->getVertexBuffer() || quads*4 != face->getGeomCount())
{
face->setSize(quads * 4, quads * 6);
- face->mVertexBuffer = new LLVertexBuffer(LLDrawPoolWater::VERTEX_DATA_MASK, GL_STREAM_DRAW_ARB);
- face->mVertexBuffer->allocateBuffer(face->getGeomCount(), face->getIndicesCount(), TRUE);
+ LLVertexBuffer* buff = new LLVertexBuffer(LLDrawPoolWater::VERTEX_DATA_MASK, GL_STREAM_DRAW_ARB);
+ buff->allocateBuffer(face->getGeomCount(), face->getIndicesCount(), TRUE);
face->setIndicesIndex(0);
face->setGeomIndex(0);
+ face->setVertexBuffer(buff);
}
LLStrider<LLVector3> verticesp;
@@ -2019,7 +2023,7 @@ void LLVOSky::updateReflectionGeometry(LLDrawable *drawable, F32 H,
}
}
- face->mVertexBuffer->setBuffer(0);
+ face->getVertexBuffer()->setBuffer(0);
}
diff --git a/indra/newview/llvosurfacepatch.cpp b/indra/newview/llvosurfacepatch.cpp
index 2eb4398488..dbcd4f50ca 100644
--- a/indra/newview/llvosurfacepatch.cpp
+++ b/indra/newview/llvosurfacepatch.cpp
@@ -54,27 +54,77 @@ public:
LLVertexBuffer(MAP_VERTEX | MAP_NORMAL | MAP_TEXCOORD0 | MAP_TEXCOORD1 | MAP_COLOR, GL_DYNAMIC_DRAW_ARB)
{
//texture coordinates 2 and 3 exist, but use the same data as texture coordinate 1
- mOffsets[TYPE_TEXCOORD3] = mOffsets[TYPE_TEXCOORD2] = mOffsets[TYPE_TEXCOORD1];
- mTypeMask |= MAP_TEXCOORD2 | MAP_TEXCOORD3;
};
- /*// virtual
+ // virtual
void setupVertexBuffer(U32 data_mask) const
- {
- if (LLDrawPoolTerrain::getDetailMode() == 0 || LLPipeline::sShadowRender)
+ {
+ U8* base = useVBOs() ? (U8*) mAlignedOffset : mMappedData;
+
+ //assume tex coords 2 and 3 are present
+ U32 type_mask = mTypeMask | MAP_TEXCOORD2 | MAP_TEXCOORD3;
+
+ if ((data_mask & type_mask) != data_mask)
{
- LLVertexBuffer::setupVertexBuffer(data_mask);
+ llerrs << "LLVertexBuffer::setupVertexBuffer missing required components for supplied data mask." << llendl;
+ }
+
+ if (data_mask & MAP_NORMAL)
+ {
+ glNormalPointer(GL_FLOAT, LLVertexBuffer::sTypeSize[TYPE_NORMAL], (void*)(base + mOffsets[TYPE_NORMAL]));
+ }
+ if (data_mask & MAP_TEXCOORD3)
+ { //substitute tex coord 0 for tex coord 3
+ glClientActiveTextureARB(GL_TEXTURE3_ARB);
+ glTexCoordPointer(2,GL_FLOAT, LLVertexBuffer::sTypeSize[TYPE_TEXCOORD0], (void*)(base + mOffsets[TYPE_TEXCOORD0]));
+ glClientActiveTextureARB(GL_TEXTURE0_ARB);
+ }
+ if (data_mask & MAP_TEXCOORD2)
+ { //substitute tex coord 0 for tex coord 2
+ glClientActiveTextureARB(GL_TEXTURE2_ARB);
+ glTexCoordPointer(2,GL_FLOAT, LLVertexBuffer::sTypeSize[TYPE_TEXCOORD0], (void*)(base + mOffsets[TYPE_TEXCOORD0]));
+ glClientActiveTextureARB(GL_TEXTURE0_ARB);
}
- else if (data_mask & LLVertexBuffer::MAP_TEXCOORD1)
+ if (data_mask & MAP_TEXCOORD1)
{
- LLVertexBuffer::setupVertexBuffer(data_mask);
+ glClientActiveTextureARB(GL_TEXTURE1_ARB);
+ glTexCoordPointer(2,GL_FLOAT, LLVertexBuffer::sTypeSize[TYPE_TEXCOORD1], (void*)(base + mOffsets[TYPE_TEXCOORD1]));
+ glClientActiveTextureARB(GL_TEXTURE0_ARB);
}
- else
+ if (data_mask & MAP_BINORMAL)
{
- LLVertexBuffer::setupVertexBuffer(data_mask);
+ glClientActiveTextureARB(GL_TEXTURE2_ARB);
+ glTexCoordPointer(3,GL_FLOAT, LLVertexBuffer::sTypeSize[TYPE_BINORMAL], (void*)(base + mOffsets[TYPE_BINORMAL]));
+ glClientActiveTextureARB(GL_TEXTURE0_ARB);
}
- llglassertok();
- }*/
+ if (data_mask & MAP_TEXCOORD0)
+ {
+ glTexCoordPointer(2,GL_FLOAT, LLVertexBuffer::sTypeSize[TYPE_TEXCOORD0], (void*)(base + mOffsets[TYPE_TEXCOORD0]));
+ }
+ if (data_mask & MAP_COLOR)
+ {
+ glColorPointer(4, GL_UNSIGNED_BYTE, LLVertexBuffer::sTypeSize[TYPE_COLOR], (void*)(base + mOffsets[TYPE_COLOR]));
+ }
+
+ if (data_mask & MAP_WEIGHT)
+ {
+ glVertexAttribPointerARB(1, 1, GL_FLOAT, FALSE, LLVertexBuffer::sTypeSize[TYPE_WEIGHT], (void*)(base + mOffsets[TYPE_WEIGHT]));
+ }
+
+ if (data_mask & MAP_WEIGHT4 && sWeight4Loc != -1)
+ {
+ glVertexAttribPointerARB(sWeight4Loc, 4, GL_FLOAT, FALSE, LLVertexBuffer::sTypeSize[TYPE_WEIGHT4], (void*)(base+mOffsets[TYPE_WEIGHT4]));
+ }
+
+ if (data_mask & MAP_CLOTHWEIGHT)
+ {
+ glVertexAttribPointerARB(4, 4, GL_FLOAT, TRUE, LLVertexBuffer::sTypeSize[TYPE_CLOTHWEIGHT], (void*)(base + mOffsets[TYPE_CLOTHWEIGHT]));
+ }
+ if (data_mask & MAP_VERTEX)
+ {
+ glVertexPointer(3,GL_FLOAT, LLVertexBuffer::sTypeSize[TYPE_VERTEX], (void*)(base + 0));
+ }
+ }
};
//============================================================================
@@ -840,7 +890,7 @@ void LLVOSurfacePatch::dirtyGeom()
if (mDrawable)
{
gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_ALL, TRUE);
- mDrawable->getFace(0)->mVertexBuffer = NULL;
+ mDrawable->getFace(0)->setVertexBuffer(NULL);
mDrawable->movePartition();
}
}
@@ -939,7 +989,13 @@ BOOL LLVOSurfacePatch::lineSegmentIntersect(const LLVector3& start, const LLVect
//step one meter at a time until intersection point found
- const LLVector3* ext = mDrawable->getSpatialExtents();
+ //VECTORIZE THIS
+ const LLVector4a* exta = mDrawable->getSpatialExtents();
+
+ LLVector3 ext[2];
+ ext[0].set(exta[0].getF32ptr());
+ ext[1].set(exta[1].getF32ptr());
+
F32 rad = (delta*tdelta).magVecSquared();
F32 t = 0.f;
@@ -1001,13 +1057,16 @@ BOOL LLVOSurfacePatch::lineSegmentIntersect(const LLVector3& start, const LLVect
return FALSE;
}
-void LLVOSurfacePatch::updateSpatialExtents(LLVector3& newMin, LLVector3 &newMax)
+void LLVOSurfacePatch::updateSpatialExtents(LLVector4a& newMin, LLVector4a &newMax)
{
LLVector3 posAgent = getPositionAgent();
LLVector3 scale = getScale();
- newMin = posAgent-scale*0.5f; // Changing to 2.f makes the culling a -little- better, but still wrong
- newMax = posAgent+scale*0.5f;
- mDrawable->setPositionGroup((newMin+newMax)*0.5f);
+ newMin.load3( (posAgent-scale*0.5f).mV); // Changing to 2.f makes the culling a -little- better, but still wrong
+ newMax.load3( (posAgent+scale*0.5f).mV);
+ LLVector4a pos;
+ pos.setAdd(newMin,newMax);
+ pos.mul(0.5f);
+ mDrawable->setPositionGroup(pos);
}
U32 LLVOSurfacePatch::getPartitionType() const
@@ -1060,7 +1119,7 @@ void LLTerrainPartition::getGeometry(LLSpatialGroup* group)
facep->setIndicesIndex(indices_index);
facep->setGeomIndex(index_offset);
- facep->mVertexBuffer = buffer;
+ facep->setVertexBuffer(buffer);
LLVOSurfacePatch* patchp = (LLVOSurfacePatch*) facep->getViewerObject();
patchp->getGeometry(vertices, normals, colors, texcoords, texcoords2, indices);
diff --git a/indra/newview/llvosurfacepatch.h b/indra/newview/llvosurfacepatch.h
index bd80e1dbe6..8e75ff2e6e 100644
--- a/indra/newview/llvosurfacepatch.h
+++ b/indra/newview/llvosurfacepatch.h
@@ -72,7 +72,7 @@ public:
/*virtual*/ void updateTextures();
/*virtual*/ void setPixelAreaAndAngle(LLAgent &agent); // generate accurate apparent angle and area
- /*virtual*/ void updateSpatialExtents(LLVector3& newMin, LLVector3& newMax);
+ /*virtual*/ void updateSpatialExtents(LLVector4a& newMin, LLVector4a& newMax);
/*virtual*/ BOOL isActive() const; // Whether this object needs to do an idleUpdate.
void setPatch(LLSurfacePatch *patchp);
diff --git a/indra/newview/llvotextbubble.cpp b/indra/newview/llvotextbubble.cpp
index b61dae53ba..a92172fe23 100644
--- a/indra/newview/llvotextbubble.cpp
+++ b/indra/newview/llvotextbubble.cpp
@@ -39,6 +39,7 @@
#include "llviewertexturelist.h"
#include "llvolume.h"
#include "pipeline.h"
+#include "llvector4a.h"
#include "llviewerregion.h"
LLVOTextBubble::LLVOTextBubble(const LLUUID &id, const LLPCode pcode, LLViewerRegion *regionp)
@@ -211,7 +212,7 @@ void LLVOTextBubble::updateFaceSize(S32 idx)
else
{
const LLVolumeFace& vol_face = getVolume()->getVolumeFace(idx);
- face->setSize(vol_face.mVertices.size(), vol_face.mIndices.size());
+ face->setSize(vol_face.mNumVertices, vol_face.mNumIndices);
}
}
@@ -229,19 +230,37 @@ void LLVOTextBubble::getGeometry(S32 idx,
const LLVolumeFace& face = getVolume()->getVolumeFace(idx);
- LLVector3 pos = getPositionAgent();
+ LLVector4a pos;
+ pos.load3(getPositionAgent().mV);
+
+ LLVector4a scale;
+ scale.load3(getScale().mV);
+
LLColor4U color = LLColor4U(getTE(idx)->getColor());
U32 offset = mDrawable->getFace(idx)->getGeomIndex();
- for (U32 i = 0; i < face.mVertices.size(); i++)
+ LLVector4a* dst_pos = (LLVector4a*) verticesp.get();
+ LLVector4a* src_pos = (LLVector4a*) face.mPositions;
+
+ LLVector4a* dst_norm = (LLVector4a*) normalsp.get();
+ LLVector4a* src_norm = (LLVector4a*) face.mNormals;
+
+ LLVector2* dst_tc = (LLVector2*) texcoordsp.get();
+ LLVector2* src_tc = (LLVector2*) face.mTexCoords;
+
+ LLVector4a::memcpyNonAliased16((F32*) dst_norm, (F32*) src_norm, face.mNumVertices*4*sizeof(F32));
+ LLVector4a::memcpyNonAliased16((F32*) dst_tc, (F32*) src_tc, face.mNumVertices*2*sizeof(F32));
+
+
+ for (U32 i = 0; i < face.mNumVertices; i++)
{
- *verticesp++ = face.mVertices[i].mPosition.scaledVec(getScale()) + pos;
- *normalsp++ = face.mVertices[i].mNormal;
- *texcoordsp++ = face.mVertices[i].mTexCoord;
+ LLVector4a t;
+ t.setMul(src_pos[i], scale);
+ dst_pos[i].setAdd(t, pos);
*colorsp++ = color;
}
- for (U32 i = 0; i < face.mIndices.size(); i++)
+ for (U32 i = 0; i < face.mNumIndices; i++)
{
*indicesp++ = face.mIndices[i] + offset;
}
diff --git a/indra/newview/llvotree.cpp b/indra/newview/llvotree.cpp
index 37a974be28..e6f2b19e07 100644
--- a/indra/newview/llvotree.cpp
+++ b/indra/newview/llvotree.cpp
@@ -485,7 +485,7 @@ void LLVOTree::updateTextures()
{
if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_AREA))
{
- setDebugText(llformat("%4.0f", fsqrtf(mPixelArea)));
+ setDebugText(llformat("%4.0f", (F32) sqrt(mPixelArea)));
}
mTreeImagep->addTextureStats(mPixelArea);
}
@@ -525,11 +525,11 @@ BOOL LLVOTree::updateGeometry(LLDrawable *drawable)
if(mTrunkLOD >= sMAX_NUM_TREE_LOD_LEVELS) //do not display the tree.
{
mReferenceBuffer = NULL ;
- mDrawable->getFace(0)->mVertexBuffer = NULL ;
+ mDrawable->getFace(0)->setVertexBuffer(NULL);
return TRUE ;
}
- if (mReferenceBuffer.isNull() || mDrawable->getFace(0)->mVertexBuffer.isNull())
+ if (mReferenceBuffer.isNull() || !mDrawable->getFace(0)->getVertexBuffer())
{
const F32 SRR3 = 0.577350269f; // sqrt(1/3)
const F32 SRR2 = 0.707106781f; // sqrt(1/2)
@@ -863,7 +863,7 @@ BOOL LLVOTree::updateGeometry(LLDrawable *drawable)
if (gSavedSettings.getBOOL("RenderAnimateTrees"))
{
- mDrawable->getFace(0)->mVertexBuffer = mReferenceBuffer;
+ mDrawable->getFace(0)->setVertexBuffer(mReferenceBuffer);
}
else
{
@@ -921,8 +921,9 @@ void LLVOTree::updateMesh()
calcNumVerts(vert_count, index_count, mTrunkLOD, stop_depth, mDepth, mTrunkDepth, mBranches);
LLFace* facep = mDrawable->getFace(0);
- facep->mVertexBuffer = new LLVertexBuffer(LLDrawPoolTree::VERTEX_DATA_MASK, GL_STATIC_DRAW_ARB);
- facep->mVertexBuffer->allocateBuffer(vert_count, index_count, TRUE);
+ LLVertexBuffer* buff = new LLVertexBuffer(LLDrawPoolTree::VERTEX_DATA_MASK, GL_STATIC_DRAW_ARB);
+ buff->allocateBuffer(vert_count, index_count, TRUE);
+ facep->setVertexBuffer(buff);
LLStrider<LLVector3> vertices;
LLStrider<LLVector3> normals;
@@ -930,16 +931,15 @@ void LLVOTree::updateMesh()
LLStrider<U16> indices;
U16 idx_offset = 0;
- facep->mVertexBuffer->getVertexStrider(vertices);
- facep->mVertexBuffer->getNormalStrider(normals);
- facep->mVertexBuffer->getTexCoord0Strider(tex_coords);
- facep->mVertexBuffer->getIndexStrider(indices);
+ buff->getVertexStrider(vertices);
+ buff->getNormalStrider(normals);
+ buff->getTexCoord0Strider(tex_coords);
+ buff->getIndexStrider(indices);
genBranchPipeline(vertices, normals, tex_coords, indices, idx_offset, scale_mat, mTrunkLOD, stop_depth, mDepth, mTrunkDepth, 1.0, mTwist, droop, mBranches, alpha);
mReferenceBuffer->setBuffer(0);
- facep->mVertexBuffer->setBuffer(0);
-
+ buff->setBuffer(0);
}
void LLVOTree::appendMesh(LLStrider<LLVector3>& vertices,
@@ -1260,7 +1260,7 @@ void LLVOTree::updateRadius()
mDrawable->setRadius(32.0f);
}
-void LLVOTree::updateSpatialExtents(LLVector3& newMin, LLVector3& newMax)
+void LLVOTree::updateSpatialExtents(LLVector4a& newMin, LLVector4a& newMax)
{
F32 radius = getScale().length()*0.05f;
LLVector3 center = getRenderPosition();
@@ -1270,9 +1270,11 @@ void LLVOTree::updateSpatialExtents(LLVector3& newMin, LLVector3& newMax)
center += LLVector3(0, 0, size.mV[2]) * getRotation();
- newMin.set(center-size);
- newMax.set(center+size);
- mDrawable->setPositionGroup(center);
+ newMin.load3((center-size).mV);
+ newMax.load3((center+size).mV);
+ LLVector4a pos;
+ pos.load3(center.mV);
+ mDrawable->setPositionGroup(pos);
}
BOOL LLVOTree::lineSegmentIntersect(const LLVector3& start, const LLVector3& end, S32 face, BOOL pick_transparent, S32 *face_hitp,
@@ -1285,8 +1287,13 @@ BOOL LLVOTree::lineSegmentIntersect(const LLVector3& start, const LLVector3& end
return FALSE;
}
- const LLVector3* ext = mDrawable->getSpatialExtents();
+ const LLVector4a* exta = mDrawable->getSpatialExtents();
+ //VECTORIZE THIS
+ LLVector3 ext[2];
+ ext[0].set(exta[0].getF32ptr());
+ ext[1].set(exta[1].getF32ptr());
+
LLVector3 center = (ext[1]+ext[0])*0.5f;
LLVector3 size = (ext[1]-ext[0]);
@@ -1323,7 +1330,7 @@ U32 LLVOTree::getPartitionType() const
}
LLTreePartition::LLTreePartition()
-: LLSpatialPartition(0, FALSE, 0)
+: LLSpatialPartition(0, FALSE, GL_DYNAMIC_DRAW_ARB)
{
mDrawableType = LLPipeline::RENDER_TYPE_TREE;
mPartitionType = LLViewerRegion::PARTITION_TREE;
diff --git a/indra/newview/llvotree.h b/indra/newview/llvotree.h
index fd0ebdf8e2..1e1deede26 100644
--- a/indra/newview/llvotree.h
+++ b/indra/newview/llvotree.h
@@ -68,7 +68,7 @@ public:
/*virtual*/ LLDrawable* createDrawable(LLPipeline *pipeline);
/*virtual*/ BOOL updateGeometry(LLDrawable *drawable);
- /*virtual*/ void updateSpatialExtents(LLVector3 &min, LLVector3 &max);
+ /*virtual*/ void updateSpatialExtents(LLVector4a &min, LLVector4a &max);
virtual U32 getPartitionType() const;
diff --git a/indra/newview/llvovolume.cpp b/indra/newview/llvovolume.cpp
index a207d3e050..43d8b9d356 100644
--- a/indra/newview/llvovolume.cpp
+++ b/indra/newview/llvovolume.cpp
@@ -1,4009 +1,4679 @@
-/**
- * @file llvovolume.cpp
- * @brief LLVOVolume class implementation
- *
- * $LicenseInfo:firstyear=2001&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-// A "volume" is a box, cylinder, sphere, or other primitive shape.
-
-#include "llviewerprecompiledheaders.h"
-
-#include "llvovolume.h"
-
-#include "llviewercontrol.h"
-#include "lldir.h"
-#include "llflexibleobject.h"
-#include "llmaterialtable.h"
-#include "llprimitive.h"
-#include "llvolume.h"
-#include "llvolumemgr.h"
-#include "llvolumemessage.h"
-#include "material_codes.h"
-#include "message.h"
-#include "llpluginclassmedia.h" // for code in the mediaEvent handler
-#include "object_flags.h"
-#include "llagentconstants.h"
-#include "lldrawable.h"
-#include "lldrawpoolbump.h"
-#include "llface.h"
-#include "llspatialpartition.h"
-#include "llhudmanager.h"
-#include "llflexibleobject.h"
-#include "llsky.h"
-#include "lltexturefetch.h"
-#include "llviewercamera.h"
-#include "llviewertexturelist.h"
-#include "llviewerregion.h"
-#include "llviewertextureanim.h"
-#include "llworld.h"
-#include "llselectmgr.h"
-#include "pipeline.h"
-#include "llsdutil.h"
-#include "llmediaentry.h"
-#include "llmediadataclient.h"
-#include "llagent.h"
-#include "llviewermediafocus.h"
-
-const S32 MIN_QUIET_FRAMES_COALESCE = 30;
-const F32 FORCE_SIMPLE_RENDER_AREA = 512.f;
-const F32 FORCE_CULL_AREA = 8.f;
-const F32 MAX_LOD_DISTANCE = 24.f;
-
-
-BOOL gAnimateTextures = TRUE;
-//extern BOOL gHideSelectedObjects;
-
-F32 LLVOVolume::sLODFactor = 1.f;
-F32 LLVOVolume::sLODSlopDistanceFactor = 0.5f; //Changing this to zero, effectively disables the LOD transition slop
-F32 LLVOVolume::sDistanceFactor = 1.0f;
-S32 LLVOVolume::sNumLODChanges = 0;
-LLPointer<LLObjectMediaDataClient> LLVOVolume::sObjectMediaClient = NULL;
-LLPointer<LLObjectMediaNavigateClient> LLVOVolume::sObjectMediaNavigateClient = NULL;
-
-static LLFastTimer::DeclareTimer FTM_GEN_TRIANGLES("Generate Triangles");
-static LLFastTimer::DeclareTimer FTM_GEN_VOLUME("Generate Volumes");
-
-// Implementation class of LLMediaDataClientObject. See llmediadataclient.h
-class LLMediaDataClientObjectImpl : public LLMediaDataClientObject
-{
-public:
- LLMediaDataClientObjectImpl(LLVOVolume *obj, bool isNew) : mObject(obj), mNew(isNew)
- {
- mObject->addMDCImpl();
- }
- ~LLMediaDataClientObjectImpl()
- {
- mObject->removeMDCImpl();
- }
-
- virtual U8 getMediaDataCount() const
- { return mObject->getNumTEs(); }
-
- virtual LLSD getMediaDataLLSD(U8 index) const
- {
- LLSD result;
- LLTextureEntry *te = mObject->getTE(index);
- if (NULL != te)
- {
- llassert((te->getMediaData() != NULL) == te->hasMedia());
- if (te->getMediaData() != NULL)
- {
- result = te->getMediaData()->asLLSD();
- // XXX HACK: workaround bug in asLLSD() where whitelist is not set properly
- // See DEV-41949
- if (!result.has(LLMediaEntry::WHITELIST_KEY))
- {
- result[LLMediaEntry::WHITELIST_KEY] = LLSD::emptyArray();
- }
- }
- }
- return result;
- }
- virtual bool isCurrentMediaUrl(U8 index, const std::string &url) const
- {
- LLTextureEntry *te = mObject->getTE(index);
- if (te)
- {
- if (te->getMediaData())
- {
- return (te->getMediaData()->getCurrentURL() == url);
- }
- }
- return url.empty();
- }
-
- virtual LLUUID getID() const
- { return mObject->getID(); }
-
- virtual void mediaNavigateBounceBack(U8 index)
- { mObject->mediaNavigateBounceBack(index); }
-
- virtual bool hasMedia() const
- { return mObject->hasMedia(); }
-
- virtual void updateObjectMediaData(LLSD const &data, const std::string &version_string)
- { mObject->updateObjectMediaData(data, version_string); }
-
- virtual F64 getMediaInterest() const
- {
- F64 interest = mObject->getTotalMediaInterest();
- if (interest < (F64)0.0)
- {
- // media interest not valid yet, try pixel area
- interest = mObject->getPixelArea();
- // HACK: force recalculation of pixel area if interest is the "magic default" of 1024.
- if (interest == 1024.f)
- {
- const_cast<LLVOVolume*>(static_cast<LLVOVolume*>(mObject))->setPixelAreaAndAngle(gAgent);
- interest = mObject->getPixelArea();
- }
- }
- return interest;
- }
-
- virtual bool isInterestingEnough() const
- {
- return LLViewerMedia::isInterestingEnough(mObject, getMediaInterest());
- }
-
- virtual std::string getCapabilityUrl(const std::string &name) const
- { return mObject->getRegion()->getCapability(name); }
-
- virtual bool isDead() const
- { return mObject->isDead(); }
-
- virtual U32 getMediaVersion() const
- { return LLTextureEntry::getVersionFromMediaVersionString(mObject->getMediaURL()); }
-
- virtual bool isNew() const
- { return mNew; }
-
-private:
- LLPointer<LLVOVolume> mObject;
- bool mNew;
-};
-
-
-LLVOVolume::LLVOVolume(const LLUUID &id, const LLPCode pcode, LLViewerRegion *regionp)
- : LLViewerObject(id, pcode, regionp),
- mVolumeImpl(NULL)
-{
- mTexAnimMode = 0;
- mRelativeXform.setIdentity();
- mRelativeXformInvTrans.setIdentity();
-
- mFaceMappingChanged = FALSE;
- mLOD = MIN_LOD;
- mTextureAnimp = NULL;
- mVolumeChanged = FALSE;
- mVObjRadius = LLVector3(1,1,0.5f).length();
- mNumFaces = 0;
- mLODChanged = FALSE;
- mSculptChanged = FALSE;
- mSpotLightPriority = 0.f;
-
- mMediaImplList.resize(getNumTEs());
- mLastFetchedMediaVersion = -1;
- mIndexInTex = 0;
- mMDCImplCount = 0;
-}
-
-LLVOVolume::~LLVOVolume()
-{
- delete mTextureAnimp;
- mTextureAnimp = NULL;
- delete mVolumeImpl;
- mVolumeImpl = NULL;
-
- if(!mMediaImplList.empty())
- {
- for(U32 i = 0 ; i < mMediaImplList.size() ; i++)
- {
- if(mMediaImplList[i].notNull())
- {
- mMediaImplList[i]->removeObject(this) ;
- }
- }
- }
-}
-
-void LLVOVolume::markDead()
-{
- if (!mDead)
- {
- if(getMDCImplCount() > 0)
- {
- LLMediaDataClientObject::ptr_t obj = new LLMediaDataClientObjectImpl(const_cast<LLVOVolume*>(this), false);
- if (sObjectMediaClient) sObjectMediaClient->removeFromQueue(obj);
- if (sObjectMediaNavigateClient) sObjectMediaNavigateClient->removeFromQueue(obj);
- }
-
- // Detach all media impls from this object
- for(U32 i = 0 ; i < mMediaImplList.size() ; i++)
- {
- removeMediaImpl(i);
- }
-
- if (mSculptTexture.notNull())
- {
- mSculptTexture->removeVolume(this);
- }
- }
-
- LLViewerObject::markDead();
-}
-
-
-// static
-void LLVOVolume::initClass()
-{
- // gSavedSettings better be around
- if (gSavedSettings.getBOOL("PrimMediaMasterEnabled"))
- {
- const F32 queue_timer_delay = gSavedSettings.getF32("PrimMediaRequestQueueDelay");
- const F32 retry_timer_delay = gSavedSettings.getF32("PrimMediaRetryTimerDelay");
- const U32 max_retries = gSavedSettings.getU32("PrimMediaMaxRetries");
- const U32 max_sorted_queue_size = gSavedSettings.getU32("PrimMediaMaxSortedQueueSize");
- const U32 max_round_robin_queue_size = gSavedSettings.getU32("PrimMediaMaxRoundRobinQueueSize");
- sObjectMediaClient = new LLObjectMediaDataClient(queue_timer_delay, retry_timer_delay, max_retries,
- max_sorted_queue_size, max_round_robin_queue_size);
- sObjectMediaNavigateClient = new LLObjectMediaNavigateClient(queue_timer_delay, retry_timer_delay,
- max_retries, max_sorted_queue_size, max_round_robin_queue_size);
- }
-}
-
-// static
-void LLVOVolume::cleanupClass()
-{
- sObjectMediaClient = NULL;
- sObjectMediaNavigateClient = NULL;
-}
-
-U32 LLVOVolume::processUpdateMessage(LLMessageSystem *mesgsys,
- void **user_data,
- U32 block_num, EObjectUpdateType update_type,
- LLDataPacker *dp)
-{
- LLColor4U color;
- const S32 teDirtyBits = (TEM_CHANGE_TEXTURE|TEM_CHANGE_COLOR|TEM_CHANGE_MEDIA);
-
- // Do base class updates...
- U32 retval = LLViewerObject::processUpdateMessage(mesgsys, user_data, block_num, update_type, dp);
-
- LLUUID sculpt_id;
- U8 sculpt_type = 0;
- if (isSculpted())
- {
- LLSculptParams *sculpt_params = (LLSculptParams *)getParameterEntry(LLNetworkData::PARAMS_SCULPT);
- sculpt_id = sculpt_params->getSculptTexture();
- sculpt_type = sculpt_params->getSculptType();
- }
-
- if (!dp)
- {
- if (update_type == OUT_FULL)
- {
- ////////////////////////////////
- //
- // Unpack texture animation data
- //
- //
-
- if (mesgsys->getSizeFast(_PREHASH_ObjectData, block_num, _PREHASH_TextureAnim))
- {
- if (!mTextureAnimp)
- {
- mTextureAnimp = new LLViewerTextureAnim();
- }
- else
- {
- if (!(mTextureAnimp->mMode & LLTextureAnim::SMOOTH))
- {
- mTextureAnimp->reset();
- }
- }
- mTexAnimMode = 0;
- mTextureAnimp->unpackTAMessage(mesgsys, block_num);
- }
- else
- {
- if (mTextureAnimp)
- {
- delete mTextureAnimp;
- mTextureAnimp = NULL;
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- mTexAnimMode = 0;
- }
- }
-
- // Unpack volume data
- LLVolumeParams volume_params;
- LLVolumeMessage::unpackVolumeParams(&volume_params, mesgsys, _PREHASH_ObjectData, block_num);
- volume_params.setSculptID(sculpt_id, sculpt_type);
-
- if (setVolume(volume_params, 0))
- {
- markForUpdate(TRUE);
- }
- }
-
- // Sigh, this needs to be done AFTER the volume is set as well, otherwise bad stuff happens...
- ////////////////////////////
- //
- // Unpack texture entry data
- //
- S32 result = unpackTEMessage(mesgsys, _PREHASH_ObjectData, block_num);
- if (result & teDirtyBits)
- {
- updateTEData();
- }
- if (result & TEM_CHANGE_MEDIA)
- {
- retval |= MEDIA_FLAGS_CHANGED;
- }
- }
- else
- {
- // CORY TO DO: Figure out how to get the value here
- if (update_type != OUT_TERSE_IMPROVED)
- {
- LLVolumeParams volume_params;
- BOOL res = LLVolumeMessage::unpackVolumeParams(&volume_params, *dp);
- if (!res)
- {
- llwarns << "Bogus volume parameters in object " << getID() << llendl;
- llwarns << getRegion()->getOriginGlobal() << llendl;
- }
-
- volume_params.setSculptID(sculpt_id, sculpt_type);
-
- if (setVolume(volume_params, 0))
- {
- markForUpdate(TRUE);
- }
- S32 res2 = unpackTEMessage(*dp);
- if (TEM_INVALID == res2)
- {
- // There's something bogus in the data that we're unpacking.
- dp->dumpBufferToLog();
- llwarns << "Flushing cache files" << llendl;
-
- if(LLVOCache::hasInstance() && getRegion())
- {
- LLVOCache::getInstance()->removeEntry(getRegion()->getHandle()) ;
- }
-
- llwarns << "Bogus TE data in " << getID() << llendl;
- }
- else
- {
- if (res2 & teDirtyBits)
- {
- updateTEData();
- }
- if (res2 & TEM_CHANGE_MEDIA)
- {
- retval |= MEDIA_FLAGS_CHANGED;
- }
- }
-
- U32 value = dp->getPassFlags();
-
- if (value & 0x40)
- {
- if (!mTextureAnimp)
- {
- mTextureAnimp = new LLViewerTextureAnim();
- }
- else
- {
- if (!(mTextureAnimp->mMode & LLTextureAnim::SMOOTH))
- {
- mTextureAnimp->reset();
- }
- }
- mTexAnimMode = 0;
- mTextureAnimp->unpackTAMessage(*dp);
- }
- else if (mTextureAnimp)
- {
- delete mTextureAnimp;
- mTextureAnimp = NULL;
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- mTexAnimMode = 0;
- }
- }
- else
- {
- S32 texture_length = mesgsys->getSizeFast(_PREHASH_ObjectData, block_num, _PREHASH_TextureEntry);
- if (texture_length)
- {
- U8 tdpbuffer[1024];
- LLDataPackerBinaryBuffer tdp(tdpbuffer, 1024);
- mesgsys->getBinaryDataFast(_PREHASH_ObjectData, _PREHASH_TextureEntry, tdpbuffer, 0, block_num);
- S32 result = unpackTEMessage(tdp);
- if (result & teDirtyBits)
- {
- updateTEData();
- }
- if (result & TEM_CHANGE_MEDIA)
- {
- retval |= MEDIA_FLAGS_CHANGED;
- }
- }
- }
- }
- if (retval & (MEDIA_URL_REMOVED | MEDIA_URL_ADDED | MEDIA_URL_UPDATED | MEDIA_FLAGS_CHANGED))
- {
- // If only the media URL changed, and it isn't a media version URL,
- // ignore it
- if ( ! ( retval & (MEDIA_URL_ADDED | MEDIA_URL_UPDATED) &&
- mMedia && ! mMedia->mMediaURL.empty() &&
- ! LLTextureEntry::isMediaVersionString(mMedia->mMediaURL) ) )
- {
- // If the media changed at all, request new media data
- LL_DEBUGS("MediaOnAPrim") << "Media update: " << getID() << ": retval=" << retval << " Media URL: " <<
- ((mMedia) ? mMedia->mMediaURL : std::string("")) << LL_ENDL;
- requestMediaDataUpdate(retval & MEDIA_FLAGS_CHANGED);
- }
- else {
- LL_INFOS("MediaOnAPrim") << "Ignoring media update for: " << getID() << " Media URL: " <<
- ((mMedia) ? mMedia->mMediaURL : std::string("")) << LL_ENDL;
- }
- }
- // ...and clean up any media impls
- cleanUpMediaImpls();
-
- return retval;
-}
-
-
-void LLVOVolume::animateTextures()
-{
- F32 off_s = 0.f, off_t = 0.f, scale_s = 1.f, scale_t = 1.f, rot = 0.f;
- S32 result = mTextureAnimp->animateTextures(off_s, off_t, scale_s, scale_t, rot);
-
- if (result)
- {
- if (!mTexAnimMode)
- {
- mFaceMappingChanged = TRUE;
- gPipeline.markTextured(mDrawable);
- }
- mTexAnimMode = result | mTextureAnimp->mMode;
-
- S32 start=0, end=mDrawable->getNumFaces()-1;
- if (mTextureAnimp->mFace >= 0 && mTextureAnimp->mFace <= end)
- {
- start = end = mTextureAnimp->mFace;
- }
-
- for (S32 i = start; i <= end; i++)
- {
- LLFace* facep = mDrawable->getFace(i);
- if(facep->getVirtualSize() <= MIN_TEX_ANIM_SIZE && facep->mTextureMatrix) continue;
-
- const LLTextureEntry* te = facep->getTextureEntry();
-
- if (!te)
- {
- continue;
- }
-
- if (!(result & LLViewerTextureAnim::ROTATE))
- {
- te->getRotation(&rot);
- }
- if (!(result & LLViewerTextureAnim::TRANSLATE))
- {
- te->getOffset(&off_s,&off_t);
- }
- if (!(result & LLViewerTextureAnim::SCALE))
- {
- te->getScale(&scale_s, &scale_t);
- }
-
- if (!facep->mTextureMatrix)
- {
- facep->mTextureMatrix = new LLMatrix4();
- }
-
- LLMatrix4& tex_mat = *facep->mTextureMatrix;
- tex_mat.setIdentity();
- LLVector3 trans ;
-
- if(facep->isAtlasInUse())
- {
- //
- //if use atlas for animated texture
- //apply the following transform to the animation matrix.
- //
-
- F32 tcoord_xoffset = 0.f ;
- F32 tcoord_yoffset = 0.f ;
- F32 tcoord_xscale = 1.f ;
- F32 tcoord_yscale = 1.f ;
- if(facep->isAtlasInUse())
- {
- const LLVector2* tmp = facep->getTexCoordOffset() ;
- tcoord_xoffset = tmp->mV[0] ;
- tcoord_yoffset = tmp->mV[1] ;
-
- tmp = facep->getTexCoordScale() ;
- tcoord_xscale = tmp->mV[0] ;
- tcoord_yscale = tmp->mV[1] ;
- }
- trans.set(LLVector3(tcoord_xoffset + tcoord_xscale * (off_s+0.5f), tcoord_yoffset + tcoord_yscale * (off_t+0.5f), 0.f));
-
- tex_mat.translate(LLVector3(-(tcoord_xoffset + tcoord_xscale * 0.5f), -(tcoord_yoffset + tcoord_yscale * 0.5f), 0.f));
- }
- else //non atlas
- {
- trans.set(LLVector3(off_s+0.5f, off_t+0.5f, 0.f));
- tex_mat.translate(LLVector3(-0.5f, -0.5f, 0.f));
- }
-
- LLVector3 scale(scale_s, scale_t, 1.f);
- LLQuaternion quat;
- quat.setQuat(rot, 0, 0, -1.f);
-
- tex_mat.rotate(quat);
-
- LLMatrix4 mat;
- mat.initAll(scale, LLQuaternion(), LLVector3());
- tex_mat *= mat;
-
- tex_mat.translate(trans);
- }
- }
- else
- {
- if (mTexAnimMode && mTextureAnimp->mRate == 0)
- {
- U8 start, count;
-
- if (mTextureAnimp->mFace == -1)
- {
- start = 0;
- count = getNumTEs();
- }
- else
- {
- start = (U8) mTextureAnimp->mFace;
- count = 1;
- }
-
- for (S32 i = start; i < start + count; i++)
- {
- if (mTexAnimMode & LLViewerTextureAnim::TRANSLATE)
- {
- setTEOffset(i, mTextureAnimp->mOffS, mTextureAnimp->mOffT);
- }
- if (mTexAnimMode & LLViewerTextureAnim::SCALE)
- {
- setTEScale(i, mTextureAnimp->mScaleS, mTextureAnimp->mScaleT);
- }
- if (mTexAnimMode & LLViewerTextureAnim::ROTATE)
- {
- setTERotation(i, mTextureAnimp->mRot);
- }
- }
-
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- mTexAnimMode = 0;
- }
- }
-}
-BOOL LLVOVolume::idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time)
-{
- LLViewerObject::idleUpdate(agent, world, time);
-
- static LLFastTimer::DeclareTimer ftm("Volume");
- LLFastTimer t(ftm);
-
- if (mDead || mDrawable.isNull())
- {
- return TRUE;
- }
-
- ///////////////////////
- //
- // Do texture animation stuff
- //
-
- if (mTextureAnimp && gAnimateTextures)
- {
- animateTextures();
- }
-
- // Dispatch to implementation
- if (mVolumeImpl)
- {
- mVolumeImpl->doIdleUpdate(agent, world, time);
- }
-
- const S32 MAX_ACTIVE_OBJECT_QUIET_FRAMES = 40;
-
- if (mDrawable->isActive())
- {
- if (mDrawable->isRoot() &&
- mDrawable->mQuietCount++ > MAX_ACTIVE_OBJECT_QUIET_FRAMES &&
- (!mDrawable->getParent() || !mDrawable->getParent()->isActive()))
- {
- mDrawable->makeStatic();
- }
- }
-
- return TRUE;
-}
-
-void LLVOVolume::updateTextures()
-{
- const F32 TEXTURE_AREA_REFRESH_TIME = 5.f; // seconds
- if (mTextureUpdateTimer.getElapsedTimeF32() > TEXTURE_AREA_REFRESH_TIME)
- {
- updateTextureVirtualSize();
- }
-}
-
-BOOL LLVOVolume::isVisible() const
-{
- if(mDrawable.notNull() && mDrawable->isVisible())
- {
- return TRUE ;
- }
-
- if(isAttachment())
- {
- LLViewerObject* objp = (LLViewerObject*)getParent() ;
- while(objp && !objp->isAvatar())
- {
- objp = (LLViewerObject*)objp->getParent() ;
- }
-
- return objp && objp->mDrawable.notNull() && objp->mDrawable->isVisible() ;
- }
-
- return FALSE ;
-}
-
-void LLVOVolume::updateTextureVirtualSize()
-{
- // Update the pixel area of all faces
-
- if(!isVisible())
- {
- return ;
- }
-
- if (!gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_SIMPLE))
- {
- return;
- }
-
- static LLCachedControl<bool> dont_load_textures(gSavedSettings,"TextureDisable");
-
- if (dont_load_textures || LLAppViewer::getTextureFetch()->mDebugPause) // || !mDrawable->isVisible())
- {
- return;
- }
-
- mTextureUpdateTimer.reset();
-
- F32 old_area = mPixelArea;
- mPixelArea = 0.f;
-
- const S32 num_faces = mDrawable->getNumFaces();
- F32 min_vsize=999999999.f, max_vsize=0.f;
- LLViewerCamera* camera = LLViewerCamera::getInstance();
- for (S32 i = 0; i < num_faces; i++)
- {
- LLFace* face = mDrawable->getFace(i);
- const LLTextureEntry *te = face->getTextureEntry();
- LLViewerTexture *imagep = face->getTexture();
- if (!imagep || !te ||
- face->mExtents[0] == face->mExtents[1])
- {
- continue;
- }
-
- F32 vsize;
- F32 old_size = face->getVirtualSize();
-
- if (isHUDAttachment())
- {
- F32 area = (F32) camera->getScreenPixelArea();
- vsize = area;
- imagep->setBoostLevel(LLViewerTexture::BOOST_HUD);
- face->setPixelArea(area); // treat as full screen
- face->setVirtualSize(vsize);
- }
- else
- {
- vsize = face->getTextureVirtualSize();
- }
-
- mPixelArea = llmax(mPixelArea, face->getPixelArea());
-
- if (face->mTextureMatrix != NULL)
- {
- if ((vsize < MIN_TEX_ANIM_SIZE && old_size > MIN_TEX_ANIM_SIZE) ||
- (vsize > MIN_TEX_ANIM_SIZE && old_size < MIN_TEX_ANIM_SIZE))
- {
- gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_TCOORD, FALSE);
- }
- }
-
- if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_AREA))
- {
- if (vsize < min_vsize) min_vsize = vsize;
- if (vsize > max_vsize) max_vsize = vsize;
- }
- else if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_PRIORITY))
- {
- LLViewerFetchedTexture* img = LLViewerTextureManager::staticCastToFetchedTexture(imagep) ;
- if(img)
- {
- F32 pri = img->getDecodePriority();
- pri = llmax(pri, 0.0f);
- if (pri < min_vsize) min_vsize = pri;
- if (pri > max_vsize) max_vsize = pri;
- }
- }
- else if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_FACE_AREA))
- {
- F32 pri = mPixelArea;
- if (pri < min_vsize) min_vsize = pri;
- if (pri > max_vsize) max_vsize = pri;
- }
- }
-
- if (isSculpted())
- {
- LLSculptParams *sculpt_params = (LLSculptParams *)getParameterEntry(LLNetworkData::PARAMS_SCULPT);
- LLUUID id = sculpt_params->getSculptTexture();
-
- updateSculptTexture();
-
- if (mSculptTexture.notNull())
- {
- mSculptTexture->setBoostLevel(llmax((S32)mSculptTexture->getBoostLevel(),
- (S32)LLViewerTexture::BOOST_SCULPTED));
- mSculptTexture->setForSculpt() ;
-
- if(!mSculptTexture->isCachedRawImageReady())
- {
- S32 lod = llmin(mLOD, 3);
- F32 lodf = ((F32)(lod + 1.0f)/4.f);
- F32 tex_size = lodf * LLViewerTexture::sMaxSculptRez ;
- mSculptTexture->addTextureStats(2.f * tex_size * tex_size, FALSE);
-
- //if the sculpty very close to the view point, load first
- {
- LLVector3 lookAt = getPositionAgent() - camera->getOrigin();
- F32 dist = lookAt.normVec() ;
- F32 cos_angle_to_view_dir = lookAt * camera->getXAxis() ;
- mSculptTexture->setAdditionalDecodePriority(0.8f * LLFace::calcImportanceToCamera(cos_angle_to_view_dir, dist)) ;
- }
- }
-
- S32 texture_discard = mSculptTexture->getDiscardLevel(); //try to match the texture
- S32 current_discard = getVolume() ? getVolume()->getSculptLevel() : -2 ;
-
- if (texture_discard >= 0 && //texture has some data available
- (texture_discard < current_discard || //texture has more data than last rebuild
- current_discard < 0)) //no previous rebuild
- {
- gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, FALSE);
- mSculptChanged = TRUE;
- }
-
- if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_SCULPTED))
- {
- setDebugText(llformat("T%d C%d V%d\n%dx%d",
- texture_discard, current_discard, getVolume()->getSculptLevel(),
- mSculptTexture->getHeight(), mSculptTexture->getWidth()));
- }
- }
- }
-
- if (getLightTextureID().notNull())
- {
- LLLightImageParams* params = (LLLightImageParams*) getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
- LLUUID id = params->getLightTexture();
- mLightTexture = LLViewerTextureManager::getFetchedTexture(id);
- if (mLightTexture.notNull())
- {
- F32 rad = getLightRadius();
- mLightTexture->addTextureStats(gPipeline.calcPixelArea(getPositionAgent(),
- LLVector3(rad,rad,rad),
- *camera));
- }
- }
-
- if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_AREA))
- {
- setDebugText(llformat("%.0f:%.0f", fsqrtf(min_vsize),fsqrtf(max_vsize)));
- }
- else if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_PRIORITY))
- {
- setDebugText(llformat("%.0f:%.0f", fsqrtf(min_vsize),fsqrtf(max_vsize)));
- }
- else if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_FACE_AREA))
- {
- setDebugText(llformat("%.0f:%.0f", fsqrtf(min_vsize),fsqrtf(max_vsize)));
- }
-
- if (mPixelArea == 0)
- { //flexi phasing issues make this happen
- mPixelArea = old_area;
- }
-}
-
-BOOL LLVOVolume::isActive() const
-{
- return !mStatic || mTextureAnimp || (mVolumeImpl && mVolumeImpl->isActive());
-}
-
-BOOL LLVOVolume::setMaterial(const U8 material)
-{
- BOOL res = LLViewerObject::setMaterial(material);
-
- return res;
-}
-
-void LLVOVolume::setTexture(const S32 face)
-{
- llassert(face < getNumTEs());
- gGL.getTexUnit(0)->bind(getTEImage(face));
-}
-
-void LLVOVolume::setScale(const LLVector3 &scale, BOOL damped)
-{
- if (scale != getScale())
- {
- // store local radius
- LLViewerObject::setScale(scale);
-
- if (mVolumeImpl)
- {
- mVolumeImpl->onSetScale(scale, damped);
- }
-
- updateRadius();
-
- //since drawable transforms do not include scale, changing volume scale
- //requires an immediate rebuild of volume verts.
- gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_POSITION, TRUE);
- }
-}
-
-LLFace* LLVOVolume::addFace(S32 f)
-{
- const LLTextureEntry* te = getTE(f);
- LLViewerTexture* imagep = getTEImage(f);
- return mDrawable->addFace(te, imagep);
-}
-
-LLDrawable *LLVOVolume::createDrawable(LLPipeline *pipeline)
-{
- pipeline->allocDrawable(this);
-
- mDrawable->setRenderType(LLPipeline::RENDER_TYPE_VOLUME);
-
- S32 max_tes_to_set = getNumTEs();
- for (S32 i = 0; i < max_tes_to_set; i++)
- {
- addFace(i);
- }
- mNumFaces = max_tes_to_set;
-
- if (isAttachment())
- {
- mDrawable->makeActive();
- }
-
- if (getIsLight())
- {
- // Add it to the pipeline mLightSet
- gPipeline.setLight(mDrawable, TRUE);
- }
-
- updateRadius();
- bool force_update = true; // avoid non-alpha mDistance update being optimized away
- mDrawable->updateDistance(*LLViewerCamera::getInstance(), force_update);
-
- return mDrawable;
-}
-
-BOOL LLVOVolume::setVolume(const LLVolumeParams &volume_params, const S32 detail, bool unique_volume)
-{
- // Check if we need to change implementations
- bool is_flexible = (volume_params.getPathParams().getCurveType() == LL_PCODE_PATH_FLEXIBLE);
- if (is_flexible)
- {
- setParameterEntryInUse(LLNetworkData::PARAMS_FLEXIBLE, TRUE, false);
- if (!mVolumeImpl)
- {
- LLFlexibleObjectData* data = (LLFlexibleObjectData*)getParameterEntry(LLNetworkData::PARAMS_FLEXIBLE);
- mVolumeImpl = new LLVolumeImplFlexible(this, data);
- }
- }
- else
- {
- // Mark the parameter not in use
- setParameterEntryInUse(LLNetworkData::PARAMS_FLEXIBLE, FALSE, false);
- if (mVolumeImpl)
- {
- delete mVolumeImpl;
- mVolumeImpl = NULL;
- if (mDrawable.notNull())
- {
- // Undo the damage we did to this matrix
- mDrawable->updateXform(FALSE);
- }
- }
- }
-
- if ((LLPrimitive::setVolume(volume_params, mLOD, (mVolumeImpl && mVolumeImpl->isVolumeUnique()))) || mSculptChanged)
- {
- mFaceMappingChanged = TRUE;
-
- if (mVolumeImpl)
- {
- mVolumeImpl->onSetVolume(volume_params, detail);
- }
-
- updateSculptTexture();
-
- if (isSculpted())
- {
- updateSculptTexture();
-
- if (mSculptTexture.notNull())
- {
- sculpt();
- }
- }
-
- return TRUE;
- }
- return FALSE;
-}
-
-void LLVOVolume::updateSculptTexture()
-{
- LLPointer<LLViewerFetchedTexture> old_sculpt = mSculptTexture;
-
- if (isSculpted())
- {
- LLSculptParams *sculpt_params = (LLSculptParams *)getParameterEntry(LLNetworkData::PARAMS_SCULPT);
- LLUUID id = sculpt_params->getSculptTexture();
- if (id.notNull())
- {
- mSculptTexture = LLViewerTextureManager::getFetchedTexture(id, TRUE, LLViewerTexture::BOOST_NONE, LLViewerTexture::LOD_TEXTURE);
- }
- }
- else
- {
- mSculptTexture = NULL;
- }
-
- if (mSculptTexture != old_sculpt)
- {
- if (old_sculpt.notNull())
- {
- old_sculpt->removeVolume(this);
- }
- if (mSculptTexture.notNull())
- {
- mSculptTexture->addVolume(this);
- }
- }
-
-}
-
-// sculpt replaces generate() for sculpted surfaces
-void LLVOVolume::sculpt()
-{
- if (mSculptTexture.notNull())
- {
- U16 sculpt_height = 0;
- U16 sculpt_width = 0;
- S8 sculpt_components = 0;
- const U8* sculpt_data = NULL;
-
- S32 discard_level = mSculptTexture->getDiscardLevel() ;
- LLImageRaw* raw_image = mSculptTexture->getCachedRawImage() ;
-
- S32 max_discard = mSculptTexture->getMaxDiscardLevel();
- if (discard_level > max_discard)
- discard_level = max_discard; // clamp to the best we can do
-
- S32 current_discard = getVolume()->getSculptLevel() ;
- if(current_discard < -2)
- {
- llwarns << "WARNING!!: Current discard of sculpty at " << current_discard
- << " is less than -2." << llendl;
-
- // corrupted volume... don't update the sculpty
- return;
- }
- else if (current_discard > MAX_DISCARD_LEVEL)
- {
- llwarns << "WARNING!!: Current discard of sculpty at " << current_discard
- << " is more than than allowed max of " << MAX_DISCARD_LEVEL << llendl;
-
- // corrupted volume... don't update the sculpty
- return;
- }
-
- if (current_discard == discard_level) // no work to do here
- return;
-
- if(!raw_image)
- {
- llassert(discard_level < 0) ;
-
- sculpt_width = 0;
- sculpt_height = 0;
- sculpt_data = NULL ;
-
- if(LLViewerTextureManager::sTesterp)
- {
- LLViewerTextureManager::sTesterp->updateGrayTextureBinding();
- }
- }
- else
- {
- sculpt_height = raw_image->getHeight();
- sculpt_width = raw_image->getWidth();
- sculpt_components = raw_image->getComponents();
-
- sculpt_data = raw_image->getData();
-
- if(LLViewerTextureManager::sTesterp)
- {
- mSculptTexture->updateBindStatsForTester() ;
- }
- }
- getVolume()->sculpt(sculpt_width, sculpt_height, sculpt_components, sculpt_data, discard_level);
-
- //notify rebuild any other VOVolumes that reference this sculpty volume
- for (S32 i = 0; i < mSculptTexture->getNumVolumes(); ++i)
- {
- LLVOVolume* volume = (*(mSculptTexture->getVolumeList()))[i];
- if (volume != this && volume->getVolume() == getVolume())
- {
- gPipeline.markRebuild(volume->mDrawable, LLDrawable::REBUILD_GEOMETRY, FALSE);
- }
- }
- }
-}
-
-S32 LLVOVolume::computeLODDetail(F32 distance, F32 radius)
-{
- S32 cur_detail;
- if (LLPipeline::sDynamicLOD)
- {
- // We've got LOD in the profile, and in the twist. Use radius.
- F32 tan_angle = (LLVOVolume::sLODFactor*radius)/distance;
- cur_detail = LLVolumeLODGroup::getDetailFromTan(llround(tan_angle, 0.01f));
- }
- else
- {
- cur_detail = llclamp((S32) (sqrtf(radius)*LLVOVolume::sLODFactor*4.f), 0, 3);
- }
- return cur_detail;
-}
-
-BOOL LLVOVolume::calcLOD()
-{
- if (mDrawable.isNull())
- {
- return FALSE;
- }
-
- S32 cur_detail = 0;
-
- F32 radius = getVolume()->mLODScaleBias.scaledVec(getScale()).length();
- F32 distance = mDrawable->mDistanceWRTCamera; //llmin(mDrawable->mDistanceWRTCamera, MAX_LOD_DISTANCE);
- distance *= sDistanceFactor;
-
- F32 rampDist = LLVOVolume::sLODFactor * 2;
-
- if (distance < rampDist)
- {
- // Boost LOD when you're REALLY close
- distance *= 1.0f/rampDist;
- distance *= distance;
- distance *= rampDist;
- }
-
- // DON'T Compensate for field of view changing on FOV zoom.
- distance *= F_PI/3.f;
-
- cur_detail = computeLODDetail(llround(distance, 0.01f),
- llround(radius, 0.01f));
-
- if (cur_detail != mLOD)
- {
- mAppAngle = llround((F32) atan2( mDrawable->getRadius(), mDrawable->mDistanceWRTCamera) * RAD_TO_DEG, 0.01f);
- mLOD = cur_detail;
- return TRUE;
- }
- else
- {
- return FALSE;
- }
-}
-
-BOOL LLVOVolume::updateLOD()
-{
- if (mDrawable.isNull())
- {
- return FALSE;
- }
-
- BOOL lod_changed = calcLOD();
-
- if (lod_changed)
- {
- gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, FALSE);
- mLODChanged = TRUE;
- }
-
- lod_changed |= LLViewerObject::updateLOD();
-
- return lod_changed;
-}
-
-BOOL LLVOVolume::setDrawableParent(LLDrawable* parentp)
-{
- if (!LLViewerObject::setDrawableParent(parentp))
- {
- // no change in drawable parent
- return FALSE;
- }
-
- if (!mDrawable->isRoot())
- {
- // rebuild vertices in parent relative space
- gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, TRUE);
-
- if (mDrawable->isActive() && !parentp->isActive())
- {
- parentp->makeActive();
- }
- else if (mDrawable->isStatic() && parentp->isActive())
- {
- mDrawable->makeActive();
- }
- }
-
- return TRUE;
-}
-
-void LLVOVolume::updateFaceFlags()
-{
- for (S32 i = 0; i < getVolume()->getNumFaces(); i++)
- {
- LLFace *face = mDrawable->getFace(i);
- BOOL fullbright = getTE(i)->getFullbright();
- face->clearState(LLFace::FULLBRIGHT | LLFace::HUD_RENDER | LLFace::LIGHT);
-
- if (fullbright || (mMaterial == LL_MCODE_LIGHT))
- {
- face->setState(LLFace::FULLBRIGHT);
- }
- if (mDrawable->isLight())
- {
- face->setState(LLFace::LIGHT);
- }
- if (isHUDAttachment())
- {
- face->setState(LLFace::HUD_RENDER);
- }
- }
-}
-
-BOOL LLVOVolume::setParent(LLViewerObject* parent)
-{
- BOOL ret = FALSE ;
- if (parent != getParent())
- {
- ret = LLViewerObject::setParent(parent);
- if (ret && mDrawable)
- {
- gPipeline.markMoved(mDrawable);
- gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, TRUE);
- }
- }
-
- return ret ;
-}
-
-// NOTE: regenFaces() MUST be followed by genTriangles()!
-void LLVOVolume::regenFaces()
-{
- // remove existing faces
- BOOL count_changed = mNumFaces != getNumTEs();
-
- if (count_changed)
- {
- deleteFaces();
- // add new faces
- mNumFaces = getNumTEs();
- }
-
- for (S32 i = 0; i < mNumFaces; i++)
- {
- LLFace* facep = count_changed ? addFace(i) : mDrawable->getFace(i);
- facep->setTEOffset(i);
- facep->setTexture(getTEImage(i));
- facep->setViewerObject(this);
-
- // If the face had media on it, this will have broken the link between the LLViewerMediaTexture and the face.
- // Re-establish the link.
- if((int)mMediaImplList.size() > i)
- {
- if(mMediaImplList[i])
- {
- LLViewerMediaTexture* media_tex = LLViewerTextureManager::findMediaTexture(mMediaImplList[i]->getMediaTextureID()) ;
- if(media_tex)
- {
- media_tex->addMediaToFace(facep) ;
- }
- }
- }
- }
-
- if (!count_changed)
- {
- updateFaceFlags();
- }
-}
-
-BOOL LLVOVolume::genBBoxes(BOOL force_global)
-{
- BOOL res = TRUE;
-
- LLVector3 min,max;
-
- BOOL rebuild = mDrawable->isState(LLDrawable::REBUILD_VOLUME | LLDrawable::REBUILD_POSITION);
-
- for (S32 i = 0; i < getVolume()->getNumFaces(); i++)
- {
- LLFace *face = mDrawable->getFace(i);
- res &= face->genVolumeBBoxes(*getVolume(), i,
- mRelativeXform, mRelativeXformInvTrans,
- (mVolumeImpl && mVolumeImpl->isVolumeGlobal()) || force_global);
-
- if (rebuild)
- {
- if (i == 0)
- {
- min = face->mExtents[0];
- max = face->mExtents[1];
- }
- else
- {
- for (U32 i = 0; i < 3; i++)
- {
- if (face->mExtents[0].mV[i] < min.mV[i])
- {
- min.mV[i] = face->mExtents[0].mV[i];
- }
- if (face->mExtents[1].mV[i] > max.mV[i])
- {
- max.mV[i] = face->mExtents[1].mV[i];
- }
- }
- }
- }
- }
-
- if (rebuild)
- {
- mDrawable->setSpatialExtents(min,max);
- mDrawable->setPositionGroup((min+max)*0.5f);
- }
-
- updateRadius();
- mDrawable->movePartition();
-
- return res;
-}
-
-void LLVOVolume::preRebuild()
-{
- if (mVolumeImpl != NULL)
- {
- mVolumeImpl->preRebuild();
- }
-}
-
-void LLVOVolume::updateRelativeXform()
-{
- if (mVolumeImpl)
- {
- mVolumeImpl->updateRelativeXform();
- return;
- }
-
- LLDrawable* drawable = mDrawable;
-
- if (drawable->isActive())
- {
- // setup relative transforms
- LLQuaternion delta_rot;
- LLVector3 delta_pos, delta_scale;
-
- //matrix from local space to parent relative/global space
- delta_rot = drawable->isSpatialRoot() ? LLQuaternion() : mDrawable->getRotation();
- delta_pos = drawable->isSpatialRoot() ? LLVector3(0,0,0) : mDrawable->getPosition();
- delta_scale = mDrawable->getScale();
-
- // Vertex transform (4x4)
- LLVector3 x_axis = LLVector3(delta_scale.mV[VX], 0.f, 0.f) * delta_rot;
- LLVector3 y_axis = LLVector3(0.f, delta_scale.mV[VY], 0.f) * delta_rot;
- LLVector3 z_axis = LLVector3(0.f, 0.f, delta_scale.mV[VZ]) * delta_rot;
-
- mRelativeXform.initRows(LLVector4(x_axis, 0.f),
- LLVector4(y_axis, 0.f),
- LLVector4(z_axis, 0.f),
- LLVector4(delta_pos, 1.f));
-
-
- // compute inverse transpose for normals
- // mRelativeXformInvTrans.setRows(x_axis, y_axis, z_axis);
- // mRelativeXformInvTrans.invert();
- // mRelativeXformInvTrans.setRows(x_axis, y_axis, z_axis);
- // grumble - invert is NOT a matrix invert, so we do it by hand:
-
- LLMatrix3 rot_inverse = LLMatrix3(~delta_rot);
-
- LLMatrix3 scale_inverse;
- scale_inverse.setRows(LLVector3(1.0, 0.0, 0.0) / delta_scale.mV[VX],
- LLVector3(0.0, 1.0, 0.0) / delta_scale.mV[VY],
- LLVector3(0.0, 0.0, 1.0) / delta_scale.mV[VZ]);
-
-
- mRelativeXformInvTrans = rot_inverse * scale_inverse;
-
- mRelativeXformInvTrans.transpose();
- }
- else
- {
- LLVector3 pos = getPosition();
- LLVector3 scale = getScale();
- LLQuaternion rot = getRotation();
-
- if (mParent)
- {
- pos *= mParent->getRotation();
- pos += mParent->getPosition();
- rot *= mParent->getRotation();
- }
-
- //LLViewerRegion* region = getRegion();
- //pos += region->getOriginAgent();
-
- LLVector3 x_axis = LLVector3(scale.mV[VX], 0.f, 0.f) * rot;
- LLVector3 y_axis = LLVector3(0.f, scale.mV[VY], 0.f) * rot;
- LLVector3 z_axis = LLVector3(0.f, 0.f, scale.mV[VZ]) * rot;
-
- mRelativeXform.initRows(LLVector4(x_axis, 0.f),
- LLVector4(y_axis, 0.f),
- LLVector4(z_axis, 0.f),
- LLVector4(pos, 1.f));
-
- // compute inverse transpose for normals
- LLMatrix3 rot_inverse = LLMatrix3(~rot);
-
- LLMatrix3 scale_inverse;
- scale_inverse.setRows(LLVector3(1.0, 0.0, 0.0) / scale.mV[VX],
- LLVector3(0.0, 1.0, 0.0) / scale.mV[VY],
- LLVector3(0.0, 0.0, 1.0) / scale.mV[VZ]);
-
-
- mRelativeXformInvTrans = rot_inverse * scale_inverse;
-
- mRelativeXformInvTrans.transpose();
- }
-}
-
-static LLFastTimer::DeclareTimer FTM_GEN_FLEX("Generate Flexies");
-static LLFastTimer::DeclareTimer FTM_UPDATE_PRIMITIVES("Update Primitives");
-
-BOOL LLVOVolume::updateGeometry(LLDrawable *drawable)
-{
- LLFastTimer t(FTM_UPDATE_PRIMITIVES);
-
- if (mVolumeImpl != NULL)
- {
- BOOL res;
- {
- LLFastTimer t(FTM_GEN_FLEX);
- res = mVolumeImpl->doUpdateGeometry(drawable);
- }
- updateFaceFlags();
- return res;
- }
-
- dirtySpatialGroup(drawable->isState(LLDrawable::IN_REBUILD_Q1));
-
- BOOL compiled = FALSE;
-
- updateRelativeXform();
-
- if (mDrawable.isNull()) // Not sure why this is happening, but it is...
- {
- return TRUE; // No update to complete
- }
-
- if (mVolumeChanged || mFaceMappingChanged )
- {
- compiled = TRUE;
-
- if (mVolumeChanged)
- {
- LLFastTimer ftm(FTM_GEN_VOLUME);
- LLVolumeParams volume_params = getVolume()->getParams();
- setVolume(volume_params, 0);
- drawable->setState(LLDrawable::REBUILD_VOLUME);
- }
-
- {
- LLFastTimer t(FTM_GEN_TRIANGLES);
- regenFaces();
- genBBoxes(FALSE);
- }
- }
- else if ((mLODChanged) || (mSculptChanged))
- {
- LLVolume *old_volumep, *new_volumep;
- F32 old_lod, new_lod;
- S32 old_num_faces, new_num_faces ;
-
- old_volumep = getVolume();
- old_lod = old_volumep->getDetail();
- old_num_faces = old_volumep->getNumFaces() ;
- old_volumep = NULL ;
-
- {
- LLFastTimer ftm(FTM_GEN_VOLUME);
- LLVolumeParams volume_params = getVolume()->getParams();
- setVolume(volume_params, 0);
- }
-
- new_volumep = getVolume();
- new_lod = new_volumep->getDetail();
- new_num_faces = new_volumep->getNumFaces() ;
- new_volumep = NULL ;
-
- if ((new_lod != old_lod) || mSculptChanged)
- {
- compiled = TRUE;
- sNumLODChanges += new_num_faces ;
-
- drawable->setState(LLDrawable::REBUILD_VOLUME); // for face->genVolumeTriangles()
-
- {
- LLFastTimer t(FTM_GEN_TRIANGLES);
- if (new_num_faces != old_num_faces)
- {
- regenFaces();
- }
- genBBoxes(FALSE);
- }
- }
- }
- // it has its own drawable (it's moved) or it has changed UVs or it has changed xforms from global<->local
- else
- {
- compiled = TRUE;
- // All it did was move or we changed the texture coordinate offset
- LLFastTimer t(FTM_GEN_TRIANGLES);
- genBBoxes(FALSE);
- }
-
- // Update face flags
- updateFaceFlags();
-
- if(compiled)
- {
- LLPipeline::sCompiles++;
- }
-
- mVolumeChanged = FALSE;
- mLODChanged = FALSE;
- mSculptChanged = FALSE;
- mFaceMappingChanged = FALSE;
-
- return LLViewerObject::updateGeometry(drawable);
-}
-
-void LLVOVolume::updateFaceSize(S32 idx)
-{
- LLFace* facep = mDrawable->getFace(idx);
- if (idx >= getVolume()->getNumVolumeFaces())
- {
- facep->setSize(0,0);
- }
- else
- {
- const LLVolumeFace& vol_face = getVolume()->getVolumeFace(idx);
- if (LLPipeline::sUseTriStrips)
- {
- facep->setSize(vol_face.mVertices.size(), vol_face.mTriStrip.size());
- }
- else
- {
- facep->setSize(vol_face.mVertices.size(), vol_face.mIndices.size());
- }
- }
-}
-
-BOOL LLVOVolume::isRootEdit() const
-{
- if (mParent && !((LLViewerObject*)mParent)->isAvatar())
- {
- return FALSE;
- }
- return TRUE;
-}
-
-//virtual
-void LLVOVolume::setNumTEs(const U8 num_tes)
-{
- const U8 old_num_tes = getNumTEs() ;
-
- if(old_num_tes && old_num_tes < num_tes) //new faces added
- {
- LLViewerObject::setNumTEs(num_tes) ;
-
- if(mMediaImplList.size() >= old_num_tes && mMediaImplList[old_num_tes -1].notNull())//duplicate the last media textures if exists.
- {
- mMediaImplList.resize(num_tes) ;
- const LLTextureEntry* te = getTE(old_num_tes - 1) ;
- for(U8 i = old_num_tes; i < num_tes ; i++)
- {
- setTE(i, *te) ;
- mMediaImplList[i] = mMediaImplList[old_num_tes -1] ;
- }
- mMediaImplList[old_num_tes -1]->setUpdated(TRUE) ;
- }
- }
- else if(old_num_tes > num_tes && mMediaImplList.size() > num_tes) //old faces removed
- {
- U8 end = mMediaImplList.size() ;
- for(U8 i = num_tes; i < end ; i++)
- {
- removeMediaImpl(i) ;
- }
- mMediaImplList.resize(num_tes) ;
-
- LLViewerObject::setNumTEs(num_tes) ;
- }
- else
- {
- LLViewerObject::setNumTEs(num_tes) ;
- }
-
- return ;
-}
-
-void LLVOVolume::setTEImage(const U8 te, LLViewerTexture *imagep)
-{
- BOOL changed = (mTEImages[te] != imagep);
- LLViewerObject::setTEImage(te, imagep);
- if (changed)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
-}
-
-S32 LLVOVolume::setTETexture(const U8 te, const LLUUID &uuid)
-{
- S32 res = LLViewerObject::setTETexture(te, uuid);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTEColor(const U8 te, const LLColor3& color)
-{
- return setTEColor(te, LLColor4(color));
-}
-
-S32 LLVOVolume::setTEColor(const U8 te, const LLColor4& color)
-{
- S32 retval = 0;
- const LLTextureEntry *tep = getTE(te);
- if (!tep)
- {
- llwarns << "No texture entry for te " << (S32)te << ", object " << mID << llendl;
- }
- else if (color != tep->getColor())
- {
- if (color.mV[3] != tep->getColor().mV[3])
- {
- gPipeline.markTextured(mDrawable);
- }
- retval = LLPrimitive::setTEColor(te, color);
- if (mDrawable.notNull() && retval)
- {
- // These should only happen on updates which are not the initial update.
- mDrawable->setState(LLDrawable::REBUILD_COLOR);
- dirtyMesh();
- }
- }
-
- return retval;
-}
-
-S32 LLVOVolume::setTEBumpmap(const U8 te, const U8 bumpmap)
-{
- S32 res = LLViewerObject::setTEBumpmap(te, bumpmap);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTETexGen(const U8 te, const U8 texgen)
-{
- S32 res = LLViewerObject::setTETexGen(te, texgen);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTEMediaTexGen(const U8 te, const U8 media)
-{
- S32 res = LLViewerObject::setTEMediaTexGen(te, media);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTEShiny(const U8 te, const U8 shiny)
-{
- S32 res = LLViewerObject::setTEShiny(te, shiny);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTEFullbright(const U8 te, const U8 fullbright)
-{
- S32 res = LLViewerObject::setTEFullbright(te, fullbright);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTEBumpShinyFullbright(const U8 te, const U8 bump)
-{
- S32 res = LLViewerObject::setTEBumpShinyFullbright(te, bump);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTEMediaFlags(const U8 te, const U8 media_flags)
-{
- S32 res = LLViewerObject::setTEMediaFlags(te, media_flags);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTEGlow(const U8 te, const F32 glow)
-{
- S32 res = LLViewerObject::setTEGlow(te, glow);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTEScale(const U8 te, const F32 s, const F32 t)
-{
- S32 res = LLViewerObject::setTEScale(te, s, t);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTEScaleS(const U8 te, const F32 s)
-{
- S32 res = LLViewerObject::setTEScaleS(te, s);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-S32 LLVOVolume::setTEScaleT(const U8 te, const F32 t)
-{
- S32 res = LLViewerObject::setTEScaleT(te, t);
- if (res)
- {
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- return res;
-}
-
-void LLVOVolume::updateTEData()
-{
- /*if (mDrawable.notNull())
- {
- mFaceMappingChanged = TRUE;
- gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_MATERIAL, TRUE);
- }*/
-}
-
-bool LLVOVolume::hasMedia() const
-{
- bool result = false;
- const U8 numTEs = getNumTEs();
- for (U8 i = 0; i < numTEs; i++)
- {
- const LLTextureEntry* te = getTE(i);
- if(te->hasMedia())
- {
- result = true;
- break;
- }
- }
- return result;
-}
-
-LLVector3 LLVOVolume::getApproximateFaceNormal(U8 face_id)
-{
- LLVolume* volume = getVolume();
- LLVector3 result;
-
- if (volume && face_id < volume->getNumVolumeFaces())
- {
- const LLVolumeFace& face = volume->getVolumeFace(face_id);
- for (S32 i = 0; i < (S32)face.mVertices.size(); ++i)
- {
- result += face.mVertices[i].mNormal;
- }
-
- result = volumeDirectionToAgent(result);
- result.normVec();
- }
-
- return result;
-}
-
-void LLVOVolume::requestMediaDataUpdate(bool isNew)
-{
- if (sObjectMediaClient)
- sObjectMediaClient->fetchMedia(new LLMediaDataClientObjectImpl(this, isNew));
-}
-
-bool LLVOVolume::isMediaDataBeingFetched() const
-{
- // I know what I'm doing by const_casting this away: this is just
- // a wrapper class that is only going to do a lookup.
- return (sObjectMediaClient) ? sObjectMediaClient->isInQueue(new LLMediaDataClientObjectImpl(const_cast<LLVOVolume*>(this), false)) : false;
-}
-
-void LLVOVolume::cleanUpMediaImpls()
-{
- // Iterate through our TEs and remove any Impls that are no longer used
- const U8 numTEs = getNumTEs();
- for (U8 i = 0; i < numTEs; i++)
- {
- const LLTextureEntry* te = getTE(i);
- if( ! te->hasMedia())
- {
- // Delete the media IMPL!
- removeMediaImpl(i) ;
- }
- }
-}
-
-void LLVOVolume::updateObjectMediaData(const LLSD &media_data_array, const std::string &media_version)
-{
- // media_data_array is an array of media entry maps
- // media_version is the version string in the response.
- U32 fetched_version = LLTextureEntry::getVersionFromMediaVersionString(media_version);
-
- // Only update it if it is newer!
- if ( (S32)fetched_version > mLastFetchedMediaVersion)
- {
- mLastFetchedMediaVersion = fetched_version;
- //llinfos << "updating:" << this->getID() << " " << ll_pretty_print_sd(media_data_array) << llendl;
-
- LLSD::array_const_iterator iter = media_data_array.beginArray();
- LLSD::array_const_iterator end = media_data_array.endArray();
- U8 texture_index = 0;
- for (; iter != end; ++iter, ++texture_index)
- {
- syncMediaData(texture_index, *iter, false/*merge*/, false/*ignore_agent*/);
- }
- }
-}
-
-void LLVOVolume::syncMediaData(S32 texture_index, const LLSD &media_data, bool merge, bool ignore_agent)
-{
- if(mDead)
- {
- // If the object has been marked dead, don't process media updates.
- return;
- }
-
- LLTextureEntry *te = getTE(texture_index);
- if(!te)
- {
- return ;
- }
-
- LL_DEBUGS("MediaOnAPrim") << "BEFORE: texture_index = " << texture_index
- << " hasMedia = " << te->hasMedia() << " : "
- << ((NULL == te->getMediaData()) ? "NULL MEDIA DATA" : ll_pretty_print_sd(te->getMediaData()->asLLSD())) << llendl;
-
- std::string previous_url;
- LLMediaEntry* mep = te->getMediaData();
- if(mep)
- {
- // Save the "current url" from before the update so we can tell if
- // it changes.
- previous_url = mep->getCurrentURL();
- }
-
- if (merge)
- {
- te->mergeIntoMediaData(media_data);
- }
- else {
- // XXX Question: what if the media data is undefined LLSD, but the
- // update we got above said that we have media flags?? Here we clobber
- // that, assuming the data from the service is more up-to-date.
- te->updateMediaData(media_data);
- }
-
- mep = te->getMediaData();
- if(mep)
- {
- bool update_from_self = false;
- if (!ignore_agent)
- {
- LLUUID updating_agent = LLTextureEntry::getAgentIDFromMediaVersionString(getMediaURL());
- update_from_self = (updating_agent == gAgent.getID());
- }
- viewer_media_t media_impl = LLViewerMedia::updateMediaImpl(mep, previous_url, update_from_self);
-
- addMediaImpl(media_impl, texture_index) ;
- }
- else
- {
- removeMediaImpl(texture_index);
- }
-
- LL_DEBUGS("MediaOnAPrim") << "AFTER: texture_index = " << texture_index
- << " hasMedia = " << te->hasMedia() << " : "
- << ((NULL == te->getMediaData()) ? "NULL MEDIA DATA" : ll_pretty_print_sd(te->getMediaData()->asLLSD())) << llendl;
-}
-
-void LLVOVolume::mediaNavigateBounceBack(U8 texture_index)
-{
- // Find the media entry for this navigate
- const LLMediaEntry* mep = NULL;
- viewer_media_t impl = getMediaImpl(texture_index);
- LLTextureEntry *te = getTE(texture_index);
- if(te)
- {
- mep = te->getMediaData();
- }
-
- if (mep && impl)
- {
- std::string url = mep->getCurrentURL();
- // Look for a ":", if not there, assume "http://"
- if (!url.empty() && std::string::npos == url.find(':'))
- {
- url = "http://" + url;
- }
- // If the url we're trying to "bounce back" to is either empty or not
- // allowed by the whitelist, try the home url. If *that* doesn't work,
- // set the media as failed and unload it
- if (url.empty() || !mep->checkCandidateUrl(url))
- {
- url = mep->getHomeURL();
- // Look for a ":", if not there, assume "http://"
- if (!url.empty() && std::string::npos == url.find(':'))
- {
- url = "http://" + url;
- }
- }
- if (url.empty() || !mep->checkCandidateUrl(url))
- {
- // The url to navigate back to is not good, and we have nowhere else
- // to go.
- LL_WARNS("MediaOnAPrim") << "FAILED to bounce back URL \"" << url << "\" -- unloading impl" << LL_ENDL;
- impl->setMediaFailed(true);
- }
- else {
- // Okay, navigate now
- LL_INFOS("MediaOnAPrim") << "bouncing back to URL: " << url << LL_ENDL;
- impl->navigateTo(url, "", false, true);
- }
- }
-}
-
-bool LLVOVolume::hasMediaPermission(const LLMediaEntry* media_entry, MediaPermType perm_type)
-{
- // NOTE: This logic ALMOST duplicates the logic in the server (in particular, in llmediaservice.cpp).
- if (NULL == media_entry ) return false; // XXX should we assert here?
-
- // The agent has permissions if:
- // - world permissions are on, or
- // - group permissions are on, and agent_id is in the group, or
- // - agent permissions are on, and agent_id is the owner
-
- // *NOTE: We *used* to check for modify permissions here (i.e. permissions were
- // granted if permModify() was true). However, this doesn't make sense in the
- // viewer: we don't want to show controls or allow interaction if the author
- // has deemed it so. See DEV-42115.
-
- U8 media_perms = (perm_type == MEDIA_PERM_INTERACT) ? media_entry->getPermsInteract() : media_entry->getPermsControl();
-
- // World permissions
- if (0 != (media_perms & LLMediaEntry::PERM_ANYONE))
- {
- return true;
- }
-
- // Group permissions
- else if (0 != (media_perms & LLMediaEntry::PERM_GROUP))
- {
- LLPermissions* obj_perm = LLSelectMgr::getInstance()->findObjectPermissions(this);
- if (obj_perm && gAgent.isInGroup(obj_perm->getGroup()))
- {
- return true;
- }
- }
-
- // Owner permissions
- else if (0 != (media_perms & LLMediaEntry::PERM_OWNER) && permYouOwner())
- {
- return true;
- }
-
- return false;
-
-}
-
-void LLVOVolume::mediaNavigated(LLViewerMediaImpl *impl, LLPluginClassMedia* plugin, std::string new_location)
-{
- bool block_navigation = false;
- // FIXME: if/when we allow the same media impl to be used by multiple faces, the logic here will need to be fixed
- // to deal with multiple face indices.
- int face_index = getFaceIndexWithMediaImpl(impl, -1);
-
- // Find the media entry for this navigate
- LLMediaEntry* mep = NULL;
- LLTextureEntry *te = getTE(face_index);
- if(te)
- {
- mep = te->getMediaData();
- }
-
- if(mep)
- {
- if(!mep->checkCandidateUrl(new_location))
- {
- block_navigation = true;
- }
- if (!block_navigation && !hasMediaPermission(mep, MEDIA_PERM_INTERACT))
- {
- block_navigation = true;
- }
- }
- else
- {
- LL_WARNS("MediaOnAPrim") << "Couldn't find media entry!" << LL_ENDL;
- }
-
- if(block_navigation)
- {
- LL_INFOS("MediaOnAPrim") << "blocking navigate to URI " << new_location << LL_ENDL;
-
- // "bounce back" to the current URL from the media entry
- mediaNavigateBounceBack(face_index);
- }
- else if (sObjectMediaNavigateClient)
- {
-
- LL_DEBUGS("MediaOnAPrim") << "broadcasting navigate with URI " << new_location << LL_ENDL;
-
- sObjectMediaNavigateClient->navigate(new LLMediaDataClientObjectImpl(this, false), face_index, new_location);
- }
-}
-
-void LLVOVolume::mediaEvent(LLViewerMediaImpl *impl, LLPluginClassMedia* plugin, LLViewerMediaObserver::EMediaEvent event)
-{
- switch(event)
- {
-
- case LLViewerMediaObserver::MEDIA_EVENT_LOCATION_CHANGED:
- {
- switch(impl->getNavState())
- {
- case LLViewerMediaImpl::MEDIANAVSTATE_FIRST_LOCATION_CHANGED:
- {
- // This is the first location changed event after the start of a non-server-directed nav. It may need to be broadcast or bounced back.
- mediaNavigated(impl, plugin, plugin->getLocation());
- }
- break;
-
- case LLViewerMediaImpl::MEDIANAVSTATE_FIRST_LOCATION_CHANGED_SPURIOUS:
- // This navigate didn't change the current URL.
- LL_DEBUGS("MediaOnAPrim") << " NOT broadcasting navigate (spurious)" << LL_ENDL;
- break;
-
- case LLViewerMediaImpl::MEDIANAVSTATE_SERVER_FIRST_LOCATION_CHANGED:
- // This is the first location changed event after the start of a server-directed nav. Don't broadcast it.
- LL_INFOS("MediaOnAPrim") << " NOT broadcasting navigate (server-directed)" << LL_ENDL;
- break;
-
- default:
- // This is a subsequent location-changed due to a redirect. Don't broadcast.
- LL_INFOS("MediaOnAPrim") << " NOT broadcasting navigate (redirect)" << LL_ENDL;
- break;
- }
- }
- break;
-
- case LLViewerMediaObserver::MEDIA_EVENT_NAVIGATE_COMPLETE:
- {
- switch(impl->getNavState())
- {
- case LLViewerMediaImpl::MEDIANAVSTATE_COMPLETE_BEFORE_LOCATION_CHANGED:
- {
- // This is the first location changed event after the start of a non-server-directed nav. It may need to be broadcast or bounced back.
- mediaNavigated(impl, plugin, plugin->getNavigateURI());
- }
- break;
-
- case LLViewerMediaImpl::MEDIANAVSTATE_COMPLETE_BEFORE_LOCATION_CHANGED_SPURIOUS:
- // This navigate didn't change the current URL.
- LL_DEBUGS("MediaOnAPrim") << " NOT broadcasting navigate (spurious)" << LL_ENDL;
- break;
-
- case LLViewerMediaImpl::MEDIANAVSTATE_SERVER_COMPLETE_BEFORE_LOCATION_CHANGED:
- // This is the the navigate complete event from a server-directed nav. Don't broadcast it.
- LL_INFOS("MediaOnAPrim") << " NOT broadcasting navigate (server-directed)" << LL_ENDL;
- break;
-
- default:
- // For all other states, the navigate should have been handled by LOCATION_CHANGED events already.
- break;
- }
- }
- break;
-
- default:
- break;
- }
-
-}
-
-void LLVOVolume::sendMediaDataUpdate()
-{
- if (sObjectMediaClient)
- sObjectMediaClient->updateMedia(new LLMediaDataClientObjectImpl(this, false));
-}
-
-void LLVOVolume::removeMediaImpl(S32 texture_index)
-{
- if(mMediaImplList.size() <= (U32)texture_index || mMediaImplList[texture_index].isNull())
- {
- return ;
- }
-
- //make the face referencing to mMediaImplList[texture_index] to point back to the old texture.
- if(mDrawable && texture_index < mDrawable->getNumFaces())
- {
- LLFace* facep = mDrawable->getFace(texture_index) ;
- if(facep)
- {
- LLViewerMediaTexture* media_tex = LLViewerTextureManager::findMediaTexture(mMediaImplList[texture_index]->getMediaTextureID()) ;
- if(media_tex)
- {
- media_tex->removeMediaFromFace(facep) ;
- }
- }
- }
-
- //check if some other face(s) of this object reference(s)to this media impl.
- S32 i ;
- S32 end = (S32)mMediaImplList.size() ;
- for(i = 0; i < end ; i++)
- {
- if( i != texture_index && mMediaImplList[i] == mMediaImplList[texture_index])
- {
- break ;
- }
- }
-
- if(i == end) //this object does not need this media impl.
- {
- mMediaImplList[texture_index]->removeObject(this) ;
- }
-
- mMediaImplList[texture_index] = NULL ;
- return ;
-}
-
-void LLVOVolume::addMediaImpl(LLViewerMediaImpl* media_impl, S32 texture_index)
-{
- if((S32)mMediaImplList.size() < texture_index + 1)
- {
- mMediaImplList.resize(texture_index + 1) ;
- }
-
- if(mMediaImplList[texture_index].notNull())
- {
- if(mMediaImplList[texture_index] == media_impl)
- {
- return ;
- }
-
- removeMediaImpl(texture_index) ;
- }
-
- mMediaImplList[texture_index] = media_impl;
- media_impl->addObject(this) ;
-
- //add the face to show the media if it is in playing
- if(mDrawable)
- {
- LLFace* facep = mDrawable->getFace(texture_index) ;
- if(facep)
- {
- LLViewerMediaTexture* media_tex = LLViewerTextureManager::findMediaTexture(mMediaImplList[texture_index]->getMediaTextureID()) ;
- if(media_tex)
- {
- media_tex->addMediaToFace(facep) ;
- }
- }
- else //the face is not available now, start media on this face later.
- {
- media_impl->setUpdated(TRUE) ;
- }
- }
- return ;
-}
-
-viewer_media_t LLVOVolume::getMediaImpl(U8 face_id) const
-{
- if(mMediaImplList.size() > face_id)
- {
- return mMediaImplList[face_id];
- }
- return NULL;
-}
-
-F64 LLVOVolume::getTotalMediaInterest() const
-{
- // If this object is currently focused, this object has "high" interest
- if (LLViewerMediaFocus::getInstance()->getFocusedObjectID() == getID())
- return F64_MAX;
-
- F64 interest = (F64)-1.0; // means not interested;
-
- // If this object is selected, this object has "high" interest, but since
- // there can be more than one, we still add in calculated impl interest
- // XXX Sadly, 'contains()' doesn't take a const :(
- if (LLSelectMgr::getInstance()->getSelection()->contains(const_cast<LLVOVolume*>(this)))
- interest = F64_MAX / 2.0;
-
- int i = 0;
- const int end = getNumTEs();
- for ( ; i < end; ++i)
- {
- const viewer_media_t &impl = getMediaImpl(i);
- if (!impl.isNull())
- {
- if (interest == (F64)-1.0) interest = (F64)0.0;
- interest += impl->getInterest();
- }
- }
- return interest;
-}
-
-S32 LLVOVolume::getFaceIndexWithMediaImpl(const LLViewerMediaImpl* media_impl, S32 start_face_id)
-{
- S32 end = (S32)mMediaImplList.size() ;
- for(S32 face_id = start_face_id + 1; face_id < end; face_id++)
- {
- if(mMediaImplList[face_id] == media_impl)
- {
- return face_id ;
- }
- }
- return -1 ;
-}
-
-//----------------------------------------------------------------------------
-
-void LLVOVolume::setLightTextureID(LLUUID id)
-{
- if (id.notNull())
- {
- if (!hasLightTexture())
- {
- setParameterEntryInUse(LLNetworkData::PARAMS_LIGHT_IMAGE, TRUE, true);
- }
- LLLightImageParams* param_block = (LLLightImageParams*) getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
- if (param_block && param_block->getLightTexture() != id)
- {
- param_block->setLightTexture(id);
- parameterChanged(LLNetworkData::PARAMS_LIGHT_IMAGE, true);
- }
- }
- else
- {
- if (hasLightTexture())
- {
- setParameterEntryInUse(LLNetworkData::PARAMS_LIGHT_IMAGE, FALSE, true);
- mLightTexture = NULL;
- }
- }
-}
-
-void LLVOVolume::setSpotLightParams(LLVector3 params)
-{
- LLLightImageParams* param_block = (LLLightImageParams*) getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
- if (param_block && param_block->getParams() != params)
- {
- param_block->setParams(params);
- parameterChanged(LLNetworkData::PARAMS_LIGHT_IMAGE, true);
- }
-}
-
-void LLVOVolume::setIsLight(BOOL is_light)
-{
- if (is_light != getIsLight())
- {
- if (is_light)
- {
- setParameterEntryInUse(LLNetworkData::PARAMS_LIGHT, TRUE, true);
- }
- else
- {
- setParameterEntryInUse(LLNetworkData::PARAMS_LIGHT, FALSE, true);
- }
-
- if (is_light)
- {
- // Add it to the pipeline mLightSet
- gPipeline.setLight(mDrawable, TRUE);
- }
- else
- {
- // Not a light. Remove it from the pipeline's light set.
- gPipeline.setLight(mDrawable, FALSE);
- }
- }
-}
-
-void LLVOVolume::setLightColor(const LLColor3& color)
-{
- LLLightParams *param_block = (LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- if (param_block->getColor() != color)
- {
- param_block->setColor(LLColor4(color, param_block->getColor().mV[3]));
- parameterChanged(LLNetworkData::PARAMS_LIGHT, true);
- gPipeline.markTextured(mDrawable);
- mFaceMappingChanged = TRUE;
- }
- }
-}
-
-void LLVOVolume::setLightIntensity(F32 intensity)
-{
- LLLightParams *param_block = (LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- if (param_block->getColor().mV[3] != intensity)
- {
- param_block->setColor(LLColor4(LLColor3(param_block->getColor()), intensity));
- parameterChanged(LLNetworkData::PARAMS_LIGHT, true);
- }
- }
-}
-
-void LLVOVolume::setLightRadius(F32 radius)
-{
- LLLightParams *param_block = (LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- if (param_block->getRadius() != radius)
- {
- param_block->setRadius(radius);
- parameterChanged(LLNetworkData::PARAMS_LIGHT, true);
- }
- }
-}
-
-void LLVOVolume::setLightFalloff(F32 falloff)
-{
- LLLightParams *param_block = (LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- if (param_block->getFalloff() != falloff)
- {
- param_block->setFalloff(falloff);
- parameterChanged(LLNetworkData::PARAMS_LIGHT, true);
- }
- }
-}
-
-void LLVOVolume::setLightCutoff(F32 cutoff)
-{
- LLLightParams *param_block = (LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- if (param_block->getCutoff() != cutoff)
- {
- param_block->setCutoff(cutoff);
- parameterChanged(LLNetworkData::PARAMS_LIGHT, true);
- }
- }
-}
-
-//----------------------------------------------------------------------------
-
-BOOL LLVOVolume::getIsLight() const
-{
- return getParameterEntryInUse(LLNetworkData::PARAMS_LIGHT);
-}
-
-LLColor3 LLVOVolume::getLightBaseColor() const
-{
- const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- return LLColor3(param_block->getColor());
- }
- else
- {
- return LLColor3(1,1,1);
- }
-}
-
-LLColor3 LLVOVolume::getLightColor() const
-{
- const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- return LLColor3(param_block->getColor()) * param_block->getColor().mV[3];
- }
- else
- {
- return LLColor3(1,1,1);
- }
-}
-
-LLUUID LLVOVolume::getLightTextureID() const
-{
- if (getParameterEntryInUse(LLNetworkData::PARAMS_LIGHT_IMAGE))
- {
- const LLLightImageParams *param_block = (const LLLightImageParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
- if (param_block)
- {
- return param_block->getLightTexture();
- }
- }
-
- return LLUUID::null;
-}
-
-
-LLVector3 LLVOVolume::getSpotLightParams() const
-{
- if (getParameterEntryInUse(LLNetworkData::PARAMS_LIGHT_IMAGE))
- {
- const LLLightImageParams *param_block = (const LLLightImageParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
- if (param_block)
- {
- return param_block->getParams();
- }
- }
-
- return LLVector3();
-}
-
-F32 LLVOVolume::getSpotLightPriority() const
-{
- return mSpotLightPriority;
-}
-
-void LLVOVolume::updateSpotLightPriority()
-{
- LLVector3 pos = mDrawable->getPositionAgent();
- LLVector3 at(0,0,-1);
- at *= getRenderRotation();
-
- F32 r = getLightRadius()*0.5f;
-
- pos += at * r;
-
- at = LLViewerCamera::getInstance()->getAtAxis();
-
- pos -= at * r;
-
- mSpotLightPriority = gPipeline.calcPixelArea(pos, LLVector3(r,r,r), *LLViewerCamera::getInstance());
-
- if (mLightTexture.notNull())
- {
- mLightTexture->addTextureStats(mSpotLightPriority);
- mLightTexture->setBoostLevel(LLViewerTexture::BOOST_CLOUDS);
- }
-}
-
-
-bool LLVOVolume::isLightSpotlight() const
-{
- LLLightImageParams* params = (LLLightImageParams*) getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
- if (params)
- {
- return params->isLightSpotlight();
- }
- return false;
-}
-
-
-LLViewerTexture* LLVOVolume::getLightTexture()
-{
- LLUUID id = getLightTextureID();
-
- if (id.notNull())
- {
- if (mLightTexture.isNull() || id != mLightTexture->getID())
- {
- mLightTexture = LLViewerTextureManager::getFetchedTexture(id);
- }
- }
- else
- {
- mLightTexture = NULL;
- }
-
- return mLightTexture;
-}
-
-F32 LLVOVolume::getLightIntensity() const
-{
- const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- return param_block->getColor().mV[3];
- }
- else
- {
- return 1.f;
- }
-}
-
-F32 LLVOVolume::getLightRadius() const
-{
- const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- return param_block->getRadius();
- }
- else
- {
- return 0.f;
- }
-}
-
-F32 LLVOVolume::getLightFalloff() const
-{
- const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- return param_block->getFalloff();
- }
- else
- {
- return 0.f;
- }
-}
-
-F32 LLVOVolume::getLightCutoff() const
-{
- const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
- if (param_block)
- {
- return param_block->getCutoff();
- }
- else
- {
- return 0.f;
- }
-}
-
-U32 LLVOVolume::getVolumeInterfaceID() const
-{
- if (mVolumeImpl)
- {
- return mVolumeImpl->getID();
- }
-
- return 0;
-}
-
-BOOL LLVOVolume::isFlexible() const
-{
- if (getParameterEntryInUse(LLNetworkData::PARAMS_FLEXIBLE))
- {
- LLVolume* volume = getVolume();
- if (volume && volume->getParams().getPathParams().getCurveType() != LL_PCODE_PATH_FLEXIBLE)
- {
- LLVolumeParams volume_params = getVolume()->getParams();
- U8 profile_and_hole = volume_params.getProfileParams().getCurveType();
- volume_params.setType(profile_and_hole, LL_PCODE_PATH_FLEXIBLE);
- }
- return TRUE;
- }
- else
- {
- return FALSE;
- }
-}
-
-BOOL LLVOVolume::isSculpted() const
-{
- if (getParameterEntryInUse(LLNetworkData::PARAMS_SCULPT))
- {
- return TRUE;
- }
-
- return FALSE;
-}
-
-BOOL LLVOVolume::hasLightTexture() const
-{
- if (getParameterEntryInUse(LLNetworkData::PARAMS_LIGHT_IMAGE))
- {
- return TRUE;
- }
-
- return FALSE;
-}
-
-BOOL LLVOVolume::isVolumeGlobal() const
-{
- if (mVolumeImpl)
- {
- return mVolumeImpl->isVolumeGlobal() ? TRUE : FALSE;
- }
- return FALSE;
-}
-
-BOOL LLVOVolume::canBeFlexible() const
-{
- U8 path = getVolume()->getParams().getPathParams().getCurveType();
- return (path == LL_PCODE_PATH_FLEXIBLE || path == LL_PCODE_PATH_LINE);
-}
-
-BOOL LLVOVolume::setIsFlexible(BOOL is_flexible)
-{
- BOOL res = FALSE;
- BOOL was_flexible = isFlexible();
- LLVolumeParams volume_params;
- if (is_flexible)
- {
- if (!was_flexible)
- {
- volume_params = getVolume()->getParams();
- U8 profile_and_hole = volume_params.getProfileParams().getCurveType();
- volume_params.setType(profile_and_hole, LL_PCODE_PATH_FLEXIBLE);
- res = TRUE;
- setFlags(FLAGS_USE_PHYSICS, FALSE);
- setFlags(FLAGS_PHANTOM, TRUE);
- setParameterEntryInUse(LLNetworkData::PARAMS_FLEXIBLE, TRUE, true);
- if (mDrawable)
- {
- mDrawable->makeActive();
- }
- }
- }
- else
- {
- if (was_flexible)
- {
- volume_params = getVolume()->getParams();
- U8 profile_and_hole = volume_params.getProfileParams().getCurveType();
- volume_params.setType(profile_and_hole, LL_PCODE_PATH_LINE);
- res = TRUE;
- setFlags(FLAGS_PHANTOM, FALSE);
- setParameterEntryInUse(LLNetworkData::PARAMS_FLEXIBLE, FALSE, true);
- }
- }
- if (res)
- {
- res = setVolume(volume_params, 1);
- if (res)
- {
- markForUpdate(TRUE);
- }
- }
- return res;
-}
-
-//----------------------------------------------------------------------------
-
-void LLVOVolume::generateSilhouette(LLSelectNode* nodep, const LLVector3& view_point)
-{
- LLVolume *volume = getVolume();
-
- if (volume)
- {
- LLVector3 view_vector;
- view_vector = view_point;
-
- //transform view vector into volume space
- view_vector -= getRenderPosition();
- mDrawable->mDistanceWRTCamera = view_vector.length();
- LLQuaternion worldRot = getRenderRotation();
- view_vector = view_vector * ~worldRot;
- if (!isVolumeGlobal())
- {
- LLVector3 objScale = getScale();
- LLVector3 invObjScale(1.f / objScale.mV[VX], 1.f / objScale.mV[VY], 1.f / objScale.mV[VZ]);
- view_vector.scaleVec(invObjScale);
- }
-
- updateRelativeXform();
- LLMatrix4 trans_mat = mRelativeXform;
- if (mDrawable->isStatic())
- {
- trans_mat.translate(getRegion()->getOriginAgent());
- }
-
- volume->generateSilhouetteVertices(nodep->mSilhouetteVertices, nodep->mSilhouetteNormals, nodep->mSilhouetteSegments, view_vector, trans_mat, mRelativeXformInvTrans, nodep->getTESelectMask());
-
- nodep->mSilhouetteExists = TRUE;
- }
-}
-
-void LLVOVolume::deleteFaces()
-{
- S32 face_count = mNumFaces;
- if (mDrawable.notNull())
- {
- mDrawable->deleteFaces(0, face_count);
- }
-
- mNumFaces = 0;
-}
-
-void LLVOVolume::updateRadius()
-{
- if (mDrawable.isNull())
- {
- return;
- }
-
- mVObjRadius = getScale().length();
- mDrawable->setRadius(mVObjRadius);
-}
-
-
-BOOL LLVOVolume::isAttachment() const
-{
- return mState != 0 ;
-}
-
-BOOL LLVOVolume::isHUDAttachment() const
-{
- // *NOTE: we assume hud attachment points are in defined range
- // since this range is constant for backwards compatibility
- // reasons this is probably a reasonable assumption to make
- S32 attachment_id = ATTACHMENT_ID_FROM_STATE(mState);
- return ( attachment_id >= 31 && attachment_id <= 38 );
-}
-
-
-const LLMatrix4 LLVOVolume::getRenderMatrix() const
-{
- if (mDrawable->isActive() && !mDrawable->isRoot())
- {
- return mDrawable->getParent()->getWorldMatrix();
- }
- return mDrawable->getWorldMatrix();
-}
-
-// Returns a base cost and adds textures to passed in set.
-// total cost is returned value + 5 * size of the resulting set.
-// Cannot include cost of textures, as they may be re-used in linked
-// children, and cost should only be increased for unique textures -Nyx
-U32 LLVOVolume::getRenderCost(std::set<LLUUID> &textures) const
-{
- // base cost of each prim should be 10 points
- static const U32 ARC_PRIM_COST = 10;
- // per-prim costs
- static const U32 ARC_INVISI_COST = 1;
- static const U32 ARC_SHINY_COST = 1;
- static const U32 ARC_GLOW_COST = 1;
- static const U32 ARC_FLEXI_COST = 8;
- static const U32 ARC_PARTICLE_COST = 16;
- static const U32 ARC_BUMP_COST = 4;
-
- // per-face costs
- static const U32 ARC_PLANAR_COST = 1;
- static const U32 ARC_ANIM_TEX_COST = 4;
- static const U32 ARC_ALPHA_COST = 4;
-
- U32 shame = ARC_PRIM_COST;
-
- U32 invisi = 0;
- U32 shiny = 0;
- U32 glow = 0;
- U32 alpha = 0;
- U32 flexi = 0;
- U32 animtex = 0;
- U32 particles = 0;
- U32 scale = 0;
- U32 bump = 0;
- U32 planar = 0;
-
- if (isFlexible())
- {
- flexi = 1;
- }
- if (isParticleSource())
- {
- particles = 1;
- }
-
- const LLVector3& sc = getScale();
- scale += (U32) sc.mV[0] + (U32) sc.mV[1] + (U32) sc.mV[2];
-
- const LLDrawable* drawablep = mDrawable;
-
- if (isSculpted())
- {
- const LLSculptParams *sculpt_params = (LLSculptParams *) getParameterEntry(LLNetworkData::PARAMS_SCULPT);
- LLUUID sculpt_id = sculpt_params->getSculptTexture();
- textures.insert(sculpt_id);
- }
-
- for (S32 i = 0; i < drawablep->getNumFaces(); ++i)
- {
- const LLFace* face = drawablep->getFace(i);
- const LLTextureEntry* te = face->getTextureEntry();
- const LLViewerTexture* img = face->getTexture();
-
- if (img)
- {
- textures.insert(img->getID());
- }
-
- if (face->getPoolType() == LLDrawPool::POOL_ALPHA)
- {
- alpha++;
- }
- else if (img && img->getPrimaryFormat() == GL_ALPHA)
- {
- invisi = 1;
- }
-
- if (te)
- {
- if (te->getBumpmap())
- {
- bump = 1;
- }
- if (te->getShiny())
- {
- shiny = 1;
- }
- if (te->getGlow() > 0.f)
- {
- glow = 1;
- }
- if (face->mTextureMatrix != NULL)
- {
- animtex++;
- }
- if (te->getTexGen())
- {
- planar++;
- }
- }
- }
-
-
- shame += invisi * ARC_INVISI_COST;
- shame += shiny * ARC_SHINY_COST;
- shame += glow * ARC_GLOW_COST;
- shame += alpha * ARC_ALPHA_COST;
- shame += flexi * ARC_FLEXI_COST;
- shame += animtex * ARC_ANIM_TEX_COST;
- shame += particles * ARC_PARTICLE_COST;
- shame += bump * ARC_BUMP_COST;
- shame += planar * ARC_PLANAR_COST;
- shame += scale;
-
- LLViewerObject::const_child_list_t& child_list = getChildren();
- for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
- iter != child_list.end();
- ++iter)
- {
- const LLViewerObject* child_objectp = *iter;
- const LLDrawable* child_drawablep = child_objectp->mDrawable;
- if (child_drawablep)
- {
- const LLVOVolume* child_volumep = child_drawablep->getVOVolume();
- if (child_volumep)
- {
- shame += child_volumep->getRenderCost(textures);
- }
- }
- }
-
- return shame;
-
-}
-
-//static
-void LLVOVolume::preUpdateGeom()
-{
- sNumLODChanges = 0;
-}
-
-void LLVOVolume::parameterChanged(U16 param_type, bool local_origin)
-{
- LLViewerObject::parameterChanged(param_type, local_origin);
-}
-
-void LLVOVolume::parameterChanged(U16 param_type, LLNetworkData* data, BOOL in_use, bool local_origin)
-{
- LLViewerObject::parameterChanged(param_type, data, in_use, local_origin);
- if (mVolumeImpl)
- {
- mVolumeImpl->onParameterChanged(param_type, data, in_use, local_origin);
- }
- if (mDrawable.notNull())
- {
- BOOL is_light = getIsLight();
- if (is_light != mDrawable->isState(LLDrawable::LIGHT))
- {
- gPipeline.setLight(mDrawable, is_light);
- }
- }
-}
-
-void LLVOVolume::setSelected(BOOL sel)
-{
- LLViewerObject::setSelected(sel);
- if (mDrawable.notNull())
- {
- markForUpdate(TRUE);
- }
-}
-
-void LLVOVolume::updateSpatialExtents(LLVector3& newMin, LLVector3& newMax)
-{
-}
-
-F32 LLVOVolume::getBinRadius()
-{
- F32 radius;
-
- const LLVector3* ext = mDrawable->getSpatialExtents();
-
- BOOL shrink_wrap = mDrawable->isAnimating();
- BOOL alpha_wrap = FALSE;
-
- if (!isHUDAttachment())
- {
- for (S32 i = 0; i < mDrawable->getNumFaces(); i++)
- {
- LLFace* face = mDrawable->getFace(i);
- if (face->getPoolType() == LLDrawPool::POOL_ALPHA &&
- !face->canRenderAsMask())
- {
- alpha_wrap = TRUE;
- break;
- }
- }
- }
- else
- {
- shrink_wrap = FALSE;
- }
-
- if (alpha_wrap)
- {
- LLVector3 bounds = getScale();
- radius = llmin(bounds.mV[1], bounds.mV[2]);
- radius = llmin(radius, bounds.mV[0]);
- radius *= 0.5f;
- }
- else if (shrink_wrap)
- {
- radius = (ext[1]-ext[0]).length()*0.5f;
- }
- else if (mDrawable->isStatic())
- {
- /*if (mDrawable->getRadius() < 2.0f)
- {
- radius = 16.f;
- }
- else
- {
- radius = llmax(mDrawable->getRadius(), 32.f);
- }*/
-
- radius = (((S32) mDrawable->getRadius())/2+1)*8;
- }
- else if (mDrawable->getVObj()->isAttachment())
- {
- radius = (((S32) (mDrawable->getRadius()*4)+1))*2;
- }
- else
- {
- radius = 8.f;
- }
-
- return llclamp(radius, 0.5f, 256.f);
-}
-
-const LLVector3 LLVOVolume::getPivotPositionAgent() const
-{
- if (mVolumeImpl)
- {
- return mVolumeImpl->getPivotPosition();
- }
- return LLViewerObject::getPivotPositionAgent();
-}
-
-void LLVOVolume::onShift(const LLVector3 &shift_vector)
-{
- if (mVolumeImpl)
- {
- mVolumeImpl->onShift(shift_vector);
- }
-
- updateRelativeXform();
-}
-
-const LLMatrix4& LLVOVolume::getWorldMatrix(LLXformMatrix* xform) const
-{
- if (mVolumeImpl)
- {
- return mVolumeImpl->getWorldMatrix(xform);
- }
- return xform->getWorldMatrix();
-}
-
-LLVector3 LLVOVolume::agentPositionToVolume(const LLVector3& pos) const
-{
- LLVector3 ret = pos - getRenderPosition();
- ret = ret * ~getRenderRotation();
- LLVector3 objScale = isVolumeGlobal() ? LLVector3(1,1,1) : getScale();
- LLVector3 invObjScale(1.f / objScale.mV[VX], 1.f / objScale.mV[VY], 1.f / objScale.mV[VZ]);
- ret.scaleVec(invObjScale);
-
- return ret;
-}
-
-LLVector3 LLVOVolume::agentDirectionToVolume(const LLVector3& dir) const
-{
- LLVector3 ret = dir * ~getRenderRotation();
-
- LLVector3 objScale = isVolumeGlobal() ? LLVector3(1,1,1) : getScale();
- ret.scaleVec(objScale);
-
- return ret;
-}
-
-LLVector3 LLVOVolume::volumePositionToAgent(const LLVector3& dir) const
-{
- LLVector3 ret = dir;
- LLVector3 objScale = isVolumeGlobal() ? LLVector3(1,1,1) : getScale();
- ret.scaleVec(objScale);
- ret = ret * getRenderRotation();
- ret += getRenderPosition();
-
- return ret;
-}
-
-LLVector3 LLVOVolume::volumeDirectionToAgent(const LLVector3& dir) const
-{
- LLVector3 ret = dir;
- LLVector3 objScale = isVolumeGlobal() ? LLVector3(1,1,1) : getScale();
- LLVector3 invObjScale(1.f / objScale.mV[VX], 1.f / objScale.mV[VY], 1.f / objScale.mV[VZ]);
- ret.scaleVec(invObjScale);
- ret = ret * getRenderRotation();
-
- return ret;
-}
-
-
-BOOL LLVOVolume::lineSegmentIntersect(const LLVector3& start, const LLVector3& end, S32 face, BOOL pick_transparent, S32 *face_hitp,
- LLVector3* intersection,LLVector2* tex_coord, LLVector3* normal, LLVector3* bi_normal)
-
-{
- if (!mbCanSelect
- || mDrawable->isDead()
- || !gPipeline.hasRenderType(mDrawable->getRenderType()))
- {
- return FALSE;
- }
-
- BOOL ret = FALSE;
-
- LLVolume* volume = getVolume();
- if (volume)
- {
- LLVector3 v_start, v_end, v_dir;
-
- v_start = agentPositionToVolume(start);
- v_end = agentPositionToVolume(end);
-
- LLVector3 p;
- LLVector3 n;
- LLVector2 tc;
- LLVector3 bn;
-
- if (intersection != NULL)
- {
- p = *intersection;
- }
-
- if (tex_coord != NULL)
- {
- tc = *tex_coord;
- }
-
- if (normal != NULL)
- {
- n = *normal;
- }
-
- if (bi_normal != NULL)
- {
- bn = *bi_normal;
- }
-
- S32 face_hit = -1;
-
- S32 start_face, end_face;
- if (face == -1)
- {
- start_face = 0;
- end_face = volume->getNumVolumeFaces();
- }
- else
- {
- start_face = face;
- end_face = face+1;
- }
-
- for (S32 i = start_face; i < end_face; ++i)
- {
- face_hit = volume->lineSegmentIntersect(v_start, v_end, i,
- &p, &tc, &n, &bn);
-
- if (face_hit >= 0 && mDrawable->getNumFaces() > face_hit)
- {
- LLFace* face = mDrawable->getFace(face_hit);
-
- if (pick_transparent || !face->getTexture() || !face->getTexture()->hasGLTexture() || face->getTexture()->getMask(face->surfaceToTexture(tc, p, n)))
- {
- v_end = p;
- if (face_hitp != NULL)
- {
- *face_hitp = face_hit;
- }
-
- if (intersection != NULL)
- {
- *intersection = volumePositionToAgent(p); // must map back to agent space
- }
-
- if (normal != NULL)
- {
- *normal = volumeDirectionToAgent(n);
- (*normal).normVec();
- }
-
- if (bi_normal != NULL)
- {
- *bi_normal = volumeDirectionToAgent(bn);
- (*bi_normal).normVec();
- }
-
- if (tex_coord != NULL)
- {
- *tex_coord = tc;
- }
-
- ret = TRUE;
- }
- }
- }
- }
-
- return ret;
-}
-
-U32 LLVOVolume::getPartitionType() const
-{
- if (isHUDAttachment())
- {
- return LLViewerRegion::PARTITION_HUD;
- }
-
- return LLViewerRegion::PARTITION_VOLUME;
-}
-
-LLVolumePartition::LLVolumePartition()
-: LLSpatialPartition(LLVOVolume::VERTEX_DATA_MASK, TRUE, GL_DYNAMIC_DRAW_ARB)
-{
- mLODPeriod = 32;
- mDepthMask = FALSE;
- mDrawableType = LLPipeline::RENDER_TYPE_VOLUME;
- mPartitionType = LLViewerRegion::PARTITION_VOLUME;
- mSlopRatio = 0.25f;
- mBufferUsage = GL_DYNAMIC_DRAW_ARB;
-}
-
-LLVolumeBridge::LLVolumeBridge(LLDrawable* drawablep)
-: LLSpatialBridge(drawablep, TRUE, LLVOVolume::VERTEX_DATA_MASK)
-{
- mDepthMask = FALSE;
- mLODPeriod = 32;
- mDrawableType = LLPipeline::RENDER_TYPE_VOLUME;
- mPartitionType = LLViewerRegion::PARTITION_BRIDGE;
-
- mBufferUsage = GL_DYNAMIC_DRAW_ARB;
-
- mSlopRatio = 0.25f;
-}
-
-void LLVolumeGeometryManager::registerFace(LLSpatialGroup* group, LLFace* facep, U32 type)
-{
- LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION);
-
- if (facep->getViewerObject()->isSelected() && LLSelectMgr::getInstance()->mHideSelectedObjects)
- {
- return;
- }
-
- //add face to drawmap
- LLSpatialGroup::drawmap_elem_t& draw_vec = group->mDrawMap[type];
-
- S32 idx = draw_vec.size()-1;
-
- BOOL fullbright = (type == LLRenderPass::PASS_FULLBRIGHT) ||
- (type == LLRenderPass::PASS_INVISIBLE) ||
- (type == LLRenderPass::PASS_ALPHA && facep->isState(LLFace::FULLBRIGHT));
-
- if (!fullbright && type != LLRenderPass::PASS_GLOW && !facep->mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_NORMAL))
- {
- llwarns << "Non fullbright face has no normals!" << llendl;
- return;
- }
-
- const LLMatrix4* tex_mat = NULL;
- if (facep->isState(LLFace::TEXTURE_ANIM) && facep->getVirtualSize() > MIN_TEX_ANIM_SIZE)
- {
- tex_mat = facep->mTextureMatrix;
- }
-
- const LLMatrix4* model_mat = NULL;
-
- LLDrawable* drawable = facep->getDrawable();
- if (drawable->isActive())
- {
- model_mat = &(drawable->getRenderMatrix());
- }
- else
- {
- model_mat = &(drawable->getRegion()->mRenderMatrix);
- }
-
-
- U8 bump = (type == LLRenderPass::PASS_BUMP || type == LLRenderPass::PASS_POST_BUMP) ? facep->getTextureEntry()->getBumpmap() : 0;
-
- LLViewerTexture* tex = facep->getTexture();
-
- U8 glow = (U8) (facep->getTextureEntry()->getGlow() * 255);
-
- if (facep->mVertexBuffer.isNull())
- {
- llerrs << "WTF?" << llendl;
- }
-
- if (idx >= 0 &&
- draw_vec[idx]->mVertexBuffer == facep->mVertexBuffer &&
- draw_vec[idx]->mEnd == facep->getGeomIndex()-1 &&
- (LLPipeline::sTextureBindTest || draw_vec[idx]->mTexture == tex) &&
-#if LL_DARWIN
- draw_vec[idx]->mEnd - draw_vec[idx]->mStart + facep->getGeomCount() <= (U32) gGLManager.mGLMaxVertexRange &&
- draw_vec[idx]->mCount + facep->getIndicesCount() <= (U32) gGLManager.mGLMaxIndexRange &&
-#endif
- draw_vec[idx]->mGlowColor.mV[3] == glow &&
- draw_vec[idx]->mFullbright == fullbright &&
- draw_vec[idx]->mBump == bump &&
- draw_vec[idx]->mTextureMatrix == tex_mat &&
- draw_vec[idx]->mModelMatrix == model_mat)
- {
- draw_vec[idx]->mCount += facep->getIndicesCount();
- draw_vec[idx]->mEnd += facep->getGeomCount();
- draw_vec[idx]->mVSize = llmax(draw_vec[idx]->mVSize, facep->getVirtualSize());
- validate_draw_info(*draw_vec[idx]);
- update_min_max(draw_vec[idx]->mExtents[0], draw_vec[idx]->mExtents[1], facep->mExtents[0]);
- update_min_max(draw_vec[idx]->mExtents[0], draw_vec[idx]->mExtents[1], facep->mExtents[1]);
- }
- else
- {
- U32 start = facep->getGeomIndex();
- U32 end = start + facep->getGeomCount()-1;
- U32 offset = facep->getIndicesStart();
- U32 count = facep->getIndicesCount();
- LLPointer<LLDrawInfo> draw_info = new LLDrawInfo(start,end,count,offset, tex,
- facep->mVertexBuffer, fullbright, bump);
- draw_info->mGroup = group;
- draw_info->mVSize = facep->getVirtualSize();
- draw_vec.push_back(draw_info);
- draw_info->mTextureMatrix = tex_mat;
- draw_info->mModelMatrix = model_mat;
- draw_info->mGlowColor.setVec(0,0,0,glow);
- if (type == LLRenderPass::PASS_ALPHA)
- { //for alpha sorting
- facep->setDrawInfo(draw_info);
- }
- draw_info->mExtents[0] = facep->mExtents[0];
- draw_info->mExtents[1] = facep->mExtents[1];
- validate_draw_info(*draw_info);
-
- if (LLPipeline::sUseTriStrips)
- {
- draw_info->mDrawMode = LLRender::TRIANGLE_STRIP;
- }
- }
-}
-
-void LLVolumeGeometryManager::getGeometry(LLSpatialGroup* group)
-{
-
-}
-
-static LLFastTimer::DeclareTimer FTM_REBUILD_VOLUME_VB("Volume");
-static LLFastTimer::DeclareTimer FTM_REBUILD_VBO("VBO Rebuilt");
-
-
-void LLVolumeGeometryManager::rebuildGeom(LLSpatialGroup* group)
-{
- if (group->changeLOD())
- {
- group->mLastUpdateDistance = group->mDistance;
- }
-
- group->mLastUpdateViewAngle = group->mViewAngle;
-
- if (!group->isState(LLSpatialGroup::GEOM_DIRTY | LLSpatialGroup::ALPHA_DIRTY))
- {
- if (group->isState(LLSpatialGroup::MESH_DIRTY) && !LLPipeline::sDelayVBUpdate)
- {
- LLFastTimer ftm(FTM_REBUILD_VBO);
- LLFastTimer ftm2(FTM_REBUILD_VOLUME_VB);
-
- rebuildMesh(group);
- }
- return;
- }
-
- group->mBuilt = 1.f;
- LLFastTimer ftm(FTM_REBUILD_VBO);
-
- LLFastTimer ftm2(FTM_REBUILD_VOLUME_VB);
-
- group->clearDrawMap();
-
- mFaceList.clear();
-
- std::vector<LLFace*> fullbright_faces;
- std::vector<LLFace*> bump_faces;
- std::vector<LLFace*> simple_faces;
-
- std::vector<LLFace*> alpha_faces;
- U32 useage = group->mSpatialPartition->mBufferUsage;
-
- U32 max_vertices = (gSavedSettings.getS32("RenderMaxVBOSize")*1024)/LLVertexBuffer::calcStride(group->mSpatialPartition->mVertexDataMask);
- U32 max_total = (gSavedSettings.getS32("RenderMaxNodeSize")*1024)/LLVertexBuffer::calcStride(group->mSpatialPartition->mVertexDataMask);
- max_vertices = llmin(max_vertices, (U32) 65535);
-
- U32 cur_total = 0;
-
- //get all the faces into a list
- for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter)
- {
- LLDrawable* drawablep = *drawable_iter;
-
- if (drawablep->isDead() || drawablep->isState(LLDrawable::FORCE_INVISIBLE) )
- {
- continue;
- }
-
- if (drawablep->isAnimating())
- { //fall back to stream draw for animating verts
- useage = GL_STREAM_DRAW_ARB;
- }
-
- LLVOVolume* vobj = drawablep->getVOVolume();
- llassert_always(vobj);
- vobj->updateTextureVirtualSize();
- vobj->preRebuild();
-
- drawablep->clearState(LLDrawable::HAS_ALPHA);
-
- //for each face
- for (S32 i = 0; i < drawablep->getNumFaces(); i++)
- {
- //sum up face verts and indices
- drawablep->updateFaceSize(i);
- LLFace* facep = drawablep->getFace(i);
-
- if (cur_total > max_total || facep->getIndicesCount() <= 0 || facep->getGeomCount() <= 0)
- {
- facep->mVertexBuffer = NULL;
- facep->mLastVertexBuffer = NULL;
- continue;
- }
-
- cur_total += facep->getGeomCount();
-
- if (facep->hasGeometry() && facep->mPixelArea > FORCE_CULL_AREA)
- {
- const LLTextureEntry* te = facep->getTextureEntry();
- LLViewerTexture* tex = facep->getTexture();
-
- if (facep->isState(LLFace::TEXTURE_ANIM))
- {
- if (!vobj->mTexAnimMode)
- {
- facep->clearState(LLFace::TEXTURE_ANIM);
- }
- }
-
- BOOL force_simple = (facep->mPixelArea < FORCE_SIMPLE_RENDER_AREA);
- U32 type = gPipeline.getPoolTypeFromTE(te, tex);
- if (type != LLDrawPool::POOL_ALPHA && force_simple)
- {
- type = LLDrawPool::POOL_SIMPLE;
- }
- facep->setPoolType(type);
-
- if (vobj->isHUDAttachment())
- {
- facep->setState(LLFace::FULLBRIGHT);
- }
-
- if (vobj->mTextureAnimp && vobj->mTexAnimMode)
- {
- if (vobj->mTextureAnimp->mFace <= -1)
- {
- S32 face;
- for (face = 0; face < vobj->getNumTEs(); face++)
- {
- drawablep->getFace(face)->setState(LLFace::TEXTURE_ANIM);
- }
- }
- else if (vobj->mTextureAnimp->mFace < vobj->getNumTEs())
- {
- drawablep->getFace(vobj->mTextureAnimp->mFace)->setState(LLFace::TEXTURE_ANIM);
- }
- }
-
- if (type == LLDrawPool::POOL_ALPHA)
- {
- if (facep->canRenderAsMask())
- { //can be treated as alpha mask
- simple_faces.push_back(facep);
- }
- else
- {
- drawablep->setState(LLDrawable::HAS_ALPHA);
- alpha_faces.push_back(facep);
- }
- }
- else
- {
- if (drawablep->isState(LLDrawable::REBUILD_VOLUME))
- {
- facep->mLastUpdateTime = gFrameTimeSeconds;
- }
-
- if (gPipeline.canUseWindLightShadersOnObjects()
- && LLPipeline::sRenderBump)
- {
- if (te->getBumpmap())
- { //needs normal + binormal
- bump_faces.push_back(facep);
- }
- else if (te->getShiny() || !te->getFullbright())
- { //needs normal
- simple_faces.push_back(facep);
- }
- else
- { //doesn't need normal
- facep->setState(LLFace::FULLBRIGHT);
- fullbright_faces.push_back(facep);
- }
- }
- else
- {
- if (te->getBumpmap() && LLPipeline::sRenderBump)
- { //needs normal + binormal
- bump_faces.push_back(facep);
- }
- else if ((te->getShiny() && LLPipeline::sRenderBump) ||
- !te->getFullbright())
- { //needs normal
- simple_faces.push_back(facep);
- }
- else
- { //doesn't need normal
- facep->setState(LLFace::FULLBRIGHT);
- fullbright_faces.push_back(facep);
- }
- }
- }
- }
- else
- { //face has no renderable geometry
- facep->mVertexBuffer = NULL;
- facep->mLastVertexBuffer = NULL;
- }
- }
- }
-
- group->mBufferUsage = useage;
-
- //PROCESS NON-ALPHA FACES
- U32 simple_mask = LLVertexBuffer::MAP_TEXCOORD0 | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_COLOR;
- U32 alpha_mask = simple_mask | 0x80000000; //hack to give alpha verts their own VBO
- U32 bump_mask = LLVertexBuffer::MAP_TEXCOORD0 | LLVertexBuffer::MAP_TEXCOORD1 | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_COLOR;
- U32 fullbright_mask = LLVertexBuffer::MAP_TEXCOORD0 | LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_COLOR;
-
- if (LLPipeline::sRenderDeferred)
- {
- bump_mask |= LLVertexBuffer::MAP_BINORMAL;
- }
-
- genDrawInfo(group, simple_mask, simple_faces);
- genDrawInfo(group, bump_mask, bump_faces);
- genDrawInfo(group, fullbright_mask, fullbright_faces);
- genDrawInfo(group, alpha_mask, alpha_faces, TRUE);
-
- if (!LLPipeline::sDelayVBUpdate)
- {
- //drawables have been rebuilt, clear rebuild status
- for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter)
- {
- LLDrawable* drawablep = *drawable_iter;
- drawablep->clearState(LLDrawable::REBUILD_ALL);
- }
- }
-
- group->mLastUpdateTime = gFrameTimeSeconds;
- group->mBuilt = 1.f;
- group->clearState(LLSpatialGroup::GEOM_DIRTY | LLSpatialGroup::ALPHA_DIRTY);
-
- if (LLPipeline::sDelayVBUpdate)
- {
- group->setState(LLSpatialGroup::MESH_DIRTY | LLSpatialGroup::NEW_DRAWINFO);
- }
-
- mFaceList.clear();
-}
-
-static LLFastTimer::DeclareTimer FTM_VOLUME_GEOM("Volume Geometry");
-static LLFastTimer::DeclareTimer FTM_VOLUME_GEOM_PARTIAL("Terse Rebuild");
-
-void LLVolumeGeometryManager::rebuildMesh(LLSpatialGroup* group)
-{
- llassert(group);
- if (group && group->isState(LLSpatialGroup::MESH_DIRTY) && !group->isState(LLSpatialGroup::GEOM_DIRTY))
- {
- LLFastTimer tm(FTM_VOLUME_GEOM);
- S32 num_mapped_veretx_buffer = LLVertexBuffer::sMappedCount ;
-
- group->mBuilt = 1.f;
-
- for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter)
- {
- LLFastTimer t(FTM_VOLUME_GEOM_PARTIAL);
- LLDrawable* drawablep = *drawable_iter;
-
- if (drawablep->isDead() || drawablep->isState(LLDrawable::FORCE_INVISIBLE) )
- {
- continue;
- }
-
- if (drawablep->isState(LLDrawable::REBUILD_ALL))
- {
- LLVOVolume* vobj = drawablep->getVOVolume();
- vobj->preRebuild();
- LLVolume* volume = vobj->getVolume();
- for (S32 i = 0; i < drawablep->getNumFaces(); ++i)
- {
- LLFace* face = drawablep->getFace(i);
- if (face && face->mVertexBuffer.notNull())
- {
- face->getGeometryVolume(*volume, face->getTEOffset(),
- vobj->getRelativeXform(), vobj->getRelativeXformInvTrans(), face->getGeomIndex());
- }
- }
-
- drawablep->clearState(LLDrawable::REBUILD_ALL);
- }
- }
-
- //unmap all the buffers
- for (LLSpatialGroup::buffer_map_t::iterator i = group->mBufferMap.begin(); i != group->mBufferMap.end(); ++i)
- {
- LLSpatialGroup::buffer_texture_map_t& map = i->second;
- for (LLSpatialGroup::buffer_texture_map_t::iterator j = map.begin(); j != map.end(); ++j)
- {
- LLSpatialGroup::buffer_list_t& list = j->second;
- for (LLSpatialGroup::buffer_list_t::iterator k = list.begin(); k != list.end(); ++k)
- {
- LLVertexBuffer* buffer = *k;
- if (buffer->isLocked())
- {
- buffer->setBuffer(0);
- }
- }
- }
- }
-
- // don't forget alpha
- if(group != NULL &&
- !group->mVertexBuffer.isNull() &&
- group->mVertexBuffer->isLocked())
- {
- group->mVertexBuffer->setBuffer(0);
- }
-
- //if not all buffers are unmapped
- if(num_mapped_veretx_buffer != LLVertexBuffer::sMappedCount)
- {
- llwarns << "Not all mapped vertex buffers are unmapped!" << llendl ;
- for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter)
- {
- LLDrawable* drawablep = *drawable_iter;
- for (S32 i = 0; i < drawablep->getNumFaces(); ++i)
- {
- LLFace* face = drawablep->getFace(i);
- if (face && face->mVertexBuffer.notNull() && face->mVertexBuffer->isLocked())
- {
- face->mVertexBuffer->setBuffer(0) ;
- }
- }
- }
- }
-
- group->clearState(LLSpatialGroup::MESH_DIRTY | LLSpatialGroup::NEW_DRAWINFO);
- }
-
- if (group && group->isState(LLSpatialGroup::NEW_DRAWINFO))
- {
- llerrs << "WTF?" << llendl;
- }
-}
-
-void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std::vector<LLFace*>& faces, BOOL distance_sort)
-{
- //calculate maximum number of vertices to store in a single buffer
- U32 max_vertices = (gSavedSettings.getS32("RenderMaxVBOSize")*1024)/LLVertexBuffer::calcStride(group->mSpatialPartition->mVertexDataMask);
- max_vertices = llmin(max_vertices, (U32) 65535);
-
- if (!distance_sort)
- {
- //sort faces by things that break batches
- std::sort(faces.begin(), faces.end(), LLFace::CompareBatchBreaker());
- }
- else
- {
- //sort faces by distance
- std::sort(faces.begin(), faces.end(), LLFace::CompareDistanceGreater());
- }
-
- std::vector<LLFace*>::iterator face_iter = faces.begin();
-
- LLSpatialGroup::buffer_map_t buffer_map;
-
- LLViewerTexture* last_tex = NULL;
- S32 buffer_index = 0;
-
- if (distance_sort)
- {
- buffer_index = -1;
- }
-
- while (face_iter != faces.end())
- {
- //pull off next face
- LLFace* facep = *face_iter;
- LLViewerTexture* tex = facep->getTexture();
-
- if (distance_sort)
- {
- tex = NULL;
- }
-
- if (last_tex == tex)
- {
- buffer_index++;
- }
- else
- {
- last_tex = tex;
- buffer_index = 0;
- }
-
- U32 index_count = facep->getIndicesCount();
- U32 geom_count = facep->getGeomCount();
-
- //sum up vertices needed for this texture
- std::vector<LLFace*>::iterator i = face_iter;
- ++i;
-
- while (i != faces.end() &&
- (LLPipeline::sTextureBindTest || (distance_sort || (*i)->getTexture() == tex)))
- {
- facep = *i;
-
- if (geom_count + facep->getGeomCount() > max_vertices)
- { //cut vertex buffers on geom count too big
- break;
- }
-
- ++i;
- index_count += facep->getIndicesCount();
- geom_count += facep->getGeomCount();
- }
-
- //create/delete/resize vertex buffer if needed
- LLVertexBuffer* buffer = NULL;
- LLSpatialGroup::buffer_texture_map_t::iterator found_iter = group->mBufferMap[mask].find(tex);
-
- if (found_iter != group->mBufferMap[mask].end())
- {
- if ((U32) buffer_index < found_iter->second.size())
- {
- buffer = found_iter->second[buffer_index];
- }
- }
-
- if (!buffer)
- { //create new buffer if needed
- buffer = createVertexBuffer(mask,
- group->mBufferUsage);
- buffer->allocateBuffer(geom_count, index_count, TRUE);
- }
- else
- {
- if (LLVertexBuffer::sEnableVBOs && buffer->getUsage() != group->mBufferUsage)
- {
- buffer = createVertexBuffer(group->mSpatialPartition->mVertexDataMask,
- group->mBufferUsage);
- buffer->allocateBuffer(geom_count, index_count, TRUE);
- }
- else
- {
- buffer->resizeBuffer(geom_count, index_count);
- }
- }
-
- buffer_map[mask][tex].push_back(buffer);
-
- //add face geometry
-
- U32 indices_index = 0;
- U16 index_offset = 0;
-
- while (face_iter < i)
- {
- facep = *face_iter;
- facep->mIndicesIndex = indices_index;
- facep->mGeomIndex = index_offset;
- facep->mVertexBuffer = buffer;
- {
- facep->updateRebuildFlags();
- if (!LLPipeline::sDelayVBUpdate)
- {
- LLDrawable* drawablep = facep->getDrawable();
- LLVOVolume* vobj = drawablep->getVOVolume();
- LLVolume* volume = vobj->getVolume();
-
- U32 te_idx = facep->getTEOffset();
-
- if (facep->getGeometryVolume(*volume, te_idx,
- vobj->getRelativeXform(), vobj->getRelativeXformInvTrans(), index_offset))
- {
- buffer->markDirty(facep->getGeomIndex(), facep->getGeomCount(),
- facep->getIndicesStart(), facep->getIndicesCount());
- }
- }
- }
-
- index_offset += facep->getGeomCount();
- indices_index += facep->mIndicesCount;
-
- BOOL force_simple = facep->mPixelArea < FORCE_SIMPLE_RENDER_AREA;
- BOOL fullbright = facep->isState(LLFace::FULLBRIGHT);
- if ((mask & LLVertexBuffer::MAP_NORMAL) == 0)
- { //paranoia check to make sure GL doesn't try to read non-existant normals
- fullbright = TRUE;
- }
-
- const LLTextureEntry* te = facep->getTextureEntry();
-
- BOOL is_alpha = (facep->getPoolType() == LLDrawPool::POOL_ALPHA) ? TRUE : FALSE;
-
- if (is_alpha)
- {
- // can we safely treat this as an alpha mask?
- if (facep->canRenderAsMask())
- {
- if (te->getFullbright())
- {
- registerFace(group, facep, LLRenderPass::PASS_FULLBRIGHT_ALPHA_MASK);
- }
- else
- {
- registerFace(group, facep, LLRenderPass::PASS_ALPHA_MASK);
- }
- }
- else
- {
- registerFace(group, facep, LLRenderPass::PASS_ALPHA);
- }
-
- if (LLPipeline::sRenderDeferred)
- {
- registerFace(group, facep, LLRenderPass::PASS_ALPHA_SHADOW);
- }
- }
- else if (gPipeline.canUseVertexShaders()
- && group->mSpatialPartition->mPartitionType != LLViewerRegion::PARTITION_HUD
- && LLPipeline::sRenderBump
- && te->getShiny())
- { //shiny
- if (tex->getPrimaryFormat() == GL_ALPHA)
- { //invisiprim+shiny
- registerFace(group, facep, LLRenderPass::PASS_INVISI_SHINY);
- registerFace(group, facep, LLRenderPass::PASS_INVISIBLE);
- }
- else if (LLPipeline::sRenderDeferred)
- { //deferred rendering
- if (te->getFullbright())
- { //register in post deferred fullbright shiny pass
- registerFace(group, facep, LLRenderPass::PASS_FULLBRIGHT_SHINY);
- if (te->getBumpmap())
- { //register in post deferred bump pass
- registerFace(group, facep, LLRenderPass::PASS_POST_BUMP);
- }
- }
- else if (te->getBumpmap())
- { //register in deferred bump pass
- registerFace(group, facep, LLRenderPass::PASS_BUMP);
- }
- else
- { //register in deferred simple pass (deferred simple includes shiny)
- llassert(mask & LLVertexBuffer::MAP_NORMAL);
- registerFace(group, facep, LLRenderPass::PASS_SIMPLE);
- }
- }
- else if (fullbright)
- { //not deferred, register in standard fullbright shiny pass
- registerFace(group, facep, LLRenderPass::PASS_FULLBRIGHT_SHINY);
- }
- else
- { //not deferred or fullbright, register in standard shiny pass
- registerFace(group, facep, LLRenderPass::PASS_SHINY);
- }
- }
- else
- { //not alpha and not shiny
- if (!is_alpha && tex->getPrimaryFormat() == GL_ALPHA)
- { //invisiprim
- registerFace(group, facep, LLRenderPass::PASS_INVISIBLE);
- }
- else if (fullbright)
- { //fullbright
- registerFace(group, facep, LLRenderPass::PASS_FULLBRIGHT);
- if (LLPipeline::sRenderDeferred && LLPipeline::sRenderBump && te->getBumpmap())
- { //if this is the deferred render and a bump map is present, register in post deferred bump
- registerFace(group, facep, LLRenderPass::PASS_POST_BUMP);
- }
- }
- else
- {
- if (LLPipeline::sRenderDeferred && LLPipeline::sRenderBump && te->getBumpmap())
- { //non-shiny or fullbright deferred bump
- registerFace(group, facep, LLRenderPass::PASS_BUMP);
- }
- else
- { //all around simple
- llassert(mask & LLVertexBuffer::MAP_NORMAL);
- registerFace(group, facep, LLRenderPass::PASS_SIMPLE);
- }
- }
-
- //not sure why this is here -- shiny HUD attachments maybe? -- davep 5/11/2010
- if (!is_alpha && te->getShiny() && LLPipeline::sRenderBump)
- {
- registerFace(group, facep, LLRenderPass::PASS_SHINY);
- }
- }
-
- //not sure why this is here, and looks like it might cause bump mapped objects to get rendered redundantly -- davep 5/11/2010
- if (!is_alpha && !LLPipeline::sRenderDeferred)
- {
- llassert((mask & LLVertexBuffer::MAP_NORMAL) || fullbright);
- facep->setPoolType((fullbright) ? LLDrawPool::POOL_FULLBRIGHT : LLDrawPool::POOL_SIMPLE);
-
- if (!force_simple && te->getBumpmap() && LLPipeline::sRenderBump)
- {
- registerFace(group, facep, LLRenderPass::PASS_BUMP);
- }
- }
-
- if (!is_alpha && LLPipeline::sRenderGlow && te->getGlow() > 0.f)
- {
- registerFace(group, facep, LLRenderPass::PASS_GLOW);
- }
-
- ++face_iter;
- }
-
- buffer->setBuffer(0);
- }
-
- group->mBufferMap[mask].clear();
- for (LLSpatialGroup::buffer_texture_map_t::iterator i = buffer_map[mask].begin(); i != buffer_map[mask].end(); ++i)
- {
- group->mBufferMap[mask][i->first] = i->second;
- }
-}
-
-void LLGeometryManager::addGeometryCount(LLSpatialGroup* group, U32 &vertex_count, U32 &index_count)
-{
- //initialize to default usage for this partition
- U32 usage = group->mSpatialPartition->mBufferUsage;
-
- //clear off any old faces
- mFaceList.clear();
-
- //for each drawable
- for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter)
- {
- LLDrawable* drawablep = *drawable_iter;
-
- if (drawablep->isDead())
- {
- continue;
- }
-
- if (drawablep->isAnimating())
- { //fall back to stream draw for animating verts
- usage = GL_STREAM_DRAW_ARB;
- }
-
- //for each face
- for (S32 i = 0; i < drawablep->getNumFaces(); i++)
- {
- //sum up face verts and indices
- drawablep->updateFaceSize(i);
- LLFace* facep = drawablep->getFace(i);
- if (facep->hasGeometry() && facep->mPixelArea > FORCE_CULL_AREA)
- {
- vertex_count += facep->getGeomCount();
- index_count += facep->getIndicesCount();
-
- //remember face (for sorting)
- mFaceList.push_back(facep);
- }
- else
- {
- facep->mVertexBuffer = NULL;
- facep->mLastVertexBuffer = NULL;
- }
- }
- }
-
- group->mBufferUsage = usage;
-}
-
-LLHUDPartition::LLHUDPartition()
-{
- mPartitionType = LLViewerRegion::PARTITION_HUD;
- mDrawableType = LLPipeline::RENDER_TYPE_HUD;
- mSlopRatio = 0.f;
- mLODPeriod = 1;
-}
-
-void LLHUDPartition::shift(const LLVector3 &offset)
-{
- //HUD objects don't shift with region crossing. That would be silly.
-}
-
-
+/**
+ * @file llvovolume.cpp
+ * @brief LLVOVolume class implementation
+ *
+ * $LicenseInfo:firstyear=2001&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+// A "volume" is a box, cylinder, sphere, or other primitive shape.
+
+#include "llviewerprecompiledheaders.h"
+
+#include "llvovolume.h"
+
+#include <sstream>
+
+#include "llviewercontrol.h"
+#include "lldir.h"
+#include "llflexibleobject.h"
+#include "llfloatertools.h"
+#include "llmaterialtable.h"
+#include "llprimitive.h"
+#include "llvolume.h"
+#include "llvolumeoctree.h"
+#include "llvolumemgr.h"
+#include "llvolumemessage.h"
+#include "material_codes.h"
+#include "message.h"
+#include "llpluginclassmedia.h" // for code in the mediaEvent handler
+#include "object_flags.h"
+#include "llagentconstants.h"
+#include "lldrawable.h"
+#include "lldrawpoolavatar.h"
+#include "lldrawpoolbump.h"
+#include "llface.h"
+#include "llspatialpartition.h"
+#include "llhudmanager.h"
+#include "llflexibleobject.h"
+#include "llsky.h"
+#include "lltexturefetch.h"
+#include "llvector4a.h"
+#include "llviewercamera.h"
+#include "llviewertexturelist.h"
+#include "llviewerobjectlist.h"
+#include "llviewerregion.h"
+#include "llviewertextureanim.h"
+#include "llworld.h"
+#include "llselectmgr.h"
+#include "pipeline.h"
+#include "llsdutil.h"
+#include "llmatrix4a.h"
+#include "llmediaentry.h"
+#include "llmediadataclient.h"
+#include "llmeshrepository.h"
+#include "llagent.h"
+#include "llviewermediafocus.h"
+#include "llvoavatar.h"
+
+const S32 MIN_QUIET_FRAMES_COALESCE = 30;
+const F32 FORCE_SIMPLE_RENDER_AREA = 512.f;
+const F32 FORCE_CULL_AREA = 8.f;
+const F32 MAX_LOD_DISTANCE = 24.f;
+
+
+BOOL gAnimateTextures = TRUE;
+//extern BOOL gHideSelectedObjects;
+
+F32 LLVOVolume::sLODFactor = 1.f;
+F32 LLVOVolume::sLODSlopDistanceFactor = 0.5f; //Changing this to zero, effectively disables the LOD transition slop
+F32 LLVOVolume::sDistanceFactor = 1.0f;
+S32 LLVOVolume::sNumLODChanges = 0;
+LLPointer<LLObjectMediaDataClient> LLVOVolume::sObjectMediaClient = NULL;
+LLPointer<LLObjectMediaNavigateClient> LLVOVolume::sObjectMediaNavigateClient = NULL;
+
+static LLFastTimer::DeclareTimer FTM_GEN_TRIANGLES("Generate Triangles");
+static LLFastTimer::DeclareTimer FTM_GEN_VOLUME("Generate Volumes");
+static LLFastTimer::DeclareTimer FTM_VOLUME_TEXTURES("Volume Textures");
+
+// Implementation class of LLMediaDataClientObject. See llmediadataclient.h
+class LLMediaDataClientObjectImpl : public LLMediaDataClientObject
+{
+public:
+ LLMediaDataClientObjectImpl(LLVOVolume *obj, bool isNew) : mObject(obj), mNew(isNew)
+ {
+ mObject->addMDCImpl();
+ }
+ ~LLMediaDataClientObjectImpl()
+ {
+ mObject->removeMDCImpl();
+ }
+
+ virtual U8 getMediaDataCount() const
+ { return mObject->getNumTEs(); }
+
+ virtual LLSD getMediaDataLLSD(U8 index) const
+ {
+ LLSD result;
+ LLTextureEntry *te = mObject->getTE(index);
+ if (NULL != te)
+ {
+ llassert((te->getMediaData() != NULL) == te->hasMedia());
+ if (te->getMediaData() != NULL)
+ {
+ result = te->getMediaData()->asLLSD();
+ // XXX HACK: workaround bug in asLLSD() where whitelist is not set properly
+ // See DEV-41949
+ if (!result.has(LLMediaEntry::WHITELIST_KEY))
+ {
+ result[LLMediaEntry::WHITELIST_KEY] = LLSD::emptyArray();
+ }
+ }
+ }
+ return result;
+ }
+ virtual bool isCurrentMediaUrl(U8 index, const std::string &url) const
+ {
+ LLTextureEntry *te = mObject->getTE(index);
+ if (te)
+ {
+ if (te->getMediaData())
+ {
+ return (te->getMediaData()->getCurrentURL() == url);
+ }
+ }
+ return url.empty();
+ }
+
+ virtual LLUUID getID() const
+ { return mObject->getID(); }
+
+ virtual void mediaNavigateBounceBack(U8 index)
+ { mObject->mediaNavigateBounceBack(index); }
+
+ virtual bool hasMedia() const
+ { return mObject->hasMedia(); }
+
+ virtual void updateObjectMediaData(LLSD const &data, const std::string &version_string)
+ { mObject->updateObjectMediaData(data, version_string); }
+
+ virtual F64 getMediaInterest() const
+ {
+ F64 interest = mObject->getTotalMediaInterest();
+ if (interest < (F64)0.0)
+ {
+ // media interest not valid yet, try pixel area
+ interest = mObject->getPixelArea();
+ // HACK: force recalculation of pixel area if interest is the "magic default" of 1024.
+ if (interest == 1024.f)
+ {
+ const_cast<LLVOVolume*>(static_cast<LLVOVolume*>(mObject))->setPixelAreaAndAngle(gAgent);
+ interest = mObject->getPixelArea();
+ }
+ }
+ return interest;
+ }
+
+ virtual bool isInterestingEnough() const
+ {
+ return LLViewerMedia::isInterestingEnough(mObject, getMediaInterest());
+ }
+
+ virtual std::string getCapabilityUrl(const std::string &name) const
+ { return mObject->getRegion()->getCapability(name); }
+
+ virtual bool isDead() const
+ { return mObject->isDead(); }
+
+ virtual U32 getMediaVersion() const
+ { return LLTextureEntry::getVersionFromMediaVersionString(mObject->getMediaURL()); }
+
+ virtual bool isNew() const
+ { return mNew; }
+
+private:
+ LLPointer<LLVOVolume> mObject;
+ bool mNew;
+};
+
+
+LLVOVolume::LLVOVolume(const LLUUID &id, const LLPCode pcode, LLViewerRegion *regionp)
+ : LLViewerObject(id, pcode, regionp),
+ mVolumeImpl(NULL)
+{
+ mTexAnimMode = 0;
+ mRelativeXform.setIdentity();
+ mRelativeXformInvTrans.setIdentity();
+
+ mFaceMappingChanged = FALSE;
+ mLOD = MIN_LOD;
+ mTextureAnimp = NULL;
+ mVolumeChanged = FALSE;
+ mVObjRadius = LLVector3(1,1,0.5f).length();
+ mNumFaces = 0;
+ mLODChanged = FALSE;
+ mSculptChanged = FALSE;
+ mSpotLightPriority = 0.f;
+
+ mMediaImplList.resize(getNumTEs());
+ mLastFetchedMediaVersion = -1;
+ mIndexInTex = 0;
+ mMDCImplCount = 0;
+}
+
+LLVOVolume::~LLVOVolume()
+{
+ delete mTextureAnimp;
+ mTextureAnimp = NULL;
+ delete mVolumeImpl;
+ mVolumeImpl = NULL;
+
+ if(!mMediaImplList.empty())
+ {
+ for(U32 i = 0 ; i < mMediaImplList.size() ; i++)
+ {
+ if(mMediaImplList[i].notNull())
+ {
+ mMediaImplList[i]->removeObject(this) ;
+ }
+ }
+ }
+}
+
+void LLVOVolume::markDead()
+{
+ if (!mDead)
+ {
+ if(getMDCImplCount() > 0)
+ {
+ LLMediaDataClientObject::ptr_t obj = new LLMediaDataClientObjectImpl(const_cast<LLVOVolume*>(this), false);
+ if (sObjectMediaClient) sObjectMediaClient->removeFromQueue(obj);
+ if (sObjectMediaNavigateClient) sObjectMediaNavigateClient->removeFromQueue(obj);
+ }
+
+ // Detach all media impls from this object
+ for(U32 i = 0 ; i < mMediaImplList.size() ; i++)
+ {
+ removeMediaImpl(i);
+ }
+
+ if (mSculptTexture.notNull())
+ {
+ mSculptTexture->removeVolume(this);
+ }
+ }
+
+ LLViewerObject::markDead();
+}
+
+
+// static
+void LLVOVolume::initClass()
+{
+ // gSavedSettings better be around
+ if (gSavedSettings.getBOOL("PrimMediaMasterEnabled"))
+ {
+ const F32 queue_timer_delay = gSavedSettings.getF32("PrimMediaRequestQueueDelay");
+ const F32 retry_timer_delay = gSavedSettings.getF32("PrimMediaRetryTimerDelay");
+ const U32 max_retries = gSavedSettings.getU32("PrimMediaMaxRetries");
+ const U32 max_sorted_queue_size = gSavedSettings.getU32("PrimMediaMaxSortedQueueSize");
+ const U32 max_round_robin_queue_size = gSavedSettings.getU32("PrimMediaMaxRoundRobinQueueSize");
+ sObjectMediaClient = new LLObjectMediaDataClient(queue_timer_delay, retry_timer_delay, max_retries,
+ max_sorted_queue_size, max_round_robin_queue_size);
+ sObjectMediaNavigateClient = new LLObjectMediaNavigateClient(queue_timer_delay, retry_timer_delay,
+ max_retries, max_sorted_queue_size, max_round_robin_queue_size);
+ }
+}
+
+// static
+void LLVOVolume::cleanupClass()
+{
+ sObjectMediaClient = NULL;
+ sObjectMediaNavigateClient = NULL;
+}
+
+U32 LLVOVolume::processUpdateMessage(LLMessageSystem *mesgsys,
+ void **user_data,
+ U32 block_num, EObjectUpdateType update_type,
+ LLDataPacker *dp)
+{
+ LLColor4U color;
+ const S32 teDirtyBits = (TEM_CHANGE_TEXTURE|TEM_CHANGE_COLOR|TEM_CHANGE_MEDIA);
+
+ // Do base class updates...
+ U32 retval = LLViewerObject::processUpdateMessage(mesgsys, user_data, block_num, update_type, dp);
+
+ LLUUID sculpt_id;
+ U8 sculpt_type = 0;
+ if (isSculpted())
+ {
+ LLSculptParams *sculpt_params = (LLSculptParams *)getParameterEntry(LLNetworkData::PARAMS_SCULPT);
+ sculpt_id = sculpt_params->getSculptTexture();
+ sculpt_type = sculpt_params->getSculptType();
+ }
+
+ if (!dp)
+ {
+ if (update_type == OUT_FULL)
+ {
+ ////////////////////////////////
+ //
+ // Unpack texture animation data
+ //
+ //
+
+ if (mesgsys->getSizeFast(_PREHASH_ObjectData, block_num, _PREHASH_TextureAnim))
+ {
+ if (!mTextureAnimp)
+ {
+ mTextureAnimp = new LLViewerTextureAnim();
+ }
+ else
+ {
+ if (!(mTextureAnimp->mMode & LLTextureAnim::SMOOTH))
+ {
+ mTextureAnimp->reset();
+ }
+ }
+ mTexAnimMode = 0;
+ mTextureAnimp->unpackTAMessage(mesgsys, block_num);
+ }
+ else
+ {
+ if (mTextureAnimp)
+ {
+ delete mTextureAnimp;
+ mTextureAnimp = NULL;
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ mTexAnimMode = 0;
+ }
+ }
+
+ // Unpack volume data
+ LLVolumeParams volume_params;
+ LLVolumeMessage::unpackVolumeParams(&volume_params, mesgsys, _PREHASH_ObjectData, block_num);
+ volume_params.setSculptID(sculpt_id, sculpt_type);
+
+ if (setVolume(volume_params, 0))
+ {
+ markForUpdate(TRUE);
+ }
+ }
+
+ // Sigh, this needs to be done AFTER the volume is set as well, otherwise bad stuff happens...
+ ////////////////////////////
+ //
+ // Unpack texture entry data
+ //
+ S32 result = unpackTEMessage(mesgsys, _PREHASH_ObjectData, block_num);
+ if (result & teDirtyBits)
+ {
+ updateTEData();
+ }
+ if (result & TEM_CHANGE_MEDIA)
+ {
+ retval |= MEDIA_FLAGS_CHANGED;
+ }
+ }
+ else
+ {
+ // CORY TO DO: Figure out how to get the value here
+ if (update_type != OUT_TERSE_IMPROVED)
+ {
+ LLVolumeParams volume_params;
+ BOOL res = LLVolumeMessage::unpackVolumeParams(&volume_params, *dp);
+ if (!res)
+ {
+ llwarns << "Bogus volume parameters in object " << getID() << llendl;
+ llwarns << getRegion()->getOriginGlobal() << llendl;
+ }
+
+ volume_params.setSculptID(sculpt_id, sculpt_type);
+
+ if (setVolume(volume_params, 0))
+ {
+ markForUpdate(TRUE);
+ }
+ S32 res2 = unpackTEMessage(*dp);
+ if (TEM_INVALID == res2)
+ {
+ // There's something bogus in the data that we're unpacking.
+ dp->dumpBufferToLog();
+ llwarns << "Flushing cache files" << llendl;
+
+ if(LLVOCache::hasInstance() && getRegion())
+ {
+ LLVOCache::getInstance()->removeEntry(getRegion()->getHandle()) ;
+ }
+
+ llwarns << "Bogus TE data in " << getID() << llendl;
+ }
+ else
+ {
+ if (res2 & teDirtyBits)
+ {
+ updateTEData();
+ }
+ if (res2 & TEM_CHANGE_MEDIA)
+ {
+ retval |= MEDIA_FLAGS_CHANGED;
+ }
+ }
+
+ U32 value = dp->getPassFlags();
+
+ if (value & 0x40)
+ {
+ if (!mTextureAnimp)
+ {
+ mTextureAnimp = new LLViewerTextureAnim();
+ }
+ else
+ {
+ if (!(mTextureAnimp->mMode & LLTextureAnim::SMOOTH))
+ {
+ mTextureAnimp->reset();
+ }
+ }
+ mTexAnimMode = 0;
+ mTextureAnimp->unpackTAMessage(*dp);
+ }
+ else if (mTextureAnimp)
+ {
+ delete mTextureAnimp;
+ mTextureAnimp = NULL;
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ mTexAnimMode = 0;
+ }
+ }
+ else
+ {
+ S32 texture_length = mesgsys->getSizeFast(_PREHASH_ObjectData, block_num, _PREHASH_TextureEntry);
+ if (texture_length)
+ {
+ U8 tdpbuffer[1024];
+ LLDataPackerBinaryBuffer tdp(tdpbuffer, 1024);
+ mesgsys->getBinaryDataFast(_PREHASH_ObjectData, _PREHASH_TextureEntry, tdpbuffer, 0, block_num);
+ S32 result = unpackTEMessage(tdp);
+ if (result & teDirtyBits)
+ {
+ updateTEData();
+ }
+ if (result & TEM_CHANGE_MEDIA)
+ {
+ retval |= MEDIA_FLAGS_CHANGED;
+ }
+ }
+ }
+ }
+ if (retval & (MEDIA_URL_REMOVED | MEDIA_URL_ADDED | MEDIA_URL_UPDATED | MEDIA_FLAGS_CHANGED))
+ {
+ // If only the media URL changed, and it isn't a media version URL,
+ // ignore it
+ if ( ! ( retval & (MEDIA_URL_ADDED | MEDIA_URL_UPDATED) &&
+ mMedia && ! mMedia->mMediaURL.empty() &&
+ ! LLTextureEntry::isMediaVersionString(mMedia->mMediaURL) ) )
+ {
+ // If the media changed at all, request new media data
+ LL_DEBUGS("MediaOnAPrim") << "Media update: " << getID() << ": retval=" << retval << " Media URL: " <<
+ ((mMedia) ? mMedia->mMediaURL : std::string("")) << LL_ENDL;
+ requestMediaDataUpdate(retval & MEDIA_FLAGS_CHANGED);
+ }
+ else {
+ LL_INFOS("MediaOnAPrim") << "Ignoring media update for: " << getID() << " Media URL: " <<
+ ((mMedia) ? mMedia->mMediaURL : std::string("")) << LL_ENDL;
+ }
+ }
+ // ...and clean up any media impls
+ cleanUpMediaImpls();
+
+ return retval;
+}
+
+
+void LLVOVolume::animateTextures()
+{
+ F32 off_s = 0.f, off_t = 0.f, scale_s = 1.f, scale_t = 1.f, rot = 0.f;
+ S32 result = mTextureAnimp->animateTextures(off_s, off_t, scale_s, scale_t, rot);
+
+ if (result)
+ {
+ if (!mTexAnimMode)
+ {
+ mFaceMappingChanged = TRUE;
+ gPipeline.markTextured(mDrawable);
+ }
+ mTexAnimMode = result | mTextureAnimp->mMode;
+
+ S32 start=0, end=mDrawable->getNumFaces()-1;
+ if (mTextureAnimp->mFace >= 0 && mTextureAnimp->mFace <= end)
+ {
+ start = end = mTextureAnimp->mFace;
+ }
+
+ for (S32 i = start; i <= end; i++)
+ {
+ LLFace* facep = mDrawable->getFace(i);
+ if(facep->getVirtualSize() <= MIN_TEX_ANIM_SIZE && facep->mTextureMatrix) continue;
+
+ const LLTextureEntry* te = facep->getTextureEntry();
+
+ if (!te)
+ {
+ continue;
+ }
+
+ if (!(result & LLViewerTextureAnim::ROTATE))
+ {
+ te->getRotation(&rot);
+ }
+ if (!(result & LLViewerTextureAnim::TRANSLATE))
+ {
+ te->getOffset(&off_s,&off_t);
+ }
+ if (!(result & LLViewerTextureAnim::SCALE))
+ {
+ te->getScale(&scale_s, &scale_t);
+ }
+
+ if (!facep->mTextureMatrix)
+ {
+ facep->mTextureMatrix = new LLMatrix4();
+ }
+
+ LLMatrix4& tex_mat = *facep->mTextureMatrix;
+ tex_mat.setIdentity();
+ LLVector3 trans ;
+
+ if(facep->isAtlasInUse())
+ {
+ //
+ //if use atlas for animated texture
+ //apply the following transform to the animation matrix.
+ //
+
+ F32 tcoord_xoffset = 0.f ;
+ F32 tcoord_yoffset = 0.f ;
+ F32 tcoord_xscale = 1.f ;
+ F32 tcoord_yscale = 1.f ;
+ if(facep->isAtlasInUse())
+ {
+ const LLVector2* tmp = facep->getTexCoordOffset() ;
+ tcoord_xoffset = tmp->mV[0] ;
+ tcoord_yoffset = tmp->mV[1] ;
+
+ tmp = facep->getTexCoordScale() ;
+ tcoord_xscale = tmp->mV[0] ;
+ tcoord_yscale = tmp->mV[1] ;
+ }
+ trans.set(LLVector3(tcoord_xoffset + tcoord_xscale * (off_s+0.5f), tcoord_yoffset + tcoord_yscale * (off_t+0.5f), 0.f));
+
+ tex_mat.translate(LLVector3(-(tcoord_xoffset + tcoord_xscale * 0.5f), -(tcoord_yoffset + tcoord_yscale * 0.5f), 0.f));
+ }
+ else //non atlas
+ {
+ trans.set(LLVector3(off_s+0.5f, off_t+0.5f, 0.f));
+ tex_mat.translate(LLVector3(-0.5f, -0.5f, 0.f));
+ }
+
+ LLVector3 scale(scale_s, scale_t, 1.f);
+ LLQuaternion quat;
+ quat.setQuat(rot, 0, 0, -1.f);
+
+ tex_mat.rotate(quat);
+
+ LLMatrix4 mat;
+ mat.initAll(scale, LLQuaternion(), LLVector3());
+ tex_mat *= mat;
+
+ tex_mat.translate(trans);
+ }
+ }
+ else
+ {
+ if (mTexAnimMode && mTextureAnimp->mRate == 0)
+ {
+ U8 start, count;
+
+ if (mTextureAnimp->mFace == -1)
+ {
+ start = 0;
+ count = getNumTEs();
+ }
+ else
+ {
+ start = (U8) mTextureAnimp->mFace;
+ count = 1;
+ }
+
+ for (S32 i = start; i < start + count; i++)
+ {
+ if (mTexAnimMode & LLViewerTextureAnim::TRANSLATE)
+ {
+ setTEOffset(i, mTextureAnimp->mOffS, mTextureAnimp->mOffT);
+ }
+ if (mTexAnimMode & LLViewerTextureAnim::SCALE)
+ {
+ setTEScale(i, mTextureAnimp->mScaleS, mTextureAnimp->mScaleT);
+ }
+ if (mTexAnimMode & LLViewerTextureAnim::ROTATE)
+ {
+ setTERotation(i, mTextureAnimp->mRot);
+ }
+ }
+
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ mTexAnimMode = 0;
+ }
+ }
+}
+BOOL LLVOVolume::idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time)
+{
+ LLViewerObject::idleUpdate(agent, world, time);
+
+ static LLFastTimer::DeclareTimer ftm("Volume");
+ LLFastTimer t(ftm);
+
+ if (mDead || mDrawable.isNull())
+ {
+ return TRUE;
+ }
+
+ ///////////////////////
+ //
+ // Do texture animation stuff
+ //
+
+ if (mTextureAnimp && gAnimateTextures)
+ {
+ animateTextures();
+ }
+
+ // Dispatch to implementation
+ if (mVolumeImpl)
+ {
+ mVolumeImpl->doIdleUpdate(agent, world, time);
+ }
+
+ const S32 MAX_ACTIVE_OBJECT_QUIET_FRAMES = 40;
+
+ if (mDrawable->isActive())
+ {
+ if (mDrawable->isRoot() &&
+ mDrawable->mQuietCount++ > MAX_ACTIVE_OBJECT_QUIET_FRAMES &&
+ (!mDrawable->getParent() || !mDrawable->getParent()->isActive()))
+ {
+ mDrawable->makeStatic();
+ }
+ }
+
+ return TRUE;
+}
+
+void LLVOVolume::updateTextures()
+{
+ const F32 TEXTURE_AREA_REFRESH_TIME = 5.f; // seconds
+ if (mTextureUpdateTimer.getElapsedTimeF32() > TEXTURE_AREA_REFRESH_TIME)
+ {
+ updateTextureVirtualSize();
+ }
+}
+
+BOOL LLVOVolume::isVisible() const
+{
+ if(mDrawable.notNull() && mDrawable->isVisible())
+ {
+ return TRUE ;
+ }
+
+ if(isAttachment())
+ {
+ LLViewerObject* objp = (LLViewerObject*)getParent() ;
+ while(objp && !objp->isAvatar())
+ {
+ objp = (LLViewerObject*)objp->getParent() ;
+ }
+
+ return objp && objp->mDrawable.notNull() && objp->mDrawable->isVisible() ;
+ }
+
+ return FALSE ;
+}
+
+void LLVOVolume::updateTextureVirtualSize()
+{
+ LLFastTimer ftm(FTM_VOLUME_TEXTURES);
+ // Update the pixel area of all faces
+
+ if(!isVisible())
+ {
+ return ;
+ }
+
+ if (!gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_SIMPLE))
+ {
+ return;
+ }
+
+ static LLCachedControl<bool> dont_load_textures(gSavedSettings,"TextureDisable");
+
+ if (dont_load_textures || LLAppViewer::getTextureFetch()->mDebugPause) // || !mDrawable->isVisible())
+ {
+ return;
+ }
+
+ mTextureUpdateTimer.reset();
+
+ F32 old_area = mPixelArea;
+ mPixelArea = 0.f;
+
+ const S32 num_faces = mDrawable->getNumFaces();
+ F32 min_vsize=999999999.f, max_vsize=0.f;
+ LLViewerCamera* camera = LLViewerCamera::getInstance();
+ for (S32 i = 0; i < num_faces; i++)
+ {
+ LLFace* face = mDrawable->getFace(i);
+ const LLTextureEntry *te = face->getTextureEntry();
+ LLViewerTexture *imagep = face->getTexture();
+ if (!imagep || !te ||
+ face->mExtents[0].equals3(face->mExtents[1]))
+ {
+ continue;
+ }
+
+ F32 vsize;
+ F32 old_size = face->getVirtualSize();
+
+ if (isHUDAttachment())
+ {
+ F32 area = (F32) camera->getScreenPixelArea();
+ vsize = area;
+ imagep->setBoostLevel(LLViewerTexture::BOOST_HUD);
+ face->setPixelArea(area); // treat as full screen
+ face->setVirtualSize(vsize);
+ }
+ else
+ {
+ vsize = face->getTextureVirtualSize();
+ }
+
+ mPixelArea = llmax(mPixelArea, face->getPixelArea());
+
+ if (face->mTextureMatrix != NULL)
+ {
+ if ((vsize < MIN_TEX_ANIM_SIZE && old_size > MIN_TEX_ANIM_SIZE) ||
+ (vsize > MIN_TEX_ANIM_SIZE && old_size < MIN_TEX_ANIM_SIZE))
+ {
+ gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_TCOORD, FALSE);
+ }
+ }
+
+ if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_AREA))
+ {
+ if (vsize < min_vsize) min_vsize = vsize;
+ if (vsize > max_vsize) max_vsize = vsize;
+ }
+ else if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_PRIORITY))
+ {
+ LLViewerFetchedTexture* img = LLViewerTextureManager::staticCastToFetchedTexture(imagep) ;
+ if(img)
+ {
+ F32 pri = img->getDecodePriority();
+ pri = llmax(pri, 0.0f);
+ if (pri < min_vsize) min_vsize = pri;
+ if (pri > max_vsize) max_vsize = pri;
+ }
+ }
+ else if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_FACE_AREA))
+ {
+ F32 pri = mPixelArea;
+ if (pri < min_vsize) min_vsize = pri;
+ if (pri > max_vsize) max_vsize = pri;
+ }
+ }
+
+ if (isSculpted())
+ {
+ LLSculptParams *sculpt_params = (LLSculptParams *)getParameterEntry(LLNetworkData::PARAMS_SCULPT);
+ LLUUID id = sculpt_params->getSculptTexture();
+
+ updateSculptTexture();
+
+
+
+ if (mSculptTexture.notNull())
+ {
+ mSculptTexture->setBoostLevel(llmax((S32)mSculptTexture->getBoostLevel(),
+ (S32)LLViewerTexture::BOOST_SCULPTED));
+ mSculptTexture->setForSculpt() ;
+
+ if(!mSculptTexture->isCachedRawImageReady())
+ {
+ S32 lod = llmin(mLOD, 3);
+ F32 lodf = ((F32)(lod + 1.0f)/4.f);
+ F32 tex_size = lodf * LLViewerTexture::sMaxSculptRez ;
+ mSculptTexture->addTextureStats(2.f * tex_size * tex_size, FALSE);
+
+ //if the sculpty very close to the view point, load first
+ {
+ LLVector3 lookAt = getPositionAgent() - camera->getOrigin();
+ F32 dist = lookAt.normVec() ;
+ F32 cos_angle_to_view_dir = lookAt * camera->getXAxis() ;
+ mSculptTexture->setAdditionalDecodePriority(0.8f * LLFace::calcImportanceToCamera(cos_angle_to_view_dir, dist)) ;
+ }
+ }
+
+ S32 texture_discard = mSculptTexture->getDiscardLevel(); //try to match the texture
+ S32 current_discard = getVolume() ? getVolume()->getSculptLevel() : -2 ;
+
+ if (texture_discard >= 0 && //texture has some data available
+ (texture_discard < current_discard || //texture has more data than last rebuild
+ current_discard < 0)) //no previous rebuild
+ {
+ gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, FALSE);
+ mSculptChanged = TRUE;
+ }
+
+ if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_SCULPTED))
+ {
+ setDebugText(llformat("T%d C%d V%d\n%dx%d",
+ texture_discard, current_discard, getVolume()->getSculptLevel(),
+ mSculptTexture->getHeight(), mSculptTexture->getWidth()));
+ }
+ }
+
+ }
+
+ if (getLightTextureID().notNull())
+ {
+ LLLightImageParams* params = (LLLightImageParams*) getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
+ LLUUID id = params->getLightTexture();
+ mLightTexture = LLViewerTextureManager::getFetchedTexture(id);
+ if (mLightTexture.notNull())
+ {
+ F32 rad = getLightRadius();
+ mLightTexture->addTextureStats(gPipeline.calcPixelArea(getPositionAgent(),
+ LLVector3(rad,rad,rad),
+ *camera));
+ }
+ }
+
+ if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_AREA))
+ {
+ setDebugText(llformat("%.0f:%.0f", (F32) sqrt(min_vsize),(F32) sqrt(max_vsize)));
+ }
+ else if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_TEXTURE_PRIORITY))
+ {
+ setDebugText(llformat("%.0f:%.0f", (F32) sqrt(min_vsize),(F32) sqrt(max_vsize)));
+ }
+ else if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_FACE_AREA))
+ {
+ setDebugText(llformat("%.0f:%.0f", (F32) sqrt(min_vsize),(F32) sqrt(max_vsize)));
+ }
+
+ if (mPixelArea == 0)
+ { //flexi phasing issues make this happen
+ mPixelArea = old_area;
+ }
+}
+
+BOOL LLVOVolume::isActive() const
+{
+ return !mStatic || mTextureAnimp || (mVolumeImpl && mVolumeImpl->isActive()) ||
+ (mDrawable.notNull() && mDrawable->isActive());
+}
+
+BOOL LLVOVolume::setMaterial(const U8 material)
+{
+ BOOL res = LLViewerObject::setMaterial(material);
+
+ return res;
+}
+
+void LLVOVolume::setTexture(const S32 face)
+{
+ llassert(face < getNumTEs());
+ gGL.getTexUnit(0)->bind(getTEImage(face));
+}
+
+void LLVOVolume::setScale(const LLVector3 &scale, BOOL damped)
+{
+ if (scale != getScale())
+ {
+ // store local radius
+ LLViewerObject::setScale(scale);
+
+ if (mVolumeImpl)
+ {
+ mVolumeImpl->onSetScale(scale, damped);
+ }
+
+ updateRadius();
+
+ //since drawable transforms do not include scale, changing volume scale
+ //requires an immediate rebuild of volume verts.
+ gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_POSITION, TRUE);
+ }
+}
+
+LLFace* LLVOVolume::addFace(S32 f)
+{
+ const LLTextureEntry* te = getTE(f);
+ LLViewerTexture* imagep = getTEImage(f);
+ return mDrawable->addFace(te, imagep);
+}
+
+LLDrawable *LLVOVolume::createDrawable(LLPipeline *pipeline)
+{
+ pipeline->allocDrawable(this);
+
+ mDrawable->setRenderType(LLPipeline::RENDER_TYPE_VOLUME);
+
+ S32 max_tes_to_set = getNumTEs();
+ for (S32 i = 0; i < max_tes_to_set; i++)
+ {
+ addFace(i);
+ }
+ mNumFaces = max_tes_to_set;
+
+ if (isAttachment())
+ {
+ mDrawable->makeActive();
+ }
+
+ if (getIsLight())
+ {
+ // Add it to the pipeline mLightSet
+ gPipeline.setLight(mDrawable, TRUE);
+ }
+
+ updateRadius();
+ bool force_update = true; // avoid non-alpha mDistance update being optimized away
+ mDrawable->updateDistance(*LLViewerCamera::getInstance(), force_update);
+
+ return mDrawable;
+}
+
+BOOL LLVOVolume::setVolume(const LLVolumeParams &params_in, const S32 detail, bool unique_volume)
+{
+ LLVolumeParams volume_params = params_in;
+
+ S32 last_lod = mVolumep.notNull() ? LLVolumeLODGroup::getVolumeDetailFromScale(mVolumep->getDetail()) : -1;
+ S32 lod = mLOD;
+
+ BOOL is404 = FALSE;
+
+ if (isSculpted())
+ {
+ // if it's a mesh
+ if ((volume_params.getSculptType() & LL_SCULPT_TYPE_MASK) == LL_SCULPT_TYPE_MESH)
+ { //meshes might not have all LODs, get the force detail to best existing LOD
+
+ LLUUID mesh_id = volume_params.getSculptID();
+
+ //profile and path params don't matter for meshes
+ volume_params.setType(LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE);
+
+ lod = gMeshRepo.getActualMeshLOD(volume_params, lod);
+ if (lod == -1)
+ {
+ is404 = TRUE;
+ lod = 0;
+ }
+ }
+ }
+
+ // Check if we need to change implementations
+ bool is_flexible = (volume_params.getPathParams().getCurveType() == LL_PCODE_PATH_FLEXIBLE);
+ if (is_flexible)
+ {
+ setParameterEntryInUse(LLNetworkData::PARAMS_FLEXIBLE, TRUE, false);
+ if (!mVolumeImpl)
+ {
+ LLFlexibleObjectData* data = (LLFlexibleObjectData*)getParameterEntry(LLNetworkData::PARAMS_FLEXIBLE);
+ mVolumeImpl = new LLVolumeImplFlexible(this, data);
+ }
+ }
+ else
+ {
+ // Mark the parameter not in use
+ setParameterEntryInUse(LLNetworkData::PARAMS_FLEXIBLE, FALSE, false);
+ if (mVolumeImpl)
+ {
+ delete mVolumeImpl;
+ mVolumeImpl = NULL;
+ if (mDrawable.notNull())
+ {
+ // Undo the damage we did to this matrix
+ mDrawable->updateXform(FALSE);
+ }
+ }
+ }
+
+ if (is404)
+ {
+ setIcon(LLViewerTextureManager::getFetchedTextureFromFile("icons/Inv_Mesh.png", TRUE, LLViewerTexture::BOOST_UI));
+ }
+
+ if ((LLPrimitive::setVolume(volume_params, lod, (mVolumeImpl && mVolumeImpl->isVolumeUnique()))) || mSculptChanged)
+ {
+ mFaceMappingChanged = TRUE;
+
+ if (mVolumeImpl)
+ {
+ mVolumeImpl->onSetVolume(volume_params, mLOD);
+ }
+
+ updateSculptTexture();
+
+
+ if (isSculpted())
+ {
+ updateSculptTexture();
+ // if it's a mesh
+ if ((volume_params.getSculptType() & LL_SCULPT_TYPE_MASK) == LL_SCULPT_TYPE_MESH)
+ {
+ if (getVolume()->getNumVolumeFaces() == 0 || getVolume()->isTetrahedron())
+ {
+ //load request not yet issued, request pipeline load this mesh
+ LLUUID asset_id = volume_params.getSculptID();
+ S32 available_lod = gMeshRepo.loadMesh(this, volume_params, lod, last_lod);
+ if (available_lod != lod)
+ {
+ LLPrimitive::setVolume(volume_params, available_lod);
+ }
+ }
+
+ }
+ else // otherwise is sculptie
+ {
+ if (mSculptTexture.notNull())
+ {
+ sculpt();
+ }
+ }
+ }
+
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+void LLVOVolume::updateSculptTexture()
+{
+ LLPointer<LLViewerFetchedTexture> old_sculpt = mSculptTexture;
+
+ if (isSculpted() && !isMesh())
+ {
+ LLSculptParams *sculpt_params = (LLSculptParams *)getParameterEntry(LLNetworkData::PARAMS_SCULPT);
+ LLUUID id = sculpt_params->getSculptTexture();
+ if (id.notNull())
+ {
+ mSculptTexture = LLViewerTextureManager::getFetchedTexture(id, TRUE, LLViewerTexture::BOOST_NONE, LLViewerTexture::LOD_TEXTURE);
+ }
+ }
+ else
+ {
+ mSculptTexture = NULL;
+ }
+
+ if (mSculptTexture != old_sculpt)
+ {
+ if (old_sculpt.notNull())
+ {
+ old_sculpt->removeVolume(this);
+ }
+ if (mSculptTexture.notNull())
+ {
+ mSculptTexture->addVolume(this);
+ }
+ }
+
+}
+
+
+
+void LLVOVolume::notifyMeshLoaded()
+{
+ mSculptChanged = TRUE;
+ gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_GEOMETRY, TRUE);
+}
+
+// sculpt replaces generate() for sculpted surfaces
+void LLVOVolume::sculpt()
+{
+ if (mSculptTexture.notNull())
+ {
+ U16 sculpt_height = 0;
+ U16 sculpt_width = 0;
+ S8 sculpt_components = 0;
+ const U8* sculpt_data = NULL;
+
+ S32 discard_level = mSculptTexture->getDiscardLevel() ;
+ LLImageRaw* raw_image = mSculptTexture->getCachedRawImage() ;
+
+ S32 max_discard = mSculptTexture->getMaxDiscardLevel();
+ if (discard_level > max_discard)
+ discard_level = max_discard; // clamp to the best we can do
+
+ S32 current_discard = getVolume()->getSculptLevel() ;
+ if(current_discard < -2)
+ {
+ llwarns << "WARNING!!: Current discard of sculpty at " << current_discard
+ << " is less than -2." << llendl;
+
+ // corrupted volume... don't update the sculpty
+ return;
+ }
+ else if (current_discard > MAX_DISCARD_LEVEL)
+ {
+ llwarns << "WARNING!!: Current discard of sculpty at " << current_discard
+ << " is more than than allowed max of " << MAX_DISCARD_LEVEL << llendl;
+
+ // corrupted volume... don't update the sculpty
+ return;
+ }
+
+ if (current_discard == discard_level) // no work to do here
+ return;
+
+ if(!raw_image)
+ {
+ llassert(discard_level < 0) ;
+
+ sculpt_width = 0;
+ sculpt_height = 0;
+ sculpt_data = NULL ;
+
+ if(LLViewerTextureManager::sTesterp)
+ {
+ LLViewerTextureManager::sTesterp->updateGrayTextureBinding();
+ }
+ }
+ else
+ {
+ sculpt_height = raw_image->getHeight();
+ sculpt_width = raw_image->getWidth();
+ sculpt_components = raw_image->getComponents();
+
+ sculpt_data = raw_image->getData();
+
+ if(LLViewerTextureManager::sTesterp)
+ {
+ mSculptTexture->updateBindStatsForTester() ;
+ }
+ }
+ getVolume()->sculpt(sculpt_width, sculpt_height, sculpt_components, sculpt_data, discard_level);
+
+ //notify rebuild any other VOVolumes that reference this sculpty volume
+ for (S32 i = 0; i < mSculptTexture->getNumVolumes(); ++i)
+ {
+ LLVOVolume* volume = (*(mSculptTexture->getVolumeList()))[i];
+ if (volume != this && volume->getVolume() == getVolume())
+ {
+ gPipeline.markRebuild(volume->mDrawable, LLDrawable::REBUILD_GEOMETRY, FALSE);
+ }
+ }
+ }
+}
+
+S32 LLVOVolume::computeLODDetail(F32 distance, F32 radius)
+{
+ S32 cur_detail;
+ if (LLPipeline::sDynamicLOD)
+ {
+ // We've got LOD in the profile, and in the twist. Use radius.
+ F32 tan_angle = (LLVOVolume::sLODFactor*radius)/distance;
+ cur_detail = LLVolumeLODGroup::getDetailFromTan(llround(tan_angle, 0.01f));
+ }
+ else
+ {
+ cur_detail = llclamp((S32) (sqrtf(radius)*LLVOVolume::sLODFactor*4.f), 0, 3);
+ }
+ return cur_detail;
+}
+
+BOOL LLVOVolume::calcLOD()
+{
+ if (mDrawable.isNull())
+ {
+ return FALSE;
+ }
+
+ S32 cur_detail = 0;
+
+ F32 radius;
+ F32 distance;
+
+ if (mDrawable->isState(LLDrawable::RIGGED))
+ {
+ LLVOAvatar* avatar = getAvatar();
+ distance = avatar->mDrawable->mDistanceWRTCamera;
+ radius = avatar->getBinRadius();
+ }
+ else
+ {
+ distance = mDrawable->mDistanceWRTCamera;
+ radius = getVolume()->mLODScaleBias.scaledVec(getScale()).length();
+ }
+
+ //hold onto unmodified distance for debugging
+ F32 debug_distance = distance;
+
+ distance *= sDistanceFactor;
+
+ F32 rampDist = LLVOVolume::sLODFactor * 2;
+
+ if (distance < rampDist)
+ {
+ // Boost LOD when you're REALLY close
+ distance *= 1.0f/rampDist;
+ distance *= distance;
+ distance *= rampDist;
+ }
+
+ // DON'T Compensate for field of view changing on FOV zoom.
+ distance *= F_PI/3.f;
+
+ cur_detail = computeLODDetail(llround(distance, 0.01f),
+ llround(radius, 0.01f));
+
+
+ if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_LOD_INFO))
+ {
+ setDebugText(llformat("%.2f:%.2f, %d", debug_distance, radius, cur_detail));
+ }
+
+ if (cur_detail != mLOD)
+ {
+ mAppAngle = llround((F32) atan2( mDrawable->getRadius(), mDrawable->mDistanceWRTCamera) * RAD_TO_DEG, 0.01f);
+ mLOD = cur_detail;
+ return TRUE;
+ }
+ else
+ {
+ return FALSE;
+ }
+}
+
+BOOL LLVOVolume::updateLOD()
+{
+ if (mDrawable.isNull())
+ {
+ return FALSE;
+ }
+
+ BOOL lod_changed = calcLOD();
+
+ if (lod_changed)
+ {
+ gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, FALSE);
+ mLODChanged = TRUE;
+ }
+
+ lod_changed = lod_changed || LLViewerObject::updateLOD();
+
+ return lod_changed;
+}
+
+BOOL LLVOVolume::setDrawableParent(LLDrawable* parentp)
+{
+ if (!LLViewerObject::setDrawableParent(parentp))
+ {
+ // no change in drawable parent
+ return FALSE;
+ }
+
+ if (!mDrawable->isRoot())
+ {
+ // rebuild vertices in parent relative space
+ gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, TRUE);
+
+ if (mDrawable->isActive() && !parentp->isActive())
+ {
+ parentp->makeActive();
+ }
+ else if (mDrawable->isStatic() && parentp->isActive())
+ {
+ mDrawable->makeActive();
+ }
+ }
+
+ return TRUE;
+}
+
+void LLVOVolume::updateFaceFlags()
+{
+ for (S32 i = 0; i < getVolume()->getNumFaces(); i++)
+ {
+ LLFace *face = mDrawable->getFace(i);
+ if (!face)
+ {
+ return;
+ }
+
+ BOOL fullbright = getTE(i)->getFullbright();
+ face->clearState(LLFace::FULLBRIGHT | LLFace::HUD_RENDER | LLFace::LIGHT);
+
+ if (fullbright || (mMaterial == LL_MCODE_LIGHT))
+ {
+ face->setState(LLFace::FULLBRIGHT);
+ }
+ if (mDrawable->isLight())
+ {
+ face->setState(LLFace::LIGHT);
+ }
+ if (isHUDAttachment())
+ {
+ face->setState(LLFace::HUD_RENDER);
+ }
+ }
+}
+
+BOOL LLVOVolume::setParent(LLViewerObject* parent)
+{
+ BOOL ret = FALSE ;
+ if (parent != getParent())
+ {
+ ret = LLViewerObject::setParent(parent);
+ if (ret && mDrawable)
+ {
+ gPipeline.markMoved(mDrawable);
+ gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, TRUE);
+ }
+ }
+
+ return ret ;
+}
+
+// NOTE: regenFaces() MUST be followed by genTriangles()!
+void LLVOVolume::regenFaces()
+{
+ // remove existing faces
+ BOOL count_changed = mNumFaces != getNumTEs();
+
+ if (count_changed)
+ {
+ deleteFaces();
+ // add new faces
+ mNumFaces = getNumTEs();
+ }
+
+ for (S32 i = 0; i < mNumFaces; i++)
+ {
+ LLFace* facep = count_changed ? addFace(i) : mDrawable->getFace(i);
+ facep->setTEOffset(i);
+ facep->setTexture(getTEImage(i));
+ facep->setViewerObject(this);
+
+ // If the face had media on it, this will have broken the link between the LLViewerMediaTexture and the face.
+ // Re-establish the link.
+ if((int)mMediaImplList.size() > i)
+ {
+ if(mMediaImplList[i])
+ {
+ LLViewerMediaTexture* media_tex = LLViewerTextureManager::findMediaTexture(mMediaImplList[i]->getMediaTextureID()) ;
+ if(media_tex)
+ {
+ media_tex->addMediaToFace(facep) ;
+ }
+ }
+ }
+ }
+
+ if (!count_changed)
+ {
+ updateFaceFlags();
+ }
+}
+
+BOOL LLVOVolume::genBBoxes(BOOL force_global)
+{
+ BOOL res = TRUE;
+
+ LLVector4a min,max;
+
+ min.clear();
+ max.clear();
+
+ BOOL rebuild = mDrawable->isState(LLDrawable::REBUILD_VOLUME | LLDrawable::REBUILD_POSITION | LLDrawable::REBUILD_RIGGED);
+
+// bool rigged = false;
+ LLVolume* volume = mRiggedVolume;
+ if (!volume)
+ {
+ volume = getVolume();
+ }
+
+ for (S32 i = 0; i < getVolume()->getNumVolumeFaces(); i++)
+ {
+ LLFace *face = mDrawable->getFace(i);
+ if (!face)
+ {
+ continue;
+ }
+ res &= face->genVolumeBBoxes(*volume, i,
+ mRelativeXform, mRelativeXformInvTrans,
+ (mVolumeImpl && mVolumeImpl->isVolumeGlobal()) || force_global);
+
+ if (rebuild)
+ {
+ if (i == 0)
+ {
+ min = face->mExtents[0];
+ max = face->mExtents[1];
+ }
+ else
+ {
+ min.setMin(min, face->mExtents[0]);
+ max.setMax(max, face->mExtents[1]);
+ }
+ }
+ }
+
+ if (rebuild)
+ {
+ mDrawable->setSpatialExtents(min,max);
+ min.add(max);
+ min.mul(0.5f);
+ mDrawable->setPositionGroup(min);
+ }
+
+ updateRadius();
+ mDrawable->movePartition();
+
+ return res;
+}
+
+void LLVOVolume::preRebuild()
+{
+ if (mVolumeImpl != NULL)
+ {
+ mVolumeImpl->preRebuild();
+ }
+}
+
+void LLVOVolume::updateRelativeXform()
+{
+ if (mVolumeImpl)
+ {
+ mVolumeImpl->updateRelativeXform();
+ return;
+ }
+
+ LLDrawable* drawable = mDrawable;
+
+ if (drawable->isState(LLDrawable::RIGGED) && mRiggedVolume.notNull())
+ { //rigged volume (which is in agent space) is used for generating bounding boxes etc
+ //inverse of render matrix should go to partition space
+ mRelativeXform = getRenderMatrix();
+
+ F32* dst = (F32*) mRelativeXformInvTrans.mMatrix;
+ F32* src = (F32*) mRelativeXform.mMatrix;
+ dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2];
+ dst[3] = src[4]; dst[4] = src[5]; dst[5] = src[6];
+ dst[6] = src[8]; dst[7] = src[9]; dst[8] = src[10];
+
+ mRelativeXform.invert();
+ mRelativeXformInvTrans.transpose();
+ }
+ else if (drawable->isActive())
+ {
+ // setup relative transforms
+ LLQuaternion delta_rot;
+ LLVector3 delta_pos, delta_scale;
+
+ //matrix from local space to parent relative/global space
+ delta_rot = drawable->isSpatialRoot() ? LLQuaternion() : mDrawable->getRotation();
+ delta_pos = drawable->isSpatialRoot() ? LLVector3(0,0,0) : mDrawable->getPosition();
+ delta_scale = mDrawable->getScale();
+
+ // Vertex transform (4x4)
+ LLVector3 x_axis = LLVector3(delta_scale.mV[VX], 0.f, 0.f) * delta_rot;
+ LLVector3 y_axis = LLVector3(0.f, delta_scale.mV[VY], 0.f) * delta_rot;
+ LLVector3 z_axis = LLVector3(0.f, 0.f, delta_scale.mV[VZ]) * delta_rot;
+
+ mRelativeXform.initRows(LLVector4(x_axis, 0.f),
+ LLVector4(y_axis, 0.f),
+ LLVector4(z_axis, 0.f),
+ LLVector4(delta_pos, 1.f));
+
+
+ // compute inverse transpose for normals
+ // mRelativeXformInvTrans.setRows(x_axis, y_axis, z_axis);
+ // mRelativeXformInvTrans.invert();
+ // mRelativeXformInvTrans.setRows(x_axis, y_axis, z_axis);
+ // grumble - invert is NOT a matrix invert, so we do it by hand:
+
+ LLMatrix3 rot_inverse = LLMatrix3(~delta_rot);
+
+ LLMatrix3 scale_inverse;
+ scale_inverse.setRows(LLVector3(1.0, 0.0, 0.0) / delta_scale.mV[VX],
+ LLVector3(0.0, 1.0, 0.0) / delta_scale.mV[VY],
+ LLVector3(0.0, 0.0, 1.0) / delta_scale.mV[VZ]);
+
+
+ mRelativeXformInvTrans = rot_inverse * scale_inverse;
+
+ mRelativeXformInvTrans.transpose();
+ }
+ else
+ {
+ LLVector3 pos = getPosition();
+ LLVector3 scale = getScale();
+ LLQuaternion rot = getRotation();
+
+ if (mParent)
+ {
+ pos *= mParent->getRotation();
+ pos += mParent->getPosition();
+ rot *= mParent->getRotation();
+ }
+
+ //LLViewerRegion* region = getRegion();
+ //pos += region->getOriginAgent();
+
+ LLVector3 x_axis = LLVector3(scale.mV[VX], 0.f, 0.f) * rot;
+ LLVector3 y_axis = LLVector3(0.f, scale.mV[VY], 0.f) * rot;
+ LLVector3 z_axis = LLVector3(0.f, 0.f, scale.mV[VZ]) * rot;
+
+ mRelativeXform.initRows(LLVector4(x_axis, 0.f),
+ LLVector4(y_axis, 0.f),
+ LLVector4(z_axis, 0.f),
+ LLVector4(pos, 1.f));
+
+ // compute inverse transpose for normals
+ LLMatrix3 rot_inverse = LLMatrix3(~rot);
+
+ LLMatrix3 scale_inverse;
+ scale_inverse.setRows(LLVector3(1.0, 0.0, 0.0) / scale.mV[VX],
+ LLVector3(0.0, 1.0, 0.0) / scale.mV[VY],
+ LLVector3(0.0, 0.0, 1.0) / scale.mV[VZ]);
+
+
+ mRelativeXformInvTrans = rot_inverse * scale_inverse;
+
+ mRelativeXformInvTrans.transpose();
+ }
+}
+
+static LLFastTimer::DeclareTimer FTM_GEN_FLEX("Generate Flexies");
+static LLFastTimer::DeclareTimer FTM_UPDATE_PRIMITIVES("Update Primitives");
+static LLFastTimer::DeclareTimer FTM_UPDATE_RIGGED_VOLUME("Update Rigged");
+
+BOOL LLVOVolume::updateGeometry(LLDrawable *drawable)
+{
+ LLFastTimer t(FTM_UPDATE_PRIMITIVES);
+
+ if (mDrawable->isState(LLDrawable::REBUILD_RIGGED))
+ {
+ {
+ LLFastTimer t(FTM_UPDATE_RIGGED_VOLUME);
+ updateRiggedVolume();
+ }
+ genBBoxes(FALSE);
+ mDrawable->clearState(LLDrawable::REBUILD_RIGGED);
+ }
+
+ if (mVolumeImpl != NULL)
+ {
+ BOOL res;
+ {
+ LLFastTimer t(FTM_GEN_FLEX);
+ res = mVolumeImpl->doUpdateGeometry(drawable);
+ }
+ updateFaceFlags();
+ return res;
+ }
+
+ dirtySpatialGroup(drawable->isState(LLDrawable::IN_REBUILD_Q1));
+
+ BOOL compiled = FALSE;
+
+ updateRelativeXform();
+
+ if (mDrawable.isNull()) // Not sure why this is happening, but it is...
+ {
+ return TRUE; // No update to complete
+ }
+
+ if (mVolumeChanged || mFaceMappingChanged )
+ {
+ compiled = TRUE;
+
+ if (mVolumeChanged)
+ {
+ LLFastTimer ftm(FTM_GEN_VOLUME);
+ LLVolumeParams volume_params = getVolume()->getParams();
+ setVolume(volume_params, 0);
+ drawable->setState(LLDrawable::REBUILD_VOLUME);
+ }
+
+ {
+ LLFastTimer t(FTM_GEN_TRIANGLES);
+ regenFaces();
+ genBBoxes(FALSE);
+ }
+ }
+ else if ((mLODChanged) || (mSculptChanged))
+ {
+ LLVolume *old_volumep, *new_volumep;
+ F32 old_lod, new_lod;
+ S32 old_num_faces, new_num_faces ;
+
+ old_volumep = getVolume();
+ old_lod = old_volumep->getDetail();
+ old_num_faces = old_volumep->getNumFaces() ;
+ old_volumep = NULL ;
+
+ {
+ LLFastTimer ftm(FTM_GEN_VOLUME);
+ LLVolumeParams volume_params = getVolume()->getParams();
+ setVolume(volume_params, 0);
+ }
+
+ new_volumep = getVolume();
+ new_lod = new_volumep->getDetail();
+ new_num_faces = new_volumep->getNumFaces() ;
+ new_volumep = NULL ;
+
+ if ((new_lod != old_lod) || mSculptChanged)
+ {
+ compiled = TRUE;
+ sNumLODChanges += new_num_faces ;
+
+ drawable->setState(LLDrawable::REBUILD_VOLUME); // for face->genVolumeTriangles()
+
+ {
+ LLFastTimer t(FTM_GEN_TRIANGLES);
+ if (new_num_faces != old_num_faces)
+ {
+ regenFaces();
+ }
+ genBBoxes(FALSE);
+
+ if (mSculptChanged)
+ { //changes in sculpt maps can thrash an object bounding box without
+ //triggering a spatial group bounding box update -- force spatial group
+ //to update bounding boxes
+ LLSpatialGroup* group = mDrawable->getSpatialGroup();
+ if (group)
+ {
+ group->unbound();
+ }
+ }
+ }
+ }
+ }
+ // it has its own drawable (it's moved) or it has changed UVs or it has changed xforms from global<->local
+ else
+ {
+ compiled = TRUE;
+ // All it did was move or we changed the texture coordinate offset
+ LLFastTimer t(FTM_GEN_TRIANGLES);
+ genBBoxes(FALSE);
+ }
+
+ // Update face flags
+ updateFaceFlags();
+
+ if(compiled)
+ {
+ LLPipeline::sCompiles++;
+ }
+
+ mVolumeChanged = FALSE;
+ mLODChanged = FALSE;
+ mSculptChanged = FALSE;
+ mFaceMappingChanged = FALSE;
+
+ return LLViewerObject::updateGeometry(drawable);
+}
+
+void LLVOVolume::updateFaceSize(S32 idx)
+{
+ LLFace* facep = mDrawable->getFace(idx);
+ if (idx >= getVolume()->getNumVolumeFaces())
+ {
+ facep->setSize(0,0, true);
+ }
+ else
+ {
+ const LLVolumeFace& vol_face = getVolume()->getVolumeFace(idx);
+ facep->setSize(vol_face.mNumVertices, vol_face.mNumIndices,
+ true); // <--- volume faces should be padded for 16-byte alignment
+
+ }
+}
+
+BOOL LLVOVolume::isRootEdit() const
+{
+ if (mParent && !((LLViewerObject*)mParent)->isAvatar())
+ {
+ return FALSE;
+ }
+ return TRUE;
+}
+
+//virtual
+void LLVOVolume::setNumTEs(const U8 num_tes)
+{
+ const U8 old_num_tes = getNumTEs() ;
+
+ if(old_num_tes && old_num_tes < num_tes) //new faces added
+ {
+ LLViewerObject::setNumTEs(num_tes) ;
+
+ if(mMediaImplList.size() >= old_num_tes && mMediaImplList[old_num_tes -1].notNull())//duplicate the last media textures if exists.
+ {
+ mMediaImplList.resize(num_tes) ;
+ const LLTextureEntry* te = getTE(old_num_tes - 1) ;
+ for(U8 i = old_num_tes; i < num_tes ; i++)
+ {
+ setTE(i, *te) ;
+ mMediaImplList[i] = mMediaImplList[old_num_tes -1] ;
+ }
+ mMediaImplList[old_num_tes -1]->setUpdated(TRUE) ;
+ }
+ }
+ else if(old_num_tes > num_tes && mMediaImplList.size() > num_tes) //old faces removed
+ {
+ U8 end = mMediaImplList.size() ;
+ for(U8 i = num_tes; i < end ; i++)
+ {
+ removeMediaImpl(i) ;
+ }
+ mMediaImplList.resize(num_tes) ;
+
+ LLViewerObject::setNumTEs(num_tes) ;
+ }
+ else
+ {
+ LLViewerObject::setNumTEs(num_tes) ;
+ }
+
+ return ;
+}
+
+void LLVOVolume::setTEImage(const U8 te, LLViewerTexture *imagep)
+{
+ BOOL changed = (mTEImages[te] != imagep);
+ LLViewerObject::setTEImage(te, imagep);
+ if (changed)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+}
+
+S32 LLVOVolume::setTETexture(const U8 te, const LLUUID &uuid)
+{
+ S32 res = LLViewerObject::setTETexture(te, uuid);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTEColor(const U8 te, const LLColor3& color)
+{
+ return setTEColor(te, LLColor4(color));
+}
+
+S32 LLVOVolume::setTEColor(const U8 te, const LLColor4& color)
+{
+ S32 retval = 0;
+ const LLTextureEntry *tep = getTE(te);
+ if (!tep)
+ {
+ llwarns << "No texture entry for te " << (S32)te << ", object " << mID << llendl;
+ }
+ else if (color != tep->getColor())
+ {
+ if (color.mV[3] != tep->getColor().mV[3])
+ {
+ gPipeline.markTextured(mDrawable);
+ }
+ retval = LLPrimitive::setTEColor(te, color);
+ if (mDrawable.notNull() && retval)
+ {
+ // These should only happen on updates which are not the initial update.
+ mDrawable->setState(LLDrawable::REBUILD_COLOR);
+ dirtyMesh();
+ }
+ }
+
+ return retval;
+}
+
+S32 LLVOVolume::setTEBumpmap(const U8 te, const U8 bumpmap)
+{
+ S32 res = LLViewerObject::setTEBumpmap(te, bumpmap);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTETexGen(const U8 te, const U8 texgen)
+{
+ S32 res = LLViewerObject::setTETexGen(te, texgen);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTEMediaTexGen(const U8 te, const U8 media)
+{
+ S32 res = LLViewerObject::setTEMediaTexGen(te, media);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTEShiny(const U8 te, const U8 shiny)
+{
+ S32 res = LLViewerObject::setTEShiny(te, shiny);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTEFullbright(const U8 te, const U8 fullbright)
+{
+ S32 res = LLViewerObject::setTEFullbright(te, fullbright);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTEBumpShinyFullbright(const U8 te, const U8 bump)
+{
+ S32 res = LLViewerObject::setTEBumpShinyFullbright(te, bump);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTEMediaFlags(const U8 te, const U8 media_flags)
+{
+ S32 res = LLViewerObject::setTEMediaFlags(te, media_flags);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTEGlow(const U8 te, const F32 glow)
+{
+ S32 res = LLViewerObject::setTEGlow(te, glow);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTEScale(const U8 te, const F32 s, const F32 t)
+{
+ S32 res = LLViewerObject::setTEScale(te, s, t);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTEScaleS(const U8 te, const F32 s)
+{
+ S32 res = LLViewerObject::setTEScaleS(te, s);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+S32 LLVOVolume::setTEScaleT(const U8 te, const F32 t)
+{
+ S32 res = LLViewerObject::setTEScaleT(te, t);
+ if (res)
+ {
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ return res;
+}
+
+void LLVOVolume::updateTEData()
+{
+ /*if (mDrawable.notNull())
+ {
+ mFaceMappingChanged = TRUE;
+ gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_MATERIAL, TRUE);
+ }*/
+}
+
+bool LLVOVolume::hasMedia() const
+{
+ bool result = false;
+ const U8 numTEs = getNumTEs();
+ for (U8 i = 0; i < numTEs; i++)
+ {
+ const LLTextureEntry* te = getTE(i);
+ if(te->hasMedia())
+ {
+ result = true;
+ break;
+ }
+ }
+ return result;
+}
+
+LLVector3 LLVOVolume::getApproximateFaceNormal(U8 face_id)
+{
+ LLVolume* volume = getVolume();
+ LLVector4a result;
+ result.clear();
+
+ LLVector3 ret;
+
+ if (volume && face_id < volume->getNumVolumeFaces())
+ {
+ const LLVolumeFace& face = volume->getVolumeFace(face_id);
+ for (S32 i = 0; i < (S32)face.mNumVertices; ++i)
+ {
+ result.add(face.mNormals[i]);
+ }
+
+ LLVector3 ret(result.getF32ptr());
+ ret = volumeDirectionToAgent(ret);
+ ret.normVec();
+ }
+
+ return ret;
+}
+
+void LLVOVolume::requestMediaDataUpdate(bool isNew)
+{
+ if (sObjectMediaClient)
+ sObjectMediaClient->fetchMedia(new LLMediaDataClientObjectImpl(this, isNew));
+}
+
+bool LLVOVolume::isMediaDataBeingFetched() const
+{
+ // I know what I'm doing by const_casting this away: this is just
+ // a wrapper class that is only going to do a lookup.
+ return (sObjectMediaClient) ? sObjectMediaClient->isInQueue(new LLMediaDataClientObjectImpl(const_cast<LLVOVolume*>(this), false)) : false;
+}
+
+void LLVOVolume::cleanUpMediaImpls()
+{
+ // Iterate through our TEs and remove any Impls that are no longer used
+ const U8 numTEs = getNumTEs();
+ for (U8 i = 0; i < numTEs; i++)
+ {
+ const LLTextureEntry* te = getTE(i);
+ if( ! te->hasMedia())
+ {
+ // Delete the media IMPL!
+ removeMediaImpl(i) ;
+ }
+ }
+}
+
+void LLVOVolume::updateObjectMediaData(const LLSD &media_data_array, const std::string &media_version)
+{
+ // media_data_array is an array of media entry maps
+ // media_version is the version string in the response.
+ U32 fetched_version = LLTextureEntry::getVersionFromMediaVersionString(media_version);
+
+ // Only update it if it is newer!
+ if ( (S32)fetched_version > mLastFetchedMediaVersion)
+ {
+ mLastFetchedMediaVersion = fetched_version;
+ //llinfos << "updating:" << this->getID() << " " << ll_pretty_print_sd(media_data_array) << llendl;
+
+ LLSD::array_const_iterator iter = media_data_array.beginArray();
+ LLSD::array_const_iterator end = media_data_array.endArray();
+ U8 texture_index = 0;
+ for (; iter != end; ++iter, ++texture_index)
+ {
+ syncMediaData(texture_index, *iter, false/*merge*/, false/*ignore_agent*/);
+ }
+ }
+}
+
+void LLVOVolume::syncMediaData(S32 texture_index, const LLSD &media_data, bool merge, bool ignore_agent)
+{
+ if(mDead)
+ {
+ // If the object has been marked dead, don't process media updates.
+ return;
+ }
+
+ LLTextureEntry *te = getTE(texture_index);
+ if(!te)
+ {
+ return ;
+ }
+
+ LL_DEBUGS("MediaOnAPrim") << "BEFORE: texture_index = " << texture_index
+ << " hasMedia = " << te->hasMedia() << " : "
+ << ((NULL == te->getMediaData()) ? "NULL MEDIA DATA" : ll_pretty_print_sd(te->getMediaData()->asLLSD())) << llendl;
+
+ std::string previous_url;
+ LLMediaEntry* mep = te->getMediaData();
+ if(mep)
+ {
+ // Save the "current url" from before the update so we can tell if
+ // it changes.
+ previous_url = mep->getCurrentURL();
+ }
+
+ if (merge)
+ {
+ te->mergeIntoMediaData(media_data);
+ }
+ else {
+ // XXX Question: what if the media data is undefined LLSD, but the
+ // update we got above said that we have media flags?? Here we clobber
+ // that, assuming the data from the service is more up-to-date.
+ te->updateMediaData(media_data);
+ }
+
+ mep = te->getMediaData();
+ if(mep)
+ {
+ bool update_from_self = false;
+ if (!ignore_agent)
+ {
+ LLUUID updating_agent = LLTextureEntry::getAgentIDFromMediaVersionString(getMediaURL());
+ update_from_self = (updating_agent == gAgent.getID());
+ }
+ viewer_media_t media_impl = LLViewerMedia::updateMediaImpl(mep, previous_url, update_from_self);
+
+ addMediaImpl(media_impl, texture_index) ;
+ }
+ else
+ {
+ removeMediaImpl(texture_index);
+ }
+
+ LL_DEBUGS("MediaOnAPrim") << "AFTER: texture_index = " << texture_index
+ << " hasMedia = " << te->hasMedia() << " : "
+ << ((NULL == te->getMediaData()) ? "NULL MEDIA DATA" : ll_pretty_print_sd(te->getMediaData()->asLLSD())) << llendl;
+}
+
+void LLVOVolume::mediaNavigateBounceBack(U8 texture_index)
+{
+ // Find the media entry for this navigate
+ const LLMediaEntry* mep = NULL;
+ viewer_media_t impl = getMediaImpl(texture_index);
+ LLTextureEntry *te = getTE(texture_index);
+ if(te)
+ {
+ mep = te->getMediaData();
+ }
+
+ if (mep && impl)
+ {
+ std::string url = mep->getCurrentURL();
+ // Look for a ":", if not there, assume "http://"
+ if (!url.empty() && std::string::npos == url.find(':'))
+ {
+ url = "http://" + url;
+ }
+ // If the url we're trying to "bounce back" to is either empty or not
+ // allowed by the whitelist, try the home url. If *that* doesn't work,
+ // set the media as failed and unload it
+ if (url.empty() || !mep->checkCandidateUrl(url))
+ {
+ url = mep->getHomeURL();
+ // Look for a ":", if not there, assume "http://"
+ if (!url.empty() && std::string::npos == url.find(':'))
+ {
+ url = "http://" + url;
+ }
+ }
+ if (url.empty() || !mep->checkCandidateUrl(url))
+ {
+ // The url to navigate back to is not good, and we have nowhere else
+ // to go.
+ LL_WARNS("MediaOnAPrim") << "FAILED to bounce back URL \"" << url << "\" -- unloading impl" << LL_ENDL;
+ impl->setMediaFailed(true);
+ }
+ else {
+ // Okay, navigate now
+ LL_INFOS("MediaOnAPrim") << "bouncing back to URL: " << url << LL_ENDL;
+ impl->navigateTo(url, "", false, true);
+ }
+ }
+}
+
+bool LLVOVolume::hasMediaPermission(const LLMediaEntry* media_entry, MediaPermType perm_type)
+{
+ // NOTE: This logic ALMOST duplicates the logic in the server (in particular, in llmediaservice.cpp).
+ if (NULL == media_entry ) return false; // XXX should we assert here?
+
+ // The agent has permissions if:
+ // - world permissions are on, or
+ // - group permissions are on, and agent_id is in the group, or
+ // - agent permissions are on, and agent_id is the owner
+
+ // *NOTE: We *used* to check for modify permissions here (i.e. permissions were
+ // granted if permModify() was true). However, this doesn't make sense in the
+ // viewer: we don't want to show controls or allow interaction if the author
+ // has deemed it so. See DEV-42115.
+
+ U8 media_perms = (perm_type == MEDIA_PERM_INTERACT) ? media_entry->getPermsInteract() : media_entry->getPermsControl();
+
+ // World permissions
+ if (0 != (media_perms & LLMediaEntry::PERM_ANYONE))
+ {
+ return true;
+ }
+
+ // Group permissions
+ else if (0 != (media_perms & LLMediaEntry::PERM_GROUP))
+ {
+ LLPermissions* obj_perm = LLSelectMgr::getInstance()->findObjectPermissions(this);
+ if (obj_perm && gAgent.isInGroup(obj_perm->getGroup()))
+ {
+ return true;
+ }
+ }
+
+ // Owner permissions
+ else if (0 != (media_perms & LLMediaEntry::PERM_OWNER) && permYouOwner())
+ {
+ return true;
+ }
+
+ return false;
+
+}
+
+void LLVOVolume::mediaNavigated(LLViewerMediaImpl *impl, LLPluginClassMedia* plugin, std::string new_location)
+{
+ bool block_navigation = false;
+ // FIXME: if/when we allow the same media impl to be used by multiple faces, the logic here will need to be fixed
+ // to deal with multiple face indices.
+ int face_index = getFaceIndexWithMediaImpl(impl, -1);
+
+ // Find the media entry for this navigate
+ LLMediaEntry* mep = NULL;
+ LLTextureEntry *te = getTE(face_index);
+ if(te)
+ {
+ mep = te->getMediaData();
+ }
+
+ if(mep)
+ {
+ if(!mep->checkCandidateUrl(new_location))
+ {
+ block_navigation = true;
+ }
+ if (!block_navigation && !hasMediaPermission(mep, MEDIA_PERM_INTERACT))
+ {
+ block_navigation = true;
+ }
+ }
+ else
+ {
+ LL_WARNS("MediaOnAPrim") << "Couldn't find media entry!" << LL_ENDL;
+ }
+
+ if(block_navigation)
+ {
+ LL_INFOS("MediaOnAPrim") << "blocking navigate to URI " << new_location << LL_ENDL;
+
+ // "bounce back" to the current URL from the media entry
+ mediaNavigateBounceBack(face_index);
+ }
+ else if (sObjectMediaNavigateClient)
+ {
+
+ LL_DEBUGS("MediaOnAPrim") << "broadcasting navigate with URI " << new_location << LL_ENDL;
+
+ sObjectMediaNavigateClient->navigate(new LLMediaDataClientObjectImpl(this, false), face_index, new_location);
+ }
+}
+
+void LLVOVolume::mediaEvent(LLViewerMediaImpl *impl, LLPluginClassMedia* plugin, LLViewerMediaObserver::EMediaEvent event)
+{
+ switch(event)
+ {
+
+ case LLViewerMediaObserver::MEDIA_EVENT_LOCATION_CHANGED:
+ {
+ switch(impl->getNavState())
+ {
+ case LLViewerMediaImpl::MEDIANAVSTATE_FIRST_LOCATION_CHANGED:
+ {
+ // This is the first location changed event after the start of a non-server-directed nav. It may need to be broadcast or bounced back.
+ mediaNavigated(impl, plugin, plugin->getLocation());
+ }
+ break;
+
+ case LLViewerMediaImpl::MEDIANAVSTATE_FIRST_LOCATION_CHANGED_SPURIOUS:
+ // This navigate didn't change the current URL.
+ LL_DEBUGS("MediaOnAPrim") << " NOT broadcasting navigate (spurious)" << LL_ENDL;
+ break;
+
+ case LLViewerMediaImpl::MEDIANAVSTATE_SERVER_FIRST_LOCATION_CHANGED:
+ // This is the first location changed event after the start of a server-directed nav. Don't broadcast it.
+ LL_INFOS("MediaOnAPrim") << " NOT broadcasting navigate (server-directed)" << LL_ENDL;
+ break;
+
+ default:
+ // This is a subsequent location-changed due to a redirect. Don't broadcast.
+ LL_INFOS("MediaOnAPrim") << " NOT broadcasting navigate (redirect)" << LL_ENDL;
+ break;
+ }
+ }
+ break;
+
+ case LLViewerMediaObserver::MEDIA_EVENT_NAVIGATE_COMPLETE:
+ {
+ switch(impl->getNavState())
+ {
+ case LLViewerMediaImpl::MEDIANAVSTATE_COMPLETE_BEFORE_LOCATION_CHANGED:
+ {
+ // This is the first location changed event after the start of a non-server-directed nav. It may need to be broadcast or bounced back.
+ mediaNavigated(impl, plugin, plugin->getNavigateURI());
+ }
+ break;
+
+ case LLViewerMediaImpl::MEDIANAVSTATE_COMPLETE_BEFORE_LOCATION_CHANGED_SPURIOUS:
+ // This navigate didn't change the current URL.
+ LL_DEBUGS("MediaOnAPrim") << " NOT broadcasting navigate (spurious)" << LL_ENDL;
+ break;
+
+ case LLViewerMediaImpl::MEDIANAVSTATE_SERVER_COMPLETE_BEFORE_LOCATION_CHANGED:
+ // This is the the navigate complete event from a server-directed nav. Don't broadcast it.
+ LL_INFOS("MediaOnAPrim") << " NOT broadcasting navigate (server-directed)" << LL_ENDL;
+ break;
+
+ default:
+ // For all other states, the navigate should have been handled by LOCATION_CHANGED events already.
+ break;
+ }
+ }
+ break;
+
+ default:
+ break;
+ }
+
+}
+
+void LLVOVolume::sendMediaDataUpdate()
+{
+ if (sObjectMediaClient)
+ sObjectMediaClient->updateMedia(new LLMediaDataClientObjectImpl(this, false));
+}
+
+void LLVOVolume::removeMediaImpl(S32 texture_index)
+{
+ if(mMediaImplList.size() <= (U32)texture_index || mMediaImplList[texture_index].isNull())
+ {
+ return ;
+ }
+
+ //make the face referencing to mMediaImplList[texture_index] to point back to the old texture.
+ if(mDrawable && texture_index < mDrawable->getNumFaces())
+ {
+ LLFace* facep = mDrawable->getFace(texture_index) ;
+ if(facep)
+ {
+ LLViewerMediaTexture* media_tex = LLViewerTextureManager::findMediaTexture(mMediaImplList[texture_index]->getMediaTextureID()) ;
+ if(media_tex)
+ {
+ media_tex->removeMediaFromFace(facep) ;
+ }
+ }
+ }
+
+ //check if some other face(s) of this object reference(s)to this media impl.
+ S32 i ;
+ S32 end = (S32)mMediaImplList.size() ;
+ for(i = 0; i < end ; i++)
+ {
+ if( i != texture_index && mMediaImplList[i] == mMediaImplList[texture_index])
+ {
+ break ;
+ }
+ }
+
+ if(i == end) //this object does not need this media impl.
+ {
+ mMediaImplList[texture_index]->removeObject(this) ;
+ }
+
+ mMediaImplList[texture_index] = NULL ;
+ return ;
+}
+
+void LLVOVolume::addMediaImpl(LLViewerMediaImpl* media_impl, S32 texture_index)
+{
+ if((S32)mMediaImplList.size() < texture_index + 1)
+ {
+ mMediaImplList.resize(texture_index + 1) ;
+ }
+
+ if(mMediaImplList[texture_index].notNull())
+ {
+ if(mMediaImplList[texture_index] == media_impl)
+ {
+ return ;
+ }
+
+ removeMediaImpl(texture_index) ;
+ }
+
+ mMediaImplList[texture_index] = media_impl;
+ media_impl->addObject(this) ;
+
+ //add the face to show the media if it is in playing
+ if(mDrawable)
+ {
+ LLFace* facep = mDrawable->getFace(texture_index) ;
+ if(facep)
+ {
+ LLViewerMediaTexture* media_tex = LLViewerTextureManager::findMediaTexture(mMediaImplList[texture_index]->getMediaTextureID()) ;
+ if(media_tex)
+ {
+ media_tex->addMediaToFace(facep) ;
+ }
+ }
+ else //the face is not available now, start media on this face later.
+ {
+ media_impl->setUpdated(TRUE) ;
+ }
+ }
+ return ;
+}
+
+viewer_media_t LLVOVolume::getMediaImpl(U8 face_id) const
+{
+ if(mMediaImplList.size() > face_id)
+ {
+ return mMediaImplList[face_id];
+ }
+ return NULL;
+}
+
+F64 LLVOVolume::getTotalMediaInterest() const
+{
+ // If this object is currently focused, this object has "high" interest
+ if (LLViewerMediaFocus::getInstance()->getFocusedObjectID() == getID())
+ return F64_MAX;
+
+ F64 interest = (F64)-1.0; // means not interested;
+
+ // If this object is selected, this object has "high" interest, but since
+ // there can be more than one, we still add in calculated impl interest
+ // XXX Sadly, 'contains()' doesn't take a const :(
+ if (LLSelectMgr::getInstance()->getSelection()->contains(const_cast<LLVOVolume*>(this)))
+ interest = F64_MAX / 2.0;
+
+ int i = 0;
+ const int end = getNumTEs();
+ for ( ; i < end; ++i)
+ {
+ const viewer_media_t &impl = getMediaImpl(i);
+ if (!impl.isNull())
+ {
+ if (interest == (F64)-1.0) interest = (F64)0.0;
+ interest += impl->getInterest();
+ }
+ }
+ return interest;
+}
+
+S32 LLVOVolume::getFaceIndexWithMediaImpl(const LLViewerMediaImpl* media_impl, S32 start_face_id)
+{
+ S32 end = (S32)mMediaImplList.size() ;
+ for(S32 face_id = start_face_id + 1; face_id < end; face_id++)
+ {
+ if(mMediaImplList[face_id] == media_impl)
+ {
+ return face_id ;
+ }
+ }
+ return -1 ;
+}
+
+//----------------------------------------------------------------------------
+
+void LLVOVolume::setLightTextureID(LLUUID id)
+{
+ if (id.notNull())
+ {
+ if (!hasLightTexture())
+ {
+ setParameterEntryInUse(LLNetworkData::PARAMS_LIGHT_IMAGE, TRUE, true);
+ }
+ LLLightImageParams* param_block = (LLLightImageParams*) getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
+ if (param_block && param_block->getLightTexture() != id)
+ {
+ param_block->setLightTexture(id);
+ parameterChanged(LLNetworkData::PARAMS_LIGHT_IMAGE, true);
+ }
+ }
+ else
+ {
+ if (hasLightTexture())
+ {
+ setParameterEntryInUse(LLNetworkData::PARAMS_LIGHT_IMAGE, FALSE, true);
+ mLightTexture = NULL;
+ }
+ }
+}
+
+void LLVOVolume::setSpotLightParams(LLVector3 params)
+{
+ LLLightImageParams* param_block = (LLLightImageParams*) getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
+ if (param_block && param_block->getParams() != params)
+ {
+ param_block->setParams(params);
+ parameterChanged(LLNetworkData::PARAMS_LIGHT_IMAGE, true);
+ }
+}
+
+void LLVOVolume::setIsLight(BOOL is_light)
+{
+ if (is_light != getIsLight())
+ {
+ if (is_light)
+ {
+ setParameterEntryInUse(LLNetworkData::PARAMS_LIGHT, TRUE, true);
+ }
+ else
+ {
+ setParameterEntryInUse(LLNetworkData::PARAMS_LIGHT, FALSE, true);
+ }
+
+ if (is_light)
+ {
+ // Add it to the pipeline mLightSet
+ gPipeline.setLight(mDrawable, TRUE);
+ }
+ else
+ {
+ // Not a light. Remove it from the pipeline's light set.
+ gPipeline.setLight(mDrawable, FALSE);
+ }
+ }
+}
+
+void LLVOVolume::setLightColor(const LLColor3& color)
+{
+ LLLightParams *param_block = (LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ if (param_block->getColor() != color)
+ {
+ param_block->setColor(LLColor4(color, param_block->getColor().mV[3]));
+ parameterChanged(LLNetworkData::PARAMS_LIGHT, true);
+ gPipeline.markTextured(mDrawable);
+ mFaceMappingChanged = TRUE;
+ }
+ }
+}
+
+void LLVOVolume::setLightIntensity(F32 intensity)
+{
+ LLLightParams *param_block = (LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ if (param_block->getColor().mV[3] != intensity)
+ {
+ param_block->setColor(LLColor4(LLColor3(param_block->getColor()), intensity));
+ parameterChanged(LLNetworkData::PARAMS_LIGHT, true);
+ }
+ }
+}
+
+void LLVOVolume::setLightRadius(F32 radius)
+{
+ LLLightParams *param_block = (LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ if (param_block->getRadius() != radius)
+ {
+ param_block->setRadius(radius);
+ parameterChanged(LLNetworkData::PARAMS_LIGHT, true);
+ }
+ }
+}
+
+void LLVOVolume::setLightFalloff(F32 falloff)
+{
+ LLLightParams *param_block = (LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ if (param_block->getFalloff() != falloff)
+ {
+ param_block->setFalloff(falloff);
+ parameterChanged(LLNetworkData::PARAMS_LIGHT, true);
+ }
+ }
+}
+
+void LLVOVolume::setLightCutoff(F32 cutoff)
+{
+ LLLightParams *param_block = (LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ if (param_block->getCutoff() != cutoff)
+ {
+ param_block->setCutoff(cutoff);
+ parameterChanged(LLNetworkData::PARAMS_LIGHT, true);
+ }
+ }
+}
+
+//----------------------------------------------------------------------------
+
+BOOL LLVOVolume::getIsLight() const
+{
+ return getParameterEntryInUse(LLNetworkData::PARAMS_LIGHT);
+}
+
+LLColor3 LLVOVolume::getLightBaseColor() const
+{
+ const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ return LLColor3(param_block->getColor());
+ }
+ else
+ {
+ return LLColor3(1,1,1);
+ }
+}
+
+LLColor3 LLVOVolume::getLightColor() const
+{
+ const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ return LLColor3(param_block->getColor()) * param_block->getColor().mV[3];
+ }
+ else
+ {
+ return LLColor3(1,1,1);
+ }
+}
+
+LLUUID LLVOVolume::getLightTextureID() const
+{
+ if (getParameterEntryInUse(LLNetworkData::PARAMS_LIGHT_IMAGE))
+ {
+ const LLLightImageParams *param_block = (const LLLightImageParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
+ if (param_block)
+ {
+ return param_block->getLightTexture();
+ }
+ }
+
+ return LLUUID::null;
+}
+
+
+LLVector3 LLVOVolume::getSpotLightParams() const
+{
+ if (getParameterEntryInUse(LLNetworkData::PARAMS_LIGHT_IMAGE))
+ {
+ const LLLightImageParams *param_block = (const LLLightImageParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
+ if (param_block)
+ {
+ return param_block->getParams();
+ }
+ }
+
+ return LLVector3();
+}
+
+F32 LLVOVolume::getSpotLightPriority() const
+{
+ return mSpotLightPriority;
+}
+
+void LLVOVolume::updateSpotLightPriority()
+{
+ LLVector3 pos = mDrawable->getPositionAgent();
+ LLVector3 at(0,0,-1);
+ at *= getRenderRotation();
+
+ F32 r = getLightRadius()*0.5f;
+
+ pos += at * r;
+
+ at = LLViewerCamera::getInstance()->getAtAxis();
+
+ pos -= at * r;
+
+ mSpotLightPriority = gPipeline.calcPixelArea(pos, LLVector3(r,r,r), *LLViewerCamera::getInstance());
+
+ if (mLightTexture.notNull())
+ {
+ mLightTexture->addTextureStats(mSpotLightPriority);
+ mLightTexture->setBoostLevel(LLViewerTexture::BOOST_CLOUDS);
+ }
+}
+
+
+bool LLVOVolume::isLightSpotlight() const
+{
+ LLLightImageParams* params = (LLLightImageParams*) getParameterEntry(LLNetworkData::PARAMS_LIGHT_IMAGE);
+ if (params)
+ {
+ return params->isLightSpotlight();
+ }
+ return false;
+}
+
+
+LLViewerTexture* LLVOVolume::getLightTexture()
+{
+ LLUUID id = getLightTextureID();
+
+ if (id.notNull())
+ {
+ if (mLightTexture.isNull() || id != mLightTexture->getID())
+ {
+ mLightTexture = LLViewerTextureManager::getFetchedTexture(id);
+ }
+ }
+ else
+ {
+ mLightTexture = NULL;
+ }
+
+ return mLightTexture;
+}
+
+F32 LLVOVolume::getLightIntensity() const
+{
+ const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ return param_block->getColor().mV[3];
+ }
+ else
+ {
+ return 1.f;
+ }
+}
+
+F32 LLVOVolume::getLightRadius() const
+{
+ const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ return param_block->getRadius();
+ }
+ else
+ {
+ return 0.f;
+ }
+}
+
+F32 LLVOVolume::getLightFalloff() const
+{
+ const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ return param_block->getFalloff();
+ }
+ else
+ {
+ return 0.f;
+ }
+}
+
+F32 LLVOVolume::getLightCutoff() const
+{
+ const LLLightParams *param_block = (const LLLightParams *)getParameterEntry(LLNetworkData::PARAMS_LIGHT);
+ if (param_block)
+ {
+ return param_block->getCutoff();
+ }
+ else
+ {
+ return 0.f;
+ }
+}
+
+U32 LLVOVolume::getVolumeInterfaceID() const
+{
+ if (mVolumeImpl)
+ {
+ return mVolumeImpl->getID();
+ }
+
+ return 0;
+}
+
+BOOL LLVOVolume::isFlexible() const
+{
+ if (getParameterEntryInUse(LLNetworkData::PARAMS_FLEXIBLE))
+ {
+ LLVolume* volume = getVolume();
+ if (volume && volume->getParams().getPathParams().getCurveType() != LL_PCODE_PATH_FLEXIBLE)
+ {
+ LLVolumeParams volume_params = getVolume()->getParams();
+ U8 profile_and_hole = volume_params.getProfileParams().getCurveType();
+ volume_params.setType(profile_and_hole, LL_PCODE_PATH_FLEXIBLE);
+ }
+ return TRUE;
+ }
+ else
+ {
+ return FALSE;
+ }
+}
+
+BOOL LLVOVolume::isSculpted() const
+{
+ if (getParameterEntryInUse(LLNetworkData::PARAMS_SCULPT))
+ {
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+BOOL LLVOVolume::isMesh() const
+{
+ if (isSculpted())
+ {
+ LLSculptParams *sculpt_params = (LLSculptParams *)getParameterEntry(LLNetworkData::PARAMS_SCULPT);
+ U8 sculpt_type = sculpt_params->getSculptType();
+
+ if ((sculpt_type & LL_SCULPT_TYPE_MASK) == LL_SCULPT_TYPE_MESH)
+ // mesh is a mesh
+ {
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+}
+
+BOOL LLVOVolume::hasLightTexture() const
+{
+ if (getParameterEntryInUse(LLNetworkData::PARAMS_LIGHT_IMAGE))
+ {
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+BOOL LLVOVolume::isVolumeGlobal() const
+{
+ if (mVolumeImpl)
+ {
+ return mVolumeImpl->isVolumeGlobal() ? TRUE : FALSE;
+ }
+ else if (mRiggedVolume.notNull())
+ {
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+BOOL LLVOVolume::canBeFlexible() const
+{
+ U8 path = getVolume()->getParams().getPathParams().getCurveType();
+ return (path == LL_PCODE_PATH_FLEXIBLE || path == LL_PCODE_PATH_LINE);
+}
+
+BOOL LLVOVolume::setIsFlexible(BOOL is_flexible)
+{
+ BOOL res = FALSE;
+ BOOL was_flexible = isFlexible();
+ LLVolumeParams volume_params;
+ if (is_flexible)
+ {
+ if (!was_flexible)
+ {
+ volume_params = getVolume()->getParams();
+ U8 profile_and_hole = volume_params.getProfileParams().getCurveType();
+ volume_params.setType(profile_and_hole, LL_PCODE_PATH_FLEXIBLE);
+ res = TRUE;
+ setFlags(FLAGS_USE_PHYSICS, FALSE);
+ setFlags(FLAGS_PHANTOM, TRUE);
+ setParameterEntryInUse(LLNetworkData::PARAMS_FLEXIBLE, TRUE, true);
+ if (mDrawable)
+ {
+ mDrawable->makeActive();
+ }
+ }
+ }
+ else
+ {
+ if (was_flexible)
+ {
+ volume_params = getVolume()->getParams();
+ U8 profile_and_hole = volume_params.getProfileParams().getCurveType();
+ volume_params.setType(profile_and_hole, LL_PCODE_PATH_LINE);
+ res = TRUE;
+ setFlags(FLAGS_PHANTOM, FALSE);
+ setParameterEntryInUse(LLNetworkData::PARAMS_FLEXIBLE, FALSE, true);
+ }
+ }
+ if (res)
+ {
+ res = setVolume(volume_params, 1);
+ if (res)
+ {
+ markForUpdate(TRUE);
+ }
+ }
+ return res;
+}
+
+//----------------------------------------------------------------------------
+
+void LLVOVolume::generateSilhouette(LLSelectNode* nodep, const LLVector3& view_point)
+{
+ LLVolume *volume = getVolume();
+
+ if (volume)
+ {
+ LLVector3 view_vector;
+ view_vector = view_point;
+
+ //transform view vector into volume space
+ view_vector -= getRenderPosition();
+ mDrawable->mDistanceWRTCamera = view_vector.length();
+ LLQuaternion worldRot = getRenderRotation();
+ view_vector = view_vector * ~worldRot;
+ if (!isVolumeGlobal())
+ {
+ LLVector3 objScale = getScale();
+ LLVector3 invObjScale(1.f / objScale.mV[VX], 1.f / objScale.mV[VY], 1.f / objScale.mV[VZ]);
+ view_vector.scaleVec(invObjScale);
+ }
+
+ updateRelativeXform();
+ LLMatrix4 trans_mat = mRelativeXform;
+ if (mDrawable->isStatic())
+ {
+ trans_mat.translate(getRegion()->getOriginAgent());
+ }
+
+ volume->generateSilhouetteVertices(nodep->mSilhouetteVertices, nodep->mSilhouetteNormals, view_vector, trans_mat, mRelativeXformInvTrans, nodep->getTESelectMask());
+
+ nodep->mSilhouetteExists = TRUE;
+ }
+}
+
+void LLVOVolume::deleteFaces()
+{
+ S32 face_count = mNumFaces;
+ if (mDrawable.notNull())
+ {
+ mDrawable->deleteFaces(0, face_count);
+ }
+
+ mNumFaces = 0;
+}
+
+void LLVOVolume::updateRadius()
+{
+ if (mDrawable.isNull())
+ {
+ return;
+ }
+
+ mVObjRadius = getScale().length();
+ mDrawable->setRadius(mVObjRadius);
+}
+
+
+BOOL LLVOVolume::isAttachment() const
+{
+ return mState != 0 ;
+}
+
+BOOL LLVOVolume::isHUDAttachment() const
+{
+ // *NOTE: we assume hud attachment points are in defined range
+ // since this range is constant for backwards compatibility
+ // reasons this is probably a reasonable assumption to make
+ S32 attachment_id = ATTACHMENT_ID_FROM_STATE(mState);
+ return ( attachment_id >= 31 && attachment_id <= 38 );
+}
+
+
+const LLMatrix4 LLVOVolume::getRenderMatrix() const
+{
+ if (mDrawable->isActive() && !mDrawable->isRoot())
+ {
+ return mDrawable->getParent()->getWorldMatrix();
+ }
+ return mDrawable->getWorldMatrix();
+}
+
+// Returns a base cost and adds textures to passed in set.
+// total cost is returned value + 5 * size of the resulting set.
+// Cannot include cost of textures, as they may be re-used in linked
+// children, and cost should only be increased for unique textures -Nyx
+U32 LLVOVolume::getRenderCost(std::set<LLUUID> &textures) const
+{
+ // base cost of each prim should be 10 points
+ static const U32 ARC_PRIM_COST = 10;
+ // per-prim costs
+ static const U32 ARC_INVISI_COST = 1;
+ static const U32 ARC_SHINY_COST = 1;
+ static const U32 ARC_GLOW_COST = 1;
+ static const U32 ARC_FLEXI_COST = 8;
+ static const U32 ARC_PARTICLE_COST = 16;
+ static const U32 ARC_BUMP_COST = 4;
+
+ // per-face costs
+ static const U32 ARC_PLANAR_COST = 1;
+ static const U32 ARC_ANIM_TEX_COST = 4;
+ static const U32 ARC_ALPHA_COST = 4;
+
+ U32 shame = ARC_PRIM_COST;
+
+ U32 invisi = 0;
+ U32 shiny = 0;
+ U32 glow = 0;
+ U32 alpha = 0;
+ U32 flexi = 0;
+ U32 animtex = 0;
+ U32 particles = 0;
+ U32 scale = 0;
+ U32 bump = 0;
+ U32 planar = 0;
+
+ if (isFlexible())
+ {
+ flexi = 1;
+ }
+ if (isParticleSource())
+ {
+ particles = 1;
+ }
+
+ const LLVector3& sc = getScale();
+ scale += (U32) sc.mV[0] + (U32) sc.mV[1] + (U32) sc.mV[2];
+
+ const LLDrawable* drawablep = mDrawable;
+
+ if (isSculpted())
+ {
+ const LLSculptParams *sculpt_params = (LLSculptParams *) getParameterEntry(LLNetworkData::PARAMS_SCULPT);
+ LLUUID sculpt_id = sculpt_params->getSculptTexture();
+ textures.insert(sculpt_id);
+ }
+
+ for (S32 i = 0; i < drawablep->getNumFaces(); ++i)
+ {
+ const LLFace* face = drawablep->getFace(i);
+ const LLTextureEntry* te = face->getTextureEntry();
+ const LLViewerTexture* img = face->getTexture();
+
+ if (img)
+ {
+ textures.insert(img->getID());
+ }
+
+ if (face->getPoolType() == LLDrawPool::POOL_ALPHA)
+ {
+ alpha++;
+ }
+ else if (img && img->getPrimaryFormat() == GL_ALPHA)
+ {
+ invisi = 1;
+ }
+
+ if (te)
+ {
+ if (te->getBumpmap())
+ {
+ bump = 1;
+ }
+ if (te->getShiny())
+ {
+ shiny = 1;
+ }
+ if (te->getGlow() > 0.f)
+ {
+ glow = 1;
+ }
+ if (face->mTextureMatrix != NULL)
+ {
+ animtex++;
+ }
+ if (te->getTexGen())
+ {
+ planar++;
+ }
+ }
+ }
+
+
+ shame += invisi * ARC_INVISI_COST;
+ shame += shiny * ARC_SHINY_COST;
+ shame += glow * ARC_GLOW_COST;
+ shame += alpha * ARC_ALPHA_COST;
+ shame += flexi * ARC_FLEXI_COST;
+ shame += animtex * ARC_ANIM_TEX_COST;
+ shame += particles * ARC_PARTICLE_COST;
+ shame += bump * ARC_BUMP_COST;
+ shame += planar * ARC_PLANAR_COST;
+ shame += scale;
+
+ LLViewerObject::const_child_list_t& child_list = getChildren();
+ for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
+ iter != child_list.end();
+ ++iter)
+ {
+ const LLViewerObject* child_objectp = *iter;
+ const LLDrawable* child_drawablep = child_objectp->mDrawable;
+ if (child_drawablep)
+ {
+ const LLVOVolume* child_volumep = child_drawablep->getVOVolume();
+ if (child_volumep)
+ {
+ shame += child_volumep->getRenderCost(textures);
+ }
+ }
+ }
+
+ return shame;
+
+}
+
+F32 LLVOVolume::getStreamingCost()
+{
+ if (isMesh())
+ {
+ const LLSD& header = gMeshRepo.getMeshHeader(getVolume()->getParams().getSculptID());
+
+ F32 radius = getScale().length();
+
+ return LLMeshRepository::getStreamingCost(header, radius);
+ }
+
+ return 0.f;
+}
+
+U32 LLVOVolume::getTriangleCount()
+{
+ U32 count = 0;
+ LLVolume* volume = getVolume();
+ if (volume)
+ {
+ count = volume->getNumTriangles();
+ }
+
+ return count;
+}
+
+//static
+void LLVOVolume::preUpdateGeom()
+{
+ sNumLODChanges = 0;
+}
+
+void LLVOVolume::parameterChanged(U16 param_type, bool local_origin)
+{
+ LLViewerObject::parameterChanged(param_type, local_origin);
+}
+
+void LLVOVolume::parameterChanged(U16 param_type, LLNetworkData* data, BOOL in_use, bool local_origin)
+{
+ LLViewerObject::parameterChanged(param_type, data, in_use, local_origin);
+ if (mVolumeImpl)
+ {
+ mVolumeImpl->onParameterChanged(param_type, data, in_use, local_origin);
+ }
+ if (mDrawable.notNull())
+ {
+ BOOL is_light = getIsLight();
+ if (is_light != mDrawable->isState(LLDrawable::LIGHT))
+ {
+ gPipeline.setLight(mDrawable, is_light);
+ }
+ }
+}
+
+void LLVOVolume::setSelected(BOOL sel)
+{
+ LLViewerObject::setSelected(sel);
+ if (mDrawable.notNull())
+ {
+ markForUpdate(TRUE);
+ }
+}
+
+void LLVOVolume::updateSpatialExtents(LLVector4a& newMin, LLVector4a& newMax)
+{
+}
+
+F32 LLVOVolume::getBinRadius()
+{
+ F32 radius;
+
+ F32 scale = 1.f;
+
+ const LLVector4a* ext = mDrawable->getSpatialExtents();
+
+ BOOL shrink_wrap = mDrawable->isAnimating();
+ BOOL alpha_wrap = FALSE;
+
+ if (!isHUDAttachment())
+ {
+ for (S32 i = 0; i < mDrawable->getNumFaces(); i++)
+ {
+ LLFace* face = mDrawable->getFace(i);
+ if (face->getPoolType() == LLDrawPool::POOL_ALPHA &&
+ !face->canRenderAsMask())
+ {
+ alpha_wrap = TRUE;
+ break;
+ }
+ }
+ }
+ else
+ {
+ shrink_wrap = FALSE;
+ }
+
+ if (alpha_wrap)
+ {
+ LLVector3 bounds = getScale();
+ radius = llmin(bounds.mV[1], bounds.mV[2]);
+ radius = llmin(radius, bounds.mV[0]);
+ radius *= 0.5f;
+ }
+ else if (shrink_wrap)
+ {
+ LLVector4a rad;
+ rad.setSub(ext[1], ext[0]);
+
+ radius = rad.getLength3().getF32()*0.5f;
+ }
+ else if (mDrawable->isStatic())
+ {
+ /*if (mDrawable->getRadius() < 2.0f)
+ {
+ radius = 16.f;
+ }
+ else
+ {
+ radius = llmax(mDrawable->getRadius(), 32.f);
+ }*/
+
+ radius = (((S32) mDrawable->getRadius())/2+1)*8;
+ }
+ else if (mDrawable->getVObj()->isAttachment())
+ {
+ radius = (((S32) (mDrawable->getRadius()*4)+1))*2;
+ }
+ else
+ {
+ radius = 8.f;
+ }
+
+ return llclamp(radius*scale, 0.5f, 256.f);
+}
+
+const LLVector3 LLVOVolume::getPivotPositionAgent() const
+{
+ if (mVolumeImpl)
+ {
+ return mVolumeImpl->getPivotPosition();
+ }
+ return LLViewerObject::getPivotPositionAgent();
+}
+
+void LLVOVolume::onShift(const LLVector4a &shift_vector)
+{
+ if (mVolumeImpl)
+ {
+ mVolumeImpl->onShift(shift_vector);
+ }
+
+ updateRelativeXform();
+}
+
+const LLMatrix4& LLVOVolume::getWorldMatrix(LLXformMatrix* xform) const
+{
+ if (mVolumeImpl)
+ {
+ return mVolumeImpl->getWorldMatrix(xform);
+ }
+ return xform->getWorldMatrix();
+}
+
+LLVector3 LLVOVolume::agentPositionToVolume(const LLVector3& pos) const
+{
+ LLVector3 ret = pos - getRenderPosition();
+ ret = ret * ~getRenderRotation();
+ LLVector3 objScale = isVolumeGlobal() ? LLVector3(1,1,1) : getScale();
+ LLVector3 invObjScale(1.f / objScale.mV[VX], 1.f / objScale.mV[VY], 1.f / objScale.mV[VZ]);
+ ret.scaleVec(invObjScale);
+
+ return ret;
+}
+
+LLVector3 LLVOVolume::agentDirectionToVolume(const LLVector3& dir) const
+{
+ LLVector3 ret = dir * ~getRenderRotation();
+
+ LLVector3 objScale = isVolumeGlobal() ? LLVector3(1,1,1) : getScale();
+ ret.scaleVec(objScale);
+
+ return ret;
+}
+
+LLVector3 LLVOVolume::volumePositionToAgent(const LLVector3& dir) const
+{
+ LLVector3 ret = dir;
+ LLVector3 objScale = isVolumeGlobal() ? LLVector3(1,1,1) : getScale();
+ ret.scaleVec(objScale);
+ ret = ret * getRenderRotation();
+ ret += getRenderPosition();
+
+ return ret;
+}
+
+LLVector3 LLVOVolume::volumeDirectionToAgent(const LLVector3& dir) const
+{
+ LLVector3 ret = dir;
+ LLVector3 objScale = isVolumeGlobal() ? LLVector3(1,1,1) : getScale();
+ LLVector3 invObjScale(1.f / objScale.mV[VX], 1.f / objScale.mV[VY], 1.f / objScale.mV[VZ]);
+ ret.scaleVec(invObjScale);
+ ret = ret * getRenderRotation();
+
+ return ret;
+}
+
+
+BOOL LLVOVolume::lineSegmentIntersect(const LLVector3& start, const LLVector3& end, S32 face, BOOL pick_transparent, S32 *face_hitp,
+ LLVector3* intersection,LLVector2* tex_coord, LLVector3* normal, LLVector3* bi_normal)
+
+{
+ if (!mbCanSelect
+ || mDrawable->isDead()
+ || !gPipeline.hasRenderType(mDrawable->getRenderType()))
+ {
+ return FALSE;
+ }
+
+ BOOL ret = FALSE;
+
+ LLVolume* volume = getVolume();
+
+ bool transform = true;
+
+ if (mDrawable->isState(LLDrawable::RIGGED))
+ {
+ if (LLFloater::isVisible(gFloaterTools) && getAvatar()->isSelf())
+ {
+ gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_RIGGED, TRUE);
+ volume = mRiggedVolume;
+ transform = false;
+ }
+ else
+ { //cannot pick rigged attachments on other avatars or when not in build mode
+ return FALSE;
+ }
+ }
+
+ if (volume)
+ {
+ LLVector3 v_start, v_end, v_dir;
+
+ if (transform)
+ {
+ v_start = agentPositionToVolume(start);
+ v_end = agentPositionToVolume(end);
+ }
+ else
+ {
+ v_start = start;
+ v_end = end;
+ }
+
+ LLVector3 p;
+ LLVector3 n;
+ LLVector2 tc;
+ LLVector3 bn;
+
+ if (intersection != NULL)
+ {
+ p = *intersection;
+ }
+
+ if (tex_coord != NULL)
+ {
+ tc = *tex_coord;
+ }
+
+ if (normal != NULL)
+ {
+ n = *normal;
+ }
+
+ if (bi_normal != NULL)
+ {
+ bn = *bi_normal;
+ }
+
+ S32 face_hit = -1;
+
+ S32 start_face, end_face;
+ if (face == -1)
+ {
+ start_face = 0;
+ end_face = volume->getNumVolumeFaces();
+ }
+ else
+ {
+ start_face = face;
+ end_face = face+1;
+ }
+
+ bool special_cursor = specialHoverCursor();
+ for (S32 i = start_face; i < end_face; ++i)
+ {
+ if (!special_cursor && !pick_transparent && getTE(i)->getColor().mV[3] == 0.f)
+ { //don't attempt to pick completely transparent faces unless
+ //pick_transparent is true
+ continue;
+ }
+
+ face_hit = volume->lineSegmentIntersect(v_start, v_end, i,
+ &p, &tc, &n, &bn);
+
+ if (face_hit >= 0 && mDrawable->getNumFaces() > face_hit)
+ {
+ LLFace* face = mDrawable->getFace(face_hit);
+
+ if (pick_transparent || !face->getTexture() || !face->getTexture()->hasGLTexture() || face->getTexture()->getMask(face->surfaceToTexture(tc, p, n)))
+ {
+ v_end = p;
+ if (face_hitp != NULL)
+ {
+ *face_hitp = face_hit;
+ }
+
+ if (intersection != NULL)
+ {
+ if (transform)
+ {
+ *intersection = volumePositionToAgent(p); // must map back to agent space
+ }
+ else
+ {
+ *intersection = p;
+ }
+ }
+
+ if (normal != NULL)
+ {
+ if (transform)
+ {
+ *normal = volumeDirectionToAgent(n);
+ }
+ else
+ {
+ *normal = n;
+ }
+
+ (*normal).normVec();
+ }
+
+ if (bi_normal != NULL)
+ {
+ if (transform)
+ {
+ *bi_normal = volumeDirectionToAgent(bn);
+ }
+ else
+ {
+ *bi_normal = bn;
+ }
+ (*bi_normal).normVec();
+ }
+
+ if (tex_coord != NULL)
+ {
+ *tex_coord = tc;
+ }
+
+ ret = TRUE;
+ }
+ }
+ }
+ }
+
+ return ret;
+}
+
+bool LLVOVolume::treatAsRigged()
+{
+ return LLFloater::isVisible(gFloaterTools) &&
+ isAttachment() &&
+ getAvatar() &&
+ getAvatar()->isSelf() &&
+ mDrawable.notNull() &&
+ mDrawable->isState(LLDrawable::RIGGED);
+}
+
+LLRiggedVolume* LLVOVolume::getRiggedVolume()
+{
+ return mRiggedVolume;
+}
+
+void LLVOVolume::clearRiggedVolume()
+{
+ if (mRiggedVolume.notNull())
+ {
+ mRiggedVolume = NULL;
+ updateRelativeXform();
+ }
+}
+
+void LLVOVolume::updateRiggedVolume()
+{
+ //Update mRiggedVolume to match current animation frame of avatar.
+ //Also update position/size in octree.
+
+ if (!treatAsRigged())
+ {
+ clearRiggedVolume();
+
+ return;
+ }
+
+ LLVolume* volume = getVolume();
+
+ const LLMeshSkinInfo* skin = gMeshRepo.getSkinInfo(volume->getParams().getSculptID());
+
+ if (!skin)
+ {
+ clearRiggedVolume();
+ return;
+ }
+
+ LLVOAvatar* avatar = getAvatar();
+
+ if (!avatar)
+ {
+ clearRiggedVolume();
+ return;
+ }
+
+ if (!mRiggedVolume)
+ {
+ LLVolumeParams p;
+ mRiggedVolume = new LLRiggedVolume(p);
+ updateRelativeXform();
+ }
+
+ mRiggedVolume->update(skin, avatar, volume);
+
+}
+
+static LLFastTimer::DeclareTimer FTM_SKIN_RIGGED("Skin");
+static LLFastTimer::DeclareTimer FTM_RIGGED_OCTREE("Octree");
+
+void LLRiggedVolume::update(const LLMeshSkinInfo* skin, LLVOAvatar* avatar, const LLVolume* volume)
+{
+ bool copy = false;
+ if (volume->getNumVolumeFaces() != getNumVolumeFaces())
+ {
+ copy = true;
+ }
+
+ for (S32 i = 0; i < volume->getNumVolumeFaces() && !copy; ++i)
+ {
+ const LLVolumeFace& src_face = volume->getVolumeFace(i);
+ const LLVolumeFace& dst_face = getVolumeFace(i);
+
+ if (src_face.mNumIndices != dst_face.mNumIndices ||
+ src_face.mNumVertices != dst_face.mNumVertices)
+ {
+ copy = true;
+ }
+ }
+
+ if (copy)
+ {
+ copyVolumeFaces(volume);
+ }
+
+ //build matrix palette
+ LLMatrix4a mp[64];
+ LLMatrix4* mat = (LLMatrix4*) mp;
+
+ for (U32 j = 0; j < skin->mJointNames.size(); ++j)
+ {
+ LLJoint* joint = avatar->getJoint(skin->mJointNames[j]);
+ if (joint)
+ {
+ mat[j] = skin->mInvBindMatrix[j];
+ mat[j] *= joint->getWorldMatrix();
+ }
+ }
+
+ for (S32 i = 0; i < volume->getNumVolumeFaces(); ++i)
+ {
+ const LLVolumeFace& vol_face = volume->getVolumeFace(i);
+
+ LLVolumeFace& dst_face = mVolumeFaces[i];
+
+ LLVector4a* weight = vol_face.mWeights;
+
+ LLMatrix4a bind_shape_matrix;
+ bind_shape_matrix.loadu(skin->mBindShapeMatrix);
+
+ LLVector4a* pos = dst_face.mPositions;
+
+ {
+ LLFastTimer t(FTM_SKIN_RIGGED);
+
+ for (U32 j = 0; j < dst_face.mNumVertices; ++j)
+ {
+ LLMatrix4a final_mat;
+ final_mat.clear();
+
+ S32 idx[4];
+
+ LLVector4 wght;
+
+ F32 scale = 0.f;
+ for (U32 k = 0; k < 4; k++)
+ {
+ F32 w = weight[j][k];
+
+ idx[k] = (S32) floorf(w);
+ wght[k] = w - floorf(w);
+ scale += wght[k];
+ }
+
+ wght *= 1.f/scale;
+
+ for (U32 k = 0; k < 4; k++)
+ {
+ F32 w = wght[k];
+
+ LLMatrix4a src;
+ src.setMul(mp[idx[k]], w);
+
+ final_mat.add(src);
+ }
+
+
+ LLVector4a& v = vol_face.mPositions[j];
+ LLVector4a t;
+ LLVector4a dst;
+ bind_shape_matrix.affineTransform(v, t);
+ final_mat.affineTransform(t, dst);
+ pos[j] = dst;
+ }
+
+ //update bounding box
+ LLVector4a& min = dst_face.mExtents[0];
+ LLVector4a& max = dst_face.mExtents[1];
+
+ min = pos[0];
+ max = pos[1];
+
+ for (U32 j = 1; j < dst_face.mNumVertices; ++j)
+ {
+ min.setMin(min, pos[j]);
+ max.setMax(max, pos[j]);
+ }
+
+ dst_face.mCenter->setAdd(dst_face.mExtents[0], dst_face.mExtents[1]);
+ dst_face.mCenter->mul(0.5f);
+
+ }
+
+ {
+ LLFastTimer t(FTM_RIGGED_OCTREE);
+ delete dst_face.mOctree;
+ dst_face.mOctree = NULL;
+
+ LLVector4a size;
+ size.setSub(dst_face.mExtents[1], dst_face.mExtents[0]);
+ size.splat(size.getLength3().getF32()*0.5f);
+
+ dst_face.createOctree(1.f);
+ }
+ }
+}
+
+U32 LLVOVolume::getPartitionType() const
+{
+ if (isHUDAttachment())
+ {
+ return LLViewerRegion::PARTITION_HUD;
+ }
+
+ return LLViewerRegion::PARTITION_VOLUME;
+}
+
+LLVolumePartition::LLVolumePartition()
+: LLSpatialPartition(LLVOVolume::VERTEX_DATA_MASK, TRUE, GL_DYNAMIC_DRAW_ARB)
+{
+ mLODPeriod = 32;
+ mDepthMask = FALSE;
+ mDrawableType = LLPipeline::RENDER_TYPE_VOLUME;
+ mPartitionType = LLViewerRegion::PARTITION_VOLUME;
+ mSlopRatio = 0.25f;
+ mBufferUsage = GL_DYNAMIC_DRAW_ARB;
+}
+
+LLVolumeBridge::LLVolumeBridge(LLDrawable* drawablep)
+: LLSpatialBridge(drawablep, TRUE, LLVOVolume::VERTEX_DATA_MASK)
+{
+ mDepthMask = FALSE;
+ mLODPeriod = 32;
+ mDrawableType = LLPipeline::RENDER_TYPE_VOLUME;
+ mPartitionType = LLViewerRegion::PARTITION_BRIDGE;
+
+ mBufferUsage = GL_DYNAMIC_DRAW_ARB;
+
+ mSlopRatio = 0.25f;
+}
+
+void LLVolumeGeometryManager::registerFace(LLSpatialGroup* group, LLFace* facep, U32 type)
+{
+ LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION);
+
+ if (facep->getViewerObject()->isSelected() && LLSelectMgr::getInstance()->mHideSelectedObjects)
+ {
+ return;
+ }
+
+ //add face to drawmap
+ LLSpatialGroup::drawmap_elem_t& draw_vec = group->mDrawMap[type];
+
+ S32 idx = draw_vec.size()-1;
+
+ BOOL fullbright = (type == LLRenderPass::PASS_FULLBRIGHT) ||
+ (type == LLRenderPass::PASS_INVISIBLE) ||
+ (type == LLRenderPass::PASS_ALPHA && facep->isState(LLFace::FULLBRIGHT));
+
+ if (!fullbright && type != LLRenderPass::PASS_GLOW && !facep->getVertexBuffer()->hasDataType(LLVertexBuffer::TYPE_NORMAL))
+ {
+ llwarns << "Non fullbright face has no normals!" << llendl;
+ return;
+ }
+
+ const LLMatrix4* tex_mat = NULL;
+ if (facep->isState(LLFace::TEXTURE_ANIM) && facep->getVirtualSize() > MIN_TEX_ANIM_SIZE)
+ {
+ tex_mat = facep->mTextureMatrix;
+ }
+
+ const LLMatrix4* model_mat = NULL;
+
+ LLDrawable* drawable = facep->getDrawable();
+ if (drawable->isActive())
+ {
+ model_mat = &(drawable->getRenderMatrix());
+ }
+ else
+ {
+ model_mat = &(drawable->getRegion()->mRenderMatrix);
+ if (model_mat->isIdentity())
+ {
+ model_mat = NULL;
+ }
+ }
+
+ U8 bump = (type == LLRenderPass::PASS_BUMP || type == LLRenderPass::PASS_POST_BUMP) ? facep->getTextureEntry()->getBumpmap() : 0;
+
+ LLViewerTexture* tex = facep->getTexture();
+
+ U8 glow = (U8) (facep->getTextureEntry()->getGlow() * 255);
+
+ if (idx >= 0 &&
+ draw_vec[idx]->mVertexBuffer == facep->getVertexBuffer() &&
+ draw_vec[idx]->mEnd == facep->getGeomIndex()-1 &&
+ (LLPipeline::sTextureBindTest || draw_vec[idx]->mTexture == tex) &&
+#if LL_DARWIN
+ draw_vec[idx]->mEnd - draw_vec[idx]->mStart + facep->getGeomCount() <= (U32) gGLManager.mGLMaxVertexRange &&
+ draw_vec[idx]->mCount + facep->getIndicesCount() <= (U32) gGLManager.mGLMaxIndexRange &&
+#endif
+ draw_vec[idx]->mGlowColor.mV[3] == glow &&
+ draw_vec[idx]->mFullbright == fullbright &&
+ draw_vec[idx]->mBump == bump &&
+ draw_vec[idx]->mTextureMatrix == tex_mat &&
+ draw_vec[idx]->mModelMatrix == model_mat)
+ {
+ draw_vec[idx]->mCount += facep->getIndicesCount();
+ draw_vec[idx]->mEnd += facep->getGeomCount();
+ draw_vec[idx]->mVSize = llmax(draw_vec[idx]->mVSize, facep->getVirtualSize());
+ draw_vec[idx]->validate();
+ update_min_max(draw_vec[idx]->mExtents[0], draw_vec[idx]->mExtents[1], facep->mExtents[0]);
+ update_min_max(draw_vec[idx]->mExtents[0], draw_vec[idx]->mExtents[1], facep->mExtents[1]);
+ }
+ else
+ {
+ U32 start = facep->getGeomIndex();
+ U32 end = start + facep->getGeomCount()-1;
+ U32 offset = facep->getIndicesStart();
+ U32 count = facep->getIndicesCount();
+ LLPointer<LLDrawInfo> draw_info = new LLDrawInfo(start,end,count,offset, tex,
+ facep->getVertexBuffer(), fullbright, bump);
+ draw_info->mGroup = group;
+ draw_info->mVSize = facep->getVirtualSize();
+ draw_vec.push_back(draw_info);
+ draw_info->mTextureMatrix = tex_mat;
+ draw_info->mModelMatrix = model_mat;
+ draw_info->mGlowColor.setVec(0,0,0,glow);
+ if (type == LLRenderPass::PASS_ALPHA)
+ { //for alpha sorting
+ facep->setDrawInfo(draw_info);
+ }
+ draw_info->mExtents[0] = facep->mExtents[0];
+ draw_info->mExtents[1] = facep->mExtents[1];
+
+ if (LLPipeline::sUseTriStrips)
+ {
+ draw_info->mDrawMode = LLRender::TRIANGLE_STRIP;
+ }
+
+ draw_info->validate();
+ }
+}
+
+void LLVolumeGeometryManager::getGeometry(LLSpatialGroup* group)
+{
+
+}
+
+static LLFastTimer::DeclareTimer FTM_REBUILD_VOLUME_VB("Volume");
+static LLFastTimer::DeclareTimer FTM_REBUILD_VBO("VBO Rebuilt");
+
+static LLDrawPoolAvatar* get_avatar_drawpool(LLViewerObject* vobj)
+{
+ LLVOAvatar* avatar = vobj->getAvatar();
+
+ if (avatar)
+ {
+ LLDrawable* drawable = avatar->mDrawable;
+ if (drawable && drawable->getNumFaces() > 0)
+ {
+ LLFace* face = drawable->getFace(0);
+ if (face)
+ {
+ LLDrawPool* drawpool = face->getPool();
+ if (drawpool)
+ {
+ if (drawpool->getType() == LLDrawPool::POOL_AVATAR)
+ {
+ return (LLDrawPoolAvatar*) drawpool;
+ }
+ }
+ }
+ }
+ }
+
+ return NULL;
+}
+
+void LLVolumeGeometryManager::rebuildGeom(LLSpatialGroup* group)
+{
+ if (group->changeLOD())
+ {
+ group->mLastUpdateDistance = group->mDistance;
+ }
+
+ group->mLastUpdateViewAngle = group->mViewAngle;
+
+ if (!group->isState(LLSpatialGroup::GEOM_DIRTY | LLSpatialGroup::ALPHA_DIRTY))
+ {
+ if (group->isState(LLSpatialGroup::MESH_DIRTY) && !LLPipeline::sDelayVBUpdate)
+ {
+ LLFastTimer ftm(FTM_REBUILD_VBO);
+ LLFastTimer ftm2(FTM_REBUILD_VOLUME_VB);
+
+ rebuildMesh(group);
+ }
+ return;
+ }
+
+ group->mBuilt = 1.f;
+ LLFastTimer ftm(FTM_REBUILD_VBO);
+
+ LLFastTimer ftm2(FTM_REBUILD_VOLUME_VB);
+
+ group->clearDrawMap();
+
+ mFaceList.clear();
+
+ std::vector<LLFace*> fullbright_faces;
+ std::vector<LLFace*> bump_faces;
+ std::vector<LLFace*> simple_faces;
+
+ std::vector<LLFace*> alpha_faces;
+ U32 useage = group->mSpatialPartition->mBufferUsage;
+
+ U32 max_vertices = (gSavedSettings.getS32("RenderMaxVBOSize")*1024)/LLVertexBuffer::calcVertexSize(group->mSpatialPartition->mVertexDataMask);
+ U32 max_total = (gSavedSettings.getS32("RenderMaxNodeSize")*1024)/LLVertexBuffer::calcVertexSize(group->mSpatialPartition->mVertexDataMask);
+ max_vertices = llmin(max_vertices, (U32) 65535);
+
+ U32 cur_total = 0;
+
+ //get all the faces into a list
+ for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter)
+ {
+ LLDrawable* drawablep = *drawable_iter;
+
+ if (drawablep->isDead() || drawablep->isState(LLDrawable::FORCE_INVISIBLE) )
+ {
+ continue;
+ }
+
+ if (drawablep->isAnimating())
+ { //fall back to stream draw for animating verts
+ useage = GL_STREAM_DRAW_ARB;
+ }
+
+ LLVOVolume* vobj = drawablep->getVOVolume();
+
+ if (vobj->getVolume() && vobj->getVolume()->isTetrahedron())
+ {
+ continue;
+ }
+
+ llassert_always(vobj);
+ vobj->updateTextureVirtualSize();
+ vobj->preRebuild();
+
+ drawablep->clearState(LLDrawable::HAS_ALPHA);
+
+ bool rigged = vobj->isAttachment() &&
+ vobj->isMesh() &&
+ gMeshRepo.getSkinInfo(vobj->getVolume()->getParams().getSculptID());
+
+ bool bake_sunlight = LLPipeline::sBakeSunlight && drawablep->isStatic();
+
+ bool is_rigged = false;
+
+ //for each face
+ for (S32 i = 0; i < drawablep->getNumFaces(); i++)
+ {
+ LLFace* facep = drawablep->getFace(i);
+
+ //ALWAYS null out vertex buffer on rebuild -- if the face lands in a render
+ // batch, it will recover its vertex buffer reference from the spatial group
+ facep->setVertexBuffer(NULL);
+
+ //sum up face verts and indices
+ drawablep->updateFaceSize(i);
+
+
+
+ if (rigged)
+ {
+ if (!facep->isState(LLFace::RIGGED))
+ { //completely reset vertex buffer
+ facep->clearVertexBuffer();
+ }
+
+ facep->setState(LLFace::RIGGED);
+ is_rigged = true;
+
+ //get drawpool of avatar with rigged face
+ LLDrawPoolAvatar* pool = get_avatar_drawpool(vobj);
+
+ //Determine if we've received skininfo that contains an
+ //alternate bind matrix - if it does then apply the translational component
+ //to the joints of the avatar.
+ LLVOAvatar* pAvatarVO = vobj->getAvatar();
+ bool pelvisGotSet = false;
+
+ if ( pAvatarVO )
+ {
+ LLUUID currentId = vobj->getVolume()->getParams().getSculptID();
+ const LLMeshSkinInfo* pSkinData = gMeshRepo.getSkinInfo( currentId );
+
+ if ( pSkinData )
+ {
+ const int bindCnt = pSkinData->mAlternateBindMatrix.size();
+ if ( bindCnt > 0 )
+ {
+ const int jointCnt = pSkinData->mJointNames.size();
+ const int pelvisZOffset = pSkinData->mPelvisOffset;
+ bool fullRig = (jointCnt>=20) ? true : false;
+ if ( fullRig )
+ {
+ for ( int i=0; i<jointCnt; ++i )
+ {
+ std::string lookingForJoint = pSkinData->mJointNames[i].c_str();
+ //llinfos<<"joint name "<<lookingForJoint.c_str()<<llendl;
+ LLJoint* pJoint = pAvatarVO->getJoint( lookingForJoint );
+ if ( pJoint && pJoint->getId() != currentId )
+ {
+ pJoint->setId( currentId );
+ const LLVector3& jointPos = pSkinData->mAlternateBindMatrix[i].getTranslation();
+ //Set the joint position
+ pJoint->storeCurrentXform( jointPos );
+ //If joint is a pelvis then handle old/new pelvis to foot values
+ if ( lookingForJoint == "mPelvis" )
+ {
+ pJoint->storeCurrentXform( jointPos );
+ if ( !pAvatarVO->hasPelvisOffset() )
+ {
+ pAvatarVO->setPelvisOffset( true, jointPos, pelvisZOffset );
+ //Trigger to rebuild viewer AV
+ pelvisGotSet = true;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ //If we've set the pelvis to a new position we need to also rebuild some information that the
+ //viewer does at launch (e.g. body size etc.)
+ if ( pelvisGotSet )
+ {
+ pAvatarVO->postPelvisSetRecalc();
+ }
+
+ if (pool)
+ {
+ const LLTextureEntry* te = facep->getTextureEntry();
+
+ //remove face from old pool if it exists
+ LLDrawPool* old_pool = facep->getPool();
+ if (old_pool && old_pool->getType() == LLDrawPool::POOL_AVATAR)
+ {
+ ((LLDrawPoolAvatar*) old_pool)->removeRiggedFace(facep);
+ }
+
+ //add face to new pool
+ LLViewerTexture* tex = facep->getTexture();
+ U32 type = gPipeline.getPoolTypeFromTE(te, tex);
+
+ if (type == LLDrawPool::POOL_ALPHA)
+ {
+ if (te->getFullbright())
+ {
+ pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_FULLBRIGHT_ALPHA);
+ }
+ else
+ {
+ pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_ALPHA);
+ }
+ }
+ else if (te->getShiny())
+ {
+ if (te->getFullbright())
+ {
+ pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_FULLBRIGHT_SHINY);
+ }
+ else
+ {
+ if (LLPipeline::sRenderDeferred)
+ {
+ pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_SIMPLE);
+ }
+ else
+ {
+ pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_SHINY);
+ }
+ }
+ }
+ else
+ {
+ if (te->getFullbright())
+ {
+ pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_FULLBRIGHT);
+ }
+ else
+ {
+ pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_SIMPLE);
+ }
+ }
+
+ if (te->getGlow())
+ {
+ pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_GLOW);
+ }
+
+ if (LLPipeline::sRenderDeferred)
+ {
+ if (type != LLDrawPool::POOL_ALPHA && !te->getFullbright())
+ {
+ if (te->getBumpmap())
+ {
+ pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_DEFERRED_BUMP);
+ }
+ else
+ {
+ pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_DEFERRED_SIMPLE);
+ }
+ }
+ }
+ }
+
+ continue;
+ }
+ else
+ {
+ if (facep->isState(LLFace::RIGGED))
+ { //face is not rigged but used to be, remove from rigged face pool
+ LLDrawPoolAvatar* pool = (LLDrawPoolAvatar*) facep->getPool();
+ if (pool)
+ {
+ pool->removeRiggedFace(facep);
+ }
+ facep->clearState(LLFace::RIGGED);
+ }
+ }
+
+ if (cur_total > max_total || facep->getIndicesCount() <= 0 || facep->getGeomCount() <= 0)
+ {
+ facep->clearVertexBuffer();
+ continue;
+ }
+
+ cur_total += facep->getGeomCount();
+
+ if (facep->hasGeometry() && facep->getPixelArea() > FORCE_CULL_AREA)
+ {
+ const LLTextureEntry* te = facep->getTextureEntry();
+ LLViewerTexture* tex = facep->getTexture();
+
+ if (facep->isState(LLFace::TEXTURE_ANIM))
+ {
+ if (!vobj->mTexAnimMode)
+ {
+ facep->clearState(LLFace::TEXTURE_ANIM);
+ }
+ }
+
+ BOOL force_simple = (facep->getPixelArea() < FORCE_SIMPLE_RENDER_AREA);
+ U32 type = gPipeline.getPoolTypeFromTE(te, tex);
+ if (type != LLDrawPool::POOL_ALPHA && force_simple)
+ {
+ type = LLDrawPool::POOL_SIMPLE;
+ }
+ facep->setPoolType(type);
+
+ if (vobj->isHUDAttachment())
+ {
+ facep->setState(LLFace::FULLBRIGHT);
+ }
+
+ if (vobj->mTextureAnimp && vobj->mTexAnimMode)
+ {
+ if (vobj->mTextureAnimp->mFace <= -1)
+ {
+ S32 face;
+ for (face = 0; face < vobj->getNumTEs(); face++)
+ {
+ drawablep->getFace(face)->setState(LLFace::TEXTURE_ANIM);
+ }
+ }
+ else if (vobj->mTextureAnimp->mFace < vobj->getNumTEs())
+ {
+ drawablep->getFace(vobj->mTextureAnimp->mFace)->setState(LLFace::TEXTURE_ANIM);
+ }
+ }
+
+ if (type == LLDrawPool::POOL_ALPHA)
+ {
+ if (facep->canRenderAsMask())
+ { //can be treated as alpha mask
+ simple_faces.push_back(facep);
+ }
+ else
+ {
+ drawablep->setState(LLDrawable::HAS_ALPHA);
+ alpha_faces.push_back(facep);
+ }
+ }
+ else
+ {
+ if (drawablep->isState(LLDrawable::REBUILD_VOLUME))
+ {
+ facep->mLastUpdateTime = gFrameTimeSeconds;
+ }
+
+ if (gPipeline.canUseWindLightShadersOnObjects()
+ && LLPipeline::sRenderBump)
+ {
+ if (te->getBumpmap())
+ { //needs normal + binormal
+ bump_faces.push_back(facep);
+ }
+ else if (te->getShiny() || !te->getFullbright())
+ { //needs normal
+ simple_faces.push_back(facep);
+ }
+ else
+ { //doesn't need normal
+ facep->setState(LLFace::FULLBRIGHT);
+ fullbright_faces.push_back(facep);
+ }
+ }
+ else
+ {
+ if (te->getBumpmap() && LLPipeline::sRenderBump)
+ { //needs normal + binormal
+ bump_faces.push_back(facep);
+ }
+ else if ((te->getShiny() && LLPipeline::sRenderBump) ||
+ !(te->getFullbright() || bake_sunlight))
+ { //needs normal
+ simple_faces.push_back(facep);
+ }
+ else
+ { //doesn't need normal
+ facep->setState(LLFace::FULLBRIGHT);
+ fullbright_faces.push_back(facep);
+ }
+ }
+ }
+ }
+ else
+ { //face has no renderable geometry
+ facep->clearVertexBuffer();
+ }
+ }
+
+ if (is_rigged)
+ {
+ drawablep->setState(LLDrawable::RIGGED);
+ }
+ else
+ {
+ drawablep->clearState(LLDrawable::RIGGED);
+ }
+ }
+
+ group->mBufferUsage = useage;
+
+ //PROCESS NON-ALPHA FACES
+ U32 simple_mask = LLVertexBuffer::MAP_TEXCOORD0 | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_COLOR;
+ U32 alpha_mask = simple_mask | 0x80000000; //hack to give alpha verts their own VBO
+ U32 bump_mask = LLVertexBuffer::MAP_TEXCOORD0 | LLVertexBuffer::MAP_TEXCOORD1 | LLVertexBuffer::MAP_NORMAL | LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_COLOR;
+ U32 fullbright_mask = LLVertexBuffer::MAP_TEXCOORD0 | LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_COLOR;
+
+ if (LLPipeline::sRenderDeferred)
+ {
+ bump_mask |= LLVertexBuffer::MAP_BINORMAL;
+ }
+
+ genDrawInfo(group, simple_mask, simple_faces);
+ genDrawInfo(group, bump_mask, bump_faces);
+ genDrawInfo(group, fullbright_mask, fullbright_faces);
+ genDrawInfo(group, alpha_mask, alpha_faces, TRUE);
+
+ if (!LLPipeline::sDelayVBUpdate)
+ {
+ //drawables have been rebuilt, clear rebuild status
+ for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter)
+ {
+ LLDrawable* drawablep = *drawable_iter;
+ drawablep->clearState(LLDrawable::REBUILD_ALL);
+ }
+ }
+
+ group->mLastUpdateTime = gFrameTimeSeconds;
+ group->mBuilt = 1.f;
+ group->clearState(LLSpatialGroup::GEOM_DIRTY | LLSpatialGroup::ALPHA_DIRTY);
+
+ if (LLPipeline::sDelayVBUpdate)
+ {
+ group->setState(LLSpatialGroup::MESH_DIRTY | LLSpatialGroup::NEW_DRAWINFO);
+ }
+
+ mFaceList.clear();
+}
+
+static LLFastTimer::DeclareTimer FTM_VOLUME_GEOM("Volume Geometry");
+static LLFastTimer::DeclareTimer FTM_VOLUME_GEOM_PARTIAL("Terse Rebuild");
+
+void LLVolumeGeometryManager::rebuildMesh(LLSpatialGroup* group)
+{
+ llassert(group);
+ if (group && group->isState(LLSpatialGroup::MESH_DIRTY) && !group->isState(LLSpatialGroup::GEOM_DIRTY))
+ {
+ LLFastTimer tm(FTM_VOLUME_GEOM);
+ S32 num_mapped_veretx_buffer = LLVertexBuffer::sMappedCount ;
+
+ group->mBuilt = 1.f;
+
+ for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter)
+ {
+ LLFastTimer t(FTM_VOLUME_GEOM_PARTIAL);
+ LLDrawable* drawablep = *drawable_iter;
+
+ if (!drawablep->isDead() && drawablep->isState(LLDrawable::REBUILD_ALL) )
+ {
+ LLVOVolume* vobj = drawablep->getVOVolume();
+ vobj->preRebuild();
+
+ LLVolume* volume = vobj->getVolume();
+ for (S32 i = 0; i < drawablep->getNumFaces(); ++i)
+ {
+ LLFace* face = drawablep->getFace(i);
+ if (face && face->getVertexBuffer())
+ {
+ face->getGeometryVolume(*volume, face->getTEOffset(),
+ vobj->getRelativeXform(), vobj->getRelativeXformInvTrans(), face->getGeomIndex());
+ }
+
+ if (!face)
+ {
+ llerrs << "WTF?" << llendl;
+ }
+ }
+
+ drawablep->clearState(LLDrawable::REBUILD_ALL);
+ }
+ }
+
+ //unmap all the buffers
+ for (LLSpatialGroup::buffer_map_t::iterator i = group->mBufferMap.begin(); i != group->mBufferMap.end(); ++i)
+ {
+ LLSpatialGroup::buffer_texture_map_t& map = i->second;
+ for (LLSpatialGroup::buffer_texture_map_t::iterator j = map.begin(); j != map.end(); ++j)
+ {
+ LLSpatialGroup::buffer_list_t& list = j->second;
+ for (LLSpatialGroup::buffer_list_t::iterator k = list.begin(); k != list.end(); ++k)
+ {
+ LLVertexBuffer* buffer = *k;
+ if (buffer->isLocked())
+ {
+ buffer->setBuffer(0);
+ }
+ }
+ }
+ }
+
+ // don't forget alpha
+ if(group != NULL &&
+ !group->mVertexBuffer.isNull() &&
+ group->mVertexBuffer->isLocked())
+ {
+ group->mVertexBuffer->setBuffer(0);
+ }
+
+ //if not all buffers are unmapped
+ if(num_mapped_veretx_buffer != LLVertexBuffer::sMappedCount)
+ {
+ llwarns << "Not all mapped vertex buffers are unmapped!" << llendl ;
+ for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter)
+ {
+ LLDrawable* drawablep = *drawable_iter;
+ for (S32 i = 0; i < drawablep->getNumFaces(); ++i)
+ {
+ LLFace* face = drawablep->getFace(i);
+ LLVertexBuffer* buff = face->getVertexBuffer();
+ if (face && buff && buff->isLocked())
+ {
+ buff->setBuffer(0) ;
+ }
+ }
+ }
+ }
+
+ group->clearState(LLSpatialGroup::MESH_DIRTY | LLSpatialGroup::NEW_DRAWINFO);
+ }
+
+ if (group && group->isState(LLSpatialGroup::NEW_DRAWINFO))
+ {
+ llerrs << "WTF?" << llendl;
+ }
+}
+
+void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std::vector<LLFace*>& faces, BOOL distance_sort)
+{
+ //calculate maximum number of vertices to store in a single buffer
+ U32 max_vertices = (gSavedSettings.getS32("RenderMaxVBOSize")*1024)/LLVertexBuffer::calcVertexSize(group->mSpatialPartition->mVertexDataMask);
+ max_vertices = llmin(max_vertices, (U32) 65535);
+
+ if (!distance_sort)
+ {
+ //sort faces by things that break batches
+ std::sort(faces.begin(), faces.end(), LLFace::CompareBatchBreaker());
+ }
+ else
+ {
+ //sort faces by distance
+ std::sort(faces.begin(), faces.end(), LLFace::CompareDistanceGreater());
+ }
+
+ std::vector<LLFace*>::iterator face_iter = faces.begin();
+
+ LLSpatialGroup::buffer_map_t buffer_map;
+
+ LLViewerTexture* last_tex = NULL;
+ S32 buffer_index = 0;
+
+ if (distance_sort)
+ {
+ buffer_index = -1;
+ }
+
+ while (face_iter != faces.end())
+ {
+ //pull off next face
+ LLFace* facep = *face_iter;
+ LLViewerTexture* tex = facep->getTexture();
+
+ if (distance_sort)
+ {
+ tex = NULL;
+ }
+
+ if (last_tex == tex)
+ {
+ buffer_index++;
+ }
+ else
+ {
+ last_tex = tex;
+ buffer_index = 0;
+ }
+
+ bool bake_sunlight = LLPipeline::sBakeSunlight && facep->getDrawable()->isStatic();
+
+ U32 index_count = facep->getIndicesCount();
+ U32 geom_count = facep->getGeomCount();
+
+ //sum up vertices needed for this render batch
+ std::vector<LLFace*>::iterator i = face_iter;
+ ++i;
+
+ while (i != faces.end() &&
+ (LLPipeline::sTextureBindTest || (distance_sort || (*i)->getTexture() == tex)))
+ {
+ facep = *i;
+
+ if (geom_count + facep->getGeomCount() > max_vertices)
+ { //cut batches on geom count too big
+ break;
+ }
+
+ ++i;
+ index_count += facep->getIndicesCount();
+ geom_count += facep->getGeomCount();
+ }
+
+ //create/delete/resize vertex buffer if needed
+ LLVertexBuffer* buffer = NULL;
+ LLSpatialGroup::buffer_texture_map_t::iterator found_iter = group->mBufferMap[mask].find(tex);
+
+ if (found_iter != group->mBufferMap[mask].end())
+ {
+ if ((U32) buffer_index < found_iter->second.size())
+ {
+ buffer = found_iter->second[buffer_index];
+ }
+ }
+
+ if (!buffer)
+ { //create new buffer if needed
+ buffer = createVertexBuffer(mask,
+ group->mBufferUsage);
+ buffer->allocateBuffer(geom_count, index_count, TRUE);
+ }
+ else
+ { //resize pre-existing buffer
+ if (LLVertexBuffer::sEnableVBOs && buffer->getUsage() != group->mBufferUsage ||
+ buffer->getTypeMask() != mask)
+ {
+ buffer = createVertexBuffer(mask,
+ group->mBufferUsage);
+ buffer->allocateBuffer(geom_count, index_count, TRUE);
+ }
+ else
+ {
+ buffer->resizeBuffer(geom_count, index_count);
+ }
+ }
+
+ buffer_map[mask][tex].push_back(buffer);
+
+ //add face geometry
+
+ U32 indices_index = 0;
+ U16 index_offset = 0;
+
+ while (face_iter < i)
+ { //update face indices for new buffer
+ facep = *face_iter;
+ facep->setIndicesIndex(indices_index);
+ facep->setGeomIndex(index_offset);
+ facep->setVertexBuffer(buffer);
+
+ {
+ //for debugging, set last time face was updated vs moved
+ facep->updateRebuildFlags();
+
+ if (!LLPipeline::sDelayVBUpdate)
+ { //copy face geometry into vertex buffer
+ LLDrawable* drawablep = facep->getDrawable();
+ LLVOVolume* vobj = drawablep->getVOVolume();
+ LLVolume* volume = vobj->getVolume();
+
+ U32 te_idx = facep->getTEOffset();
+
+ if (facep->getGeometryVolume(*volume, te_idx,
+ vobj->getRelativeXform(), vobj->getRelativeXformInvTrans(), index_offset))
+ {
+ buffer->markDirty(facep->getGeomIndex(), facep->getGeomCount(),
+ facep->getIndicesStart(), facep->getIndicesCount());
+ }
+ }
+ }
+
+ index_offset += facep->getGeomCount();
+ indices_index += facep->getIndicesCount();
+
+
+ //append face to appropriate render batch
+
+ BOOL force_simple = facep->getPixelArea() < FORCE_SIMPLE_RENDER_AREA;
+ BOOL fullbright = facep->isState(LLFace::FULLBRIGHT);
+ if ((mask & LLVertexBuffer::MAP_NORMAL) == 0)
+ { //paranoia check to make sure GL doesn't try to read non-existant normals
+ fullbright = TRUE;
+ }
+
+ const LLTextureEntry* te = facep->getTextureEntry();
+
+ BOOL is_alpha = (facep->getPoolType() == LLDrawPool::POOL_ALPHA) ? TRUE : FALSE;
+
+ if (is_alpha)
+ {
+ // can we safely treat this as an alpha mask?
+ if (facep->canRenderAsMask())
+ {
+ if (te->getFullbright() || LLPipeline::sNoAlpha)
+ {
+ registerFace(group, facep, LLRenderPass::PASS_FULLBRIGHT_ALPHA_MASK);
+ }
+ else
+ {
+ registerFace(group, facep, LLRenderPass::PASS_ALPHA_MASK);
+ }
+ }
+ else
+ {
+ registerFace(group, facep, LLRenderPass::PASS_ALPHA);
+ }
+
+ if (LLPipeline::sRenderDeferred)
+ {
+ registerFace(group, facep, LLRenderPass::PASS_ALPHA_SHADOW);
+ }
+ }
+ else if (gPipeline.canUseVertexShaders()
+ && group->mSpatialPartition->mPartitionType != LLViewerRegion::PARTITION_HUD
+ && LLPipeline::sRenderBump
+ && te->getShiny())
+ { //shiny
+ if (tex->getPrimaryFormat() == GL_ALPHA)
+ { //invisiprim+shiny
+ registerFace(group, facep, LLRenderPass::PASS_INVISI_SHINY);
+ registerFace(group, facep, LLRenderPass::PASS_INVISIBLE);
+ }
+ else if (LLPipeline::sRenderDeferred)
+ { //deferred rendering
+ if (te->getFullbright())
+ { //register in post deferred fullbright shiny pass
+ registerFace(group, facep, LLRenderPass::PASS_FULLBRIGHT_SHINY);
+ if (te->getBumpmap())
+ { //register in post deferred bump pass
+ registerFace(group, facep, LLRenderPass::PASS_POST_BUMP);
+ }
+ }
+ else if (te->getBumpmap())
+ { //register in deferred bump pass
+ registerFace(group, facep, LLRenderPass::PASS_BUMP);
+ }
+ else
+ { //register in deferred simple pass (deferred simple includes shiny)
+ llassert(mask & LLVertexBuffer::MAP_NORMAL);
+ registerFace(group, facep, LLRenderPass::PASS_SIMPLE);
+ }
+ }
+ else if (fullbright)
+ { //not deferred, register in standard fullbright shiny pass
+ registerFace(group, facep, LLRenderPass::PASS_FULLBRIGHT_SHINY);
+ }
+ else
+ { //not deferred or fullbright, register in standard shiny pass
+ registerFace(group, facep, LLRenderPass::PASS_SHINY);
+ }
+ }
+ else
+ { //not alpha and not shiny
+ if (!is_alpha && tex->getPrimaryFormat() == GL_ALPHA)
+ { //invisiprim
+ registerFace(group, facep, LLRenderPass::PASS_INVISIBLE);
+ }
+ else if (fullbright || bake_sunlight)
+ { //fullbright
+ registerFace(group, facep, LLRenderPass::PASS_FULLBRIGHT);
+ if (LLPipeline::sRenderDeferred && LLPipeline::sRenderBump && te->getBumpmap())
+ { //if this is the deferred render and a bump map is present, register in post deferred bump
+ registerFace(group, facep, LLRenderPass::PASS_POST_BUMP);
+ }
+ }
+ else
+ {
+ if (LLPipeline::sRenderDeferred && LLPipeline::sRenderBump && te->getBumpmap())
+ { //non-shiny or fullbright deferred bump
+ registerFace(group, facep, LLRenderPass::PASS_BUMP);
+ }
+ else
+ { //all around simple
+ llassert(mask & LLVertexBuffer::MAP_NORMAL);
+ registerFace(group, facep, LLRenderPass::PASS_SIMPLE);
+ }
+ }
+
+ //not sure why this is here -- shiny HUD attachments maybe? -- davep 5/11/2010
+ if (!is_alpha && te->getShiny() && LLPipeline::sRenderBump)
+ {
+ registerFace(group, facep, LLRenderPass::PASS_SHINY);
+ }
+ }
+
+ //not sure why this is here, and looks like it might cause bump mapped objects to get rendered redundantly -- davep 5/11/2010
+ if (!is_alpha && !LLPipeline::sRenderDeferred)
+ {
+ llassert((mask & LLVertexBuffer::MAP_NORMAL) || fullbright);
+ facep->setPoolType((fullbright) ? LLDrawPool::POOL_FULLBRIGHT : LLDrawPool::POOL_SIMPLE);
+
+ if (!force_simple && te->getBumpmap() && LLPipeline::sRenderBump)
+ {
+ registerFace(group, facep, LLRenderPass::PASS_BUMP);
+ }
+ }
+
+ if (!is_alpha && LLPipeline::sRenderGlow && te->getGlow() > 0.f)
+ {
+ registerFace(group, facep, LLRenderPass::PASS_GLOW);
+ }
+
+ ++face_iter;
+ }
+
+ buffer->setBuffer(0);
+ }
+
+ group->mBufferMap[mask].clear();
+ for (LLSpatialGroup::buffer_texture_map_t::iterator i = buffer_map[mask].begin(); i != buffer_map[mask].end(); ++i)
+ {
+ group->mBufferMap[mask][i->first] = i->second;
+ }
+}
+
+void LLGeometryManager::addGeometryCount(LLSpatialGroup* group, U32 &vertex_count, U32 &index_count)
+{
+ //initialize to default usage for this partition
+ U32 usage = group->mSpatialPartition->mBufferUsage;
+
+ //clear off any old faces
+ mFaceList.clear();
+
+ //for each drawable
+ for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter)
+ {
+ LLDrawable* drawablep = *drawable_iter;
+
+ if (drawablep->isDead())
+ {
+ continue;
+ }
+
+ if (drawablep->isAnimating())
+ { //fall back to stream draw for animating verts
+ usage = GL_STREAM_DRAW_ARB;
+ }
+
+ //for each face
+ for (S32 i = 0; i < drawablep->getNumFaces(); i++)
+ {
+ //sum up face verts and indices
+ drawablep->updateFaceSize(i);
+ LLFace* facep = drawablep->getFace(i);
+ if (facep->hasGeometry() && facep->getPixelArea() > FORCE_CULL_AREA)
+ {
+ vertex_count += facep->getGeomCount();
+ index_count += facep->getIndicesCount();
+
+ //remember face (for sorting)
+ mFaceList.push_back(facep);
+ }
+ else
+ {
+ facep->clearVertexBuffer();
+ }
+ }
+ }
+
+ group->mBufferUsage = usage;
+}
+
+LLHUDPartition::LLHUDPartition()
+{
+ mPartitionType = LLViewerRegion::PARTITION_HUD;
+ mDrawableType = LLPipeline::RENDER_TYPE_HUD;
+ mSlopRatio = 0.f;
+ mLODPeriod = 1;
+}
+
+void LLHUDPartition::shift(const LLVector4a &offset)
+{
+ //HUD objects don't shift with region crossing. That would be silly.
+}
+
+
diff --git a/indra/newview/llvovolume.h b/indra/newview/llvovolume.h
index 8b68e7c78a..b09243055c 100644
--- a/indra/newview/llvovolume.h
+++ b/indra/newview/llvovolume.h
@@ -40,6 +40,8 @@ class LLDrawPool;
class LLSelectNode;
class LLObjectMediaDataClient;
class LLObjectMediaNavigateClient;
+class LLVOAvatar;
+class LLMeshSkinInfo;
typedef std::vector<viewer_media_t> media_list_t;
@@ -48,6 +50,18 @@ enum LLVolumeInterfaceType
INTERFACE_FLEXIBLE = 1,
};
+
+class LLRiggedVolume : public LLVolume
+{
+public:
+ LLRiggedVolume(const LLVolumeParams& params)
+ : LLVolume(params, 0.f)
+ {
+ }
+
+ void update(const LLMeshSkinInfo* skin, LLVOAvatar* avatar, const LLVolume* src_volume);
+};
+
// Base class for implementations of the volume - Primitive, Flexible Object, etc.
class LLVolumeInterface
{
@@ -60,7 +74,7 @@ public:
virtual void onSetVolume(const LLVolumeParams &volume_params, const S32 detail) = 0;
virtual void onSetScale(const LLVector3 &scale, BOOL damped) = 0;
virtual void onParameterChanged(U16 param_type, LLNetworkData *data, BOOL in_use, bool local_origin) = 0;
- virtual void onShift(const LLVector3 &shift_vector) = 0;
+ virtual void onShift(const LLVector4a &shift_vector) = 0;
virtual bool isVolumeUnique() const = 0; // Do we need a unique LLVolume instance?
virtual bool isVolumeGlobal() const = 0; // Are we in global space?
virtual bool isActive() const = 0; // Is this object currently active?
@@ -116,7 +130,8 @@ public:
const LLMatrix3& getRelativeXformInvTrans() const { return mRelativeXformInvTrans; }
/*virtual*/ const LLMatrix4 getRenderMatrix() const;
U32 getRenderCost(std::set<LLUUID> &textures) const;
-
+ /*virtual*/ F32 getStreamingCost();
+ /*virtual*/ U32 getTriangleCount();
/*virtual*/ BOOL lineSegmentIntersect(const LLVector3& start, const LLVector3& end,
S32 face = -1, // which face to check, -1 = ALL_SIDES
BOOL pick_transparent = FALSE,
@@ -140,7 +155,7 @@ public:
void markForUpdate(BOOL priority) { LLViewerObject::markForUpdate(priority); mVolumeChanged = TRUE; }
- /*virtual*/ void onShift(const LLVector3 &shift_vector); // Called when the drawable shifts
+ /*virtual*/ void onShift(const LLVector4a &shift_vector); // Called when the drawable shifts
/*virtual*/ void parameterChanged(U16 param_type, bool local_origin);
/*virtual*/ void parameterChanged(U16 param_type, LLNetworkData* data, BOOL in_use, bool local_origin);
@@ -179,6 +194,11 @@ public:
void updateSculptTexture();
void setIndexInTex(S32 index) { mIndexInTex = index ;}
void sculpt();
+ static void rebuildMeshAssetCallback(LLVFS *vfs,
+ const LLUUID& asset_uuid,
+ LLAssetType::EType type,
+ void* user_data, S32 status, LLExtStat ext_status);
+
void updateRelativeXform();
/*virtual*/ BOOL updateGeometry(LLDrawable *drawable);
/*virtual*/ void updateFaceSize(S32 idx);
@@ -191,7 +211,7 @@ public:
void regenFaces();
BOOL genBBoxes(BOOL force_global);
void preRebuild();
- virtual void updateSpatialExtents(LLVector3& min, LLVector3& max);
+ virtual void updateSpatialExtents(LLVector4a& min, LLVector4a& max);
virtual F32 getBinRadius();
virtual U32 getPartitionType() const;
@@ -225,6 +245,7 @@ public:
U32 getVolumeInterfaceID() const;
virtual BOOL isFlexible() const;
virtual BOOL isSculpted() const;
+ virtual BOOL isMesh() const;
virtual BOOL hasLightTexture() const;
BOOL isVolumeGlobal() const;
@@ -249,6 +270,7 @@ public:
void mediaNavigated(LLViewerMediaImpl *impl, LLPluginClassMedia* plugin, std::string new_location);
void mediaEvent(LLViewerMediaImpl *impl, LLPluginClassMedia* plugin, LLViewerMediaObserver::EMediaEvent event);
+
// Sync the given media data with the impl and the given te
void syncMediaData(S32 te, const LLSD &media_data, bool merge, bool ignore_agent);
@@ -264,9 +286,11 @@ public:
LLVector3 getApproximateFaceNormal(U8 face_id);
+ void notifyMeshLoaded();
+
// Returns 'true' iff the media data for this object is in flight
bool isMediaDataBeingFetched() const;
-
+
// Returns the "last fetched" media version, or -1 if not fetched yet
S32 getLastFetchedMediaVersion() const { return mLastFetchedMediaVersion; }
@@ -274,6 +298,21 @@ public:
void removeMDCImpl() { --mMDCImplCount; }
S32 getMDCImplCount() { return mMDCImplCount; }
+
+ //rigged volume update (for raycasting)
+ void updateRiggedVolume();
+ LLRiggedVolume* getRiggedVolume();
+
+ //returns true if volume should be treated as a rigged volume
+ // - Build tools are open
+ // - object is an attachment
+ // - object is attached to self
+ // - object is rendered as rigged
+ bool treatAsRigged();
+
+ //clear out rigged volume and revert back to non-rigged state for picking/LOD/distance updates
+ void clearRiggedVolume();
+
protected:
S32 computeLODDetail(F32 distance, F32 radius);
BOOL calcLOD();
@@ -307,6 +346,9 @@ private:
S32 mLastFetchedMediaVersion; // as fetched from the server, starts as -1
S32 mIndexInTex;
S32 mMDCImplCount;
+
+ LLPointer<LLRiggedVolume> mRiggedVolume;
+
// statics
public:
static F32 sLODSlopDistanceFactor;// Changing this to zero, effectively disables the LOD transition slop
diff --git a/indra/newview/llvowater.cpp b/indra/newview/llvowater.cpp
index 71f08ec36d..69ebad61ac 100644
--- a/indra/newview/llvowater.cpp
+++ b/indra/newview/llvowater.cpp
@@ -166,16 +166,18 @@ BOOL LLVOWater::updateGeometry(LLDrawable *drawable)
face->setSize(vertices_per_quad * num_quads,
indices_per_quad * num_quads);
- if (face->mVertexBuffer.isNull())
+ LLVertexBuffer* buff = face->getVertexBuffer();
+ if (!buff)
{
- face->mVertexBuffer = new LLVertexBuffer(LLDrawPoolWater::VERTEX_DATA_MASK, GL_DYNAMIC_DRAW_ARB);
- face->mVertexBuffer->allocateBuffer(face->getGeomCount(), face->getIndicesCount(), TRUE);
+ buff = new LLVertexBuffer(LLDrawPoolWater::VERTEX_DATA_MASK, GL_DYNAMIC_DRAW_ARB);
+ buff->allocateBuffer(face->getGeomCount(), face->getIndicesCount(), TRUE);
face->setIndicesIndex(0);
face->setGeomIndex(0);
+ face->setVertexBuffer(buff);
}
else
{
- face->mVertexBuffer->resizeBuffer(face->getGeomCount(), face->getIndicesCount());
+ buff->resizeBuffer(face->getGeomCount(), face->getIndicesCount());
}
index_offset = face->getGeometry(verticesp,normalsp,texCoordsp, indicesp);
@@ -229,7 +231,7 @@ BOOL LLVOWater::updateGeometry(LLDrawable *drawable)
}
}
- face->mVertexBuffer->setBuffer(0);
+ buff->setBuffer(0);
mDrawable->movePartition();
LLPipeline::sCompiles++;
@@ -261,15 +263,21 @@ void LLVOWater::setIsEdgePatch(const BOOL edge_patch)
mIsEdgePatch = edge_patch;
}
-void LLVOWater::updateSpatialExtents(LLVector3 &newMin, LLVector3& newMax)
+void LLVOWater::updateSpatialExtents(LLVector4a &newMin, LLVector4a& newMax)
{
- LLVector3 pos = getPositionAgent();
- LLVector3 scale = getScale();
-
- newMin = pos - scale * 0.5f;
- newMax = pos + scale * 0.5f;
+ LLVector4a pos;
+ pos.load3(getPositionAgent().mV);
+ LLVector4a scale;
+ scale.load3(getScale().mV);
+ scale.mul(0.5f);
+
+ newMin.setSub(pos, scale);
+ newMax.setAdd(pos, scale);
+
+ pos.setAdd(newMin,newMax);
+ pos.mul(0.5f);
- mDrawable->setPositionGroup((newMin + newMax) * 0.5f);
+ mDrawable->setPositionGroup(pos);
}
U32 LLVOWater::getPartitionType() const
@@ -283,7 +291,7 @@ U32 LLVOVoidWater::getPartitionType() const
}
LLWaterPartition::LLWaterPartition()
-: LLSpatialPartition(0, FALSE, 0)
+: LLSpatialPartition(0, FALSE, GL_DYNAMIC_DRAW_ARB)
{
mInfiniteFarClip = TRUE;
mDrawableType = LLPipeline::RENDER_TYPE_WATER;
diff --git a/indra/newview/llvowater.h b/indra/newview/llvowater.h
index cb9584cabf..ed709dd840 100644
--- a/indra/newview/llvowater.h
+++ b/indra/newview/llvowater.h
@@ -61,7 +61,7 @@ public:
/*virtual*/ BOOL idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time);
/*virtual*/ LLDrawable* createDrawable(LLPipeline *pipeline);
/*virtual*/ BOOL updateGeometry(LLDrawable *drawable);
- /*virtual*/ void updateSpatialExtents(LLVector3& newMin, LLVector3& newMax);
+ /*virtual*/ void updateSpatialExtents(LLVector4a& newMin, LLVector4a& newMax);
/*virtual*/ void updateTextures();
/*virtual*/ void setPixelAreaAndAngle(LLAgent &agent); // generate accurate apparent angle and area
diff --git a/indra/newview/llvowlsky.cpp b/indra/newview/llvowlsky.cpp
index ca57c0144b..51664cb31d 100644
--- a/indra/newview/llvowlsky.cpp
+++ b/indra/newview/llvowlsky.cpp
@@ -332,7 +332,7 @@ BOOL LLVOWLSky::updateGeometry(LLDrawable * drawable)
{
const U32 max_buffer_bytes = gSavedSettings.getS32("RenderMaxVBOSize")*1024;
const U32 data_mask = LLDrawPoolWLSky::SKY_VERTEX_DATA_MASK;
- const U32 max_verts = max_buffer_bytes / LLVertexBuffer::calcStride(data_mask);
+ const U32 max_verts = max_buffer_bytes / LLVertexBuffer::calcVertexSize(data_mask);
const U32 total_stacks = getNumStacks();
diff --git a/indra/newview/llwearableitemslist.h b/indra/newview/llwearableitemslist.h
index b060c9f076..a8a5ef3117 100644
--- a/indra/newview/llwearableitemslist.h
+++ b/indra/newview/llwearableitemslist.h
@@ -396,7 +396,6 @@ protected:
*/
class LLWearableItemsList : public LLInventoryItemsList
{
- LOG_CLASS(LLWearableItemsList);
public:
/**
* Context menu.
diff --git a/indra/newview/llworld.cpp b/indra/newview/llworld.cpp
index 8f7197c607..96bc8cbdd9 100644
--- a/indra/newview/llworld.cpp
+++ b/indra/newview/llworld.cpp
@@ -1,1520 +1,1348 @@
-/**
- * @file llworld.cpp
- * @brief Initial test structure to organize viewer regions
- *
- * $LicenseInfo:firstyear=2001&license=viewerlgpl$
- * Second Life Viewer Source Code
- * Copyright (C) 2010, Linden Research, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License only.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
- * $/LicenseInfo$
- */
-
-#include "llviewerprecompiledheaders.h"
-
-#include "llworld.h"
-#include "llrender.h"
-
-#include "indra_constants.h"
-#include "llstl.h"
-
-#include "llagent.h"
-#include "llviewercontrol.h"
-#include "lldrawpool.h"
-#include "llglheaders.h"
-#include "llhttpnode.h"
-#include "llregionhandle.h"
-#include "llsurface.h"
-#include "lltrans.h"
-#include "llviewercamera.h"
-#include "llviewertexture.h"
-#include "llviewertexturelist.h"
-#include "llviewernetwork.h"
-#include "llviewerobjectlist.h"
-#include "llviewerparceloverlay.h"
-#include "llviewerregion.h"
-#include "llviewerstats.h"
-#include "llvlcomposition.h"
-#include "llvoavatar.h"
-#include "llvowater.h"
-#include "message.h"
-#include "pipeline.h"
-#include "llappviewer.h" // for do_disconnect()
-
-#include <deque>
-#include <queue>
-#include <map>
-#include <cstring>
-
-//
-// Globals
-//
-U32 gAgentPauseSerialNum = 0;
-
-//
-// Constants
-//
-const S32 MAX_NUMBER_OF_CLOUDS = 750;
-const S32 WORLD_PATCH_SIZE = 16;
-
-extern LLColor4U MAX_WATER_COLOR;
-
-const U32 LLWorld::mWidth = 256;
-
-// meters/point, therefore mWidth * mScale = meters per edge
-const F32 LLWorld::mScale = 1.f;
-
-const F32 LLWorld::mWidthInMeters = mWidth * mScale;
-
-//
-// Functions
-//
-
-// allocate the stack
-LLWorld::LLWorld() :
- mLandFarClip(DEFAULT_FAR_PLANE),
- mLastPacketsIn(0),
- mLastPacketsOut(0),
- mLastPacketsLost(0),
- mSpaceTimeUSec(0),
- mClassicCloudsEnabled(TRUE)
-{
- for (S32 i = 0; i < 8; i++)
- {
- mEdgeWaterObjects[i] = NULL;
- }
-
- if (gNoRender)
- {
- return;
- }
-
- LLPointer<LLImageRaw> raw = new LLImageRaw(1,1,4);
- U8 *default_texture = raw->getData();
- *(default_texture++) = MAX_WATER_COLOR.mV[0];
- *(default_texture++) = MAX_WATER_COLOR.mV[1];
- *(default_texture++) = MAX_WATER_COLOR.mV[2];
- *(default_texture++) = MAX_WATER_COLOR.mV[3];
-
- mDefaultWaterTexturep = LLViewerTextureManager::getLocalTexture(raw.get(), FALSE);
- gGL.getTexUnit(0)->bind(mDefaultWaterTexturep);
- mDefaultWaterTexturep->setAddressMode(LLTexUnit::TAM_CLAMP);
-
-}
-
-
-void LLWorld::destroyClass()
-{
- mHoleWaterObjects.clear();
- gObjectList.destroy();
- for(region_list_t::iterator region_it = mRegionList.begin(); region_it != mRegionList.end(); )
- {
- LLViewerRegion* region_to_delete = *region_it++;
- removeRegion(region_to_delete->getHost());
- }
- if(LLVOCache::hasInstance())
- {
- LLVOCache::getInstance()->destroyClass() ;
- }
- LLViewerPartSim::getInstance()->destroyClass();
-}
-
-
-LLViewerRegion* LLWorld::addRegion(const U64 &region_handle, const LLHost &host)
-{
- LLMemType mt(LLMemType::MTYPE_REGIONS);
- llinfos << "Add region with handle: " << region_handle << " on host " << host << llendl;
- LLViewerRegion *regionp = getRegionFromHandle(region_handle);
- if (regionp)
- {
- llinfos << "Region exists, removing it " << llendl;
- LLHost old_host = regionp->getHost();
- // region already exists!
- if (host == old_host && regionp->isAlive())
- {
- // This is a duplicate for the same host and it's alive, don't bother.
- return regionp;
- }
-
- if (host != old_host)
- {
- llwarns << "LLWorld::addRegion exists, but old host " << old_host
- << " does not match new host " << host << llendl;
- }
- if (!regionp->isAlive())
- {
- llwarns << "LLWorld::addRegion exists, but isn't alive" << llendl;
- }
-
- // Kill the old host, and then we can continue on and add the new host. We have to kill even if the host
- // matches, because all the agent state for the new camera is completely different.
- removeRegion(old_host);
- }
-
- U32 iindex = 0;
- U32 jindex = 0;
- from_region_handle(region_handle, &iindex, &jindex);
- S32 x = (S32)(iindex/mWidth);
- S32 y = (S32)(jindex/mWidth);
- llinfos << "Adding new region (" << x << ":" << y << ")" << llendl;
- llinfos << "Host: " << host << llendl;
-
- LLVector3d origin_global;
-
- origin_global = from_region_handle(region_handle);
-
- regionp = new LLViewerRegion(region_handle,
- host,
- mWidth,
- WORLD_PATCH_SIZE,
- getRegionWidthInMeters() );
- if (!regionp)
- {
- llerrs << "Unable to create new region!" << llendl;
- }
-
- regionp->mCloudLayer.create(regionp);
- regionp->mCloudLayer.setWidth((F32)mWidth);
- regionp->mCloudLayer.setWindPointer(&regionp->mWind);
-
- mRegionList.push_back(regionp);
- mActiveRegionList.push_back(regionp);
- mCulledRegionList.push_back(regionp);
-
-
- // Find all the adjacent regions, and attach them.
- // Generate handles for all of the adjacent regions, and attach them in the correct way.
- // connect the edges
- F32 adj_x = 0.f;
- F32 adj_y = 0.f;
- F32 region_x = 0.f;
- F32 region_y = 0.f;
- U64 adj_handle = 0;
-
- F32 width = getRegionWidthInMeters();
-
- LLViewerRegion *neighborp;
- from_region_handle(region_handle, &region_x, &region_y);
-
- // Iterate through all directions, and connect neighbors if there.
- S32 dir;
- for (dir = 0; dir < 8; dir++)
- {
- adj_x = region_x + width * gDirAxes[dir][0];
- adj_y = region_y + width * gDirAxes[dir][1];
- to_region_handle(adj_x, adj_y, &adj_handle);
-
- neighborp = getRegionFromHandle(adj_handle);
- if (neighborp)
- {
- //llinfos << "Connecting " << region_x << ":" << region_y << " -> " << adj_x << ":" << adj_y << llendl;
- regionp->connectNeighbor(neighborp, dir);
- }
- }
-
- updateWaterObjects();
-
- return regionp;
-}
-
-
-void LLWorld::removeRegion(const LLHost &host)
-{
- F32 x, y;
-
- LLViewerRegion *regionp = getRegion(host);
- if (!regionp)
- {
- llwarns << "Trying to remove region that doesn't exist!" << llendl;
- return;
- }
-
- if (regionp == gAgent.getRegion())
- {
- for (region_list_t::iterator iter = mRegionList.begin();
- iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* reg = *iter;
- llwarns << "RegionDump: " << reg->getName()
- << " " << reg->getHost()
- << " " << reg->getOriginGlobal()
- << llendl;
- }
-
- llwarns << "Agent position global " << gAgent.getPositionGlobal()
- << " agent " << gAgent.getPositionAgent()
- << llendl;
-
- llwarns << "Regions visited " << gAgent.getRegionsVisited() << llendl;
-
- llwarns << "gFrameTimeSeconds " << gFrameTimeSeconds << llendl;
-
- llwarns << "Disabling region " << regionp->getName() << " that agent is in!" << llendl;
- LLAppViewer::instance()->forceDisconnect(LLTrans::getString("YouHaveBeenDisconnected"));
-
- regionp->saveObjectCache() ; //force to save objects here in case that the object cache is about to be destroyed.
- return;
- }
-
- from_region_handle(regionp->getHandle(), &x, &y);
- llinfos << "Removing region " << x << ":" << y << llendl;
-
- mRegionList.remove(regionp);
- mActiveRegionList.remove(regionp);
- mCulledRegionList.remove(regionp);
- mVisibleRegionList.remove(regionp);
-
- delete regionp;
-
- updateWaterObjects();
-
- //double check all objects of this region are removed.
- gObjectList.clearAllMapObjectsInRegion(regionp) ;
- //llassert_always(!gObjectList.hasMapObjectInRegion(regionp)) ;
-}
-
-
-LLViewerRegion* LLWorld::getRegion(const LLHost &host)
-{
- for (region_list_t::iterator iter = mRegionList.begin();
- iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- if (regionp->getHost() == host)
- {
- return regionp;
- }
- }
- return NULL;
-}
-
-LLViewerRegion* LLWorld::getRegionFromPosAgent(const LLVector3 &pos)
-{
- return getRegionFromPosGlobal(gAgent.getPosGlobalFromAgent(pos));
-}
-
-LLViewerRegion* LLWorld::getRegionFromPosGlobal(const LLVector3d &pos)
-{
- for (region_list_t::iterator iter = mRegionList.begin();
- iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- if (regionp->pointInRegionGlobal(pos))
- {
- return regionp;
- }
- }
- return NULL;
-}
-
-
-LLVector3d LLWorld::clipToVisibleRegions(const LLVector3d &start_pos, const LLVector3d &end_pos)
-{
- if (positionRegionValidGlobal(end_pos))
- {
- return end_pos;
- }
-
- LLViewerRegion* regionp = getRegionFromPosGlobal(start_pos);
- if (!regionp)
- {
- return start_pos;
- }
-
- LLVector3d delta_pos = end_pos - start_pos;
- LLVector3d delta_pos_abs;
- delta_pos_abs.setVec(delta_pos);
- delta_pos_abs.abs();
-
- LLVector3 region_coord = regionp->getPosRegionFromGlobal(end_pos);
- F64 clip_factor = 1.0;
- F32 region_width = regionp->getWidth();
- if (region_coord.mV[VX] < 0.f)
- {
- if (region_coord.mV[VY] < region_coord.mV[VX])
- {
- // clip along y -
- clip_factor = -(region_coord.mV[VY] / delta_pos_abs.mdV[VY]);
- }
- else
- {
- // clip along x -
- clip_factor = -(region_coord.mV[VX] / delta_pos_abs.mdV[VX]);
- }
- }
- else if (region_coord.mV[VX] > region_width)
- {
- if (region_coord.mV[VY] > region_coord.mV[VX])
- {
- // clip along y +
- clip_factor = (region_coord.mV[VY] - region_width) / delta_pos_abs.mdV[VY];
- }
- else
- {
- //clip along x +
- clip_factor = (region_coord.mV[VX] - region_width) / delta_pos_abs.mdV[VX];
- }
- }
- else if (region_coord.mV[VY] < 0.f)
- {
- // clip along y -
- clip_factor = -(region_coord.mV[VY] / delta_pos_abs.mdV[VY]);
- }
- else if (region_coord.mV[VY] > region_width)
- {
- // clip along y +
- clip_factor = (region_coord.mV[VY] - region_width) / delta_pos_abs.mdV[VY];
- }
-
- // clamp to within region dimensions
- LLVector3d final_region_pos = LLVector3d(region_coord) - (delta_pos * clip_factor);
- final_region_pos.mdV[VX] = llclamp(final_region_pos.mdV[VX], 0.0,
- (F64)(region_width - F_ALMOST_ZERO));
- final_region_pos.mdV[VY] = llclamp(final_region_pos.mdV[VY], 0.0,
- (F64)(region_width - F_ALMOST_ZERO));
- final_region_pos.mdV[VZ] = llclamp(final_region_pos.mdV[VZ], 0.0,
- (F64)(LLWorld::getInstance()->getRegionMaxHeight() - F_ALMOST_ZERO));
- return regionp->getPosGlobalFromRegion(LLVector3(final_region_pos));
-}
-
-LLViewerRegion* LLWorld::getRegionFromHandle(const U64 &handle)
-{
- for (region_list_t::iterator iter = mRegionList.begin();
- iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- if (regionp->getHandle() == handle)
- {
- return regionp;
- }
- }
- return NULL;
-}
-
-
-void LLWorld::updateAgentOffset(const LLVector3d &offset_global)
-{
-#if 0
- for (region_list_t::iterator iter = mRegionList.begin();
- iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- regionp->setAgentOffset(offset_global);
- }
-#endif
-}
-
-
-BOOL LLWorld::positionRegionValidGlobal(const LLVector3d &pos_global)
-{
- for (region_list_t::iterator iter = mRegionList.begin();
- iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- if (regionp->pointInRegionGlobal(pos_global))
- {
- return TRUE;
- }
- }
- return FALSE;
-}
-
-
-// Allow objects to go up to their radius underground.
-F32 LLWorld::getMinAllowedZ(LLViewerObject* object, const LLVector3d &global_pos)
-{
- F32 land_height = resolveLandHeightGlobal(global_pos);
- F32 radius = 0.5f * object->getScale().length();
- return land_height - radius;
-}
-
-
-
-LLViewerRegion* LLWorld::resolveRegionGlobal(LLVector3 &pos_region, const LLVector3d &pos_global)
-{
- LLViewerRegion *regionp = getRegionFromPosGlobal(pos_global);
-
- if (regionp)
- {
- pos_region = regionp->getPosRegionFromGlobal(pos_global);
- return regionp;
- }
-
- return NULL;
-}
-
-
-LLViewerRegion* LLWorld::resolveRegionAgent(LLVector3 &pos_region, const LLVector3 &pos_agent)
-{
- LLVector3d pos_global = gAgent.getPosGlobalFromAgent(pos_agent);
- LLViewerRegion *regionp = getRegionFromPosGlobal(pos_global);
-
- if (regionp)
- {
- pos_region = regionp->getPosRegionFromGlobal(pos_global);
- return regionp;
- }
-
- return NULL;
-}
-
-
-F32 LLWorld::resolveLandHeightAgent(const LLVector3 &pos_agent)
-{
- LLVector3d pos_global = gAgent.getPosGlobalFromAgent(pos_agent);
- return resolveLandHeightGlobal(pos_global);
-}
-
-
-F32 LLWorld::resolveLandHeightGlobal(const LLVector3d &pos_global)
-{
- LLViewerRegion *regionp = getRegionFromPosGlobal(pos_global);
- if (regionp)
- {
- return regionp->getLand().resolveHeightGlobal(pos_global);
- }
- return 0.0f;
-}
-
-
-// Takes a line defined by "point_a" and "point_b" and determines the closest (to point_a)
-// point where the the line intersects an object or the land surface. Stores the results
-// in "intersection" and "intersection_normal" and returns a scalar value that represents
-// the normalized distance along the line from "point_a" to "intersection".
-//
-// Currently assumes point_a and point_b only differ in z-direction,
-// but it may eventually become more general.
-F32 LLWorld::resolveStepHeightGlobal(const LLVOAvatar* avatarp, const LLVector3d &point_a, const LLVector3d &point_b,
- LLVector3d &intersection, LLVector3 &intersection_normal,
- LLViewerObject **viewerObjectPtr)
-{
- // initialize return value to null
- if (viewerObjectPtr)
- {
- *viewerObjectPtr = NULL;
- }
-
- LLViewerRegion *regionp = getRegionFromPosGlobal(point_a);
- if (!regionp)
- {
- // We're outside the world
- intersection = 0.5f * (point_a + point_b);
- intersection_normal.setVec(0.0f, 0.0f, 1.0f);
- return 0.5f;
- }
-
- // calculate the length of the segment
- F32 segment_length = (F32)((point_a - point_b).length());
- if (0.0f == segment_length)
- {
- intersection = point_a;
- intersection_normal.setVec(0.0f, 0.0f, 1.0f);
- return segment_length;
- }
-
- // get land height
- // Note: we assume that the line is parallel to z-axis here
- LLVector3d land_intersection = point_a;
- F32 normalized_land_distance;
-
- land_intersection.mdV[VZ] = regionp->getLand().resolveHeightGlobal(point_a);
- normalized_land_distance = (F32)(point_a.mdV[VZ] - land_intersection.mdV[VZ]) / segment_length;
- intersection = land_intersection;
- intersection_normal = resolveLandNormalGlobal(land_intersection);
-
- if (avatarp && !avatarp->mFootPlane.isExactlyClear())
- {
- LLVector3 foot_plane_normal(avatarp->mFootPlane.mV);
- LLVector3 start_pt = avatarp->getRegion()->getPosRegionFromGlobal(point_a);
- // added 0.05 meters to compensate for error in foot plane reported by Havok
- F32 norm_dist_from_plane = ((start_pt * foot_plane_normal) - avatarp->mFootPlane.mV[VW]) + 0.05f;
- norm_dist_from_plane = llclamp(norm_dist_from_plane / segment_length, 0.f, 1.f);
- if (norm_dist_from_plane < normalized_land_distance)
- {
- // collided with object before land
- normalized_land_distance = norm_dist_from_plane;
- intersection = point_a;
- intersection.mdV[VZ] -= norm_dist_from_plane * segment_length;
- intersection_normal = foot_plane_normal;
- }
- else
- {
- intersection = land_intersection;
- intersection_normal = resolveLandNormalGlobal(land_intersection);
- }
- }
-
- return normalized_land_distance;
-}
-
-
-LLSurfacePatch * LLWorld::resolveLandPatchGlobal(const LLVector3d &pos_global)
-{
- // returns a pointer to the patch at this location
- LLViewerRegion *regionp = getRegionFromPosGlobal(pos_global);
- if (!regionp)
- {
- return NULL;
- }
-
- return regionp->getLand().resolvePatchGlobal(pos_global);
-}
-
-
-LLVector3 LLWorld::resolveLandNormalGlobal(const LLVector3d &pos_global)
-{
- LLViewerRegion *regionp = getRegionFromPosGlobal(pos_global);
- if (!regionp)
- {
- return LLVector3::z_axis;
- }
-
- return regionp->getLand().resolveNormalGlobal(pos_global);
-}
-
-
-void LLWorld::updateVisibilities()
-{
- F32 cur_far_clip = LLViewerCamera::getInstance()->getFar();
-
- LLViewerCamera::getInstance()->setFar(mLandFarClip);
-
- F32 diagonal_squared = F_SQRT2 * F_SQRT2 * mWidth * mWidth;
- // Go through the culled list and check for visible regions
- for (region_list_t::iterator iter = mCulledRegionList.begin();
- iter != mCulledRegionList.end(); )
- {
- region_list_t::iterator curiter = iter++;
- LLViewerRegion* regionp = *curiter;
- F32 height = regionp->getLand().getMaxZ() - regionp->getLand().getMinZ();
- F32 radius = 0.5f*fsqrtf(height * height + diagonal_squared);
- if (!regionp->getLand().hasZData()
- || LLViewerCamera::getInstance()->sphereInFrustum(regionp->getCenterAgent(), radius))
- {
- mCulledRegionList.erase(curiter);
- mVisibleRegionList.push_back(regionp);
- }
- }
-
- // Update all of the visible regions
- for (region_list_t::iterator iter = mVisibleRegionList.begin();
- iter != mVisibleRegionList.end(); )
- {
- region_list_t::iterator curiter = iter++;
- LLViewerRegion* regionp = *curiter;
- if (!regionp->getLand().hasZData())
- {
- continue;
- }
-
- F32 height = regionp->getLand().getMaxZ() - regionp->getLand().getMinZ();
- F32 radius = 0.5f*fsqrtf(height * height + diagonal_squared);
- if (LLViewerCamera::getInstance()->sphereInFrustum(regionp->getCenterAgent(), radius))
- {
- regionp->calculateCameraDistance();
- if (!gNoRender)
- {
- regionp->getLand().updatePatchVisibilities(gAgent);
- }
- }
- else
- {
- mVisibleRegionList.erase(curiter);
- mCulledRegionList.push_back(regionp);
- }
- }
-
- // Sort visible regions
- mVisibleRegionList.sort(LLViewerRegion::CompareDistance());
-
- LLViewerCamera::getInstance()->setFar(cur_far_clip);
-}
-
-void LLWorld::updateRegions(F32 max_update_time)
-{
- LLMemType mt_ur(LLMemType::MTYPE_IDLE_UPDATE_REGIONS);
- LLTimer update_timer;
- BOOL did_one = FALSE;
-
- // Perform idle time updates for the regions (and associated surfaces)
- for (region_list_t::iterator iter = mRegionList.begin();
- iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- F32 max_time = max_update_time - update_timer.getElapsedTimeF32();
- if (did_one && max_time <= 0.f)
- break;
- max_time = llmin(max_time, max_update_time*.1f);
- did_one |= regionp->idleUpdate(max_update_time);
- }
-}
-
-void LLWorld::updateParticles()
-{
- LLViewerPartSim::getInstance()->updateSimulation();
-}
-
-void LLWorld::updateClouds(const F32 dt)
-{
- static LLFastTimer::DeclareTimer ftm("World Clouds");
- LLFastTimer t(ftm);
-
- if ( gSavedSettings.getBOOL("FreezeTime") )
- {
- // don't move clouds in snapshot mode
- return;
- }
-
- if (
- mClassicCloudsEnabled !=
- gSavedSettings.getBOOL("SkyUseClassicClouds") )
- {
- // The classic cloud toggle has been flipped
- // gotta update all of the cloud layers
- mClassicCloudsEnabled =
- gSavedSettings.getBOOL("SkyUseClassicClouds");
-
- if ( !mClassicCloudsEnabled && mActiveRegionList.size() )
- {
- // We've transitioned to having classic clouds disabled
- // reset all cloud layers.
- for (
- region_list_t::iterator iter = mActiveRegionList.begin();
- iter != mActiveRegionList.end();
- ++iter)
- {
- LLViewerRegion* regionp = *iter;
- regionp->mCloudLayer.reset();
- }
-
- return;
- }
- }
- else if ( !mClassicCloudsEnabled ) return;
-
- if (mActiveRegionList.size())
- {
- for (region_list_t::iterator iter = mActiveRegionList.begin();
- iter != mActiveRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- regionp->mCloudLayer.updatePuffs(dt);
- }
-
- // Reshuffle who owns which puffs
- for (region_list_t::iterator iter = mActiveRegionList.begin();
- iter != mActiveRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- regionp->mCloudLayer.updatePuffOwnership();
- }
-
- // Add new puffs
- for (region_list_t::iterator iter = mActiveRegionList.begin();
- iter != mActiveRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- regionp->mCloudLayer.updatePuffCount();
- }
- }
-}
-
-LLCloudGroup* LLWorld::findCloudGroup(const LLCloudPuff &puff)
-{
- if (mActiveRegionList.size())
- {
- // Update all the cloud puff positions, and timer based stuff
- // such as death decay
- for (region_list_t::iterator iter = mActiveRegionList.begin();
- iter != mActiveRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- LLCloudGroup *groupp = regionp->mCloudLayer.findCloudGroup(puff);
- if (groupp)
- {
- return groupp;
- }
- }
- }
- return NULL;
-}
-
-
-void LLWorld::renderPropertyLines()
-{
- S32 region_count = 0;
- S32 vertex_count = 0;
-
- for (region_list_t::iterator iter = mVisibleRegionList.begin();
- iter != mVisibleRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- region_count++;
- vertex_count += regionp->renderPropertyLines();
- }
-}
-
-
-void LLWorld::updateNetStats()
-{
- F32 bits = 0.f;
- U32 packets = 0;
-
- for (region_list_t::iterator iter = mActiveRegionList.begin();
- iter != mActiveRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- regionp->updateNetStats();
- bits += regionp->mBitStat.getCurrent();
- packets += llfloor( regionp->mPacketsStat.getCurrent() );
- }
-
- S32 packets_in = gMessageSystem->mPacketsIn - mLastPacketsIn;
- S32 packets_out = gMessageSystem->mPacketsOut - mLastPacketsOut;
- S32 packets_lost = gMessageSystem->mDroppedPackets - mLastPacketsLost;
-
- S32 actual_in_bits = gMessageSystem->mPacketRing.getAndResetActualInBits();
- S32 actual_out_bits = gMessageSystem->mPacketRing.getAndResetActualOutBits();
- LLViewerStats::getInstance()->mActualInKBitStat.addValue(actual_in_bits/1024.f);
- LLViewerStats::getInstance()->mActualOutKBitStat.addValue(actual_out_bits/1024.f);
- LLViewerStats::getInstance()->mKBitStat.addValue(bits/1024.f);
- LLViewerStats::getInstance()->mPacketsInStat.addValue(packets_in);
- LLViewerStats::getInstance()->mPacketsOutStat.addValue(packets_out);
- LLViewerStats::getInstance()->mPacketsLostStat.addValue(gMessageSystem->mDroppedPackets);
- if (packets_in)
- {
- LLViewerStats::getInstance()->mPacketsLostPercentStat.addValue(100.f*((F32)packets_lost/(F32)packets_in));
- }
- else
- {
- LLViewerStats::getInstance()->mPacketsLostPercentStat.addValue(0.f);
- }
-
- mLastPacketsIn = gMessageSystem->mPacketsIn;
- mLastPacketsOut = gMessageSystem->mPacketsOut;
- mLastPacketsLost = gMessageSystem->mDroppedPackets;
-}
-
-
-void LLWorld::printPacketsLost()
-{
- llinfos << "Simulators:" << llendl;
- llinfos << "----------" << llendl;
-
- LLCircuitData *cdp = NULL;
- for (region_list_t::iterator iter = mActiveRegionList.begin();
- iter != mActiveRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- cdp = gMessageSystem->mCircuitInfo.findCircuit(regionp->getHost());
- if (cdp)
- {
- LLVector3d range = regionp->getCenterGlobal() - gAgent.getPositionGlobal();
-
- llinfos << regionp->getHost() << ", range: " << range.length()
- << " packets lost: " << cdp->getPacketsLost() << llendl;
- }
- }
-}
-
-void LLWorld::processCoarseUpdate(LLMessageSystem* msg, void** user_data)
-{
- LLViewerRegion* region = LLWorld::getInstance()->getRegion(msg->getSender());
- if( region )
- {
- region->updateCoarseLocations(msg);
- }
-}
-
-F32 LLWorld::getLandFarClip() const
-{
- return mLandFarClip;
-}
-
-void LLWorld::setLandFarClip(const F32 far_clip)
-{
- static S32 const rwidth = (S32)REGION_WIDTH_U32;
- S32 const n1 = (llceil(mLandFarClip) - 1) / rwidth;
- S32 const n2 = (llceil(far_clip) - 1) / rwidth;
- bool need_water_objects_update = n1 != n2;
-
- mLandFarClip = far_clip;
-
- if (need_water_objects_update)
- {
- updateWaterObjects();
- }
-}
-
-// Some region that we're connected to, but not the one we're in, gave us
-// a (possibly) new water height. Update it in our local copy.
-void LLWorld::waterHeightRegionInfo(std::string const& sim_name, F32 water_height)
-{
- for (region_list_t::iterator iter = mRegionList.begin(); iter != mRegionList.end(); ++iter)
- {
- if ((*iter)->getName() == sim_name)
- {
- (*iter)->setWaterHeight(water_height);
- break;
- }
- }
-}
-
-// There are three types of water objects:
-// Region water objects: the water in a region.
-// Hole water objects: water in the void but within current draw distance.
-// Edge water objects: the water outside the draw distance, up till the horizon.
-//
-// For example:
-//
-// -----------------------horizon-------------------------
-// | | | |
-// | Edge Water | | |
-// | | | |
-// | | | |
-// | | | |
-// | | | |
-// | | rwidth | |
-// | | <-----> | |
-// -------------------------------------------------------
-// | |Hole |other| | |
-// | |Water|reg. | | |
-// | |-----------------| |
-// | |other|cur. |<--> | |
-// | |reg. | reg.| \__|_ draw distance |
-// | |-----------------| |
-// | | | |<--->| |
-// | | | | \__|_ range |
-// -------------------------------------------------------
-// | |<----width------>|<--horizon ext.->|
-// | | | |
-// | | | |
-// | | | |
-// | | | |
-// | | | |
-// | | | |
-// | | | |
-// -------------------------------------------------------
-//
-void LLWorld::updateWaterObjects()
-{
- if (!gAgent.getRegion())
- {
- return;
- }
- if (mRegionList.empty())
- {
- llwarns << "No regions!" << llendl;
- return;
- }
-
- // Region width in meters.
- S32 const rwidth = (S32)REGION_WIDTH_U32;
-
- // The distance we might see into the void
- // when standing on the edge of a region, in meters.
- S32 const draw_distance = llceil(mLandFarClip);
-
- // We can only have "holes" in the water (where there no region) if we
- // can have existing regions around it. Taking into account that this
- // code is only executed when we enter a region, and not when we walk
- // around in it, we (only) need to take into account regions that fall
- // within the draw_distance.
- //
- // Set 'range' to draw_distance, rounded up to the nearest multiple of rwidth.
- S32 const nsims = (draw_distance + rwidth - 1) / rwidth;
- S32 const range = nsims * rwidth;
-
- // Get South-West corner of current region.
- LLViewerRegion const* regionp = gAgent.getRegion();
- U32 region_x, region_y;
- from_region_handle(regionp->getHandle(), &region_x, &region_y);
-
- // The min. and max. coordinates of the South-West corners of the Hole water objects.
- S32 const min_x = (S32)region_x - range;
- S32 const min_y = (S32)region_y - range;
- S32 const max_x = (S32)region_x + range;
- S32 const max_y = (S32)region_y + range;
-
- // Attempt to determine a sensible water height for all the
- // Hole Water objects.
- //
- // It make little sense to try to guess what the best water
- // height should be when that isn't completely obvious: if it's
- // impossible to satisfy every region's water height without
- // getting a jump in the water height.
- //
- // In order to keep the reasoning simple, we assume something
- // logical as a group of connected regions, where the coastline
- // is at the outer edge. Anything more complex that would "break"
- // under such an assumption would probably break anyway (would
- // depend on terrain editing and existing mega prims, say, if
- // anything would make sense at all).
- //
- // So, what we do is find all connected regions within the
- // draw distance that border void, and then pick the lowest
- // water height of those (coast) regions.
- S32 const n = 2 * nsims + 1;
- S32 const origin = nsims + nsims * n;
- std::vector<F32> water_heights(n * n);
- std::vector<U8> checked(n * n, 0); // index = nx + ny * n + origin;
- U8 const region_bit = 1;
- U8 const hole_bit = 2;
- U8 const bordering_hole_bit = 4;
- U8 const bordering_edge_bit = 8;
- // Use the legacy waterheight for the Edge water in the case
- // that we don't find any Hole water at all.
- F32 water_height = DEFAULT_WATER_HEIGHT;
- int max_count = 0;
- LL_DEBUGS("WaterHeight") << "Current region: " << regionp->getName() << "; water height: " << regionp->getWaterHeight() << " m." << LL_ENDL;
- std::map<S32, int> water_height_counts;
- typedef std::queue<std::pair<S32, S32>, std::deque<std::pair<S32, S32> > > nxny_pairs_type;
- nxny_pairs_type nxny_pairs;
- nxny_pairs.push(nxny_pairs_type::value_type(0, 0));
- water_heights[origin] = regionp->getWaterHeight();
- checked[origin] = region_bit;
- // For debugging purposes.
- int number_of_connected_regions = 1;
- int uninitialized_regions = 0;
- int bordering_hole = 0;
- int bordering_edge = 0;
- while(!nxny_pairs.empty())
- {
- S32 const nx = nxny_pairs.front().first;
- S32 const ny = nxny_pairs.front().second;
- LL_DEBUGS("WaterHeight") << "nx,ny = " << nx << "," << ny << LL_ENDL;
- S32 const index = nx + ny * n + origin;
- nxny_pairs.pop();
- for (S32 dir = 0; dir < 4; ++dir)
- {
- S32 const cnx = nx + gDirAxes[dir][0];
- S32 const cny = ny + gDirAxes[dir][1];
- LL_DEBUGS("WaterHeight") << "dir = " << dir << "; cnx,cny = " << cnx << "," << cny << LL_ENDL;
- S32 const cindex = cnx + cny * n + origin;
- bool is_hole = false;
- bool is_edge = false;
- LLViewerRegion* new_region_found = NULL;
- if (cnx < -nsims || cnx > nsims ||
- cny < -nsims || cny > nsims)
- {
- LL_DEBUGS("WaterHeight") << " Edge Water!" << LL_ENDL;
- // Bumped into Edge water object.
- is_edge = true;
- }
- else if (checked[cindex])
- {
- LL_DEBUGS("WaterHeight") << " Already checked before!" << LL_ENDL;
- // Already checked.
- is_hole = (checked[cindex] & hole_bit);
- }
- else
- {
- S32 x = (S32)region_x + cnx * rwidth;
- S32 y = (S32)region_y + cny * rwidth;
- U64 region_handle = to_region_handle(x, y);
- new_region_found = getRegionFromHandle(region_handle);
- is_hole = !new_region_found;
- checked[cindex] = is_hole ? hole_bit : region_bit;
- }
- if (is_hole)
- {
- // This was a region that borders at least one 'hole'.
- // Count the found coastline.
- F32 new_water_height = water_heights[index];
- LL_DEBUGS("WaterHeight") << " This is void; counting coastline with water height of " << new_water_height << LL_ENDL;
- S32 new_water_height_cm = llround(new_water_height * 100);
- int count = (water_height_counts[new_water_height_cm] += 1);
- // Just use the lowest water height: this is mainly about the horizon water,
- // and whatever we do, we don't want it to be possible to look under the water
- // when looking in the distance: it is better to make a step downwards in water
- // height when going away from the avie than a step upwards. However, since
- // everyone is used to DEFAULT_WATER_HEIGHT, don't allow a single region
- // to drag the water level below DEFAULT_WATER_HEIGHT on it's own.
- if (bordering_hole == 0 || // First time we get here.
- (new_water_height >= DEFAULT_WATER_HEIGHT &&
- new_water_height < water_height) ||
- (new_water_height < DEFAULT_WATER_HEIGHT &&
- count > max_count)
- )
- {
- water_height = new_water_height;
- }
- if (count > max_count)
- {
- max_count = count;
- }
- if (!(checked[index] & bordering_hole_bit))
- {
- checked[index] |= bordering_hole_bit;
- ++bordering_hole;
- }
- }
- else if (is_edge && !(checked[index] & bordering_edge_bit))
- {
- checked[index] |= bordering_edge_bit;
- ++bordering_edge;
- }
- if (!new_region_found)
- {
- // Dead end, there is no region here.
- continue;
- }
- // Found a new connected region.
- ++number_of_connected_regions;
- if (new_region_found->getName().empty())
- {
- // Uninitialized LLViewerRegion, don't use it's water height.
- LL_DEBUGS("WaterHeight") << " Uninitialized region." << LL_ENDL;
- ++uninitialized_regions;
- continue;
- }
- nxny_pairs.push(nxny_pairs_type::value_type(cnx, cny));
- water_heights[cindex] = new_region_found->getWaterHeight();
- LL_DEBUGS("WaterHeight") << " Found a new region (name: " << new_region_found->getName() << "; water height: " << water_heights[cindex] << " m)!" << LL_ENDL;
- }
- }
- llinfos << "Number of connected regions: " << number_of_connected_regions << " (" << uninitialized_regions <<
- " uninitialized); number of regions bordering Hole water: " << bordering_hole <<
- "; number of regions bordering Edge water: " << bordering_edge << llendl;
- llinfos << "Coastline count (height, count): ";
- bool first = true;
- for (std::map<S32, int>::iterator iter = water_height_counts.begin(); iter != water_height_counts.end(); ++iter)
- {
- if (!first) llcont << ", ";
- llcont << "(" << (iter->first / 100.f) << ", " << iter->second << ")";
- first = false;
- }
- llcont << llendl;
- llinfos << "Water height used for Hole and Edge water objects: " << water_height << llendl;
-
- // Update all Region water objects.
- for (region_list_t::iterator iter = mRegionList.begin(); iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- LLVOWater* waterp = regionp->getLand().getWaterObj();
- if (waterp)
- {
- gObjectList.updateActive(waterp);
- }
- }
-
- // Clean up all existing Hole water objects.
- for (std::list<LLVOWater*>::iterator iter = mHoleWaterObjects.begin();
- iter != mHoleWaterObjects.end(); ++iter)
- {
- LLVOWater* waterp = *iter;
- gObjectList.killObject(waterp);
- }
- mHoleWaterObjects.clear();
-
- // Let the Edge and Hole water boxes be 1024 meter high so that they
- // are never too small to be drawn (A LL_VO_*_WATER box has water
- // rendered on it's bottom surface only), and put their bottom at
- // the current regions water height.
- F32 const box_height = 1024;
- F32 const water_center_z = water_height + box_height / 2;
-
- // Create new Hole water objects within 'range' where there is no region.
- for (S32 x = min_x; x <= max_x; x += rwidth)
- {
- for (S32 y = min_y; y <= max_y; y += rwidth)
- {
- U64 region_handle = to_region_handle(x, y);
- if (!getRegionFromHandle(region_handle))
- {
- LLVOWater* waterp = (LLVOWater*)gObjectList.createObjectViewer(LLViewerObject::LL_VO_VOID_WATER, gAgent.getRegion());
- waterp->setUseTexture(FALSE);
- waterp->setPositionGlobal(LLVector3d(x + rwidth / 2, y + rwidth / 2, water_center_z));
- waterp->setScale(LLVector3((F32)rwidth, (F32)rwidth, box_height));
- gPipeline.createObject(waterp);
- mHoleWaterObjects.push_back(waterp);
- }
- }
- }
-
- // Center of the region.
- S32 const center_x = region_x + rwidth / 2;
- S32 const center_y = region_y + rwidth / 2;
- // Width of the area with Hole water objects.
- S32 const width = rwidth + 2 * range;
- S32 const horizon_extend = 2048 + 512 - range; // Legacy value.
- // The overlap is needed to get rid of sky pixels being visible between the
- // Edge and Hole water object at greater distances (due to floating point
- // round off errors).
- S32 const edge_hole_overlap = 1; // Twice the actual overlap.
-
- for (S32 dir = 0; dir < 8; ++dir)
- {
- // Size of the Edge water objects.
- S32 const dim_x = (gDirAxes[dir][0] == 0) ? width : (horizon_extend + edge_hole_overlap);
- S32 const dim_y = (gDirAxes[dir][1] == 0) ? width : (horizon_extend + edge_hole_overlap);
- // And their position.
- S32 const water_center_x = center_x + (width + horizon_extend) / 2 * gDirAxes[dir][0];
- S32 const water_center_y = center_y + (width + horizon_extend) / 2 * gDirAxes[dir][1];
-
- LLVOWater* waterp = mEdgeWaterObjects[dir];
- if (!waterp || waterp->isDead())
- {
- // The edge water objects can be dead because they're attached to the region that the
- // agent was in when they were originally created.
- mEdgeWaterObjects[dir] = (LLVOWater *)gObjectList.createObjectViewer(LLViewerObject::LL_VO_VOID_WATER, gAgent.getRegion());
- waterp = mEdgeWaterObjects[dir];
- waterp->setUseTexture(FALSE);
- waterp->setIsEdgePatch(TRUE); // Mark that this is edge water and not hole water.
- gPipeline.createObject(waterp);
- }
-
- waterp->setRegion(gAgent.getRegion());
- LLVector3d water_pos(water_center_x, water_center_y, water_center_z);
- LLVector3 water_scale((F32) dim_x, (F32) dim_y, box_height);
-
- waterp->setPositionGlobal(water_pos);
- waterp->setScale(water_scale);
-
- gObjectList.updateActive(waterp);
- }
-}
-
-void LLWorld::shiftRegions(const LLVector3& offset)
-{
- for (region_list_t::const_iterator i = getRegionList().begin(); i != getRegionList().end(); ++i)
- {
- LLViewerRegion* region = *i;
- region->updateRenderMatrix();
- }
-
- LLViewerPartSim::getInstance()->shift(offset);
-}
-
-LLViewerTexture* LLWorld::getDefaultWaterTexture()
-{
- return mDefaultWaterTexturep;
-}
-
-void LLWorld::setSpaceTimeUSec(const U64 space_time_usec)
-{
- mSpaceTimeUSec = space_time_usec;
-}
-
-U64 LLWorld::getSpaceTimeUSec() const
-{
- return mSpaceTimeUSec;
-}
-
-void LLWorld::requestCacheMisses()
-{
- for (region_list_t::iterator iter = mRegionList.begin();
- iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- regionp->requestCacheMisses();
- }
-}
-
-void LLWorld::getInfo(LLSD& info)
-{
- LLSD region_info;
- for (region_list_t::iterator iter = mRegionList.begin();
- iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- regionp->getInfo(region_info);
- info["World"].append(region_info);
- }
-}
-
-void LLWorld::disconnectRegions()
-{
- LLMessageSystem* msg = gMessageSystem;
- for (region_list_t::iterator iter = mRegionList.begin();
- iter != mRegionList.end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- if (regionp == gAgent.getRegion())
- {
- // Skip the main agent
- continue;
- }
-
- llinfos << "Sending AgentQuitCopy to: " << regionp->getHost() << llendl;
- msg->newMessageFast(_PREHASH_AgentQuitCopy);
- msg->nextBlockFast(_PREHASH_AgentData);
- msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
- msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- msg->nextBlockFast(_PREHASH_FuseBlock);
- msg->addU32Fast(_PREHASH_ViewerCircuitCode, gMessageSystem->mOurCircuitCode);
- msg->sendMessage(regionp->getHost());
- }
-}
-
-static LLFastTimer::DeclareTimer FTM_ENABLE_SIMULATOR("Enable Sim");
-
-void process_enable_simulator(LLMessageSystem *msg, void **user_data)
-{
- LLFastTimer t(FTM_ENABLE_SIMULATOR);
- // enable the appropriate circuit for this simulator and
- // add its values into the gSimulator structure
- U64 handle;
- U32 ip_u32;
- U16 port;
-
- msg->getU64Fast(_PREHASH_SimulatorInfo, _PREHASH_Handle, handle);
- msg->getIPAddrFast(_PREHASH_SimulatorInfo, _PREHASH_IP, ip_u32);
- msg->getIPPortFast(_PREHASH_SimulatorInfo, _PREHASH_Port, port);
-
- // which simulator should we modify?
- LLHost sim(ip_u32, port);
-
- // Viewer trusts the simulator.
- msg->enableCircuit(sim, TRUE);
- LLWorld::getInstance()->addRegion(handle, sim);
-
- // give the simulator a message it can use to get ip and port
- llinfos << "simulator_enable() Enabling " << sim << " with code " << msg->getOurCircuitCode() << llendl;
- msg->newMessageFast(_PREHASH_UseCircuitCode);
- msg->nextBlockFast(_PREHASH_CircuitCode);
- msg->addU32Fast(_PREHASH_Code, msg->getOurCircuitCode());
- msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
- msg->addUUIDFast(_PREHASH_ID, gAgent.getID());
- msg->sendReliable(sim);
-}
-
-class LLEstablishAgentCommunication : public LLHTTPNode
-{
- LOG_CLASS(LLEstablishAgentCommunication);
-public:
- virtual void describe(Description& desc) const
- {
- desc.shortInfo("seed capability info for a region");
- desc.postAPI();
- desc.input(
- "{ seed-capability: ..., sim-ip: ..., sim-port }");
- desc.source(__FILE__, __LINE__);
- }
-
- virtual void post(ResponsePtr response, const LLSD& context, const LLSD& input) const
- {
- if (!input["body"].has("agent-id") ||
- !input["body"].has("sim-ip-and-port") ||
- !input["body"].has("seed-capability"))
- {
- llwarns << "invalid parameters" << llendl;
- return;
- }
-
- LLHost sim(input["body"]["sim-ip-and-port"].asString());
-
- LLViewerRegion* regionp = LLWorld::getInstance()->getRegion(sim);
- if (!regionp)
- {
- llwarns << "Got EstablishAgentCommunication for unknown region "
- << sim << llendl;
- return;
- }
- regionp->setSeedCapability(input["body"]["seed-capability"]);
- }
-};
-
-// disable the circuit to this simulator
-// Called in response to "DisableSimulator" message.
-void process_disable_simulator(LLMessageSystem *mesgsys, void **user_data)
-{
- LLHost host = mesgsys->getSender();
-
- //llinfos << "Disabling simulator with message from " << host << llendl;
- LLWorld::getInstance()->removeRegion(host);
-
- mesgsys->disableCircuit(host);
-}
-
-
-void process_region_handshake(LLMessageSystem* msg, void** user_data)
-{
- LLHost host = msg->getSender();
- LLViewerRegion* regionp = LLWorld::getInstance()->getRegion(host);
- if (!regionp)
- {
- llwarns << "Got region handshake for unknown region "
- << host << llendl;
- return;
- }
-
- regionp->unpackRegionHandshake();
-}
-
-
-void send_agent_pause()
-{
- // *NOTE:Mani Pausing the mainloop timeout. Otherwise a long modal event may cause
- // the thread monitor to timeout.
- LLAppViewer::instance()->pauseMainloopTimeout();
-
- // Note: used to check for LLWorld initialization before it became a singleton.
- // Rather than just remove this check I'm changing it to assure that the message
- // system has been initialized. -MG
- if (!gMessageSystem)
- {
- return;
- }
-
- gMessageSystem->newMessageFast(_PREHASH_AgentPause);
- gMessageSystem->nextBlockFast(_PREHASH_AgentData);
- gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgentID);
- gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgentSessionID);
-
- gAgentPauseSerialNum++;
- gMessageSystem->addU32Fast(_PREHASH_SerialNum, gAgentPauseSerialNum);
-
- for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
- iter != LLWorld::getInstance()->getRegionList().end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- gMessageSystem->sendReliable(regionp->getHost());
- }
-
- gObjectList.mWasPaused = TRUE;
-}
-
-
-void send_agent_resume()
-{
- // Note: used to check for LLWorld initialization before it became a singleton.
- // Rather than just remove this check I'm changing it to assure that the message
- // system has been initialized. -MG
- if (!gMessageSystem)
- {
- return;
- }
-
- gMessageSystem->newMessageFast(_PREHASH_AgentResume);
- gMessageSystem->nextBlockFast(_PREHASH_AgentData);
- gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgentID);
- gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgentSessionID);
-
- gAgentPauseSerialNum++;
- gMessageSystem->addU32Fast(_PREHASH_SerialNum, gAgentPauseSerialNum);
-
-
- for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
- iter != LLWorld::getInstance()->getRegionList().end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- gMessageSystem->sendReliable(regionp->getHost());
- }
-
- // Reset the FPS counter to avoid an invalid fps
- LLViewerStats::getInstance()->mFPSStat.start();
-
- LLAppViewer::instance()->resumeMainloopTimeout();
-}
-
-static LLVector3d unpackLocalToGlobalPosition(U32 compact_local, const LLVector3d& region_origin)
-{
- LLVector3d pos_global;
- LLVector3 pos_local;
- U8 bits;
-
- bits = compact_local & 0xFF;
- pos_local.mV[VZ] = F32(bits) * 4.f;
- compact_local >>= 8;
-
- bits = compact_local & 0xFF;
- pos_local.mV[VY] = (F32)bits;
- compact_local >>= 8;
-
- bits = compact_local & 0xFF;
- pos_local.mV[VX] = (F32)bits;
-
- pos_global.setVec( pos_local );
- pos_global += region_origin;
- return pos_global;
-}
-
-void LLWorld::getAvatars(uuid_vec_t* avatar_ids, std::vector<LLVector3d>* positions, const LLVector3d& relative_to, F32 radius) const
-{
- if(avatar_ids != NULL)
- {
- avatar_ids->clear();
- }
- if(positions != NULL)
- {
- positions->clear();
- }
- for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
- iter != LLWorld::getInstance()->getRegionList().end(); ++iter)
- {
- LLViewerRegion* regionp = *iter;
- const LLVector3d& origin_global = regionp->getOriginGlobal();
- S32 count = regionp->mMapAvatars.count();
- for (S32 i = 0; i < count; i++)
- {
- LLVector3d pos_global = unpackLocalToGlobalPosition(regionp->mMapAvatars.get(i), origin_global);
- if(dist_vec(pos_global, relative_to) <= radius)
- {
- if(positions != NULL)
- {
- positions->push_back(pos_global);
- }
- if(avatar_ids != NULL)
- {
- avatar_ids->push_back(regionp->mMapAvatarIDs.get(i));
- }
- }
- }
- }
- // retrieve the list of close avatars from viewer objects as well
- // for when we are above 1000m, only do this when we are retrieving
- // uuid's too as there could be duplicates
- if(avatar_ids != NULL)
- {
- for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
- iter != LLCharacter::sInstances.end(); ++iter)
- {
- LLVOAvatar* pVOAvatar = (LLVOAvatar*) *iter;
- if(pVOAvatar->isDead() || pVOAvatar->isSelf())
- continue;
- LLUUID uuid = pVOAvatar->getID();
- if(uuid.isNull())
- continue;
- LLVector3d pos_global = pVOAvatar->getPositionGlobal();
- if(dist_vec(pos_global, relative_to) <= radius)
- {
- bool found = false;
- uuid_vec_t::iterator sel_iter = avatar_ids->begin();
- for (; sel_iter != avatar_ids->end(); sel_iter++)
- {
- if(*sel_iter == uuid)
- {
- found = true;
- break;
- }
- }
- if(!found)
- {
- if(positions != NULL)
- positions->push_back(pos_global);
- avatar_ids->push_back(uuid);
- }
- }
- }
- }
-}
-
-
-LLHTTPRegistration<LLEstablishAgentCommunication>
- gHTTPRegistrationEstablishAgentCommunication(
- "/message/EstablishAgentCommunication");
+/**
+ * @file llworld.cpp
+ * @brief Initial test structure to organize viewer regions
+ *
+ * $LicenseInfo:firstyear=2001&license=viewerlgpl$
+ * Second Life Viewer Source Code
+ * Copyright (C) 2010, Linden Research, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation;
+ * version 2.1 of the License only.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+ * $/LicenseInfo$
+ */
+
+#include "llviewerprecompiledheaders.h"
+
+#include "llworld.h"
+#include "llrender.h"
+
+#include "indra_constants.h"
+#include "llstl.h"
+
+#include "llagent.h"
+#include "llviewercontrol.h"
+#include "lldrawpool.h"
+#include "llglheaders.h"
+#include "llhttpnode.h"
+#include "llregionhandle.h"
+#include "llsurface.h"
+#include "lltrans.h"
+#include "llviewercamera.h"
+#include "llviewertexture.h"
+#include "llviewertexturelist.h"
+#include "llviewernetwork.h"
+#include "llviewerobjectlist.h"
+#include "llviewerparceloverlay.h"
+#include "llviewerregion.h"
+#include "llviewerstats.h"
+#include "llvlcomposition.h"
+#include "llvoavatar.h"
+#include "llvowater.h"
+#include "message.h"
+#include "pipeline.h"
+#include "llappviewer.h" // for do_disconnect()
+
+#include <deque>
+#include <queue>
+#include <map>
+#include <cstring>
+
+//
+// Globals
+//
+U32 gAgentPauseSerialNum = 0;
+
+//
+// Constants
+//
+const S32 MAX_NUMBER_OF_CLOUDS = 750;
+const S32 WORLD_PATCH_SIZE = 16;
+
+extern LLColor4U MAX_WATER_COLOR;
+
+const U32 LLWorld::mWidth = 256;
+
+// meters/point, therefore mWidth * mScale = meters per edge
+const F32 LLWorld::mScale = 1.f;
+
+const F32 LLWorld::mWidthInMeters = mWidth * mScale;
+
+//
+// Functions
+//
+
+// allocate the stack
+LLWorld::LLWorld() :
+ mLandFarClip(DEFAULT_FAR_PLANE),
+ mLastPacketsIn(0),
+ mLastPacketsOut(0),
+ mLastPacketsLost(0),
+ mSpaceTimeUSec(0),
+ mClassicCloudsEnabled(TRUE)
+{
+ for (S32 i = 0; i < 8; i++)
+ {
+ mEdgeWaterObjects[i] = NULL;
+ }
+
+ if (gNoRender)
+ {
+ return;
+ }
+
+ LLPointer<LLImageRaw> raw = new LLImageRaw(1,1,4);
+ U8 *default_texture = raw->getData();
+ *(default_texture++) = MAX_WATER_COLOR.mV[0];
+ *(default_texture++) = MAX_WATER_COLOR.mV[1];
+ *(default_texture++) = MAX_WATER_COLOR.mV[2];
+ *(default_texture++) = MAX_WATER_COLOR.mV[3];
+
+ mDefaultWaterTexturep = LLViewerTextureManager::getLocalTexture(raw.get(), FALSE);
+ gGL.getTexUnit(0)->bind(mDefaultWaterTexturep);
+ mDefaultWaterTexturep->setAddressMode(LLTexUnit::TAM_CLAMP);
+
+}
+
+
+void LLWorld::destroyClass()
+{
+ mHoleWaterObjects.clear();
+ gObjectList.destroy();
+ for(region_list_t::iterator region_it = mRegionList.begin(); region_it != mRegionList.end(); )
+ {
+ LLViewerRegion* region_to_delete = *region_it++;
+ removeRegion(region_to_delete->getHost());
+ }
+ if(LLVOCache::hasInstance())
+ {
+ LLVOCache::getInstance()->destroyClass() ;
+ }
+ LLViewerPartSim::getInstance()->destroyClass();
+}
+
+
+LLViewerRegion* LLWorld::addRegion(const U64 &region_handle, const LLHost &host)
+{
+ LLMemType mt(LLMemType::MTYPE_REGIONS);
+ llinfos << "Add region with handle: " << region_handle << " on host " << host << llendl;
+ LLViewerRegion *regionp = getRegionFromHandle(region_handle);
+ if (regionp)
+ {
+ llinfos << "Region exists, removing it " << llendl;
+ LLHost old_host = regionp->getHost();
+ // region already exists!
+ if (host == old_host && regionp->isAlive())
+ {
+ // This is a duplicate for the same host and it's alive, don't bother.
+ return regionp;
+ }
+
+ if (host != old_host)
+ {
+ llwarns << "LLWorld::addRegion exists, but old host " << old_host
+ << " does not match new host " << host << llendl;
+ }
+ if (!regionp->isAlive())
+ {
+ llwarns << "LLWorld::addRegion exists, but isn't alive" << llendl;
+ }
+
+ // Kill the old host, and then we can continue on and add the new host. We have to kill even if the host
+ // matches, because all the agent state for the new camera is completely different.
+ removeRegion(old_host);
+ }
+
+ U32 iindex = 0;
+ U32 jindex = 0;
+ from_region_handle(region_handle, &iindex, &jindex);
+ S32 x = (S32)(iindex/mWidth);
+ S32 y = (S32)(jindex/mWidth);
+ llinfos << "Adding new region (" << x << ":" << y << ")" << llendl;
+ llinfos << "Host: " << host << llendl;
+
+ LLVector3d origin_global;
+
+ origin_global = from_region_handle(region_handle);
+
+ regionp = new LLViewerRegion(region_handle,
+ host,
+ mWidth,
+ WORLD_PATCH_SIZE,
+ getRegionWidthInMeters() );
+ if (!regionp)
+ {
+ llerrs << "Unable to create new region!" << llendl;
+ }
+
+ regionp->mCloudLayer.create(regionp);
+ regionp->mCloudLayer.setWidth((F32)mWidth);
+ regionp->mCloudLayer.setWindPointer(&regionp->mWind);
+
+ mRegionList.push_back(regionp);
+ mActiveRegionList.push_back(regionp);
+ mCulledRegionList.push_back(regionp);
+
+
+ // Find all the adjacent regions, and attach them.
+ // Generate handles for all of the adjacent regions, and attach them in the correct way.
+ // connect the edges
+ F32 adj_x = 0.f;
+ F32 adj_y = 0.f;
+ F32 region_x = 0.f;
+ F32 region_y = 0.f;
+ U64 adj_handle = 0;
+
+ F32 width = getRegionWidthInMeters();
+
+ LLViewerRegion *neighborp;
+ from_region_handle(region_handle, &region_x, &region_y);
+
+ // Iterate through all directions, and connect neighbors if there.
+ S32 dir;
+ for (dir = 0; dir < 8; dir++)
+ {
+ adj_x = region_x + width * gDirAxes[dir][0];
+ adj_y = region_y + width * gDirAxes[dir][1];
+ to_region_handle(adj_x, adj_y, &adj_handle);
+
+ neighborp = getRegionFromHandle(adj_handle);
+ if (neighborp)
+ {
+ //llinfos << "Connecting " << region_x << ":" << region_y << " -> " << adj_x << ":" << adj_y << llendl;
+ regionp->connectNeighbor(neighborp, dir);
+ }
+ }
+
+ updateWaterObjects();
+
+ return regionp;
+}
+
+
+void LLWorld::removeRegion(const LLHost &host)
+{
+ F32 x, y;
+
+ LLViewerRegion *regionp = getRegion(host);
+ if (!regionp)
+ {
+ llwarns << "Trying to remove region that doesn't exist!" << llendl;
+ return;
+ }
+
+ if (regionp == gAgent.getRegion())
+ {
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* reg = *iter;
+ llwarns << "RegionDump: " << reg->getName()
+ << " " << reg->getHost()
+ << " " << reg->getOriginGlobal()
+ << llendl;
+ }
+
+ llwarns << "Agent position global " << gAgent.getPositionGlobal()
+ << " agent " << gAgent.getPositionAgent()
+ << llendl;
+
+ llwarns << "Regions visited " << gAgent.getRegionsVisited() << llendl;
+
+ llwarns << "gFrameTimeSeconds " << gFrameTimeSeconds << llendl;
+
+ llwarns << "Disabling region " << regionp->getName() << " that agent is in!" << llendl;
+ LLAppViewer::instance()->forceDisconnect(LLTrans::getString("YouHaveBeenDisconnected"));
+
+ regionp->saveObjectCache() ; //force to save objects here in case that the object cache is about to be destroyed.
+ return;
+ }
+
+ from_region_handle(regionp->getHandle(), &x, &y);
+ llinfos << "Removing region " << x << ":" << y << llendl;
+
+ mRegionList.remove(regionp);
+ mActiveRegionList.remove(regionp);
+ mCulledRegionList.remove(regionp);
+ mVisibleRegionList.remove(regionp);
+
+ delete regionp;
+
+ updateWaterObjects();
+
+ //double check all objects of this region are removed.
+ gObjectList.clearAllMapObjectsInRegion(regionp) ;
+ //llassert_always(!gObjectList.hasMapObjectInRegion(regionp)) ;
+}
+
+
+LLViewerRegion* LLWorld::getRegion(const LLHost &host)
+{
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ if (regionp->getHost() == host)
+ {
+ return regionp;
+ }
+ }
+ return NULL;
+}
+
+LLViewerRegion* LLWorld::getRegionFromPosAgent(const LLVector3 &pos)
+{
+ return getRegionFromPosGlobal(gAgent.getPosGlobalFromAgent(pos));
+}
+
+LLViewerRegion* LLWorld::getRegionFromPosGlobal(const LLVector3d &pos)
+{
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ if (regionp->pointInRegionGlobal(pos))
+ {
+ return regionp;
+ }
+ }
+ return NULL;
+}
+
+
+LLVector3d LLWorld::clipToVisibleRegions(const LLVector3d &start_pos, const LLVector3d &end_pos)
+{
+ if (positionRegionValidGlobal(end_pos))
+ {
+ return end_pos;
+ }
+
+ LLViewerRegion* regionp = getRegionFromPosGlobal(start_pos);
+ if (!regionp)
+ {
+ return start_pos;
+ }
+
+ LLVector3d delta_pos = end_pos - start_pos;
+ LLVector3d delta_pos_abs;
+ delta_pos_abs.setVec(delta_pos);
+ delta_pos_abs.abs();
+
+ LLVector3 region_coord = regionp->getPosRegionFromGlobal(end_pos);
+ F64 clip_factor = 1.0;
+ F32 region_width = regionp->getWidth();
+ if (region_coord.mV[VX] < 0.f)
+ {
+ if (region_coord.mV[VY] < region_coord.mV[VX])
+ {
+ // clip along y -
+ clip_factor = -(region_coord.mV[VY] / delta_pos_abs.mdV[VY]);
+ }
+ else
+ {
+ // clip along x -
+ clip_factor = -(region_coord.mV[VX] / delta_pos_abs.mdV[VX]);
+ }
+ }
+ else if (region_coord.mV[VX] > region_width)
+ {
+ if (region_coord.mV[VY] > region_coord.mV[VX])
+ {
+ // clip along y +
+ clip_factor = (region_coord.mV[VY] - region_width) / delta_pos_abs.mdV[VY];
+ }
+ else
+ {
+ //clip along x +
+ clip_factor = (region_coord.mV[VX] - region_width) / delta_pos_abs.mdV[VX];
+ }
+ }
+ else if (region_coord.mV[VY] < 0.f)
+ {
+ // clip along y -
+ clip_factor = -(region_coord.mV[VY] / delta_pos_abs.mdV[VY]);
+ }
+ else if (region_coord.mV[VY] > region_width)
+ {
+ // clip along y +
+ clip_factor = (region_coord.mV[VY] - region_width) / delta_pos_abs.mdV[VY];
+ }
+
+ // clamp to within region dimensions
+ LLVector3d final_region_pos = LLVector3d(region_coord) - (delta_pos * clip_factor);
+ final_region_pos.mdV[VX] = llclamp(final_region_pos.mdV[VX], 0.0,
+ (F64)(region_width - F_ALMOST_ZERO));
+ final_region_pos.mdV[VY] = llclamp(final_region_pos.mdV[VY], 0.0,
+ (F64)(region_width - F_ALMOST_ZERO));
+ final_region_pos.mdV[VZ] = llclamp(final_region_pos.mdV[VZ], 0.0,
+ (F64)(LLWorld::getInstance()->getRegionMaxHeight() - F_ALMOST_ZERO));
+ return regionp->getPosGlobalFromRegion(LLVector3(final_region_pos));
+}
+
+LLViewerRegion* LLWorld::getRegionFromHandle(const U64 &handle)
+{
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ if (regionp->getHandle() == handle)
+ {
+ return regionp;
+ }
+ }
+ return NULL;
+}
+
+
+void LLWorld::updateAgentOffset(const LLVector3d &offset_global)
+{
+#if 0
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ regionp->setAgentOffset(offset_global);
+ }
+#endif
+}
+
+
+BOOL LLWorld::positionRegionValidGlobal(const LLVector3d &pos_global)
+{
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ if (regionp->pointInRegionGlobal(pos_global))
+ {
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+
+// Allow objects to go up to their radius underground.
+F32 LLWorld::getMinAllowedZ(LLViewerObject* object, const LLVector3d &global_pos)
+{
+ F32 land_height = resolveLandHeightGlobal(global_pos);
+ F32 radius = 0.5f * object->getScale().length();
+ return land_height - radius;
+}
+
+
+
+LLViewerRegion* LLWorld::resolveRegionGlobal(LLVector3 &pos_region, const LLVector3d &pos_global)
+{
+ LLViewerRegion *regionp = getRegionFromPosGlobal(pos_global);
+
+ if (regionp)
+ {
+ pos_region = regionp->getPosRegionFromGlobal(pos_global);
+ return regionp;
+ }
+
+ return NULL;
+}
+
+
+LLViewerRegion* LLWorld::resolveRegionAgent(LLVector3 &pos_region, const LLVector3 &pos_agent)
+{
+ LLVector3d pos_global = gAgent.getPosGlobalFromAgent(pos_agent);
+ LLViewerRegion *regionp = getRegionFromPosGlobal(pos_global);
+
+ if (regionp)
+ {
+ pos_region = regionp->getPosRegionFromGlobal(pos_global);
+ return regionp;
+ }
+
+ return NULL;
+}
+
+
+F32 LLWorld::resolveLandHeightAgent(const LLVector3 &pos_agent)
+{
+ LLVector3d pos_global = gAgent.getPosGlobalFromAgent(pos_agent);
+ return resolveLandHeightGlobal(pos_global);
+}
+
+
+F32 LLWorld::resolveLandHeightGlobal(const LLVector3d &pos_global)
+{
+ LLViewerRegion *regionp = getRegionFromPosGlobal(pos_global);
+ if (regionp)
+ {
+ return regionp->getLand().resolveHeightGlobal(pos_global);
+ }
+ return 0.0f;
+}
+
+
+// Takes a line defined by "point_a" and "point_b" and determines the closest (to point_a)
+// point where the the line intersects an object or the land surface. Stores the results
+// in "intersection" and "intersection_normal" and returns a scalar value that represents
+// the normalized distance along the line from "point_a" to "intersection".
+//
+// Currently assumes point_a and point_b only differ in z-direction,
+// but it may eventually become more general.
+F32 LLWorld::resolveStepHeightGlobal(const LLVOAvatar* avatarp, const LLVector3d &point_a, const LLVector3d &point_b,
+ LLVector3d &intersection, LLVector3 &intersection_normal,
+ LLViewerObject **viewerObjectPtr)
+{
+ // initialize return value to null
+ if (viewerObjectPtr)
+ {
+ *viewerObjectPtr = NULL;
+ }
+
+ LLViewerRegion *regionp = getRegionFromPosGlobal(point_a);
+ if (!regionp)
+ {
+ // We're outside the world
+ intersection = 0.5f * (point_a + point_b);
+ intersection_normal.setVec(0.0f, 0.0f, 1.0f);
+ return 0.5f;
+ }
+
+ // calculate the length of the segment
+ F32 segment_length = (F32)((point_a - point_b).length());
+ if (0.0f == segment_length)
+ {
+ intersection = point_a;
+ intersection_normal.setVec(0.0f, 0.0f, 1.0f);
+ return segment_length;
+ }
+
+ // get land height
+ // Note: we assume that the line is parallel to z-axis here
+ LLVector3d land_intersection = point_a;
+ F32 normalized_land_distance;
+
+ land_intersection.mdV[VZ] = regionp->getLand().resolveHeightGlobal(point_a);
+ normalized_land_distance = (F32)(point_a.mdV[VZ] - land_intersection.mdV[VZ]) / segment_length;
+ intersection = land_intersection;
+ intersection_normal = resolveLandNormalGlobal(land_intersection);
+
+ if (avatarp && !avatarp->mFootPlane.isExactlyClear())
+ {
+ LLVector3 foot_plane_normal(avatarp->mFootPlane.mV);
+ LLVector3 start_pt = avatarp->getRegion()->getPosRegionFromGlobal(point_a);
+ // added 0.05 meters to compensate for error in foot plane reported by Havok
+ F32 norm_dist_from_plane = ((start_pt * foot_plane_normal) - avatarp->mFootPlane.mV[VW]) + 0.05f;
+ norm_dist_from_plane = llclamp(norm_dist_from_plane / segment_length, 0.f, 1.f);
+ if (norm_dist_from_plane < normalized_land_distance)
+ {
+ // collided with object before land
+ normalized_land_distance = norm_dist_from_plane;
+ intersection = point_a;
+ intersection.mdV[VZ] -= norm_dist_from_plane * segment_length;
+ intersection_normal = foot_plane_normal;
+ }
+ else
+ {
+ intersection = land_intersection;
+ intersection_normal = resolveLandNormalGlobal(land_intersection);
+ }
+ }
+
+ return normalized_land_distance;
+}
+
+
+LLSurfacePatch * LLWorld::resolveLandPatchGlobal(const LLVector3d &pos_global)
+{
+ // returns a pointer to the patch at this location
+ LLViewerRegion *regionp = getRegionFromPosGlobal(pos_global);
+ if (!regionp)
+ {
+ return NULL;
+ }
+
+ return regionp->getLand().resolvePatchGlobal(pos_global);
+}
+
+
+LLVector3 LLWorld::resolveLandNormalGlobal(const LLVector3d &pos_global)
+{
+ LLViewerRegion *regionp = getRegionFromPosGlobal(pos_global);
+ if (!regionp)
+ {
+ return LLVector3::z_axis;
+ }
+
+ return regionp->getLand().resolveNormalGlobal(pos_global);
+}
+
+
+void LLWorld::updateVisibilities()
+{
+ F32 cur_far_clip = LLViewerCamera::getInstance()->getFar();
+
+ LLViewerCamera::getInstance()->setFar(mLandFarClip);
+
+ F32 diagonal_squared = F_SQRT2 * F_SQRT2 * mWidth * mWidth;
+ // Go through the culled list and check for visible regions
+ for (region_list_t::iterator iter = mCulledRegionList.begin();
+ iter != mCulledRegionList.end(); )
+ {
+ region_list_t::iterator curiter = iter++;
+ LLViewerRegion* regionp = *curiter;
+ F32 height = regionp->getLand().getMaxZ() - regionp->getLand().getMinZ();
+ F32 radius = 0.5f*(F32) sqrt(height * height + diagonal_squared);
+ if (!regionp->getLand().hasZData()
+ || LLViewerCamera::getInstance()->sphereInFrustum(regionp->getCenterAgent(), radius))
+ {
+ mCulledRegionList.erase(curiter);
+ mVisibleRegionList.push_back(regionp);
+ }
+ }
+
+ // Update all of the visible regions
+ for (region_list_t::iterator iter = mVisibleRegionList.begin();
+ iter != mVisibleRegionList.end(); )
+ {
+ region_list_t::iterator curiter = iter++;
+ LLViewerRegion* regionp = *curiter;
+ if (!regionp->getLand().hasZData())
+ {
+ continue;
+ }
+
+ F32 height = regionp->getLand().getMaxZ() - regionp->getLand().getMinZ();
+ F32 radius = 0.5f*(F32) sqrt(height * height + diagonal_squared);
+ if (LLViewerCamera::getInstance()->sphereInFrustum(regionp->getCenterAgent(), radius))
+ {
+ regionp->calculateCameraDistance();
+ if (!gNoRender)
+ {
+ regionp->getLand().updatePatchVisibilities(gAgent);
+ }
+ }
+ else
+ {
+ mVisibleRegionList.erase(curiter);
+ mCulledRegionList.push_back(regionp);
+ }
+ }
+
+ // Sort visible regions
+ mVisibleRegionList.sort(LLViewerRegion::CompareDistance());
+
+ LLViewerCamera::getInstance()->setFar(cur_far_clip);
+}
+
+void LLWorld::updateRegions(F32 max_update_time)
+{
+ LLMemType mt_ur(LLMemType::MTYPE_IDLE_UPDATE_REGIONS);
+ LLTimer update_timer;
+ BOOL did_one = FALSE;
+
+ // Perform idle time updates for the regions (and associated surfaces)
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ F32 max_time = max_update_time - update_timer.getElapsedTimeF32();
+ if (did_one && max_time <= 0.f)
+ break;
+ max_time = llmin(max_time, max_update_time*.1f);
+ did_one |= regionp->idleUpdate(max_update_time);
+ }
+}
+
+void LLWorld::updateParticles()
+{
+ LLViewerPartSim::getInstance()->updateSimulation();
+}
+
+void LLWorld::updateClouds(const F32 dt)
+{
+ static LLFastTimer::DeclareTimer ftm("World Clouds");
+ LLFastTimer t(ftm);
+
+ if ( gSavedSettings.getBOOL("FreezeTime") )
+ {
+ // don't move clouds in snapshot mode
+ return;
+ }
+
+ if (
+ mClassicCloudsEnabled !=
+ gSavedSettings.getBOOL("SkyUseClassicClouds") )
+ {
+ // The classic cloud toggle has been flipped
+ // gotta update all of the cloud layers
+ mClassicCloudsEnabled =
+ gSavedSettings.getBOOL("SkyUseClassicClouds");
+
+ if ( !mClassicCloudsEnabled && mActiveRegionList.size() )
+ {
+ // We've transitioned to having classic clouds disabled
+ // reset all cloud layers.
+ for (
+ region_list_t::iterator iter = mActiveRegionList.begin();
+ iter != mActiveRegionList.end();
+ ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ regionp->mCloudLayer.reset();
+ }
+
+ return;
+ }
+ }
+ else if ( !mClassicCloudsEnabled ) return;
+
+ if (mActiveRegionList.size())
+ {
+ for (region_list_t::iterator iter = mActiveRegionList.begin();
+ iter != mActiveRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ regionp->mCloudLayer.updatePuffs(dt);
+ }
+
+ // Reshuffle who owns which puffs
+ for (region_list_t::iterator iter = mActiveRegionList.begin();
+ iter != mActiveRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ regionp->mCloudLayer.updatePuffOwnership();
+ }
+
+ // Add new puffs
+ for (region_list_t::iterator iter = mActiveRegionList.begin();
+ iter != mActiveRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ regionp->mCloudLayer.updatePuffCount();
+ }
+ }
+}
+
+LLCloudGroup* LLWorld::findCloudGroup(const LLCloudPuff &puff)
+{
+ if (mActiveRegionList.size())
+ {
+ // Update all the cloud puff positions, and timer based stuff
+ // such as death decay
+ for (region_list_t::iterator iter = mActiveRegionList.begin();
+ iter != mActiveRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ LLCloudGroup *groupp = regionp->mCloudLayer.findCloudGroup(puff);
+ if (groupp)
+ {
+ return groupp;
+ }
+ }
+ }
+ return NULL;
+}
+
+
+void LLWorld::renderPropertyLines()
+{
+ S32 region_count = 0;
+ S32 vertex_count = 0;
+
+ for (region_list_t::iterator iter = mVisibleRegionList.begin();
+ iter != mVisibleRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ region_count++;
+ vertex_count += regionp->renderPropertyLines();
+ }
+}
+
+
+void LLWorld::updateNetStats()
+{
+ F32 bits = 0.f;
+ U32 packets = 0;
+
+ for (region_list_t::iterator iter = mActiveRegionList.begin();
+ iter != mActiveRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ regionp->updateNetStats();
+ bits += regionp->mBitStat.getCurrent();
+ packets += llfloor( regionp->mPacketsStat.getCurrent() );
+ }
+
+ S32 packets_in = gMessageSystem->mPacketsIn - mLastPacketsIn;
+ S32 packets_out = gMessageSystem->mPacketsOut - mLastPacketsOut;
+ S32 packets_lost = gMessageSystem->mDroppedPackets - mLastPacketsLost;
+
+ S32 actual_in_bits = gMessageSystem->mPacketRing.getAndResetActualInBits();
+ S32 actual_out_bits = gMessageSystem->mPacketRing.getAndResetActualOutBits();
+ LLViewerStats::getInstance()->mActualInKBitStat.addValue(actual_in_bits/1024.f);
+ LLViewerStats::getInstance()->mActualOutKBitStat.addValue(actual_out_bits/1024.f);
+ LLViewerStats::getInstance()->mKBitStat.addValue(bits/1024.f);
+ LLViewerStats::getInstance()->mPacketsInStat.addValue(packets_in);
+ LLViewerStats::getInstance()->mPacketsOutStat.addValue(packets_out);
+ LLViewerStats::getInstance()->mPacketsLostStat.addValue(gMessageSystem->mDroppedPackets);
+ if (packets_in)
+ {
+ LLViewerStats::getInstance()->mPacketsLostPercentStat.addValue(100.f*((F32)packets_lost/(F32)packets_in));
+ }
+ else
+ {
+ LLViewerStats::getInstance()->mPacketsLostPercentStat.addValue(0.f);
+ }
+
+ mLastPacketsIn = gMessageSystem->mPacketsIn;
+ mLastPacketsOut = gMessageSystem->mPacketsOut;
+ mLastPacketsLost = gMessageSystem->mDroppedPackets;
+}
+
+
+void LLWorld::printPacketsLost()
+{
+ llinfos << "Simulators:" << llendl;
+ llinfos << "----------" << llendl;
+
+ LLCircuitData *cdp = NULL;
+ for (region_list_t::iterator iter = mActiveRegionList.begin();
+ iter != mActiveRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ cdp = gMessageSystem->mCircuitInfo.findCircuit(regionp->getHost());
+ if (cdp)
+ {
+ LLVector3d range = regionp->getCenterGlobal() - gAgent.getPositionGlobal();
+
+ llinfos << regionp->getHost() << ", range: " << range.length()
+ << " packets lost: " << cdp->getPacketsLost() << llendl;
+ }
+ }
+}
+
+void LLWorld::processCoarseUpdate(LLMessageSystem* msg, void** user_data)
+{
+ LLViewerRegion* region = LLWorld::getInstance()->getRegion(msg->getSender());
+ if( region )
+ {
+ region->updateCoarseLocations(msg);
+ }
+}
+
+F32 LLWorld::getLandFarClip() const
+{
+ return mLandFarClip;
+}
+
+void LLWorld::setLandFarClip(const F32 far_clip)
+{
+ static S32 const rwidth = (S32)REGION_WIDTH_U32;
+ S32 const n1 = (llceil(mLandFarClip) - 1) / rwidth;
+ S32 const n2 = (llceil(far_clip) - 1) / rwidth;
+ bool need_water_objects_update = n1 != n2;
+
+ mLandFarClip = far_clip;
+
+ if (need_water_objects_update)
+ {
+ updateWaterObjects();
+ }
+}
+
+// Some region that we're connected to, but not the one we're in, gave us
+// a (possibly) new water height. Update it in our local copy.
+void LLWorld::waterHeightRegionInfo(std::string const& sim_name, F32 water_height)
+{
+ for (region_list_t::iterator iter = mRegionList.begin(); iter != mRegionList.end(); ++iter)
+ {
+ if ((*iter)->getName() == sim_name)
+ {
+ (*iter)->setWaterHeight(water_height);
+ break;
+ }
+ }
+}
+
+void LLWorld::updateWaterObjects()
+{
+ if (!gAgent.getRegion())
+ {
+ return;
+ }
+ if (mRegionList.empty())
+ {
+ llwarns << "No regions!" << llendl;
+ return;
+ }
+
+ // First, determine the min and max "box" of water objects
+ S32 min_x = 0;
+ S32 min_y = 0;
+ S32 max_x = 0;
+ S32 max_y = 0;
+ U32 region_x, region_y;
+
+ S32 rwidth = 256;
+
+ // We only want to fill in water for stuff that's near us, say, within 256 or 512m
+ S32 range = LLViewerCamera::getInstance()->getFar() > 256.f ? 512 : 256;
+
+ LLViewerRegion* regionp = gAgent.getRegion();
+ from_region_handle(regionp->getHandle(), &region_x, &region_y);
+
+ min_x = (S32)region_x - range;
+ min_y = (S32)region_y - range;
+ max_x = (S32)region_x + range;
+ max_y = (S32)region_y + range;
+
+ F32 height = 0.f;
+
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ LLVOWater* waterp = regionp->getLand().getWaterObj();
+ height += regionp->getWaterHeight();
+ if (waterp)
+ {
+ gObjectList.updateActive(waterp);
+ }
+ }
+
+ for (std::list<LLVOWater*>::iterator iter = mHoleWaterObjects.begin();
+ iter != mHoleWaterObjects.end(); ++ iter)
+ {
+ LLVOWater* waterp = *iter;
+ gObjectList.killObject(waterp);
+ }
+ mHoleWaterObjects.clear();
+
+ // Now, get a list of the holes
+ S32 x, y;
+ for (x = min_x; x <= max_x; x += rwidth)
+ {
+ for (y = min_y; y <= max_y; y += rwidth)
+ {
+ U64 region_handle = to_region_handle(x, y);
+ if (!getRegionFromHandle(region_handle))
+ {
+ LLVOWater* waterp = (LLVOWater *)gObjectList.createObjectViewer(LLViewerObject::LL_VO_WATER, gAgent.getRegion());
+ waterp->setUseTexture(FALSE);
+ waterp->setPositionGlobal(LLVector3d(x + rwidth/2,
+ y + rwidth/2,
+ 256.f+DEFAULT_WATER_HEIGHT));
+ waterp->setScale(LLVector3((F32)rwidth, (F32)rwidth, 512.f));
+ gPipeline.createObject(waterp);
+ mHoleWaterObjects.push_back(waterp);
+ }
+ }
+ }
+
+ // Update edge water objects
+ S32 wx, wy;
+ S32 center_x, center_y;
+ wx = (max_x - min_x) + rwidth;
+ wy = (max_y - min_y) + rwidth;
+ center_x = min_x + (wx >> 1);
+ center_y = min_y + (wy >> 1);
+
+ S32 add_boundary[4] = {
+ 512 - (max_x - region_x),
+ 512 - (max_y - region_y),
+ 512 - (region_x - min_x),
+ 512 - (region_y - min_y) };
+
+ S32 dir;
+ for (dir = 0; dir < 8; dir++)
+ {
+ S32 dim[2] = { 0 };
+ switch (gDirAxes[dir][0])
+ {
+ case -1: dim[0] = add_boundary[2]; break;
+ case 0: dim[0] = wx; break;
+ default: dim[0] = add_boundary[0]; break;
+ }
+ switch (gDirAxes[dir][1])
+ {
+ case -1: dim[1] = add_boundary[3]; break;
+ case 0: dim[1] = wy; break;
+ default: dim[1] = add_boundary[1]; break;
+ }
+
+ // Resize and reshape the water objects
+ const S32 water_center_x = center_x + llround((wx + dim[0]) * 0.5f * gDirAxes[dir][0]);
+ const S32 water_center_y = center_y + llround((wy + dim[1]) * 0.5f * gDirAxes[dir][1]);
+
+ LLVOWater* waterp = mEdgeWaterObjects[dir];
+ if (!waterp || waterp->isDead())
+ {
+ // The edge water objects can be dead because they're attached to the region that the
+ // agent was in when they were originally created.
+ mEdgeWaterObjects[dir] = (LLVOWater *)gObjectList.createObjectViewer(LLViewerObject::LL_VO_VOID_WATER,
+ gAgent.getRegion());
+ waterp = mEdgeWaterObjects[dir];
+ waterp->setUseTexture(FALSE);
+ waterp->setIsEdgePatch(TRUE);
+ gPipeline.createObject(waterp);
+ }
+
+ waterp->setRegion(gAgent.getRegion());
+ LLVector3d water_pos(water_center_x, water_center_y,
+ DEFAULT_WATER_HEIGHT+256.f);
+ LLVector3 water_scale((F32) dim[0], (F32) dim[1], 512.f);
+
+ //stretch out to horizon
+ water_scale.mV[0] += fabsf(2048.f * gDirAxes[dir][0]);
+ water_scale.mV[1] += fabsf(2048.f * gDirAxes[dir][1]);
+
+ water_pos.mdV[0] += 1024.f * gDirAxes[dir][0];
+ water_pos.mdV[1] += 1024.f * gDirAxes[dir][1];
+
+ waterp->setPositionGlobal(water_pos);
+ waterp->setScale(water_scale);
+
+ gObjectList.updateActive(waterp);
+ }
+}
+
+
+void LLWorld::shiftRegions(const LLVector3& offset)
+{
+ for (region_list_t::const_iterator i = getRegionList().begin(); i != getRegionList().end(); ++i)
+ {
+ LLViewerRegion* region = *i;
+ region->updateRenderMatrix();
+ }
+
+ LLViewerPartSim::getInstance()->shift(offset);
+}
+
+LLViewerTexture* LLWorld::getDefaultWaterTexture()
+{
+ return mDefaultWaterTexturep;
+}
+
+void LLWorld::setSpaceTimeUSec(const U64 space_time_usec)
+{
+ mSpaceTimeUSec = space_time_usec;
+}
+
+U64 LLWorld::getSpaceTimeUSec() const
+{
+ return mSpaceTimeUSec;
+}
+
+void LLWorld::requestCacheMisses()
+{
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ regionp->requestCacheMisses();
+ }
+}
+
+void LLWorld::getInfo(LLSD& info)
+{
+ LLSD region_info;
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ regionp->getInfo(region_info);
+ info["World"].append(region_info);
+ }
+}
+
+void LLWorld::disconnectRegions()
+{
+ LLMessageSystem* msg = gMessageSystem;
+ for (region_list_t::iterator iter = mRegionList.begin();
+ iter != mRegionList.end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ if (regionp == gAgent.getRegion())
+ {
+ // Skip the main agent
+ continue;
+ }
+
+ llinfos << "Sending AgentQuitCopy to: " << regionp->getHost() << llendl;
+ msg->newMessageFast(_PREHASH_AgentQuitCopy);
+ msg->nextBlockFast(_PREHASH_AgentData);
+ msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
+ msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ msg->nextBlockFast(_PREHASH_FuseBlock);
+ msg->addU32Fast(_PREHASH_ViewerCircuitCode, gMessageSystem->mOurCircuitCode);
+ msg->sendMessage(regionp->getHost());
+ }
+}
+
+static LLFastTimer::DeclareTimer FTM_ENABLE_SIMULATOR("Enable Sim");
+
+void process_enable_simulator(LLMessageSystem *msg, void **user_data)
+{
+ LLFastTimer t(FTM_ENABLE_SIMULATOR);
+ // enable the appropriate circuit for this simulator and
+ // add its values into the gSimulator structure
+ U64 handle;
+ U32 ip_u32;
+ U16 port;
+
+ msg->getU64Fast(_PREHASH_SimulatorInfo, _PREHASH_Handle, handle);
+ msg->getIPAddrFast(_PREHASH_SimulatorInfo, _PREHASH_IP, ip_u32);
+ msg->getIPPortFast(_PREHASH_SimulatorInfo, _PREHASH_Port, port);
+
+ // which simulator should we modify?
+ LLHost sim(ip_u32, port);
+
+ // Viewer trusts the simulator.
+ msg->enableCircuit(sim, TRUE);
+ LLWorld::getInstance()->addRegion(handle, sim);
+
+ // give the simulator a message it can use to get ip and port
+ llinfos << "simulator_enable() Enabling " << sim << " with code " << msg->getOurCircuitCode() << llendl;
+ msg->newMessageFast(_PREHASH_UseCircuitCode);
+ msg->nextBlockFast(_PREHASH_CircuitCode);
+ msg->addU32Fast(_PREHASH_Code, msg->getOurCircuitCode());
+ msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
+ msg->addUUIDFast(_PREHASH_ID, gAgent.getID());
+ msg->sendReliable(sim);
+}
+
+class LLEstablishAgentCommunication : public LLHTTPNode
+{
+ LOG_CLASS(LLEstablishAgentCommunication);
+public:
+ virtual void describe(Description& desc) const
+ {
+ desc.shortInfo("seed capability info for a region");
+ desc.postAPI();
+ desc.input(
+ "{ seed-capability: ..., sim-ip: ..., sim-port }");
+ desc.source(__FILE__, __LINE__);
+ }
+
+ virtual void post(ResponsePtr response, const LLSD& context, const LLSD& input) const
+ {
+ if (!input["body"].has("agent-id") ||
+ !input["body"].has("sim-ip-and-port") ||
+ !input["body"].has("seed-capability"))
+ {
+ llwarns << "invalid parameters" << llendl;
+ return;
+ }
+
+ LLHost sim(input["body"]["sim-ip-and-port"].asString());
+
+ LLViewerRegion* regionp = LLWorld::getInstance()->getRegion(sim);
+ if (!regionp)
+ {
+ llwarns << "Got EstablishAgentCommunication for unknown region "
+ << sim << llendl;
+ return;
+ }
+ regionp->setSeedCapability(input["body"]["seed-capability"]);
+ }
+};
+
+// disable the circuit to this simulator
+// Called in response to "DisableSimulator" message.
+void process_disable_simulator(LLMessageSystem *mesgsys, void **user_data)
+{
+ LLHost host = mesgsys->getSender();
+
+ //llinfos << "Disabling simulator with message from " << host << llendl;
+ LLWorld::getInstance()->removeRegion(host);
+
+ mesgsys->disableCircuit(host);
+}
+
+
+void process_region_handshake(LLMessageSystem* msg, void** user_data)
+{
+ LLHost host = msg->getSender();
+ LLViewerRegion* regionp = LLWorld::getInstance()->getRegion(host);
+ if (!regionp)
+ {
+ llwarns << "Got region handshake for unknown region "
+ << host << llendl;
+ return;
+ }
+
+ regionp->unpackRegionHandshake();
+}
+
+
+void send_agent_pause()
+{
+ // *NOTE:Mani Pausing the mainloop timeout. Otherwise a long modal event may cause
+ // the thread monitor to timeout.
+ LLAppViewer::instance()->pauseMainloopTimeout();
+
+ // Note: used to check for LLWorld initialization before it became a singleton.
+ // Rather than just remove this check I'm changing it to assure that the message
+ // system has been initialized. -MG
+ if (!gMessageSystem)
+ {
+ return;
+ }
+
+ gMessageSystem->newMessageFast(_PREHASH_AgentPause);
+ gMessageSystem->nextBlockFast(_PREHASH_AgentData);
+ gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgentID);
+ gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgentSessionID);
+
+ gAgentPauseSerialNum++;
+ gMessageSystem->addU32Fast(_PREHASH_SerialNum, gAgentPauseSerialNum);
+
+ for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
+ iter != LLWorld::getInstance()->getRegionList().end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ gMessageSystem->sendReliable(regionp->getHost());
+ }
+
+ gObjectList.mWasPaused = TRUE;
+}
+
+
+void send_agent_resume()
+{
+ // Note: used to check for LLWorld initialization before it became a singleton.
+ // Rather than just remove this check I'm changing it to assure that the message
+ // system has been initialized. -MG
+ if (!gMessageSystem)
+ {
+ return;
+ }
+
+ gMessageSystem->newMessageFast(_PREHASH_AgentResume);
+ gMessageSystem->nextBlockFast(_PREHASH_AgentData);
+ gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgentID);
+ gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgentSessionID);
+
+ gAgentPauseSerialNum++;
+ gMessageSystem->addU32Fast(_PREHASH_SerialNum, gAgentPauseSerialNum);
+
+
+ for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
+ iter != LLWorld::getInstance()->getRegionList().end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ gMessageSystem->sendReliable(regionp->getHost());
+ }
+
+ // Reset the FPS counter to avoid an invalid fps
+ LLViewerStats::getInstance()->mFPSStat.start();
+
+ LLAppViewer::instance()->resumeMainloopTimeout();
+}
+
+static LLVector3d unpackLocalToGlobalPosition(U32 compact_local, const LLVector3d& region_origin)
+{
+ LLVector3d pos_global;
+ LLVector3 pos_local;
+ U8 bits;
+
+ bits = compact_local & 0xFF;
+ pos_local.mV[VZ] = F32(bits) * 4.f;
+ compact_local >>= 8;
+
+ bits = compact_local & 0xFF;
+ pos_local.mV[VY] = (F32)bits;
+ compact_local >>= 8;
+
+ bits = compact_local & 0xFF;
+ pos_local.mV[VX] = (F32)bits;
+
+ pos_global.setVec( pos_local );
+ pos_global += region_origin;
+ return pos_global;
+}
+
+void LLWorld::getAvatars(uuid_vec_t* avatar_ids, std::vector<LLVector3d>* positions, const LLVector3d& relative_to, F32 radius) const
+{
+ if(avatar_ids != NULL)
+ {
+ avatar_ids->clear();
+ }
+ if(positions != NULL)
+ {
+ positions->clear();
+ }
+ for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
+ iter != LLWorld::getInstance()->getRegionList().end(); ++iter)
+ {
+ LLViewerRegion* regionp = *iter;
+ const LLVector3d& origin_global = regionp->getOriginGlobal();
+ S32 count = regionp->mMapAvatars.count();
+ for (S32 i = 0; i < count; i++)
+ {
+ LLVector3d pos_global = unpackLocalToGlobalPosition(regionp->mMapAvatars.get(i), origin_global);
+ if(dist_vec(pos_global, relative_to) <= radius)
+ {
+ if(positions != NULL)
+ {
+ positions->push_back(pos_global);
+ }
+ if(avatar_ids != NULL)
+ {
+ avatar_ids->push_back(regionp->mMapAvatarIDs.get(i));
+ }
+ }
+ }
+ }
+ // retrieve the list of close avatars from viewer objects as well
+ // for when we are above 1000m, only do this when we are retrieving
+ // uuid's too as there could be duplicates
+ if(avatar_ids != NULL)
+ {
+ for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
+ iter != LLCharacter::sInstances.end(); ++iter)
+ {
+ LLVOAvatar* pVOAvatar = (LLVOAvatar*) *iter;
+ if(pVOAvatar->isDead() || pVOAvatar->isSelf())
+ continue;
+ LLUUID uuid = pVOAvatar->getID();
+ if(uuid.isNull())
+ continue;
+ LLVector3d pos_global = pVOAvatar->getPositionGlobal();
+ if(dist_vec(pos_global, relative_to) <= radius)
+ {
+ bool found = false;
+ uuid_vec_t::iterator sel_iter = avatar_ids->begin();
+ for (; sel_iter != avatar_ids->end(); sel_iter++)
+ {
+ if(*sel_iter == uuid)
+ {
+ found = true;
+ break;
+ }
+ }
+ if(!found)
+ {
+ if(positions != NULL)
+ positions->push_back(pos_global);
+ avatar_ids->push_back(uuid);
+ }
+ }
+ }
+ }
+}
+
+
+LLHTTPRegistration<LLEstablishAgentCommunication>
+ gHTTPRegistrationEstablishAgentCommunication(
+ "/message/EstablishAgentCommunication");
diff --git a/indra/newview/pipeline.cpp b/indra/newview/pipeline.cpp
index 99feb9a061..24486a7411 100644..100755
--- a/indra/newview/pipeline.cpp
+++ b/indra/newview/pipeline.cpp
@@ -67,6 +67,7 @@
#include "llhudnametag.h"
#include "llhudtext.h"
#include "lllightconstants.h"
+#include "llmeshrepository.h"
#include "llresmgr.h"
#include "llselectmgr.h"
#include "llsky.h"
@@ -74,6 +75,7 @@
#include "lltool.h"
#include "lltoolmgr.h"
#include "llviewercamera.h"
+#include "llviewermediafocus.h"
#include "llviewertexturelist.h"
#include "llviewerobject.h"
#include "llviewerobjectlist.h"
@@ -100,8 +102,29 @@
#include "llspatialpartition.h"
#include "llmutelist.h"
#include "lltoolpie.h"
+#include "llcurl.h"
+void check_stack_depth(S32 stack_depth)
+{
+ if (gDebugGL || gDebugSession)
+ {
+ GLint depth;
+ glGetIntegerv(GL_MODELVIEW_STACK_DEPTH, &depth);
+ if (depth != stack_depth)
+ {
+ if (gDebugSession)
+ {
+ ll_fail("GL matrix stack corrupted.");
+ }
+ else
+ {
+ llerrs << "GL matrix stack corrupted!" << llendl;
+ }
+ }
+ }
+}
+
#ifdef _DEBUG
// Debug indices is disabled for now for debug performance - djs 4/24/02
//#define DEBUG_INDICES
@@ -169,19 +192,20 @@ std::string gPoolNames[] =
// Correspond to LLDrawpool enum render type
"NONE",
"POOL_SIMPLE",
- "POOL_TERRAIN",
+ "POOL_GROUND",
+ "POOL_FULLBRIGHT",
"POOL_BUMP",
- "POOL_TREE",
+ "POOL_TERRAIN,"
"POOL_SKY",
"POOL_WL_SKY",
- "POOL_GROUND",
+ "POOL_TREE",
+ "POOL_GRASS",
"POOL_INVISIBLE",
"POOL_AVATAR",
+ "POOL_VOIDWATER",
"POOL_WATER",
- "POOL_GRASS",
- "POOL_FULLBRIGHT",
"POOL_GLOW",
- "POOL_ALPHA",
+ "POOL_ALPHA"
};
void drawBox(const LLVector3& c, const LLVector3& r);
@@ -267,6 +291,8 @@ BOOL LLPipeline::sAutoMaskAlphaDeferred = TRUE;
BOOL LLPipeline::sAutoMaskAlphaNonDeferred = FALSE;
BOOL LLPipeline::sDisableShaders = FALSE;
BOOL LLPipeline::sRenderBump = TRUE;
+BOOL LLPipeline::sBakeSunlight = FALSE;
+BOOL LLPipeline::sNoAlpha = FALSE;
BOOL LLPipeline::sUseTriStrips = TRUE;
BOOL LLPipeline::sUseFarClip = TRUE;
BOOL LLPipeline::sShadowRender = FALSE;
@@ -280,7 +306,6 @@ BOOL LLPipeline::sRenderFrameTest = FALSE;
BOOL LLPipeline::sRenderAttachedLights = TRUE;
BOOL LLPipeline::sRenderAttachedParticles = TRUE;
BOOL LLPipeline::sRenderDeferred = FALSE;
-BOOL LLPipeline::sAllowRebuildPriorityGroup = FALSE ;
S32 LLPipeline::sVisibleLightCount = 0;
F32 LLPipeline::sMinRenderSize = 0.f;
@@ -327,6 +352,8 @@ LLPipeline::LLPipeline() :
mRenderDebugFeatureMask(0),
mRenderDebugMask(0),
mOldRenderDebugMask(0),
+ mGroupQ1Locked(false),
+ mGroupQ2Locked(false),
mLastRebuildPool(NULL),
mAlphaPool(NULL),
mSkyPool(NULL),
@@ -358,6 +385,7 @@ void LLPipeline::init()
sRenderBump = gSavedSettings.getBOOL("RenderObjectBump");
sUseTriStrips = gSavedSettings.getBOOL("RenderUseTriStrips");
LLVertexBuffer::sUseStreamDraw = gSavedSettings.getBOOL("RenderUseStreamVBO");
+ LLVertexBuffer::sPreferStreamDraw = gSavedSettings.getBOOL("RenderPreferStreamDraw");
sRenderAttachedLights = gSavedSettings.getBOOL("RenderAttachedLights");
sRenderAttachedParticles = gSavedSettings.getBOOL("RenderAttachedParticles");
@@ -392,6 +420,14 @@ void LLPipeline::init()
toggleRenderType(RENDER_TYPE_GROUND);
}
+ // make sure RenderPerformanceTest persists (hackity hack hack)
+ // disables non-object rendering (UI, sky, water, etc)
+ if (gSavedSettings.getBOOL("RenderPerformanceTest"))
+ {
+ gSavedSettings.setBOOL("RenderPerformanceTest", FALSE);
+ gSavedSettings.setBOOL("RenderPerformanceTest", TRUE);
+ }
+
mOldRenderDebugMask = mRenderDebugMask;
mBackfaceCull = TRUE;
@@ -525,6 +561,22 @@ void LLPipeline::resizeScreenTexture()
}
}
+void LLPipeline::allocatePhysicsBuffer()
+{
+ GLuint resX = gViewerWindow->getWorldViewWidthRaw();
+ GLuint resY = gViewerWindow->getWorldViewHeightRaw();
+
+ if (mPhysicsDisplay.getWidth() != resX || mPhysicsDisplay.getHeight() != resY)
+ {
+ mPhysicsDisplay.allocate(resX, resY, GL_RGBA, TRUE, FALSE, LLTexUnit::TT_RECT_TEXTURE, FALSE);
+ if (mSampleBuffer.getWidth() == mPhysicsDisplay.getWidth() &&
+ mSampleBuffer.getHeight() == mPhysicsDisplay.getHeight())
+ {
+ mPhysicsDisplay.setSampleBuffer(&mSampleBuffer);
+ }
+ }
+}
+
void LLPipeline::allocateScreenBuffer(U32 resX, U32 resY)
{
// remember these dimensions
@@ -533,6 +585,11 @@ void LLPipeline::allocateScreenBuffer(U32 resX, U32 resY)
//never use more than 4 samples for render targets
U32 samples = llmin(gSavedSettings.getU32("RenderFSAASamples"), (U32) 4);
+ if (gGLManager.mIsATI)
+ { //disable multisampling of render targets where ATI is involved
+ samples = 0;
+ }
+
U32 res_mod = gSavedSettings.getU32("RenderResolutionDivisor");
if (res_mod > 1 && res_mod < resX && res_mod < resY)
@@ -548,6 +605,10 @@ void LLPipeline::allocateScreenBuffer(U32 resX, U32 resY)
if (LLPipeline::sRenderDeferred)
{
+ S32 shadow_detail = gSavedSettings.getS32("RenderShadowDetail");
+ BOOL ssao = gSavedSettings.getBOOL("RenderDeferredSSAO");
+ bool gi = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_DEFERRED);
+
//allocate deferred rendering color buffers
mDeferredScreen.allocate(resX, resY, GL_RGBA, TRUE, TRUE, LLTexUnit::TT_RECT_TEXTURE, FALSE);
mDeferredDepth.allocate(resX, resY, 0, TRUE, FALSE, LLTexUnit::TT_RECT_TEXTURE, FALSE);
@@ -556,14 +617,40 @@ void LLPipeline::allocateScreenBuffer(U32 resX, U32 resY)
mScreen.allocate(resX, resY, GL_RGBA, FALSE, FALSE, LLTexUnit::TT_RECT_TEXTURE, FALSE);
mEdgeMap.allocate(resX, resY, GL_ALPHA, FALSE, FALSE, LLTexUnit::TT_RECT_TEXTURE, FALSE);
- for (U32 i = 0; i < 3; i++)
+ if (shadow_detail > 0 || ssao)
+ { //only need mDeferredLight[0] for shadows OR ssao
+ mDeferredLight[0].allocate(resX, resY, GL_RGBA, FALSE, FALSE, LLTexUnit::TT_RECT_TEXTURE);
+ }
+ else
{
- mDeferredLight[i].allocate(resX, resY, GL_RGBA, FALSE, FALSE, LLTexUnit::TT_RECT_TEXTURE);
+ mDeferredLight[0].release();
}
- for (U32 i = 0; i < 2; i++)
+ if (ssao)
+ { //only need mDeferredLight[1] for ssao
+ mDeferredLight[1].allocate(resX, resY, GL_RGBA, FALSE, FALSE, LLTexUnit::TT_RECT_TEXTURE);
+ }
+ else
{
- mGIMapPost[i].allocate(resX,resY, GL_RGB, FALSE, FALSE, LLTexUnit::TT_RECT_TEXTURE);
+ mDeferredLight[1].release();
+ }
+
+ if (gi)
+ { //only need mDeferredLight[2] and mGIMapPost for gi
+ mDeferredLight[2].allocate(resX, resY, GL_RGBA, FALSE, FALSE, LLTexUnit::TT_RECT_TEXTURE);
+ for (U32 i = 0; i < 2; i++)
+ {
+ mGIMapPost[i].allocate(resX,resY, GL_RGB, FALSE, FALSE, LLTexUnit::TT_RECT_TEXTURE);
+ }
+ }
+ else
+ {
+ mDeferredLight[2].release();
+
+ for (U32 i = 0; i < 2; i++)
+ {
+ mGIMapPost[i].release();
+ }
}
F32 scale = gSavedSettings.getF32("RenderShadowResolutionScale");
@@ -571,18 +658,37 @@ void LLPipeline::allocateScreenBuffer(U32 resX, U32 resY)
//HACK: make alpha masking work on ATI depth shadows (work around for ATI driver bug)
U32 shadow_fmt = gGLManager.mIsATI ? GL_ALPHA : 0;
- for (U32 i = 0; i < 4; i++)
+ if (shadow_detail > 0)
+ { //allocate 4 sun shadow maps
+ for (U32 i = 0; i < 4; i++)
+ {
+ mShadow[i].allocate(U32(resX*scale),U32(resY*scale), shadow_fmt, TRUE, FALSE, LLTexUnit::TT_RECT_TEXTURE);
+ }
+ }
+ else
{
- mShadow[i].allocate(U32(resX*scale),U32(resY*scale), shadow_fmt, TRUE, FALSE, LLTexUnit::TT_RECT_TEXTURE);
+ for (U32 i = 0; i < 4; i++)
+ {
+ mShadow[i].release();
+ }
}
-
U32 width = nhpo2(U32(resX*scale))/2;
U32 height = width;
- for (U32 i = 4; i < 6; i++)
+ if (shadow_detail > 1)
+ { //allocate two spot shadow maps
+ for (U32 i = 4; i < 6; i++)
+ {
+ mShadow[i].allocate(width, height, shadow_fmt, TRUE, FALSE);
+ }
+ }
+ else
{
- mShadow[i].allocate(width, height, shadow_fmt, TRUE, FALSE);
+ for (U32 i = 4; i < 6; i++)
+ {
+ mShadow[i].release();
+ }
}
width = nhpo2(resX)/2;
@@ -591,30 +697,55 @@ void LLPipeline::allocateScreenBuffer(U32 resX, U32 resY)
}
else
{
+ for (U32 i = 0; i < 3; i++)
+ {
+ mDeferredLight[i].release();
+ }
+ for (U32 i = 0; i < 2; i++)
+ {
+ mGIMapPost[i].release();
+ }
+ for (U32 i = 0; i < 6; i++)
+ {
+ mShadow[i].release();
+ }
+ mScreen.release();
+ mDeferredScreen.release(); //make sure to release any render targets that share a depth buffer with mDeferredScreen first
+ mDeferredDepth.release();
+ mEdgeMap.release();
+ mLuminanceMap.release();
+
mScreen.allocate(resX, resY, GL_RGBA, TRUE, TRUE, LLTexUnit::TT_RECT_TEXTURE, FALSE);
}
-
- if (LLRenderTarget::sUseFBO && gGLManager.mHasFramebufferMultisample && samples > 1)
- {
+ if (LLRenderTarget::sUseFBO && samples > 1)
+ {
mSampleBuffer.allocate(resX,resY,GL_RGBA,TRUE,TRUE,LLTexUnit::TT_RECT_TEXTURE,FALSE,samples);
if (LLPipeline::sRenderDeferred)
{
addDeferredAttachments(mSampleBuffer);
mDeferredScreen.setSampleBuffer(&mSampleBuffer);
+ mEdgeMap.setSampleBuffer(&mSampleBuffer);
}
mScreen.setSampleBuffer(&mSampleBuffer);
stop_glerror();
}
+ else
+ {
+ mSampleBuffer.release();
+ }
if (LLPipeline::sRenderDeferred)
{ //share depth buffer between deferred targets
mDeferredScreen.shareDepthBuffer(mScreen);
for (U32 i = 0; i < 3; i++)
{ //share stencil buffer with screen space lightmap to stencil out sky
- mDeferredScreen.shareDepthBuffer(mDeferredLight[i]);
+ if (mDeferredLight[i].getTexture(0))
+ {
+ mDeferredScreen.shareDepthBuffer(mDeferredLight[i]);
+ }
}
}
@@ -635,7 +766,11 @@ void LLPipeline::updateRenderDeferred()
gSavedSettings.getBOOL("WindLightUseAtmosShaders")) ? TRUE : FALSE) &&
!gUseWireframe;
- sRenderDeferred = deferred;
+ sRenderDeferred = deferred;
+ if (deferred)
+ { //must render glow when rendering deferred since post effect pass is needed to present any lighting at all
+ sRenderGlow = TRUE;
+ }
}
void LLPipeline::releaseGLBuffers()
@@ -663,8 +798,9 @@ void LLPipeline::releaseGLBuffers()
mWaterRef.release();
mWaterDis.release();
mScreen.release();
+ mPhysicsDisplay.release();
mUIScreen.release();
- mSampleBuffer.releaseSampleBuffer();
+ mSampleBuffer.release();
mDeferredScreen.release();
mDeferredDepth.release();
for (U32 i = 0; i < 3; i++)
@@ -689,6 +825,7 @@ void LLPipeline::releaseGLBuffers()
mGlow[i].release();
}
+ gBumpImageList.destroyGL();
LLVOAvatar::resetImpostors();
}
@@ -727,7 +864,6 @@ void LLPipeline::createGLBuffers()
allocateScreenBuffer(resX,resY);
mScreenWidth = 0;
mScreenHeight = 0;
-
}
if (sRenderDeferred)
@@ -812,6 +948,8 @@ void LLPipeline::createGLBuffers()
addDeferredAttachments(mGIMap);
}
}
+
+ gBumpImageList.restoreGL();
}
void LLPipeline::restoreGL()
@@ -871,7 +1009,7 @@ BOOL LLPipeline::canUseWindLightShadersOnObjects() const
BOOL LLPipeline::canUseAntiAliasing() const
{
- return TRUE; //(gSavedSettings.getBOOL("RenderUseFBO"));
+ return TRUE;
}
void LLPipeline::unloadShaders()
@@ -909,11 +1047,10 @@ S32 LLPipeline::getMaxLightingDetail() const
S32 LLPipeline::setLightingDetail(S32 level)
{
LLMemType mt_ld(LLMemType::MTYPE_PIPELINE_LIGHTING_DETAIL);
- assertInitialized();
if (level < 0)
{
- if (gSavedSettings.getBOOL("VertexShaderEnable"))
+ if (gSavedSettings.getBOOL("RenderLocalLights"))
{
level = 1;
}
@@ -923,15 +1060,8 @@ S32 LLPipeline::setLightingDetail(S32 level)
}
}
level = llclamp(level, 0, getMaxLightingDetail());
- if (level != mLightingDetail)
- {
- mLightingDetail = level;
-
- if (mVertexShadersLoaded == 1)
- {
- LLViewerShaderMgr::instance()->setShaders();
- }
- }
+ mLightingDetail = level;
+
return mLightingDetail;
}
@@ -1157,9 +1287,15 @@ void LLPipeline::allocDrawable(LLViewerObject *vobj)
}
+static LLFastTimer::DeclareTimer FTM_UNLINK("Unlink");
+static LLFastTimer::DeclareTimer FTM_REMOVE_FROM_MOVE_LIST("Movelist");
+static LLFastTimer::DeclareTimer FTM_REMOVE_FROM_SPATIAL_PARTITION("Spatial Partition");
+static LLFastTimer::DeclareTimer FTM_REMOVE_FROM_LIGHT_SET("Light Set");
+static LLFastTimer::DeclareTimer FTM_REMOVE_FROM_HIGHLIGHT_SET("Highlight Set");
+
void LLPipeline::unlinkDrawable(LLDrawable *drawable)
{
- LLFastTimer t(FTM_PIPELINE);
+ LLFastTimer t(FTM_UNLINK);
assertInitialized();
@@ -1168,6 +1304,7 @@ void LLPipeline::unlinkDrawable(LLDrawable *drawable)
// Based on flags, remove the drawable from the queues that it's on.
if (drawablep->isState(LLDrawable::ON_MOVE_LIST))
{
+ LLFastTimer t(FTM_REMOVE_FROM_MOVE_LIST);
LLDrawable::drawable_vector_t::iterator iter = std::find(mMovedList.begin(), mMovedList.end(), drawablep);
if (iter != mMovedList.end())
{
@@ -1177,6 +1314,7 @@ void LLPipeline::unlinkDrawable(LLDrawable *drawable)
if (drawablep->getSpatialGroup())
{
+ LLFastTimer t(FTM_REMOVE_FROM_SPATIAL_PARTITION);
if (!drawablep->getSpatialGroup()->mSpatialPartition->remove(drawablep, drawablep->getSpatialGroup()))
{
#ifdef LL_RELEASE_FOR_DOWNLOAD
@@ -1187,18 +1325,23 @@ void LLPipeline::unlinkDrawable(LLDrawable *drawable)
}
}
- mLights.erase(drawablep);
- for (light_set_t::iterator iter = mNearbyLights.begin();
- iter != mNearbyLights.end(); iter++)
{
- if (iter->drawable == drawablep)
+ LLFastTimer t(FTM_REMOVE_FROM_LIGHT_SET);
+ mLights.erase(drawablep);
+
+ for (light_set_t::iterator iter = mNearbyLights.begin();
+ iter != mNearbyLights.end(); iter++)
{
- mNearbyLights.erase(iter);
- break;
+ if (iter->drawable == drawablep)
+ {
+ mNearbyLights.erase(iter);
+ break;
+ }
}
}
{
+ LLFastTimer t(FTM_REMOVE_FROM_HIGHLIGHT_SET);
HighlightItem item(drawablep);
mHighlightSet.erase(item);
@@ -1495,11 +1638,214 @@ F32 LLPipeline::calcPixelArea(LLVector3 center, LLVector3 size, LLCamera &camera
return radius*radius * F_PI;
}
+//static
+F32 LLPipeline::calcPixelArea(const LLVector4a& center, const LLVector4a& size, LLCamera &camera)
+{
+ LLVector4a origin;
+ origin.load3(camera.getOrigin().mV);
+
+ LLVector4a lookAt;
+ lookAt.setSub(center, origin);
+ F32 dist = lookAt.getLength3().getF32();
+
+ //ramp down distance for nearby objects
+ //shrink dist by dist/16.
+ if (dist < 16.f)
+ {
+ dist /= 16.f;
+ dist *= dist;
+ dist *= 16.f;
+ }
+
+ //get area of circle around node
+ F32 app_angle = atanf(size.getLength3().getF32()/dist);
+ F32 radius = app_angle*LLDrawable::sCurPixelAngle;
+ return radius*radius * F_PI;
+}
+
void LLPipeline::grabReferences(LLCullResult& result)
{
sCull = &result;
}
+void LLPipeline::clearReferences()
+{
+ sCull = NULL;
+}
+
+void check_references(LLSpatialGroup* group, LLDrawable* drawable)
+{
+ for (LLSpatialGroup::element_iter i = group->getData().begin(); i != group->getData().end(); ++i)
+ {
+ if (drawable == *i)
+ {
+ llerrs << "LLDrawable deleted while actively reference by LLPipeline." << llendl;
+ }
+ }
+}
+
+void check_references(LLDrawable* drawable, LLFace* face)
+{
+ for (S32 i = 0; i < drawable->getNumFaces(); ++i)
+ {
+ if (drawable->getFace(i) == face)
+ {
+ llerrs << "LLFace deleted while actively referenced by LLPipeline." << llendl;
+ }
+ }
+}
+
+void check_references(LLSpatialGroup* group, LLFace* face)
+{
+ for (LLSpatialGroup::element_iter i = group->getData().begin(); i != group->getData().end(); ++i)
+ {
+ LLDrawable* drawable = *i;
+ check_references(drawable, face);
+ }
+}
+
+void LLPipeline::checkReferences(LLFace* face)
+{
+#if 0
+ if (sCull)
+ {
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginVisibleGroups(); iter != sCull->endVisibleGroups(); ++iter)
+ {
+ LLSpatialGroup* group = *iter;
+ check_references(group, face);
+ }
+
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginAlphaGroups(); iter != sCull->endAlphaGroups(); ++iter)
+ {
+ LLSpatialGroup* group = *iter;
+ check_references(group, face);
+ }
+
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginDrawableGroups(); iter != sCull->endDrawableGroups(); ++iter)
+ {
+ LLSpatialGroup* group = *iter;
+ check_references(group, face);
+ }
+
+ for (LLCullResult::drawable_list_t::iterator iter = sCull->beginVisibleList(); iter != sCull->endVisibleList(); ++iter)
+ {
+ LLDrawable* drawable = *iter;
+ check_references(drawable, face);
+ }
+ }
+#endif
+}
+
+void LLPipeline::checkReferences(LLDrawable* drawable)
+{
+#if 0
+ if (sCull)
+ {
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginVisibleGroups(); iter != sCull->endVisibleGroups(); ++iter)
+ {
+ LLSpatialGroup* group = *iter;
+ check_references(group, drawable);
+ }
+
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginAlphaGroups(); iter != sCull->endAlphaGroups(); ++iter)
+ {
+ LLSpatialGroup* group = *iter;
+ check_references(group, drawable);
+ }
+
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginDrawableGroups(); iter != sCull->endDrawableGroups(); ++iter)
+ {
+ LLSpatialGroup* group = *iter;
+ check_references(group, drawable);
+ }
+
+ for (LLCullResult::drawable_list_t::iterator iter = sCull->beginVisibleList(); iter != sCull->endVisibleList(); ++iter)
+ {
+ if (drawable == *iter)
+ {
+ llerrs << "LLDrawable deleted while actively referenced by LLPipeline." << llendl;
+ }
+ }
+ }
+#endif
+}
+
+void check_references(LLSpatialGroup* group, LLDrawInfo* draw_info)
+{
+ for (LLSpatialGroup::draw_map_t::iterator i = group->mDrawMap.begin(); i != group->mDrawMap.end(); ++i)
+ {
+ LLSpatialGroup::drawmap_elem_t& draw_vec = i->second;
+ for (LLSpatialGroup::drawmap_elem_t::iterator j = draw_vec.begin(); j != draw_vec.end(); ++j)
+ {
+ LLDrawInfo* params = *j;
+ if (params == draw_info)
+ {
+ llerrs << "LLDrawInfo deleted while actively referenced by LLPipeline." << llendl;
+ }
+ }
+ }
+}
+
+
+void LLPipeline::checkReferences(LLDrawInfo* draw_info)
+{
+#if 0
+ if (sCull)
+ {
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginVisibleGroups(); iter != sCull->endVisibleGroups(); ++iter)
+ {
+ LLSpatialGroup* group = *iter;
+ check_references(group, draw_info);
+ }
+
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginAlphaGroups(); iter != sCull->endAlphaGroups(); ++iter)
+ {
+ LLSpatialGroup* group = *iter;
+ check_references(group, draw_info);
+ }
+
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginDrawableGroups(); iter != sCull->endDrawableGroups(); ++iter)
+ {
+ LLSpatialGroup* group = *iter;
+ check_references(group, draw_info);
+ }
+ }
+#endif
+}
+
+void LLPipeline::checkReferences(LLSpatialGroup* group)
+{
+#if 0
+ if (sCull)
+ {
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginVisibleGroups(); iter != sCull->endVisibleGroups(); ++iter)
+ {
+ if (group == *iter)
+ {
+ llerrs << "LLSpatialGroup deleted while actively referenced by LLPipeline." << llendl;
+ }
+ }
+
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginAlphaGroups(); iter != sCull->endAlphaGroups(); ++iter)
+ {
+ if (group == *iter)
+ {
+ llerrs << "LLSpatialGroup deleted while actively referenced by LLPipeline." << llendl;
+ }
+ }
+
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginDrawableGroups(); iter != sCull->endDrawableGroups(); ++iter)
+ {
+ if (group == *iter)
+ {
+ llerrs << "LLSpatialGroup deleted while actively referenced by LLPipeline." << llendl;
+ }
+ }
+ }
+#endif
+}
+
+
BOOL LLPipeline::visibleObjectsInFrustum(LLCamera& camera)
{
for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
@@ -1695,7 +2041,7 @@ void LLPipeline::markNotCulled(LLSpatialGroup* group, LLCamera& camera)
}
if (sMinRenderSize > 0.f &&
- llmax(llmax(group->mBounds[1].mV[0], group->mBounds[1].mV[1]), group->mBounds[1].mV[2]) < sMinRenderSize)
+ llmax(llmax(group->mBounds[1][0], group->mBounds[1][1]), group->mBounds[1][2]) < sMinRenderSize)
{
return;
}
@@ -1739,33 +2085,34 @@ void LLPipeline::markOccluder(LLSpatialGroup* group)
void LLPipeline::doOcclusion(LLCamera& camera)
{
- LLVertexBuffer::unbind();
-
- if (hasRenderDebugMask(LLPipeline::RENDER_DEBUG_OCCLUSION))
- {
- gGL.setColorMask(true, false, false, false);
- }
- else
+ if (LLPipeline::sUseOcclusion > 1 && sCull->hasOcclusionGroups())
{
- gGL.setColorMask(false, false);
- }
- LLGLDisable blend(GL_BLEND);
- LLGLDisable test(GL_ALPHA_TEST);
- gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
- LLGLDepthTest depth(GL_TRUE, GL_FALSE);
+ LLVertexBuffer::unbind();
- LLGLDisable cull(GL_CULL_FACE);
- if (LLPipeline::sUseOcclusion > 1)
- {
+ if (hasRenderDebugMask(LLPipeline::RENDER_DEBUG_OCCLUSION))
+ {
+ gGL.setColorMask(true, false, false, false);
+ }
+ else
+ {
+ gGL.setColorMask(false, false);
+ }
+ LLGLDisable blend(GL_BLEND);
+ LLGLDisable test(GL_ALPHA_TEST);
+ gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
+ LLGLDepthTest depth(GL_TRUE, GL_FALSE);
+
+ LLGLDisable cull(GL_CULL_FACE);
+
for (LLCullResult::sg_list_t::iterator iter = sCull->beginOcclusionGroups(); iter != sCull->endOcclusionGroups(); ++iter)
{
LLSpatialGroup* group = *iter;
group->doOcclusion(&camera);
group->clearOcclusionState(LLSpatialGroup::ACTIVE_OCCLUSION);
}
+
+ gGL.setColorMask(true, false);
}
-
- gGL.setColorMask(true, false);
}
BOOL LLPipeline::updateDrawableGeom(LLDrawable* drawablep, BOOL priority)
@@ -1792,17 +2139,14 @@ void LLPipeline::updateGL()
void LLPipeline::rebuildPriorityGroups()
{
- if(!sAllowRebuildPriorityGroup)
- {
- return ;
- }
- sAllowRebuildPriorityGroup = FALSE ;
-
LLTimer update_timer;
LLMemType mt(LLMemType::MTYPE_PIPELINE);
assertInitialized();
+ gMeshRepo.notifyLoadedMeshes();
+
+ mGroupQ1Locked = true;
// Iterate through all drawables on the priority build queue,
for (LLSpatialGroup::sg_vector_t::iterator iter = mGroupQ1.begin();
iter != mGroupQ1.end(); ++iter)
@@ -1813,10 +2157,18 @@ void LLPipeline::rebuildPriorityGroups()
}
mGroupQ1.clear();
+ mGroupQ1Locked = false;
+
}
void LLPipeline::rebuildGroups()
{
+ if (mGroupQ2.empty())
+ {
+ return;
+ }
+
+ mGroupQ2Locked = true;
// Iterate through some drawables on the non-priority build queue
S32 size = (S32) mGroupQ2.size();
S32 min_count = llclamp((S32) ((F32) (size * size)/4096*0.25f), 1, size);
@@ -1826,33 +2178,30 @@ void LLPipeline::rebuildGroups()
std::sort(mGroupQ2.begin(), mGroupQ2.end(), LLSpatialGroup::CompareUpdateUrgency());
LLSpatialGroup::sg_vector_t::iterator iter;
+ LLSpatialGroup::sg_vector_t::iterator last_iter = mGroupQ2.begin();
+
for (iter = mGroupQ2.begin();
- iter != mGroupQ2.end(); ++iter)
+ iter != mGroupQ2.end() && count <= min_count; ++iter)
{
LLSpatialGroup* group = *iter;
+ last_iter = iter;
- if (group->isDead())
+ if (!group->isDead())
{
- continue;
+ group->rebuildGeom();
+
+ if (group->mSpatialPartition->mRenderByGroup)
+ {
+ count++;
+ }
}
- group->rebuildGeom();
-
- if (group->mSpatialPartition->mRenderByGroup)
- {
- count++;
- }
-
group->clearState(LLSpatialGroup::IN_BUILD_Q2);
-
- if (count > min_count)
- {
- ++iter;
- break;
- }
}
- mGroupQ2.erase(mGroupQ2.begin(), iter);
+ mGroupQ2.erase(mGroupQ2.begin(), ++last_iter);
+
+ mGroupQ2Locked = false;
updateMovedList(mMovedBridge);
}
@@ -2078,6 +2427,9 @@ void LLPipeline::shiftObjects(const LLVector3 &offset)
glClear(GL_DEPTH_BUFFER_BIT);
gDepthDirty = TRUE;
+ LLVector4a offseta;
+ offseta.load3(offset.mV);
+
for (LLDrawable::drawable_vector_t::iterator iter = mShiftList.begin();
iter != mShiftList.end(); iter++)
{
@@ -2086,7 +2438,7 @@ void LLPipeline::shiftObjects(const LLVector3 &offset)
{
continue;
}
- drawablep->shiftPos(offset);
+ drawablep->shiftPos(offseta);
drawablep->clearState(LLDrawable::ON_SHIFT_LIST);
}
mShiftList.resize(0);
@@ -2100,7 +2452,7 @@ void LLPipeline::shiftObjects(const LLVector3 &offset)
LLSpatialPartition* part = region->getSpatialPartition(i);
if (part)
{
- part->shift(offset);
+ part->shift(offseta);
}
}
}
@@ -2132,8 +2484,7 @@ void LLPipeline::markGLRebuild(LLGLUpdate* glu)
void LLPipeline::markRebuild(LLSpatialGroup* group, BOOL priority)
{
LLMemType mt(LLMemType::MTYPE_PIPELINE);
- //assert_main_thread();
-
+
if (group && !group->isDead() && group->mSpatialPartition)
{
if (group->mSpatialPartition->mPartitionType == LLViewerRegion::PARTITION_HUD)
@@ -2145,6 +2496,8 @@ void LLPipeline::markRebuild(LLSpatialGroup* group, BOOL priority)
{
if (!group->isState(LLSpatialGroup::IN_BUILD_Q1))
{
+ llassert_always(!mGroupQ1Locked);
+
mGroupQ1.push_back(group);
group->setState(LLSpatialGroup::IN_BUILD_Q1);
@@ -2161,11 +2514,7 @@ void LLPipeline::markRebuild(LLSpatialGroup* group, BOOL priority)
}
else if (!group->isState(LLSpatialGroup::IN_BUILD_Q2 | LLSpatialGroup::IN_BUILD_Q1))
{
- //llerrs << "Non-priority updates not yet supported!" << llendl;
- if (std::find(mGroupQ2.begin(), mGroupQ2.end(), group) != mGroupQ2.end())
- {
- llerrs << "WTF?" << llendl;
- }
+ llassert_always(!mGroupQ2Locked);
mGroupQ2.push_back(group);
group->setState(LLSpatialGroup::IN_BUILD_Q2);
@@ -2245,6 +2594,42 @@ void LLPipeline::stateSort(LLCamera& camera, LLCullResult &result)
}
}
}
+
+ if (LLViewerCamera::sCurCameraID == LLViewerCamera::CAMERA_WORLD)
+ {
+ LLSpatialGroup* last_group = NULL;
+ for (LLCullResult::bridge_list_t::iterator i = sCull->beginVisibleBridge(); i != sCull->endVisibleBridge(); ++i)
+ {
+ LLCullResult::bridge_list_t::iterator cur_iter = i;
+ LLSpatialBridge* bridge = *cur_iter;
+ LLSpatialGroup* group = bridge->getSpatialGroup();
+
+ if (last_group == NULL)
+ {
+ last_group = group;
+ }
+
+ if (!bridge->isDead() && group && !group->isOcclusionState(LLSpatialGroup::OCCLUDED))
+ {
+ stateSort(bridge, camera);
+ }
+
+ if (LLViewerCamera::sCurCameraID == LLViewerCamera::CAMERA_WORLD &&
+ last_group != group && last_group->changeLOD())
+ {
+ last_group->mLastUpdateDistance = last_group->mDistance;
+ }
+
+ last_group = group;
+ }
+
+ if (LLViewerCamera::sCurCameraID == LLViewerCamera::CAMERA_WORLD &&
+ last_group && last_group->changeLOD())
+ {
+ last_group->mLastUpdateDistance = last_group->mDistance;
+ }
+ }
+
for (LLCullResult::sg_list_t::iterator iter = sCull->beginVisibleGroups(); iter != sCull->endVisibleGroups(); ++iter)
{
LLSpatialGroup* group = *iter;
@@ -2260,19 +2645,6 @@ void LLPipeline::stateSort(LLCamera& camera, LLCullResult &result)
}
}
- if (LLViewerCamera::sCurCameraID == LLViewerCamera::CAMERA_WORLD)
- {
- for (LLCullResult::bridge_list_t::iterator i = sCull->beginVisibleBridge(); i != sCull->endVisibleBridge(); ++i)
- {
- LLCullResult::bridge_list_t::iterator cur_iter = i;
- LLSpatialBridge* bridge = *cur_iter;
- LLSpatialGroup* group = bridge->getSpatialGroup();
- if (!bridge->isDead() && group && !group->isOcclusionState(LLSpatialGroup::OCCLUDED))
- {
- stateSort(bridge, camera);
- }
- }
- }
{
LLFastTimer ftm(FTM_STATESORT_DRAWABLE);
for (LLCullResult::drawable_list_t::iterator iter = sCull->beginVisibleList();
@@ -2303,6 +2675,11 @@ void LLPipeline::stateSort(LLSpatialGroup* group, LLCamera& camera)
LLDrawable* drawablep = *i;
stateSort(drawablep, camera);
}
+
+ if (LLViewerCamera::sCurCameraID == LLViewerCamera::CAMERA_WORLD)
+ { //avoid redundant stateSort calls
+ group->mLastUpdateDistance = group->mDistance;
+ }
}
}
@@ -2310,7 +2687,7 @@ void LLPipeline::stateSort(LLSpatialGroup* group, LLCamera& camera)
void LLPipeline::stateSort(LLSpatialBridge* bridge, LLCamera& camera)
{
LLMemType mt(LLMemType::MTYPE_PIPELINE_STATE_SORT);
- if (!sShadowRender && bridge->getSpatialGroup()->changeLOD())
+ if (bridge->getSpatialGroup()->changeLOD())
{
bool force_update = false;
bridge->updateDistance(camera, force_update);
@@ -2369,21 +2746,17 @@ void LLPipeline::stateSort(LLDrawable* drawablep, LLCamera& camera)
if (LLViewerCamera::sCurCameraID == LLViewerCamera::CAMERA_WORLD)
{
- LLSpatialGroup* group = drawablep->getSpatialGroup();
- if (!group || group->changeLOD())
+ //if (drawablep->isVisible()) isVisible() check here is redundant, if it wasn't visible, it wouldn't be here
{
- if (drawablep->isVisible())
+ if (!drawablep->isActive())
{
- if (!drawablep->isActive())
- {
- bool force_update = false;
- drawablep->updateDistance(camera, force_update);
- }
- else if (drawablep->isAvatar())
- {
- bool force_update = false;
- drawablep->updateDistance(camera, force_update); // calls vobj->updateLOD() which calls LLVOAvatar::updateVisibility()
- }
+ bool force_update = false;
+ drawablep->updateDistance(camera, force_update);
+ }
+ else if (drawablep->isAvatar())
+ {
+ bool force_update = false;
+ drawablep->updateDistance(camera, force_update); // calls vobj->updateLOD() which calls LLVOAvatar::updateVisibility()
}
}
}
@@ -2575,21 +2948,6 @@ void LLPipeline::postSort(LLCamera& camera)
//rebuild groups
sCull->assertDrawMapsEmpty();
- /*LLSpatialGroup::sNoDelete = FALSE;
- for (LLCullResult::sg_list_t::iterator i = sCull->beginVisibleGroups(); i != sCull->endVisibleGroups(); ++i)
- {
- LLSpatialGroup* group = *i;
- if (sUseOcclusion &&
- group->isState(LLSpatialGroup::OCCLUDED))
- {
- continue;
- }
-
- group->rebuildGeom();
- }
- LLSpatialGroup::sNoDelete = TRUE;*/
-
-
rebuildPriorityGroups();
llpushcallstacks ;
@@ -2635,8 +2993,10 @@ void LLPipeline::postSort(LLCamera& camera)
{
if (sMinRenderSize > 0.f)
{
- LLVector3 bounds = (*k)->mExtents[1]-(*k)->mExtents[0];
- if (llmax(llmax(bounds.mV[0], bounds.mV[1]), bounds.mV[2]) > sMinRenderSize)
+ LLVector4a bounds;
+ bounds.setSub((*k)->mExtents[1],(*k)->mExtents[0]);
+
+ if (llmax(llmax(bounds[0], bounds[1]), bounds[2]) > sMinRenderSize)
{
sCull->pushDrawInfo(j->first, *k);
}
@@ -2792,7 +3152,7 @@ void render_hud_elements()
gGL.color4f(1,1,1,1);
if (!LLPipeline::sReflectionRender && gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
{
- LLGLEnable multisample(GL_MULTISAMPLE_ARB);
+ LLGLEnable multisample(gSavedSettings.getU32("RenderFSAASamples") > 0 ? GL_MULTISAMPLE_ARB : 0);
gViewerWindow->renderSelections(FALSE, FALSE, FALSE); // For HUD version in render_ui_3d()
// Draw the tracking overlays
@@ -3006,6 +3366,13 @@ void LLPipeline::renderGeom(LLCamera& camera, BOOL forceVBOUpdate)
}
}
+ S32 stack_depth = 0;
+
+ if (gDebugGL)
+ {
+ glGetIntegerv(GL_MODELVIEW_STACK_DEPTH, &stack_depth);
+ }
+
///////////////////////////////////////////
//
// Sync and verify GL state
@@ -3036,7 +3403,7 @@ void LLPipeline::renderGeom(LLCamera& camera, BOOL forceVBOUpdate)
glMatrixMode(GL_MODELVIEW);
LLGLSPipeline gls_pipeline;
- LLGLEnable multisample(GL_MULTISAMPLE_ARB);
+ LLGLEnable multisample(gSavedSettings.getU32("RenderFSAASamples") > 0 ? GL_MULTISAMPLE_ARB : 0);
LLGLState gls_color_material(GL_COLOR_MATERIAL, mLightingDetail < 2);
@@ -3130,18 +3497,9 @@ void LLPipeline::renderGeom(LLCamera& camera, BOOL forceVBOUpdate)
}
poolp->endRenderPass(i);
LLVertexBuffer::unbind();
- if (gDebugGL || gDebugPipeline)
+ if (gDebugGL)
{
- GLint depth;
- glGetIntegerv(GL_MODELVIEW_STACK_DEPTH, &depth);
- if (depth > 3)
- {
- if (gDebugSession)
- {
- ll_fail("GL matrix stack corrupted.");
- }
- llerrs << "GL matrix stack corrupted!" << llendl;
- }
+ check_stack_depth(stack_depth);
std::string msg = llformat("%s pass %d", gPoolNames[cur_type].c_str(), i);
LLGLState::checkStates(msg);
LLGLState::checkTextureChannels(msg);
@@ -3164,11 +3522,11 @@ void LLPipeline::renderGeom(LLCamera& camera, BOOL forceVBOUpdate)
iter1 = iter2;
stop_glerror();
}
-
- LLAppViewer::instance()->pingMainloopTimeout("Pipeline:RenderDrawPoolsEnd");
-
- LLVertexBuffer::unbind();
+ LLAppViewer::instance()->pingMainloopTimeout("Pipeline:RenderDrawPoolsEnd");
+
+ LLVertexBuffer::unbind();
+
gGLLastMatrix = NULL;
glLoadMatrixd(gGLModelView);
@@ -3215,9 +3573,9 @@ void LLPipeline::renderGeom(LLCamera& camera, BOOL forceVBOUpdate)
{
if (gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_UI))
{
- // Render debugging beacons.
- gObjectList.renderObjectBeacons();
- gObjectList.resetObjectBeacons();
+ // Render debugging beacons.
+ gObjectList.renderObjectBeacons();
+ gObjectList.resetObjectBeacons();
}
else
{
@@ -3276,7 +3634,7 @@ void LLPipeline::renderGeomDeferred(LLCamera& camera)
}
}
- LLGLEnable multisample(GL_MULTISAMPLE_ARB);
+ LLGLEnable multisample(gSavedSettings.getU32("RenderFSAASamples") > 0 ? GL_MULTISAMPLE_ARB : 0);
LLVertexBuffer::unbind();
@@ -3365,7 +3723,7 @@ void LLPipeline::renderGeomPostDeferred(LLCamera& camera)
LLGLEnable cull(GL_CULL_FACE);
- LLGLEnable multisample(GL_MULTISAMPLE_ARB);
+ LLGLEnable multisample(gSavedSettings.getU32("RenderFSAASamples") > 0 ? GL_MULTISAMPLE_ARB : 0);
calcNearbyLights(camera);
setupHWLights(NULL);
@@ -3550,6 +3908,59 @@ void LLPipeline::addTrianglesDrawn(S32 index_count, U32 render_type)
}
}
+void LLPipeline::renderPhysicsDisplay()
+{
+ if (!hasRenderDebugMask(LLPipeline::RENDER_DEBUG_PHYSICS_SHAPES))
+ {
+ return;
+ }
+
+ allocatePhysicsBuffer();
+
+ gGL.flush();
+ mPhysicsDisplay.bindTarget();
+ glClearColor(0,0,0,1);
+ gGL.setColorMask(true, true);
+ mPhysicsDisplay.clear();
+ glClearColor(0,0,0,0);
+
+ gGL.setColorMask(true, false);
+
+ for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
+ iter != LLWorld::getInstance()->getRegionList().end(); ++iter)
+ {
+ LLViewerRegion* region = *iter;
+ for (U32 i = 0; i < LLViewerRegion::NUM_PARTITIONS; i++)
+ {
+ LLSpatialPartition* part = region->getSpatialPartition(i);
+ if (part)
+ {
+ if (hasRenderType(part->mDrawableType))
+ {
+ part->renderPhysicsShapes();
+ }
+ }
+ }
+ }
+
+ for (LLCullResult::bridge_list_t::const_iterator i = sCull->beginVisibleBridge(); i != sCull->endVisibleBridge(); ++i)
+ {
+ LLSpatialBridge* bridge = *i;
+ if (!bridge->isDead() && hasRenderType(bridge->mDrawableType))
+ {
+ glPushMatrix();
+ glMultMatrixf((F32*)bridge->mDrawable->getRenderMatrix().mMatrix);
+ bridge->renderPhysicsShapes();
+ glPopMatrix();
+ }
+ }
+
+
+ gGL.flush();
+ mPhysicsDisplay.flush();
+}
+
+
void LLPipeline::renderDebug()
{
LLMemType mt(LLMemType::MTYPE_PIPELINE);
@@ -3562,6 +3973,8 @@ void LLPipeline::renderDebug()
glLoadMatrixd(gGLModelView);
gGL.setColorMask(true, false);
+ bool hud_only = hasRenderType(LLPipeline::RENDER_TYPE_HUD);
+
// Debug stuff.
for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
iter != LLWorld::getInstance()->getRegionList().end(); ++iter)
@@ -3572,7 +3985,8 @@ void LLPipeline::renderDebug()
LLSpatialPartition* part = region->getSpatialPartition(i);
if (part)
{
- if (hasRenderType(part->mDrawableType))
+ if ( hud_only && (part->mDrawableType == RENDER_TYPE_HUD || part->mDrawableType == RENDER_TYPE_HUD_PARTICLES) ||
+ !hud_only && hasRenderType(part->mDrawableType) )
{
part->renderDebug();
}
@@ -3592,8 +4006,67 @@ void LLPipeline::renderDebug()
}
}
+ if (gSavedSettings.getBOOL("DebugShowUploadCost"))
+ {
+ std::set<LLUUID> textures;
+ std::set<LLUUID> sculpts;
+ std::set<LLUUID> meshes;
+
+ BOOL selected = TRUE;
+ if (LLSelectMgr::getInstance()->getSelection()->isEmpty())
+ {
+ selected = FALSE;
+ }
+
+ for (LLCullResult::sg_list_t::iterator iter = sCull->beginVisibleGroups(); iter != sCull->endVisibleGroups(); ++iter)
+ {
+ LLSpatialGroup* group = *iter;
+ LLSpatialGroup::OctreeNode* node = group->mOctreeNode;
+ for (LLSpatialGroup::OctreeNode::element_iter elem = node->getData().begin(); elem != node->getData().end(); ++elem)
+ {
+ LLDrawable* drawable = *elem;
+ LLVOVolume* volume = drawable->getVOVolume();
+ if (volume && volume->isSelected() == selected)
+ {
+ for (U32 i = 0; i < volume->getNumTEs(); ++i)
+ {
+ LLTextureEntry* te = volume->getTE(i);
+ textures.insert(te->getID());
+ }
+
+ if (volume->isSculpted())
+ {
+ LLUUID sculpt_id = volume->getVolume()->getParams().getSculptID();
+ if (volume->isMesh())
+ {
+ meshes.insert(sculpt_id);
+ }
+ else
+ {
+ sculpts.insert(sculpt_id);
+ }
+ }
+ }
+ }
+ }
+
+ gPipeline.mDebugTextureUploadCost = textures.size() * 10;
+ gPipeline.mDebugSculptUploadCost = sculpts.size()*10;
+
+ U32 mesh_cost = 0;
+
+ for (std::set<LLUUID>::iterator iter = meshes.begin(); iter != meshes.end(); ++iter)
+ {
+ mesh_cost += gMeshRepo.getResourceCost(*iter)*10;
+ }
+
+ gPipeline.mDebugMeshUploadCost = mesh_cost;
+ }
+
if (hasRenderDebugMask(LLPipeline::RENDER_DEBUG_SHADOW_FRUSTA))
{
+ LLVertexBuffer::unbind();
+
LLGLEnable blend(GL_BLEND);
LLGLDepthTest depth(TRUE, FALSE);
LLGLDisable cull(GL_CULL_FACE);
@@ -3657,7 +4130,7 @@ void LLPipeline::renderDebug()
if (i < 4)
{
- if (i == 0 || !mShadowFrustPoints[i].empty())
+ //if (i == 0 || !mShadowFrustPoints[i].empty())
{
//render visible point cloud
gGL.flush();
@@ -3697,11 +4170,12 @@ void LLPipeline::renderDebug()
gGL.vertex3fv(frust[2].mV); gGL.vertex3fv(frust[6].mV);
gGL.vertex3fv(frust[3].mV); gGL.vertex3fv(frust[7].mV);
gGL.end();
- }
-
+ }
}
- /*for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
+ /*gGL.flush();
+ glLineWidth(16-i*2);
+ for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
iter != LLWorld::getInstance()->getRegionList().end(); ++iter)
{
LLViewerRegion* region = *iter;
@@ -3716,7 +4190,9 @@ void LLPipeline::renderDebug()
}
}
}
- }*/
+ }
+ gGL.flush();
+ glLineWidth(1.f);*/
}
}
@@ -3756,13 +4232,19 @@ void LLPipeline::renderDebug()
if (mRenderDebugMask & LLPipeline::RENDER_DEBUG_BUILD_QUEUE)
{
U32 count = 0;
- U32 size = mBuildQ2.size();
+ U32 size = mGroupQ2.size();
LLColor4 col;
+ LLVertexBuffer::unbind();
LLGLEnable blend(GL_BLEND);
+ gGL.setSceneBlendType(LLRender::BT_ALPHA);
LLGLDepthTest depth(GL_TRUE, GL_FALSE);
gGL.getTexUnit(0)->bind(LLViewerFetchedTexture::sWhiteImagep);
+ gGL.pushMatrix();
+ glLoadMatrixd(gGLModelView);
+ gGLLastMatrix = NULL;
+
for (LLSpatialGroup::sg_vector_t::iterator iter = mGroupQ2.begin(); iter != mGroupQ2.end(); ++iter)
{
LLSpatialGroup* group = *iter;
@@ -3784,7 +4266,7 @@ void LLPipeline::renderDebug()
glMultMatrixf((F32*)bridge->mDrawable->getRenderMatrix().mMatrix);
}
- F32 alpha = (F32) (size-count)/size;
+ F32 alpha = llclamp((F32) (size-count)/size, 0.f, 1.f);
LLVector2 c(1.f-alpha, alpha);
@@ -3792,7 +4274,7 @@ void LLPipeline::renderDebug()
++count;
- col.set(c.mV[0], c.mV[1], 0, alpha*0.5f+0.1f);
+ col.set(c.mV[0], c.mV[1], 0, alpha*0.5f+0.5f);
group->drawObjectBox(col);
if (bridge)
@@ -3800,9 +4282,13 @@ void LLPipeline::renderDebug()
gGL.popMatrix();
}
}
+
+ gGL.popMatrix();
}
gGL.flush();
+
+ gPipeline.renderPhysicsDisplay();
}
void LLPipeline::rebuildPools()
@@ -4134,16 +4620,19 @@ void LLPipeline::setupAvatarLights(BOOL for_edit)
light_pos.normalize();
+ LLLightState* light = gGL.getLight(1);
+
mHWLightColors[1] = diffuse;
- glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse.mV);
- glLightfv(GL_LIGHT1, GL_AMBIENT, LLColor4::black.mV);
- glLightfv(GL_LIGHT1, GL_SPECULAR, LLColor4::black.mV);
- glLightfv(GL_LIGHT1, GL_POSITION, light_pos.mV);
- glLightf (GL_LIGHT1, GL_CONSTANT_ATTENUATION, 1.0f);
- glLightf (GL_LIGHT1, GL_LINEAR_ATTENUATION, 0.0f);
- glLightf (GL_LIGHT1, GL_QUADRATIC_ATTENUATION, 0.0f);
- glLightf (GL_LIGHT1, GL_SPOT_EXPONENT, 0.0f);
- glLightf (GL_LIGHT1, GL_SPOT_CUTOFF, 180.0f);
+
+ light->setDiffuse(diffuse);
+ light->setAmbient(LLColor4::black);
+ light->setSpecular(LLColor4::black);
+ light->setPosition(light_pos);
+ light->setConstantAttenuation(1.f);
+ light->setLinearAttenuation(0.f);
+ light->setQuadraticAttenuation(0.f);
+ light->setSpotExponent(0.f);
+ light->setSpotCutoff(180.f);
}
else if (gAvatarBacklight) // Always true (unless overridden in a devs .ini)
{
@@ -4174,22 +4663,28 @@ void LLPipeline::setupAvatarLights(BOOL for_edit)
backlight_diffuse *= backlight_mag / max_component;
mHWLightColors[1] = backlight_diffuse;
- glLightfv(GL_LIGHT1, GL_POSITION, backlight_pos.mV); // this is just sun/moon direction
- glLightfv(GL_LIGHT1, GL_DIFFUSE, backlight_diffuse.mV);
- glLightfv(GL_LIGHT1, GL_AMBIENT, LLColor4::black.mV);
- glLightfv(GL_LIGHT1, GL_SPECULAR, LLColor4::black.mV);
- glLightf (GL_LIGHT1, GL_CONSTANT_ATTENUATION, 1.0f);
- glLightf (GL_LIGHT1, GL_LINEAR_ATTENUATION, 0.0f);
- glLightf (GL_LIGHT1, GL_QUADRATIC_ATTENUATION, 0.0f);
- glLightf (GL_LIGHT1, GL_SPOT_EXPONENT, 0.0f);
- glLightf (GL_LIGHT1, GL_SPOT_CUTOFF, 180.0f);
+
+ LLLightState* light = gGL.getLight(1);
+
+ light->setPosition(backlight_pos);
+ light->setDiffuse(backlight_diffuse);
+ light->setAmbient(LLColor4::black);
+ light->setSpecular(LLColor4::black);
+ light->setConstantAttenuation(1.f);
+ light->setLinearAttenuation(0.f);
+ light->setQuadraticAttenuation(0.f);
+ light->setSpotExponent(0.f);
+ light->setSpotCutoff(180.f);
}
else
{
+ LLLightState* light = gGL.getLight(1);
+
mHWLightColors[1] = LLColor4::black;
- glLightfv(GL_LIGHT1, GL_DIFFUSE, LLColor4::black.mV);
- glLightfv(GL_LIGHT1, GL_AMBIENT, LLColor4::black.mV);
- glLightfv(GL_LIGHT1, GL_SPECULAR, LLColor4::black.mV);
+
+ light->setDiffuse(LLColor4::black);
+ light->setAmbient(LLColor4::black);
+ light->setSpecular(LLColor4::black);
}
}
@@ -4208,7 +4703,7 @@ static F32 calc_light_dist(LLVOVolume* light, const LLVector3& cam_pos, F32 max_
{
return max_dist;
}
- F32 dist = fsqrtf(dist2);
+ F32 dist = (F32) sqrt(dist2);
dist *= 1.f / inten;
dist -= radius;
if (selected)
@@ -4237,7 +4732,7 @@ void LLPipeline::calcNearbyLights(LLCamera& camera)
// mNearbyLight (and all light_set_t's) are sorted such that
// begin() == the closest light and rbegin() == the farthest light
const S32 MAX_LOCAL_LIGHTS = 6;
-// LLVector3 cam_pos = gAgentCamera.getCameraPositionAgent();
+// LLVector3 cam_pos = gAgent.getCameraPositionAgent();
LLVector3 cam_pos = LLViewerJoystick::getInstance()->getOverrideCamera() ?
camera.getOrigin() :
gAgent.getPositionAgent();
@@ -4370,15 +4865,17 @@ void LLPipeline::setupHWLights(LLDrawPool* pool)
LLVector4 light_pos(mSunDir, 0.0f);
LLColor4 light_diffuse = mSunDiffuse;
mHWLightColors[0] = light_diffuse;
- glLightfv(GL_LIGHT0, GL_POSITION, light_pos.mV); // this is just sun/moon direction
- glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse.mV);
- glLightfv(GL_LIGHT0, GL_AMBIENT, LLColor4::black.mV);
- glLightfv(GL_LIGHT0, GL_SPECULAR, LLColor4::black.mV);
- glLightf (GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1.0f);
- glLightf (GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.0f);
- glLightf (GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.0f);
- glLightf (GL_LIGHT0, GL_SPOT_EXPONENT, 0.0f);
- glLightf (GL_LIGHT0, GL_SPOT_CUTOFF, 180.0f);
+
+ LLLightState* light = gGL.getLight(0);
+ light->setPosition(light_pos);
+ light->setDiffuse(light_diffuse);
+ light->setAmbient(LLColor4::black);
+ light->setSpecular(LLColor4::black);
+ light->setConstantAttenuation(1.f);
+ light->setLinearAttenuation(0.f);
+ light->setQuadraticAttenuation(0.f);
+ light->setSpotExponent(0.f);
+ light->setSpotCutoff(180.f);
}
// Light 1 = Backlight (for avatars)
@@ -4436,13 +4933,15 @@ void LLPipeline::setupHWLights(LLDrawPool* pool)
float linatten = x / (light_radius); // % of brightness at radius
mHWLightColors[cur_light] = light_color;
- S32 gllight = GL_LIGHT0+cur_light;
- glLightfv(gllight, GL_POSITION, light_pos_gl.mV);
- glLightfv(gllight, GL_DIFFUSE, light_color.mV);
- glLightfv(gllight, GL_AMBIENT, LLColor4::black.mV);
- glLightf (gllight, GL_CONSTANT_ATTENUATION, 0.0f);
- glLightf (gllight, GL_LINEAR_ATTENUATION, linatten);
- glLightf (gllight, GL_QUADRATIC_ATTENUATION, 0.0f);
+ LLLightState* light_state = gGL.getLight(cur_light);
+
+ light_state->setPosition(light_pos_gl);
+ light_state->setDiffuse(light_color);
+ light_state->setAmbient(LLColor4::black);
+ light_state->setConstantAttenuation(0.f);
+ light_state->setLinearAttenuation(linatten);
+ light_state->setQuadraticAttenuation(0.f);
+
if (light->isLightSpotlight() // directional (spot-)light
&& (LLPipeline::sRenderDeferred || gSavedSettings.getBOOL("RenderSpotLightsInNondeferred"))) // these are only rendered as GL spotlights if we're in deferred rendering mode *or* the setting forces them on
{
@@ -4450,22 +4949,21 @@ void LLPipeline::setupHWLights(LLDrawPool* pool)
LLQuaternion quat = light->getRenderRotation();
LLVector3 at_axis(0,0,-1); // this matches deferred rendering's object light direction
at_axis *= quat;
- //llinfos << "SPOT!!!!!!! fov: " << spotparams.mV[0] << " focus: " << spotparams.mV[1] << " dir: " << at_axis << llendl;
- glLightfv(gllight, GL_SPOT_DIRECTION, at_axis.mV);
- glLightf (gllight, GL_SPOT_EXPONENT, 2.0f); // 2.0 = good old dot product ^ 2
- glLightf (gllight, GL_SPOT_CUTOFF, 90.0f); // hemisphere
- const float specular[] = {0.f, 0.f, 0.f, 0.f};
- glLightfv(gllight, GL_SPECULAR, specular);
+
+ light_state->setSpotDirection(at_axis);
+ light_state->setSpotCutoff(90.f);
+ light_state->setSpotExponent(2.f);
+
+ light_state->setSpecular(LLColor4::black);
}
else // omnidirectional (point) light
{
- glLightf (gllight, GL_SPOT_EXPONENT, 0.0f);
- glLightf (gllight, GL_SPOT_CUTOFF, 180.0f);
-
+ light_state->setSpotExponent(0.f);
+ light_state->setSpotCutoff(180.f);
+
// we use specular.w = 1.0 as a cheap hack for the shaders to know that this is omnidirectional rather than a spotlight
- const float specular[] = {0.f, 0.f, 0.f, 1.f};
- glLightfv(gllight, GL_SPECULAR, specular);
- //llinfos << "boring light" << llendl;
+ const LLColor4 specular(0.f, 0.f, 0.f, 1.f);
+ light_state->setSpecular(specular);
}
cur_light++;
if (cur_light >= 8)
@@ -4477,13 +4975,13 @@ void LLPipeline::setupHWLights(LLDrawPool* pool)
for ( ; cur_light < 8 ; cur_light++)
{
mHWLightColors[cur_light] = LLColor4::black;
- S32 gllight = GL_LIGHT0+cur_light;
- glLightfv(gllight, GL_DIFFUSE, LLColor4::black.mV);
- glLightfv(gllight, GL_AMBIENT, LLColor4::black.mV);
- glLightfv(gllight, GL_SPECULAR, LLColor4::black.mV);
- }
+ LLLightState* light = gGL.getLight(cur_light);
- if (isAgentAvatarValid() &&
+ light->setDiffuse(LLColor4::black);
+ light->setAmbient(LLColor4::black);
+ light->setSpecular(LLColor4::black);
+ }
+ if (gAgentAvatarp &&
gAgentAvatarp->mSpecialRenderMode == 3)
{
LLColor4 light_color = LLColor4::white;
@@ -4498,23 +4996,24 @@ void LLPipeline::setupHWLights(LLDrawPool* pool)
float linatten = x / (light_radius); // % of brightness at radius
mHWLightColors[2] = light_color;
- S32 gllight = GL_LIGHT2;
- glLightfv(gllight, GL_POSITION, light_pos_gl.mV);
- glLightfv(gllight, GL_DIFFUSE, light_color.mV);
- glLightfv(gllight, GL_AMBIENT, LLColor4::black.mV);
- glLightfv(gllight, GL_SPECULAR, LLColor4::black.mV);
- glLightf (gllight, GL_CONSTANT_ATTENUATION, 0.0f);
- glLightf (gllight, GL_LINEAR_ATTENUATION, linatten);
- glLightf (gllight, GL_QUADRATIC_ATTENUATION, 0.0f);
- glLightf (gllight, GL_SPOT_EXPONENT, 0.0f);
- glLightf (gllight, GL_SPOT_CUTOFF, 180.0f);
+ LLLightState* light = gGL.getLight(2);
+
+ light->setPosition(light_pos_gl);
+ light->setDiffuse(light_color);
+ light->setAmbient(LLColor4::black);
+ light->setSpecular(LLColor4::black);
+ light->setQuadraticAttenuation(0.f);
+ light->setConstantAttenuation(0.f);
+ light->setLinearAttenuation(linatten);
+ light->setSpotExponent(0.f);
+ light->setSpotCutoff(180.f);
}
// Init GL state
glDisable(GL_LIGHTING);
- for (S32 gllight=GL_LIGHT0; gllight<=GL_LIGHT7; gllight++)
+ for (S32 i = 0; i < 8; ++i)
{
- glDisable(gllight);
+ gGL.getLight(i)->disable();
}
mLightMask = 0;
}
@@ -4539,15 +5038,16 @@ void LLPipeline::enableLights(U32 mask)
stop_glerror();
for (S32 i=0; i<8; i++)
{
+ LLLightState* light = gGL.getLight(i);
if (mask & (1<<i))
{
- glEnable(GL_LIGHT0 + i);
- glLightfv(GL_LIGHT0 + i, GL_DIFFUSE, mHWLightColors[i].mV);
+ light->enable();
+ light->setDiffuse(mHWLightColors[i]);
}
else
{
- glDisable(GL_LIGHT0 + i);
- glLightfv(GL_LIGHT0 + i, GL_DIFFUSE, LLColor4::black.mV);
+ light->disable();
+ light->setDiffuse(LLColor4::black);
}
}
stop_glerror();
@@ -4571,7 +5071,6 @@ void LLPipeline::enableLightsStatic()
if (mLightingDetail >= 2)
{
mask |= mLightMovingMask; // Hardware moving lights
- glColor4f(0.f, 0.f, 0.f, 1.0f); // no local lighting by default
}
else
{
@@ -4585,11 +5084,7 @@ void LLPipeline::enableLightsDynamic()
assertInitialized();
U32 mask = 0xff & (~2); // Local lights
enableLights(mask);
- if (mLightingDetail >= 2)
- {
- glColor4f(0.f, 0.f, 0.f, 1.f); // no local lighting by default
- }
-
+
if (isAgentAvatarValid() && getLightingDetail() <= 0)
{
if (gAgentAvatarp->mSpecialRenderMode == 0) // normal
@@ -4610,6 +5105,65 @@ void LLPipeline::enableLightsAvatar()
enableLights(mask);
}
+void LLPipeline::enableLightsPreview()
+{
+ disableLights();
+
+ glEnable(GL_LIGHTING);
+ LLColor4 ambient = gSavedSettings.getColor4("PreviewAmbientColor");
+ glLightModelfv(GL_LIGHT_MODEL_AMBIENT,ambient.mV);
+
+
+ LLColor4 diffuse0 = gSavedSettings.getColor4("PreviewDiffuse0");
+ LLColor4 specular0 = gSavedSettings.getColor4("PreviewSpecular0");
+ LLColor4 diffuse1 = gSavedSettings.getColor4("PreviewDiffuse1");
+ LLColor4 specular1 = gSavedSettings.getColor4("PreviewSpecular1");
+ LLColor4 diffuse2 = gSavedSettings.getColor4("PreviewDiffuse2");
+ LLColor4 specular2 = gSavedSettings.getColor4("PreviewSpecular2");
+
+ LLVector3 dir0 = gSavedSettings.getVector3("PreviewDirection0");
+ LLVector3 dir1 = gSavedSettings.getVector3("PreviewDirection1");
+ LLVector3 dir2 = gSavedSettings.getVector3("PreviewDirection2");
+
+ dir0.normVec();
+ dir1.normVec();
+ dir2.normVec();
+
+ LLVector4 light_pos(dir0, 0.0f);
+
+ LLLightState* light = gGL.getLight(0);
+
+ light->enable();
+ light->setPosition(light_pos);
+ light->setDiffuse(diffuse0);
+ light->setAmbient(LLColor4::black);
+ light->setSpecular(specular0);
+ light->setSpotExponent(0.f);
+ light->setSpotCutoff(180.f);
+
+ light_pos = LLVector4(dir1, 0.f);
+
+ light = gGL.getLight(1);
+ light->enable();
+ light->setPosition(light_pos);
+ light->setDiffuse(diffuse1);
+ light->setAmbient(LLColor4::black);
+ light->setSpecular(specular1);
+ light->setSpotExponent(0.f);
+ light->setSpotCutoff(180.f);
+
+ light_pos = LLVector4(dir2, 0.f);
+ light = gGL.getLight(2);
+ light->enable();
+ light->setPosition(light_pos);
+ light->setDiffuse(diffuse2);
+ light->setAmbient(LLColor4::black);
+ light->setSpecular(specular2);
+ light->setSpotExponent(0.f);
+ light->setSpotCutoff(180.f);
+}
+
+
void LLPipeline::enableLightsAvatarEdit(const LLColor4& color)
{
U32 mask = 0x2002; // Avatar backlight only, set ambient
@@ -4626,16 +5180,11 @@ void LLPipeline::enableLightsFullbright(const LLColor4& color)
enableLights(mask);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,color.mV);
- /*if (mLightingDetail >= 2)
- {
- glColor4f(0.f, 0.f, 0.f, 1.f); // no local lighting by default
- }*/
}
void LLPipeline::disableLights()
{
enableLights(0); // no lighting (full bright)
- glColor4f(1.f, 1.f, 1.f, 1.f); // lighting color = white by default
}
//============================================================================
@@ -4901,6 +5450,18 @@ BOOL LLPipeline::toggleRenderDebugFeatureControl(void* data)
return gPipeline.hasRenderDebugFeatureMask(bit);
}
+void LLPipeline::setRenderDebugFeatureControl(U32 bit, bool value)
+{
+ if (value)
+ {
+ gPipeline.mRenderDebugFeatureMask |= bit;
+ }
+ else
+ {
+ gPipeline.mRenderDebugFeatureMask &= !bit;
+ }
+}
+
// static
void LLPipeline::setRenderScriptedBeacons(BOOL val)
{
@@ -5233,17 +5794,12 @@ void LLPipeline::resetVertexBuffers(LLDrawable* drawable)
for (S32 i = 0; i < drawable->getNumFaces(); i++)
{
LLFace* facep = drawable->getFace(i);
- facep->mVertexBuffer = NULL;
- facep->mLastVertexBuffer = NULL;
+ facep->clearVertexBuffer();
}
}
void LLPipeline::resetVertexBuffers()
-{
- sRenderBump = gSavedSettings.getBOOL("RenderObjectBump");
- sUseTriStrips = gSavedSettings.getBOOL("RenderUseTriStrips");
- LLVertexBuffer::sUseStreamDraw = gSavedSettings.getBOOL("RenderUseStreamVBO");
-
+{
for (LLWorld::region_list_t::const_iterator iter = LLWorld::getInstance()->getRegionList().begin();
iter != LLWorld::getInstance()->getRegionList().end(); ++iter)
{
@@ -5283,8 +5839,16 @@ void LLPipeline::resetVertexBuffers()
llwarns << "VBO name pool cleanup failed." << llendl;
}
- LLVertexBuffer::unbind();
-
+ LLVertexBuffer::unbind();
+
+ sRenderBump = gSavedSettings.getBOOL("RenderObjectBump");
+ sUseTriStrips = gSavedSettings.getBOOL("RenderUseTriStrips");
+ LLVertexBuffer::sUseStreamDraw = gSavedSettings.getBOOL("RenderUseStreamVBO");
+ LLVertexBuffer::sPreferStreamDraw = gSavedSettings.getBOOL("RenderPreferStreamDraw");
+ LLVertexBuffer::sEnableVBOs = gSavedSettings.getBOOL("RenderVBOEnable");
+ LLVertexBuffer::sDisableVBOMapping = LLVertexBuffer::sEnableVBOs && gSavedSettings.getBOOL("RenderVBOMappingDisable") ;
+ sBakeSunlight = gSavedSettings.getBOOL("RenderBakeSunlight");
+ sNoAlpha = gSavedSettings.getBOOL("RenderNoAlpha");
LLPipeline::sTextureBindTest = gSavedSettings.getBOOL("RenderDebugTextureBind");
}
@@ -5299,42 +5863,6 @@ void LLPipeline::renderObjects(U32 type, U32 mask, BOOL texture)
gGLLastMatrix = NULL;
}
-void LLPipeline::setUseVBO(BOOL use_vbo)
-{
- if (use_vbo != LLVertexBuffer::sEnableVBOs)
- {
- if (use_vbo)
- {
- llinfos << "Enabling VBO." << llendl;
- }
- else
- {
- llinfos << "Disabling VBO." << llendl;
- }
-
- resetVertexBuffers();
- LLVertexBuffer::initClass(use_vbo, gSavedSettings.getBOOL("RenderVBOMappingDisable"));
- }
-}
-
-void LLPipeline::setDisableVBOMapping(BOOL no_vbo_mapping)
-{
- if (LLVertexBuffer::sEnableVBOs && no_vbo_mapping != LLVertexBuffer::sDisableVBOMapping)
- {
- if (no_vbo_mapping)
- {
- llinfos << "Disabling VBO glMapBufferARB." << llendl;
- }
- else
- {
- llinfos << "Enabling VBO glMapBufferARB." << llendl;
- }
-
- resetVertexBuffers();
- LLVertexBuffer::initClass(true, no_vbo_mapping);
- }
-}
-
void apply_cube_face_rotation(U32 face)
{
switch (face)
@@ -5366,21 +5894,21 @@ void apply_cube_face_rotation(U32 face)
void validate_framebuffer_object()
{
GLenum status;
- status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+ status = glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT);
switch(status)
{
- case GL_FRAMEBUFFER_COMPLETE_EXT:
+ case GL_FRAMEBUFFER_COMPLETE:
//framebuffer OK, no error.
break;
- case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
+ case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
// frame buffer not OK: probably means unsupported depth buffer format
- llerrs << "Framebuffer Incomplete Dimensions." << llendl;
+ llerrs << "Framebuffer Incomplete Missing Attachment." << llendl;
break;
- case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
+ case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
// frame buffer not OK: probably means unsupported depth buffer format
llerrs << "Framebuffer Incomplete Attachment." << llendl;
break;
- case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
+ case GL_FRAMEBUFFER_UNSUPPORTED:
/* choose different formats */
llerrs << "Framebuffer unsupported." << llendl;
break;
@@ -5428,8 +5956,6 @@ void LLPipeline::renderBloom(BOOL for_snapshot, F32 zoom_factor, int subfield)
tc2 /= (F32) res_mod;
}
- gGL.setColorMask(true, true);
-
LLFastTimer ftm(FTM_RENDER_BLOOM);
gGL.color4f(1,1,1,1);
LLGLDepthTest depth(GL_FALSE);
@@ -5625,7 +6151,7 @@ void LLPipeline::renderBloom(BOOL for_snapshot, F32 zoom_factor, int subfield)
if (LLRenderTarget::sUseFBO)
{
LLFastTimer ftm(FTM_RENDER_BLOOM_FBO);
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
gGLViewport[0] = gViewerWindow->getWorldViewRectRaw().mLeft;
@@ -5641,16 +6167,142 @@ void LLPipeline::renderBloom(BOOL for_snapshot, F32 zoom_factor, int subfield)
LLVertexBuffer::unbind();
- if (LLPipeline::sRenderDeferred && LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_DEFERRED) > 2)
+ if (LLPipeline::sRenderDeferred && !LLViewerCamera::getInstance()->cameraUnderWater())
{
+ LLGLSLShader* shader = &gDeferredPostProgram;
+ if (LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_DEFERRED) > 2)
+ {
+ shader = &gDeferredGIFinalProgram;
+ }
+
LLGLDisable blend(GL_BLEND);
- bindDeferredShader(gDeferredGIFinalProgram);
+ bindDeferredShader(*shader);
+
+ //depth of field focal plane calculations
+
+ static F32 current_distance = 16.f;
+ static F32 start_distance = 16.f;
+ static F32 transition_time = 1.f;
+
+ LLVector3 focus_point;
+
+ LLViewerObject* obj = LLViewerMediaFocus::getInstance()->getFocusedObject();
+ if (obj && obj->mDrawable && obj->isSelected())
+ {
+ S32 face_idx = LLViewerMediaFocus::getInstance()->getFocusedFace();
+ if (obj && obj->mDrawable)
+ {
+ LLFace* face = obj->mDrawable->getFace(face_idx);
+ if (face)
+ {
+ focus_point = face->getPositionAgent();
+ }
+ }
+ }
+
+ if (focus_point.isExactlyZero())
+ {
+ if (LLViewerJoystick::getInstance()->getOverrideCamera())
+ {
+ focus_point = gDebugRaycastIntersection;
+ }
+ else if (gAgentCamera.cameraMouselook())
+ {
+ gViewerWindow->cursorIntersect(-1, -1, 512.f, NULL, -1, FALSE,
+ NULL,
+ &focus_point);
+ }
+ else
+ {
+ LLViewerObject* obj = gAgentCamera.getFocusObject();
+ if (obj)
+ {
+ focus_point = LLVector3(gAgentCamera.getFocusGlobal()-gAgent.getRegion()->getOriginGlobal());
+ }
+ else
+ {
+ focus_point = gDebugRaycastIntersection;
+ }
+ }
+ }
+
+ LLVector3 eye = LLViewerCamera::getInstance()->getOrigin();
+ F32 target_distance = 16.f;
+ if (!focus_point.isExactlyZero())
+ {
+ target_distance = LLViewerCamera::getInstance()->getAtAxis() * (focus_point-eye);
+ }
+
+ if (transition_time >= 1.f &&
+ fabsf(current_distance-target_distance)/current_distance > 0.01f)
+ { //large shift happened, interpolate smoothly to new target distance
+ transition_time = 0.f;
+ start_distance = current_distance;
+ }
+ else if (transition_time < 1.f)
+ { //currently in a transition, continue interpolating
+ transition_time += 1.f/gSavedSettings.getF32("CameraFocusTransitionTime")*gFrameIntervalSeconds;
+ transition_time = llmin(transition_time, 1.f);
+
+ F32 t = cosf(transition_time*F_PI+F_PI)*0.5f+0.5f;
+ current_distance = start_distance + (target_distance-start_distance)*t;
+ }
+ else
+ { //small or no change, just snap to target distance
+ current_distance = target_distance;
+ }
+
+ //convert to mm
+ F32 subject_distance = current_distance*1000.f;
+ F32 fnumber = gSavedSettings.getF32("CameraFNumber");
+ F32 default_focal_length = gSavedSettings.getF32("CameraFocalLength");
+
+ if (LLToolMgr::getInstance()->inBuildMode())
+ { //squish focal length when in build mode so DoF doesn't make editing objects difficult
+ default_focal_length = 5.f;
+ }
+
+ F32 fov = LLViewerCamera::getInstance()->getView();
+
+ const F32 default_fov = gSavedSettings.getF32("CameraFieldOfView") * F_PI/180.f;
+ //const F32 default_aspect_ratio = gSavedSettings.getF32("CameraAspectRatio");
+
+ //F32 aspect_ratio = (F32) mScreen.getWidth()/(F32)mScreen.getHeight();
+
+ F32 dv = 2.f*default_focal_length * tanf(default_fov/2.f);
+ //F32 dh = 2.f*default_focal_length * tanf(default_fov*default_aspect_ratio/2.f);
- S32 channel = gDeferredGIFinalProgram.enableTexture(LLViewerShaderMgr::DEFERRED_DIFFUSE, LLTexUnit::TT_RECT_TEXTURE);
+ F32 focal_length = dv/(2*tanf(fov/2.f));
+
+ //F32 tan_pixel_angle = tanf(LLDrawable::sCurPixelAngle);
+
+ // from wikipedia -- c = |s2-s1|/s2 * f^2/(N(S1-f))
+ // where N = fnumber
+ // s2 = dot distance
+ // s1 = subject distance
+ // f = focal length
+ //
+
+ F32 blur_constant = focal_length*focal_length/(fnumber*(subject_distance-focal_length));
+ blur_constant /= 1000.f; //convert to meters for shader
+ F32 magnification = focal_length/(subject_distance-focal_length);
+
+ shader->uniform1f("focal_distance", -subject_distance/1000.f);
+ shader->uniform1f("blur_constant", blur_constant);
+ shader->uniform1f("tan_pixel_angle", tanf(1.f/LLDrawable::sCurPixelAngle));
+ shader->uniform1f("magnification", magnification);
+
+ S32 channel = shader->enableTexture(LLViewerShaderMgr::DEFERRED_DIFFUSE, LLTexUnit::TT_RECT_TEXTURE);
if (channel > -1)
{
mScreen.bindTexture(0, channel);
+ gGL.getTexUnit(0)->setTextureFilteringOption(LLTexUnit::TFO_BILINEAR);
}
+ //channel = shader->enableTexture(LLViewerShaderMgr::DEFERRED_DEPTH, LLTexUnit::TT_RECT_TEXTURE);
+ //if (channel > -1)
+ //{
+ //gGL.getTexUnit(channel)->setTextureFilteringOption(LLTexUnit::TFO_BILINEAR);
+ //}
gGL.begin(LLRender::TRIANGLE_STRIP);
gGL.texCoord2f(tc1.mV[0], tc1.mV[1]);
@@ -5664,11 +6316,10 @@ void LLPipeline::renderBloom(BOOL for_snapshot, F32 zoom_factor, int subfield)
gGL.end();
- unbindDeferredShader(gDeferredGIFinalProgram);
+ unbindDeferredShader(*shader);
}
else
{
-
if (res_mod > 1)
{
tc2 /= (F32) res_mod;
@@ -5716,7 +6367,7 @@ void LLPipeline::renderBloom(BOOL for_snapshot, F32 zoom_factor, int subfield)
gGL.getTexUnit(1)->bind(&mScreen);
gGL.getTexUnit(1)->activate();
- LLGLEnable multisample(GL_MULTISAMPLE_ARB);
+ LLGLEnable multisample(gSavedSettings.getU32("RenderFSAASamples") > 0 ? GL_MULTISAMPLE_ARB : 0);
buff->setBuffer(mask);
buff->drawArrays(LLRender::TRIANGLE_STRIP, 0, 3);
@@ -5726,16 +6377,41 @@ void LLPipeline::renderBloom(BOOL for_snapshot, F32 zoom_factor, int subfield)
gGL.getTexUnit(0)->activate();
gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
+ }
- if (LLRenderTarget::sUseFBO)
- { //copy depth buffer from mScreen to framebuffer
- LLRenderTarget::copyContentsToFramebuffer(mScreen, 0, 0, mScreen.getWidth(), mScreen.getHeight(),
- 0, 0, mScreen.getWidth(), mScreen.getHeight(), GL_DEPTH_BUFFER_BIT, GL_NEAREST);
- }
+ if (LLRenderTarget::sUseFBO)
+ { //copy depth buffer from mScreen to framebuffer
+ LLRenderTarget::copyContentsToFramebuffer(mScreen, 0, 0, mScreen.getWidth(), mScreen.getHeight(),
+ 0, 0, mScreen.getWidth(), mScreen.getHeight(), GL_DEPTH_BUFFER_BIT, GL_NEAREST);
}
-
gGL.setSceneBlendType(LLRender::BT_ALPHA);
+
+ if (hasRenderDebugMask(LLPipeline::RENDER_DEBUG_PHYSICS_SHAPES))
+ {
+ LLVector2 tc1(0,0);
+ LLVector2 tc2((F32) gViewerWindow->getWorldViewWidthRaw()*2,
+ (F32) gViewerWindow->getWorldViewHeightRaw()*2);
+
+ LLGLEnable blend(GL_BLEND);
+ gGL.color4f(1,1,1,0.75f);
+
+ gGL.getTexUnit(0)->bind(&mPhysicsDisplay);
+
+ gGL.begin(LLRender::TRIANGLE_STRIP);
+ gGL.texCoord2f(tc1.mV[0], tc1.mV[1]);
+ gGL.vertex2f(-1,-1);
+
+ gGL.texCoord2f(tc1.mV[0], tc2.mV[1]);
+ gGL.vertex2f(-1,3);
+
+ gGL.texCoord2f(tc2.mV[0], tc1.mV[1]);
+ gGL.vertex2f(3,-1);
+
+ gGL.end();
+ gGL.flush();
+ }
+
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
@@ -6118,6 +6794,7 @@ void LLPipeline::bindDeferredShader(LLGLSLShader& shader, U32 light_index, LLRen
shader.uniform2f("proj_shadow_res", mShadow[4].getWidth(), mShadow[4].getHeight());
shader.uniform1f("depth_cutoff", gSavedSettings.getF32("RenderEdgeDepthCutoff"));
shader.uniform1f("norm_cutoff", gSavedSettings.getF32("RenderEdgeNormCutoff"));
+
if (shader.getUniformLocation("norm_mat") >= 0)
{
@@ -6155,7 +6832,7 @@ void LLPipeline::renderDeferredLighting()
0, 0, mDeferredDepth.getWidth(), mDeferredDepth.getHeight(), GL_DEPTH_BUFFER_BIT, GL_NEAREST);
}
- LLGLEnable multisample(GL_MULTISAMPLE_ARB);
+ LLGLEnable multisample(gSavedSettings.getU32("RenderFSAASamples") > 0 ? GL_MULTISAMPLE_ARB : 0);
if (gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_HUD))
{
@@ -6194,16 +6871,15 @@ void LLPipeline::renderDeferredLighting()
glTexCoord4f(tc.v[0], tc.v[1], tc.v[2], 0);
}
- glPushMatrix();
- glLoadIdentity();
- glMatrixMode(GL_PROJECTION);
- glPushMatrix();
- glLoadIdentity();
-
- mDeferredLight[0].bindTarget();
+ glPushMatrix();
+ glLoadIdentity();
+ glMatrixMode(GL_PROJECTION);
+ glPushMatrix();
+ glLoadIdentity();
if (gSavedSettings.getBOOL("RenderDeferredSSAO") || gSavedSettings.getS32("RenderShadowDetail") > 0)
{
+ mDeferredLight[0].bindTarget();
{ //paint shadow/SSAO light map (direct lighting lightmap)
LLFastTimer ftm(FTM_SUN_SHADOW);
bindDeferredShader(gDeferredSunProgram, 0);
@@ -6244,16 +6920,9 @@ void LLPipeline::renderDeferredLighting()
unbindDeferredShader(gDeferredSunProgram);
}
- }
- else
- {
- glClearColor(1,1,1,1);
- mDeferredLight[0].clear(GL_COLOR_BUFFER_BIT);
- glClearColor(0,0,0,0);
- }
-
mDeferredLight[0].flush();
-
+ }
+
{ //global illumination specific block (still experimental)
if (gSavedSettings.getBOOL("RenderDeferredBlurLight") &&
gSavedSettings.getBOOL("RenderDeferredGI"))
@@ -6296,7 +6965,7 @@ void LLPipeline::renderDeferredLighting()
mLuminanceMap.flush();
gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, mLuminanceMap.getTexture(), true);
gGL.getTexUnit(0)->setTextureFilteringOption(LLTexUnit::TFO_TRILINEAR);
- glGenerateMipmapEXT(GL_TEXTURE_2D);
+ glGenerateMipmap(GL_TEXTURE_2D);
}
}
@@ -6359,75 +7028,74 @@ void LLPipeline::renderDeferredLighting()
}
if (gSavedSettings.getBOOL("RenderDeferredSSAO"))
- { //soften direct lighting lightmap
- LLFastTimer ftm(FTM_SOFTEN_SHADOW);
- //blur lightmap
- mDeferredLight[1].bindTarget();
+ { //soften direct lighting lightmap
+ LLFastTimer ftm(FTM_SOFTEN_SHADOW);
+ //blur lightmap
+ mDeferredLight[1].bindTarget();
- glClearColor(1,1,1,1);
- mDeferredLight[1].clear(GL_COLOR_BUFFER_BIT);
- glClearColor(0,0,0,0);
-
- bindDeferredShader(gDeferredBlurLightProgram);
+ glClearColor(1,1,1,1);
+ mDeferredLight[1].clear(GL_COLOR_BUFFER_BIT);
+ glClearColor(0,0,0,0);
+
+ bindDeferredShader(gDeferredBlurLightProgram);
- LLVector3 go = gSavedSettings.getVector3("RenderShadowGaussian");
- const U32 kern_length = 4;
- F32 blur_size = gSavedSettings.getF32("RenderShadowBlurSize");
- F32 dist_factor = gSavedSettings.getF32("RenderShadowBlurDistFactor");
+ LLVector3 go = gSavedSettings.getVector3("RenderShadowGaussian");
+ const U32 kern_length = 4;
+ F32 blur_size = gSavedSettings.getF32("RenderShadowBlurSize");
+ F32 dist_factor = gSavedSettings.getF32("RenderShadowBlurDistFactor");
- // sample symmetrically with the middle sample falling exactly on 0.0
- F32 x = 0.f;
+ // sample symmetrically with the middle sample falling exactly on 0.0
+ F32 x = 0.f;
- LLVector3 gauss[32]; // xweight, yweight, offset
+ LLVector3 gauss[32]; // xweight, yweight, offset
- for (U32 i = 0; i < kern_length; i++)
- {
- gauss[i].mV[0] = llgaussian(x, go.mV[0]);
- gauss[i].mV[1] = llgaussian(x, go.mV[1]);
- gauss[i].mV[2] = x;
- x += 1.f;
- }
+ for (U32 i = 0; i < kern_length; i++)
+ {
+ gauss[i].mV[0] = llgaussian(x, go.mV[0]);
+ gauss[i].mV[1] = llgaussian(x, go.mV[1]);
+ gauss[i].mV[2] = x;
+ x += 1.f;
+ }
- gDeferredBlurLightProgram.uniform2f("delta", 1.f, 0.f);
- gDeferredBlurLightProgram.uniform1f("dist_factor", dist_factor);
- gDeferredBlurLightProgram.uniform3fv("kern[0]", kern_length, gauss[0].mV);
- gDeferredBlurLightProgram.uniform3fv("kern", kern_length, gauss[0].mV);
- gDeferredBlurLightProgram.uniform1f("kern_scale", blur_size * (kern_length/2.f - 0.5f));
+ gDeferredBlurLightProgram.uniform2f("delta", 1.f, 0.f);
+ gDeferredBlurLightProgram.uniform1f("dist_factor", dist_factor);
+ gDeferredBlurLightProgram.uniform3fv("kern", kern_length, gauss[0].mV);
+ gDeferredBlurLightProgram.uniform1f("kern_scale", blur_size * (kern_length/2.f - 0.5f));
+
+ {
+ LLGLDisable blend(GL_BLEND);
+ LLGLDepthTest depth(GL_TRUE, GL_FALSE, GL_ALWAYS);
+ stop_glerror();
+ glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
+ stop_glerror();
+ }
- {
- LLGLDisable blend(GL_BLEND);
- LLGLDepthTest depth(GL_TRUE, GL_FALSE, GL_ALWAYS);
- stop_glerror();
- glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
- stop_glerror();
- }
-
- mDeferredLight[1].flush();
- unbindDeferredShader(gDeferredBlurLightProgram);
+ mDeferredLight[1].flush();
+ unbindDeferredShader(gDeferredBlurLightProgram);
- bindDeferredShader(gDeferredBlurLightProgram, 1);
- mDeferredLight[0].bindTarget();
+ bindDeferredShader(gDeferredBlurLightProgram, 1);
+ mDeferredLight[0].bindTarget();
- gDeferredBlurLightProgram.uniform2f("delta", 0.f, 1.f);
+ gDeferredBlurLightProgram.uniform2f("delta", 0.f, 1.f);
- {
- LLGLDisable blend(GL_BLEND);
- LLGLDepthTest depth(GL_TRUE, GL_FALSE, GL_ALWAYS);
- stop_glerror();
- glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
- stop_glerror();
- }
- mDeferredLight[0].flush();
- unbindDeferredShader(gDeferredBlurLightProgram);
+ {
+ LLGLDisable blend(GL_BLEND);
+ LLGLDepthTest depth(GL_TRUE, GL_FALSE, GL_ALWAYS);
+ stop_glerror();
+ glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
+ stop_glerror();
}
+ mDeferredLight[0].flush();
+ unbindDeferredShader(gDeferredBlurLightProgram);
+ }
- stop_glerror();
- glPopMatrix();
- stop_glerror();
- glMatrixMode(GL_MODELVIEW);
- stop_glerror();
- glPopMatrix();
- stop_glerror();
+ stop_glerror();
+ glPopMatrix();
+ stop_glerror();
+ glMatrixMode(GL_MODELVIEW);
+ stop_glerror();
+ glPopMatrix();
+ stop_glerror();
//copy depth and stencil from deferred screen
//mScreen.copyContents(mDeferredScreen, 0, 0, mDeferredScreen.getWidth(), mDeferredScreen.getHeight(),
@@ -6493,10 +7161,8 @@ void LLPipeline::renderDeferredLighting()
gPipeline.popRenderTypeMask();
}
- BOOL render_local = gSavedSettings.getBOOL("RenderDeferredLocalLights");
- BOOL render_fullscreen = gSavedSettings.getBOOL("RenderDeferredFullscreenLights");
-
-
+ BOOL render_local = gSavedSettings.getBOOL("RenderLocalLights");
+
if (LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_DEFERRED) > 2)
{
mDeferredLight[1].flush();
@@ -6504,7 +7170,7 @@ void LLPipeline::renderDeferredLighting()
mDeferredLight[2].clear(GL_COLOR_BUFFER_BIT);
}
- if (render_local || render_fullscreen)
+ if (render_local)
{
gGL.setSceneBlendType(LLRender::BT_ADD);
std::list<LLVector4> fullscreen_lights;
@@ -6518,10 +7184,11 @@ void LLPipeline::renderDeferredLighting()
std::list<LLVector4> light_colors;
+ LLVertexBuffer::unbind();
+
F32 v[24];
glVertexPointer(3, GL_FLOAT, 0, v);
- BOOL render_local = gSavedSettings.getBOOL("RenderDeferredLocalLights");
-
+
{
bindDeferredShader(gDeferredLightProgram);
LLGLDepthTest depth(GL_TRUE, GL_FALSE);
@@ -6544,8 +7211,9 @@ void LLPipeline::renderDeferredLighting()
}
- LLVector3 center = drawablep->getPositionAgent();
- F32* c = center.mV;
+ LLVector4a center;
+ center.load3(drawablep->getPositionAgent().mV);
+ const F32* c = center.getF32ptr();
F32 s = volume->getLightRadius()*1.5f;
LLColor3 col = volume->getLightColor();
@@ -6561,7 +7229,9 @@ void LLPipeline::renderDeferredLighting()
continue;
}
- if (camera->AABBInFrustumNoFarClip(center, LLVector3(s,s,s)) == 0)
+ LLVector4a sa;
+ sa.splat(s);
+ if (camera->AABBInFrustumNoFarClip(center, sa) == 0)
{
continue;
}
@@ -6605,11 +7275,11 @@ void LLPipeline::renderDeferredLighting()
glTexCoord4f(tc.v[0], tc.v[1], tc.v[2], s*s);
glColor4f(col.mV[0], col.mV[1], col.mV[2], volume->getLightFalloff()*0.5f);
glDrawRangeElements(GL_TRIANGLE_FAN, 0, 7, 8,
- GL_UNSIGNED_BYTE, get_box_fan_indices(camera, center));
+ GL_UNSIGNED_BYTE, get_box_fan_indices_ptr(camera, center));
stop_glerror();
}
}
- else if (render_fullscreen)
+ else
{
if (volume->isLightSpotlight())
{
@@ -6639,8 +7309,9 @@ void LLPipeline::renderDeferredLighting()
LLVOVolume* volume = drawablep->getVOVolume();
- LLVector3 center = drawablep->getPositionAgent();
- F32* c = center.mV;
+ LLVector4a center;
+ center.load3(drawablep->getPositionAgent().mV);
+ const F32* c = center.getF32ptr();
F32 s = volume->getLightRadius()*1.5f;
sVisibleLightCount++;
@@ -6670,7 +7341,7 @@ void LLPipeline::renderDeferredLighting()
glTexCoord4f(tc.v[0], tc.v[1], tc.v[2], s*s);
glColor4f(col.mV[0], col.mV[1], col.mV[2], volume->getLightFalloff()*0.5f);
glDrawRangeElements(GL_TRIANGLE_FAN, 0, 7, 8,
- GL_UNSIGNED_BYTE, get_box_fan_indices(camera, center));
+ GL_UNSIGNED_BYTE, get_box_fan_indices_ptr(camera, center));
}
gDeferredSpotLightProgram.disableTexture(LLViewerShaderMgr::DEFERRED_PROJECTION);
unbindDeferredShader(gDeferredSpotLightProgram);
@@ -6712,9 +7383,7 @@ void LLPipeline::renderDeferredLighting()
if (count == max_count || fullscreen_lights.empty())
{
gDeferredMultiLightProgram.uniform1i("light_count", count);
- gDeferredMultiLightProgram.uniform4fv("light[0]", count, (GLfloat*) light);
gDeferredMultiLightProgram.uniform4fv("light", count, (GLfloat*) light);
- gDeferredMultiLightProgram.uniform4fv("light_col[0]", count, (GLfloat*) col);
gDeferredMultiLightProgram.uniform4fv("light_col", count, (GLfloat*) col);
gDeferredMultiLightProgram.uniform1f("far_z", far_z);
far_z = 0.f;
@@ -7082,11 +7751,6 @@ void LLPipeline::generateWaterReflection(LLCamera& camera_in)
LLCamera camera = camera_in;
camera.setFar(camera.getFar()*0.87654321f);
LLPipeline::sReflectionRender = TRUE;
- S32 occlusion = LLPipeline::sUseOcclusion;
-
- LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WORLD;
-
- LLPipeline::sUseOcclusion = llmin(occlusion, 1);
gPipeline.pushRenderTypeMask();
@@ -7125,19 +7789,20 @@ void LLPipeline::generateWaterReflection(LLCamera& camera_in)
gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
glClearColor(0,0,0,0);
mWaterRef.bindTarget();
+ LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WATER0;
gGL.setColorMask(true, true);
mWaterRef.clear();
gGL.setColorMask(true, false);
mWaterRef.getViewport(gGLViewport);
-
+
stop_glerror();
glPushMatrix();
mat.set_scale(glh::vec3f(1,1,-1));
mat.set_translate(glh::vec3f(0,0,height*2.f));
-
+
glh::matrix4f current = glh_get_current_modelview();
mat = current * mat;
@@ -7157,47 +7822,51 @@ void LLPipeline::generateWaterReflection(LLCamera& camera_in)
glCullFace(GL_FRONT);
static LLCullResult ref_result;
-
+
if (LLDrawPoolWater::sNeedsDistortionUpdate)
{
//initial sky pass (no user clip plane)
{ //mask out everything but the sky
gPipeline.pushRenderTypeMask();
gPipeline.andRenderTypeMask(LLPipeline::RENDER_TYPE_SKY,
- LLPipeline::RENDER_TYPE_WL_SKY,
- LLPipeline::END_RENDER_TYPES);
+ LLPipeline::RENDER_TYPE_WL_SKY,
+ LLPipeline::END_RENDER_TYPES);
+
static LLCullResult result;
updateCull(camera, result);
stateSort(camera, result);
+
andRenderTypeMask(LLPipeline::RENDER_TYPE_SKY,
- LLPipeline::RENDER_TYPE_CLOUDS,
- LLPipeline::RENDER_TYPE_WL_SKY,
- LLPipeline::END_RENDER_TYPES);
+ LLPipeline::RENDER_TYPE_CLOUDS,
+ LLPipeline::RENDER_TYPE_WL_SKY,
+ LLPipeline::END_RENDER_TYPES);
+ //bad pop here
renderGeom(camera, TRUE);
+
gPipeline.popRenderTypeMask();
}
gPipeline.pushRenderTypeMask();
clearRenderTypeMask(LLPipeline::RENDER_TYPE_WATER,
- LLPipeline::RENDER_TYPE_VOIDWATER,
- LLPipeline::RENDER_TYPE_GROUND,
- LLPipeline::RENDER_TYPE_SKY,
- LLPipeline::RENDER_TYPE_CLOUDS,
- LLPipeline::END_RENDER_TYPES);
+ LLPipeline::RENDER_TYPE_VOIDWATER,
+ LLPipeline::RENDER_TYPE_GROUND,
+ LLPipeline::RENDER_TYPE_SKY,
+ LLPipeline::RENDER_TYPE_CLOUDS,
+ LLPipeline::END_RENDER_TYPES);
- S32 detail = gSavedSettings.getS32("RenderReflectionDetail");
+ S32 detail = gSavedSettings.getS32("RenderReflectionDetail");
if (detail > 0)
{ //mask out selected geometry based on reflection detail
if (detail < 4)
{
clearRenderTypeMask(LLPipeline::RENDER_TYPE_PARTICLES, END_RENDER_TYPES);
- if (detail < 3)
- {
- clearRenderTypeMask(LLPipeline::RENDER_TYPE_AVATAR, END_RENDER_TYPES);
- if (detail < 2)
+ if (detail < 3)
{
+ clearRenderTypeMask(LLPipeline::RENDER_TYPE_AVATAR, END_RENDER_TYPES);
+ if (detail < 2)
+ {
clearRenderTypeMask(LLPipeline::RENDER_TYPE_VOLUME, END_RENDER_TYPES);
}
}
@@ -7207,17 +7876,17 @@ void LLPipeline::generateWaterReflection(LLCamera& camera_in)
LLGLDisable cull(GL_CULL_FACE);
updateCull(camera, ref_result, 1);
stateSort(camera, ref_result);
- }
-
- if (LLDrawPoolWater::sNeedsDistortionUpdate)
- {
- if (gSavedSettings.getS32("RenderReflectionDetail") > 0)
+ }
+
+ if (LLDrawPoolWater::sNeedsDistortionUpdate)
{
- gPipeline.grabReferences(ref_result);
- LLGLUserClipPlane clip_plane(plane, mat, projection);
- renderGeom(camera);
- }
- }
+ if (gSavedSettings.getS32("RenderReflectionDetail") > 0)
+ {
+ gPipeline.grabReferences(ref_result);
+ LLGLUserClipPlane clip_plane(plane, mat, projection);
+ renderGeom(camera);
+ }
+ }
gPipeline.popRenderTypeMask();
}
@@ -7255,6 +7924,7 @@ void LLPipeline::generateWaterReflection(LLCamera& camera_in)
LLColor4& col = LLDrawPoolWater::sWaterFogColor;
glClearColor(col.mV[0], col.mV[1], col.mV[2], 0.f);
mWaterDis.bindTarget();
+ LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WATER1;
mWaterDis.getViewport(gGLViewport);
if (!LLPipeline::sUnderWaterRender || LLDrawPoolWater::sNeedsReflectionUpdate)
@@ -7291,8 +7961,8 @@ void LLPipeline::generateWaterReflection(LLCamera& camera_in)
gPipeline.popRenderTypeMask();
LLDrawPoolWater::sNeedsReflectionUpdate = FALSE;
LLDrawPoolWater::sNeedsDistortionUpdate = FALSE;
- LLViewerCamera::getInstance()->setUserClipPlane(LLPlane(-pnorm, -pd));
- LLPipeline::sUseOcclusion = occlusion;
+ LLPlane npnorm(-pnorm, -pd);
+ LLViewerCamera::getInstance()->setUserClipPlane(npnorm);
LLGLState::checkStates();
LLGLState::checkTextureChannels();
@@ -7302,6 +7972,8 @@ void LLPipeline::generateWaterReflection(LLCamera& camera_in)
{
gAgentAvatarp->updateAttachmentVisibility(gAgentCamera.getCameraMode());
}
+
+ LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_WORLD;
}
}
@@ -7404,14 +8076,14 @@ void LLPipeline::renderShadow(glh::matrix4f& view, glh::matrix4f& proj, LLCamera
glLoadMatrixf(proj.m);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
- glLoadMatrixf(view.m);
+ glLoadMatrixd(gGLModelView);
stop_glerror();
gGLLastMatrix = NULL;
{
- LLGLDepthTest depth(GL_TRUE);
- glClear(GL_DEPTH_BUFFER_BIT);
+ //LLGLDepthTest depth(GL_TRUE);
+ //glClear(GL_DEPTH_BUFFER_BIT);
}
gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
@@ -7424,6 +8096,8 @@ void LLPipeline::renderShadow(glh::matrix4f& view, glh::matrix4f& proj, LLCamera
//glCullFace(GL_FRONT);
+ LLVertexBuffer::unbind();
+
{
LLFastTimer ftm(FTM_SHADOW_SIMPLE);
LLGLDisable test(GL_ALPHA_TEST);
@@ -7491,14 +8165,13 @@ BOOL LLPipeline::getVisiblePointCloud(LLCamera& camera, LLVector3& min, LLVector
}
//get set of planes on bounding box
- std::vector<LLPlane> bp;
-
- bp.push_back(LLPlane(min, LLVector3(-1,0,0)));
- bp.push_back(LLPlane(min, LLVector3(0,-1,0)));
- bp.push_back(LLPlane(min, LLVector3(0,0,-1)));
- bp.push_back(LLPlane(max, LLVector3(1,0,0)));
- bp.push_back(LLPlane(max, LLVector3(0,1,0)));
- bp.push_back(LLPlane(max, LLVector3(0,0,1)));
+ LLPlane bp[] = {
+ LLPlane(min, LLVector3(-1,0,0)),
+ LLPlane(min, LLVector3(0,-1,0)),
+ LLPlane(min, LLVector3(0,0,-1)),
+ LLPlane(max, LLVector3(1,0,0)),
+ LLPlane(max, LLVector3(0,1,0)),
+ LLPlane(max, LLVector3(0,0,1))};
//potential points
std::vector<LLVector3> pp;
@@ -7546,7 +8219,8 @@ BOOL LLPipeline::getVisiblePointCloud(LLCamera& camera, LLVector3& min, LLVector
const LLPlane& cp = camera.getAgentPlane(j);
const LLVector3& v1 = pp[bs[i*2+0]];
const LLVector3& v2 = pp[bs[i*2+1]];
- const LLVector3 n(cp.mV);
+ LLVector3 n;
+ cp.getVector3(n);
LLVector3 line = v1-v2;
@@ -7560,8 +8234,8 @@ BOOL LLPipeline::getVisiblePointCloud(LLCamera& camera, LLVector3& min, LLVector
LLVector3 intersect = v2+line*t;
pp.push_back(intersect);
}
- }
}
+ }
//camera frustum line segments
const U32 fs[] =
@@ -7569,7 +8243,7 @@ BOOL LLPipeline::getVisiblePointCloud(LLCamera& camera, LLVector3& min, LLVector
0,1,
1,2,
2,3,
- 3,1,
+ 3,0,
4,5,
5,6,
@@ -7592,7 +8266,8 @@ BOOL LLPipeline::getVisiblePointCloud(LLCamera& camera, LLVector3& min, LLVector
const LLVector3& v1 = pp[fs[i*2+0]+8];
const LLVector3& v2 = pp[fs[i*2+1]+8];
const LLPlane& cp = bp[j];
- const LLVector3 n(cp.mV);
+ LLVector3 n;
+ cp.getVector3(n);
LLVector3 line = v1-v2;
@@ -7607,7 +8282,7 @@ BOOL LLPipeline::getVisiblePointCloud(LLCamera& camera, LLVector3& min, LLVector
pp.push_back(intersect);
}
}
- }
+ }
LLVector3 ext[] = { min-LLVector3(0.05f,0.05f,0.05f),
max+LLVector3(0.05f,0.05f,0.05f) };
@@ -7971,6 +8646,14 @@ void LLPipeline::generateSunShadow(LLCamera& camera)
LLVector3 n = gSavedSettings.getVector3("RenderShadowNearDist");
//F32 nearDist[] = { n.mV[0], n.mV[1], n.mV[2], n.mV[2] };
+ //put together a universal "near clip" plane for shadow frusta
+ LLPlane shadow_near_clip;
+ {
+ LLVector3 p = gAgent.getPositionAgent();
+ p += mSunDir * gSavedSettings.getF32("RenderFarClip")*2.f;
+ shadow_near_clip.setVec(p, mSunDir);
+ }
+
LLVector3 lightDir = -mSunDir;
lightDir.normVec();
@@ -8405,7 +9088,8 @@ void LLPipeline::generateSunShadow(LLCamera& camera)
LLViewerCamera::updateFrustumPlanes(shadow_cam, FALSE, FALSE, TRUE);
- shadow_cam.ignoreAgentFrustumPlane(LLCamera::AGENT_PLANE_NEAR);
+ //shadow_cam.ignoreAgentFrustumPlane(LLCamera::AGENT_PLANE_NEAR);
+ shadow_cam.getAgentPlane(LLCamera::AGENT_PLANE_NEAR).set(shadow_near_clip);
//translate and scale to from [-1, 1] to [0, 1]
glh::matrix4f trans(0.5f, 0.f, 0.f, 0.5f,
@@ -8432,7 +9116,8 @@ void LLPipeline::generateSunShadow(LLCamera& camera)
mShadow[j].bindTarget();
mShadow[j].getViewport(gGLViewport);
-
+ mShadow[j].clear();
+
{
static LLCullResult result[4];
@@ -8451,152 +9136,138 @@ void LLPipeline::generateSunShadow(LLCamera& camera)
//hack to disable projector shadows
- static bool clear = true;
bool gen_shadow = gSavedSettings.getS32("RenderShadowDetail") > 1;
if (gen_shadow)
{
- clear = true;
- F32 fade_amt = gFrameIntervalSeconds * llmax(LLViewerCamera::getInstance()->getVelocityStat()->getCurrentPerSec(), 1.f);
-
- //update shadow targets
- for (U32 i = 0; i < 2; i++)
- { //for each current shadow
- LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_SHADOW4+i;
+ F32 fade_amt = gFrameIntervalSeconds * llmax(LLViewerCamera::getInstance()->getVelocityStat()->getCurrentPerSec(), 1.f);
- if (mShadowSpotLight[i].notNull() &&
- (mShadowSpotLight[i] == mTargetShadowSpotLight[0] ||
- mShadowSpotLight[i] == mTargetShadowSpotLight[1]))
- { //keep this spotlight
- mSpotLightFade[i] = llmin(mSpotLightFade[i]+fade_amt, 1.f);
- }
- else
- { //fade out this light
- mSpotLightFade[i] = llmax(mSpotLightFade[i]-fade_amt, 0.f);
-
- if (mSpotLightFade[i] == 0.f || mShadowSpotLight[i].isNull())
- { //faded out, grab one of the pending spots (whichever one isn't already taken)
- if (mTargetShadowSpotLight[0] != mShadowSpotLight[(i+1)%2])
- {
- mShadowSpotLight[i] = mTargetShadowSpotLight[0];
- }
- else
- {
- mShadowSpotLight[i] = mTargetShadowSpotLight[1];
+ //update shadow targets
+ for (U32 i = 0; i < 2; i++)
+ { //for each current shadow
+ LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_SHADOW4+i;
+
+ if (mShadowSpotLight[i].notNull() &&
+ (mShadowSpotLight[i] == mTargetShadowSpotLight[0] ||
+ mShadowSpotLight[i] == mTargetShadowSpotLight[1]))
+ { //keep this spotlight
+ mSpotLightFade[i] = llmin(mSpotLightFade[i]+fade_amt, 1.f);
+ }
+ else
+ { //fade out this light
+ mSpotLightFade[i] = llmax(mSpotLightFade[i]-fade_amt, 0.f);
+
+ if (mSpotLightFade[i] == 0.f || mShadowSpotLight[i].isNull())
+ { //faded out, grab one of the pending spots (whichever one isn't already taken)
+ if (mTargetShadowSpotLight[0] != mShadowSpotLight[(i+1)%2])
+ {
+ mShadowSpotLight[i] = mTargetShadowSpotLight[0];
+ }
+ else
+ {
+ mShadowSpotLight[i] = mTargetShadowSpotLight[1];
+ }
}
}
}
- }
- for (S32 i = 0; i < 2; i++)
- {
- glh_set_current_modelview(saved_view);
- glh_set_current_projection(saved_proj);
-
- if (mShadowSpotLight[i].isNull())
+ for (S32 i = 0; i < 2; i++)
{
- continue;
- }
+ glh_set_current_modelview(saved_view);
+ glh_set_current_projection(saved_proj);
- LLVOVolume* volume = mShadowSpotLight[i]->getVOVolume();
+ if (mShadowSpotLight[i].isNull())
+ {
+ continue;
+ }
- if (!volume)
- {
- mShadowSpotLight[i] = NULL;
- continue;
- }
+ LLVOVolume* volume = mShadowSpotLight[i]->getVOVolume();
- LLDrawable* drawable = mShadowSpotLight[i];
+ if (!volume)
+ {
+ mShadowSpotLight[i] = NULL;
+ continue;
+ }
- LLVector3 params = volume->getSpotLightParams();
- F32 fov = params.mV[0];
+ LLDrawable* drawable = mShadowSpotLight[i];
- //get agent->light space matrix (modelview)
- LLVector3 center = drawable->getPositionAgent();
- LLQuaternion quat = volume->getRenderRotation();
+ LLVector3 params = volume->getSpotLightParams();
+ F32 fov = params.mV[0];
- //get near clip plane
- LLVector3 scale = volume->getScale();
- LLVector3 at_axis(0,0,-scale.mV[2]*0.5f);
- at_axis *= quat;
+ //get agent->light space matrix (modelview)
+ LLVector3 center = drawable->getPositionAgent();
+ LLQuaternion quat = volume->getRenderRotation();
- LLVector3 np = center+at_axis;
- at_axis.normVec();
+ //get near clip plane
+ LLVector3 scale = volume->getScale();
+ LLVector3 at_axis(0,0,-scale.mV[2]*0.5f);
+ at_axis *= quat;
- //get origin that has given fov for plane np, at_axis, and given scale
- F32 dist = (scale.mV[1]*0.5f)/tanf(fov*0.5f);
+ LLVector3 np = center+at_axis;
+ at_axis.normVec();
- LLVector3 origin = np - at_axis*dist;
+ //get origin that has given fov for plane np, at_axis, and given scale
+ F32 dist = (scale.mV[1]*0.5f)/tanf(fov*0.5f);
- LLMatrix4 mat(quat, LLVector4(origin, 1.f));
+ LLVector3 origin = np - at_axis*dist;
- view[i+4] = glh::matrix4f((F32*) mat.mMatrix);
+ LLMatrix4 mat(quat, LLVector4(origin, 1.f));
- view[i+4] = view[i+4].inverse();
+ view[i+4] = glh::matrix4f((F32*) mat.mMatrix);
- //get perspective matrix
- F32 near_clip = dist+0.01f;
- F32 width = scale.mV[VX];
- F32 height = scale.mV[VY];
- F32 far_clip = dist+volume->getLightRadius()*1.5f;
+ view[i+4] = view[i+4].inverse();
- F32 fovy = fov * RAD_TO_DEG;
- F32 aspect = width/height;
-
- proj[i+4] = gl_perspective(fovy, aspect, near_clip, far_clip);
+ //get perspective matrix
+ F32 near_clip = dist+0.01f;
+ F32 width = scale.mV[VX];
+ F32 height = scale.mV[VY];
+ F32 far_clip = dist+volume->getLightRadius()*1.5f;
- //translate and scale to from [-1, 1] to [0, 1]
- glh::matrix4f trans(0.5f, 0.f, 0.f, 0.5f,
- 0.f, 0.5f, 0.f, 0.5f,
- 0.f, 0.f, 0.5f, 0.5f,
- 0.f, 0.f, 0.f, 1.f);
+ F32 fovy = fov * RAD_TO_DEG;
+ F32 aspect = width/height;
+
+ proj[i+4] = gl_perspective(fovy, aspect, near_clip, far_clip);
- glh_set_current_modelview(view[i+4]);
- glh_set_current_projection(proj[i+4]);
+ //translate and scale to from [-1, 1] to [0, 1]
+ glh::matrix4f trans(0.5f, 0.f, 0.f, 0.5f,
+ 0.f, 0.5f, 0.f, 0.5f,
+ 0.f, 0.f, 0.5f, 0.5f,
+ 0.f, 0.f, 0.f, 1.f);
- mSunShadowMatrix[i+4] = trans*proj[i+4]*view[i+4]*inv_view;
-
- for (U32 j = 0; j < 16; j++)
- {
- gGLLastModelView[j] = mShadowModelview[i+4].m[j];
- gGLLastProjection[j] = mShadowProjection[i+4].m[j];
- }
+ glh_set_current_modelview(view[i+4]);
+ glh_set_current_projection(proj[i+4]);
- mShadowModelview[i+4] = view[i+4];
- mShadowProjection[i+4] = proj[i+4];
+ mSunShadowMatrix[i+4] = trans*proj[i+4]*view[i+4]*inv_view;
+
+ for (U32 j = 0; j < 16; j++)
+ {
+ gGLLastModelView[j] = mShadowModelview[i+4].m[j];
+ gGLLastProjection[j] = mShadowProjection[i+4].m[j];
+ }
- LLCamera shadow_cam = camera;
- shadow_cam.setFar(far_clip);
- shadow_cam.setOrigin(origin);
+ mShadowModelview[i+4] = view[i+4];
+ mShadowProjection[i+4] = proj[i+4];
- LLViewerCamera::updateFrustumPlanes(shadow_cam, FALSE, FALSE, TRUE);
+ LLCamera shadow_cam = camera;
+ shadow_cam.setFar(far_clip);
+ shadow_cam.setOrigin(origin);
- stop_glerror();
+ LLViewerCamera::updateFrustumPlanes(shadow_cam, FALSE, FALSE, TRUE);
- mShadow[i+4].bindTarget();
- mShadow[i+4].getViewport(gGLViewport);
+ stop_glerror();
- static LLCullResult result[2];
+ mShadow[i+4].bindTarget();
+ mShadow[i+4].getViewport(gGLViewport);
+ mShadow[i+4].clear();
- LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_SHADOW0+i+4;
+ static LLCullResult result[2];
- renderShadow(view[i+4], proj[i+4], shadow_cam, result[i], FALSE, FALSE);
+ LLViewerCamera::sCurCameraID = LLViewerCamera::CAMERA_SHADOW0+i+4;
- mShadow[i+4].flush();
- }
- }
- else
- {
- if (clear)
- {
- clear = false;
- for (U32 i = 4; i < 6; i++)
- {
- mShadow[i].bindTarget();
- mShadow[i].clear();
- mShadow[i].flush();
- }
- }
+ renderShadow(view[i+4], proj[i+4], shadow_cam, result[i], FALSE, FALSE);
+
+ mShadow[i+4].flush();
+ }
}
if (!gSavedSettings.getBOOL("CameraOffset"))
@@ -8716,7 +9387,7 @@ void LLPipeline::generateImpostor(LLVOAvatar* avatar)
stateSort(*LLViewerCamera::getInstance(), result);
- const LLVector3* ext = avatar->mDrawable->getSpatialExtents();
+ const LLVector4a* ext = avatar->mDrawable->getSpatialExtents();
LLVector3 pos(avatar->getRenderPosition()+avatar->getImpostorOffset());
LLCamera camera = *viewer_camera;
@@ -8725,25 +9396,30 @@ void LLPipeline::generateImpostor(LLVOAvatar* avatar)
LLVector2 tdim;
- LLVector3 half_height = (ext[1]-ext[0])*0.5f;
- LLVector3 left = camera.getLeftAxis();
- left *= left;
- left.normalize();
+ LLVector4a half_height;
+ half_height.setSub(ext[1], ext[0]);
+ half_height.mul(0.5f);
+
+ LLVector4a left;
+ left.load3(camera.getLeftAxis().mV);
+ left.mul(left);
+ left.normalize3fast();
- LLVector3 up = camera.getUpAxis();
- up *= up;
- up.normalize();
+ LLVector4a up;
+ up.load3(camera.getUpAxis().mV);
+ up.mul(up);
+ up.normalize3fast();
- tdim.mV[0] = fabsf(half_height * left);
- tdim.mV[1] = fabsf(half_height * up);
+ tdim.mV[0] = fabsf(half_height.dot3(left).getF32());
+ tdim.mV[1] = fabsf(half_height.dot3(up).getF32());
glMatrixMode(GL_PROJECTION);
glPushMatrix();
- //glh::matrix4f ortho = gl_ortho(-tdim.mV[0], tdim.mV[0], -tdim.mV[1], tdim.mV[1], 1.0, 256.0);
+
F32 distance = (pos-camera.getOrigin()).length();
F32 fov = atanf(tdim.mV[1]/distance)*2.f*RAD_TO_DEG;
- F32 aspect = tdim.mV[0]/tdim.mV[1]; //128.f/256.f;
+ F32 aspect = tdim.mV[0]/tdim.mV[1];
glh::matrix4f persp = gl_perspective(fov, aspect, 1.f, 256.f);
glh_set_current_projection(persp);
glLoadMatrixf(persp.m);
@@ -8760,9 +9436,7 @@ void LLPipeline::generateImpostor(LLVOAvatar* avatar)
glClearColor(0.0f,0.0f,0.0f,0.0f);
gGL.setColorMask(true, true);
- glStencilMask(0xFFFFFFFF);
- glClearStencil(0);
-
+
// get the number of pixels per angle
F32 pa = gViewerWindow->getWindowHeightRaw() / (RAD_TO_DEG * viewer_camera->getView());
@@ -8773,7 +9447,7 @@ void LLPipeline::generateImpostor(LLVOAvatar* avatar)
if (!avatar->mImpostor.isComplete() || resX != avatar->mImpostor.getWidth() ||
resY != avatar->mImpostor.getHeight())
{
- avatar->mImpostor.allocate(resX,resY,GL_RGBA,TRUE,TRUE);
+ avatar->mImpostor.allocate(resX,resY,GL_RGBA,TRUE,FALSE);
if (LLPipeline::sRenderDeferred)
{
@@ -8785,43 +9459,30 @@ void LLPipeline::generateImpostor(LLVOAvatar* avatar)
gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
}
- LLGLEnable stencil(GL_STENCIL_TEST);
- glStencilMask(0xFFFFFFFF);
- glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);
- glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
+ avatar->mImpostor.bindTarget();
- {
- LLGLEnable scissor(GL_SCISSOR_TEST);
- glScissor(0, 0, resX, resY);
- avatar->mImpostor.bindTarget();
- avatar->mImpostor.clear();
- }
-
if (LLPipeline::sRenderDeferred)
{
- stop_glerror();
+ avatar->mImpostor.clear();
renderGeomDeferred(camera);
renderGeomPostDeferred(camera);
}
else
{
+ LLGLEnable scissor(GL_SCISSOR_TEST);
+ glScissor(0, 0, resX, resY);
+ avatar->mImpostor.clear();
renderGeom(camera);
}
- glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
- glStencilFunc(GL_EQUAL, 1, 0xFFFFFF);
-
- { //create alpha mask based on stencil buffer (grey out if muted)
- LLVector3 left = camera.getLeftAxis()*tdim.mV[0]*2.f;
- LLVector3 up = camera.getUpAxis()*tdim.mV[1]*2.f;
-
+ { //create alpha mask based on depth buffer (grey out if muted)
if (LLPipeline::sRenderDeferred)
{
- GLuint buff = GL_COLOR_ATTACHMENT0_EXT;
+ GLuint buff = GL_COLOR_ATTACHMENT0;
glDrawBuffersARB(1, &buff);
}
- LLGLEnable blend(muted ? 0 : GL_BLEND);
+ LLGLDisable blend(GL_BLEND);
if (muted)
{
@@ -8832,25 +9493,34 @@ void LLPipeline::generateImpostor(LLVOAvatar* avatar)
gGL.setColorMask(false, true);
}
- gGL.setSceneBlendType(LLRender::BT_ADD);
gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
- LLGLDepthTest depth(GL_FALSE, GL_FALSE);
+ LLGLDepthTest depth(GL_TRUE, GL_FALSE, GL_GREATER);
+
+ gGL.flush();
+
+ glPushMatrix();
+ glLoadIdentity();
+ glMatrixMode(GL_PROJECTION);
+ glPushMatrix();
+ glLoadIdentity();
+
+ static const F32 clip_plane = 0.99999f;
- gGL.color4f(1,1,1,1);
gGL.color4ub(64,64,64,255);
gGL.begin(LLRender::QUADS);
- gGL.vertex3fv((pos+left-up).mV);
- gGL.vertex3fv((pos-left-up).mV);
- gGL.vertex3fv((pos-left+up).mV);
- gGL.vertex3fv((pos+left+up).mV);
+ gGL.vertex3f(-1, -1, clip_plane);
+ gGL.vertex3f(1, -1, clip_plane);
+ gGL.vertex3f(1, 1, clip_plane);
+ gGL.vertex3f(-1, 1, clip_plane);
gGL.end();
gGL.flush();
- gGL.setSceneBlendType(LLRender::BT_ALPHA);
+ glPopMatrix();
+ glMatrixMode(GL_MODELVIEW);
+ glPopMatrix();
}
-
avatar->mImpostor.flush();
avatar->setImpostorDim(tdim);
diff --git a/indra/newview/pipeline.h b/indra/newview/pipeline.h
index e99b0d71e3..be58af947c 100644
--- a/indra/newview/pipeline.h
+++ b/indra/newview/pipeline.h
@@ -42,6 +42,10 @@
#include <stack>
+#include <stack>
+
+#include <stack>
+
class LLViewerTexture;
class LLEdge;
class LLFace;
@@ -54,6 +58,9 @@ class LLCubeMap;
class LLCullResult;
class LLVOAvatar;
class LLGLSLShader;
+class LLCurlRequest;
+
+class LLMeshResponder;
typedef enum e_avatar_skinning_method
{
@@ -107,11 +114,11 @@ public:
void resizeScreenTexture();
void releaseGLBuffers();
void createGLBuffers();
- void allocateScreenBuffer(U32 resX, U32 resY);
+ void allocateScreenBuffer(U32 resX, U32 resY);
+ void allocatePhysicsBuffer();
+
void resetVertexBuffers(LLDrawable* drawable);
- void setUseVBO(BOOL use_vbo);
- void setDisableVBOMapping(BOOL no_vbo_mapping);
void generateImpostor(LLVOAvatar* avatar);
void bindScreenToTexture();
void renderBloom(BOOL for_snapshot, F32 zoom_factor = 1.f, int subfield = 0);
@@ -211,6 +218,7 @@ public:
//calculate pixel area of given box from vantage point of given camera
static F32 calcPixelArea(LLVector3 center, LLVector3 size, LLCamera& camera);
+ static F32 calcPixelArea(const LLVector4a& center, const LLVector4a& size, LLCamera &camera);
void stateSort(LLCamera& camera, LLCullResult& result);
void stateSort(LLSpatialGroup* group, LLCamera& camera);
@@ -223,6 +231,14 @@ public:
void renderGroups(LLRenderPass* pass, U32 type, U32 mask, BOOL texture);
void grabReferences(LLCullResult& result);
+ void clearReferences();
+
+ //check references will assert that there are no references in sCullResult to the provided data
+ void checkReferences(LLFace* face);
+ void checkReferences(LLDrawable* drawable);
+ void checkReferences(LLDrawInfo* draw_info);
+ void checkReferences(LLSpatialGroup* group);
+
void renderGeom(LLCamera& camera, BOOL forceVBOUpdate = FALSE);
void renderGeomDeferred(LLCamera& camera);
@@ -245,6 +261,7 @@ public:
void generateGI(LLCamera& camera, LLVector3& lightDir, std::vector<LLVector3>& vpc);
void renderHighlights();
void renderDebug();
+ void renderPhysicsDisplay();
void rebuildPools(); // Rebuild pools
@@ -260,6 +277,7 @@ public:
void enableLightsStatic();
void enableLightsDynamic();
void enableLightsAvatar();
+ void enableLightsPreview();
void enableLightsAvatarEdit(const LLColor4& color);
void enableLightsFullbright(const LLColor4& color);
void disableLights();
@@ -303,6 +321,7 @@ public:
static BOOL toggleRenderTypeControlNegated(void* data);
static BOOL toggleRenderDebugControl(void* data);
static BOOL toggleRenderDebugFeatureControl(void* data);
+ static void setRenderDebugFeatureControl(U32 bit, bool value);
static void setRenderParticleBeacons(BOOL val);
static void toggleRenderParticleBeacons(void* data);
@@ -426,6 +445,9 @@ public:
RENDER_DEBUG_BUILD_QUEUE = 0x0200000,
RENDER_DEBUG_AGENT_TARGET = 0x0400000,
RENDER_DEBUG_UPDATE_TYPE = 0x0800000,
+ RENDER_DEBUG_PHYSICS_SHAPES = 0x1000000,
+ RENDER_DEBUG_NORMALS = 0x2000000,
+ RENDER_DEBUG_LOD_INFO = 0x4000000,
};
public:
@@ -448,6 +470,10 @@ public:
S32 mNumVisibleNodes;
S32 mVerticesRelit;
+ S32 mDebugTextureUploadCost;
+ S32 mDebugSculptUploadCost;
+ S32 mDebugMeshUploadCost;
+
S32 mLightingChanges;
S32 mGeometryChanges;
@@ -463,6 +489,8 @@ public:
static BOOL sAutoMaskAlphaNonDeferred;
static BOOL sDisableShaders; // if TRUE, rendering will be done without shaders
static BOOL sRenderBump;
+ static BOOL sBakeSunlight;
+ static BOOL sNoAlpha;
static BOOL sUseTriStrips;
static BOOL sUseFarClip;
static BOOL sShadowRender;
@@ -478,7 +506,6 @@ public:
static BOOL sRenderAttachedLights;
static BOOL sRenderAttachedParticles;
static BOOL sRenderDeferred;
- static BOOL sAllowRebuildPriorityGroup;
static S32 sVisibleLightCount;
static F32 sMinRenderSize;
@@ -497,6 +524,7 @@ public:
LLRenderTarget mGIMapPost[2];
LLRenderTarget mLuminanceMap;
LLRenderTarget mHighlight;
+ LLRenderTarget mPhysicsDisplay;
//sun shadow map
LLRenderTarget mShadow[6];
@@ -604,6 +632,8 @@ protected:
LLDrawable::drawable_list_t mBuildQ2; // non-priority
LLSpatialGroup::sg_vector_t mGroupQ1; //priority
LLSpatialGroup::sg_vector_t mGroupQ2; // non-priority
+ bool mGroupQ2Locked;
+ bool mGroupQ1Locked;
LLViewerObject::vobj_list_t mCreateQ;
diff --git a/indra/newview/skins/default/colors.xml b/indra/newview/skins/default/colors.xml
index 75aec21f93..7d767b9222 100644
--- a/indra/newview/skins/default/colors.xml
+++ b/indra/newview/skins/default/colors.xml
@@ -763,4 +763,10 @@
<color
name="MenuBarProjectBgColor"
reference="MdBlue" />
+ <color
+ name="MeshImportTableNormalColor"
+ value="1 1 1 1"/>
+ <color
+ name="MeshImportTableHighlightColor"
+ value="0.2 0.8 1 1"/>
</colors>
diff --git a/indra/newview/skins/default/textures/icons/Inv_Mesh.png b/indra/newview/skins/default/textures/icons/Inv_Mesh.png
new file mode 100644
index 0000000000..f1f21f7941
--- /dev/null
+++ b/indra/newview/skins/default/textures/icons/Inv_Mesh.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/icons/check_mark.png b/indra/newview/skins/default/textures/icons/check_mark.png
new file mode 100644
index 0000000000..2c05297f4f
--- /dev/null
+++ b/indra/newview/skins/default/textures/icons/check_mark.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/model_wizard/divider_line.png b/indra/newview/skins/default/textures/model_wizard/divider_line.png
new file mode 100644
index 0000000000..76c9e68767
--- /dev/null
+++ b/indra/newview/skins/default/textures/model_wizard/divider_line.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/model_wizard/progress_bar_bg.png b/indra/newview/skins/default/textures/model_wizard/progress_bar_bg.png
new file mode 100644
index 0000000000..d0b213cdc5
--- /dev/null
+++ b/indra/newview/skins/default/textures/model_wizard/progress_bar_bg.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/model_wizard/progress_light.png b/indra/newview/skins/default/textures/model_wizard/progress_light.png
new file mode 100644
index 0000000000..019344f812
--- /dev/null
+++ b/indra/newview/skins/default/textures/model_wizard/progress_light.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/textures.xml b/indra/newview/skins/default/textures/textures.xml
index cec2942b35..87d8e54a89 100644
--- a/indra/newview/skins/default/textures/textures.xml
+++ b/indra/newview/skins/default/textures/textures.xml
@@ -73,7 +73,22 @@ with the same filename but different name
<texture name="BackButton_Press" file_name="icons/back_arrow_press.png" preload="false" scale.left="22" scale.top="12" scale.right="25" scale.bottom="12" />
<texture name="Blank" file_name="Blank.png" preload="false" />
-
+
+ <texture name="BreadCrumbBtn_Left_Disabled" file_name="widgets/BreadCrumbBtn_Left_Disabled.png" preload="false"/>
+ <texture name="BreadCrumbBtn_Left_Off" file_name="widgets/BreadCrumbBtn_Left_Off.png" preload="false"/>
+ <texture name="BreadCrumbBtn_Left_Over" file_name="widgets/BreadCrumbBtn_Left_Over.png" preload="false"/>
+ <texture name="BreadCrumbBtn_Left_Press" file_name="widgets/BreadCrumbBtn_Left_Press.png" preload="false"/>
+
+ <texture name="BreadCrumbBtn_Middle_Disabled" file_name="widgets/BreadCrumbBtn_Middle_Disabled.png" preload="false"/>
+ <texture name="BreadCrumbBtn_Middle_Off" file_name="widgets/BreadCrumbBtn_Middle_Off.png" preload="false"/>
+ <texture name="BreadCrumbBtn_Middle_Over" file_name="widgets/BreadCrumbBtn_Middle_Over.png" preload="false"/>
+ <texture name="BreadCrumbBtn_Middle_Press" file_name="widgets/BreadCrumbBtn_Middle_Press.png" preload="false"/>
+
+ <texture name="BreadCrumbBtn_Right_Disabled" file_name="widgets/BreadCrumbBtn_Right_Disabled.png" preload="false"/>
+ <texture name="BreadCrumbBtn_Right_Off" file_name="widgets/BreadCrumbBtn_Right_Off.png" preload="false"/>
+ <texture name="BreadCrumbBtn_Right_Over" file_name="widgets/BreadCrumbBtn_Right_Over.png" preload="false"/>
+ <texture name="BreadCrumbBtn_Right_Press" file_name="widgets/BreadCrumbBtn_Right_Press.png" preload="false"/>
+
<texture name="BuyArrow_Over" file_name="navbar/BuyArrow_Over.png" preload="true" scale.left="0" scale.top="1" scale.right="0" scale.bottom="0" />
<texture name="BuyArrow_Press" file_name="navbar/BuyArrow_Press.png" preload="true" scale.left="1" scale.top="1" scale.right="0" scale.bottom="0" />
@@ -102,6 +117,7 @@ with the same filename but different name
<texture name="Checkbox_On" file_name="widgets/Checkbox_On.png" preload="true" />
<texture name="Checkbox_On_Press" file_name="widgets/Checkbox_On_Press.png" preload="true" />
<texture name="Checkbox_Press" file_name="widgets/Checkbox_Press.png" preload="true" />
+ <texture name="Check_Mark" file_name="icons/check_mark" preload="true" />
<texture name="ComboButton_Disabled" file_name="widgets/ComboButton_Disabled.png" preload="true" scale.left="2" scale.top="19" scale.right="18" scale.bottom="2" />
<texture name="ComboButton_Selected" file_name="widgets/ComboButton_Selected.png" preload="true" scale.left="2" scale.top="19" scale.right="18" scale.bottom="2" />
@@ -211,6 +227,7 @@ with the same filename but different name
<texture name="Inv_LostClosed" file_name="icons/Inv_LostClosed.png" preload="false" />
<texture name="Inv_LostOpen" file_name="icons/Inv_LostOpen.png" preload="false" />
<texture name="Inv_Landmark" file_name="icons/Inv_Landmark.png" preload="false" />
+ <texture name="Inv_Mesh" file_name="icons/Inv_Mesh.png" preload="false" />
<texture name="Inv_Notecard" file_name="icons/Inv_Notecard.png" preload="false" />
<texture name="Inv_Object" file_name="icons/Inv_Object.png" preload="false" />
<texture name="Inv_Object_Multi" file_name="icons/Inv_Object_Multi.png" preload="false" />
@@ -257,6 +274,10 @@ with the same filename but different name
<texture name="menu_separator" file_name="navbar/FileMenu_Divider.png" scale.left="4" scale.top="166" scale.right="0" scale.bottom="0" />
+ <texture name="ModelImport_Status_Good" file_name="lag_status_good.tga" preload="false"/>
+ <texture name="ModelImport_Status_Warning" file_name="lag_status_warning.tga" preload="false"/>
+ <texture name="ModelImport_Status_Error" file_name="lag_status_critical.tga" preload="false"/>
+
<texture name="MouseLook_View_Off" file_name="bottomtray/MouseLook_view_off.png" preload="false" />
<texture name="MouseLook_View_On" file_name="bottomtray/MouseLook_view_on.png" preload="false" />
@@ -625,6 +646,8 @@ with the same filename but different name
<texture name="icon_for_sale.tga" file_name="icons/Icon_For_Sale.png" />
<texture name="icon_top_pick.tga" />
+ <texture name="inv_folder_mesh.tga"/>
+ <texture name="inv_item_mesh.tga"/>
<texture name="lag_status_critical.tga" />
<texture name="lag_status_good.tga" />
<texture name="lag_status_warning.tga" />
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Disabled.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Disabled.png
new file mode 100644
index 0000000000..c7c0eaa96b
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Disabled.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Off.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Off.png
new file mode 100644
index 0000000000..4a73c254fc
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Off.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Over.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Over.png
new file mode 100644
index 0000000000..6fb5c432de
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Over.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Press.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Press.png
new file mode 100644
index 0000000000..fa18517933
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Left_Press.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Disabled.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Disabled.png
new file mode 100644
index 0000000000..bed1a701bd
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Disabled.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Off.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Off.png
new file mode 100644
index 0000000000..57ce9af574
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Off.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Over.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Over.png
new file mode 100644
index 0000000000..2c43022f0e
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Over.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Press.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Press.png
new file mode 100644
index 0000000000..6b8c1baca4
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Middle_Press.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Disabled.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Disabled.png
new file mode 100644
index 0000000000..51505e80c5
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Disabled.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Off.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Off.png
new file mode 100644
index 0000000000..9f93efbd93
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Off.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Over.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Over.png
new file mode 100644
index 0000000000..3a4ec1a315
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Over.png
Binary files differ
diff --git a/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Press.png b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Press.png
new file mode 100644
index 0000000000..1f1b4c2ed5
--- /dev/null
+++ b/indra/newview/skins/default/textures/widgets/BreadCrumbBtn_Right_Press.png
Binary files differ
diff --git a/indra/newview/skins/default/xui/en/floater_about.xml b/indra/newview/skins/default/xui/en/floater_about.xml
index f5365be11f..967cb28476 100644
--- a/indra/newview/skins/default/xui/en/floater_about.xml
+++ b/indra/newview/skins/default/xui/en/floater_about.xml
@@ -139,17 +139,20 @@ Thank you to the following Residents for helping to ensure that this is the best
word_wrap="true">
3Dconnexion SDK Copyright (C) 1992-2007 3Dconnexion
APR Copyright (C) 2000-2004 The Apache Software Foundation
+ Collada DOM Copyright 2005 Sony Computer Entertainment Inc.
cURL Copyright (C) 1996-2002, Daniel Stenberg, (daniel@haxx.se)
DBus/dbus-glib Copyright (C) 2002, 2003 CodeFactory AB / Copyright (C) 2003, 2004 Red Hat, Inc.
expat Copyright (C) 1998, 1999, 2000 Thai Open Source Software Center Ltd.
FreeType Copyright (C) 1996-2002, The FreeType Project (www.freetype.org).
GL Copyright (C) 1999-2004 Brian Paul.
+ GLOD Copyright (C) 2003-04 Jonathan Cohen, Nat Duca, Chris Niski, Johns Hopkins University and David Luebke, Brenden Schubert, University of Virginia.
google-perftools Copyright (c) 2005, Google Inc.
Havok.com(TM) Copyright (C) 1999-2001, Telekinesys Research Limited.
jpeg2000 Copyright (C) 2001, David Taubman, The University of New South Wales (UNSW)
jpeglib Copyright (C) 1991-1998, Thomas G. Lane.
ogg/vorbis Copyright (C) 2001, Xiphophorus
OpenSSL Copyright (C) 1998-2002 The OpenSSL Project.
+ PCRE Copyright (c) 1997-2008 University of Cambridge
Pth Copyright (C) 1999-2006 Ralf S. Engelschall &lt;rse@gnu.org&gt;
SDL Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002 Sam Lantinga
SSLeay Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
@@ -157,10 +160,12 @@ xmlrpc-epi Copyright (C) 2000 Epinions, Inc.
zlib Copyright (C) 1995-2002 Jean-loup Gailly and Mark Adler.
google-perftools Copyright (c) 2005, Google Inc.
+Second Life Viewer uses Havok (TM) Physics. (c)Copyright 1999-2010 Havok.com Inc. (and its Licensors). All Rights Reserved. See www.havok.com for details.
+
All rights reserved. See licenses.txt for details.
Voice chat Audio coding: Polycom(R) Siren14(TM) (ITU-T Rec. G.722.1 Annex C)
- </text_editor>
+ </text_editor>
</panel>
</tab_container>
</floater>
diff --git a/indra/newview/skins/default/xui/en/floater_import_collada.xml b/indra/newview/skins/default/xui/en/floater_import_collada.xml
new file mode 100644
index 0000000000..441ab6a2de
--- /dev/null
+++ b/indra/newview/skins/default/xui/en/floater_import_collada.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
+<floater can_close="false" can_drag_on_left="false" can_minimize="false"
+ can_resize="false" height="160" min_height="160" width="300" min_width="300"
+ name="Import Collada" title="Import Scene">
+
+ <text bottom_delta="40" left="20" name="mesh count" height="15" follows="top|left">
+ Meshes: [COUNT]
+ </text>
+
+ <text bottom_delta="20" left="20" name="texture count" height="15" follows="top|left">
+ Textures: [COUNT]
+ </text>
+
+ <text bottom_delta="40" left="10" name="status" height="15" follows="top|left">
+ Status: [STATUS]
+ </text>
+
+ <button
+ bottom_delta="40"
+ name="cancel"
+ label="Cancel"
+ enabled="true"
+ height="20"
+ layout="topleft"
+ left="125"
+ width="75" />
+
+ <button
+ bottom_delta="0"
+ name="ok"
+ label="OK"
+ enabled="true"
+ height="20"
+ layout="topleft"
+ left="210"
+ width="75" />
+
+ <string name="status_idle">Idle</string>
+ <string name="status_uploading">Uploading [NAME]</string>
+ <string name="status_creating">Creating object [NAME]</string>
+
+ </floater>
diff --git a/indra/newview/skins/default/xui/en/floater_inventory_view_finder.xml b/indra/newview/skins/default/xui/en/floater_inventory_view_finder.xml
index 90fee857fb..c86ed595a7 100644
--- a/indra/newview/skins/default/xui/en/floater_inventory_view_finder.xml
+++ b/indra/newview/skins/default/xui/en/floater_inventory_view_finder.xml
@@ -95,6 +95,23 @@
width="126" />
<icon
height="16"
+ image_name="Inv_Mesh"
+ layout="topleft"
+ left="8"
+ mouse_opaque="true"
+ name="icon_mesh"
+ top="142"
+ width="16" />
+ <check_box
+ height="16"
+ label="Meshes"
+ layout="topleft"
+ left_pad="2"
+ name="check_mesh"
+ top_delta="0"
+ width="126" />
+ <icon
+ height="16"
image_name="Inv_Notecard"
layout="topleft"
left="8"
@@ -117,7 +134,7 @@
left="8"
mouse_opaque="true"
name="icon_object"
- top="142"
+ top="162"
width="16" />
<check_box
height="16"
@@ -134,7 +151,7 @@
left="8"
mouse_opaque="true"
name="icon_script"
- top="162"
+ top="182"
width="16" />
<check_box
height="16"
@@ -151,7 +168,7 @@
left="8"
mouse_opaque="true"
name="icon_sound"
- top="182"
+ top="202"
width="16" />
<check_box
height="16"
@@ -168,7 +185,7 @@
left="8"
mouse_opaque="true"
name="icon_texture"
- top="202"
+ top="222"
width="16" />
<check_box
height="16"
@@ -185,7 +202,7 @@
left="8"
mouse_opaque="true"
name="icon_snapshot"
- top="222"
+ top="242"
width="16" />
<check_box
height="16"
@@ -203,7 +220,7 @@
layout="topleft"
left="8"
name="All"
- top="242"
+ top="262"
width="100" />
<button
follows="left|top"
diff --git a/indra/newview/skins/default/xui/en/floater_model_preview.xml b/indra/newview/skins/default/xui/en/floater_model_preview.xml
new file mode 100644
index 0000000000..e79dfcbc7d
--- /dev/null
+++ b/indra/newview/skins/default/xui/en/floater_model_preview.xml
@@ -0,0 +1,544 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
+<floater can_close="true" can_drag_on_left="false" can_minimize="false"
+ can_resize="true" height="550" min_height="550" min_width="620"
+ name="Model Preview" title="Upload Model" width="620">
+
+ <string name="status_idle">Idle</string>
+ <string name="status_reading_file">Loading...</string>
+ <string name="status_generating_meshes">Generating Meshes...</string>
+ <string name="high">High</string>
+ <string name="medium">Medium</string>
+ <string name="low">Low</string>
+ <string name="lowest">Lowest</string>
+ <string name="mesh_status_good">Ship it!</string>
+ <string name="mesh_status_na">N/A</string>
+ <string name="mesh_status_none">None</string>
+ <string name="mesh_status_submesh_mismatch">Levels of detail have a different number of textureable faces.</string>
+ <string name="mesh_status_mesh_mismatch">Levels of detail have a different number of mesh instances.</string>
+ <string name="mesh_status_too_many_vertices">Level of detail has too many vertices.</string>
+ <string name="mesh_status_missing_lod">Missing required level of detail.</string>
+ <string name="layer_all">All</string> <!-- Text to display in physics layer combo box for "all layers" -->
+ <string name="decomposing">Analyzing...</string>
+ <string name="simplifying">Simplifying...</string>
+
+
+ <text left="15" bottom="25" follows="top|left" height="15" name="name_label">
+ Name:
+ </text>
+ <line_editor bottom_delta="20" follows="top|left|right" height="19"
+ name="description_form" prevalidate_callback="ascii" width="290" />
+
+ <text bottom_delta="20" left="15" follows="left|top" height="15" name="lod_label">
+ Preview:
+ </text>
+ <combo_box bottom_delta="20" follows="left|top" height="18"
+ name="preview_lod_combo" width="240" tool_tip="LOD to view in preview render">
+ <combo_item name="high">
+ Level of Detail: High
+ </combo_item>
+ <combo_item name="medium">
+ Level of Detail: Medium
+ </combo_item>
+ <combo_item name="low">
+ Level of Detail: Low
+ </combo_item>
+ <combo_item name="lowest">
+ Level of Detail: Lowest
+ </combo_item>
+ </combo_box>
+
+ <menu_button follows="top|left"
+ image_hover_unselected="Toolbar_Left_Over"
+ image_overlay="OptionsMenu_Off"
+ image_selected="Toolbar_Left_Selected"
+ image_unselected="Toolbar_Left_Off"
+ layout="topleft"
+ left_pad="5"
+ name="options_gear_btn"
+ width="31"
+ height="25"/>
+ <!-- Placeholder panel for 3D preview render -->
+ <panel
+ name="preview_panel"
+ left="15"
+ bevel_style="none"
+ border_style="line"
+ border="true"
+ width="290"
+ height="290"
+ follows="all"/>
+
+ <text bottom_delta="25" left="25" width="100" follows="bottom|left">Upload Details</text>
+ <panel top_pad="5" border="true" left="15" width="290" height="70" follows="bottom|left"
+ bevel_style="none" bg_alpha_color="0 0 0 0" bg_opaque_color="0 0 0 0.3">
+ <text left="25" follows="bottom|left" width="140" height="15" name="streaming cost">
+ Resource Cost: [COST]
+ </text>
+ <text left="25" top_pad="5" width="140" follows="bottom|left" height="15" name="physics cost">
+ Physics Cost: [COST]
+ </text>
+ <text left="25" top_pad="5" follows="bottom|left" height="15" name="upload fee">
+ Upload Fee: N/A
+ </text>
+ </panel>
+
+ <text left="10" bottom="540" width="290" height="15" follows="bottom|left|right" name="status">[STATUS]</text>
+
+
+ <button bottom="540" left="430" follows="bottom|right" height="20" label="Upload"
+ width="80" name="ok_btn" tool_tip="Upload to simulator"/>
+ <button left_pad="10" follows="right|bottom" height="20" width="80" label="Cancel" name="cancel_btn"/>
+
+ <tab_container
+ follows="right|top|bottom"
+ top="15"
+ left="310"
+ height="470"
+ width="300"
+ name="import_tab"
+ border="true"
+ tab_position="top">
+
+ <!-- LOD PANEL -->
+ <panel
+ border="true"
+ label="Level of Detail"
+ name="lod_panel">
+
+ <text left="10" width="240" bottom="20" height="15" follows="left|top" name="lod_table_header">
+ Select Level of Detail:
+ </text>
+
+ <text valign="center" halign="center" bg_visible="true" bottom_delta="16" left="75" width="65" height="18" follows="left|top" value="Triangles"/>
+ <text valign="center" halign="center" bg_visible="true" left_pad="0" width="65" height="18" follows="left|top" value="Vertices"/>
+ <text valign="center" halign="center" left_pad="0" width="65" bg_visible="true" height="18" follows="left|top" value="Status"/>
+
+ <text valign="center" halign="center" bg_visible="true" name="high_label" left="10" top_pad="0" width="65" height="18" follows="left|top" value="High"/>
+ <text valign="center" halign="center" bg_visible="true" name="high_triangles" left_pad="0" width="65" height="18" follows="left|top" value="0"/>
+ <text valign="center" halign="center" bg_visible="true" name="high_vertices" left_pad="0" width="65" height="18" follows="left|top" value="0"/>
+ <text valign="center" halign="center" bg_visible="true" name="high_status" left_pad="0" width="65" height="18" follows="left|top" value=""/>
+ <icon height="16" width="16" image_name="lag_status_critical.tga" mouse_opaque="true" name="status_icon_high" left_delta="20" top_delta="0" />
+
+ <text valign="center" halign="center" bg_visible="true" name="medium_label" left="10" top_pad="0" width="65" height="18" follows="left|top" value="Medium"/>
+ <text valign="center" halign="center" bg_visible="true" name="medium_triangles" left_pad="0" width="65" height="18" follows="left|top" value="0"/>
+ <text valign="center" halign="center" bg_visible="true" name="medium_vertices" left_pad="0" width="65" height="18" follows="left|top" value="0"/>
+ <text valign="center" halign="center" bg_visible="true" name="medium_status" left_pad="0" width="65" height="18" follows="left|top" value=""/>
+ <icon height="16" width="16" image_name="lag_status_critical.tga" mouse_opaque="true" name="status_icon_medium" left_delta="20" top_delta="0" />
+
+ <text valign="center" halign="center" bg_visible="true" name="low_label" left="10" top_pad="0" width="65" height="18" follows="left|top" value="Low"/>
+ <text valign="center" halign="center" bg_visible="true" name="low_triangles" left_pad="0" width="65" height="18" follows="left|top" value="0"/>
+ <text valign="center" halign="center" bg_visible="true" name="low_vertices" left_pad="0" width="65" height="18" follows="left|top" value="0"/>
+ <text valign="center" halign="center" bg_visible="true" name="low_status" left_pad="0" width="65" height="18" follows="left|top" value=""/>
+ <icon height="16" width="16" image_name="lag_status_critical.tga" mouse_opaque="true" name="status_icon_low" left_delta="20" top_delta="0" />
+
+ <text valign="center" halign="center" bg_visible="true" name="lowest_label" left="10" top_pad="0" width="65" height="18" follows="left|top" value="Lowest"/>
+ <text valign="center" halign="center" bg_visible="true" name="lowest_triangles" left_pad="0" width="65" height="18" follows="left|top" value="0"/>
+ <text valign="center" halign="center" bg_visible="true" name="lowest_vertices" left_pad="0" width="65" height="18" follows="left|top" value="0"/>
+ <text valign="center" halign="center" bg_visible="true" name="lowest_status" left_pad="0" width="65" height="18" follows="left|top" value=""/>
+ <icon height="16" width="16" image_name="lag_status_critical.tga" mouse_opaque="true" name="status_icon_lowest" left_delta="20" top_delta="0" />
+
+ <text left="10" width="240" height="15" top_pad="15" follows="left|top" name="lod_table_footer">
+ Level of Detail: [DETAIL]
+ </text>
+
+ <icon height="16" width="16" left="20" follows="left|top" name="lod_status_message_icon"/>
+ <text left_pad="5" width="200" height="28" follows="left|top" top_pad="-15" wrap="true" name="lod_status_message_text"/>
+
+ <text top_pad="-3" left="10" height="15" follows="left|top">
+ Mesh
+ </text>
+
+ <radio_group follows="top|left" height="210" left="30" name="lod_file_or_limit" width="240" value="lod_from_file">
+ <radio_item bottom="195" label="Load from file" name="lod_from_file"/>
+ <radio_item bottom="150" label="Auto generate" name="lod_auto_generate"/>
+ <radio_item bottom="0" label="None" name="lod_none"/>
+ </radio_group>
+
+ <line_editor follows="left|top" bottom_delta="-170" width="140" left="45" value="" name="lod_file" height="20"/>
+ <button bottom_delta="3" name="lod_browse" label="Browse..." left_pad="5" follows="left|top" width="70" height="25"/>
+
+ <combo_box follows="top|left" name="lod_mode" top_pad="22" width="100" left="45" height="20">
+ <combo_item name="triangle_limit">
+ Triangle Limit
+ </combo_item>
+ <combo_item name="error_threshold">
+ Error Threshold
+ </combo_item>
+ </combo_box>
+ <spinner follows="top|left" name="lod_triangle_limit" increment="10" left_pad="5" height="20" width="100" decimal_digits="0" enabled="true"/>
+ <spinner left_delta="0" bottom_delta="0" increment="0.01" follows="top|left" name="lod_error_threshold" min_val="0" max_val="100" height="20" width="100" decimal_digits="3" visible="false" enabled="true"/>
+
+ <text follows="top|left" name="build_operator_text" left="45" top_pad="10" width="100" height="15">
+ Build Operator:
+ </text>
+ <text follows="top|left" name="queue_mode_text" left_pad="5" width="100" height="15">
+ Queue Mode:
+ </text>
+ <combo_box follows="top|left" name="build_operator" top_pad="5" left="45" width="100" height="20">
+ <combo_item name="edge_collapse">
+ Edge Collapse
+ </combo_item>
+ <combo_item name="half_edge_collapse">
+ Half Edge Collapse
+ </combo_item>
+ </combo_box>
+
+ <combo_box follows="top|left" name="queue_mode" left_pad="5" width="100" height="20">
+ <combo_item name="greedy">
+ Greedy
+ </combo_item>
+ <combo_item name="lazy">
+ Lazy
+ </combo_item>
+ <combo_item name="independent">
+ Independent
+ </combo_item>
+ </combo_box>
+
+ <text top_pad="10" name="border_mode_text" left="45" follows="left|top" width="100" height="15">
+ Border Mode:
+ </text>
+
+ <text left_pad="5" name="share_tolderance_text" follows="left|top" width="100" height="15">
+ Share Tolerance:
+ </text>
+
+ <combo_box follows="left|top" left="45" height="20" name="border_mode" width="100">
+ <combo_item name="border_unlock">
+ Unlock
+ </combo_item>
+ <combo_item name="border_lock">
+ Lock
+ </combo_item>
+ </combo_box>
+ <spinner follows="left|top" name="share_tolerance" left_pad="5" width="100" decimal_digits="5" initial_value="0.00001" height="20"/>
+
+ <text left="10" top_pad="35" follows="top|left" width="240" height="15">
+ Generate Normals
+ </text>
+ <text left="35" top_pad="5" follows="top|left" width="100" height="15">
+ Crease Angle:
+ </text>
+ <spinner follows="top|left" left_pad="5" min_val="0" max_val="180" value="75" width="60" height="20" name="crease_angle"/>
+ </panel>
+
+ <!-- PANEL -->
+ <panel
+ border="true"
+ label="Physics"
+ name="physics_panel">
+
+ <!-- PHYSICS GEOMETRY-->
+ <panel
+ follows="top|left"
+ name="physics geometry"
+ left="0"
+ top="0"
+ width="300"
+ height="65"
+ visible="true"
+ border="true"
+ bevel_style="none" bg_alpha_color="0 0 0 0" bg_opaque_color="0 0 0 0.3">
+
+ <radio_group follows="top|left" top="10" width="240" height="40" name="physics_load_radio" value="physics_load_from_file">
+ <radio_item bottom="0" name="physics_load_from_file" label="File:"/>
+ <radio_item bottom="23" name="physics_use_lod" label="Use Level of Detail:"/>
+ </radio_group>
+
+ <combo_box left="180" top="10" follows="left|top" height="18"
+ name="physics_lod_combo" width="110" tool_tip="LOD to use for physics shape">
+ <combo_item name="physics_lowest">
+ Lowest
+ </combo_item>
+ <combo_item name="physics_low">
+ Low
+ </combo_item>
+ <combo_item name="physics_medium">
+ Medium
+ </combo_item>
+ <combo_item name="physics_high">
+ High
+ </combo_item>
+ </combo_box>
+
+ <line_editor follows="left|top" top_pad="5" width="140" left="60" value="" name="physics_file" height="20"/>
+ <button left_pad="10" name="physics_browse" label="Browse..." follows="left|top" width="70" height="20"/>
+
+ <!--
+ <check_box name="physics_optimize" follows="left|top" width="130" left="10" top_pad="5" height="20" label="Optimize"/>
+ <check_box name="physics_use_hull" follows="left|top" width="130" left_pad="5" height="20" label="Use Convex Hull"/>
+ -->
+ </panel>
+
+
+ <!-- PHYSICS ANALYSIS-->
+ <panel
+ follows="top|left"
+ name="physics analysis"
+ top_pad="0"
+ left="0"
+ width="300"
+ height="130"
+ visible="true"
+ border="true"
+ bevel_style="none" bg_alpha_color="0 0 0 0" bg_opaque_color="0 0 0 0.3">
+
+ <text follows="left|top" bottom="40" height="30" left="10" font="SansSerifBig">
+ Step 1: Analysis
+ </text>
+
+ <text top_pad="5" width="50" follows="top|left" height="15">
+ Method:
+ </text>
+ <combo_box name="Method" follows="top|left" left_pad="5" bottom_delta="2" height="20" width="80"/>
+ <text left="160" bottom_delta="-2" width="50" follows="top|left" height="15">
+ Quality:
+ </text>
+ <combo_box name="Decompose Quality" bottom_delta="2" follows="top|left" left_pad="5" height="20" width="80"/>
+
+ <slider name="Smooth" left="10" width="280" follows="top|left" top_pad="10" height="20" label="Smooth:"/>
+
+ <check_box name="Close Holes (Slow)" follows="top|left" top_pad="10" height="15" label="Close Holes (slow)"/>
+
+ <button left="200" bottom_delta="0" width="90" follows="top|left" label="Analyze" name="Decompose" height="20"/>
+ <button left="200" bottom_delta="0" width="90" follows="top|left" label="Cancel" name="decompose_cancel" visble="false" height="20"/>
+ </panel>
+
+
+ <!-- PHYSICS SIMPLIFICATION -->
+ <panel
+ follows="top|left"
+ name="physics simplification"
+ left="0"
+ top_pad="0"
+ width="300"
+ height="150"
+ visible="true"
+ border="true"
+ bevel_style="none" bg_alpha_color="0 0 0 0" bg_opaque_color="0 0 0 0.3">
+
+ <text follows="left|top" bottom="40" height="30" left="10" font="SansSerifBig">
+ Step 2: Simplification
+ </text>
+
+ <text left="10" top_pad="5" height="15" width="140" follows="top|left">
+ Method:
+ </text>
+
+ <combo_box left_pad="5" height="20" width="120" follows="top|left" name="Simplify Method"/>
+
+ <slider left="10" name="Combine Quality" label="Passes:" label_width="120" width="270" follows="top|left" top_pad="10" height="20"/>
+ <slider name="Detail Scale" label="Detail Scale:" label_width="120" width="270" follows="top|left" top_pad="10" height="20"/>
+ <slider name="Retain%" label="Retain:" label_width="120" width="270" follows="top|left" bottom_delta="0" left_delta="0" visible="false" height="20"/>
+ <button left="190" width="90" follows="top|left" label="Simplify" name="Simplify" height="20"/>
+ <button left="190" bottom_delta="0" width="90" follows="top|left" label="Cancel" name="simplify_cancel" height="20"/>
+
+ </panel>
+
+ <!-- INFO PANEL -->
+ <panel
+ left="0"
+ top_pad="0"
+ width="300"
+ height="100"
+ follows="left|top"
+ name="physics info"
+ visible="true"
+ border="true"
+ bevel_style="none" bg_alpha_color="0 0 0 0" bg_opaque_color="0 0 0 0.3">
+
+ <slider name="physics_explode" follows="top|left" top="10" left="10" label="Preview Spread:" min_val="0.0" max_val="3.0" height="20" width="280"/>
+
+ <text follows="top|left" name="physics_triangles" top_pad="10" height="15" left="10">
+ Triangles: [TRIANGLES]
+ </text>
+ <text follows="top|left" name="physics_points" top_pad="5" height="15">
+ Vertices: [POINTS]
+ </text>
+ <text follows="top|left" name="physics_hulls" top_pad="5" height="15">
+ Hulls: [HULLS]
+ </text>
+
+
+ </panel>
+ </panel>
+
+ <!-- MODIFIERS PANEL -->
+ <panel
+ border="true"
+ label="Modifiers"
+ name="modifiers_panel">
+ <text left="10" width="90" bottom="30" follows="top|left" height="15">
+ Scale:
+ </text>
+ <text left_pad="5" width="140" follows="top|left" height="15">
+ Dimensions:
+ </text>
+
+ <spinner left="10" height="20" follows="top|left" width="80" top_pad="5" value="1.0" min_val="0.01" max_val="64.0" name="import_scale"/>
+
+ <text left_pad="20" height="15" name="import_dimensions" follows="top|left">
+ [X] x [Y] x [Z] m
+ </text>
+
+ <text left="10" top_pad="20" follows="top|left" height="15">
+ Include:
+ </text>
+
+ <check_box top_pad="5" name="upload_textures" height="15" follows="top|left" label="Textures"/>
+ <check_box top_pad="5" name="upload_skin" height="15" follows="top|left" label="Skin weight"/>
+ <check_box top_pad="5" left="20" name="upload_joints" height="15" follows="top|left" label="Joint positions"/>
+
+ <text left="10" top_pad="4" width="90" bottom="30" follows="top|left" height="15">
+ Pelvis Offset:
+ </text>
+
+ <spinner left="10" top_pad="4" height="20" follows="top|left" width="80" value="0.0" min_val="0.00" max_val="32.0" name="pelvis_offset"/>
+
+ </panel>
+ </tab_container>
+
+ <!--
+ <button bottom_delta="0" left="10" width="120" name="auto fill" label="Generate LOD" tool_tip="Automatically generate levels of detail"/>
+ <button bottom_delta="0" left="140" width="120" name="smooth normals" label="Generate Normals" tool_tip="Regenerate normals based on mesh shape"/>
+ <button bottom_delta="0" left="260" width="120" name="consolidate" label="Consolidate" tool_tip="Combine similar submeshes (reduces number of submeshes)"/>
+ <button bottom_delta="30" left="260" width="120" name="scrub materials" label="Scrub Materials" tool_tip="Remove all material information (clear textures, set all colors to white)."/>
+
+ <spinner bottom_delta="0" left="140" width="120" height="16" initial_value="75" label_width="60" name="edge threshold" decimal_digits="0" min_val="0" max_val="180" increment="5" label="Hard Angle" tool_tip="Maximum angle that will be smoothed between triangles when using Generate Normals"/>
+
+ <text bottom_delta="30" follows="top|left" height="15" left="10" name="high_lod_label">
+ High LOD:
+ </text>
+ <combo_box bottom_delta="0" left="97" follows="left|top" height="18"
+ name="high detail combo" width="100" tool_tip="Specify mesh for this level of detail">
+ <combo_item name="high none" value="none">
+ None
+ </combo_item>
+ <combo_item name="high choose file" value="file">
+ Choose File...
+ </combo_item>
+ <combo_item name="high triangle limit" value="limit">
+ Triangle Limit
+ </combo_item>
+ </combo_box>
+ <spinner bottom_delta="-5" left="200" width="120" name="high limit" decimal_digits="0" increment="1" min_val="0" max_val="100" tool_tip="Triangle budget for this LOD"/>
+ <text bottom_delta="25" follows="top|left" height="15" left="10" name="high info" width="300">
+ [TRIANGLES] Triangles, [VERTICES] Vertices, [SUBMESHES] Submeshes.
+ [MESSAGE]
+ </text>
+
+ <text bottom_delta="35" follows="top|left" height="15" left="10" name="medium_lod_label">
+ Medium LOD:
+ </text>
+ <combo_box bottom_delta="0" left="97" follows="left|top" height="18"
+ name="medium detail combo" width="100" tool_tip="Specify mesh for this level of detail">
+ <combo_item name="medium none" value="none">
+ None
+ </combo_item>
+ <combo_item name="medium choose file" value="file">
+ Choose File...
+ </combo_item>
+ <combo_item name="medium triangle limit" value="limit">
+ Triangle Limit
+ </combo_item>
+ </combo_box>
+ <spinner bottom_delta="-5" left="200" width="120" name="medium limit" decimal_digits="0" increment="1" min_val="0" max_val="100" tool_tip="Triangle budget for this LOD"/>
+ <text bottom_delta="25" follows="top|left" height="15" left="10" name="medium info" width="300">
+ [TRIANGLES] Triangles, [VERTICES] Vertices, [SUBMESHES] Submeshes.
+ [MESSAGE]
+ </text>
+
+ <text bottom_delta="35" follows="top|left" height="15" left="10" name="low_lod_label">
+ Low LOD:
+ </text>
+ <combo_box bottom_delta="0" left="97" follows="left|top" height="18"
+ name="low detail combo" width="100" tool_tip="Specify mesh for this level of detail">
+ <combo_item name="low none" value="none">
+ None
+ </combo_item>
+ <combo_item name="low choose file" value="file">
+ Choose File...
+ </combo_item>
+ <combo_item name="low triangle limit" value="limit">
+ Triangle Limit
+ </combo_item>
+ </combo_box>
+ <spinner bottom_delta="-5" left="200" width="120" name="low limit" decimal_digits="0" increment="1" min_val="0" max_val="100" tool_tip="Triangle budget for this LOD"/>
+ <text bottom_delta="25" follows="top|left" height="15" left="10" name="low info" width="300">
+ [TRIANGLES] Triangles, [VERTICES] Vertices, [SUBMESHES] Submeshes
+ [MESSAGE]
+ </text>
+
+ <text bottom_delta="35" follows="top|left" height="15" left="10" name="lowest_lod_label">
+ Lowest LOD:
+ </text>
+ <combo_box bottom_delta="0" left="97" follows="left|top" height="18"
+ name="lowest detail combo" width="100" tool_tip="Specify mesh for this level of detail">
+ <combo_item name="lowest none" value="none">
+ None
+ </combo_item>
+ <combo_item name="lowest choose file" value="file">
+ Choose File...
+ </combo_item>
+ <combo_item name="lowest triangle limit" value="limit">
+ Triangle Limit
+ </combo_item>
+ </combo_box>
+ <spinner bottom_delta="-5" left="200" width="120" name="lowest limit" decimal_digits="0" increment="1" min_val="0" max_val="100" tool_tip="Triangle budget for this LOD"/>
+ <text bottom_delta="25" follows="top|left" height="15" left="10" name="lowest info" width="300">
+ [TRIANGLES] Triangles, [VERTICES] Vertices, [SUBMESHES] Submeshes
+ [MESSAGE]
+ </text>
+
+ <text bottom_delta="35" follows="top|left" height="15" left="10" name="physics_lod_label">
+ Physical Shape:
+ </text>
+ <combo_box bottom_delta="0" left="97" follows="left|top" height="18"
+ name="physics detail combo" width="100">
+ <combo_item name="physics none" value="none">
+ None
+ </combo_item>
+ <combo_item name="physics choose file" value="file">
+ Choose File...
+ </combo_item>
+ <combo_item name="physics triangle limit" value="limit">
+ Triangle Limit...
+ </combo_item>
+ </combo_box>
+ <spinner bottom_delta="-5" left="200" width="90" name="physics limit" decimal_digits="0" increment="1" min_val="0" max_val="100" tool_tip="Triangle budget for this LOD"/>
+ <button bottom_delta="0" left="290" width="30" follows="left|top" height="20" label=">>"
+ name="decompose_btn" tool_tip="Create convex decomposition."/>
+ <text bottom_delta="25" follows="top|left" height="15" left="10" name="physics info" width="300">
+ [TRIANGLES] Triangles, [HULLS] Hulls, [POINTS] Points
+ </text>
+
+ <text bottom_delta="25" follows="top|left" height="15" left="10" name="include label" width="300">
+ Include:
+ </text>
+
+ <check_box bottom_delta="20" follow="bottom|left" height="20" label="Textures"
+ left="15" width="125" name="upload_textures" tool_tip="Upload associated textures "/>
+
+ <check_box bottom_delta="20" follow="bottom|left" height="20" label="Skin Weights"
+ left="15" width="125" name="upload_skin" tool_tip="Upload vertex skin weighting information."/>
+
+ <check_box bottom_delta="20" follow="bottom|left" height="20" label="Joint Positions"
+ left="15" width="125" name="upload_joints" tool_tip="Upload joint position information (will override avatar joint positions when mesh is worn)."/>
+
+
+ <button bottom_delta="25" follows="bottom|left" height="20" label="Upload"
+ left="15" name="ok_btn" width="125" tool_tip="Upload to simulator"/>
+
+ <text bottom_delta="20" left="15" width="280" follows="top|left" height="15" name="description_label" text_color="1 0.82 0.46 1">
+ (No charge for upload during First Look)
+ </text>
+ <text bottom_delta="20" left="15" width="280" follows="top|left" height="15" name="upload_message">
+ [MESSAGE]
+ </text>
+
+ <spinner bottom_delta="20" label="Scale" left="15" width="120" name="debug scale" decimal_digits="3" increment="0.1" min_val="0" max_val="64" initial_value="1" tool_tip="Multiplier for incoming object scale. If incoming dimensions are very small or very large, modify this value to get dimensions into an acceptable range."/>
+ <text bottom_delta="30" left="15" width="280" follows="top|left" height="15" name="dimensions">
+ Model Dimensions: [X]m x [Y]m x [Z]m
+ </text>
+ -->
+</floater>
diff --git a/indra/newview/skins/default/xui/en/floater_model_wizard.xml b/indra/newview/skins/default/xui/en/floater_model_wizard.xml
new file mode 100644
index 0000000000..f133d75eee
--- /dev/null
+++ b/indra/newview/skins/default/xui/en/floater_model_wizard.xml
@@ -0,0 +1,895 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
+<floater
+ legacy_header_height="18"
+ layout="topleft"
+ name="Model Wizard"
+ help_topic="model_wizard"
+ bg_opaque_image_overlay="0.5 0.5 0.5 1"
+ height="475"
+ save_rect="true"
+ title="UPLOAD MODEL WIZARD"
+ width="530">
+ <button
+ top="32"
+ tab_stop="false"
+ left="410"
+ height="32"
+ name="upload_btn"
+ enabled="false"
+ label="5. Upload"
+ border="false"
+ image_unselected="BreadCrumbBtn_Right_Off"
+ image_selected="BreadCrumbBtn_Right_Press"
+ image_hover_unselected="BreadCrumbBtn_Right_Over"
+ image_disabled="BreadCrumbBtn_Right_Disabled"
+ image_disabled_selected="BreadCrumbBtn_Right_Disabled"
+ width="110">
+ <button.commit_callback
+ function="Wizard.Upload"/>
+ </button>
+ <button
+ top="32"
+ left="310"
+ height="32"
+ tab_stop="false"
+ name="review_btn"
+ label="4. Review"
+ enabled="false"
+ border="false"
+ image_unselected="BreadCrumbBtn_Middle_Off"
+ image_selected="BreadCrumbBtn_Middle_Press"
+ image_hover_unselected="BreadCrumbBtn_Middle_Over"
+ image_disabled="BreadCrumbBtn_Middle_Disabled"
+ image_disabled_selected="BreadCrumbBtn_Middle_Disabled"
+ width="110">
+ <button.commit_callback
+ function="Wizard.Review"/>
+ </button>
+ <button
+ top="32"
+ left="210"
+ height="32"
+ name="physics_btn"
+ label="3. Physics"
+ tab_stop="false"
+ enabled="false"
+ border="false"
+ image_unselected="BreadCrumbBtn_Middle_Off"
+ image_selected="BreadCrumbBtn_Middle_Press"
+ image_hover_unselected="BreadCrumbBtn_Middle_Over"
+ image_disabled="BreadCrumbBtn_Middle_Disabled"
+ image_disabled_selected="BreadCrumbBtn_Middle_Disabled"
+ width="110">
+ <button.commit_callback
+ function="Wizard.Physics"/>
+ </button>
+ <button
+ top="32"
+ left="115"
+ name="optimize_btn"
+ label="2. Optimize"
+ tab_stop="false"
+ height="32"
+ border="false"
+ image_unselected="BreadCrumbBtn_Middle_Off"
+ image_selected="BreadCrumbBtn_Middle_Press"
+ image_hover_unselected="BreadCrumbBtn_Middle_Over"
+ image_disabled="BreadCrumbBtn_Middle_Disabled"
+ image_disabled_selected="BreadCrumbBtn_Middle_Disabled"
+ width="110">
+ <button.commit_callback
+ function="Wizard.Optimize"/>
+ </button>
+ <button
+ top="32"
+ left="15"
+ name="choose_file_btn"
+ tab_stop="false"
+ enabled="false"
+ label="1. Choose File"
+ height="32"
+ image_unselected="BreadCrumbBtn_Left_Off"
+ image_selected="BreadCrumbBtn_Left_Press"
+ image_hover_unselected="BreadCrumbBtn_Left_Over"
+ image_disabled="BreadCrumbBtn_Left_Disabled"
+ image_disabled_selected="BreadCrumbBtn_Left_Disabled"
+ width="110">
+ <button.commit_callback
+ function="Wizard.Choose"/>
+ </button>
+ <panel
+ height="388"
+ top_pad="0"
+ name="choose_file_panel"
+ visible="true"
+ width="530"
+ left="0">
+ <panel
+ height="20"
+ top_pad="20"
+ width="500"
+ name="header_panel"
+ bg_opaque_color="DkGray2"
+ background_visible="true"
+ background_opaque="true"
+ left="20">
+ <text
+ width="200"
+ left="10"
+ top="2"
+ name="header_text"
+ height="10"
+ font="SansSerifBig"
+ layout="topleft">
+ Upload Model
+ </text>
+ </panel>
+ <text
+ top_pad="14"
+ width="460"
+ height="20"
+ name="description"
+ font="SansSerifSmall"
+ layout="topleft"
+ word_wrap="true"
+ left_delta="0">
+ This wizard will help you import mesh models to Second Life. First specify a file containing the model you wish to import. Second Life supports COLLADA (.dae) files.
+ </text>
+ <panel
+ top_delta="40"
+ left="15"
+ height="245"
+ width="500"
+ name="content"
+ bg_opaque_color="DkGray2"
+ background_visible="true"
+ background_opaque="true">
+ <text
+ type="string"
+ length="1"
+ text_color="White"
+ follows="left|top"
+ top="10"
+ height="10"
+ layout="topleft"
+ left_delta="10"
+ name="Cache location"
+ width="300">
+ Filename:
+ </text>
+ <line_editor
+ border_style="line"
+ border_thickness="1"
+ follows="left|top"
+ font="SansSerifSmall"
+ height="20"
+ layout="topleft"
+ left_delta="0"
+ max_length="4096"
+ name="lod_file"
+ top_pad="5"
+ width="220" />
+ <button
+ follows="left|top"
+ height="23"
+ label="Browse..."
+ label_selected="Browse..."
+ layout="topleft"
+ left_pad="5"
+ name="browse"
+ top_delta="-1"
+ width="85">
+ </button>
+ <text
+ top_delta="-15"
+ width="200"
+ height="15"
+ font="SansSerifSmall"
+ layout="topleft"
+ text_color="White"
+ left_pad="19">
+ Model Preview:
+ </text>
+ <!-- Placeholder panel for 3D preview render -->
+ <panel
+ left_delta="0"
+ top_pad="0"
+ name="preview_panel"
+ bevel_style="none"
+ highlight_light_color="0.09 0.09 0.09 1"
+ border="true"
+ height="150"
+ follows="all"
+ width="150">
+ </panel>
+ <text
+ top_pad="10"
+ width="130"
+ height="14"
+ left="340"
+ text_color="White"
+ word_wrap="true">
+ Dimensions (meters):
+ </text>
+ <text
+ top_pad="0"
+ width="160"
+ height="15"
+ font="SansSerifSmallBold"
+ text_color="White"
+ name="dimensions"
+ left_delta="0">
+ X: Y: Z:
+ </text>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_dividers"
+ left_delta="41">
+ | |
+ </text>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_x"
+ left="356"/>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_y"
+ left="403"/>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_z"
+ left="450"/>
+ <text
+ top="100"
+ width="320"
+ height="15"
+ left="10"
+ text_color="White"
+ word_wrap="true">
+ Note:
+ </text>
+ <text
+ top_pad="0"
+ width="320"
+ height="40"
+ left="10"
+ word_wrap="true">
+Advanced users familiar with 3d content creation tools may prefer to use the [secondlife:///app/floater/upload_model Advanced Mesh Import Window] .
+ </text>
+ </panel>
+ </panel>
+
+
+ <panel
+ height="388"
+ top_delta="0"
+ name="optimize_panel"
+ visible="false"
+ width="530"
+ left="0">
+ <panel
+ height="20"
+ top_pad="20"
+ name="header_panel"
+ width="500"
+ bg_opaque_color="DkGray2"
+ background_visible="true"
+ background_opaque="true"
+ left="20">
+ <text
+ width="200"
+ left="10"
+ name="header_text"
+ top="2"
+ height="10"
+ font="SansSerifBig"
+ layout="topleft">
+ Optimize
+ </text>
+ </panel>
+ <text
+ top_pad="14"
+ width="460"
+ height="20"
+ font="SansSerifSmall"
+ layout="topleft"
+ name="description"
+ word_wrap="true"
+ left_delta="0">
+ This wizard is optimizing your model. This may take several minutes. To stop the process click the back button
+ </text>
+ <panel
+ top_delta="40"
+ visible="false"
+ left="15"
+ height="245"
+ width="500"
+ name="content"
+ bg_opaque_color="DkGray2"
+ background_visible="true"
+ background_opaque="true">
+ <text
+ top="20"
+ width="300"
+ height="12"
+ font="SansSerifBold"
+ left="112">Generating Level of Detail</text>
+ <progress_bar
+ name="optimize_progress_bar"
+ image_fill="model_wizard\progress_light.png"
+ color_bg="1 1 1 1"
+ color_bar="1 1 1 0.96"
+ follows="left|right|top"
+ width="260"
+ height="16"
+ image_bar="model_wizard\progress_bar_bg.png"
+ top_pad="14"
+ left="110"/>
+ <icon
+ top_pad="10"
+ left_delta="0"
+ width="13"
+ height="12"
+ image_name="model_wizard\check_mark.png"/>
+ <text
+ top_delta="0"
+ left_delta="18"
+ name="high_detail_text"
+ width="200"
+ height="14">Generate Level of Detail: High</text>
+ <icon
+ top_pad="10"
+ left_delta="-18"
+ width="13"
+ height="12"
+ image_name="model_wizard\check_mark.png"/>
+ <text
+ top_delta="0"
+ left_delta="18"
+ name="medium_detail_text"
+ width="200"
+ height="14">Generate Level of Detail: Medium</text>
+ <icon
+ top_pad="10"
+ left_delta="-18"
+ width="13"
+ height="12"
+ image_name="model_wizard\check_mark.png"/>
+ <text
+ top_delta="0"
+ left_delta="18"
+ name="low_detail_text"
+ width="200"
+ height="14">Generate Level of Detail: Low</text>
+ <icon
+ top_pad="10"
+ left_delta="-18"
+ width="13"
+ height="12"
+ image_name="model_wizard\check_mark.png"/>
+ <text
+ top_delta="0"
+ left_delta="18"
+ name="lowest_detail_text"
+ width="200"
+ height="14">Generate Level of Detail: Lowest</text>
+ </panel>
+ <panel
+ top_delta="0"
+ left_delta="0"
+ height="245"
+ width="500"
+ name="content2"
+ bg_opaque_color="DkGray2"
+ background_visible="true"
+ background_opaque="true">
+ <text top="10" left="10" width="85" text_color="White" follows="left|top" height="15" name="lod_label">
+ Model Preview:
+ </text>
+ <combo_box left_pad="5" top_delta="-2" follows="left|top" list_position="below" height="18"
+ name="preview_lod_combo2" width="90" tool_tip="LOD to view in preview render">
+ <combo_item name="high">
+ High
+ </combo_item>
+ <combo_item name="medium">
+ Medium
+ </combo_item>
+ <combo_item name="lowest">
+ Lowest
+ </combo_item>
+ <combo_item name="low">
+ Low
+ </combo_item>
+ </combo_box>
+ <panel
+ left="10"
+ top_pad="5"
+ name="preview_panel"
+ bevel_style="none"
+ highlight_light_color="0.09 0.09 0.09 1"
+ border_style="line"
+ border="true"
+ height="175"
+ follows="all"
+ width="175">
+ </panel>
+ <text top="35" left="220" text_color="White" font="SansSerifSmallBold" width="300" height="4">Performance</text>
+ <text top="55" left="200" halign="center" width="130" word_wrap="true" font="SansSerifSmall" height="80">Faster rendering but less detailed; lowers Resource (prim) cost.</text>
+ <text top="35" left="380" text_color="White" font="SansSerifSmallBold" width="300" height="4">Accuracy</text>
+ <text top="55" left="360" halign="center" width="130" word_wrap="true" font="SansSerifSmall" height="80">More detailed model but slower; increases Resource (prim) cost.</text>
+
+ <slider
+ follows="left|top"
+ height="20"
+ increment="1"
+ layout="topleft"
+ left="200"
+ max_val="2"
+ initial_value="1"
+ min_val="0"
+ name="accuracy_slider"
+ show_text="false"
+ top="105"
+ width="290" />
+ <text
+ font="SansSerifSmall"
+ top_pad="0"
+ width="300"
+ left_delta="6"
+ height="4">' ' '</text>
+
+
+ <icon
+ top_pad="10"
+ left_delta="0"
+ width="280"
+ height="2"
+ image_name="model_wizard\divider_line.png"/>
+
+ <text top_delta="25" width="200" text_color="White" left_delta="50" name="streaming cost" height="20">Resource Cost: [COST]</text>
+ <text top_delta="25" width="100" text_color="White" left_delta="0" height="20">Upload Fee:</text>
+ <text
+ top_pad="5"
+ width="130"
+ height="14"
+ left="10"
+ text_color="White"
+ word_wrap="true">
+ Dimensions (meters):
+ </text>
+ <text
+ top_pad="0"
+ width="160"
+ height="15"
+ font="SansSerifSmallBold"
+ text_color="White"
+ name="dimensions"
+ left_delta="0">
+ X: Y: Z:
+ </text>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_dividers"
+ left_delta="41">
+ | |
+ </text>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_x"
+ left_delta="-25"/>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_y"
+ left_delta="46"/>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_z"
+ left_delta="46"/>
+ </panel>
+ </panel>
+
+
+
+ <panel
+ height="388"
+ top_delta="0"
+ name="physics_panel"
+ visible="false"
+ width="530"
+ left="0">
+ <panel
+ height="20"
+ top_pad="20"
+ name="header_panel"
+ width="500"
+ bg_opaque_color="DkGray2"
+ background_visible="true"
+ background_opaque="true"
+ left="20">
+ <text
+ width="200"
+ left="10"
+ name="header_text"
+ top="2"
+ height="10"
+ font="SansSerifBig"
+ layout="topleft">
+ Physics
+ </text>
+ </panel>
+ <text
+ top_pad="14"
+ width="460"
+ height="50"
+ font="SansSerifSmall"
+ layout="topleft"
+ name="description"
+ word_wrap="true"
+ left_delta="0">
+ The wizard will create a physical shape, which determines how the object interacts with other objects and avatars. Set the slider to the detail level most appropriate for how your object will be used:
+ </text>
+ <panel
+ top_delta="40"
+ left="15"
+ height="265"
+ width="500"
+ name="content"
+ bg_opaque_color="DkGray2"
+ background_visible="true"
+ background_opaque="true">
+ <text top="15" left="30" text_color="White" font="SansSerifSmallBold" width="300" height="4">Performance</text>
+ <text top="35" left="10" halign="center" width="130" word_wrap="true" font="SansSerifSmall" height="80">Faster rendering but less detailed; lowers Resource (prim) cost.</text>
+ <text top="15" left="390" text_color="White" font="SansSerifSmallBold" width="300" height="4">Accuracy</text>
+ <text top="35" left="360" halign="center" width="130" word_wrap="true" font="SansSerifSmall" height="80">More detailed model but slower; increases Resource (prim) cost.</text>
+
+ <slider
+ follows="left|top"
+ height="22"
+ increment=".1"
+ layout="topleft"
+ left="20"
+ max_val="1"
+ initial_value="0.5"
+ min_val="0"
+ name="physics_slider"
+ show_text="false"
+ top="80"
+ width="440" />
+ <text
+ font="SansSerifSmall"
+ top_pad="0"
+ width="500"
+ left_delta="6"
+ height="4">' ' ' ' ' ' ' ' ' ' '</text>
+ <text top_pad="10" width="110" halign="center" word_wrap="true" left="25" height="40">Recommended for solid objects</text>
+ <text top_delta="0" width="110" halign="center" word_wrap="true" left="190" height="40">Recommended for buildings</text>
+ <text top_delta="0" width="110" halign="center" word_wrap="true" left="350" height="40">Recommended for vehicles</text>
+
+
+ <icon
+ top_pad="5"
+ left="15"
+ width="470"
+ height="2"
+ image_name="model_wizard\divider_line.png"/>
+
+ <text top_delta="20" width="180" text_color="White" left="160" name="streaming cost" height="20">Resource Cost: [COST]</text>
+ <text top_delta="26" width="180" text_color="White" left_delta="0" name="physics cost" height="20">Physics Cost: [COST]</text>
+ <text top_delta="26" width="180" text_color="White" left_delta="0" height="20">Upload Fee:</text>
+
+ </panel>
+ </panel>
+
+
+ <panel
+ height="388"
+ top_delta="0"
+ name="review_panel"
+ visible="false"
+ width="530"
+ left="0">
+ <panel
+ height="22"
+ top_pad="16"
+ name="header_panel"
+ width="500"
+ bg_opaque_color="DkGray2"
+ background_visible="true"
+ background_opaque="true"
+ left="20">
+ <text
+ width="200"
+ left="10"
+ name="header_text"
+ text_color="White"
+ top="3"
+ height="10"
+ font="SansSerifBig"
+ layout="topleft">
+ Review
+ </text>
+ </panel>
+ <text
+ top_pad="14"
+ width="460"
+ height="24"
+ font="SansSerifSmall"
+ layout="topleft"
+ name="description"
+ word_wrap="true"
+ left_delta="10">
+ Review the details below then click. Upload to upload your model. Your L$ balance will be charged when you click Upload.
+ </text>
+ <icon
+ top_pad="10"
+ left="20"
+ width="495"
+ height="2"
+ image_name="model_wizard\divider_line.png"/>
+ <panel
+ top_pad="5"
+ left="15"
+ height="245"
+ width="500"
+ name="content">
+ <text top="10" left="10" width="85" text_color="White" follows="left|top" height="15" name="lod_label">
+ Model Preview:
+ </text>
+ <combo_box left_pad="5" top_delta="-5" follows="left|top" list_position="below" height="22"
+ name="preview_lod_combo" width="90" tool_tip="LOD to view in preview render">
+ <combo_item name="high">
+ High
+ </combo_item>
+ <combo_item name="medium">
+ Medium
+ </combo_item>
+ <combo_item name="lowest">
+ Lowest
+ </combo_item>
+ <combo_item name="low">
+ Low
+ </combo_item>
+ </combo_box>
+ <panel
+ left="10"
+ top_pad="10"
+ name="preview_panel"
+ bevel_style="none"
+ highlight_light_color="0.09 0.09 0.09 1"
+ border_style="line"
+ border="true"
+ height="190"
+ follows="all"
+ width="190">
+ </panel>
+ <text
+ top_pad="8"
+ width="130"
+ height="14"
+ left="10"
+ text_color="White"
+ word_wrap="true">
+ Dimensions (meters):
+ </text>
+ <text
+ top_pad="0"
+ width="160"
+ height="15"
+ font="SansSerifSmallBold"
+ text_color="White"
+ name="dimensions"
+ left_delta="0">
+ X: Y: Z:
+ </text>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_dividers"
+ left_delta="41">
+ | |
+ </text>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_x"
+ left_delta="-25"/>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_y"
+ left_delta="46"/>
+ <text
+ top_delta="0"
+ width="160"
+ height="15"
+ name="dimension_z"
+ left_delta="46"/>
+ </panel>
+ <text
+ width="300"
+ height="12"
+ top="125"
+ name="streaming cost"
+ left="230"
+ font="SansSerifSmallBold"
+ text_color="White">Resource Cost: [COST]</text>
+ <text
+ width="285"
+ height="30"
+ top_pad="0"
+ left_delta="0"
+ word_wrap="true"
+ font="SansSerifItalic">This is the cost to your Region's prim/object limit, at default scale</text>
+ <text
+ width="300"
+ height="12"
+ name="physics cost"
+ top_pad="10"
+ left_delta="0"
+ font="SansSerifSmallBold"
+ text_color="White">Physics Cost: [COST]</text>
+ <text
+ width="285"
+ height="30"
+ top_pad="0"
+ left_delta="0"
+ word_wrap="true"
+ font="SansSerifItalic">This is the cost to your Region's prim/object limit, at default scale</text>
+ <text
+ width="200"
+ height="12"
+ top_pad="10"
+ left_delta="0"
+ font="SansSerifSmallBold"
+ text_color="White">Upload Fee:</text>
+ <text
+ width="285"
+ height="26"
+ top_pad="0"
+ left_delta="0"
+ word_wrap="true"
+ font="SansSerifItalic">This is the amount the upload will cost.</text>
+ <check_box
+ height="16"
+ layout="topleft"
+ left_delta="0"
+ name="confirm_checkbox"
+ top_pad="15"
+ width="16" />
+ <text
+ height="100"
+ width="240"
+ word_wrap="true"
+ left_delta="25"
+ top_delta="0">I confirm that I have the appropriate rights to the material contained in this model. [secondlife:///app/floater/learn_more Learn more]</text>
+ </panel>
+
+
+
+
+ <panel
+ height="388"
+ top_delta="0"
+ name="upload_panel"
+ visible="false"
+ width="530"
+ left="0">
+ <panel
+ height="20"
+ top_pad="20"
+ name="header_panel"
+ width="500"
+ bg_opaque_color="DkGray2"
+ background_visible="true"
+ background_opaque="true"
+ left="20">
+ <text
+ width="200"
+ left="10"
+ name="header_text"
+ top="2"
+ text_color="White"
+ height="10"
+ font="SansSerifBig"
+ layout="topleft">
+ Upload Complete!
+ </text>
+ </panel>
+ <text
+ top_pad="14"
+ width="460"
+ height="20"
+ font="SansSerifSmall"
+ layout="topleft"
+ name="description"
+ word_wrap="true"
+ left_delta="0">
+ Congratulations! Your model has been sucessfully uploaded. You will find the model in the Objects folder in your inventory.
+ </text>
+ <icon
+ top_pad="15"
+ left_delta="0"
+ width="495"
+ height="2"
+ image_name="model_wizard\divider_line.png"/>
+ </panel>
+
+
+
+ <button
+ top="440"
+ right="-245"
+ width="90"
+ height="22"
+ name="back"
+ label="&lt;&lt; Back" />
+ <button
+ top_delta="0"
+ right="-150"
+ width="90"
+ height="22"
+ name="next"
+ label="Next &gt;&gt; " />
+ <button
+ top_delta="0"
+ right="-150"
+ width="90"
+ height="22"
+ visible="false"
+ name="upload"
+ tool_tip="Upload to simulator"
+ label="Upload" />
+ <button
+ top_delta="0"
+ right="-15"
+ width="90"
+ height="22"
+ name="cancel"
+ label="Cancel" />
+ <button
+ top_delta="0"
+ right="-15"
+ width="90"
+ height="22"
+ name="close"
+ visible="false"
+ label="Close" />
+ <spinner visible="false" left="10" height="20" follows="top|left" width="80" top_pad="-50" value="1.0" min_val="0.01" max_val="64.0" name="import_scale"/>
+
+ <string name="status_idle">Idle</string>
+ <string name="status_reading_file">Loading...</string>
+ <string name="status_generating_meshes">Generating Meshes...</string>
+ <string name="high">High</string>
+ <string name="medium">Medium</string>
+ <string name="low">Low</string>
+ <string name="lowest">Lowest</string>
+ <string name="mesh_status_good">Ship it!</string>
+ <string name="mesh_status_na">N/A</string>
+ <string name="mesh_status_none">None</string>
+ <string name="mesh_status_submesh_mismatch">Levels of detail have a different number of textureable faces.</string>
+ <string name="mesh_status_mesh_mismatch">Levels of detail have a different number of mesh instances.</string>
+ <string name="mesh_status_too_many_vertices">Level of detail has too many vertices.</string>
+ <string name="mesh_status_missing_lod">Missing required level of detail.</string>
+ <string name="layer_all">All</string>
+ <!-- Text to display in physics layer combo box for "all layers" -->
+
+</floater>
diff --git a/indra/newview/skins/default/xui/en/floater_price_for_listing.xml b/indra/newview/skins/default/xui/en/floater_price_for_listing.xml
new file mode 100644
index 0000000000..6312366b86
--- /dev/null
+++ b/indra/newview/skins/default/xui/en/floater_price_for_listing.xml
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
+<floater
+ legacy_header_height="18"
+ can_minimize="false"
+ height="240"
+ layout="topleft"
+ name="price_for_listing"
+ help_topic="price_for_listing"
+ title="PUBLISH CLASSIFIED AD"
+ width="320">
+ <text
+ type="string"
+ length="1"
+ bottom="200"
+ follows="top|left"
+ font="SansSerif"
+ height="165"
+ layout="topleft"
+ left="15"
+ word_wrap="true"
+ name="explanation_text">
+ Your classified ad will run for one week from the day it is published.
+
+Your ad&apos;s position in the classified listings is determined by how much you choose to pay.
+
+The highest paid ads go to the top of the list, and appear higher in searches.
+ </text>
+ <text
+ type="string"
+ length="1"
+ follows="top|right"
+ font="SansSerif"
+ height="20"
+ layout="topleft"
+ left="140"
+ name="price_text"
+ top_delta="135"
+ width="85">
+ Price for Ad:
+ </text>
+ <text
+ type="string"
+ length="1"
+ follows="top|right"
+ font="SansSerif"
+ height="20"
+ layout="topleft"
+ left_pad="4"
+ name="price_symbol"
+ top_delta="0"
+ width="20">
+ L$
+ </text>
+ <line_editor
+ follows="top|left"
+ height="20"
+ layout="topleft"
+ left_pad="0"
+ max_length="6"
+ top_delta="-4"
+ name="price_edit"
+ width="60" />
+ <button
+ follows="top|left"
+ height="22"
+ label="OK"
+ layout="topleft"
+ left="105"
+ name="set_price_btn"
+ top_pad="22"
+ width="100" />
+ <button
+ follows="top|left"
+ height="22"
+ label="Cancel"
+ layout="topleft"
+ left_pad="5"
+ name="cancel_btn"
+ width="100" />
+
+</floater>
diff --git a/indra/newview/skins/default/xui/en/floater_tools.xml b/indra/newview/skins/default/xui/en/floater_tools.xml
index 85182c1c28..a0a370dc12 100644
--- a/indra/newview/skins/default/xui/en/floater_tools.xml
+++ b/indra/newview/skins/default/xui/en/floater_tools.xml
@@ -2,7 +2,7 @@
<floater
legacy_header_height="18"
follows="left|top|right"
- height="580"
+ height="780"
layout="topleft"
bg_opaque_image="Window_NoTitle_Foreground"
bg_alpha_image="Window_NoTitle_Background"
@@ -295,22 +295,24 @@
width="100">
þ: [COUNT]
</text>
- <check_box
+ <check_box
control_name="ScaleUniform"
height="19"
label=""
layout="topleft"
left="143"
name="checkbox uniform"
- top="50"
+ top="50"
width="20" />
<text
height="19"
label="Stretch Both Sides"
- left="163"
+ left_delta="20"
name="checkbox uniform label"
- top="55"
+ top_delta="2"
width="120"
+ layout="topleft"
+ follows="top|left"
wrap="true">
Stretch Both Sides
</text>
@@ -323,6 +325,7 @@
left="143"
name="checkbox stretch textures"
top_pad="-6"
+ follows="left|top"
width="134" />
<check_box
control_name="SnapEnabled"
@@ -361,9 +364,10 @@
image_selected="ForwardArrow_Press"
image_unselected="ForwardArrow_Off"
layout="topleft"
+ follows="top|left"
name="Options..."
tool_tip="See more grid options"
- top_delta="0"
+ top_pad="-22"
right="-10"
width="18"
height="23" >
@@ -745,18 +749,73 @@
<button.commit_callback
function="BuildTool.applyToSelection"/>
</button>
- <text
+ <text
+ text_color="LtGray_50"
+ type="string"
+ length="1"
+ height="10"
+ follows="left|top"
+ halign="right"
+ layout="topleft"
+ right="-10"
+ name="obj_count"
+ top_pad="5"
+ width="143">
+ Objects: [COUNT]
+ </text>
+ <text
text_color="LtGray_50"
type="string"
length="1"
- height="10"
+ height="10"
follows="left|top"
halign="right"
layout="topleft"
right="-10"
- name="obj_count"
- top_pad="7"
+ name="prim_count"
width="143">
+ Prims: [COUNT]
+ </text>
+ <text
+ text_color="LtGray_50"
+ type="string"
+ length="1"
+ height="10"
+ follows="left|top"
+ halign="right"
+ layout="topleft"
+ right="-120"
+ name="linked_set_count"
+ top="144"
+ width="80">
+ Linked Sets: [COUNT]
+ </text>
+ <text
+ text_color="LtGray_50"
+ type="string"
+ length="1"
+ height="10"
+ follows="left|top"
+ halign="right"
+ layout="topleft"
+ top_delta="0"
+ right="-8"
+ name="linked_set_cost"
+ tool_tip="Cost of currently selected linked sets as [prims],[physics complexity]"
+ width="80">
+ Cost: [COST] / [PHYSICS]
+ </text>
+ <text
+ text_color="LtGray_50"
+ type="string"
+ length="1"
+ follows="left|top"
+ halign="right"
+ layout="topleft"
+ top_pad="5"
+ right="-120"
+ name="object_count"
+ width="80">
Objects: [COUNT]
</text>
<text
@@ -766,14 +825,42 @@
follows="left|top"
halign="right"
layout="topleft"
- right="-10"
- name="prim_count"
- width="143">
- Prims: [COUNT]
+ top_delta="0"
+ right="-8"
+ name="object_cost"
+ tool_tip="Cost of currently selected objects as [prims] / [physics complexity]"
+ width="80">
+ Cost: [COST] / [PHYSICS]
</text>
+ <!-- <text -->
+ <!-- text_color="LtGray_50" -->
+ <!-- type="string" -->
+ <!-- length="1" -->
+ <!-- height="10" -->
+ <!-- follows="left|top" -->
+ <!-- halign="right" -->
+ <!-- layout="topleft" -->
+ <!-- right="-10" -->
+ <!-- name="obj_count" -->
+ <!-- top_pad="5" -->
+ <!-- width="143"> -->
+ <!-- Objects: [COUNT] -->
+ <!-- </text> -->
+ <!-- <text -->
+ <!-- text_color="LtGray_50" -->
+ <!-- type="string" -->
+ <!-- length="1" -->
+ <!-- follows="left|top" -->
+ <!-- halign="right" -->
+ <!-- layout="topleft" -->
+ <!-- right="-10" -->
+ <!-- name="prim_count" -->
+ <!-- width="143"> -->
+ <!-- Prims: [COUNT] -->
+ <!-- </text> -->
<tab_container
follows="left|top"
- height="410"
+ height="610"
halign="center"
left="0"
name="Object Info Tabs"
@@ -783,7 +870,8 @@
tab_height="25"
top="173"
width="295">
- <panel
+
+<panel
border="false"
follows="all"
label="General"
@@ -1253,7 +1341,7 @@ even though the user gets a free copy.
<panel
border="false"
follows="all"
- height="367"
+ height="567"
label="Object"
layout="topleft"
left_delta="0"
@@ -1262,6 +1350,9 @@ even though the user gets a free copy.
name="Object"
top="16"
width="295">
+ <panel.string name="None">None</panel.string>
+ <panel.string name="Prim">Prim</panel.string>
+ <panel.string name="Convex Hull">Convex Hull</panel.string>
<check_box
height="19"
label="Locked"
@@ -1372,7 +1463,7 @@ even though the user gets a free copy.
label_width="10"
layout="topleft"
left_delta="0"
- max_val="10"
+ max_val="64"
min_val="0.01"
name="Scale X"
text_enabled_color="1 1 1 1"
@@ -1387,7 +1478,7 @@ even though the user gets a free copy.
label_width="10"
layout="topleft"
left_delta="0"
- max_val="10"
+ max_val="64"
min_val="0.01"
name="Scale Y"
text_enabled_color="1 1 1 1"
@@ -1402,7 +1493,7 @@ even though the user gets a free copy.
label_width="10"
layout="topleft"
left_delta="0"
- max_val="10"
+ max_val="64"
min_val="0.01"
name="Scale Z"
text_enabled_color="1 1 1 1"
@@ -1468,6 +1559,99 @@ even though the user gets a free copy.
text_enabled_color="1 1 1 1"
top_pad="3"
width="87" />
+ <text
+ type="string"
+ length="1"
+ follows="left|top"
+ height="10"
+ layout="topleft"
+ left_delta="0"
+ name="label physicsshapetype"
+ top_pad="50"
+ width="121">
+ Physics Shape Type:
+ </text>
+ <combo_box
+ height="23"
+ top_delta="-5"
+ layout="topleft"
+ follows="left|top"
+ name="Physics Shape Type Combo Ctrl"
+ tool_tip="Choose the physics shape type"
+ left_pad="5"
+ width="108"/>
+
+ <spinner
+ follows="left|top"
+ height="19"
+ increment="1"
+ initial_value="1"
+ label="Gravity"
+ label_width="70"
+ layout="topleft"
+ left="10"
+ min_val="-1"
+ max_val="28"
+ name="Physics Gravity"
+ top_pad="10"
+ width="132" />
+
+ <check_box
+ height="19"
+ label="Override material"
+ layout="topleft"
+ left_delta="0"
+ name="Physics Material Override"
+ tool_tip="Override Material"
+ top_pad="10"
+ width="132" />
+
+ <spinner
+ follows="left|top"
+ height="19"
+ increment="0.1"
+ initial_value="0"
+ label="Friction"
+ label_width="70"
+ layout="topleft"
+ left_delta="0"
+ max_val="255"
+ min_val="0"
+ name="Physics Friction"
+ top_pad="4"
+ width="132" />
+
+ <spinner
+ follows="left|top"
+ height="19"
+ increment="0.1"
+ initial_value="0"
+ label="Density"
+ label_width="70"
+ layout="topleft"
+ left_delta="0"
+ max_val="22587"
+ min_val="1"
+ name="Physics Density"
+ top_pad="4"
+ width="132" />
+
+ <spinner
+ follows="left|top"
+ height="19"
+ increment="0.01"
+ initial_value="0"
+ label="Restitution"
+ label_width="70"
+ layout="topleft"
+ left_delta="0"
+ max_val="1"
+ min_val="0"
+ name="Physics Restitution"
+ top_pad="4"
+ width="132" />
+
+
<!-- <text
type="string"
@@ -2046,6 +2230,10 @@ even though the user gets a free copy.
label="Cylinder"
name="Cylinder"
value="Cylinder" />
+ <combo_box.item
+ label="Mesh"
+ name="Mesh"
+ value="Mesh" />
</combo_box>
</panel>
<panel
@@ -2378,7 +2566,7 @@ even though the user gets a free copy.
initial_value="0"
layout="topleft"
left_delta="0"
- max_val="90"
+ max_val="100"
name="ColorTrans"
top_pad="4"
width="80" />
diff --git a/indra/newview/skins/default/xui/en/menu_inventory_add.xml b/indra/newview/skins/default/xui/en/menu_inventory_add.xml
index ae98abf4fb..62db15d456 100644
--- a/indra/newview/skins/default/xui/en/menu_inventory_add.xml
+++ b/indra/newview/skins/default/xui/en/menu_inventory_add.xml
@@ -42,6 +42,18 @@
<menu_item_call.on_enable
function="File.EnableUpload" />
</menu_item_call>
+ <menu_item_call
+ label="Model..."
+ layout="topleft"
+ name="Upload Model">
+ <menu_item_call.on_click
+ function="File.UploadModel"
+ parameter="" />
+ <menu_item_call.on_enable
+ function="File.EnableUploadModel" />
+ <menu_item_call.on_visible
+ function="File.VisibleUploadModel"/>
+ </menu_item_call>
<menu_item_call
label="Bulk (L$[COST] per file)..."
layout="topleft"
@@ -231,4 +243,4 @@
parameter="eyes" />
</menu_item_call>
</menu>
-</menu> \ No newline at end of file
+</menu>
diff --git a/indra/newview/skins/default/xui/en/menu_model_import_gear_default.xml b/indra/newview/skins/default/xui/en/menu_model_import_gear_default.xml
new file mode 100644
index 0000000000..2650903f88
--- /dev/null
+++ b/indra/newview/skins/default/xui/en/menu_model_import_gear_default.xml
@@ -0,0 +1,79 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
+<toggleable_menu
+ bottom="806"
+ layout="topleft"
+ left="0"
+ mouse_opaque="false"
+ name="model_menu_gear_default"
+ visible="false">
+ <menu_item_check
+ label="Show edges"
+ layout="topleft"
+ name="show_edges">
+ <on_click
+ function="ModelImport.ViewOption.Action"
+ parameter="show_edges" />
+ <on_check
+ function="ModelImport.ViewOption.Check"
+ parameter="show_edges" />
+ <on_enable
+ function="ModelImport.ViewOption.Enabled"
+ parameter="show_edges" />
+ </menu_item_check>
+ <menu_item_check
+ label="Show physics"
+ layout="topleft"
+ name="show_physics">
+ <on_click
+ function="ModelImport.ViewOption.Action"
+ parameter="show_physics" />
+ <on_check
+ function="ModelImport.ViewOption.Check"
+ parameter="show_physics" />
+ <on_enable
+ function="ModelImport.ViewOption.Enabled"
+ parameter="show_physics" />
+ </menu_item_check>
+ <menu_item_check
+ label="Show textures"
+ layout="topleft"
+ name="show_textures">
+ <on_click
+ function="ModelImport.ViewOption.Action"
+ parameter="show_textures" />
+ <on_check
+ function="ModelImport.ViewOption.Check"
+ parameter="show_textures" />
+ <on_enable
+ function="ModelImport.ViewOption.Enabled"
+ parameter="show_textures" />
+ </menu_item_check>
+ <menu_item_check
+ label="Show skin weight"
+ layout="topleft"
+ name="show_skin_weight">
+ <on_click
+ function="ModelImport.ViewOption.Action"
+ parameter="show_skin_weight" />
+ <on_check
+ function="ModelImport.ViewOption.Check"
+ parameter="show_skin_weight" />
+ <on_enable
+ function="ModelImport.ViewOption.Enabled"
+ parameter="show_skin_weight" />
+ </menu_item_check>
+ <menu_item_check
+ label="Show joint positions"
+ layout="topleft"
+ name="show_joint_positions">
+ <on_click
+ function="ModelImport.ViewOption.Action"
+ parameter="show_joint_positions" />
+ <on_check
+ function="ModelImport.ViewOption.Check"
+ parameter="show_joint_positions" />
+ <on_enable
+ function="ModelImport.ViewOption.Enabled"
+ parameter="show_joint_positions" />
+ </menu_item_check>
+</toggleable_menu>
diff --git a/indra/newview/skins/default/xui/en/menu_viewer.xml b/indra/newview/skins/default/xui/en/menu_viewer.xml
index 606ff69599..8655a6bf97 100644
--- a/indra/newview/skins/default/xui/en/menu_viewer.xml
+++ b/indra/newview/skins/default/xui/en/menu_viewer.xml
@@ -89,7 +89,7 @@
visibility_control="VoiceMorphingEnabled">
<menu_item_check.on_check
function="Floater.Visible"
- parameter="voice_effect" />
+ Parameter="voice_effect" />
<menu_item_check.on_click
function="Floater.Toggle"
parameter="voice_effect" />
@@ -961,6 +961,30 @@
parameter="Upload Animation" />
</menu_item_call>
<menu_item_call
+ label="Model..."
+ layout="topleft"
+ name="Upload Model">
+ <menu_item_call.on_click
+ function="File.UploadModel"
+ parameter="" />
+ <menu_item_call.on_enable
+ function="File.EnableUploadModel" />
+ <menu_item_call.on_visible
+ function="File.VisibleUploadModel"/>
+ </menu_item_call>
+ <menu_item_call
+ label="Model Wizard..."
+ layout="topleft"
+ name="Upload Model Wizard">
+ <menu_item_call.on_click
+ function="Floater.Show"
+ parameter="upload_model_wizard" />
+ <menu_item_call.on_enable
+ function="File.EnableUploadModel" />
+ <menu_item_call.on_visible
+ function="File.VisibleUploadModel"/>
+ </menu_item_call>
+ <menu_item_call
label="Bulk (L$[COST] per file)..."
layout="topleft"
name="Bulk Upload">
@@ -1331,15 +1355,15 @@
parameter="character" />
</menu_item_check>
<menu_item_check
- label="SurfacePath"
- name="SurfacePath"
+ label="Surface Patch"
+ name="Surface Patch"
shortcut="control|alt|shift|5">
<menu_item_check.on_check
function="Advanced.CheckRenderType"
- parameter="surfacePath" />
+ parameter="surfacePatch" />
<menu_item_check.on_click
function="Advanced.ToggleRenderType"
- parameter="surfacePath" />
+ parameter="surfacePatch" />
</menu_item_check>
<menu_item_check
label="Sky"
@@ -1950,6 +1974,17 @@
function="ToggleControl"
parameter="DebugShowTime" />
</menu_item_check>
+ <menu_item_check
+ label="Show Upload Cost"
+ layout="topleft"
+ name="Show Upload Cost">
+ <menu_item_check.on_check
+ function="CheckControl"
+ parameter="DebugShowUploadCost" />
+ <menu_item_check.on_click
+ function="ToggleControl"
+ parameter="DebugShowUploadCost" />
+ </menu_item_check>
<menu_item_check
label="Show Render Info"
name="Show Render Info">
@@ -2133,6 +2168,16 @@
parameter="bboxes" />
</menu_item_check>
<menu_item_check
+ label="Normals"
+ name="Normals">
+ <menu_item_check.on_check
+ function="Advanced.CheckInfoDisplay"
+ parameter="normals" />
+ <menu_item_check.on_click
+ function="Advanced.ToggleInfoDisplay"
+ parameter="normals" />
+ </menu_item_check>
+ <menu_item_check
label="Octree"
name="Octree">
<menu_item_check.on_check
@@ -2153,6 +2198,16 @@
parameter="shadow frusta" />
</menu_item_check>
<menu_item_check
+ label="Physics Shapes"
+ name="Physics Shapes">
+ <menu_item_check.on_check
+ function="Advanced.CheckInfoDisplay"
+ parameter="physics shapes" />
+ <menu_item_check.on_click
+ function="Advanced.ToggleInfoDisplay"
+ parameter="physics shapes" />
+ </menu_item_check>
+ <menu_item_check
label="Occlusion"
name="Occlusion">
<menu_item_check.on_check
@@ -2223,6 +2278,26 @@
parameter="face area" />
</menu_item_check>
<menu_item_check
+ label="LOD Info"
+ name="LOD Info">
+ <menu_item_check.on_check
+ function="Advanced.CheckInfoDisplay"
+ parameter="lod info" />
+ <menu_item_check.on_click
+ function="Advanced.ToggleInfoDisplay"
+ parameter="lod info" />
+ </menu_item_check>
+ <menu_item_check
+ label="Build Queue"
+ name="Build Queue">
+ <menu_item_check.on_check
+ function="Advanced.CheckInfoDisplay"
+ parameter="build queue" />
+ <menu_item_check.on_click
+ function="Advanced.ToggleInfoDisplay"
+ parameter="build queue" />
+ </menu_item_check>
+ <menu_item_check
label="Lights"
name="Lights">
<menu_item_check.on_check
@@ -2308,19 +2383,6 @@
<menu_item_check.on_enable
function="Advanced.EnableObjectObjectOcclusion" />
</menu_item_check>
- <menu_item_check
- label="Framebuffer Objects"
- name="Framebuffer Objects">
- <menu_item_check.on_check
- function="CheckControl"
- parameter="RenderUseFBO" />
- <menu_item_check.on_click
- function="ToggleControl"
- parameter="RenderUseFBO" />
- <menu_item_check.on_enable
- function="Advanced.EnableRenderFBO" />
- </menu_item_check>
-
<menu_item_separator />
<menu_item_check
@@ -2747,7 +2809,6 @@
function="Floater.Toggle"
parameter="region_debug_console" />
</menu_item_check>
-
<menu_item_separator />
<menu_item_check
@@ -3145,7 +3206,7 @@
<menu_item_call.on_click
function="Advanced.LeaveAdminStatus" />
</menu_item_call>
- <menu_item_check
+ <menu_item_check
label="Show Admin Menu"
name="View Admin Options">
<menu_item_check.on_enable
diff --git a/indra/newview/skins/default/xui/en/notifications.xml b/indra/newview/skins/default/xui/en/notifications.xml
index 6ecaef1bf3..f703acaa66 100644
--- a/indra/newview/skins/default/xui/en/notifications.xml
+++ b/indra/newview/skins/default/xui/en/notifications.xml
@@ -6737,7 +6737,7 @@ Unable to find the help topic for this element.
<tag>fail</tag>
</notification>
- <notification
+ <notification
icon="alertmodal.tga"
name="ObjectMediaFailure"
type="alertmodal">
@@ -6769,6 +6769,17 @@ Your voice has been muted by moderator.
name="okbutton"
yestext="OK"/>
</notification>
+
+ <notification
+ icon="alertmodal.tga"
+ name="UploadCostConfirmation"
+ type="alertmodal">
+This upload will cost L$[PRICE], do you wish to continue with the upload?
+ <usetemplate
+ name="okcancelbuttons"
+ notext="Cancel"
+ yestext="Upload"/>
+ </notification>
<notification
icon="alertmodal.tga"
@@ -6797,6 +6808,14 @@ The button will be shown when there is enough space for it.
type="notifytip">
Select residents to share with.
</notification>
+
+ <notification
+ name="MeshUploadError"
+ icon="alert.tga"
+ type="alert">
+ [LABEL] failed to upload: [MESSAGE] [IDENTIFIER] [INVALIDITY_IDENTIFIER]
+ </notification>
+
<notification
icon="notifytip.tga"
name="ShareItemsConfirmation"
@@ -6983,7 +7002,6 @@ Mute everyone?
notext="Cancel"
unique="true"/>
</notification>
-
<notification
name="HintChat"
label="Chat"
@@ -7213,9 +7231,6 @@ The site at &apos;&lt;nolink&gt;[HOST_NAME]&lt;/nolink&gt;&apos; in realm &apos;
yestext="Quit"
notext="Don't Quit"/>
</notification>
-
- <global name="UnsupportedCPU">
-- Your CPU speed does not meet the minimum requirements.
</global>
<global name="UnsupportedGLRequirements">
diff --git a/indra/newview/skins/default/xui/en/panel_place_profile.xml b/indra/newview/skins/default/xui/en/panel_place_profile.xml
index 7e89860c60..774a9e8bbf 100644
--- a/indra/newview/skins/default/xui/en/panel_place_profile.xml
+++ b/indra/newview/skins/default/xui/en/panel_place_profile.xml
@@ -191,7 +191,7 @@
width="310">
<panel
bg_alpha_color="DkGray2"
- follows="left|top|right"
+ follows="left|top|right|bottom"
height="580"
layout="topleft"
left="0"
diff --git a/indra/newview/skins/default/xui/en/panel_preferences_graphics1.xml b/indra/newview/skins/default/xui/en/panel_preferences_graphics1.xml
index 6573822d1a..70db3c6592 100644
--- a/indra/newview/skins/default/xui/en/panel_preferences_graphics1.xml
+++ b/indra/newview/skins/default/xui/en/panel_preferences_graphics1.xml
@@ -193,8 +193,19 @@
left_delta="0"
name="BumpShiny"
top_pad="1"
+ width="256" />
+ <check_box
+ control_name="RenderLocalLights"
+ height="16"
+ initial_value="true"
+ label="Local Lights"
+ layout="topleft"
+ left_delta="0"
+ name="LocalLights"
+ top_pad="1"
width="256" />
- <check_box
+ width="256" />
+ <check_box
control_name="VertexShaderEnable"
height="16"
initial_value="true"
@@ -221,7 +232,6 @@
<check_box.commit_callback
function="Pref.VertexShaderEnable" />
</check_box>
-<!-- DISABLED UNTIL WE REALLY WANT TO SUPPORT THIS
<check_box
control_name="RenderDeferred"
height="16"
@@ -283,7 +293,7 @@
name="2"
value="2"/>
</combo_box>
--->
+
<text
type="string"
length="1"
diff --git a/indra/newview/skins/default/xui/en/strings.xml b/indra/newview/skins/default/xui/en/strings.xml
index d0625d9755..b7bf2526ab 100644
--- a/indra/newview/skins/default/xui/en/strings.xml
+++ b/indra/newview/skins/default/xui/en/strings.xml
@@ -198,6 +198,7 @@
<string name="favorite">favorite</string>
<string name="symbolic link">link</string>
<string name="symbolic folder link">folder link</string>
+ <string name="mesh">mesh</string>
<!-- llvoavatar. Displayed in the avatar chat bubble -->
<string name="AvatarEditingAppearance">(Editing Appearance)</string>
@@ -2005,6 +2006,7 @@ Requests name of an avatar. When data is available the dataserver event will be
<string name="InvFolder Initial Outfits">Initial Outfits</string>
<string name="InvFolder My Outfits">My Outfits</string>
<string name="InvFolder Accessories">Accessories</string>
+ <string name="InvFolder Meshes">Meshes</string>
<!-- are used for Friends and Friends/All folders in Inventory "Calling cards" folder. See EXT-694-->
<string name="InvFolder Friends">Friends</string>
diff --git a/indra/newview/tests/llcapabilitylistener_test.cpp b/indra/newview/tests/llcapabilitylistener_test.cpp
index d691bb6c44..2ad08dc1f3 100644
--- a/indra/newview/tests/llcapabilitylistener_test.cpp
+++ b/indra/newview/tests/llcapabilitylistener_test.cpp
@@ -114,6 +114,7 @@ namespace tut
regionListener("testCapabilityListener", NULL, provider, LLUUID(), LLUUID()),
regionPump(regionListener.getCapAPI())
{
+ LLCurl::initClass();
provider.setCapability("good", server + "capability-test");
provider.setCapability("fail", server + "fail");
}
diff --git a/indra/newview/viewer_manifest.py b/indra/newview/viewer_manifest.py
index 483c9515db..2d7a6f7a67 100644
--- a/indra/newview/viewer_manifest.py
+++ b/indra/newview/viewer_manifest.py
@@ -1,975 +1,1032 @@
-#!/usr/bin/env python
-"""\
-@file viewer_manifest.py
-@author Ryan Williams
-@brief Description of all installer viewer files, and methods for packaging
- them into installers for all supported platforms.
-
-$LicenseInfo:firstyear=2006&license=viewerlgpl$
-Second Life Viewer Source Code
-Copyright (C) 2006-2011, Linden Research, Inc.
-
-This library is free software; you can redistribute it and/or
-modify it under the terms of the GNU Lesser General Public
-License as published by the Free Software Foundation;
-version 2.1 of the License only.
-
-This library is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public
-License along with this library; if not, write to the Free Software
-Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-
-Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
-$/LicenseInfo$
-"""
-import sys
-import os.path
-import re
-import tarfile
-import time
-viewer_dir = os.path.dirname(__file__)
-# add llmanifest library to our path so we don't have to muck with PYTHONPATH
-sys.path.append(os.path.join(viewer_dir, '../lib/python/indra/util'))
-from llmanifest import LLManifest, main, proper_windows_path, path_ancestors
-
-class ViewerManifest(LLManifest):
- def is_packaging_viewer(self):
- # Some commands, files will only be included
- # if we are packaging the viewer on windows.
- # This manifest is also used to copy
- # files during the build (see copy_w_viewer_manifest
- # and copy_l_viewer_manifest targets)
- return 'package' in self.args['actions']
-
- def construct(self):
- super(ViewerManifest, self).construct()
- self.exclude("*.svn*")
- self.path(src="../../scripts/messages/message_template.msg", dst="app_settings/message_template.msg")
- self.path(src="../../etc/message.xml", dst="app_settings/message.xml")
-
- if self.is_packaging_viewer():
- if self.prefix(src="app_settings"):
- self.exclude("logcontrol.xml")
- self.exclude("logcontrol-dev.xml")
- self.path("*.pem")
- self.path("*.ini")
- self.path("*.xml")
- self.path("*.db2")
-
- # include the entire shaders directory recursively
- self.path("shaders")
- # ... and the entire windlight directory
- self.path("windlight")
- self.end_prefix("app_settings")
-
- if self.prefix(src="character"):
- self.path("*.llm")
- self.path("*.xml")
- self.path("*.tga")
- self.end_prefix("character")
-
- # Include our fonts
- if self.prefix(src="fonts"):
- self.path("*.ttf")
- self.path("*.txt")
- self.end_prefix("fonts")
-
- # skins
- if self.prefix(src="skins"):
- self.path("paths.xml")
- # include the entire textures directory recursively
- if self.prefix(src="*/textures"):
- self.path("*/*.tga")
- self.path("*/*.j2c")
- self.path("*/*.jpg")
- self.path("*/*.png")
- self.path("*.tga")
- self.path("*.j2c")
- self.path("*.jpg")
- self.path("*.png")
- self.path("textures.xml")
- self.end_prefix("*/textures")
- self.path("*/xui/*/*.xml")
- self.path("*/xui/*/widgets/*.xml")
- self.path("*/*.xml")
-
- # Local HTML files (e.g. loading screen)
- if self.prefix(src="*/html"):
- self.path("*.png")
- self.path("*/*/*.html")
- self.path("*/*/*.gif")
- self.end_prefix("*/html")
- self.end_prefix("skins")
-
- # local_assets dir (for pre-cached textures)
- if self.prefix(src="local_assets"):
- self.path("*.j2c")
- self.path("*.tga")
- self.end_prefix("local_assets")
-
- # Files in the newview/ directory
- self.path("gpu_table.txt")
-
- def login_channel(self):
- """Channel reported for login and upgrade purposes ONLY;
- used for A/B testing"""
- # NOTE: Do not return the normal channel if login_channel
- # is not specified, as some code may branch depending on
- # whether or not this is present
- return self.args.get('login_channel')
-
- def grid(self):
- return self.args['grid']
- def channel(self):
- return self.args['channel']
- def channel_unique(self):
- return self.channel().replace("Second Life", "").strip()
- def channel_oneword(self):
- return "".join(self.channel_unique().split())
- def channel_lowerword(self):
- return self.channel_oneword().lower()
-
- def flags_list(self):
- """ Convenience function that returns the command-line flags
- for the grid"""
-
- # Set command line flags relating to the target grid
- grid_flags = ''
- if not self.default_grid():
- grid_flags = "--grid %(grid)s "\
- "--helperuri http://preview-%(grid)s.secondlife.com/helpers/" %\
- {'grid':self.grid()}
-
- # set command line flags for channel
- channel_flags = ''
- if self.login_channel() and self.login_channel() != self.channel():
- # Report a special channel during login, but use default
- channel_flags = '--channel "%s"' % (self.login_channel())
- elif not self.default_channel():
- channel_flags = '--channel "%s"' % self.channel()
-
- # Deal with settings
- setting_flags = ''
- if not self.default_channel() or not self.default_grid():
- if self.default_grid():
- setting_flags = '--settings settings_%s.xml'\
- % self.channel_lowerword()
- else:
- setting_flags = '--settings settings_%s_%s.xml'\
- % (self.grid(), self.channel_lowerword())
-
- return " ".join((channel_flags, grid_flags, setting_flags)).strip()
-
-
-class WindowsManifest(ViewerManifest):
- def final_exe(self):
- if self.default_channel():
- if self.default_grid():
- return "SecondLife.exe"
- else:
- return "SecondLifePreview.exe"
- else:
- return ''.join(self.channel().split()) + '.exe'
-
- def test_msvcrt_and_copy_action(self, src, dst):
- # This is used to test a dll manifest.
- # It is used as a temporary override during the construct method
- from test_win32_manifest import test_assembly_binding
- if src and (os.path.exists(src) or os.path.islink(src)):
- # ensure that destination path exists
- self.cmakedirs(os.path.dirname(dst))
- self.created_paths.append(dst)
- if not os.path.isdir(src):
- if(self.args['configuration'].lower() == 'debug'):
- test_assembly_binding(src, "Microsoft.VC80.DebugCRT", "8.0.50727.4053")
- else:
- test_assembly_binding(src, "Microsoft.VC80.CRT", "8.0.50727.4053")
- self.ccopy(src,dst)
- else:
- raise Exception("Directories are not supported by test_CRT_and_copy_action()")
- else:
- print "Doesn't exist:", src
-
- def test_for_no_msvcrt_manifest_and_copy_action(self, src, dst):
- # This is used to test that no manifest for the msvcrt exists.
- # It is used as a temporary override during the construct method
- from test_win32_manifest import test_assembly_binding
- from test_win32_manifest import NoManifestException, NoMatchingAssemblyException
- if src and (os.path.exists(src) or os.path.islink(src)):
- # ensure that destination path exists
- self.cmakedirs(os.path.dirname(dst))
- self.created_paths.append(dst)
- if not os.path.isdir(src):
- try:
- if(self.args['configuration'].lower() == 'debug'):
- test_assembly_binding(src, "Microsoft.VC80.DebugCRT", "")
- else:
- test_assembly_binding(src, "Microsoft.VC80.CRT", "")
- raise Exception("Unknown condition")
- except NoManifestException, err:
- pass
- except NoMatchingAssemblyException, err:
- pass
-
- self.ccopy(src,dst)
- else:
- raise Exception("Directories are not supported by test_CRT_and_copy_action()")
- else:
- print "Doesn't exist:", src
-
- def enable_crt_manifest_check(self):
- if self.is_packaging_viewer():
- WindowsManifest.copy_action = WindowsManifest.test_msvcrt_and_copy_action
-
- def enable_no_crt_manifest_check(self):
- if self.is_packaging_viewer():
- WindowsManifest.copy_action = WindowsManifest.test_for_no_msvcrt_manifest_and_copy_action
-
- def disable_manifest_check(self):
- if self.is_packaging_viewer():
- del WindowsManifest.copy_action
-
- def construct(self):
- super(WindowsManifest, self).construct()
-
- self.enable_crt_manifest_check()
-
- if self.is_packaging_viewer():
- # Find secondlife-bin.exe in the 'configuration' dir, then rename it to the result of final_exe.
- self.path(src='%s/secondlife-bin.exe' % self.args['configuration'], dst=self.final_exe())
-
- # Plugin host application
- self.path(os.path.join(os.pardir,
- 'llplugin', 'slplugin', self.args['configuration'], "slplugin.exe"),
- "slplugin.exe")
-
- self.disable_manifest_check()
-
- self.path(src="../viewer_components/updater/scripts/windows/update_install.bat", dst="update_install.bat")
-
- # Get shared libs from the shared libs staging directory
- if self.prefix(src=os.path.join(os.pardir, 'sharedlibs', self.args['configuration']),
- dst=""):
-
- self.enable_crt_manifest_check()
-
- # Get llcommon and deps. If missing assume static linkage and continue.
- try:
- self.path('llcommon.dll')
- self.path('libapr-1.dll')
- self.path('libaprutil-1.dll')
- self.path('libapriconv-1.dll')
- except RuntimeError, err:
- print err.message
- print "Skipping llcommon.dll (assuming llcommon was linked statically)"
-
- self.disable_manifest_check()
-
- # Get fmod dll, continue if missing
- try:
- self.path("fmod.dll")
- except:
- print "Skipping fmod.dll"
-
- # For textures
- if self.args['configuration'].lower() == 'debug':
- self.path("openjpegd.dll")
- else:
- self.path("openjpeg.dll")
-
- # These need to be installed as a SxS assembly, currently a 'private' assembly.
- # See http://msdn.microsoft.com/en-us/library/ms235291(VS.80).aspx
- if self.args['configuration'].lower() == 'debug':
- self.path("msvcr80d.dll")
- self.path("msvcp80d.dll")
- self.path("Microsoft.VC80.DebugCRT.manifest")
- else:
- self.path("msvcr80.dll")
- self.path("msvcp80.dll")
- self.path("Microsoft.VC80.CRT.manifest")
-
- # Vivox runtimes
- self.path("SLVoice.exe")
- self.path("vivoxsdk.dll")
- self.path("ortp.dll")
- self.path("libsndfile-1.dll")
- self.path("zlib1.dll")
- self.path("vivoxplatform.dll")
- self.path("vivoxoal.dll")
-
- # For google-perftools tcmalloc allocator.
- try:
- if self.args['configuration'].lower() == 'debug':
- self.path('libtcmalloc_minimal-debug.dll')
- else:
- self.path('libtcmalloc_minimal.dll')
- except:
- print "Skipping libtcmalloc_minimal.dll"
-
- self.end_prefix()
-
- self.path(src="licenses-win32.txt", dst="licenses.txt")
- self.path("featuretable.txt")
- self.path("featuretable_xp.txt")
-
- # For use in crash reporting (generates minidumps)
- self.path("dbghelp.dll")
-
- self.enable_no_crt_manifest_check()
-
- # Media plugins - QuickTime
- if self.prefix(src='../media_plugins/quicktime/%s' % self.args['configuration'], dst="llplugin"):
- self.path("media_plugin_quicktime.dll")
- self.end_prefix()
-
- # Media plugins - WebKit/Qt
- if self.prefix(src='../media_plugins/webkit/%s' % self.args['configuration'], dst="llplugin"):
- self.path("media_plugin_webkit.dll")
- self.end_prefix()
-
- # winmm.dll shim
- if self.prefix(src='../media_plugins/winmmshim/%s' % self.args['configuration'], dst=""):
- self.path("winmm.dll")
- self.end_prefix()
-
-
- if self.args['configuration'].lower() == 'debug':
- if self.prefix(src=os.path.join(os.pardir, os.pardir, 'libraries', 'i686-win32', 'lib', 'debug'),
- dst="llplugin"):
- self.path("libeay32.dll")
- self.path("qtcored4.dll")
- self.path("qtguid4.dll")
- self.path("qtnetworkd4.dll")
- self.path("qtopengld4.dll")
- self.path("qtwebkitd4.dll")
- self.path("qtxmlpatternsd4.dll")
- self.path("ssleay32.dll")
-
- # For WebKit/Qt plugin runtimes (image format plugins)
- if self.prefix(src="imageformats", dst="imageformats"):
- self.path("qgifd4.dll")
- self.path("qicod4.dll")
- self.path("qjpegd4.dll")
- self.path("qmngd4.dll")
- self.path("qsvgd4.dll")
- self.path("qtiffd4.dll")
- self.end_prefix()
-
- # For WebKit/Qt plugin runtimes (codec/character encoding plugins)
- if self.prefix(src="codecs", dst="codecs"):
- self.path("qcncodecsd4.dll")
- self.path("qjpcodecsd4.dll")
- self.path("qkrcodecsd4.dll")
- self.path("qtwcodecsd4.dll")
- self.end_prefix()
-
- self.end_prefix()
- else:
- if self.prefix(src=os.path.join(os.pardir, os.pardir, 'libraries', 'i686-win32', 'lib', 'release'),
- dst="llplugin"):
- self.path("libeay32.dll")
- self.path("qtcore4.dll")
- self.path("qtgui4.dll")
- self.path("qtnetwork4.dll")
- self.path("qtopengl4.dll")
- self.path("qtwebkit4.dll")
- self.path("qtxmlpatterns4.dll")
- self.path("ssleay32.dll")
-
- # For WebKit/Qt plugin runtimes (image format plugins)
- if self.prefix(src="imageformats", dst="imageformats"):
- self.path("qgif4.dll")
- self.path("qico4.dll")
- self.path("qjpeg4.dll")
- self.path("qmng4.dll")
- self.path("qsvg4.dll")
- self.path("qtiff4.dll")
- self.end_prefix()
-
- # For WebKit/Qt plugin runtimes (codec/character encoding plugins)
- if self.prefix(src="codecs", dst="codecs"):
- self.path("qcncodecs4.dll")
- self.path("qjpcodecs4.dll")
- self.path("qkrcodecs4.dll")
- self.path("qtwcodecs4.dll")
- self.end_prefix()
-
- self.end_prefix()
-
- self.disable_manifest_check()
-
- # pull in the crash logger and updater from other projects
- # tag:"crash-logger" here as a cue to the exporter
- self.path(src='../win_crash_logger/%s/windows-crash-logger.exe' % self.args['configuration'],
- dst="win_crash_logger.exe")
- self.path(src='../win_updater/%s/windows-updater.exe' % self.args['configuration'],
- dst="updater.exe")
-
- if not self.is_packaging_viewer():
- self.package_file = "copied_deps"
-
- def nsi_file_commands(self, install=True):
- def wpath(path):
- if path.endswith('/') or path.endswith(os.path.sep):
- path = path[:-1]
- path = path.replace('/', '\\')
- return path
-
- result = ""
- dest_files = [pair[1] for pair in self.file_list if pair[0] and os.path.isfile(pair[1])]
- # sort deepest hierarchy first
- dest_files.sort(lambda a,b: cmp(a.count(os.path.sep),b.count(os.path.sep)) or cmp(a,b))
- dest_files.reverse()
- out_path = None
- for pkg_file in dest_files:
- rel_file = os.path.normpath(pkg_file.replace(self.get_dst_prefix()+os.path.sep,''))
- installed_dir = wpath(os.path.join('$INSTDIR', os.path.dirname(rel_file)))
- pkg_file = wpath(os.path.normpath(pkg_file))
- if installed_dir != out_path:
- if install:
- out_path = installed_dir
- result += 'SetOutPath ' + out_path + '\n'
- if install:
- result += 'File ' + pkg_file + '\n'
- else:
- result += 'Delete ' + wpath(os.path.join('$INSTDIR', rel_file)) + '\n'
- # at the end of a delete, just rmdir all the directories
- if not install:
- deleted_file_dirs = [os.path.dirname(pair[1].replace(self.get_dst_prefix()+os.path.sep,'')) for pair in self.file_list]
- # find all ancestors so that we don't skip any dirs that happened to have no non-dir children
- deleted_dirs = []
- for d in deleted_file_dirs:
- deleted_dirs.extend(path_ancestors(d))
- # sort deepest hierarchy first
- deleted_dirs.sort(lambda a,b: cmp(a.count(os.path.sep),b.count(os.path.sep)) or cmp(a,b))
- deleted_dirs.reverse()
- prev = None
- for d in deleted_dirs:
- if d != prev: # skip duplicates
- result += 'RMDir ' + wpath(os.path.join('$INSTDIR', os.path.normpath(d))) + '\n'
- prev = d
-
- return result
-
- def package_finish(self):
- # a standard map of strings for replacing in the templates
- substitution_strings = {
- 'version' : '.'.join(self.args['version']),
- 'version_short' : '.'.join(self.args['version'][:-1]),
- 'version_dashes' : '-'.join(self.args['version']),
- 'final_exe' : self.final_exe(),
- 'grid':self.args['grid'],
- 'grid_caps':self.args['grid'].upper(),
- # escape quotes becase NSIS doesn't handle them well
- 'flags':self.flags_list().replace('"', '$\\"'),
- 'channel':self.channel(),
- 'channel_oneword':self.channel_oneword(),
- 'channel_unique':self.channel_unique(),
- }
-
- version_vars = """
- !define INSTEXE "%(final_exe)s"
- !define VERSION "%(version_short)s"
- !define VERSION_LONG "%(version)s"
- !define VERSION_DASHES "%(version_dashes)s"
- """ % substitution_strings
- if self.default_channel():
- if self.default_grid():
- # release viewer
- installer_file = "Second_Life_%(version_dashes)s_Setup.exe"
- grid_vars_template = """
- OutFile "%(installer_file)s"
- !define INSTFLAGS "%(flags)s"
- !define INSTNAME "SecondLifeViewer2"
- !define SHORTCUT "Second Life Viewer 2"
- !define URLNAME "secondlife"
- Caption "Second Life ${VERSION}"
- """
- else:
- # beta grid viewer
- installer_file = "Second_Life_%(version_dashes)s_(%(grid_caps)s)_Setup.exe"
- grid_vars_template = """
- OutFile "%(installer_file)s"
- !define INSTFLAGS "%(flags)s"
- !define INSTNAME "SecondLife%(grid_caps)s"
- !define SHORTCUT "Second Life (%(grid_caps)s)"
- !define URLNAME "secondlife%(grid)s"
- !define UNINSTALL_SETTINGS 1
- Caption "Second Life %(grid)s ${VERSION}"
- """
- else:
- # some other channel on some grid
- installer_file = "Second_Life_%(version_dashes)s_%(channel_oneword)s_Setup.exe"
- grid_vars_template = """
- OutFile "%(installer_file)s"
- !define INSTFLAGS "%(flags)s"
- !define INSTNAME "SecondLife%(channel_oneword)s"
- !define SHORTCUT "%(channel)s"
- !define URLNAME "secondlife"
- !define UNINSTALL_SETTINGS 1
- Caption "%(channel)s ${VERSION}"
- """
- if 'installer_name' in self.args:
- installer_file = self.args['installer_name']
- else:
- installer_file = installer_file % substitution_strings
- substitution_strings['installer_file'] = installer_file
-
- tempfile = "secondlife_setup_tmp.nsi"
- # the following replaces strings in the nsi template
- # it also does python-style % substitution
- self.replace_in("installers/windows/installer_template.nsi", tempfile, {
- "%%VERSION%%":version_vars,
- "%%SOURCE%%":self.get_src_prefix(),
- "%%GRID_VARS%%":grid_vars_template % substitution_strings,
- "%%INSTALL_FILES%%":self.nsi_file_commands(True),
- "%%DELETE_FILES%%":self.nsi_file_commands(False)})
-
- # We use the Unicode version of NSIS, available from
- # http://www.scratchpaper.com/
- # Check two paths, one for Program Files, and one for Program Files (x86).
- # Yay 64bit windows.
- NSIS_path = os.path.expandvars('${ProgramFiles}\\NSIS\\Unicode\\makensis.exe')
- if not os.path.exists(NSIS_path):
- NSIS_path = os.path.expandvars('${ProgramFiles(x86)}\\NSIS\\Unicode\\makensis.exe')
- self.run_command('"' + proper_windows_path(NSIS_path) + '" ' + self.dst_path_of(tempfile))
- # self.remove(self.dst_path_of(tempfile))
- # If we're on a build machine, sign the code using our Authenticode certificate. JC
- sign_py = os.path.expandvars("${SIGN}")
- if not sign_py or sign_py == "${SIGN}":
- sign_py = 'C:\\buildscripts\\code-signing\\sign.py'
- else:
- sign_py = sign_py.replace('\\', '\\\\\\\\')
- python = os.path.expandvars("${PYTHON}")
- if not python or python == "${PYTHON}":
- python = 'python'
- if os.path.exists(sign_py):
- self.run_command("%s %s %s" % (python, sign_py, self.dst_path_of(installer_file).replace('\\', '\\\\\\\\')))
- else:
- print "Skipping code signing,", sign_py, "does not exist"
- self.created_path(self.dst_path_of(installer_file))
- self.package_file = installer_file
-
-
-class DarwinManifest(ViewerManifest):
- def is_packaging_viewer(self):
- # darwin requires full app bundle packaging even for debugging.
- return True
-
- def construct(self):
- # copy over the build result (this is a no-op if run within the xcode script)
- self.path(self.args['configuration'] + "/Second Life.app", dst="")
-
- if self.prefix(src="", dst="Contents"): # everything goes in Contents
- self.path("Info-SecondLife.plist", dst="Info.plist")
-
- # copy additional libs in <bundle>/Contents/MacOS/
- self.path("../../libraries/universal-darwin/lib_release/libndofdev.dylib", dst="MacOS/libndofdev.dylib")
-
- self.path("../viewer_components/updater/scripts/darwin/update_install", "MacOS/update_install")
-
- # most everything goes in the Resources directory
- if self.prefix(src="", dst="Resources"):
- super(DarwinManifest, self).construct()
-
- if self.prefix("cursors_mac"):
- self.path("*.tif")
- self.end_prefix("cursors_mac")
-
- self.path("licenses-mac.txt", dst="licenses.txt")
- self.path("featuretable_mac.txt")
- self.path("SecondLife.nib")
-
- # If we are not using the default channel, use the 'Firstlook
- # icon' to show that it isn't a stable release.
- if self.default_channel() and self.default_grid():
- self.path("secondlife.icns")
- else:
- self.path("secondlife_firstlook.icns", "secondlife.icns")
- self.path("SecondLife.nib")
-
- # Translations
- self.path("English.lproj")
- self.path("German.lproj")
- self.path("Japanese.lproj")
- self.path("Korean.lproj")
- self.path("da.lproj")
- self.path("es.lproj")
- self.path("fr.lproj")
- self.path("hu.lproj")
- self.path("it.lproj")
- self.path("nl.lproj")
- self.path("pl.lproj")
- self.path("pt.lproj")
- self.path("ru.lproj")
- self.path("tr.lproj")
- self.path("uk.lproj")
- self.path("zh-Hans.lproj")
-
- # SLVoice and vivox lols
- self.path("vivox-runtime/universal-darwin/libsndfile.dylib", "libsndfile.dylib")
- self.path("vivox-runtime/universal-darwin/libvivoxoal.dylib", "libvivoxoal.dylib")
- self.path("vivox-runtime/universal-darwin/libortp.dylib", "libortp.dylib")
- self.path("vivox-runtime/universal-darwin/libvivoxsdk.dylib", "libvivoxsdk.dylib")
- self.path("vivox-runtime/universal-darwin/libvivoxplatform.dylib", "libvivoxplatform.dylib")
- self.path("vivox-runtime/universal-darwin/SLVoice", "SLVoice")
-
- libdir = "../../libraries/universal-darwin/lib_release"
- dylibs = {}
-
- # Need to get the llcommon dll from any of the build directories as well
- lib = "llcommon"
- libfile = "lib%s.dylib" % lib
- try:
- self.path(self.find_existing_file(os.path.join(os.pardir,
- lib,
- self.args['configuration'],
- libfile),
- os.path.join(libdir, libfile)),
- dst=libfile)
- except RuntimeError:
- print "Skipping %s" % libfile
- dylibs[lib] = False
- else:
- dylibs[lib] = True
-
- if dylibs["llcommon"]:
- for libfile in ("libapr-1.0.3.7.dylib",
- "libaprutil-1.0.3.8.dylib",
- "libexpat.0.5.0.dylib",
- "libexception_handler.dylib",
- ):
- self.path(os.path.join(libdir, libfile), libfile)
-
- try:
- # FMOD for sound
- self.path(self.args['configuration'] + "/libfmodwrapper.dylib", "libfmodwrapper.dylib")
- except:
- print "Skipping FMOD - not found"
-
- # our apps
- self.path("../mac_crash_logger/" + self.args['configuration'] + "/mac-crash-logger.app", "mac-crash-logger.app")
- self.path("../mac_updater/" + self.args['configuration'] + "/mac-updater.app", "mac-updater.app")
-
- # plugin launcher
- self.path("../llplugin/slplugin/" + self.args['configuration'] + "/SLPlugin.app", "SLPlugin.app")
-
- # our apps dependencies on shared libs
- if dylibs["llcommon"]:
- mac_crash_logger_res_path = self.dst_path_of("mac-crash-logger.app/Contents/Resources")
- mac_updater_res_path = self.dst_path_of("mac-updater.app/Contents/Resources")
- slplugin_res_path = self.dst_path_of("SLPlugin.app/Contents/Resources")
- for libfile in ("libllcommon.dylib",
- "libapr-1.0.3.7.dylib",
- "libaprutil-1.0.3.8.dylib",
- "libexpat.0.5.0.dylib",
- "libexception_handler.dylib",
- ):
- target_lib = os.path.join('../../..', libfile)
- self.run_command("ln -sf %(target)r %(link)r" %
- {'target': target_lib,
- 'link' : os.path.join(mac_crash_logger_res_path, libfile)}
- )
- self.run_command("ln -sf %(target)r %(link)r" %
- {'target': target_lib,
- 'link' : os.path.join(mac_updater_res_path, libfile)}
- )
- self.run_command("ln -sf %(target)r %(link)r" %
- {'target': target_lib,
- 'link' : os.path.join(slplugin_res_path, libfile)}
- )
-
- # plugins
- if self.prefix(src="", dst="llplugin"):
- self.path("../media_plugins/quicktime/" + self.args['configuration'] + "/media_plugin_quicktime.dylib", "media_plugin_quicktime.dylib")
- self.path("../media_plugins/webkit/" + self.args['configuration'] + "/media_plugin_webkit.dylib", "media_plugin_webkit.dylib")
- self.path("../../libraries/universal-darwin/lib_release/libllqtwebkit.dylib", "libllqtwebkit.dylib")
-
- self.end_prefix("llplugin")
-
- # command line arguments for connecting to the proper grid
- self.put_in_file(self.flags_list(), 'arguments.txt')
-
- self.end_prefix("Resources")
-
- self.end_prefix("Contents")
-
- # NOTE: the -S argument to strip causes it to keep enough info for
- # annotated backtraces (i.e. function names in the crash log). 'strip' with no
- # arguments yields a slightly smaller binary but makes crash logs mostly useless.
- # This may be desirable for the final release. Or not.
- if ("package" in self.args['actions'] or
- "unpacked" in self.args['actions']):
- self.run_command('strip -S %(viewer_binary)r' %
- { 'viewer_binary' : self.dst_path_of('Contents/MacOS/Second Life')})
-
- def copy_finish(self):
- # Force executable permissions to be set for scripts
- # see CHOP-223 and http://mercurial.selenic.com/bts/issue1802
- for script in 'Contents/MacOS/update_install',:
- self.run_command("chmod +x %r" % os.path.join(self.get_dst_prefix(), script))
-
- def package_finish(self):
- channel_standin = 'Second Life Viewer 2' # hah, our default channel is not usable on its own
- if not self.default_channel():
- channel_standin = self.channel()
-
- imagename="SecondLife_" + '_'.join(self.args['version'])
-
- # MBW -- If the mounted volume name changes, it breaks the .DS_Store's background image and icon positioning.
- # If we really need differently named volumes, we'll need to create multiple DS_Store file images, or use some other trick.
-
- volname="Second Life Installer" # DO NOT CHANGE without understanding comment above
-
- if self.default_channel():
- if not self.default_grid():
- # beta case
- imagename = imagename + '_' + self.args['grid'].upper()
- else:
- # first look, etc
- imagename = imagename + '_' + self.channel_oneword().upper()
-
- sparsename = imagename + ".sparseimage"
- finalname = imagename + ".dmg"
- # make sure we don't have stale files laying about
- self.remove(sparsename, finalname)
-
- self.run_command('hdiutil create %(sparse)r -volname %(vol)r -fs HFS+ -type SPARSE -megabytes 700 -layout SPUD' % {
- 'sparse':sparsename,
- 'vol':volname})
-
- # mount the image and get the name of the mount point and device node
- hdi_output = self.run_command('hdiutil attach -private %r' % sparsename)
- try:
- devfile = re.search("/dev/disk([0-9]+)[^s]", hdi_output).group(0).strip()
- volpath = re.search('HFS\s+(.+)', hdi_output).group(1).strip()
-
- if devfile != '/dev/disk1':
- # adding more debugging info based upon nat's hunches to the
- # logs to help track down 'SetFile -a V' failures -brad
- print "WARNING: 'SetFile -a V' command below is probably gonna fail"
-
- # Copy everything in to the mounted .dmg
-
- if self.default_channel() and not self.default_grid():
- app_name = "Second Life " + self.args['grid']
- else:
- app_name = channel_standin.strip()
-
- # Hack:
- # Because there is no easy way to coerce the Finder into positioning
- # the app bundle in the same place with different app names, we are
- # adding multiple .DS_Store files to svn. There is one for release,
- # one for release candidate and one for first look. Any other channels
- # will use the release .DS_Store, and will look broken.
- # - Ambroff 2008-08-20
- dmg_template = os.path.join(
- 'installers',
- 'darwin',
- '%s-dmg' % "".join(self.channel_unique().split()).lower())
-
- if not os.path.exists (self.src_path_of(dmg_template)):
- dmg_template = os.path.join ('installers', 'darwin', 'release-dmg')
-
- for s,d in {self.get_dst_prefix():app_name + ".app",
- os.path.join(dmg_template, "_VolumeIcon.icns"): ".VolumeIcon.icns",
- os.path.join(dmg_template, "background.jpg"): "background.jpg",
- os.path.join(dmg_template, "_DS_Store"): ".DS_Store"}.items():
- print "Copying to dmg", s, d
- self.copy_action(self.src_path_of(s), os.path.join(volpath, d))
-
- # Hide the background image, DS_Store file, and volume icon file (set their "visible" bit)
- for f in ".VolumeIcon.icns", "background.jpg", ".DS_Store":
- pathname = os.path.join(volpath, f)
- # We've observed mysterious "no such file" failures of the SetFile
- # command, especially on the first file listed above -- yet
- # subsequent inspection of the target directory confirms it's
- # there. Timing problem with copy command? Try to handle.
- for x in xrange(3):
- if os.path.exists(pathname):
- print "Confirmed existence: %r" % pathname
- break
- print "Waiting for %s copy command to complete (%s)..." % (f, x+1)
- sys.stdout.flush()
- time.sleep(1)
- # If we fall out of the loop above without a successful break, oh
- # well, possibly we've mistaken the nature of the problem. In any
- # case, don't hang up the whole build looping indefinitely, let
- # the original problem manifest by executing the desired command.
- self.run_command('SetFile -a V %r' % pathname)
-
- # Create the alias file (which is a resource file) from the .r
- self.run_command('Rez %r -o %r' %
- (self.src_path_of("installers/darwin/release-dmg/Applications-alias.r"),
- os.path.join(volpath, "Applications")))
-
- # Set the alias file's alias and custom icon bits
- self.run_command('SetFile -a AC %r' % os.path.join(volpath, "Applications"))
-
- # Set the disk image root's custom icon bit
- self.run_command('SetFile -a C %r' % volpath)
- finally:
- # Unmount the image even if exceptions from any of the above
- self.run_command('hdiutil detach -force %r' % devfile)
-
- print "Converting temp disk image to final disk image"
- self.run_command('hdiutil convert %(sparse)r -format UDZO -imagekey zlib-level=9 -o %(final)r' % {'sparse':sparsename, 'final':finalname})
- # get rid of the temp file
- self.package_file = finalname
- self.remove(sparsename)
-
-class LinuxManifest(ViewerManifest):
- def construct(self):
- super(LinuxManifest, self).construct()
- self.path("licenses-linux.txt","licenses.txt")
- self.path("res/ll_icon.png","secondlife_icon.png")
- if self.prefix("linux_tools", dst=""):
- self.path("client-readme.txt","README-linux.txt")
- self.path("client-readme-voice.txt","README-linux-voice.txt")
- self.path("client-readme-joystick.txt","README-linux-joystick.txt")
- self.path("wrapper.sh","secondlife")
- self.path("handle_secondlifeprotocol.sh", "etc/handle_secondlifeprotocol.sh")
- self.path("register_secondlifeprotocol.sh", "etc/register_secondlifeprotocol.sh")
- self.path("refresh_desktop_app_entry.sh", "etc/refresh_desktop_app_entry.sh")
- self.path("launch_url.sh","etc/launch_url.sh")
- self.path("install.sh")
- self.end_prefix("linux_tools")
-
- # Create an appropriate gridargs.dat for this package, denoting required grid.
- self.put_in_file(self.flags_list(), 'etc/gridargs.dat')
-
- self.path("secondlife-bin","bin/do-not-directly-run-secondlife-bin")
- self.path("../linux_crash_logger/linux-crash-logger","bin/linux-crash-logger.bin")
- self.path("../linux_updater/linux-updater", "bin/linux-updater.bin")
- self.path("../llplugin/slplugin/SLPlugin", "bin/SLPlugin")
-
- if self.prefix("res-sdl"):
- self.path("*")
- # recurse
- self.end_prefix("res-sdl")
-
- self.path("../viewer_components/updater/scripts/linux/update_install", "bin/update_install")
-
- # plugins
- if self.prefix(src="", dst="bin/llplugin"):
- self.path("../media_plugins/webkit/libmedia_plugin_webkit.so", "libmedia_plugin_webkit.so")
- self.path("../media_plugins/gstreamer010/libmedia_plugin_gstreamer010.so", "libmedia_plugin_gstreamer.so")
- self.end_prefix("bin/llplugin")
-
- try:
- self.path("../llcommon/libllcommon.so", "lib/libllcommon.so")
- except:
- print "Skipping llcommon.so (assuming llcommon was linked statically)"
-
- self.path("featuretable_linux.txt")
-
- def copy_finish(self):
- # Force executable permissions to be set for scripts
- # see CHOP-223 and http://mercurial.selenic.com/bts/issue1802
- for script in 'secondlife', 'bin/update_install':
- self.run_command("chmod +x %r" % os.path.join(self.get_dst_prefix(), script))
-
- def package_finish(self):
- if 'installer_name' in self.args:
- installer_name = self.args['installer_name']
- else:
- installer_name_components = ['SecondLife_', self.args.get('arch')]
- installer_name_components.extend(self.args['version'])
- installer_name = "_".join(installer_name_components)
- if self.default_channel():
- if not self.default_grid():
- installer_name += '_' + self.args['grid'].upper()
- else:
- installer_name += '_' + self.channel_oneword().upper()
-
- if self.args['buildtype'].lower() == 'release' and self.is_packaging_viewer():
- print "* Going strip-crazy on the packaged binaries, since this is a RELEASE build"
- self.run_command("find %(d)r/bin %(d)r/lib -type f \\! -name update_install | xargs --no-run-if-empty strip -S" % {'d': self.get_dst_prefix()} ) # makes some small assumptions about our packaged dir structure
-
- # Fix access permissions
- self.run_command("""
- find %(dst)s -type d | xargs --no-run-if-empty chmod 755;
- find %(dst)s -type f -perm 0700 | xargs --no-run-if-empty chmod 0755;
- find %(dst)s -type f -perm 0500 | xargs --no-run-if-empty chmod 0555;
- find %(dst)s -type f -perm 0600 | xargs --no-run-if-empty chmod 0644;
- find %(dst)s -type f -perm 0400 | xargs --no-run-if-empty chmod 0444;
- true""" % {'dst':self.get_dst_prefix() })
- self.package_file = installer_name + '.tar.bz2'
-
- # temporarily move directory tree so that it has the right
- # name in the tarfile
- self.run_command("mv %(dst)s %(inst)s" % {
- 'dst': self.get_dst_prefix(),
- 'inst': self.build_path_of(installer_name)})
- try:
- # only create tarball if it's a release build.
- if self.args['buildtype'].lower() == 'release':
- # --numeric-owner hides the username of the builder for
- # security etc.
- self.run_command('tar -C %(dir)s --numeric-owner -cjf '
- '%(inst_path)s.tar.bz2 %(inst_name)s' % {
- 'dir': self.get_build_prefix(),
- 'inst_name': installer_name,
- 'inst_path':self.build_path_of(installer_name)})
- else:
- print "Skipping %s.tar.bz2 for non-Release build (%s)" % \
- (installer_name, self.args['buildtype'])
- finally:
- self.run_command("mv %(inst)s %(dst)s" % {
- 'dst': self.get_dst_prefix(),
- 'inst': self.build_path_of(installer_name)})
-
-class Linux_i686Manifest(LinuxManifest):
- def construct(self):
- super(Linux_i686Manifest, self).construct()
-
- if self.prefix("../../libraries/i686-linux/lib_release_client", dst="lib"):
- self.path("libapr-1.so.0")
- self.path("libaprutil-1.so.0")
- self.path("libbreakpad_client.so.0.0.0", "libbreakpad_client.so.0")
- self.path("libdb-4.2.so")
- self.path("libcrypto.so.0.9.7")
- self.path("libexpat.so.1")
- self.path("libssl.so.0.9.7")
- self.path("libuuid.so.1")
- self.path("libSDL-1.2.so.0")
- self.path("libELFIO.so")
- self.path("libopenjpeg.so.1.3.0", "libopenjpeg.so.1.3")
- self.path("libalut.so")
- self.path("libopenal.so", "libopenal.so.1")
- self.path("libopenal.so", "libvivoxoal.so.1") # vivox's sdk expects this soname
- try:
- self.path("libfmod-3.75.so")
- pass
- except:
- print "Skipping libfmod-3.75.so - not found"
- pass
- self.end_prefix("lib")
-
- # Vivox runtimes
- if self.prefix(src="vivox-runtime/i686-linux", dst="bin"):
- self.path("SLVoice")
- self.end_prefix()
- if self.prefix(src="vivox-runtime/i686-linux", dst="lib"):
- self.path("libortp.so")
- self.path("libsndfile.so.1")
- #self.path("libvivoxoal.so.1") # no - we'll re-use the viewer's own OpenAL lib
- self.path("libvivoxsdk.so")
- self.path("libvivoxplatform.so")
- self.end_prefix("lib")
-
-class Linux_x86_64Manifest(LinuxManifest):
- def construct(self):
- super(Linux_x86_64Manifest, self).construct()
-
- # support file for valgrind debug tool
- self.path("secondlife-i686.supp")
-
-################################################################
-
-if __name__ == "__main__":
- main()
+#!/usr/bin/env python
+"""\
+@file viewer_manifest.py
+@author Ryan Williams
+@brief Description of all installer viewer files, and methods for packaging
+ them into installers for all supported platforms.
+
+$LicenseInfo:firstyear=2006&license=viewerlgpl$
+Second Life Viewer Source Code
+Copyright (C) 2006-2011, Linden Research, Inc.
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation;
+version 2.1 of the License only.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
+$/LicenseInfo$
+"""
+import sys
+import os.path
+import re
+import tarfile
+import time
+viewer_dir = os.path.dirname(__file__)
+# add llmanifest library to our path so we don't have to muck with PYTHONPATH
+sys.path.append(os.path.join(viewer_dir, '../lib/python/indra/util'))
+from llmanifest import LLManifest, main, proper_windows_path, path_ancestors
+
+class ViewerManifest(LLManifest):
+ def is_packaging_viewer(self):
+ # Some commands, files will only be included
+ # if we are packaging the viewer on windows.
+ # This manifest is also used to copy
+ # files during the build (see copy_w_viewer_manifest
+ # and copy_l_viewer_manifest targets)
+ return 'package' in self.args['actions']
+
+ def construct(self):
+ super(ViewerManifest, self).construct()
+ self.exclude("*.svn*")
+ self.path(src="../../scripts/messages/message_template.msg", dst="app_settings/message_template.msg")
+ self.path(src="../../etc/message.xml", dst="app_settings/message.xml")
+
+ if self.is_packaging_viewer():
+ if self.prefix(src="app_settings"):
+ self.exclude("logcontrol.xml")
+ self.exclude("logcontrol-dev.xml")
+ self.path("*.pem")
+ self.path("*.ini")
+ self.path("*.xml")
+ self.path("*.db2")
+
+ # include the entire shaders directory recursively
+ self.path("shaders")
+ # ... and the entire windlight directory
+ self.path("windlight")
+ self.end_prefix("app_settings")
+
+ if self.prefix(src="character"):
+ self.path("*.llm")
+ self.path("*.xml")
+ self.path("*.tga")
+ self.end_prefix("character")
+
+ # Include our fonts
+ if self.prefix(src="fonts"):
+ self.path("*.ttf")
+ self.path("*.txt")
+ self.end_prefix("fonts")
+
+ # skins
+ if self.prefix(src="skins"):
+ self.path("paths.xml")
+ # include the entire textures directory recursively
+ if self.prefix(src="*/textures"):
+ self.path("*/*.tga")
+ self.path("*/*.j2c")
+ self.path("*/*.jpg")
+ self.path("*/*.png")
+ self.path("*.tga")
+ self.path("*.j2c")
+ self.path("*.jpg")
+ self.path("*.png")
+ self.path("textures.xml")
+ self.end_prefix("*/textures")
+ self.path("*/xui/*/*.xml")
+ self.path("*/xui/*/widgets/*.xml")
+ self.path("*/*.xml")
+
+ # Local HTML files (e.g. loading screen)
+ if self.prefix(src="*/html"):
+ self.path("*.png")
+ self.path("*/*/*.html")
+ self.path("*/*/*.gif")
+ self.end_prefix("*/html")
+ self.end_prefix("skins")
+
+ # local_assets dir (for pre-cached textures)
+ if self.prefix(src="local_assets"):
+ self.path("*.j2c")
+ self.path("*.tga")
+ self.end_prefix("local_assets")
+
+ # Files in the newview/ directory
+ self.path("gpu_table.txt")
+
+ def login_channel(self):
+ """Channel reported for login and upgrade purposes ONLY;
+ used for A/B testing"""
+ # NOTE: Do not return the normal channel if login_channel
+ # is not specified, as some code may branch depending on
+ # whether or not this is present
+ return self.args.get('login_channel')
+
+ def grid(self):
+ return self.args['grid']
+ def channel(self):
+ return self.args['channel']
+ def channel_unique(self):
+ return self.channel().replace("Second Life", "").strip()
+ def channel_oneword(self):
+ return "".join(self.channel_unique().split())
+ def channel_lowerword(self):
+ return self.channel_oneword().lower()
+
+ def flags_list(self):
+ """ Convenience function that returns the command-line flags
+ for the grid"""
+
+ # Set command line flags relating to the target grid
+ grid_flags = ''
+ if not self.default_grid():
+ grid_flags = "--grid %(grid)s "\
+ "--helperuri http://preview-%(grid)s.secondlife.com/helpers/" %\
+ {'grid':self.grid()}
+
+ # set command line flags for channel
+ channel_flags = ''
+ if self.login_channel() and self.login_channel() != self.channel():
+ # Report a special channel during login, but use default
+ channel_flags = '--channel "%s"' % (self.login_channel())
+ elif not self.default_channel():
+ channel_flags = '--channel "%s"' % self.channel()
+
+ # Deal with settings
+ setting_flags = ''
+ if not self.default_channel() or not self.default_grid():
+ if self.default_grid():
+ setting_flags = '--settings settings_%s.xml'\
+ % self.channel_lowerword()
+ else:
+ setting_flags = '--settings settings_%s_%s.xml'\
+ % (self.grid(), self.channel_lowerword())
+
+ return " ".join((channel_flags, grid_flags, setting_flags)).strip()
+
+
+class WindowsManifest(ViewerManifest):
+ def final_exe(self):
+ if self.default_channel():
+ if self.default_grid():
+ return "SecondLife.exe"
+ else:
+ return "SecondLifePreview.exe"
+ else:
+ return ''.join(self.channel().split()) + '.exe'
+
+ def test_msvcrt_and_copy_action(self, src, dst):
+ # This is used to test a dll manifest.
+ # It is used as a temporary override during the construct method
+ from test_win32_manifest import test_assembly_binding
+ if src and (os.path.exists(src) or os.path.islink(src)):
+ # ensure that destination path exists
+ self.cmakedirs(os.path.dirname(dst))
+ self.created_paths.append(dst)
+ if not os.path.isdir(src):
+ if(self.args['configuration'].lower() == 'debug'):
+ test_assembly_binding(src, "Microsoft.VC80.DebugCRT", "8.0.50727.4053")
+ else:
+ test_assembly_binding(src, "Microsoft.VC80.CRT", "8.0.50727.4053")
+ self.ccopy(src,dst)
+ else:
+ raise Exception("Directories are not supported by test_CRT_and_copy_action()")
+ else:
+ print "Doesn't exist:", src
+
+ def test_for_no_msvcrt_manifest_and_copy_action(self, src, dst):
+ # This is used to test that no manifest for the msvcrt exists.
+ # It is used as a temporary override during the construct method
+ from test_win32_manifest import test_assembly_binding
+ from test_win32_manifest import NoManifestException, NoMatchingAssemblyException
+ if src and (os.path.exists(src) or os.path.islink(src)):
+ # ensure that destination path exists
+ self.cmakedirs(os.path.dirname(dst))
+ self.created_paths.append(dst)
+ if not os.path.isdir(src):
+ try:
+ if(self.args['configuration'].lower() == 'debug'):
+ test_assembly_binding(src, "Microsoft.VC80.DebugCRT", "")
+ else:
+ test_assembly_binding(src, "Microsoft.VC80.CRT", "")
+ raise Exception("Unknown condition")
+ except NoManifestException, err:
+ pass
+ except NoMatchingAssemblyException, err:
+ pass
+
+ self.ccopy(src,dst)
+ else:
+ raise Exception("Directories are not supported by test_CRT_and_copy_action()")
+ else:
+ print "Doesn't exist:", src
+
+ def enable_crt_manifest_check(self):
+ if self.is_packaging_viewer():
+ WindowsManifest.copy_action = WindowsManifest.test_msvcrt_and_copy_action
+
+ def enable_no_crt_manifest_check(self):
+ if self.is_packaging_viewer():
+ WindowsManifest.copy_action = WindowsManifest.test_for_no_msvcrt_manifest_and_copy_action
+
+ def disable_manifest_check(self):
+ if self.is_packaging_viewer():
+ del WindowsManifest.copy_action
+
+ def construct(self):
+ super(WindowsManifest, self).construct()
+
+ self.enable_crt_manifest_check()
+
+ if self.is_packaging_viewer():
+ # Find secondlife-bin.exe in the 'configuration' dir, then rename it to the result of final_exe.
+ self.path(src='%s/secondlife-bin.exe' % self.args['configuration'], dst=self.final_exe())
+
+ # Plugin host application
+ self.path(os.path.join(os.pardir,
+ 'llplugin', 'slplugin', self.args['configuration'], "slplugin.exe"),
+ "slplugin.exe")
+
+ self.disable_manifest_check()
+
+ self.path(src="../viewer_components/updater/scripts/windows/update_install.bat", dst="update_install.bat")
+ # Get shared libs from the shared libs staging directory
+ if self.prefix(src=os.path.join(os.pardir, 'sharedlibs', self.args['configuration']),
+ dst=""):
+
+ self.enable_crt_manifest_check()
+
+ # Get llcommon and deps. If missing assume static linkage and continue.
+ try:
+ self.path('llcommon.dll')
+ self.path('libapr-1.dll')
+ self.path('libaprutil-1.dll')
+ self.path('libapriconv-1.dll')
+
+ except RuntimeError, err:
+ print err.message
+ print "Skipping llcommon.dll (assuming llcommon was linked statically)"
+
+ self.disable_manifest_check()
+
+ # Mesh 3rd party libs needed for auto LOD and collada reading
+ try:
+ if self.args['configuration'].lower() == 'debug':
+ self.path("libcollada14dom21-d.dll")
+ else:
+ self.path("libcollada14dom21.dll")
+
+ self.path("glod.dll")
+ except RuntimeError, err:
+ print err.message
+ print "Skipping COLLADA and GLOD libraries (assumming linked statically)"
+
+
+ # Get fmod dll, continue if missing
+ try:
+ self.path("fmod.dll")
+ except:
+ print "Skipping fmod.dll"
+
+ # For textures
+ if self.args['configuration'].lower() == 'debug':
+ self.path("openjpegd.dll")
+ else:
+ self.path("openjpeg.dll")
+
+ # These need to be installed as a SxS assembly, currently a 'private' assembly.
+ # See http://msdn.microsoft.com/en-us/library/ms235291(VS.80).aspx
+ if self.args['configuration'].lower() == 'debug':
+ self.path("msvcr80d.dll")
+ self.path("msvcp80d.dll")
+ self.path("Microsoft.VC80.DebugCRT.manifest")
+ else:
+ self.path("msvcr80.dll")
+ self.path("msvcp80.dll")
+ self.path("Microsoft.VC80.CRT.manifest")
+
+ # Vivox runtimes
+ self.path("SLVoice.exe")
+ self.path("vivoxsdk.dll")
+ self.path("ortp.dll")
+ self.path("libsndfile-1.dll")
+ self.path("zlib1.dll")
+ self.path("vivoxplatform.dll")
+ self.path("vivoxoal.dll")
+
+ # For google-perftools tcmalloc allocator.
+ try:
+ if self.args['configuration'].lower() == 'debug':
+ self.path('libtcmalloc_minimal-debug.dll')
+ else:
+ self.path('libtcmalloc_minimal.dll')
+ except:
+ print "Skipping libtcmalloc_minimal.dll"
+
+ self.end_prefix()
+
+ self.path(src="licenses-win32.txt", dst="licenses.txt")
+ self.path("featuretable.txt")
+ self.path("featuretable_xp.txt")
+
+ # For use in crash reporting (generates minidumps)
+ self.path("dbghelp.dll")
+
+ self.enable_no_crt_manifest_check()
+
+ # Media plugins - QuickTime
+ if self.prefix(src='../media_plugins/quicktime/%s' % self.args['configuration'], dst="llplugin"):
+ self.path("media_plugin_quicktime.dll")
+ self.end_prefix()
+
+ # Media plugins - WebKit/Qt
+ if self.prefix(src='../media_plugins/webkit/%s' % self.args['configuration'], dst="llplugin"):
+ self.path("media_plugin_webkit.dll")
+ self.end_prefix()
+
+ # winmm.dll shim
+ if self.prefix(src='../media_plugins/winmmshim/%s' % self.args['configuration'], dst=""):
+ self.path("winmm.dll")
+ self.end_prefix()
+
+
+ if self.args['configuration'].lower() == 'debug':
+ if self.prefix(src=os.path.join(os.pardir, os.pardir, 'libraries', 'i686-win32', 'lib', 'debug'),
+ dst="llplugin"):
+ self.path("libeay32.dll")
+ self.path("qtcored4.dll")
+ self.path("qtguid4.dll")
+ self.path("qtnetworkd4.dll")
+ self.path("qtopengld4.dll")
+ self.path("qtwebkitd4.dll")
+ self.path("qtxmlpatternsd4.dll")
+ self.path("ssleay32.dll")
+
+ # For WebKit/Qt plugin runtimes (image format plugins)
+ if self.prefix(src="imageformats", dst="imageformats"):
+ self.path("qgifd4.dll")
+ self.path("qicod4.dll")
+ self.path("qjpegd4.dll")
+ self.path("qmngd4.dll")
+ self.path("qsvgd4.dll")
+ self.path("qtiffd4.dll")
+ self.end_prefix()
+
+ # For WebKit/Qt plugin runtimes (codec/character encoding plugins)
+ if self.prefix(src="codecs", dst="codecs"):
+ self.path("qcncodecsd4.dll")
+ self.path("qjpcodecsd4.dll")
+ self.path("qkrcodecsd4.dll")
+ self.path("qtwcodecsd4.dll")
+ self.end_prefix()
+
+ self.end_prefix()
+ else:
+ if self.prefix(src=os.path.join(os.pardir, os.pardir, 'libraries', 'i686-win32', 'lib', 'release'),
+ dst="llplugin"):
+ self.path("libeay32.dll")
+ self.path("qtcore4.dll")
+ self.path("qtgui4.dll")
+ self.path("qtnetwork4.dll")
+ self.path("qtopengl4.dll")
+ self.path("qtwebkit4.dll")
+ self.path("qtxmlpatterns4.dll")
+ self.path("ssleay32.dll")
+
+ # For WebKit/Qt plugin runtimes (image format plugins)
+ if self.prefix(src="imageformats", dst="imageformats"):
+ self.path("qgif4.dll")
+ self.path("qico4.dll")
+ self.path("qjpeg4.dll")
+ self.path("qmng4.dll")
+ self.path("qsvg4.dll")
+ self.path("qtiff4.dll")
+ self.end_prefix()
+
+ # For WebKit/Qt plugin runtimes (codec/character encoding plugins)
+ if self.prefix(src="codecs", dst="codecs"):
+ self.path("qcncodecs4.dll")
+ self.path("qjpcodecs4.dll")
+ self.path("qkrcodecs4.dll")
+ self.path("qtwcodecs4.dll")
+ self.end_prefix()
+
+ self.end_prefix()
+
+ self.disable_manifest_check()
+
+ # pull in the crash logger and updater from other projects
+ # tag:"crash-logger" here as a cue to the exporter
+ self.path(src='../win_crash_logger/%s/windows-crash-logger.exe' % self.args['configuration'],
+ dst="win_crash_logger.exe")
+ self.path(src='../win_updater/%s/windows-updater.exe' % self.args['configuration'],
+ dst="updater.exe")
+
+ if not self.is_packaging_viewer():
+ self.package_file = "copied_deps"
+
+ def nsi_file_commands(self, install=True):
+ def wpath(path):
+ if path.endswith('/') or path.endswith(os.path.sep):
+ path = path[:-1]
+ path = path.replace('/', '\\')
+ return path
+
+ result = ""
+ dest_files = [pair[1] for pair in self.file_list if pair[0] and os.path.isfile(pair[1])]
+ # sort deepest hierarchy first
+ dest_files.sort(lambda a,b: cmp(a.count(os.path.sep),b.count(os.path.sep)) or cmp(a,b))
+ dest_files.reverse()
+ out_path = None
+ for pkg_file in dest_files:
+ rel_file = os.path.normpath(pkg_file.replace(self.get_dst_prefix()+os.path.sep,''))
+ installed_dir = wpath(os.path.join('$INSTDIR', os.path.dirname(rel_file)))
+ pkg_file = wpath(os.path.normpath(pkg_file))
+ if installed_dir != out_path:
+ if install:
+ out_path = installed_dir
+ result += 'SetOutPath ' + out_path + '\n'
+ if install:
+ result += 'File ' + pkg_file + '\n'
+ else:
+ result += 'Delete ' + wpath(os.path.join('$INSTDIR', rel_file)) + '\n'
+ # at the end of a delete, just rmdir all the directories
+ if not install:
+ deleted_file_dirs = [os.path.dirname(pair[1].replace(self.get_dst_prefix()+os.path.sep,'')) for pair in self.file_list]
+ # find all ancestors so that we don't skip any dirs that happened to have no non-dir children
+ deleted_dirs = []
+ for d in deleted_file_dirs:
+ deleted_dirs.extend(path_ancestors(d))
+ # sort deepest hierarchy first
+ deleted_dirs.sort(lambda a,b: cmp(a.count(os.path.sep),b.count(os.path.sep)) or cmp(a,b))
+ deleted_dirs.reverse()
+ prev = None
+ for d in deleted_dirs:
+ if d != prev: # skip duplicates
+ result += 'RMDir ' + wpath(os.path.join('$INSTDIR', os.path.normpath(d))) + '\n'
+ prev = d
+
+ return result
+
+ def package_finish(self):
+ # a standard map of strings for replacing in the templates
+ substitution_strings = {
+ 'version' : '.'.join(self.args['version']),
+ 'version_short' : '.'.join(self.args['version'][:-1]),
+ 'version_dashes' : '-'.join(self.args['version']),
+ 'final_exe' : self.final_exe(),
+ 'grid':self.args['grid'],
+ 'grid_caps':self.args['grid'].upper(),
+ # escape quotes becase NSIS doesn't handle them well
+ 'flags':self.flags_list().replace('"', '$\\"'),
+ 'channel':self.channel(),
+ 'channel_oneword':self.channel_oneword(),
+ 'channel_unique':self.channel_unique(),
+ }
+
+ version_vars = """
+ !define INSTEXE "%(final_exe)s"
+ !define VERSION "%(version_short)s"
+ !define VERSION_LONG "%(version)s"
+ !define VERSION_DASHES "%(version_dashes)s"
+ """ % substitution_strings
+ if self.default_channel():
+ if self.default_grid():
+ # release viewer
+ installer_file = "Second_Life_%(version_dashes)s_Setup.exe"
+ grid_vars_template = """
+ OutFile "%(installer_file)s"
+ !define INSTFLAGS "%(flags)s"
+ !define INSTNAME "SecondLifeViewer2"
+ !define SHORTCUT "Second Life Viewer 2"
+ !define URLNAME "secondlife"
+ Caption "Second Life ${VERSION}"
+ """
+ else:
+ # beta grid viewer
+ installer_file = "Second_Life_%(version_dashes)s_(%(grid_caps)s)_Setup.exe"
+ grid_vars_template = """
+ OutFile "%(installer_file)s"
+ !define INSTFLAGS "%(flags)s"
+ !define INSTNAME "SecondLife%(grid_caps)s"
+ !define SHORTCUT "Second Life (%(grid_caps)s)"
+ !define URLNAME "secondlife%(grid)s"
+ !define UNINSTALL_SETTINGS 1
+ Caption "Second Life %(grid)s ${VERSION}"
+ """
+ else:
+ # some other channel on some grid
+ installer_file = "Second_Life_%(version_dashes)s_%(channel_oneword)s_Setup.exe"
+ grid_vars_template = """
+ OutFile "%(installer_file)s"
+ !define INSTFLAGS "%(flags)s"
+ !define INSTNAME "SecondLife%(channel_oneword)s"
+ !define SHORTCUT "%(channel)s"
+ !define URLNAME "secondlife"
+ !define UNINSTALL_SETTINGS 1
+ Caption "%(channel)s ${VERSION}"
+ """
+ if 'installer_name' in self.args:
+ installer_file = self.args['installer_name']
+ else:
+ installer_file = installer_file % substitution_strings
+ substitution_strings['installer_file'] = installer_file
+
+ tempfile = "secondlife_setup_tmp.nsi"
+ # the following replaces strings in the nsi template
+ # it also does python-style % substitution
+ self.replace_in("installers/windows/installer_template.nsi", tempfile, {
+ "%%VERSION%%":version_vars,
+ "%%SOURCE%%":self.get_src_prefix(),
+ "%%GRID_VARS%%":grid_vars_template % substitution_strings,
+ "%%INSTALL_FILES%%":self.nsi_file_commands(True),
+ "%%DELETE_FILES%%":self.nsi_file_commands(False)})
+
+ # We use the Unicode version of NSIS, available from
+ # http://www.scratchpaper.com/
+ # Check two paths, one for Program Files, and one for Program Files (x86).
+ # Yay 64bit windows.
+ NSIS_path = os.path.expandvars('${ProgramFiles}\\NSIS\\Unicode\\makensis.exe')
+ if not os.path.exists(NSIS_path):
+ NSIS_path = os.path.expandvars('${ProgramFiles(x86)}\\NSIS\\Unicode\\makensis.exe')
+ self.run_command('"' + proper_windows_path(NSIS_path) + '" ' + self.dst_path_of(tempfile))
+ # self.remove(self.dst_path_of(tempfile))
+ # If we're on a build machine, sign the code using our Authenticode certificate. JC
+ sign_py = os.path.expandvars("${SIGN}")
+ if not sign_py or sign_py == "${SIGN}":
+ sign_py = 'C:\\buildscripts\\code-signing\\sign.py'
+ else:
+ sign_py = sign_py.replace('\\', '\\\\\\\\')
+ python = os.path.expandvars("${PYTHON}")
+ if not python or python == "${PYTHON}":
+ python = 'python'
+ if os.path.exists(sign_py):
+ self.run_command("%s %s %s" % (python, sign_py, self.dst_path_of(installer_file).replace('\\', '\\\\\\\\')))
+ else:
+ print "Skipping code signing,", sign_py, "does not exist"
+ self.created_path(self.dst_path_of(installer_file))
+ self.package_file = installer_file
+
+
+class DarwinManifest(ViewerManifest):
+ def is_packaging_viewer(self):
+ # darwin requires full app bundle packaging even for debugging.
+ return True
+
+ def construct(self):
+ # copy over the build result (this is a no-op if run within the xcode script)
+ self.path(self.args['configuration'] + "/Second Life.app", dst="")
+
+ if self.prefix(src="", dst="Contents"): # everything goes in Contents
+ self.path("Info-SecondLife.plist", dst="Info.plist")
+
+ # copy additional libs in <bundle>/Contents/MacOS/
+ self.path("../../libraries/universal-darwin/lib_release/libndofdev.dylib", dst="MacOS/libndofdev.dylib")
+
+ self.path("../viewer_components/updater/scripts/darwin/update_install", "MacOS/update_install")
+
+ # most everything goes in the Resources directory
+ if self.prefix(src="", dst="Resources"):
+ super(DarwinManifest, self).construct()
+
+ if self.prefix("cursors_mac"):
+ self.path("*.tif")
+ self.end_prefix("cursors_mac")
+
+ self.path("licenses-mac.txt", dst="licenses.txt")
+ self.path("featuretable_mac.txt")
+ self.path("SecondLife.nib")
+
+ # If we are not using the default channel, use the 'Firstlook
+ # icon' to show that it isn't a stable release.
+ if self.default_channel() and self.default_grid():
+ self.path("secondlife.icns")
+ else:
+ self.path("secondlife_firstlook.icns", "secondlife.icns")
+ self.path("SecondLife.nib")
+
+ # Translations
+ self.path("English.lproj")
+ self.path("German.lproj")
+ self.path("Japanese.lproj")
+ self.path("Korean.lproj")
+ self.path("da.lproj")
+ self.path("es.lproj")
+ self.path("fr.lproj")
+ self.path("hu.lproj")
+ self.path("it.lproj")
+ self.path("nl.lproj")
+ self.path("pl.lproj")
+ self.path("pt.lproj")
+ self.path("ru.lproj")
+ self.path("tr.lproj")
+ self.path("uk.lproj")
+ self.path("zh-Hans.lproj")
+
+ # SLVoice and vivox lols
+ self.path("vivox-runtime/universal-darwin/libsndfile.dylib", "libsndfile.dylib")
+ self.path("vivox-runtime/universal-darwin/libvivoxoal.dylib", "libvivoxoal.dylib")
+ self.path("vivox-runtime/universal-darwin/libortp.dylib", "libortp.dylib")
+ self.path("vivox-runtime/universal-darwin/libvivoxsdk.dylib", "libvivoxsdk.dylib")
+ self.path("vivox-runtime/universal-darwin/libvivoxplatform.dylib", "libvivoxplatform.dylib")
+ self.path("vivox-runtime/universal-darwin/SLVoice", "SLVoice")
+
+ libdir = "../../libraries/universal-darwin/lib_release"
+ dylibs = {}
+
+ # Need to get the llcommon dll from any of the build directories as well
+ lib = "llcommon"
+ libfile = "lib%s.dylib" % lib
+ try:
+ self.path(self.find_existing_file(os.path.join(os.pardir,
+ lib,
+ self.args['configuration'],
+ libfile),
+ os.path.join(libdir, libfile)),
+ dst=libfile)
+ except RuntimeError:
+ print "Skipping %s" % libfile
+ dylibs[lib] = False
+ else:
+ dylibs[lib] = True
+
+ if dylibs["llcommon"]:
+ for libfile in ("libapr-1.0.3.7.dylib",
+ "libaprutil-1.0.3.8.dylib",
+ "libexpat.0.5.0.dylib",
+ "libexception_handler.dylib",
+ "libGLOD.dylib",
+ "libcollada14dom.dylib"
+ ):
+ self.path(os.path.join(libdir, libfile), libfile)
+
+ try:
+ # FMOD for sound
+ self.path(self.args['configuration'] + "/libfmodwrapper.dylib", "libfmodwrapper.dylib")
+ except:
+ print "Skipping FMOD - not found"
+
+ # our apps
+ self.path("../mac_crash_logger/" + self.args['configuration'] + "/mac-crash-logger.app", "mac-crash-logger.app")
+ self.path("../mac_updater/" + self.args['configuration'] + "/mac-updater.app", "mac-updater.app")
+
+ # plugin launcher
+ self.path("../llplugin/slplugin/" + self.args['configuration'] + "/SLPlugin.app", "SLPlugin.app")
+
+ # our apps dependencies on shared libs
+ if dylibs["llcommon"]:
+ mac_crash_logger_res_path = self.dst_path_of("mac-crash-logger.app/Contents/Resources")
+ mac_updater_res_path = self.dst_path_of("mac-updater.app/Contents/Resources")
+ slplugin_res_path = self.dst_path_of("SLPlugin.app/Contents/Resources")
+ for libfile in ("libllcommon.dylib",
+ "libapr-1.0.3.7.dylib",
+ "libaprutil-1.0.3.8.dylib",
+ "libexpat.0.5.0.dylib",
+ "libexception_handler.dylib",
+ "libGLOD.dylib",
+ "libcollada14dom.dylib"
+ ):
+ target_lib = os.path.join('../../..', libfile)
+ self.run_command("ln -sf %(target)r %(link)r" %
+ {'target': target_lib,
+ 'link' : os.path.join(mac_crash_logger_res_path, libfile)}
+ )
+ self.run_command("ln -sf %(target)r %(link)r" %
+ {'target': target_lib,
+ 'link' : os.path.join(mac_updater_res_path, libfile)}
+ )
+ self.run_command("ln -sf %(target)r %(link)r" %
+ {'target': target_lib,
+ 'link' : os.path.join(slplugin_res_path, libfile)}
+ )
+
+ # plugins
+ if self.prefix(src="", dst="llplugin"):
+ self.path("../media_plugins/quicktime/" + self.args['configuration'] + "/media_plugin_quicktime.dylib", "media_plugin_quicktime.dylib")
+ self.path("../media_plugins/webkit/" + self.args['configuration'] + "/media_plugin_webkit.dylib", "media_plugin_webkit.dylib")
+ self.path("../../libraries/universal-darwin/lib_release/libllqtwebkit.dylib", "libllqtwebkit.dylib")
+
+ self.end_prefix("llplugin")
+
+ # command line arguments for connecting to the proper grid
+ self.put_in_file(self.flags_list(), 'arguments.txt')
+
+ self.end_prefix("Resources")
+
+ self.end_prefix("Contents")
+
+ # NOTE: the -S argument to strip causes it to keep enough info for
+ # annotated backtraces (i.e. function names in the crash log). 'strip' with no
+ # arguments yields a slightly smaller binary but makes crash logs mostly useless.
+ # This may be desirable for the final release. Or not.
+ if ("package" in self.args['actions'] or
+ "unpacked" in self.args['actions']):
+ self.run_command('strip -S %(viewer_binary)r' %
+ { 'viewer_binary' : self.dst_path_of('Contents/MacOS/Second Life')})
+
+
+ def copy_finish(self):
+ # Force executable permissions to be set for scripts
+ # see CHOP-223 and http://mercurial.selenic.com/bts/issue1802
+ for script in 'Contents/MacOS/update_install',:
+ self.run_command("chmod +x %r" % os.path.join(self.get_dst_prefix(), script))
+
+ def package_finish(self):
+ channel_standin = 'Second Life Viewer 2' # hah, our default channel is not usable on its own
+ if not self.default_channel():
+ channel_standin = self.channel()
+
+ imagename="SecondLife_" + '_'.join(self.args['version'])
+
+ # MBW -- If the mounted volume name changes, it breaks the .DS_Store's background image and icon positioning.
+ # If we really need differently named volumes, we'll need to create multiple DS_Store file images, or use some other trick.
+
+ volname="Second Life Installer" # DO NOT CHANGE without understanding comment above
+
+ if self.default_channel():
+ if not self.default_grid():
+ # beta case
+ imagename = imagename + '_' + self.args['grid'].upper()
+ else:
+ # first look, etc
+ imagename = imagename + '_' + self.channel_oneword().upper()
+
+ sparsename = imagename + ".sparseimage"
+ finalname = imagename + ".dmg"
+ # make sure we don't have stale files laying about
+ self.remove(sparsename, finalname)
+
+ self.run_command('hdiutil create %(sparse)r -volname %(vol)r -fs HFS+ -type SPARSE -megabytes 700 -layout SPUD' % {
+ 'sparse':sparsename,
+ 'vol':volname})
+
+ # mount the image and get the name of the mount point and device node
+ hdi_output = self.run_command('hdiutil attach -private %r' % sparsename)
+ try:
+ devfile = re.search("/dev/disk([0-9]+)[^s]", hdi_output).group(0).strip()
+ volpath = re.search('HFS\s+(.+)', hdi_output).group(1).strip()
+
+ if devfile != '/dev/disk1':
+ # adding more debugging info based upon nat's hunches to the
+ # logs to help track down 'SetFile -a V' failures -brad
+ print "WARNING: 'SetFile -a V' command below is probably gonna fail"
+
+ # Copy everything in to the mounted .dmg
+
+ if self.default_channel() and not self.default_grid():
+ app_name = "Second Life " + self.args['grid']
+ else:
+ app_name = channel_standin.strip()
+
+ # Hack:
+ # Because there is no easy way to coerce the Finder into positioning
+ # the app bundle in the same place with different app names, we are
+ # adding multiple .DS_Store files to svn. There is one for release,
+ # one for release candidate and one for first look. Any other channels
+ # will use the release .DS_Store, and will look broken.
+ # - Ambroff 2008-08-20
+ dmg_template = os.path.join(
+ 'installers',
+ 'darwin',
+ '%s-dmg' % "".join(self.channel_unique().split()).lower())
+
+ if not os.path.exists (self.src_path_of(dmg_template)):
+ dmg_template = os.path.join ('installers', 'darwin', 'release-dmg')
+
+ for s,d in {self.get_dst_prefix():app_name + ".app",
+ os.path.join(dmg_template, "_VolumeIcon.icns"): ".VolumeIcon.icns",
+ os.path.join(dmg_template, "background.jpg"): "background.jpg",
+ os.path.join(dmg_template, "_DS_Store"): ".DS_Store"}.items():
+ print "Copying to dmg", s, d
+ self.copy_action(self.src_path_of(s), os.path.join(volpath, d))
+
+ # Hide the background image, DS_Store file, and volume icon file (set their "visible" bit)
+ for f in ".VolumeIcon.icns", "background.jpg", ".DS_Store":
+ pathname = os.path.join(volpath, f)
+ # We've observed mysterious "no such file" failures of the SetFile
+ # command, especially on the first file listed above -- yet
+ # subsequent inspection of the target directory confirms it's
+ # there. Timing problem with copy command? Try to handle.
+ for x in xrange(3):
+ if os.path.exists(pathname):
+ print "Confirmed existence: %r" % pathname
+ break
+ print "Waiting for %s copy command to complete (%s)..." % (f, x+1)
+ sys.stdout.flush()
+ time.sleep(1)
+ # If we fall out of the loop above without a successful break, oh
+ # well, possibly we've mistaken the nature of the problem. In any
+ # case, don't hang up the whole build looping indefinitely, let
+ # the original problem manifest by executing the desired command.
+ self.run_command('SetFile -a V %r' % pathname)
+
+ # Create the alias file (which is a resource file) from the .r
+ self.run_command('Rez %r -o %r' %
+ (self.src_path_of("installers/darwin/release-dmg/Applications-alias.r"),
+ os.path.join(volpath, "Applications")))
+
+ # Set the alias file's alias and custom icon bits
+ self.run_command('SetFile -a AC %r' % os.path.join(volpath, "Applications"))
+
+ # Set the disk image root's custom icon bit
+ self.run_command('SetFile -a C %r' % volpath)
+ finally:
+ # Unmount the image even if exceptions from any of the above
+ self.run_command('hdiutil detach -force %r' % devfile)
+
+ print "Converting temp disk image to final disk image"
+ self.run_command('hdiutil convert %(sparse)r -format UDZO -imagekey zlib-level=9 -o %(final)r' % {'sparse':sparsename, 'final':finalname})
+ # get rid of the temp file
+ self.package_file = finalname
+ self.remove(sparsename)
+
+class LinuxManifest(ViewerManifest):
+ def construct(self):
+ super(LinuxManifest, self).construct()
+ self.path("licenses-linux.txt","licenses.txt")
+ self.path("res/ll_icon.png","secondlife_icon.png")
+ if self.prefix("linux_tools", dst=""):
+ self.path("client-readme.txt","README-linux.txt")
+ self.path("client-readme-voice.txt","README-linux-voice.txt")
+ self.path("client-readme-joystick.txt","README-linux-joystick.txt")
+ self.path("wrapper.sh","secondlife")
+ self.path("handle_secondlifeprotocol.sh", "etc/handle_secondlifeprotocol.sh")
+ self.path("register_secondlifeprotocol.sh", "etc/register_secondlifeprotocol.sh")
+ self.path("refresh_desktop_app_entry.sh", "etc/refresh_desktop_app_entry.sh")
+ self.path("launch_url.sh","etc/launch_url.sh")
+ self.path("install.sh")
+ self.end_prefix("linux_tools")
+
+ # Create an appropriate gridargs.dat for this package, denoting required grid.
+ self.put_in_file(self.flags_list(), 'etc/gridargs.dat')
+
+ self.path("secondlife-bin","bin/do-not-directly-run-secondlife-bin")
+ self.path("../linux_crash_logger/linux-crash-logger","bin/linux-crash-logger.bin")
+ self.path("../linux_updater/linux-updater", "bin/linux-updater.bin")
+ self.path("../llplugin/slplugin/SLPlugin", "bin/SLPlugin")
+
+ if self.prefix("res-sdl"):
+ self.path("*")
+ # recurse
+ self.end_prefix("res-sdl")
+
+ self.path("../viewer_components/updater/scripts/linux/update_install", "bin/update_install")
+
+ # plugins
+ if self.prefix(src="", dst="bin/llplugin"):
+ self.path("../media_plugins/webkit/libmedia_plugin_webkit.so", "libmedia_plugin_webkit.so")
+ self.path("../media_plugins/gstreamer010/libmedia_plugin_gstreamer010.so", "libmedia_plugin_gstreamer.so")
+ self.end_prefix("bin/llplugin")
+
+ try:
+ self.path("../llcommon/libllcommon.so", "lib/libllcommon.so")
+ except:
+ print "Skipping llcommon.so (assuming llcommon was linked statically)"
+
+ self.path("featuretable_linux.txt")
+
+ def copy_finish(self):
+ # Force executable permissions to be set for scripts
+ # see CHOP-223 and http://mercurial.selenic.com/bts/issue1802
+ for script in 'secondlife', 'bin/update_install':
+ self.run_command("chmod +x %r" % os.path.join(self.get_dst_prefix(), script))
+
+ def package_finish(self):
+ if 'installer_name' in self.args:
+ installer_name = self.args['installer_name']
+ else:
+ installer_name_components = ['SecondLife_', self.args.get('arch')]
+ installer_name_components.extend(self.args['version'])
+ installer_name = "_".join(installer_name_components)
+ if self.default_channel():
+ if not self.default_grid():
+ installer_name += '_' + self.args['grid'].upper()
+ else:
+ installer_name += '_' + self.channel_oneword().upper()
+
+ if self.args['buildtype'].lower() == 'release' and self.is_packaging_viewer():
+ print "* Going strip-crazy on the packaged binaries, since this is a RELEASE build"
+ self.run_command("find %(d)r/bin %(d)r/lib -type f \\! -name update_install | xargs --no-run-if-empty strip -S" % {'d': self.get_dst_prefix()} ) # makes some small assumptions about our packaged dir structure
+
+ # Fix access permissions
+ self.run_command("""
+ find %(dst)s -type d | xargs --no-run-if-empty chmod 755;
+ find %(dst)s -type f -perm 0700 | xargs --no-run-if-empty chmod 0755;
+ find %(dst)s -type f -perm 0500 | xargs --no-run-if-empty chmod 0555;
+ find %(dst)s -type f -perm 0600 | xargs --no-run-if-empty chmod 0644;
+ find %(dst)s -type f -perm 0400 | xargs --no-run-if-empty chmod 0444;
+ true""" % {'dst':self.get_dst_prefix() })
+ self.package_file = installer_name + '.tar.bz2'
+
+ # temporarily move directory tree so that it has the right
+ # name in the tarfile
+ self.run_command("mv %(dst)s %(inst)s" % {
+ 'dst': self.get_dst_prefix(),
+ 'inst': self.build_path_of(installer_name)})
+ try:
+ # only create tarball if it's a release build.
+ if self.args['buildtype'].lower() == 'release':
+ # --numeric-owner hides the username of the builder for
+ # security etc.
+ self.run_command('tar -C %(dir)s --numeric-owner -cjf '
+ '%(inst_path)s.tar.bz2 %(inst_name)s' % {
+ 'dir': self.get_build_prefix(),
+ 'inst_name': installer_name,
+ 'inst_path':self.build_path_of(installer_name)})
+ else:
+ print "Skipping %s.tar.bz2 for non-Release build (%s)" % \
+ (installer_name, self.args['buildtype'])
+ finally:
+ self.run_command("mv %(inst)s %(dst)s" % {
+ 'dst': self.get_dst_prefix(),
+ 'inst': self.build_path_of(installer_name)})
+
+class Linux_i686Manifest(LinuxManifest):
+ def construct(self):
+ super(Linux_i686Manifest, self).construct()
+
+ for lib, destdir in ("llkdu", "bin"), ("llcommon", "lib"):
+ libfile = "lib%s.so" % lib
+ try:
+ self.path(self.find_existing_file(os.path.join(os.pardir, lib, libfile),
+ '../../libraries/i686-linux/lib_release_client/%s' % libfile),
+ dst=os.path.join(destdir, libfile))
+ # keep this one to preserve syntax, open source mangling removes previous lines
+ pass
+ except RuntimeError:
+ print "Skipping %s - not found" % libfile
+ pass
+
+ self.path("secondlife-bin","bin/do-not-directly-run-secondlife-bin")
+
+ self.path("../linux_crash_logger/linux-crash-logger","bin/linux-crash-logger.bin")
+ self.path("../linux_updater/linux-updater", "bin/linux-updater.bin")
+ self.path("../llplugin/slplugin/SLPlugin", "bin/SLPlugin")
+ if self.prefix("res-sdl"):
+ self.path("*")
+ # recurse
+ self.end_prefix("res-sdl")
+
+ # plugins
+ if self.prefix(src="", dst="bin/llplugin"):
+ self.path("../media_plugins/webkit/libmedia_plugin_webkit.so", "libmedia_plugin_webkit.so")
+ self.path("../media_plugins/gstreamer010/libmedia_plugin_gstreamer010.so", "libmedia_plugin_gstreamer.so")
+ self.end_prefix("bin/llplugin")
+
+ self.path("featuretable_linux.txt")
+ #self.path("secondlife-i686.supp")
+ if self.prefix("../../libraries/i686-linux/lib_release_client", dst="lib"):
+ self.path("libapr-1.so.0")
+ self.path("libaprutil-1.so.0")
+ self.path("libbreakpad_client.so.0.0.0", "libbreakpad_client.so.0")
+ self.path("libdb-4.2.so")
+ self.path("libcrypto.so.0.9.7")
+ self.path("libuuid.so.1")
+ self.path("libexpat.so.1")
+ self.path("libglod.so")
+ self.path("libssl.so.0.9.7")
+ self.path("libuuid.so.1")
+ self.path("libSDL-1.2.so.0")
+ self.path("libELFIO.so")
+ self.path("libopenjpeg.so.1.3.0", "libopenjpeg.so.1.3")
+ self.path("libalut.so")
+ self.path("libopenal.so", "libopenal.so.1")
+ self.path("libopenal.so", "libvivoxoal.so.1") # vivox's sdk expects this soname
+ self.path("libtcmalloc_minimal.so", "libtcmalloc_minimal.so") #formerly called google perf tools
+ self.path("libtcmalloc_minimal.so.0", "libtcmalloc_minimal.so.0") #formerly called google perf tools
+ try:
+ self.path("libfmod-3.75.so")
+ pass
+ except:
+ print "Skipping libfmod-3.75.so - not found"
+ pass
+ self.end_prefix("lib")
+
+ # Vivox runtimes
+ if self.prefix(src="vivox-runtime/i686-linux", dst="bin"):
+ self.path("SLVoice")
+ self.end_prefix()
+ if self.prefix(src="vivox-runtime/i686-linux", dst="lib"):
+ self.path("libortp.so")
+ self.path("libsndfile.so.1")
+ #self.path("libvivoxoal.so.1") # no - we'll re-use the viewer's own OpenAL lib
+ self.path("libvivoxsdk.so")
+ self.path("libvivoxplatform.so")
+ self.end_prefix("lib")
+
+ if self.args['buildtype'].lower() == 'release' and self.is_packaging_viewer():
+ print "* Going strip-crazy on the packaged binaries, since this is a RELEASE build"
+ self.run_command("find %(d)r/bin %(d)r/lib -type f \\! -name update_install | xargs --no-run-if-empty strip -S" % {'d': self.get_dst_prefix()} ) # makes some small assumptions about our packaged dir structure
+
+
+class Linux_x86_64Manifest(LinuxManifest):
+ def construct(self):
+ super(Linux_x86_64Manifest, self).construct()
+
+ # support file for valgrind debug tool
+ self.path("secondlife-i686.supp")
+
+################################################################
+
+if __name__ == "__main__":
+ main()