Exemplo n.º 1
0
        /// <summary>
        /// Get an asset id given an item name and an item type.
        /// </summary>
        /// <returns>UUID.Zero if the name and type did not match any item.</returns>
        /// <param name='part'></param>
        /// <param name='name'></param>
        /// <param name='type'></param>
        public static UUID GetAssetIdFromItemName(SceneObjectPart part, string name, int type)
        {
            TaskInventoryItem item = part.Inventory.GetInventoryItem(name);

            if (item != null && item.Type == type)
                return item.AssetID;
            else
                return UUID.Zero;
        }
Exemplo n.º 2
0
 public void Enqueue(SceneObjectPart part)
 {
     lock (m_syncObject)
     {
         if (!m_ids.ContainsKey(part.UUID)) {
             m_ids.Add(part.UUID, true);
             m_queue.Enqueue(part);
         }
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// accepts a valid UUID, -or- a name of an inventory item.
        /// Returns a valid UUID or UUID.Zero if key invalid and item not found
        /// in prim inventory.
        /// </summary>
        /// <param name="part">Scene object part to search for inventory item</param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static UUID GetAssetIdFromKeyOrItemName(SceneObjectPart part, string identifier)
        {
            UUID key;

            // if we can parse the string as a key, use it.
            // else try to locate the name in inventory of object. found returns key,
            // not found returns UUID.Zero
            if (!UUID.TryParse(identifier, out key))
            {
                TaskInventoryItem item = part.Inventory.GetInventoryItem(identifier);

                if (item != null)
                    key = item.AssetID;
                else
                    key = UUID.Zero;
            }

            return key;
        }
Exemplo n.º 4
0
 /// <summary>
 /// Add a simple script to the given part.
 /// </summary>
 /// <remarks>
 /// TODO: Accept input for item and asset IDs to avoid mysterious script failures that try to use any of these
 /// functions more than once in a test.
 /// </remarks>
 /// <param name="scene"></param>
 /// <param name="part"></param>
 /// <returns>The item that was added</returns>
 public static TaskInventoryItem AddScript(Scene scene, SceneObjectPart part)
 {
     return(AddScript(scene, part, "scriptItem", "default { state_entry() { llSay(0, \"Hello World\"); } }"));
 }
Exemplo n.º 5
0
            /// <summary>
            /// Called once new texture data has been received for this updater.
            /// </summary>
            /// <param name="data"></param>
            /// <param name="scene"></param>
            /// <param name="isReuseable">True if the data given is reuseable.</param>
            /// <returns>The asset UUID given to the incoming data.</returns>
            public UUID DataReceived(byte[] data, Scene scene)
            {
                // this are local assets and will not work without cache
                IAssetCache iac = scene.RequestModuleInterface <IAssetCache>();

                if (iac == null)
                {
                    return(UUID.Zero);
                }

                SceneObjectPart part = scene.GetSceneObjectPart(PrimID);

                if (part == null || data == null || data.Length <= 1)
                {
                    string msg = string.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
                    scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
                                  0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);

                    return(UUID.Zero);
                }

                byte[]    assetData = null;
                AssetBase oldAsset  = null;

                if (BlendWithOldTexture)
                {
                    Primitive.TextureEntryFace curFace;
                    if (Face == ALL_SIDES)
                    {
                        curFace = part.Shape.Textures.DefaultTexture;
                    }
                    else
                    {
                        try
                        {
                            curFace = part.Shape.Textures.GetFace((uint)Face);
                        }
                        catch
                        {
                            curFace = null;
                        }
                    }
                    if (curFace != null)
                    {
                        oldAsset = scene.AssetService.Get(curFace.TextureID.ToString());

                        if (oldAsset != null)
                        {
                            assetData = BlendTextures(data, oldAsset.Data, FrontAlpha);
                        }
                    }
                }
                else if (FrontAlpha < 255)
                {
                    assetData = BlendTextures(data, null, FrontAlpha);
                }


                if (assetData == null)
                {
                    assetData = new byte[data.Length];
                    Array.Copy(data, assetData, data.Length);
                }

                // Create a new asset for user
                AssetBase asset = new AssetBase(
                    UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
                    part.OwnerID.ToString());

                asset.Data        = assetData;
                asset.Description = string.Format("URL image : {0}", Url);
                if (asset.Description.Length > 128)
                {
                    asset.Description = asset.Description.Substring(0, 128);
                }
                asset.Local     = true; // dynamic images aren't saved in the assets server
                asset.Temporary = ((Disp & DISP_TEMP) != 0);

                iac.Cache(asset);

                UUID oldID = UpdatePart(part, asset.FullID);

                if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
                {
                    if (oldAsset == null)
                    {
                        oldAsset = scene.AssetService.Get(oldID.ToString());
                    }

                    if (oldAsset != null)
                    {
                        if (oldAsset.Temporary)
                        {
                            iac.Expire(oldID.ToString());
                        }
                    }
                }

                return(asset.FullID);
            }
 private void GenericByte(SceneObjectPart obj, XmlTextReader reader, string name, Type SOPType)
 {
     SOPType.GetProperty(name)
            .SetValue(obj, byte.Parse(reader.ReadElementContentAsString(name, String.Empty)), null);
 }
 private void ProcessParticleSystem(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.ParticleSystem =
         Convert.FromBase64String(reader.ReadElementContentAsString("ParticleSystem", String.Empty));
 }
 private void ProcessCollisionSound(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.CollisionSound = ReadUUID(reader, "CollisionSound");
 }
 private void ProcessGroupID(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.GroupID = ReadUUID(reader, "GroupID");
 }
 private void ProcessCategory(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.Category = uint.Parse(reader.ReadElementContentAsString("Category", String.Empty));
 }
Exemplo n.º 11
0
        public void TestSaveOar()
        {
            TestHelper.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            SceneObjectPart  part1 = CreateSceneObjectPart1();
            SceneObjectGroup sog1  = new SceneObjectGroup(part1);

            m_scene.AddNewSceneObject(sog1, false);

            SceneObjectPart part2 = CreateSceneObjectPart2();

            AssetNotecard nc = new AssetNotecard();

            nc.BodyText = "Hello World!";
            nc.Encode();
            UUID      ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
            UUID      ncItemUuid  = new UUID("00000000-0000-0000-1100-000000000000");
            AssetBase ncAsset
                = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);

            m_scene.AssetService.Store(ncAsset);
            SceneObjectGroup  sog2 = new SceneObjectGroup(part2);
            TaskInventoryItem ncItem
                = new TaskInventoryItem {
                Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid
                };

            part2.Inventory.AddInventoryItem(ncItem, true);

            m_scene.AddNewSceneObject(sog2, false);

            MemoryStream archiveWriteStream = new MemoryStream();

            m_scene.EventManager.OnOarFileSaved += SaveCompleted;

            Guid requestId = new Guid("00000000-0000-0000-0000-808080808080");

            lock (this)
            {
                m_archiverModule.ArchiveRegion(archiveWriteStream, requestId);
                //AssetServerBase assetServer = (AssetServerBase)scene.CommsManager.AssetCache.AssetServer;
                //while (assetServer.HasWaitingRequests())
                //    assetServer.ProcessNextRequest();

                Monitor.Wait(this, 60000);
            }

            Assert.That(m_lastRequestId, Is.EqualTo(requestId));

            byte[]           archive           = archiveWriteStream.ToArray();
            MemoryStream     archiveReadStream = new MemoryStream(archive);
            TarArchiveReader tar = new TarArchiveReader(archiveReadStream);

            bool gotNcAssetFile = false;

            string expectedNcAssetFileName = string.Format("{0}_{1}", ncAssetUuid, "notecard.txt");

            List <string> foundPaths    = new List <string>();
            List <string> expectedPaths = new List <string>();

            expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1));
            expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2));

            string filePath;

            TarArchiveReader.TarEntryType tarEntryType;

            byte[] data = tar.ReadEntry(out filePath, out tarEntryType);
            Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH));

            ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, false, false, Guid.Empty);

            arr.LoadControlFile(filePath, data);

            Assert.That(arr.ControlFileLoaded, Is.True);

            while (tar.ReadEntry(out filePath, out tarEntryType) != null)
            {
                if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
                {
                    string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);

                    Assert.That(fileName, Is.EqualTo(expectedNcAssetFileName));
                    gotNcAssetFile = true;
                }
                else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
                {
                    foundPaths.Add(filePath);
                }
            }

            Assert.That(gotNcAssetFile, Is.True, "No notecard asset file in archive");
            Assert.That(foundPaths, Is.EquivalentTo(expectedPaths));

            // TODO: Test presence of more files and contents of files.
        }
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="part">
 ///     A <see cref="SceneObjectPart" />
 /// </param>
 public SceneObjectPartInventory(SceneObjectPart part)
 {
     m_part = part;
 }
Exemplo n.º 13
0
 public SOPObjectMaterial(int m_face, SceneObjectPart m_parent)
 {
     this.m_face   = m_face;
     this.m_parent = m_parent;
 }
Exemplo n.º 14
0
        public void Say(string msg)
        {
            SceneObjectPart sop = GetSOP();

            m_rootScene.SimChat(msg, ChatTypeEnum.Say, sop.AbsolutePosition, sop.Name, sop.UUID, false);
        }
