Materials module: a) Store materials as assets; b) Finalized it (removed the "Demo" label; removed most of the logging); c) Enabled by default

Changed UuidGatherer to use 'sbyte' to identify assets instead of 'AssetType'. This lets UuidGatherer handle Materials, which are defined in a different enum from 'AssetType'.
master-beforevarregion
Oren Hurvitz 2013-12-06 16:21:11 +02:00 committed by dahlia
parent ca0336d834
commit 3018b2c5d7
12 changed files with 312 additions and 458 deletions

View File

@ -39,8 +39,32 @@ namespace OpenSim.Framework
{ {
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Asset types used only in OpenSim.
/// To avoid clashing with the code numbers used in Second Life, use only negative numbers here.
/// </summary>
public enum OpenSimAssetType : sbyte
{
Material = -2
}
#region SL / file extension / content-type conversions #region SL / file extension / content-type conversions
/// <summary>
/// Returns the Enum entry corresponding to the given code, regardless of whether it belongs
/// to the AssetType or OpenSimAssetType enums.
/// </summary>
public static object AssetTypeFromCode(sbyte assetType)
{
if (Enum.IsDefined(typeof(OpenMetaverse.AssetType), assetType))
return (OpenMetaverse.AssetType)assetType;
else if (Enum.IsDefined(typeof(OpenSimAssetType), assetType))
return (OpenSimAssetType)assetType;
else
return OpenMetaverse.AssetType.Unknown;
}
private class TypeMapping private class TypeMapping
{ {
private sbyte assetType; private sbyte assetType;
@ -56,12 +80,7 @@ namespace OpenSim.Framework
public object AssetType public object AssetType
{ {
get { get { return AssetTypeFromCode(assetType); }
if (Enum.IsDefined(typeof(OpenMetaverse.AssetType), assetType))
return (OpenMetaverse.AssetType)assetType;
else
return OpenMetaverse.AssetType.Unknown;
}
} }
public InventoryType InventoryType public InventoryType InventoryType
@ -102,6 +121,11 @@ namespace OpenSim.Framework
: this((sbyte)assetType, inventoryType, contentType, null, extension) : this((sbyte)assetType, inventoryType, contentType, null, extension)
{ {
} }
public TypeMapping(OpenSimAssetType assetType, InventoryType inventoryType, string contentType, string extension)
: this((sbyte)assetType, inventoryType, contentType, null, extension)
{
}
} }
/// <summary> /// <summary>
@ -142,7 +166,9 @@ namespace OpenSim.Framework
new TypeMapping(AssetType.CurrentOutfitFolder, InventoryType.Unknown, "application/vnd.ll.currentoutfitfolder", "currentoutfitfolder"), new TypeMapping(AssetType.CurrentOutfitFolder, InventoryType.Unknown, "application/vnd.ll.currentoutfitfolder", "currentoutfitfolder"),
new TypeMapping(AssetType.OutfitFolder, InventoryType.Unknown, "application/vnd.ll.outfitfolder", "outfitfolder"), new TypeMapping(AssetType.OutfitFolder, InventoryType.Unknown, "application/vnd.ll.outfitfolder", "outfitfolder"),
new TypeMapping(AssetType.MyOutfitsFolder, InventoryType.Unknown, "application/vnd.ll.myoutfitsfolder", "myoutfitsfolder"), new TypeMapping(AssetType.MyOutfitsFolder, InventoryType.Unknown, "application/vnd.ll.myoutfitsfolder", "myoutfitsfolder"),
new TypeMapping(AssetType.Mesh, InventoryType.Mesh, "application/vnd.ll.mesh", "llm") new TypeMapping(AssetType.Mesh, InventoryType.Mesh, "application/vnd.ll.mesh", "llm"),
new TypeMapping(OpenSimAssetType.Material, InventoryType.Unknown, "application/llsd+xml", "material")
}; };
private static Dictionary<sbyte, string> asset2Content; private static Dictionary<sbyte, string> asset2Content;

View File

@ -29,6 +29,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using OpenMetaverse; using OpenMetaverse;
using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
namespace OpenSim.Framework.Serialization namespace OpenSim.Framework.Serialization
{ {
@ -128,6 +129,7 @@ namespace OpenSim.Framework.Serialization
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Texture] = ASSET_EXTENSION_SEPARATOR + "texture.jp2"; ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Texture] = ASSET_EXTENSION_SEPARATOR + "texture.jp2";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.TextureTGA] = ASSET_EXTENSION_SEPARATOR + "texture.tga"; ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.TextureTGA] = ASSET_EXTENSION_SEPARATOR + "texture.tga";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.TrashFolder] = ASSET_EXTENSION_SEPARATOR + "trashfolder.txt"; // Not sure if we'll ever see this ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.TrashFolder] = ASSET_EXTENSION_SEPARATOR + "trashfolder.txt"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)OpenSimAssetType.Material] = ASSET_EXTENSION_SEPARATOR + "material.xml"; // Not sure if we'll ever see this
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "animation.bvh"] = (sbyte)AssetType.Animation; EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "animation.bvh"] = (sbyte)AssetType.Animation;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "bodypart.txt"] = (sbyte)AssetType.Bodypart; EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "bodypart.txt"] = (sbyte)AssetType.Bodypart;
@ -152,6 +154,7 @@ namespace OpenSim.Framework.Serialization
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.jp2"] = (sbyte)AssetType.Texture; EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.jp2"] = (sbyte)AssetType.Texture;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.tga"] = (sbyte)AssetType.TextureTGA; EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.tga"] = (sbyte)AssetType.TextureTGA;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "trashfolder.txt"] = (sbyte)AssetType.TrashFolder; EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "trashfolder.txt"] = (sbyte)AssetType.TrashFolder;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "material.xml"] = (sbyte)OpenSimAssetType.Material;
} }
public static string CreateOarLandDataPath(LandData ld) public static string CreateOarLandDataPath(LandData ld)

View File

