public AssetLandmark(AssetBase a) : base(a.ID, a.Name, a.TypeAsset, a.CreatorID) { Data = a.Data; Description = a.Description; InternData(); }
public UUID SaveBitmap (Bitmap data, bool lossless, bool temporary) { AssetBase asset = new AssetBase ( UUID.Random (), "MRMDynamicImage", AssetType.Texture, m_scene.RegionInfo.RegionID) { Data = OpenJPEG.EncodeFromImage (data, lossless), Description = "MRM Image", Flags = (temporary) ? AssetFlags.Temporary : 0 }; var assetID = m_scene.AssetService.Store (asset); asset.Dispose (); return assetID; }
public virtual UUID Store (AssetBase asset) { if (asset == null) return UUID.Zero; if (m_doRemoteOnly) { object remoteValue = DoRemoteByURL ("AssetServerURI", asset); if (remoteValue == null) return UUID.Zero; asset.ID = (UUID)remoteValue; } else FileSetAsset (asset); IImprovedAssetCache cache = m_registry.RequestModuleInterface<IImprovedAssetCache> (); if (doDatabaseCaching && cache != null && asset != null && asset.Data != null && asset.Data.Length != 0) { cache.Expire (asset.ID.ToString ()); cache.Cache (asset.ID.ToString (), asset); } return asset.ID; }
/// <summary> /// </summary> /// <param name="assetName"></param> /// <param name="assetDescription"></param> /// <param name="assetID"></param> /// <param name="inventoryItem"></param> /// <param name="parentFolder"></param> /// <param name="data"></param> /// <param name="inventoryType"></param> /// <param name="assetType"></param> /// <param name="everyoneMask"></param> /// <param name="groupMask"></param> /// <param name="nextOwnerMask"></param> public UUID UploadCompleteHandler (string assetName, string assetDescription, UUID assetID, UUID inventoryItem, UUID parentFolder, byte [] data, string inventoryType, string assetType, uint everyoneMask, uint groupMask, uint nextOwnerMask) { sbyte assType = 0; sbyte inType = 0; switch (inventoryType) { case "sound": inType = 1; assType = 1; break; case "animation": inType = 19; assType = 20; break; case "snapshot": inType = 15; assType = 0; break; case "wearable": inType = 18; switch (assetType) { case "bodypart": assType = 13; break; case "clothing": assType = 5; break; } break; case "object": { inType = (sbyte)InventoryType.Object; assType = (sbyte)AssetType.Object; List<Vector3> positions = new List<Vector3> (); List<Quaternion> rotations = new List<Quaternion> (); OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml (data); OSDArray instance_list = (OSDArray)request ["instance_list"]; OSDArray mesh_list = (OSDArray)request ["mesh_list"]; OSDArray texture_list = (OSDArray)request ["texture_list"]; SceneObjectGroup grp = null; List<UUID> textures = new List<UUID> (); foreach ( AssetBase textureAsset in texture_list.Select (t => new AssetBase (UUID.Random (), assetName, AssetType.Texture, m_agentID) { Data = t.AsBinary () })) { textureAsset.ID = m_assetService.Store (textureAsset); textures.Add (textureAsset.ID); } InventoryFolderBase meshFolder = m_inventoryService.GetFolderForType (m_agentID, InventoryType.Mesh, FolderType.Mesh); for (int i = 0; i < mesh_list.Count; i++) { PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox (); Primitive.TextureEntry textureEntry = new Primitive.TextureEntry (Primitive.TextureEntry.WHITE_TEXTURE); OSDMap inner_instance_list = (OSDMap)instance_list [i]; OSDArray face_list = (OSDArray)inner_instance_list ["face_list"]; for (uint face = 0; face < face_list.Count; face++) { OSDMap faceMap = (OSDMap)face_list [(int)face]; Primitive.TextureEntryFace f = pbs.Textures.CreateFace (face); if (faceMap.ContainsKey ("fullbright")) f.Fullbright = faceMap ["fullbright"].AsBoolean (); if (faceMap.ContainsKey ("diffuse_color")) f.RGBA = faceMap ["diffuse_color"].AsColor4 (); int textureNum = faceMap ["image"].AsInteger (); float imagerot = faceMap ["imagerot"].AsInteger (); float offsets = (float)faceMap ["offsets"].AsReal (); float offsett = (float)faceMap ["offsett"].AsReal (); float scales = (float)faceMap ["scales"].AsReal (); float scalet = (float)faceMap ["scalet"].AsReal (); if (imagerot != 0) f.Rotation = imagerot; if (offsets != 0) f.OffsetU = offsets; if (offsett != 0) f.OffsetV = offsett; if (scales != 0) f.RepeatU = scales; if (scalet != 0) f.RepeatV = scalet; f.TextureID = textures.Count > textureNum ? textures [textureNum] : Primitive.TextureEntry.WHITE_TEXTURE; textureEntry.FaceTextures [face] = f; } pbs.TextureEntry = textureEntry.GetBytes (); AssetBase meshAsset = new AssetBase (UUID.Random (), assetName, AssetType.Mesh, m_agentID) { Data = mesh_list [i].AsBinary () }; meshAsset.ID = m_assetService.Store (meshAsset); if (meshFolder == null) { m_inventoryService.CreateUserInventory (m_agentID, false); meshFolder = m_inventoryService.GetFolderForType (m_agentID, InventoryType.Mesh, FolderType.Mesh); } InventoryItemBase itemBase = new InventoryItemBase (UUID.Random (), m_agentID) { AssetType = (sbyte)AssetType.Mesh, AssetID = meshAsset.ID, CreatorId = m_agentID.ToString (), Folder = meshFolder.ID, InvType = (int)InventoryType.Texture, Name = "(Mesh) - " + assetName, CurrentPermissions = (uint)PermissionMask.All, BasePermissions = (uint)PermissionMask.All, EveryOnePermissions = everyoneMask, GroupPermissions = groupMask, NextPermissions = nextOwnerMask }; //Bad... but whatever m_inventoryService.AddItem (itemBase); pbs.SculptEntry = true; pbs.SculptTexture = meshAsset.ID; pbs.SculptType = (byte)SculptType.Mesh; pbs.SculptData = meshAsset.Data; Vector3 position = inner_instance_list ["position"].AsVector3 (); Vector3 scale = inner_instance_list ["scale"].AsVector3 (); Quaternion rotation = inner_instance_list ["rotation"].AsQuaternion (); int physicsShapeType = inner_instance_list ["physics_shape_type"].AsInteger (); // not currently used int material = inner_instance_list["material"].AsInteger(); // not currently used int mesh = inner_instance_list["mesh"].AsInteger(); SceneObjectPart prim = new SceneObjectPart (m_agentID, pbs, position, Quaternion.Identity, Vector3.Zero, assetName) { Scale = scale, AbsolutePosition = position }; rotations.Add (rotation); positions.Add (position); prim.UUID = UUID.Random (); prim.CreatorID = m_agentID; prim.OwnerID = m_agentID; prim.GroupID = UUID.Zero; prim.LastOwnerID = m_agentID; prim.CreationDate = Util.UnixTimeSinceEpoch (); prim.Name = assetName; prim.Description = ""; prim.PhysicsType = (byte)physicsShapeType; prim.BaseMask = (uint)PermissionMask.All; prim.EveryoneMask = everyoneMask; prim.NextOwnerMask = nextOwnerMask; prim.GroupMask = groupMask; prim.OwnerMask = (uint)PermissionMask.All; if (grp == null) grp = new SceneObjectGroup (prim, null); else grp.AddChild (prim, i + 1); grp.RootPart.IsAttachment = false; } if (grp != null) { // unlikely not to have anything but itis possible if (grp.ChildrenList.Count > 1) //Fix first link # grp.RootPart.LinkNum++; Vector3 rootPos = positions [0]; grp.SetAbsolutePosition (false, rootPos); for (int i = 0; i < positions.Count; i++) { Vector3 offset = positions [i] - rootPos; grp.ChildrenList [i].SetOffsetPosition (offset); } //grp.Rotation = rotations[0]; for (int i = 0; i < rotations.Count; i++) { if (i != 0) grp.ChildrenList [i].SetRotationOffset (false, rotations [i], false); } grp.UpdateGroupRotationR (rotations [0]); data = Encoding.ASCII.GetBytes (grp.ToXml2 ()); } } break; } AssetBase asset = new AssetBase (assetID, assetName, (AssetType)assType, m_agentID) { Data = data }; asset.ID = m_assetService.Store (asset); assetID = asset.ID; InventoryItemBase item = new InventoryItemBase { Owner = m_agentID, CreatorId = m_agentID.ToString (), ID = inventoryItem, AssetID = asset.ID, Description = assetDescription, Name = assetName, AssetType = assType, InvType = inType, Folder = parentFolder, CurrentPermissions = (uint)PermissionMask.All, BasePermissions = (uint)PermissionMask.All, EveryOnePermissions = everyoneMask, NextPermissions = nextOwnerMask, GroupPermissions = groupMask, CreationDate = Util.UnixTimeSinceEpoch () }; m_inventoryService.AddItem (item); return assetID; }
/// <summary> /// Builds a composited terrain texture given the region texture /// and heightmap settings /// </summary> /// <param name="heightmap">Terrain heightmap</param> /// <param name="textureIDs"></param> /// <param name="startHeights"></param> /// <param name="heightRanges"></param> /// <param name="regionPosition"></param> /// <param name="assetService"></param> /// <param name="textureTerrain"></param> /// <returns>A composited 256x256 RGB texture ready for rendering</returns> /// <remarks> /// Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting /// </remarks> public static Bitmap Splat(ITerrainChannel heightmap, UUID[] textureIDs, float[] startHeights, float[] heightRanges, Vector3d regionPosition, IAssetService assetService, bool textureTerrain) { Debug.Assert(textureIDs.Length == 4); Debug.Assert(startHeights.Length == 4); Debug.Assert(heightRanges.Length == 4); Bitmap[] detailTexture = new Bitmap[4]; int outWidth = heightmap.Width; int outHeight = heightmap.Height; IJ2KDecoder m_imgDecoder; if (textureTerrain) { // Swap empty terrain textureIDs with default IDs for (int i = 0; i < textureIDs.Length; i++) { if (textureIDs[i] == UUID.Zero) textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i]; } #region Texture Fetching if (assetService != null) { m_imgDecoder = heightmap.Scene.RequestModuleInterface<IJ2KDecoder>(); for (int i = 0; i < 4; i++) { UUID cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]); AssetBase asset = assetService.Get(cacheID.ToString(),false); // ignore warnings here as the cached texture may not exist if ((asset != null) && (asset.Data != null) && (asset.Data.Length != 0)) { try { using (MemoryStream stream = new MemoryStream(asset.Data)) detailTexture[i] = (Bitmap) Image.FromStream(stream); } catch (Exception ex) { MainConsole.Instance.Warn("Failed to decode cached terrain texture " + cacheID + " (textureID: " + textureIDs[i] + "): " + ex.Message); } } if (detailTexture[i] == null) { // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG byte[] assetData = assetService.GetData(textureIDs[i].ToString()); if (assetData != null) { try { detailTexture[i] = (Bitmap)m_imgDecoder.DecodeToImage(assetData); } catch (Exception ex) { MainConsole.Instance.Warn("Failed to decode terrain texture " + textureIDs[i] + ": " + ex.Message); } } if (detailTexture[i] != null) { Bitmap bitmap = detailTexture[i]; // Make sure this texture is the correct size, otherwise resize if (bitmap.Width != outWidth || bitmap.Height != outHeight) bitmap = ImageUtils.ResizeImage(bitmap, outWidth, outHeight); // Save the decoded and resized texture to the cache byte[] data; using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Png); data = stream.ToArray(); } // Cache a PNG copy of this terrain texture AssetBase newAsset = new AssetBase { Data = data, Description = "PNG", Flags = AssetFlags.Collectable | AssetFlags.Temporary | AssetFlags.Local, ID = cacheID, Name = String.Empty, TypeString = "image/png" }; newAsset.ID = assetService.Store(newAsset); } } } } #endregion Texture Fetching } // Fill in any missing textures with a solid color for (int i = 0; i < 4; i++) { if (detailTexture[i] == null) { // Create a solid color texture for this layer detailTexture[i] = new Bitmap(outWidth, outHeight, PixelFormat.Format24bppRgb); using (Graphics gfx = Graphics.FromImage(detailTexture[i])) { using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i])) gfx.FillRectangle(brush, 0, 0, outWidth, outHeight); } } else if (detailTexture[i].Width != outWidth || detailTexture[i].Height != outHeight) { detailTexture[i] = ResizeBitmap(detailTexture[i], outWidth, outHeight); } } #region Layer Map float diffX = 1.0f; float diffY = 1.0f; int newRsX = heightmap.Width / (int)diffX; int newRsY = heightmap.Height / (int)diffY; float[] layermap = new float[newRsX*newRsY]; for (float y = 0; y < heightmap.Height; y += diffY) { for (float x = 0; x < heightmap.Width; x += diffX) { float newX = x/diffX; float newY = y/diffY; float height = heightmap[(int) x, (int) y]; float pctX = newX/255f; float pctY = newY/255f; // Use bilinear interpolation between the four corners of start height and // height range to select the current values at this position float startHeight = ImageUtils.Bilinear( startHeights[0], startHeights[2], startHeights[1], startHeights[3], pctX, pctY); startHeight = Utils.Clamp(startHeight, 0f, 255f); float heightRange = ImageUtils.Bilinear( heightRanges[0], heightRanges[2], heightRanges[1], heightRanges[3], pctX, pctY); heightRange = Utils.Clamp(heightRange, 0f, 255f); // Generate two frequencies of perlin noise based on our global position // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting Vector3 vec = new Vector3 ( ((float) regionPosition.X + newX)*0.20319f, ((float) regionPosition.Y + newY)*0.20319f, height*0.25f ); float lowFreq = Perlin.noise2(vec.X*0.222222f, vec.Y*0.222222f)*6.5f; float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f)*2.25f; float noise = (lowFreq + highFreq)*2f; // Combine the current height, generated noise, start height, and height range parameters, then scale all of it float layer = ((height + noise - startHeight)/heightRange)*4f; if (Single.IsNaN(layer)) layer = 0f; layermap[(int) (newY*newRsX + newX)] = Utils.Clamp(layer, 0f, 3f); } } #endregion Layer Map #region Texture Compositing Bitmap output = new Bitmap(outWidth, outHeight, PixelFormat.Format24bppRgb); BitmapData outputData = output.LockBits(new Rectangle(0, 0, outWidth, outHeight), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); unsafe { // Get handles to all of the texture data arrays BitmapData[] datas = new[] { detailTexture[0].LockBits(new Rectangle(0, 0, outWidth, outHeight), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat), detailTexture[1].LockBits(new Rectangle(0, 0, outWidth, outHeight), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat), detailTexture[2].LockBits(new Rectangle(0, 0, outWidth, outHeight), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat), detailTexture[3].LockBits(new Rectangle(0, 0, outWidth, outHeight), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat) }; int[] comps = new[] { (datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3, (datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3, (datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3, (datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3 }; for (int y = 0; y < newRsY; y++) { for (int x = 0; x < newRsX; x++) { float layer = layermap[y*newRsX + x]; // Select two textures int l0 = (int) Math.Floor(layer); int l1 = Math.Min(l0 + 1, 3); byte* ptrA = (byte*) datas[l0].Scan0 + y*datas[l0].Stride + x*comps[l0]; byte* ptrB = (byte*) datas[l1].Scan0 + y*datas[l1].Stride + x*comps[l1]; byte* ptrO = (byte*) outputData.Scan0 + y*outputData.Stride + x*3; float aB = *(ptrA + 0); float aG = *(ptrA + 1); float aR = *(ptrA + 2); float bB = *(ptrB + 0); float bG = *(ptrB + 1); float bR = *(ptrB + 2); float layerDiff = layer - l0; // Interpolate between the two selected textures *(ptrO + 0) = (byte) Math.Floor(aB + layerDiff*(bB - aB)); *(ptrO + 1) = (byte) Math.Floor(aG + layerDiff*(bG - aG)); *(ptrO + 2) = (byte) Math.Floor(aR + layerDiff*(bR - aR)); } } for (int i = 0; i < 4; i++) { detailTexture[i].UnlockBits(datas[i]); detailTexture[i].Dispose(); } } layermap = null; output.UnlockBits(outputData); // We generated the texture upside down, so flip it output.RotateFlip(RotateFlipType.RotateNoneFlipY); #endregion Texture Compositing return output; }
public EstateTerrainXferHandler(IClientAPI pRemoteClient, string pClientFilename) { m_asset = new AssetBase(UUID.Zero, pClientFilename, AssetType.Texture, pRemoteClient.AgentId) {Data = new byte[0], Description = "empty", Flags = AssetFlags.Temporary | AssetFlags.Local}; }
/// <summary> /// Save a notecard to prim inventory. /// </summary> /// <param name="name"></param> /// <param name="description">Description of notecard</param> /// <param name="notecardData"></param> /// <param name="forceSameName"> /// If true, then if an item exists with the same name, it is replaced. /// If false, then a new item is created witha slightly different name (e.g. name 1) /// </param> /// <returns>Prim inventory item created.</returns> protected TaskInventoryItem SaveNotecard(string name, string description, string data, bool forceSameName) { // Create new asset AssetBase asset = new AssetBase(UUID.Random(), name, AssetType.Notecard, m_host.OwnerID); asset.Description = description; byte[] a; byte[] b; byte[] c; b = Util.UTF8.GetBytes(data); a = Util.UTF8.GetBytes( "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length " + b.Length + "\n"); c = Util.UTF8.GetBytes("}"); byte[] d = new byte[a.Length + b.Length + c.Length]; Buffer.BlockCopy(a, 0, d, 0, a.Length); Buffer.BlockCopy(b, 0, d, a.Length, b.Length); Buffer.BlockCopy(c, 0, d, a.Length + b.Length, c.Length); asset.Data = d; World.AssetService.Store(asset); // Create Task Entry TaskInventoryItem taskItem = new TaskInventoryItem(); taskItem.ResetIDs(m_host.UUID); taskItem.ParentID = m_host.UUID; taskItem.CreationDate = (uint)Util.UnixTimeSinceEpoch(); taskItem.Name = asset.Name; taskItem.Description = asset.Description; taskItem.Type = (int)AssetType.Notecard; taskItem.InvType = (int)InventoryType.Notecard; taskItem.OwnerID = m_host.OwnerID; taskItem.CreatorID = m_host.OwnerID; taskItem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export; taskItem.CurrentPermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export; taskItem.EveryonePermissions = 0; taskItem.NextPermissions = (uint)PermissionMask.All; taskItem.GroupID = m_host.GroupID; taskItem.GroupPermissions = 0; taskItem.Flags = 0; taskItem.PermsGranter = UUID.Zero; taskItem.PermsMask = 0; taskItem.AssetID = asset.ID; if (forceSameName) m_host.Inventory.AddInventoryItemExclusive(taskItem, false); else m_host.Inventory.AddInventoryItem(taskItem, false); return taskItem; }
AssetBase LoadAssetBase (OSDMap map) { AssetBase asset = new AssetBase (); asset.FromOSD (map); return asset; }
public void AbuseTextureUploaded(UUID agentID, UUID assetID, byte[] data) { //MainConsole.Instance.InfoFormat("[AssetCAPS]: Received baked texture {0}", assetID.ToString()); AssetBase asset = new AssetBase(assetID, "Abuse Texture", AssetType.Texture, agentID) { Data = data }; asset.ID = m_Scene.AssetService.Store(asset); MainConsole.Instance.DebugFormat("[AbuseCAPS]: texture new id {0}", assetID.ToString()); }
public virtual UUID Store (AssetBase asset) { // this should never happen but... if (asset != null) { if (m_doRemoteOnly) { object remoteValue = DoRemoteByURL ("AssetServerURI", asset); if (remoteValue != null) asset.ID = (UUID)remoteValue; else return UUID.Zero; } else asset.ID = m_database.Store (asset); if (doDatabaseCaching) { IImprovedAssetCache cache = m_registry.RequestModuleInterface<IImprovedAssetCache> (); if (cache != null && asset.Data.Length != 0) { cache.Expire (asset.ID.ToString ()); cache.Cache (asset.ID.ToString (), asset); } } return asset.ID; } MainConsole.Instance.Error ("[Asset service]: Trying to store a null asset!"); return UUID.Zero; }
/// <summary> /// Load an asset /// </summary> /// <param name="assetPath"> </param> /// <param name="data"></param> /// <returns>true if asset was successfully loaded, false otherwise</returns> bool LoadAsset (string assetPath, byte [] data) { //IRegionSerializer serializer = scene.RequestModuleInterface<IRegionSerializer>(); // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove (0, ArchiveConstants.ASSETS_PATH.Length); int i = filename.LastIndexOf (ArchiveConstants.ASSET_EXTENSION_SEPARATOR, StringComparison.Ordinal); if (i == -1) { MainConsole.Instance.ErrorFormat ( "[Inventory Archiver]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR); return false; } string extension = filename.Substring (i); string uuid = filename.Remove (filename.Length - extension.Length); UUID assetID = UUID.Parse (uuid); if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey (extension)) { AssetType assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE [extension]; if (assetType == AssetType.Unknown) MainConsole.Instance.WarnFormat ( "[Inventory Archiver]: Importing {0} byte asset {1} with unknown type", data.Length, uuid); else if (assetType == AssetType.Object) { string xmlData = Utils.BytesToString (data); ISceneEntity sceneObject = SceneEntitySerializer.SceneObjectSerializer.FromOriginalXmlFormat ( xmlData, m_registry); if (sceneObject != null) { if (m_creatorIdForAssetId.ContainsKey (assetID)) { foreach ( ISceneChildEntity sop in from sop in sceneObject.ChildrenEntities () where string.IsNullOrEmpty (sop.CreatorData) select sop) sop.CreatorID = m_creatorIdForAssetId [assetID]; } foreach (ISceneChildEntity sop in sceneObject.ChildrenEntities ()) { //Fix ownerIDs and perms sop.Inventory.ApplyGodPermissions ((uint)PermissionMask.All); sceneObject.ApplyPermissions ((uint)PermissionMask.All); foreach (TaskInventoryItem item in sop.Inventory.GetInventoryItems ()) item.OwnerID = m_userInfo.PrincipalID; sop.OwnerID = m_userInfo.PrincipalID; } data = Utils.StringToBytes ( SceneEntitySerializer.SceneObjectSerializer.ToOriginalXmlFormat (sceneObject)); } } //MainConsole.Instance.DebugFormat("[Inventory Archiver]: Importing asset {0}, type {1}", uuid, assetType); AssetBase asset = new AssetBase (assetID, "From IAR", assetType, m_overridecreator) { Data = data, Flags = AssetFlags.Normal }; if (m_assetData != null && ReplaceAssets) m_assetData.Delete (asset.ID, true); // check if this asset already exists in the database try { if (!m_assetService.GetExists (asset.ID.ToString ())) m_assetService.Store (asset); } catch { MainConsole.Instance.Error ( "[Inventory Archiver]: Error checking if asset exists. Possibly 'Path too long' for file based asset storage"); } asset.Dispose (); return true; } MainConsole.Instance.ErrorFormat ( "[Inventory Archiver]: Tried to dearchive data with path {0} with an unknown type extension {1}", assetPath, extension); return false; }
private void InsertAsset(AssetBase asset, UUID assetID) { int now = (int) Utils.DateTimeToUnixTime(DateTime.UtcNow); Dictionary<string, object> row = new Dictionary<string, object>(11); row["id"] = assetID; row["name"] = asset.Name; row["description"] = asset.Description; row["assetType"] = (sbyte) asset.TypeAsset; row["local"] = (asset.Flags & AssetFlags.Local) == AssetFlags.Local; row["temporary"] = (asset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary; row["create_time"] = now; row["access_time"] = now; row["asset_flags"] = (int) asset.Flags; row["creatorID"] = asset.CreatorID; row["data"] = asset.Data; m_Gd.Insert("assets", row); }
public void AddAsset(AssetBase asset) { if (asset != null && asset.Data != null) { if (asset.Type == (sbyte) AssetType.Texture) { texturesInCache++; // This could have been a pull stat, though there was originally a nebulous idea to measure flow rates textureCacheMemoryUsage += asset.Data.Length; } else { assetsInCache++; assetCacheMemoryUsage += asset.Data.Length; } } else assetServiceRequestFailures++; }
private static AssetBase LoadAssetFromDataRead(IDataRecord dr) { AssetBase asset = new AssetBase(dr["id"].ToString()) { Name = dr["name"].ToString(), Description = dr["description"].ToString() }; string Flags = dr["asset_flags"].ToString(); if (Flags != "") asset.Flags = (AssetFlags) int.Parse(Flags); string type = dr["assetType"].ToString(); asset.TypeAsset = (AssetType) int.Parse(type); UUID creator; if (UUID.TryParse(dr["creatorID"].ToString(), out creator)) asset.CreatorID = creator; try { object d = dr["data"]; if ((d != null) && (d.ToString() != "")) { asset.Data = (Byte[]) d; asset.MetaOnly = false; } else { asset.MetaOnly = true; asset.Data = new byte[0]; } } catch (Exception ex) { asset.MetaOnly = true; asset.Data = new byte[0]; if (MainConsole.Instance != null) MainConsole.Instance.Error("[Local Asset Database]: Failed to cast data for " + asset.ID + ", " + ex); } if (dr["local"].ToString().Equals("1") || dr["local"].ToString().Equals("true", StringComparison.InvariantCultureIgnoreCase)) asset.Flags |= AssetFlags.Local; string temp = dr["temporary"].ToString(); if (temp != "") { bool tempbool = false; int tempint = 0; if (bool.TryParse(temp, out tempbool)) { if (tempbool) asset.Flags |= AssetFlags.Temporary; } else if (int.TryParse(temp, out tempint)) { if (tempint == 1) asset.Flags |= AssetFlags.Temporary; } } return asset; }
public bool StoreAsset(AssetBase asset) { try { if (asset.Name.Length > 64) asset.Name = asset.Name.Substring(0, 64); if (asset.Description.Length > 128) asset.Description = asset.Description.Substring(0, 128); if (ExistsAsset(asset.ID)) { AssetBase oldAsset = GetAsset(asset.ID); if (oldAsset == null || (oldAsset.Flags & AssetFlags.Rewritable) == AssetFlags.Rewritable) { if (MainConsole.Instance != null) MainConsole.Instance.Debug( "[Local Asset Database]: Asset already exists in the db, overwriting - " + asset.ID); Delete(asset.ID, true); InsertAsset(asset, asset.ID); } else { if (MainConsole.Instance != null) MainConsole.Instance.Debug( "[Local Asset Database]: Asset already exists in the db, fixing ID... - " + asset.ID); InsertAsset(asset, UUID.Random()); } } else { InsertAsset(asset, asset.ID); } } catch (Exception e) { if (MainConsole.Instance != null) MainConsole.Instance.ErrorFormat( "[Local Asset Database]: Failure creating asset {0} with name \"{1}\". Error: {2}", asset.ID, asset.Name, e); } return true; }
public UUID Store(AssetBase asset) { StoreAsset(asset); return asset.ID; }
public bool FileSetAsset (AssetBase asset) { FileStream assetStream; try { string hash = asset.HashCode; bool duplicate = File.Exists (GetDataPathForID (hash)); byte[] data = asset.Data; asset.Data = new byte[0]; lock (_lock) { assetStream = File.OpenWrite (GetPathForID (asset.IDString)); asset.HashCode = hash; ProtoBuf.Serializer.Serialize (assetStream, asset); assetStream.SetLength (assetStream.Position); assetStream.Close (); asset.Data = data; //Deduplication... if (duplicate) { //Only set id --> asset, and not the hashcode --> data to de-duplicate return true; } File.WriteAllBytes (GetDataPathForID (hash), data); } return true; } catch { return false; } }
public bool BuyObject(IClientAPI remoteClient, UUID categoryID, uint localID, byte saleType) { ISceneChildEntity part = m_scene.GetSceneObjectPart(localID); if (part == null) return false; if (part.ParentEntity == null) return false; ISceneEntity group = part.ParentEntity; ILLClientInventory inventoryModule = m_scene.RequestModuleInterface<ILLClientInventory>(); switch (saleType) { case 1: // Sell as original (in-place sale) uint effectivePerms = group.GetEffectivePermissions(); if ((effectivePerms & (uint) PermissionMask.Transfer) == 0) { if (m_dialogModule != null) m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale"); return false; } group.SetOwnerId(remoteClient.AgentId); group.SetRootPartOwner(part, remoteClient.AgentId, remoteClient.ActiveGroupId); if (m_scene.Permissions.PropagatePermissions()) { foreach (ISceneChildEntity child in group.ChildrenEntities()) { child.Inventory.ChangeInventoryOwner(remoteClient.AgentId); child.TriggerScriptChangedEvent(Changed.OWNER); child.ApplyNextOwnerPermissions(); } } part.ObjectSaleType = 0; part.SalePrice = 10; group.HasGroupChanged = true; part.GetProperties(remoteClient); part.TriggerScriptChangedEvent(Changed.OWNER); group.ResumeScripts(); part.ScheduleUpdate(PrimUpdateFlags.ForcedFullUpdate); break; case 2: // Sell a copy Vector3 inventoryStoredPosition = new Vector3 (((group.AbsolutePosition.X > m_scene.RegionInfo.RegionSizeX) ? m_scene.RegionInfo.RegionSizeX - 1 : group.AbsolutePosition.X) , (group.AbsolutePosition.X > m_scene.RegionInfo.RegionSizeY) ? m_scene.RegionInfo.RegionSizeY - 1 : group.AbsolutePosition.X, group.AbsolutePosition.Z); Vector3 originalPosition = group.AbsolutePosition; group.AbsolutePosition = inventoryStoredPosition; string sceneObjectXml = SceneEntitySerializer.SceneObjectSerializer.ToOriginalXmlFormat(group); group.AbsolutePosition = originalPosition; uint perms = group.GetEffectivePermissions(); if ((perms & (uint) PermissionMask.Transfer) == 0) { if (m_dialogModule != null) m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale"); return false; } AssetBase asset = new AssetBase(UUID.Random(), part.Name, AssetType.Object, group.OwnerID) {Description = part.Description, Data = Utils.StringToBytes(sceneObjectXml)}; asset.ID = m_scene.AssetService.Store(asset); InventoryItemBase item = new InventoryItemBase { CreatorId = part.CreatorID.ToString(), CreatorData = part.CreatorData, ID = UUID.Random(), Owner = remoteClient.AgentId, AssetID = asset.ID, Description = asset.Description, Name = asset.Name, AssetType = asset.Type, InvType = (int) InventoryType.Object, Folder = categoryID }; uint nextPerms = (perms & 7) << 13; if ((nextPerms & (uint) PermissionMask.Copy) == 0) perms &= ~(uint) PermissionMask.Copy; if ((nextPerms & (uint) PermissionMask.Transfer) == 0) perms &= ~(uint) PermissionMask.Transfer; if ((nextPerms & (uint) PermissionMask.Modify) == 0) perms &= ~(uint) PermissionMask.Modify; item.BasePermissions = perms & part.NextOwnerMask; item.CurrentPermissions = perms & part.NextOwnerMask; item.NextPermissions = part.NextOwnerMask; item.EveryOnePermissions = part.EveryoneMask & part.NextOwnerMask; item.GroupPermissions = part.GroupMask & part.NextOwnerMask; item.CurrentPermissions |= 16; // Slam! item.CreationDate = Util.UnixTimeSinceEpoch(); m_scene.InventoryService.AddItemAsync(item, (itm) => remoteClient.SendInventoryItemCreateUpdate(itm, 0)); break; case 3: // Sell contents List<UUID> invList = part.Inventory.GetInventoryList(); bool okToSell = invList.Select(invID => part.Inventory.GetInventoryItem(invID)) .All(item1 => (item1.CurrentPermissions & (uint) PermissionMask.Transfer) != 0); if (!okToSell) { if (m_dialogModule != null) m_dialogModule.SendAlertToUser( remoteClient, "This item's inventory doesn't appear to be for sale"); return false; } if (invList.Count > 0) { if (inventoryModule != null) inventoryModule.MoveTaskInventoryItemsToUserInventory(remoteClient.AgentId, part.Name, part, invList); } break; } return true; }
public byte[] RenderMaterialsPostCap(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { MainConsole.Instance.Debug("[MaterialsDemoModule]: POST cap handler"); OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request); OSDMap resp = new OSDMap(); OSDMap materialsFromViewer = null; OSDArray respArr = new OSDArray(); if (req.ContainsKey("Zipped")) { OSD osd = null; byte[] inBytes = req["Zipped"].AsBinary(); try { osd = ZDecompressBytesToOsd(inBytes); if (osd != null) { if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries { foreach (OSD elem in (OSDArray)osd) { try { UUID id = new UUID(elem.AsBinary(), 0); AssetBase materialAsset = null; if (m_knownMaterials.ContainsKey(id)) { MainConsole.Instance.Info("[MaterialsDemoModule]: request for known material ID: " + id.ToString()); OSDMap matMap = new OSDMap(); matMap["ID"] = elem.AsBinary(); matMap["Material"] = m_knownMaterials[id]; respArr.Add(matMap); } else if ((materialAsset = m_scene.AssetService.Get(id.ToString())) != null) { MainConsole.Instance.Info("[MaterialsDemoModule]: request for stored material ID: " + id.ToString()); OSDMap matMap = new OSDMap(); matMap["ID"] = elem.AsBinary(); matMap["Material"] = (OSDMap)OSDParser.DeserializeJson( Encoding.UTF8.GetString(materialAsset.Data)); respArr.Add(matMap); } else MainConsole.Instance.Info("[MaterialsDemoModule]: request for UNKNOWN material ID: " + id.ToString()); } catch (Exception) { // report something here? continue; } } } else if (osd is OSDMap) // request to assign a material { materialsFromViewer = osd as OSDMap; if (materialsFromViewer.ContainsKey("FullMaterialsPerFace")) { OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"]; if (matsOsd is OSDArray) { OSDArray matsArr = matsOsd as OSDArray; try { foreach (OSDMap matsMap in matsArr) { MainConsole.Instance.Debug("[MaterialsDemoModule]: processing matsMap: " + OSDParser.SerializeJsonString(matsMap)); uint matLocalID = 0; try { matLocalID = matsMap["ID"].AsUInteger(); } catch (Exception e) { MainConsole.Instance.Warn("[MaterialsDemoModule]: cannot decode \"ID\" from matsMap: " + e.Message); } MainConsole.Instance.Debug("[MaterialsDemoModule]: matLocalId: " + matLocalID.ToString()); OSDMap mat = null; try { mat = matsMap["Material"] as OSDMap; } catch (Exception e) { MainConsole.Instance.Warn("[MaterialsDemoModule]: cannot decode \"Material\" from matsMap: " + e.Message); } MainConsole.Instance.Debug("[MaterialsDemoModule]: mat: " + OSDParser.SerializeJsonString(mat)); UUID id = HashOsd(mat); m_knownMaterials[id] = mat; var sop = m_scene.GetSceneObjectPart(matLocalID); if (sop == null) MainConsole.Instance.Debug("[MaterialsDemoModule]: null SOP for localId: " + matLocalID.ToString()); else { var te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length); if (te == null) { MainConsole.Instance.Debug("[MaterialsDemoModule]: null TextureEntry for localId: " + matLocalID.ToString()); } else { int face = -1; if (matsMap.ContainsKey("Face")) { face = matsMap["Face"].AsInteger(); if (te.FaceTextures == null) // && face == 0) { if (te.DefaultTexture == null) MainConsole.Instance.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; } MainConsole.Instance.Debug("[MaterialsDemoModule]: setting material ID for face " + face.ToString() + " to " + id.ToString()); //we cant use sop.UpdateTextureEntry(te); because it filters so do it manually if (sop.ParentEntity != null) { sop.Shape.TextureEntry = te.GetBytes(); sop.TriggerScriptChangedEvent(Changed.TEXTURE); sop.ParentEntity.HasGroupChanged = true; sop.ScheduleUpdate(PrimUpdateFlags.FullUpdate); AssetBase asset = new AssetBase(id, "RenderMaterial", AssetType.Texture, sop.OwnerID) { Data = Encoding.UTF8.GetBytes( OSDParser.SerializeJsonString(mat)) }; m_scene.AssetService.Store(asset); StoreMaterialsForPart(sop); } } } } } catch (Exception e) { MainConsole.Instance.Warn("[MaterialsDemoModule]: exception processing received material: " + e.ToString()); } } } } } } catch (Exception e) { MainConsole.Instance.Warn("[MaterialsDemoModule]: exception decoding zipped CAP payload: " + e.ToString()); } MainConsole.Instance.Debug("[MaterialsDemoModule]: knownMaterials.Count: " + m_knownMaterials.Count.ToString()); } resp["Zipped"] = ZCompressOSD(respArr, false); string response = OSDParser.SerializeLLSDXmlString(resp); //MainConsole.Instance.Debug("[MaterialsDemoModule]: cap request: " + request); MainConsole.Instance.Debug("[MaterialsDemoModule]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); MainConsole.Instance.Debug("[MaterialsDemoModule]: cap response: " + response); return OSDParser.SerializeLLSDBinary(resp); }
//////////////////////////////////////////////////////////// // IImprovedAssetCache // public void Cache(string assetID, AssetBase asset) { if (asset != null) m_Cache.AddOrUpdate(asset.IDString, asset); }
/// <summary> /// Resolve a new piece of asset data against stored metadata /// </summary> /// <param name="assetPath"></param> /// <param name="data"></param> protected void ResolveAssetData(string assetPath, byte[] data) { // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); if (m_metadata.ContainsKey(filename)) { AssetMetadata metadata = m_metadata[filename]; if (ArchiveConstants.ASSET_TYPE_TO_EXTENSION.ContainsKey(metadata.AssetType)) { string extension = ArchiveConstants.ASSET_TYPE_TO_EXTENSION[metadata.AssetType]; filename = filename.Remove(filename.Length - extension.Length); } MainConsole.Instance.DebugFormat("[Archiver]: Importing asset {0}", filename); AssetBase asset = new AssetBase(filename, metadata.Name, (AssetType) metadata.AssetType, UUID.Zero) {Description = metadata.Description, Data = data, MetaOnly = false}; asset.ID = m_cache.Store(asset); } else { MainConsole.Instance.ErrorFormat( "[De-Archiver]: Tried to de-archive data with filename {0} without any corresponding metadata", assetPath); } }
/// <summary> /// Create a new asset data structure. /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <param name="assetType"></param> /// <param name="data"></param> /// <param name="creatorID"></param> /// <returns></returns> AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, string creatorID) { AssetBase asset = new AssetBase(UUID.Random(), name, (AssetType) assetType, UUID.Parse(creatorID)) {Description = description, Data = data ?? new byte[1]}; return asset; }
/// <summary> /// Update what the avatar is wearing using an item from their inventory. /// </summary> /// <param name="client"></param> /// <param name="e"></param> public void AvatarIsWearing (IClientAPI client, AvatarWearingArgs e) { IScenePresence sp = m_scene.GetScenePresence (client.AgentId); if (sp == null) { MainConsole.Instance.WarnFormat ("[AvatarFactory]: AvatarIsWearing unable to find presence for {0}", client.AgentId); return; } MainConsole.Instance.DebugFormat ("[AvatarFactory]: AvatarIsWearing called for {0}", client.AgentId); // operate on a copy of the appearance so we don't have to lock anything IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule> (); AvatarAppearance avatAppearance = new AvatarAppearance (appearance.Appearance, false); #region Teen Mode Stuff IOpenRegionSettingsModule module = m_scene.RequestModuleInterface<IOpenRegionSettingsModule> (); bool NeedsRebake = false; if (module != null && module.EnableTeenMode) { foreach (AvatarWearingArgs.Wearable wear in e.NowWearing) { if (wear.Type == 10 & wear.ItemID == UUID.Zero && module.DefaultUnderpants != UUID.Zero) { NeedsRebake = true; wear.ItemID = module.DefaultUnderpants; InventoryItemBase item = new InventoryItemBase (UUID.Random ()) { InvType = (int)InventoryType.Wearable, AssetType = (int)AssetType.Clothing, Name = "Default Underpants", Folder = m_scene.InventoryService.GetFolderForType (client.AgentId, InventoryType.Wearable, FolderType.Clothing).ID, Owner = client.AgentId, CurrentPermissions = 0, CreatorId = UUID.Zero.ToString (), AssetID = module.DefaultUnderpants }; //Locked client.SendInventoryItemCreateUpdate (item, 0); } else if (wear.Type == 10 & wear.ItemID == UUID.Zero) { NeedsRebake = true; InventoryItemBase item = new InventoryItemBase (UUID.Random ()) { InvType = (int)InventoryType.Wearable, AssetType = (int)AssetType.Clothing, Name = "Default Underpants", Folder = m_scene.InventoryService.GetFolderForType (client.AgentId, InventoryType.Wearable, FolderType.Clothing).ID, Owner = client.AgentId, CurrentPermissions = 0 }; //Locked if (m_underPantsUUID == UUID.Zero) { m_underPantsUUID = UUID.Random (); AssetBase asset = new AssetBase (m_underPantsUUID, "Default Underpants", AssetType.Clothing, UUID.Zero) { Data = Utils.StringToBytes (m_defaultUnderPants) }; asset.ID = m_scene.AssetService.Store (asset); m_underPantsUUID = asset.ID; } item.CreatorId = UUID.Zero.ToString (); item.AssetID = m_underPantsUUID; m_scene.InventoryService.AddItemAsync (item, null); client.SendInventoryItemCreateUpdate (item, 0); wear.ItemID = item.ID; } if (wear.Type == 11 && wear.ItemID == UUID.Zero && module.DefaultUndershirt != UUID.Zero) { NeedsRebake = true; wear.ItemID = module.DefaultUndershirt; InventoryItemBase item = new InventoryItemBase (UUID.Random ()) { InvType = (int)InventoryType.Wearable, AssetType = (int)AssetType.Clothing, Name = "Default Undershirt", Folder = m_scene.InventoryService.GetFolderForType (client.AgentId, InventoryType.Wearable, FolderType.Clothing).ID, Owner = client.AgentId, CurrentPermissions = 0, CreatorId = UUID.Zero.ToString (), AssetID = module.DefaultUndershirt }; //Locked client.SendInventoryItemCreateUpdate (item, 0); } else if (wear.Type == 11 & wear.ItemID == UUID.Zero) { NeedsRebake = true; InventoryItemBase item = new InventoryItemBase (UUID.Random ()) { InvType = (int)InventoryType.Wearable, AssetType = (int)AssetType.Clothing, Name = "Default Undershirt", Folder = m_scene.InventoryService.GetFolderForType (client.AgentId, InventoryType.Wearable, FolderType.Clothing).ID, Owner = client.AgentId, CurrentPermissions = 0 }; //Locked if (m_underShirtUUID == UUID.Zero) { m_underShirtUUID = UUID.Random (); AssetBase asset = new AssetBase (m_underShirtUUID, "Default Undershirt", AssetType.Clothing, UUID.Zero) { Data = Utils.StringToBytes (m_defaultUnderShirt) }; asset.ID = m_scene.AssetService.Store (asset); m_underShirtUUID = asset.ID; } item.CreatorId = UUID.Zero.ToString (); item.AssetID = m_underShirtUUID; m_scene.InventoryService.AddItemAsync (item, null); client.SendInventoryItemCreateUpdate (item, 0); wear.ItemID = item.ID; } } } #endregion foreach ( AvatarWearingArgs.Wearable wear in e.NowWearing.Where (wear => wear.Type < AvatarWearable.MAX_WEARABLES)) { avatAppearance.Wearables [wear.Type].Add (wear.ItemID, UUID.Zero); } avatAppearance.GetAssetsFrom (appearance.Appearance); // This could take awhile since it needs to pull inventory SetAppearanceAssets (sp.UUID, e.NowWearing, appearance.Appearance, ref avatAppearance); // could get fancier with the locks here, but in the spirit of "last write wins" // this should work correctly, also, we don't need to send the appearance here // since the "iswearing" will trigger a new set of visual param and baked texture changes // when those complete, the new appearance will be sent appearance.Appearance = avatAppearance; //This only occurs if something has been forced on afterwards (teen mode stuff) if (NeedsRebake) { //Tell the client about the new things it is wearing sp.ControllingClient.SendWearables (appearance.Appearance.Wearables, appearance.Appearance.Serial); //Then forcefully tell it to rebake foreach ( Primitive.TextureEntryFace face in appearance.Appearance.Texture.FaceTextures.Select (t => (t)).Where (face => face != null)) { sp.ControllingClient.SendRebakeAvatarTextures (face.TextureID); } } QueueAppearanceSave (sp.UUID); //Send the wearables HERE so that the client knows what it is wearing //sp.ControllingClient.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial); //Do not save or send the appearance! The client loops back and sends a bunch of SetAppearance // (handled above) and that takes care of it }
/// <summary> /// Cache asset. /// </summary> /// <param name="assetID"></param> /// <param name="asset"> /// The asset that is being cached. /// </param> public void Cache(string assetID, AssetBase asset) { if (asset != null) { // MainConsole.Instance.DebugFormat("[CENOME ASSET CACHE]: Caching asset {0}", asset.IDString); long size = asset.Data != null ? asset.Data.Length : 1; m_cache.Set(asset.IDString, asset, size); m_cachedCount++; } }
// This needs ThreatLevel high. It is an excellent griefer tool, // In a loop, it can cause asset bloat and DOS levels of asset // writes. // public void osMakeNotecard(string notecardName, LSL_List contents) { if (!ScriptProtection.CheckThreatLevel(ThreatLevel.High, "osMakeNotecard", m_host, "OSSL", m_itemID)) return; // Create new asset AssetBase asset = new AssetBase(UUID.Random(), notecardName, AssetType.Notecard, m_host.OwnerID) { Description = "Script Generated Notecard" }; string notecardData = String.Empty; for (int i = 0; i < contents.Length; i++) { notecardData += contents.GetLSLStringItem(i) + "\n"; } int textLength = notecardData.Length; notecardData = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length " + textLength.ToString(CultureInfo.InvariantCulture) + "\n" + notecardData + "}\n"; asset.Data = Util.UTF8.GetBytes(notecardData); asset.ID = World.AssetService.Store(asset); // Create Task Entry TaskInventoryItem taskItem = new TaskInventoryItem(); taskItem.ResetIDs(m_host.UUID); taskItem.ParentID = m_host.UUID; taskItem.CreationDate = (uint) Util.UnixTimeSinceEpoch(); taskItem.Name = asset.Name; taskItem.Description = asset.Description; taskItem.Type = (int) AssetType.Notecard; taskItem.InvType = (int) InventoryType.Notecard; taskItem.OwnerID = m_host.OwnerID; taskItem.CreatorID = m_host.OwnerID; taskItem.BasePermissions = (uint) PermissionMask.All; taskItem.CurrentPermissions = (uint) PermissionMask.All; taskItem.EveryonePermissions = 0; taskItem.NextPermissions = (uint) PermissionMask.All; taskItem.GroupID = m_host.GroupID; taskItem.GroupPermissions = 0; taskItem.Flags = 0; taskItem.SalePrice = 0; taskItem.SaleType = 0; taskItem.PermsGranter = UUID.Zero; taskItem.PermsMask = 0; taskItem.AssetID = asset.ID; m_host.Inventory.AddInventoryItem(taskItem, false); }
public AvatarAppearance BakeAppearance(UUID agentID, int cof_version) { AvatarAppearance appearance = m_avatarService.GetAppearance(agentID); List<BakeType> pendingBakes = new List<BakeType>(); InventoryFolderBase cof = m_inventoryService.GetFolderForType(agentID, InventoryType.Unknown, AssetType.CurrentOutfitFolder); if (cof.Version < cof_version) { int i = 0; while (i < 10) { cof = m_inventoryService.GetFolderForType(agentID, InventoryType.Unknown, AssetType.CurrentOutfitFolder); System.Threading.Thread.Sleep(100); if (cof.Version >= cof_version) break; i++; } } List<InventoryItemBase> items = m_inventoryService.GetFolderItems(agentID, cof.ID); foreach (InventoryItemBase itm in items) MainConsole.Instance.Warn("[Server Side Appearance]: Baking " + itm.Name); for (int i = 0; i < Textures.Length; i++) Textures[i] = new TextureData(); WearableData alphaWearable = null; List<UUID> currentItemIDs = new List<UUID>(); foreach (InventoryItemBase itm in items) { if (itm.AssetType == (int)AssetType.Link) { UUID assetID = m_inventoryService.GetItemAssetID(agentID, itm.AssetID); if (appearance.Wearables.Any((w) => w.GetItem(assetID) != UUID.Zero)) { currentItemIDs.Add(assetID); WearableData wearable = new WearableData(); AssetBase asset = m_assetService.Get(assetID.ToString()); if (asset != null && asset.TypeAsset != AssetType.Object) { wearable.Asset = new AssetClothing(assetID, asset.Data); if (wearable.Asset.Decode()) { wearable.AssetID = assetID; wearable.AssetType = wearable.Asset.AssetType; wearable.WearableType = wearable.Asset.WearableType; wearable.ItemID = itm.AssetID; if (wearable.WearableType == WearableType.Alpha) { alphaWearable = wearable; continue; } AppearanceManager.DecodeWearableParams(wearable, ref Textures); } } } else { } } } for (int i = 0; i < Textures.Length; i++) { AssetBase asset = m_assetService.Get(Textures[i].TextureID.ToString()); if (asset != null) { Textures[i].Texture = new AssetTexture(Textures[i].TextureID, asset.Data); Textures[i].Texture.Decode(); } } for (int bakedIndex = 0; bakedIndex < AppearanceManager.BAKED_TEXTURE_COUNT; bakedIndex++) { AvatarTextureIndex textureIndex = AppearanceManager.BakeTypeToAgentTextureIndex((BakeType)bakedIndex); if (Textures[(int)textureIndex].TextureID == UUID.Zero) { // If this is the skirt layer and we're not wearing a skirt then skip it if (bakedIndex == (int)BakeType.Skirt && appearance.Wearables[(int)WearableType.Skirt].Count == 0) continue; pendingBakes.Add((BakeType)bakedIndex); } } int start = Environment.TickCount; List<UUID> newBakeIDs = new List<UUID>(); foreach (BakeType bakeType in pendingBakes) { UUID assetID = UUID.Zero; List<AvatarTextureIndex> textureIndices = OpenMetaverse.AppearanceManager.BakeTypeToTextures(bakeType); Baker oven = new Baker(bakeType); for (int i = 0; i < textureIndices.Count; i++) { int textureIndex = (int)textureIndices[i]; TextureData texture = Textures[(int)textureIndex]; texture.TextureIndex = (AvatarTextureIndex)textureIndex; if (alphaWearable != null) { if (alphaWearable.Asset.Textures.ContainsKey(texture.TextureIndex) && alphaWearable.Asset.Textures[texture.TextureIndex] != UUID.Parse("5748decc-f629-461c-9a36-a35a221fe21f")) { assetID = alphaWearable.Asset.Textures[texture.TextureIndex]; goto bake_complete; } } oven.AddTexture(texture); } oven.Bake(); byte[] assetData = oven.BakedTexture.AssetData; AssetBase newBakedAsset = new AssetBase(UUID.Random()); newBakedAsset.Data = assetData; newBakedAsset.TypeAsset = AssetType.Texture; newBakedAsset.Name = "ServerSideAppearance Texture"; newBakedAsset.Flags = AssetFlags.Deletable | AssetFlags.Collectable | AssetFlags.Rewritable | AssetFlags.Temporary; if (appearance.Texture.FaceTextures[(int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType)].TextureID != UUID.Zero) m_assetService.Delete(appearance.Texture.FaceTextures[(int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType)].TextureID); assetID = m_assetService.Store(newBakedAsset); bake_complete: newBakeIDs.Add(assetID); MainConsole.Instance.WarnFormat("[Server Side Appearance]: Baked {0}", assetID); int place = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType); appearance.Texture.FaceTextures[place].TextureID = assetID; } MainConsole.Instance.ErrorFormat("[Server Side Appearance]: Baking took {0} ms", (Environment.TickCount - start)); appearance.Serial = cof_version + 1; cof = m_inventoryService.GetFolderForType(agentID, InventoryType.Unknown, AssetType.CurrentOutfitFolder); if (cof.Version > cof_version) { //it changed during the baking return null; } m_avatarService.SetAppearance(agentID, appearance); return appearance; }
public virtual UUID SaveAsAsset(List<ISceneEntity> objectGroups, out AssetBase asset) { Vector3 GroupMiddle = Vector3.Zero; string AssetXML = "<groups>"; if (objectGroups.Count == 1) { m_scene.UniverseEventManager.FireGenericEventHandler("DeleteToInventory", objectGroups[0]); AssetXML = objectGroups[0].ToXml2(); } else { foreach (ISceneEntity objectGroup in objectGroups) { Vector3 inventoryStoredPosition = new Vector3 (((objectGroup.AbsolutePosition.X > m_scene.RegionInfo.RegionSizeX) ? m_scene.RegionInfo.RegionSizeX - 1 : objectGroup.AbsolutePosition.X) , (objectGroup.AbsolutePosition.Y > m_scene.RegionInfo.RegionSizeY) ? m_scene.RegionInfo.RegionSizeY - 1 : objectGroup.AbsolutePosition.Y, objectGroup.AbsolutePosition.Z); GroupMiddle += inventoryStoredPosition; Vector3 originalPosition = objectGroup.AbsolutePosition; objectGroup.AbsolutePosition = inventoryStoredPosition; m_scene.UniverseEventManager.FireGenericEventHandler("DeleteToInventory", objectGroup); AssetXML += objectGroup.ToXml2(); objectGroup.AbsolutePosition = originalPosition; } GroupMiddle.X /= objectGroups.Count; GroupMiddle.Y /= objectGroups.Count; GroupMiddle.Z /= objectGroups.Count; AssetXML += "<middle>"; AssetXML += "<mid>" + GroupMiddle.ToRawString() + "</mid>"; AssetXML += "</middle>"; AssetXML += "</groups>"; } asset = CreateAsset( objectGroups[0].Name, objectGroups[0].RootChild.Description, (sbyte) AssetType.Object, Utils.StringToBytes(AssetXML), objectGroups[0].OwnerID.ToString()); asset.ID = m_scene.AssetService.Store(asset); return asset.ID; }
/// <summary> /// Called once new texture data has been received for this updater. /// </summary> public void DataReceived(byte[] data, IScene scene) { ISceneChildEntity part = scene.GetSceneObjectPart(PrimID); if (part == null || data == null || data.Length <= 1) { string msg = String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url); IChatModule chatModule = scene.RequestModuleInterface<IChatModule>(); if (chatModule != null) chatModule.SimChat(msg, ChatTypeEnum.Say, 0, part.ParentEntity.AbsolutePosition, part.Name, part.UUID, false, scene); return; } byte[] assetData = null; AssetBase oldAsset = null; if (BlendWithOldTexture) { Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture; if (defaultFace != null) { oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString()); if (oldAsset != null) assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha, scene); } } if (assetData == null) { assetData = new byte[data.Length]; Array.Copy(data, assetData, data.Length); } AssetBase asset = null; if (LastAssetID != UUID.Zero) { asset = scene.AssetService.Get(LastAssetID.ToString()); asset.Description = String.Format("URL image : {0}", Url); asset.Data = assetData; if ((asset.Flags & AssetFlags.Local) == AssetFlags.Local) { asset.Flags = asset.Flags & ~AssetFlags.Local; } if (((asset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary) != ((Disp & DISP_TEMP) != 0)) { if ((Disp & DISP_TEMP) != 0) asset.Flags |= AssetFlags.Temporary; else asset.Flags = asset.Flags & ~AssetFlags.Temporary; } asset.ID = scene.AssetService.Store(asset); } else { // Create a new asset for user asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), AssetType.Texture, scene.RegionInfo.RegionID) {Data = assetData, Description = String.Format("URL image : {0}", Url)}; if ((Disp & DISP_TEMP) != 0) asset.Flags = AssetFlags.Temporary; asset.ID = scene.AssetService.Store(asset); } IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>(); if (cacheLayerDecode != null) { cacheLayerDecode.Decode(asset.ID, asset.Data); cacheLayerDecode = null; LastAssetID = asset.ID; } UUID oldID = UUID.Zero; lock (part) { // mostly keep the values from before Primitive.TextureEntry tmptex = part.Shape.Textures; // remove the old asset from the cache oldID = tmptex.DefaultTexture.TextureID; if (Face == ALL_SIDES) { tmptex.DefaultTexture.TextureID = asset.ID; } else { try { Primitive.TextureEntryFace texface = tmptex.CreateFace((uint) Face); texface.TextureID = asset.ID; tmptex.FaceTextures[Face] = texface; } catch (Exception) { tmptex.DefaultTexture.TextureID = asset.ID; } } // I'm pretty sure we always want to force this to true // I'm pretty sure noone whats to set fullbright true if it wasn't true before. part.UpdateTexture(tmptex, true); } if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0)) { if (oldAsset == null) oldAsset = scene.AssetService.Get(oldID.ToString()); if (oldAsset != null) { if ((oldAsset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary) { scene.AssetService.Delete(oldID); } } } }
void SaveFileCacheForAsset(UUID assetId, OpenJPEG.J2KLayerInfo[] layers) { if (m_useCache) m_decodedCache.AddOrUpdate(assetId, layers, TimeSpan.FromMinutes(10)); if (m_cache != null) { string assetID = "j2kCache_" + assetId; AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, AssetType.Notecard, UUID.Zero) {Flags = AssetFlags.Local | AssetFlags.Temporary}; #region Serialize Layer Data StringBuilder stringResult = new StringBuilder(); string strEnd = "\n"; for (int i = 0; i < layers.Length; i++) { if (i == layers.Length - 1) strEnd = string.Empty; stringResult.AppendFormat("{0}|{1}|{2}{3}", layers[i].Start, layers[i].End, layers[i].End - layers[i].Start, strEnd); } layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString()); #endregion Serialize Layer Data m_cache.Cache(assetID, layerDecodeAsset); } }
/// <summary> /// AssetXferUploader constructor /// </summary> /// <param name='transactions'></param> /// <param name='scene'></param> /// <param name='transactionID'></param> /// <param name='dumpAssetToFile'> /// If true then when the asset is uploaded it is dumped to a file with the format /// String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat", /// now.Year, now.Month, now.Day, now.Hour, now.Minute, /// now.Second, m_asset.Name, m_asset.Type); /// for debugging purposes. /// </param> public AssetXferUploader( AgentAssetTransactions transactions, IScene scene, UUID transactionID, bool dumpAssetToFile) { m_asset = new AssetBase(); m_transactions = transactions; m_transactionID = transactionID; m_Scene = scene; m_dumpAssetToFile = dumpAssetToFile; }