Exemplo n.º 15
0
        public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap)
        {
            Hashtable responsedata = new Hashtable();

            responsedata["int_response_code"]   = 400; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = "Request wasn't what was expected";
            ScenePresence avatar;

            if (!m_scene.TryGetAvatar(AgentId, out avatar))
            {
                return(responsedata);
            }


            OSD r = OSDParser.DeserializeLLSDXml((string)request["requestbody"]);
            //UUID session_id = UUID.Zero;
            bool       bypass_raycast          = false;
            uint       everyone_mask           = 0;
            uint       group_mask              = 0;
            uint       next_owner_mask         = 0;
            uint       flags                   = 0;
            UUID       group_id                = UUID.Zero;
            int        hollow                  = 0;
            int        material                = 0;
            int        p_code                  = 0;
            int        path_begin              = 0;
            int        path_curve              = 0;
            int        path_end                = 0;
            int        path_radius_offset      = 0;
            int        path_revolutions        = 0;
            int        path_scale_x            = 0;
            int        path_scale_y            = 0;
            int        path_shear_x            = 0;
            int        path_shear_y            = 0;
            int        path_skew               = 0;
            int        path_taper_x            = 0;
            int        path_taper_y            = 0;
            int        path_twist              = 0;
            int        path_twist_begin        = 0;
            int        profile_begin           = 0;
            int        profile_curve           = 0;
            int        profile_end             = 0;
            Vector3    ray_end                 = Vector3.Zero;
            bool       ray_end_is_intersection = false;
            Vector3    ray_start               = Vector3.Zero;
            UUID       ray_target_id           = UUID.Zero;
            Quaternion rotation                = Quaternion.Identity;
            Vector3    scale                   = Vector3.Zero;
            int        state                   = 0;

            if (r.Type != OSDType.Map) // not a proper req
            {
                return(responsedata);
            }

            OSDMap rm = (OSDMap)r;

            if (rm.ContainsKey("ObjectData")) //v2
            {
                if (rm["ObjectData"].Type != OSDType.Map)
                {
                    responsedata["str_response_string"] = "Has ObjectData key, but data not in expected format";
                    return(responsedata);
                }

                OSDMap ObjMap = (OSDMap)rm["ObjectData"];

                bypass_raycast  = ObjMap["BypassRaycast"].AsBoolean();
                everyone_mask   = readuintval(ObjMap["EveryoneMask"]);
                flags           = readuintval(ObjMap["Flags"]);
                group_mask      = readuintval(ObjMap["GroupMask"]);
                material        = ObjMap["Material"].AsInteger();
                next_owner_mask = readuintval(ObjMap["NextOwnerMask"]);
                p_code          = ObjMap["PCode"].AsInteger();

                if (ObjMap.ContainsKey("Path"))
                {
                    if (ObjMap["Path"].Type != OSDType.Map)
                    {
                        responsedata["str_response_string"] = "Has Path key, but data not in expected format";
                        return(responsedata);
                    }

                    OSDMap PathMap = (OSDMap)ObjMap["Path"];
                    path_begin         = PathMap["Begin"].AsInteger();
                    path_curve         = PathMap["Curve"].AsInteger();
                    path_end           = PathMap["End"].AsInteger();
                    path_radius_offset = PathMap["RadiusOffset"].AsInteger();
                    path_revolutions   = PathMap["Revolutions"].AsInteger();
                    path_scale_x       = PathMap["ScaleX"].AsInteger();
                    path_scale_y       = PathMap["ScaleY"].AsInteger();
                    path_shear_x       = PathMap["ShearX"].AsInteger();
                    path_shear_y       = PathMap["ShearY"].AsInteger();
                    path_skew          = PathMap["Skew"].AsInteger();
                    path_taper_x       = PathMap["TaperX"].AsInteger();
                    path_taper_y       = PathMap["TaperY"].AsInteger();
                    path_twist         = PathMap["Twist"].AsInteger();
                    path_twist_begin   = PathMap["TwistBegin"].AsInteger();
                }

                if (ObjMap.ContainsKey("Profile"))
                {
                    if (ObjMap["Profile"].Type != OSDType.Map)
                    {
                        responsedata["str_response_string"] = "Has Profile key, but data not in expected format";
                        return(responsedata);
                    }

                    OSDMap ProfileMap = (OSDMap)ObjMap["Profile"];

                    profile_begin = ProfileMap["Begin"].AsInteger();
                    profile_curve = ProfileMap["Curve"].AsInteger();
                    profile_end   = ProfileMap["End"].AsInteger();
                    hollow        = ProfileMap["Hollow"].AsInteger();
                }
                ray_end_is_intersection = ObjMap["RayEndIsIntersection"].AsBoolean();

                ray_target_id = ObjMap["RayTargetId"].AsUUID();
                state         = ObjMap["State"].AsInteger();
                try
                {
                    ray_end   = ((OSDArray)ObjMap["RayEnd"]).AsVector3();
                    ray_start = ((OSDArray)ObjMap["RayStart"]).AsVector3();
                    scale     = ((OSDArray)ObjMap["Scale"]).AsVector3();
                    rotation  = ((OSDArray)ObjMap["Rotation"]).AsQuaternion();
                }
                catch (Exception)
                {
                    responsedata["str_response_string"] = "RayEnd, RayStart, Scale or Rotation wasn't in the expected format";
                    return(responsedata);
                }

                if (rm.ContainsKey("AgentData"))
                {
                    if (rm["AgentData"].Type != OSDType.Map)
                    {
                        responsedata["str_response_string"] = "Has AgentData key, but data not in expected format";
                        return(responsedata);
                    }

                    OSDMap AgentDataMap = (OSDMap)rm["AgentData"];

                    //session_id = AgentDataMap["SessionId"].AsUUID();
                    group_id = AgentDataMap["GroupId"].AsUUID();
                }
            }
            else
            { //v1
                bypass_raycast = rm["bypass_raycast"].AsBoolean();

                everyone_mask      = readuintval(rm["everyone_mask"]);
                flags              = readuintval(rm["flags"]);
                group_id           = rm["group_id"].AsUUID();
                group_mask         = readuintval(rm["group_mask"]);
                hollow             = rm["hollow"].AsInteger();
                material           = rm["material"].AsInteger();
                next_owner_mask    = readuintval(rm["next_owner_mask"]);
                hollow             = rm["hollow"].AsInteger();
                p_code             = rm["p_code"].AsInteger();
                path_begin         = rm["path_begin"].AsInteger();
                path_curve         = rm["path_curve"].AsInteger();
                path_end           = rm["path_end"].AsInteger();
                path_radius_offset = rm["path_radius_offset"].AsInteger();
                path_revolutions   = rm["path_revolutions"].AsInteger();
                path_scale_x       = rm["path_scale_x"].AsInteger();
                path_scale_y       = rm["path_scale_y"].AsInteger();
                path_shear_x       = rm["path_shear_x"].AsInteger();
                path_shear_y       = rm["path_shear_y"].AsInteger();
                path_skew          = rm["path_skew"].AsInteger();
                path_taper_x       = rm["path_taper_x"].AsInteger();
                path_taper_y       = rm["path_taper_y"].AsInteger();
                path_twist         = rm["path_twist"].AsInteger();
                path_twist_begin   = rm["path_twist_begin"].AsInteger();
                profile_begin      = rm["profile_begin"].AsInteger();
                profile_curve      = rm["profile_curve"].AsInteger();
                profile_end        = rm["profile_end"].AsInteger();

                ray_end_is_intersection = rm["ray_end_is_intersection"].AsBoolean();

                ray_target_id = rm["ray_target_id"].AsUUID();


                //session_id = rm["session_id"].AsUUID();
                state = rm["state"].AsInteger();
                try
                {
                    ray_end   = ((OSDArray)rm["ray_end"]).AsVector3();
                    ray_start = ((OSDArray)rm["ray_start"]).AsVector3();
                    rotation  = ((OSDArray)rm["rotation"]).AsQuaternion();
                    scale     = ((OSDArray)rm["scale"]).AsVector3();
                }
                catch (Exception)
                {
                    responsedata["str_response_string"] = "RayEnd, RayStart, Scale or Rotation wasn't in the expected format";
                    return(responsedata);
                }
            }



            Vector3 pos = m_scene.GetNewRezLocation(ray_start, ray_end, ray_target_id, rotation, (bypass_raycast) ? (byte)1 : (byte)0, (ray_end_is_intersection) ? (byte)1 : (byte)0, true, scale, false);

            PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

            pbs.PathBegin        = (ushort)path_begin;
            pbs.PathCurve        = (byte)path_curve;
            pbs.PathEnd          = (ushort)path_end;
            pbs.PathRadiusOffset = (sbyte)path_radius_offset;
            pbs.PathRevolutions  = (byte)path_revolutions;
            pbs.PathScaleX       = (byte)path_scale_x;
            pbs.PathScaleY       = (byte)path_scale_y;
            pbs.PathShearX       = (byte)path_shear_x;
            pbs.PathShearY       = (byte)path_shear_y;
            pbs.PathSkew         = (sbyte)path_skew;
            pbs.PathTaperX       = (sbyte)path_taper_x;
            pbs.PathTaperY       = (sbyte)path_taper_y;
            pbs.PathTwist        = (sbyte)path_twist;
            pbs.PathTwistBegin   = (sbyte)path_twist_begin;
            pbs.HollowShape      = (HollowShape)hollow;
            pbs.PCode            = (byte)p_code;
            pbs.ProfileBegin     = (ushort)profile_begin;
            pbs.ProfileCurve     = (byte)profile_curve;
            pbs.ProfileEnd       = (ushort)profile_end;
            pbs.Scale            = scale;
            pbs.State            = (byte)state;

            SceneObjectGroup obj = null;;

            if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos))
            {
                // rez ON the ground, not IN the ground
                pos.Z += 0.25F;

                obj = m_scene.AddNewPrim(avatar.UUID, group_id, pos, rotation, pbs);
            }


            if (obj == null)
            {
                return(responsedata);
            }

            SceneObjectPart rootpart = obj.RootPart;

            rootpart.Shape         = pbs;
            rootpart.Flags        |= (PrimFlags)flags;
            rootpart.EveryoneMask  = everyone_mask;
            rootpart.GroupID       = group_id;
            rootpart.GroupMask     = group_mask;
            rootpart.NextOwnerMask = next_owner_mask;
            rootpart.Material      = (byte)material;



            m_scene.PhysicsScene.AddPhysicsActorTaint(rootpart.PhysActor);

            responsedata["int_response_code"]   = 200; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(obj.LocalId));

            return(responsedata);
        }
        public void TestLoadIarPathWithEscapedChars()
        {
            TestHelpers.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            string itemName             = "You & you are a mean/man/";
            string humanEscapedItemName = @"You & you are a mean\/man\/";
            string userPassword         = "******";

            InventoryArchiverModule archiverModule = new InventoryArchiverModule();

            Scene scene = new SceneHelpers().SetupScene();

            SceneHelpers.SetupSceneModules(scene, archiverModule);

            // Create user
            string userFirstName = "Jock";
            string userLastName  = "Stirrup";
            UUID   userId        = UUID.Parse("00000000-0000-0000-0000-000000000020");

            UserAccountHelpers.CreateUserWithInventory(scene, userFirstName, userLastName, userId, "meowfood");

            // Create asset
            SceneObjectGroup object1;
            SceneObjectPart  part1;
            {
                string             partName       = "part name";
                UUID               ownerId        = UUID.Parse("00000000-0000-0000-0000-000000000040");
                PrimitiveBaseShape shape          = PrimitiveBaseShape.CreateSphere();
                Vector3            groupPosition  = new Vector3(10, 20, 30);
                Quaternion         rotationOffset = new Quaternion(20, 30, 40, 50);
                Vector3            offsetPosition = new Vector3(5, 10, 15);

                part1
                    = new SceneObjectPart(
                          ownerId, shape, groupPosition, rotationOffset, offsetPosition);
                part1.Name = partName;

                object1 = new SceneObjectGroup(part1);
                scene.AddNewSceneObject(object1, false);
            }

            UUID      asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
            AssetBase asset1   = AssetHelpers.CreateAsset(asset1Id, object1);

            scene.AssetService.Store(asset1);

            // Create item
            UUID item1Id            = UUID.Parse("00000000-0000-0000-0000-000000000080");
            InventoryItemBase item1 = new InventoryItemBase();

            item1.Name    = itemName;
            item1.AssetID = asset1.FullID;
            item1.ID      = item1Id;
            InventoryFolderBase objsFolder
                = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, userId, "Objects")[0];

            item1.Folder = objsFolder.ID;
            scene.AddInventoryItem(item1);

            MemoryStream archiveWriteStream = new MemoryStream();

            archiverModule.OnInventoryArchiveSaved += SaveCompleted;

            mre.Reset();
            archiverModule.ArchiveInventory(
                UUID.Random(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream);
            mre.WaitOne(60000, false);

            // LOAD ITEM
            MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());

            archiverModule.DearchiveInventory(UUID.Random(), userFirstName, userLastName, "Scripts", userPassword, archiveReadStream);

            InventoryItemBase foundItem1
                = InventoryArchiveUtils.FindItemByPath(
                      scene.InventoryService, userId, "Scripts/Objects/" + humanEscapedItemName);

            Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
//            Assert.That(
//                foundItem1.CreatorId, Is.EqualTo(userUuid),
//                "Loaded item non-uuid creator doesn't match that of the loading user");
            Assert.That(
                foundItem1.Name, Is.EqualTo(itemName),
                "Loaded item name doesn't match saved name");
        }
Exemplo n.º 17
0
 /// <summary>
 /// Add a notecard item to the given part.
 /// </summary>
 /// <param name="scene"></param>
 /// <param name="part"></param>
 /// <param name="itemName"></param>
 /// <param name="itemIDFrag">UUID or UUID stem</param>
 /// <param name="assetIDFrag">UUID or UUID stem</param>
 /// <param name="text">The tex to put in the notecard.</param>
 /// <returns>The item that was added</returns>
 public static TaskInventoryItem AddNotecard(
     Scene scene, SceneObjectPart part, string itemName, string itemIDStem, string assetIDStem, string text)
 {
     return(AddNotecard(
                scene, part, itemName, TestHelpers.ParseStem(itemIDStem), TestHelpers.ParseStem(assetIDStem), text));
 }
 private void ProcessSitTargetOrientation(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.SitTargetOrientation = ReadQuaternion(reader, "SitTargetOrientation");
 }
 private void ProcessParentID(SceneObjectPart obj, XmlTextReader reader)
 {
     string str = reader.ReadElementContentAsString("ParentID", String.Empty);
     obj.ParentID = Convert.ToUInt32(str);
 }