@ -771,7 +771,7 @@ namespace OpenSim.Region.CoreModules.Asset
UuidGatherer gatherer = new UuidGatherer(m_AssetService); UuidGatherer gatherer = new UuidGatherer(m_AssetService);
HashSet<UUID> uniqueUuids = new HashSet<UUID>(); HashSet<UUID> uniqueUuids = new HashSet<UUID>();
Dictionary<UUID, AssetType> assets = new Dictionary<UUID, AssetType>(); Dictionary<UUID, sbyte> assets = new Dictionary<UUID, sbyte>();
foreach (Scene s in m_Scenes) foreach (Scene s in m_Scenes)
{ {
@ -794,7 +794,7 @@ namespace OpenSim.Region.CoreModules.Asset
else if (storeUncached) else if (storeUncached)
{ {
AssetBase cachedAsset = m_AssetService.Get(assetID.ToString()); AssetBase cachedAsset = m_AssetService.Get(assetID.ToString());
if (cachedAsset == null && assets[assetID] != AssetType.Unknown) if (cachedAsset == null && assets[assetID] != (sbyte)AssetType.Unknown)
m_log.DebugFormat( m_log.DebugFormat(
"[FLOTSAM ASSET CACHE]: Could not find asset {0}, type {1} referenced by object {2} at {3} in scene {4} when pre-caching all scene assets", "[FLOTSAM ASSET CACHE]: Could not find asset {0}, type {1} referenced by object {2} at {3} in scene {4} when pre-caching all scene assets",
assetID, assets[assetID], e.Name, e.AbsolutePosition, s.Name); assetID, assets[assetID], e.Name, e.AbsolutePosition, s.Name);

View File

@ -78,7 +78,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// <value> /// <value>
/// Used to collect the uuids of the assets that we need to save into the archive /// Used to collect the uuids of the assets that we need to save into the archive
/// </value> /// </value>
protected Dictionary<UUID, AssetType> m_assetUuids = new Dictionary<UUID, AssetType>(); protected Dictionary<UUID, sbyte> m_assetUuids = new Dictionary<UUID, sbyte>();
/// <value> /// <value>
/// Used to collect the uuids of the users that we need to save into the archive /// Used to collect the uuids of the users that we need to save into the archive
@ -187,7 +187,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
// Don't chase down link asset items as they actually point to their target item IDs rather than an asset // Don't chase down link asset items as they actually point to their target item IDs rather than an asset
if (SaveAssets && itemAssetType != AssetType.Link && itemAssetType != AssetType.LinkFolder) if (SaveAssets && itemAssetType != AssetType.Link && itemAssetType != AssetType.LinkFolder)
m_assetGatherer.GatherAssetUuids(inventoryItem.AssetID, (AssetType)inventoryItem.AssetType, m_assetUuids); m_assetGatherer.GatherAssetUuids(inventoryItem.AssetID, (sbyte)inventoryItem.AssetType, m_assetUuids);
} }
/// <summary> /// <summary>

View File

@ -182,11 +182,11 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
{ {
string url = aCircuit.ServiceURLs["AssetServerURI"].ToString(); string url = aCircuit.ServiceURLs["AssetServerURI"].ToString();
m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Incoming attachment {0} for HG user {1} with asset server {2}", so.Name, so.AttachedAvatar, url); m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Incoming attachment {0} for HG user {1} with asset server {2}", so.Name, so.AttachedAvatar, url);
Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>(); Dictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(Scene.AssetService, url); HGUuidGatherer uuidGatherer = new HGUuidGatherer(Scene.AssetService, url);
uuidGatherer.GatherAssetUuids(so, ids); uuidGatherer.GatherAssetUuids(so, ids);
foreach (KeyValuePair<UUID, AssetType> kvp in ids) foreach (KeyValuePair<UUID, sbyte> kvp in ids)
uuidGatherer.FetchAsset(kvp.Key); uuidGatherer.FetchAsset(kvp.Key);
} }
} }

View File

@ -260,9 +260,9 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
// The act of gathering UUIDs downloads some assets from the remote server // The act of gathering UUIDs downloads some assets from the remote server
// but not all... // but not all...
Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>(); Dictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, userAssetURL); HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, userAssetURL);
uuidGatherer.GatherAssetUuids(assetID, (AssetType)meta.Type, ids); uuidGatherer.GatherAssetUuids(assetID, meta.Type, ids);
m_log.DebugFormat("[HG ASSET MAPPER]: Preparing to get {0} assets", ids.Count); m_log.DebugFormat("[HG ASSET MAPPER]: Preparing to get {0} assets", ids.Count);
bool success = true; bool success = true;
foreach (UUID uuid in ids.Keys) foreach (UUID uuid in ids.Keys)
@ -286,9 +286,9 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
AssetBase asset = m_scene.AssetService.Get(assetID.ToString()); AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
if (asset != null) if (asset != null)
{ {
Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>(); Dictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, string.Empty); HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, string.Empty);
uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids); uuidGatherer.GatherAssetUuids(asset.FullID, asset.Type, ids);
bool success = false; bool success = false;
foreach (UUID uuid in ids.Keys) foreach (UUID uuid in ids.Keys)
{ {

View File

@ -178,7 +178,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
// Archive the regions // Archive the regions
Dictionary<UUID, AssetType> assetUuids = new Dictionary<UUID, AssetType>(); Dictionary<UUID, sbyte> assetUuids = new Dictionary<UUID, sbyte>();
scenesGroup.ForEachScene(delegate(Scene scene) scenesGroup.ForEachScene(delegate(Scene scene)
{ {
@ -216,7 +216,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
} }
} }
private void ArchiveOneRegion(Scene scene, string regionDir, Dictionary<UUID, AssetType> assetUuids) private void ArchiveOneRegion(Scene scene, string regionDir, Dictionary<UUID, sbyte> assetUuids)
{ {
m_log.InfoFormat("[ARCHIVER]: Writing region {0}", scene.RegionInfo.RegionName); m_log.InfoFormat("[ARCHIVER]: Writing region {0}", scene.RegionInfo.RegionName);
@ -276,16 +276,16 @@ namespace OpenSim.Region.CoreModules.World.Archiver
RegionSettings regionSettings = scene.RegionInfo.RegionSettings; RegionSettings regionSettings = scene.RegionInfo.RegionSettings;
if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1) if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1)
assetUuids[regionSettings.TerrainTexture1] = AssetType.Texture; assetUuids[regionSettings.TerrainTexture1] = (sbyte)AssetType.Texture;
if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2) if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2)
assetUuids[regionSettings.TerrainTexture2] = AssetType.Texture; assetUuids[regionSettings.TerrainTexture2] = (sbyte)AssetType.Texture;
if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3) if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3)
assetUuids[regionSettings.TerrainTexture3] = AssetType.Texture; assetUuids[regionSettings.TerrainTexture3] = (sbyte)AssetType.Texture;
if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4) if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4)
assetUuids[regionSettings.TerrainTexture4] = AssetType.Texture; assetUuids[regionSettings.TerrainTexture4] = (sbyte)AssetType.Texture;
Save(scene, sceneObjects, regionDir); Save(scene, sceneObjects, regionDir);
} }

View File

@ -81,7 +81,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
/// <value> /// <value>
/// uuids to request /// uuids to request
/// </value> /// </value>
protected IDictionary<UUID, AssetType> m_uuids; protected IDictionary<UUID, sbyte> m_uuids;
/// <value> /// <value>
/// Callback used when all the assets requested have been received. /// Callback used when all the assets requested have been received.
@ -115,7 +115,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
protected Dictionary<string, object> m_options; protected Dictionary<string, object> m_options;
protected internal AssetsRequest( protected internal AssetsRequest(
AssetsArchiver assetsArchiver, IDictionary<UUID, AssetType> uuids, AssetsArchiver assetsArchiver, IDictionary<UUID, sbyte> uuids,
IAssetService assetService, IUserAccountService userService, IAssetService assetService, IUserAccountService userService,
UUID scope, Dictionary<string, object> options, UUID scope, Dictionary<string, object> options,
AssetsRequestCallback assetsRequestCallback) AssetsRequestCallback assetsRequestCallback)
@ -154,7 +154,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
m_requestCallbackTimer.Enabled = true; m_requestCallbackTimer.Enabled = true;
foreach (KeyValuePair<UUID, AssetType> kvp in m_uuids) foreach (KeyValuePair<UUID, sbyte> kvp in m_uuids)
{ {
// m_log.DebugFormat("[ARCHIVER]: Requesting asset {0}", kvp.Key); // m_log.DebugFormat("[ARCHIVER]: Requesting asset {0}", kvp.Key);
@ -235,9 +235,8 @@ namespace OpenSim.Region.CoreModules.World.Archiver
// Check for broken asset types and fix them with the AssetType gleaned by UuidGatherer // Check for broken asset types and fix them with the AssetType gleaned by UuidGatherer
if (fetchedAsset != null && fetchedAsset.Type == (sbyte)AssetType.Unknown) if (fetchedAsset != null && fetchedAsset.Type == (sbyte)AssetType.Unknown)
{ {
AssetType type = (AssetType)assetType; m_log.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}", fetchedAsset.ID, SLUtil.AssetTypeFromCode((sbyte)assetType));
m_log.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}", fetchedAsset.ID, type); fetchedAsset.Type = (sbyte)assetType;
fetchedAsset.Type = (sbyte)type;
} }
AssetRequestCallback(fetchedAssetID, this, fetchedAsset); AssetRequestCallback(fetchedAssetID, this, fetchedAsset);