Exemplo n.º 20
0
        public void TestLoadOar()
        {
            TestHelper.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            MemoryStream     archiveWriteStream = new MemoryStream();
            TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);

            // Put in a random blank directory to check that this doesn't upset the load process
            tar.WriteDir("ignoreme");

            // Also check that direct entries which will also have a file entry containing that directory doesn't
            // upset load
            tar.WriteDir(ArchiveConstants.TERRAINS_PATH);

            tar.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, ArchiveWriteRequestPreparation.CreateControlFile(new Dictionary <string, Object>()));

            SceneObjectPart  part1   = CreateSceneObjectPart1();
            SceneObjectGroup object1 = new SceneObjectGroup(part1);

            // Let's put some inventory items into our object
            string   soundItemName         = "sound-item1";
            UUID     soundItemUuid         = UUID.Parse("00000000-0000-0000-0000-000000000002");
            Type     type                  = GetType();
            Assembly assembly              = type.Assembly;
            string   soundDataResourceName = null;

            string[] names = assembly.GetManifestResourceNames();
            foreach (string name in names)
            {
                if (name.EndsWith(".Resources.test-sound.wav"))
                {
                    soundDataResourceName = name;
                }
            }
            Assert.That(soundDataResourceName, Is.Not.Null);

            byte[] soundData;
            Console.WriteLine("Loading " + soundDataResourceName);
            using (Stream resource = assembly.GetManifestResourceStream(soundDataResourceName))
            {
                using (BinaryReader br = new BinaryReader(resource))
                {
                    // FIXME: Use the inspector insteadthere are so many forums and lists already, though admittedly none of them are suitable for cross virtual-enivornemnt discussion
                    soundData = br.ReadBytes(99999999);
                    UUID   soundUuid = UUID.Parse("00000000-0000-0000-0000-000000000001");
                    string soundAssetFileName
                        = ArchiveConstants.ASSETS_PATH + soundUuid
                          + ArchiveConstants.ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.SoundWAV];
                    tar.WriteFile(soundAssetFileName, soundData);

                    /*
                     * AssetBase soundAsset = AssetHelpers.CreateAsset(soundUuid, soundData);
                     * scene.AssetService.Store(soundAsset);
                     * asset1FileName = ArchiveConstants.ASSETS_PATH + soundUuid + ".wav";
                     */

                    TaskInventoryItem item1
                        = new TaskInventoryItem {
                        AssetID = soundUuid, ItemID = soundItemUuid, Name = soundItemName
                        };
                    part1.Inventory.AddInventoryItem(item1, true);
                }
            }

            m_scene.AddNewSceneObject(object1, false);

            string object1FileName = string.Format(
                "{0}_{1:000}-{2:000}-{3:000}__{4}.xml",
                part1.Name,
                Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z),
                part1.UUID);

            tar.WriteFile(ArchiveConstants.OBJECTS_PATH + object1FileName, SceneObjectSerializer.ToXml2Format(object1));

            tar.Close();

            MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());

            lock (this)
            {
                m_scene.EventManager.OnOarFileLoaded += LoadCompleted;
                m_archiverModule.DearchiveRegion(archiveReadStream);
            }

            Assert.That(m_lastErrorMessage, Is.Null);

            SceneObjectPart object1PartLoaded = m_scene.GetSceneObjectPart(part1.Name);

            Assert.That(object1PartLoaded, Is.Not.Null, "object1 was not loaded");
            Assert.That(object1PartLoaded.Name, Is.EqualTo(part1.Name), "object1 names not identical");
            Assert.That(object1PartLoaded.GroupPosition, Is.EqualTo(part1.GroupPosition), "object1 group position not equal");
            Assert.That(
                object1PartLoaded.RotationOffset, Is.EqualTo(part1.RotationOffset), "object1 rotation offset not equal");
            Assert.That(
                object1PartLoaded.OffsetPosition, Is.EqualTo(part1.OffsetPosition), "object1 offset position not equal");

            TaskInventoryItem loadedSoundItem = object1PartLoaded.Inventory.GetInventoryItems(soundItemName)[0];

            Assert.That(loadedSoundItem, Is.Not.Null, "loaded sound item was null");
            AssetBase loadedSoundAsset = m_scene.AssetService.Get(loadedSoundItem.AssetID.ToString());

            Assert.That(loadedSoundAsset, Is.Not.Null, "loaded sound asset was null");
            Assert.That(loadedSoundAsset.Data, Is.EqualTo(soundData), "saved and loaded sound data do not match");

            Assert.Greater(m_scene.LandChannel.AllParcels().Count, 0, "incorrect number of parcels");

            // Temporary
            Console.WriteLine("Successfully completed {0}", MethodBase.GetCurrentMethod());
        }
 private void ProcessObjectSaleType(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.ObjectSaleType = (byte) reader.ReadElementContentAsInt("ObjectSaleType", String.Empty);
 }
Exemplo n.º 22
0
        public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
                                          string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face)
        {
            if (!RenderPlugins.ContainsKey(contentType))
            {
                return(UUID.Zero);
            }

            Scene scene;

            RegisteredScenes.TryGetValue(simID, out scene);

            if (scene == null)
            {
                return(UUID.Zero);
            }

            SceneObjectPart part = scene.GetSceneObjectPart(primID);

            if (part == null)
            {
                return(UUID.Zero);
            }

            // If we want to reuse dynamic textures then we have to ignore any request from the caller to expire
            // them.
            if (ReuseTextures)
            {
                disp = disp & ~DISP_EXPIRE;
            }

            DynamicTextureUpdater updater = new DynamicTextureUpdater();

            updater.SimUUID             = simID;
            updater.PrimID              = primID;
            updater.ContentType         = contentType;
            updater.BodyData            = data;
            updater.UpdateTimer         = updateTimer;
            updater.UpdaterID           = UUID.Random();
            updater.Params              = extraParams;
            updater.BlendWithOldTexture = SetBlending;
            updater.FrontAlpha          = AlphaValue;
            updater.Face = face;
            updater.Url  = "Local image";
            updater.Disp = disp;

            object objReusableTextureUUID = null;

            if (ReuseTextures && !updater.BlendWithOldTexture)
            {
                string reuseableTextureKey = GenerateReusableTextureKey(data, extraParams);
                objReusableTextureUUID = m_reuseableDynamicTextures.Get(reuseableTextureKey);

                if (objReusableTextureUUID != null)
                {
                    // If something else has removed this temporary asset from the cache, detect and invalidate
                    // our cached uuid.
                    if (scene.AssetService.GetMetadata(objReusableTextureUUID.ToString()) == null)
                    {
                        m_reuseableDynamicTextures.Invalidate(reuseableTextureKey);
                        objReusableTextureUUID = null;
                    }
                }
            }

            // We cannot reuse a dynamic texture if the data is going to be blended with something already there.
            if (objReusableTextureUUID == null)
            {
                lock (Updaters)
                {
                    if (!Updaters.ContainsKey(updater.UpdaterID))
                    {
                        Updaters.Add(updater.UpdaterID, updater);
                    }
                }

//                m_log.DebugFormat(
//                    "[DYNAMIC TEXTURE MODULE]: Requesting generation of new dynamic texture for {0} in {1}",
//                    part.Name, part.ParentGroup.Scene.Name);

                RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams);
            }
            else
            {
//                m_log.DebugFormat(
//                    "[DYNAMIC TEXTURE MODULE]: Reusing cached texture {0} for {1} in {2}",
//                    objReusableTextureUUID, part.Name, part.ParentGroup.Scene.Name);

                // No need to add to updaters as the texture is always the same.  Not that this functionality
                // apppears to be implemented anyway.
                updater.UpdatePart(part, (UUID)objReusableTextureUUID);
            }

            return(updater.UpdaterID);
        }
 private void ProcessNextOwnerMask(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.NextOwnerMask = uint.Parse(reader.ReadElementContentAsString("NextOwnerMask", String.Empty));
 }
Exemplo n.º 24
0
            /// <summary>
            /// Called once new texture data has been received for this updater.
            /// </summary>
            /// <param name="data"></param>
            /// <param name="scene"></param>
            /// <param name="isReuseable">True if the data given is reuseable.</param>
            /// <returns>The asset UUID given to the incoming data.</returns>
            public UUID DataReceived(byte[] data, Scene scene)
            {
                SceneObjectPart part = scene.GetSceneObjectPart(PrimID);

                if (part == null || data == null || data.Length <= 1)
                {
                    string msg =
                        String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
                    scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
                                  0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);

                    return(UUID.Zero);
                }

                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);
                        }
                    }
                }

                if (assetData == null)
                {
                    assetData = new byte[data.Length];
                    Array.Copy(data, assetData, data.Length);
                }

                // Create a new asset for user
                AssetBase asset
                    = new AssetBase(
                          UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
                          scene.RegionInfo.RegionID.ToString());

                asset.Data        = assetData;
                asset.Description = String.Format("URL image : {0}", Url);
                if (asset.Description.Length > 128)
                {
                    asset.Description = asset.Description.Substring(0, 128);
                }
                asset.Local     = true;          // dynamic images aren't saved in the assets server
                asset.Temporary = ((Disp & DISP_TEMP) != 0);
                scene.AssetService.Store(asset); // this will only save the asset in the local asset cache

                IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface <IJ2KDecoder>();

                if (cacheLayerDecode != null)
                {
                    if (!cacheLayerDecode.Decode(asset.FullID, asset.Data))
                    {
                        m_log.WarnFormat(
                            "[DYNAMIC TEXTURE MODULE]: Decoding of dynamically generated asset {0} for {1} in {2} failed",
                            asset.ID, part.Name, part.ParentGroup.Scene.Name);
                    }
                }

                UUID oldID = UpdatePart(part, asset.FullID);

                if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
                {
                    if (oldAsset == null)
                    {
                        oldAsset = scene.AssetService.Get(oldID.ToString());
                    }

                    if (oldAsset != null)
                    {
                        if (oldAsset.Temporary)
                        {
                            scene.AssetService.Delete(oldID.ToString());
                        }
                    }
                }

                return(asset.FullID);
            }
 private void ProcessMediaUrl(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.MediaUrl = reader.ReadElementContentAsString("MediaUrl", String.Empty);
 }
Exemplo n.º 26
0
        public XmlNode RequestSnapshotData(XmlDocument nodeFactory)
        {
            m_log.Debug("[DATASNAPSHOT]: Generating object data for scene " + m_scene.RegionInfo.RegionName);

            XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "objectdata", "");
            XmlNode node;

            foreach (EntityBase entity in m_scene.Entities)
            {
                // only objects, not avatars
                if (entity is SceneObjectGroup)
                {
                    SceneObjectGroup obj = (SceneObjectGroup)entity;

//                    m_log.Debug("[DATASNAPSHOT]: Found object " + obj.Name + " in scene");

                    // libomv will complain about PrimFlags.JointWheel
                    // being obsolete, so we...
                    #pragma warning disable 0612
                    if ((obj.RootPart.Flags & PrimFlags.JointWheel) == PrimFlags.JointWheel)
                    {
                        SceneObjectPart m_rootPart = obj.RootPart;

                        if (m_rootPart != null)
                        {
                            ILandObject land = m_scene.LandChannel.GetLandObject(m_rootPart.AbsolutePosition.X, m_rootPart.AbsolutePosition.Y);

                            XmlNode xmlobject = nodeFactory.CreateNode(XmlNodeType.Element, "object", "");
                            node           = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", "");
                            node.InnerText = obj.UUID.ToString();
                            xmlobject.AppendChild(node);

                            node           = nodeFactory.CreateNode(XmlNodeType.Element, "title", "");
                            node.InnerText = m_rootPart.Name;
                            xmlobject.AppendChild(node);

                            node           = nodeFactory.CreateNode(XmlNodeType.Element, "description", "");
                            node.InnerText = m_rootPart.Description;
                            xmlobject.AppendChild(node);

                            node           = nodeFactory.CreateNode(XmlNodeType.Element, "flags", "");
                            node.InnerText = String.Format("{0:x}", m_rootPart.ObjectFlags);
                            xmlobject.AppendChild(node);

                            node           = nodeFactory.CreateNode(XmlNodeType.Element, "regionuuid", "");
                            node.InnerText = m_scene.RegionInfo.RegionSettings.RegionUUID.ToString();
                            xmlobject.AppendChild(node);

                            node           = nodeFactory.CreateNode(XmlNodeType.Element, "parceluuid", "");
                            node.InnerText = land.landData.GlobalID.ToString();
                            xmlobject.AppendChild(node);

                            parent.AppendChild(xmlobject);
                        }
                    }
                    #pragma warning disable 0612
                }
            }
            this.Stale = false;
            return(parent);
        }
 private void ProcessFromUserInventoryItemID(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.FromUserInventoryItemID = ReadUUID(reader, "FromUserInventoryItemID");
 }
        /// <summary>
        /// Add an inventory item from a user's inventory to a prim in this scene object.
        /// </summary>
        /// <param name="agentID">The agent adding the item.</param>
        /// <param name="localID">The local ID of the part receiving the add.</param>
        /// <param name="item">The user inventory item being added.</param>
        /// <param name="copyItemID">The item UUID that should be used by the new item.</param>
        /// <returns></returns>
        public bool AddInventoryItem(UUID agentID, uint localID, InventoryItemBase item, UUID copyItemID, bool withModRights = true)
        {
//            m_log.DebugFormat(
//                "[PRIM INVENTORY]: Adding inventory item {0} from {1} to part with local ID {2}",
//                item.Name, remoteClient.Name, localID);

            UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID;

            SceneObjectPart part = GetPart(localID);

            if (part == null)
            {
                m_log.ErrorFormat(
                    "[PRIM INVENTORY]: " +
                    "Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}",
                    localID, Name, UUID, newItemId);
                return(false);
            }

            TaskInventoryItem taskItem = new TaskInventoryItem();

            taskItem.ItemID      = newItemId;
            taskItem.AssetID     = item.AssetID;
            taskItem.Name        = item.Name;
            taskItem.Description = item.Description;
            taskItem.OwnerID     = part.OwnerID; // Transfer ownership
            taskItem.CreatorID   = item.CreatorIdAsUuid;
            taskItem.Type        = item.AssetType;
            taskItem.InvType     = item.InvType;

            if (agentID != part.OwnerID && m_scene.Permissions.PropagatePermissions())
            {
                taskItem.BasePermissions = item.BasePermissions &
                                           item.NextPermissions;
                taskItem.CurrentPermissions = item.CurrentPermissions &
                                              item.NextPermissions;
                taskItem.EveryonePermissions = item.EveryOnePermissions &
                                               item.NextPermissions;
                taskItem.GroupPermissions = item.GroupPermissions &
                                            item.NextPermissions;
                taskItem.NextPermissions = item.NextPermissions;
                // We're adding this to a prim we don't own. Force
                // owner change
                taskItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
            }
            else
            {
                taskItem.BasePermissions     = item.BasePermissions;
                taskItem.CurrentPermissions  = item.CurrentPermissions;
                taskItem.EveryonePermissions = item.EveryOnePermissions;
                taskItem.GroupPermissions    = item.GroupPermissions;
                taskItem.NextPermissions     = item.NextPermissions;
            }

            taskItem.Flags = item.Flags;

//                m_log.DebugFormat(
//                    "[PRIM INVENTORY]: Flags are 0x{0:X} for item {1} added to part {2} by {3}",
//                    taskItem.Flags, taskItem.Name, localID, remoteClient.Name);

            // TODO: These are pending addition of those fields to TaskInventoryItem
//                taskItem.SalePrice = item.SalePrice;
//                taskItem.SaleType = item.SaleType;
            taskItem.CreationDate = (uint)item.CreationDate;

            bool addFromAllowedDrop;

            if (withModRights)
            {
                addFromAllowedDrop = false;
            }
            else
            {
                addFromAllowedDrop = (part.ParentGroup.RootPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) != 0;
            }

            part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop);
            part.ParentGroup.InvalidateEffectivePerms();
            return(true);
        }
        public void SOPToXml2(XmlTextWriter writer, SceneObjectPart sop, Dictionary<string, object> options)
        {
            writer.WriteStartElement("SceneObjectPart");
            writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");

            writer.WriteElementString("AllowedDrop", sop.AllowedDrop.ToString().ToLower());
            WriteUUID(writer, "CreatorID", sop.CreatorID, options);

            if (!string.IsNullOrEmpty(sop.CreatorData))
                writer.WriteElementString("CreatorData", sop.CreatorData);

            writer.WriteElementString("InventorySerial", sop.InventorySerial.ToString());

            WriteTaskInventory(writer, sop.TaskInventory, options, sop.ParentEntity.Scene);

            WriteUUID(writer, "UUID", sop.UUID, options);
            writer.WriteElementString("LocalId", sop.LocalId.ToString());
            writer.WriteElementString("Name", sop.Name);
            writer.WriteElementString("Material", sop.Material.ToString());
            writer.WriteElementString("PassTouch", sop.PassTouch.ToString());
            writer.WriteElementString("PassCollisions", sop.PassCollisions.ToString());
            writer.WriteElementString("ScriptAccessPin", sop.ScriptAccessPin.ToString());

            WriteVector(writer, "GroupPosition", sop.GroupPosition);
            WriteVector(writer, "OffsetPosition", sop.OffsetPosition);

            WriteQuaternion(writer, "RotationOffset", sop.RotationOffset);
            WriteVector(writer, "Velocity", sop.Velocity);
            WriteVector(writer, "AngularVelocity", sop.AngularVelocity);
            WriteVector(writer, "Acceleration", sop.Acceleration);
            writer.WriteElementString("Description", sop.Description);
            writer.WriteStartElement("Color");
            writer.WriteElementString("R", sop.Color.R.ToString(Utils.EnUsCulture));
            writer.WriteElementString("G", sop.Color.G.ToString(Utils.EnUsCulture));
            writer.WriteElementString("B", sop.Color.B.ToString(Utils.EnUsCulture));
            writer.WriteElementString("A", sop.Color.G.ToString(Utils.EnUsCulture));
            writer.WriteEndElement();

            writer.WriteElementString("Text", sop.Text);
            writer.WriteElementString("SitName", sop.SitName);
            writer.WriteElementString("TouchName", sop.TouchName);

            writer.WriteElementString("LinkNum", sop.LinkNum.ToString());
            writer.WriteElementString("ClickAction", sop.ClickAction.ToString());

            WriteShape(writer, sop.Shape, options);

            WriteVector(writer, "Scale", sop.Scale);
            writer.WriteElementString("UpdateFlag", ((byte) 0).ToString());
            WriteQuaternion(writer, "SitTargetOrientation", sop.SitTargetOrientation);
            WriteVector(writer, "SitTargetPosition", sop.SitTargetPosition);
            writer.WriteElementString("ParentID", sop.ParentID.ToString());
            writer.WriteElementString("CreationDate", sop.CreationDate.ToString());
            writer.WriteElementString("Category", sop.Category.ToString());
            writer.WriteElementString("SalePrice", sop.SalePrice.ToString());
            writer.WriteElementString("ObjectSaleType", sop.ObjectSaleType.ToString());
            writer.WriteElementString("OwnershipCost", sop.OwnershipCost.ToString());
            WriteUUID(writer, "GroupID", sop.GroupID, options);
            WriteUUID(writer, "OwnerID", sop.OwnerID, options);
            WriteUUID(writer, "LastOwnerID", sop.LastOwnerID, options);
            writer.WriteElementString("BaseMask", sop.BaseMask.ToString());
            writer.WriteElementString("OwnerMask", sop.OwnerMask.ToString());
            writer.WriteElementString("GroupMask", sop.GroupMask.ToString());
            writer.WriteElementString("EveryoneMask", sop.EveryoneMask.ToString());
            writer.WriteElementString("NextOwnerMask", sop.NextOwnerMask.ToString());
            writer.WriteElementString("Flags", sop.Flags.ToString());
            WriteUUID(writer, "CollisionSound", sop.CollisionSound, options);
            writer.WriteElementString("CollisionSoundVolume", sop.CollisionSoundVolume.ToString());
            if (sop.MediaUrl != null)
                writer.WriteElementString("MediaUrl", sop.MediaUrl);
            WriteBytes(writer, "TextureAnimation", sop.TextureAnimation);
            WriteBytes(writer, "ParticleSystem", sop.ParticleSystem);
            writer.WriteElementString("PayPrice0", sop.PayPrice[0].ToString());
            writer.WriteElementString("PayPrice1", sop.PayPrice[1].ToString());
            writer.WriteElementString("PayPrice2", sop.PayPrice[2].ToString());
            writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString());
            writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString());
            writer.WriteElementString("FromUserInventoryItemID", sop.FromUserInventoryItemID.ToString());
            writer.WriteElementString("FromUserInventoryAssetID", sop.FromUserInventoryAssetID.ToString());

            writer.WriteElementString("RETURN_AT_EDGE", sop.RETURN_AT_EDGE.ToString().ToLower());
            writer.WriteElementString("BlockGrab", sop.BlockGrab.ToString().ToLower());
            writer.WriteElementString("BlockGrabObject", sop.BlockGrabObject.ToString().ToLower());
            writer.WriteElementString("StatusSandbox", sop.StatusSandbox.ToString().ToLower());
            WriteVector(writer, "StatusSandboxPos", sop.StatusSandboxPos);

            writer.WriteElementString("STATUS_ROTATE_X", sop.STATUS_ROTATE_X.ToString());
            writer.WriteElementString("STATUS_ROTATE_Y", sop.STATUS_ROTATE_Y.ToString());
            writer.WriteElementString("STATUS_ROTATE_Z", sop.STATUS_ROTATE_Z.ToString());

            WriteVector(writer, "SitTargetPosition", sop.SitTargetPosition);
            WriteQuaternion(writer, "SitTargetOrientation", sop.SitTargetOrientation);
            WriteVector(writer, "OmegaAxis", sop.OmegaAxis);

            writer.WriteElementString("OmegaSpinRate", sop.OmegaSpinRate.ToString());
            writer.WriteElementString("OmegaGain", sop.OmegaGain.ToString());
            writer.WriteElementString("PhysicsType", sop.PhysicsType.ToString());
            writer.WriteElementString("Density", sop.Density.ToString());
            writer.WriteElementString("Friction", sop.Friction.ToString());
            writer.WriteElementString("Restitution", sop.Restitution.ToString());
            writer.WriteElementString("GravityMultiplier", sop.GravityMultiplier.ToString());
            writer.WriteElementString("DIE_AT_EDGE", sop.DIE_AT_EDGE.ToString().ToLower());
            writer.WriteElementString("UseSoundQueue", sop.UseSoundQueue.ToString().ToLower());

            WriteUUID(writer, "Sound", sop.Sound, options);

            writer.WriteElementString("SoundFlags", sop.SoundFlags.ToString());
            writer.WriteElementString("SoundGain", sop.SoundGain.ToString());
            writer.WriteElementString("SoundRadius", sop.SoundRadius.ToString());

            WriteVector(writer, "PIDTarget", sop.PIDTarget);

            writer.WriteElementString("PIDActive", sop.PIDActive.ToString().ToLower());
            writer.WriteElementString("PIDTau", sop.PIDTau.ToString()); //fl
            writer.WriteElementString("PIDHoverHeight", sop.PIDHoverHeight.ToString()); //fl
            writer.WriteElementString("PIDHoverTau", sop.PIDHoverTau.ToString()); //fl
            writer.WriteElementString("VehicleType", sop.VehicleType.ToString());

            WriteVector(writer, "SavedAttachedPos", sop.SavedAttachedPos);
            writer.WriteElementString("SavedAttachmentPoint", sop.SavedAttachmentPoint.ToString());
            writer.WriteElementString("VolumeDetectActive", sop.VolumeDetectActive.ToString().ToLower());

            WriteVector(writer, "CameraEyeOffset", sop.CameraEyeOffset);
            WriteVector(writer, "CameraAtOffset", sop.CameraAtOffset);

            writer.WriteElementString("ForceMouselook", sop.ForceMouselook.ToString().ToLower());

            WriteQuaternion(writer, "APIDTarget", sop.APIDTarget);
            writer.WriteElementString("APIDDamp", sop.APIDDamp.ToString());
            writer.WriteElementString("APIDStrength", sop.APIDStrength.ToString());
            writer.WriteElementString("APIDIterations", sop.APIDIterations.ToString());
            writer.WriteElementString("APIDEnabled", sop.APIDEnabled.ToString().ToLower());
            writer.WriteElementString("Damage", sop.Damage.ToString());


            //Write the generic elements last
            foreach (KeyValuePair<string, Serialization> kvp in m_genericSerializers)
            {
                string val = kvp.Value(sop);
                if (val != null)
                    writer.WriteElementString(kvp.Key, val);
            }

            writer.WriteEndElement();
        }
 private void ProcessScale(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.Scale = ReadVector(reader, "Scale");
 }
        public void AggregatePerms()
        {
            lock (m_PermissionsLock)
            {
                // aux
                const uint allmask          = (uint)PermissionMask.AllEffective;
                const uint movemodmask      = (uint)(PermissionMask.Move | PermissionMask.Modify);
                const uint copytransfermast = (uint)(PermissionMask.Copy | PermissionMask.Transfer);

                uint basePerms      = (RootPart.BaseMask & allmask) | (uint)PermissionMask.Move;
                bool noBaseTransfer = (basePerms & (uint)PermissionMask.Transfer) == 0;

                uint rootOwnerPerms    = RootPart.OwnerMask;
                uint owner             = rootOwnerPerms;
                uint rootGroupPerms    = RootPart.GroupMask;
                uint group             = rootGroupPerms;
                uint rootEveryonePerms = RootPart.EveryoneMask;
                uint everyone          = rootEveryonePerms;

                bool needUpdate = false;
                // date is time of writing april 30th 2017
                bool newobj             = (RootPart.CreationDate == 0 || RootPart.CreationDate > 1493574994);
                SceneObjectPart[] parts = m_parts.GetArray();
                for (int i = 0; i < parts.Length; i++)
                {
                    SceneObjectPart part = parts[i];

                    if (m_DeepEffectivePermsInvalid)
                    {
                        part.AggregatedInnerPermsForGroup();
                    }

                    owner &= part.AggregatedInnerOwnerPerms;
                    group &= part.AggregatedInnerGroupPerms;
                    if (newobj)
                    {
                        group &= part.AggregatedInnerGroupPerms;
                    }
                    if (newobj)
                    {
                        everyone &= part.AggregatedInnerEveryonePerms;
                    }
                }
                // recover modify and move
                rootOwnerPerms &= movemodmask;
                owner          |= rootOwnerPerms;
                if ((owner & copytransfermast) == 0)
                {
                    owner |= (uint)PermissionMask.Transfer;
                }

                owner &= basePerms;
                if (owner != m_EffectiveOwnerPerms)
                {
                    needUpdate            = true;
                    m_EffectiveOwnerPerms = owner;
                }

                uint ownertransfermask = owner & (uint)PermissionMask.Transfer;

                // recover modify and move
                rootGroupPerms &= movemodmask;
                group          |= rootGroupPerms;
                if (noBaseTransfer)
                {
                    group &= ~(uint)PermissionMask.Copy;
                }
                else
                {
                    group |= ownertransfermask;
                }

                uint groupOrEveryone = group;
                uint tmpPerms        = group & owner;
                if (tmpPerms != m_EffectiveGroupPerms)
                {
                    needUpdate            = true;
                    m_EffectiveGroupPerms = tmpPerms;
                }

                // recover move
                rootEveryonePerms &= (uint)PermissionMask.Move;
                everyone          |= rootEveryonePerms;
                everyone          &= ~(uint)PermissionMask.Modify;
                if (noBaseTransfer)
                {
                    everyone &= ~(uint)PermissionMask.Copy;
                }
                else
                {
                    everyone |= ownertransfermask;
                }

                groupOrEveryone |= everyone;

                tmpPerms = everyone & owner;
                if (tmpPerms != m_EffectiveEveryOnePerms)
                {
                    needUpdate = true;
                    m_EffectiveEveryOnePerms = tmpPerms;
                }

                tmpPerms = groupOrEveryone & owner;
                if (tmpPerms != m_EffectiveGroupOrEveryOnePerms)
                {
                    needUpdate = true;
                    m_EffectiveGroupOrEveryOnePerms = tmpPerms;
                }

                m_DeepEffectivePermsInvalid = false;
                m_EffectivePermsInvalid     = false;

                if (needUpdate)
                {
                    RootPart.ScheduleFullUpdate();
                }
            }
        }