View File

@ -62,8 +62,8 @@ namespace OpenSim.Region.Framework.Scenes.Tests
= AssetHelpers.CreateAsset(corruptAssetUuid, AssetType.Notecard, "CORRUPT ASSET", UUID.Zero); = AssetHelpers.CreateAsset(corruptAssetUuid, AssetType.Notecard, "CORRUPT ASSET", UUID.Zero);
m_assetService.Store(corruptAsset); m_assetService.Store(corruptAsset);
IDictionary<UUID, AssetType> foundAssetUuids = new Dictionary<UUID, AssetType>(); IDictionary<UUID, sbyte> foundAssetUuids = new Dictionary<UUID, sbyte>();
m_uuidGatherer.GatherAssetUuids(corruptAssetUuid, AssetType.Object, foundAssetUuids); m_uuidGatherer.GatherAssetUuids(corruptAssetUuid, (sbyte)AssetType.Object, foundAssetUuids);
// We count the uuid as gathered even if the asset itself is corrupt. // We count the uuid as gathered even if the asset itself is corrupt.
Assert.That(foundAssetUuids.Count, Is.EqualTo(1)); Assert.That(foundAssetUuids.Count, Is.EqualTo(1));
@ -78,9 +78,9 @@ namespace OpenSim.Region.Framework.Scenes.Tests
TestHelpers.InMethod(); TestHelpers.InMethod();
UUID missingAssetUuid = UUID.Parse("00000000-0000-0000-0000-000000000666"); UUID missingAssetUuid = UUID.Parse("00000000-0000-0000-0000-000000000666");
IDictionary<UUID, AssetType> foundAssetUuids = new Dictionary<UUID, AssetType>(); IDictionary<UUID, sbyte> foundAssetUuids = new Dictionary<UUID, sbyte>();
m_uuidGatherer.GatherAssetUuids(missingAssetUuid, AssetType.Object, foundAssetUuids); m_uuidGatherer.GatherAssetUuids(missingAssetUuid, (sbyte)AssetType.Object, foundAssetUuids);
// We count the uuid as gathered even if the asset itself is missing. // We count the uuid as gathered even if the asset itself is missing.
Assert.That(foundAssetUuids.Count, Is.EqualTo(1)); Assert.That(foundAssetUuids.Count, Is.EqualTo(1));
@ -103,8 +103,8 @@ namespace OpenSim.Region.Framework.Scenes.Tests
AssetBase ncAsset = AssetHelpers.CreateNotecardAsset(ncAssetId, soAssetId.ToString()); AssetBase ncAsset = AssetHelpers.CreateNotecardAsset(ncAssetId, soAssetId.ToString());
m_assetService.Store(ncAsset); m_assetService.Store(ncAsset);
IDictionary<UUID, AssetType> foundAssetUuids = new Dictionary<UUID, AssetType>(); IDictionary<UUID, sbyte> foundAssetUuids = new Dictionary<UUID, sbyte>();
m_uuidGatherer.GatherAssetUuids(ncAssetId, AssetType.Notecard, foundAssetUuids); m_uuidGatherer.GatherAssetUuids(ncAssetId, (sbyte)AssetType.Notecard, foundAssetUuids);
// We count the uuid as gathered even if the asset itself is corrupt. // We count the uuid as gathered even if the asset itself is corrupt.
Assert.That(foundAssetUuids.Count, Is.EqualTo(2)); Assert.That(foundAssetUuids.Count, Is.EqualTo(2));

View File