Exemplo n.º 32
0
        public XmlNode RequestSnapshotData(XmlDocument nodeFactory)
        {
            m_log.Debug("[DATASNAPSHOT]: Generating object data for scene " + m_scene.RegionInfo.RegionName);

            XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "objectdata", "");
            XmlNode node;

            EntityBase[] entities = m_scene.Entities.GetEntities();
            foreach (EntityBase entity in entities)
            {
                // only objects, not avatars
                if (entity is SceneObjectGroup)
                {
                    SceneObjectGroup obj = (SceneObjectGroup)entity;

                    //                    m_log.Debug("[DATASNAPSHOT]: Found object " + obj.Name + " in scene");

                    // libomv will complain about PrimFlags.JointWheel
                    // being obsolete, so we...
#pragma warning disable 0612
                    if ((obj.RootPart.Flags & PrimFlags.JointWheel) == PrimFlags.JointWheel)
                    {
                        SceneObjectPart m_rootPart = obj.RootPart;

                        ILandObject land = m_scene.LandChannel.GetLandObject(m_rootPart.AbsolutePosition.X, m_rootPart.AbsolutePosition.Y);

                        XmlNode xmlobject = nodeFactory.CreateNode(XmlNodeType.Element, "object", "");
                        node           = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", "");
                        node.InnerText = obj.UUID.ToString();
                        xmlobject.AppendChild(node);

                        node           = nodeFactory.CreateNode(XmlNodeType.Element, "title", "");
                        node.InnerText = m_rootPart.Name;
                        xmlobject.AppendChild(node);

                        node           = nodeFactory.CreateNode(XmlNodeType.Element, "description", "");
                        node.InnerText = m_rootPart.Description;
                        xmlobject.AppendChild(node);

                        node           = nodeFactory.CreateNode(XmlNodeType.Element, "flags", "");
                        node.InnerText = String.Format("{0:x}", (uint)m_rootPart.Flags);
                        xmlobject.AppendChild(node);

                        node           = nodeFactory.CreateNode(XmlNodeType.Element, "regionuuid", "");
                        node.InnerText = m_scene.RegionInfo.RegionSettings.RegionUUID.ToString();
                        xmlobject.AppendChild(node);

                        if (land != null && land.LandData != null)
                        {
                            node           = nodeFactory.CreateNode(XmlNodeType.Element, "parceluuid", "");
                            node.InnerText = land.LandData.GlobalID.ToString();
                            xmlobject.AppendChild(node);
                        }
                        else
                        {
                            // Something is wrong with this object. Let's not list it.
                            m_log.WarnFormat("[DATASNAPSHOT]: Bad data for object {0} ({1}) in region {2}", obj.Name, obj.UUID, m_scene.RegionInfo.RegionName);
                            continue;
                        }

                        node = nodeFactory.CreateNode(XmlNodeType.Element, "location", "");
                        Vector3 loc = obj.AbsolutePosition;
                        node.InnerText = loc.X.ToString() + "/" + loc.Y.ToString() + "/" + loc.Z.ToString();
                        xmlobject.AppendChild(node);

                        string bestImage = GuessImage(obj);
                        if (bestImage != string.Empty)
                        {
                            node           = nodeFactory.CreateNode(XmlNodeType.Element, "image", "");
                            node.InnerText = bestImage;
                            xmlobject.AppendChild(node);
                        }

                        parent.AppendChild(xmlobject);
                    }
#pragma warning disable 0612
                }
            }
            this.Stale = false;
            return(parent);
        }
 private void ProcessShape(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.Shape = ReadShape(reader, "Shape");
 }
Exemplo n.º 34
0
        private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim)
        {
            if ((PCode)prim.Shape.PCode != PCode.Prim)
            {
                return;
            }

            Vector3 ppos = prim.GetWorldPosition();

            if (ppos.Z < m_renderMinHeight || ppos.Z > m_renderMaxHeight)
            {
                return;
            }

            warp_Vector     primPos = ConvertVector(ppos);
            warp_Quaternion primRot = ConvertQuaternion(prim.GetWorldRotation());
            warp_Matrix     m       = warp_Matrix.quaternionMatrix(primRot);

            float screenFactor = renderer.Scene.EstimateBoxProjectedArea(primPos, ConvertVector(prim.Scale), m);

            if (screenFactor < 0)
            {
                return;
            }

            int p2 = (int)(-(float)Math.Log(screenFactor) * 1.442695f * 0.5 - 1);

            if (p2 < 0)
            {
                p2 = 0;
            }
            else if (p2 > 3)
            {
                p2 = 3;
            }

            DetailLevel lod = (DetailLevel)(3 - p2);

            FacetedMesh renderMesh = null;
            Primitive   omvPrim    = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);

            if (m_renderMeshes)
            {
                if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
                {
                    // Try fetchinng the asset
                    AssetBase sculptAsset = m_scene.AssetService.Get(omvPrim.Sculpt.SculptTexture.ToString());
                    if (sculptAsset != null)
                    {
                        // Is it a mesh?
                        if (omvPrim.Sculpt.Type == SculptType.Mesh)
                        {
                            AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset.Data);
                            FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, lod, out renderMesh);
                            meshAsset = null;
                        }
                        else // It's sculptie
                        {
                            if (m_imgDecoder != null)
                            {
                                Image sculpt = m_imgDecoder.DecodeToImage(sculptAsset.Data);
                                if (sculpt != null)
                                {
                                    renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt, lod);
                                    sculpt.Dispose();
                                }
                            }
                        }
                    }
                    else
                    {
                        m_log.WarnFormat("[Warp3D] failed to get mesh or sculpt asset {0} of prim {1} at {2}",
                                         omvPrim.Sculpt.SculptTexture.ToString(), prim.Name, prim.GetWorldPosition().ToString());
                    }
                }
            }

            // If not a mesh or sculptie, try the regular mesher
            if (renderMesh == null)
            {
                renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, lod);
            }

            if (renderMesh == null)
            {
                return;
            }

            string primID = prim.UUID.ToString();

            // Create the prim faces
            // TODO: Implement the useTextures flag behavior
            for (int i = 0; i < renderMesh.Faces.Count; i++)
            {
                Face   face     = renderMesh.Faces[i];
                string meshName = primID + i.ToString();

                // Avoid adding duplicate meshes to the scene
                if (renderer.Scene.objectData.ContainsKey(meshName))
                {
                    continue;
                }

                warp_Object faceObj = new warp_Object();

                Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
                Color4 faceColor = teFace.RGBA;
                if (faceColor.A == 0)
                {
                    continue;
                }

                string materialName = String.Empty;
                if (m_texturePrims)
                {
                    //                    if(lod > DetailLevel.Low)
                    {
                        //                    materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID, lod == DetailLevel.Low);
                        materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID, false, prim);
                        if (String.IsNullOrEmpty(materialName))
                        {
                            continue;
                        }
                        int c = renderer.Scene.material(materialName).getColor();
                        if ((c & warp_Color.MASKALPHA) == 0)
                        {
                            continue;
                        }
                    }
                }
                else
                {
                    materialName = GetOrCreateMaterial(renderer, faceColor);
                }

                if (renderer.Scene.material(materialName).getTexture() == null)
                {
                    // uv map details dont not matter for color;
                    for (int j = 0; j < face.Vertices.Count; j++)
                    {
                        Vertex      v    = face.Vertices[j];
                        warp_Vector pos  = ConvertVector(v.Position);
                        warp_Vertex vert = new warp_Vertex(pos, v.TexCoord.X, v.TexCoord.Y);
                        faceObj.addVertex(vert);
                    }
                }
                else
                {
                    float tu;
                    float tv;
                    float offsetu  = teFace.OffsetU + 0.5f;
                    float offsetv  = teFace.OffsetV + 0.5f;
                    float scaleu   = teFace.RepeatU;
                    float scalev   = teFace.RepeatV;
                    float rotation = teFace.Rotation;
                    float rc       = 0;
                    float rs       = 0;
                    if (rotation != 0)
                    {
                        rc = (float)Math.Cos(rotation);
                        rs = (float)Math.Sin(rotation);
                    }

                    for (int j = 0; j < face.Vertices.Count; j++)
                    {
                        warp_Vertex vert;
                        Vertex      v   = face.Vertices[j];
                        warp_Vector pos = ConvertVector(v.Position);
                        if (teFace.TexMapType == MappingType.Planar)
                        {
                            UVPlanarMap(v, prim.Scale, out tu, out tv);
                        }
                        else
                        {
                            tu = v.TexCoord.X - 0.5f;
                            tv = 0.5f - v.TexCoord.Y;
                        }
                        if (rotation != 0)
                        {
                            float tur = tu * rc - tv * rs;
                            float tvr = tu * rs + tv * rc;
                            tur *= scaleu;
                            tur += offsetu;

                            tvr *= scalev;
                            tvr += offsetv;
                            vert = new warp_Vertex(pos, tur, tvr);
                        }
                        else
                        {
                            tu  *= scaleu;
                            tu  += offsetu;
                            tv  *= scalev;
                            tv  += offsetv;
                            vert = new warp_Vertex(pos, tu, tv);
                        }

                        faceObj.addVertex(vert);
                    }
                }

                for (int j = 0; j < face.Indices.Count; j += 3)
                {
                    faceObj.addTriangle(
                        face.Indices[j + 0],
                        face.Indices[j + 1],
                        face.Indices[j + 2]);
                }

                faceObj.scaleSelf(prim.Scale.X, prim.Scale.Z, prim.Scale.Y);
                faceObj.transform(m);
                faceObj.setPos(primPos);

                renderer.Scene.addObject(meshName, faceObj);
                renderer.SetObjectMaterial(meshName, materialName);
            }
        }
 private void ProcessUpdateFlag(SceneObjectPart obj, XmlTextReader reader)
 {
     reader.Read();
     //InternalUpdateFlags flags = (InternalUpdateFlags)(byte)reader.ReadElementContentAsInt("UpdateFlag", String.Empty);
 }