@ -38,6 +38,7 @@ using OpenMetaverse.StructuredData;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces; using OpenSim.Services.Interfaces;
using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
namespace OpenSim.Region.Framework.Scenes namespace OpenSim.Region.Framework.Scenes
{ {
@ -83,7 +84,7 @@ namespace OpenSim.Region.Framework.Scenes
/// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param> /// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param>
/// <param name="assetType">The type of the asset for the uuid given</param> /// <param name="assetType">The type of the asset for the uuid given</param>
/// <param name="assetUuids">The assets gathered</param> /// <param name="assetUuids">The assets gathered</param>
public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids) public void GatherAssetUuids(UUID assetUuid, sbyte assetType, IDictionary<UUID, sbyte> assetUuids)
{ {
// avoid infinite loops // avoid infinite loops
if (assetUuids.ContainsKey(assetUuid)) if (assetUuids.ContainsKey(assetUuid))
@ -93,23 +94,27 @@ namespace OpenSim.Region.Framework.Scenes
{ {
assetUuids[assetUuid] = assetType; assetUuids[assetUuid] = assetType;
if (AssetType.Bodypart == assetType || AssetType.Clothing == assetType) if ((sbyte)AssetType.Bodypart == assetType || (sbyte)AssetType.Clothing == assetType)
{ {
GetWearableAssetUuids(assetUuid, assetUuids); GetWearableAssetUuids(assetUuid, assetUuids);
} }
else if (AssetType.Gesture == assetType) else if ((sbyte)AssetType.Gesture == assetType)
{ {
GetGestureAssetUuids(assetUuid, assetUuids); GetGestureAssetUuids(assetUuid, assetUuids);
} }
else if (AssetType.Notecard == assetType) else if ((sbyte)AssetType.Notecard == assetType)
{ {
GetTextEmbeddedAssetUuids(assetUuid, assetUuids); GetTextEmbeddedAssetUuids(assetUuid, assetUuids);
} }
else if (AssetType.LSLText == assetType) else if ((sbyte)AssetType.LSLText == assetType)
{ {
GetTextEmbeddedAssetUuids(assetUuid, assetUuids); GetTextEmbeddedAssetUuids(assetUuid, assetUuids);
} }
else if (AssetType.Object == assetType) else if ((sbyte)OpenSimAssetType.Material == assetType)
{
GetMaterialAssetUuids(assetUuid, assetUuids);
}
else if ((sbyte)AssetType.Object == assetType)
{ {
GetSceneObjectAssetUuids(assetUuid, assetUuids); GetSceneObjectAssetUuids(assetUuid, assetUuids);
} }
@ -136,7 +141,7 @@ namespace OpenSim.Region.Framework.Scenes
/// A dictionary which is populated with the asset UUIDs gathered and the type of that asset. /// A dictionary which is populated with the asset UUIDs gathered and the type of that asset.
/// For assets where the type is not clear (e.g. UUIDs extracted from LSL and notecards), the type is Unknown. /// For assets where the type is not clear (e.g. UUIDs extracted from LSL and notecards), the type is Unknown.
/// </param> /// </param>
public void GatherAssetUuids(SceneObjectGroup sceneObject, IDictionary<UUID, AssetType> assetUuids) public void GatherAssetUuids(SceneObjectGroup sceneObject, IDictionary<UUID, sbyte> assetUuids)
{ {
// m_log.DebugFormat( // m_log.DebugFormat(
// "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID); // "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID);
@ -156,7 +161,7 @@ namespace OpenSim.Region.Framework.Scenes
{ {
// Get the prim's default texture. This will be used for faces which don't have their own texture // Get the prim's default texture. This will be used for faces which don't have their own texture
if (textureEntry.DefaultTexture != null) if (textureEntry.DefaultTexture != null)
assetUuids[textureEntry.DefaultTexture.TextureID] = AssetType.Texture; assetUuids[textureEntry.DefaultTexture.TextureID] = (sbyte)AssetType.Texture;
if (textureEntry.FaceTextures != null) if (textureEntry.FaceTextures != null)
{ {
@ -164,20 +169,20 @@ namespace OpenSim.Region.Framework.Scenes
foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures) foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures)
{ {
if (texture != null) if (texture != null)
assetUuids[texture.TextureID] = AssetType.Texture; assetUuids[texture.TextureID] = (sbyte)AssetType.Texture;
} }
} }
} }
// If the prim is a sculpt then preserve this information too // If the prim is a sculpt then preserve this information too
if (part.Shape.SculptTexture != UUID.Zero) if (part.Shape.SculptTexture != UUID.Zero)
assetUuids[part.Shape.SculptTexture] = AssetType.Texture; assetUuids[part.Shape.SculptTexture] = (sbyte)AssetType.Texture;
if (part.Shape.ProjectionTextureUUID != UUID.Zero) if (part.Shape.ProjectionTextureUUID != UUID.Zero)
assetUuids[part.Shape.ProjectionTextureUUID] = AssetType.Texture; assetUuids[part.Shape.ProjectionTextureUUID] = (sbyte)AssetType.Texture;
if (part.CollisionSound != UUID.Zero) if (part.CollisionSound != UUID.Zero)
assetUuids[part.CollisionSound] = AssetType.Sound; assetUuids[part.CollisionSound] = (sbyte)AssetType.Sound;
if (part.ParticleSystem.Length > 0) if (part.ParticleSystem.Length > 0)
{ {
@ -185,7 +190,7 @@ namespace OpenSim.Region.Framework.Scenes
{ {
Primitive.ParticleSystem ps = new Primitive.ParticleSystem(part.ParticleSystem, 0); Primitive.ParticleSystem ps = new Primitive.ParticleSystem(part.ParticleSystem, 0);
if (ps.Texture != UUID.Zero) if (ps.Texture != UUID.Zero)
assetUuids[ps.Texture] = AssetType.Texture; assetUuids[ps.Texture] = (sbyte)AssetType.Texture;
} }
catch (Exception e) catch (Exception e)
{ {
@ -205,7 +210,7 @@ namespace OpenSim.Region.Framework.Scenes
// tii.Name, tii.Type, part.Name, part.UUID); // tii.Name, tii.Type, part.Name, part.UUID);
if (!assetUuids.ContainsKey(tii.AssetID)) if (!assetUuids.ContainsKey(tii.AssetID))
GatherAssetUuids(tii.AssetID, (AssetType)tii.Type, assetUuids); GatherAssetUuids(tii.AssetID, (sbyte)tii.Type, assetUuids);
} }
// FIXME: We need to make gathering modular but we cannot yet, since gatherers are not guaranteed // FIXME: We need to make gathering modular but we cannot yet, since gatherers are not guaranteed
@ -213,8 +218,6 @@ namespace OpenSim.Region.Framework.Scenes
// inventory transfer. There needs to be a way for a module to register a method without assuming a // inventory transfer. There needs to be a way for a module to register a method without assuming a
// Scene.EventManager is present. // Scene.EventManager is present.
// part.ParentGroup.Scene.EventManager.TriggerGatherUuids(part, assetUuids); // part.ParentGroup.Scene.EventManager.TriggerGatherUuids(part, assetUuids);
GatherMaterialsUuids(part, assetUuids);
} }
catch (Exception e) catch (Exception e)
{ {
@ -225,7 +228,7 @@ namespace OpenSim.Region.Framework.Scenes
} }
} }
} }
// /// <summary> // /// <summary>
// /// The callback made when we request the asset for an object from the asset service. // /// The callback made when we request the asset for an object from the asset service.
// /// </summary> // /// </summary>
@ -238,73 +241,6 @@ namespace OpenSim.Region.Framework.Scenes
// Monitor.Pulse(this); // Monitor.Pulse(this);
// } // }
// } // }
/// <summary>
/// Gather all of the texture asset UUIDs used to reference "Materials" such as normal and specular maps
/// </summary>
/// <param name="part"></param>
/// <param name="assetUuids"></param>
public void GatherMaterialsUuids(SceneObjectPart part, IDictionary<UUID, AssetType> assetUuids)
{
// scan thru the dynAttrs map of this part for any textures used as materials
OSD osdMaterials = null;
lock (part.DynAttrs)
{
if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
{
OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
if (materialsStore == null)
return;
materialsStore.TryGetValue("Materials", out osdMaterials);
}
if (osdMaterials != null)
{
//m_log.Info("[UUID Gatherer]: found Materials: " + OSDParser.SerializeJsonString(osd));
if (osdMaterials is OSDArray)
{
OSDArray matsArr = osdMaterials as OSDArray;
foreach (OSDMap matMap in matsArr)
{
try
{
if (matMap.ContainsKey("Material"))
{
OSDMap mat = matMap["Material"] as OSDMap;
if (mat.ContainsKey("NormMap"))
{
UUID normalMapId = mat["NormMap"].AsUUID();
if (normalMapId != UUID.Zero)
{
assetUuids[normalMapId] = AssetType.Texture;
//m_log.Info("[UUID Gatherer]: found normal map ID: " + normalMapId.ToString());
}
}
if (mat.ContainsKey("SpecMap"))
{
UUID specularMapId = mat["SpecMap"].AsUUID();
if (specularMapId != UUID.Zero)
{
assetUuids[specularMapId] = AssetType.Texture;
//m_log.Info("[UUID Gatherer]: found specular map ID: " + specularMapId.ToString());
}
}
}
}
catch (Exception e)
{
m_log.Warn("[UUID Gatherer]: exception getting materials: " + e.Message);
}
}
}
}
}
}
/// <summary> /// <summary>
/// Get an asset synchronously, potentially using an asynchronous callback. If the /// Get an asset synchronously, potentially using an asynchronous callback. If the
@ -344,7 +280,7 @@ namespace OpenSim.Region.Framework.Scenes
/// </summary> /// </summary>
/// <param name="scriptUuid"></param> /// <param name="scriptUuid"></param>
/// <param name="assetUuids">Dictionary in which to record the references</param> /// <param name="assetUuids">Dictionary in which to record the references</param>
private void GetTextEmbeddedAssetUuids(UUID embeddingAssetId, IDictionary<UUID, AssetType> assetUuids) private void GetTextEmbeddedAssetUuids(UUID embeddingAssetId, IDictionary<UUID, sbyte> assetUuids)
{ {
// m_log.DebugFormat("[ASSET GATHERER]: Getting assets for uuid references in asset {0}", embeddingAssetId); // m_log.DebugFormat("[ASSET GATHERER]: Getting assets for uuid references in asset {0}", embeddingAssetId);
@ -364,7 +300,7 @@ namespace OpenSim.Region.Framework.Scenes
// Embedded asset references (if not false positives) could be for many types of asset, so we will // Embedded asset references (if not false positives) could be for many types of asset, so we will
// label these as unknown. // label these as unknown.
assetUuids[uuid] = AssetType.Unknown; assetUuids[uuid] = (sbyte)AssetType.Unknown;
} }
} }
} }
@ -374,7 +310,7 @@ namespace OpenSim.Region.Framework.Scenes
/// </summary> /// </summary>
/// <param name="wearableAssetUuid"></param> /// <param name="wearableAssetUuid"></param>
/// <param name="assetUuids">Dictionary in which to record the references</param> /// <param name="assetUuids">Dictionary in which to record the references</param>
private void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, AssetType> assetUuids) private void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, sbyte> assetUuids)
{ {
AssetBase assetBase = GetAsset(wearableAssetUuid); AssetBase assetBase = GetAsset(wearableAssetUuid);
@ -389,7 +325,7 @@ namespace OpenSim.Region.Framework.Scenes
foreach (UUID uuid in wearableAsset.Textures.Values) foreach (UUID uuid in wearableAsset.Textures.Values)
{ {
assetUuids[uuid] = AssetType.Texture; assetUuids[uuid] = (sbyte)AssetType.Texture;
} }
} }
} }
@ -401,7 +337,7 @@ namespace OpenSim.Region.Framework.Scenes
/// </summary> /// </summary>
/// <param name="sceneObject"></param> /// <param name="sceneObject"></param>
/// <param name="assetUuids"></param> /// <param name="assetUuids"></param>
private void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, AssetType> assetUuids) private void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, sbyte> assetUuids)
{ {
AssetBase objectAsset = GetAsset(sceneObjectUuid); AssetBase objectAsset = GetAsset(sceneObjectUuid);
@ -430,7 +366,7 @@ namespace OpenSim.Region.Framework.Scenes
/// </summary> /// </summary>
/// <param name="gestureUuid"></param> /// <param name="gestureUuid"></param>
/// <param name="assetUuids"></param> /// <param name="assetUuids"></param>
private void GetGestureAssetUuids(UUID gestureUuid, IDictionary<UUID, AssetType> assetUuids) private void GetGestureAssetUuids(UUID gestureUuid, IDictionary<UUID, sbyte> assetUuids)
{ {
AssetBase assetBase = GetAsset(gestureUuid); AssetBase assetBase = GetAsset(gestureUuid);
if (null == assetBase) if (null == assetBase)
@ -464,9 +400,29 @@ namespace OpenSim.Region.Framework.Scenes
// If it can be parsed as a UUID, it is an asset ID // If it can be parsed as a UUID, it is an asset ID
UUID uuid; UUID uuid;
if (UUID.TryParse(id, out uuid)) if (UUID.TryParse(id, out uuid))
assetUuids[uuid] = AssetType.Animation; assetUuids[uuid] = (sbyte)AssetType.Animation;
} }
} }
/// <summary>
/// Get the asset uuid's referenced in a material.
/// </summary>
private void GetMaterialAssetUuids(UUID materialUuid, IDictionary<UUID, sbyte> assetUuids)
{
AssetBase assetBase = GetAsset(materialUuid);
if (null == assetBase)
return;
OSDMap mat = (OSDMap)OSDParser.DeserializeLLSDXml(assetBase.Data);
UUID normMap = mat["NormMap"].AsUUID();
if (normMap != UUID.Zero)
assetUuids[normMap] = (sbyte)AssetType.Texture;
UUID specMap = mat["SpecMap"].AsUUID();
if (specMap != UUID.Zero)
assetUuids[specMap] = (sbyte)AssetType.Texture;
}
} }
public class HGUuidGatherer : UuidGatherer public class HGUuidGatherer : UuidGatherer

View File

@ -42,77 +42,49 @@ using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes;
using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
using Ionic.Zlib; using Ionic.Zlib;
// You will need to uncomment these lines if you are adding a region module to some other assembly which does not already // You will need to uncomment these lines if you are adding a region module to some other assembly which does not already
// specify its assembly. Otherwise, the region modules in the assembly will not be picked up when OpenSimulator scans // specify its assembly. Otherwise, the region modules in the assembly will not be picked up when OpenSimulator scans
// the available DLLs // the available DLLs
//[assembly: Addin("MaterialsDemoModule", "1.0")] //[assembly: Addin("MaterialsModule", "1.0")]
//[assembly: AddinDependency("OpenSim", "0.5")] //[assembly: AddinDependency("OpenSim", "0.5")]
namespace OpenSim.Region.OptionalModules.MaterialsDemoModule namespace OpenSim.Region.OptionalModules.Materials
{ {
/// <summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MaterialsModule")]
/// public class MaterialsModule : INonSharedRegionModule
// # # ## ##### # # # # # ####
// # # # # # # ## # # ## # # #
// # # # # # # # # # # # # # #
// # ## # ###### ##### # # # # # # # # ###
// ## ## # # # # # ## # # ## # #
// # # # # # # # # # # # ####
//
// THIS MODULE IS FOR EXPERIMENTAL USE ONLY AND MAY CAUSE REGION OR ASSET CORRUPTION!
//
////////////// WARNING //////////////////////////////////////////////////////////////////
/// This is an *Experimental* module for developing support for materials-capable viewers
/// This module should NOT be used in a production environment! It may cause data corruption and
/// viewer crashes. It should be only used to evaluate implementations of materials.
///
/// Materials are persisted via SceneObjectPart.dynattrs. This is a relatively new feature
/// of OpenSimulator and is not field proven at the time this module was written. Persistence
/// may fail or become corrupt and this could cause viewer crashes due to erroneous materials
/// data being sent to viewers. Materials descriptions might survive IAR, OAR, or other means
/// of archiving however the texture resources used by these materials probably will not as they
/// may not be adequately referenced to ensure proper archiving.
///
///
///
/// To enable this module, add this string at the bottom of OpenSim.ini:
/// [MaterialsDemoModule]
///
/// </summary>
///
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MaterialsDemoModule")]
public class MaterialsDemoModule : INonSharedRegionModule
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Name { get { return "MaterialsDemoModule"; } } public string Name { get { return "MaterialsModule"; } }
public Type ReplaceableInterface { get { return null; } } public Type ReplaceableInterface { get { return null; } }
private Scene m_scene = null; private Scene m_scene = null;
private bool m_enabled = false; private bool m_enabled = false;
public Dictionary<UUID, OSDMap> m_knownMaterials = new Dictionary<UUID, OSDMap>(); public Dictionary<UUID, OSDMap> m_regionMaterials = new Dictionary<UUID, OSDMap>();
public void Initialise(IConfigSource source) public void Initialise(IConfigSource source)
{ {
m_enabled = (source.Configs["MaterialsDemoModule"] != null); IConfig config = source.Configs["Materials"];
if (config == null)
return;
m_enabled = config.GetBoolean("enable_materials", true);
if (!m_enabled) if (!m_enabled)
return; return;
m_log.DebugFormat("[MaterialsDemoModule]: Initialized"); m_log.DebugFormat("[Materials]: Initialized");
} }
public void Close() public void Close()
{ {
if (!m_enabled) if (!m_enabled)
return; return;
//m_log.DebugFormat("[MaterialsDemoModule]: CLOSED MODULE");
} }
public void AddRegion(Scene scene) public void AddRegion(Scene scene)
@ -120,22 +92,19 @@ namespace OpenSim.Region.OptionalModules.MaterialsDemoModule
if (!m_enabled) if (!m_enabled)
return; return;
//m_log.DebugFormat("[MaterialsDemoModule]: REGION {0} ADDED", scene.RegionInfo.RegionName);
m_scene = scene; m_scene = scene;
m_scene.EventManager.OnRegisterCaps += OnRegisterCaps; m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene; m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene;
// m_scene.EventManager.OnGatherUuids += GatherMaterialsUuids;
} }
void EventManager_OnObjectAddedToScene(SceneObjectGroup obj) private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj)
{ {
foreach (var part in obj.Parts) foreach (var part in obj.Parts)
if (part != null) if (part != null)
GetStoredMaterialsForPart(part); GetStoredMaterialsInPart(part);
} }
void OnRegisterCaps(OpenMetaverse.UUID agentID, OpenSim.Framework.Capabilities.Caps caps) private void OnRegisterCaps(OpenMetaverse.UUID agentID, OpenSim.Framework.Capabilities.Caps caps)
{ {
string capsBase = "/CAPS/" + caps.CapsObjectPath; string capsBase = "/CAPS/" + caps.CapsObjectPath;
@ -164,143 +133,65 @@ namespace OpenSim.Region.OptionalModules.MaterialsDemoModule
m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps; m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene; m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene;
// m_scene.EventManager.OnGatherUuids -= GatherMaterialsUuids;
//m_log.DebugFormat("[MaterialsDemoModule]: REGION {0} REMOVED", scene.RegionInfo.RegionName);
} }
public void RegionLoaded(Scene scene) public void RegionLoaded(Scene scene)
{ {
} }
OSDMap GetMaterial(UUID id) /// <summary>
{ /// Find the materials used in the SOP, and add them to 'm_regionMaterials'.
OSDMap map = null; /// </summary>
lock (m_knownMaterials) private void GetStoredMaterialsInPart(SceneObjectPart part)
{
if (m_knownMaterials.ContainsKey(id))
{
map = new OSDMap();
map["ID"] = OSD.FromBinary(id.GetBytes());
map["Material"] = m_knownMaterials[id];
}
}
return map;
}
void GetStoredMaterialsForPart(SceneObjectPart part)
{ {
OSD OSMaterials = null; if (part.Shape == null)
OSDArray matsArr = null;
if (part.DynAttrs == null)
{
//m_log.Warn("[MaterialsDemoModule]: NULL DYNATTRS :( ");
return; return;
} var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
if (te == null)
lock (part.DynAttrs)
{
if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
{
OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
if (materialsStore == null)
return;
materialsStore.TryGetValue("Materials", out OSMaterials);
}
if (OSMaterials != null && OSMaterials is OSDArray)
matsArr = OSMaterials as OSDArray;
else
return;
}
//m_log.Info("[MaterialsDemoModule]: OSMaterials: " + OSDParser.SerializeJsonString(OSMaterials));
if (matsArr == null)
{
//m_log.Info("[MaterialsDemoModule]: matsArr is null :( ");
return; return;
}
foreach (OSD elemOsd in matsArr) GetStoredMaterialInFace(part, te.DefaultTexture);
foreach (Primitive.TextureEntryFace face in te.FaceTextures)
{ {
if (elemOsd != null && elemOsd is OSDMap) if (face != null)
{ GetStoredMaterialInFace(part, face);
OSDMap matMap = elemOsd as OSDMap;
if (matMap.ContainsKey("ID") && matMap.ContainsKey("Material"))
{
try
{
lock (m_knownMaterials)
m_knownMaterials[matMap["ID"].AsUUID()] = (OSDMap)matMap["Material"];
}
catch (Exception e)
{
m_log.Warn("[MaterialsDemoModule]: exception decoding persisted material ", e);
}
}
}
} }
} }
void StoreMaterialsForPart(SceneObjectPart part) /// <summary>
/// Find the materials used in one Face, and add them to 'm_regionMaterials'.
/// </summary>
private void GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face)
{ {
try UUID id = face.MaterialID;
if (id == UUID.Zero)
return;
lock (m_regionMaterials)
{ {
if (part == null || part.Shape == null) if (m_regionMaterials.ContainsKey(id))
return; return;
Dictionary<UUID, OSDMap> mats = new Dictionary<UUID, OSDMap>(); byte[] data = m_scene.AssetService.GetData(id.ToString());
if (data == null)
Primitive.TextureEntry te = part.Shape.Textures;
if (te.DefaultTexture != null)
{ {
lock (m_knownMaterials) m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id);
{
if (m_knownMaterials.ContainsKey(te.DefaultTexture.MaterialID))
mats[te.DefaultTexture.MaterialID] = m_knownMaterials[te.DefaultTexture.MaterialID];
}
}
if (te.FaceTextures != null)
{
foreach (var face in te.FaceTextures)
{
if (face != null)
{
lock (m_knownMaterials)
{
if (m_knownMaterials.ContainsKey(face.MaterialID))
mats[face.MaterialID] = m_knownMaterials[face.MaterialID];
}
}
}
}
if (mats.Count == 0)
return; return;
OSDArray matsArr = new OSDArray();
foreach (KeyValuePair<UUID, OSDMap> kvp in mats)
{
OSDMap matOsd = new OSDMap();
matOsd["ID"] = OSD.FromUUID(kvp.Key);
matOsd["Material"] = kvp.Value;
matsArr.Add(matOsd);
} }
OSDMap OSMaterials = new OSDMap(); OSDMap mat;
OSMaterials["Materials"] = matsArr; try
{
mat = (OSDMap)OSDParser.DeserializeLLSDXml(data);
}
catch (Exception e)
{
m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message);
return;
}
lock (part.DynAttrs) m_regionMaterials[id] = mat;
part.DynAttrs.SetStore("OpenSim", "Materials", OSMaterials);
}
catch (Exception e)
{
m_log.Warn("[MaterialsDemoModule]: exception in StoreMaterialsForPart() ", e);
} }
} }
@ -308,8 +199,6 @@ namespace OpenSim.Region.OptionalModules.MaterialsDemoModule
string param, IOSHttpRequest httpRequest, string param, IOSHttpRequest httpRequest,
IOSHttpResponse httpResponse) IOSHttpResponse httpResponse)
{ {
//m_log.Debug("[MaterialsDemoModule]: POST cap handler");
OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request); OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
OSDMap resp = new OSDMap(); OSDMap resp = new OSDMap();
@ -333,34 +222,38 @@ namespace OpenSim.Region.OptionalModules.MaterialsDemoModule
{ {
foreach (OSD elem in (OSDArray)osd) foreach (OSD elem in (OSDArray)osd)
{ {
try try
{ {
UUID id = new UUID(elem.AsBinary(), 0); UUID id = new UUID(elem.AsBinary(), 0);
lock (m_knownMaterials) lock (m_regionMaterials)
{ {
if (m_knownMaterials.ContainsKey(id)) if (m_regionMaterials.ContainsKey(id))
{ {
//m_log.Info("[MaterialsDemoModule]: request for known material ID: " + id.ToString());
OSDMap matMap = new OSDMap(); OSDMap matMap = new OSDMap();
matMap["ID"] = OSD.FromBinary(id.GetBytes()); matMap["ID"] = OSD.FromBinary(id.GetBytes());
matMap["Material"] = m_regionMaterials[id];
matMap["Material"] = m_knownMaterials[id];
respArr.Add(matMap); respArr.Add(matMap);
} }
else else
m_log.Info("[MaterialsDemoModule]: request for UNKNOWN material ID: " + id.ToString()); {
m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());
// Theoretically we could try to load the material from the assets service,
// but that shouldn't be necessary because the viewer should only request
// materials that exist in a prim on the region, and all of these materials
// are already stored in m_regionMaterials.
}
} }
} }
catch (Exception e) catch (Exception e)
{ {
// report something here? m_log.Error("Error getting materials in response to viewer request", e);
continue; continue;
} }
} }
} }
else if (osd is OSDMap) // reqest to assign a material else if (osd is OSDMap) // request to assign a material
{ {
materialsFromViewer = osd as OSDMap; materialsFromViewer = osd as OSDMap;
@ -375,94 +268,118 @@ namespace OpenSim.Region.OptionalModules.MaterialsDemoModule
{ {
foreach (OSDMap matsMap in matsArr) foreach (OSDMap matsMap in matsArr)
{ {
//m_log.Debug("[MaterialsDemoModule]: processing matsMap: " + OSDParser.SerializeJsonString(matsMap));
uint primLocalID = 0; uint primLocalID = 0;
try { primLocalID = matsMap["ID"].AsUInteger(); } try {
catch (Exception e) { m_log.Warn("[MaterialsDemoModule]: cannot decode \"ID\" from matsMap: " + e.Message); } primLocalID = matsMap["ID"].AsUInteger();
//m_log.Debug("[MaterialsDemoModule]: primLocalID: " + primLocalID.ToString()); }
catch (Exception e) {
m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
continue;
}
OSDMap mat = null; OSDMap mat = null;
try { mat = matsMap["Material"] as OSDMap; } try
catch (Exception e) { m_log.Warn("[MaterialsDemoModule]: cannot decode \"Material\" from matsMap: " + e.Message); } {
//m_log.Debug("[MaterialsDemoModule]: mat: " + OSDParser.SerializeJsonString(mat)); mat = matsMap["Material"] as OSDMap;
}
catch (Exception e)
{
m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
continue;
}
SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
if (sop == null)
{
m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
continue;
}
Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
if (te == null)
{
m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
continue;
}
UUID id; UUID id;
if (mat == null) if (mat == null)
{ {
// This happens then the user removes a material from a prim
id = UUID.Zero; id = UUID.Zero;
} }
else else
{ {
id = HashOsd(mat); // Material UUID = hash of the material's data.
lock (m_knownMaterials) // This makes materials deduplicate across the entire grid (but isn't otherwise required).
m_knownMaterials[id] = mat; byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat));
using (var md5 = MD5.Create())
id = new UUID(md5.ComputeHash(data), 0);
lock (m_regionMaterials)
{
if (!m_regionMaterials.ContainsKey(id))
{
m_regionMaterials[id] = mat;
// This asset might exist already, but it's ok to try to store it again
string name = "Material " + ChooseMaterialName(mat, sop);
name = name.Substring(0, Math.Min(64, name.Length)).Trim();
AssetBase asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, sop.OwnerID.ToString());
asset.Data = data;
m_scene.AssetService.Store(asset);
}
}
} }
var sop = m_scene.GetSceneObjectPart(primLocalID);
if (sop == null)
m_log.Debug("[MaterialsDemoModule]: null SOP for localId: " + primLocalID.ToString());
else
{
var te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
if (te == null) int face = -1;
if (matsMap.ContainsKey("Face"))
{
face = matsMap["Face"].AsInteger();
if (te.FaceTextures == null) // && face == 0)
{ {
m_log.Debug("[MaterialsDemoModule]: null TextureEntry for localId: " + primLocalID.ToString()); if (te.DefaultTexture == null)
m_log.WarnFormat("[Materials]: te.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID);
else
te.DefaultTexture.MaterialID = id;
} }
else else
{ {
int face = -1; if (te.FaceTextures.Length >= face - 1)
if (matsMap.ContainsKey("Face"))
{ {
face = matsMap["Face"].AsInteger(); if (te.FaceTextures[face] == null)
if (te.FaceTextures == null) // && face == 0)
{
if (te.DefaultTexture == null)
m_log.Debug("[MaterialsDemoModule]: te.DefaultTexture is null");
else
te.DefaultTexture.MaterialID = id;
}
else
{
if (te.FaceTextures.Length >= face - 1)
{
if (te.FaceTextures[face] == null)
te.DefaultTexture.MaterialID = id;
else
te.FaceTextures[face].MaterialID = id;
}
}
}
else
{
if (te.DefaultTexture != null)
te.DefaultTexture.MaterialID = id; te.DefaultTexture.MaterialID = id;
} else
te.FaceTextures[face].MaterialID = id;
//m_log.DebugFormat("[MaterialsDemoModule]: in \"{0}\", setting material ID for face {1} to {2}", sop.Name, face, id);
//we cant use sop.UpdateTextureEntry(te); because it filters so do it manually
if (sop.ParentGroup != null)
{
sop.Shape.TextureEntry = te.GetBytes();
sop.TriggerScriptChangedEvent(Changed.TEXTURE);
sop.UpdateFlag = UpdateRequired.FULL;
sop.ParentGroup.HasGroupChanged = true;
sop.ScheduleFullUpdate();
StoreMaterialsForPart(sop);
} }
} }
} }
else
{
if (te.DefaultTexture != null)
te.DefaultTexture.MaterialID = id;
}
//m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);
// We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
sop.Shape.TextureEntry = te.GetBytes();
if (sop.ParentGroup != null)
{
sop.TriggerScriptChangedEvent(Changed.TEXTURE);
sop.UpdateFlag = UpdateRequired.FULL;
sop.ParentGroup.HasGroupChanged = true;
sop.ScheduleFullUpdate();
}
} }
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Warn("[MaterialsDemoModule]: exception processing received material ", e); m_log.Warn("[Materials]: exception processing received material ", e);
} }
} }
} }
@ -472,36 +389,63 @@ namespace OpenSim.Region.OptionalModules.MaterialsDemoModule
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Warn("[MaterialsDemoModule]: exception decoding zipped CAP payload ", e); m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
//return ""; //return "";
} }
//m_log.Debug("[MaterialsDemoModule]: knownMaterials.Count: " + m_knownMaterials.Count.ToString());
} }
resp["Zipped"] = ZCompressOSD(respArr, false); resp["Zipped"] = ZCompressOSD(respArr, false);
string response = OSDParser.SerializeLLSDXmlString(resp); string response = OSDParser.SerializeLLSDXmlString(resp);
//m_log.Debug("[MaterialsDemoModule]: cap request: " + request); //m_log.Debug("[Materials]: cap request: " + request);
//m_log.Debug("[MaterialsDemoModule]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
//m_log.Debug("[MaterialsDemoModule]: cap response: " + response); //m_log.Debug("[Materials]: cap response: " + response);
return response; return response;
} }
/// <summary>
/// Use heuristics to choose a good name for the material.
/// </summary>
private string ChooseMaterialName(OSDMap mat, SceneObjectPart sop)
{
UUID normMap = mat["NormMap"].AsUUID();
if (normMap != UUID.Zero)
{
AssetBase asset = m_scene.AssetService.GetCached(normMap.ToString());
if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
return asset.Name;
}
UUID specMap = mat["SpecMap"].AsUUID();
if (specMap != UUID.Zero)
{
AssetBase asset = m_scene.AssetService.GetCached(specMap.ToString());
if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
return asset.Name;
}
if (sop.Name != "Primitive")
return sop.Name;
if ((sop.ParentGroup != null) && (sop.ParentGroup.Name != "Primitive"))
return sop.ParentGroup.Name;
return "";
}
public string RenderMaterialsGetCap(string request, string path, public string RenderMaterialsGetCap(string request, string path,
string param, IOSHttpRequest httpRequest, string param, IOSHttpRequest httpRequest,
IOSHttpResponse httpResponse) IOSHttpResponse httpResponse)
{ {
//m_log.Debug("[MaterialsDemoModule]: GET cap handler");
OSDMap resp = new OSDMap(); OSDMap resp = new OSDMap();
int matsCount = 0; int matsCount = 0;
OSDArray allOsd = new OSDArray(); OSDArray allOsd = new OSDArray();
lock (m_knownMaterials) lock (m_regionMaterials)
{ {
foreach (KeyValuePair<UUID, OSDMap> kvp in m_knownMaterials) foreach (KeyValuePair<UUID, OSDMap> kvp in m_regionMaterials)
{ {
OSDMap matMap = new OSDMap(); OSDMap matMap = new OSDMap();
@ -513,12 +457,11 @@ namespace OpenSim.Region.OptionalModules.MaterialsDemoModule
} }
resp["Zipped"] = ZCompressOSD(allOsd, false); resp["Zipped"] = ZCompressOSD(allOsd, false);
//m_log.Debug("[MaterialsDemoModule]: matsCount: " + matsCount.ToString());
return OSDParser.SerializeLLSDXmlString(resp); return OSDParser.SerializeLLSDXmlString(resp);
} }
static string ZippedOsdBytesToString(byte[] bytes) private static string ZippedOsdBytesToString(byte[] bytes)
{ {
try try
{ {
@ -537,26 +480,27 @@ namespace OpenSim.Region.OptionalModules.MaterialsDemoModule
/// <returns></returns> /// <returns></returns>
private static UUID HashOsd(OSD osd) private static UUID HashOsd(OSD osd)
{ {
byte[] data = OSDParser.SerializeLLSDBinary(osd, false);
using (var md5 = MD5.Create()) using (var md5 = MD5.Create())
using (MemoryStream ms = new MemoryStream(OSDParser.SerializeLLSDBinary(osd, false))) return new UUID(md5.ComputeHash(data), 0);
return new UUID(md5.ComputeHash(ms), 0);
} }
public static OSD ZCompressOSD(OSD inOsd, bool useHeader) public static OSD ZCompressOSD(OSD inOsd, bool useHeader)
{ {
OSD osd = null; OSD osd = null;
byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader);
using (MemoryStream msSinkCompressed = new MemoryStream()) using (MemoryStream msSinkCompressed = new MemoryStream())
{ {
using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed, using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed,
Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true)) Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true))
{ {
CopyStream(new MemoryStream(OSDParser.SerializeLLSDBinary(inOsd, useHeader)), zOut); zOut.Write(data, 0, data.Length);
zOut.Close();
} }
msSinkCompressed.Seek(0L, SeekOrigin.Begin); msSinkCompressed.Seek(0L, SeekOrigin.Begin);
osd = OSD.FromBinary( msSinkCompressed.ToArray()); osd = OSD.FromBinary(msSinkCompressed.ToArray());
} }
return osd; return osd;
@ -571,94 +515,14 @@ namespace OpenSim.Region.OptionalModules.MaterialsDemoModule
{ {
using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkUnCompressed, CompressionMode.Decompress, true)) using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkUnCompressed, CompressionMode.Decompress, true))
{ {
CopyStream(new MemoryStream(input), zOut); zOut.Write(input, 0, input.Length);
zOut.Close();
} }
msSinkUnCompressed.Seek(0L, SeekOrigin.Begin); msSinkUnCompressed.Seek(0L, SeekOrigin.Begin);
osd = OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray()); osd = OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray());
} }
return osd; return osd;
} }
static void CopyStream(System.IO.Stream input, System.IO.Stream output)
{
byte[] buffer = new byte[2048];
int len;
while ((len = input.Read(buffer, 0, 2048)) > 0)
{
output.Write(buffer, 0, len);
}
output.Flush();
}
// FIXME: This code is currently still in UuidGatherer since we cannot use Scene.EventManager as some
// calls to the gatherer are done for objects with no scene.
// /// <summary>
// /// Gather all of the texture asset UUIDs used to reference "Materials" such as normal and specular maps
// /// </summary>
// /// <param name="part"></param>
// /// <param name="assetUuids"></param>
// private void GatherMaterialsUuids(SceneObjectPart part, IDictionary<UUID, AssetType> assetUuids)
// {
// // scan thru the dynAttrs map of this part for any textures used as materials
// OSD osdMaterials = null;
//
// lock (part.DynAttrs)
// {
// if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
// {
// OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
// if (materialsStore == null)
// return;
//
// materialsStore.TryGetValue("Materials", out osdMaterials);
// }
//
// if (osdMaterials != null)
// {
// //m_log.Info("[UUID Gatherer]: found Materials: " + OSDParser.SerializeJsonString(osd));
//
// if (osdMaterials is OSDArray)
// {
// OSDArray matsArr = osdMaterials as OSDArray;
// foreach (OSDMap matMap in matsArr)
// {
// try
// {
// if (matMap.ContainsKey("Material"))
// {
// OSDMap mat = matMap["Material"] as OSDMap;
// if (mat.ContainsKey("NormMap"))
// {
// UUID normalMapId = mat["NormMap"].AsUUID();
// if (normalMapId != UUID.Zero)
// {
// assetUuids[normalMapId] = AssetType.Texture;
// //m_log.Info("[UUID Gatherer]: found normal map ID: " + normalMapId.ToString());
// }
// }
// if (mat.ContainsKey("SpecMap"))
// {
// UUID specularMapId = mat["SpecMap"].AsUUID();
// if (specularMapId != UUID.Zero)
// {
// assetUuids[specularMapId] = AssetType.Texture;
// //m_log.Info("[UUID Gatherer]: found specular map ID: " + specularMapId.ToString());
// }
// }
// }
//
// }
// catch (Exception e)
// {
// m_log.Warn("[MaterialsDemoModule]: exception getting materials: " + e.Message);
// }
// }
// }
// }
// }
// }
} }
} }

View File

@ -691,6 +691,12 @@
; enable_windlight = false ; enable_windlight = false
[Materials]
;# {enable_materials} {} {Enable Materials support?} {true false} true
;; This enables the use of Materials.
; enable_materials = true
[DataSnapshot] [DataSnapshot]
;# {index_sims} {} {Enable data snapshotting (search)?} {true false} false ;# {index_sims} {} {Enable data snapshotting (search)?} {true false} false
;; The following set of configs pertains to search. ;; The following set of configs pertains to search.