Exemplo n.º 36
0
        public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID, bool useAverageTextureColor, SceneObjectPart sop)
        {
            int    color        = ConvertColor(faceColor);
            string idstr        = textureID.ToString() + color.ToString();
            string materialName = "MAPMAT" + idstr;

            if (renderer.Scene.material(materialName) != null)
            {
                return(materialName);
            }

            warp_Material mat     = new warp_Material();
            warp_Texture  texture = GetTexture(textureID, sop);

            if (texture != null)
            {
                if (useAverageTextureColor)
                {
                    color = warp_Color.multiply(color, texture.averageColor);
                }
                else
                {
                    mat.setTexture(texture);
                }
            }
            else
            {
                color = warp_Color.multiply(color, warp_Color.Grey);
            }

            mat.setColor(color);
            renderer.Scene.addMaterial(materialName, mat);

            return(materialName);
        }
 private void ProcessSitTargetPosition(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.SitTargetPosition = ReadVector(reader, "SitTargetPosition");
 }
Exemplo n.º 38
0
 private bool hasTouchEvents(SceneObjectPart part)
 {
     return((part.ScriptEvents & scriptEvents.anytouch) != 0);
 }
 private void ProcessCreationDate(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty);
 }
        /// <summary>
        /// Parses add request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AgentId"></param>
        /// <param name="cap"></param>
        /// <returns></returns>
        public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap)
        {
            Hashtable responsedata = new Hashtable();

            responsedata["int_response_code"]   = 400; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = "Request wasn't what was expected";
            ScenePresence avatar;

            if (!m_scene.TryGetScenePresence(AgentId, out avatar))
            {
                return(responsedata);
            }

            OSDMap r = (OSDMap)OSDParser.Deserialize((string)request["requestbody"]);
            UploadObjectAssetMessage message = new UploadObjectAssetMessage();

            try
            {
                message.Deserialize(r);
            }
            catch (Exception ex)
            {
                m_log.Error("[UPLOAD OBJECT ASSET MODULE]: Error deserializing message " + ex.ToString());
                message = null;
            }

            if (message == null)
            {
                responsedata["int_response_code"]   = 400; //501; //410; //404;
                responsedata["content_type"]        = "text/plain";
                responsedata["keepalive"]           = false;
                responsedata["str_response_string"] =
                    "<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>";

                return(responsedata);
            }

            Vector3    pos     = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation);
            Quaternion rot     = Quaternion.Identity;
            Vector3    rootpos = Vector3.Zero;
//            Quaternion rootrot = Quaternion.Identity;

            SceneObjectGroup rootGroup = null;

            SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length];
            for (int i = 0; i < message.Objects.Length; i++)
            {
                UploadObjectAssetMessage.Object obj = message.Objects[i];
                PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                if (i == 0)
                {
                    rootpos = obj.Position;
//                    rootrot = obj.Rotation;
                }

                // Combine the extraparams data into it's ugly blob again....
                //int bytelength = 0;
                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    bytelength += obj.ExtraParams[extparams].ExtraParamData.Length;
                //}
                //byte[] extraparams = new byte[bytelength];
                //int position = 0;



                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position,
                //                     obj.ExtraParams[extparams].ExtraParamData.Length);
                //
                //    position += obj.ExtraParams[extparams].ExtraParamData.Length;
                // }

                //pbs.ExtraParams = extraparams;
                for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                {
                    UploadObjectAssetMessage.Object.ExtraParam extraParam = obj.ExtraParams[extparams];
                    switch ((ushort)extraParam.Type)
                    {
                    case (ushort)ExtraParamType.Sculpt:
                        Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);

                        pbs.SculptEntry = true;

                        pbs.SculptTexture = obj.SculptID;
                        pbs.SculptType    = (byte)sculpt.Type;

                        break;

                    case (ushort)ExtraParamType.Flexible:
                        Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
                        pbs.FlexiEntry    = true;
                        pbs.FlexiDrag     = flex.Drag;
                        pbs.FlexiForceX   = flex.Force.X;
                        pbs.FlexiForceY   = flex.Force.Y;
                        pbs.FlexiForceZ   = flex.Force.Z;
                        pbs.FlexiGravity  = flex.Gravity;
                        pbs.FlexiSoftness = flex.Softness;
                        pbs.FlexiTension  = flex.Tension;
                        pbs.FlexiWind     = flex.Wind;
                        break;

                    case (ushort)ExtraParamType.Light:
                        Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0);
                        pbs.LightColorA    = light.Color.A;
                        pbs.LightColorB    = light.Color.B;
                        pbs.LightColorG    = light.Color.G;
                        pbs.LightColorR    = light.Color.R;
                        pbs.LightCutoff    = light.Cutoff;
                        pbs.LightEntry     = true;
                        pbs.LightFalloff   = light.Falloff;
                        pbs.LightIntensity = light.Intensity;
                        pbs.LightRadius    = light.Radius;
                        break;

                    case 0x40:
                        pbs.ReadProjectionData(extraParam.ExtraParamData, 0);
                        break;
                    }
                }

                pbs.PathBegin        = (ushort)obj.PathBegin;
                pbs.PathCurve        = (byte)obj.PathCurve;
                pbs.PathEnd          = (ushort)obj.PathEnd;
                pbs.PathRadiusOffset = (sbyte)obj.RadiusOffset;
                pbs.PathRevolutions  = (byte)obj.Revolutions;
                pbs.PathScaleX       = (byte)obj.ScaleX;
                pbs.PathScaleY       = (byte)obj.ScaleY;
                pbs.PathShearX       = (byte)obj.ShearX;
                pbs.PathShearY       = (byte)obj.ShearY;
                pbs.PathSkew         = (sbyte)obj.Skew;
                pbs.PathTaperX       = (sbyte)obj.TaperX;
                pbs.PathTaperY       = (sbyte)obj.TaperY;
                pbs.PathTwist        = (sbyte)obj.Twist;
                pbs.PathTwistBegin   = (sbyte)obj.TwistBegin;
                pbs.HollowShape      = (HollowShape)obj.ProfileHollow;
                pbs.PCode            = (byte)PCode.Prim;
                pbs.ProfileBegin     = (ushort)obj.ProfileBegin;
                pbs.ProfileCurve     = (byte)obj.ProfileCurve;
                pbs.ProfileEnd       = (ushort)obj.ProfileEnd;
                pbs.Scale            = obj.Scale;
                pbs.State            = (byte)0;
                pbs.LastAttachPoint  = (byte)0;
                SceneObjectPart prim = new SceneObjectPart();
                prim.UUID         = UUID.Random();
                prim.CreatorID    = AgentId;
                prim.OwnerID      = AgentId;
                prim.GroupID      = obj.GroupID;
                prim.LastOwnerID  = prim.OwnerID;
                prim.CreationDate = Util.UnixTimeSinceEpoch();
                prim.Name         = obj.Name;
                prim.Description  = "";

                prim.PayPrice[0] = -2;
                prim.PayPrice[1] = -2;
                prim.PayPrice[2] = -2;
                prim.PayPrice[3] = -2;
                prim.PayPrice[4] = -2;
                Primitive.TextureEntry tmp =
                    new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f"));

                for (int j = 0; j < obj.Faces.Length; j++)
                {
                    UploadObjectAssetMessage.Object.Face face = obj.Faces[j];

                    Primitive.TextureEntryFace primFace = tmp.CreateFace((uint)j);

                    primFace.Bump       = face.Bump;
                    primFace.RGBA       = face.Color;
                    primFace.Fullbright = face.Fullbright;
                    primFace.Glow       = face.Glow;
                    primFace.TextureID  = face.ImageID;
                    primFace.Rotation   = face.ImageRot;
                    primFace.MediaFlags = ((face.MediaFlags & 1) != 0);

                    primFace.OffsetU    = face.OffsetS;
                    primFace.OffsetV    = face.OffsetT;
                    primFace.RepeatU    = face.ScaleS;
                    primFace.RepeatV    = face.ScaleT;
                    primFace.TexMapType = (MappingType)(face.MediaFlags & 6);
                }

                pbs.TextureEntry = tmp.GetBytes();
                prim.Shape       = pbs;
                prim.Scale       = obj.Scale;

                SceneObjectGroup grp = new SceneObjectGroup();

                grp.SetRootPart(prim);
                prim.ParentID = 0;
                if (i == 0)
                {
                    rootGroup = grp;
                }
                grp.AttachToScene(m_scene);
                grp.AbsolutePosition = obj.Position;
                prim.RotationOffset  = obj.Rotation;

                // Required for linking
                grp.RootPart.ClearUpdateSchedule();

                if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos))
                {
                    m_scene.AddSceneObject(grp);
                    grp.AbsolutePosition = obj.Position;
                }

                allparts[i] = grp;
            }

            for (int j = 1; j < allparts.Length; j++)
            {
                // Required for linking
                rootGroup.RootPart.ClearUpdateSchedule();
                allparts[j].RootPart.ClearUpdateSchedule();
                rootGroup.LinkToGroup(allparts[j]);
            }

            rootGroup.ScheduleGroupForFullUpdate();
            pos
                = m_scene.GetNewRezLocation(
                      Vector3.Zero, rootpos, UUID.Zero, rot, (byte)1, 1, true, allparts[0].GroupScale, false);

            responsedata["int_response_code"]   = 200; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(allparts[0].LocalId));

            return(responsedata);
        }
 private void ProcessSalePrice(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty);
 }
Exemplo n.º 42
0
        private double GetPriorityByBestAvatarResponsiveness(IScenePresence presence, IEntity entity)
        {
            // If this is an update for our own avatar give it the highest priority
            if (presence.UUID == entity.UUID)
            {
                return(0.0);
            }
            if (entity == null)
            {
                return(double.NaN);
            }
            if (entity is IScenePresence)
            {
                return(1.0);
            }

            // Use group position for child prims
            Vector3 entityPos = entity.AbsolutePosition;

            if (!presence.IsChildAgent)
            {
                // Root agent. Use distance from camera and a priority decrease for objects behind us
                Vector3 camPosition = presence.CameraPosition;
                Vector3 camAtAxis   = presence.CameraAtAxis;

                // Distance
                double priority = Vector3.DistanceSquared(camPosition, entityPos);

                // Plane equation
                float d = -Vector3.Dot(camPosition, camAtAxis);
                float p = Vector3.Dot(camAtAxis, entityPos) + d;
                if (p < 0.0f)
                {
                    priority *= 2.0;
                }

                //Add distance again to really emphasize it
                priority += Vector3.DistanceSquared(presence.AbsolutePosition, entityPos);

                if ((Vector3.Distance(presence.AbsolutePosition, entityPos) / 2) > presence.DrawDistance)
                {
                    //Outside of draw distance!
                    priority *= 2;
                }

                SceneObjectPart rootPart = null;
                if (entity is SceneObjectPart)
                {
                    if (((SceneObjectPart)entity).ParentGroup != null &&
                        ((SceneObjectPart)entity).ParentGroup.RootPart != null)
                    {
                        rootPart = ((SceneObjectPart)entity).ParentGroup.RootPart;
                    }
                }
                if (entity is SceneObjectGroup)
                {
                    if (((SceneObjectGroup)entity).RootPart != null)
                    {
                        rootPart = ((SceneObjectGroup)entity).RootPart;
                    }
                }

                if (rootPart != null)
                {
                    PhysicsActor physActor = rootPart.PhysActor;

                    // Objects avatars are sitting on should be prioritized more
                    if (presence.ParentID == rootPart.UUID)
                    {
                        //Objects that are physical get more priority.
                        if (physActor != null && physActor.IsPhysical)
                        {
                            return(0.0);
                        }
                        else
                        {
                            return(1.2);
                        }
                    }

                    if (physActor == null || physActor.IsPhysical)
                    {
                        priority /= 2; //Emphasize physical objs
                    }
                    //Factor in the size of objects as well, big ones are MUCH more important than small ones
                    float size = rootPart.ParentGroup.GroupScale().Length();
                    //Cap size at 200 so that it doesn't completely overwhelm other objects
                    if (size > 200)
                    {
                        size = 200;
                    }

                    //Do it dynamically as well so that larger prims get smaller quicker
                    priority /= size > 40 ? (size / 35) : (size > 20 ? (size / 17) : 1);

                    if (rootPart.IsAttachment)
                    {
                        //Attachments are always high!
                        priority = 0.5;
                    }
                }
                //Closest first!
                return(priority);
            }
            else
            {
                // Child agent. Use the normal distance method
                Vector3 presencePos = presence.AbsolutePosition;

                return(Vector3.DistanceSquared(presencePos, entityPos));
            }
        }
 private void ProcessOwnershipCost(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.OwnershipCost = reader.ReadElementContentAsInt("OwnershipCost", String.Empty);
 }
        /// <summary>
        /// Parses add request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="agentID"></param>
        /// <param name="cap"></param>
        /// <returns></returns>
        public void ProcessAdd(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, OSDMap map, UUID agentID, Caps cap)
        {
            httpResponse.KeepAlive = false;

            if (!m_scene.TryGetScenePresence(agentID, out ScenePresence avatar))
            {
                httpResponse.StatusCode = (int)HttpStatusCode.Gone;
                return;
            }

            UploadObjectAssetMessage message = new UploadObjectAssetMessage();

            try
            {
                message.Deserialize(map);
            }
            catch (Exception ex)
            {
                m_log.Error("[UPLOAD OBJECT ASSET MODULE]: Error deserializing message " + ex.ToString());
                message = null;
            }

            if (message == null)
            {
                httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            try
            {
                Vector3    pos     = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation);
                Quaternion rot     = Quaternion.Identity;
                Vector3    rootpos = Vector3.Zero;

                SceneObjectGroup   rootGroup = null;
                SceneObjectGroup[] allparts  = new SceneObjectGroup[message.Objects.Length];
                for (int i = 0; i < message.Objects.Length; i++)
                {
                    UploadObjectAssetMessage.Object obj = message.Objects[i];
                    PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                    if (i == 0)
                    {
                        rootpos = obj.Position;
                    }

                    for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                    {
                        UploadObjectAssetMessage.Object.ExtraParam extraParam = obj.ExtraParams[extparams];
                        switch ((ushort)extraParam.Type)
                        {
                        case (ushort)ExtraParamType.Sculpt:
                            Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);

                            pbs.SculptEntry = true;

                            pbs.SculptTexture = obj.SculptID;
                            pbs.SculptType    = (byte)sculpt.Type;

                            break;

                        case (ushort)ExtraParamType.Flexible:
                            Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
                            pbs.FlexiEntry    = true;
                            pbs.FlexiDrag     = flex.Drag;
                            pbs.FlexiForceX   = flex.Force.X;
                            pbs.FlexiForceY   = flex.Force.Y;
                            pbs.FlexiForceZ   = flex.Force.Z;
                            pbs.FlexiGravity  = flex.Gravity;
                            pbs.FlexiSoftness = flex.Softness;
                            pbs.FlexiTension  = flex.Tension;
                            pbs.FlexiWind     = flex.Wind;
                            break;

                        case (ushort)ExtraParamType.Light:
                            Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0);
                            pbs.LightColorA    = light.Color.A;
                            pbs.LightColorB    = light.Color.B;
                            pbs.LightColorG    = light.Color.G;
                            pbs.LightColorR    = light.Color.R;
                            pbs.LightCutoff    = light.Cutoff;
                            pbs.LightEntry     = true;
                            pbs.LightFalloff   = light.Falloff;
                            pbs.LightIntensity = light.Intensity;
                            pbs.LightRadius    = light.Radius;
                            break;

                        case 0x40:
                            pbs.ReadProjectionData(extraParam.ExtraParamData, 0);
                            break;
                        }
                    }

                    pbs.PathBegin        = (ushort)obj.PathBegin;
                    pbs.PathCurve        = (byte)obj.PathCurve;
                    pbs.PathEnd          = (ushort)obj.PathEnd;
                    pbs.PathRadiusOffset = (sbyte)obj.RadiusOffset;
                    pbs.PathRevolutions  = (byte)obj.Revolutions;
                    pbs.PathScaleX       = (byte)obj.ScaleX;
                    pbs.PathScaleY       = (byte)obj.ScaleY;
                    pbs.PathShearX       = (byte)obj.ShearX;
                    pbs.PathShearY       = (byte)obj.ShearY;
                    pbs.PathSkew         = (sbyte)obj.Skew;
                    pbs.PathTaperX       = (sbyte)obj.TaperX;
                    pbs.PathTaperY       = (sbyte)obj.TaperY;
                    pbs.PathTwist        = (sbyte)obj.Twist;
                    pbs.PathTwistBegin   = (sbyte)obj.TwistBegin;
                    pbs.HollowShape      = (HollowShape)obj.ProfileHollow;
                    pbs.PCode            = (byte)PCode.Prim;
                    pbs.ProfileBegin     = (ushort)obj.ProfileBegin;
                    pbs.ProfileCurve     = (byte)obj.ProfileCurve;
                    pbs.ProfileEnd       = (ushort)obj.ProfileEnd;
                    pbs.Scale            = obj.Scale;
                    pbs.State            = (byte)0;
                    pbs.LastAttachPoint  = (byte)0;
                    SceneObjectPart prim = new SceneObjectPart();
                    prim.UUID         = UUID.Random();
                    prim.CreatorID    = agentID;
                    prim.OwnerID      = agentID;
                    prim.GroupID      = obj.GroupID;
                    prim.LastOwnerID  = prim.OwnerID;
                    prim.RezzerID     = agentID;
                    prim.CreationDate = Util.UnixTimeSinceEpoch();
                    prim.Name         = obj.Name;
                    prim.Description  = "";

                    prim.PayPrice[0] = -2;
                    prim.PayPrice[1] = -2;
                    prim.PayPrice[2] = -2;
                    prim.PayPrice[3] = -2;
                    prim.PayPrice[4] = -2;
                    Primitive.TextureEntry tmp =
                        new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f"));

                    for (int j = 0; j < obj.Faces.Length; j++)
                    {
                        UploadObjectAssetMessage.Object.Face face     = obj.Faces[j];
                        Primitive.TextureEntryFace           primFace = tmp.CreateFace((uint)j);

                        primFace.Bump       = face.Bump;
                        primFace.RGBA       = face.Color;
                        primFace.Fullbright = face.Fullbright;
                        primFace.Glow       = face.Glow;
                        primFace.TextureID  = face.ImageID;
                        primFace.Rotation   = face.ImageRot;
                        primFace.MediaFlags = ((face.MediaFlags & 1) != 0);

                        primFace.OffsetU    = face.OffsetS;
                        primFace.OffsetV    = face.OffsetT;
                        primFace.RepeatU    = face.ScaleS;
                        primFace.RepeatV    = face.ScaleT;
                        primFace.TexMapType = (MappingType)(face.MediaFlags & 6);
                    }

                    pbs.TextureEntry = tmp.GetBytes();
                    prim.Shape       = pbs;
                    prim.Scale       = obj.Scale;

                    SceneObjectGroup grp = new SceneObjectGroup();

                    grp.SetRootPart(prim);
                    prim.ParentID = 0;
                    if (i == 0)
                    {
                        rootGroup = grp;
                    }

                    grp.AttachToScene(m_scene);
                    grp.AbsolutePosition = obj.Position;
                    prim.RotationOffset  = obj.Rotation;

                    // Required for linking
                    grp.RootPart.ClearUpdateSchedule();

                    if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos))
                    {
                        m_scene.AddSceneObject(grp);
                        grp.AbsolutePosition = obj.Position;
                    }

                    allparts[i] = grp;
                }

                for (int j = 1; j < allparts.Length; j++)
                {
                    // Required for linking
                    rootGroup.RootPart.ClearUpdateSchedule();
                    allparts[j].RootPart.ClearUpdateSchedule();
                    rootGroup.LinkToGroup(allparts[j]);
                }

                rootGroup.ScheduleGroupForFullAnimUpdate();

                httpResponse.StatusCode = (int)HttpStatusCode.OK;
                httpResponse.RawBuffer  = Util.UTF8NBGetbytes(String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(allparts[0].LocalId)));
            }
            catch { }

            httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
        }
 private void ProcessLastOwnerID(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.LastOwnerID = ReadUUID(reader, "LastOwnerID");
 }
Exemplo n.º 46
0
        /// <summary>
        ///     Add an inventory item to a prim in this group.
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="localID"></param>
        /// <param name="item"></param>
        /// <param name="copyItemID">The item UUID that should be used by the new item.</param>
        /// <returns></returns>
        public bool AddInventoryItem(IClientAPI remoteClient, uint localID,
                                     InventoryItemBase item, UUID copyItemID)
        {
            UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID;

            SceneObjectPart part = (SceneObjectPart) GetChildPart(localID);
            if (part != null)
            {
                TaskInventoryItem taskItem = new TaskInventoryItem
                                                 {
                                                     ItemID = newItemId,
                                                     AssetID = item.AssetID,
                                                     Name = item.Name,
                                                     Description = item.Description,
                                                     OwnerID = part.OwnerID,
                                                     CreatorID = item.CreatorIdAsUuid,
                                                     Type = item.AssetType,
                                                     InvType = item.InvType
                                                 };

                // Transfer ownership

                if (remoteClient != null &&
                    remoteClient.AgentId != part.OwnerID &&
                    m_scene.Permissions.PropagatePermissions())
                {
                    taskItem.BasePermissions = item.BasePermissions &
                                               item.NextPermissions;
                    taskItem.CurrentPermissions = item.CurrentPermissions &
                                                  item.NextPermissions;
                    taskItem.EveryonePermissions = item.EveryOnePermissions &
                                                   item.NextPermissions;
                    taskItem.GroupPermissions = item.GroupPermissions &
                                                item.NextPermissions;
                    taskItem.NextPermissions = item.NextPermissions;
                    // We're adding this to a prim we don't own. Force
                    // owner change
                    taskItem.CurrentPermissions |= 16; // Slam
                }
                else
                {
                    taskItem.BasePermissions = item.BasePermissions;
                    taskItem.CurrentPermissions = item.CurrentPermissions;
                    taskItem.EveryonePermissions = item.EveryOnePermissions;
                    taskItem.GroupPermissions = item.GroupPermissions;
                    taskItem.NextPermissions = item.NextPermissions;
                }

                taskItem.Flags = item.Flags;
                taskItem.SalePrice = item.SalePrice;
                taskItem.SaleType = item.SaleType;
                taskItem.CreationDate = (uint) item.CreationDate;

                bool addFromAllowedDrop = false;
                if (remoteClient != null)
                {
                    addFromAllowedDrop = remoteClient.AgentId != part.OwnerID;
                }

                part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop);

                return true;
            }
            MainConsole.Instance.ErrorFormat(
                "[PRIM INVENTORY]: " +
                "Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}",
                localID, Name, UUID, newItemId);

            return false;
        }
 private void ProcessFlags(SceneObjectPart obj, XmlTextReader reader)
 {
     string value = reader.ReadElementContentAsString("Flags", String.Empty);
     // !!!!! to deal with flags without commas
     if (value.Contains(" ") && !value.Contains(","))
         value = value.Replace(" ", ", ");
     obj.Flags = (PrimFlags) Enum.Parse(typeof (PrimFlags), value);
 }
Exemplo n.º 48
0
        private void FindObjects(IClientAPI client, string[] args)
        {
            if (args.Length <= 1)
            {
                SendSystemChat(client, "Error: expected either a UUID or a local ID for an object or user.");
                return;
            }

            string arg     = args[1];
            UUID   uuid    = UUID.Zero;
            uint   localID = 0;

            if (!UUID.TryParse(arg, out uuid))
            {
                uuid = UUID.Zero;
            }

            if (uuid != UUID.Zero)  // see if it's a prim
            {
                foreach (Scene scene in m_scenes)
                {
                    SceneObjectPart part = scene.GetSceneObjectPart(uuid);
                    if (part != null)
                    {
                        // Allow the user to dump any part (including an attachment) if they specify the UUID.
                        DumpPart(client, scene, part);
                        return;
                    }
                }
            }

            if ((uuid == UUID.Zero) && uint.TryParse(arg, out localID))
            {
                foreach (Scene scene in m_scenes)
                {
                    SceneObjectPart part = scene.GetSceneObjectPart(localID);
                    if (part != null)
                    {
                        // Allow the user to dump any part (including an attachment) if they are the owner of the attachment.
                        if (part.IsAttachment && part.OwnerID != client.AgentId && !scene.Permissions.IsGod(client.AgentId))
                        {
                            SendSystemChat(client, "That ID specifies an attachment.");
                        }
                        else
                        {
                            DumpPart(client, scene, part);
                        }
                        return;
                    }
                }
                SendSystemChat(client, "Error: Could not find an part with local ID: " + localID.ToString());
                return;
            }

            List <SceneObjectGroup> results;

            if (uuid != UUID.Zero)  // find by user
            {
                results = FindMatchingObjects(uuid.ToString(), client.AgentId);
            }
            else
            {
                string objName = string.Join(" ", args, 1, args.Length - 1);
                results = FindMatchingObjects(objName, client.AgentId);
            }

            if (results.Count < 1)
            {
                SendSystemChat(client, "No matching objects found.");
            }
            else
            {
                SendSystemChat(client, "{0} matching objects found:", results.Count);
                foreach (SceneObjectGroup group in results)
                {
                    DumpPart(client, group.Scene, group.RootPart);
                }
            }
        }
 private void ProcessCollisionSoundVolume(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.CollisionSoundVolume =
         float.Parse(reader.ReadElementContentAsString("CollisionSoundVolume", String.Empty));
 }
Exemplo n.º 50
0
        private static int getNumberOfSides(SceneObjectPart part)
        {
            int  ret;
            bool hasCut;
            bool hasHollow;
            bool hasDimple;
            bool hasProfileCut;

            int primType = getScriptPrimType(part.Shape);

            hasCutHollowDimpleProfileCut(primType, part.Shape, out hasCut, out hasHollow, out hasDimple, out hasProfileCut);

            switch (primType)
            {
            default:
            case (int)PrimType.Box:
                ret = 6;
                if (hasCut)
                {
                    ret += 2;
                }
                if (hasHollow)
                {
                    ret += 1;
                }
                break;

            case (int)PrimType.Cylinder:
                ret = 3;
                if (hasCut)
                {
                    ret += 2;
                }
                if (hasHollow)
                {
                    ret += 1;
                }
                break;

            case (int)PrimType.Prism:
                ret = 5;
                if (hasCut)
                {
                    ret += 2;
                }
                if (hasHollow)
                {
                    ret += 1;
                }
                break;

            case (int)PrimType.Sphere:
                ret = 1;
                if (hasCut)
                {
                    ret += 2;
                }
                if (hasDimple)
                {
                    ret += 2;
                }
                if (hasHollow)
                {
                    ret += 1;     // GOTCHA: LSL shows 2 additional sides here.
                }
                // This has been fixed, but may cause porting issues.
                break;

            case (int)PrimType.Torus:
                ret = 1;
                if (hasCut)
                {
                    ret += 2;
                }
                if (hasProfileCut)
                {
                    ret += 2;
                }
                if (hasHollow)
                {
                    ret += 1;
                }
                break;

            case (int)PrimType.Tube:
                ret = 4;
                if (hasCut)
                {
                    ret += 2;
                }
                if (hasProfileCut)
                {
                    ret += 2;
                }
                if (hasHollow)
                {
                    ret += 1;
                }
                break;

            case (int)PrimType.Ring:
                ret = 3;
                if (hasCut)
                {
                    ret += 2;
                }
                if (hasProfileCut)
                {
                    ret += 2;
                }
                if (hasHollow)
                {
                    ret += 1;
                }
                break;

            case (int)PrimType.Sculpt:
                ret = 1;
                break;
            }
            return(ret);
        }
 private void ProcessTextureAnimation(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.TextureAnimation =
         Convert.FromBase64String(reader.ReadElementContentAsString("TextureAnimation", String.Empty));
 }
Exemplo n.º 52
0
 private Promise <DisplayableRenderable> MeshFromPrimShapeData(SceneObjectGroup sog, SceneObjectPart sop,
                                                               OMV.Primitive prim, IAssetFetcher assetFetcher, OMVR.DetailLevel lod)
 {
     return(new Promise <DisplayableRenderable>((resolve, reject) => {
         OMVR.FacetedMesh mesh = _mesher.GenerateFacetedMesh(prim, lod);
         DisplayableRenderable dr = ConvertFacetedMeshToDisplayable(assetFetcher, mesh, prim.Textures.DefaultTexture, prim.Scale);
         BHash drHash = dr.GetBHash();
         DisplayableRenderable realDR = assetFetcher.GetRenderable(drHash, () => { return dr; });
         BConverterOS.LogBProgress("{0} MeshFromPrimShapeData. numGenedMeshed={1}",
                                   _logHeader, ((RenderableMeshGroup)realDR).meshes.Count);
         resolve(realDR);
     }));
 }
 private void ProcessPayPrice4(SceneObjectPart obj, XmlTextReader reader)
 {
     obj.PayPrice[4] = int.Parse(reader.ReadElementContentAsString("PayPrice4", String.Empty));
 }
Exemplo n.º 54
0
 private Promise <DisplayableRenderable> MeshFromPrimSculptData(SceneObjectGroup sog, SceneObjectPart sop,
                                                                OMV.Primitive prim, IAssetFetcher assetFetcher, OMVR.DetailLevel lod)
 {
     return(new Promise <DisplayableRenderable>((resolve, reject) => {
         // Get the asset that the sculpty is built on
         EntityHandleUUID texHandle = new EntityHandleUUID(prim.Sculpt.SculptTexture);
         assetFetcher.FetchTexture(texHandle)
         .Then((bm) => {
             OMVR.FacetedMesh fMesh = _mesher.GenerateFacetedSculptMesh(prim, bm.Image.ExportBitmap(), lod);
             DisplayableRenderable dr =
                 ConvertFacetedMeshToDisplayable(assetFetcher, fMesh, prim.Textures.DefaultTexture, prim.Scale);
             BHash drHash = dr.GetBHash();
             DisplayableRenderable realDR = assetFetcher.GetRenderable(drHash, () => { return dr; });
             BConverterOS.LogBProgress("{0} MeshFromPrimSculptData. numFaces={1}, numGenedMeshed={2}",
                                       _logHeader, fMesh.Faces.Count, ((RenderableMeshGroup)realDR).meshes.Count);
             resolve(realDR);
         }, (e) => {
             ConvOAR.Globals.log.ErrorFormat("{0} MeshFromPrimSculptData: Rejected FetchTexture: {1}: {2}", _logHeader, texHandle, e);
             reject(null);
         });
     }));
 }
 private void GenericBool(SceneObjectPart obj, XmlTextReader reader, string name, Type SOPType)
 {
     bool val = reader.ReadElementContentAsBoolean(name, "");
     SOPType.GetProperty(name).SetValue(obj, val, null);
 }
Exemplo n.º 56
0
        private Promise <DisplayableRenderable> MeshFromPrimMeshData(SceneObjectGroup sog, SceneObjectPart sop,
                                                                     OMV.Primitive prim, IAssetFetcher assetFetcher, OMVR.DetailLevel lod)
        {
            EntityHandleUUID meshHandle = new EntityHandleUUID(prim.Sculpt.SculptTexture);

            return(new Promise <DisplayableRenderable>((resolve, reject) => {
                assetFetcher.FetchRawAsset(meshHandle)
                .Then(meshBytes => {
                    // OMVA.AssetMesh meshAsset = new OMVA.AssetMesh(prim.ID, meshBytes);
                    // if (OMVR.FacetedMesh.TryDecodeFromAsset(prim, meshAsset, lod, out fMesh)) {
                    OMVR.FacetedMesh fMesh = null;
                    try {
                        fMesh = _mesher.GenerateFacetedMeshMesh(prim, meshBytes);
                    }
                    catch (Exception e) {
                        ConvOAR.Globals.log.ErrorFormat("{0} Exception in GenerateFacetedMeshMesh: {1}", _logHeader, e);
                    }
                    if (fMesh != null)
                    {
                        DisplayableRenderable dr = ConvertFacetedMeshToDisplayable(assetFetcher, fMesh, prim.Textures.DefaultTexture, prim.Scale);
                        // Don't know the hash of the DisplayableRenderable until after it has been created.
                        // Now use the hash to see if this has already been done.
                        // If this DisplayableRenderable has already been built, use the other one and throw this away.
                        BHash drHash = dr.GetBHash();
                        DisplayableRenderable realDR = assetFetcher.GetRenderable(drHash, () => { return dr; });
                        resolve(realDR);
                    }
                    else
                    {
                        reject(new Exception("MeshFromPrimMeshData: could not decode mesh information from asset. ID="
                                             + prim.ID.ToString()));
                    }
                }, e => {
                    ConvOAR.Globals.log.ErrorFormat("{0} MeshFromPrimMeshData: exception: {1}", _logHeader, e);
                    reject(e);
                });
            }));
        }
 private void GenericQuaternion(SceneObjectPart obj, XmlTextReader reader, string name, Type SOPType)
 {
     SOPType.GetProperty(name).SetValue(obj, ReadQuaternion(reader, name), null);
 }
Exemplo n.º 58
0
        private void HandleTreeFreeze(Object[] args)
        {
            string  copsename   = ((string)args[0]).Trim();
            Boolean freezeState = (Boolean)args[1];

            lock (mylock)
            {
                foreach (Copse cp in m_copses)
                {
                    if (cp.m_name != copsename)
                    {
                        continue;
                    }

                    if (!cp.m_frozen && freezeState || cp.m_frozen && !freezeState)
                    {
                        cp.m_frozen = freezeState;
                        List <UUID> losttrees = new List <UUID>();
                        foreach (UUID tree in cp.m_trees)
                        {
                            SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
                            if (sog != null && !sog.IsDeleted)
                            {
                                SceneObjectPart sop  = sog.RootPart;
                                string          name = sop.Name;
                                if (freezeState)
                                {
                                    if (name.StartsWith("FTPM"))
                                    {
                                        continue;
                                    }
                                    if (!name.StartsWith("ATPM"))
                                    {
                                        continue;
                                    }
                                    sop.Name = sop.Name.Replace("ATPM", "FTPM");
                                }
                                else
                                {
                                    if (name.StartsWith("ATPM"))
                                    {
                                        continue;
                                    }
                                    if (!name.StartsWith("FTPM"))
                                    {
                                        continue;
                                    }
                                    sop.Name = sop.Name.Replace("FTPM", "ATPM");
                                }
                                sop.ParentGroup.HasGroupChanged = true;
                                sog.ScheduleGroupForFullUpdate();
                            }
                            else
                            {
                                losttrees.Add(tree);
                            }
                        }
                        foreach (UUID tree in losttrees)
                        {
                            cp.m_trees.Remove(tree);
                        }

                        m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
                        return;
                    }
                    else
                    {
                        m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
                        return;
                    }
                }
            }
            m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
        }
        public SceneObjectPart Xml2ToSOP(XmlTextReader reader)
        {
            SceneObjectPart obj = new SceneObjectPart();

            reader.ReadStartElement("SceneObjectPart");

            string nodeName = string.Empty;
            while (reader.Name != "SceneObjectPart")
            {
                nodeName = reader.Name;
                SOPXmlProcessor p = null;
                if (m_SOPXmlProcessors.TryGetValue(reader.Name, out p))
                {
                    //MainConsole.Instance.DebugFormat("[XXX] Processing: {0}", reader.Name);
                    try
                    {
                        p(obj, reader);
                    }
                    catch (Exception e)
                    {
                        MainConsole.Instance.DebugFormat("[SceneObjectSerializer]: exception while parsing {0}: {1}",
                                                         nodeName, e);
                        if (reader.NodeType == XmlNodeType.EndElement)
                            reader.Read();
                    }
                }
                else
                {
                    //                    MainConsole.Instance.DebugFormat("[SceneObjectSerializer]: caught unknown element {0}", nodeName);
                    reader.ReadOuterXml(); // ignore
                }
            }

            reader.ReadEndElement(); // SceneObjectPart

            //SceneObjectPart copy = ProtoBuf.Serializer.DeepClone<SceneObjectPart>(obj);
            //MainConsole.Instance.DebugFormat("[XXX]: parsed SOP {0} - {1}", obj.Name, obj.UUID);
            //bool success = AreMatch(obj, copy);
            return obj;
        }
Exemplo n.º 60
0
 public SitTargetInfo(SceneObjectPart part, Vector3 pos, Quaternion rot)
 {
     m_offset   = pos;
     m_rotation = rot;
     m_part     = part;
 }